certal 0.0.0-stage → 0.1.0
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/.claude-plugin/plugin.json +11 -0
- package/CHANGELOG.md +32 -0
- package/LICENSE +21 -0
- package/README.md +277 -2
- package/SECURITY.md +36 -0
- package/bin/certal.mjs +12 -0
- package/certal.schema.json +156 -0
- package/dist/adapters/approval-channel.d.ts +44 -0
- package/dist/adapters/approval-channel.js +74 -0
- package/dist/adapters/commands.d.ts +73 -0
- package/dist/adapters/commands.js +185 -0
- package/dist/adapters/contracts.d.ts +59 -0
- package/dist/adapters/contracts.js +1 -0
- package/dist/adapters/file-watcher.d.ts +53 -0
- package/dist/adapters/file-watcher.js +142 -0
- package/dist/adapters/in-memory.d.ts +53 -0
- package/dist/adapters/in-memory.js +165 -0
- package/dist/adapters/index.d.ts +8 -0
- package/dist/adapters/index.js +8 -0
- package/dist/adapters/manifest.d.ts +105 -0
- package/dist/adapters/manifest.js +438 -0
- package/dist/adapters/operator-auth.d.ts +47 -0
- package/dist/adapters/operator-auth.js +72 -0
- package/dist/adapters/tool-sdk.d.ts +150 -0
- package/dist/adapters/tool-sdk.js +336 -0
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.js +1 -0
- package/dist/cli/main.d.ts +1 -0
- package/dist/cli/main.js +386 -0
- package/dist/kernel/common.d.ts +46 -0
- package/dist/kernel/common.js +238 -0
- package/dist/kernel/crypto.d.ts +35 -0
- package/dist/kernel/crypto.js +54 -0
- package/dist/kernel/effects.d.ts +4 -0
- package/dist/kernel/effects.js +178 -0
- package/dist/kernel/index.d.ts +9 -0
- package/dist/kernel/index.js +9 -0
- package/dist/kernel/jcs.d.ts +24 -0
- package/dist/kernel/jcs.js +93 -0
- package/dist/kernel/leases.d.ts +11 -0
- package/dist/kernel/leases.js +86 -0
- package/dist/kernel/step.d.ts +10 -0
- package/dist/kernel/step.js +967 -0
- package/dist/kernel/types.d.ts +538 -0
- package/dist/kernel/types.js +1 -0
- package/dist/kernel/undo.d.ts +4 -0
- package/dist/kernel/undo.js +180 -0
- package/dist/kernel/validation.d.ts +13 -0
- package/dist/kernel/validation.js +307 -0
- package/dist/kernel/witness.d.ts +34 -0
- package/dist/kernel/witness.js +279 -0
- package/dist/mcp/host.d.ts +141 -0
- package/dist/mcp/host.js +517 -0
- package/dist/mcp/index.d.ts +2 -0
- package/dist/mcp/index.js +2 -0
- package/dist/mcp/server.d.ts +70 -0
- package/dist/mcp/server.js +508 -0
- package/dist/runtime/dp1.d.ts +48 -0
- package/dist/runtime/dp1.js +229 -0
- package/dist/runtime/engine.d.ts +86 -0
- package/dist/runtime/engine.js +320 -0
- package/dist/runtime/index.d.ts +4 -0
- package/dist/runtime/index.js +4 -0
- package/dist/runtime/outbox.d.ts +69 -0
- package/dist/runtime/outbox.js +238 -0
- package/dist/runtime/store.d.ts +204 -0
- package/dist/runtime/store.js +746 -0
- package/package.json +91 -4
- package/presets/exchange-firewall.json +40 -0
- package/presets/sdk.json +32 -0
- package/presets/solver.json +22 -0
- package/presets/vibeops.json +34 -0
- package/skills/certal/SKILL.md +49 -0
|
@@ -0,0 +1,508 @@
|
|
|
1
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import http from 'node:http';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { computeScopeHash, computeToolAutonomy, hashCanonical, pendingVerifyEpoch, scopeEpochOf, slotKey } from '../kernel/index.js';
|
|
6
|
+
import { normalizeObjectPath, scopeOfPath } from '../adapters/file-watcher.js';
|
|
7
|
+
import { computeClusterId } from '../adapters/tool-sdk.js';
|
|
8
|
+
/**
|
|
9
|
+
* MCP gate for agents. The tool surface is narrow on purpose: an agent can take and release a
|
|
10
|
+
* lease, propose a batch, finalize it and read the status. Approvals, undo, halt, reset and pin
|
|
11
|
+
* changes are not tools. They belong to the operator and go through the signed CLI channel.
|
|
12
|
+
*/
|
|
13
|
+
/** MCP protocol versions that this server speaks, newest first. */
|
|
14
|
+
export const SUPPORTED_PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'];
|
|
15
|
+
export const PROTOCOL_VERSION = SUPPORTED_PROTOCOL_VERSIONS[0];
|
|
16
|
+
/** Largest message that a transport accepts. */
|
|
17
|
+
export const MAX_MESSAGE_BYTES = 4 * 1024 * 1024;
|
|
18
|
+
export const AGENT_ID_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
19
|
+
const APPROVAL_REASONS = /APPROVAL/;
|
|
20
|
+
function nextAction(code, reason, onAllow) {
|
|
21
|
+
if (code === 'ALLOW')
|
|
22
|
+
return { nextLegalAction: onAllow, retryable: false };
|
|
23
|
+
if (code === 'HALT')
|
|
24
|
+
return { nextLegalAction: 'stop', retryable: false };
|
|
25
|
+
if (code === 'PAUSE') {
|
|
26
|
+
return APPROVAL_REASONS.test(reason)
|
|
27
|
+
? { nextLegalAction: 'wait_for_operator_approval', retryable: true }
|
|
28
|
+
: { nextLegalAction: 'stop_and_ask_operator', retryable: false };
|
|
29
|
+
}
|
|
30
|
+
if (/PIN_TEMP/.test(reason))
|
|
31
|
+
return { nextLegalAction: 'wait_for_pin_expiry', retryable: true };
|
|
32
|
+
if (/STALE|LEASE|CONFLICT|EPOCH|NOT_HELD|CAPACITY|BUSY/.test(reason))
|
|
33
|
+
return { nextLegalAction: 'certal_lease_acquire', retryable: true };
|
|
34
|
+
if (/PIN|FORBIDDEN|SCHEMA|UNKNOWN_TOOL|NOT_YOUR|SCOPE_UNDECLARED|CLASS_MISMATCH|OUT_OF_SCOPE/.test(reason))
|
|
35
|
+
return { nextLegalAction: 'stop', retryable: false };
|
|
36
|
+
return { nextLegalAction: 'fix_request', retryable: false };
|
|
37
|
+
}
|
|
38
|
+
const text = { type: 'string', minLength: 1 };
|
|
39
|
+
export const TOOLS = [
|
|
40
|
+
{
|
|
41
|
+
name: 'certal_lease_acquire',
|
|
42
|
+
description: 'Take a lease on a scope before any change. Returns the attemptId for the next calls.',
|
|
43
|
+
inputSchema: { type: 'object', properties: { scopeId: text, classId: text, ttlMs: { type: 'integer', minimum: 1 } }, required: ['scopeId'], additionalProperties: false },
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
name: 'certal_lease_release',
|
|
47
|
+
description: 'Give back the lease of an attempt that will not be finalized.',
|
|
48
|
+
inputSchema: { type: 'object', properties: { attemptId: text }, required: ['attemptId'], additionalProperties: false },
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
name: 'certal_propose_batch',
|
|
52
|
+
description: 'Open the attempt, submit the changes and run the declared witness stages. Call it before the changes are made.',
|
|
53
|
+
inputSchema: {
|
|
54
|
+
type: 'object',
|
|
55
|
+
properties: {
|
|
56
|
+
attemptId: text,
|
|
57
|
+
toolId: text,
|
|
58
|
+
taskId: text,
|
|
59
|
+
inputs: {},
|
|
60
|
+
ops: {
|
|
61
|
+
type: 'array',
|
|
62
|
+
minItems: 1,
|
|
63
|
+
items: {
|
|
64
|
+
type: 'object',
|
|
65
|
+
properties: {
|
|
66
|
+
objectId: text,
|
|
67
|
+
field: text,
|
|
68
|
+
value: {},
|
|
69
|
+
effect: { type: 'object', properties: { key: text, payload: {}, inversePayload: {} }, required: ['key', 'payload'], additionalProperties: false },
|
|
70
|
+
},
|
|
71
|
+
required: ['objectId', 'field', 'value'],
|
|
72
|
+
additionalProperties: false,
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
},
|
|
76
|
+
required: ['attemptId', 'toolId', 'ops'],
|
|
77
|
+
additionalProperties: false,
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
name: 'certal_finalize_batch',
|
|
82
|
+
description: 'Close a verified batch and send its effects. Answers PAUSE with the attemptId when the operator must approve first.',
|
|
83
|
+
inputSchema: { type: 'object', properties: { attemptId: text }, required: ['attemptId'], additionalProperties: false },
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
name: 'certal_status',
|
|
87
|
+
description: 'Task status, scope epochs, active leases, autonomy tiers and attempts that wait for approval.',
|
|
88
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
89
|
+
},
|
|
90
|
+
];
|
|
91
|
+
const str = (args, key) => (typeof args[key] === 'string' ? args[key] : '');
|
|
92
|
+
export class McpGateway {
|
|
93
|
+
host;
|
|
94
|
+
counter = 0;
|
|
95
|
+
constructor(host) {
|
|
96
|
+
this.host = host;
|
|
97
|
+
}
|
|
98
|
+
get state() {
|
|
99
|
+
return this.host.runtime.getState();
|
|
100
|
+
}
|
|
101
|
+
auth(agentId, attemptId, taskId) {
|
|
102
|
+
return { origin: { kind: 'Agent', actorId: agentId, taskId, attemptId }, roles: ['executor'], authMethod: 'mcp' };
|
|
103
|
+
}
|
|
104
|
+
reply(code, reason, scopeId, onAllow, extra = {}) {
|
|
105
|
+
return { decision: code, reason, scopeId, scopeEpoch: scopeEpochOf(this.state, scopeId), ...nextAction(code, reason, onAllow), ...extra };
|
|
106
|
+
}
|
|
107
|
+
fromStep(res, scopeId, onAllow, extra = {}) {
|
|
108
|
+
return this.reply(res.decision.code, res.decision.reason, scopeId, onAllow, extra);
|
|
109
|
+
}
|
|
110
|
+
classOf(scopeId, requested) {
|
|
111
|
+
return requested || this.host.manifest.scopes.find((s) => s.id === scopeId)?.classId || 'default';
|
|
112
|
+
}
|
|
113
|
+
async leaseAcquire(agentId, args) {
|
|
114
|
+
const scopeId = str(args, 'scopeId');
|
|
115
|
+
if (!scopeId)
|
|
116
|
+
return this.reply('REJECT', 'SCHEMA_SCOPE_REQUIRED', '*', '');
|
|
117
|
+
// A manifest that declares scopes is a closed list: an invented scope would have no pins.
|
|
118
|
+
const declared = this.host.manifest.scopes;
|
|
119
|
+
const scope = declared.find((s) => s.id === scopeId);
|
|
120
|
+
if (declared.length > 0 && !scope)
|
|
121
|
+
return this.reply('REJECT', 'SCOPE_UNDECLARED', scopeId, '');
|
|
122
|
+
if (scope && str(args, 'classId') && str(args, 'classId') !== scope.classId)
|
|
123
|
+
return this.reply('REJECT', 'CLASS_MISMATCH', scopeId, '');
|
|
124
|
+
const classId = this.classOf(scopeId, str(args, 'classId'));
|
|
125
|
+
this.counter += 1;
|
|
126
|
+
const attemptId = `${agentId}-${this.state.serverSeq}-${this.counter}-${randomBytes(3).toString('hex')}`;
|
|
127
|
+
const res = await this.host.agentPort.submit(`${attemptId}:lease`, this.auth(agentId, attemptId, attemptId), {
|
|
128
|
+
kind: 'AcquireLease',
|
|
129
|
+
leaseId: `lease:${attemptId}`,
|
|
130
|
+
scopeId,
|
|
131
|
+
classId,
|
|
132
|
+
attemptId,
|
|
133
|
+
units: { inferenceSlots: 1, witnessSlots: 1, mutationSlots: 1 },
|
|
134
|
+
...(typeof args.ttlMs === 'number' ? { ttlMs: args.ttlMs } : {}),
|
|
135
|
+
});
|
|
136
|
+
return this.fromStep(res, scopeId, 'certal_propose_batch', res.decision.code === 'ALLOW' ? { attemptId } : {});
|
|
137
|
+
}
|
|
138
|
+
async leaseRelease(agentId, args) {
|
|
139
|
+
const attemptId = str(args, 'attemptId');
|
|
140
|
+
const lease = this.state.leases.find((l) => l.attemptId === attemptId && l.ownerId === agentId);
|
|
141
|
+
if (!lease)
|
|
142
|
+
return this.reply('REJECT', 'LEASE_NOT_HELD', '*', '', { attemptId });
|
|
143
|
+
const res = await this.host.agentPort.submit(`${attemptId}:release:${this.state.serverSeq}`, this.auth(agentId, attemptId, attemptId), {
|
|
144
|
+
kind: 'ReleaseLease',
|
|
145
|
+
leaseId: lease.leaseId,
|
|
146
|
+
leaseEpoch: lease.leaseEpoch,
|
|
147
|
+
});
|
|
148
|
+
return this.fromStep(res, lease.scopeId, 'done', { attemptId });
|
|
149
|
+
}
|
|
150
|
+
async proposeBatch(agentId, args) {
|
|
151
|
+
const attemptId = str(args, 'attemptId');
|
|
152
|
+
const toolId = str(args, 'toolId');
|
|
153
|
+
const taskId = str(args, 'taskId') || attemptId;
|
|
154
|
+
const lease = this.state.leases.find((l) => l.attemptId === attemptId && l.ownerId === agentId);
|
|
155
|
+
if (!lease)
|
|
156
|
+
return this.reply('REJECT', 'LEASE_NOT_HELD', '*', '', { attemptId });
|
|
157
|
+
const { scopeId, classId } = lease;
|
|
158
|
+
const tool = this.host.manifest.tools[toolId];
|
|
159
|
+
if (!tool)
|
|
160
|
+
return this.reply('REJECT', 'UNKNOWN_TOOL', scopeId, '', { attemptId });
|
|
161
|
+
const rawOps = Array.isArray(args.ops) ? args.ops : [];
|
|
162
|
+
if (rawOps.length === 0 || rawOps.some((op) => !str(op, 'objectId') || !str(op, 'field') || !('value' in op))) {
|
|
163
|
+
return this.reply('REJECT', 'SCHEMA_OPS_INVALID', scopeId, '', { attemptId });
|
|
164
|
+
}
|
|
165
|
+
// Every object must belong to the leased scope. Without this check a lease on one scope
|
|
166
|
+
// could write an object that a pin protects in another scope.
|
|
167
|
+
const leased = this.host.manifest.scopes.find((s) => s.id === scopeId);
|
|
168
|
+
const objectIds = [];
|
|
169
|
+
for (const raw of rawOps) {
|
|
170
|
+
const objectId = normalizeObjectPath(str(raw, 'objectId'));
|
|
171
|
+
const owner = objectId === null ? null : scopeOfPath(this.host.manifest.scopes, objectId);
|
|
172
|
+
const outside = objectId === null || (owner !== null && owner.id !== scopeId) || (owner === null && leased !== undefined && leased.paths.length > 0);
|
|
173
|
+
if (outside)
|
|
174
|
+
return this.reply('REJECT', 'OBJECT_OUT_OF_SCOPE', scopeId, '', { attemptId });
|
|
175
|
+
objectIds.push(objectId);
|
|
176
|
+
}
|
|
177
|
+
const auth = this.auth(agentId, attemptId, taskId);
|
|
178
|
+
const scopeHash = computeScopeHash(this.state, scopeId, classId);
|
|
179
|
+
const opened = await this.host.agentPort.submit(`${attemptId}:open`, auth, {
|
|
180
|
+
kind: 'OpenAttempt',
|
|
181
|
+
attemptId,
|
|
182
|
+
taskId,
|
|
183
|
+
toolId,
|
|
184
|
+
clusterId: computeClusterId(scopeId, objectIds[0]),
|
|
185
|
+
executorId: agentId,
|
|
186
|
+
scopeId,
|
|
187
|
+
classId,
|
|
188
|
+
expectedScopeHash: scopeHash,
|
|
189
|
+
});
|
|
190
|
+
if (opened.decision.code !== 'ALLOW')
|
|
191
|
+
return this.fromStep(opened, scopeId, '', { attemptId });
|
|
192
|
+
const ops = rawOps.map((op, opIndex) => {
|
|
193
|
+
const objectId = objectIds[opIndex];
|
|
194
|
+
const field = str(op, 'field');
|
|
195
|
+
const slot = this.state.slots[slotKey(scopeId, classId, objectId, field)];
|
|
196
|
+
const effect = op.effect;
|
|
197
|
+
return {
|
|
198
|
+
opIndex,
|
|
199
|
+
objectId,
|
|
200
|
+
classId,
|
|
201
|
+
field,
|
|
202
|
+
expectedBeforeRev: slot?.rev ?? 0,
|
|
203
|
+
beforeValue: slot?.value ?? null,
|
|
204
|
+
afterValue: op.value,
|
|
205
|
+
reversibility: tool.reversibility,
|
|
206
|
+
...(effect
|
|
207
|
+
? {
|
|
208
|
+
externalEffect: {
|
|
209
|
+
effectKey: str(effect, 'key'),
|
|
210
|
+
recipientId: toolId,
|
|
211
|
+
supportsCas: tool.supportsCas,
|
|
212
|
+
actionPayload: effect.payload,
|
|
213
|
+
...('inversePayload' in effect ? { inversePayload: effect.inversePayload } : {}),
|
|
214
|
+
},
|
|
215
|
+
}
|
|
216
|
+
: {}),
|
|
217
|
+
};
|
|
218
|
+
});
|
|
219
|
+
// The kernel takes the near-miss flag of a submit for the first stage only.
|
|
220
|
+
const firstStage = this.state.policy.requiredWitnessStages[0] ?? 'L0';
|
|
221
|
+
const submitted = await this.host.agentPort.submit(`${attemptId}:submit`, auth, {
|
|
222
|
+
kind: 'SubmitBatch',
|
|
223
|
+
attemptId,
|
|
224
|
+
executorId: agentId,
|
|
225
|
+
leaseId: lease.leaseId,
|
|
226
|
+
leaseEpoch: lease.leaseEpoch,
|
|
227
|
+
expectedScopeHash: scopeHash,
|
|
228
|
+
ops,
|
|
229
|
+
snapshot: {
|
|
230
|
+
schemaVersion: 1,
|
|
231
|
+
dataRef: `mcp://${scopeId}/${attemptId}`,
|
|
232
|
+
hash: hashCanonical('input_snapshot', 1, { scopeId, inputs: args.inputs ?? null }),
|
|
233
|
+
capturedAtMs: this.host.runtime.getNowMs(),
|
|
234
|
+
confidence: 'exact',
|
|
235
|
+
},
|
|
236
|
+
...(this.host.witness.requiresNearMiss(firstStage) ? { requireNearMiss: true } : {}),
|
|
237
|
+
});
|
|
238
|
+
if (submitted.decision.code !== 'ALLOW')
|
|
239
|
+
return this.fromStep(submitted, scopeId, '', { attemptId });
|
|
240
|
+
let last = submitted;
|
|
241
|
+
for (let guard = 0; guard < 8; guard += 1) {
|
|
242
|
+
const verify = last.intents.find((i) => i.kind === 'Verify');
|
|
243
|
+
if (!verify || verify.kind !== 'Verify')
|
|
244
|
+
break;
|
|
245
|
+
const run = await this.host.witness.runStage({ verifyId: verify.verifyId, attemptId, stage: verify.stage, binding: verify.binding, scopeId, classId, toolId, ops, budgetCpuMs: verify.budgetCpuMs, requireNearMiss: verify.requireNearMiss });
|
|
246
|
+
last = await this.host.systemPort.submit(`${attemptId}:witness:${verify.stage}`, { origin: { kind: 'System', actorId: 'certal-witness' }, roles: ['witness'], authMethod: 'internal' }, {
|
|
247
|
+
kind: 'WitnessVerdict',
|
|
248
|
+
attemptId,
|
|
249
|
+
verifyId: verify.verifyId,
|
|
250
|
+
stage: verify.stage,
|
|
251
|
+
epoch: pendingVerifyEpoch(this.state, attemptId) ?? this.state.epoch,
|
|
252
|
+
scopeHash: verify.binding.scopeHash,
|
|
253
|
+
inputSnapshotHash: verify.binding.inputSnapshotHash,
|
|
254
|
+
verdict: run.verdict,
|
|
255
|
+
cpuMs: run.cpuMs,
|
|
256
|
+
nearMissPassed: run.nearMissPassed,
|
|
257
|
+
});
|
|
258
|
+
if (last.decision.code !== 'ALLOW' && last.decision.code !== 'PAUSE')
|
|
259
|
+
return this.fromStep(last, scopeId, '', { attemptId });
|
|
260
|
+
}
|
|
261
|
+
const attempt = this.state.activeAttempts.find((a) => a.attemptId === attemptId);
|
|
262
|
+
if (attempt && this.needsApproval(attempt)) {
|
|
263
|
+
await this.host.announceApproval(attemptId);
|
|
264
|
+
const granted = this.state.activeAttempts.find((a) => a.attemptId === attemptId)?.approval;
|
|
265
|
+
if (!granted)
|
|
266
|
+
return this.reply('PAUSE', attempt.approvalReason ?? 'APPROVAL_REQUIRED', scopeId, '', { attemptId });
|
|
267
|
+
}
|
|
268
|
+
return this.fromStep(last, scopeId, 'certal_finalize_batch', { attemptId });
|
|
269
|
+
}
|
|
270
|
+
needsApproval(attempt) {
|
|
271
|
+
if (attempt.approval)
|
|
272
|
+
return false;
|
|
273
|
+
const ladder = this.state.policy.enforceAutonomyLadder && computeToolAutonomy(this.state, attempt.toolId).tier !== 'AUTO';
|
|
274
|
+
return attempt.needsApproval || ladder || attempt.ops.some((o) => o.reversibility === 'IRREVERSIBLE');
|
|
275
|
+
}
|
|
276
|
+
async finalizeBatch(agentId, args) {
|
|
277
|
+
const attemptId = str(args, 'attemptId');
|
|
278
|
+
const attempt = this.state.activeAttempts.find((a) => a.attemptId === attemptId);
|
|
279
|
+
if (!attempt)
|
|
280
|
+
return this.reply('REJECT', 'ATTEMPT_NOT_FOUND', '*', '', { attemptId });
|
|
281
|
+
if (attempt.executorId !== agentId)
|
|
282
|
+
return this.reply('REJECT', 'NOT_YOUR_ATTEMPT', attempt.scopeId, '', { attemptId });
|
|
283
|
+
if (attempt.status === 'VERIFIED' && this.needsApproval(attempt)) {
|
|
284
|
+
// Asked here, before the kernel sees the finalize, so a missing approval does not pause the task for other agents.
|
|
285
|
+
await this.host.announceApproval(attemptId);
|
|
286
|
+
if (!this.state.activeAttempts.find((a) => a.attemptId === attemptId)?.approval) {
|
|
287
|
+
return this.reply('PAUSE', attempt.approvalReason ?? 'APPROVAL_REQUIRED', attempt.scopeId, '', { attemptId });
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
const approval = this.state.activeAttempts.find((a) => a.attemptId === attemptId)?.approval;
|
|
291
|
+
const res = await this.host.agentPort.submit(`${attemptId}:finalize:${this.state.serverSeq}`, this.auth(agentId, attemptId, attempt.taskId), {
|
|
292
|
+
kind: 'FinalizeBatch',
|
|
293
|
+
attemptId,
|
|
294
|
+
...(approval ? { approvalId: approval.approvalId } : {}),
|
|
295
|
+
});
|
|
296
|
+
if (res.decision.code !== 'ALLOW')
|
|
297
|
+
return this.fromStep(res, attempt.scopeId, '', { attemptId });
|
|
298
|
+
await this.host.drainOutbox();
|
|
299
|
+
const batch = this.state.batches.find((b) => b.attemptId === attemptId);
|
|
300
|
+
return this.fromStep(res, attempt.scopeId, 'done', { attemptId, ...(batch ? { batchId: batch.batchId } : {}) });
|
|
301
|
+
}
|
|
302
|
+
async call(agentId, name, args) {
|
|
303
|
+
switch (name) {
|
|
304
|
+
case 'certal_lease_acquire': return this.leaseAcquire(agentId, args);
|
|
305
|
+
case 'certal_lease_release': return this.leaseRelease(agentId, args);
|
|
306
|
+
case 'certal_propose_batch': return this.proposeBatch(agentId, args);
|
|
307
|
+
case 'certal_finalize_batch': return this.finalizeBatch(agentId, args);
|
|
308
|
+
case 'certal_status': return this.host.status();
|
|
309
|
+
default: throw new RpcError(-32602, `unknown tool: ${name}`);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
class RpcError extends Error {
|
|
314
|
+
code;
|
|
315
|
+
constructor(code, message) {
|
|
316
|
+
super(message);
|
|
317
|
+
this.code = code;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
export function packageVersion() {
|
|
321
|
+
try {
|
|
322
|
+
const file = path.join(import.meta.dirname, '..', '..', 'package.json');
|
|
323
|
+
return String(JSON.parse(fs.readFileSync(file, 'utf8')).version ?? '0.0.0');
|
|
324
|
+
}
|
|
325
|
+
catch {
|
|
326
|
+
return '0.0.0';
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
/** Handles one JSON-RPC message. Returns null for a notification. */
|
|
330
|
+
export async function handleRpc(gateway, agentId, message) {
|
|
331
|
+
const req = (typeof message === 'object' && message !== null ? message : {});
|
|
332
|
+
const isNotification = req.id === undefined;
|
|
333
|
+
const fail = (code, text) => ({ jsonrpc: '2.0', id: req.id ?? null, error: { code, message: text } });
|
|
334
|
+
if (req.jsonrpc !== '2.0' || typeof req.method !== 'string')
|
|
335
|
+
return fail(-32600, 'invalid request');
|
|
336
|
+
try {
|
|
337
|
+
let result;
|
|
338
|
+
switch (req.method) {
|
|
339
|
+
case 'initialize':
|
|
340
|
+
result = {
|
|
341
|
+
// The client's version when this server speaks it, otherwise the newest one this server speaks.
|
|
342
|
+
protocolVersion: SUPPORTED_PROTOCOL_VERSIONS.includes(req.params?.protocolVersion) ? req.params?.protocolVersion : PROTOCOL_VERSION,
|
|
343
|
+
capabilities: { tools: {} },
|
|
344
|
+
serverInfo: { name: 'certal', version: packageVersion() },
|
|
345
|
+
};
|
|
346
|
+
break;
|
|
347
|
+
case 'ping':
|
|
348
|
+
result = {};
|
|
349
|
+
break;
|
|
350
|
+
case 'tools/list':
|
|
351
|
+
result = { tools: TOOLS };
|
|
352
|
+
break;
|
|
353
|
+
case 'tools/call': {
|
|
354
|
+
const name = typeof req.params?.name === 'string' ? req.params.name : '';
|
|
355
|
+
const args = (typeof req.params?.arguments === 'object' && req.params.arguments !== null ? req.params.arguments : {});
|
|
356
|
+
const out = await gateway.call(agentId, name, args);
|
|
357
|
+
// A refusal is an error result, so a client that only looks at the flag does not go on. PAUSE is not: the agent waits.
|
|
358
|
+
const decision = out.decision;
|
|
359
|
+
result = { content: [{ type: 'text', text: JSON.stringify(out) }], isError: decision === 'REJECT' || decision === 'HALT' };
|
|
360
|
+
break;
|
|
361
|
+
}
|
|
362
|
+
default:
|
|
363
|
+
if (isNotification)
|
|
364
|
+
return null;
|
|
365
|
+
return fail(-32601, `method not found: ${req.method}`);
|
|
366
|
+
}
|
|
367
|
+
return isNotification ? null : { jsonrpc: '2.0', id: req.id, result };
|
|
368
|
+
}
|
|
369
|
+
catch (err) {
|
|
370
|
+
if (isNotification)
|
|
371
|
+
return null;
|
|
372
|
+
return err instanceof RpcError ? fail(err.code, err.message) : fail(-32603, String(err.message ?? err));
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* Serves MCP over stdin and stdout, one JSON message per line. One process is one agent.
|
|
377
|
+
* The size limit is applied to the raw input before a line is complete, so a line without an end
|
|
378
|
+
* cannot fill the memory. The rest of an oversized line is dropped.
|
|
379
|
+
*/
|
|
380
|
+
export function serveStdio(gateway, agentId, input, output) {
|
|
381
|
+
return new Promise((resolve) => {
|
|
382
|
+
let chain = Promise.resolve();
|
|
383
|
+
let parts = [];
|
|
384
|
+
let size = 0;
|
|
385
|
+
let discarding = false;
|
|
386
|
+
const send = (message) => void output.write(`${JSON.stringify(message)}\n`);
|
|
387
|
+
const handleLine = (line) => {
|
|
388
|
+
if (line.trim() === '')
|
|
389
|
+
return;
|
|
390
|
+
chain = chain.then(async () => {
|
|
391
|
+
let message;
|
|
392
|
+
try {
|
|
393
|
+
message = JSON.parse(line);
|
|
394
|
+
}
|
|
395
|
+
catch {
|
|
396
|
+
send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } });
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
const answer = await handleRpc(gateway, agentId, message);
|
|
400
|
+
if (answer !== null)
|
|
401
|
+
send(answer);
|
|
402
|
+
});
|
|
403
|
+
};
|
|
404
|
+
const flush = () => {
|
|
405
|
+
const line = Buffer.concat(parts, size).toString('utf8');
|
|
406
|
+
parts = [];
|
|
407
|
+
size = 0;
|
|
408
|
+
handleLine(line);
|
|
409
|
+
};
|
|
410
|
+
input.on('data', (chunk) => {
|
|
411
|
+
let rest = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, 'utf8');
|
|
412
|
+
while (rest.length > 0) {
|
|
413
|
+
const newline = rest.indexOf(0x0a);
|
|
414
|
+
const piece = newline >= 0 ? rest.subarray(0, newline) : rest;
|
|
415
|
+
if (!discarding) {
|
|
416
|
+
if (size + piece.length > MAX_MESSAGE_BYTES) {
|
|
417
|
+
discarding = true;
|
|
418
|
+
parts = [];
|
|
419
|
+
size = 0;
|
|
420
|
+
chain = chain.then(() => send({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'message exceeds the 4 MiB limit' } }));
|
|
421
|
+
}
|
|
422
|
+
else {
|
|
423
|
+
parts.push(piece);
|
|
424
|
+
size += piece.length;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
if (newline < 0)
|
|
428
|
+
break;
|
|
429
|
+
if (discarding)
|
|
430
|
+
discarding = false;
|
|
431
|
+
else
|
|
432
|
+
flush();
|
|
433
|
+
rest = rest.subarray(newline + 1);
|
|
434
|
+
}
|
|
435
|
+
});
|
|
436
|
+
input.on('end', () => {
|
|
437
|
+
if (!discarding && size > 0)
|
|
438
|
+
flush();
|
|
439
|
+
void chain.then(resolve);
|
|
440
|
+
});
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
/**
|
|
444
|
+
* Serves MCP over HTTP on a local address. Every agent has a bearer token of its own, created at
|
|
445
|
+
* start, and the token alone decides who the caller is. A request whose `x-certal-agent` header
|
|
446
|
+
* names another agent is refused, so one agent cannot act as another.
|
|
447
|
+
*/
|
|
448
|
+
export function serveHttp(gateway, listenHost, listenPort, agents = ['agent-1']) {
|
|
449
|
+
const tokens = {};
|
|
450
|
+
const expected = [];
|
|
451
|
+
for (const agentId of agents) {
|
|
452
|
+
const token = randomBytes(32).toString('hex');
|
|
453
|
+
tokens[agentId] = token;
|
|
454
|
+
expected.push({ agentId, header: Buffer.from(`Bearer ${token}`, 'utf8') });
|
|
455
|
+
}
|
|
456
|
+
const agentOf = (authorization) => {
|
|
457
|
+
const given = Buffer.from(authorization, 'utf8');
|
|
458
|
+
let found = null;
|
|
459
|
+
// Every token is compared, so the time does not tell which agent a near miss belongs to.
|
|
460
|
+
for (const entry of expected) {
|
|
461
|
+
if (given.length === entry.header.length && timingSafeEqual(given, entry.header))
|
|
462
|
+
found = entry.agentId;
|
|
463
|
+
}
|
|
464
|
+
return found;
|
|
465
|
+
};
|
|
466
|
+
const server = http.createServer((req, res) => {
|
|
467
|
+
const send = (status, body) => {
|
|
468
|
+
res.writeHead(status, { 'content-type': 'application/json' });
|
|
469
|
+
res.end(body === null ? '' : JSON.stringify(body));
|
|
470
|
+
};
|
|
471
|
+
const agentId = agentOf(String(req.headers.authorization ?? ''));
|
|
472
|
+
if (agentId === null)
|
|
473
|
+
return send(401, { error: 'unauthorized' });
|
|
474
|
+
if (req.method !== 'POST' || req.url !== '/mcp')
|
|
475
|
+
return send(404, { error: 'not found' });
|
|
476
|
+
const claimed = req.headers['x-certal-agent'];
|
|
477
|
+
if (claimed !== undefined && claimed !== agentId)
|
|
478
|
+
return send(403, { error: 'AGENT_IDENTITY_MISMATCH' });
|
|
479
|
+
const chunks = [];
|
|
480
|
+
let size = 0;
|
|
481
|
+
req.on('data', (chunk) => {
|
|
482
|
+
size += chunk.length;
|
|
483
|
+
if (size > MAX_MESSAGE_BYTES)
|
|
484
|
+
req.destroy();
|
|
485
|
+
else
|
|
486
|
+
chunks.push(chunk);
|
|
487
|
+
});
|
|
488
|
+
req.on('end', () => {
|
|
489
|
+
let message;
|
|
490
|
+
try {
|
|
491
|
+
message = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
492
|
+
}
|
|
493
|
+
catch {
|
|
494
|
+
return send(400, { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } });
|
|
495
|
+
}
|
|
496
|
+
handleRpc(gateway, agentId, message)
|
|
497
|
+
.then((answer) => (answer === null ? send(202, null) : send(200, answer)))
|
|
498
|
+
.catch((err) => send(500, { error: String(err.message ?? err) }));
|
|
499
|
+
});
|
|
500
|
+
});
|
|
501
|
+
return new Promise((resolve, reject) => {
|
|
502
|
+
server.once('error', reject);
|
|
503
|
+
server.listen(listenPort, listenHost, () => {
|
|
504
|
+
const address = server.address();
|
|
505
|
+
resolve({ server, port: typeof address === 'object' && address ? address.port : listenPort, tokens });
|
|
506
|
+
});
|
|
507
|
+
});
|
|
508
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { EventEnvelope } from '../kernel/types.ts';
|
|
2
|
+
import type { BlobStore, PendingBlob } from './store.ts';
|
|
3
|
+
export interface BlobPointer {
|
|
4
|
+
readonly __certalBlobRef: true;
|
|
5
|
+
readonly blobHash: string;
|
|
6
|
+
readonly byteSize: number;
|
|
7
|
+
}
|
|
8
|
+
export declare function isBlobPointer(v: unknown): v is BlobPointer;
|
|
9
|
+
/**
|
|
10
|
+
* Deterministic redaction of secrets and PII at the ingress boundary, before canonicalization and storage.
|
|
11
|
+
*/
|
|
12
|
+
export declare function redactSecrets<T>(payload: T): {
|
|
13
|
+
sanitized: T;
|
|
14
|
+
redactedCount: number;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Enforces the hard event size limit in bytes before the event enters the log chain.
|
|
18
|
+
*/
|
|
19
|
+
export declare function assertEventSizeLimit(payload: unknown, maxBytes?: number): number;
|
|
20
|
+
export interface Dp1PreparedEnvelope {
|
|
21
|
+
readonly ok: true;
|
|
22
|
+
readonly envelope: EventEnvelope;
|
|
23
|
+
readonly redactedCount: number;
|
|
24
|
+
readonly pendingBlobs: readonly PendingBlob[];
|
|
25
|
+
}
|
|
26
|
+
export interface Dp1RejectedEnvelope {
|
|
27
|
+
readonly ok: false;
|
|
28
|
+
readonly reason: 'EVENT_SIZE_LIMIT_EXCEEDED' | 'FLOAT_NOT_ALLOWED' | 'SCHEMA_INVALID';
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Restores the original value behind a __certalBlobRef pointer from the BlobStore.
|
|
32
|
+
*/
|
|
33
|
+
export declare function hydrateBlobValue(value: unknown, blobStore: BlobStore): unknown;
|
|
34
|
+
/**
|
|
35
|
+
* Strict variant: restores the value behind a __certalBlobRef pointer and reports a missing blob.
|
|
36
|
+
*/
|
|
37
|
+
export declare function hydrateBlobValueStrict(value: unknown, blobStore: BlobStore): {
|
|
38
|
+
readonly ok: true;
|
|
39
|
+
readonly value: unknown;
|
|
40
|
+
} | {
|
|
41
|
+
readonly ok: false;
|
|
42
|
+
readonly missingBlobHash: string;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Ingress boundary: redacts secrets, buffers the offload of large single fields (nothing is written
|
|
46
|
+
* before step() accepts the event) and checks the hard event size limit.
|
|
47
|
+
*/
|
|
48
|
+
export declare function prepareDp1Envelope(rawEnvelope: EventEnvelope, maxInlinePayloadBytes: number, maxEventBytes: number, fieldOffloadThresholdBytes?: number): Dp1PreparedEnvelope | Dp1RejectedEnvelope;
|