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

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 +734 -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 +1862 -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 +11629 -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 +127 -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 +353 -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 @@
1
+ export {};
@@ -0,0 +1,44 @@
1
+ import { CodingService } from './coding.js';
2
+ import { ApiError } from './errors.js';
3
+ import { RunCommands } from '../engine/commands.js';
4
+ import { WorkflowEngine } from '../engine/workflow-engine.js';
5
+ import { SqliteCoordinator } from '../storage/coordinator.js';
6
+ import { brokerHandlers } from './broker-handlers.js';
7
+ import { controlPlaneHandlers } from './control-plane.js';
8
+ import { historyHandlers } from './history-handlers.js';
9
+ import { createHttpServer } from './http.js';
10
+ import { Paging } from './paging.js';
11
+ import { toolEventHandlers } from './tool-event-handler.js';
12
+ import { workspaceHandlers } from './workspace-handlers.js';
13
+ /** Normal production assembly. Deployment owns its startup lock and native
14
+ * services, acquired BEFORE entering this function. Tests may supply explicit
15
+ * controlled ports, but never a second route-registration implementation. */
16
+ export function createApplication(services) {
17
+ const { store, auth, publication, validation, broker, workspaces, pins, schemas, checks, driver } = services;
18
+ const coordinator = store.coordinator;
19
+ if (!(coordinator instanceof SqliteCoordinator))
20
+ throw new Error('application_requires_shared_sqlite_coordinator');
21
+ coordinator.assertOutsideTransaction();
22
+ let engine;
23
+ const commands = new RunCommands({ store, auth, publication, broker, workspaces, pins,
24
+ checkNames: () => checks.list().map(check => check.name), ...(services.coding ? { commandRecoveryRequired: (id) => services.coding.runner.recoveryRequired(id) } : {}), work: id => engine.work(id), wake: id => engine.wake(id),
25
+ ...(services.now ? { now: services.now } : {}) });
26
+ engine = new WorkflowEngine({ commands, workspaces, pins, schemas, checks, driver, validation,
27
+ ...(services.coding ? { commandCapabilities: () => ({ ...services.coding.runner.settings }) } : {}),
28
+ ...(services.coding ? { reconcileCommands: (id) => services.coding.runner.reconcile(id), additionalWork: (id) => services.coding.runner.activeWork(id), inputWaiting: (id) => services.coding.developer.waiting(id), closeCommands: async () => { await services.coding.developer.close(); await services.coding.runner.close(); }, ...(services.coding.configuration.contextBytes ? { contextBytes: services.coding.configuration.contextBytes } : {}) } : {}),
29
+ deploymentPolicy: services.deploymentPolicy, workspaceInstructions: services.workspaceInstructions });
30
+ const coding = services.coding ? new CodingService({ ...services.coding, store, auth, workspaces, publication, checks, commands, assignEvidence: (sessionId, artifactId) => engine.addInput(sessionId, artifactId), wake: id => engine.wake(id) }) : undefined;
31
+ const codingHandlers = coding?.handlers() ?? new Map(['getCodingReadiness', 'startCodingTask', 'getCodingTaskResult', 'sendTaskMessage', 'listTaskQuestions', 'answerTaskQuestion'].map(name => [name, () => { throw new ApiError(503, 'coding_unavailable', 'This deployment does not have coding services configured.'); }]));
32
+ const paging = new Paging(coordinator);
33
+ const handlers = new Map([...controlPlaneHandlers(store, publication, paging, checks),
34
+ ...historyHandlers(store, auth, paging), ...brokerHandlers(store, broker, auth, paging, id => commands.binding(id), engine.projection),
35
+ ...workspaceHandlers(store, workspaces, auth, paging), ...toolEventHandlers(store, auth, id => commands.binding(id)), ...commands.handlers(), ...codingHandlers]);
36
+ const app = createHttpServer({ auth, validation, handlers, requireComplete: true });
37
+ coordinator.setQuiescenceProbe(id => engine.quiet(id));
38
+ return { app, engine, commands, handlers, coding,
39
+ start(recover = false) { if (recover)
40
+ engine.restoreInterrupted(); engine.start(); },
41
+ /** Native services, worker pool and database remain deployment-owned. */
42
+ async close() { await app.close(); await engine.close(); },
43
+ };
44
+ }
@@ -0,0 +1,67 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { ApiError } from './errors.js';
3
+ const tokenDigest = (token) => createHash('sha256').update(token).digest('hex');
4
+ export class AuthService {
5
+ coordinator;
6
+ sessionCurrent;
7
+ constructor(coordinator, sessionCurrent) {
8
+ this.coordinator = coordinator;
9
+ this.sessionCurrent = sessionCurrent;
10
+ }
11
+ registerOperator(id, token, workspaceIds) {
12
+ if (!token || !id || !workspaceIds.length)
13
+ throw new Error('Operator token and explicit workspace scope are required');
14
+ this.coordinator.atomic(() => {
15
+ const digest = tokenDigest(token);
16
+ const existing = this.coordinator.db.prepare('SELECT principal_id,audience FROM engine_tokens WHERE digest=?').get(digest);
17
+ if (existing && (existing.audience !== 'operator' || existing.principal_id !== id))
18
+ throw new Error('Token identity collision');
19
+ this.coordinator.db.prepare("UPDATE engine_tokens SET revoked=1 WHERE principal_id=? AND audience='operator' AND digest<>?").run(id, digest);
20
+ this.coordinator.db.prepare(`INSERT INTO engine_tokens VALUES (?,?,'operator',NULL,NULL,NULL,?,0)
21
+ ON CONFLICT(digest) DO UPDATE SET workspace_scope=excluded.workspace_scope,revoked=0`).run(digest, id, JSON.stringify(workspaceIds));
22
+ });
23
+ }
24
+ issueSession(sessionId, epoch, role, workspaceId) {
25
+ const token = randomBytes(32).toString('base64url');
26
+ this.coordinator.atomic(() => {
27
+ if (!this.sessionCurrent(sessionId, epoch))
28
+ throw new ApiError(409, 'stale_epoch', 'Cannot issue a token for a stale session.');
29
+ this.coordinator.db.prepare("INSERT INTO engine_tokens VALUES (?,?,'adapter',?,?,?,?,0)").run(tokenDigest(token), `adapter_${sessionId}`, sessionId, epoch, role, JSON.stringify([workspaceId]));
30
+ });
31
+ return token; // Deployment/bridge channel only, NEVER a public DTO or log.
32
+ }
33
+ revokeSession(sessionId) {
34
+ this.coordinator.atomic(() => {
35
+ this.coordinator.db.prepare("UPDATE engine_tokens SET revoked=1 WHERE session_id=? AND audience='adapter'").run(sessionId);
36
+ });
37
+ }
38
+ authenticate(authorization, epochHeader, audience) {
39
+ const match = /^Bearer ([^\s]+)$/.exec(authorization ?? '');
40
+ if (!match)
41
+ throw new ApiError(401, 'unauthorized', 'A bearer token is required.');
42
+ const row = this.coordinator.db.prepare('SELECT * FROM engine_tokens WHERE digest=?').get(tokenDigest(match[1]));
43
+ if (!row)
44
+ throw new ApiError(401, 'unauthorized', 'The bearer token is invalid.');
45
+ if (row.audience === 'adapter') {
46
+ if (audience === 'operator')
47
+ throw new ApiError(403, 'forbidden', 'Operator authentication is required.');
48
+ const epoch = Number(epochHeader);
49
+ if (row.revoked || !epochHeader || !Number.isSafeInteger(epoch) || epoch < 1 ||
50
+ epoch !== row.epoch || !row.session_id || !row.role || !this.sessionCurrent(row.session_id, epoch)) {
51
+ throw new ApiError(409, 'stale_epoch', 'The session epoch is stale or revoked.');
52
+ }
53
+ return { id: row.principal_id, audience: 'adapter', workspaceIds: JSON.parse(row.workspace_scope),
54
+ sessionId: row.session_id, epoch, role: row.role };
55
+ }
56
+ if (row.revoked)
57
+ throw new ApiError(401, 'unauthorized', 'The bearer token is invalid.');
58
+ if (audience === 'adapter')
59
+ throw new ApiError(403, 'forbidden', 'Session authentication is required.');
60
+ return { id: row.principal_id, audience: 'operator', workspaceIds: JSON.parse(row.workspace_scope) };
61
+ }
62
+ assertWorkspace(principal, workspaceId) {
63
+ if (!principal.workspaceIds.includes('*') && !principal.workspaceIds.includes(workspaceId)) {
64
+ throw new ApiError(404, 'not_found', 'Resource not found.');
65
+ }
66
+ }
67
+ }
@@ -0,0 +1,242 @@
1
+ import { ActionBroker, canonical, normalizeResources, BrokerError } from '../broker/index.js';
2
+ import { EngineStore } from '../storage/store.js';
3
+ import { AuthService } from './auth.js';
4
+ import { Paging } from './paging.js';
5
+ import { commandIdentity } from './control-plane.js';
6
+ import { ApiError, problem } from './errors.js';
7
+ import { approvalWaitFor, brokerWorkId } from '../engine/drain-state.js';
8
+ /** Explicit DTO projection only. Never expose private policy-audit rows,
9
+ * resolved credentials, execution callbacks or filesystem descriptors. */
10
+ export class BrokerProjection {
11
+ store;
12
+ broker;
13
+ options;
14
+ constructor(store, broker, options = {}) {
15
+ this.store = store;
16
+ this.broker = broker;
17
+ this.options = options;
18
+ }
19
+ rawAction(id) {
20
+ const row = this.store.coordinator.db.prepare('SELECT body FROM broker_actions WHERE id=?').get(id);
21
+ if (!row)
22
+ throw new ApiError(404, 'not_found', 'Resource not found.');
23
+ return JSON.parse(row.body);
24
+ }
25
+ rawApproval(id) { return this.broker.approval(id); }
26
+ action(value) {
27
+ const dispatch = value.state === 'consumed' ? this.store.coordinator.db.prepare('SELECT id FROM broker_dispatches WHERE action_id=?').get(value.id) : undefined;
28
+ const reason = this.store.private('action_reason', value.id)?.code;
29
+ return { id: value.id, runId: value.runId, stepExecutionId: value.stepExecutionId, sessionId: value.sessionId,
30
+ epoch: value.epoch, profileVersionId: value.profileVersionId,
31
+ action: { toolId: value.action.toolId, arguments: value.action.arguments, resources: value.action.resources },
32
+ actionDigest: value.actionDigest, resourceDigest: value.resourceDigest, policyEffect: value.policyEffect, state: value.state,
33
+ ...(value.approvalId ? { approvalId: value.approvalId } : {}), ...(dispatch ? { dispatchAuthorizationId: dispatch.id } : {}),
34
+ reasonCode: reason ?? (value.state === 'denied' ? value.policyEffect === 'deny' ? 'policy_denied' : 'approval_denied' :
35
+ value.state === 'expired' ? 'action_expired' : value.state === 'invalidated' ? 'authority_invalidated' :
36
+ value.policyEffect === 'require_approval' ? 'approval_required' : 'policy_allowed'),
37
+ version: value.version, createdAt: new Date(value.createdAt).toISOString(), expiresAt: new Date(value.expiresAt).toISOString() };
38
+ }
39
+ approval(value) {
40
+ const action = this.action(this.rawAction(value.actionRequestId));
41
+ const meta = this.store.private('approval_metadata', value.id);
42
+ return { id: value.id, runId: action.runId, stepExecutionId: action.stepExecutionId, sessionId: action.sessionId,
43
+ epoch: action.epoch, profileVersionId: action.profileVersionId, actionRequestId: value.actionRequestId, action: action.action,
44
+ actionDigest: action.actionDigest, resourceDigest: action.resourceDigest, policyEffect: 'require_approval', state: value.state,
45
+ version: value.version, createdAt: action.createdAt, expiresAt: action.expiresAt,
46
+ ...(meta ? meta : value.actor ? { actorId: value.actor } : {}),
47
+ ...(value.state === 'consumed' && action.dispatchAuthorizationId ? { dispatchAuthorizationId: action.dispatchAuthorizationId } : {}) };
48
+ }
49
+ dispatch(value) {
50
+ return { id: value.id, actionRequestId: value.actionRequestId, sessionId: value.sessionId, epoch: value.epoch,
51
+ profileVersionId: value.profileVersionId, actionDigest: value.actionDigest, resourceDigest: value.resourceDigest,
52
+ mode: 'single_use', claimedAt: new Date(value.claimedAt).toISOString(), expiresAt: new Date(value.expiresAt).toISOString() };
53
+ }
54
+ /** Also catches durable invalidations made by internal runtime invocations
55
+ * and startup recovery, rather than trusting a process-local notification. */
56
+ syncSql(runId) {
57
+ this.store.coordinator.atomic(() => this.projectSql(runId));
58
+ }
59
+ projectSql(runId) {
60
+ const rows = this.store.coordinator.db.prepare("SELECT body FROM broker_actions WHERE json_extract(body,'$.runId')=? ORDER BY rowid").all(runId);
61
+ for (const row of rows) {
62
+ const value = this.action(JSON.parse(row.body)), prior = this.store.find('actions', value.id);
63
+ if (prior && canonical(prior) === canonical(value))
64
+ continue;
65
+ this.store.put('actions', value, { runId });
66
+ if (!prior)
67
+ this.store.event(runId, value.state === 'denied' ? 'action_denied' : 'action_authorized', 'action', value.id, { state: value.state, actionDigest: value.actionDigest }, Date.parse(value.createdAt));
68
+ }
69
+ const approvals = this.store.coordinator.db.prepare('SELECT body FROM broker_approvals WHERE run_id=? ORDER BY rowid').all(runId);
70
+ for (const row of approvals) {
71
+ const value = this.approval(JSON.parse(row.body)), prior = this.store.find('approvals', value.id);
72
+ if (prior && canonical(prior) === canonical(value))
73
+ continue;
74
+ this.store.put('approvals', value, { runId });
75
+ if (!prior)
76
+ this.store.event(runId, 'approval_requested', 'approval', value.id, { actionRequestId: value.actionRequestId }, Date.parse(value.createdAt));
77
+ if (prior?.state !== value.state && value.state !== 'pending') {
78
+ const type = value.state === 'expired' ? 'approval_expired' : value.state === 'invalidated' ? 'approval_invalidated' :
79
+ value.state === 'consumed' ? 'approval_consumed' : 'approval_decided';
80
+ this.store.event(runId, type, 'approval', value.id, { state: value.state, actionRequestId: value.actionRequestId });
81
+ }
82
+ }
83
+ const run = this.store.find('runs', runId);
84
+ if (run) {
85
+ const pendingApprovalIds = this.store.list('approvals', { runId, limit: Number.MAX_SAFE_INTEGER }).filter(row => row.value.state === 'pending').map(row => row.value.id).sort();
86
+ const work = this.store.coordinator.db.prepare('SELECT id FROM broker_work WHERE run_id=?').all(runId);
87
+ const inFlightWork = this.options.work?.(runId) ?? work.map(item => ({ id: brokerWorkId(item.id),
88
+ kind: item.id.includes(':runtime-model:') ? 'agent_turn' : 'tool',
89
+ description: item.id.includes(':runtime-model:') ? 'Agent generation' : 'Broker-managed work' }));
90
+ const approvalWait = approvalWaitFor(run, pendingApprovalIds, inFlightWork, Date.now()), status = approvalWait.status;
91
+ if (canonical(approvalWait) !== canonical(run.approvalWait)) {
92
+ // A waiting hold proves this owner's work has drained. Publish its
93
+ // frozen public clock in the SAME commit, never an invalid interim Run.
94
+ // Core also checkpoints all authoritative clock books below.
95
+ // Let the authoritative checkpoint see the old clock state so its
96
+ // transition also records sub-second consumed time at the freeze.
97
+ const timing = !this.options.onRunChangedSql && status === 'waiting' && run.timing.clockState === 'running' ?
98
+ { ...run.timing, clockState: 'paused' } : run.timing;
99
+ this.store.put('runs', { ...run, timing, approvalWait, version: run.version + 1, updatedAt: new Date().toISOString() });
100
+ this.store.event(runId, 'approval_wait_changed', 'run', runId, { status, pendingApprovalIds });
101
+ this.options.onRunChangedSql?.(runId);
102
+ }
103
+ }
104
+ }
105
+ refresh(runId) {
106
+ this.store.coordinator.assertOutsideTransaction();
107
+ if (this.store.coordinator.db.prepare('SELECT id FROM broker_runs WHERE id=?').get(runId))
108
+ this.broker.snapshot(runId);
109
+ this.store.coordinator.atomic(() => this.syncSql(runId));
110
+ }
111
+ }
112
+ export function brokerHandlers(store, broker, auth, paging, resolveBinding, projection = new BrokerProjection(store, broker)) {
113
+ const authorizeRun = (context, runId) => auth.assertWorkspace(context.principal, store.get('runs', runId).workspaceId);
114
+ const binding = (context) => {
115
+ if (context.principal.audience !== 'adapter' || context.principal.sessionId !== context.params.sessionId)
116
+ throw new ApiError(403, 'assignment_forbidden', 'Session is not assigned.');
117
+ const value = resolveBinding(context.principal.sessionId);
118
+ if (value.sessionId !== context.principal.sessionId || value.epoch !== context.principal.epoch || value.role !== context.principal.role)
119
+ throw new ApiError(409, 'stale_epoch', 'Session authority is stale.');
120
+ authorizeRun(context, value.runId);
121
+ return value;
122
+ };
123
+ const etag = (kind, value) => `"${kind}:${value.id}:${value.version}"`;
124
+ const version = (supplied, kind, value) => supplied === undefined ? undefined : supplied === etag(kind, value) ? value.version : -1;
125
+ const original = (identity) => { const receipt = store.receipt(identity); return receipt ? { receipt, replay: true } : undefined; };
126
+ const failure = (context, identity, runId, actionId) => (error) => {
127
+ if (actionId)
128
+ store.setPrivate('action_reason', actionId, { code: error.code });
129
+ projection.syncSql(runId);
130
+ store.saveReceipt(identity, { status: error.status, headers: {}, body: problem(new ApiError(error.status, error.code, 'Action authority is no longer usable.'), context.requestId) });
131
+ };
132
+ const committed = (identity, error) => {
133
+ if (!(error instanceof BrokerError) || !error.persist)
134
+ throw error;
135
+ store.coordinator.assertOutsideTransaction();
136
+ const receipt = store.receipt(identity);
137
+ if (!receipt)
138
+ throw error;
139
+ return { receipt, replay: false };
140
+ };
141
+ const handlers = new Map();
142
+ handlers.set('authorizeAction', async (context) => {
143
+ const bound = binding(context), identity = commandIdentity(context, `/sessions/${bound.sessionId}/action-requests`);
144
+ const prior = original(identity);
145
+ if (prior)
146
+ return prior;
147
+ const input = context.body;
148
+ let receipt;
149
+ const result = await broker.authorize(bound, { clientActionId: input.clientActionId, toolId: input.action.toolId, arguments: input.action.arguments }, identity.key, {
150
+ onAdmittedSql(value) {
151
+ if (value.policyEffect !== 'deny' && canonical(normalizeResources(input.action.resources)) !== canonical(value.action.resources))
152
+ throw new ApiError(422, 'action_resource_mismatch', 'Declared action resources do not match trusted interception.');
153
+ projection.syncSql(bound.runId);
154
+ const body = projection.action(value);
155
+ receipt = { status: 201, headers: { ETag: etag('action', body), Location: `/api/v1/actions/${body.id}` }, body };
156
+ store.saveReceipt(identity, receipt);
157
+ },
158
+ });
159
+ return { receipt, replay: result.replay };
160
+ });
161
+ handlers.set('getActionAuthorization', context => {
162
+ const bound = binding(context);
163
+ const raw = broker.action(bound, context.params.actionId);
164
+ projection.refresh(raw.runId);
165
+ const body = projection.action(raw);
166
+ return { status: 200, headers: { ETag: etag('action', body) }, body };
167
+ });
168
+ handlers.set('claimActionDispatch', async (context) => {
169
+ const bound = binding(context), actionId = context.params.actionId, identity = commandIdentity(context, `/sessions/${bound.sessionId}/action-requests/${actionId}/claims`);
170
+ const prior = original(identity);
171
+ if (prior)
172
+ return prior;
173
+ const current = broker.action(bound, actionId), input = context.body;
174
+ let receipt;
175
+ const expectedVersion = version(context.header('if-match'), 'action', current);
176
+ try {
177
+ const result = await broker.claim(bound, actionId, { idempotencyKey: identity.key, actionDigest: input.actionDigest, resourceDigest: input.resourceDigest,
178
+ ...(expectedVersion === undefined ? {} : { expectedVersion }) }, {
179
+ onAdmittedSql(value) {
180
+ projection.syncSql(bound.runId);
181
+ const body = projection.dispatch(value);
182
+ receipt = { status: 201, headers: { Location: `/api/v1/actions/${actionId}`, ETag: etag('action', projection.action(projection.rawAction(actionId))) }, body };
183
+ store.saveReceipt(identity, receipt);
184
+ }, onCommittedErrorSql: failure(context, identity, bound.runId, actionId),
185
+ });
186
+ return { receipt, replay: result.replay };
187
+ }
188
+ catch (error) {
189
+ return committed(identity, error);
190
+ }
191
+ });
192
+ for (const [operation, kind] of [['listRunActions', 'actions'], ['listRunApprovals', 'approvals']])
193
+ handlers.set(operation, context => {
194
+ const runId = context.params.runId;
195
+ authorizeRun(context, runId);
196
+ projection.refresh(runId);
197
+ return { status: 200, headers: {}, body: paging.page(`${kind}:${runId}`, context.principal, context.query, (after, limit) => store.list(kind, { runId, after, limit })) };
198
+ });
199
+ handlers.set('getAction', context => {
200
+ const raw = projection.rawAction(context.params.actionId);
201
+ authorizeRun(context, raw.runId);
202
+ projection.refresh(raw.runId);
203
+ const body = projection.action(projection.rawAction(raw.id));
204
+ return { status: 200, headers: { ETag: etag('action', body) }, body };
205
+ });
206
+ handlers.set('getApproval', context => {
207
+ const raw = projection.rawApproval(context.params.approvalId);
208
+ authorizeRun(context, raw.runId);
209
+ projection.refresh(raw.runId);
210
+ const body = projection.approval(projection.rawApproval(raw.id));
211
+ return { status: 200, headers: { ETag: etag('approval', body) }, body };
212
+ });
213
+ handlers.set('decideApproval', context => {
214
+ const id = context.params.approvalId, raw = projection.rawApproval(id);
215
+ authorizeRun(context, raw.runId);
216
+ const identity = commandIdentity(context, `/approvals/${id}/decisions`), prior = original(identity);
217
+ if (prior)
218
+ return prior;
219
+ const input = context.body;
220
+ let receipt;
221
+ const expectedVersion = version(context.header('if-match'), 'approval', raw);
222
+ try {
223
+ const result = broker.decide(id, { actor: context.principal.id, idempotencyKey: identity.key, actionDigest: input.actionDigest, decision: input.decision,
224
+ ...(expectedVersion === undefined ? {} : { expectedVersion }) }, {
225
+ onAdmittedSql(value) {
226
+ if (!store.private('approval_metadata', id))
227
+ store.setPrivate('approval_metadata', id, { actorId: context.principal.id,
228
+ ...(input.reason === undefined ? {} : { reason: input.reason }), decidedAt: new Date().toISOString() });
229
+ projection.syncSql(raw.runId);
230
+ const body = projection.approval(value);
231
+ receipt = { status: 200, headers: { ETag: etag('approval', body), Location: `/api/v1/approvals/${id}` }, body };
232
+ store.saveReceipt(identity, receipt);
233
+ }, onCommittedErrorSql: failure(context, identity, raw.runId, raw.actionRequestId),
234
+ });
235
+ return { receipt, replay: result.replay };
236
+ }
237
+ catch (error) {
238
+ return committed(identity, error);
239
+ }
240
+ });
241
+ return handlers;
242
+ }