pi-agy-provider 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/LICENSE +21 -0
  3. package/README.md +114 -2
  4. package/extensions/btw-extension-tools.ts +129 -0
  5. package/extensions/btw-ssh-workspace.ts +254 -0
  6. package/extensions/btw.ts +4445 -0
  7. package/index.ts +4404 -0
  8. package/lib/agy-acp-client.ts +1913 -0
  9. package/lib/agy-acp-driver.ts +1369 -0
  10. package/lib/agy-children.ts +403 -0
  11. package/lib/agy-client.ts +714 -0
  12. package/lib/agy-compaction.ts +373 -0
  13. package/lib/agy-diagnostics.ts +562 -0
  14. package/lib/agy-driver.ts +1592 -0
  15. package/lib/agy-paths.ts +9 -0
  16. package/lib/agy-profile.ts +58 -0
  17. package/lib/agy-thoughts.ts +1650 -0
  18. package/lib/artifacts.ts +127 -0
  19. package/lib/bridge-lifecycle.ts +140 -0
  20. package/lib/bridge.ts +481 -0
  21. package/lib/command-result.ts +82 -0
  22. package/lib/config.ts +28 -0
  23. package/lib/conversation-metadata.ts +1292 -0
  24. package/lib/conversation-state.ts +303 -0
  25. package/lib/diff.ts +649 -0
  26. package/lib/events.ts +159 -0
  27. package/lib/footer.ts +555 -0
  28. package/lib/mcp-cache.ts +15 -0
  29. package/lib/mcp-config.ts +51 -0
  30. package/lib/models.ts +521 -0
  31. package/lib/native-tools.ts +153 -0
  32. package/lib/pi-tools-agent.ts +106 -0
  33. package/lib/prompt.ts +759 -0
  34. package/lib/reducer.ts +495 -0
  35. package/lib/render.ts +370 -0
  36. package/lib/replay.ts +40 -0
  37. package/lib/skills.ts +189 -0
  38. package/lib/subagents.ts +1739 -0
  39. package/lib/swarm.ts +751 -0
  40. package/lib/tasks.ts +1197 -0
  41. package/lib/tool-mode-settings.ts +119 -0
  42. package/lib/tool-mode.ts +33 -0
  43. package/lib/tool-steps.ts +14 -0
  44. package/lib/tool-summary.ts +530 -0
  45. package/lib/turn.ts +215 -0
  46. package/lib/usage.ts +332 -0
  47. package/lib/wrapper-activation.ts +22 -0
  48. package/package.json +62 -3
  49. package/skills/btw/SKILL.md +200 -0
  50. package/src/artifacts-ui.ts +465 -0
  51. package/src/provider.ts +2451 -0
  52. package/src/runtime.ts +973 -0
  53. package/src/subagents-ui.ts +646 -0
  54. package/src/swarm-ui.ts +665 -0
  55. package/src/tasks-ui.ts +607 -0
  56. package/src/usage-ui.ts +97 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,37 @@
1
+ # Changelog
2
+
3
+ ## [1.1.0] - 2026-11-02
4
+
5
+ ### Added
6
+
7
+ - **Grill design-interview mode (`/grill-me`, `/grill`, `/agy-grill`)**: Stress-test plans and designs in dependency-ordered frontier rounds before writing code — automatically using `pi__ask_user_question` TUI cards when available on the Pi bridge or falling back to structured Markdown rounds (`❓ **Q1**` + `➡️ *Recommended*:`) with zero external dependencies.
8
+ - **Teamwork multi-agent mode (`/teamwork`, `/agy-teamwork`)**: Two-phase collaborative prompt crafting (`prompt_draft.md`) and `teamwork_preview` autonomous team execution, plus live multi-line subagent progress and diff previews.
9
+ - **Goal autonomous mode (`/goal`, `/agy-goal`)**: Long-horizon audit-and-continuation loop until `<!-- GOAL_COMPLETE -->` or `/goal off`.
10
+ - **Pi tools mode by default (`/agy-tools`)**: Expose active Pi built-in, extension, and MCP tools eagerly to `agy` through a session-scoped bridge while preserving `agy` specialty tools and image attachments.
11
+ - **2-row custom footer (`/agy-footer`)**: Live Antigravity 300k scheduling / 1.0M Claude context bar, cache-hit rate, and provider-aware branch footprint tracking across `/compact` and `/m` consults.
12
+ - **Cross-provider `/m` consults & model switching**: Consult any configured Pi `provider/model` for one turn, or omit the prompt to switch models/efforts directly.
13
+ - **Session lifecycle sync (`/rename`, `/resume`)**: Sync session renames (`Ctrl+R` and `/rename`) to `agy` conversation titles, and recursively clean up linked `agy` conversations and subagent trees on `/resume` `Ctrl+D` delete (scoped safely by `sessionId` on forked sessions).
14
+
15
+ ### Changed
16
+
17
+ - **Row 1 footer label clipping & model display priority**: Automatically clip overlong `gitBranch` and `sessionName` with `…` (while stripping inner ANSI resets to preserve styling) and prioritize keeping the `Model • thinkingLevel → routedModel` label intact on narrow terminals or deep directory paths.
18
+ - **Pi 1.5.0 compatibility**: Strip structured `<tools>...</tools>` sections (including Pi 1.5.0's tightened `"Additional tools may be available."` wording) when relaying Pi instructions to `agy`, align relayed `<docs>` paths (`docs/mcp.md`, `docs/codemode.md`), and use injected `context.keyHint("app.tools.expand", "to expand")` in tool result renderers.
19
+ - Default `agy` invocation to `--model <base> --effort <level>` with automatic fallback to legacy model-effort suffixes; bump recommended `agy` version to `1.4.9+`.
20
+
21
+ ### Fixed
22
+
23
+ - Handle `agy` 1.4.11 `finished_reason` (`print_timeout`, `interrupted`, `error`) without swallowing partial-output or hook errors.
24
+ - Prevent `unhandledRejection` crashes when a turn stalls while a `>64KB` stdin write awaits drain, and preserve user prompts when resumed conversations stall before `init`.
25
+ - Preserve user highlight position in `/model` when background model catalog refresh completes.
26
+
27
+ ## [1.0.0] - 2026-10-18
28
+
29
+ ### Features
30
+
31
+ - **Persistent Antigravity stream-json driver**: Reuse a single `agy` process across user turns with automatic recycling on model, workspace, agent, mode, or bridge changes.
32
+ - **One-shot model & effort consult (`/m`, `/consult`, `/agy-consult`)**: Consult any Antigravity model (`opus`, `sonnet`, `argon`, `flash`) with optional thinking effort suffixes (`1`=low, `2`=medium, `3`=high) for a single turn without changing the active session model, displaying a `Consulted <Model> (<effort>)` badge.
33
+ - **Boost multi-agent orchestration (`/boost`, `/agy-boost`)**: Delegate complex coding to `DeepCoder` and investigation to `DeepInvestigator` via `invoke_subagent`, automatically restoring Solo execution (`BOOST_DEACTIVATED_PROMPT`) when toggled off, and stripping hallucinated `<MESSAGE_RECEIVED>` turn boundaries.
34
+ - **Clear conversation (`/clear [prompt]`)**: Reset the active `agy` conversation and start a fresh Pi session in one step.
35
+ - **Live SQLite thinking stream & interactive dashboards**: Stream real-time reasoning traces from `agy`'s SQLite state (`lib/agy-thoughts.ts`) and provide interactive TUI dashboards for `/agy-tasks`, `/agy-artifacts`, `/agy-subagents`, and `/agy-usage`.
36
+ - **Skills & MCP bridge**: Expose Pi-private skills via `pi__activate_skill` and bridge Pi's built-in direct-exposure MCP tools into `agy`.
37
+ - **Isolated side-conversations**: Run Pi compaction, branch summaries, and `/btw` side-threads in disposable isolated `agy` runtimes without interrupting or polluting the main conversation.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 teededung
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,115 @@
1
- # Temporary Holding Version
1
+ # pi-agy-provider
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Run **Google Antigravity** (`agy`) models inside the [Pi coding agent](https://pi.dev), keeping Pi's TUI, tool cards, permissions, skills, MCP servers, and sessions while the official `agy` CLI (`acp` or `stream-json`) runs underneath.
4
+
5
+ ## Why This Exists
6
+
7
+ I use this extension daily on my own projects and refine it continuously around two goals: **stability** and **speed**. Huge kudos to the Antigravity team for `agy` native and its multi-agent capabilities. `pi-agy-provider` is simply an option if you enjoy working inside Pi's TUI and extension ecosystem; it is **not** a replacement for `agy`, because `agy` itself remains the foundation powering every model turn underneath.
8
+
9
+ ## Install
10
+
11
+ Requires the official `agy` CLI on `PATH` (sign in inside `agy`, or run `/agy-login` in Pi).
12
+
13
+ ```bash
14
+ pi install npm:pi-agy-provider
15
+ # or from GitHub:
16
+ pi install git:github.com/teededung/pi-agy-provider
17
+ ```
18
+
19
+ Update anytime with `pi update npm:pi-agy-provider`.
20
+
21
+ ## Multi-Agent & Workflow Modes
22
+
23
+ | Command | Mode | What it does |
24
+ | --- | --- | --- |
25
+ | `/swarm <task>` | **Swarm** | Parallel multi-agent board orchestration (`swarm`, `post_message`, `read_board`, `swarm_wait`) with automatic `@coordinator` wakeups. Toggle session mode via `/swarm on\|off`; inspect live via `/swarm board` or `Alt+s`. |
26
+ | `/boost [task]` | **Boost** | Multi-agent orchestrator delegating coding and root-cause work to `DeepCoder` and `DeepInvestigator` subagents (`on\|off\|status`). |
27
+ | `/teamwork [idea]` | **Teamwork** | Two-phase workflow: refines `prompt_draft.md` with you first, then launches autonomous specialist teammates (`on\|off\|status`). |
28
+ | `/goal <task>` | **Goal** | Autonomous multi-turn loop with self-auditing continuations until the objective completes (`/goal off\|status`). |
29
+ | `/grill-me [plan]` | **Grill** | Dependency-ordered frontier design interview using interactive `ask_user_question` cards (or Markdown fallback) before coding (`/grill`, `on\|off\|status`). |
30
+ | `/m <spec> <msg>` | **Consult** | One-shot consult with another model/effort without switching your session model, e.g. `/m opus3 review diff`, `/m argon1 quick check` (alias `/consult`). |
31
+ | `/btw [prompt]` | **Side chat** | Non-blocking side thread overlay in an isolated runtime (`Esc` / `Alt+m` to minimize, `Alt+/` to restore, `/btw:model`, `/btw:thinking`, `/btw:copy`, `/btw:new`). |
32
+
33
+ > While `/swarm`, `/boost`, `/teamwork`, or subagents are streaming, pressing `Enter` routes side questions straight into `/btw` instead of stalling in the steer queue (`Alt+Enter` still queues a main-session follow-up).
34
+
35
+ ## Commands
36
+
37
+ | Command | Description |
38
+ | --- | --- |
39
+ | `/agy` | Active conversation ID, model, driver, tool mode, and context status |
40
+ | `/agy-tools [on\|off\|status]` | Switch between **Pi tools mode** (default, routes work through Pi tools/MCP/permissions) and **native** `agy` tools |
41
+ | `/agy-config` | Configure driver (`driver acp\|stream-json\|one-shot`) and 2-row custom context footer (`footer on\|off`) |
42
+ | `/agy-login [method]` | Authenticate `agy` via ACP (`oauth-personal`, `oauth-business`, `gemini-api-key`, `agent-platform`, `status`) |
43
+ | `/agy-usage` | Live 5-hour & weekly quota bars per model group (zero model tokens spent) |
44
+ | `/agy-subagents [list]` | Interactive live worker & subagent inspector (plus real-time stack above editor) |
45
+ | `/swarm-board` (`Alt+s`) | Full-screen live `/swarm` roster, `#seq` feed, filters, and member transcript viewer |
46
+ | `/agy-tasks` | Inspect or stop (`stop <id>\|all`) background `agy` shell tasks |
47
+ | `/agy-artifacts` | Browse generated artifacts, plans, and media in the current `agy` brain directory |
48
+ | `/agy-models` / `/agy-agents` | Re-discover available models or list custom `agy` agents |
49
+ | `/agy-doctor` | Inspect binary resolution, driver health, MCP bridge, and state DB |
50
+ | `/clear [prompt]` / `/agy-reset` | Reset both the `agy` conversation and Pi session (`/agy-reset` drops only the `agy` side) |
51
+ | `/rename [name]` | Rename the Pi session and sync the title to `agy` conversation metadata |
52
+
53
+ ## Tool Modes & Drivers
54
+
55
+ - **Pi tools mode (`pi-tools:on`, default)**: `agy` runs with native tools disabled and calls your active Pi builtins, extensions, private skills, and MCP servers through a local loopback bridge so Pi's hooks and permissions apply.
56
+ - **Native mode (`/agy-tools off`)**: `agy` uses its own built-in file/shell/browser tools (read-only steps render as native Pi cards; edits render unified diffs).
57
+ - **Execution drivers (`/agy-config driver …`)**: Supports warm zero-respawn **`acp`** (native image blocks, live model discovery, cooperative cancel) and persistent **`stream-json`** RPC, with automatic compaction tracking and liveness-aware stall recovery.
58
+
59
+ > [!WARNING]
60
+ > In **native tool mode** (`/agy-tools off`), `agy` executes built-in file/shell/browser actions directly with `--dangerously-skip-permissions` before replaying cards to Pi. Keep `pi-tools:on` whenever you want tool calls gated by Pi's permission hooks.
61
+
62
+ <details>
63
+ <summary><strong>Configuration (`settings.json` & environment variables)</strong></summary>
64
+
65
+ Saved settings live in `~/.pi/agent/settings.json`:
66
+
67
+ ```json
68
+ {
69
+ "antigravity": {
70
+ "toolMode": "pi",
71
+ "driver": "acp",
72
+ "footer": "on"
73
+ },
74
+ "pi-agy": {
75
+ "turnTimeoutMs": 600000,
76
+ "stallTimeoutMs": 120000
77
+ }
78
+ }
79
+ ```
80
+
81
+ | Variable / Flag | Default | Effect |
82
+ | --- | --- | --- |
83
+ | `--agy-tools native\|pi` / `PI_ANTIGRAVITY_TOOLS` | `pi` | Override startup tool mode for one session |
84
+ | `--agy-footer on\|off` / `PI_ANTIGRAVITY_FOOTER` | `on` | Toggle the 2-row context & quota footer |
85
+ | `PI_ANTIGRAVITY_DRIVER` | `acp` | Override driver mode (`acp`, `stream-json`, or `0`/`one-shot`) |
86
+ | `PI_ANTIGRAVITY_PI_TOOL_BRIDGE=0` | enabled | Disable the local MCP/skills bridge |
87
+ | `PI_ANTIGRAVITY_AGENT=<name>` | none | Custom `agy` agent name (native tool mode only) |
88
+ | `PI_ANTIGRAVITY_MODE=plan\|accept-edits\|auto` | none | Explicit `agy` execution mode |
89
+ | `PI_ANTIGRAVITY_HIDDEN_MODELS` | `gemini-3.6, gemini-3.7, gpt-oss` | Comma/space-separated model IDs or prefixes to hide (`""` shows all) |
90
+ | `AGY_BINARY` | auto | Pin an exact `/path/to/agy` executable |
91
+ | `AGY_TURN_TIMEOUT_MS` | `600000` | Overall logical turn budget (ms) |
92
+ | `AGY_STALL_TIMEOUT_MS` | `120000` | Stream silence watchdog before auto-resume (scales automatically on >250k context) |
93
+ | `AGY_TOOL_STALL_TIMEOUT_MS` | `300000` | Silence budget while a foreground tool step is active |
94
+ | `AGY_PARKED_WATCH_MS` | `5000` | Poll interval to finish turns early when `agy` parks on a background task |
95
+ | `AGY_STALL_RETRY_BACKOFF_MS` | `3000` | Base backoff before stall recovery retries |
96
+
97
+ </details>
98
+
99
+ ## Account Safety
100
+
101
+ `pi-agy-provider` never contacts Google endpoints or extracts OAuth tokens. All authentication and API traffic stay inside the official first-party `agy` binary over its documented CLI/ACP interfaces, avoiding third-party `cloudcode-pa.googleapis.com` client spoofing that triggers account suspensions under the [Antigravity Terms of Service](https://antigravity.google/terms).
102
+
103
+ ## More Pi Extensions
104
+
105
+ | Package | Description | Install |
106
+ | --- | --- | --- |
107
+ | [pi-agy-provider](https://github.com/teededung/pi-agy-provider) | Antigravity (`agy`) provider & multi-agent orchestrator (`/swarm`, `/boost`, `/teamwork`, `/btw`) | `pi install npm:pi-agy-provider` |
108
+ | [pi-md-render](https://github.com/teededung/pi-md-render) | Streaming-first rich Markdown, code, Mermaid & LaTeX rendering for the Pi TUI | `pi install npm:pi-md-render` |
109
+ | [pi-session-sweep](https://github.com/teededung/pi-session-sweep) | Session management & cleanup with native `agy` conversation cleanup | `pi install npm:pi-session-sweep` |
110
+
111
+ ## Credits & License
112
+
113
+ - **Credits**: Started as an enhanced fork of [`@tian.zuo/pi-antigravity`](https://github.com/TianZuo555/pi-extensions#antigravity) by **Tian Zuo**.
114
+ - **Release notes**: [CHANGELOG.md](https://github.com/teededung/pi-agy-provider/blob/main/CHANGELOG.md) · [GitHub Releases](https://github.com/teededung/pi-agy-provider/releases)
115
+ - **License**: MIT (see [LICENSE](./LICENSE)).
@@ -0,0 +1,129 @@
1
+ import { readFile, realpath } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import {
5
+ DefaultPackageManager,
6
+ DefaultResourceLoader,
7
+ SettingsManager,
8
+ type ResourceLoader,
9
+ } from "@earendil-works/pi-coding-agent";
10
+
11
+ /** Resolve local paths relative to the config that owns them, not process.cwd(). */
12
+ function resolveSource(source: string, configPath: string): string {
13
+ if (source.startsWith("npm:") || source.startsWith("git:")) return source;
14
+ if (source.startsWith("~/")) return join(homedir(), source.slice(2));
15
+ return resolve(dirname(configPath), source);
16
+ }
17
+
18
+ type BtwConfig = { extensions?: string[]; workspace?: "local" | "ssh" };
19
+
20
+ async function readConfig(path: string, includeExtensions = true): Promise<BtwConfig | undefined> {
21
+ let text: string;
22
+ try {
23
+ text = await readFile(path, "utf8");
24
+ } catch (error) {
25
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
26
+ throw new Error(`Cannot read BTW config ${path}: ${error instanceof Error ? error.message : String(error)}`);
27
+ }
28
+
29
+ let config: unknown;
30
+ try {
31
+ config = JSON.parse(text);
32
+ } catch {
33
+ throw new Error(`Invalid BTW config ${path}: expected JSON.`);
34
+ }
35
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
36
+ throw new Error(`Invalid BTW config ${path}: expected an object.`);
37
+ }
38
+ const fields = Object.keys(config);
39
+ if (fields.some((field) => field !== "extensions" && field !== "workspace")) {
40
+ throw new Error(`Invalid BTW config ${path}: only "extensions" and "workspace" keys are supported.`);
41
+ }
42
+ if ("workspace" in config && config.workspace !== "local" && config.workspace !== "ssh") {
43
+ throw new Error(`Invalid BTW config ${path}: "workspace" must be "local" or "ssh".`);
44
+ }
45
+ if (includeExtensions && "extensions" in config && (!Array.isArray(config.extensions) || config.extensions.some((source) => typeof source !== "string" || !source.trim()))) {
46
+ throw new Error(`Invalid BTW config ${path}: "extensions" must be an array of nonempty source strings.`);
47
+ }
48
+ return {
49
+ ...(includeExtensions && "extensions" in config && Array.isArray(config.extensions) ? { extensions: [...new Set(config.extensions.map((source: string) => resolveSource(source.trim(), path)))] } : {}),
50
+ ...("workspace" in config ? { workspace: config.workspace as "local" | "ssh" } : {}),
51
+ };
52
+ }
53
+
54
+ /** Project lists replace global lists, including an explicit empty list. */
55
+ export async function readBtwExtensionSources(options: {
56
+ cwd: string;
57
+ agentDir: string;
58
+ projectTrusted: boolean;
59
+ }): Promise<string[]> {
60
+ const globalSources = await readConfig(join(options.agentDir, "btw.json"));
61
+ const projectSources = options.projectTrusted
62
+ ? await readConfig(join(options.cwd, ".pi", "btw.json"))
63
+ : undefined;
64
+ return projectSources?.extensions ?? globalSources?.extensions ?? [];
65
+ }
66
+
67
+ /** Workspace selection is independent of extension tool loading, including ask mode. */
68
+ export async function readBtwWorkspaceMode(options: {
69
+ cwd: string;
70
+ agentDir: string;
71
+ projectTrusted: boolean;
72
+ }): Promise<"local" | "ssh"> {
73
+ const globalConfig = await readConfig(join(options.agentDir, "btw.json"), false);
74
+ const projectConfig = options.projectTrusted ? await readConfig(join(options.cwd, ".pi", "btw.json"), false) : undefined;
75
+ return projectConfig?.workspace ?? globalConfig?.workspace ?? "local";
76
+ }
77
+
78
+ async function canonicalPath(path: string): Promise<string> {
79
+ try {
80
+ return await realpath(path);
81
+ } catch {
82
+ return resolve(path);
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Resolve the allowlist before running any extension factories. Remote packages
88
+ * have a BTW-owned install root so Pi's factory cache cannot reuse the parent's
89
+ * module globals. Local sources already loaded by the parent are rejected.
90
+ */
91
+ export async function loadBtwExtensionResources(options: {
92
+ cwd: string;
93
+ agentDir: string;
94
+ sources: string[];
95
+ parentExtensionPaths: string[];
96
+ }): Promise<ResourceLoader> {
97
+ const agentDir = join(options.agentDir, "btw");
98
+ const settingsManager = SettingsManager.inMemory();
99
+ const packages = new DefaultPackageManager({ cwd: options.cwd, agentDir, settingsManager });
100
+ const selectedPaths = new Set<string>();
101
+ for (const source of options.sources) {
102
+ const resolved = await packages.resolveExtensionSources([source], { temporary: true });
103
+ const paths = resolved.extensions.filter((resource) => resource.enabled).map((resource) => resource.path);
104
+ if (paths.length === 0) throw new Error(`BTW source ${source} did not resolve to any extensions.`);
105
+ for (const path of paths) selectedPaths.add(path);
106
+ }
107
+ const paths = [...selectedPaths];
108
+ const parentPaths = new Set(await Promise.all(options.parentExtensionPaths.map(canonicalPath)));
109
+ for (const path of paths) {
110
+ if (parentPaths.has(await canonicalPath(path))) {
111
+ throw new Error(
112
+ `BTW cannot reload the parent's extension ${path}: Pi can share its module state. Use an npm: or git: source for a separate BTW install.`,
113
+ );
114
+ }
115
+ }
116
+ const loader = new DefaultResourceLoader({
117
+ cwd: options.cwd,
118
+ agentDir,
119
+ settingsManager,
120
+ noExtensions: true,
121
+ noSkills: true,
122
+ noPromptTemplates: true,
123
+ noThemes: true,
124
+ noContextFiles: true,
125
+ additionalExtensionPaths: paths,
126
+ });
127
+ await loader.reload();
128
+ return loader;
129
+ }
@@ -0,0 +1,254 @@
1
+ import { pathToFileURL } from "node:url";
2
+ import {
3
+ createReadToolDefinition, createWriteToolDefinition, createEditToolDefinition,
4
+ createBashToolDefinition, createGrepToolDefinition, createFindToolDefinition,
5
+ createLsToolDefinition, defineTool, truncateHead, truncateLine,
6
+ type ExtensionAPI, type ExtensionCommandContext, type ToolDefinition,
7
+ type AgentToolResult, type BashOperations,
8
+ } from "@earendil-works/pi-coding-agent";
9
+
10
+ type SshState = {
11
+ target: string; port?: number; configFile?: string; remoteCwd: string;
12
+ remoteHome: string; remotePlatform: string; remoteShell: string;
13
+ };
14
+ type Workspace = { cwd: string; home: string; platform: string; shell: string };
15
+ type Entry = { path: string; isDirectory: boolean };
16
+ type Match = { path: string; toolPath: string; lineNumber: number; line: string };
17
+
18
+ // The published SSH extension exposes these backend APIs independently of its
19
+ // default extension factory. Importing them does not start or stop the parent.
20
+ type Adapter = {
21
+ toToolPath(path: string, workspace: Workspace): string;
22
+ mapCwd(path: string, localCwd: string, workspace: Workspace): string;
23
+ readFile(path: string, signal?: AbortSignal): Promise<Buffer>;
24
+ access(path: string, mode: "read" | "write", signal?: AbortSignal): Promise<void>;
25
+ detectImageMimeType(path: string, signal?: AbortSignal): Promise<string | null>;
26
+ mkdir(path: string, signal?: AbortSignal): Promise<void>;
27
+ writeFile(path: string, data: Buffer | string, signal?: AbortSignal): Promise<void>;
28
+ runShell(command: string, cwd: string, options: {
29
+ signal?: AbortSignal; timeoutSeconds?: number; env?: NodeJS.ProcessEnv;
30
+ captureOutput: boolean; onStdout: (data: Buffer) => void; onStderr: (data: Buffer) => void;
31
+ }): Promise<number | null>;
32
+ listDirectory(path: string, signal?: AbortSignal): Promise<Array<{ name: string; isDirectory: boolean }>>;
33
+ findEntries(path: string, pattern: string, limit: number, signal?: AbortSignal): Promise<Entry[]>;
34
+ grep(path: string, pattern: string, options: {
35
+ glob?: string; ignoreCase?: boolean; literal?: boolean; limit: number;
36
+ }, signal?: AbortSignal): Promise<Match[]>;
37
+ };
38
+ type Client = { dispose(): Promise<void>; onDisconnect?(handler: (error: Error) => void): () => void };
39
+ type SshApi = {
40
+ findSshEnvironmentState(entries: readonly unknown[]): { mode: "local" } | { mode: "remote"; session: SshState } | undefined;
41
+ createSshTransportClient(options: {
42
+ target: string; port?: number; configFile?: string; batchMode: boolean; connectTimeoutSeconds: number;
43
+ }, settings: { platform: NodeJS.Platform; preference: "auto" }): Client;
44
+ selectRemoteAdapter(client: Client, options: {
45
+ localPlatform: NodeJS.Platform; preference: string; expectedPlatform: string;
46
+ expectedShell: string; requestedCwd: string;
47
+ }): Promise<{ adapter: Adapter; workspace: Workspace }>;
48
+ };
49
+
50
+ export type BtwSshWorkspace = {
51
+ label: string;
52
+ identity: string;
53
+ tools: ToolDefinition[];
54
+ assertCurrent(): void;
55
+ dispose(): Promise<void>;
56
+ };
57
+
58
+ function limit(value: number | undefined, fallback: number): number {
59
+ if (value === undefined) return fallback;
60
+ if (!Number.isFinite(value) || value <= 0) throw new Error("Limit must be a positive finite number.");
61
+ return Math.max(1, Math.floor(value));
62
+ }
63
+
64
+ type SearchDetails = {
65
+ truncation?: ReturnType<typeof truncateHead>; entryLimitReached?: number;
66
+ resultLimitReached?: number; matchLimitReached?: number;
67
+ };
68
+
69
+ function textResult(text: string, details: SearchDetails = {}): AgentToolResult<SearchDetails> {
70
+ const truncation = truncateHead(text, { maxLines: Number.MAX_SAFE_INTEGER });
71
+ if (truncation.truncated) details.truncation = truncation;
72
+ const notices = Object.entries(details).filter(([key]) => key.endsWith("LimitReached"))
73
+ .map(([, value]) => `${value} results limit reached; increase limit or narrow the search.`);
74
+ if (truncation.truncated) notices.push("Output truncated; narrow the search.");
75
+ return {
76
+ content: [{ type: "text", text: truncation.content + (notices.length ? `\n\n[${notices.join(" ")}]` : "") }],
77
+ details,
78
+ };
79
+ }
80
+
81
+ async function displayFileErrors<T extends AgentToolResult<unknown>>(
82
+ displayPath: string, toolPath: string, run: () => Promise<T>,
83
+ ): Promise<T> {
84
+ try {
85
+ // Successful results may contain literal file contents or diff lines.
86
+ // Never rewrite them just to make encoded remote paths prettier.
87
+ return await run();
88
+ } catch (error) {
89
+ throw new Error((error instanceof Error ? error.message : String(error)).replaceAll(toolPath, displayPath));
90
+ }
91
+ }
92
+
93
+ export async function createBtwSshWorkspace(
94
+ pi: ExtensionAPI,
95
+ ctx: ExtensionCommandContext,
96
+ readonly: boolean,
97
+ ): Promise<BtwSshWorkspace> {
98
+ const source = pi.getAllTools().find((tool) => tool.name === "read")?.sourceInfo.path;
99
+ if (!source || source.startsWith("<")) {
100
+ throw new Error('workspace: "ssh" requires the parent pi-ssh-remote extension (0.6.2 or newer).');
101
+ }
102
+ const api = await import(/* @vite-ignore */ pathToFileURL(source).href) as Partial<SshApi>;
103
+ if (!api.findSshEnvironmentState || !api.createSshTransportClient || !api.selectRemoteAdapter) {
104
+ throw new Error("The parent read backend does not expose the supported pi-ssh-remote APIs.");
105
+ }
106
+ const getState = () => api.findSshEnvironmentState!(ctx.sessionManager.getBranch());
107
+ const environment = getState();
108
+ if (environment?.mode !== "remote") {
109
+ throw new Error('No active parent SSH workspace. Connect SSH first, or select workspace: "local".');
110
+ }
111
+ const state = environment.session;
112
+ const signature = JSON.stringify(state);
113
+ let unavailable: string | undefined;
114
+ let disposed = false;
115
+ const assertCurrent = () => {
116
+ const current = getState();
117
+ if (disposed || unavailable || current?.mode !== "remote" || JSON.stringify(current.session) !== signature) {
118
+ throw new Error(`${unavailable ?? "Parent SSH workspace changed."} Run /btw:clear before continuing.`);
119
+ }
120
+ };
121
+ const unsubscribe = pi.events.on("ssh-remote:environment", () => {
122
+ unavailable = "Parent SSH workspace changed.";
123
+ });
124
+ let client: Client | undefined;
125
+ let removeDisconnectListener: (() => void) | undefined;
126
+ const dispose = async () => {
127
+ if (disposed) return;
128
+ disposed = true;
129
+ unsubscribe();
130
+ removeDisconnectListener?.();
131
+ await client?.dispose();
132
+ };
133
+
134
+ try {
135
+ client = api.createSshTransportClient({
136
+ target: state.target, port: state.port, configFile: state.configFile,
137
+ batchMode: true, connectTimeoutSeconds: 10,
138
+ }, { platform: process.platform, preference: "auto" });
139
+ const { adapter, workspace } = await api.selectRemoteAdapter(client, {
140
+ localPlatform: process.platform, preference: state.remoteShell,
141
+ expectedPlatform: state.remotePlatform, expectedShell: state.remoteShell, requestedCwd: state.remoteCwd,
142
+ });
143
+ removeDisconnectListener = client.onDisconnect?.((error) => { unavailable = `BTW SSH disconnected: ${error.message}`; });
144
+ assertCurrent();
145
+ const cwd = adapter.toToolPath(workspace.cwd, workspace);
146
+ const filePath = (path: string) => adapter.toToolPath(path, workspace);
147
+ const searchPath = (path?: string) => adapter.toToolPath(adapter.mapCwd(path || ".", ctx.cwd, workspace), workspace);
148
+ const read = createReadToolDefinition(cwd);
149
+ const tools: ToolDefinition[] = [defineTool({
150
+ ...read,
151
+ async execute(id, args, signal, onUpdate, toolCtx) {
152
+ assertCurrent();
153
+ const path = filePath(args.path);
154
+ return displayFileErrors(args.path, path, () => createReadToolDefinition(cwd, { operations: {
155
+ readFile: (path) => adapter.readFile(path, signal),
156
+ access: (path) => adapter.access(path, "read", signal),
157
+ detectImageMimeType: (path) => adapter.detectImageMimeType(path, signal),
158
+ } }).execute(id, { ...args, path }, signal, onUpdate, toolCtx));
159
+ },
160
+ })];
161
+
162
+ if (readonly) {
163
+ tools.push(defineTool({
164
+ ...createLsToolDefinition(cwd),
165
+ async execute(_id, args, signal) {
166
+ assertCurrent();
167
+ const count = limit(args.limit, 500);
168
+ const entries = (await adapter.listDirectory(searchPath(args.path), signal))
169
+ .sort((a, b) => a.name.localeCompare(b.name));
170
+ return textResult(entries.slice(0, count).map((entry) => entry.name + (entry.isDirectory ? "/" : "")).join("\n") || "(empty directory)",
171
+ entries.length > count ? { entryLimitReached: count } : {});
172
+ },
173
+ }), defineTool({
174
+ ...createFindToolDefinition(cwd),
175
+ async execute(_id, args, signal) {
176
+ assertCurrent();
177
+ const count = limit(args.limit, 1000);
178
+ const entries = await adapter.findEntries(searchPath(args.path), args.pattern, count + 1, signal);
179
+ return textResult(entries.slice(0, count).map((entry) => entry.path + (entry.isDirectory ? "/" : "")).join("\n") || "No files found matching pattern",
180
+ entries.length > count ? { resultLimitReached: count } : {});
181
+ },
182
+ }), defineTool({
183
+ ...createGrepToolDefinition(cwd),
184
+ async execute(_id, args, signal) {
185
+ assertCurrent();
186
+ const count = limit(args.limit, 100);
187
+ const matches = await adapter.grep(searchPath(args.path), args.pattern, {
188
+ glob: args.glob, ignoreCase: args.ignoreCase, literal: args.literal, limit: count + 1,
189
+ }, signal);
190
+ const context = args.context === undefined ? 0 : Math.max(0, Math.floor(args.context));
191
+ if (!Number.isFinite(context)) throw new Error("Context must be a finite number.");
192
+ const lines: string[] = [];
193
+ const files = new Map<string, string[]>();
194
+ for (const match of matches.slice(0, count)) {
195
+ signal?.throwIfAborted();
196
+ if (!context) {
197
+ lines.push(`${match.path}:${match.lineNumber}: ${truncateLine(match.line).text}`);
198
+ continue;
199
+ }
200
+ let content = files.get(match.toolPath);
201
+ if (!content) {
202
+ content = (await adapter.readFile(match.toolPath, signal)).toString("utf8").replace(/\r\n/g, "\n").split("\n");
203
+ files.set(match.toolPath, content);
204
+ }
205
+ for (let line = Math.max(1, match.lineNumber - context); line <= Math.min(content.length, match.lineNumber + context); line++) {
206
+ const separator = line === match.lineNumber ? ":" : "-";
207
+ lines.push(`${match.path}${separator}${line}${separator} ${truncateLine(content[line - 1]).text}`);
208
+ }
209
+ }
210
+ return textResult(lines.join("\n") || "No matches found", matches.length > count ? { matchLimitReached: count } : {});
211
+ },
212
+ }));
213
+ } else {
214
+ tools.push(defineTool({
215
+ ...createWriteToolDefinition(cwd),
216
+ async execute(id, args, signal, onUpdate, toolCtx) {
217
+ assertCurrent();
218
+ const path = filePath(args.path);
219
+ return displayFileErrors(args.path, path, () => createWriteToolDefinition(cwd, { operations: {
220
+ mkdir: (path) => adapter.mkdir(path, signal),
221
+ writeFile: (path, data) => adapter.writeFile(path, data, signal),
222
+ } }).execute(id, { ...args, path }, signal, onUpdate, toolCtx));
223
+ },
224
+ }), defineTool({
225
+ ...createEditToolDefinition(cwd),
226
+ async execute(id, args, signal, onUpdate, toolCtx) {
227
+ assertCurrent();
228
+ const path = filePath(args.path);
229
+ return displayFileErrors(args.path, path, () => createEditToolDefinition(cwd, { operations: {
230
+ readFile: (path) => adapter.readFile(path, signal),
231
+ access: (path) => adapter.access(path, "write", signal),
232
+ writeFile: (path, data) => adapter.writeFile(path, data, signal),
233
+ } }).execute(id, { ...args, path }, signal, onUpdate, toolCtx));
234
+ },
235
+ }), defineTool({
236
+ ...createBashToolDefinition(cwd),
237
+ async execute(id, args, signal, onUpdate, toolCtx) {
238
+ assertCurrent();
239
+ const operations: BashOperations = {
240
+ exec: async (command, _cwd, options) => ({ exitCode: await adapter.runShell(command, workspace.cwd, {
241
+ signal: options.signal, timeoutSeconds: options.timeout,
242
+ captureOutput: false, onStdout: options.onData, onStderr: options.onData,
243
+ }) }),
244
+ };
245
+ return createBashToolDefinition(cwd, { operations, exposeSessionEnvironment: false }).execute(id, args, signal, onUpdate, toolCtx);
246
+ },
247
+ }));
248
+ }
249
+ return { label: `SSH ${state.target}${state.port ? `:${state.port}` : ""}:${workspace.cwd}`, identity: `ssh:${signature}`, tools, assertCurrent, dispose };
250
+ } catch (error) {
251
+ await dispose();
252
+ throw new Error(`Could not connect BTW SSH workspace: ${error instanceof Error ? error.message : String(error)}`);
253
+ }
254
+ }