code60-transmission-server 0.0.0-stage → 0.1.0-staging.13

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 (98) hide show
  1. package/LICENSE +180 -0
  2. package/README.engine.md +463 -0
  3. package/README.md +376 -2
  4. package/dist/src/broker/filesystem.js +385 -0
  5. package/dist/src/broker/index.js +777 -0
  6. package/dist/src/broker/native/README.md +207 -0
  7. package/dist/src/broker/native/build.js +46 -0
  8. package/dist/src/broker/native/command-helper.c +93 -0
  9. package/dist/src/broker/native/fs-helper.c +529 -0
  10. package/dist/src/broker/native/git-helper.c +205 -0
  11. package/dist/src/broker/policy.js +149 -0
  12. package/dist/src/broker/startup-lock.js +14 -0
  13. package/dist/src/broker/types.js +11 -0
  14. package/dist/src/cli/configure.js +208 -0
  15. package/dist/src/cli/daemon.js +369 -0
  16. package/dist/src/cli/helpers.js +112 -0
  17. package/dist/src/cli/main.js +189 -0
  18. package/dist/src/cli/runtime-build.js +38 -0
  19. package/dist/src/config/coding-policy.js +4 -0
  20. package/dist/src/config/deployment.js +183 -0
  21. package/dist/src/config/documents.js +29 -0
  22. package/dist/src/config/profile-validation.js +129 -0
  23. package/dist/src/config/schema-graph.js +237 -0
  24. package/dist/src/config/schema-loader.js +185 -0
  25. package/dist/src/config/validation-pool.js +105 -0
  26. package/dist/src/config/validation-protocol.js +1 -0
  27. package/dist/src/config/validation-worker.js +106 -0
  28. package/dist/src/config/workflow-language.js +9 -0
  29. package/dist/src/config/workflow-schema.json +545 -0
  30. package/dist/src/config/workflow-types.js +1 -0
  31. package/dist/src/config/workflow-validation.js +95 -0
  32. package/dist/src/engine/budgets.js +50 -0
  33. package/dist/src/engine/clocks.js +27 -0
  34. package/dist/src/engine/commands.js +477 -0
  35. package/dist/src/engine/contracts.js +11 -0
  36. package/dist/src/engine/drain-state.js +31 -0
  37. package/dist/src/engine/effective-permissions.js +120 -0
  38. package/dist/src/engine/instruction-pins.js +205 -0
  39. package/dist/src/engine/retries.js +50 -0
  40. package/dist/src/engine/state.js +1 -0
  41. package/dist/src/engine/timing.js +23 -0
  42. package/dist/src/engine/tool-observations.js +87 -0
  43. package/dist/src/engine/workflow-engine.js +1864 -0
  44. package/dist/src/main.js +28 -0
  45. package/dist/src/mcp/catalog.js +71 -0
  46. package/dist/src/mcp/main.js +26 -0
  47. package/dist/src/mcp/server.js +177 -0
  48. package/dist/src/runtime/codex-app-server.js +91 -0
  49. package/dist/src/runtime/codex-executable.js +50 -0
  50. package/dist/src/runtime/containment.js +82 -0
  51. package/dist/src/runtime/engine-driver.js +221 -0
  52. package/dist/src/runtime/json-line-writer.js +192 -0
  53. package/dist/src/runtime/pinned-instruction-sources.js +24 -0
  54. package/dist/src/runtime/protocol-client.js +264 -0
  55. package/dist/src/runtime/protocol-pool.js +183 -0
  56. package/dist/src/runtime/protocol-projection.js +393 -0
  57. package/dist/src/runtime/protocol-types.js +1 -0
  58. package/dist/src/runtime/protocol-worker.js +18 -0
  59. package/dist/src/runtime/provider-bridge.js +290 -0
  60. package/dist/src/runtime/provider-credentials.js +41 -0
  61. package/dist/src/runtime/provider-transport.js +406 -0
  62. package/dist/src/runtime/runtime-broker.js +213 -0
  63. package/dist/src/runtime/workspace-instructions.js +120 -0
  64. package/dist/src/runtime/workspace-view.js +74 -0
  65. package/dist/src/server/api-contract.json +11637 -0
  66. package/dist/src/server/api-types.js +1 -0
  67. package/dist/src/server/application.js +44 -0
  68. package/dist/src/server/auth.js +67 -0
  69. package/dist/src/server/broker-handlers.js +242 -0
  70. package/dist/src/server/coding.js +281 -0
  71. package/dist/src/server/control-plane.js +50 -0
  72. package/dist/src/server/deployment.js +249 -0
  73. package/dist/src/server/errors.js +22 -0
  74. package/dist/src/server/history-handlers.js +130 -0
  75. package/dist/src/server/http.js +124 -0
  76. package/dist/src/server/paging.js +56 -0
  77. package/dist/src/server/publication.js +119 -0
  78. package/dist/src/server/tool-event-handler.js +77 -0
  79. package/dist/src/server/workspace-handlers.js +34 -0
  80. package/dist/src/storage/coordinator.js +224 -0
  81. package/dist/src/storage/startup-lock.js +71 -0
  82. package/dist/src/storage/store.js +167 -0
  83. package/dist/src/tools/check-worker.js +81 -0
  84. package/dist/src/tools/checks.js +117 -0
  85. package/dist/src/tools/command-check.js +34 -0
  86. package/dist/src/tools/commands.js +312 -0
  87. package/dist/src/tools/developer.js +355 -0
  88. package/dist/src/tools/dns.js +248 -0
  89. package/dist/src/tools/http-contract.js +38 -0
  90. package/dist/src/tools/http.js +358 -0
  91. package/dist/src/tools/index.js +194 -0
  92. package/dist/src/tools/worker-check.js +73 -0
  93. package/dist/src/workspaces/git.js +227 -0
  94. package/dist/src/workspaces/index.js +937 -0
  95. package/dist/src/workspaces/source.js +295 -0
  96. package/examples/deployment.local.json +22 -0
  97. package/package.json +71 -4
  98. package/scripts/postinstall.mjs +26 -0
@@ -0,0 +1,50 @@
1
+ import { ApiError } from '../server/errors.js';
2
+ import { durationMs } from './timing.js';
3
+ export function limitsFor(step, role, override = {}) {
4
+ const value = {};
5
+ const bounds = role === 'worker' ? { count: step.execution['max-attempts-per-session'], timeout: step.execution.session?.timeout?.duration } :
6
+ role === 'verifier' ? { count: step.exitCriteria.semantic?.verifier['max-attempts'], timeout: step.exitCriteria.semantic?.verifier.timeout?.duration } :
7
+ { count: step.handoffArtifact?.['max-attempts'], timeout: step.handoffArtifact?.timeout?.duration };
8
+ if (bounds.count !== undefined)
9
+ value.maxSubmissions = bounds.count;
10
+ if (bounds.timeout !== undefined)
11
+ value.executionTimeLimit = bounds.timeout;
12
+ if (role === 'worker') {
13
+ if (override.workerMaxSubmissions !== undefined)
14
+ value.maxSubmissions = override.workerMaxSubmissions;
15
+ if (override.workerExecutionTimeLimit !== undefined)
16
+ value.executionTimeLimit = override.workerExecutionTimeLimit;
17
+ }
18
+ else
19
+ Object.assign(value, role === 'verifier' ? override.verifierLimits : override.handoffLimits);
20
+ if (value.maxSubmissions === undefined && value.executionTimeLimit === undefined)
21
+ throw new ApiError(422, 'unbounded_session', 'Every selected session role requires an explicit finite count or execution budget.');
22
+ return value;
23
+ }
24
+ export function validateIncrease(run, execution, step, current, increase, worker) {
25
+ const larger = (next, previous) => {
26
+ if (next !== undefined && (previous === undefined || !Number.isSafeInteger(next) || next <= previous))
27
+ throw new ApiError(422, 'budget_not_increased', 'Budget changes must be strictly larger absolute maxima.');
28
+ };
29
+ const longer = (next, previous) => larger(next === undefined ? undefined : durationMs(next), previous === undefined ? undefined : durationMs(previous));
30
+ const workerLimits = worker?.limits ?? limitsFor(step, 'worker', current);
31
+ larger(increase.maxSessionResets, execution.maxSessionResets);
32
+ larger(increase.workerMaxSubmissions, workerLimits.maxSubmissions);
33
+ longer(increase.workerExecutionTimeLimit, workerLimits.executionTimeLimit);
34
+ larger(increase.infrastructureRetries, run.policy.infrastructureRetries ?? 3);
35
+ larger(increase.verificationRetries, run.policy.verificationRetries ?? 3);
36
+ longer(increase.submissionInterval, current.submissionInterval ?? step.execution['submission-interval']?.duration);
37
+ for (const role of ['verifier', 'handoff']) {
38
+ const next = role === 'verifier' ? increase.verifierLimits : increase.handoffLimits;
39
+ if (!next)
40
+ continue;
41
+ const previous = limitsFor(step, role, current);
42
+ larger(next.maxSubmissions, previous.maxSubmissions);
43
+ longer(next.executionTimeLimit, previous.executionTimeLimit);
44
+ }
45
+ }
46
+ export function mergeIncrease(current, increase) {
47
+ return { ...current, ...increase,
48
+ ...(current.verifierLimits || increase.verifierLimits ? { verifierLimits: { ...current.verifierLimits, ...increase.verifierLimits } } : {}),
49
+ ...(current.handoffLimits || increase.handoffLimits ? { handoffLimits: { ...current.handoffLimits, ...increase.handoffLimits } } : {}) };
50
+ }
@@ -0,0 +1,27 @@
1
+ import { durationMs } from './timing.js';
2
+ import { ApiError } from '../server/errors.js';
3
+ export function clock(policy, now = Date.now()) {
4
+ if (policy.executionTimeLimit && (!policy.downtimeAccounting || !policy.blockedTimeAccounting))
5
+ throw new ApiError(422, 'timing_accounting_required', 'Execution budgets require explicit downtime and blocked-time accounting.');
6
+ const deadlineAt = policy.deadlineAt === undefined ? undefined : Date.parse(policy.deadlineAt);
7
+ if (deadlineAt !== undefined && !Number.isFinite(deadlineAt))
8
+ throw new ApiError(422, 'invalid_deadline', 'Absolute deadline is invalid.');
9
+ return { consumedMs: 0, changedAt: now, running: true,
10
+ ...(policy.executionTimeLimit ? { limitMs: durationMs(policy.executionTimeLimit) } : {}),
11
+ ...(deadlineAt === undefined ? {} : { deadlineAt }) };
12
+ }
13
+ export function consumed(value, now = Date.now()) {
14
+ return value.consumedMs + (value.running ? Math.max(0, now - value.changedAt) : 0);
15
+ }
16
+ export function checkpoint(value, running, now = Date.now()) {
17
+ return { ...value, consumedMs: consumed(value, now), changedAt: now, running };
18
+ }
19
+ export function status(value, stopped = false, now = Date.now()) {
20
+ const executionConsumedMs = consumed(value, now);
21
+ return { executionConsumedMs, clockState: stopped ? 'stopped' : value.running ? 'running' : 'paused',
22
+ ...(value.limitMs === undefined ? {} : { executionRemainingMs: Math.max(0, value.limitMs - executionConsumedMs) }),
23
+ ...(value.deadlineAt === undefined ? {} : { deadlineAt: new Date(value.deadlineAt).toISOString() }) };
24
+ }
25
+ export function expired(value, now = Date.now()) {
26
+ return (value.deadlineAt !== undefined && now >= value.deadlineAt) || (value.limitMs !== undefined && consumed(value, now) >= value.limitMs);
27
+ }
@@ -0,0 +1,477 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { canonical, digest } from '../broker/policy.js';
3
+ import { EngineStore } from '../storage/store.js';
4
+ import { commandIdentity } from '../server/control-plane.js';
5
+ import { ApiError, problem } from '../server/errors.js';
6
+ import { clock, checkpoint, consumed, expired, status } from './clocks.js';
7
+ import { durationMs } from './timing.js';
8
+ import { RetryLedger } from './retries.js';
9
+ import { validateIncrease } from './budgets.js';
10
+ export const terminal = (run) => ['succeeded', 'failed', 'cancelled'].includes(run.state);
11
+ const sha = (content) => `sha256:${createHash('sha256').update(content, 'utf8').digest('hex')}`;
12
+ const conflict = (message = 'This command is not permitted in the current state.') => { throw new ApiError(409, 'state_conflict', message); };
13
+ /** Command admission is SQL-only. Effects belong to the sequential executor,
14
+ * which consumes durable plans after commit and rechecks every closed gate. */
15
+ export class RunCommands {
16
+ options;
17
+ store;
18
+ retries;
19
+ now;
20
+ constructor(options) {
21
+ this.options = options;
22
+ this.store = options.store;
23
+ this.retries = new RetryLedger(this.store);
24
+ this.now = options.now ?? Date.now;
25
+ }
26
+ plan(runId) {
27
+ const value = this.store.private('run_plan', runId);
28
+ if (!value)
29
+ throw new ApiError(409, 'run_state_unavailable', 'Durable execution state is unavailable.');
30
+ return value;
31
+ }
32
+ savePlan(runId, plan) { this.store.setPrivate('run_plan', runId, plan); }
33
+ wake(runId) { this.store.coordinator.afterCommit(() => this.options.wake(runId)); }
34
+ binding(sessionId) {
35
+ const authority = this.store.private('session_authority', sessionId);
36
+ if (!authority)
37
+ throw new ApiError(409, 'stale_epoch', 'Session authority is unavailable.');
38
+ return authority.binding;
39
+ }
40
+ current(sessionId, epoch) {
41
+ const session = this.store.find('sessions', sessionId);
42
+ const broker = this.store.coordinator.db.prepare('SELECT body,fenced FROM broker_sessions WHERE id=?').get(sessionId);
43
+ return !!session && session.epoch === epoch && !!broker && !broker.fenced && JSON.parse(broker.body).epoch === epoch;
44
+ }
45
+ updateRun(runId, patch) {
46
+ return this.store.coordinator.atomic(() => {
47
+ const previous = this.store.get('runs', runId);
48
+ const value = { ...previous, ...patch, version: previous.version + 1, updatedAt: new Date(this.now()).toISOString() };
49
+ if (patch.policy)
50
+ this.syncBrokerApprovalTimeoutSql(runId, value.policy);
51
+ this.store.put('runs', value);
52
+ if (previous.state !== value.state)
53
+ this.store.event(runId, 'run_state_changed', 'run', runId, { state: value.state });
54
+ return value;
55
+ });
56
+ }
57
+ /** Only future authority uses this effective policy. Issued actions and
58
+ * historical receipts retain their original immutable admission expiry. */
59
+ syncBrokerApprovalTimeoutSql(runId, policy) {
60
+ const timeout = durationMs(policy.approvalTimeout ?? '24h');
61
+ const result = this.store.coordinator.db.prepare("UPDATE broker_runs SET body=json_set(body,'$.approvalTimeoutMs',?) WHERE id=?")
62
+ .run(timeout, runId);
63
+ if (result.changes !== 1)
64
+ throw new Error('broker_run_gate_missing');
65
+ }
66
+ operation(runId, kind) {
67
+ const timestamp = new Date(this.now()).toISOString();
68
+ const operation = { id: randomUUID(), kind, runId, state: 'pending', createdAt: timestamp, updatedAt: timestamp };
69
+ this.store.put('operations', operation, { runId });
70
+ return operation;
71
+ }
72
+ operationReceipt(operation) {
73
+ return { status: 202, headers: { Location: `/api/v1/operations/${operation.id}` }, body: operation };
74
+ }
75
+ block(runId, reason, message, kinds, extra = {}) {
76
+ return this.store.coordinator.atomic(() => {
77
+ const run = this.store.get('runs', runId);
78
+ const prior = run.pendingBlockIds.map(id => this.store.get('blocks', id)).find(value => value.reason === reason && value.hold === extra.hold);
79
+ if (prior)
80
+ return prior;
81
+ const block = { id: randomUUID(), runId, ...(run.currentStepId ? { stepExecutionId: run.currentStepId } : {}),
82
+ reason, status: 'pending', version: 1, message, allowedDecisionKinds: kinds, createdAt: new Date(this.now()).toISOString(), ...extra };
83
+ this.store.put('blocks', block, { runId });
84
+ this.options.broker.setHold(runId, `block:${block.id}`, true);
85
+ this.updateRun(runId, { pendingBlockIds: [...run.pendingBlockIds, block.id], activeBlockId: run.activeBlockId ?? block.id,
86
+ state: run.executionControl.status === 'running' ? 'blocked' : run.state });
87
+ this.store.event(runId, reason === 'pause_stalled' ? 'pause_stalled' : 'block_created', 'block', block.id, { reason });
88
+ return block;
89
+ });
90
+ }
91
+ resolveBlock(id) {
92
+ const block = this.store.get('blocks', id);
93
+ if (block.status === 'resolved')
94
+ return;
95
+ this.store.put('blocks', { ...block, ...(block.recoveryAllowed ? { recoveryAllowed: false } : {}),
96
+ status: 'resolved', version: block.version + 1, resolvedAt: new Date(this.now()).toISOString() }, { runId: block.runId });
97
+ const run = this.store.get('runs', block.runId), pendingBlockIds = run.pendingBlockIds.filter(value => value !== id);
98
+ this.options.broker.setHold(run.id, `block:${id}`, false);
99
+ const next = { pendingBlockIds };
100
+ if (pendingBlockIds[0])
101
+ next.activeBlockId = pendingBlockIds[0];
102
+ else {
103
+ // Canonical JSON excludes no values: remove optional properties rather
104
+ // than serializing undefined into durable records.
105
+ const { activeBlockId: _old, ...without } = run;
106
+ this.store.put('runs', { ...without, pendingBlockIds, version: run.version + 1, updatedAt: new Date(this.now()).toISOString() });
107
+ return;
108
+ }
109
+ this.updateRun(run.id, next);
110
+ }
111
+ operatorRun(context, runId) {
112
+ if (context.principal.audience !== 'operator')
113
+ throw new ApiError(403, 'forbidden', 'Operator authentication is required.');
114
+ const run = this.store.get('runs', runId);
115
+ this.options.auth.assertWorkspace(context.principal, run.workspaceId);
116
+ return run;
117
+ }
118
+ adapter(context) {
119
+ const principal = context.principal;
120
+ if (principal.audience !== 'adapter' || principal.sessionId !== context.params.sessionId)
121
+ throw new ApiError(403, 'assignment_forbidden', 'Session is not assigned.');
122
+ const session = this.store.get('sessions', principal.sessionId), authority = this.store.private('session_authority', session.id);
123
+ if (!authority || !this.current(session.id, principal.epoch) || session.role !== principal.role ||
124
+ authority.binding.epoch !== principal.epoch || authority.binding.role !== principal.role || authority.binding.sessionId !== session.id ||
125
+ authority.binding.runId !== session.runId || authority.binding.stepExecutionId !== session.stepExecutionId ||
126
+ authority.binding.profileVersionId !== session.profileVersionId)
127
+ throw new ApiError(409, 'stale_epoch', 'Session authority is stale.');
128
+ const run = this.store.get('runs', session.runId);
129
+ this.options.auth.assertWorkspace(principal, run.workspaceId);
130
+ return { session, authority, run };
131
+ }
132
+ live(run) { if (terminal(run) || this.plan(run.id).cancelOperationId)
133
+ conflict(); }
134
+ runCommand(context, suffix, apply) {
135
+ const id = context.params.runId;
136
+ this.operatorRun(context, id);
137
+ return this.store.command(commandIdentity(context, `/runs/${id}/${suffix}`), () => {
138
+ this.store.expectMatch('runs', id, context.header('if-match'));
139
+ const run = this.operatorRun(context, id);
140
+ this.live(run);
141
+ const result = apply(run, this.plan(id));
142
+ this.wake(id);
143
+ return result;
144
+ });
145
+ }
146
+ async createRun(context) {
147
+ const input = context.body;
148
+ if (context.principal.audience !== 'operator')
149
+ throw new ApiError(403, 'forbidden', 'Operator authentication is required.');
150
+ this.options.auth.assertWorkspace(context.principal, input.workspaceId);
151
+ const identity = commandIdentity(context, '/runs'), original = this.store.receipt(identity);
152
+ if (original)
153
+ return { receipt: original, replay: true };
154
+ const version = this.store.get('workflow_versions', input.workflowVersionId);
155
+ const validated = await this.options.publication.workflowReport(version, this.options.checkNames(), context.signal);
156
+ if (!validated.report.valid || !validated.definition)
157
+ throw new ApiError(422, 'invalid_workflow', 'Workflow configuration is invalid.', false, validated.report.issues);
158
+ const definition = validated.definition, bindings = await this.options.pins.resolve(definition, input.agentProfiles ?? {}, context.signal);
159
+ if (definition.inputs !== undefined) {
160
+ const report = await this.options.publication.validation.run({ kind: 'artifact', rootUri: 'urn:code60:run-inputs', resources: [{ uri: 'urn:code60:run-inputs', schema: definition.inputs }], value: input.inputs ?? null }, { signal: context.signal });
161
+ if (!report.valid)
162
+ throw new ApiError(422, 'invalid_run_inputs', 'Run inputs do not match the workflow input schema.', false, report.errors);
163
+ }
164
+ // Do not charge a new run, open a native root or reserve a lease on replay.
165
+ const raced = this.store.receipt(identity);
166
+ if (raced)
167
+ return { receipt: raced, replay: true };
168
+ // Selecting uncommitted results opts a legacy, idle workspace into source
169
+ // tracking before its baseline is captured. Commit-mode runs stay pinned
170
+ // to their existing workspace semantics.
171
+ if (input.resultMode === 'working_tree')
172
+ this.options.workspaces.enableSourceTracking(input.workspaceId);
173
+ const id = randomUUID(), now = this.now(), timingPolicy = input.timing ?? {}, runClock = clock(timingPolicy, now);
174
+ const global = definition.config?.timeout;
175
+ if (global)
176
+ runClock.deadlineAt = Math.min(runClock.deadlineAt ?? Infinity, now + durationMs(global.duration));
177
+ const createdAt = new Date(now).toISOString(), config = definition.config;
178
+ const policy = { infrastructureRetries: config?.['infrastructure-retries'] ?? 3,
179
+ verificationRetries: config?.['verification-retries'] ?? 3, schemaFetchTimeout: config?.['schema-fetch']?.timeout ?? '30s',
180
+ schemaFetchRetryDelays: config?.['schema-fetch']?.['retry-delays'] ?? ['1s', '2s'],
181
+ pauseGracePeriod: config?.['pause-grace-period'] ?? '30s', approvalTimeout: config?.['approval-timeout'] ?? '24h', ...input.policy };
182
+ const approvalTimeoutMs = durationMs(policy.approvalTimeout);
183
+ const plan = { definition, ordinal: 0, stage: 'startup', timingPolicy, clock: runClock, stepClocks: {}, queuedDecisions: [],
184
+ resultMode: input.resultMode ?? 'commit', inputs: input.inputs ?? null, inputArtifacts: input.inputArtifacts ?? [],
185
+ steps: definition.steps.map((_step, index) => ({ id: randomUUID(), profiles: Object.fromEntries(Object.entries(bindings[index]).map(([role, profileVersionId]) => [role, { profileVersionId }])),
186
+ verificationCharges: 0, verificationConsumedMs: 0 })) };
187
+ const run = { id, resultMode: input.resultMode ?? 'commit', workflowVersionId: version.id, workspaceId: input.workspaceId, state: 'starting', version: 1, policy,
188
+ timing: status(runClock, false, now), createdAt, updatedAt: createdAt,
189
+ executionControl: { status: 'running', inFlightWork: [] }, pendingBlockIds: [], approvalWait: { status: 'none', pendingApprovalIds: [], inFlightWork: [] },
190
+ agentProfiles: { ...config?.['agent-profiles'], ...input.agentProfiles } };
191
+ let receipt;
192
+ this.options.workspaces.acquireLease(input.workspaceId, id, { onAdmittedSql: () => {
193
+ this.store.put('runs', run);
194
+ this.savePlan(id, plan);
195
+ for (const document of input.inputArtifacts ?? []) {
196
+ const artifactId = randomUUID();
197
+ this.store.put('artifacts', { id: artifactId, runId: id, kind: 'input', document, contentDigest: digest(document.content), state: 'accepted', createdAt }, { runId: id, immutable: true });
198
+ }
199
+ plan.inputArtifacts = [];
200
+ this.savePlan(id, plan);
201
+ this.store.coordinator.db.prepare('INSERT INTO broker_runs VALUES (?,?)').run(id, canonical({ operatorPaused: false, cancelled: false, holds: [], deadlineAt: runClock.deadlineAt ?? null, approvalTimeoutMs }));
202
+ for (const [index, stepPlan] of plan.steps.entries()) {
203
+ const step = definition.steps[index];
204
+ this.store.put('steps', { id: stepPlan.id, runId: id, workflowStepId: step.id, ordinal: index, state: 'pending', resetsUsed: 0,
205
+ maxSessionResets: step.execution['max-session-resets'], timing: { executionConsumedMs: 0, clockState: 'stopped' },
206
+ agentProfiles: bindings[index] }, { runId: id });
207
+ }
208
+ this.store.event(id, 'run_state_changed', 'run', id, { state: 'starting' }, now);
209
+ receipt = { status: 202, headers: { Location: `/api/v1/runs/${id}`, ETag: this.store.etag('runs', id) }, body: run };
210
+ this.store.saveReceipt(identity, receipt);
211
+ this.wake(id);
212
+ } }, input.resultMode ?? 'commit');
213
+ return { receipt, replay: false };
214
+ }
215
+ pause(context) {
216
+ return this.runCommand(context, 'pauses', (run, plan) => {
217
+ if (run.executionControl.status === 'resuming')
218
+ conflict();
219
+ if (['pausing', 'paused'].includes(run.executionControl.status)) {
220
+ if (!run.executionControl.pauseOperationId)
221
+ conflict();
222
+ return this.operationReceipt(this.store.get('operations', run.executionControl.pauseOperationId));
223
+ }
224
+ const operation = this.operation(run.id, 'pause'), work = this.options.work(run.id), now = this.now();
225
+ this.options.broker.pause(run.id);
226
+ this.store.setPrivate('pause_admission', run.id, { sessionIds: [...new Set(work.flatMap(value => value.sessionId ? [value.sessionId] : []))] });
227
+ this.updateRun(run.id, { state: 'pausing', executionControl: { status: 'pausing', continuationState: run.state,
228
+ pauseOperationId: operation.id, requestedAt: new Date(now).toISOString(),
229
+ graceDeadlineAt: new Date(now + durationMs(run.policy.pauseGracePeriod ?? '30s')).toISOString(), inFlightWork: work } });
230
+ this.savePlan(run.id, plan);
231
+ this.store.event(run.id, 'pause_requested', 'operation', operation.id, {});
232
+ return this.operationReceipt(operation);
233
+ });
234
+ }
235
+ resume(context) {
236
+ return this.runCommand(context, 'resumptions', run => {
237
+ if (run.executionControl.status !== 'paused')
238
+ conflict();
239
+ const operation = this.operation(run.id, 'resume');
240
+ this.updateRun(run.id, { state: 'resuming', executionControl: { ...run.executionControl, status: 'resuming', inFlightWork: [] } });
241
+ this.store.setPrivate('resume_operation', run.id, { id: operation.id });
242
+ this.store.event(run.id, 'resume_requested', 'operation', operation.id, {});
243
+ return this.operationReceipt(operation);
244
+ });
245
+ }
246
+ cancel(context) {
247
+ return this.runCommand(context, 'cancellations', (run, plan) => {
248
+ const operation = this.operation(run.id, 'cancel');
249
+ plan.cancelOperationId = operation.id;
250
+ plan.stage = 'cancel';
251
+ this.options.broker.cancel(run.id);
252
+ this.savePlan(run.id, plan);
253
+ for (const { value } of this.store.list('operations', { runId: run.id, limit: Number.MAX_SAFE_INTEGER })) {
254
+ if (value.id !== operation.id && ['pending', 'running', 'waiting_for_decision'].includes(value.state))
255
+ this.store.put('operations', { ...value, state: 'failed', updatedAt: new Date(this.now()).toISOString(),
256
+ error: problem(new ApiError(409, 'operation_superseded', 'Cancellation superseded this operation.'), context.requestId) }, { runId: run.id });
257
+ }
258
+ for (const { value } of this.store.list('sessions', { runId: run.id, limit: Number.MAX_SAFE_INTEGER }))
259
+ this.options.auth.revokeSession(value.id);
260
+ const now = this.now();
261
+ this.updateRun(run.id, { state: 'pausing', executionControl: { status: 'pausing',
262
+ continuationState: run.executionControl.continuationState ?? (['pausing', 'paused', 'resuming'].includes(run.state) ? 'interrupted' : run.state),
263
+ pauseOperationId: operation.id, requestedAt: new Date(now).toISOString(),
264
+ graceDeadlineAt: new Date(now + durationMs(run.policy.pauseGracePeriod ?? '30s')).toISOString(), inFlightWork: this.options.work(run.id) } });
265
+ return this.operationReceipt(operation);
266
+ });
267
+ }
268
+ recover(context) {
269
+ return this.runCommand(context, 'recoveries', (run, plan) => {
270
+ const recovery = run.pendingBlockIds.map(id => this.store.get('blocks', id)).filter(block => block.reason === 'resume_requires_recovery' && block.recoveryAllowed);
271
+ const commandRecovery = this.options.commandRecoveryRequired?.(run.id) ?? false;
272
+ const resolution = context.body.commandResolution;
273
+ if (commandRecovery && !resolution)
274
+ throw new ApiError(422, 'command_resolution_required', 'Read get_coding_task_result and supply commandResolution with the observed sourceDigest and preserve_changes or rollback.');
275
+ if (resolution && commandRecovery)
276
+ this.store.setPrivate('command_resolution', run.id, resolution);
277
+ if (plan.recoveryOperationId && commandRecovery && resolution) {
278
+ const held = this.store.private('command_recovery_block', run.id);
279
+ if (held)
280
+ this.resolveBlock(held.id);
281
+ const operation = this.store.get('operations', plan.recoveryOperationId);
282
+ this.store.put('operations', { ...operation, state: 'running' }, { runId: run.id });
283
+ this.wake(run.id);
284
+ return this.operationReceipt(operation);
285
+ }
286
+ if (run.state !== 'interrupted' && !recovery.length && run.executionControl.continuationState !== 'interrupted' && !commandRecovery)
287
+ conflict();
288
+ if (plan.recoveryOperationId)
289
+ conflict('Recovery is already pending.');
290
+ const operation = this.operation(run.id, 'recover');
291
+ plan.recoveryOperationId = operation.id;
292
+ for (const block of recovery)
293
+ this.resolveBlock(block.id);
294
+ this.options.broker.pause(run.id);
295
+ this.updateRun(run.id, { state: 'recovering', executionControl: { status: 'running', inFlightWork: [] } });
296
+ this.savePlan(run.id, plan);
297
+ this.store.event(run.id, 'recovery_started', 'operation', operation.id, {});
298
+ return this.operationReceipt(operation);
299
+ });
300
+ }
301
+ replace(context) {
302
+ return this.runCommand(context, 'profile-replacements', (run, plan) => {
303
+ if (run.executionControl.status !== 'paused' && run.state !== 'blocked')
304
+ conflict();
305
+ if (!run.currentStepId)
306
+ conflict('No current step is available.');
307
+ const operation = this.operation(run.id, 'replace_profile'), decision = context.body;
308
+ plan.queuedDecisions.push({ operationId: operation.id, decision, ...(run.currentStepId ? { stepExecutionId: run.currentStepId } : {}) });
309
+ this.savePlan(run.id, plan);
310
+ this.store.event(run.id, 'profile_replacement_requested', 'operation', operation.id, { role: decision.role, profileVersionId: decision.profileVersionId });
311
+ return { ...this.operationReceipt(operation), headers: { Location: `/api/v1/operations/${operation.id}`, ETag: this.store.etag('runs', run.id) } };
312
+ });
313
+ }
314
+ decide(context) {
315
+ const blockId = context.params.blockId, before = this.store.get('blocks', blockId);
316
+ this.operatorRun(context, before.runId);
317
+ return this.store.command(commandIdentity(context, `/blocks/${blockId}/decisions`), () => {
318
+ this.store.expectMatch('blocks', blockId, context.header('if-match'));
319
+ const block = this.store.get('blocks', blockId), run = this.operatorRun(context, block.runId);
320
+ this.live(run);
321
+ const input = context.body;
322
+ if (block.status !== 'pending' || !block.allowedDecisionKinds.includes(input.kind))
323
+ conflict();
324
+ if (input.kind === 'increase_budgets') {
325
+ const plan = this.plan(run.id), step = plan.steps[plan.ordinal];
326
+ validateIncrease(run, this.store.get('steps', step.id), plan.definition.steps[plan.ordinal], plan.budgetOverrides?.[step.id] ?? {}, input.budgets, step.workerSessionId ? this.store.get('sessions', step.workerSessionId) : undefined);
327
+ }
328
+ if (input.kind === 'rollback') {
329
+ this.rollbackOrdinal(run.id, input.baselineId);
330
+ }
331
+ if (input.kind === 'overwrite' && block.workspaceConflict?.conflictDigest !== input.conflictDigest)
332
+ conflict('Overwrite permission does not match this conflict.');
333
+ if (input.kind === 'extend_pause_grace' && (block.reason !== 'pause_stalled' || !block.hold))
334
+ conflict();
335
+ const operation = this.operation(run.id, 'apply_decision');
336
+ const decision = { id: randomUUID(), blockId, actorId: context.principal.id, decision: input,
337
+ operationId: operation.id, createdAt: new Date(this.now()).toISOString() };
338
+ this.store.put('decisions', decision, { runId: run.id, parentId: blockId, immutable: true });
339
+ if (input.kind !== 'overwrite' || input.approve) {
340
+ this.resolveBlock(blockId);
341
+ const plan = this.plan(run.id);
342
+ plan.queuedDecisions.push({ operationId: operation.id, decision: input, blockId,
343
+ ...(block.stepExecutionId ? { stepExecutionId: block.stepExecutionId } : {}) });
344
+ this.savePlan(run.id, plan);
345
+ }
346
+ else
347
+ this.store.put('operations', { ...operation, state: 'succeeded' }, { runId: run.id });
348
+ this.store.event(run.id, 'decision_recorded', 'decision', decision.id, { blockId, kind: input.kind });
349
+ this.wake(run.id);
350
+ return { status: 202, headers: { Location: `/api/v1/operations/${operation.id}` }, body: decision };
351
+ });
352
+ }
353
+ rollbackOrdinal(runId, baselineId) {
354
+ const baseline = this.store.get('baselines', baselineId), plan = this.plan(runId);
355
+ const ordinal = baseline.scope === 'run_start' ? 0 : plan.steps.findIndex(step => step.id === baseline.stepExecutionId);
356
+ if (baseline.runId !== runId || ordinal < 0 || ordinal > plan.ordinal || !plan.stepClocks[plan.steps[ordinal].id])
357
+ conflict('Baseline must belong to an already-entered step at or before the current step of this run.');
358
+ return ordinal;
359
+ }
360
+ submit(context, kind) {
361
+ const initial = this.adapter(context), suffix = kind === 'exit' ? 'exit-submissions' : kind === 'verdict' ? 'verification-verdicts' : 'handoff-submissions';
362
+ const identity = commandIdentity(context, `/sessions/${initial.session.id}/${suffix}`), original = this.store.receipt(identity);
363
+ if (original)
364
+ return { receipt: original, replay: true };
365
+ this.resultGate(initial.run, initial.session, initial.authority, kind);
366
+ const verdict = context.body;
367
+ if (kind === 'verdict') {
368
+ if (initial.authority.phase !== 'verification' || initial.session.role !== 'verifier' ||
369
+ verdict.subjectSubmissionId !== initial.authority.subjectSubmissionId || verdict.workspaceRevisionId !== initial.authority.workspaceRevisionId)
370
+ conflict('Verdict does not match its assigned subject and revision.');
371
+ this.options.workspaces.assertRevision(initial.run.id, verdict.workspaceRevisionId);
372
+ }
373
+ return this.store.command(identity, () => {
374
+ const { session, authority, run } = this.adapter(context);
375
+ this.live(run);
376
+ this.resultGate(run, session, authority, kind);
377
+ const input = context.body;
378
+ const document = 'report' in input ? input.report : input.artifact, now = this.now(), createdAt = new Date(now).toISOString();
379
+ const plan = this.plan(run.id), superseded = kind === 'exit' && !!plan.reset;
380
+ const artifact = { id: randomUUID(), runId: run.id, stepExecutionId: session.stepExecutionId, kind,
381
+ document, contentDigest: sha(document.content), state: superseded ? 'superseded' : 'submitted', createdAt };
382
+ const submission = { id: randomUUID(), runId: run.id, stepExecutionId: session.stepExecutionId, sessionId: session.id,
383
+ kind, state: superseded ? 'superseded' : 'received', attemptNumber: session.submissionsUsed + 1, artifactId: artifact.id, createdAt,
384
+ ...(kind === 'verdict' ? { subjectSubmissionId: verdict.subjectSubmissionId } : {}) };
385
+ authority.clock = checkpoint(authority.clock, false, now);
386
+ authority.lastSubmissionConsumedMs = consumed(authority.clock, now);
387
+ this.store.setPrivate('session_authority', session.id, authority);
388
+ this.store.put('sessions', { ...session, submissionsUsed: session.submissionsUsed + 1,
389
+ state: kind === 'exit' ? 'paused_for_verification' : 'paused', timing: status(authority.clock, false, now) }, { runId: run.id, parentId: session.stepExecutionId });
390
+ this.store.put('artifacts', artifact, { runId: run.id });
391
+ this.store.put('submissions', submission, { runId: run.id, parentId: session.id });
392
+ this.retries.complete(authority.logicalOperationId, submission.id);
393
+ if ('observedHeadCommit' in input)
394
+ this.store.setPrivate('submission_metadata', submission.id, { observedHeadCommit: input.observedHeadCommit });
395
+ if (session.role === 'verifier')
396
+ plan.steps[plan.ordinal].verificationCharges++;
397
+ if (session.role === 'handoff' && plan.reset)
398
+ plan.reset.handoffCharges = (plan.reset.handoffCharges ?? 0) + 1;
399
+ if (!superseded) {
400
+ plan.pendingSubmissionId = submission.id;
401
+ plan.stage = 'evaluate';
402
+ }
403
+ this.savePlan(run.id, plan);
404
+ this.options.broker.setHold(run.id, 'submission', !superseded);
405
+ this.store.event(run.id, 'submission_received', 'submission', submission.id, { kind, sessionId: session.id });
406
+ this.wake(run.id);
407
+ return { status: 202, headers: { Location: `/api/v1/submissions/${submission.id}` }, body: submission };
408
+ });
409
+ }
410
+ resultGate(run, session, authority, kind) {
411
+ this.live(run);
412
+ const permitted = run.executionControl.status === 'running' || run.executionControl.status === 'pausing' &&
413
+ this.store.private('pause_admission', run.id)?.sessionIds.includes(session.id);
414
+ if (!permitted || run.approvalWait.status === 'waiting')
415
+ throw new ApiError(409, 'execution_paused', 'The execution gate is closed.');
416
+ if (session.state !== 'running' || (kind === 'exit' ? session.role !== 'worker' || authority.phase !== 'work' :
417
+ kind === 'verdict' ? session.role !== 'verifier' || authority.phase !== 'verification' : authority.phase !== 'handoff'))
418
+ conflict('Session is not assigned to this submission phase.');
419
+ const plan = this.plan(run.id);
420
+ const step = plan.steps[plan.ordinal];
421
+ if (run.currentStepId !== session.stepExecutionId || step?.id !== session.stepExecutionId ||
422
+ (authority.phase === 'verification' || session.role === 'handoff' ? step.auxiliarySessionId : step.workerSessionId) !== session.id)
423
+ conflict('Session is no longer the current role assignment.');
424
+ if (run.pendingBlockIds.length || plan.pendingSubmissionId)
425
+ conflict();
426
+ if (expired(plan.clock, this.now()) || plan.stepClocks[session.stepExecutionId] && expired(plan.stepClocks[session.stepExecutionId], this.now()))
427
+ throw new ApiError(409, 'deadline_exceeded', 'The workflow or step allowance is exhausted.');
428
+ if (expired(authority.clock, this.now()) || session.limits.maxSubmissions !== undefined && session.submissionsUsed >= session.limits.maxSubmissions)
429
+ throw new ApiError(409, 'session_budget_exhausted', 'The session allowance is exhausted.');
430
+ }
431
+ failure(context) {
432
+ const initial = this.adapter(context), input = context.body;
433
+ const identity = commandIdentity(context, `/sessions/${initial.session.id}/failures`);
434
+ return this.store.command(identity, () => {
435
+ const { session, authority, run } = this.adapter(context);
436
+ const key = digest([session.id, session.epoch, input.clientFailureId]);
437
+ const prior = this.store.private('session_failure_id', key);
438
+ if (prior) {
439
+ if (prior.body !== canonical(input))
440
+ throw new ApiError(409, 'session_failure_conflict', 'Client failure identity was used with a different observation.');
441
+ return { status: 202, headers: {}, body: this.store.get('failures', prior.id) };
442
+ }
443
+ const plan = this.plan(run.id), chargeAllowed = !terminal(run) && !plan.cancelOperationId && run.currentStepId === session.stepExecutionId &&
444
+ !['completed', 'terminated', 'interrupted'].includes(session.state);
445
+ const outcome = chargeAllowed ? this.retries.failure(authority.retryEpisodeId, authority.logicalOperationId, {
446
+ category: session.role === 'verifier' && input.category === 'verification_execution' ? 'verification_execution' : 'infrastructure',
447
+ verifier: session.role === 'verifier', infrastructureRetries: run.policy.infrastructureRetries ?? 3, verificationRetries: run.policy.verificationRetries ?? 3
448
+ })
449
+ : { retry: false, chargeAttempt: false, category: 'infrastructure' };
450
+ if (outcome.chargeAttempt) {
451
+ this.store.put('sessions', { ...session, submissionsUsed: session.submissionsUsed + 1,
452
+ infrastructureAttemptCharges: session.infrastructureAttemptCharges + (outcome.category === 'infrastructure' ? 1 : 0) }, { runId: run.id, parentId: session.stepExecutionId });
453
+ if (session.role === 'verifier')
454
+ plan.steps[plan.ordinal].verificationCharges++;
455
+ if (session.role === 'handoff' && plan.reset)
456
+ plan.reset.handoffCharges = (plan.reset.handoffCharges ?? 0) + 1;
457
+ this.savePlan(run.id, plan);
458
+ }
459
+ const record = { id: randomUUID(), sessionId: session.id, category: input.category,
460
+ retryable: outcome.retry, engineAction: outcome.retry ? 'retry_pending' : outcome.chargeAttempt ? 'attempt_charged' : 'blocked',
461
+ recordedAt: new Date(this.now()).toISOString() };
462
+ this.store.put('failures', record, { runId: run.id, parentId: session.id, immutable: true });
463
+ this.store.setPrivate('session_failure_id', key, { id: record.id, body: canonical(input) });
464
+ this.wake(run.id);
465
+ return { status: 202, headers: {}, body: record };
466
+ });
467
+ }
468
+ handlers() {
469
+ return new Map([
470
+ ['createRun', context => this.createRun(context)], ['pauseRun', context => this.pause(context)], ['resumeRun', context => this.resume(context)],
471
+ ['cancelRun', context => this.cancel(context)], ['recoverRun', context => this.recover(context)], ['replaceRunProfile', context => this.replace(context)],
472
+ ['createBlockDecision', context => this.decide(context)], ['submitExit', context => this.submit(context, 'exit')],
473
+ ['submitVerificationVerdict', context => this.submit(context, 'verdict')], ['submitHandoff', context => this.submit(context, 'handoff')],
474
+ ['reportSessionFailure', context => this.failure(context)],
475
+ ]);
476
+ }
477
+ }
@@ -0,0 +1,11 @@
1
+ import { SqlAsyncEscapeError } from '../storage/coordinator.js';
2
+ export function runSqlCommitHook(hook, value) {
3
+ if (!hook)
4
+ return;
5
+ if (hook.constructor.name === 'AsyncFunction')
6
+ throw new Error('async_sql_commit_hook');
7
+ const result = hook(value);
8
+ if (result !== null && (typeof result === 'object' || typeof result === 'function') &&
9
+ typeof result.then === 'function')
10
+ throw new SqlAsyncEscapeError(result, 'async_sql_commit_hook');
11
+ }
@@ -0,0 +1,31 @@
1
+ import { digest } from '../broker/policy.js';
2
+ import { durationMs } from './timing.js';
3
+ /** Public identity, not a canonical digest field. Both work projections must
4
+ * identify the same private broker row without exposing its internal key. */
5
+ export const brokerWorkId = (id) => `work_${digest(id).slice('sha256:'.length)}`;
6
+ function continuation(run) {
7
+ if (run.executionControl.continuationState)
8
+ return run.executionControl.continuationState;
9
+ switch (run.state) {
10
+ case 'starting':
11
+ case 'running':
12
+ case 'verifying':
13
+ case 'generating_handoff':
14
+ case 'resetting':
15
+ case 'blocked':
16
+ case 'interrupted':
17
+ case 'recovering': return run.state;
18
+ default: throw new Error('approval_continuation_unavailable');
19
+ }
20
+ }
21
+ /** Establish the entire hold at its first durable admission, before the actor
22
+ * runs. Later projections preserve its original phase, origin and extensions. */
23
+ export function approvalWaitFor(run, pendingApprovalIds, work, now) {
24
+ if (!pendingApprovalIds.length)
25
+ return { status: 'none', pendingApprovalIds: [], inFlightWork: [] };
26
+ const prior = run.approvalWait.status === 'none' ? undefined : run.approvalWait;
27
+ const requestedAt = prior?.requestedAt ?? new Date(now).toISOString();
28
+ return { status: work.length ? 'draining' : 'waiting', pendingApprovalIds, inFlightWork: work,
29
+ continuationState: prior?.continuationState ?? continuation(run), requestedAt,
30
+ graceDeadlineAt: prior?.graceDeadlineAt ?? new Date(Date.parse(requestedAt) + durationMs(run.policy.pauseGracePeriod ?? '30s')).toISOString() };
31
+ }