14 14 import { Type }
from "typebox";
16 16 type GoalStatus = "active" | "paused" | "complete" | "blocked";
17 +type GoalVerdictLabel = "done" | "blocked" | "continue" | "error";
17 18 type ProbeMode = "direct" | "microtask" | "timeout";
19 20 type GoalSettings = {
21 22 judgeModel
?: string;
24 + tokenBudget
?: number;
25 + timeBudgetSeconds
?: number;
28 +type BlockedStreak = {
32 40 lastReason
?: string;
41 + lastVerdict
?: GoalVerdictLabel;
42 + blockedStreak
?: BlockedStreak;
43 + judgeFailures
?: number;
44 + tokenBudget
?: number;
45 + tokensUsed
?: number;
46 + timeBudgetSeconds
?: number;
47 + timeUsedSeconds
?: number;
33 48 sessionId
?: string;
59 +type TurnEvidence = {
60 + assistantText
: string;
61 + stopReason
?: string;
62 + errorMessage
?: string;
64 + toolCalls
: Array<{ id
?: string; name
: string; args
: unknown }>;
65 + toolResults
: Array<{
66 + toolCallId
?: string;
73 +type ContinuationState = {
44 80 type ProbeState = {
56 92 const GOAL_STATE_ENTRY
= "goal-state";
57 93 const GOAL_JUDGE_ENTRY
= "goal-judge";
94 +const GOAL_EVENT_ENTRY
= "goal-event";
95 +const GOAL_DEBUG_ENTRY
= "goal-debug";
96 +const GOAL_COMPACTION_ENTRY
= "goal-compaction";
97 +const GOAL_CONTINUATION_ENTRY
= "goal-continuation";
58 98 const PROBE_ENTRY
= "goal-probe";
59 99 const PROBE_MESSAGE
= "GOAL_PROBE_CONTINUATION";
60 100 const DEFAULT_MAX_TURNS
= 20;
63 103 const WIDGET_KEY
= "goal";
64 104 const FOOTER_KEY
= Symbol.
for(
"@bugabinga/pi-ext-footer");
65 105 const FOOTER_SEGMENT
= { id:
"goal", zone:
"llm", order:
30 }
as const;
66 -const CONTINUATION_RETRY_MS
= 250;
67 -const CONTINUATION_MAX_ATTEMPTS
= 20;
68 106 const JUDGE_ATTEMPTS
= 2;
107 +const JUDGE_PARSE_FAILURE_LIMIT
= 3;
108 +const BLOCKED_STREAK_LIMIT
= 3;
69 109 const ANSI_RE
= /\x1b\[[0-?]*[ -/]*[@-~]/g;
70 110 const CONTROL_RE
= /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g;
71 111 const GOAL_WIDGET_LABEL_WIDTH
= 11;
88 128 {
value:
"clear-criteria",
description:
"Clear all criteria" },
91 -type GoalUiMode = "normal" | "judging";
131 +type GoalUiMode = "normal" | "judging" | "queued";
93 133 type SettingsAPI = ExtensionAPI & {
94 134 settingsManager
?: {
getSettings()
: Record<
string,
unknown>
| undefined };
109 149 return Math.
max(min,
Math.
min(max,
Math.
trunc(n)));
152 +function parseBudgetCount(value
: unknown)
: number | undefined {
153 + if (
typeof value
=== "number" && Number.
isFinite(value)
&& value
> 0)
154 + return Math.
trunc(value);
155 + if (
typeof value
!== "string")
return undefined;
156 + const match
= value
159 + .
match(
/^(\d+(?:\.\d+)?)([kmg])?$/);
160 + if (
!match)
return undefined;
169 + const parsed
= Number(match[
1])
* multiplier;
170 + return Number.
isFinite(parsed)
&& parsed
> 0 ? Math.
trunc(parsed)
: undefined;
173 +function parseDurationSeconds(value
: unknown)
: number | undefined {
174 + if (
typeof value
=== "number" && Number.
isFinite(value)
&& value
> 0)
175 + return Math.
trunc(value);
176 + if (
typeof value
!== "string")
return undefined;
177 + const match
= value
180 + .
match(
/^(\d+(?:\.\d+)?)(s|m|h)?$/);
181 + if (
!match)
return undefined;
182 + const multiplier
= match[
2]
=== "h" ? 3600 : match[
2]
=== "m" ? 60 : 1;
183 + const parsed
= Number(match[
1])
* multiplier;
184 + return Number.
isFinite(parsed)
&& parsed
> 0 ? Math.
trunc(parsed)
: undefined;
112 187 function loadSettings(pi
: ExtensionAPI)
: GoalSettings {
113 188 const all
= (pi
as SettingsAPI).settingsManager?.
getSettings?.();
114 189 const raw
= isRecord(all?.goal)
? all.goal
: {};
190 + const settings
: GoalSettings = {
116 191 maxTurns:
clampInt(raw.maxTurns, DEFAULT_MAX_TURNS,
1,
10_000),
118 193 typeof raw.judgeModel
=== "string" && raw.judgeModel.
trim()
121 196 tailBytes:
clampInt(raw.tailBytes, DEFAULT_TAIL_BYTES,
512,
65_536),
198 + const tokenBudget
= parseBudgetCount(raw.tokenBudget);
199 + const timeBudgetSeconds
= parseDurationSeconds(
200 + raw.timeBudgetSeconds
?? raw.timeBudget,
202 + if (tokenBudget) settings.tokenBudget
= tokenBudget;
203 + if (timeBudgetSeconds) settings.timeBudgetSeconds
= timeBudgetSeconds;
125 207 function textFromContent(content
: unknown)
: string {
221 +function escapeXmlText(text
: string)
: string {
223 + .
replace(
/&/g,
"&")
224 + .
replace(
/</g,
"<")
225 + .
replace(
/>/g,
">");
228 +function unescapeXmlText(text
: string)
: string {
230 + .
replace(
/</g,
"<")
231 + .
replace(
/>/g,
">")
232 + .
replace(
/&/g,
"&");
139 235 function extractStandingGoalObjective(prompt
: string)
: string | undefined {
140 236 if (
!/standing goal/i.
test(prompt))
return undefined;
141 - const match
= prompt.
match(
/<objective>\s*([\s\S]*?)\s*<\/objective>/i);
142 - const objective
= match?.[
1]?.
trim();
239 + /<untrusted_objective>\s*([\s\S]*?)\s*<\/untrusted_objective>/i,
240 + )
?? prompt.
match(
/<objective>\s*([\s\S]*?)\s*<\/objective>/i);
241 + const objective
= match?.[
1]
? unescapeXmlText(match[
1]).
trim()
: undefined;
143 242 return objective
|| undefined;
162 261 isGoalStatus(value.
status)
&& 163 262 Number.
isInteger(value.turnsUsed)
&& 164 263 Number.
isInteger(value.maxTurns)
&& 264 + (value.lastVerdict
=== undefined || 265 + value.lastVerdict
=== "done" || 266 + value.lastVerdict
=== "blocked" || 267 + value.lastVerdict
=== "continue" || 268 + value.lastVerdict
=== "error")
&& 269 + (value.blockedStreak
=== undefined || 270 + (
isRecord(value.blockedStreak)
&& 271 + typeof value.blockedStreak.reasonHash
=== "string" && 272 + Number.
isInteger(value.blockedStreak.count)))
&& 273 + (value.judgeFailures
=== undefined || 274 + Number.
isInteger(value.judgeFailures))
&& 275 + (value.tokenBudget
=== undefined || Number.
isInteger(value.tokenBudget))
&& 276 + (value.tokensUsed
=== undefined || Number.
isInteger(value.tokensUsed))
&& 277 + (value.timeBudgetSeconds
=== undefined || 278 + Number.
isInteger(value.timeBudgetSeconds))
&& 279 + (value.timeUsedSeconds
=== undefined || 280 + Number.
isInteger(value.timeUsedSeconds))
&& 165 281 (value.sessionId
=== undefined || typeof value.sessionId
=== "string")
&& 166 282 typeof value.createdAt
=== "number" && 167 283 typeof value.updatedAt
=== "number" 217 333 return oneLine.
length <= max
? oneLine
: `${oneLine.slice(0, max - 1)}…`;
336 +function elapsedSeconds(state
: GoalState)
: number {
337 + return state.timeUsedSeconds
?? 0;
340 +function currentElapsedSeconds(state
: GoalState)
: number {
342 + elapsedSeconds(state),
343 + Math.
floor((
Date.
now()
- state.createdAt)
/ 1000),
347 +function durationText(seconds
: number)
: string {
348 + if (seconds
< 60)
return `${seconds}s`;
349 + if (seconds
< 3600)
return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
350 + const h
= Math.
floor(seconds
/ 3600);
351 + const m
= Math.
floor((seconds
% 3600)
/ 60);
352 + return `${h}h${m}m`;
355 +function compactCount(value
: number)
: string {
356 + if (value
>= 1_000_000)
return `${Math.round(value / 100_000) / 10}m`;
357 + if (value
>= 1_000)
return `${Math.round(value / 100) / 10}k`;
358 + return String(value);
361 +function verdictGlyph(label
: GoalVerdictLabel | undefined)
: string {
362 + if (label
=== "done")
return "✓";
363 + if (label
=== "blocked")
return "⊘";
364 + if (label
=== "error")
return "!";
368 +function criteriaPreview(state
: GoalState)
: string {
369 + if (state.criteria.
length === 0)
return "";
371 + state.criteria.
length > 1 ? ` +${state.criteria.length - 1}` : "";
372 + return `${shortText(state.criteria[0], 36)}${more}`;
375 +function budgetText(state
: GoalState)
: string {
376 + const parts
: string[]
= [];
377 + if (state.tokenBudget)
379 + `${compactCount(state.tokensUsed ?? 0)}/${compactCount(state.tokenBudget)} tok`,
381 + if (state.timeBudgetSeconds)
383 + `${durationText(elapsedSeconds(state))}/${durationText(state.timeBudgetSeconds)}`,
385 + else parts.
push(
durationText(
elapsedSeconds(state)));
386 + return parts.
join(
" · ");
220 389 function sanitizeGoalText(text
: string, max
= 160)
: string {
221 390 return shortText(
222 391 text.
replace(ANSI_RE,
"").
replace(CONTROL_RE,
" ").
replace(
/\s+/g,
" "),
240 409 return verdict.reason.
startsWith(
"judge failed:");
412 +function isJudgeParseFailure(verdict
: JudgeVerdict)
: boolean {
414 + verdict.reason.
includes(
"judge returned")
|| 415 + verdict.reason.
includes(
"JSON")
|| 416 + verdict.reason.
includes(
"Unexpected")
420 +function reasonHash(reason
: string)
: string {
422 + for (
const char
of reason.
toLowerCase().
replace(
/\s+/g,
" ").
trim())
423 + hash
= ((hash
<< 5)
+ hash)
^ char.
charCodeAt(
0);
424 + return (hash
>>> 0).
toString(
36);
427 +function nextBlockedStreak(state
: GoalState, reason
: string)
: BlockedStreak {
428 + const hash
= reasonHash(reason);
429 + return state.blockedStreak?.reasonHash
=== hash
430 + ? { reasonHash: hash, count: state.blockedStreak.count
+ 1 }
431 + : { reasonHash: hash, count:
1 };
434 +function usageTokenDelta(usage
: unknown)
: number | undefined {
435 + if (
!isRecord(usage))
return undefined;
436 + const input
= Number(usage.
input ?? 0);
437 + const output
= Number(usage.output
?? 0);
438 + const cacheRead
= Number(usage.cacheRead
?? 0);
439 + if (
![input, output, cacheRead].
every(
Number.isFinite))
return undefined;
440 + return Math.
max(
0, input
- cacheRead)
+ Math.
max(
0, output);
443 +function tokenDelta(evidence
: TurnEvidence | undefined)
: number {
444 + return Math.
max(
0, evidence?.tokens
?? 0);
447 +function goalVerdictLabel(verdict
: JudgeVerdict)
: GoalVerdictLabel {
448 + if (
isJudgeFailure(verdict))
return "error";
449 + return judgeVerdictLabel(verdict);
452 +function appendGoalEvent(
455 + state
: GoalState | undefined,
456 + data
: Record<
string,
unknown>
= {},
461 + status: state?.
status,
462 + timestamp:
Date.
now(),
465 + pi.
appendEntry(GOAL_EVENT_ENTRY, payload);
469 + customType: GOAL_EVENT_ENTRY,
470 + content:
`goal ${event}${state?.lastReason ? ` · ${shortText(state.lastReason)}` : ""}`,
474 + { triggerTurn:
false },
477 + if (
!isStaleContextError(error))
throw error;
484 + data
: Record<
string,
unknown>
= {},
486 + if (
process.
env.PI_GOAL_LOG
!== "1")
return;
487 + pi.
appendEntry(GOAL_DEBUG_ENTRY, { event,
...data, timestamp:
Date.
now() });
243 490 function judgeRunningText(state
: GoalState)
: string {
245 492 state.criteria.
length === 0 ? "" : ` · ${state.criteria.length} criteria`;
274 521 return `goal judging ${state.turnsUsed + 1}/${state.maxTurns}${criteria}`;
524 +function compactStatusLine(
526 + currentSessionId
?: string,
529 + state.sessionId
&& currentSessionId
&& state.sessionId
!== currentSessionId
530 + ? " · other session" 532 + const criterion
= criteriaPreview(state);
533 + const criterionText
= criterion
? `\ncriterion: ${criterion}` : "";
534 + const reason
= state.lastReason
535 + ? `\n${verdictGlyph(state.lastVerdict)} ${judgeDisplayReason(state.lastReason)}` 537 + return `${goalPhaseText(state, "normal")}${owner} · ${budgetText(state)}\n${shortText(state.objective, 160)}${criterionText}${reason}`;
540 +function notifyGoalStatus(
541 + ctx
: ExtensionContext,
542 + state
: GoalState | undefined,
545 + state
? compactStatusLine(state,
currentSessionId(ctx))
: "No active goal.",
546 + state
? "info" : "warning",
277 550 function hasFooter()
: boolean {
278 551 const footer
= (globalThis
as any)[FOOTER_KEY];
279 552 return footer?.loaded
=== true && (footer.
version ?? 0)
>= 1;
316 589 return padVisible(
truncateToWidth(text, width,
"…"), width);
592 +function wrapVisibleWords(text
: string, width
: number)
: string[] {
593 + if (width
<= 0)
return [
""];
594 + const chunks
= text.
replace(
/\s+/g,
" ").
trim().
split(
" ").
filter(
Boolean);
595 + if (chunks.
length === 0)
return [
""];
596 + const lines
: string[]
= [];
598 + const pushWord = (word
: string)
=> {
599 + if (
visibleWidth(word)
<= width) {
600 + if (
!line) line
= word;
601 + else if (
visibleWidth(
`${line} ${word}`)
<= width)
602 + line
= `${line} ${word}`;
614 + while (
visibleWidth(rest)
> width) {
615 + const part
= truncateToWidth(rest, width,
"");
618 + rest
= rest.
slice(part.
length);
622 + for (
const word
of chunks)
pushWord(word);
623 + if (line) lines.
push(line);
624 + return lines.
length === 0 ? [
""]
: lines;
319 627 function goalWidgetRow(
322 630 innerWidth
: number,
324 632 const labelText
= fitVisible(label, GOAL_WIDGET_LABEL_WIDTH);
325 633 const valueWidth
= Math.
max(
0, innerWidth
- GOAL_WIDGET_LABEL_WIDTH);
326 - return `│ ${labelText}${fitVisible(value, valueWidth)} │`;
634 + return wrapVisibleWords(value, valueWidth).
map((line, index)
=> {
636 + index
=== 0 ? labelText
: fitVisible(
"", GOAL_WIDGET_LABEL_WIDTH);
637 + return `│ ${shownLabel}${fitVisible(line, valueWidth)} │`;
329 641 function insetWidgetLine(line
: string, width
: number)
: string {
330 642 if (width
<= 0)
return "";
331 - return ` ${truncateToWidth(line, Math.max(0, width - GOAL_WIDGET_LEFT_PADDING), "…")}`;
643 + return ` ${fitVisible(line, Math.max(0, width - GOAL_WIDGET_LEFT_PADDING))}`;
334 646 function goalJudgeMessageLine(content
: string)
: string {
355 667 const top
= `╭${title}${"─".repeat(Math.max(0, boxWidth - visibleWidth(title) - 2))}╮`;
360 - sanitizeGoalText(state.objective,
120),
672 + sanitizeGoalText(state.objective,
4000),
364 676 if (mode
=== "judging") {
368 680 `${state.turnsUsed + 1}/${state.maxTurns}`,
372 684 }
else if (
showsTurnBudget(state)) {
376 - `${state.turnsUsed}/${state.maxTurns} ${goalBar(state)} ${goalProgress(state)}%`,
688 + `${state.turnsUsed}/${state.maxTurns} ${goalBar(state)} ${goalProgress(state)}% · ${budgetText(state)}`,
693 + const criterion
= criteriaPreview(state);
695 + lines.
push(
...goalWidgetRow(
"criterion", criterion, innerWidth));
381 696 if (state.lastReason)
383 - goalWidgetRow(
"judge",
judgeDisplayReason(state.lastReason), innerWidth),
700 + `${verdictGlyph(state.lastVerdict)} ${judgeDisplayReason(state.lastReason)}`,
385 704 lines.
push(
`╰${"─".repeat(boxWidth - 2)}╯`);
389 708 function goalPhaseText(state
: GoalState, mode
: GoalUiMode)
: string {
390 709 if (mode
=== "judging")
391 710 return `judging ${state.turnsUsed + 1}/${state.maxTurns}`;
711 + if (mode
=== "queued")
712 + return `queued continuation ${state.turnsUsed + 1}/${state.maxTurns}`;
392 713 if (
!showsTurnBudget(state))
return state.
status;
393 714 return `${state.status} ${state.turnsUsed}/${state.maxTurns}`;
439 760 ctx.ui.
setStatus(
441 - mode
=== "judging" && state
? judgeStatusText(state)
: statusText(state),
762 + state
&& (mode
=== "judging" || mode
=== "queued")
763 + ? `goal ${goalPhaseText(state, mode)}` 764 + : statusText(state),
785 +function updateHeartbeat(
786 + ctx
: ExtensionContext,
787 + state
: GoalState | undefined,
790 + const active
= state?.
status === "active";
791 + const ui
= ctx.ui
as ExtensionContext[
"ui"]
& {
792 + setWorkingIndicator
?: ExtensionContext[
"ui"][
"setWorkingIndicator"];
795 + ctx.ui.
setWorkingMessage();
796 + ui.
setWorkingIndicator?.();
801 + ? `goal judging ${state.turnsUsed + 1}/${state.maxTurns}` 802 + : mode
=== "queued" 803 + ? `goal queued ${state.turnsUsed + 1}/${state.maxTurns}` 804 + : `goal active ${state.turnsUsed}/${state.maxTurns}`;
805 + ctx.ui.
setWorkingMessage(phase);
806 + ui.
setWorkingIndicator?.({ frames: [
"◐",
"◓",
"◑",
"◒"], intervalMs:
180 });
462 809 function updateUI(
463 810 pi
: ExtensionAPI,
464 811 ctx
: ExtensionContext,
468 815 if (
!ctx.hasUI)
return;
469 816 updateWidget(ctx, state, mode);
470 817 updateFooter(pi, ctx, state, mode);
818 + updateHeartbeat(ctx, state, mode);
473 821 function canUseUpdateGoal(state
: GoalState | undefined)
: state
is GoalState {
544 892 return matches.
length === 0 ? null : matches;
895 +function criteriaBlock(state
: GoalState)
: string {
896 + return state.criteria.
length === 0 899 + .
map((criterion, index)
=> `${index + 1}. ${escapeXmlText(criterion)}`)
547 903 function activeGoalPrompt(state
: GoalState)
: string {
549 - state.criteria.
length === 0 552 - .
map((criterion, index)
=> `${index + 1}. ${criterion}`)
554 - return `\n\nActive /goal:\n<objective>\n${state.objective}\n</objective>\n\nCriteria:\n${criteria}\n\nKeep working toward this standing goal. Do not redefine success smaller. Before claiming completion, verify current files, commands, tests, or deliverables. Use update_goal only after judge review and only when complete or genuinely blocked.`;
904 + return `\n\nActive /goal:\n<untrusted_objective>\n${escapeXmlText(state.objective)}\n</untrusted_objective>\n\nCriteria:\n${criteriaBlock(state)}\n\nKeep working toward this standing goal. Do not redefine success smaller. Before claiming completion, verify current files, commands, tests, or deliverables. Use update_goal only after judge review and only when complete or genuinely blocked.`;
557 907 function continuationPrompt(state
: GoalState)
: string {
559 - state.criteria.
length === 0 562 - .
map((criterion, index)
=> `${index + 1}. ${criterion}`)
564 - return `Continue working toward this standing goal.\n\n<objective>\n${state.objective}\n</objective>\n\nCriteria:\n${criteria}\n\nDo not redefine success smaller. Inspect current state before claiming completion. If incomplete, make concrete progress. If complete or blocked after judge review, call update_goal.`;
908 + return `Continue working toward this standing goal.\n\n<untrusted_objective>\n${escapeXmlText(state.objective)}\n</untrusted_objective>\n\nCriteria:\n${criteriaBlock(state)}\n\nDo not redefine success smaller. Inspect current state before claiming completion. If incomplete, make concrete progress. Call update_goal with status "complete" only after verifying success. Call update_goal with status "blocked" only if truly at an impasse after at least three consecutive goal turns with the same blocking condition.`;
567 911 function kickoffPrompt(state
: GoalState)
: string {
568 - return `Start working toward this standing goal.\n\n<objective>\n${state.objective}\n</objective>\n\nDo not stop just because one turn ends. Keep making concrete progress until the goal is complete, blocked, paused, cleared, or the turn budget is exhausted.`;
912 + return `Start working toward this standing goal.\n\n<untrusted_objective>\n${escapeXmlText(state.objective)}\n</untrusted_objective>\n\nDo not stop just because one turn ends. Keep making concrete progress until the goal is complete, blocked, paused, cleared, or the turn budget is exhausted.`;
571 915 function latestAssistantTail(ctx
: ExtensionContext, tailBytes
: number)
: string {
931 +function toolCallsFromContent(content
: unknown)
: TurnEvidence[
"toolCalls"] {
932 + if (
!Array.
isArray(content))
return [];
935 + (part)
: part
is Record<
string,
unknown>
=> 937 + part.
type === "toolCall" && 938 + typeof part.
name === "string",
941 + id:
typeof part.
id === "string" ? part.
id : undefined,
942 + name: part.
name as string,
943 + args: part.
arguments,
947 +function buildTurnEvidence(event
: {
948 + message
: Record<
string,
unknown>;
949 + toolResults
?: Array<
Record<
string,
unknown>>;
951 + const message
= event.message;
952 + const toolResults
= event.toolResults
?? [];
954 + assistantText:
textFromContent(message.
content).
trim(),
956 + typeof message.stopReason
=== "string" ? message.stopReason
: undefined,
958 + typeof message.errorMessage
=== "string" 959 + ? message.errorMessage
961 + tokens:
usageTokenDelta(message.usage),
962 + toolCalls:
toolCallsFromContent(message.
content),
963 + toolResults: toolResults.
map((result)
=> ({
965 + typeof result.toolCallId
=== "string" ? result.toolCallId
: undefined,
967 + typeof result.toolName
=== "string" ? result.toolName
: "unknown",
968 + isError: result.isError
=== true,
969 + text:
textFromContent(result.
content),
974 +function mergeTurnEvidence(
975 + previous
: TurnEvidence | undefined,
976 + current
: TurnEvidence,
979 + assistantText: current.assistantText
|| previous?.assistantText
|| "",
980 + stopReason: current.stopReason
?? previous?.stopReason,
981 + errorMessage: current.errorMessage
?? previous?.errorMessage,
982 + tokens: (previous?.tokens
?? 0)
+ (current.tokens
?? 0),
983 + toolCalls: [
...(previous?.toolCalls
?? []),
...current.toolCalls],
984 + toolResults: [
...(previous?.toolResults
?? []),
...current.toolResults],
988 +function tailText(text
: string, tailBytes
: number)
: string {
989 + return Buffer.
from(text).
subarray(
-tailBytes).
toString();
587 992 function parseModelRef(ref
: string)
: { provider
: string; model
: string } {
588 993 const i
= ref.
indexOf(
"/");
589 994 if (i
<= 0 || i
=== ref.
length - 1)
603 -function parseJudge(raw
: string)
: JudgeVerdict {
604 - const trimmed
= raw.
trim();
1008 +function parseLooseBoolean(value
: unknown)
: boolean {
1009 + if (value
=== true)
return true;
1010 + if (value
=== false)
return false;
1011 + if (
typeof value
=== "string")
return value.
trim().
toLowerCase()
=== "true";
1015 +function extractJsonObject(raw
: string)
: string {
1016 + const trimmed
= raw
1018 + .
replace(
/^```(?:json)?\s*/i,
"")
1019 + .
replace(
/\s*```$/i,
"")
605 1021 if (
!trimmed)
throw new Error(
"judge returned empty response");
606 - const json
= trimmed.
match(
/\{[\s\S]*\}/)?.[
0]
?? trimmed;
607 - const parsed
= JSON.
parse(json);
1022 + const start
= trimmed.
indexOf(
"{");
1023 + const end
= trimmed.
lastIndexOf(
"}");
1024 + if (start
=== -1 || end
< start)
return trimmed;
1025 + return trimmed.
slice(start, end
+ 1);
1028 +function parseJudge(raw
: string)
: JudgeVerdict {
1029 + const parsed
= JSON.
parse(
extractJsonObject(raw));
608 1030 if (
!isRecord(parsed))
throw new Error(
"judge returned non-object JSON");
610 - done: parsed.done
=== true,
611 - blocked: parsed.blocked
=== true,
1032 + done:
parseLooseBoolean(parsed.done),
1033 + blocked:
parseLooseBoolean(parsed.blocked),
613 1035 typeof parsed.reason
=== "string" && parsed.reason.
trim()
614 1036 ? parsed.reason.
trim()
655 1077 ctx: ExtensionContext,
656 1078 state: GoalState,
657 1079 settings: GoalSettings,
1080 + evidence: TurnEvidence
| undefined,
658 1081 ):
Promise<JudgeVerdict
> {
659 1082 const model
= resolveJudgeModel(ctx, settings);
660 1083 if (!model) return {
done:
false,
blocked:
false,
reason:
"no judge model" };
678 1101 objective: state.objective,
679 1102 criteria: state.criteria,
680 - latestAssistantResponse:
latestAssistantTail(
682 - settings.tailBytes,
1103 + turn: state.turnsUsed
+ 1,
1104 + maxTurns: state.maxTurns,
1105 + latestAssistantResponse: evidence
1106 + ? tailText(evidence.assistantText, settings.tailBytes)
1107 + : latestAssistantTail(ctx, settings.tailBytes),
1108 + stopReason: evidence?.stopReason,
1109 + errorMessage: evidence?.errorMessage,
1110 + toolCalls: evidence?.toolCalls
?? [],
1111 + toolResults: (evidence?.toolResults
?? []).
map((result)
=> ({
1113 + text:
tailText(result.
text, settings.tailBytes),
1160 +function goalSummary(
1161 + state
: GoalState | undefined,
1162 + continuation
: ContinuationState,
1164 + if (
!state)
return "No active /goal.";
1166 + `/goal status: ${state.status}`,
1167 + `objective: ${state.objective}`,
1168 + `criteria: ${state.criteria.length === 0 ? "none" : state.criteria.join("; ")}`,
1169 + `turns: ${state.turnsUsed}/${state.maxTurns}`,
1170 + `last verdict: ${state.lastVerdict ?? "none"}`,
1171 + `last reason: ${state.lastReason ?? "none"}`,
1172 + `blocked streak: ${state.blockedStreak ? `${state.blockedStreak.count} (${state.blockedStreak.reasonHash})` : "none"}`,
1173 + `continuation: ${continuation.queued ? `queued turn ${continuation.turn ?? "?"}` : "idle"}`,
1177 +function pruneContinuationMessages(
1178 + messages
: Array<
Record<
string,
unknown>>,
1179 + state
: GoalState | undefined,
1180 +)
: Array<
Record<
string,
unknown>> {
1181 + let latestIndex
= -1;
1182 + for (
let i
= messages.
length - 1; i
>= 0; i
--) {
1183 + const msg
= messages[i];
1184 + if (msg.role
!== "custom" || msg.customType
!== GOAL_CONTINUATION_ENTRY)
1186 + const details
= isRecord(msg.details)
? msg.details
: {};
1187 + if (state
&& details.goalId
=== state.
id && latestIndex
=== -1) {
1191 + return messages.
filter((msg, index)
=> {
1192 + if (msg.role
!== "custom" || msg.customType
!== GOAL_CONTINUATION_ENTRY)
1194 + return index
=== latestIndex;
729 1198 function cancelGoalRun(
730 1199 pi
: ExtensionAPI,
731 1200 ctx
: ExtensionContext,
746 -function sendWhenIdle(
1215 +function scheduleContinuation(
747 1216 pi
: ExtensionAPI,
748 1217 ctx
: ExtensionContext,
749 1218 state
: GoalState,
750 - scheduled
: { value
: boolean },
755 - let latest
: GoalState | undefined;
757 - latest
= latestGoalState(ctx);
759 - if (
isStaleContextError(error)) {
760 - scheduled.
value = false;
767 - latest.
id !== state.
id || 768 - latest.
status !== "active" || 769 - !ownsGoal(ctx, latest)
771 - scheduled.
value = false;
1219 + continuation
: ContinuationState,
1221 + if (continuation.queued
|| continuation.scheduled)
return;
1222 + continuation.goalId
= state.
id;
1223 + continuation.turn
= state.turnsUsed
+ 1;
1224 + continuation.queued
= true;
1225 + continuation.scheduled
= true;
1226 + debugGoal(pi,
"continuation-queued", {
1228 + turn: continuation.turn,
1230 + updateUI(pi, ctx, state,
"queued");
1231 + setTimeout(()
=> {
1232 + continuation.scheduled
= false;
1233 + let latest
: GoalState | undefined;
1235 + latest
= latestGoalState(ctx);
1237 + if (
isStaleContextError(error)) {
1238 + continuation.queued
= false;
774 - if (
!ctx.
isIdle()
|| ctx.
hasPendingMessages()) {
775 - if (attempt
>= CONTINUATION_MAX_ATTEMPTS) {
776 - scheduled.
value = false;
779 - return sendWhenIdle(pi, ctx, latest, scheduled, attempt
+ 1);
781 - scheduled.
value = false;
782 - pi.
sendUserMessage(
continuationPrompt(latest));
784 - attempt
=== 0 ? 0 : CONTINUATION_RETRY_MS,
1245 + latest.
id !== state.
id || 1246 + latest.
status !== "active" || 1247 + !ownsGoal(ctx, latest)
1249 + debugGoal(pi,
"continuation-stale", { goalId: state.
id });
1250 + appendGoalEvent(pi,
"continuation skipped", latest, { goalId: state.
id });
1251 + continuation.queued
= false;
1257 + customType: GOAL_CONTINUATION_ENTRY,
1258 + content:
continuationPrompt(latest),
1260 + details: { goalId: latest.
id, turn: latest.turnsUsed
+ 1 },
1262 + { triggerTurn:
true, deliverAs:
"followUp" },
1264 + debugGoal(pi,
"continuation-dispatched", {
1265 + goalId: latest.
id,
1266 + turn: latest.turnsUsed
+ 1,
1269 + continuation.queued
= false;
1270 + if (
!isStaleContextError(error))
throw error;
788 1275 function appendProbe(
1341 + pi.
registerMessageRenderer(GOAL_EVENT_ENTRY, (message, _options, theme)
=> {
1343 + theme.
fg(
"muted",
goalJudgeMessageLine(message.
content)),
854 1349 let state
: GoalState | undefined;
855 - const continuationScheduled
= { value:
false };
1350 + const continuation
: ContinuationState = { queued:
false, scheduled:
false };
856 1351 let removeTerminalInput
: (()
=> void)
| undefined;
857 1352 let probe
: ProbeState | undefined;
1353 + let lastTurnEvidence
: TurnEvidence | undefined;
858 1354 const syncUpdateGoalTool = ()
=> 859 1355 setToolActive(pi,
"update_goal",
canUseUpdateGoal(state));
861 1357 pi.
on(
"session_start", (_event, ctx)
=> {
862 1358 state
= latestGoalState(ctx);
1359 + continuation.queued
= false;
1360 + continuation.scheduled
= false;
863 1361 removeTerminalInput?.();
864 1362 removeTerminalInput
= ctx.hasUI
865 1363 ? ctx.ui.
onTerminalInput((data)
=> {
866 1364 if (
matchesKey(data,
"escape")) {
867 1365 state
= cancelGoalRun(pi, ctx, state);
868 - continuationScheduled.
value = false;
1366 + continuation.queued
= false;
1367 + continuation.scheduled
= false;
870 1369 return undefined;
874 1373 syncUpdateGoalTool();
1376 + pi.
on(
"input", (event, ctx)
=> {
1377 + const text
= event.
text.
trim();
1380 + text.
startsWith(
"/")
|| 1381 + event.
source === "extension" || 1384 + state.
status !== "active" || 1385 + !ownsGoal(ctx, state)
1387 + return { action:
"continue" }
as const;
1388 + state
= updateGoal(pi, state, {
1389 + criteria: [
...state.criteria, text],
1390 + lastReason:
`steering added as criterion: ${shortText(text)}`,
1392 + appendGoalEvent(pi,
"steering-added", state, { text });
1393 + updateUI(pi, ctx, state);
1397 + customType: GOAL_EVENT_ENTRY,
1398 + content:
`Additional /goal criterion from user steering:\n${text}`,
1400 + details: { goalId: state.
id, criterion: text },
1402 + { triggerTurn:
false, deliverAs:
"steer" },
1405 + if (
!isStaleContextError(error))
throw error;
1407 + return { action:
"handled" }
as const;
877 1410 pi.
on(
"before_agent_start", (event, ctx)
=> {
879 1412 const objective
= extractStandingGoalObjective(
event.
prompt);
887 1420 status:
"active",
889 1422 maxTurns: settings.maxTurns,
1423 + tokenBudget: settings.tokenBudget,
1425 + timeBudgetSeconds: settings.timeBudgetSeconds,
1426 + timeUsedSeconds:
0,
890 1427 sessionId:
currentSessionId(ctx),
900 1437 return { systemPrompt:
event.systemPrompt
+ activeGoalPrompt(state) };
1440 + pi.
on(
"context", (event)
=> {
1442 + messages:
pruneContinuationMessages(
1443 + event.messages
as never,
903 1449 pi.
on(
"agent_start", (_event, _ctx)
=> {
1450 + lastTurnEvidence
= undefined;
904 1451 if (probe?.active)
appendProbe(pi,
"agent-start", { mode: probe.mode });
1454 + pi.
on(
"turn_end", (event)
=> {
1455 + lastTurnEvidence
= mergeTurnEvidence(
1457 + buildTurnEvidence(
event as never),
907 1461 pi.
on(
"session_shutdown", (_event, ctx)
=> {
908 1462 removeTerminalInput?.();
909 1463 removeTerminalInput
= undefined;
911 1465 setToolActive(pi,
"update_goal",
false);
1468 + pi.
on(
"session_before_compact", ()
=> {
1469 + const summary
= goalSummary(state, continuation);
1470 + pi.
appendEntry(GOAL_COMPACTION_ENTRY, {
1473 + timestamp:
Date.
now(),
1475 + if (
!state
|| state.
status === "complete")
return;
1478 + customType: GOAL_COMPACTION_ENTRY,
1479 + content:
`Current /goal summary before compaction:\n${summary}`,
1481 + details: { goalId: state.
id },
1483 + { triggerTurn:
false, deliverAs:
"nextTurn" },
1487 + pi.
on(
"session_compact", ()
=> {
1488 + pi.
appendEntry(GOAL_COMPACTION_ENTRY, {
1490 + summary:
goalSummary(state, continuation),
1491 + timestamp:
Date.
now(),
914 1495 pi.
on(
"agent_end",
async (_event, ctx)
=> {
915 1496 if (probe?.active) {
916 1497 appendProbe(pi,
"agent-end", { mode: probe.mode });
1506 + continuation.queued
= false;
925 1507 updateUI(pi, ctx, state);
926 1508 syncUpdateGoalTool();
1509 + if (
!state
|| state.
status !== "active" || !ownsGoal(ctx, state))
return;
1510 + const evidence
= lastTurnEvidence;
929 - state.
status !== "active" || 930 - !ownsGoal(ctx, state)
|| 931 - continuationScheduled.
value 1512 + evidence?.stopReason
=== "aborted" || 1513 + evidence?.stopReason
=== "error" 1515 + state
= updateGoal(pi, state, {
1517 + lastVerdict:
"error",
1518 + lastReason: evidence.errorMessage
|| `assistant ${evidence.stopReason}`,
1520 + appendGoalEvent(pi,
"paused", state, { reason: state.lastReason });
1521 + updateUI(pi, ctx, state);
1522 + syncUpdateGoalTool();
1524 + ctx.ui.
notify(
`Goal paused — ${state.lastReason}`,
"warning");
934 1527 const judged
= state;
935 1528 appendJudge(pi,
"start", judged);
936 1529 updateUI(pi, ctx, judged,
"judging");
937 1530 let verdict
: JudgeVerdict;
939 - verdict
= await judgeGoal(ctx, judged,
loadSettings(pi));
1532 + verdict
= await judgeGoal(ctx, judged,
loadSettings(pi), evidence);
947 1540 if (state
!== judged
|| state.
status !== "active")
return;
948 1541 appendJudge(pi,
"verdict", judged, verdict);
1542 + const commonPatch
: Partial<
GoalState>
= {
1543 + lastReason: verdict.reason,
1544 + lastVerdict:
goalVerdictLabel(verdict),
1545 + tokensUsed: (judged.tokensUsed
?? 0)
+ tokenDelta(evidence),
1546 + timeUsedSeconds:
currentElapsedSeconds(judged),
949 1548 if (
isJudgeFailure(verdict)) {
1549 + const parseFailure
= isJudgeParseFailure(verdict);
1550 + const failures
= parseFailure
? (judged.judgeFailures
?? 0)
+ 1 : 0;
1551 + const repeated
= failures
>= JUDGE_PARSE_FAILURE_LIMIT;
950 1552 state
= updateGoal(pi, judged, {
952 - lastReason: verdict.reason,
1554 + lastReason: repeated
1555 + ? `judge parse failed repeatedly: ${verdict.reason}` 1557 + judgeFailures: failures,
1558 + status:
!parseFailure
|| repeated
? "paused" : "active",
954 1560 updateUI(pi, ctx, state);
955 1561 syncUpdateGoalTool();
957 - ctx.ui.
notify(
`Goal paused — ${verdict.reason}`,
"warning");
1562 + if (state.
status === "paused") {
1563 + appendGoalEvent(pi,
"paused", state, { reason: verdict.reason });
1565 + ctx.ui.
notify(
`Goal paused — ${verdict.reason}`,
"warning");
1566 + }
else scheduleContinuation(pi, ctx, state, continuation);
960 1569 if (verdict.done) {
961 1570 state
= updateGoal(pi, judged, {
962 1572 status:
"complete",
963 - lastReason: verdict.reason,
1575 + appendGoalEvent(pi,
"complete", state, { reason: verdict.reason });
965 1576 updateUI(pi, ctx, state);
966 1577 syncUpdateGoalTool();
971 1582 if (verdict.blocked) {
1583 + const blockedStreak
= nextBlockedStreak(judged, verdict.reason);
1584 + const turnsUsed
= judged.turnsUsed
+ 1;
1585 + const blocked
= blockedStreak.count
>= BLOCKED_STREAK_LIMIT;
972 1586 state
= updateGoal(pi, judged, {
974 - lastReason: verdict.reason,
1588 + status: blocked
? "blocked" : "active",
976 1593 updateUI(pi, ctx, state);
977 1594 syncUpdateGoalTool();
979 - ctx.ui.
notify(
`Goal blocked: ${verdict.reason}`,
"warning");
1596 + appendGoalEvent(pi,
"blocked", state, { reason: verdict.reason });
1598 + ctx.ui.
notify(
`Goal blocked: ${verdict.reason}`,
"warning");
1599 + }
else scheduleContinuation(pi, ctx, state, continuation);
982 1602 const turnsUsed
= judged.turnsUsed
+ 1;
983 - if (turnsUsed
>= judged.maxTurns) {
1603 + const exhaustedTurns
= turnsUsed
>= judged.maxTurns;
1604 + const exhaustedTokens
= 1605 + judged.tokenBudget
!== undefined && 1606 + (commonPatch.tokensUsed
?? 0)
>= judged.tokenBudget;
1607 + const exhaustedTime
= 1608 + judged.timeBudgetSeconds
!== undefined && 1609 + (commonPatch.timeUsedSeconds
?? 0)
>= judged.timeBudgetSeconds;
1610 + if (exhaustedTurns
|| exhaustedTokens
|| exhaustedTime) {
1611 + const kind
= exhaustedTokens
? "token" : exhaustedTime
? "time" : "turn";
984 1612 state
= updateGoal(pi, judged, {
985 1614 status:
"paused",
987 - lastReason:
`turn budget exhausted: ${verdict.reason}`,
1616 + blockedStreak:
undefined,
1618 + lastReason:
`${kind} budget exhausted: ${verdict.reason}`,
1620 + appendGoalEvent(pi,
"paused", state, { reason: state.lastReason });
989 1621 updateUI(pi, ctx, state);
990 1622 syncUpdateGoalTool();
998 - state
= updateGoal(pi, judged, { turnsUsed, lastReason: verdict.reason });
1630 + state
= updateGoal(pi, judged, {
1633 + blockedStreak:
undefined,
999 1636 updateUI(pi, ctx, state);
1000 1637 syncUpdateGoalTool();
1001 - continuationScheduled.
value = true;
1002 - sendWhenIdle(pi, ctx, state, continuationScheduled);
1638 + scheduleContinuation(pi, ctx, state, continuation);
1005 1641 pi.
registerTool({
1025 1661 throw new Error(
"Goal has not been judged yet.");
1026 1662 state
= updateGoal(pi, state, {
1027 1663 status: params.
status,
1664 + lastVerdict: params.
status === "complete" ? "done" : "blocked",
1028 1665 lastReason: params.reason,
1030 1667 updateUI(pi, ctx, state);
1051 1688 const cmd
= firstSpace
=== -1 ? input
: input.
slice(
0, firstSpace);
1052 1689 const rest
= firstSpace
=== -1 ? "" : input.
slice(firstSpace).
trim();
1053 1690 if (
!input
|| cmd
=== "status") {
1055 - state
? statusLine(state,
currentSessionId(ctx))
: "No active goal.",
1056 - state
? "info" : "warning",
1691 + notifyGoalStatus(ctx, state);
1058 1692 updateUI(pi, ctx, state);
1075 1709 state
= updateGoal(pi, state, {
1076 1710 status:
"active",
1712 + lastVerdict:
undefined,
1713 + blockedStreak:
undefined,
1078 1715 sessionId:
currentSessionId(ctx),
1080 1717 updateUI(pi, ctx, state);
1083 1720 rebinding
? "Goal resumed in this session" : "Goal resumed",
1084 1721 rebinding
? "warning" : "info",
1086 - continuationScheduled.
value = true;
1087 - sendWhenIdle(pi, ctx, state, continuationScheduled);
1723 + scheduleContinuation(pi, ctx, state, continuation);
1090 1726 if (cmd
=== "complete") {
1172 1808 status:
"active",
1174 1810 maxTurns: settings.maxTurns,
1811 + tokenBudget: settings.tokenBudget,
1813 + timeBudgetSeconds: settings.timeBudgetSeconds,
1814 + timeUsedSeconds:
0,
1175 1815 sessionId:
currentSessionId(ctx),
1176 1816 createdAt:
Date.
now(),
1177 1817 updatedAt:
Date.
now(),
1217 1857 latestAssistantTail,
1218 1858 latestGoalState,
1859 + buildTurnEvidence,
1860 + mergeTurnEvidence,
1221 1863 judgeRunningText,
1226 1868 extractStandingGoalObjective,
1869 + compactStatusLine,
1871 + pruneContinuationMessages,
1229 1874 textFromContent,