From 11fe1f0eda0d857e81846fbc01ed1d24c26fbe12 Mon Sep 17 00:00:00 2001 From: deymosh <232244450+deymosh@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:13:52 +0100 Subject: [PATCH 1/8] build(agent-host): pin Pi 1.5.2 for the Pi driver The Pi driver runs the pinned CLI from an install-on-demand tree, the way the DeepSeek Harness and Qwen Code drivers do: nothing larger than one binary is shipped, and the tree is downloaded at the version and sha512 pnpm-lock.yaml holds the first time a Pi session needs it. The generated pins are the root package's full dependency closure, laid out where Node resolves each package exactly as pnpm did. Pi is pure JavaScript, so no platform binary is involved; the optional native packages its closure carries are skipped where their gates do not match. The DeepSeek Harness pins gain two entries: Pi's own undici pin hoists that version, and the harness's openai optional dependency now resolves its own nested copy, which is how pnpm laid the shared closure out. Co-Authored-By: Claude Code --- packages/agent-host/package.json | 1 + .../agent-host/src/generated/dshPackages.ts | 2 + .../agent-host/src/generated/piPackages.ts | 219 ++++++++++++++++ .../install/__tests__/lockfilePins.test.ts | 13 +- .../agent-host/src/install/lockfilePins.ts | 5 + pnpm-lock.yaml | 246 ++++++++++++++++-- 6 files changed, 461 insertions(+), 25 deletions(-) create mode 100644 packages/agent-host/src/generated/piPackages.ts diff --git a/packages/agent-host/package.json b/packages/agent-host/package.json index 8bed9540..936a7153 100644 --- a/packages/agent-host/package.json +++ b/packages/agent-host/package.json @@ -20,6 +20,7 @@ "devDependencies": { "@agentclientprotocol/sdk": "^2.5.0", "@deepseek-ai/dsh": "0.2.2-rc.1", + "@earendil-works/pi-coding-agent": "1.5.2", "@opencode/cli": "2.2.7", "@qwen-code/qwen-code": "0.27.1", "@types/js-yaml": "^4.0.9", diff --git a/packages/agent-host/src/generated/dshPackages.ts b/packages/agent-host/src/generated/dshPackages.ts index fb67c21b..142771b3 100644 --- a/packages/agent-host/src/generated/dshPackages.ts +++ b/packages/agent-host/src/generated/dshPackages.ts @@ -8,6 +8,7 @@ export const DSH_PACKAGES: readonly TreePackageEntry[] = [ { name: "@anthropic-ai/sdk", version: "0.129.0", integrity: "sha512-MH7LB20kNpGLUpPTe2OG5XvL/KhX8HUO9XyBaFjgFk6TLS4Xjt0VPIuMKywe7POKKPslX+QxSlVok9e+8kG5Nw==", dest: "node_modules/@anthropic-ai/sdk" }, { name: "zod", version: "4.6.7", integrity: "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", dest: "node_modules/@anthropic-ai/sdk/node_modules/zod" }, { name: "@aws-sdk/client-bedrock-runtime", version: "3.1127.0", integrity: "sha512-IDl/lrPb90aH+pZFHGNDmgH9nAUQj5PlZH1sJ3w7RikctyjHSnY3oNjZhrLoaBoQn/rNK0zsP6OHEqEhj2tdLA==", dest: "node_modules/@aws-sdk/client-bedrock-runtime" }, + { name: "@smithy/node-http-handler", version: "4.14.2", integrity: "sha512-i1uORV1v3qBqP43ayRKzIdm1q5x14tf8N4Dd06/QUX1Szm6VxHMrTsu20X5E63UFsaNZCRjI4SXG0jDmqYa+3w==", dest: "node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/node-http-handler" }, { name: "@aws-sdk/core", version: "3.980.2", integrity: "sha512-Q0hqjfLf1zvwB6aY6fi8pYrtgxHs8sqymhXH/iWBZM/wkokjT869Ws4F12nCD2KX3hiAvKku2cZplxM0cydX8A==", dest: "node_modules/@aws-sdk/core" }, { name: "@aws-sdk/credential-provider-env", version: "3.972.83", integrity: "sha512-6+hlZC2mCIX9XnjO+x3MwJuR9U7whWiiP0CVq3SLrCluueze0Elce40ivWPuH0TArqHBNyF4y62V5clNDCjtVw==", dest: "node_modules/@aws-sdk/credential-provider-env" }, { name: "@aws-sdk/credential-provider-http", version: "3.972.85", integrity: "sha512-Rm6vdrzm3eUoG+9frOhS9Q93WdqKq/5h+971aeazkTftwbz3AfYlATd7avn9aMkg2AHlafkbewm0yq/3Sc7GYA==", dest: "node_modules/@aws-sdk/credential-provider-http" }, @@ -658,6 +659,7 @@ export const DSH_PACKAGES: readonly TreePackageEntry[] = [ { name: "once", version: "1.4.0", integrity: "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", dest: "node_modules/once", optional: true }, { name: "open", version: "11.0.4", integrity: "sha512-++Zlftm0kVLPmzC06t6epuWmcRMDbI4z5P3NNX979WA/k23+NtSOynEGzsVfZwguKw2mi5umVgnBlJQMwRz4Pg==", dest: "node_modules/open" }, { name: "openai", version: "7.19.0", integrity: "sha512-MX2s3u2L5racTO0CC/SWpCOasJQBCJrqLKXK+l82cAhdeF8mPMBEe/gxMm0ZFa2xpKpOFLRjxv5afYEZbBXmbQ==", dest: "node_modules/openai" }, + { name: "undici", version: "8.12.3", integrity: "sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==", dest: "node_modules/openai/node_modules/undici", optional: true }, { name: "zod", version: "4.6.7", integrity: "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", dest: "node_modules/openai/node_modules/zod" }, { name: "p-cancelable", version: "4.0.1", integrity: "sha512-wBowNApzd45EIKdO1LaU+LrMBwAcjfPaYtVzV3lmfM3gf8Z4CHZsiIqlM8TZZ8okYvh5A1cP6gTfCRQtwUpaUg==", dest: "node_modules/p-cancelable" }, { name: "p-limit", version: "7.3.3", integrity: "sha512-SKgVvDU5TNIxQ4r30U75BNLC6a+6GOEjngrk/ysM5+Zu3oJuk1SC5ApzIzY/7PjCEjoVPMWJ0zho/4QUiEB7TQ==", dest: "node_modules/p-limit" }, diff --git a/packages/agent-host/src/generated/piPackages.ts b/packages/agent-host/src/generated/piPackages.ts new file mode 100644 index 00000000..4c8b7155 --- /dev/null +++ b/packages/agent-host/src/generated/piPackages.ts @@ -0,0 +1,219 @@ +// Generated from pnpm-lock.yaml by src/install/lockfilePins.ts — do not edit. +// Regenerate with this package's `gen:platform-packages` script. +import type { TreePackageEntry } from '../install/lockfilePins'; + +export const PI_PACKAGES: readonly TreePackageEntry[] = [ + { name: "@anthropic-ai/sdk", version: "0.129.0", integrity: "sha512-MH7LB20kNpGLUpPTe2OG5XvL/KhX8HUO9XyBaFjgFk6TLS4Xjt0VPIuMKywe7POKKPslX+QxSlVok9e+8kG5Nw==", dest: "node_modules/@anthropic-ai/sdk" }, + { name: "@aws-sdk/client-bedrock-runtime", version: "3.1127.0", integrity: "sha512-IDl/lrPb90aH+pZFHGNDmgH9nAUQj5PlZH1sJ3w7RikctyjHSnY3oNjZhrLoaBoQn/rNK0zsP6OHEqEhj2tdLA==", dest: "node_modules/@aws-sdk/client-bedrock-runtime" }, + { name: "@smithy/node-http-handler", version: "4.14.2", integrity: "sha512-i1uORV1v3qBqP43ayRKzIdm1q5x14tf8N4Dd06/QUX1Szm6VxHMrTsu20X5E63UFsaNZCRjI4SXG0jDmqYa+3w==", dest: "node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/node-http-handler" }, + { name: "@aws-sdk/core", version: "3.980.2", integrity: "sha512-Q0hqjfLf1zvwB6aY6fi8pYrtgxHs8sqymhXH/iWBZM/wkokjT869Ws4F12nCD2KX3hiAvKku2cZplxM0cydX8A==", dest: "node_modules/@aws-sdk/core" }, + { name: "@aws-sdk/credential-provider-env", version: "3.972.83", integrity: "sha512-6+hlZC2mCIX9XnjO+x3MwJuR9U7whWiiP0CVq3SLrCluueze0Elce40ivWPuH0TArqHBNyF4y62V5clNDCjtVw==", dest: "node_modules/@aws-sdk/credential-provider-env" }, + { name: "@aws-sdk/credential-provider-http", version: "3.972.85", integrity: "sha512-Rm6vdrzm3eUoG+9frOhS9Q93WdqKq/5h+971aeazkTftwbz3AfYlATd7avn9aMkg2AHlafkbewm0yq/3Sc7GYA==", dest: "node_modules/@aws-sdk/credential-provider-http" }, + { name: "@smithy/node-http-handler", version: "4.14.2", integrity: "sha512-i1uORV1v3qBqP43ayRKzIdm1q5x14tf8N4Dd06/QUX1Szm6VxHMrTsu20X5E63UFsaNZCRjI4SXG0jDmqYa+3w==", dest: "node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/node-http-handler" }, + { name: "@aws-sdk/credential-provider-ini", version: "3.973.28", integrity: "sha512-hSXbMSuPeUY1/RjBC9vahy3ADVULVLU/wyGEXeoelVFYEs7Pki3RF37wROlHOmT8c4XARhJhvLLs+65sczEsoA==", dest: "node_modules/@aws-sdk/credential-provider-ini" }, + { name: "@aws-sdk/credential-provider-login", version: "3.972.90", integrity: "sha512-Hzpp8qvA1qcpAB3xX1+VUwmuTJBPh9h5Ju6CdzzESXTym2JvsTR1NmlhmrufkLr5y+Bj5rj/xjtK4gYu1wA6KA==", dest: "node_modules/@aws-sdk/credential-provider-login" }, + { name: "@aws-sdk/credential-provider-node", version: "3.972.95", integrity: "sha512-3IIZ78pwRVLy+d2xn1yRAyEXRc2eCYQ9r5zO4QqDQuVHbOHe01nTWGqLkEM5JAp/vA0pmQTjPojg8JZ10C668Q==", dest: "node_modules/@aws-sdk/credential-provider-node" }, + { name: "@aws-sdk/credential-provider-process", version: "3.972.83", integrity: "sha512-XejCj4/jfZuXmH6P3HCP4eW/7rfrxG70RhurqAvyoo8hevgDwLDW8xR79ww8ad+T/ZD7ERK6jV7CCFBLLBhiLQ==", dest: "node_modules/@aws-sdk/credential-provider-process" }, + { name: "@aws-sdk/credential-provider-sso", version: "3.973.27", integrity: "sha512-lM9xX3+0PCW3H4QfIDk0PRlcJCeF7kV2Cv93MhWQgKRhxzdis5m9inBa801X0w+nq+ckzlYYxa4674etFTikvw==", dest: "node_modules/@aws-sdk/credential-provider-sso" }, + { name: "@aws-sdk/token-providers", version: "3.1165.0", integrity: "sha512-xYE0nhi3LLacRnoSuUzEv6riWczXXeOOoXeMVw97KBHMLmHKqxmc94leV4RMzEK/BNbZfCKmL5FQoOiuIBkp/g==", dest: "node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers" }, + { name: "@aws-sdk/credential-provider-web-identity", version: "3.972.89", integrity: "sha512-4uJ8gF2huGZ6QisO/AeQm7H2+4HXtEJTw0e6lsbc+Qu3YohUErkYGfJlKJWx3ociM6zlxVObiC6etoAKmnafKg==", dest: "node_modules/@aws-sdk/credential-provider-web-identity" }, + { name: "@aws-sdk/eventstream-handler-node", version: "3.972.41", integrity: "sha512-wxumGicDtZHD8KwT5F6AKogDxzpA83lOSe8I1y0FFtuYSXz2AhVC8NVL4PbP68ApYzsaFJYFxxu9pDszfo4cbA==", dest: "node_modules/@aws-sdk/eventstream-handler-node" }, + { name: "@aws-sdk/middleware-eventstream", version: "3.972.37", integrity: "sha512-gWP0pJN+YD9nR+OVegvj52tL45WYghqcnKDg2Vid+zIvrQfp5WPP89mGcYTAyfUuLao6IfF16j9lUFLtipEJiw==", dest: "node_modules/@aws-sdk/middleware-eventstream" }, + { name: "@aws-sdk/middleware-websocket", version: "3.972.65", integrity: "sha512-ECX3mJ1dPL1WpfsXtJlM2YR+QnHpqt2/xhAUBDQWcWxhC0gZgsZP9tTVC5xmeCBJR6kRac6aY7RupXia7rAtOA==", dest: "node_modules/@aws-sdk/middleware-websocket" }, + { name: "@aws-sdk/nested-clients", version: "3.998.2", integrity: "sha512-T1vNOfMdvdjXU4Nq267iTFoxZ2Bj0vEatkp66j8wBtrpDoX1mBWmxy7RL8O93S2oXo+BFEiXH3nWtLMd0svLnA==", dest: "node_modules/@aws-sdk/nested-clients" }, + { name: "@smithy/node-http-handler", version: "4.14.2", integrity: "sha512-i1uORV1v3qBqP43ayRKzIdm1q5x14tf8N4Dd06/QUX1Szm6VxHMrTsu20X5E63UFsaNZCRjI4SXG0jDmqYa+3w==", dest: "node_modules/@aws-sdk/nested-clients/node_modules/@smithy/node-http-handler" }, + { name: "@aws-sdk/signature-v4-multi-region", version: "3.996.52", integrity: "sha512-6W6SjGc8OXUhMzNxU1X922ghD+PP1XvzmCk5Scui0jaYsLezycMYR1RaLp5xTIOUrhTXyb4DnAbPr3fBgmdnzg==", dest: "node_modules/@aws-sdk/signature-v4-multi-region" }, + { name: "@aws-sdk/token-providers", version: "3.1127.0", integrity: "sha512-Dv2TMWBshJ+tF6ahs2Sy5bh4Iabsd4GAQqVvE9XZmYmnoaVbpS2QKIKE/HRacc7bTtbjEEvP+laGzHvHlf1CiQ==", dest: "node_modules/@aws-sdk/token-providers" }, + { name: "@aws-sdk/types", version: "3.975.1", integrity: "sha512-7rGxUkCB2QPoQOeJmonmAICTN2zrH+fpmi1p4Iwu72lnxNaMhOgqcbpyddifnM1DBb19TWQ1u6z/XjkaFNEDWw==", dest: "node_modules/@aws-sdk/types" }, + { name: "@aws-sdk/xml-builder", version: "3.972.43", integrity: "sha512-rG8QVx4DOrJWptsogu1Aq+CDsnPKaBrAlJpKLxrJrIDXAq1ElnW0yQjjBnlWSXll0cDakCG6UDvaqwz0A9d9Og==", dest: "node_modules/@aws-sdk/xml-builder" }, + { name: "@aws/lambda-invoke-store", version: "0.3.0", integrity: "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==", dest: "node_modules/@aws/lambda-invoke-store" }, + { name: "@babel/runtime", version: "7.29.7", integrity: "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==", dest: "node_modules/@babel/runtime" }, + { name: "@earendil-works/pi-agent-core", version: "1.5.2", integrity: "sha512-ie5mejS7mGfXt//9As7i3LfxVXdktZvF1JP4EQsUXTp4mU437h23MNGx7wXZ5VYs3YiG/Qnj3e7OZ2HC069OMw==", dest: "node_modules/@earendil-works/pi-agent-core" }, + { name: "@earendil-works/pi-ai", version: "1.5.2", integrity: "sha512-2tWPSnV3qzfiDIY3aWluBag3vC++Vs+VsXt/UquSU5onPMohPih72FUhIhaqmDdMYubOgB3Byl9uF4Vk40JLvQ==", dest: "node_modules/@earendil-works/pi-ai" }, + { name: "https-proxy-agent", version: "9.1.0", integrity: "sha512-ag87y7cJJ9/3+GxFr8Oy4O5faDsGRGnBGsJj/YjOSsSx/5eadKLYTMPlzuR6obgoCDDm0abAAZitXXQkMOPSpA==", dest: "node_modules/@earendil-works/pi-ai/node_modules/https-proxy-agent" }, + { name: "agent-base", version: "9.0.0", integrity: "sha512-TQf59BsZnytt8GdJKLPfUZ54g/iaUL2OWDSFCCvMOhsHduDQxO8xC4PNeyIkVcA5KwL2phPSv0douC0fgWzmnA==", dest: "node_modules/@earendil-works/pi-ai/node_modules/https-proxy-agent/node_modules/agent-base" }, + { name: "@earendil-works/pi-codemode", version: "1.5.2", integrity: "sha512-HoZQ40a9RgdZ1VgmrX6x8887cNXedaRJT1l+Ie5YRIMK4gY7v0EpsiNqf6dmixrKylZlTgUSyR+vE8xhjfkr+w==", dest: "node_modules/@earendil-works/pi-codemode" }, + { name: "@earendil-works/pi-coding-agent", version: "1.5.2", integrity: "sha512-mUWI04rqF1Vd/m1q+Ps1XeWsTXEVvRUnsmRa83I3Dzua0Tx5bYS93imeqtIfrXf7PkkaR6ERz+AuQhIJlom5yA==", dest: "node_modules/@earendil-works/pi-coding-agent" }, + { name: "@earendil-works/pi-mcp", version: "1.5.2", integrity: "sha512-zU1UgeXDlbixPqGEWD7Ql0brEMIpYr7aEWjoEE5h5enJbM/kQ2jIr7lN8JoR80oUnq1fJSU7SC8kLx2Fx/IZYg==", dest: "node_modules/@earendil-works/pi-mcp" }, + { name: "@earendil-works/pi-schema", version: "1.5.2", integrity: "sha512-hJoyCXWUhsSrXY5wJo2Q4kHXUsR51pNhkJHAMkWRwVMLDRtMDPkKNaa+JlVRVqTw1hjdSxcVVaFLSDbKlaTXEQ==", dest: "node_modules/@earendil-works/pi-schema" }, + { name: "@earendil-works/pi-telemetry", version: "1.5.2", integrity: "sha512-m+cumjIqNh1aMISi/9ttcG3ZOwIdriPbz/eMyWmRMJCGa/WcgY1RX4lrb7HvsHhSfI/JUeBESA4nOCr8C3y5ow==", dest: "node_modules/@earendil-works/pi-telemetry" }, + { name: "@earendil-works/pi-tui", version: "1.5.2", integrity: "sha512-WK8ih+c88GWizaB79y7Pq3PV7ySf5VI1pZ1i/6aBBjDOAiG2EE3ojKjl+pxQqLfyQGnzHYu4VfakOBJgumuoyw==", dest: "node_modules/@earendil-works/pi-tui" }, + { name: "@google/genai", version: "2.21.0", integrity: "sha512-+PDtco2/Z0ONdzCGekCoCT+O1VJS9xJQNN4XzQpXG/t3El/SWWMkCWlFRO1KmivOHPa4Q0VjUYu1HBKCZ/v33Q==", dest: "node_modules/@google/genai" }, + { name: "@hono/node-server", version: "2.1.5", integrity: "sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q==", dest: "node_modules/@hono/node-server", optional: true }, + { name: "@isaacs/nonrecursive-glob-match", version: "1.1.0", integrity: "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==", dest: "node_modules/@isaacs/nonrecursive-glob-match" }, + { name: "@modelcontextprotocol/sdk", version: "1.30.0", integrity: "sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA==", dest: "node_modules/@modelcontextprotocol/sdk", optional: true }, + { name: "@protobufjs/aspromise", version: "1.1.2", integrity: "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", dest: "node_modules/@protobufjs/aspromise" }, + { name: "@protobufjs/base64", version: "1.1.2", integrity: "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", dest: "node_modules/@protobufjs/base64" }, + { name: "@protobufjs/codegen", version: "2.0.5", integrity: "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", dest: "node_modules/@protobufjs/codegen" }, + { name: "@protobufjs/eventemitter", version: "1.1.1", integrity: "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==", dest: "node_modules/@protobufjs/eventemitter" }, + { name: "@protobufjs/fetch", version: "1.1.1", integrity: "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", dest: "node_modules/@protobufjs/fetch" }, + { name: "@protobufjs/float", version: "1.0.2", integrity: "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", dest: "node_modules/@protobufjs/float" }, + { name: "@protobufjs/path", version: "1.1.2", integrity: "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", dest: "node_modules/@protobufjs/path" }, + { name: "@protobufjs/pool", version: "1.1.0", integrity: "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", dest: "node_modules/@protobufjs/pool" }, + { name: "@protobufjs/utf8", version: "1.1.2", integrity: "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==", dest: "node_modules/@protobufjs/utf8" }, + { name: "@silvia-odwyer/photon-node", version: "0.3.4", integrity: "sha512-bnly4BKB3KDTFxrUIcgCLbaeVVS8lrAkri1pEzskpmxu9MdfGQTy8b8EgcD83ywD3RPMsIulY8xJH5Awa+t9fA==", dest: "node_modules/@silvia-odwyer/photon-node" }, + { name: "@smithy/core", version: "3.40.0", integrity: "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ==", dest: "node_modules/@smithy/core" }, + { name: "@smithy/credential-provider-imds", version: "4.5.2", integrity: "sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==", dest: "node_modules/@smithy/credential-provider-imds" }, + { name: "@smithy/fetch-http-handler", version: "5.8.1", integrity: "sha512-h8BdMUrUBhMhMaeK7QqAdINRZezCGuYOCpcOZZ1ewxbHST9rdTd09xwNpvLTYfzDRehxQiReK4SKbdYZxBA+ew==", dest: "node_modules/@smithy/fetch-http-handler" }, + { name: "@smithy/node-http-handler", version: "4.12.1", integrity: "sha512-ThMkboGeONWXAelq9FvGsuJC4rOi+qyC4/zhUF58xYpxUg5sQKx2VXZYJmtNjr4dSuBJ1HeJXETQILCz3wOHvw==", dest: "node_modules/@smithy/node-http-handler" }, + { name: "@smithy/signature-v4", version: "5.7.5", integrity: "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg==", dest: "node_modules/@smithy/signature-v4" }, + { name: "@smithy/types", version: "4.20.0", integrity: "sha512-lCA6QG22dPk9ecHbv91jDQZsmtPUjdS1aE2Il6NNPqe7DrYc0dZQi6DhcESk2KYXH2sp5xbAcGdYMZDFnuzA2A==", dest: "node_modules/@smithy/types" }, + { name: "@stablelib/base64", version: "1.0.1", integrity: "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==", dest: "node_modules/@stablelib/base64" }, + { name: "@types/node", version: "22.20.1", integrity: "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==", dest: "node_modules/@types/node" }, + { name: "@types/retry", version: "0.12.0", integrity: "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==", dest: "node_modules/@types/retry" }, + { name: "accepts", version: "2.0.0", integrity: "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", dest: "node_modules/accepts", optional: true }, + { name: "agent-base", version: "7.1.4", integrity: "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", dest: "node_modules/agent-base" }, + { name: "ajv", version: "8.20.0", integrity: "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", dest: "node_modules/ajv", optional: true }, + { name: "ajv-formats", version: "3.0.1", integrity: "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", dest: "node_modules/ajv-formats", optional: true }, + { name: "balanced-match", version: "4.0.4", integrity: "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", dest: "node_modules/balanced-match" }, + { name: "base64-js", version: "1.5.1", integrity: "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", dest: "node_modules/base64-js" }, + { name: "bignumber.js", version: "9.3.1", integrity: "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==", dest: "node_modules/bignumber.js" }, + { name: "body-parser", version: "2.4.0", integrity: "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", dest: "node_modules/body-parser", optional: true }, + { name: "content-type", version: "2.1.0", integrity: "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", dest: "node_modules/body-parser/node_modules/content-type", optional: true }, + { name: "bowser", version: "2.15.0", integrity: "sha512-xic6KSZglg/I4ymp45fdM4GWfYpBK79Fxd/TOvJktlaPgQqqDxvmGwOPZl2V0dyeS3Lj5c180bLhXF43iyAjZQ==", dest: "node_modules/bowser" }, + { name: "brace-expansion", version: "5.0.12", integrity: "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", dest: "node_modules/brace-expansion" }, + { name: "buffer-equal-constant-time", version: "1.0.1", integrity: "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", dest: "node_modules/buffer-equal-constant-time" }, + { name: "bytes", version: "3.1.2", integrity: "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", dest: "node_modules/bytes", optional: true }, + { name: "call-bind-apply-helpers", version: "1.0.2", integrity: "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", dest: "node_modules/call-bind-apply-helpers", optional: true }, + { name: "call-bound", version: "1.0.4", integrity: "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", dest: "node_modules/call-bound", optional: true }, + { name: "chalk", version: "6.0.0", integrity: "sha512-2uNTXIuTTxk7ciZgAU1BQcgnchcG0xXnrs6jzkQfj9SsRa9M2s5zE8WT96hS6KmG4MzWHSrvH43DF1m4XRkrFg==", dest: "node_modules/chalk" }, + { name: "content-disposition", version: "2.0.1", integrity: "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==", dest: "node_modules/content-disposition", optional: true }, + { name: "content-type", version: "1.0.5", integrity: "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", dest: "node_modules/content-type", optional: true }, + { name: "cookie", version: "0.7.2", integrity: "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", dest: "node_modules/cookie", optional: true }, + { name: "cookie-signature", version: "1.2.2", integrity: "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", dest: "node_modules/cookie-signature", optional: true }, + { name: "cors", version: "2.8.6", integrity: "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", dest: "node_modules/cors", optional: true }, + { name: "cross-spawn", version: "7.0.6", integrity: "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", dest: "node_modules/cross-spawn" }, + { name: "data-uri-to-buffer", version: "4.0.1", integrity: "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", dest: "node_modules/data-uri-to-buffer" }, + { name: "debug", version: "4.4.3", integrity: "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", dest: "node_modules/debug" }, + { name: "depd", version: "2.0.0", integrity: "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", dest: "node_modules/depd", optional: true }, + { name: "diff", version: "8.0.4", integrity: "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==", dest: "node_modules/diff" }, + { name: "dunder-proto", version: "1.0.1", integrity: "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", dest: "node_modules/dunder-proto", optional: true }, + { name: "ecdsa-sig-formatter", version: "1.0.11", integrity: "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", dest: "node_modules/ecdsa-sig-formatter" }, + { name: "ee-first", version: "1.1.1", integrity: "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", dest: "node_modules/ee-first", optional: true }, + { name: "encodeurl", version: "2.0.0", integrity: "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", dest: "node_modules/encodeurl", optional: true }, + { name: "es-define-property", version: "1.0.1", integrity: "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", dest: "node_modules/es-define-property", optional: true }, + { name: "es-errors", version: "1.3.0", integrity: "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", dest: "node_modules/es-errors", optional: true }, + { name: "es-object-atoms", version: "1.1.2", integrity: "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", dest: "node_modules/es-object-atoms", optional: true }, + { name: "escape-html", version: "1.0.3", integrity: "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", dest: "node_modules/escape-html", optional: true }, + { name: "etag", version: "1.8.1", integrity: "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", dest: "node_modules/etag", optional: true }, + { name: "eventsource", version: "3.0.7", integrity: "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", dest: "node_modules/eventsource", optional: true }, + { name: "eventsource-parser", version: "3.1.1", integrity: "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", dest: "node_modules/eventsource-parser", optional: true }, + { name: "express", version: "5.3.0", integrity: "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==", dest: "node_modules/express", optional: true }, + { name: "express-rate-limit", version: "8.7.1", integrity: "sha512-2FXbqkygil3mZiXzEtM0IjE/UBmBNot0J1GEVrJT4JbrvwOSoEtqtO+wHbiMQELWe1eNvHoYRg2dkjOid+6JkA==", dest: "node_modules/express-rate-limit", optional: true }, + { name: "content-type", version: "2.1.0", integrity: "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", dest: "node_modules/express/node_modules/content-type", optional: true }, + { name: "extend", version: "3.0.2", integrity: "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", dest: "node_modules/extend" }, + { name: "fast-deep-equal", version: "3.1.3", integrity: "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", dest: "node_modules/fast-deep-equal", optional: true }, + { name: "fast-sha256", version: "1.3.0", integrity: "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==", dest: "node_modules/fast-sha256" }, + { name: "fast-uri", version: "3.1.5", integrity: "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==", dest: "node_modules/fast-uri", optional: true }, + { name: "fetch-blob", version: "3.2.0", integrity: "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", dest: "node_modules/fetch-blob" }, + { name: "finalhandler", version: "2.1.1", integrity: "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", dest: "node_modules/finalhandler", optional: true }, + { name: "formdata-polyfill", version: "4.0.10", integrity: "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", dest: "node_modules/formdata-polyfill" }, + { name: "forwarded", version: "0.2.0", integrity: "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", dest: "node_modules/forwarded", optional: true }, + { name: "fresh", version: "2.0.0", integrity: "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", dest: "node_modules/fresh", optional: true }, + { name: "function-bind", version: "1.1.2", integrity: "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", dest: "node_modules/function-bind", optional: true }, + { name: "gaxios", version: "7.3.1", integrity: "sha512-kB3rzJV7d9juLZh8/56QTXCwQfxyhdOMdyYk1HdQKFtF8TJTDTZQJtixWIwXdE9Jji91mC41DUNpjleo4L4eAQ==", dest: "node_modules/gaxios" }, + { name: "gcp-metadata", version: "8.1.2", integrity: "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg==", dest: "node_modules/gcp-metadata" }, + { name: "get-east-asian-width", version: "1.6.0", integrity: "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==", dest: "node_modules/get-east-asian-width" }, + { name: "get-intrinsic", version: "1.3.0", integrity: "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", dest: "node_modules/get-intrinsic", optional: true }, + { name: "get-proto", version: "1.0.1", integrity: "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", dest: "node_modules/get-proto", optional: true }, + { name: "google-auth-library", version: "10.9.1", integrity: "sha512-i1ydyHrqcIxXkWh/uBmVkzCvIuq5yiK2ATndIe5XxKholrG/MTYP9xGYka4sQhrbIAgGjL2B6NOE7rFaiF3fXw==", dest: "node_modules/google-auth-library" }, + { name: "google-logging-utils", version: "1.1.3", integrity: "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==", dest: "node_modules/google-logging-utils" }, + { name: "gopd", version: "1.2.0", integrity: "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", dest: "node_modules/gopd", optional: true }, + { name: "graceful-fs", version: "4.2.12", integrity: "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==", dest: "node_modules/graceful-fs" }, + { name: "has-symbols", version: "1.1.0", integrity: "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", dest: "node_modules/has-symbols", optional: true }, + { name: "hasown", version: "2.0.4", integrity: "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", dest: "node_modules/hasown", optional: true }, + { name: "highlight.js", version: "10.7.3", integrity: "sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A==", dest: "node_modules/highlight.js" }, + { name: "hono", version: "4.13.14", integrity: "sha512-yhRLQ21U6qa9Hsu2N7Qcbh8tE+WKEcoErjIo56LeSGiGXGp9sA7UpE86Ui9uexb61KakiGwuHMn2QdV7w6i6kQ==", dest: "node_modules/hono", optional: true }, + { name: "hosted-git-info", version: "9.0.3", integrity: "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg==", dest: "node_modules/hosted-git-info" }, + { name: "http-errors", version: "2.0.1", integrity: "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", dest: "node_modules/http-errors", optional: true }, + { name: "http-proxy-agent", version: "9.1.0", integrity: "sha512-2NxoveTT58mjYT4n3RPTEfCZGLMbidoO8XEieXfpSYxu+PQJ1qpx4ypwH6N+uF9twBPIvRRgvkvW5HUTYWENig==", dest: "node_modules/http-proxy-agent" }, + { name: "agent-base", version: "9.0.0", integrity: "sha512-TQf59BsZnytt8GdJKLPfUZ54g/iaUL2OWDSFCCvMOhsHduDQxO8xC4PNeyIkVcA5KwL2phPSv0douC0fgWzmnA==", dest: "node_modules/http-proxy-agent/node_modules/agent-base" }, + { name: "https-proxy-agent", version: "7.0.6", integrity: "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", dest: "node_modules/https-proxy-agent" }, + { name: "iconv-lite", version: "0.7.3", integrity: "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", dest: "node_modules/iconv-lite", optional: true }, + { name: "ignore", version: "7.0.8", integrity: "sha512-YYNsSlXBjMk92SKnkwvB5LOVSa6OznlFUGcsvrFgNJbJCd0M1XKeFVRc8ZByeCqz32FivYNHJVooLmdqrmvp/Q==", dest: "node_modules/ignore" }, + { name: "inherits", version: "2.0.4", integrity: "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", dest: "node_modules/inherits", optional: true }, + { name: "ip-address", version: "10.7.5", integrity: "sha512-t2v0rkILYv9WXmSL7TpAaU3HXgaFYOPUcH3QHgwQ++gpJuH3bqyMy4Fvt/DJCTKwzH3Cf+bAp5W/mFL39KPLzA==", dest: "node_modules/ip-address", optional: true }, + { name: "ipaddr.js", version: "1.9.1", integrity: "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", dest: "node_modules/ipaddr.js", optional: true }, + { name: "is-promise", version: "4.0.0", integrity: "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", dest: "node_modules/is-promise", optional: true }, + { name: "isexe", version: "2.0.0", integrity: "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", dest: "node_modules/isexe" }, + { name: "jiti", version: "2.7.0", integrity: "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", dest: "node_modules/jiti" }, + { name: "jose", version: "6.2.13", integrity: "sha512-7TIg10ZE1x82YediN+lcrPNvGMKge9yFHQD+Qho/b8y2adfugU3AsvvHfxV0fzyFllT6l9xCjf4RWY9g/Z9PJQ==", dest: "node_modules/jose", optional: true }, + { name: "json-bigint", version: "1.0.0", integrity: "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==", dest: "node_modules/json-bigint" }, + { name: "json-schema-to-ts", version: "3.1.1", integrity: "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", dest: "node_modules/json-schema-to-ts" }, + { name: "json-schema-traverse", version: "1.0.0", integrity: "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", dest: "node_modules/json-schema-traverse", optional: true }, + { name: "json-schema-typed", version: "8.0.2", integrity: "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", dest: "node_modules/json-schema-typed", optional: true }, + { name: "jwa", version: "2.0.1", integrity: "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", dest: "node_modules/jwa" }, + { name: "jws", version: "4.0.1", integrity: "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", dest: "node_modules/jws" }, + { name: "long", version: "5.3.2", integrity: "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", dest: "node_modules/long" }, + { name: "lovely-mermaid", version: "0.3.3", integrity: "sha512-EMLJS934qwt2MLO/a5o+T/89HGbuXZPwmCpHIhHO+DVrm+y5tHlEHgpZzlC2o4yW/rFPHRFO9xSMafzqH4wH5A==", dest: "node_modules/lovely-mermaid" }, + { name: "lru-cache", version: "11.5.3", integrity: "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", dest: "node_modules/lru-cache" }, + { name: "marked", version: "18.0.11", integrity: "sha512-HnslJfsZkRPBDJRHvVtAaWlZHEpSu7u8LgQuJCELjRKuWR+hpq4A7sLq3p8HaI9ypVoXDXxV34CsQJEe1+J5Aw==", dest: "node_modules/marked" }, + { name: "marked-cjk-friendly", version: "0.1.2", integrity: "sha512-GUj8HjiEbur9yhgUo52FBgKizggF1QtT6gVdrYdWW6ZB4lVVjgS3EyyXPyfyRD0V4ghGRPlO7MO80rgSWbm0eA==", dest: "node_modules/marked-cjk-friendly" }, + { name: "math-intrinsics", version: "1.1.0", integrity: "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", dest: "node_modules/math-intrinsics", optional: true }, + { name: "media-typer", version: "1.1.1", integrity: "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", dest: "node_modules/media-typer", optional: true }, + { name: "merge-descriptors", version: "2.0.0", integrity: "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", dest: "node_modules/merge-descriptors", optional: true }, + { name: "mime-db", version: "1.54.0", integrity: "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", dest: "node_modules/mime-db", optional: true }, + { name: "mime-types", version: "3.0.2", integrity: "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", dest: "node_modules/mime-types", optional: true }, + { name: "minimatch", version: "11.0.3", integrity: "sha512-iny/40PEGkNJQ5/Pv6z3nm6FbRAby32GeZRjCUJk2WnNDbgPSTcdI+DDvLqsgBdD4cD5sMtMheqPPnehCCa8Nw==", dest: "node_modules/minimatch" }, + { name: "brace-expansion", version: "5.0.13", integrity: "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", dest: "node_modules/minimatch/node_modules/brace-expansion" }, + { name: "ms", version: "2.1.3", integrity: "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", dest: "node_modules/ms" }, + { name: "negotiator", version: "1.1.0", integrity: "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", dest: "node_modules/negotiator", optional: true }, + { name: "content-type", version: "2.1.0", integrity: "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", dest: "node_modules/negotiator/node_modules/content-type", optional: true }, + { name: "node-domexception", version: "1.0.0", integrity: "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", dest: "node_modules/node-domexception" }, + { name: "node-fetch", version: "3.3.2", integrity: "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==", dest: "node_modules/node-fetch" }, + { name: "object-assign", version: "4.1.1", integrity: "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", dest: "node_modules/object-assign", optional: true }, + { name: "object-inspect", version: "1.13.4", integrity: "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", dest: "node_modules/object-inspect", optional: true }, + { name: "on-finished", version: "2.4.2", integrity: "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==", dest: "node_modules/on-finished", optional: true }, + { name: "once", version: "1.4.0", integrity: "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", dest: "node_modules/once", optional: true }, + { name: "openai", version: "7.19.0", integrity: "sha512-MX2s3u2L5racTO0CC/SWpCOasJQBCJrqLKXK+l82cAhdeF8mPMBEe/gxMm0ZFa2xpKpOFLRjxv5afYEZbBXmbQ==", dest: "node_modules/openai" }, + { name: "p-retry", version: "4.6.2", integrity: "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==", dest: "node_modules/p-retry" }, + { name: "retry", version: "0.13.1", integrity: "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", dest: "node_modules/p-retry/node_modules/retry" }, + { name: "parseurl", version: "1.3.3", integrity: "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", dest: "node_modules/parseurl", optional: true }, + { name: "partial-json", version: "0.1.7", integrity: "sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA==", dest: "node_modules/partial-json" }, + { name: "path-key", version: "3.1.1", integrity: "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", dest: "node_modules/path-key" }, + { name: "path-to-regexp", version: "8.4.2", integrity: "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", dest: "node_modules/path-to-regexp", optional: true }, + { name: "pkce-challenge", version: "5.0.1", integrity: "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", dest: "node_modules/pkce-challenge", optional: true }, + { name: "proper-lockfile", version: "4.1.2", integrity: "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==", dest: "node_modules/proper-lockfile" }, + { name: "protobufjs", version: "7.6.6", integrity: "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==", dest: "node_modules/protobufjs" }, + { name: "proxy-addr", version: "2.0.8", integrity: "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", dest: "node_modules/proxy-addr", optional: true }, + { name: "proxy-agent-negotiate", version: "1.1.0", integrity: "sha512-N8IBcM3UgCVzz2L2Lqv8DVntDnnC8/hiV4nEDUPkqq72TPUgYWjQc+bdZlBPZK9LzPAvOY//gAt0S0DApoOXWQ==", dest: "node_modules/proxy-agent-negotiate" }, + { name: "qs", version: "6.16.1", integrity: "sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg==", dest: "node_modules/qs", optional: true }, + { name: "quickjs-wasi", version: "3.6.2", integrity: "sha512-FCqGtGOrMgzUiIrMNMA2YnsOxCNwo31dzqXvclXUC6xeT35NJLKXQJsvbeCTjvoFAwZgEAPg8U6+KAPDGXn8Mg==", dest: "node_modules/quickjs-wasi" }, + { name: "range-parser", version: "1.3.0", integrity: "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", dest: "node_modules/range-parser", optional: true }, + { name: "raw-body", version: "3.0.2", integrity: "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", dest: "node_modules/raw-body", optional: true }, + { name: "require-from-string", version: "2.0.2", integrity: "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", dest: "node_modules/require-from-string", optional: true }, + { name: "retry", version: "0.12.0", integrity: "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==", dest: "node_modules/retry" }, + { name: "router", version: "2.2.0", integrity: "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", dest: "node_modules/router", optional: true }, + { name: "safe-buffer", version: "5.2.1", integrity: "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", dest: "node_modules/safe-buffer" }, + { name: "safer-buffer", version: "2.1.2", integrity: "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", dest: "node_modules/safer-buffer", optional: true }, + { name: "semver", version: "7.8.5", integrity: "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", dest: "node_modules/semver" }, + { name: "send", version: "1.2.1", integrity: "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", dest: "node_modules/send", optional: true }, + { name: "serve-static", version: "2.2.1", integrity: "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", dest: "node_modules/serve-static", optional: true }, + { name: "setprototypeof", version: "1.2.0", integrity: "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", dest: "node_modules/setprototypeof", optional: true }, + { name: "shebang-command", version: "2.0.0", integrity: "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", dest: "node_modules/shebang-command" }, + { name: "shebang-regex", version: "3.0.0", integrity: "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", dest: "node_modules/shebang-regex" }, + { name: "side-channel", version: "1.1.1", integrity: "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", dest: "node_modules/side-channel", optional: true }, + { name: "side-channel-list", version: "1.0.1", integrity: "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", dest: "node_modules/side-channel-list", optional: true }, + { name: "side-channel-map", version: "1.0.1", integrity: "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", dest: "node_modules/side-channel-map", optional: true }, + { name: "side-channel-weakmap", version: "1.0.2", integrity: "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", dest: "node_modules/side-channel-weakmap", optional: true }, + { name: "signal-exit", version: "3.0.7", integrity: "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", dest: "node_modules/signal-exit" }, + { name: "standardwebhooks", version: "1.0.0", integrity: "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==", dest: "node_modules/standardwebhooks" }, + { name: "statuses", version: "2.0.2", integrity: "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", dest: "node_modules/statuses", optional: true }, + { name: "toidentifier", version: "1.0.1", integrity: "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", dest: "node_modules/toidentifier", optional: true }, + { name: "ts-algebra", version: "2.0.0", integrity: "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", dest: "node_modules/ts-algebra" }, + { name: "tslib", version: "2.8.1", integrity: "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", dest: "node_modules/tslib" }, + { name: "type-is", version: "2.1.0", integrity: "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", dest: "node_modules/type-is", optional: true }, + { name: "content-type", version: "2.1.0", integrity: "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", dest: "node_modules/type-is/node_modules/content-type", optional: true }, + { name: "typebox", version: "1.3.27", integrity: "sha512-zu+jc1pcy4UiNThxikUr36f0Rybk9PEeCg/NE6adeWr/SKsdNO4EzZHYRDlv2YCVAfj3Odq3dESSo/jNyoBXzA==", dest: "node_modules/typebox" }, + { name: "undici", version: "8.12.3", integrity: "sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==", dest: "node_modules/undici" }, + { name: "undici-types", version: "6.21.0", integrity: "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", dest: "node_modules/undici-types" }, + { name: "unpipe", version: "1.0.0", integrity: "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", dest: "node_modules/unpipe", optional: true }, + { name: "vary", version: "1.1.2", integrity: "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", dest: "node_modules/vary", optional: true }, + { name: "web-streams-polyfill", version: "3.3.3", integrity: "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", dest: "node_modules/web-streams-polyfill" }, + { name: "which", version: "2.0.2", integrity: "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", dest: "node_modules/which" }, + { name: "wrappy", version: "1.0.2", integrity: "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", dest: "node_modules/wrappy", optional: true }, + { name: "ws", version: "8.22.2", integrity: "sha512-/rEZ2ejown2N5gxVTHUu9bVVC7ttu0/Tgzf5hbTOixR3Fs7mbbXgn2DbdbcKgJOmpQMtrIUWivtYuVMnp/W/yA==", dest: "node_modules/ws" }, + { name: "yaml", version: "2.9.0", integrity: "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==", dest: "node_modules/yaml" }, + { name: "zod", version: "4.6.7", integrity: "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", dest: "node_modules/zod", optional: true }, + { name: "zod-to-json-schema", version: "3.25.2", integrity: "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", dest: "node_modules/zod-to-json-schema", optional: true }, +]; diff --git a/packages/agent-host/src/install/__tests__/lockfilePins.test.ts b/packages/agent-host/src/install/__tests__/lockfilePins.test.ts index 04b1aa3e..dea33057 100644 --- a/packages/agent-host/src/install/__tests__/lockfilePins.test.ts +++ b/packages/agent-host/src/install/__tests__/lockfilePins.test.ts @@ -1,7 +1,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import { describe, expect, it } from 'vitest'; -import { packageTree, platformPackages, renderDshPackages, renderPlatformPackages, renderQwenPackages } from '../lockfilePins'; +import { packageTree, platformPackages, renderDshPackages, renderPiPackages, renderPlatformPackages, renderQwenPackages } from '../lockfilePins'; const LOCKFILE = `lockfileVersion: '9.0' @@ -65,7 +65,7 @@ const LOCKFILE_PATH = path.resolve(__dirname, '../../../../../pnpm-lock.yaml'); * lay down, so the single-binary map leaves them out. */ function runtimeTreeNames(lockfile: string): Set { const names = new Set(); - for (const root of ['@deepseek-ai/dsh', '@qwen-code/qwen-code']) { + for (const root of ['@deepseek-ai/dsh', '@qwen-code/qwen-code', '@earendil-works/pi-coding-agent']) { for (const entry of packageTree(lockfile, 'packages/agent-host', root)) names.add(entry.name); } return names; @@ -213,3 +213,12 @@ describe('src/generated/qwenPackages.ts', () => { ); }); }); + +describe('src/generated/piPackages.ts', () => { + it('matches pnpm-lock.yaml', async () => { + const lockfile = fs.readFileSync(LOCKFILE_PATH, 'utf8'); + await expect( + renderPiPackages(packageTree(lockfile, 'packages/agent-host', '@earendil-works/pi-coding-agent')), + ).toMatchFileSnapshot('../../generated/piPackages.ts'); + }); +}); diff --git a/packages/agent-host/src/install/lockfilePins.ts b/packages/agent-host/src/install/lockfilePins.ts index f2339972..4f09e7d4 100644 --- a/packages/agent-host/src/install/lockfilePins.ts +++ b/packages/agent-host/src/install/lockfilePins.ts @@ -308,3 +308,8 @@ export function renderDshPackages(entries: TreePackageEntry[]): string { export function renderQwenPackages(entries: TreePackageEntry[]): string { return renderTree(entries, 'QWEN_PACKAGES'); } + +/** The generated module's source for the Pi runtime tree. */ +export function renderPiPackages(entries: TreePackageEntry[]): string { + return renderTree(entries, 'PI_PACKAGES'); +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3ac4adb1..9d17793e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -31,7 +31,10 @@ importers: version: 2.5.0(zod@4.6.7) '@deepseek-ai/dsh': specifier: 0.2.2-rc.1 - version: 0.2.2-rc.1(1d84d006321b94c5e228438151df696e) + version: 0.2.2-rc.1(fca01932baa61bf52e1ecbaaa5e62eb1) + '@earendil-works/pi-coding-agent': + specifier: 1.5.2 + version: 1.5.2(@aws-sdk/credential-provider-node@3.972.95)(@modelcontextprotocol/sdk@1.30.0(zod@4.6.7))(@smithy/signature-v4@5.7.5)(ws@8.22.2)(zod@4.6.7) '@opencode/cli': specifier: 2.2.7 version: 2.2.7 @@ -52,7 +55,7 @@ importers: version: 5.9.3 vitest: specifier: ^3.0.0 - version: 3.2.7(@types/debug@4.1.13)(@types/node@22.20.1)(jsdom@30.0.1(@noble/hashes@2.0.1))(yaml@2.9.1) + version: 3.2.7(@types/debug@4.1.13)(@types/node@22.20.1)(jiti@2.7.0)(jsdom@30.0.1(@noble/hashes@2.0.1))(yaml@2.9.1) packages/vscode-extension: devDependencies: @@ -73,7 +76,7 @@ importers: version: 5.9.3 vitest: specifier: ^3.0.0 - version: 3.2.7(@types/debug@4.1.13)(@types/node@22.20.1)(jsdom@30.0.1(@noble/hashes@2.0.1))(yaml@2.9.1) + version: 3.2.7(@types/debug@4.1.13)(@types/node@22.20.1)(jiti@2.7.0)(jsdom@30.0.1(@noble/hashes@2.0.1))(yaml@2.9.1) packages: @@ -3016,11 +3019,28 @@ packages: '@deepseek-ai/schemastery@3.19.0': resolution: {integrity: sha512-bDXoYQa7ghAhmdYD5VPlzKxEzJV/aKkz5l4V5h1u06z8GAPN1ROewSjvR9WiXhpa52E9fng8lpH5QdCRIQgnyQ==} + '@earendil-works/pi-agent-core@1.5.2': + resolution: {integrity: sha512-ie5mejS7mGfXt//9As7i3LfxVXdktZvF1JP4EQsUXTp4mU437h23MNGx7wXZ5VYs3YiG/Qnj3e7OZ2HC069OMw==} + engines: {node: '>=22.19.0'} + '@earendil-works/pi-ai@1.5.2': resolution: {integrity: sha512-2tWPSnV3qzfiDIY3aWluBag3vC++Vs+VsXt/UquSU5onPMohPih72FUhIhaqmDdMYubOgB3Byl9uF4Vk40JLvQ==} engines: {node: '>=22.19.0'} hasBin: true + '@earendil-works/pi-codemode@1.5.2': + resolution: {integrity: sha512-HoZQ40a9RgdZ1VgmrX6x8887cNXedaRJT1l+Ie5YRIMK4gY7v0EpsiNqf6dmixrKylZlTgUSyR+vE8xhjfkr+w==} + engines: {node: '>=22.19.0'} + + '@earendil-works/pi-coding-agent@1.5.2': + resolution: {integrity: sha512-mUWI04rqF1Vd/m1q+Ps1XeWsTXEVvRUnsmRa83I3Dzua0Tx5bYS93imeqtIfrXf7PkkaR6ERz+AuQhIJlom5yA==} + engines: {node: '>=22.19.0'} + hasBin: true + + '@earendil-works/pi-mcp@1.5.2': + resolution: {integrity: sha512-zU1UgeXDlbixPqGEWD7Ql0brEMIpYr7aEWjoEE5h5enJbM/kQ2jIr7lN8JoR80oUnq1fJSU7SC8kLx2Fx/IZYg==} + engines: {node: '>=22.19.0'} + '@earendil-works/pi-schema@1.5.2': resolution: {integrity: sha512-hJoyCXWUhsSrXY5wJo2Q4kHXUsR51pNhkJHAMkWRwVMLDRtMDPkKNaa+JlVRVqTw1hjdSxcVVaFLSDbKlaTXEQ==} engines: {node: '>=22.19.0'} @@ -3029,6 +3049,10 @@ packages: resolution: {integrity: sha512-m+cumjIqNh1aMISi/9ttcG3ZOwIdriPbz/eMyWmRMJCGa/WcgY1RX4lrb7HvsHhSfI/JUeBESA4nOCr8C3y5ow==} engines: {node: '>=22.19.0'} + '@earendil-works/pi-tui@1.5.2': + resolution: {integrity: sha512-WK8ih+c88GWizaB79y7Pq3PV7ySf5VI1pZ1i/6aBBjDOAiG2EE3ojKjl+pxQqLfyQGnzHYu4VfakOBJgumuoyw==} + engines: {node: '>=22.19.0'} + '@emnapi/runtime@1.11.3': resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==} @@ -3504,6 +3528,9 @@ packages: cpu: [x64] os: [win32] + '@isaacs/nonrecursive-glob-match@1.1.0': + resolution: {integrity: sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==} + '@joplin/turndown-plugin-gfm@1.0.68': resolution: {integrity: sha512-m8DfAQNC/V7g0j5H6Jv60WhekBBjodD+zTPGrU+g2m+ux/z8ZX07KQIl6kaAmbKwfvsQhC04op52g63I78sVgg==} @@ -4075,6 +4102,9 @@ packages: resolution: {integrity: sha512-Nqc90v4lWCXyakD6xNyNACBJNJ0tNCwj2WNk/7ivyacYHxiITVgmLUFXTBOeCdy79iz6HtN9Y31uw/jbLrdOAg==} engines: {node: '>=20.0.0'} + '@silvia-odwyer/photon-node@0.3.4': + resolution: {integrity: sha512-bnly4BKB3KDTFxrUIcgCLbaeVVS8lrAkri1pEzskpmxu9MdfGQTy8b8EgcD83ywD3RPMsIulY8xJH5Awa+t9fA==} + '@sindresorhus/is@7.2.0': resolution: {integrity: sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==} engines: {node: '>=18'} @@ -4417,6 +4447,10 @@ packages: bowser@2.15.0: resolution: {integrity: sha512-xic6KSZglg/I4ymp45fdM4GWfYpBK79Fxd/TOvJktlaPgQqqDxvmGwOPZl2V0dyeS3Lj5c180bLhXF43iyAjZQ==} + brace-expansion@5.0.12: + resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==} + engines: {node: 20 || >=22} + brace-expansion@5.0.13: resolution: {integrity: sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==} engines: {node: 20 || >=22} @@ -4466,6 +4500,10 @@ packages: resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==} engines: {node: '>=18'} + chalk@6.0.0: + resolution: {integrity: sha512-2uNTXIuTTxk7ciZgAU1BQcgnchcG0xXnrs6jzkQfj9SsRa9M2s5zE8WT96hS6KmG4MzWHSrvH43DF1m4XRkrFg==} + engines: {node: '>=22'} + check-error@2.1.3: resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==} engines: {node: '>= 16'} @@ -4593,6 +4631,10 @@ packages: dfa@1.2.0: resolution: {integrity: sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==} + diff@8.0.4: + resolution: {integrity: sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==} + engines: {node: '>=0.3.1'} + diff@9.0.0: resolution: {integrity: sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw==} engines: {node: '>=0.3.1'} @@ -4752,6 +4794,10 @@ packages: resolution: {integrity: sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg==} engines: {node: '>=18'} + get-east-asian-width@1.6.0: + resolution: {integrity: sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==} + engines: {node: '>=18'} + get-intrinsic@1.3.0: resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==} engines: {node: '>= 0.4'} @@ -4791,6 +4837,9 @@ packages: resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==} engines: {node: '>= 0.4'} + highlight.js@10.7.3: + resolution: {integrity: sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A==} + hono@4.13.14: resolution: {integrity: sha512-yhRLQ21U6qa9Hsu2N7Qcbh8tE+WKEcoErjIo56LeSGiGXGp9sA7UpE86Ui9uexb61KakiGwuHMn2QdV7w6i6kQ==} engines: {node: '>=16.9.0'} @@ -4838,6 +4887,10 @@ packages: resolution: {integrity: sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==} engines: {node: '>=0.10.0'} + ignore@7.0.8: + resolution: {integrity: sha512-YYNsSlXBjMk92SKnkwvB5LOVSa6OznlFUGcsvrFgNJbJCd0M1XKeFVRc8ZByeCqz32FivYNHJVooLmdqrmvp/Q==} + engines: {node: '>= 4'} + inherits@2.0.4: resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} @@ -4896,6 +4949,10 @@ packages: resolution: {integrity: sha512-5mbUj3SiZXCuRf9fT3ibzbSSEWiy63gFfksmGfdOzujPjW3k+z8WvIBxcJHBoQNlaZaiyB25deviif2+osLmLw==} engines: {node: '>=4'} + jiti@2.7.0: + resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} + hasBin: true + jose@6.2.13: resolution: {integrity: sha512-7TIg10ZE1x82YediN+lcrPNvGMKge9yFHQD+Qho/b8y2adfugU3AsvvHfxV0fzyFllT6l9xCjf4RWY9g/Z9PJQ==} @@ -4980,6 +5037,10 @@ packages: loupe@3.2.1: resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==} + lovely-mermaid@0.3.3: + resolution: {integrity: sha512-EMLJS934qwt2MLO/a5o+T/89HGbuXZPwmCpHIhHO+DVrm+y5tHlEHgpZzlC2o4yW/rFPHRFO9xSMafzqH4wH5A==} + engines: {node: '>=18'} + lowercase-keys@3.0.0: resolution: {integrity: sha512-ozCC6gdQ+glXOQsveKD0YsDy8DSQFjDTz4zyzEHNV5+JP5D62LmfDZ6o1cycFx9ouG940M5dE8C8CTewdj2YWQ==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} @@ -4995,6 +5056,17 @@ packages: magic-string@0.30.21: resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + marked-cjk-friendly@0.1.2: + resolution: {integrity: sha512-GUj8HjiEbur9yhgUo52FBgKizggF1QtT6gVdrYdWW6ZB4lVVjgS3EyyXPyfyRD0V4ghGRPlO7MO80rgSWbm0eA==} + engines: {node: '>=18'} + peerDependencies: + marked: '>=15.0.0' + + marked@18.0.11: + resolution: {integrity: sha512-HnslJfsZkRPBDJRHvVtAaWlZHEpSu7u8LgQuJCELjRKuWR+hpq4A7sLq3p8HaI9ypVoXDXxV34CsQJEe1+J5Aw==} + engines: {node: '>= 20'} + hasBin: true + marked@18.2.0: resolution: {integrity: sha512-KaeL+tAbtvI930q7HE2PN5lYXYdT8EiSmxHlN6F3rsfb57wd5mp5W5TLazpdj4inTQBJdgjYwbs40W/0VUGU+Q==} engines: {node: '>= 20'} @@ -5036,6 +5108,10 @@ packages: resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==} engines: {node: 18 || 20 || >=22} + minimatch@11.0.3: + resolution: {integrity: sha512-iny/40PEGkNJQ5/Pv6z3nm6FbRAby32GeZRjCUJk2WnNDbgPSTcdI+DDvLqsgBdD4cD5sMtMheqPPnehCCa8Nw==} + engines: {node: 18 || 20 || >=22} + minisearch@7.2.0: resolution: {integrity: sha512-dqT2XBYUOZOiC5t2HRnwADjhNS2cecp9u+TJRiJ1Qp/f5qjkeT5APcGPjHw+bz89Ms8Jp+cG4AlE+QZ/QnDglg==} @@ -5302,6 +5378,9 @@ packages: resolution: {integrity: sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==} engines: {node: '>=10'} + quickjs-wasi@3.6.2: + resolution: {integrity: sha512-FCqGtGOrMgzUiIrMNMA2YnsOxCNwo31dzqXvclXUC6xeT35NJLKXQJsvbeCTjvoFAwZgEAPg8U6+KAPDGXn8Mg==} + range-parser@1.3.0: resolution: {integrity: sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==} engines: {node: '>= 0.6'} @@ -5583,6 +5662,9 @@ packages: resolution: {integrity: sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==} engines: {node: '>= 18'} + typebox@1.3.27: + resolution: {integrity: sha512-zu+jc1pcy4UiNThxikUr36f0Rybk9PEeCg/NE6adeWr/SKsdNO4EzZHYRDlv2YCVAfj3Odq3dESSo/jNyoBXzA==} + typed-rest-client@1.8.11: resolution: {integrity: sha512-5UvfMpd1oelmUPRbbaVnq+rHP7ng2cE4qoQkQeAqxRL6PklkxsM0g32/HL0yfvruK6ojQ5x8EE+HF4YV6DtuCA==} @@ -5601,6 +5683,10 @@ packages: resolution: {integrity: sha512-u4UB2/IrKdU6lFxumHmmo1a3fCQO5tzQllRorfoRS63txhrB7xTpSn1PftwC4qEHkOaqP95fCWW4lJzwErwzhQ==} engines: {node: '>=22.19.0'} + undici@8.12.3: + resolution: {integrity: sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==} + engines: {node: '>=22.19.0'} + unicode-properties@1.4.1: resolution: {integrity: sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==} @@ -5775,6 +5861,11 @@ packages: yallist@4.0.0: resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==} + yaml@2.9.0: + resolution: {integrity: sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==} + engines: {node: '>= 14.6'} + hasBin: true + yaml@2.9.1: resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} engines: {node: '>= 14.6'} @@ -5890,7 +5981,7 @@ snapshots: '@aws-sdk/types': 3.975.1 '@smithy/core': 3.40.0 '@smithy/fetch-http-handler': 5.8.1 - '@smithy/node-http-handler': 4.12.1 + '@smithy/node-http-handler': 4.14.2 '@smithy/types': 4.20.0 tslib: 2.8.1 @@ -6560,7 +6651,7 @@ snapshots: '@deepseek-ai/dsh-credentials': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/dsh-llm': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) - '@deepseek-ai/dsh-base@0.2.2-rc.1(9eeab18ba2d7c4b838a234c5b6746e80)': + '@deepseek-ai/dsh-base@0.2.2-rc.1(2247109099c0704de54befb237440464)': dependencies: '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) '@deepseek-ai/cordis-plugin-timer': 1.2.0(@deepseek-ai/cordis@4.1.0) @@ -6594,7 +6685,7 @@ snapshots: '@deepseek-ai/dsh-llm': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/dsh-llm-deepseek-account': 0.2.2-rc.1(@deepseek-ai/cordis-plugin-loader@1.1.0)(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-deepseek-account@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-agent@0.2.2-rc.1(d9740b81bf2b48fd86b0c38a41e906a0))(@deepseek-ai/dsh-brand@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-util-values@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-launch-environment@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-llm-deepseek@0.2.2-rc.1(956429393e4ea8c4b7066693d213f8f6))(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) '@deepseek-ai/dsh-llm-deepseek-api-key': 0.2.2-rc.1(@deepseek-ai/cordis-plugin-loader@1.1.0)(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-credentials@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-launch-environment@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-llm-deepseek@0.2.2-rc.1(956429393e4ea8c4b7066693d213f8f6))(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) - '@deepseek-ai/dsh-llm-pi-ai': 0.2.2-rc.1(b581825234a99d73e38a912584eadff9) + '@deepseek-ai/dsh-llm-pi-ai': 0.2.2-rc.1(6d593f4e4ef8cb3e5de695aa900bf844) '@deepseek-ai/dsh-llm-retry': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-agent@0.2.2-rc.1(d9740b81bf2b48fd86b0c38a41e906a0))(@deepseek-ai/dsh-brand@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session-projection@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-timeout@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) '@deepseek-ai/dsh-mcp-resources': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-system-prompt@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-tools@0.2.2-rc.1(71e9b8099add9aaf7bb42662f07c41a3)) '@deepseek-ai/dsh-otel': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))) @@ -7872,7 +7963,7 @@ snapshots: optionalDependencies: '@deepseek-ai/cordis-plugin-loader': 1.1.0(@deepseek-ai/cordis@4.1.0)(node-addon-require-builtin@0.1.9) - '@deepseek-ai/dsh-llm-pi-ai@0.2.2-rc.1(b581825234a99d73e38a912584eadff9)': + '@deepseek-ai/dsh-llm-pi-ai@0.2.2-rc.1(6d593f4e4ef8cb3e5de695aa900bf844)': dependencies: '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) '@deepseek-ai/dsh-attachment': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-brand@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) @@ -7885,7 +7976,7 @@ snapshots: '@deepseek-ai/dsh-timeout': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/dsh-util-values': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/schemastery': 3.19.0 - '@earendil-works/pi-ai': 1.5.2(@aws-sdk/credential-provider-node@3.972.95)(@modelcontextprotocol/sdk@1.30.0(zod@4.6.7))(@smithy/signature-v4@5.7.5)(undici@8.11.2)(ws@8.22.2)(zod@4.6.7) + '@earendil-works/pi-ai': 1.5.2(@aws-sdk/credential-provider-node@3.972.95)(@modelcontextprotocol/sdk@1.30.0(zod@4.6.7))(@smithy/signature-v4@5.7.5)(undici@8.12.3)(ws@8.22.2)(zod@4.6.7) optionalDependencies: '@deepseek-ai/cordis-plugin-loader': 1.1.0(@deepseek-ai/cordis@4.1.0)(node-addon-require-builtin@0.1.9) transitivePeerDependencies: @@ -9598,7 +9689,7 @@ snapshots: '@deepseek-ai/dsh-typert-protocol': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) zod: 4.4.3 - '@deepseek-ai/dsh@0.2.2-rc.1(1d84d006321b94c5e228438151df696e)': + '@deepseek-ai/dsh@0.2.2-rc.1(fca01932baa61bf52e1ecbaaa5e62eb1)': dependencies: '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) '@deepseek-ai/cordis-plugin-include': 1.1.0(@deepseek-ai/cordis-plugin-loader@1.1.0)(@deepseek-ai/cordis@4.1.0) @@ -9610,7 +9701,7 @@ snapshots: '@deepseek-ai/dsh-agent-tool-presentation': 0.2.2-rc.1(9121e207bacfe5f50c5d945c203115c2) '@deepseek-ai/dsh-app-boot': 0.2.2-rc.1(@deepseek-ai/cordis-plugin-group@1.1.0(@deepseek-ai/cordis-plugin-loader@1.1.0)(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0)(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-home-paths@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-launch-environment@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) '@deepseek-ai/dsh-atomic-write': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) - '@deepseek-ai/dsh-base': 0.2.2-rc.1(9eeab18ba2d7c4b838a234c5b6746e80) + '@deepseek-ai/dsh-base': 0.2.2-rc.1(2247109099c0704de54befb237440464) '@deepseek-ai/dsh-client-ui-agent-preset': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/dsh-client-ui-cordis': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/dsh-cmdline': 0.2.2-rc.1(@deepseek-ai/cordis-plugin-loader@1.1.0)(@deepseek-ai/cordis@4.1.0) @@ -9824,7 +9915,24 @@ snapshots: '@deepseek-ai/cosmokit': 1.9.0 '@standard-schema/spec': 1.1.0 - '@earendil-works/pi-ai@1.5.2(@aws-sdk/credential-provider-node@3.972.95)(@modelcontextprotocol/sdk@1.30.0(zod@4.6.7))(@smithy/signature-v4@5.7.5)(undici@8.11.2)(ws@8.22.2)(zod@4.6.7)': + '@earendil-works/pi-agent-core@1.5.2(@aws-sdk/credential-provider-node@3.972.95)(@modelcontextprotocol/sdk@1.30.0(zod@4.6.7))(@smithy/signature-v4@5.7.5)(undici@8.12.3)(ws@8.22.2)(zod@4.6.7)': + dependencies: + '@earendil-works/pi-ai': 1.5.2(@aws-sdk/credential-provider-node@3.972.95)(@modelcontextprotocol/sdk@1.30.0(zod@4.6.7))(@smithy/signature-v4@5.7.5)(undici@8.12.3)(ws@8.22.2)(zod@4.6.7) + '@earendil-works/pi-schema': 1.5.2 + transitivePeerDependencies: + - '@aws-sdk/credential-provider-node' + - '@modelcontextprotocol/sdk' + - '@smithy/hash-node' + - '@smithy/signature-v4' + - bufferutil + - kerberos + - supports-color + - undici + - utf-8-validate + - ws + - zod + + '@earendil-works/pi-ai@1.5.2(@aws-sdk/credential-provider-node@3.972.95)(@modelcontextprotocol/sdk@1.30.0(zod@4.6.7))(@smithy/signature-v4@5.7.5)(undici@8.12.3)(ws@8.22.2)(zod@4.6.7)': dependencies: '@anthropic-ai/sdk': 0.129.0(zod@4.6.7) '@aws-sdk/client-bedrock-runtime': 3.1127.0 @@ -9834,7 +9942,7 @@ snapshots: '@smithy/node-http-handler': 4.12.1 http-proxy-agent: 9.1.0 https-proxy-agent: 9.1.0 - openai: 7.19.0(@aws-sdk/credential-provider-node@3.972.95)(@smithy/signature-v4@5.7.5)(undici@8.11.2)(ws@8.22.2)(zod@4.6.7) + openai: 7.19.0(@aws-sdk/credential-provider-node@3.972.95)(@smithy/signature-v4@5.7.5)(undici@8.12.3)(ws@8.22.2)(zod@4.6.7) partial-json: 0.1.7 transitivePeerDependencies: - '@aws-sdk/credential-provider-node' @@ -9849,10 +9957,60 @@ snapshots: - ws - zod + '@earendil-works/pi-codemode@1.5.2': + dependencies: + quickjs-wasi: 3.6.2 + + '@earendil-works/pi-coding-agent@1.5.2(@aws-sdk/credential-provider-node@3.972.95)(@modelcontextprotocol/sdk@1.30.0(zod@4.6.7))(@smithy/signature-v4@5.7.5)(ws@8.22.2)(zod@4.6.7)': + dependencies: + '@earendil-works/pi-agent-core': 1.5.2(@aws-sdk/credential-provider-node@3.972.95)(@modelcontextprotocol/sdk@1.30.0(zod@4.6.7))(@smithy/signature-v4@5.7.5)(undici@8.12.3)(ws@8.22.2)(zod@4.6.7) + '@earendil-works/pi-ai': 1.5.2(@aws-sdk/credential-provider-node@3.972.95)(@modelcontextprotocol/sdk@1.30.0(zod@4.6.7))(@smithy/signature-v4@5.7.5)(undici@8.12.3)(ws@8.22.2)(zod@4.6.7) + '@earendil-works/pi-codemode': 1.5.2 + '@earendil-works/pi-mcp': 1.5.2 + '@earendil-works/pi-tui': 1.5.2 + '@silvia-odwyer/photon-node': 0.3.4 + brace-expansion: 5.0.12 + chalk: 6.0.0 + cross-spawn: 7.0.6 + diff: 8.0.4 + highlight.js: 10.7.3 + hosted-git-info: 9.0.3 + ignore: 7.0.8 + jiti: 2.7.0 + lovely-mermaid: 0.3.3 + minimatch: 11.0.3 + proper-lockfile: 4.1.2 + quickjs-wasi: 3.6.2 + semver: 7.8.5 + typebox: 1.3.27 + undici: 8.12.3 + yaml: 2.9.0 + transitivePeerDependencies: + - '@aws-sdk/credential-provider-node' + - '@modelcontextprotocol/sdk' + - '@smithy/hash-node' + - '@smithy/signature-v4' + - bufferutil + - kerberos + - supports-color + - utf-8-validate + - ws + - zod + + '@earendil-works/pi-mcp@1.5.2': + dependencies: + cross-spawn: 7.0.6 + '@earendil-works/pi-schema@1.5.2': {} '@earendil-works/pi-telemetry@1.5.2': {} + '@earendil-works/pi-tui@1.5.2': + dependencies: + get-east-asian-width: 1.6.0 + marked: 18.0.11 + marked-cjk-friendly: 0.1.2(marked@18.0.11) + '@emnapi/runtime@1.11.3': dependencies: tslib: 2.8.1 @@ -10170,6 +10328,8 @@ snapshots: '@img/sharp-win32-x64@0.35.5': optional: true + '@isaacs/nonrecursive-glob-match@1.1.0': {} + '@joplin/turndown-plugin-gfm@1.0.68': {} '@jridgewell/sourcemap-codec@1.5.5': {} @@ -10635,6 +10795,8 @@ snapshots: '@secretlint/types@10.2.2': {} + '@silvia-odwyer/photon-node@0.3.4': {} + '@sindresorhus/is@7.2.0': {} '@sindresorhus/merge-streams@4.0.0': {} @@ -10758,13 +10920,13 @@ snapshots: chai: 5.3.3 tinyrainbow: 2.0.0 - '@vitest/mocker@3.2.7(vite@6.4.3(@types/node@22.20.1)(yaml@2.9.1))': + '@vitest/mocker@3.2.7(vite@6.4.3(@types/node@22.20.1)(jiti@2.7.0)(yaml@2.9.1))': dependencies: '@vitest/spy': 3.2.7 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: - vite: 6.4.3(@types/node@22.20.1)(yaml@2.9.1) + vite: 6.4.3(@types/node@22.20.1)(jiti@2.7.0)(yaml@2.9.1) '@vitest/pretty-format@3.2.7': dependencies: @@ -10988,6 +11150,10 @@ snapshots: bowser@2.15.0: {} + brace-expansion@5.0.12: + dependencies: + balanced-match: 4.0.4 + brace-expansion@5.0.13: dependencies: balanced-match: 4.0.4 @@ -11040,6 +11206,8 @@ snapshots: loupe: 3.2.1 pathval: 2.0.1 + chalk@6.0.0: {} + check-error@2.1.3: {} chokidar@5.0.0: @@ -11142,6 +11310,8 @@ snapshots: dfa@1.2.0: {} + diff@8.0.4: {} + diff@9.0.0: {} dunder-proto@1.0.1: @@ -11356,6 +11526,8 @@ snapshots: transitivePeerDependencies: - supports-color + get-east-asian-width@1.6.0: {} + get-intrinsic@1.3.0: dependencies: call-bind-apply-helpers: 1.0.2 @@ -11417,6 +11589,8 @@ snapshots: dependencies: function-bind: 1.1.2 + highlight.js@10.7.3: {} + hono@4.13.14: {} hosted-git-info@4.1.0: @@ -11480,6 +11654,8 @@ snapshots: dependencies: safer-buffer: 2.1.2 + ignore@7.0.8: {} + inherits@2.0.4: {} ip-address@10.7.5: {} @@ -11519,6 +11695,8 @@ snapshots: editions: 6.22.0 textextensions: 6.11.0 + jiti@2.7.0: {} + jose@6.2.13: {} js-tokens@4.0.0: {} @@ -11637,6 +11815,8 @@ snapshots: loupe@3.2.1: {} + lovely-mermaid@0.3.3: {} + lowercase-keys@3.0.0: {} lru-cache@11.5.3: {} @@ -11649,6 +11829,12 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.5.5 + marked-cjk-friendly@0.1.2(marked@18.0.11): + dependencies: + marked: 18.0.11 + + marked@18.0.11: {} + marked@18.2.0: {} math-intrinsics@1.1.0: {} @@ -11674,6 +11860,11 @@ snapshots: dependencies: brace-expansion: 5.0.13 + minimatch@11.0.3: + dependencies: + '@isaacs/nonrecursive-glob-match': 1.1.0 + brace-expansion: 5.0.13 + minisearch@7.2.0: {} ms@2.0.0: {} @@ -11798,11 +11989,11 @@ snapshots: powershell-utils: 0.2.1 wsl-utils: 1.0.1 - openai@7.19.0(@aws-sdk/credential-provider-node@3.972.95)(@smithy/signature-v4@5.7.5)(undici@8.11.2)(ws@8.22.2)(zod@4.6.7): + openai@7.19.0(@aws-sdk/credential-provider-node@3.972.95)(@smithy/signature-v4@5.7.5)(undici@8.12.3)(ws@8.22.2)(zod@4.6.7): optionalDependencies: '@aws-sdk/credential-provider-node': 3.972.95 '@smithy/signature-v4': 5.7.5 - undici: 8.11.2 + undici: 8.12.3 ws: 8.22.2 zod: 4.6.7 @@ -11896,6 +12087,8 @@ snapshots: quick-lru@5.1.1: {} + quickjs-wasi@3.6.2: {} + range-parser@1.3.0: {} raw-body@3.0.2: @@ -12240,6 +12433,8 @@ snapshots: media-typer: 1.1.1 mime-types: 3.0.2 + typebox@1.3.27: {} + typed-rest-client@1.8.11: dependencies: qs: 6.16.1 @@ -12254,6 +12449,8 @@ snapshots: undici@8.11.2: {} + undici@8.12.3: {} + unicode-properties@1.4.1: dependencies: base64-js: 1.5.1 @@ -12274,13 +12471,13 @@ snapshots: version-range@4.15.0: {} - vite-node@3.2.4(@types/node@22.20.1)(yaml@2.9.1): + vite-node@3.2.4(@types/node@22.20.1)(jiti@2.7.0)(yaml@2.9.1): dependencies: cac: 6.7.14 debug: 4.4.3 es-module-lexer: 1.7.0 pathe: 2.0.3 - vite: 6.4.3(@types/node@22.20.1)(yaml@2.9.1) + vite: 6.4.3(@types/node@22.20.1)(jiti@2.7.0)(yaml@2.9.1) transitivePeerDependencies: - '@types/node' - jiti @@ -12295,7 +12492,7 @@ snapshots: - tsx - yaml - vite@6.4.3(@types/node@22.20.1)(yaml@2.9.1): + vite@6.4.3(@types/node@22.20.1)(jiti@2.7.0)(yaml@2.9.1): dependencies: esbuild: 0.25.12 fdir: 6.5.0(picomatch@4.0.7) @@ -12306,13 +12503,14 @@ snapshots: optionalDependencies: '@types/node': 22.20.1 fsevents: 2.3.3 + jiti: 2.7.0 yaml: 2.9.1 - vitest@3.2.7(@types/debug@4.1.13)(@types/node@22.20.1)(jsdom@30.0.1(@noble/hashes@2.0.1))(yaml@2.9.1): + vitest@3.2.7(@types/debug@4.1.13)(@types/node@22.20.1)(jiti@2.7.0)(jsdom@30.0.1(@noble/hashes@2.0.1))(yaml@2.9.1): dependencies: '@types/chai': 5.2.3 '@vitest/expect': 3.2.7 - '@vitest/mocker': 3.2.7(vite@6.4.3(@types/node@22.20.1)(yaml@2.9.1)) + '@vitest/mocker': 3.2.7(vite@6.4.3(@types/node@22.20.1)(jiti@2.7.0)(yaml@2.9.1)) '@vitest/pretty-format': 3.2.7 '@vitest/runner': 3.2.7 '@vitest/snapshot': 3.2.7 @@ -12330,8 +12528,8 @@ snapshots: tinyglobby: 0.2.17 tinypool: 1.1.1 tinyrainbow: 2.0.0 - vite: 6.4.3(@types/node@22.20.1)(yaml@2.9.1) - vite-node: 3.2.4(@types/node@22.20.1)(yaml@2.9.1) + vite: 6.4.3(@types/node@22.20.1)(jiti@2.7.0)(yaml@2.9.1) + vite-node: 3.2.4(@types/node@22.20.1)(jiti@2.7.0)(yaml@2.9.1) why-is-node-running: 2.3.0 optionalDependencies: '@types/debug': 4.1.13 @@ -12416,6 +12614,8 @@ snapshots: yallist@4.0.0: {} + yaml@2.9.0: {} + yaml@2.9.1: {} yauzl@3.4.0: From 19bf521db748191320010c4a907d51b2fb12bc4f Mon Sep 17 00:00:00 2001 From: deymosh <232244450+deymosh@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:30:51 +0100 Subject: [PATCH 2/8] feat(agent-host): add the Pi driver MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pi has no permission system of its own: its tool calls run as soon as the model asks for them. CodeDeck's own Pi extension holds every tool_call and asks the client through Pi's extension-UI protocol, which is what turns those calls into the phone's permission cards. The extension is a single self-contained function serialized into Pi's config directory at session start, so it runs inside Pi's process with nothing of the host beside it. Policy lives in the driver, where the card is built from the tool_execution_start facts of the call: ask (the default) asks for every tool except Pi's own read-only set, yolo answers everything, and "allow for this session" is remembered per tool. Other extensions' dialogs reach the phone as questions, and a session's end or an interrupt answers every open dialog cancelled — Pi does not settle an agent while one waits. Sessions are one Pi process each over RPC (JSONL on stdio, LF-only framing so U+2028 inside a string is data, not a record boundary), with Pi's own conversation ids resumed through --session and its context meter reported as session info. A provider profile is bound through the environment and registered by the same extension with Pi's OpenAI-completions API, the token referenced by name so it never reaches the file on disk. Models are listed from a short-lived probe process. The shared tool reader now treats a path with a non-empty edits list as a file change: Pi's editor and Claude Code's MultiEdit both spell their changes that way, and a call from either was read as a read. Co-Authored-By: Claude Code --- .../src/drivers/pi/__tests__/fakePi.ts | 369 +++++++ .../src/drivers/pi/__tests__/piDriver.test.ts | 453 ++++++++ .../drivers/pi/__tests__/piExtension.test.ts | 146 +++ .../drivers/pi/__tests__/piFakeModel.test.ts | 194 ++++ .../src/drivers/pi/__tests__/piRpc.test.ts | 104 ++ .../src/drivers/pi/__tests__/piTools.test.ts | 69 ++ packages/agent-host/src/drivers/pi/driver.ts | 993 ++++++++++++++++++ packages/agent-host/src/drivers/pi/env.ts | 99 ++ .../agent-host/src/drivers/pi/extension.ts | 126 +++ packages/agent-host/src/drivers/pi/install.ts | 54 + packages/agent-host/src/drivers/pi/module.ts | 53 + packages/agent-host/src/drivers/pi/rpc.ts | 305 ++++++ packages/agent-host/src/drivers/pi/runtime.ts | 115 ++ packages/agent-host/src/drivers/pi/style.ts | 28 + packages/agent-host/src/drivers/pi/tools.ts | 62 ++ .../src/host/__tests__/modules.test.ts | 14 +- packages/agent-host/src/host/modules.ts | 3 +- packages/agent-host/src/sdk/tools.ts | 10 +- 18 files changed, 3191 insertions(+), 6 deletions(-) create mode 100644 packages/agent-host/src/drivers/pi/__tests__/fakePi.ts create mode 100644 packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts create mode 100644 packages/agent-host/src/drivers/pi/__tests__/piExtension.test.ts create mode 100644 packages/agent-host/src/drivers/pi/__tests__/piFakeModel.test.ts create mode 100644 packages/agent-host/src/drivers/pi/__tests__/piRpc.test.ts create mode 100644 packages/agent-host/src/drivers/pi/__tests__/piTools.test.ts create mode 100644 packages/agent-host/src/drivers/pi/driver.ts create mode 100644 packages/agent-host/src/drivers/pi/env.ts create mode 100644 packages/agent-host/src/drivers/pi/extension.ts create mode 100644 packages/agent-host/src/drivers/pi/install.ts create mode 100644 packages/agent-host/src/drivers/pi/module.ts create mode 100644 packages/agent-host/src/drivers/pi/rpc.ts create mode 100644 packages/agent-host/src/drivers/pi/runtime.ts create mode 100644 packages/agent-host/src/drivers/pi/style.ts create mode 100644 packages/agent-host/src/drivers/pi/tools.ts diff --git a/packages/agent-host/src/drivers/pi/__tests__/fakePi.ts b/packages/agent-host/src/drivers/pi/__tests__/fakePi.ts new file mode 100644 index 00000000..5d8ccd35 --- /dev/null +++ b/packages/agent-host/src/drivers/pi/__tests__/fakePi.ts @@ -0,0 +1,369 @@ +/** + * A scripted Pi RPC process for driver tests: the records of `pi --mode rpc` + * that this driver reads, with no SDK, no model and no network. + * + * Verified against Pi 1.5.2 by driving the real CLI over RPC, and it states + * only what was checked there: + * + * - a command is answered by `{type:"response", id, command, success, data}`; + * `get_state` carries `sessionId`, `sessionFile`, `model`, `thinkingLevel`; + * `prompt` answers `{disposition:"started"}` before any event; + * - a run is `agent_start`, `turn_start`, `message_start`/`message_end` + * (user), the assistant's `message_start`, `message_update` deltas, + * `message_end` with the authoritative content, `tool_execution_start` / + * `extension_ui_request` / `tool_execution_end`, `turn_end`, `agent_end` + * and finally `agent_settled {aborted}`; + * - the permission gate's dialog is an `extension_ui_request` with + * `method:"select"`, answered by `extension_ui_response` with `value` or + * `cancelled:true`; a blocked call ends with `isError:true` and the + * extension's reason as its result text; + * - `agent_settled` does not arrive while such a dialog is unanswered; + * - a failed request is an assistant `message_end` with `stopReason: + * "error"` and `errorMessage`, then `turn_end` and `agent_end`; next comes + * `auto_retry_start {attempt, maxAttempts, delayMs, errorMessage}` when Pi + * retries it, `auto_retry_end {success:false, finalError}` when it gives + * up, or `agent_settled` at once for an error it does not retry — and a + * recovered retry ends with `auto_retry_end {success:true}` after the + * reply's `message_end` (recorded with a server answering 429). + * + * The child is a plain EventEmitter with the stdio surface `PiRpc` uses, so a + * test can inject it through the driver's spawn seam. + */ +import { EventEmitter } from 'node:events'; + +interface FakeStdin extends EventEmitter { + destroyed: boolean; + write(chunk: string): boolean; + end(): void; +} + +export interface FakeChild extends EventEmitter { + stdout: EventEmitter; + stderr: EventEmitter; + stdin: FakeStdin; + pid: number; + kill(signal?: string): boolean; +} + +export interface FakePiOptions { + sessionId?: string; + sessionFile?: string; + model?: { provider: string; id: string; name?: string; contextWindow?: number }; + thinkingLevel?: string; + /** Exits before answering anything, as a missing `--session` does. */ + exitOnStart?: { code: number; stderr: string }; +} + +/** A tool call a `/tool` prompt scripts. */ +interface ScriptedCall { + id: string; + toolName: string; + args: Record; +} + +/** What the scripted 429 says, in Pi's own wording of one. */ +const RATE_LIMITED = `429: ${JSON.stringify({ + message: 'rate limited (scripted)', + type: 'rate_limit', + // As long as a gateway's: one router's 429 carried hundreds of characters + // of upstream detail in one line. + attempts: Array.from({ length: 6 }, (_, i) => ({ provider: `upstream-${i}`, status: 429, message: 'Upstream request failed.' })), +})}`; + +export class FakePi { + readonly child: FakeChild; + /** Every command the driver wrote, in order. */ + readonly commands: Array> = []; + /** Every `extension_ui_response` the driver wrote. */ + readonly uiResponses: Array> = []; + /** Dialogs answered by allow/deny, by their call id. */ + readonly answers = new Map(); + private readonly options: FakePiOptions; + private nextCall = 0; + private pendingDialog: { uiId: string; call: ScriptedCall } | undefined; + + constructor(options: FakePiOptions = {}) { + this.options = options; + const child = new EventEmitter() as FakeChild; + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + let ended = false; + // A real child emits `exit`, then `close` once its stdio is drained. + const exit = (code: number | null, signal: string | null): void => { + child.emit('exit', code, signal); + child.emit('close', code, signal); + }; + const stdin = Object.assign(new EventEmitter(), { + destroyed: false, + write: (chunk: string): boolean => { + this.read(chunk); + return true; + }, + end: (): void => { + if (ended) return; + ended = true; + setTimeout(() => exit(0, null), 0); + }, + }) as FakeStdin; + child.stdin = stdin; + child.pid = 4242; + child.kill = (): boolean => { + if (!ended) { + ended = true; + setTimeout(() => exit(null, 'SIGKILL'), 0); + } + return true; + }; + this.child = child; + if (options.exitOnStart) { + setTimeout(() => { + child.stderr.emit('data', Buffer.from(`${options.exitOnStart!.stderr}\n`)); + exit(options.exitOnStart!.code, null); + }, 5); + } + } + + /** Send one record to the driver, as Pi writes it on stdout. */ + emit(record: Record): void { + this.child.stdout.emit('data', Buffer.from(`${JSON.stringify(record)}\n`)); + } + + private respond(id: unknown, command: string, data?: unknown): void { + this.emit({ ...(typeof id === 'string' ? { id } : {}), type: 'response', command, success: true, ...(data !== undefined ? { data } : {}) }); + } + + private read(chunk: string): void { + for (const line of chunk.split('\n')) { + if (line.trim() === '') continue; + let command: Record; + try { + command = JSON.parse(line) as Record; + } catch { + continue; + } + this.commands.push(command); + this.handle(command); + } + } + + private handle(command: Record): void { + // A missing conversation exits before Pi's RPC starts: it reads no + // command at all. + if (this.options.exitOnStart) return; + const id = command.id; + switch (command.type) { + case 'get_state': + this.respond(id, 'get_state', { + model: this.options.model + ? { + id: this.options.model.id, + name: this.options.model.name ?? this.options.model.id, + provider: this.options.model.provider, + contextWindow: this.options.model.contextWindow ?? 200_000, + } + : undefined, + thinkingLevel: this.options.thinkingLevel ?? 'medium', + isStreaming: false, + sessionFile: this.options.sessionFile ?? '/pi/sessions/x.jsonl', + sessionId: this.options.sessionId ?? 'pi-session-1', + messageCount: 0, + }); + return; + case 'get_available_models': + this.respond(id, 'get_available_models', { + models: this.options.model + ? [{ id: this.options.model.id, name: this.options.model.name ?? this.options.model.id, provider: this.options.model.provider }] + : [], + }); + return; + case 'get_available_thinking_levels': + this.respond(id, 'get_available_thinking_levels', { levels: ['off', 'minimal', 'low', 'medium', 'high'] }); + return; + case 'get_commands': + this.respond(id, 'get_commands', { commands: [{ name: 'fix-tests', description: 'Fix failing tests', source: 'prompt' }] }); + return; + case 'get_session_stats': + this.respond(id, 'get_session_stats', { contextUsage: { tokens: 4_259, contextWindow: 200_000, percent: 2 } }); + return; + case 'set_model': { + const provider = typeof command.provider === 'string' ? command.provider : this.options.model?.provider; + const modelId = typeof command.modelId === 'string' ? command.modelId : this.options.model?.id; + this.respond(id, 'set_model', { id: modelId, provider, name: modelId }); + return; + } + case 'set_thinking_level': + this.respond(id, 'set_thinking_level'); + return; + case 'abort': + this.respond(id, 'abort'); + this.settle(true); + return; + case 'prompt': + this.respond(id, 'prompt', { disposition: 'started' }); + setTimeout(() => this.run(String(command.message ?? '')), 0); + return; + case 'steer': + this.respond(id, 'steer', { disposition: 'queued' }); + return; + case 'extension_ui_response': + this.uiResponses.push(command); + this.dialogAnswer(command); + return; + default: + this.respond(id, String(command.type ?? 'unknown'), {}); + return; + } + } + + private run(text: string): void { + if (text === '/tool') { + this.runTool({ id: `call_${++this.nextCall}`, toolName: 'bash', args: { command: 'echo codedeck > file.txt' } }); + return; + } + if (text === '/read') { + this.runTool({ id: `call_${++this.nextCall}`, toolName: 'read', args: { path: 'a.txt' } }); + return; + } + if (text === '/retry') { + // Two failed attempts, then the reply. + this.failedAttempt(1); + this.failedAttempt(2); + this.say('recovered', { retried: 2 }); + return; + } + if (text === '/give-up') { + this.failedAttempt(1); + this.failedAttempt(2); + this.failedAttempt(3); + this.attemptError(); + this.emit({ type: 'turn_end', message: {}, toolResults: [] }); + this.emit({ type: 'agent_end', messages: [] }); + this.emit({ type: 'auto_retry_end', success: false, attempt: 3, finalError: RATE_LIMITED }); + this.emit({ type: 'agent_settled', aborted: false }); + return; + } + if (text === '/retry-wait') { + // One failed attempt, then Pi waits before the retry (until aborted). + this.failedAttempt(1); + return; + } + if (text === '/bad-request') { + // An error Pi does not retry: settled at once. + this.emit({ type: 'agent_start' }); + this.attemptError('400: invalid request'); + this.settle(false); + return; + } + this.say(`echo: ${text}`); + } + + /** One failed request that Pi then retries. */ + private failedAttempt(attempt: number): void { + if (attempt === 1) this.emit({ type: 'agent_start' }); + this.attemptError(); + this.emit({ type: 'turn_end', message: {}, toolResults: [] }); + this.emit({ type: 'agent_end', messages: [] }); + // Pi retries up to three times, each retry announced before it starts. + this.emit({ type: 'auto_retry_start', attempt, maxAttempts: 3, delayMs: 2000 * attempt, errorMessage: RATE_LIMITED }); + this.emit({ type: 'agent_start' }); + } + + private attemptError(errorMessage = RATE_LIMITED): void { + const message = { role: 'assistant', timestamp: Date.now(), content: [], stopReason: 'error', errorMessage }; + this.emit({ type: 'message_start', message }); + this.emit({ type: 'message_end', message }); + } + + private runTool(call: ScriptedCall): void { + this.emit({ type: 'agent_start' }); + this.emit({ type: 'turn_start' }); + this.emit({ type: 'message_start', message: { role: 'user', content: [{ type: 'text', text: call.toolName }] } }); + this.emit({ type: 'message_end', message: { role: 'user', content: [{ type: 'text', text: call.toolName }] } }); + const assistant = { + role: 'assistant', + timestamp: Date.now(), + content: [{ type: 'toolCall', id: call.id, name: call.toolName, arguments: call.args }], + stopReason: 'toolUse', + }; + this.emit({ type: 'message_start', message: { ...assistant, content: [], stopReason: 'pending' } }); + this.emit({ type: 'message_end', message: assistant }); + this.emit({ type: 'tool_execution_start', toolCallId: call.id, toolName: call.toolName, args: call.args }); + const uiId = `ui-${call.id}`; + this.pendingDialog = { uiId, call }; + this.emit({ + type: 'extension_ui_request', + id: uiId, + method: 'select', + title: `codedeck-permission:${call.id}`, + options: ['allow', 'deny'], + }); + } + + private dialogAnswer(response: Record): void { + const pending = this.pendingDialog; + if (!pending || response.id !== pending.uiId) return; + this.pendingDialog = undefined; + const value = typeof response.value === 'string' ? response.value : response.cancelled === true ? 'deny' : 'deny'; + this.answers.set(pending.call.id, value); + if (value === 'allow') { + this.emit({ + type: 'tool_execution_end', + toolCallId: pending.call.id, + toolName: pending.call.toolName, + result: { content: [{ type: 'text', text: 'ran it' }] }, + isError: false, + durationMs: 1, + }); + this.say('tool-finished'); + return; + } + this.emit({ + type: 'tool_execution_end', + toolCallId: pending.call.id, + toolName: pending.call.toolName, + result: { content: [{ type: 'text', text: 'Denied by the user' }] }, + isError: true, + }); + this.say('tool-finished: Denied by the user'); + } + + /** One assistant reply, streamed and then completed, followed by the end of + * the run. */ + private say(text: string, options: { retried?: number } = {}): void { + const timestamp = Date.now(); + this.emit({ + type: 'message_start', + message: { + role: 'assistant', + timestamp, + content: [], + stopReason: 'pending', + provider: this.options.model?.provider, + model: this.options.model?.id, + }, + }); + this.emit({ type: 'message_update', assistantMessageEvent: { type: 'text_start', contentIndex: 0 } }); + this.emit({ type: 'message_update', assistantMessageEvent: { type: 'text_delta', contentIndex: 0, delta: text } }); + this.emit({ type: 'message_update', assistantMessageEvent: { type: 'text_end', contentIndex: 0, content: text } }); + this.emit({ + type: 'message_end', + message: { + role: 'assistant', + timestamp, + content: [{ type: 'text', text }], + stopReason: 'stop', + provider: this.options.model?.provider, + model: this.options.model?.id, + }, + }); + if (options.retried !== undefined) this.emit({ type: 'auto_retry_end', success: true, attempt: options.retried }); + this.settle(false); + } + + private settle(aborted: boolean): void { + this.emit({ type: 'turn_start' }); + this.emit({ type: 'turn_end', message: {}, toolResults: [] }); + this.emit({ type: 'agent_end', messages: [] }); + this.emit({ type: 'agent_settled', aborted }); + } +} diff --git a/packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts b/packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts new file mode 100644 index 00000000..3b068479 --- /dev/null +++ b/packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts @@ -0,0 +1,453 @@ +/** + * The Pi driver over a scripted RPC process (fakePi.ts): the session + * lifecycle, the permission policy, dialogs, interruption and resume. + */ +import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import * as path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { recordingContext, type RecordingContext } from '../../../sdk/__tests__/context'; +import type { DriverSession } from '../../../sdk/driver'; +import type { SelectOutcome, StartSession } from '../../../sdk/types'; +import { PiDriver } from '../driver'; +import { PI_PERMISSION_PREFIX } from '../extension'; +import { PiRuntime } from '../runtime'; +import { PI_READ_ONLY_TOOLS } from '../tools'; +import { FakePi, type FakePiOptions } from './fakePi'; + +interface Harness { + driver: PiDriver; + fake: FakePi; + home: string; + spawns: Array<{ command: string; args: string[]; env: Record; cwd: string }>; + logs: string[]; + session?: DriverSession; +} + +function withDriver(options: { fake?: FakePiOptions } = {}): Harness { + const root = mkdtempSync(path.join(tmpdir(), 'codedeck-pi-')); + const home = path.join(root, 'home'); + const cli = path.join(root, 'pi.js'); + writeFileSync(cli, '// a scripted Pi: the spawn seam answers instead\n'); + const fake = new FakePi({ model: { provider: 'anthropic', id: 'claude-sonnet-5', name: 'Claude Sonnet 5' }, ...options.fake }); + const spawns: Harness['spawns'] = []; + const logs: string[] = []; + const runtime = new PiRuntime({ + piPath: cli, + cacheDir: path.join(root, 'agents'), + installPi: async () => cli, + log: (line) => logs.push(line), + }); + const driver = new PiDriver({ + runtime, + home, + baseEnv: {}, + spawnFn: ((command: string, args: string[], opts: { env: Record; cwd: string }) => { + spawns.push({ command, args, env: opts.env, cwd: opts.cwd }); + return fake.child; + }) as never, + log: (line) => logs.push(line), + }); + return { driver, fake, home, spawns, logs }; +} + +function start(h: Harness, overrides: Partial = {}, ctx: RecordingContext = recordingContext()): RecordingContext { + h.session = h.driver.startSession({ sessionId: 'b1', agent: 'pi', cwd: '/work', ...overrides }, ctx); + return ctx; +} + +async function ready(h: Harness, overrides: Partial = {}, ctx: RecordingContext = recordingContext()): Promise { + start(h, overrides, ctx); + await ctx.waitFor((event) => event.type === 'ready'); + return ctx; +} + +async function turn(session: DriverSession, ctx: RecordingContext, text: string): Promise { + // The event's own position, not just its shape: an earlier turn's idle is + // already in the recording and would otherwise end this wait at once. + const start = ctx.events.length; + const idle = ctx.waitFor( + (event) => ctx.events.indexOf(event) >= start && event.type === 'turn' && event.state === 'idle', + ); + session.prompt(text); + await idle; +} + +const entries = (ctx: RecordingContext) => ctx.entries(); + +describe('PiDriver.info', () => { + it('advertises the modes, efforts and capabilities the RPC surface has', () => { + const { driver } = withDriver(); + const info = driver.info(); + expect(info.id).toBe('pi'); + expect(info.displayName).toBe('Pi'); + expect(info.modes?.map((mode) => mode.id)).toEqual(['ask', 'yolo']); + expect(info.efforts?.map((effort) => effort.id)).toEqual(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']); + expect(info.defaultMode).toBe('ask'); + expect(info.defaultEffort).toBe('medium'); + expect(info.supports).toEqual({ + models: true, + usage: false, + providers: true, + interrupt: true, + commands: true, + plugins: false, + mcp: false, + tasks: false, + }); + // Pi's own auth in its home applies; there is no CodeDeck credential. + expect(info.credentials).toEqual([]); + }); + + it('lists the read-only tools Pi runs without a card', () => { + expect([...PI_READ_ONLY_TOOLS].sort()).toEqual(['find', 'grep', 'ls', 'read']); + }); +}); + +describe('PiSession startup', () => { + it('spawns the pinned CLI in RPC mode with the session home and the extension', async () => { + const h = withDriver(); + const ctx = await ready(h, { model: 'claude-sonnet-5' }); + + expect(h.spawns).toHaveLength(1); + const spawn = h.spawns[0]!; + expect(spawn.command).toMatch(/node/i); + // The CLI's path is the first argument (the process is the host's node). + expect(spawn.args.slice(1, 4)).toEqual(['--mode', 'rpc', '--offline']); + const extension = spawn.args[spawn.args.indexOf('-e') + 1]!; + expect(extension.endsWith(path.join('codedeck', 'codedeck-pi.js'))).toBe(true); + expect(spawn.args).toContain('--model'); + expect(spawn.args[spawn.args.indexOf('--model') + 1]).toBe('claude-sonnet-5'); + expect(spawn.env.PI_CODING_AGENT_DIR).toBe(h.home); + expect(spawn.env.PI_SKIP_VERSION_CHECK).toBe('1'); + expect(spawn.env.PI_TELEMETRY).toBe('0'); + expect(spawn.cwd).toBe('/work'); + + expect(ctx.events).toContainEqual( + expect.objectContaining({ type: 'info', nativeSessionId: 'pi-session-1', model: 'Claude Sonnet 5', mode: 'ask' }), + ); + }); + + it('resumes by passing --session with the Pi conversation id', async () => { + const h = withDriver(); + await ready(h, { resume: 'pi-session-1' }); + const args = h.spawns[0]!.args; + expect(args[args.indexOf('--session') + 1]).toBe('pi-session-1'); + }); + + it('reports a resume Pi cannot find as resumeLost, with Pi’s own line', async () => { + const h = withDriver({ + fake: { exitOnStart: { code: 1, stderr: "No session found matching 'gone'" } }, + }); + const ctx = start(h, { resume: 'gone' }); + const ended = await ctx.ended(); + expect(ended).toMatchObject({ resumeLost: true, error: expect.stringContaining('No session found') }); + }); + + it('keeps a resumed conversation when Pi fails to start for any other reason', async () => { + // resumeLost makes the bridge forget the conversation and start afresh: + // a crash or a bad flag must not cost the user their history. + const h = withDriver({ fake: { exitOnStart: { code: 1, stderr: 'Error: unknown option --bogus' } } }); + const ctx = start(h, { resume: 'pi-session-1' }); + const ended = await ctx.ended(); + expect(ended).toMatchObject({ error: expect.stringContaining('unknown option') }); + expect(ended).not.toHaveProperty('resumeLost'); + }); + + it('keeps a resumed conversation when the runtime cannot be installed', async () => { + const h = withDriver(); + const failing = new PiDriver({ + runtime: new PiRuntime({ + cacheDir: path.join(h.home, 'agents'), + installPi: async () => { + throw new Error('registry unreachable'); + }, + log: () => {}, + }), + home: h.home, + baseEnv: {}, + log: () => {}, + }); + const ctx = recordingContext(); + failing.startSession({ sessionId: 'b1', agent: 'pi', cwd: '/work', resume: 'pi-session-1' }, ctx); + const ended = await ctx.ended(); + expect(ended).toMatchObject({ error: expect.stringContaining('registry unreachable') }); + expect(ended).not.toHaveProperty('resumeLost'); + }); + + it('binds a provider profile through the environment, token kept out of the profile JSON', async () => { + const h = withDriver(); + await ready(h, { + model: 'fake-model-1', + provider: { + id: 'codedeck-fake', + label: 'Fake', + baseUrl: 'https://api.example.com', + authToken: 'sk-secret', + models: [{ id: 'fake-model-1', label: 'Fake model' }], + }, + }); + const spawn = h.spawns[0]!; + expect(spawn.args[spawn.args.indexOf('--model') + 1]).toBe('codedeck-fake/fake-model-1'); + const profile = JSON.parse(spawn.env.CODEDECK_PI_PROVIDER!) as Record; + expect(profile).toMatchObject({ id: 'codedeck-fake', label: 'Fake', baseUrl: 'https://api.example.com/v1' }); + expect(JSON.stringify(profile)).not.toContain('sk-secret'); + expect(spawn.env.CODEDECK_PI_PROVIDER_TOKEN).toBe('sk-secret'); + }); + + it('refuses a provider profile with an insecure endpoint before it starts', () => { + const h = withDriver(); + expect(() => + start(h, { + provider: { + id: 'insecure', + label: 'Insecure', + baseUrl: 'http://example.com', + authToken: 'sk', + models: [{ id: 'm' }], + }, + }), + ).toThrow(/insecure base URL/); + expect(h.spawns).toHaveLength(0); + }); +}); + +describe('PiSession turns', () => { + it('streams the reply and reports it as one agent text entry', async () => { + const h = withDriver(); + const ctx = await ready(h); + await turn(h.session!, ctx, 'hello'); + + expect(entries(ctx)).toContainEqual( + expect.objectContaining({ entryType: 'text', role: 'agent', text: 'echo: hello' }), + ); + expect(entries(ctx)).toContainEqual(expect.objectContaining({ entryType: 'turn_complete' })); + expect(ctx.events).toContainEqual({ type: 'turn', state: 'running' }); + expect(ctx.events).toContainEqual({ type: 'turn', state: 'idle' }); + expect(h.fake.commands.find((c) => c.type === 'prompt')).toMatchObject({ message: 'hello' }); + // The context meter Pi reports reaches the phone as session info. + await ctx.waitFor((event) => event.type === 'info' && event.contextPercentage !== undefined); + }); + + it('shows a request Pi retried and recovered as retries, not errors', async () => { + const h = withDriver(); + const ctx = await ready(h); + await turn(h.session!, ctx, '/retry'); + const shown = entries(ctx); + expect(shown.filter((entry) => entry.entryType === 'error')).toEqual([]); + expect(shown.filter((entry) => entry.entryType === 'status').map((entry) => entry.entryType === 'status' && entry.text)).toEqual([ + expect.stringMatching(/^Retrying in 2s \(1 of 3\): 429/), + expect.stringMatching(/^Retrying in 4s \(2 of 3\): 429/), + ]); + expect(shown).toContainEqual(expect.objectContaining({ entryType: 'text', role: 'agent', text: 'recovered' })); + }); + + it('shows one error when Pi gives up retrying', async () => { + const h = withDriver(); + const ctx = await ready(h); + await turn(h.session!, ctx, '/give-up'); + const errors = entries(ctx).filter((entry) => entry.entryType === 'error'); + expect(errors).toEqual([expect.objectContaining({ text: expect.stringContaining('rate limited (scripted)') })]); + }); + + it('keeps a retry line to the first line of a long provider error', async () => { + const h = withDriver(); + const ctx = await ready(h); + await turn(h.session!, ctx, '/retry'); + const lines = entries(ctx).flatMap((entry) => (entry.entryType === 'status' ? [entry.text] : [])); + expect(lines.length).toBeGreaterThan(0); + for (const line of lines) expect(line.length).toBeLessThan(170); + }); + + it('shows no error when the user stops a turn waiting to retry', async () => { + const h = withDriver(); + const ctx = await ready(h); + const idle = ctx.waitFor((event) => event.type === 'turn' && event.state === 'idle'); + h.session!.prompt('/retry-wait'); + await ctx.waitFor((event) => event.type === 'entries' && event.entries.some((entry) => entry.entryType === 'status')); + await h.session!.interrupt(); + await idle; + expect(entries(ctx).filter((entry) => entry.entryType === 'error')).toEqual([]); + }); + + it('shows an error Pi does not retry once the run settles', async () => { + const h = withDriver(); + const ctx = await ready(h); + await turn(h.session!, ctx, '/bad-request'); + expect(entries(ctx).filter((entry) => entry.entryType === 'error')).toEqual([ + expect.objectContaining({ text: '400: invalid request' }), + ]); + }); + + it('steers a message sent while a turn runs', async () => { + const h = withDriver(); + const ctx = await ready(h); + // A turn is running once `prompt` started; the first settled event ends + // it, so the steer is written before that. + h.session!.prompt('hello'); + h.session!.prompt('change of plan'); + await ctx.waitFor((event) => event.type === 'turn' && event.state === 'idle'); + expect(h.fake.commands.find((c) => c.type === 'steer')).toMatchObject({ message: 'change of plan' }); + }); +}); + +describe('PiSession permission policy', () => { + it('asks in ask mode, and Deny blocks the call with Pi’s reason', async () => { + const h = withDriver(); + const ctx = await ready(h); + await turn(h.session!, ctx, '/tool'); + + expect(ctx.permissions).toHaveLength(1); + expect(ctx.permissions[0]).toMatchObject({ toolName: 'bash', kind: 'execute', title: 'echo codedeck > file.txt' }); + expect(ctx.permissions[0]!.options.map((option) => option.id)).toEqual(['allow', 'allow_session', 'deny']); + expect(h.fake.uiResponses.at(-1)).toMatchObject({ value: 'deny' }); + expect(entries(ctx)).toContainEqual( + expect.objectContaining({ entryType: 'tool_result', isError: true, text: expect.stringContaining('Denied by the user') }), + ); + }); + + it('answers Allow and the tool runs', async () => { + const h = withDriver(); + const ctx = await ready(h, {}, recordingContext({ permission: () => ({ outcome: 'selected', optionId: 'allow' }) })); + await turn(h.session!, ctx, '/tool'); + + expect(h.fake.uiResponses.at(-1)).toMatchObject({ value: 'allow' }); + expect(entries(ctx)).toContainEqual(expect.objectContaining({ entryType: 'tool_call', toolName: 'bash', kind: 'execute' })); + expect(entries(ctx)).toContainEqual( + expect.objectContaining({ entryType: 'tool_result', text: 'ran it' }), + ); + }); + + it('answers everything in yolo mode without a card', async () => { + const h = withDriver(); + const ctx = await ready(h, { mode: 'yolo' }); + await turn(h.session!, ctx, '/tool'); + + expect(ctx.permissions).toHaveLength(0); + expect(h.fake.uiResponses.at(-1)).toMatchObject({ value: 'allow' }); + }); + + it('lets Pi’s read-only tools run without a card in ask mode', async () => { + const h = withDriver(); + const ctx = await ready(h); + await turn(h.session!, ctx, '/read'); + + expect(ctx.permissions).toHaveLength(0); + expect(h.fake.uiResponses.at(-1)).toMatchObject({ value: 'allow' }); + expect(entries(ctx)).toContainEqual(expect.objectContaining({ entryType: 'tool_call', toolName: 'read', kind: 'read' })); + }); + + it('remembers “allow for this session” for that tool only', async () => { + const h = withDriver(); + const ctx = await ready( + h, + {}, + recordingContext({ permission: () => ({ outcome: 'selected', optionId: 'allow_session' }) }), + ); + await turn(h.session!, ctx, '/tool'); + await turn(h.session!, ctx, '/tool'); + + expect(ctx.permissions).toHaveLength(1); + expect(h.fake.uiResponses.filter((response) => response.value === 'allow')).toHaveLength(2); + }); + + it('answers a dialog cancelled when the turn is interrupted, so Pi settles', async () => { + let release!: (outcome: SelectOutcome) => void; + const h = withDriver(); + const ctx = await ready(h, {}, recordingContext({ permission: () => new Promise((resolve) => (release = resolve)) })); + + h.session!.prompt('/tool'); + await ctx.waitFor((event) => event.type === 'entries' && event.entries.some((entry) => entry.entryType === 'tool_call')); + await h.session!.interrupt(); + release({ outcome: 'cancelled', reason: 'interrupted' }); + await ctx.waitFor((event) => event.type === 'turn' && event.state === 'idle'); + + expect(h.fake.uiResponses.at(-1)).toMatchObject({ cancelled: true }); + expect(h.fake.commands.some((command) => command.type === 'abort')).toBe(true); + }); +}); + +describe('PiSession commands and options', () => { + it('lists the commands Pi reports', async () => { + const h = withDriver(); + await ready(h); + expect(await h.session!.listCommands!()).toEqual([{ name: 'fix-tests', description: 'Fix failing tests' }]); + }); + + it('applies a thinking level through Pi’s own command', async () => { + const h = withDriver(); + await ready(h); + await h.session!.setOption('effort', 'high'); + expect(h.fake.commands.find((command) => command.type === 'set_thinking_level')).toMatchObject({ level: 'high' }); + }); + + it('applies a thinking level chosen while Pi is still starting, once it is ready', async () => { + // The process starts asynchronously (the runtime is resolved first), so + // right after startSession there is no Pi to send the command to yet. + const h = withDriver(); + const ctx = start(h); + const applied = h.session!.setOption('effort', 'low'); + await ctx.waitFor((event) => event.type === 'ready'); + await applied; + expect(h.fake.commands.find((command) => command.type === 'set_thinking_level')).toMatchObject({ level: 'low' }); + }); + + it('refuses an option for a session that ended before Pi was ready', async () => { + const h = withDriver(); + start(h); + const applied = h.session!.setOption('effort', 'low'); + await h.session!.end(); + await expect(applied).rejects.toThrow(/ended/); + }); + + it('switches models through set_model, naming the profile for a bound session', async () => { + const h = withDriver(); + await ready(h, { + provider: { + id: 'codedeck-fake', + label: 'Fake', + baseUrl: 'https://api.example.com/v1', + authToken: 'sk', + models: [{ id: 'fake-model-1' }], + }, + }); + await h.session!.setOption('model', 'fake-model-1'); + expect(h.fake.commands.find((command) => command.type === 'set_model')).toMatchObject({ + provider: 'codedeck-fake', + modelId: 'fake-model-1', + }); + }); + + it('refuses a mode or effort Pi does not have', async () => { + const h = withDriver(); + await ready(h); + await expect(h.session!.setOption('mode', 'plan')).rejects.toThrow(/no mode 'plan'/); + await expect(h.session!.setOption('effort', 'turbo')).rejects.toThrow(/no thinking level 'turbo'/); + }); +}); + +describe('PiDriver models and conversations', () => { + it('lists the model catalog of a probe process, with unique ids', async () => { + const h = withDriver(); + const listed = await h.driver.listModels(); + expect(listed.models).toEqual([ + { id: 'anthropic/claude-sonnet-5', label: 'Claude Sonnet 5', provider: 'anthropic' }, + ]); + expect(listed.defaultModel).toBe('anthropic/claude-sonnet-5'); + }); + + it('deletes the session file Pi filed under its project directory', async () => { + const h = withDriver(); + const project = path.join(h.home, 'sessions', '--work--'); + mkdirSync(project, { recursive: true }); + const file = path.join(project, '2026-01-01T00-00-00-000Z_abc.jsonl'); + writeFileSync(file, '{}\n'); + await h.driver.deleteConversation('abc', '/work'); + expect(existsSync(file)).toBe(false); + }); + + it('refuses to delete a path that is not a session id', async () => { + const h = withDriver(); + await expect(h.driver.deleteConversation('../state', '/work')).rejects.toThrow(/not a Pi session id/); + }); +}); diff --git a/packages/agent-host/src/drivers/pi/__tests__/piExtension.test.ts b/packages/agent-host/src/drivers/pi/__tests__/piExtension.test.ts new file mode 100644 index 00000000..eb92ad80 --- /dev/null +++ b/packages/agent-host/src/drivers/pi/__tests__/piExtension.test.ts @@ -0,0 +1,146 @@ +/** + * The extension CodeDeck writes into Pi's process: it must be a standalone + * module (Pi serialises the function and runs it where nothing this host + * defines exists), it must gate every tool call, and it must register a + * provider profile with the token read from the environment. + */ +import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import * as path from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; +import { codedeckPiExtensionSource, installPiExtension, PI_PERMISSION_PREFIX, piExtensionPath } from '../extension'; + +const read = (file: string): string => readFileSync(file, 'utf8'); + +describe('the generated extension source', () => { + it('is one standalone module, with no import and no reference to this host', () => { + const source = codedeckPiExtensionSource(); + expect(source).toMatch(/^export default function/m); + expect(source).not.toMatch(/^\s*import\s/m); + expect(source).not.toMatch(/\brequire\(/); + // The literal, not the constant: the constant does not exist inside Pi. + expect(source).toContain(PI_PERMISSION_PREFIX); + expect(source).not.toContain('PI_PERMISSION_PREFIX'); + }); + + it('reads the profile token from the environment by name', () => { + expect(codedeckPiExtensionSource()).toContain('$CODEDECK_PI_PROVIDER_TOKEN'); + }); +}); + +describe('installPiExtension', () => { + it('writes the file under the state root, and only rewrites a changed one', () => { + const home = mkdtempSync(path.join(tmpdir(), 'codedeck-pi-ext-')); + const file = installPiExtension(home); + expect(file).toBe(piExtensionPath(home)); + expect(read(file)).toBe(codedeckPiExtensionSource()); + // A rewrite would change nothing; the driver must not touch it then. + writeFileSync(file, codedeckPiExtensionSource()); + const before = read(file); + expect(installPiExtension(home)).toBe(file); + expect(read(file)).toBe(before); + }); +}); + +describe('the extension as Pi loads it', () => { + const env = process.env; + afterEach(() => { + process.env = env; + }); + + /** The serialised function, evaluated the way a JavaScript engine reads + * the module Pi is handed: the source is `export default `, so + * it becomes the body of a function that returns that function. This also + * proves the text needs nothing else — an identifier from this host would + * throw here. */ + async function evaluate(): Promise<(pi: Record) => void> { + const source = codedeckPiExtensionSource().replace(/^export default /m, 'return '); + // eslint-disable-next-line no-new-func + return new Function(source)() as (pi: Record) => void; + } + + function api(): { + calls: { + provider?: { id: string; config: Record }; + toolCall?: (event: unknown, ctx: unknown) => Promise; + }; + pi: Record; + } { + const calls: { + provider?: { id: string; config: Record }; + toolCall?: (event: unknown, ctx: unknown) => Promise; + } = {}; + const pi = { + registerProvider: (id: string, config: Record) => { + calls.provider = { id, config }; + }, + on: (_event: string, handler: (event: unknown, ctx: unknown) => Promise) => { + calls.toolCall = handler; + }, + }; + return { calls, pi }; + } + + it('registers a bound profile at the endpoint the driver resolved, with the token reference', async () => { + process.env = { + ...env, + CODEDECK_PI_PROVIDER: JSON.stringify({ + id: 'codedeck-fake', + label: 'Fake', + baseUrl: 'https://api.example.com/v1', + models: [{ id: 'fake-model-1', label: 'Fake model', contextWindow: 64_000 }], + }), + CODEDECK_PI_PROVIDER_TOKEN: 'sk-value', + }; + const { calls, pi } = api(); + (await evaluate())(pi); + expect(calls.provider?.id).toBe('codedeck-fake'); + expect(calls.provider?.config).toMatchObject({ + name: 'Fake', + baseUrl: 'https://api.example.com/v1', + api: 'openai-completions', + apiKey: '$CODEDECK_PI_PROVIDER_TOKEN', + models: [expect.objectContaining({ id: 'fake-model-1', contextWindow: 64_000 })], + }); + }); + + it('registers nothing without a profile, and a malformed one does not throw', async () => { + process.env = { ...env }; + delete process.env.CODEDECK_PI_PROVIDER; + const first = api(); + (await evaluate())(first.pi); + expect(first.calls.provider).toBeUndefined(); + + process.env.CODEDECK_PI_PROVIDER = '{ not json'; + const second = api(); + const extension = await evaluate(); + expect(() => extension(second.pi)).not.toThrow(); + expect(second.calls.provider).toBeUndefined(); + }); + + it('holds a tool call until the dialog answers, and blocks anything but allow', async () => { + process.env = { ...env }; + delete process.env.CODEDECK_PI_PROVIDER; + const { calls, pi } = api(); + (await evaluate())(pi); + const handler = calls.toolCall!; + + let asked: { title: string; options: string[] } | undefined; + const ctx = { + ui: { + select: (title: string, options: string[]) => { + asked = { title, options }; + return Promise.resolve('deny'); + }, + }, + }; + await expect(handler({ toolCallId: 'call_1', toolName: 'bash', input: {} }, ctx)).resolves.toEqual({ + block: true, + reason: 'Denied by the user', + }); + expect(asked).toEqual({ title: `${PI_PERMISSION_PREFIX}call_1`, options: ['allow', 'deny'] }); + + const allowing = { ui: { select: () => Promise.resolve('allow') } }; + await expect(handler({ toolCallId: 'call_2', toolName: 'bash', input: {} }, allowing)).resolves.toBeUndefined(); + }); +}); diff --git a/packages/agent-host/src/drivers/pi/__tests__/piFakeModel.test.ts b/packages/agent-host/src/drivers/pi/__tests__/piFakeModel.test.ts new file mode 100644 index 00000000..c8908c71 --- /dev/null +++ b/packages/agent-host/src/drivers/pi/__tests__/piFakeModel.test.ts @@ -0,0 +1,194 @@ +/** + * The real Pi CLI against the local model server (tools/fake-model.mjs) — + * one session, its provider profile bound the way the bridge binds one, and + * the permission gate exercised both ways. + * + * What this covers that the scripted RPC tests cannot: Pi's own startup with + * the extension CodeDeck writes, the provider registration reaching Pi's model + * selector, the tool call the fake model scripts, and the hold-and-answer of + * Pi's extension UI dialog. Nothing leaves the machine and nothing is spent: + * the model server answers every request. + * + * The CLI is the package this build pins as a devDependency, so the test runs + * wherever the workspace is installed (CI included) and skips, saying so, + * where it is not. The model server runs as its own process, since a driver + * test may not import outside its folder. + * + * Timing: each test starts Pi and runs one turn, so the timeouts are generous + * on purpose — a slow runner must not read as a failure. + */ +import { spawn, type ChildProcess } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import * as path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { PiDriver } from '../driver'; +import { bundledPiExecutable } from '../install'; +import { PiRuntime } from '../runtime'; +import { recordingContext, type Handlers, type RecordingContext } from '../../../sdk/__tests__/context'; +import type { DriverSession } from '../../../sdk/driver'; +import type { StartSession } from '../../../sdk/types'; + +/** The local model server and the one model it answers as (both named here: + * this file may not import from outside its folder). */ +const MODEL_SERVER = fileURLToPath(new URL('../../../../tools/fake-model.mjs', import.meta.url)); +const FAKE_MODEL_ID = 'fake-model-1'; + +interface FakeModelServer { + url: string; + stop(): Promise; +} + +function startFakeModel(timeoutMs = 15_000): Promise { + const child = spawn(process.execPath, [MODEL_SERVER, '--port', '0'], { stdio: ['ignore', 'pipe', 'pipe'] }); + return new Promise((resolve, reject) => { + let output = ''; + const timer = setTimeout(() => { + void stopServer(child); + reject(new Error(`the fake model did not start: ${output}`)); + }, timeoutMs); + const onOutput = (chunk: Buffer) => { + output += chunk.toString(); + const match = /listening on (http:\/\/\S+)/.exec(output); + if (!match) return; + clearTimeout(timer); + resolve({ url: match[1]!, stop: () => stopServer(child) }); + }; + child.stdout.on('data', onOutput); + child.stderr.on('data', onOutput); + child.on('exit', (code) => { + clearTimeout(timer); + reject(new Error(`the fake model exited (${code}): ${output}`)); + }); + }); +} + +function stopServer(child: ChildProcess): Promise { + if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(); + return new Promise((resolve) => { + const kill = setTimeout(() => child.kill('SIGKILL'), 3_000); + child.once('exit', () => { + clearTimeout(kill); + resolve(); + }); + child.kill('SIGTERM'); + }); +} + +const piPath = bundledPiExecutable(); +if (!piPath) { + // Said once, at collection: a skip with no reason reads like a broken test. + console.warn('piFakeModel: no Pi CLI beside the workspace — skipping the live fake-model tests'); +} +const live = piPath ? describe : describe.skip; + +/** How long a turn may take: process start, extension load and one request to + * a loopback server. */ +const TURN_MS = 90_000; + +live('Pi against the fake model', () => { + let model: FakeModelServer | undefined; + let modelUrl = ''; + let home = ''; + let cwd = ''; + let session: DriverSession | undefined; + + beforeEach(async () => { + model = await startFakeModel(); + modelUrl = model.url; + home = await mkdtemp(path.join(tmpdir(), 'codedeck-pi-home-')); + cwd = await mkdtemp(path.join(tmpdir(), 'codedeck-pi-work-')); + }); + + afterEach(async () => { + await session?.end(); + session = undefined; + await model?.stop(); + model = undefined; + await rm(home, { recursive: true, force: true }); + await rm(cwd, { recursive: true, force: true }); + }); + + /** A session bound to the local server the way the bridge binds one to a + * provider profile. */ + function start(handlers: Handlers = {}, overrides: Partial = {}): RecordingContext { + const ctx = recordingContext(handlers); + const runtime = new PiRuntime({ + piPath: piPath!, + cacheDir: path.join(home, 'agents'), + installPi: async () => piPath!, + log: (line) => ctx.log(line), + }); + const driver = new PiDriver({ runtime, home, baseEnv: {}, log: (line) => ctx.log(line) }); + session = driver.startSession( + { + sessionId: `live-${Date.now()}`, + agent: 'pi', + cwd, + mode: 'ask', + model: FAKE_MODEL_ID, + provider: { + id: 'codedeck-fake', + label: 'Fake model', + baseUrl: modelUrl, + authToken: 'codedeck-fake-model', + models: [{ id: FAKE_MODEL_ID, label: 'Fake model' }], + defaultModel: FAKE_MODEL_ID, + }, + ...overrides, + }, + ctx, + ); + return ctx; + } + + async function turn(ctx: RecordingContext, text: string): Promise { + await ctx.waitFor((event) => event.type === 'ready', TURN_MS); + const start = ctx.events.length; + const idle = ctx.waitFor( + (event) => ctx.events.indexOf(event) >= start && event.type === 'turn' && event.state === 'idle', + TURN_MS, + ); + session!.prompt(text); + await idle; + } + + it( + 'raises the permission card for the tool call, and Deny blocks the write', + async () => { + const ctx = start({ permission: () => ({ outcome: 'selected', optionId: 'deny' }) }); + await turn(ctx, '/tool'); + + expect(ctx.permissions).toHaveLength(1); + expect(ctx.permissions[0]).toMatchObject({ toolName: 'bash', kind: 'execute' }); + expect(ctx.entries()).toContainEqual(expect.objectContaining({ entryType: 'tool_call', toolName: 'bash' })); + expect(ctx.entries()).toContainEqual( + expect.objectContaining({ entryType: 'tool_result', isError: true, text: expect.stringContaining('Denied by the user') }), + ); + expect(existsSync(path.join(cwd, 'codedeck-fake-model.txt'))).toBe(false); + }, + TURN_MS, + ); + + it( + 'lets Allow run the tool, and the answer that follows ends the turn', + async () => { + const ctx = start({ permission: () => ({ outcome: 'selected', optionId: 'allow' }) }); + await turn(ctx, '/tool'); + + expect(ctx.permissions).toHaveLength(1); + expect(existsSync(path.join(cwd, 'codedeck-fake-model.txt'))).toBe(true); + const results = ctx.entries().filter((entry) => entry.entryType === 'tool_result'); + expect(results).not.toHaveLength(0); + expect(results.every((entry) => entry.entryType !== 'tool_result' || entry.isError !== true)).toBe(true); + // The fake model answers the tool result with text, which is the last + // assistant turn the session shows. + expect(ctx.entries()).toContainEqual( + expect.objectContaining({ entryType: 'text', role: 'agent', text: expect.stringContaining('tool-finished') }), + ); + }, + TURN_MS, + ); +}); diff --git a/packages/agent-host/src/drivers/pi/__tests__/piRpc.test.ts b/packages/agent-host/src/drivers/pi/__tests__/piRpc.test.ts new file mode 100644 index 00000000..93d6e543 --- /dev/null +++ b/packages/agent-host/src/drivers/pi/__tests__/piRpc.test.ts @@ -0,0 +1,104 @@ +/** + * The RPC codec's two absolute rules: it is total (a line that does not read + * is reported and skipped, never thrown), and it splits on LF only — a + * U+2028 inside a JSON string is data, not a record boundary. + */ +import { describe, expect, it } from 'vitest'; +import { PiLineDecoder, PiRpc, type PiRecord } from '../rpc'; +import { FakePi } from './fakePi'; + +function decoder(): { records: PiRecord[]; bad: string[]; push: (chunk: Buffer | string) => void } { + const records: PiRecord[] = []; + const bad: string[] = []; + const line = new PiLineDecoder( + (record) => records.push(record), + (_text, reason) => bad.push(reason), + ); + return { records, bad, push: (chunk) => line.push(chunk) }; +} + +describe('PiLineDecoder', () => { + it('skips a line that is not JSON and keeps reading the next one', () => { + const d = decoder(); + d.push('not json\n{"type":"agent_start"}\n[1,2]\n{"type":"agent_settled","aborted":false}\n'); + expect(d.records.map((record) => record.type)).toEqual(['agent_start', 'agent_settled']); + expect(d.bad).toHaveLength(2); + }); + + it('keeps U+2028 and U+2029 inside a JSON string in one record', () => { + const text = 'line one
line two
line three'; + const d = decoder(); + d.push(`${JSON.stringify({ type: 'message_update', text })}\n`); + expect(d.records).toHaveLength(1); + expect(d.records[0]!.text).toBe(text); + }); + + it('accepts CRLF and an empty line', () => { + const d = decoder(); + d.push('{"type":"turn_start"}\r\n\r\n{"type":"turn_end"}\r\n'); + expect(d.records.map((record) => record.type)).toEqual(['turn_start', 'turn_end']); + expect(d.bad).toEqual([]); + }); + + it('joins a UTF-8 character split across two chunks', () => { + const bytes = Buffer.from('{"type":"message_update","text":"é"}\n'); + const cut = bytes.indexOf(Buffer.from('é')) + 1; + const d = decoder(); + d.push(bytes.subarray(0, cut)); + d.push(bytes.subarray(cut)); + expect(d.records).toHaveLength(1); + expect(d.records[0]!.text).toBe('é'); + }); +}); + +describe('PiRpc', () => { + it('correlates a response by id after a garbage line, and skips an unknown id', async () => { + const fake = new FakePi({ sessionId: 's-1' }); + const bad: string[] = []; + const rpc = new PiRpc({ + command: 'node', + args: [], + cwd: '/w', + env: {}, + onEvent: () => {}, + onUiRequest: () => {}, + onExit: () => {}, + onStderr: () => {}, + onBadLine: (_line, reason) => bad.push(reason), + spawnFn: (() => fake.child) as never, + }); + fake.child.stdout.emit('data', Buffer.from('garbage\n')); + const state = (await rpc.request('get_state')) as Record; + expect(state.sessionId).toBe('s-1'); + // A response to a command nobody waits for is logged, not thrown. + fake.emit({ id: 'nobody', type: 'response', command: 'get_state', success: true }); + expect(bad.some((reason) => reason.includes('unknown command'))).toBe(true); + await rpc.close(100); + }); + + it('closes a Pi that stopped reading its stdin, instead of waiting for a drain', async () => { + const fake = new FakePi(); + // A full pipe nobody reads: every write reports backpressure and no + // `drain` ever comes. + fake.child.stdin.write = () => false; + let exited = false; + const rpc = new PiRpc({ + command: 'node', + args: [], + cwd: '/w', + env: {}, + onEvent: () => {}, + onUiRequest: () => {}, + onExit: () => { + exited = true; + }, + onStderr: () => {}, + onBadLine: () => {}, + spawnFn: (() => fake.child) as never, + requestTimeoutMs: 50, + }); + await expect(rpc.request('get_state')).rejects.toThrow(/did not answer/); + await rpc.close(50); + expect(exited).toBe(true); + }); +}); diff --git a/packages/agent-host/src/drivers/pi/__tests__/piTools.test.ts b/packages/agent-host/src/drivers/pi/__tests__/piTools.test.ts new file mode 100644 index 00000000..8ec3e5b3 --- /dev/null +++ b/packages/agent-host/src/drivers/pi/__tests__/piTools.test.ts @@ -0,0 +1,69 @@ +/** + * Pi's built-in tool table, and — against the package this build pins — the + * names that package declares. + */ +import { existsSync, readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import * as path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { PI_READ_ONLY_TOOLS, PI_TOOLS, piTool } from '../tools'; + +describe('piTool', () => { + it('reads a shell call by its command', () => { + expect(piTool('bash', { command: 'npm test', timeout: 30 })).toEqual({ kind: 'execute', title: 'npm test' }); + expect(piTool('powershell', { command: 'Get-ChildItem' }).kind).toBe('execute'); + }); + + it('reads the file tools by their path', () => { + expect(piTool('read', { path: 'src/main.rs' })).toEqual({ kind: 'read', title: 'src/main.rs' }); + expect(piTool('write', { path: 'a.txt', content: 'x' })).toEqual({ kind: 'edit', title: 'a.txt' }); + // An edit's content travels as its diff, not as a second copy of the path. + expect(piTool('edit', { path: 'a.txt', edits: [{ oldText: 'a', newText: 'b' }] })).toEqual({ kind: 'edit', title: 'a.txt' }); + }); + + it('reads the search tools by their pattern', () => { + expect(piTool('grep', { pattern: 'TODO', path: 'src' })).toMatchObject({ kind: 'search', title: 'TODO' }); + expect(piTool('find', { pattern: '**/*.rs' })).toMatchObject({ kind: 'search', title: '**/*.rs' }); + }); + + it('reads ls as the directory it lists', () => { + expect(piTool('ls', { path: 'src' })).toEqual({ kind: 'read', title: 'src' }); + expect(piTool('ls', {})).toEqual({ kind: 'read', title: '.' }); + }); + + it('leaves a tool this table does not know to its own name and arguments', () => { + const reported: string[] = []; + expect(piTool('deploy', { target: 'prod' }, (name) => reported.push(name))).toEqual({ + kind: 'other', + title: 'deploy', + input: '{\n "target": "prod"\n}', + }); + expect(reported).toEqual(['deploy']); + }); + + it('keeps the read-only set to the four tools Pi itself treats as read-only', () => { + expect([...PI_READ_ONLY_TOOLS].sort()).toEqual(['find', 'grep', 'ls', 'read']); + }); +}); + +/** `dist/core/tools/index.js`, where the built-in names live, found by + * walking up from this file to the installed package (pnpm links it into + * the workspace's `node_modules`). */ +function toolsIndex(): string { + for (let dir = path.dirname(fileURLToPath(import.meta.url)); ; dir = path.dirname(dir)) { + const candidate = path.join(dir, 'node_modules', '@earendil-works', 'pi-coding-agent', 'dist', 'core', 'tools', 'index.js'); + if (existsSync(candidate)) return readFileSync(candidate, 'utf8'); + if (path.dirname(dir) === dir) throw new Error('@earendil-works/pi-coding-agent is not installed beside the workspace'); + } +} + +describe('the built-in tools the installed Pi declares', () => { + it('has a table entry for every name Pi declares, and no other', () => { + const match = /allToolNames\s*=\s*new Set\(\[([\s\S]*?)\]\)/.exec(toolsIndex()); + expect(match, 'the bundle still declares allToolNames').not.toBeNull(); + const declared = [...match![1]!.matchAll(/"([^"]+)"/g)].map((m) => m[1]!); + // A silent zero would make the comparison below pass for the wrong reason. + expect(declared.length).toBeGreaterThan(4); + expect([...declared].sort()).toEqual(Object.keys(PI_TOOLS).sort()); + }); +}); diff --git a/packages/agent-host/src/drivers/pi/driver.ts b/packages/agent-host/src/drivers/pi/driver.ts new file mode 100644 index 00000000..53f9adfb --- /dev/null +++ b/packages/agent-host/src/drivers/pi/driver.ts @@ -0,0 +1,993 @@ +/** + * The Pi driver, over its RPC mode (`pi --mode rpc`): JSONL commands on + * stdin, responses and session events on stdout, and an extension-UI + * sub-protocol for dialogs (rpc.ts). + * + * What Pi does not have is a permission system of its own. CodeDeck's + * extension (extension.ts) holds every `tool_call` until this driver answers, + * which is what turns Pi's tool calls into the phone's permission cards: the + * driver decides whether a card is needed — `yolo`, Pi's read-only tools, and + * a tool allowed for the session are answered at once — and the card is built + * from the `tool_execution_start` facts of that call. + * + * One Pi process serves exactly one CodeDeck session (runtime.ts). The session + * is Pi's own on disk: `get_state` reports its id and file, and a resume + * opens it again with `--session`. + * + * Deliberate limits, all of them this driver's for now: no plugins or MCP + * management (Pi reads its own configuration), no subscription usage (there + * is none to ask), no background-task control. Provider profiles are session + * bindings only; their models are not added to Pi's own catalog. + */ +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import type { Driver, DriverSession, SessionContext } from '../../sdk/driver'; +import type { ProviderHttp } from '../../sdk/net'; +import { OPENAI_API, checkToken, listModels } from '../../sdk/providerApi'; +import type { EndpointModel } from '../../sdk/providerModels'; +import { now, PERMISSION_ALLOW, PERMISSION_DENY, toolLocations, unknownToolReporter } from '../../sdk/tools'; +import { truncateToolResult } from '../../sdk/transcript'; +import { PartialCoalescer } from '../../sdk/partial'; +import type { + AgentInfo, + ModelEntry, + OptionChoice, + OutputEntry, + PermissionOption, + PermissionRequest, + ProviderBinding, + QuestionOutcome, + QuestionSpec, + SelectOutcome, + SessionOption, + SlashCommand, + StartSession, + UsageData, +} from '../../sdk/types'; +import { buildPiEnv } from './env'; +import { PI_PERMISSION_PREFIX, installPiExtension } from './extension'; +import { PI_LABEL } from './install'; +import { PiRpc, type PiRecord, type PiRpcOptions } from './rpc'; +import { PI_READ_ONLY_TOOLS, piTool } from './tools'; +import { PI_STYLE } from './style'; +import { PiRuntime, piCommand, type PiRuntimeOptions } from './runtime'; + +export const PI_AGENT_ID = 'pi'; + +const ASK_MODE = 'ask'; +const YOLO_MODE = 'yolo'; +const DEFAULT_MODE = ASK_MODE; +const PI_MODES = [ + { id: ASK_MODE, label: 'Ask', description: 'Ask before each tool call, except for read-only tools' }, + { id: YOLO_MODE, label: 'YOLO', description: 'Run every tool without asking' }, +]; + +/** Pi's thinking levels (`--thinking`, `set_thinking_level`). A model that + * does not support one clamps it, as Pi does in its own UI; the list is the + * vocabulary, not a promise that every model has every level. */ +const PI_EFFORTS: OptionChoice[] = [ + { id: 'off', label: 'Off', description: 'No reasoning.' }, + { id: 'minimal', label: 'Minimal', description: 'The shortest reasoning budget.' }, + { id: 'low', label: 'Low', description: 'A small reasoning budget.' }, + { id: 'medium', label: 'Medium', description: "Pi's default balance." }, + { id: 'high', label: 'High', description: 'For harder tasks.' }, + { id: 'xhigh', label: 'Extra high', description: 'Only models that support it.' }, + { id: 'max', label: 'Max', description: 'Only models that support it.' }, +]; +/** Pi's own default when neither the settings nor the session says. */ +const DEFAULT_EFFORT = 'medium'; + +/** The card's third choice: the tool is not asked about again in this + * session. Pi itself has no saved rules, so this lives in the session. */ +const ALLOW_SESSION: PermissionOption = { id: 'allow_session', label: 'Allow for this session', kind: 'allow_always' }; + +/** What Pi prints on stderr, before exiting with 1, when `--session` names a + * conversation it does not have (verified against 1.5.2: "No session found + * matching ''"). */ +const PI_SESSION_MISSING = /^No session found matching /; + +/** How long the model probe may take: it starts a Pi process and reads its + * declarative catalog, so no account or endpoint is involved. */ +const PROBE_TIMEOUT_MS = 30_000; + +function str(value: unknown): string | undefined { + return typeof value === 'string' && value !== '' ? value : undefined; +} + +function num(value: unknown): number | undefined { + return typeof value === 'number' && Number.isFinite(value) ? value : undefined; +} + +function recordOf(value: unknown): Record | undefined { + return typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Record) : undefined; +} + +/** The text blocks of a Pi tool result, joined as the phone shows them. */ +function resultText(result: unknown): string { + const content = recordOf(result)?.content; + if (!Array.isArray(content)) return ''; + return content + .flatMap((block) => { + const part = recordOf(block); + return part?.type === 'text' && typeof part.text === 'string' ? [part.text] : []; + }) + .join('\n'); +} + +/** The model a provider profile names, and the model id inside it. A + * bound session names its profile's model — with or without the profile's + * id before it — and the model id itself may contain a slash (a gateway's + * routing key), so the bound profile wins over splitting at the first + * slash. */ +function splitModel(model: string, boundProvider: string | undefined): { provider?: string; modelId: string } { + if (boundProvider !== undefined) { + const prefix = `${boundProvider}/`; + return { provider: boundProvider, modelId: model.startsWith(prefix) ? model.slice(prefix.length) : model }; + } + const slash = model.indexOf('/'); + if (slash > 0) return { provider: model.slice(0, slash), modelId: model.slice(slash + 1) }; + return { modelId: model }; +} + +/** What one Pi session is built with. */ +interface PiSessionDeps { + runtime: PiRuntime; + home: string; + baseEnv: NodeJS.ProcessEnv; + spawnFn?: PiRpcOptions['spawnFn']; + log: (message: string) => void; +} + +export class PiSession implements DriverSession { + private rpc: PiRpc | undefined; + private sessionMode: string; + private readonly allowedTools = new Set(); + private readonly toolFacts = new Map }>(); + /** Dialog requests Pi is waiting on, by id, so an interrupt or the + * session's end answers every one. */ + private readonly openUi = new Set(); + /** Dialogs an interrupt or the session's end already answered: their + * handlers must not send a second response. */ + private readonly cancelledUi = new Set(); + private readonly coalescer: PartialCoalescer; + private readonly reportUnknownTool: (toolName: string) => void; + + private ended = false; + private ready = false; + private running = false; + private nativeSessionId: string | undefined; + private sessionFile: string | undefined; + private contextWindow: number | undefined; + private contextPercentage: number | undefined; + private modelLabel: string | undefined; + private currentProvider: string | undefined; + private currentModelId: string | undefined; + /** The assistant message being streamed: its part key prefix and the + * content indexes that streamed under it. */ + private assistant: { key: string; parts: Map } | undefined; + private lastStderr = ''; + /** The last failed attempt's error, until Pi says whether it retries. */ + private heldError: string | undefined; + /** Pi said the conversation `--session` names does not exist. */ + private sessionMissing = false; + /** Prompts that arrived before the process was ready; flushed at `ready`. */ + private readonly queuedPrompts: string[] = []; + /** The child's environment. Built synchronously, so a provider profile that + * cannot be used refuses the session before it starts. */ + private readonly env: Record; + /** The running process once it accepts commands; rejected if the session + * ends first. An option changed while Pi starts waits on it, rather than + * being dropped as if it applied. */ + private readonly started: Promise; + private settleStarted!: { resolve(rpc: PiRpc): void; reject(error: Error): void }; + + constructor( + private readonly params: StartSession, + private readonly ctx: SessionContext, + private readonly deps: PiSessionDeps, + ) { + this.sessionMode = params.mode ?? DEFAULT_MODE; + this.started = new Promise((resolve, reject) => { + this.settleStarted = { resolve, reject }; + }); + // Nobody may be waiting when the session ends early. + this.started.catch(() => {}); + this.env = buildPiEnv(params, deps.home, deps.baseEnv); + this.reportUnknownTool = unknownToolReporter((message) => ctx.log(message)); + this.coalescer = new PartialCoalescer((update) => { + if (!this.ended) this.ctx.emit({ type: 'partial', ...update }); + }); + this.start(); + } + + // --- startup --- + + private start(): void { + void this.launch().catch((error: unknown) => { + this.fail(error instanceof Error ? error.message : String(error)); + }); + } + + private async launch(): Promise { + const entry = await this.deps.runtime.entryPoint(); + if (this.ended) return; + const extension = installPiExtension(this.deps.home); + const command = piCommand(entry, this.arguments(extension)); + this.rpc = new PiRpc({ + command: command.command, + args: command.args, + cwd: this.params.cwd, + env: this.env, + onEvent: (record) => this.event(record), + onUiRequest: (record) => this.uiRequest(record), + onExit: (code, signal) => this.exited(code, signal), + onStderr: (line) => { + this.lastStderr = line; + if (PI_SESSION_MISSING.test(line)) this.sessionMissing = true; + this.deps.log(`[pi] ${line}`); + }, + onBadLine: (line, reason) => { + this.deps.log(`[pi] dropped a line from Pi (${reason})${line ? `: ${line.slice(0, 200)}` : ''}`); + }, + ...(this.deps.spawnFn !== undefined ? { spawnFn: this.deps.spawnFn } : {}), + }); + + const state = recordOf(await this.rpc.request('get_state')); + if (this.ended) return; + this.nativeSessionId = str(state?.sessionId); + this.sessionFile = str(state?.sessionFile); + const model = recordOf(state?.model); + if (model) { + this.currentProvider = str(model.provider); + this.currentModelId = str(model.id); + this.modelLabel = str(model.name) ?? this.modelName(); + this.contextWindow = num(model.contextWindow); + } + this.ready = true; + this.ctx.emit({ + type: 'info', + ...(this.nativeSessionId ? { nativeSessionId: this.nativeSessionId } : {}), + ...(this.modelLabel ? { model: this.modelLabel } : {}), + mode: this.sessionMode, + ...(this.contextWindow !== undefined ? { contextWindow: this.contextWindow } : {}), + }); + this.ctx.emit({ type: 'ready' }); + this.settleStarted.resolve(this.rpc); + for (const text of this.queuedPrompts.splice(0)) this.prompt(text); + } + + private arguments(extension: string): string[] { + const args = ['--mode', 'rpc', '--offline', '-e', extension]; + if (this.params.resume) args.push('--session', this.params.resume); + const model = this.params.model?.trim(); + if (model) args.push('--model', this.modelArgument(model)); + const effort = this.params.effort?.trim(); + if (effort) args.push('--thinking', effort); + return args; + } + + /** The selector `--model` takes: a profile-bound session names its + * profile's model under the profile's id, so Pi resolves it even when the + * bridge sent only the model id. */ + private modelArgument(model: string): string { + const provider = this.params.provider?.id; + if (provider === undefined) return model; + return model.startsWith(`${provider}/`) ? model : `${provider}/${model}`; + } + + private modelName(): string | undefined { + if (this.currentProvider !== undefined && this.currentModelId !== undefined) { + return `${this.currentProvider}/${this.currentModelId}`; + } + return this.currentModelId; + } + + // --- process and turn state --- + + private exited(code: number | null, signal: NodeJS.Signals | null): void { + if (this.ended) return; + const why = this.lastStderr || `Pi exited (${code ?? signal ?? 'no code'})`; + this.ended = true; + this.settleStarted.reject(new Error(`the Pi session ended: ${why}`)); + this.coalescer.reset(); + this.openUi.clear(); + this.ctx.emit({ + type: 'ended', + error: this.ready ? why : `Pi could not start: ${why}`, + // Only Pi saying the conversation is not there makes it lost: the + // bridge then starts the session fresh and forgets the old id, which + // any other early exit (a crash, a bad flag) must not cost the user. + ...(this.params.resume && !this.ready && this.sessionMissing ? { resumeLost: true } : {}), + }); + } + + /** A failure before Pi ran (the runtime would not install, the process + * would not answer). The conversation, if any, is untouched on disk. */ + private fail(reason: string): void { + if (this.ended) return; + this.ended = true; + this.settleStarted.reject(new Error(`the Pi session ended: ${reason}`)); + this.coalescer.reset(); + this.ctx.emit({ type: 'ended', error: reason }); + } + + private emit(entries: OutputEntry[]): void { + if (!this.ended && entries.length > 0) this.ctx.emit({ type: 'entries', entries }); + } + + /** One session event from Pi. Everything Pi reports after `agent_settled` + * that adds nothing to the phone's transcript — queue state, retry + * progress, compaction bookkeeping — is left out. */ + private event(record: PiRecord): void { + if (this.ended) return; + switch (record.type) { + case 'agent_settled': + this.settled(record.aborted === true); + return; + case 'message_start': + this.messageStart(record.message); + return; + case 'message_update': + this.messageUpdate(record); + return; + case 'message_end': + this.messageEnd(record.message); + return; + case 'tool_execution_start': + this.toolStart(record); + return; + case 'tool_execution_end': + this.toolEnd(record); + return; + case 'auto_retry_start': + this.retrying(record); + return; + case 'auto_retry_end': + if (record.success === false) { + // Pi gave up: its final error is the turn's, said once. + this.heldError = undefined; + this.emit([{ entryType: 'error', text: str(record.finalError) ?? 'Pi gave up after retrying', timestamp: now() }]); + } + return; + case 'extension_error': + this.deps.log(`[pi] an extension failed: ${String(record.error ?? record.event ?? 'unknown')}`); + return; + default: + return; + } + } + + private messageStart(message: unknown): void { + const msg = recordOf(message); + if (msg?.role !== 'assistant') { + this.assistant = undefined; + return; + } + this.assistant = { key: String(num(msg.timestamp) ?? Date.now()), parts: new Map() }; + } + + private messageUpdate(record: PiRecord): void { + const update = recordOf(record.assistantMessageEvent); + if (!update || !this.assistant) return; + const index = num(update.contentIndex) ?? 0; + const delta = str(update.delta); + if (delta === undefined) return; + if (update.type === 'text_delta') { + this.assistant.parts.set(index, 'text'); + this.coalescer.delta({ key: `${this.assistant.key}:${index}`, entryType: 'text', text: delta }); + } else if (update.type === 'thinking_delta') { + this.assistant.parts.set(index, 'thinking'); + this.coalescer.delta({ key: `${this.assistant.key}:${index}`, entryType: 'thinking', text: delta }); + } + } + + private messageEnd(message: unknown): void { + const msg = recordOf(message); + if (msg?.role !== 'assistant') return; + const assistant = this.assistant; + this.assistant = undefined; + const entries: OutputEntry[] = []; + const timestamp = now(); + + const errorMessage = str(msg.errorMessage); + const aborted = msg.stopReason === 'aborted'; + if (msg.stopReason === 'error' || (errorMessage !== undefined && !aborted)) { + // Whatever streamed is dropped: the error replaces it. It is held, not + // shown: Pi may retry the request (`auto_retry_start` follows), and a + // failed attempt that a later one recovers from is not the turn's error. + for (const index of assistant?.parts.keys() ?? []) this.coalescer.complete(`${assistant!.key}:${index}`); + this.heldError = errorMessage ?? 'Pi reported an error'; + return; + } + // An aborted response is the user's own interrupting: its partial content + // is completed as text, with no error row to blame them for it. + + const content = Array.isArray(msg.content) ? msg.content : []; + content.forEach((block, index) => { + const part = recordOf(block); + const key = assistant ? `${assistant.key}:${index}` : undefined; + const streamed = assistant?.parts.get(index); + if (part?.type === 'text' && typeof part.text === 'string' && part.text !== '') { + entries.push({ + entryType: 'text', + role: 'agent', + text: part.text, + ...(streamed === 'text' && key !== undefined ? { part: key } : {}), + timestamp, + }); + } else if (part?.type === 'thinking' && typeof part.text === 'string' && part.text !== '') { + entries.push({ + entryType: 'thinking', + text: part.text, + ...(streamed === 'thinking' && key !== undefined ? { part: key } : {}), + timestamp, + }); + } + if (key !== undefined) this.coalescer.complete(key); + }); + + const provider = str(msg.provider); + const modelId = str(msg.model); + if (provider !== undefined && modelId !== undefined && (provider !== this.currentProvider || modelId !== this.currentModelId)) { + this.currentProvider = provider; + this.currentModelId = modelId; + const label = this.modelName(); + if (label !== undefined && label !== this.modelLabel) { + this.modelLabel = label; + this.ctx.emit({ type: 'info', model: label }); + } + } + this.emit(entries); + } + + private toolStart(record: PiRecord): void { + const callId = str(record.toolCallId); + const toolName = str(record.toolName); + if (callId === undefined || toolName === undefined) return; + const input = recordOf(record.args) ?? {}; + this.toolFacts.set(callId, { name: toolName, input }); + const call = piTool(toolName, input, this.reportUnknownTool); + const locations = toolLocations(input); + this.emit([ + { + entryType: 'tool_call', + callId, + toolName, + kind: call.kind, + title: call.title, + ...(locations.length > 0 ? { locations } : {}), + ...(call.input !== undefined ? { input: call.input } : {}), + timestamp: now(), + }, + ]); + } + + private toolEnd(record: PiRecord): void { + const callId = str(record.toolCallId); + if (callId === undefined) return; + this.toolFacts.delete(callId); + // The facts are gone by now; a call the permission gate hid would be + // known here, but nothing is hidden: Pi's own question tools are none. + const text = resultText(record.result); + this.emit([ + { + entryType: 'tool_result', + callId, + text: text === '' ? (record.isError === true ? 'The tool failed.' : '(no output)') : truncateToolResult(text), + ...(record.isError === true ? { isError: true } : {}), + timestamp: now(), + }, + ]); + } + + /** Pi will try the failed request again: one status line says so, in + * place of the attempt's error. */ + private retrying(record: PiRecord): void { + this.heldError = undefined; + const attempt = num(record.attempt); + const of = num(record.maxAttempts); + const delay = num(record.delayMs); + // The first line, briefly: a provider's error can be a page of JSON, and + // the full text is the error entry's if Pi gives up. + const firstLine = str(record.errorMessage)?.split('\n')[0]; + const why = firstLine !== undefined && firstLine.length > 120 ? `${firstLine.slice(0, 119)}…` : firstLine; + const when = delay !== undefined ? ` in ${Math.max(1, Math.round(delay / 1000))}s` : ''; + const count = attempt !== undefined && of !== undefined ? ` (${attempt} of ${of})` : ''; + this.emit([{ entryType: 'status', text: `Retrying${when}${count}${why ? `: ${why}` : ''}`, timestamp: now() }]); + } + + private settled(aborted: boolean): void { + // An error Pi did not retry is the turn's: shown now that nothing follows + // — unless the user stopped the turn, which is why nothing followed. + if (this.heldError !== undefined && !aborted) { + this.emit([{ entryType: 'error', text: this.heldError, timestamp: now() }]); + } + this.heldError = undefined; + this.coalescer.reset(); + this.assistant = undefined; + if (!this.running) return; + this.running = false; + this.emit([{ entryType: 'turn_complete', timestamp: now() }]); + this.ctx.emit({ type: 'turn', state: 'idle' }); + void this.refreshContext(); + } + + /** Pi reports the context-window estimate it uses for its own compaction + * footer; the phone gets it as session info, the way the other drivers + * report their agents' meters. */ + private async refreshContext(): Promise { + if (!this.rpc?.alive) return; + try { + const stats = recordOf(await this.rpc.request('get_session_stats')); + const usage = recordOf(stats?.contextUsage); + const window = num(usage?.contextWindow); + const percent = num(usage?.percent); + const rounded = percent !== undefined ? Math.round(percent) : undefined; + const changedWindow = window !== undefined && window > 0 && window !== this.contextWindow; + const changedPercent = rounded !== undefined && rounded !== this.contextPercentage; + if (changedWindow) this.contextWindow = window; + if (changedPercent) this.contextPercentage = rounded; + if (!this.ended && (changedWindow || changedPercent)) { + this.ctx.emit({ + type: 'info', + ...(changedWindow ? { contextWindow: window } : {}), + ...(changedPercent ? { contextPercentage: rounded } : {}), + }); + } + } catch { + // The meter is cosmetic: a session that cannot report it runs on. + } + } + + // --- the permission gate and other extensions' dialogs --- + + private uiRequest(record: PiRecord): void { + if (this.ended) return; + const method = str(record.method); + if (method === 'notify') { + const text = str(record.message); + if (text !== undefined) this.emit([{ entryType: 'status', text, timestamp: now() }]); + return; + } + if (method !== 'select' && method !== 'confirm' && method !== 'input' && method !== 'editor') return; + const id = str(record.id); + if (id === undefined) return; + this.openUi.add(id); + void this.answerUi(id, method, record) + .catch((error: unknown) => { + this.deps.log(`[pi] could not answer a dialog: ${error instanceof Error ? error.message : String(error)}`); + this.respond({ type: 'extension_ui_response', id, cancelled: true }); + }) + .finally(() => this.openUi.delete(id)); + } + + private respond(response: Record): void { + const id = str(response.id); + if (id !== undefined && this.cancelledUi.has(id)) return; + this.rpc?.respond(response); + } + + private async answerUi(id: string, method: string, record: PiRecord): Promise { + const title = str(record.title) ?? ''; + if (method === 'select' && title.startsWith(PI_PERMISSION_PREFIX)) { + await this.answerPermission(id, title.slice(PI_PERMISSION_PREFIX.length)); + return; + } + if (method === 'select') { + const options = Array.isArray(record.options) ? record.options.filter((o): o is string => typeof o === 'string') : []; + const outcome = await this.ask(id, title || 'Pi asks', options); + this.reply(id, outcome); + return; + } + if (method === 'confirm') { + const message = str(record.message); + const question = message !== undefined && message !== title ? `${title}\n\n${message}` : title || 'Pi asks'; + const outcome = await this.ask(id, question, ['Yes', 'No']); + if (outcome.outcome === 'cancelled') { + this.respond({ type: 'extension_ui_response', id, cancelled: true }); + return; + } + const answer = outcome.answers[0]; + const yes = + answer?.type === 'selected' ? answer.labels.includes('Yes') : answer?.type === 'text' ? /^\s*y/i.test(answer.text) : false; + this.respond({ type: 'extension_ui_response', id, confirmed: yes }); + return; + } + // input / editor: free text, with the editor's prefill in the question. + const prefill = str(record.prefill); + const question = prefill !== undefined ? `${title || 'Pi asks'}\n\n${prefill}` : title || 'Pi asks'; + const outcome = await this.ask(id, question, []); + this.reply(id, outcome); + } + + private ask(requestId: string, question: string, options: string[]): Promise { + const spec: QuestionSpec = { + question, + ...(options.length > 0 ? { options: options.map((label) => ({ label })) } : {}), + }; + return this.ctx.askQuestion(requestId, [spec]); + } + + private reply(id: string, outcome: QuestionOutcome): void { + if (outcome.outcome === 'cancelled') { + this.respond({ type: 'extension_ui_response', id, cancelled: true }); + return; + } + const answer = outcome.answers[0]; + const value = answer?.type === 'selected' ? (answer.labels[0] ?? '') : answer?.type === 'text' ? answer.text : ''; + this.respond({ type: 'extension_ui_response', id, value }); + } + + /** + * One CodeDeck permission gate. The facts of the call Pi already reported + * name the tool, its input and its kind; whether it needs a card at all is + * this driver's decision, and the phone's answer becomes Pi's `select` + * value: only "allow" lets the call run. + */ + private async answerPermission(id: string, callId: string): Promise { + const facts = this.toolFacts.get(callId); + const toolName = facts?.name ?? 'tool'; + if (this.sessionMode === YOLO_MODE || this.allowedTools.has(toolName) || PI_READ_ONLY_TOOLS.has(toolName)) { + this.respond({ type: 'extension_ui_response', id, value: 'allow' }); + return; + } + const input = facts?.input ?? {}; + const call = piTool(toolName, input, this.reportUnknownTool); + const locations = toolLocations(input); + const request: Omit = { + requestId: id, + toolName, + kind: call.kind, + title: call.title, + ...(locations.length > 0 ? { locations } : {}), + options: [PERMISSION_ALLOW, { ...ALLOW_SESSION, label: `Allow ${toolName} for this session` }, PERMISSION_DENY], + }; + const outcome: SelectOutcome = await this.ctx.requestPermission(request); + if (this.cancelledUi.has(id)) return; + if (outcome.outcome === 'cancelled') { + this.respond({ type: 'extension_ui_response', id, cancelled: true }); + return; + } + if (outcome.optionId === PERMISSION_ALLOW.id || outcome.optionId === ALLOW_SESSION.id) { + if (outcome.optionId === ALLOW_SESSION.id) this.allowedTools.add(toolName); + this.respond({ type: 'extension_ui_response', id, value: 'allow' }); + return; + } + this.respond({ type: 'extension_ui_response', id, value: 'deny' }); + } + + /** Answer every dialog still waiting with "cancelled". Pi does not settle + * an agent while an extension dialog is open (verified against 1.5.2), so + * an interrupt and the session's end must close them. */ + private cancelDialogs(): void { + for (const id of this.openUi) { + if (this.cancelledUi.has(id)) continue; + this.cancelledUi.add(id); + this.rpc?.respond({ type: 'extension_ui_response', id, cancelled: true }); + } + this.openUi.clear(); + } + + // --- the DriverSession surface --- + + prompt(text: string): void { + if (this.ended) return; + if (!this.ready || this.rpc === undefined) { + // The bridge waits for `ready` before it offers input; a prompt that + // races the process start is held rather than dropped. + this.queuedPrompts.push(text); + return; + } + if (!this.running) { + this.running = true; + this.ctx.emit({ type: 'turn', state: 'running' }); + void this.startTurn(text); + return; + } + // A message while a turn runs is steered into that turn: Pi delivers it + // after the current tool calls, before the next model request. + void this.rpc.request('steer', { message: text }).catch((error: unknown) => { + this.deps.log(`[pi] could not steer the running turn: ${error instanceof Error ? error.message : String(error)}`); + }); + } + + private async startTurn(text: string): Promise { + try { + if (this.rpc === undefined) throw new Error('the process is not running'); + const data = recordOf(await this.rpc.request('prompt', { message: text })); + if (this.ended) return; + // "handled": an extension command consumed the prompt, so no run + // started — the turn is over as soon as it began. + if (data?.disposition === 'handled' && this.running) { + this.running = false; + this.emit([{ entryType: 'turn_complete', timestamp: now() }]); + this.ctx.emit({ type: 'turn', state: 'idle' }); + } + } catch (error: unknown) { + if (this.ended) return; + this.emit([ + { entryType: 'error', text: `Pi refused the prompt: ${error instanceof Error ? error.message : String(error)}`, timestamp: now() }, + ]); + if (this.running) { + this.running = false; + this.ctx.emit({ type: 'turn', state: 'idle' }); + } + } + } + + async interrupt(): Promise { + if (this.ended) return; + this.cancelDialogs(); + try { + await this.rpc?.request('abort'); + } catch (error: unknown) { + this.deps.log(`[pi] could not abort the turn: ${error instanceof Error ? error.message : String(error)}`); + } + } + + async setOption(option: SessionOption, value: string): Promise { + switch (option) { + case 'mode': + if (!PI_MODES.some((mode) => mode.id === value)) throw new Error(`${PI_LABEL} has no mode '${value}'`); + this.sessionMode = value; + return; + case 'effort': + if (!PI_EFFORTS.some((effort) => effort.id === value)) throw new Error(`${PI_LABEL} has no thinking level '${value}'`); + await (await this.started).request('set_thinking_level', { level: value }); + return; + case 'model': { + const { provider, modelId } = splitModel(value, this.params.provider?.id); + const rpc = await this.started; + const data = recordOf(await rpc.request('set_model', { ...(provider !== undefined ? { provider } : {}), modelId })); + const label = str(data?.name) ?? (provider !== undefined ? `${provider}/${modelId}` : modelId); + if (label !== this.modelLabel) { + this.modelLabel = label; + this.ctx.emit({ type: 'info', model: label }); + } + return; + } + } + } + + async getUsage(): Promise { + return null; + } + + async listCommands(): Promise { + if (this.ended || !this.rpc?.alive) return []; + try { + const data = recordOf(await this.rpc.request('get_commands')); + const commands = Array.isArray(data?.commands) ? data.commands : []; + return commands.flatMap((raw): SlashCommand[] => { + const command = recordOf(raw); + const name = str(command?.name); + if (name === undefined) return []; + const description = str(command?.description); + return [{ name, ...(description !== undefined ? { description } : {}) }]; + }); + } catch (error: unknown) { + this.deps.log(`[pi] could not list commands: ${error instanceof Error ? error.message : String(error)}`); + return []; + } + } + + async end(): Promise { + if (this.ended) return; + this.ended = true; + this.settleStarted.reject(new Error('the Pi session ended')); + this.cancelDialogs(); + this.coalescer.reset(); + await this.rpc?.close(); + } +} + +export interface PiDriverOptions { + runtime: PiRuntime; + /** `CODEDECK_PI_HOME` — where Pi's settings, credentials and sessions + * live. */ + home: string; + /** The environment a session inherits (the host's, without its own + * variables). */ + baseEnv?: NodeJS.ProcessEnv; + /** Outbound HTTP to provider profiles' endpoints. */ + providerHttp?: ProviderHttp; + /** Spawn seam for tests. */ + spawnFn?: PiRpcOptions['spawnFn']; + log: (message: string) => void; +} + +export class PiDriver implements Driver { + private unavailable: string | undefined; + private models?: Promise<{ models: ModelEntry[]; defaultModel?: string }>; + + constructor(private readonly options: PiDriverOptions) { + // Pi's state root must exist before the first process starts in it + // (whether that is a session or the model probe). + try { + fs.mkdirSync(options.home, { recursive: true }); + } catch (error) { + options.log(`[pi] could not create ${options.home}: ${error instanceof Error ? error.message : String(error)}`); + } + // The runtime is fetched as the host starts, like the other agents', so + // the first session (and the model list the phone asks for before it) + // finds it ready instead of waiting on a download. + void options.runtime.prepare(); + } + + /** Mark the driver unusable (a path the operator named is not a file). */ + setUnavailable(reason: string): void { + this.unavailable = reason; + } + + /** The release of the installed package, from its manifest. */ + version(): Promise { + return this.options.runtime.version(); + } + + info(): AgentInfo { + return { + id: PI_AGENT_ID, + displayName: PI_LABEL, + modes: PI_MODES, + efforts: PI_EFFORTS, + defaultMode: DEFAULT_MODE, + defaultEffort: DEFAULT_EFFORT, + // What the RPC surface carries: models, commands and interruption, and + // a provider profile bound to a session. Its plugins, MCP servers and + // saved permission rules are its own configuration and have no manager + // here; there is no subscription usage to ask for. + supports: { + models: true, + usage: false, + providers: true, + interrupt: true, + commands: true, + plugins: false, + mcp: false, + tasks: false, + }, + credentials: [], + style: PI_STYLE, + ...(this.unavailable ? { unavailableReason: this.unavailable } : {}), + }; + } + + startSession(params: StartSession, ctx: SessionContext): DriverSession { + if (this.unavailable) throw new Error(this.unavailable); + if (params.mode !== undefined && !PI_MODES.some((mode) => mode.id === params.mode)) { + throw new Error(`${PI_LABEL} has no mode '${params.mode}'`); + } + if (params.effort !== undefined && !PI_EFFORTS.some((effort) => effort.id === params.effort)) { + throw new Error(`${PI_LABEL} has no thinking level '${params.effort}'`); + } + // Built here so a provider that cannot be used at all refuses the + // session before it starts, rather than after an error entry. + return new PiSession(params, ctx, { + runtime: this.options.runtime, + home: this.options.home, + baseEnv: this.options.baseEnv ?? process.env, + ...(this.options.spawnFn !== undefined ? { spawnFn: this.options.spawnFn } : {}), + log: this.options.log, + }); + } + + /** + * Pi's model catalog, from a short-lived probe process: the list is the + * package's own built-ins plus the operator's `models.json`, and reading it + * needs neither a credential nor a reachable endpoint. Cached once it says + * something, and asked again after a failure or an empty answer. + */ + listModels(): Promise<{ models: ModelEntry[]; defaultModel?: string }> { + this.models ??= this.probeModels().catch((error: unknown) => { + this.models = undefined; + this.options.log(`[pi] could not list models: ${error instanceof Error ? error.message : String(error)}`); + return { models: [] }; + }); + return this.models; + } + + private async probeModels(): Promise<{ models: ModelEntry[]; defaultModel?: string }> { + const entry = await this.options.runtime.entryPoint(); + const command = piCommand(entry, ['--mode', 'rpc', '--no-session', '--offline']); + const rpc = new PiRpc({ + command: command.command, + args: command.args, + cwd: this.options.home, + env: buildPiEnv({}, this.options.home, this.options.baseEnv ?? process.env), + onEvent: () => {}, + onUiRequest: () => {}, + onExit: () => {}, + onStderr: () => {}, + onBadLine: () => {}, + ...(this.options.spawnFn !== undefined ? { spawnFn: this.options.spawnFn } : {}), + }); + try { + const listed = recordOf(await rpc.request('get_available_models', {}, PROBE_TIMEOUT_MS)); + const state = recordOf(await rpc.request('get_state', {}, PROBE_TIMEOUT_MS)); + const models: ModelEntry[] = []; + for (const raw of Array.isArray(listed?.models) ? listed.models : []) { + const model = recordOf(raw); + const id = str(model?.id); + const provider = str(model?.provider); + if (id === undefined) continue; + const full = provider !== undefined ? `${provider}/${id}` : id; + const name = str(model?.name); + models.push({ id: full, label: name ?? id, ...(provider !== undefined ? { provider } : {}) }); + } + const current = recordOf(state?.model); + const currentId = str(current?.id); + const currentProvider = str(current?.provider); + if (models.length === 0) this.models = undefined; + return { + models, + ...(currentId !== undefined + ? { defaultModel: currentProvider !== undefined ? `${currentProvider}/${currentId}` : currentId } + : {}), + }; + } finally { + await rpc.close(1_000); + } + } + + /** Pi speaks OpenAI's chat-completions API to a profile's endpoint, so the + * token is checked the way any OpenAI-compatible client would. */ + async checkProvider(provider: ProviderBinding, model: string): Promise { + return this.options.providerHttp ? checkToken(OPENAI_API, provider, model, this.options.providerHttp.post) : undefined; + } + + async listProviderModels(baseUrl: string, token: string): Promise { + if (!this.options.providerHttp) throw new Error('this host reads no provider endpoints'); + return listModels(OPENAI_API, baseUrl, token, this.options.providerHttp.get); + } + + /** + * Remove Pi's record of conversation `id`: its session file, under + * whichever project directory Pi filed it in. The layout is Pi's own — + * + * $PI_CODING_AGENT_DIR/sessions//_.jsonl + * + * — and the project directory is not recomputed here: an id is a UUID, so + * every one is searched. Resolves when nothing of it is left. + */ + async deleteConversation(conversationId: string, cwd: string): Promise { + void cwd; // Pi files sessions by cwd; every project directory is searched. + if (!/^[A-Za-z0-9._-]+$/.test(conversationId) || conversationId === '.' || conversationId === '..') { + throw new Error(`'${conversationId}' is not a Pi session id`); + } + const root = path.join(this.options.home, 'sessions'); + for (const project of directories(root)) { + const dir = path.join(root, project); + for (const name of files(dir)) { + if (name.endsWith(`_${conversationId}.jsonl`) || name === `${conversationId}.jsonl`) { + await fs.promises.rm(path.join(dir, name), { force: true }); + } + } + } + } + + async shutdown(): Promise { + await this.options.runtime.close(); + } +} + +function directories(dir: string): string[] { + try { + return fs + .readdirSync(dir, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name); + } catch { + return []; + } +} + +function files(dir: string): string[] { + try { + return fs + .readdirSync(dir, { withFileTypes: true }) + .filter((entry) => entry.isFile()) + .map((entry) => entry.name); + } catch { + return []; + } +} diff --git a/packages/agent-host/src/drivers/pi/env.ts b/packages/agent-host/src/drivers/pi/env.ts new file mode 100644 index 00000000..6359932b --- /dev/null +++ b/packages/agent-host/src/drivers/pi/env.ts @@ -0,0 +1,99 @@ +/** + * The Pi child's environment for one spawn: the state root it must use, the + * switches that keep it from phoning home, and — for a session bound to a + * provider profile — the profile CodeDeck's extension registers with Pi. + * The returned object carries SECRETS — never log it. + * + * Pi reads its endpoint and key from its own `models.json` or `auth.json` + * under `$PI_CODING_AGENT_DIR`, or from an extension registration. A profile + * is the second kind: its endpoint, label and models travel as JSON in + * `CODEDECK_PI_PROVIDER`, while the token travels in its own variable + * (`CODEDECK_PI_PROVIDER_TOKEN`) and is referenced from the extension by name, + * so the secret never reaches the file written to disk. + * + * The profile's `baseUrl` is the endpoint as the user saved it; Pi's + * OpenAI-compatible provider needs its versioned API root, so `/v1` is + * appended unless the URL already ends there — the same rule + * `providerApiRoot` applies for the other drivers. + */ +import { isValidProviderBaseUrl, PROVIDER_BASE_URL_ERROR } from '../../sdk/provider'; +import { providerApiRoot } from '../../sdk/providerModels'; +import type { ProviderBinding, StartSession } from '../../sdk/types'; +import { PI_AGENT_DIR_ENV } from './runtime'; + +/** The profile (no secret) the extension registers, when a session is bound + * to one. */ +export const PI_PROVIDER_ENV = 'CODEDECK_PI_PROVIDER'; +/** The profile's auth token, read by the extension through `$`-interpolation. */ +export const PI_PROVIDER_TOKEN_ENV = 'CODEDECK_PI_PROVIDER_TOKEN'; + +/** The provider registration as the extension's JSON variable carries it. */ +export interface PiProviderProfile { + id: string; + label: string; + baseUrl: string; + models: Array<{ id: string; label?: string; contextWindow?: number }>; +} + +/** The profile a session is bound to, with the endpoint Pi will call. */ +export function toPiProviderProfile(provider: ProviderBinding): PiProviderProfile { + return { + id: provider.id, + label: provider.label || provider.id, + baseUrl: providerApiRoot(provider.baseUrl), + models: provider.models.map((model) => ({ + id: model.id, + ...(model.label ? { label: model.label } : {}), + ...(model.contextWindow !== undefined && model.contextWindow !== null ? { contextWindow: model.contextWindow } : {}), + })), + }; +} + +/** + * The environment for one spawn. Without a provider: everything inherited, + * with the stored or inherited Pi credentials untouched (Pi's own provider + * setup in its home applies) and the bridge-level `env` on top (e.g. + * `GITHUB_TOKEN`, stored wins). With a provider: the profile's own endpoint + * and token replace any such variable a session might otherwise inherit, so + * the session cannot quietly reach another account. + * + * `PI_CODING_AGENT_DIR` is always this driver's, set last: a session that + * moved it would lose the conversation it is resuming. Throws for an + * insecure provider base URL or a missing token — the session is then + * refused loudly rather than run against the wrong account. + */ +export function buildPiEnv( + params: Pick, + home: string, + baseEnv: Record = process.env, +): Record { + const env: Record = {}; + for (const [key, value] of Object.entries(baseEnv)) { + if (value !== undefined) env[key] = value; + } + delete env[PI_PROVIDER_ENV]; + delete env[PI_PROVIDER_TOKEN_ENV]; + + const provider = params.provider ?? undefined; + if (provider) { + // Checked before the token: this decides whether the token may travel on + // this connection at all. The base URL is not a secret. + if (!isValidProviderBaseUrl(provider.baseUrl)) { + throw new Error( + `provider profile '${provider.id}' has an insecure base URL (${provider.baseUrl}) — ` + + `${PROVIDER_BASE_URL_ERROR}. Its API token would travel in cleartext, so the session is refused.`, + ); + } + if (!provider.authToken) throw new Error(`provider profile '${provider.id}' has no stored auth token`); + env[PI_PROVIDER_ENV] = JSON.stringify(toPiProviderProfile(provider)); + env[PI_PROVIDER_TOKEN_ENV] = provider.authToken; + } + + Object.assign(env, params.env ?? {}); + // Last: the state root and the offline switches belong to this driver, not + // to whatever the bridge or the operator's environment says. + env[PI_AGENT_DIR_ENV] = home; + env.PI_SKIP_VERSION_CHECK = '1'; + env.PI_TELEMETRY = '0'; + return env; +} diff --git a/packages/agent-host/src/drivers/pi/extension.ts b/packages/agent-host/src/drivers/pi/extension.ts new file mode 100644 index 00000000..e53f61af --- /dev/null +++ b/packages/agent-host/src/drivers/pi/extension.ts @@ -0,0 +1,126 @@ +/** + * The extension CodeDeck installs into every Pi session: the permission gate, + * and the provider profile a bound session runs on. + * + * Pi loads an extension as a module whose default export is a function that + * receives Pi's `ExtensionAPI`. The driver serialises the function below with + * `Function.prototype.toString()` and writes `export default ` into + * Pi's config directory before a session starts (installPiExtension), then + * passes that file with `-e`. That is what makes this function special: it + * runs inside Pi's process, where nothing this host defines exists, so it must + * stay self-contained — no imports, and no reference to any module-scope + * binding other than types (which are erased). Everything it needs comes from + * its `pi` argument, its `ctx` argument, or a global. + * + * What it does: + * + * - `tool_call` — every tool call Pi is about to run is held until the driver + * answers. The title carries the call's id (`PI_PERMISSION_PREFIX` + id), so + * the driver can build the card from the `tool_execution_start` facts it + * already has. Pi's extension UI `select` is the dialog the RPC client + * answers with `extension_ui_response`; anything but "allow" blocks the call + * with a fixed reason. The driver decides whether to ask at all: `yolo`, a + * read-only tool and "allow for this session" are answered "allow" without + * a card ever reaching the phone. + * - a provider profile, when the session is bound to one — registered at + * startup with Pi's `openai-completions` API, its token read from the + * environment through Pi's `$NAME` interpolation so the secret never reaches + * the file on disk. Its models become selectable as `/`. + */ +import * as fs from 'node:fs'; +import * as path from 'node:path'; + +/** The prefix the `tool_call` dialog's title carries, before the call's id. + * The driver matches on it to tell CodeDeck's gate from another extension's + * own dialog. */ +export const PI_PERMISSION_PREFIX = 'codedeck-permission:'; + +/** The `ExtensionAPI` surface this extension uses, typed locally: the module + * is serialised, so the real types are not available at run time. */ +interface PiExtensionApi { + registerProvider(id: string, config: Record): void; + on( + event: 'tool_call', + handler: (event: { toolCallId: string; toolName: string; input: unknown }, ctx: PiExtensionContext) => Promise, + ): void; +} + +interface PiExtensionContext { + ui: { select(title: string, options: string[]): Promise }; +} + +/** + * The extension's body. Keep it self-contained: see the module comment. + * `PI_PERMISSION_PREFIX` is written out as a literal because the constant is + * erased with the rest of this module when Pi loads the serialised function. + */ +export function codedeckPiExtension(pi: PiExtensionApi): void { + const profile = process.env.CODEDECK_PI_PROVIDER; + if (profile) { + try { + // `baseUrl` is already the profile's versioned API root: the driver + // resolved it (env.ts), so the one rule for it lives in the host. + const parsed = JSON.parse(profile); + const baseUrl = String(parsed.baseUrl || ''); + const models = Array.isArray(parsed.models) ? parsed.models : []; + pi.registerProvider(String(parsed.id || 'codedeck'), { + name: String(parsed.label || parsed.id || 'CodeDeck provider'), + baseUrl: baseUrl, + api: 'openai-completions', + apiKey: '$CODEDECK_PI_PROVIDER_TOKEN', + models: models.map(function (model: { id: string; label?: string; contextWindow?: number }) { + return { + id: String(model.id), + name: String(model.label || model.id), + // A profile carries no reasoning metadata: Pi sends no thinking + // parameters, and the model clamps every level to off. + reasoning: false, + input: ['text'], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: Number(model.contextWindow) > 0 ? Number(model.contextWindow) : 128000, + maxTokens: 32768, + }; + }), + }); + } catch { + // A malformed profile is not a reason to keep Pi from starting: the + // session runs Pi's own models and reports what it cannot do. + } + } + pi.on('tool_call', async function (event, ctx) { + const choice = await ctx.ui.select('codedeck-permission:' + event.toolCallId, ['allow', 'deny']); + if (choice !== 'allow') return { block: true, reason: 'Denied by the user' }; + return undefined; + }); +} + +/** The extension file's contents: one ESM module with the function above as + * its default export. Deterministic, so the driver writes it only when it + * changed. */ +export function codedeckPiExtensionSource(): string { + return ( + '// Written by CodeDeck+ — the permission gate and provider registration of\n' + + '// every Pi session. Regenerated at each session start; do not edit.\n' + + `export default ${codedeckPiExtension.toString()};\n` + ); +} + +/** Where Pi finds the extension: a directory of its own under the state root, + * which Pi never scans on its own (only the `-e` path names it). */ +export function piExtensionPath(home: string): string { + return path.join(home, 'codedeck', 'codedeck-pi.js'); +} + +/** Write the extension file when its contents changed, and return its path. */ +export function installPiExtension(home: string): string { + const file = piExtensionPath(home); + const source = codedeckPiExtensionSource(); + try { + if (fs.readFileSync(file, 'utf8') === source) return file; + } catch { + // Not there yet: written below. + } + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, source); + return file; +} diff --git a/packages/agent-host/src/drivers/pi/install.ts b/packages/agent-host/src/drivers/pi/install.ts new file mode 100644 index 00000000..ba4e681b --- /dev/null +++ b/packages/agent-host/src/drivers/pi/install.ts @@ -0,0 +1,54 @@ +/** + * Where Pi's runtime comes from when the machine has none: + * `@earendil-works/pi-coding-agent` and its whole dependency closure, + * installed on demand (agentInstall.installPackageTree) at the version and + * sha512 pnpm-lock.yaml pins (src/generated/piPackages.ts). The release + * archives and the default image ship no part of it — a driver that finds + * nothing on the machine downloads the tree the first time it needs it. + * + * Pi is a pure-JS CLI: nothing runs until every package of that closure sits + * in one `node_modules`, which is what the tree installer reproduces. + * `dist/bundle/cli.js` is the CLI's entry point, run with the host's own + * `node` — the same file the package's `bin` names. + */ +import { fileURLToPath } from 'node:url'; +import * as path from 'node:path'; +import { installedPackageTree, installPackageTree, type InstallOptions } from '../../install/agentInstall'; +import { PI_PACKAGES } from '../../generated/piPackages'; +import { isFile } from '../../sdk/executable'; + +/** The npm package Pi ships as. */ +export const PI_PACKAGE = '@earendil-works/pi-coding-agent'; +/** Its CLI, relative to the installed package directory. */ +const PI_ENTRY = 'dist/bundle/cli.js'; +/** How the driver refers to it in progress lines and errors. */ +export const PI_LABEL = 'Pi'; + +/** The CLI entry point of a tree the installer has laid down. */ +export function piEntryPoint(treeRoot: string): string { + return path.join(treeRoot, ...PI_ENTRY.split('/')); +} + +/** The CLI entry point of the pinned tree when it is installed, else null. */ +export function installedPiTree(cacheDir: string): string | null { + const root = installedPackageTree(PI_PACKAGE, PI_PACKAGES, cacheDir); + return root ? piEntryPoint(root) : null; +} + +/** Install (or find) the Pi tree and return its CLI entry point. */ +export async function installPiTree(options: InstallOptions): Promise { + return piEntryPoint(await installPackageTree(PI_PACKAGE, PI_PACKAGES, { ...options, label: PI_LABEL })); +} + +/** The CLI of the package when it is installed beside the host — a dev + * checkout, where pnpm-lock.yaml pins it as a devDependency — else null. Found by walking up from this module to a `node_modules` that + * holds it; the package's `exports` map names neither the manifest nor the + * bundle its `bin` entry runs, so neither `require.resolve` nor a subpath + * import can reach them. */ +export function bundledPiExecutable(): string | null { + for (let dir = path.dirname(fileURLToPath(import.meta.url)); ; dir = path.dirname(dir)) { + const entry = path.join(dir, 'node_modules', ...PI_PACKAGE.split('/'), ...PI_ENTRY.split('/')); + if (isFile(entry)) return entry; + if (path.dirname(dir) === dir) return null; + } +} diff --git a/packages/agent-host/src/drivers/pi/module.ts b/packages/agent-host/src/drivers/pi/module.ts new file mode 100644 index 00000000..9efe8ca0 --- /dev/null +++ b/packages/agent-host/src/drivers/pi/module.ts @@ -0,0 +1,53 @@ +/** + * Pi: its CLI over RPC — the operator's own (CODEDECK_PI_PATH), else the + * pinned package tree installed on demand — with its state under + * `$PI_CODING_AGENT_DIR` in CODEDECK_PI_HOME. + */ +import type { DriverEnv, DriverModule } from '../../sdk/module'; +import { isFile } from '../../sdk/executable'; +import { providerHttp } from '../../sdk/net'; +import { removePackageTree } from '../../install/agentInstall'; +import { PiDriver } from './driver'; +import { PI_PACKAGE, installPiTree, installedPiTree } from './install'; +import { PiRuntime, piHomeDir } from './runtime'; + +const explicitPath = (ctx: DriverEnv): string | undefined => ctx.env.CODEDECK_PI_PATH?.trim() || undefined; + +export const piModule: DriverModule = { + id: 'pi', + label: 'Pi', + create(ctx) { + const home = piHomeDir(ctx.lookupEnv); + const piPath = explicitPath(ctx); + const runtime = new PiRuntime({ + // An explicit path is the operator's own CLI; without one the pinned + // tree is installed on demand, at the version and sha512 + // pnpm-lock.yaml holds. + ...(piPath ? { piPath } : {}), + cacheDir: ctx.cacheDir, + registry: ctx.registry, + installPi: installPiTree, + log: ctx.log, + }); + const driver = new PiDriver({ + runtime, + home, + baseEnv: ctx.ownEnv, + providerHttp, + log: ctx.log, + }); + if (piPath && !isFile(piPath)) { + driver.setUnavailable(`CODEDECK_PI_PATH points at ${piPath}, which is not a file.`); + } + return driver; + }, + runtime: { + find: (ctx) => { + const piPath = explicitPath(ctx); + return piPath ? `the CLI at ${piPath}` : null; + }, + installed: (ctx) => installedPiTree(ctx.cacheDir), + install: (ctx) => installPiTree({ cacheDir: ctx.cacheDir, registry: ctx.registry, log: ctx.log }), + remove: (ctx) => removePackageTree(PI_PACKAGE, ctx.cacheDir), + }, +}; diff --git a/packages/agent-host/src/drivers/pi/rpc.ts b/packages/agent-host/src/drivers/pi/rpc.ts new file mode 100644 index 00000000..118f2aae --- /dev/null +++ b/packages/agent-host/src/drivers/pi/rpc.ts @@ -0,0 +1,305 @@ +/** + * Pi's RPC framing: one JSON object per LF-terminated line, in both + * directions, over the child's stdio. + * + * The framing rules are Pi's own (`docs/rpc.md`), and two of them are the + * reason this is not `readline`: + * + * - records are split on LF only, with one optional carriage return stripped + * before it. `U+2028` and `U+2029` are valid inside JSON strings and are + * not record boundaries — Node's `readline` treats them as ones, which + * would cut a record in half; + * - a line that does not read is logged and skipped. The decoder is total: + * stdout is a child process's, and a crash or a stray write must not take + * the host down with it. + * + * Commands carry an id and are answered by id, since Pi handles commands + * asynchronously. Writes honour stdin backpressure: a command is queued until + * the pipe drains, so a burst of large prompts does not grow an unbounded + * buffer in the child. + */ +import { spawn, type ChildProcess } from 'node:child_process'; +import { StringDecoder } from 'node:string_decoder'; + +/** One decoded RPC record. Only the envelope matters here; the driver reads + * the rest. */ +export interface PiRecord { + type?: string; + [key: string]: unknown; +} + +/** How a child is spawned. Tests inject their own; production uses Node's. */ +export type PiSpawn = ( + command: string, + args: string[], + options: { cwd: string; env: Record; stdio: ['pipe', 'pipe', 'pipe'] }, +) => ChildProcess; + +/** How long a command may go unanswered before its promise rejects. A local + * process should answer in milliseconds; a wedged one must not hold a + * session open for ever. */ +export const PI_REQUEST_TIMEOUT_MS = 15_000; + +/** How long closing stdin may take before the child is killed. Pi disposes + * its runtime and finishes pending work on EOF, which can take a moment. */ +export const PI_CLOSE_GRACE_MS = 5_000; + +/** Splits a byte stream into JSON records on LF. `push` never throws. */ +export class PiLineDecoder { + private readonly decoder = new StringDecoder('utf8'); + private pending = ''; + + constructor( + private readonly onRecord: (record: PiRecord) => void, + private readonly onBadLine: (line: string, reason: string) => void, + ) {} + + push(chunk: Buffer | string): void { + this.pending += typeof chunk === 'string' ? chunk : this.decoder.write(chunk); + for (;;) { + const end = this.pending.indexOf('\n'); + if (end < 0) return; + let line = this.pending.slice(0, end); + this.pending = this.pending.slice(end + 1); + if (line.endsWith('\r')) line = line.slice(0, -1); + if (line.trim() === '') continue; + let value: unknown; + try { + value = JSON.parse(line); + } catch (error) { + this.onBadLine(line, error instanceof Error ? error.message : String(error)); + continue; + } + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + this.onBadLine(line, 'not a JSON object'); + continue; + } + this.onRecord(value as PiRecord); + } + } +} + +/** Splits a byte stream into lines (stderr, which is plain text). */ +class TextLineDecoder { + private readonly decoder = new StringDecoder('utf8'); + private pending = ''; + + constructor(private readonly onLine: (line: string) => void) {} + + push(chunk: Buffer | string): void { + this.pending += typeof chunk === 'string' ? chunk : this.decoder.write(chunk); + for (;;) { + const end = this.pending.indexOf('\n'); + if (end < 0) return; + let line = this.pending.slice(0, end); + this.pending = this.pending.slice(end + 1); + if (line.endsWith('\r')) line = line.slice(0, -1); + if (line.trim() !== '') this.onLine(line); + } + } +} + +interface PendingCommand { + type: string; + resolve(value: unknown): void; + reject(error: Error): void; + timer: ReturnType; +} + +export interface PiRpcOptions { + command: string; + args: string[]; + cwd: string; + env: Record; + /** A session event (everything that is neither a command response nor an + * extension UI request). */ + onEvent(record: PiRecord): void; + /** An `extension_ui_request`: a dialog or a notification from an + * extension. */ + onUiRequest(record: PiRecord): void; + /** The child is gone. Called exactly once. */ + onExit(code: number | null, signal: NodeJS.Signals | null): void; + /** A diagnostic line from Pi (stderr). */ + onStderr(line: string): void; + /** A stdout line that was not a record. */ + onBadLine(line: string, reason: string): void; + spawnFn?: PiSpawn; + requestTimeoutMs?: number; +} + +export class PiRpc { + private readonly child: ChildProcess; + private readonly pending = new Map(); + private readonly timeoutMs: number; + private writing: Promise = Promise.resolve(); + private nextId = 0; + private exited = false; + + constructor(private readonly options: PiRpcOptions) { + this.timeoutMs = options.requestTimeoutMs ?? PI_REQUEST_TIMEOUT_MS; + const spawnFn: PiSpawn = options.spawnFn ?? ((command, args, opts) => spawn(command, args, opts)); + this.child = spawnFn(options.command, options.args, { + cwd: options.cwd, + env: options.env, + stdio: ['pipe', 'pipe', 'pipe'], + }); + + const stdout = new PiLineDecoder((record) => this.route(record), options.onBadLine); + this.child.stdout?.on('data', (chunk: Buffer) => stdout.push(chunk)); + const stderr = new TextLineDecoder((line) => options.onStderr(line)); + this.child.stderr?.on('data', (chunk: Buffer) => stderr.push(chunk)); + this.child.stdin?.on('error', (error: Error) => options.onBadLine('', `stdin: ${error.message}`)); + this.child.on('error', (error: Error) => { + options.onBadLine('', `process: ${error.message}`); + this.finish(null, null); + }); + // `close`, not `exit`: `exit` may come while stdout still holds the + // child's last records (an error message, `agent_settled`), and those + // must reach the driver before it hears the process is gone. + this.child.on('close', (code, signal) => this.finish(code, signal)); + } + + /** Whether the process is still running. */ + get alive(): boolean { + return !this.exited; + } + + get pid(): number | undefined { + return this.child.pid; + } + + /** Send one command and resolve with its `data` once Pi answers. Rejects + * with Pi's own error text, or when the timeout expires. */ + request(type: string, fields: Record = {}, timeoutMs = this.timeoutMs): Promise { + const id = `cd${++this.nextId}`; + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + this.pending.delete(id); + reject(new Error(`Pi did not answer '${type}' within ${Math.round(timeoutMs / 1000)}s`)); + }, timeoutMs); + timer.unref?.(); + this.pending.set(id, { type, resolve, reject, timer }); + this.write({ id, type, ...fields }); + }); + } + + /** Answer an extension UI request (`extension_ui_response`). Pi expects no + * command response to these. */ + respond(record: Record): void { + this.write(record); + } + + /** Close stdin and wait for a graceful exit, killing the process when it + * does not come. Idempotent. */ + async close(graceMs = PI_CLOSE_GRACE_MS): Promise { + if (this.exited) return; + // Queued commands go first, but only for the grace period: a Pi that + // stopped reading its stdin never drains it, and closing must still end. + await Promise.race([ + this.writing.catch(() => {}), + new Promise((resolve) => setTimeout(resolve, graceMs).unref?.()), + ]); + try { + this.child.stdin?.end(); + } catch { + // Already closed. + } + const exit = new Promise((resolve) => { + if (this.exited) return resolve(); + this.child.once('close', () => resolve()); + }); + const gaveUp = new Promise((resolve) => { + const timer = setTimeout(resolve, graceMs); + timer.unref?.(); + }); + await Promise.race([exit, gaveUp]); + if (!this.exited) { + try { + this.child.kill('SIGKILL'); + } catch { + // Already gone. + } + await Promise.race([exit, new Promise((resolve) => setTimeout(resolve, 1_000).unref?.())]); + } + } + + /** Stop the process now, without a graceful shutdown. Idempotent. */ + kill(): void { + if (this.exited) return; + try { + this.child.kill('SIGKILL'); + } catch { + // Already gone. + } + } + + private route(record: PiRecord): void { + if (record.type === 'response') { + const id = typeof record.id === 'string' ? record.id : undefined; + if (id !== undefined) { + const pending = this.pending.get(id); + if (!pending) { + this.options.onBadLine('', `response for unknown command '${String(record.command ?? '?')}'`); + return; + } + this.pending.delete(id); + clearTimeout(pending.timer); + if (record.success === false) { + const reason = typeof record.error === 'string' && record.error !== '' ? record.error : 'the command failed'; + pending.reject(new Error(reason)); + } else { + pending.resolve(record.data); + } + return; + } + // A parse error's response carries no id: Pi could not read a command. + this.options.onBadLine('', `Pi reported: ${String(record.error ?? 'a command it could not parse')}`); + return; + } + if (record.type === 'extension_ui_request') { + this.options.onUiRequest(record); + return; + } + this.options.onEvent(record); + } + + /** Serialise writes and honour stdin backpressure. */ + private write(record: Record): void { + const line = `${JSON.stringify(record)}\n`; + this.writing = this.writing.then(() => this.writeLine(line)); + } + + private writeLine(line: string): Promise { + const stdin = this.child.stdin; + if (!stdin || stdin.destroyed || this.exited) return Promise.resolve(); + return new Promise((resolve) => { + // A pipe that closes (the child exited) neither drains nor always + // errors: `close` settles the write too, so the queue never stalls. + const done = (): void => { + stdin.off('drain', done); + stdin.off('error', done); + stdin.off('close', done); + resolve(); + }; + stdin.once('drain', done); + stdin.once('error', done); + stdin.once('close', done); + try { + if (stdin.write(line)) done(); + } catch { + done(); + } + }); + } + + private finish(code: number | null, signal: NodeJS.Signals | null): void { + if (this.exited) return; + this.exited = true; + for (const pending of this.pending.values()) { + clearTimeout(pending.timer); + pending.reject(new Error(`Pi exited before answering '${pending.type}'`)); + } + this.pending.clear(); + this.options.onExit(code, signal); + } +} diff --git a/packages/agent-host/src/drivers/pi/runtime.ts b/packages/agent-host/src/drivers/pi/runtime.ts new file mode 100644 index 00000000..4936ecd8 --- /dev/null +++ b/packages/agent-host/src/drivers/pi/runtime.ts @@ -0,0 +1,115 @@ +/** + * Where the Pi CLI comes from, and the state root every Pi process shares. + * + * There is no process pool here: a Pi process serves exactly one conversation + * (the RPC mode's `new_session` and `--session` switch are the same process, + * but a CodeDeck session never leaves its own), so each driver session owns + * one child and closes it with the session (rpc.ts). + * + * Pi's own state — provider credentials, settings, sessions — lives under + * `$PI_CODING_AGENT_DIR`, the directory every process is pointed at. A + * conversation resumed after a restart is on disk, not in the process. + */ +import * as path from 'node:path'; +import { agentCacheDir } from '../../install/agentInstall'; +import { isFile } from '../../sdk/executable'; +import { packageVersionOf } from '../../sdk/version'; + +/** `$PI_CODING_AGENT_DIR` inside a CodeDeck-managed home: the directory Pi + * writes `settings.json`, `auth.json`, `models.json` and `sessions/` into. */ +export const PI_AGENT_DIR_ENV = 'PI_CODING_AGENT_DIR'; + +/** `$CODEDECK_PI_HOME`: the operator's override, else a `pi` directory beside + * the installed agent binaries (the bridge passes its own home, so this + * follows it). Absolute: a process starts inside `cwd`, so a relative path + * would resolve a second time, against the session's working directory. */ +export function piHomeDir(env: NodeJS.ProcessEnv = process.env): string { + return path.resolve(env.CODEDECK_PI_HOME?.trim() || path.join(path.dirname(agentCacheDir(env)), 'pi')); +} + +/** + * How to run Pi's CLI: an operator's own entry point may be the bundle's + * `cli.js` (this host runs it with its own node) or an executable of their + * own, which is run as it stands. Never through a shell: the arguments a + * session contributes are never shell syntax. + */ +export function piCommand(entry: string, args: string[]): { command: string; args: string[] } { + return /\.[cm]?js$/i.test(entry) ? { command: process.execPath, args: [entry, ...args] } : { command: entry, args }; +} + +export interface PiRuntimeOptions { + /** An operator-provided CLI (a `pi` they installed and want used, + * `CODEDECK_PI_PATH`); wins over the installed tree. */ + piPath?: string; + cacheDir: string; + registry?: string; + log: (message: string) => void; + /** Installs the runtime tree (install.ts). */ + installPi: (options: { cacheDir: string; registry?: string; log: (message: string) => void }) => Promise; +} + +export class PiRuntime { + private entry: Promise | null = null; + private knownVersion?: string; + + constructor(private readonly pi: PiRuntimeOptions) {} + + /** The CLI entry point: the operator's own, else the installed tree. */ + entryPoint(): Promise { + if (this.pi.piPath) { + // The host's path: Pi starts in the session's cwd, where a relative one + // would name another file. + const explicit = path.resolve(this.pi.piPath); + if (!isFile(explicit)) return Promise.reject(new Error(`CODEDECK_PI_PATH points at ${explicit}, which is not a file`)); + return Promise.resolve(explicit); + } + this.entry ??= this.pi + .installPi({ + cacheDir: this.pi.cacheDir, + ...(this.pi.registry !== undefined ? { registry: this.pi.registry } : {}), + log: this.pi.log, + }) + .catch((error: unknown) => { + // A download that failed is attempted again by the next session + // rather than remembered as this driver's permanent state. + this.entry = null; + throw error; + }); + return this.entry; + } + + /** + * Resolve the runtime now — installing it when the machine has none — so a + * session that comes later does not wait for the download. A failure is + * only logged: the next session asks again, and reports it then. + */ + async prepare(): Promise { + try { + await this.entryPoint(); + } catch (error) { + this.pi.log(`[pi] the Pi runtime is not ready yet: ${error instanceof Error ? error.message : String(error)}`); + } + } + + /** + * Pi's own version, from its package's manifest. An operator's own CLI + * counts too: its entry is followed through symlinks to the package it + * belongs to. Undefined when no Pi manifest is above it. + */ + async version(): Promise { + if (this.knownVersion !== undefined) return this.knownVersion; + try { + // Only a found version is kept: one the tree cannot tell yet may be + // readable once an install finishes. + this.knownVersion = await packageVersionOf(await this.entryPoint(), '@earendil-works/pi-coding-agent'); + } catch { + // No runtime yet: the line goes without. + } + return this.knownVersion; + } + + /** Forget the resolved entry point. Called on host shutdown. */ + async close(): Promise { + this.entry = null; + } +} diff --git a/packages/agent-host/src/drivers/pi/style.ts b/packages/agent-host/src/drivers/pi/style.ts new file mode 100644 index 00000000..8e3a3e0c --- /dev/null +++ b/packages/agent-host/src/drivers/pi/style.ts @@ -0,0 +1,28 @@ +/** + * How Pi's sessions look on the phone, taken from Pi's own terminal UI. + * + * Three values are quoted from the installed package: the loader's frame set + * and pace (`@earendil-works/pi-tui` `dist/components/loader.js`), the coral + * of its logo (`dist/modes/interactive/components/pi-logo.js`, `rgb(228, 138, + * 122)`) and the half-block logo itself. Pi's tool rows are bordered boxes + * with a title line rather than a glyph per kind, so none is set; its working + * line is the loader's message with no elapsed-time counter, so none is set + * either. + */ +import type { AgentInfo } from '../../sdk/types'; + +/** The generated shape `AgentInfo.style` carries. */ +type AgentStyle = NonNullable; + +export const PI_STYLE: AgentStyle = { + // The loader's DEFAULT_FRAMES and DEFAULT_INTERVAL_MS: ten braille frames, + // one every 80 ms, played forward. + spinner: { frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'], intervalMs: 80 }, + // The logo's coral, the mark's own colour (the theme's `accent` token is a + // violet used for selection; the brand mark stays fixed across themes). + accent: '#E48A7A', + // pi-logo.js draws a four-cell, two-line mark: coral and blue on the top + // line, blue and yellow on the bottom. The phone paints a mark in one + // colour, so it keeps the shape and not the three brand tones. + wordmark: ['▀▀█ ', '█▀ █'], +}; diff --git a/packages/agent-host/src/drivers/pi/tools.ts b/packages/agent-host/src/drivers/pi/tools.ts new file mode 100644 index 00000000..ff37dc32 --- /dev/null +++ b/packages/agent-host/src/drivers/pi/tools.ts @@ -0,0 +1,62 @@ +/** + * Pi's built-in tool names, and what each one is. + * + * The names are the ones the CLI registers in its own tool table + * (`dist/core/tools/index.js`, `allToolNames`): `read`, `bash`, `powershell`, + * `edit`, `write`, `grep`, `find` and `ls`. Which of them a session has is the + * profile's `defaultTools` setting — `read`, `bash`, `edit` and `write` unless + * it says otherwise — but the table covers all of them, since an operator's + * settings may enable any. Extensions and MCP servers add names no table can + * know; those read from their own arguments through the shared reader. + * + * Pi's argument spellings are its own: a file tool names `path` (not + * `file_path`), an edit carries `edits: [{oldText, newText}]`, and the + * search tools match a glob `pattern`. + */ +import { oneLine, readToolCall, str, ToolKind, type ToolCallRead, type ToolDialects } from '../../sdk/tools'; + +type Input = Record; + +/** The file a call names; Pi spells it `path` in every file tool. */ +const fileOf = (input: Input): string => str(input.path); + +/** A file change shows its diff, which carries the content itself, so the + * arguments are not repeated under the title. */ +const diffShowsIt = (): undefined => undefined; + +const runTitle = (input: Input): string => oneLine(str(input.command)); + +/** Every built-in name Pi answers to: the table the drift test reads, and what + * `piTool` falls back to when a call's arguments say nothing. */ +export const PI_TOOLS: ToolDialects = { + // --- running things --- + // `bash` runs Git Bash on Windows; `powershell` is the other shell tool a + // profile may enable instead of or beside it. + bash: { kind: ToolKind.Execute, title: runTitle, detail: (input) => str(input.command) }, + powershell: { kind: ToolKind.Execute, title: runTitle, detail: (input) => str(input.command) }, + + // --- files --- + read: { kind: ToolKind.Read, title: fileOf }, + write: { kind: ToolKind.Edit, title: fileOf, detail: diffShowsIt }, + edit: { kind: ToolKind.Edit, title: fileOf, detail: diffShowsIt }, + + // --- searching --- + grep: { kind: ToolKind.Search, title: (input) => str(input.pattern) }, + find: { kind: ToolKind.Search, title: (input) => str(input.pattern) }, + + // --- the directory --- + ls: { kind: ToolKind.Read, title: (input) => fileOf(input) || '.' }, +}; + +/** + * The tools this driver's `ask` mode runs without a card: Pi's own read-only + * set, the same four `--tools read,grep,find,ls` selects. A call to any other + * tool — including one an operator's extension registered — asks. + */ +export const PI_READ_ONLY_TOOLS: ReadonlySet = new Set(['read', 'grep', 'find', 'ls']); + +/** Read one of this agent's tool calls. `report` is told a name this table + * does not list (`unknownToolReporter`). */ +export function piTool(toolName: string, input: Input, report?: (toolName: string) => void): ToolCallRead { + return readToolCall(PI_TOOLS, toolName, input, report); +} diff --git a/packages/agent-host/src/host/__tests__/modules.test.ts b/packages/agent-host/src/host/__tests__/modules.test.ts index 8ca8c852..51653b03 100644 --- a/packages/agent-host/src/host/__tests__/modules.test.ts +++ b/packages/agent-host/src/host/__tests__/modules.test.ts @@ -6,14 +6,20 @@ import { DRIVER_MODULES, selectModules } from '../modules'; describe('selectModules', () => { it('loads every agent but the test ones by default, in catalog order', () => { - expect(selectModules({}, () => {}).map((m) => m.id)).toEqual(['opencode', 'claude-code', 'deepseek-harness', 'qwen-code']); + expect(selectModules({}, () => {}).map((m) => m.id)).toEqual([ + 'opencode', + 'claude-code', + 'deepseek-harness', + 'qwen-code', + 'pi', + ]); }); it('loads what CODEDECK_AGENT_HOST_DRIVERS names, in its order, and skips an unknown id', () => { const log: string[] = []; - const picked = selectModules({ CODEDECK_AGENT_HOST_DRIVERS: ' fake, pi ,opencode' }, (m) => log.push(m)); - expect(picked.map((m) => m.id)).toEqual(['fake', 'opencode']); - expect(log).toEqual(["[agent-host] unknown driver 'pi' — skipped"]); + const picked = selectModules({ CODEDECK_AGENT_HOST_DRIVERS: ' fake, gemini ,pi,opencode' }, (m) => log.push(m)); + expect(picked.map((m) => m.id)).toEqual(['fake', 'pi', 'opencode']); + expect(log).toEqual(["[agent-host] unknown driver 'gemini' — skipped"]); }); it('module ids are unique', () => { diff --git a/packages/agent-host/src/host/modules.ts b/packages/agent-host/src/host/modules.ts index 2f2c5001..c39c1929 100644 --- a/packages/agent-host/src/host/modules.ts +++ b/packages/agent-host/src/host/modules.ts @@ -7,10 +7,11 @@ import { claudeModule } from '../drivers/claude/module'; import { deepSeekModule } from '../drivers/deepseek/module'; import { fakeModule } from '../drivers/fake/module'; import { openCodeModule } from '../drivers/opencode/module'; +import { piModule } from '../drivers/pi/module'; import { qwenModule } from '../drivers/qwen/module'; import type { DriverModule } from '../sdk/module'; -export const DRIVER_MODULES: readonly DriverModule[] = [openCodeModule, claudeModule, deepSeekModule, qwenModule, fakeModule]; +export const DRIVER_MODULES: readonly DriverModule[] = [openCodeModule, claudeModule, deepSeekModule, qwenModule, piModule, fakeModule]; /** * The modules `CODEDECK_AGENT_HOST_DRIVERS` (comma-separated ids) asks for, diff --git a/packages/agent-host/src/sdk/tools.ts b/packages/agent-host/src/sdk/tools.ts index 1c5e6530..16e03b68 100644 --- a/packages/agent-host/src/sdk/tools.ts +++ b/packages/agent-host/src/sdk/tools.ts @@ -72,6 +72,14 @@ function hasAny(input: Input, keys: readonly string[]): boolean { return keys.some((key) => has(input, key)); } +/** Whether a call carries replacements as a list (`edits: [{oldText, + * newText}]`): Pi's editor and Claude Code's MultiEdit spell their changes + * this way, so a path plus a non-empty list is a file change even though no + * single text key holds a string. */ +function hasEdits(input: Input): boolean { + return Array.isArray(input.edits) && input.edits.length > 0; +} + /** The file a call names, under any of the spellings these agents use: * Claude Code and the DeepSeek Harness say `file_path`, OpenCode v2 `path`, * and a notebook has a path of its own. */ @@ -121,7 +129,7 @@ const CALL_PATTERNS: readonly CallPattern[] = [ // A file change: a path, and the text that goes in it. { kind: ToolKind.Edit, - matches: (input) => callPath(input) !== '' && hasAny(input, EDIT_TEXT_KEYS), + matches: (input) => callPath(input) !== '' && (hasAny(input, EDIT_TEXT_KEYS) || hasEdits(input)), title: callPath, }, // Something to find: a pattern, and where to look for it. From d8955deaaa3ef86d680b82b2fa88b1f1dff70ccd Mon Sep 17 00:00:00 2001 From: deymosh <232244450+deymosh@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:32:40 +0100 Subject: [PATCH 3/8] feat(agent-host): run Pi in the live probe MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `live pi` binds the local fake model to the session as a provider profile, which is exactly the shape the bridge gives a real one, and names its model under the profile's id — the selector Pi's startup resolves after the driver's extension has registered it. The probe's agent lists and the weekly release watch know the package too. Verified against Pi 1.5.2 with the fake model: the install-on-demand tree boots, hello is echoed, the scripted tool call raises a permission card and runs once allowed, and a /question prompt answers that the request offers no question tool (Pi ships none). Co-Authored-By: Claude Code --- .github/workflows/agent-updates.yml | 2 +- codedeck | 4 ++-- packages/agent-host/tools/live-probe.mjs | 9 +++++++-- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/.github/workflows/agent-updates.yml b/.github/workflows/agent-updates.yml index e6456ac1..026765ac 100644 --- a/.github/workflows/agent-updates.yml +++ b/.github/workflows/agent-updates.yml @@ -35,7 +35,7 @@ jobs: set -euo pipefail title='Agent updates available' # The agents' own packages, and the ACP types their drivers use. - packages='@anthropic-ai/claude-agent-sdk @opencode/client @opencode/cli @deepseek-ai/dsh @qwen-code/qwen-code @agentclientprotocol/sdk' + packages='@anthropic-ai/claude-agent-sdk @opencode/client @opencode/cli @deepseek-ai/dsh @qwen-code/qwen-code @earendil-works/pi-coding-agent @agentclientprotocol/sdk' rows='' for name in $packages; do pinned=$(jq -r --arg n "$name" '(.dependencies + .devDependencies)[$n] // empty' packages/agent-host/package.json | sed 's/^[\^~]//') diff --git a/codedeck b/codedeck index e130d33c..bfcfb1a2 100755 --- a/codedeck +++ b/codedeck @@ -324,7 +324,7 @@ a Docker-less host: --persona ID, --cwd DIR, --env K=V (agent paths and keys), --timeout SECONDS (default 300), --no-sync agents: claude-code, opencode, deepseek-harness, - qwen-code, and `fake` for the driver-protocol + qwen-code, pi, and `fake` for the driver-protocol test agent live --fake-model Point the agent at a local model server instead @@ -1290,7 +1290,7 @@ cmd_live() { echo " background sub-agent or a late notification does" >&2 echo " CODEDECK_DEBUG_EVENTS=1 (via --env) logs every raw agent event the" >&2 echo " OpenCode driver received, with the session each names" >&2 - echo "agents: claude-code, opencode, deepseek-harness, qwen-code, fake" >&2 + echo "agents: claude-code, opencode, deepseek-harness, qwen-code, pi, fake" >&2 exit 2 ;; esac diff --git a/packages/agent-host/tools/live-probe.mjs b/packages/agent-host/tools/live-probe.mjs index 86675ed2..567e9659 100644 --- a/packages/agent-host/tools/live-probe.mjs +++ b/packages/agent-host/tools/live-probe.mjs @@ -80,7 +80,8 @@ const FLAGS = new Set(['models', 'fake-model']); * * Qwen Code takes a profile the way the phone hands one over: the driver's * `set-providers` writes it into Qwen Code's own settings, so the probe sends - * that frame (see `main`) and names the profile's model. + * that frame (see `main`) and names the profile's model. Pi binds a profile + * to a session; its driver registers it through the extension it writes. */ function fakeModelSession(agent, url) { const provider = { @@ -105,6 +106,10 @@ function fakeModelSession(agent, url) { // session therefore keeps its own default name while every request // still goes to the stub — nothing is spent on that name. return { provider }; + case 'pi': + // Pi's driver registers the profile through the extension it writes, + // and names the profile's model as `/` at startup. + return { provider, model: FAKE_MODEL_ID }; case 'opencode': { // `aisdk:@ai-sdk/openai-compatible` is the package the driver uses for // an endpoint OpenCode's own catalog does not know. @@ -192,7 +197,7 @@ async function main() { if (args['fake-model'] && args.agent === 'fake') { // Nothing to point and no model to name: the fake agent answers from the // prompt itself, and a server behind it would be decoration. - say('model: the fake agent runs no model, so --fake-model has nothing to do (it is for claude-code, opencode, deepseek-harness and qwen-code)'); + say('model: the fake agent runs no model, so --fake-model has nothing to do (it is for claude-code, opencode, deepseek-harness, qwen-code and pi)'); } else if (args['fake-model']) { fakeModel = await startFakeModel({ log: (line) => say(`model: ${line}`), dump: args.dump ?? null }); fakeSession = fakeModelSession(args.agent, fakeModel.url); From 5687c1ba4aced9e09b72e8327744c2a8c009a21a Mon Sep 17 00:00:00 2001 From: deymosh <232244450+deymosh@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:41:34 +0100 Subject: [PATCH 4/8] docs: document the Pi driver docs/PI.md says how Pi gets installed and a model (a provider profile, or Pi's own providers through the bridge's environment or its own login in CODEDECK_PI_HOME), what the permission gate CodeDeck writes into every session asks about in Ask and YOLO, how reasoning and mid-turn messages map, and what Pi does not have. The agent lists in the README, BRIDGE.md, PROTOCOL.md, AGENT-CANDIDATES.md, CLAUDE.md and the verify-changes skill name Pi beside the others. Co-Authored-By: Claude Code --- .claude/CLAUDE.md | 15 +-- .claude/skills/verify-changes/SKILL.md | 1 + README.md | 6 +- docs/AGENT-CANDIDATES.md | 2 + docs/BRIDGE.md | 6 +- docs/PI.md | 140 +++++++++++++++++++++++++ docs/PROTOCOL.md | 8 +- 7 files changed, 164 insertions(+), 14 deletions(-) create mode 100644 docs/PI.md diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index d9bc9bb8..26038542 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -5,7 +5,7 @@ Guidance for Claude Code (claude.ai/code) when working in this repository. ## Project identity CodeDeck+ is a community-maintained continuation of CodeDeck Next: run coding -agents (Claude Code, OpenCode, DeepSeek Harness, Qwen Code) on a laptop/VPS ("the bridge") and drive them +agents (Claude Code, OpenCode, DeepSeek Harness, Qwen Code, Pi) on a laptop/VPS ("the bridge") and drive them from an Android phone over end-to-end-encrypted Nostr. It started as a merge of the two upstream projects (`codedeck-next-bridge`, `codedeck-next-mobile`) and has since been rebuilt: the protocol, the bridge and the phone's core are Rust; @@ -181,18 +181,19 @@ credentials (`--env` is for the agent's own paths, not its keys). 1. **`live fake`** — the scripted test agent: the driver protocol's own plumbing, with no SDK and no model at all. 2. **`live --fake-model`** — a real agent (claude-code, opencode, - deepseek-harness, qwen-code) against a local model server + deepseek-harness, qwen-code, pi) against a local model server (`packages/agent-host/tools/fake-model.mjs`). The session is real, the model is not: each prompt is a scenario — `/tool` (a tool call; OpenCode - asks permission for it), `/question` (a question form), `/plan-approval` + and Pi ask permission for it), `/question` (a question form), `/plan-approval` (a plan card), `/error` (an API failure), `/long` (a long answer and a large context) — and anything else is echoed. Nothing reaches an account, - and CI runs the same thing for claude-code - (`src/drivers/claude/__tests__/claudeFakeModel.test.ts`). + and CI runs the same thing for claude-code and pi + (`src/drivers/claude/__tests__/claudeFakeModel.test.ts`, + `src/drivers/pi/__tests__/piFakeModel.test.ts`). 3. **A real model** — OpenCode on its free Zen models (`--model opencode/cat-jam-free`) for fidelity, since only a real model chooses its own tool arguments and writes prose. Everything else on - claude-code, deepseek-harness or qwen-code spends the account. The + claude-code, deepseek-harness, qwen-code or pi spends the account. The commands for each tier are in the verify-changes skill. ### Tests @@ -332,7 +333,7 @@ crates/protocol the phone wire: messages, total codec, kinds, ranges, │ workspace, uploads, direct link, CLI. │ │ stdio (driver protocol) │ packages/agent-host Node: one driver per agent - │ (opencode, claude, deepseek, qwen, fake) around + │ (opencode, claude, deepseek, qwen, pi, fake) around │ its SDK. │ packages/vscode-extension installs a release's │ bridge (sha256 baked in at release), runs it on diff --git a/.claude/skills/verify-changes/SKILL.md b/.claude/skills/verify-changes/SKILL.md index 9f2b530c..7bfaa2a5 100644 --- a/.claude/skills/verify-changes/SKILL.md +++ b/.claude/skills/verify-changes/SKILL.md @@ -135,6 +135,7 @@ tiers, cheapest first — pick by what needs proving: ./codedeck live opencode --fake-model --prompt /question --prompt /long ./codedeck live deepseek-harness --fake-model --prompt /error ./codedeck live qwen-code --fake-model --prompt /tool +./codedeck live pi --fake-model --prompt /tool # 3. A real model. Free on OpenCode's Zen models; anything else spends the account. ./codedeck live opencode --model opencode/cat-jam-free --prompt "Reply with exactly: ok" diff --git a/README.md b/README.md index 58ab3aa3..5590468a 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ # CodeDeck+ -**Control coding agents (OpenCode, Claude Code, DeepSeek Harness, Qwen Code) +**Control coding agents (OpenCode, Claude Code, DeepSeek Harness, Qwen Code, Pi) running on your laptop or VPS from your Android phone, over end-to-end encrypted Nostr.** No accounts and no CodeDeck server: the phone and the bridge pair by scanning a QR code and talk through ordinary Nostr relays — public ones, or @@ -44,7 +44,8 @@ Pairing is a one-time QR scan; it survives restarts on both ends. - [OpenCode](https://opencode.ai) (the default, installed on first start), Claude Code, the [DeepSeek Harness](https://www.deepseek.com/en/harness/) and - [Qwen Code](https://github.com/QwenLM/qwen-code) (installed from the phone + [Qwen Code](https://github.com/QwenLM/qwen-code) and + [Pi](https://github.com/earendil-works/pi) (installed from the phone when chosen), picked per session — the protocol is agent-neutral, so another agent is one driver away ([`docs/PROTOCOL.md`](docs/PROTOCOL.md#adding-an-agent)) @@ -247,6 +248,7 @@ the full runbook. - [`docs/CLAUDE-CODE.md`](docs/CLAUDE-CODE.md) — Claude Code: sign-in, modes and models, the 1M window, gateways and provider profiles - [`docs/DEEPSEEK.md`](docs/DEEPSEEK.md) — the DeepSeek Harness: API key, models and reasoning, gateways, MCP servers and plugins - [`docs/QWEN.md`](docs/QWEN.md) — Qwen Code: install, OpenAI-compatible providers, its home, modes, MCP servers and extensions +- [`docs/PI.md`](docs/PI.md) — Pi: install, accounts and providers, its home, the permission gate and its tiers, MCP servers and packages - [`docs/AGENT-CANDIDATES.md`](docs/AGENT-CANDIDATES.md) — which agents to add next and how - [`.claude/skills/cut-release/SKILL.md`](.claude/skills/cut-release/SKILL.md) — the release runbook diff --git a/docs/AGENT-CANDIDATES.md b/docs/AGENT-CANDIDATES.md index 82cc15ed..d378bd8a 100644 --- a/docs/AGENT-CANDIDATES.md +++ b/docs/AGENT-CANDIDATES.md @@ -56,6 +56,8 @@ install a gate (an extension hooking tool calls) that routes each call to unasked. A pure-JS package with ~23 dependencies: installs as a package tree, like the DeepSeek Harness. Prefer the RPC mode: it keeps the agent out of the host's process and is the same surface Oh My Pi speaks (below). +**Added** (`drivers/pi/`, see [PI.md](PI.md)): over RPC, with the gate as an +extension the driver writes into every session. **GitHub Copilot CLI** (`@github/copilot`, proprietary). Reaches everyone who has Copilot through an employer or the free tier. Speaks ACP diff --git a/docs/BRIDGE.md b/docs/BRIDGE.md index 82b2b5ad..832a8521 100644 --- a/docs/BRIDGE.md +++ b/docs/BRIDGE.md @@ -1,7 +1,7 @@ # The bridge The bridge runs coding agents (OpenCode, Claude Code, the DeepSeek -Harness and Qwen Code) on your laptop or VPS and serves them to the CodeDeck+ Android app +Harness, Qwen Code and Pi) on your laptop or VPS and serves them to the CodeDeck+ Android app over end-to-end encrypted Nostr (NIP-44). No accounts and no central server: the phone and the bridge pair by scanning a QR code. @@ -124,6 +124,8 @@ asked for: `CODEDECK_DEEPSEEK_PATH` names a CLI to use instead. - **Qwen Code**: a package tree too (`@qwen-code/qwen-code`); `CODEDECK_QWEN_PATH` names a CLI to use instead. +- **Pi**: a package tree too (`@earendil-works/pi-coding-agent`); + `CODEDECK_PI_PATH` names a CLI to use instead. Every download comes from the npm registry and is checked against the sha512 in this build's `pnpm-lock.yaml`; a mismatch is refused. Binaries live in @@ -140,7 +142,7 @@ for it. - Ahead of time: `codedeck-bridge agents install …` installs from the terminal, into the same cache, before any phone asks. - Offline machines: install `claude` (or `opencode`) yourself and it is used - as is, point `CODEDECK_DEEPSEEK_PATH` (or `CODEDECK_QWEN_PATH`) at one you + as is, point `CODEDECK_DEEPSEEK_PATH` (or `CODEDECK_QWEN_PATH`, `CODEDECK_PI_PATH`) at one you installed, or copy an `agents/` directory from another machine. - A mirror: `CODEDECK_NPM_REGISTRY=https://…` (the sha512 still applies). diff --git a/docs/PI.md b/docs/PI.md new file mode 100644 index 00000000..67a81397 --- /dev/null +++ b/docs/PI.md @@ -0,0 +1,140 @@ +# Pi backend + +[Pi](https://github.com/earendil-works/pi) runs over its RPC mode +(`pi --mode rpc`: JSON lines on stdio), one Pi process per session. The +driver is `packages/agent-host/src/drivers/pi/`. + +## Getting it running + +Nothing to install by hand: `@earendil-works/pi-coding-agent` is installed on +demand at the version and sha512 `pnpm-lock.yaml` pins, into `/agents/` +— Install on the phone, or `codedeck-bridge agents install pi`. It is a +pure-JS package tree, like the DeepSeek Harness's. `CODEDECK_PI_PATH` names a +CLI of your own to use instead (its `cli.js`, run with the bridge's Node, or +an executable). + +A session needs a model Pi can reach, any of: + +- **An account** connected on the phone (the agent's page → Accounts): an + API key for any of Pi's providers, or a sign-in to a subscription where + Pi has one (Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot, xAI and + others). Pi's own code stores it, in its home (below), exactly where its + `/login` would. The model picker then lists that provider's models. +- **A provider profile** added on the phone (the agent's page → AI + providers): any OpenAI-compatible endpoint. A session bound to one runs on + it, and its models are the ones the picker offers. +- **The bridge's environment**: the keys Pi reads itself, such as + `ANTHROPIC_API_KEY` or `OPENROUTER_API_KEY`. Accounts shows them as the + machine's, which only the machine can change. + +## Accounts + +The list is Pi's own: every provider the installed Pi knows, with a key +form where Pi takes a key and a sign-in where it has one. A key is checked +by Pi only when a session uses it. + +A sign-in gives a page to open on any device. Some providers then show a +code to enter there and finish on their own; the others send the browser +back to an address on the bridge's machine, which a phone cannot open: paste +the address it fails to load, and Pi finishes the sign-in with it. A +provider whose login asks something more than a key or a sign-in (a +resource name, a region) is refused with Pi's question — run Pi's own +`/login` on the machine for it. + +## Its own home + +Pi's settings, credentials, models and conversations live in the directory +the driver points `PI_CODING_AGENT_DIR` at: `CODEDECK_PI_HOME`, else a `pi` +directory beside the agent cache. Pi in a terminal shares all of it when +pointed there (`PI_CODING_AGENT_DIR=`): accounts, MCP +servers and packages added either way are there for both. Conversations are files under its `sessions/`, which is what a session +resumes from after a restart and what deleting a conversation removes. + +A profile's token never touches a file: the driver hands the session's +process the profile in one environment variable and the token in another, +which the registration names (`$CODEDECK_PI_PROVIDER_TOKEN`), so Pi reads +the token from its own environment. + +Pi runs with `--offline`, version checks and telemetry off: it makes no +network request of its own beyond the model's. Its model catalog is therefore +the one its release shipped with, plus your own `models.json`. + +## Permissions + +Pi has no permission system of its own: it runs every tool call it decides +on. CodeDeck installs an extension into every session — +`/codedeck/codedeck-pi.js`, rewritten when the bridge's version of it +changes and loaded with `-e` — that holds each tool call until the phone +answers: + +- **Ask** (the default): a card for every tool call, except Pi's read-only + tools (`read`, `grep`, `find`, `ls`), which run without one. The card + offers Allow, Allow `` for this session, and Deny; a denied call + never runs, and Pi tells the model it was denied. A tool that another + extension or an MCP server adds asks like any other. +- **Auto edit**: Pi's own file tools (`edit`, `write`) also run without a + card; a command, and any tool an extension or an MCP server adds, still + asks. +- **YOLO**: every tool call runs without a card. + +What "for this session" allows is kept by the session only: Pi saves no +rules, so the next session asks again. + +## Reasoning and messages + +Reasoning is Pi's thinking level: Off, Minimal, Low, Medium (Pi's default), +High, Extra high, Max. A model without one of them runs at the nearest it +has, as in Pi's own terminal UI. + +A message sent while a turn runs is steered into that turn: Pi hands it to +the model after the tool calls in flight, before its next request. Stop +aborts the turn and answers any card still open as cancelled. + +When a request fails and Pi retries it, the session shows one line per +retry instead of an error; only an error Pi gives up on, or one it does not +retry, is shown as an error. + +Dialogs that your own Pi extensions open (`select`, `confirm`, `input`, +`editor`) reach the phone as question cards; their notifications show as a +status line in the session. + +## MCP servers + +The MCP screen manages the `mcpServers` of `mcp.json` in Pi's home, the file +`pi mcp add` and `/mcp` edit. Stdio and streamable HTTP servers only: Pi +rejects the legacy SSE transport, and server names other than letters, +digits, `_` and `-`. Switching one off keeps it with Pi's own +`enabled: false`. A Pi process connects its servers as its session starts: +a change applies to the sessions started after it, and a session's MCP +panel shows a server changed since as not loaded yet. Env and header values +are kept in the file, which is written readable by its owner only on Linux +and macOS. + +## Packages + +The Plugins screen manages Pi's packages, through Pi's own `pi install`, +`pi update` and `pi remove`. A package bundles extensions, skills, prompt +templates and themes from npm (`npm:`), git (`git:github.com/…` or +a URL) or a path, and is how Pi gains tools it does not ship — subagents, +LSP diagnostics and the like come from packages rather than from CodeDeck. +A package runs code with the bridge's permissions: install only ones you +trust. An npm package needs `npm` on the machine (the container image has +it, a release archive does not); `CODEDECK_NPM_REGISTRY` is passed on to it. +Packages cannot be switched off, only removed; sessions started after a +change load it. + +## What this does not have + +- **No question or plan tool**: Pi has neither, so the session shows no + question forms or plan cards of its own. +- **No subscription usage** to ask for (the context meter still works), no + background tasks and no saved permission rules. +- **Accounts need Pi's package**: with `CODEDECK_PI_PATH` naming an + executable rather than a `cli.js`, they cannot be listed or changed. + +## Offline and container notes + +Like the DeepSeek Harness it is a package tree in the `agents` volume. A host +without npm registry access installs it from a copied `agents/` directory, +points `CODEDECK_NPM_REGISTRY` at a mirror, or points `CODEDECK_PI_PATH` at +its own. diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index db05e851..9996a36d 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -1010,9 +1010,11 @@ restart. environment, and its runtime (what the machine already has, and how to install the pinned one). Add it to the list in `src/host/modules.ts`; it is enabled through `CODEDECK_AGENT_HOST_DRIVERS`. - The host ships four: `drivers/opencode/`, `drivers/claude/`, - `drivers/deepseek/` and `drivers/qwen/` (the last two over the shared - `acp/` machinery, which is what an ACP agent's driver reuses). + The host ships five: `drivers/opencode/`, `drivers/claude/`, + `drivers/deepseek/`, `drivers/qwen/` (those two over the shared `acp/` + machinery, which is what an ACP agent's driver reuses) and `drivers/pi/` + (Pi's own RPC mode, with an extension the driver writes for the + permission gate). 4. Test it beside the driver, in `src/drivers//__tests__/`, like `drivers/claude/__tests__/claudeDriver.test.ts` and `drivers/opencode/__tests__/opencodeDriver.test.ts` do, with the From b3712ed59b98c6db0c964d6729eb964bd860b19f Mon Sep 17 00:00:00 2001 From: deymosh <232244450+deymosh@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:09:24 +0100 Subject: [PATCH 5/8] feat(agent-host): connect Pi's provider accounts from the phone Pi had no way to get a key from the phone: a session needed a provider profile, a key in the bridge's environment or Pi's own login on the machine. The driver now advertises `supports.accounts` and manages them with Pi's own code, so a key or a sign-in lands where Pi's /login keeps it (auth.json in Pi's home, under Pi's own lock, which a running Pi that refreshes a token also takes). A short-lived helper process (authHelper.ts, serialised like the extension and run with the host's node) loads the installed Pi's bundle and drives its ModelRuntime: getProviders for the list (43 providers in 1.5.2, nine with a subscription sign-in) with each one's auth status, login(api_key) with its secret prompt answered for a key, login(oauth) for a sign-in, logout for a removal. The key reaches the helper on stdin, never in its arguments or environment. A sign-in's page becomes a paste-back attempt whose pasted address answers Pi's manual_code prompt; a device code becomes a code to enter. A login that asks anything else is refused with Pi's own question. Errors are redacted of the key and the pasted address. After a change the model list is read again. Tests: listing, storing and removing run the real helper against the pinned Pi (local file operations only); the sign-in flow runs on a scripted helper. The redaction test was proven by removing it once. Co-Authored-By: Claude Code --- .../drivers/pi/__tests__/piAccounts.test.ts | 244 ++++++++++ .../src/drivers/pi/__tests__/piDriver.test.ts | 1 + .../agent-host/src/drivers/pi/accounts.ts | 429 ++++++++++++++++++ .../agent-host/src/drivers/pi/authHelper.ts | 192 ++++++++ packages/agent-host/src/drivers/pi/driver.ts | 17 + 5 files changed, 883 insertions(+) create mode 100644 packages/agent-host/src/drivers/pi/__tests__/piAccounts.test.ts create mode 100644 packages/agent-host/src/drivers/pi/accounts.ts create mode 100644 packages/agent-host/src/drivers/pi/authHelper.ts diff --git a/packages/agent-host/src/drivers/pi/__tests__/piAccounts.test.ts b/packages/agent-host/src/drivers/pi/__tests__/piAccounts.test.ts new file mode 100644 index 00000000..3711e1bc --- /dev/null +++ b/packages/agent-host/src/drivers/pi/__tests__/piAccounts.test.ts @@ -0,0 +1,244 @@ +/** + * Pi's accounts. Listing, storing a key and removing it run the real helper + * against the Pi this workspace pins (all three are local file operations, + * no network), so what is checked is what Pi itself stores and reports. A + * sign-in needs a provider's own server, so its flow runs on a scripted + * helper that speaks the helper's records. + */ +import { EventEmitter } from 'node:events'; +import { existsSync, mkdtempSync, readFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import * as path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import type { SignInState } from '../../../sdk/driver'; +import { PiAccounts } from '../accounts'; +import { bundledPiExecutable } from '../install'; + +const piPath = bundledPiExecutable(); +if (!piPath) console.warn('piAccounts: no Pi CLI beside the workspace — skipping the real-helper tests'); +const real = piPath ? describe : describe.skip; + +function accounts(env: Record = {}): { accounts: PiAccounts; home: string; changes: number[] } { + const home = mkdtempSync(path.join(tmpdir(), 'codedeck-pi-accounts-')); + const changes: number[] = []; + const manager = new PiAccounts({ + home, + entryPoint: async () => piPath!, + env: () => ({ PATH: process.env.PATH ?? '', SystemRoot: process.env.SystemRoot ?? '', PI_CODING_AGENT_DIR: home, ...env }), + changed: () => changes.push(1), + }); + return { accounts: manager, home, changes }; +} + +const noEnd = (): void => {}; + +real('Pi accounts, through the installed Pi', () => { + it('lists every provider Pi knows with its ways to connect, and only connected ones by default', async () => { + const { accounts: manager } = accounts(); + const all = await manager.list(true); + const openrouter = all.find((account) => account.id === 'openrouter'); + expect(openrouter?.methods).toContainEqual(expect.objectContaining({ id: 'key', kind: 'key' })); + const anthropic = all.find((account) => account.id === 'anthropic'); + expect(anthropic?.methods).toContainEqual(expect.objectContaining({ id: 'sign-in', kind: 'sign-in' })); + expect(await manager.list(false)).toEqual([]); + }, 60_000); + + it('stores a key where Pi keeps it, shows it without the secret, and removes it', async () => { + const { accounts: manager, home, changes } = accounts(); + const result = await manager.change('openrouter', { kind: 'key', method: 'key', key: 'sk-or-codedeck-test' }, noEnd); + expect('accounts' in result && result.accounts).toEqual([ + expect.objectContaining({ + id: 'openrouter', + connections: [expect.objectContaining({ id: 'openrouter', kind: 'key', removable: true })], + }), + ]); + expect(JSON.stringify(result)).not.toContain('sk-or-codedeck-test'); + const stored = JSON.parse(readFileSync(path.join(home, 'auth.json'), 'utf8')) as Record; + expect(stored.openrouter).toEqual({ type: 'api_key', key: 'sk-or-codedeck-test' }); + expect(changes).toHaveLength(1); + + const removed = await manager.change('openrouter', { kind: 'remove', connection: 'openrouter' }, noEnd); + expect('accounts' in removed && removed.accounts).toEqual([]); + expect(JSON.parse(readFileSync(path.join(home, 'auth.json'), 'utf8'))).toEqual({}); + expect(changes).toHaveLength(2); + }, 60_000); + + it('shows a key from the machine’s environment as the machine’s, and will not remove it', async () => { + const { accounts: manager, home } = accounts({ OPENROUTER_API_KEY: 'sk-or-env' }); + const listed = await manager.list(false); + expect(listed).toEqual([ + expect.objectContaining({ id: 'openrouter', connections: [expect.objectContaining({ kind: 'env' })] }), + ]); + expect(JSON.stringify(listed)).not.toContain('sk-or-env'); + const connection = listed[0]!.connections![0]!.id; + await expect(manager.change('openrouter', { kind: 'remove', connection }, noEnd)).rejects.toThrow(/only the machine/); + expect(existsSync(path.join(home, 'auth.json')) ? readFileSync(path.join(home, 'auth.json'), 'utf8') : '{}').not.toContain('sk-or-env'); + }, 60_000); +}); + +/** A scripted helper: records what the driver sends, and answers with the + * records a test plays. */ +class ScriptedHelper { + readonly sent: Array> = []; + readonly child = Object.assign(new EventEmitter(), { + stdout: new EventEmitter(), + stderr: new EventEmitter(), + stdin: Object.assign(new EventEmitter(), { + write: (line: string): boolean => { + for (const part of line.split('\n').filter(Boolean)) this.sent.push(JSON.parse(part) as Record); + this.onSend?.(this.sent[this.sent.length - 1]!); + return true; + }, + }), + kill: (): boolean => { + this.exit(null); + return true; + }, + }); + onSend?: (record: Record) => void; + private exited = false; + + say(record: Record): void { + this.child.stdout.emit('data', Buffer.from(`${JSON.stringify(record)}\n`)); + } + + exit(code: number | null): void { + if (this.exited) return; + this.exited = true; + this.child.emit('close', code); + } +} + +function scripted(helper: ScriptedHelper, now = () => 1_000): PiAccounts { + const home = mkdtempSync(path.join(tmpdir(), 'codedeck-pi-accounts-')); + return new PiAccounts({ + home, + entryPoint: async () => path.join(home, 'dist', 'bundle', 'cli.js'), + env: () => ({}), + changed: () => {}, + spawnFn: (() => helper.child) as never, + now, + }); +} + +const tick = () => new Promise((resolve) => setImmediate(resolve)); + +describe('Pi sign-in', () => { + it('starts a paste-back sign-in, hands the pasted address to Pi, and reports the end once', async () => { + const helper = new ScriptedHelper(); + helper.onSend = (record) => { + if (record.op === 'login') { + setImmediate(() => { + helper.say({ type: 'notify', event: { type: 'auth_url', url: 'https://claude.ai/oauth/authorize?x=1' } }); + helper.say({ type: 'prompt', id: 'p1', prompt: { type: 'manual_code', message: 'Paste the redirect URL' } }); + }); + } + if (record.op === 'answer') { + setImmediate(() => { + helper.say({ type: 'done' }); + helper.exit(0); + }); + } + }; + const ends: SignInState[] = []; + const manager = scripted(helper); + const started = await manager.change('anthropic', { kind: 'sign-in', method: 'sign-in' }, (end) => ends.push(end)); + expect('signIn' in started && started.signIn).toMatchObject({ + status: 'started', + attempt: { url: 'https://claude.ai/oauth/authorize?x=1', pasteBack: true }, + }); + const attemptId = 'signIn' in started ? started.signIn.attemptId : ''; + await tick(); + await manager.change('anthropic', { kind: 'finish', attempt: attemptId, callbackUrl: 'http://localhost:53692/callback?code=abc' }, noEnd); + expect(helper.sent).toContainEqual({ op: 'answer', id: 'p1', value: 'http://localhost:53692/callback?code=abc' }); + await tick(); + await tick(); + expect(ends).toEqual([{ status: 'complete', attemptId }]); + }); + + it('keeps an address pasted before Pi asks for it, and gives it when Pi does', async () => { + const helper = new ScriptedHelper(); + helper.onSend = (record) => { + if (record.op === 'login') setImmediate(() => helper.say({ type: 'notify', event: { type: 'auth_url', url: 'https://example.com/a' } })); + }; + const manager = scripted(helper); + const started = await manager.change('xai', { kind: 'sign-in', method: 'sign-in' }, noEnd); + const attemptId = 'signIn' in started ? started.signIn.attemptId : ''; + await manager.change('xai', { kind: 'finish', attempt: attemptId, callbackUrl: 'http://localhost:1/cb?code=z' }, noEnd); + helper.say({ type: 'prompt', id: 'p7', prompt: { type: 'manual_code', message: 'Paste' } }); + expect(helper.sent).toContainEqual({ op: 'answer', id: 'p7', value: 'http://localhost:1/cb?code=z' }); + }); + + it('shows a device code to enter, and reports Pi’s failure as the end', async () => { + const helper = new ScriptedHelper(); + helper.onSend = (record) => { + if (record.op === 'login') { + setImmediate(() => + helper.say({ type: 'notify', event: { type: 'device_code', userCode: 'ABCD-1234', verificationUri: 'https://github.com/login/device', expiresInSeconds: 900 } }), + ); + } + }; + const ends: SignInState[] = []; + const manager = scripted(helper); + const started = await manager.change('github-copilot', { kind: 'sign-in', method: 'sign-in' }, (end) => ends.push(end)); + expect('signIn' in started && started.signIn.attempt).toEqual( + expect.objectContaining({ url: 'https://github.com/login/device', instructions: expect.stringContaining('ABCD-1234'), expiresAt: 1_000 + 900_000 }), + ); + expect('signIn' in started && started.signIn.attempt?.pasteBack).toBeUndefined(); + helper.say({ type: 'error', message: 'The device code expired' }); + helper.exit(1); + await tick(); + await tick(); + expect(ends).toEqual([expect.objectContaining({ status: 'failed', error: 'The device code expired' })]); + }); + + it('reports nothing after the user cancels', async () => { + const helper = new ScriptedHelper(); + helper.onSend = (record) => { + if (record.op === 'login') setImmediate(() => helper.say({ type: 'notify', event: { type: 'auth_url', url: 'https://example.com/a' } })); + }; + const ends: SignInState[] = []; + const manager = scripted(helper); + const started = await manager.change('openai', { kind: 'sign-in', method: 'sign-in' }, (end) => ends.push(end)); + const attemptId = 'signIn' in started ? started.signIn.attemptId : ''; + const cancelled = await manager.change('openai', { kind: 'cancel', attempt: attemptId }, noEnd); + expect('signIn' in cancelled && cancelled.signIn.status).toBe('cancelled'); + expect(helper.sent).toContainEqual({ op: 'cancel' }); + await tick(); + expect(ends).toEqual([]); + }); +}); + +describe('Pi key login', () => { + it('refuses a provider whose login asks more than the key, with Pi’s own question', async () => { + const helper = new ScriptedHelper(); + helper.onSend = (record) => { + if (record.op === 'login') { + setImmediate(() => helper.say({ type: 'prompt', id: 'p1', prompt: { type: 'text', message: 'Azure resource name' } })); + } + if (record.op === 'cancel') { + setImmediate(() => { + helper.say({ type: 'error', message: 'cancelled' }); + helper.exit(1); + }); + } + }; + await expect(scripted(helper).change('azure', { kind: 'key', method: 'key', key: 'k' }, noEnd)).rejects.toThrow(/Azure resource name/); + }); + + it('keeps the key out of an error Pi gives back', async () => { + const helper = new ScriptedHelper(); + helper.onSend = (record) => { + if (record.op === 'login') setImmediate(() => helper.say({ type: 'prompt', id: 'p1', prompt: { type: 'secret', message: 'Key' } })); + if (record.op === 'answer') { + setImmediate(() => { + helper.say({ type: 'error', message: 'invalid key sk-secret-value' }); + helper.exit(1); + }); + } + }; + const failure = scripted(helper).change('openrouter', { kind: 'key', method: 'key', key: 'sk-secret-value' }, noEnd); + await expect(failure).rejects.toThrow(/invalid key/); + await expect(failure).rejects.not.toThrow(/sk-secret-value/); + }); +}); diff --git a/packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts b/packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts index 3b068479..7b1d7810 100644 --- a/packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts +++ b/packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts @@ -91,6 +91,7 @@ describe('PiDriver.info', () => { providers: true, interrupt: true, commands: true, + accounts: true, plugins: false, mcp: false, tasks: false, diff --git a/packages/agent-host/src/drivers/pi/accounts.ts b/packages/agent-host/src/drivers/pi/accounts.ts new file mode 100644 index 00000000..edae7cf8 --- /dev/null +++ b/packages/agent-host/src/drivers/pi/accounts.ts @@ -0,0 +1,429 @@ +/** + * Pi's provider accounts — an API key or a subscription sign-in per + * provider — managed with Pi's own code (authHelper.ts), so they land where + * `/login` puts them (`auth.json` in Pi's home) and every Pi started after + * the change can use them, inside CodeDeck or in a terminal on that home. + * + * What Pi offers is read from the installed Pi, never from a table here: + * its providers, the key and sign-in methods each has (verified against + * 1.5.2: 43 providers, nine of them with a subscription sign-in), and where + * each one's access comes from now (stored, or the machine's environment). + * + * A key is Pi's own key login with its one `secret` prompt answered. A + * sign-in is Pi's OAuth login, which tells the user where to go — a page to + * open (`auth_url`) or a code to enter on any device (`device_code`) — and, + * for a page, asks for the address the browser lands on (`manual_code`), + * since the provider sends it back to a listener on this machine a phone + * cannot reach. A login that asks anything else is refused with Pi's own + * question: only Pi's interactive `/login` can hold that conversation. + */ +import { randomUUID } from 'node:crypto'; +import { spawn, type ChildProcess } from 'node:child_process'; +import { pathToFileURL } from 'node:url'; +import * as path from 'node:path'; +import type { AccountChangeResult, AccountManager, SignInState } from '../../sdk/driver'; +import { redactSecrets } from '../../sdk/redact'; +import type { AccountChange, AccountConnection, AccountMethod, AgentAccount } from '../../sdk/types'; +import { installPiAuthHelper } from './authHelper'; +import { PiLineDecoder, type PiRecord, type PiSpawn } from './rpc'; + +/** The method ids an account offers, one of each kind at most. */ +export const PI_KEY_METHOD = 'key'; +export const PI_SIGN_IN_METHOD = 'sign-in'; + +/** How long a sign-in that names no lifetime of its own waits for the user. */ +const SIGN_IN_LIFETIME_MS = 10 * 60_000; +/** How long one list, key or removal may take: a local process that loads + * Pi's bundle and reads one file. */ +const OPERATION_TIMEOUT_MS = 60_000; + +/** A provider as the helper lists it. */ +interface HelperProvider { + id: string; + name: string; + /** The key method's name ("Anthropic API key"), when a key can be entered. */ + key?: string; + /** The sign-in's name ("Anthropic (Claude Pro/Max)"), when there is one. */ + signIn?: string; + status?: { configured?: boolean; source?: string; label?: string }; +} + +/** One helper process: an operation sent, its records read back. */ +class HelperRun { + private readonly child: ChildProcess; + readonly finished: Promise; + private exited = false; + + constructor( + command: { command: string; args: string[]; cwd: string; env: Record }, + spawnFn: PiSpawn, + onRecord: (record: PiRecord) => void, + ) { + this.child = spawnFn(command.command, command.args, { cwd: command.cwd, env: command.env, stdio: ['pipe', 'pipe', 'pipe'] }); + const lines = new PiLineDecoder(onRecord, () => {}); + let stderr = ''; + this.child.stdout?.on('data', (chunk: Buffer) => lines.push(chunk)); + this.child.stderr?.on('data', (chunk: Buffer) => { + stderr = (stderr + chunk.toString()).slice(-2_000); + }); + this.child.stdin?.on('error', () => {}); + this.finished = new Promise((resolve, reject) => { + this.child.on('error', (error: Error) => { + this.exited = true; + reject(error); + }); + this.child.on('close', (code) => { + this.exited = true; + if (code === 0) resolve(); + else reject(new Error(stderr.trim().split('\n').pop() || `the Pi account helper exited (${code ?? 'killed'})`)); + }); + }); + this.finished.catch(() => {}); + } + + send(record: Record): void { + if (this.exited) return; + this.child.stdin?.write(`${JSON.stringify(record)}\n`); + } + + kill(): void { + if (this.exited) return; + try { + this.child.kill('SIGKILL'); + } catch { + // Already gone. + } + } +} + +/** A sign-in waiting on the user. */ +interface Attempt { + account: string; + run: HelperRun; + /** The `manual_code` prompt Pi is waiting on, when it asked. */ + pastePrompt?: string; + /** An address pasted before Pi asked for it. */ + pasted?: string; + timer: NodeJS.Timeout; + ended: (end: SignInState) => void; +} + +export interface PiAccountsOptions { + /** Pi's state root (`PI_CODING_AGENT_DIR`). */ + home: string; + /** The CLI entry point (`dist/bundle/cli.js`); the bundle's `index.js` + * beside it is what the helper loads. */ + entryPoint: () => Promise; + /** The helper's environment (secret-free apart from what the machine's + * own environment holds, which is how environment keys are seen). */ + env: () => Record; + /** Called after a change, so the model list is read again. */ + changed: () => void; + spawnFn?: PiSpawn; + now?: () => number; +} + +export class PiAccounts implements AccountManager { + private readonly attempts = new Map(); + /** What each helper said went wrong, read once it exits. */ + private readonly errors = new WeakMap string | undefined>(); + private readonly spawnFn: PiSpawn; + private readonly now: () => number; + + constructor(private readonly options: PiAccountsOptions) { + this.spawnFn = options.spawnFn ?? ((command, args, opts) => spawn(command, args, opts)); + this.now = options.now ?? Date.now; + } + + async list(all: boolean): Promise { + let listed: PiRecord | undefined; + await this.once({ op: 'list' }, (record) => { + if (record.type === 'list') listed = record; + }); + const providers = Array.isArray(listed?.providers) ? (listed.providers as HelperProvider[]) : []; + const stored = new Map(); + for (const raw of Array.isArray(listed?.credentials) ? listed.credentials : []) { + const credential = raw as { providerId?: unknown; type?: unknown }; + if (typeof credential.providerId === 'string' && typeof credential.type === 'string') { + stored.set(credential.providerId, credential.type); + } + } + return providers + .map((provider) => toAccount(provider, stored.get(provider.id))) + .filter((account) => all || (account.connections?.length ?? 0) > 0) + .sort((a, b) => a.name.localeCompare(b.name)); + } + + async change(account: string, change: AccountChange, ended: (end: SignInState) => void): Promise { + try { + switch (change.kind) { + case 'key': + await this.storeKey(account, change.key); + this.options.changed(); + return { accounts: await this.list(false) }; + case 'remove': + if (change.connection !== account) { + throw new Error("That access comes from the machine's own environment or Pi's configuration; only the machine can change it."); + } + await this.once({ op: 'logout', provider: account }); + this.options.changed(); + return { accounts: await this.list(false) }; + case 'activate': + // Pi keeps one stored access per provider: it is the active one. + return { accounts: await this.list(false) }; + case 'sign-in': + return { signIn: await this.signIn(account, ended) }; + case 'finish': + return { signIn: this.finish(account, change.attempt, change.callbackUrl) }; + case 'cancel': + return { signIn: this.cancel(change.attempt) }; + } + } catch (error) { + // Pi's refusal may quote what it was given; a pasted address carries a + // one-time code. Neither travels back in the error. + const secrets = change.kind === 'key' ? [change.key] : change.kind === 'finish' ? [change.callbackUrl] : []; + throw new Error(redactSecrets(reason(error), secrets)); + } + } + + /** Stop every sign-in still waiting (the driver is shutting down). */ + close(): void { + for (const attempt of this.attempts.values()) { + clearTimeout(attempt.timer); + attempt.run.kill(); + } + this.attempts.clear(); + } + + private async storeKey(account: string, key: string): Promise { + let refused: string | undefined; + let answered = false; + const run = await this.start({ op: 'login', provider: account, method: 'api_key' }, (record) => { + if (record.type !== 'prompt') return; + const prompt = record.prompt as { type?: string; message?: string } | undefined; + if (prompt?.type === 'secret' && !answered) { + answered = true; + run.send({ op: 'answer', id: record.id, value: key }); + return; + } + refused = prompt?.message ?? 'a question'; + run.send({ op: 'cancel' }); + }, OPERATION_TIMEOUT_MS); + const failure = await this.outcome(run); + if (refused !== undefined) { + throw new Error(`Pi also asks "${refused}" for this provider, which only Pi's own /login can answer.`); + } + if (failure !== undefined) throw new Error(failure); + } + + private async signIn(account: string, ended: (end: SignInState) => void): Promise { + const attemptId = randomUUID(); + let begun = false; + let settle!: { resolve(state: SignInState): void; reject(error: Error): void }; + const first = new Promise((resolve, reject) => { + settle = { resolve, reject }; + }); + const run: HelperRun = await this.start({ op: 'login', provider: account, method: 'oauth' }, (record) => { + if (record.type === 'notify' && !begun) { + const started = startedAttempt(attemptId, record.event, this.now()); + if (!started) return; + begun = true; + const timer = setTimeout(() => this.end(attemptId, { status: 'expired', attemptId }), started.expiresAt - this.now()); + timer.unref?.(); + this.attempts.set(attemptId, { account, run, timer, ended }); + settle.resolve({ status: 'started', attemptId, attempt: started }); + return; + } + if (record.type !== 'prompt') return; + const prompt = record.prompt as { type?: string; message?: string } | undefined; + const id = String(record.id); + const attempt = this.attempts.get(attemptId); + if (prompt?.type === 'manual_code' && attempt) { + if (attempt.pasted !== undefined) { + run.send({ op: 'answer', id, value: attempt.pasted }); + attempt.pasted = undefined; + } else { + attempt.pastePrompt = id; + } + return; + } + // A choice or a field this flow cannot put to the phone. + run.send({ op: 'cancel' }); + const why = `Pi asks "${prompt?.message ?? 'a question'}" for this sign-in, which only Pi's own /login can answer.`; + if (begun) this.end(attemptId, { status: 'failed', attemptId, error: why }); + else settle.reject(new Error(why)); + }); + void this.outcome(run).then((failure) => { + if (failure === undefined) this.options.changed(); + if (!begun) { + // Over before it asked the user anything: a provider that needed + // nothing more, or a failure to start. + if (failure === undefined) settle.resolve({ status: 'complete', attemptId }); + else settle.reject(new Error(failure)); + return; + } + this.end(attemptId, failure === undefined ? { status: 'complete', attemptId } : { status: 'failed', attemptId, error: failure }); + }); + return first; + } + + private finish(account: string, attemptId: string, pasted: string): SignInState { + const attempt = this.attempts.get(attemptId); + if (!attempt || attempt.account !== account) throw new Error('That sign-in is over — start it again.'); + const value = pasted.trim(); + if (value === '') throw new Error('Paste the address the browser landed on.'); + if (attempt.pastePrompt !== undefined) { + attempt.run.send({ op: 'answer', id: attempt.pastePrompt, value }); + attempt.pastePrompt = undefined; + } else { + attempt.pasted = value; + } + return { status: 'started', attemptId }; + } + + private cancel(attemptId: string): SignInState { + const attempt = this.attempts.get(attemptId); + if (attempt) { + // Forgotten first, so its end is not reported a second time. + this.attempts.delete(attemptId); + clearTimeout(attempt.timer); + attempt.run.send({ op: 'cancel' }); + attempt.run.kill(); + } + return { status: 'cancelled', attemptId }; + } + + /** Report a sign-in's end once, and stop its helper. */ + private end(attemptId: string, state: SignInState): void { + const attempt = this.attempts.get(attemptId); + if (!attempt) return; + this.attempts.delete(attemptId); + clearTimeout(attempt.timer); + attempt.run.kill(); + attempt.ended(state); + } + + /** Run one operation to its end; rejects with the helper's reason. */ + private async once(record: Record, onRecord: (record: PiRecord) => void = () => {}): Promise { + const run = await this.start(record, onRecord, OPERATION_TIMEOUT_MS); + const failure = await this.outcome(run); + if (failure !== undefined) throw new Error(failure); + } + + /** Start one helper on `record`. A one-shot operation is given a time + * limit; a sign-in waits on the user, and its own expiry ends it. */ + private async start(record: Record, onRecord: (record: PiRecord) => void, timeoutMs?: number): Promise { + const entry = await this.options.entryPoint(); + if (!/\.[cm]?js$/i.test(entry)) { + throw new Error("Accounts need Pi's own package; CODEDECK_PI_PATH names an executable instead."); + } + const bundle = path.join(path.dirname(entry), 'index.js'); + const helper = installPiAuthHelper(this.options.home); + let errorText: string | undefined; + const run = new HelperRun( + { command: process.execPath, args: [helper, pathToFileURL(bundle).href], cwd: this.options.home, env: this.options.env() }, + this.spawnFn, + (line) => { + if (line.type === 'error') errorText = typeof line.message === 'string' ? line.message : 'Pi refused the change'; + onRecord(line); + }, + ); + this.errors.set(run, () => errorText); + if (timeoutMs !== undefined) { + const timer = setTimeout(() => { + errorText ??= `Pi did not finish within ${Math.round(timeoutMs / 1000)}s`; + run.kill(); + }, timeoutMs); + timer.unref?.(); + void run.finished.finally(() => clearTimeout(timer)).catch(() => {}); + } + run.send(record); + return run; + } + + /** Undefined when the operation finished, else why it did not. */ + private async outcome(run: HelperRun): Promise { + try { + await run.finished; + return this.errors.get(run)?.(); + } catch (error) { + // Not logged: the helper's stderr may quote the key it was given, and + // only the caller knows the secrets to redact before anything leaves. + return this.errors.get(run)?.() ?? reason(error); + } + } +} + +/** One provider as a phone sees it: the ways to connect it, and where its + * access comes from now — never the secret itself. */ +export function toAccount(provider: HelperProvider, storedType: string | undefined): AgentAccount { + const methods: AccountMethod[] = []; + if (provider.key) methods.push({ id: PI_KEY_METHOD, kind: 'key', label: provider.key }); + if (provider.signIn) methods.push({ id: PI_SIGN_IN_METHOD, kind: 'sign-in', label: provider.signIn }); + const connections: AccountConnection[] = []; + const status = provider.status; + if (status?.configured) { + if (status.source === 'stored') { + const signedIn = storedType === 'oauth'; + connections.push({ + id: provider.id, + label: signedIn ? (provider.signIn ?? 'Signed in') : (provider.key ?? 'API key'), + kind: signedIn ? 'sign-in' : 'key', + active: true, + removable: true, + }); + } else { + // The environment, `models.json` or a key command: the machine's own + // setup, which only the machine can change. + connections.push({ id: `${status.source ?? 'config'}:${provider.id}`, label: status.label ?? describeSource(status.source), kind: 'env' }); + } + } + return { + id: provider.id, + name: provider.name, + ...(methods.length > 0 ? { methods } : {}), + ...(connections.length > 0 ? { connections } : {}), + }; +} + +function describeSource(source: string | undefined): string { + switch (source) { + case 'environment': + return 'An environment variable'; + case 'models_json_key': + case 'models_json_command': + return "Pi's models.json"; + default: + return "Pi's own configuration"; + } +} + +/** The attempt a sign-in's first event describes, or null for an event that + * says nothing the user must act on (progress, information). */ +export function startedAttempt( + attemptId: string, + event: unknown, + now: number, +): { attemptId: string; url: string; instructions: string; expiresAt: number; pasteBack?: boolean } | null { + const e = event as { type?: string; url?: string; instructions?: string; userCode?: string; verificationUri?: string; expiresInSeconds?: number }; + if (e?.type === 'auth_url' && typeof e.url === 'string') { + return { + attemptId, + url: e.url, + instructions: + e.instructions ?? + 'Sign in in the browser. When it then fails to open a page, paste that page\'s address here.', + expiresAt: now + SIGN_IN_LIFETIME_MS, + pasteBack: true, + }; + } + if (e?.type === 'device_code' && typeof e.verificationUri === 'string' && typeof e.userCode === 'string') { + const lifetime = typeof e.expiresInSeconds === 'number' && e.expiresInSeconds > 0 ? e.expiresInSeconds * 1000 : SIGN_IN_LIFETIME_MS; + return { attemptId, url: e.verificationUri, instructions: `Enter the code ${e.userCode}`, expiresAt: now + lifetime }; + } + return null; +} + +function reason(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} diff --git a/packages/agent-host/src/drivers/pi/authHelper.ts b/packages/agent-host/src/drivers/pi/authHelper.ts new file mode 100644 index 00000000..181b037b --- /dev/null +++ b/packages/agent-host/src/drivers/pi/authHelper.ts @@ -0,0 +1,192 @@ +/** + * The helper that manages Pi's accounts with Pi's own code: a short-lived + * Node process that loads the installed Pi's bundle and drives its + * `ModelRuntime` — `getProviders`, `login`, `logout` — so a key or a + * sign-in is stored exactly as Pi's `/login` stores it (`auth.json`, under + * Pi's own lock, which a running Pi refreshing a token also takes). + * + * Like the extension (extension.ts), the function below is serialised and + * written into Pi's home (installPiAuthHelper), then run with the host's own + * `node`, so it must stay self-contained: no imports, no reference to module + * scope. The bundle's file URL is its first argument; the state root comes + * from `PI_CODING_AGENT_DIR` in its environment. + * + * It speaks JSON lines on stdio, one operation per process: + * + * in {op:"list"} out {type:"list", providers:[…], credentials:[…]} + * in {op:"login", provider, method} out {type:"notify", event} | {type:"prompt", id, prompt} + * in {op:"answer", id, value} …, then {type:"done"} + * in {op:"cancel"} out {type:"error", message} (aborted) + * in {op:"logout", provider} out {type:"done"} + * + * A key reaches it on stdin, never in its arguments or environment, which + * other processes on the machine can read. Nothing it writes carries a + * secret: a provider's status says where its key comes from, not what it is. + */ +import * as fs from 'node:fs'; +import * as path from 'node:path'; + +/** The installed Pi's bundle, as the helper uses it. */ +interface PiBundle { + ModelRuntime: { create(options: Record): Promise }; +} + +/** + * The helper's body. Keep it self-contained: see the module comment. Pi's + * bundle is imported by the generated module itself and handed in, rather + * than with `import()` in here: a transform (vitest's, for one) may rewrite + * that expression into a helper of its own, which the child does not have. + */ +export async function codedeckPiAuthHelper(pi: PiBundle): Promise { + const write = (record: unknown): void => { + process.stdout.write(JSON.stringify(record) + '\n'); + }; + const fail = (error: unknown): void => { + write({ type: 'error', message: error instanceof Error ? error.message : String(error) }); + }; + const waiting = new Map(); + const controller = new AbortController(); + let started = false; + let nextPrompt = 0; + let pending = ''; + + const run = async (command: Record): Promise => { + const dir = String(process.env.PI_CODING_AGENT_DIR || ''); + const runtime = await pi.ModelRuntime.create({ + authPath: dir + '/auth.json', + modelsPath: dir + '/models.json', + }); + try { + if (command.op === 'list') { + const providers = runtime.getProviders().map(function (provider: { + id: string; + name: string; + auth: { apiKey?: { name: string; login?: unknown }; oauth?: { name: string } }; + }) { + return { + id: provider.id, + name: provider.name, + ...(provider.auth.apiKey && provider.auth.apiKey.login ? { key: provider.auth.apiKey.name } : {}), + ...(provider.auth.oauth ? { signIn: provider.auth.oauth.name } : {}), + status: runtime.getProviderAuthStatus(provider.id), + }; + }); + const credentials = await runtime.listCredentials(); + write({ type: 'list', providers, credentials }); + return; + } + if (command.op === 'logout') { + await runtime.logout(String(command.provider)); + write({ type: 'done' }); + return; + } + if (command.op === 'login') { + await runtime.login(String(command.provider), command.method === 'oauth' ? 'oauth' : 'api_key', { + signal: controller.signal, + notify: function (event: unknown) { + write({ type: 'notify', event }); + }, + prompt: function (prompt: { type: string; message: string; placeholder?: string; options?: unknown }) { + const id = 'p' + ++nextPrompt; + write({ + type: 'prompt', + id, + prompt: { type: prompt.type, message: prompt.message, placeholder: prompt.placeholder, options: prompt.options }, + }); + return new Promise(function (resolve, reject) { + waiting.set(id, { resolve, reject }); + }); + }, + }); + write({ type: 'done' }); + return; + } + write({ type: 'error', message: 'unknown operation' }); + } finally { + await runtime.settleCredentialWrites(); + } + }; + + process.stdin.setEncoding('utf8'); + process.stdin.on('data', function (chunk: string) { + pending += chunk; + for (;;) { + const end = pending.indexOf('\n'); + if (end < 0) return; + const line = pending.slice(0, end).trim(); + pending = pending.slice(end + 1); + if (!line) continue; + let command: Record; + try { + command = JSON.parse(line); + } catch { + continue; + } + if (command.op === 'answer') { + const prompt = waiting.get(String(command.id)); + waiting.delete(String(command.id)); + if (prompt) prompt.resolve(String(command.value ?? '')); + continue; + } + if (command.op === 'cancel') { + controller.abort(); + for (const prompt of waiting.values()) prompt.reject(new Error('cancelled')); + waiting.clear(); + continue; + } + if (started) continue; + started = true; + // Exit once the last line is out: a pipe may still hold it when + // `process.exit` runs, and Pi's runtime keeps timers alive otherwise. + const exit = function (code: number): void { + process.stdout.write('', function () { + process.exit(code); + }); + }; + run(command).then( + function () { + exit(0); + }, + function (error: unknown) { + fail(error); + exit(1); + }, + ); + } + }); + process.stdin.on('end', function () { + // The driver went away: nothing is left to answer a prompt. + controller.abort(); + if (!started) process.exit(0); + }); +} + +/** The helper file's contents: one ESM module that runs the function. */ +export function codedeckPiAuthHelperSource(): string { + return ( + '// Written by CodeDeck+ — manages Pi accounts with Pi\'s own code. Regenerated\n' + + '// whenever it changes; do not edit.\n' + + 'const pi = await import(process.argv[2]);\n' + + `const main = ${codedeckPiAuthHelper.toString()};\n` + + 'main(pi);\n' + ); +} + +/** Where the helper lives: beside the extension, under the state root. */ +export function piAuthHelperPath(home: string): string { + return path.join(home, 'codedeck', 'codedeck-auth.mjs'); +} + +/** Write the helper file when its contents changed, and return its path. */ +export function installPiAuthHelper(home: string): string { + const file = piAuthHelperPath(home); + const source = codedeckPiAuthHelperSource(); + try { + if (fs.readFileSync(file, 'utf8') === source) return file; + } catch { + // Not there yet: written below. + } + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, source); + return file; +} diff --git a/packages/agent-host/src/drivers/pi/driver.ts b/packages/agent-host/src/drivers/pi/driver.ts index 53f9adfb..4f8e134e 100644 --- a/packages/agent-host/src/drivers/pi/driver.ts +++ b/packages/agent-host/src/drivers/pi/driver.ts @@ -44,6 +44,7 @@ import type { StartSession, UsageData, } from '../../sdk/types'; +import { PiAccounts } from './accounts'; import { buildPiEnv } from './env'; import { PI_PERMISSION_PREFIX, installPiExtension } from './extension'; import { PI_LABEL } from './install'; @@ -793,12 +794,17 @@ export interface PiDriverOptions { providerHttp?: ProviderHttp; /** Spawn seam for tests. */ spawnFn?: PiRpcOptions['spawnFn']; + /** Spawn seam for the account helper, in tests. */ + accountsSpawnFn?: PiRpcOptions['spawnFn']; log: (message: string) => void; } export class PiDriver implements Driver { private unavailable: string | undefined; private models?: Promise<{ models: ModelEntry[]; defaultModel?: string }>; + /** Pi's provider keys and sign-ins, stored where Pi's own `/login` keeps + * them; a change makes the model list be read again. */ + readonly accounts: PiAccounts; constructor(private readonly options: PiDriverOptions) { // Pi's state root must exist before the first process starts in it @@ -812,6 +818,15 @@ export class PiDriver implements Driver { // the first session (and the model list the phone asks for before it) // finds it ready instead of waiting on a download. void options.runtime.prepare(); + this.accounts = new PiAccounts({ + home: options.home, + entryPoint: () => options.runtime.entryPoint(), + env: () => buildPiEnv({}, options.home, options.baseEnv ?? process.env), + changed: () => { + this.models = undefined; + }, + ...(options.accountsSpawnFn !== undefined ? { spawnFn: options.accountsSpawnFn } : {}), + }); } /** Mark the driver unusable (a path the operator named is not a file). */ @@ -842,6 +857,7 @@ export class PiDriver implements Driver { providers: true, interrupt: true, commands: true, + accounts: true, plugins: false, mcp: false, tasks: false, @@ -966,6 +982,7 @@ export class PiDriver implements Driver { } async shutdown(): Promise { + this.accounts.close(); await this.options.runtime.close(); } } From d0a14c9bc2daad78c9bb5ffe2c37583e2e577f86 Mon Sep 17 00:00:00 2001 From: deymosh <232244450+deymosh@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:12:19 +0100 Subject: [PATCH 6/8] feat(agent-host): manage Pi's MCP servers from the phone The driver now advertises `supports.mcp`: the MCP screen edits the `mcpServers` map of mcp.json in Pi's home, the file `pi mcp add` and /mcp edit, so a server added from the phone is also there for Pi in a terminal on that home. Stdio servers take command/args/env, HTTP ones url/headers, and switching one off writes Pi's own `enabled: false`. Pi rejects the legacy SSE transport and names other than letters, digits, `_` and `-` (verified with `pi mcp list --json` on 1.5.2), so both are refused before anything is written. Edits are serialised and written beside the file then renamed over it, owner-only, since env and header values are kept there. A session's MCP panel says what its Pi loaded as it started, as the DeepSeek driver's does: Pi connects its servers at session start and reports nothing about them over RPC, so a server changed afterwards is shown as not loaded yet. `--offline` does not affect MCP connections (it covers model catalog refreshes and package installs only). Tests: the pinned Pi validates the file this writes (proven by writing an HTTP server under the wrong key once); listing carries no argument, env or header value; refusals change nothing; the session panel follows changes made after the session started. Co-Authored-By: Claude Code --- .../src/drivers/pi/__tests__/piDriver.test.ts | 15 +- .../src/drivers/pi/__tests__/piMcp.test.ts | 97 ++++++++++ packages/agent-host/src/drivers/pi/driver.ts | 31 ++- packages/agent-host/src/drivers/pi/mcp.ts | 180 ++++++++++++++++++ 4 files changed, 320 insertions(+), 3 deletions(-) create mode 100644 packages/agent-host/src/drivers/pi/__tests__/piMcp.test.ts create mode 100644 packages/agent-host/src/drivers/pi/mcp.ts diff --git a/packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts b/packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts index 7b1d7810..ad79d947 100644 --- a/packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts +++ b/packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts @@ -93,7 +93,7 @@ describe('PiDriver.info', () => { commands: true, accounts: true, plugins: false, - mcp: false, + mcp: true, tasks: false, }); // Pi's own auth in its home applies; there is no CodeDeck credential. @@ -375,6 +375,19 @@ describe('PiSession commands and options', () => { expect(await h.session!.listCommands!()).toEqual([{ name: 'fix-tests', description: 'Fix failing tests' }]); }); + it('shows the MCP servers the session’s Pi loaded, and one added since as not loaded yet', async () => { + const h = withDriver(); + await h.driver.mcp.act('add', [{ name: 'first', setup: { type: 'stdio', command: 'node' } }], []); + await ready(h); + expect((await h.session!.mcpStatus!()).servers).toEqual([{ name: 'first', status: 'connected' }]); + await h.driver.mcp.act('add', [{ name: 'second', setup: { type: 'stdio', command: 'node' } }], []); + await h.driver.mcp.act('disable', [], ['first']); + expect((await h.session!.mcpStatus!()).servers).toEqual([ + { name: 'first', status: 'disabled' }, + { name: 'second', status: 'pending' }, + ]); + }); + it('applies a thinking level through Pi’s own command', async () => { const h = withDriver(); await ready(h); diff --git a/packages/agent-host/src/drivers/pi/__tests__/piMcp.test.ts b/packages/agent-host/src/drivers/pi/__tests__/piMcp.test.ts new file mode 100644 index 00000000..1aa239a5 --- /dev/null +++ b/packages/agent-host/src/drivers/pi/__tests__/piMcp.test.ts @@ -0,0 +1,97 @@ +/** + * Pi's MCP servers, in `mcp.json` in its home. What matters is that Pi reads + * the file this writes as intended, so the pinned Pi itself checks it + * (`pi mcp list --json`, which reports every invalid entry and exits 1), + * and that nothing secret comes back out. + */ +import { execFileSync } from 'node:child_process'; +import { mkdtempSync, readFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import * as path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import type { McpServerAdd } from '../../../sdk/types'; +import { bundledPiExecutable } from '../install'; +import { PiMcp } from '../mcp'; + +const piPath = bundledPiExecutable(); +const real = piPath ? it : it.skip; + +const LOCAL: McpServerAdd = { + name: 'local-tools', + setup: { type: 'stdio', command: 'node', args: ['server.js', '--token', 'arg-secret'], env: { API_KEY: 'env-secret' } }, +}; +const REMOTE: McpServerAdd = { + name: 'docs', + setup: { type: 'http', url: 'https://example.com/mcp', headers: { Authorization: 'Bearer header-secret' } }, +}; + +function manager(): { mcp: PiMcp; home: string } { + const home = mkdtempSync(path.join(tmpdir(), 'codedeck-pi-mcp-')); + return { mcp: new PiMcp(home, () => {}), home }; +} + +function piList(home: string): { servers: Array<{ name: string; state: string }>; errors: string[] } { + const out = execFileSync(process.execPath, [piPath!, 'mcp', 'list', '--json'], { + cwd: home, + env: { ...process.env, PI_CODING_AGENT_DIR: home }, + encoding: 'utf8', + timeout: 60_000, + }); + return JSON.parse(out) as { servers: Array<{ name: string; state: string }>; errors: string[] }; +} + +describe('PiMcp', () => { + real( + 'writes servers the pinned Pi reads without an error, and switches them off its way', + async () => { + const { mcp, home } = manager(); + await mcp.act('add', [LOCAL, REMOTE], []); + // Off, so Pi checks the entries without trying to connect them. + await mcp.act('disable', [], ['local-tools', 'docs']); + const listed = piList(home); + expect(listed.errors).toEqual([]); + expect(listed.servers.map((server) => [server.name, server.state]).sort()).toEqual([ + ['docs', 'disabled'], + ['local-tools', 'disabled'], + ]); + }, + 60_000, + ); + + it('lists servers by name, program and keys, never a secret', async () => { + const { mcp } = manager(); + const state = await mcp.act('add', [LOCAL, REMOTE], []); + expect(state.servers).toEqual([ + expect.objectContaining({ name: 'docs', transport: 'http', headerKeys: ['Authorization'], enabled: true }), + expect.objectContaining({ name: 'local-tools', transport: 'stdio', target: 'node', envKeys: ['API_KEY'], enabled: true }), + ]); + const shown = JSON.stringify(await mcp.list()); + for (const secret of ['arg-secret', 'env-secret', 'header-secret']) expect(shown).not.toContain(secret); + }); + + it('switches a server back on by dropping the flag, and removes one', async () => { + const { mcp, home } = manager(); + await mcp.act('add', [LOCAL], []); + await mcp.act('disable', [], ['local-tools']); + await mcp.act('enable', [], ['local-tools']); + const file = JSON.parse(readFileSync(path.join(home, 'mcp.json'), 'utf8')) as { mcpServers: Record> }; + expect(file.mcpServers['local-tools']).not.toHaveProperty('enabled'); + expect((await mcp.act('remove', [], ['local-tools'])).servers).toEqual([]); + }); + + it('refuses what Pi would reject — an SSE server, a name it cannot take — and changes nothing', async () => { + const { mcp } = manager(); + await expect(mcp.act('add', [{ name: 'old', setup: { type: 'sse', url: 'https://example.com/sse' } }], [])).rejects.toThrow(/SSE/); + await expect(mcp.act('add', [{ ...LOCAL, name: 'bad name' }], [])).rejects.toThrow(/letters, digits/); + await expect(mcp.act('remove', [], ['missing'])).rejects.toThrow(/no MCP server named missing/); + expect((await mcp.list()).servers).toEqual([]); + }); + + it('counts only changes that change something', async () => { + const { mcp } = manager(); + await mcp.act('add', [LOCAL], []); + expect(mcp.version).toBe(1); + await mcp.act('enable', [], ['local-tools']); + expect(mcp.version).toBe(1); + }); +}); diff --git a/packages/agent-host/src/drivers/pi/driver.ts b/packages/agent-host/src/drivers/pi/driver.ts index 4f8e134e..b22f4387 100644 --- a/packages/agent-host/src/drivers/pi/driver.ts +++ b/packages/agent-host/src/drivers/pi/driver.ts @@ -21,7 +21,7 @@ */ import * as fs from 'node:fs'; import * as path from 'node:path'; -import type { Driver, DriverSession, SessionContext } from '../../sdk/driver'; +import type { Driver, DriverSession, SessionContext, SessionMcpState } from '../../sdk/driver'; import type { ProviderHttp } from '../../sdk/net'; import { OPENAI_API, checkToken, listModels } from '../../sdk/providerApi'; import type { EndpointModel } from '../../sdk/providerModels'; @@ -39,12 +39,14 @@ import type { QuestionOutcome, QuestionSpec, SelectOutcome, + SessionMcpServer, SessionOption, SlashCommand, StartSession, UsageData, } from '../../sdk/types'; import { PiAccounts } from './accounts'; +import { PiMcp } from './mcp'; import { buildPiEnv } from './env'; import { PI_PERMISSION_PREFIX, installPiExtension } from './extension'; import { PI_LABEL } from './install'; @@ -133,6 +135,7 @@ function splitModel(model: string, boundProvider: string | undefined): { provide /** What one Pi session is built with. */ interface PiSessionDeps { runtime: PiRuntime; + mcp: PiMcp; home: string; baseEnv: NodeJS.ProcessEnv; spawnFn?: PiRpcOptions['spawnFn']; @@ -167,6 +170,8 @@ export class PiSession implements DriverSession { * content indexes that streamed under it. */ private assistant: { key: string; parts: Map } | undefined; private lastStderr = ''; + /** The MCP configuration this session's Pi loaded as it started. */ + private mcpVersion = Number.POSITIVE_INFINITY; /** The last failed attempt's error, until Pi says whether it retries. */ private heldError: string | undefined; /** Pi said the conversation `--session` names does not exist. */ @@ -213,6 +218,9 @@ export class PiSession implements DriverSession { const entry = await this.deps.runtime.entryPoint(); if (this.ended) return; const extension = installPiExtension(this.deps.home); + // Read before the process starts: a change made while it boots may or + // may not be in it, and is then reported as not loaded yet. + this.mcpVersion = this.deps.mcp.version; const command = piCommand(entry, this.arguments(extension)); this.rpc = new PiRpc({ command: command.command, @@ -750,6 +758,21 @@ export class PiSession implements DriverSession { } } + /** + * The session's MCP servers. Pi connects them as its session starts and + * reports nothing about them over RPC, so this says what the running + * process has: a server changed after it started is not in it yet. + */ + async mcpStatus(): Promise { + const state = await this.deps.mcp.list(); + const current = !this.ended && this.rpc?.alive === true && this.deps.mcp.version <= this.mcpVersion; + const servers: SessionMcpServer[] = state.servers.map((server) => ({ + name: server.name, + status: !server.enabled ? 'disabled' : current ? 'connected' : 'pending', + })); + return { servers, toggles: false, projectWide: false }; + } + async getUsage(): Promise { return null; } @@ -805,6 +828,8 @@ export class PiDriver implements Driver { /** Pi's provider keys and sign-ins, stored where Pi's own `/login` keeps * them; a change makes the model list be read again. */ readonly accounts: PiAccounts; + /** Pi's MCP servers, in `mcp.json` in its home. */ + readonly mcp: PiMcp; constructor(private readonly options: PiDriverOptions) { // Pi's state root must exist before the first process starts in it @@ -818,6 +843,7 @@ export class PiDriver implements Driver { // the first session (and the model list the phone asks for before it) // finds it ready instead of waiting on a download. void options.runtime.prepare(); + this.mcp = new PiMcp(options.home, options.log); this.accounts = new PiAccounts({ home: options.home, entryPoint: () => options.runtime.entryPoint(), @@ -859,7 +885,7 @@ export class PiDriver implements Driver { commands: true, accounts: true, plugins: false, - mcp: false, + mcp: true, tasks: false, }, credentials: [], @@ -880,6 +906,7 @@ export class PiDriver implements Driver { // session before it starts, rather than after an error entry. return new PiSession(params, ctx, { runtime: this.options.runtime, + mcp: this.mcp, home: this.options.home, baseEnv: this.options.baseEnv ?? process.env, ...(this.options.spawnFn !== undefined ? { spawnFn: this.options.spawnFn } : {}), diff --git a/packages/agent-host/src/drivers/pi/mcp.ts b/packages/agent-host/src/drivers/pi/mcp.ts new file mode 100644 index 00000000..a8b6b820 --- /dev/null +++ b/packages/agent-host/src/drivers/pi/mcp.ts @@ -0,0 +1,180 @@ +/** + * Pi's MCP servers for the whole machine: the `mcpServers` map of `mcp.json` + * in Pi's home — the file `pi mcp add` and `/mcp` edit, which every Pi + * session on that home loads, in CodeDeck or in a terminal. + * + * The format is the common one (Pi's docs/mcp.md): `command`/`args`/`env` + * for a stdio server, `url`/`headers` for a streamable HTTP one, and + * `enabled: false` to keep a server without connecting it. Pi rejects the + * legacy SSE transport, so an SSE server is refused here rather than + * written into a file Pi would then report as invalid. A name is what Pi + * accepts: letters, digits, `_` and `-`. + * + * A Pi process connects its servers as its session starts: a change reaches + * the sessions started after it, while a running one keeps its own set. + */ +import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'; +import * as path from 'node:path'; +import type { McpManager, McpState } from '../../sdk/driver'; +import { serverInfo } from '../../sdk/mcp'; +import type { McpAction, McpServerAdd, McpServerInfo } from '../../sdk/types'; + +/** What Pi accepts as a server name (docs/mcp.md, "Configuration rules"). */ +const SERVER_NAME = /^[A-Za-z0-9_-]+$/; + +/** A server as Pi's `mcp.json` takes it: the phone's setup, secrets in + * place (the file is owner-only). */ +export function piServerJson(add: McpServerAdd): Record { + const s = add.setup; + switch (s.type) { + case 'stdio': + return { + command: s.command, + args: s.args ?? [], + ...(s.env && Object.keys(s.env).length ? { env: s.env } : {}), + }; + case 'http': + return { url: s.url, ...(s.headers && Object.keys(s.headers).length ? { headers: s.headers } : {}) }; + case 'sse': + throw new Error(`Pi does not support SSE MCP servers ('${add.name}'): most of them also serve streamable HTTP, often at /mcp.`); + } +} + +/** The servers in an `mcp.json` document, secret-free. */ +export function piServers(config: Record): McpServerInfo[] { + const out: McpServerInfo[] = []; + for (const [name, raw] of Object.entries(record(config.mcpServers))) { + if (!raw || typeof raw !== 'object') continue; + const r = raw as { command?: unknown; url?: unknown; env?: unknown; headers?: unknown; enabled?: unknown }; + const keys = (v: unknown) => (v && typeof v === 'object' ? Object.keys(v) : []); + const transport = typeof r.url === 'string' ? 'http' : typeof r.command === 'string' ? 'stdio' : undefined; + if (transport === undefined) continue; + out.push( + serverInfo({ + name, + transport, + ...(typeof r.command === 'string' ? { command: r.command } : {}), + ...(transport === 'http' ? { url: r.url as string } : {}), + envKeys: keys(r.env), + headerKeys: keys(r.headers), + enabled: r.enabled !== false, + }), + ); + } + return out.sort((a, b) => a.name.localeCompare(b.name)); +} + +/** `config` with one change applied. Throws, changing nothing, when the + * change cannot be made as asked. */ +export function applyPiMcp( + config: Record, + action: McpAction, + servers: McpServerAdd[], + names: string[], +): Record { + const map = { ...record(config.mcpServers) }; + if (action === 'add') { + for (const server of servers) { + if (!SERVER_NAME.test(server.name)) { + throw new Error(`Pi cannot name an MCP server '${server.name}': use letters, digits, '_' and '-'.`); + } + // Added again replaces it, and an added server is on. + map[server.name] = piServerJson(server); + } + } else { + const missing = names.filter((name) => !Object.hasOwn(map, name)); + if (missing.length > 0) throw new Error(`Pi has no MCP server named ${missing.join(', ')}.`); + for (const name of names) { + if (action === 'remove') { + delete map[name]; + continue; + } + const entry = { ...record(map[name]) }; + if (action === 'disable') entry.enabled = false; + else delete entry.enabled; + map[name] = entry; + } + } + return { ...config, mcpServers: map }; +} + +/** Pi's `mcp.json`, every edit waiting for the one before it: two + * overlapping rewrites of one file would keep only the last. */ +export class PiMcp implements McpManager { + private queue: Promise = Promise.resolve(); + private changes = 0; + + /** How many changes this manager has made: a session that recorded fewer + * as its Pi started has not loaded the servers as they are now. */ + get version(): number { + return this.changes; + } + + constructor( + private readonly home: string, + private readonly log: (message: string) => void, + ) {} + + async list(): Promise { + return { servers: piServers(await this.serial(() => this.read())), toggles: true }; + } + + async act(action: McpAction, servers: McpServerAdd[], names: string[]): Promise { + const next = await this.serial(async () => { + const existing = await this.read(); + const edited = applyPiMcp(existing, action, servers, names); + // A change that changes nothing (switching on a server that is on) + // leaves running sessions as current as they were. + if (JSON.stringify(edited) !== JSON.stringify(existing)) { + await this.write(edited); + this.changes += 1; + } + return edited; + }); + return { servers: piServers(next), toggles: true }; + } + + private get file(): string { + return path.join(this.home, 'mcp.json'); + } + + /** A missing or unreadable file is an empty configuration. */ + private async read(): Promise> { + try { + return record(JSON.parse(await readFile(this.file, 'utf8'))); + } catch (error) { + // Only the kind of failure: a JSON error quotes the text around it, + // and the file holds servers' env and header values. + const code = (error as { code?: string }).code; + if (code !== 'ENOENT') { + this.log(`[pi] ${this.file} could not be read (${code ?? (error instanceof SyntaxError ? 'not valid JSON' : 'unreadable')}) — treating it as empty`); + } + return {}; + } + } + + /** Written beside the file and renamed over it, so a Pi that starts + * meanwhile reads the old servers or the new ones, never half of either; + * owner-only, for the env and header values it keeps. */ + private async write(config: Record): Promise { + await mkdir(this.home, { recursive: true }); + const staged = `${this.file}.${process.pid}.tmp`; + try { + await writeFile(staged, `${JSON.stringify(config, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 }); + await rename(staged, this.file); + } catch (error) { + await rm(staged, { force: true }); + throw error; + } + } + + private serial(work: () => Promise): Promise { + const next = this.queue.then(work, work); + this.queue = next.catch(() => {}); + return next; + } +} + +function record(value: unknown): Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Record) : {}; +} From dd465117added4c887ad4412b94b86dd7f4734c3 Mon Sep 17 00:00:00 2001 From: deymosh <232244450+deymosh@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:14:56 +0100 Subject: [PATCH 7/8] feat(agent-host): manage Pi's packages as plugins The driver now advertises `supports.plugins`: the phone's plugins are Pi's packages, installed, updated and removed with Pi's own commands (`pi install|update|remove `, none of which asks anything without a terminal, verified on 1.5.2) and listed from the `packages` array of settings.json in Pi's home. A package bundles extensions, skills, prompt templates and themes, which is how Pi gains what it does not ship (subagents, LSP diagnostics, other tools) without CodeDeck maintaining any of it. The commands run in Pi's home: Pi records a local path relative to its settings file, and only there does that record name the same directory (outside it Pi answers "No matching package found"). An npm source needs npm, which Pi runs: the image has it, a release archive does not, and Pi's raw `spawn npm ENOENT` becomes a sentence that says so. The bridge's CODEDECK_NPM_REGISTRY mirror is passed on as npm_config_registry. Pi can only turn a package off by rewriting its resource filters, which would discard the user's own, so there are no toggles. Tests: install, update and uninstall of a local package through the pinned Pi (proven by running the commands outside Pi's home once); parsing of Pi's records and the refusals that never reach Pi. Co-Authored-By: Claude Code --- .../src/drivers/pi/__tests__/piDriver.test.ts | 2 +- .../drivers/pi/__tests__/piPlugins.test.ts | 81 +++++++++ packages/agent-host/src/drivers/pi/driver.ts | 23 ++- packages/agent-host/src/drivers/pi/module.ts | 1 + packages/agent-host/src/drivers/pi/plugins.ts | 164 ++++++++++++++++++ 5 files changed, 269 insertions(+), 2 deletions(-) create mode 100644 packages/agent-host/src/drivers/pi/__tests__/piPlugins.test.ts create mode 100644 packages/agent-host/src/drivers/pi/plugins.ts diff --git a/packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts b/packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts index ad79d947..652e784a 100644 --- a/packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts +++ b/packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts @@ -92,7 +92,7 @@ describe('PiDriver.info', () => { interrupt: true, commands: true, accounts: true, - plugins: false, + plugins: true, mcp: true, tasks: false, }); diff --git a/packages/agent-host/src/drivers/pi/__tests__/piPlugins.test.ts b/packages/agent-host/src/drivers/pi/__tests__/piPlugins.test.ts new file mode 100644 index 00000000..b2d5bc8d --- /dev/null +++ b/packages/agent-host/src/drivers/pi/__tests__/piPlugins.test.ts @@ -0,0 +1,81 @@ +/** + * Pi's packages as the phone's plugins. Install, update and uninstall run + * the pinned Pi's own commands on a local package (no network), so what is + * checked is what Pi itself records; the parsing and refusals run alone. + */ +import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import * as path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { bundledPiExecutable } from '../install'; +import { PiPlugins, piCliRunner, piPackageSources, piPlugin } from '../plugins'; + +const piPath = bundledPiExecutable(); +const real = piPath ? it : it.skip; + +function localPackage(root: string): string { + const dir = path.join(root, 'my-pi-package'); + mkdirSync(path.join(dir, 'prompts'), { recursive: true }); + writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'my-pi-package', version: '1.2.3', keywords: ['pi-package'] })); + writeFileSync(path.join(dir, 'prompts', 'hello.md'), 'Say hello'); + return dir; +} + +describe('PiPlugins', () => { + real( + 'installs, updates and uninstalls through Pi’s own commands, and lists what Pi recorded', + async () => { + const root = mkdtempSync(path.join(tmpdir(), 'codedeck-pi-plugins-')); + const home = path.join(root, 'home'); + mkdirSync(home); + const pkg = localPackage(root); + const plugins = new PiPlugins( + home, + piCliRunner({ entryPoint: async () => piPath!, home, env: () => ({ ...process.env, PI_CODING_AGENT_DIR: home }) as Record }), + ); + + const installed = await plugins.act('install', pkg); + // Pi records a local path relative to its settings file; the plugin's + // id is that record, which uninstall then resolves from Pi's home. + expect(installed.installed).toEqual([expect.objectContaining({ name: 'my-pi-package', enabled: true })]); + expect(installed.toggles).toBe(false); + + const updated = await plugins.act('update', installed.installed[0]!.id); + expect(updated.message).toMatch(/already up to date/); + + expect((await plugins.act('uninstall', installed.installed[0]!.id)).installed).toEqual([]); + }, + 120_000, + ); + + it('explains a missing npm instead of Pi’s spawn error', async () => { + const plugins = new PiPlugins(mkdtempSync(path.join(tmpdir(), 'codedeck-pi-plugins-')), async () => ({ + code: 1, + stdout: 'Installing npm:some-package...\n', + stderr: 'Error: spawn npm ENOENT\n', + })); + await expect(plugins.act('install', 'npm:some-package')).rejects.toThrow(/npm, which is not on this machine/); + }); + + it('refuses a switch, a marketplace, and a source that would read as an option, without running Pi', async () => { + const ran: string[][] = []; + const plugins = new PiPlugins(mkdtempSync(path.join(tmpdir(), 'codedeck-pi-plugins-')), async (args) => { + ran.push(args); + return { code: 0, stdout: '', stderr: '' }; + }); + await expect(plugins.act('disable', 'npm:x')).rejects.toThrow(/cannot be switched off/); + await expect(plugins.act('add-marketplace', 'x')).rejects.toThrow(/not from marketplaces/); + await expect(plugins.act('install', '--local')).rejects.toThrow(/not a package source/); + expect(ran).toEqual([]); + }); + + it('reads the sources Pi keeps, as strings or filtered entries', () => { + expect( + piPackageSources({ packages: ['npm:@scope/tool@1.0.0', { source: 'git:github.com/me/pkg@v2', skills: [] }, 42, { other: 1 }] }), + ).toEqual(['npm:@scope/tool@1.0.0', 'git:github.com/me/pkg@v2']); + expect(piPlugin('npm:@scope/tool@1.0.0')).toEqual({ id: 'npm:@scope/tool@1.0.0', name: '@scope/tool', version: '1.0.0', enabled: true }); + expect(piPlugin('git:github.com/me/pkg@v2')).toEqual({ id: 'git:github.com/me/pkg@v2', name: 'github.com/me/pkg', version: 'v2', enabled: true }); + expect(piPlugin('..\\my-pkg').name).toBe('my-pkg'); + expect(piPlugin('../packages/my-pkg/').name).toBe('my-pkg'); + }); +}); diff --git a/packages/agent-host/src/drivers/pi/driver.ts b/packages/agent-host/src/drivers/pi/driver.ts index b22f4387..107fc648 100644 --- a/packages/agent-host/src/drivers/pi/driver.ts +++ b/packages/agent-host/src/drivers/pi/driver.ts @@ -47,6 +47,7 @@ import type { } from '../../sdk/types'; import { PiAccounts } from './accounts'; import { PiMcp } from './mcp'; +import { PiPlugins, piCliRunner, type PiCliRunner } from './plugins'; import { buildPiEnv } from './env'; import { PI_PERMISSION_PREFIX, installPiExtension } from './extension'; import { PI_LABEL } from './install'; @@ -819,6 +820,10 @@ export interface PiDriverOptions { spawnFn?: PiRpcOptions['spawnFn']; /** Spawn seam for the account helper, in tests. */ accountsSpawnFn?: PiRpcOptions['spawnFn']; + /** Runs Pi's package commands; tests pass their own. */ + pluginRunner?: PiCliRunner; + /** `CODEDECK_NPM_REGISTRY`, when the operator set one. */ + npmRegistry?: string; log: (message: string) => void; } @@ -830,6 +835,8 @@ export class PiDriver implements Driver { readonly accounts: PiAccounts; /** Pi's MCP servers, in `mcp.json` in its home. */ readonly mcp: PiMcp; + /** Pi's packages, through its own package commands. */ + readonly plugins: PiPlugins; constructor(private readonly options: PiDriverOptions) { // Pi's state root must exist before the first process starts in it @@ -844,6 +851,20 @@ export class PiDriver implements Driver { // finds it ready instead of waiting on a download. void options.runtime.prepare(); this.mcp = new PiMcp(options.home, options.log); + this.plugins = new PiPlugins( + options.home, + options.pluginRunner ?? + piCliRunner({ + entryPoint: () => options.runtime.entryPoint(), + home: options.home, + // The bridge's registry mirror reaches the npm Pi runs, so a + // machine without the public registry installs from it too. + env: () => ({ + ...buildPiEnv({}, options.home, options.baseEnv ?? process.env), + ...(options.npmRegistry ? { npm_config_registry: options.npmRegistry } : {}), + }), + }), + ); this.accounts = new PiAccounts({ home: options.home, entryPoint: () => options.runtime.entryPoint(), @@ -884,7 +905,7 @@ export class PiDriver implements Driver { interrupt: true, commands: true, accounts: true, - plugins: false, + plugins: true, mcp: true, tasks: false, }, diff --git a/packages/agent-host/src/drivers/pi/module.ts b/packages/agent-host/src/drivers/pi/module.ts index 9efe8ca0..ff28f371 100644 --- a/packages/agent-host/src/drivers/pi/module.ts +++ b/packages/agent-host/src/drivers/pi/module.ts @@ -34,6 +34,7 @@ export const piModule: DriverModule = { home, baseEnv: ctx.ownEnv, providerHttp, + ...(ctx.env.CODEDECK_NPM_REGISTRY?.trim() ? { npmRegistry: ctx.env.CODEDECK_NPM_REGISTRY.trim() } : {}), log: ctx.log, }); if (piPath && !isFile(piPath)) { diff --git a/packages/agent-host/src/drivers/pi/plugins.ts b/packages/agent-host/src/drivers/pi/plugins.ts new file mode 100644 index 00000000..0b8ed355 --- /dev/null +++ b/packages/agent-host/src/drivers/pi/plugins.ts @@ -0,0 +1,164 @@ +/** + * Pi's packages, as the phone's plugins: changed through Pi's own package + * commands (`pi install|remove|update `, verified without a + * terminal on 1.5.2: none of them asks anything) and listed from the + * `packages` array of `settings.json` in Pi's home, which those commands + * keep and which every Pi session on that home loads. + * + * A package bundles extensions, skills, prompt templates and themes, and is + * how Pi gains what it does not ship — subagents, LSP diagnostics, other + * tools — so this is where those come from rather than from CodeDeck. + * + * - A source is what Pi takes: `npm:[@version]`, `git:` + * (or a URL), or a local path. Pi stores a local path relative to its + * settings file, so the commands run in Pi's home, where that relative + * path resolves to the same directory. + * - An npm source needs `npm` (Pi runs it): the container image has one, + * a release archive does not. The bridge's own registry mirror + * (`CODEDECK_NPM_REGISTRY`) is passed on to it. + * - Pi has no switch to turn a package off other than rewriting its + * resource filters, which would discard the user's own: no toggles. + * - A Pi process loads its packages as its session starts: a change reaches + * the sessions started after it. + */ +import { spawn } from 'node:child_process'; +import { readFile } from 'node:fs/promises'; +import * as path from 'node:path'; +import type { PluginManager, PluginState } from '../../sdk/driver'; +import type { InstalledPlugin, PluginAction } from '../../sdk/types'; +import { piCommand } from './runtime'; + +export interface PiCliResult { + code: number; + stdout: string; + stderr: string; +} + +/** Runs Pi's CLI with these arguments, in Pi's home. */ +export type PiCliRunner = (args: string[], timeoutMs: number) => Promise; + +/** Installing clones a repository or fetches a package and its dependencies. */ +const CHANGE_TIMEOUT_MS = 10 * 60_000; + +const INSTALL_HINT = 'npm:package, git:github.com/owner/repo, a URL or a path'; +const INSTALL_NOTE = + 'Pi packages add extensions, skills, prompt templates and themes to every Pi session on this machine, ' + + 'from npm, git or a path; sessions started after a change load it. A package runs code with your ' + + 'permissions: install only ones you trust. An npm package needs npm on the machine.'; + +/** The sources in Pi's settings, as Pi wrote them. */ +export function piPackageSources(settings: Record): string[] { + const packages = Array.isArray(settings.packages) ? settings.packages : []; + return packages.flatMap((entry): string[] => { + if (typeof entry === 'string') return entry.trim() ? [entry] : []; + const source = (entry as { source?: unknown } | null)?.source; + return typeof source === 'string' && source.trim() ? [source] : []; + }); +} + +/** One package as the phone lists it: its source is its id. */ +export function piPlugin(source: string): InstalledPlugin { + const npm = /^npm:((?:@[^/@]+\/)?[^@]+)(?:@(.+))?$/.exec(source); + if (npm) return { id: source, name: npm[1]!, ...(npm[2] ? { version: npm[2] } : {}), enabled: true }; + const git = /^(?:git:|https?:\/\/)(.+?)(?:\.git)?(?:@([^@/]+))?$/.exec(source); + if (git) return { id: source, name: git[1]!.replace(/\/+$/, ''), ...(git[2] ? { version: git[2] } : {}), enabled: true }; + // Split on both separators, not `path.basename`'s own: Pi on Windows + // records `..\\pkg`, and the name must not depend on the bridge's OS. + const last = source.replace(/[\\/]+$/, '').split(/[\\/]/).pop(); + return { id: source, name: last || source, enabled: true }; +} + +export class PiPlugins implements PluginManager { + constructor( + private readonly home: string, + private readonly run: PiCliRunner, + ) {} + + async list(): Promise { + return { + installed: piPackageSources(await this.settings()).map(piPlugin), + toggles: false, + installHint: INSTALL_HINT, + installNote: INSTALL_NOTE, + }; + } + + async act(action: PluginAction, target: string): Promise { + const source = target.trim(); + if (source === '') throw new Error('Name the package to change.'); + const command = action === 'install' ? 'install' : action === 'uninstall' ? 'remove' : action === 'update' ? 'update' : undefined; + if (command === undefined) { + throw new Error( + action === 'enable' || action === 'disable' + ? 'Pi packages cannot be switched off; uninstall one instead.' + : 'Pi installs packages by source, not from marketplaces.', + ); + } + // A leading dash would read as one of Pi's options, not a source. + if (source.startsWith('-')) throw new Error(`'${source}' is not a package source.`); + const result = await this.run([command, source], CHANGE_TIMEOUT_MS); + if (result.code !== 0) throw new Error(failureOf(result)); + const state = await this.list(); + const said = lastLine(result.stdout); + return { ...state, ...(said ? { message: said } : {}) }; + } + + private async settings(): Promise> { + try { + const parsed = JSON.parse(await readFile(path.join(this.home, 'settings.json'), 'utf8')) as unknown; + return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? (parsed as Record) : {}; + } catch { + return {}; + } + } +} + +/** What went wrong, in Pi's words where it said any. Pi runs `npm` for an + * npm source and its absence surfaces as a spawn error, phrased here. */ +function failureOf(result: PiCliResult): string { + const text = `${result.stderr}\n${result.stdout}`; + if (/spawn npm ENOENT/.test(text)) { + return 'Pi installs npm packages with npm, which is not on this machine. A git: source or a path needs no npm.'; + } + return lastLine(result.stderr) ?? lastLine(result.stdout) ?? `Pi exited with ${result.code}`; +} + +function lastLine(text: string): string | undefined { + const lines = text + .split(/\r?\n/) + .map((line) => line.trim()) + .filter(Boolean); + return lines[lines.length - 1]; +} + +/** The production runner: Pi's CLI, never through a shell, in Pi's home. */ +export function piCliRunner(options: { + entryPoint: () => Promise; + home: string; + env: () => Record; +}): PiCliRunner { + return async (args, timeoutMs) => { + const command = piCommand(await options.entryPoint(), args); + return new Promise((resolve) => { + const child = spawn(command.command, command.args, { cwd: options.home, env: options.env(), stdio: ['ignore', 'pipe', 'pipe'] }); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (chunk: Buffer) => { + stdout = (stdout + chunk.toString()).slice(-20_000); + }); + child.stderr.on('data', (chunk: Buffer) => { + stderr = (stderr + chunk.toString()).slice(-20_000); + }); + const timer = setTimeout(() => child.kill('SIGKILL'), timeoutMs); + timer.unref?.(); + child.on('error', (error) => { + clearTimeout(timer); + resolve({ code: 1, stdout, stderr: `${stderr}\n${error.message}` }); + }); + child.on('close', (code) => { + clearTimeout(timer); + resolve({ code: code ?? 1, stdout, stderr: code === null ? `${stderr}\nPi did not finish in time` : stderr }); + }); + }); + }; +} From bcaf1a8e1ff99dbb8bb4bef0cac7d26272fa36ee Mon Sep 17 00:00:00 2001 From: deymosh <232244450+deymosh@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:15:51 +0100 Subject: [PATCH 8/8] feat(agent-host): add an Auto edit approval tier to Pi Between Ask and YOLO: Pi's own file writers (`edit`, `write`) run without a card, while a shell command and every other tool still ask. Only Pi's built-ins count, by name: a tool an extension or an MCP server adds may look like an edit and do anything else besides, so it asks. The tier is the driver's policy, like the other two; the extension still holds every call until the driver answers. Co-Authored-By: Claude Code --- .../src/drivers/pi/__tests__/fakePi.ts | 5 +++++ .../src/drivers/pi/__tests__/piDriver.test.ts | 22 ++++++++++++++++++- packages/agent-host/src/drivers/pi/driver.ts | 11 ++++++++-- packages/agent-host/src/drivers/pi/tools.ts | 8 +++++++ 4 files changed, 43 insertions(+), 3 deletions(-) diff --git a/packages/agent-host/src/drivers/pi/__tests__/fakePi.ts b/packages/agent-host/src/drivers/pi/__tests__/fakePi.ts index 5d8ccd35..de9c3aaa 100644 --- a/packages/agent-host/src/drivers/pi/__tests__/fakePi.ts +++ b/packages/agent-host/src/drivers/pi/__tests__/fakePi.ts @@ -224,6 +224,11 @@ export class FakePi { this.runTool({ id: `call_${++this.nextCall}`, toolName: 'read', args: { path: 'a.txt' } }); return; } + if (text === '/edit') { + // Pi's edit tool's own argument shape (its tool schema in 1.5.2). + this.runTool({ id: `call_${++this.nextCall}`, toolName: 'edit', args: { path: 'a.txt', edits: [{ oldText: 'a', newText: 'b' }] } }); + return; + } if (text === '/retry') { // Two failed attempts, then the reply. this.failedAttempt(1); diff --git a/packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts b/packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts index 652e784a..21dfafc3 100644 --- a/packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts +++ b/packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts @@ -81,7 +81,7 @@ describe('PiDriver.info', () => { const info = driver.info(); expect(info.id).toBe('pi'); expect(info.displayName).toBe('Pi'); - expect(info.modes?.map((mode) => mode.id)).toEqual(['ask', 'yolo']); + expect(info.modes?.map((mode) => mode.id)).toEqual(['ask', 'auto-edit', 'yolo']); expect(info.efforts?.map((effort) => effort.id)).toEqual(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']); expect(info.defaultMode).toBe('ask'); expect(info.defaultEffort).toBe('medium'); @@ -338,6 +338,26 @@ describe('PiSession permission policy', () => { expect(entries(ctx)).toContainEqual(expect.objectContaining({ entryType: 'tool_call', toolName: 'read', kind: 'read' })); }); + it('runs Pi’s file edits without a card in auto-edit mode, and still asks before a command', async () => { + const h = withDriver(); + const ctx = await ready(h, { mode: 'auto-edit' }); + await turn(h.session!, ctx, '/edit'); + expect(ctx.permissions).toHaveLength(0); + expect(h.fake.uiResponses.at(-1)).toMatchObject({ value: 'allow' }); + + await turn(h.session!, ctx, '/tool'); + expect(ctx.permissions).toHaveLength(1); + expect(ctx.permissions[0]).toMatchObject({ toolName: 'bash' }); + }); + + it('asks before a file edit in ask mode', async () => { + const h = withDriver(); + const ctx = await ready(h); + await turn(h.session!, ctx, '/edit'); + expect(ctx.permissions).toHaveLength(1); + expect(ctx.permissions[0]).toMatchObject({ toolName: 'edit', kind: 'edit' }); + }); + it('remembers “allow for this session” for that tool only', async () => { const h = withDriver(); const ctx = await ready( diff --git a/packages/agent-host/src/drivers/pi/driver.ts b/packages/agent-host/src/drivers/pi/driver.ts index 107fc648..578d60c5 100644 --- a/packages/agent-host/src/drivers/pi/driver.ts +++ b/packages/agent-host/src/drivers/pi/driver.ts @@ -52,17 +52,19 @@ import { buildPiEnv } from './env'; import { PI_PERMISSION_PREFIX, installPiExtension } from './extension'; import { PI_LABEL } from './install'; import { PiRpc, type PiRecord, type PiRpcOptions } from './rpc'; -import { PI_READ_ONLY_TOOLS, piTool } from './tools'; +import { PI_EDIT_TOOLS, PI_READ_ONLY_TOOLS, piTool } from './tools'; import { PI_STYLE } from './style'; import { PiRuntime, piCommand, type PiRuntimeOptions } from './runtime'; export const PI_AGENT_ID = 'pi'; const ASK_MODE = 'ask'; +const AUTO_EDIT_MODE = 'auto-edit'; const YOLO_MODE = 'yolo'; const DEFAULT_MODE = ASK_MODE; const PI_MODES = [ { id: ASK_MODE, label: 'Ask', description: 'Ask before each tool call, except for read-only tools' }, + { id: AUTO_EDIT_MODE, label: 'Auto edit', description: 'Edit files without asking; ask before running commands' }, { id: YOLO_MODE, label: 'YOLO', description: 'Run every tool without asking' }, ]; @@ -637,7 +639,12 @@ export class PiSession implements DriverSession { private async answerPermission(id: string, callId: string): Promise { const facts = this.toolFacts.get(callId); const toolName = facts?.name ?? 'tool'; - if (this.sessionMode === YOLO_MODE || this.allowedTools.has(toolName) || PI_READ_ONLY_TOOLS.has(toolName)) { + if ( + this.sessionMode === YOLO_MODE || + this.allowedTools.has(toolName) || + PI_READ_ONLY_TOOLS.has(toolName) || + (this.sessionMode === AUTO_EDIT_MODE && PI_EDIT_TOOLS.has(toolName)) + ) { this.respond({ type: 'extension_ui_response', id, value: 'allow' }); return; } diff --git a/packages/agent-host/src/drivers/pi/tools.ts b/packages/agent-host/src/drivers/pi/tools.ts index ff37dc32..ae60ea1a 100644 --- a/packages/agent-host/src/drivers/pi/tools.ts +++ b/packages/agent-host/src/drivers/pi/tools.ts @@ -55,6 +55,14 @@ export const PI_TOOLS: ToolDialects = { */ export const PI_READ_ONLY_TOOLS: ReadonlySet = new Set(['read', 'grep', 'find', 'ls']); +/** + * The tools this driver's `auto-edit` mode also runs without a card: Pi's + * own file writers. Only Pi's built-ins, by name — an extension's or an MCP + * server's tool that looks like an edit may do anything else as well, so it + * still asks, and so does every shell. + */ +export const PI_EDIT_TOOLS: ReadonlySet = new Set(['edit', 'write']); + /** Read one of this agent's tool calls. `report` is told a name this table * does not list (`unknownToolReporter`). */ export function piTool(toolName: string, input: Input, report?: (toolName: string) => void): ToolCallRead {