@caupulican/pi-adaptative 0.81.41 → 0.81.42

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 (237) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/text.py +5 -1
  3. package/dist/bundled-resources/runtimes/pi-shell-engine/context.py +3 -3
  4. package/dist/bundled-resources/runtimes/pi-shell-engine/errors.py +8 -0
  5. package/dist/bundled-resources/runtimes/pi-shell-engine/exec.py +26 -3
  6. package/dist/bundled-resources/runtimes/pi-shell-engine/expand.py +3 -0
  7. package/dist/bundled-resources/runtimes/pi-shell-engine/main.py +4 -1
  8. package/dist/bundled-resources/runtimes/pi-shell-engine/state.py +2 -1
  9. package/dist/bundled-resources/runtimes/pi-shell-engine/tokens.py +2 -0
  10. package/dist/core/agent-paths.d.ts +32 -0
  11. package/dist/core/agent-paths.d.ts.map +1 -1
  12. package/dist/core/agent-paths.js +65 -0
  13. package/dist/core/agent-paths.js.map +1 -1
  14. package/dist/core/agent-session-contracts.d.ts +19 -1
  15. package/dist/core/agent-session-contracts.d.ts.map +1 -1
  16. package/dist/core/agent-session-contracts.js.map +1 -1
  17. package/dist/core/agent-session.d.ts.map +1 -1
  18. package/dist/core/agent-session.js +4 -9
  19. package/dist/core/agent-session.js.map +1 -1
  20. package/dist/core/autonomy/contracts.d.ts +2 -0
  21. package/dist/core/autonomy/contracts.d.ts.map +1 -1
  22. package/dist/core/autonomy/contracts.js.map +1 -1
  23. package/dist/core/autonomy/envelope-enforcement.d.ts.map +1 -1
  24. package/dist/core/autonomy/envelope-enforcement.js +4 -9
  25. package/dist/core/autonomy/envelope-enforcement.js.map +1 -1
  26. package/dist/core/autonomy/lane-tool-surface.d.ts +3 -1
  27. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  28. package/dist/core/autonomy/lane-tool-surface.js +17 -4
  29. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  30. package/dist/core/autonomy/path-scope.d.ts +14 -0
  31. package/dist/core/autonomy/path-scope.d.ts.map +1 -1
  32. package/dist/core/autonomy/path-scope.js +37 -6
  33. package/dist/core/autonomy/path-scope.js.map +1 -1
  34. package/dist/core/background-lane-controller.d.ts +27 -1
  35. package/dist/core/background-lane-controller.d.ts.map +1 -1
  36. package/dist/core/background-lane-controller.js +32 -1
  37. package/dist/core/background-lane-controller.js.map +1 -1
  38. package/dist/core/delegation/managed-lane-controller.d.ts +11 -1
  39. package/dist/core/delegation/managed-lane-controller.d.ts.map +1 -1
  40. package/dist/core/delegation/managed-lane-controller.js +84 -41
  41. package/dist/core/delegation/managed-lane-controller.js.map +1 -1
  42. package/dist/core/delegation/session-worker-claim.d.ts.map +1 -1
  43. package/dist/core/delegation/session-worker-claim.js +4 -3
  44. package/dist/core/delegation/session-worker-claim.js.map +1 -1
  45. package/dist/core/delegation/worker-action-journal.d.ts +73 -0
  46. package/dist/core/delegation/worker-action-journal.d.ts.map +1 -0
  47. package/dist/core/delegation/worker-action-journal.js +297 -0
  48. package/dist/core/delegation/worker-action-journal.js.map +1 -0
  49. package/dist/core/delegation/worker-actions.d.ts +36 -1
  50. package/dist/core/delegation/worker-actions.d.ts.map +1 -1
  51. package/dist/core/delegation/worker-actions.js +171 -46
  52. package/dist/core/delegation/worker-actions.js.map +1 -1
  53. package/dist/core/delegation/worker-agent-control-coordinator.d.ts +75 -0
  54. package/dist/core/delegation/worker-agent-control-coordinator.d.ts.map +1 -0
  55. package/dist/core/delegation/worker-agent-control-coordinator.js +218 -0
  56. package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -0
  57. package/dist/core/delegation/worker-agent-control.d.ts +66 -0
  58. package/dist/core/delegation/worker-agent-control.d.ts.map +1 -0
  59. package/dist/core/delegation/worker-agent-control.js +163 -0
  60. package/dist/core/delegation/worker-agent-control.js.map +1 -0
  61. package/dist/core/delegation/worker-attempt-executor.d.ts +80 -0
  62. package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -0
  63. package/dist/core/delegation/worker-attempt-executor.js +343 -0
  64. package/dist/core/delegation/worker-attempt-executor.js.map +1 -0
  65. package/dist/core/delegation/worker-claim.d.ts +30 -0
  66. package/dist/core/delegation/worker-claim.d.ts.map +1 -1
  67. package/dist/core/delegation/worker-claim.js +205 -53
  68. package/dist/core/delegation/worker-claim.js.map +1 -1
  69. package/dist/core/delegation/worker-conversation-store.d.ts +116 -0
  70. package/dist/core/delegation/worker-conversation-store.d.ts.map +1 -0
  71. package/dist/core/delegation/worker-conversation-store.js +442 -0
  72. package/dist/core/delegation/worker-conversation-store.js.map +1 -0
  73. package/dist/core/delegation/worker-delegation-controller.d.ts +21 -5
  74. package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
  75. package/dist/core/delegation/worker-delegation-controller.js +386 -251
  76. package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
  77. package/dist/core/delegation/worker-delegation-request.d.ts +14 -0
  78. package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -1
  79. package/dist/core/delegation/worker-delegation-request.js.map +1 -1
  80. package/dist/core/delegation/worker-dispatch-scheduler.d.ts +4 -2
  81. package/dist/core/delegation/worker-dispatch-scheduler.d.ts.map +1 -1
  82. package/dist/core/delegation/worker-dispatch-scheduler.js +16 -6
  83. package/dist/core/delegation/worker-dispatch-scheduler.js.map +1 -1
  84. package/dist/core/delegation/worker-execution-policy.d.ts +2 -1
  85. package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -1
  86. package/dist/core/delegation/worker-execution-policy.js +5 -7
  87. package/dist/core/delegation/worker-execution-policy.js.map +1 -1
  88. package/dist/core/delegation/worker-lifecycle.d.ts +44 -1
  89. package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -1
  90. package/dist/core/delegation/worker-lifecycle.js +120 -0
  91. package/dist/core/delegation/worker-lifecycle.js.map +1 -1
  92. package/dist/core/delegation/worker-process-owner.d.ts +18 -0
  93. package/dist/core/delegation/worker-process-owner.d.ts.map +1 -0
  94. package/dist/core/delegation/worker-process-owner.js +54 -0
  95. package/dist/core/delegation/worker-process-owner.js.map +1 -0
  96. package/dist/core/delegation/worker-profile-resolver.d.ts +5 -1
  97. package/dist/core/delegation/worker-profile-resolver.d.ts.map +1 -1
  98. package/dist/core/delegation/worker-profile-resolver.js +8 -0
  99. package/dist/core/delegation/worker-profile-resolver.js.map +1 -1
  100. package/dist/core/delegation/worker-recovery-coordinator.d.ts +54 -0
  101. package/dist/core/delegation/worker-recovery-coordinator.d.ts.map +1 -0
  102. package/dist/core/delegation/worker-recovery-coordinator.js +181 -0
  103. package/dist/core/delegation/worker-recovery-coordinator.js.map +1 -0
  104. package/dist/core/delegation/worker-resource-catalog.d.ts +32 -0
  105. package/dist/core/delegation/worker-resource-catalog.d.ts.map +1 -0
  106. package/dist/core/delegation/worker-resource-catalog.js +116 -0
  107. package/dist/core/delegation/worker-resource-catalog.js.map +1 -0
  108. package/dist/core/delegation/worker-resource-materializer.d.ts +47 -0
  109. package/dist/core/delegation/worker-resource-materializer.d.ts.map +1 -0
  110. package/dist/core/delegation/worker-resource-materializer.js +137 -0
  111. package/dist/core/delegation/worker-resource-materializer.js.map +1 -0
  112. package/dist/core/delegation/worker-runner.d.ts +3 -1
  113. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  114. package/dist/core/delegation/worker-runner.js +189 -54
  115. package/dist/core/delegation/worker-runner.js.map +1 -1
  116. package/dist/core/delegation/worker-terminal-finalizer.d.ts +23 -0
  117. package/dist/core/delegation/worker-terminal-finalizer.d.ts.map +1 -0
  118. package/dist/core/delegation/worker-terminal-finalizer.js +12 -0
  119. package/dist/core/delegation/worker-terminal-finalizer.js.map +1 -0
  120. package/dist/core/delegation/worker-write-reservation-coordinator.d.ts +38 -0
  121. package/dist/core/delegation/worker-write-reservation-coordinator.d.ts.map +1 -0
  122. package/dist/core/delegation/worker-write-reservation-coordinator.js +107 -0
  123. package/dist/core/delegation/worker-write-reservation-coordinator.js.map +1 -0
  124. package/dist/core/delegation/worker-write-reservation.d.ts +90 -0
  125. package/dist/core/delegation/worker-write-reservation.d.ts.map +1 -0
  126. package/dist/core/delegation/worker-write-reservation.js +348 -0
  127. package/dist/core/delegation/worker-write-reservation.js.map +1 -0
  128. package/dist/core/models/model-endpoint.d.ts +3 -0
  129. package/dist/core/models/model-endpoint.d.ts.map +1 -0
  130. package/dist/core/models/model-endpoint.js +11 -0
  131. package/dist/core/models/model-endpoint.js.map +1 -0
  132. package/dist/core/orchestration/agent-resume.d.ts +2 -0
  133. package/dist/core/orchestration/agent-resume.d.ts.map +1 -1
  134. package/dist/core/orchestration/agent-resume.js +7 -0
  135. package/dist/core/orchestration/agent-resume.js.map +1 -1
  136. package/dist/core/orchestration/attempt-usage.d.ts +28 -0
  137. package/dist/core/orchestration/attempt-usage.d.ts.map +1 -0
  138. package/dist/core/orchestration/attempt-usage.js +168 -0
  139. package/dist/core/orchestration/attempt-usage.js.map +1 -0
  140. package/dist/core/orchestration/capability-gateway.d.ts +19 -1
  141. package/dist/core/orchestration/capability-gateway.d.ts.map +1 -1
  142. package/dist/core/orchestration/capability-gateway.js +128 -28
  143. package/dist/core/orchestration/capability-gateway.js.map +1 -1
  144. package/dist/core/orchestration/contracts.d.ts +35 -0
  145. package/dist/core/orchestration/contracts.d.ts.map +1 -1
  146. package/dist/core/orchestration/contracts.js +17 -0
  147. package/dist/core/orchestration/contracts.js.map +1 -1
  148. package/dist/core/orchestration/delegation-ledger.d.ts +17 -2
  149. package/dist/core/orchestration/delegation-ledger.d.ts.map +1 -1
  150. package/dist/core/orchestration/delegation-ledger.js +78 -3
  151. package/dist/core/orchestration/delegation-ledger.js.map +1 -1
  152. package/dist/core/orchestration/event-store.d.ts +1 -0
  153. package/dist/core/orchestration/event-store.d.ts.map +1 -1
  154. package/dist/core/orchestration/event-store.js +78 -38
  155. package/dist/core/orchestration/event-store.js.map +1 -1
  156. package/dist/core/orchestration/profile-registry.d.ts.map +1 -1
  157. package/dist/core/orchestration/profile-registry.js +81 -41
  158. package/dist/core/orchestration/profile-registry.js.map +1 -1
  159. package/dist/core/orchestration/profile-store.d.ts.map +1 -1
  160. package/dist/core/orchestration/profile-store.js +18 -4
  161. package/dist/core/orchestration/profile-store.js.map +1 -1
  162. package/dist/core/orchestration/risk-budget.d.ts +2 -0
  163. package/dist/core/orchestration/risk-budget.d.ts.map +1 -1
  164. package/dist/core/orchestration/risk-budget.js +26 -0
  165. package/dist/core/orchestration/risk-budget.js.map +1 -1
  166. package/dist/core/orchestration/task-runtime.d.ts +13 -1
  167. package/dist/core/orchestration/task-runtime.d.ts.map +1 -1
  168. package/dist/core/orchestration/task-runtime.js +127 -16
  169. package/dist/core/orchestration/task-runtime.js.map +1 -1
  170. package/dist/core/orchestration/worker-execution-contract.d.ts +3 -1
  171. package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -1
  172. package/dist/core/orchestration/worker-execution-contract.js +75 -23
  173. package/dist/core/orchestration/worker-execution-contract.js.map +1 -1
  174. package/dist/core/orchestration/worker-result-adapter.d.ts +9 -3
  175. package/dist/core/orchestration/worker-result-adapter.d.ts.map +1 -1
  176. package/dist/core/orchestration/worker-result-adapter.js +167 -14
  177. package/dist/core/orchestration/worker-result-adapter.js.map +1 -1
  178. package/dist/core/reflection-controller.d.ts +1 -1
  179. package/dist/core/reflection-controller.d.ts.map +1 -1
  180. package/dist/core/reflection-controller.js +90 -54
  181. package/dist/core/reflection-controller.js.map +1 -1
  182. package/dist/core/research/evidence-bundle.d.ts +20 -0
  183. package/dist/core/research/evidence-bundle.d.ts.map +1 -1
  184. package/dist/core/research/evidence-bundle.js +173 -69
  185. package/dist/core/research/evidence-bundle.js.map +1 -1
  186. package/dist/core/runtime-builder.d.ts +7 -0
  187. package/dist/core/runtime-builder.d.ts.map +1 -1
  188. package/dist/core/runtime-builder.js +15 -1
  189. package/dist/core/runtime-builder.js.map +1 -1
  190. package/dist/core/session-artifact-bundle.d.ts +35 -0
  191. package/dist/core/session-artifact-bundle.d.ts.map +1 -0
  192. package/dist/core/session-artifact-bundle.js +61 -0
  193. package/dist/core/session-artifact-bundle.js.map +1 -0
  194. package/dist/core/tools/delegate-status.d.ts +6 -1
  195. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  196. package/dist/core/tools/delegate-status.js +100 -18
  197. package/dist/core/tools/delegate-status.js.map +1 -1
  198. package/dist/core/tools/delegate.d.ts +9 -1
  199. package/dist/core/tools/delegate.d.ts.map +1 -1
  200. package/dist/core/tools/delegate.js +323 -61
  201. package/dist/core/tools/delegate.js.map +1 -1
  202. package/dist/core/tools/run-process.d.ts +1 -1
  203. package/dist/core/tools/run-process.d.ts.map +1 -1
  204. package/dist/core/tools/run-process.js +69 -9
  205. package/dist/core/tools/run-process.js.map +1 -1
  206. package/dist/core/tools/shell-contract-router.d.ts.map +1 -1
  207. package/dist/core/tools/shell-contract-router.js +12 -5
  208. package/dist/core/tools/shell-contract-router.js.map +1 -1
  209. package/dist/core/util/bounded-file.d.ts +15 -0
  210. package/dist/core/util/bounded-file.d.ts.map +1 -0
  211. package/dist/core/util/bounded-file.js +120 -0
  212. package/dist/core/util/bounded-file.js.map +1 -0
  213. package/dist/core/util/bounded-jsonl.d.ts.map +1 -1
  214. package/dist/core/util/bounded-jsonl.js +119 -9
  215. package/dist/core/util/bounded-jsonl.js.map +1 -1
  216. package/dist/core/util/bounded-value.d.ts +3 -0
  217. package/dist/core/util/bounded-value.d.ts.map +1 -0
  218. package/dist/core/util/bounded-value.js +12 -0
  219. package/dist/core/util/bounded-value.js.map +1 -0
  220. package/dist/core/util/value-guards.d.ts +2 -0
  221. package/dist/core/util/value-guards.d.ts.map +1 -1
  222. package/dist/core/util/value-guards.js +5 -0
  223. package/dist/core/util/value-guards.js.map +1 -1
  224. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  225. package/dist/modes/interactive/components/session-selector.js +27 -44
  226. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  227. package/docs/tool-repair.md +3 -0
  228. package/docs/windows.md +4 -2
  229. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  230. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  231. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  232. package/examples/extensions/sandbox/package-lock.json +2 -2
  233. package/examples/extensions/sandbox/package.json +1 -1
  234. package/examples/extensions/with-deps/package-lock.json +2 -2
  235. package/examples/extensions/with-deps/package.json +1 -1
  236. package/npm-shrinkwrap.json +12 -12
  237. package/package.json +4 -4
@@ -1,6 +1,8 @@
1
+ import { sameAgentResumeIdentity } from "../orchestration/agent-resume.js";
1
2
  import { DelegationOrchestrationLedger, } from "../orchestration/delegation-ledger.js";
2
3
  import { verifierWorkerExecutionContract } from "../orchestration/worker-execution-contract.js";
3
4
  import { ACTIVE_WORKER_ATTEMPT_STATUSES, isManagedWorkerAttempt, projectManagedWorkerLaneRecords, projectWorkerLaneRecord, selectedManagedWorkerAttempt, selectedWorkerAttempt, } from "./worker-lane-projection.js";
5
+ import { isLocalProcessAlive, isLocalWorkerProcessOwnerProvenDead } from "./worker-process-owner.js";
4
6
  /**
5
7
  * Sole owner of in-process worker lifecycle state. LaneRecord is a compatibility/UI projection;
6
8
  * all transitions are committed through DurableTaskRuntime before the projection is returned.
@@ -8,8 +10,10 @@ import { ACTIVE_WORKER_ATTEMPT_STATUSES, isManagedWorkerAttempt, projectManagedW
8
10
  export class WorkerLifecycle {
9
11
  ledger;
10
12
  nextLaneNumber;
13
+ isProcessAlive;
11
14
  constructor(options) {
12
15
  this.ledger = new DelegationOrchestrationLedger(options);
16
+ this.isProcessAlive = options.isProcessAlive ?? isLocalProcessAlive;
13
17
  const snapshot = this.ledger.runtime.getSnapshot();
14
18
  const highest = Object.keys(snapshot.tasks).reduce((current, taskId) => {
15
19
  const suffix = /^worker-(\d+)$/.exec(taskId)?.[1];
@@ -31,6 +35,24 @@ export class WorkerLifecycle {
31
35
  throw new Error(`Durable worker '${selectedLaneId}' was not projected after enqueue.`);
32
36
  return { record, attempt };
33
37
  }
38
+ /** Queue the next distinct task/attempt for an idle logical agent. */
39
+ prepareAgentTurn(input) {
40
+ const attempt = this.ledger.prepareAgentTurn(input);
41
+ const record = this.getRecord(attempt.taskId);
42
+ if (!record)
43
+ throw new Error(`Logical worker '${input.agentId}' turn was not projected after enqueue.`);
44
+ return { record, attempt };
45
+ }
46
+ ensureAgent(input) {
47
+ const agentId = input.agentId.trim();
48
+ const existing = this.ledger.runtime.getSnapshot().agents[agentId];
49
+ if (!existing)
50
+ return this.ledger.runtime.registerAgent(input);
51
+ if (existing.role !== input.role || !sameAgentResumeIdentity(existing.resumeContext, input.resumeContext)) {
52
+ throw new Error(`Agent '${agentId}' was re-registered with conflicting identity.`);
53
+ }
54
+ return existing;
55
+ }
34
56
  prepareManaged(input) {
35
57
  const before = selectedManagedWorkerAttempt(this.ledger.runtime.getSnapshot(), input.laneId);
36
58
  if (before?.dispatch.dispatchSequence === input.dispatchSequence) {
@@ -90,6 +112,91 @@ export class WorkerLifecycle {
90
112
  const attempt = this.requireActiveAttempt(laneId);
91
113
  return this.ledger.start(attempt.attemptId, leaseTtlMs);
92
114
  }
115
+ startAgent(laneId, agentId, leaseTtlMs, ownerId = agentId) {
116
+ const attempt = this.requireActiveAttempt(laneId);
117
+ return this.ledger.start(attempt.attemptId, leaseTtlMs, ownerId, agentId);
118
+ }
119
+ checkpoint(laneId, input) {
120
+ const attempt = this.requireActiveAttempt(laneId);
121
+ if (!attempt.lease)
122
+ throw new Error(`Durable worker '${laneId}' has no live lease.`);
123
+ return this.ledger.runtime.checkpointAttempt({
124
+ attemptId: attempt.attemptId,
125
+ leaseId: attempt.lease.leaseId,
126
+ fencingToken: attempt.lease.fencingToken,
127
+ summary: input.summary,
128
+ ...(input.artifactIds ? { artifactIds: input.artifactIds } : {}),
129
+ ...(input.evidenceIds ? { evidenceIds: input.evidenceIds } : {}),
130
+ ...(input.usage ? { usage: input.usage } : {}),
131
+ });
132
+ }
133
+ /**
134
+ * Suspend only attempts whose exact controller owner is known (explicit shutdown) or whose
135
+ * recorded local owner PID is proven gone (recovery). A live/unknown owner is never stolen.
136
+ */
137
+ suspendBoundInProcessAttemptsForRestart(ownerId) {
138
+ const suspended = [];
139
+ for (const attempt of Object.values(this.ledger.runtime.getSnapshot().attempts)) {
140
+ if ((attempt.status !== "leased" && attempt.status !== "running") ||
141
+ !attempt.agentId ||
142
+ attempt.dispatch.executionKind === "managed-process" ||
143
+ !attempt.lease) {
144
+ continue;
145
+ }
146
+ const ownsAttempt = ownerId !== undefined
147
+ ? attempt.lease.ownerId === ownerId
148
+ : isLocalWorkerProcessOwnerProvenDead(attempt.lease.ownerId, this.isProcessAlive);
149
+ if (!ownsAttempt)
150
+ continue;
151
+ this.suspendBoundAttempt({
152
+ laneId: attempt.taskId,
153
+ ownerId: attempt.lease.ownerId,
154
+ leaseId: attempt.lease.leaseId,
155
+ fencingToken: attempt.lease.fencingToken,
156
+ reasonCode: ownerId === undefined ? "agent_process_recovered_after_owner_exit" : "agent_process_interrupted",
157
+ });
158
+ suspended.push(attempt.attemptId);
159
+ }
160
+ return suspended;
161
+ }
162
+ /**
163
+ * Applies an explicitly authorized restart suspension. The caller must identify both the logical
164
+ * lane and the current lease fence; process liveness policy is intentionally kept by this class.
165
+ */
166
+ suspendBoundAttempt(args) {
167
+ const attempt = this.getActiveAttempt(args.laneId);
168
+ if (!attempt || !attempt.agentId || !attempt.lease) {
169
+ throw new Error(`Durable worker '${args.laneId}' has no live agent-bound attempt for suspension.`);
170
+ }
171
+ this.ledger.runtime.suspendBoundAttempt({
172
+ attemptId: attempt.attemptId,
173
+ ownerId: args.ownerId,
174
+ leaseId: args.leaseId,
175
+ fencingToken: args.fencingToken,
176
+ reasonCode: args.reasonCode,
177
+ });
178
+ }
179
+ resumeAgent(laneId, agentId, leaseTtlMs, ownerId = agentId) {
180
+ const attempt = this.getActiveAttempt(laneId);
181
+ if (!attempt)
182
+ throw new Error(`Durable worker '${laneId}' has no resumable attempt.`);
183
+ this.ledger.runtime.requestAgentResume(agentId);
184
+ const lease = this.ledger.runtime.resumeAttempt(attempt.attemptId, agentId, leaseTtlMs, ownerId);
185
+ return this.startedHandle(this.ledger.runtime.startAttempt(attempt.attemptId, lease.leaseId, lease.fencingToken));
186
+ }
187
+ suspendAgent(laneId, agentId, ownerId, reasonCode = "agent_interrupted") {
188
+ const attempt = this.getActiveAttempt(laneId);
189
+ if (!attempt || attempt.agentId !== agentId || !attempt.lease) {
190
+ throw new Error(`Logical worker '${agentId}' has no live attempt for interruption.`);
191
+ }
192
+ this.suspendBoundAttempt({
193
+ laneId,
194
+ ownerId,
195
+ leaseId: attempt.lease.leaseId,
196
+ fencingToken: attempt.lease.fencingToken,
197
+ reasonCode,
198
+ });
199
+ }
93
200
  bindGrant(attemptId, grant) {
94
201
  this.ledger.runtime.bindAttemptGrant(attemptId, grant);
95
202
  }
@@ -202,6 +309,15 @@ export class WorkerLifecycle {
202
309
  getTask(taskId) {
203
310
  return this.ledger.runtime.getSnapshot().tasks[taskId];
204
311
  }
312
+ getAgent(agentId) {
313
+ return this.ledger.runtime.getSnapshot().agents[agentId];
314
+ }
315
+ getLatestAgentAttempt(agentId) {
316
+ return Object.values(this.ledger.runtime.getSnapshot().attempts)
317
+ .filter((attempt) => attempt.agentId === agentId)
318
+ .sort((left, right) => left.createdAt.localeCompare(right.createdAt))
319
+ .at(-1);
320
+ }
205
321
  getTaskRuntimeSnapshot() {
206
322
  return this.ledger.runtime.getSnapshot();
207
323
  }
@@ -237,6 +353,10 @@ export class WorkerLifecycle {
237
353
  getActiveAttempt(laneId) {
238
354
  return selectedWorkerAttempt(this.ledger.runtime.getSnapshot(), laneId);
239
355
  }
356
+ getAttemptUsage(laneId) {
357
+ const attempt = this.getActiveAttempt(laneId);
358
+ return attempt ? this.ledger.getAttemptUsage(attempt.attemptId) : undefined;
359
+ }
240
360
  getRunningCount(profileId) {
241
361
  const snapshot = this.ledger.runtime.getSnapshot();
242
362
  return Object.keys(snapshot.tasks).fil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SAC5B,CAAC,CAAC;QACH,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;QACzC,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,CACvB,OAAO,CAAC,SAAS,EACjB,UAAU,EACV,WAAW,OAAO,CAAC,QAAQ,CAAC,aAAa,IAAI,OAAO,CAAC,MAAM,EAAE,CAC7D,CAAC;IAAA,CACF;CACD","sourcesContent":["import type { LaneRecord } from \"../autonomy/lane-tracker.ts\";\nimport type { GoalState } from \"../goals/goal-state.ts\";\nimport type { ExecutionGrant, WorkerExecutionContract, WorkerResultContract } from \"../orchestration/contracts.ts\";\nimport {\n\tDelegationOrchestrationLedger,\n\ttype PrepareDelegationInput,\n\ttype PrepareManagedDelegationInput,\n\ttype StartedDelegationAttempt,\n} from \"../orchestration/delegation-ledger.ts\";\nimport type { AttemptRuntimeState, TaskRuntimeProjection } from \"../orchestration/task-runtime.ts\";\nimport { verifierWorkerExecutionContract } from \"../orchestration/worker-execution-contract.ts\";\nimport {\n\tACTIVE_WORKER_ATTEMPT_STATUSES,\n\tisManagedWorkerAttempt,\n\tprojectManagedWorkerLaneRecords,\n\tprojectWorkerLaneRecord,\n\tselectedManagedWorkerAttempt,\n\tselectedWorkerAttempt,\n} from \"./worker-lane-projection.ts\";\n\nexport type PendingVerificationRecovery =\n\t| {\n\t\t\taction: \"dispatch\";\n\t\t\tsubjectTaskId: string;\n\t\t\timplementationProfileId: string;\n\t\t\tsummary: string;\n\t\t\tartifactUris: readonly string[];\n\t\t\tverifierExecutionContract?: WorkerExecutionContract;\n\t }\n\t| {\n\t\t\taction: \"reconcile\";\n\t\t\tsubjectTaskId: string;\n\t\t\tverifierTaskId: string;\n\t\t\tverifierAttemptId: string;\n\t\t\tverdict: \"accepted\" | \"rejected\" | \"inconclusive\";\n\t\t\treasonCode: string;\n\t };\n\n/**\n * Sole owner of in-process worker lifecycle state. LaneRecord is a compatibility/UI projection;\n * all transitions are committed through DurableTaskRuntime before the projection is returned.\n */\nexport class WorkerLifecycle {\n\treadonly ledger: DelegationOrchestrationLedger;\n\tprivate nextLaneNumber: number;\n\n\tconstructor(options: { agentDir: string; sessionId: string }) {\n\t\tthis.ledger = new DelegationOrchestrationLedger(options);\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\tconst highest = Object.keys(snapshot.tasks).reduce((current, taskId) => {\n\t\t\tconst suffix = /^worker-(\\d+)$/.exec(taskId)?.[1];\n\t\t\treturn suffix ? Math.max(current, Number(suffix)) : current;\n\t\t}, 0);\n\t\tthis.nextLaneNumber = highest + 1;\n\t}\n\n\tprepare(\n\t\tinput: Omit<PrepareDelegationInput, \"laneId\">,\n\t\tlaneId?: string,\n\t): {\n\t\trecord: LaneRecord;\n\t\tattempt: AttemptRuntimeState;\n\t} {\n\t\tlet selectedLaneId = laneId;\n\t\tif (!selectedLaneId) {\n\t\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\t\twhile (snapshot.tasks[`worker-${this.nextLaneNumber}`]) this.nextLaneNumber += 1;\n\t\t\tselectedLaneId = `worker-${this.nextLaneNumber++}`;\n\t\t}\n\t\tconst attempt = this.ledger.prepare({ ...input, laneId: selectedLaneId });\n\t\tconst record = this.getRecord(selectedLaneId);\n\t\tif (!record) throw new Error(`Durable worker '${selectedLaneId}' was not projected after enqueue.`);\n\t\treturn { record, attempt };\n\t}\n\n\tprepareManaged(\n\t\tinput: PrepareManagedDelegationInput & {\n\t\t\tleaseTtlMs: number;\n\t\t\tcompileGrant(target: { objectiveId: string; taskId: string; attemptId: string }): ExecutionGrant;\n\t\t},\n\t): {\n\t\trecord: LaneRecord;\n\t\tattempt: AttemptRuntimeState;\n\t\thandle: StartedDelegationAttempt;\n\t\tcreated: boolean;\n\t} {\n\t\tconst before = selectedManagedWorkerAttempt(this.ledger.runtime.getSnapshot(), input.laneId);\n\t\tif (before?.dispatch.dispatchSequence === input.dispatchSequence) {\n\t\t\tif (\n\t\t\t\tbefore.dispatch.provider !== \"legacy\" &&\n\t\t\t\t(before.dispatch.instructions !== input.instructions ||\n\t\t\t\t\tbefore.dispatch.profileId !== input.profileId ||\n\t\t\t\t\tbefore.dispatch.provider !== input.provider ||\n\t\t\t\t\tbefore.dispatch.worktreeLaneKey !== input.worktreeLaneKey ||\n\t\t\t\t\tbefore.dispatch.authorizationId !== input.authorizationId)\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Managed worker '${input.laneId}' turn ${input.dispatchSequence} was re-reported with conflicting dispatch data.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (before.status === \"queued\") {\n\t\t\t\tconst handle = this.startPreparedManagedAttempt(before, input.leaseTtlMs, input.compileGrant);\n\t\t\t\tconst record = this.getManagedRecord(input.laneId);\n\t\t\t\tif (!record) throw new Error(`Managed worker '${input.laneId}' was not projected.`);\n\t\t\t\treturn {\n\t\t\t\t\trecord,\n\t\t\t\t\tattempt: this.ledger.runtime.getSnapshot().attempts[before.attemptId]!,\n\t\t\t\t\thandle,\n\t\t\t\t\tcreated: true,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst record = this.getManagedRecord(input.laneId);\n\t\t\tif (!record) throw new Error(`Managed worker '${input.laneId}' was not projected.`);\n\t\t\tif (!before.lease) throw new Error(`Managed worker '${input.laneId}' has no durable lease.`);\n\t\t\treturn {\n\t\t\t\trecord,\n\t\t\t\tattempt: before,\n\t\t\t\thandle: this.startedHandle(before),\n\t\t\t\tcreated: false,\n\t\t\t};\n\t\t}\n\t\tif (before && ACTIVE_WORKER_ATTEMPT_STATUSES.has(before.status)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Managed worker '${input.laneId}' cannot dispatch turn ${input.dispatchSequence} while turn ${before.dispatch.dispatchSequence ?? 1} is active.`,\n\t\t\t);\n\t\t}\n\t\tconst attempt = this.ledger.prepareManaged(input);\n\t\tconst handle = this.startPreparedManagedAttempt(attempt, input.leaseTtlMs, input.compileGrant);\n\t\tconst record = this.getManagedRecord(input.laneId);\n\t\tif (!record) throw new Error(`Managed worker '${input.laneId}' was not projected after dispatch.`);\n\t\treturn { record, attempt: this.ledger.runtime.getSnapshot().attempts[attempt.attemptId]!, handle, created: true };\n\t}\n\n\tsynchronizeGoalState(goal: GoalState): LaneRecord[] {\n\t\tconst before = new Map(this.getRecords().map((record) => [record.laneId, record.status]));\n\t\tthis.ledger.synchronizeGoalState(goal);\n\t\treturn this.getRecords().filter((record) => {\n\t\t\tconst previous = before.get(record.laneId);\n\t\t\treturn (\n\t\t\t\t(previous === \"queued\" || previous === \"running\") &&\n\t\t\t\trecord.status !== \"queued\" &&\n\t\t\t\trecord.status !== \"running\"\n\t\t\t);\n\t\t});\n\t}\n\n\tstart(laneId: string, leaseTtlMs: number): StartedDelegationAttempt {\n\t\tconst attempt = this.requireActiveAttempt(laneId);\n\t\treturn this.ledger.start(attempt.attemptId, leaseTtlMs);\n\t}\n\n\tbindGrant(attemptId: string, grant: ExecutionGrant): void {\n\t\tthis.ledger.runtime.bindAttemptGrant(attemptId, grant);\n\t}\n\n\tfinish(result: WorkerResultContract, options: { notify?: boolean } = {}): LaneRecord {\n\t\tthis.ledger.runtime.finishAttempt(result);\n\t\tconst record = this.getRecord(result.taskId);\n\t\tif (!record) throw new Error(`Durable worker '${result.taskId}' was not projected after completion.`);\n\t\tif (options.notify !== false) this.enqueueTerminalNotification(record);\n\t\treturn record;\n\t}\n\n\treconcileVerification(args: {\n\t\tsubjectTaskId: string;\n\t\tverifierTaskId: string;\n\t\tverifierAttemptId: string;\n\t\tverdict: \"accepted\" | \"rejected\" | \"inconclusive\";\n\t\treasonCode: string;\n\t}): LaneRecord {\n\t\tthis.ledger.runtime.finishVerification({\n\t\t\ttaskId: args.subjectTaskId,\n\t\t\tverifierTaskId: args.verifierTaskId,\n\t\t\tverifierAttemptId: args.verifierAttemptId,\n\t\t\tverdict: args.verdict,\n\t\t\treasonCode: args.reasonCode,\n\t\t});\n\t\tconst subject = this.getRecord(args.subjectTaskId);\n\t\tif (!subject) throw new Error(`Verified worker '${args.subjectTaskId}' was not projected.`);\n\t\tthis.enqueueTerminalNotification(subject);\n\t\treturn subject;\n\t}\n\n\tcancel(laneId: string, reasonCode: string): LaneRecord | undefined {\n\t\tconst attempt = this.getActiveAttempt(laneId);\n\t\tif (!attempt) return this.getRecord(laneId);\n\t\tthis.ledger.cancel(attempt.attemptId, reasonCode);\n\t\tconst record = this.getRecord(laneId);\n\t\tif (record) this.enqueueTerminalNotification(record);\n\t\treturn record;\n\t}\n\n\trecoverQueued(): Array<{\n\t\trecord: LaneRecord;\n\t\tattempt: AttemptRuntimeState;\n\t\tverificationOfTaskId?: string;\n\t}> {\n\t\treturn this.ledger.recoverQueuedDispatches().flatMap((attempt) => {\n\t\t\tif (isManagedWorkerAttempt(attempt)) return [];\n\t\t\tconst record = this.getRecord(attempt.taskId);\n\t\t\tconst task = this.ledger.runtime.getSnapshot().tasks[attempt.taskId]?.task;\n\t\t\treturn record\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trecord,\n\t\t\t\t\t\t\tattempt,\n\t\t\t\t\t\t\t...(task?.verificationOfTaskId ? { verificationOfTaskId: task.verificationOfTaskId } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: [];\n\t\t});\n\t}\n\n\t/** Close crash windows between implementation completion, verifier dispatch, and reconciliation. */\n\tgetPendingVerificationRecoveries(): PendingVerificationRecovery[] {\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\treturn Object.values(snapshot.tasks).flatMap<PendingVerificationRecovery>((subject) => {\n\t\t\tif (subject.verification) return [];\n\t\t\tconst implementationAttempt = selectedWorkerAttempt(snapshot, subject.task.taskId);\n\t\t\tif (implementationAttempt?.result?.nextAction !== \"independent_verification_required\") return [];\n\t\t\tconst verifier = Object.values(snapshot.tasks)\n\t\t\t\t.filter((candidate) => candidate.task.verificationOfTaskId === subject.task.taskId)\n\t\t\t\t.sort((left, right) => left.task.createdAt.localeCompare(right.task.createdAt))\n\t\t\t\t.at(-1);\n\t\t\tif (!verifier) {\n\t\t\t\tconst verifierExecutionContract = implementationAttempt.dispatch.executionContract\n\t\t\t\t\t? verifierWorkerExecutionContract(implementationAttempt.dispatch.executionContract)\n\t\t\t\t\t: undefined;\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\taction: \"dispatch\" as const,\n\t\t\t\t\t\tsubjectTaskId: subject.task.taskId,\n\t\t\t\t\t\timplementationProfileId: implementationAttempt.dispatch.profileId,\n\t\t\t\t\t\tsummary: implementationAttempt.result.summary,\n\t\t\t\t\t\tartifactUris: implementationAttempt.result.artifacts.map((artifact) => artifact.uri),\n\t\t\t\t\t\t...(verifierExecutionContract ? { verifierExecutionContract } : {}),\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\t}\n\t\t\tconst verifierAttempt = selectedWorkerAttempt(snapshot, verifier.task.taskId);\n\t\t\tif (!verifierAttempt || ACTIVE_WORKER_ATTEMPT_STATUSES.has(verifierAttempt.status)) return [];\n\t\t\tconst review = verifierAttempt.result?.evidence.find(\n\t\t\t\t(evidence) => evidence.kind === \"review\" && evidence.metadata?.subjectTaskId === subject.task.taskId,\n\t\t\t);\n\t\t\tconst verdictValue = review?.metadata?.verdict;\n\t\t\tconst verdict =\n\t\t\t\treview?.trusted && (verdictValue === \"accepted\" || verdictValue === \"rejected\")\n\t\t\t\t\t? verdictValue\n\t\t\t\t\t: \"inconclusive\";\n\t\t\tconst reasonCodesValue = review?.metadata?.reasonCodes;\n\t\t\tconst reasonCodes = Array.isArray(reasonCodesValue)\n\t\t\t\t? reasonCodesValue.filter((reasonCode): reasonCode is string => typeof reasonCode === \"string\")\n\t\t\t\t: [];\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\taction: \"reconcile\" as const,\n\t\t\t\t\tsubjectTaskId: subject.task.taskId,\n\t\t\t\t\tverifierTaskId: verifier.task.taskId,\n\t\t\t\t\tverifierAttemptId: verifierAttempt.attemptId,\n\t\t\t\t\tverdict,\n\t\t\t\t\treasonCode:\n\t\t\t\t\t\tverdict === \"accepted\"\n\t\t\t\t\t\t\t? \"independent_verification_accepted\"\n\t\t\t\t\t\t\t: verdict === \"rejected\"\n\t\t\t\t\t\t\t\t? `independent_verification_rejected:${reasonCodes.join(\",\") || \"unspecified\"}`\n\t\t\t\t\t\t\t\t: `independent_verification_inconclusive:${verifierAttempt.reasonCode ?? verifierAttempt.result?.reasonCode ?? \"interrupted\"}`,\n\t\t\t\t},\n\t\t\t];\n\t\t});\n\t}\n\n\tgetTask(taskId: string): TaskRuntimeProjection[\"tasks\"][string] | undefined {\n\t\treturn this.ledger.runtime.getSnapshot().tasks[taskId];\n\t}\n\n\tgetTaskRuntimeSnapshot(): TaskRuntimeProjection {\n\t\treturn this.ledger.runtime.getSnapshot();\n\t}\n\n\tgetRecords(): LaneRecord[] {\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\treturn Object.keys(snapshot.tasks).flatMap((taskId) => {\n\t\t\tconst attempt = selectedWorkerAttempt(snapshot, taskId);\n\t\t\tif (!attempt || isManagedWorkerAttempt(attempt)) return [];\n\t\t\tconst record = projectWorkerLaneRecord(snapshot, taskId);\n\t\t\treturn record ? [record] : [];\n\t\t});\n\t}\n\n\tgetManagedRecords(): LaneRecord[] {\n\t\treturn projectManagedWorkerLaneRecords(this.ledger.runtime.getSnapshot());\n\t}\n\n\tgetAllRecords(): LaneRecord[] {\n\t\treturn [...this.getRecords(), ...this.getManagedRecords()];\n\t}\n\n\tgetRecord(laneId: string): LaneRecord | undefined {\n\t\treturn projectWorkerLaneRecord(this.ledger.runtime.getSnapshot(), laneId);\n\t}\n\n\tgetManagedRecord(laneId: string): LaneRecord | undefined {\n\t\treturn this.getManagedRecords().find((record) => record.laneId === laneId);\n\t}\n\n\tgetManagedAttempt(laneId: string): AttemptRuntimeState | undefined {\n\t\treturn selectedManagedWorkerAttempt(this.ledger.runtime.getSnapshot(), laneId);\n\t}\n\n\tgetManagedHandle(laneId: string): StartedDelegationAttempt | undefined {\n\t\tconst attempt = this.getManagedAttempt(laneId);\n\t\treturn attempt?.lease ? this.startedHandle(attempt) : undefined;\n\t}\n\n\tgetActiveAttempt(laneId: string): AttemptRuntimeState | undefined {\n\t\treturn selectedWorkerAttempt(this.ledger.runtime.getSnapshot(), laneId);\n\t}\n\n\tgetRunningCount(profileId?: string): number {\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\treturn Object.keys(snapshot.tasks).filter((taskId) => {\n\t\t\tconst attempt = selectedWorkerAttempt(snapshot, taskId);\n\t\t\treturn (\n\t\t\t\tattempt?.status === \"running\" &&\n\t\t\t\t!isManagedWorkerAttempt(attempt) &&\n\t\t\t\t(!profileId || attempt.dispatch.profileId === profileId)\n\t\t\t);\n\t\t}).length;\n\t}\n\n\tgetPendingTerminalNotifications(): Array<{ notificationId: string; record: LaneRecord }> {\n\t\tthis.ensureTerminalNotifications();\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\treturn Object.values(snapshot.notifications).flatMap((notification) => {\n\t\t\tif (notification.status !== \"pending\" || !notification.attemptId) return [];\n\t\t\tconst attempt = snapshot.attempts[notification.attemptId];\n\t\t\tif (!attempt) return [];\n\t\t\tconst record = projectWorkerLaneRecord(snapshot, attempt.taskId);\n\t\t\tif (!record || record.status === \"queued\" || record.status === \"running\") return [];\n\t\t\treturn [{ notificationId: notification.notificationId, record }];\n\t\t});\n\t}\n\n\tgetTerminalNotification(\n\t\tlaneId: string,\n\t): { notificationId: string; status: \"pending\" | \"delivered\"; record: LaneRecord } | undefined {\n\t\tconst record = this.getRecord(laneId) ?? this.getManagedRecord(laneId);\n\t\tif (!record || record.status === \"queued\" || record.status === \"running\") return undefined;\n\t\tthis.enqueueTerminalNotification(record);\n\t\tconst attempt = this.getActiveAttempt(laneId) ?? this.getManagedAttempt(laneId);\n\t\tif (!attempt) return undefined;\n\t\tconst notificationId = `worker-terminal:${attempt.attemptId}`;\n\t\tconst notification = this.ledger.runtime.getSnapshot().notifications[notificationId];\n\t\treturn notification ? { notificationId, status: notification.status, record } : undefined;\n\t}\n\n\tmarkNotificationsDelivered(notificationIds: readonly string[]): void {\n\t\tfor (const notificationId of notificationIds) this.ledger.runtime.markNotificationDelivered(notificationId);\n\t}\n\n\tprivate ensureTerminalNotifications(): void {\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\tfor (const taskId of Object.keys(snapshot.tasks)) {\n\t\t\tconst record = projectWorkerLaneRecord(snapshot, taskId);\n\t\t\tif (record && record.status !== \"queued\" && record.status !== \"running\") {\n\t\t\t\tthis.enqueueTerminalNotification(record);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate enqueueTerminalNotification(record: LaneRecord): void {\n\t\tconst attempt = this.getActiveAttempt(record.laneId) ?? this.getManagedAttempt(record.laneId);\n\t\tif (!attempt || ACTIVE_WORKER_ATTEMPT_STATUSES.has(attempt.status)) return;\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\tconst task = snapshot.tasks[attempt.taskId];\n\t\tif (!task) return;\n\t\tif (attempt.result?.nextAction === \"independent_verification_required\" && !task.verification) return;\n\t\tthis.ledger.runtime.enqueueNotification({\n\t\t\tnotificationId: `worker-terminal:${attempt.attemptId}`,\n\t\t\tobjectiveId: task.task.objectiveId,\n\t\t\tattemptId: attempt.attemptId,\n\t\t\tmessage: `Worker ${record.laneId} reached ${record.status}.`,\n\t\t});\n\t}\n\n\tprivate requireActiveAttempt(laneId: string): AttemptRuntimeState {\n\t\tconst attempt = this.getActiveAttempt(laneId);\n\t\tif (!attempt || !ACTIVE_WORKER_ATTEMPT_STATUSES.has(attempt.status)) {\n\t\t\tthrow new Error(`Durable worker '${laneId}' has no active attempt.`);\n\t\t}\n\t\treturn attempt;\n\t}\n\n\tprivate startedHandle(attempt: AttemptRuntimeState): StartedDelegationAttempt {\n\t\tconst task = this.ledger.runtime.getSnapshot().tasks[attempt.taskId];\n\t\tif (!task || !attempt.lease) throw new Error(`Attempt '${attempt.attemptId}' has no started handle.`);\n\t\treturn {\n\t\t\tobjectiveId: task.task.objectiveId,\n\t\t\ttaskId: task.task.taskId,\n\t\t\tattemptId: attempt.attemptId,\n\t\t\tleaseId: attempt.lease.leaseId,\n\t\t\tfencingToken: attempt.lease.fencingToken,\n\t\t\texpiresAt: attempt.lease.expiresAt,\n\t\t};\n\t}\n\n\tprivate startPreparedManagedAttempt(\n\t\tattempt: AttemptRuntimeState,\n\t\tleaseTtlMs: number,\n\t\tcompileGrant: (target: { objectiveId: string; taskId: string; attemptId: string }) => ExecutionGrant,\n\t): StartedDelegationAttempt {\n\t\tconst task = this.ledger.runtime.getSnapshot().tasks[attempt.taskId];\n\t\tif (!task) throw new Error(`Managed attempt '${attempt.attemptId}' has no durable task.`);\n\t\tconst grant = compileGrant({\n\t\t\tobjectiveId: task.task.objectiveId,\n\t\t\ttaskId: task.task.taskId,\n\t\t\tattemptId: attempt.attemptId,\n\t\t});\n\t\tthis.bindGrant(attempt.attemptId, grant);\n\t\treturn this.ledger.start(\n\t\t\tattempt.attemptId,\n\t\t\tleaseTtlMs,\n\t\t\t`managed:${attempt.dispatch.logicalLaneId ?? attempt.taskId}`,\n\t\t);\n\t}\n}\n"]}
1
+ {"version":3,"file":"worker-lifecycle.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-lifecycle.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,uBAAuB,EAAE,MAAM,kCAAkC,CAAC;AAU3E,OAAO,EACN,6BAA6B,GAI7B,MAAM,uCAAuC,CAAC;AAE/C,OAAO,EAAE,+BAA+B,EAAE,MAAM,+CAA+C,CAAC;AAChG,OAAO,EACN,8BAA8B,EAC9B,sBAAsB,EACtB,+BAA+B,EAC/B,uBAAuB,EACvB,4BAA4B,EAC5B,qBAAqB,GACrB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,mBAAmB,EAAE,mCAAmC,EAAE,MAAM,2BAA2B,CAAC;AAoBrG;;;GAGG;AACH,MAAM,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,CAAC,SAAS;SAClC,CAAC;IAAA,CACF;IAEO,2BAA2B,CAClC,OAA4B,EAC5B,UAAkB,EAClB,YAAoG,EACzE;QAC3B,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACrE,IAAI,CAAC,IAAI;YAAE,MAAM,IAAI,KAAK,CAAC,oBAAoB,OAAO,CAAC,SAAS,wBAAwB,CAAC,CAAC;QAC1F,MAAM,KAAK,GAAG,YAAY,CAAC;YAC1B,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,WAAW;YAClC,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,MAAM;YACxB,SAAS,EAAE,OAAO,CAAC,SAAS;SAC5B,CAAC,CAAC;QACH,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;QACzC,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,CACvB,OAAO,CAAC,SAAS,EACjB,UAAU,EACV,WAAW,OAAO,CAAC,QAAQ,CAAC,aAAa,IAAI,OAAO,CAAC,MAAM,EAAE,CAC7D,CAAC;IAAA,CACF;CACD","sourcesContent":["import type { LaneRecord } from \"../autonomy/lane-tracker.ts\";\nimport type { GoalState } from \"../goals/goal-state.ts\";\nimport { sameAgentResumeIdentity } from \"../orchestration/agent-resume.ts\";\nimport type {\n\tAgentBindingContract,\n\tAgentResumeContext,\n\tAttemptUsageSnapshot,\n\tExecutionGrant,\n\tWorkerExecutionContract,\n\tWorkerResultContract,\n\tWorkerRole,\n} from \"../orchestration/contracts.ts\";\nimport {\n\tDelegationOrchestrationLedger,\n\ttype PrepareDelegationInput,\n\ttype PrepareManagedDelegationInput,\n\ttype StartedDelegationAttempt,\n} from \"../orchestration/delegation-ledger.ts\";\nimport type { AttemptRuntimeState, TaskRuntimeProjection } from \"../orchestration/task-runtime.ts\";\nimport { verifierWorkerExecutionContract } from \"../orchestration/worker-execution-contract.ts\";\nimport {\n\tACTIVE_WORKER_ATTEMPT_STATUSES,\n\tisManagedWorkerAttempt,\n\tprojectManagedWorkerLaneRecords,\n\tprojectWorkerLaneRecord,\n\tselectedManagedWorkerAttempt,\n\tselectedWorkerAttempt,\n} from \"./worker-lane-projection.ts\";\nimport { isLocalProcessAlive, isLocalWorkerProcessOwnerProvenDead } from \"./worker-process-owner.ts\";\n\nexport type PendingVerificationRecovery =\n\t| {\n\t\t\taction: \"dispatch\";\n\t\t\tsubjectTaskId: string;\n\t\t\timplementationProfileId: string;\n\t\t\tsummary: string;\n\t\t\tartifactUris: readonly string[];\n\t\t\tverifierExecutionContract?: WorkerExecutionContract;\n\t }\n\t| {\n\t\t\taction: \"reconcile\";\n\t\t\tsubjectTaskId: string;\n\t\t\tverifierTaskId: string;\n\t\t\tverifierAttemptId: string;\n\t\t\tverdict: \"accepted\" | \"rejected\" | \"inconclusive\";\n\t\t\treasonCode: string;\n\t };\n\n/**\n * Sole owner of in-process worker lifecycle state. LaneRecord is a compatibility/UI projection;\n * all transitions are committed through DurableTaskRuntime before the projection is returned.\n */\nexport class WorkerLifecycle {\n\treadonly ledger: DelegationOrchestrationLedger;\n\tprivate nextLaneNumber: number;\n\tprivate readonly isProcessAlive: (pid: number) => boolean;\n\n\tconstructor(options: { agentDir: string; sessionId: string; isProcessAlive?: (pid: number) => boolean }) {\n\t\tthis.ledger = new DelegationOrchestrationLedger(options);\n\t\tthis.isProcessAlive = options.isProcessAlive ?? isLocalProcessAlive;\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\tconst highest = Object.keys(snapshot.tasks).reduce((current, taskId) => {\n\t\t\tconst suffix = /^worker-(\\d+)$/.exec(taskId)?.[1];\n\t\t\treturn suffix ? Math.max(current, Number(suffix)) : current;\n\t\t}, 0);\n\t\tthis.nextLaneNumber = highest + 1;\n\t}\n\n\tprepare(\n\t\tinput: Omit<PrepareDelegationInput, \"laneId\">,\n\t\tlaneId?: string,\n\t): {\n\t\trecord: LaneRecord;\n\t\tattempt: AttemptRuntimeState;\n\t} {\n\t\tlet selectedLaneId = laneId;\n\t\tif (!selectedLaneId) {\n\t\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\t\twhile (snapshot.tasks[`worker-${this.nextLaneNumber}`]) this.nextLaneNumber += 1;\n\t\t\tselectedLaneId = `worker-${this.nextLaneNumber++}`;\n\t\t}\n\t\tconst attempt = this.ledger.prepare({ ...input, laneId: selectedLaneId });\n\t\tconst record = this.getRecord(selectedLaneId);\n\t\tif (!record) throw new Error(`Durable worker '${selectedLaneId}' was not projected after enqueue.`);\n\t\treturn { record, attempt };\n\t}\n\n\t/** Queue the next distinct task/attempt for an idle logical agent. */\n\tprepareAgentTurn(input: { agentId: string; instructions: string }): {\n\t\trecord: LaneRecord;\n\t\tattempt: AttemptRuntimeState;\n\t} {\n\t\tconst attempt = this.ledger.prepareAgentTurn(input);\n\t\tconst record = this.getRecord(attempt.taskId);\n\t\tif (!record) throw new Error(`Logical worker '${input.agentId}' turn was not projected after enqueue.`);\n\t\treturn { record, attempt };\n\t}\n\n\tensureAgent(input: { agentId: string; role: WorkerRole; resumeContext: AgentResumeContext }): AgentBindingContract {\n\t\tconst agentId = input.agentId.trim();\n\t\tconst existing = this.ledger.runtime.getSnapshot().agents[agentId];\n\t\tif (!existing) return this.ledger.runtime.registerAgent(input);\n\t\tif (existing.role !== input.role || !sameAgentResumeIdentity(existing.resumeContext, input.resumeContext)) {\n\t\t\tthrow new Error(`Agent '${agentId}' was re-registered with conflicting identity.`);\n\t\t}\n\t\treturn existing;\n\t}\n\n\tprepareManaged(\n\t\tinput: PrepareManagedDelegationInput & {\n\t\t\tleaseTtlMs: number;\n\t\t\tcompileGrant(target: { objectiveId: string; taskId: string; attemptId: string }): ExecutionGrant;\n\t\t},\n\t): {\n\t\trecord: LaneRecord;\n\t\tattempt: AttemptRuntimeState;\n\t\thandle: StartedDelegationAttempt;\n\t\tcreated: boolean;\n\t} {\n\t\tconst before = selectedManagedWorkerAttempt(this.ledger.runtime.getSnapshot(), input.laneId);\n\t\tif (before?.dispatch.dispatchSequence === input.dispatchSequence) {\n\t\t\tif (\n\t\t\t\tbefore.dispatch.provider !== \"legacy\" &&\n\t\t\t\t(before.dispatch.instructions !== input.instructions ||\n\t\t\t\t\tbefore.dispatch.profileId !== input.profileId ||\n\t\t\t\t\tbefore.dispatch.provider !== input.provider ||\n\t\t\t\t\tbefore.dispatch.worktreeLaneKey !== input.worktreeLaneKey ||\n\t\t\t\t\tbefore.dispatch.authorizationId !== input.authorizationId)\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Managed worker '${input.laneId}' turn ${input.dispatchSequence} was re-reported with conflicting dispatch data.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (before.status === \"queued\") {\n\t\t\t\tconst handle = this.startPreparedManagedAttempt(before, input.leaseTtlMs, input.compileGrant);\n\t\t\t\tconst record = this.getManagedRecord(input.laneId);\n\t\t\t\tif (!record) throw new Error(`Managed worker '${input.laneId}' was not projected.`);\n\t\t\t\treturn {\n\t\t\t\t\trecord,\n\t\t\t\t\tattempt: this.ledger.runtime.getSnapshot().attempts[before.attemptId]!,\n\t\t\t\t\thandle,\n\t\t\t\t\tcreated: true,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst record = this.getManagedRecord(input.laneId);\n\t\t\tif (!record) throw new Error(`Managed worker '${input.laneId}' was not projected.`);\n\t\t\tif (!before.lease) throw new Error(`Managed worker '${input.laneId}' has no durable lease.`);\n\t\t\treturn {\n\t\t\t\trecord,\n\t\t\t\tattempt: before,\n\t\t\t\thandle: this.startedHandle(before),\n\t\t\t\tcreated: false,\n\t\t\t};\n\t\t}\n\t\tif (before && ACTIVE_WORKER_ATTEMPT_STATUSES.has(before.status)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Managed worker '${input.laneId}' cannot dispatch turn ${input.dispatchSequence} while turn ${before.dispatch.dispatchSequence ?? 1} is active.`,\n\t\t\t);\n\t\t}\n\t\tconst attempt = this.ledger.prepareManaged(input);\n\t\tconst handle = this.startPreparedManagedAttempt(attempt, input.leaseTtlMs, input.compileGrant);\n\t\tconst record = this.getManagedRecord(input.laneId);\n\t\tif (!record) throw new Error(`Managed worker '${input.laneId}' was not projected after dispatch.`);\n\t\treturn { record, attempt: this.ledger.runtime.getSnapshot().attempts[attempt.attemptId]!, handle, created: true };\n\t}\n\n\tsynchronizeGoalState(goal: GoalState): LaneRecord[] {\n\t\tconst before = new Map(this.getRecords().map((record) => [record.laneId, record.status]));\n\t\tthis.ledger.synchronizeGoalState(goal);\n\t\treturn this.getRecords().filter((record) => {\n\t\t\tconst previous = before.get(record.laneId);\n\t\t\treturn (\n\t\t\t\t(previous === \"queued\" || previous === \"running\") &&\n\t\t\t\trecord.status !== \"queued\" &&\n\t\t\t\trecord.status !== \"running\"\n\t\t\t);\n\t\t});\n\t}\n\n\tstart(laneId: string, leaseTtlMs: number): StartedDelegationAttempt {\n\t\tconst attempt = this.requireActiveAttempt(laneId);\n\t\treturn this.ledger.start(attempt.attemptId, leaseTtlMs);\n\t}\n\n\tstartAgent(laneId: string, agentId: string, leaseTtlMs: number, ownerId = agentId): StartedDelegationAttempt {\n\t\tconst attempt = this.requireActiveAttempt(laneId);\n\t\treturn this.ledger.start(attempt.attemptId, leaseTtlMs, ownerId, agentId);\n\t}\n\n\tcheckpoint(\n\t\tlaneId: string,\n\t\tinput: {\n\t\t\tsummary: string;\n\t\t\tartifactIds?: readonly string[];\n\t\t\tevidenceIds?: readonly string[];\n\t\t\tusage?: AttemptUsageSnapshot;\n\t\t},\n\t) {\n\t\tconst attempt = this.requireActiveAttempt(laneId);\n\t\tif (!attempt.lease) throw new Error(`Durable worker '${laneId}' has no live lease.`);\n\t\treturn this.ledger.runtime.checkpointAttempt({\n\t\t\tattemptId: attempt.attemptId,\n\t\t\tleaseId: attempt.lease.leaseId,\n\t\t\tfencingToken: attempt.lease.fencingToken,\n\t\t\tsummary: input.summary,\n\t\t\t...(input.artifactIds ? { artifactIds: input.artifactIds } : {}),\n\t\t\t...(input.evidenceIds ? { evidenceIds: input.evidenceIds } : {}),\n\t\t\t...(input.usage ? { usage: input.usage } : {}),\n\t\t});\n\t}\n\n\t/**\n\t * Suspend only attempts whose exact controller owner is known (explicit shutdown) or whose\n\t * recorded local owner PID is proven gone (recovery). A live/unknown owner is never stolen.\n\t */\n\tsuspendBoundInProcessAttemptsForRestart(ownerId?: string): string[] {\n\t\tconst suspended: string[] = [];\n\t\tfor (const attempt of Object.values(this.ledger.runtime.getSnapshot().attempts)) {\n\t\t\tif (\n\t\t\t\t(attempt.status !== \"leased\" && attempt.status !== \"running\") ||\n\t\t\t\t!attempt.agentId ||\n\t\t\t\tattempt.dispatch.executionKind === \"managed-process\" ||\n\t\t\t\t!attempt.lease\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst ownsAttempt =\n\t\t\t\townerId !== undefined\n\t\t\t\t\t? attempt.lease.ownerId === ownerId\n\t\t\t\t\t: isLocalWorkerProcessOwnerProvenDead(attempt.lease.ownerId, this.isProcessAlive);\n\t\t\tif (!ownsAttempt) continue;\n\t\t\tthis.suspendBoundAttempt({\n\t\t\t\tlaneId: attempt.taskId,\n\t\t\t\townerId: attempt.lease.ownerId,\n\t\t\t\tleaseId: attempt.lease.leaseId,\n\t\t\t\tfencingToken: attempt.lease.fencingToken,\n\t\t\t\treasonCode:\n\t\t\t\t\townerId === undefined ? \"agent_process_recovered_after_owner_exit\" : \"agent_process_interrupted\",\n\t\t\t});\n\t\t\tsuspended.push(attempt.attemptId);\n\t\t}\n\t\treturn suspended;\n\t}\n\n\t/**\n\t * Applies an explicitly authorized restart suspension. The caller must identify both the logical\n\t * lane and the current lease fence; process liveness policy is intentionally kept by this class.\n\t */\n\tsuspendBoundAttempt(args: {\n\t\tlaneId: string;\n\t\townerId: string;\n\t\tleaseId: string;\n\t\tfencingToken: number;\n\t\treasonCode: string;\n\t}): void {\n\t\tconst attempt = this.getActiveAttempt(args.laneId);\n\t\tif (!attempt || !attempt.agentId || !attempt.lease) {\n\t\t\tthrow new Error(`Durable worker '${args.laneId}' has no live agent-bound attempt for suspension.`);\n\t\t}\n\t\tthis.ledger.runtime.suspendBoundAttempt({\n\t\t\tattemptId: attempt.attemptId,\n\t\t\townerId: args.ownerId,\n\t\t\tleaseId: args.leaseId,\n\t\t\tfencingToken: args.fencingToken,\n\t\t\treasonCode: args.reasonCode,\n\t\t});\n\t}\n\n\tresumeAgent(laneId: string, agentId: string, leaseTtlMs: number, ownerId = agentId): StartedDelegationAttempt {\n\t\tconst attempt = this.getActiveAttempt(laneId);\n\t\tif (!attempt) throw new Error(`Durable worker '${laneId}' has no resumable attempt.`);\n\t\tthis.ledger.runtime.requestAgentResume(agentId);\n\t\tconst lease = this.ledger.runtime.resumeAttempt(attempt.attemptId, agentId, leaseTtlMs, ownerId);\n\t\treturn this.startedHandle(this.ledger.runtime.startAttempt(attempt.attemptId, lease.leaseId, lease.fencingToken));\n\t}\n\n\tsuspendAgent(laneId: string, agentId: string, ownerId: string, reasonCode = \"agent_interrupted\"): void {\n\t\tconst attempt = this.getActiveAttempt(laneId);\n\t\tif (!attempt || attempt.agentId !== agentId || !attempt.lease) {\n\t\t\tthrow new Error(`Logical worker '${agentId}' has no live attempt for interruption.`);\n\t\t}\n\t\tthis.suspendBoundAttempt({\n\t\t\tlaneId,\n\t\t\townerId,\n\t\t\tleaseId: attempt.lease.leaseId,\n\t\t\tfencingToken: attempt.lease.fencingToken,\n\t\t\treasonCode,\n\t\t});\n\t}\n\n\tbindGrant(attemptId: string, grant: ExecutionGrant): void {\n\t\tthis.ledger.runtime.bindAttemptGrant(attemptId, grant);\n\t}\n\n\tfinish(result: WorkerResultContract, options: { notify?: boolean } = {}): LaneRecord {\n\t\tthis.ledger.runtime.finishAttempt(result);\n\t\tconst record = this.getRecord(result.taskId);\n\t\tif (!record) throw new Error(`Durable worker '${result.taskId}' was not projected after completion.`);\n\t\tif (options.notify !== false) this.enqueueTerminalNotification(record);\n\t\treturn record;\n\t}\n\n\treconcileVerification(args: {\n\t\tsubjectTaskId: string;\n\t\tverifierTaskId: string;\n\t\tverifierAttemptId: string;\n\t\tverdict: \"accepted\" | \"rejected\" | \"inconclusive\";\n\t\treasonCode: string;\n\t}): LaneRecord {\n\t\tthis.ledger.runtime.finishVerification({\n\t\t\ttaskId: args.subjectTaskId,\n\t\t\tverifierTaskId: args.verifierTaskId,\n\t\t\tverifierAttemptId: args.verifierAttemptId,\n\t\t\tverdict: args.verdict,\n\t\t\treasonCode: args.reasonCode,\n\t\t});\n\t\tconst subject = this.getRecord(args.subjectTaskId);\n\t\tif (!subject) throw new Error(`Verified worker '${args.subjectTaskId}' was not projected.`);\n\t\tthis.enqueueTerminalNotification(subject);\n\t\treturn subject;\n\t}\n\n\tcancel(laneId: string, reasonCode: string): LaneRecord | undefined {\n\t\tconst attempt = this.getActiveAttempt(laneId);\n\t\tif (!attempt) return this.getRecord(laneId);\n\t\tthis.ledger.cancel(attempt.attemptId, reasonCode);\n\t\tconst record = this.getRecord(laneId);\n\t\tif (record) this.enqueueTerminalNotification(record);\n\t\treturn record;\n\t}\n\n\trecoverQueued(): Array<{\n\t\trecord: LaneRecord;\n\t\tattempt: AttemptRuntimeState;\n\t\tverificationOfTaskId?: string;\n\t}> {\n\t\treturn this.ledger.recoverQueuedDispatches().flatMap((attempt) => {\n\t\t\tif (isManagedWorkerAttempt(attempt)) return [];\n\t\t\tconst record = this.getRecord(attempt.taskId);\n\t\t\tconst task = this.ledger.runtime.getSnapshot().tasks[attempt.taskId]?.task;\n\t\t\treturn record\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trecord,\n\t\t\t\t\t\t\tattempt,\n\t\t\t\t\t\t\t...(task?.verificationOfTaskId ? { verificationOfTaskId: task.verificationOfTaskId } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: [];\n\t\t});\n\t}\n\n\t/** Close crash windows between implementation completion, verifier dispatch, and reconciliation. */\n\tgetPendingVerificationRecoveries(): PendingVerificationRecovery[] {\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\treturn Object.values(snapshot.tasks).flatMap<PendingVerificationRecovery>((subject) => {\n\t\t\tif (subject.verification) return [];\n\t\t\tconst implementationAttempt = selectedWorkerAttempt(snapshot, subject.task.taskId);\n\t\t\tif (implementationAttempt?.result?.nextAction !== \"independent_verification_required\") return [];\n\t\t\tconst verifier = Object.values(snapshot.tasks)\n\t\t\t\t.filter((candidate) => candidate.task.verificationOfTaskId === subject.task.taskId)\n\t\t\t\t.sort((left, right) => left.task.createdAt.localeCompare(right.task.createdAt))\n\t\t\t\t.at(-1);\n\t\t\tif (!verifier) {\n\t\t\t\tconst verifierExecutionContract = implementationAttempt.dispatch.executionContract\n\t\t\t\t\t? verifierWorkerExecutionContract(implementationAttempt.dispatch.executionContract)\n\t\t\t\t\t: undefined;\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\taction: \"dispatch\" as const,\n\t\t\t\t\t\tsubjectTaskId: subject.task.taskId,\n\t\t\t\t\t\timplementationProfileId: implementationAttempt.dispatch.profileId,\n\t\t\t\t\t\tsummary: implementationAttempt.result.summary,\n\t\t\t\t\t\tartifactUris: implementationAttempt.result.artifacts.map((artifact) => artifact.uri),\n\t\t\t\t\t\t...(verifierExecutionContract ? { verifierExecutionContract } : {}),\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\t}\n\t\t\tconst verifierAttempt = selectedWorkerAttempt(snapshot, verifier.task.taskId);\n\t\t\tif (!verifierAttempt || ACTIVE_WORKER_ATTEMPT_STATUSES.has(verifierAttempt.status)) return [];\n\t\t\tconst review = verifierAttempt.result?.evidence.find(\n\t\t\t\t(evidence) => evidence.kind === \"review\" && evidence.metadata?.subjectTaskId === subject.task.taskId,\n\t\t\t);\n\t\t\tconst verdictValue = review?.metadata?.verdict;\n\t\t\tconst verdict =\n\t\t\t\treview?.trusted && (verdictValue === \"accepted\" || verdictValue === \"rejected\")\n\t\t\t\t\t? verdictValue\n\t\t\t\t\t: \"inconclusive\";\n\t\t\tconst reasonCodesValue = review?.metadata?.reasonCodes;\n\t\t\tconst reasonCodes = Array.isArray(reasonCodesValue)\n\t\t\t\t? reasonCodesValue.filter((reasonCode): reasonCode is string => typeof reasonCode === \"string\")\n\t\t\t\t: [];\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\taction: \"reconcile\" as const,\n\t\t\t\t\tsubjectTaskId: subject.task.taskId,\n\t\t\t\t\tverifierTaskId: verifier.task.taskId,\n\t\t\t\t\tverifierAttemptId: verifierAttempt.attemptId,\n\t\t\t\t\tverdict,\n\t\t\t\t\treasonCode:\n\t\t\t\t\t\tverdict === \"accepted\"\n\t\t\t\t\t\t\t? \"independent_verification_accepted\"\n\t\t\t\t\t\t\t: verdict === \"rejected\"\n\t\t\t\t\t\t\t\t? `independent_verification_rejected:${reasonCodes.join(\",\") || \"unspecified\"}`\n\t\t\t\t\t\t\t\t: `independent_verification_inconclusive:${verifierAttempt.reasonCode ?? verifierAttempt.result?.reasonCode ?? \"interrupted\"}`,\n\t\t\t\t},\n\t\t\t];\n\t\t});\n\t}\n\n\tgetTask(taskId: string): TaskRuntimeProjection[\"tasks\"][string] | undefined {\n\t\treturn this.ledger.runtime.getSnapshot().tasks[taskId];\n\t}\n\n\tgetAgent(agentId: string): AgentBindingContract | undefined {\n\t\treturn this.ledger.runtime.getSnapshot().agents[agentId];\n\t}\n\n\tgetLatestAgentAttempt(agentId: string): AttemptRuntimeState | undefined {\n\t\treturn Object.values(this.ledger.runtime.getSnapshot().attempts)\n\t\t\t.filter((attempt) => attempt.agentId === agentId)\n\t\t\t.sort((left, right) => left.createdAt.localeCompare(right.createdAt))\n\t\t\t.at(-1);\n\t}\n\n\tgetTaskRuntimeSnapshot(): TaskRuntimeProjection {\n\t\treturn this.ledger.runtime.getSnapshot();\n\t}\n\n\tgetRecords(): LaneRecord[] {\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\treturn Object.keys(snapshot.tasks).flatMap((taskId) => {\n\t\t\tconst attempt = selectedWorkerAttempt(snapshot, taskId);\n\t\t\tif (!attempt || isManagedWorkerAttempt(attempt)) return [];\n\t\t\tconst record = projectWorkerLaneRecord(snapshot, taskId);\n\t\t\treturn record ? [record] : [];\n\t\t});\n\t}\n\n\tgetManagedRecords(): LaneRecord[] {\n\t\treturn projectManagedWorkerLaneRecords(this.ledger.runtime.getSnapshot());\n\t}\n\n\tgetAllRecords(): LaneRecord[] {\n\t\treturn [...this.getRecords(), ...this.getManagedRecords()];\n\t}\n\n\tgetRecord(laneId: string): LaneRecord | undefined {\n\t\treturn projectWorkerLaneRecord(this.ledger.runtime.getSnapshot(), laneId);\n\t}\n\n\tgetManagedRecord(laneId: string): LaneRecord | undefined {\n\t\treturn this.getManagedRecords().find((record) => record.laneId === laneId);\n\t}\n\n\tgetManagedAttempt(laneId: string): AttemptRuntimeState | undefined {\n\t\treturn selectedManagedWorkerAttempt(this.ledger.runtime.getSnapshot(), laneId);\n\t}\n\n\tgetManagedHandle(laneId: string): StartedDelegationAttempt | undefined {\n\t\tconst attempt = this.getManagedAttempt(laneId);\n\t\treturn attempt?.lease ? this.startedHandle(attempt) : undefined;\n\t}\n\n\tgetActiveAttempt(laneId: string): AttemptRuntimeState | undefined {\n\t\treturn selectedWorkerAttempt(this.ledger.runtime.getSnapshot(), laneId);\n\t}\n\n\tgetAttemptUsage(laneId: string): AttemptUsageSnapshot | undefined {\n\t\tconst attempt = this.getActiveAttempt(laneId);\n\t\treturn attempt ? this.ledger.getAttemptUsage(attempt.attemptId) : undefined;\n\t}\n\n\tgetRunningCount(profileId?: string): number {\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\treturn Object.keys(snapshot.tasks).filter((taskId) => {\n\t\t\tconst attempt = selectedWorkerAttempt(snapshot, taskId);\n\t\t\treturn (\n\t\t\t\tattempt?.status === \"running\" &&\n\t\t\t\t!isManagedWorkerAttempt(attempt) &&\n\t\t\t\t(!profileId || attempt.dispatch.profileId === profileId)\n\t\t\t);\n\t\t}).length;\n\t}\n\n\tgetPendingTerminalNotifications(): Array<{ notificationId: string; record: LaneRecord }> {\n\t\tthis.ensureTerminalNotifications();\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\treturn Object.values(snapshot.notifications).flatMap((notification) => {\n\t\t\tif (notification.status !== \"pending\" || !notification.attemptId) return [];\n\t\t\tconst attempt = snapshot.attempts[notification.attemptId];\n\t\t\tif (!attempt) return [];\n\t\t\tconst record = projectWorkerLaneRecord(snapshot, attempt.taskId);\n\t\t\tif (!record || record.status === \"queued\" || record.status === \"running\") return [];\n\t\t\treturn [{ notificationId: notification.notificationId, record }];\n\t\t});\n\t}\n\n\tgetTerminalNotification(\n\t\tlaneId: string,\n\t): { notificationId: string; status: \"pending\" | \"delivered\"; record: LaneRecord } | undefined {\n\t\tconst record = this.getRecord(laneId) ?? this.getManagedRecord(laneId);\n\t\tif (!record || record.status === \"queued\" || record.status === \"running\") return undefined;\n\t\tthis.enqueueTerminalNotification(record);\n\t\tconst attempt = this.getActiveAttempt(laneId) ?? this.getManagedAttempt(laneId);\n\t\tif (!attempt) return undefined;\n\t\tconst notificationId = `worker-terminal:${attempt.attemptId}`;\n\t\tconst notification = this.ledger.runtime.getSnapshot().notifications[notificationId];\n\t\treturn notification ? { notificationId, status: notification.status, record } : undefined;\n\t}\n\n\tmarkNotificationsDelivered(notificationIds: readonly string[]): void {\n\t\tfor (const notificationId of notificationIds) this.ledger.runtime.markNotificationDelivered(notificationId);\n\t}\n\n\tprivate ensureTerminalNotifications(): void {\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\tfor (const taskId of Object.keys(snapshot.tasks)) {\n\t\t\tconst record = projectWorkerLaneRecord(snapshot, taskId);\n\t\t\tif (record && record.status !== \"queued\" && record.status !== \"running\") {\n\t\t\t\tthis.enqueueTerminalNotification(record);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate enqueueTerminalNotification(record: LaneRecord): void {\n\t\tconst attempt = this.getActiveAttempt(record.laneId) ?? this.getManagedAttempt(record.laneId);\n\t\tif (!attempt || ACTIVE_WORKER_ATTEMPT_STATUSES.has(attempt.status)) return;\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\tconst task = snapshot.tasks[attempt.taskId];\n\t\tif (!task) return;\n\t\tif (attempt.result?.nextAction === \"independent_verification_required\" && !task.verification) return;\n\t\tthis.ledger.runtime.enqueueNotification({\n\t\t\tnotificationId: `worker-terminal:${attempt.attemptId}`,\n\t\t\tobjectiveId: task.task.objectiveId,\n\t\t\tattemptId: attempt.attemptId,\n\t\t\tmessage: `Worker ${record.laneId} reached ${record.status}.`,\n\t\t});\n\t}\n\n\tprivate requireActiveAttempt(laneId: string): AttemptRuntimeState {\n\t\tconst attempt = this.getActiveAttempt(laneId);\n\t\tif (!attempt || !ACTIVE_WORKER_ATTEMPT_STATUSES.has(attempt.status)) {\n\t\t\tthrow new Error(`Durable worker '${laneId}' has no active attempt.`);\n\t\t}\n\t\treturn attempt;\n\t}\n\n\tprivate startedHandle(attempt: AttemptRuntimeState): StartedDelegationAttempt {\n\t\tconst task = this.ledger.runtime.getSnapshot().tasks[attempt.taskId];\n\t\tif (!task || !attempt.lease) throw new Error(`Attempt '${attempt.attemptId}' has no started handle.`);\n\t\treturn {\n\t\t\tobjectiveId: task.task.objectiveId,\n\t\t\ttaskId: task.task.taskId,\n\t\t\tattemptId: attempt.attemptId,\n\t\t\tleaseId: attempt.lease.leaseId,\n\t\t\tfencingToken: attempt.lease.fencingToken,\n\t\t\texpiresAt: attempt.lease.expiresAt,\n\t\t};\n\t}\n\n\tprivate startPreparedManagedAttempt(\n\t\tattempt: AttemptRuntimeState,\n\t\tleaseTtlMs: number,\n\t\tcompileGrant: (target: { objectiveId: string; taskId: string; attemptId: string }) => ExecutionGrant,\n\t): StartedDelegationAttempt {\n\t\tconst task = this.ledger.runtime.getSnapshot().tasks[attempt.taskId];\n\t\tif (!task) throw new Error(`Managed attempt '${attempt.attemptId}' has no durable task.`);\n\t\tconst grant = compileGrant({\n\t\t\tobjectiveId: task.task.objectiveId,\n\t\t\ttaskId: task.task.taskId,\n\t\t\tattemptId: attempt.attemptId,\n\t\t});\n\t\tthis.bindGrant(attempt.attemptId, grant);\n\t\treturn this.ledger.start(\n\t\t\tattempt.attemptId,\n\t\t\tleaseTtlMs,\n\t\t\t`managed:${attempt.dispatch.logicalLaneId ?? attempt.taskId}`,\n\t\t);\n\t}\n}\n"]}
@@ -0,0 +1,18 @@
1
+ export interface LocalWorkerProcessOwner {
2
+ pid: number;
3
+ instanceId: string;
4
+ }
5
+ export type LocalWorkerProcessOwnerLiveness = "live" | "dead" | "unknown";
6
+ /** Process liveness probe shared by lifecycle and reservation recovery. Permission denial means live. */
7
+ export declare function isLocalProcessAlive(pid: number): boolean;
8
+ /** Create the durable identity for one local pi worker process instance. */
9
+ export declare function createLocalWorkerProcessOwnerId(pid: number, instanceId: string): string;
10
+ /** Parse only a complete, bounded pi-owned process identity. Unknown owner schemes remain untrusted. */
11
+ export declare function parseLocalWorkerProcessOwnerId(ownerId: string): LocalWorkerProcessOwner | undefined;
12
+ /**
13
+ * Resolve a local owner exactly once through the caller's liveness seam. Invalid identities and
14
+ * liveness probe failures stay unknown so recovery cannot steal a potentially active worker.
15
+ */
16
+ export declare function localWorkerProcessOwnerLiveness(ownerId: string, isProcessAlive: (pid: number) => boolean): LocalWorkerProcessOwnerLiveness;
17
+ export declare function isLocalWorkerProcessOwnerProvenDead(ownerId: string, isProcessAlive: (pid: number) => boolean): boolean;
18
+ //# sourceMappingURL=worker-process-owner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-process-owner.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-process-owner.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,uBAAuB;IACvC,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,MAAM,+BAA+B,GAAG,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;AAE1E,yGAAyG;AACzG,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAOxD;AAED,4EAA4E;AAC5E,wBAAgB,+BAA+B,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAQvF;AAED,wGAAwG;AACxG,wBAAgB,8BAA8B,CAAC,OAAO,EAAE,MAAM,GAAG,uBAAuB,GAAG,SAAS,CAOnG;AAED;;;GAGG;AACH,wBAAgB,+BAA+B,CAC9C,OAAO,EAAE,MAAM,EACf,cAAc,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,GACtC,+BAA+B,CAQjC;AAED,wBAAgB,mCAAmC,CAClD,OAAO,EAAE,MAAM,EACf,cAAc,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,GACtC,OAAO,CAET","sourcesContent":["const MAX_OWNER_ID_CHARS = 256;\nconst LOCAL_WORKER_OWNER_PATTERN =\n\t/^pi-worker:([1-9]\\d*):([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$/i;\n\nexport interface LocalWorkerProcessOwner {\n\tpid: number;\n\tinstanceId: string;\n}\n\nexport type LocalWorkerProcessOwnerLiveness = \"live\" | \"dead\" | \"unknown\";\n\n/** Process liveness probe shared by lifecycle and reservation recovery. Permission denial means live. */\nexport function isLocalProcessAlive(pid: number): boolean {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn typeof error === \"object\" && error !== null && (error as { code?: string }).code === \"EPERM\";\n\t}\n}\n\n/** Create the durable identity for one local pi worker process instance. */\nexport function createLocalWorkerProcessOwnerId(pid: number, instanceId: string): string {\n\tif (!Number.isSafeInteger(pid) || pid < 1) throw new TypeError(\"Worker owner pid must be a positive safe integer.\");\n\tconst normalizedInstanceId = instanceId.trim().toLowerCase();\n\tconst ownerId = `pi-worker:${pid}:${normalizedInstanceId}`;\n\tif (ownerId.length > MAX_OWNER_ID_CHARS || !parseLocalWorkerProcessOwnerId(ownerId)) {\n\t\tthrow new TypeError(\"Worker owner instance id must be a UUID.\");\n\t}\n\treturn ownerId;\n}\n\n/** Parse only a complete, bounded pi-owned process identity. Unknown owner schemes remain untrusted. */\nexport function parseLocalWorkerProcessOwnerId(ownerId: string): LocalWorkerProcessOwner | undefined {\n\tif (ownerId.length === 0 || ownerId.length > MAX_OWNER_ID_CHARS || ownerId.trim() !== ownerId) return undefined;\n\tconst matched = LOCAL_WORKER_OWNER_PATTERN.exec(ownerId);\n\tif (!matched) return undefined;\n\tconst pid = Number(matched[1]);\n\tif (!Number.isSafeInteger(pid) || pid < 1) return undefined;\n\treturn { pid, instanceId: matched[2]!.toLowerCase() };\n}\n\n/**\n * Resolve a local owner exactly once through the caller's liveness seam. Invalid identities and\n * liveness probe failures stay unknown so recovery cannot steal a potentially active worker.\n */\nexport function localWorkerProcessOwnerLiveness(\n\townerId: string,\n\tisProcessAlive: (pid: number) => boolean,\n): LocalWorkerProcessOwnerLiveness {\n\tconst owner = parseLocalWorkerProcessOwnerId(ownerId);\n\tif (!owner) return \"unknown\";\n\ttry {\n\t\treturn isProcessAlive(owner.pid) ? \"live\" : \"dead\";\n\t} catch {\n\t\treturn \"unknown\";\n\t}\n}\n\nexport function isLocalWorkerProcessOwnerProvenDead(\n\townerId: string,\n\tisProcessAlive: (pid: number) => boolean,\n): boolean {\n\treturn localWorkerProcessOwnerLiveness(ownerId, isProcessAlive) === \"dead\";\n}\n"]}
@@ -0,0 +1,54 @@
1
+ const MAX_OWNER_ID_CHARS = 256;
2
+ const LOCAL_WORKER_OWNER_PATTERN = /^pi-worker:([1-9]\d*):([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$/i;
3
+ /** Process liveness probe shared by lifecycle and reservation recovery. Permission denial means live. */
4
+ export function isLocalProcessAlive(pid) {
5
+ try {
6
+ process.kill(pid, 0);
7
+ return true;
8
+ }
9
+ catch (error) {
10
+ return typeof error === "object" && error !== null && error.code === "EPERM";
11
+ }
12
+ }
13
+ /** Create the durable identity for one local pi worker process instance. */
14
+ export function createLocalWorkerProcessOwnerId(pid, instanceId) {
15
+ if (!Number.isSafeInteger(pid) || pid < 1)
16
+ throw new TypeError("Worker owner pid must be a positive safe integer.");
17
+ const normalizedInstanceId = instanceId.trim().toLowerCase();
18
+ const ownerId = `pi-worker:${pid}:${normalizedInstanceId}`;
19
+ if (ownerId.length > MAX_OWNER_ID_CHARS || !parseLocalWorkerProcessOwnerId(ownerId)) {
20
+ throw new TypeError("Worker owner instance id must be a UUID.");
21
+ }
22
+ return ownerId;
23
+ }
24
+ /** Parse only a complete, bounded pi-owned process identity. Unknown owner schemes remain untrusted. */
25
+ export function parseLocalWorkerProcessOwnerId(ownerId) {
26
+ if (ownerId.length === 0 || ownerId.length > MAX_OWNER_ID_CHARS || ownerId.trim() !== ownerId)
27
+ return undefined;
28
+ const matched = LOCAL_WORKER_OWNER_PATTERN.exec(ownerId);
29
+ if (!matched)
30
+ return undefined;
31
+ const pid = Number(matched[1]);
32
+ if (!Number.isSafeInteger(pid) || pid < 1)
33
+ return undefined;
34
+ return { pid, instanceId: matched[2].toLowerCase() };
35
+ }
36
+ /**
37
+ * Resolve a local owner exactly once through the caller's liveness seam. Invalid identities and
38
+ * liveness probe failures stay unknown so recovery cannot steal a potentially active worker.
39
+ */
40
+ export function localWorkerProcessOwnerLiveness(ownerId, isProcessAlive) {
41
+ const owner = parseLocalWorkerProcessOwnerId(ownerId);
42
+ if (!owner)
43
+ return "unknown";
44
+ try {
45
+ return isProcessAlive(owner.pid) ? "live" : "dead";
46
+ }
47
+ catch {
48
+ return "unknown";
49
+ }
50
+ }
51
+ export function isLocalWorkerProcessOwnerProvenDead(ownerId, isProcessAlive) {
52
+ return localWorkerProcessOwnerLiveness(ownerId, isProcessAlive) === "dead";
53
+ }
54
+ //# sourceMappingURL=worker-process-owner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-process-owner.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-process-owner.ts"],"names":[],"mappings":"AAAA,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAC/B,MAAM,0BAA0B,GAC/B,mGAAmG,CAAC;AASrG,yGAAyG;AACzG,MAAM,UAAU,mBAAmB,CAAC,GAAW,EAAW;IACzD,IAAI,CAAC;QACJ,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;QACrB,OAAO,IAAI,CAAC;IACb,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAA2B,CAAC,IAAI,KAAK,OAAO,CAAC;IACrG,CAAC;AAAA,CACD;AAED,4EAA4E;AAC5E,MAAM,UAAU,+BAA+B,CAAC,GAAW,EAAE,UAAkB,EAAU;IACxF,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC;QAAE,MAAM,IAAI,SAAS,CAAC,mDAAmD,CAAC,CAAC;IACpH,MAAM,oBAAoB,GAAG,UAAU,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAC7D,MAAM,OAAO,GAAG,aAAa,GAAG,IAAI,oBAAoB,EAAE,CAAC;IAC3D,IAAI,OAAO,CAAC,MAAM,GAAG,kBAAkB,IAAI,CAAC,8BAA8B,CAAC,OAAO,CAAC,EAAE,CAAC;QACrF,MAAM,IAAI,SAAS,CAAC,0CAA0C,CAAC,CAAC;IACjE,CAAC;IACD,OAAO,OAAO,CAAC;AAAA,CACf;AAED,wGAAwG;AACxG,MAAM,UAAU,8BAA8B,CAAC,OAAe,EAAuC;IACpG,IAAI,OAAO,C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kerProcessOwner {\n\tpid: number;\n\tinstanceId: string;\n}\n\nexport type LocalWorkerProcessOwnerLiveness = \"live\" | \"dead\" | \"unknown\";\n\n/** Process liveness probe shared by lifecycle and reservation recovery. Permission denial means live. */\nexport function isLocalProcessAlive(pid: number): boolean {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn typeof error === \"object\" && error !== null && (error as { code?: string }).code === \"EPERM\";\n\t}\n}\n\n/** Create the durable identity for one local pi worker process instance. */\nexport function createLocalWorkerProcessOwnerId(pid: number, instanceId: string): string {\n\tif (!Number.isSafeInteger(pid) || pid < 1) throw new TypeError(\"Worker owner pid must be a positive safe integer.\");\n\tconst normalizedInstanceId = instanceId.trim().toLowerCase();\n\tconst ownerId = `pi-worker:${pid}:${normalizedInstanceId}`;\n\tif (ownerId.length > MAX_OWNER_ID_CHARS || !parseLocalWorkerProcessOwnerId(ownerId)) {\n\t\tthrow new TypeError(\"Worker owner instance id must be a UUID.\");\n\t}\n\treturn ownerId;\n}\n\n/** Parse only a complete, bounded pi-owned process identity. Unknown owner schemes remain untrusted. */\nexport function parseLocalWorkerProcessOwnerId(ownerId: string): LocalWorkerProcessOwner | undefined {\n\tif (ownerId.length === 0 || ownerId.length > MAX_OWNER_ID_CHARS || ownerId.trim() !== ownerId) return undefined;\n\tconst matched = LOCAL_WORKER_OWNER_PATTERN.exec(ownerId);\n\tif (!matched) return undefined;\n\tconst pid = Number(matched[1]);\n\tif (!Number.isSafeInteger(pid) || pid < 1) return undefined;\n\treturn { pid, instanceId: matched[2]!.toLowerCase() };\n}\n\n/**\n * Resolve a local owner exactly once through the caller's liveness seam. Invalid identities and\n * liveness probe failures stay unknown so recovery cannot steal a potentially active worker.\n */\nexport function localWorkerProcessOwnerLiveness(\n\townerId: string,\n\tisProcessAlive: (pid: number) => boolean,\n): LocalWorkerProcessOwnerLiveness {\n\tconst owner = parseLocalWorkerProcessOwnerId(ownerId);\n\tif (!owner) return \"unknown\";\n\ttry {\n\t\treturn isProcessAlive(owner.pid) ? \"live\" : \"dead\";\n\t} catch {\n\t\treturn \"unknown\";\n\t}\n}\n\nexport function isLocalWorkerProcessOwnerProvenDead(\n\townerId: string,\n\tisProcessAlive: (pid: number) => boolean,\n): boolean {\n\treturn localWorkerProcessOwnerLiveness(ownerId, isProcessAlive) === \"dead\";\n}\n"]}
@@ -1,18 +1,22 @@
1
1
  import type { Api, Model } from "@caupulican/pi-ai";
2
2
  import type { ModelRegistry } from "../model-registry.ts";
3
- import type { OrchestrationModelBinding, OrchestrationProfile, WorkerProfileExecutionContract } from "../orchestration/contracts.ts";
3
+ import type { OrchestrationModelBinding, OrchestrationProfile, ResourcePointer, WorkerProfileExecutionContract } from "../orchestration/contracts.ts";
4
4
  import type { SettingsManager } from "../settings-manager.ts";
5
5
  import type { WorkerDelegationRequest } from "./worker-delegation-request.ts";
6
+ import { type WorkerResourceCatalogResourceLoader } from "./worker-resource-catalog.ts";
6
7
  export interface ResolvedWorkerProfile {
7
8
  model: Model<Api>;
8
9
  modelBinding: OrchestrationModelBinding;
9
10
  profile: OrchestrationProfile;
11
+ /** Metadata-only pointers admitted from the profile-linked resource configuration. */
12
+ resourcePointers: readonly ResourcePointer[];
10
13
  soul?: string;
11
14
  }
12
15
  export interface WorkerProfileResolverOptions {
13
16
  agentDir: string;
14
17
  cwd: string;
15
18
  getSettingsManager(): SettingsManager;
19
+ getResourceLoader(): WorkerResourceCatalogResourceLoader;
16
20
  getModelRegistry(): ModelRegistry;
17
21
  isModelExhausted(model: Model<Api>): boolean;
18
22
  getActiveOrchestrationProfile(): OrchestrationProfile | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"worker-profile-resolver.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-profile-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sB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MAAM,CAAA;KAAE,CAa/E;IAED,eAAe,CACd,aAAa,EAAE,oBAAoB,GACjC;QAAE,EAAE,EAAE,IAAI,CAAC;QAAC,QAAQ,EAAE,qBAAqB,CAAA;KAAE,GAAG;QAAE,EAAE,EAAE,KAAK,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAU/E;IAED,eAAe,CACd,QAAQ,EAAE,8BAA8B,GACtC;QAAE,EAAE,EAAE,IAAI,CAAC;QAAC,QAAQ,EAAE,qBAAqB,CAAA;KAAE,GAAG;QAAE,EAAE,EAAE,KAAK,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAkB/E;IAED,OAAO,CAAC,gBAAgB;IAiCxB,OAAO,CAAC,mBAAmB;IAQ3B,OAAO,CAAC,YAAY;CAcpB","sourcesContent":["import type { Api, Model } from \"@caupulican/pi-ai\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport type {\n\tOrchestrationModelBinding,\n\tOrchestrationProfile,\n\tWorkerProfileExecutionContract,\n} from \"../orchestration/contracts.ts\";\nimport {\n\tresolveConfiguredOrchestrationModel,\n\tresolvePinnedOrchestrationModel,\n} from \"../orchestration/model-binding.ts\";\nimport { OrchestrationProfileStore } from \"../orchestration/profile-store.ts\";\nimport type { SettingsManager } from \"../settings-manager.ts\";\nimport type { WorkerDelegationRequest } from \"./worker-delegation-request.ts\";\n\nexport interface ResolvedWorkerProfile {\n\tmodel: Model<Api>;\n\tmodelBinding: OrchestrationModelBinding;\n\tprofile: OrchestrationProfile;\n\tsoul?: string;\n}\n\nexport interface WorkerProfileResolverOptions {\n\tagentDir: string;\n\tcwd: string;\n\tgetSettingsManager(): SettingsManager;\n\tgetModelRegistry(): ModelRegistry;\n\tisModelExhausted(model: Model<Api>): boolean;\n\tgetActiveOrchestrationProfile(): OrchestrationProfile | undefined;\n\tonDiagnostic(message: string): void;\n}\n\nexport class WorkerProfileResolver {\n\tprivate readonly options: WorkerProfileResolverOptions;\n\tprivate readonly warnedDiagnostics = new Set<string>();\n\n\tconstructor(options: WorkerProfileResolverOptions) {\n\t\tthis.options = options;\n\t}\n\n\tcatalog(): Array<{ profileId: string; role: string; description: string }> {\n\t\tconst activeProfile = this.options.getActiveOrchestrationProfile();\n\t\tconst allowedProfileIds =\n\t\t\tactiveProfile?.role === \"orchestrator\" ? new Set(activeProfile.dispatchProfileIds) : undefined;\n\t\treturn this.loadProfiles()\n\t\t\t.profiles.filter(\n\t\t\t\t(profile) =>\n\t\t\t\t\tprofile.role !== \"orchestrator\" && (!allowedProfileIds || allowedProfileIds.has(profile.profileId)),\n\t\t\t)\n\t\t\t.map((profile) => ({\n\t\t\t\tprofileId: profile.profileId,\n\t\t\t\trole: profile.role,\n\t\t\t\tdescription: profile.description,\n\t\t\t}));\n\t}\n\n\tresolve(\n\t\trequest: WorkerDelegationRequest,\n\t\tdefaultProfileId: string | undefined,\n\t): { ok: true; resolved: ResolvedWorkerProfile } | { ok: false; reason: string } {\n\t\tconst profileId = request.profileId?.trim() || defaultProfileId;\n\t\tif (!profileId) return { ok: false, reason: \"orchestration_profile_required\" };\n\t\tconst selected = this.resolveProfileId(profileId);\n\t\tif (!selected.ok) return selected;\n\t\tconst profile = selected.resolved.profile;\n\t\tif (request.verificationOfTaskId && profile.role !== \"verifier\") {\n\t\t\treturn { ok: false, reason: \"verification_profile_role_mismatch\" };\n\t\t}\n\t\tif (!request.verificationOfTaskId && profile.role === \"verifier\") {\n\t\t\treturn { ok: false, reason: \"verifier_profile_requires_runtime_dispatch\" };\n\t\t}\n\t\treturn selected;\n\t}\n\n\tresolveVerifier(\n\t\tworkerProfile: OrchestrationProfile,\n\t): { ok: true; resolved: ResolvedWorkerProfile } | { ok: false; reason: string } {\n\t\tif (!workerProfile.requireIndependentVerification || !workerProfile.verificationProfileId) {\n\t\t\treturn { ok: false, reason: \"independent_verifier_not_configured\" };\n\t\t}\n\t\tconst selected = this.resolveProfileId(workerProfile.verificationProfileId);\n\t\tif (!selected.ok) return selected;\n\t\tif (selected.resolved.profile.role !== \"verifier\") {\n\t\t\treturn { ok: false, reason: \"verification_profile_role_mismatch\" };\n\t\t}\n\t\treturn selected;\n\t}\n\n\tresolveContract(\n\t\tcontract: WorkerProfileExecutionContract,\n\t): { ok: true; resolved: ResolvedWorkerProfile } | { ok: false; reason: string } {\n\t\t// The architect allowlist authorized this immutable contract at admission. Live session/goal\n\t\t// controls may revoke execution, but mutable profile files cannot retroactively redefine it.\n\t\tconst resolvedModel = resolvePinnedOrchestrationModel(\n\t\t\tcontract.modelBinding,\n\t\t\tthis.options.getModelRegistry(),\n\t\t\t(model) => this.options.isModelExhausted(model),\n\t\t);\n\t\tif (!resolvedModel) return { ok: false, reason: \"orchestration_profile_model_unavailable\" };\n\t\treturn {\n\t\t\tok: true,\n\t\t\tresolved: {\n\t\t\t\tmodel: resolvedModel.model,\n\t\t\t\tmodelBinding: resolvedModel.binding,\n\t\t\t\tprofile: structuredClone(contract.profile),\n\t\t\t\t...(contract.soul ? { soul: contract.soul } : {}),\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate resolveProfileId(\n\t\tprofileId: string,\n\t): { ok: true; resolved: ResolvedWorkerProfile } | { ok: false; reason: string } {\n\t\tif (!this.isProfileAuthorized(profileId)) {\n\t\t\treturn { ok: false, reason: \"orchestration_profile_not_authorized_for_orchestrator\" };\n\t\t}\n\t\tconst profile = this.loadProfiles().registry.get(profileId);\n\t\tif (!profile) return { ok: false, reason: \"orchestration_profile_not_found\" };\n\t\tconst resolvedModel = resolveConfiguredOrchestrationModel(profile, this.options.getModelRegistry(), (model) =>\n\t\t\tthis.options.isModelExhausted(model),\n\t\t);\n\t\tif (!resolvedModel) return { ok: false, reason: \"orchestration_profile_model_unavailable\" };\n\t\tconst linkedProfiles = profile.resourceProfileNames.map((name) =>\n\t\t\tthis.options.getSettingsManager().getProfileRegistry().getProfile(name),\n\t\t);\n\t\tif (linkedProfiles.some((linked) => linked === undefined)) {\n\t\t\treturn { ok: false, reason: \"orchestration_resource_profile_not_found\" };\n\t\t}\n\t\tconst soul = linkedProfiles\n\t\t\t.flatMap((linked) => (linked?.soul ? [linked.soul] : []))\n\t\t\t.join(\"\\n\\n\")\n\t\t\t.trim();\n\t\treturn {\n\t\t\tok: true,\n\t\t\tresolved: {\n\t\t\t\tmodel: resolvedModel.model,\n\t\t\t\tmodelBinding: resolvedModel.binding,\n\t\t\t\tprofile,\n\t\t\t\t...(soul ? { soul } : {}),\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate isProfileAuthorized(profileId: string): boolean {\n\t\tconst activeProfile = this.options.getActiveOrchestrationProfile();\n\t\treturn (\n\t\t\t!activeProfile ||\n\t\t\t(activeProfile.role === \"orchestrator\" && activeProfile.dispatchProfileIds.includes(profileId))\n\t\t);\n\t}\n\n\tprivate loadProfiles(): ReturnType<OrchestrationProfileStore[\"load\"]> {\n\t\tconst loaded = new OrchestrationProfileStore({\n\t\t\tagentDir: this.options.agentDir,\n\t\t\tcwd: this.options.cwd,\n\t\t\tprojectTrusted: this.options.getSettingsManager().isProjectTrusted(),\n\t\t}).load();\n\t\tfor (const diagnostic of loaded.diagnostics) {\n\t\t\tconst key = `${diagnostic.path}\\0${diagnostic.message}`;\n\t\t\tif (this.warnedDiagnostics.has(key)) continue;\n\t\t\tthis.warnedDiagnostics.add(key);\n\t\t\tthis.options.onDiagnostic(`Orchestration profile ignored (${diagnostic.path}): ${diagnostic.message}`);\n\t\t}\n\t\treturn loaded;\n\t}\n}\n"]}
1
+ {"version":3,"file":"worker-profile-resolver.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-profile-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,KAAK,EACX,yBAAyB,EACzB,oBAAoB,EACpB,eAAe,EACf,8BAA8B,EAC9B,MAAM,+BAA+B,CA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AAE,GAAG;QAAE,EAAE,EAAE,KAAK,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAa/E;IAED,eAAe,CACd,aAAa,EAAE,oBAAoB,GACjC;QAAE,EAAE,EAAE,IAAI,CAAC;QAAC,QAAQ,EAAE,qBAAqB,CAAA;KAAE,GAAG;QAAE,EAAE,EAAE,KAAK,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAU/E;IAED,eAAe,CACd,QAAQ,EAAE,8BAA8B,GACtC;QAAE,EAAE,EAAE,IAAI,CAAC;QAAC,QAAQ,EAAE,qBAAqB,CAAA;KAAE,GAAG;QAAE,EAAE,EAAE,KAAK,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAmB/E;IAED,OAAO,CAAC,gBAAgB;IAyCxB,OAAO,CAAC,mBAAmB;IAQ3B,OAAO,CAAC,YAAY;CAcpB","sourcesContent":["import type { Api, Model } from \"@caupulican/pi-ai\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport type {\n\tOrchestrationModelBinding,\n\tOrchestrationProfile,\n\tResourcePointer,\n\tWorkerProfileExecutionContract,\n} from \"../orchestration/contracts.ts\";\nimport {\n\tresolveConfiguredOrchestrationModel,\n\tresolvePinnedOrchestrationModel,\n} from \"../orchestration/model-binding.ts\";\nimport { OrchestrationProfileStore } from \"../orchestration/profile-store.ts\";\nimport type { SettingsManager } from \"../settings-manager.ts\";\nimport type { WorkerDelegationRequest } from \"./worker-delegation-request.ts\";\nimport { catalogWorkerResourcePointers, type WorkerResourceCatalogResourceLoader } from \"./worker-resource-catalog.ts\";\n\nexport interface ResolvedWorkerProfile {\n\tmodel: Model<Api>;\n\tmodelBinding: OrchestrationModelBinding;\n\tprofile: OrchestrationProfile;\n\t/** Metadata-only pointers admitted from the profile-linked resource configuration. */\n\tresourcePointers: readonly ResourcePointer[];\n\tsoul?: string;\n}\n\nexport interface WorkerProfileResolverOptions {\n\tagentDir: string;\n\tcwd: string;\n\tgetSettingsManager(): SettingsManager;\n\tgetResourceLoader(): WorkerResourceCatalogResourceLoader;\n\tgetModelRegistry(): ModelRegistry;\n\tisModelExhausted(model: Model<Api>): boolean;\n\tgetActiveOrchestrationProfile(): OrchestrationProfile | undefined;\n\tonDiagnostic(message: string): void;\n}\n\nexport class WorkerProfileResolver {\n\tprivate readonly options: WorkerProfileResolverOptions;\n\tprivate readonly warnedDiagnostics = new Set<string>();\n\n\tconstructor(options: WorkerProfileResolverOptions) {\n\t\tthis.options = options;\n\t}\n\n\tcatalog(): Array<{ profileId: string; role: string; description: string }> {\n\t\tconst activeProfile = this.options.getActiveOrchestrationProfile();\n\t\tconst allowedProfileIds =\n\t\t\tactiveProfile?.role === \"orchestrator\" ? new Set(activeProfile.dispatchProfileIds) : undefined;\n\t\treturn this.loadProfiles()\n\t\t\t.profiles.filter(\n\t\t\t\t(profile) =>\n\t\t\t\t\tprofile.role !== \"orchestrator\" && (!allowedProfileIds || allowedProfileIds.has(profile.profileId)),\n\t\t\t)\n\t\t\t.map((profile) => ({\n\t\t\t\tprofileId: profile.profileId,\n\t\t\t\trole: profile.role,\n\t\t\t\tdescription: profile.description,\n\t\t\t}));\n\t}\n\n\tresolve(\n\t\trequest: WorkerDelegationRequest,\n\t\tdefaultProfileId: string | undefined,\n\t): { ok: true; resolved: ResolvedWorkerProfile } | { ok: false; reason: string } {\n\t\tconst profileId = request.profileId?.trim() || defaultProfileId;\n\t\tif (!profileId) return { ok: false, reason: \"orchestration_profile_required\" };\n\t\tconst selected = this.resolveProfileId(profileId);\n\t\tif (!selected.ok) return selected;\n\t\tconst profile = selected.resolved.profile;\n\t\tif (request.verificationOfTaskId && profile.role !== \"verifier\") {\n\t\t\treturn { ok: false, reason: \"verification_profile_role_mismatch\" };\n\t\t}\n\t\tif (!request.verificationOfTaskId && profile.role === \"verifier\") {\n\t\t\treturn { ok: false, reason: \"verifier_profile_requires_runtime_dispatch\" };\n\t\t}\n\t\treturn selected;\n\t}\n\n\tresolveVerifier(\n\t\tworkerProfile: OrchestrationProfile,\n\t): { ok: true; resolved: ResolvedWorkerProfile } | { ok: false; reason: string } {\n\t\tif (!workerProfile.requireIndependentVerification || !workerProfile.verificationProfileId) {\n\t\t\treturn { ok: false, reason: \"independent_verifier_not_configured\" };\n\t\t}\n\t\tconst selected = this.resolveProfileId(workerProfile.verificationProfileId);\n\t\tif (!selected.ok) return selected;\n\t\tif (selected.resolved.profile.role !== \"verifier\") {\n\t\t\treturn { ok: false, reason: \"verification_profile_role_mismatch\" };\n\t\t}\n\t\treturn selected;\n\t}\n\n\tresolveContract(\n\t\tcontract: WorkerProfileExecutionContract,\n\t): { ok: true; resolved: ResolvedWorkerProfile } | { ok: false; reason: string } {\n\t\t// The architect allowlist authorized this immutable contract at admission. Live session/goal\n\t\t// controls may revoke execution, but mutable profile files cannot retroactively redefine it.\n\t\tconst resolvedModel = resolvePinnedOrchestrationModel(\n\t\t\tcontract.modelBinding,\n\t\t\tthis.options.getModelRegistry(),\n\t\t\t(model) => this.options.isModelExhausted(model),\n\t\t);\n\t\tif (!resolvedModel) return { ok: false, reason: \"orchestration_profile_model_unavailable\" };\n\t\treturn {\n\t\t\tok: true,\n\t\t\tresolved: {\n\t\t\t\tmodel: resolvedModel.model,\n\t\t\t\tmodelBinding: resolvedModel.binding,\n\t\t\t\tprofile: structuredClone(contract.profile),\n\t\t\t\tresourcePointers: structuredClone(contract.resourcePointers),\n\t\t\t\t...(contract.soul ? { soul: contract.soul } : {}),\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate resolveProfileId(\n\t\tprofileId: string,\n\t): { ok: true; resolved: ResolvedWorkerProfile } | { ok: false; reason: string } {\n\t\tif (!this.isProfileAuthorized(profileId)) {\n\t\t\treturn { ok: false, reason: \"orchestration_profile_not_authorized_for_orchestrator\" };\n\t\t}\n\t\tconst profile = this.loadProfiles().registry.get(profileId);\n\t\tif (!profile) return { ok: false, reason: \"orchestration_profile_not_found\" };\n\t\tconst resolvedModel = resolveConfiguredOrchestrationModel(profile, this.options.getModelRegistry(), (model) =>\n\t\t\tthis.options.isModelExhausted(model),\n\t\t);\n\t\tif (!resolvedModel) return { ok: false, reason: \"orchestration_profile_model_unavailable\" };\n\t\tconst linkedProfiles = profile.resourceProfileNames.map((name) =>\n\t\t\tthis.options.getSettingsManager().getProfileRegistry().getProfile(name),\n\t\t);\n\t\tif (linkedProfiles.some((linked) => linked === undefined)) {\n\t\t\treturn { ok: false, reason: \"orchestration_resource_profile_not_found\" };\n\t\t}\n\t\tconst soul = linkedProfiles\n\t\t\t.flatMap((linked) => (linked?.soul ? [linked.soul] : []))\n\t\t\t.join(\"\\n\\n\")\n\t\t\t.trim();\n\t\tconst resourcePointers = catalogWorkerResourcePointers({\n\t\t\tcwd: this.options.cwd,\n\t\t\tresourceLoader: this.options.getResourceLoader(),\n\t\t\tresourceProfiles: linkedProfiles.filter(\n\t\t\t\t(linked): linked is NonNullable<typeof linked> => linked !== undefined,\n\t\t\t),\n\t\t});\n\t\treturn {\n\t\t\tok: true,\n\t\t\tresolved: {\n\t\t\t\tmodel: resolvedModel.model,\n\t\t\t\tmodelBinding: resolvedModel.binding,\n\t\t\t\tprofile,\n\t\t\t\tresourcePointers,\n\t\t\t\t...(soul ? { soul } : {}),\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate isProfileAuthorized(profileId: string): boolean {\n\t\tconst activeProfile = this.options.getActiveOrchestrationProfile();\n\t\treturn (\n\t\t\t!activeProfile ||\n\t\t\t(activeProfile.role === \"orchestrator\" && activeProfile.dispatchProfileIds.includes(profileId))\n\t\t);\n\t}\n\n\tprivate loadProfiles(): ReturnType<OrchestrationProfileStore[\"load\"]> {\n\t\tconst loaded = new OrchestrationProfileStore({\n\t\t\tagentDir: this.options.agentDir,\n\t\t\tcwd: this.options.cwd,\n\t\t\tprojectTrusted: this.options.getSettingsManager().isProjectTrusted(),\n\t\t}).load();\n\t\tfor (const diagnostic of loaded.diagnostics) {\n\t\t\tconst key = `${diagnostic.path}\\0${diagnostic.message}`;\n\t\t\tif (this.warnedDiagnostics.has(key)) continue;\n\t\t\tthis.warnedDiagnostics.add(key);\n\t\t\tthis.options.onDiagnostic(`Orchestration profile ignored (${diagnostic.path}): ${diagnostic.message}`);\n\t\t}\n\t\treturn loaded;\n\t}\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import { resolveConfiguredOrchestrationModel, resolvePinnedOrchestrationModel, } from "../orchestration/model-binding.js";
2
2
  import { OrchestrationProfileStore } from "../orchestration/profile-store.js";
3
+ import { catalogWorkerResourcePointers } from "./worker-resource-catalog.js";
3
4
  export class WorkerProfileResolver {
4
5
  options;
5
6
  warnedDiagnostics = new Set();
@@ -57,6 +58,7 @@ export class WorkerProfileResolver {
57
58
  model: resolvedModel.model,
58
59
  modelBinding: resolvedModel.binding,
59
60
  profile: structuredClone(contract.profile),
61
+ resourcePointers: structuredClone(contract.resourcePointers),
60
62
  ...(contract.soul ? { soul: contract.soul } : {}),
61
63
  },
62
64
  };
@@ -79,12 +81,18 @@ export class WorkerProfileResolver {
79
81
  .flatMap((linked) => (linked?.soul ? [linked.soul] : []))
80
82
  .join("\n\n")
81
83
  .trim();
84
+ const resourcePointers = catalogWorkerResourcePointers({
85
+ cwd: this.options.cwd,
86
+ resourceLoader: this.options.getResourceLoader(),
87
+ resourceProfiles: linkedProfiles.filter((linked) => linked !== undefined),
88
+ });
82
89
  return {
83
90
  ok: true,
84
91
  resolved: {
85
92
  model: resolvedModel.model,
86
93
  modelBinding: resolvedModel.binding,
87
94
  profile,
95
+ resourcePointers,
88
96
  ...(soul ? { soul } : {}),
89
97
  },
90
98
  };
@@ -1 +1 @@
1
- {"version":3,"file":"worker-profile-resolver.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-profile-resolver.ts"],"names":[],"mappings":"AAOA,OAAO,EACN,mCAAmC,EACnC,+BAA+B,GAC/B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAqB9E,MAA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SACpE,CAAC,CAAC,IAAI,EAAE,CAAC;QACV,KAAK,MAAM,UAAU,IAAI,MAAM,CAAC,WAAW,EAAE,CAAC;YAC7C,MAAM,GAAG,GAAG,GAAG,UAAU,CAAC,IAAI,KAAK,UAAU,CAAC,OAAO,EAAE,CAAC;YACxD,IAAI,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,GAAG,CAAC;gBAAE,SAAS;YAC9C,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YAChC,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,kCAAkC,UAAU,CAAC,IAAI,MAAM,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC;QACxG,CAAC;QACD,OAAO,MAAM,CAAC;IAAA,CACd;CACD","sourcesContent":["import type { Api, Model } from \"@caupulican/pi-ai\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport type {\n\tOrchestrationModelBinding,\n\tOrchestrationProfile,\n\tWorkerProfileExecutionContract,\n} from \"../orchestration/contracts.ts\";\nimport {\n\tresolveConfiguredOrchestrationModel,\n\tresolvePinnedOrchestrationModel,\n} from \"../orchestration/model-binding.ts\";\nimport { OrchestrationProfileStore } from \"../orchestration/profile-store.ts\";\nimport type { SettingsManager } from \"../settings-manager.ts\";\nimport type { WorkerDelegationRequest } from \"./worker-delegation-request.ts\";\n\nexport interface ResolvedWorkerProfile {\n\tmodel: Model<Api>;\n\tmodelBinding: OrchestrationModelBinding;\n\tprofile: OrchestrationProfile;\n\tsoul?: string;\n}\n\nexport interface WorkerProfileResolverOptions {\n\tagentDir: string;\n\tcwd: string;\n\tgetSettingsManager(): SettingsManager;\n\tgetModelRegistry(): ModelRegistry;\n\tisModelExhausted(model: Model<Api>): boolean;\n\tgetActiveOrchestrationProfile(): OrchestrationProfile | undefined;\n\tonDiagnostic(message: string): void;\n}\n\nexport class WorkerProfileResolver {\n\tprivate readonly options: WorkerProfileResolverOptions;\n\tprivate readonly warnedDiagnostics = new Set<string>();\n\n\tconstructor(options: WorkerProfileResolverOptions) {\n\t\tthis.options = options;\n\t}\n\n\tcatalog(): Array<{ profileId: string; role: string; description: string }> {\n\t\tconst activeProfile = this.options.getActiveOrchestrationProfile();\n\t\tconst allowedProfileIds =\n\t\t\tactiveProfile?.role === \"orchestrator\" ? new Set(activeProfile.dispatchProfileIds) : undefined;\n\t\treturn this.loadProfiles()\n\t\t\t.profiles.filter(\n\t\t\t\t(profile) =>\n\t\t\t\t\tprofile.role !== \"orchestrator\" && (!allowedProfileIds || allowedProfileIds.has(profile.profileId)),\n\t\t\t)\n\t\t\t.map((profile) => ({\n\t\t\t\tprofileId: profile.profileId,\n\t\t\t\trole: profile.role,\n\t\t\t\tdescription: profile.description,\n\t\t\t}));\n\t}\n\n\tresolve(\n\t\trequest: WorkerDelegationRequest,\n\t\tdefaultProfileId: string | undefined,\n\t): { ok: true; resolved: ResolvedWorkerProfile } | { ok: false; reason: string } {\n\t\tconst profileId = request.profileId?.trim() || defaultProfileId;\n\t\tif (!profileId) return { ok: false, reason: \"orchestration_profile_required\" };\n\t\tconst selected = this.resolveProfileId(profileId);\n\t\tif (!selected.ok) return selected;\n\t\tconst profile = selected.resolved.profile;\n\t\tif (request.verificationOfTaskId && profile.role !== \"verifier\") {\n\t\t\treturn { ok: false, reason: \"verification_profile_role_mismatch\" };\n\t\t}\n\t\tif (!request.verificationOfTaskId && profile.role === \"verifier\") {\n\t\t\treturn { ok: false, reason: \"verifier_profile_requires_runtime_dispatch\" };\n\t\t}\n\t\treturn selected;\n\t}\n\n\tresolveVerifier(\n\t\tworkerProfile: OrchestrationProfile,\n\t): { ok: true; resolved: ResolvedWorkerProfile } | { ok: false; reason: string } {\n\t\tif (!workerProfile.requireIndependentVerification || !workerProfile.verificationProfileId) {\n\t\t\treturn { ok: false, reason: \"independent_verifier_not_configured\" };\n\t\t}\n\t\tconst selected = this.resolveProfileId(workerProfile.verificationProfileId);\n\t\tif (!selected.ok) return selected;\n\t\tif (selected.resolved.profile.role !== \"verifier\") {\n\t\t\treturn { ok: false, reason: \"verification_profile_role_mismatch\" };\n\t\t}\n\t\treturn selected;\n\t}\n\n\tresolveContract(\n\t\tcontract: WorkerProfileExecutionContract,\n\t): { ok: true; resolved: ResolvedWorkerProfile } | { ok: false; reason: string } {\n\t\t// The architect allowlist authorized this immutable contract at admission. Live session/goal\n\t\t// controls may revoke execution, but mutable profile files cannot retroactively redefine it.\n\t\tconst resolvedModel = resolvePinnedOrchestrationModel(\n\t\t\tcontract.modelBinding,\n\t\t\tthis.options.getModelRegistry(),\n\t\t\t(model) => this.options.isModelExhausted(model),\n\t\t);\n\t\tif (!resolvedModel) return { ok: false, reason: \"orchestration_profile_model_unavailable\" };\n\t\treturn {\n\t\t\tok: true,\n\t\t\tresolved: {\n\t\t\t\tmodel: resolvedModel.model,\n\t\t\t\tmodelBinding: resolvedModel.binding,\n\t\t\t\tprofile: structuredClone(contract.profile),\n\t\t\t\t...(contract.soul ? { soul: contract.soul } : {}),\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate resolveProfileId(\n\t\tprofileId: string,\n\t): { ok: true; resolved: ResolvedWorkerProfile } | { ok: false; reason: string } {\n\t\tif (!this.isProfileAuthorized(profileId)) {\n\t\t\treturn { ok: false, reason: \"orchestration_profile_not_authorized_for_orchestrator\" };\n\t\t}\n\t\tconst profile = this.loadProfiles().registry.get(profileId);\n\t\tif (!profile) return { ok: false, reason: \"orchestration_profile_not_found\" };\n\t\tconst resolvedModel = resolveConfiguredOrchestrationModel(profile, this.options.getModelRegistry(), (model) =>\n\t\t\tthis.options.isModelExhausted(model),\n\t\t);\n\t\tif (!resolvedModel) return { ok: false, reason: \"orchestration_profile_model_unavailable\" };\n\t\tconst linkedProfiles = profile.resourceProfileNames.map((name) =>\n\t\t\tthis.options.getSettingsManager().getProfileRegistry().getProfile(name),\n\t\t);\n\t\tif (linkedProfiles.some((linked) => linked === undefined)) {\n\t\t\treturn { ok: false, reason: \"orchestration_resource_profile_not_found\" };\n\t\t}\n\t\tconst soul = linkedProfiles\n\t\t\t.flatMap((linked) => (linked?.soul ? [linked.soul] : []))\n\t\t\t.join(\"\\n\\n\")\n\t\t\t.trim();\n\t\treturn {\n\t\t\tok: true,\n\t\t\tresolved: {\n\t\t\t\tmodel: resolvedModel.model,\n\t\t\t\tmodelBinding: resolvedModel.binding,\n\t\t\t\tprofile,\n\t\t\t\t...(soul ? { soul } : {}),\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate isProfileAuthorized(profileId: string): boolean {\n\t\tconst activeProfile = this.options.getActiveOrchestrationProfile();\n\t\treturn (\n\t\t\t!activeProfile ||\n\t\t\t(activeProfile.role === \"orchestrator\" && activeProfile.dispatchProfileIds.includes(profileId))\n\t\t);\n\t}\n\n\tprivate loadProfiles(): ReturnType<OrchestrationProfileStore[\"load\"]> {\n\t\tconst loaded = new OrchestrationProfileStore({\n\t\t\tagentDir: this.options.agentDir,\n\t\t\tcwd: this.options.cwd,\n\t\t\tprojectTrusted: this.options.getSettingsManager().isProjectTrusted(),\n\t\t}).load();\n\t\tfor (const diagnostic of loaded.diagnostics) {\n\t\t\tconst key = `${diagnostic.path}\\0${diagnostic.message}`;\n\t\t\tif (this.warnedDiagnostics.has(key)) continue;\n\t\t\tthis.warnedDiagnostics.add(key);\n\t\t\tthis.options.onDiagnostic(`Orchestration profile ignored (${diagnostic.path}): ${diagnostic.message}`);\n\t\t}\n\t\treturn loaded;\n\t}\n}\n"]}
1
+ {"version":3,"file":"worker-profile-resolver.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-profile-resolver.ts"],"names":[],"mappings":"AAQA,OAAO,EACN,mCAAmC,EACnC,+BAA+B,GAC/B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAG9E,OAAO,EAAE,6BAA6B,EAA4C,MAAM,8BAA8B,CAAC;AAsBvH,MAAM,OAAO,qBAAqB;IAChB,OAAO,CAA+B;IACtC,iBAAiB,GA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C,SAAS,CAAC,CAAC,CAC/F,CAAC;IAAA,CACF;IAEO,YAAY,GAAkD;QACrE,MAAM,MAAM,GAAG,IAAI,yBAAyB,CAAC;YAC5C,QAAQ,EAAE,IAAI,CAAC,OAAO,CAAC,QAAQ;YAC/B,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,GAAG;YACrB,cAAc,EAAE,IAAI,CAAC,OAAO,CAAC,kBAAkB,EAAE,CAAC,gBAAgB,EAAE;SACpE,CAAC,CAAC,IAAI,EAAE,CAAC;QACV,KAAK,MAAM,UAAU,IAAI,MAAM,CAAC,WAAW,EAAE,CAAC;YAC7C,MAAM,GAAG,GAAG,GAAG,UAAU,CAAC,IAAI,KAAK,UAAU,CAAC,OAAO,EAAE,CAAC;YACxD,IAAI,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,GAAG,CAAC;gBAAE,SAAS;YAC9C,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YAChC,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,kCAAkC,UAAU,CAAC,IAAI,MAAM,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC;QACxG,CAAC;QACD,OAAO,MAAM,CAAC;IAAA,CACd;CACD","sourcesContent":["import type { Api, Model } from \"@caupulican/pi-ai\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport type {\n\tOrchestrationModelBinding,\n\tOrchestrationProfile,\n\tResourcePointer,\n\tWorkerProfileExecutionContract,\n} from \"../orchestration/contracts.ts\";\nimport {\n\tresolveConfiguredOrchestrationModel,\n\tresolvePinnedOrchestrationModel,\n} from \"../orchestration/model-binding.ts\";\nimport { OrchestrationProfileStore } from \"../orchestration/profile-store.ts\";\nimport type { SettingsManager } from \"../settings-manager.ts\";\nimport type { WorkerDelegationRequest } from \"./worker-delegation-request.ts\";\nimport { catalogWorkerResourcePointers, type WorkerResourceCatalogResourceLoader } from \"./worker-resource-catalog.ts\";\n\nexport interface ResolvedWorkerProfile {\n\tmodel: Model<Api>;\n\tmodelBinding: OrchestrationModelBinding;\n\tprofile: OrchestrationProfile;\n\t/** Metadata-only pointers admitted from the profile-linked resource configuration. */\n\tresourcePointers: readonly ResourcePointer[];\n\tsoul?: string;\n}\n\nexport interface WorkerProfileResolverOptions {\n\tagentDir: string;\n\tcwd: string;\n\tgetSettingsManager(): SettingsManager;\n\tgetResourceLoader(): WorkerResourceCatalogResourceLoader;\n\tgetModelRegistry(): ModelRegistry;\n\tisModelExhausted(model: Model<Api>): boolean;\n\tgetActiveOrchestrationProfile(): OrchestrationProfile | undefined;\n\tonDiagnostic(message: string): void;\n}\n\nexport class WorkerProfileResolver {\n\tprivate readonly options: WorkerProfileResolverOptions;\n\tprivate readonly warnedDiagnostics = new Set<string>();\n\n\tconstructor(options: WorkerProfileResolverOptions) {\n\t\tthis.options = options;\n\t}\n\n\tcatalog(): Array<{ profileId: string; role: string; description: string }> {\n\t\tconst activeProfile = this.options.getActiveOrchestrationProfile();\n\t\tconst allowedProfileIds =\n\t\t\tactiveProfile?.role === \"orchestrator\" ? new Set(activeProfile.dispatchProfileIds) : undefined;\n\t\treturn this.loadProfiles()\n\t\t\t.profiles.filter(\n\t\t\t\t(profile) =>\n\t\t\t\t\tprofile.role !== \"orchestrator\" && (!allowedProfileIds || allowedProfileIds.has(profile.profileId)),\n\t\t\t)\n\t\t\t.map((profile) => ({\n\t\t\t\tprofileId: profile.profileId,\n\t\t\t\trole: profile.role,\n\t\t\t\tdescription: profile.description,\n\t\t\t}));\n\t}\n\n\tresolve(\n\t\trequest: WorkerDelegationRequest,\n\t\tdefaultProfileId: string | undefined,\n\t): { ok: true; resolved: ResolvedWorkerProfile } | { ok: false; reason: string } {\n\t\tconst profileId = request.profileId?.trim() || defaultProfileId;\n\t\tif (!profileId) return { ok: false, reason: \"orchestration_profile_required\" };\n\t\tconst selected = this.resolveProfileId(profileId);\n\t\tif (!selected.ok) return selected;\n\t\tconst profile = selected.resolved.profile;\n\t\tif (request.verificationOfTaskId && profile.role !== \"verifier\") {\n\t\t\treturn { ok: false, reason: \"verification_profile_role_mismatch\" };\n\t\t}\n\t\tif (!request.verificationOfTaskId && profile.role === \"verifier\") {\n\t\t\treturn { ok: false, reason: \"verifier_profile_requires_runtime_dispatch\" };\n\t\t}\n\t\treturn selected;\n\t}\n\n\tresolveVerifier(\n\t\tworkerProfile: OrchestrationProfile,\n\t): { ok: true; resolved: ResolvedWorkerProfile } | { ok: false; reason: string } {\n\t\tif (!workerProfile.requireIndependentVerification || !workerProfile.verificationProfileId) {\n\t\t\treturn { ok: false, reason: \"independent_verifier_not_configured\" };\n\t\t}\n\t\tconst selected = this.resolveProfileId(workerProfile.verificationProfileId);\n\t\tif (!selected.ok) return selected;\n\t\tif (selected.resolved.profile.role !== \"verifier\") {\n\t\t\treturn { ok: false, reason: \"verification_profile_role_mismatch\" };\n\t\t}\n\t\treturn selected;\n\t}\n\n\tresolveContract(\n\t\tcontract: WorkerProfileExecutionContract,\n\t): { ok: true; resolved: ResolvedWorkerProfile } | { ok: false; reason: string } {\n\t\t// The architect allowlist authorized this immutable contract at admission. Live session/goal\n\t\t// controls may revoke execution, but mutable profile files cannot retroactively redefine it.\n\t\tconst resolvedModel = resolvePinnedOrchestrationModel(\n\t\t\tcontract.modelBinding,\n\t\t\tthis.options.getModelRegistry(),\n\t\t\t(model) => this.options.isModelExhausted(model),\n\t\t);\n\t\tif (!resolvedModel) return { ok: false, reason: \"orchestration_profile_model_unavailable\" };\n\t\treturn {\n\t\t\tok: true,\n\t\t\tresolved: {\n\t\t\t\tmodel: resolvedModel.model,\n\t\t\t\tmodelBinding: resolvedModel.binding,\n\t\t\t\tprofile: structuredClone(contract.profile),\n\t\t\t\tresourcePointers: structuredClone(contract.resourcePointers),\n\t\t\t\t...(contract.soul ? { soul: contract.soul } : {}),\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate resolveProfileId(\n\t\tprofileId: string,\n\t): { ok: true; resolved: ResolvedWorkerProfile } | { ok: false; reason: string } {\n\t\tif (!this.isProfileAuthorized(profileId)) {\n\t\t\treturn { ok: false, reason: \"orchestration_profile_not_authorized_for_orchestrator\" };\n\t\t}\n\t\tconst profile = this.loadProfiles().registry.get(profileId);\n\t\tif (!profile) return { ok: false, reason: \"orchestration_profile_not_found\" };\n\t\tconst resolvedModel = resolveConfiguredOrchestrationModel(profile, this.options.getModelRegistry(), (model) =>\n\t\t\tthis.options.isModelExhausted(model),\n\t\t);\n\t\tif (!resolvedModel) return { ok: false, reason: \"orchestration_profile_model_unavailable\" };\n\t\tconst linkedProfiles = profile.resourceProfileNames.map((name) =>\n\t\t\tthis.options.getSettingsManager().getProfileRegistry().getProfile(name),\n\t\t);\n\t\tif (linkedProfiles.some((linked) => linked === undefined)) {\n\t\t\treturn { ok: false, reason: \"orchestration_resource_profile_not_found\" };\n\t\t}\n\t\tconst soul = linkedProfiles\n\t\t\t.flatMap((linked) => (linked?.soul ? [linked.soul] : []))\n\t\t\t.join(\"\\n\\n\")\n\t\t\t.trim();\n\t\tconst resourcePointers = catalogWorkerResourcePointers({\n\t\t\tcwd: this.options.cwd,\n\t\t\tresourceLoader: this.options.getResourceLoader(),\n\t\t\tresourceProfiles: linkedProfiles.filter(\n\t\t\t\t(linked): linked is NonNullable<typeof linked> => linked !== undefined,\n\t\t\t),\n\t\t});\n\t\treturn {\n\t\t\tok: true,\n\t\t\tresolved: {\n\t\t\t\tmodel: resolvedModel.model,\n\t\t\t\tmodelBinding: resolvedModel.binding,\n\t\t\t\tprofile,\n\t\t\t\tresourcePointers,\n\t\t\t\t...(soul ? { soul } : {}),\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate isProfileAuthorized(profileId: string): boolean {\n\t\tconst activeProfile = this.options.getActiveOrchestrationProfile();\n\t\treturn (\n\t\t\t!activeProfile ||\n\t\t\t(activeProfile.role === \"orchestrator\" && activeProfile.dispatchProfileIds.includes(profileId))\n\t\t);\n\t}\n\n\tprivate loadProfiles(): ReturnType<OrchestrationProfileStore[\"load\"]> {\n\t\tconst loaded = new OrchestrationProfileStore({\n\t\t\tagentDir: this.options.agentDir,\n\t\t\tcwd: this.options.cwd,\n\t\t\tprojectTrusted: this.options.getSettingsManager().isProjectTrusted(),\n\t\t}).load();\n\t\tfor (const diagnostic of loaded.diagnostics) {\n\t\t\tconst key = `${diagnostic.path}\\0${diagnostic.message}`;\n\t\t\tif (this.warnedDiagnostics.has(key)) continue;\n\t\t\tthis.warnedDiagnostics.add(key);\n\t\t\tthis.options.onDiagnostic(`Orchestration profile ignored (${diagnostic.path}): ${diagnostic.message}`);\n\t\t}\n\t\treturn loaded;\n\t}\n}\n"]}