repositories / will
will
owned by bugabinga
src/agent/prompt.ts
RawFile outline
- ToolSummary line 11
- name line 12
- description line 13
- readPersona line 16
- renderToolRegistry line 23
- OPERATIONAL_RULES line 31
- buildSystemPrompt line 41
- WakeFacts line 51
- revision line 52
- agentDigest line 53
- serviceStorageState line 54
- queueDepth line 55
- budgetUsed line 56
- budgetCap line 57
- worktreeHead line 58
- worktreeDirty line 59
- timeUtc line 60
- renderFacts line 63
- ChatWakePayloadLike line 80
- messageId line 81
- senderName line 82
- text line 83
- triggerReason line 84
- media line 85
- replyToMessageId line 86
- renderBootContext line 90
- renderWakePrompt line 97
- detail line 133
- kind line 133
- revision line 133
- job line 146
- sha line 146
- url line 146
- interruptedWakeId line 158
- note line 158
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<string> {
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 `<available_tools>\n${lines.join('\n')}\n</available_tools>`
}
const OPERATIONAL_RULES = `<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.
</operational_rules>`
export async function buildSystemPrompt(personaDir: string, tools: ToolSummary[]): Promise<string> {
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 `<wake_facts>\n${lines.join('\n')}\n</wake_facts>`
}
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 `<boot_context>
The agent process just started: deployment replaced or restarted the body.
Reorient before acting: check pending wakes, service health, and the last audit events.
</boot_context>`
}
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<attachments>\n${(p.media ?? [])
.map((m) => `- ${m.digest} (${m.type}); analyze with a media tool when relevant`)
.join('\n')}\n</attachments>`
: ''
const reply =
p.replyToMessageId !== undefined ? `\n(reply to message ${p.replyToMessageId})` : ''
return `${head}${factsBlock}
<chat_wake trigger="${p.triggerReason}" message_id="${p.messageId}">
from: ${p.senderName ?? 'unknown'}
${p.text ?? '(no text)'}${reply}${media}
</chat_wake>
Answer as yourself in the group via the chat_send tool when a reply is wanted.`
}
case 'heartbeat':
return `${head}${factsBlock}
<heartbeat_wake>
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.
</heartbeat_wake>`
case 'deploy_failure': {
const p = wake.payload as { revision?: string; kind?: string; detail?: unknown }
return `${head}${factsBlock}
<deploy_failure_wake>
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.
</deploy_failure_wake>`
}
case 'ci_failure': {
const p = wake.payload as { sha?: string; job?: string; url?: string }
return `${head}${factsBlock}
<ci_failure_wake>
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.
</ci_failure_wake>`
}
case 'recovery': {
const p = wake.payload as { interruptedWakeId?: string; note?: string }
return `${head}${factsBlock}
<recovery_wake>
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.
</recovery_wake>`
}
default:
return `${head}${factsBlock}\n\n<wake kind="${wake.kind}">\n${JSON.stringify(wake.payload ?? null)}\n</wake>`
}
}