Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix: remove server workdir path and add workdir init

Gus75e6b4250c54
diff --git a/src/cli/daemon/agent/__tests__/codex.test.ts b/src/cli/daemon/agent/__tests__/codex.test.ts
index 68aec9e43..0276402cd 100644
--- a/src/cli/daemon/agent/__tests__/codex.test.ts
+++ b/src/cli/daemon/agent/__tests__/codex.test.ts
@@ -48,7 +48,7 @@ async function collectMessages(
return collected;
}
-const { CodexBackend, extractThreadID, nilIfEmpty } = await import("../codex.js");
+const { CodexBackend, extractThreadID } = await import("../codex.js");
function getMock() {
return currentMockProc!;
@@ -104,18 +104,6 @@ describe("extractThreadID", () => {
});
});
-describe("nilIfEmpty", () => {
- it("returns undefined for empty/null", () => {
- expect(nilIfEmpty("")).toBeUndefined();
- expect(nilIfEmpty(null)).toBeUndefined();
- expect(nilIfEmpty(undefined)).toBeUndefined();
- });
-
- it("returns string when non-empty", () => {
- expect(nilIfEmpty("hello")).toBe("hello");
- });
-});
-
describe("CodexBackend", () => {
let backend: InstanceType<typeof CodexBackend>;
@@ -161,10 +149,9 @@ describe("CodexBackend", () => {
await session.result;
});
- it("thread/start includes correct params (no prompt)", async () => {
+ it("thread/start includes correct params without developerInstructions", async () => {
const session = backend.execute("hello", {
cwd: "/tmp",
- systemPrompt: "You are helpful",
model: "gpt-4",
});
const mock = getMock();
@@ -180,9 +167,8 @@ describe("CodexBackend", () => {
expect(parsed.params.sandbox).toBe("workspace-write");
expect(parsed.params.persistExtendedHistory).toBe(true);
expect(parsed.params.experimentalRawEvents).toBe(false);
- expect(parsed.params.developerInstructions).toBe("You are helpful");
+ expect(parsed.params.developerInstructions).toBeUndefined();
expect(parsed.params.model).toBe("gpt-4");
- expect(parsed.params.instructions).toBeUndefined();
mock.proc.emit("close", 1);
await session.result;
diff --git a/src/cli/daemon/agent/__tests__/opencode.test.ts b/src/cli/daemon/agent/__tests__/opencode.test.ts
index 324482137..241d1903a 100644
--- a/src/cli/daemon/agent/__tests__/opencode.test.ts
+++ b/src/cli/daemon/agent/__tests__/opencode.test.ts
@@ -201,17 +201,18 @@ describe("OpenCodeBackend", () => {
expect(env.OPENCODE_PERMISSION).toBe('{"*":"allow"}');
});
- it("uses --prompt for systemPrompt and user prompt as positional arg", () => {
- backend.execute("do things", { cwd: "/tmp", systemPrompt: "You are helpful" });
+ it("merges execenv vars into spawn env and OPENCODE_PERMISSION wins", () => {
+ backend.execute("hello", {
+ cwd: "/tmp",
+ env: { ALOOK_WORKSPACE_ID: "ws1", OPENCODE_PERMISSION: "should-be-overridden" },
+ });
expect(lastSpawnArgs).toBeTruthy();
- const args = lastSpawnArgs!.args;
- const promptIdx = args.indexOf("--prompt");
- expect(promptIdx).toBeGreaterThan(-1);
- expect(args[promptIdx + 1]).toBe("You are helpful");
- expect(args[args.length - 1]).toBe("do things");
+ const env = lastSpawnArgs!.opts.env as Record<string, string>;
+ expect(env.ALOOK_WORKSPACE_ID).toBe("ws1");
+ expect(env.OPENCODE_PERMISSION).toBe('{"*":"allow"}');
});
- it("without systemPrompt, no --prompt flag, user prompt is positional", () => {
+ it("does not pass --prompt flag, user prompt is positional", () => {
backend.execute("do things", { cwd: "/tmp" });
expect(lastSpawnArgs).toBeTruthy();
const args = lastSpawnArgs!.args;
diff --git a/src/cli/daemon/agent/claude.ts b/src/cli/daemon/agent/claude.ts
index 629979038..db4c6fe11 100644
--- a/src/cli/daemon/agent/claude.ts
+++ b/src/cli/daemon/agent/claude.ts
@@ -25,9 +25,6 @@ export class ClaudeBackend implements AgentBackend {
if (options.maxTurns) {
args.push("--max-turns", String(options.maxTurns));
}
- if (options.systemPrompt) {
- args.push("--append-system-prompt", options.systemPrompt);
- }
if (options.resumeSessionId) {
args.push("--resume", options.resumeSessionId);
}
@@ -35,7 +32,7 @@ export class ClaudeBackend implements AgentBackend {
const proc = spawn(this.cliPath, args, {
cwd: options.cwd,
stdio: ["pipe", "pipe", "pipe"],
- env: { ...process.env },
+ env: { ...process.env, ...options.env },
});
let timedOut = false;
diff --git a/src/cli/daemon/agent/codex.ts b/src/cli/daemon/agent/codex.ts
index 192663da4..542d8c5b9 100644
--- a/src/cli/daemon/agent/codex.ts
+++ b/src/cli/daemon/agent/codex.ts
@@ -39,11 +39,6 @@ export function extractThreadID(response: unknown): string {
return "";
}
-/** Return undefined if the string is empty/null, otherwise the string. */
-export function nilIfEmpty(s: string | undefined | null): string | undefined {
- return s ? s : undefined;
-}
-
export class CodexBackend implements AgentBackend {
name = "codex";
@@ -53,7 +48,7 @@ export class CodexBackend implements AgentBackend {
const proc = spawn(this.cliPath, ["app-server", "--listen", "stdio://"], {
cwd: options.cwd,
stdio: ["pipe", "pipe", "pipe"],
- env: { ...process.env },
+ env: { ...process.env, ...options.env },
});
let timedOut = false;
@@ -429,9 +424,6 @@ export class CodexBackend implements AgentBackend {
threadResponse = await sendRpc("thread/resume", {
threadId: options.resumeSessionId,
...(options.model ? { model: options.model } : {}),
- ...(nilIfEmpty(options.systemPrompt)
- ? { developerInstructions: options.systemPrompt }
- : {}),
});
sessionId = options.resumeSessionId;
} else {
@@ -442,9 +434,6 @@ export class CodexBackend implements AgentBackend {
persistExtendedHistory: true,
experimentalRawEvents: false,
};
- if (nilIfEmpty(options.systemPrompt)) {
- threadParams.developerInstructions = options.systemPrompt;
- }
if (options.model) {
threadParams.model = options.model;
}
diff --git a/src/cli/daemon/agent/opencode.ts b/src/cli/daemon/agent/opencode.ts
index eea61777e..b017f78b6 100644
--- a/src/cli/daemon/agent/opencode.ts
+++ b/src/cli/daemon/agent/opencode.ts
@@ -14,9 +14,6 @@ export class OpenCodeBackend implements AgentBackend {
if (options.model) {
args.push("--model", options.model);
}
- if (options.systemPrompt) {
- args.push("--prompt", options.systemPrompt);
- }
if (options.resumeSessionId) {
args.push("--session", options.resumeSessionId);
}
@@ -27,7 +24,7 @@ export class OpenCodeBackend implements AgentBackend {
const proc = spawn(this.cliPath, args, {
cwd: options.cwd,
stdio: ["pipe", "pipe", "pipe"],
- env: { ...process.env, OPENCODE_PERMISSION: '{"*":"allow"}' },
+ env: { ...process.env, ...options.env, OPENCODE_PERMISSION: '{"*":"allow"}' },
});
let timedOut = false;
diff --git a/src/cli/daemon/client.test.ts b/src/cli/daemon/client.test.ts
index 2149bf0e3..ca2f46c57 100644
--- a/src/cli/daemon/client.test.ts
+++ b/src/cli/daemon/client.test.ts
@@ -28,7 +28,6 @@ describe("DaemonClient claimTask schema validation", () => {
created_at: "2024-01-01T00:00:00Z",
agent: { instructions: "help", name: "bot", runtime_config: {} },
prior_session_id: "sess-0",
- prior_work_dir: "/tmp",
},
};
@@ -185,7 +184,6 @@ function validApiTask(): TaskApi {
created_at: "2024-01-01T00:00:00Z",
agent: { instructions: "help", name: "bot", runtime_config: {} },
prior_session_id: "sess-0",
- prior_work_dir: "/tmp/old",
};
}
@@ -203,7 +201,6 @@ describe("fromApiTask", () => {
expect(task.agent?.name).toBe("bot");
expect(task.agent?.instructions).toBe("help");
expect(task.priorSessionId).toBe("sess-0");
- expect(task.priorWorkDir).toBe("/tmp/old");
expect(task.createdAt).toBe("2024-01-01T00:00:00Z");
});
diff --git a/src/cli/daemon/client.ts b/src/cli/daemon/client.ts
index 6908c02c0..61f2a17c8 100644
--- a/src/cli/daemon/client.ts
+++ b/src/cli/daemon/client.ts
@@ -79,7 +79,6 @@ export class DaemonClient {
body: {
output: string;
session_id?: string;
- work_dir?: string;
branch_name?: string;
},
) {
@@ -102,6 +101,7 @@ export class DaemonClient {
seq: number;
type: string;
tool?: string;
+ call_id?: string;
content?: string;
input?: Record<string, unknown>;
output?: string;
diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.ts
index 14a6db418..879ce7f49 100644
--- a/src/cli/daemon/daemon.test.ts
+++ b/src/cli/daemon/daemon.test.ts
@@ -62,6 +62,24 @@ vi.mock("child_process", () => ({
vi.mock("fs", () => ({
mkdirSync: vi.fn(),
+ createWriteStream: vi.fn(() => ({
+ write: vi.fn(),
+ end: vi.fn(),
+ })),
+}));
+
+vi.mock("./execenv/index.js", () => ({
+ prepare: vi.fn(() => ({
+ workDir: "/tmp/ws/ws1/agent1/workdir",
+ logFile: "/tmp/ws/ws1/agent1/agent.log",
+ env: {
+ ALOOK_WORKSPACE_ID: "ws1",
+ ALOOK_AGENT_ID: "agent1",
+ ALOOK_TASK_ID: "t1",
+ ALOOK_CONVERSATION_ID: "c1",
+ ALOOK_HEALTH_PORT: "19514",
+ },
+ })),
}));
// Capture signal handlers and prevent actual process.exit
diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.ts
index f96a71807..e122d62df 100644
--- a/src/cli/daemon/daemon.ts
+++ b/src/cli/daemon/daemon.ts
@@ -4,10 +4,11 @@ import { createHealthServer } from "./health.js";
import { buildPrompt } from "./prompt.js";
import { createBackend, detectVersion } from "./agent/index.js";
import { type Task, type TaskResult, fromApiTask } from "./types.js";
+import { prepare } from "./execenv/index.js";
import { loadCLIConfigForProfile } from "../lib/config.js";
import { log } from "../lib/logger.js";
import { cmdPrefix } from "../lib/env.js";
-import { mkdirSync } from "fs";
+import { createWriteStream } from "fs";
import { join } from "path";
import { execSync } from "child_process";
@@ -187,11 +188,9 @@ async function handleTask(
const body: {
output: string;
session_id?: string;
- work_dir?: string;
branch_name?: string;
} = { output: result.comment };
if (result.sessionId) body.session_id = result.sessionId;
- if (result.workDir) body.work_dir = result.workDir;
if (result.branchName) body.branch_name = result.branchName;
await client.completeTask(task.id, body);
log.info(`Task ${task.id} completed`);
@@ -230,20 +229,18 @@ async function runTask(
const backend = createBackend(provider, cliPath);
- let prompt = buildPrompt(task);
- if (task.agent?.instructions) {
- prompt = task.agent.instructions + "\n\n" + prompt;
- }
+ const prompt = buildPrompt(task);
- const workDir = task.priorWorkDir
- ? task.priorWorkDir
- : join(config.workspacesRoot, task.workspaceId, task.agentId, "workdir");
- mkdirSync(workDir, { recursive: true });
+ const { workDir, logFile, env } = prepare(
+ { workspacesRoot: config.workspacesRoot },
+ task,
+ provider,
+ );
const session = backend.execute(prompt, {
cwd: workDir,
model: model || undefined,
- systemPrompt: task.agent?.instructions,
+ env,
timeout: config.agentTimeout,
resumeSessionId: task.priorSessionId,
});
@@ -252,6 +249,7 @@ async function runTask(
seq: number;
type: string;
tool?: string;
+ call_id?: string;
content?: string;
input?: Record<string, unknown>;
output?: string;
@@ -272,6 +270,22 @@ async function runTask(
const flushTimer = setInterval(flushMessages, FLUSH_INTERVAL_MS);
+ // Log capture — append JSONL to agent.log (best-effort)
+ let logStream: ReturnType<typeof createWriteStream> | undefined;
+ try {
+ logStream = createWriteStream(logFile, { flags: "a" });
+ logStream.write(
+ JSON.stringify({
+ ts: new Date().toISOString(),
+ type: "text",
+ role: "user",
+ content: prompt,
+ }) + "\n",
+ );
+ } catch {
+ logStream = undefined;
+ }
+
try {
for await (const msg of session.messages) {
seq++;
@@ -279,11 +293,26 @@ async function runTask(
seq,
type: msg.type,
tool: msg.tool,
+ call_id: msg.callId,
content: msg.content,
input: msg.input,
output: msg.output,
});
+ if (logStream) {
+ try {
+ logStream.write(
+ JSON.stringify({
+ ts: new Date().toISOString(),
+ role: "assistant",
+ ...msg,
+ }) + "\n",
+ );
+ } catch {
+ // skip logging on write failure
+ }
+ }
+
if (pendingMessages.length >= BATCH_SIZE) {
await flushMessages();
}
@@ -292,6 +321,7 @@ async function runTask(
await flushMessages();
} finally {
clearInterval(flushTimer);
+ logStream?.end();
}
const result = await session.result;
@@ -299,6 +329,5 @@ async function runTask(
status: result.status === "completed" ? "completed" : "failed",
comment: result.output || result.error,
sessionId: result.sessionId,
- workDir,
};
}
diff --git a/src/cli/daemon/execenv/__tests__/context.test.ts b/src/cli/daemon/execenv/__tests__/context.test.ts
new file mode 100644
index 000000000..28a54d03f
--- /dev/null
+++ b/src/cli/daemon/execenv/__tests__/context.test.ts
@@ -0,0 +1,142 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { mkdirSync, writeFileSync, readFileSync, unlinkSync, existsSync, rmSync } from "fs";
+import { join } from "path";
+import { tmpdir } from "os";
+import { buildInstructionContent, writeInstructionFile, cleanStaleProviderFiles } from "../context.js";
+import type { Task } from "../../types.js";
+
+function makeTask(overrides: Partial<Task> = {}): Task {
+ return {
+ id: "t1",
+ agentId: "a1",
+ runtimeId: "rt1",
+ conversationId: "c1",
+ workspaceId: "ws1",
+ prompt: "do something",
+ status: "running",
+ priority: 0,
+ createdAt: "2026-01-01T00:00:00Z",
+ agent: { name: "test-agent", instructions: "Be helpful and concise." },
+ ...overrides,
+ };
+}
+
+describe("buildInstructionContent", () => {
+ it("assembles system section + agent instructions section", () => {
+ const task = makeTask();
+ const content = buildInstructionContent(task);
+
+ expect(content).toContain("# Alook Agent Instructions");
+ expect(content).toContain("## System");
+ expect(content).toContain("SYSPROMPT TODO FOR ALOOK");
+ expect(content).toContain("## Agent Instructions");
+ expect(content).toContain("Be helpful and concise.");
+ });
+
+ it("with task.agent undefined — omits agent instructions section, keeps system section", () => {
+ const task = makeTask({ agent: undefined });
+ const content = buildInstructionContent(task);
+
+ expect(content).toContain("## System");
+ expect(content).toContain("SYSPROMPT TODO FOR ALOOK");
+ expect(content).not.toContain("## Agent Instructions");
+ });
+
+ it("with empty instructions string — omits agent instructions section, keeps system section", () => {
+ const task = makeTask({ agent: { name: "test", instructions: "" } });
+ const content = buildInstructionContent(task);
+
+ expect(content).toContain("## System");
+ expect(content).not.toContain("## Agent Instructions");
+ });
+});
+
+describe("writeInstructionFile", () => {
+ let workDir: string;
+
+ beforeEach(() => {
+ workDir = join(tmpdir(), `execenv-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
+ mkdirSync(workDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(workDir, { recursive: true, force: true });
+ });
+
+ it("for Claude — writes CLAUDE.md with assembled content", () => {
+ const task = makeTask();
+ writeInstructionFile(workDir, task, "claude");
+
+ const content = readFileSync(join(workDir, "CLAUDE.md"), "utf-8");
+ expect(content).toContain("# Alook Agent Instructions");
+ expect(content).toContain("Be helpful and concise.");
+ });
+
+ it("for OpenCode — writes AGENTS.md with assembled content", () => {
+ const task = makeTask();
+ writeInstructionFile(workDir, task, "opencode");
+
+ const content = readFileSync(join(workDir, "AGENTS.md"), "utf-8");
+ expect(content).toContain("# Alook Agent Instructions");
+ expect(content).toContain("Be helpful and concise.");
+ });
+
+ it("for Codex — writes AGENTS.md with assembled content", () => {
+ const task = makeTask();
+ writeInstructionFile(workDir, task, "codex");
+
+ const content = readFileSync(join(workDir, "AGENTS.md"), "utf-8");
+ expect(content).toContain("# Alook Agent Instructions");
+ expect(content).toContain("Be helpful and concise.");
+ });
+
+ it("overwrites existing file on re-run with new instructions", () => {
+ const task1 = makeTask({ agent: { name: "a", instructions: "Old instructions" } });
+ writeInstructionFile(workDir, task1, "claude");
+
+ const task2 = makeTask({ agent: { name: "a", instructions: "New instructions" } });
+ writeInstructionFile(workDir, task2, "claude");
+
+ const content = readFileSync(join(workDir, "CLAUDE.md"), "utf-8");
+ expect(content).toContain("New instructions");
+ expect(content).not.toContain("Old instructions");
+ });
+});
+
+describe("cleanStaleProviderFiles", () => {
+ let workDir: string;
+
+ beforeEach(() => {
+ workDir = join(tmpdir(), `execenv-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
+ mkdirSync(workDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(workDir, { recursive: true, force: true });
+ });
+
+ it("for Claude — removes AGENTS.md if present", () => {
+ writeFileSync(join(workDir, "AGENTS.md"), "old");
+ cleanStaleProviderFiles(workDir, "claude");
+
+ expect(existsSync(join(workDir, "AGENTS.md"))).toBe(false);
+ });
+
+ it("for OpenCode — removes CLAUDE.md if present", () => {
+ writeFileSync(join(workDir, "CLAUDE.md"), "old");
+ cleanStaleProviderFiles(workDir, "opencode");
+
+ expect(existsSync(join(workDir, "CLAUDE.md"))).toBe(false);
+ });
+
+ it("for Codex — removes CLAUDE.md if present", () => {
+ writeFileSync(join(workDir, "CLAUDE.md"), "old");
+ cleanStaleProviderFiles(workDir, "codex");
+
+ expect(existsSync(join(workDir, "CLAUDE.md"))).toBe(false);
+ });
+
+ it("does not throw when file does not exist", () => {
+ expect(() => cleanStaleProviderFiles(workDir, "claude")).not.toThrow();
+ });
+});
diff --git a/src/cli/daemon/execenv/__tests__/index.test.ts b/src/cli/daemon/execenv/__tests__/index.test.ts
new file mode 100644
index 000000000..afaf9cbba
--- /dev/null
+++ b/src/cli/daemon/execenv/__tests__/index.test.ts
@@ -0,0 +1,81 @@
+import { describe, it, expect, beforeEach, afterEach } from "vitest";
+import { mkdirSync, existsSync, readFileSync, rmSync } from "fs";
+import { join } from "path";
+import { tmpdir } from "os";
+import { prepare } from "../index.js";
+import type { Task } from "../../types.js";
+
+function makeTask(overrides: Partial<Task> = {}): Task {
+ return {
+ id: "t1",
+ agentId: "a1",
+ runtimeId: "rt1",
+ conversationId: "c1",
+ workspaceId: "ws1",
+ prompt: "do something",
+ status: "running",
+ priority: 0,
+ createdAt: "2026-01-01T00:00:00Z",
+ agent: { name: "test-agent", instructions: "Be helpful." },
+ ...overrides,
+ };
+}
+
+describe("prepare", () => {
+ let root: string;
+
+ beforeEach(() => {
+ root = join(tmpdir(), `execenv-prepare-${Date.now()}-${Math.random().toString(36).slice(2)}`);
+ mkdirSync(root, { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ it("creates workdir directory", () => {
+ const task = makeTask();
+ const result = prepare({ workspacesRoot: root }, task, "claude");
+
+ expect(existsSync(result.workDir)).toBe(true);
+ });
+
+ it("always constructs {root}/{wsId}/{agentId}/workdir", () => {
+ const task = makeTask();
+ const result = prepare({ workspacesRoot: root }, task, "claude");
+
+ expect(result.workDir).toBe(join(root, "ws1", "a1", "workdir"));
+ });
+
+ it("on existing workdir overwrites instruction file with fresh data", () => {
+ const task1 = makeTask({ agent: { name: "a", instructions: "Old" } });
+ prepare({ workspacesRoot: root }, task1, "claude");
+
+ const task2 = makeTask({ agent: { name: "a", instructions: "New" } });
+ const result = prepare({ workspacesRoot: root }, task2, "claude");
+
+ const content = readFileSync(join(result.workDir, "CLAUDE.md"), "utf-8");
+ expect(content).toContain("New");
+ expect(content).not.toContain("Old");
+ });
+
+ it("returns logFile path at {root}/{wsId}/{agentId}/agent.log", () => {
+ const task = makeTask();
+ const result = prepare({ workspacesRoot: root }, task, "claude");
+
+ expect(result.logFile).toBe(join(root, "ws1", "a1", "agent.log"));
+ });
+
+ it("returns env with all expected keys", () => {
+ const task = makeTask();
+ const result = prepare({ workspacesRoot: root }, task, "claude");
+
+ expect(result.env).toEqual({
+ ALOOK_WORKSPACE_ID: "ws1",
+ ALOOK_AGENT_ID: "a1",
+ ALOOK_TASK_ID: "t1",
+ ALOOK_CONVERSATION_ID: "c1",
+ ALOOK_HEALTH_PORT: expect.any(String),
+ });
+ });
+});
diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.ts
new file mode 100644
index 000000000..0eef563ea
--- /dev/null
+++ b/src/cli/daemon/execenv/context.ts
@@ -0,0 +1,54 @@
+import { writeFileSync, unlinkSync } from "fs";
+import { join } from "path";
+import type { Task } from "../types.js";
+
+const INSTRUCTION_FILES = {
+ claude: "CLAUDE.md",
+ opencode: "AGENTS.md",
+ codex: "AGENTS.md",
+} as const;
+
+export function buildInstructionContent(task: Task): string {
+ let content = `# Alook Agent Instructions
+
+## System
+SYSPROMPT TODO FOR ALOOK`;
+
+ if (task.agent?.instructions) {
+ content += `
+
+## Agent Instructions
+${task.agent.instructions}`;
+ }
+
+ return content;
+}
+
+export function writeInstructionFile(
+ workDir: string,
+ task: Task,
+ provider: string,
+): void {
+ const fileName = INSTRUCTION_FILES[provider as keyof typeof INSTRUCTION_FILES];
+ if (!fileName) return;
+
+ const content = buildInstructionContent(task);
+ writeFileSync(join(workDir, fileName), content, "utf-8");
+}
+
+export function cleanStaleProviderFiles(
+ workDir: string,
+ provider: string,
+): void {
+ if (!(provider in INSTRUCTION_FILES)) return;
+
+ try {
+ if (provider === "claude") {
+ unlinkSync(join(workDir, "AGENTS.md"));
+ } else {
+ unlinkSync(join(workDir, "CLAUDE.md"));
+ }
+ } catch (err: unknown) {
+ if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") throw err;
+ }
+}
diff --git a/src/cli/daemon/execenv/index.ts b/src/cli/daemon/execenv/index.ts
new file mode 100644
index 000000000..98a72e4c6
--- /dev/null
+++ b/src/cli/daemon/execenv/index.ts
@@ -0,0 +1,47 @@
+import { mkdirSync } from "fs";
+import { join, dirname } from "path";
+import { writeInstructionFile, cleanStaleProviderFiles } from "./context.js";
+import type { Task } from "../types.js";
+
+export interface ExecEnvConfig {
+ workspacesRoot: string;
+}
+
+export interface ExecEnvResult {
+ workDir: string;
+ logFile: string;
+ env: Record<string, string>;
+}
+
+export function prepare(
+ config: ExecEnvConfig,
+ task: Task,
+ provider: string,
+): ExecEnvResult {
+ const workDir = join(config.workspacesRoot, task.workspaceId, task.agentId, "workdir");
+
+ mkdirSync(workDir, { recursive: true });
+
+ writeInstructionFile(workDir, task, provider);
+ cleanStaleProviderFiles(workDir, provider);
+
+ const logFile = join(
+ config.workspacesRoot,
+ task.workspaceId,
+ task.agentId,
+ "agent.log",
+ );
+ mkdirSync(dirname(logFile), { recursive: true });
+
+ const env: Record<string, string> = {
+ ALOOK_WORKSPACE_ID: task.workspaceId,
+ ALOOK_AGENT_ID: task.agentId,
+ ALOOK_TASK_ID: task.id,
+ ALOOK_CONVERSATION_ID: task.conversationId,
+ ALOOK_HEALTH_PORT: process.env.ALOOK_HEALTH_PORT || "19514",
+ };
+
+ return { workDir, logFile, env };
+}
+
+export { buildInstructionContent, writeInstructionFile, cleanStaleProviderFiles } from "./context.js";
diff --git a/src/cli/daemon/types.ts b/src/cli/daemon/types.ts
index 3845af7ec..3590dc657 100644
--- a/src/cli/daemon/types.ts
+++ b/src/cli/daemon/types.ts
@@ -9,7 +9,6 @@ export interface Task {
priority: number;
agent?: TaskAgentData;
priorSessionId?: string;
- priorWorkDir?: string;
repos?: RepoData[];
createdAt: string;
}
@@ -30,7 +29,6 @@ export interface TaskResult {
comment: string;
branchName?: string;
sessionId?: string;
- workDir?: string;
}
export interface RuntimeInfo {
@@ -70,7 +68,7 @@ export interface AgentResult {
export interface ExecOptions {
cwd: string;
model?: string;
- systemPrompt?: string;
+ env?: Record<string, string>;
maxTurns?: number;
timeout?: number;
resumeSessionId?: string;
@@ -91,7 +89,6 @@ export function fromApiTask(api: import("@alook/shared").TaskApi): Task {
? { name: api.agent.name, instructions: api.agent.instructions }
: undefined,
priorSessionId: api.prior_session_id ?? undefined,
- priorWorkDir: api.prior_work_dir ?? undefined,
repos: undefined,
createdAt: api.created_at,
};