code60-transmission-server 0.1.0-staging.2 → 0.1.0-staging.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/INTENT.md +47 -0
  2. package/README.md +85 -244
  3. package/dist/src/acp.js +115 -0
  4. package/dist/src/contract.js +133 -0
  5. package/dist/src/engine.js +650 -0
  6. package/dist/src/main.js +76 -22
  7. package/dist/src/repository.js +94 -0
  8. package/dist/src/service.js +192 -0
  9. package/package.json +16 -32
  10. package/reference/openapi.json +1073 -0
  11. package/README.engine.md +0 -401
  12. package/dist/src/broker/filesystem.js +0 -385
  13. package/dist/src/broker/index.js +0 -734
  14. package/dist/src/broker/native/README.md +0 -192
  15. package/dist/src/broker/native/build.js +0 -43
  16. package/dist/src/broker/native/fs-helper.c +0 -529
  17. package/dist/src/broker/native/git-helper.c +0 -205
  18. package/dist/src/broker/policy.js +0 -149
  19. package/dist/src/broker/startup-lock.js +0 -14
  20. package/dist/src/broker/types.js +0 -11
  21. package/dist/src/cli/daemon.js +0 -365
  22. package/dist/src/cli/helpers.js +0 -104
  23. package/dist/src/cli/main.js +0 -180
  24. package/dist/src/config/deployment.js +0 -163
  25. package/dist/src/config/documents.js +0 -29
  26. package/dist/src/config/profile-validation.js +0 -123
  27. package/dist/src/config/schema-graph.js +0 -237
  28. package/dist/src/config/schema-loader.js +0 -185
  29. package/dist/src/config/validation-pool.js +0 -105
  30. package/dist/src/config/validation-protocol.js +0 -1
  31. package/dist/src/config/validation-worker.js +0 -106
  32. package/dist/src/config/workflow-language.js +0 -9
  33. package/dist/src/config/workflow-schema.json +0 -534
  34. package/dist/src/config/workflow-types.js +0 -1
  35. package/dist/src/config/workflow-validation.js +0 -95
  36. package/dist/src/engine/budgets.js +0 -50
  37. package/dist/src/engine/clocks.js +0 -27
  38. package/dist/src/engine/commands.js +0 -441
  39. package/dist/src/engine/contracts.js +0 -11
  40. package/dist/src/engine/drain-state.js +0 -31
  41. package/dist/src/engine/effective-permissions.js +0 -120
  42. package/dist/src/engine/instruction-pins.js +0 -205
  43. package/dist/src/engine/retries.js +0 -50
  44. package/dist/src/engine/state.js +0 -1
  45. package/dist/src/engine/timing.js +0 -23
  46. package/dist/src/engine/tool-observations.js +0 -87
  47. package/dist/src/engine/workflow-engine.js +0 -1807
  48. package/dist/src/mcp/catalog.js +0 -71
  49. package/dist/src/mcp/main.js +0 -24
  50. package/dist/src/mcp/server.js +0 -104
  51. package/dist/src/runtime/codex-app-server.js +0 -91
  52. package/dist/src/runtime/containment.js +0 -82
  53. package/dist/src/runtime/engine-driver.js +0 -212
  54. package/dist/src/runtime/json-line-writer.js +0 -192
  55. package/dist/src/runtime/pinned-instruction-sources.js +0 -24
  56. package/dist/src/runtime/protocol-client.js +0 -264
  57. package/dist/src/runtime/protocol-pool.js +0 -183
  58. package/dist/src/runtime/protocol-projection.js +0 -393
  59. package/dist/src/runtime/protocol-types.js +0 -1
  60. package/dist/src/runtime/protocol-worker.js +0 -18
  61. package/dist/src/runtime/provider-bridge.js +0 -288
  62. package/dist/src/runtime/provider-credentials.js +0 -41
  63. package/dist/src/runtime/provider-transport.js +0 -404
  64. package/dist/src/runtime/runtime-broker.js +0 -213
  65. package/dist/src/runtime/workspace-instructions.js +0 -120
  66. package/dist/src/runtime/workspace-view.js +0 -74
  67. package/dist/src/server/api-contract.json +0 -11078
  68. package/dist/src/server/api-types.js +0 -1
  69. package/dist/src/server/application.js +0 -38
  70. package/dist/src/server/auth.js +0 -67
  71. package/dist/src/server/broker-handlers.js +0 -242
  72. package/dist/src/server/control-plane.js +0 -50
  73. package/dist/src/server/deployment.js +0 -237
  74. package/dist/src/server/errors.js +0 -22
  75. package/dist/src/server/history-handlers.js +0 -113
  76. package/dist/src/server/http.js +0 -124
  77. package/dist/src/server/paging.js +0 -56
  78. package/dist/src/server/publication.js +0 -119
  79. package/dist/src/server/tool-event-handler.js +0 -77
  80. package/dist/src/server/workspace-handlers.js +0 -34
  81. package/dist/src/storage/coordinator.js +0 -224
  82. package/dist/src/storage/startup-lock.js +0 -71
  83. package/dist/src/storage/store.js +0 -167
  84. package/dist/src/tools/check-worker.js +0 -81
  85. package/dist/src/tools/checks.js +0 -106
  86. package/dist/src/tools/dns.js +0 -248
  87. package/dist/src/tools/http-contract.js +0 -38
  88. package/dist/src/tools/http.js +0 -358
  89. package/dist/src/tools/index.js +0 -177
  90. package/dist/src/tools/worker-check.js +0 -73
  91. package/dist/src/workspaces/git.js +0 -227
  92. package/dist/src/workspaces/index.js +0 -715
  93. package/examples/deployment.local.json +0 -22
  94. package/scripts/postinstall.mjs +0 -25
@@ -0,0 +1,650 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { isDeepStrictEqual } from 'node:util';
4
+ import { closeSync, mkdirSync, openSync, readSync, realpathSync, renameSync, rmSync, statSync, } from 'node:fs';
5
+ import { join, sep } from 'node:path';
6
+ import { AcpHarness } from './acp.js';
7
+ import { revision, terminal, verifierReply, workerReply, } from './contract.js';
8
+ import { repository, snapshot, writePatch } from './repository.js';
9
+ const diagnostic = (error) => error instanceof Error ? error.message : String(error);
10
+ const jsonCopy = (value) => JSON.parse(JSON.stringify(value));
11
+ function taskState(run, index) {
12
+ if (index < run.index)
13
+ return 'accepted';
14
+ if (index > run.index)
15
+ return 'pending';
16
+ switch (run.status) {
17
+ case 'running':
18
+ if (run.phase === 'verifier')
19
+ return 'verifying';
20
+ return run.repairsUsed > 0 ? 'repairing' : 'implementing';
21
+ case 'completed':
22
+ return 'accepted';
23
+ default:
24
+ return run.status;
25
+ }
26
+ }
27
+ export class Engine {
28
+ state;
29
+ factory;
30
+ db;
31
+ runs = new Map();
32
+ pumps = new Map();
33
+ agents = new Map();
34
+ pending = new Map();
35
+ disposals = new Map();
36
+ pauses = new Map();
37
+ closing = false;
38
+ settling = new Set();
39
+ constructor(state, factory = (hooks, cwd) => new AcpHarness(hooks, cwd)) {
40
+ this.state = state;
41
+ this.factory = factory;
42
+ mkdirSync(state, { recursive: true, mode: 0o700 });
43
+ this.db = new DatabaseSync(join(state, 'workflows.sqlite'));
44
+ this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
45
+ CREATE TABLE IF NOT EXISTS runs(id TEXT PRIMARY KEY, caller_key TEXT UNIQUE NOT NULL, body TEXT NOT NULL);
46
+ CREATE TABLE IF NOT EXISTS events(sequence INTEGER PRIMARY KEY, run TEXT NOT NULL, time TEXT NOT NULL, kind TEXT NOT NULL, detail TEXT NOT NULL);
47
+ CREATE INDEX IF NOT EXISTS by_run ON events(run,sequence);`);
48
+ for (const row of this.db.prepare('SELECT body FROM runs').all()) {
49
+ const r = JSON.parse(String(row.body));
50
+ this.runs.set(r.id, r);
51
+ if (terminal(r.status))
52
+ continue;
53
+ if (r.status === 'pausing' || r.status === 'paused') {
54
+ this.withdrawPermission(r);
55
+ this.retireSessions(r);
56
+ const interrupted = r.status === 'pausing';
57
+ r.status = 'paused';
58
+ if (interrupted)
59
+ this.save(r, 'paused');
60
+ continue;
61
+ }
62
+ if (r.worker || r.verifier) {
63
+ this.retireSessions(r);
64
+ r.feedback +=
65
+ '\nTransmission restarted. Inspect existing work and the outcome of consequential actions before repeating them. Ask if their outcome cannot be determined.';
66
+ this.save(r, 'task_resumed', { task: r.plan.tasks[r.index].name });
67
+ }
68
+ this.wake(r);
69
+ }
70
+ }
71
+ dir(r) {
72
+ return join(this.state, r.id);
73
+ }
74
+ save(r, kind, detail = {}) {
75
+ this.db.exec('BEGIN IMMEDIATE');
76
+ try {
77
+ this.db
78
+ .prepare('INSERT INTO runs VALUES(?,?,?) ON CONFLICT(id) DO UPDATE SET body=excluded.body')
79
+ .run(r.id, r.plan.idempotencyKey, JSON.stringify(r));
80
+ this.event(r, kind, detail);
81
+ this.db.exec('COMMIT');
82
+ }
83
+ catch (error) {
84
+ this.db.exec('ROLLBACK');
85
+ throw error;
86
+ }
87
+ }
88
+ event(r, kind, detail) {
89
+ this.db
90
+ .prepare('INSERT INTO events(run,time,kind,detail) VALUES(?,?,?,?)')
91
+ .run(r.id, new Date().toISOString(), kind, JSON.stringify({ ...detail, planRevision: r.planRevision ?? 0 }));
92
+ }
93
+ get(id) {
94
+ const r = this.runs.get(id);
95
+ if (!r)
96
+ throw new Error('Unknown workflow.');
97
+ return r;
98
+ }
99
+ start(plan) {
100
+ const prior = this.db
101
+ .prepare('SELECT id FROM runs WHERE caller_key=?')
102
+ .get(plan.idempotencyKey);
103
+ if (prior) {
104
+ const r = this.get(String(prior.id));
105
+ if (JSON.stringify(r.initialPlan ?? r.plan) !==
106
+ JSON.stringify({ ...plan, repository: repository(plan.repository) }))
107
+ throw new Error('This key belongs to a different workflow.');
108
+ return this.status(r.id);
109
+ }
110
+ const root = repository(plan.repository);
111
+ const state = realpathSync(this.state);
112
+ if (state === root || state.startsWith(root + sep))
113
+ throw new Error('Keep Transmission state outside the target repository.');
114
+ if ([...this.runs.values()].some((r) => (!terminal(r.status) || this.settling.has(r.id)) &&
115
+ r.plan.repository === root))
116
+ throw new Error('A workflow is already active in this project.');
117
+ const id = randomUUID();
118
+ const r = {
119
+ id,
120
+ plan: { ...plan, repository: root },
121
+ planRevision: 0,
122
+ baseline: snapshot(root, join(this.state, id)),
123
+ index: 0,
124
+ status: 'running',
125
+ phase: 'worker',
126
+ generation: 0,
127
+ repairsUsed: 0,
128
+ feedback: '',
129
+ messages: [],
130
+ guidance: [],
131
+ formatErrors: 0,
132
+ accepted: [],
133
+ attempts: [],
134
+ };
135
+ this.save(r, 'started');
136
+ this.runs.set(id, r);
137
+ this.wake(r);
138
+ return this.status(id);
139
+ }
140
+ status(id) {
141
+ const row = this.db.prepare(`
142
+ SELECT body, (SELECT MAX(sequence) FROM events WHERE run = runs.id) AS cursor
143
+ FROM runs WHERE id = ?
144
+ `).get(id);
145
+ if (!row)
146
+ throw new Error('Unknown workflow.');
147
+ const r = JSON.parse(String(row.body));
148
+ return {
149
+ runId: id,
150
+ planRevision: r.planRevision ?? 0,
151
+ status: r.status,
152
+ tasks: r.plan.tasks.map(({ name }, index) => ({ index, name, state: taskState(r, index) })),
153
+ activeTaskIndex: terminal(r.status) ? null : r.index,
154
+ eventCursor: Number(row.cursor),
155
+ task: r.plan.tasks[r.index]?.name,
156
+ phase: terminal(r.status) ? undefined : r.phase,
157
+ accepted: r.accepted,
158
+ decision: r.question,
159
+ reason: r.failure,
160
+ attempts: r.attempts,
161
+ ...(r.status === 'completed'
162
+ ? {
163
+ result: r.accepted.at(-1).result,
164
+ verdict: r.accepted.at(-1).verdict,
165
+ }
166
+ : {}),
167
+ };
168
+ }
169
+ plan(id) {
170
+ const row = this.db.prepare('SELECT body FROM runs WHERE id=?').get(id);
171
+ if (!row)
172
+ throw new Error('Unknown workflow.');
173
+ const r = JSON.parse(String(row.body));
174
+ return { runId: id, planRevision: r.planRevision ?? 0,
175
+ activeTaskIndex: terminal(r.status) ? null : r.index, tasks: r.plan.tasks };
176
+ }
177
+ revise(input) {
178
+ // Compare the same JSON values SQLite retains: -0 becomes 0, and absent
179
+ // optional properties do not acquire a different identity after restart.
180
+ const request = jsonCopy(revision.parse(input)), r = this.get(request.runId);
181
+ if (this.closing)
182
+ throw new Error('Engine is stopping.');
183
+ const prior = this.db.prepare(`SELECT detail FROM events WHERE run=? AND kind='plan_revised'
184
+ AND json_extract(detail,'$.request.idempotencyKey')=? LIMIT 1`).get(r.id, request.idempotencyKey);
185
+ if (prior) {
186
+ if (!isDeepStrictEqual(JSON.parse(String(prior.detail)).request, request))
187
+ throw new Error('This revision key belongs to a different request.');
188
+ return this.status(r.id);
189
+ }
190
+ if (r.status !== 'paused')
191
+ throw new Error('Workflow must be fully paused before revision.');
192
+ const currentRevision = r.planRevision ?? 0;
193
+ if (request.expectedRevision !== currentRevision)
194
+ throw new Error('The workflow plan revision has changed.');
195
+ if (r.index + request.remainingTasks.length > 100)
196
+ throw new Error('A workflow may contain at most 100 tasks, including completed tasks.');
197
+ const changed = !isDeepStrictEqual(jsonCopy(r.plan.tasks[r.index]), request.remainingTasks[0]);
198
+ const archivedContext = changed ? { feedback: r.feedback, messages: r.messages, guidance: r.guidance,
199
+ question: r.question, questionKind: r.questionKind, lastAnswer: r.lastAnswer } : undefined;
200
+ const next = { ...r, initialPlan: r.initialPlan ?? r.plan, planRevision: currentRevision + 1,
201
+ plan: { ...r.plan, tasks: [...r.plan.tasks.slice(0, r.index), ...request.remainingTasks] } };
202
+ if (changed) {
203
+ next.feedback = '';
204
+ next.messages = [];
205
+ next.guidance = [];
206
+ delete next.question;
207
+ delete next.questionKind;
208
+ delete next.lastAnswer;
209
+ }
210
+ this.retireSessions(next);
211
+ // Persist the complete transition and its replay identity before replacing
212
+ // the live object. A failed SQL transaction must leave both plans intact.
213
+ this.save(next, 'plan_revised', { fromRevision: currentRevision, activeTaskIndex: r.index,
214
+ remainingTasksBefore: r.plan.tasks.slice(r.index), request,
215
+ ...(archivedContext ? { archivedContext } : {}) });
216
+ this.runs.set(r.id, next);
217
+ return this.status(r.id);
218
+ }
219
+ events(id, after) {
220
+ this.get(id);
221
+ return this.db
222
+ .prepare('SELECT sequence,time,kind,detail FROM events WHERE run=? AND sequence>? ORDER BY sequence LIMIT 100')
223
+ .all(id, after)
224
+ .map((e) => ({
225
+ sequence: Number(e.sequence),
226
+ time: String(e.time),
227
+ kind: String(e.kind),
228
+ detail: JSON.parse(String(e.detail)),
229
+ }));
230
+ }
231
+ diff(id, offset) {
232
+ const r = this.get(id), rev = r.accepted.at(-1)?.revision;
233
+ if (!rev)
234
+ return { content: '', nextOffset: null };
235
+ const path = join(this.dir(r), rev + '.patch'), size = statSync(path).size, fd = openSync(path, 'r');
236
+ try {
237
+ const b = Buffer.alloc(Math.max(0, Math.min(size - offset, 65536)));
238
+ const n = readSync(fd, b, 0, b.length, offset);
239
+ return {
240
+ content: b.subarray(0, n).toString('base64'),
241
+ nextOffset: offset + n < size ? offset + n : null,
242
+ revision: rev,
243
+ };
244
+ }
245
+ finally {
246
+ closeSync(fd);
247
+ }
248
+ }
249
+ answer(id, questionId, answer) {
250
+ const r = this.get(id);
251
+ if (r.lastAnswer?.id === questionId && r.lastAnswer.answer === answer)
252
+ return this.status(id);
253
+ if (!['needs_input', 'pausing', 'paused'].includes(r.status) || r.question?.id !== questionId)
254
+ throw new Error('This decision is no longer pending.');
255
+ if (r.question.options &&
256
+ !r.question.options.some((opt) => opt.id === answer))
257
+ throw new Error('Select one of the offered option IDs.');
258
+ const q = r.question, p = this.pending.get(id);
259
+ delete r.question;
260
+ delete r.questionKind;
261
+ r.lastAnswer = { id: questionId, answer };
262
+ if (r.status === 'needs_input')
263
+ r.status = 'running';
264
+ if (!p || p.id !== q.id)
265
+ r.guidance.push('Decision: ' + q.text + '\nUser answer: ' + answer);
266
+ this.save(r, 'answered', { question: q, answer });
267
+ this.pending.delete(id);
268
+ p?.resolve(answer);
269
+ this.wake(r);
270
+ return this.status(id);
271
+ }
272
+ message(id, message) {
273
+ const r = this.get(id);
274
+ if (terminal(r.status))
275
+ throw new Error('Workflow has ended.');
276
+ r.messages.push(message);
277
+ r.guidance.push(message);
278
+ this.save(r, 'message', { message });
279
+ return this.status(id);
280
+ }
281
+ pause(id) {
282
+ const r = this.get(id);
283
+ if (this.closing)
284
+ throw new Error('Engine is stopping.');
285
+ if (terminal(r.status))
286
+ throw new Error('Workflow has ended.');
287
+ const prior = this.pauses.get(id);
288
+ if (prior)
289
+ return prior;
290
+ if (r.status === 'paused')
291
+ return Promise.resolve(this.status(id));
292
+ if (r.status !== 'pausing') {
293
+ r.status = 'pausing';
294
+ this.withdrawPermission(r);
295
+ this.save(r, 'pause_requested');
296
+ }
297
+ // Install the shared operation before shutdown can settle a prompt or a
298
+ // concurrent pause/cancel can join the same physical-exit barrier.
299
+ const work = Promise.resolve().then(async () => {
300
+ await this.dispose(r);
301
+ await this.pumps.get(id);
302
+ if (r.status === 'pausing') {
303
+ this.retireSessions(r);
304
+ r.status = 'paused';
305
+ this.save(r, 'paused');
306
+ }
307
+ return this.status(id);
308
+ }).finally(() => this.pauses.delete(id));
309
+ this.pauses.set(id, work);
310
+ return work;
311
+ }
312
+ resume(id) {
313
+ const r = this.get(id);
314
+ if (this.closing)
315
+ throw new Error('Engine is stopping.');
316
+ if (terminal(r.status))
317
+ throw new Error('Workflow has ended.');
318
+ if (r.status === 'pausing')
319
+ throw new Error('Workflow is still pausing.');
320
+ if (r.status !== 'paused')
321
+ return this.status(id);
322
+ this.retireSessions(r);
323
+ r.feedback += '\nWorkflow resumed after an operator pause. Inspect existing work and the outcome of consequential actions before repeating them. Ask if their outcome cannot be determined.';
324
+ r.status = r.question ? 'needs_input' : 'running';
325
+ this.save(r, 'resumed');
326
+ this.wake(r);
327
+ return this.status(id);
328
+ }
329
+ withdrawPermission(r) {
330
+ // Older records did not store question origin. Only permissions have
331
+ // offered options; scope questions must survive the loss of a session.
332
+ if (r.questionKind === 'permission' || r.question?.options) {
333
+ delete r.question;
334
+ delete r.questionKind;
335
+ }
336
+ }
337
+ async cancel(id) {
338
+ const r = this.get(id);
339
+ if (!terminal(r.status)) {
340
+ r.status = 'cancelled';
341
+ delete r.question;
342
+ delete r.questionKind;
343
+ this.save(r, 'cancelled');
344
+ }
345
+ if (r.status === 'cancelled') {
346
+ this.settling.add(id);
347
+ try {
348
+ await this.dispose(r);
349
+ await this.pumps.get(id);
350
+ }
351
+ finally {
352
+ this.settling.delete(id);
353
+ }
354
+ }
355
+ return this.status(id);
356
+ }
357
+ dispose(r) {
358
+ const prior = this.disposals.get(r.id);
359
+ if (prior)
360
+ return prior;
361
+ this.pending.get(r.id)?.resolve(undefined);
362
+ this.pending.delete(r.id);
363
+ const agent = this.agents.get(r.id);
364
+ this.agents.delete(r.id);
365
+ const work = Promise.resolve().then(() => agent?.close())
366
+ .catch(error => {
367
+ // A rejected shutdown is not proof of exit. Keep the same agent for
368
+ // another shutdown attempt instead of later declaring it paused.
369
+ if (agent)
370
+ this.agents.set(r.id, agent);
371
+ throw error;
372
+ })
373
+ .finally(() => this.disposals.delete(r.id));
374
+ this.disposals.set(r.id, work);
375
+ return work;
376
+ }
377
+ async close() {
378
+ this.closing = true;
379
+ await Promise.all([...this.runs.values()].map((r) => this.dispose(r)));
380
+ await Promise.all(this.pumps.values());
381
+ await Promise.all(this.pauses.values());
382
+ this.db.close();
383
+ }
384
+ wake(r) {
385
+ if (this.closing || r.status !== 'running' || this.pumps.has(r.id))
386
+ return;
387
+ const work = Promise.resolve()
388
+ .then(() => this.drive(r))
389
+ .finally(() => {
390
+ this.pumps.delete(r.id);
391
+ this.wake(r);
392
+ });
393
+ this.pumps.set(r.id, work);
394
+ }
395
+ retireSessions(r) {
396
+ delete r.worker;
397
+ delete r.verifier;
398
+ delete r.candidate;
399
+ r.phase = 'worker';
400
+ r.formatErrors = 0;
401
+ }
402
+ restart(r, reason) {
403
+ r.attempts.push(reason);
404
+ this.retireSessions(r);
405
+ r.repairsUsed = 0;
406
+ delete r.question;
407
+ delete r.questionKind;
408
+ if (r.generation >= r.plan.retries) {
409
+ r.failure = reason + ' Fresh-session retry limit reached.';
410
+ r.status = 'failed';
411
+ }
412
+ else {
413
+ r.generation++;
414
+ r.feedback = reason + ' Inspect existing work before continuing.';
415
+ r.status = 'running';
416
+ }
417
+ this.save(r, 'attempt_ended', {
418
+ reason,
419
+ next: r.status,
420
+ retriesUsed: r.generation,
421
+ });
422
+ }
423
+ ask(r, question, kind = 'scope') {
424
+ r.question = question;
425
+ r.questionKind = kind;
426
+ r.status = 'needs_input';
427
+ this.save(r, 'needs_input', question);
428
+ }
429
+ client(r) {
430
+ let agent = this.agents.get(r.id);
431
+ if (agent)
432
+ return agent;
433
+ agent = this.factory({
434
+ tool: (session, detail) => {
435
+ if (this.agents.get(r.id) === agent)
436
+ this.event(r, 'tool', { session, detail });
437
+ },
438
+ permission: async (request) => {
439
+ if (r.status !== 'running' || this.closing || this.agents.get(r.id) !== agent)
440
+ return undefined;
441
+ const once = request.options.find((o) => o.kind === 'allow_once');
442
+ if (r.plan.autoApprove && once) {
443
+ this.event(r, 'permission', {
444
+ session: request.sessionId,
445
+ selected: once.optionId,
446
+ });
447
+ return once.optionId;
448
+ }
449
+ const question = {
450
+ id: randomUUID(),
451
+ text: request.toolCall.title ?? 'Choose an agent permission.',
452
+ options: request.options.map((o) => ({
453
+ id: o.optionId,
454
+ name: o.name,
455
+ })),
456
+ };
457
+ this.ask(r, question, 'permission');
458
+ return new Promise((resolve) => this.pending.set(r.id, { id: question.id, resolve }));
459
+ },
460
+ }, r.plan.repository);
461
+ this.agents.set(r.id, agent);
462
+ return agent;
463
+ }
464
+ async drive(r) {
465
+ try {
466
+ while (!this.closing && r.status === 'running') {
467
+ const harness = this.client(r), role = r.phase, task = r.plan.tasks[r.index];
468
+ if (!r[role]) {
469
+ const session = await harness.session(r.plan.repository);
470
+ if (this.closing || r.status !== 'running')
471
+ return;
472
+ r[role] = session;
473
+ this.save(r, 'session_started', {
474
+ role,
475
+ session,
476
+ task: task.name,
477
+ generation: r.generation,
478
+ });
479
+ }
480
+ const session = r[role], messages = [...r.messages];
481
+ const data = {
482
+ task: role === 'verifier'
483
+ ? task
484
+ : {
485
+ name: task.name,
486
+ instructions: task.instructions,
487
+ checks: task.checks,
488
+ },
489
+ incoming: messages,
490
+ priorTasks: r.accepted.slice(-8).map((a) => ({
491
+ name: a.name,
492
+ result: a.result.slice(0, 4096),
493
+ })),
494
+ feedback: r.feedback,
495
+ operatorGuidance: r.guidance.join('\n').slice(-65536),
496
+ ...(role === 'verifier' ? { candidate: r.candidate } : {}),
497
+ };
498
+ const instructions = role === 'worker'
499
+ ? 'Implement the assigned task using your normal tools in this project. Preserve prior edits, HEAD and staging. Install dependencies and run the relevant checks. Finish commands and stop temporary background services before submitting. Act on feedback from independent review. End with one line of JSON: {"kind":"result","summary":"result and executed checks"}.'
500
+ : 'Independently verify the candidate in the current repository against the verification prompt. Inspect and test it yourself. Leave the source unchanged. If task.checks are specified, run each command with your own harness and include a checks array in the final JSON with command (exact), passed (boolean), and evidence (observed output) for each. End with one line of JSON: {"kind":"verdict","decision":"accept" or "reject","reason":"specific evidence or actionable repair instructions"}.';
501
+ this.save(r, 'turn_started', { role, session, task: task.name });
502
+ const raw = await harness.prompt(session, instructions +
503
+ ' Only for a genuine decision about intent or scope, end with {"kind":"question","question":"decision needed"}.\n' +
504
+ JSON.stringify(data));
505
+ if (this.closing || r.status !== 'running')
506
+ return;
507
+ // Retain messages until a turn consumes them successfully.
508
+ r.messages.splice(0, messages.length);
509
+ const line = raw
510
+ .trim()
511
+ .replace(/^```(?:json)?\s*|\s*```$/g, '')
512
+ .trim();
513
+ let value;
514
+ try {
515
+ value = JSON.parse(line);
516
+ }
517
+ catch {
518
+ try {
519
+ value = JSON.parse(line.split('\n').at(-1));
520
+ }
521
+ catch { }
522
+ }
523
+ const reply = role === 'worker'
524
+ ? workerReply.safeParse(value)
525
+ : verifierReply.safeParse(value);
526
+ if (!reply.success &&
527
+ role === 'verifier' &&
528
+ r.formatErrors < r.plan.repairs) {
529
+ r.formatErrors++;
530
+ r.feedback =
531
+ 'Your verdict could not be parsed. Return the specified JSON verdict and evidence.';
532
+ this.save(r, 'invalid_verdict', { session });
533
+ continue;
534
+ }
535
+ if (!reply.success && role === 'verifier') {
536
+ this.restart(r, 'The verifier did not return a valid verdict.');
537
+ await this.dispose(r);
538
+ return;
539
+ }
540
+ if (!reply.success) {
541
+ await this.repair(r, 'Invalid ' +
542
+ role +
543
+ ' response. Return the requested final JSON object.');
544
+ continue;
545
+ }
546
+ r.formatErrors = 0;
547
+ const v = reply.data;
548
+ if (v.kind === 'question') {
549
+ this.ask(r, { id: randomUUID(), text: v.question });
550
+ return;
551
+ }
552
+ const revision = snapshot(r.plan.repository, this.dir(r));
553
+ if (v.kind === 'result') {
554
+ r.candidate = { summary: v.summary, revision };
555
+ delete r.verifier;
556
+ r.phase = 'verifier';
557
+ r.feedback = '';
558
+ this.save(r, 'submitted', { session, revision, summary: v.summary });
559
+ continue;
560
+ }
561
+ const candidate = r.candidate;
562
+ const missing = task.checks?.filter((command) => !v.checks?.some((c) => c.command === command && c.passed));
563
+ if (v.decision === 'accept' && missing?.length) {
564
+ v.decision = 'reject';
565
+ v.reason =
566
+ 'Missing passing verifier evidence for ' +
567
+ missing.join(', ') +
568
+ '. ' +
569
+ v.reason;
570
+ }
571
+ this.save(r, 'verdict', {
572
+ worker: r.worker,
573
+ verifier: session,
574
+ revision: candidate.revision,
575
+ ...v,
576
+ });
577
+ if (v.decision === 'reject' ||
578
+ candidate.revision !== revision ||
579
+ r.messages.length ||
580
+ messages.length) {
581
+ await this.repair(r, v.decision === 'reject'
582
+ ? v.reason
583
+ : candidate.revision !== revision
584
+ ? 'Source changed during verification. Submit the current candidate.'
585
+ : 'Address user guidance before resubmitting: ' +
586
+ [...messages, ...r.messages].join('\n'));
587
+ continue;
588
+ }
589
+ const accepted = {
590
+ name: task.name,
591
+ result: candidate.summary,
592
+ revision,
593
+ worker: r.worker,
594
+ verifier: session,
595
+ verdict: {
596
+ decision: v.decision,
597
+ reason: v.reason,
598
+ ...(v.checks ? { checks: v.checks } : {}),
599
+ },
600
+ };
601
+ const patch = join(this.dir(r), revision + '.patch'), tmp = patch + '.tmp', fd = openSync(tmp, 'w', 0o600);
602
+ try {
603
+ try {
604
+ writePatch(r.plan.repository, this.dir(r), r.baseline, revision, fd);
605
+ }
606
+ finally {
607
+ closeSync(fd);
608
+ }
609
+ renameSync(tmp, patch);
610
+ }
611
+ finally {
612
+ rmSync(tmp, { force: true });
613
+ }
614
+ r.accepted.push(accepted);
615
+ r.guidance = [];
616
+ r.index++;
617
+ r.phase = 'worker';
618
+ r.feedback = '';
619
+ r.repairsUsed = 0;
620
+ r.generation = 0;
621
+ delete r.worker;
622
+ delete r.verifier;
623
+ delete r.candidate;
624
+ if (r.index === r.plan.tasks.length)
625
+ r.status = 'completed';
626
+ this.save(r, 'task_accepted', accepted);
627
+ await this.dispose(r);
628
+ }
629
+ }
630
+ catch (error) {
631
+ if (this.closing || terminal(r.status) || r.status === 'pausing' || r.status === 'paused')
632
+ return;
633
+ this.restart(r, diagnostic(error));
634
+ await this.dispose(r);
635
+ }
636
+ }
637
+ async repair(r, reason) {
638
+ if (r.repairsUsed >= r.plan.repairs) {
639
+ this.restart(r, reason);
640
+ await this.dispose(r);
641
+ return;
642
+ }
643
+ r.repairsUsed++;
644
+ r.attempts.push(reason);
645
+ r.feedback = reason;
646
+ r.phase = 'worker';
647
+ delete r.verifier;
648
+ this.save(r, 'repair_requested', { worker: r.worker, reason });
649
+ }
650
+ }