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
42 changes: 24 additions & 18 deletions packages/server/build-pi-process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,24 +46,30 @@ NodeRuntime.runMain(
yield* Effect.die(new Error(`Building pi-process failed: ${piProcessExit}`));
}

const workerExit = yield* spawner.exitCode(
ChildProcess.make(
process.execPath,
[
"build",
path.join(piDir, "dist/utils/image-resize-worker.js"),
"--target",
"bun",
"--define",
"PI_BUNDLED_NODE=true",
"--outfile",
path.join(outDir, "image-resize-worker.js"),
],
{ stdout: "inherit", stderr: "inherit" },
),
);
if (workerExit !== 0) {
yield* Effect.die(new Error(`Building image-resize-worker failed: ${workerExit}`));
// Pi resolves bundled workers beside the bundle (PI_BUNDLED_NODE).
for (const [entry, outfile] of [
["dist/utils/image-resize-worker.js", "image-resize-worker.js"],
["dist/extensions/codemode/worker.js", "codemode-worker.js"],
] as const) {
const workerExit = yield* spawner.exitCode(
ChildProcess.make(
process.execPath,
[
"build",
path.join(piDir, entry),
"--target",
"bun",
"--define",
"PI_BUNDLED_NODE=true",
"--outfile",
path.join(outDir, outfile),
],
{ stdout: "inherit", stderr: "inherit" },
),
);
if (workerExit !== 0) {
yield* Effect.die(new Error(`Building ${outfile} failed: ${workerExit}`));
}
}

// Keep Pi's package layout so getPackageDir(), documentation and HTML export
Expand Down
106 changes: 106 additions & 0 deletions packages/server/test/harness/pi/rpc-bundle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,112 @@ layer(NodeServices.layer, { excludeTestServices: true })("Pi RPC bundle", (it) =
);
}

it.effect("runs codemode scripts in the bundled sandbox outside the bundle directory", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "pie-rpc-codemode-" });
const runtimeDir = path.join(cwd, "runtime");
yield* fs.copy(path.dirname(bundle), runtimeDir);
yield* fs.copy(builtIsland, path.join(cwd, "fff"));
yield* fs.makeDirectory(path.join(cwd, "extensions"));
// codemode is registered inactive; MCP activates it in practice.
yield* fs.writeFileString(
path.join(cwd, "settings.json"),
JSON.stringify({ defaultTools: ["read", "codemode"] }),
);
// Calls codemode on the first request, then answers with text.
yield* fs.writeFileString(
path.join(cwd, "extensions/codemode-provider.ts"),
`import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
export default function (pi) {
pi.registerProvider("codemode-test", {
baseUrl: "http://127.0.0.1:1",
apiKey: "test-only",
api: "codemode-test",
models: [{ id: "model", name: "Codemode test", reasoning: false, input: ["text"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 200000, maxTokens: 4096 }],
streamSimple(model, context) {
const stream = createAssistantMessageEventStream();
const call = context.messages.at(-1)?.role === "user";
const output = { role: "assistant", content: [], api: model.api,
provider: model.provider, model: model.id,
usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
stopReason: call ? "toolUse" : "stop", timestamp: Date.now() };
stream.push({ type: "start", partial: output });
if (call) {
const toolCall = { type: "toolCall", id: "call-1", name: "codemode",
arguments: { code: "return 6 * 7" } };
output.content.push(toolCall);
stream.push({ type: "toolcall_start", contentIndex: 0, partial: output });
stream.push({ type: "toolcall_end", contentIndex: 0, toolCall, partial: output });
} else {
output.content.push({ type: "text", text: "done" });
stream.push({ type: "text_start", contentIndex: 0, partial: output });
stream.push({ type: "text_end", contentIndex: 0, content: "done", partial: output });
}
stream.push({ type: "done", reason: output.stopReason, message: output });
stream.end();
return stream;
},
});
}`,
);
const turnEnded = yield* Deferred.make<void>();
const child = yield* spawner.spawn(
ChildProcess.make(
"bun",
[
"--no-install",
path.join(runtimeDir, "pi-process.js"),
"--mode",
"rpc",
"--provider",
"codemode-test",
"--model",
"model",
],
{
cwd,
env: { PATH: process.env.PATH, HOME: cwd, PI_CODING_AGENT_DIR: cwd, PI_OFFLINE: "1" },
// Keep stdin open until the turn finishes; EOF shuts the RPC child down.
stdin: Stream.make('{"type":"prompt","message":"run"}\n').pipe(
Stream.concat(Stream.fromEffect(Deferred.await(turnEnded)).pipe(Stream.drain)),
Stream.encodeText,
),
},
),
);
const lines = yield* child.stdout.pipe(
Stream.decodeText(),
Stream.splitLines,
Stream.tap((line) =>
line.includes('"type":"agent_end"')
? Deferred.succeed(turnEnded, undefined)
: Effect.void,
),
Stream.takeUntil((line) => line.includes('"type":"agent_end"')),
Stream.runCollect,
);
const result = Array.from(lines)
.map(
(line) =>
JSON.parse(line) as {
type?: string;
toolName?: string;
isError?: boolean;
result?: { content: Array<{ text?: string }> };
},
)
.find((event) => event.type === "tool_execution_end" && event.toolName === "codemode");
assert.ok(result, lines.join("\n"));
assert.equal(result.isError, false, JSON.stringify(result));
assert.equal(result.result?.content.at(-1)?.text, "42");
}),
);

it.effect("routes queued RPC input through extension input handlers", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
Expand Down
21 changes: 21 additions & 0 deletions patches/@earendil-works__pi-coding-agent@1.0.2.patch
Original file line number Diff line number Diff line change
@@ -1,3 +1,24 @@
diff --git a/dist/bun/runtime-setup.js b/dist/bun/runtime-setup.js
index 282e8d3d54897a7c032616542596be5221937d73..718f7067e5432179faaec935fca6971f9a7dde0a 100644
--- a/dist/bun/runtime-setup.js
+++ b/dist/bun/runtime-setup.js
@@ -1,6 +1,7 @@
import { bedrockProviderModule } from "@earendil-works/pi-ai/bedrock-provider";
import { registerBunOAuthFlows } from "@earendil-works/pi-ai/bun-oauth";
import { setBedrockProviderModule } from "@earendil-works/pi-ai/compat";
+import { fileURLToPath } from "node:url";
// Bun loads .wasm imports as files: embedded in compiled executables, evaluating to a readable path.
import quickjsWasmPath from "quickjs-wasi/quickjs.wasm";
import { APP_NAME, setEmbeddedQuickJSWasmPath } from "../config.js";
@@ -8,5 +9,6 @@ process.title = APP_NAME;
process.emitWarning = (() => { });
registerBunOAuthFlows();
setBedrockProviderModule(bedrockProviderModule);
-setEmbeddedQuickJSWasmPath(quickjsWasmPath);
+// A non-compiled `bun build --outdir` bundle gets a path relative to the bundle, not the cwd.
+setEmbeddedQuickJSWasmPath(quickjsWasmPath.startsWith(".") ? fileURLToPath(new URL(quickjsWasmPath, import.meta.url)) : quickjsWasmPath);
//# sourceMappingURL=runtime-setup.js.map
\ No newline at end of file
diff --git a/dist/core/agent-session.js b/dist/core/agent-session.js
index 33338d518743ba2fd4ee2d710c5496a6ddcd1856..5cafd057a0fae8632caa4fae539917f199005500 100644
--- a/dist/core/agent-session.js
Expand Down
18 changes: 9 additions & 9 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading