Skip to content

armgit / pibot

Public Imported from GitHub
0

Open-source, local-first AI agent team for your desktop: multi-agent group chats, computer use, browser, MCP, routines and approvals. macOS, Windows, Linux + Android. Built on pi.

6.7 KB
Raw Blame
import { randomUUID } from "node:crypto";
import type { DatabaseSync } from "node:sqlite";
import {
  type ComputerStep,
  ComputerStepActionSchema,
  ComputerStepPageSchema,
  ComputerStepSchema,
  IdSchema,
  type Page,
} from "@pibot/protocol-base";
import { transaction } from "../database/database.ts";
import { readPage } from "../database/paging.ts";

/**
 * Screenshot files live under the Bot directory; the path is relative and generated by brain,
 * so a forged value can neither escape the directory nor point at another Bot's files.
 */
const SCREENSHOT_PATH = /^computer\/screenshots\/[0-9a-f-]{36}\.(?:jpg|png|webp)$/;
const columns = `id,bot_id AS botId,run_id AS runId,tool_call_id AS toolCallId,app,app_name AS appName,
  method,stage,target,result,screenshot_path AS screenshotPath,created_at AS createdAt,
  action,page_url AS pageUrl,page_title AS pageTitle,handoff`;
function json(value: unknown): unknown {
  try {
    return typeof value === "string" ? JSON.parse(value) : undefined;
  } catch {
    // A damaged optional detail only loses the localized wording; the row keeps its `target`.
    return undefined;
  }
}
function parseStep(row: Record<string, unknown>): ComputerStep {
  const { app, appName, screenshotPath, action, pageUrl, pageTitle, handoff, ...fields } = row;
  // Optional details: a row this build cannot read still shows with its plain `target`.
  const parsedAction = ComputerStepActionSchema.safeParse(json(action)).data;
  const page = ComputerStepPageSchema.safeParse({ url: pageUrl, title: pageTitle }).data;
  return ComputerStepSchema.parse({
    ...fields,
    app: { id: app, name: appName },
    hasScreenshot: screenshotPath != null,
    ...(parsedAction ? { action: parsedAction } : {}),
    ...(page ? { page } : {}),
    ...(handoff == null ? {} : { handoff }),
  });
}

export type CreateComputerStep = Omit<ComputerStep, "id" | "createdAt" | "hasScreenshot"> & {
  screenshotPath: string | null;
};

export class ComputerStepsRepo {
  constructor(private readonly db: DatabaseSync) {}

  create(input: CreateComputerStep): ComputerStep {
    const { screenshotPath, ...fields } = input;
    if (screenshotPath !== null && !SCREENSHOT_PATH.test(screenshotPath))
      throw new TypeError("Invalid screenshot path");
    const step = ComputerStepSchema.parse({
      ...fields,
      id: randomUUID(),
      hasScreenshot: screenshotPath !== null,
      createdAt: new Date().toISOString(),
    });
    this.db
      .prepare(`INSERT INTO computer_steps(id,bot_id,run_id,tool_call_id,app,app_name,method,stage,
        target,result,screenshot_path,created_at,action,page_url,page_title,handoff)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`)
      .run(
        step.id,
        step.botId,
        step.runId,
        step.toolCallId,
        step.app.id,
        step.app.name,
        step.method,
        step.stage,
        step.target,
        step.result,
        screenshotPath,
        step.createdAt,
        step.action ? JSON.stringify(step.action) : null,
        step.page?.url ?? null,
        step.page?.title ?? null,
        step.handoff ?? null,
      );
    return step;
  }

  /**
   * The step that waited on a "come help for a moment" card gets the outcome of the call
   * (the retry after "continue", or the original failure) instead of a second row.
   */
  finishHandoff(
    id: string,
    change: Pick<ComputerStep, "handoff" | "result" | "stage" | "target" | "action"> & {
      screenshotPath: string | null;
    },
  ): ComputerStep | undefined {
    const current = this.get(id);
    if (!current) return undefined;
    const { screenshotPath, action, ...fields } = change;
    if (screenshotPath !== null && !SCREENSHOT_PATH.test(screenshotPath))
      throw new TypeError("Invalid screenshot path");
    const next = ComputerStepSchema.parse({
      ...current,
      ...fields,
      ...(action ? { action } : {}),
      ...(screenshotPath !== null ? { hasScreenshot: true } : {}),
    });
    this.db
      .prepare(
        "UPDATE computer_steps SET handoff=?,result=?,stage=?,target=?,action=COALESCE(?,action),screenshot_path=COALESCE(?,screenshot_path) WHERE id=?",
      )
      .run(
        next.handoff ?? null,
        next.result,
        next.stage,
        next.target,
        action ? JSON.stringify(action) : null,
        screenshotPath,
        next.id,
      );
    return next;
  }

  get(id: string): ComputerStep | undefined {
    const row = this.db
      .prepare(`SELECT ${columns} FROM computer_steps WHERE id=?`)
      .get(IdSchema.parse(id));
    return row ? parseStep(row) : undefined;
  }

  /** Brain-only: where the screenshot lives, for thumbnails and the retention sweep. */
  screenshotPath(id: string): { botId: string; path: string } | undefined {
    const row = this.db
      .prepare(
        "SELECT bot_id,screenshot_path FROM computer_steps WHERE id=? AND screenshot_path IS NOT NULL",
      )
      .get(IdSchema.parse(id));
    return row ? { botId: String(row.bot_id), path: String(row.screenshot_path) } : undefined;
  }

  list(
    query: { botId?: string; runId?: string; groupId?: string; from?: string } = {},
    page: Page = {},
  ): ComputerStep[] {
    const scope: [string, string][] = [];
    if (query.botId) scope.push(["bot_id", IdSchema.parse(query.botId)]);
    if (query.runId) scope.push(["run_id", IdSchema.parse(query.runId)]);
    if (query.groupId)
      scope.push([
        "(SELECT r.group_id FROM runs r WHERE r.id=computer_steps.run_id)",
        IdSchema.parse(query.groupId),
      ]);
    return readPage(this.db, "computer_steps", columns, "created_at", page, scope)
      .filter((row) => !query.from || String(row.createdAt) >= query.from)
      .map(parseStep);
  }

  /**
   * Retention sweep, one bounded batch at a time: returns files older than `before` and clears
   * their references in the same transaction, so a crash after deletion never leaves a step
   * pointing at a missing file (an orphan file is retried by the directory scan instead).
   */
  takeExpiredScreenshots(before: Date, limit = 200): { id: string; botId: string; path: string }[] {
    if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000)
      throw new TypeError("Invalid sweep limit");
    return transaction(this.db, () => {
      const rows = this.db
        .prepare(
          `SELECT id,bot_id,screenshot_path FROM computer_steps
            WHERE screenshot_path IS NOT NULL AND created_at<? ORDER BY created_at LIMIT ?`,
        )
        .all(before.toISOString(), limit)
        .map((row) => ({
          id: String(row.id),
          botId: String(row.bot_id),
          path: String(row.screenshot_path),
        }));
      const clear = this.db.prepare("UPDATE computer_steps SET screenshot_path=NULL WHERE id=?");
      for (const row of rows) clear.run(row.id);
      return rows;
    });
  }
}