Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): task service, response formatters, errors, logger

Gener6032447ad5e0
diff --git a/src/web/src/lib/api/responses.ts b/src/web/src/lib/api/responses.ts
new file mode 100644
index 000000000..4fed98a03
--- /dev/null
+++ b/src/web/src/lib/api/responses.ts
@@ -0,0 +1,147 @@
+import {
+ formatTimestamp,
+ formatTimestampNullable,
+} from "@/lib/middleware/helpers";
+import { TaskApiBaseSchema } from "@alook/shared";
+
+/* eslint-disable @typescript-eslint/no-explicit-any */
+
+export function userToResponse(u: any) {
+ return {
+ id: u.id,
+ name: u.name,
+ email: u.email,
+ avatar_url: u.avatarUrl || null,
+ created_at: formatTimestamp(u.createdAt),
+ updated_at: formatTimestamp(u.updatedAt),
+ };
+}
+
+export function workspaceToResponse(w: any) {
+ return {
+ id: w.id,
+ name: w.name,
+ slug: w.slug,
+ created_at: formatTimestamp(w.createdAt),
+ updated_at: formatTimestamp(w.updatedAt),
+ };
+}
+
+export function agentToResponse(a: any) {
+ let rc = a.runtimeConfig;
+ if (!rc) rc = {};
+ return {
+ id: a.id,
+ workspace_id: a.workspaceId,
+ runtime_id: a.runtimeId || "",
+ name: a.name,
+ description: a.description,
+ instructions: a.instructions,
+ runtime_mode: a.runtimeMode,
+ runtime_config: rc,
+ status: a.status,
+ max_concurrent_tasks: a.maxConcurrentTasks,
+ created_at: formatTimestamp(a.createdAt),
+ updated_at: formatTimestamp(a.updatedAt),
+ };
+}
+
+export function taskToResponse(t: {
+ id: string;
+ agentId: string;
+ runtimeId: string;
+ conversationId: string;
+ workspaceId: string;
+ prompt: string;
+ status: string;
+ priority: number;
+ dispatchedAt: Date | string | null;
+ startedAt: Date | string | null;
+ completedAt: Date | string | null;
+ result?: unknown;
+ error?: string | null;
+ createdAt: Date | string;
+}) {
+ return TaskApiBaseSchema.parse({
+ id: t.id,
+ agent_id: t.agentId,
+ runtime_id: t.runtimeId,
+ conversation_id: t.conversationId,
+ workspace_id: t.workspaceId,
+ prompt: t.prompt,
+ status: t.status,
+ priority: t.priority,
+ dispatched_at: formatTimestampNullable(t.dispatchedAt),
+ started_at: formatTimestampNullable(t.startedAt),
+ completed_at: formatTimestampNullable(t.completedAt),
+ result: t.result ?? null,
+ error: t.error || null,
+ created_at: formatTimestamp(t.createdAt),
+ });
+}
+
+export function conversationToResponse(c: any) {
+ const resp: any = {
+ id: c.id,
+ agent_id: c.agentId,
+ title: c.title,
+ created_at: formatTimestamp(c.createdAt),
+ };
+ if (c.messageCount !== undefined) {
+ resp.message_count = c.messageCount;
+ }
+ return resp;
+}
+
+export function messageToResponse(m: any) {
+ return {
+ id: m.id,
+ conversation_id: m.conversationId,
+ role: m.role,
+ content: m.content,
+ task_id: m.taskId || null,
+ created_at: formatTimestamp(m.createdAt),
+ };
+}
+
+export function taskMessageToResponse(m: any) {
+ const resp: any = {
+ id: m.id,
+ task_id: m.taskId,
+ seq: m.seq,
+ type: m.type,
+ tool: m.tool,
+ content: m.content,
+ output: m.output,
+ };
+ if (m.input) resp.input = m.input;
+ return resp;
+}
+
+export function runtimeToResponse(rt: any) {
+ let metadata = rt.metadata;
+ if (!metadata) metadata = {};
+ return {
+ id: rt.id,
+ workspace_id: rt.workspaceId,
+ daemon_id: rt.daemonId || null,
+ name: rt.name,
+ runtime_mode: rt.runtimeMode,
+ provider: rt.provider,
+ status: rt.status,
+ device_info: rt.deviceInfo,
+ metadata,
+ last_seen_at: formatTimestampNullable(rt.lastSeenAt),
+ created_at: formatTimestamp(rt.createdAt),
+ updated_at: formatTimestamp(rt.updatedAt),
+ };
+}
+
+export function machineTokenToResponse(mt: any) {
+ return {
+ id: mt.id,
+ name: mt.name,
+ last_used_at: formatTimestampNullable(mt.lastUsedAt),
+ created_at: formatTimestamp(mt.createdAt),
+ };
+}
diff --git a/src/web/src/lib/errors.ts b/src/web/src/lib/errors.ts
new file mode 100644
index 000000000..31c78228c
--- /dev/null
+++ b/src/web/src/lib/errors.ts
@@ -0,0 +1,23 @@
+export class ApiError extends Error {
+ status: number;
+ details?: string[];
+
+ constructor(message: string, status: number, details?: string[]) {
+ super(message);
+ this.name = "ApiError";
+ this.status = status;
+ this.details = details;
+ }
+
+ get isNetworkError(): boolean {
+ return this.status === 0;
+ }
+
+ get isRateLimit(): boolean {
+ return this.status === 429;
+ }
+
+ get isUnauthorized(): boolean {
+ return this.status === 401;
+ }
+}
diff --git a/src/web/src/lib/logger.ts b/src/web/src/lib/logger.ts
new file mode 100644
index 000000000..b2e6501d7
--- /dev/null
+++ b/src/web/src/lib/logger.ts
@@ -0,0 +1,62 @@
+export type LogLevel = "debug" | "info" | "warn" | "error" | "silent";
+
+const LEVELS: Record<LogLevel, number> = {
+ debug: 0,
+ info: 1,
+ warn: 2,
+ error: 3,
+ silent: 4,
+};
+
+export class Logger {
+ private level: number;
+
+ constructor(level: LogLevel = "info") {
+ this.level = LEVELS[level];
+ }
+
+ debug(msg: string, ctx?: Record<string, unknown>): void {
+ this.write("debug", msg, ctx);
+ }
+
+ info(msg: string, ctx?: Record<string, unknown>): void {
+ this.write("info", msg, ctx);
+ }
+
+ warn(msg: string, ctx?: Record<string, unknown>): void {
+ this.write("warn", msg, ctx);
+ }
+
+ error(msg: string, ctx?: Record<string, unknown>): void {
+ this.write("error", msg, ctx);
+ }
+
+ private write(
+ level: Exclude<LogLevel, "silent">,
+ msg: string,
+ ctx?: Record<string, unknown>,
+ ): void {
+ if (LEVELS[level] < this.level) return;
+
+ const entry: Record<string, unknown> = {
+ level,
+ msg,
+ ...ctx,
+ ts: new Date().toISOString(),
+ };
+
+ // Serialize Error objects in context
+ for (const [k, v] of Object.entries(entry)) {
+ if (v instanceof Error) {
+ entry[k] = v.message;
+ }
+ }
+
+ const line = JSON.stringify(entry);
+ const dest = level === "error" ? process.stderr : process.stdout;
+ dest.write(line + "\n");
+ }
+}
+
+const envLevel = (process.env.ALOOK_LOG_LEVEL as LogLevel) || "info";
+export const log = new Logger(envLevel);
diff --git a/src/web/src/lib/services/task.ts b/src/web/src/lib/services/task.ts
new file mode 100644
index 000000000..c9c04b0c4
--- /dev/null
+++ b/src/web/src/lib/services/task.ts
@@ -0,0 +1,157 @@
+import type { Database } from "@alook/shared";
+import { queries } from "@alook/shared";
+import { log } from "@/lib/logger";
+
+const taskQueries = queries.task;
+const agentQueries = queries.agent;
+const messageQueries = queries.message;
+
+export class TaskService {
+ constructor(private db: Database) {}
+
+ async enqueueTask(
+ agentId: string,
+ conversationId: string,
+ workspaceId: string,
+ prompt: string
+ ) {
+ const agent = await agentQueries.getAgent(this.db, agentId);
+ if (!agent) {
+ throw new Error("agent not found");
+ }
+ if (!agent.runtimeId) {
+ throw new Error("agent has no runtime");
+ }
+
+ return taskQueries.createTask(this.db, {
+ agentId,
+ runtimeId: agent.runtimeId,
+ workspaceId,
+ conversationId,
+ prompt,
+ priority: 0,
+ });
+ }
+
+ async claimTask(agentId: string) {
+ const agent = await agentQueries.getAgent(this.db, agentId);
+ if (!agent) {
+ return null;
+ }
+
+ const running = await taskQueries.countRunningTasks(this.db, agentId);
+ if (running >= agent.maxConcurrentTasks) {
+ return null;
+ }
+
+ const task = await taskQueries.claimTask(this.db, agentId);
+ if (!task) {
+ return null;
+ }
+
+ await agentQueries.updateAgentStatus(this.db, agentId, "working");
+ return task;
+ }
+
+ async claimTaskForRuntime(runtimeId: string) {
+ const tasks = await taskQueries.listPendingTasksByRuntime(
+ this.db,
+ runtimeId
+ );
+ const triedAgents = new Set<string>();
+
+ for (const candidate of tasks) {
+ if (triedAgents.has(candidate.agentId)) {
+ continue;
+ }
+ triedAgents.add(candidate.agentId);
+
+ const task = await this.claimTask(candidate.agentId);
+ if (task && task.runtimeId === runtimeId) {
+ return task;
+ }
+ }
+
+ return null;
+ }
+
+ async startTask(taskId: string) {
+ const task = await taskQueries.startTask(this.db, taskId);
+ if (!task) {
+ throw new Error("task not in dispatched status");
+ }
+ return task;
+ }
+
+ async completeTask(
+ taskId: string,
+ result: string,
+ sessionId: string,
+ workDir: string
+ ) {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(result);
+ } catch {
+ parsed = { raw: result };
+ }
+
+ const task = await taskQueries.completeTask(this.db, taskId, {
+ result: parsed,
+ sessionId: sessionId || null,
+ workDir: workDir || null,
+ });
+
+ if (!task) {
+ const existing = await taskQueries.getTask(this.db, taskId);
+ const status = existing?.status ?? "unknown";
+ log.warn(`completeTask failed: task is in '${status}' status`, { taskId });
+ throw new Error(`cannot complete task in '${status}' status`);
+ }
+
+ const payload = parsed as Record<string, unknown>;
+ const output =
+ typeof payload?.output === "string" ? payload.output : "";
+
+ if (output) {
+ await messageQueries.createMessage(this.db, {
+ conversationId: task.conversationId,
+ role: "assistant",
+ content: output,
+ taskId,
+ });
+ }
+
+ await this.reconcileAgentStatus(task.agentId);
+ return task;
+ }
+
+ async failTask(taskId: string, error: string) {
+ const task = await taskQueries.failTask(this.db, taskId, error);
+
+ if (!task) {
+ const existing = await taskQueries.getTask(this.db, taskId);
+ const status = existing?.status ?? "unknown";
+ log.warn(`failTask failed: task is in '${status}' status`, { taskId });
+ throw new Error(`cannot fail task in '${status}' status`);
+ }
+
+ if (error) {
+ await messageQueries.createMessage(this.db, {
+ conversationId: task.conversationId,
+ role: "assistant",
+ content: `Error: ${error}`,
+ taskId,
+ });
+ }
+
+ await this.reconcileAgentStatus(task.agentId);
+ return task;
+ }
+
+ async reconcileAgentStatus(agentId: string) {
+ const running = await taskQueries.countRunningTasks(this.db, agentId);
+ const status = running > 0 ? "working" : "idle";
+ await agentQueries.updateAgentStatus(this.db, agentId, status);
+ }
+}