poe-code 3.0.202 → 3.0.204

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.
Files changed (119) hide show
  1. package/dist/cli/commands/braintrust.d.ts +3 -0
  2. package/dist/cli/commands/braintrust.js +77 -0
  3. package/dist/cli/commands/braintrust.js.map +1 -0
  4. package/dist/cli/commands/configure.d.ts +1 -0
  5. package/dist/cli/commands/configure.js +197 -0
  6. package/dist/cli/commands/configure.js.map +1 -1
  7. package/dist/cli/commands/experiment.js +51 -7
  8. package/dist/cli/commands/experiment.js.map +1 -1
  9. package/dist/cli/commands/harness.d.ts +3 -0
  10. package/dist/cli/commands/harness.js +260 -0
  11. package/dist/cli/commands/harness.js.map +1 -0
  12. package/dist/cli/commands/pipeline.js +58 -24
  13. package/dist/cli/commands/pipeline.js.map +1 -1
  14. package/dist/cli/commands/ralph.js +19 -7
  15. package/dist/cli/commands/ralph.js.map +1 -1
  16. package/dist/cli/commands/runtime/build.d.ts +7 -0
  17. package/dist/cli/commands/runtime/build.js +128 -0
  18. package/dist/cli/commands/runtime/build.js.map +1 -0
  19. package/dist/cli/commands/runtime/index.d.ts +3 -0
  20. package/dist/cli/commands/runtime/index.js +14 -0
  21. package/dist/cli/commands/runtime/index.js.map +1 -0
  22. package/dist/cli/commands/runtime/init.d.ts +7 -0
  23. package/dist/cli/commands/runtime/init.js +39 -0
  24. package/dist/cli/commands/runtime/init.js.map +1 -0
  25. package/dist/cli/commands/runtime/jobs/attach.d.ts +3 -0
  26. package/dist/cli/commands/runtime/jobs/attach.js +35 -0
  27. package/dist/cli/commands/runtime/jobs/attach.js.map +1 -0
  28. package/dist/cli/commands/runtime/jobs/index.d.ts +3 -0
  29. package/dist/cli/commands/runtime/jobs/index.js +16 -0
  30. package/dist/cli/commands/runtime/jobs/index.js.map +1 -0
  31. package/dist/cli/commands/runtime/jobs/logs.d.ts +3 -0
  32. package/dist/cli/commands/runtime/jobs/logs.js +27 -0
  33. package/dist/cli/commands/runtime/jobs/logs.js.map +1 -0
  34. package/dist/cli/commands/runtime/jobs/ls.d.ts +3 -0
  35. package/dist/cli/commands/runtime/jobs/ls.js +60 -0
  36. package/dist/cli/commands/runtime/jobs/ls.js.map +1 -0
  37. package/dist/cli/commands/runtime/jobs/sandbox.d.ts +3 -0
  38. package/dist/cli/commands/runtime/jobs/sandbox.js +15 -0
  39. package/dist/cli/commands/runtime/jobs/sandbox.js.map +1 -0
  40. package/dist/cli/commands/runtime/jobs/shared.d.ts +22 -0
  41. package/dist/cli/commands/runtime/jobs/shared.js +124 -0
  42. package/dist/cli/commands/runtime/jobs/shared.js.map +1 -0
  43. package/dist/cli/commands/runtime/jobs/stop.d.ts +3 -0
  44. package/dist/cli/commands/runtime/jobs/stop.js +31 -0
  45. package/dist/cli/commands/runtime/jobs/stop.js.map +1 -0
  46. package/dist/cli/commands/runtime/jobs/sync.d.ts +3 -0
  47. package/dist/cli/commands/runtime/jobs/sync.js +25 -0
  48. package/dist/cli/commands/runtime/jobs/sync.js.map +1 -0
  49. package/dist/cli/commands/runtime/shared.d.ts +20 -0
  50. package/dist/cli/commands/runtime/shared.js +69 -0
  51. package/dist/cli/commands/runtime/shared.js.map +1 -0
  52. package/dist/cli/commands/runtime/templates/clear.d.ts +3 -0
  53. package/dist/cli/commands/runtime/templates/clear.js +53 -0
  54. package/dist/cli/commands/runtime/templates/clear.js.map +1 -0
  55. package/dist/cli/commands/runtime/templates/index.d.ts +3 -0
  56. package/dist/cli/commands/runtime/templates/index.js +10 -0
  57. package/dist/cli/commands/runtime/templates/index.js.map +1 -0
  58. package/dist/cli/commands/runtime/templates/ls.d.ts +3 -0
  59. package/dist/cli/commands/runtime/templates/ls.js +52 -0
  60. package/dist/cli/commands/runtime/templates/ls.js.map +1 -0
  61. package/dist/cli/commands/runtime-options.d.ts +11 -0
  62. package/dist/cli/commands/runtime-options.js +26 -0
  63. package/dist/cli/commands/runtime-options.js.map +1 -0
  64. package/dist/cli/commands/spawn.js +36 -7
  65. package/dist/cli/commands/spawn.js.map +1 -1
  66. package/dist/cli/program.js +17 -1
  67. package/dist/cli/program.js.map +1 -1
  68. package/dist/index.js +70879 -47381
  69. package/dist/index.js.map +4 -4
  70. package/dist/providers/claude-code.js +3486 -852
  71. package/dist/providers/claude-code.js.map +4 -4
  72. package/dist/providers/codex.js +3486 -852
  73. package/dist/providers/codex.js.map +4 -4
  74. package/dist/providers/goose.js +3432 -798
  75. package/dist/providers/goose.js.map +4 -4
  76. package/dist/providers/kimi.js +3486 -852
  77. package/dist/providers/kimi.js.map +4 -4
  78. package/dist/providers/opencode.js +3486 -852
  79. package/dist/providers/opencode.js.map +4 -4
  80. package/dist/providers/poe-agent.js +20641 -17147
  81. package/dist/providers/poe-agent.js.map +4 -4
  82. package/dist/providers/spawn-options.d.ts +10 -1
  83. package/dist/sdk/experiment.js +6 -0
  84. package/dist/sdk/experiment.js.map +1 -1
  85. package/dist/sdk/ralph.js +108 -11
  86. package/dist/sdk/ralph.js.map +1 -1
  87. package/dist/sdk/spawn.js +27 -4
  88. package/dist/sdk/spawn.js.map +1 -1
  89. package/dist/sdk/types.d.ts +23 -1
  90. package/dist/utils/command-checks.js +2 -29
  91. package/dist/utils/command-checks.js.map +1 -1
  92. package/package.json +12 -7
  93. package/packages/design-system/dist/components/help-formatter-plain.d.ts +4 -0
  94. package/packages/design-system/dist/components/help-formatter-plain.js +132 -0
  95. package/packages/design-system/dist/components/help-formatter.d.ts +13 -0
  96. package/packages/design-system/dist/components/help-formatter.js +116 -7
  97. package/packages/design-system/dist/components/index.d.ts +2 -2
  98. package/packages/design-system/dist/components/index.js +1 -1
  99. package/packages/design-system/dist/components/text.d.ts +1 -0
  100. package/packages/design-system/dist/components/text.js +8 -0
  101. package/packages/design-system/dist/index.d.ts +3 -2
  102. package/packages/design-system/dist/index.js +2 -1
  103. package/packages/memory/dist/index.js +3406 -387
  104. package/packages/memory/dist/index.js.map +4 -4
  105. package/packages/superintendent/dist/commands/run.d.ts +45 -0
  106. package/packages/superintendent/dist/commands/run.js +133 -38
  107. package/packages/superintendent/dist/commands/superintendent-group.d.ts +36 -0
  108. package/packages/superintendent/dist/runtime/agent-runner.d.ts +31 -0
  109. package/packages/superintendent/dist/runtime/agent-runner.js +121 -0
  110. package/packages/superintendent/dist/runtime/loop.d.ts +7 -1
  111. package/packages/superintendent/dist/runtime/loop.js +3 -11
  112. package/packages/superintendent/dist/runtime/run-builder.d.ts +1 -0
  113. package/packages/superintendent/dist/runtime/run-builder.js +3 -25
  114. package/packages/superintendent/dist/runtime/run-inspector.d.ts +1 -0
  115. package/packages/superintendent/dist/runtime/run-inspector.js +3 -25
  116. package/packages/superintendent/dist/runtime/run-owner-review.d.ts +1 -0
  117. package/packages/superintendent/dist/runtime/run-owner-review.js +3 -25
  118. package/packages/superintendent/dist/runtime/run-superintendent.d.ts +1 -0
  119. package/packages/superintendent/dist/runtime/run-superintendent.js +3 -25
@@ -52,19 +52,11 @@ var require_config_toml = __commonJS({
52
52
  }
53
53
  });
54
54
 
55
- // packages/agent-spawn/src/run-command.ts
56
- import { spawn } from "node:child_process";
55
+ // packages/agent-spawn/src/register-factories.ts
56
+ import { spawn as spawnChildProcess2 } from "node:child_process";
57
57
 
58
- // packages/agent-spawn/src/types.ts
59
- function resolveModeConfig(modeConfig) {
60
- if (Array.isArray(modeConfig)) {
61
- return { args: modeConfig };
62
- }
63
- return {
64
- args: modeConfig.args ?? [],
65
- env: modeConfig.env && Object.keys(modeConfig.env).length > 0 ? modeConfig.env : void 0
66
- };
67
- }
58
+ // packages/agent-harness-tools/src/paths.ts
59
+ import path from "node:path";
68
60
 
69
61
  // packages/agent-defs/src/agents/claude-code.ts
70
62
  var claudeCodeAgent = {
@@ -205,918 +197,935 @@ function resolveAgentId(input) {
205
197
  return lookup.get(input.toLowerCase());
206
198
  }
207
199
 
208
- // packages/agent-spawn/src/configs/mcp.ts
209
- function toJsonMcpServers(servers) {
210
- const out = {};
211
- for (const [name, server] of Object.entries(servers)) {
212
- const mapped = { command: server.command };
213
- if (server.args && server.args.length > 0) {
214
- mapped.args = server.args;
200
+ // packages/agent-harness-tools/src/select-agent.ts
201
+ var loopAgents = allAgents.filter(
202
+ (agent) => agent.binaryName !== void 0 || agent.id === "poe-agent"
203
+ );
204
+ var supportedAgents = loopAgents.map((agent) => agent.id).join(", ");
205
+
206
+ // packages/file-lock/src/lock.ts
207
+ import * as fsPromises from "node:fs/promises";
208
+ import * as os from "node:os";
209
+
210
+ // packages/agent-harness-tools/src/run-logs.ts
211
+ import path2 from "node:path";
212
+
213
+ // packages/agent-harness-tools/src/log-stream.ts
214
+ import nodeFs from "node:fs";
215
+ var JOB_DIR = "/tmp/poe-jobs";
216
+ var POLL_INTERVAL_MS = 250;
217
+ async function* streamLogFile(env, jobId, opts) {
218
+ const fs = env.fs ?? nodeFs;
219
+ const file = jobLogPath(jobId);
220
+ let byteOffset = opts.sinceByte ?? 0;
221
+ while (true) {
222
+ if (opts.since !== void 0 && !await wasModifiedSince(fs, file, opts.since)) {
223
+ await waitForLogChange(fs, file);
224
+ continue;
215
225
  }
216
- if (server.env && Object.keys(server.env).length > 0) {
217
- mapped.env = server.env;
226
+ const result = await readLogChunk(fs, file, byteOffset);
227
+ if (result !== null) {
228
+ byteOffset = result.nextByteOffset;
229
+ yield result.chunk;
230
+ continue;
218
231
  }
219
- if (server.timeout !== void 0) {
220
- mapped.timeout = server.timeout;
232
+ await waitForLogChange(fs, file);
233
+ }
234
+ }
235
+ async function wasModifiedSince(fs, file, since) {
236
+ if (fs.promises.stat === void 0) {
237
+ return true;
238
+ }
239
+ try {
240
+ const stat2 = await fs.promises.stat(file);
241
+ return stat2.mtimeMs >= since.getTime();
242
+ } catch (error2) {
243
+ if (isNodeError(error2) && error2.code === "ENOENT") {
244
+ return false;
221
245
  }
222
- out[name] = mapped;
246
+ throw error2;
223
247
  }
224
- return out;
225
248
  }
226
- function toTomlString(value) {
227
- return JSON.stringify(value);
249
+ async function waitForExit(env, jobId, opts = {}) {
250
+ const fs = env.fs ?? nodeFs;
251
+ const file = jobExitPath(jobId);
252
+ while (true) {
253
+ throwIfAborted(opts.signal);
254
+ const contents = await readTextFileIfExists(fs, file);
255
+ if (contents !== null) {
256
+ const text4 = contents.trim();
257
+ const exitCode = Number(text4);
258
+ if (text4.length === 0 || !Number.isInteger(exitCode)) {
259
+ throw new Error(`Invalid exit code in ${file}: ${contents}`);
260
+ }
261
+ return { exitCode };
262
+ }
263
+ await sleep(POLL_INTERVAL_MS, opts.signal);
264
+ }
228
265
  }
229
- function toTomlArray(values) {
230
- const serialized = values.map((value) => toTomlString(value));
231
- return `[${serialized.join(", ")}]`;
266
+ function jobLogPath(jobId) {
267
+ return `${JOB_DIR}/${jobId}.log`;
232
268
  }
233
- function toTomlInlineTable(values) {
234
- const parts = [];
235
- for (const [key, value] of Object.entries(values)) {
236
- parts.push(`${JSON.stringify(key)}=${toTomlString(value)}`);
269
+ function jobExitPath(jobId) {
270
+ return `${JOB_DIR}/${jobId}.exit`;
271
+ }
272
+ async function readLogChunk(fs, file, byteOffset) {
273
+ const contents = await readFileIfExists(fs, file);
274
+ if (contents === null || byteOffset >= contents.byteLength) {
275
+ return null;
237
276
  }
238
- return `{${parts.join(", ")}}`;
277
+ return {
278
+ chunk: {
279
+ byteOffset,
280
+ data: contents.subarray(byteOffset).toString("utf8")
281
+ },
282
+ nextByteOffset: contents.byteLength
283
+ };
239
284
  }
240
- function serializeJsonMcpArgs(servers) {
241
- return ["--mcp-config", JSON.stringify({ mcpServers: toJsonMcpServers(servers) })];
285
+ async function readTextFileIfExists(fs, file) {
286
+ const contents = await readFileIfExists(fs, file);
287
+ return contents?.toString("utf8") ?? null;
242
288
  }
243
- function serializeOpenCodeMcpEnv(servers) {
244
- const mcp = {};
245
- for (const [name, server] of Object.entries(servers)) {
246
- const entry = { type: "local", command: [server.command, ...server.args ?? []] };
247
- if (server.env && Object.keys(server.env).length > 0) {
248
- entry.environment = server.env;
289
+ async function readFileIfExists(fs, file) {
290
+ try {
291
+ const contents = await fs.promises.readFile(file);
292
+ return Buffer.isBuffer(contents) ? contents : Buffer.from(contents);
293
+ } catch (error2) {
294
+ if (isNodeError(error2) && error2.code === "ENOENT") {
295
+ return null;
249
296
  }
250
- mcp[name] = entry;
297
+ throw error2;
251
298
  }
252
- return { OPENCODE_CONFIG_CONTENT: JSON.stringify({ mcp }) };
253
299
  }
254
- function serializeCodexMcpArgs(servers) {
255
- const args = [];
256
- for (const [name, server] of Object.entries(servers)) {
257
- const prefix = `mcp_servers.${name}`;
258
- args.push("-c", `${prefix}.command=${toTomlString(server.command)}`);
259
- if (server.args && server.args.length > 0) {
260
- args.push("-c", `${prefix}.args=${toTomlArray(server.args)}`);
300
+ async function waitForLogChange(fs, file) {
301
+ const watch = fs.watch;
302
+ if (typeof watch !== "function") {
303
+ await sleep(POLL_INTERVAL_MS);
304
+ return;
305
+ }
306
+ await new Promise((resolve2) => {
307
+ let watcher = null;
308
+ const timer = setTimeout(done, POLL_INTERVAL_MS);
309
+ function done() {
310
+ clearTimeout(timer);
311
+ watcher?.close();
312
+ resolve2();
261
313
  }
262
- if (server.env && Object.keys(server.env).length > 0) {
263
- args.push("-c", `${prefix}.env=${toTomlInlineTable(server.env)}`);
314
+ try {
315
+ watcher = watch(file, done);
316
+ } catch {
317
+ done();
264
318
  }
265
- if (server.timeout !== void 0) {
266
- args.push("-c", `${prefix}.timeout=${server.timeout}`);
319
+ });
320
+ }
321
+ function sleep(ms, signal) {
322
+ return new Promise((resolve2, reject) => {
323
+ let timer = null;
324
+ const abort = () => {
325
+ if (timer !== null) {
326
+ clearTimeout(timer);
327
+ }
328
+ reject(new Error("waitForExit aborted."));
329
+ };
330
+ if (signal?.aborted) {
331
+ abort();
332
+ return;
267
333
  }
334
+ timer = setTimeout(() => {
335
+ signal?.removeEventListener("abort", abort);
336
+ resolve2();
337
+ }, ms);
338
+ signal?.addEventListener("abort", abort, { once: true });
339
+ });
340
+ }
341
+ function throwIfAborted(signal) {
342
+ if (signal?.aborted) {
343
+ throw new Error("waitForExit aborted.");
268
344
  }
269
- return args;
270
345
  }
271
- function serializeGooseMcpArgs(servers) {
272
- return Object.values(servers).flatMap((server) => [
273
- "--with-extension",
274
- [server.command, ...server.args ?? []].join(" ")
275
- ]);
346
+ function isNodeError(error2) {
347
+ return error2 instanceof Error && "code" in error2;
276
348
  }
277
349
 
278
- // packages/agent-spawn/src/configs/claude-code.ts
279
- var claudeCodeSpawnConfig = {
280
- kind: "cli",
281
- agentId: "claude-code",
282
- // ACP adapter support: yes (adapter: "claude")
283
- adapter: "claude",
284
- promptFlag: "-p",
285
- modelFlag: "--model",
286
- modelStripProviderPrefix: true,
287
- modelTransform: (model) => model.replaceAll(".", "-"),
288
- defaultArgs: [
289
- "--output-format",
290
- "stream-json",
291
- "--verbose"
292
- ],
293
- mcpArgs: serializeJsonMcpArgs,
294
- modes: {
295
- yolo: ["--dangerously-skip-permissions"],
296
- edit: ["--permission-mode", "acceptEdits", "--allowedTools", "Bash,Read,Write,Edit,Glob,Grep,NotebookEdit"],
297
- read: ["--permission-mode", "plan"]
298
- },
299
- stdinMode: {
300
- omitPrompt: true,
301
- extraArgs: ["--input-format", "text"]
302
- },
303
- interactive: {
304
- defaultArgs: []
305
- },
306
- resumeCommand: (threadId) => ["--resume", threadId]
307
- };
350
+ // packages/agent-harness-tools/src/run-poe-command.ts
351
+ import { randomBytes } from "node:crypto";
308
352
 
309
- // packages/agent-spawn/src/configs/codex.ts
310
- var codexSpawnConfig = {
311
- kind: "cli",
312
- agentId: "codex",
313
- // ACP adapter support: yes (adapter: "codex")
314
- adapter: "codex",
315
- promptFlag: "exec",
316
- modelFlag: "--model",
317
- modelStripProviderPrefix: true,
318
- defaultArgs: ["--skip-git-repo-check", "--json"],
319
- mcpArgs: serializeCodexMcpArgs,
320
- mcpArgsBeforeCommand: true,
321
- modes: {
322
- yolo: ["-s", "danger-full-access"],
323
- edit: ["-s", "workspace-write"],
324
- read: ["-s", "read-only"]
325
- },
326
- stdinMode: {
327
- omitPrompt: true,
328
- extraArgs: ["-"]
329
- },
330
- interactive: {
331
- defaultArgs: ["-a", "never"]
332
- },
333
- resumeCommand: (threadId, cwd) => ["resume", "-C", cwd, threadId]
334
- };
353
+ // packages/agent-harness-tools/src/binary-exists.ts
354
+ function createBinaryExistsDetectors(binaryName) {
355
+ const commonPaths = [
356
+ `/usr/local/bin/${binaryName}`,
357
+ `/usr/bin/${binaryName}`,
358
+ `$HOME/.local/bin/${binaryName}`,
359
+ `$HOME/.claude/local/bin/${binaryName}`
360
+ ];
361
+ return [
362
+ {
363
+ command: "which",
364
+ args: [binaryName],
365
+ validate: (result) => result.exitCode === 0
366
+ },
367
+ {
368
+ command: "where",
369
+ args: [binaryName],
370
+ validate: (result) => result.exitCode === 0 && result.stdout.trim().length > 0
371
+ },
372
+ {
373
+ command: "sh",
374
+ args: ["-c", commonPaths.map((p) => `test -f "${p}"`).join(" || ")],
375
+ validate: (result) => result.exitCode === 0
376
+ }
377
+ ];
378
+ }
335
379
 
336
- // packages/agent-spawn/src/configs/opencode.ts
337
- var openCodeSpawnConfig = {
338
- kind: "cli",
339
- agentId: "opencode",
340
- // ACP adapter support: yes (adapter: "opencode").
341
- // OpenCode's `--format json` emits NDJSON events with `{ type, sessionID, part }`
342
- // (no `{ event, ... }` field), so it needs the OpenCode adapter (not "native").
343
- adapter: "opencode",
344
- promptFlag: "run",
345
- modelFlag: "--model",
346
- modelStripProviderPrefix: false,
347
- modelTransform: (model) => {
348
- return model.startsWith("poe/") ? model : `poe/${model}`;
349
- },
350
- defaultArgs: ["--format", "json"],
351
- modes: {
352
- yolo: [],
353
- edit: [],
354
- read: ["--agent", "plan"]
355
- },
356
- interactive: {
357
- defaultArgs: [],
358
- promptFlag: "--prompt"
359
- },
360
- resumeCommand: (threadId, cwd) => [cwd, "--session", threadId],
361
- mcpEnv: serializeOpenCodeMcpEnv
362
- };
363
- var openCodeAcpSpawnConfig = {
364
- kind: "acp",
365
- agentId: "opencode",
366
- acpArgs: ["acp"],
367
- skipAuth: true,
368
- mcpEnv: serializeOpenCodeMcpEnv
369
- };
380
+ // packages/agent-harness-tools/src/poe-command-execution.ts
381
+ import { existsSync as existsSync2, readFileSync } from "node:fs";
382
+ import os3 from "node:os";
370
383
 
371
- // packages/agent-spawn/src/configs/kimi.ts
372
- var kimiSpawnConfig = {
373
- kind: "cli",
374
- agentId: "kimi",
375
- // ACP adapter support: yes (adapter: "kimi").
376
- // Kimi's `--output-format stream-json` emits OpenAI-style `{ role, content }` JSON
377
- // (no `{ event, ... }` field), so it needs the Kimi adapter (not "native").
378
- adapter: "kimi",
379
- promptFlag: "-p",
380
- modelStripProviderPrefix: true,
381
- defaultArgs: ["--print", "--output-format", "stream-json"],
382
- mcpArgs: serializeJsonMcpArgs,
383
- modes: {
384
- yolo: ["--yolo"],
385
- edit: [],
386
- read: []
387
- },
388
- stdinMode: {
389
- omitPrompt: true,
390
- extraArgs: ["--input-format", "stream-json"]
391
- },
392
- interactive: {
393
- defaultArgs: [],
394
- promptFlag: "-p"
395
- },
396
- resumeCommand: (threadId, cwd) => ["--session", threadId, "--work-dir", cwd]
397
- };
398
- var kimiAcpSpawnConfig = {
399
- kind: "acp",
400
- agentId: "kimi",
401
- acpArgs: ["acp"]
384
+ // packages/poe-code-config/src/runtime.ts
385
+ import { existsSync } from "node:fs";
386
+ import path3 from "node:path";
387
+ var defaultWorkspaceExclude = [
388
+ ".git",
389
+ "node_modules",
390
+ "dist",
391
+ ".turbo",
392
+ ".next",
393
+ ".poe-code/state.json"
394
+ ];
395
+ var runtimeConfigScope = {
396
+ scope: "runtime",
397
+ schema: {
398
+ type: {
399
+ type: "string",
400
+ default: "host",
401
+ doc: "Runtime backend: host, docker, or e2b"
402
+ },
403
+ build_args: {
404
+ type: "json",
405
+ default: {},
406
+ parse: parseBuildArgs,
407
+ doc: "Build arguments passed to the runtime image build"
408
+ },
409
+ mounts: {
410
+ type: "json",
411
+ default: [],
412
+ parse: parseMounts,
413
+ doc: "Additional runtime mounts"
414
+ },
415
+ runner: {
416
+ type: "json",
417
+ default: createDefaultRunnerScope(),
418
+ parse: parseRunner,
419
+ doc: "Runner process and workspace transfer settings"
420
+ },
421
+ link: {
422
+ type: "string",
423
+ default: "",
424
+ doc: "Informational link for the runtime definition"
425
+ },
426
+ image: {
427
+ type: "string",
428
+ default: "",
429
+ doc: "Prebuilt Docker image"
430
+ },
431
+ dockerfile: {
432
+ type: "string",
433
+ default: "",
434
+ doc: "Path to the Dockerfile used for docker or e2b builds"
435
+ },
436
+ build_context: {
437
+ type: "string",
438
+ default: "",
439
+ doc: "Path to the Docker build context"
440
+ },
441
+ workspace_dir: {
442
+ type: "string",
443
+ default: "/workspace",
444
+ doc: "Sandbox-local workspace directory for E2B runtime upload, execution, and download"
445
+ },
446
+ engine: {
447
+ type: "string",
448
+ default: "",
449
+ doc: "Container engine for Docker runtime"
450
+ },
451
+ network: {
452
+ type: "string",
453
+ default: "",
454
+ doc: "Docker network"
455
+ },
456
+ extra_args: {
457
+ type: "json",
458
+ default: void 0,
459
+ parse: parseOptionalStringArray,
460
+ doc: "Extra Docker runtime arguments"
461
+ },
462
+ template_id: {
463
+ type: "string",
464
+ default: "",
465
+ doc: "Prebuilt E2B template id"
466
+ },
467
+ from_template: {
468
+ type: "string",
469
+ default: "",
470
+ doc: "Existing E2B template alias to extend instead of using the Dockerfile FROM image"
471
+ },
472
+ cpu: {
473
+ type: "json",
474
+ default: void 0,
475
+ parse: parseOptionalNumber,
476
+ doc: "E2B CPU count"
477
+ },
478
+ memory_mb: {
479
+ type: "json",
480
+ default: void 0,
481
+ parse: parseOptionalNumber,
482
+ doc: "E2B memory in megabytes"
483
+ },
484
+ timeout_minutes: {
485
+ type: "json",
486
+ default: void 0,
487
+ parse: parseOptionalNumber,
488
+ doc: "E2B timeout in minutes"
489
+ },
490
+ preserve_after_exit_hours: {
491
+ type: "json",
492
+ default: void 0,
493
+ parse: parseOptionalNumber,
494
+ doc: "Hours to keep an E2B sandbox alive after job exit"
495
+ }
496
+ }
402
497
  };
403
-
404
- // packages/agent-spawn/src/configs/goose.ts
405
- var gooseFileSecretsEnv = { GOOSE_DISABLE_KEYRING: "1" };
406
- var gooseSpawnConfig = {
407
- kind: "cli",
408
- agentId: "goose",
409
- adapter: "native",
410
- promptFlag: "--text",
411
- modelFlag: "--model",
412
- modelStripProviderPrefix: false,
413
- defaultArgs: ["run", "--output-format", "stream-json"],
414
- defaultArgsPosition: "beforePrompt",
415
- mcpArgs: serializeGooseMcpArgs,
416
- mcpArgsPosition: "beforePrompt",
417
- modes: {
418
- yolo: { env: { ...gooseFileSecretsEnv, GOOSE_MODE: "auto" } },
419
- edit: { env: { ...gooseFileSecretsEnv, GOOSE_MODE: "smart_approve" } },
420
- read: { env: { ...gooseFileSecretsEnv, GOOSE_MODE: "chat" } }
421
- },
422
- stdinMode: {
423
- omitPrompt: true,
424
- extraArgs: ["--instructions", "-"]
425
- },
426
- interactive: {
427
- defaultArgs: ["session"],
428
- defaultArgsPosition: "beforePrompt"
429
- },
430
- resumeCommand: () => ["run", "--resume", "--text", "continue"]
431
- };
432
- var gooseAcpSpawnConfig = {
433
- kind: "acp",
434
- agentId: "goose",
435
- acpArgs: ["acp"],
436
- env: gooseFileSecretsEnv,
437
- skipAuth: true
438
- };
439
-
440
- // packages/agent-spawn/src/configs/index.ts
441
- var allSpawnConfigs = [
442
- claudeCodeSpawnConfig,
443
- codexSpawnConfig,
444
- openCodeSpawnConfig,
445
- kimiSpawnConfig,
446
- gooseSpawnConfig
447
- ];
448
- var lookup2 = /* @__PURE__ */ new Map();
449
- for (const config of allSpawnConfigs) {
450
- lookup2.set(config.agentId, config);
498
+ function parseRunner(raw) {
499
+ if (raw === void 0) {
500
+ return createDefaultRunnerScope();
501
+ }
502
+ const record = asRecord(raw);
503
+ if (record === void 0) {
504
+ throw new Error("runner: expected an object.");
505
+ }
506
+ const uploadMaxFileMb = parseOptionalNumber(record.upload_max_file_mb, "runner.upload_max_file_mb") ?? 100;
507
+ if (uploadMaxFileMb <= 0) {
508
+ throw new Error("runner.upload_max_file_mb: expected a positive finite number.");
509
+ }
510
+ return omitUndefined({
511
+ detach: parseOptionalBoolean(record.detach, "runner.detach") ?? false,
512
+ upload_max_file_mb: uploadMaxFileMb,
513
+ download_conflict: parseDownloadConflict(record.download_conflict),
514
+ sync: parseRunnerSync(record.sync),
515
+ workspace: parseRunnerWorkspace(record.workspace)
516
+ });
451
517
  }
452
- var acpLookup = /* @__PURE__ */ new Map();
453
- acpLookup.set(openCodeAcpSpawnConfig.agentId, openCodeAcpSpawnConfig);
454
- acpLookup.set(kimiAcpSpawnConfig.agentId, kimiAcpSpawnConfig);
455
- acpLookup.set(gooseAcpSpawnConfig.agentId, gooseAcpSpawnConfig);
456
- function getSpawnConfig(input) {
457
- const resolvedId = resolveAgentId(input);
458
- if (!resolvedId) {
459
- return void 0;
518
+ function createDefaultRunnerScope() {
519
+ return {
520
+ detach: false,
521
+ upload_max_file_mb: 100,
522
+ download_conflict: "refuse",
523
+ sync: "both",
524
+ workspace: {
525
+ exclude: [...defaultWorkspaceExclude]
526
+ }
527
+ };
528
+ }
529
+ function parseRunnerWorkspace(value) {
530
+ if (value === void 0) {
531
+ return {
532
+ exclude: [...defaultWorkspaceExclude]
533
+ };
460
534
  }
461
- return lookup2.get(resolvedId);
535
+ const record = asRecord(value);
536
+ if (record === void 0) {
537
+ throw new Error("runner.workspace: expected an object.");
538
+ }
539
+ return {
540
+ exclude: parseOptionalStringArray(record.exclude, "runner.workspace.exclude") ?? [
541
+ ...defaultWorkspaceExclude
542
+ ]
543
+ };
462
544
  }
463
- function listMcpSupportedAgents() {
464
- const supported = [];
465
- for (const config of allSpawnConfigs) {
466
- if (config.kind !== "cli" || typeof config.mcpArgs !== "function" && typeof config.mcpEnv !== "function") {
467
- continue;
468
- }
469
- supported.push(config.agentId);
545
+ function parseDownloadConflict(value) {
546
+ if (value === void 0) {
547
+ return "refuse";
470
548
  }
471
- return supported;
549
+ if (value === "refuse" || value === "overwrite") {
550
+ return value;
551
+ }
552
+ throw new Error('runner.download_conflict: expected "refuse" or "overwrite".');
472
553
  }
473
-
474
- // packages/agent-spawn/src/spawn.ts
475
- import { spawn as spawnChildProcess } from "node:child_process";
476
- import { mkdirSync, openSync, writeSync, closeSync } from "node:fs";
477
- import path from "node:path";
478
-
479
- // packages/agent-spawn/src/configs/resolve-config.ts
480
- function resolveConfig(agentId) {
481
- const resolvedAgentId = resolveAgentId(agentId);
482
- if (!resolvedAgentId) {
483
- throw new Error(`Unknown agent "${agentId}".`);
554
+ function parseRunnerSync(value) {
555
+ if (value === void 0) {
556
+ return "both";
484
557
  }
485
- const agentDefinition = allAgents.find((agent) => agent.id === resolvedAgentId);
486
- if (!agentDefinition) {
487
- throw new Error(`Unknown agent "${agentId}".`);
558
+ if (value === "both" || value === "upload" || value === "none") {
559
+ return value;
488
560
  }
489
- const spawnConfig = getSpawnConfig(resolvedAgentId);
490
- const binaryName = agentDefinition.binaryName;
491
- return { agentId: resolvedAgentId, binaryName, spawnConfig };
561
+ throw new Error('runner.sync: expected "both", "upload", or "none".');
492
562
  }
493
-
494
- // packages/agent-spawn/src/mcp-args.ts
495
- function hasMcpServers(servers) {
496
- if (!servers) {
497
- return false;
563
+ function parseBuildArgs(value) {
564
+ if (value === void 0) {
565
+ return {};
498
566
  }
499
- return Object.keys(servers).length > 0;
567
+ const record = asRecord(value);
568
+ if (record === void 0) {
569
+ throw new Error("build_args: expected an object.");
570
+ }
571
+ const parsed = {};
572
+ for (const [key, entry] of Object.entries(record)) {
573
+ if (typeof entry !== "string") {
574
+ throw new Error(`build_args.${key}: expected a string.`);
575
+ }
576
+ parsed[key] = entry;
577
+ }
578
+ return parsed;
500
579
  }
501
- function getMcpArgs(config, servers) {
502
- if (!hasMcpServers(servers)) {
580
+ function parseMounts(value) {
581
+ if (value === void 0) {
503
582
  return [];
504
583
  }
505
- if (!config.mcpArgs && !config.mcpEnv) {
506
- throw new Error(formatUnsupportedMcpSpawnMessage(config.agentId));
584
+ if (!Array.isArray(value)) {
585
+ throw new Error("mounts: expected an array.");
507
586
  }
508
- if (!config.mcpArgs) {
509
- return [];
587
+ return value.map((entry, index) => {
588
+ const record = asRecord(entry);
589
+ if (record === void 0) {
590
+ throw new Error(`mounts[${index}]: expected an object.`);
591
+ }
592
+ const source = record.source;
593
+ const target = record.target;
594
+ if (typeof source !== "string") {
595
+ throw new Error(`mounts[${index}].source: expected a string.`);
596
+ }
597
+ if (typeof target !== "string") {
598
+ throw new Error(`mounts[${index}].target: expected a string.`);
599
+ }
600
+ return omitUndefined({
601
+ source,
602
+ target,
603
+ readonly: parseOptionalBoolean(record.readonly, `mounts[${index}].readonly`)
604
+ });
605
+ });
606
+ }
607
+ function parseOptionalStringArray(value, key = "") {
608
+ if (value === void 0) {
609
+ return void 0;
510
610
  }
511
- return config.mcpArgs(servers);
611
+ if (!Array.isArray(value)) {
612
+ throw new Error(`${key ? `${key}: ` : ""}expected an array.`);
613
+ }
614
+ return value.map((entry, index) => {
615
+ if (typeof entry !== "string") {
616
+ throw new Error(`${key}[${index}]: expected a string.`);
617
+ }
618
+ return entry;
619
+ });
512
620
  }
513
- function formatUnsupportedMcpSpawnMessage(agentId) {
514
- const supported = listMcpSupportedAgents();
515
- const supportedText = supported.length > 0 ? supported.join(", ") : "(none)";
516
- return `Agent "${agentId}" does not support MCP servers at spawn time.
517
- Agents with spawn-time MCP support: ${supportedText}`;
621
+ function parseOptionalNumber(value, key = "") {
622
+ if (value === void 0) {
623
+ return void 0;
624
+ }
625
+ if (typeof value !== "number" || !Number.isFinite(value)) {
626
+ throw new Error(`${key ? `${key}: ` : ""}expected a finite number.`);
627
+ }
628
+ return value;
518
629
  }
519
-
520
- // packages/agent-spawn/src/model-utils.ts
521
- function stripModelNamespace(model) {
522
- const slashIndex = model.indexOf("/");
523
- return slashIndex === -1 ? model : model.slice(slashIndex + 1);
630
+ function parseOptionalBoolean(value, key) {
631
+ if (value === void 0) {
632
+ return void 0;
633
+ }
634
+ if (typeof value !== "boolean") {
635
+ throw new Error(`${key}: expected a boolean.`);
636
+ }
637
+ return value;
638
+ }
639
+ function asRecord(value) {
640
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
641
+ return void 0;
642
+ }
643
+ return value;
644
+ }
645
+ function omitUndefined(value) {
646
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0));
524
647
  }
525
648
 
526
- // packages/agent-spawn/src/spawn.ts
527
- function resolveCliConfig(agentId) {
528
- const resolved = resolveConfig(agentId);
529
- if (!resolved.spawnConfig) {
530
- throw new Error(`Agent "${resolved.agentId}" has no spawn config.`);
649
+ // packages/poe-code-config/src/schema.ts
650
+ function defineScope(scope, schema) {
651
+ return {
652
+ scope,
653
+ schema
654
+ };
655
+ }
656
+ var integrationsConfigScope = defineScope("integrations", {
657
+ braintrust: {
658
+ type: "json",
659
+ default: {
660
+ enabled: false
661
+ },
662
+ parse: parseBraintrustIntegrationConfig,
663
+ doc: "Braintrust integration configuration"
531
664
  }
532
- if (resolved.spawnConfig.kind !== "cli") {
533
- throw new Error(`Agent "${resolved.agentId}" does not support CLI spawn.`);
665
+ });
666
+ function parseBraintrustIntegrationConfig(value) {
667
+ if (!isRecord(value)) {
668
+ throw new Error("expected an object");
534
669
  }
535
- if (!resolved.binaryName) {
536
- throw new Error(`Agent "${resolved.agentId}" has no binaryName.`);
670
+ const enabled = value.enabled === void 0 ? false : value.enabled;
671
+ if (typeof enabled !== "boolean") {
672
+ throw new Error("enabled must be a boolean");
537
673
  }
538
674
  return {
539
- agentId: resolved.agentId,
540
- binaryName: resolved.binaryName,
541
- spawnConfig: resolved.spawnConfig
675
+ enabled,
676
+ ...optionalStringEntry("apiKey", value.apiKey),
677
+ ...optionalStringEntry("apiUrl", value.apiUrl),
678
+ ...optionalStringEntry("project", value.project)
542
679
  };
543
680
  }
544
- function getDefaultArgsPosition(config) {
545
- return config.defaultArgsPosition ?? "afterPrompt";
546
- }
547
- function getMcpArgsPosition(config) {
548
- if (config.mcpArgsPosition) {
549
- return config.mcpArgsPosition;
681
+ function optionalStringEntry(key, value) {
682
+ if (value === void 0) {
683
+ return {};
550
684
  }
551
- return config.mcpArgsBeforeCommand ? "beforeCommand" : "afterCommand";
685
+ if (typeof value !== "string") {
686
+ throw new Error(`${key} must be a string`);
687
+ }
688
+ return { [key]: value };
552
689
  }
553
- function buildCliArgs(config, options, stdinMode) {
554
- const mcpArgs = getMcpArgs(config, options.mcpServers);
555
- const defaultArgsPosition = getDefaultArgsPosition(config);
556
- const mcpArgsPosition = getMcpArgsPosition(config);
557
- const args = [];
558
- if (mcpArgsPosition === "beforeCommand") {
559
- args.push(...mcpArgs);
690
+ function isRecord(value) {
691
+ return typeof value === "object" && value !== null && !Array.isArray(value);
692
+ }
693
+
694
+ // packages/poe-code-config/src/plan-scope.ts
695
+ var planConfigScope = defineScope("plan", {
696
+ plan_directory: {
697
+ type: "string",
698
+ default: "docs/plans",
699
+ env: "POE_PLAN_DIRECTORY",
700
+ doc: "Directory where planning documents are stored"
560
701
  }
561
- if (defaultArgsPosition === "beforePrompt") {
562
- args.push(...config.defaultArgs);
702
+ });
703
+
704
+ // packages/poe-code-config/src/store.ts
705
+ import path8 from "node:path";
706
+
707
+ // packages/config-extends/src/discover.ts
708
+ import path4 from "node:path";
709
+ async function findBase(name, bases, fs) {
710
+ const checkedPaths = [];
711
+ for (const basePath of bases) {
712
+ for (const extension of [".md", ".yaml", ".yml", ".json"]) {
713
+ const filePath = path4.join(basePath, `${name}${extension}`);
714
+ checkedPaths.push(filePath);
715
+ try {
716
+ return {
717
+ content: await fs.readFile(filePath, "utf8"),
718
+ filePath
719
+ };
720
+ } catch (error2) {
721
+ if (hasCode(error2, "ENOENT")) {
722
+ continue;
723
+ }
724
+ throw error2;
725
+ }
726
+ }
563
727
  }
564
- if (mcpArgsPosition === "beforePrompt") {
565
- args.push(...mcpArgs);
728
+ throw new Error(`Base "${name}" not found.
729
+ Checked paths:
730
+ - ${checkedPaths.join("\n- ")}`);
731
+ }
732
+ function hasCode(error2, code) {
733
+ return typeof error2 === "object" && error2 !== null && "code" in error2 && error2.code === code;
734
+ }
735
+
736
+ // packages/config-extends/src/parse.ts
737
+ import path5 from "node:path";
738
+ import matter from "gray-matter";
739
+ import { parse as parseYaml } from "yaml";
740
+ function parseDocument(content, filePath) {
741
+ const normalizedContent = stripBom(content);
742
+ const format = detectFormat(normalizedContent, filePath);
743
+ const data = format === "markdown" ? parseMarkdown(normalizedContent) : toData(format === "json" ? JSON.parse(normalizedContent) : parseYaml(normalizedContent));
744
+ const hasExtendsField = Object.hasOwn(data, "extends");
745
+ const extendsValue = data.extends === true;
746
+ delete data.extends;
747
+ return {
748
+ data,
749
+ format,
750
+ extends: extendsValue,
751
+ hasExtendsField
752
+ };
753
+ }
754
+ function detectFormat(content, filePath) {
755
+ const extension = path5.extname(filePath).toLowerCase();
756
+ if (extension === ".md") {
757
+ return "markdown";
566
758
  }
567
- if (stdinMode) {
568
- args.push(
569
- config.promptFlag,
570
- ...stdinMode.omitPrompt ? [] : [options.prompt],
571
- ...stdinMode.extraArgs
572
- );
573
- } else {
574
- args.push(config.promptFlag, options.prompt);
759
+ if (extension === ".yaml" || extension === ".yml") {
760
+ return "yaml";
575
761
  }
576
- if (options.model && config.modelFlag) {
577
- let model = config.modelStripProviderPrefix ? stripModelNamespace(options.model) : options.model;
578
- if (config.modelTransform) model = config.modelTransform(model);
579
- args.push(config.modelFlag, model);
762
+ if (extension === ".json") {
763
+ return "json";
580
764
  }
581
- if (defaultArgsPosition === "afterPrompt") {
582
- args.push(...config.defaultArgs);
765
+ if (content.startsWith("{")) {
766
+ return "json";
583
767
  }
584
- if (mcpArgsPosition === "afterCommand") {
585
- args.push(...mcpArgs);
768
+ if (content.startsWith("---\n") || content.startsWith("---\r\n")) {
769
+ return "markdown";
586
770
  }
587
- const mode = resolveModeConfig(config.modes[options.mode ?? "yolo"]);
588
- args.push(...mode.args);
589
- if (options.args && options.args.length > 0) {
590
- args.push(...options.args);
771
+ return "yaml";
772
+ }
773
+ function parseMarkdown(content) {
774
+ const document = matter(content);
775
+ return {
776
+ ...toData(document.data),
777
+ prompt: document.content
778
+ };
779
+ }
780
+ function toData(value) {
781
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
782
+ return {};
591
783
  }
592
- return { args, env: mode.env };
784
+ return { ...value };
593
785
  }
594
- function buildSpawnArgs(agentId, options) {
595
- const { binaryName, spawnConfig } = resolveCliConfig(agentId);
596
- const stdinMode = options.useStdin && spawnConfig.stdinMode ? spawnConfig.stdinMode : void 0;
597
- const result = buildCliArgs(spawnConfig, options, stdinMode);
598
- return { binaryName, args: result.args, env: result.env };
786
+ function stripBom(content) {
787
+ if (!content.startsWith("\uFEFF")) {
788
+ return content;
789
+ }
790
+ return content.slice(1);
599
791
  }
600
792
 
601
- // packages/agent-spawn/src/spawn-interactive.ts
602
- import { spawn as spawnChildProcess2 } from "node:child_process";
603
-
604
- // packages/design-system/src/tokens/colors.ts
605
- import chalk from "chalk";
606
- var dark = {
607
- header: (text4) => chalk.magentaBright.bold(text4),
608
- divider: (text4) => chalk.dim(text4),
609
- prompt: (text4) => chalk.cyan(text4),
610
- number: (text4) => chalk.cyanBright(text4),
611
- intro: (text4) => chalk.bgMagenta.white(` Poe - ${text4} `),
612
- resolvedSymbol: chalk.magenta("\u25C7"),
613
- errorSymbol: chalk.red("\u25A0"),
614
- accent: (text4) => chalk.cyan(text4),
615
- muted: (text4) => chalk.dim(text4),
616
- success: (text4) => chalk.green(text4),
617
- warning: (text4) => chalk.yellow(text4),
618
- error: (text4) => chalk.red(text4),
619
- info: (text4) => chalk.magenta(text4),
620
- badge: (text4) => chalk.bgYellow.black(` ${text4} `)
621
- };
622
- var light = {
623
- header: (text4) => chalk.hex("#a200ff").bold(text4),
624
- divider: (text4) => chalk.hex("#666666")(text4),
625
- prompt: (text4) => chalk.hex("#006699").bold(text4),
626
- number: (text4) => chalk.hex("#0077cc").bold(text4),
627
- intro: (text4) => chalk.bgHex("#a200ff").white(` Poe - ${text4} `),
628
- resolvedSymbol: chalk.hex("#a200ff")("\u25C7"),
629
- errorSymbol: chalk.hex("#cc0000")("\u25A0"),
630
- accent: (text4) => chalk.hex("#006699").bold(text4),
631
- muted: (text4) => chalk.hex("#666666")(text4),
632
- success: (text4) => chalk.hex("#008800")(text4),
633
- warning: (text4) => chalk.hex("#cc6600")(text4),
634
- error: (text4) => chalk.hex("#cc0000")(text4),
635
- info: (text4) => chalk.hex("#a200ff")(text4),
636
- badge: (text4) => chalk.bgHex("#cc6600").white(` ${text4} `)
637
- };
638
-
639
- // packages/design-system/src/tokens/typography.ts
640
- import chalk2 from "chalk";
641
-
642
- // packages/design-system/src/components/text.ts
643
- import chalk3 from "chalk";
644
-
645
- // packages/design-system/src/internal/output-format.ts
646
- import { AsyncLocalStorage } from "node:async_hooks";
647
- var VALID_FORMATS = /* @__PURE__ */ new Set(["terminal", "markdown", "json"]);
648
- var formatStorage = new AsyncLocalStorage();
649
- var cached;
650
- function resolveOutputFormat(env = process.env) {
651
- const scoped = formatStorage.getStore();
652
- if (scoped) {
653
- return scoped;
654
- }
655
- if (cached) {
656
- return cached;
793
+ // packages/config-extends/src/merge.ts
794
+ function mergeLayers(layers) {
795
+ return mergeObjectLayers(layers, []);
796
+ }
797
+ function mergeObjectLayers(layers, path22) {
798
+ const data = {};
799
+ const sources = {};
800
+ for (const key of collectKeys(layers)) {
801
+ const resolved = resolveKey(layers, key, path22);
802
+ if (resolved === void 0) {
803
+ continue;
804
+ }
805
+ data[key] = resolved.value;
806
+ Object.assign(sources, resolved.sources);
657
807
  }
658
- const raw = env.OUTPUT_FORMAT?.toLowerCase();
659
- cached = VALID_FORMATS.has(raw) ? raw : "terminal";
660
- return cached;
808
+ return { data, sources };
661
809
  }
662
-
663
- // packages/design-system/src/internal/theme-detect.ts
664
- function detectThemeFromEnv(env) {
665
- const apple = env.APPLE_INTERFACE_STYLE;
666
- if (typeof apple === "string") {
667
- return apple.toLowerCase() === "dark" ? "dark" : "light";
810
+ function collectKeys(layers) {
811
+ const keys = /* @__PURE__ */ new Set();
812
+ for (const layer of layers) {
813
+ for (const key of Object.keys(layer.data)) {
814
+ keys.add(key);
815
+ }
668
816
  }
669
- const vscodeKind = env.VSCODE_COLOR_THEME_KIND;
670
- if (typeof vscodeKind === "string") {
671
- const normalized = vscodeKind.toLowerCase();
672
- if (normalized.includes("light")) {
673
- return "light";
817
+ return [...keys];
818
+ }
819
+ function resolveKey(layers, key, path22) {
820
+ let winningSource;
821
+ let winningValue;
822
+ const objectLayers = [];
823
+ for (const layer of layers) {
824
+ const candidate = layer.data[key];
825
+ if (!isWinningCandidate(key, candidate)) {
826
+ continue;
674
827
  }
675
- if (normalized.includes("dark")) {
676
- return "dark";
828
+ if (winningSource === void 0) {
829
+ winningSource = layer.source;
830
+ winningValue = candidate;
831
+ if (isPlainObject(candidate)) {
832
+ objectLayers.push({
833
+ source: layer.source,
834
+ data: candidate
835
+ });
836
+ }
837
+ continue;
677
838
  }
678
- }
679
- const colorFGBG = env.COLORFGBG;
680
- if (typeof colorFGBG === "string") {
681
- const parts = colorFGBG.split(";").map((part) => Number.parseInt(part, 10));
682
- const background = parts.at(-1);
683
- if (Number.isFinite(background)) {
684
- return background >= 8 ? "light" : "dark";
839
+ if (isPlainObject(winningValue) && isPlainObject(candidate)) {
840
+ objectLayers.push({
841
+ source: layer.source,
842
+ data: candidate
843
+ });
685
844
  }
686
845
  }
687
- return void 0;
688
- }
689
- function resolveThemeName(env = process.env) {
690
- const raw = (env.POE_CODE_THEME ?? env.POE_THEME)?.toLowerCase();
691
- if (raw === "light" || raw === "dark") {
692
- return raw;
846
+ if (winningSource === void 0) {
847
+ return void 0;
693
848
  }
694
- const detected = detectThemeFromEnv(env);
695
- if (detected) {
696
- return detected;
849
+ const fullPath = buildPath(path22, key);
850
+ if (isPlainObject(winningValue)) {
851
+ const merged = mergeObjectLayers(objectLayers, [...path22, key]);
852
+ return {
853
+ value: merged.data,
854
+ sources: {
855
+ [fullPath]: winningSource,
856
+ ...merged.sources
857
+ }
858
+ };
697
859
  }
698
- return "dark";
860
+ return {
861
+ value: cloneValue(winningValue),
862
+ sources: {
863
+ [fullPath]: winningSource
864
+ }
865
+ };
699
866
  }
700
- var cachedTheme;
701
- function getTheme(env) {
702
- if (cachedTheme) {
703
- return cachedTheme;
867
+ function isWinningCandidate(key, value) {
868
+ if (value === void 0) {
869
+ return false;
704
870
  }
705
- const themeName = resolveThemeName(env);
706
- cachedTheme = themeName === "light" ? light : dark;
707
- return cachedTheme;
871
+ if (key === "prompt" && value === "") {
872
+ return false;
873
+ }
874
+ return true;
708
875
  }
709
-
710
- // packages/design-system/src/components/symbols.ts
711
- import chalk4 from "chalk";
712
- var symbols = {
713
- get info() {
714
- const format = resolveOutputFormat();
715
- if (format === "json") return "info";
716
- if (format === "markdown") return "(i)";
717
- return chalk4.magenta("\u25CF");
718
- },
719
- get success() {
720
- const format = resolveOutputFormat();
721
- if (format === "json") return "success";
722
- if (format === "markdown") return "[ok]";
723
- return chalk4.magenta("\u25C6");
724
- },
725
- get resolved() {
726
- const format = resolveOutputFormat();
727
- if (format === "json") return "resolved";
728
- if (format === "markdown") return ">";
729
- return getTheme().resolvedSymbol;
730
- },
731
- get errorResolved() {
732
- const format = resolveOutputFormat();
733
- if (format === "json") return "error";
734
- if (format === "markdown") return "[!]";
735
- return getTheme().errorSymbol;
736
- },
737
- get bar() {
738
- const format = resolveOutputFormat();
739
- if (format === "json") return "";
740
- if (format === "markdown") return "|";
741
- return "\u2502";
742
- },
743
- cornerTopRight: "\u256E",
744
- cornerBottomRight: "\u256F",
745
- get warning() {
746
- const format = resolveOutputFormat();
747
- if (format === "json") return "warning";
748
- if (format === "markdown") return "[!]";
749
- return "\u25B2";
750
- },
751
- get active() {
752
- const format = resolveOutputFormat();
753
- if (format === "json") return "active";
754
- if (format === "markdown") return "[x]";
755
- return "\u25C6";
756
- },
757
- get inactive() {
758
- const format = resolveOutputFormat();
759
- if (format === "json") return "inactive";
760
- if (format === "markdown") return "[ ]";
761
- return "\u25CB";
876
+ function buildPath(path22, key) {
877
+ return [...path22, key].join(".");
878
+ }
879
+ function isPlainObject(value) {
880
+ if (value === null || Array.isArray(value) || typeof value !== "object") {
881
+ return false;
762
882
  }
763
- };
764
-
765
- // packages/design-system/src/components/logger.ts
766
- import chalk6 from "chalk";
767
-
768
- // packages/design-system/src/prompts/primitives/log.ts
769
- import chalk5 from "chalk";
770
-
771
- // packages/design-system/src/internal/strip-ansi.ts
772
- function stripAnsi(value) {
773
- return value.replace(/\u001b\[[0-9;]*m/g, "");
883
+ const prototype = Object.getPrototypeOf(value);
884
+ return prototype === Object.prototype || prototype === null;
774
885
  }
775
-
776
- // packages/design-system/src/prompts/primitives/log.ts
777
- function writeTerminalMessage(msg, {
778
- symbol = chalk5.gray("\u2502"),
779
- secondarySymbol = chalk5.gray("\u2502"),
780
- spacing: spacing2 = 1,
781
- withGuide = true
782
- } = {}) {
783
- const lines = [];
784
- const showGuide = withGuide !== false;
785
- const contentLines = msg.split("\n");
786
- const prefix = showGuide ? `${symbol} ` : "";
787
- const continuationPrefix = showGuide ? `${secondarySymbol} ` : "";
788
- const emptyGuide = showGuide ? secondarySymbol : "";
789
- for (let index = 0; index < spacing2; index += 1) {
790
- lines.push(emptyGuide);
886
+ function cloneValue(value) {
887
+ if (Array.isArray(value)) {
888
+ return value.map((entry) => cloneValue(entry));
791
889
  }
792
- if (contentLines.length === 0) {
793
- process.stdout.write("\n");
794
- return;
890
+ if (!isPlainObject(value)) {
891
+ return value;
795
892
  }
796
- const [firstLine = "", ...continuationLines] = contentLines;
797
- if (firstLine.length > 0) {
798
- lines.push(`${prefix}${firstLine}`);
799
- } else {
800
- lines.push(showGuide ? symbol : "");
893
+ const clone = Object.create(Object.getPrototypeOf(value));
894
+ for (const [key, entry] of Object.entries(value)) {
895
+ clone[key] = cloneValue(entry);
801
896
  }
802
- for (const line of continuationLines) {
803
- if (line.length > 0) {
804
- lines.push(`${continuationPrefix}${line}`);
897
+ return clone;
898
+ }
899
+
900
+ // packages/config-extends/src/resolve.ts
901
+ import path6 from "node:path";
902
+ var MAX_EXTENDS_DEPTH = 5;
903
+ var YIELD_TOKEN = "{{yield}}";
904
+ async function resolve(chain, options) {
905
+ const { baseLayers, documentIndex, documentLayer } = classifyChain(chain);
906
+ const parsedDocument = parseDocument(documentLayer.content, documentLayer.filePath);
907
+ const resolvedBase = shouldResolveBase(parsedDocument, options.autoExtend) ? await resolveBaseChain({
908
+ name: documentLayer.baseName ?? getBaseName(documentLayer.filePath),
909
+ baseLayers,
910
+ options,
911
+ optional: !parsedDocument.extends,
912
+ visited: /* @__PURE__ */ new Set([documentLayer.filePath]),
913
+ depth: 1
914
+ }) : void 0;
915
+ const composedPrompt = composePromptChain(
916
+ {
917
+ source: documentLayer.source,
918
+ data: parsedDocument.data
919
+ },
920
+ resolvedBase?.layers ?? []
921
+ );
922
+ const merged = mergeLayers([
923
+ ...collectDataLayers(chain.slice(0, documentIndex)),
924
+ {
925
+ source: documentLayer.source,
926
+ data: withResolvedPrompt(parsedDocument.data, composedPrompt?.prompt)
927
+ },
928
+ ...stripResolvedBasePrompts(resolvedBase?.layers ?? [], composedPrompt?.consumedBaseIndexes ?? /* @__PURE__ */ new Set()),
929
+ ...collectDataLayers(chain.slice(documentIndex + 1))
930
+ ]);
931
+ if (composedPrompt !== void 0 && merged.sources.prompt === documentLayer.source && composedPrompt.source !== void 0) {
932
+ merged.sources.prompt = composedPrompt.source;
933
+ }
934
+ return {
935
+ data: merged.data,
936
+ sources: merged.sources,
937
+ chain: [documentLayer.filePath, ...resolvedBase?.chain ?? []]
938
+ };
939
+ }
940
+ function classifyChain(chain) {
941
+ const baseLayers = [];
942
+ const documentLayers = [];
943
+ for (const [index, layer] of chain.entries()) {
944
+ if (isDataLayer(layer)) {
805
945
  continue;
806
946
  }
807
- lines.push(emptyGuide);
947
+ if (isDocumentLayer(layer)) {
948
+ documentLayers.push({ index, layer });
949
+ continue;
950
+ }
951
+ if (isBaseLayer(layer)) {
952
+ baseLayers.push(layer);
953
+ }
808
954
  }
809
- process.stdout.write(`${lines.join("\n")}
810
- `);
955
+ if (documentLayers.length !== 1) {
956
+ throw new Error(`Exactly one document layer is required, received ${documentLayers.length}.`);
957
+ }
958
+ return {
959
+ baseLayers,
960
+ documentIndex: documentLayers[0].index,
961
+ documentLayer: documentLayers[0].layer
962
+ };
811
963
  }
812
- function message(msg, options) {
813
- const format = resolveOutputFormat();
814
- if (format === "markdown") {
815
- process.stdout.write(`- ${stripAnsi(msg)}
816
- `);
817
- return;
964
+ async function resolveBaseChain({
965
+ name,
966
+ baseLayers,
967
+ options,
968
+ optional,
969
+ visited,
970
+ depth
971
+ }) {
972
+ if (depth > MAX_EXTENDS_DEPTH) {
973
+ throw new Error(`Maximum extends depth exceeded (${MAX_EXTENDS_DEPTH}).`);
974
+ }
975
+ let discoveredBase;
976
+ try {
977
+ discoveredBase = await findBase(
978
+ name,
979
+ baseLayers.map((layer) => layer.path),
980
+ options.fs
981
+ );
982
+ } catch (error2) {
983
+ if (optional && isBaseNotFoundError(error2)) {
984
+ return void 0;
985
+ }
986
+ throw error2;
818
987
  }
819
- if (format === "json") {
820
- process.stdout.write(
821
- `${JSON.stringify({ level: "message", message: stripAnsi(msg) })}
822
- `
988
+ if (visited.has(discoveredBase.filePath)) {
989
+ if (optional) {
990
+ return void 0;
991
+ }
992
+ throw new Error(
993
+ `Circular extends detected.
994
+ Visited files:
995
+ - ${[...visited, discoveredBase.filePath].join("\n- ")}`
823
996
  );
824
- return;
825
997
  }
826
- writeTerminalMessage(msg, options);
998
+ const matchedBaseIndex = baseLayers.findIndex(
999
+ (layer) => layer.path === path6.dirname(discoveredBase.filePath)
1000
+ );
1001
+ if (matchedBaseIndex === -1) {
1002
+ throw new Error(`Resolved base is outside configured base paths: ${discoveredBase.filePath}`);
1003
+ }
1004
+ const parsedBase = parseDocument(discoveredBase.content, discoveredBase.filePath);
1005
+ const nextVisited = new Set(visited);
1006
+ nextVisited.add(discoveredBase.filePath);
1007
+ const nestedBase = parsedBase.extends ? await resolveBaseChain({
1008
+ name: getBaseName(discoveredBase.filePath),
1009
+ baseLayers: baseLayers.slice(matchedBaseIndex + 1),
1010
+ options,
1011
+ optional: false,
1012
+ visited: nextVisited,
1013
+ depth: depth + 1
1014
+ }) : void 0;
1015
+ return {
1016
+ layers: [
1017
+ {
1018
+ source: baseLayers[matchedBaseIndex].source,
1019
+ data: parsedBase.data
1020
+ },
1021
+ ...nestedBase?.layers ?? []
1022
+ ],
1023
+ chain: [discoveredBase.filePath, ...nestedBase?.chain ?? []]
1024
+ };
827
1025
  }
828
- function info(msg) {
829
- const format = resolveOutputFormat();
830
- if (format === "markdown") {
831
- process.stdout.write(`- **info:** ${stripAnsi(msg)}
832
- `);
833
- return;
1026
+ function collectDataLayers(chain) {
1027
+ return chain.filter(isDataLayer);
1028
+ }
1029
+ function composePromptChain(documentLayer, baseLayers) {
1030
+ const documentPrompt = documentLayer.data.prompt;
1031
+ if (documentPrompt !== void 0 && typeof documentPrompt !== "string") {
1032
+ return void 0;
834
1033
  }
835
- if (format === "json") {
836
- process.stdout.write(
837
- `${JSON.stringify({ level: "info", message: stripAnsi(msg) })}
838
- `
839
- );
840
- return;
1034
+ if (documentPrompt !== void 0) {
1035
+ assertValidYieldCount(documentPrompt);
841
1036
  }
842
- message(msg, { symbol: symbols.info });
843
- }
844
- function success(msg) {
845
- const format = resolveOutputFormat();
846
- if (format === "markdown") {
847
- process.stdout.write(`- **success:** ${stripAnsi(msg)}
848
- `);
849
- return;
1037
+ let prompt = documentPrompt;
1038
+ let source = prompt === void 0 || prompt === "" ? void 0 : documentLayer.source;
1039
+ const consumedBaseIndexes = /* @__PURE__ */ new Set();
1040
+ for (const [index, layer] of baseLayers.entries()) {
1041
+ const candidate = layer.data.prompt;
1042
+ if (candidate === void 0) {
1043
+ continue;
1044
+ }
1045
+ if (typeof candidate !== "string") {
1046
+ break;
1047
+ }
1048
+ assertValidYieldCount(candidate);
1049
+ consumedBaseIndexes.add(index);
1050
+ prompt = composeAdjacentPrompts(prompt, candidate);
1051
+ if (source === void 0 && candidate !== "") {
1052
+ source = layer.source;
1053
+ }
850
1054
  }
851
- if (format === "json") {
852
- process.stdout.write(
853
- `${JSON.stringify({ level: "success", message: stripAnsi(msg) })}
854
- `
855
- );
856
- return;
1055
+ if (prompt !== void 0 && prompt.includes(YIELD_TOKEN)) {
1056
+ throw new Error('Final resolved prompt contains an unresolved "{{yield}}" token.');
857
1057
  }
858
- message(msg, { symbol: symbols.success });
859
- }
860
- function warn(msg) {
861
- const format = resolveOutputFormat();
862
- if (format === "markdown") {
863
- process.stdout.write(`- **warning:** ${stripAnsi(msg)}
864
- `);
865
- return;
866
- }
867
- if (format === "json") {
868
- process.stdout.write(
869
- `${JSON.stringify({ level: "warn", message: stripAnsi(msg) })}
870
- `
871
- );
872
- return;
1058
+ if (prompt === void 0) {
1059
+ return void 0;
873
1060
  }
874
- message(msg, { symbol: chalk5.yellow("\u25B2") });
1061
+ return {
1062
+ consumedBaseIndexes,
1063
+ prompt,
1064
+ source
1065
+ };
875
1066
  }
876
- function error(msg) {
877
- const format = resolveOutputFormat();
878
- if (format === "markdown") {
879
- process.stdout.write(`- **error:** ${stripAnsi(msg)}
880
- `);
881
- return;
1067
+ function composeAdjacentPrompts(high, low) {
1068
+ if (high === void 0 || high === "") {
1069
+ return low.includes(YIELD_TOKEN) ? replaceYield(low, "") : low;
882
1070
  }
883
- if (format === "json") {
884
- process.stdout.write(
885
- `${JSON.stringify({ level: "error", message: stripAnsi(msg) })}
886
- `
887
- );
888
- return;
1071
+ if (high.includes(YIELD_TOKEN)) {
1072
+ return replaceYield(high, low);
889
1073
  }
890
- message(msg, { symbol: chalk5.red("\u25A0") });
1074
+ if (low.includes(YIELD_TOKEN)) {
1075
+ return replaceYield(low, high);
1076
+ }
1077
+ return high;
891
1078
  }
892
- var log = {
893
- info,
894
- success,
895
- message,
896
- warn,
897
- error
898
- };
899
-
900
- // packages/design-system/src/components/logger.ts
901
- function createLogger(emitter) {
902
- const emit = (level, message2) => {
903
- if (emitter) {
904
- emitter(message2);
905
- return;
906
- }
907
- if (level === "success") {
908
- log.success(message2);
909
- return;
910
- }
911
- if (level === "warn") {
912
- log.warn(message2);
913
- return;
914
- }
915
- if (level === "error") {
916
- log.error(message2);
917
- return;
918
- }
919
- log.info(message2);
920
- };
921
- return {
922
- info(message2) {
923
- emit("info", message2);
924
- },
925
- success(message2) {
926
- emit("success", message2);
927
- },
928
- warn(message2) {
929
- emit("warn", message2);
930
- },
931
- error(message2) {
932
- emit("error", message2);
933
- },
934
- resolved(label, value) {
935
- if (emitter) {
936
- emitter(`${label}: ${value}`);
937
- return;
938
- }
939
- log.message(`${label}
940
- ${value}`, { symbol: symbols.resolved });
941
- },
942
- errorResolved(label, value) {
943
- if (emitter) {
944
- emitter(`${label}: ${value}`);
945
- return;
946
- }
947
- log.message(`${label}
948
- ${value}`, { symbol: symbols.errorResolved });
949
- },
950
- message(message2, symbol) {
951
- if (emitter) {
952
- emitter(message2);
953
- return;
954
- }
955
- log.message(message2, { symbol: symbol ?? chalk6.gray("\u2502") });
956
- }
957
- };
1079
+ function replaceYield(prompt, replacement) {
1080
+ return prompt.replace(YIELD_TOKEN, replacement);
958
1081
  }
959
- var logger = createLogger();
960
-
961
- // packages/design-system/src/components/table.ts
962
- import { Table } from "console-table-printer";
963
-
964
- // packages/design-system/src/acp/components.ts
965
- import chalk7 from "chalk";
966
-
967
- // packages/design-system/src/acp/writer.ts
968
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
969
- var storage = new AsyncLocalStorage2();
970
-
971
- // packages/design-system/src/acp/components.ts
972
- var AGENT_PREFIX = `${chalk7.green.bold("\u2713")} agent: `;
973
-
974
- // packages/design-system/src/dashboard/buffer.ts
975
- import chalk8 from "chalk";
976
-
977
- // packages/design-system/src/dashboard/terminal.ts
978
- import readline from "node:readline";
979
- import { PassThrough } from "node:stream";
980
-
981
- // packages/design-system/src/prompts/index.ts
982
- import chalk15 from "chalk";
983
- import * as clack from "@clack/prompts";
984
-
985
- // packages/design-system/src/prompts/primitives/cancel.ts
986
- import chalk9 from "chalk";
987
- import { isCancel } from "@clack/prompts";
988
-
989
- // packages/design-system/src/prompts/primitives/intro.ts
990
- import chalk10 from "chalk";
991
-
992
- // packages/design-system/src/prompts/primitives/note.ts
993
- import chalk11 from "chalk";
994
-
995
- // packages/design-system/src/prompts/primitives/outro.ts
996
- import chalk12 from "chalk";
997
-
998
- // packages/design-system/src/prompts/primitives/spinner.ts
999
- import chalk14 from "chalk";
1000
-
1001
- // packages/design-system/src/static/spinner.ts
1002
- import chalk13 from "chalk";
1003
-
1004
- // packages/design-system/src/static/menu.ts
1005
- import chalk16 from "chalk";
1006
-
1007
- // packages/agent-spawn/src/autonomous.ts
1008
- var DEFAULT_ACTIVITY_TIMEOUT_MS = 10 * 60 * 1e3;
1009
-
1010
- // packages/agent-spawn/src/acp/replay.ts
1011
- import path2 from "node:path";
1012
- import { homedir as homedir2 } from "node:os";
1013
- import { open, readdir } from "node:fs/promises";
1014
- import { createInterface } from "node:readline";
1015
-
1016
- // packages/poe-acp-client/src/acp-client.ts
1017
- import { isAbsolute } from "node:path";
1018
-
1019
- // packages/poe-acp-client/src/acp-transport.ts
1020
- import {
1021
- spawn as spawnChildProcess3
1022
- } from "node:child_process";
1023
-
1024
- // packages/poe-acp-client/src/run-report.ts
1025
- import * as fsPromises from "node:fs/promises";
1026
- import { homedir } from "node:os";
1027
- import { join } from "node:path";
1028
-
1029
- // packages/agent-spawn/src/acp/spawn.ts
1030
- import { spawn as spawnChildProcess4 } from "node:child_process";
1031
-
1032
- // packages/agent-spawn/src/acp/middlewares/spawn-log.ts
1033
- import path3 from "node:path";
1034
- import { homedir as homedir3 } from "node:os";
1035
- import { mkdir, open as open2 } from "node:fs/promises";
1036
-
1037
- // src/utils/command-checks.ts
1038
- function formatCommandRunnerResult(result) {
1039
- const stdout = result.stdout.length > 0 ? result.stdout : "<empty>";
1040
- const stderr = result.stderr.length > 0 ? result.stderr : "<empty>";
1041
- return `stdout:
1042
- ${stdout}
1043
- stderr:
1044
- ${stderr}`;
1082
+ function assertValidYieldCount(prompt) {
1083
+ if (countYieldTokens(prompt) > 1) {
1084
+ throw new Error('Prompt composition supports exactly one "{{yield}}" token per prompt.');
1085
+ }
1045
1086
  }
1046
- function createSpawnHealthCheck(agentId, options) {
1047
- const prompt = `Output exactly: ${options.expectedOutput}`;
1048
- const { binaryName, args, env: modeEnv } = buildSpawnArgs(agentId, {
1049
- prompt,
1050
- model: options.model,
1051
- mode: "yolo"
1052
- });
1087
+ function countYieldTokens(prompt) {
1088
+ return prompt.split(YIELD_TOKEN).length - 1;
1089
+ }
1090
+ function withResolvedPrompt(data, prompt) {
1091
+ if (prompt === void 0) {
1092
+ return data;
1093
+ }
1053
1094
  return {
1054
- id: `${agentId}-cli-health`,
1055
- description: `spawn ${agentId} (expecting "${options.expectedOutput}")`,
1056
- async run(context) {
1057
- if (context.isDryRun) {
1058
- context.logDryRun?.(
1059
- `Dry run: ${[binaryName, ...args].join(" ")} (expecting "${options.expectedOutput}")`
1060
- );
1061
- return;
1062
- }
1063
- const result = modeEnv ? await context.runCommand(binaryName, args, { env: modeEnv }) : await context.runCommand(binaryName, args);
1064
- if (result.exitCode !== 0) {
1065
- throw new Error(
1066
- `spawn ${agentId} failed with exit code ${result.exitCode}.
1067
- ${formatCommandRunnerResult(result)}`
1068
- );
1069
- }
1070
- if (!result.stdout.includes(options.expectedOutput)) {
1071
- throw new Error(
1072
- `spawn ${agentId}: expected "${options.expectedOutput}" in stdout.
1073
- ${formatCommandRunnerResult(result)}`
1074
- );
1075
- }
1076
- }
1095
+ ...data,
1096
+ prompt
1077
1097
  };
1078
1098
  }
1079
- function createBinaryExistsCheck(binaryName, id, description) {
1080
- return {
1081
- id,
1082
- description,
1083
- async run({ runCommand: runCommand2 }) {
1084
- const commonPaths = [
1085
- `/usr/local/bin/${binaryName}`,
1086
- `/usr/bin/${binaryName}`,
1087
- `$HOME/.local/bin/${binaryName}`,
1088
- `$HOME/.claude/local/bin/${binaryName}`
1089
- ];
1090
- const detectors = [
1091
- {
1092
- command: "which",
1093
- args: [binaryName],
1094
- validate: (result) => result.exitCode === 0
1095
- },
1096
- {
1097
- command: "where",
1098
- args: [binaryName],
1099
- validate: (result) => result.exitCode === 0 && result.stdout.trim().length > 0
1100
- },
1101
- // Check common installation paths using shell expansion for $HOME
1102
- {
1103
- command: "sh",
1104
- args: [
1105
- "-c",
1106
- commonPaths.map((p) => `test -f "${p}"`).join(" || ")
1107
- ],
1108
- validate: (result) => result.exitCode === 0
1109
- }
1110
- ];
1111
- for (const detector of detectors) {
1112
- const result = await runCommand2(detector.command, detector.args);
1113
- if (detector.validate(result)) {
1114
- return;
1115
- }
1116
- }
1117
- throw new Error(`${binaryName} CLI binary not found on PATH.`);
1099
+ function stripResolvedBasePrompts(layers, consumedBaseIndexes) {
1100
+ return layers.map((layer, index) => {
1101
+ if (!consumedBaseIndexes.has(index) || typeof layer.data.prompt !== "string") {
1102
+ return layer;
1118
1103
  }
1119
- };
1104
+ const { prompt: ignoredPrompt, ...data } = layer.data;
1105
+ void ignoredPrompt;
1106
+ return {
1107
+ source: layer.source,
1108
+ data
1109
+ };
1110
+ });
1111
+ }
1112
+ function getBaseName(filePath) {
1113
+ return path6.basename(filePath, path6.extname(filePath));
1114
+ }
1115
+ function shouldResolveBase(parsedDocument, autoExtend) {
1116
+ return parsedDocument.extends || autoExtend === true && !parsedDocument.hasExtendsField;
1117
+ }
1118
+ function isBaseNotFoundError(error2) {
1119
+ return error2 instanceof Error && error2.message.startsWith('Base "') && error2.message.includes('" not found.\nChecked paths:');
1120
+ }
1121
+ function isDataLayer(layer) {
1122
+ return "data" in layer;
1123
+ }
1124
+ function isDocumentLayer(layer) {
1125
+ return "filePath" in layer && "content" in layer;
1126
+ }
1127
+ function isBaseLayer(layer) {
1128
+ return "path" in layer;
1120
1129
  }
1121
1130
 
1122
1131
  // packages/config-mutations/src/mutations/config-mutation.ts
@@ -1211,7 +1220,7 @@ import * as jsonc from "jsonc-parser";
1211
1220
  function isConfigObject(value) {
1212
1221
  return typeof value === "object" && value !== null && !Array.isArray(value);
1213
1222
  }
1214
- function parse3(content) {
1223
+ function parse2(content) {
1215
1224
  if (!content || content.trim() === "") {
1216
1225
  return {};
1217
1226
  }
@@ -1284,7 +1293,7 @@ function prune2(obj, shape) {
1284
1293
  return { changed, result };
1285
1294
  }
1286
1295
  var jsonFormat = {
1287
- parse: parse3,
1296
+ parse: parse2,
1288
1297
  serialize,
1289
1298
  merge: merge2,
1290
1299
  prune: prune2
@@ -1295,7 +1304,7 @@ import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
1295
1304
  function isConfigObject2(value) {
1296
1305
  return typeof value === "object" && value !== null && !Array.isArray(value);
1297
1306
  }
1298
- function parse4(content) {
1307
+ function parse3(content) {
1299
1308
  if (!content || content.trim() === "") {
1300
1309
  return {};
1301
1310
  }
@@ -1359,22 +1368,22 @@ function prune3(obj, shape) {
1359
1368
  return { changed, result };
1360
1369
  }
1361
1370
  var tomlFormat = {
1362
- parse: parse4,
1371
+ parse: parse3,
1363
1372
  serialize: serialize2,
1364
1373
  merge: merge3,
1365
1374
  prune: prune3
1366
1375
  };
1367
1376
 
1368
1377
  // packages/config-mutations/src/formats/yaml.ts
1369
- import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
1378
+ import { parse as parseYaml2, stringify as stringifyYaml } from "yaml";
1370
1379
  function isConfigObject3(value) {
1371
1380
  return typeof value === "object" && value !== null && !Array.isArray(value);
1372
1381
  }
1373
- function parse5(content) {
1382
+ function parse4(content) {
1374
1383
  if (!content || content.trim() === "") {
1375
1384
  return {};
1376
1385
  }
1377
- const parsed = parseYaml(content);
1386
+ const parsed = parseYaml2(content);
1378
1387
  if (parsed === null || parsed === void 0) {
1379
1388
  return {};
1380
1389
  }
@@ -1434,7 +1443,7 @@ function prune4(obj, shape) {
1434
1443
  return { changed, result };
1435
1444
  }
1436
1445
  var yamlFormat = {
1437
- parse: parse5,
1446
+ parse: parse4,
1438
1447
  serialize: serialize3,
1439
1448
  merge: merge4,
1440
1449
  prune: prune4
@@ -1465,20 +1474,20 @@ function getConfigFormat(pathOrFormat) {
1465
1474
  }
1466
1475
  return formatRegistry[formatName];
1467
1476
  }
1468
- function detectFormat(path5) {
1469
- const ext = getExtension(path5);
1477
+ function detectFormat2(path22) {
1478
+ const ext = getExtension(path22);
1470
1479
  return extensionMap[ext];
1471
1480
  }
1472
- function getExtension(path5) {
1473
- const lastDot = path5.lastIndexOf(".");
1481
+ function getExtension(path22) {
1482
+ const lastDot = path22.lastIndexOf(".");
1474
1483
  if (lastDot === -1) {
1475
1484
  return "";
1476
1485
  }
1477
- return path5.slice(lastDot).toLowerCase();
1486
+ return path22.slice(lastDot).toLowerCase();
1478
1487
  }
1479
1488
 
1480
1489
  // packages/config-mutations/src/execution/path-utils.ts
1481
- import path4 from "node:path";
1490
+ import path7 from "node:path";
1482
1491
  function expandHome(targetPath, homeDir) {
1483
1492
  if (!targetPath?.startsWith("~")) {
1484
1493
  return targetPath;
@@ -1495,7 +1504,7 @@ function expandHome(targetPath, homeDir) {
1495
1504
  remainder = remainder.slice(1);
1496
1505
  }
1497
1506
  }
1498
- return remainder.length === 0 ? homeDir : path4.join(homeDir, remainder);
1507
+ return remainder.length === 0 ? homeDir : path7.join(homeDir, remainder);
1499
1508
  }
1500
1509
  function validateHomePath(targetPath) {
1501
1510
  if (typeof targetPath !== "string" || targetPath.length === 0) {
@@ -1513,19 +1522,19 @@ function resolvePath(rawPath, homeDir, pathMapper) {
1513
1522
  if (!pathMapper) {
1514
1523
  return expanded;
1515
1524
  }
1516
- const rawDirectory = path4.dirname(expanded);
1525
+ const rawDirectory = path7.dirname(expanded);
1517
1526
  const mappedDirectory = pathMapper.mapTargetDirectory({
1518
1527
  targetDirectory: rawDirectory
1519
1528
  });
1520
- const filename = path4.basename(expanded);
1521
- return filename.length === 0 ? mappedDirectory : path4.join(mappedDirectory, filename);
1529
+ const filename = path7.basename(expanded);
1530
+ return filename.length === 0 ? mappedDirectory : path7.join(mappedDirectory, filename);
1522
1531
  }
1523
1532
 
1524
1533
  // packages/config-mutations/src/fs-utils.ts
1525
1534
  function isNotFound(error2) {
1526
1535
  return typeof error2 === "object" && error2 !== null && "code" in error2 && error2.code === "ENOENT";
1527
1536
  }
1528
- async function readFileIfExists(fs, target) {
1537
+ async function readFileIfExists2(fs, target) {
1529
1538
  try {
1530
1539
  return await fs.readFile(target, "utf8");
1531
1540
  } catch (error2) {
@@ -1776,8 +1785,8 @@ async function applyChmod(mutation, context, options) {
1776
1785
  };
1777
1786
  }
1778
1787
  try {
1779
- const stat = await context.fs.stat(targetPath);
1780
- const currentMode = typeof stat.mode === "number" ? stat.mode & 511 : null;
1788
+ const stat2 = await context.fs.stat(targetPath);
1789
+ const currentMode = typeof stat2.mode === "number" ? stat2.mode & 511 : null;
1781
1790
  if (currentMode === mutation.mode) {
1782
1791
  return {
1783
1792
  outcome: { changed: false, effect: "none", detail: "noop" },
@@ -1809,7 +1818,7 @@ async function applyBackup(mutation, context, options) {
1809
1818
  label: mutation.label ?? describeMutation(mutation.kind, targetPath),
1810
1819
  targetPath
1811
1820
  };
1812
- const content = await readFileIfExists(context.fs, targetPath);
1821
+ const content = await readFileIfExists2(context.fs, targetPath);
1813
1822
  if (content === null) {
1814
1823
  return {
1815
1824
  outcome: { changed: false, effect: "none", detail: "noop" },
@@ -1833,14 +1842,14 @@ async function applyConfigMerge(mutation, context, options) {
1833
1842
  label: mutation.label ?? describeMutation(mutation.kind, targetPath),
1834
1843
  targetPath
1835
1844
  };
1836
- const formatName = mutation.format ?? detectFormat(rawPath);
1845
+ const formatName = mutation.format ?? detectFormat2(rawPath);
1837
1846
  if (!formatName) {
1838
1847
  throw new Error(
1839
1848
  `Cannot detect config format for "${rawPath}". Provide explicit format option.`
1840
1849
  );
1841
1850
  }
1842
1851
  const format = getConfigFormat(formatName);
1843
- const rawContent = await readFileIfExists(context.fs, targetPath);
1852
+ const rawContent = await readFileIfExists2(context.fs, targetPath);
1844
1853
  let current;
1845
1854
  try {
1846
1855
  current = rawContent === null ? {} : format.parse(rawContent);
@@ -1879,14 +1888,14 @@ async function applyConfigPrune(mutation, context, options) {
1879
1888
  label: mutation.label ?? describeMutation(mutation.kind, targetPath),
1880
1889
  targetPath
1881
1890
  };
1882
- const rawContent = await readFileIfExists(context.fs, targetPath);
1891
+ const rawContent = await readFileIfExists2(context.fs, targetPath);
1883
1892
  if (rawContent === null) {
1884
1893
  return {
1885
1894
  outcome: { changed: false, effect: "none", detail: "noop" },
1886
1895
  details
1887
1896
  };
1888
1897
  }
1889
- const formatName = mutation.format ?? detectFormat(rawPath);
1898
+ const formatName = mutation.format ?? detectFormat2(rawPath);
1890
1899
  if (!formatName) {
1891
1900
  throw new Error(
1892
1901
  `Cannot detect config format for "${rawPath}". Provide explicit format option.`
@@ -1942,14 +1951,14 @@ async function applyConfigTransform(mutation, context, options) {
1942
1951
  label: mutation.label ?? describeMutation(mutation.kind, targetPath),
1943
1952
  targetPath
1944
1953
  };
1945
- const formatName = mutation.format ?? detectFormat(rawPath);
1954
+ const formatName = mutation.format ?? detectFormat2(rawPath);
1946
1955
  if (!formatName) {
1947
1956
  throw new Error(
1948
1957
  `Cannot detect config format for "${rawPath}". Provide explicit format option.`
1949
1958
  );
1950
1959
  }
1951
1960
  const format = getConfigFormat(formatName);
1952
- const rawContent = await readFileIfExists(context.fs, targetPath);
1961
+ const rawContent = await readFileIfExists2(context.fs, targetPath);
1953
1962
  let current;
1954
1963
  try {
1955
1964
  current = rawContent === null ? {} : format.parse(rawContent);
@@ -2049,7 +2058,7 @@ async function applyTemplateMerge(mutation, context, options, formatName) {
2049
2058
  { cause: error2 }
2050
2059
  );
2051
2060
  }
2052
- const rawContent = await readFileIfExists(context.fs, targetPath);
2061
+ const rawContent = await readFileIfExists2(context.fs, targetPath);
2053
2062
  let current;
2054
2063
  try {
2055
2064
  current = rawContent === null ? {} : format.parse(rawContent);
@@ -2124,6 +2133,2631 @@ async function executeMutation(mutation, context, options) {
2124
2133
  import Mustache2 from "mustache";
2125
2134
  var originalEscape = Mustache2.escape;
2126
2135
 
2136
+ // packages/poe-code-config/src/store.ts
2137
+ async function readMergedDocument(fs, globalPath, projectPath) {
2138
+ const globalDocument = await readStoredDocument(fs, globalPath);
2139
+ if (!projectPath || projectPath === globalPath) {
2140
+ return globalDocument.data;
2141
+ }
2142
+ const projectDocument = await readStoredDocument(fs, projectPath);
2143
+ const resolved = await resolve(
2144
+ [
2145
+ {
2146
+ source: "project",
2147
+ filePath: projectPath,
2148
+ content: projectDocument.content
2149
+ },
2150
+ {
2151
+ source: "base",
2152
+ path: path8.dirname(globalPath)
2153
+ }
2154
+ ],
2155
+ {
2156
+ fs: createResolvedConfigFs(fs, globalPath, globalDocument.content),
2157
+ autoExtend: true
2158
+ }
2159
+ );
2160
+ return normalizeDocument(resolved.data);
2161
+ }
2162
+ async function readStoredDocument(fs, filePath) {
2163
+ try {
2164
+ const raw = await fs.readFile(filePath, "utf8");
2165
+ return await parseStoredDocument(fs, filePath, raw);
2166
+ } catch (error2) {
2167
+ if (isNotFound(error2)) {
2168
+ return {
2169
+ content: EMPTY_DOCUMENT,
2170
+ data: {}
2171
+ };
2172
+ }
2173
+ throw error2;
2174
+ }
2175
+ }
2176
+ async function parseStoredDocument(fs, filePath, raw) {
2177
+ try {
2178
+ return {
2179
+ content: raw,
2180
+ data: normalizeDocument(JSON.parse(raw))
2181
+ };
2182
+ } catch (error2) {
2183
+ if (error2 instanceof SyntaxError) {
2184
+ await recoverInvalidDocument(fs, filePath, raw);
2185
+ return {
2186
+ content: EMPTY_DOCUMENT,
2187
+ data: {}
2188
+ };
2189
+ }
2190
+ throw error2;
2191
+ }
2192
+ }
2193
+ function normalizeDocument(value) {
2194
+ if (!isRecord2(value)) {
2195
+ return {};
2196
+ }
2197
+ const document = {};
2198
+ for (const [scope, scopeValues] of Object.entries(value)) {
2199
+ const normalizedValues = normalizeScopeValues(scopeValues);
2200
+ if (Object.keys(normalizedValues).length > 0) {
2201
+ document[scope] = normalizedValues;
2202
+ }
2203
+ }
2204
+ return document;
2205
+ }
2206
+ function normalizeScopeValues(value) {
2207
+ if (!isRecord2(value)) {
2208
+ return {};
2209
+ }
2210
+ const normalized = {};
2211
+ for (const [key, entry] of Object.entries(value)) {
2212
+ if (entry !== void 0) {
2213
+ normalized[key] = entry;
2214
+ }
2215
+ }
2216
+ return normalized;
2217
+ }
2218
+ function createResolvedConfigFs(fs, globalPath, globalContent) {
2219
+ return {
2220
+ readFile(filePath, _encoding) {
2221
+ if (filePath === globalPath) {
2222
+ return Promise.resolve(globalContent);
2223
+ }
2224
+ return fs.readFile(filePath, "utf8");
2225
+ }
2226
+ };
2227
+ }
2228
+ async function recoverInvalidDocument(fs, filePath, content) {
2229
+ await fs.mkdir(path8.dirname(filePath), { recursive: true });
2230
+ const backupPath = createInvalidBackupPath(filePath);
2231
+ await fs.writeFile(backupPath, content, { encoding: "utf8" });
2232
+ await fs.writeFile(filePath, EMPTY_DOCUMENT, { encoding: "utf8" });
2233
+ }
2234
+ function createInvalidBackupPath(filePath) {
2235
+ const directory = path8.dirname(filePath);
2236
+ const baseName = path8.basename(filePath);
2237
+ return path8.join(directory, `${baseName}.invalid-${createTimestamp()}.json`);
2238
+ }
2239
+ function isRecord2(value) {
2240
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
2241
+ }
2242
+ function resolveConfigPath(homeDir) {
2243
+ return path8.join(homeDir, ".poe-code", "config.json");
2244
+ }
2245
+ function resolveProjectConfigPath(cwd) {
2246
+ return path8.join(cwd, ".poe-code", "config.json");
2247
+ }
2248
+ var EMPTY_DOCUMENT = `${JSON.stringify({}, null, 2)}
2249
+ `;
2250
+
2251
+ // packages/poe-code-config/src/resolve.ts
2252
+ function resolveScope(schema, fileValues, env = {}) {
2253
+ const resolved = {};
2254
+ for (const key of Object.keys(schema)) {
2255
+ const field = schema[key];
2256
+ const envValue = resolveEnvValue(field, env, key);
2257
+ const fileValue = resolveFileValue(field, fileValues?.[key], key);
2258
+ resolved[key] = envValue ?? fileValue ?? field.default;
2259
+ }
2260
+ return resolved;
2261
+ }
2262
+ function resolveEnvValue(field, env, key) {
2263
+ if (!field.env) {
2264
+ return void 0;
2265
+ }
2266
+ const raw = env[field.env];
2267
+ if (raw === void 0) {
2268
+ return void 0;
2269
+ }
2270
+ return coerceValue(field, raw, key);
2271
+ }
2272
+ function resolveFileValue(field, value, key) {
2273
+ return coerceValue(field, value, key);
2274
+ }
2275
+ function coerceValue(field, value, key) {
2276
+ switch (field.type) {
2277
+ case "string":
2278
+ return typeof value === "string" ? value : void 0;
2279
+ case "number":
2280
+ return coerceNumber(value);
2281
+ case "boolean":
2282
+ return coerceBoolean(value);
2283
+ case "json":
2284
+ return coerceJson(field, value, key);
2285
+ }
2286
+ }
2287
+ function coerceNumber(value) {
2288
+ if (typeof value === "number" && Number.isFinite(value)) {
2289
+ return value;
2290
+ }
2291
+ if (typeof value !== "string" || value.length === 0) {
2292
+ return void 0;
2293
+ }
2294
+ const parsed = Number(value);
2295
+ return Number.isNaN(parsed) ? void 0 : parsed;
2296
+ }
2297
+ function coerceBoolean(value) {
2298
+ if (typeof value === "boolean") {
2299
+ return value;
2300
+ }
2301
+ if (value === "true" || value === "1") {
2302
+ return true;
2303
+ }
2304
+ if (value === "false" || value === "0") {
2305
+ return false;
2306
+ }
2307
+ return void 0;
2308
+ }
2309
+ function coerceJson(field, value, key) {
2310
+ if (value === void 0) {
2311
+ return void 0;
2312
+ }
2313
+ const parsedValue = parseJsonValue(value, key);
2314
+ try {
2315
+ return field.parse(parsedValue);
2316
+ } catch (error2) {
2317
+ const message2 = error2 instanceof Error ? error2.message : "Invalid JSON value.";
2318
+ throw new Error(`Invalid config value for "${key}": ${message2}`);
2319
+ }
2320
+ }
2321
+ function parseJsonValue(value, key) {
2322
+ if (typeof value !== "string") {
2323
+ return value;
2324
+ }
2325
+ try {
2326
+ return JSON.parse(value);
2327
+ } catch {
2328
+ throw new Error(`Invalid config value for "${key}": expected valid JSON.`);
2329
+ }
2330
+ }
2331
+
2332
+ // packages/poe-code-config/src/inspect.ts
2333
+ import path9 from "node:path";
2334
+ var EMPTY_DOCUMENT2 = `${JSON.stringify({}, null, 2)}
2335
+ `;
2336
+
2337
+ // packages/poe-code-config/src/state/index.ts
2338
+ import os2 from "node:os";
2339
+
2340
+ // packages/poe-code-config/src/state/jobs.ts
2341
+ import path10 from "node:path";
2342
+
2343
+ // packages/poe-code-config/src/state/fs.ts
2344
+ import * as nodeFs2 from "node:fs/promises";
2345
+
2346
+ // packages/poe-code-config/src/state/templates.ts
2347
+ import path11 from "node:path";
2348
+
2349
+ // packages/agent-harness-tools/src/execution-env.ts
2350
+ var executionEnvFactories = /* @__PURE__ */ new Map();
2351
+ function registerExecutionEnvFactory(factory) {
2352
+ executionEnvFactories.set(factory.type, factory);
2353
+ }
2354
+
2355
+ // packages/agent-harness-tools/src/workspace-transfer.ts
2356
+ import { createHash } from "node:crypto";
2357
+ import { promises as nodeFs3 } from "node:fs";
2358
+ import path12 from "node:path";
2359
+
2360
+ // packages/process-runner/src/docker/context.ts
2361
+ import { execSync } from "node:child_process";
2362
+ function detectContext() {
2363
+ try {
2364
+ const output = execSync("colima list --json", {
2365
+ encoding: "utf-8",
2366
+ stdio: ["pipe", "pipe", "ignore"]
2367
+ });
2368
+ const lines = output.trim().split("\n").filter(Boolean);
2369
+ for (const line of lines) {
2370
+ const profile = JSON.parse(line);
2371
+ if (profile.status === "Running" && profile.runtime === "docker") {
2372
+ const name = profile.name ?? profile.profile;
2373
+ if (!name) {
2374
+ continue;
2375
+ }
2376
+ return name === "default" ? "colima" : `colima-${name}`;
2377
+ }
2378
+ }
2379
+ } catch {
2380
+ return null;
2381
+ }
2382
+ return null;
2383
+ }
2384
+ function buildContextArgs(engine, context) {
2385
+ if (engine === "docker" && context) {
2386
+ return ["--context", context];
2387
+ }
2388
+ return [];
2389
+ }
2390
+
2391
+ // packages/process-runner/src/docker/engine.ts
2392
+ import { execSync as execSync2 } from "node:child_process";
2393
+ function detectEngine() {
2394
+ if (isEngineAvailable("docker")) {
2395
+ return "docker";
2396
+ }
2397
+ if (isEngineAvailable("podman")) {
2398
+ return "podman";
2399
+ }
2400
+ throw new Error(
2401
+ "No container engine found. Please install Docker or Podman:\n - Docker Desktop: https://www.docker.com/products/docker-desktop\n - Colima (macOS): brew install colima && colima start\n - Podman: https://podman.io/docs/installation"
2402
+ );
2403
+ }
2404
+ function isEngineAvailable(engine) {
2405
+ try {
2406
+ execSync2(`${engine} --version`, {
2407
+ stdio: "ignore"
2408
+ });
2409
+ return true;
2410
+ } catch {
2411
+ return false;
2412
+ }
2413
+ }
2414
+
2415
+ // packages/process-runner/src/docker/docker-runner.ts
2416
+ import * as childProcess from "node:child_process";
2417
+ import { randomBytes as randomBytes2 } from "node:crypto";
2418
+
2419
+ // packages/process-runner/src/docker/args.ts
2420
+ import path13 from "node:path";
2421
+ function buildDockerRunArgs(input) {
2422
+ const args = [input.engine];
2423
+ if (input.engine === "docker" && input.context) {
2424
+ args.push("--context", input.context);
2425
+ }
2426
+ args.push("run");
2427
+ if (input.rm) {
2428
+ args.push("--rm");
2429
+ }
2430
+ if (input.detached) {
2431
+ args.push("-d");
2432
+ }
2433
+ if (input.interactive) {
2434
+ args.push("-i");
2435
+ }
2436
+ if (input.tty) {
2437
+ args.push("-t");
2438
+ }
2439
+ args.push("--name", input.containerName);
2440
+ if (input.cwd !== void 0) {
2441
+ args.push("-w", input.cwd);
2442
+ }
2443
+ for (const [key, value] of Object.entries(input.env ?? {})) {
2444
+ args.push("-e", `${key}=${value}`);
2445
+ }
2446
+ for (const mount of input.mounts) {
2447
+ const volume = `${path13.resolve(mount.source)}:${mount.target}${mount.readonly ? ":ro" : ""}`;
2448
+ args.push("-v", volume);
2449
+ }
2450
+ for (const port of input.ports) {
2451
+ const mapping = `${port.host}:${port.container}${port.protocol === void 0 || port.protocol === "tcp" ? "" : `/${port.protocol}`}`;
2452
+ args.push("-p", mapping);
2453
+ }
2454
+ if (input.network !== void 0) {
2455
+ args.push("--network", input.network);
2456
+ }
2457
+ args.push(...input.extraArgs, input.image, input.command, ...input.args);
2458
+ return args;
2459
+ }
2460
+
2461
+ // packages/process-runner/src/docker/docker-execution-env.ts
2462
+ import { createHash as createHash2, randomBytes as randomBytes3 } from "node:crypto";
2463
+ import { mkdtempSync, rmSync } from "node:fs";
2464
+ import { readFile as readFile2 } from "node:fs/promises";
2465
+ import { tmpdir } from "node:os";
2466
+ import path14 from "node:path";
2467
+
2468
+ // packages/process-runner/src/host/host-runner.ts
2469
+ import { spawn as spawnChildProcess } from "node:child_process";
2470
+ function createHostRunner(options = {}) {
2471
+ const detached = options.detached === true;
2472
+ return {
2473
+ name: "host",
2474
+ exec(spec) {
2475
+ const stdinMode = spec.stdin ?? "ignore";
2476
+ const stdoutMode = spec.stdout ?? "pipe";
2477
+ const stderrMode = spec.stderr ?? "pipe";
2478
+ const stdio = stdinMode === "inherit" && stdoutMode === "inherit" && stderrMode === "inherit" ? "inherit" : [stdinMode, stdoutMode, stderrMode];
2479
+ const child = spawnChildProcess(spec.command, spec.args ?? [], {
2480
+ cwd: spec.cwd,
2481
+ env: spec.env,
2482
+ stdio,
2483
+ ...detached ? { detached: true } : {}
2484
+ });
2485
+ if (detached) {
2486
+ child.unref();
2487
+ }
2488
+ const kill = (signal) => {
2489
+ if (detached && process.platform !== "win32" && child.pid !== void 0) {
2490
+ process.kill(-child.pid, signal);
2491
+ return;
2492
+ }
2493
+ child.kill(signal);
2494
+ };
2495
+ let settled = false;
2496
+ let resolveResult = null;
2497
+ const result = new Promise((resolve2) => {
2498
+ resolveResult = resolve2;
2499
+ });
2500
+ const cleanupAbort = bindAbortSignal(spec.signal, () => {
2501
+ kill("SIGTERM");
2502
+ });
2503
+ child.once("close", (code) => {
2504
+ if (settled) return;
2505
+ settled = true;
2506
+ cleanupAbort();
2507
+ resolveResult?.({ exitCode: code ?? 1 });
2508
+ });
2509
+ child.once("error", () => {
2510
+ if (settled) return;
2511
+ settled = true;
2512
+ cleanupAbort();
2513
+ resolveResult?.({ exitCode: 1 });
2514
+ });
2515
+ return {
2516
+ pid: child.pid ?? null,
2517
+ stdin: child.stdin,
2518
+ stdout: child.stdout,
2519
+ stderr: child.stderr,
2520
+ result,
2521
+ kill
2522
+ };
2523
+ }
2524
+ };
2525
+ }
2526
+ function bindAbortSignal(signal, onAbort) {
2527
+ if (signal === void 0) {
2528
+ return () => {
2529
+ };
2530
+ }
2531
+ if (signal.aborted) {
2532
+ onAbort();
2533
+ return () => {
2534
+ };
2535
+ }
2536
+ signal.addEventListener("abort", onAbort, { once: true });
2537
+ return () => {
2538
+ signal.removeEventListener("abort", onAbort);
2539
+ };
2540
+ }
2541
+
2542
+ // packages/process-runner/src/docker/docker-execution-env.ts
2543
+ var containerCommand = ["sh", "-c", "while :; do sleep 3600; done"];
2544
+ var dockerExecutionEnvFactory = {
2545
+ type: "docker",
2546
+ supportsDetach: true,
2547
+ async open(spec) {
2548
+ const runtime = parseDockerRuntime(spec.runtime);
2549
+ const runner = spec.hostRunner ?? createHostRunner();
2550
+ const engine = runtime.engine ?? detectEngine();
2551
+ const context = detectContext();
2552
+ const image = await resolveImage({
2553
+ spec,
2554
+ runtime,
2555
+ runner,
2556
+ engine,
2557
+ context
2558
+ });
2559
+ const containerName = createContainerName();
2560
+ const runArgs = buildDockerRunArgs({
2561
+ engine,
2562
+ context,
2563
+ image,
2564
+ command: containerCommand[0],
2565
+ args: containerCommand.slice(1),
2566
+ cwd: void 0,
2567
+ env: void 0,
2568
+ mounts: runtime.mounts ?? [],
2569
+ ports: [],
2570
+ network: runtime.network,
2571
+ containerName,
2572
+ detached: true,
2573
+ interactive: true,
2574
+ tty: false,
2575
+ rm: false,
2576
+ extraArgs: runtime.extra_args ?? []
2577
+ });
2578
+ const [command, ...args] = runArgs;
2579
+ const id = (await runAndRead(runner, { command, args, stdout: "pipe", stderr: "pipe" })).trim();
2580
+ return createDockerEnv({
2581
+ id,
2582
+ spec,
2583
+ runner,
2584
+ engine,
2585
+ context
2586
+ });
2587
+ },
2588
+ async attach(envId, context) {
2589
+ const engine = detectEngine();
2590
+ return createDockerEnv({
2591
+ id: envId,
2592
+ spec: createAttachedSpec(context?.cwd),
2593
+ runner: createHostRunner(),
2594
+ engine,
2595
+ context: detectContext(),
2596
+ attachedJobId: context?.jobId
2597
+ });
2598
+ }
2599
+ };
2600
+ function createDockerEnv(input) {
2601
+ const containerRef = input.id;
2602
+ return {
2603
+ id: containerRef,
2604
+ job: input.attachedJobId === void 0 ? null : createContainerJob(containerRef, input.runner, input.engine, input.context, input.attachedJobId),
2605
+ async uploadWorkspace() {
2606
+ const tempDir = mkdtempSync(path14.join(tmpdir(), "poe-docker-upload-"));
2607
+ const archivePath = path14.join(tempDir, "workspace.tar");
2608
+ try {
2609
+ const excludeArgs = input.spec.uploadIgnoreFiles.flatMap((ignored) => [
2610
+ "--exclude",
2611
+ ignored
2612
+ ]);
2613
+ const tarArgs = [...excludeArgs, "-cf", archivePath, "-C", input.spec.cwd, "."];
2614
+ await runOrThrow(input.runner, {
2615
+ command: "tar",
2616
+ args: tarArgs,
2617
+ stdout: "pipe",
2618
+ stderr: "pipe"
2619
+ });
2620
+ await runOrThrow(input.runner, {
2621
+ command: input.engine,
2622
+ args: [
2623
+ ...buildContextArgs(input.engine, input.context),
2624
+ "cp",
2625
+ archivePath,
2626
+ `${containerRef}:/tmp/poe-workspace-upload.tar`
2627
+ ],
2628
+ stdout: "pipe",
2629
+ stderr: "pipe"
2630
+ });
2631
+ await runOrThrow(input.runner, {
2632
+ command: input.engine,
2633
+ args: [
2634
+ ...buildContextArgs(input.engine, input.context),
2635
+ "exec",
2636
+ containerRef,
2637
+ "sh",
2638
+ "-c",
2639
+ `mkdir -p ${shellQuote(input.spec.cwd)} && tar -xf /tmp/poe-workspace-upload.tar -C ${shellQuote(input.spec.cwd)}`
2640
+ ],
2641
+ stdout: "pipe",
2642
+ stderr: "pipe"
2643
+ });
2644
+ return { files: 0, bytes: 0, skipped: [] };
2645
+ } finally {
2646
+ rmSync(tempDir, { recursive: true, force: true });
2647
+ }
2648
+ },
2649
+ async downloadWorkspace(opts) {
2650
+ const tempDir = mkdtempSync(path14.join(tmpdir(), "poe-docker-download-"));
2651
+ const archivePath = path14.join(tempDir, "workspace.tar");
2652
+ try {
2653
+ await runOrThrow(input.runner, {
2654
+ command: input.engine,
2655
+ args: [
2656
+ ...buildContextArgs(input.engine, input.context),
2657
+ "exec",
2658
+ containerRef,
2659
+ "sh",
2660
+ "-c",
2661
+ `tar -cf /tmp/poe-workspace-download.tar -C ${shellQuote(input.spec.cwd)} .`
2662
+ ],
2663
+ stdout: "pipe",
2664
+ stderr: "pipe"
2665
+ });
2666
+ await runOrThrow(input.runner, {
2667
+ command: input.engine,
2668
+ args: [
2669
+ ...buildContextArgs(input.engine, input.context),
2670
+ "cp",
2671
+ `${containerRef}:/tmp/poe-workspace-download.tar`,
2672
+ archivePath
2673
+ ],
2674
+ stdout: "pipe",
2675
+ stderr: "pipe"
2676
+ });
2677
+ const extractMode = opts.conflictPolicy === "refuse" ? "-xkf" : "-xf";
2678
+ await runOrThrow(input.runner, {
2679
+ command: "tar",
2680
+ args: [extractMode, archivePath, "-C", input.spec.cwd],
2681
+ stdout: "pipe",
2682
+ stderr: "pipe"
2683
+ });
2684
+ return { files: 0, bytes: 0, conflicts: [] };
2685
+ } finally {
2686
+ rmSync(tempDir, { recursive: true, force: true });
2687
+ }
2688
+ },
2689
+ exec(spec) {
2690
+ return input.runner.exec({
2691
+ command: input.engine,
2692
+ args: [
2693
+ ...buildContextArgs(input.engine, input.context),
2694
+ "exec",
2695
+ ...spec.stdin === "pipe" || spec.stdin === "inherit" ? ["-i"] : [],
2696
+ ...spec.tty === true ? ["-t"] : [],
2697
+ ...spec.cwd !== void 0 ? ["-w", spec.cwd] : [],
2698
+ ...buildEnvArgs(spec.env),
2699
+ containerRef,
2700
+ spec.command,
2701
+ ...spec.args ?? []
2702
+ ],
2703
+ stdin: spec.stdin,
2704
+ stdout: spec.stdout,
2705
+ stderr: spec.stderr,
2706
+ tty: spec.tty
2707
+ });
2708
+ },
2709
+ async detach() {
2710
+ return createContainerJob(containerRef, input.runner, input.engine, input.context);
2711
+ },
2712
+ shell() {
2713
+ const shellSpec = input.spec.shellSpec;
2714
+ return this.exec({
2715
+ command: shellSpec?.command ?? input.spec.env.SHELL ?? "sh",
2716
+ ...shellSpec?.args ? { args: shellSpec.args } : {},
2717
+ cwd: input.spec.cwd,
2718
+ env: shellSpec && "env" in shellSpec ? shellSpec.env : input.spec.env,
2719
+ stdin: "inherit",
2720
+ stdout: "inherit",
2721
+ stderr: "inherit",
2722
+ tty: true
2723
+ });
2724
+ },
2725
+ async close() {
2726
+ await runOrThrow(input.runner, {
2727
+ command: input.engine,
2728
+ args: [...buildContextArgs(input.engine, input.context), "rm", "-f", containerRef],
2729
+ stdout: "pipe",
2730
+ stderr: "pipe"
2731
+ });
2732
+ }
2733
+ };
2734
+ }
2735
+ async function resolveImage(input) {
2736
+ if (input.runtime.image !== void 0) {
2737
+ return input.runtime.image;
2738
+ }
2739
+ const result = await buildDockerRuntimeTemplate({
2740
+ cwd: input.spec.cwd,
2741
+ runtime: input.runtime,
2742
+ state: input.spec.state,
2743
+ runner: input.runner
2744
+ });
2745
+ return result.image;
2746
+ }
2747
+ async function buildDockerRuntimeTemplate(input) {
2748
+ const runner = input.runner ?? createHostRunner();
2749
+ const engine = input.runtime.engine ?? detectEngine();
2750
+ const context = detectContext();
2751
+ const dockerfilePath = path14.resolve(
2752
+ input.cwd,
2753
+ input.runtime.dockerfile ?? path14.join(".poe-code", "Dockerfile")
2754
+ );
2755
+ const buildContext = path14.resolve(input.cwd, input.runtime.build_context ?? ".");
2756
+ const dockerfileBytes = await readFile2(dockerfilePath);
2757
+ const hash = hashDockerTemplate(dockerfileBytes, input.runtime.build_args ?? {});
2758
+ const cached2 = input.force ? null : await input.state?.templates.get("docker", hash);
2759
+ if (cached2?.image !== void 0) {
2760
+ return {
2761
+ backend: "docker",
2762
+ hash,
2763
+ image: cached2.image,
2764
+ cached: true
2765
+ };
2766
+ }
2767
+ const image = `poe-code/local:${hash}`;
2768
+ await buildImage({
2769
+ runner,
2770
+ engine,
2771
+ context,
2772
+ image,
2773
+ dockerfilePath,
2774
+ buildContext,
2775
+ buildArgs: input.runtime.build_args ?? {}
2776
+ });
2777
+ await input.state?.templates.put("docker", {
2778
+ hash,
2779
+ image,
2780
+ runtime_type: "docker",
2781
+ dockerfile_path: dockerfilePath,
2782
+ built_at: (/* @__PURE__ */ new Date()).toISOString()
2783
+ });
2784
+ return {
2785
+ backend: "docker",
2786
+ hash,
2787
+ image,
2788
+ cached: false
2789
+ };
2790
+ }
2791
+ function hashDockerTemplate(dockerfileBytes, buildArgs) {
2792
+ const hash = createHash2("sha256");
2793
+ hash.update(dockerfileBytes);
2794
+ hash.update("\0");
2795
+ for (const [key, value] of sortedBuildArgs(buildArgs)) {
2796
+ hash.update(key);
2797
+ hash.update("=");
2798
+ hash.update(value);
2799
+ hash.update("\0");
2800
+ }
2801
+ return hash.digest("hex");
2802
+ }
2803
+ async function buildImage(input) {
2804
+ await runOrThrow(input.runner, {
2805
+ command: input.engine,
2806
+ args: [
2807
+ ...buildContextArgs(input.engine, input.context),
2808
+ "build",
2809
+ "--tag",
2810
+ input.image,
2811
+ "-f",
2812
+ input.dockerfilePath,
2813
+ ...sortedBuildArgs(input.buildArgs).flatMap(([key, value]) => [
2814
+ "--build-arg",
2815
+ `${key}=${value}`
2816
+ ]),
2817
+ input.buildContext
2818
+ ],
2819
+ stdout: "pipe",
2820
+ stderr: "pipe"
2821
+ });
2822
+ }
2823
+ function parseDockerRuntime(runtime) {
2824
+ if (!runtime || typeof runtime !== "object" || Array.isArray(runtime)) {
2825
+ throw new Error("docker runtime must be an object");
2826
+ }
2827
+ const record = runtime;
2828
+ if (record.type !== "docker") {
2829
+ throw new Error('docker runtime type must be "docker"');
2830
+ }
2831
+ return record;
2832
+ }
2833
+ async function runAndRead(runner, spec) {
2834
+ const handle = runner.exec(spec);
2835
+ const stdout = readStream(handle.stdout);
2836
+ const stderr = readStream(handle.stderr);
2837
+ const result = await handle.result;
2838
+ const output = await stdout;
2839
+ if (result.exitCode !== 0) {
2840
+ const errorOutput = await stderr;
2841
+ throw new Error(
2842
+ `Command failed with exit code ${result.exitCode}: ${spec.command} ${(spec.args ?? []).join(" ")}${errorOutput ? `
2843
+ ${errorOutput}` : ""}`
2844
+ );
2845
+ }
2846
+ return output;
2847
+ }
2848
+ async function runOrThrow(runner, spec) {
2849
+ await runAndRead(runner, spec);
2850
+ }
2851
+ async function readStream(stream) {
2852
+ if (stream === null) {
2853
+ return "";
2854
+ }
2855
+ stream.setEncoding("utf8");
2856
+ const chunks = [];
2857
+ for await (const chunk of stream) {
2858
+ chunks.push(String(chunk));
2859
+ }
2860
+ return chunks.join("");
2861
+ }
2862
+ function sortedBuildArgs(buildArgs) {
2863
+ return Object.entries(buildArgs).sort(([left], [right]) => left.localeCompare(right));
2864
+ }
2865
+ function buildEnvArgs(env) {
2866
+ if (env === void 0) {
2867
+ return [];
2868
+ }
2869
+ return Object.entries(env).flatMap(([key, value]) => ["-e", `${key}=${value}`]);
2870
+ }
2871
+ function createContainerName() {
2872
+ return `poe-env-${randomBytes3(6).toString("hex")}`;
2873
+ }
2874
+ function createContainerJob(containerId, runner, engine, context, jobId = containerId) {
2875
+ return {
2876
+ id: jobId,
2877
+ envId: containerId,
2878
+ tool: "docker",
2879
+ argv: ["attach", containerId],
2880
+ async status() {
2881
+ const handle = runner.exec({
2882
+ command: engine,
2883
+ args: [
2884
+ ...buildContextArgs(engine, context),
2885
+ "inspect",
2886
+ "-f",
2887
+ "{{.State.Status}}",
2888
+ containerId
2889
+ ],
2890
+ stdout: "pipe",
2891
+ stderr: "pipe"
2892
+ });
2893
+ const stdout = await readStream(handle.stdout);
2894
+ const result = await handle.result;
2895
+ if (result.exitCode !== 0) {
2896
+ return "lost";
2897
+ }
2898
+ return stdout.trim() === "running" ? "running" : "exited";
2899
+ },
2900
+ async *stream(opts) {
2901
+ const handle = runner.exec({
2902
+ command: engine,
2903
+ args: [
2904
+ ...buildContextArgs(engine, context),
2905
+ "exec",
2906
+ containerId,
2907
+ "sh",
2908
+ "-c",
2909
+ `test -f ${shellQuote(`/tmp/poe-jobs/${jobId}.log`)} && tail -c +${(opts?.sinceByte ?? 0) + 1} ${shellQuote(`/tmp/poe-jobs/${jobId}.log`)} || true`
2910
+ ],
2911
+ stdout: "pipe",
2912
+ stderr: "pipe"
2913
+ });
2914
+ const stdout = await readStream(handle.stdout);
2915
+ await handle.result;
2916
+ if (stdout.length > 0) {
2917
+ yield { byteOffset: opts?.sinceByte ?? 0, data: stdout };
2918
+ }
2919
+ },
2920
+ async wait() {
2921
+ const handle = runner.exec({
2922
+ command: engine,
2923
+ args: [...buildContextArgs(engine, context), "wait", containerId],
2924
+ stdout: "pipe",
2925
+ stderr: "pipe"
2926
+ });
2927
+ const stdout = await readStream(handle.stdout);
2928
+ const result = await handle.result;
2929
+ return { exitCode: Number.parseInt(stdout.trim(), 10) || result.exitCode };
2930
+ },
2931
+ async kill(signal) {
2932
+ const args = signal === void 0 || signal === "SIGTERM" ? ["stop", containerId] : ["kill", ...signal === "SIGKILL" ? [] : [`--signal=${signal}`], containerId];
2933
+ await runOrThrow(runner, {
2934
+ command: engine,
2935
+ args: [...buildContextArgs(engine, context), ...args],
2936
+ stdout: "pipe",
2937
+ stderr: "pipe"
2938
+ });
2939
+ }
2940
+ };
2941
+ }
2942
+ function createAttachedSpec(cwd = "/workspace") {
2943
+ return {
2944
+ cwd,
2945
+ runtime: {
2946
+ type: "docker",
2947
+ image: "attached",
2948
+ build_args: {},
2949
+ mounts: []
2950
+ },
2951
+ env: {},
2952
+ uploadIgnoreFiles: [],
2953
+ jobLabel: {
2954
+ tool: "docker",
2955
+ argv: []
2956
+ }
2957
+ };
2958
+ }
2959
+ function shellQuote(value) {
2960
+ return `'${value.replaceAll("'", "'\\''")}'`;
2961
+ }
2962
+
2963
+ // packages/process-runner/src/host/host-execution-env.ts
2964
+ var hostExecutionEnvFactory = {
2965
+ type: "host",
2966
+ supportsDetach: false,
2967
+ async open(openSpec) {
2968
+ return {
2969
+ id: "host",
2970
+ job: null,
2971
+ async uploadWorkspace() {
2972
+ return {
2973
+ files: 0,
2974
+ bytes: 0,
2975
+ skipped: []
2976
+ };
2977
+ },
2978
+ async downloadWorkspace() {
2979
+ return {
2980
+ files: 0,
2981
+ bytes: 0,
2982
+ conflicts: []
2983
+ };
2984
+ },
2985
+ exec(spec) {
2986
+ return createHostRunner().exec(spec);
2987
+ },
2988
+ async detach() {
2989
+ throw new Error("host runtime does not support detach because host has no addressable env");
2990
+ },
2991
+ shell() {
2992
+ const shellSpec = openSpec.shellSpec;
2993
+ return createHostRunner().exec({
2994
+ command: shellSpec?.command ?? openSpec.env.SHELL ?? process.env.SHELL ?? "sh",
2995
+ ...shellSpec?.args ? { args: shellSpec.args } : {},
2996
+ cwd: openSpec.cwd,
2997
+ env: shellSpec && "env" in shellSpec ? shellSpec.env : openSpec.env,
2998
+ stdin: "inherit",
2999
+ stdout: "inherit",
3000
+ stderr: "inherit",
3001
+ tty: true
3002
+ });
3003
+ },
3004
+ async close() {
3005
+ }
3006
+ };
3007
+ },
3008
+ async attach() {
3009
+ throw new Error("host runtime does not support reattach");
3010
+ }
3011
+ };
3012
+
3013
+ // packages/process-runner/src/testing/mock-runner.ts
3014
+ import { Readable, Writable } from "node:stream";
3015
+
3016
+ // packages/runner-e2b/src/factory.ts
3017
+ import path18 from "node:path";
3018
+
3019
+ // packages/runner-e2b/src/sdk.ts
3020
+ import { Template, Sandbox } from "e2b";
3021
+ async function createSandbox(opts) {
3022
+ return Sandbox.create(opts.templateId, {
3023
+ apiKey: opts.apiKey,
3024
+ envs: opts.env,
3025
+ ...opts.timeoutMinutes === void 0 ? {} : { timeoutMs: opts.timeoutMinutes * 6e4 }
3026
+ });
3027
+ }
3028
+ async function connectSandbox(id, apiKey) {
3029
+ return Sandbox.connect(id, apiKey === void 0 ? void 0 : { apiKey });
3030
+ }
3031
+ async function buildTemplate(opts) {
3032
+ const template = Template({ fileContextPath: opts.buildContext }).fromDockerfile(
3033
+ opts.dockerfilePath
3034
+ );
3035
+ if (opts.fromTemplate !== void 0 && opts.fromTemplate.length > 0) {
3036
+ template.fromTemplate(opts.fromTemplate);
3037
+ }
3038
+ const result = await Template.build(template, opts.name, {
3039
+ apiKey: opts.apiKey,
3040
+ ...opts.cpu === void 0 ? {} : { cpuCount: opts.cpu },
3041
+ ...opts.memoryMb === void 0 ? {} : { memoryMB: opts.memoryMb },
3042
+ ...opts.onLog ? { onBuildLogs: opts.onLog } : {}
3043
+ });
3044
+ return { templateId: result.templateId };
3045
+ }
3046
+ function toArrayBuffer(buffer) {
3047
+ const output = new ArrayBuffer(buffer.byteLength);
3048
+ new Uint8Array(output).set(buffer);
3049
+ return output;
3050
+ }
3051
+ async function readableToString(stream) {
3052
+ if (stream === null) {
3053
+ return "";
3054
+ }
3055
+ stream.setEncoding("utf8");
3056
+ const chunks = [];
3057
+ for await (const chunk of stream) {
3058
+ chunks.push(String(chunk));
3059
+ }
3060
+ return chunks.join("");
3061
+ }
3062
+
3063
+ // packages/runner-e2b/src/template-build.ts
3064
+ import { createHash as createHash3 } from "node:crypto";
3065
+ import { readdir, readFile as readFile3 } from "node:fs/promises";
3066
+ import path15 from "node:path";
3067
+ var BUILD_LOG_TAIL_SIZE = 30;
3068
+ async function buildE2bRuntimeTemplate(input) {
3069
+ const dockerfileBytes = await readFile3(input.dockerfilePath);
3070
+ const buildContextFiles = await readBuildContextFiles(input.buildContext);
3071
+ const hash = hashTemplate(dockerfileBytes, buildContextFiles, input.runtime.build_args);
3072
+ const cached2 = input.force === true ? null : await input.state?.templates.get("e2b", hash);
3073
+ if (cached2?.template_id !== void 0) {
3074
+ return { backend: "e2b", hash, templateId: cached2.template_id, cached: true };
3075
+ }
3076
+ const tail = [];
3077
+ const onLog = (entry) => {
3078
+ tail.push(entry.message);
3079
+ if (tail.length > BUILD_LOG_TAIL_SIZE) {
3080
+ tail.shift();
3081
+ }
3082
+ input.onLog?.(entry);
3083
+ };
3084
+ let built;
3085
+ try {
3086
+ built = await buildTemplate({
3087
+ apiKey: input.apiKey,
3088
+ name: `poe-code-${hash.slice(0, 32)}`,
3089
+ dockerfilePath: input.dockerfilePath,
3090
+ buildContext: input.buildContext,
3091
+ cpu: input.runtime.cpu,
3092
+ memoryMb: input.runtime.memory_mb,
3093
+ fromTemplate: input.runtime.from_template,
3094
+ onLog
3095
+ });
3096
+ } catch (error2) {
3097
+ throw decorateBuildError(error2, tail);
3098
+ }
3099
+ await input.state?.templates.put("e2b", {
3100
+ hash,
3101
+ template_id: built.templateId,
3102
+ runtime_type: "e2b",
3103
+ dockerfile_path: input.dockerfilePath,
3104
+ built_at: (/* @__PURE__ */ new Date()).toISOString()
3105
+ });
3106
+ return { backend: "e2b", hash, templateId: built.templateId, cached: false };
3107
+ }
3108
+ function decorateBuildError(error2, tail) {
3109
+ const original = error2 instanceof Error ? error2 : new Error(String(error2));
3110
+ if (tail.length === 0) {
3111
+ return original;
3112
+ }
3113
+ const decorated = new Error(`${original.message}
3114
+
3115
+ Last build output:
3116
+ ${tail.join("\n")}`);
3117
+ decorated.stack = original.stack;
3118
+ decorated.cause = original;
3119
+ return decorated;
3120
+ }
3121
+ function hashTemplate(dockerfileBytes, buildContextFiles, buildArgs) {
3122
+ const hash = createHash3("sha256");
3123
+ hash.update(dockerfileBytes);
3124
+ hash.update("\0");
3125
+ for (const file of buildContextFiles) {
3126
+ hash.update(file.relativePath);
3127
+ hash.update("\0");
3128
+ hash.update(file.bytes);
3129
+ hash.update("\0");
3130
+ }
3131
+ for (const [key, value] of Object.entries(buildArgs).sort(
3132
+ ([left], [right]) => left.localeCompare(right)
3133
+ )) {
3134
+ hash.update(key);
3135
+ hash.update("=");
3136
+ hash.update(value);
3137
+ hash.update("\0");
3138
+ }
3139
+ return hash.digest("hex");
3140
+ }
3141
+ async function readBuildContextFiles(buildContext) {
3142
+ const files = [];
3143
+ await collectBuildContextFiles(buildContext, "", files);
3144
+ return files.sort((left, right) => left.relativePath.localeCompare(right.relativePath));
3145
+ }
3146
+ async function collectBuildContextFiles(buildContext, relativeDir, files) {
3147
+ const absoluteDir = path15.join(buildContext, relativeDir);
3148
+ const entries = await readdir(absoluteDir, { withFileTypes: true });
3149
+ for (const entry of entries) {
3150
+ const relativePath = path15.join(relativeDir, entry.name);
3151
+ if (entry.isDirectory()) {
3152
+ await collectBuildContextFiles(buildContext, relativePath, files);
3153
+ continue;
3154
+ }
3155
+ if (!entry.isFile()) {
3156
+ continue;
3157
+ }
3158
+ files.push({
3159
+ relativePath: relativePath.split(path15.sep).join("/"),
3160
+ bytes: await readFile3(path15.join(buildContext, relativePath))
3161
+ });
3162
+ }
3163
+ }
3164
+
3165
+ // packages/runner-e2b/src/opened-env.ts
3166
+ import { mkdtempSync as mkdtempSync2, rmSync as rmSync2 } from "node:fs";
3167
+ import { readFile as readFile4, writeFile } from "node:fs/promises";
3168
+ import { tmpdir as tmpdir2 } from "node:os";
3169
+ import path17 from "node:path";
3170
+ import { PassThrough, Writable as Writable2 } from "node:stream";
3171
+
3172
+ // packages/runner-e2b/src/job-handle.ts
3173
+ import path16 from "node:path";
3174
+ var JOB_DIR2 = "/tmp/poe-jobs";
3175
+ function createE2bJobHandle(input) {
3176
+ const fs = createE2bLogStreamFs(input.sandbox);
3177
+ return {
3178
+ id: input.jobId,
3179
+ envId: input.envId,
3180
+ tool: input.tool,
3181
+ argv: input.argv,
3182
+ async status() {
3183
+ const exit = await readExitCode(input.sandbox, input.jobId);
3184
+ if (exit !== null) {
3185
+ return "exited";
3186
+ }
3187
+ const processes = await input.sandbox.commands.list();
3188
+ const isRunning = input.pid === void 0 ? processes.some((process2) => processMentionsJob(process2, input.jobId)) : processes.some((process2) => process2.pid === input.pid);
3189
+ return isRunning ? "running" : "lost";
3190
+ },
3191
+ stream(opts = {}) {
3192
+ return streamLogFile({ fs }, input.jobId, opts);
3193
+ },
3194
+ async wait() {
3195
+ const result = await waitForExit({ fs }, input.jobId);
3196
+ const preserveMs = input.preserveAfterExitHours * 60 * 60 * 1e3;
3197
+ if (preserveMs > 0) {
3198
+ await input.sandbox.setTimeout(preserveMs);
3199
+ }
3200
+ return result;
3201
+ },
3202
+ async kill() {
3203
+ const pids = input.pid === void 0 ? (await input.sandbox.commands.list()).filter((process2) => processMentionsJob(process2, input.jobId)).map((process2) => process2.pid) : [input.pid];
3204
+ await Promise.all(pids.map((pid) => input.sandbox.commands.kill(pid)));
3205
+ }
3206
+ };
3207
+ }
3208
+ function createE2bLogStreamFs(sandbox) {
3209
+ return {
3210
+ promises: {
3211
+ async readFile(filePath) {
3212
+ return Buffer.from(await sandbox.files.read(filePath, { format: "bytes" }));
3213
+ },
3214
+ async stat(filePath) {
3215
+ const result = await sandbox.commands.run(
3216
+ `stat -c %Y ${shellQuote2(filePath)} 2>/dev/null || stat -f %m ${shellQuote2(filePath)}`
3217
+ );
3218
+ if (!("stdout" in result)) {
3219
+ throw new Error(`Unable to stat ${filePath}`);
3220
+ }
3221
+ const seconds = Number(result.stdout?.trim());
3222
+ if (!Number.isFinite(seconds)) {
3223
+ throw new Error(`Unable to stat ${filePath}`);
3224
+ }
3225
+ return { mtimeMs: seconds * 1e3 };
3226
+ }
3227
+ },
3228
+ watch(filePath, listener) {
3229
+ let closed = false;
3230
+ let stop = null;
3231
+ void sandbox.files.watchDir(path16.dirname(filePath), listener, { recursive: false }).then((handle) => {
3232
+ if (closed) {
3233
+ void handle.stop();
3234
+ return;
3235
+ }
3236
+ stop = () => {
3237
+ void handle.stop();
3238
+ };
3239
+ });
3240
+ return {
3241
+ close() {
3242
+ closed = true;
3243
+ stop?.();
3244
+ }
3245
+ };
3246
+ }
3247
+ };
3248
+ }
3249
+ function processMentionsJob(process2, jobId) {
3250
+ const needle = `/tmp/poe-jobs/${jobId}`;
3251
+ return process2.cmd.includes(needle) || process2.args.some((arg) => arg.includes(needle));
3252
+ }
3253
+ function shellQuote2(value) {
3254
+ return `'${value.replaceAll("'", "'\\''")}'`;
3255
+ }
3256
+ async function readExitCode(sandbox, jobId) {
3257
+ try {
3258
+ const contents = await sandbox.files.read(`${JOB_DIR2}/${jobId}.exit`);
3259
+ const exitCode = Number(contents.trim());
3260
+ return Number.isInteger(exitCode) ? exitCode : null;
3261
+ } catch {
3262
+ return null;
3263
+ }
3264
+ }
3265
+
3266
+ // packages/runner-e2b/src/opened-env.ts
3267
+ var REMOTE_COMMAND_STDERR_TAIL_SIZE = 30;
3268
+ function createOpenedE2bEnv(input) {
3269
+ const hostRunner = input.spec.hostRunner ?? createHostRunner();
3270
+ const hostWorkspaceDir = path17.resolve(input.spec.cwd);
3271
+ const sandboxWorkspaceDir = normalizeSandboxWorkspaceDir(input.runtime.workspace_dir);
3272
+ let lastProcess = null;
3273
+ let detachedJobContext = null;
3274
+ const mapWorkspaceCwd = (cwd) => {
3275
+ if (cwd === void 0) {
3276
+ return void 0;
3277
+ }
3278
+ if (path17.isAbsolute(cwd) && path17.resolve(cwd) === hostWorkspaceDir) {
3279
+ return sandboxWorkspaceDir;
3280
+ }
3281
+ return cwd;
3282
+ };
3283
+ const attachedJobId = input.spec.detachedJobId;
3284
+ const env = {
3285
+ id: input.sandbox.sandboxId,
3286
+ job: attachedJobId ? createE2bJobHandle({
3287
+ sandbox: input.sandbox,
3288
+ envId: input.sandbox.sandboxId,
3289
+ jobId: attachedJobId,
3290
+ tool: input.spec.jobLabel.tool,
3291
+ argv: input.spec.jobLabel.argv,
3292
+ preserveAfterExitHours: input.runtime.preserve_after_exit_hours ?? 24
3293
+ }) : null,
3294
+ fs: createE2bLogStreamFs(input.sandbox),
3295
+ setDetachedJobContext(context) {
3296
+ detachedJobContext = context;
3297
+ },
3298
+ async uploadWorkspace() {
3299
+ if (input.spec.runner?.sync === "none") {
3300
+ return { files: 0, bytes: 0, skipped: [] };
3301
+ }
3302
+ const tempDir = mkdtempSync2(path17.join(tmpdir2(), "poe-e2b-upload-"));
3303
+ const archivePath = path17.join(tempDir, "workspace.tar");
3304
+ try {
3305
+ await runOrThrow2(hostRunner, {
3306
+ command: "tar",
3307
+ args: [
3308
+ ...input.spec.uploadIgnoreFiles.flatMap((ignored) => ["--exclude", ignored]),
3309
+ "-cf",
3310
+ archivePath,
3311
+ "-C",
3312
+ input.spec.cwd,
3313
+ "."
3314
+ ],
3315
+ stdout: "pipe",
3316
+ stderr: "pipe"
3317
+ });
3318
+ await input.sandbox.files.write(
3319
+ "/tmp/poe-workspace-upload.tar",
3320
+ toArrayBuffer(await readFile4(archivePath))
3321
+ );
3322
+ await runRemoteOrThrow(
3323
+ input.sandbox,
3324
+ createUploadWorkspaceCommand(sandboxWorkspaceDir)
3325
+ );
3326
+ return { files: 0, bytes: 0, skipped: [] };
3327
+ } finally {
3328
+ rmSync2(tempDir, { recursive: true, force: true });
3329
+ }
3330
+ },
3331
+ async downloadWorkspace(opts) {
3332
+ if (input.spec.runner?.sync === "upload" || input.spec.runner?.sync === "none") {
3333
+ return { files: 0, bytes: 0, conflicts: [] };
3334
+ }
3335
+ const tempDir = mkdtempSync2(path17.join(tmpdir2(), "poe-e2b-download-"));
3336
+ const archivePath = path17.join(tempDir, "workspace.tar");
3337
+ try {
3338
+ await runRemoteOrThrow(
3339
+ input.sandbox,
3340
+ `tar -cf /tmp/poe-workspace-download.tar -C ${shellQuote3(sandboxWorkspaceDir)} .`
3341
+ );
3342
+ const archive = await input.sandbox.files.read("/tmp/poe-workspace-download.tar", {
3343
+ format: "bytes"
3344
+ });
3345
+ await writeFile(archivePath, Buffer.from(archive));
3346
+ await runOrThrow2(hostRunner, {
3347
+ command: "tar",
3348
+ args: [
3349
+ opts.conflictPolicy === "refuse" ? "-xkf" : "-xf",
3350
+ archivePath,
3351
+ "-C",
3352
+ input.spec.cwd
3353
+ ],
3354
+ stdout: "pipe",
3355
+ stderr: "pipe"
3356
+ });
3357
+ return { files: 0, bytes: archive.byteLength, conflicts: [] };
3358
+ } finally {
3359
+ rmSync2(tempDir, { recursive: true, force: true });
3360
+ }
3361
+ },
3362
+ exec(spec) {
3363
+ const handle = runE2bCommand(input.sandbox, {
3364
+ ...spec,
3365
+ cwd: mapWorkspaceCwd(spec.cwd),
3366
+ env: resolveSandboxCommandEnv(spec.env)
3367
+ });
3368
+ lastProcess = { started: handle.started };
3369
+ return handle;
3370
+ },
3371
+ async detach() {
3372
+ if (detachedJobContext === null) {
3373
+ throw new Error("Cannot detach E2B environment before a job context is registered.");
3374
+ }
3375
+ if (lastProcess === null) {
3376
+ throw new Error("Cannot detach E2B environment before a command is running.");
3377
+ }
3378
+ const command = await lastProcess.started;
3379
+ const preserveAfterExitHours = input.runtime.preserve_after_exit_hours ?? 24;
3380
+ const preserveMs = preserveAfterExitHours * 60 * 60 * 1e3;
3381
+ if (preserveMs > 0) {
3382
+ await input.sandbox.setTimeout(preserveMs);
3383
+ }
3384
+ return createE2bJobHandle({
3385
+ sandbox: input.sandbox,
3386
+ envId: input.sandbox.sandboxId,
3387
+ jobId: detachedJobContext.id,
3388
+ tool: detachedJobContext.tool,
3389
+ argv: detachedJobContext.argv,
3390
+ pid: command.pid,
3391
+ preserveAfterExitHours
3392
+ });
3393
+ },
3394
+ shell() {
3395
+ const shellSpec = input.spec.shellSpec;
3396
+ const command = shellSpec?.command ?? input.spec.env.SHELL ?? "sh";
3397
+ return runE2bPty(input.sandbox, {
3398
+ command,
3399
+ ...shellSpec?.args ? { args: shellSpec.args } : {},
3400
+ cwd: mapWorkspaceCwd(shellSpec?.cwd ?? input.spec.cwd),
3401
+ env: resolveSandboxCommandEnv(
3402
+ shellSpec && "env" in shellSpec ? shellSpec.env : input.spec.env
3403
+ ),
3404
+ stdin: "inherit",
3405
+ stdout: "inherit",
3406
+ stderr: "inherit",
3407
+ tty: true
3408
+ });
3409
+ },
3410
+ async close() {
3411
+ await input.sandbox.kill();
3412
+ }
3413
+ };
3414
+ return env;
3415
+ }
3416
+ function runE2bCommand(sandbox, spec) {
3417
+ const stdout = spec.stdout === "inherit" ? null : new PassThrough();
3418
+ const stderr = spec.stderr === "inherit" ? null : new PassThrough();
3419
+ let e2bHandle = null;
3420
+ const command = shellCommand([spec.command, ...spec.args ?? []]);
3421
+ const started = sandbox.commands.run(command, {
3422
+ background: true,
3423
+ cwd: spec.cwd,
3424
+ envs: spec.env,
3425
+ stdin: spec.stdin === "pipe",
3426
+ onStdout(data) {
3427
+ stdout?.write(data);
3428
+ if (spec.stdout === "inherit") {
3429
+ process.stdout.write(data);
3430
+ }
3431
+ },
3432
+ onStderr(data) {
3433
+ stderr?.write(data);
3434
+ if (spec.stderr === "inherit") {
3435
+ process.stderr.write(data);
3436
+ }
3437
+ }
3438
+ });
3439
+ const stdin = spec.stdin === "pipe" ? new Writable2({
3440
+ write(chunk, _encoding, callback) {
3441
+ started.then(
3442
+ (handle) => sandbox.commands.sendStdin(
3443
+ handle.pid,
3444
+ Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))
3445
+ )
3446
+ ).then(() => callback(), callback);
3447
+ },
3448
+ final(callback) {
3449
+ if (sandbox.commands.closeStdin === void 0) {
3450
+ callback();
3451
+ return;
3452
+ }
3453
+ started.then((handle) => sandbox.commands.closeStdin(handle.pid)).then(() => callback(), callback);
3454
+ }
3455
+ }) : null;
3456
+ const result = started.then((handle) => {
3457
+ e2bHandle = handle;
3458
+ return handle.wait();
3459
+ }).then(
3460
+ (result2) => {
3461
+ stdout?.end();
3462
+ stderr?.end();
3463
+ return { exitCode: result2.exitCode ?? 0 };
3464
+ },
3465
+ (error2) => {
3466
+ stdout?.end();
3467
+ stderr?.end();
3468
+ if (isExitError(error2)) {
3469
+ return { exitCode: error2.exitCode };
3470
+ }
3471
+ return { exitCode: 1 };
3472
+ }
3473
+ );
3474
+ return {
3475
+ get pid() {
3476
+ return e2bHandle?.pid ?? null;
3477
+ },
3478
+ stdin,
3479
+ stdout,
3480
+ stderr,
3481
+ result,
3482
+ kill() {
3483
+ void e2bHandle?.kill();
3484
+ },
3485
+ get e2bHandle() {
3486
+ return e2bHandle;
3487
+ },
3488
+ started
3489
+ };
3490
+ }
3491
+ function runE2bPty(sandbox, spec) {
3492
+ const stdout = new PassThrough();
3493
+ let handleRef = null;
3494
+ const stdin = new Writable2({
3495
+ write(chunk, _encoding, callback) {
3496
+ if (handleRef === null) {
3497
+ callback(new Error("E2B PTY stdin is not ready."));
3498
+ return;
3499
+ }
3500
+ sandbox.pty.sendInput(handleRef.pid, Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))).then(() => callback(), callback);
3501
+ }
3502
+ });
3503
+ const started = sandbox.pty.create({
3504
+ cols: process.stdout.columns || 80,
3505
+ rows: process.stdout.rows || 24,
3506
+ cwd: spec.cwd,
3507
+ envs: spec.env,
3508
+ onData(data) {
3509
+ stdout.write(Buffer.from(data));
3510
+ if (spec.stdout === "inherit") {
3511
+ process.stdout.write(Buffer.from(data));
3512
+ }
3513
+ }
3514
+ });
3515
+ const result = started.then((handle) => {
3516
+ handleRef = handle;
3517
+ return handle.wait();
3518
+ }).then(
3519
+ (result2) => {
3520
+ stdout.end();
3521
+ return { exitCode: result2.exitCode ?? 0 };
3522
+ },
3523
+ () => {
3524
+ stdout.end();
3525
+ return { exitCode: 1 };
3526
+ }
3527
+ );
3528
+ return {
3529
+ get pid() {
3530
+ return handleRef?.pid ?? null;
3531
+ },
3532
+ stdin: spec.stdin === "inherit" ? process.stdin : stdin,
3533
+ stdout: spec.stdout === "inherit" ? null : stdout,
3534
+ stderr: null,
3535
+ result,
3536
+ kill() {
3537
+ void (handleRef === null ? void 0 : sandbox.pty.kill(handleRef.pid));
3538
+ }
3539
+ };
3540
+ }
3541
+ async function runRemoteOrThrow(sandbox, command) {
3542
+ const stdoutTail = createLineTail(REMOTE_COMMAND_STDERR_TAIL_SIZE);
3543
+ const stderrTail = createLineTail(REMOTE_COMMAND_STDERR_TAIL_SIZE);
3544
+ let result;
3545
+ try {
3546
+ result = await sandbox.commands.run(command, {
3547
+ onStdout(data) {
3548
+ stdoutTail.push(data);
3549
+ },
3550
+ onStderr(data) {
3551
+ stderrTail.push(data);
3552
+ }
3553
+ });
3554
+ } catch (error2) {
3555
+ appendRemoteCommandOutput(error2, stdoutTail, stderrTail);
3556
+ if (isCommandExitError(error2)) {
3557
+ throw decorateRemoteCommandError(error2, command, stderrTail.values());
3558
+ }
3559
+ throw error2;
3560
+ }
3561
+ appendRemoteCommandOutput(result, stdoutTail, stderrTail);
3562
+ if ("exitCode" in result && result.exitCode !== 0) {
3563
+ throw decorateRemoteCommandError(
3564
+ new Error(`E2B command failed with exit code ${result.exitCode}`),
3565
+ command,
3566
+ stderrTail.values()
3567
+ );
3568
+ }
3569
+ }
3570
+ function appendRemoteCommandOutput(source, stdoutTail, stderrTail) {
3571
+ if (!source || typeof source !== "object") {
3572
+ return;
3573
+ }
3574
+ const output = source;
3575
+ if (typeof output.stdout === "string") {
3576
+ stdoutTail.push(output.stdout);
3577
+ }
3578
+ if (typeof output.stderr === "string") {
3579
+ stderrTail.push(output.stderr);
3580
+ }
3581
+ }
3582
+ function decorateRemoteCommandError(error2, command, stderrTail) {
3583
+ const original = error2 instanceof Error ? error2 : new Error(String(error2));
3584
+ const tail = stderrTail.length === 0 ? "" : `
3585
+
3586
+ Last stderr output:
3587
+ ${stderrTail.join("\n")}`;
3588
+ const decorated = new Error(`E2B command failed: ${command}
3589
+ ${original.message}${tail}`);
3590
+ decorated.stack = original.stack;
3591
+ decorated.cause = original;
3592
+ return decorated;
3593
+ }
3594
+ function createLineTail(maxLines) {
3595
+ const lines = [];
3596
+ let pending = "";
3597
+ const appendLine = (line) => {
3598
+ lines.push(trimTrailingCarriageReturn(line));
3599
+ while (lines.length > maxLines) {
3600
+ lines.shift();
3601
+ }
3602
+ };
3603
+ return {
3604
+ push(chunk) {
3605
+ pending += chunk;
3606
+ const parts = pending.split("\n");
3607
+ pending = parts.pop() ?? "";
3608
+ for (const line of parts) {
3609
+ appendLine(line);
3610
+ }
3611
+ },
3612
+ values() {
3613
+ const output = [...lines];
3614
+ if (pending.length > 0) {
3615
+ output.push(trimTrailingCarriageReturn(pending));
3616
+ }
3617
+ return output.slice(-maxLines);
3618
+ }
3619
+ };
3620
+ }
3621
+ function trimTrailingCarriageReturn(value) {
3622
+ return value.endsWith("\r") ? value.slice(0, -1) : value;
3623
+ }
3624
+ async function runOrThrow2(runner, spec) {
3625
+ const handle = runner.exec(spec);
3626
+ const stderr = readableToString(handle.stderr);
3627
+ const result = await handle.result;
3628
+ if (result.exitCode !== 0) {
3629
+ throw new Error(
3630
+ `Command failed with exit code ${result.exitCode}: ${spec.command} ${(spec.args ?? []).join(" ")}
3631
+ ${await stderr}`
3632
+ );
3633
+ }
3634
+ }
3635
+ function shellCommand(argv) {
3636
+ return argv.map(shellQuote3).join(" ");
3637
+ }
3638
+ function shellQuote3(value) {
3639
+ return `'${value.replaceAll("'", "'\\''")}'`;
3640
+ }
3641
+ function createUploadWorkspaceCommand(sandboxWorkspaceDir) {
3642
+ const quotedWorkspaceDir = shellQuote3(sandboxWorkspaceDir);
3643
+ return [
3644
+ `mkdir -p ${quotedWorkspaceDir} || { command -v sudo >/dev/null 2>&1 && sudo mkdir -p ${quotedWorkspaceDir} && sudo chown "$(id -u):$(id -g)" ${quotedWorkspaceDir}; }`,
3645
+ `test -w ${quotedWorkspaceDir} && tar -xf /tmp/poe-workspace-upload.tar -C ${quotedWorkspaceDir}`
3646
+ ].join("\n");
3647
+ }
3648
+ function resolveSandboxCommandEnv(env) {
3649
+ if (env === void 0) {
3650
+ return void 0;
3651
+ }
3652
+ return {
3653
+ ...env,
3654
+ HOME: "/home/user"
3655
+ };
3656
+ }
3657
+ function normalizeSandboxWorkspaceDir(workspaceDir) {
3658
+ const resolvedWorkspaceDir = workspaceDir ?? "/workspace";
3659
+ if (!path17.posix.isAbsolute(resolvedWorkspaceDir)) {
3660
+ throw new Error("E2B runtime workspace_dir must be an absolute sandbox path.");
3661
+ }
3662
+ let normalized = path17.posix.normalize(resolvedWorkspaceDir);
3663
+ while (normalized.length > 1 && normalized.endsWith("/")) {
3664
+ normalized = normalized.slice(0, -1);
3665
+ }
3666
+ return normalized;
3667
+ }
3668
+ function isExitError(error2) {
3669
+ return Boolean(
3670
+ error2 && typeof error2 === "object" && typeof error2.exitCode === "number"
3671
+ );
3672
+ }
3673
+ function isCommandExitError(error2) {
3674
+ return isExitError(error2) || Boolean(
3675
+ error2 && typeof error2 === "object" && error2.name === "CommandExitError"
3676
+ );
3677
+ }
3678
+
3679
+ // packages/runner-e2b/src/auth-scope.ts
3680
+ import os4 from "node:os";
3681
+ import { promises as nodeFs4 } from "node:fs";
3682
+ var e2bAuthScope = defineScope("e2b", {
3683
+ api_key: {
3684
+ type: "string",
3685
+ default: "",
3686
+ doc: "E2B API key",
3687
+ env: "E2B_API_KEY"
3688
+ }
3689
+ });
3690
+ async function resolveE2bApiKey(input) {
3691
+ const homeDir = input.homeDir ?? os4.homedir();
3692
+ const fs = input.fs ?? nodeFs4;
3693
+ const env = input.env ?? process.env;
3694
+ const document = await readMergedDocument(
3695
+ fs,
3696
+ resolveConfigPath(homeDir),
3697
+ resolveProjectConfigPath(input.cwd)
3698
+ );
3699
+ const resolved = resolveScope(e2bAuthScope.schema, document.e2b, env);
3700
+ if (resolved.api_key.length === 0) {
3701
+ throw new Error(
3702
+ "No E2B API key. Set E2B_API_KEY or e2b.api_key in ~/.poe-code/config.json."
3703
+ );
3704
+ }
3705
+ return resolved.api_key;
3706
+ }
3707
+
3708
+ // packages/runner-e2b/src/factory.ts
3709
+ var e2bExecutionEnvFactory = {
3710
+ type: "e2b",
3711
+ supportsDetach: true,
3712
+ async open(spec) {
3713
+ const runtime = parseE2bRuntime(spec.runtime);
3714
+ const runtimeCwd = spec.runtimeCwd ?? spec.cwd;
3715
+ const apiKey = await resolveE2bApiKey({ cwd: runtimeCwd });
3716
+ const templateId = runtime.template_id ?? (await buildE2bRuntimeTemplate({
3717
+ runtime,
3718
+ dockerfilePath: path18.resolve(
3719
+ runtimeCwd,
3720
+ runtime.dockerfile ?? path18.join(".poe-code", "Dockerfile")
3721
+ ),
3722
+ buildContext: path18.resolve(runtimeCwd, runtime.build_context ?? "."),
3723
+ state: spec.state,
3724
+ apiKey
3725
+ })).templateId;
3726
+ const sandbox = await createSandbox({
3727
+ apiKey,
3728
+ templateId,
3729
+ env: spec.env,
3730
+ timeoutMinutes: runtime.timeout_minutes
3731
+ });
3732
+ return createOpenedE2bEnv({ sandbox, spec, runtime });
3733
+ },
3734
+ async attach(envId, context) {
3735
+ const cwd = context?.cwd ?? process.cwd();
3736
+ const apiKey = await resolveE2bApiKey({ cwd });
3737
+ const sandbox = await connectSandbox(envId, apiKey);
3738
+ return createOpenedE2bEnv({
3739
+ sandbox,
3740
+ spec: {
3741
+ cwd: context?.cwd ?? "/workspace",
3742
+ runtime: {
3743
+ type: "e2b",
3744
+ build_args: {},
3745
+ mounts: [],
3746
+ workspace_dir: "/workspace",
3747
+ preserve_after_exit_hours: 24
3748
+ },
3749
+ env: {},
3750
+ uploadIgnoreFiles: [],
3751
+ jobLabel: { tool: context?.tool ?? "e2b", argv: context?.argv ?? [] },
3752
+ ...context?.jobId ? { detachedJobId: context.jobId } : {}
3753
+ },
3754
+ runtime: {
3755
+ type: "e2b",
3756
+ build_args: {},
3757
+ mounts: [],
3758
+ workspace_dir: "/workspace",
3759
+ preserve_after_exit_hours: 24
3760
+ }
3761
+ });
3762
+ }
3763
+ };
3764
+ function parseE2bRuntime(runtime) {
3765
+ if (!runtime || typeof runtime !== "object" || Array.isArray(runtime)) {
3766
+ throw new Error("e2b runtime must be an object");
3767
+ }
3768
+ const record = runtime;
3769
+ if (record.type !== "e2b") {
3770
+ throw new Error('e2b runtime type must be "e2b"');
3771
+ }
3772
+ return record;
3773
+ }
3774
+
3775
+ // packages/runner-e2b/src/index.ts
3776
+ var e2bExecutionEnvFactory2 = e2bExecutionEnvFactory;
3777
+
3778
+ // packages/agent-spawn/src/register-factories.ts
3779
+ registerExecutionEnvFactory(hostExecutionEnvFactory);
3780
+ registerExecutionEnvFactory(dockerExecutionEnvFactory);
3781
+ registerExecutionEnvFactory(e2bExecutionEnvFactory2);
3782
+ if (isVitest()) {
3783
+ registerExecutionEnvFactory(createTestHostExecutionEnvFactory());
3784
+ }
3785
+ function isVitest() {
3786
+ return process.env.VITEST !== void 0 || process.env.VITEST_POOL_ID !== void 0;
3787
+ }
3788
+ function createTestHostExecutionEnvFactory() {
3789
+ return {
3790
+ type: "host",
3791
+ supportsDetach: false,
3792
+ open: ((openSpec) => {
3793
+ return {
3794
+ id: "host",
3795
+ job: null,
3796
+ async uploadWorkspace() {
3797
+ return { files: 0, bytes: 0, skipped: [] };
3798
+ },
3799
+ async downloadWorkspace() {
3800
+ return { files: 0, bytes: 0, conflicts: [] };
3801
+ },
3802
+ exec(spec) {
3803
+ return runHost(spawnChildProcess2, spec);
3804
+ },
3805
+ async detach() {
3806
+ throw new Error(
3807
+ "host runtime does not support detach because host has no addressable env"
3808
+ );
3809
+ },
3810
+ shell() {
3811
+ return runHost(spawnChildProcess2, {
3812
+ command: openSpec.shellSpec?.command ?? openSpec.env.SHELL ?? process.env.SHELL ?? "sh",
3813
+ args: openSpec.shellSpec?.args,
3814
+ cwd: openSpec.cwd,
3815
+ env: openSpec.shellSpec && "env" in openSpec.shellSpec ? openSpec.shellSpec.env : openSpec.env,
3816
+ stdin: "inherit",
3817
+ stdout: "inherit",
3818
+ stderr: "inherit",
3819
+ tty: true
3820
+ });
3821
+ },
3822
+ async close() {
3823
+ }
3824
+ };
3825
+ }),
3826
+ async attach() {
3827
+ throw new Error("host runtime does not support reattach");
3828
+ }
3829
+ };
3830
+ }
3831
+ function runHost(spawnProcess, spec) {
3832
+ const stdin = spec.stdin ?? "ignore";
3833
+ const stdout = spec.stdout ?? "pipe";
3834
+ const stderr = spec.stderr ?? "pipe";
3835
+ const stdio = stdin === "inherit" && stdout === "inherit" && stderr === "inherit" ? "inherit" : [stdin, stdout, stderr];
3836
+ const child = spawnProcess(spec.command, spec.args ?? [], {
3837
+ cwd: spec.cwd,
3838
+ env: spec.env,
3839
+ stdio
3840
+ });
3841
+ const result = new Promise((resolve2) => {
3842
+ child.once("close", (code) => {
3843
+ resolve2({ exitCode: code ?? 1 });
3844
+ });
3845
+ child.once("error", () => {
3846
+ resolve2({ exitCode: 1 });
3847
+ });
3848
+ });
3849
+ const kill = (signal) => {
3850
+ child.kill(signal);
3851
+ };
3852
+ if (spec.signal?.aborted) {
3853
+ kill("SIGTERM");
3854
+ } else {
3855
+ spec.signal?.addEventListener("abort", () => kill("SIGTERM"), { once: true });
3856
+ }
3857
+ return {
3858
+ pid: child.pid ?? null,
3859
+ stdin: child.stdin,
3860
+ stdout: child.stdout,
3861
+ stderr: child.stderr,
3862
+ result,
3863
+ kill
3864
+ };
3865
+ }
3866
+
3867
+ // packages/agent-spawn/src/run-command.ts
3868
+ import { spawn as spawn2 } from "node:child_process";
3869
+
3870
+ // packages/agent-spawn/src/types.ts
3871
+ function resolveModeConfig(modeConfig) {
3872
+ if (Array.isArray(modeConfig)) {
3873
+ return { args: modeConfig };
3874
+ }
3875
+ return {
3876
+ args: modeConfig.args ?? [],
3877
+ env: modeConfig.env && Object.keys(modeConfig.env).length > 0 ? modeConfig.env : void 0
3878
+ };
3879
+ }
3880
+
3881
+ // packages/agent-spawn/src/configs/mcp.ts
3882
+ function toJsonMcpServers(servers) {
3883
+ const out = {};
3884
+ for (const [name, server] of Object.entries(servers)) {
3885
+ const mapped = { command: server.command };
3886
+ if (server.args && server.args.length > 0) {
3887
+ mapped.args = server.args;
3888
+ }
3889
+ if (server.env && Object.keys(server.env).length > 0) {
3890
+ mapped.env = server.env;
3891
+ }
3892
+ if (server.timeout !== void 0) {
3893
+ mapped.timeout = server.timeout;
3894
+ }
3895
+ out[name] = mapped;
3896
+ }
3897
+ return out;
3898
+ }
3899
+ function toTomlString(value) {
3900
+ return JSON.stringify(value);
3901
+ }
3902
+ function toTomlArray(values) {
3903
+ const serialized = values.map((value) => toTomlString(value));
3904
+ return `[${serialized.join(", ")}]`;
3905
+ }
3906
+ function toTomlInlineTable(values) {
3907
+ const parts = [];
3908
+ for (const [key, value] of Object.entries(values)) {
3909
+ parts.push(`${JSON.stringify(key)}=${toTomlString(value)}`);
3910
+ }
3911
+ return `{${parts.join(", ")}}`;
3912
+ }
3913
+ function serializeJsonMcpArgs(servers) {
3914
+ return ["--mcp-config", JSON.stringify({ mcpServers: toJsonMcpServers(servers) })];
3915
+ }
3916
+ function serializeOpenCodeMcpEnv(servers) {
3917
+ const mcp = {};
3918
+ for (const [name, server] of Object.entries(servers)) {
3919
+ const entry = { type: "local", command: [server.command, ...server.args ?? []] };
3920
+ if (server.env && Object.keys(server.env).length > 0) {
3921
+ entry.environment = server.env;
3922
+ }
3923
+ mcp[name] = entry;
3924
+ }
3925
+ return { OPENCODE_CONFIG_CONTENT: JSON.stringify({ mcp }) };
3926
+ }
3927
+ function serializeCodexMcpArgs(servers) {
3928
+ const args = [];
3929
+ for (const [name, server] of Object.entries(servers)) {
3930
+ const prefix = `mcp_servers.${name}`;
3931
+ args.push("-c", `${prefix}.command=${toTomlString(server.command)}`);
3932
+ if (server.args && server.args.length > 0) {
3933
+ args.push("-c", `${prefix}.args=${toTomlArray(server.args)}`);
3934
+ }
3935
+ if (server.env && Object.keys(server.env).length > 0) {
3936
+ args.push("-c", `${prefix}.env=${toTomlInlineTable(server.env)}`);
3937
+ }
3938
+ if (server.timeout !== void 0) {
3939
+ args.push("-c", `${prefix}.timeout=${server.timeout}`);
3940
+ }
3941
+ }
3942
+ return args;
3943
+ }
3944
+ function serializeGooseMcpArgs(servers) {
3945
+ return Object.values(servers).flatMap((server) => [
3946
+ "--with-extension",
3947
+ [server.command, ...server.args ?? []].join(" ")
3948
+ ]);
3949
+ }
3950
+
3951
+ // packages/agent-spawn/src/configs/claude-code.ts
3952
+ var claudeCodeSpawnConfig = {
3953
+ kind: "cli",
3954
+ agentId: "claude-code",
3955
+ // ACP adapter support: yes (adapter: "claude")
3956
+ adapter: "claude",
3957
+ promptFlag: "-p",
3958
+ modelFlag: "--model",
3959
+ modelStripProviderPrefix: true,
3960
+ modelTransform: (model) => model.replaceAll(".", "-"),
3961
+ defaultArgs: [
3962
+ "--output-format",
3963
+ "stream-json",
3964
+ "--verbose"
3965
+ ],
3966
+ mcpArgs: serializeJsonMcpArgs,
3967
+ modes: {
3968
+ yolo: ["--dangerously-skip-permissions"],
3969
+ edit: ["--permission-mode", "acceptEdits", "--allowedTools", "Bash,Read,Write,Edit,Glob,Grep,NotebookEdit"],
3970
+ read: ["--permission-mode", "plan"]
3971
+ },
3972
+ stdinMode: {
3973
+ omitPrompt: true,
3974
+ extraArgs: ["--input-format", "text"]
3975
+ },
3976
+ interactive: {
3977
+ defaultArgs: []
3978
+ },
3979
+ resumeCommand: (threadId) => ["--resume", threadId]
3980
+ };
3981
+
3982
+ // packages/agent-spawn/src/configs/codex.ts
3983
+ var codexSpawnConfig = {
3984
+ kind: "cli",
3985
+ agentId: "codex",
3986
+ // ACP adapter support: yes (adapter: "codex")
3987
+ adapter: "codex",
3988
+ promptFlag: "exec",
3989
+ modelFlag: "--model",
3990
+ modelStripProviderPrefix: true,
3991
+ defaultArgs: ["--skip-git-repo-check", "--json"],
3992
+ mcpArgs: serializeCodexMcpArgs,
3993
+ mcpArgsBeforeCommand: true,
3994
+ modes: {
3995
+ yolo: ["-s", "danger-full-access"],
3996
+ edit: ["-s", "workspace-write"],
3997
+ read: ["-s", "read-only"]
3998
+ },
3999
+ stdinMode: {
4000
+ omitPrompt: true,
4001
+ extraArgs: ["-"]
4002
+ },
4003
+ interactive: {
4004
+ defaultArgs: ["-a", "never"]
4005
+ },
4006
+ resumeCommand: (threadId, cwd) => ["resume", "-C", cwd, threadId]
4007
+ };
4008
+
4009
+ // packages/agent-spawn/src/configs/opencode.ts
4010
+ var openCodeSpawnConfig = {
4011
+ kind: "cli",
4012
+ agentId: "opencode",
4013
+ // ACP adapter support: yes (adapter: "opencode").
4014
+ // OpenCode's `--format json` emits NDJSON events with `{ type, sessionID, part }`
4015
+ // (no `{ event, ... }` field), so it needs the OpenCode adapter (not "native").
4016
+ adapter: "opencode",
4017
+ promptFlag: "run",
4018
+ modelFlag: "--model",
4019
+ modelStripProviderPrefix: false,
4020
+ modelTransform: (model) => {
4021
+ return model.startsWith("poe/") ? model : `poe/${model}`;
4022
+ },
4023
+ defaultArgs: ["--format", "json"],
4024
+ modes: {
4025
+ yolo: [],
4026
+ edit: [],
4027
+ read: ["--agent", "plan"]
4028
+ },
4029
+ interactive: {
4030
+ defaultArgs: [],
4031
+ promptFlag: "--prompt"
4032
+ },
4033
+ resumeCommand: (threadId, cwd) => [cwd, "--session", threadId],
4034
+ mcpEnv: serializeOpenCodeMcpEnv
4035
+ };
4036
+ var openCodeAcpSpawnConfig = {
4037
+ kind: "acp",
4038
+ agentId: "opencode",
4039
+ acpArgs: ["acp"],
4040
+ skipAuth: true,
4041
+ mcpEnv: serializeOpenCodeMcpEnv
4042
+ };
4043
+
4044
+ // packages/agent-spawn/src/configs/kimi.ts
4045
+ var kimiSpawnConfig = {
4046
+ kind: "cli",
4047
+ agentId: "kimi",
4048
+ // ACP adapter support: yes (adapter: "kimi").
4049
+ // Kimi's `--output-format stream-json` emits OpenAI-style `{ role, content }` JSON
4050
+ // (no `{ event, ... }` field), so it needs the Kimi adapter (not "native").
4051
+ adapter: "kimi",
4052
+ promptFlag: "-p",
4053
+ modelStripProviderPrefix: true,
4054
+ defaultArgs: ["--print", "--output-format", "stream-json"],
4055
+ mcpArgs: serializeJsonMcpArgs,
4056
+ modes: {
4057
+ yolo: ["--yolo"],
4058
+ edit: [],
4059
+ read: []
4060
+ },
4061
+ stdinMode: {
4062
+ omitPrompt: true,
4063
+ extraArgs: ["--input-format", "stream-json"]
4064
+ },
4065
+ interactive: {
4066
+ defaultArgs: [],
4067
+ promptFlag: "-p"
4068
+ },
4069
+ resumeCommand: (threadId, cwd) => ["--session", threadId, "--work-dir", cwd]
4070
+ };
4071
+ var kimiAcpSpawnConfig = {
4072
+ kind: "acp",
4073
+ agentId: "kimi",
4074
+ acpArgs: ["acp"]
4075
+ };
4076
+
4077
+ // packages/agent-spawn/src/configs/goose.ts
4078
+ var gooseFileSecretsEnv = { GOOSE_DISABLE_KEYRING: "1" };
4079
+ var gooseSpawnConfig = {
4080
+ kind: "cli",
4081
+ agentId: "goose",
4082
+ adapter: "native",
4083
+ promptFlag: "--text",
4084
+ modelFlag: "--model",
4085
+ modelStripProviderPrefix: false,
4086
+ defaultArgs: ["run", "--output-format", "stream-json"],
4087
+ defaultArgsPosition: "beforePrompt",
4088
+ mcpArgs: serializeGooseMcpArgs,
4089
+ mcpArgsPosition: "beforePrompt",
4090
+ modes: {
4091
+ yolo: { env: { ...gooseFileSecretsEnv, GOOSE_MODE: "auto" } },
4092
+ edit: { env: { ...gooseFileSecretsEnv, GOOSE_MODE: "smart_approve" } },
4093
+ read: { env: { ...gooseFileSecretsEnv, GOOSE_MODE: "chat" } }
4094
+ },
4095
+ stdinMode: {
4096
+ omitPrompt: true,
4097
+ extraArgs: ["--instructions", "-"]
4098
+ },
4099
+ interactive: {
4100
+ defaultArgs: ["session"],
4101
+ defaultArgsPosition: "beforePrompt"
4102
+ },
4103
+ resumeCommand: () => ["run", "--resume", "--text", "continue"]
4104
+ };
4105
+ var gooseAcpSpawnConfig = {
4106
+ kind: "acp",
4107
+ agentId: "goose",
4108
+ acpArgs: ["acp"],
4109
+ env: gooseFileSecretsEnv,
4110
+ skipAuth: true
4111
+ };
4112
+
4113
+ // packages/agent-spawn/src/configs/index.ts
4114
+ var allSpawnConfigs = [
4115
+ claudeCodeSpawnConfig,
4116
+ codexSpawnConfig,
4117
+ openCodeSpawnConfig,
4118
+ kimiSpawnConfig,
4119
+ gooseSpawnConfig
4120
+ ];
4121
+ var lookup2 = /* @__PURE__ */ new Map();
4122
+ for (const config of allSpawnConfigs) {
4123
+ lookup2.set(config.agentId, config);
4124
+ }
4125
+ var acpLookup = /* @__PURE__ */ new Map();
4126
+ acpLookup.set(openCodeAcpSpawnConfig.agentId, openCodeAcpSpawnConfig);
4127
+ acpLookup.set(kimiAcpSpawnConfig.agentId, kimiAcpSpawnConfig);
4128
+ acpLookup.set(gooseAcpSpawnConfig.agentId, gooseAcpSpawnConfig);
4129
+ function getSpawnConfig(input) {
4130
+ const resolvedId = resolveAgentId(input);
4131
+ if (!resolvedId) {
4132
+ return void 0;
4133
+ }
4134
+ return lookup2.get(resolvedId);
4135
+ }
4136
+ function listMcpSupportedAgents() {
4137
+ const supported = [];
4138
+ for (const config of allSpawnConfigs) {
4139
+ if (config.kind !== "cli" || typeof config.mcpArgs !== "function" && typeof config.mcpEnv !== "function") {
4140
+ continue;
4141
+ }
4142
+ supported.push(config.agentId);
4143
+ }
4144
+ return supported;
4145
+ }
4146
+
4147
+ // packages/agent-spawn/src/spawn.ts
4148
+ import { mkdirSync, openSync, writeSync, closeSync } from "node:fs";
4149
+ import path19 from "node:path";
4150
+
4151
+ // packages/agent-spawn/src/configs/resolve-config.ts
4152
+ function resolveConfig(agentId) {
4153
+ const resolvedAgentId = resolveAgentId(agentId);
4154
+ if (!resolvedAgentId) {
4155
+ throw new Error(`Unknown agent "${agentId}".`);
4156
+ }
4157
+ const agentDefinition = allAgents.find((agent) => agent.id === resolvedAgentId);
4158
+ if (!agentDefinition) {
4159
+ throw new Error(`Unknown agent "${agentId}".`);
4160
+ }
4161
+ const spawnConfig = getSpawnConfig(resolvedAgentId);
4162
+ const binaryName = agentDefinition.binaryName;
4163
+ return { agentId: resolvedAgentId, binaryName, spawnConfig };
4164
+ }
4165
+
4166
+ // packages/agent-spawn/src/mcp-args.ts
4167
+ function hasMcpServers(servers) {
4168
+ if (!servers) {
4169
+ return false;
4170
+ }
4171
+ return Object.keys(servers).length > 0;
4172
+ }
4173
+ function getMcpArgs(config, servers) {
4174
+ if (!hasMcpServers(servers)) {
4175
+ return [];
4176
+ }
4177
+ if (!config.mcpArgs && !config.mcpEnv) {
4178
+ throw new Error(formatUnsupportedMcpSpawnMessage(config.agentId));
4179
+ }
4180
+ if (!config.mcpArgs) {
4181
+ return [];
4182
+ }
4183
+ return config.mcpArgs(servers);
4184
+ }
4185
+ function formatUnsupportedMcpSpawnMessage(agentId) {
4186
+ const supported = listMcpSupportedAgents();
4187
+ const supportedText = supported.length > 0 ? supported.join(", ") : "(none)";
4188
+ return `Agent "${agentId}" does not support MCP servers at spawn time.
4189
+ Agents with spawn-time MCP support: ${supportedText}`;
4190
+ }
4191
+
4192
+ // packages/agent-spawn/src/model-utils.ts
4193
+ function stripModelNamespace(model) {
4194
+ const slashIndex = model.indexOf("/");
4195
+ return slashIndex === -1 ? model : model.slice(slashIndex + 1);
4196
+ }
4197
+
4198
+ // packages/agent-spawn/src/spawn.ts
4199
+ function resolveCliConfig(agentId) {
4200
+ const resolved = resolveConfig(agentId);
4201
+ if (!resolved.spawnConfig) {
4202
+ throw new Error(`Agent "${resolved.agentId}" has no spawn config.`);
4203
+ }
4204
+ if (resolved.spawnConfig.kind !== "cli") {
4205
+ throw new Error(`Agent "${resolved.agentId}" does not support CLI spawn.`);
4206
+ }
4207
+ if (!resolved.binaryName) {
4208
+ throw new Error(`Agent "${resolved.agentId}" has no binaryName.`);
4209
+ }
4210
+ return {
4211
+ agentId: resolved.agentId,
4212
+ binaryName: resolved.binaryName,
4213
+ spawnConfig: resolved.spawnConfig
4214
+ };
4215
+ }
4216
+ function getDefaultArgsPosition(config) {
4217
+ return config.defaultArgsPosition ?? "afterPrompt";
4218
+ }
4219
+ function getMcpArgsPosition(config) {
4220
+ if (config.mcpArgsPosition) {
4221
+ return config.mcpArgsPosition;
4222
+ }
4223
+ return config.mcpArgsBeforeCommand ? "beforeCommand" : "afterCommand";
4224
+ }
4225
+ function buildCliArgs(config, options, stdinMode) {
4226
+ const mcpArgs = getMcpArgs(config, options.mcpServers);
4227
+ const defaultArgsPosition = getDefaultArgsPosition(config);
4228
+ const mcpArgsPosition = getMcpArgsPosition(config);
4229
+ const args = [];
4230
+ if (mcpArgsPosition === "beforeCommand") {
4231
+ args.push(...mcpArgs);
4232
+ }
4233
+ if (defaultArgsPosition === "beforePrompt") {
4234
+ args.push(...config.defaultArgs);
4235
+ }
4236
+ if (mcpArgsPosition === "beforePrompt") {
4237
+ args.push(...mcpArgs);
4238
+ }
4239
+ if (stdinMode) {
4240
+ args.push(
4241
+ config.promptFlag,
4242
+ ...stdinMode.omitPrompt ? [] : [options.prompt],
4243
+ ...stdinMode.extraArgs
4244
+ );
4245
+ } else {
4246
+ args.push(config.promptFlag, options.prompt);
4247
+ }
4248
+ if (options.model && config.modelFlag) {
4249
+ let model = config.modelStripProviderPrefix ? stripModelNamespace(options.model) : options.model;
4250
+ if (config.modelTransform) model = config.modelTransform(model);
4251
+ args.push(config.modelFlag, model);
4252
+ }
4253
+ if (defaultArgsPosition === "afterPrompt") {
4254
+ args.push(...config.defaultArgs);
4255
+ }
4256
+ if (mcpArgsPosition === "afterCommand") {
4257
+ args.push(...mcpArgs);
4258
+ }
4259
+ const mode = resolveModeConfig(config.modes[options.mode ?? "yolo"]);
4260
+ args.push(...mode.args);
4261
+ if (options.args && options.args.length > 0) {
4262
+ args.push(...options.args);
4263
+ }
4264
+ return { args, env: mode.env };
4265
+ }
4266
+ function buildSpawnArgs(agentId, options) {
4267
+ const { binaryName, spawnConfig } = resolveCliConfig(agentId);
4268
+ const stdinMode = options.useStdin && spawnConfig.stdinMode ? spawnConfig.stdinMode : void 0;
4269
+ const result = buildCliArgs(spawnConfig, options, stdinMode);
4270
+ return { binaryName, args: result.args, env: result.env };
4271
+ }
4272
+
4273
+ // packages/design-system/src/tokens/colors.ts
4274
+ import chalk from "chalk";
4275
+ var dark = {
4276
+ header: (text4) => chalk.magentaBright.bold(text4),
4277
+ divider: (text4) => chalk.dim(text4),
4278
+ prompt: (text4) => chalk.cyan(text4),
4279
+ number: (text4) => chalk.cyanBright(text4),
4280
+ intro: (text4) => chalk.bgMagenta.white(` Poe - ${text4} `),
4281
+ resolvedSymbol: chalk.magenta("\u25C7"),
4282
+ errorSymbol: chalk.red("\u25A0"),
4283
+ accent: (text4) => chalk.cyan(text4),
4284
+ muted: (text4) => chalk.dim(text4),
4285
+ success: (text4) => chalk.green(text4),
4286
+ warning: (text4) => chalk.yellow(text4),
4287
+ error: (text4) => chalk.red(text4),
4288
+ info: (text4) => chalk.magenta(text4),
4289
+ badge: (text4) => chalk.bgYellow.black(` ${text4} `)
4290
+ };
4291
+ var light = {
4292
+ header: (text4) => chalk.hex("#a200ff").bold(text4),
4293
+ divider: (text4) => chalk.hex("#666666")(text4),
4294
+ prompt: (text4) => chalk.hex("#006699").bold(text4),
4295
+ number: (text4) => chalk.hex("#0077cc").bold(text4),
4296
+ intro: (text4) => chalk.bgHex("#a200ff").white(` Poe - ${text4} `),
4297
+ resolvedSymbol: chalk.hex("#a200ff")("\u25C7"),
4298
+ errorSymbol: chalk.hex("#cc0000")("\u25A0"),
4299
+ accent: (text4) => chalk.hex("#006699").bold(text4),
4300
+ muted: (text4) => chalk.hex("#666666")(text4),
4301
+ success: (text4) => chalk.hex("#008800")(text4),
4302
+ warning: (text4) => chalk.hex("#cc6600")(text4),
4303
+ error: (text4) => chalk.hex("#cc0000")(text4),
4304
+ info: (text4) => chalk.hex("#a200ff")(text4),
4305
+ badge: (text4) => chalk.bgHex("#cc6600").white(` ${text4} `)
4306
+ };
4307
+
4308
+ // packages/design-system/src/tokens/typography.ts
4309
+ import chalk2 from "chalk";
4310
+
4311
+ // packages/design-system/src/components/text.ts
4312
+ import chalk3 from "chalk";
4313
+
4314
+ // packages/design-system/src/internal/output-format.ts
4315
+ import { AsyncLocalStorage } from "node:async_hooks";
4316
+ var VALID_FORMATS = /* @__PURE__ */ new Set(["terminal", "markdown", "json"]);
4317
+ var formatStorage = new AsyncLocalStorage();
4318
+ var cached;
4319
+ function resolveOutputFormat(env = process.env) {
4320
+ const scoped = formatStorage.getStore();
4321
+ if (scoped) {
4322
+ return scoped;
4323
+ }
4324
+ if (cached) {
4325
+ return cached;
4326
+ }
4327
+ const raw = env.OUTPUT_FORMAT?.toLowerCase();
4328
+ cached = VALID_FORMATS.has(raw) ? raw : "terminal";
4329
+ return cached;
4330
+ }
4331
+
4332
+ // packages/design-system/src/internal/theme-detect.ts
4333
+ function detectThemeFromEnv(env) {
4334
+ const apple = env.APPLE_INTERFACE_STYLE;
4335
+ if (typeof apple === "string") {
4336
+ return apple.toLowerCase() === "dark" ? "dark" : "light";
4337
+ }
4338
+ const vscodeKind = env.VSCODE_COLOR_THEME_KIND;
4339
+ if (typeof vscodeKind === "string") {
4340
+ const normalized = vscodeKind.toLowerCase();
4341
+ if (normalized.includes("light")) {
4342
+ return "light";
4343
+ }
4344
+ if (normalized.includes("dark")) {
4345
+ return "dark";
4346
+ }
4347
+ }
4348
+ const colorFGBG = env.COLORFGBG;
4349
+ if (typeof colorFGBG === "string") {
4350
+ const parts = colorFGBG.split(";").map((part) => Number.parseInt(part, 10));
4351
+ const background = parts.at(-1);
4352
+ if (Number.isFinite(background)) {
4353
+ return background >= 8 ? "light" : "dark";
4354
+ }
4355
+ }
4356
+ return void 0;
4357
+ }
4358
+ function resolveThemeName(env = process.env) {
4359
+ const raw = (env.POE_CODE_THEME ?? env.POE_THEME)?.toLowerCase();
4360
+ if (raw === "light" || raw === "dark") {
4361
+ return raw;
4362
+ }
4363
+ const detected = detectThemeFromEnv(env);
4364
+ if (detected) {
4365
+ return detected;
4366
+ }
4367
+ return "dark";
4368
+ }
4369
+ var cachedTheme;
4370
+ function getTheme(env) {
4371
+ if (cachedTheme) {
4372
+ return cachedTheme;
4373
+ }
4374
+ const themeName = resolveThemeName(env);
4375
+ cachedTheme = themeName === "light" ? light : dark;
4376
+ return cachedTheme;
4377
+ }
4378
+
4379
+ // packages/design-system/src/components/symbols.ts
4380
+ import chalk4 from "chalk";
4381
+ var symbols = {
4382
+ get info() {
4383
+ const format = resolveOutputFormat();
4384
+ if (format === "json") return "info";
4385
+ if (format === "markdown") return "(i)";
4386
+ return chalk4.magenta("\u25CF");
4387
+ },
4388
+ get success() {
4389
+ const format = resolveOutputFormat();
4390
+ if (format === "json") return "success";
4391
+ if (format === "markdown") return "[ok]";
4392
+ return chalk4.magenta("\u25C6");
4393
+ },
4394
+ get resolved() {
4395
+ const format = resolveOutputFormat();
4396
+ if (format === "json") return "resolved";
4397
+ if (format === "markdown") return ">";
4398
+ return getTheme().resolvedSymbol;
4399
+ },
4400
+ get errorResolved() {
4401
+ const format = resolveOutputFormat();
4402
+ if (format === "json") return "error";
4403
+ if (format === "markdown") return "[!]";
4404
+ return getTheme().errorSymbol;
4405
+ },
4406
+ get bar() {
4407
+ const format = resolveOutputFormat();
4408
+ if (format === "json") return "";
4409
+ if (format === "markdown") return "|";
4410
+ return "\u2502";
4411
+ },
4412
+ cornerTopRight: "\u256E",
4413
+ cornerBottomRight: "\u256F",
4414
+ get warning() {
4415
+ const format = resolveOutputFormat();
4416
+ if (format === "json") return "warning";
4417
+ if (format === "markdown") return "[!]";
4418
+ return "\u25B2";
4419
+ },
4420
+ get active() {
4421
+ const format = resolveOutputFormat();
4422
+ if (format === "json") return "active";
4423
+ if (format === "markdown") return "[x]";
4424
+ return "\u25C6";
4425
+ },
4426
+ get inactive() {
4427
+ const format = resolveOutputFormat();
4428
+ if (format === "json") return "inactive";
4429
+ if (format === "markdown") return "[ ]";
4430
+ return "\u25CB";
4431
+ }
4432
+ };
4433
+
4434
+ // packages/design-system/src/components/logger.ts
4435
+ import chalk6 from "chalk";
4436
+
4437
+ // packages/design-system/src/prompts/primitives/log.ts
4438
+ import chalk5 from "chalk";
4439
+
4440
+ // packages/design-system/src/internal/strip-ansi.ts
4441
+ function stripAnsi(value) {
4442
+ return value.replace(/\u001b\[[0-9;]*m/g, "");
4443
+ }
4444
+
4445
+ // packages/design-system/src/prompts/primitives/log.ts
4446
+ function writeTerminalMessage(msg, {
4447
+ symbol = chalk5.gray("\u2502"),
4448
+ secondarySymbol = chalk5.gray("\u2502"),
4449
+ spacing: spacing2 = 1,
4450
+ withGuide = true
4451
+ } = {}) {
4452
+ const lines = [];
4453
+ const showGuide = withGuide !== false;
4454
+ const contentLines = msg.split("\n");
4455
+ const prefix = showGuide ? `${symbol} ` : "";
4456
+ const continuationPrefix = showGuide ? `${secondarySymbol} ` : "";
4457
+ const emptyGuide = showGuide ? secondarySymbol : "";
4458
+ for (let index = 0; index < spacing2; index += 1) {
4459
+ lines.push(emptyGuide);
4460
+ }
4461
+ if (contentLines.length === 0) {
4462
+ process.stdout.write("\n");
4463
+ return;
4464
+ }
4465
+ const [firstLine = "", ...continuationLines] = contentLines;
4466
+ if (firstLine.length > 0) {
4467
+ lines.push(`${prefix}${firstLine}`);
4468
+ } else {
4469
+ lines.push(showGuide ? symbol : "");
4470
+ }
4471
+ for (const line of continuationLines) {
4472
+ if (line.length > 0) {
4473
+ lines.push(`${continuationPrefix}${line}`);
4474
+ continue;
4475
+ }
4476
+ lines.push(emptyGuide);
4477
+ }
4478
+ process.stdout.write(`${lines.join("\n")}
4479
+ `);
4480
+ }
4481
+ function message(msg, options) {
4482
+ const format = resolveOutputFormat();
4483
+ if (format === "markdown") {
4484
+ process.stdout.write(`- ${stripAnsi(msg)}
4485
+ `);
4486
+ return;
4487
+ }
4488
+ if (format === "json") {
4489
+ process.stdout.write(
4490
+ `${JSON.stringify({ level: "message", message: stripAnsi(msg) })}
4491
+ `
4492
+ );
4493
+ return;
4494
+ }
4495
+ writeTerminalMessage(msg, options);
4496
+ }
4497
+ function info(msg) {
4498
+ const format = resolveOutputFormat();
4499
+ if (format === "markdown") {
4500
+ process.stdout.write(`- **info:** ${stripAnsi(msg)}
4501
+ `);
4502
+ return;
4503
+ }
4504
+ if (format === "json") {
4505
+ process.stdout.write(
4506
+ `${JSON.stringify({ level: "info", message: stripAnsi(msg) })}
4507
+ `
4508
+ );
4509
+ return;
4510
+ }
4511
+ message(msg, { symbol: symbols.info });
4512
+ }
4513
+ function success(msg) {
4514
+ const format = resolveOutputFormat();
4515
+ if (format === "markdown") {
4516
+ process.stdout.write(`- **success:** ${stripAnsi(msg)}
4517
+ `);
4518
+ return;
4519
+ }
4520
+ if (format === "json") {
4521
+ process.stdout.write(
4522
+ `${JSON.stringify({ level: "success", message: stripAnsi(msg) })}
4523
+ `
4524
+ );
4525
+ return;
4526
+ }
4527
+ message(msg, { symbol: symbols.success });
4528
+ }
4529
+ function warn(msg) {
4530
+ const format = resolveOutputFormat();
4531
+ if (format === "markdown") {
4532
+ process.stdout.write(`- **warning:** ${stripAnsi(msg)}
4533
+ `);
4534
+ return;
4535
+ }
4536
+ if (format === "json") {
4537
+ process.stdout.write(
4538
+ `${JSON.stringify({ level: "warn", message: stripAnsi(msg) })}
4539
+ `
4540
+ );
4541
+ return;
4542
+ }
4543
+ message(msg, { symbol: chalk5.yellow("\u25B2") });
4544
+ }
4545
+ function error(msg) {
4546
+ const format = resolveOutputFormat();
4547
+ if (format === "markdown") {
4548
+ process.stdout.write(`- **error:** ${stripAnsi(msg)}
4549
+ `);
4550
+ return;
4551
+ }
4552
+ if (format === "json") {
4553
+ process.stdout.write(
4554
+ `${JSON.stringify({ level: "error", message: stripAnsi(msg) })}
4555
+ `
4556
+ );
4557
+ return;
4558
+ }
4559
+ message(msg, { symbol: chalk5.red("\u25A0") });
4560
+ }
4561
+ var log = {
4562
+ info,
4563
+ success,
4564
+ message,
4565
+ warn,
4566
+ error
4567
+ };
4568
+
4569
+ // packages/design-system/src/components/logger.ts
4570
+ function createLogger(emitter) {
4571
+ const emit = (level, message2) => {
4572
+ if (emitter) {
4573
+ emitter(message2);
4574
+ return;
4575
+ }
4576
+ if (level === "success") {
4577
+ log.success(message2);
4578
+ return;
4579
+ }
4580
+ if (level === "warn") {
4581
+ log.warn(message2);
4582
+ return;
4583
+ }
4584
+ if (level === "error") {
4585
+ log.error(message2);
4586
+ return;
4587
+ }
4588
+ log.info(message2);
4589
+ };
4590
+ return {
4591
+ info(message2) {
4592
+ emit("info", message2);
4593
+ },
4594
+ success(message2) {
4595
+ emit("success", message2);
4596
+ },
4597
+ warn(message2) {
4598
+ emit("warn", message2);
4599
+ },
4600
+ error(message2) {
4601
+ emit("error", message2);
4602
+ },
4603
+ resolved(label, value) {
4604
+ if (emitter) {
4605
+ emitter(`${label}: ${value}`);
4606
+ return;
4607
+ }
4608
+ log.message(`${label}
4609
+ ${value}`, { symbol: symbols.resolved });
4610
+ },
4611
+ errorResolved(label, value) {
4612
+ if (emitter) {
4613
+ emitter(`${label}: ${value}`);
4614
+ return;
4615
+ }
4616
+ log.message(`${label}
4617
+ ${value}`, { symbol: symbols.errorResolved });
4618
+ },
4619
+ message(message2, symbol) {
4620
+ if (emitter) {
4621
+ emitter(message2);
4622
+ return;
4623
+ }
4624
+ log.message(message2, { symbol: symbol ?? chalk6.gray("\u2502") });
4625
+ }
4626
+ };
4627
+ }
4628
+ var logger = createLogger();
4629
+
4630
+ // packages/design-system/src/components/table.ts
4631
+ import { Table } from "console-table-printer";
4632
+
4633
+ // packages/design-system/src/acp/components.ts
4634
+ import chalk7 from "chalk";
4635
+
4636
+ // packages/design-system/src/acp/writer.ts
4637
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
4638
+ var storage = new AsyncLocalStorage2();
4639
+
4640
+ // packages/design-system/src/acp/components.ts
4641
+ var AGENT_PREFIX = `${chalk7.green.bold("\u2713")} agent: `;
4642
+
4643
+ // packages/design-system/src/dashboard/buffer.ts
4644
+ import chalk8 from "chalk";
4645
+
4646
+ // packages/design-system/src/dashboard/terminal.ts
4647
+ import readline from "node:readline";
4648
+ import { PassThrough as PassThrough2 } from "node:stream";
4649
+
4650
+ // packages/design-system/src/prompts/index.ts
4651
+ import chalk15 from "chalk";
4652
+ import * as clack from "@clack/prompts";
4653
+
4654
+ // packages/design-system/src/prompts/primitives/cancel.ts
4655
+ import chalk9 from "chalk";
4656
+ import { isCancel } from "@clack/prompts";
4657
+
4658
+ // packages/design-system/src/prompts/primitives/intro.ts
4659
+ import chalk10 from "chalk";
4660
+
4661
+ // packages/design-system/src/prompts/primitives/note.ts
4662
+ import chalk11 from "chalk";
4663
+
4664
+ // packages/design-system/src/prompts/primitives/outro.ts
4665
+ import chalk12 from "chalk";
4666
+
4667
+ // packages/design-system/src/prompts/primitives/spinner.ts
4668
+ import chalk14 from "chalk";
4669
+
4670
+ // packages/design-system/src/static/spinner.ts
4671
+ import chalk13 from "chalk";
4672
+
4673
+ // packages/design-system/src/static/menu.ts
4674
+ import chalk16 from "chalk";
4675
+
4676
+ // packages/agent-spawn/src/autonomous.ts
4677
+ var DEFAULT_ACTIVITY_TIMEOUT_MS = 10 * 60 * 1e3;
4678
+
4679
+ // packages/agent-spawn/src/acp/replay.ts
4680
+ import path20 from "node:path";
4681
+ import { homedir as homedir2 } from "node:os";
4682
+ import { open as open2, readdir as readdir2 } from "node:fs/promises";
4683
+ import { createInterface } from "node:readline";
4684
+
4685
+ // packages/poe-acp-client/src/acp-client.ts
4686
+ import { isAbsolute } from "node:path";
4687
+
4688
+ // packages/poe-acp-client/src/acp-transport.ts
4689
+ import {
4690
+ spawn as spawnChildProcess3
4691
+ } from "node:child_process";
4692
+
4693
+ // packages/poe-acp-client/src/run-report.ts
4694
+ import * as fsPromises2 from "node:fs/promises";
4695
+ import { homedir } from "node:os";
4696
+ import { join } from "node:path";
4697
+
4698
+ // packages/agent-spawn/src/acp/middlewares/spawn-log.ts
4699
+ import path21 from "node:path";
4700
+ import { homedir as homedir3 } from "node:os";
4701
+ import { mkdir, open as open3 } from "node:fs/promises";
4702
+
4703
+ // src/utils/command-checks.ts
4704
+ function formatCommandRunnerResult(result) {
4705
+ const stdout = result.stdout.length > 0 ? result.stdout : "<empty>";
4706
+ const stderr = result.stderr.length > 0 ? result.stderr : "<empty>";
4707
+ return `stdout:
4708
+ ${stdout}
4709
+ stderr:
4710
+ ${stderr}`;
4711
+ }
4712
+ function createSpawnHealthCheck(agentId, options) {
4713
+ const prompt = `Output exactly: ${options.expectedOutput}`;
4714
+ const { binaryName, args, env: modeEnv } = buildSpawnArgs(agentId, {
4715
+ prompt,
4716
+ model: options.model,
4717
+ mode: "yolo"
4718
+ });
4719
+ return {
4720
+ id: `${agentId}-cli-health`,
4721
+ description: `spawn ${agentId} (expecting "${options.expectedOutput}")`,
4722
+ async run(context) {
4723
+ if (context.isDryRun) {
4724
+ context.logDryRun?.(
4725
+ `Dry run: ${[binaryName, ...args].join(" ")} (expecting "${options.expectedOutput}")`
4726
+ );
4727
+ return;
4728
+ }
4729
+ const result = modeEnv ? await context.runCommand(binaryName, args, { env: modeEnv }) : await context.runCommand(binaryName, args);
4730
+ if (result.exitCode !== 0) {
4731
+ throw new Error(
4732
+ `spawn ${agentId} failed with exit code ${result.exitCode}.
4733
+ ${formatCommandRunnerResult(result)}`
4734
+ );
4735
+ }
4736
+ if (!result.stdout.includes(options.expectedOutput)) {
4737
+ throw new Error(
4738
+ `spawn ${agentId}: expected "${options.expectedOutput}" in stdout.
4739
+ ${formatCommandRunnerResult(result)}`
4740
+ );
4741
+ }
4742
+ }
4743
+ };
4744
+ }
4745
+ function createBinaryExistsCheck(binaryName, id, description) {
4746
+ return {
4747
+ id,
4748
+ description,
4749
+ async run({ runCommand: runCommand2 }) {
4750
+ for (const detector of createBinaryExistsDetectors(binaryName)) {
4751
+ const result = await runCommand2(detector.command, detector.args);
4752
+ if (detector.validate(result)) {
4753
+ return;
4754
+ }
4755
+ }
4756
+ throw new Error(`${binaryName} CLI binary not found on PATH.`);
4757
+ }
4758
+ };
4759
+ }
4760
+
2127
4761
  // src/cli/constants.ts
2128
4762
  var CLAUDE_CODE_VARIANTS = {
2129
4763
  haiku: "anthropic/claude-haiku-4.5",