@agimon-ai/doompi-goal 0.0.1-alpha.0

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.
Files changed (180) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +25 -0
  3. package/dist/_virtual/_rolldown/runtime.cjs +1 -0
  4. package/dist/adapters/node/historyLock.cjs +2 -0
  5. package/dist/adapters/node/historyLock.cjs.map +1 -0
  6. package/dist/adapters/node/historyLock.mjs +2 -0
  7. package/dist/adapters/node/historyLock.mjs.map +1 -0
  8. package/dist/adapters/node/historyStore.cjs +2 -0
  9. package/dist/adapters/node/historyStore.cjs.map +1 -0
  10. package/dist/adapters/node/historyStore.mjs +2 -0
  11. package/dist/adapters/node/historyStore.mjs.map +1 -0
  12. package/dist/adapters/node/repositoryIdentity.cjs +2 -0
  13. package/dist/adapters/node/repositoryIdentity.cjs.map +1 -0
  14. package/dist/adapters/node/repositoryIdentity.mjs +2 -0
  15. package/dist/adapters/node/repositoryIdentity.mjs.map +1 -0
  16. package/dist/adapters/pi/goalManager.cjs +2 -0
  17. package/dist/adapters/pi/goalManager.cjs.map +1 -0
  18. package/dist/adapters/pi/goalManager.d.cts +86 -0
  19. package/dist/adapters/pi/goalManager.d.cts.map +1 -0
  20. package/dist/adapters/pi/goalManager.d.mts +86 -0
  21. package/dist/adapters/pi/goalManager.d.mts.map +1 -0
  22. package/dist/adapters/pi/goalManager.mjs +2 -0
  23. package/dist/adapters/pi/goalManager.mjs.map +1 -0
  24. package/dist/adapters/pi/toolVisibility.cjs +2 -0
  25. package/dist/adapters/pi/toolVisibility.cjs.map +1 -0
  26. package/dist/adapters/pi/toolVisibility.mjs +2 -0
  27. package/dist/adapters/pi/toolVisibility.mjs.map +1 -0
  28. package/dist/container/index.cjs +2 -0
  29. package/dist/container/index.cjs.map +1 -0
  30. package/dist/container/index.mjs +2 -0
  31. package/dist/container/index.mjs.map +1 -0
  32. package/dist/extensions/doom.cjs +2 -0
  33. package/dist/extensions/doom.cjs.map +1 -0
  34. package/dist/extensions/doom.d.cts +6 -0
  35. package/dist/extensions/doom.d.cts.map +1 -0
  36. package/dist/extensions/doom.d.mts +6 -0
  37. package/dist/extensions/doom.d.mts.map +1 -0
  38. package/dist/extensions/doom.mjs +2 -0
  39. package/dist/extensions/doom.mjs.map +1 -0
  40. package/dist/extensions/pi.cjs +2 -0
  41. package/dist/extensions/pi.cjs.map +1 -0
  42. package/dist/extensions/pi.d.cts +7 -0
  43. package/dist/extensions/pi.d.cts.map +1 -0
  44. package/dist/extensions/pi.d.mts +7 -0
  45. package/dist/extensions/pi.d.mts.map +1 -0
  46. package/dist/extensions/pi.mjs +2 -0
  47. package/dist/extensions/pi.mjs.map +1 -0
  48. package/dist/extensions/runtimeActivation.cjs +2 -0
  49. package/dist/extensions/runtimeActivation.cjs.map +1 -0
  50. package/dist/extensions/runtimeActivation.d.cts +14 -0
  51. package/dist/extensions/runtimeActivation.d.cts.map +1 -0
  52. package/dist/extensions/runtimeActivation.d.mts +14 -0
  53. package/dist/extensions/runtimeActivation.d.mts.map +1 -0
  54. package/dist/extensions/runtimeActivation.mjs +2 -0
  55. package/dist/extensions/runtimeActivation.mjs.map +1 -0
  56. package/dist/index.cjs +1 -0
  57. package/dist/index.d.cts +17 -0
  58. package/dist/index.d.mts +17 -0
  59. package/dist/index.mjs +1 -0
  60. package/dist/services/extensionService.cjs +2 -0
  61. package/dist/services/extensionService.cjs.map +1 -0
  62. package/dist/services/extensionService.d.cts +8 -0
  63. package/dist/services/extensionService.d.cts.map +1 -0
  64. package/dist/services/extensionService.d.mts +8 -0
  65. package/dist/services/extensionService.d.mts.map +1 -0
  66. package/dist/services/extensionService.mjs +2 -0
  67. package/dist/services/extensionService.mjs.map +1 -0
  68. package/dist/services/goal/accounting.cjs +2 -0
  69. package/dist/services/goal/accounting.cjs.map +1 -0
  70. package/dist/services/goal/accounting.d.cts +34 -0
  71. package/dist/services/goal/accounting.d.cts.map +1 -0
  72. package/dist/services/goal/accounting.d.mts +34 -0
  73. package/dist/services/goal/accounting.d.mts.map +1 -0
  74. package/dist/services/goal/accounting.mjs +2 -0
  75. package/dist/services/goal/accounting.mjs.map +1 -0
  76. package/dist/services/goal/parser.cjs +2 -0
  77. package/dist/services/goal/parser.cjs.map +1 -0
  78. package/dist/services/goal/parser.d.cts +24 -0
  79. package/dist/services/goal/parser.d.cts.map +1 -0
  80. package/dist/services/goal/parser.d.mts +24 -0
  81. package/dist/services/goal/parser.d.mts.map +1 -0
  82. package/dist/services/goal/parser.mjs +2 -0
  83. package/dist/services/goal/parser.mjs.map +1 -0
  84. package/dist/services/goal/prompts.cjs +3 -0
  85. package/dist/services/goal/prompts.cjs.map +1 -0
  86. package/dist/services/goal/prompts.d.cts +23 -0
  87. package/dist/services/goal/prompts.d.cts.map +1 -0
  88. package/dist/services/goal/prompts.d.mts +23 -0
  89. package/dist/services/goal/prompts.d.mts.map +1 -0
  90. package/dist/services/goal/prompts.mjs +3 -0
  91. package/dist/services/goal/prompts.mjs.map +1 -0
  92. package/dist/services/goal/queue.cjs +2 -0
  93. package/dist/services/goal/queue.cjs.map +1 -0
  94. package/dist/services/goal/queue.d.cts +19 -0
  95. package/dist/services/goal/queue.d.cts.map +1 -0
  96. package/dist/services/goal/queue.d.mts +19 -0
  97. package/dist/services/goal/queue.d.mts.map +1 -0
  98. package/dist/services/goal/queue.mjs +2 -0
  99. package/dist/services/goal/queue.mjs.map +1 -0
  100. package/dist/services/goal/runtime.cjs +2 -0
  101. package/dist/services/goal/runtime.cjs.map +1 -0
  102. package/dist/services/goal/runtime.d.cts +31 -0
  103. package/dist/services/goal/runtime.d.cts.map +1 -0
  104. package/dist/services/goal/runtime.d.mts +31 -0
  105. package/dist/services/goal/runtime.d.mts.map +1 -0
  106. package/dist/services/goal/runtime.mjs +2 -0
  107. package/dist/services/goal/runtime.mjs.map +1 -0
  108. package/dist/services/goal/safety.cjs +3 -0
  109. package/dist/services/goal/safety.cjs.map +1 -0
  110. package/dist/services/goal/safety.d.cts +18 -0
  111. package/dist/services/goal/safety.d.cts.map +1 -0
  112. package/dist/services/goal/safety.d.mts +18 -0
  113. package/dist/services/goal/safety.d.mts.map +1 -0
  114. package/dist/services/goal/safety.mjs +3 -0
  115. package/dist/services/goal/safety.mjs.map +1 -0
  116. package/dist/services/goal/settings.cjs +2 -0
  117. package/dist/services/goal/settings.cjs.map +1 -0
  118. package/dist/services/goal/settings.d.cts +24 -0
  119. package/dist/services/goal/settings.d.cts.map +1 -0
  120. package/dist/services/goal/settings.d.mts +24 -0
  121. package/dist/services/goal/settings.d.mts.map +1 -0
  122. package/dist/services/goal/settings.mjs +2 -0
  123. package/dist/services/goal/settings.mjs.map +1 -0
  124. package/dist/services/goal/stateCodec.cjs +2 -0
  125. package/dist/services/goal/stateCodec.cjs.map +1 -0
  126. package/dist/services/goal/stateCodec.d.cts +22 -0
  127. package/dist/services/goal/stateCodec.d.cts.map +1 -0
  128. package/dist/services/goal/stateCodec.d.mts +22 -0
  129. package/dist/services/goal/stateCodec.d.mts.map +1 -0
  130. package/dist/services/goal/stateCodec.mjs +2 -0
  131. package/dist/services/goal/stateCodec.mjs.map +1 -0
  132. package/dist/services/goal/stateMachine.cjs +3 -0
  133. package/dist/services/goal/stateMachine.cjs.map +1 -0
  134. package/dist/services/goal/stateMachine.d.cts +25 -0
  135. package/dist/services/goal/stateMachine.d.cts.map +1 -0
  136. package/dist/services/goal/stateMachine.d.mts +25 -0
  137. package/dist/services/goal/stateMachine.d.mts.map +1 -0
  138. package/dist/services/goal/stateMachine.mjs +3 -0
  139. package/dist/services/goal/stateMachine.mjs.map +1 -0
  140. package/dist/services/goal/tools.cjs +2 -0
  141. package/dist/services/goal/tools.cjs.map +1 -0
  142. package/dist/services/goal/tools.d.cts +29 -0
  143. package/dist/services/goal/tools.d.cts.map +1 -0
  144. package/dist/services/goal/tools.d.mts +29 -0
  145. package/dist/services/goal/tools.d.mts.map +1 -0
  146. package/dist/services/goal/tools.mjs +2 -0
  147. package/dist/services/goal/tools.mjs.map +1 -0
  148. package/dist/services/history/historyService.cjs +2 -0
  149. package/dist/services/history/historyService.cjs.map +1 -0
  150. package/dist/services/history/historyService.mjs +2 -0
  151. package/dist/services/history/historyService.mjs.map +1 -0
  152. package/dist/tui/goalHistoryOverlay.cjs +3 -0
  153. package/dist/tui/goalHistoryOverlay.cjs.map +1 -0
  154. package/dist/tui/goalHistoryOverlay.mjs +3 -0
  155. package/dist/tui/goalHistoryOverlay.mjs.map +1 -0
  156. package/dist/types/extension.d.cts +17 -0
  157. package/dist/types/extension.d.cts.map +1 -0
  158. package/dist/types/extension.d.mts +17 -0
  159. package/dist/types/extension.d.mts.map +1 -0
  160. package/dist/types/goal.cjs +2 -0
  161. package/dist/types/goal.cjs.map +1 -0
  162. package/dist/types/goal.d.cts +57 -0
  163. package/dist/types/goal.d.cts.map +1 -0
  164. package/dist/types/goal.d.mts +57 -0
  165. package/dist/types/goal.d.mts.map +1 -0
  166. package/dist/types/goal.mjs +2 -0
  167. package/dist/types/goal.mjs.map +1 -0
  168. package/dist/types/history.d.cts +27 -0
  169. package/dist/types/history.d.cts.map +1 -0
  170. package/dist/types/history.d.mts +27 -0
  171. package/dist/types/history.d.mts.map +1 -0
  172. package/dist/types/ports.d.cts +19 -0
  173. package/dist/types/ports.d.cts.map +1 -0
  174. package/dist/types/ports.d.mts +19 -0
  175. package/dist/types/ports.d.mts.map +1 -0
  176. package/dist/types/settings.d.cts +6 -0
  177. package/dist/types/settings.d.cts.map +1 -0
  178. package/dist/types/settings.d.mts +6 -0
  179. package/dist/types/settings.d.mts.map +1 -0
  180. package/package.json +79 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"goalManager.d.cts","names":[],"sources":["../../../src/adapters/pi/goalManager.ts"],"mappings":";;;;;cA6Fa;mBACM;mBACA;mBACA;mBACA;UACT;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;mBACS;EAEL,YAAA,IAAI,cAAc,eAAe,2BAA2B,uBAAuB;EASxF,YAAY;EAIN,gBAAgB,KAAK,mBAAmB;EAgBxC,cAAc,KAAK,mBAAmB;EAKtC,eAAe,KAAK,mBAAmB;EAKvC,YAAY,KAAK,mBAAmB,QAAQ;EAK5C,mBAAmB,YAAY,KAAK,mBAAmB;EAgBvD,cAAc,YAAY,KAAK,mBAAmB;UAcjD;EAKd;UAmEQ;UAiCA;UAeM;UAsCN;UAQM;UAWN;UAIA;UASA;UAgBA;UASA;UAYA;UASA;UAgBA;UAoBM;UAmBN;UAQA;UAYA;UAIA;UASM;UAiDN;UAWM;UA4CN;UAqBM;UAoCA;UAgBA;UAyBA;UA2BA;UAmBN;UAcM;UAyBA;UA0DA;UAoFA;UAkCN;UAaA;UA8BA;UAWM;UAgCA;UAuBN;UAYM;UAmCA;UASA;UAUA;UAoBN"}
@@ -0,0 +1,86 @@
1
+ import { GoalHistoryEntry } from "../../types/history.mjs";
2
+ import { GoalExtensionDependencies, GoalExtensionService } from "../../types/extension.mjs";
3
+ import { GoalRuntimeSnapshot } from "../../types/goal.mjs";
4
+ import { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
5
+ //#region src/adapters/pi/goalManager.d.ts
6
+ declare class GoalPiManager {
7
+ private readonly pi;
8
+ private readonly runtime;
9
+ private readonly dependencies?;
10
+ private readonly legacyCommandService?;
11
+ private context?;
12
+ private sessionId?;
13
+ private generation;
14
+ private operations;
15
+ private settings;
16
+ private history?;
17
+ private runGoalId?;
18
+ private runOrigin?;
19
+ private runExecutionGeneration?;
20
+ private pendingRunOrigin;
21
+ private lastToolCallGoalId?;
22
+ private lastToolCallGeneration?;
23
+ private executionGeneration;
24
+ private compactState?;
25
+ private budgetWrapUpGoalId?;
26
+ private lastGoalId?;
27
+ private runToolAttempted;
28
+ private disposed;
29
+ private readonly disposers;
30
+ constructor(pi: ExtensionAPI, dependencies?: GoalExtensionDependencies, legacyCommandService?: GoalExtensionService);
31
+ snapshot(): GoalRuntimeSnapshot;
32
+ startFromLeader(ctx: ExtensionContext): Promise<void>;
33
+ endFromLeader(ctx: ExtensionContext): Promise<void>;
34
+ showFromLeader(ctx: ExtensionContext): Promise<void>;
35
+ listHistory(ctx: ExtensionContext): Promise<GoalHistoryEntry[]>;
36
+ restartFromHistory(id: string, ctx: ExtensionContext): Promise<void>;
37
+ removeHistory(id: string, ctx: ExtensionContext): Promise<void>;
38
+ private ensureSession;
39
+ register(): () => void;
40
+ private registerTools;
41
+ private registerRpc;
42
+ private startSession;
43
+ private createHistory;
44
+ private loadSettings;
45
+ private isCurrent;
46
+ private enqueue;
47
+ private activateTools;
48
+ private deactivateTools;
49
+ private fenceExecution;
50
+ private noteToolCall;
51
+ private pauseForToolPolicyDrift;
52
+ private beforeCompact;
53
+ private afterCompact;
54
+ private refreshStatus;
55
+ private emitState;
56
+ private notify;
57
+ private abortCurrentTurn;
58
+ private executeCommand;
59
+ private showStatus;
60
+ private startGoal;
61
+ private pauseGoal;
62
+ private resumeGoal;
63
+ private clearGoal;
64
+ private editGoal;
65
+ private addGoal;
66
+ private prioritizeGoal;
67
+ private dropLastGoal;
68
+ private skipGoal;
69
+ private finishAgentRun;
70
+ private dispatchPendingQueueAction;
71
+ private continueAfterSettled;
72
+ private pauseForSafety;
73
+ private limitForBudget;
74
+ private pauseForDeliveryFailure;
75
+ private complete;
76
+ private blocked;
77
+ private acceptsToolCall;
78
+ private handleRpcStart;
79
+ private handleRpcPause;
80
+ private archiveAll;
81
+ private archive;
82
+ private dispose;
83
+ }
84
+ //#endregion
85
+ export { GoalPiManager };
86
+ //# sourceMappingURL=goalManager.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"goalManager.d.mts","names":[],"sources":["../../../src/adapters/pi/goalManager.ts"],"mappings":";;;;;cA6Fa;mBACM;mBACA;mBACA;mBACA;UACT;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;mBACS;EAEL,YAAA,IAAI,cAAc,eAAe,2BAA2B,uBAAuB;EASxF,YAAY;EAIN,gBAAgB,KAAK,mBAAmB;EAgBxC,cAAc,KAAK,mBAAmB;EAKtC,eAAe,KAAK,mBAAmB;EAKvC,YAAY,KAAK,mBAAmB,QAAQ;EAK5C,mBAAmB,YAAY,KAAK,mBAAmB;EAgBvD,cAAc,YAAY,KAAK,mBAAmB;UAcjD;EAKd;UAmEQ;UAiCA;UAeM;UAsCN;UAQM;UAWN;UAIA;UASA;UAgBA;UASA;UAYA;UASA;UAgBA;UAoBM;UAmBN;UAQA;UAYA;UAIA;UASM;UAiDN;UAWM;UA4CN;UAqBM;UAoCA;UAgBA;UAyBA;UA2BA;UAmBN;UAcM;UAyBA;UA0DA;UAoFA;UAkCN;UAaA;UA8BA;UAWM;UAgCA;UAuBN;UAYM;UAmCA;UASA;UAUA;UAoBN"}
@@ -0,0 +1,2 @@
1
+ import{currentTokenTotal as e,updateGoalUsage as t}from"../../services/goal/accounting.mjs";import{parseGoalCommand as n,validateObjective as r}from"../../services/goal/parser.mjs";import{buildContinuePrompt as i,buildGoalPrompt as a,buildGoalSystemPrompt as o,buildObjectiveUpdatedPrompt as s,buildResumePrompt as c}from"../../services/goal/prompts.mjs";import{createGoal as l,formatStatus as u,incrementGoal as d,isContradictoryCompletionSummary as f,isResumableGoalStatus as p,transitionGoal as m}from"../../services/goal/stateMachine.mjs";import{enqueueGoal as h,promoteNextGoal as g,skipCurrentGoal as _}from"../../services/goal/queue.mjs";import{loadGoalStateFromSession as v}from"../../services/goal/stateCodec.mjs";import{GoalRuntimeModel as y}from"../../services/goal/runtime.mjs";import{nextToolFreeRepeatState as b,resetGoalSafetyEpoch as x,safetyLimitReached as S}from"../../services/goal/safety.mjs";import{DEFAULT_GOAL_SETTINGS as C,normalizeGoalSettings as w}from"../../services/goal/settings.mjs";import{validateBlockedInput as T,validateCompletionInput as E}from"../../services/goal/tools.mjs";import{GoalHistoryService as D}from"../../services/history/historyService.mjs";import{createGoalHistoryStore as O}from"../node/historyStore.mjs";import{canExecuteGoalTools as k,reconcileGoalTools as A,removeGoalTools as j}from"./toolVisibility.mjs";import{getAgentDir as M}from"@earendil-works/pi-coding-agent";const N=`goal_complete`,P=`goal_blocked`,F={type:`object`,properties:{goal_id:{type:`string`,minLength:1},summary:{type:`string`,minLength:1}},required:[`goal_id`,`summary`],additionalProperties:!1},I={type:`object`,properties:{goal_id:{type:`string`,minLength:1},reason:{type:`string`,minLength:1},evidence:{type:`string`,minLength:1},repeated_turns:{type:`integer`,minimum:3}},required:[`goal_id`,`reason`,`evidence`,`repeated_turns`],additionalProperties:!1};function L(e,t=!1){return{content:[{type:`text`,text:e}],details:{error:t}}}function R(e){return e instanceof Error?e.message:String(e)}function z(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}var B=class{pi;runtime;dependencies;legacyCommandService;context;sessionId;generation=0;operations=Promise.resolve();settings=C;history;runGoalId;runOrigin;runExecutionGeneration;pendingRunOrigin=`manual`;lastToolCallGoalId;lastToolCallGeneration;executionGeneration=0;compactState;budgetWrapUpGoalId;lastGoalId;runToolAttempted=!1;disposed=!1;disposers=[];constructor(e,t,n){this.pi=e,this.dependencies=t,this.legacyCommandService=n,this.runtime=new y({persist:e=>this.pi.appendEntry(`goal-state`,e)})}snapshot(){return this.runtime.snapshot()}async startFromLeader(e){if(!e.hasUI||e.mode!==`tui`){this.notify(`Goal leader actions require the Doom TUI.`,`warning`);return}e.ui.getEditorText().length>0&&!await e.ui.confirm(`Replace editor draft?`,`Goal start will replace the current draft with /goal .`)||e.ui.setEditorText(`/goal `)}async endFromLeader(e){await this.ensureSession(e),await this.enqueue(()=>this.clearGoal(e))}async showFromLeader(e){await this.ensureSession(e),this.showStatus()}async listHistory(e){return await this.ensureSession(e),await this.history?.list()??[]}async restartFromHistory(e,t){if(await this.ensureSession(t),!this.history){this.notify(`Goal history is unavailable.`,`error`);return}try{let n=await this.history.restart(e);await this.enqueue(()=>this.startGoal(n.objective,n.budget,t,n.goalId))}catch(e){this.notify(`Goal history restart failed: ${R(e)}`,`error`)}}async removeHistory(e,t){if(await this.ensureSession(t),!this.history){this.notify(`Goal history is unavailable.`,`error`);return}try{await this.history.remove(e),this.notify(`Goal history entry removed.`,`info`)}catch(e){this.notify(`Goal history removal failed: ${R(e)}`,`error`)}}async ensureSession(e){this.isCurrent(e)||await this.enqueue(()=>this.startSession(e))}register(){return typeof this.pi.registerTool==`function`&&this.registerTools(),this.pi.registerCommand(`goal`,{description:`Manage persistent goal execution`,handler:(e,t)=>this.enqueue(()=>this.executeCommand(e,t))}),this.disposers.push(this.registerRpc()),this.pi.on(`session_start`,(e,t)=>{this.enqueue(()=>this.startSession(t))}),this.pi.on(`session_shutdown`,()=>{this.fenceExecution(),this.generation+=1,this.context=void 0,this.sessionId=void 0,this.runGoalId=void 0,this.runOrigin=void 0,this.runExecutionGeneration=void 0,this.runToolAttempted=!1,this.compactState=void 0,this.deactivateTools()}),this.pi.on(`before_agent_start`,(e,t)=>{if(!this.isCurrent(t))return;let n=this.runtime.snapshot().goal;if(!n||n.status!==`active`)return;if(!k(this.pi,n)){this.pauseForToolPolicyDrift(t,n);return}let r=o(n);return{systemPrompt:`${e.systemPrompt}\n\n${r}`}}),this.pi.on(`agent_start`,(e,t)=>{if(!this.isCurrent(t))return;let n=this.runtime.snapshot().goal;this.runGoalId=n?.status===`active`?n.id:void 0,this.runOrigin=this.runGoalId?this.pendingRunOrigin:void 0,this.runExecutionGeneration=this.runGoalId?this.executionGeneration:void 0,this.pendingRunOrigin=`manual`,this.runToolAttempted=!1}),this.pi.on(`tool_call`,(e,t)=>{this.isCurrent(t)&&this.noteToolCall(e.toolName)}),this.pi.on(`tool_execution_start`,(e,t)=>{this.isCurrent(t)&&this.noteToolCall(e.toolName)}),this.pi.on(`agent_end`,(e,t)=>{this.enqueue(()=>this.finishAgentRun(e,t))}),this.pi.on(`agent_settled`,(e,t)=>{this.enqueue(async()=>{await this.dispatchPendingQueueAction(t)||await this.continueAfterSettled(t)})}),this.pi.on(`session_before_compact`,(e,t)=>this.beforeCompact(e,t)),this.pi.on(`session_compact`,(e,t)=>{this.enqueue(()=>this.afterCompact(e,t))}),()=>this.dispose()}registerTools(){let e={name:N,label:`Goal complete`,description:`Mark the active Goal complete after verifying every requirement.`,promptSnippet:`Complete an active Goal after authoritative verification.`,parameters:F,execute:async(e,t,n,r,i)=>this.enqueue(()=>this.complete(t,i))},t={name:P,label:`Goal blocked`,description:`Mark the active Goal blocked after the same external blocker recurs with evidence.`,promptSnippet:`Report a repeated external blocker for the active Goal.`,parameters:I,execute:async(e,t,n,r,i)=>this.enqueue(()=>this.blocked(t,i))};this.pi.registerTool(e),this.pi.registerTool(t)}registerRpc(){let e=this.pi.events;if(typeof e.on!=`function`)return()=>void 0;let t=e.on(`pi-goal:rpc:start`,e=>{this.enqueue(()=>this.handleRpcStart(e))}),n=e.on(`pi-goal:rpc:pause`,e=>{this.enqueue(()=>this.handleRpcPause(e))});return()=>{t(),n()}}async startSession(e){this.fenceExecution(),this.generation+=1;let t=this.generation;this.context=e,this.sessionId=e.sessionManager.getSessionId(),this.runGoalId=void 0,this.runOrigin=void 0,this.runExecutionGeneration=void 0,this.runToolAttempted=!1,this.pendingRunOrigin=`manual`,this.budgetWrapUpGoalId=void 0,this.settings=await this.loadSettings(),this.history=this.dependencies?.history??this.createHistory(e.cwd);let n=v({sessionManager:e.sessionManager});this.runtime.load(n),this.deactivateTools();let r=this.runtime.snapshot().goal;n.hasExperimentalQueueState&&!this.settings.experimental.goals&&r?.status===`active`&&(r=m({...r},`paused`),this.runtime.replaceState({goal:r,queue:[...this.runtime.snapshot().queue],pendingAction:this.runtime.snapshot().pendingAction})),r?.status===`active`&&(this.activateTools(r)||(this.runtime.replaceState({goal:m(r,`paused`),queue:[...this.runtime.snapshot().queue]}),this.notify(`Goal paused because host policy does not expose both Goal tools.`,`warning`))),t===this.generation&&(this.refreshStatus(),this.emitState())}createHistory(e){try{return new D(O(e))}catch{return}}async loadSettings(){try{let e=await import(`node:fs/promises`),t=await import(`node:path`),n=JSON.parse(await e.readFile(t.join(M(),`pi-goal.json`),`utf8`));return w(n)??C}catch{return C}}isCurrent(e){return!this.disposed&&this.context===e&&this.sessionId===e.sessionManager.getSessionId()}enqueue(e){let t=this.operations.then(e,e);return this.operations=t.then(()=>void 0,()=>void 0),t}activateTools(e){if(typeof this.pi.getActiveTools!=`function`||typeof this.pi.setActiveTools!=`function`)return!1;let t=this.pi.getActiveTools(),n=A(this.pi,e);return(e.status===`budget_limited`?[N]:[N,P]).every(e=>n.activeTools.includes(e))?(this.executionGeneration+=1,this.lastToolCallGoalId=void 0,this.lastToolCallGeneration=void 0,!0):(this.pi.setActiveTools(t),!1)}deactivateTools(){typeof this.pi.getActiveTools==`function`&&typeof this.pi.setActiveTools==`function`&&j(this.pi),this.executionGeneration+=1,this.lastToolCallGoalId=void 0,this.lastToolCallGeneration=void 0}fenceExecution(){this.executionGeneration+=1,this.runGoalId=void 0,this.runOrigin=void 0,this.runExecutionGeneration=void 0,this.runToolAttempted=!1,this.lastToolCallGoalId=void 0,this.lastToolCallGeneration=void 0,this.compactState=void 0,this.budgetWrapUpGoalId=void 0}noteToolCall(e){if(e!==N&&e!==P)return;this.runToolAttempted=!0;let t=this.runtime.snapshot().goal;t&&(this.lastToolCallGoalId=t.id,this.lastToolCallGeneration=this.executionGeneration)}pauseForToolPolicyDrift(e,n){if(!this.isCurrent(e)||this.runtime.snapshot().goal?.id!==n.id||n.status!==`active`)return;t(n,e,Date.now(),!1),this.fenceExecution();let r=m({...n},`paused`);this.runtime.replaceState({goal:r,queue:[...this.runtime.snapshot().queue]}),this.deactivateTools(),this.abortCurrentTurn(e),this.refreshStatus(),this.emitState(`required Goal tool unavailable`),this.notify(`Goal tools are unavailable, so the Goal was paused. Restore the tools and run /goal resume.`,`warning`)}beforeCompact(e,t){if(!this.isCurrent(t))return;let n=this.runtime.snapshot().goal;!n||n.status!==`active`||(this.compactState={goalId:n.id,hadAutomaticRun:this.runOrigin===`automatic`&&this.runGoalId===n.id,willRetry:e.willRetry===!0},this.executionGeneration+=1,this.runGoalId=void 0,this.runOrigin=void 0,this.runExecutionGeneration=void 0,this.lastToolCallGoalId=void 0,this.lastToolCallGeneration=void 0)}async afterCompact(e,t){if(!this.isCurrent(t))return;let n=this.compactState;if(!n)return;let r=this.runtime.snapshot().goal;this.compactState=void 0,!(!r||r.id!==n.goalId||r.status!==`active`)&&(this.executionGeneration+=1,this.runToolAttempted=!1,!n.willRetry&&n.hadAutomaticRun&&e.willRetry!==!0&&(this.pendingRunOrigin=`automatic`,this.runGoalId=r.id,this.runOrigin=`automatic`,this.runExecutionGeneration=this.executionGeneration))}refreshStatus(){let e=this.context,t=this.runtime.snapshot();if(!e?.hasUI)return;let n=t.pendingAction!==void 0||!t.goal&&t.queue.length>0;e.ui.setStatus(`goal`,n?`queued`:u(t.goal))}emitState(e,t){let n=this.runtime.snapshot().goal,r=n?.status??`cleared`;this.lastGoalId=n?.id??this.lastGoalId,this.pi.events.emit(`pi-goal:state`,{goalId:n?.id??this.lastGoalId??``,status:r,...e?{reason:e}:{},...t?{summary:t}:{}})}notify(e,t=`info`){this.context?.hasUI&&this.context.ui.notify(e,t)}abortCurrentTurn(e){try{return e.abort(),!0}catch{return!1}}async executeCommand(e,t){let r=Object.hasOwn(t,`sessionManager`);if(!e.trim()&&this.legacyCommandService&&!r){let e=await this.legacyCommandService.execute();t.hasUI&&t.ui.notify(e.message,e.level);return}this.isCurrent(t)||await this.startSession(t);let i=n(e,{experimentalGoals:this.settings.experimental.goals});if(typeof i==`string`){this.notify(i,`warning`);return}switch(i.kind){case`show`:this.showStatus();return;case`start`:await this.startGoal(i.objective??``,i.tokenBudget,t);return;case`pause`:this.pauseGoal(t);return;case`resume`:await this.resumeGoal(t);return;case`clear`:await this.clearGoal(t);return;case`edit`:await this.editGoal(i.objective??``,i.tokenBudget,t);return;case`add`:await this.addGoal(i.objective??``,i.tokenBudget,t);return;case`prioritize`:await this.prioritizeGoal(i.objective??``,i.tokenBudget,t);return;case`drop-last`:this.dropLastGoal(t);return;case`skip`:await this.skipGoal(t);return}}showStatus(){let e=this.runtime.snapshot(),t=e.goal;if(!t){this.notify(`No active goal.`,`info`);return}let n=e.queue.length?`\nQueued: ${e.queue.map(e=>e.text).join(`, `)}`:``;this.notify(`Goal: ${t.text}\nStatus: ${t.status}${n}`,`info`)}async startGoal(t,n,i,o){let s=r(t);if(s){this.notify(s,`warning`);return}let c=this.runtime.snapshot(),u=c.goal&&c.goal.status!==`complete`?c.goal:void 0;if(u){if(!await i.ui.confirm(`Replace goal?`,`Current goal: ${u.text}\n\nNew goal: ${t}`))return;if(!await this.archiveAll([u,...c.queue],`replaced`)){this.notify(`Goal replacement aborted because history archival failed.`,`error`);return}}let d=l(t,n,{id:o,baselineTokens:e(i)});if(!this.activateTools(d)){this.notify(`Cannot start /goal: host policy rejected Goal tools.`,`error`);return}this.runtime.replaceState({goal:d,queue:[]}),this.budgetWrapUpGoalId=void 0,this.pendingRunOrigin=`manual`,this.refreshStatus(),this.emitState();try{this.pi.sendUserMessage(a(d),{deliverAs:`followUp`})}catch(e){this.runtime.replaceState({goal:u,queue:c.queue}),this.fenceExecution(),u||this.deactivateTools(),this.refreshStatus(),this.notify(`Goal kickoff failed: ${R(e)}`,`error`);return}this.notify(u?`Goal replaced: ${t}`:`Goal started: ${t}`)}pauseGoal(e){let n=this.runtime.snapshot().goal;if(!n){this.notify(`No active goal.`);return}if(n.status!==`active`){this.notify(`Goal is ${n.status}; only active goals can be paused.`,`warning`);return}t(n,e,Date.now(),!1),this.fenceExecution();let r=m({...n},`paused`);this.runtime.replaceState({goal:r,queue:[...this.runtime.snapshot().queue]}),this.deactivateTools(),e.abort(),this.refreshStatus(),this.emitState(`paused`),this.notify(`Goal paused: ${n.text}`)}async resumeGoal(e){let t=this.runtime.snapshot().goal;if(!t){this.notify(`No active goal.`);return}if(!p(t.status)){this.notify(`Goal is ${t.status}; it cannot be resumed.`,`warning`);return}if(t.tokenBudget!==void 0&&t.tokensUsed>=t.tokenBudget){this.notify(`Goal token budget is still reached.`,`warning`);return}let n=x(m({...t,updatedAt:Date.now()},`active`));if(!this.activateTools(n)){this.notify(`Cannot resume /goal: host policy rejected Goal tools.`,`error`);return}this.runtime.replaceState({goal:n,queue:[...this.runtime.snapshot().queue]}),this.budgetWrapUpGoalId=void 0,this.pendingRunOrigin=`manual`,this.refreshStatus(),this.emitState();try{this.pi.sendUserMessage(c(n,t.status),{deliverAs:`followUp`})}catch(e){this.fenceExecution(),this.runtime.replaceState({goal:t,queue:[...this.runtime.snapshot().queue]}),this.deactivateTools(),this.refreshStatus(),this.notify(`Goal resume failed: ${R(e)}`,`error`)}}async clearGoal(e){let t=this.runtime.snapshot();if(!await this.archiveAll([...t.goal?[t.goal]:[],...t.queue],`cleared`)){this.notify(`Goal clear aborted because history archival failed.`,`error`);return}this.fenceExecution(),this.runtime.clear(),this.deactivateTools(),e.abort(),this.refreshStatus(),this.emitState(`cleared`),t.goal?this.notify(`Goal cleared: ${t.goal.text}`,`warning`):this.notify(`No active goal.`,`info`)}async editGoal(e,t,n){let i=r(e);if(i){this.notify(i,`warning`);return}let a=this.runtime.snapshot().goal;if(!a){this.notify(`No active goal. Use /goal <objective> to start one.`,`warning`);return}let o={...a,text:e,...t===void 0?{}:{tokenBudget:t},updatedAt:Date.now()};this.runtime.replaceState({goal:o,queue:[...this.runtime.snapshot().queue]}),this.refreshStatus(),this.emitState(),a.status===`active`?this.pi.sendUserMessage(s(o),{deliverAs:`followUp`}):this.notify(`Goal updated but remains ${a.status}. Resume explicitly to execute it.`)}async addGoal(e,t,n){let i=r(e);if(i){this.notify(i,`warning`);return}let a=this.runtime.snapshot();if(!a.goal){await this.startGoal(e,t,this.context);return}let o=h({goal:a.goal,queue:[...a.queue],pendingAction:a.pendingAction,enabled:this.settings.experimental.goals},e,t);this.runtime.replaceState(o),this.refreshStatus(),this.emitState(),this.notify(`Goal added at position ${o.queue.length+1}: ${e}`)}async prioritizeGoal(e,t,n){let i=r(e);if(i){this.notify(i,`warning`);return}let a=this.runtime.snapshot();if(!a.goal){await this.startGoal(e,t,this.context);return}this.runtime.replaceState({goal:a.goal,queue:[...a.queue],pendingAction:{kind:`prioritize`,objective:e,tokenBudget:t}}),this.notify(`Priority goal queued until the current turn settles: ${e}`)}dropLastGoal(e){let t=this.runtime.snapshot();if(!t.queue.length){this.notify(`No queued goals.`,`info`);return}this.runtime.replaceState({goal:t.goal,queue:[...t.queue].slice(0,-1),pendingAction:t.pendingAction}),this.notify(`Last queued goal dropped.`,`warning`)}async skipGoal(e){let t=this.runtime.snapshot();if(!t.goal){this.notify(`No goals to skip.`,`info`);return}if(!await this.archive(t.goal,`skipped`)){this.notify(`Goal skip aborted because history archival failed.`,`error`);return}this.fenceExecution();let n=_({goal:t.goal,queue:[...t.queue],pendingAction:t.pendingAction,enabled:this.settings.experimental.goals});n.pendingAction?this.runtime.replaceState(n):this.runtime.clear(),this.deactivateTools(),e.abort(),this.refreshStatus(),this.emitState(`skipped`)}async finishAgentRun(e,n){if(!this.isCurrent(n))return;let r=this.runtime.snapshot(),i=r.goal;if(!i||i.status!==`active`)return;if(this.runGoalId!==i.id||this.runExecutionGeneration!==this.executionGeneration){this.fenceExecution();return}let a=e.messages??[],o=V(a);if(t(i,n,Date.now(),!0),o===`aborted`){this.fenceExecution(),this.runtime.replaceState({goal:i,queue:[...r.queue]}),this.refreshStatus();return}if(o===`usage_limited`||o===`blocked`){this.fenceExecution();let e=m({...i},o);this.runtime.replaceState({goal:e,queue:[...r.queue]}),this.deactivateTools(),this.abortCurrentTurn(n),this.refreshStatus(),this.emitState(o===`usage_limited`?`provider usage limit`:`provider error`),this.notify(o===`usage_limited`?`Goal paused because the provider usage limit was reached. Run /goal resume after it resets.`:`Goal blocked because the provider reported a terminal error. Resolve it or run /goal resume.`,`warning`);return}if(this.runOrigin===`automatic`){i.automaticModelTurns=Math.min(2**53-1,i.automaticModelTurns+1);let e=b(i,a,this.runToolAttempted);i.toolFreeRepeatCount=e.toolFreeRepeatCount,i.lastToolFreeOutputFingerprint=e.lastToolFreeOutputFingerprint;let t=S(i,this.settings.continuationLimits);if(t){this.pauseForSafety(n,i,t);return}}if(i.tokenBudget!==void 0&&i.tokensUsed>=i.tokenBudget){this.limitForBudget(n,i,r.queue);return}this.runtime.replaceState({goal:i,queue:[...r.queue]}),this.refreshStatus()}async dispatchPendingQueueAction(n){if(!this.isCurrent(n))return!1;let r=this.runtime.snapshot(),i=r.pendingAction;if(!i)return!1;if(!this.settings.experimental.goals||!n.isIdle()||n.hasPendingMessages())return!0;if(i.kind===`prioritize`){let o=r.goal;if(!o)return this.runtime.replaceState({queue:[...r.queue]}),await this.startGoal(i.objective,i.tokenBudget,n),!0;o.status===`active`&&t(o,n,Date.now(),!1);let s=l(i.objective,i.tokenBudget,{baselineTokens:e(n)}),c=o.status===`complete`?[...r.queue]:[m({...o,activeStartedAt:void 0},`queued`),...r.queue];if(this.deactivateTools(),!this.activateTools(s)){let e=m(s,`paused`);return this.runtime.replaceState({goal:e,queue:c}),this.deactivateTools(),this.refreshStatus(),this.emitState(`queued goal tools unavailable`),this.notify(`Priority Goal is retained but paused because host policy rejected Goal tools.`,`warning`),!0}this.runtime.replaceState({goal:s,queue:c}),this.pendingRunOrigin=`manual`,this.refreshStatus(),this.emitState(`prioritized`);try{this.pi.sendUserMessage(a(s),{deliverAs:`followUp`})}catch(e){this.pauseForDeliveryFailure(n,s,`Priority Goal kickoff failed: ${R(e)}`)}return!0}let o=r.goal;if(!o||o.id!==i.goalId||i.reason===`complete`&&o.status!==`complete`)return this.runtime.replaceState({goal:o,queue:[...r.queue]}),this.refreshStatus(),!0;let s=g({goal:o,queue:[...r.queue],pendingAction:i,enabled:!0},Date.now(),e(n)),c=s.goal;if(!c||c.id===o.id)return this.runtime.clear(),this.deactivateTools(),this.refreshStatus(),this.emitState(i.reason),!0;if(!this.activateTools(c)){let e=m(c,`paused`);return this.runtime.replaceState({goal:e,queue:[...s.queue]}),this.deactivateTools(),this.refreshStatus(),this.emitState(`queued goal tools unavailable`),this.notify(`Next Goal is retained but paused because host policy rejected Goal tools.`,`warning`),!0}this.runtime.replaceState({goal:c,queue:[...s.queue]}),this.pendingRunOrigin=`manual`,this.refreshStatus(),this.emitState(i.reason);try{this.pi.sendUserMessage(a(c),{deliverAs:`followUp`})}catch(e){this.pauseForDeliveryFailure(n,c,`Queued Goal kickoff failed: ${R(e)}`)}return!0}async continueAfterSettled(e){if(!this.isCurrent(e)||!e.isIdle()||e.hasPendingMessages())return;let t=this.runtime.snapshot(),n=t.goal;if(!n||n.status!==`active`||!this.runGoalId||this.runGoalId!==n.id)return;if(this.runExecutionGeneration!==this.executionGeneration){this.fenceExecution();return}if(!k(this.pi,n)){this.pauseForToolPolicyDrift(e,n);return}let r=S(n,this.settings.continuationLimits);if(r){this.pauseForSafety(e,n,r);return}let a=d({...n});this.runtime.replaceState({goal:a,queue:[...t.queue]});let o=i(a);this.pendingRunOrigin=`automatic`;try{this.pi.sendUserMessage(o,{deliverAs:`followUp`})}catch(t){this.pauseForDeliveryFailure(e,a,`Goal continuation failed: ${R(t)}`);return}this.runGoalId=void 0,this.runOrigin=void 0,this.runExecutionGeneration=void 0,this.runToolAttempted=!1}pauseForSafety(e,t,n){if(this.runtime.snapshot().goal?.id!==t.id)return;this.fenceExecution();let r=m({...t,safetyPauseCause:n},`paused`);this.runtime.replaceState({goal:r,queue:[...this.runtime.snapshot().queue]}),this.deactivateTools(),this.abortCurrentTurn(e),this.refreshStatus(),this.emitState(n===`continuation_limit`?`automatic response limit`:`no progress`);let i=n===`continuation_limit`?`automatic response limit`:`no progress`;this.notify(`Goal paused by safety limit: ${i}. Run /goal resume to continue.`,`warning`)}limitForBudget(e,t,n){this.fenceExecution();let r=m({...t},`budget_limited`);this.runtime.replaceState({goal:r,queue:[...n]}),this.deactivateTools();let i=this.activateTools(r);if(i&&this.budgetWrapUpGoalId!==r.id){this.budgetWrapUpGoalId=r.id;try{this.pi.sendMessage({customType:`goal-budget-wrap-up`,content:`The Goal token budget is exhausted. Stop substantive work, summarize verified progress and blockers, and call goal_complete only if every requirement is already proven.`,display:!0,details:{goalId:r.id}},{deliverAs:`steer`})}catch(e){this.budgetWrapUpGoalId=void 0,this.notify(`Goal budget wrap-up failed: ${R(e)}`,`error`)}}i||this.notify(`Goal budget reached, but host policy rejected goal_complete.`,`warning`),this.abortCurrentTurn(e),this.refreshStatus(),this.emitState(`token budget reached`)}pauseForDeliveryFailure(e,t,n){this.fenceExecution();let r=m({...t},`paused`);this.runtime.replaceState({goal:r,queue:[...this.runtime.snapshot().queue]}),this.deactivateTools(),this.abortCurrentTurn(e),this.refreshStatus(),this.emitState(`delivery failed`),this.notify(n,`error`)}async complete(e,t){let n=this.runtime.snapshot(),r=n.goal;if(!r||!this.acceptsToolCall(t,r))return L(`Goal completion rejected because this tool call belongs to a stale Goal execution.`,!0);let i=E(r,e);if(!r||r.status!==`active`&&r.status!==`budget_limited`)return L(`Goal completion is not available in the current state.`,!0);if(!i.ok)return L(i.reason??`Goal completion rejected.`,!0);let a=typeof e.summary==`string`?e.summary.trim():``;if(f(a))return L(`Completion evidence contradicts completion.`,!0);if(!await this.archive(r,`complete`,a))return L(`Completion aborted because history archival failed.`,!0);this.fenceExecution();let o=m({...r},`complete`);return n.queue.length&&this.settings.experimental.goals?this.runtime.replaceState({goal:o,queue:[...n.queue],pendingAction:{kind:`advance`,goalId:r.id,reason:`complete`,completedText:r.text}}):this.runtime.clear(),this.deactivateTools(),t.abort(),this.refreshStatus(),this.emitState(void 0,a),L(`Goal complete: ${r.text}`)}async blocked(e,t){let n=this.runtime.snapshot(),r=n.goal;if(!r||!this.acceptsToolCall(t,r))return L(`Goal blocker rejected because this tool call belongs to a stale Goal execution.`,!0);let i=T(r,e);if(!r||r.status!==`active`)return L(`Goal blocking is not available in the current state.`,!0);if(!i.ok)return L(i.reason??`Goal blocker rejected.`,!0);let a=typeof e.reason==`string`?e.reason.trim():`blocked`;this.fenceExecution();let o=m({...r},`blocked`);return this.runtime.replaceState({goal:o,queue:[...n.queue]}),this.deactivateTools(),t.abort(),this.refreshStatus(),this.emitState(a),L(`Goal blocked: ${a}`)}acceptsToolCall(e,t){return!this.isCurrent(e)||this.runGoalId&&(this.runGoalId!==t.id||this.runExecutionGeneration!==this.executionGeneration)||this.lastToolCallGoalId&&(this.lastToolCallGoalId!==t.id||this.lastToolCallGeneration!==this.executionGeneration)?!1:k(this.pi,t)}async handleRpcStart(e){let t=z(e),n=typeof t?.requestId==`string`?t.requestId.trim():``,i=this.pi.events;if(!n)return;let a=e=>i.emit(`pi-goal:rpc:start:reply:${n}`,e),o=typeof t?.objective==`string`?t.objective.trim():``,s=r(o);if(s){a({success:!1,error:s});return}if(this.runtime.snapshot().goal){a({success:!1,error:`a goal already exists`});return}let c=this.context;if(!c){a({success:!1,error:`no active pi-goal session context`});return}try{await this.startGoal(o,typeof t?.tokenBudget==`number`?t.tokenBudget:void 0,c);let e=this.runtime.snapshot().goal;a(e?{success:!0,data:{goalId:e.id,status:e.status}}:{success:!1,error:`goal could not be activated`})}catch(e){a({success:!1,error:`goal start failed: ${R(e)}`})}}async handleRpcPause(e){let t=z(e),n=this.runtime.snapshot().goal;if(!n||n.status!==`active`)return;let r=typeof t?.goalId==`string`?t.goalId:void 0;r&&r!==n.id||this.context&&this.pauseGoal(this.context)}async archiveAll(e,t){let n=new Set;for(let r of e)if(!n.has(r.id)&&(n.add(r.id),!await this.archive(r,t)))return!1;return!0}async archive(e,t,n){if(!this.history)return!0;try{return await this.history.archive({id:e.id,objective:e.text,status:t===`complete`?`complete`:e.status,...n?{reason:n}:{reason:t},...e.tokenBudget===void 0?{}:{budget:e.tokenBudget},archivedAt:new Date().toISOString(),startedAt:new Date(e.startedAt).toISOString(),...t===`complete`?{completedAt:new Date().toISOString()}:{}}),!0}catch(e){return this.notify(`Goal history archival failed: ${R(e)}`,`error`),!1}}dispose(){if(!this.disposed){this.disposed=!0,this.generation+=1;for(let e of this.disposers.splice(0))e();this.deactivateTools(),this.context=void 0}}};function V(e){let t=[...e].reverse().find(e=>H(e));if(!t||typeof t!=`object`)return;let n=t;if(n.stopReason===`aborted`)return`aborted`;if(n.stopReason!==`error`&&n.stopReason!==`length`&&n.errorMessage===void 0)return;let r=[n.errorMessage,U(n)].filter(e=>typeof e==`string`).join(` `).toLowerCase();return n.stopReason===`length`||/(?:rate|quota|usage|token|context|capacity|limit|429|too many|billing|exhaust)/u.test(r)?`usage_limited`:`blocked`}function H(e){return!!(e&&typeof e==`object`&&e.role===`assistant`)}function U(e){return typeof e.text==`string`?e.text:typeof e.content==`string`?e.content:Array.isArray(e.content)?e.content.map(e=>{if(!e||typeof e!=`object`)return``;let t=e.text;return typeof t==`string`?t:``}).join(` `):``}export{B as GoalPiManager};
2
+ //# sourceMappingURL=goalManager.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"goalManager.mjs","names":[],"sources":["../../../src/adapters/pi/goalManager.ts"],"sourcesContent":["import type {\n AgentToolResult,\n ExtensionAPI,\n ExtensionCommandContext,\n ExtensionContext,\n ToolDefinition,\n} from '@earendil-works/pi-coding-agent';\nimport { getAgentDir } from '@earendil-works/pi-coding-agent';\nimport { currentTokenTotal, updateGoalUsage } from '../../services/goal/accounting.ts';\nimport { parseGoalCommand, validateObjective } from '../../services/goal/parser.ts';\nimport {\n buildContinuePrompt,\n buildGoalPrompt,\n buildGoalSystemPrompt,\n buildObjectiveUpdatedPrompt,\n buildResumePrompt,\n} from '../../services/goal/prompts.ts';\nimport { enqueueGoal, promoteNextGoal, skipCurrentGoal } from '../../services/goal/queue.ts';\nimport { GoalRuntimeModel } from '../../services/goal/runtime.ts';\nimport { nextToolFreeRepeatState, resetGoalSafetyEpoch, safetyLimitReached } from '../../services/goal/safety.ts';\nimport { DEFAULT_GOAL_SETTINGS, normalizeGoalSettings } from '../../services/goal/settings.ts';\nimport { loadGoalStateFromSession } from '../../services/goal/stateCodec.ts';\nimport {\n createGoal,\n formatStatus,\n incrementGoal,\n isContradictoryCompletionSummary,\n isResumableGoalStatus,\n transitionGoal,\n} from '../../services/goal/stateMachine.ts';\nimport { validateBlockedInput, validateCompletionInput } from '../../services/goal/tools.ts';\nimport { GoalHistoryService } from '../../services/history/historyService.ts';\nimport type { GoalExtensionDependencies, GoalExtensionService } from '../../types/extension.ts';\nimport type { ActiveGoal, GoalRuntimeSnapshot, GoalStateData } from '../../types/goal.ts';\nimport type { GoalHistoryEntry, GoalHistoryPort } from '../../types/history.ts';\nimport { createGoalHistoryStore } from '../node/historyStore.ts';\nimport { canExecuteGoalTools, reconcileGoalTools, removeGoalTools } from './toolVisibility.ts';\n\nconst STATE_EVENT = 'pi-goal:state';\nconst RPC_START = 'pi-goal:rpc:start';\nconst RPC_PAUSE = 'pi-goal:rpc:pause';\nconst COMPLETE_TOOL = 'goal_complete';\nconst BLOCKED_TOOL = 'goal_blocked';\nconst STATUS_KEY = 'goal';\nconst SETTINGS_FILE = 'pi-goal.json';\n\nconst COMPLETE_PARAMETERS = {\n type: 'object',\n properties: {\n goal_id: { type: 'string', minLength: 1 },\n summary: { type: 'string', minLength: 1 },\n },\n required: ['goal_id', 'summary'],\n additionalProperties: false,\n} as const;\n\nconst BLOCKED_PARAMETERS = {\n type: 'object',\n properties: {\n goal_id: { type: 'string', minLength: 1 },\n reason: { type: 'string', minLength: 1 },\n evidence: { type: 'string', minLength: 1 },\n repeated_turns: { type: 'integer', minimum: 3 },\n },\n required: ['goal_id', 'reason', 'evidence', 'repeated_turns'],\n additionalProperties: false,\n} as const;\n\ntype CompleteInput = { goal_id?: unknown; summary?: unknown };\ntype BlockedInput = { goal_id?: unknown; reason?: unknown; evidence?: unknown; repeated_turns?: unknown };\ntype ToolResult = AgentToolResult<Record<string, unknown>>;\ntype RunOrigin = 'manual' | 'automatic';\ntype AgentEndEventLike = { messages?: readonly unknown[] };\ntype CompactEventLike = { reason?: string; willRetry?: boolean };\ntype CompactState = { goalId: string; hadAutomaticRun: boolean; willRetry: boolean };\n\ntype EventBus = {\n emit(channel: string, data: unknown): void;\n on(channel: string, handler: (data: unknown) => void): () => void;\n};\n\nfunction messageResult(text: string, isError = false): ToolResult {\n return { content: [{ type: 'text', text }], details: { error: isError } };\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;\n}\n\nexport class GoalPiManager {\n private readonly pi: ExtensionAPI;\n private readonly runtime: GoalRuntimeModel;\n private readonly dependencies?: GoalExtensionDependencies;\n private readonly legacyCommandService?: GoalExtensionService;\n private context?: ExtensionContext;\n private sessionId?: string;\n private generation = 0;\n private operations: Promise<void> = Promise.resolve();\n private settings = DEFAULT_GOAL_SETTINGS;\n private history?: GoalHistoryPort;\n private runGoalId?: string;\n private runOrigin?: RunOrigin;\n private runExecutionGeneration?: number;\n private pendingRunOrigin: RunOrigin = 'manual';\n private lastToolCallGoalId?: string;\n private lastToolCallGeneration?: number;\n private executionGeneration = 0;\n private compactState?: CompactState;\n private budgetWrapUpGoalId?: string;\n private lastGoalId?: string;\n private runToolAttempted = false;\n private disposed = false;\n private readonly disposers: Array<() => void> = [];\n\n constructor(pi: ExtensionAPI, dependencies?: GoalExtensionDependencies, legacyCommandService?: GoalExtensionService) {\n this.pi = pi;\n this.dependencies = dependencies;\n this.legacyCommandService = legacyCommandService;\n this.runtime = new GoalRuntimeModel({\n persist: (state: GoalStateData) => this.pi.appendEntry('goal-state', state),\n });\n }\n\n public snapshot(): GoalRuntimeSnapshot {\n return this.runtime.snapshot();\n }\n\n public async startFromLeader(ctx: ExtensionContext): Promise<void> {\n if (!ctx.hasUI || ctx.mode !== 'tui') {\n this.notify('Goal leader actions require the Doom TUI.', 'warning');\n return;\n }\n const draft = ctx.ui.getEditorText();\n if (draft.length > 0) {\n const accepted = await ctx.ui.confirm(\n 'Replace editor draft?',\n 'Goal start will replace the current draft with /goal .',\n );\n if (!accepted) return;\n }\n ctx.ui.setEditorText('/goal ');\n }\n\n public async endFromLeader(ctx: ExtensionContext): Promise<void> {\n await this.ensureSession(ctx);\n await this.enqueue(() => this.clearGoal(ctx));\n }\n\n public async showFromLeader(ctx: ExtensionContext): Promise<void> {\n await this.ensureSession(ctx);\n this.showStatus();\n }\n\n public async listHistory(ctx: ExtensionContext): Promise<GoalHistoryEntry[]> {\n await this.ensureSession(ctx);\n return (await this.history?.list()) ?? [];\n }\n\n public async restartFromHistory(id: string, ctx: ExtensionContext): Promise<void> {\n await this.ensureSession(ctx);\n if (!this.history) {\n this.notify('Goal history is unavailable.', 'error');\n return;\n }\n try {\n const restart = await this.history.restart(id);\n await this.enqueue(() =>\n this.startGoal(restart.objective, restart.budget, ctx as ExtensionCommandContext, restart.goalId),\n );\n } catch (error) {\n this.notify(`Goal history restart failed: ${errorText(error)}`, 'error');\n }\n }\n\n public async removeHistory(id: string, ctx: ExtensionContext): Promise<void> {\n await this.ensureSession(ctx);\n if (!this.history) {\n this.notify('Goal history is unavailable.', 'error');\n return;\n }\n try {\n await this.history.remove(id);\n this.notify('Goal history entry removed.', 'info');\n } catch (error) {\n this.notify(`Goal history removal failed: ${errorText(error)}`, 'error');\n }\n }\n\n private async ensureSession(ctx: ExtensionContext): Promise<void> {\n if (this.isCurrent(ctx)) return;\n await this.enqueue(() => this.startSession(ctx));\n }\n\n register(): () => void {\n if (typeof this.pi.registerTool === 'function') this.registerTools();\n this.pi.registerCommand('goal', {\n description: 'Manage persistent goal execution',\n handler: (args, ctx) => this.enqueue(() => this.executeCommand(args, ctx)),\n });\n this.disposers.push(this.registerRpc());\n this.pi.on('session_start', (_event, ctx) => {\n void this.enqueue(() => this.startSession(ctx));\n });\n this.pi.on('session_shutdown', () => {\n this.fenceExecution();\n this.generation += 1;\n this.context = undefined;\n this.sessionId = undefined;\n this.runGoalId = undefined;\n this.runOrigin = undefined;\n this.runExecutionGeneration = undefined;\n this.runToolAttempted = false;\n this.compactState = undefined;\n this.deactivateTools();\n });\n this.pi.on('before_agent_start', (event, ctx) => {\n if (!this.isCurrent(ctx)) return undefined;\n const goal = this.runtime.snapshot().goal;\n if (!goal || goal.status !== 'active') return undefined;\n if (!canExecuteGoalTools(this.pi, goal)) {\n this.pauseForToolPolicyDrift(ctx, goal);\n return undefined;\n }\n const prompt = buildGoalSystemPrompt(goal);\n return { systemPrompt: `${event.systemPrompt}\\n\\n${prompt}` };\n });\n this.pi.on('agent_start', (_event, ctx) => {\n if (!this.isCurrent(ctx)) return;\n const goal = this.runtime.snapshot().goal;\n this.runGoalId = goal?.status === 'active' ? goal.id : undefined;\n this.runOrigin = this.runGoalId ? this.pendingRunOrigin : undefined;\n this.runExecutionGeneration = this.runGoalId ? this.executionGeneration : undefined;\n this.pendingRunOrigin = 'manual';\n this.runToolAttempted = false;\n });\n this.pi.on('tool_call', (event, ctx) => {\n if (!this.isCurrent(ctx)) return undefined;\n this.noteToolCall(event.toolName);\n return undefined;\n });\n this.pi.on('tool_execution_start', (event, ctx) => {\n if (!this.isCurrent(ctx)) return;\n this.noteToolCall(event.toolName);\n });\n this.pi.on('agent_end', (event, ctx) => {\n void this.enqueue(() => this.finishAgentRun(event, ctx));\n });\n this.pi.on('agent_settled', (_event, ctx) => {\n void this.enqueue(async () => {\n if (await this.dispatchPendingQueueAction(ctx)) return;\n await this.continueAfterSettled(ctx);\n });\n });\n this.pi.on('session_before_compact', (event, ctx) => this.beforeCompact(event, ctx));\n this.pi.on('session_compact', (event, ctx) => {\n void this.enqueue(() => this.afterCompact(event, ctx));\n });\n return () => this.dispose();\n }\n\n private registerTools(): void {\n const complete = {\n name: COMPLETE_TOOL,\n label: 'Goal complete',\n description: 'Mark the active Goal complete after verifying every requirement.',\n promptSnippet: 'Complete an active Goal after authoritative verification.',\n parameters: COMPLETE_PARAMETERS,\n execute: async (\n _toolCallId: string,\n params: CompleteInput,\n _signal: AbortSignal | undefined,\n _onUpdate: unknown,\n ctx: ExtensionContext,\n ): Promise<ToolResult> => this.enqueue(() => this.complete(params, ctx)),\n } as unknown as ToolDefinition;\n const blocked = {\n name: BLOCKED_TOOL,\n label: 'Goal blocked',\n description: 'Mark the active Goal blocked after the same external blocker recurs with evidence.',\n promptSnippet: 'Report a repeated external blocker for the active Goal.',\n parameters: BLOCKED_PARAMETERS,\n execute: async (\n _toolCallId: string,\n params: BlockedInput,\n _signal: AbortSignal | undefined,\n _onUpdate: unknown,\n ctx: ExtensionContext,\n ): Promise<ToolResult> => this.enqueue(() => this.blocked(params, ctx)),\n } as unknown as ToolDefinition;\n this.pi.registerTool(complete);\n this.pi.registerTool(blocked);\n }\n\n private registerRpc(): () => void {\n const events = this.pi.events as Partial<EventBus>;\n if (typeof events.on !== 'function') return () => undefined;\n const disposeStart = events.on(RPC_START, (data) => {\n void this.enqueue(() => this.handleRpcStart(data));\n });\n const disposePause = events.on(RPC_PAUSE, (data) => {\n void this.enqueue(() => this.handleRpcPause(data));\n });\n return () => {\n disposeStart();\n disposePause();\n };\n }\n\n private async startSession(ctx: ExtensionContext): Promise<void> {\n this.fenceExecution();\n this.generation += 1;\n const activeGeneration = this.generation;\n this.context = ctx;\n this.sessionId = ctx.sessionManager.getSessionId();\n this.runGoalId = undefined;\n this.runOrigin = undefined;\n this.runExecutionGeneration = undefined;\n this.runToolAttempted = false;\n this.pendingRunOrigin = 'manual';\n this.budgetWrapUpGoalId = undefined;\n this.settings = await this.loadSettings();\n this.history = this.dependencies?.history ?? this.createHistory(ctx.cwd);\n const loaded = loadGoalStateFromSession({ sessionManager: ctx.sessionManager });\n this.runtime.load(loaded);\n this.deactivateTools();\n let goal = this.runtime.snapshot().goal;\n if (loaded.hasExperimentalQueueState && !this.settings.experimental.goals && goal?.status === 'active') {\n goal = transitionGoal({ ...goal }, 'paused');\n this.runtime.replaceState({\n goal,\n queue: [...this.runtime.snapshot().queue],\n pendingAction: this.runtime.snapshot().pendingAction,\n });\n }\n if (goal?.status === 'active') {\n const activated = this.activateTools(goal);\n if (!activated) {\n this.runtime.replaceState({ goal: transitionGoal(goal, 'paused'), queue: [...this.runtime.snapshot().queue] });\n this.notify('Goal paused because host policy does not expose both Goal tools.', 'warning');\n }\n }\n if (activeGeneration !== this.generation) return;\n this.refreshStatus();\n this.emitState();\n }\n\n private createHistory(cwd: string): GoalHistoryPort | undefined {\n try {\n return new GoalHistoryService(createGoalHistoryStore(cwd));\n } catch {\n return undefined;\n }\n }\n\n private async loadSettings(): Promise<typeof DEFAULT_GOAL_SETTINGS> {\n try {\n const fs = await import('node:fs/promises');\n const path = await import('node:path');\n const raw = JSON.parse(await fs.readFile(path.join(getAgentDir(), SETTINGS_FILE), 'utf8')) as unknown;\n return normalizeGoalSettings(raw) ?? DEFAULT_GOAL_SETTINGS;\n } catch {\n return DEFAULT_GOAL_SETTINGS;\n }\n }\n\n private isCurrent(ctx: ExtensionContext): boolean {\n return !this.disposed && this.context === ctx && this.sessionId === ctx.sessionManager.getSessionId();\n }\n\n private enqueue<T>(operation: () => Promise<T>): Promise<T> {\n const run = this.operations.then(operation, operation);\n this.operations = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n }\n\n private activateTools(goal: ActiveGoal): boolean {\n if (typeof this.pi.getActiveTools !== 'function' || typeof this.pi.setActiveTools !== 'function') return false;\n const previous = this.pi.getActiveTools();\n const result = reconcileGoalTools(this.pi, goal);\n const required = goal.status === 'budget_limited' ? [COMPLETE_TOOL] : [COMPLETE_TOOL, BLOCKED_TOOL];\n const available = required.every((name) => result.activeTools.includes(name));\n if (!available) {\n this.pi.setActiveTools(previous);\n return false;\n }\n this.executionGeneration += 1;\n this.lastToolCallGoalId = undefined;\n this.lastToolCallGeneration = undefined;\n return true;\n }\n\n private deactivateTools(): void {\n if (typeof this.pi.getActiveTools === 'function' && typeof this.pi.setActiveTools === 'function') {\n removeGoalTools(this.pi);\n }\n this.executionGeneration += 1;\n this.lastToolCallGoalId = undefined;\n this.lastToolCallGeneration = undefined;\n }\n\n private fenceExecution(): void {\n this.executionGeneration += 1;\n this.runGoalId = undefined;\n this.runOrigin = undefined;\n this.runExecutionGeneration = undefined;\n this.runToolAttempted = false;\n this.lastToolCallGoalId = undefined;\n this.lastToolCallGeneration = undefined;\n this.compactState = undefined;\n this.budgetWrapUpGoalId = undefined;\n }\n\n private noteToolCall(toolName: string): void {\n if (toolName !== COMPLETE_TOOL && toolName !== BLOCKED_TOOL) return;\n this.runToolAttempted = true;\n const goal = this.runtime.snapshot().goal;\n if (!goal) return;\n this.lastToolCallGoalId = goal.id;\n this.lastToolCallGeneration = this.executionGeneration;\n }\n\n private pauseForToolPolicyDrift(ctx: ExtensionContext, goal: ActiveGoal): void {\n if (!this.isCurrent(ctx) || this.runtime.snapshot().goal?.id !== goal.id || goal.status !== 'active') return;\n updateGoalUsage(goal, ctx, Date.now(), false);\n this.fenceExecution();\n const paused = transitionGoal({ ...goal }, 'paused');\n this.runtime.replaceState({ goal: paused, queue: [...this.runtime.snapshot().queue] });\n this.deactivateTools();\n this.abortCurrentTurn(ctx);\n this.refreshStatus();\n this.emitState('required Goal tool unavailable');\n this.notify(\n 'Goal tools are unavailable, so the Goal was paused. Restore the tools and run /goal resume.',\n 'warning',\n );\n }\n\n private beforeCompact(event: CompactEventLike, ctx: ExtensionContext): undefined {\n if (!this.isCurrent(ctx)) return undefined;\n const goal = this.runtime.snapshot().goal;\n if (!goal || goal.status !== 'active') return undefined;\n this.compactState = {\n goalId: goal.id,\n hadAutomaticRun: this.runOrigin === 'automatic' && this.runGoalId === goal.id,\n willRetry: event.willRetry === true,\n };\n // A compaction invalidates the current turn's leases. The persisted Goal remains\n // authoritative, while a retry/settled boundary may establish a new lease.\n this.executionGeneration += 1;\n this.runGoalId = undefined;\n this.runOrigin = undefined;\n this.runExecutionGeneration = undefined;\n this.lastToolCallGoalId = undefined;\n this.lastToolCallGeneration = undefined;\n return undefined;\n }\n\n private async afterCompact(event: CompactEventLike, ctx: ExtensionContext): Promise<void> {\n if (!this.isCurrent(ctx)) return;\n const compact = this.compactState;\n if (!compact) return;\n const goal = this.runtime.snapshot().goal;\n this.compactState = undefined;\n if (!goal || goal.id !== compact.goalId || goal.status !== 'active') return;\n this.executionGeneration += 1;\n this.runToolAttempted = false;\n // Overflow retries belong to Pi's current run and must not receive a duplicate\n // continuation. Manual/threshold compaction keeps one guarded recovery marker.\n if (!compact.willRetry && compact.hadAutomaticRun && event.willRetry !== true) {\n this.pendingRunOrigin = 'automatic';\n this.runGoalId = goal.id;\n this.runOrigin = 'automatic';\n this.runExecutionGeneration = this.executionGeneration;\n }\n }\n\n private refreshStatus(): void {\n const ctx = this.context;\n const snapshot = this.runtime.snapshot();\n if (!ctx?.hasUI) return;\n const queueWaiting = snapshot.pendingAction !== undefined || (!snapshot.goal && snapshot.queue.length > 0);\n ctx.ui.setStatus(STATUS_KEY, queueWaiting ? 'queued' : formatStatus(snapshot.goal));\n }\n\n private emitState(reason?: string, summary?: string): void {\n const goal = this.runtime.snapshot().goal;\n const status = goal?.status ?? 'cleared';\n this.lastGoalId = goal?.id ?? this.lastGoalId;\n (this.pi.events as EventBus).emit(STATE_EVENT, {\n goalId: goal?.id ?? this.lastGoalId ?? '',\n status,\n ...(reason ? { reason } : {}),\n ...(summary ? { summary } : {}),\n });\n }\n\n private notify(message: string, level: 'info' | 'warning' | 'error' = 'info'): void {\n if (this.context?.hasUI) this.context.ui.notify(message, level);\n }\n\n private abortCurrentTurn(ctx: ExtensionContext): boolean {\n try {\n ctx.abort();\n return true;\n } catch {\n return false;\n }\n }\n\n private async executeCommand(args: string, ctx: ExtensionCommandContext): Promise<void> {\n const hasSessionManager = Object.hasOwn(ctx, 'sessionManager');\n if (!args.trim() && this.legacyCommandService && !hasSessionManager) {\n const result = await this.legacyCommandService.execute();\n if (ctx.hasUI) ctx.ui.notify(result.message, result.level);\n return;\n }\n if (!this.isCurrent(ctx)) {\n await this.startSession(ctx);\n }\n const parsed = parseGoalCommand(args, { experimentalGoals: this.settings.experimental.goals });\n if (typeof parsed === 'string') {\n this.notify(parsed, 'warning');\n return;\n }\n switch (parsed.kind) {\n case 'show':\n this.showStatus();\n return;\n case 'start':\n await this.startGoal(parsed.objective ?? '', parsed.tokenBudget, ctx);\n return;\n case 'pause':\n this.pauseGoal(ctx);\n return;\n case 'resume':\n await this.resumeGoal(ctx);\n return;\n case 'clear':\n await this.clearGoal(ctx);\n return;\n case 'edit':\n await this.editGoal(parsed.objective ?? '', parsed.tokenBudget, ctx);\n return;\n case 'add':\n await this.addGoal(parsed.objective ?? '', parsed.tokenBudget, ctx);\n return;\n case 'prioritize':\n await this.prioritizeGoal(parsed.objective ?? '', parsed.tokenBudget, ctx);\n return;\n case 'drop-last':\n this.dropLastGoal(ctx);\n return;\n case 'skip':\n await this.skipGoal(ctx);\n return;\n }\n }\n\n private showStatus(): void {\n const snapshot = this.runtime.snapshot();\n const goal = snapshot.goal;\n if (!goal) {\n this.notify('No active goal.', 'info');\n return;\n }\n const queue = snapshot.queue.length ? `\\nQueued: ${snapshot.queue.map((item) => item.text).join(', ')}` : '';\n this.notify(`Goal: ${goal.text}\\nStatus: ${goal.status}${queue}`, 'info');\n }\n\n private async startGoal(\n objective: string,\n budget: number | undefined,\n ctx: ExtensionCommandContext,\n goalId?: string,\n ): Promise<void> {\n const validation = validateObjective(objective);\n if (validation) {\n this.notify(validation, 'warning');\n return;\n }\n const previous = this.runtime.snapshot();\n const oldGoal = previous.goal && previous.goal.status !== 'complete' ? previous.goal : undefined;\n if (oldGoal) {\n const accepted = await ctx.ui.confirm('Replace goal?', `Current goal: ${oldGoal.text}\\n\\nNew goal: ${objective}`);\n if (!accepted) return;\n if (!(await this.archiveAll([oldGoal, ...previous.queue], 'replaced'))) {\n this.notify('Goal replacement aborted because history archival failed.', 'error');\n return;\n }\n }\n const next = createGoal(objective, budget, { id: goalId, baselineTokens: currentTokenTotal(ctx) });\n if (!this.activateTools(next)) {\n this.notify('Cannot start /goal: host policy rejected Goal tools.', 'error');\n return;\n }\n this.runtime.replaceState({ goal: next, queue: [] });\n this.budgetWrapUpGoalId = undefined;\n this.pendingRunOrigin = 'manual';\n this.refreshStatus();\n this.emitState();\n try {\n this.pi.sendUserMessage(buildGoalPrompt(next), { deliverAs: 'followUp' });\n } catch (error) {\n this.runtime.replaceState({ goal: oldGoal, queue: previous.queue });\n this.fenceExecution();\n if (!oldGoal) this.deactivateTools();\n this.refreshStatus();\n this.notify(`Goal kickoff failed: ${errorText(error)}`, 'error');\n return;\n }\n this.notify(oldGoal ? `Goal replaced: ${objective}` : `Goal started: ${objective}`);\n }\n\n private pauseGoal(ctx: ExtensionContext): void {\n const goal = this.runtime.snapshot().goal;\n if (!goal) {\n this.notify('No active goal.');\n return;\n }\n if (goal.status !== 'active') {\n this.notify(`Goal is ${goal.status}; only active goals can be paused.`, 'warning');\n return;\n }\n updateGoalUsage(goal, ctx, Date.now(), false);\n this.fenceExecution();\n const next = transitionGoal({ ...goal }, 'paused');\n this.runtime.replaceState({ goal: next, queue: [...this.runtime.snapshot().queue] });\n this.deactivateTools();\n ctx.abort();\n this.refreshStatus();\n this.emitState('paused');\n this.notify(`Goal paused: ${goal.text}`);\n }\n\n private async resumeGoal(ctx: ExtensionContext): Promise<void> {\n const goal = this.runtime.snapshot().goal;\n if (!goal) {\n this.notify('No active goal.');\n return;\n }\n if (!isResumableGoalStatus(goal.status)) {\n this.notify(`Goal is ${goal.status}; it cannot be resumed.`, 'warning');\n return;\n }\n void ctx;\n if (goal.tokenBudget !== undefined && goal.tokensUsed >= goal.tokenBudget) {\n this.notify('Goal token budget is still reached.', 'warning');\n return;\n }\n const next = resetGoalSafetyEpoch(transitionGoal({ ...goal, updatedAt: Date.now() }, 'active'));\n if (!this.activateTools(next)) {\n this.notify('Cannot resume /goal: host policy rejected Goal tools.', 'error');\n return;\n }\n this.runtime.replaceState({ goal: next, queue: [...this.runtime.snapshot().queue] });\n this.budgetWrapUpGoalId = undefined;\n this.pendingRunOrigin = 'manual';\n this.refreshStatus();\n this.emitState();\n try {\n this.pi.sendUserMessage(buildResumePrompt(next, goal.status), { deliverAs: 'followUp' });\n } catch (error) {\n this.fenceExecution();\n this.runtime.replaceState({ goal, queue: [...this.runtime.snapshot().queue] });\n this.deactivateTools();\n this.refreshStatus();\n this.notify(`Goal resume failed: ${errorText(error)}`, 'error');\n }\n }\n\n private async clearGoal(ctx: ExtensionContext): Promise<void> {\n const snapshot = this.runtime.snapshot();\n if (!(await this.archiveAll([...(snapshot.goal ? [snapshot.goal] : []), ...snapshot.queue], 'cleared'))) {\n this.notify('Goal clear aborted because history archival failed.', 'error');\n return;\n }\n this.fenceExecution();\n this.runtime.clear();\n this.deactivateTools();\n ctx.abort();\n this.refreshStatus();\n this.emitState('cleared');\n if (snapshot.goal) this.notify(`Goal cleared: ${snapshot.goal.text}`, 'warning');\n else this.notify('No active goal.', 'info');\n }\n\n private async editGoal(objective: string, budget: number | undefined, ctx: ExtensionCommandContext): Promise<void> {\n const validation = validateObjective(objective);\n if (validation) {\n this.notify(validation, 'warning');\n return;\n }\n const goal = this.runtime.snapshot().goal;\n if (!goal) {\n this.notify('No active goal. Use /goal <objective> to start one.', 'warning');\n return;\n }\n const next = {\n ...goal,\n text: objective,\n ...(budget === undefined ? {} : { tokenBudget: budget }),\n updatedAt: Date.now(),\n };\n this.runtime.replaceState({ goal: next, queue: [...this.runtime.snapshot().queue] });\n this.refreshStatus();\n this.emitState();\n if (goal.status === 'active') this.pi.sendUserMessage(buildObjectiveUpdatedPrompt(next), { deliverAs: 'followUp' });\n else this.notify(`Goal updated but remains ${goal.status}. Resume explicitly to execute it.`);\n void ctx;\n }\n\n private async addGoal(objective: string, budget: number | undefined, _ctx: ExtensionContext): Promise<void> {\n const validation = validateObjective(objective);\n if (validation) {\n this.notify(validation, 'warning');\n return;\n }\n const snapshot = this.runtime.snapshot();\n if (!snapshot.goal) {\n await this.startGoal(objective, budget, this.context as ExtensionCommandContext);\n return;\n }\n const state = enqueueGoal(\n {\n goal: snapshot.goal,\n queue: [...snapshot.queue],\n pendingAction: snapshot.pendingAction,\n enabled: this.settings.experimental.goals,\n },\n objective,\n budget,\n );\n this.runtime.replaceState(state);\n this.refreshStatus();\n this.emitState();\n this.notify(`Goal added at position ${state.queue.length + 1}: ${objective}`);\n }\n\n private async prioritizeGoal(objective: string, budget: number | undefined, _ctx: ExtensionContext): Promise<void> {\n const validation = validateObjective(objective);\n if (validation) {\n this.notify(validation, 'warning');\n return;\n }\n const snapshot = this.runtime.snapshot();\n if (!snapshot.goal) {\n await this.startGoal(objective, budget, this.context as ExtensionCommandContext);\n return;\n }\n this.runtime.replaceState({\n goal: snapshot.goal,\n queue: [...snapshot.queue],\n pendingAction: { kind: 'prioritize', objective, tokenBudget: budget },\n });\n this.notify(`Priority goal queued until the current turn settles: ${objective}`);\n }\n\n private dropLastGoal(_ctx: ExtensionContext): void {\n const snapshot = this.runtime.snapshot();\n if (!snapshot.queue.length) {\n this.notify('No queued goals.', 'info');\n return;\n }\n this.runtime.replaceState({\n goal: snapshot.goal,\n queue: [...snapshot.queue].slice(0, -1),\n pendingAction: snapshot.pendingAction,\n });\n this.notify('Last queued goal dropped.', 'warning');\n }\n\n private async skipGoal(ctx: ExtensionContext): Promise<void> {\n const snapshot = this.runtime.snapshot();\n if (!snapshot.goal) {\n this.notify('No goals to skip.', 'info');\n return;\n }\n if (!(await this.archive(snapshot.goal, 'skipped'))) {\n this.notify('Goal skip aborted because history archival failed.', 'error');\n return;\n }\n this.fenceExecution();\n const nextState = skipCurrentGoal({\n goal: snapshot.goal,\n queue: [...snapshot.queue],\n pendingAction: snapshot.pendingAction,\n enabled: this.settings.experimental.goals,\n });\n if (nextState.pendingAction) this.runtime.replaceState(nextState);\n else this.runtime.clear();\n this.deactivateTools();\n ctx.abort();\n this.refreshStatus();\n this.emitState('skipped');\n }\n\n private async finishAgentRun(event: AgentEndEventLike, ctx: ExtensionContext): Promise<void> {\n if (!this.isCurrent(ctx)) return;\n const snapshot = this.runtime.snapshot();\n const goal = snapshot.goal;\n if (!goal || goal.status !== 'active') return;\n if (this.runGoalId !== goal.id || this.runExecutionGeneration !== this.executionGeneration) {\n this.fenceExecution();\n return;\n }\n\n const messages = event.messages ?? [];\n const failure = classifyAgentFailure(messages);\n updateGoalUsage(goal, ctx, Date.now(), true);\n if (failure === 'aborted') {\n // User-initiated aborts and safety aborts are fenced without inventing a\n // provider failure. A later explicit resume establishes a new execution lease.\n this.fenceExecution();\n this.runtime.replaceState({ goal, queue: [...snapshot.queue] });\n this.refreshStatus();\n return;\n }\n if (failure === 'usage_limited' || failure === 'blocked') {\n this.fenceExecution();\n const stopped = transitionGoal({ ...goal }, failure);\n this.runtime.replaceState({ goal: stopped, queue: [...snapshot.queue] });\n this.deactivateTools();\n this.abortCurrentTurn(ctx);\n this.refreshStatus();\n this.emitState(failure === 'usage_limited' ? 'provider usage limit' : 'provider error');\n this.notify(\n failure === 'usage_limited'\n ? 'Goal paused because the provider usage limit was reached. Run /goal resume after it resets.'\n : 'Goal blocked because the provider reported a terminal error. Resolve it or run /goal resume.',\n 'warning',\n );\n return;\n }\n\n if (this.runOrigin === 'automatic') {\n goal.automaticModelTurns = Math.min(Number.MAX_SAFE_INTEGER, goal.automaticModelTurns + 1);\n const progress = nextToolFreeRepeatState(goal, messages, this.runToolAttempted);\n goal.toolFreeRepeatCount = progress.toolFreeRepeatCount;\n goal.lastToolFreeOutputFingerprint = progress.lastToolFreeOutputFingerprint;\n const cause = safetyLimitReached(goal, this.settings.continuationLimits);\n if (cause) {\n this.pauseForSafety(ctx, goal, cause);\n return;\n }\n }\n\n if (goal.tokenBudget !== undefined && goal.tokensUsed >= goal.tokenBudget) {\n this.limitForBudget(ctx, goal, snapshot.queue);\n return;\n }\n this.runtime.replaceState({ goal, queue: [...snapshot.queue] });\n this.refreshStatus();\n }\n\n private async dispatchPendingQueueAction(ctx: ExtensionContext): Promise<boolean> {\n if (!this.isCurrent(ctx)) return false;\n const snapshot = this.runtime.snapshot();\n const pending = snapshot.pendingAction;\n if (!pending) return false;\n if (!this.settings.experimental.goals || !ctx.isIdle() || ctx.hasPendingMessages()) return true;\n\n if (pending.kind === 'prioritize') {\n const current = snapshot.goal;\n if (!current) {\n this.runtime.replaceState({ queue: [...snapshot.queue] });\n await this.startGoal(pending.objective, pending.tokenBudget, ctx as ExtensionCommandContext);\n return true;\n }\n if (current.status === 'active') updateGoalUsage(current, ctx, Date.now(), false);\n const prioritized = createGoal(pending.objective, pending.tokenBudget, {\n baselineTokens: currentTokenTotal(ctx),\n });\n const displacedQueue =\n current.status === 'complete'\n ? [...snapshot.queue]\n : [transitionGoal({ ...current, activeStartedAt: undefined }, 'queued'), ...snapshot.queue];\n this.deactivateTools();\n if (!this.activateTools(prioritized)) {\n const paused = transitionGoal(prioritized, 'paused');\n this.runtime.replaceState({ goal: paused, queue: displacedQueue });\n this.deactivateTools();\n this.refreshStatus();\n this.emitState('queued goal tools unavailable');\n this.notify('Priority Goal is retained but paused because host policy rejected Goal tools.', 'warning');\n return true;\n }\n this.runtime.replaceState({ goal: prioritized, queue: displacedQueue });\n this.pendingRunOrigin = 'manual';\n this.refreshStatus();\n this.emitState('prioritized');\n try {\n this.pi.sendUserMessage(buildGoalPrompt(prioritized), { deliverAs: 'followUp' });\n } catch (error) {\n this.pauseForDeliveryFailure(ctx, prioritized, `Priority Goal kickoff failed: ${errorText(error)}`);\n }\n return true;\n }\n\n const current = snapshot.goal;\n if (!current || current.id !== pending.goalId || (pending.reason === 'complete' && current.status !== 'complete')) {\n this.runtime.replaceState({ goal: current, queue: [...snapshot.queue] });\n this.refreshStatus();\n return true;\n }\n const promoted = promoteNextGoal(\n { goal: current, queue: [...snapshot.queue], pendingAction: pending, enabled: true },\n Date.now(),\n currentTokenTotal(ctx),\n );\n const next = promoted.goal;\n if (!next || next.id === current.id) {\n this.runtime.clear();\n this.deactivateTools();\n this.refreshStatus();\n this.emitState(pending.reason);\n return true;\n }\n if (!this.activateTools(next)) {\n const paused = transitionGoal(next, 'paused');\n this.runtime.replaceState({ goal: paused, queue: [...promoted.queue] });\n this.deactivateTools();\n this.refreshStatus();\n this.emitState('queued goal tools unavailable');\n this.notify('Next Goal is retained but paused because host policy rejected Goal tools.', 'warning');\n return true;\n }\n this.runtime.replaceState({ goal: next, queue: [...promoted.queue] });\n this.pendingRunOrigin = 'manual';\n this.refreshStatus();\n this.emitState(pending.reason);\n try {\n this.pi.sendUserMessage(buildGoalPrompt(next), { deliverAs: 'followUp' });\n } catch (error) {\n this.pauseForDeliveryFailure(ctx, next, `Queued Goal kickoff failed: ${errorText(error)}`);\n }\n return true;\n }\n\n private async continueAfterSettled(ctx: ExtensionContext): Promise<void> {\n if (!this.isCurrent(ctx) || !ctx.isIdle() || ctx.hasPendingMessages()) return;\n const snapshot = this.runtime.snapshot();\n const goal = snapshot.goal;\n if (!goal || goal.status !== 'active' || !this.runGoalId || this.runGoalId !== goal.id) return;\n if (this.runExecutionGeneration !== this.executionGeneration) {\n this.fenceExecution();\n return;\n }\n if (!canExecuteGoalTools(this.pi, goal)) {\n this.pauseForToolPolicyDrift(ctx, goal);\n return;\n }\n const cause = safetyLimitReached(goal, this.settings.continuationLimits);\n if (cause) {\n this.pauseForSafety(ctx, goal, cause);\n return;\n }\n const next = incrementGoal({ ...goal });\n this.runtime.replaceState({ goal: next, queue: [...snapshot.queue] });\n const continuation = buildContinuePrompt(next);\n this.pendingRunOrigin = 'automatic';\n try {\n this.pi.sendUserMessage(continuation, { deliverAs: 'followUp' });\n } catch (error) {\n this.pauseForDeliveryFailure(ctx, next, `Goal continuation failed: ${errorText(error)}`);\n return;\n }\n this.runGoalId = undefined;\n this.runOrigin = undefined;\n this.runExecutionGeneration = undefined;\n this.runToolAttempted = false;\n }\n\n private pauseForSafety(ctx: ExtensionContext, goal: ActiveGoal, cause: 'continuation_limit' | 'no_progress'): void {\n if (this.runtime.snapshot().goal?.id !== goal.id) return;\n this.fenceExecution();\n const paused = transitionGoal({ ...goal, safetyPauseCause: cause }, 'paused');\n this.runtime.replaceState({ goal: paused, queue: [...this.runtime.snapshot().queue] });\n this.deactivateTools();\n this.abortCurrentTurn(ctx);\n this.refreshStatus();\n this.emitState(cause === 'continuation_limit' ? 'automatic response limit' : 'no progress');\n const detail = cause === 'continuation_limit' ? 'automatic response limit' : 'no progress';\n this.notify(`Goal paused by safety limit: ${detail}. Run /goal resume to continue.`, 'warning');\n }\n\n private limitForBudget(ctx: ExtensionContext, goal: ActiveGoal, queue: readonly ActiveGoal[]): void {\n this.fenceExecution();\n const limited = transitionGoal({ ...goal }, 'budget_limited');\n this.runtime.replaceState({ goal: limited, queue: [...queue] });\n this.deactivateTools();\n const canWrap = this.activateTools(limited);\n if (canWrap && this.budgetWrapUpGoalId !== limited.id) {\n this.budgetWrapUpGoalId = limited.id;\n try {\n this.pi.sendMessage(\n {\n customType: 'goal-budget-wrap-up',\n content:\n 'The Goal token budget is exhausted. Stop substantive work, summarize verified progress and blockers, and call goal_complete only if every requirement is already proven.',\n display: true,\n details: { goalId: limited.id },\n },\n { deliverAs: 'steer' },\n );\n } catch (error) {\n this.budgetWrapUpGoalId = undefined;\n this.notify(`Goal budget wrap-up failed: ${errorText(error)}`, 'error');\n }\n }\n if (!canWrap) this.notify('Goal budget reached, but host policy rejected goal_complete.', 'warning');\n this.abortCurrentTurn(ctx);\n this.refreshStatus();\n this.emitState('token budget reached');\n }\n\n private pauseForDeliveryFailure(ctx: ExtensionContext, goal: ActiveGoal, message: string): void {\n this.fenceExecution();\n const paused = transitionGoal({ ...goal }, 'paused');\n this.runtime.replaceState({ goal: paused, queue: [...this.runtime.snapshot().queue] });\n this.deactivateTools();\n this.abortCurrentTurn(ctx);\n this.refreshStatus();\n this.emitState('delivery failed');\n this.notify(message, 'error');\n }\n\n private async complete(params: CompleteInput, ctx: ExtensionContext): Promise<ToolResult> {\n const snapshot = this.runtime.snapshot();\n const goal = snapshot.goal;\n if (!goal || !this.acceptsToolCall(ctx, goal))\n return messageResult('Goal completion rejected because this tool call belongs to a stale Goal execution.', true);\n const validation = validateCompletionInput(goal, params as { goal_id?: string; summary?: string });\n if (!goal || (goal.status !== 'active' && goal.status !== 'budget_limited'))\n return messageResult('Goal completion is not available in the current state.', true);\n if (!validation.ok) return messageResult(validation.reason ?? 'Goal completion rejected.', true);\n const summary = typeof params.summary === 'string' ? params.summary.trim() : '';\n if (isContradictoryCompletionSummary(summary))\n return messageResult('Completion evidence contradicts completion.', true);\n if (!(await this.archive(goal, 'complete', summary)))\n return messageResult('Completion aborted because history archival failed.', true);\n this.fenceExecution();\n const completed = transitionGoal({ ...goal }, 'complete');\n if (snapshot.queue.length && this.settings.experimental.goals) {\n this.runtime.replaceState({\n goal: completed,\n queue: [...snapshot.queue],\n pendingAction: { kind: 'advance', goalId: goal.id, reason: 'complete', completedText: goal.text },\n });\n } else {\n this.runtime.clear();\n }\n this.deactivateTools();\n ctx.abort();\n this.refreshStatus();\n this.emitState(undefined, summary);\n return messageResult(`Goal complete: ${goal.text}`);\n }\n\n private async blocked(params: BlockedInput, ctx: ExtensionContext): Promise<ToolResult> {\n const snapshot = this.runtime.snapshot();\n const goal = snapshot.goal;\n if (!goal || !this.acceptsToolCall(ctx, goal))\n return messageResult('Goal blocker rejected because this tool call belongs to a stale Goal execution.', true);\n const validation = validateBlockedInput(\n goal,\n params as { goal_id?: string; reason?: string; evidence?: string; repeated_turns?: number },\n );\n if (!goal || goal.status !== 'active')\n return messageResult('Goal blocking is not available in the current state.', true);\n if (!validation.ok) return messageResult(validation.reason ?? 'Goal blocker rejected.', true);\n const reason = typeof params.reason === 'string' ? params.reason.trim() : 'blocked';\n this.fenceExecution();\n const blocked = transitionGoal({ ...goal }, 'blocked');\n this.runtime.replaceState({ goal: blocked, queue: [...snapshot.queue] });\n this.deactivateTools();\n ctx.abort();\n this.refreshStatus();\n this.emitState(reason);\n return messageResult(`Goal blocked: ${reason}`);\n }\n\n private acceptsToolCall(ctx: ExtensionContext, goal: ActiveGoal): boolean {\n if (!this.isCurrent(ctx)) return false;\n if (this.runGoalId && (this.runGoalId !== goal.id || this.runExecutionGeneration !== this.executionGeneration))\n return false;\n if (\n this.lastToolCallGoalId &&\n (this.lastToolCallGoalId !== goal.id || this.lastToolCallGeneration !== this.executionGeneration)\n )\n return false;\n return canExecuteGoalTools(this.pi, goal);\n }\n\n private async handleRpcStart(data: unknown): Promise<void> {\n const payload = asRecord(data);\n const requestId = typeof payload?.requestId === 'string' ? payload.requestId.trim() : '';\n const events = this.pi.events as EventBus;\n if (!requestId) return;\n const reply = (value: unknown): void => events.emit(`pi-goal:rpc:start:reply:${requestId}`, value);\n const objective = typeof payload?.objective === 'string' ? payload.objective.trim() : '';\n const validation = validateObjective(objective);\n if (validation) {\n reply({ success: false, error: validation });\n return;\n }\n if (this.runtime.snapshot().goal) {\n reply({ success: false, error: 'a goal already exists' });\n return;\n }\n const ctx = this.context;\n if (!ctx) {\n reply({ success: false, error: 'no active pi-goal session context' });\n return;\n }\n try {\n await this.startGoal(\n objective,\n typeof payload?.tokenBudget === 'number' ? payload.tokenBudget : undefined,\n ctx as ExtensionCommandContext,\n );\n const goal = this.runtime.snapshot().goal;\n if (!goal) reply({ success: false, error: 'goal could not be activated' });\n else reply({ success: true, data: { goalId: goal.id, status: goal.status } });\n } catch (error) {\n reply({ success: false, error: `goal start failed: ${errorText(error)}` });\n }\n }\n\n private async handleRpcPause(data: unknown): Promise<void> {\n const payload = asRecord(data);\n const goal = this.runtime.snapshot().goal;\n if (!goal || goal.status !== 'active') return;\n const requestGoalId = typeof payload?.goalId === 'string' ? payload.goalId : undefined;\n if (requestGoalId && requestGoalId !== goal.id) return;\n if (this.context) this.pauseGoal(this.context);\n }\n\n private async archiveAll(goals: readonly ActiveGoal[], reason: string): Promise<boolean> {\n const seen = new Set<string>();\n for (const goal of goals) {\n if (seen.has(goal.id)) continue;\n seen.add(goal.id);\n if (!(await this.archive(goal, reason))) return false;\n }\n return true;\n }\n\n private async archive(goal: ActiveGoal, reason: string, summary?: string): Promise<boolean> {\n if (!this.history) return true;\n try {\n await this.history.archive({\n id: goal.id,\n objective: goal.text,\n status: reason === 'complete' ? 'complete' : goal.status,\n ...(summary ? { reason: summary } : { reason }),\n ...(goal.tokenBudget === undefined ? {} : { budget: goal.tokenBudget }),\n archivedAt: new Date().toISOString(),\n startedAt: new Date(goal.startedAt).toISOString(),\n ...(reason === 'complete' ? { completedAt: new Date().toISOString() } : {}),\n });\n return true;\n } catch (error) {\n this.notify(`Goal history archival failed: ${errorText(error)}`, 'error');\n return false;\n }\n }\n\n private dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.generation += 1;\n for (const dispose of this.disposers.splice(0)) dispose();\n this.deactivateTools();\n this.context = undefined;\n }\n}\n\nfunction classifyAgentFailure(messages: readonly unknown[]): 'usage_limited' | 'blocked' | 'aborted' | undefined {\n const assistant = [...messages].reverse().find((message) => isAssistantMessage(message));\n if (!assistant || typeof assistant !== 'object') return undefined;\n const candidate = assistant as { stopReason?: unknown; errorMessage?: unknown; content?: unknown; text?: unknown };\n if (candidate.stopReason === 'aborted') return 'aborted';\n if (candidate.stopReason !== 'error' && candidate.stopReason !== 'length' && candidate.errorMessage === undefined)\n return undefined;\n const details = [candidate.errorMessage, extractMessageText(candidate)]\n .filter((value): value is string => typeof value === 'string')\n .join(' ')\n .toLowerCase();\n if (\n candidate.stopReason === 'length' ||\n /(?:rate|quota|usage|token|context|capacity|limit|429|too many|billing|exhaust)/u.test(details)\n )\n return 'usage_limited';\n return 'blocked';\n}\n\nfunction isAssistantMessage(value: unknown): boolean {\n return Boolean(value && typeof value === 'object' && (value as { role?: unknown }).role === 'assistant');\n}\n\nfunction extractMessageText(value: { content?: unknown; text?: unknown }): string {\n if (typeof value.text === 'string') return value.text;\n if (typeof value.content === 'string') return value.content;\n if (!Array.isArray(value.content)) return '';\n return value.content\n .map((part) => {\n if (!part || typeof part !== 'object') return '';\n const text = (part as { text?: unknown }).text;\n return typeof text === 'string' ? text : '';\n })\n .join(' ');\n}\n"],"mappings":"84CAsCA,MAGM,EAAgB,gBAChB,EAAe,eAI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U,eAAiB,IAAA,GACtG,OACF,IAAM,EAAU,CAAC,EAAU,aAAc,EAAmB,CAAS,CAAC,CAAC,CACpE,OAAQ,GAA2B,OAAO,GAAU,QAAQ,CAAC,CAC7D,KAAK,GAAG,CAAC,CACT,YAAY,EAMf,OAJE,EAAU,aAAe,UACzB,kFAAkF,KAAK,CAAO,EAEvF,gBACF,SACT,CAEA,SAAS,EAAmB,EAAyB,CACnD,MAAO,GAAQ,GAAS,OAAO,GAAU,UAAa,EAA6B,OAAS,YAC9F,CAEA,SAAS,EAAmB,EAAsD,CAIhF,OAHI,OAAO,EAAM,MAAS,SAAiB,EAAM,KAC7C,OAAO,EAAM,SAAY,SAAiB,EAAM,QAC/C,MAAM,QAAQ,EAAM,OAAO,EACzB,EAAM,QACV,IAAK,GAAS,CACb,GAAI,CAAC,GAAQ,OAAO,GAAS,SAAU,MAAO,GAC9C,IAAM,EAAQ,EAA4B,KAC1C,OAAO,OAAO,GAAS,SAAW,EAAO,EAC3C,CAAC,CAAC,CACD,KAAK,GAAG,EAP+B,EAQ5C"}
@@ -0,0 +1,2 @@
1
+ const e=`goal_complete`,t=[e,`goal_blocked`];function n(n){return n?n.status===`budget_limited`?[e]:n.status===`active`?t:[]:[]}function r(e){return e.filter(e=>!t.includes(e))}function i(n,i){let a=r(n);return i===`budget_limited`?[...a,e]:i===`active`?[...a,...t]:a}function a(e,t){let a=e.getActiveTools(),o=n(t),s=o.length===0?r(a):i(a,t?.status??`paused`);e.setActiveTools(s);let c=e.getActiveTools();return{activeTools:c,goalTools:o.filter(e=>c.includes(e))}}function o(e,t){return t?n(t).every(t=>e.getActiveTools().includes(t)):!1}function s(e){let t=e.getActiveTools(),n=r(t);n.length!==t.length&&e.setActiveTools(n)}exports.canExecuteGoalTools=o,exports.reconcileGoalTools=a,exports.removeGoalTools=s;
2
+ //# sourceMappingURL=toolVisibility.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toolVisibility.cjs","names":[],"sources":["../../../src/adapters/pi/toolVisibility.ts"],"sourcesContent":["import type { GoalStatus } from '../../types/goal.ts';\nimport type { ActiveGoal } from '../../types/goal.ts';\n\nconst GOAL_COMPLETE = 'goal_complete';\nconst GOAL_BLOCKED = 'goal_blocked';\nconst GOAL_TOOLS = [GOAL_COMPLETE, GOAL_BLOCKED] as const;\n\nfunction namesForGoal(goal: ActiveGoal | undefined): readonly string[] {\n if (!goal) return [];\n if (goal.status === 'budget_limited') return [GOAL_COMPLETE];\n return goal.status === 'active' ? GOAL_TOOLS : [];\n}\n\nfunction withoutGoalTools(names: readonly string[]): string[] {\n return names.filter((name) => !GOAL_TOOLS.includes(name as (typeof GOAL_TOOLS)[number]));\n}\n\nfunction withGoalTools(names: readonly string[], status: GoalStatus): string[] {\n const base = withoutGoalTools(names);\n if (status === 'budget_limited') return [...base, GOAL_COMPLETE];\n if (status === 'active') return [...base, ...GOAL_TOOLS];\n return base;\n}\n\nexport interface ActiveToolHost {\n getActiveTools(): string[];\n setActiveTools(toolNames: string[]): void;\n}\n\nexport interface ToolVisibilityResult {\n activeTools: string[];\n goalTools: string[];\n}\n\n/**\n * Changes only Goal-owned names in Pi's current effective tool policy. The\n * caller must bind this after registration; changing tools during factory load\n * would accidentally widen a host policy before its session exists.\n */\nexport function reconcileGoalTools(host: ActiveToolHost, goal: ActiveGoal | undefined): ToolVisibilityResult {\n const current = host.getActiveTools();\n const desired = namesForGoal(goal);\n const next = desired.length === 0 ? withoutGoalTools(current) : withGoalTools(current, goal?.status ?? 'paused');\n host.setActiveTools(next);\n const verified = host.getActiveTools();\n const goalTools = desired.filter((name) => verified.includes(name));\n return { activeTools: verified, goalTools };\n}\n\nexport function canExecuteGoalTools(host: ActiveToolHost, goal: ActiveGoal | undefined): boolean {\n if (!goal) return false;\n const required = namesForGoal(goal);\n return required.every((name) => host.getActiveTools().includes(name));\n}\n\nexport function removeGoalTools(host: ActiveToolHost): void {\n const current = host.getActiveTools();\n const next = withoutGoalTools(current);\n if (next.length !== current.length) host.setActiveTools(next);\n}\n"],"mappings":"AAGA,MAAM,EAAgB,gBAEhB,EAAa,CAAC,EAAe,cAAY,EAE/C,SAAS,EAAa,EAAiD,CAGrE,OAFK,EACD,EAAK,SAAW,iBAAyB,CAAC,CAAa,EACpD,EAAK,SAAW,SAAW,EAAa,CAAC,EAF9B,CAAC,CAGrB,CAEA,SAAS,EAAiB,EAAoC,CAC5D,OAAO,EAAM,OAAQ,GAAS,CAAC,EAAW,SAAS,CAAmC,CAAC,CACzF,CAEA,SAAS,EAAc,EAA0B,EAA8B,CAC7E,IAAM,EAAO,EAAiB,CAAK,EAGnC,OAFI,IAAW,iBAAyB,CAAC,GAAG,EAAM,CAAa,EAC3D,IAAW,SAAiB,CAAC,GAAG,EAAM,GAAG,CAAU,EAChD,CACT,CAiBA,SAAgB,EAAmB,EAAsB,EAAoD,CAC3G,IAAM,EAAU,EAAK,eAAe,EAC9B,EAAU,EAAa,CAAI,EAC3B,EAAO,EAAQ,SAAW,EAAI,EAAiB,CAAO,EAAI,EAAc,EAAS,GAAM,QAAU,QAAQ,EAC/G,EAAK,eAAe,CAAI,EACxB,IAAM,EAAW,EAAK,eAAe,EAErC,MAAO,CAAE,YAAa,EAAU,UADd,EAAQ,OAAQ,GAAS,EAAS,SAAS,CAAI,CACzB,CAAE,CAC5C,CAEA,SAAgB,EAAoB,EAAsB,EAAuC,CAG/F,OAFK,EACY,EAAa,CAChB,CAAC,CAAC,MAAO,GAAS,EAAK,eAAe,CAAC,CAAC,SAAS,CAAI,CAAC,EAFlD,EAGpB,CAEA,SAAgB,EAAgB,EAA4B,CAC1D,IAAM,EAAU,EAAK,eAAe,EAC9B,EAAO,EAAiB,CAAO,EACjC,EAAK,SAAW,EAAQ,QAAQ,EAAK,eAAe,CAAI,CAC9D"}
@@ -0,0 +1,2 @@
1
+ const e=`goal_complete`,t=[e,`goal_blocked`];function n(n){return n?n.status===`budget_limited`?[e]:n.status===`active`?t:[]:[]}function r(e){return e.filter(e=>!t.includes(e))}function i(n,i){let a=r(n);return i===`budget_limited`?[...a,e]:i===`active`?[...a,...t]:a}function a(e,t){let a=e.getActiveTools(),o=n(t),s=o.length===0?r(a):i(a,t?.status??`paused`);e.setActiveTools(s);let c=e.getActiveTools();return{activeTools:c,goalTools:o.filter(e=>c.includes(e))}}function o(e,t){return t?n(t).every(t=>e.getActiveTools().includes(t)):!1}function s(e){let t=e.getActiveTools(),n=r(t);n.length!==t.length&&e.setActiveTools(n)}export{o as canExecuteGoalTools,a as reconcileGoalTools,s as removeGoalTools};
2
+ //# sourceMappingURL=toolVisibility.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toolVisibility.mjs","names":[],"sources":["../../../src/adapters/pi/toolVisibility.ts"],"sourcesContent":["import type { GoalStatus } from '../../types/goal.ts';\nimport type { ActiveGoal } from '../../types/goal.ts';\n\nconst GOAL_COMPLETE = 'goal_complete';\nconst GOAL_BLOCKED = 'goal_blocked';\nconst GOAL_TOOLS = [GOAL_COMPLETE, GOAL_BLOCKED] as const;\n\nfunction namesForGoal(goal: ActiveGoal | undefined): readonly string[] {\n if (!goal) return [];\n if (goal.status === 'budget_limited') return [GOAL_COMPLETE];\n return goal.status === 'active' ? GOAL_TOOLS : [];\n}\n\nfunction withoutGoalTools(names: readonly string[]): string[] {\n return names.filter((name) => !GOAL_TOOLS.includes(name as (typeof GOAL_TOOLS)[number]));\n}\n\nfunction withGoalTools(names: readonly string[], status: GoalStatus): string[] {\n const base = withoutGoalTools(names);\n if (status === 'budget_limited') return [...base, GOAL_COMPLETE];\n if (status === 'active') return [...base, ...GOAL_TOOLS];\n return base;\n}\n\nexport interface ActiveToolHost {\n getActiveTools(): string[];\n setActiveTools(toolNames: string[]): void;\n}\n\nexport interface ToolVisibilityResult {\n activeTools: string[];\n goalTools: string[];\n}\n\n/**\n * Changes only Goal-owned names in Pi's current effective tool policy. The\n * caller must bind this after registration; changing tools during factory load\n * would accidentally widen a host policy before its session exists.\n */\nexport function reconcileGoalTools(host: ActiveToolHost, goal: ActiveGoal | undefined): ToolVisibilityResult {\n const current = host.getActiveTools();\n const desired = namesForGoal(goal);\n const next = desired.length === 0 ? withoutGoalTools(current) : withGoalTools(current, goal?.status ?? 'paused');\n host.setActiveTools(next);\n const verified = host.getActiveTools();\n const goalTools = desired.filter((name) => verified.includes(name));\n return { activeTools: verified, goalTools };\n}\n\nexport function canExecuteGoalTools(host: ActiveToolHost, goal: ActiveGoal | undefined): boolean {\n if (!goal) return false;\n const required = namesForGoal(goal);\n return required.every((name) => host.getActiveTools().includes(name));\n}\n\nexport function removeGoalTools(host: ActiveToolHost): void {\n const current = host.getActiveTools();\n const next = withoutGoalTools(current);\n if (next.length !== current.length) host.setActiveTools(next);\n}\n"],"mappings":"AAGA,MAAM,EAAgB,gBAEhB,EAAa,CAAC,EAAe,cAAY,EAE/C,SAAS,EAAa,EAAiD,CAGrE,OAFK,EACD,EAAK,SAAW,iBAAyB,CAAC,CAAa,EACpD,EAAK,SAAW,SAAW,EAAa,CAAC,EAF9B,CAAC,CAGrB,CAEA,SAAS,EAAiB,EAAoC,CAC5D,OAAO,EAAM,OAAQ,GAAS,CAAC,EAAW,SAAS,CAAmC,CAAC,CACzF,CAEA,SAAS,EAAc,EAA0B,EAA8B,CAC7E,IAAM,EAAO,EAAiB,CAAK,EAGnC,OAFI,IAAW,iBAAyB,CAAC,GAAG,EAAM,CAAa,EAC3D,IAAW,SAAiB,CAAC,GAAG,EAAM,GAAG,CAAU,EAChD,CACT,CAiBA,SAAgB,EAAmB,EAAsB,EAAoD,CAC3G,IAAM,EAAU,EAAK,eAAe,EAC9B,EAAU,EAAa,CAAI,EAC3B,EAAO,EAAQ,SAAW,EAAI,EAAiB,CAAO,EAAI,EAAc,EAAS,GAAM,QAAU,QAAQ,EAC/G,EAAK,eAAe,CAAI,EACxB,IAAM,EAAW,EAAK,eAAe,EAErC,MAAO,CAAE,YAAa,EAAU,UADd,EAAQ,OAAQ,GAAS,EAAS,SAAS,CAAI,CACzB,CAAE,CAC5C,CAEA,SAAgB,EAAoB,EAAsB,EAAuC,CAG/F,OAFK,EACY,EAAa,CAChB,CAAC,CAAC,MAAO,GAAS,EAAK,eAAe,CAAC,CAAC,SAAS,CAAI,CAAC,EAFlD,EAGpB,CAEA,SAAgB,EAAgB,EAA4B,CAC1D,IAAM,EAAU,EAAK,eAAe,EAC9B,EAAO,EAAiB,CAAO,EACjC,EAAK,SAAW,EAAQ,QAAQ,EAAK,eAAe,CAAI,CAC9D"}
@@ -0,0 +1,2 @@
1
+ const e=require("../services/extensionService.cjs");function t(t={}){return{service:t.service??new e.DefaultGoalExtensionService}}exports.createGoalContainer=t;
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["DefaultGoalExtensionService"],"sources":["../../src/container/index.ts"],"sourcesContent":["import { DefaultGoalExtensionService } from '../services/extensionService.ts';\nimport type { GoalExtensionDependencies } from '../types/extension.ts';\n\nexport function createGoalContainer(overrides: Partial<GoalExtensionDependencies> = {}): GoalExtensionDependencies {\n return {\n service: overrides.service ?? new DefaultGoalExtensionService(),\n };\n}\n"],"mappings":"oDAGA,SAAgB,EAAoB,EAAgD,CAAC,EAA8B,CACjH,MAAO,CACL,QAAS,EAAU,SAAW,IAAIA,EAAAA,2BACpC,CACF"}
@@ -0,0 +1,2 @@
1
+ import{DefaultGoalExtensionService as e}from"../services/extensionService.mjs";function t(t={}){return{service:t.service??new e}}export{t as createGoalContainer};
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/container/index.ts"],"sourcesContent":["import { DefaultGoalExtensionService } from '../services/extensionService.ts';\nimport type { GoalExtensionDependencies } from '../types/extension.ts';\n\nexport function createGoalContainer(overrides: Partial<GoalExtensionDependencies> = {}): GoalExtensionDependencies {\n return {\n service: overrides.service ?? new DefaultGoalExtensionService(),\n };\n}\n"],"mappings":"+EAGA,SAAgB,EAAoB,EAAgD,CAAC,EAA8B,CACjH,MAAO,CACL,QAAS,EAAU,SAAW,IAAI,CACpC,CACF"}
@@ -0,0 +1,2 @@
1
+ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require("./runtimeActivation.cjs"),t=require("../tui/goalHistoryOverlay.cjs");let n=require("@agimon-ai/doompi-extension-contracts/leader"),r=require("@agimon-ai/doompi-extension-contracts/mode");const i=`@agimon-ai/doompi-goal`,a=`active`,o={show:`goal.show`,start:`goal.start`,end:`goal.end`,history:`goal.history`};function s(e){switch(e){case a:return a;case`paused`:return`paused`;case`blocked`:return`blocked`;case`usage_limited`:return`usage limited`;case`budget_limited`:return`budget limited`;case`queued`:return`queued`;default:return e}}function c(e){if(typeof e!=`string`||e===`cleared`||e===`complete`)return;let t=e!==a;return{label:`GOAL`,detail:s(e),color:t?`warning`:`accent`}}function l(e){let t={key:`g`,label:`goal`,order:100},n=[{id:o.start,path:[t,{key:`s`,label:`start`}],action:{name:o.start}},{id:o.end,path:[t,{key:`e`,label:`end`}],action:{name:o.end}},{id:o.history,path:[t,{key:`p`,label:`history`}],action:{name:o.history}}];return c(e)&&n.push({id:o.show,path:[t,{key:`g`,label:`current`}],action:{name:o.show}}),n}function u(a){let s=e.registerGoalRuntime(a);if(!s)return;let u=s.manager,d=a,f=(0,r.registerDoomModeContribution)(d,{source:i,id:`goal`,order:100}),p=(0,n.createDoomLeaderContribution)(d,{source:i,bindings:l(u.snapshot().goal?.status)}),m=e=>{f.update(c(e)),p.update(l(e))},h=a.events.on(`pi-goal:state`,e=>{m(e.status)});a.on(`session_start`,()=>m(u.snapshot().goal?.status));let g=(0,n.registerDoomLeaderActionHandlers)(d,{source:i,handlers:{[o.show]:e=>u.showFromLeader(e),[o.start]:e=>u.startFromLeader(e),[o.end]:e=>u.endFromLeader(e),[o.history]:e=>t.openGoalHistoryOverlay(e,u)},onError:(e,t,n)=>{n.hasUI&&n.ui.notify(e instanceof Error?e.message:String(e),`error`)}}),_=!1;a.on(`session_shutdown`,()=>{_||(_=!0,h(),g(),p.dispose(),f.dispose(),s.dispose())})}exports.default=u,exports.registerGoalDoomExtension=u;
2
+ //# sourceMappingURL=doom.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"doom.cjs","names":["registerGoalRuntime","registerDoomModeContribution","createDoomLeaderContribution","registerDoomLeaderActionHandlers","openGoalHistoryOverlay"],"sources":["../../src/extensions/doom.ts"],"sourcesContent":["import {\n createDoomLeaderContribution,\n registerDoomLeaderActionHandlers,\n type LeaderBinding,\n} from '@agimon-ai/doompi-extension-contracts/leader';\nimport type { DoomExtensionContext, DoomExtensionHost } from '@agimon-ai/doompi-extension-contracts/config';\nimport { registerDoomModeContribution } from '@agimon-ai/doompi-extension-contracts/mode';\nimport type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';\nimport { openGoalHistoryOverlay } from '../tui/goalHistoryOverlay.ts';\nimport { registerGoalRuntime } from './runtimeActivation.ts';\n\nconst PACKAGE_SOURCE = '@agimon-ai/doompi-goal';\nconst MODE_ID = 'goal';\nconst LEADER_ORDER = 100;\nconst STATE_EVENT = 'pi-goal:state';\nconst ACTIVE_STATUS = 'active';\nconst GOAL_ACTION = {\n show: 'goal.show',\n start: 'goal.start',\n end: 'goal.end',\n history: 'goal.history',\n} as const;\n\ntype GoalStateEvent = { status?: unknown };\ntype EventBus = { on(channel: string, handler: (data: unknown) => void): () => void };\n\ntype GoalDoomHost = DoomExtensionHost<ExtensionContext & DoomExtensionContext>;\n\nfunction detailForStatus(status: string): string {\n switch (status) {\n case ACTIVE_STATUS:\n return ACTIVE_STATUS;\n case 'paused':\n return 'paused';\n case 'blocked':\n return 'blocked';\n case 'usage_limited':\n return 'usage limited';\n case 'budget_limited':\n return 'budget limited';\n case 'queued':\n return 'queued';\n default:\n return status;\n }\n}\n\nfunction valueForStatus(\n status: unknown,\n): { label: string; detail: string; color: 'accent' | 'warning' | 'dim' } | undefined {\n if (typeof status !== 'string' || status === 'cleared' || status === 'complete') return undefined;\n const stopped = status !== ACTIVE_STATUS;\n return {\n label: 'GOAL',\n detail: detailForStatus(status),\n color: stopped ? 'warning' : 'accent',\n };\n}\n\nfunction goalLeaderBindings(status: unknown): LeaderBinding[] {\n const group = { key: 'g', label: 'goal', order: LEADER_ORDER } as const;\n const bindings: LeaderBinding[] = [\n {\n id: GOAL_ACTION.start,\n path: [group, { key: 's', label: 'start' }],\n action: { name: GOAL_ACTION.start },\n },\n {\n id: GOAL_ACTION.end,\n path: [group, { key: 'e', label: 'end' }],\n action: { name: GOAL_ACTION.end },\n },\n {\n id: GOAL_ACTION.history,\n path: [group, { key: 'p', label: 'history' }],\n action: { name: GOAL_ACTION.history },\n },\n ];\n if (valueForStatus(status)) {\n bindings.push({\n id: GOAL_ACTION.show,\n path: [group, { key: 'g', label: 'current' }],\n action: { name: GOAL_ACTION.show },\n });\n }\n return bindings;\n}\n\nexport function registerGoalDoomExtension(pi: ExtensionAPI): void {\n const activation = registerGoalRuntime(pi);\n if (!activation) return;\n const manager = activation.manager;\n const host = pi as unknown as GoalDoomHost;\n const mode = registerDoomModeContribution(host, {\n source: PACKAGE_SOURCE,\n id: MODE_ID,\n order: LEADER_ORDER,\n });\n const leader = createDoomLeaderContribution(host, {\n source: PACKAGE_SOURCE,\n bindings: goalLeaderBindings(manager.snapshot().goal?.status),\n });\n const publishState = (status: unknown): void => {\n mode.update(valueForStatus(status));\n leader.update(goalLeaderBindings(status));\n };\n const stateDisposer = (pi.events as unknown as EventBus).on(STATE_EVENT, (event) => {\n publishState((event as GoalStateEvent).status);\n });\n pi.on('session_start', () => publishState(manager.snapshot().goal?.status));\n const actions = registerDoomLeaderActionHandlers(host, {\n source: PACKAGE_SOURCE,\n handlers: {\n [GOAL_ACTION.show]: (ctx) => manager.showFromLeader(ctx),\n [GOAL_ACTION.start]: (ctx) => manager.startFromLeader(ctx),\n [GOAL_ACTION.end]: (ctx) => manager.endFromLeader(ctx),\n [GOAL_ACTION.history]: (ctx) => openGoalHistoryOverlay(ctx, manager),\n },\n onError: (error, _action, ctx) => {\n if (ctx.hasUI) ctx.ui.notify(error instanceof Error ? error.message : String(error), 'error');\n },\n });\n\n let disposed = false;\n const dispose = (): void => {\n if (disposed) return;\n disposed = true;\n stateDisposer();\n actions();\n leader.dispose();\n mode.dispose();\n activation.dispose();\n };\n pi.on('session_shutdown', dispose);\n}\n\nexport { registerGoalDoomExtension as default };\n"],"mappings":"2SAWA,MAAM,EAAiB,yBAIjB,EAAgB,SAChB,EAAc,CAClB,KAAM,YACN,MAAO,aACP,IAAK,WACL,QAAS,cACX,EAOA,SAAS,EAAgB,EAAwB,CAC/C,OAAQ,EAAR,CACE,KAAK,EACH,OAAO,EACT,IAAK,SACH,MAAO,SACT,IAAK,UACH,MAAO,UACT,IAAK,gBACH,MAAO,gBACT,IAAK,iBACH,MAAO,iBACT,IAAK,SACH,MAAO,SACT,QACE,OAAO,CACX,CACF,CAEA,SAAS,EACP,EACoF,CACpF,GAAI,OAAO,GAAW,UAAY,IAAW,WAAa,IAAW,WAAY,OACjF,IAAM,EAAU,IAAW,EAC3B,MAAO,CACL,MAAO,OACP,OAAQ,EAAgB,CAAM,EAC9B,MAAO,EAAU,UAAY,QAC/B,CACF,CAEA,SAAS,EAAmB,EAAkC,CAC5D,IAAM,EAAQ,CAAE,IAAK,IAAK,MAAO,OAAQ,MAAO,GAAa,EACvD,EAA4B,CAChC,CACE,GAAI,EAAY,MAChB,KAAM,CAAC,EAAO,CAAE,IAAK,IAAK,MAAO,OAAQ,CAAC,EAC1C,OAAQ,CAAE,KAAM,EAAY,KAAM,CACpC,EACA,CACE,GAAI,EAAY,IAChB,KAAM,CAAC,EAAO,CAAE,IAAK,IAAK,MAAO,KAAM,CAAC,EACxC,OAAQ,CAAE,KAAM,EAAY,GAAI,CAClC,EACA,CACE,GAAI,EAAY,QAChB,KAAM,CAAC,EAAO,CAAE,IAAK,IAAK,MAAO,SAAU,CAAC,EAC5C,OAAQ,CAAE,KAAM,EAA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W,GAUf,EAAG,GAAG,uBATsB,CACtB,IACJ,EAAW,GACX,EAAc,EACd,EAAQ,EACR,EAAO,QAAQ,EACf,EAAK,QAAQ,EACb,EAAW,QAAQ,EACrB,CACiC,CACnC"}
@@ -0,0 +1,6 @@
1
+ import { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ //#region src/extensions/doom.d.ts
3
+ declare function registerGoalDoomExtension(pi: ExtensionAPI): void;
4
+ //#endregion
5
+ export { registerGoalDoomExtension as default, registerGoalDoomExtension };
6
+ //# sourceMappingURL=doom.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"doom.d.cts","names":[],"sources":["../../src/extensions/doom.ts"],"mappings":";;iBAwFgB,0BAA0B,IAAI"}
@@ -0,0 +1,6 @@
1
+ import { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ //#region src/extensions/doom.d.ts
3
+ declare function registerGoalDoomExtension(pi: ExtensionAPI): void;
4
+ //#endregion
5
+ export { registerGoalDoomExtension as default, registerGoalDoomExtension };
6
+ //# sourceMappingURL=doom.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"doom.d.mts","names":[],"sources":["../../src/extensions/doom.ts"],"mappings":";;iBAwFgB,0BAA0B,IAAI"}
@@ -0,0 +1,2 @@
1
+ import{registerGoalRuntime as e}from"./runtimeActivation.mjs";import{openGoalHistoryOverlay as t}from"../tui/goalHistoryOverlay.mjs";import{createDoomLeaderContribution as n,registerDoomLeaderActionHandlers as r}from"@agimon-ai/doompi-extension-contracts/leader";import{registerDoomModeContribution as i}from"@agimon-ai/doompi-extension-contracts/mode";const a=`@agimon-ai/doompi-goal`,o=`active`,s={show:`goal.show`,start:`goal.start`,end:`goal.end`,history:`goal.history`};function c(e){switch(e){case o:return o;case`paused`:return`paused`;case`blocked`:return`blocked`;case`usage_limited`:return`usage limited`;case`budget_limited`:return`budget limited`;case`queued`:return`queued`;default:return e}}function l(e){if(typeof e!=`string`||e===`cleared`||e===`complete`)return;let t=e!==o;return{label:`GOAL`,detail:c(e),color:t?`warning`:`accent`}}function u(e){let t={key:`g`,label:`goal`,order:100},n=[{id:s.start,path:[t,{key:`s`,label:`start`}],action:{name:s.start}},{id:s.end,path:[t,{key:`e`,label:`end`}],action:{name:s.end}},{id:s.history,path:[t,{key:`p`,label:`history`}],action:{name:s.history}}];return l(e)&&n.push({id:s.show,path:[t,{key:`g`,label:`current`}],action:{name:s.show}}),n}function d(o){let c=e(o);if(!c)return;let d=c.manager,f=o,p=i(f,{source:a,id:`goal`,order:100}),m=n(f,{source:a,bindings:u(d.snapshot().goal?.status)}),h=e=>{p.update(l(e)),m.update(u(e))},g=o.events.on(`pi-goal:state`,e=>{h(e.status)});o.on(`session_start`,()=>h(d.snapshot().goal?.status));let _=r(f,{source:a,handlers:{[s.show]:e=>d.showFromLeader(e),[s.start]:e=>d.startFromLeader(e),[s.end]:e=>d.endFromLeader(e),[s.history]:e=>t(e,d)},onError:(e,t,n)=>{n.hasUI&&n.ui.notify(e instanceof Error?e.message:String(e),`error`)}}),v=!1;o.on(`session_shutdown`,()=>{v||(v=!0,g(),_(),m.dispose(),p.dispose(),c.dispose())})}export{d as default,d as registerGoalDoomExtension};
2
+ //# sourceMappingURL=doom.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"doom.mjs","names":[],"sources":["../../src/extensions/doom.ts"],"sourcesContent":["import {\n createDoomLeaderContribution,\n registerDoomLeaderActionHandlers,\n type LeaderBinding,\n} from '@agimon-ai/doompi-extension-contracts/leader';\nimport type { DoomExtensionContext, DoomExtensionHost } from '@agimon-ai/doompi-extension-contracts/config';\nimport { registerDoomModeContribution } from '@agimon-ai/doompi-extension-contracts/mode';\nimport type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';\nimport { openGoalHistoryOverlay } from '../tui/goalHistoryOverlay.ts';\nimport { registerGoalRuntime } from './runtimeActivation.ts';\n\nconst PACKAGE_SOURCE = '@agimon-ai/doompi-goal';\nconst MODE_ID = 'goal';\nconst LEADER_ORDER = 100;\nconst STATE_EVENT = 'pi-goal:state';\nconst ACTIVE_STATUS = 'active';\nconst GOAL_ACTION = {\n show: 'goal.show',\n start: 'goal.start',\n end: 'goal.end',\n history: 'goal.history',\n} as const;\n\ntype GoalStateEvent = { status?: unknown };\ntype EventBus = { on(channel: string, handler: (data: unknown) => void): () => void };\n\ntype GoalDoomHost = DoomExtensionHost<ExtensionContext & DoomExtensionContext>;\n\nfunction detailForStatus(status: string): string {\n switch (status) {\n case ACTIVE_STATUS:\n return ACTIVE_STATUS;\n case 'paused':\n return 'paused';\n case 'blocked':\n return 'blocked';\n case 'usage_limited':\n return 'usage limited';\n case 'budget_limited':\n return 'budget limited';\n case 'queued':\n return 'queued';\n default:\n return status;\n }\n}\n\nfunction valueForStatus(\n status: unknown,\n): { label: string; detail: string; color: 'accent' | 'warning' | 'dim' } | undefined {\n if (typeof status !== 'string' || status === 'cleared' || status === 'complete') return undefined;\n const stopped = status !== ACTIVE_STATUS;\n return {\n label: 'GOAL',\n detail: detailForStatus(status),\n color: stopped ? 'warning' : 'accent',\n };\n}\n\nfunction goalLeaderBindings(status: unknown): LeaderBinding[] {\n const group = { key: 'g', label: 'goal', order: LEADER_ORDER } as const;\n const bindings: LeaderBinding[] = [\n {\n id: GOAL_ACTION.start,\n path: [group, { key: 's', label: 'start' }],\n action: { name: GOAL_ACTION.start },\n },\n {\n id: GOAL_ACTION.end,\n path: [group, { key: 'e', label: 'end' }],\n action: { name: GOAL_ACTION.end },\n },\n {\n id: GOAL_ACTION.history,\n path: [group, { key: 'p', label: 'history' }],\n action: { name: GOAL_ACTION.history },\n },\n ];\n if (valueForStatus(status)) {\n bindings.push({\n id: GOAL_ACTION.show,\n path: [group, { key: 'g', label: 'current' }],\n action: { name: GOAL_ACTION.show },\n });\n }\n return bindings;\n}\n\nexport function registerGoalDoomExtension(pi: ExtensionAPI): void {\n const activation = registerGoalRuntime(pi);\n if (!activation) return;\n const manager = activation.manager;\n const host = pi as unknown as GoalDoomHost;\n const mode = registerDoomModeContribution(host, {\n source: PACKAGE_SOURCE,\n id: MODE_ID,\n order: LEADER_ORDER,\n });\n const leader = createDoomLeaderContribution(host, {\n source: PACKAGE_SOURCE,\n bindings: goalLeaderBindings(manager.snapshot().goal?.status),\n });\n const publishState = (status: unknown): void => {\n mode.update(valueForStatus(status));\n leader.update(goalLeaderBindings(status));\n };\n const stateDisposer = (pi.events as unknown as EventBus).on(STATE_EVENT, (event) => {\n publishState((event as GoalStateEvent).status);\n });\n pi.on('session_start', () => publishState(manager.snapshot().goal?.status));\n const actions = registerDoomLeaderActionHandlers(host, {\n source: PACKAGE_SOURCE,\n handlers: {\n [GOAL_ACTION.show]: (ctx) => manager.showFromLeader(ctx),\n [GOAL_ACTION.start]: (ctx) => manager.startFromLeader(ctx),\n [GOAL_ACTION.end]: (ctx) => manager.endFromLeader(ctx),\n [GOAL_ACTION.history]: (ctx) => openGoalHistoryOverlay(ctx, manager),\n },\n onError: (error, _action, ctx) => {\n if (ctx.hasUI) ctx.ui.notify(error instanceof Error ? error.message : String(error), 'error');\n },\n });\n\n let disposed = false;\n const dispose = (): void => {\n if (disposed) return;\n disposed = true;\n stateDisposer();\n actions();\n leader.dispose();\n mode.dispose();\n activation.dispose();\n };\n pi.on('session_shutdown', dispose);\n}\n\nexport { registerGoalDoomExtension as default };\n"],"mappings":"iWAWA,MAAM,EAAiB,yBAIjB,EAAgB,SAChB,EAAc,CAClB,KAAM,YACN,MAAO,aACP,IAAK,WACL,QAAS,cACX,EAOA,SAAS,EAAgB,EAAwB,CAC/C,OAAQ,EAAR,CACE,KAAK,EACH,OAAO,EACT,IAAK,SACH,MAAO,SACT,IAAK,UACH,MAAO,UACT,IAAK,gBACH,MAAO,gBACT,IAAK,iBACH,MAAO,iBACT,IAAK,SACH,MAAO,SACT,QACE,OAAO,CACX,CACF,CAEA,SAAS,EACP,EACoF,CACpF,GAAI,OAAO,GAAW,UAAY,IAAW,WAAa,IAAW,WAAY,OACjF,IAA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B,MAAM,CAC/C,CAAC,EACD,EAAG,GAAG,oBAAuB,EAAa,EAAQ,SAAS,CAAC,CAAC,MAAM,MAAM,CAAC,EAC1E,IAAM,EAAU,EAAiC,EAAM,CACrD,OAAQ,EACR,SAAU,EACP,EAAY,MAAQ,GAAQ,EAAQ,eAAe,CAAG,GACtD,EAAY,OAAS,GAAQ,EAAQ,gBAAgB,CAAG,GACxD,EAAY,KAAO,GAAQ,EAAQ,cAAc,CAAG,GACpD,EAAY,SAAW,GAAQ,EAAuB,EAAK,CAAO,CACrE,EACA,SAAU,EAAO,EAAS,IAAQ,CAC5B,EAAI,OAAO,EAAI,GAAG,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,EAAG,OAAO,CAC9F,CACF,CAAC,EAEG,EAAW,GAUf,EAAG,GAAG,uBATsB,CACtB,IACJ,EAAW,GACX,EAAc,EACd,EAAQ,EACR,EAAO,QAAQ,EACf,EAAK,QAAQ,EACb,EAAW,QAAQ,EACrB,CACiC,CACnC"}
@@ -0,0 +1,2 @@
1
+ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require("./runtimeActivation.cjs");function t(t){e.registerGoalRuntime(t)}exports.activateGoalExtension=e.activateGoalExtension,exports.activateGoalRuntime=e.activateGoalRuntime,exports.default=t,exports.registerGoalExtension=t,exports.registerGoalRuntime=e.registerGoalRuntime;
2
+ //# sourceMappingURL=pi.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pi.cjs","names":[],"sources":["../../src/extensions/pi.ts"],"sourcesContent":["import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\nimport { registerGoalRuntime } from './runtimeActivation.ts';\n\nexport { activateGoalExtension, activateGoalRuntime, registerGoalRuntime } from './runtimeActivation.ts';\n\nexport function registerGoalExtension(pi: ExtensionAPI): void {\n registerGoalRuntime(pi);\n}\n\nexport { registerGoalExtension as default };\n"],"mappings":"0IAKA,SAAgB,EAAsB,EAAwB,CAC5D,EAAA,oBAAoB,CAAE,CACxB"}
@@ -0,0 +1,7 @@
1
+ import { activateGoalExtension, activateGoalRuntime, registerGoalRuntime } from "./runtimeActivation.cjs";
2
+ import { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+ //#region src/extensions/pi.d.ts
4
+ declare function registerGoalExtension(pi: ExtensionAPI): void;
5
+ //#endregion
6
+ export { activateGoalExtension, activateGoalRuntime, registerGoalExtension as default, registerGoalExtension, registerGoalRuntime };
7
+ //# sourceMappingURL=pi.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pi.d.cts","names":[],"sources":["../../src/extensions/pi.ts"],"mappings":";;;iBAKgB,sBAAsB,IAAI"}
@@ -0,0 +1,7 @@
1
+ import { activateGoalExtension, activateGoalRuntime, registerGoalRuntime } from "./runtimeActivation.mjs";
2
+ import { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+ //#region src/extensions/pi.d.ts
4
+ declare function registerGoalExtension(pi: ExtensionAPI): void;
5
+ //#endregion
6
+ export { activateGoalExtension, activateGoalRuntime, registerGoalExtension as default, registerGoalExtension, registerGoalRuntime };
7
+ //# sourceMappingURL=pi.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pi.d.mts","names":[],"sources":["../../src/extensions/pi.ts"],"mappings":";;;iBAKgB,sBAAsB,IAAI"}
@@ -0,0 +1,2 @@
1
+ import{activateGoalExtension as e,activateGoalRuntime as t,registerGoalRuntime as n}from"./runtimeActivation.mjs";function r(e){n(e)}export{e as activateGoalExtension,t as activateGoalRuntime,r as default,r as registerGoalExtension,n as registerGoalRuntime};
2
+ //# sourceMappingURL=pi.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pi.mjs","names":[],"sources":["../../src/extensions/pi.ts"],"sourcesContent":["import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\nimport { registerGoalRuntime } from './runtimeActivation.ts';\n\nexport { activateGoalExtension, activateGoalRuntime, registerGoalRuntime } from './runtimeActivation.ts';\n\nexport function registerGoalExtension(pi: ExtensionAPI): void {\n registerGoalRuntime(pi);\n}\n\nexport { registerGoalExtension as default };\n"],"mappings":"kHAKA,SAAgB,EAAsB,EAAwB,CAC5D,EAAoB,CAAE,CACxB"}
@@ -0,0 +1,2 @@
1
+ const e=require("../adapters/pi/goalManager.cjs"),t=require("../container/index.cjs"),n=Symbol.for(`@agimon-ai/doompi-goal/installed-hosts`);function r(e){let t=globalThis,r=t[n]??new WeakSet;return t[n]=r,!r.has(e)&&(r.add(e),!0)}function i(n,r){let i=r??t.createGoalContainer(),a=new e.GoalPiManager(n,i,r?.service),o=a.register(),s=!1;return{manager:a,dispose(){s||(s=!0,o())}}}function a(e,t){if(!r(e))return;let n=i(e,t);return e.on(`session_shutdown`,()=>n.dispose()),n}function o(e,t){let n=i(e,t);return()=>n.dispose()}exports.activateGoalExtension=o,exports.activateGoalRuntime=i,exports.registerGoalRuntime=a;
2
+ //# sourceMappingURL=runtimeActivation.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtimeActivation.cjs","names":["createGoalContainer","GoalPiManager"],"sources":["../../src/extensions/runtimeActivation.ts"],"sourcesContent":["import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\nimport { GoalPiManager } from '../adapters/pi/goalManager.ts';\nimport { createGoalContainer } from '../container/index.ts';\nimport type { GoalExtensionDependencies } from '../types/extension.ts';\n\nconst PACKAGE_SOURCE = '@agimon-ai/doompi-goal';\nconst INSTALLATIONS_KEY = Symbol.for(`${PACKAGE_SOURCE}/installed-hosts`);\n\ntype InstallationRegistry = typeof globalThis & {\n [INSTALLATIONS_KEY]?: WeakSet<object>;\n};\n\nfunction claimHostInstallation(pi: ExtensionAPI): boolean {\n const registry = globalThis as InstallationRegistry;\n const installedHosts = registry[INSTALLATIONS_KEY] ?? new WeakSet<object>();\n registry[INSTALLATIONS_KEY] = installedHosts;\n if (installedHosts.has(pi)) return false;\n installedHosts.add(pi);\n return true;\n}\n\nexport interface GoalRuntimeActivation {\n manager: GoalPiManager;\n dispose(): void;\n}\n\nexport function activateGoalRuntime(pi: ExtensionAPI, dependencies?: GoalExtensionDependencies): GoalRuntimeActivation {\n const resolvedDependencies = dependencies ?? createGoalContainer();\n const manager = new GoalPiManager(pi, resolvedDependencies, dependencies?.service);\n const disposeManager = manager.register();\n let disposed = false;\n return {\n manager,\n dispose() {\n if (disposed) return;\n disposed = true;\n disposeManager();\n },\n };\n}\n\nexport function registerGoalRuntime(\n pi: ExtensionAPI,\n dependencies?: GoalExtensionDependencies,\n): GoalRuntimeActivation | undefined {\n if (!claimHostInstallation(pi)) return undefined;\n const activation = activateGoalRuntime(pi, dependencies);\n pi.on('session_shutdown', () => activation.dispose());\n return activation;\n}\n\nexport function activateGoalExtension(pi: ExtensionAPI, dependencies?: GoalExtensionDependencies): () => void {\n const activation = activateGoalRuntime(pi, dependencies);\n return () => activation.dispose();\n}\n"],"mappings":"sFAMM,EAAoB,OAAO,IAAI,wCAAmC,EAMxE,SAAS,EAAsB,EAA2B,CACxD,IAAM,EAAW,WACX,EAAiB,EAAS,IAAsB,IAAI,QAI1D,MAHA,GAAS,GAAqB,EAC9B,CAAI,EAAe,IAAI,CAAE,IACzB,EAAe,IAAI,CAAE,EACd,GACT,CAOA,SAAgB,EAAoB,EAAkB,EAAiE,CACrH,IAAM,EAAuB,GAAgBA,EAAAA,oBAAoB,EAC3D,EAAU,IAAIC,EAAAA,cAAc,EAAI,EAAsB,GAAc,OAAO,EAC3E,EAAiB,EAAQ,SAAS,EACpC,EAAW,GACf,MAAO,CACL,UACA,SAAU,CACJ,IACJ,EAAW,GACX,EAAe,EACjB,CACF,CACF,CAEA,SAAgB,EACd,EACA,EACmC,CACnC,GAAI,CAAC,EAAsB,CAAE,EAAG,OAChC,IAAM,EAAa,EAAoB,EAAI,CAAY,EAEvD,OADA,EAAG,GAAG,uBAA0B,EAAW,QAAQ,CAAC,EAC7C,CACT,CAEA,SAAgB,EAAsB,EAAkB,EAAsD,CAC5G,IAAM,EAAa,EAAoB,EAAI,CAAY,EACvD,UAAa,EAAW,QAAQ,CAClC"}
@@ -0,0 +1,14 @@
1
+ import { GoalExtensionDependencies } from "../types/extension.cjs";
2
+ import { GoalPiManager } from "../adapters/pi/goalManager.cjs";
3
+ import { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
+ //#region src/extensions/runtimeActivation.d.ts
5
+ interface GoalRuntimeActivation {
6
+ manager: GoalPiManager;
7
+ dispose(): void;
8
+ }
9
+ declare function activateGoalRuntime(pi: ExtensionAPI, dependencies?: GoalExtensionDependencies): GoalRuntimeActivation;
10
+ declare function registerGoalRuntime(pi: ExtensionAPI, dependencies?: GoalExtensionDependencies): GoalRuntimeActivation | undefined;
11
+ declare function activateGoalExtension(pi: ExtensionAPI, dependencies?: GoalExtensionDependencies): () => void;
12
+ //#endregion
13
+ export { GoalRuntimeActivation, activateGoalExtension, activateGoalRuntime, registerGoalRuntime };
14
+ //# sourceMappingURL=runtimeActivation.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtimeActivation.d.cts","names":[],"sources":["../../src/extensions/runtimeActivation.ts"],"mappings":";;;;UAqBiB;EACf,SAAS;EACT;;iBAGc,oBAAoB,IAAI,cAAc,eAAe,4BAA4B;iBAejF,oBACd,IAAI,cACJ,eAAe,4BACd;iBAOa,sBAAsB,IAAI,cAAc,eAAe"}
@@ -0,0 +1,14 @@
1
+ import { GoalExtensionDependencies } from "../types/extension.mjs";
2
+ import { GoalPiManager } from "../adapters/pi/goalManager.mjs";
3
+ import { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
+ //#region src/extensions/runtimeActivation.d.ts
5
+ interface GoalRuntimeActivation {
6
+ manager: GoalPiManager;
7
+ dispose(): void;
8
+ }
9
+ declare function activateGoalRuntime(pi: ExtensionAPI, dependencies?: GoalExtensionDependencies): GoalRuntimeActivation;
10
+ declare function registerGoalRuntime(pi: ExtensionAPI, dependencies?: GoalExtensionDependencies): GoalRuntimeActivation | undefined;
11
+ declare function activateGoalExtension(pi: ExtensionAPI, dependencies?: GoalExtensionDependencies): () => void;
12
+ //#endregion
13
+ export { GoalRuntimeActivation, activateGoalExtension, activateGoalRuntime, registerGoalRuntime };
14
+ //# sourceMappingURL=runtimeActivation.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtimeActivation.d.mts","names":[],"sources":["../../src/extensions/runtimeActivation.ts"],"mappings":";;;;UAqBiB;EACf,SAAS;EACT;;iBAGc,oBAAoB,IAAI,cAAc,eAAe,4BAA4B;iBAejF,oBACd,IAAI,cACJ,eAAe,4BACd;iBAOa,sBAAsB,IAAI,cAAc,eAAe"}
@@ -0,0 +1,2 @@
1
+ import{GoalPiManager as e}from"../adapters/pi/goalManager.mjs";import{createGoalContainer as t}from"../container/index.mjs";const n=Symbol.for(`@agimon-ai/doompi-goal/installed-hosts`);function r(e){let t=globalThis,r=t[n]??new WeakSet;return t[n]=r,!r.has(e)&&(r.add(e),!0)}function i(n,r){let i=r??t(),a=new e(n,i,r?.service),o=a.register(),s=!1;return{manager:a,dispose(){s||(s=!0,o())}}}function a(e,t){if(!r(e))return;let n=i(e,t);return e.on(`session_shutdown`,()=>n.dispose()),n}function o(e,t){let n=i(e,t);return()=>n.dispose()}export{o as activateGoalExtension,i as activateGoalRuntime,a as registerGoalRuntime};
2
+ //# sourceMappingURL=runtimeActivation.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtimeActivation.mjs","names":[],"sources":["../../src/extensions/runtimeActivation.ts"],"sourcesContent":["import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\nimport { GoalPiManager } from '../adapters/pi/goalManager.ts';\nimport { createGoalContainer } from '../container/index.ts';\nimport type { GoalExtensionDependencies } from '../types/extension.ts';\n\nconst PACKAGE_SOURCE = '@agimon-ai/doompi-goal';\nconst INSTALLATIONS_KEY = Symbol.for(`${PACKAGE_SOURCE}/installed-hosts`);\n\ntype InstallationRegistry = typeof globalThis & {\n [INSTALLATIONS_KEY]?: WeakSet<object>;\n};\n\nfunction claimHostInstallation(pi: ExtensionAPI): boolean {\n const registry = globalThis as InstallationRegistry;\n const installedHosts = registry[INSTALLATIONS_KEY] ?? new WeakSet<object>();\n registry[INSTALLATIONS_KEY] = installedHosts;\n if (installedHosts.has(pi)) return false;\n installedHosts.add(pi);\n return true;\n}\n\nexport interface GoalRuntimeActivation {\n manager: GoalPiManager;\n dispose(): void;\n}\n\nexport function activateGoalRuntime(pi: ExtensionAPI, dependencies?: GoalExtensionDependencies): GoalRuntimeActivation {\n const resolvedDependencies = dependencies ?? createGoalContainer();\n const manager = new GoalPiManager(pi, resolvedDependencies, dependencies?.service);\n const disposeManager = manager.register();\n let disposed = false;\n return {\n manager,\n dispose() {\n if (disposed) return;\n disposed = true;\n disposeManager();\n },\n };\n}\n\nexport function registerGoalRuntime(\n pi: ExtensionAPI,\n dependencies?: GoalExtensionDependencies,\n): GoalRuntimeActivation | undefined {\n if (!claimHostInstallation(pi)) return undefined;\n const activation = activateGoalRuntime(pi, dependencies);\n pi.on('session_shutdown', () => activation.dispose());\n return activation;\n}\n\nexport function activateGoalExtension(pi: ExtensionAPI, dependencies?: GoalExtensionDependencies): () => void {\n const activation = activateGoalRuntime(pi, dependencies);\n return () => activation.dispose();\n}\n"],"mappings":"4HAMA,MAAM,EAAoB,OAAO,IAAI,wCAAmC,EAMxE,SAAS,EAAsB,EAA2B,CACxD,IAAM,EAAW,WACX,EAAiB,EAAS,IAAsB,IAAI,QAI1D,MAHA,GAAS,GAAqB,EAC9B,CAAI,EAAe,IAAI,CAAE,IACzB,EAAe,IAAI,CAAE,EACd,GACT,CAOA,SAAgB,EAAoB,EAAkB,EAAiE,CACrH,IAAM,EAAuB,GAAgB,EAAoB,EAC3D,EAAU,IAAI,EAAc,EAAI,EAAsB,GAAc,OAAO,EAC3E,EAAiB,EAAQ,SAAS,EACpC,EAAW,GACf,MAAO,CACL,UACA,SAAU,CACJ,IACJ,EAAW,GACX,EAAe,EACjB,CACF,CACF,CAEA,SAAgB,EACd,EACA,EACmC,CACnC,GAAI,CAAC,EAAsB,CAAE,EAAG,OAChC,IAAM,EAAa,EAAoB,EAAI,CAAY,EAEvD,OADA,EAAG,GAAG,uBAA0B,EAAW,QAAQ,CAAC,EAC7C,CACT,CAEA,SAAgB,EAAsB,EAAkB,EAAsD,CAC5G,IAAM,EAAa,EAAoB,EAAI,CAAY,EACvD,UAAa,EAAW,QAAQ,CAClC"}