Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

13.0 KB
Raw Blame
/**
 * Delivering work to employees. Every automatic trigger is one user input sent to a
 * session: an `[org_trigger]` block (built by core's marker module, which also owns the
 * parser the frontend folds it with) followed by the trigger's content. `ensureDesk` here
 * is the single way a desk session comes into being — the hire opens one, the reconcile
 * pass provisions the ones that are missing, a trigger falls back on it, and it renews a
 * desk when the CEO reassigns a workspace; ticket sessions are opened per start. Both are
 * company Sessions — `source: "company"` in their session_meta, which keeps them out of every
 * category of the session list — stamped `client: "org"` at creation — the durable marker
 * development mode's list reads to leave them and what they spawn out of it — and take the
 * organization's approval mode of that moment; a later change of the mode reaches them
 * through `syncApprovalMode` (reconcile.ts).
 */
import { buildOrgTriggerMessage, userText } from "@adelie/core";
import type { OrgTriggerOrigin } from "@adelie/core";
import type { TicketDoc } from "../../organization/files.js";
import { orgLanguage, serializeTicket } from "../../organization/files.js";
import { agentPrincipal } from "../../organization/principal.js";
import type { OrgDeps } from "./deps.js";
import type { LoadedOrg } from "./model.js";
import { employeeLine, sharedWorkspace } from "./model.js";

/** The desk session's title, in the organization's working language. */
function deskTitle(org: LoadedOrg, name: string): string {
  return orgLanguage(org.config) === "zh" ? `${name} 的工位` : `${name}'s desk`;
}

export interface DeskHandle {
  sessionId: string;
  workspace: string;
  openedAt: string;
  created: boolean;
}

export type DeskResult = { ok: true; desk: DeskHandle } | { ok: false; error: string };

/**
 * The employee's desk session: reused while it exists and still sits in the workspace the
 * chart resolves to; otherwise (the hire, a desk the pass found missing, a session deleted
 * by hand or with its Agent, a reassigned workspace, or an explicit renewal) a new one is
 * opened and the ledger rewritten. The old session stays as history under `previous` so its
 * cost keeps counting. A relative workspace that is not on disk is created here too — a
 * hand-edited chart, or the calendar reaching a desk before anyone opened it, must not leave
 * an employee unable to work over a missing directory.
 */
export async function ensureDesk(
  deps: OrgDeps,
  org: LoadedOrg,
  agentId: string,
  opts: { renew?: boolean } = {},
): Promise<DeskResult> {
  const employee = org.byId.get(agentId);
  if (!employee) return { ok: false, error: `${agentId} is not an employee of ${org.orgId}` };
  if (!(await deps.agents.exists(org.projectId, agentId))) {
    return { ok: false, error: `Agent ${agentId} does not exist` };
  }
  const shared = sharedWorkspace(org);
  if (deps.store.workspaceTarget(shared, employee.workspace) === null) {
    return {
      ok: false,
      error: `workspace leaves the shared workspace for ${agentId}: ${employee.workspace}`,
    };
  }
  const workspace = await deps.store.ensureWorkspace(shared, employee.workspace);
  if (workspace === null) {
    return {
      ok: false,
      error: `workspace directory does not exist for ${agentId}: ${employee.workspace}`,
    };
  }
  // What a desk is opened on. The chart follows an in-session switch made on the desk (see
  // OrganizationService.deskModelChanged), so a renewal keeps the employee's model.
  const model = employee.model ?? org.config.model;
  const existing = org.desks[agentId];
  if (
    existing &&
    opts.renew !== true &&
    existing.workspace === workspace &&
    deps.sessions.findById(existing.sessionId) !== null
  ) {
    return {
      ok: true,
      desk: {
        sessionId: existing.sessionId,
        workspace: existing.workspace,
        openedAt: existing.openedAt,
        created: false,
      },
    };
  }
  let created: { sessionId: string; workspace: string };
  try {
    created = await deps.sessionCreator.createSession({
      projectId: org.projectId,
      agentId,
      workspace,
      ...(model !== undefined ? { modelId: model.modelId, provider: model.provider } : {}),
      approvalMode: org.config.approvalMode,
      client: "org",
      source: "company",
    });
  } catch (err) {
    return {
      ok: false,
      error: `failed to open a desk session for ${agentId}: ${err instanceof Error ? err.message : String(err)}`,
    };
  }
  const name = await deps.agents.displayName(org.projectId, agentId);
  // A manual title: the auto-title pass only fills empty titles, so the desk keeps its name.
  deps.sessions.updateTitle(created.sessionId, deskTitle(org, name));
  const openedAt = new Date(deps.now?.() ?? Date.now()).toISOString();
  const previous = existing ? [...existing.previous, existing.sessionId] : [];
  org.desks[agentId] = {
    sessionId: created.sessionId,
    workspace: created.workspace,
    openedAt,
    previous,
  };
  await deps.store.writeDesks(org.dir, org.desks);
  syncDeskCache(deps, org);
  return {
    ok: true,
    desk: { sessionId: created.sessionId, workspace: created.workspace, openedAt, created: true },
  };
}

/**
 * The model an employee's current desk Session runs on, or undefined when it has no desk (or
 * the desk's Session is gone). The chart's `model` is what a desk is OPENED on; from then on
 * the desk Session is where the employee's model is read.
 */
export function deskModel(
  deps: OrgDeps,
  org: LoadedOrg,
  agentId: string,
): { provider: string; modelId: string } | undefined {
  const desk = org.desks[agentId];
  const row = desk ? deps.sessions.findById(desk.sessionId) : null;
  return row ? { provider: row.provider, modelId: row.modelId } : undefined;
}

/** Projects the ledger into `org_sessions` (current desks and their history). */
export function syncDeskCache(deps: OrgDeps, org: LoadedOrg): void {
  const rows: Array<{ sessionId: string; agentId: string; current: boolean }> = [];
  for (const [agentId, desk] of Object.entries(org.desks)) {
    rows.push({ sessionId: desk.sessionId, agentId, current: true });
    for (const prev of desk.previous) rows.push({ sessionId: prev, agentId, current: false });
  }
  deps.cache.syncDeskSessions(org.projectId, org.orgId, rows);
}

export type DeskTrigger = Omit<OrgTriggerOrigin, "org" | "employee" | "budget">;

export type DispatchOutcome = "sent" | "queued" | "skipped";

/**
 * Sends one work run to an employee's desk: opens the desk if needed, prefixes the block,
 * queues behind a running Task (`queueIfBusy`: a busy desk works it next — for as long as this
 * process lives; mentions therefore wait in `org_desk_mentions` and come here only for an idle
 * desk), records the chain hop and notifies the Project's users.
 */
export async function dispatchToDesk(
  deps: OrgDeps,
  org: LoadedOrg,
  agentId: string,
  trigger: DeskTrigger,
  body: string,
  opts: { hop: number; budget?: string },
): Promise<DispatchOutcome> {
  const desk = await ensureDesk(deps, org, agentId);
  if (!desk.ok) {
    deps.errors.record({
      source: "organization",
      err: new Error(desk.error),
      code: "org_desk_unavailable",
      ctx: { projectId: org.projectId, agentId },
    });
    return "skipped";
  }
  const origin: OrgTriggerOrigin = {
    org: org.orgId,
    employee: employeeLine(org, agentId),
    ...trigger,
    ...(opts.budget !== undefined ? { budget: opts.budget } : {}),
  };
  const text = buildOrgTriggerMessage(origin, body);
  let queued = false;
  try {
    // sender "server": in the Trace this user turn was injected by the organization scheduler, not typed by a person.
    const res = await deps.runner.startTask(desk.desk.sessionId, [userText(text, "server")], {
      queueIfBusy: true,
    });
    queued = res.queued === true;
  } catch (err) {
    deps.errors.record({
      source: "organization",
      err,
      code: "org_dispatch_failed",
      ctx: { projectId: org.projectId, agentId, sessionId: desk.desk.sessionId },
    });
    return "skipped";
  }
  deps.cache.setTriggerHop(desk.desk.sessionId, opts.hop);
  deps.notifyProject(org.projectId, {
    type: "org_run",
    projectId: org.projectId,
    orgId: org.orgId,
    agentId,
    sessionId: desk.desk.sessionId,
    kind: trigger.kind,
  });
  return queued ? "queued" : "sent";
}

/**
 * Opens a ticket session: an ordinary session of the employee's Agent in the desk's (or a
 * chosen) workspace, appended to the ticket's `sessions` list — the fact that makes the
 * session the ticket's — and started with one input carrying where it stands, the rule that
 * references and deliverables are named by full path, and the whole ticket. The ticket file
 * and the cache learn of the session only once the task is away: a start that throws must
 * leave no session behind for the spend, the history and the `#n` titles to count. `by` is
 * the principal the `session_started` history entry is recorded under; it defaults to the
 * employee the session runs as, which is who started it in every path but a person's.
 */
export async function openTicketSession(
  deps: OrgDeps,
  org: LoadedOrg,
  ticket: { ticketId: string; column: TicketDoc["status"]; doc: TicketDoc },
  agentId: string,
  opts: { message?: string; workspace?: string; budget?: string; by?: string },
): Promise<{ ok: true; sessionId: string } | { ok: false; error: string }> {
  const employee = org.byId.get(agentId);
  if (!employee) return { ok: false, error: `${agentId} is not an employee of ${org.orgId}` };
  const spec = opts.workspace ?? employee.workspace;
  const workspace = await deps.store.ensureWorkspace(sharedWorkspace(org), spec);
  if (workspace === null) {
    return { ok: false, error: `workspace directory does not exist: ${spec}` };
  }
  // An employee's model is its desk Session's: a ticket Session opens on the model the
  // current desk runs on now — an in-session switch there moved it — and on the chart's only
  // for an employee that has no desk.
  const model = deskModel(deps, org, agentId) ?? employee.model ?? org.config.model;
  let created: { sessionId: string; workspace: string };
  try {
    created = await deps.sessionCreator.createSession({
      projectId: org.projectId,
      agentId,
      workspace,
      ...(model !== undefined ? { modelId: model.modelId, provider: model.provider } : {}),
      approvalMode: org.config.approvalMode,
      client: "org",
      source: "company",
    });
  } catch (err) {
    return { ok: false, error: err instanceof Error ? err.message : String(err) };
  }
  // The session joins the ticket in memory first, because the trigger below sends the ticket
  // as it now stands; nothing is persisted until the task has started.
  const n = ticket.doc.sessions.length + 1;
  deps.sessions.updateTitle(created.sessionId, `${ticket.doc.title} #${n}`);
  ticket.doc.sessions = [...ticket.doc.sessions, created.sessionId];
  ticket.doc.history = [
    ...ticket.doc.history,
    {
      at: new Date(deps.now?.() ?? Date.now()).toISOString(),
      by: opts.by ?? agentPrincipal(agentId),
      action: "session_started",
      note: created.sessionId,
    },
  ];
  // Messages a ticket session sends carry hop 1: it was opened by a work run, not by a person.
  deps.cache.setTriggerHop(created.sessionId, 0);
  const origin: OrgTriggerOrigin = {
    org: org.orgId,
    employee: employeeLine(org, agentId),
    kind: "ticket_work",
    ticket: ticket.ticketId,
    ...(opts.budget !== undefined ? { budget: opts.budget } : {}),
  };
  // Where the session stands, then the naming rule: colleagues read each other's tickets,
  // not each other's terminals, so a reference nobody can open is a reference nobody has.
  const note = opts.message?.trim() ?? "";
  const body = [
    `Workspace: ${created.workspace} — the organization is at \`<app_data_dir>/organizations/${org.orgId}/\`.`,
    "Name every input you rely on and every deliverable you produce by its full path (absolute, or `<app_data_dir>/…`) in your progress lines and in `## Result`; a colleague must be able to open it without asking.",
    ...(note !== "" ? [`Note from the desk: ${note}`] : []),
    `The ticket, as filed:\n\n${serializeTicket(ticket.doc).trimEnd()}`,
  ].join("\n\n");
  try {
    await deps.runner.startTask(created.sessionId, [
      userText(buildOrgTriggerMessage(origin, body), "server"),
    ]);
  } catch (err) {
    return { ok: false, error: err instanceof Error ? err.message : String(err) };
  }
  // The task is away: the ticket may own the session now.
  await deps.store.writeTicket(org.dir, ticket.ticketId, ticket.column, ticket.doc);
  deps.cache.addTicketSession(
    org.projectId,
    org.orgId,
    ticket.ticketId,
    created.sessionId,
    agentId,
  );
  deps.notifyProject(org.projectId, {
    type: "org_run",
    projectId: org.projectId,
    orgId: org.orgId,
    agentId,
    sessionId: created.sessionId,
    kind: "ticket_work",
  });
  deps.notifyProject(org.projectId, {
    type: "org_ticket",
    projectId: org.projectId,
    orgId: org.orgId,
    ticketId: ticket.ticketId,
    change: "session_started",
  });
  return { ok: true, sessionId: created.sessionId };
}