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
@@ -1,22 +0,0 @@
1
- export class ApiError extends Error {
2
- status;
3
- code;
4
- retryable;
5
- issues;
6
- constructor(status, code, message, retryable = false, issues) {
7
- super(message);
8
- this.status = status;
9
- this.code = code;
10
- this.retryable = retryable;
11
- this.issues = issues;
12
- }
13
- }
14
- export function problem(error, requestId) {
15
- return { type: 'about:blank', title: error.code.replaceAll('_', ' '), status: error.status,
16
- code: error.code, detail: error.message, retryable: error.retryable, requestId,
17
- ...(error.issues ? { errors: error.issues } : {}) };
18
- }
19
- export function required(condition, status, code, detail) {
20
- if (!condition)
21
- throw new ApiError(status, code, detail);
22
- }
@@ -1,113 +0,0 @@
1
- import { EngineStore } from '../storage/store.js';
2
- import { AuthService } from './auth.js';
3
- import { Paging } from './paging.js';
4
- import { ApiError } from './errors.js';
5
- export function historyHandlers(store, auth, paging) {
6
- const handlers = new Map();
7
- const run = (context, id) => {
8
- const value = store.get('runs', id);
9
- auth.assertWorkspace(context.principal, value.workspaceId);
10
- return value;
11
- };
12
- const access = (context, runId) => {
13
- if (context.principal.audience !== 'adapter')
14
- throw new ApiError(403, 'forbidden', 'Session authentication is required.');
15
- const value = store.private('session_access', context.principal.sessionId);
16
- if (!value || (runId !== undefined && value.runId !== runId))
17
- throw new ApiError(403, 'assignment_forbidden', 'Resource is not in the current assignment.');
18
- run(context, value.runId);
19
- return value;
20
- };
21
- handlers.set('listRuns', context => ({ status: 200, headers: {}, body: paging.page('runs', context.principal, context.query, (after, limit) => {
22
- // Scope in SQL before pagination. A forbidden row cannot truncate a page.
23
- const scope = JSON.stringify(context.principal.workspaceIds);
24
- return store.coordinator.db.prepare(`SELECT body,seq FROM engine_resources WHERE kind='runs' AND seq>?
25
- AND (EXISTS(SELECT 1 FROM json_each(?) WHERE value='*') OR json_extract(body,'$.workspaceId') IN (SELECT value FROM json_each(?)))
26
- ORDER BY seq LIMIT ?`).all(after, scope, scope, limit)
27
- .map(row => ({ value: JSON.parse(row.body), seq: row.seq }));
28
- }) }));
29
- const collections = [
30
- ['listRunStepExecutions', 'steps'], ['listRunSessions', 'sessions'], ['listRunSubmissions', 'submissions'],
31
- ['listRunArtifacts', 'artifacts'], ['listRunBlocks', 'blocks'], ['listRunBaselines', 'baselines'],
32
- ['listRunInstructionSnapshots', 'snapshots'],
33
- ];
34
- for (const [operation, kind] of collections)
35
- handlers.set(operation, context => {
36
- const runId = context.params.runId;
37
- run(context, runId);
38
- return { status: 200, headers: {}, body: paging.page(`${kind}:${runId}`, context.principal, context.query, (after, limit) => store.list(kind, { runId, after, limit })) };
39
- });
40
- const singles = [
41
- ['getRun', 'runs', 'runId'], ['getSubmission', 'submissions', 'submissionId'],
42
- ['getArtifact', 'artifacts', 'artifactId'], ['getBlock', 'blocks', 'blockId'],
43
- ['getOperation', 'operations', 'operationId'], ['getInstructionSnapshot', 'snapshots', 'snapshotId'],
44
- ];
45
- for (const [operation, kind, parameter] of singles)
46
- handlers.set(operation, context => {
47
- const id = context.params[parameter], body = store.get(kind, id);
48
- const runId = kind === 'runs' ? id : body.runId;
49
- run(context, runId);
50
- if (context.principal.audience === 'adapter' && (kind !== 'artifacts' || !access(context, runId).inputArtifactIds.includes(id)))
51
- throw new ApiError(403, 'assignment_forbidden', 'Artifact is not in the current assignment.');
52
- return { status: 200, headers: { ETag: store.etag(kind, id) }, body };
53
- });
54
- handlers.set('getSessionAssignment', context => {
55
- if (context.principal.audience !== 'adapter' || context.principal.sessionId !== context.params.sessionId)
56
- throw new ApiError(403, 'assignment_forbidden', 'Session assignment is not authorized.');
57
- access(context);
58
- const body = store.private('assignments', context.principal.sessionId);
59
- if (!body)
60
- throw new ApiError(409, 'assignment_unavailable', 'Session assignment is unavailable.');
61
- const session = store.get('sessions', context.principal.sessionId);
62
- const current = run(context, session.runId);
63
- const closed = current.executionControl.status === 'paused' ||
64
- ['succeeded', 'failed', 'cancelled', 'interrupted'].includes(current.state) ||
65
- ['paused', 'paused_for_verification', 'completed', 'exhausted', 'interrupted', 'terminated'].includes(session.state);
66
- const executionGate = closed ? 'closed' :
67
- current.executionControl.status !== 'running' || current.approvalWait.status === 'draining' ? 'draining' :
68
- current.approvalWait.status === 'waiting' || current.pendingBlockIds.length ? 'closed' : 'open';
69
- return { status: 200, headers: { ETag: store.etag('sessions', context.principal.sessionId) },
70
- body: { ...body, session, executionGate } };
71
- });
72
- handlers.set('listRunToolHistory', context => {
73
- const runId = context.params.runId;
74
- run(context, runId);
75
- const window = context.principal.audience === 'adapter' ? access(context, runId) : undefined;
76
- return { status: 200, headers: {}, body: paging.page(`tool_history:${runId}:${window?.historyAfterSeq ?? 0}:${window?.historyThroughSeq ?? '*'}`, context.principal, context.query, (after, limit) => store.list('tool_history', { runId, limit,
77
- after: Math.max(after, window?.historyAfterSeq ?? 0), ...(window ? { through: window.historyThroughSeq } : {}) })) };
78
- });
79
- handlers.set('listRunEvents', async (context) => {
80
- const runId = context.params.runId;
81
- run(context, runId);
82
- const text = context.query.waitSeconds;
83
- const waitSeconds = text === undefined ? 0 : /^(?:[0-9]|[12][0-9]|30)$/.test(text) ? Number(text) : NaN;
84
- if (!Number.isInteger(waitSeconds))
85
- throw new ApiError(400, 'invalid_wait', 'waitSeconds must be an integer from 0 through 30.');
86
- const follow = context.query.follow;
87
- if (follow !== undefined && follow !== 'true' && follow !== 'false')
88
- throw new ApiError(400, 'invalid_follow', 'follow must be true or false.');
89
- // During a long poll only issue a cursor when there are events to return or the wait has ended.
90
- const continuation = follow === 'true' && (waitSeconds ? 'nonempty' : true);
91
- const page = (atTimeout = false) => paging.page(`events:${runId}`, context.principal, context.query, (after, limit) => store.list('events', { runId, after, limit }), { continuation: atTimeout || continuation });
92
- let body = page();
93
- if (body.items.length || !waitSeconds)
94
- return { status: 200, headers: {}, body };
95
- const watch = store.watchEvents(runId, waitSeconds * 1000, context.signal);
96
- try {
97
- body = page(); // Register BEFORE recheck to close the read/wait race.
98
- if (!body.items.length) {
99
- await watch.done;
100
- if (context.signal.aborted)
101
- throw new ApiError(409, 'request_cancelled', 'Event wait was cancelled.');
102
- body = page();
103
- if (!body.items.length)
104
- body = page(true);
105
- }
106
- return { status: 200, headers: {}, body };
107
- }
108
- finally {
109
- watch.close();
110
- }
111
- });
112
- return handlers;
113
- }
@@ -1,124 +0,0 @@
1
- import Fastify from 'fastify';
2
- import contract from './api-contract.json' with { type: 'json' };
3
- import { AuthService } from './auth.js';
4
- import { ApiError, problem } from './errors.js';
5
- import { ValidationPool } from '../config/validation-pool.js';
6
- import { HttpReceiptReplay } from '../storage/store.js';
7
- import { BrokerError } from '../broker/types.js';
8
- import { WorkspaceError } from '../workspaces/git.js';
9
- export function createHttpServer(options) {
10
- const app = Fastify({ logger: false, exposeHeadRoutes: false, bodyLimit: options.bodyLimit ?? 1_048_576,
11
- requestTimeout: 30_000, routerOptions: { maxParamLength: contract.components.schemas.Id.maxLength },
12
- frameworkErrors(error, request, reply) {
13
- const publicError = error.code === 'FST_ERR_MAX_PARAM_LENGTH' ?
14
- new ApiError(414, 'uri_too_long', 'Resource identifier exceeds the configured size limit.') :
15
- error.code === 'FST_ERR_BAD_URL' ? new ApiError(400, 'invalid_request', 'Request URL encoding is invalid.') :
16
- new ApiError(500, 'internal_error', 'The request could not be completed.');
17
- void reply.code(publicError.status).type('application/problem+json').send(problem(publicError, request.id));
18
- } });
19
- const principals = new WeakMap();
20
- const controllers = new WeakMap();
21
- app.removeContentTypeParser('application/json');
22
- app.addContentTypeParser('application/json', { parseAs: 'buffer' }, (request, buffer, done) => {
23
- const controller = controllers.get(request);
24
- if (!controller) {
25
- done(new ApiError(404, 'not_found', 'Resource not found.'));
26
- return;
27
- }
28
- let content;
29
- try {
30
- content = new TextDecoder('utf-8', { fatal: true }).decode(buffer);
31
- }
32
- catch {
33
- done(new ApiError(400, 'invalid_json', 'Request JSON must be valid UTF-8.'));
34
- return;
35
- }
36
- const signal = controller.signal;
37
- void options.validation.run({ kind: 'decode', content, format: 'json' }, { signal }).then(result => {
38
- if (!result.valid)
39
- done(new ApiError(400, 'invalid_json', 'Request must contain valid JSON with unique string keys.'));
40
- else
41
- done(null, result.value);
42
- }, error => done(error));
43
- });
44
- app.setErrorHandler((error, request, reply) => {
45
- const framework = error && typeof error === 'object' ? error : {};
46
- const publicError = error instanceof ApiError ? error :
47
- (error instanceof BrokerError || error instanceof WorkspaceError) ? new ApiError(error.status, /^[a-z][a-z0-9_]{0,79}$/.test(error.code) ? error.code : 'service_error', error instanceof WorkspaceError && error.detail ? error.detail : 'The requested state transition is not permitted.') :
48
- framework.code === 'FST_ERR_CTP_BODY_TOO_LARGE' ? new ApiError(413, 'payload_too_large', 'Request body exceeds the configured size limit.') :
49
- framework.statusCode === 400 || framework.statusCode === 415 ? new ApiError(framework.statusCode, 'invalid_request', 'Request encoding or structure is invalid.') :
50
- new ApiError(500, 'internal_error', 'The request could not be completed.');
51
- void reply.code(publicError.status).type('application/problem+json').send(problem(publicError, request.id));
52
- });
53
- app.setNotFoundHandler((request, reply) => reply.code(404).type('application/problem+json')
54
- .send(problem(new ApiError(404, 'not_found', 'Resource not found.'), request.id)));
55
- const paths = contract.paths;
56
- for (const [path, methods] of Object.entries(paths))
57
- for (const [method, operation] of Object.entries(methods)) {
58
- const handler = options.handlers.get(operation.operationId);
59
- if (!handler) {
60
- if (options.requireComplete !== false)
61
- throw new Error(`Missing authored API operation: ${operation.operationId}`);
62
- continue;
63
- }
64
- app.route({
65
- method: method.toUpperCase(),
66
- url: `/api/v1${path.replaceAll(/\{([^}]+)\}/g, ':$1')}`,
67
- onRequest: async (request, reply) => {
68
- const controller = new AbortController();
69
- controllers.set(request, controller);
70
- request.raw.once('aborted', () => controller.abort());
71
- reply.raw.once('close', () => { if (!reply.raw.writableFinished)
72
- controller.abort(); });
73
- const authorization = request.headers.authorization;
74
- const epoch = request.headers['x-session-epoch'];
75
- principals.set(request, options.auth.authenticate(authorization, typeof epoch === 'string' ? epoch : undefined, operation['x-audience']));
76
- },
77
- handler: async (request, reply) => {
78
- const principal = principals.get(request);
79
- const params = request.params;
80
- for (const value of Object.values(params)) {
81
- if (!/^[A-Za-z0-9_-]{1,128}$/.test(value))
82
- throw new ApiError(400, 'invalid_identifier', 'Resource identifier is invalid.');
83
- }
84
- if (method === 'post' && (typeof request.headers['idempotency-key'] !== 'string' || !request.headers['idempotency-key'] ||
85
- request.headers['idempotency-key'].length > 200))
86
- throw new ApiError(400, 'invalid_idempotency_key', 'Idempotency-Key must contain 1 to 200 characters.');
87
- const schema = operation.requestBody?.content['application/json']?.schema.$ref.split('/').at(-1);
88
- if (schema) {
89
- const validation = await options.validation.run({ kind: 'wire', schema, value: request.body }, { signal: controllers.get(request).signal });
90
- if (!validation.valid)
91
- throw new ApiError(400, 'invalid_request', 'Request does not match its authored envelope.', false, validation.errors);
92
- }
93
- let result;
94
- try {
95
- result = await handler({ requestId: request.id, signal: controllers.get(request).signal, principal, params, query: request.query, body: request.body,
96
- header(name) { const value = request.headers[name.toLowerCase()]; return typeof value === 'string' ? value : undefined; } });
97
- }
98
- catch (error) {
99
- if (!(error instanceof HttpReceiptReplay))
100
- throw error;
101
- result = { receipt: error.receipt, replay: true };
102
- }
103
- const receipt = 'receipt' in result ? result.receipt : result;
104
- const mediaType = receipt.status >= 400 ? 'application/problem+json' : 'application/json';
105
- // The authored Problem contract applies to common error responses even
106
- // where a path lists only its success response. Stored committed-error
107
- // receipts must take this SAME validation/replay path, not become 500.
108
- const response = receipt.status >= 400 && receipt.status <= 599 ? 'Problem' :
109
- operation.responses[String(receipt.status)]?.content?.[mediaType]?.schema.$ref.split('/').at(-1);
110
- if (!response)
111
- throw new ApiError(500, 'invalid_response', 'Operation produced an undeclared response status.');
112
- const validation = await options.validation.run({ kind: 'wire', schema: response, value: receipt.body }, { signal: controllers.get(request).signal });
113
- if (!validation.valid)
114
- throw new ApiError(500, 'invalid_response', 'Operation produced an invalid public response.');
115
- for (const [name, value] of Object.entries(receipt.headers))
116
- reply.header(name, value);
117
- if ('receipt' in result)
118
- reply.header('Idempotent-Replay', result.replay ? 'true' : 'false');
119
- return reply.code(receipt.status).type(mediaType).send(receipt.body);
120
- },
121
- });
122
- }
123
- return app;
124
- }
@@ -1,56 +0,0 @@
1
- import { createHash, randomBytes } from 'node:crypto';
2
- import { canonical } from '../broker/policy.js';
3
- import { ApiError } from './errors.js';
4
- export class Paging {
5
- coordinator;
6
- now;
7
- retentionMs;
8
- constructor(coordinator, now = Date.now, retentionMs = 86_400_000) {
9
- this.coordinator = coordinator;
10
- this.now = now;
11
- this.retentionMs = retentionMs;
12
- }
13
- authorizationScope(principal) {
14
- return canonical({ id: principal.id, audience: principal.audience, workspaces: [...principal.workspaceIds].sort(),
15
- ...(principal.audience === 'adapter' ? { sessionId: principal.sessionId, epoch: principal.epoch } : {}) });
16
- }
17
- limit(value) {
18
- if (value === undefined)
19
- return 50;
20
- const limit = typeof value === 'number' ? value : /^[0-9]+$/.test(value) ? Number(value) : NaN;
21
- if (!Number.isSafeInteger(limit) || limit < 1 || limit > 200)
22
- throw new ApiError(400, 'invalid_limit', 'limit must be an integer from 1 to 200.');
23
- return limit;
24
- }
25
- after(collection, principal, cursor) {
26
- if (cursor === undefined)
27
- return 0;
28
- if (!/^[A-Za-z0-9_-]{43}$/.test(cursor))
29
- throw new ApiError(400, 'invalid_cursor', 'Cursor is invalid or expired for this collection and authorization scope.');
30
- const row = this.coordinator.db.prepare('SELECT * FROM engine_cursors WHERE id=?').get(this.#hash(cursor));
31
- if (!row || row.expires_at <= this.now())
32
- throw new ApiError(409, 'cursor_expired', 'Cursor has expired or is no longer retained.');
33
- if (row.collection !== collection || row.principal_id !== this.authorizationScope(principal))
34
- throw new ApiError(400, 'invalid_cursor', 'Cursor is invalid or expired for this collection and authorization scope.');
35
- return row.last_seq;
36
- }
37
- cursor(collection, principal, after) {
38
- const value = randomBytes(32).toString('base64url');
39
- this.coordinator.atomic(() => {
40
- this.coordinator.db.prepare('DELETE FROM engine_cursors WHERE expires_at<=?').run(this.now());
41
- this.coordinator.db.prepare('INSERT INTO engine_cursors VALUES (?,?,?,?,?)').run(this.#hash(value), collection, this.authorizationScope(principal), after, this.now() + this.retentionMs);
42
- });
43
- return value;
44
- }
45
- page(collection, principal, query, read, options = {}) {
46
- const limit = this.limit(query.limit);
47
- const after = this.after(collection, principal, query.cursor);
48
- const rows = read(after, limit + 1);
49
- const selected = rows.slice(0, limit);
50
- const last = selected.at(-1)?.seq ?? after;
51
- const nextCursor = rows.length > limit || options.continuation === true || (options.continuation === 'nonempty' && selected.length > 0)
52
- ? selected.length === 0 && query.cursor ? query.cursor : this.cursor(collection, principal, last) : null;
53
- return { items: selected.map(row => row.value), nextCursor };
54
- }
55
- #hash(value) { return createHash('sha256').update(value).digest('hex'); }
56
- }
@@ -1,119 +0,0 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { digest } from '../broker/policy.js';
3
- import { EngineStore } from '../storage/store.js';
4
- import { ValidationPool } from '../config/validation-pool.js';
5
- import { ApiError } from './errors.js';
6
- export class PublicationService {
7
- store;
8
- validation;
9
- runtimes;
10
- credentialIds;
11
- now;
12
- constructor(store, validation, runtimes, credentialIds, now = Date.now) {
13
- this.store = store;
14
- this.validation = validation;
15
- this.runtimes = runtimes;
16
- this.credentialIds = credentialIds;
17
- this.now = now;
18
- }
19
- async profileReport(input, signal) {
20
- const result = await this.validation.run({ kind: 'profile', input, runtimes: this.runtimes, credentialIds: this.credentialIds }, signal ? { signal } : {});
21
- if (!result.profileReport)
22
- throw new ApiError(422, 'invalid_profile', 'Profile validation could not complete.', false, result.errors);
23
- return result.profileReport;
24
- }
25
- async validateProfile(identity, input, signal) {
26
- const existing = this.store.receipt(identity);
27
- if (existing)
28
- return { receipt: existing, replay: true };
29
- const report = await this.profileReport(input, signal);
30
- return this.store.command(identity, () => ({ status: 200, headers: {}, body: report }));
31
- }
32
- async createProfile(identity, input, signal) {
33
- const existing = this.store.receipt(identity);
34
- if (existing)
35
- return { receipt: existing, replay: true };
36
- const report = await this.profileReport(input.initialVersion, signal);
37
- if (!report.valid)
38
- throw new ApiError(422, 'invalid_profile', 'Profile configuration is invalid.', false, report.issues);
39
- return this.store.command(identity, () => {
40
- const createdAt = new Date(this.now()).toISOString();
41
- const profile = { id: randomUUID(), name: input.name, latestVersionId: randomUUID(), createdAt };
42
- const version = this.#profileVersion(profile.latestVersionId, profile.id, 1, input.initialVersion, createdAt);
43
- this.store.put('profiles', profile);
44
- this.store.put('profile_versions', version, { parentId: profile.id, immutable: true });
45
- return { status: 201, headers: { Location: `/api/v1/agent-profiles/${profile.id}`, ETag: this.store.etag('profiles', profile.id) }, body: profile };
46
- });
47
- }
48
- async publishProfile(identity, profileId, etag, input, signal) {
49
- const existing = this.store.receipt(identity);
50
- if (existing)
51
- return { receipt: existing, replay: true };
52
- const report = await this.profileReport(input, signal);
53
- if (!report.valid)
54
- throw new ApiError(422, 'invalid_profile', 'Profile configuration is invalid.', false, report.issues);
55
- return this.store.command(identity, () => {
56
- this.store.expectMatch('profiles', profileId, etag);
57
- const profile = this.store.get('profiles', profileId);
58
- const prior = this.store.get('profile_versions', profile.latestVersionId);
59
- const version = this.#profileVersion(randomUUID(), profileId, prior.version + 1, input, new Date(this.now()).toISOString());
60
- this.store.put('profile_versions', version, { parentId: profileId, immutable: true });
61
- this.store.put('profiles', { ...profile, latestVersionId: version.id });
62
- return { status: 201, headers: { Location: `/api/v1/agent-profile-versions/${version.id}`, ETag: this.store.etag('profiles', profileId) }, body: version };
63
- });
64
- }
65
- #profileVersion(id, profileId, version, input, createdAt) {
66
- return { id, profileId, version, definition: input.definition, resources: input.resources, createdAt,
67
- contentDigest: digest({ definition: input.definition, resources: input.resources }) };
68
- }
69
- async workflowReport(input, checks, signal) {
70
- const result = await this.validation.run({ kind: 'workflow', input, checks }, signal ? { signal } : {});
71
- if (!result.workflowResult)
72
- throw new ApiError(422, 'invalid_workflow', 'Workflow validation could not complete.', false, result.errors);
73
- return result.workflowResult;
74
- }
75
- async validateWorkflow(identity, input, checks, signal) {
76
- const existing = this.store.receipt(identity);
77
- if (existing)
78
- return { receipt: existing, replay: true };
79
- const result = await this.workflowReport(input, checks, signal);
80
- return this.store.command(identity, () => ({ status: 200, headers: {}, body: result.report }));
81
- }
82
- async createWorkflow(identity, input, checks, signal) {
83
- const existing = this.store.receipt(identity);
84
- if (existing)
85
- return { receipt: existing, replay: true };
86
- const result = await this.workflowReport(input.initialVersion, checks, signal);
87
- if (!result.report.valid)
88
- throw new ApiError(422, 'invalid_workflow', 'Workflow configuration is invalid.', false, result.report.issues);
89
- return this.store.command(identity, () => {
90
- const createdAt = new Date(this.now()).toISOString();
91
- const workflow = { id: randomUUID(), name: input.name, latestVersionId: randomUUID(), createdAt };
92
- const version = this.#workflowVersion(workflow.latestVersionId, workflow.id, 1, input.initialVersion, createdAt);
93
- this.store.put('workflows', workflow);
94
- this.store.put('workflow_versions', version, { parentId: workflow.id, immutable: true });
95
- return { status: 201, headers: { Location: `/api/v1/workflows/${workflow.id}`, ETag: this.store.etag('workflows', workflow.id) }, body: workflow };
96
- });
97
- }
98
- async publishWorkflow(identity, workflowId, etag, input, checks, signal) {
99
- const existing = this.store.receipt(identity);
100
- if (existing)
101
- return { receipt: existing, replay: true };
102
- const result = await this.workflowReport(input, checks, signal);
103
- if (!result.report.valid)
104
- throw new ApiError(422, 'invalid_workflow', 'Workflow configuration is invalid.', false, result.report.issues);
105
- return this.store.command(identity, () => {
106
- this.store.expectMatch('workflows', workflowId, etag);
107
- const workflow = this.store.get('workflows', workflowId);
108
- const prior = this.store.get('workflow_versions', workflow.latestVersionId);
109
- const version = this.#workflowVersion(randomUUID(), workflowId, prior.version + 1, input, new Date(this.now()).toISOString());
110
- this.store.put('workflow_versions', version, { parentId: workflowId, immutable: true });
111
- this.store.put('workflows', { ...workflow, latestVersionId: version.id });
112
- return { status: 201, headers: { Location: `/api/v1/workflow-versions/${version.id}`, ETag: this.store.etag('workflows', workflowId) }, body: version };
113
- });
114
- }
115
- #workflowVersion(id, workflowId, version, input, createdAt) {
116
- return { id, workflowId, version, source: input.source, resources: input.resources ?? [], createdAt,
117
- contentDigest: digest({ source: input.source, resources: input.resources ?? [] }) };
118
- }
119
- }
@@ -1,77 +0,0 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { canonical, digest, jsonCopy } from '../broker/policy.js';
3
- import { EngineStore } from '../storage/store.js';
4
- import { AuthService } from './auth.js';
5
- import { commandIdentity } from './control-plane.js';
6
- import { ApiError } from './errors.js';
7
- /** Append untrusted observations only. No broker execution, completion, work
8
- * drain, run advancement or gate change is performed by this handler. */
9
- export function toolEventHandlers(store, auth, resolveBinding) {
10
- const binding = (context) => {
11
- const principal = context.principal;
12
- if (principal.audience !== 'adapter' || principal.sessionId !== context.params.sessionId)
13
- throw new ApiError(403, 'assignment_forbidden', 'Session is not assigned.');
14
- const bound = jsonCopy(resolveBinding(principal.sessionId));
15
- const session = store.get('sessions', principal.sessionId);
16
- if (bound.sessionId !== principal.sessionId || bound.epoch !== principal.epoch || bound.role !== principal.role ||
17
- session.id !== bound.sessionId || session.epoch !== bound.epoch || session.role !== bound.role ||
18
- session.runId !== bound.runId || session.stepExecutionId !== bound.stepExecutionId || session.profileVersionId !== bound.profileVersionId)
19
- throw new ApiError(409, 'stale_epoch', 'Session authority is stale.');
20
- auth.assertWorkspace(principal, store.get('runs', bound.runId).workspaceId);
21
- return bound;
22
- };
23
- const correspondence = (input, bound) => {
24
- if ((input.status === 'completed' || input.status === 'in_progress') && (!input.actionRequestId || !input.dispatchAuthorizationId))
25
- throw new ApiError(409, 'tool_event_authority_mismatch', 'Execution observation requires its action and dispatch.');
26
- if (input.dispatchAuthorizationId && !input.actionRequestId)
27
- throw new ApiError(409, 'tool_event_authority_mismatch', 'Dispatch observation requires its matching action.');
28
- if (!input.actionRequestId && !input.dispatchAuthorizationId)
29
- return;
30
- const row = input.dispatchAuthorizationId ? store.coordinator.db.prepare('SELECT action_id,state,body FROM broker_dispatches WHERE id=?')
31
- .get(input.dispatchAuthorizationId) : undefined;
32
- const dispatch = row ? JSON.parse(row.body) : undefined;
33
- const actionId = input.actionRequestId;
34
- const actionRow = actionId ? store.coordinator.db.prepare('SELECT session_id,epoch,body FROM broker_actions WHERE id=?')
35
- .get(actionId) : undefined;
36
- const action = actionRow ? JSON.parse(actionRow.body) : undefined;
37
- if (!actionRow || !action || actionRow.session_id !== bound.sessionId || actionRow.epoch !== bound.epoch ||
38
- action.id !== actionId || action.sessionId !== bound.sessionId || action.epoch !== bound.epoch ||
39
- action.profileVersionId !== bound.profileVersionId || action.runId !== bound.runId || action.stepExecutionId !== bound.stepExecutionId)
40
- throw new ApiError(409, 'tool_event_authority_mismatch', 'Observation authority does not match this session.');
41
- if (input.dispatchAuthorizationId && (!row || !dispatch || !['started', 'completed', 'uncertain'].includes(row.state) ||
42
- action.state !== 'consumed' || row.action_id !== action.id ||
43
- dispatch.id !== input.dispatchAuthorizationId || dispatch.actionRequestId !== action.id ||
44
- dispatch.sessionId !== bound.sessionId || dispatch.epoch !== bound.epoch || dispatch.profileVersionId !== bound.profileVersionId ||
45
- dispatch.actionDigest !== action.actionDigest || dispatch.resourceDigest !== action.resourceDigest))
46
- throw new ApiError(409, 'tool_event_authority_mismatch', 'Observation dispatch has not been consumed in this scope.');
47
- };
48
- return new Map([['recordToolEvent', context => {
49
- // Scope checks precede HTTP receipt lookup, including authenticated replay.
50
- const bound = binding(context), input = jsonCopy(context.body);
51
- const identity = commandIdentity(context, `/sessions/${bound.sessionId}/tool-events`);
52
- return store.command(identity, () => {
53
- const key = digest([bound.sessionId, bound.epoch, input.clientEventId]);
54
- const prior = store.private('tool_event_id', key);
55
- if (prior) {
56
- const original = store.get('tool_history', prior.recordId);
57
- if (original.runId !== bound.runId || original.sessionId !== bound.sessionId || canonical(original.event) !== canonical(input))
58
- throw new ApiError(409, 'tool_event_conflict', 'Client event identity was used with a different observation.');
59
- return { status: 202, headers: {}, body: original };
60
- }
61
- correspondence(input, bound);
62
- const counter = store.private('tool_history_sequence', bound.runId);
63
- const previous = counter?.value ?? store.coordinator.db.prepare("SELECT MAX(json_extract(body,'$.sequence')) AS value FROM engine_resources WHERE kind='tool_history' AND run_id=?")
64
- .get(bound.runId).value ?? 0;
65
- const sequence = previous + 1;
66
- if (!Number.isSafeInteger(previous) || previous < 0 || !Number.isSafeInteger(sequence))
67
- throw new ApiError(500, 'tool_history_sequence_exhausted', 'Tool history sequence cannot advance.');
68
- const record = { id: randomUUID(), runId: bound.runId, sessionId: bound.sessionId,
69
- sequence, event: input, recordedAt: new Date().toISOString() };
70
- store.put('tool_history', record, { runId: bound.runId, parentId: bound.sessionId, immutable: true });
71
- store.setPrivate('tool_event_id', key, { recordId: record.id });
72
- store.setPrivate('tool_history_sequence', bound.runId, { value: sequence });
73
- store.event(bound.runId, 'tool_history_recorded', 'tool_history', record.id, { sessionId: bound.sessionId, sequence });
74
- return { status: 202, headers: {}, body: record };
75
- });
76
- }]]);
77
- }
@@ -1,34 +0,0 @@
1
- import { EngineStore } from '../storage/store.js';
2
- import { WorkspaceService } from '../workspaces/index.js';
3
- import { AuthService } from './auth.js';
4
- import { Paging } from './paging.js';
5
- import { commandIdentity } from './control-plane.js';
6
- import { ApiError } from './errors.js';
7
- export function workspaceHandlers(store, workspaces, auth, paging) {
8
- const etag = (value) => `"workspace:${value.id}:${value.version}"`;
9
- return new Map([
10
- ['listWorkspaces', context => ({ status: 200, headers: {}, body: paging.page('workspaces', context.principal, context.query, (after, limit) => workspaces.list().map((value, index) => ({ value, seq: index + 1 }))
11
- .filter(row => row.seq > after && (context.principal.workspaceIds.includes('*') || context.principal.workspaceIds.includes(row.value.id))).slice(0, limit)) })],
12
- ['getWorkspace', context => {
13
- auth.assertWorkspace(context.principal, context.params.workspaceId);
14
- const body = workspaces.get(context.params.workspaceId);
15
- return { status: 200, headers: { ETag: etag(body) }, body };
16
- }],
17
- ['createWorkspace', context => {
18
- const identity = commandIdentity(context, '/workspaces');
19
- const prior = store.receipt(identity);
20
- if (prior) {
21
- auth.assertWorkspace(context.principal, prior.body.id);
22
- return { receipt: prior, replay: true };
23
- }
24
- if (!context.principal.workspaceIds.includes('*'))
25
- throw new ApiError(403, 'workspace_registration_forbidden', 'Workspace registration requires an unrestricted operator.');
26
- let receipt;
27
- workspaces.register(context.body, { onAdmittedSql(body) {
28
- receipt = { status: 201, headers: { Location: `/api/v1/workspaces/${body.id}`, ETag: etag(body) }, body };
29
- store.saveReceipt(identity, receipt);
30
- } });
31
- return { receipt, replay: false };
32
- }],
33
- ]);
34
- }