@caupulican/pi-adaptative 0.90.6 → 0.90.7

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 (63) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/core/agent-session-contracts.d.ts +2 -0
  3. package/dist/core/agent-session-contracts.d.ts.map +1 -1
  4. package/dist/core/agent-session-contracts.js.map +1 -1
  5. package/dist/core/agent-session.d.ts +5 -10
  6. package/dist/core/agent-session.d.ts.map +1 -1
  7. package/dist/core/agent-session.js +33 -10
  8. package/dist/core/agent-session.js.map +1 -1
  9. package/dist/core/delegation/worker-delegation-controller.d.ts +3 -7
  10. package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
  11. package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
  12. package/dist/core/delegation/worker-notification-coordinator.d.ts +2 -0
  13. package/dist/core/delegation/worker-notification-coordinator.d.ts.map +1 -1
  14. package/dist/core/delegation/worker-notification-coordinator.js +9 -20
  15. package/dist/core/delegation/worker-notification-coordinator.js.map +1 -1
  16. package/dist/core/durable-custom-message-turn-controller.d.ts +24 -0
  17. package/dist/core/durable-custom-message-turn-controller.d.ts.map +1 -0
  18. package/dist/core/durable-custom-message-turn-controller.js +60 -0
  19. package/dist/core/durable-custom-message-turn-controller.js.map +1 -0
  20. package/dist/core/foreground-terminal-handoff-controller.d.ts +13 -7
  21. package/dist/core/foreground-terminal-handoff-controller.d.ts.map +1 -1
  22. package/dist/core/foreground-terminal-handoff-controller.js +48 -10
  23. package/dist/core/foreground-terminal-handoff-controller.js.map +1 -1
  24. package/dist/core/goal-loop-controller.d.ts +5 -9
  25. package/dist/core/goal-loop-controller.d.ts.map +1 -1
  26. package/dist/core/goal-loop-controller.js +9 -6
  27. package/dist/core/goal-loop-controller.js.map +1 -1
  28. package/dist/core/goals/goal-session-controller.d.ts +30 -1
  29. package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
  30. package/dist/core/goals/goal-session-controller.js +155 -18
  31. package/dist/core/goals/goal-session-controller.js.map +1 -1
  32. package/dist/core/goals/goal-state.d.ts +6 -7
  33. package/dist/core/goals/goal-state.d.ts.map +1 -1
  34. package/dist/core/goals/goal-state.js.map +1 -1
  35. package/dist/core/goals/natural-language-goal.d.ts +6 -0
  36. package/dist/core/goals/natural-language-goal.d.ts.map +1 -1
  37. package/dist/core/goals/natural-language-goal.js +36 -1
  38. package/dist/core/goals/natural-language-goal.js.map +1 -1
  39. package/dist/core/provider-request-runtime-controller.d.ts +1 -0
  40. package/dist/core/provider-request-runtime-controller.d.ts.map +1 -1
  41. package/dist/core/provider-request-runtime-controller.js +10 -2
  42. package/dist/core/provider-request-runtime-controller.js.map +1 -1
  43. package/dist/core/runtime-builder.d.ts +3 -0
  44. package/dist/core/runtime-builder.d.ts.map +1 -1
  45. package/dist/core/runtime-builder.js +3 -0
  46. package/dist/core/runtime-builder.js.map +1 -1
  47. package/dist/core/tool-recovery-logger.d.ts +2 -0
  48. package/dist/core/tool-recovery-logger.d.ts.map +1 -1
  49. package/dist/core/tool-recovery-logger.js +11 -0
  50. package/dist/core/tool-recovery-logger.js.map +1 -1
  51. package/dist/core/tools/goal.d.ts +2 -0
  52. package/dist/core/tools/goal.d.ts.map +1 -1
  53. package/dist/core/tools/goal.js +9 -0
  54. package/dist/core/tools/goal.js.map +1 -1
  55. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  56. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  57. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  58. package/examples/extensions/sandbox/package-lock.json +2 -2
  59. package/examples/extensions/sandbox/package.json +1 -1
  60. package/examples/extensions/with-deps/package-lock.json +2 -2
  61. package/examples/extensions/with-deps/package.json +1 -1
  62. package/npm-shrinkwrap.json +12 -12
  63. package/package.json +4 -4
@@ -1,10 +1,12 @@
1
1
  import type { SessionManager } from "@caupulican/pi-agent-core/session";
2
+ import type { AssistantMessage } from "@caupulican/pi-ai";
2
3
  import type { GoalContinuationLoopOptions, GoalContinuationLoopResult, GoalContinuationOnceOptions, GoalContinuationOnceResult, PromptOptions } from "../agent-session-contracts.ts";
3
4
  import type { LaneRecord } from "../autonomy/lane-tracker.ts";
4
5
  import type { TaskRuntimeProjection } from "../orchestration/task-runtime.ts";
5
6
  import { type GoalStateRevision } from "./goal-lifecycle.ts";
6
7
  import { type GoalRuntimeSnapshot, type GoalRuntimeSnapshotSettings } from "./goal-runtime-snapshot.ts";
7
8
  import { type GoalState } from "./goal-state.ts";
9
+ import { type ExplicitGoalStartAuthority } from "./natural-language-goal.ts";
8
10
  export interface GoalSessionControllerDeps {
9
11
  getSessionManager(): SessionManager;
10
12
  getModelProvider(): string | undefined;
@@ -24,6 +26,12 @@ export type ChatGoalAdmission = {
24
26
  status: "unfinished_goal_exists";
25
27
  state: GoalState;
26
28
  };
29
+ declare const goalExecutionLeaseMarker: unique symbol;
30
+ /** Identity-bound attribution for one goal-owned foreground execution. */
31
+ export interface GoalExecutionLease {
32
+ readonly goalId?: string;
33
+ readonly [goalExecutionLeaseMarker]: true;
34
+ }
27
35
  /**
28
36
  * Owns durable goal state, exact continuation accounting, and the raw continuation loop. The
29
37
  * AgentSession facade supplies process collaborators but no longer implements goal lifecycle rules.
@@ -31,6 +39,8 @@ export type ChatGoalAdmission = {
31
39
  export declare class GoalSessionController {
32
40
  private readonly deps;
33
41
  private readonly loop;
42
+ private executionLease;
43
+ private startAuthority;
34
44
  constructor(deps: GoalSessionControllerDeps);
35
45
  saveState(state: GoalState, expected?: GoalStateRevision): string;
36
46
  clearState(state: GoalState, now: string): string;
@@ -41,11 +51,29 @@ export declare class GoalSessionController {
41
51
  * goal, and an unfinished goal is never replaced implicitly.
42
52
  */
43
53
  admitExplicitChatGoal(text: string, now?: string): ChatGoalAdmission;
54
+ /** Attribute turn/wall-clock telemetry after usage has already been charged per response. */
44
55
  recordContinuationPass(pass: {
45
56
  turns: number;
46
57
  wallClockMs: number;
47
- usageCursor: string | null;
48
58
  }): void;
59
+ /** Begin one foreground execution whose provider usage belongs to the specified active goal. */
60
+ beginExecution(goalId: string | undefined, options?: {
61
+ adoptNewGoal?: boolean;
62
+ provisionalTokenBudget?: number;
63
+ }): GoalExecutionLease | undefined;
64
+ endExecution(lease: GoalExecutionLease | undefined): void;
65
+ /** Charge one observed assistant response exactly once, including routed responses buffered from persistence. */
66
+ recordExecutionUsage(message: AssistantMessage): void;
67
+ private chargeExecutionUsage;
68
+ markProtocolFailureBlocked(errorMessage: string): boolean;
69
+ setStartAuthority(authority: ExplicitGoalStartAuthority | undefined): void;
70
+ authorizeStartFromTool(input: {
71
+ tokenBudget?: number;
72
+ }): string | undefined;
73
+ /** Reserve only remaining output capacity; actual provider usage is charged on response. */
74
+ admitProviderRequest(): number | undefined;
75
+ private resolveExecutionState;
76
+ private flushPendingExecutionUsage;
49
77
  markToolUnavailable(): void;
50
78
  markRunawayBlocked(info: {
51
79
  signature: string;
@@ -60,4 +88,5 @@ export declare class GoalSessionController {
60
88
  private markBudgetLimited;
61
89
  private stopActiveGoal;
62
90
  }
91
+ export {};
63
92
  //# sourceMappingURL=goal-session-controller.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"goal-session-controller.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-session-controller.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mCAAmC,CAAC;AAExE,OAAO,KAAK,EACX,2BAA2B,EAC3B,0BAA0B,EAC1B,2BAA2B,EAC3B,0BAA0B,EAC1B,aAAa,EACb,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAE9D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAC9E,OAAO,EAAE,KAAK,iBAAiB,EAA4C,MAAM,qBAAqB,CAAC;AACvG,OAAO,EAEN,KAAK,mBAAmB,EACxB,KAAK,2BAA2B,EAChC,MAA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CAAC,IAAI,EAAE;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAKxE;IAED,8BAA8B,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAKxD;IAED,kBAAkB,CAAC,QAAQ,EAAE,2BAA2B,GAAG,mBAAmB,CAO7E;IAED,YAAY,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAEtF;IAED,YAAY,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAEtF;IAED,kBAAkB,IAAI,IAAI,CAEzB;IAED,OAAO,CAAC,yBAAyB;IASjC,OAAO,CAAC,iBAAiB;IAIzB,OAAO,CAAC,cAAc;CAOtB"}
@@ -1,12 +1,14 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { classifyFailure } from "@caupulican/pi-agent-core/reliability";
3
3
  import { GoalLoopController } from "../goal-loop-controller.js";
4
+ import { budgetedTokens } from "../orchestration/capability-gateway.js";
4
5
  import { getGoalStateRevision, stopGoalFromSystem } from "./goal-lifecycle.js";
5
6
  import { buildGoalRuntimeSnapshot, } from "./goal-runtime-snapshot.js";
6
7
  import { applyGoalEvent, isGoalUnfinishedStatus } from "./goal-state.js";
7
8
  import { applyGoalAction } from "./goal-tool-core.js";
8
9
  import { parseExplicitChatGoal } from "./natural-language-goal.js";
9
10
  import { appendGoalClearedSnapshot, appendGoalStateSnapshot, getLatestGoalStateSnapshot, } from "./session-goal-state.js";
11
+ const goalExecutionLeaseMarker = Symbol("goalExecutionLease");
10
12
  /**
11
13
  * Owns durable goal state, exact continuation accounting, and the raw continuation loop. The
12
14
  * AgentSession facade supplies process collaborators but no longer implements goal lifecycle rules.
@@ -17,7 +19,6 @@ export class GoalSessionController {
17
19
  this.loop = new GoalLoopController({
18
20
  getGoalRuntimeSnapshot: (settings) => this.getRuntimeSnapshot(settings),
19
21
  prompt: (text, options) => this.deps.prompt(text, options),
20
- captureUsageCursor: () => this.deps.getSessionManager().getLeafId(),
21
22
  recordGoalContinuationPass: (pass) => this.recordContinuationPass(pass),
22
23
  recordGoalContinuationFailure: (error) => this.recordContinuationFailure(error),
23
24
  markGoalBudgetLimited: (reason) => this.markBudgetLimited(reason),
@@ -69,41 +70,177 @@ export class GoalSessionController {
69
70
  .update(`${now}\0${current?.goalId ?? "none"}\0${parsed.objective}`)
70
71
  .digest("hex")
71
72
  .slice(0, 20);
72
- const result = applyGoalAction(current, { action: "start", goalId: `chat-${digest}`, userGoal: parsed.objective }, now);
73
+ const result = applyGoalAction(current, {
74
+ action: "start",
75
+ goalId: `chat-${digest}`,
76
+ userGoal: parsed.objective,
77
+ tokenBudget: parsed.tokenBudget,
78
+ }, now);
73
79
  if (!result.ok)
74
80
  throw new Error(result.error);
75
81
  this.saveState(result.state, current ? getGoalStateRevision(current) : undefined);
76
82
  return { status: "started", state: result.state };
77
83
  }
84
+ /** Attribute turn/wall-clock telemetry after usage has already been charged per response. */
78
85
  recordContinuationPass(pass) {
79
86
  const state = this.getState();
80
87
  if (!state)
81
88
  return;
82
- const branch = this.deps.getSessionManager().getBranch();
83
- const cursorIndex = pass.usageCursor === null ? -1 : branch.findIndex((entry) => entry.id === pass.usageCursor);
84
- if (pass.usageCursor !== null && cursorIndex < 0) {
85
- this.deps.emitWarning("Goal usage cursor is no longer on the active branch; stopping instead of guessing usage.");
86
- this.recordContinuationFailure(new Error("goal_usage_cursor_lost"));
87
- return;
88
- }
89
- let tokens = 0;
90
- let spendUsd = 0;
91
- for (const entry of branch.slice(cursorIndex + 1)) {
92
- if (entry.type !== "message" || entry.message.role !== "assistant")
93
- continue;
94
- const usage = entry.message.usage;
95
- tokens += Math.max(0, usage.input) + Math.max(0, usage.output);
96
- spendUsd += Math.max(0, usage.cost.total);
97
- }
98
89
  const updated = applyGoalEvent(state, {
99
90
  type: "record_continuation_budget",
100
91
  turns: pass.turns,
101
92
  wallClockMs: pass.wallClockMs,
93
+ tokens: 0,
94
+ spendUsd: 0,
95
+ now: new Date().toISOString(),
96
+ });
97
+ this.saveState(updated, getGoalStateRevision(state));
98
+ }
99
+ /** Begin one foreground execution whose provider usage belongs to the specified active goal. */
100
+ beginExecution(goalId, options = {}) {
101
+ if (!goalId && !options.adoptNewGoal)
102
+ return undefined;
103
+ if (this.executionLease)
104
+ throw new Error("Goal execution attribution is already active");
105
+ const state = this.getState();
106
+ if (goalId && (!state || state.goalId !== goalId || state.status !== "active"))
107
+ return undefined;
108
+ const lease = {
109
+ ...(goalId ? { goalId } : {}),
110
+ [goalExecutionLeaseMarker]: true,
111
+ adoptNewGoal: options.adoptNewGoal === true,
112
+ ...(options.adoptNewGoal && state ? { adoptionBaselineGoalId: state.goalId } : {}),
113
+ ...(options.provisionalTokenBudget !== undefined
114
+ ? { provisionalTokenBudget: options.provisionalTokenBudget }
115
+ : {}),
116
+ pendingTokens: 0,
117
+ pendingSpendUsd: 0,
118
+ };
119
+ this.executionLease = lease;
120
+ return lease;
121
+ }
122
+ endExecution(lease) {
123
+ if (!lease)
124
+ return;
125
+ if (this.executionLease !== lease)
126
+ throw new Error("Cannot end goal execution attribution owned by another run");
127
+ this.flushPendingExecutionUsage(this.executionLease);
128
+ this.executionLease = undefined;
129
+ }
130
+ /** Charge one observed assistant response exactly once, including routed responses buffered from persistence. */
131
+ recordExecutionUsage(message) {
132
+ const lease = this.executionLease;
133
+ if (!lease)
134
+ return;
135
+ const tokens = budgetedTokens({
136
+ inputTokens: Math.max(0, message.usage.input),
137
+ outputTokens: Math.max(0, message.usage.output),
138
+ cacheReadTokens: Math.max(0, message.usage.cacheRead),
139
+ cacheWriteTokens: Math.max(0, message.usage.cacheWrite),
140
+ totalTokens: Math.max(0, message.usage.totalTokens),
141
+ });
142
+ const spendUsd = Math.max(0, message.usage.cost.total);
143
+ if (tokens === 0 && spendUsd === 0)
144
+ return;
145
+ const state = this.resolveExecutionState(lease);
146
+ if (!state) {
147
+ lease.pendingTokens += tokens;
148
+ lease.pendingSpendUsd += spendUsd;
149
+ return;
150
+ }
151
+ this.chargeExecutionUsage(lease, state, tokens, spendUsd);
152
+ }
153
+ chargeExecutionUsage(lease, state, tokens, spendUsd) {
154
+ const updated = applyGoalEvent(state, {
155
+ type: "record_continuation_budget",
156
+ turns: 0,
157
+ wallClockMs: 0,
102
158
  tokens,
103
159
  spendUsd,
104
160
  now: new Date().toISOString(),
105
161
  });
106
162
  this.saveState(updated, getGoalStateRevision(state));
163
+ lease.pendingTokens = 0;
164
+ lease.pendingSpendUsd = 0;
165
+ if (updated.status === "active" &&
166
+ updated.tokenBudget !== undefined &&
167
+ (updated.tokensUsed ?? 0) >= updated.tokenBudget) {
168
+ this.markBudgetLimited(`token budget exhausted (${updated.tokensUsed ?? 0}/${updated.tokenBudget}) during goal execution`);
169
+ }
170
+ }
171
+ markProtocolFailureBlocked(errorMessage) {
172
+ const lease = this.executionLease;
173
+ if (!lease)
174
+ return false;
175
+ const state = this.resolveExecutionState(lease);
176
+ if (!state || state.status !== "active")
177
+ return false;
178
+ const stopped = stopGoalFromSystem(state, { status: "blocked", reason: errorMessage.slice(0, 500) }, new Date().toISOString());
179
+ if (!stopped.ok)
180
+ return false;
181
+ this.saveState(stopped.state, getGoalStateRevision(state));
182
+ return true;
183
+ }
184
+ setStartAuthority(authority) {
185
+ this.startAuthority = authority;
186
+ }
187
+ authorizeStartFromTool(input) {
188
+ const authority = this.startAuthority;
189
+ if (!authority)
190
+ return "goal start requires explicit owner authorization in the current prompt.";
191
+ if (authority.tokenBudget === undefined && input.tokenBudget !== undefined) {
192
+ return "tokenBudget requires an exact numeric token ceiling in the current owner prompt.";
193
+ }
194
+ if (authority.tokenBudget !== undefined && input.tokenBudget !== authority.tokenBudget) {
195
+ return `tokenBudget must equal the owner-requested ceiling ${authority.tokenBudget}.`;
196
+ }
197
+ return undefined;
198
+ }
199
+ /** Reserve only remaining output capacity; actual provider usage is charged on response. */
200
+ admitProviderRequest() {
201
+ const lease = this.executionLease;
202
+ if (!lease)
203
+ return undefined;
204
+ this.flushPendingExecutionUsage(lease);
205
+ const state = this.resolveExecutionState(lease);
206
+ const tokenBudget = state?.tokenBudget ?? lease.provisionalTokenBudget;
207
+ if (tokenBudget === undefined)
208
+ return undefined;
209
+ if (state?.status === "budget_limited") {
210
+ throw new Error(`goal_token_budget_exhausted: ${state.blockedReason ?? lease.goalId}`);
211
+ }
212
+ if (state && state.status !== "active")
213
+ return undefined;
214
+ const tokensUsed = state?.tokensUsed ?? lease.pendingTokens;
215
+ const remaining = Math.max(0, tokenBudget - tokensUsed);
216
+ if (remaining === 0) {
217
+ if (state) {
218
+ this.markBudgetLimited(`token budget exhausted (${tokensUsed}/${tokenBudget}) before provider request`);
219
+ }
220
+ throw new Error(`goal_token_budget_exhausted: no tokens remain for provider output`);
221
+ }
222
+ return remaining;
223
+ }
224
+ resolveExecutionState(lease) {
225
+ const state = this.getState();
226
+ if (!state)
227
+ return undefined;
228
+ if (lease.goalId === state.goalId)
229
+ return state;
230
+ if (lease.goalId !== undefined || !lease.adoptNewGoal)
231
+ return undefined;
232
+ if (lease.adoptionBaselineGoalId === state.goalId)
233
+ return undefined;
234
+ lease.goalId = state.goalId;
235
+ return state;
236
+ }
237
+ flushPendingExecutionUsage(lease) {
238
+ if (lease.pendingTokens === 0 && lease.pendingSpendUsd === 0)
239
+ return;
240
+ const state = this.resolveExecutionState(lease);
241
+ if (!state)
242
+ return;
243
+ this.chargeExecutionUsage(lease, state, lease.pendingTokens, lease.pendingSpendUsd);
107
244
  }
108
245
  markToolUnavailable() {
109
246
  this.stopActiveGoal("blocked", "goal_tool_unavailable: the active capability surface cannot update durable goal state");
@@ -1 +1 @@
1
- {"version":3,"file":"goal-session-controller.js","sourceRoot":"","sources":["../../../src/core/goals/goal-session-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AAWxE,OA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,EAAE,MAAc;QAC5F,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC;QAC9B,MAAM,OAAO,GAAG,kBAAkB,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC;QACxF,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,KAAK;YAAE,OAAO,KAAK,CAAC;QACxC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,KAAK,EAAE,oBAAoB,CAAC,KAAK,CAAC,CAAC,CAAC;QAC3D,OAAO,IAAI,CAAC;IACb,CAAC;CACD","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { classifyFailure } from \"@caupulican/pi-agent-core/reliability\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/session\";\nimport type { AssistantMessage } from \"@caupulican/pi-ai\";\nimport type {\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tGoalContinuationOnceOptions,\n\tGoalContinuationOnceResult,\n\tPromptOptions,\n} from \"../agent-session-contracts.ts\";\nimport type { LaneRecord } from \"../autonomy/lane-tracker.ts\";\nimport { GoalLoopController } from \"../goal-loop-controller.ts\";\nimport type { TaskRuntimeProjection } from \"../orchestration/task-runtime.ts\";\nimport { type GoalStateRevision, getGoalStateRevision, stopGoalFromSystem } from \"./goal-lifecycle.ts\";\nimport {\n\tbuildGoalRuntimeSnapshot,\n\ttype GoalRuntimeSnapshot,\n\ttype GoalRuntimeSnapshotSettings,\n} from \"./goal-runtime-snapshot.ts\";\nimport { applyGoalEvent, type GoalState, isGoalUnfinishedStatus } from \"./goal-state.ts\";\nimport { applyGoalAction } from \"./goal-tool-core.ts\";\nimport { parseExplicitChatGoal } from \"./natural-language-goal.ts\";\nimport {\n\tappendGoalClearedSnapshot,\n\tappendGoalStateSnapshot,\n\tgetLatestGoalStateSnapshot,\n} from \"./session-goal-state.ts\";\n\nexport interface GoalSessionControllerDeps {\n\tgetSessionManager(): SessionManager;\n\tgetModelProvider(): string | undefined;\n\tgetLaneRecords(): readonly LaneRecord[];\n\tgetTaskRuntimeSnapshot(): TaskRuntimeProjection | undefined;\n\tsynchronizeGoalState(state: GoalState): void;\n\tscheduleGoalAutoContinueFromIdle(): void;\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\temitWarning(message: string): void;\n}\n\nexport type ChatGoalAdmission =\n\t| { status: \"not_explicit\" }\n\t| { status: \"started\"; state: GoalState }\n\t| { status: \"unfinished_goal_exists\"; state: GoalState };\n\n/**\n * Owns durable goal state, exact continuation accounting, and the raw continuation loop. The\n * AgentSession facade supplies process collaborators but no longer implements goal lifecycle rules.\n */\nexport class GoalSessionController {\n\tprivate readonly deps: GoalSessionControllerDeps;\n\tprivate readonly loop: GoalLoopController;\n\n\tconstructor(deps: GoalSessionControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis.loop = new GoalLoopController({\n\t\t\tgetGoalRuntimeSnapshot: (settings) => this.getRuntimeSnapshot(settings),\n\t\t\tprompt: (text, options) => this.deps.prompt(text, options),\n\t\t\tcaptureUsageCursor: () => this.deps.getSessionManager().getLeafId(),\n\t\t\trecordGoalContinuationPass: (pass) => this.recordContinuationPass(pass),\n\t\t\trecordGoalContinuationFailure: (error) => this.recordContinuationFailure(error),\n\t\t\tmarkGoalBudgetLimited: (reason) => this.markBudgetLimited(reason),\n\t\t});\n\t}\n\n\tsaveState(state: GoalState, expected?: GoalStateRevision): string {\n\t\tconst current = this.getState();\n\t\tif (\n\t\t\texpected &&\n\t\t\t(!current || current.goalId !== expected.goalId || (current.revision ?? 0) !== expected.revision)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Goal state changed concurrently; expected ${expected.goalId}@${expected.revision}, found ${current ? `${current.goalId}@${current.revision ?? 0}` : \"none\"}. Retry against the latest state.`,\n\t\t\t);\n\t\t}\n\t\tconst entryId = appendGoalStateSnapshot(this.deps.getSessionManager(), state, current);\n\t\ttry {\n\t\t\tthis.deps.synchronizeGoalState(state);\n\t\t} catch (error) {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Goal state persisted but durable worker reconciliation failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\treturn entryId;\n\t}\n\n\tclearState(state: GoalState, now: string): string {\n\t\tconst current = this.getState();\n\t\tconst expected = getGoalStateRevision(state);\n\t\tif (!current || current.goalId !== expected.goalId || (current.revision ?? 0) !== expected.revision) {\n\t\t\tthrow new Error(\"Goal state changed concurrently; retry clear against the latest state.\");\n\t\t}\n\t\tif (state.status !== \"completed\" && state.status !== \"cancelled\") {\n\t\t\tthis.deps.synchronizeGoalState(applyGoalEvent(state, { type: \"cancel_goal\", now }));\n\t\t}\n\t\treturn appendGoalClearedSnapshot(this.deps.getSessionManager(), state, now);\n\t}\n\n\tgetState(): GoalState | undefined {\n\t\treturn getLatestGoalStateSnapshot(this.deps.getSessionManager());\n\t}\n\n\t/**\n\t * Promote high-confidence natural-language persistence into the same durable state written by the\n\t * goal tool. This is intentionally narrower than task detection: ordinary work never starts a\n\t * goal, and an unfinished goal is never replaced implicitly.\n\t */\n\tadmitExplicitChatGoal(text: string, now = new Date().toISOString()): ChatGoalAdmission {\n\t\tconst parsed = parseExplicitChatGoal(text);\n\t\tif (!parsed) return { status: \"not_explicit\" };\n\t\tconst current = this.getState();\n\t\tif (current && isGoalUnfinishedStatus(current.status)) {\n\t\t\treturn { status: \"unfinished_goal_exists\", state: current };\n\t\t}\n\t\tconst digest = createHash(\"sha256\")\n\t\t\t.update(`${now}\\0${current?.goalId ?? \"none\"}\\0${parsed.objective}`)\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 20);\n\t\tconst result = applyGoalAction(\n\t\t\tcurrent,\n\t\t\t{ action: \"start\", goalId: `chat-${digest}`, userGoal: parsed.objective },\n\t\t\tnow,\n\t\t);\n\t\tif (!result.ok) throw new Error(result.error);\n\t\tthis.saveState(result.state, current ? getGoalStateRevision(current) : undefined);\n\t\treturn { status: \"started\", state: result.state };\n\t}\n\n\trecordContinuationPass(pass: { turns: number; wallClockMs: number; usageCursor: string | null }): void {\n\t\tconst state = this.getState();\n\t\tif (!state) return;\n\t\tconst branch = this.deps.getSessionManager().getBranch();\n\t\tconst cursorIndex = pass.usageCursor === null ? -1 : branch.findIndex((entry) => entry.id === pass.usageCursor);\n\t\tif (pass.usageCursor !== null && cursorIndex < 0) {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t\"Goal usage cursor is no longer on the active branch; stopping instead of guessing usage.\",\n\t\t\t);\n\t\t\tthis.recordContinuationFailure(new Error(\"goal_usage_cursor_lost\"));\n\t\t\treturn;\n\t\t}\n\t\tlet tokens = 0;\n\t\tlet spendUsd = 0;\n\t\tfor (const entry of branch.slice(cursorIndex + 1)) {\n\t\t\tif (entry.type !== \"message\" || entry.message.role !== \"assistant\") continue;\n\t\t\tconst usage = (entry.message as AssistantMessage).usage;\n\t\t\ttokens += Math.max(0, usage.input) + Math.max(0, usage.output);\n\t\t\tspendUsd += Math.max(0, usage.cost.total);\n\t\t}\n\t\tconst updated = applyGoalEvent(state, {\n\t\t\ttype: \"record_continuation_budget\",\n\t\t\tturns: pass.turns,\n\t\t\twallClockMs: pass.wallClockMs,\n\t\t\ttokens,\n\t\t\tspendUsd,\n\t\t\tnow: new Date().toISOString(),\n\t\t});\n\t\tthis.saveState(updated, getGoalStateRevision(state));\n\t}\n\n\tmarkToolUnavailable(): void {\n\t\tthis.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t\"goal_tool_unavailable: the active capability surface cannot update durable goal state\",\n\t\t);\n\t}\n\n\tmarkRunawayBlocked(info: { signature: string; repeats: number }): boolean {\n\t\treturn this.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t`runaway_tool_loop: repeated tool-call signature ${info.signature} ${info.repeats} times without progress`,\n\t\t);\n\t}\n\n\tmarkTerminalToolFailureBlocked(toolName: string): boolean {\n\t\treturn this.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t`terminal_tool_failure: ${toolName} reported an unrecoverable error and terminated the run`,\n\t\t);\n\t}\n\n\tgetRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot {\n\t\treturn buildGoalRuntimeSnapshot({\n\t\t\tsessionManager: this.deps.getSessionManager(),\n\t\t\tsettings,\n\t\t\tlaneRecords: this.deps.getLaneRecords(),\n\t\t\ttaskRuntime: this.deps.getTaskRuntimeSnapshot(),\n\t\t});\n\t}\n\n\tcontinueOnce(options: GoalContinuationOnceOptions): Promise<GoalContinuationOnceResult> {\n\t\treturn this.loop.continueGoalOnce(options);\n\t}\n\n\tcontinueLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\treturn this.loop.continueGoalLoop(options);\n\t}\n\n\trestoreAfterResume(): void {\n\t\tthis.deps.scheduleGoalAutoContinueFromIdle();\n\t}\n\n\tprivate recordContinuationFailure(error: unknown): void {\n\t\tconst state = this.getState();\n\t\tif (!state || state.status !== \"active\") return;\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconst classified = classifyFailure({ message, provider: this.deps.getModelProvider() });\n\t\tconst status = classified.reason === \"billing_or_quota\" ? \"usage_limited\" : \"blocked\";\n\t\tthis.stopActiveGoal(status, `${classified.reason}: ${message}`);\n\t}\n\n\tprivate markBudgetLimited(reason: string): void {\n\t\tthis.stopActiveGoal(\"budget_limited\", reason);\n\t}\n\n\tprivate stopActiveGoal(status: \"blocked\" | \"usage_limited\" | \"budget_limited\", reason: string): boolean {\n\t\tconst state = this.getState();\n\t\tconst stopped = stopGoalFromSystem(state, { status, reason }, new Date().toISOString());\n\t\tif (!stopped.ok || !state) return false;\n\t\tthis.saveState(stopped.state, getGoalStateRevision(state));\n\t\treturn true;\n\t}\n}\n"]}
1
+ {"version":3,"file":"goal-session-controller.js","sourceRoot":"","sources":["../../../src/core/goals/goal-session-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,U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EAAE,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,EAAE,CAAC,CAAC;QACxF,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,KAAK,kBAAkB,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,SAAS,CAAC;QACtF,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE,GAAG,UAAU,CAAC,MAAM,KAAK,OAAO,EAAE,CAAC,CAAC;IACjE,CAAC;IAEO,iBAAiB,CAAC,MAAc;QACvC,IAAI,CAAC,cAAc,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAC;IAC/C,CAAC;IAEO,cAAc,CAAC,MAAsD,EAAE,MAAc;QAC5F,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC;QAC9B,MAAM,OAAO,GAAG,kBAAkB,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC;QACxF,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,KAAK;YAAE,OAAO,KAAK,CAAC;QACxC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,KAAK,EAAE,oBAAoB,CAAC,KAAK,CAAC,CAAC,CAAC;QAC3D,OAAO,IAAI,CAAC;IACb,CAAC;CACD","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { classifyFailure } from \"@caupulican/pi-agent-core/reliability\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/session\";\nimport type { AssistantMessage } from \"@caupulican/pi-ai\";\nimport type {\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tGoalContinuationOnceOptions,\n\tGoalContinuationOnceResult,\n\tPromptOptions,\n} from \"../agent-session-contracts.ts\";\nimport type { LaneRecord } from \"../autonomy/lane-tracker.ts\";\nimport { GoalLoopController } from \"../goal-loop-controller.ts\";\nimport { budgetedTokens } from \"../orchestration/capability-gateway.ts\";\nimport type { TaskRuntimeProjection } from \"../orchestration/task-runtime.ts\";\nimport { type GoalStateRevision, getGoalStateRevision, stopGoalFromSystem } from \"./goal-lifecycle.ts\";\nimport {\n\tbuildGoalRuntimeSnapshot,\n\ttype GoalRuntimeSnapshot,\n\ttype GoalRuntimeSnapshotSettings,\n} from \"./goal-runtime-snapshot.ts\";\nimport { applyGoalEvent, type GoalState, isGoalUnfinishedStatus } from \"./goal-state.ts\";\nimport { applyGoalAction } from \"./goal-tool-core.ts\";\nimport { type ExplicitGoalStartAuthority, parseExplicitChatGoal } from \"./natural-language-goal.ts\";\nimport {\n\tappendGoalClearedSnapshot,\n\tappendGoalStateSnapshot,\n\tgetLatestGoalStateSnapshot,\n} from \"./session-goal-state.ts\";\n\nexport interface GoalSessionControllerDeps {\n\tgetSessionManager(): SessionManager;\n\tgetModelProvider(): string | undefined;\n\tgetLaneRecords(): readonly LaneRecord[];\n\tgetTaskRuntimeSnapshot(): TaskRuntimeProjection | undefined;\n\tsynchronizeGoalState(state: GoalState): void;\n\tscheduleGoalAutoContinueFromIdle(): void;\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\temitWarning(message: string): void;\n}\n\nexport type ChatGoalAdmission =\n\t| { status: \"not_explicit\" }\n\t| { status: \"started\"; state: GoalState }\n\t| { status: \"unfinished_goal_exists\"; state: GoalState };\n\nconst goalExecutionLeaseMarker: unique symbol = Symbol(\"goalExecutionLease\");\n\n/** Identity-bound attribution for one goal-owned foreground execution. */\nexport interface GoalExecutionLease {\n\treadonly goalId?: string;\n\treadonly [goalExecutionLeaseMarker]: true;\n}\n\ninterface MutableGoalExecutionLease extends GoalExecutionLease {\n\tgoalId?: string;\n\tadoptNewGoal: boolean;\n\tadoptionBaselineGoalId?: string;\n\tprovisionalTokenBudget?: number;\n\tpendingTokens: number;\n\tpendingSpendUsd: number;\n}\n\n/**\n * Owns durable goal state, exact continuation accounting, and the raw continuation loop. The\n * AgentSession facade supplies process collaborators but no longer implements goal lifecycle rules.\n */\nexport class GoalSessionController {\n\tprivate readonly deps: GoalSessionControllerDeps;\n\tprivate readonly loop: GoalLoopController;\n\tprivate executionLease: MutableGoalExecutionLease | undefined;\n\tprivate startAuthority: ExplicitGoalStartAuthority | undefined;\n\n\tconstructor(deps: GoalSessionControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis.loop = new GoalLoopController({\n\t\t\tgetGoalRuntimeSnapshot: (settings) => this.getRuntimeSnapshot(settings),\n\t\t\tprompt: (text, options) => this.deps.prompt(text, options),\n\t\t\trecordGoalContinuationPass: (pass) => this.recordContinuationPass(pass),\n\t\t\trecordGoalContinuationFailure: (error) => this.recordContinuationFailure(error),\n\t\t\tmarkGoalBudgetLimited: (reason) => this.markBudgetLimited(reason),\n\t\t});\n\t}\n\n\tsaveState(state: GoalState, expected?: GoalStateRevision): string {\n\t\tconst current = this.getState();\n\t\tif (\n\t\t\texpected &&\n\t\t\t(!current || current.goalId !== expected.goalId || (current.revision ?? 0) !== expected.revision)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Goal state changed concurrently; expected ${expected.goalId}@${expected.revision}, found ${current ? `${current.goalId}@${current.revision ?? 0}` : \"none\"}. Retry against the latest state.`,\n\t\t\t);\n\t\t}\n\t\tconst entryId = appendGoalStateSnapshot(this.deps.getSessionManager(), state, current);\n\t\ttry {\n\t\t\tthis.deps.synchronizeGoalState(state);\n\t\t} catch (error) {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Goal state persisted but durable worker reconciliation failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\treturn entryId;\n\t}\n\n\tclearState(state: GoalState, now: string): string {\n\t\tconst current = this.getState();\n\t\tconst expected = getGoalStateRevision(state);\n\t\tif (!current || current.goalId !== expected.goalId || (current.revision ?? 0) !== expected.revision) {\n\t\t\tthrow new Error(\"Goal state changed concurrently; retry clear against the latest state.\");\n\t\t}\n\t\tif (state.status !== \"completed\" && state.status !== \"cancelled\") {\n\t\t\tthis.deps.synchronizeGoalState(applyGoalEvent(state, { type: \"cancel_goal\", now }));\n\t\t}\n\t\treturn appendGoalClearedSnapshot(this.deps.getSessionManager(), state, now);\n\t}\n\n\tgetState(): GoalState | undefined {\n\t\treturn getLatestGoalStateSnapshot(this.deps.getSessionManager());\n\t}\n\n\t/**\n\t * Promote high-confidence natural-language persistence into the same durable state written by the\n\t * goal tool. This is intentionally narrower than task detection: ordinary work never starts a\n\t * goal, and an unfinished goal is never replaced implicitly.\n\t */\n\tadmitExplicitChatGoal(text: string, now = new Date().toISOString()): ChatGoalAdmission {\n\t\tconst parsed = parseExplicitChatGoal(text);\n\t\tif (!parsed) return { status: \"not_explicit\" };\n\t\tconst current = this.getState();\n\t\tif (current && isGoalUnfinishedStatus(current.status)) {\n\t\t\treturn { status: \"unfinished_goal_exists\", state: current };\n\t\t}\n\t\tconst digest = createHash(\"sha256\")\n\t\t\t.update(`${now}\\0${current?.goalId ?? \"none\"}\\0${parsed.objective}`)\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 20);\n\t\tconst result = applyGoalAction(\n\t\t\tcurrent,\n\t\t\t{\n\t\t\t\taction: \"start\",\n\t\t\t\tgoalId: `chat-${digest}`,\n\t\t\t\tuserGoal: parsed.objective,\n\t\t\t\ttokenBudget: parsed.tokenBudget,\n\t\t\t},\n\t\t\tnow,\n\t\t);\n\t\tif (!result.ok) throw new Error(result.error);\n\t\tthis.saveState(result.state, current ? getGoalStateRevision(current) : undefined);\n\t\treturn { status: \"started\", state: result.state };\n\t}\n\n\t/** Attribute turn/wall-clock telemetry after usage has already been charged per response. */\n\trecordContinuationPass(pass: { turns: number; wallClockMs: number }): void {\n\t\tconst state = this.getState();\n\t\tif (!state) return;\n\t\tconst updated = applyGoalEvent(state, {\n\t\t\ttype: \"record_continuation_budget\",\n\t\t\tturns: pass.turns,\n\t\t\twallClockMs: pass.wallClockMs,\n\t\t\ttokens: 0,\n\t\t\tspendUsd: 0,\n\t\t\tnow: new Date().toISOString(),\n\t\t});\n\t\tthis.saveState(updated, getGoalStateRevision(state));\n\t}\n\n\t/** Begin one foreground execution whose provider usage belongs to the specified active goal. */\n\tbeginExecution(\n\t\tgoalId: string | undefined,\n\t\toptions: { adoptNewGoal?: boolean; provisionalTokenBudget?: number } = {},\n\t): GoalExecutionLease | undefined {\n\t\tif (!goalId && !options.adoptNewGoal) return undefined;\n\t\tif (this.executionLease) throw new Error(\"Goal execution attribution is already active\");\n\t\tconst state = this.getState();\n\t\tif (goalId && (!state || state.goalId !== goalId || state.status !== \"active\")) return undefined;\n\t\tconst lease: MutableGoalExecutionLease = {\n\t\t\t...(goalId ? { goalId } : {}),\n\t\t\t[goalExecutionLeaseMarker]: true,\n\t\t\tadoptNewGoal: options.adoptNewGoal === true,\n\t\t\t...(options.adoptNewGoal && state ? { adoptionBaselineGoalId: state.goalId } : {}),\n\t\t\t...(options.provisionalTokenBudget !== undefined\n\t\t\t\t? { provisionalTokenBudget: options.provisionalTokenBudget }\n\t\t\t\t: {}),\n\t\t\tpendingTokens: 0,\n\t\t\tpendingSpendUsd: 0,\n\t\t};\n\t\tthis.executionLease = lease;\n\t\treturn lease;\n\t}\n\n\tendExecution(lease: GoalExecutionLease | undefined): void {\n\t\tif (!lease) return;\n\t\tif (this.executionLease !== lease) throw new Error(\"Cannot end goal execution attribution owned by another run\");\n\t\tthis.flushPendingExecutionUsage(this.executionLease);\n\t\tthis.executionLease = undefined;\n\t}\n\n\t/** Charge one observed assistant response exactly once, including routed responses buffered from persistence. */\n\trecordExecutionUsage(message: AssistantMessage): void {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return;\n\t\tconst tokens = budgetedTokens({\n\t\t\tinputTokens: Math.max(0, message.usage.input),\n\t\t\toutputTokens: Math.max(0, message.usage.output),\n\t\t\tcacheReadTokens: Math.max(0, message.usage.cacheRead),\n\t\t\tcacheWriteTokens: Math.max(0, message.usage.cacheWrite),\n\t\t\ttotalTokens: Math.max(0, message.usage.totalTokens),\n\t\t});\n\t\tconst spendUsd = Math.max(0, message.usage.cost.total);\n\t\tif (tokens === 0 && spendUsd === 0) return;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state) {\n\t\t\tlease.pendingTokens += tokens;\n\t\t\tlease.pendingSpendUsd += spendUsd;\n\t\t\treturn;\n\t\t}\n\t\tthis.chargeExecutionUsage(lease, state, tokens, spendUsd);\n\t}\n\n\tprivate chargeExecutionUsage(\n\t\tlease: MutableGoalExecutionLease,\n\t\tstate: GoalState,\n\t\ttokens: number,\n\t\tspendUsd: number,\n\t): void {\n\t\tconst updated = applyGoalEvent(state, {\n\t\t\ttype: \"record_continuation_budget\",\n\t\t\tturns: 0,\n\t\t\twallClockMs: 0,\n\t\t\ttokens,\n\t\t\tspendUsd,\n\t\t\tnow: new Date().toISOString(),\n\t\t});\n\t\tthis.saveState(updated, getGoalStateRevision(state));\n\t\tlease.pendingTokens = 0;\n\t\tlease.pendingSpendUsd = 0;\n\t\tif (\n\t\t\tupdated.status === \"active\" &&\n\t\t\tupdated.tokenBudget !== undefined &&\n\t\t\t(updated.tokensUsed ?? 0) >= updated.tokenBudget\n\t\t) {\n\t\t\tthis.markBudgetLimited(\n\t\t\t\t`token budget exhausted (${updated.tokensUsed ?? 0}/${updated.tokenBudget}) during goal execution`,\n\t\t\t);\n\t\t}\n\t}\n\n\tmarkProtocolFailureBlocked(errorMessage: string): boolean {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return false;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state || state.status !== \"active\") return false;\n\t\tconst stopped = stopGoalFromSystem(\n\t\t\tstate,\n\t\t\t{ status: \"blocked\", reason: errorMessage.slice(0, 500) },\n\t\t\tnew Date().toISOString(),\n\t\t);\n\t\tif (!stopped.ok) return false;\n\t\tthis.saveState(stopped.state, getGoalStateRevision(state));\n\t\treturn true;\n\t}\n\n\tsetStartAuthority(authority: ExplicitGoalStartAuthority | undefined): void {\n\t\tthis.startAuthority = authority;\n\t}\n\n\tauthorizeStartFromTool(input: { tokenBudget?: number }): string | undefined {\n\t\tconst authority = this.startAuthority;\n\t\tif (!authority) return \"goal start requires explicit owner authorization in the current prompt.\";\n\t\tif (authority.tokenBudget === undefined && input.tokenBudget !== undefined) {\n\t\t\treturn \"tokenBudget requires an exact numeric token ceiling in the current owner prompt.\";\n\t\t}\n\t\tif (authority.tokenBudget !== undefined && input.tokenBudget !== authority.tokenBudget) {\n\t\t\treturn `tokenBudget must equal the owner-requested ceiling ${authority.tokenBudget}.`;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/** Reserve only remaining output capacity; actual provider usage is charged on response. */\n\tadmitProviderRequest(): number | undefined {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return undefined;\n\t\tthis.flushPendingExecutionUsage(lease);\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tconst tokenBudget = state?.tokenBudget ?? lease.provisionalTokenBudget;\n\t\tif (tokenBudget === undefined) return undefined;\n\t\tif (state?.status === \"budget_limited\") {\n\t\t\tthrow new Error(`goal_token_budget_exhausted: ${state.blockedReason ?? lease.goalId}`);\n\t\t}\n\t\tif (state && state.status !== \"active\") return undefined;\n\t\tconst tokensUsed = state?.tokensUsed ?? lease.pendingTokens;\n\t\tconst remaining = Math.max(0, tokenBudget - tokensUsed);\n\t\tif (remaining === 0) {\n\t\t\tif (state) {\n\t\t\t\tthis.markBudgetLimited(`token budget exhausted (${tokensUsed}/${tokenBudget}) before provider request`);\n\t\t\t}\n\t\t\tthrow new Error(`goal_token_budget_exhausted: no tokens remain for provider output`);\n\t\t}\n\t\treturn remaining;\n\t}\n\n\tprivate resolveExecutionState(lease: MutableGoalExecutionLease): GoalState | undefined {\n\t\tconst state = this.getState();\n\t\tif (!state) return undefined;\n\t\tif (lease.goalId === state.goalId) return state;\n\t\tif (lease.goalId !== undefined || !lease.adoptNewGoal) return undefined;\n\t\tif (lease.adoptionBaselineGoalId === state.goalId) return undefined;\n\t\tlease.goalId = state.goalId;\n\t\treturn state;\n\t}\n\n\tprivate flushPendingExecutionUsage(lease: MutableGoalExecutionLease): void {\n\t\tif (lease.pendingTokens === 0 && lease.pendingSpendUsd === 0) return;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state) return;\n\t\tthis.chargeExecutionUsage(lease, state, lease.pendingTokens, lease.pendingSpendUsd);\n\t}\n\n\tmarkToolUnavailable(): void {\n\t\tthis.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t\"goal_tool_unavailable: the active capability surface cannot update durable goal state\",\n\t\t);\n\t}\n\n\tmarkRunawayBlocked(info: { signature: string; repeats: number }): boolean {\n\t\treturn this.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t`runaway_tool_loop: repeated tool-call signature ${info.signature} ${info.repeats} times without progress`,\n\t\t);\n\t}\n\n\tmarkTerminalToolFailureBlocked(toolName: string): boolean {\n\t\treturn this.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t`terminal_tool_failure: ${toolName} reported an unrecoverable error and terminated the run`,\n\t\t);\n\t}\n\n\tgetRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot {\n\t\treturn buildGoalRuntimeSnapshot({\n\t\t\tsessionManager: this.deps.getSessionManager(),\n\t\t\tsettings,\n\t\t\tlaneRecords: this.deps.getLaneRecords(),\n\t\t\ttaskRuntime: this.deps.getTaskRuntimeSnapshot(),\n\t\t});\n\t}\n\n\tcontinueOnce(options: GoalContinuationOnceOptions): Promise<GoalContinuationOnceResult> {\n\t\treturn this.loop.continueGoalOnce(options);\n\t}\n\n\tcontinueLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\treturn this.loop.continueGoalLoop(options);\n\t}\n\n\trestoreAfterResume(): void {\n\t\tthis.deps.scheduleGoalAutoContinueFromIdle();\n\t}\n\n\tprivate recordContinuationFailure(error: unknown): void {\n\t\tconst state = this.getState();\n\t\tif (!state || state.status !== \"active\") return;\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconst classified = classifyFailure({ message, provider: this.deps.getModelProvider() });\n\t\tconst status = classified.reason === \"billing_or_quota\" ? \"usage_limited\" : \"blocked\";\n\t\tthis.stopActiveGoal(status, `${classified.reason}: ${message}`);\n\t}\n\n\tprivate markBudgetLimited(reason: string): void {\n\t\tthis.stopActiveGoal(\"budget_limited\", reason);\n\t}\n\n\tprivate stopActiveGoal(status: \"blocked\" | \"usage_limited\" | \"budget_limited\", reason: string): boolean {\n\t\tconst state = this.getState();\n\t\tconst stopped = stopGoalFromSystem(state, { status, reason }, new Date().toISOString());\n\t\tif (!stopped.ok || !state) return false;\n\t\tthis.saveState(stopped.state, getGoalStateRevision(state));\n\t\treturn true;\n\t}\n}\n"]}
@@ -16,9 +16,9 @@ export interface GoalState {
16
16
  revision?: number;
17
17
  /** Monotonic meaningful-progress revision used by the continuation stall gate. */
18
18
  progressRevision?: number;
19
- /** Optional owner-requested token ceiling. Charged usage is uncached input plus output. */
19
+ /** Optional owner-requested ceiling using the shared cache-discounted token-budget accounting. */
20
20
  tokenBudget?: number;
21
- /** Exact usage attributed to submitted goal-continuation turns. */
21
+ /** Budget-counted usage attributed to all goal-owned foreground execution. */
22
22
  tokensUsed?: number;
23
23
  requirements: readonly Requirement[];
24
24
  evidence: readonly GoalEvidenceRef[];
@@ -43,9 +43,8 @@ export interface GoalState {
43
43
  */
44
44
  continuationWallClockMs?: number;
45
45
  /**
46
- * Observed cumulative USD attributed to this goal's own continuation passes from assistant messages
47
- * appended within each pass's captured branch interval. Deliberately excludes worker/subagent spend,
48
- * which is reported separately. Same backward-compat note.
46
+ * Observed cumulative USD attributed to this goal's own foreground provider responses. Deliberately
47
+ * excludes worker/subagent spend, which is reported separately. Same backward-compat note.
49
48
  */
50
49
  continuationSpendUsd?: number;
51
50
  /**
@@ -160,9 +159,9 @@ export type GoalEvent = {
160
159
  turns: number;
161
160
  /** This pass's own active wall-clock duration, in milliseconds. */
162
161
  wallClockMs: number;
163
- /** Exact uncached input + output tokens produced after this pass's session-entry cursor. */
162
+ /** Budget-counted provider usage; cache reads use the shared lean-budget weight. */
164
163
  tokens: number;
165
- /** Exact model spend produced after this pass's session-entry cursor. */
164
+ /** Exact model spend attributed to the goal-owned execution. */
166
165
  spendUsd: number;
167
166
  now: string;
168
167
  } | {
@@ -1 +1 @@
1
- {"version":3,"file":"goal-state.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-state.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,UAAU,GACnB,QAAQ,GACR,QAAQ,GACR,SAAS,GACT,eAAe,GACf,gBAAgB,GAChB,WAAW,GACX,WAAW,CAAC;AACf,MAAM,MAAM,iBAAiB,GAAG,MAAM,GAAG,WAAW,GAAG,SAAS,CAAC;AACjE,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,SAAS,GAAG,QAAQ,CAAC;AAExF,eAAO,MAAM,yBAAyB,OAAQ,CAAC;AAC/C,eAAO,MAAM,sBAAsB,MAAM,CAAC;AAE1C,mFAAmF;AACnF,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAEjE;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAEjE;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAEhE;AAED,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAElE;AAED,MAAM,WAAW,SAAS;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,UAAU,CAAC;IACnB,oGAAoG;IACpG,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,kFAAkF;IAClF,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,2FAA2F;IAC3F,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,mEAAmE;IACnE,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,Y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