Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
refactor(cli): unify command utilities and fix self-hosted env var fallback (#142)
Generaa10940690f8
diff --git a/src/cli/commands/calendar.ts b/src/cli/commands/calendar.tsindex 5aac67f58..fe55b0c6f 100644--- a/src/cli/commands/calendar.ts+++ b/src/cli/commands/calendar.ts@@ -1,9 +1,8 @@import { Command } from "commander";import { APIClient } from "../lib/client.js";-import { loadCLIConfigForProfile } from "../lib/config.js";import { printJSON } from "../lib/output.js";-import { cmdPrefix } from "../lib/env.js";import { resolveAgentId } from "../lib/flags.js";+import { resolveClientOpts } from "../lib/resolve-client.js";interface CalendarEventResponse {id: string;@@ -21,22 +20,6 @@ interface CalendarEventResponse {updated_at: string;}-function resolveClientOpts(command: Command, agentId: string) {- const parentOpts = command.parent?.parent?.opts() || {};- const profile: string | undefined = parentOpts.profile;- const cfg = loadCLIConfigForProfile(profile);- const serverUrl = parentOpts.server || cfg.server_url;- const workspaces = cfg.watched_workspaces || [];-- const ws = workspaces.find((w) => w.agent_ids?.includes(agentId));- if (!ws || !ws.token) {- console.error(- `Error: no registered workspace contains agent ${agentId}. Run '${cmdPrefix()} register --token <token>' first.`- );- process.exit(1);- }- return { serverUrl, token: ws.token, workspaceId: ws.id };-}function parseLocalDatetime(input: string): string {// Accepts YYYY-MM-DDTHH:MM and interprets as local time.@@ -113,10 +96,7 @@ export function calendarCommand(): Command {.option("--json", "Output as JSON").action(async (opts, command) => {const agentId = resolveAgentId(opts);- const { serverUrl, token, workspaceId } = resolveClientOpts(- command,- agentId- );+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });const client = new APIClient(serverUrl, token, workspaceId);let scheduledAt: string;@@ -177,10 +157,7 @@ export function calendarCommand(): Command {.option("--json", "Output as JSON").action(async (opts, command) => {const agentId = resolveAgentId(opts);- const { serverUrl, token, workspaceId } = resolveClientOpts(- command,- agentId- );+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });const client = new APIClient(serverUrl, token, workspaceId);const now = Date.now();@@ -226,10 +203,7 @@ export function calendarCommand(): Command {.option("--json", "Output as JSON").action(async (opts, command) => {const agentId = resolveAgentId(opts);- const { serverUrl, token, workspaceId } = resolveClientOpts(- command,- agentId- );+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });const client = new APIClient(serverUrl, token, workspaceId);try {@@ -326,10 +300,7 @@ export function calendarCommand(): Command {}const agentId = resolveAgentId(opts);- const { serverUrl, token, workspaceId } = resolveClientOpts(- command,- agentId- );+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });const client = new APIClient(serverUrl, token, workspaceId);try {@@ -361,10 +332,7 @@ export function calendarCommand(): Command {.requiredOption("--event_id <id>", "Event ID").action(async (opts, command) => {const agentId = resolveAgentId(opts);- const { serverUrl, token, workspaceId } = resolveClientOpts(- command,- agentId- );+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });const client = new APIClient(serverUrl, token, workspaceId);try {diff --git a/src/cli/commands/email.ts b/src/cli/commands/email.tsindex 3e20a1824..8f59eca29 100644--- a/src/cli/commands/email.ts+++ b/src/cli/commands/email.ts@@ -1,14 +1,16 @@import { Command } from "commander";-import { writeFileSync, mkdirSync, readFileSync, statSync } from "fs";-import { basename, join } from "path";+import { writeFileSync, mkdirSync, readFileSync } from "fs";+import { join } from "path";import PostalMime from "postal-mime";import { APIClient } from "../lib/client.js";-import { loadCLIConfigForProfile } from "../lib/config.js";import { printJSON, printTable } from "../lib/output.js";-import { cmdPrefix } from "../lib/env.js";import { tempDir } from "../lib/platform.js";import { createLogger } from "../lib/logger.js";-import { resolveAgentId } from "../lib/flags.js";+import { resolveAgentId, collectRepeated } from "../lib/flags.js";+import { resolveClientOpts } from "../lib/resolve-client.js";+import { contentToBuffer, uploadFile } from "../lib/file-utils.js";+import type { UploadedFile } from "../lib/file-utils.js";+import { gatherContextEnvVars } from "../lib/context-env.js";const log = createLogger({ module: "email" });@@ -34,41 +36,6 @@ const VALID_STATUSES = ["unread", "read", "archived", "sent"];const VALID_FOLDERS = ["inbox", "sent", "untrust"];const EMAIL_BASE = tempDir("alook-emails");-const MIME_BY_EXT: Record<string, string> = {- ".pdf": "application/pdf",- ".png": "image/png",- ".jpg": "image/jpeg",- ".jpeg": "image/jpeg",- ".gif": "image/gif",- ".webp": "image/webp",- ".svg": "image/svg+xml",- ".txt": "text/plain",- ".html": "text/html",- ".htm": "text/html",- ".json": "application/json",- ".csv": "text/csv",- ".md": "text/markdown",- ".zip": "application/zip",-};--function guessContentType(filename: string): string {- const idx = filename.lastIndexOf(".");- if (idx < 0) return "application/octet-stream";- const ext = filename.slice(idx).toLowerCase();- return MIME_BY_EXT[ext] ?? "application/octet-stream";-}--function collectRepeated(value: string, previous: string[]): string[] {- return previous.concat([value]);-}--interface AttachmentDescriptor {- key: string;- filename: string;- size: number;- contentType: string;-}-interface SendResponse {id: string;to_email: string;@@ -80,55 +47,6 @@ interface WhitelistEntry {created_at: string;}-function resolveClientOpts(command: Command, opts: { workspace?: string; agentId?: string }) {- let root = command;- while (root.parent) root = root.parent;- const parentOpts = root.opts() || {};- const profile: string | undefined = parentOpts.profile;- const cfg = loadCLIConfigForProfile(profile);- const serverUrl = parentOpts.server || cfg.server_url;- const workspaces = cfg.watched_workspaces || [];-- // Resolve workspace: explicit flag > lookup by agent_id > single workspace- let ws;- if (opts.workspace) {- ws = workspaces.find((w) => w.id === opts.workspace);- if (!ws) {- console.error(`Error: workspace ${opts.workspace} not found in config.`);- process.exit(1);- }- } else if (opts.agentId) {- ws = workspaces.find((w) => w.agent_ids?.includes(opts.agentId!));- if (!ws) {- if (workspaces.length === 1) {- ws = workspaces[0];- } else {- console.error(- `Error: agent ${opts.agentId} not found in any registered workspace. Use --workspace to specify.`,- );- process.exit(1);- }- }- } else if (workspaces.length === 1) {- ws = workspaces[0];- } else {- console.error(- `Error: multiple workspaces registered. Use --workspace to specify which one.`,- );- process.exit(1);- }-- const token = ws?.token;-- if (!token) {- console.error(- `Error: not registered. Run '${cmdPrefix()} register --token <token>' first.`,- );- process.exit(1);- }-- return { serverUrl, token, cfg, profile, workspaceId: ws?.id };-}export function emailCommand(): Command {const cmd = new Command("email").description("Manage agent emails");@@ -263,16 +181,7 @@ export function emailCommand(): Command {}usedFilenames.add(filename);const attPath = join(attDir, filename);- const content = att.content;- let buf: Buffer;- if (typeof content === "string") {- buf = Buffer.from(content, "base64");- } else if (content instanceof ArrayBuffer) {- buf = Buffer.from(new Uint8Array(content));- } else {- buf = Buffer.from(content as Uint8Array);- }- writeFileSync(attPath, buf);+ writeFileSync(attPath, contentToBuffer(att.content));downloadedPaths.push(attPath);}}@@ -359,39 +268,11 @@ export function emailCommand(): Command {}const attachmentPaths: string[] = opts.attachment ?? [];- const attachments: AttachmentDescriptor[] = [];+ const attachments: UploadedFile[] = [];try {- for (const path of attachmentPaths) {- let bytes: Buffer;- let size: number;- try {- bytes = readFileSync(path);- size = statSync(path).size;- } catch (err) {- console.error(- `Error: cannot read attachment "${path}": ${err instanceof Error ? err.message : err}`,- );- process.exit(1);- }- const filename = basename(path);- const contentType = guessContentType(filename);- const form = new FormData();- form.append(- "file",- new Blob([new Uint8Array(bytes)], { type: contentType }),- filename,- );- const uploaded = await client.postMultipart<AttachmentDescriptor>(- "/api/email/upload",- form,- );- attachments.push({- key: uploaded.key,- filename: uploaded.filename,- size: uploaded.size ?? size,- contentType: uploaded.contentType ?? contentType,- });+ for (const filePath of attachmentPaths) {+ attachments.push(await uploadFile(client, filePath, "/api/email/upload"));}// Build threading context if replying@@ -409,9 +290,7 @@ export function emailCommand(): Command {}}- const conversationId = process.env.ALOOK_CONVERSATION_ID;- const traceId = process.env.ALOOK_TRACE_ID;- const sourceTaskId = process.env.ALOOK_TASK_ID;+ const ctx = gatherContextEnvVars();const res = await client.postJSON<SendResponse>("/api/email/send", {agentId,to: opts.to,@@ -420,9 +299,9 @@ export function emailCommand(): Command {attachments,...(inReplyTo ? { inReplyTo, references } : {}),...(opts.from ? { from: opts.from } : {}),- ...(conversationId ? { conversationId } : {}),- ...(traceId ? { traceId } : {}),- ...(sourceTaskId ? { sourceTaskId } : {}),+ ...(ctx.conversationId ? { conversationId: ctx.conversationId } : {}),+ ...(ctx.traceId ? { traceId: ctx.traceId } : {}),+ ...(ctx.sourceTaskId ? { sourceTaskId: ctx.sourceTaskId } : {}),});console.log(`Sent email to ${res.to_email} (id: ${res.id})`);} catch (err) {@@ -485,27 +364,19 @@ export function emailCommand(): Command {const parsed = await new PostalMime().parse(rawMime);// 4. Re-upload original attachments- const attachments: AttachmentDescriptor[] = [];+ const attachments: UploadedFile[] = [];if (parsed.attachments && parsed.attachments.length > 0) {for (const att of parsed.attachments) {const filename = att.filename || "attachment.bin";const contentType = att.mimeType || "application/octet-stream";- const content = att.content;- let buf: Buffer;- if (typeof content === "string") {- buf = Buffer.from(content, "base64");- } else if (content instanceof ArrayBuffer) {- buf = Buffer.from(new Uint8Array(content));- } else {- buf = Buffer.from(content as Uint8Array);- }+ const buf = contentToBuffer(att.content);const form = new FormData();form.append("file",new Blob([new Uint8Array(buf)], { type: contentType }),filename,);- const uploaded = await client.postMultipart<AttachmentDescriptor>(+ const uploaded = await client.postMultipart<UploadedFile>("/api/email/upload",form,);@@ -520,36 +391,8 @@ export function emailCommand(): Command {// 5. Upload extra --attachment filesconst extraPaths: string[] = opts.attachment ?? [];- for (const path of extraPaths) {- let bytes: Buffer;- let size: number;- try {- bytes = readFileSync(path);- size = statSync(path).size;- } catch (err) {- console.error(- `Error: cannot read attachment "${path}": ${err instanceof Error ? err.message : err}`,- );- process.exit(1);- }- const filename = basename(path);- const contentType = guessContentType(filename);- const form = new FormData();- form.append(- "file",- new Blob([new Uint8Array(bytes)], { type: contentType }),- filename,- );- const uploaded = await client.postMultipart<AttachmentDescriptor>(- "/api/email/upload",- form,- );- attachments.push({- key: uploaded.key,- filename: uploaded.filename,- size: uploaded.size ?? size,- contentType: uploaded.contentType ?? contentType,- });+ for (const filePath of extraPaths) {+ attachments.push(await uploadFile(client, filePath, "/api/email/upload"));}// 6. Compose forwarded HTML body@@ -574,9 +417,7 @@ export function emailCommand(): Command {: `Fwd: ${original.subject}`;// 8. Send- const conversationId = process.env.ALOOK_CONVERSATION_ID;- const traceId = process.env.ALOOK_TRACE_ID;- const sourceTaskId = process.env.ALOOK_TASK_ID;+ const ctx = gatherContextEnvVars();const res = await client.postJSON<SendResponse>("/api/email/send", {agentId,to: opts.to,@@ -584,9 +425,9 @@ export function emailCommand(): Command {htmlBody,attachments,...(opts.from ? { from: opts.from } : {}),- ...(conversationId ? { conversationId } : {}),- ...(traceId ? { traceId } : {}),- ...(sourceTaskId ? { sourceTaskId } : {}),+ ...(ctx.conversationId ? { conversationId: ctx.conversationId } : {}),+ ...(ctx.traceId ? { traceId: ctx.traceId } : {}),+ ...(ctx.sourceTaskId ? { sourceTaskId: ctx.sourceTaskId } : {}),});console.log(`Forwarded email to ${res.to_email} (id: ${res.id})`);} catch (err) {diff --git a/src/cli/commands/issue.ts b/src/cli/commands/issue.tsindex 241259b4e..cbcae55f5 100644--- a/src/cli/commands/issue.ts+++ b/src/cli/commands/issue.ts@@ -1,10 +1,8 @@import { Command } from "commander";-import { readFileSync } from "fs";import { APIClient } from "../lib/client.js";-import { loadCLIConfigForProfile } from "../lib/config.js";import { printJSON } from "../lib/output.js";-import { cmdPrefix } from "../lib/env.js";-import { resolveAgentId } from "../lib/flags.js";+import { resolveAgentId, readBody } from "../lib/flags.js";+import { resolveClientOpts } from "../lib/resolve-client.js";const VALID_STATUSES = ["todo", "in_progress", "review", "done", "closed", "canceled", "failed"];@@ -38,33 +36,6 @@ interface CommentResponse {created_at: string;}-function resolveClientOpts(command: Command, agentId: string) {- let root = command;- while (root.parent) root = root.parent;- const parentOpts = root.opts() || {};- const profile: string | undefined = parentOpts.profile;- const cfg = loadCLIConfigForProfile(profile);- const serverUrl = parentOpts.server || cfg.server_url;- const workspaces = cfg.watched_workspaces || [];-- const ws = workspaces.find((w) => w.agent_ids?.includes(agentId));- if (!ws || !ws.token) {- console.error(- `Error: no registered workspace contains agent ${agentId}. Run '${cmdPrefix()} register --token <token>' first.`- );- process.exit(1);- }- return { serverUrl, token: ws.token, workspaceId: ws.id };-}--function readBody(opts: { body?: string; bodyFile?: string }): string {- if (opts.body && opts.bodyFile) {- console.error("Error: --body and --body-file are mutually exclusive");- process.exit(1);- }- if (opts.bodyFile) return readFileSync(opts.bodyFile, "utf-8");- return opts.body ?? "";-}function printIssue(issue: IssueResponse): void {console.log(`${issue.id} ${issue.status.padEnd(11)} ${issue.title}`);@@ -107,7 +78,7 @@ export function issueCommand(): Command {.option("--json", "Output as JSON").action(async (opts, command) => {const agentId = resolveAgentId(opts);- const { serverUrl, token, workspaceId } = resolveClientOpts(command, agentId);+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });const client = new APIClient(serverUrl, token, workspaceId);const description = readBody({ body: opts.description, bodyFile: opts.bodyFile });try {@@ -138,7 +109,7 @@ export function issueCommand(): Command {process.exit(1);}const agentId = resolveAgentId(opts);- const { serverUrl, token, workspaceId } = resolveClientOpts(command, agentId);+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });const client = new APIClient(serverUrl, token, workspaceId);const params = new URLSearchParams({ agentId });if (opts.status) params.set("status", opts.status);@@ -165,7 +136,7 @@ export function issueCommand(): Command {.option("--json", "Output as JSON").action(async (opts, command) => {const agentId = resolveAgentId(opts);- const { serverUrl, token, workspaceId } = resolveClientOpts(command, agentId);+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });const client = new APIClient(serverUrl, token, workspaceId);try {const res = await client.getJSON<{ issue: IssueResponse; messages: MessageResponse[]; comments: CommentResponse[] }>(`/api/issues/${opts.issue_id}?agentId=${encodeURIComponent(agentId)}`);@@ -206,7 +177,7 @@ export function issueCommand(): Command {process.exit(1);}const agentId = resolveAgentId(opts);- const { serverUrl, token, workspaceId } = resolveClientOpts(command, agentId);+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });const client = new APIClient(serverUrl, token, workspaceId);try {const issue = await client.patchJSON<IssueResponse>(`/api/issues/${opts.issue_id}?agentId=${encodeURIComponent(agentId)}`, body);@@ -233,7 +204,7 @@ export function issueCommand(): Command {process.exit(1);}const agentId = resolveAgentId(opts);- const { serverUrl, token, workspaceId } = resolveClientOpts(command, agentId);+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });const client = new APIClient(serverUrl, token, workspaceId);try {const res = await client.postJSON<{ comment: CommentResponse }>(`/api/issues/${opts.issue_id}/comments?agentId=${encodeURIComponent(agentId)}`, { content });diff --git a/src/cli/commands/sync.ts b/src/cli/commands/sync.tsindex ac6540ae0..8f6db100a 100644--- a/src/cli/commands/sync.ts+++ b/src/cli/commands/sync.ts@@ -2,54 +2,10 @@ import { Command } from "commander";import { readFileSync } from "fs";import { basename } from "path";import { APIClient } from "../lib/client.js";-import { loadCLIConfigForProfile } from "../lib/config.js";import { printJSON } from "../lib/output.js";-import { cmdPrefix } from "../lib/env.js";import { resolveAgentId } from "../lib/flags.js";--const MIME_BY_EXT: Record<string, string> = {- ".pdf": "application/pdf",- ".png": "image/png",- ".jpg": "image/jpeg",- ".jpeg": "image/jpeg",- ".gif": "image/gif",- ".txt": "text/plain",- ".html": "text/html",- ".json": "application/json",- ".csv": "text/csv",- ".md": "text/markdown",- ".ts": "text/typescript",- ".js": "text/javascript",- ".yaml": "text/yaml",- ".yml": "text/yaml",- ".svg": "image/svg+xml",- ".xml": "application/xml",- ".zip": "application/zip",-};--function guessContentType(filename: string): string {- const idx = filename.lastIndexOf(".");- if (idx < 0) return "application/octet-stream";- const ext = filename.slice(idx).toLowerCase();- return MIME_BY_EXT[ext] ?? "application/octet-stream";-}--function resolveClientOpts(command: Command, agentId: string) {- const parentOpts = command.parent?.parent?.opts() || {};- const profile: string | undefined = parentOpts.profile;- const cfg = loadCLIConfigForProfile(profile);- const serverUrl = parentOpts.server || cfg.server_url;- const workspaces = cfg.watched_workspaces || [];-- const ws = workspaces.find((w) => w.agent_ids?.includes(agentId));- if (!ws || !ws.token) {- console.error(- `Error: no registered workspace contains agent ${agentId}. Run '${cmdPrefix()} register --token <token>' first.`- );- process.exit(1);- }- return { serverUrl, token: ws.token, workspaceId: ws.id };-}+import { resolveClientOpts } from "../lib/resolve-client.js";+import { guessContentType } from "../lib/file-utils.js";export function syncCommand(): Command {const cmd = new Command("sync").description("File sync utilities");@@ -62,7 +18,7 @@ export function syncCommand(): Command {.requiredOption("--file <path>", "Path to file to upload").action(async (opts, command) => {const agentId = resolveAgentId(opts);- const { serverUrl, token, workspaceId } = resolveClientOpts(command, agentId);+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });const client = new APIClient(serverUrl, token, workspaceId);let bytes: Buffer;diff --git a/src/cli/daemon/execenv/index.ts b/src/cli/daemon/execenv/index.tsindex 6f466a441..1789cd629 100644--- a/src/cli/daemon/execenv/index.ts+++ b/src/cli/daemon/execenv/index.ts@@ -5,6 +5,7 @@ import type { Task } from "../types.js";export interface ExecEnvConfig {workspacesRoot: string;+ token?: string;}export interface ExecEnvResult {@@ -34,6 +35,7 @@ export function prepare(ALOOK_TRACE_ID: task.traceId ?? "",ALOOK_CHANNEL: task.channel ?? "default",ALOOK_HEALTH_PORT: process.env.ALOOK_HEALTH_PORT || "19514",+ ...(config.token ? { ALOOK_TOKEN: config.token } : {}),};return { workDir, timelineDir, env };diff --git a/src/cli/daemon/session-runner.test.ts b/src/cli/daemon/session-runner.test.tsindex 17d35f721..5ec2c6a35 100644--- a/src/cli/daemon/session-runner.test.ts+++ b/src/cli/daemon/session-runner.test.ts@@ -170,7 +170,7 @@ describe("session-runner runSession", () => {await runSession(makeInput());expect(mockPrepare).toHaveBeenCalledWith(- { workspacesRoot: "/tmp/ws" },+ { workspacesRoot: "/tmp/ws", token: "test_token" },expect.objectContaining({ id: "t1" }),);expect(createBackend).toHaveBeenCalledWith("claude", "claude");diff --git a/src/cli/daemon/session-runner.ts b/src/cli/daemon/session-runner.tsindex 23cbb90ae..6b0cc7ab4 100644--- a/src/cli/daemon/session-runner.ts+++ b/src/cli/daemon/session-runner.ts@@ -174,7 +174,7 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {);const { workDir, env } = prepare(- { workspacesRoot },+ { workspacesRoot, token },task,);diff --git a/src/cli/lib/command-utils.test.ts b/src/cli/lib/command-utils.test.tsnew file mode 100644index 000000000..4cb56cbf2--- /dev/null+++ b/src/cli/lib/command-utils.test.ts@@ -0,0 +1,24 @@+import { describe, it, expect } from "vitest";+import { getRootOpts } from "./command-utils.js";++describe("getRootOpts", () => {+ it("returns opts from root command (no parent)", () => {+ const cmd = { parent: null, opts: () => ({ server: "https://x.com", profile: "dev" }) } as any;+ expect(getRootOpts(cmd)).toEqual({ server: "https://x.com", profile: "dev" });+ });++ it("traverses up to root from deeply nested command", () => {+ const root = { parent: null, opts: () => ({ server: "https://root.com" }) } as any;+ const mid = { parent: root, opts: () => ({ mid: true }) } as any;+ const leaf = { parent: mid, opts: () => ({ leaf: true }) } as any;++ expect(getRootOpts(leaf)).toEqual({ server: "https://root.com" });+ });++ it("returns empty object if root has no opts", () => {+ const root = { parent: null, opts: () => ({}) } as any;+ const child = { parent: root, opts: () => ({ something: true }) } as any;++ expect(getRootOpts(child)).toEqual({});+ });+});diff --git a/src/cli/lib/command-utils.ts b/src/cli/lib/command-utils.tsnew file mode 100644index 000000000..689032bcc--- /dev/null+++ b/src/cli/lib/command-utils.ts@@ -0,0 +1,7 @@+import { Command } from "commander";++export function getRootOpts(command: Command): Record<string, unknown> {+ let root = command;+ while (root.parent) root = root.parent;+ return root.opts() || {};+}diff --git a/src/cli/lib/context-env.test.ts b/src/cli/lib/context-env.test.tsnew file mode 100644index 000000000..53fe9622f--- /dev/null+++ b/src/cli/lib/context-env.test.ts@@ -0,0 +1,50 @@+import { describe, it, expect, beforeEach, afterEach } from "vitest";+import { gatherContextEnvVars } from "./context-env.js";++describe("gatherContextEnvVars", () => {+ const envKeys = ["ALOOK_CONVERSATION_ID", "ALOOK_TRACE_ID", "ALOOK_TASK_ID"];+ const saved: Record<string, string | undefined> = {};++ beforeEach(() => {+ for (const k of envKeys) {+ saved[k] = process.env[k];+ delete process.env[k];+ }+ });++ afterEach(() => {+ for (const k of envKeys) {+ if (saved[k] !== undefined) process.env[k] = saved[k];+ else delete process.env[k];+ }+ });++ it("returns all env vars when set", () => {+ process.env.ALOOK_CONVERSATION_ID = "conv_123";+ process.env.ALOOK_TRACE_ID = "trace_456";+ process.env.ALOOK_TASK_ID = "task_789";++ const result = gatherContextEnvVars();+ expect(result).toEqual({+ conversationId: "conv_123",+ traceId: "trace_456",+ sourceTaskId: "task_789",+ });+ });++ it("returns undefined for unset vars", () => {+ const result = gatherContextEnvVars();+ expect(result.conversationId).toBeUndefined();+ expect(result.traceId).toBeUndefined();+ expect(result.sourceTaskId).toBeUndefined();+ });++ it("handles partial env vars", () => {+ process.env.ALOOK_CONVERSATION_ID = "conv_123";++ const result = gatherContextEnvVars();+ expect(result.conversationId).toBe("conv_123");+ expect(result.traceId).toBeUndefined();+ expect(result.sourceTaskId).toBeUndefined();+ });+});diff --git a/src/cli/lib/context-env.ts b/src/cli/lib/context-env.tsnew file mode 100644index 000000000..2e93ad330--- /dev/null+++ b/src/cli/lib/context-env.ts@@ -0,0 +1,12 @@+export interface ContextEnvVars {+ conversationId?: string;+ traceId?: string;+ sourceTaskId?: string;+}++export function gatherContextEnvVars(): ContextEnvVars {+ const conversationId = process.env.ALOOK_CONVERSATION_ID || undefined;+ const traceId = process.env.ALOOK_TRACE_ID || undefined;+ const sourceTaskId = process.env.ALOOK_TASK_ID || undefined;+ return { conversationId, traceId, sourceTaskId };+}diff --git a/src/cli/lib/file-utils.test.ts b/src/cli/lib/file-utils.test.tsnew file mode 100644index 000000000..5759e99f3--- /dev/null+++ b/src/cli/lib/file-utils.test.ts@@ -0,0 +1,63 @@+import { describe, it, expect } from "vitest";+import { guessContentType, contentToBuffer } from "./file-utils.js";++describe("guessContentType", () => {+ it("returns correct MIME for known extensions", () => {+ expect(guessContentType("report.pdf")).toBe("application/pdf");+ expect(guessContentType("image.png")).toBe("image/png");+ expect(guessContentType("photo.jpg")).toBe("image/jpeg");+ expect(guessContentType("photo.jpeg")).toBe("image/jpeg");+ expect(guessContentType("anim.gif")).toBe("image/gif");+ expect(guessContentType("hero.webp")).toBe("image/webp");+ expect(guessContentType("icon.svg")).toBe("image/svg+xml");+ expect(guessContentType("readme.md")).toBe("text/markdown");+ expect(guessContentType("data.json")).toBe("application/json");+ expect(guessContentType("styles.css")).toBe("application/octet-stream");+ expect(guessContentType("index.html")).toBe("text/html");+ expect(guessContentType("page.htm")).toBe("text/html");+ expect(guessContentType("app.ts")).toBe("text/typescript");+ expect(guessContentType("app.js")).toBe("text/javascript");+ expect(guessContentType("config.yaml")).toBe("text/yaml");+ expect(guessContentType("config.yml")).toBe("text/yaml");+ expect(guessContentType("data.xml")).toBe("application/xml");+ expect(guessContentType("archive.zip")).toBe("application/zip");+ expect(guessContentType("data.csv")).toBe("text/csv");+ expect(guessContentType("notes.txt")).toBe("text/plain");+ });++ it("is case-insensitive for extensions", () => {+ expect(guessContentType("image.PNG")).toBe("image/png");+ expect(guessContentType("file.PDF")).toBe("application/pdf");+ });++ it("returns octet-stream for unknown extensions", () => {+ expect(guessContentType("file.xyz")).toBe("application/octet-stream");+ expect(guessContentType("file.wasm")).toBe("application/octet-stream");+ });++ it("returns octet-stream for files without extension", () => {+ expect(guessContentType("Makefile")).toBe("application/octet-stream");+ expect(guessContentType("noext")).toBe("application/octet-stream");+ });+});++describe("contentToBuffer", () => {+ it("handles base64 string input", () => {+ const base64 = Buffer.from("hello world").toString("base64");+ const result = contentToBuffer(base64);+ expect(result.toString()).toBe("hello world");+ });++ it("handles ArrayBuffer input", () => {+ const data = new TextEncoder().encode("test data");+ const arrayBuffer = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);+ const result = contentToBuffer(arrayBuffer);+ expect(result.toString()).toBe("test data");+ });++ it("handles Uint8Array input", () => {+ const data = new Uint8Array([72, 101, 108, 108, 111]);+ const result = contentToBuffer(data);+ expect(result.toString()).toBe("Hello");+ });+});diff --git a/src/cli/lib/file-utils.ts b/src/cli/lib/file-utils.tsnew file mode 100644index 000000000..56f32d138--- /dev/null+++ b/src/cli/lib/file-utils.ts@@ -0,0 +1,78 @@+import { readFileSync, statSync } from "fs";+import { basename } from "path";+import { APIClient } from "./client.js";++const MIME_BY_EXT: Record<string, string> = {+ ".pdf": "application/pdf",+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp",+ ".svg": "image/svg+xml",+ ".txt": "text/plain",+ ".html": "text/html",+ ".htm": "text/html",+ ".json": "application/json",+ ".csv": "text/csv",+ ".md": "text/markdown",+ ".ts": "text/typescript",+ ".js": "text/javascript",+ ".yaml": "text/yaml",+ ".yml": "text/yaml",+ ".xml": "application/xml",+ ".zip": "application/zip",+};++export function guessContentType(filename: string): string {+ const idx = filename.lastIndexOf(".");+ if (idx < 0) return "application/octet-stream";+ const ext = filename.slice(idx).toLowerCase();+ return MIME_BY_EXT[ext] ?? "application/octet-stream";+}++export function contentToBuffer(content: string | ArrayBuffer | Uint8Array): Buffer {+ if (typeof content === "string") {+ return Buffer.from(content, "base64");+ } else if (content instanceof ArrayBuffer) {+ return Buffer.from(new Uint8Array(content));+ }+ return Buffer.from(content as Uint8Array);+}++export interface UploadedFile {+ key: string;+ filename: string;+ size: number;+ contentType: string;+}++export async function uploadFile(+ client: APIClient,+ filePath: string,+ endpoint: string,+): Promise<UploadedFile> {+ let bytes: Buffer;+ let size: number;+ try {+ bytes = readFileSync(filePath);+ size = statSync(filePath).size;+ } catch (err) {+ throw new Error(`cannot read file "${filePath}": ${err instanceof Error ? err.message : err}`);+ }+ const filename = basename(filePath);+ const contentType = guessContentType(filename);+ const form = new FormData();+ form.append(+ "file",+ new Blob([new Uint8Array(bytes)], { type: contentType }),+ filename,+ );+ const uploaded = await client.postMultipart<UploadedFile>(endpoint, form);+ return {+ key: uploaded.key,+ filename: uploaded.filename,+ size: uploaded.size ?? size,+ contentType: uploaded.contentType ?? contentType,+ };+}diff --git a/src/cli/lib/flags.ts b/src/cli/lib/flags.tsindex 221418e9a..bcb2a2ad2 100644--- a/src/cli/lib/flags.ts+++ b/src/cli/lib/flags.ts@@ -1,4 +1,5 @@import { Command } from "commander";+import { readFileSync } from "fs";export function flagOrEnv(cmd: Command,@@ -20,3 +21,16 @@ export function resolveAgentId(opts: { agent_id?: string }): string {}return id;}++export function collectRepeated(value: string, previous: string[]): string[] {+ return previous.concat([value]);+}++export function readBody(opts: { body?: string; bodyFile?: string }): string {+ if (opts.body && opts.bodyFile) {+ console.error("Error: --body and --body-file are mutually exclusive");+ process.exit(1);+ }+ if (opts.bodyFile) return readFileSync(opts.bodyFile, "utf-8");+ return opts.body ?? "";+}diff --git a/src/cli/lib/resolve-client.test.ts b/src/cli/lib/resolve-client.test.tsnew file mode 100644index 000000000..68a73b65a--- /dev/null+++ b/src/cli/lib/resolve-client.test.ts@@ -0,0 +1,200 @@+import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";++vi.mock("./config.js", () => ({+ loadCLIConfigForProfile: vi.fn(),+}));++vi.mock("./env.js", () => ({+ cmdPrefix: () => "npx @alook/cli",+}));++import { resolveClientOpts } from "./resolve-client.js";+import { loadCLIConfigForProfile } from "./config.js";++const mockedLoadConfig = vi.mocked(loadCLIConfigForProfile);++function makeCommand(opts: Record<string, unknown> = {}) {+ return { parent: null, opts: () => opts } as any;+}++function makeNestedCommand(rootOpts: Record<string, unknown> = {}) {+ const root = { parent: null, opts: () => rootOpts } as any;+ const child = { parent: root, opts: () => ({}) } as any;+ return { parent: child, opts: () => ({}) } as any;+}++describe("resolveClientOpts", () => {+ const envKeys = ["ALOOK_SERVER_URL", "ALOOK_WORKSPACE_ID", "ALOOK_TOKEN"];+ const savedEnv: Record<string, string | undefined> = {};++ beforeEach(() => {+ for (const k of envKeys) {+ savedEnv[k] = process.env[k];+ delete process.env[k];+ }+ mockedLoadConfig.mockReturnValue({+ server_url: "",+ watched_workspaces: [],+ });+ });++ afterEach(() => {+ for (const k of envKeys) {+ if (savedEnv[k] !== undefined) process.env[k] = savedEnv[k];+ else delete process.env[k];+ }+ });++ it("resolves from env vars when no config exists", () => {+ process.env.ALOOK_SERVER_URL = "https://self-hosted.example.com";+ process.env.ALOOK_WORKSPACE_ID = "ws_env";+ process.env.ALOOK_TOKEN = "tok_env";++ const result = resolveClientOpts(makeCommand(), { agentId: "ag1" });++ expect(result.serverUrl).toBe("https://self-hosted.example.com");+ expect(result.workspaceId).toBe("ws_env");+ expect(result.token).toBe("tok_env");+ });++ it("env token takes priority over config token", () => {+ process.env.ALOOK_TOKEN = "tok_env";+ mockedLoadConfig.mockReturnValue({+ server_url: "https://config.example.com",+ watched_workspaces: [+ { id: "ws1", name: "WS1", token: "tok_config", agent_ids: ["ag1"] },+ ],+ });++ const result = resolveClientOpts(makeCommand(), { agentId: "ag1" });++ expect(result.token).toBe("tok_env");+ expect(result.workspaceId).toBe("ws1");+ });++ it("flag > env > config for server URL", () => {+ process.env.ALOOK_SERVER_URL = "https://env.example.com";+ mockedLoadConfig.mockReturnValue({+ server_url: "https://config.example.com",+ watched_workspaces: [+ { id: "ws1", name: "WS1", token: "tok1", agent_ids: ["ag1"] },+ ],+ });++ const result = resolveClientOpts(+ makeCommand({ server: "https://flag.example.com" }),+ { agentId: "ag1" },+ );++ expect(result.serverUrl).toBe("https://flag.example.com");+ });++ it("resolves workspace by agent_id from config", () => {+ mockedLoadConfig.mockReturnValue({+ server_url: "https://alook.ai",+ watched_workspaces: [+ { id: "ws1", name: "WS1", token: "tok1", agent_ids: ["ag1"] },+ { id: "ws2", name: "WS2", token: "tok2", agent_ids: ["ag2"] },+ ],+ });++ const result = resolveClientOpts(makeCommand(), { agentId: "ag2" });++ expect(result.workspaceId).toBe("ws2");+ expect(result.token).toBe("tok2");+ });++ it("falls back to single workspace when agent not found", () => {+ mockedLoadConfig.mockReturnValue({+ server_url: "https://alook.ai",+ watched_workspaces: [+ { id: "ws1", name: "WS1", token: "tok1", agent_ids: ["other"] },+ ],+ });++ const result = resolveClientOpts(makeCommand(), { agentId: "ag_unknown" });++ expect(result.workspaceId).toBe("ws1");+ expect(result.token).toBe("tok1");+ });++ it("resolves via env when agent_id not in config and no single fallback", () => {+ process.env.ALOOK_WORKSPACE_ID = "ws_env";+ process.env.ALOOK_TOKEN = "tok_env";+ mockedLoadConfig.mockReturnValue({+ server_url: "https://alook.ai",+ watched_workspaces: [+ { id: "ws1", name: "WS1", token: "tok1", agent_ids: ["other1"] },+ { id: "ws2", name: "WS2", token: "tok2", agent_ids: ["other2"] },+ ],+ });++ const result = resolveClientOpts(makeCommand(), { agentId: "ag_self_hosted" });++ expect(result.workspaceId).toBe("ws_env");+ expect(result.token).toBe("tok_env");+ });++ it("exits with error when nothing available", () => {+ const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {+ throw new Error("__exit__");+ }) as never);+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});++ expect(() => resolveClientOpts(makeCommand(), { agentId: "ag1" })).toThrow("__exit__");+ expect(exitSpy).toHaveBeenCalledWith(1);++ exitSpy.mockRestore();+ errSpy.mockRestore();+ });++ it("traverses to root command for parent opts", () => {+ process.env.ALOOK_TOKEN = "tok_env";+ process.env.ALOOK_WORKSPACE_ID = "ws_env";++ const cmd = makeNestedCommand({ server: "https://from-root.example.com" });+ const result = resolveClientOpts(cmd, { agentId: "ag1" });++ expect(result.serverUrl).toBe("https://from-root.example.com");+ });++ it("workspace flag selects specific workspace from config", () => {+ mockedLoadConfig.mockReturnValue({+ server_url: "https://alook.ai",+ watched_workspaces: [+ { id: "ws1", name: "WS1", token: "tok1", agent_ids: ["ag1"] },+ { id: "ws2", name: "WS2", token: "tok2", agent_ids: ["ag2"] },+ ],+ });++ const result = resolveClientOpts(makeCommand(), { workspace: "ws2", agentId: "ag1" });++ expect(result.workspaceId).toBe("ws2");+ expect(result.token).toBe("tok2");+ });++ it("errors with workspace guidance when token is set but workspace cannot be determined", () => {+ process.env.ALOOK_TOKEN = "tok_env";+ // No ALOOK_WORKSPACE_ID, no config match, multiple workspaces+ mockedLoadConfig.mockReturnValue({+ server_url: "https://alook.ai",+ watched_workspaces: [+ { id: "ws1", name: "WS1", token: "tok1", agent_ids: ["other1"] },+ { id: "ws2", name: "WS2", token: "tok2", agent_ids: ["other2"] },+ ],+ });++ const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {+ throw new Error("__exit__");+ }) as never);+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});++ expect(() => resolveClientOpts(makeCommand(), { agentId: "ag_missing" })).toThrow("__exit__");+ expect(errSpy).toHaveBeenCalledWith(+ "Error: cannot determine workspace. Set ALOOK_WORKSPACE_ID env var or use --workspace flag.",+ );++ exitSpy.mockRestore();+ errSpy.mockRestore();+ });+});diff --git a/src/cli/lib/resolve-client.ts b/src/cli/lib/resolve-client.tsnew file mode 100644index 000000000..8ec79c5de--- /dev/null+++ b/src/cli/lib/resolve-client.ts@@ -0,0 +1,80 @@+import { Command } from "commander";+import { loadCLIConfigForProfile } from "./config.js";+import { cmdPrefix } from "./env.js";+import { getRootOpts } from "./command-utils.js";++export interface ResolvedClient {+ serverUrl: string;+ token: string;+ workspaceId: string;+}++export interface ResolveClientOptions {+ workspace?: string;+ agentId?: string;+}++export function resolveClientOpts(command: Command, opts: ResolveClientOptions = {}): ResolvedClient {+ const parentOpts = getRootOpts(command) as { server?: string; profile?: string };+ const cfg = loadCLIConfigForProfile(parentOpts.profile);++ // Server URL: flag > env > config+ const serverUrl = parentOpts.server || process.env.ALOOK_SERVER_URL || cfg.server_url;++ if (!serverUrl) {+ console.error("Error: no server URL configured. Set ALOOK_SERVER_URL or run register.");+ process.exit(1);+ }++ const workspaces = cfg.watched_workspaces || [];++ // Workspace resolution: flag > env > config lookup by agent_id > single workspace fallback+ let ws;+ const envWorkspaceId = process.env.ALOOK_WORKSPACE_ID;++ if (opts.workspace) {+ ws = workspaces.find((w) => w.id === opts.workspace);+ if (!ws) {+ if (envWorkspaceId === opts.workspace) {+ // workspace from flag matches env — use env-based resolution+ ws = undefined;+ } else {+ console.error(`Error: workspace ${opts.workspace} not found in config.`);+ process.exit(1);+ }+ }+ } else if (opts.agentId) {+ ws = workspaces.find((w) => w.agent_ids?.includes(opts.agentId!));+ if (!ws) {+ if (workspaces.length === 1) {+ ws = workspaces[0];+ }+ // If still not found, fall through to env var resolution below+ }+ } else if (workspaces.length === 1) {+ ws = workspaces[0];+ }++ // Token resolution: env > config+ const envToken = process.env.ALOOK_TOKEN;+ const token = envToken || ws?.token;++ if (!token) {+ console.error(+ `Error: not registered. Run '${cmdPrefix()} register --token <token>' first.`,+ );+ process.exit(1);+ }++ // Workspace ID resolution: ws from config > env > error+ const workspaceId = ws?.id || envWorkspaceId;++ if (!workspaceId) {+ console.error(+ "Error: cannot determine workspace. Set ALOOK_WORKSPACE_ID env var or use --workspace flag.",+ );+ process.exit(1);+ }++ return { serverUrl, token, workspaceId };+}