@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 +21 -0
- package/README.md +132 -2
- package/dist/agentfs-extension.d.ts +2 -0
- package/dist/agentfs-extension.js +8 -0
- package/dist/factory.d.ts +18 -0
- package/dist/factory.js +100 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/output.d.ts +4 -0
- package/dist/output.js +10 -0
- package/dist/paths.d.ts +3 -0
- package/dist/paths.js +18 -0
- package/dist/read.d.ts +5 -0
- package/dist/read.js +53 -0
- package/dist/renderers.d.ts +4 -0
- package/dist/renderers.js +65 -0
- package/dist/tools.d.ts +12 -0
- package/dist/tools.js +156 -0
- package/dist/workspace.d.ts +20 -0
- package/dist/workspace.js +184 -0
- package/docs/dependency-security.md +20 -0
- package/docs/integration.md +208 -0
- package/examples/service.ts +118 -0
- package/package.json +56 -4
- package/src/agentfs-extension.ts +10 -0
- package/src/factory.ts +112 -0
- package/src/index.ts +1 -0
- package/src/output.ts +11 -0
- package/src/paths.ts +16 -0
- package/src/read.ts +53 -0
- package/src/renderers.ts +76 -0
- package/src/tools.ts +176 -0
- package/src/workspace.ts +181 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { IFileSystem } from "just-bash";
|
|
2
|
+
/** One session owns one connection and one queue covering complete shell and file operations. */
|
|
3
|
+
export declare class Workspace {
|
|
4
|
+
private readonly path;
|
|
5
|
+
private state;
|
|
6
|
+
private database?;
|
|
7
|
+
private filesystem?;
|
|
8
|
+
private opening?;
|
|
9
|
+
private closing?;
|
|
10
|
+
private databaseClosing?;
|
|
11
|
+
private tail;
|
|
12
|
+
private active?;
|
|
13
|
+
constructor(path: string);
|
|
14
|
+
open(): Promise<void>;
|
|
15
|
+
private initialize;
|
|
16
|
+
private assertOpening;
|
|
17
|
+
private closeDatabase;
|
|
18
|
+
run<T>(signal: AbortSignal | undefined, callback: (fs: IFileSystem, signal: AbortSignal) => Promise<T>): Promise<T>;
|
|
19
|
+
close(): Promise<void>;
|
|
20
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { Database } from "@tursodatabase/database";
|
|
2
|
+
import { Filesystem } from "agentfs-sdk";
|
|
3
|
+
import { AgentFsWrapper } from "agentfs-sdk/just-bash";
|
|
4
|
+
import { validateDatabasePath, virtualPath } from "./paths.js";
|
|
5
|
+
function isMissing(error) {
|
|
6
|
+
return !!error && typeof error === "object" && "code" in error && error.code === "ENOENT";
|
|
7
|
+
}
|
|
8
|
+
/** Add missing just-bash methods and preserve storage failures instead of treating them as absence. */
|
|
9
|
+
class VirtualFileSystem extends AgentFsWrapper {
|
|
10
|
+
filesystem;
|
|
11
|
+
constructor(filesystem) {
|
|
12
|
+
super({ fs: { fs: filesystem } });
|
|
13
|
+
this.filesystem = filesystem;
|
|
14
|
+
}
|
|
15
|
+
async exists(path) {
|
|
16
|
+
try {
|
|
17
|
+
await this.filesystem.access(virtualPath(path));
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
if (!isMissing(error))
|
|
22
|
+
throw error;
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
async appendFile(...[path, content, options]) {
|
|
27
|
+
const normalized = virtualPath(path);
|
|
28
|
+
let previous;
|
|
29
|
+
try {
|
|
30
|
+
previous = Buffer.from(await this.filesystem.readFile(normalized));
|
|
31
|
+
}
|
|
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))
|
|
36
|
+
throw error;
|
|
37
|
+
previous = Buffer.alloc(0);
|
|
38
|
+
}
|
|
39
|
+
const encoding = typeof options === "string" ? options : options?.encoding;
|
|
40
|
+
const bytes = typeof content === "string" ? Buffer.from(content, encoding) : Buffer.from(content);
|
|
41
|
+
await this.filesystem.writeFile(normalized, Buffer.concat([previous, bytes]));
|
|
42
|
+
}
|
|
43
|
+
async realpath(path) {
|
|
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)
|
|
50
|
+
throw new Error("Symbolic links are not supported.");
|
|
51
|
+
}
|
|
52
|
+
return normalized;
|
|
53
|
+
}
|
|
54
|
+
async utimes() {
|
|
55
|
+
throw new Error("File timestamp changes are not supported.");
|
|
56
|
+
}
|
|
57
|
+
async symlink() {
|
|
58
|
+
throw new Error("Symbolic links are not supported.");
|
|
59
|
+
}
|
|
60
|
+
async link() {
|
|
61
|
+
throw new Error("Hard links are not supported.");
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** One session owns one connection and one queue covering complete shell and file operations. */
|
|
65
|
+
export class Workspace {
|
|
66
|
+
path;
|
|
67
|
+
state = "new";
|
|
68
|
+
database;
|
|
69
|
+
filesystem;
|
|
70
|
+
opening;
|
|
71
|
+
closing;
|
|
72
|
+
databaseClosing;
|
|
73
|
+
tail = Promise.resolve();
|
|
74
|
+
active;
|
|
75
|
+
constructor(path) {
|
|
76
|
+
this.path = path;
|
|
77
|
+
validateDatabasePath(path);
|
|
78
|
+
}
|
|
79
|
+
open() {
|
|
80
|
+
if (this.state === "ready")
|
|
81
|
+
return Promise.resolve();
|
|
82
|
+
if (this.state === "opening")
|
|
83
|
+
return this.opening;
|
|
84
|
+
if (this.state !== "new")
|
|
85
|
+
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
|
+
async initialize() {
|
|
91
|
+
try {
|
|
92
|
+
// Own the connection before initialization. Initialize only the public filesystem API:
|
|
93
|
+
// AgentFS.openWith() starts unrelated schema branches in Promise.all and can reject before
|
|
94
|
+
// sibling initialization work drains, making immediate failure cleanup unsafe.
|
|
95
|
+
this.database = new Database(this.path);
|
|
96
|
+
await this.database.connect();
|
|
97
|
+
this.assertOpening();
|
|
98
|
+
this.filesystem = await Filesystem.fromDatabase(this.database);
|
|
99
|
+
this.assertOpening();
|
|
100
|
+
this.state = "ready";
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
if (this.state === "opening")
|
|
104
|
+
this.state = "failed";
|
|
105
|
+
await this.closeDatabase();
|
|
106
|
+
throw new Error("AgentFS workspace initialization failed; no host fallback is available.");
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
assertOpening() {
|
|
110
|
+
if (this.state !== "opening")
|
|
111
|
+
throw new Error("AgentFS workspace was closed during initialization.");
|
|
112
|
+
}
|
|
113
|
+
closeDatabase() {
|
|
114
|
+
this.databaseClosing ??= this.database?.close() ?? Promise.resolve();
|
|
115
|
+
return this.databaseClosing;
|
|
116
|
+
}
|
|
117
|
+
run(signal, callback) {
|
|
118
|
+
const operation = this.tail.then(async () => {
|
|
119
|
+
if (this.state !== "ready" || !this.filesystem)
|
|
120
|
+
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();
|
|
126
|
+
const check = () => {
|
|
127
|
+
if (!valid || combined.aborted || this.state !== "ready")
|
|
128
|
+
throw new Error("AgentFS operation aborted.");
|
|
129
|
+
};
|
|
130
|
+
// Track the actual database operations, not just the interpreter promise. Cancellation may
|
|
131
|
+
// revoke an interpreter while a database operation is still completing. Drain before close.
|
|
132
|
+
const guarded = new Proxy(this.filesystem, {
|
|
133
|
+
get(target, key) {
|
|
134
|
+
const value = Reflect.get(target, key);
|
|
135
|
+
if (typeof value !== "function")
|
|
136
|
+
return value;
|
|
137
|
+
return (...args) => {
|
|
138
|
+
check();
|
|
139
|
+
const work = Promise.resolve(Reflect.apply(value, target, args)).then((result) => {
|
|
140
|
+
check();
|
|
141
|
+
return result;
|
|
142
|
+
});
|
|
143
|
+
pending.add(work);
|
|
144
|
+
void work.then(() => pending.delete(work), () => pending.delete(work));
|
|
145
|
+
return work;
|
|
146
|
+
};
|
|
147
|
+
},
|
|
148
|
+
});
|
|
149
|
+
try {
|
|
150
|
+
check();
|
|
151
|
+
const result = await callback(new VirtualFileSystem(guarded), combined);
|
|
152
|
+
check();
|
|
153
|
+
return result;
|
|
154
|
+
}
|
|
155
|
+
finally {
|
|
156
|
+
valid = false;
|
|
157
|
+
while (pending.size)
|
|
158
|
+
await Promise.allSettled([...pending]);
|
|
159
|
+
if (this.active === controller)
|
|
160
|
+
this.active = undefined;
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
this.tail = operation.catch(() => undefined);
|
|
164
|
+
return operation;
|
|
165
|
+
}
|
|
166
|
+
close() {
|
|
167
|
+
if (this.closing)
|
|
168
|
+
return this.closing;
|
|
169
|
+
this.state = "closing";
|
|
170
|
+
this.active?.abort();
|
|
171
|
+
this.closing = (async () => {
|
|
172
|
+
await this.opening?.catch(() => undefined);
|
|
173
|
+
await this.tail;
|
|
174
|
+
try {
|
|
175
|
+
await this.closeDatabase();
|
|
176
|
+
}
|
|
177
|
+
finally {
|
|
178
|
+
this.filesystem = undefined;
|
|
179
|
+
this.state = "closed";
|
|
180
|
+
}
|
|
181
|
+
})();
|
|
182
|
+
return this.closing;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Dependency security
|
|
2
|
+
|
|
3
|
+
The root manifest overrides `just-bash`'s `guarded-fetch` dependency to use its patched HTTP dependency chain.
|
|
4
|
+
The root manifest also aligns `agentfs-sdk`'s Turso database dependencies with this workspace's direct database dependency.
|
|
5
|
+
The lockfile records the selected versions.
|
|
6
|
+
These overrides apply to repository installs, not independent installs of published workspace packages.
|
|
7
|
+
Remove each override when the declared upstream dependencies resolve to compatible, patched releases without it.
|
|
8
|
+
|
|
9
|
+
## Formatter replacement
|
|
10
|
+
|
|
11
|
+
The root manifest replaces `just-bash`'s `sprintf-js` dependency with the `@lvcabral/sprintf` fork through an npm alias.
|
|
12
|
+
This removes the package flagged by [GHSA-hp3w-g68c-fv3c](https://github.com/advisories/GHSA-hp3w-g68c-fv3c) without downgrading AgentFS or suppressing audit results.
|
|
13
|
+
The [authoritative CVE record](https://cveawg.mitre.org/api/cve/CVE-2026-97058) marks this CVE as `REJECTED`; the alias is a dependency replacement, not a claim that the fork patches the rejected CVE.
|
|
14
|
+
|
|
15
|
+
Invalid precision can still raise JavaScript exceptions.
|
|
16
|
+
`just-bash` must contain those exceptions and return command failures.
|
|
17
|
+
`packages/pi-agentfs/test/formatter-compatibility.test.ts` verifies that behavior, recovery after failure, and the relevant native and formatter-backed conversions through both ESM and CommonJS entrypoints.
|
|
18
|
+
|
|
19
|
+
AgentFS does not expose `printf` or `awk` in its restricted shell.
|
|
20
|
+
`packages/pi-agentfs/test/workspace.test.ts` verifies that the reported precision inputs cannot reach either command and that the workspace remains usable after rejection.
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
# Service integration
|
|
2
|
+
|
|
3
|
+
The service authorizes a host database path, then gives one Pi session access to the files inside that database.
|
|
4
|
+
Pi AgentFS controls its four tools. The service controls every other way that data or executable code can enter the Pi process.
|
|
5
|
+
|
|
6
|
+
## Ownership and paths
|
|
7
|
+
|
|
8
|
+
The service must authenticate the user and resolve an authorized workspace before it creates the extension.
|
|
9
|
+
Do not accept a database path, extension path, or user-to-workspace mapping from model output.
|
|
10
|
+
Pass a nonempty absolute database path with no NUL characters. Create and secure its host parent directory first.
|
|
11
|
+
The package can initialize a database at that path; it does not create host directory trees.
|
|
12
|
+
|
|
13
|
+
| Value | Example | Owner |
|
|
14
|
+
| --- | --- | --- |
|
|
15
|
+
| Host database path | `/srv/agentfs/alice.db` | Trusted service or operator |
|
|
16
|
+
| Virtual file path | `/notes/today.txt` | Tool caller within the selected workspace |
|
|
17
|
+
| Pi conversation history | In-memory `SessionManager`, or service-owned storage | Service |
|
|
18
|
+
|
|
19
|
+
The database path is not the virtual root. Virtual paths resolve from `/`, independent of Pi's host cwd and the database's parent directory.
|
|
20
|
+
Parent traversal stays within the virtual path namespace. `~` and `~/` mean the virtual root; named home directories and symbolic or hard links are unsupported.
|
|
21
|
+
A missing virtual file fails; it does not cause a host filesystem lookup.
|
|
22
|
+
|
|
23
|
+
One session workspace owns one connection and a queue covering whole `read`, `write`, `edit`, and `bash` operations.
|
|
24
|
+
The queue prevents an edit or shell operation from interleaving with another operation on that workspace.
|
|
25
|
+
It does not coordinate separate workspace owners or processes. Do not open the same database concurrently through multiple sessions or processes.
|
|
26
|
+
Use distinct extension instances and database paths for users that require separate workspaces.
|
|
27
|
+
|
|
28
|
+
The implemented data path does not authorize users or restrict the surrounding process:
|
|
29
|
+
|
|
30
|
+
```mermaid
|
|
31
|
+
flowchart LR
|
|
32
|
+
U[Authenticated user] --> S[Service authorization]
|
|
33
|
+
S --> P[Approved absolute database path]
|
|
34
|
+
P --> E[Session-owned extension]
|
|
35
|
+
E --> T[read / write / edit]
|
|
36
|
+
E --> B[just-bash tool]
|
|
37
|
+
T --> W[Shared AgentFS connection]
|
|
38
|
+
B --> W
|
|
39
|
+
W --> D[Selected database]
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## CLI and RPC startup
|
|
43
|
+
|
|
44
|
+
Load the package with `-e` and pass `--agentfs-path` on the same invocation.
|
|
45
|
+
For example, from a checkout after `npm install` and the root `npm run build`:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
pi --mode rpc --no-extensions -e ./packages/pi-agentfs \
|
|
49
|
+
--no-skills --no-prompt-templates --no-themes --no-context-files --no-approve \
|
|
50
|
+
--no-session --tools read,write,edit,bash \
|
|
51
|
+
--agentfs-path /srv/agentfs/alice.db
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Omit `--mode rpc` for interactive use. After publication, `-e npm:@narumitw/pi-agentfs` can replace the local package path.
|
|
55
|
+
The Pi entrypoint is source TypeScript. SDK imports instead require the package build.
|
|
56
|
+
|
|
57
|
+
These options do not make the CLI a hardened service. Pi can still use personal `SYSTEM.md`, `APPEND_SYSTEM.md`, credentials, model configuration, and other host features.
|
|
58
|
+
Use a controlled agent directory and process environment, and reject unapproved startup inputs.
|
|
59
|
+
Do not pass host `@file` attachments or arbitrary system-prompt paths. RPC clients must also restrict session switching, import/export, and other host-facing commands.
|
|
60
|
+
|
|
61
|
+
The absent flag leaves ordinary Pi behavior unchanged. An empty or relative flag value is invalid, not a request for disabled mode.
|
|
62
|
+
When workspace mode is requested, replacements are installed before database initialization; loading, failed, and closed workspaces reject calls without a host fallback.
|
|
63
|
+
Pi can catch extension startup errors and keep running. A process that is alive or a successful RPC state response is not proof that the workspace opened.
|
|
64
|
+
Treat startup diagnostics and RPC `extension_error` records as service failures; do not admit requests on an unverified session.
|
|
65
|
+
For an explicit programmatic readiness barrier, use the SDK factory below.
|
|
66
|
+
|
|
67
|
+
The extension rejects `user_bash`, including interactive `!` and `!!` and the RPC `bash` command path.
|
|
68
|
+
These are not aliases for the AgentFS `bash` tool.
|
|
69
|
+
|
|
70
|
+
## SDK startup and shutdown
|
|
71
|
+
|
|
72
|
+
Import the named factory from the package root:
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
import { createAgentfsExtension } from "@narumitw/pi-agentfs";
|
|
76
|
+
|
|
77
|
+
const extension = createAgentfsExtension({ path: approvedDatabasePath });
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Its interface is:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
createAgentfsExtension(options: { path: string }): ExtensionFactory & {
|
|
84
|
+
ready(sessionManager: object): Promise<void>;
|
|
85
|
+
};
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
The factory validates the explicit path and registers replacements without opening the database during factory loading.
|
|
89
|
+
Opening starts at `session_start`, emitted by `session.bindExtensions()`.
|
|
90
|
+
Readiness is keyed by the owning `sessionManager`, not by `ctx.ui`, which can be shared in headless mode.
|
|
91
|
+
|
|
92
|
+
Follow the full runnable [service example](../examples/service.ts). It makes no model requests and uses no API key.
|
|
93
|
+
From the repository root, with an approved path whose parent already exists:
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
npm run build
|
|
97
|
+
node --experimental-strip-types packages/pi-agentfs/examples/service.ts /srv/agentfs/alice.db
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
The sample creates the session, checks readiness and tool ownership, and shuts it down without modifying virtual files.
|
|
101
|
+
A successful exit means the startup checks passed, not that a real deployment or provider integration was verified.
|
|
102
|
+
|
|
103
|
+
The sample has these required boundaries:
|
|
104
|
+
|
|
105
|
+
1. Use in-memory settings, credentials, model catalog storage, and `SessionManager`; disable model catalog network refresh and disk model configuration.
|
|
106
|
+
2. Disable discovery of extensions, skills, templates, themes, and context files. Supply the AgentFS factory explicitly.
|
|
107
|
+
- Set a literal `systemPrompt` and `appendSystemPrompt: []`; `noContextFiles` alone does not suppress `SYSTEM.md` and `APPEND_SYSTEM.md`.
|
|
108
|
+
3. Use the exact tool allowlist `['read', 'write', 'edit', 'bash']`, not additive selections or the default tool list.
|
|
109
|
+
4. Reject resource-loader errors and session loader errors, collect lifecycle errors through `bindExtensions({ onError })`, and await `extension.ready(session.sessionManager)` after binding.
|
|
110
|
+
5. Check the active tool names, callable tool names, all registered tools, and that every implementation is the registered AgentFS replacement before admitting service requests.
|
|
111
|
+
6. On failure or completion, stop active work, await `session_shutdown`, then dispose the session.
|
|
112
|
+
- In the tested Pi runtime, `session.dispose()` alone does not emit the extension shutdown event.
|
|
113
|
+
- Shutdown closes the connection after active database work drains; it does not delete the database.
|
|
114
|
+
|
|
115
|
+
The sequence keeps an unready session out of the service request path:
|
|
116
|
+
|
|
117
|
+
```mermaid
|
|
118
|
+
sequenceDiagram
|
|
119
|
+
participant S as Trusted service
|
|
120
|
+
participant L as Resource loader
|
|
121
|
+
participant P as Pi session
|
|
122
|
+
participant E as AgentFS extension
|
|
123
|
+
S->>L: Load only supplied factory
|
|
124
|
+
L-->>S: Extensions and loader errors
|
|
125
|
+
S->>P: Create with exact tool allowlist
|
|
126
|
+
S->>P: bindExtensions with onError
|
|
127
|
+
P->>E: session_start
|
|
128
|
+
E->>E: Open approved database
|
|
129
|
+
S->>E: ready(sessionManager)
|
|
130
|
+
alt Initialization and checks succeed
|
|
131
|
+
E-->>S: Ready
|
|
132
|
+
S->>S: Admit authorized requests
|
|
133
|
+
else Initialization or checks fail
|
|
134
|
+
E-->>S: Reject or lifecycle error
|
|
135
|
+
S->>S: Refuse requests without host fallback
|
|
136
|
+
end
|
|
137
|
+
S->>P: Abort and await session_shutdown
|
|
138
|
+
P->>E: Close workspace and drain operations
|
|
139
|
+
S->>P: dispose
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
A service must retain lifecycle error handling after startup and stop admitting work if the session fails or closes.
|
|
143
|
+
For session replacement or reload, repeat authorization and startup checks for the new owner; do not reuse an old readiness result or extension context.
|
|
144
|
+
|
|
145
|
+
Never route a request to `session.executeBash()`. This direct SDK method can bypass `user_bash` and execute on the host.
|
|
146
|
+
Do not give an untrusted client access to the raw SDK session or allow it to change tools, load extensions, or select arbitrary database paths.
|
|
147
|
+
|
|
148
|
+
## Shell contract and bounds
|
|
149
|
+
|
|
150
|
+
The `bash` tool uses `just-bash` with the same AgentFS connection as the file tools.
|
|
151
|
+
It starts a fresh interpreter at `/` for every call, with `HOME=/` and `PATH=/usr/bin:/bin` instead of `process.env`.
|
|
152
|
+
`PATH` is interpreter configuration, not permission to launch host executables.
|
|
153
|
+
Files persist between calls. Changes to cwd, exported variables, shell functions, and other interpreter state do not.
|
|
154
|
+
|
|
155
|
+
The command allowlist is:
|
|
156
|
+
|
|
157
|
+
```text
|
|
158
|
+
cat cp cut echo false find grep head ls mkdir mv pwd rm sed seq sleep
|
|
159
|
+
sort tail tee tr true uniq wc
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Shell syntax includes pipelines and redirection, but this is not a promise of full GNU Bash or GNU utility compatibility.
|
|
163
|
+
Unsupported commands fail. Network commands, host shell processes, package managers, JavaScript/Python executors, and custom host commands are not enabled.
|
|
164
|
+
|
|
165
|
+
The fixed limits are defined by the tool implementation. They are not service configuration settings.
|
|
166
|
+
|
|
167
|
+
| Limit | Bound |
|
|
168
|
+
| --- | --- |
|
|
169
|
+
| Shell timeout | Default and maximum 30 seconds |
|
|
170
|
+
| Command source | 64 KiB |
|
|
171
|
+
| Interpreter command count | 10,000 |
|
|
172
|
+
| Interpreter loop iterations | 1,000 |
|
|
173
|
+
| Interpreter output | 1 MiB |
|
|
174
|
+
| Model-visible output | At most 50 KiB or 2,000 lines, including truncation notices |
|
|
175
|
+
|
|
176
|
+
Output beyond the tool bound is truncated; full shell output is not saved to a host temporary file or retained as a separate workspace log.
|
|
177
|
+
A nonzero exit, timeout, cancellation, or interpreter limit produces a tool failure, not host execution.
|
|
178
|
+
Cancellation and shutdown stop further workspace operations, but file changes that completed before failure are not rolled back.
|
|
179
|
+
These bounds are not database storage quotas or an operating-system CPU/memory isolation guarantee.
|
|
180
|
+
|
|
181
|
+
## Text reader compatibility
|
|
182
|
+
|
|
183
|
+
The `read` tool implements the text-only path and uses Pi's public truncation helpers.
|
|
184
|
+
Pi's complete reader probes host paths before it calls injected read operations, so reusing that complete reader would break the no-host-access requirement.
|
|
185
|
+
The extension-owned reader avoids those probes and provides line offsets, limits, continuation notices, and bounded text output through AgentFS only.
|
|
186
|
+
It does not provide Pi's image-reading behavior.
|
|
187
|
+
`write` and `edit` retain Pi's operations-based text behavior with virtual filesystem adapters.
|
|
188
|
+
The adapters pin the original normalized virtual path, so Pi's host-oriented filename transformations cannot select another file.
|
|
189
|
+
Unicode spaces, `@` prefixes, and file-URL-looking names are literal virtual filenames; no host-dependent filename guesses are made.
|
|
190
|
+
|
|
191
|
+
Tool rendering intentionally omits host-file hyperlinks and speculative edit previews because Pi's default edit preview reads host files.
|
|
192
|
+
The renderers use only supplied arguments, results, and completed edit diffs. They remove terminal controls from display copies without changing stored filenames or tool payloads.
|
|
193
|
+
Display rows use cell-aware hard wrapping. Spaces and blank lines remain in the sanitized text; a grapheme wider than the available row is shown as `?` instead of overflowing the row.
|
|
194
|
+
Read paging accepts positive integer offsets and limits, and reserves space for continuation notices within the complete output bound.
|
|
195
|
+
|
|
196
|
+
## Deployment and publication handoff
|
|
197
|
+
|
|
198
|
+
The actual chatbot service and its permission system have not been inspected or deployed as part of this package.
|
|
199
|
+
Before claiming end-to-end user isolation, the service owner must verify authentication, authorization, database mapping, one-owner database access, session history, attachments, logs, exports, backups, and retention.
|
|
200
|
+
Also verify that no alternate tool, MCP server, extension, auto-loaded resource, direct SDK method, or RPC route exposes host data or another user's resources.
|
|
201
|
+
Use an operating-system isolation boundary when the threat model requires one; this extension is not that boundary.
|
|
202
|
+
|
|
203
|
+
The npm name's availability, publication authorization, and trusted publishing setup remain unverified.
|
|
204
|
+
Local package preparation is not approval to publish, change visibility, create release tags, or deploy a service.
|
|
205
|
+
Review the pinned dependency tree and current advisories before deployment; excluding a shell command does not remove its dependency from an installed package.
|
|
206
|
+
The initial dependency audit reports advisories through `guarded-fetch`/`undici` and `sprintf-js`; their network and `printf` command paths are not enabled and have rejection tests.
|
|
207
|
+
These packages remain installed dependencies, not audited-safe code. The repository denies install scripts for optional native compression libraries, which this command allowlist does not use.
|
|
208
|
+
Do not deploy this MVP as a hostile-code or multi-tenant process security boundary.
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* No-model SDK startup check. The service must authorize this database path first.
|
|
3
|
+
* From the repository root, run npm run build, then run:
|
|
4
|
+
* node --experimental-strip-types packages/pi-agentfs/examples/service.ts /approved/absolute/workspace.db
|
|
5
|
+
* The database parent must already exist. This does not implement authentication.
|
|
6
|
+
*/
|
|
7
|
+
import assert from "node:assert/strict";
|
|
8
|
+
import { InMemoryCredentialStore, InMemoryModelsStore } from "@earendil-works/pi-ai";
|
|
9
|
+
import {
|
|
10
|
+
createAgentSession,
|
|
11
|
+
DefaultResourceLoader,
|
|
12
|
+
type ExtensionError,
|
|
13
|
+
ModelRuntime,
|
|
14
|
+
SessionManager,
|
|
15
|
+
SettingsManager,
|
|
16
|
+
} from "@earendil-works/pi-coding-agent";
|
|
17
|
+
import { createAgentfsExtension } from "@narumitw/pi-agentfs";
|
|
18
|
+
|
|
19
|
+
const approvedPath = process.argv[2];
|
|
20
|
+
if (process.argv.length !== 3 || !approvedPath) {
|
|
21
|
+
throw new Error("Pass one service-approved absolute database path with an existing parent directory.");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const expectedTools = ["read", "write", "edit", "bash"];
|
|
25
|
+
const extension = createAgentfsExtension({ path: approvedPath });
|
|
26
|
+
const settingsManager = SettingsManager.inMemory({
|
|
27
|
+
defaultTools: expectedTools,
|
|
28
|
+
enableSkillCommands: false,
|
|
29
|
+
cacheWarming: "off",
|
|
30
|
+
compaction: { enabled: false },
|
|
31
|
+
retry: { enabled: false },
|
|
32
|
+
});
|
|
33
|
+
const modelRuntime = await ModelRuntime.create({
|
|
34
|
+
credentials: new InMemoryCredentialStore(),
|
|
35
|
+
modelsStore: new InMemoryModelsStore(),
|
|
36
|
+
modelsPath: null,
|
|
37
|
+
allowModelNetwork: false,
|
|
38
|
+
refreshOnCreate: false,
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
// This cwd is only Pi metadata. It is not a host filesystem restriction.
|
|
42
|
+
const cwd = "/";
|
|
43
|
+
const resourceLoader = new DefaultResourceLoader({
|
|
44
|
+
cwd,
|
|
45
|
+
agentDir: "/",
|
|
46
|
+
settingsManager,
|
|
47
|
+
extensionFactories: [extension],
|
|
48
|
+
noExtensions: true,
|
|
49
|
+
noSkills: true,
|
|
50
|
+
noPromptTemplates: true,
|
|
51
|
+
noThemes: true,
|
|
52
|
+
noContextFiles: true,
|
|
53
|
+
// noContextFiles does not disable SYSTEM.md or APPEND_SYSTEM.md discovery.
|
|
54
|
+
systemPrompt: "Use only the AgentFS workspace tools. All tool paths are virtual paths.",
|
|
55
|
+
appendSystemPrompt: [],
|
|
56
|
+
});
|
|
57
|
+
await resourceLoader.reload();
|
|
58
|
+
const loaded = resourceLoader.getExtensions();
|
|
59
|
+
if (loaded.errors.length) throw new Error("AgentFS extension loading failed; session creation refused.");
|
|
60
|
+
assert.equal(loaded.extensions.length, 1, "Only the supplied factory may load");
|
|
61
|
+
const registered = loaded.extensions[0];
|
|
62
|
+
assert.ok(registered);
|
|
63
|
+
assert.deepEqual([...registered.tools.keys()].sort(), [...expectedTools].sort());
|
|
64
|
+
assert.deepEqual(resourceLoader.getSkills().skills, []);
|
|
65
|
+
assert.deepEqual(resourceLoader.getPrompts().prompts, []);
|
|
66
|
+
assert.deepEqual(resourceLoader.getThemes().themes, []);
|
|
67
|
+
assert.deepEqual(resourceLoader.getAgentsFiles().agentsFiles, []);
|
|
68
|
+
|
|
69
|
+
const { session, extensionsResult } = await createAgentSession({
|
|
70
|
+
cwd,
|
|
71
|
+
agentDir: "/",
|
|
72
|
+
modelRuntime,
|
|
73
|
+
resourceLoader,
|
|
74
|
+
settingsManager,
|
|
75
|
+
sessionManager: SessionManager.inMemory(cwd),
|
|
76
|
+
tools: ["read", "write", "edit", "bash"],
|
|
77
|
+
});
|
|
78
|
+
const errors: ExtensionError[] = [];
|
|
79
|
+
async function closeSession(): Promise<void> {
|
|
80
|
+
const previousErrors = errors.length;
|
|
81
|
+
try {
|
|
82
|
+
try {
|
|
83
|
+
await session.abort();
|
|
84
|
+
} finally {
|
|
85
|
+
// In the tested Pi runtime dispose() alone does not emit session_shutdown.
|
|
86
|
+
await session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" });
|
|
87
|
+
}
|
|
88
|
+
} finally {
|
|
89
|
+
session.dispose();
|
|
90
|
+
}
|
|
91
|
+
if (errors.length !== previousErrors) throw new Error("AgentFS workspace shutdown failed.");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
try {
|
|
95
|
+
if (extensionsResult.errors.length) throw new Error("Session extension loading failed.");
|
|
96
|
+
await session.bindExtensions({
|
|
97
|
+
mode: "print",
|
|
98
|
+
onError: (error) => errors.push(error),
|
|
99
|
+
});
|
|
100
|
+
// Pi can catch session_start failures. A resolved bindExtensions() is not readiness.
|
|
101
|
+
await extension.ready(session.sessionManager);
|
|
102
|
+
if (errors.length) throw new Error("AgentFS extension startup failed.");
|
|
103
|
+
|
|
104
|
+
// Check declarations, nested-tool reach, registry contents, and replacement ownership.
|
|
105
|
+
for (const names of [
|
|
106
|
+
session.getActiveToolNames(),
|
|
107
|
+
session.getCallableToolNames(),
|
|
108
|
+
session.getAllTools().map((tool) => tool.name),
|
|
109
|
+
]) {
|
|
110
|
+
assert.deepEqual([...names].sort(), [...expectedTools].sort());
|
|
111
|
+
}
|
|
112
|
+
for (const name of expectedTools) {
|
|
113
|
+
assert.equal(session.getToolDefinition(name), registered.tools.get(name)?.definition);
|
|
114
|
+
}
|
|
115
|
+
// Admit service requests only here. This sample makes no prompt or model calls.
|
|
116
|
+
} finally {
|
|
117
|
+
await closeSession();
|
|
118
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@narumitw/pi-agentfs",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "AgentFS virtual file workspace and restricted just-bash tools for Pi.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"pi-package",
|
|
9
|
+
"pi-extension",
|
|
10
|
+
"agentfs",
|
|
11
|
+
"workspace",
|
|
12
|
+
"just-bash"
|
|
13
|
+
],
|
|
14
|
+
"files": [
|
|
15
|
+
"src",
|
|
16
|
+
"dist",
|
|
17
|
+
"docs",
|
|
18
|
+
"examples",
|
|
19
|
+
"README.md",
|
|
20
|
+
"LICENSE"
|
|
21
|
+
],
|
|
22
|
+
"exports": {
|
|
23
|
+
".": {
|
|
24
|
+
"types": "./dist/factory.d.ts",
|
|
25
|
+
"import": "./dist/factory.js"
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"pi": {
|
|
29
|
+
"extensions": [
|
|
30
|
+
"./src/index.ts"
|
|
31
|
+
]
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "tsc -p tsconfig.build.json",
|
|
35
|
+
"prepack": "npm run build",
|
|
36
|
+
"typecheck": "tsc --noEmit"
|
|
37
|
+
},
|
|
38
|
+
"engines": {
|
|
39
|
+
"node": ">=22.19.0"
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"@narumitw/pi-tui-kit": "^0.66.0",
|
|
43
|
+
"@tursodatabase/database": "0.8.3",
|
|
44
|
+
"agentfs-sdk": "0.6.4",
|
|
45
|
+
"just-bash": "3.6.0"
|
|
46
|
+
},
|
|
47
|
+
"peerDependencies": {
|
|
48
|
+
"@earendil-works/pi-ai": "*",
|
|
49
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
50
|
+
"@earendil-works/pi-tui": "*",
|
|
51
|
+
"typebox": "*"
|
|
52
|
+
},
|
|
53
|
+
"repository": {
|
|
54
|
+
"type": "git",
|
|
55
|
+
"url": "https://github.com/narumiruna/pi-extensions",
|
|
56
|
+
"directory": "packages/pi-agentfs"
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { installAgentfsLifecycle } from "./factory.js";
|
|
3
|
+
|
|
4
|
+
export default function agentfsExtension(pi: ExtensionAPI): void {
|
|
5
|
+
pi.registerFlag("agentfs-path", {
|
|
6
|
+
type: "string",
|
|
7
|
+
description: "Enable AgentFS with an absolute database path (blocks ! and !! host commands)",
|
|
8
|
+
});
|
|
9
|
+
installAgentfsLifecycle(pi, new WeakMap(), () => pi.getFlag("agentfs-path"), false);
|
|
10
|
+
}
|