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.
Files changed (73) hide show
  1. package/.claude-plugin/plugin.json +11 -0
  2. package/CHANGELOG.md +32 -0
  3. package/LICENSE +21 -0
  4. package/README.md +277 -2
  5. package/SECURITY.md +36 -0
  6. package/bin/certal.mjs +12 -0
  7. package/certal.schema.json +156 -0
  8. package/dist/adapters/approval-channel.d.ts +44 -0
  9. package/dist/adapters/approval-channel.js +74 -0
  10. package/dist/adapters/commands.d.ts +73 -0
  11. package/dist/adapters/commands.js +185 -0
  12. package/dist/adapters/contracts.d.ts +59 -0
  13. package/dist/adapters/contracts.js +1 -0
  14. package/dist/adapters/file-watcher.d.ts +53 -0
  15. package/dist/adapters/file-watcher.js +142 -0
  16. package/dist/adapters/in-memory.d.ts +53 -0
  17. package/dist/adapters/in-memory.js +165 -0
  18. package/dist/adapters/index.d.ts +8 -0
  19. package/dist/adapters/index.js +8 -0
  20. package/dist/adapters/manifest.d.ts +105 -0
  21. package/dist/adapters/manifest.js +438 -0
  22. package/dist/adapters/operator-auth.d.ts +47 -0
  23. package/dist/adapters/operator-auth.js +72 -0
  24. package/dist/adapters/tool-sdk.d.ts +150 -0
  25. package/dist/adapters/tool-sdk.js +336 -0
  26. package/dist/cli/index.d.ts +1 -0
  27. package/dist/cli/index.js +1 -0
  28. package/dist/cli/main.d.ts +1 -0
  29. package/dist/cli/main.js +386 -0
  30. package/dist/kernel/common.d.ts +46 -0
  31. package/dist/kernel/common.js +238 -0
  32. package/dist/kernel/crypto.d.ts +35 -0
  33. package/dist/kernel/crypto.js +54 -0
  34. package/dist/kernel/effects.d.ts +4 -0
  35. package/dist/kernel/effects.js +178 -0
  36. package/dist/kernel/index.d.ts +9 -0
  37. package/dist/kernel/index.js +9 -0
  38. package/dist/kernel/jcs.d.ts +24 -0
  39. package/dist/kernel/jcs.js +93 -0
  40. package/dist/kernel/leases.d.ts +11 -0
  41. package/dist/kernel/leases.js +86 -0
  42. package/dist/kernel/step.d.ts +10 -0
  43. package/dist/kernel/step.js +967 -0
  44. package/dist/kernel/types.d.ts +538 -0
  45. package/dist/kernel/types.js +1 -0
  46. package/dist/kernel/undo.d.ts +4 -0
  47. package/dist/kernel/undo.js +180 -0
  48. package/dist/kernel/validation.d.ts +13 -0
  49. package/dist/kernel/validation.js +307 -0
  50. package/dist/kernel/witness.d.ts +34 -0
  51. package/dist/kernel/witness.js +279 -0
  52. package/dist/mcp/host.d.ts +141 -0
  53. package/dist/mcp/host.js +517 -0
  54. package/dist/mcp/index.d.ts +2 -0
  55. package/dist/mcp/index.js +2 -0
  56. package/dist/mcp/server.d.ts +70 -0
  57. package/dist/mcp/server.js +508 -0
  58. package/dist/runtime/dp1.d.ts +48 -0
  59. package/dist/runtime/dp1.js +229 -0
  60. package/dist/runtime/engine.d.ts +86 -0
  61. package/dist/runtime/engine.js +320 -0
  62. package/dist/runtime/index.d.ts +4 -0
  63. package/dist/runtime/index.js +4 -0
  64. package/dist/runtime/outbox.d.ts +69 -0
  65. package/dist/runtime/outbox.js +238 -0
  66. package/dist/runtime/store.d.ts +204 -0
  67. package/dist/runtime/store.js +746 -0
  68. package/package.json +91 -4
  69. package/presets/exchange-firewall.json +40 -0
  70. package/presets/sdk.json +32 -0
  71. package/presets/solver.json +22 -0
  72. package/presets/vibeops.json +34 -0
  73. package/skills/certal/SKILL.md +49 -0
@@ -0,0 +1,517 @@
1
+ import fs from 'node:fs';
2
+ import http from 'node:http';
3
+ import path from 'node:path';
4
+ import { DatabaseSync } from 'node:sqlite';
5
+ import { computeToolAutonomy, createKeyringSignatureVerifier, hashBinding, hashCanonical, scopeEpochOf, slotKey, } from '../kernel/index.js';
6
+ import { CertalRuntime, OutboxWorker, SQLiteStore } from '../runtime/index.js';
7
+ import { LocalCliApprovalChannel, WebhookApprovalChannel } from '../adapters/approval-channel.js';
8
+ import { CommandTransport, CommandWitness, createCommandPreflight } from '../adapters/commands.js';
9
+ import { FILE_FIELD, HumanFileWatcher } from '../adapters/file-watcher.js';
10
+ import { loadManifest, policyDifference, policyRelaxations } from '../adapters/manifest.js';
11
+ import { COMMAND_MAX_AGE_MS, verifyOperatorCommand } from '../adapters/operator-auth.js';
12
+ /**
13
+ * One Certal host per state directory: the manifest, the SQLite log, the runtime with its single
14
+ * writer, the outbox worker and the operator endpoint. Agents reach it through the MCP server.
15
+ * The operator reaches it through the CLI, which signs every command with the Ed25519 key.
16
+ */
17
+ export const DB_FILE = 'certal.db';
18
+ export const RUNTIME_FILE = 'runtime.json';
19
+ const DEFAULT_HUMAN_ID = 'operator';
20
+ /** A checkpoint is saved after this many new log entries, so a cold start replays a short tail only. */
21
+ const CHECKPOINT_EVERY = 100;
22
+ export class HostBusyError extends Error {
23
+ info;
24
+ constructor(info) {
25
+ super(`another Certal process (pid ${info.pid}) owns this state directory`);
26
+ this.name = 'HostBusyError';
27
+ this.info = info;
28
+ }
29
+ }
30
+ function isAlive(pid) {
31
+ try {
32
+ process.kill(pid, 0);
33
+ return true;
34
+ }
35
+ catch (err) {
36
+ return err.code === 'EPERM';
37
+ }
38
+ }
39
+ /** The process that owns the state directory right now, or null. A stale file is removed. */
40
+ export function readRuntimeInfo(stateDir) {
41
+ const file = path.join(stateDir, RUNTIME_FILE);
42
+ try {
43
+ const info = JSON.parse(fs.readFileSync(file, 'utf8'));
44
+ if (typeof info.pid === 'number' && isAlive(info.pid))
45
+ return info;
46
+ fs.rmSync(file, { force: true });
47
+ }
48
+ catch {
49
+ // No file, or an unreadable one: nobody owns the directory.
50
+ }
51
+ return null;
52
+ }
53
+ /**
54
+ * Takes ownership of the state directory. The file is created exclusively, so of two processes
55
+ * that start at the same moment only one gets through.
56
+ */
57
+ function claimDirectory(stateDir) {
58
+ const owner = readRuntimeInfo(stateDir);
59
+ if (owner)
60
+ throw new HostBusyError(owner);
61
+ const info = { pid: process.pid, operatorPort: 0, startedAtMs: Date.now() };
62
+ try {
63
+ fs.writeFileSync(path.join(stateDir, RUNTIME_FILE), JSON.stringify(info), { mode: 0o600, flag: 'wx' });
64
+ }
65
+ catch (err) {
66
+ if (err.code !== 'EEXIST')
67
+ throw err;
68
+ throw new HostBusyError(readRuntimeInfo(stateDir) ?? info);
69
+ }
70
+ }
71
+ function hooksFor(publicKeys) {
72
+ return { signatureVerifier: createKeyringSignatureVerifier({ ed25519PublicKeysPem: publicKeys }) };
73
+ }
74
+ /** Operator public keys that the database carries, so an audit needs no other file. */
75
+ export function readStoredOperatorKeys(dbPath) {
76
+ const db = new DatabaseSync(dbPath);
77
+ try {
78
+ const exists = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'operator_keys'").get();
79
+ if (!exists)
80
+ return {};
81
+ const keys = {};
82
+ for (const row of db.prepare('SELECT key_id, public_key_pem FROM operator_keys ORDER BY key_id').all()) {
83
+ keys[String(row.key_id)] = String(row.public_key_pem);
84
+ }
85
+ return keys;
86
+ }
87
+ finally {
88
+ db.close();
89
+ }
90
+ }
91
+ /**
92
+ * Records the operator keys on the first start. Later starts must not bring a key that the
93
+ * database does not know: a manifest edit cannot add an approver to a running log.
94
+ */
95
+ function pinOperatorKeys(dbPath, publicKeys) {
96
+ const known = fs.existsSync(dbPath) ? readStoredOperatorKeys(dbPath) : {};
97
+ const db = new DatabaseSync(dbPath);
98
+ try {
99
+ db.exec('CREATE TABLE IF NOT EXISTS operator_keys (key_id TEXT PRIMARY KEY, public_key_pem TEXT NOT NULL)');
100
+ const pinned = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'log_entries'").get() !== undefined || Object.keys(known).length > 0;
101
+ const added = Object.entries(publicKeys).filter(([keyId, pem]) => known[keyId] !== pem).map(([keyId]) => keyId);
102
+ if (pinned && added.length > 0) {
103
+ throw new Error(`The manifest names an operator key that this log did not start with: ${added.join(', ')}. A manifest edit cannot add an approver. Use a new state directory to change the operator keys.`);
104
+ }
105
+ const insert = db.prepare('INSERT OR IGNORE INTO operator_keys (key_id, public_key_pem) VALUES (?, ?)');
106
+ for (const [keyId, pem] of Object.entries(publicKeys))
107
+ insert.run(keyId, pem);
108
+ }
109
+ finally {
110
+ db.close();
111
+ }
112
+ }
113
+ export function describeOps(ops) {
114
+ return ops.slice(0, 20).map((op) => `${op.objectId}.${op.field} ${op.reversibility}${op.externalEffect ? ' +effect' : ''}`);
115
+ }
116
+ export function pendingApprovalsOf(state) {
117
+ const ladder = state.policy.enforceAutonomyLadder;
118
+ return state.activeAttempts
119
+ .filter((a) => a.status === 'VERIFIED' && a.binding !== null && a.approval === null)
120
+ .filter((a) => {
121
+ const tier = computeToolAutonomy(state, a.toolId).tier;
122
+ return a.needsApproval || a.ops.some((o) => o.reversibility === 'IRREVERSIBLE') || (ladder && tier !== 'AUTO');
123
+ })
124
+ .map((a) => {
125
+ const binding = a.binding;
126
+ return {
127
+ attemptId: a.attemptId,
128
+ scopeId: a.scopeId,
129
+ toolId: a.toolId,
130
+ executorId: a.executorId,
131
+ reason: a.approvalReason,
132
+ binding,
133
+ bindingHash: hashBinding(binding.diffHash, binding.scopeHash, binding.inputSnapshotHash),
134
+ diffSummary: describeOps(a.ops),
135
+ };
136
+ });
137
+ }
138
+ export function buildStatus(state, nowMs, toolIds) {
139
+ const tools = [...new Set([...toolIds, ...Object.keys(state.toolClusterStats)])].sort();
140
+ return {
141
+ taskStatus: state.taskStatus,
142
+ pauseReason: state.pauseReason,
143
+ haltReason: state.haltReason,
144
+ serverSeq: state.serverSeq,
145
+ lastEntryHash: state.lastEntryHash,
146
+ scopeEpochs: { ...state.scopeEpochs },
147
+ leases: state.leases
148
+ .filter((l) => l.expiresAtMs > nowMs)
149
+ .map((l) => ({ leaseId: l.leaseId, scopeId: l.scopeId, classId: l.classId, ownerId: l.ownerId, attemptId: l.attemptId, leaseEpoch: l.leaseEpoch, expiresInMs: l.expiresAtMs - nowMs })),
150
+ autonomy: tools.map((toolId) => {
151
+ const a = computeToolAutonomy(state, toolId);
152
+ return { toolId, tier: a.tier, toApproval: `${Math.min(a.cleanClusterCount, 59)}/59`, toAuto: `${Math.min(a.cleanClusterCount, 299)}/299`, violations: a.violationCount };
153
+ }),
154
+ pendingApprovals: pendingApprovalsOf(state),
155
+ };
156
+ }
157
+ /** Reads the state from the log without taking ownership of the state directory. */
158
+ export function readStatus(cwd) {
159
+ const manifest = loadManifest(cwd);
160
+ const dbPath = path.join(manifest.stateDir, DB_FILE);
161
+ const live = readRuntimeInfo(manifest.stateDir) !== null;
162
+ if (!fs.existsSync(dbPath)) {
163
+ const runtime = new CertalRuntime({ store: new SQLiteStore(':memory:') });
164
+ const status = buildStatus(runtime.getState(), Date.now(), Object.keys(manifest.tools));
165
+ runtime.close();
166
+ return { status, manifest, live };
167
+ }
168
+ const store = new SQLiteStore(dbPath);
169
+ try {
170
+ const replayed = store.replay(hooksFor(manifest.operator?.publicKeys ?? {}));
171
+ return { status: buildStatus(replayed.state, Date.now(), Object.keys(manifest.tools)), manifest, live };
172
+ }
173
+ finally {
174
+ store.close();
175
+ }
176
+ }
177
+ export class CertalHost {
178
+ manifest;
179
+ runtime;
180
+ witness;
181
+ agentPort;
182
+ systemPort;
183
+ humanPort;
184
+ outbox;
185
+ channel;
186
+ notified = new Set();
187
+ seenNonces = new Map();
188
+ watcher = null;
189
+ operatorServer = null;
190
+ ownsDirectory = false;
191
+ closed = false;
192
+ checkpointSeq = 0;
193
+ humanOpCounter = 0;
194
+ shutdownRequested = false;
195
+ /** Declared pins that the kernel refused while the task was halted. They are set after a reset. */
196
+ deferredPins = [];
197
+ /** Called after the operator asks the host to stop. */
198
+ onShutdown = null;
199
+ constructor(manifest, runtime) {
200
+ this.manifest = manifest;
201
+ this.runtime = runtime;
202
+ this.witness = new CommandWitness(manifest.witness, manifest.baseDir);
203
+ this.agentPort = runtime.createPort(['Agent']);
204
+ this.systemPort = runtime.createPort(['System']);
205
+ this.humanPort = runtime.createPort(['Human']);
206
+ this.outbox = new OutboxWorker(runtime.getStore(), new CommandTransport(manifest.tools, manifest.baseDir), { getState: () => runtime.getState(), getNowMs: () => runtime.getNowMs(), dispatch: (env) => runtime.dispatch(env) }, { baseBackoffMs: 0, maxBackoffMs: 0, blobStore: runtime.getStore(), preflightCheck: createCommandPreflight(manifest.tools, manifest.baseDir) });
207
+ const keys = manifest.operator?.publicKeys ?? {};
208
+ this.channel = manifest.approvals.channel === 'webhook' && manifest.approvals.url
209
+ ? new WebhookApprovalChannel(manifest.approvals.url, keys)
210
+ : new LocalCliApprovalChannel();
211
+ }
212
+ static async open(options) {
213
+ const manifest = loadManifest(options.cwd);
214
+ fs.mkdirSync(manifest.stateDir, { recursive: true });
215
+ claimDirectory(manifest.stateDir);
216
+ const release = () => fs.rmSync(path.join(manifest.stateDir, RUNTIME_FILE), { force: true });
217
+ const dbPath = path.join(manifest.stateDir, DB_FILE);
218
+ const keys = manifest.operator?.publicKeys ?? {};
219
+ let runtime;
220
+ try {
221
+ pinOperatorKeys(dbPath, keys);
222
+ const store = new SQLiteStore(dbPath);
223
+ try {
224
+ const fresh = store.getLastServerSeq() === 0;
225
+ runtime = new CertalRuntime({ store, hooks: hooksFor(keys), ...(fresh ? { policyOverrides: manifest.policy } : {}) });
226
+ }
227
+ catch (err) {
228
+ store.close();
229
+ throw err;
230
+ }
231
+ }
232
+ catch (err) {
233
+ release();
234
+ throw err;
235
+ }
236
+ const host = new CertalHost(manifest, runtime);
237
+ host.ownsDirectory = true;
238
+ try {
239
+ await host.applyPolicyDrift();
240
+ await host.applyPins();
241
+ await host.outbox.recoverInFlight();
242
+ await host.drainOutbox();
243
+ if (options.serveOperator !== false)
244
+ await host.startOperatorEndpoint();
245
+ if (options.watch ?? manifest.watch)
246
+ host.startWatcher();
247
+ }
248
+ catch (err) {
249
+ host.close();
250
+ throw err;
251
+ }
252
+ return host;
253
+ }
254
+ get humanId() {
255
+ return this.manifest.operator?.humanId ?? DEFAULT_HUMAN_ID;
256
+ }
257
+ humanAuth(humanId = this.humanId) {
258
+ return { origin: { kind: 'Human', actorId: humanId }, roles: ['operator'], authMethod: 'session' };
259
+ }
260
+ /** A manifest that became stricter since the log started is applied. A looser one is refused. */
261
+ async applyPolicyDrift() {
262
+ const current = this.runtime.getState().policy;
263
+ const diff = policyDifference(current, this.manifest.policy);
264
+ if (Object.keys(diff).length === 0)
265
+ return;
266
+ const relaxed = policyRelaxations(current, diff);
267
+ if (relaxed.length > 0) {
268
+ throw new Error(`The manifest relaxes the policy that this log records:\n- ${relaxed.join('\n- ')}\nA manifest edit cannot do that. Use a new state directory to start with a looser policy.`);
269
+ }
270
+ // The manifest is the operator's declaration. The kernel takes a policy update in PAUSED and HALTED only from a human.
271
+ const res = await this.humanPort.submit(`manifest:policy:${hashCanonical('manifest_policy', 1, diff)}:${this.runtime.getState().serverSeq}`, { ...this.humanAuth(), authMethod: 'manifest' }, { kind: 'PolicyUpdated', policy: diff });
272
+ if (!res.logEntry?.applied)
273
+ throw new Error(`The stricter manifest policy was not applied: ${res.decision.reason}`);
274
+ }
275
+ /**
276
+ * Sets every declared pin that the state does not hold yet. Pins are never removed from here.
277
+ * A halted task takes no pin, so such pins are kept aside and set right after the reset.
278
+ * Any other refusal stops the start: the host does not run without a declared pin.
279
+ */
280
+ async applyPins() {
281
+ this.deferredPins = [];
282
+ for (const pin of this.manifest.pins) {
283
+ const wanted = {
284
+ pinId: pin.id,
285
+ kind: pin.kind,
286
+ scopeId: pin.scopeId,
287
+ classId: pin.classId,
288
+ ruleId: pin.rule,
289
+ ownerId: this.humanId,
290
+ ...(pin.costPenaltyMicroUnits !== undefined ? { costPenaltyMicroUnits: pin.costPenaltyMicroUnits } : {}),
291
+ };
292
+ const held = this.runtime.getState().pins.find((p) => p.pinId === pin.id);
293
+ if (held && hashCanonical('pin', 1, held) === hashCanonical('pin', 1, wanted))
294
+ continue;
295
+ const res = await this.humanPort.submit(`manifest:pin:${hashCanonical('pin', 1, wanted)}:${this.runtime.getState().serverSeq}`, { ...this.humanAuth(), authMethod: 'manifest' }, { kind: 'SetPin', pin: wanted });
296
+ const set = this.runtime.getState().pins.some((p) => p.pinId === pin.id && hashCanonical('pin', 1, p) === hashCanonical('pin', 1, wanted));
297
+ if (set)
298
+ continue;
299
+ if (this.runtime.getState().taskStatus === 'HALTED')
300
+ this.deferredPins.push(pin.id);
301
+ else
302
+ throw new Error(`The declared pin "${pin.id}" was not set: ${res.decision.reason}`);
303
+ }
304
+ if (this.deferredPins.length > 0) {
305
+ process.stderr.write(`certal: the task is halted, so these declared pins wait for the reset: ${this.deferredPins.join(', ')}\n`);
306
+ }
307
+ }
308
+ async drainOutbox() {
309
+ for (let guard = 0; guard < 10; guard += 1) {
310
+ if ((await this.outbox.processOnce()) === 0)
311
+ break;
312
+ }
313
+ this.checkpoint(false);
314
+ }
315
+ checkpoint(force) {
316
+ const seq = this.runtime.getState().serverSeq;
317
+ if (seq === this.checkpointSeq || (!force && seq - this.checkpointSeq < CHECKPOINT_EVERY))
318
+ return;
319
+ this.runtime.saveCheckpoint();
320
+ this.checkpointSeq = seq;
321
+ }
322
+ status() {
323
+ return buildStatus(this.runtime.getState(), this.runtime.getNowMs(), Object.keys(this.manifest.tools));
324
+ }
325
+ /** Announces a pending approval once per attempt. A token that the channel returns is granted at once. */
326
+ async announceApproval(attemptId) {
327
+ if (this.notified.has(attemptId))
328
+ return;
329
+ const pending = pendingApprovalsOf(this.runtime.getState()).find((p) => p.attemptId === attemptId);
330
+ if (!pending)
331
+ return;
332
+ this.notified.add(attemptId);
333
+ const notice = {
334
+ attemptId,
335
+ scopeId: pending.scopeId,
336
+ toolId: pending.toolId,
337
+ reason: pending.reason,
338
+ binding: pending.binding,
339
+ bindingHash: pending.bindingHash,
340
+ diffSummary: pending.diffSummary,
341
+ expiresAtMs: this.runtime.getNowMs() + 15 * 60_000,
342
+ };
343
+ const token = await this.channel.notify(notice);
344
+ if (token)
345
+ await this.grant(token);
346
+ }
347
+ grant(token) {
348
+ return this.humanPort.submit(`grant:${token.approvalId}`, this.humanAuth(token.humanId), { kind: 'GrantApproval', approval: token });
349
+ }
350
+ humanOp(prefix) {
351
+ // The counter keeps two events of the same millisecond apart. The process id keeps two runs apart.
352
+ this.humanOpCounter += 1;
353
+ return `${prefix}:${this.runtime.getState().serverSeq}:${this.runtime.getNowMs()}:${process.pid}-${this.humanOpCounter}`;
354
+ }
355
+ /** Runs one operator command. The caller has already established that a human issued it. */
356
+ async operatorCommand(command, args) {
357
+ const text = (key) => (typeof args[key] === 'string' ? args[key] : '');
358
+ const reply = (res, data) => ({
359
+ // A human halt is applied and answers HALT, so success is read from the log entry.
360
+ ok: res.logEntry ? res.logEntry.applied : res.decision.code === 'ALLOW',
361
+ decision: res.decision.code,
362
+ reason: res.decision.reason,
363
+ ...(data !== undefined ? { data } : {}),
364
+ });
365
+ switch (command) {
366
+ case 'status':
367
+ return { ok: true, data: this.status() };
368
+ case 'grant': {
369
+ const token = args.token;
370
+ if (!token || typeof token.approvalId !== 'string' || typeof token.humanId !== 'string')
371
+ return { ok: false, reason: 'BAD_TOKEN' };
372
+ return reply(await this.grant(token));
373
+ }
374
+ case 'undo': {
375
+ const batch = this.runtime.getState().batches.find((b) => b.batchId === text('batchId'));
376
+ if (!batch)
377
+ return { ok: false, decision: 'REJECT', reason: 'BATCH_NOT_FOUND' };
378
+ const res = await this.humanPort.submit(this.humanOp('undo'), this.humanAuth(), {
379
+ kind: 'OriginUndo',
380
+ batchId: batch.batchId,
381
+ scopeId: batch.scopeId,
382
+ reason: text('reason') || 'operator undo',
383
+ ...(typeof args.compensationPolicy === 'string' ? { compensationPolicy: args.compensationPolicy } : {}),
384
+ });
385
+ await this.drainOutbox();
386
+ return reply(res, res.undoReport ?? null);
387
+ }
388
+ case 'halt':
389
+ return reply(await this.humanPort.submit(this.humanOp('halt'), this.humanAuth(), { kind: 'HumanHalt', scopeId: text('scopeId'), reason: text('reason') }));
390
+ case 'reset': {
391
+ const res = await this.humanPort.submit(this.humanOp('reset'), this.humanAuth(), { kind: 'HumanReset', scopeId: text('scopeId'), reason: text('reason') });
392
+ // Pins that a halted task refused are set before any agent gets a turn.
393
+ if (res.logEntry?.applied && this.deferredPins.length > 0)
394
+ await this.applyPins();
395
+ return reply(res);
396
+ }
397
+ case 'resume':
398
+ return reply(await this.humanPort.submit(this.humanOp('resume'), this.humanAuth(), { kind: 'HumanResume', scopeId: text('scopeId') }));
399
+ case 'shutdown':
400
+ // The endpoint stops the host only after this answer has left, so the caller always gets it.
401
+ this.shutdownRequested = true;
402
+ return { ok: true };
403
+ default:
404
+ return { ok: false, reason: 'UNKNOWN_COMMAND' };
405
+ }
406
+ }
407
+ startWatcher() {
408
+ const classOf = new Map(this.manifest.scopes.map((s) => [s.id, s.classId]));
409
+ this.watcher = new HumanFileWatcher({
410
+ baseDir: this.manifest.baseDir,
411
+ scopes: this.manifest.scopes,
412
+ ignore: ['.git', 'node_modules', path.relative(this.manifest.baseDir, this.manifest.stateDir).split(path.sep).join('/') || '.certal'],
413
+ sink: {
414
+ currentHash: (scope, relativePath) => this.runtime.getState().slots[slotKey(scope.id, classOf.get(scope.id) ?? scope.classId, relativePath, FILE_FIELD)]?.value,
415
+ humanEdit: async (scope, relativePath, hash) => {
416
+ await this.humanPort.submit(this.humanOp(`watch:${relativePath}`), this.humanAuth(), {
417
+ kind: 'HumanEdit',
418
+ scopeId: scope.id,
419
+ classId: scope.classId,
420
+ objectId: relativePath,
421
+ field: FILE_FIELD,
422
+ value: hash,
423
+ });
424
+ },
425
+ },
426
+ });
427
+ this.watcher.start();
428
+ }
429
+ /** Resolves when the file watcher has handled every change seen so far. */
430
+ async watcherSettled() {
431
+ await this.watcher?.settled();
432
+ }
433
+ acceptSigned(signed) {
434
+ const keys = this.manifest.operator?.publicKeys ?? {};
435
+ if (!signed || typeof signed !== 'object' || !signed.body || typeof signed.body.command !== 'string')
436
+ return 'BAD_REQUEST';
437
+ if (!verifyOperatorCommand(signed, keys))
438
+ return 'BAD_SIGNATURE';
439
+ const now = Date.now();
440
+ if (Math.abs(now - signed.body.issuedAtMs) > COMMAND_MAX_AGE_MS)
441
+ return 'STALE_COMMAND';
442
+ for (const [nonce, at] of this.seenNonces)
443
+ if (now - at > 2 * COMMAND_MAX_AGE_MS)
444
+ this.seenNonces.delete(nonce);
445
+ if (this.seenNonces.has(signed.body.nonce))
446
+ return 'REPLAYED_COMMAND';
447
+ this.seenNonces.set(signed.body.nonce, now);
448
+ return null;
449
+ }
450
+ startOperatorEndpoint() {
451
+ const server = http.createServer((req, res) => {
452
+ const send = (status, body) => {
453
+ res.writeHead(status, { 'content-type': 'application/json', connection: 'close' });
454
+ res.end(JSON.stringify(body), () => {
455
+ if (this.shutdownRequested)
456
+ setImmediate(() => this.onShutdown?.());
457
+ });
458
+ };
459
+ if (req.method !== 'POST' || req.url !== '/operator')
460
+ return send(404, { ok: false, reason: 'NOT_FOUND' });
461
+ const chunks = [];
462
+ let size = 0;
463
+ req.on('data', (chunk) => {
464
+ size += chunk.length;
465
+ if (size > 1_000_000)
466
+ req.destroy();
467
+ else
468
+ chunks.push(chunk);
469
+ });
470
+ req.on('end', () => {
471
+ let signed;
472
+ try {
473
+ signed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
474
+ }
475
+ catch {
476
+ return send(400, { ok: false, reason: 'BAD_JSON' });
477
+ }
478
+ const refusal = this.acceptSigned(signed);
479
+ if (refusal)
480
+ return send(403, { ok: false, reason: refusal });
481
+ this.operatorCommand(signed.body.command, (signed.body.args ?? {}))
482
+ .then((out) => send(200, out))
483
+ .catch((err) => send(500, { ok: false, reason: String(err.message ?? err) }));
484
+ });
485
+ });
486
+ return new Promise((resolve, reject) => {
487
+ server.once('error', reject);
488
+ server.listen(0, '127.0.0.1', () => {
489
+ const address = server.address();
490
+ const port = typeof address === 'object' && address ? address.port : 0;
491
+ const info = { pid: process.pid, operatorPort: port, startedAtMs: Date.now() };
492
+ fs.writeFileSync(path.join(this.manifest.stateDir, RUNTIME_FILE), JSON.stringify(info), { mode: 0o600 });
493
+ this.operatorServer = server;
494
+ resolve();
495
+ });
496
+ });
497
+ }
498
+ scopeEpoch(scopeId) {
499
+ return scopeEpochOf(this.runtime.getState(), scopeId);
500
+ }
501
+ close() {
502
+ if (this.closed)
503
+ return;
504
+ this.closed = true;
505
+ this.watcher?.stop();
506
+ this.operatorServer?.close();
507
+ this.operatorServer?.closeAllConnections();
508
+ if (this.ownsDirectory)
509
+ fs.rmSync(path.join(this.manifest.stateDir, RUNTIME_FILE), { force: true });
510
+ try {
511
+ this.checkpoint(true);
512
+ }
513
+ finally {
514
+ this.runtime.close();
515
+ }
516
+ }
517
+ }
@@ -0,0 +1,2 @@
1
+ export * from './host.ts';
2
+ export * from './server.ts';
@@ -0,0 +1,2 @@
1
+ export * from './host.js';
2
+ export * from './server.js';
@@ -0,0 +1,70 @@
1
+ import http from 'node:http';
2
+ import type { Decision } from '../kernel/index.ts';
3
+ import type { CertalHost } from './host.ts';
4
+ /**
5
+ * MCP gate for agents. The tool surface is narrow on purpose: an agent can take and release a
6
+ * lease, propose a batch, finalize it and read the status. Approvals, undo, halt, reset and pin
7
+ * changes are not tools. They belong to the operator and go through the signed CLI channel.
8
+ */
9
+ /** MCP protocol versions that this server speaks, newest first. */
10
+ export declare const SUPPORTED_PROTOCOL_VERSIONS: readonly string[];
11
+ export declare const PROTOCOL_VERSION: string;
12
+ /** Largest message that a transport accepts. */
13
+ export declare const MAX_MESSAGE_BYTES: number;
14
+ export declare const AGENT_ID_PATTERN: RegExp;
15
+ /** Short answer for an agent: what the kernel decided and what the agent may do next. */
16
+ export interface AgentReply {
17
+ readonly decision: Decision['code'];
18
+ readonly reason: string;
19
+ readonly scopeId: string;
20
+ readonly scopeEpoch: number;
21
+ readonly nextLegalAction: string;
22
+ readonly retryable: boolean;
23
+ readonly attemptId?: string;
24
+ readonly batchId?: string;
25
+ }
26
+ interface ToolDefinition {
27
+ readonly name: string;
28
+ readonly description: string;
29
+ readonly inputSchema: Record<string, unknown>;
30
+ }
31
+ export declare const TOOLS: readonly ToolDefinition[];
32
+ type Args = Record<string, unknown>;
33
+ export declare class McpGateway {
34
+ private readonly host;
35
+ private counter;
36
+ constructor(host: CertalHost);
37
+ private get state();
38
+ private auth;
39
+ private reply;
40
+ private fromStep;
41
+ private classOf;
42
+ leaseAcquire(agentId: string, args: Args): Promise<AgentReply>;
43
+ leaseRelease(agentId: string, args: Args): Promise<AgentReply>;
44
+ proposeBatch(agentId: string, args: Args): Promise<AgentReply>;
45
+ private needsApproval;
46
+ finalizeBatch(agentId: string, args: Args): Promise<AgentReply>;
47
+ call(agentId: string, name: string, args: Args): Promise<unknown>;
48
+ }
49
+ export declare function packageVersion(): string;
50
+ /** Handles one JSON-RPC message. Returns null for a notification. */
51
+ export declare function handleRpc(gateway: McpGateway, agentId: string, message: unknown): Promise<unknown | null>;
52
+ /**
53
+ * Serves MCP over stdin and stdout, one JSON message per line. One process is one agent.
54
+ * The size limit is applied to the raw input before a line is complete, so a line without an end
55
+ * cannot fill the memory. The rest of an oversized line is dropped.
56
+ */
57
+ export declare function serveStdio(gateway: McpGateway, agentId: string, input: NodeJS.ReadableStream, output: NodeJS.WritableStream): Promise<void>;
58
+ export interface HttpMcpServer {
59
+ readonly server: http.Server;
60
+ readonly port: number;
61
+ /** One bearer token per agent id. */
62
+ readonly tokens: Readonly<Record<string, string>>;
63
+ }
64
+ /**
65
+ * Serves MCP over HTTP on a local address. Every agent has a bearer token of its own, created at
66
+ * start, and the token alone decides who the caller is. A request whose `x-certal-agent` header
67
+ * names another agent is refused, so one agent cannot act as another.
68
+ */
69
+ export declare function serveHttp(gateway: McpGateway, listenHost: string, listenPort: number, agents?: readonly string[]): Promise<HttpMcpServer>;
70
+ export {};