@narumitw/pi-agentfs 0.0.0-stage → 0.2.1

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 narumiruna
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,133 @@
1
- # Temporary Holding Version
1
+ # 🗄️ pi-agentfs — AgentFS Workspaces for Pi
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
+ [![npm](https://img.shields.io/npm/v/@narumitw/pi-agentfs)](https://www.npmjs.com/package/@narumitw/pi-agentfs) [![Pi extension](https://img.shields.io/badge/Pi-extension-blue)](https://pi.dev) [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](./LICENSE)
4
+
5
+ Pi AgentFS replaces Pi's `read`, `write`, `edit`, and `bash` tools with tools that share one AgentFS database.
6
+ Use it when a trusted service selects a virtual file workspace for a session.
7
+
8
+ **This is not an operating-system sandbox.** Extensions run with all permissions of the Pi process.
9
+ The service must authorize database access and control other tools, resources, attachments, and conversation history.
10
+
11
+ ## ✨ Features
12
+
13
+ - Persistent virtual files shared by text tools and a restricted `just-bash` interpreter.
14
+ - Explicit database selection through CLI/RPC startup or an SDK extension factory.
15
+ - Session-owned connections, ordered operations, and failure paths without host-tool fallback.
16
+
17
+ ## 📦 Install
18
+
19
+ Requires Node.js `>=22.19.0` and a compatible Pi runtime.
20
+ Runtime dependency versions and the Node.js minimum are declared in [package.json](./package.json).
21
+
22
+ The npm name, publication permissions, and trusted publishing setup are not yet verified. Use the local checkout until a published release is available.
23
+ After publication, persistent installation and temporary execution use:
24
+
25
+ ```bash
26
+ pi install npm:@narumitw/pi-agentfs
27
+ pi -e npm:@narumitw/pi-agentfs
28
+ ```
29
+
30
+ From a local repository checkout:
31
+
32
+ ```bash
33
+ npm install
34
+ npm run build
35
+ pi --no-extensions -e ./packages/pi-agentfs
36
+ ```
37
+
38
+ The root build prepares Kit before its consumers. Run it before local extension loading or the SDK example.
39
+ Pi loads the source entrypoint. SDK imports use built JavaScript.
40
+
41
+ Only install trusted code. The restricted tool interface does not remove the extension's process permissions.
42
+
43
+ ## 🚀 Quick start
44
+
45
+ Have the operator create and secure `/srv/agentfs` first, then authorize `/srv/agentfs/alice.db` for this session.
46
+ AgentFS can initialize a new database at that approved path; this package does not create host parent directories.
47
+
48
+ For a local checkout, start Pi with only this extension and the four workspace tools:
49
+
50
+ ```bash
51
+ pi --no-extensions -e ./packages/pi-agentfs \
52
+ --no-skills --no-prompt-templates --no-themes --no-context-files --no-approve \
53
+ --no-session --tools read,write,edit,bash \
54
+ --agentfs-path /srv/agentfs/alice.db
55
+ ```
56
+
57
+ Ask Pi to write `hello` to `/notes/hello.txt`, then read it with `read` or `bash` using `cat /notes/hello.txt`.
58
+ `/notes/hello.txt` is inside the database, not on the host.
59
+
60
+ This CLI example limits common discovery paths, not all host access.
61
+ In particular, Pi can still load personal system-prompt files and credentials; `--no-context-files` does not disable `SYSTEM.md` or `APPEND_SYSTEM.md`.
62
+ Use controlled service configuration as described in [Integration](./docs/integration.md), not this command as a multi-user security boundary.
63
+
64
+ ## 🛠️ Tools
65
+
66
+ | Tool | Behavior |
67
+ | --- | --- |
68
+ | `read` | Reads text with one-based `offset` and optional line `limit`; output uses Pi's truncation helpers. No image support. |
69
+ | `write` | Creates or overwrites a virtual file and creates required virtual parent directories. |
70
+ | `edit` | Uses Pi's exact text replacement and diff behavior with AgentFS operations. |
71
+ | `bash` | Runs the allowed virtual shell commands through `just-bash`, not a host shell. |
72
+
73
+ File-tool relative paths start at `/`. Absolute paths also refer to the virtual root.
74
+ `~` and `~/` refer to that root, not the host home directory; named home directories and links are unsupported.
75
+ There are no additional slash commands or standalone search tools.
76
+ Tool views omit host-file links and speculative edit previews; completed edit diffs remain available.
77
+
78
+ ## ⚙️ Settings
79
+
80
+ The extension has no settings file or extension-specific environment variables.
81
+ Enable it with `--agentfs-path <absolute-database-path>` at CLI/RPC startup, or pass `{ path }` to `createAgentfsExtension()` in the SDK.
82
+ The path is fixed for that extension runtime; tools cannot change it.
83
+
84
+ Without the CLI flag, the extension stays disabled and leaves ordinary Pi tools unchanged.
85
+ An explicitly invalid path is not disabled mode: requested workspace tools reject operations during loading, after initialization failure, or after closure. They never switch to host tools.
86
+ SDK callers must check loader errors, `onError`, and `await extension.ready(session.sessionManager)` after `bindExtensions()` before admitting requests.
87
+ See [SDK startup and shutdown](./docs/integration.md#sdk-startup-and-shutdown) and the runnable [service example](./examples/service.ts).
88
+
89
+ ## 🔒 Security and privacy
90
+
91
+ Only the trusted operator or service supplies the host database path. A model-supplied path is a virtual file path, never a database selector.
92
+ Database authorization, host directory permissions, backups, encryption, retention, and user-to-workspace mapping belong to the service.
93
+ AgentFS files persist in the selected database; Pi conversation history is separate and is not automatically stored there.
94
+
95
+ When workspace mode is requested, `!` and `!!` are explicitly blocked. Use the model-facing `bash` tool instead.
96
+ Do not expose SDK `session.executeBash()` to untrusted requests: that direct API bypasses the `user_bash` hook and can execute on the host.
97
+ Other extensions, MCP tools, native file/search tools, host attachments, and session import/export routes can also bypass the four-tool interface.
98
+
99
+ The shell does not receive `process.env`, service secrets, network commands, or arbitrary program executors.
100
+ This restriction applies to the workspace tools, not to the surrounding Pi process.
101
+ Review dependency advisories and deployment controls before production use; a command allowlist is not a security audit of every installed dependency.
102
+ See [Dependency security](./docs/dependency-security.md) for repository dependency overrides and their scope.
103
+
104
+ ## 🚧 Limitations
105
+
106
+ `bash` is a limited interpreter, not GNU Bash or a Linux environment. Each call starts at `/` with a fresh shell environment.
107
+ `cd`, `export`, shell functions, and variables do not persist between calls; file changes do.
108
+ Unsupported commands fail without a native-shell fallback. See the exact [shell contract and bounds](./docs/integration.md#shell-contract-and-bounds).
109
+
110
+ All four tools serialize complete operations within one session workspace. This does not coordinate multiple processes or separate owners of the same database.
111
+ Use one owner per database; simultaneous same-database sessions and cross-process access are not supported.
112
+ Cancellation and failure do not roll back file changes that already completed.
113
+
114
+ Real service deployment and end-to-end multi-user isolation remain unverified.
115
+ The [service handoff](./docs/integration.md#deployment-and-publication-handoff) lists the remaining responsibilities.
116
+
117
+ ## 🗂️ Package layout
118
+
119
+ - `src/index.ts`: thin Pi source entrypoint.
120
+ - `src/factory.ts`: SDK factory, readiness barrier, and session lifecycle.
121
+ - `src/workspace.ts`, `src/tools.ts`, `src/paths.ts`: shared database ownership, tool implementations, and virtual paths.
122
+ - `dist/`: built JavaScript and declarations for SDK imports; generated by the package build.
123
+ - `docs/integration.md`, `examples/service.ts`: service contract and no-model startup example.
124
+
125
+ The package publishes source for Pi and built output for the SDK, plus its documentation, example, and license.
126
+
127
+ ## 🔎 Keywords
128
+
129
+ Pi extension, AgentFS, virtual filesystem, workspace, just-bash, SDK integration.
130
+
131
+ ## 📄 License
132
+
133
+ [MIT](./LICENSE).
@@ -0,0 +1,2 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ export default function agentfsExtension(pi: ExtensionAPI): void;
@@ -0,0 +1,8 @@
1
+ import { installAgentfsLifecycle } from "./factory.js";
2
+ export default function agentfsExtension(pi) {
3
+ pi.registerFlag("agentfs-path", {
4
+ type: "string",
5
+ description: "Enable AgentFS with an absolute database path (blocks ! and !! host commands)",
6
+ });
7
+ installAgentfsLifecycle(pi, new WeakMap(), () => pi.getFlag("agentfs-path"), false);
8
+ }
@@ -0,0 +1,18 @@
1
+ import type { ExtensionAPI, ExtensionFactory } from "@earendil-works/pi-coding-agent";
2
+ import { Workspace } from "./workspace.js";
3
+ type WorkspaceState = {
4
+ status: "loading" | "ready" | "failed" | "closed";
5
+ workspace?: Workspace;
6
+ initialization: Promise<void>;
7
+ };
8
+ export type AgentfsExtension = ExtensionFactory & {
9
+ /** Call after session.bindExtensions(); Pi reports lifecycle errors without rejecting that call. */
10
+ ready(sessionManager: object): Promise<void>;
11
+ };
12
+ /** Package-owned lifecycle shared by the SDK factory and the opt-in CLI entrypoint. */
13
+ export declare function installAgentfsLifecycle(pi: ExtensionAPI, states: WeakMap<object, WorkspaceState>, resolvePath: () => unknown, registerDuringLoad: boolean): void;
14
+ /** Register exactly the AgentFS read, write, edit, and bash replacements. */
15
+ export declare function createAgentfsExtension(options: {
16
+ path: string;
17
+ }): AgentfsExtension;
18
+ export {};
@@ -0,0 +1,100 @@
1
+ import { validateDatabasePath } from "./paths.js";
2
+ import { createWorkspaceTools } from "./tools.js";
3
+ import { Workspace } from "./workspace.js";
4
+ /** Package-owned lifecycle shared by the SDK factory and the opt-in CLI entrypoint. */
5
+ export function installAgentfsLifecycle(pi, states, resolvePath, registerDuringLoad) {
6
+ // CLI flags are fixed for this runtime, including an absent flag.
7
+ let pathResolved = false;
8
+ let path;
9
+ let requested = registerDuringLoad;
10
+ const resolveWorkspace = (ctx) => {
11
+ const state = states.get(ctx.sessionManager);
12
+ if (state?.status !== "ready" || !state.workspace) {
13
+ throw new Error(`AgentFS workspace is ${state?.status ?? "not started"}`);
14
+ }
15
+ return state.workspace;
16
+ };
17
+ let toolsRegistered = false;
18
+ const registerTools = () => {
19
+ if (toolsRegistered)
20
+ return;
21
+ for (const tool of createWorkspaceTools(resolveWorkspace))
22
+ pi.registerTool(tool);
23
+ toolsRegistered = true;
24
+ };
25
+ if (registerDuringLoad)
26
+ registerTools();
27
+ pi.on("user_bash", () => {
28
+ if (requested) {
29
+ // Returning undefined here would let ! and !! execute on the host.
30
+ throw new Error("AgentFS blocks ! and !! host commands; use the bash tool instead");
31
+ }
32
+ return undefined;
33
+ });
34
+ pi.on("session_start", async (_event, ctx) => {
35
+ if (!pathResolved) {
36
+ path = resolvePath();
37
+ pathResolved = true;
38
+ }
39
+ if (path === undefined && !registerDuringLoad)
40
+ return;
41
+ requested = true;
42
+ const key = ctx.sessionManager;
43
+ const previous = states.get(key);
44
+ if (previous)
45
+ previous.status = "closed";
46
+ const state = { status: "loading", initialization: Promise.resolve() };
47
+ const isCurrent = () => states.get(key) === state && state.status !== "closed";
48
+ states.set(key, state);
49
+ // Replace host tools before validation or opening. Pi swallows session_start errors.
50
+ if (!registerDuringLoad)
51
+ registerTools();
52
+ state.initialization = (async () => {
53
+ try {
54
+ await previous?.workspace?.close();
55
+ if (!isCurrent())
56
+ throw new Error("AgentFS workspace was closed during initialization");
57
+ validateDatabasePath(path);
58
+ state.workspace = new Workspace(path);
59
+ await state.workspace.open();
60
+ if (!isCurrent())
61
+ throw new Error("AgentFS workspace was closed during initialization");
62
+ state.status = "ready";
63
+ }
64
+ catch (error) {
65
+ if (state.status !== "closed")
66
+ state.status = "failed";
67
+ await state.workspace?.close();
68
+ throw error;
69
+ }
70
+ })();
71
+ await state.initialization;
72
+ });
73
+ pi.on("session_shutdown", async (_event, ctx) => {
74
+ const state = states.get(ctx.sessionManager);
75
+ if (!state)
76
+ return;
77
+ state.status = "closed";
78
+ await state.workspace?.close();
79
+ // Also drain a pending open, including its cleanup, before shutdown returns.
80
+ await state.initialization.catch(() => undefined);
81
+ });
82
+ }
83
+ /** Register exactly the AgentFS read, write, edit, and bash replacements. */
84
+ export function createAgentfsExtension(options) {
85
+ validateDatabasePath(options.path);
86
+ const path = options.path;
87
+ const states = new WeakMap();
88
+ const factory = (pi) => installAgentfsLifecycle(pi, states, () => path, true);
89
+ return Object.assign(factory, {
90
+ async ready(sessionManager) {
91
+ const state = states.get(sessionManager);
92
+ if (!state)
93
+ throw new Error("AgentFS workspace has not started; call session.bindExtensions() first");
94
+ await state.initialization;
95
+ if (states.get(sessionManager) !== state || state.status !== "ready") {
96
+ throw new Error(`AgentFS workspace is ${state.status}`);
97
+ }
98
+ },
99
+ });
100
+ }
@@ -0,0 +1 @@
1
+ export { default } from "./agentfs-extension.js";
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { default } from "./agentfs-extension.js";
@@ -0,0 +1,4 @@
1
+ export declare const MAX_OUTPUT_BYTES: number;
2
+ export declare const MAX_OUTPUT_LINES = 2000;
3
+ /** Reserve space for the notice so the complete returned text stays within Pi's limits. */
4
+ export declare function boundedText(text: string): string;
package/dist/output.js ADDED
@@ -0,0 +1,10 @@
1
+ import { truncateHead } from "@earendil-works/pi-coding-agent";
2
+ export const MAX_OUTPUT_BYTES = 50 * 1024;
3
+ export const MAX_OUTPUT_LINES = 2000;
4
+ /** Reserve space for the notice so the complete returned text stays within Pi's limits. */
5
+ export function boundedText(text) {
6
+ if (!truncateHead(text).truncated)
7
+ return text;
8
+ const result = truncateHead(text, { maxBytes: MAX_OUTPUT_BYTES - 128, maxLines: MAX_OUTPUT_LINES - 2 });
9
+ return result.truncated ? `${result.content}\n[Output truncated; excess output was discarded.]` : text;
10
+ }
@@ -0,0 +1,3 @@
1
+ export declare function validateDatabasePath(path: unknown): asserts path is string;
2
+ /** Virtual paths never use the host cwd or home directory. */
3
+ export declare function virtualPath(path: string): string;
package/dist/paths.js ADDED
@@ -0,0 +1,18 @@
1
+ import { isAbsolute, posix } from "node:path";
2
+ export function validateDatabasePath(path) {
3
+ if (typeof path !== "string" || !path.trim() || !isAbsolute(path) || path.includes("\0")) {
4
+ throw new Error("AgentFS requires a nonempty absolute database path.");
5
+ }
6
+ }
7
+ /** Virtual paths never use the host cwd or home directory. */
8
+ export function virtualPath(path) {
9
+ if (!path || path.includes("\0"))
10
+ throw new Error("Invalid virtual path.");
11
+ if (path === "~")
12
+ return "/";
13
+ if (path.startsWith("~/"))
14
+ path = path.slice(2);
15
+ else if (path.startsWith("~"))
16
+ throw new Error("Named home directories are not supported.");
17
+ return posix.resolve("/", path);
18
+ }
package/dist/read.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import type { ReadOperations } from "@earendil-works/pi-coding-agent";
2
+ import { createReadToolDefinition } from "@earendil-works/pi-coding-agent";
3
+ /** Pi's resolver probes the host before ReadOperations. Use only its schema and
4
+ * truncation helpers, never its execute method. Images and host filename guesses are omitted. */
5
+ export declare function createVirtualRead(operations: ReadOperations): ReturnType<typeof createReadToolDefinition>;
package/dist/read.js ADDED
@@ -0,0 +1,53 @@
1
+ import { createReadToolDefinition, formatSize, truncateHead } from "@earendil-works/pi-coding-agent";
2
+ import { MAX_OUTPUT_BYTES, MAX_OUTPUT_LINES } from "./output.js";
3
+ import { virtualRenderers } from "./renderers.js";
4
+ /** Pi's resolver probes the host before ReadOperations. Use only its schema and
5
+ * truncation helpers, never its execute method. Images and host filename guesses are omitted. */
6
+ export function createVirtualRead(operations) {
7
+ const core = createReadToolDefinition("/", { operations });
8
+ return {
9
+ ...core,
10
+ ...virtualRenderers("read"),
11
+ description: "Read a text file in AgentFS. Paths are relative to virtual /. Use offset (1-indexed) and limit for paged reads. Output is limited to 50 KB or 2,000 lines. Images are not supported.",
12
+ async execute(_id, { path, offset, limit }, signal) {
13
+ const check = () => {
14
+ if (signal?.aborted)
15
+ throw new Error("Operation aborted");
16
+ };
17
+ for (const [name, value] of [
18
+ ["offset", offset],
19
+ ["limit", limit],
20
+ ]) {
21
+ if (value !== undefined && (!Number.isSafeInteger(value) || value < 1)) {
22
+ throw new Error(`${name} must be a positive integer.`);
23
+ }
24
+ }
25
+ check();
26
+ await operations.access(path);
27
+ check();
28
+ const buffer = await operations.readFile(path);
29
+ check();
30
+ const lines = buffer.toString("utf-8").split("\n");
31
+ const start = (offset ?? 1) - 1;
32
+ if (start >= lines.length)
33
+ throw new Error(`Offset ${offset} is beyond end of file (${lines.length} lines total)`);
34
+ const selected = lines.slice(start, limit === undefined ? undefined : start + limit).join("\n");
35
+ const truncation = truncateHead(selected, { maxBytes: MAX_OUTPUT_BYTES - 512, maxLines: MAX_OUTPUT_LINES - 3 });
36
+ let text = truncation.content;
37
+ let details;
38
+ if (truncation.firstLineExceedsLimit) {
39
+ text = `[Line ${start + 1} is ${formatSize(Buffer.byteLength(lines[start], "utf-8"))}, exceeds the text output limit. Use bash with head -c to read a smaller part.]`;
40
+ details = { truncation };
41
+ }
42
+ else if (truncation.truncated) {
43
+ const end = start + truncation.outputLines;
44
+ text += `\n\n[Showing lines ${start + 1}-${end} of ${lines.length}. Use offset=${end + 1} to continue.]`;
45
+ details = { truncation };
46
+ }
47
+ else if (limit !== undefined && start + limit < lines.length) {
48
+ text += `\n\n[${lines.length - start - limit} more lines in file. Use offset=${start + limit + 1} to continue.]`;
49
+ }
50
+ return { content: [{ type: "text", text }], details, structuredContent: text };
51
+ },
52
+ };
53
+ }
@@ -0,0 +1,4 @@
1
+ import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
2
+ /** Core path renderers link to host files; the edit preview also reads host files. Neither applies
3
+ * to virtual files. Render only supplied text and completed diffs, without speculative I/O. */
4
+ export declare function virtualRenderers(name: string): Pick<ToolDefinition, "renderCall" | "renderResult" | "renderShell">;
@@ -0,0 +1,65 @@
1
+ import { stripVTControlCharacters } from "node:util";
2
+ import { hardWrapTerminalDocument } from "@narumitw/pi-tui-kit";
3
+ function displayText(text) {
4
+ // Preserve raw tool payloads; strip terminal controls only at the display boundary.
5
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: intentionally remove controls, except line feeds and tabs.
6
+ const controls = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g;
7
+ return stripVTControlCharacters(text).replace(controls, "").replaceAll("\t", " ");
8
+ }
9
+ function boundedComponent(text, style, padding = 0) {
10
+ let cachedWidth;
11
+ let cachedLines;
12
+ return {
13
+ render(width) {
14
+ if (!Number.isFinite(width) || width < 1)
15
+ return [];
16
+ const safeWidth = Math.floor(width);
17
+ if (cachedWidth === safeWidth && cachedLines)
18
+ return cachedLines;
19
+ const marginWidth = Math.min(padding, Math.max(0, Math.floor((safeWidth - 1) / 2)));
20
+ const margin = " ".repeat(marginWidth);
21
+ let offset = 0;
22
+ // Word wrapping trims spaces and hides whitespace-only documents. Wrap sanitized text
23
+ // by display cells first, then apply trusted theme styles to each complete output row.
24
+ cachedLines = hardWrapTerminalDocument(text, safeWidth - marginWidth * 2).map((line) => {
25
+ const rendered = margin + style(line, offset) + margin;
26
+ offset += line.length;
27
+ return rendered;
28
+ });
29
+ cachedWidth = safeWidth;
30
+ return cachedLines;
31
+ },
32
+ invalidate() {
33
+ cachedWidth = undefined;
34
+ cachedLines = undefined;
35
+ },
36
+ };
37
+ }
38
+ /** Core path renderers link to host files; the edit preview also reads host files. Neither applies
39
+ * to virtual files. Render only supplied text and completed diffs, without speculative I/O. */
40
+ export function virtualRenderers(name) {
41
+ return {
42
+ renderShell: undefined,
43
+ renderCall(input, theme) {
44
+ const args = input && typeof input === "object" ? input : {};
45
+ const value = name === "bash" ? args.command : args.path;
46
+ const label = typeof value === "string" ? displayText(value).replaceAll("\n", "\\n") : "...";
47
+ return boundedComponent(`${name} ${label}`, (line, offset) => {
48
+ const titleLength = Math.max(0, name.length - offset);
49
+ return (theme.fg("toolTitle", theme.bold(line.slice(0, titleLength))) + theme.fg("accent", line.slice(titleLength)));
50
+ });
51
+ },
52
+ renderResult(result, options, theme, context) {
53
+ const details = result.details && typeof result.details === "object" ? result.details : {};
54
+ const raw = name === "edit" && !context.isError && typeof details.diff === "string"
55
+ ? details.diff
56
+ : result.content
57
+ .filter((item) => item.type === "text")
58
+ .map((item) => item.text)
59
+ .join("\n");
60
+ const text = displayText(raw);
61
+ const visible = options.expanded ? text : text.split("\n").slice(0, 10).join("\n");
62
+ return boundedComponent(visible, (line) => theme.fg(context.isError ? "error" : "toolOutput", line), context.outputPad);
63
+ },
64
+ };
65
+ }
@@ -0,0 +1,12 @@
1
+ import { type ExtensionContext, type ToolDefinition } from "@earendil-works/pi-coding-agent";
2
+ import type { Workspace } from "./workspace.js";
3
+ export declare const SHELL_COMMANDS: readonly ["ls", "cat", "grep", "find", "mkdir", "rm", "cp", "mv", "head", "tail", "wc", "sort", "uniq", "cut", "tr", "tee", "pwd", "echo", "true", "false", "sleep", "seq", "sed"];
4
+ export declare const SHELL_TIMEOUT_SECONDS = 30;
5
+ export declare const SHELL_LIMITS: {
6
+ readonly maxSourceBytes: number;
7
+ readonly maxCommandCount: 10000;
8
+ readonly maxLoopIterations: 1000;
9
+ readonly maxOutputSize: number;
10
+ readonly maxExecutionTimeMs: number;
11
+ };
12
+ export declare function createWorkspaceTools(resolveWorkspace: (ctx: ExtensionContext) => Workspace): ToolDefinition[];
package/dist/tools.js ADDED
@@ -0,0 +1,156 @@
1
+ import { posix } from "node:path";
2
+ import { createEditToolDefinition, createWriteToolDefinition, } from "@earendil-works/pi-coding-agent";
3
+ import { Bash } from "just-bash";
4
+ import { Type } from "typebox";
5
+ import { boundedText } from "./output.js";
6
+ import { virtualPath } from "./paths.js";
7
+ import { createVirtualRead } from "./read.js";
8
+ import { virtualRenderers } from "./renderers.js";
9
+ export const SHELL_COMMANDS = [
10
+ "ls",
11
+ "cat",
12
+ "grep",
13
+ "find",
14
+ "mkdir",
15
+ "rm",
16
+ "cp",
17
+ "mv",
18
+ "head",
19
+ "tail",
20
+ "wc",
21
+ "sort",
22
+ "uniq",
23
+ "cut",
24
+ "tr",
25
+ "tee",
26
+ "pwd",
27
+ "echo",
28
+ "true",
29
+ "false",
30
+ "sleep",
31
+ "seq",
32
+ "sed",
33
+ ];
34
+ export const SHELL_TIMEOUT_SECONDS = 30;
35
+ export const SHELL_LIMITS = {
36
+ maxSourceBytes: 64 * 1024,
37
+ maxCommandCount: 10_000,
38
+ maxLoopIterations: 1000,
39
+ maxOutputSize: 1024 * 1024,
40
+ maxExecutionTimeMs: SHELL_TIMEOUT_SECONDS * 1000,
41
+ };
42
+ function fileOperations(fs, path) {
43
+ // Pin operations to the virtual path. Pi may normalize Unicode spaces, file URLs, or Windows
44
+ // paths internally; those host-oriented transformations must not select a different file.
45
+ return {
46
+ access: async () => {
47
+ const stat = await fs.stat(path);
48
+ if (!stat.isFile || stat.isSymbolicLink)
49
+ throw new Error("Path is not a regular virtual file.");
50
+ },
51
+ readFile: async () => Buffer.from(await fs.readFileBuffer(path)),
52
+ writeFile: async (_resolved, content) => fs.writeFile(path, content),
53
+ mkdir: () => fs.mkdir(posix.dirname(path), { recursive: true }),
54
+ };
55
+ }
56
+ export function createWorkspaceTools(resolveWorkspace) {
57
+ function wrap(metadata, create, normalize) {
58
+ return {
59
+ ...metadata,
60
+ ...virtualRenderers(metadata.name),
61
+ async execute(id, input, signal, _onUpdate, ctx) {
62
+ try {
63
+ return await resolveWorkspace(ctx).run(signal, async (fs, operationSignal) => {
64
+ const normalized = normalize(input);
65
+ const result = await create(fs, normalized).execute(id, normalized, operationSignal, undefined, {
66
+ ...ctx,
67
+ cwd: "/",
68
+ });
69
+ return {
70
+ ...result,
71
+ content: result.content.map((item) => item.type === "text" ? { ...item, text: boundedText(item.text) } : item),
72
+ };
73
+ });
74
+ }
75
+ catch (error) {
76
+ throw new Error(boundedText(error instanceof Error ? error.message : String(error)));
77
+ }
78
+ },
79
+ };
80
+ }
81
+ const files = [
82
+ wrap(createVirtualRead({ access: async () => { }, readFile: async () => Buffer.alloc(0) }), (fs, input) => createVirtualRead(fileOperations(fs, input.path)), (input) => ({ ...input, path: virtualPath(input.path) })),
83
+ wrap(createWriteToolDefinition("/"), (fs, input) => createWriteToolDefinition("/", { operations: fileOperations(fs, input.path) }), (input) => ({ ...input, path: virtualPath(input.path) })),
84
+ wrap(createEditToolDefinition("/"), (fs, input) => createEditToolDefinition("/", { operations: fileOperations(fs, input.path) }), (input) => ({ ...input, path: virtualPath(input.path) })),
85
+ ];
86
+ const shellSchema = Type.Object({
87
+ command: Type.String(),
88
+ timeout: Type.Optional(Type.Number({ description: "Timeout in seconds, greater than 0 and at most 30" })),
89
+ });
90
+ const shell = {
91
+ name: "bash",
92
+ label: "bash",
93
+ description: "Run a restricted just-bash script in AgentFS, not a host shell. Supports virtual file commands, pipes, and redirection. Each call starts at / with a fresh environment. No network, subprocesses, Python, or JavaScript. Output is limited to 50 KB or 2,000 lines; excess output is discarded. Timeout defaults to 30 seconds and cannot exceed 30 seconds.",
94
+ promptSnippet: "Run restricted shell commands in the AgentFS virtual workspace",
95
+ parameters: shellSchema,
96
+ outputSchema: Type.Object({ output: Type.String(), exit_code: Type.Number(), truncated: Type.Boolean() }),
97
+ ...virtualRenderers("bash"),
98
+ async execute(_id, { command, timeout = SHELL_TIMEOUT_SECONDS }, signal, _onUpdate, ctx) {
99
+ if (!Number.isFinite(timeout) || timeout <= 0 || timeout > SHELL_TIMEOUT_SECONDS) {
100
+ throw new Error("Timeout must be greater than 0 and at most 30 seconds.");
101
+ }
102
+ try {
103
+ return await resolveWorkspace(ctx).run(signal, async (fs, operationSignal) => {
104
+ const deadline = new AbortController();
105
+ const timer = setTimeout(() => deadline.abort(), Math.max(1, timeout * 1000));
106
+ const combined = AbortSignal.any([operationSignal, deadline.signal]);
107
+ try {
108
+ const shell = new Bash({
109
+ fs,
110
+ cwd: "/",
111
+ env: { HOME: "/", PATH: "/usr/bin:/bin" },
112
+ commands: [...SHELL_COMMANDS],
113
+ python: false,
114
+ javascript: false,
115
+ executionLimitProfile: "hardened",
116
+ executionLimits: SHELL_LIMITS,
117
+ });
118
+ const result = await shell.exec(command, {
119
+ signal: combined,
120
+ cwd: "/",
121
+ replaceEnv: true,
122
+ env: { HOME: "/", PATH: "/usr/bin:/bin" },
123
+ });
124
+ if (combined.aborted)
125
+ throw new Error("Command aborted");
126
+ const raw = result.stdout + result.stderr;
127
+ const output = boundedText(raw);
128
+ if (result.exitCode !== 0)
129
+ throw new Error(boundedText(`Command exited with code ${result.exitCode}\n${raw}`));
130
+ return {
131
+ content: [{ type: "text", text: output || "(no output)" }],
132
+ details: undefined,
133
+ structuredContent: { output, exit_code: result.exitCode, truncated: output !== raw },
134
+ };
135
+ }
136
+ catch (error) {
137
+ if (deadline.signal.aborted)
138
+ throw new Error(`Command timed out after ${timeout} seconds.`);
139
+ if (operationSignal.aborted)
140
+ throw new Error("Command aborted.");
141
+ throw error;
142
+ }
143
+ finally {
144
+ clearTimeout(timer);
145
+ }
146
+ });
147
+ }
148
+ catch (error) {
149
+ throw new Error(boundedText(error instanceof Error ? error.message : String(error)));
150
+ }
151
+ },
152
+ };
153
+ // ToolDefinition is invariant in its schema/renderers. Pi validates each concrete schema before
154
+ // execute; this heterogeneous registration list does not change any definition or implementation.
155
+ return [...files, shell];
156
+ }