Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 45 additions & 101 deletions bun.lock

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion esbuild.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ const buildConfig = {
},
bundle: true,
minify: true,
// WebView loads this as UTF-8; avoid expanding Unicode provider data into escapes.
charset: "utf8",
platform: "browser",
target: ["chrome90"],
format: "iife",
Expand Down Expand Up @@ -121,7 +123,7 @@ const buildConfig = {
`Portable bundle has external runtime imports: ${externalImports.map((entry) => entry.path).join(", ")}`,
);
}
// Pi 0.85.1 adds durable lane execution and updated provider SDKs (~2.28 MB).
// Keep the agent and provider SDKs within the mobile bundle budget.
if ((output?.bytes ?? 0) > 2_400_000) {
throw new Error(`AI bundle exceeds the 2.4 MB mobile budget: ${output.bytes} bytes`);
}
Expand Down
1,645 changes: 1,158 additions & 487 deletions package-lock.json

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@
"@codemirror/merge": "^6.12.2",
"@codemirror/state": "^6.7.1",
"@codemirror/view": "^6.43.9",
"@earendil-works/pi-agent-core": "0.85.1",
"@earendil-works/pi-ai": "0.85.1",
"@earendil-works/pi-agent-core": "0.86.1",
"@earendil-works/pi-ai": "0.86.1",
"acode-plugin-types": "^1.12.9",
"dompurify": "^3.4.13",
"lucide-preact": "^1.32.0",
Expand Down
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ A coding agent that runs inside [Acode](https://acode.app) as an editor tab. It

## Built on Pi

This is not a from-scratch agent. The model loop, providers, sessions, skills, compaction, and tool calling come from [Pi](https://github.com/earendil-works/pi) (`@earendil-works/pi-agent-core` and `@earendil-works/pi-ai` 0.85.1). This plugin is the Acode/Android host: editor UI, workspace sandbox, approvals, and anything that has to work in a WebView without Node.
This is not a from-scratch agent. The model loop, providers, sessions, skills, compaction, and tool calling come from [Pi](https://github.com/earendil-works/pi) (`@earendil-works/pi-agent-core` and `@earendil-works/pi-ai` 0.86.1). This plugin is the Acode/Android host: editor UI, workspace sandbox, approvals, and anything that has to work in a WebView without Node.

If you already use Pi on a desktop, the same ideas apply here:

Expand Down
5 changes: 5 additions & 0 deletions src/platform/sessionFileSystem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
type FileSystem,
type Result,
} from "@earendil-works/pi-agent-core";
import { openCordovaSessionReader } from "./sessionLineReader";

/** A private virtual path namespace; workspace tools never receive this adapter. */
export class SessionFileSystem implements FileSystem {
Expand All @@ -16,6 +17,7 @@ export class SessionFileSystem implements FileSystem {
rootUri: string,
private readonly fs: Acode.FS = acode.fsOperation,
private readonly append = appendWithCordova,
private readonly openReader = openCordovaSessionReader,
) {
if (!rootUri.startsWith("file:///"))
throw new Error("Session storage requires a private local file directory.");
Expand Down Expand Up @@ -62,6 +64,9 @@ export class SessionFileSystem implements FileSystem {
readTextFile(path: string, _context: Context) {
return this.#result(path, () => this.fs(this.#uri(path)).readFile("utf-8"));
}
openTextLineReader(path: string, context: Context) {
return this.#result(path, () => this.openReader(this.#uri(path), path, context));
}
readTextLines(path: string, options: { maxLines?: number } | undefined, _context: Context) {
return this.#result(path, async () =>
(await this.fs(this.#uri(path)).readFile("utf-8")).split(/\r?\n/).slice(0, options?.maxLines),
Expand Down
194 changes: 194 additions & 0 deletions src/platform/sessionLineReader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
import {
FileError,
err,
ok,
type Context,
type FileSystem,
type Result,
} from "@earendil-works/pi-agent-core";

type TextLineReader = Extract<
Awaited<ReturnType<FileSystem["openTextLineReader"]>>,
{ ok: true }
>["value"];
type TextLine = Exclude<
Extract<Awaited<ReturnType<TextLineReader["readLine"]>>, { ok: true }>["value"],
undefined
>;

const CHUNK_BYTES = 64 * 1024;

/** A byte source keeps the line decoder independent of the host filesystem. */
export type SessionByteSource = {
size: number;
read(start: number, end: number, signal: AbortSignal): Promise<ArrayBuffer>;
};

function sessionFileError(error: unknown, path: string): FileError {
if (error instanceof FileError) return error;
const code = (error as { code?: number })?.code;
return new FileError(
code === 1 ? "not_found" : code === 2 || code === 6 ? "permission_denied" : "unknown",
error instanceof Error ? error.message : String(error),
path,
);
}

/** Memory is bounded by one chunk plus the current line (which can itself be large). */
export class SessionLineReader implements TextLineReader {
#decoder = new TextDecoder();
#offset = 0;
#buffer = "";
#ended = false;
#closed = false;
#pending?: AbortController;

constructor(
private source: SessionByteSource | undefined,
private path: string,
) {}

async readLine(context: Context): Promise<Result<TextLine | undefined, FileError>> {
if (context.abortSignal?.aborted)
return err(new FileError("aborted", "Read aborted", this.path));
if (this.#closed) return err(new FileError("invalid", "Text line reader is closed", this.path));
if (this.#pending) return err(new FileError("invalid", "Read already in progress", this.path));
const pending = new AbortController();
this.#pending = pending;
const abort = () => pending.abort();
context.abortSignal?.addEventListener("abort", abort, { once: true });
try {
while (true) {
if (pending.signal.aborted) throw new FileError("aborted", "Read aborted", this.path);
const newline = this.#buffer.indexOf("\n");
if (newline !== -1) {
const text = this.#buffer.slice(0, newline);
this.#buffer = this.#buffer.slice(newline + 1);
return ok({ text, terminated: true });
}
if (this.#ended) {
if (!this.#buffer) return ok(undefined);
const text = this.#buffer;
this.#buffer = "";
return ok({ text, terminated: false });
}
const source = this.source!;
if (this.#offset >= source.size) {
this.#buffer += this.#decoder.decode();
this.#ended = true;
continue;
}
const end = Math.min(this.#offset + CHUNK_BYTES, source.size);
const bytes = await source.read(this.#offset, end, pending.signal);
if (pending.signal.aborted) throw new FileError("aborted", "Read aborted", this.path);
if (!bytes.byteLength || bytes.byteLength > end - this.#offset)
throw new FileError("unknown", "Invalid session chunk length", this.path);
// Do not advance the cursor or decoder after cancellation; a retry reads the same bytes.
this.#offset += bytes.byteLength;
this.#buffer += this.#decoder.decode(bytes, { stream: true });
}
} catch (error) {
return err(sessionFileError(error, this.path));
} finally {
context.abortSignal?.removeEventListener("abort", abort);
this.#pending = undefined;
}
}

async close(_context: Context): Promise<void> {
this.#closed = true;
this.#pending?.abort();
this.#buffer = "";
this.source = undefined;
this.#decoder = new TextDecoder();
}
}

/** Use Cordova's FileReader, not Blob.arrayBuffer(): Cordova File slices are native file references. */
export async function openCordovaSessionReader(
uri: string,
path: string,
context: Context,
): Promise<TextLineReader> {
const file = await new Promise<File>((resolve, reject) => {
const signal = context.abortSignal;
const abort = () => finish(new FileError("aborted", "Read aborted", path));
const finish = (error?: unknown, file?: File) => {
signal?.removeEventListener("abort", abort);
if (error !== undefined) reject(error);
else resolve(file!);
};
if (signal?.aborted) {
abort();
return;
}
signal?.addEventListener("abort", abort, { once: true });
const host = globalThis as unknown as {
resolveLocalFileSystemURL?: (
uri: string,
success: (entry: {
file(success: (file: File) => void, failure: (error: unknown) => void): void;
}) => void,
failure: (error: unknown) => void,
) => void;
};
try {
if (!host.resolveLocalFileSystemURL) throw new Error("Cordova file reader is unavailable");
host.resolveLocalFileSystemURL(
uri,
(entry) => {
if (signal?.aborted) return;
try {
entry.file(
(file) => finish(undefined, file),
(error) => finish(error),
);
} catch (error) {
finish(error);
}
},
(error) => finish(error),
);
} catch (error) {
finish(error);
}
});
return new SessionLineReader(
{
size: file.size,
read: (start, end, signal) =>
new Promise<ArrayBuffer>((resolve, reject) => {
const reader = new FileReader();
const finish = (error?: unknown) => {
signal.removeEventListener("abort", abort);
reader.onload = reader.onerror = reader.onabort = null;
if (error !== undefined) reject(error);
else if (reader.result instanceof ArrayBuffer) resolve(reader.result);
else reject(new Error("Cordova returned a non-binary session chunk"));
};
const abort = () => {
finish(new FileError("aborted", "Read aborted", path));
try {
reader.abort();
} catch {
// Native cleanup is best-effort; the pending read is already rejected.
}
};
reader.onload = () => finish();
reader.onerror = () => finish(reader.error ?? new Error("Session read failed"));
reader.onabort = () => finish(new FileError("aborted", "Read aborted", path));
if (signal.aborted) {
abort();
return;
}
signal.addEventListener("abort", abort, { once: true });
try {
reader.readAsArrayBuffer(file.slice(start, end));
} catch (error) {
finish(error);
}
}),
},
path,
);
}
21 changes: 20 additions & 1 deletion tests/sessionFileSystem.fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";
import { dirname, basename, join } from "node:path";
import { tmpdir } from "node:os";
import { SessionFileSystem } from "../src/platform/sessionFileSystem";
import { SessionLineReader } from "../src/platform/sessionLineReader";

export async function sessionFileSystemFixture() {
const root = await fs.mkdtemp(join(tmpdir(), "acode-session-"));
Expand Down Expand Up @@ -68,7 +69,25 @@ export async function sessionFileSystemFixture() {
await fs.appendFile(native(uri), content);
};
return {
adapter: new SessionFileSystem(uri, host, append),
adapter: new SessionFileSystem(uri, host, append, async (uri, path) => {
const size = (await fs.stat(native(uri))).size;
return new SessionLineReader(
{
size,
read: async (start, end) => {
const handle = await fs.open(native(uri), "r");
try {
const bytes = new Uint8Array(end - start);
const { bytesRead } = await handle.read(bytes, 0, bytes.length, start);
return bytes.buffer.slice(0, bytesRead);
} finally {
await handle.close();
}
},
},
path,
);
}),
host,
uri,
root,
Expand Down
11 changes: 11 additions & 0 deletions tests/sessionFileSystem.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,14 @@ test.each([
modifiedDate === "invalid" || modifiedDate === null ? 0 : 1700000000000,
);
});

test("line reader rejects escaping paths before opening the native file", async () => {
const { host, uri } = await setup();
const open = vi.fn();
const adapter = new SessionFileSystem(uri, host, undefined, open);
expect(await adapter.openTextLineReader("../../secret", context)).toMatchObject({
ok: false,
error: { code: "permission_denied" },
});
expect(open).not.toHaveBeenCalled();
});
Loading
Loading