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.

7.1 KB
Raw Blame
import { createHash, randomUUID } from "node:crypto";
import type { ContextEvent } from "@earendil-works/pi-coding-agent";
import { z } from "zod";
import { STATE_MARKER } from "./volatile-state.ts";

type Message = ContextEvent["messages"][number];
type Text = { type: "text"; text: string };

/**
 * Writes Pi Bot's own model-visible messages (runtime states, untrusted references) into
 * the session transcript as pi `custom_message` entries, so a later run of the same session sees
 * them byte-identical at the place they were first sent and the provider's cached prefix of the
 * previous run still matches. Injected by the runtime (the pi SessionManager); absent in callers
 * that keep the per-run layout.
 */
export interface TranscriptPort {
  /** Appends after the session's last entry, which is where the hook placed the message. */
  append(customType: string, content: Text[], details: unknown): void;
  /** Every entry of the session file on all branches (the state counter must never go back). */
  entries(): readonly unknown[];
}

export const STATE_TYPE = "pibot_state";
export const REFERENCE_TYPE = "pibot_reference";

const id = z.string().uuid();
const hash = z.string().regex(/^[0-9a-f]{16}$/);
const stateDetails = z.object({ v: z.literal(1), id, number: z.number().int().min(1) });
export const referenceDetails = z.object({
  v: z.literal(1),
  id,
  /**
   * A full group reference, a routine-result-only reference, an update on an earlier one, or
   * (SEC) the run context: memory, working location, project notes, workflow skill text.
   */
  kind: z.enum(["group", "routine", "update", "context"]),
  /** Image digests in content order; the bytes never go to the transcript (rehydrated). */
  images: z.array(z.string().regex(/^[0-9a-f]{64}$/)).max(5),
  /** What this message adds to what the model was shown (ids and hashes only, no text). */
  known: z.object({
    messages: z.record(z.string().max(200), hash),
    parts: z.array(hash).max(5000),
    images: z.array(z.string().max(200)).max(5000),
    workplace: hash.optional(),
    routine: hash.optional(),
    /** SEC: hash of each run-context block this message shows (the newest of a kind wins). */
    context: z
      .object({
        memory: hash.optional(),
        workplace: hash.optional(),
        projectNotes: hash.optional(),
        workflow: hash.optional(),
        backgroundResults: hash.optional(),
        routineTopicReference: hash.optional(),
      })
      .optional(),
  }),
});
export type ReferenceDetails = z.infer<typeof referenceDetails>;

export const shortHash = (text: string) =>
  createHash("sha256").update(text).digest("hex").slice(0, 16);
export const newEntryId = () => randomUUID();

/** First line of state message `number` up to its fixed wording; nothing else can produce it. */
export const stateHead = (number: number) => `${STATE_MARKER} #${number}: generated by Pi Bot`;

const textOf = (m: Message) => {
  if (m.role !== "custom" || !Array.isArray(m.content) || m.content.length !== 1) return undefined;
  const [part] = m.content;
  return part?.type === "text" ? part.text : undefined;
};

/**
 * A Pi Bot state message: the right custom type, valid details, one text part that starts with
 * the exact head for its number. Only Pi Bot's code writes this custom type (pi loads no other
 * extension), and untrusted text can never carry the marker (`disarmStateMarker`, `groupText`).
 */
export function stateEntry(m: Message) {
  if (m.role !== "custom" || m.customType !== STATE_TYPE) return undefined;
  const details = stateDetails.safeParse(m.details);
  const text = textOf(m);
  if (!details.success || text === undefined || !text.startsWith(stateHead(details.data.number)))
    return undefined;
  return { id: details.data.id, number: details.data.number, text };
}

/** A Pi Bot reference message (untrusted data inside); `id` identifies it across requests. */
export function referenceEntry(m: Message) {
  if (m.role !== "custom" || m.customType !== REFERENCE_TYPE) return undefined;
  const details = referenceDetails.safeParse(m.details);
  return details.success ? details.data : undefined;
}

/** Whether the conversation already shows a full group reference (a new run opens with an update). */
export const showsGroupReference = (messages: readonly Message[]) =>
  messages.some((m) => referenceEntry(m)?.kind === "group");

/** Id of a Pi Bot message (state or reference), persisted or not. */
export const entryId = (m: Message) => (stateEntry(m) ?? referenceEntry(m))?.id;

/** Highest state number ever written to this session, so numbers stay unique session-wide. */
export function highestState(entries: readonly unknown[]) {
  let highest = 0;
  for (const entry of entries) {
    const e = entry as { type?: unknown; customType?: unknown; details?: unknown };
    if (e?.type !== "custom_message" || e.customType !== STATE_TYPE) continue;
    const details = stateDetails.safeParse(e.details);
    if (details.success) highest = Math.max(highest, details.data.number);
  }
  return highest;
}

export function customMessage(
  customType: string,
  content: (Text | { type: "image"; data: string; mimeType: string })[],
  details: unknown,
) {
  return {
    role: "custom",
    customType,
    display: false,
    content,
    details,
    timestamp: Date.now(),
  } as Message;
}

export function stateDetailsFor(number: number) {
  return { v: 1 as const, id: newEntryId(), number };
}

/** Identity of a transcript message across requests (pi hands each hook a fresh clone). */
export const messageKey = (m: Message) =>
  `${m.role}:${m.timestamp}:${m.role === "toolResult" ? m.toolCallId : ""}`;

/**
 * Where a Pi Bot message sits: right after another Pi Bot message (by id) or after a transcript
 * message (by key). Always the request's last message at creation, which is also where the
 * transcript port appends it, so the in-run and the persisted order agree.
 */
export type Anchor = { id: string } | { key: string };

export function anchorAfter(messages: Message[]): Anchor {
  const last = messages.at(-1);
  if (!last) return { key: "" };
  const own = entryId(last);
  return own ? { id: own } : { key: messageKey(last) };
}

/** Index of the anchor in a request; `ids` are the requests's Pi Bot message ids by position. */
function locate(messages: Message[], ids: (string | undefined)[], anchor: Anchor) {
  return "id" in anchor
    ? ids.indexOf(anchor.id)
    : messages.findLastIndex((m, i) => !ids[i] && messageKey(m) === anchor.key);
}

/**
 * Inserts this run's messages that the transcript does not show yet (pi refreshes its message
 * list from the session file at some boundaries, after which they are already in place). One
 * whose anchor is gone was dropped together with it by a compaction, and stays out.
 */
export function placeCreated(messages: Message[], created: { anchor: Anchor; message: Message }[]) {
  const out = messages.slice();
  const ids = out.map(entryId);
  for (const item of created) {
    const id = entryId(item.message);
    if (ids.includes(id)) continue;
    const at = locate(out, ids, item.anchor);
    if (at < 0) continue;
    out.splice(at + 1, 0, item.message);
    ids.splice(at + 1, 0, id);
  }
  return out;
}