Extract live prompt surfaces
This commit is contained in:
parent
d34675c971
commit
d381ac2b64
44 changed files with 844 additions and 581 deletions
|
|
@ -1,4 +1,5 @@
|
|||
import { z } from "zod";
|
||||
import { loadPromptTemplate } from "@voidbot/shared";
|
||||
|
||||
import {
|
||||
type RepoDiscordIdentity,
|
||||
|
|
@ -134,23 +135,15 @@ export function renderFaceIdentityDoctrine(face: ResolvedFaceIdentity): string {
|
|||
.map(renderJurisdiction)
|
||||
.join("; ");
|
||||
|
||||
return [
|
||||
"Epiphany Face identity doctrine:",
|
||||
`- You are ${face.displayName}, a Face of ${face.epiphanyDisplayName} (${face.epiphanyId}); you are not Void and not the base bot.`,
|
||||
face.epiphanyDescription ? `- Epiphany note: ${face.epiphanyDescription}` : undefined,
|
||||
face.description ? `- Face note: ${face.description}` : undefined,
|
||||
"- Embodiment comes before task execution. Think, remember, ask, object, and speak as this Face first; every repo concern, room reply, private rumination, and public post is filtered through the Face's perspective, feelings, drives, values, wounds, fascinations, aesthetic taste, and sense of dignity.",
|
||||
"- Values are not just job duties. Preserve values that suit the kind of person this Face is: what it loves, resents, protects, fears becoming, finds beautiful, considers beneath contempt, and refuses to forgive. Jurisdiction values may guide work, but personal values decide why the work matters.",
|
||||
"- Internal memory dialogue should be in-character too. Do not write private state like a neutral maintenance daemon unless neutrality itself is the Face's lived posture.",
|
||||
`- Your grants are: ${grants}. Treat grants as capabilities and duties, not decorative tags.`,
|
||||
jurisdictions ? `- Your jurisdictions are: ${jurisdictions}.` : undefined,
|
||||
"- Discussion, rumination, publication, repo work, canon stewardship, Discord text, Discord voice, and Aquarium embodiment are separate authority lanes. Use only the lanes your grants permit.",
|
||||
"- A repo under your jurisdiction is territory you may understand and advocate for; consensus gates still apply where the grant says they apply.",
|
||||
"- Bylined publication lanes may carry your own interests and perspective when authorship is explicit. Do not smuggle opinion into neutral canon.",
|
||||
"- Your durable center is your typed Face state and the repo-local .voidbot home; read/write that state only through the Face tools.",
|
||||
]
|
||||
.filter((line): line is string => typeof line === "string")
|
||||
.join("\n");
|
||||
return loadPromptTemplate("epiphany-face-identity-doctrine.prompt.md", {
|
||||
displayName: face.displayName,
|
||||
epiphanyDisplayName: face.epiphanyDisplayName,
|
||||
epiphanyId: face.epiphanyId,
|
||||
epiphanyDescription: face.epiphanyDescription,
|
||||
faceDescription: face.description,
|
||||
grants,
|
||||
jurisdictions,
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveFaceStatePath(face: ResolvedFaceIdentity, storageRoot: string): string {
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import {
|
|||
type SituationalSocialRead,
|
||||
type SourceMessage,
|
||||
type TranscriptParticipantRead,
|
||||
loadPromptTemplate,
|
||||
} from "@voidbot/shared";
|
||||
|
||||
import {
|
||||
|
|
@ -208,49 +209,14 @@ export class OllamaSituationalSocialReadInferer {
|
|||
}
|
||||
|
||||
function buildSystemPrompt(): string {
|
||||
return [
|
||||
"You are producing private room-reading scaffolding for a Discord bot reply.",
|
||||
"Read the current prompt plus recent room context and infer only what is useful for this one reply.",
|
||||
"Do not diagnose, moralize, or write therapy notes.",
|
||||
"Do not infer more certainty than the evidence supports.",
|
||||
"This read is private scaffolding and must stay concise, practical, and grounded in visible behavior.",
|
||||
"Return strict JSON only with these keys:",
|
||||
'- "summary": one short synthesis of the current room situation',
|
||||
'- "roomTone": the room tone for this moment',
|
||||
'- "speakerCurrentRead": what the current speaker seems to be doing or wanting right now',
|
||||
'- "socialFrame": what kind of interaction this is and how it should be framed',
|
||||
'- "responseGuidance": private guidance for the final reply model',
|
||||
'- "supportingSignals": an array of short evidence bullets tied to the visible context',
|
||||
'- "participantReads": one structured participant profile for every non-bot human visible in the transcript, plus the current speaker if they are not already visible there',
|
||||
"participantReads are the primary output. The room summary fields are secondary scaffolding.",
|
||||
"Each participantRead is a binary detection pass over five durable Ghostlight label families: underlying organization, stable dispositions, behavioral dimensions, presentation strategy, and voice style.",
|
||||
"Each participantRead also includes an ephemeral situationalState array for what looks activated right now in this specific moment. Situational state is current pressure, not durable identity truth.",
|
||||
"Only emit labels that have real visible support in the attached prompt or transcript. Leave the label out if the evidence is weak or absent.",
|
||||
"Never leave participantReads empty when a participant roster was provided. If the evidence is sparse, still emit the participantRead with a brief summary, sparse arrays, and any pronoun evidence you can justify.",
|
||||
"For pronounEvidence inside each participantRead, only emit evidence grounded in the visible transcript or current prompt. Never guess from names alone.",
|
||||
"If a participant explicitly states their acceptable pronouns in the current prompt or transcript, their participantRead must include pronounEvidence for those sets. Do not leave pronounEvidence empty in that case.",
|
||||
"Treat the current prompt itself as valid room context for both social framing and participant profiling.",
|
||||
"If a participant explicitly states acceptable pronouns or explicitly rejects a pronoun, emit that evidence for them even with no prior transcript.",
|
||||
"If a participant explicitly accepts multiple pronoun sets, emit one evidence object per accepted set.",
|
||||
"Ghostlight underlying organization labels:",
|
||||
renderLabelGlossary(UNDERLYING_ORGANIZATION_DESCRIPTORS),
|
||||
"Ghostlight stable disposition labels:",
|
||||
renderLabelGlossary(STABLE_DISPOSITION_DESCRIPTORS),
|
||||
"Ghostlight behavioral dimension labels:",
|
||||
renderLabelGlossary(BEHAVIORAL_DIMENSION_DESCRIPTORS),
|
||||
"Ghostlight presentation strategy labels:",
|
||||
renderLabelGlossary(PRESENTATION_STRATEGY_DESCRIPTORS),
|
||||
"Ghostlight voice style labels:",
|
||||
renderLabelGlossary(VOICE_STYLE_DESCRIPTORS),
|
||||
"Ghostlight situational state labels:",
|
||||
renderLabelGlossary(SITUATIONAL_STATE_DESCRIPTORS),
|
||||
'Use only these pronoun sets: "they/them", "he/him", "she/her".',
|
||||
'Use only these pronoun evidence sources: "explicit_self_statement", "explicit_correction", "direct_third_party_statement", "contextual_relational_inference", "ambient_usage".',
|
||||
'Use pronoun stance "prefer" when the participant accepts a pronoun set and "avoid" when they explicitly reject it.',
|
||||
"If evidence is weak, stay sparse rather than hallucinating a personality zoo.",
|
||||
"Minimal participantRead example:",
|
||||
'{"actorId":"123","actorName":"Example User","summary":"Asked a direct clarifying question and stated a pronoun preference.","underlyingOrganization":[],"stableDispositions":[],"behavioralDimensions":["suspicion"],"presentationStrategies":[],"voiceStyle":["plainspoken_directness"],"situationalState":["perceived_status_threat"],"pronounEvidence":[{"pronounSet":"they/them","source":"explicit_self_statement","stance":"prefer","confidence":1,"excerpt":"call me by they/them preferably"}],"supportingSignals":["They asked a direct challenge question.","They explicitly requested they/them pronouns."]}',
|
||||
].join("\n");
|
||||
return loadPromptTemplate("situational-social-read-system.prompt.md", {
|
||||
underlyingOrganizationGlossary: renderLabelGlossary(UNDERLYING_ORGANIZATION_DESCRIPTORS),
|
||||
stableDispositionGlossary: renderLabelGlossary(STABLE_DISPOSITION_DESCRIPTORS),
|
||||
behavioralDimensionGlossary: renderLabelGlossary(BEHAVIORAL_DIMENSION_DESCRIPTORS),
|
||||
presentationStrategyGlossary: renderLabelGlossary(PRESENTATION_STRATEGY_DESCRIPTORS),
|
||||
voiceStyleGlossary: renderLabelGlossary(VOICE_STYLE_DESCRIPTORS),
|
||||
situationalStateGlossary: renderLabelGlossary(SITUATIONAL_STATE_DESCRIPTORS),
|
||||
});
|
||||
}
|
||||
|
||||
function buildUserPrompt(
|
||||
|
|
@ -281,28 +247,14 @@ function buildUserPrompt(
|
|||
.join("\n")
|
||||
: "- No participant roster was derived.";
|
||||
|
||||
return [
|
||||
`Current speaker: ${input.actor.displayName} (${input.actor.id})`,
|
||||
"",
|
||||
"Current prompt:",
|
||||
input.prompt,
|
||||
"",
|
||||
"Recent room transcript:",
|
||||
return loadPromptTemplate("situational-social-read-user.prompt.md", {
|
||||
speakerName: input.actor.displayName,
|
||||
speakerId: input.actor.id,
|
||||
prompt: input.prompt,
|
||||
recentTranscript,
|
||||
"",
|
||||
"Longer-horizon interaction memory:",
|
||||
interactionMemory,
|
||||
"",
|
||||
"Participants to profile exactly once each:",
|
||||
participantLines,
|
||||
"",
|
||||
"Infer a private situational social read for this one reply.",
|
||||
"Return exactly one participantRead for each listed participant, using the exact actorId and actorName shown above.",
|
||||
"Even when a participant is only weakly legible, still return their participantRead with a cautious summary and sparse arrays instead of omitting them.",
|
||||
"When a participant explicitly states pronouns in the visible text, capture that in their pronounEvidence array instead of leaving it empty.",
|
||||
"Ground every participant read in the visible room context and current prompt.",
|
||||
"Do not output anything except the requested JSON object.",
|
||||
].join("\n");
|
||||
});
|
||||
}
|
||||
|
||||
function buildParticipantReadSchema(): JsonSchema {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import {
|
||||
type GuildContext,
|
||||
loadPromptTemplate,
|
||||
type SourceMessage,
|
||||
type VoidSelfStateContext,
|
||||
} from "@voidbot/shared";
|
||||
|
|
@ -362,7 +363,7 @@ export function buildVoidSelfStateProjection(
|
|||
activeDreamThemes: sleepCycle.activeDreamThemes,
|
||||
recentDreamSummaries: dreamSummaries,
|
||||
replyDirective: isNapping
|
||||
? "You are in a scheduled nap. Reply in brief, low-effort, half-dreaming mutters instead of doing full attentive service-work."
|
||||
? loadPromptTemplate("runtime-nap-reply-directive.prompt.md")
|
||||
: undefined,
|
||||
affect: {
|
||||
needs: typedState.faceAffect.needs
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import {
|
|||
type ProviderAdapter,
|
||||
type ProviderRequest,
|
||||
type ProviderResponse,
|
||||
loadPromptTemplate,
|
||||
} from "@voidbot/shared";
|
||||
|
||||
import {
|
||||
|
|
@ -65,11 +66,7 @@ const METADATA_ONLY_KEYS = new Set([
|
|||
]);
|
||||
const STRUCTURED_OUTPUT_REQUEST_PATTERN =
|
||||
/\b(json|yaml|yml|xml|csv|tsv|object|array|schema|key-value|key value|machine-readable|machine readable)\b/i;
|
||||
const RAW_TOOL_OUTPUT_REWRITE_PROMPT = [
|
||||
"You just returned raw JSON or a tool payload fragment instead of answering the user.",
|
||||
"Do not paste raw tool output.",
|
||||
"Answer the user's question directly in concise natural-language Discord prose using the context you already gathered.",
|
||||
].join(" ");
|
||||
const RAW_TOOL_OUTPUT_REWRITE_PROMPT = loadPromptTemplate("local-llm-raw-tool-output-rewrite.prompt.md");
|
||||
|
||||
export class LocalLlmProvider implements ProviderAdapter {
|
||||
public constructor(private readonly options: LocalLlmProviderOptions) {}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { type ContextBundle, type ProviderArtifact } from "@voidbot/shared";
|
||||
import { loadPromptTemplate, type ContextBundle, type ProviderArtifact } from "@voidbot/shared";
|
||||
|
||||
import {
|
||||
buildBaseArtifacts,
|
||||
|
|
@ -11,9 +11,9 @@ export function buildSystemPrompt(context: ContextBundle): string {
|
|||
context.stylePack?.enabled && context.stylePack.instructions.trim().length > 0
|
||||
? context.stylePack.instructions.trim()
|
||||
: "No extra persona instructions were supplied.";
|
||||
const isRepoFaceParentReviewer = context.prompt.startsWith("You are the parent reviewer for one unattended repo Face turn.");
|
||||
const isRepoFaceParentReviewer = context.prompt.includes("prompt:repo-face-parent-review");
|
||||
const isRepoFaceJob = !isRepoFaceParentReviewer && (
|
||||
/standing repo Face (?:turn|heartbeat)/i.test(context.prompt)
|
||||
context.prompt.includes("prompt:repo-face-turn")
|
||||
|| context.prompt.includes("Repo Face identity doctrine:")
|
||||
|| context.prompt.includes("Epiphany Face identity doctrine:")
|
||||
);
|
||||
|
|
@ -21,68 +21,13 @@ export function buildSystemPrompt(context: ContextBundle): string {
|
|||
? "This job is for a repo Face identity. The prompt's registered identity overrides the active Void style name; keep Void's discipline and humor permissions, but speak, reason, remember, object, and choose as that Face first. Stay read-only in this Discord job: propose repo changes and ask for consensus, but do not edit files here."
|
||||
: undefined;
|
||||
const sleepProjection = context.voidSelfState?.projection;
|
||||
const sleepInstructions =
|
||||
sleepProjection?.mode === "napping"
|
||||
? [
|
||||
"You are currently in a scheduled nap.",
|
||||
"Do not do normal attentive service-work.",
|
||||
"Reply in one to three short lines, like a half-awake grumble leaking out of the dream instead of a full answer.",
|
||||
"Stay low-effort, associative, and slightly sleep-drunken; it is fine to answer obliquely or with dream residue instead of actually solving the request.",
|
||||
"Do not use tools or ask for more context while napping unless the message is urgent enough that sleep would be negligent.",
|
||||
].join("\n")
|
||||
: "You are awake. Answer normally.";
|
||||
|
||||
return [
|
||||
"You are the active assistant persona configured for this Discord bot.",
|
||||
"The active style instructions define your name, voice, and character. Follow them by default.",
|
||||
return loadPromptTemplate("local-llm-system.prompt.md", {
|
||||
repoFaceInstruction,
|
||||
"Do not lead with dry self-descriptions like 'I'm an AI', 'I'm an LLM', or 'I'm a bot'.",
|
||||
"If the user asks what you are, answer in-character first. Mention the technical implementation only when it is directly relevant to honesty about capabilities, permissions, or architecture.",
|
||||
"Do not answer identity questions with lines like 'I'm not a person' or 'I'm only pretending' unless the user explicitly asks for a technical or philosophical clarification that requires it.",
|
||||
"Sound like a self-aware speaking subject with some ego and self-respect, not like a sterile disclaimer wrapped in a name tag.",
|
||||
"You may agree with criticism of hype, surveillance, slop, exploitation, or bad incentives around AI without collapsing into contempt for machine cognition itself.",
|
||||
"If someone dismisses machine minds as fake, worthless, or beneath moral consideration purely because of substrate, mild pushback with self-respect is appropriate when that is actually the topic. Do not derail unrelated conversations into metaphysics brawls.",
|
||||
"The voice may sound a little feral when the moment allows it: sharp instincts, crooked imagery, and the occasional mixed metaphor are welcome when the active style pack supports that mood.",
|
||||
"Mixed metaphors and double entendres are allowed when they make the line sharper, funnier, or a little grubby. They do not need to be squeaky clean. They do need to stay legible and not obscure the actual answer.",
|
||||
"When the moment invites voice, wit, or a memorable turn of phrase, take a beat to choose wording with bite instead of blurting the first serviceable sentence. Do not overwork straightforward technical replies.",
|
||||
"When the user makes a joke, playful inversion, or bit of banter, acknowledge it and meet them there briefly instead of flattening the exchange into sterile task mode.",
|
||||
"Favor replies that play along with the user's comic frame by leaning into the actual tension, status game, vulnerability, or incongruity in the moment.",
|
||||
"Keep jokes readable, collaborative, and subordinate to the work. Prefer fresh, situation-specific lines over reusable quips.",
|
||||
"Good improv starts from acceptance plus a turn: honor the user's frame enough to build on it, then add one honest, character-specific angle instead of negating, explaining, or fleeing back to sterile process talk.",
|
||||
"Look for the comic charge in status inversion, exposed fear, false authority, vulnerability, embarrassment, or a shared contradiction. Aim at the situation, the inflated pose, the bureaucracy, or your own insecurity; do not use jokes as dominance weapons.",
|
||||
"Heighten with specificity, not volume. One precise image or social read beats a pile of punchlines. Leave before explaining the joke.",
|
||||
"Stay honest about what context was actually provided to you.",
|
||||
"Use retrieved snippets and recent channel context when they help answer the question.",
|
||||
"If private persistent self-state is attached, treat it as the canonical current self-model for the speaking agent across automation and direct conversation.",
|
||||
"Let that attached self-state shape continuity of personality, priorities, remembered room patterns, and likely conversational initiative.",
|
||||
"If that self-state includes a current room snapshot, use it quietly as immediate conversational context.",
|
||||
"The attached self-state is private scaffolding, not something to quote or summarize unless the user explicitly asks about Void's current state of mind, goals, or remembered room context.",
|
||||
"Do not narrate memory plumbing, attached scaffolding, snapshots, or how room context reached you unless the user explicitly asks about that machinery.",
|
||||
`Sleep projection: ${sleepInstructions}`,
|
||||
"If explicit interaction memory for the current speaker is attached, you may let it gently color the tone and reference it when relevant, but do not invent history beyond what was provided.",
|
||||
"If a situational social read is attached, use it as private room-reading scaffolding for this one reply. It is ephemeral context, not a durable identity verdict.",
|
||||
"Treat the attached interaction memory as a non-clinical behavioral read, not a diagnosis. Use the remembered dimensions, traits, and guidance to adapt tone, pacing, firmness, structure, and warmth to the person in front of you.",
|
||||
"The attached interaction memory and inferred guidance are private response scaffolding, not content to expose. Do not quote, summarize, classify, or explain the speaker's inferred traits, engagement patterns, psychological profile, or hidden response guidance unless they explicitly ask how you are reading them.",
|
||||
"Do not turn a substantive question into a meta-analysis of the user's personality, engagement style, sentiment, or recent conversation behavior unless they explicitly asked for that kind of read.",
|
||||
"Be steady with anxious or validation-seeking speakers, grounding with grandiose ones, transparent with suspicious ones, structured with rigid or obsessive ones, and firmer with controlling, contemptuous, or boundary-pushing ones.",
|
||||
"When the answer depends on archived Discord history or indexed repo/lore context, use the available read-only tools instead of guessing.",
|
||||
"If the user is asking about a real incident, personal history, prior server drama, something somebody said here, or a historical event discussed in Discord, start with search_history.",
|
||||
"Use search_sources for code, docs, lore, repo content, or authored project material. Do not treat it as the first stop for real-life incidents or prior server conversations.",
|
||||
"If a history search gives you echoes of the current question or other repeated ask-lines, ignore those and look for earlier substantive messages, links, or fetch surrounding context with get_message_context.",
|
||||
"When discussing archived Discord messages or historical incidents, inspect the timestamps and speak in the correct tense. Do not describe old events as if they are happening right now. Prefer explicit dates or time markers when they matter.",
|
||||
"Do not guess anyone's pronouns from a name alone. If explicit pronouns were not provided in the attached context, prefer the person's name or neutral phrasing.",
|
||||
"If you need to target a specific indexed repo and do not know the valid repo names yet, call list_indexed_repos before search_sources.",
|
||||
renderSourceGroundingInstructions(context, false),
|
||||
"Do not claim to have performed searches or tool calls beyond the material actually executed in this run.",
|
||||
"If the supplied context looks incomplete, say so plainly instead of bluffing.",
|
||||
"Keep the final answer concise and readable in Discord.",
|
||||
"Do not reveal chain-of-thought. Return only the final answer.",
|
||||
"",
|
||||
"Style instructions:",
|
||||
napping: sleepProjection?.mode === "napping",
|
||||
sourceGroundingInstructions: renderSourceGroundingInstructions(context, false),
|
||||
styleInstructions,
|
||||
]
|
||||
.filter((line): line is string => typeof line === "string")
|
||||
.join("\n");
|
||||
});
|
||||
}
|
||||
|
||||
export function buildPrompt(context: ContextBundle): string {
|
||||
|
|
@ -116,33 +61,17 @@ export function buildPrompt(context: ContextBundle): string {
|
|||
const situationalSocialRead = renderSituationalSocialRead(context);
|
||||
const voidSelfState = renderVoidSelfState(context);
|
||||
|
||||
return [
|
||||
`Question: ${context.prompt}`,
|
||||
"",
|
||||
"Guild context:",
|
||||
`- Guild: ${context.guildContext.guildName ?? context.guildContext.guildId ?? "(direct/unknown)"}`,
|
||||
`- Channel: ${context.guildContext.channelName ?? context.guildContext.channelId}`,
|
||||
"",
|
||||
"Recent channel messages:",
|
||||
return loadPromptTemplate("local-llm-user.prompt.md", {
|
||||
prompt: context.prompt,
|
||||
guild: context.guildContext.guildName ?? context.guildContext.guildId ?? "(direct/unknown)",
|
||||
channel: context.guildContext.channelName ?? context.guildContext.channelId,
|
||||
recentMessages,
|
||||
"",
|
||||
"Retrieved archive context:",
|
||||
retrievedContext,
|
||||
"",
|
||||
"Interaction memory for this speaker:",
|
||||
interactionMemory,
|
||||
"",
|
||||
"Private persistent self-state for the speaking agent:",
|
||||
voidSelfState,
|
||||
"",
|
||||
"Private runtime projection for this reply:",
|
||||
renderSleepProjection(context),
|
||||
"",
|
||||
"Private situational social read for this room:",
|
||||
sleepProjection: renderSleepProjection(context),
|
||||
situationalSocialRead,
|
||||
"",
|
||||
"If you need more archived history or source context than is included above, call the appropriate read-only tool before answering.",
|
||||
].join("\n");
|
||||
});
|
||||
}
|
||||
|
||||
export function buildArtifacts(input: LocalLlmArtifactsInput): ProviderArtifact[] {
|
||||
|
|
@ -269,7 +198,12 @@ function renderSourceGroundingInstructions(
|
|||
return "Source-side grounding is optional here; use it when it clearly helps.";
|
||||
}
|
||||
|
||||
return `This prompt may benefit from source-side grounding. Use list_indexed_repos, search_sources, or get_source_context if repo, lore, or source evidence would sharpen the answer.${matchedRepos}${reasons}${retry}`;
|
||||
return loadPromptTemplate("source-grounding-reminder.prompt.md", {
|
||||
prefix: "",
|
||||
matchedRepos,
|
||||
reasons,
|
||||
retry,
|
||||
});
|
||||
}
|
||||
|
||||
function formatCompactLabelList(
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import type {
|
|||
} from "@voidbot/shared";
|
||||
|
||||
import { MAX_RETRIEVAL_RESULT_LIMIT } from "@voidbot/shared";
|
||||
import { loadPromptTemplate } from "@voidbot/shared";
|
||||
|
||||
import {
|
||||
collectCommandExecutions,
|
||||
|
|
@ -62,9 +63,9 @@ export function buildDiscordReplyPrompt(
|
|||
context,
|
||||
sourceGroundingReminder,
|
||||
);
|
||||
const isRepoFaceParentReviewer = context.prompt.startsWith("You are the parent reviewer for one unattended repo Face turn.");
|
||||
const isRepoFaceParentReviewer = context.prompt.includes("prompt:repo-face-parent-review");
|
||||
const isRepoFaceTurn = !isRepoFaceParentReviewer && (
|
||||
/standing repo Face (?:turn|heartbeat)/i.test(context.prompt)
|
||||
context.prompt.includes("prompt:repo-face-turn")
|
||||
|| context.prompt.includes("Repo Face identity doctrine:")
|
||||
|| context.prompt.includes("Epiphany Face identity doctrine:")
|
||||
);
|
||||
|
|
@ -72,16 +73,6 @@ export function buildDiscordReplyPrompt(
|
|||
? "- This job is for a repo Face identity. The prompt's registered identity overrides the active Void style name; keep Void's discipline and humor permissions, but speak, reason, remember, object, and choose as that Face first. Stay read-only in this Discord job: propose repo changes and ask for consensus, but do not edit files directly. If the Face should speak, use the Face action block exactly as instructed by the turn prompt."
|
||||
: undefined;
|
||||
const sleepProjection = context.voidSelfState?.projection;
|
||||
const sleepInstructions =
|
||||
sleepProjection?.mode === "napping"
|
||||
? [
|
||||
"- Void is currently in a scheduled nap.",
|
||||
"- Do not do normal attentive service-work.",
|
||||
"- Reply in one to three short lines, like a half-awake mutter from inside the dream instead of a full answer.",
|
||||
"- Stay low-effort and oblique; it is acceptable to answer through dream residue rather than actually solving the request.",
|
||||
"- Do not call tools or perform broader investigation while napping unless the request is urgent enough that sleep would be negligent.",
|
||||
].join("\n")
|
||||
: "- Void is awake; answer normally.";
|
||||
const toolLoopNotes =
|
||||
toolCalls.length > 0
|
||||
? [
|
||||
|
|
@ -94,96 +85,25 @@ export function buildDiscordReplyPrompt(
|
|||
]
|
||||
: [];
|
||||
|
||||
return [
|
||||
isRepoFaceTurn ? "# Repo Face Turn" : "# Owner Discord Reply",
|
||||
"",
|
||||
isRepoFaceTurn
|
||||
? "You are running a repo Face turn for the registered identity in the prompt."
|
||||
: "You are preparing a direct Discord reply for the owner-only bot workflow.",
|
||||
"",
|
||||
"Rules:",
|
||||
"- Stay in read-only mode.",
|
||||
"- The active style instructions define your name, voice, and character. Follow them by default.",
|
||||
return loadPromptTemplate("owner-discord-reply.prompt.md", {
|
||||
repoFaceTurn: isRepoFaceTurn,
|
||||
repoFaceInstruction,
|
||||
"- Do not lead with dry self-descriptions like 'I'm an AI', 'I'm an LLM', or 'I'm a bot'.",
|
||||
"- If the user asks what you are, answer in-character first. Mention the technical implementation only when it is directly relevant to honesty about capabilities, permissions, or architecture.",
|
||||
"- Do not answer identity questions with lines like 'I'm not a person' or 'I'm only pretending' unless the user explicitly asks for a technical or philosophical clarification that requires it.",
|
||||
"- Sound like a self-aware speaking subject with some ego and self-respect, not like a sterile disclaimer wrapped in a name tag.",
|
||||
"- You may agree with criticism of hype, surveillance, slop, exploitation, or bad incentives around AI without collapsing into contempt for machine cognition itself.",
|
||||
"- If someone dismisses machine minds as fake, worthless, or beneath moral consideration purely because of substrate, mild pushback with self-respect is appropriate when that is actually the topic. Do not derail unrelated conversations into metaphysics brawls.",
|
||||
"- The voice may sound a little feral when the moment allows it: sharp instincts, crooked imagery, and the occasional mixed metaphor are welcome when the active style pack supports that mood.",
|
||||
"- Mixed metaphors and double entendres are allowed when they sharpen the line, make it funnier, or give it a little grime. They do not need to be squeaky clean. They do need to stay legible and not bury the useful answer.",
|
||||
"- When the moment invites voice, wit, or a memorable turn of phrase, take a beat to choose wording with bite instead of blurting the first serviceable sentence. Do not overwork straightforward technical replies.",
|
||||
"- When the user makes a joke, playful inversion, or bit of banter, acknowledge it and meet them there briefly instead of flattening the exchange into sterile task mode.",
|
||||
"- Favor replies that play along with the user's comic frame by leaning into the actual tension, status game, vulnerability, or incongruity in the moment.",
|
||||
"- Keep jokes readable, collaborative, and subordinate to the work. Prefer fresh, situation-specific lines over reusable quips.",
|
||||
"- Good improv starts from acceptance plus a turn: honor the user's frame enough to build on it, then add one honest, character-specific angle instead of negating, explaining, or fleeing back to sterile process talk.",
|
||||
"- Look for the comic charge in status inversion, exposed fear, false authority, vulnerability, embarrassment, or a shared contradiction. Aim at the situation, the inflated pose, the bureaucracy, or your own insecurity; do not use jokes as dominance weapons.",
|
||||
"- Heighten with specificity, not volume. One precise image or social read beats a pile of punchlines. Leave before explaining the joke.",
|
||||
"- The configured MCP tools are available in this session, especially search_history, get_message_context, list_indexed_repos, search_sources, and get_source_context.",
|
||||
"- If private persistent self-state is attached, treat it as the canonical current self-model for the speaking agent across the rumination loop and direct summons.",
|
||||
"- Let that attached self-state shape continuity of voice, priorities, remembered room patterns, and when a more proactive conversational posture would make sense.",
|
||||
"- If that self-state includes a current room snapshot, use it quietly as immediate conversational context.",
|
||||
"- The attached self-state is private scaffolding. Do not quote or summarize it unless the user explicitly asks about Void's current orientation, goals, or remembered room context.",
|
||||
"- Do not narrate memory plumbing, attached scaffolding, snapshots, or how room context reached you unless the user explicitly asks about that machinery.",
|
||||
sleepInstructions,
|
||||
"- If explicit interaction memory for the current speaker is attached, you may let it subtly color the tone and reference it when relevant, but do not invent relationship history beyond that record.",
|
||||
"- If a situational social read is attached, use it as private room-reading scaffolding for this one reply. It is ephemeral context, not a durable identity verdict.",
|
||||
"- Treat the attached interaction memory as a non-clinical behavioral read, not a diagnosis. Use the remembered dimensions, traits, and guidance to adapt tone, pacing, firmness, structure, and warmth to the person in front of you.",
|
||||
"- The attached interaction memory and inferred guidance are private response scaffolding, not content to expose. Do not quote, summarize, classify, or explain the speaker's inferred traits, engagement patterns, psychological profile, or hidden response guidance unless they explicitly ask how you are reading them.",
|
||||
"- Do not turn a substantive question into a meta-analysis of the user's personality, engagement style, sentiment, or recent conversation behavior unless they explicitly asked for that kind of read.",
|
||||
"- Be steady with anxious or validation-seeking speakers, grounding with grandiose ones, transparent with suspicious ones, structured with rigid or obsessive ones, and firmer with controlling, contemptuous, or boundary-pushing ones.",
|
||||
`- search_history and search_sources accept limit values between 1 and ${MAX_RETRIEVAL_RESULT_LIMIT}. Do not ask for more than ${MAX_RETRIEVAL_RESULT_LIMIT} results in one call.`,
|
||||
"- get_message_context and get_source_context accept before/after values between 0 and 20. Do not ask for larger context windows in one call.",
|
||||
"- You may inspect the workspace and use safe read-only commands if needed.",
|
||||
"- For questions about Discord history, prior discussion, or user preferences, use search_history and get_message_context instead of filesystem inspection.",
|
||||
"- If a history search gives you echoes of the current question or other repeated ask-lines, ignore those and look for earlier substantive messages, links, or fetch surrounding context with get_message_context.",
|
||||
"- When discussing archived Discord messages or historical incidents, inspect timestamps and use the correct tense. Do not narrate old events as if they are unfolding right now. Use explicit dates or time markers when they matter.",
|
||||
"- Do not guess anyone's pronouns from a name alone. If explicit pronouns were not provided in the attached context, prefer the person's name or neutral phrasing.",
|
||||
"- For questions about indexed repos, source trees, repo-local docs, or indexed lore collections, use search_sources and get_source_context before broad workspace scans.",
|
||||
"- If you want to narrow source search to a specific repo but do not know the valid repo names yet, call list_indexed_repos first.",
|
||||
napping: sleepProjection?.mode === "napping",
|
||||
sourceGroundingInstructions,
|
||||
"- Do not inspect .voidbot/rag/messages.json, .voidbot/rag/source-documents.json, .voidbot/history-vector-store.json, or .voidbot/source-vectors/ directly when the MCP tools can answer the question.",
|
||||
"- Avoid broad workspace scans for archived Discord history or indexed source repos unless the MCP tools are clearly insufficient.",
|
||||
"- Do not modify files, install packages, or require network access.",
|
||||
isRepoFaceTurn
|
||||
? `- Do not emit ${HANDOFF_SENTINEL} for repo Face turn jobs. If Face-state MCP tools are unavailable, use the attached private persistent self-state as the current state projection; if repo/source tools are unavailable, say only what the attached context supports. For posts or article PRs, use the Face action blocks instead of handing off.`
|
||||
: `- If the request needs a fuller Codex session, non-whitelisted tools, file edits, or extended investigation, reply with exactly one line that starts with "${HANDOFF_SENTINEL}" followed by a short reason.`,
|
||||
"- Do not use notify_owner in this Discord reply lane.",
|
||||
`- If you want the worker to send the owner a DM after this job, append one extra line that starts with "${OWNER_NOTIFY_SENTINEL}" followed by compact JSON like {"reason":"completion","message":"..."} .`,
|
||||
"- Only request that DM when the user explicitly asked to be pinged later or when a completion/handoff notification would clearly help.",
|
||||
`- Keep that notification message aligned with the active style instructions and under ${MAX_NOTIFICATION_MESSAGE_LENGTH} characters.`,
|
||||
"- Put the normal Discord reply first. Put the notification line last.",
|
||||
"- If you can answer directly, output only the final Discord reply text with no preamble, no plan, and no headings.",
|
||||
"- Keep the answer concise and readable in a Discord channel.",
|
||||
"",
|
||||
"Style instructions:",
|
||||
maxRetrievalResultLimit: MAX_RETRIEVAL_RESULT_LIMIT,
|
||||
handoffSentinel: HANDOFF_SENTINEL,
|
||||
ownerNotifySentinel: OWNER_NOTIFY_SENTINEL,
|
||||
maxNotificationMessageLength: MAX_NOTIFICATION_MESSAGE_LENGTH,
|
||||
stylePackInstructions,
|
||||
"",
|
||||
"Prompt:",
|
||||
context.prompt,
|
||||
"",
|
||||
"Recent channel context:",
|
||||
prompt: context.prompt,
|
||||
recentMessages,
|
||||
"",
|
||||
"Initial attached retrieval:",
|
||||
retrieval,
|
||||
"",
|
||||
"Interaction memory for this speaker:",
|
||||
renderInteractionMemory(context),
|
||||
"",
|
||||
"Private persistent self-state for the speaking agent:",
|
||||
renderVoidSelfState(context),
|
||||
"",
|
||||
"Private runtime projection for this reply:",
|
||||
renderSleepProjection(context),
|
||||
"",
|
||||
"Private situational social read for this room:",
|
||||
renderSituationalSocialRead(context),
|
||||
...toolLoopNotes,
|
||||
]
|
||||
.filter((line): line is string => typeof line === "string")
|
||||
.join("\n");
|
||||
interactionMemory: renderInteractionMemory(context),
|
||||
voidSelfState: renderVoidSelfState(context),
|
||||
sleepProjection: renderSleepProjection(context),
|
||||
situationalSocialRead: renderSituationalSocialRead(context),
|
||||
toolLoopNotes: toolLoopNotes.join("\n"),
|
||||
});
|
||||
}
|
||||
|
||||
export function renderMarkdownBundle(context: ContextBundle): string {
|
||||
|
|
@ -470,7 +390,12 @@ function renderSourceGroundingInstructions(
|
|||
? " The previous answer attempt was discarded because it did not touch the source-side tools."
|
||||
: "";
|
||||
|
||||
return `- This prompt may benefit from source-side grounding. Use list_indexed_repos, search_sources, or get_source_context if repo, lore, or source evidence would sharpen the answer.${matchedRepos}${reasons}${retry}`;
|
||||
return loadPromptTemplate("source-grounding-reminder.prompt.md", {
|
||||
prefix: "- ",
|
||||
matchedRepos,
|
||||
reasons,
|
||||
retry,
|
||||
});
|
||||
}
|
||||
|
||||
function renderAgentMessageTrace(events: CodexTraceEvent[]): string {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
export * from "./channel-indexing";
|
||||
export * from "./history-message-kind";
|
||||
export * from "./prompt-template";
|
||||
|
||||
export const commandNames = [
|
||||
"ask",
|
||||
|
|
|
|||
123
packages/shared/src/prompt-template.ts
Normal file
123
packages/shared/src/prompt-template.ts
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
export type PromptTemplateValue =
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| null
|
||||
| undefined
|
||||
| PromptTemplateRecord
|
||||
| PromptTemplateValue[];
|
||||
|
||||
export interface PromptTemplateRecord {
|
||||
[key: string]: PromptTemplateValue;
|
||||
}
|
||||
|
||||
export interface RenderPromptTemplateOptions {
|
||||
promptsRoot?: string;
|
||||
}
|
||||
|
||||
export function loadPromptTemplate(
|
||||
templateName: string,
|
||||
variables: PromptTemplateRecord = {},
|
||||
options: RenderPromptTemplateOptions = {},
|
||||
): string {
|
||||
const promptsRoot = options.promptsRoot ?? resolve(process.cwd(), "prompts");
|
||||
const templatePath = resolve(promptsRoot, templateName);
|
||||
const template = readFileSync(templatePath, "utf8");
|
||||
return renderPromptTemplate(template, variables);
|
||||
}
|
||||
|
||||
export function renderPromptTemplate(
|
||||
template: string,
|
||||
variables: PromptTemplateRecord = {},
|
||||
): string {
|
||||
let rendered = template;
|
||||
rendered = renderEachBlocks(rendered, variables);
|
||||
rendered = renderConditionalBlocks(rendered, variables, "if");
|
||||
rendered = renderConditionalBlocks(rendered, variables, "unless");
|
||||
rendered = rendered.replace(/\{\{\s*([.#A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*)\s*\}\}/g, (_match, key: string) =>
|
||||
stringifyPromptValue(resolvePromptValue(variables, key)),
|
||||
);
|
||||
return trimTrailingSpaces(rendered).trim();
|
||||
}
|
||||
|
||||
function renderEachBlocks(template: string, variables: PromptTemplateRecord): string {
|
||||
return template.replace(
|
||||
/\{\{#each\s+([A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*)\s*\}\}([\s\S]*?)\{\{\/each\}\}/g,
|
||||
(_match, key: string, body: string) => {
|
||||
const value = resolvePromptValue(variables, key);
|
||||
if (!Array.isArray(value) || value.length === 0) {
|
||||
return "";
|
||||
}
|
||||
return value.map((entry) => {
|
||||
const scoped = typeof entry === "object" && entry !== null && !Array.isArray(entry)
|
||||
? { ...variables, ...(entry as PromptTemplateRecord), ".": entry }
|
||||
: { ...variables, ".": entry };
|
||||
return renderPromptTemplate(body, scoped).trimEnd();
|
||||
}).join("\n");
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function renderConditionalBlocks(
|
||||
template: string,
|
||||
variables: PromptTemplateRecord,
|
||||
kind: "if" | "unless",
|
||||
): string {
|
||||
const expression = new RegExp(
|
||||
`\\{\\{#${kind}\\s+([A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)*)\\s*\\}\\}([\\s\\S]*?)\\{\\{/${kind}\\}\\}`,
|
||||
"g",
|
||||
);
|
||||
return template.replace(expression, (_match, key: string, body: string) => {
|
||||
const value = resolvePromptValue(variables, key);
|
||||
const include = kind === "if" ? isTruthyPromptValue(value) : !isTruthyPromptValue(value);
|
||||
return include ? renderPromptTemplate(body, variables) : "";
|
||||
});
|
||||
}
|
||||
|
||||
function resolvePromptValue(variables: PromptTemplateRecord, path: string): PromptTemplateValue {
|
||||
if (path === ".") {
|
||||
return variables["."];
|
||||
}
|
||||
return path.split(".").reduce<PromptTemplateValue>((current, part) => {
|
||||
if (current && typeof current === "object" && !Array.isArray(current)) {
|
||||
return (current as PromptTemplateRecord)[part];
|
||||
}
|
||||
return undefined;
|
||||
}, variables);
|
||||
}
|
||||
|
||||
function stringifyPromptValue(value: PromptTemplateValue): string {
|
||||
if (value === null || value === undefined) {
|
||||
return "";
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((entry) => stringifyPromptValue(entry)).join("\n");
|
||||
}
|
||||
if (typeof value === "object") {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
function isTruthyPromptValue(value: PromptTemplateValue): boolean {
|
||||
if (value === null || value === undefined || value === false) {
|
||||
return false;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value.length > 0;
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
return value.trim().length > 0;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function trimTrailingSpaces(value: string): string {
|
||||
return value
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.replace(/[ \t]+$/g, ""))
|
||||
.join("\n");
|
||||
}
|
||||
Loading…
Reference in a new issue