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,229 @@
1
+ import { hashCanonical, jcs } from '../kernel/jcs.js';
2
+ /**
3
+ * Narrow pattern for secret keys at the ingress boundary. It keeps legitimate fields
4
+ * such as designTokens, tokenBudget, maxTokens, fencingToken and tokenizer.
5
+ */
6
+ const SECRET_KEY_PATTERN = /^(?:api[-_]?key|.*[-_]api[-_]?key|.*secret.*|client[-_]?secret|password|passwd|private[-_]?key|.*[-_]private[-_]?key|authorization|bearer|credential|credentials|access[-_]?token|auth[-_]?token|refresh[-_]?token|id[-_]?token|session[-_]?token|api[-_]?token)$/i;
7
+ const SECRET_VALUE_PATTERNS = [
8
+ /Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi,
9
+ /sk-[A-Za-z0-9]{16,}/g,
10
+ /ghp_[A-Za-z0-9]{20,}/g,
11
+ /AKIA[0-9A-Z]{16}/g,
12
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
13
+ ];
14
+ export function isBlobPointer(v) {
15
+ return (typeof v === 'object' &&
16
+ v !== null &&
17
+ v.__certalBlobRef === true &&
18
+ typeof v.blobHash === 'string' &&
19
+ typeof v.byteSize === 'number');
20
+ }
21
+ function redactString(input) {
22
+ let current = input;
23
+ let count = 0;
24
+ for (const pattern of SECRET_VALUE_PATTERNS) {
25
+ const regex = new RegExp(pattern.source, pattern.flags);
26
+ current = current.replace(regex, () => {
27
+ count += 1;
28
+ return '[REDACTED]';
29
+ });
30
+ }
31
+ return { value: current, count };
32
+ }
33
+ function redactRecursive(value, keyHint) {
34
+ if (keyHint && SECRET_KEY_PATTERN.test(keyHint)) {
35
+ if (value === undefined)
36
+ return { value: undefined, count: 0 };
37
+ return { value: '[REDACTED]', count: 1 };
38
+ }
39
+ if (value === null ||
40
+ typeof value === 'boolean' ||
41
+ typeof value === 'number' ||
42
+ typeof value === 'bigint') {
43
+ return { value, count: 0 };
44
+ }
45
+ if (typeof value === 'string') {
46
+ return redactString(value);
47
+ }
48
+ if (Array.isArray(value)) {
49
+ let count = 0;
50
+ const out = [];
51
+ for (let i = 0; i < value.length; i += 1) {
52
+ const res = redactRecursive(value[i]);
53
+ count += res.count;
54
+ out.push(res.value);
55
+ }
56
+ return { value: out, count };
57
+ }
58
+ if (typeof value === 'object') {
59
+ let count = 0;
60
+ const record = value;
61
+ const out = {};
62
+ for (const key of Object.keys(record)) {
63
+ const prop = record[key];
64
+ if (prop === undefined)
65
+ continue;
66
+ const res = redactRecursive(prop, key);
67
+ count += res.count;
68
+ out[key] = res.value;
69
+ }
70
+ return { value: out, count };
71
+ }
72
+ return { value, count: 0 };
73
+ }
74
+ /**
75
+ * Deterministic redaction of secrets and PII at the ingress boundary, before canonicalization and storage.
76
+ */
77
+ export function redactSecrets(payload) {
78
+ const res = redactRecursive(payload);
79
+ return {
80
+ sanitized: res.value,
81
+ redactedCount: res.count,
82
+ };
83
+ }
84
+ /**
85
+ * Enforces the hard event size limit in bytes before the event enters the log chain.
86
+ */
87
+ export function assertEventSizeLimit(payload, maxBytes = 65_536) {
88
+ const serialized = jcs(payload);
89
+ const byteLength = Buffer.byteLength(serialized, 'utf8');
90
+ if (byteLength > maxBytes) {
91
+ throw new Error(`EVENT_SIZE_LIMIT_EXCEEDED: ${byteLength} > ${maxBytes}`);
92
+ }
93
+ return byteLength;
94
+ }
95
+ function maybeBufferField(val, thresholdBytes, pending) {
96
+ if (val === undefined || val === null)
97
+ return val;
98
+ const serialized = jcs(val);
99
+ const byteSize = Buffer.byteLength(serialized, 'utf8');
100
+ if (byteSize <= thresholdBytes) {
101
+ return val;
102
+ }
103
+ const blobHash = hashCanonical('blob', 1, val);
104
+ if (!pending.some((b) => b.blobHash === blobHash)) {
105
+ pending.push({ blobHash, byteSize, payloadJson: serialized });
106
+ }
107
+ const ptr = { __certalBlobRef: true, blobHash, byteSize };
108
+ return ptr;
109
+ }
110
+ function offloadHeavyFields(event, fieldOffloadThresholdBytes) {
111
+ const pending = [];
112
+ if (event.kind === 'SubmitBatch') {
113
+ const ops = event.ops.map((op) => {
114
+ const beforeValue = maybeBufferField(op.beforeValue, fieldOffloadThresholdBytes, pending);
115
+ const afterValue = maybeBufferField(op.afterValue, fieldOffloadThresholdBytes, pending);
116
+ const externalEffect = op.externalEffect
117
+ ? {
118
+ ...op.externalEffect,
119
+ actionPayload: maybeBufferField(op.externalEffect.actionPayload, fieldOffloadThresholdBytes, pending),
120
+ ...(op.externalEffect.inversePayload !== undefined
121
+ ? {
122
+ inversePayload: maybeBufferField(op.externalEffect.inversePayload, fieldOffloadThresholdBytes, pending),
123
+ }
124
+ : {}),
125
+ }
126
+ : undefined;
127
+ return {
128
+ ...op,
129
+ beforeValue,
130
+ afterValue,
131
+ ...(externalEffect !== undefined ? { externalEffect } : {}),
132
+ };
133
+ });
134
+ const firstBlob = pending[0];
135
+ return {
136
+ pendingBlobs: pending,
137
+ event: {
138
+ ...event,
139
+ ops,
140
+ ...(firstBlob !== undefined
141
+ ? { blobRef: { blobHash: firstBlob.blobHash, byteSize: firstBlob.byteSize } }
142
+ : {}),
143
+ },
144
+ };
145
+ }
146
+ if (event.kind === 'HumanEdit') {
147
+ const value = maybeBufferField(event.value, fieldOffloadThresholdBytes, pending);
148
+ return {
149
+ pendingBlobs: pending,
150
+ event: {
151
+ ...event,
152
+ value,
153
+ },
154
+ };
155
+ }
156
+ return { pendingBlobs: [], event };
157
+ }
158
+ /**
159
+ * Restores the original value behind a __certalBlobRef pointer from the BlobStore.
160
+ */
161
+ export function hydrateBlobValue(value, blobStore) {
162
+ if (isBlobPointer(value)) {
163
+ const loaded = blobStore.getBlob(value.blobHash);
164
+ return loaded !== null ? loaded : value;
165
+ }
166
+ return value;
167
+ }
168
+ /**
169
+ * Strict variant: restores the value behind a __certalBlobRef pointer and reports a missing blob.
170
+ */
171
+ export function hydrateBlobValueStrict(value, blobStore) {
172
+ if (isBlobPointer(value)) {
173
+ const loaded = blobStore.getBlob(value.blobHash);
174
+ if (loaded === null) {
175
+ return { ok: false, missingBlobHash: value.blobHash };
176
+ }
177
+ return { ok: true, value: loaded };
178
+ }
179
+ return { ok: true, value };
180
+ }
181
+ /**
182
+ * Ingress boundary: redacts secrets, buffers the offload of large single fields (nothing is written
183
+ * before step() accepts the event) and checks the hard event size limit.
184
+ */
185
+ export function prepareDp1Envelope(rawEnvelope, maxInlinePayloadBytes, maxEventBytes, fieldOffloadThresholdBytes = 4_096) {
186
+ let redactedEvent;
187
+ let redactedCount;
188
+ let bytes;
189
+ try {
190
+ const red = redactSecrets(rawEnvelope.event);
191
+ redactedEvent = red.sanitized;
192
+ redactedCount = red.redactedCount;
193
+ bytes = Buffer.byteLength(jcs(redactedEvent), 'utf8');
194
+ }
195
+ catch (err) {
196
+ const msg = err instanceof Error ? err.message : '';
197
+ if (msg.startsWith('FLOAT_NOT_ALLOWED_IN_HASH')) {
198
+ return { ok: false, reason: 'FLOAT_NOT_ALLOWED' };
199
+ }
200
+ return { ok: false, reason: 'SCHEMA_INVALID' };
201
+ }
202
+ let finalEvent = redactedEvent;
203
+ let pendingBlobs = [];
204
+ if (bytes > maxInlinePayloadBytes) {
205
+ const offloaded = offloadHeavyFields(redactedEvent, fieldOffloadThresholdBytes);
206
+ finalEvent = offloaded.event;
207
+ pendingBlobs = offloaded.pendingBlobs;
208
+ try {
209
+ bytes = Buffer.byteLength(jcs(finalEvent), 'utf8');
210
+ }
211
+ catch {
212
+ return { ok: false, reason: 'SCHEMA_INVALID' };
213
+ }
214
+ }
215
+ if (bytes > maxEventBytes) {
216
+ return { ok: false, reason: 'EVENT_SIZE_LIMIT_EXCEEDED' };
217
+ }
218
+ const envelope = {
219
+ ...rawEnvelope,
220
+ event: finalEvent,
221
+ ...(redactedCount > 0 ? { dp1Meta: { redactedCount } } : {}),
222
+ };
223
+ return {
224
+ ok: true,
225
+ envelope,
226
+ redactedCount,
227
+ pendingBlobs,
228
+ };
229
+ }
@@ -0,0 +1,86 @@
1
+ import { createInitialState } from '../kernel/index.ts';
2
+ import type { CheckpointSnapshot, DeterministicHooks, EventEnvelope, KernelEvent, KernelState, Origin, PolicyConfig, StepResult } from '../kernel/index.ts';
3
+ import type { UnifiedStore } from './store.ts';
4
+ export interface CertalRuntimeOptions {
5
+ readonly store: UnifiedStore;
6
+ readonly policyOverrides?: Partial<PolicyConfig>;
7
+ readonly hooks?: DeterministicHooks;
8
+ readonly clock?: () => number;
9
+ readonly maxInlinePayloadBytes?: number;
10
+ readonly fieldOffloadThresholdBytes?: number;
11
+ readonly haltRejectionAggThreshold?: number;
12
+ }
13
+ /**
14
+ * Runtime port restricted to selected origin kinds.
15
+ * A component that holds an `Agent` port cannot send a human or system event through it.
16
+ */
17
+ /** opId of the log entry that records the starting policy. */
18
+ export declare const GENESIS_POLICY_OP_ID = "genesis:policy";
19
+ export interface RuntimePort {
20
+ readonly allowedOrigins: readonly Origin['kind'][];
21
+ submit(opId: string, auth: EventEnvelope['auth'], event: KernelEvent): Promise<StepResult>;
22
+ getState(): KernelState;
23
+ getNowMs(): number;
24
+ }
25
+ export interface RuntimeMetrics {
26
+ readonly humanDispatches: number;
27
+ readonly agentDispatches: number;
28
+ readonly aggregatedHaltDrops: number;
29
+ readonly offloadedBlobs: number;
30
+ }
31
+ /**
32
+ * Certal runtime layer:
33
+ * - a single write loop (one SQLite WAL writer),
34
+ * - a human priority lane that does not starve the event loop,
35
+ * - a monotonic clock clamp,
36
+ * - secret redaction before the log, with buffered per-field offload to the BlobStore,
37
+ * - durable op_index and spent_approvals indexes in the store,
38
+ * - aggregation of repeated rejections while HALTED.
39
+ */
40
+ export declare class CertalRuntime {
41
+ private readonly store;
42
+ private readonly hooks;
43
+ private readonly clock;
44
+ private readonly maxInlinePayloadBytes;
45
+ private readonly fieldOffloadThresholdBytes;
46
+ private readonly haltRejectionAggThreshold;
47
+ private state;
48
+ private lastPersistedNowMs;
49
+ private readonly humanQueue;
50
+ private readonly agentQueue;
51
+ private draining;
52
+ private suppressedHaltedCount;
53
+ private metrics;
54
+ constructor(options: CertalRuntimeOptions);
55
+ /**
56
+ * Makes the log self-contained. On an empty store, policy overrides become the first log entry:
57
+ * a PolicyUpdated event from the system. On a store that already has a log, the overrides must
58
+ * match that first entry, otherwise the start fails with GENESIS_POLICY_MISMATCH.
59
+ */
60
+ private applyGenesisPolicy;
61
+ getState(): KernelState;
62
+ getStore(): UnifiedStore;
63
+ getStateHash(): string;
64
+ getMetrics(): RuntimeMetrics;
65
+ /**
66
+ * Reads a slot value and resolves a __certalBlobRef pointer from the BlobStore when present.
67
+ */
68
+ readHydratedSlot(scopeId: string, classId: string, objectId: string, field: string): unknown;
69
+ /**
70
+ * Monotonic clock clamp: time never goes back relative to the persisted state.
71
+ */
72
+ getNowMs(): number;
73
+ saveCheckpoint(): CheckpointSnapshot;
74
+ dispatch(envelope: EventEnvelope, serverTime?: boolean): Promise<StepResult>;
75
+ /**
76
+ * Creates a port restricted to the given origin kinds. The port rejects any other origin
77
+ * before the queue and before the log, with reason PORT_ORIGIN_FORBIDDEN.
78
+ */
79
+ createPort(allowedOrigins: readonly Origin['kind'][]): RuntimePort;
80
+ submit(opId: string, auth: EventEnvelope['auth'], event: KernelEvent, explicitNowMs?: number): Promise<StepResult>;
81
+ private scheduleDrain;
82
+ private drainOneTick;
83
+ private processSingle;
84
+ close(): void;
85
+ }
86
+ export { createInitialState };
@@ -0,0 +1,320 @@
1
+ import { HASH_ALG, computeStateHash, createInitialState, hashCanonical, slotKey, step, } from '../kernel/index.js';
2
+ import { hydrateBlobValue, prepareDp1Envelope } from './dp1.js';
3
+ /**
4
+ * Runtime port restricted to selected origin kinds.
5
+ * A component that holds an `Agent` port cannot send a human or system event through it.
6
+ */
7
+ /** opId of the log entry that records the starting policy. */
8
+ export const GENESIS_POLICY_OP_ID = 'genesis:policy';
9
+ /**
10
+ * Certal runtime layer:
11
+ * - a single write loop (one SQLite WAL writer),
12
+ * - a human priority lane that does not starve the event loop,
13
+ * - a monotonic clock clamp,
14
+ * - secret redaction before the log, with buffered per-field offload to the BlobStore,
15
+ * - durable op_index and spent_approvals indexes in the store,
16
+ * - aggregation of repeated rejections while HALTED.
17
+ */
18
+ export class CertalRuntime {
19
+ store;
20
+ hooks;
21
+ clock;
22
+ maxInlinePayloadBytes;
23
+ fieldOffloadThresholdBytes;
24
+ haltRejectionAggThreshold;
25
+ state;
26
+ lastPersistedNowMs;
27
+ humanQueue = [];
28
+ agentQueue = [];
29
+ draining = false;
30
+ suppressedHaltedCount = 0;
31
+ metrics = {
32
+ humanDispatches: 0,
33
+ agentDispatches: 0,
34
+ aggregatedHaltDrops: 0,
35
+ offloadedBlobs: 0,
36
+ };
37
+ constructor(options) {
38
+ this.store = options.store;
39
+ this.hooks = {
40
+ ...options.hooks,
41
+ lookupOpId: (opId) => this.store.lookupOpId(opId),
42
+ isApprovalSpent: (approvalId) => this.store.isApprovalSpent(approvalId),
43
+ lookupClusterOutcome: (toolId, clusterId) => this.store.lookupClusterOutcome(toolId, clusterId),
44
+ };
45
+ this.clock = options.clock ?? (() => Date.now());
46
+ this.maxInlinePayloadBytes = options.maxInlinePayloadBytes ?? 60_000;
47
+ this.fieldOffloadThresholdBytes = options.fieldOffloadThresholdBytes ?? 4_096;
48
+ this.haltRejectionAggThreshold = options.haltRejectionAggThreshold ?? 10;
49
+ const replayed = this.store.replay(options.hooks);
50
+ this.state = replayed.state;
51
+ this.lastPersistedNowMs = Math.max(this.store.getLastPersistedNowMs(), this.state.lastNowMs);
52
+ this.applyGenesisPolicy(options.policyOverrides);
53
+ }
54
+ /**
55
+ * Makes the log self-contained. On an empty store, policy overrides become the first log entry:
56
+ * a PolicyUpdated event from the system. On a store that already has a log, the overrides must
57
+ * match that first entry, otherwise the start fails with GENESIS_POLICY_MISMATCH.
58
+ */
59
+ applyGenesisPolicy(overrides) {
60
+ if (overrides === undefined || Object.keys(overrides).length === 0)
61
+ return;
62
+ const policy = {
63
+ ...overrides,
64
+ ...(overrides.resourcePoolCapacity !== undefined
65
+ ? { resourcePoolCapacity: { ...this.state.policy.resourcePoolCapacity, ...overrides.resourcePoolCapacity } }
66
+ : {}),
67
+ };
68
+ const event = { kind: 'PolicyUpdated', policy };
69
+ const payloadHash = hashCanonical('event_payload', 1, event);
70
+ if (this.store.getLastServerSeq() > 0) {
71
+ const genesis = this.store.lookupOpId(GENESIS_POLICY_OP_ID);
72
+ if (!genesis || genesis.payloadHash !== payloadHash) {
73
+ throw new Error('GENESIS_POLICY_MISMATCH: the policy overrides differ from the policy this log started with');
74
+ }
75
+ return;
76
+ }
77
+ const nowMs = this.getNowMs();
78
+ const envelope = {
79
+ opId: GENESIS_POLICY_OP_ID,
80
+ nowMs,
81
+ auth: { origin: { kind: 'System', actorId: 'certal-runtime' }, roles: ['system'], authMethod: 'internal' },
82
+ event,
83
+ };
84
+ const result = step(this.state, envelope, this.hooks);
85
+ if (result.logEntry === null || !result.logEntry.applied) {
86
+ throw new Error(`GENESIS_POLICY_REJECTED: ${result.decision.reason}`);
87
+ }
88
+ this.store.commitStep(result.logEntry, envelope, result.intents, nowMs);
89
+ this.state = result.state;
90
+ }
91
+ getState() {
92
+ return this.state;
93
+ }
94
+ getStore() {
95
+ return this.store;
96
+ }
97
+ getStateHash() {
98
+ return computeStateHash(this.state);
99
+ }
100
+ getMetrics() {
101
+ return this.metrics;
102
+ }
103
+ /**
104
+ * Reads a slot value and resolves a __certalBlobRef pointer from the BlobStore when present.
105
+ */
106
+ readHydratedSlot(scopeId, classId, objectId, field) {
107
+ const slot = this.state.slots[slotKey(scopeId, classId, objectId, field)];
108
+ if (!slot)
109
+ return undefined;
110
+ return hydrateBlobValue(slot.value, this.store);
111
+ }
112
+ /**
113
+ * Monotonic clock clamp: time never goes back relative to the persisted state.
114
+ */
115
+ getNowMs() {
116
+ const raw = Math.trunc(this.clock());
117
+ const effective = Math.max(raw, this.lastPersistedNowMs);
118
+ this.lastPersistedNowMs = effective;
119
+ return effective;
120
+ }
121
+ saveCheckpoint() {
122
+ const snapshot = {
123
+ schemaVersion: 1,
124
+ hashAlg: HASH_ALG,
125
+ serverSeq: this.state.serverSeq,
126
+ stateHash: computeStateHash(this.state),
127
+ state: this.state,
128
+ createdAtMs: this.getNowMs(),
129
+ };
130
+ this.store.saveCheckpoint(snapshot);
131
+ return snapshot;
132
+ }
133
+ dispatch(envelope, serverTime = false) {
134
+ return new Promise((resolve, reject) => {
135
+ const task = { envelope, serverTime, resolve, reject };
136
+ if (envelope.auth.origin.kind === 'Human') {
137
+ this.humanQueue.push(task);
138
+ }
139
+ else {
140
+ this.agentQueue.push(task);
141
+ }
142
+ this.scheduleDrain();
143
+ });
144
+ }
145
+ /**
146
+ * Creates a port restricted to the given origin kinds. The port rejects any other origin
147
+ * before the queue and before the log, with reason PORT_ORIGIN_FORBIDDEN.
148
+ */
149
+ createPort(allowedOrigins) {
150
+ const allowed = new Set(allowedOrigins);
151
+ return Object.freeze({
152
+ allowedOrigins: Object.freeze([...allowedOrigins]),
153
+ submit: (opId, auth, event) => {
154
+ const kind = auth?.origin?.kind;
155
+ if (typeof kind !== 'string' || !allowed.has(kind)) {
156
+ return Promise.resolve({
157
+ state: this.state,
158
+ decision: { code: 'REJECT', reason: 'PORT_ORIGIN_FORBIDDEN' },
159
+ intents: [],
160
+ logEntry: null,
161
+ idempotentReplay: false,
162
+ schemaRejected: true,
163
+ });
164
+ }
165
+ return this.submit(opId, auth, event);
166
+ },
167
+ getState: () => this.state,
168
+ getNowMs: () => this.getNowMs(),
169
+ });
170
+ }
171
+ submit(opId, auth, event, explicitNowMs) {
172
+ const nowMs = explicitNowMs ?? this.getNowMs();
173
+ return this.dispatch({ opId, nowMs, auth, event }, explicitNowMs === undefined);
174
+ }
175
+ scheduleDrain(yieldMacrotask = false) {
176
+ if (this.draining)
177
+ return;
178
+ this.draining = true;
179
+ const run = () => {
180
+ this.drainOneTick();
181
+ };
182
+ if (yieldMacrotask) {
183
+ setImmediate(run);
184
+ }
185
+ else {
186
+ queueMicrotask(run);
187
+ }
188
+ }
189
+ drainOneTick() {
190
+ let processedAgent = false;
191
+ try {
192
+ while (this.humanQueue.length > 0) {
193
+ const humanTask = this.humanQueue.shift();
194
+ try {
195
+ const res = this.processSingle(humanTask.envelope, humanTask.serverTime);
196
+ humanTask.resolve(res);
197
+ }
198
+ catch (err) {
199
+ humanTask.reject(err);
200
+ }
201
+ }
202
+ if (this.agentQueue.length > 0) {
203
+ const agentTask = this.agentQueue.shift();
204
+ processedAgent = true;
205
+ try {
206
+ const res = this.processSingle(agentTask.envelope, agentTask.serverTime);
207
+ agentTask.resolve(res);
208
+ }
209
+ catch (err) {
210
+ agentTask.reject(err);
211
+ }
212
+ }
213
+ }
214
+ finally {
215
+ this.draining = false;
216
+ if (this.humanQueue.length > 0) {
217
+ this.scheduleDrain(false);
218
+ }
219
+ else if (this.agentQueue.length > 0) {
220
+ this.scheduleDrain(processedAgent);
221
+ }
222
+ }
223
+ }
224
+ processSingle(rawEnvelope, serverTime) {
225
+ const isHuman = rawEnvelope.auth.origin.kind === 'Human';
226
+ if (isHuman) {
227
+ this.metrics = { ...this.metrics, humanDispatches: this.metrics.humanDispatches + 1 };
228
+ }
229
+ else {
230
+ this.metrics = { ...this.metrics, agentDispatches: this.metrics.agentDispatches + 1 };
231
+ }
232
+ if (!isHuman &&
233
+ this.state.taskStatus === 'HALTED' &&
234
+ rawEnvelope.event.kind !== 'EffectTransition' &&
235
+ rawEnvelope.event.kind !== 'OriginUndo' &&
236
+ rawEnvelope.event.kind !== 'ExpireUndoWindow') {
237
+ this.suppressedHaltedCount += 1;
238
+ if (this.suppressedHaltedCount > 1 && this.suppressedHaltedCount % this.haltRejectionAggThreshold !== 0) {
239
+ this.metrics = {
240
+ ...this.metrics,
241
+ aggregatedHaltDrops: this.metrics.aggregatedHaltDrops + 1,
242
+ };
243
+ return {
244
+ state: this.state,
245
+ decision: { code: 'HALT', reason: this.state.haltReason ?? 'TASK_HALTED' },
246
+ intents: [],
247
+ logEntry: null,
248
+ idempotentReplay: false,
249
+ schemaRejected: false,
250
+ };
251
+ }
252
+ }
253
+ else if (this.state.taskStatus !== 'HALTED') {
254
+ this.suppressedHaltedCount = 0;
255
+ }
256
+ // Ingress boundary: redact secrets and buffer large fields. Nothing reaches the BlobStore before step() accepts.
257
+ const dp1 = prepareDp1Envelope(rawEnvelope, this.maxInlinePayloadBytes, this.state.policy.maxEventBytes, this.fieldOffloadThresholdBytes);
258
+ if (!dp1.ok) {
259
+ return {
260
+ state: this.state,
261
+ decision: { code: 'REJECT', reason: dp1.reason },
262
+ intents: [],
263
+ logEntry: null,
264
+ idempotentReplay: false,
265
+ schemaRejected: true,
266
+ };
267
+ }
268
+ const preparedEnvelope = dp1.envelope;
269
+ // The human lane overtakes the agent lane, so an operation submitted earlier can reach the kernel
270
+ // later. A server-assigned time is then raised to the state time. An explicit time stays as given,
271
+ // and the kernel rejects it when it goes back (CLOCK_REGRESSION).
272
+ const effectiveNowMs = serverTime
273
+ ? Math.max(preparedEnvelope.nowMs, this.state.lastNowMs)
274
+ : preparedEnvelope.nowMs;
275
+ const cleanEnvelope = {
276
+ ...preparedEnvelope,
277
+ nowMs: effectiveNowMs,
278
+ };
279
+ const prevSpentLen = this.state.spentApprovals.length;
280
+ const prevSpentLast = this.state.spentApprovals[prevSpentLen - 1] ?? null;
281
+ const result = step(this.state, cleanEnvelope, this.hooks);
282
+ const newSpentLast = result.state.spentApprovals[result.state.spentApprovals.length - 1] ?? null;
283
+ const spentApprovalId = result.logEntry?.kind === 'FinalizeBatch' &&
284
+ result.logEntry.applied &&
285
+ newSpentLast !== null &&
286
+ (result.state.spentApprovals.length !== prevSpentLen || newSpentLast !== prevSpentLast)
287
+ ? newSpentLast
288
+ : null;
289
+ const clusterUpdate = result.state.clusters !== this.state.clusters
290
+ ? (result.state.clusters[result.state.clusters.length - 1] ?? null)
291
+ : null;
292
+ const ev = cleanEnvelope.event;
293
+ const effectStatusAfter = ev.kind === 'EffectTransition'
294
+ ? (result.state.effects.find((e) => e.effectId === ev.effectId)?.status ?? null)
295
+ : null;
296
+ if (result.logEntry !== null) {
297
+ if (result.logEntry.applied && dp1.pendingBlobs.length > 0) {
298
+ this.metrics = {
299
+ ...this.metrics,
300
+ offloadedBlobs: this.metrics.offloadedBlobs + dp1.pendingBlobs.length,
301
+ };
302
+ }
303
+ this.store.commitStep(result.logEntry, cleanEnvelope, result.intents, cleanEnvelope.nowMs, {
304
+ pendingBlobs: dp1.pendingBlobs,
305
+ spentApprovalId,
306
+ clusterUpdate,
307
+ effectStatusAfter,
308
+ });
309
+ if (cleanEnvelope.nowMs > this.lastPersistedNowMs) {
310
+ this.lastPersistedNowMs = cleanEnvelope.nowMs;
311
+ }
312
+ }
313
+ this.state = result.state;
314
+ return result;
315
+ }
316
+ close() {
317
+ this.store.close();
318
+ }
319
+ }
320
+ export { createInitialState };
@@ -0,0 +1,4 @@
1
+ export * from './store.ts';
2
+ export * from './dp1.ts';
3
+ export * from './outbox.ts';
4
+ export * from './engine.ts';
@@ -0,0 +1,4 @@
1
+ export * from './store.js';
2
+ export * from './dp1.js';
3
+ export * from './outbox.js';
4
+ export * from './engine.js';