@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/src/factory.ts ADDED
@@ -0,0 +1,112 @@
1
+ import type { ExtensionAPI, ExtensionContext, ExtensionFactory } from "@earendil-works/pi-coding-agent";
2
+ import { validateDatabasePath } from "./paths.js";
3
+ import { createWorkspaceTools } from "./tools.js";
4
+ import { Workspace } from "./workspace.js";
5
+
6
+ type WorkspaceState = {
7
+ status: "loading" | "ready" | "failed" | "closed";
8
+ workspace?: Workspace;
9
+ initialization: Promise<void>;
10
+ };
11
+
12
+ export type AgentfsExtension = ExtensionFactory & {
13
+ /** Call after session.bindExtensions(); Pi reports lifecycle errors without rejecting that call. */
14
+ ready(sessionManager: object): Promise<void>;
15
+ };
16
+
17
+ /** Package-owned lifecycle shared by the SDK factory and the opt-in CLI entrypoint. */
18
+ export function installAgentfsLifecycle(
19
+ pi: ExtensionAPI,
20
+ states: WeakMap<object, WorkspaceState>,
21
+ resolvePath: () => unknown,
22
+ registerDuringLoad: boolean,
23
+ ): void {
24
+ // CLI flags are fixed for this runtime, including an absent flag.
25
+ let pathResolved = false;
26
+ let path: unknown;
27
+ let requested = registerDuringLoad;
28
+
29
+ const resolveWorkspace = (ctx: ExtensionContext): Workspace => {
30
+ const state = states.get(ctx.sessionManager);
31
+ if (state?.status !== "ready" || !state.workspace) {
32
+ throw new Error(`AgentFS workspace is ${state?.status ?? "not started"}`);
33
+ }
34
+ return state.workspace;
35
+ };
36
+ let toolsRegistered = false;
37
+ const registerTools = () => {
38
+ if (toolsRegistered) return;
39
+ for (const tool of createWorkspaceTools(resolveWorkspace)) pi.registerTool(tool);
40
+ toolsRegistered = true;
41
+ };
42
+ if (registerDuringLoad) registerTools();
43
+
44
+ pi.on("user_bash", () => {
45
+ if (requested) {
46
+ // Returning undefined here would let ! and !! execute on the host.
47
+ throw new Error("AgentFS blocks ! and !! host commands; use the bash tool instead");
48
+ }
49
+ return undefined;
50
+ });
51
+
52
+ pi.on("session_start", async (_event, ctx) => {
53
+ if (!pathResolved) {
54
+ path = resolvePath();
55
+ pathResolved = true;
56
+ }
57
+ if (path === undefined && !registerDuringLoad) return;
58
+ requested = true;
59
+
60
+ const key = ctx.sessionManager;
61
+ const previous = states.get(key);
62
+ if (previous) previous.status = "closed";
63
+ const state: WorkspaceState = { status: "loading", initialization: Promise.resolve() };
64
+ const isCurrent = () => states.get(key) === state && state.status !== "closed";
65
+ states.set(key, state);
66
+ // Replace host tools before validation or opening. Pi swallows session_start errors.
67
+ if (!registerDuringLoad) registerTools();
68
+ state.initialization = (async () => {
69
+ try {
70
+ await previous?.workspace?.close();
71
+ if (!isCurrent()) throw new Error("AgentFS workspace was closed during initialization");
72
+ validateDatabasePath(path);
73
+ state.workspace = new Workspace(path);
74
+ await state.workspace.open();
75
+ if (!isCurrent()) throw new Error("AgentFS workspace was closed during initialization");
76
+ state.status = "ready";
77
+ } catch (error) {
78
+ if (state.status !== "closed") state.status = "failed";
79
+ await state.workspace?.close();
80
+ throw error;
81
+ }
82
+ })();
83
+ await state.initialization;
84
+ });
85
+
86
+ pi.on("session_shutdown", async (_event, ctx) => {
87
+ const state = states.get(ctx.sessionManager);
88
+ if (!state) return;
89
+ state.status = "closed";
90
+ await state.workspace?.close();
91
+ // Also drain a pending open, including its cleanup, before shutdown returns.
92
+ await state.initialization.catch(() => undefined);
93
+ });
94
+ }
95
+
96
+ /** Register exactly the AgentFS read, write, edit, and bash replacements. */
97
+ export function createAgentfsExtension(options: { path: string }): AgentfsExtension {
98
+ validateDatabasePath(options.path);
99
+ const path = options.path;
100
+ const states = new WeakMap<object, WorkspaceState>();
101
+ const factory: ExtensionFactory = (pi) => installAgentfsLifecycle(pi, states, () => path, true);
102
+ return Object.assign(factory, {
103
+ async ready(sessionManager: object): Promise<void> {
104
+ const state = states.get(sessionManager);
105
+ if (!state) throw new Error("AgentFS workspace has not started; call session.bindExtensions() first");
106
+ await state.initialization;
107
+ if (states.get(sessionManager) !== state || state.status !== "ready") {
108
+ throw new Error(`AgentFS workspace is ${state.status}`);
109
+ }
110
+ },
111
+ });
112
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { default } from "./agentfs-extension.js";
package/src/output.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { truncateHead } from "@earendil-works/pi-coding-agent";
2
+
3
+ export const MAX_OUTPUT_BYTES = 50 * 1024;
4
+ export const MAX_OUTPUT_LINES = 2000;
5
+
6
+ /** Reserve space for the notice so the complete returned text stays within Pi's limits. */
7
+ export function boundedText(text: string): string {
8
+ if (!truncateHead(text).truncated) return text;
9
+ const result = truncateHead(text, { maxBytes: MAX_OUTPUT_BYTES - 128, maxLines: MAX_OUTPUT_LINES - 2 });
10
+ return result.truncated ? `${result.content}\n[Output truncated; excess output was discarded.]` : text;
11
+ }
package/src/paths.ts ADDED
@@ -0,0 +1,16 @@
1
+ import { isAbsolute, posix } from "node:path";
2
+
3
+ export function validateDatabasePath(path: unknown): asserts path is string {
4
+ if (typeof path !== "string" || !path.trim() || !isAbsolute(path) || path.includes("\0")) {
5
+ throw new Error("AgentFS requires a nonempty absolute database path.");
6
+ }
7
+ }
8
+
9
+ /** Virtual paths never use the host cwd or home directory. */
10
+ export function virtualPath(path: string): string {
11
+ if (!path || path.includes("\0")) throw new Error("Invalid virtual path.");
12
+ if (path === "~") return "/";
13
+ if (path.startsWith("~/")) path = path.slice(2);
14
+ else if (path.startsWith("~")) throw new Error("Named home directories are not supported.");
15
+ return posix.resolve("/", path);
16
+ }
package/src/read.ts ADDED
@@ -0,0 +1,53 @@
1
+ import type { ReadOperations, ReadToolDetails, ReadToolInput } from "@earendil-works/pi-coding-agent";
2
+ import { createReadToolDefinition, formatSize, truncateHead } from "@earendil-works/pi-coding-agent";
3
+ import { MAX_OUTPUT_BYTES, MAX_OUTPUT_LINES } from "./output.js";
4
+ import { virtualRenderers } from "./renderers.js";
5
+
6
+ /** Pi's resolver probes the host before ReadOperations. Use only its schema and
7
+ * truncation helpers, never its execute method. Images and host filename guesses are omitted. */
8
+ export function createVirtualRead(operations: ReadOperations): ReturnType<typeof createReadToolDefinition> {
9
+ const core = createReadToolDefinition("/", { operations });
10
+ return {
11
+ ...core,
12
+ ...virtualRenderers("read"),
13
+ description:
14
+ "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.",
15
+ async execute(_id: string, { path, offset, limit }: ReadToolInput, signal?: AbortSignal) {
16
+ const check = () => {
17
+ if (signal?.aborted) throw new Error("Operation aborted");
18
+ };
19
+ for (const [name, value] of [
20
+ ["offset", offset],
21
+ ["limit", limit],
22
+ ] as const) {
23
+ if (value !== undefined && (!Number.isSafeInteger(value) || value < 1)) {
24
+ throw new Error(`${name} must be a positive integer.`);
25
+ }
26
+ }
27
+ check();
28
+ await operations.access(path);
29
+ check();
30
+ const buffer = await operations.readFile(path);
31
+ check();
32
+ const lines = buffer.toString("utf-8").split("\n");
33
+ const start = (offset ?? 1) - 1;
34
+ if (start >= lines.length)
35
+ throw new Error(`Offset ${offset} is beyond end of file (${lines.length} lines total)`);
36
+ const selected = lines.slice(start, limit === undefined ? undefined : start + limit).join("\n");
37
+ const truncation = truncateHead(selected, { maxBytes: MAX_OUTPUT_BYTES - 512, maxLines: MAX_OUTPUT_LINES - 3 });
38
+ let text = truncation.content;
39
+ let details: ReadToolDetails | undefined;
40
+ if (truncation.firstLineExceedsLimit) {
41
+ 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.]`;
42
+ details = { truncation };
43
+ } else if (truncation.truncated) {
44
+ const end = start + truncation.outputLines;
45
+ text += `\n\n[Showing lines ${start + 1}-${end} of ${lines.length}. Use offset=${end + 1} to continue.]`;
46
+ details = { truncation };
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" as const, text }], details, structuredContent: text };
51
+ },
52
+ };
53
+ }
@@ -0,0 +1,76 @@
1
+ import { stripVTControlCharacters } from "node:util";
2
+ import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
3
+ import type { Component } from "@earendil-works/pi-tui";
4
+ import { hardWrapTerminalDocument } from "@narumitw/pi-tui-kit";
5
+
6
+ function displayText(text: string): string {
7
+ // Preserve raw tool payloads; strip terminal controls only at the display boundary.
8
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: intentionally remove controls, except line feeds and tabs.
9
+ const controls = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g;
10
+ return stripVTControlCharacters(text).replace(controls, "").replaceAll("\t", " ");
11
+ }
12
+
13
+ function boundedComponent(text: string, style: (line: string, offset: number) => string, padding = 0): Component {
14
+ let cachedWidth: number | undefined;
15
+ let cachedLines: string[] | undefined;
16
+ return {
17
+ render(width) {
18
+ if (!Number.isFinite(width) || width < 1) return [];
19
+ const safeWidth = Math.floor(width);
20
+ if (cachedWidth === safeWidth && cachedLines) return cachedLines;
21
+ const marginWidth = Math.min(padding, Math.max(0, Math.floor((safeWidth - 1) / 2)));
22
+ const margin = " ".repeat(marginWidth);
23
+ let offset = 0;
24
+ // Word wrapping trims spaces and hides whitespace-only documents. Wrap sanitized text
25
+ // by display cells first, then apply trusted theme styles to each complete output row.
26
+ cachedLines = hardWrapTerminalDocument(text, safeWidth - marginWidth * 2).map((line) => {
27
+ const rendered = margin + style(line, offset) + margin;
28
+ offset += line.length;
29
+ return rendered;
30
+ });
31
+ cachedWidth = safeWidth;
32
+ return cachedLines;
33
+ },
34
+ invalidate() {
35
+ cachedWidth = undefined;
36
+ cachedLines = undefined;
37
+ },
38
+ };
39
+ }
40
+
41
+ /** Core path renderers link to host files; the edit preview also reads host files. Neither applies
42
+ * to virtual files. Render only supplied text and completed diffs, without speculative I/O. */
43
+ export function virtualRenderers(name: string): Pick<ToolDefinition, "renderCall" | "renderResult" | "renderShell"> {
44
+ return {
45
+ renderShell: undefined,
46
+ renderCall(input, theme) {
47
+ const args = input && typeof input === "object" ? (input as Record<string, unknown>) : {};
48
+ const value = name === "bash" ? args.command : args.path;
49
+ const label = typeof value === "string" ? displayText(value).replaceAll("\n", "\\n") : "...";
50
+ return boundedComponent(`${name} ${label}`, (line, offset) => {
51
+ const titleLength = Math.max(0, name.length - offset);
52
+ return (
53
+ theme.fg("toolTitle", theme.bold(line.slice(0, titleLength))) + theme.fg("accent", line.slice(titleLength))
54
+ );
55
+ });
56
+ },
57
+ renderResult(result, options, theme, context) {
58
+ const details =
59
+ result.details && typeof result.details === "object" ? (result.details as Record<string, unknown>) : {};
60
+ const raw =
61
+ name === "edit" && !context.isError && typeof details.diff === "string"
62
+ ? details.diff
63
+ : result.content
64
+ .filter((item) => item.type === "text")
65
+ .map((item) => item.text)
66
+ .join("\n");
67
+ const text = displayText(raw);
68
+ const visible = options.expanded ? text : text.split("\n").slice(0, 10).join("\n");
69
+ return boundedComponent(
70
+ visible,
71
+ (line) => theme.fg(context.isError ? "error" : "toolOutput", line),
72
+ context.outputPad,
73
+ );
74
+ },
75
+ };
76
+ }
package/src/tools.ts ADDED
@@ -0,0 +1,176 @@
1
+ import { posix } from "node:path";
2
+ import {
3
+ createEditToolDefinition,
4
+ createWriteToolDefinition,
5
+ type ExtensionContext,
6
+ type ToolDefinition,
7
+ } from "@earendil-works/pi-coding-agent";
8
+ import { Bash, type IFileSystem } from "just-bash";
9
+ import { Type } from "typebox";
10
+ import { boundedText } from "./output.js";
11
+ import { virtualPath } from "./paths.js";
12
+ import { createVirtualRead } from "./read.js";
13
+ import { virtualRenderers } from "./renderers.js";
14
+ import type { Workspace } from "./workspace.js";
15
+
16
+ export const SHELL_COMMANDS = [
17
+ "ls",
18
+ "cat",
19
+ "grep",
20
+ "find",
21
+ "mkdir",
22
+ "rm",
23
+ "cp",
24
+ "mv",
25
+ "head",
26
+ "tail",
27
+ "wc",
28
+ "sort",
29
+ "uniq",
30
+ "cut",
31
+ "tr",
32
+ "tee",
33
+ "pwd",
34
+ "echo",
35
+ "true",
36
+ "false",
37
+ "sleep",
38
+ "seq",
39
+ "sed",
40
+ ] as const;
41
+ export const SHELL_TIMEOUT_SECONDS = 30;
42
+ export const SHELL_LIMITS = {
43
+ maxSourceBytes: 64 * 1024,
44
+ maxCommandCount: 10_000,
45
+ maxLoopIterations: 1000,
46
+ maxOutputSize: 1024 * 1024,
47
+ maxExecutionTimeMs: SHELL_TIMEOUT_SECONDS * 1000,
48
+ } as const;
49
+
50
+ function fileOperations(fs: IFileSystem, path: string) {
51
+ // Pin operations to the virtual path. Pi may normalize Unicode spaces, file URLs, or Windows
52
+ // paths internally; those host-oriented transformations must not select a different file.
53
+ return {
54
+ access: async () => {
55
+ const stat = await fs.stat(path);
56
+ if (!stat.isFile || stat.isSymbolicLink) throw new Error("Path is not a regular virtual file.");
57
+ },
58
+ readFile: async () => Buffer.from(await fs.readFileBuffer(path)),
59
+ writeFile: async (_resolved: string, content: string) => fs.writeFile(path, content),
60
+ mkdir: () => fs.mkdir(posix.dirname(path), { recursive: true }),
61
+ };
62
+ }
63
+
64
+ export function createWorkspaceTools(resolveWorkspace: (ctx: ExtensionContext) => Workspace): ToolDefinition[] {
65
+ function wrap<T extends Type.TSchema, D, S>(
66
+ metadata: ToolDefinition<T, D, S>,
67
+ create: (fs: IFileSystem, input: Parameters<ToolDefinition<T>["execute"]>[1]) => ToolDefinition<T, D, S>,
68
+ normalize: (input: Parameters<ToolDefinition<T>["execute"]>[1]) => Parameters<ToolDefinition<T>["execute"]>[1],
69
+ ): ToolDefinition<T, D, S> {
70
+ return {
71
+ ...metadata,
72
+ ...virtualRenderers(metadata.name),
73
+ async execute(id, input, signal, _onUpdate, ctx) {
74
+ try {
75
+ return await resolveWorkspace(ctx).run(signal, async (fs, operationSignal) => {
76
+ const normalized = normalize(input);
77
+ const result = await create(fs, normalized).execute(id, normalized, operationSignal, undefined, {
78
+ ...ctx,
79
+ cwd: "/",
80
+ });
81
+ return {
82
+ ...result,
83
+ content: result.content.map((item) =>
84
+ item.type === "text" ? { ...item, text: boundedText(item.text) } : item,
85
+ ),
86
+ };
87
+ });
88
+ } catch (error) {
89
+ throw new Error(boundedText(error instanceof Error ? error.message : String(error)));
90
+ }
91
+ },
92
+ };
93
+ }
94
+ const files = [
95
+ wrap(
96
+ createVirtualRead({ access: async () => {}, readFile: async () => Buffer.alloc(0) }),
97
+ (fs, input) => createVirtualRead(fileOperations(fs, input.path)),
98
+ (input) => ({ ...input, path: virtualPath(input.path) }),
99
+ ),
100
+ wrap(
101
+ createWriteToolDefinition("/"),
102
+ (fs, input) => createWriteToolDefinition("/", { operations: fileOperations(fs, input.path) }),
103
+ (input) => ({ ...input, path: virtualPath(input.path) }),
104
+ ),
105
+ wrap(
106
+ createEditToolDefinition("/"),
107
+ (fs, input) => createEditToolDefinition("/", { operations: fileOperations(fs, input.path) }),
108
+ (input) => ({ ...input, path: virtualPath(input.path) }),
109
+ ),
110
+ ];
111
+ const shellSchema = Type.Object({
112
+ command: Type.String(),
113
+ timeout: Type.Optional(Type.Number({ description: "Timeout in seconds, greater than 0 and at most 30" })),
114
+ });
115
+ const shell: ToolDefinition<typeof shellSchema> = {
116
+ name: "bash",
117
+ label: "bash",
118
+ description:
119
+ "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.",
120
+ promptSnippet: "Run restricted shell commands in the AgentFS virtual workspace",
121
+ parameters: shellSchema,
122
+ outputSchema: Type.Object({ output: Type.String(), exit_code: Type.Number(), truncated: Type.Boolean() }),
123
+ ...virtualRenderers("bash"),
124
+ async execute(_id, { command, timeout = SHELL_TIMEOUT_SECONDS }, signal, _onUpdate, ctx) {
125
+ if (!Number.isFinite(timeout) || timeout <= 0 || timeout > SHELL_TIMEOUT_SECONDS) {
126
+ throw new Error("Timeout must be greater than 0 and at most 30 seconds.");
127
+ }
128
+ try {
129
+ return await resolveWorkspace(ctx).run(signal, async (fs, operationSignal) => {
130
+ const deadline = new AbortController();
131
+ const timer = setTimeout(() => deadline.abort(), Math.max(1, timeout * 1000));
132
+ const combined = AbortSignal.any([operationSignal, deadline.signal]);
133
+ try {
134
+ const shell = new Bash({
135
+ fs,
136
+ cwd: "/",
137
+ env: { HOME: "/", PATH: "/usr/bin:/bin" },
138
+ commands: [...SHELL_COMMANDS],
139
+ python: false,
140
+ javascript: false,
141
+ executionLimitProfile: "hardened",
142
+ executionLimits: SHELL_LIMITS,
143
+ });
144
+ const result = await shell.exec(command, {
145
+ signal: combined,
146
+ cwd: "/",
147
+ replaceEnv: true,
148
+ env: { HOME: "/", PATH: "/usr/bin:/bin" },
149
+ });
150
+ if (combined.aborted) throw new Error("Command aborted");
151
+ const raw = result.stdout + result.stderr;
152
+ const output = boundedText(raw);
153
+ if (result.exitCode !== 0)
154
+ throw new Error(boundedText(`Command exited with code ${result.exitCode}\n${raw}`));
155
+ return {
156
+ content: [{ type: "text" as const, text: output || "(no output)" }],
157
+ details: undefined,
158
+ structuredContent: { output, exit_code: result.exitCode, truncated: output !== raw },
159
+ };
160
+ } catch (error) {
161
+ if (deadline.signal.aborted) throw new Error(`Command timed out after ${timeout} seconds.`);
162
+ if (operationSignal.aborted) throw new Error("Command aborted.");
163
+ throw error;
164
+ } finally {
165
+ clearTimeout(timer);
166
+ }
167
+ });
168
+ } catch (error) {
169
+ throw new Error(boundedText(error instanceof Error ? error.message : String(error)));
170
+ }
171
+ },
172
+ };
173
+ // ToolDefinition is invariant in its schema/renderers. Pi validates each concrete schema before
174
+ // execute; this heterogeneous registration list does not change any definition or implementation.
175
+ return [...files, shell] as unknown as ToolDefinition[];
176
+ }
@@ -0,0 +1,181 @@
1
+ import { Database } from "@tursodatabase/database";
2
+ import { type FileSystem, Filesystem } from "agentfs-sdk";
3
+ import { AgentFsWrapper } from "agentfs-sdk/just-bash";
4
+ import type { IFileSystem } from "just-bash";
5
+ import { validateDatabasePath, virtualPath } from "./paths.js";
6
+
7
+ function isMissing(error: unknown): boolean {
8
+ return !!error && typeof error === "object" && "code" in error && error.code === "ENOENT";
9
+ }
10
+
11
+ /** Add missing just-bash methods and preserve storage failures instead of treating them as absence. */
12
+ class VirtualFileSystem extends AgentFsWrapper implements IFileSystem {
13
+ constructor(private readonly filesystem: FileSystem) {
14
+ super({ fs: { fs: filesystem } });
15
+ }
16
+
17
+ override async exists(path: string): Promise<boolean> {
18
+ try {
19
+ await this.filesystem.access(virtualPath(path));
20
+ return true;
21
+ } catch (error) {
22
+ if (!isMissing(error)) throw error;
23
+ return false;
24
+ }
25
+ }
26
+
27
+ override async appendFile(...[path, content, options]: Parameters<AgentFsWrapper["appendFile"]>): Promise<void> {
28
+ const normalized = virtualPath(path);
29
+ let previous: Buffer;
30
+ try {
31
+ previous = Buffer.from(await this.filesystem.readFile(normalized));
32
+ } catch (error) {
33
+ // The upstream wrapper treats every read failure as an absent file, which can truncate
34
+ // existing data after an I/O error. Only the SDK's explicit ENOENT means an empty file.
35
+ if (!isMissing(error)) throw error;
36
+ previous = Buffer.alloc(0);
37
+ }
38
+ const encoding = typeof options === "string" ? options : options?.encoding;
39
+ const bytes = typeof content === "string" ? Buffer.from(content, encoding) : Buffer.from(content);
40
+ await this.filesystem.writeFile(normalized, Buffer.concat([previous, bytes]));
41
+ }
42
+
43
+ async realpath(path: string): Promise<string> {
44
+ const normalized = virtualPath(path);
45
+ let current = "";
46
+ for (const part of normalized.split("/").filter(Boolean)) {
47
+ current += `/${part}`;
48
+ const stat = await this.lstat(current);
49
+ if (stat.isSymbolicLink) throw new Error("Symbolic links are not supported.");
50
+ }
51
+ return normalized;
52
+ }
53
+
54
+ async utimes(): Promise<void> {
55
+ throw new Error("File timestamp changes are not supported.");
56
+ }
57
+
58
+ override async symlink(): Promise<void> {
59
+ throw new Error("Symbolic links are not supported.");
60
+ }
61
+
62
+ override async link(): Promise<void> {
63
+ throw new Error("Hard links are not supported.");
64
+ }
65
+ }
66
+
67
+ /** One session owns one connection and one queue covering complete shell and file operations. */
68
+ export class Workspace {
69
+ private state: "new" | "opening" | "ready" | "failed" | "closing" | "closed" = "new";
70
+ private database?: Database;
71
+ private filesystem?: FileSystem;
72
+ private opening?: Promise<void>;
73
+ private closing?: Promise<void>;
74
+ private databaseClosing?: Promise<void>;
75
+ private tail: Promise<unknown> = Promise.resolve();
76
+ private active?: AbortController;
77
+
78
+ constructor(private readonly path: string) {
79
+ validateDatabasePath(path);
80
+ }
81
+
82
+ open(): Promise<void> {
83
+ if (this.state === "ready") return Promise.resolve();
84
+ if (this.state === "opening") return this.opening as Promise<void>;
85
+ if (this.state !== "new") return Promise.reject(new Error("AgentFS workspace is not available."));
86
+ this.state = "opening";
87
+ this.opening = this.initialize();
88
+ return this.opening;
89
+ }
90
+
91
+ private async initialize(): Promise<void> {
92
+ try {
93
+ // Own the connection before initialization. Initialize only the public filesystem API:
94
+ // AgentFS.openWith() starts unrelated schema branches in Promise.all and can reject before
95
+ // sibling initialization work drains, making immediate failure cleanup unsafe.
96
+ this.database = new Database(this.path);
97
+ await this.database.connect();
98
+ this.assertOpening();
99
+ this.filesystem = await Filesystem.fromDatabase(this.database);
100
+ this.assertOpening();
101
+ this.state = "ready";
102
+ } catch {
103
+ if (this.state === "opening") this.state = "failed";
104
+ await this.closeDatabase();
105
+ throw new Error("AgentFS workspace initialization failed; no host fallback is available.");
106
+ }
107
+ }
108
+
109
+ private assertOpening(): void {
110
+ if (this.state !== "opening") throw new Error("AgentFS workspace was closed during initialization.");
111
+ }
112
+
113
+ private closeDatabase(): Promise<void> {
114
+ this.databaseClosing ??= this.database?.close() ?? Promise.resolve();
115
+ return this.databaseClosing;
116
+ }
117
+
118
+ run<T>(signal: AbortSignal | undefined, callback: (fs: IFileSystem, signal: AbortSignal) => Promise<T>): Promise<T> {
119
+ const operation = this.tail.then(async () => {
120
+ if (this.state !== "ready" || !this.filesystem) throw new Error("AgentFS workspace is not ready or is closed.");
121
+ const controller = new AbortController();
122
+ this.active = controller;
123
+ const combined = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
124
+ let valid = true;
125
+ const pending = new Set<Promise<unknown>>();
126
+ const check = () => {
127
+ if (!valid || combined.aborted || this.state !== "ready") throw new Error("AgentFS operation aborted.");
128
+ };
129
+ // Track the actual database operations, not just the interpreter promise. Cancellation may
130
+ // revoke an interpreter while a database operation is still completing. Drain before close.
131
+ const guarded = new Proxy(this.filesystem, {
132
+ get(target, key) {
133
+ const value: unknown = Reflect.get(target, key);
134
+ if (typeof value !== "function") return value;
135
+ return (...args: unknown[]) => {
136
+ check();
137
+ const work = Promise.resolve(Reflect.apply(value, target, args)).then((result) => {
138
+ check();
139
+ return result;
140
+ });
141
+ pending.add(work);
142
+ void work.then(
143
+ () => pending.delete(work),
144
+ () => pending.delete(work),
145
+ );
146
+ return work;
147
+ };
148
+ },
149
+ }) as FileSystem;
150
+ try {
151
+ check();
152
+ const result = await callback(new VirtualFileSystem(guarded), combined);
153
+ check();
154
+ return result;
155
+ } finally {
156
+ valid = false;
157
+ while (pending.size) await Promise.allSettled([...pending]);
158
+ if (this.active === controller) this.active = undefined;
159
+ }
160
+ });
161
+ this.tail = operation.catch(() => undefined);
162
+ return operation;
163
+ }
164
+
165
+ close(): Promise<void> {
166
+ if (this.closing) return this.closing;
167
+ this.state = "closing";
168
+ this.active?.abort();
169
+ this.closing = (async () => {
170
+ await this.opening?.catch(() => undefined);
171
+ await this.tail;
172
+ try {
173
+ await this.closeDatabase();
174
+ } finally {
175
+ this.filesystem = undefined;
176
+ this.state = "closed";
177
+ }
178
+ })();
179
+ return this.closing;
180
+ }
181
+ }