code60-transmission-server 0.1.0-staging.6 → 0.1.1
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.
- package/INTENT.md +47 -0
- package/README.md +87 -308
- package/dist/src/acp.js +130 -0
- package/dist/src/contract.js +133 -0
- package/dist/src/engine.js +650 -0
- package/dist/src/linux.js +84 -0
- package/dist/src/main.js +81 -25
- package/dist/src/repository.js +94 -0
- package/dist/src/service.js +196 -0
- package/package.json +19 -35
- package/reference/openapi.json +1073 -0
- package/README.engine.md +0 -463
- package/dist/src/broker/filesystem.js +0 -385
- package/dist/src/broker/index.js +0 -734
- package/dist/src/broker/native/README.md +0 -207
- package/dist/src/broker/native/build.js +0 -46
- package/dist/src/broker/native/command-helper.c +0 -93
- package/dist/src/broker/native/fs-helper.c +0 -529
- package/dist/src/broker/native/git-helper.c +0 -205
- package/dist/src/broker/policy.js +0 -149
- package/dist/src/broker/startup-lock.js +0 -14
- package/dist/src/broker/types.js +0 -11
- package/dist/src/cli/configure.js +0 -193
- package/dist/src/cli/daemon.js +0 -369
- package/dist/src/cli/helpers.js +0 -112
- package/dist/src/cli/main.js +0 -189
- package/dist/src/cli/runtime-build.js +0 -38
- package/dist/src/config/coding-policy.js +0 -4
- package/dist/src/config/deployment.js +0 -182
- package/dist/src/config/documents.js +0 -29
- package/dist/src/config/profile-validation.js +0 -123
- package/dist/src/config/schema-graph.js +0 -237
- package/dist/src/config/schema-loader.js +0 -185
- package/dist/src/config/validation-pool.js +0 -105
- package/dist/src/config/validation-protocol.js +0 -1
- package/dist/src/config/validation-worker.js +0 -106
- package/dist/src/config/workflow-language.js +0 -9
- package/dist/src/config/workflow-schema.json +0 -545
- package/dist/src/config/workflow-types.js +0 -1
- package/dist/src/config/workflow-validation.js +0 -95
- package/dist/src/engine/budgets.js +0 -50
- package/dist/src/engine/clocks.js +0 -27
- package/dist/src/engine/commands.js +0 -472
- package/dist/src/engine/contracts.js +0 -11
- package/dist/src/engine/drain-state.js +0 -31
- package/dist/src/engine/effective-permissions.js +0 -120
- package/dist/src/engine/instruction-pins.js +0 -205
- package/dist/src/engine/retries.js +0 -50
- package/dist/src/engine/state.js +0 -1
- package/dist/src/engine/timing.js +0 -23
- package/dist/src/engine/tool-observations.js +0 -87
- package/dist/src/engine/workflow-engine.js +0 -1862
- package/dist/src/mcp/catalog.js +0 -71
- package/dist/src/mcp/main.js +0 -26
- package/dist/src/mcp/server.js +0 -147
- package/dist/src/runtime/codex-app-server.js +0 -91
- package/dist/src/runtime/containment.js +0 -82
- package/dist/src/runtime/engine-driver.js +0 -221
- package/dist/src/runtime/json-line-writer.js +0 -192
- package/dist/src/runtime/pinned-instruction-sources.js +0 -24
- package/dist/src/runtime/protocol-client.js +0 -264
- package/dist/src/runtime/protocol-pool.js +0 -183
- package/dist/src/runtime/protocol-projection.js +0 -393
- package/dist/src/runtime/protocol-types.js +0 -1
- package/dist/src/runtime/protocol-worker.js +0 -18
- package/dist/src/runtime/provider-bridge.js +0 -290
- package/dist/src/runtime/provider-credentials.js +0 -41
- package/dist/src/runtime/provider-transport.js +0 -406
- package/dist/src/runtime/runtime-broker.js +0 -213
- package/dist/src/runtime/workspace-instructions.js +0 -120
- package/dist/src/runtime/workspace-view.js +0 -74
- package/dist/src/server/api-contract.json +0 -11614
- package/dist/src/server/api-types.js +0 -1
- package/dist/src/server/application.js +0 -44
- package/dist/src/server/auth.js +0 -67
- package/dist/src/server/broker-handlers.js +0 -242
- package/dist/src/server/coding.js +0 -254
- package/dist/src/server/control-plane.js +0 -50
- package/dist/src/server/deployment.js +0 -249
- package/dist/src/server/errors.js +0 -22
- package/dist/src/server/history-handlers.js +0 -127
- package/dist/src/server/http.js +0 -124
- package/dist/src/server/paging.js +0 -56
- package/dist/src/server/publication.js +0 -119
- package/dist/src/server/tool-event-handler.js +0 -77
- package/dist/src/server/workspace-handlers.js +0 -34
- package/dist/src/storage/coordinator.js +0 -224
- package/dist/src/storage/startup-lock.js +0 -71
- package/dist/src/storage/store.js +0 -167
- package/dist/src/tools/check-worker.js +0 -81
- package/dist/src/tools/checks.js +0 -117
- package/dist/src/tools/command-check.js +0 -34
- package/dist/src/tools/commands.js +0 -310
- package/dist/src/tools/developer.js +0 -351
- package/dist/src/tools/dns.js +0 -248
- package/dist/src/tools/http-contract.js +0 -38
- package/dist/src/tools/http.js +0 -358
- package/dist/src/tools/index.js +0 -194
- package/dist/src/tools/worker-check.js +0 -73
- package/dist/src/workspaces/git.js +0 -227
- package/dist/src/workspaces/index.js +0 -937
- package/dist/src/workspaces/source.js +0 -295
- package/examples/deployment.local.json +0 -22
- package/scripts/postinstall.mjs +0 -26
|
@@ -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({ sourceTracking: true, ...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
|
-
}
|
|
@@ -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
|
-
}
|