diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 91c9eca..625def4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,7 +30,7 @@ jobs: uses: actions/checkout@v6 with: repository: getpaseo/paseo - ref: cafe4b01c8522ff39560241c5deb01427dc8dc5b # v0.12.0 + ref: d91ae138cb931447635e94296023414a58bedcc5 # v0.15.3 path: paseo persist-credentials: false - name: Check out reference ZCode source diff --git a/AGENTS.md b/AGENTS.md index 693cfb7..de02ff9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -59,8 +59,9 @@ Identify the root cause and do not add ad hoc workarounds. Add backward compatib - `npm run test:stdio-runtime` uses the real runtime (override pair or managed runtime under `XDG_DATA_HOME`) with isolated data and a local model fixture. Resume guarantees require both Paseo's saved `mode` and `settings.plan_mode`; failures of this supported contract block release. Keep source SHA, distribution hashes, runtime versions and actual OS coverage separate. - `npm run test:native-restore` separately checks resume without explicit settings. The pinned upstream fails this unsupported path; retain its nonzero exit and run it when evaluating runtime updates. It is not a required CI or release condition (ADR 14). - Account and provider settings go only through the official `oauth`, `setting` and `provider-settings` services of a plugin-owned Server, as Desktop does (ADR 17). Never read or write ZCode's credential or configuration files directly, store credentials in the plugin, or return API keys or native error messages to clients. -- On Paseo 0.11+, the provider's `status()` reports runtime discovery without starting a Server, and the `zcode` usage source reads Coding Plan quota only through `usage-stats.getEntitlementSnapshot` on the same Server (ADR 18). Register Paseo 0.11 APIs only when the daemon provides them, and import their types only from `@getpaseo/plugin/server`: older compilers reject `@getpaseo/plugin/server/usage`, even for types. +- The provider's `status()` reports runtime discovery without starting a Server, and the `zcode` usage source reads Coding Plan quota only through `usage-stats.getEntitlementSnapshot` on the same Server (ADR 18). - Computer Use and Browser Use cannot run in the provider's standalone Server (ADR 19), and Visualize renders only in Desktop (ADR 21). `server/unsupported-capabilities.ts` defines what the bridge passes to every Server (`ZCODE_CUA_PRODUCT_HELPER=0` and `PASEO_ZCODE_SUPPRESSED_PLUGINS`) and the per-turn `toolDisallowlist`. Keep the official switches as well as the patch: `PASEO_ZCODE_RUNTIME` runtimes are unpatched. -- Plugin preferences are Paseo host settings defined in `shared/` and followed on the server through the `registerSettings()` handle (ADR 24). Paseo 0.9.0 is the minimum because older daemons cannot read them. Model change markers are hidden by default; whether one is shown is decided when it is first seen. +- Plugin preferences are Paseo host settings defined in `shared/` and followed on the server through the `registerSettings()` handle (ADR 24). Model change markers are hidden by default; whether one is shown is decided when it is first seen. +- Paseo 0.15.0 is the minimum (ADR 25); do not add branches for older daemons or import deprecated SDK entries such as `@getpaseo/plugin/client/react-native`. Paseo closes an idle session after an hour unless the provider vetoes it: `session.can_stop_runtime` answers from ZCode's V4 state and keeps the runtime while foreground work, input, interactions, commands, running background work or subagents, or an active/verifying goal remain. `resultPending` stays after delivery on the pinned source, so it does not count. - Persistence handles use version 3. Do not migrate old Paseo handles or introduce Plan restoration storage. - The plugin is published to npm only through the Version Bump and Release workflows (ADR 16); see `docs/development.md`. npm installation omits development dependencies, so keep runtime libraries other than Paseo's host modules (`@getpaseo/plugin/*`, `zod`) in `dependencies`. The `build` commands in `paseo-plugin.json` prepare Git checkouts only; `prepack` removes them from the npm package. diff --git a/NOTICE.md b/NOTICE.md index 233a366..8952926 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -20,7 +20,7 @@ Node.js は利用者のマシンが nodejs.org の公式成果物を直接取得 ファイルごとの出典・SHA-256、private workspace import の変更、第三者通知の抽出範囲を [provenance.json](server/vendor/zcode/provenance.json) に記録しています。取得・照合は `scripts/sync-zcode-source.mjs` で行います。`npm run build` はこれらのライセンス・通知を `dist/licenses/zcode` にも配置します。 -開発 SDK は `@getpaseo/plugin@0.12.0` です。ビルドは `@getpaseo/plugin/server/provider` と `zod` を外部モジュールとして維持し、Paseo に解決させます。 +開発 SDK は `@getpaseo/plugin@0.15.3` です。ビルドは `@getpaseo/plugin/server/provider` と `zod` を外部モジュールとして維持し、Paseo に解決させます。 `icon.svg` は [Paseo main c424f829 の glm-acp-agent.svg](https://github.com/getpaseo/paseo/blob/c424f82922fcd36aa9cc9e473644bca04417b420/packages/app/src/assets/acp-provider-icons/glm-acp-agent.svg) のコピーです。この SVG は [ACP Registry の glm-acp-agent/icon.svg](https://github.com/agentclientprotocol/registry/blob/f3826ddd6e35951ea9b7fd0cf43c35a30c3c64cd/glm-acp-agent/icon.svg) とバイト単位で一致します。ACP Registry は Apache-2.0 で配布されており、その [LICENSE](vendor/acp-registry/LICENSE) を保持しています。アイコンは変更していません。商標への権利や公式の承認を示すものではありません。 diff --git a/README.md b/README.md index f9d5a71..ef8fe01 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ This is an unofficial plugin. It is not endorsed or maintained by ZCode or Z.ai. | Setting | Requirement | | -------------- | --------------------------------------------------------------------------------------------------------------------------------------- | -| Paseo | 0.9.0 or later; development SDK 0.12.0 | +| Paseo | 0.15.0 or later; development SDK 0.15.3 | | Plugin Node.js | 22.12.0 or later (the Paseo daemon's runtime) | | Managed setup | darwin-arm64, linux-x64, linux-arm64, win-x64, win-arm64 | | ZCode | Managed: 3.16.2 (release `3.16.2-paseo.1`) with Node.js 24.21.0. Overrides: stable Server 3.14.0+ / Agent 0.16.9+ with Node.js 24.14.0+ | @@ -24,9 +24,9 @@ paseo plugin add npm:paseo-plugin-zcode-provider paseo plugin ls ``` -You can also paste `npm:paseo-plugin-zcode-provider` into **Settings → Plugins → Plugin source**. npm packages require Paseo 0.9.0 or later and npm on the daemon host. Paseo installs the released version and compiles the plugin. Update with `paseo plugin update zcode-provider`. Plugins execute with the daemon user's permissions. +You can also paste `npm:paseo-plugin-zcode-provider` into **Settings → Plugins → Plugin source**. npm packages require npm on the daemon host. Paseo installs the released version and compiles the plugin. Update with `paseo plugin update zcode-provider`. Plugins execute with the daemon user's permissions. -To follow the `main` branch instead, install the Git repository with `paseo plugin add github:supermomonga/paseo-plugin-zcode-provider` (Paseo 0.9.0 or later). Since Paseo 0.11.0, the form without `github:` looks the plugin up in Paseo's plugin registry, which does not list it. Paseo prepares the checkout with `npm ci`. +To follow the `main` branch instead, install the Git repository with `paseo plugin add github:supermomonga/paseo-plugin-zcode-provider`. The form without `github:` looks the plugin up in Paseo's plugin registry, which does not list it. Paseo prepares the checkout with `npm ci`. ## Setup @@ -55,7 +55,7 @@ The **Account** tab uses ZCode's own account and provider services, the same one - **Sign in**: choose Z.ai (international) or BigModel (China) and press **Sign in**. The sign-in page opens in your browser; the link is also shown, so you can finish on any device. The daemon receives the result, then selects the account's Coding Plan unless a plan is already chosen. The **Plans** section shows which of the account's plans (Coding Plan, Start Plan) are available. ZCode allows one signed-in account at a time. - **Model providers**: add any number of providers that use an API key, from a ZCode template (Z.ai, BigModel, Kimi, MiniMax, DeepSeek, Alibaba Cloud, OpenAI, Anthropic, xAI, OpenRouter and others) or a custom endpoint with its base URL, API format and model IDs. Providers and models can be turned off, edited and deleted. -API keys are sent to ZCode, which stores them as Desktop does, and are never shown again. The plugin itself stores no credentials. Afterwards, choose **ZCode** when creating an agent; the model list is refreshed after each change on Paseo 0.9 or later. +API keys are sent to ZCode, which stores them as Desktop does, and are never shown again. The plugin itself stores no credentials. Afterwards, choose **ZCode** when creating an agent; the model list is refreshed after each change. ### Timeline @@ -63,7 +63,7 @@ ZCode adds a line when a turn runs on a different model than the previous turn, ### Coding Plan usage -On Paseo 0.11 and later, Paseo's **Usage** screen and sidebar usage summary show a **ZCode** card for the signed-in account's Individual Coding Plan (Z.ai or BigModel). It lists the 5-hour, weekly, monthly tool-call and ZCode MCP quotas with their reset times, as ZCode Desktop does. The plugin asks ZCode's official usage service for this plan only, on the same ZCode Server as the Account tab. The service never uses an API key from the environment. Team Plan and Start Plan are not shown. Paseo 0.12.0 does not yet show usage in a ZCode agent's popover. +Paseo's **Usage** screen and sidebar usage summary show a **ZCode** card for the signed-in account's Individual Coding Plan (Z.ai or BigModel). It lists the 5-hour, weekly, monthly tool-call and ZCode MCP quotas with their reset times, as ZCode Desktop does. The plugin asks ZCode's official usage service for this plan only, on the same ZCode Server as the Account tab. The service never uses an API key from the environment. Team Plan and Start Plan are not shown. Nothing is requested while **Check usage** is off for the host. Paseo 0.15.3 does not yet show usage in a ZCode agent's popover. ### Using your own runtime @@ -86,13 +86,14 @@ The source baseline is `3c5b227649371507ddc4eb46ac5133afe6db1cab` (ZCode 3.16.2, - Text, thoughts, tools, subagent progress, usage and history use V4 snapshots and deltas. Tool output is marked when ZCode truncates it. Usage is cumulative; repeated snapshots do not add it again. - Text submitted during generation uses native guidance. Attachments use the native queue. Paseo reports one run across these native turns and completes it only after all accepted input has been consumed and foreground work has ended. - Paseo sends every message typed in the app during a run as a steer that asks to clear pending permissions. The plugin queues it first, then declines pending permissions, questions and Plan approvals with their deny action until ZCode reads the message, including requests opened in the meantime. Requests that appear after it is read are left to the user. Declining a Plan approval in Plan mode ends ZCode's turn; the message then starts the next native turn in the same Paseo run (ADR 22). -- A failed turn reports a code classified from the attribution of ZCode's error: `MODEL_RATE_LIMITED`, `MODEL_AUTH_FAILED`, `MODEL_CONTEXT_EXCEEDED`, `MODEL_NETWORK_ERROR`, `MODEL_PROVIDER_ERROR` or `MODEL_REQUEST_FAILED` when the model provider or network failed, and `NATIVE_TURN_FAILED` otherwise. The message is the plugin's own text with the HTTP status and the provider's error code when known. The provider's own message, which can include a quota reset time, is not shown; Coding Plan reset times appear on Paseo 0.11's Usage screen (ADR 23). +- A failed turn reports a code classified from the attribution of ZCode's error: `MODEL_RATE_LIMITED`, `MODEL_AUTH_FAILED`, `MODEL_CONTEXT_EXCEEDED`, `MODEL_NETWORK_ERROR`, `MODEL_PROVIDER_ERROR` or `MODEL_REQUEST_FAILED` when the model provider or network failed, and `NATIVE_TURN_FAILED` otherwise. The message is the plugin's own text with the HTTP status and the provider's error code when known. The provider's own message, which can include a quota reset time, is not shown; Coding Plan reset times appear on Paseo's Usage screen (ADR 23). - Acceptance is reported once, after the native acknowledgement. Unknown delivery results are never automatically resent. Stop identifies the current native execution, disables automatic queue execution and removes pending input. A new explicit run enables the queue again. - As in ZCode Desktop, successful hooks are not shown. A finished hook invocation appears once, as a notification, only when a hook was blocked, failed, timed out or was cancelled; context compaction also appears once, when it ends. Paseo appends every notification it receives, so progress is not reported. Model changes appear only when turned on (see [Timeline](#timeline)). - Native permission IDs, option values, questions and Plan approval retain their meanings. Question auto-resolution is disabled for each owned Server. Workspace hook trust is reviewed through the official CLI; it is not represented as “allow once.” - Each session owns its Server process and environment. Metadata requests use temporary Servers. Closing stdin gives ZCode time to clean up before process termination. +- With **Release idle agents** (Host settings → Agents, on by default), Paseo closes an agent's session after an hour of inactivity and reopens it on the next message. The plugin keeps the session while ZCode still has a foreground turn, queued input, a pending question or approval, a running background command, subagent or workflow, or a goal that is active or being verified (ADR 25). A finished background command's result that ZCode has not yet delivered is not distinguishable and does not keep it. **Resume agents after restart** reopens agents interrupted by a host restart and sends the resume prompt. Both reopen the saved conversation with Paseo's saved mode and Plan settings ([ADR 14](docs/adr/0014-paseoの保存設定を再適用する復元を保証範囲とする.md)). -The plugin uses ZCode's own skills, MCP configuration and tools. Browser Use and Computer Use cannot run in the plugin's ZCode, even when ZCode Desktop has them enabled: the Computer Use helper accepts only the signed Desktop app, and only Desktop provides browsers. ZCode's Visualize (interactive views in the conversation) renders only in Desktop. The plugin therefore hides all three from the model (ADR 19, ADR 21); Desktop is not affected. Generic rewind, independent Paseo child agents, hook-review UI and Goal/Workflow controls are outside this migration. `prompt.output_schema`, custom system prompts and `persist:false` are unsupported. A system prompt makes session creation fail with `INVALID_CONFIGURATION` and a message explaining why, including one appended by Paseo's Orchestration → System prompt setting or by another plugin that adds one to new agents. MCP `alwaysLoad` is unsupported; stdio MCP commands must be absolute paths. Provider options are unsupported: in Paseo 0.11 and later, `agents.providers.zcode.options` in Paseo's `config.json` makes sessions fail with `INVALID_CONFIGURATION`, and the `command` and `env` overrides there are not applied. Paseo does not show context usage reported before the first turn, and the plugin adds no substitute display; Coding Plan quota appears in Paseo 0.11's Usage screen (see [Coding Plan usage](#coding-plan-usage)). +The plugin uses ZCode's own skills, MCP configuration and tools. Browser Use and Computer Use cannot run in the plugin's ZCode, even when ZCode Desktop has them enabled: the Computer Use helper accepts only the signed Desktop app, and only Desktop provides browsers. ZCode's Visualize (interactive views in the conversation) renders only in Desktop. The plugin therefore hides all three from the model (ADR 19, ADR 21); Desktop is not affected. Generic rewind, independent Paseo child agents, hook-review UI and Goal/Workflow controls are outside this migration. `prompt.output_schema`, custom system prompts and `persist:false` are unsupported. A system prompt makes session creation fail with `INVALID_CONFIGURATION` and a message explaining why, including one appended by Paseo's Orchestration → System prompt setting or by another plugin that adds one to new agents. MCP `alwaysLoad` is unsupported; stdio MCP commands must be absolute paths. Provider options are unsupported: `agents.providers.zcode.options` in Paseo's `config.json` makes sessions fail with `INVALID_CONFIGURATION`, and the `command` and `env` overrides there are not applied. Paseo does not show context usage reported before the first turn, and the plugin adds no substitute display; Coding Plan quota appears in Paseo's Usage screen (see [Coding Plan usage](#coding-plan-usage)). ## Persistence @@ -104,7 +105,7 @@ New conversations support listing, resume and paged V4 history. From ZCode 3.16, ## Diagnostics -**Settings → Plugins → zcode-provider → Diagnostics** shows whether the managed runtime or the environment override is in use, the runtime and Node.js paths and versions, Server/Agent versions and hashes, minimum-version assessment and mapping location. The screen is read-only. Its optional version check does not prove that authentication or a model call succeeds. On Paseo 0.11 and later, **Settings → Providers** also shows ZCode as not installed until the runtime is set up and supported. Its diagnostic lists the runtime source, Server, Agent and Node.js versions and platform, or the reason the runtime cannot be used. This check reuses its result for 30 seconds and does not start ZCode, so sign-in problems still appear when a session starts. +**Settings → Plugins → zcode-provider → Diagnostics** shows whether the managed runtime or the environment override is in use, the runtime and Node.js paths and versions, Server/Agent versions and hashes, minimum-version assessment and mapping location. The screen is read-only. Its optional version check does not prove that authentication or a model call succeeds. **Settings → Providers** also shows ZCode as not installed until the runtime is set up and supported. Its diagnostic lists the runtime source, Server, Agent and Node.js versions and platform, or the reason the runtime cannot be used. This check reuses its result for 30 seconds and does not start ZCode, so sign-in problems still appear when a session starts. ```bash paseo plugin logs zcode-provider diff --git a/client/account.tsx b/client/account.tsx index c519d40..a787bd2 100644 --- a/client/account.tsx +++ b/client/account.tsx @@ -1,13 +1,13 @@ import { useCallback, useEffect, useRef, useState } from "react"; -import { Linking, Platform, Text, View } from "react-native"; +import { Platform, Text, View } from "react-native"; import { getPaseoClient, openExternalUrl, type PluginSurfaceProps, useRpc, } from "@getpaseo/plugin/client"; -import { copyText } from "@getpaseo/plugin/client/react-native"; import { + copyText, SettingsAction, SettingsCard, SettingsInput, @@ -56,18 +56,9 @@ const CUSTOM = "custom"; const failure = (cause: unknown) => cause instanceof Error ? cause.message : "The account request failed."; -// openExternalUrl, copyText and getPaseoClient arrived in Paseo 0.9; 0.8 -// hosts omit them. -async function openUrl(url: string): Promise { - if (typeof openExternalUrl === "function") await openExternalUrl(url); - else await Linking.openURL(url); -} -const canCopy = typeof copyText === "function"; - // Paseo caches provider catalogs, so new models would otherwise appear only // after a manual refresh. function refreshCatalog(serverId: string): void { - if (typeof getPaseoClient !== "function") return; getPaseoClient(serverId) .providers.refresh({ providers: ["zcode"] }) .catch(() => {}); @@ -152,7 +143,7 @@ function Account({ const { account, signIn } = view; const open = (url: string) => { setOpenError(null); - openUrl(url).catch(() => + openExternalUrl(url).catch(() => setOpenError("The browser could not be opened. Copy the link instead."), ); }; @@ -216,14 +207,12 @@ function Account({ actionLabel="Open" onPress={() => open(signIn.authorizeUrl)} />, - canCopy ? ( - void copyText(signIn.authorizeUrl)} - /> - ) : null, + void copyText(signIn.authorizeUrl)} + />, void openUrl(template.apiKeyManagementUrl!)} + onPress={() => void openExternalUrl(template.apiKeyManagementUrl!)} /> ) : null} void openUrl(provider.apiKeyManagementUrl!)} + onPress={() => + void openExternalUrl(provider.apiKeyManagementUrl!) + } /> ) : null} w.status === "running")` として求める(`sessions-index-projection.ts`)。スキーマのコメントには、`resultPending` は結果を届けると消えるとある。しかし 3c5b227 の `product-projection.ts` の `onBackgroundTaskLifecycle` は、完了を `resultPending` に変えるだけで、項目を消す経路を持たない。管理下ランタイム 3.16.2 でも、結果を届けたターンが完了した後まで `resultPending` が残った。 + +プラグインには、Paseo 0.8〜0.10 向けの分岐も残っていた。daemon に `registerUsageSource` が有るか確かめてから登録する処理と、Account タブの `openExternalUrl`・`copyText`・`getPaseoClient` が無い場合の代替である。`copyText` は、0.13 で非推奨になった `@getpaseo/plugin/client/react-native`(2027-04-20 以降に削除)から読んでいた。ユーザーは、最低要件を 0.15 に上げることを認めた。 + +## Decision Drivers + +- アイドル時の解放で、Paseo からは見えない ZCode の作業を失わない。 +- 判断には ZCode が公式に投影する V4 の状態だけを使い、ZCode 自身と同じ基準にする。 +- 完了した作業のせいで、ランタイムを解放できない状態が続かないようにする。 +- 解放後の開き直しと、再起動後の再開を、ADR 14 の保証範囲の中に収める。 +- 対応しない Paseo のための分岐を持たない。宣言する最低要件を、実際に検証した版に近づける。 + +## Considered Options + +- `session.can_stop_runtime` を宣言し、V4 の状態に未完了の作業がある間は拒否する。最低要件を 0.15.0 に上げる。 +- `session.can_stop_runtime` を宣言せず、Paseo の基本条件に任せる。 +- 宣言したうえで、`resultPending` の作業も未完了として扱う。 +- 宣言を加え、最低要件は 0.9.0 のままにする。 + +## Decision Outcome + +Chosen option: 「`session.can_stop_runtime` を宣言し、V4 の状態に未完了の作業がある間は拒否する。最低要件を 0.15.0 に上げる」。ZCode の作業を失わない唯一の選択肢であり、かつ完了した作業のせいで解放が止まり続けることも無いため。 + +- 接続と `session.opened` の capabilities に `session.can_stop_runtime` を加える。問い合わせには、同じ `requestId` と `sessionId` を持つ `session.can_stop_runtime` で答える。`request.completed` は送らない。知らないセッションへの問い合わせは `request.failed` にする(Paseo は解放しない)。 +- 次のすべてを満たすときだけ `canStop: true` を返す。Paseo の実行が無い。受付待ちの入力が無い。会話がアイドルである(`canStop`・`activeWorks`・`running`/`prewarming`・待機キュー・再同期が無い)。`pendingInteractions` と `pendingCommands` が空である。`backgroundWorks` に `running` が無い。`subagents.running` が空である。`goal` が `active` でも `verifying` でもない。 +- `resultPending` は数えない。上記の理由で、届けた後も残るためである。結果を届けるターンが動いている間は、フォアグラウンドの条件で解放を拒否する。 +- 解放後の開き直しも再起動後の再開も、Paseo が保存した `mode` と `settings.plan_mode` を渡す `session.open` を通る。ADR 14 の保証範囲は変えない。 +- `paseo-plugin.json` の最低要件を `>=0.15.0` に上げる。開発 SDK を 0.15.3 にし、CI の上流チェックアウトを v0.15.3 に固定する。usage source は無条件に登録する。Account タブは `openExternalUrl`・`getPaseoClient` と `@getpaseo/plugin/client/ui` の `copyText` を直接使う。 + +### Consequences + +- Good, because バックグラウンドの Bash・サブエージェント・workflow の実行と、進行中の goal が、アイドル時の解放で止められない。 +- Good, because 古い Paseo のための分岐が無くなり、宣言する最低要件が、Paseo 自身の判定で確かめた範囲になる。 +- Bad, because Paseo 0.9〜0.14 の利用者は、新しい版を導入できない。 +- Bad, because 完了したがまだ届いていないバックグラウンドの結果は、状態から区別できない。結果がすぐに届かない状況で解放された場合に、その結果が失われるかは確認していない。 +- Bad, because `active` のまま進まない goal があると、ランタイムと Server のプロセスが解放されずに残る。 + +### Confirmation + +`test/provider.test.ts` で、capability の宣言、応答の形、`request.completed` を送らないこと、知らないセッションでの失敗を確認する。あわせて、フォアグラウンドの実行・`running` の作業・実行中のサブエージェント・`active`/`verifying` の goal では拒否し、`resultPending` と `paused` では拒否しないことも確認する。`npm run test:upstream`(v0.15.3)では、次の三つを確認する。Paseo の実アダプターの `canStopRuntime()` が `running` の作業の有無で答えを変えること。Paseo の `compileDirectoryPlugin` が 0.14.0 を拒否すること。クライアントのバンドルが `client/react-native` を読まないこと。`npm run test:stdio-runtime` は実ランタイムで次の二つを確認する。`run_in_background` の `sleep 3` が動いている間は拒否し、結果を届けたターンの完了後は拒否しないこと。実行中に Server を SIGKILL した会話を、保存した設定で開き直して `Resume working.` を送ると完了すること。 + +## Pros and Cons of the Options + +### V4 の状態で拒否し、最低要件を 0.15.0 に上げる + +- Good, because ZCode と同じ基準で、作業が残る間だけランタイムを保つ。 +- Bad, because 古い Paseo を切り捨てる。 + +### 宣言せず Paseo の基本条件に任せる + +- Good, because 実装が要らない。 +- Bad, because バックグラウンドの作業が 1 時間後に止められる。 + +### `resultPending` も未完了として扱う + +- Good, because 届いていない結果を確実に守れる。 +- Bad, because 固定ソースでは届いた後も残るので、バックグラウンドの作業を一度使ったセッションは二度と解放されない。 + +### 宣言を加え、最低要件は 0.9.0 のままにする + +- Good, because 古い Paseo の利用者も更新できる。capability の交渉により、古い daemon では問い合わせが来ないだけになる。 +- Bad, because 0.8 系向けの分岐と非推奨の UI 入口が残る。また、宣言する最低要件を実コンパイラで検証できていない状態も続く。 + +## More Information + +ADR 18 のうち「daemon が `registerUsageSource` を持つときだけ登録する」を、無条件の登録に変える。ADR 17 の互換性の段落(0.8 での代替)を取り下げる。ADR 24 で上げた最低要件 0.9.0 を、0.15.0 に上げる。ADR 14 は変えない。 + +- Paseo v0.15.3(`d91ae138cb931447635e94296023414a58bedcc5`):`public-docs/plugins/providers.md` の Permit idle runtime cleanup、`packages/server/src/server/agent/idle-runtime-cleanup/index.ts`、`agent-manager.ts` の `getRuntimeCleanupCandidates` と `runtimeHasNoPendingWork`、`plugin-provider.ts` の `canStopRuntime` +- ZCode 3c5b227:`packages/shared/src/zcode-protocol-v4/snapshot.ts` の `backgroundWorkSummarySchema`、`apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/product-projection.ts` の `onBackgroundTaskLifecycle`、`sessions-index-projection.ts` の `hasBackgroundWork` + +ZCode が届けた結果の項目を消すようになったとき、または配送待ちの結果を状態に出すようになったときは、`resultPending` の扱いを見直す。Paseo が解放の契約を変えたときも見直す。 diff --git a/docs/adr/README.md b/docs/adr/README.md index 57862e6..e3a1dc7 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -22,3 +22,4 @@ * [22. Paseoが求めるときは受け付けたSteerが読まれるまで保留中の権限確認を拒否する](0022-paseoが求めるときは受け付けたsteerが読まれるまで保留中の権限確認を拒否する.md) * [23. ターンの失敗はV4のlastErrorのattributionで分類したコードと固定の文言で伝える](0023-ターンの失敗はv4のlasterrorのattributionで分類したコードと固定の文言で伝える.md) * [24. モデル切り替えの表示をPaseoの設定APIで選べるようにし最低要件を0.9.0に上げる](0024-モデル切り替えの表示をpaseoの設定apiで選べるようにし最低要件を0-9-0に上げる.md) +* [25. Paseo 0.15を最低要件にしZCodeの作業が残る間はアイドル時のランタイム解放を拒否する](0025-paseo-0-15を最低要件にしzcodeの作業が残る間はアイドル時のランタイム解放を拒否する.md) diff --git a/docs/development.md b/docs/development.md index 0d87c76..fb03f03 100644 --- a/docs/development.md +++ b/docs/development.md @@ -12,7 +12,7 @@ npm run check:zcode-source -- ~/ghq/github.com/zai-org/ZCode npm run test:upstream -- /absolute/path/to/paseo ``` -`test:upstream` uses Paseo's actual plugin compiler, Git preparation and Provider adapter. Use commit `cafe4b01c8522ff39560241c5deb01427dc8dc5b` (0.12.0), matching the installed development SDK. It checks clean npm preparation of a Git checkout both with `NODE_ENV` unset and `production`, installation of the `npm pack` tarball with Paseo's npm acquisition options, server/client registration (including the timeline settings document) and the provider icon of both, V4 timeline, guidance, attachment queue aggregation, a classified turn failure, stop, provider replacement, history and Plan configuration on resume. The adapter fixture uses the official V4 schemas and delta application; it does not prove native behavior. +`test:upstream` uses Paseo's actual plugin compiler, Git preparation and Provider adapter. Use commit `d91ae138cb931447635e94296023414a58bedcc5` (0.15.3), matching the installed development SDK. Paseo runs compilation and preparation in a worker; the check loads the worker's own modules (`compiler-build.ts`, `preparation-build.ts`) instead. It checks clean npm preparation of a Git checkout both with `NODE_ENV` unset and `production`, installation of the `npm pack` tarball with Paseo's npm acquisition options, the daemon's `requirements.paseo` check (0.14.0 is rejected), server/client registration (including the timeline settings document and the usage source) and the provider icon of both, that the client imports no deprecated SDK entry, V4 timeline, guidance, attachment queue aggregation, the idle runtime veto, a classified turn failure, stop, provider replacement, history and Plan configuration on resume. The adapter fixture uses the official V4 schemas and delta application; it does not prove native behavior. ## Source of truth @@ -73,7 +73,7 @@ The baseline's remote terminal service cannot locate the integrated distribution `npm run test:usage-runtime` runs the provider's `status()` and the Coding Plan usage source (ADR 18) against the same runtime and existing ZCode sign-in, and validates the results with Paseo's `ProviderStatusSchema` and `UsageReportSchema`. ZCode requests the account's quota from Z.ai or BigModel; the check writes no settings and prints no account names or keys. -`npm run test:stdio-runtime` exercises the real extracted Server and Agent against a deterministic **local HTTP model fixture**, without billable API calls. It isolates HOME, ZCode settings, the SQLite database, temp sockets, workspace and plugin mappings. It checks catalog, draft, Bash, acknowledgements, completion, paged replay, mode/Plan restore **with both saved Paseo settings**, questions, tool approval, targeted stop and restart, a provider quota failure (HTTP 429 with GLM's code 1310) that must arrive as `MODEL_RATE_LIMITED` without the provider's text and a following completed turn, session listing and owned Agent exit after Server SIGKILL. The test captures the settings before shutdown, closes the Server, opens a separate connection and requires the restored settings to be reported before `session.ready`. Any failed assertion exits nonzero. It deletes test data after cleanup. Loopback and Unix sockets require execution outside a restrictive network sandbox. +`npm run test:stdio-runtime` exercises the real extracted Server and Agent against a deterministic **local HTTP model fixture**, without billable API calls. It isolates HOME, ZCode settings, the SQLite database, temp sockets, workspace and plugin mappings. It checks catalog, draft, Bash, acknowledgements, completion, paged replay, mode/Plan restore **with both saved Paseo settings**, questions, tool approval, targeted stop and restart, a provider quota failure (HTTP 429 with GLM's code 1310) that must arrive as `MODEL_RATE_LIMITED` without the provider's text and a following completed turn, the idle runtime veto while a `run_in_background` Bash runs and its release after the turn that delivers the result (ADR 25), session listing, owned Agent exit after Server SIGKILL, and resuming that interrupted conversation with the saved settings and Paseo's `Resume working.` prompt. The test captures the settings before shutdown, closes the Server, opens a separate connection and requires the restored settings to be reported before `session.ready`. Any failed assertion exits nonzero. It deletes test data after cleanup. Loopback and Unix sockets require execution outside a restrictive network sandbox. `npm run test:native-restore` adds a strict check of cold resume **without explicit settings** to the same isolated runner. It fails on the pinned source because ZCode replaces saved execution state with an old message mode and Plan OFF. This path is outside the supported restoration contract, so this command is separate from required CI and release conditions; there is no `continue-on-error` or blanket error suppression. Run it when evaluating official runtime updates and record the outcome. A successful upstream check is evidence for reconsidering the guarantee, not an automatic expansion of it. See [ADR 14](adr/0014-paseoの保存設定を再適用する復元を保証範囲とする.md). diff --git a/docs/todo.md b/docs/todo.md index fc015c4..2dc12f9 100644 --- a/docs/todo.md +++ b/docs/todo.md @@ -17,7 +17,8 @@ Paseo・ZCode 本体の改変は禁止。対応範囲はこの Provider に限 - プロキシや社内ミラーのみの環境での取得。現状は nodejs.org と GitHub への直接接続が必要で、失敗時は環境変数の上書きで回避する。 - Desktop ネイティブ画面とモバイル実機での操作。Electron Helper / 通常 Node の両 daemon 起動と、実 Web UI の入力・質問・承認・停止・再起動復元は確認済み([検証記録](verification.md))。 - macOS x64(管理下セットアップの対象外)、長時間ツール/MCP 子プロセスを含む異常終了時の回収は未検証。 -- native の長い会話・世代変更・background continuation・子エージェントからの権限要求。現在の契約試験の結果と実行確認を混同しない。 +- native の長い会話・世代変更・子エージェントからの権限要求。background continuation は、`run_in_background` の Bash の結果が届くまでを契約試験で確認した。現在の契約試験の結果と実行確認を混同しない。 +- アイドル時の解放(ADR 25)で、完了したがまだ届いていないバックグラウンドの結果が失われるか。固定ソースの V4 の状態は、届けた後も `resultPending` を残すので区別できない。ZCode が届けた項目を消すようになったら、扱いを見直す。 - Desktop でアーカイブした会話。ZCode 3.16 の `session/list` はアーカイブを除かなくなり、Paseo の一覧にも出る。アーカイブはサービス側のタスク索引(`zcodeTaskService`)にあるので、公式サービスで除外できるか確認する。 - 統合 CLI の remote terminal 用 node-pty 配置。Provider はその terminal API を呼ばず、Agent Bash は検証済みだが、upstream 配布の問題として追跡する。 @@ -31,7 +32,7 @@ Paseo 標準の quota/リセット時刻/初期 usage 表示は公開プラグ `ProviderRegistration.status()` と usage source を採用した([ADR 18](adr/0018-paseo-0-11のprovider-statusとusage-sourceでランタイムの可用性とcoding-planの利用量を表示する.md))。残る項目は次のとおり。 -- **ZCode エージェント単位の利用量**:0.12.0 の Paseo も、プラグイン Provider のセッションでアカウントを探索しない(`plugin-provider.ts` の `PluginAgentSession` に `usageSession()` が無い)ため、エージェントのポップオーバーに利用量が出ない。プラグインはセッションの範囲の探索に対応済みなので、Paseo が探索するようになったら表示を確認する。 +- **ZCode エージェント単位の利用量**:0.15.3 の Paseo も、プラグイン Provider のセッションでアカウントを探索しない(`plugin-provider.ts` の `PluginAgentSession` に `usageSession()` が無い)ため、エージェントのポップオーバーに利用量が出ない。プラグインはセッションの範囲の探索に対応済みなので、Paseo が探索するようになったら表示を確認する。 - **Team Plan と Start Plan の利用量**:Desktop は Team Plan に組織とプロジェクトを含む動的なアカウントアクセスを渡し、Start Plan は残高として別に表示する。同じ経路を公式サービスで再現できるか確認してから対応する。 - **サインイン状態の可用性**:`status()` はランタイムだけを検査する。未サインインやモデルが無い状態は、Server を起動しないと分からないため、従来どおりセッション作成時に知らせる。 -- **初期 usage**:0.10.3、0.11.0-beta.5、0.12.0 でも、`session.ready` 前に送った使用量は購読者へ再通知されない。0.11.0-beta.4 の変更(getpaseo/paseo#6089)は、初回ターン前のメーターをアプリ側で空表示にするものである。制約は残る。 +- **初期 usage**:0.10.3、0.11.0-beta.5、0.12.0 でも、`session.ready` 前に送った使用量は購読者へ再通知されない。0.15.3 のアダプターも、ready 前のイベントは履歴に積むだけで購読者へ流さない。0.11.0-beta.4 の変更(getpaseo/paseo#6089)は、初回ターン前のメーターをアプリ側で空表示にするものである。制約は残る。 diff --git a/docs/verification.md b/docs/verification.md index 4f1e3a1..05cd6a7 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -1,3 +1,38 @@ +# Paseo 0.15.3 への追従(2026-11-09) + +Issue #69、#75〜#82、#85、#87〜#89 の対応。Paseo 0.13.0-beta.1 から 0.15.3 までの変更履歴を読んだ。あわせて v0.12.0 と v0.15.3(`d91ae138cb931447635e94296023414a58bedcc5`)の差分を確認した。対象は `packages/plugin`、`plugin-provider.ts`、`agent-manager.ts`、アイドル時の解放、プラグインのコンパイラと準備処理である。判断は [ADR 25](adr/0025-paseo-0-15を最低要件にしzcodeの作業が残る間はアイドル時のランタイム解放を拒否する.md) に記録した。 + +## 変更履歴とこのプロバイダ + +- **Provider の契約**:0.14 で `session.can_stop_runtime` の入力とイベントが加わった。それ以外の入力・イベント・capabilities と usage source の契約は変わっていない。 +- **アイドル時の解放(#7782)**:既定でオンで、1 時間アイドルのセッションを close する。拒否するには、プロバイダーが capability を宣言する必要がある。プラグインのバックグラウンドの作業は `tool_call` として出しているので、Paseo の基本条件では守られない。`session.can_stop_runtime` を実装した。 +- **再起動後の再開(#8127、#8619、既定はオフ)**:既存の `session.open` の再開経路を使い、保存された `modeId` と `featureValues` を渡してから `Resume working.` を送る。実ランタイムで確認した(下記)。 +- **UI の入口(#7474)**:`@getpaseo/plugin/client/react-native` は非推奨になった。`copyText` を `@getpaseo/plugin/client/ui` から読むように変えた。0.15.3 のアプリの `client/ui`(`packages/app/src/plugins/react-native/ui.ts`)も `copyText` を出している。 +- **コンパイラ**:0.15 ではコンパイルと準備を worker で行う。`test:upstream` は、worker が読むモジュール(`compiler-build.ts`、`preparation-build.ts`)を直接使うように変えた。アダプターは CommonJS の `which` を取り込むので、バンドルに `require` を用意した。 +- **確認したが変更しない項目**:次の項目は、このプロバイダの経路に関係しないか、Paseo の中だけで完結する。 + - プラグインがエージェントに渡すツール(#7938)は、Paseo の MCP サーバーのツールとして登録される(`registerPluginTools`)。 + - turn-ended フックの `timeline` が空になった変更(#7477)と、worktree のフック(#8117、#8081)。プラグインはフックを使わない。 + - プラグインの会話を rewind した後の修正(#8368)。プラグインは rewind を宣言しない。 + - 表示中だけ利用量を取得し、**Check usage** で止められる変更(#8181)。usage source の呼び出しは、この設定で止まる要求からだけ行われる。 + - 翻訳・ファイルパネル・SVG アイコンは採用しない。 +- **残る制約**:0.15.3 でも、プラグイン Provider のセッションには `usageSession()` が無い。ready より前のイベントは、アダプターの履歴に積まれるだけで購読者へ流れない。 + +## ZCode の挙動(3c5b227、管理下ランタイム 3.16.2-paseo.1) + +- `run_in_background` の Bash は、フォアグラウンドのターンが終わった後も `backgroundWorks` に `running` で残る。終わると `resultPending` になり、ZCode が結果を届けるターンを自分から始める。 +- 結果を届けたターンが完了した後も、20 秒以上 `resultPending` のまま残った。`product-projection.ts` の `onBackgroundTaskLifecycle` には、項目を消す経路が無い。このため `resultPending` は拒否の条件に入れない。 +- 実行中に Server を SIGKILL した会話も、別の接続から保存した設定で開き直せる。プラグインの「再開した会話にフォアグラウンドの作業が残っている」という拒否には当たらなかった。続けて送った `Resume working.` のターンも完了した。 + +## 検証(Linux x64、Node.js 26.8.1、2026-11-09) + +- **テスト**:`test/provider.test.ts` に拒否の条件のテストを加えた。条件をフォアグラウンドのアイドルだけに弱めると、このテストが失敗することを確かめた。`npm run typecheck`、`npm test`(24 ファイル、234 tests)、`npm run build`、`npm run format:check` が成功した。 +- **上流**:`git clone --shared` で作った別の clone を v0.15.3 にし、`NODE_PATH` を外して `npm run test:upstream` を実行し、成功した。Git と npm からの導入で、Paseo の `compileDirectoryPlugin` が 0.14.0 を拒否し 0.15.3 を受け入れることを確かめた。クライアントのバンドルが `client/react-native` を読まないことも確かめた。実アダプターの `canStopRuntime()` は、`running` の作業がある間だけ `false` を返した。 +- **実ランタイム**:管理下ランタイム 3.16.2-paseo.1 を一時的な `XDG_DATA_HOME` に導入し、`npm run test:stdio-runtime` を実行して成功した。加えた確認は二つある。`sleep 3` のバックグラウンドの Bash で、動いている間は拒否し、結果を届けたターンの後は拒否しないこと。SIGKILL 後に開き直して再開すること。 +- **CI**:[run 42562005991](https://github.com/supermomonga/paseo-plugin-zcode-provider/actions/runs/42562005991) の管理下ランタイムの契約(darwin-arm64、linux-x64、linux-arm64、win32-x64、win32-arm64)で、追加した二つの確認を含めて `test:stdio-runtime` が成功した。実モデルの E2E も成功した。 +- **実 daemon**:`@getpaseo/cli@0.15.3` を一時ディレクトリに入れた。一時 daemon(`--home` は一時ディレクトリ、loopback、relay と MCP は無効、plugins は有効)に、作業ツリーを複製して準備したディレクトリを導入した。プラグインは `running` になり、ZCode は available で、診断は Server 3.16.2 / Agent 0.17.0 を示した。ヘッドレス Chrome で Settings → Plugins → zcode-provider → Settings を開くと、Runtime・Account・Timeline の各タブが表示された。HOME は隔離していないので、モデル一覧と Account タブはこの端末の既存の ZCode のデータを読んだ。会話は作っていない。 + +未検証:実 daemon でのアイドル時の解放と再起動後の再開(1 時間の待機と、ZCode のセッションの作成が要る)。サインイン中の Account タブの Copy ボタン。Paseo 0.15.0 の実 daemon。完了したがまだ届いていないバックグラウンドの結果が、解放で失われるか。 + # モデル切り替えの行を設定で出し分ける(2026-11-09) [Issue #83](https://github.com/supermomonga/paseo-plugin-zcode-provider/issues/83) で、ZCode のエージェントのタイムラインに `Model: GLM-5.3-Flash ()` と `Model: auto/glm-5.3-flash (max)` がターンごとに交互に増えると報告された。 diff --git a/index.server.ts b/index.server.ts index 00fe1aa..3f5295e 100644 --- a/index.server.ts +++ b/index.server.ts @@ -34,10 +34,8 @@ export default function contribute(server: PluginServerContext): () => void { ); server.handle(zcodeAccountView, () => account.view()); server.handle(zcodeAccountChange, (input) => account.change(input)); - // Usage sources arrived in Paseo 0.11; older daemons do not offer them. const usage = createUsageSource(account); - if (typeof server.registerUsageSource === "function") - server.registerUsageSource(usage.source); + server.registerUsageSource(usage.source); return () => { usage.dispose(); timeline.dispose(); diff --git a/package-lock.json b/package-lock.json index 1dc0a20..aa7de59 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,9 +12,9 @@ "semver": "7.8.5" }, "devDependencies": { - "@getpaseo/client": "0.12.0", - "@getpaseo/plugin": "0.12.0", - "@getpaseo/protocol": "0.12.0", + "@getpaseo/client": "0.15.3", + "@getpaseo/plugin": "0.15.3", + "@getpaseo/protocol": "0.15.3", "@types/node": "22.18.3", "@types/react": "~19.2.0", "@types/semver": "7.8.0", @@ -980,29 +980,31 @@ } }, "node_modules/@getpaseo/client": { - "version": "0.12.0", - "resolved": "https://registry.npmjs.org/@getpaseo/client/-/client-0.12.0.tgz", - "integrity": "sha512-FrszuQkG73mbU5nJcaWKjW2K1mDt6k1veCa2acV9V8HphPD7BtQLPiiUnXsSUdYeP8S54duGbuYfZgaVyUvd5g==", + "version": "0.15.3", + "resolved": "https://registry.npmjs.org/@getpaseo/client/-/client-0.15.3.tgz", + "integrity": "sha512-gdZ7pmLIVmFof8lUUEUH5NmaqJ6W3u8SelerwaBn6Ygv+iRzVSZeMt43/OyrEmdr8p3eCMj4D3TrCP3T6ZdrZw==", "dev": true, "dependencies": { - "@getpaseo/protocol": "0.12.0", - "@getpaseo/relay": "0.12.0", + "@getpaseo/protocol": "0.15.3", + "@getpaseo/relay": "0.15.3", + "ws": "^8.20.0", "zod": "^4.4.3" } }, "node_modules/@getpaseo/plugin": { - "version": "0.12.0", - "resolved": "https://registry.npmjs.org/@getpaseo/plugin/-/plugin-0.12.0.tgz", - "integrity": "sha512-LSwpGU3o6/SRAfzIIq9BA6aqEO6LRmbJTyyCRl+jWCsguL++klMpf6HBbAZJtQOlv5YuF21gjKZvLcSkngpxFg==", + "version": "0.15.3", + "resolved": "https://registry.npmjs.org/@getpaseo/plugin/-/plugin-0.15.3.tgz", + "integrity": "sha512-c5+bi4M5CKSV85vEcms/NDDBrIn0jaihofXm/P73Hni0movbrn3hv/QQdOY3pcaQ07zNqi6P7VzNLanryUIYgA==", "dev": true, "dependencies": { "@agentclientprotocol/sdk": "^1.4.0", + "i18next": "^26.3.0", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { - "@getpaseo/client": "0.12.0", - "@getpaseo/protocol": "0.12.0", - "react": "~19.1.0", + "@getpaseo/client": "0.15.3", + "@getpaseo/protocol": "0.15.3", + "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" }, @@ -1013,9 +1015,9 @@ } }, "node_modules/@getpaseo/protocol": { - "version": "0.12.0", - "resolved": "https://registry.npmjs.org/@getpaseo/protocol/-/protocol-0.12.0.tgz", - "integrity": "sha512-05jivVDeG18jWTpvQZ3yETNxH/AfHpHy9CgnP7O5ZxQLUr3onJIAqaGNzv15dPnGf4fU342UHQBFAE2t2Yc7fQ==", + "version": "0.15.3", + "resolved": "https://registry.npmjs.org/@getpaseo/protocol/-/protocol-0.15.3.tgz", + "integrity": "sha512-JhAYutwgLUSDdvDhQ8yLjxzqJroR3yqmt+5/rv07iqmOAd/CNtKNJSXZAFaTOavWZcRVlL6DD3tkwaobjgb1Xg==", "dev": true, "dependencies": { "semver": "^7.8.5", @@ -1023,11 +1025,14 @@ } }, "node_modules/@getpaseo/relay": { - "version": "0.12.0", - "resolved": "https://registry.npmjs.org/@getpaseo/relay/-/relay-0.12.0.tgz", - "integrity": "sha512-ochmc4uIZWlSgMr9aJIEqnyiFrhcW+TjOWxnTYX4LCyiJMvLrhN4DJpZlReAqyWmSgEybjjRBq+7NBH64FIV3A==", + "version": "0.15.3", + "resolved": "https://registry.npmjs.org/@getpaseo/relay/-/relay-0.15.3.tgz", + "integrity": "sha512-zLgnVLLo1WsVXIQQF5z1DAt7hg6t6K3Zbxnk22uA/DUKE0ip1brQQSmgN1cNN7a9ss3Hqg5Fdr/4r4Yh401gDA==", "dev": true, "dependencies": { + "@noble/ciphers": "^2.4.0", + "@noble/curves": "^2.4.0", + "@noble/hashes": "^2.4.0", "base64-js": "^1.5.1", "tweetnacl": "^1.0.3", "ws": "^8.14.2" @@ -1260,6 +1265,48 @@ "node": "^22.20 || ^24.12 || >=25" } }, + "node_modules/@noble/ciphers": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-2.4.0.tgz", + "integrity": "sha512-AnjFn0Jv92laAkvMrghlFZq4qQCIN/4DxFV/eooqtC2YTjB7kBeLMS2T9KJX4Dn+ZVXLOwK0lSgqDtx9gvxtiw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/curves": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz", + "integrity": "sha512-P4/62zrgfH33CneE3Dn4WhJVA22YUU0eR51wKIan4NVRvwsA0YnPTwWGpNbpuacSujmSFLvyzpyuR30+fbq2Ew==", + "dev": true, + "license": "MIT", + "dependencies": { + "@noble/hashes": "2.4.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz", + "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@react-native/assets-registry": { "version": "0.81.5", "resolved": "https://registry.npmjs.org/@react-native/assets-registry/-/assets-registry-0.81.5.tgz", @@ -3358,6 +3405,35 @@ "node": ">= 14" } }, + "node_modules/i18next": { + "version": "26.7.2", + "resolved": "https://registry.npmjs.org/i18next/-/i18next-26.7.2.tgz", + "integrity": "sha512-RsOY3BeaCDdkk52NeJSFAXELQ2rQXBO/tOub6L8ue2ICPfR/FRDWDOfEDg4xMPd1SqO5goVYQ6i72qWEUB/PPw==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://www.locize.com/i18next" + }, + { + "type": "individual", + "url": "https://www.i18next.com/how-to/faq#i18next-is-awesome.-how-can-i-support-the-project" + }, + { + "type": "individual", + "url": "https://www.locize.com" + } + ], + "license": "MIT", + "peerDependencies": { + "typescript": "^5 || ^6 || ^7" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, "node_modules/iconv-lite": { "version": "0.6.3", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", @@ -6372,9 +6448,9 @@ } }, "node_modules/ws": { - "version": "8.22.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", - "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "version": "8.22.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.2.tgz", + "integrity": "sha512-/rEZ2ejown2N5gxVTHUu9bVVC7ttu0/Tgzf5hbTOixR3Fs7mbbXgn2DbdbcKgJOmpQMtrIUWivtYuVMnp/W/yA==", "dev": true, "license": "MIT", "engines": { diff --git a/package.json b/package.json index 803932f..ba7939a 100644 --- a/package.json +++ b/package.json @@ -60,9 +60,9 @@ "semver": "7.8.5" }, "devDependencies": { - "@getpaseo/client": "0.12.0", - "@getpaseo/plugin": "0.12.0", - "@getpaseo/protocol": "0.12.0", + "@getpaseo/client": "0.15.3", + "@getpaseo/plugin": "0.15.3", + "@getpaseo/protocol": "0.15.3", "@types/node": "22.18.3", "@types/react": "~19.2.0", "@types/semver": "7.8.0", diff --git a/paseo-plugin.json b/paseo-plugin.json index adccc97..6999ace 100644 --- a/paseo-plugin.json +++ b/paseo-plugin.json @@ -1,5 +1,5 @@ { "id": "zcode-provider", - "requirements": { "paseo": ">=0.9.0" }, + "requirements": { "paseo": ">=0.15.0" }, "build": [["npm", "ci", "--include=dev"]] } diff --git a/scripts/check-stdio-runtime.mjs b/scripts/check-stdio-runtime.mjs index 5bbdc4e..8370af5 100644 --- a/scripts/check-stdio-runtime.mjs +++ b/scripts/check-stdio-runtime.mjs @@ -111,10 +111,16 @@ const modelServer = createServer(async (req, res) => { command: "rm -r guarded-fixture", description: "Remove the guarded fixture directory", } - : { - command: "printf ZCODE_STDIO_BASH_OK", - description: "Verify native shell execution", - }; + : scenario === "background" + ? { + command: "sleep 3", + description: "Outlive the foreground turn", + run_in_background: true, + } + : { + command: "printf ZCODE_STDIO_BASH_OK", + description: "Verify native shell execution", + }; const delta = useTool ? { tool_calls: [ @@ -355,6 +361,17 @@ try { e.type === "session.turn" && ["completed", "canceled", "failed"].includes(e.state), ); + // Paseo's idle runtime cleanup asks this before closing a session. + const canStopRuntime = async () => { + const requestId = `can-stop-${++seq}`; + await send({ type: "session.can_stop_runtime", requestId }); + return ( + await wait( + (e) => + e.type === "session.can_stop_runtime" && e.requestId === requestId, + ) + ).canStop; + }; await connect(); await connection.send({ type: "catalog", @@ -580,6 +597,21 @@ try { assert.ok(!JSON.stringify(quota).includes(QUOTA_MESSAGE)); await prompt("bash"); assert.equal((await terminal()).state, "completed"); + assert.equal(await canStopRuntime(), true); + // A background Bash outlives the foreground turn and keeps the runtime until + // ZCode delivers its result in a turn of its own. + await prompt("background"); + const foreground = await terminal(); + assert.equal(foreground.state, "completed"); + assert.equal(await canStopRuntime(), false); + const continuation = await wait( + (e) => + e.type === "session.turn" && + e.state === "completed" && + e.turnId !== foreground.turnId, + ); + assert.ok(continuation); + assert.equal(await canStopRuntime(), true); await prompt("command", "/plan"); assert.equal( events.find((e) => e.type === "session.prompt_result").result.type, @@ -627,6 +659,13 @@ try { owned.every((p) => exited(p.pid)), "Owned Agent must exit after its Server is killed", ); + // Paseo can resume an agent interrupted by a host restart: it reopens the + // saved session with its settings and sends a prompt. + await connection.close(); + await connect(); + await open(saved, { mode: "yolo", settings: { plan_mode: false } }); + await prompt("bash", "Resume working."); + assert.equal((await terminal()).state, "completed"); console.log( JSON.stringify( { @@ -650,10 +689,12 @@ try { "restart after stop", "provider quota failure", "restart after failure", + "idle runtime kept for background Bash", "slash command completion", "session listing v3", "EOF cleanup", "Agent cleanup after Server SIGKILL", + "resume after Server SIGKILL", patched ? "unsupported plugins and tool hidden (patched runtime)" : "unsupported tool hidden, plugins visible (unpatched runtime)", diff --git a/scripts/check-upstream.mjs b/scripts/check-upstream.mjs index 4fb1ac0..8b933a5 100644 --- a/scripts/check-upstream.mjs +++ b/scripts/check-upstream.mjs @@ -50,13 +50,21 @@ try { platform: "node", format: "esm", nodePaths: [join(root, "node_modules")], + // Bundled CommonJS dependencies (such as `which`) require Node builtins. + banner: { + js: 'import { createRequire as createBannerRequire } from "node:module"; const require = createBannerRequire(import.meta.url);', + }, }; + // Paseo runs these in a compiler worker; load the work itself, as the worker does. const sources = { - compiler: join(upstream, "packages/server/src/server/plugins/compiler.ts"), + compiler: join( + upstream, + "packages/server/src/server/plugins/compiler-build.ts", + ), manifest: join(upstream, "packages/server/src/server/plugins/manifest.ts"), preparation: join( upstream, - "packages/server/src/server/plugins/preparation.ts", + "packages/server/src/server/plugins/preparation-build.ts", ), icon: join(upstream, "packages/server/src/server/plugins/provider-icon.ts"), adapter: join( @@ -76,12 +84,13 @@ try { }); const load = (name) => import(pathToFileURL(join(directory, `${name}.mjs`)).href); - const { compilePlugin } = await load("compiler"); + const { compileDirectoryPlugin } = await load("compiler"); const { readPluginManifest } = await load("manifest"); const { runPluginBuild } = await load("preparation"); const { readPluginProviderIcon } = await load("icon"); const plugin = { - compilePlugin, + compileDirectoryPlugin, + daemonVersion: upstreamPackage.version, readPluginManifest, readPluginProviderIcon, runPluginBuild, @@ -128,7 +137,7 @@ try { registry.replace([registration()]); try { const client = registry.clients().zcode; - // Paseo 0.11 asks the registration's status() instead of connecting. + // Paseo asks the registration's status() instead of connecting. assert.equal(await client.isAvailable(), true); assert.deepEqual(await client.getDiagnostic(), { diagnostic: available.diagnostic, @@ -190,6 +199,24 @@ try { "hello", ); assert.equal(events.filter((e) => e.type === "turn_completed").length, 1); + // Paseo asks before releasing an idle runtime; ZCode background work keeps it. + assert.equal(typeof session.canStopRuntime, "function"); + assert.equal(await session.canStopRuntime(), true); + const backgroundWork = { + workId: "work-1", + kind: "bash", + title: "npm run dev", + status: "running", + startedAt: 1, + anchorRowId: null, + }; + await host.deltas([ + { op: "state.updated", patch: { backgroundWorks: [backgroundWork] } }, + ]); + assert.equal(await session.canStopRuntime(), false); + await host.deltas([ + { op: "state.updated", patch: { backgroundWorks: [] } }, + ]); await session.setFeature("plan_mode", true); assert.equal(host.state.config.planEnabled, true); const persistence = session.describePersistence(); @@ -302,6 +329,7 @@ try { textSteering: "passed", attachmentQueue: "passed", singleCompletion: "passed", + idleRuntimeVeto: "passed", turnFailure: "passed", providerReplacement: "passed", persistenceResume: "passed", @@ -322,7 +350,8 @@ try { } async function checkGitPreparation({ - compilePlugin, + compileDirectoryPlugin, + daemonVersion, readPluginManifest, readPluginProviderIcon, runPluginBuild, @@ -347,17 +376,15 @@ async function checkGitPreparation({ }); const manifest = await readPluginManifest(candidate); - const previousNodeEnv = process.env.NODE_ENV; - try { - if (nodeEnv === undefined) delete process.env.NODE_ENV; - else process.env.NODE_ENV = nodeEnv; - await runPluginBuild(candidate, manifest.build, { - info: logPreparation, - }); - } finally { - if (previousNodeEnv === undefined) delete process.env.NODE_ENV; - else process.env.NODE_ENV = previousNodeEnv; - } + const environment = { ...process.env }; + if (nodeEnv === undefined) delete environment.NODE_ENV; + else environment.NODE_ENV = nodeEnv; + await runPluginBuild( + candidate, + manifest.build, + { info: logPreparation }, + environment, + ); await access(join(candidate, "server/build-info.ts")); assert.ok( @@ -369,7 +396,8 @@ async function checkGitPreparation({ return { nodeEnv: nodeEnv ?? "unset", ...(await checkContributions({ - compilePlugin, + compileDirectoryPlugin, + daemonVersion, readPluginProviderIcon, candidate, requireModule: nodeRequire, @@ -381,7 +409,8 @@ async function checkGitPreparation({ } async function checkNpmInstallation({ - compilePlugin, + compileDirectoryPlugin, + daemonVersion, readPluginManifest, readPluginProviderIcon, runPluginBuild, @@ -435,12 +464,18 @@ async function checkNpmInstallation({ ); const candidate = join(installation, "node_modules", name); const manifest = await readPluginManifest(candidate); - await runPluginBuild(candidate, manifest.build, { info: logPreparation }); + await runPluginBuild( + candidate, + manifest.build, + { info: logPreparation }, + { ...process.env }, + ); return { package: filename, // Development dependencies are not installed: Paseo supplies the SDK and zod. ...(await checkContributions({ - compilePlugin, + compileDirectoryPlugin, + daemonVersion, readPluginProviderIcon, candidate, requireModule: createRequire(join(root, "package.json")), @@ -480,24 +515,33 @@ function logPreparation(fields, message) { // Compiles both entries with Paseo's compiler and registers them like Paseo. async function checkContributions({ - compilePlugin, + compileDirectoryPlugin, + daemonVersion, readPluginProviderIcon, candidate, requireModule, }) { - const { serverBundle, clientBundle } = await compilePlugin({ - server: join(candidate, "index.server.ts"), - client: join(candidate, "index.client.tsx"), + // The daemon checks requirements.paseo against its own version first. + await assert.rejects(compileDirectoryPlugin(candidate, "0.14.0"), { + message: /requires Paseo >=0\.15\.0/u, }); + const { serverBundle, clientBundle } = await compileDirectoryPlugin( + candidate, + daemonVersion, + ); assert.ok(clientBundle, "The client entry must compile"); + assert.ok( + !clientBundle.includes('"@getpaseo/plugin/client/react-native"'), + "Import Paseo UI from the current entry", + ); assert.ok( serverBundle.includes('require("@getpaseo/plugin/server/provider")'), ); const contribution = runInThisContext(serverBundle)((name) => name === "@getpaseo/plugin/server/provider" ? sdk : requireModule(name), ); - // Paseo 0.9+ returns a settings handle; the plugin follows the timeline - // settings with it. + // Paseo returns a settings handle; the plugin follows the timeline settings + // with it. const settings = []; const registerSettings = (definition) => { settings.push(definition.id); @@ -510,12 +554,15 @@ async function checkContributions({ subscribe: () => () => {}, }; }; - // Paseo 0.9–0.10 offer no registerUsageSource; the plugin must still load. let registered; + const sources = []; const dispose = contribution.default({ registerProvider(provider) { registered = provider; }, + registerUsageSource(source) { + sources.push(source); + }, registerSettings, handle() {}, }); @@ -523,18 +570,7 @@ async function checkContributions({ assert.equal(registered.id, "zcode"); assert.equal(typeof registered.status, "function"); await readPluginProviderIcon(candidate, registered.icon); - assert.equal(typeof dispose, "function"); - await dispose(); - // Paseo 0.11 checks these fields and the icon when registering a source. - const sources = []; - const disposeWithUsage = contribution.default({ - registerProvider() {}, - registerUsageSource(source) { - sources.push(source); - }, - registerSettings, - handle() {}, - }); + // Paseo checks these fields and the icon when registering a source. assert.equal(sources.length, 1); const [source] = sources; assert.equal(source.id, "zcode"); @@ -543,7 +579,8 @@ async function checkContributions({ assert.equal(typeof source.fetch, "function"); assert.equal(typeof source.input.parseAsync, "function"); await readPluginProviderIcon(candidate, source.icon); - await disposeWithUsage(); + assert.equal(typeof dispose, "function"); + await dispose(); const clientContribution = runInThisContext(clientBundle)((name) => { if (name === "react") @@ -556,7 +593,6 @@ async function checkContributions({ return { jsx: () => null, jsxs: () => null }; if (name === "react-native") return { - Linking: {}, Platform: { select: () => undefined }, Pressable: () => null, Text: () => null, @@ -568,10 +604,9 @@ async function checkContributions({ useRpc: () => async () => ({}), useSettings: () => ({ status: "loading" }), }; - if (name === "@getpaseo/plugin/client/react-native") - return { copyText: async () => {} }; if (name === "@getpaseo/plugin/client/ui") return { + copyText: async () => {}, SettingsAction: () => null, SettingsCard: () => null, SettingsInput: () => null, @@ -599,6 +634,7 @@ async function checkContributions({ return { compiledBytes: Buffer.byteLength(serverBundle), clientCompiledBytes: Buffer.byteLength(clientBundle), + paseoRequirement: "passed", registration: "passed", settingsRegistration: "passed", usageSourceRegistration: "passed", diff --git a/server/provider-status.ts b/server/provider-status.ts index 90aa2f1..973f9c8 100644 --- a/server/provider-status.ts +++ b/server/provider-status.ts @@ -62,9 +62,9 @@ async function check( } /** - * Availability for Paseo's provider snapshot and diagnostics (Paseo 0.11+; - * older daemons ignore it). It inspects the runtime without starting a Server, - * so sign-in problems still surface when a session opens. + * Availability for Paseo's provider snapshot and diagnostics. It inspects the + * runtime without starting a Server, so sign-in problems still surface when a + * session opens. */ export function createRuntimeStatus(options: RuntimeStatusOptions = {}) { const environment = options.environment ?? process.env; diff --git a/server/provider.ts b/server/provider.ts index fa11a1a..8a25ff8 100644 --- a/server/provider.ts +++ b/server/provider.ts @@ -62,6 +62,7 @@ export const CAPABILITIES = [ "prompt.command", "prompt.image", "prompt.steer", + "session.can_stop_runtime", "session.configure", "session.list", "session.persistence", @@ -478,6 +479,15 @@ export class ZCodeConnection implements ProviderConnection { case "session.interrupt": await entry.native.interrupt(); break; + // Paseo asks before releasing an idle runtime; the answer is the reply. + case "session.can_stop_runtime": + this.emit({ + type: "session.can_stop_runtime", + requestId: input.requestId, + sessionId: input.sessionId, + canStop: entry.native.canStopRuntime(), + }); + return; case "session.permission": await entry.native.respondToPermission( input.permissionId, diff --git a/server/session.ts b/server/session.ts index 817d8b9..fab8e26 100644 --- a/server/session.ts +++ b/server/session.ts @@ -466,6 +466,28 @@ export class ZCodeSession { hasActiveTurn(): boolean { return !!this.active; } + /** + * Whether closing loses no native work (Paseo's idle runtime cleanup). + * Background Bash, subagents and workflow runs outlive the foreground turn, + * and an active goal continues on its own. Only `running` work counts, as in + * ZCode's own `hasBackgroundWork`: a finished one stays `resultPending` even + * after the turn that delivered its result. + */ + canStopRuntime(): boolean { + this.assertOpen(); + const state = this.state; + return ( + !this.active && + !this.pendingAdmissions && + this.conversation.idle && + !state.pendingInteractions.length && + !state.pendingCommands.length && + !state.backgroundWorks.some((w) => w.status === "running") && + !state.subagents?.running.length && + state.goal?.status !== "active" && + state.goal?.status !== "verifying" + ); + } subscribe(listener: (event: NativeSessionEvent) => void): () => void { this.listeners.add(listener); listener({ type: "usage_updated", usage: usage(this.state) }); diff --git a/server/turn-failure.ts b/server/turn-failure.ts index b701074..df0b3d2 100644 --- a/server/turn-failure.ts +++ b/server/turn-failure.ts @@ -38,7 +38,7 @@ const messages: Record< NATIVE_TURN_FAILED: ["ZCode turn failed"], MODEL_RATE_LIMITED: [ "The model provider's usage or rate limit was reached", - "Wait for it to reset or switch models. For a ZCode Coding Plan, Paseo 0.11 and later show the reset times on the Usage screen.", + "Wait for it to reset or switch models. For a ZCode Coding Plan, Paseo shows the reset times on the Usage screen.", ], MODEL_AUTH_FAILED: [ "The model provider is not signed in or rejected the credentials", diff --git a/server/usage.ts b/server/usage.ts index 88f1369..3a1224e 100644 --- a/server/usage.ts +++ b/server/usage.ts @@ -1,6 +1,4 @@ import { createHash } from "node:crypto"; -// Types only, from the module every supported Paseo resolves; Paseo 0.9–0.10 -// reject `@getpaseo/plugin/server/usage` even as a type import. import type { UsageReport, UsageSourceRegistration, @@ -234,7 +232,7 @@ export interface UsageSourceOptions { } /** - * Coding Plan quota for Paseo's Usage screen (Paseo 0.11+), read through + * Coding Plan quota for Paseo's Usage screen, read through * ZCode's official usage-stats service on the account Server (ADR 18). */ export function createUsageSource( diff --git a/test/provider.test.ts b/test/provider.test.ts index 03b769a..744dd06 100644 --- a/test/provider.test.ts +++ b/test/provider.test.ts @@ -467,6 +467,110 @@ it("replays model change markers with the setting current at reopening", async ( await f.wait((e) => e.type === "timeline.item" && e.item.id === id), ).toMatchObject({ item: { message: "Using provider/model" } }); }); +it("keeps an idle runtime while ZCode background work or a goal remains", async () => { + const f = await fixture(); + expect(await f.open()).toMatchObject({ type: "session.ready" }); + expect( + f.events.find((e) => e.type === "session.opened")?.capabilities, + ).toContain("session.can_stop_runtime"); + let request = 0; + const canStop = async () => { + const requestId = `stop-${++request}`; + await f.send({ + type: "session.can_stop_runtime", + requestId, + sessionId: "public", + }); + const reply = await f.wait( + (e) => "requestId" in e && e.requestId === requestId, + ); + expect(reply).toMatchObject({ + type: "session.can_stop_runtime", + sessionId: "public", + }); + return reply.type === "session.can_stop_runtime" && reply.canStop; + }; + const work = (status: "running" | "resultPending") => ({ + workId: "work-1", + kind: "bash" as const, + title: "npm run dev", + status, + startedAt: 1, + anchorRowId: null, + }); + expect(await canStop()).toBe(true); + await f.prompt(); + expect(await canStop()).toBe(false); + await completeTurn(f.host); + await f.wait((e) => e.type === "session.turn" && e.state === "completed"); + expect(await canStop()).toBe(true); + await f.host.deltas([ + { op: "state.updated", patch: { backgroundWorks: [work("running")] } }, + ]); + expect(await canStop()).toBe(false); + // ZCode keeps a finished work as resultPending after delivering its result. + await f.host.deltas([ + { + op: "state.updated", + patch: { backgroundWorks: [work("resultPending")] }, + }, + ]); + expect(await canStop()).toBe(true); + const subagents = (running: number) => ({ + revision: running + 1, + childSessionIds: ["child-1"], + running: Array.from({ length: running }, () => ({ + childSessionId: "child-1", + subagentType: "explore", + title: "Explore", + status: "running" as const, + })), + endedTotal: 1 - running, + }); + await f.host.deltas([ + { op: "state.updated", patch: { subagents: subagents(1) } }, + ]); + expect(await canStop()).toBe(false); + await f.host.deltas([ + { op: "state.updated", patch: { subagents: subagents(0) } }, + ]); + expect(await canStop()).toBe(true); + const goal = (status: "active" | "verifying" | "paused") => ({ + targetId: "goal-1", + objective: "Ship it", + summaryTitle: null, + timeUsedSeconds: 0, + activeRunStartedAtMs: null, + status, + iteration: 1, + verifications: [], + iterations: [], + }); + for (const status of ["active", "verifying"] as const) { + await f.host.deltas([ + { op: "state.updated", patch: { goal: goal(status) } }, + ]); + expect(await canStop()).toBe(false); + } + await f.host.deltas([ + { op: "state.updated", patch: { goal: goal("paused") } }, + ]); + expect(await canStop()).toBe(true); + // The reply is the answer; Paseo rejects request.completed for this query. + expect( + f.events.filter( + (e) => e.type === "request.completed" && e.requestId.startsWith("stop-"), + ), + ).toEqual([]); + await f.send({ + type: "session.can_stop_runtime", + requestId: "unknown", + sessionId: "missing", + }); + expect( + await f.wait((e) => "requestId" in e && e.requestId === "unknown"), + ).toMatchObject({ type: "request.failed" }); +}); it("lists native sessions using the current handle version", async () => { const f = await fixture(); await f.send({ type: "sessions", requestId: "list", cwd: f.cwd });