@narumitw/pi-goal 0.53.1 → 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.1",
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",
@@ -2,7 +2,13 @@ import type { GoalPromptContext } from "./prompts.js";
2
2
  import { buildGoalContextPrompt } from "./prompts.js";
3
3
 
4
4
  export const GOAL_CONTRACT_MESSAGE_TYPE = "goal-contract";
5
- export const GOAL_CONTRACT_VERSION = 1;
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");
6
12
 
7
13
  interface ContractMessage {
8
14
  role?: string;
@@ -10,40 +16,86 @@ interface ContractMessage {
10
16
  content?: unknown;
11
17
  }
12
18
 
19
+ interface ContractSessionEntry extends ContractMessage {
20
+ type?: string;
21
+ message?: unknown;
22
+ }
23
+
13
24
  export function createGoalContextContract(goal: GoalPromptContext) {
14
25
  return {
15
26
  role: "custom" as const,
16
27
  customType: GOAL_CONTRACT_MESSAGE_TYPE,
17
- content: buildGoalContextPrompt(goal),
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"),
18
33
  display: false,
19
- details: { version: GOAL_CONTRACT_VERSION, goalId: goal.id },
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" },
20
46
  timestamp: 0,
21
47
  };
22
48
  }
23
49
 
24
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;
25
86
  const summaryBoundary = leadingSummaryBoundary(messages);
26
- const expected = createGoalContextContract(goal);
27
- const contractIndexes = messages.flatMap((message, index) =>
28
- unwrapMessage(message).customType === GOAL_CONTRACT_MESSAGE_TYPE ? [index] : [],
29
- );
30
- if (
31
- contractIndexes.length === 1 &&
32
- contractIndexes[0] === summaryBoundary &&
33
- unwrapMessage(messages[summaryBoundary]).content === expected.content
34
- ) {
35
- return messages;
87
+ if (!hasGoalContextContractHistory(messages) && summaryBoundary > 0) {
88
+ return [...messages.slice(0, summaryBoundary), expected, ...messages.slice(summaryBoundary)];
36
89
  }
90
+ return [...messages, expected];
91
+ }
37
92
 
38
- const withoutContracts = messages.filter(
39
- (message) => unwrapMessage(message).customType !== GOAL_CONTRACT_MESSAGE_TYPE,
40
- );
41
- const insertionIndex = leadingSummaryBoundary(withoutContracts);
42
- return [
43
- ...withoutContracts.slice(0, insertionIndex),
44
- expected,
45
- ...withoutContracts.slice(insertionIndex),
46
- ];
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;
47
99
  }
48
100
 
49
101
  function leadingSummaryBoundary(messages: readonly unknown[]) {
@@ -57,6 +109,7 @@ function leadingSummaryBoundary(messages: readonly unknown[]) {
57
109
  }
58
110
 
59
111
  function unwrapMessage(message: unknown): ContractMessage {
60
- const entry = message as { message?: unknown } | undefined;
112
+ const entry = message as ContractSessionEntry | undefined;
113
+ if (entry?.type === "custom_message") return entry;
61
114
  return (entry?.message ?? message ?? {}) as ContractMessage;
62
115
  }
package/src/lifecycle.ts CHANGED
@@ -1,7 +1,12 @@
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 { reconcileGoalContextContract } from "./goal-contract.js";
4
+ import {
5
+ GOAL_CONTRACT_MESSAGE_TYPE,
6
+ isGoalContextContract,
7
+ reconcileGoalContextContract,
8
+ reconcileInactiveGoalContextContract,
9
+ } from "./goal-contract.js";
5
10
  import { type ActiveGoal, loadGoalStateFromSession } from "./persistence.js";
6
11
  import type { GoalRunController } from "./run-protocol.js";
7
12
  import {
@@ -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) {
@@ -340,10 +367,14 @@ export function registerGoalLifecycle(
340
367
  const keptMessages = event.messages.filter((message) =>
341
368
  runtime.keepBudgetWrapUpMessage(message),
342
369
  );
370
+ const hasGoalContractHistory =
371
+ keptMessages.some(isGoalContextContract) || runtime.hasGoalContextContractHistory(ctx);
343
372
  const messages =
344
373
  runtime.activeGoal?.status === "active" && runtime.ownsWorkflow(runtime.activeGoal)
345
374
  ? reconcileGoalContextContract(keptMessages, runtime.activeGoal)
346
- : keptMessages;
375
+ : hasGoalContractHistory
376
+ ? reconcileInactiveGoalContextContract(keptMessages)
377
+ : keptMessages;
347
378
  if (
348
379
  runtime.activeGoal?.status === "paused" &&
349
380
  runtime.guardAbortGoalId === runtime.activeGoal.id
@@ -450,7 +481,7 @@ export function registerGoalLifecycle(
450
481
  : "manual";
451
482
  if (activeBudgetWrapUp && runtime.activeGoal) {
452
483
  runtime.beginAgentRun(runtime.activeGoal.id, "manual");
453
- return;
484
+ return goalContractBoundaryResult(ctx);
454
485
  }
455
486
  if (ownedPromptGoalId && ownedPromptGoalId !== runtime.activeGoal?.id) {
456
487
  runtime.beginAgentRun(ownedPromptGoalId, runOrigin);
@@ -461,18 +492,19 @@ export function registerGoalLifecycle(
461
492
  return;
462
493
  }
463
494
  if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
464
- return;
495
+ return goalContractBoundaryResult(ctx);
465
496
  }
466
497
  runtime.beginAgentRun(runtime.activeGoal.id, runOrigin);
467
498
  if (!runtime.toolPolicy.toolsAvailable()) {
468
499
  runtime.pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);
469
- return;
500
+ return goalContractBoundaryResult(ctx);
470
501
  }
471
502
  if (goalPrompt?.resetSafetyEpoch && goalPromptGoalId === runtime.activeGoal.id) {
472
503
  runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
473
504
  runtime.persistGoal(runtime.activeGoal);
474
505
  runtime.updateStatus(ctx, runtime.activeGoal);
475
506
  }
507
+ return goalContractBoundaryResult(ctx, runtime.activeGoal);
476
508
  });
477
509
 
478
510
  pi.on("agent_start", (_event, _ctx) => {
@@ -600,6 +632,11 @@ export function registerGoalLifecycle(
600
632
  runtime.clearSettledSafetyTracking();
601
633
  });
602
634
 
635
+ function goalContractBoundaryResult(ctx: StatusContext, goal?: ActiveGoal) {
636
+ const message = runtime.goalContextContractForPrompt(ctx, goal);
637
+ return message ? { message } : undefined;
638
+ }
639
+
603
640
  function beginNonGoalFollowUp(ctx: StatusContext, resetSafetyEpoch: boolean) {
604
641
  runtime.clearGoalRecovery();
605
642
  runtime.clearStaleGoalToolCallBlock();
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,