code60-transmission-server 0.0.0-stage → 0.1.0-staging.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +180 -0
- package/README.engine.md +401 -0
- package/README.md +294 -2
- package/dist/src/broker/filesystem.js +385 -0
- package/dist/src/broker/index.js +734 -0
- package/dist/src/broker/native/README.md +192 -0
- package/dist/src/broker/native/build.js +43 -0
- package/dist/src/broker/native/fs-helper.c +529 -0
- package/dist/src/broker/native/git-helper.c +205 -0
- package/dist/src/broker/policy.js +149 -0
- package/dist/src/broker/startup-lock.js +14 -0
- package/dist/src/broker/types.js +11 -0
- package/dist/src/cli/daemon.js +365 -0
- package/dist/src/cli/helpers.js +104 -0
- package/dist/src/cli/main.js +180 -0
- package/dist/src/config/deployment.js +166 -0
- package/dist/src/config/documents.js +29 -0
- package/dist/src/config/profile-validation.js +123 -0
- package/dist/src/config/schema-graph.js +237 -0
- package/dist/src/config/schema-loader.js +185 -0
- package/dist/src/config/validation-pool.js +105 -0
- package/dist/src/config/validation-protocol.js +1 -0
- package/dist/src/config/validation-worker.js +106 -0
- package/dist/src/config/workflow-language.js +9 -0
- package/dist/src/config/workflow-schema.json +534 -0
- package/dist/src/config/workflow-types.js +1 -0
- package/dist/src/config/workflow-validation.js +95 -0
- package/dist/src/engine/budgets.js +50 -0
- package/dist/src/engine/clocks.js +27 -0
- package/dist/src/engine/commands.js +441 -0
- package/dist/src/engine/contracts.js +11 -0
- package/dist/src/engine/drain-state.js +31 -0
- package/dist/src/engine/effective-permissions.js +120 -0
- package/dist/src/engine/instruction-pins.js +205 -0
- package/dist/src/engine/retries.js +50 -0
- package/dist/src/engine/state.js +1 -0
- package/dist/src/engine/timing.js +23 -0
- package/dist/src/engine/tool-observations.js +87 -0
- package/dist/src/engine/workflow-engine.js +1807 -0
- package/dist/src/main.js +25 -0
- package/dist/src/mcp/catalog.js +71 -0
- package/dist/src/mcp/main.js +24 -0
- package/dist/src/mcp/server.js +116 -0
- package/dist/src/runtime/codex-app-server.js +91 -0
- package/dist/src/runtime/containment.js +82 -0
- package/dist/src/runtime/engine-driver.js +212 -0
- package/dist/src/runtime/json-line-writer.js +192 -0
- package/dist/src/runtime/pinned-instruction-sources.js +24 -0
- package/dist/src/runtime/protocol-client.js +264 -0
- package/dist/src/runtime/protocol-pool.js +183 -0
- package/dist/src/runtime/protocol-projection.js +393 -0
- package/dist/src/runtime/protocol-types.js +1 -0
- package/dist/src/runtime/protocol-worker.js +18 -0
- package/dist/src/runtime/provider-bridge.js +288 -0
- package/dist/src/runtime/provider-credentials.js +41 -0
- package/dist/src/runtime/provider-transport.js +404 -0
- package/dist/src/runtime/runtime-broker.js +213 -0
- package/dist/src/runtime/workspace-instructions.js +120 -0
- package/dist/src/runtime/workspace-view.js +74 -0
- package/dist/src/server/api-contract.json +11086 -0
- package/dist/src/server/api-types.js +1 -0
- package/dist/src/server/application.js +38 -0
- package/dist/src/server/auth.js +67 -0
- package/dist/src/server/broker-handlers.js +242 -0
- package/dist/src/server/control-plane.js +50 -0
- package/dist/src/server/deployment.js +237 -0
- package/dist/src/server/errors.js +22 -0
- package/dist/src/server/history-handlers.js +113 -0
- package/dist/src/server/http.js +124 -0
- package/dist/src/server/paging.js +56 -0
- package/dist/src/server/publication.js +119 -0
- package/dist/src/server/tool-event-handler.js +77 -0
- package/dist/src/server/workspace-handlers.js +34 -0
- package/dist/src/storage/coordinator.js +224 -0
- package/dist/src/storage/startup-lock.js +71 -0
- package/dist/src/storage/store.js +167 -0
- package/dist/src/tools/check-worker.js +81 -0
- package/dist/src/tools/checks.js +106 -0
- package/dist/src/tools/dns.js +248 -0
- package/dist/src/tools/http-contract.js +38 -0
- package/dist/src/tools/http.js +358 -0
- package/dist/src/tools/index.js +177 -0
- package/dist/src/tools/worker-check.js +73 -0
- package/dist/src/workspaces/git.js +227 -0
- package/dist/src/workspaces/index.js +715 -0
- package/examples/deployment.local.json +22 -0
- package/package.json +68 -4
- package/scripts/postinstall.mjs +25 -0
|
@@ -0,0 +1,1807 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { canonical, digest, jsonCopy } from '../broker/policy.js';
|
|
3
|
+
import { WorkspaceError } from '../workspaces/index.js';
|
|
4
|
+
import { CoordinatorError } from '../storage/coordinator.js';
|
|
5
|
+
import { ApiError, problem } from '../server/errors.js';
|
|
6
|
+
import { RunCommands, terminal } from './commands.js';
|
|
7
|
+
import { checkpoint, consumed, expired, status } from './clocks.js';
|
|
8
|
+
import { durationMs } from './timing.js';
|
|
9
|
+
import { limitsFor, mergeIncrease, validateIncrease } from './budgets.js';
|
|
10
|
+
import { BrokerProjection } from '../server/broker-handlers.js';
|
|
11
|
+
import { approvalWaitFor, brokerWorkId } from './drain-state.js';
|
|
12
|
+
const sha = (text) => `sha256:${createHash('sha256').update(text).digest('hex')}`;
|
|
13
|
+
const held = () => new ApiError(409, 'execution_held', 'Execution is held at a safe boundary.');
|
|
14
|
+
const criterionIds = (criteria) => criteria.map((_criterion, index) => `criterion_${index + 1}`);
|
|
15
|
+
const verifierSchema = {
|
|
16
|
+
type: 'object', required: ['decision', 'criteria'], additionalProperties: false,
|
|
17
|
+
properties: { decision: { enum: ['approve', 'revise'] }, guidance: { type: 'string' }, criteria: { type: 'array', items: {
|
|
18
|
+
type: 'object', required: ['criterionId', 'status', 'explanation'], additionalProperties: false,
|
|
19
|
+
properties: { criterionId: { type: 'string', minLength: 1 }, status: { enum: ['pass', 'fail'] },
|
|
20
|
+
explanation: { type: 'string', minLength: 1 }, evidenceArtifactIds: { type: 'array', items: { type: 'string' } } },
|
|
21
|
+
} } },
|
|
22
|
+
};
|
|
23
|
+
/** Durable single-run actor. Every await is outside SQL, and each run has one
|
|
24
|
+
* active transition. Different workspaces may progress independently. */
|
|
25
|
+
export class WorkflowEngine {
|
|
26
|
+
options;
|
|
27
|
+
commands;
|
|
28
|
+
projection;
|
|
29
|
+
#pending = new Set();
|
|
30
|
+
#running = new Set();
|
|
31
|
+
#actors = new Map();
|
|
32
|
+
#effects = new Map();
|
|
33
|
+
#effectSettlements = new Map();
|
|
34
|
+
#controllers = new Map();
|
|
35
|
+
#stopped = new Set();
|
|
36
|
+
#readProof = new Set();
|
|
37
|
+
#timer;
|
|
38
|
+
#closed = false;
|
|
39
|
+
#fatal;
|
|
40
|
+
constructor(options) {
|
|
41
|
+
this.options = options;
|
|
42
|
+
this.commands = options.commands;
|
|
43
|
+
this.projection = new BrokerProjection(this.commands.store, this.commands.options.broker, { work: id => this.work(id), onRunChangedSql: id => {
|
|
44
|
+
// Final approval release and current role state must commit together,
|
|
45
|
+
// before broker waiters attempt their already-authorized claim.
|
|
46
|
+
if (!this.store.get('runs', id).approvalWait.pendingApprovalIds.length)
|
|
47
|
+
this.approvalDrainSql(id);
|
|
48
|
+
this.updateClocks(id);
|
|
49
|
+
} });
|
|
50
|
+
options.driver.onResult((id, content) => this.result(id, content));
|
|
51
|
+
options.driver.onFailure((id, message) => this.failure(id, message));
|
|
52
|
+
}
|
|
53
|
+
get store() { return this.commands.store; }
|
|
54
|
+
get broker() { return this.commands.options.broker; }
|
|
55
|
+
work(runId) {
|
|
56
|
+
const sessions = this.store.list('sessions', { runId, limit: Number.MAX_SAFE_INTEGER }).map(row => row.value);
|
|
57
|
+
const rows = this.store.coordinator.db.prepare('SELECT id,state FROM broker_work WHERE run_id=?').all(runId);
|
|
58
|
+
const work = rows.map(row => {
|
|
59
|
+
const session = sessions.find(value => row.id.startsWith(`external:${value.id}:${value.epoch}:`));
|
|
60
|
+
return { id: brokerWorkId(row.id), kind: row.id.includes(':runtime-model:') ? 'agent_turn' : 'tool',
|
|
61
|
+
...(session ? { sessionId: session.id } : {}), description: row.state === 'uncertain' ? 'Work requires physical-stop reconciliation' : 'Broker-managed work' };
|
|
62
|
+
});
|
|
63
|
+
work.push(...[...this.#effects.values()].filter(value => value.runId === runId).map(value => value.value));
|
|
64
|
+
if (this.options.driver.activeWork(runId))
|
|
65
|
+
work.push({ id: 'runtime_process_barrier', kind: 'engine_transition', description: 'Runtime startup or physical-exit barrier' });
|
|
66
|
+
if (this.options.validation.activeWork(runId))
|
|
67
|
+
work.push({ id: 'validation_workers', kind: 'engine_transition', description: 'Pure validation workers awaiting physical exit' });
|
|
68
|
+
if (this.options.checks.activeWork(runId).length)
|
|
69
|
+
work.push({ id: 'trusted_checks', kind: 'engine_transition', description: 'Registered checks still physically active' });
|
|
70
|
+
if (this.options.schemas.activeWork(runId))
|
|
71
|
+
work.push({ id: 'schema_startup', kind: 'engine_transition', description: 'Schema graph startup' });
|
|
72
|
+
for (const job of this.options.workspaces.activeWork(runId))
|
|
73
|
+
if (!(this.#readProof.has(runId) && job.state === 'uncertain'))
|
|
74
|
+
work.push({ id: job.id, kind: 'engine_transition', description: job.state === 'uncertain' ? 'Workspace effect requires read-only reconciliation' : 'Workspace Git effect' });
|
|
75
|
+
return work;
|
|
76
|
+
}
|
|
77
|
+
quiet(runId) { return this.work(runId).length === 0; }
|
|
78
|
+
signal(runId) {
|
|
79
|
+
let controller = this.#controllers.get(runId);
|
|
80
|
+
if (!controller) {
|
|
81
|
+
controller = new AbortController();
|
|
82
|
+
this.#controllers.set(runId, controller);
|
|
83
|
+
}
|
|
84
|
+
return controller.signal;
|
|
85
|
+
}
|
|
86
|
+
async effect(runId, description, perform, sessionId) {
|
|
87
|
+
this.store.coordinator.assertOutsideTransaction();
|
|
88
|
+
if (this.#closed)
|
|
89
|
+
throw held();
|
|
90
|
+
const id = randomUUID();
|
|
91
|
+
let settle;
|
|
92
|
+
this.#effectSettlements.set(id, new Promise(resolve => { settle = resolve; }));
|
|
93
|
+
this.#effects.set(id, { runId, value: { id, kind: 'engine_transition', description, ...(sessionId ? { sessionId } : {}) } });
|
|
94
|
+
try {
|
|
95
|
+
return await perform();
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
this.#effects.delete(id);
|
|
99
|
+
this.#effectSettlements.delete(id);
|
|
100
|
+
settle();
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
wake(runId) {
|
|
104
|
+
this.store.coordinator.assertOutsideTransaction();
|
|
105
|
+
if (this.#closed || this.#fatal)
|
|
106
|
+
return;
|
|
107
|
+
const run = this.store.find('runs', runId);
|
|
108
|
+
if (!run)
|
|
109
|
+
return;
|
|
110
|
+
const plan = this.commands.plan(runId);
|
|
111
|
+
if (plan.cancelOperationId || terminal(run)) {
|
|
112
|
+
this.#controllers.get(runId)?.abort();
|
|
113
|
+
void this.stopSessions(runId).catch(error => { this.#fatal = error; });
|
|
114
|
+
}
|
|
115
|
+
this.#pending.add(runId);
|
|
116
|
+
queueMicrotask(() => { void this.pump(); });
|
|
117
|
+
}
|
|
118
|
+
start() {
|
|
119
|
+
this.store.coordinator.assertOutsideTransaction();
|
|
120
|
+
if (this.#timer)
|
|
121
|
+
throw new Error('engine_already_started');
|
|
122
|
+
this.#timer = setInterval(() => {
|
|
123
|
+
if (this.#closed || this.#fatal)
|
|
124
|
+
return;
|
|
125
|
+
try {
|
|
126
|
+
for (const row of this.store.coordinator.db.prepare("SELECT id FROM engine_resources WHERE kind='runs' AND (json_extract(body,'$.state') NOT IN ('succeeded','failed','cancelled') OR json_extract(body,'$.state') IN ('failed','cancelled') AND id NOT IN (SELECT id FROM engine_private WHERE scope='lease_released'))").all()) {
|
|
127
|
+
const run = this.store.get('runs', row.id), plan = this.commands.plan(row.id);
|
|
128
|
+
if (!terminal(run) && !plan.cancelOperationId)
|
|
129
|
+
this.deadlines(row.id);
|
|
130
|
+
if (!plan.cancelOperationId && run.executionControl.status === 'pausing')
|
|
131
|
+
this.pause(row.id);
|
|
132
|
+
this.wake(row.id);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
catch (error) {
|
|
136
|
+
this.#fatal = error;
|
|
137
|
+
}
|
|
138
|
+
}, 100);
|
|
139
|
+
this.#timer.unref();
|
|
140
|
+
}
|
|
141
|
+
async close() {
|
|
142
|
+
this.#closed = true;
|
|
143
|
+
if (this.#timer)
|
|
144
|
+
clearInterval(this.#timer);
|
|
145
|
+
for (const controller of this.#controllers.values())
|
|
146
|
+
controller.abort();
|
|
147
|
+
const ids = this.store.coordinator.db.prepare("SELECT id FROM engine_resources WHERE kind='runs'").all();
|
|
148
|
+
this.store.coordinator.atomic(() => {
|
|
149
|
+
for (const { id } of ids)
|
|
150
|
+
for (const { value: session } of this.store.list('sessions', { runId: id, limit: Number.MAX_SAFE_INTEGER })) {
|
|
151
|
+
const authority = this.store.private('session_authority', session.id);
|
|
152
|
+
// Shutdown destroys the preserved conversation. Revoke unused authority
|
|
153
|
+
// before waiting on runtime invocations; pending approval is not an
|
|
154
|
+
// executing effect. Consumed effects still retain their own barriers.
|
|
155
|
+
if (authority && this.commands.current(session.id, session.epoch))
|
|
156
|
+
this.broker.fenceSession(authority.binding);
|
|
157
|
+
this.commands.options.auth.revokeSession(session.id);
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
for (const { id } of ids)
|
|
161
|
+
await this.stopSessions(id);
|
|
162
|
+
await Promise.allSettled([...this.#actors.values()]);
|
|
163
|
+
await Promise.allSettled([...this.#effectSettlements.values()]);
|
|
164
|
+
}
|
|
165
|
+
async pump() {
|
|
166
|
+
for (const runId of this.#pending) {
|
|
167
|
+
if (this.#running.has(runId) || this.#closed || this.#fatal)
|
|
168
|
+
continue;
|
|
169
|
+
this.#pending.delete(runId);
|
|
170
|
+
this.#running.add(runId);
|
|
171
|
+
const actor = this.drive(runId).catch(error => this.handleError(runId, error)).finally(() => {
|
|
172
|
+
this.#running.delete(runId);
|
|
173
|
+
this.#actors.delete(runId);
|
|
174
|
+
if (this.#pending.has(runId) && !this.#closed && !this.#fatal)
|
|
175
|
+
queueMicrotask(() => { void this.pump(); });
|
|
176
|
+
});
|
|
177
|
+
this.#actors.set(runId, actor);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
gate(runId, allowBlocks = false, replaceUnderApprovalWait = false) {
|
|
181
|
+
if (this.#closed)
|
|
182
|
+
throw held();
|
|
183
|
+
const run = this.store.get('runs', runId), plan = this.commands.plan(runId);
|
|
184
|
+
if (terminal(run) || plan.cancelOperationId || run.executionControl.status !== 'running' ||
|
|
185
|
+
!allowBlocks && run.pendingBlockIds.length || run.approvalWait.status !== 'none' &&
|
|
186
|
+
!(replaceUnderApprovalWait && this.quiet(runId)))
|
|
187
|
+
throw held();
|
|
188
|
+
if (expired(plan.clock, this.commands.now()))
|
|
189
|
+
throw new ApiError(409, 'deadline_exceeded', 'Workflow allowance is exhausted.');
|
|
190
|
+
const step = plan.steps[plan.ordinal], stepClock = step && plan.stepClocks[step.id];
|
|
191
|
+
if (stepClock && expired(stepClock, this.commands.now()))
|
|
192
|
+
throw new ApiError(409, 'deadline_exceeded', 'Step allowance is exhausted.');
|
|
193
|
+
}
|
|
194
|
+
absoluteDeadline(plan, stepId = plan.steps[plan.ordinal]?.id) {
|
|
195
|
+
if (stepId !== plan.steps[plan.ordinal]?.id)
|
|
196
|
+
throw new Error('deadline_step_binding_mismatch');
|
|
197
|
+
const run = plan.clock.deadlineAt, step = stepId === undefined ? undefined : plan.stepClocks[stepId]?.deadlineAt;
|
|
198
|
+
return run === undefined ? step ?? null : step === undefined ? run : Math.min(run, step);
|
|
199
|
+
}
|
|
200
|
+
/** Join the clock/ordinal mutation. Only the current step can have live
|
|
201
|
+
* sessions; accept fences the old sessions before advancing. Recompute from
|
|
202
|
+
* absolute clocks, never from the previous gate or a relative role budget. */
|
|
203
|
+
syncBrokerDeadlineSql(runId, plan, stepId = plan.steps[plan.ordinal]?.id) {
|
|
204
|
+
const result = this.store.coordinator.db.prepare("UPDATE broker_runs SET body=json_set(body,'$.deadlineAt',?) WHERE id=?")
|
|
205
|
+
.run(this.absoluteDeadline(plan, stepId), runId);
|
|
206
|
+
if (result.changes !== 1)
|
|
207
|
+
throw new Error('broker_run_gate_missing');
|
|
208
|
+
}
|
|
209
|
+
/** Authority-only resolver also serves already-admitted effects. Admission
|
|
210
|
+
* gates are checked separately before a new trusted tool preparation. */
|
|
211
|
+
context(binding) {
|
|
212
|
+
if (!this.commands.current(binding.sessionId, binding.epoch))
|
|
213
|
+
throw new ApiError(409, 'stale_epoch', 'Session is stale.');
|
|
214
|
+
const authority = this.store.private('session_authority', binding.sessionId);
|
|
215
|
+
const session = this.store.get('sessions', binding.sessionId), lease = this.options.workspaces.lease(binding.runId);
|
|
216
|
+
if (authority.binding.profileVersionId !== binding.profileVersionId || authority.binding.role !== binding.role ||
|
|
217
|
+
session.instructionSnapshotId !== session.effectiveConfiguration.instructionSnapshotId || lease.id !== authority.leaseId || lease.state !== 'active')
|
|
218
|
+
throw new ApiError(409, 'stale_assignment', 'Session assignment is stale.');
|
|
219
|
+
return { binding, leaseId: lease.id, workspaceId: authority.workspaceId, instructionSnapshotId: session.instructionSnapshotId,
|
|
220
|
+
...(authority.workspaceRevisionId ? { workspaceRevisionId: authority.workspaceRevisionId } : {}) };
|
|
221
|
+
}
|
|
222
|
+
toolAdmission(binding) {
|
|
223
|
+
this.context(binding);
|
|
224
|
+
this.gate(binding.runId);
|
|
225
|
+
const session = this.store.get('sessions', binding.sessionId), authority = this.store.private('session_authority', session.id);
|
|
226
|
+
if (session.state !== 'running' || expired(authority.clock, this.commands.now()) ||
|
|
227
|
+
session.limits.maxSubmissions !== undefined && session.submissionsUsed >= session.limits.maxSubmissions ||
|
|
228
|
+
this.commands.plan(binding.runId).reset && authority.phase === 'work')
|
|
229
|
+
throw held();
|
|
230
|
+
}
|
|
231
|
+
async drive(runId) {
|
|
232
|
+
let run = this.store.get('runs', runId), plan = this.commands.plan(runId);
|
|
233
|
+
if (plan.cancelOperationId) {
|
|
234
|
+
await this.cancel(runId);
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
if (terminal(run)) {
|
|
238
|
+
await this.finish(runId);
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
if (this.deadlines(runId))
|
|
242
|
+
return;
|
|
243
|
+
this.projection.refresh(runId);
|
|
244
|
+
await this.extendGrace(runId);
|
|
245
|
+
this.approvalDrain(runId);
|
|
246
|
+
run = this.store.get('runs', runId);
|
|
247
|
+
if (run.executionControl.status === 'pausing') {
|
|
248
|
+
this.pause(runId);
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
if (run.executionControl.status === 'resuming') {
|
|
252
|
+
await this.resume(runId);
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
if (run.executionControl.status === 'paused')
|
|
256
|
+
return;
|
|
257
|
+
if (plan.recoveryOperationId) {
|
|
258
|
+
await this.recover(runId);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
if (run.state === 'interrupted')
|
|
262
|
+
return;
|
|
263
|
+
// Explicit continuation may retire the replaced role's unused approvals.
|
|
264
|
+
// Only this quiescent administrative transition can cross the wait; normal
|
|
265
|
+
// agents, tools, Git and unrelated pending approvals keep their gates.
|
|
266
|
+
if (plan.queuedDecisions[0]?.decision.kind === 'replace_profile' && this.quiet(runId)) {
|
|
267
|
+
await this.decisions(runId);
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
if (run.approvalWait.status !== 'none') {
|
|
271
|
+
this.updateClocks(runId);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
if (plan.queuedDecisions.length) {
|
|
275
|
+
await this.decisions(runId);
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
if (run.pendingBlockIds.length) {
|
|
279
|
+
this.updateClocks(runId);
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
this.gate(runId);
|
|
283
|
+
this.updateClocks(runId);
|
|
284
|
+
plan = this.commands.plan(runId);
|
|
285
|
+
if (plan.stage === 'startup')
|
|
286
|
+
await this.startup(runId);
|
|
287
|
+
else if (plan.stage === 'evaluate')
|
|
288
|
+
await this.evaluate(runId);
|
|
289
|
+
else if (plan.stage === 'accept')
|
|
290
|
+
await this.accept(runId);
|
|
291
|
+
else if (plan.stage === 'reset' || plan.stage === 'handoff')
|
|
292
|
+
await this.reset(runId);
|
|
293
|
+
else if (plan.stage === 'complete')
|
|
294
|
+
await this.finish(runId);
|
|
295
|
+
else if (plan.stage === 'worker' && !plan.steps[plan.ordinal].baselineId)
|
|
296
|
+
await this.startStep(runId);
|
|
297
|
+
else
|
|
298
|
+
await this.agent(runId, plan.stage === 'verify' ? 'verifier' : 'worker');
|
|
299
|
+
}
|
|
300
|
+
async startup(runId) {
|
|
301
|
+
let plan = this.commands.plan(runId);
|
|
302
|
+
this.gate(runId);
|
|
303
|
+
if (!plan.graph) {
|
|
304
|
+
const version = this.store.get('workflow_versions', this.store.get('runs', runId).workflowVersionId), policy = this.store.get('runs', runId).policy;
|
|
305
|
+
const loaded = await this.effect(runId, 'Resolve and pin complete schema graph', () => this.options.schemas.load(version, this.options.checks.list().map(check => check.name), { operationId: runId, signal: this.signal(runId),
|
|
306
|
+
...(plan.clock.deadlineAt === undefined ? {} : { deadlineAt: plan.clock.deadlineAt }),
|
|
307
|
+
timeout: policy.schemaFetchTimeout ?? '30s', retryDelays: policy.schemaFetchRetryDelays ?? ['1s', '2s'],
|
|
308
|
+
beforeFetch: () => this.gate(runId), onPinnedSql: resource => {
|
|
309
|
+
const id = createHash('sha256').update(`${runId}\0${resource.uri}`).digest('hex');
|
|
310
|
+
this.store.put('artifacts', { id, runId, kind: 'schema_snapshot', document: resource.document,
|
|
311
|
+
contentDigest: sha(resource.document.content), state: 'accepted', createdAt: new Date(this.commands.now()).toISOString() }, { runId, immutable: true });
|
|
312
|
+
this.store.event(runId, 'schema_resolved', 'artifact', id, { uri: resource.uri });
|
|
313
|
+
} }));
|
|
314
|
+
if (!loaded.report.valid || !loaded.graph)
|
|
315
|
+
throw new ApiError(422, 'invalid_schema_graph', 'Complete schema graph validation failed.', false, loaded.report.issues);
|
|
316
|
+
plan = this.commands.plan(runId);
|
|
317
|
+
plan.graph = loaded.graph;
|
|
318
|
+
this.commands.savePlan(runId, plan);
|
|
319
|
+
}
|
|
320
|
+
this.gate(runId);
|
|
321
|
+
if (!plan.workspaceInstructions) {
|
|
322
|
+
this.options.workspaces.assertKnown(runId);
|
|
323
|
+
const snapshots = this.options.pins.assemble(runId, plan.definition, plan.steps), workspace = this.options.workspaceInstructions(runId);
|
|
324
|
+
this.options.workspaces.assertKnown(runId);
|
|
325
|
+
this.store.coordinator.atomic(() => {
|
|
326
|
+
plan = this.commands.plan(runId);
|
|
327
|
+
for (const snapshot of snapshots) {
|
|
328
|
+
this.store.put('snapshots', snapshot, { runId, parentId: snapshot.stepExecutionId, immutable: true });
|
|
329
|
+
plan.steps.find(step => step.id === snapshot.stepExecutionId).profiles[snapshot.role].snapshotId = snapshot.id;
|
|
330
|
+
this.store.event(runId, 'instruction_snapshot_created', 'instruction_snapshot', snapshot.id, { role: snapshot.role, stepExecutionId: snapshot.stepExecutionId });
|
|
331
|
+
}
|
|
332
|
+
plan.workspaceInstructions = workspace;
|
|
333
|
+
this.commands.savePlan(runId, plan);
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
plan = this.commands.plan(runId);
|
|
337
|
+
for (const step of plan.steps)
|
|
338
|
+
for (const role of ['worker', 'verifier', 'handoff']) {
|
|
339
|
+
const pin = step.profiles[role];
|
|
340
|
+
if (!pin)
|
|
341
|
+
continue;
|
|
342
|
+
const key = `${step.id}:${role}`;
|
|
343
|
+
if (this.store.private('effective_configuration', key))
|
|
344
|
+
continue;
|
|
345
|
+
this.gate(runId);
|
|
346
|
+
const profile = this.store.get('profile_versions', pin.profileVersionId);
|
|
347
|
+
const result = await this.effect(runId, 'Compile pinned effective permissions', () => this.options.validation.run({
|
|
348
|
+
kind: 'effective_permissions', profile: profile.definition.permissions, deployment: this.options.deploymentPolicy,
|
|
349
|
+
role, configuredTools: profile.definition.tools.map(tool => tool.toolId)
|
|
350
|
+
}, { runId, signal: this.signal(runId) }));
|
|
351
|
+
if (!result.valid || !result.effectivePolicy)
|
|
352
|
+
throw new ApiError(422, 'invalid_effective_permissions', 'Effective permissions cannot be compiled.', false, result.errors);
|
|
353
|
+
const configuration = { profileVersionId: profile.id, role, definition: profile.definition, instructionSnapshotId: pin.snapshotId,
|
|
354
|
+
deploymentPolicyDigest: digest(this.options.deploymentPolicy), effectivePermissions: result.effectivePolicy };
|
|
355
|
+
this.store.setPrivate('effective_configuration', key, { ...configuration, contentDigest: digest(configuration) });
|
|
356
|
+
}
|
|
357
|
+
this.gate(runId);
|
|
358
|
+
if (!this.store.private('run_baseline', runId))
|
|
359
|
+
this.options.workspaces.baseline(runId, 'run_start', undefined, {
|
|
360
|
+
onAdmittedSql: baseline => { this.store.put('baselines', baseline, { runId, immutable: true }); this.store.setPrivate('run_baseline', runId, { id: baseline.id }); }
|
|
361
|
+
});
|
|
362
|
+
await this.startStep(runId);
|
|
363
|
+
}
|
|
364
|
+
async startStep(runId) {
|
|
365
|
+
this.gate(runId);
|
|
366
|
+
let plan = this.commands.plan(runId);
|
|
367
|
+
if (plan.ordinal >= plan.steps.length) {
|
|
368
|
+
plan.stage = 'complete';
|
|
369
|
+
this.commands.savePlan(runId, plan);
|
|
370
|
+
await this.finish(runId);
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
const stepPlan = plan.steps[plan.ordinal], definition = plan.definition.steps[plan.ordinal], now = this.commands.now();
|
|
374
|
+
if (!plan.stepClocks[stepPlan.id])
|
|
375
|
+
plan.stepClocks[stepPlan.id] = { consumedMs: 0, changedAt: now, running: true,
|
|
376
|
+
...(definition.timeout ? { deadlineAt: now + durationMs(definition.timeout.duration) } : {}) };
|
|
377
|
+
this.store.coordinator.atomic(() => {
|
|
378
|
+
this.commands.savePlan(runId, plan);
|
|
379
|
+
this.syncBrokerDeadlineSql(runId, plan);
|
|
380
|
+
});
|
|
381
|
+
if (!stepPlan.baselineId)
|
|
382
|
+
this.options.workspaces.baseline(runId, 'step_start', stepPlan.id, { onAdmittedSql: baseline => {
|
|
383
|
+
plan = this.commands.plan(runId);
|
|
384
|
+
plan.steps[plan.ordinal].baselineId = baseline.id;
|
|
385
|
+
this.commands.savePlan(runId, plan);
|
|
386
|
+
this.store.put('baselines', baseline, { runId, immutable: true });
|
|
387
|
+
this.store.put('steps', { ...this.store.get('steps', stepPlan.id), baselineId: baseline.id }, { runId });
|
|
388
|
+
} });
|
|
389
|
+
this.store.coordinator.atomic(() => {
|
|
390
|
+
const current = this.commands.plan(runId), step = current.steps[current.ordinal];
|
|
391
|
+
if (step.reentry) {
|
|
392
|
+
current.reset = { ...step.reentry.reset, id: randomUUID(), reason: 'rollback_reentry', role: 'worker',
|
|
393
|
+
...(step.reentry.oldSessionId ? { oldSessionId: step.reentry.oldSessionId } : {}) };
|
|
394
|
+
if (step.reentry.oldSessionId)
|
|
395
|
+
step.workerSessionId = step.reentry.oldSessionId;
|
|
396
|
+
}
|
|
397
|
+
current.stage = step.reentry ? 'reset' : 'worker';
|
|
398
|
+
this.commands.savePlan(runId, current);
|
|
399
|
+
this.commands.updateRun(runId, { state: step.reentry ? 'resetting' : 'running', currentStepId: stepPlan.id });
|
|
400
|
+
this.stepState(runId, step.reentry ? 'resetting' : 'running');
|
|
401
|
+
});
|
|
402
|
+
this.wake(runId);
|
|
403
|
+
}
|
|
404
|
+
stepState(runId, state) {
|
|
405
|
+
const plan = this.commands.plan(runId), step = this.store.get('steps', plan.steps[plan.ordinal].id);
|
|
406
|
+
if (step.state === state)
|
|
407
|
+
return;
|
|
408
|
+
this.store.put('steps', { ...step, state }, { runId });
|
|
409
|
+
this.store.event(runId, 'step_state_changed', 'step_execution', step.id, { state });
|
|
410
|
+
}
|
|
411
|
+
setSession(sessionId, state) {
|
|
412
|
+
const session = this.store.get('sessions', sessionId), authority = this.store.private('session_authority', sessionId);
|
|
413
|
+
authority.clock = checkpoint(authority.clock, state === 'running', this.commands.now());
|
|
414
|
+
this.store.setPrivate('session_authority', sessionId, authority);
|
|
415
|
+
this.store.put('sessions', { ...session, state, timing: status(authority.clock, ['terminated', 'completed'].includes(state), this.commands.now()) }, { runId: session.runId, parentId: session.stepExecutionId });
|
|
416
|
+
if (state !== session.state)
|
|
417
|
+
this.store.event(session.runId, 'session_state_changed', 'session', sessionId, { state });
|
|
418
|
+
}
|
|
419
|
+
roleLimits(plan, role) {
|
|
420
|
+
const step = plan.steps[plan.ordinal], limits = limitsFor(plan.definition.steps[plan.ordinal], role, plan.budgetOverrides?.[step.id]);
|
|
421
|
+
const charges = role === 'verifier' ? step.verificationCharges : role === 'handoff' ? plan.reset?.handoffCharges ?? 0 : 0;
|
|
422
|
+
const elapsed = role === 'verifier' ? step.verificationConsumedMs : role === 'handoff' ? plan.reset?.handoffConsumedMs ?? 0 : 0;
|
|
423
|
+
if (limits.maxSubmissions !== undefined) {
|
|
424
|
+
if (limits.maxSubmissions <= charges)
|
|
425
|
+
throw new ApiError(409, 'session_budget_exhausted', 'The role episode has no remaining attempts.');
|
|
426
|
+
limits.maxSubmissions -= charges;
|
|
427
|
+
}
|
|
428
|
+
if (limits.executionTimeLimit) {
|
|
429
|
+
const remaining = durationMs(limits.executionTimeLimit) - elapsed;
|
|
430
|
+
if (remaining <= 0)
|
|
431
|
+
throw new ApiError(409, 'session_budget_exhausted', 'The role episode has no remaining execution time.');
|
|
432
|
+
limits.executionTimeLimit = `${Math.ceil(remaining)}ms`;
|
|
433
|
+
}
|
|
434
|
+
return limits;
|
|
435
|
+
}
|
|
436
|
+
async launch(runId, role) {
|
|
437
|
+
this.gate(runId);
|
|
438
|
+
if (!this.quiet(runId))
|
|
439
|
+
throw held();
|
|
440
|
+
const plan = this.commands.plan(runId), step = plan.steps[plan.ordinal], pin = step.profiles[role];
|
|
441
|
+
if (!pin?.snapshotId || !plan.workspaceInstructions)
|
|
442
|
+
throw new Error('profile_or_instruction_pins_missing');
|
|
443
|
+
const effective = this.store.private('effective_configuration', `${step.id}:${role}`);
|
|
444
|
+
if (!effective || effective.profileVersionId !== pin.profileVersionId || effective.instructionSnapshotId !== pin.snapshotId)
|
|
445
|
+
throw new Error('effective_configuration_pin_mismatch');
|
|
446
|
+
const profile = this.store.get('profile_versions', pin.profileVersionId), lease = this.options.workspaces.lease(runId);
|
|
447
|
+
const id = randomUUID(), limits = this.roleLimits(plan, role), now = this.commands.now();
|
|
448
|
+
const binding = { sessionId: id, runId, stepExecutionId: step.id, epoch: 1, role, profileVersionId: profile.id,
|
|
449
|
+
configuredTools: profile.definition.tools.map(tool => tool.toolId), permissions: profile.definition.permissions, deploymentPermissions: jsonCopy(this.options.deploymentPolicy) };
|
|
450
|
+
const candidate = step.candidateId ? this.store.get('submissions', step.candidateId) : undefined;
|
|
451
|
+
const phase = role === 'verifier' ? 'verification' : role === 'handoff' ? 'handoff' : 'work';
|
|
452
|
+
const root = plan.graph.roots.find(value => value.stepId === plan.definition.steps[plan.ordinal].id && value.kind === (role === 'handoff' ? 'handoff' : 'exit'));
|
|
453
|
+
const schema = role === 'verifier' ? verifierSchema : plan.graph.resources.find(value => value.uri === root?.uri)?.schema;
|
|
454
|
+
if (schema === undefined || typeof schema !== 'boolean' && (!schema || typeof schema !== 'object' || Array.isArray(schema)))
|
|
455
|
+
throw new Error('output_schema_pin_missing');
|
|
456
|
+
const inputArtifacts = this.store.coordinator.db.prepare("SELECT id FROM engine_resources WHERE kind='artifacts' AND run_id=? AND json_extract(body,'$.state')='accepted' ORDER BY seq").all(runId);
|
|
457
|
+
const inputArtifactIds = [...new Set([...inputArtifacts.map(value => value.id), ...(candidate ? [candidate.artifactId] : [])])];
|
|
458
|
+
const history = this.store.coordinator.db.prepare("SELECT MAX(seq) AS value FROM engine_resources WHERE kind='tool_history' AND run_id=?").get(runId);
|
|
459
|
+
const through = history.value ?? 0, historyLimit = phase === 'handoff' ? plan.definition.steps[plan.ordinal].handoffArtifact.historyLimit : 100;
|
|
460
|
+
const earliest = this.store.coordinator.db.prepare("SELECT seq FROM engine_resources WHERE kind='tool_history' AND run_id=? ORDER BY seq DESC LIMIT 1 OFFSET ?").get(runId, Math.max(0, historyLimit - 1));
|
|
461
|
+
const sessionClock = { consumedMs: 0, changedAt: now, running: true,
|
|
462
|
+
...(limits.executionTimeLimit ? { limitMs: durationMs(limits.executionTimeLimit) } : {}) };
|
|
463
|
+
const session = { id, runId, stepExecutionId: step.id, role, state: 'running', epoch: 1, limits, submissionsUsed: 0,
|
|
464
|
+
infrastructureAttemptCharges: 0, timing: status(sessionClock), createdAt: new Date(now).toISOString(), profileVersionId: profile.id,
|
|
465
|
+
instructionSnapshotId: pin.snapshotId, effectiveConfiguration: effective };
|
|
466
|
+
const authority = { binding, workspaceId: lease.workspaceId, leaseId: lease.id, outputSchema: schema,
|
|
467
|
+
inputArtifactIds, phase, clock: sessionClock, logicalOperationId: randomUUID(), infrastructureFailures: 0, lastSubmissionConsumedMs: 0,
|
|
468
|
+
retryEpisodeId: role === 'verifier' ? `verification_${candidate.id}` : role === 'handoff' ? `handoff_${step.id}_${this.store.get('steps', step.id).resetsUsed}` : randomUUID(),
|
|
469
|
+
...(role === 'verifier' ? { subjectSubmissionId: candidate.id, workspaceRevisionId: candidate.workspaceRevision.id } : {}) };
|
|
470
|
+
const snapshot = this.store.get('snapshots', pin.snapshotId), workspace = this.options.workspaces.get(lease.workspaceId);
|
|
471
|
+
const assignment = { session, workspace, instructions: snapshot.assembledText, inputArtifactIds,
|
|
472
|
+
permissions: { projectWrite: role !== 'verifier', scratchPaths: workspace.scratchPaths }, outputSchema: schema,
|
|
473
|
+
instructionSnapshot: snapshot, executionGate: 'open',
|
|
474
|
+
...(candidate?.workspaceRevision ? { workspaceRevision: candidate.workspaceRevision } : { workspaceRevision: this.options.workspaces.revision(lease.knownRevisionId) }),
|
|
475
|
+
...(role === 'verifier' ? { subjectSubmissionId: candidate.id } : {}) };
|
|
476
|
+
this.store.coordinator.atomic(() => {
|
|
477
|
+
this.gate(runId);
|
|
478
|
+
this.broker.registerSession(binding, this.absoluteDeadline(plan, binding.stepExecutionId));
|
|
479
|
+
this.syncBrokerDeadlineSql(runId, plan, binding.stepExecutionId);
|
|
480
|
+
this.store.put('sessions', session, { runId, parentId: step.id });
|
|
481
|
+
this.store.setPrivate('session_authority', id, authority);
|
|
482
|
+
this.commands.retries.begin(authority.retryEpisodeId, authority.logicalOperationId);
|
|
483
|
+
this.store.setPrivate('assignments', id, assignment);
|
|
484
|
+
this.store.setPrivate('session_access', id, { runId, inputArtifactIds, historyAfterSeq: Math.max(0, (earliest?.seq ?? 1) - 1), historyThroughSeq: through });
|
|
485
|
+
const current = this.commands.plan(runId);
|
|
486
|
+
if (role === 'worker') {
|
|
487
|
+
current.steps[current.ordinal].workerSessionId = id;
|
|
488
|
+
if (current.reset?.role === 'worker' && !current.reset.replacementSessionId) {
|
|
489
|
+
const execution = this.store.get('steps', step.id);
|
|
490
|
+
if (execution.resetsUsed >= execution.maxSessionResets)
|
|
491
|
+
throw new ApiError(409, 'session_budget_exhausted', 'The worker reset allowance is exhausted.');
|
|
492
|
+
this.store.put('steps', { ...execution, resetsUsed: execution.resetsUsed + 1 }, { runId });
|
|
493
|
+
current.reset.replacementSessionId = id;
|
|
494
|
+
delete current.steps[current.ordinal].reentry;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
else
|
|
498
|
+
current.steps[current.ordinal].auxiliarySessionId = id;
|
|
499
|
+
this.commands.savePlan(runId, current);
|
|
500
|
+
this.store.put('steps', { ...this.store.get('steps', step.id), activeSessionId: id }, { runId });
|
|
501
|
+
this.store.event(runId, 'session_started', 'session', id, { role, profileVersionId: profile.id, instructionSnapshotId: pin.snapshotId });
|
|
502
|
+
});
|
|
503
|
+
await this.effect(runId, 'Start fresh contained provider conversation', () => this.options.driver.start({
|
|
504
|
+
session, assignment, binding, workspaceInstructions: plan.workspaceInstructions
|
|
505
|
+
}), id);
|
|
506
|
+
return id;
|
|
507
|
+
}
|
|
508
|
+
async agent(runId, role) {
|
|
509
|
+
this.gate(runId);
|
|
510
|
+
let plan = this.commands.plan(runId), step = plan.steps[plan.ordinal];
|
|
511
|
+
if (role === 'verifier' && step.verifierRetirementId) {
|
|
512
|
+
const retiring = step.verifierRetirementId;
|
|
513
|
+
await this.closeSession(retiring);
|
|
514
|
+
this.gate(runId);
|
|
515
|
+
plan = this.commands.plan(runId);
|
|
516
|
+
step = plan.steps[plan.ordinal];
|
|
517
|
+
if (step.auxiliarySessionId === retiring)
|
|
518
|
+
delete step.auxiliarySessionId;
|
|
519
|
+
delete step.verifierRetirementId;
|
|
520
|
+
this.commands.savePlan(runId, plan);
|
|
521
|
+
this.wake(runId);
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
let id = role === 'worker' ? step.workerSessionId : step.auxiliarySessionId;
|
|
525
|
+
if (!id)
|
|
526
|
+
id = await this.launch(runId, role);
|
|
527
|
+
this.gate(runId);
|
|
528
|
+
plan = this.commands.plan(runId);
|
|
529
|
+
step = plan.steps[plan.ordinal];
|
|
530
|
+
const session = this.store.get('sessions', id), authority = this.store.private('session_authority', id);
|
|
531
|
+
if (this.options.driver.active(id)) {
|
|
532
|
+
this.options.driver.flush(id);
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
if (!this.options.driver.alive(id)) {
|
|
536
|
+
this.interrupt(runId);
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
if (expired(authority.clock, this.commands.now()) || session.limits.maxSubmissions !== undefined && session.submissionsUsed >= session.limits.maxSubmissions) {
|
|
540
|
+
this.setSession(id, 'exhausted');
|
|
541
|
+
if (role === 'worker') {
|
|
542
|
+
plan.reset = { reason: 'worker_exhausted', role: 'worker', oldSessionId: id };
|
|
543
|
+
plan.stage = 'reset';
|
|
544
|
+
this.commands.savePlan(runId, plan);
|
|
545
|
+
this.wake(runId);
|
|
546
|
+
}
|
|
547
|
+
else
|
|
548
|
+
this.commands.block(runId, 'verification_failed', 'The verifier episode allowance is exhausted.', ['increase_budgets', 'replace_profile', 'rollback']);
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
if (session.state !== 'running')
|
|
552
|
+
return;
|
|
553
|
+
const prior = this.store.private('execution_failure', authority.logicalOperationId);
|
|
554
|
+
if (role === 'verifier' && prior && !prior.retry) {
|
|
555
|
+
this.commands.block(runId, 'verification_failed', 'The shared verifier execution retry allowance is exhausted.', ['increase_budgets', 'replace_profile', 'rollback']);
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
if (role === 'verifier' && prior?.retry) {
|
|
559
|
+
step.verifierRetirementId = id;
|
|
560
|
+
this.commands.savePlan(runId, plan);
|
|
561
|
+
this.wake(runId);
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
if (this.store.private('execution_completion', authority.logicalOperationId) || prior) {
|
|
565
|
+
if (role === 'worker' && (this.store.private('execution_completion', authority.logicalOperationId) || prior?.chargeAttempt))
|
|
566
|
+
authority.retryEpisodeId = randomUUID();
|
|
567
|
+
authority.logicalOperationId = randomUUID();
|
|
568
|
+
this.store.coordinator.atomic(() => { this.store.setPrivate('session_authority', id, authority); this.commands.retries.begin(authority.retryEpisodeId, authority.logicalOperationId); });
|
|
569
|
+
}
|
|
570
|
+
await this.effect(runId, 'Admit one bounded agent turn', () => this.options.driver.turn(id, this.prompt(id)), id);
|
|
571
|
+
}
|
|
572
|
+
prompt(sessionId) {
|
|
573
|
+
const session = this.store.get('sessions', sessionId), authority = this.store.private('session_authority', sessionId);
|
|
574
|
+
const plan = this.commands.plan(session.runId), step = plan.definition.steps[plan.ordinal];
|
|
575
|
+
const byteCount = this.store.coordinator.db.prepare("SELECT COALESCE(SUM(length(CAST(body AS BLOB))),0) AS n FROM engine_resources WHERE kind='artifacts' AND id IN (SELECT value FROM json_each(?))")
|
|
576
|
+
.get(JSON.stringify(authority.inputArtifactIds));
|
|
577
|
+
if (byteCount.n > (this.options.maxContextBytes ?? 67_108_864))
|
|
578
|
+
throw new ApiError(422, 'assignment_context_limit', 'Assigned artifact context exceeds the configured runtime bound.');
|
|
579
|
+
const artifacts = authority.inputArtifactIds.map(id => this.store.get('artifacts', id));
|
|
580
|
+
const ids = criterionIds(step.exitCriteria.semantic?.criteria ?? []);
|
|
581
|
+
const format = session.effectiveConfiguration.definition.runtime.options?.artifactFormat === 'yaml' ? 'YAML' : 'JSON';
|
|
582
|
+
return `Perform only the current assigned ${authority.phase} task. Use only the broker tools. Return ONLY the ${format} output document, without Markdown fences. Do not submit HTTP envelopes or claim Git authority.\n` +
|
|
583
|
+
(authority.phase === 'verification' ? 'Check every assigned criterion against the exact artifact and pinned live workspace revision. approve requires ALL pass. revise requires actionable guidance. Project edits are forbidden.\n' : '') +
|
|
584
|
+
JSON.stringify({ workflowStepId: step.id, name: step.name ?? step.id, outputSchema: authority.outputSchema, phase: authority.phase,
|
|
585
|
+
criteria: (step.exitCriteria.semantic?.criteria ?? []).map((description, index) => ({ criterionId: ids[index], description })),
|
|
586
|
+
...(authority.subjectSubmissionId ? { subjectSubmissionId: authority.subjectSubmissionId, workspaceRevisionId: authority.workspaceRevisionId } : {}),
|
|
587
|
+
artifacts: artifacts.map(value => ({ id: value.id, kind: value.kind, document: value.document, contentDigest: value.contentDigest })),
|
|
588
|
+
schemaResources: plan.graph.resources });
|
|
589
|
+
}
|
|
590
|
+
adapterContext(sessionId, body, key) {
|
|
591
|
+
const session = this.store.get('sessions', sessionId), authority = this.store.private('session_authority', sessionId);
|
|
592
|
+
return { requestId: key, signal: this.signal(session.runId), principal: { id: `adapter_${sessionId}`, audience: 'adapter', sessionId,
|
|
593
|
+
epoch: session.epoch, role: session.role, workspaceIds: [authority.workspaceId] }, params: { sessionId }, query: {}, body,
|
|
594
|
+
header: name => name === 'idempotency-key' ? key : undefined };
|
|
595
|
+
}
|
|
596
|
+
async result(sessionId, content) {
|
|
597
|
+
if (this.#closed)
|
|
598
|
+
return;
|
|
599
|
+
const session = this.store.get('sessions', sessionId);
|
|
600
|
+
if (!this.commands.current(sessionId, session.epoch))
|
|
601
|
+
return;
|
|
602
|
+
const authority = this.store.private('session_authority', sessionId);
|
|
603
|
+
const mediaType = session.effectiveConfiguration.definition.runtime.options?.artifactFormat === 'yaml' ? 'application/yaml' : 'application/json';
|
|
604
|
+
const document = { mediaType, content }, kind = authority.phase === 'work' ? 'exit' : authority.phase === 'verification' ? 'verdict' : 'handoff';
|
|
605
|
+
const lease = this.options.workspaces.lease(session.runId);
|
|
606
|
+
const body = kind === 'exit' ? { artifact: document, observedHeadCommit: this.options.workspaces.revision(lease.knownRevisionId).headCommit } :
|
|
607
|
+
kind === 'verdict' ? { report: document, subjectSubmissionId: authority.subjectSubmissionId, workspaceRevisionId: authority.workspaceRevisionId } : { artifact: document };
|
|
608
|
+
const envelope = await this.effect(session.runId, 'Validate adapter completion envelope', () => this.options.validation.run({
|
|
609
|
+
kind: 'wire', schema: kind === 'exit' ? 'ExitSubmissionCreate' : kind === 'verdict' ? 'VerificationVerdictCreate' : 'HandoffSubmissionCreate', value: body
|
|
610
|
+
}, { runId: session.runId, signal: this.signal(session.runId) }), sessionId);
|
|
611
|
+
if (!envelope.valid)
|
|
612
|
+
throw new ApiError(400, 'invalid_adapter_envelope', 'Runtime completion envelope is invalid.', false, envelope.errors);
|
|
613
|
+
if (this.#closed)
|
|
614
|
+
return;
|
|
615
|
+
this.commands.submit(this.adapterContext(sessionId, body, `turn_${authority.logicalOperationId}`), kind);
|
|
616
|
+
}
|
|
617
|
+
async failure(sessionId, message) {
|
|
618
|
+
if (this.#closed)
|
|
619
|
+
return;
|
|
620
|
+
const session = this.store.find('sessions', sessionId);
|
|
621
|
+
if (!session || !this.commands.current(sessionId, session.epoch))
|
|
622
|
+
return;
|
|
623
|
+
const authority = this.store.private('session_authority', sessionId);
|
|
624
|
+
this.commands.failure(this.adapterContext(sessionId, { clientFailureId: `failure_${authority.logicalOperationId}`, category: 'runtime', message }, `failure_${authority.logicalOperationId}`));
|
|
625
|
+
if (!this.options.driver.alive(sessionId) && !this.commands.plan(session.runId).cancelOperationId)
|
|
626
|
+
this.interrupt(session.runId);
|
|
627
|
+
}
|
|
628
|
+
async evaluate(runId) {
|
|
629
|
+
this.gate(runId);
|
|
630
|
+
if (!this.quiet(runId))
|
|
631
|
+
return;
|
|
632
|
+
let plan = this.commands.plan(runId);
|
|
633
|
+
const id = plan.pendingSubmissionId;
|
|
634
|
+
if (!id)
|
|
635
|
+
throw new Error('pending_submission_missing');
|
|
636
|
+
let submission = this.store.get('submissions', id);
|
|
637
|
+
const artifact = this.store.get('artifacts', submission.artifactId), step = plan.definition.steps[plan.ordinal];
|
|
638
|
+
if (submission.kind === 'exit' && !submission.workspaceRevision) {
|
|
639
|
+
const revision = this.options.workspaces.captureRevision(runId);
|
|
640
|
+
submission = { ...submission, workspaceRevision: revision, state: 'validating' };
|
|
641
|
+
this.store.put('submissions', submission, { runId, parentId: submission.sessionId });
|
|
642
|
+
const expected = this.store.private('submission_metadata', id);
|
|
643
|
+
if (revision.headCommit !== expected.observedHeadCommit)
|
|
644
|
+
throw new WorkspaceError('git_expected_head_conflict');
|
|
645
|
+
}
|
|
646
|
+
const decoded = artifact.document.mediaType === 'text/plain' ? { valid: true, value: artifact.document.content, errors: [] } :
|
|
647
|
+
await this.effect(runId, 'Decode admitted artifact', () => this.options.validation.run({ kind: 'decode', content: artifact.document.content,
|
|
648
|
+
format: artifact.document.mediaType === 'application/json' ? 'json' : 'yaml' }, { runId, signal: this.signal(runId) }));
|
|
649
|
+
this.gate(runId);
|
|
650
|
+
if (!decoded.valid) {
|
|
651
|
+
await this.reject(runId, submission, decoded.errors);
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
654
|
+
if (submission.kind === 'verdict') {
|
|
655
|
+
const authority = this.store.private('session_authority', submission.sessionId);
|
|
656
|
+
this.options.workspaces.assertRevision(runId, authority.workspaceRevisionId);
|
|
657
|
+
const validated = await this.effect(runId, 'Validate verifier correspondence and evidence', () => this.options.validation.run({
|
|
658
|
+
kind: 'verdict', value: decoded.value, criterionIds: criterionIds(step.exitCriteria.semantic.criteria), evidenceArtifactIds: authority.inputArtifactIds
|
|
659
|
+
}, { runId, signal: this.signal(runId) }));
|
|
660
|
+
this.gate(runId);
|
|
661
|
+
if (!validated.valid) {
|
|
662
|
+
await this.reject(runId, submission, validated.errors);
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
const report = validated.value;
|
|
666
|
+
this.store.coordinator.atomic(() => {
|
|
667
|
+
this.store.put('submissions', { ...submission, state: 'accepted' }, { runId, parentId: submission.sessionId });
|
|
668
|
+
this.store.put('artifacts', { ...artifact, state: 'accepted' }, { runId });
|
|
669
|
+
this.store.event(runId, 'submission_evaluated', 'submission', submission.id, { decision: report.decision });
|
|
670
|
+
});
|
|
671
|
+
await this.closeSession(submission.sessionId);
|
|
672
|
+
plan = this.commands.plan(runId);
|
|
673
|
+
delete plan.pendingSubmissionId;
|
|
674
|
+
delete plan.steps[plan.ordinal].auxiliarySessionId;
|
|
675
|
+
if (report.decision === 'approve')
|
|
676
|
+
plan.stage = 'accept';
|
|
677
|
+
else {
|
|
678
|
+
const candidate = this.store.get('submissions', plan.steps[plan.ordinal].candidateId);
|
|
679
|
+
this.store.put('submissions', { ...candidate, state: 'rejected', validationIssues: [{ code: 'semantic_revision', message: report.guidance }] }, { runId, parentId: candidate.sessionId });
|
|
680
|
+
this.store.put('artifacts', { ...this.store.get('artifacts', candidate.artifactId), state: 'rejected' }, { runId });
|
|
681
|
+
const guidance = { id: randomUUID(), runId, stepExecutionId: candidate.stepExecutionId, kind: 'guidance',
|
|
682
|
+
document: { mediaType: 'text/plain', content: report.guidance }, contentDigest: sha(report.guidance), state: 'accepted', createdAt: new Date(this.commands.now()).toISOString() };
|
|
683
|
+
this.store.put('artifacts', guidance, { runId, immutable: true });
|
|
684
|
+
plan.stage = 'worker';
|
|
685
|
+
this.addInput(plan.steps[plan.ordinal].workerSessionId, guidance.id);
|
|
686
|
+
this.setSession(plan.steps[plan.ordinal].workerSessionId, 'running');
|
|
687
|
+
this.commands.updateRun(runId, { state: 'running' });
|
|
688
|
+
this.stepState(runId, 'running');
|
|
689
|
+
}
|
|
690
|
+
this.store.coordinator.atomic(() => { this.commands.savePlan(runId, plan); this.broker.setHold(runId, 'submission', false); });
|
|
691
|
+
this.wake(runId);
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
const root = plan.graph.roots.find(value => value.stepId === step.id && value.kind === (submission.kind === 'handoff' ? 'handoff' : 'exit'));
|
|
695
|
+
const checked = await this.effect(runId, 'Validate mandatory artifact schema', () => this.options.validation.run({
|
|
696
|
+
kind: 'artifact', rootUri: root.uri, resources: plan.graph.resources, value: decoded.value
|
|
697
|
+
}, { runId, signal: this.signal(runId) }));
|
|
698
|
+
this.gate(runId);
|
|
699
|
+
if (!checked.valid) {
|
|
700
|
+
await this.reject(runId, submission, checked.errors);
|
|
701
|
+
return;
|
|
702
|
+
}
|
|
703
|
+
if (submission.kind === 'handoff') {
|
|
704
|
+
this.store.coordinator.atomic(() => {
|
|
705
|
+
const current = this.commands.plan(runId);
|
|
706
|
+
if (!current.reset)
|
|
707
|
+
throw new Error('handoff_reset_missing');
|
|
708
|
+
current.reset.handoffId = artifact.id;
|
|
709
|
+
current.stage = 'reset';
|
|
710
|
+
delete current.pendingSubmissionId;
|
|
711
|
+
this.commands.savePlan(runId, current);
|
|
712
|
+
this.store.put('submissions', { ...submission, state: 'accepted' }, { runId, parentId: submission.sessionId });
|
|
713
|
+
this.store.put('artifacts', { ...artifact, state: 'accepted' }, { runId });
|
|
714
|
+
this.broker.setHold(runId, 'submission', false);
|
|
715
|
+
});
|
|
716
|
+
this.wake(runId);
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
if (!await this.checks(runId, submission, decoded.value))
|
|
720
|
+
return;
|
|
721
|
+
this.gate(runId);
|
|
722
|
+
this.store.coordinator.atomic(() => {
|
|
723
|
+
const current = this.commands.plan(runId), currentStep = current.steps[current.ordinal];
|
|
724
|
+
currentStep.candidateId = submission.id;
|
|
725
|
+
currentStep.verificationCharges = 0;
|
|
726
|
+
currentStep.verificationConsumedMs = 0;
|
|
727
|
+
delete current.pendingSubmissionId;
|
|
728
|
+
current.stage = step.exitCriteria.semantic?.criteria.length ? 'verify' : 'accept';
|
|
729
|
+
this.commands.savePlan(runId, current);
|
|
730
|
+
this.store.put('submissions', { ...submission, state: 'verifying' }, { runId, parentId: submission.sessionId });
|
|
731
|
+
this.commands.updateRun(runId, { state: 'verifying' });
|
|
732
|
+
this.stepState(runId, 'verifying');
|
|
733
|
+
this.broker.setHold(runId, 'submission', false);
|
|
734
|
+
});
|
|
735
|
+
this.wake(runId);
|
|
736
|
+
}
|
|
737
|
+
async checks(runId, submission, decoded) {
|
|
738
|
+
const plan = this.commands.plan(runId), step = plan.definition.steps[plan.ordinal], artifact = this.store.get('artifacts', submission.artifactId);
|
|
739
|
+
const failures = [];
|
|
740
|
+
for (const name of step.exitCriteria.deterministic?.checks ?? []) {
|
|
741
|
+
this.gate(runId);
|
|
742
|
+
const key = `${submission.id}:${name}`, prior = this.store.private('check_result', key);
|
|
743
|
+
if (prior) {
|
|
744
|
+
if (prior.status === 'fail')
|
|
745
|
+
failures.push({ code: 'named_check_failed', message: prior.explanation, path: name });
|
|
746
|
+
continue;
|
|
747
|
+
}
|
|
748
|
+
const check = this.options.checks.get(name);
|
|
749
|
+
if (!check)
|
|
750
|
+
throw new ApiError(422, 'unknown_named_check', 'A required check is unavailable.');
|
|
751
|
+
const episode = `verification_${submission.id}`, operation = randomUUID();
|
|
752
|
+
this.commands.retries.begin(episode, operation);
|
|
753
|
+
this.store.setPrivate('check_intent', key, { operationId: operation, episodeId: episode, state: 'started' });
|
|
754
|
+
const result = await this.effect(runId, 'Execute registered deterministic check', () => check.execute({ runId,
|
|
755
|
+
stepExecutionId: submission.stepExecutionId, leaseId: this.options.workspaces.lease(runId).id,
|
|
756
|
+
workspaceRevisionId: submission.workspaceRevision.id, artifactId: artifact.id,
|
|
757
|
+
artifact: { mediaType: artifact.document.mediaType, content: artifact.document.content, decoded },
|
|
758
|
+
deadlineAt: Math.min(this.commands.now() + 30_000, plan.clock.deadlineAt ?? Infinity, plan.stepClocks[submission.stepExecutionId]?.deadlineAt ?? Infinity) }, this.signal(runId)));
|
|
759
|
+
if (result.status === 'infrastructure_error') {
|
|
760
|
+
const retry = this.commands.retries.failure(episode, operation, { category: 'infrastructure', verifier: true, alreadyCharged: true,
|
|
761
|
+
infrastructureRetries: this.store.get('runs', runId).policy.infrastructureRetries ?? 3,
|
|
762
|
+
verificationRetries: this.store.get('runs', runId).policy.verificationRetries ?? 3 });
|
|
763
|
+
this.store.setPrivate('check_intent', key, { operationId: operation, episodeId: episode, state: 'failed' });
|
|
764
|
+
if (!retry.retry || !result.retryable)
|
|
765
|
+
this.commands.block(runId, 'verification_failed', 'A mandatory deterministic check could not execute within its retry allowance.', ['increase_budgets', 'rollback']);
|
|
766
|
+
else
|
|
767
|
+
this.wake(runId);
|
|
768
|
+
return false;
|
|
769
|
+
}
|
|
770
|
+
this.store.setPrivate('check_result', key, result);
|
|
771
|
+
this.store.setPrivate('check_intent', key, { operationId: operation, episodeId: episode, state: 'done' });
|
|
772
|
+
if (result.status === 'fail')
|
|
773
|
+
failures.push({ code: 'named_check_failed', message: result.explanation, path: name });
|
|
774
|
+
}
|
|
775
|
+
if (failures.length) {
|
|
776
|
+
await this.reject(runId, submission, failures);
|
|
777
|
+
return false;
|
|
778
|
+
}
|
|
779
|
+
return true;
|
|
780
|
+
}
|
|
781
|
+
async reject(runId, submission, issues) {
|
|
782
|
+
const artifact = this.store.get('artifacts', submission.artifactId);
|
|
783
|
+
let plan = this.commands.plan(runId);
|
|
784
|
+
this.store.coordinator.atomic(() => {
|
|
785
|
+
this.store.put('submissions', { ...submission, state: 'rejected', validationIssues: issues }, { runId, parentId: submission.sessionId });
|
|
786
|
+
this.store.put('artifacts', { ...artifact, state: 'rejected' }, { runId });
|
|
787
|
+
this.store.event(runId, 'submission_evaluated', 'submission', submission.id, { state: 'rejected', issues });
|
|
788
|
+
});
|
|
789
|
+
const session = this.store.get('sessions', submission.sessionId), authority = this.store.private('session_authority', session.id);
|
|
790
|
+
if (submission.kind === 'verdict') {
|
|
791
|
+
const retry = this.commands.retries.failure(authority.retryEpisodeId, authority.logicalOperationId, { category: 'verification_execution',
|
|
792
|
+
verifier: true, alreadyCharged: true, infrastructureRetries: this.store.get('runs', runId).policy.infrastructureRetries ?? 3,
|
|
793
|
+
verificationRetries: this.store.get('runs', runId).policy.verificationRetries ?? 3 });
|
|
794
|
+
await this.closeSession(session.id);
|
|
795
|
+
plan = this.commands.plan(runId);
|
|
796
|
+
delete plan.steps[plan.ordinal].auxiliarySessionId;
|
|
797
|
+
plan.stage = 'verify';
|
|
798
|
+
if (!retry.retry)
|
|
799
|
+
this.commands.block(runId, 'verification_failed', 'Verifier execution retry allowance is exhausted.', ['increase_budgets', 'replace_profile', 'rollback']);
|
|
800
|
+
}
|
|
801
|
+
else if (submission.kind === 'handoff') {
|
|
802
|
+
plan.stage = 'handoff';
|
|
803
|
+
this.setSession(session.id, 'running');
|
|
804
|
+
const current = this.store.private('session_authority', session.id);
|
|
805
|
+
if (expired(current.clock, this.commands.now()) || session.limits.maxSubmissions !== undefined && session.submissionsUsed >= session.limits.maxSubmissions)
|
|
806
|
+
this.commands.block(runId, 'handoff_failed', 'The mandatory handoff could not be produced within the original bounded allowance.', ['increase_budgets', 'replace_profile']);
|
|
807
|
+
}
|
|
808
|
+
else {
|
|
809
|
+
plan.stage = 'worker';
|
|
810
|
+
this.setSession(session.id, 'running');
|
|
811
|
+
}
|
|
812
|
+
delete plan.pendingSubmissionId;
|
|
813
|
+
this.store.coordinator.atomic(() => {
|
|
814
|
+
this.commands.savePlan(runId, plan);
|
|
815
|
+
this.broker.setHold(runId, 'submission', false);
|
|
816
|
+
const content = issues.map(issue => `${issue.code}: ${issue.message}`).join('\n');
|
|
817
|
+
const guidance = { id: randomUUID(), runId, kind: 'guidance', stepExecutionId: submission.stepExecutionId,
|
|
818
|
+
document: { mediaType: 'text/plain', content }, contentDigest: sha(content), state: 'accepted', createdAt: new Date(this.commands.now()).toISOString() };
|
|
819
|
+
this.store.put('artifacts', guidance, { runId, immutable: true });
|
|
820
|
+
this.addInput(session.id, guidance.id);
|
|
821
|
+
});
|
|
822
|
+
this.wake(runId);
|
|
823
|
+
}
|
|
824
|
+
addInput(sessionId, artifactId) {
|
|
825
|
+
const authority = this.store.private('session_authority', sessionId);
|
|
826
|
+
if (!authority.inputArtifactIds.includes(artifactId))
|
|
827
|
+
authority.inputArtifactIds.push(artifactId);
|
|
828
|
+
this.store.setPrivate('session_authority', sessionId, authority);
|
|
829
|
+
const assignment = this.store.private('assignments', sessionId);
|
|
830
|
+
if (assignment)
|
|
831
|
+
this.store.setPrivate('assignments', sessionId, { ...assignment, inputArtifactIds: authority.inputArtifactIds });
|
|
832
|
+
const access = this.store.private('session_access', sessionId);
|
|
833
|
+
this.store.setPrivate('session_access', sessionId, { ...access, inputArtifactIds: authority.inputArtifactIds });
|
|
834
|
+
}
|
|
835
|
+
async closeSession(id) {
|
|
836
|
+
const session = this.store.get('sessions', id), authority = this.store.private('session_authority', id);
|
|
837
|
+
this.store.coordinator.atomic(() => {
|
|
838
|
+
if (this.commands.current(id, session.epoch))
|
|
839
|
+
this.broker.fenceSession(authority.binding);
|
|
840
|
+
this.commands.options.auth.revokeSession(id);
|
|
841
|
+
if (!this.store.private('session_time_accounted', id)) {
|
|
842
|
+
const elapsed = consumed(authority.clock, this.commands.now()), plan = this.commands.plan(session.runId);
|
|
843
|
+
if (session.role === 'verifier')
|
|
844
|
+
plan.steps.find(value => value.id === session.stepExecutionId).verificationConsumedMs += elapsed;
|
|
845
|
+
if (session.role === 'handoff' && plan.reset)
|
|
846
|
+
plan.reset.handoffConsumedMs = (plan.reset.handoffConsumedMs ?? 0) + elapsed;
|
|
847
|
+
this.commands.savePlan(session.runId, plan);
|
|
848
|
+
this.store.setPrivate('session_time_accounted', id, { elapsed });
|
|
849
|
+
}
|
|
850
|
+
this.setSession(id, 'terminated');
|
|
851
|
+
});
|
|
852
|
+
await this.effect(session.runId, 'Wait for managed runtime physical exit', () => this.options.driver.stop(id), id);
|
|
853
|
+
this.#stopped.add(id);
|
|
854
|
+
}
|
|
855
|
+
async stopSessions(runId) {
|
|
856
|
+
for (const row of this.store.list('sessions', { runId, limit: Number.MAX_SAFE_INTEGER })) {
|
|
857
|
+
await this.options.driver.stop(row.value.id);
|
|
858
|
+
this.#stopped.add(row.value.id);
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
async accept(runId) {
|
|
862
|
+
this.gate(runId);
|
|
863
|
+
const plan = this.commands.plan(runId), step = plan.steps[plan.ordinal], submission = this.store.get('submissions', step.candidateId);
|
|
864
|
+
for (const id of [step.auxiliarySessionId, step.workerSessionId])
|
|
865
|
+
if (id)
|
|
866
|
+
await this.closeSession(id);
|
|
867
|
+
this.gate(runId);
|
|
868
|
+
if (!this.quiet(runId))
|
|
869
|
+
return;
|
|
870
|
+
const artifact = this.store.get('artifacts', submission.artifactId);
|
|
871
|
+
this.options.workspaces.accept({ runId, stepExecutionId: step.id, artifactId: artifact.id, revisionId: submission.workspaceRevision.id,
|
|
872
|
+
expectedHead: submission.workspaceRevision.headCommit }, { onAdmittedSql: job => {
|
|
873
|
+
this.store.setPrivate('workspace_continuation', job.id, { kind: 'accept', submissionId: submission.id, stepId: step.id });
|
|
874
|
+
}, onCompletedSql: job => this.workspaceCompleted(job) });
|
|
875
|
+
this.wake(runId);
|
|
876
|
+
}
|
|
877
|
+
workspaceCompleted(job) {
|
|
878
|
+
if (this.store.private('workspace_completion', job.id))
|
|
879
|
+
return;
|
|
880
|
+
const continuation = this.store.private('workspace_continuation', job.id);
|
|
881
|
+
if (!continuation)
|
|
882
|
+
throw new Error('workspace_continuation_missing');
|
|
883
|
+
const plan = this.commands.plan(job.runId);
|
|
884
|
+
if (continuation.kind === 'accept') {
|
|
885
|
+
const submission = this.store.get('submissions', continuation.submissionId), artifact = this.store.get('artifacts', submission.artifactId);
|
|
886
|
+
const eligible = submission.state !== 'superseded' && plan.steps[plan.ordinal]?.id === continuation.stepId;
|
|
887
|
+
this.store.put('submissions', { ...submission, state: eligible ? 'accepted' : 'superseded' }, { runId: job.runId, parentId: submission.sessionId });
|
|
888
|
+
this.store.put('artifacts', { ...artifact, state: eligible ? 'accepted' : 'superseded', commit: job.commit }, { runId: job.runId });
|
|
889
|
+
if (eligible) {
|
|
890
|
+
const step = this.store.get('steps', continuation.stepId), stepClock = plan.stepClocks[step.id];
|
|
891
|
+
if (stepClock)
|
|
892
|
+
plan.stepClocks[step.id] = checkpoint(stepClock, false, this.commands.now());
|
|
893
|
+
this.store.put('steps', { ...step, state: 'succeeded', acceptedSubmissionId: submission.id, acceptedCommit: job.commit,
|
|
894
|
+
...(stepClock ? { timing: status(plan.stepClocks[step.id], true, this.commands.now()) } : {}) }, { runId: job.runId });
|
|
895
|
+
plan.ordinal++;
|
|
896
|
+
plan.stage = plan.ordinal >= plan.steps.length ? 'complete' : 'worker';
|
|
897
|
+
}
|
|
898
|
+
this.store.event(job.runId, 'artifact_committed', 'artifact', artifact.id, { commit: job.commit, submissionId: submission.id });
|
|
899
|
+
}
|
|
900
|
+
else {
|
|
901
|
+
this.store.setPrivate('restore_completed', job.runId, { operationId: continuation.operationId ?? '', jobId: job.id });
|
|
902
|
+
}
|
|
903
|
+
this.commands.savePlan(job.runId, plan);
|
|
904
|
+
this.syncBrokerDeadlineSql(job.runId, plan);
|
|
905
|
+
this.store.setPrivate('workspace_completion', job.id, { completed: true });
|
|
906
|
+
}
|
|
907
|
+
operationState(id, state, code, blockId) {
|
|
908
|
+
const previous = this.store.get('operations', id);
|
|
909
|
+
const { error: _error, blockId: _block, ...base } = previous;
|
|
910
|
+
this.store.put('operations', { ...base, state, updatedAt: new Date(this.commands.now()).toISOString(),
|
|
911
|
+
...(code ? { error: problem(new ApiError(409, code, 'The operation could not complete in the current execution state.'), id) } : {}),
|
|
912
|
+
...(blockId ? { blockId } : {}), ...(state === 'succeeded' ? { result: { resourceType: 'run', resourceId: previous.runId } } : {}) }, { runId: previous.runId });
|
|
913
|
+
}
|
|
914
|
+
pause(runId) {
|
|
915
|
+
const work = this.work(runId), run = this.store.get('runs', runId), operationId = run.executionControl.pauseOperationId;
|
|
916
|
+
if (work.length) {
|
|
917
|
+
const grace = run.executionControl.graceDeadlineAt;
|
|
918
|
+
if (grace && this.commands.now() >= Date.parse(grace)) {
|
|
919
|
+
const block = this.commands.block(runId, 'pause_stalled', 'Active work did not drain before operator pause grace expired.', ['extend_pause_grace'], { hold: 'operator_pause' });
|
|
920
|
+
if (operationId)
|
|
921
|
+
this.operationState(operationId, 'waiting_for_decision', undefined, block.id);
|
|
922
|
+
}
|
|
923
|
+
if (canonical(work) !== canonical(run.executionControl.inFlightWork))
|
|
924
|
+
this.commands.updateRun(runId, { executionControl: { ...this.store.get('runs', runId).executionControl, inFlightWork: work } });
|
|
925
|
+
this.updateClocks(runId);
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
this.store.coordinator.atomic(() => {
|
|
929
|
+
const current = this.store.get('runs', runId);
|
|
930
|
+
for (const { value: session } of this.store.list('sessions', { runId, limit: Number.MAX_SAFE_INTEGER })) {
|
|
931
|
+
if (['starting', 'running', 'paused_for_verification', 'waiting_for_approval'].includes(session.state)) {
|
|
932
|
+
this.setSession(session.id, 'paused');
|
|
933
|
+
this.store.put('sessions', { ...this.store.get('sessions', session.id), suspendedState: session.state }, { runId, parentId: session.stepExecutionId });
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
this.commands.updateRun(runId, { state: 'paused', executionControl: { ...current.executionControl, status: 'paused',
|
|
937
|
+
pausedAt: new Date(this.commands.now()).toISOString(), inFlightWork: [] } });
|
|
938
|
+
this.updateClocks(runId);
|
|
939
|
+
if (operationId)
|
|
940
|
+
this.operationState(operationId, 'succeeded');
|
|
941
|
+
this.store.event(runId, 'pause_completed', 'run', runId, {});
|
|
942
|
+
});
|
|
943
|
+
}
|
|
944
|
+
async resume(runId) {
|
|
945
|
+
const operationId = this.store.private('resume_operation', runId).id;
|
|
946
|
+
let run = this.store.get('runs', runId), plan = this.commands.plan(runId);
|
|
947
|
+
const step = plan.steps[plan.ordinal];
|
|
948
|
+
// Recovery already stopped this retiring worker before recording its reset.
|
|
949
|
+
// Re-pausing that authorized transition must not demand its lost conversation
|
|
950
|
+
// again. Every other preserved session still requires the ordinary proof.
|
|
951
|
+
const reset = plan.reset, recovery = reset?.operationId ? this.store.find('operations', reset.operationId) : undefined;
|
|
952
|
+
const retiring = reset?.oldSessionId ? this.store.find('sessions', reset.oldSessionId) : undefined;
|
|
953
|
+
const authority = retiring ? this.store.private('session_authority', retiring.id) : undefined;
|
|
954
|
+
const retiringWorkerId = step && recovery && retiring && authority && reset?.id &&
|
|
955
|
+
reset.reason === 'recovery' && reset.interrupted === true && reset.role === 'worker' &&
|
|
956
|
+
!reset.replacementSessionId && reset.oldSessionId === step?.workerSessionId && step?.id === run.currentStepId &&
|
|
957
|
+
recovery?.id === reset.operationId && recovery.kind === 'recover' && recovery.runId === runId && recovery.state === 'running' &&
|
|
958
|
+
retiring?.id === reset.oldSessionId && retiring.role === 'worker' && retiring.runId === runId && retiring.stepExecutionId === step.id &&
|
|
959
|
+
authority?.binding.sessionId === retiring.id && authority.binding.runId === runId && authority.binding.stepExecutionId === step.id &&
|
|
960
|
+
authority.binding.role === 'worker' && authority.binding.epoch === retiring.epoch && authority.binding.profileVersionId === retiring.profileVersionId
|
|
961
|
+
? retiring.id : undefined;
|
|
962
|
+
const required = [step?.workerSessionId, step?.auxiliarySessionId].filter((id) => !!id)
|
|
963
|
+
.map(id => this.store.get('sessions', id)).filter(session => session.id !== retiringWorkerId && !['terminated', 'completed'].includes(session.state));
|
|
964
|
+
if (required.some(session => !this.options.driver.alive(session.id))) {
|
|
965
|
+
const block = this.commands.block(runId, 'resume_requires_recovery', 'A preserved provider conversation is missing. Explicit recovery is required.', [], { recoveryAllowed: true });
|
|
966
|
+
this.commands.updateRun(runId, { state: 'blocked', executionControl: { ...run.executionControl, status: 'paused' } });
|
|
967
|
+
this.operationState(operationId, 'failed', 'resume_requires_recovery', block.id);
|
|
968
|
+
this.store.event(runId, 'resume_blocked', 'operation', operationId, { blockId: block.id });
|
|
969
|
+
return;
|
|
970
|
+
}
|
|
971
|
+
if (run.pendingBlockIds.length) {
|
|
972
|
+
this.commands.updateRun(runId, { state: 'blocked', executionControl: { ...run.executionControl, status: 'paused' } });
|
|
973
|
+
this.operationState(operationId, 'failed', 'state_conflict', run.pendingBlockIds[0]);
|
|
974
|
+
return;
|
|
975
|
+
}
|
|
976
|
+
try {
|
|
977
|
+
this.options.workspaces.assertKnown(runId);
|
|
978
|
+
}
|
|
979
|
+
catch (error) {
|
|
980
|
+
this.commands.updateRun(runId, { state: 'blocked', executionControl: { ...run.executionControl, status: 'paused' } });
|
|
981
|
+
this.operationState(operationId, 'failed', 'state_conflict');
|
|
982
|
+
throw error;
|
|
983
|
+
}
|
|
984
|
+
this.store.coordinator.atomic(() => {
|
|
985
|
+
run = this.store.get('runs', runId);
|
|
986
|
+
plan = this.commands.plan(runId);
|
|
987
|
+
this.broker.setHold(runId, 'queued_decisions', plan.queuedDecisions.length > 0);
|
|
988
|
+
for (const session of required) {
|
|
989
|
+
if (session.state !== 'paused' || !session.suspendedState)
|
|
990
|
+
continue;
|
|
991
|
+
const state = session.suspendedState === 'running' || session.suspendedState === 'waiting_for_approval'
|
|
992
|
+
? run.approvalWait.status === 'none' ? 'running' : 'waiting_for_approval'
|
|
993
|
+
: session.suspendedState;
|
|
994
|
+
const { suspendedState: _old, ...rest } = session;
|
|
995
|
+
this.store.put('sessions', rest, { runId, parentId: session.stepExecutionId });
|
|
996
|
+
this.setSession(session.id, state);
|
|
997
|
+
}
|
|
998
|
+
this.commands.updateRun(runId, { state: run.executionControl.continuationState ?? 'running', executionControl: { status: 'running', inFlightWork: [] } });
|
|
999
|
+
this.broker.resume(runId);
|
|
1000
|
+
this.operationState(operationId, 'succeeded');
|
|
1001
|
+
this.updateClocks(runId);
|
|
1002
|
+
this.store.event(runId, 'resume_completed', 'operation', operationId, {});
|
|
1003
|
+
});
|
|
1004
|
+
if (!plan.queuedDecisions.length && run.approvalWait.status === 'none')
|
|
1005
|
+
for (const session of required)
|
|
1006
|
+
this.options.driver.flush(session.id);
|
|
1007
|
+
this.wake(runId);
|
|
1008
|
+
}
|
|
1009
|
+
async extendGrace(runId) {
|
|
1010
|
+
const plan = this.commands.plan(runId), selected = plan.queuedDecisions.filter(value => value.decision.kind === 'extend_pause_grace');
|
|
1011
|
+
if (!selected.length)
|
|
1012
|
+
return;
|
|
1013
|
+
this.store.coordinator.atomic(() => {
|
|
1014
|
+
for (const queued of selected) {
|
|
1015
|
+
if (queued.decision.kind !== 'extend_pause_grace')
|
|
1016
|
+
continue;
|
|
1017
|
+
const block = queued.blockId && this.store.get('blocks', queued.blockId), run = this.store.get('runs', runId);
|
|
1018
|
+
const deadline = new Date(this.commands.now() + durationMs(queued.decision.duration)).toISOString();
|
|
1019
|
+
if (block && block.hold === 'operator_pause' && run.executionControl.status === 'pausing') {
|
|
1020
|
+
this.commands.updateRun(runId, { executionControl: { ...run.executionControl, graceDeadlineAt: deadline } });
|
|
1021
|
+
if (run.executionControl.pauseOperationId)
|
|
1022
|
+
this.operationState(run.executionControl.pauseOperationId, 'running');
|
|
1023
|
+
}
|
|
1024
|
+
else if (block && block.hold === 'approval_wait' && run.approvalWait.status === 'draining')
|
|
1025
|
+
this.commands.updateRun(runId, { approvalWait: { ...run.approvalWait, graceDeadlineAt: deadline } });
|
|
1026
|
+
this.operationState(queued.operationId, 'succeeded');
|
|
1027
|
+
}
|
|
1028
|
+
const current = this.commands.plan(runId);
|
|
1029
|
+
current.queuedDecisions = current.queuedDecisions.filter(value => !selected.some(chosen => chosen.operationId === value.operationId));
|
|
1030
|
+
this.commands.savePlan(runId, current);
|
|
1031
|
+
});
|
|
1032
|
+
}
|
|
1033
|
+
approvalDrain(runId) {
|
|
1034
|
+
this.store.coordinator.atomic(() => this.approvalDrainSql(runId));
|
|
1035
|
+
}
|
|
1036
|
+
approvalDrainSql(runId) {
|
|
1037
|
+
let run = this.store.get('runs', runId);
|
|
1038
|
+
if (!run.approvalWait.pendingApprovalIds.length) {
|
|
1039
|
+
if (!terminal(run) && !this.commands.plan(runId).cancelOperationId &&
|
|
1040
|
+
run.executionControl.status === 'running' && !run.pendingBlockIds.length) {
|
|
1041
|
+
for (const { value: session } of this.store.list('sessions', { runId, limit: Number.MAX_SAFE_INTEGER }))
|
|
1042
|
+
if (session.state === 'waiting_for_approval' && this.commands.current(session.id, session.epoch))
|
|
1043
|
+
this.setSession(session.id, 'running');
|
|
1044
|
+
}
|
|
1045
|
+
return;
|
|
1046
|
+
}
|
|
1047
|
+
const work = this.work(runId), approvalWait = approvalWaitFor(run, run.approvalWait.pendingApprovalIds, work, this.commands.now());
|
|
1048
|
+
if (canonical(approvalWait) !== canonical(run.approvalWait))
|
|
1049
|
+
this.commands.updateRun(runId, { approvalWait });
|
|
1050
|
+
if (!work.length) {
|
|
1051
|
+
for (const { value: session } of this.store.list('sessions', { runId, limit: Number.MAX_SAFE_INTEGER }))
|
|
1052
|
+
if (session.state === 'running')
|
|
1053
|
+
this.setSession(session.id, 'waiting_for_approval');
|
|
1054
|
+
}
|
|
1055
|
+
else if (this.commands.now() >= Date.parse(approvalWait.graceDeadlineAt))
|
|
1056
|
+
this.commands.block(runId, 'pause_stalled', 'Active work did not drain before approval-wait grace expired.', ['extend_pause_grace'], { hold: 'approval_wait' });
|
|
1057
|
+
this.updateClocks(runId);
|
|
1058
|
+
}
|
|
1059
|
+
updateClocks(runId) {
|
|
1060
|
+
const run = this.store.get('runs', runId), plan = this.commands.plan(runId), now = this.commands.now();
|
|
1061
|
+
const stopped = terminal(run), paused = run.executionControl.status === 'paused';
|
|
1062
|
+
const blocked = run.pendingBlockIds.length > 0 || run.state === 'interrupted';
|
|
1063
|
+
const running = !stopped && !paused && run.approvalWait.status !== 'waiting' && (!blocked || plan.timingPolicy.blockedTimeAccounting === 'count');
|
|
1064
|
+
plan.clock = checkpoint(plan.clock, running, now);
|
|
1065
|
+
const current = plan.steps[plan.ordinal], stepClock = current && plan.stepClocks[current.id];
|
|
1066
|
+
if (stepClock)
|
|
1067
|
+
plan.stepClocks[current.id] = checkpoint(stepClock, running, now);
|
|
1068
|
+
this.commands.savePlan(runId, plan);
|
|
1069
|
+
const timing = status(plan.clock, stopped, now);
|
|
1070
|
+
if (timing.clockState !== run.timing.clockState || Math.abs(timing.executionConsumedMs - run.timing.executionConsumedMs) >= 1_000)
|
|
1071
|
+
this.commands.updateRun(runId, { timing });
|
|
1072
|
+
if (stepClock) {
|
|
1073
|
+
const step = this.store.get('steps', current.id), next = status(plan.stepClocks[current.id], stopped || step.state === 'succeeded', now);
|
|
1074
|
+
if (step.timing.clockState !== next.clockState || Math.abs(next.executionConsumedMs - step.timing.executionConsumedMs) >= 1_000)
|
|
1075
|
+
this.store.put('steps', { ...step, timing: next }, { runId });
|
|
1076
|
+
}
|
|
1077
|
+
for (const { value: session } of this.store.list('sessions', { runId, limit: Number.MAX_SAFE_INTEGER })) {
|
|
1078
|
+
if (['completed', 'terminated'].includes(session.state))
|
|
1079
|
+
continue;
|
|
1080
|
+
const authority = this.store.private('session_authority', session.id);
|
|
1081
|
+
if (!authority)
|
|
1082
|
+
continue;
|
|
1083
|
+
authority.clock = checkpoint(authority.clock, running && session.state === 'running', now);
|
|
1084
|
+
this.store.setPrivate('session_authority', session.id, authority);
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
deadlines(runId) {
|
|
1088
|
+
const plan = this.commands.plan(runId), now = this.commands.now(), step = plan.steps[plan.ordinal], definition = plan.definition.steps[plan.ordinal];
|
|
1089
|
+
const overall = expired(plan.clock, now), stepExpired = step && plan.stepClocks[step.id] && expired(plan.stepClocks[step.id], now);
|
|
1090
|
+
if (overall || stepExpired) {
|
|
1091
|
+
const policy = overall ? plan.definition.config?.timeout?.['on-timeout'] ?? 'fail' : definition?.timeout?.['on-timeout'] ?? 'block';
|
|
1092
|
+
this.broker.setHold(runId, 'deadline', true);
|
|
1093
|
+
this.#controllers.get(runId)?.abort();
|
|
1094
|
+
void this.stopSessions(runId).catch(error => { this.#fatal = error; });
|
|
1095
|
+
if (policy === 'fail') {
|
|
1096
|
+
this.commands.updateRun(runId, { state: 'failed', completedAt: new Date(now).toISOString() });
|
|
1097
|
+
this.wake(runId);
|
|
1098
|
+
}
|
|
1099
|
+
else
|
|
1100
|
+
this.commands.block(runId, 'deadline_exceeded', 'The workflow or step deadline is exhausted.', []);
|
|
1101
|
+
const resume = this.store.private('resume_operation', runId);
|
|
1102
|
+
if (resume && ['pending', 'running'].includes(this.store.get('operations', resume.id).state))
|
|
1103
|
+
this.operationState(resume.id, 'failed', 'deadline_exceeded');
|
|
1104
|
+
this.updateClocks(runId);
|
|
1105
|
+
return true;
|
|
1106
|
+
}
|
|
1107
|
+
if (!step || !definition)
|
|
1108
|
+
return false;
|
|
1109
|
+
for (const id of [step.workerSessionId, step.auxiliarySessionId]) {
|
|
1110
|
+
if (!id)
|
|
1111
|
+
continue;
|
|
1112
|
+
const session = this.store.get('sessions', id), authority = this.store.private('session_authority', id);
|
|
1113
|
+
if (session.state !== 'running')
|
|
1114
|
+
continue;
|
|
1115
|
+
if (expired(authority.clock, now)) {
|
|
1116
|
+
this.setSession(id, 'exhausted');
|
|
1117
|
+
void this.options.driver.stop(id).catch(error => { this.#fatal = error; });
|
|
1118
|
+
if (authority.phase === 'work') {
|
|
1119
|
+
plan.reset = { reason: 'worker_timeout', oldSessionId: id, role: 'worker', interrupted: true };
|
|
1120
|
+
plan.stage = 'reset';
|
|
1121
|
+
this.commands.savePlan(runId, plan);
|
|
1122
|
+
}
|
|
1123
|
+
else {
|
|
1124
|
+
const timeout = authority.phase === 'verification' ? definition.exitCriteria.semantic?.verifier.timeout : definition.handoffArtifact?.timeout;
|
|
1125
|
+
if (timeout?.['on-timeout'] === 'fail')
|
|
1126
|
+
this.commands.updateRun(runId, { state: 'failed', completedAt: new Date(now).toISOString() });
|
|
1127
|
+
else
|
|
1128
|
+
this.commands.block(runId, authority.phase === 'verification' ? 'verification_failed' : 'handoff_failed', 'The bounded role execution-time allowance is exhausted.', ['increase_budgets', 'replace_profile']);
|
|
1129
|
+
}
|
|
1130
|
+
this.wake(runId);
|
|
1131
|
+
return true;
|
|
1132
|
+
}
|
|
1133
|
+
const interval = plan.budgetOverrides?.[step.id]?.submissionInterval ?? definition.execution['submission-interval']?.duration;
|
|
1134
|
+
if (authority.phase === 'work' && interval && consumed(authority.clock, now) - authority.lastSubmissionConsumedMs >= durationMs(interval)) {
|
|
1135
|
+
this.commands.block(runId, 'submission_interval_expired', 'The worker submission interval expired.', ['increase_budgets', 'replace_profile']);
|
|
1136
|
+
this.updateClocks(runId);
|
|
1137
|
+
return true;
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
return false;
|
|
1141
|
+
}
|
|
1142
|
+
supersede(runId, role) {
|
|
1143
|
+
const plan = this.commands.plan(runId);
|
|
1144
|
+
const unaccepted = this.store.list('submissions', { runId, limit: Number.MAX_SAFE_INTEGER }).map(row => row.value)
|
|
1145
|
+
.filter(submission => submission.stepExecutionId === plan.steps[plan.ordinal]?.id && !['accepted', 'superseded'].includes(submission.state));
|
|
1146
|
+
const affected = new Set(unaccepted.filter(submission => !role || this.store.get('sessions', submission.sessionId).role === role)
|
|
1147
|
+
.map(submission => submission.id));
|
|
1148
|
+
if (role === 'worker')
|
|
1149
|
+
for (const submission of unaccepted) {
|
|
1150
|
+
if (submission.kind === 'verdict' && submission.subjectSubmissionId && affected.has(submission.subjectSubmissionId))
|
|
1151
|
+
affected.add(submission.id);
|
|
1152
|
+
}
|
|
1153
|
+
for (const submission of unaccepted) {
|
|
1154
|
+
if (!affected.has(submission.id))
|
|
1155
|
+
continue;
|
|
1156
|
+
this.store.put('submissions', { ...submission, state: 'superseded' }, { runId, parentId: submission.sessionId });
|
|
1157
|
+
const artifact = this.store.get('artifacts', submission.artifactId);
|
|
1158
|
+
this.store.put('artifacts', { ...artifact, state: 'superseded' }, { runId });
|
|
1159
|
+
if (plan.pendingSubmissionId === submission.id)
|
|
1160
|
+
delete plan.pendingSubmissionId;
|
|
1161
|
+
}
|
|
1162
|
+
if (!role || role === 'worker')
|
|
1163
|
+
delete plan.steps[plan.ordinal].candidateId;
|
|
1164
|
+
this.commands.savePlan(runId, plan);
|
|
1165
|
+
this.broker.setHold(runId, 'submission', !!plan.pendingSubmissionId);
|
|
1166
|
+
}
|
|
1167
|
+
async decisions(runId) {
|
|
1168
|
+
let plan = this.commands.plan(runId), queued = plan.queuedDecisions[0];
|
|
1169
|
+
const input = queued.decision, step = plan.steps[plan.ordinal], execution = this.store.get('steps', step.id), run = this.store.get('runs', runId);
|
|
1170
|
+
const decisionStepId = queued.stepExecutionId ?? (queued.blockId ? this.store.get('blocks', queued.blockId).stepExecutionId : undefined);
|
|
1171
|
+
if (decisionStepId && decisionStepId !== step.id) {
|
|
1172
|
+
this.operationState(queued.operationId, 'failed', 'state_conflict');
|
|
1173
|
+
plan.queuedDecisions.shift();
|
|
1174
|
+
this.commands.savePlan(runId, plan);
|
|
1175
|
+
this.broker.setHold(runId, 'queued_decisions', plan.queuedDecisions.length > 0);
|
|
1176
|
+
this.wake(runId);
|
|
1177
|
+
return;
|
|
1178
|
+
}
|
|
1179
|
+
this.gate(runId, true, input.kind === 'replace_profile');
|
|
1180
|
+
if (input.kind === 'extend_pause_grace')
|
|
1181
|
+
return;
|
|
1182
|
+
this.operationState(queued.operationId, 'running');
|
|
1183
|
+
if (input.kind === 'increase_budgets') {
|
|
1184
|
+
validateIncrease(run, execution, plan.definition.steps[plan.ordinal], plan.budgetOverrides?.[step.id] ?? {}, input.budgets, step.workerSessionId ? this.store.get('sessions', step.workerSessionId) : undefined);
|
|
1185
|
+
this.store.coordinator.atomic(() => {
|
|
1186
|
+
plan = this.commands.plan(runId);
|
|
1187
|
+
plan.budgetOverrides ??= {};
|
|
1188
|
+
plan.budgetOverrides[step.id] = mergeIncrease(plan.budgetOverrides[step.id] ?? {}, input.budgets);
|
|
1189
|
+
this.commands.savePlan(runId, plan);
|
|
1190
|
+
this.store.put('steps', { ...execution, ...(input.budgets.maxSessionResets === undefined ? {} : { maxSessionResets: input.budgets.maxSessionResets }) }, { runId });
|
|
1191
|
+
const policy = { ...run.policy,
|
|
1192
|
+
...(input.budgets.infrastructureRetries === undefined ? {} : { infrastructureRetries: input.budgets.infrastructureRetries }),
|
|
1193
|
+
...(input.budgets.verificationRetries === undefined ? {} : { verificationRetries: input.budgets.verificationRetries }) };
|
|
1194
|
+
this.commands.updateRun(runId, { policy });
|
|
1195
|
+
for (const id of [step.workerSessionId, step.auxiliarySessionId]) {
|
|
1196
|
+
if (!id)
|
|
1197
|
+
continue;
|
|
1198
|
+
const session = this.store.get('sessions', id), authority = this.store.private('session_authority', id);
|
|
1199
|
+
const total = limitsFor(plan.definition.steps[plan.ordinal], session.role, plan.budgetOverrides[step.id]);
|
|
1200
|
+
const retired = session.role === 'verifier' ? step.verificationCharges - session.submissionsUsed :
|
|
1201
|
+
session.role === 'handoff' ? (plan.reset?.handoffCharges ?? 0) - session.submissionsUsed : 0;
|
|
1202
|
+
const retiredTime = session.role === 'verifier' ? step.verificationConsumedMs : session.role === 'handoff' ? plan.reset?.handoffConsumedMs ?? 0 : 0;
|
|
1203
|
+
const limits = { ...total, ...(total.maxSubmissions === undefined ? {} : { maxSubmissions: total.maxSubmissions - Math.max(0, retired) }),
|
|
1204
|
+
...(total.executionTimeLimit ? { executionTimeLimit: `${Math.max(0, durationMs(total.executionTimeLimit) - retiredTime)}ms` } : {}) };
|
|
1205
|
+
if (limits.executionTimeLimit)
|
|
1206
|
+
authority.clock.limitMs = durationMs(limits.executionTimeLimit);
|
|
1207
|
+
this.store.setPrivate('session_authority', id, authority);
|
|
1208
|
+
this.store.put('sessions', { ...session, limits }, { runId, parentId: session.stepExecutionId });
|
|
1209
|
+
if (session.state === 'exhausted' && this.options.driver.alive(id) && !expired(authority.clock, this.commands.now()) &&
|
|
1210
|
+
(limits.maxSubmissions === undefined || limits.maxSubmissions > session.submissionsUsed))
|
|
1211
|
+
this.setSession(id, 'running');
|
|
1212
|
+
}
|
|
1213
|
+
plan = this.commands.plan(runId);
|
|
1214
|
+
if (plan.reset?.reason === 'worker_exhausted' && !plan.reset.profileVersionId && step.workerSessionId && this.store.get('sessions', step.workerSessionId).state === 'running') {
|
|
1215
|
+
delete plan.reset;
|
|
1216
|
+
plan.stage = 'worker';
|
|
1217
|
+
}
|
|
1218
|
+
this.commands.savePlan(runId, plan);
|
|
1219
|
+
this.completeDecision(runId, queued.operationId);
|
|
1220
|
+
});
|
|
1221
|
+
}
|
|
1222
|
+
else if (input.kind === 'replace_profile') {
|
|
1223
|
+
if (input.role === 'worker' && plan.reset?.profileVersionId)
|
|
1224
|
+
throw new ApiError(409, 'transition_in_progress', 'A worker profile replacement is already pending.');
|
|
1225
|
+
const profile = this.store.get('profile_versions', input.profileVersionId);
|
|
1226
|
+
const validation = await this.effect(runId, 'Validate replacement profile', () => this.commands.options.publication.profileReport({ definition: profile.definition, resources: profile.resources }, this.signal(runId)));
|
|
1227
|
+
this.gate(runId, true, true);
|
|
1228
|
+
if (!validation.valid)
|
|
1229
|
+
throw new ApiError(422, 'invalid_profile', 'Replacement profile is invalid.', false, validation.issues);
|
|
1230
|
+
this.options.workspaces.assertKnown(runId);
|
|
1231
|
+
const snapshot = this.options.pins.assembleRole({ runId, stepExecutionId: step.id, role: input.role, profileVersionId: profile.id,
|
|
1232
|
+
stepInstructions: plan.definition.steps[plan.ordinal].instructions ?? [], stepPackageResources: plan.definition['instruction-resources'] ?? [] });
|
|
1233
|
+
this.options.workspaces.assertKnown(runId);
|
|
1234
|
+
const compiled = await this.effect(runId, 'Compile replacement permissions', () => this.options.validation.run({ kind: 'effective_permissions',
|
|
1235
|
+
profile: profile.definition.permissions, deployment: this.options.deploymentPolicy, role: input.role, configuredTools: profile.definition.tools.map(tool => tool.toolId) }, { runId, signal: this.signal(runId) }));
|
|
1236
|
+
this.gate(runId, true, true);
|
|
1237
|
+
if (!compiled.valid || !compiled.effectivePolicy)
|
|
1238
|
+
throw new ApiError(422, 'invalid_effective_permissions', 'Replacement permissions are invalid.', false, compiled.errors);
|
|
1239
|
+
const configuration = { profileVersionId: profile.id, role: input.role, definition: profile.definition, instructionSnapshotId: snapshot.id,
|
|
1240
|
+
deploymentPolicyDigest: digest(this.options.deploymentPolicy), effectivePermissions: compiled.effectivePolicy };
|
|
1241
|
+
const oldSessionId = input.role === 'worker' ? step.workerSessionId :
|
|
1242
|
+
step.auxiliarySessionId && this.store.get('sessions', step.auxiliarySessionId).role === input.role ? step.auxiliarySessionId : undefined;
|
|
1243
|
+
this.store.coordinator.atomic(() => {
|
|
1244
|
+
this.store.put('snapshots', snapshot, { runId, parentId: step.id, immutable: true });
|
|
1245
|
+
this.store.setPrivate('pending_profile', queued.operationId, { snapshotId: snapshot.id, configuration: { ...configuration, contentDigest: digest(configuration) } });
|
|
1246
|
+
this.supersede(runId, input.role);
|
|
1247
|
+
plan = this.commands.plan(runId);
|
|
1248
|
+
if (oldSessionId && this.commands.current(oldSessionId, this.store.get('sessions', oldSessionId).epoch))
|
|
1249
|
+
this.broker.invalidateSessionActions(this.commands.binding(oldSessionId));
|
|
1250
|
+
if (input.role === 'worker') {
|
|
1251
|
+
const prior = plan.reset;
|
|
1252
|
+
plan.reset = { ...(prior ?? { id: randomUUID(), reason: 'profile_replacement', role: 'worker', ...(oldSessionId ? { oldSessionId } : {}) }),
|
|
1253
|
+
profileVersionId: profile.id, profileOperationId: queued.operationId,
|
|
1254
|
+
operationId: prior?.operationId ?? queued.operationId,
|
|
1255
|
+
operationIds: [...new Set([...(prior?.operationIds ?? []), ...(prior?.operationId ? [prior.operationId] : []), queued.operationId])] };
|
|
1256
|
+
plan.stage = 'reset';
|
|
1257
|
+
}
|
|
1258
|
+
plan.queuedDecisions.shift();
|
|
1259
|
+
this.commands.savePlan(runId, plan);
|
|
1260
|
+
this.broker.setHold(runId, 'queued_decisions', false);
|
|
1261
|
+
this.store.event(runId, 'instruction_snapshot_created', 'instruction_snapshot', snapshot.id, { role: input.role, stepExecutionId: step.id });
|
|
1262
|
+
});
|
|
1263
|
+
if (input.role !== 'worker') {
|
|
1264
|
+
if (oldSessionId)
|
|
1265
|
+
await this.closeSession(oldSessionId);
|
|
1266
|
+
this.store.coordinator.atomic(() => {
|
|
1267
|
+
plan = this.commands.plan(runId);
|
|
1268
|
+
plan.steps[plan.ordinal].profiles[input.role] = { profileVersionId: profile.id, snapshotId: snapshot.id };
|
|
1269
|
+
if (oldSessionId) {
|
|
1270
|
+
delete plan.steps[plan.ordinal].auxiliarySessionId;
|
|
1271
|
+
plan.stage = input.role === 'verifier' ? 'verify' : 'handoff';
|
|
1272
|
+
}
|
|
1273
|
+
this.commands.savePlan(runId, plan);
|
|
1274
|
+
this.store.setPrivate('effective_configuration', `${step.id}:${input.role}`, { ...configuration, contentDigest: digest(configuration) });
|
|
1275
|
+
const publicStep = this.store.get('steps', step.id);
|
|
1276
|
+
this.store.put('steps', { ...publicStep, agentProfiles: { ...publicStep.agentProfiles, [input.role]: profile.id } }, { runId });
|
|
1277
|
+
this.store.event(runId, 'profile_replaced', 'step_execution', step.id, { role: input.role, profileVersionId: profile.id });
|
|
1278
|
+
this.operationState(queued.operationId, 'succeeded');
|
|
1279
|
+
});
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
else {
|
|
1283
|
+
this.gate(runId, true);
|
|
1284
|
+
if (input.kind === 'overwrite') {
|
|
1285
|
+
if (!input.approve) {
|
|
1286
|
+
this.completeDecision(runId, queued.operationId);
|
|
1287
|
+
return;
|
|
1288
|
+
}
|
|
1289
|
+
this.options.workspaces.approveOverwrite(runId, input.conflictDigest);
|
|
1290
|
+
}
|
|
1291
|
+
const baselineId = input.kind === 'rollback' ? input.baselineId : plan.reset?.restoreBaselineId ?? step.baselineId;
|
|
1292
|
+
if (!baselineId)
|
|
1293
|
+
throw new ApiError(409, 'baseline_unavailable', 'No recorded baseline is available.');
|
|
1294
|
+
if (input.kind === 'rollback') {
|
|
1295
|
+
this.rewind(runId, this.commands.rollbackOrdinal(runId, baselineId), baselineId, queued.operationId);
|
|
1296
|
+
this.wake(runId);
|
|
1297
|
+
return;
|
|
1298
|
+
}
|
|
1299
|
+
this.store.coordinator.atomic(() => {
|
|
1300
|
+
this.supersede(runId);
|
|
1301
|
+
plan = this.commands.plan(runId);
|
|
1302
|
+
plan.stage = 'reset';
|
|
1303
|
+
if (step.workerSessionId && this.commands.current(step.workerSessionId, this.store.get('sessions', step.workerSessionId).epoch))
|
|
1304
|
+
this.broker.invalidateSessionActions(this.commands.binding(step.workerSessionId));
|
|
1305
|
+
const prior = plan.reset;
|
|
1306
|
+
plan.reset = { ...(prior ?? { id: randomUUID(), reason: 'rollback', role: 'worker', ...(step.workerSessionId ? { oldSessionId: step.workerSessionId } : {}) }),
|
|
1307
|
+
operationId: prior?.operationId ?? queued.operationId,
|
|
1308
|
+
operationIds: [...new Set([...(prior?.operationIds ?? []), ...(prior?.operationId ? [prior.operationId] : []), queued.operationId])],
|
|
1309
|
+
restoreBaselineId: baselineId, ...(input.kind === 'overwrite' ? { overwriteConflictDigest: input.conflictDigest } : {}) };
|
|
1310
|
+
plan.queuedDecisions.shift();
|
|
1311
|
+
this.commands.savePlan(runId, plan);
|
|
1312
|
+
});
|
|
1313
|
+
}
|
|
1314
|
+
this.wake(runId);
|
|
1315
|
+
}
|
|
1316
|
+
rewind(runId, ordinal, baselineId, operationId, restoreProofId) {
|
|
1317
|
+
this.store.coordinator.atomic(() => {
|
|
1318
|
+
const plan = this.commands.plan(runId), source = plan.ordinal, id = randomUUID(), now = this.commands.now();
|
|
1319
|
+
const affected = new Set(plan.steps.slice(ordinal).map(step => step.id));
|
|
1320
|
+
const submissions = this.store.list('submissions', { runId, limit: Number.MAX_SAFE_INTEGER }).map(row => row.value)
|
|
1321
|
+
.filter(value => affected.has(value.stepExecutionId));
|
|
1322
|
+
const artifacts = this.store.list('artifacts', { runId, limit: Number.MAX_SAFE_INTEGER }).map(row => row.value)
|
|
1323
|
+
.filter(value => value.stepExecutionId && affected.has(value.stepExecutionId));
|
|
1324
|
+
this.store.setPrivate('rewind_history', id, { operationId, baselineId, ordinal, source,
|
|
1325
|
+
steps: plan.steps.slice(ordinal).map(step => this.store.get('steps', step.id)), submissions, artifacts });
|
|
1326
|
+
for (const submission of submissions)
|
|
1327
|
+
if (submission.state !== 'superseded')
|
|
1328
|
+
this.store.put('submissions', { ...submission, state: 'superseded' }, { runId, parentId: submission.sessionId });
|
|
1329
|
+
for (const artifact of artifacts)
|
|
1330
|
+
if (artifact.state !== 'superseded')
|
|
1331
|
+
this.store.put('artifacts', { ...artifact, state: 'superseded' }, { runId });
|
|
1332
|
+
for (const queued of plan.queuedDecisions)
|
|
1333
|
+
queued.stepExecutionId ??= plan.steps[source].id;
|
|
1334
|
+
for (let index = ordinal; index < plan.steps.length; index++) {
|
|
1335
|
+
const step = plan.steps[index], clock = plan.stepClocks[step.id];
|
|
1336
|
+
if (!clock)
|
|
1337
|
+
continue;
|
|
1338
|
+
plan.stepClocks[step.id] = checkpoint(clock, false, now);
|
|
1339
|
+
step.reentry ??= { ...(step.workerSessionId ? { oldSessionId: step.workerSessionId } : {}) };
|
|
1340
|
+
if (index === source && plan.reset) {
|
|
1341
|
+
const { handoffId: _handoff, replacementSessionId: _replacement, restoreBaselineId: _restore, overwriteConflictDigest: _overwrite, ...pending } = plan.reset;
|
|
1342
|
+
step.reentry.reset = pending;
|
|
1343
|
+
}
|
|
1344
|
+
delete step.workerSessionId;
|
|
1345
|
+
delete step.auxiliarySessionId;
|
|
1346
|
+
delete step.candidateId;
|
|
1347
|
+
delete step.handoffId;
|
|
1348
|
+
delete step.baselineId;
|
|
1349
|
+
delete step.verifierRetirementId;
|
|
1350
|
+
const { acceptedSubmissionId: _submission, acceptedCommit: _commit, activeSessionId: _session, baselineId: _baseline, ...execution } = this.store.get('steps', step.id);
|
|
1351
|
+
this.store.put('steps', { ...execution, state: 'pending', timing: status(plan.stepClocks[step.id], false, now) }, { runId });
|
|
1352
|
+
}
|
|
1353
|
+
const target = plan.steps[ordinal], pending = target.reentry.reset;
|
|
1354
|
+
const { handoffId: _handoff, replacementSessionId: _replacement, restoreBaselineId: _restore, overwriteConflictDigest: _overwrite, ...retained } = pending ?? {};
|
|
1355
|
+
plan.reset = { ...retained, id: restoreProofId ?? id, reason: 'rollback', role: 'worker',
|
|
1356
|
+
...(target.reentry.oldSessionId ? { oldSessionId: target.reentry.oldSessionId } : {}),
|
|
1357
|
+
operationId: pending?.operationId ?? operationId,
|
|
1358
|
+
restoreBaselineId: baselineId, operationIds: [...new Set([...(pending?.operationIds ?? []), ...(pending?.operationId ? [pending.operationId] : []), operationId])] };
|
|
1359
|
+
if (target.reentry.oldSessionId)
|
|
1360
|
+
target.workerSessionId = target.reentry.oldSessionId;
|
|
1361
|
+
plan.ordinal = ordinal;
|
|
1362
|
+
plan.stage = 'reset';
|
|
1363
|
+
delete plan.pendingSubmissionId;
|
|
1364
|
+
const retiringSessionIds = this.store.list('sessions', { runId, limit: Number.MAX_SAFE_INTEGER }).map(row => row.value)
|
|
1365
|
+
.filter(session => affected.has(session.stepExecutionId)).map(session => session.id);
|
|
1366
|
+
plan.rewind = { id, targetStepId: target.id, retiringSessionIds };
|
|
1367
|
+
for (const sessionId of retiringSessionIds)
|
|
1368
|
+
if (this.commands.current(sessionId, this.store.get('sessions', sessionId).epoch)) {
|
|
1369
|
+
this.broker.invalidateSessionActions(this.commands.binding(sessionId));
|
|
1370
|
+
if (sessionId !== plan.reset.oldSessionId) {
|
|
1371
|
+
this.broker.fenceSession(this.commands.binding(sessionId));
|
|
1372
|
+
this.commands.options.auth.revokeSession(sessionId);
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
plan.queuedDecisions = plan.queuedDecisions.filter(queued => queued.operationId !== operationId);
|
|
1376
|
+
this.commands.savePlan(runId, plan);
|
|
1377
|
+
this.broker.setHold(runId, 'submission', false);
|
|
1378
|
+
this.broker.setHold(runId, 'queued_decisions', plan.queuedDecisions.length > 0);
|
|
1379
|
+
this.commands.updateRun(runId, { state: 'resetting', currentStepId: target.id });
|
|
1380
|
+
this.stepState(runId, 'resetting');
|
|
1381
|
+
this.syncBrokerDeadlineSql(runId, plan);
|
|
1382
|
+
this.store.event(runId, 'step_state_changed', 'step_execution', target.id, { state: 'resetting', rewindId: id, baselineId, sourceOrdinal: source, ordinal });
|
|
1383
|
+
});
|
|
1384
|
+
}
|
|
1385
|
+
completeDecision(runId, operationId) {
|
|
1386
|
+
const plan = this.commands.plan(runId);
|
|
1387
|
+
plan.queuedDecisions = plan.queuedDecisions.filter(value => value.operationId !== operationId);
|
|
1388
|
+
this.commands.savePlan(runId, plan);
|
|
1389
|
+
this.operationState(operationId, 'succeeded');
|
|
1390
|
+
this.broker.setHold(runId, 'queued_decisions', plan.queuedDecisions.length > 0);
|
|
1391
|
+
if (!this.store.get('runs', runId).pendingBlockIds.length)
|
|
1392
|
+
this.commands.updateRun(runId, { state: plan.stage === 'verify' ? 'verifying' : plan.stage === 'startup' ? 'starting' : plan.reset ? 'resetting' : 'running' });
|
|
1393
|
+
}
|
|
1394
|
+
async reset(runId) {
|
|
1395
|
+
this.gate(runId);
|
|
1396
|
+
let plan = this.commands.plan(runId), reset = plan.reset;
|
|
1397
|
+
if (!reset)
|
|
1398
|
+
throw new Error('reset_plan_missing');
|
|
1399
|
+
if (reset.reason === 'rollback' && !plan.rewind && !plan.steps[plan.ordinal].reentry && reset.restoreBaselineId) {
|
|
1400
|
+
const operations = new Set([...(reset.operationIds ?? []), ...(reset.operationId ? [reset.operationId] : [])]);
|
|
1401
|
+
const rollback = this.store.list('decisions', { runId, limit: Number.MAX_SAFE_INTEGER }).reverse()
|
|
1402
|
+
.find(({ value }) => operations.has(value.operationId) && value.decision.kind === 'rollback');
|
|
1403
|
+
if (rollback) {
|
|
1404
|
+
this.rewind(runId, this.commands.rollbackOrdinal(runId, reset.restoreBaselineId), reset.restoreBaselineId, rollback.value.operationId, reset.id);
|
|
1405
|
+
this.wake(runId);
|
|
1406
|
+
return;
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
if (!reset.id) {
|
|
1410
|
+
reset.id = randomUUID();
|
|
1411
|
+
this.commands.savePlan(runId, plan);
|
|
1412
|
+
}
|
|
1413
|
+
if (plan.rewind?.retiringSessionIds.length) {
|
|
1414
|
+
for (const id of plan.rewind.retiringSessionIds)
|
|
1415
|
+
if (id !== reset.oldSessionId)
|
|
1416
|
+
await this.closeSession(id);
|
|
1417
|
+
plan = this.commands.plan(runId);
|
|
1418
|
+
plan.rewind.retiringSessionIds = [];
|
|
1419
|
+
this.commands.savePlan(runId, plan);
|
|
1420
|
+
this.gate(runId);
|
|
1421
|
+
reset = plan.reset;
|
|
1422
|
+
}
|
|
1423
|
+
let step = plan.steps[plan.ordinal], definition = plan.definition.steps[plan.ordinal];
|
|
1424
|
+
const execution = this.store.get('steps', step.id);
|
|
1425
|
+
if (reset.role === 'worker' && !reset.replacementSessionId && execution.resetsUsed >= execution.maxSessionResets) {
|
|
1426
|
+
const block = this.commands.block(runId, 'retry_budget_exhausted', 'The current step has no remaining worker reset allowance.', ['increase_budgets', 'replace_profile', 'rollback']);
|
|
1427
|
+
for (const id of new Set([...(reset.operationIds ?? []), ...(reset.operationId ? [reset.operationId] : [])]))
|
|
1428
|
+
this.operationState(id, 'waiting_for_decision', undefined, block.id);
|
|
1429
|
+
return;
|
|
1430
|
+
}
|
|
1431
|
+
if (reset.role === 'worker' && definition.handoffArtifact && !reset.handoffId && !reset.replacementSessionId) {
|
|
1432
|
+
const independent = definition.handoffArtifact['independent-handoff'];
|
|
1433
|
+
let id = independent ? step.auxiliarySessionId : reset.oldSessionId;
|
|
1434
|
+
if (independent && id && this.store.get('sessions', id).role !== 'handoff') {
|
|
1435
|
+
await this.closeSession(id);
|
|
1436
|
+
plan = this.commands.plan(runId);
|
|
1437
|
+
delete plan.steps[plan.ordinal].auxiliarySessionId;
|
|
1438
|
+
this.commands.savePlan(runId, plan);
|
|
1439
|
+
id = undefined;
|
|
1440
|
+
}
|
|
1441
|
+
if (!independent && (!id || reset.interrupted || !this.options.driver.alive(id))) {
|
|
1442
|
+
const block = this.commands.block(runId, 'handoff_failed', 'The mandatory worker-context handoff cannot be generated because its original conversation is unavailable.', ['increase_budgets', 'replace_profile']);
|
|
1443
|
+
for (const operation of new Set([...(reset.operationIds ?? []), ...(reset.operationId ? [reset.operationId] : [])]))
|
|
1444
|
+
this.operationState(operation, 'waiting_for_decision', undefined, block.id);
|
|
1445
|
+
return;
|
|
1446
|
+
}
|
|
1447
|
+
if (id && this.options.driver.active(id)) {
|
|
1448
|
+
this.options.driver.flush(id);
|
|
1449
|
+
return;
|
|
1450
|
+
}
|
|
1451
|
+
if (!this.quiet(runId))
|
|
1452
|
+
return;
|
|
1453
|
+
if (!id)
|
|
1454
|
+
id = await this.launch(runId, 'handoff');
|
|
1455
|
+
const session = this.store.get('sessions', id), authority = this.store.private('session_authority', id);
|
|
1456
|
+
if (expired(authority.clock, this.commands.now()) || session.limits.maxSubmissions !== undefined && session.submissionsUsed >= session.limits.maxSubmissions) {
|
|
1457
|
+
const block = this.commands.block(runId, 'handoff_failed', 'Mandatory handoff has no remaining count or time allowance.', ['increase_budgets', 'replace_profile']);
|
|
1458
|
+
if (reset.operationId)
|
|
1459
|
+
this.operationState(reset.operationId, 'waiting_for_decision', undefined, block.id);
|
|
1460
|
+
return;
|
|
1461
|
+
}
|
|
1462
|
+
this.store.coordinator.atomic(() => {
|
|
1463
|
+
const current = this.commands.plan(runId), root = current.graph.roots.find(value => value.stepId === definition.id && value.kind === 'handoff');
|
|
1464
|
+
authority.phase = 'handoff';
|
|
1465
|
+
authority.outputSchema = current.graph.resources.find(value => value.uri === root.uri).schema;
|
|
1466
|
+
if (this.store.private('execution_completion', authority.logicalOperationId) || this.store.private('execution_failure', authority.logicalOperationId)) {
|
|
1467
|
+
authority.logicalOperationId = randomUUID();
|
|
1468
|
+
this.commands.retries.begin(authority.retryEpisodeId, authority.logicalOperationId);
|
|
1469
|
+
}
|
|
1470
|
+
this.store.setPrivate('session_authority', id, authority);
|
|
1471
|
+
const assignment = this.store.private('assignments', id);
|
|
1472
|
+
this.store.setPrivate('assignments', id, { ...assignment, outputSchema: authority.outputSchema });
|
|
1473
|
+
current.stage = 'handoff';
|
|
1474
|
+
this.commands.savePlan(runId, current);
|
|
1475
|
+
this.commands.updateRun(runId, { state: 'generating_handoff' });
|
|
1476
|
+
this.stepState(runId, 'generating_handoff');
|
|
1477
|
+
this.setSession(id, 'running');
|
|
1478
|
+
});
|
|
1479
|
+
await this.effect(runId, 'Generate bounded mandatory handoff in assigned conversation', () => this.options.driver.turn(id, this.prompt(id)), id);
|
|
1480
|
+
return;
|
|
1481
|
+
}
|
|
1482
|
+
if (!reset.replacementSessionId) {
|
|
1483
|
+
for (const id of [step.auxiliarySessionId, ...(reset.role === 'worker' && reset.oldSessionId ? [reset.oldSessionId] : [])])
|
|
1484
|
+
if (id)
|
|
1485
|
+
await this.closeSession(id);
|
|
1486
|
+
this.gate(runId);
|
|
1487
|
+
if (!this.quiet(runId))
|
|
1488
|
+
return;
|
|
1489
|
+
plan = this.commands.plan(runId);
|
|
1490
|
+
reset = plan.reset;
|
|
1491
|
+
step = plan.steps[plan.ordinal];
|
|
1492
|
+
if (reset.role === 'worker' && (reset.restoreBaselineId || definition.execution['git-reset-on-session-reset'])) {
|
|
1493
|
+
const restored = this.store.private('restore_completed', runId);
|
|
1494
|
+
if (restored?.operationId !== reset.id) {
|
|
1495
|
+
const baselineId = reset.restoreBaselineId ?? step.baselineId;
|
|
1496
|
+
if (!baselineId) {
|
|
1497
|
+
this.commands.block(runId, 'baseline_unavailable', 'The recorded step baseline is unavailable.', ['rollback']);
|
|
1498
|
+
return;
|
|
1499
|
+
}
|
|
1500
|
+
this.options.workspaces.restore({ runId, baselineId, ...(reset.overwriteConflictDigest ? { overwriteConflictDigest: reset.overwriteConflictDigest } : {}) }, {
|
|
1501
|
+
onAdmittedSql: job => this.store.setPrivate('workspace_continuation', job.id, { kind: 'session_reset', operationId: reset.id }),
|
|
1502
|
+
onCompletedSql: job => this.workspaceCompleted(job),
|
|
1503
|
+
});
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
if (step.reentry && !step.baselineId)
|
|
1507
|
+
this.options.workspaces.baseline(runId, 'step_start', step.id, { onAdmittedSql: baseline => {
|
|
1508
|
+
const current = this.commands.plan(runId);
|
|
1509
|
+
current.steps[current.ordinal].baselineId = baseline.id;
|
|
1510
|
+
this.commands.savePlan(runId, current);
|
|
1511
|
+
this.store.put('baselines', baseline, { runId, immutable: true });
|
|
1512
|
+
this.store.put('steps', { ...this.store.get('steps', step.id), baselineId: baseline.id }, { runId });
|
|
1513
|
+
} });
|
|
1514
|
+
this.store.coordinator.atomic(() => {
|
|
1515
|
+
plan = this.commands.plan(runId);
|
|
1516
|
+
reset = plan.reset;
|
|
1517
|
+
step = plan.steps[plan.ordinal];
|
|
1518
|
+
if (reset.operationId && reset.profileVersionId) {
|
|
1519
|
+
const replacement = this.store.private('pending_profile', reset.profileOperationId ?? reset.operationId);
|
|
1520
|
+
step.profiles[reset.role] = { profileVersionId: reset.profileVersionId, snapshotId: replacement.snapshotId };
|
|
1521
|
+
this.store.setPrivate('effective_configuration', `${step.id}:${reset.role}`, replacement.configuration);
|
|
1522
|
+
const publicStep = this.store.get('steps', step.id);
|
|
1523
|
+
this.store.put('steps', { ...publicStep, agentProfiles: { ...publicStep.agentProfiles, [reset.role]: reset.profileVersionId } }, { runId });
|
|
1524
|
+
this.store.event(runId, 'profile_replaced', 'step_execution', step.id, { role: reset.role, profileVersionId: reset.profileVersionId });
|
|
1525
|
+
}
|
|
1526
|
+
delete step.auxiliarySessionId;
|
|
1527
|
+
if (reset.role === 'worker') {
|
|
1528
|
+
delete step.workerSessionId;
|
|
1529
|
+
delete step.candidateId;
|
|
1530
|
+
if (reset.handoffId)
|
|
1531
|
+
step.handoffId = reset.handoffId;
|
|
1532
|
+
}
|
|
1533
|
+
this.commands.savePlan(runId, plan);
|
|
1534
|
+
this.commands.updateRun(runId, { state: 'resetting' });
|
|
1535
|
+
this.stepState(runId, 'resetting');
|
|
1536
|
+
});
|
|
1537
|
+
const id = await this.launch(runId, reset.role);
|
|
1538
|
+
plan = this.commands.plan(runId);
|
|
1539
|
+
plan.reset.replacementSessionId = id;
|
|
1540
|
+
this.commands.savePlan(runId, plan);
|
|
1541
|
+
}
|
|
1542
|
+
this.gate(runId);
|
|
1543
|
+
this.store.coordinator.atomic(() => {
|
|
1544
|
+
plan = this.commands.plan(runId);
|
|
1545
|
+
reset = plan.reset;
|
|
1546
|
+
const operationIds = [...new Set([...(reset.operationIds ?? []), ...(reset.operationId ? [reset.operationId] : [])])], role = reset.role;
|
|
1547
|
+
if (plan.rewind?.targetStepId === plan.steps[plan.ordinal].id)
|
|
1548
|
+
delete plan.rewind;
|
|
1549
|
+
delete plan.reset;
|
|
1550
|
+
plan.stage = role === 'verifier' ? 'verify' : role === 'handoff' ? 'handoff' : 'worker';
|
|
1551
|
+
this.commands.savePlan(runId, plan);
|
|
1552
|
+
this.commands.updateRun(runId, { state: role === 'verifier' ? 'verifying' : 'running' });
|
|
1553
|
+
this.stepState(runId, role === 'verifier' ? 'verifying' : 'running');
|
|
1554
|
+
for (const id of operationIds)
|
|
1555
|
+
this.operationState(id, 'succeeded');
|
|
1556
|
+
});
|
|
1557
|
+
this.wake(runId);
|
|
1558
|
+
}
|
|
1559
|
+
/** Called only after the deployment acquired its inherited writer lock and
|
|
1560
|
+
* constructed the broker/workspace recovery owners. Never reconnect threads. */
|
|
1561
|
+
restoreInterrupted() {
|
|
1562
|
+
this.store.coordinator.assertOutsideTransaction();
|
|
1563
|
+
const now = this.commands.now();
|
|
1564
|
+
for (const { value: run } of this.store.list('runs', { limit: Number.MAX_SAFE_INTEGER })) {
|
|
1565
|
+
if (terminal(run))
|
|
1566
|
+
continue;
|
|
1567
|
+
this.store.coordinator.atomic(() => {
|
|
1568
|
+
const plan = this.commands.plan(run.id), count = plan.timingPolicy.downtimeAccounting === 'count';
|
|
1569
|
+
plan.clock = count ? checkpoint(plan.clock, false, now) : { ...plan.clock, changedAt: now, running: false };
|
|
1570
|
+
for (const [id, value] of Object.entries(plan.stepClocks))
|
|
1571
|
+
plan.stepClocks[id] = count ? checkpoint(value, false, now) : { ...value, changedAt: now, running: false };
|
|
1572
|
+
this.commands.savePlan(run.id, plan);
|
|
1573
|
+
this.syncBrokerDeadlineSql(run.id, plan);
|
|
1574
|
+
this.commands.syncBrokerApprovalTimeoutSql(run.id, run.policy);
|
|
1575
|
+
for (const { value: session } of this.store.list('sessions', { runId: run.id, limit: Number.MAX_SAFE_INTEGER })) {
|
|
1576
|
+
if (['completed', 'terminated'].includes(session.state))
|
|
1577
|
+
continue;
|
|
1578
|
+
const authority = this.store.private('session_authority', session.id);
|
|
1579
|
+
if (authority) {
|
|
1580
|
+
authority.clock = count ? checkpoint(authority.clock, false, now) : { ...authority.clock, changedAt: now, running: false };
|
|
1581
|
+
this.store.setPrivate('session_authority', session.id, authority);
|
|
1582
|
+
}
|
|
1583
|
+
this.commands.options.auth.revokeSession(session.id);
|
|
1584
|
+
this.store.put('sessions', { ...session, state: 'interrupted', ...(authority ? { timing: status(authority.clock, false, now) } : {}) }, { runId: run.id, parentId: session.stepExecutionId });
|
|
1585
|
+
}
|
|
1586
|
+
this.broker.pause(run.id);
|
|
1587
|
+
const paused = ['paused', 'pausing', 'resuming'].includes(run.executionControl.status);
|
|
1588
|
+
this.commands.updateRun(run.id, { state: paused ? run.executionControl.status === 'pausing' ? 'pausing' : 'paused' : 'interrupted',
|
|
1589
|
+
timing: status(plan.clock, false, now),
|
|
1590
|
+
executionControl: { ...run.executionControl, status: paused ? run.executionControl.status === 'pausing' ? 'pausing' : 'paused' : 'running',
|
|
1591
|
+
...(paused ? { continuationState: 'interrupted' } : {}), inFlightWork: this.work(run.id) } });
|
|
1592
|
+
});
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1595
|
+
reconcileStoppedModels(runId) {
|
|
1596
|
+
const work = this.store.coordinator.db.prepare("SELECT id FROM broker_work WHERE run_id=? AND state='uncertain'").all(runId);
|
|
1597
|
+
this.store.coordinator.atomic(() => {
|
|
1598
|
+
for (const { id } of work) {
|
|
1599
|
+
const session = this.store.list('sessions', { runId, limit: Number.MAX_SAFE_INTEGER }).find(({ value }) => this.#stopped.has(value.id) && id.startsWith(`external:${value.id}:${value.epoch}:runtime-model:`));
|
|
1600
|
+
if (!session)
|
|
1601
|
+
continue;
|
|
1602
|
+
this.store.setPrivate('model_stop_proof', id, { sessionId: session.value.id, observedAt: this.commands.now() });
|
|
1603
|
+
this.store.coordinator.db.prepare("DELETE FROM broker_work WHERE run_id=? AND id=? AND state='uncertain'").run(runId, id);
|
|
1604
|
+
}
|
|
1605
|
+
});
|
|
1606
|
+
}
|
|
1607
|
+
async recover(runId) {
|
|
1608
|
+
let plan = this.commands.plan(runId);
|
|
1609
|
+
const operationId = plan.recoveryOperationId;
|
|
1610
|
+
if (this.store.get('operations', operationId).state === 'waiting_for_decision')
|
|
1611
|
+
return;
|
|
1612
|
+
this.operationState(operationId, 'running');
|
|
1613
|
+
await this.stopSessions(runId);
|
|
1614
|
+
this.reconcileStoppedModels(runId);
|
|
1615
|
+
if (this.work(runId).some(value => value.description !== 'Workspace effect requires read-only reconciliation')) {
|
|
1616
|
+
const block = this.commands.block(runId, 'verification_failed', 'Prior tool effects remain uncertain. Recovery cannot redispatch them or treat containment as completion.', []);
|
|
1617
|
+
this.operationState(operationId, 'waiting_for_decision', undefined, block.id);
|
|
1618
|
+
return;
|
|
1619
|
+
}
|
|
1620
|
+
if (this.options.workspaces.activeWork(runId).length) {
|
|
1621
|
+
this.#readProof.add(runId);
|
|
1622
|
+
try {
|
|
1623
|
+
this.options.workspaces.reconcile(runId, { onCompletedSql: job => this.workspaceCompleted(job) });
|
|
1624
|
+
}
|
|
1625
|
+
finally {
|
|
1626
|
+
this.#readProof.delete(runId);
|
|
1627
|
+
}
|
|
1628
|
+
if (this.options.workspaces.activeWork(runId).length) {
|
|
1629
|
+
const block = this.commands.block(runId, 'external_workspace_change', 'An interrupted Git operation cannot be proven complete. Its journal and workspace lease remain held.', []);
|
|
1630
|
+
this.operationState(operationId, 'waiting_for_decision', undefined, block.id);
|
|
1631
|
+
return;
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
if (this.options.workspaces.lease(runId).state === 'uncertain')
|
|
1635
|
+
this.options.workspaces.activateLeaseForRecovery(runId);
|
|
1636
|
+
plan = this.commands.plan(runId);
|
|
1637
|
+
const queued = plan.queuedDecisions[0];
|
|
1638
|
+
const workspaceDecision = queued?.blockId && this.store.get('blocks', queued.blockId).reason === 'external_workspace_change' &&
|
|
1639
|
+
(queued.decision.kind === 'rollback' || queued.decision.kind === 'overwrite' && queued.decision.approve);
|
|
1640
|
+
if (workspaceDecision) {
|
|
1641
|
+
// Only after physical/uncertain-tool reconciliation may an explicit
|
|
1642
|
+
// conflict decision select a restore. Ordinary assertKnown must still
|
|
1643
|
+
// reject external bytes until that exact overwrite/rollback is chosen.
|
|
1644
|
+
await this.decisions(runId);
|
|
1645
|
+
plan = this.commands.plan(runId);
|
|
1646
|
+
}
|
|
1647
|
+
if (!plan.reset?.restoreBaselineId)
|
|
1648
|
+
this.options.workspaces.assertKnown(runId);
|
|
1649
|
+
if (plan.workspaceInstructions)
|
|
1650
|
+
this.options.pins.assemble(runId, plan.definition, plan.steps);
|
|
1651
|
+
this.store.coordinator.atomic(() => {
|
|
1652
|
+
plan = this.commands.plan(runId);
|
|
1653
|
+
const step = plan.steps[plan.ordinal], old = step?.workerSessionId ?? plan.reset?.oldSessionId;
|
|
1654
|
+
if ((plan.rewind || step?.reentry || plan.reset?.restoreBaselineId) && plan.reset) {
|
|
1655
|
+
const reset = plan.reset;
|
|
1656
|
+
if (reset.replacementSessionId) {
|
|
1657
|
+
reset.oldSessionId = reset.replacementSessionId;
|
|
1658
|
+
delete reset.replacementSessionId;
|
|
1659
|
+
}
|
|
1660
|
+
reset.interrupted = true;
|
|
1661
|
+
reset.operationIds = [...new Set([...(reset.operationIds ?? []), ...(reset.operationId ? [reset.operationId] : []), operationId])];
|
|
1662
|
+
if (plan.rewind?.attentionBlockId)
|
|
1663
|
+
this.commands.resolveBlock(plan.rewind.attentionBlockId);
|
|
1664
|
+
if (plan.rewind)
|
|
1665
|
+
delete plan.rewind.attentionBlockId;
|
|
1666
|
+
plan.stage = 'reset';
|
|
1667
|
+
}
|
|
1668
|
+
else if (old) {
|
|
1669
|
+
this.supersede(runId);
|
|
1670
|
+
plan = this.commands.plan(runId);
|
|
1671
|
+
plan.reset = { id: randomUUID(), reason: 'recovery', role: 'worker', oldSessionId: old, operationId, interrupted: true };
|
|
1672
|
+
plan.stage = 'reset';
|
|
1673
|
+
}
|
|
1674
|
+
delete plan.recoveryOperationId;
|
|
1675
|
+
this.commands.savePlan(runId, plan);
|
|
1676
|
+
this.broker.setHold(runId, 'recovery', false);
|
|
1677
|
+
this.broker.setHold(runId, 'submission', false);
|
|
1678
|
+
if (!this.store.get('runs', runId).pendingBlockIds.length)
|
|
1679
|
+
this.broker.resume(runId);
|
|
1680
|
+
this.commands.updateRun(runId, { state: 'recovering' });
|
|
1681
|
+
if (!old)
|
|
1682
|
+
this.operationState(operationId, 'succeeded');
|
|
1683
|
+
});
|
|
1684
|
+
this.updateClocks(runId);
|
|
1685
|
+
this.wake(runId);
|
|
1686
|
+
}
|
|
1687
|
+
interrupt(runId) {
|
|
1688
|
+
const run = this.store.get('runs', runId);
|
|
1689
|
+
if (terminal(run) || this.commands.plan(runId).cancelOperationId)
|
|
1690
|
+
return;
|
|
1691
|
+
this.store.coordinator.atomic(() => {
|
|
1692
|
+
this.broker.pause(runId);
|
|
1693
|
+
for (const { value: session } of this.store.list('sessions', { runId, limit: Number.MAX_SAFE_INTEGER })) {
|
|
1694
|
+
if (['completed', 'terminated', 'interrupted'].includes(session.state))
|
|
1695
|
+
continue;
|
|
1696
|
+
if (this.commands.current(session.id, session.epoch))
|
|
1697
|
+
this.broker.fenceSession(this.commands.binding(session.id));
|
|
1698
|
+
this.commands.options.auth.revokeSession(session.id);
|
|
1699
|
+
this.setSession(session.id, 'interrupted');
|
|
1700
|
+
}
|
|
1701
|
+
const paused = run.executionControl.status === 'paused' || run.executionControl.status === 'pausing';
|
|
1702
|
+
this.commands.updateRun(runId, { state: paused ? run.state : 'interrupted',
|
|
1703
|
+
executionControl: { ...run.executionControl, ...(paused ? { continuationState: 'interrupted' } : {}) } });
|
|
1704
|
+
this.updateClocks(runId);
|
|
1705
|
+
});
|
|
1706
|
+
void this.stopSessions(runId).catch(error => { this.#fatal = error; });
|
|
1707
|
+
}
|
|
1708
|
+
async cancel(runId) {
|
|
1709
|
+
const operationId = this.commands.plan(runId).cancelOperationId;
|
|
1710
|
+
await this.stopSessions(runId);
|
|
1711
|
+
this.reconcileStoppedModels(runId);
|
|
1712
|
+
if (!this.quiet(runId))
|
|
1713
|
+
return;
|
|
1714
|
+
this.store.coordinator.atomic(() => {
|
|
1715
|
+
for (const { value: session } of this.store.list('sessions', { runId, limit: Number.MAX_SAFE_INTEGER })) {
|
|
1716
|
+
if (this.commands.current(session.id, session.epoch))
|
|
1717
|
+
this.broker.fenceSession(this.commands.binding(session.id));
|
|
1718
|
+
this.setSession(session.id, 'terminated');
|
|
1719
|
+
}
|
|
1720
|
+
this.supersede(runId);
|
|
1721
|
+
this.commands.updateRun(runId, { state: 'cancelled', completedAt: new Date(this.commands.now()).toISOString(),
|
|
1722
|
+
executionControl: { status: 'paused', inFlightWork: [] } });
|
|
1723
|
+
this.operationState(operationId, 'succeeded');
|
|
1724
|
+
this.updateClocks(runId);
|
|
1725
|
+
});
|
|
1726
|
+
await this.finish(runId);
|
|
1727
|
+
}
|
|
1728
|
+
async finish(runId) {
|
|
1729
|
+
let run = this.store.get('runs', runId);
|
|
1730
|
+
await this.stopSessions(runId);
|
|
1731
|
+
this.reconcileStoppedModels(runId);
|
|
1732
|
+
if (!this.quiet(runId))
|
|
1733
|
+
return;
|
|
1734
|
+
if (!terminal(run)) {
|
|
1735
|
+
this.gate(runId);
|
|
1736
|
+
this.store.coordinator.atomic(() => {
|
|
1737
|
+
const plan = this.commands.plan(runId);
|
|
1738
|
+
plan.stage = 'complete';
|
|
1739
|
+
this.commands.savePlan(runId, plan);
|
|
1740
|
+
this.broker.setHold(runId, 'complete', true);
|
|
1741
|
+
this.commands.updateRun(runId, { state: 'succeeded', completedAt: new Date(this.commands.now()).toISOString() });
|
|
1742
|
+
this.updateClocks(runId);
|
|
1743
|
+
});
|
|
1744
|
+
}
|
|
1745
|
+
run = this.store.get('runs', runId);
|
|
1746
|
+
if (!this.store.private('lease_released', runId))
|
|
1747
|
+
this.options.workspaces.releaseLease(runId, terminal(run), {
|
|
1748
|
+
onAdmittedSql: () => this.store.setPrivate('lease_released', runId, { releasedAt: this.commands.now() }),
|
|
1749
|
+
});
|
|
1750
|
+
}
|
|
1751
|
+
handleError(runId, error) {
|
|
1752
|
+
if (this.#closed)
|
|
1753
|
+
return;
|
|
1754
|
+
try {
|
|
1755
|
+
if (error instanceof CoordinatorError) {
|
|
1756
|
+
if (error.code === 'run_not_quiescent')
|
|
1757
|
+
return;
|
|
1758
|
+
this.#fatal = error;
|
|
1759
|
+
return;
|
|
1760
|
+
}
|
|
1761
|
+
const run = this.store.get('runs', runId);
|
|
1762
|
+
if (this.#closed || terminal(run) || this.commands.plan(runId).cancelOperationId)
|
|
1763
|
+
return;
|
|
1764
|
+
if (error instanceof ApiError && ['execution_held', 'validation_aborted'].includes(error.code))
|
|
1765
|
+
return;
|
|
1766
|
+
if (error instanceof WorkspaceError) {
|
|
1767
|
+
if (error.code === 'run_not_quiescent' || error.code === 'workspace_writers_or_operations_unresolved')
|
|
1768
|
+
return;
|
|
1769
|
+
const conflict = this.options.workspaces.getConflict(runId);
|
|
1770
|
+
const block = this.commands.block(runId, error.code.includes('baseline') ? 'baseline_unavailable' : 'external_workspace_change', 'Workspace state no longer matches the recorded safe boundary.', conflict ? ['overwrite', 'rollback'] : ['rollback'], conflict ? { workspaceConflict: conflict } : {});
|
|
1771
|
+
const plan = this.commands.plan(runId);
|
|
1772
|
+
if (plan.rewind && this.options.workspaces.activeWork(runId).length) {
|
|
1773
|
+
plan.rewind.attentionBlockId = block.id;
|
|
1774
|
+
this.commands.savePlan(runId, plan);
|
|
1775
|
+
}
|
|
1776
|
+
return;
|
|
1777
|
+
}
|
|
1778
|
+
if (error instanceof ApiError) {
|
|
1779
|
+
if (error.code === 'deadline_exceeded') {
|
|
1780
|
+
this.deadlines(runId);
|
|
1781
|
+
return;
|
|
1782
|
+
}
|
|
1783
|
+
if (error.code === 'session_budget_exhausted') {
|
|
1784
|
+
const plan = this.commands.plan(runId);
|
|
1785
|
+
this.commands.block(runId, plan.stage === 'verify' ? 'verification_failed' : 'handoff_failed', 'The role episode has no remaining bounded allowance.', ['increase_budgets', 'replace_profile']);
|
|
1786
|
+
return;
|
|
1787
|
+
}
|
|
1788
|
+
const queued = this.commands.plan(runId).queuedDecisions[0];
|
|
1789
|
+
if (queued && ['invalid_profile', 'profile_role_mismatch', 'not_found', 'invalid_effective_permissions', 'budget_not_increased', 'transition_in_progress'].includes(error.code)) {
|
|
1790
|
+
this.operationState(queued.operationId, 'failed', error.code);
|
|
1791
|
+
const plan = this.commands.plan(runId);
|
|
1792
|
+
plan.queuedDecisions.shift();
|
|
1793
|
+
this.commands.savePlan(runId, plan);
|
|
1794
|
+
this.broker.setHold(runId, 'queued_decisions', plan.queuedDecisions.length > 0);
|
|
1795
|
+
this.wake(runId);
|
|
1796
|
+
return;
|
|
1797
|
+
}
|
|
1798
|
+
this.commands.block(runId, 'verification_failed', 'A required validation or execution prerequisite failed.', ['replace_profile', 'rollback']);
|
|
1799
|
+
return;
|
|
1800
|
+
}
|
|
1801
|
+
this.interrupt(runId);
|
|
1802
|
+
}
|
|
1803
|
+
catch (failure) {
|
|
1804
|
+
this.#fatal = failure;
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
}
|