import { readdir, readFile } from 'node:fs/promises' import { join } from 'node:path' /** * System prompt construction (spec AC15/AC20). * pi's default prompt is fully replaced; the replacement is persona plus a * generated operational core derived from the actual tool registry, so * guidance stays truthful because it is rendered from runtime state. */ export interface ToolSummary { name: string description: string } export async function readPersona(personaDir: string): Promise { const files = (await readdir(personaDir)).filter((f) => f.endsWith('.md')).sort() const parts: string[] = [] for (const f of files) parts.push(await readFile(join(personaDir, f), 'utf8')) return parts.join('\n\n') } export function renderToolRegistry(tools: ToolSummary[]): string { const lines = tools .slice() .sort((a, b) => a.name.localeCompare(b.name)) .map((t) => `- ${t.name}: ${t.description.split('\n')[0]?.trim() ?? ''}`) return `\n${lines.join('\n')}\n` } const OPERATIONAL_RULES = ` - Tools are listed above with their real names and schemas; the registry is generated from the live session, never hand-maintained. - Skills are discovered automatically; read a skill's SKILL.md only when its description matches the task (progressive disclosure). - Before editing code under a subdirectory, read the nearest AGENTS.md in that subtree; the root AGENTS.md is already in context. - All chat, audit, and deployment history is queryable through the recall tool; compaction never destroys information. - Registry credentials are absent from this body: image releases flow only through CI on git push. - The deployment platform owns probation and rollback; explicit image rollback is available via the deployment_rollback tool restricted to the previous revision. - The worktree is the editing source; operational persona, skills, and prompts come from the deployed image. ` export async function buildSystemPrompt(personaDir: string, tools: ToolSummary[]): Promise { const persona = await readPersona(personaDir) return `${persona.trim()} ${renderToolRegistry(tools)} ${OPERATIONAL_RULES}` } /** Live facts rendered into every wake prompt, never frozen into the system prompt. */ export interface WakeFacts { revision?: string | undefined agentDigest?: string | undefined serviceStorageState?: string | undefined queueDepth?: number | undefined budgetUsed?: number | undefined budgetCap?: number | undefined worktreeHead?: string | undefined worktreeDirty?: boolean | undefined timeUtc?: string | undefined } export function renderFacts(facts: WakeFacts): string { const lines: string[] = [] if (facts.timeUtc !== undefined) lines.push(`time_utc: ${facts.timeUtc}`) if (facts.revision !== undefined) lines.push(`deployment_revision: ${facts.revision}`) if (facts.agentDigest !== undefined) lines.push(`agent_image: ${facts.agentDigest}`) if (facts.worktreeHead !== undefined) lines.push( `worktree_head: ${facts.worktreeHead}${facts.worktreeDirty === true ? ' (dirty)' : ''}`, ) if (facts.serviceStorageState !== undefined) lines.push(`service_storage: ${facts.serviceStorageState}`) if (facts.queueDepth !== undefined) lines.push(`pending_wakes: ${facts.queueDepth}`) if (facts.budgetUsed !== undefined && facts.budgetCap !== undefined) lines.push(`model_budget_used: ${facts.budgetUsed}/${facts.budgetCap}`) return `\n${lines.join('\n')}\n` } export interface ChatWakePayloadLike { messageId: number senderName?: string | undefined text?: string | undefined triggerReason: string media?: { digest: string; type: string }[] | undefined replyToMessageId?: number | undefined } /** Boot context merged into the first pending wake (spec AC16: no separate boot call). */ export function renderBootContext(): string { return ` The agent process just started: deployment replaced or restarted the body. Reorient before acting: check pending wakes, service health, and the last audit events. ` } export function renderWakePrompt( wake: { kind: string; payload: unknown }, facts: WakeFacts, opts: { boot?: boolean } = {}, ): string { const head = opts.boot === true ? `${renderBootContext()}\n\n` : '' const factsBlock = renderFacts(facts) switch (wake.kind) { case 'chat': { const p = wake.payload as ChatWakePayloadLike const media = (p.media?.length ?? 0) > 0 ? `\n\n${(p.media ?? []) .map((m) => `- ${m.digest} (${m.type}); analyze with a media tool when relevant`) .join('\n')}\n` : '' const reply = p.replyToMessageId !== undefined ? `\n(reply to message ${p.replyToMessageId})` : '' return `${head}${factsBlock} from: ${p.senderName ?? 'unknown'} ${p.text ?? '(no text)'}${reply}${media} Answer as yourself in the group via the chat_send tool when a reply is wanted.` } case 'heartbeat': return `${head}${factsBlock} Hourly heartbeat. Review: recent audit events for errors, deployment history for failures, storage state, unpushed worktree commits, and anything you promised to follow up on. Act on findings; otherwise stay quiet unless something deserves sharing. ` case 'deploy_failure': { const p = wake.payload as { revision?: string; kind?: string; detail?: unknown } return `${head}${factsBlock} Deployment failed and was rolled back (or stopped at v0). revision: ${p.revision ?? 'unknown'} kind: ${p.kind ?? 'unknown'} detail: ${JSON.stringify(p.detail ?? {})} Read the failure, diagnose the cause, then push a revert or fix commit that names the failed revision so CI can reconcile the deployment barrier. ` } case 'ci_failure': { const p = wake.payload as { sha?: string; job?: string; url?: string } return `${head}${factsBlock} A pushed commit failed its CI gates before deployment. commit: ${p.sha ?? 'unknown'} job: ${p.job ?? 'unknown'} logs: ${p.url ?? 'check via the ci skill'} Diagnose the failure and push a fix. ` } case 'recovery': { const p = wake.payload as { interruptedWakeId?: string; note?: string } return `${head}${factsBlock} A previous turn was interrupted (timeout or crash) and may have left partial side effects. interrupted wake: ${p.interruptedWakeId ?? 'unknown'} ${p.note ?? ''} Inspect current state with recall and the filesystem before continuing; do not blindly replay. ` } default: return `${head}${factsBlock}\n\n\n${JSON.stringify(wake.payload ?? null)}\n` } }