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

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 +58 -253
  3. package/dist/src/acp.js +115 -0
  4. package/dist/src/contract.js +108 -0
  5. package/dist/src/engine.js +596 -0
  6. package/dist/src/main.js +72 -22
  7. package/dist/src/repository.js +94 -0
  8. package/dist/src/service.js +188 -0
  9. package/package.json +16 -32
  10. package/reference/openapi.json +834 -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
@@ -1,224 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- export class CoordinatorError extends Error {
3
- code;
4
- constructor(code) {
5
- super(code);
6
- this.code = code;
7
- }
8
- }
9
- /** An asynchronous continuation already exists, unlike a rejected async
10
- * function whose body was never called. SQL rollback cannot undo it. */
11
- export class SqlAsyncEscapeError extends CoordinatorError {
12
- constructor(value, code = 'async_transaction') {
13
- super(code);
14
- // Observe a rejected promise without calling foreign thenables inside SQL.
15
- queueMicrotask(() => { try {
16
- void Promise.resolve(value).catch(() => { });
17
- }
18
- catch { /* Already fail-stop. */ } });
19
- }
20
- }
21
- /** Single synchronous ordering boundary. Protected effects are never callbacks
22
- * of atomic(): record started intent, commit, assertOutsideTransaction, execute.
23
- * Only SQL-only lifecycle/lease mutations may join. Authority/resource
24
- * invalidation and approval decisions require their own root transaction. */
25
- export class SqliteCoordinator {
26
- db;
27
- #depth = 0;
28
- #after = [];
29
- #rollbackOnly = false;
30
- #quiescence;
31
- #fenced = false;
32
- #savepoints = 0;
33
- #savepointSequence = 0;
34
- constructor(db) {
35
- this.db = db;
36
- }
37
- setQuiescenceProbe(probe) {
38
- if (this.#quiescence)
39
- throw new CoordinatorError('quiescence_probe_already_installed');
40
- this.#quiescence = probe;
41
- }
42
- assertOutsideTransaction() {
43
- if (this.#fenced)
44
- throw new CoordinatorError('coordinator_fenced');
45
- if (this.#depth) {
46
- if (this.#savepoints) {
47
- this.#rollbackOnly = true;
48
- this.#fenced = true;
49
- }
50
- throw new CoordinatorError('effect_inside_transaction');
51
- }
52
- }
53
- assertQuiescent(runId) {
54
- if (this.#fenced)
55
- throw new CoordinatorError('coordinator_fenced');
56
- // No session/role exception: all actual model/tool/check/Git work must drain.
57
- // The workspace operation checks BEFORE admitting its own active intent.
58
- if (!this.#quiescence || !this.#quiescence(runId))
59
- throw new CoordinatorError('run_not_quiescent');
60
- }
61
- afterCommit(callback) {
62
- if (this.#fenced)
63
- throw new CoordinatorError('coordinator_fenced');
64
- if (this.#depth)
65
- this.#after.push(callback);
66
- else
67
- callback();
68
- }
69
- atomic(operation, options = {}) {
70
- if (this.#fenced)
71
- throw new CoordinatorError('coordinator_fenced');
72
- if (operation.constructor.name === 'AsyncFunction') {
73
- if (this.#depth)
74
- this.#rollbackOnly = true;
75
- throw new CoordinatorError('async_transaction');
76
- }
77
- const root = this.#depth === 0;
78
- if (root) {
79
- this.db.exec('BEGIN IMMEDIATE');
80
- this.#after = [];
81
- this.#rollbackOnly = false;
82
- this.#savepointSequence = 0;
83
- }
84
- this.#depth++;
85
- let result;
86
- try {
87
- result = operation();
88
- if (result !== null && (typeof result === 'object' || typeof result === 'function') &&
89
- typeof result.then === 'function') {
90
- throw new SqlAsyncEscapeError(result);
91
- }
92
- }
93
- catch (error) {
94
- if (error instanceof SqlAsyncEscapeError) {
95
- this.#fenced = true;
96
- this.#rollbackOnly = true;
97
- }
98
- const preserve = options.commitOnError?.(error) === true;
99
- if (!root) {
100
- this.#rollbackOnly = true;
101
- // A programming error must not roll back an invalidation and then let
102
- // the same coordinator redeem the revived authority.
103
- if (preserve)
104
- this.#fenced = true;
105
- }
106
- this.#depth--;
107
- if (root)
108
- this.#finish(preserve && !this.#rollbackOnly);
109
- throw error;
110
- }
111
- this.#depth--;
112
- if (root) {
113
- const aborted = this.#rollbackOnly;
114
- this.#finish(!aborted);
115
- if (aborted)
116
- throw new CoordinatorError('transaction_aborted');
117
- }
118
- return result;
119
- }
120
- /** Explicit recovery boundary for trusted SQL-only error receipt hooks.
121
- * This is NOT an effect sandbox or an independent transaction. */
122
- savepoint(operation) {
123
- if (this.#fenced)
124
- throw new CoordinatorError('coordinator_fenced');
125
- if (!this.#depth)
126
- throw new CoordinatorError('savepoint_requires_transaction');
127
- if (operation.constructor.name === 'AsyncFunction') {
128
- this.#rollbackOnly = true;
129
- throw new CoordinatorError('async_transaction');
130
- }
131
- const name = `coordinator_sp_${++this.#savepointSequence}`;
132
- const callbacks = this.#after.length;
133
- const rollbackOnly = this.#rollbackOnly;
134
- try {
135
- this.db.exec(`SAVEPOINT ${name}`);
136
- }
137
- catch {
138
- this.#fenced = true;
139
- this.#rollbackOnly = true;
140
- throw new CoordinatorError('savepoint_begin_failed');
141
- }
142
- this.#savepoints++;
143
- try {
144
- const result = operation();
145
- if (result !== null && (typeof result === 'object' || typeof result === 'function') &&
146
- typeof result.then === 'function') {
147
- // An unknown asynchronous continuation cannot be undone with SQL.
148
- throw new SqlAsyncEscapeError(result);
149
- }
150
- if (this.#fenced)
151
- throw new CoordinatorError('coordinator_fenced');
152
- if (this.#rollbackOnly && !rollbackOnly)
153
- throw new CoordinatorError('transaction_aborted');
154
- try {
155
- this.db.exec(`RELEASE SAVEPOINT ${name}`);
156
- }
157
- catch {
158
- this.#fenced = true;
159
- this.#rollbackOnly = true;
160
- throw new CoordinatorError('savepoint_release_failed');
161
- }
162
- return result;
163
- }
164
- catch (error) {
165
- if (error instanceof SqlAsyncEscapeError) {
166
- this.#fenced = true;
167
- this.#rollbackOnly = true;
168
- }
169
- this.#after.length = callbacks;
170
- try {
171
- this.db.exec(`ROLLBACK TO SAVEPOINT ${name}`);
172
- this.db.exec(`RELEASE SAVEPOINT ${name}`);
173
- }
174
- catch {
175
- this.#fenced = true;
176
- this.#rollbackOnly = true;
177
- // Never disguise an unproved rollback as an ordinary receipt replay.
178
- throw new CoordinatorError('savepoint_rollback_failed');
179
- }
180
- if (!this.#fenced)
181
- this.#rollbackOnly = rollbackOnly;
182
- else
183
- this.#rollbackOnly = true;
184
- throw error;
185
- }
186
- finally {
187
- this.#savepoints--;
188
- }
189
- }
190
- #finish(commit) {
191
- const callbacks = commit ? this.#after : [];
192
- this.#after = [];
193
- this.#rollbackOnly = false;
194
- try {
195
- this.db.exec(commit ? 'COMMIT' : 'ROLLBACK');
196
- }
197
- catch (error) {
198
- this.#fenced = true;
199
- throw error;
200
- }
201
- // Notification callbacks run only after the OUTERMOST durable commit.
202
- for (const callback of callbacks)
203
- callback();
204
- }
205
- migrate(migrations) {
206
- this.assertOutsideTransaction();
207
- this.atomic(() => {
208
- this.db.exec('CREATE TABLE IF NOT EXISTS schema_migrations (id TEXT PRIMARY KEY, digest TEXT NOT NULL)');
209
- for (const migration of migrations) {
210
- if (!/^[a-zA-Z0-9._-]+$/.test(migration.id))
211
- throw new CoordinatorError('invalid_migration_id');
212
- const digest = createHash('sha256').update(migration.sql).digest('hex');
213
- const existing = this.db.prepare('SELECT digest FROM schema_migrations WHERE id=?').get(migration.id);
214
- if (existing) {
215
- if (existing.digest !== digest)
216
- throw new CoordinatorError('migration_changed');
217
- continue;
218
- }
219
- this.db.exec(migration.sql);
220
- this.db.prepare('INSERT INTO schema_migrations VALUES (?,?)').run(migration.id, digest);
221
- }
222
- });
223
- }
224
- }
@@ -1,71 +0,0 @@
1
- import { spawnSync } from 'node:child_process';
2
- import { closeSync, constants, fstatSync, lstatSync, openSync, realpathSync } from 'node:fs';
3
- import { isAbsolute, join } from 'node:path';
4
- export class StartupLockError extends Error {
5
- code;
6
- constructor(code) {
7
- super(code);
8
- this.code = code;
9
- }
10
- }
11
- /** The same open description must outlive every effectful descendant.
12
- * Never issue LOCK_UN, even during graceful shutdown. */
13
- export class StartupLock {
14
- directory;
15
- fd;
16
- directoryFd;
17
- #closed = false;
18
- constructor(directory, fd, directoryFd) {
19
- this.directory = directory;
20
- this.fd = fd;
21
- this.directoryFd = directoryFd;
22
- }
23
- close() {
24
- if (this.#closed)
25
- return;
26
- this.#closed = true;
27
- try {
28
- closeSync(this.fd);
29
- }
30
- finally {
31
- closeSync(this.directoryFd);
32
- }
33
- }
34
- }
35
- /** Acquire BEFORE opening SQLite, recovery, reconciliation or agent launch.
36
- * Fixed trusted helper, empty private file, no model input or ambient shell. */
37
- export function acquireStartupLock(directory, helperPath) {
38
- if (!isAbsolute(directory) || !isAbsolute(helperPath))
39
- throw new StartupLockError('invalid_startup_lock_path');
40
- const physical = realpathSync(directory);
41
- const directoryFd = openSync(physical, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
42
- let fd;
43
- try {
44
- const root = fstatSync(directoryFd);
45
- if (!root.isDirectory() || root.uid !== process.geteuid?.() || root.mode & 0o77)
46
- throw new StartupLockError('unsafe_state_directory');
47
- const helper = lstatSync(helperPath);
48
- if (!helper.isFile() || helper.isSymbolicLink() || helper.uid !== process.geteuid?.() || helper.nlink !== 1 ||
49
- helper.mode & 0o6022)
50
- throw new StartupLockError('untrusted_startup_lock_helper');
51
- fd = openSync(join(physical, 'startup.lock'), constants.O_RDWR | constants.O_CREAT | constants.O_NOFOLLOW, 0o600);
52
- const lock = fstatSync(fd);
53
- if (!lock.isFile() || lock.uid !== process.geteuid?.() || lock.nlink !== 1 || lock.mode & 0o77 || lock.size !== 0)
54
- throw new StartupLockError('unsafe_startup_lock_file');
55
- const result = spawnSync(helperPath, ['startup-lock'], {
56
- stdio: ['ignore', 'pipe', 'pipe', fd], encoding: 'utf8', timeout: 5000,
57
- env: { PATH: '/usr/bin:/bin', LC_ALL: 'C' }, maxBuffer: 4096,
58
- });
59
- if (result.status === 75)
60
- throw new StartupLockError('startup_lock_busy');
61
- if (result.error || result.status !== 0 || result.stdout !== 'locked\n')
62
- throw new StartupLockError('startup_lock_failed');
63
- return new StartupLock(physical, fd, directoryFd);
64
- }
65
- catch (error) {
66
- if (fd !== undefined)
67
- closeSync(fd);
68
- closeSync(directoryFd);
69
- throw error;
70
- }
71
- }
@@ -1,167 +0,0 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { canonical, digest } from '../broker/policy.js';
3
- import { ApiError } from '../server/errors.js';
4
- export class HttpReceiptReplay extends Error {
5
- receipt;
6
- constructor(receipt) {
7
- super('http_receipt_replay');
8
- this.receipt = receipt;
9
- }
10
- }
11
- export const ENGINE_MIGRATION = {
12
- id: 'engine.foundation.v1',
13
- sql: `
14
- CREATE TABLE engine_resources (
15
- seq INTEGER PRIMARY KEY AUTOINCREMENT, kind TEXT NOT NULL, id TEXT NOT NULL,
16
- run_id TEXT, parent_id TEXT, revision INTEGER NOT NULL, body TEXT NOT NULL,
17
- UNIQUE(kind,id));
18
- CREATE INDEX engine_resource_collection ON engine_resources(kind,run_id,parent_id,seq);
19
- CREATE TABLE engine_private (scope TEXT NOT NULL, id TEXT NOT NULL, body TEXT NOT NULL, PRIMARY KEY(scope,id));
20
- CREATE TABLE engine_http_receipts (scope TEXT NOT NULL, key TEXT NOT NULL, digest TEXT NOT NULL, body TEXT NOT NULL, PRIMARY KEY(scope,key));
21
- CREATE TABLE engine_sequences (run_id TEXT PRIMARY KEY, value INTEGER NOT NULL);
22
- CREATE TABLE engine_tokens (
23
- digest TEXT PRIMARY KEY, principal_id TEXT NOT NULL, audience TEXT NOT NULL,
24
- session_id TEXT, epoch INTEGER, role TEXT, workspace_scope TEXT NOT NULL, revoked INTEGER NOT NULL DEFAULT 0);
25
- CREATE TABLE engine_cursors (
26
- id TEXT PRIMARY KEY, collection TEXT NOT NULL, principal_id TEXT NOT NULL,
27
- last_seq INTEGER NOT NULL, expires_at INTEGER NOT NULL);
28
- `,
29
- };
30
- /** Public DTOs and private orchestration records are separate by construction.
31
- * Never put broker audit rows, FDs, tokens or resolved credentials in this map. */
32
- export class EngineStore {
33
- coordinator;
34
- #eventWaiters = new Map();
35
- #waiterCount = 0;
36
- constructor(coordinator) {
37
- this.coordinator = coordinator;
38
- }
39
- get(kind, id) {
40
- const row = this.coordinator.db.prepare('SELECT body,revision,seq FROM engine_resources WHERE kind=? AND id=?').get(kind, id);
41
- if (!row)
42
- throw new ApiError(404, 'not_found', 'Resource not found.');
43
- return JSON.parse(row.body);
44
- }
45
- find(kind, id) {
46
- try {
47
- return this.get(kind, id);
48
- }
49
- catch (error) {
50
- if (error instanceof ApiError && error.status === 404)
51
- return undefined;
52
- throw error;
53
- }
54
- }
55
- etag(kind, id) {
56
- const row = this.coordinator.db.prepare('SELECT revision FROM engine_resources WHERE kind=? AND id=?').get(kind, id);
57
- if (!row)
58
- throw new ApiError(404, 'not_found', 'Resource not found.');
59
- return `"${kind}:${id}:${row.revision}"`;
60
- }
61
- expectMatch(kind, id, supplied) {
62
- if (!supplied)
63
- throw new ApiError(428, 'precondition_required', 'If-Match is required.');
64
- if (supplied !== this.etag(kind, id))
65
- throw new ApiError(412, 'precondition_failed', 'The resource revision is stale.');
66
- }
67
- put(kind, value, options = {}) {
68
- this.coordinator.atomic(() => {
69
- const prior = this.coordinator.db.prepare('SELECT body FROM engine_resources WHERE kind=? AND id=?').get(kind, value.id);
70
- const body = canonical(value);
71
- if (prior && options.immutable) {
72
- if (prior.body !== body)
73
- throw new ApiError(409, 'immutable_resource', 'Immutable resource content cannot change.');
74
- return;
75
- }
76
- this.coordinator.db.prepare(`INSERT INTO engine_resources(kind,id,run_id,parent_id,revision,body) VALUES (?,?,?,?,1,?)
77
- ON CONFLICT(kind,id) DO UPDATE SET body=excluded.body, revision=revision+1`).run(kind, value.id, options.runId ?? null, options.parentId ?? null, body);
78
- });
79
- }
80
- list(kind, filter = {}) {
81
- return this.coordinator.db.prepare(`SELECT body,seq,revision FROM engine_resources WHERE kind=?
82
- AND (? IS NULL OR run_id=?) AND (? IS NULL OR parent_id=?) AND seq>? AND seq<=? ORDER BY seq LIMIT ?`).all(kind, filter.runId ?? null, filter.runId ?? null, filter.parentId ?? null, filter.parentId ?? null, filter.after ?? 0, filter.through ?? Number.MAX_SAFE_INTEGER, filter.limit ?? 201).map(row => ({ value: JSON.parse(row.body), seq: row.seq }));
83
- }
84
- watchEvents(runId, timeoutMs, signal) {
85
- this.coordinator.assertOutsideTransaction();
86
- if (!Number.isInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > 30_000)
87
- throw new ApiError(400, 'invalid_wait', 'Event wait must be from 0 through 30000 milliseconds.');
88
- if (this.#waiterCount >= 1024)
89
- throw new ApiError(503, 'event_wait_overloaded', 'The event wait capacity is exhausted.', true);
90
- let close;
91
- const done = new Promise(resolve => {
92
- const set = this.#eventWaiters.get(runId) ?? new Set();
93
- this.#eventWaiters.set(runId, set);
94
- this.#waiterCount++;
95
- const timer = setTimeout(() => close(), timeoutMs);
96
- let closed = false;
97
- close = () => {
98
- if (closed)
99
- return;
100
- closed = true;
101
- clearTimeout(timer);
102
- signal.removeEventListener('abort', close);
103
- set.delete(close);
104
- this.#waiterCount--;
105
- if (!set.size)
106
- this.#eventWaiters.delete(runId);
107
- resolve();
108
- };
109
- set.add(close);
110
- if (signal.aborted)
111
- close();
112
- else
113
- signal.addEventListener('abort', close, { once: true });
114
- });
115
- return { done, close };
116
- }
117
- private(scope, id) {
118
- const row = this.coordinator.db.prepare('SELECT body FROM engine_private WHERE scope=? AND id=?').get(scope, id);
119
- return row ? JSON.parse(row.body) : undefined;
120
- }
121
- setPrivate(scope, id, value) {
122
- this.coordinator.atomic(() => {
123
- this.coordinator.db.prepare('INSERT INTO engine_private VALUES (?,?,?) ON CONFLICT(scope,id) DO UPDATE SET body=excluded.body').run(scope, id, canonical(value));
124
- });
125
- }
126
- receipt(identity) {
127
- if (!identity.key || identity.key.length > 200)
128
- throw new ApiError(400, 'invalid_idempotency_key', 'Idempotency-Key must contain 1 to 200 characters.');
129
- const scope = canonical([identity.principal, identity.method.toUpperCase(), identity.path]);
130
- const row = this.coordinator.db.prepare('SELECT digest,body FROM engine_http_receipts WHERE scope=? AND key=?').get(scope, identity.key);
131
- if (!row)
132
- return undefined;
133
- if (row.digest !== digest(identity.body))
134
- throw new ApiError(409, 'idempotency_conflict', 'Idempotency key was used with a different body.');
135
- return JSON.parse(row.body);
136
- }
137
- saveReceipt(identity, receipt) {
138
- this.coordinator.atomic(() => {
139
- const existing = this.receipt(identity);
140
- if (existing)
141
- throw new HttpReceiptReplay(existing);
142
- const scope = canonical([identity.principal, identity.method.toUpperCase(), identity.path]);
143
- this.coordinator.db.prepare('INSERT INTO engine_http_receipts VALUES (?,?,?,?)').run(scope, identity.key, digest(identity.body), canonical(receipt));
144
- });
145
- }
146
- command(identity, apply) {
147
- return this.coordinator.atomic(() => {
148
- const existing = this.receipt(identity);
149
- if (existing)
150
- return { receipt: existing, replay: true };
151
- const receipt = apply();
152
- this.saveReceipt(identity, receipt);
153
- return { receipt, replay: false };
154
- });
155
- }
156
- event(runId, type, resourceType, resourceId, data, now = Date.now()) {
157
- return this.coordinator.atomic(() => {
158
- this.coordinator.db.prepare('INSERT INTO engine_sequences VALUES (?,1) ON CONFLICT(run_id) DO UPDATE SET value=value+1').run(runId);
159
- const sequence = this.coordinator.db.prepare('SELECT value FROM engine_sequences WHERE run_id=?').get(runId).value;
160
- const event = { id: randomUUID(), runId, sequence, occurredAt: new Date(now).toISOString(), type, resourceType, resourceId, data };
161
- this.put('events', event, { runId, immutable: true });
162
- this.coordinator.afterCommit(() => { for (const close of [...this.#eventWaiters.get(runId) ?? []])
163
- close(); });
164
- return event;
165
- });
166
- }
167
- }
@@ -1,81 +0,0 @@
1
- import { parentPort, workerData } from "node:worker_threads";
2
- import { Ajv2020 } from "ajv/dist/2020.js";
3
- import { createRequire } from "node:module";
4
- const addFormats = createRequire(import.meta.url)("ajv-formats");
5
- /** Ordinary Draft 2020 artifact policy matches the source schema graph: ignore
6
- * $async only at schema locations, never within const/default/example data or
7
- * a property's literal name. This mutates only the worker's private clone. */
8
- function ordinaryArtifactSchema(input) {
9
- const object = (value) => !!value && typeof value === "object" && !Array.isArray(value);
10
- const visit = (node) => {
11
- if (!object(node))
12
- return;
13
- delete node.$async;
14
- for (const key of ["additionalProperties", "unevaluatedProperties", "propertyNames", "contains", "items", "unevaluatedItems", "if", "then", "else", "not", "contentSchema"])
15
- visit(node[key]);
16
- for (const key of ["allOf", "anyOf", "oneOf", "prefixItems"])
17
- if (Array.isArray(node[key]))
18
- for (const child of node[key])
19
- visit(child);
20
- for (const key of ["properties", "patternProperties", "dependentSchemas", "dependencies", "$defs", "definitions"])
21
- if (object(node[key]))
22
- for (const child of Object.values(node[key]))
23
- visit(child);
24
- };
25
- visit(input);
26
- return input;
27
- }
28
- // Fixed trusted pure implementation. No model code, module path, eval/command
29
- // arguments, environment credentials, filesystem, network or subprocess API.
30
- const input = workerData;
31
- try {
32
- let pass = false;
33
- if (input.predicate.kind === "text_includes") {
34
- parentPort.postMessage({ event: "started" });
35
- pass = input.artifact.content.includes(input.predicate.needle);
36
- }
37
- else if (input.predicate.kind === "json_pointer_equals") {
38
- let value = input.artifact.decoded, found = true;
39
- const parts = input.predicate.pointer === "" ? [] : input.predicate.pointer.slice(1).split("/").map(part => part.replaceAll("~1", "/").replaceAll("~0", "~"));
40
- for (const part of parts) {
41
- if (!value || typeof value !== "object" || (Array.isArray(value) && !/^(?:0|[1-9][0-9]*)$/.test(part)) ||
42
- !Object.hasOwn(value, part)) {
43
- found = false;
44
- break;
45
- }
46
- value = value[part];
47
- }
48
- const equal = (a, b) => {
49
- if (Object.is(a, b))
50
- return true;
51
- if (!a || !b || typeof a !== "object" || typeof b !== "object" || Array.isArray(a) !== Array.isArray(b))
52
- return false;
53
- const keys = Object.keys(a).sort(), other = Object.keys(b).sort();
54
- return keys.length === other.length && keys.every((key, i) => key === other[i] &&
55
- equal(a[key], b[key]));
56
- };
57
- parentPort.postMessage({ event: "started" });
58
- pass = found && equal(value, input.predicate.expected);
59
- }
60
- else if (input.predicate.kind === "json_schema") {
61
- const ajv = new Ajv2020({ strict: false, allErrors: false, coerceTypes: false, useDefaults: false,
62
- removeAdditional: false });
63
- addFormats(ajv);
64
- const validate = ajv.compile(ordinaryArtifactSchema(input.predicate.schema));
65
- parentPort.postMessage({ event: "started" });
66
- const result = validate(input.artifact.decoded);
67
- if (typeof result !== "boolean")
68
- throw new Error("async_check_schema");
69
- pass = result;
70
- }
71
- else
72
- throw new Error("unknown_predicate");
73
- parentPort.postMessage({ status: pass ? "pass" : "fail", explanation: pass ? "Registered artifact predicate passed." : "Registered artifact predicate failed." });
74
- }
75
- catch {
76
- parentPort.postMessage({ status: "infrastructure_error", code: "check_worker_invalid_configuration", retryable: false,
77
- explanation: "Registered pure check could not evaluate its deployment configuration." });
78
- }
79
- finally {
80
- parentPort.close();
81
- }
@@ -1,106 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import { canonical, jsonCopy } from "../broker/policy.js";
3
- export class CheckRegistryError extends Error {
4
- code;
5
- constructor(code) {
6
- super(code);
7
- this.code = code;
8
- }
9
- }
10
- /** Deployment code registrations only. No workflow/model shell, expression,
11
- * inline function, module path, command or unknown check is executed. */
12
- export class TrustedCheckRegistry {
13
- options;
14
- checks = new Map();
15
- running = new Map();
16
- constructor(options) {
17
- this.options = options;
18
- for (const check of options.checks) {
19
- if (!check.id || !check.description || !check.version || typeof check.execute !== "function" || this.checks.has(check.id)) {
20
- throw new CheckRegistryError("invalid_check_registration");
21
- }
22
- if (check.parametersSchema !== undefined)
23
- canonical(check.parametersSchema);
24
- this.checks.set(check.id, Object.freeze({ id: check.id, description: check.description, version: check.version,
25
- ...(check.parametersSchema === undefined ? {} : { parametersSchema: jsonCopy(check.parametersSchema) }),
26
- execute: (request, signal) => this.execute(check, request, signal) }));
27
- }
28
- }
29
- list() {
30
- return [...this.checks.values()].map(check => ({ name: check.id, description: check.description, version: check.version,
31
- ...(check.parametersSchema === undefined ? {} : { parametersSchema: jsonCopy(check.parametersSchema) }) }));
32
- }
33
- get(id) { return this.checks.get(id); }
34
- preflight(ids) {
35
- if (new Set(ids).size !== ids.length || ids.some(id => !this.checks.has(id)))
36
- throw new CheckRegistryError("unknown_named_check");
37
- }
38
- /** A timed-out implementation which ignores AbortSignal stays active until
39
- * it actually settles. The engine's GLOBAL quiescence probe must include this. */
40
- activeWork(runId) { return [...this.running].filter(([, run]) => run === runId).map(([id]) => id); }
41
- async execute(check, request, signal) {
42
- this.options.coordinator.assertOutsideTransaction();
43
- const now = this.options.now ?? Date.now;
44
- if (!request.runId || !request.stepExecutionId || !request.leaseId || !request.workspaceRevisionId || !request.artifactId ||
45
- !Number.isFinite(request.deadlineAt) || request.deadlineAt <= now() || signal.aborted) {
46
- return { status: "infrastructure_error", code: "check_deadline_or_scope", retryable: false, explanation: "Check cannot start in this scope or after its deadline." };
47
- }
48
- const validation = this.options.validateRequest?.(request);
49
- if (validation && typeof validation === "object" && "then" in validation)
50
- throw new CheckRegistryError("async_check_scope_validation");
51
- const controller = new AbortController(), combined = AbortSignal.any([signal, controller.signal]);
52
- const id = randomUUID();
53
- this.running.set(id, request.runId);
54
- let timer;
55
- const actual = Promise.resolve().then(() => {
56
- if (combined.aborted || request.deadlineAt <= now())
57
- throw new CheckRegistryError("check_aborted");
58
- return check.execute(jsonCopy(request), combined);
59
- }).then(result => this.result(result)).catch(() => ({ status: "infrastructure_error", code: "check_execution_error",
60
- retryable: true, explanation: "Registered check did not complete successfully." }))
61
- .finally(() => { this.running.delete(id); if (timer)
62
- clearTimeout(timer); });
63
- const timeout = new Promise(resolve => {
64
- let finished = false;
65
- const finish = () => {
66
- if (finished)
67
- return;
68
- finished = true;
69
- if (timer)
70
- clearTimeout(timer);
71
- controller.abort();
72
- resolve({ status: "infrastructure_error", code: "check_aborted_or_timed_out",
73
- retryable: true, explanation: "Registered check exceeded its deadline or was cancelled." });
74
- };
75
- const arm = () => {
76
- if (finished)
77
- return;
78
- const remaining = request.deadlineAt - now();
79
- if (remaining <= 0)
80
- finish();
81
- else
82
- timer = setTimeout(arm, Math.min(2_147_483_647, Math.ceil(remaining)));
83
- };
84
- combined.addEventListener("abort", finish, { once: true });
85
- arm();
86
- void actual.finally(() => combined.removeEventListener("abort", finish));
87
- });
88
- return Promise.race([actual, timeout]);
89
- }
90
- result(result) {
91
- if (!result || !["pass", "fail", "infrastructure_error"].includes(result.status) ||
92
- typeof result.explanation !== "string" || !result.explanation || result.explanation.length > 16384) {
93
- return { status: "infrastructure_error", code: "invalid_check_result", retryable: false, explanation: "Registered check returned an invalid result." };
94
- }
95
- if (result.status === "infrastructure_error") {
96
- if (!/^[a-z0-9_]{1,80}$/.test(result.code) || typeof result.retryable !== "boolean")
97
- throw new CheckRegistryError("invalid_check_result");
98
- return { status: result.status, code: result.code, retryable: result.retryable, explanation: result.explanation };
99
- }
100
- if (result.evidenceArtifactIds !== undefined && (result.evidenceArtifactIds.length > 32 ||
101
- result.evidenceArtifactIds.some(id => typeof id !== "string" || !id || id.length > 200)))
102
- throw new CheckRegistryError("invalid_check_result");
103
- return { status: result.status, explanation: result.explanation,
104
- ...(result.evidenceArtifactIds === undefined ? {} : { evidenceArtifactIds: [...result.evidenceArtifactIds] }) };
105
- }
106
- }