@caupulican/pi-adaptative 0.90.0 → 0.90.4

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 (172) hide show
  1. package/CHANGELOG.md +43 -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.map +1 -1
  6. package/dist/core/agent-session.js +5 -1
  7. package/dist/core/agent-session.js.map +1 -1
  8. package/dist/core/autonomy/bounded-completion.d.ts +10 -1
  9. package/dist/core/autonomy/bounded-completion.d.ts.map +1 -1
  10. package/dist/core/autonomy/bounded-completion.js +24 -2
  11. package/dist/core/autonomy/bounded-completion.js.map +1 -1
  12. package/dist/core/autonomy/lane-tracker.d.ts +1 -1
  13. package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
  14. package/dist/core/autonomy/lane-tracker.js +9 -1
  15. package/dist/core/autonomy/lane-tracker.js.map +1 -1
  16. package/dist/core/background-lane-controller.d.ts +1 -3
  17. package/dist/core/background-lane-controller.d.ts.map +1 -1
  18. package/dist/core/background-lane-controller.js.map +1 -1
  19. package/dist/core/compaction-controller.d.ts.map +1 -1
  20. package/dist/core/compaction-controller.js +0 -1
  21. package/dist/core/compaction-controller.js.map +1 -1
  22. package/dist/core/delegation/managed-lane-controller.d.ts.map +1 -1
  23. package/dist/core/delegation/managed-lane-controller.js +5 -1
  24. package/dist/core/delegation/managed-lane-controller.js.map +1 -1
  25. package/dist/core/delegation/worker-agent-control-coordinator.d.ts +8 -1
  26. package/dist/core/delegation/worker-agent-control-coordinator.d.ts.map +1 -1
  27. package/dist/core/delegation/worker-agent-control-coordinator.js +94 -36
  28. package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
  29. package/dist/core/delegation/worker-agent-control.d.ts +1 -0
  30. package/dist/core/delegation/worker-agent-control.d.ts.map +1 -1
  31. package/dist/core/delegation/worker-agent-control.js.map +1 -1
  32. package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -1
  33. package/dist/core/delegation/worker-attempt-executor.js +7 -2
  34. package/dist/core/delegation/worker-attempt-executor.js.map +1 -1
  35. package/dist/core/delegation/worker-authority-resolver.d.ts.map +1 -1
  36. package/dist/core/delegation/worker-authority-resolver.js +26 -3
  37. package/dist/core/delegation/worker-authority-resolver.js.map +1 -1
  38. package/dist/core/delegation/worker-delegation-controller.d.ts +7 -4
  39. package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
  40. package/dist/core/delegation/worker-delegation-controller.js +110 -27
  41. package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
  42. package/dist/core/delegation/worker-fleet-limits.d.ts +9 -2
  43. package/dist/core/delegation/worker-fleet-limits.d.ts.map +1 -1
  44. package/dist/core/delegation/worker-fleet-limits.js +39 -3
  45. package/dist/core/delegation/worker-fleet-limits.js.map +1 -1
  46. package/dist/core/delegation/worker-lane-projection.d.ts.map +1 -1
  47. package/dist/core/delegation/worker-lane-projection.js +4 -0
  48. package/dist/core/delegation/worker-lane-projection.js.map +1 -1
  49. package/dist/core/delegation/worker-lease-heartbeat.d.ts +16 -0
  50. package/dist/core/delegation/worker-lease-heartbeat.d.ts.map +1 -0
  51. package/dist/core/delegation/worker-lease-heartbeat.js +37 -0
  52. package/dist/core/delegation/worker-lease-heartbeat.js.map +1 -0
  53. package/dist/core/delegation/worker-lifecycle.d.ts +1 -0
  54. package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -1
  55. package/dist/core/delegation/worker-lifecycle.js +6 -0
  56. package/dist/core/delegation/worker-lifecycle.js.map +1 -1
  57. package/dist/core/delegation/worker-notification-coordinator.d.ts.map +1 -1
  58. package/dist/core/delegation/worker-notification-coordinator.js +2 -1
  59. package/dist/core/delegation/worker-notification-coordinator.js.map +1 -1
  60. package/dist/core/delegation/worker-runner.js +2 -2
  61. package/dist/core/delegation/worker-runner.js.map +1 -1
  62. package/dist/core/delegation/worker-terminal-handoff-coordinator.d.ts +1 -0
  63. package/dist/core/delegation/worker-terminal-handoff-coordinator.d.ts.map +1 -1
  64. package/dist/core/delegation/worker-terminal-handoff-coordinator.js +1 -0
  65. package/dist/core/delegation/worker-terminal-handoff-coordinator.js.map +1 -1
  66. package/dist/core/delegation/worker-tree-budget-coordinator.d.ts +4 -2
  67. package/dist/core/delegation/worker-tree-budget-coordinator.d.ts.map +1 -1
  68. package/dist/core/delegation/worker-tree-budget-coordinator.js +10 -2
  69. package/dist/core/delegation/worker-tree-budget-coordinator.js.map +1 -1
  70. package/dist/core/delegation/worker-write-reservation-coordinator.d.ts +14 -0
  71. package/dist/core/delegation/worker-write-reservation-coordinator.d.ts.map +1 -1
  72. package/dist/core/delegation/worker-write-reservation-coordinator.js +121 -33
  73. package/dist/core/delegation/worker-write-reservation-coordinator.js.map +1 -1
  74. package/dist/core/foreground-terminal-handoff-controller.d.ts +5 -0
  75. package/dist/core/foreground-terminal-handoff-controller.d.ts.map +1 -1
  76. package/dist/core/foreground-terminal-handoff-controller.js +28 -12
  77. package/dist/core/foreground-terminal-handoff-controller.js.map +1 -1
  78. package/dist/core/goals/goal-session-controller.d.ts +6 -0
  79. package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
  80. package/dist/core/goals/goal-session-controller.js +16 -13
  81. package/dist/core/goals/goal-session-controller.js.map +1 -1
  82. package/dist/core/orchestration/capability-gateway.d.ts +2 -1
  83. package/dist/core/orchestration/capability-gateway.d.ts.map +1 -1
  84. package/dist/core/orchestration/capability-gateway.js +9 -2
  85. package/dist/core/orchestration/capability-gateway.js.map +1 -1
  86. package/dist/core/orchestration/contracts.d.ts +16 -1
  87. package/dist/core/orchestration/contracts.d.ts.map +1 -1
  88. package/dist/core/orchestration/contracts.js +5 -0
  89. package/dist/core/orchestration/contracts.js.map +1 -1
  90. package/dist/core/orchestration/profile-registry.d.ts.map +1 -1
  91. package/dist/core/orchestration/profile-registry.js +38 -1
  92. package/dist/core/orchestration/profile-registry.js.map +1 -1
  93. package/dist/core/orchestration/risk-budget.d.ts +10 -0
  94. package/dist/core/orchestration/risk-budget.d.ts.map +1 -1
  95. package/dist/core/orchestration/risk-budget.js +14 -0
  96. package/dist/core/orchestration/risk-budget.js.map +1 -1
  97. package/dist/core/orchestration/task-runtime-reducer.d.ts +1 -0
  98. package/dist/core/orchestration/task-runtime-reducer.d.ts.map +1 -1
  99. package/dist/core/orchestration/task-runtime-reducer.js +34 -0
  100. package/dist/core/orchestration/task-runtime-reducer.js.map +1 -1
  101. package/dist/core/orchestration/task-runtime.d.ts +1 -0
  102. package/dist/core/orchestration/task-runtime.d.ts.map +1 -1
  103. package/dist/core/orchestration/task-runtime.js +24 -1
  104. package/dist/core/orchestration/task-runtime.js.map +1 -1
  105. package/dist/core/provider-prompt-contracts.d.ts.map +1 -1
  106. package/dist/core/provider-prompt-contracts.js +2 -1
  107. package/dist/core/provider-prompt-contracts.js.map +1 -1
  108. package/dist/core/reflection-controller.d.ts.map +1 -1
  109. package/dist/core/reflection-controller.js +8 -1
  110. package/dist/core/reflection-controller.js.map +1 -1
  111. package/dist/core/settings-manager.d.ts +2 -2
  112. package/dist/core/settings-manager.d.ts.map +1 -1
  113. package/dist/core/settings-manager.js +2 -2
  114. package/dist/core/settings-manager.js.map +1 -1
  115. package/dist/core/tools/bash.d.ts +3 -0
  116. package/dist/core/tools/bash.d.ts.map +1 -1
  117. package/dist/core/tools/bash.js +13 -2
  118. package/dist/core/tools/bash.js.map +1 -1
  119. package/dist/core/tools/delegate-status.d.ts +1 -0
  120. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  121. package/dist/core/tools/delegate-status.js +19 -1
  122. package/dist/core/tools/delegate-status.js.map +1 -1
  123. package/dist/core/tools/delegate.d.ts +9 -1
  124. package/dist/core/tools/delegate.d.ts.map +1 -1
  125. package/dist/core/tools/delegate.js +198 -64
  126. package/dist/core/tools/delegate.js.map +1 -1
  127. package/dist/core/tools/edit.d.ts.map +1 -1
  128. package/dist/core/tools/edit.js +14 -1
  129. package/dist/core/tools/edit.js.map +1 -1
  130. package/dist/core/tools/file-failure-recovery.d.ts +3 -0
  131. package/dist/core/tools/file-failure-recovery.d.ts.map +1 -1
  132. package/dist/core/tools/file-failure-recovery.js +11 -0
  133. package/dist/core/tools/file-failure-recovery.js.map +1 -1
  134. package/dist/core/tools/orchestration-panel.d.ts +1 -1
  135. package/dist/core/tools/orchestration-panel.d.ts.map +1 -1
  136. package/dist/core/tools/orchestration-panel.js +1 -0
  137. package/dist/core/tools/orchestration-panel.js.map +1 -1
  138. package/dist/core/tools/profile-writer.d.ts.map +1 -1
  139. package/dist/core/tools/profile-writer.js +2 -8
  140. package/dist/core/tools/profile-writer.js.map +1 -1
  141. package/dist/core/tools/search-command-guard.d.ts.map +1 -1
  142. package/dist/core/tools/search-command-guard.js +10 -3
  143. package/dist/core/tools/search-command-guard.js.map +1 -1
  144. package/dist/core/tools/tool-task.d.ts.map +1 -1
  145. package/dist/core/tools/tool-task.js +4 -0
  146. package/dist/core/tools/tool-task.js.map +1 -1
  147. package/dist/core/tools/write.d.ts.map +1 -1
  148. package/dist/core/tools/write.js +10 -1
  149. package/dist/core/tools/write.js.map +1 -1
  150. package/dist/modes/interactive/components/activity-lane.d.ts +1 -1
  151. package/dist/modes/interactive/components/activity-lane.d.ts.map +1 -1
  152. package/dist/modes/interactive/components/activity-lane.js +11 -2
  153. package/dist/modes/interactive/components/activity-lane.js.map +1 -1
  154. package/dist/modes/interactive/components/settings-selector.js +1 -1
  155. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  156. package/dist/utils/shell.d.ts +2 -0
  157. package/dist/utils/shell.d.ts.map +1 -1
  158. package/dist/utils/shell.js +3 -1
  159. package/dist/utils/shell.js.map +1 -1
  160. package/docs/harness-architecture.md +6 -3
  161. package/docs/settings.md +8 -6
  162. package/docs/tool-repair.md +1 -1
  163. package/docs/worker-profiles.md +2 -2
  164. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  165. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  166. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  167. package/examples/extensions/sandbox/package-lock.json +2 -2
  168. package/examples/extensions/sandbox/package.json +1 -1
  169. package/examples/extensions/with-deps/package-lock.json +2 -2
  170. package/examples/extensions/with-deps/package.json +1 -1
  171. package/npm-shrinkwrap.json +12 -12
  172. package/package.json +4 -4
@@ -1,5 +1,5 @@
1
1
  import { isLocalProcessAlive, localWorkerProcessOwnerLiveness } from "./worker-process-owner.js";
2
- import { WorkerWriteReservationStore } from "./worker-write-reservation.js";
2
+ import { WorkerWriteReservationStore, } from "./worker-write-reservation.js";
3
3
  /**
4
4
  * Owns one controller process's write-reservation lifecycle: admission, exact-fence release,
5
5
  * event-driven queue wakeup, and fail-closed recovery of positively dead owners.
@@ -7,54 +7,92 @@ import { WorkerWriteReservationStore } from "./worker-write-reservation.js";
7
7
  export class WorkerWriteReservationCoordinator {
8
8
  constructor(options) {
9
9
  this.leases = new Map();
10
+ this.blockedByLocalLaneIds = new Map();
10
11
  this.options = options;
11
12
  this.store = new WorkerWriteReservationStore({ agentDir: options.agentDir });
12
13
  }
13
14
  acquire(laneId, attempt, plan) {
14
- if (!plan.writeEnabled || plan.writePaths.length === 0)
15
+ if (!plan.writeEnabled || plan.writePaths.length === 0) {
16
+ this.blockedByLocalLaneIds.delete(laneId);
15
17
  return { kind: "granted" };
18
+ }
16
19
  const fencingToken = (attempt.lease?.fencingToken ?? 0) + 1;
17
20
  const current = this.leases.get(laneId);
18
21
  if (current && current.attemptId === attempt.attemptId && current.fencingToken === fencingToken) {
22
+ this.blockedByLocalLaneIds.delete(laneId);
19
23
  return { kind: "granted" };
20
24
  }
21
- try {
22
- const result = this.store.acquire({
23
- parentSessionId: this.options.getParentSessionId(),
24
- ownerId: this.options.ownerId,
25
- taskId: laneId,
26
- attemptId: attempt.attemptId,
27
- fencingToken,
28
- access: "write",
29
- workspace: this.workspace(),
30
- writeScopes: plan.writePaths,
31
- });
32
- if (result.kind !== "granted" || !result.lease) {
33
- this.ensureWatch();
34
- return { kind: "blocked" };
35
- }
36
- this.leases.set(laneId, result.lease);
37
- return { kind: "granted" };
38
- }
39
- catch (error) {
40
- const message = error instanceof Error ? error.message : String(error);
41
- this.options.warn(`Worker write reservation denied: ${message}`);
42
- return {
43
- kind: "denied",
44
- reasonCode: message.includes("within the execution root")
45
- ? "write_reservation_scope_invalid"
46
- : "write_reservation_unavailable",
47
- };
48
- }
25
+ return this.acquireLease(laneId, {
26
+ parentSessionId: this.options.getParentSessionId(),
27
+ ownerId: this.options.ownerId,
28
+ taskId: laneId,
29
+ attemptId: attempt.attemptId,
30
+ fencingToken,
31
+ access: "write",
32
+ workspace: this.workspace(),
33
+ writeScopes: plan.writePaths,
34
+ }, "Worker write reservation denied", true);
49
35
  }
50
36
  hasFenceMismatch(laneId, attemptId, fencingToken) {
51
37
  const lease = this.leases.get(laneId);
52
38
  return lease !== undefined && (lease.attemptId !== attemptId || lease.fencingToken !== fencingToken);
53
39
  }
54
- release(laneId, expectedAttemptId, expectedFencingToken) {
40
+ isBlockedBy(targetLaneId, blockerLaneId) {
41
+ return this.blockedByLocalLaneIds.get(targetLaneId)?.has(blockerLaneId) === true;
42
+ }
43
+ /** Release one exact live caller lane while its model turn is blocked inside a worker wait. */
44
+ yieldForWait(laneId, expectedAttemptId, expectedFencingToken) {
55
45
  const held = this.leases.get(laneId);
56
46
  if (!held)
47
+ return undefined;
48
+ if (held.attemptId !== expectedAttemptId || held.fencingToken !== expectedFencingToken) {
49
+ throw new Error("Worker wait cannot yield a write reservation owned by another attempt fence.");
50
+ }
51
+ const released = this.store.release(held);
52
+ if (released.kind === "stale_fence") {
53
+ throw new Error("Worker wait write reservation yield encountered a stale attempt fence.");
54
+ }
55
+ this.forgetLease(laneId, held);
56
+ return {
57
+ laneId,
58
+ lease: { ...held, writeScopes: [...held.writeScopes] },
59
+ };
60
+ }
61
+ /** Reacquire the exact yielded attempt fence before its model turn may resume. */
62
+ restoreAfterWait(yielded) {
63
+ const { laneId, lease } = yielded;
64
+ if (lease.taskId !== laneId ||
65
+ lease.parentSessionId !== this.options.getParentSessionId() ||
66
+ lease.ownerId !== this.options.ownerId) {
67
+ return { kind: "denied", reasonCode: "write_reservation_unavailable" };
68
+ }
69
+ const current = this.leases.get(laneId);
70
+ if (current) {
71
+ return current.attemptId === lease.attemptId && current.fencingToken === lease.fencingToken
72
+ ? { kind: "granted" }
73
+ : { kind: "denied", reasonCode: "write_reservation_unavailable" };
74
+ }
75
+ return this.acquireLease(laneId, {
76
+ parentSessionId: lease.parentSessionId,
77
+ ownerId: lease.ownerId,
78
+ taskId: lease.taskId,
79
+ attemptId: lease.attemptId,
80
+ fencingToken: lease.fencingToken,
81
+ access: "write",
82
+ workspace: {
83
+ repositoryRoot: lease.repositoryRoot,
84
+ executionRoot: lease.executionRoot,
85
+ ...(lease.isolatedWorktreeId ? { isolatedWorktreeId: lease.isolatedWorktreeId } : {}),
86
+ },
87
+ writeScopes: lease.writeScopes,
88
+ }, "Worker write reservation restore denied", false);
89
+ }
90
+ release(laneId, expectedAttemptId, expectedFencingToken) {
91
+ const held = this.leases.get(laneId);
92
+ if (!held) {
93
+ this.blockedByLocalLaneIds.delete(laneId);
57
94
  return;
95
+ }
58
96
  if (expectedAttemptId !== undefined && held.attemptId !== expectedAttemptId)
59
97
  return;
60
98
  if (expectedFencingToken !== undefined && held.fencingToken !== expectedFencingToken)
@@ -66,8 +104,7 @@ export class WorkerWriteReservationCoordinator {
66
104
  this.options.warn(`Failed to release worker write reservation ${laneId}: ${error instanceof Error ? error.message : String(error)}`);
67
105
  }
68
106
  finally {
69
- if (this.leases.get(laneId) === held)
70
- this.leases.delete(laneId);
107
+ this.forgetLease(laneId, held);
71
108
  }
72
109
  }
73
110
  recoverProvenStale() {
@@ -90,11 +127,62 @@ export class WorkerWriteReservationCoordinator {
90
127
  dispose() {
91
128
  this.watchDispose?.();
92
129
  this.watchDispose = undefined;
130
+ this.blockedByLocalLaneIds.clear();
93
131
  }
94
132
  workspace() {
95
133
  const cwd = this.options.getCwd();
96
134
  return { repositoryRoot: cwd, executionRoot: cwd };
97
135
  }
136
+ acquireLease(laneId, request, warningPrefix, classifyScopeFailure) {
137
+ try {
138
+ const result = this.store.acquire(request);
139
+ if (result.kind === "blocked") {
140
+ this.recordLocalBlockers(laneId, result.conflictingReservationIds);
141
+ this.ensureWatch();
142
+ return { kind: "blocked" };
143
+ }
144
+ if (!result.lease) {
145
+ this.blockedByLocalLaneIds.delete(laneId);
146
+ this.ensureWatch();
147
+ return { kind: "blocked" };
148
+ }
149
+ this.blockedByLocalLaneIds.delete(laneId);
150
+ this.leases.set(laneId, result.lease);
151
+ return { kind: "granted" };
152
+ }
153
+ catch (error) {
154
+ this.blockedByLocalLaneIds.delete(laneId);
155
+ const message = error instanceof Error ? error.message : String(error);
156
+ this.options.warn(`${warningPrefix}: ${message}`);
157
+ return {
158
+ kind: "denied",
159
+ reasonCode: classifyScopeFailure && message.includes("within the execution root")
160
+ ? "write_reservation_scope_invalid"
161
+ : "write_reservation_unavailable",
162
+ };
163
+ }
164
+ }
165
+ recordLocalBlockers(laneId, conflictingReservationIds) {
166
+ const conflictingIds = new Set(conflictingReservationIds ?? []);
167
+ const localBlockers = new Set([...this.leases]
168
+ .filter(([, lease]) => conflictingIds.has(lease.reservationId))
169
+ .map(([blockedLaneId]) => blockedLaneId));
170
+ if (localBlockers.size > 0)
171
+ this.blockedByLocalLaneIds.set(laneId, localBlockers);
172
+ else
173
+ this.blockedByLocalLaneIds.delete(laneId);
174
+ }
175
+ forgetLease(laneId, held) {
176
+ if (this.leases.get(laneId) !== held)
177
+ return;
178
+ this.leases.delete(laneId);
179
+ this.blockedByLocalLaneIds.delete(laneId);
180
+ for (const [targetLaneId, blockerLaneIds] of this.blockedByLocalLaneIds) {
181
+ blockerLaneIds.delete(laneId);
182
+ if (blockerLaneIds.size === 0)
183
+ this.blockedByLocalLaneIds.delete(targetLaneId);
184
+ }
185
+ }
98
186
  ensureWatch() {
99
187
  if (this.watchDispose)
100
188
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"worker-write-reservation-coordinator.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-write-reservation-coordinator.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mBAAmB,EAAE,+BAA+B,EAAE,MAAM,2BAA2B,CAAC;AACjG,OAAO,EAAoC,2BAA2B,EAAE,MAAM,+BAA+B,CAAC;AAiB9G;;;GAGG;AACH,MAAM,OAAO,iCAAiC;IAM7C,YAAY,OAAiD;QAH5C,WAAM,GAAG,IAAI,GAAG,EAAuC,CAAC;QAIxE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,KAAK,GAAG,IAAI,2BAA2B,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;IAC9E,CAAC;IAED,OAAO,CACN,MAAc,EACd,OAAyD,EACzD,IAA8D;QAE9D,IAAI,CAAC,IAAI,CAAC,YAAY,IAAI,IAAI,CAAC,UAAU,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;QACnF,MAAM,YAAY,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,YAAY,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;QAC5D,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACxC,IAAI,OAAO,IAAI,OAAO,CAAC,SAAS,KAAK,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,YAAY,KAAK,YAAY,EAAE,CAAC;YACjG,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;QAC5B,CAAC;QACD,IAAI,CAAC;YACJ,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC;gBACjC,eAAe,EAAE,IAAI,CAAC,OAAO,CAAC,kBAAkB,EAA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Plan } from \"./worker-execution-policy.ts\";\nimport { isLocalProcessAlive, localWorkerProcessOwnerLiveness } from \"./worker-process-owner.ts\";\nimport { type WorkerWriteReservationLease, WorkerWriteReservationStore } from \"./worker-write-reservation.ts\";\n\nexport type WorkerWriteReservationAdmission =\n\t| { kind: \"granted\" }\n\t| { kind: \"blocked\" }\n\t| { kind: \"denied\"; reasonCode: \"write_reservation_scope_invalid\" | \"write_reservation_unavailable\" };\n\nexport interface WorkerWriteReservationCoordinatorOptions {\n\tagentDir: string;\n\tgetCwd(): string;\n\tgetParentSessionId(): string;\n\townerId: string;\n\tdrainQueuedWorkers(): void;\n\twarn(message: string): void;\n\tisProcessAlive?(pid: number): boolean;\n}\n\n/**\n * Owns one controller process's write-reservation lifecycle: admission, exact-fence release,\n * event-driven queue wakeup, and fail-closed recovery of positively dead owners.\n */\nexport class WorkerWriteReservationCoordinator {\n\tprivate readonly options: WorkerWriteReservationCoordinatorOptions;\n\tprivate readonly store: WorkerWriteReservationStore;\n\tprivate readonly leases = new Map<string, WorkerWriteReservationLease>();\n\tprivate watchDispose: (() => void) | undefined;\n\n\tconstructor(options: WorkerWriteReservationCoordinatorOptions) {\n\t\tthis.options = options;\n\t\tthis.store = new WorkerWriteReservationStore({ agentDir: options.agentDir });\n\t}\n\n\tacquire(\n\t\tlaneId: string,\n\t\tattempt: Pick<AttemptRuntimeState, \"attemptId\" | \"lease\">,\n\t\tplan: Pick<WorkerExecutionPlan, \"writeEnabled\" | \"writePaths\">,\n\t): WorkerWriteReservationAdmission {\n\t\tif (!plan.writeEnabled || plan.writePaths.length === 0) return { kind: \"granted\" };\n\t\tconst fencingToken = (attempt.lease?.fencingToken ?? 0) + 1;\n\t\tconst current = this.leases.get(laneId);\n\t\tif (current && current.attemptId === attempt.attemptId && current.fencingToken === fencingToken) {\n\t\t\treturn { kind: \"granted\" };\n\t\t}\n\t\ttry {\n\t\t\tconst result = this.store.acquire({\n\t\t\t\tparentSessionId: this.options.getParentSessionId(),\n\t\t\t\townerId: this.options.ownerId,\n\t\t\t\ttaskId: laneId,\n\t\t\t\tattemptId: attempt.attemptId,\n\t\t\t\tfencingToken,\n\t\t\t\taccess: \"write\",\n\t\t\t\tworkspace: this.workspace(),\n\t\t\t\twriteScopes: plan.writePaths,\n\t\t\t});\n\t\t\tif (result.kind !== \"granted\" || !result.lease) {\n\t\t\t\tthis.ensureWatch();\n\t\t\t\treturn { kind: \"blocked\" };\n\t\t\t}\n\t\t\tthis.leases.set(laneId, result.lease);\n\t\t\treturn { kind: \"granted\" };\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.options.warn(`Worker write reservation denied: ${message}`);\n\t\t\treturn {\n\t\t\t\tkind: \"denied\",\n\t\t\t\treasonCode: message.includes(\"within the execution root\")\n\t\t\t\t\t? \"write_reservation_scope_invalid\"\n\t\t\t\t\t: \"write_reservation_unavailable\",\n\t\t\t};\n\t\t}\n\t}\n\n\thasFenceMismatch(laneId: string, attemptId: string, fencingToken: number): boolean {\n\t\tconst lease = this.leases.get(laneId);\n\t\treturn lease !== undefined && (lease.attemptId !== attemptId || lease.fencingToken !== fencingToken);\n\t}\n\n\trelease(laneId: string, expectedAttemptId?: string, expectedFencingToken?: number): void {\n\t\tconst held = this.leases.get(laneId);\n\t\tif (!held) return;\n\t\tif (expectedAttemptId !== undefined && held.attemptId !== expectedAttemptId) return;\n\t\tif (expectedFencingToken !== undefined && held.fencingToken !== expectedFencingToken) return;\n\t\ttry {\n\t\t\tthis.store.release(held);\n\t\t} catch (error) {\n\t\t\tthis.options.warn(\n\t\t\t\t`Failed to release worker write reservation ${laneId}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t} finally {\n\t\t\tif (this.leases.get(laneId) === held) this.leases.delete(laneId);\n\t\t}\n\t}\n\n\trecoverProvenStale(): void {\n\t\tconst discovered = this.store.recover({ workspace: this.workspace(), evidence: [] });\n\t\tconst evidence = discovered.outcomes.map((outcome) => ({\n\t\t\treservationId: outcome.reservationId,\n\t\t\tstate:\n\t\t\t\tlocalWorkerProcessOwnerLiveness(\n\t\t\t\t\toutcome.lease.ownerId,\n\t\t\t\t\tthis.options.isProcessAlive ?? isLocalProcessAlive,\n\t\t\t\t) === \"dead\"\n\t\t\t\t\t? (\"not_live\" as const)\n\t\t\t\t\t: (\"unknown\" as const),\n\t\t}));\n\t\tfor (const outcome of this.store.recover({ workspace: this.workspace(), evidence }).outcomes) {\n\t\t\tif (outcome.kind !== \"stale\") continue;\n\t\t\tconst released = this.store.release(outcome.lease);\n\t\t\tif (released.kind !== \"released\" && released.kind !== \"not_found\") {\n\t\t\t\tthis.options.warn(\n\t\t\t\t\t`Stale worker write reservation ${outcome.reservationId} was not released (${released.kind}).`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tthis.watchDispose?.();\n\t\tthis.watchDispose = undefined;\n\t}\n\n\tprivate workspace() {\n\t\tconst cwd = this.options.getCwd();\n\t\treturn { repositoryRoot: cwd, executionRoot: cwd };\n\t}\n\n\tprivate ensureWatch(): void {\n\t\tif (this.watchDispose) return;\n\t\tthis.watchDispose = this.store.watchAvailability(this.workspace(), () => this.options.drainQueuedWorkers());\n\t}\n}\n"]}
1
+ {"version":3,"file":"worker-write-reservation-coordinator.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-write-reservation-coordinator.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mBAAmB,EAAE,+BAA+B,EAAE,MAAM,2BAA2B,CAAC;AACjG,OAAO,EAGN,2BAA2B,GAC3B,MAAM,+BAA+B,CAAC;AAsBvC;;;GAGG;AACH,MAAM,OAAO,iCAAiC;IAO7C,YAAY,OAAiD;QAJ5C,WAAM,GAAG,IAAI,GAAG,EAAuC,CAAC;QACxD,0BAAqB,GAAG,IAAI,GAAG,EAAuB,CAAC;QAIvE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,KAAK,GAAG,IAAI,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AAC,GAAG,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;aAC9D,GAAG,CAAC,CAAC,CAAC,aAAa,CAAC,EAAE,EAAE,CAAC,aAAa,CAAC,CACzC,CAAC;QACF,IAAI,aAAa,CAAC,IAAI,GAAG,CAAC;YAAE,IAAI,CAAC,qBAAqB,CAAC,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;;YAC7E,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAChD,CAAC;IAEO,WAAW,CAAC,MAAc,EAAE,IAAiC;QACpE,IAAI,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,IAAI;YAAE,OAAO;QAC7C,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC3B,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC1C,KAAK,MAAM,CAAC,YAAY,EAAE,cAAc,CAAC,IAAI,IAAI,CAAC,qBAAqB,EAAE,CAAC;YACzE,cAAc,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YAC9B,IAAI,cAAc,CAAC,IAAI,KAAK,CAAC;gBAAE,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;QAChF,CAAC;IACF,CAAC;IAEO,WAAW;QAClB,IAAI,IAAI,CAAC,YAAY;YAAE,OAAO;QAC9B,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC,IAAI,CAAC,SAAS,EAAE,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,kBAAkB,EAAE,CAAC,CAAC;IAC7G,CAAC;CACD","sourcesContent":["import type { AttemptRuntimeState } from \"../orchestration/task-runtime.ts\";\nimport type { WorkerExecutionPlan } from \"./worker-execution-policy.ts\";\nimport { isLocalProcessAlive, localWorkerProcessOwnerLiveness } from \"./worker-process-owner.ts\";\nimport {\n\ttype WorkerWriteReservationLease,\n\ttype WorkerWriteReservationRequest,\n\tWorkerWriteReservationStore,\n} from \"./worker-write-reservation.ts\";\n\nexport type WorkerWriteReservationAdmission =\n\t| { kind: \"granted\" }\n\t| { kind: \"blocked\" }\n\t| { kind: \"denied\"; reasonCode: \"write_reservation_scope_invalid\" | \"write_reservation_unavailable\" };\n\nexport interface WorkerWriteReservationWaitYield {\n\tlaneId: string;\n\tlease: WorkerWriteReservationLease;\n}\n\nexport interface WorkerWriteReservationCoordinatorOptions {\n\tagentDir: string;\n\tgetCwd(): string;\n\tgetParentSessionId(): string;\n\townerId: string;\n\tdrainQueuedWorkers(): void;\n\twarn(message: string): void;\n\tisProcessAlive?(pid: number): boolean;\n}\n\n/**\n * Owns one controller process's write-reservation lifecycle: admission, exact-fence release,\n * event-driven queue wakeup, and fail-closed recovery of positively dead owners.\n */\nexport class WorkerWriteReservationCoordinator {\n\tprivate readonly options: WorkerWriteReservationCoordinatorOptions;\n\tprivate readonly store: WorkerWriteReservationStore;\n\tprivate readonly leases = new Map<string, WorkerWriteReservationLease>();\n\tprivate readonly blockedByLocalLaneIds = new Map<string, Set<string>>();\n\tprivate watchDispose: (() => void) | undefined;\n\n\tconstructor(options: WorkerWriteReservationCoordinatorOptions) {\n\t\tthis.options = options;\n\t\tthis.store = new WorkerWriteReservationStore({ agentDir: options.agentDir });\n\t}\n\n\tacquire(\n\t\tlaneId: string,\n\t\tattempt: Pick<AttemptRuntimeState, \"attemptId\" | \"lease\">,\n\t\tplan: Pick<WorkerExecutionPlan, \"writeEnabled\" | \"writePaths\">,\n\t): WorkerWriteReservationAdmission {\n\t\tif (!plan.writeEnabled || plan.writePaths.length === 0) {\n\t\t\tthis.blockedByLocalLaneIds.delete(laneId);\n\t\t\treturn { kind: \"granted\" };\n\t\t}\n\t\tconst fencingToken = (attempt.lease?.fencingToken ?? 0) + 1;\n\t\tconst current = this.leases.get(laneId);\n\t\tif (current && current.attemptId === attempt.attemptId && current.fencingToken === fencingToken) {\n\t\t\tthis.blockedByLocalLaneIds.delete(laneId);\n\t\t\treturn { kind: \"granted\" };\n\t\t}\n\t\treturn this.acquireLease(\n\t\t\tlaneId,\n\t\t\t{\n\t\t\t\tparentSessionId: this.options.getParentSessionId(),\n\t\t\t\townerId: this.options.ownerId,\n\t\t\t\ttaskId: laneId,\n\t\t\t\tattemptId: attempt.attemptId,\n\t\t\t\tfencingToken,\n\t\t\t\taccess: \"write\",\n\t\t\t\tworkspace: this.workspace(),\n\t\t\t\twriteScopes: plan.writePaths,\n\t\t\t},\n\t\t\t\"Worker write reservation denied\",\n\t\t\ttrue,\n\t\t);\n\t}\n\n\thasFenceMismatch(laneId: string, attemptId: string, fencingToken: number): boolean {\n\t\tconst lease = this.leases.get(laneId);\n\t\treturn lease !== undefined && (lease.attemptId !== attemptId || lease.fencingToken !== fencingToken);\n\t}\n\n\tisBlockedBy(targetLaneId: string, blockerLaneId: string): boolean {\n\t\treturn this.blockedByLocalLaneIds.get(targetLaneId)?.has(blockerLaneId) === true;\n\t}\n\n\t/** Release one exact live caller lane while its model turn is blocked inside a worker wait. */\n\tyieldForWait(\n\t\tlaneId: string,\n\t\texpectedAttemptId: string,\n\t\texpectedFencingToken: number,\n\t): WorkerWriteReservationWaitYield | undefined {\n\t\tconst held = this.leases.get(laneId);\n\t\tif (!held) return undefined;\n\t\tif (held.attemptId !== expectedAttemptId || held.fencingToken !== expectedFencingToken) {\n\t\t\tthrow new Error(\"Worker wait cannot yield a write reservation owned by another attempt fence.\");\n\t\t}\n\t\tconst released = this.store.release(held);\n\t\tif (released.kind === \"stale_fence\") {\n\t\t\tthrow new Error(\"Worker wait write reservation yield encountered a stale attempt fence.\");\n\t\t}\n\t\tthis.forgetLease(laneId, held);\n\t\treturn {\n\t\t\tlaneId,\n\t\t\tlease: { ...held, writeScopes: [...held.writeScopes] },\n\t\t};\n\t}\n\n\t/** Reacquire the exact yielded attempt fence before its model turn may resume. */\n\trestoreAfterWait(yielded: WorkerWriteReservationWaitYield): WorkerWriteReservationAdmission {\n\t\tconst { laneId, lease } = yielded;\n\t\tif (\n\t\t\tlease.taskId !== laneId ||\n\t\t\tlease.parentSessionId !== this.options.getParentSessionId() ||\n\t\t\tlease.ownerId !== this.options.ownerId\n\t\t) {\n\t\t\treturn { kind: \"denied\", reasonCode: \"write_reservation_unavailable\" };\n\t\t}\n\t\tconst current = this.leases.get(laneId);\n\t\tif (current) {\n\t\t\treturn current.attemptId === lease.attemptId && current.fencingToken === lease.fencingToken\n\t\t\t\t? { kind: \"granted\" }\n\t\t\t\t: { kind: \"denied\", reasonCode: \"write_reservation_unavailable\" };\n\t\t}\n\t\treturn this.acquireLease(\n\t\t\tlaneId,\n\t\t\t{\n\t\t\t\tparentSessionId: lease.parentSessionId,\n\t\t\t\townerId: lease.ownerId,\n\t\t\t\ttaskId: lease.taskId,\n\t\t\t\tattemptId: lease.attemptId,\n\t\t\t\tfencingToken: lease.fencingToken,\n\t\t\t\taccess: \"write\",\n\t\t\t\tworkspace: {\n\t\t\t\t\trepositoryRoot: lease.repositoryRoot,\n\t\t\t\t\texecutionRoot: lease.executionRoot,\n\t\t\t\t\t...(lease.isolatedWorktreeId ? { isolatedWorktreeId: lease.isolatedWorktreeId } : {}),\n\t\t\t\t},\n\t\t\t\twriteScopes: lease.writeScopes,\n\t\t\t},\n\t\t\t\"Worker write reservation restore denied\",\n\t\t\tfalse,\n\t\t);\n\t}\n\n\trelease(laneId: string, expectedAttemptId?: string, expectedFencingToken?: number): void {\n\t\tconst held = this.leases.get(laneId);\n\t\tif (!held) {\n\t\t\tthis.blockedByLocalLaneIds.delete(laneId);\n\t\t\treturn;\n\t\t}\n\t\tif (expectedAttemptId !== undefined && held.attemptId !== expectedAttemptId) return;\n\t\tif (expectedFencingToken !== undefined && held.fencingToken !== expectedFencingToken) return;\n\t\ttry {\n\t\t\tthis.store.release(held);\n\t\t} catch (error) {\n\t\t\tthis.options.warn(\n\t\t\t\t`Failed to release worker write reservation ${laneId}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t} finally {\n\t\t\tthis.forgetLease(laneId, held);\n\t\t}\n\t}\n\n\trecoverProvenStale(): void {\n\t\tconst discovered = this.store.recover({ workspace: this.workspace(), evidence: [] });\n\t\tconst evidence = discovered.outcomes.map((outcome) => ({\n\t\t\treservationId: outcome.reservationId,\n\t\t\tstate:\n\t\t\t\tlocalWorkerProcessOwnerLiveness(\n\t\t\t\t\toutcome.lease.ownerId,\n\t\t\t\t\tthis.options.isProcessAlive ?? isLocalProcessAlive,\n\t\t\t\t) === \"dead\"\n\t\t\t\t\t? (\"not_live\" as const)\n\t\t\t\t\t: (\"unknown\" as const),\n\t\t}));\n\t\tfor (const outcome of this.store.recover({ workspace: this.workspace(), evidence }).outcomes) {\n\t\t\tif (outcome.kind !== \"stale\") continue;\n\t\t\tconst released = this.store.release(outcome.lease);\n\t\t\tif (released.kind !== \"released\" && released.kind !== \"not_found\") {\n\t\t\t\tthis.options.warn(\n\t\t\t\t\t`Stale worker write reservation ${outcome.reservationId} was not released (${released.kind}).`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tthis.watchDispose?.();\n\t\tthis.watchDispose = undefined;\n\t\tthis.blockedByLocalLaneIds.clear();\n\t}\n\n\tprivate workspace() {\n\t\tconst cwd = this.options.getCwd();\n\t\treturn { repositoryRoot: cwd, executionRoot: cwd };\n\t}\n\n\tprivate acquireLease(\n\t\tlaneId: string,\n\t\trequest: WorkerWriteReservationRequest,\n\t\twarningPrefix: string,\n\t\tclassifyScopeFailure: boolean,\n\t): WorkerWriteReservationAdmission {\n\t\ttry {\n\t\t\tconst result = this.store.acquire(request);\n\t\t\tif (result.kind === \"blocked\") {\n\t\t\t\tthis.recordLocalBlockers(laneId, result.conflictingReservationIds);\n\t\t\t\tthis.ensureWatch();\n\t\t\t\treturn { kind: \"blocked\" };\n\t\t\t}\n\t\t\tif (!result.lease) {\n\t\t\t\tthis.blockedByLocalLaneIds.delete(laneId);\n\t\t\t\tthis.ensureWatch();\n\t\t\t\treturn { kind: \"blocked\" };\n\t\t\t}\n\t\t\tthis.blockedByLocalLaneIds.delete(laneId);\n\t\t\tthis.leases.set(laneId, result.lease);\n\t\t\treturn { kind: \"granted\" };\n\t\t} catch (error) {\n\t\t\tthis.blockedByLocalLaneIds.delete(laneId);\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.options.warn(`${warningPrefix}: ${message}`);\n\t\t\treturn {\n\t\t\t\tkind: \"denied\",\n\t\t\t\treasonCode:\n\t\t\t\t\tclassifyScopeFailure && message.includes(\"within the execution root\")\n\t\t\t\t\t\t? \"write_reservation_scope_invalid\"\n\t\t\t\t\t\t: \"write_reservation_unavailable\",\n\t\t\t};\n\t\t}\n\t}\n\n\tprivate recordLocalBlockers(laneId: string, conflictingReservationIds: readonly string[] | undefined): void {\n\t\tconst conflictingIds = new Set(conflictingReservationIds ?? []);\n\t\tconst localBlockers = new Set(\n\t\t\t[...this.leases]\n\t\t\t\t.filter(([, lease]) => conflictingIds.has(lease.reservationId))\n\t\t\t\t.map(([blockedLaneId]) => blockedLaneId),\n\t\t);\n\t\tif (localBlockers.size > 0) this.blockedByLocalLaneIds.set(laneId, localBlockers);\n\t\telse this.blockedByLocalLaneIds.delete(laneId);\n\t}\n\n\tprivate forgetLease(laneId: string, held: WorkerWriteReservationLease): void {\n\t\tif (this.leases.get(laneId) !== held) return;\n\t\tthis.leases.delete(laneId);\n\t\tthis.blockedByLocalLaneIds.delete(laneId);\n\t\tfor (const [targetLaneId, blockerLaneIds] of this.blockedByLocalLaneIds) {\n\t\t\tblockerLaneIds.delete(laneId);\n\t\t\tif (blockerLaneIds.size === 0) this.blockedByLocalLaneIds.delete(targetLaneId);\n\t\t}\n\t}\n\n\tprivate ensureWatch(): void {\n\t\tif (this.watchDispose) return;\n\t\tthis.watchDispose = this.store.watchAvailability(this.workspace(), () => this.options.drainQueuedWorkers());\n\t}\n}\n"]}
@@ -11,6 +11,11 @@ interface ForegroundTerminalHandoffControllerDeps {
11
11
  deliverAs: "followUp";
12
12
  }, lease: ForegroundSubmissionLease): Promise<void>;
13
13
  }
14
+ export declare function buildForegroundWorkerTerminalHandoffContent(records: readonly {
15
+ laneId: string;
16
+ status: LaneTerminalStatus;
17
+ reasonCode?: string;
18
+ }[]): string;
14
19
  /** Serializes durable background terminal delivery through the foreground submission owner. */
15
20
  export declare class ForegroundTerminalHandoffController {
16
21
  private readonly deps;
@@ -1 +1 @@
1
- {"version":3,"file":"foreground-terminal-handoff-controller.d.ts","sourceRoot":"","sources":["../../src/core/foreground-terminal-handoff-controller.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AACrE,OAAO,EACN,KAAK,wBAAwB,EAE7B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,KAAK,EAAE,4BAA4B,EAAE,yBAAyB,EAAE,MAAM,qCAAqC,CAAC;AAEnH,UAAU,uCAAuC;IAChD,UAAU,EAAE,4BAA4B,CAAC;IACzC,UAAU,IAAI,OAAO,CAAC;IACtB,0BAA0B,CAAC,gBAAgB,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC;IACzE,iBAAiB,CAChB,OAAO,EAAE,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,EAAE,YAAY,GAAG,SAAS,GAAG,SAAS,GAAG,SAAS,CAAC,EACvF,OAAO,EAAE;QAAE,WAAW,EAAE,OAAO,CAAC;QAAC,SAAS,EAAE,UAAU,CAAA;KAAE,EACxD,KAAK,EAAE,yBAAyB,GAC9B,OAAO,CAAC,IAAI,CAAC,CAAC;CACjB;AAED,+FAA+F;AAC/F,qBAAa,mCAAmC;IAC/C,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA0C;IAE/D,YAAY,IAAI,EAAE,uCAAuC,EAExD;IAEK,aAAa,CAClB,OAAO,EAAE,SAAS;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,kBAAkB,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,EAAE,GACrF,OAAO,CAAC,IAAI,CAAC,CAkCf;IAEK,WAAW,CAAC,OAAO,EAAE,SAAS,wBAAwB,EAAE,EAAE,UAAU,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAclG;IAED,OAAO,CAAC,UAAU;CAGlB"}
1
+ {"version":3,"file":"foreground-terminal-handoff-controller.d.ts","sourceRoot":"","sources":["../../src/core/foreground-terminal-handoff-controller.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AACrE,OAAO,EACN,KAAK,wBAAwB,EAE7B,MAAM,sCAAsC,CAAC;AAE9C,OAAO,KAAK,EAAE,4BAA4B,EAAE,yBAAyB,EAAE,MAAM,qCAAqC,CAAC;AAEnH,UAAU,uCAAuC;IAChD,UAAU,EAAE,4BAA4B,CAAC;IACzC,UAAU,IAAI,OAAO,CAAC;IACtB,0BAA0B,CAAC,gBAAgB,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC;IACzE,iBAAiB,CAChB,OAAO,EAAE,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,EAAE,YAAY,GAAG,SAAS,GAAG,SAAS,GAAG,SAAS,CAAC,EACvF,OAAO,EAAE;QAAE,WAAW,EAAE,OAAO,CAAC;QAAC,SAAS,EAAE,UAAU,CAAA;KAAE,EACxD,KAAK,EAAE,yBAAyB,GAC9B,OAAO,CAAC,IAAI,CAAC,CAAC;CACjB;AAED,wBAAgB,2CAA2C,CAC1D,OAAO,EAAE,SAAS;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,kBAAkB,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAA;CAAE,EAAE,GACrF,MAAM,CAyBR;AAED,+FAA+F;AAC/F,qBAAa,mCAAmC;IAC/C,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA0C;IAE/D,YAAY,IAAI,EAAE,uCAAuC,EAExD;IAEK,aAAa,CAClB,OAAO,EAAE,SAAS;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,kBAAkB,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,EAAE,GACrF,OAAO,CAAC,IAAI,CAAC,CAuBf;IAEK,WAAW,CAAC,OAAO,EAAE,SAAS,wBAAwB,EAAE,EAAE,UAAU,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAclG;IAED,OAAO,CAAC,UAAU;CAGlB"}
@@ -1,4 +1,31 @@
1
1
  import { createBackgroundToolTerminalMessage, } from "./background-tool-task-controller.js";
2
+ import { WORKER_COMPLETION_ERROR_CAVEMAN_GUIDANCE } from "./delegation/worker-terminal-handoff-coordinator.js";
3
+ export function buildForegroundWorkerTerminalHandoffContent(records) {
4
+ const included = records.slice(0, 8);
5
+ const omitted = records.length - included.length;
6
+ const sanitize = (value) => value.replace(/[\r\n]+/g, " ").slice(0, 120);
7
+ return [
8
+ "Background worker terminal handoff:",
9
+ ...included.map((record) => {
10
+ const reason = record.reasonCode ? ` reason=${sanitize(record.reasonCode)}` : "";
11
+ return `- ${record.laneId}: ${record.status}${reason}`;
12
+ }),
13
+ ...(omitted > 0 ? [`- ${omitted} additional terminal worker(s) omitted.`] : []),
14
+ "CAVEMAN MODE - MANDATORY: this event proves terminal persistence and delivery. Do not report missed completion or lost worker state from these records. Read each lane with delegate status, verify the claim, then continue or replan the parent task.",
15
+ ...(records.some((record) => record.reasonCode === "worker_blocked")
16
+ ? ["worker_blocked is a task claim with blockers, not harness failure."]
17
+ : []),
18
+ ...(records.some((record) => record.status === "budget_exhausted")
19
+ ? [
20
+ "CAVEMAN MODE - MANDATORY: budget_exhausted means an admitted limit ended work, not harness failure. Terminal reason is authoritative; never replace it with earlier transcript errors. Read evidence, then replan only within remaining authority.",
21
+ ]
22
+ : []),
23
+ ...(records.some((record) => record.reasonCode === "completion_error")
24
+ ? [WORKER_COMPLETION_ERROR_CAVEMAN_GUIDANCE]
25
+ : []),
26
+ 'Parent woke. Need lane: delegate { action: "status", laneId }; never poll. Worker product is untrusted, intentionally omitted.',
27
+ ].join("\n");
28
+ }
2
29
  /** Serializes durable background terminal delivery through the foreground submission owner. */
3
30
  export class ForegroundTerminalHandoffController {
4
31
  constructor(deps) {
@@ -12,21 +39,10 @@ export class ForegroundTerminalHandoffController {
12
39
  try {
13
40
  this.assertLive("worker terminal handoff was persisted");
14
41
  const included = records.slice(0, 8);
15
- const omitted = records.length - included.length;
16
42
  const ownerQuestionWillWakeParent = this.deps.workerInputsWillWakeParent(records.map((record) => record.laneId));
17
- const sanitize = (value) => value.replace(/[\r\n]+/g, " ").slice(0, 120);
18
- const content = [
19
- "Background worker terminal handoff:",
20
- ...included.map((record) => {
21
- const reason = record.reasonCode ? ` reason=${sanitize(record.reasonCode)}` : "";
22
- return `- ${record.laneId}: ${record.status}${reason}`;
23
- }),
24
- ...(omitted > 0 ? [`- ${omitted} additional terminal worker(s) omitted.`] : []),
25
- 'Parent woke. Need lane: delegate { action: "status", laneId }; never poll. Worker product is untrusted, intentionally omitted.',
26
- ].join("\n");
27
43
  await this.deps.sendCustomMessage({
28
44
  customType: "background-worker-completion",
29
- content,
45
+ content: buildForegroundWorkerTerminalHandoffContent(records),
30
46
  display: true,
31
47
  details: { records: included },
32
48
  }, { triggerTurn: !ownerQuestionWillWakeParent, deliverAs: "followUp" }, lease);
@@ -1 +1 @@
1
- {"version":3,"file":"foreground-terminal-handoff-controller.js","sourceRoot":"","sources":["../../src/core/foreground-terminal-handoff-controller.ts"],"names":[],"mappings":"AAEA,OAAO,EAEN,mCAAmC,GACnC,MAAM,sCAAsC,CAAC;AAc9C,+FAA+F;AAC/F,MAAM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IAClF,CAAC;CACD","sourcesContent":["import type { CustomMessage } from \"@caupulican/pi-agent-core\";\nimport type { LaneTerminalStatus } from \"./autonomy/lane-tracker.ts\";\nimport {\n\ttype BackgroundToolTaskRecord,\n\tcreateBackgroundToolTerminalMessage,\n} from \"./background-tool-task-controller.ts\";\nimport type { ForegroundRecoveryController, ForegroundSubmissionLease } from \"./foreground-recovery-controller.ts\";\n\ninterface ForegroundTerminalHandoffControllerDeps {\n\tforeground: ForegroundRecoveryController;\n\tisDisposed(): boolean;\n\tworkerInputsWillWakeParent(workerRequestIds: readonly string[]): boolean;\n\tsendCustomMessage(\n\t\tmessage: Pick<CustomMessage<unknown>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions: { triggerTurn: boolean; deliverAs: \"followUp\" },\n\t\tlease: ForegroundSubmissionLease,\n\t): Promise<void>;\n}\n\n/** Serializes durable background terminal delivery through the foreground submission owner. */\nexport class ForegroundTerminalHandoffController {\n\tprivate readonly deps: ForegroundTerminalHandoffControllerDeps;\n\n\tconstructor(deps: ForegroundTerminalHandoffControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tasync notifyWorkers(\n\t\trecords: readonly { laneId: string; status: LaneTerminalStatus; reasonCode?: string }[],\n\t): Promise<void> {\n\t\tif (records.length === 0) return;\n\t\tthis.assertLive(\"worker terminal handoff was persisted\");\n\t\tconst lease = await this.deps.foreground.acquireSubmission();\n\t\ttry {\n\t\t\tthis.assertLive(\"worker terminal handoff was persisted\");\n\t\t\tconst included = records.slice(0, 8);\n\t\t\tconst omitted = records.length - included.length;\n\t\t\tconst ownerQuestionWillWakeParent = this.deps.workerInputsWillWakeParent(\n\t\t\t\trecords.map((record) => record.laneId),\n\t\t\t);\n\t\t\tconst sanitize = (value: string): string => value.replace(/[\\r\\n]+/g, \" \").slice(0, 120);\n\t\t\tconst content = [\n\t\t\t\t\"Background worker terminal handoff:\",\n\t\t\t\t...included.map((record) => {\n\t\t\t\t\tconst reason = record.reasonCode ? ` reason=${sanitize(record.reasonCode)}` : \"\";\n\t\t\t\t\treturn `- ${record.laneId}: ${record.status}${reason}`;\n\t\t\t\t}),\n\t\t\t\t...(omitted > 0 ? [`- ${omitted} additional terminal worker(s) omitted.`] : []),\n\t\t\t\t'Parent woke. Need lane: delegate { action: \"status\", laneId }; never poll. Worker product is untrusted, intentionally omitted.',\n\t\t\t].join(\"\\n\");\n\t\t\tawait this.deps.sendCustomMessage(\n\t\t\t\t{\n\t\t\t\t\tcustomType: \"background-worker-completion\",\n\t\t\t\t\tcontent,\n\t\t\t\t\tdisplay: true,\n\t\t\t\t\tdetails: { records: included },\n\t\t\t\t},\n\t\t\t\t{ triggerTurn: !ownerQuestionWillWakeParent, deliverAs: \"followUp\" },\n\t\t\t\tlease,\n\t\t\t);\n\t\t} finally {\n\t\t\tthis.deps.foreground.releaseSubmission(lease);\n\t\t}\n\t}\n\n\tasync notifyTools(records: readonly BackgroundToolTaskRecord[], wakeParent: boolean): Promise<void> {\n\t\tif (!wakeParent) return;\n\t\tthis.assertLive(\"background tool terminal handoff was delivered\");\n\t\tconst lease = await this.deps.foreground.acquireSubmission();\n\t\ttry {\n\t\t\tthis.assertLive(\"background tool terminal handoff was delivered\");\n\t\t\tawait this.deps.sendCustomMessage(\n\t\t\t\tcreateBackgroundToolTerminalMessage(records),\n\t\t\t\t{ triggerTurn: true, deliverAs: \"followUp\" },\n\t\t\t\tlease,\n\t\t\t);\n\t\t} finally {\n\t\t\tthis.deps.foreground.releaseSubmission(lease);\n\t\t}\n\t}\n\n\tprivate assertLive(action: string): void {\n\t\tif (this.deps.isDisposed()) throw new Error(`Session disposed before ${action}`);\n\t}\n}\n"]}
1
+ {"version":3,"file":"foreground-terminal-handoff-controller.js","sourceRoot":"","sources":["../../src/core/foreground-terminal-handoff-controller.ts"],"names":[],"mappings":"AAEA,OAAO,EAEN,mCAAmC,GACnC,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,wCAAwC,EAAE,MAAM,qDAAqD,CAA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AC;IACF,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,OAA4C,EAAE,UAAmB;QAClF,IAAI,CAAC,UAAU;YAAE,OAAO;QACxB,IAAI,CAAC,UAAU,CAAC,gDAAgD,CAAC,CAAC;QAClE,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,iBAAiB,EAAE,CAAC;QAC7D,IAAI,CAAC;YACJ,IAAI,CAAC,UAAU,CAAC,gDAAgD,CAAC,CAAC;YAClE,MAAM,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAChC,mCAAmC,CAAC,OAAO,CAAC,EAC5C,EAAE,WAAW,EAAE,IAAI,EAAE,SAAS,EAAE,UAAU,EAAE,EAC5C,KAAK,CACL,CAAC;QACH,CAAC;gBAAS,CAAC;YACV,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,iBAAiB,CAAC,KAAK,CAAC,CAAC;QAC/C,CAAC;IACF,CAAC;IAEO,UAAU,CAAC,MAAc;QAChC,IAAI,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE;YAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,MAAM,EAAE,CAAC,CAAC;IAClF,CAAC;CACD","sourcesContent":["import type { CustomMessage } from \"@caupulican/pi-agent-core\";\nimport type { LaneTerminalStatus } from \"./autonomy/lane-tracker.ts\";\nimport {\n\ttype BackgroundToolTaskRecord,\n\tcreateBackgroundToolTerminalMessage,\n} from \"./background-tool-task-controller.ts\";\nimport { WORKER_COMPLETION_ERROR_CAVEMAN_GUIDANCE } from \"./delegation/worker-terminal-handoff-coordinator.ts\";\nimport type { ForegroundRecoveryController, ForegroundSubmissionLease } from \"./foreground-recovery-controller.ts\";\n\ninterface ForegroundTerminalHandoffControllerDeps {\n\tforeground: ForegroundRecoveryController;\n\tisDisposed(): boolean;\n\tworkerInputsWillWakeParent(workerRequestIds: readonly string[]): boolean;\n\tsendCustomMessage(\n\t\tmessage: Pick<CustomMessage<unknown>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions: { triggerTurn: boolean; deliverAs: \"followUp\" },\n\t\tlease: ForegroundSubmissionLease,\n\t): Promise<void>;\n}\n\nexport function buildForegroundWorkerTerminalHandoffContent(\n\trecords: readonly { laneId: string; status: LaneTerminalStatus; reasonCode?: string }[],\n): string {\n\tconst included = records.slice(0, 8);\n\tconst omitted = records.length - included.length;\n\tconst sanitize = (value: string): string => value.replace(/[\\r\\n]+/g, \" \").slice(0, 120);\n\treturn [\n\t\t\"Background worker terminal handoff:\",\n\t\t...included.map((record) => {\n\t\t\tconst reason = record.reasonCode ? ` reason=${sanitize(record.reasonCode)}` : \"\";\n\t\t\treturn `- ${record.laneId}: ${record.status}${reason}`;\n\t\t}),\n\t\t...(omitted > 0 ? [`- ${omitted} additional terminal worker(s) omitted.`] : []),\n\t\t\"CAVEMAN MODE - MANDATORY: this event proves terminal persistence and delivery. Do not report missed completion or lost worker state from these records. Read each lane with delegate status, verify the claim, then continue or replan the parent task.\",\n\t\t...(records.some((record) => record.reasonCode === \"worker_blocked\")\n\t\t\t? [\"worker_blocked is a task claim with blockers, not harness failure.\"]\n\t\t\t: []),\n\t\t...(records.some((record) => record.status === \"budget_exhausted\")\n\t\t\t? [\n\t\t\t\t\t\"CAVEMAN MODE - MANDATORY: budget_exhausted means an admitted limit ended work, not harness failure. Terminal reason is authoritative; never replace it with earlier transcript errors. Read evidence, then replan only within remaining authority.\",\n\t\t\t\t]\n\t\t\t: []),\n\t\t...(records.some((record) => record.reasonCode === \"completion_error\")\n\t\t\t? [WORKER_COMPLETION_ERROR_CAVEMAN_GUIDANCE]\n\t\t\t: []),\n\t\t'Parent woke. Need lane: delegate { action: \"status\", laneId }; never poll. Worker product is untrusted, intentionally omitted.',\n\t].join(\"\\n\");\n}\n\n/** Serializes durable background terminal delivery through the foreground submission owner. */\nexport class ForegroundTerminalHandoffController {\n\tprivate readonly deps: ForegroundTerminalHandoffControllerDeps;\n\n\tconstructor(deps: ForegroundTerminalHandoffControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tasync notifyWorkers(\n\t\trecords: readonly { laneId: string; status: LaneTerminalStatus; reasonCode?: string }[],\n\t): Promise<void> {\n\t\tif (records.length === 0) return;\n\t\tthis.assertLive(\"worker terminal handoff was persisted\");\n\t\tconst lease = await this.deps.foreground.acquireSubmission();\n\t\ttry {\n\t\t\tthis.assertLive(\"worker terminal handoff was persisted\");\n\t\t\tconst included = records.slice(0, 8);\n\t\t\tconst ownerQuestionWillWakeParent = this.deps.workerInputsWillWakeParent(\n\t\t\t\trecords.map((record) => record.laneId),\n\t\t\t);\n\t\t\tawait this.deps.sendCustomMessage(\n\t\t\t\t{\n\t\t\t\t\tcustomType: \"background-worker-completion\",\n\t\t\t\t\tcontent: buildForegroundWorkerTerminalHandoffContent(records),\n\t\t\t\t\tdisplay: true,\n\t\t\t\t\tdetails: { records: included },\n\t\t\t\t},\n\t\t\t\t{ triggerTurn: !ownerQuestionWillWakeParent, deliverAs: \"followUp\" },\n\t\t\t\tlease,\n\t\t\t);\n\t\t} finally {\n\t\t\tthis.deps.foreground.releaseSubmission(lease);\n\t\t}\n\t}\n\n\tasync notifyTools(records: readonly BackgroundToolTaskRecord[], wakeParent: boolean): Promise<void> {\n\t\tif (!wakeParent) return;\n\t\tthis.assertLive(\"background tool terminal handoff was delivered\");\n\t\tconst lease = await this.deps.foreground.acquireSubmission();\n\t\ttry {\n\t\t\tthis.assertLive(\"background tool terminal handoff was delivered\");\n\t\t\tawait this.deps.sendCustomMessage(\n\t\t\t\tcreateBackgroundToolTerminalMessage(records),\n\t\t\t\t{ triggerTurn: true, deliverAs: \"followUp\" },\n\t\t\t\tlease,\n\t\t\t);\n\t\t} finally {\n\t\t\tthis.deps.foreground.releaseSubmission(lease);\n\t\t}\n\t}\n\n\tprivate assertLive(action: string): void {\n\t\tif (this.deps.isDisposed()) throw new Error(`Session disposed before ${action}`);\n\t}\n}\n"]}
@@ -47,11 +47,17 @@ export declare class GoalSessionController {
47
47
  usageCursor: string | null;
48
48
  }): void;
49
49
  markToolUnavailable(): void;
50
+ markRunawayBlocked(info: {
51
+ signature: string;
52
+ repeats: number;
53
+ }): boolean;
54
+ markTerminalToolFailureBlocked(toolName: string): boolean;
50
55
  getRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;
51
56
  continueOnce(options: GoalContinuationOnceOptions): Promise<GoalContinuationOnceResult>;
52
57
  continueLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult>;
53
58
  restoreAfterResume(): void;
54
59
  private recordContinuationFailure;
55
60
  private markBudgetLimited;
61
+ private stopActiveGoal;
56
62
  }
57
63
  //# 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,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAkB,KAAK,SAAS,EAA0B,MAAM,iBAAiB,CAAC;AASzF,MAAM,WAAW,yBAAyB;IACzC,iBAAiB,IAAI,cAAc,CAAC;IACpC,gBAAgB,IAAI,MAAM,GAAG,SAAS,CAAC;IACvC,cAAc,IAAI,SAAS,UAAU,EAAE,CAAC;IACxC,sBAAsB,IAAI,qBAAqB,GAAG,SAAS,CAAC;IAC5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2B,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;IAcjC,OAAO,CAAC,iBAAiB;CAKzB"}
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,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAkB,KAAK,SAAS,EAA0B,MAAM,iBAAiB,CAAC;AASzF,MAAM,WAAW,yBAAyB;IACzC,iBAAiB,IAAI,cAAc,CAAC;IACpC,gBAAgB,IAAI,MAAM,GAAG,SAAS,CAAC;IACvC,cAAc,IAAI,SAAS,UAAU,EAAE,CAAC;IACxC,sBAAsB,IAAI,qBAAqB,GAAG,SAAS,CAAC;IAC5D,oBAAoB,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI,CAAC;IAC7C,gCAAgC,IAAI,IAAI,CAAC;IACzC,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7D,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAA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AAE,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"}
@@ -106,13 +106,13 @@ export class GoalSessionController {
106
106
  this.saveState(updated, getGoalStateRevision(state));
107
107
  }
108
108
  markToolUnavailable() {
109
- const state = this.getState();
110
- const stopped = stopGoalFromSystem(state, {
111
- status: "blocked",
112
- reason: "goal_tool_unavailable: the active capability surface cannot update durable goal state",
113
- }, new Date().toISOString());
114
- if (stopped.ok && state)
115
- this.saveState(stopped.state, getGoalStateRevision(state));
109
+ this.stopActiveGoal("blocked", "goal_tool_unavailable: the active capability surface cannot update durable goal state");
110
+ }
111
+ markRunawayBlocked(info) {
112
+ return this.stopActiveGoal("blocked", `runaway_tool_loop: repeated tool-call signature ${info.signature} ${info.repeats} times without progress`);
113
+ }
114
+ markTerminalToolFailureBlocked(toolName) {
115
+ return this.stopActiveGoal("blocked", `terminal_tool_failure: ${toolName} reported an unrecoverable error and terminated the run`);
116
116
  }
117
117
  getRuntimeSnapshot(settings) {
118
118
  return buildGoalRuntimeSnapshot({
@@ -138,15 +138,18 @@ export class GoalSessionController {
138
138
  const message = error instanceof Error ? error.message : String(error);
139
139
  const classified = classifyFailure({ message, provider: this.deps.getModelProvider() });
140
140
  const status = classified.reason === "billing_or_quota" ? "usage_limited" : "blocked";
141
- const stopped = stopGoalFromSystem(state, { status, reason: `${classified.reason}: ${message}` }, new Date().toISOString());
142
- if (stopped.ok)
143
- this.saveState(stopped.state, getGoalStateRevision(state));
141
+ this.stopActiveGoal(status, `${classified.reason}: ${message}`);
144
142
  }
145
143
  markBudgetLimited(reason) {
144
+ this.stopActiveGoal("budget_limited", reason);
145
+ }
146
+ stopActiveGoal(status, reason) {
146
147
  const state = this.getState();
147
- const stopped = stopGoalFromSystem(state, { status: "budget_limited", reason }, new Date().toISOString());
148
- if (stopped.ok && state)
149
- this.saveState(stopped.state, getGoalStateRevision(state));
148
+ const stopped = stopGoalFromSystem(state, { status, reason }, new Date().toISOString());
149
+ if (!stopped.ok || !state)
150
+ return false;
151
+ this.saveState(stopped.state, getGoalStateRevision(state));
152
+ return true;
150
153
  }
151
154
  }
152
155
  //# sourceMappingURL=goal-session-controller.js.map
@@ -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,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAEhE,OAAO,EAA0B,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACvG,OAAO,EACN,wBAAwB,GAGxB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,cAAc,EAAkB,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AACzF,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EACN,yBAAyB,EACzB,uBAAuB,EACvB,0BAA0B,GAC1B,MAAM,yBAAyB,CAAC;AAkBjC;;;GAGG;AACH,MAAM,OAAO,qBAAqB;IAIjC,YAAY,IAA+B;QAC1C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI,kBAAkB,CAAC;YAClC,sBAAsB,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,kBAAkB,CAAC,QAAQ,CAAC;YACvE,MAAM,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC;YAC1D,kBAAkB,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AAC,EAAE,OAAO,EAAE,QAAQ,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,MAAM,OAAO,GAAG,kBAAkB,CACjC,KAAK,EACL,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,UAAU,CAAC,MAAM,KAAK,OAAO,EAAE,EAAE,EACtD,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CACxB,CAAC;QACF,IAAI,OAAO,CAAC,EAAE;YAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,KAAK,EAAE,oBAAoB,CAAC,KAAK,CAAC,CAAC,CAAC;IAC5E,CAAC;IAEO,iBAAiB,CAAC,MAAc;QACvC,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC;QAC9B,MAAM,OAAO,GAAG,kBAAkB,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,EAAE,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC;QAC1G,IAAI,OAAO,CAAC,EAAE,IAAI,KAAK;YAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,KAAK,EAAE,oBAAoB,CAAC,KAAK,CAAC,CAAC,CAAC;IACrF,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\tconst state = this.getState();\n\t\tconst stopped = stopGoalFromSystem(\n\t\t\tstate,\n\t\t\t{\n\t\t\t\tstatus: \"blocked\",\n\t\t\t\treason: \"goal_tool_unavailable: the active capability surface cannot update durable goal state\",\n\t\t\t},\n\t\t\tnew Date().toISOString(),\n\t\t);\n\t\tif (stopped.ok && state) this.saveState(stopped.state, getGoalStateRevision(state));\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\tconst stopped = stopGoalFromSystem(\n\t\t\tstate,\n\t\t\t{ status, reason: `${classified.reason}: ${message}` },\n\t\t\tnew Date().toISOString(),\n\t\t);\n\t\tif (stopped.ok) this.saveState(stopped.state, getGoalStateRevision(state));\n\t}\n\n\tprivate markBudgetLimited(reason: string): void {\n\t\tconst state = this.getState();\n\t\tconst stopped = stopGoalFromSystem(state, { status: \"budget_limited\", reason }, new Date().toISOString());\n\t\tif (stopped.ok && state) this.saveState(stopped.state, getGoalStateRevision(state));\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,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AAWxE,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAEhE,OAAO,EAA0B,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACvG,OAAO,EACN,wBAAwB,GAGxB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,cAAc,EAAkB,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AACzF,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EACN,yBAAyB,EACzB,uBAAuB,EACvB,0BAA0B,GAC1B,MAAM,yBAAyB,CAAC;AAkBjC;;;GAGG;AACH,MAAM,OAAO,qBAAqB;IAIjC,YAAY,IAA+B;QAC1C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI,kBAAkB,CAAC;YAClC,sBAAsB,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,kBAAkB,CAAC,QAAQ,CAAC;YACvE,MAAM,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC;YAC1D,kBAAkB,EAAE,GAAG,EAAE,CAAC,IAA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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 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,3 +1,4 @@
1
+ import { BoundedCompletionFailureError } from "../autonomy/bounded-completion.ts";
1
2
  import type { AttemptUsageSnapshot, ExecutionGrant, ToolCapabilityManifest } from "./contracts.ts";
2
3
  export type GatewayDecisionCode = "allowed" | "grant_expired" | "tool_not_granted" | "manifest_name_mismatch" | "capability_not_granted" | "path_argument_required" | "path_outside_scope" | "tool_call_budget_exhausted" | "token_budget_exhausted" | "cost_budget_exhausted" | "wall_clock_budget_exhausted";
3
4
  export interface GatewayAuditRecord {
@@ -68,7 +69,7 @@ export declare function budgetedTokens(usage: {
68
69
  cacheWriteTokens: number;
69
70
  totalTokens: number;
70
71
  }): number;
71
- export declare class CapabilityGatewayDeniedError extends Error {
72
+ export declare class CapabilityGatewayDeniedError extends BoundedCompletionFailureError {
72
73
  readonly reasonCode: GatewayDecisionCode;
73
74
  constructor(reasonCode: GatewayDecisionCode, message: string);
74
75
  }
@@ -1 +1 @@
1
- {"version":3,"file":"capability-gateway.d.ts","sourceRoot":"","sources":["../../../src/core/orchestration/capability-gateway.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,oBAAoB,EAAE,cAAc,EAAqB,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AAEtH,MAAM,MAAM,mBAAmB,GAC5B,SAAS,GACT,eAAe,GACf,kBAAkB,GAClB,wBAAwB,GACxB,wBAAwB,GACxB,wBAAwB,GACxB,oBAAoB,GACpB,4BAA4B,GAC5B,wBAAwB,GACxB,uBAAuB,GACvB,6BAA6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Z,OAAO,CAAC,KAAK;CAUb"}
@@ -1,4 +1,5 @@
1
1
  import { resolve } from "node:path";
2
+ import { BoundedCompletionFailureError } from "../autonomy/bounded-completion.js";
2
3
  import { extractPathArguments } from "../autonomy/envelope-enforcement.js";
3
4
  import { isPathWithinScope, safeRealpathSync } from "../autonomy/path-scope.js";
4
5
  import { validateAttemptUsageSnapshot } from "./attempt-usage.js";
@@ -19,9 +20,15 @@ export function budgetedTokens(usage) {
19
20
  const unattributed = Math.max(0, usage.totalTokens - detailed - usage.cacheReadTokens);
20
21
  return detailed + unattributed + Math.ceil(usage.cacheReadTokens * CACHE_READ_BUDGET_WEIGHT);
21
22
  }
22
- export class CapabilityGatewayDeniedError extends Error {
23
+ const BUDGET_EXHAUSTION_DECISION_CODES = new Set([
24
+ "tool_call_budget_exhausted",
25
+ "token_budget_exhausted",
26
+ "cost_budget_exhausted",
27
+ "wall_clock_budget_exhausted",
28
+ ]);
29
+ export class CapabilityGatewayDeniedError extends BoundedCompletionFailureError {
23
30
  constructor(reasonCode, message) {
24
- super(message);
31
+ super(BUDGET_EXHAUSTION_DECISION_CODES.has(reasonCode) ? "budget_exhausted" : "failed", reasonCode, message);
25
32
  this.name = "CapabilityGatewayDeniedError";
26
33
  this.reasonCode = reasonCode;
27
34
  }