1 1 import { spawn }
from "node:child_process";
2 2 import { accessSync, constants, existsSync }
from "node:fs";
3 -import { basename, delimiter, join }
from "node:path";
4 -import type { Message, ThinkingLevel }
from "@earendil-works/pi-ai";
3 +import { basename, delimiter, dirname, join }
from "node:path";
8 +}
from "@earendil-works/pi-ai";
6 10 buildSessionContext,
13 + DefaultResourceLoader,
9 16 type ExtensionContext,
12 23 }
from "@earendil-works/pi-coding-agent";
19 30 type GoodJobRecord,
33 + LearningSubmissionSchema,
26 38 } from
"./core.js";
46 58 const SPINNER
= [
"◐",
"◓",
"◑",
"◒"]
as const;
47 59 const MAX_TOKENS
= 1_200;
49 -type ContextSnapshot = Message[];
50 61 type BackgroundContext = {
51 62 modelRegistry
: ExtensionContext[
"modelRegistry"];
52 63 ui
?: ExtensionContext[
"ui"];
157 -function completionContext(
158 - conversation
: readonly Message[],
159 - kind
: FeedbackKind,
166 - content: [{ type:
"text", text:
analysisPrompt(kind, feedback) }],
167 - timestamp:
Date.
now(),
172 -function contextFromSession(job
: GoodJobJob)
: ContextSnapshot {
173 - if (
!job.
source.sessionPath)
174 - throw new Error(
"source session was ephemeral and is no longer available");
175 - const manager
= SessionManager.
open(job.
source.sessionPath);
176 - if (job.
source.leafId
&& !manager.
getEntry(job.
source.leafId))
177 - throw new Error(
`source session leaf ${job.source.leafId} is missing`);
178 - const context
= buildSessionContext(
179 - manager.
getEntries(),
182 - return convertToLlm(context);
185 168 function findExecutable(
187 170 env
: NodeJS.
ProcessEnv,
198 181 return undefined;
184 +function copyRegisteredProviders(
185 + registry
: ExtensionContext[
"modelRegistry"],
186 + runtime
: ModelRuntime,
188 + for (
const providerId
of registry.
getRegisteredProviderIds()) {
189 + const native
= registry.
getRegisteredNativeProvider(providerId);
191 + runtime.
registerNativeProvider(native);
194 + const config
= registry.
getRegisteredProviderConfig(providerId);
195 + if (config) runtime.
registerProvider(providerId, config);
201 199 export function openerFor(
202 200 platform
= process.
platform,
203 201 env
: NodeJS.
ProcessEnv = process.
env,
252 250 private
activeController: AbortController
| undefined;
253 251 private
pumpPromise:
Promise<void> | undefined;
254 252 private pumpRequested
= false;
255 - private readonly snapshots
= new Map<
string,
ContextSnapshot>();
253 + private readonly snapshots
= new Map<
string,
SessionEntry[]>();
256 254 private
spinnerTimer: ReturnType
<typeof setInterval
> | undefined;
257 255 private spinnerStartedAt
= 0;
258 256 private spinnerCount
= 0;
336 334 ctx.sessionManager.
getEntries(),
337 335 ctx.sessionManager.
getLeafId(),
339 - const snapshot
= convertToLlm(sessionContext.messages);
340 337 const job
: GoodJobJob = {
341 338 version: JOB_VERSION,
342 339 id:
feedbackId(kind),
349 346 await ensureLayout(this.paths);
350 347 await enqueueJob(job, this.paths);
351 - this.snapshots.
set(job.
id, snapshot);
348 + this.snapshots.
set(
350 + structuredClone(ctx.sessionManager.
getEntries()),
352 352 background.ui?.
notify(
`${job.id} queued`,
"info");
353 353 void this.
pump(background, this.generation, job.
id);
471 471 `analysis model ${job.analysisModel.provider}/${job.analysisModel.id} is unavailable`,
473 - const snapshot
= this.snapshots.
get(job.
id)
?? contextFromSession(job);
474 - const response
= await ctx.modelRegistry.
complete(
473 + const { learning, response }
= await this.
runChildAnalysis(
478 - "Extract evidence-backed, reusable lessons from explicit user feedback about coding-agent work.",
479 - messages:
completionContext(snapshot, job.kind, job.feedback),
482 - maxTokens: MAX_TOKENS,
483 - reasoning: this.settings.thinkingLevel,
484 - cacheRetention:
"none",
486 - signal: controller.signal,
489 479 if (controller.signal.aborted
|| generation
!== this.generation)
return;
490 - if (response.stopReason
!== "stop")
492 - response.errorMessage
|| 493 - `analysis stopped with ${response.stopReason}`,
495 - const learning
= parseLearning(
responseText(response));
496 480 const record
: GoodJobRecord = {
497 481 version: RECORD_VERSION,
518 + private async
runChildAnalysis(
521 + ctx: BackgroundContext,
522 + signal: AbortSignal,
523 + ):
Promise<{
learning: Learning;
response: AssistantMessage }
> {
524 + const sourcePath
= job.
source.sessionPath;
525 + let manager: SessionManager;
527 + manager
= SessionManager.
forkFrom(
530 + dirname(sourcePath),
531 + { parentSession: sourcePath },
534 + const snapshot
= this.snapshots.
get(job.
id);
537 + "source session was ephemeral and its snapshot is unavailable",
539 + const header:
FileEntry = {
542 + id: job.
source.sessionId,
543 + timestamp: job.createdAt,
544 + cwd: job.
source.cwd,
546 + manager
= SessionManager.
inMemory(job.
source.cwd,
undefined, [
551 + if (job.
source.leafId) {
552 + if (!manager.getEntry(job.source.leafId))
553 + throw new
Error(
`source session leaf ${job.source.leafId} is missing`);
554 + manager.branch(job.source.leafId);
556 + manager.
appendSessionInfo(
`good-job · ${job.id}`);
558 + const agentDir
= getAgentDir();
559 + const childRuntime
= await ModelRuntime.
create({
560 + authPath:
join(agentDir,
"auth.json"),
561 + modelsPath:
join(agentDir,
"models.json"),
562 + refreshOnCreate:
false,
565 + copyRegisteredProviders(ctx.modelRegistry, childRuntime);
567 + const settingsManager
= SettingsManager.
create(job.
source.cwd, agentDir);
568 + const resourceLoader
= new DefaultResourceLoader({
569 + cwd: job.
source.cwd,
572 + eventBus:
createEventBus(),
573 + noExtensions:
true,
575 + noPromptTemplates:
true,
577 + noContextFiles:
true,
579 + await resourceLoader.
reload();
580 + signal.
throwIfAborted();
582 + const childModel
= {
585 + model.maxTokens
> 0 586 + ? Math.
min(model.maxTokens, MAX_TOKENS)
589 + let learning: Learning
| undefined;
590 + let duplicateSubmission
= false;
591 + const submitLearningTool
= defineTool
< 592 + typeof LearningSubmissionSchema,
595 + name:
"submit_learning",
596 + label:
"Submit Learning",
597 + description:
"Submit the final structured learning and finish analysis.",
598 + parameters: LearningSubmissionSchema,
599 + constrainedSampling: { type:
"json_schema", strict:
"prefer" },
600 + async execute(_toolCallId, params) {
602 + duplicateSubmission
= true;
603 + throw new Error(
"submit_learning may be called exactly once");
605 + const parsed
= parseLearning(
JSON.
stringify(params));
608 + content: [{ type:
"text", text:
"Learning submitted." }],
615 + | Awaited<
ReturnType<
typeof createAgentSession>>[
"session"]
618 + const created
= await createAgentSession({
619 + cwd: job.
source.cwd,
622 + thinkingLevel: this.settings.thinkingLevel,
623 + modelRuntime: childRuntime,
626 + sessionManager: manager,
627 + tools: [submitLearningTool.
name],
628 + customTools: [submitLearningTool],
630 + child
= created.session;
631 + const abortChild = ()
=> void child?.
abort();
632 + signal.
addEventListener(
"abort", abortChild, { once:
true });
634 + await child.
prompt(
analysisPrompt(job.kind, job.feedback), {
635 + expandPromptTemplates:
false,
636 + source:
"extension",
639 + signal.
removeEventListener(
"abort", abortChild);
641 + signal.
throwIfAborted();
642 + const finalAssistant
= [
...child.messages]
645 + (message)
: message
is AssistantMessage => 646 + message.role
=== "assistant",
648 + if (
!finalAssistant)
650 + "child analysis finished without an assistant response",
652 + if (duplicateSubmission)
653 + throw new Error(
"analysis called submit_learning more than once");
656 + finalAssistant.errorMessage
|| 657 + "analysis finished without calling submit_learning",
659 + return { learning, response: finalAssistant };
662 + if (
!child.isIdle)
await child.
abort();
534 668 private
startSpinner(ctx: BackgroundContext, count: number):
void {
535 669 const { ui }
= ctx;
536 670 this.
stopSpinner(ui);