@narumitw/pi-goal 0.53.0 → 0.53.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-goal",
3
- "version": "0.53.0",
3
+ "version": "0.53.3",
4
4
  "description": "Pi extension for autonomous single-objective /goal completion.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -41,16 +41,16 @@
41
41
  "typebox": "*"
42
42
  },
43
43
  "devDependencies": {
44
- "@biomejs/biome": "2.5.9",
45
- "@earendil-works/pi-ai": "0.84.2",
46
- "@earendil-works/pi-coding-agent": "0.84.2",
47
- "@earendil-works/pi-tui": "0.84.2",
44
+ "@biomejs/biome": "2.5.10",
45
+ "@earendil-works/pi-ai": "0.84.3",
46
+ "@earendil-works/pi-coding-agent": "0.84.3",
47
+ "@earendil-works/pi-tui": "0.84.3",
48
48
  "esbuild": "0.28.2",
49
- "typebox": "1.3.16",
49
+ "typebox": "1.3.18",
50
50
  "typescript": "7.0.2"
51
51
  },
52
52
  "dependencies": {
53
- "@narumitw/pi-tui-kit": "^0.57.0"
53
+ "@narumitw/pi-tui-kit": "^0.58.0"
54
54
  },
55
55
  "repository": {
56
56
  "type": "git",
@@ -0,0 +1,115 @@
1
+ import type { GoalPromptContext } from "./prompts.js";
2
+ import { buildGoalContextPrompt } from "./prompts.js";
3
+
4
+ export const GOAL_CONTRACT_MESSAGE_TYPE = "goal-contract";
5
+ export const GOAL_CONTRACT_VERSION = 2;
6
+
7
+ const INACTIVE_GOAL_CONTRACT_CONTENT = [
8
+ "Goal mode is inactive.",
9
+ "This Goal contract supersedes every earlier goal-contract message.",
10
+ "Do not treat an earlier Goal objective, goal_id, Goal-mode rule, or summary of them as current unless a later Goal contract explicitly reactivates Goal mode.",
11
+ ].join("\n");
12
+
13
+ interface ContractMessage {
14
+ role?: string;
15
+ customType?: string;
16
+ content?: unknown;
17
+ }
18
+
19
+ interface ContractSessionEntry extends ContractMessage {
20
+ type?: string;
21
+ message?: unknown;
22
+ }
23
+
24
+ export function createGoalContextContract(goal: GoalPromptContext) {
25
+ return {
26
+ role: "custom" as const,
27
+ customType: GOAL_CONTRACT_MESSAGE_TYPE,
28
+ content: [
29
+ "This Goal contract supersedes every earlier goal-contract message.",
30
+ "Only the objective and goal_id in this latest Goal contract are current.",
31
+ buildGoalContextPrompt(goal),
32
+ ].join("\n\n"),
33
+ display: false,
34
+ details: { version: GOAL_CONTRACT_VERSION, state: "active", goalId: goal.id },
35
+ timestamp: 0,
36
+ };
37
+ }
38
+
39
+ export function createInactiveGoalContextContract() {
40
+ return {
41
+ role: "custom" as const,
42
+ customType: GOAL_CONTRACT_MESSAGE_TYPE,
43
+ content: INACTIVE_GOAL_CONTRACT_CONTENT,
44
+ display: false,
45
+ details: { version: GOAL_CONTRACT_VERSION, state: "inactive" },
46
+ timestamp: 0,
47
+ };
48
+ }
49
+
50
+ export function reconcileGoalContextContract(messages: unknown[], goal: GoalPromptContext) {
51
+ return reconcileContract(messages, createGoalContextContract(goal));
52
+ }
53
+
54
+ export function reconcileInactiveGoalContextContract(messages: unknown[]) {
55
+ return reconcileContract(messages, createInactiveGoalContextContract());
56
+ }
57
+
58
+ export function hasGoalContextContract(entries: unknown[], goal: GoalPromptContext) {
59
+ return latestGoalContractContent(entries) === createGoalContextContract(goal).content;
60
+ }
61
+
62
+ export function hasInactiveGoalContextContract(entries: unknown[]) {
63
+ return latestGoalContractContent(entries) === INACTIVE_GOAL_CONTRACT_CONTENT;
64
+ }
65
+
66
+ export function hasGoalContextContractHistory(entries: unknown[]) {
67
+ return entries.some(isGoalContextContract);
68
+ }
69
+
70
+ export function isGoalContextContract(message: unknown) {
71
+ return unwrapMessage(message).customType === GOAL_CONTRACT_MESSAGE_TYPE;
72
+ }
73
+
74
+ function reconcileContract(
75
+ messages: unknown[],
76
+ expected: {
77
+ role: "custom";
78
+ customType: string;
79
+ content: string;
80
+ display: boolean;
81
+ details: object;
82
+ timestamp: number;
83
+ },
84
+ ) {
85
+ if (latestGoalContractContent(messages) === expected.content) return messages;
86
+ const summaryBoundary = leadingSummaryBoundary(messages);
87
+ if (!hasGoalContextContractHistory(messages) && summaryBoundary > 0) {
88
+ return [...messages.slice(0, summaryBoundary), expected, ...messages.slice(summaryBoundary)];
89
+ }
90
+ return [...messages, expected];
91
+ }
92
+
93
+ function latestGoalContractContent(messages: readonly unknown[]) {
94
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
95
+ const message = messages[index];
96
+ if (isGoalContextContract(message)) return unwrapMessage(message).content;
97
+ }
98
+ return undefined;
99
+ }
100
+
101
+ function leadingSummaryBoundary(messages: readonly unknown[]) {
102
+ let index = 0;
103
+ while (index < messages.length) {
104
+ const role = unwrapMessage(messages[index]).role;
105
+ if (role !== "compactionSummary" && role !== "branchSummary") break;
106
+ index += 1;
107
+ }
108
+ return index;
109
+ }
110
+
111
+ function unwrapMessage(message: unknown): ContractMessage {
112
+ const entry = message as ContractSessionEntry | undefined;
113
+ if (entry?.type === "custom_message") return entry;
114
+ return (entry?.message ?? message ?? {}) as ContractMessage;
115
+ }
package/src/lifecycle.ts CHANGED
@@ -1,8 +1,13 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { currentTokenTotal } from "./accounting.js";
3
3
  import { notifyTerminal } from "./errors.js";
4
+ import {
5
+ GOAL_CONTRACT_MESSAGE_TYPE,
6
+ isGoalContextContract,
7
+ reconcileGoalContextContract,
8
+ reconcileInactiveGoalContextContract,
9
+ } from "./goal-contract.js";
4
10
  import { type ActiveGoal, loadGoalStateFromSession } from "./persistence.js";
5
- import { buildGoalSystemPrompt } from "./prompts.js";
6
11
  import type { GoalRunController } from "./run-protocol.js";
7
12
  import {
8
13
  type AssistantMessageLike,
@@ -81,6 +86,7 @@ export function registerGoalLifecycle(
81
86
  if (!runtime.acquireWorkflow()) {
82
87
  runtime.activeGoal = transitionGoal(loaded.goal, "paused");
83
88
  runtime.persistGoal(runtime.activeGoal);
89
+ runtime.ensureInactiveGoalContextContract(ctx);
84
90
  runtime.updateStatus(ctx, runtime.activeGoal);
85
91
  notifyTerminal(
86
92
  ctx.ui,
@@ -121,6 +127,15 @@ export function registerGoalLifecycle(
121
127
  }
122
128
  runtime.persistGoal(runtime.activeGoal);
123
129
  if (!runtime.ownsWorkflow(runtime.activeGoal)) return;
130
+ const restoredGoalId = runtime.activeGoal.id;
131
+ runtime.ensureGoalContextContract(ctx, runtime.activeGoal);
132
+ if (
133
+ runtime.activeGoal?.id !== restoredGoalId ||
134
+ runtime.activeGoal.status !== "active" ||
135
+ !runtime.ownsWorkflow(runtime.activeGoal)
136
+ ) {
137
+ return;
138
+ }
124
139
  runtime.updateStatus(ctx, runtime.activeGoal);
125
140
  runtime.restoreGoalWaitTimer(ctx);
126
141
  return;
@@ -162,8 +177,10 @@ export function registerGoalLifecycle(
162
177
  }
163
178
  if (runtime.activeGoal) {
164
179
  runtime.persistGoal(runtime.activeGoal);
180
+ runtime.ensureInactiveGoalContextContract(ctx);
165
181
  runtime.updateStatus(ctx, runtime.activeGoal);
166
182
  } else {
183
+ runtime.ensureInactiveGoalContextContract(ctx);
167
184
  ctx.ui.setStatus(STATUS_KEY, undefined);
168
185
  }
169
186
  });
@@ -226,8 +243,17 @@ export function registerGoalLifecycle(
226
243
  runtime.persistGoal(runtime.activeGoal);
227
244
  runtime.updateStatus(ctx, runtime.activeGoal);
228
245
  }
229
- if (!usageRecorded) return;
230
246
  if (runtime.limitActiveGoalForBudget(ctx, false)) return;
247
+ const compactedGoalId = runtime.activeGoal.id;
248
+ runtime.ensureGoalContextContract(ctx, runtime.activeGoal);
249
+ if (
250
+ runtime.activeGoal?.id !== compactedGoalId ||
251
+ runtime.activeGoal.status !== "active" ||
252
+ !runtime.ownsWorkflow(runtime.activeGoal)
253
+ ) {
254
+ return;
255
+ }
256
+ if (!usageRecorded) return;
231
257
 
232
258
  const wasPiRetry = runtime.isPiOwnedCompactionRetry(event, runtime.activeGoal.id);
233
259
  if (wasPiRetry) return;
@@ -287,6 +313,7 @@ export function registerGoalLifecycle(
287
313
  return;
288
314
  }
289
315
  if (message.role === "custom") {
316
+ if (Reflect.get(message, "customType") === GOAL_CONTRACT_MESSAGE_TYPE) return;
290
317
  if (runtime.isActiveBudgetWrapUpMessage(message)) return;
291
318
  if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);
292
319
  if (runtime.guardAbortGoalId === runtime.activeGoal?.id) {
@@ -337,7 +364,17 @@ export function registerGoalLifecycle(
337
364
  });
338
365
 
339
366
  pi.on("context", (event, ctx) => {
340
- const messages = event.messages.filter((message) => runtime.keepBudgetWrapUpMessage(message));
367
+ const keptMessages = event.messages.filter((message) =>
368
+ runtime.keepBudgetWrapUpMessage(message),
369
+ );
370
+ const hasGoalContractHistory =
371
+ keptMessages.some(isGoalContextContract) || runtime.hasGoalContextContractHistory(ctx);
372
+ const messages =
373
+ runtime.activeGoal?.status === "active" && runtime.ownsWorkflow(runtime.activeGoal)
374
+ ? reconcileGoalContextContract(keptMessages, runtime.activeGoal)
375
+ : hasGoalContractHistory
376
+ ? reconcileInactiveGoalContextContract(keptMessages)
377
+ : keptMessages;
341
378
  if (
342
379
  runtime.activeGoal?.status === "paused" &&
343
380
  runtime.guardAbortGoalId === runtime.activeGoal.id
@@ -346,7 +383,9 @@ export function registerGoalLifecycle(
346
383
  // context transformation aborts before the provider adapter receives the signal.
347
384
  abortCurrentTurn(ctx);
348
385
  }
349
- if (messages.length !== event.messages.length) return { messages };
386
+ if (messages !== keptMessages || keptMessages.length !== event.messages.length) {
387
+ return { messages: messages as typeof event.messages };
388
+ }
350
389
  });
351
390
 
352
391
  pi.on("tool_call", (event, ctx) => {
@@ -442,7 +481,7 @@ export function registerGoalLifecycle(
442
481
  : "manual";
443
482
  if (activeBudgetWrapUp && runtime.activeGoal) {
444
483
  runtime.beginAgentRun(runtime.activeGoal.id, "manual");
445
- return;
484
+ return goalContractBoundaryResult(ctx);
446
485
  }
447
486
  if (ownedPromptGoalId && ownedPromptGoalId !== runtime.activeGoal?.id) {
448
487
  runtime.beginAgentRun(ownedPromptGoalId, runOrigin);
@@ -453,22 +492,19 @@ export function registerGoalLifecycle(
453
492
  return;
454
493
  }
455
494
  if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
456
- return;
495
+ return goalContractBoundaryResult(ctx);
457
496
  }
458
497
  runtime.beginAgentRun(runtime.activeGoal.id, runOrigin);
459
498
  if (!runtime.toolPolicy.toolsAvailable()) {
460
499
  runtime.pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);
461
- return;
500
+ return goalContractBoundaryResult(ctx);
462
501
  }
463
502
  if (goalPrompt?.resetSafetyEpoch && goalPromptGoalId === runtime.activeGoal.id) {
464
503
  runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
465
504
  runtime.persistGoal(runtime.activeGoal);
466
505
  runtime.updateStatus(ctx, runtime.activeGoal);
467
506
  }
468
-
469
- return {
470
- systemPrompt: `${event.systemPrompt}\n\n${buildGoalSystemPrompt(runtime.activeGoal)}`,
471
- };
507
+ return goalContractBoundaryResult(ctx, runtime.activeGoal);
472
508
  });
473
509
 
474
510
  pi.on("agent_start", (_event, _ctx) => {
@@ -596,6 +632,11 @@ export function registerGoalLifecycle(
596
632
  runtime.clearSettledSafetyTracking();
597
633
  });
598
634
 
635
+ function goalContractBoundaryResult(ctx: StatusContext, goal?: ActiveGoal) {
636
+ const message = runtime.goalContextContractForPrompt(ctx, goal);
637
+ return message ? { message } : undefined;
638
+ }
639
+
599
640
  function beginNonGoalFollowUp(ctx: StatusContext, resetSafetyEpoch: boolean) {
600
641
  runtime.clearGoalRecovery();
601
642
  runtime.clearStaleGoalToolCallBlock();
@@ -82,12 +82,6 @@ export function loadGoalStateFromSession(ctx: SessionContext): LoadedGoalState {
82
82
  return legacyEntry ? loadLegacyGoalsState(legacyEntry.data) : emptyGoalState("none");
83
83
  }
84
84
 
85
- export function loadGoalFromSession(ctx: SessionContext): ActiveGoal | undefined {
86
- const loaded = loadGoalStateFromSession(ctx);
87
- if (loaded.legacyQueueState || loaded.goal?.status === "complete") return undefined;
88
- return loaded.goal;
89
- }
90
-
91
85
  function loadCanonicalGoalState(data: unknown): LoadedGoalState {
92
86
  if (!isRecord(data)) return emptyGoalState("canonical");
93
87
  const rawGoal = data.goal;
package/src/prompts.ts CHANGED
@@ -56,8 +56,14 @@ export function buildGoalSystemPrompt(goal: GoalPromptContext) {
56
56
  return `Active /goal:\n${goalContextBlock(goal)}\n\n${goalModeRules("the active goal")}${budgetLine}`;
57
57
  }
58
58
 
59
+ export function buildGoalContextPrompt(goal: GoalPromptContext) {
60
+ return `Active /goal context:\n${goalContextBlock(goal)}\n\n${goalModeRules("the active goal")}`;
61
+ }
62
+
59
63
  export function buildContinuePrompt(goal: GoalPromptContext, marker: string) {
60
- return `Continue the active /goal until it is complete:\n\n${goalContextBlock(goal)}\n\nThis is automatic continuation #${goal.iteration}. The full objective persists across turns; continue from the authoritative current state.\n\n${goalModeRules("this goal")}\n\n${continuationMarkerComment(marker)}`;
64
+ const budgetLine =
65
+ goal.tokenBudget === undefined ? "" : `\nToken budget: ${formatBudget(goal)} used.`;
66
+ return `Continue the active /goal until it is complete:\n\n${goalContextBlock(goal)}${budgetLine}\n\nThis is automatic continuation #${goal.iteration}. The full objective persists across turns; continue from the authoritative current state.\n\n${goalModeRules("this goal")}\n\n${continuationMarkerComment(marker)}`;
61
67
  }
62
68
 
63
69
  function goalContextBlock(goal: GoalPromptContext) {
package/src/runtime.ts CHANGED
@@ -7,6 +7,13 @@ import {
7
7
  updateGoalUsage,
8
8
  } from "./accounting.js";
9
9
  import { formatError, notifyTerminal, safeGoalMenuText, truncateNotification } from "./errors.js";
10
+ import {
11
+ createGoalContextContract,
12
+ createInactiveGoalContextContract,
13
+ hasGoalContextContract,
14
+ hasGoalContextContractHistory,
15
+ hasInactiveGoalContextContract,
16
+ } from "./goal-contract.js";
10
17
  import {
11
18
  appendGoalPromptMarker,
12
19
  extractContinuationMarker,
@@ -695,6 +702,7 @@ export class GoalRuntime {
695
702
  if (terminalReason !== undefined) this.setTerminalReason(this.activeGoal.id, terminalReason);
696
703
  const stoppedGoal = this.activeGoal;
697
704
  this.persistGoal(stoppedGoal);
705
+ this.ensureInactiveGoalContextContract(ctx);
698
706
  if (this.activeGoal?.id === stoppedGoal.id && this.activeGoal.status === stoppedGoal.status) {
699
707
  this.updateStatus(ctx, stoppedGoal);
700
708
  this.releaseWorkflow();
@@ -893,8 +901,22 @@ export class GoalRuntime {
893
901
  if (!recovery) return false;
894
902
  this.goalRecovery = undefined;
895
903
  const goal = this.activeGoal;
896
- if (goal?.id !== recovery.goalId || goal.status !== "active") return false;
904
+ if (goal?.id !== recovery.goalId || goal.status !== "active" || !this.ownsWorkflow(goal)) {
905
+ return false;
906
+ }
897
907
  const details = recovery.errorMessage ? `: ${truncateNotification(recovery.errorMessage)}` : "";
908
+ if (recovery.kind === "provider_retry") {
909
+ const waitingGoal = this.enterGoalWait(ctx, goal.id, {
910
+ reason: `Provider retries exhausted${details}`,
911
+ });
912
+ if (!waitingGoal) return false;
913
+ notifyTerminal(
914
+ ctx.ui,
915
+ `Goal waiting after provider retries were exhausted${details}. Send a follow-up or run /goal resume to retry.`,
916
+ "warning",
917
+ );
918
+ return true;
919
+ }
898
920
  const stoppedGoal = this.stopActiveGoal(ctx, {
899
921
  kind: "retry_exhausted",
900
922
  expectedGoalId: goal.id,
@@ -946,6 +968,37 @@ export class GoalRuntime {
946
968
  this.pendingNonGoalInputs = [];
947
969
  }
948
970
 
971
+ ensureGoalContextContract(ctx: StatusContext, goal: ActiveGoal) {
972
+ const contract = this.goalContextContractForPrompt(ctx, goal);
973
+ if (contract) this.pi.sendMessage(contract, { triggerTurn: false });
974
+ }
975
+
976
+ ensureInactiveGoalContextContract(ctx: StatusContext) {
977
+ const contract = this.goalContextContractForPrompt(ctx);
978
+ if (contract) this.pi.sendMessage(contract, { triggerTurn: false });
979
+ }
980
+
981
+ goalContextContractForPrompt(ctx: StatusContext, goal?: ActiveGoal) {
982
+ const { contextEntries, historyEntries } = goalContractEntries(ctx);
983
+ if (goal) {
984
+ return hasGoalContextContract(contextEntries, goal)
985
+ ? undefined
986
+ : createGoalContextContract(goal);
987
+ }
988
+ const hasHistory =
989
+ hasGoalContextContractHistory(contextEntries) ||
990
+ hasGoalContextContractHistory(historyEntries);
991
+ if (!hasHistory || hasInactiveGoalContextContract(contextEntries)) return undefined;
992
+ return createInactiveGoalContextContract();
993
+ }
994
+
995
+ hasGoalContextContractHistory(ctx: StatusContext) {
996
+ const { contextEntries, historyEntries } = goalContractEntries(ctx);
997
+ return (
998
+ hasGoalContextContractHistory(contextEntries) || hasGoalContextContractHistory(historyEntries)
999
+ );
1000
+ }
1001
+
949
1002
  async sendOwnedGoalPrompt(
950
1003
  ctx: StatusContext,
951
1004
  goalId: string,
@@ -1210,6 +1263,7 @@ export class GoalRuntime {
1210
1263
  this.activeGoal = undefined;
1211
1264
  this.legacyQueueState = undefined;
1212
1265
  this.clearPersistedGoal(ctx.cwd, clearedGoal, reason);
1266
+ this.ensureInactiveGoalContextContract(ctx);
1213
1267
  ctx.ui.setStatus(STATUS_KEY, undefined);
1214
1268
  if (releaseWorkflow) this.releaseWorkflow();
1215
1269
  // Do not relock toolPolicy: after first activation, keep tools visible for the
@@ -1541,6 +1595,25 @@ function inputFingerprint(prompt: unknown) {
1541
1595
  .digest("hex");
1542
1596
  }
1543
1597
 
1598
+ function goalContractEntries(ctx: StatusContext) {
1599
+ const sessionManager = ctx.sessionManager as
1600
+ | {
1601
+ buildContextEntries?: () => unknown[];
1602
+ buildSessionContext?: () => { messages?: unknown[] };
1603
+ getBranch?: () => unknown[];
1604
+ getEntries?: () => unknown[];
1605
+ }
1606
+ | undefined;
1607
+ const historyEntries = sessionManager?.getBranch?.() ?? sessionManager?.getEntries?.() ?? [];
1608
+ return {
1609
+ contextEntries:
1610
+ sessionManager?.buildSessionContext?.().messages ??
1611
+ sessionManager?.buildContextEntries?.() ??
1612
+ historyEntries,
1613
+ historyEntries,
1614
+ };
1615
+ }
1616
+
1544
1617
  async function sendPrompt(
1545
1618
  pi: ExtensionAPI,
1546
1619
  ctx: StatusContext,
@@ -389,10 +389,6 @@ export function parseGoalLimit(value: string): number | undefined {
389
389
  return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
390
390
  }
391
391
 
392
- export function formatGoalLimit(value: number | null) {
393
- return value === null ? "Unlimited" : String(value);
394
- }
395
-
396
392
  async function resolveLimitSelection(
397
393
  field: LimitField,
398
394
  selection: LimitSelection,