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,150 @@
1
+ import type { ApprovalToken, CompensationPolicy, PinPolicy, Binding, Grade, Intent, KernelState, StateOp, StepResult, UndoReport } from '../kernel/index.ts';
2
+ import { OutboxWorker } from '../runtime/index.ts';
3
+ import type { CertalRuntime, OutboxWorkerOptions, RuntimePort } from '../runtime/index.ts';
4
+ import type { InMemoryReferenceAdapter } from './in-memory.ts';
5
+ /**
6
+ * Trust boundary. The agent is untrusted, so the SDK has three parts,
7
+ * and each one gets its own runtime port that accepts only its origin kind:
8
+ *
9
+ * - `AgentGateway` port `Agent`: lease, attempt, batch, finalize. It cannot issue a human event.
10
+ * - `WitnessService` port `System`: witness verdicts.
11
+ * - `OperatorConsole` port `Human`: edits, approvals, undo. Only this part holds the approval signing key.
12
+ *
13
+ * The agent asks for approval through `ApprovalRequester`. The operator side decides and signs.
14
+ */
15
+ export interface ToolCallRequest {
16
+ readonly opId: string;
17
+ readonly attemptId: string;
18
+ readonly taskId: string;
19
+ readonly toolId: string;
20
+ /** Domain identifier assigned on the trusted side, for example an order id or a pull request id. */
21
+ readonly domainObjectId: string;
22
+ readonly executorId: string;
23
+ readonly scopeId: string;
24
+ readonly classId: string;
25
+ readonly ops: readonly StateOp[];
26
+ readonly rawInputs: unknown;
27
+ readonly confidence: Grade;
28
+ }
29
+ export interface ToolCallOutcome {
30
+ readonly finalized: boolean;
31
+ readonly decisionCode: StepResult['decision']['code'];
32
+ readonly reason: string;
33
+ readonly attemptId: string;
34
+ readonly state: KernelState;
35
+ }
36
+ /** Approval request from the agent. It carries the content the human consents to. */
37
+ export interface ApprovalRequest {
38
+ readonly attemptId: string;
39
+ readonly binding: Binding;
40
+ readonly reason: string | null;
41
+ }
42
+ /** Answer from the operator side: the id of the granted approval, or null when there is none. */
43
+ export interface ApprovalRequester {
44
+ requestApproval(request: ApprovalRequest): Promise<string | null>;
45
+ }
46
+ export interface WitnessRunner {
47
+ submitVerdict(opId: string, attemptId: string, verify: Extract<Intent, {
48
+ kind: 'Verify';
49
+ }>): Promise<StepResult>;
50
+ }
51
+ /** Operator's decision to approve one attempt. */
52
+ export interface OperatorApproval {
53
+ readonly approvalId: string;
54
+ readonly humanId: string;
55
+ readonly ttlMs: number;
56
+ }
57
+ /** Signs an approval with the operator's key. Without a signer the approval is unsigned. */
58
+ export type ApprovalSigner = (payload: {
59
+ readonly approvalId: string;
60
+ readonly humanId: string;
61
+ readonly attemptId: string;
62
+ readonly bindingHash: string;
63
+ readonly expiresAtMs: number;
64
+ readonly singleUse: true;
65
+ }) => NonNullable<ApprovalToken['signature']>;
66
+ /** Builds a signer that signs approvals with the operator's Ed25519 private key (PEM). */
67
+ export declare function createEd25519ApprovalSigner(privateKeyPem: string, keyId: string): ApprovalSigner;
68
+ /** Derives a deterministic clusterId from the domain object. Runs on the trusted side only. */
69
+ export declare function computeClusterId(scopeId: string, domainObjectId: string): string;
70
+ /** Witness: runs a verification stage and sends the verdict through the `System` port. */
71
+ export declare class WitnessService implements WitnessRunner {
72
+ private readonly port;
73
+ private readonly adapter;
74
+ constructor(port: RuntimePort, adapter: InMemoryReferenceAdapter);
75
+ submitVerdict(opId: string, attemptId: string, verify: Extract<Intent, {
76
+ kind: 'Verify';
77
+ }>): Promise<StepResult>;
78
+ }
79
+ /** Operator console: the only place that issues human events. */
80
+ export declare class OperatorConsole {
81
+ private readonly port;
82
+ private readonly signer;
83
+ private seq;
84
+ constructor(port: RuntimePort, signer?: ApprovalSigner);
85
+ private auth;
86
+ private nextId;
87
+ humanEdit(humanId: string, scopeId: string, classId: string, objectId: string, field: string, value: unknown, parentObjectId?: string, autoPinTtlMs?: number): Promise<StepResult>;
88
+ /** Grants approval for the content of the attempt's current batch. Signs it when the console has a key. */
89
+ grantApproval(opId: string, attemptId: string, decision: OperatorApproval): Promise<StepResult>;
90
+ setPin(humanId: string, pin: PinPolicy): Promise<StepResult>;
91
+ removePin(humanId: string, pinId: string, scopeId: string, reason: string): Promise<StepResult>;
92
+ halt(humanId: string, scopeId: string, reason: string): Promise<StepResult>;
93
+ reset(humanId: string, scopeId: string, reason: string): Promise<StepResult>;
94
+ cancelAttempt(humanId: string, attemptId: string, reason: string): Promise<StepResult>;
95
+ resume(humanId: string, scopeId: string): Promise<StepResult>;
96
+ originUndo(humanId: string, batchId: string, scopeId: string, reason: string, compensationPolicy?: CompensationPolicy): Promise<StepResult>;
97
+ }
98
+ /**
99
+ * Agent side of the SDK. It holds an `Agent` port, the witness and the approval request channel.
100
+ * It has no access to the human port or to the signing key.
101
+ */
102
+ export declare class AgentGateway {
103
+ private readonly port;
104
+ private readonly adapter;
105
+ private readonly witness;
106
+ private readonly approvals;
107
+ private readonly drainOutbox;
108
+ constructor(options: {
109
+ readonly agentPort: RuntimePort;
110
+ readonly adapter: InMemoryReferenceAdapter;
111
+ readonly witness: WitnessRunner;
112
+ readonly approvals?: ApprovalRequester;
113
+ readonly drainOutbox?: () => Promise<void>;
114
+ });
115
+ executeToolCall(req: ToolCallRequest): Promise<ToolCallOutcome>;
116
+ }
117
+ export interface EmbeddedToolSdkOptions {
118
+ readonly outbox?: OutboxWorkerOptions;
119
+ /** Operator key for signing approvals. Required when the policy has `enforceApprovalSignature = true`. */
120
+ readonly approvalSigner?: ApprovalSigner;
121
+ }
122
+ /**
123
+ * Embedded tool-call SDK: the reference setup in a single process.
124
+ * It wires the three parts with separate ports. Agent code should receive only the `agent` field.
125
+ * The host passes the operator's approval as the second argument of `executeToolCall`. The agent request has no such field.
126
+ */
127
+ export declare class EmbeddedToolSdk {
128
+ readonly runtime: CertalRuntime;
129
+ readonly adapter: InMemoryReferenceAdapter;
130
+ readonly outbox: OutboxWorker;
131
+ readonly agent: AgentGateway;
132
+ readonly operator: OperatorConsole;
133
+ readonly witness: WitnessService;
134
+ private readonly pendingApprovals;
135
+ private readonly approvalResults;
136
+ constructor(runtime: CertalRuntime, adapter: InMemoryReferenceAdapter, options?: EmbeddedToolSdkOptions | OutboxWorkerOptions);
137
+ private takeApprovalResult;
138
+ private drainOutbox;
139
+ computeClusterId(scopeId: string, domainObjectId: string): string;
140
+ humanEdit(humanId: string, scopeId: string, classId: string, objectId: string, field: string, value: unknown, parentObjectId?: string, autoPinTtlMs?: number): Promise<StepResult>;
141
+ /**
142
+ * Runs a tool call through the agent side. `operatorApproval` is the operator's decision prepared
143
+ * by the host. When the attempt needs approval, the operator console issues and signs it.
144
+ */
145
+ executeToolCall(req: ToolCallRequest, operatorApproval?: OperatorApproval): Promise<ToolCallOutcome>;
146
+ originUndo(humanId: string, batchId: string, scopeId: string, reason: string, compensationPolicy?: CompensationPolicy): Promise<{
147
+ readonly result: StepResult;
148
+ readonly report?: UndoReport;
149
+ }>;
150
+ }
@@ -0,0 +1,336 @@
1
+ import { computeScopeHash, hashBinding, hashCanonical, pendingVerifyEpoch, signApprovalEd25519 } from '../kernel/index.js';
2
+ import { OutboxWorker } from '../runtime/index.js';
3
+ /** Builds a signer that signs approvals with the operator's Ed25519 private key (PEM). */
4
+ export function createEd25519ApprovalSigner(privateKeyPem, keyId) {
5
+ return (payload) => ({
6
+ algorithm: 'Ed25519',
7
+ keyId,
8
+ value: signApprovalEd25519(privateKeyPem, payload),
9
+ });
10
+ }
11
+ function failed(res, attemptId) {
12
+ return {
13
+ finalized: false,
14
+ decisionCode: res.decision.code,
15
+ reason: res.decision.reason,
16
+ attemptId,
17
+ state: res.state,
18
+ };
19
+ }
20
+ /** Derives a deterministic clusterId from the domain object. Runs on the trusted side only. */
21
+ export function computeClusterId(scopeId, domainObjectId) {
22
+ return hashCanonical('cluster', 1, { scopeId, domainObjectId });
23
+ }
24
+ /** Witness: runs a verification stage and sends the verdict through the `System` port. */
25
+ export class WitnessService {
26
+ port;
27
+ adapter;
28
+ constructor(port, adapter) {
29
+ this.port = port;
30
+ this.adapter = adapter;
31
+ }
32
+ async submitVerdict(opId, attemptId, verify) {
33
+ const stageExec = await this.adapter.runStage(verify);
34
+ const state = this.port.getState();
35
+ return this.port.submit(`${opId}:witness:${verify.stage}`, { origin: { kind: 'System', actorId: 'witness-oracle' }, roles: ['witness'], authMethod: 'internal' }, {
36
+ kind: 'WitnessVerdict',
37
+ attemptId,
38
+ verifyId: verify.verifyId,
39
+ stage: verify.stage,
40
+ epoch: pendingVerifyEpoch(state, attemptId) ?? state.epoch,
41
+ scopeHash: verify.binding.scopeHash,
42
+ inputSnapshotHash: verify.binding.inputSnapshotHash,
43
+ verdict: stageExec.verdict,
44
+ cpuMs: stageExec.cpuMs,
45
+ nearMissPassed: stageExec.nearMissPassed,
46
+ ...(stageExec.optimization !== undefined ? { optimization: stageExec.optimization } : {}),
47
+ });
48
+ }
49
+ }
50
+ /** Operator console: the only place that issues human events. */
51
+ export class OperatorConsole {
52
+ port;
53
+ signer;
54
+ seq = 0;
55
+ constructor(port, signer) {
56
+ this.port = port;
57
+ this.signer = signer ?? null;
58
+ }
59
+ auth(humanId, role) {
60
+ return { origin: { kind: 'Human', actorId: humanId }, roles: [role], authMethod: 'session' };
61
+ }
62
+ nextId(prefix) {
63
+ this.seq += 1;
64
+ return `${prefix}:${this.seq}`;
65
+ }
66
+ humanEdit(humanId, scopeId, classId, objectId, field, value, parentObjectId, autoPinTtlMs) {
67
+ return this.port.submit(this.nextId('human'), this.auth(humanId, 'operator'), {
68
+ kind: 'HumanEdit',
69
+ scopeId,
70
+ classId,
71
+ objectId,
72
+ field,
73
+ value,
74
+ ...(parentObjectId !== undefined ? { parentObjectId } : {}),
75
+ ...(autoPinTtlMs !== undefined ? { autoPinTtlMs } : {}),
76
+ });
77
+ }
78
+ /** Grants approval for the content of the attempt's current batch. Signs it when the console has a key. */
79
+ grantApproval(opId, attemptId, decision) {
80
+ const attempt = this.port.getState().activeAttempts.find((a) => a.attemptId === attemptId);
81
+ const binding = attempt?.binding ?? { diffHash: '-', scopeHash: '-', inputSnapshotHash: '-' };
82
+ const expiresAtMs = this.port.getNowMs() + decision.ttlMs;
83
+ const base = {
84
+ approvalId: decision.approvalId,
85
+ humanId: decision.humanId,
86
+ attemptId,
87
+ binding,
88
+ expiresAtMs,
89
+ singleUse: true,
90
+ };
91
+ const token = this.signer
92
+ ? {
93
+ ...base,
94
+ signature: this.signer({
95
+ approvalId: decision.approvalId,
96
+ humanId: decision.humanId,
97
+ attemptId,
98
+ bindingHash: hashBinding(binding.diffHash, binding.scopeHash, binding.inputSnapshotHash),
99
+ expiresAtMs,
100
+ singleUse: true,
101
+ }),
102
+ }
103
+ : base;
104
+ return this.port.submit(opId, this.auth(decision.humanId, 'approver'), { kind: 'GrantApproval', approval: token });
105
+ }
106
+ setPin(humanId, pin) {
107
+ return this.port.submit(this.nextId('pin'), this.auth(humanId, 'operator'), { kind: 'SetPin', pin });
108
+ }
109
+ removePin(humanId, pinId, scopeId, reason) {
110
+ return this.port.submit(this.nextId('unpin'), this.auth(humanId, 'operator'), {
111
+ kind: 'RemovePin',
112
+ pinId,
113
+ scopeId,
114
+ reason,
115
+ });
116
+ }
117
+ halt(humanId, scopeId, reason) {
118
+ return this.port.submit(this.nextId('halt'), this.auth(humanId, 'operator'), { kind: 'HumanHalt', scopeId, reason });
119
+ }
120
+ reset(humanId, scopeId, reason) {
121
+ return this.port.submit(this.nextId('reset'), this.auth(humanId, 'operator'), { kind: 'HumanReset', scopeId, reason });
122
+ }
123
+ cancelAttempt(humanId, attemptId, reason) {
124
+ return this.port.submit(this.nextId('cancel'), this.auth(humanId, 'operator'), {
125
+ kind: 'CancelAttempt',
126
+ attemptId,
127
+ reason,
128
+ });
129
+ }
130
+ resume(humanId, scopeId) {
131
+ return this.port.submit(this.nextId('resume'), this.auth(humanId, 'operator'), { kind: 'HumanResume', scopeId });
132
+ }
133
+ originUndo(humanId, batchId, scopeId, reason, compensationPolicy) {
134
+ return this.port.submit(this.nextId('undo'), this.auth(humanId, 'operator'), {
135
+ kind: 'OriginUndo',
136
+ batchId,
137
+ scopeId,
138
+ reason,
139
+ ...(compensationPolicy !== undefined ? { compensationPolicy } : {}),
140
+ });
141
+ }
142
+ }
143
+ /**
144
+ * Agent side of the SDK. It holds an `Agent` port, the witness and the approval request channel.
145
+ * It has no access to the human port or to the signing key.
146
+ */
147
+ export class AgentGateway {
148
+ port;
149
+ adapter;
150
+ witness;
151
+ approvals;
152
+ drainOutbox;
153
+ constructor(options) {
154
+ this.port = options.agentPort;
155
+ this.adapter = options.adapter;
156
+ this.witness = options.witness;
157
+ this.approvals = options.approvals ?? null;
158
+ this.drainOutbox = options.drainOutbox ?? (async () => { });
159
+ }
160
+ async executeToolCall(req) {
161
+ const agentAuth = {
162
+ origin: { kind: 'Agent', actorId: req.executorId, taskId: req.taskId, attemptId: req.attemptId },
163
+ roles: ['executor'],
164
+ authMethod: 'sdk',
165
+ };
166
+ const clusterId = computeClusterId(req.scopeId, req.domainObjectId);
167
+ const currentScopeHash = computeScopeHash(this.port.getState(), req.scopeId, req.classId);
168
+ const leaseId = `lease:${req.attemptId}`;
169
+ const units = { inferenceSlots: 1, witnessSlots: 1, mutationSlots: 1 };
170
+ const leaseRes = await this.port.submit(`${req.opId}:lease`, agentAuth, {
171
+ kind: 'AcquireLease',
172
+ leaseId,
173
+ scopeId: req.scopeId,
174
+ classId: req.classId,
175
+ attemptId: req.attemptId,
176
+ units,
177
+ });
178
+ if (leaseRes.decision.code !== 'ALLOW')
179
+ return failed(leaseRes, req.attemptId);
180
+ const leaseEpoch = leaseRes.state.leases.find((l) => l.leaseId === leaseId)?.leaseEpoch ?? 1;
181
+ const openRes = await this.port.submit(`${req.opId}:open`, agentAuth, {
182
+ kind: 'OpenAttempt',
183
+ attemptId: req.attemptId,
184
+ taskId: req.taskId,
185
+ toolId: req.toolId,
186
+ clusterId,
187
+ executorId: req.executorId,
188
+ scopeId: req.scopeId,
189
+ classId: req.classId,
190
+ expectedScopeHash: currentScopeHash,
191
+ });
192
+ if (openRes.decision.code !== 'ALLOW')
193
+ return failed(openRes, req.attemptId);
194
+ const nowMs = this.port.getNowMs();
195
+ const snapshot = this.adapter.freezeInputs(req.scopeId, req.rawInputs, req.confidence, nowMs);
196
+ const submitRes = await this.port.submit(`${req.opId}:submit`, agentAuth, {
197
+ kind: 'SubmitBatch',
198
+ attemptId: req.attemptId,
199
+ executorId: req.executorId,
200
+ leaseId,
201
+ leaseEpoch,
202
+ expectedScopeHash: currentScopeHash,
203
+ ops: req.ops,
204
+ snapshot,
205
+ });
206
+ if (submitRes.decision.code !== 'ALLOW')
207
+ return failed(submitRes, req.attemptId);
208
+ // Witness stages L0..L3. The witness sends each verdict through its own port.
209
+ let pendingIntents = submitRes.intents;
210
+ while (pendingIntents.length > 0) {
211
+ const verifyIntent = pendingIntents.find((i) => i.kind === 'Verify');
212
+ if (!verifyIntent || verifyIntent.kind !== 'Verify')
213
+ break;
214
+ const witnessRes = await this.witness.submitVerdict(req.opId, req.attemptId, verifyIntent);
215
+ if (witnessRes.decision.code !== 'ALLOW' && witnessRes.decision.code !== 'PAUSE') {
216
+ return failed(witnessRes, req.attemptId);
217
+ }
218
+ pendingIntents = witnessRes.intents;
219
+ }
220
+ const attempt = this.port.getState().activeAttempts.find((a) => a.attemptId === req.attemptId);
221
+ let approvalId = null;
222
+ if (attempt?.needsApproval && attempt.binding && this.approvals) {
223
+ approvalId = await this.approvals.requestApproval({
224
+ attemptId: req.attemptId,
225
+ binding: attempt.binding,
226
+ reason: attempt.approvalReason,
227
+ });
228
+ }
229
+ const finRes = await this.port.submit(`${req.opId}:finalize`, agentAuth, {
230
+ kind: 'FinalizeBatch',
231
+ attemptId: req.attemptId,
232
+ ...(approvalId !== null ? { approvalId } : {}),
233
+ });
234
+ if (finRes.decision.code !== 'ALLOW')
235
+ return failed(finRes, req.attemptId);
236
+ await this.drainOutbox();
237
+ return {
238
+ finalized: true,
239
+ decisionCode: finRes.decision.code,
240
+ reason: finRes.decision.reason,
241
+ attemptId: req.attemptId,
242
+ state: this.port.getState(),
243
+ };
244
+ }
245
+ }
246
+ /**
247
+ * Embedded tool-call SDK: the reference setup in a single process.
248
+ * It wires the three parts with separate ports. Agent code should receive only the `agent` field.
249
+ * The host passes the operator's approval as the second argument of `executeToolCall`. The agent request has no such field.
250
+ */
251
+ export class EmbeddedToolSdk {
252
+ runtime;
253
+ adapter;
254
+ outbox;
255
+ agent;
256
+ operator;
257
+ witness;
258
+ pendingApprovals = new Map();
259
+ approvalResults = new Map();
260
+ constructor(runtime, adapter, options) {
261
+ const opts = options !== undefined && ('outbox' in options || 'approvalSigner' in options)
262
+ ? options
263
+ : { ...(options !== undefined ? { outbox: options } : {}) };
264
+ this.runtime = runtime;
265
+ this.adapter = adapter;
266
+ this.outbox = new OutboxWorker(runtime.getStore(), adapter, {
267
+ getState: () => this.runtime.getState(),
268
+ getNowMs: () => this.runtime.getNowMs(),
269
+ dispatch: (env) => this.runtime.dispatch(env),
270
+ }, { baseBackoffMs: 0, maxBackoffMs: 0, blobStore: runtime.getStore(), ...opts.outbox });
271
+ this.operator = new OperatorConsole(runtime.createPort(['Human']), opts.approvalSigner);
272
+ this.witness = new WitnessService(runtime.createPort(['System']), adapter);
273
+ this.agent = new AgentGateway({
274
+ agentPort: runtime.createPort(['Agent']),
275
+ adapter,
276
+ witness: this.witness,
277
+ approvals: {
278
+ requestApproval: async (request) => {
279
+ const pending = this.pendingApprovals.get(request.attemptId);
280
+ if (!pending)
281
+ return null;
282
+ const granted = await this.operator.grantApproval(`${pending.opId}:grant`, request.attemptId, pending.decision);
283
+ this.approvalResults.set(request.attemptId, granted);
284
+ return granted.decision.code === 'ALLOW' ? pending.decision.approvalId : null;
285
+ },
286
+ },
287
+ drainOutbox: () => this.drainOutbox(),
288
+ });
289
+ }
290
+ takeApprovalResult(attemptId) {
291
+ const result = this.approvalResults.get(attemptId) ?? null;
292
+ this.approvalResults.delete(attemptId);
293
+ return result;
294
+ }
295
+ async drainOutbox() {
296
+ for (let guard = 0; guard < 10; guard += 1) {
297
+ const count = await this.outbox.processOnce();
298
+ if (count === 0)
299
+ break;
300
+ }
301
+ }
302
+ computeClusterId(scopeId, domainObjectId) {
303
+ return computeClusterId(scopeId, domainObjectId);
304
+ }
305
+ humanEdit(humanId, scopeId, classId, objectId, field, value, parentObjectId, autoPinTtlMs) {
306
+ return this.operator.humanEdit(humanId, scopeId, classId, objectId, field, value, parentObjectId, autoPinTtlMs);
307
+ }
308
+ /**
309
+ * Runs a tool call through the agent side. `operatorApproval` is the operator's decision prepared
310
+ * by the host. When the attempt needs approval, the operator console issues and signs it.
311
+ */
312
+ async executeToolCall(req, operatorApproval) {
313
+ if (operatorApproval)
314
+ this.pendingApprovals.set(req.attemptId, { opId: req.opId, decision: operatorApproval });
315
+ try {
316
+ const outcome = await this.agent.executeToolCall(req);
317
+ const grant = this.takeApprovalResult(req.attemptId);
318
+ if (!outcome.finalized && grant !== null && grant.decision.code !== 'ALLOW') {
319
+ return failed(grant, req.attemptId);
320
+ }
321
+ return outcome;
322
+ }
323
+ finally {
324
+ this.pendingApprovals.delete(req.attemptId);
325
+ this.approvalResults.delete(req.attemptId);
326
+ }
327
+ }
328
+ async originUndo(humanId, batchId, scopeId, reason, compensationPolicy) {
329
+ const res = await this.operator.originUndo(humanId, batchId, scopeId, reason, compensationPolicy);
330
+ await this.drainOutbox();
331
+ return {
332
+ result: res,
333
+ ...(res.undoReport !== undefined ? { report: res.undoReport } : {}),
334
+ };
335
+ }
336
+ }
@@ -0,0 +1 @@
1
+ export * from './main.ts';
@@ -0,0 +1 @@
1
+ export * from './main.js';
@@ -0,0 +1 @@
1
+ export declare function main(argv: readonly string[]): Promise<number>;