repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/good-job/core.ts
RawFile outline
- JOB_VERSION line 3
- RECORD_VERSION line 4
- FAILURE_VERSION line 5
- ModelRef line 7
- provider line 8
- id line 9
- LearningSource line 12
- cwd line 13
- sessionPath line 14
- sessionId line 15
- sessionName line 16
- leafId line 17
- agentModel line 18
- GoodJobJob line 21
- version line 22
- id line 23
- createdAt line 24
- praise line 25
- source line 26
- analysisModel line 27
- Learning line 30
- achievement line 31
- evidence line 32
- successfulBehaviors line 33
- candidateRule line 34
- GoodJobRecord line 37
- version line 38
- id line 39
- createdAt line 40
- completedAt line 41
- praise line 42
- source line 43
- analysisModel line 44
- learning line 45
- usage line 46
- GoodJobFailure line 56
- version line 57
- job line 58
- failedAt line 59
- error line 60
- CONTROL_CHARACTERS line 63
- TRIGGER line 64
- MAX_ACHIEVEMENT_CHARS line 65
- MAX_ITEM_CHARS line 66
- MAX_RULE_CHARS line 67
- MAX_ITEMS line 68
- isGoodJobTrigger line 70
- cleanText line 74
- isRecord line 82
- cleanStringArray line 86
- jsonObject line 97
- parseLearning line 109
- responseText line 134
- text line 137
- type line 137
- analysisPrompt line 143
- lastAgentModel line 161
- boundedError line 175
import type { AssistantMessage } from "@earendil-works/pi-ai";
export const JOB_VERSION = 1 as const;
export const RECORD_VERSION = 1 as const;
export const FAILURE_VERSION = 1 as const;
export interface ModelRef {
provider: string;
id: string;
}
export interface LearningSource {
cwd: string;
sessionPath: string | null;
sessionId: string;
sessionName: string | null;
leafId: string | null;
agentModel: ModelRef | null;
}
export interface GoodJobJob {
version: typeof JOB_VERSION;
id: string;
createdAt: string;
praise: string;
source: LearningSource;
analysisModel: ModelRef | null;
}
export interface Learning {
achievement: string;
evidence: string[];
successfulBehaviors: string[];
candidateRule: string | null;
}
export interface GoodJobRecord {
version: typeof RECORD_VERSION;
id: string;
createdAt: string;
completedAt: string;
praise: string;
source: LearningSource;
analysisModel: ModelRef;
learning: Learning;
usage: {
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
totalTokens: number;
cost: number;
};
}
export interface GoodJobFailure {
version: typeof FAILURE_VERSION;
job: GoodJobJob;
failedAt: string;
error: string;
}
const CONTROL_CHARACTERS = /[\x00-\x1F\x7F-\x9F]/g;
const TRIGGER = /^(?:gj|good\s+job)[.!?]*$/i;
const MAX_ACHIEVEMENT_CHARS = 180;
const MAX_ITEM_CHARS = 500;
const MAX_RULE_CHARS = 700;
const MAX_ITEMS = 8;
export function isGoodJobTrigger(text: string): boolean {
return TRIGGER.test(text.trim());
}
export function cleanText(text: string, maximum: number): string {
const cleaned = text
.replace(CONTROL_CHARACTERS, " ")
.replace(/\s+/g, " ")
.trim();
return Array.from(cleaned).slice(0, maximum).join("");
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function cleanStringArray(value: unknown): string[] | undefined {
if (!Array.isArray(value)) return undefined;
const strings = value
.slice(0, MAX_ITEMS)
.map((item) =>
typeof item === "string" ? cleanText(item, MAX_ITEM_CHARS) : "",
)
.filter(Boolean);
return strings.length > 0 ? strings : undefined;
}
function jsonObject(text: string): unknown {
const trimmed = text.trim();
const unfenced = trimmed
.replace(/^```(?:json)?\s*/i, "")
.replace(/\s*```$/, "")
.trim();
const start = unfenced.indexOf("{");
const end = unfenced.lastIndexOf("}");
if (start < 0 || end < start) throw new Error("analysis did not return JSON");
return JSON.parse(unfenced.slice(start, end + 1));
}
export function parseLearning(text: string): Learning {
const value = jsonObject(text);
if (!isRecord(value)) throw new Error("analysis returned a non-object");
const achievement =
typeof value.achievement === "string"
? cleanText(value.achievement, MAX_ACHIEVEMENT_CHARS)
: "";
const evidence = cleanStringArray(value.evidence);
const successfulBehaviors = cleanStringArray(
value.successful_behaviors ?? value.successfulBehaviors,
);
const candidateValue = value.candidate_rule ?? value.candidateRule;
const candidateRule =
candidateValue === null
? null
: typeof candidateValue === "string"
? cleanText(candidateValue, MAX_RULE_CHARS)
: undefined;
if (!achievement || !evidence || !successfulBehaviors)
throw new Error("analysis JSON is missing required learning fields");
if (candidateRule === undefined)
throw new Error("analysis JSON is missing candidate_rule");
return { achievement, evidence, successfulBehaviors, candidateRule };
}
export function responseText(response: AssistantMessage): string {
return response.content
.filter(
(part): part is { type: "text"; text: string } => part.type === "text",
)
.map((part) => part.text)
.join("\n");
}
export function analysisPrompt(praise: string): string {
return `The user just praised the preceding coding-agent work with: ${JSON.stringify(praise)}
Analyze what concretely went well across the full conversation above.
Infer causes only when supported by the transcript.
Focus on reusable agent behavior, not compliments or personality.
Do not reproduce credentials, secrets, long source excerpts, or private data.
Return exactly one JSON object with this shape:
{
"achievement": "one concrete summary, at most 180 characters",
"evidence": ["observable result or user-visible outcome"],
"successful_behaviors": ["specific agent decision or behavior that contributed"],
"candidate_rule": "concise reusable instruction for future agents, or null when evidence is insufficient"
}
Use 1-8 concise items per array.
No markdown fences or commentary.`;
}
export function lastAgentModel(messages: readonly unknown[]): ModelRef | null {
for (let index = messages.length - 1; index >= 0; index--) {
const message = messages[index];
if (!isRecord(message) || message.role !== "assistant") continue;
if (
typeof message.provider !== "string" ||
typeof message.model !== "string"
)
continue;
return { provider: message.provider, id: message.model };
}
return null;
}
export function boundedError(error: unknown): string {
const message = error instanceof Error ? error.message : String(error);
return cleanText(message, 300) || "unknown error";
}