@deepstrike/sdk 0.2.39 → 0.2.40

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 (102) hide show
  1. package/README.md +61 -31
  2. package/dist/collaboration/contract.d.ts +2 -2
  3. package/dist/collaboration/contract.js +2 -2
  4. package/dist/collaboration/handoff.d.ts +2 -14
  5. package/dist/collaboration/handoff.js +1 -17
  6. package/dist/collaboration/harness.d.ts +16 -47
  7. package/dist/collaboration/harness.js +57 -158
  8. package/dist/collaboration/index.d.ts +2 -2
  9. package/dist/collaboration/index.js +1 -2
  10. package/dist/collaboration/modes/creator-verifier.js +42 -6
  11. package/dist/collaboration/pool.d.ts +8 -0
  12. package/dist/collaboration/pool.js +56 -3
  13. package/dist/harness/harness.d.ts +97 -97
  14. package/dist/harness/harness.js +190 -144
  15. package/dist/harness/judge.d.ts +3 -2
  16. package/dist/harness/judge.js +7 -3
  17. package/dist/harness/public.d.ts +5 -3
  18. package/dist/harness/public.js +3 -2
  19. package/dist/index.d.ts +22 -7
  20. package/dist/index.js +8 -1
  21. package/dist/kernel.d.ts +12 -39
  22. package/dist/memory/agent.d.ts +8 -41
  23. package/dist/memory/agent.js +34 -117
  24. package/dist/memory/extraction.d.ts +4 -0
  25. package/dist/memory/extraction.js +79 -0
  26. package/dist/memory/in-memory-store.d.ts +28 -15
  27. package/dist/memory/in-memory-store.js +74 -25
  28. package/dist/memory/protocols.d.ts +56 -56
  29. package/dist/memory/protocols.js +1 -0
  30. package/dist/memory/public.d.ts +3 -1
  31. package/dist/memory/public.js +1 -0
  32. package/dist/memory/ranking.d.ts +33 -0
  33. package/dist/memory/ranking.js +77 -0
  34. package/dist/memory/retention.d.ts +17 -0
  35. package/dist/memory/retention.js +54 -0
  36. package/dist/os/public.d.ts +3 -3
  37. package/dist/os/public.js +1 -1
  38. package/dist/providers/base.d.ts +8 -0
  39. package/dist/providers/base.js +0 -0
  40. package/dist/providers/gemini.js +12 -0
  41. package/dist/providers/ollama.js +3 -1
  42. package/dist/providers/openai-responses.js +9 -2
  43. package/dist/providers/profiles.d.ts +5 -3
  44. package/dist/providers/profiles.js +3 -3
  45. package/dist/runtime/context-policy.d.ts +35 -0
  46. package/dist/runtime/context-policy.js +66 -0
  47. package/dist/runtime/eval.d.ts +6 -2
  48. package/dist/runtime/eval.js +2 -2
  49. package/dist/runtime/event-stream.d.ts +9 -0
  50. package/dist/runtime/event-stream.js +25 -11
  51. package/dist/runtime/execution-plane.d.ts +5 -1
  52. package/dist/runtime/execution-plane.js +9 -3
  53. package/dist/runtime/facade.js +2 -1
  54. package/dist/runtime/kernel-event-log.d.ts +0 -2
  55. package/dist/runtime/kernel-event-log.js +61 -13
  56. package/dist/runtime/kernel-primitives-dashboard.js +1 -1
  57. package/dist/runtime/kernel-rebuild.d.ts +13 -0
  58. package/dist/runtime/kernel-rebuild.js +75 -0
  59. package/dist/runtime/kernel-step.d.ts +157 -8
  60. package/dist/runtime/kernel-step.js +220 -7
  61. package/dist/runtime/kernel-transaction-log.d.ts +61 -0
  62. package/dist/runtime/kernel-transaction-log.js +149 -0
  63. package/dist/runtime/large-result-spool.d.ts +3 -1
  64. package/dist/runtime/large-result-spool.js +24 -5
  65. package/dist/runtime/loop-driver.d.ts +1 -1
  66. package/dist/runtime/loop-driver.js +2 -7
  67. package/dist/runtime/mcp-proxy-plane.d.ts +1 -0
  68. package/dist/runtime/mcp-proxy-plane.js +23 -6
  69. package/dist/runtime/os-profile.d.ts +9 -10
  70. package/dist/runtime/os-profile.js +14 -10
  71. package/dist/runtime/os-snapshot.d.ts +19 -0
  72. package/dist/runtime/os-snapshot.js +33 -3
  73. package/dist/runtime/process-sandbox-plane.js +16 -11
  74. package/dist/runtime/reaction-checkpoint.d.ts +51 -0
  75. package/dist/runtime/reaction-checkpoint.js +83 -0
  76. package/dist/runtime/reactive-session.d.ts +9 -3
  77. package/dist/runtime/reactive-session.js +44 -14
  78. package/dist/runtime/reliability.d.ts +48 -0
  79. package/dist/runtime/reliability.js +86 -0
  80. package/dist/runtime/remote-vpc-plane.js +4 -3
  81. package/dist/runtime/run-group.d.ts +38 -35
  82. package/dist/runtime/run-group.js +97 -54
  83. package/dist/runtime/runner.d.ts +117 -78
  84. package/dist/runtime/runner.js +1516 -1197
  85. package/dist/runtime/session-log.d.ts +71 -12
  86. package/dist/runtime/session-log.js +192 -32
  87. package/dist/runtime/session-repair.d.ts +11 -7
  88. package/dist/runtime/session-repair.js +11 -8
  89. package/dist/runtime/sub-agent-orchestrator.d.ts +6 -2
  90. package/dist/runtime/sub-agent-orchestrator.js +45 -18
  91. package/dist/signals/gateway.d.ts +23 -10
  92. package/dist/signals/gateway.js +81 -17
  93. package/dist/signals/scheduled.js +0 -1
  94. package/dist/signals/types.d.ts +21 -13
  95. package/dist/skills/loader.js +12 -2
  96. package/dist/tools/index.d.ts +2 -0
  97. package/dist/types/agent.d.ts +40 -1
  98. package/dist/types/agent.js +61 -1
  99. package/dist/types.d.ts +6 -1
  100. package/dist/workflow/public.d.ts +2 -3
  101. package/dist/workflow/public.js +0 -1
  102. package/package.json +2 -2
@@ -1,9 +1,16 @@
1
1
  import type { EntropySample, Message, RenderedContext, TaskUpdate, ToolCall, ToolResult, ToolSchema } from "../types.js";
2
2
  import type { SkillMetadata } from "../skills/loader.js";
3
3
  import type { RollbackReason } from "./session-log.js";
4
- export declare const KERNEL_ABI_VERSION = 1;
4
+ import type { SessionLog } from "./session-log.js";
5
+ export declare const KERNEL_ABI_VERSION = 2;
5
6
  export interface KernelRuntimeHandle {
6
7
  step(inputJson: string): string;
8
+ prepareStep(inputJson: string): string;
9
+ commitPrepared(prepareToken: string): string;
10
+ abortPrepared(prepareToken: string): void;
11
+ snapshot(): string;
12
+ restore(snapshotJson: string): void;
13
+ diagnostics(): string;
7
14
  isTerminal(): boolean;
8
15
  turn(): number;
9
16
  recoveryContentBytes(): number;
@@ -11,6 +18,52 @@ export interface KernelRuntimeHandle {
11
18
  drainNewMessages(): Message[];
12
19
  preservedRefs(): string[];
13
20
  }
21
+ export type KernelPreparationStatus = "prepared" | "replayed" | "rejected";
22
+ export interface KernelPreparedStep {
23
+ status: KernelPreparationStatus;
24
+ base_generation: number;
25
+ prepare_token?: string;
26
+ input: Record<string, unknown>;
27
+ step: KernelStepJson;
28
+ }
29
+ export interface KernelDiagnostics {
30
+ lifecycle: string;
31
+ next_step_seq: number;
32
+ accepted_input_count: number;
33
+ accepted_input_bytes: number;
34
+ snapshot_input_limit: number;
35
+ snapshot_journal_bytes_limit: number;
36
+ max_input_bytes: number;
37
+ snapshot_overflowed: boolean;
38
+ recorded_event_count: number;
39
+ completed_effect_count: number;
40
+ pending_effect_count: number;
41
+ }
42
+ export declare function readKernelDiagnostics(runtime: KernelRuntimeHandle): KernelDiagnostics;
43
+ export interface KernelSnapshot {
44
+ snapshot_version: 2;
45
+ abi_version: 2;
46
+ initial_policy: {
47
+ max_tokens: number;
48
+ max_turns: number;
49
+ max_total_tokens: string;
50
+ max_wall_ms?: string;
51
+ };
52
+ lifecycle: string;
53
+ operation_id?: string;
54
+ next_step_seq: number;
55
+ snapshot_input_limit: number;
56
+ max_input_bytes: number;
57
+ snapshot_journal_bytes_limit: number;
58
+ accepted_input_bytes: number;
59
+ accepted_inputs: Array<{
60
+ event_id: string;
61
+ [key: string]: unknown;
62
+ }>;
63
+ last_step?: Record<string, unknown>;
64
+ }
65
+ export declare function snapshotKernelRuntime(runtime: KernelRuntimeHandle): KernelSnapshot;
66
+ export declare function restoreKernelRuntime(runtime: KernelRuntimeHandle, snapshot: KernelSnapshot): void;
14
67
  export interface PaceDecision {
15
68
  action: "continue" | "sleep" | "stop";
16
69
  delayMs?: number;
@@ -39,19 +92,67 @@ export type MilestoneVerifierKind = {
39
92
  };
40
93
  export type KernelRunnerAction = {
41
94
  kind: "call_provider";
95
+ effectId: string;
42
96
  context: RenderedContext;
43
97
  tools: ToolSchema[];
44
98
  } | {
45
99
  kind: "execute_tool";
100
+ effectId: string;
46
101
  calls: ToolCall[];
102
+ } | {
103
+ kind: "request_approval";
104
+ effectId: string;
105
+ requests: Array<{
106
+ callId: string;
107
+ tool: string;
108
+ arguments: string;
109
+ reason: string;
110
+ }>;
111
+ } | {
112
+ kind: "spawn_workflow";
113
+ effectId: string;
114
+ nodes: Array<Record<string, unknown>>;
115
+ budget?: Record<string, unknown>;
116
+ } | {
117
+ kind: "preempt_sub_agents";
118
+ effectId: string;
119
+ agentIds: string[];
120
+ reason: string;
121
+ } | {
122
+ kind: "persist_memory";
123
+ effectId: string;
124
+ memory: Record<string, unknown>;
125
+ } | {
126
+ kind: "query_memory";
127
+ effectId: string;
128
+ query: Record<string, unknown>;
129
+ requestedK: number;
130
+ } | {
131
+ kind: "spool_large_result";
132
+ effectId: string;
133
+ callId: string;
134
+ tool: string;
135
+ output: string;
136
+ originalSize: number;
137
+ previewSize: number;
138
+ } | {
139
+ kind: "archive_page_out";
140
+ effectId: string;
141
+ turn: number;
142
+ action: string;
143
+ summary?: string;
144
+ archived: Message[];
145
+ tier: string;
47
146
  } | {
48
147
  kind: "evaluate_milestone";
148
+ effectId: string;
49
149
  phaseId: string;
50
150
  criteria: string[];
51
151
  verifier?: MilestoneVerifierKind;
52
152
  requiredEvidence: string[];
53
153
  } | {
54
154
  kind: "done";
155
+ effectId: string;
55
156
  result: KernelLoopResult;
56
157
  };
57
158
  export interface KernelObservation {
@@ -60,7 +161,7 @@ export interface KernelObservation {
60
161
  rho_after?: number;
61
162
  sprint?: number;
62
163
  summary?: string;
63
- archived?: Message[];
164
+ archived_count?: number;
64
165
  turn?: number;
65
166
  checkpoint_history_len?: number;
66
167
  history_len?: number;
@@ -85,20 +186,44 @@ export interface KernelObservation {
85
186
  permitted_capability_ids?: string[];
86
187
  call_id?: string;
87
188
  tool?: string;
189
+ operation_id?: string;
190
+ delivery_id?: string;
191
+ attempt?: number;
88
192
  signal_id?: string;
89
193
  disposition?: string;
90
194
  queue_depth?: number;
91
195
  budget?: string;
196
+ reservation_id?: string;
197
+ tokens?: number;
198
+ subagents?: number;
199
+ rounds?: number;
92
200
  pending_calls?: string[];
201
+ pending_call_ids?: string[];
93
202
  approved?: string[];
94
203
  denied?: string[];
95
- tier_hint?: string;
96
- memory_id?: string;
204
+ tier?: string;
205
+ message_count?: number;
206
+ archive_ref?: string;
207
+ spool_ref?: string;
208
+ original_size?: number;
209
+ preview_size?: number;
210
+ record_id?: string;
211
+ scope?: {
212
+ tenant_id: string;
213
+ namespace: string;
214
+ };
215
+ name?: string;
97
216
  memory_kind?: string;
98
217
  size_bytes?: number;
99
- query_context?: string;
218
+ query?: string;
100
219
  requested_k?: number;
101
220
  requires_async_response?: boolean;
221
+ recalls?: Array<{
222
+ record_id: string;
223
+ recall_count: number;
224
+ last_recalled_at: number;
225
+ }>;
226
+ recall_count?: number;
102
227
  /** memory_validation_failed (Phase 7). */
103
228
  error?: string;
104
229
  /** workflow_batch_spawned: per-node spawn descriptors (agent_id + goal + role/isolation). */
@@ -112,8 +237,9 @@ export interface KernelObservation {
112
237
  trust?: string;
113
238
  }>;
114
239
  /** workflow_completed. */
115
- completed?: string[];
116
- failed?: string[];
240
+ node_outcomes?: import("../types/agent.js").KernelWorkflowNodeOutcome[];
241
+ /** nodes_rejected. */
242
+ node_index?: number;
117
243
  score?: number;
118
244
  score_version?: number;
119
245
  rho?: number;
@@ -123,6 +249,19 @@ export interface KernelObservation {
123
249
  window_turns?: number;
124
250
  threshold?: number;
125
251
  }
252
+ export interface KernelStepJson {
253
+ version: number;
254
+ operation_id: string;
255
+ input_event_id: string;
256
+ step_seq: number;
257
+ actions: Array<Record<string, unknown>>;
258
+ observations: KernelObservation[];
259
+ faults?: Array<{
260
+ code?: string;
261
+ message?: string;
262
+ effect_id?: string;
263
+ }>;
264
+ }
126
265
  export declare function toolSchemaToKernel(schema: ToolSchema): Record<string, unknown>;
127
266
  export declare function skillMetadataToKernel(skill: SkillMetadata): Record<string, unknown>;
128
267
  export declare function messageToKernelMessage(message: Message): Record<string, unknown>;
@@ -135,6 +274,15 @@ export declare function capabilityCommandMount(capability: Record<string, unknow
135
274
  export declare function capabilityCommandUnmount(capabilityKind: string, id: string): Record<string, unknown>;
136
275
  /** Camel-case an `entropy_sample` kernel observation into the SDK's `EntropySample`. */
137
276
  export declare function entropySampleFromObservation(obs: KernelObservation): EntropySample;
277
+ /**
278
+ * Execute one production transition behind the durable action-publish gate. Genesis is persisted
279
+ * before prepare; a newly prepared transaction is CAS-appended before commit; only the committed
280
+ * step is returned to callers, so actions and observations cannot escape early.
281
+ */
282
+ export declare function durableKernelStep(runtime: KernelRuntimeHandle, sessionLog: SessionLog, sessionId: string, event: Record<string, unknown>): Promise<KernelStepJson>;
283
+ export declare function durableKernelApply(runtime: KernelRuntimeHandle, sessionLog: SessionLog, sessionId: string, pending: KernelObservation[], event: Record<string, unknown>): Promise<KernelObservation[]>;
284
+ export declare function durableKernelMaybeAction(runtime: KernelRuntimeHandle, sessionLog: SessionLog, sessionId: string, pending: KernelObservation[], event: Record<string, unknown>): Promise<KernelRunnerAction | null>;
285
+ export declare function durableKernelAction(runtime: KernelRuntimeHandle, sessionLog: SessionLog, sessionId: string, pending: KernelObservation[], event: Record<string, unknown>): Promise<KernelRunnerAction>;
138
286
  export declare function kernelApply(runtime: KernelRuntimeHandle, pending: KernelObservation[], event: Record<string, unknown>): KernelObservation[];
139
287
  export declare function kernelAction(runtime: KernelRuntimeHandle, pending: KernelObservation[], event: Record<string, unknown>): KernelRunnerAction;
140
288
  /**
@@ -143,4 +291,5 @@ export declare function kernelAction(runtime: KernelRuntimeHandle, pending: Kern
143
291
  * or ignores returns no action. Returns `null` in that case.
144
292
  */
145
293
  export declare function kernelMaybeAction(runtime: KernelRuntimeHandle, pending: KernelObservation[], event: Record<string, unknown>): KernelRunnerAction | null;
146
- export declare function forceCompact(runtime: KernelRuntimeHandle, pending: KernelObservation[]): boolean;
294
+ /** Internal ABI-v2 step primitive shared by SDK adapters and conformance tests. */
295
+ export declare function kernelStep(runtime: KernelRuntimeHandle, event: Record<string, unknown>): KernelStepJson;
@@ -1,4 +1,26 @@
1
- export const KERNEL_ABI_VERSION = 1;
1
+ import { createKernelOperationGenesis, createKernelTransaction, kernelRecordDigest, } from "./kernel-transaction-log.js";
2
+ export const KERNEL_ABI_VERSION = 2;
3
+ export function readKernelDiagnostics(runtime) {
4
+ return JSON.parse(runtime.diagnostics());
5
+ }
6
+ export function snapshotKernelRuntime(runtime) {
7
+ return JSON.parse(runtime.snapshot());
8
+ }
9
+ export function restoreKernelRuntime(runtime, snapshot) {
10
+ runtime.restore(JSON.stringify(snapshot));
11
+ const operationId = snapshot.operation_id;
12
+ if (!operationId) {
13
+ kernelWireStates.delete(runtime);
14
+ return;
15
+ }
16
+ const nextEventSequence = snapshot.accepted_inputs.reduce((next, input) => {
17
+ const match = input.event_id.match(/-event-(\d+)$/);
18
+ return match ? Math.max(next, Number(match[1]) + 1) : next;
19
+ }, 1);
20
+ kernelWireStates.set(runtime, { operationId, nextEventSequence });
21
+ }
22
+ let nextOperationSequence = 1;
23
+ const kernelWireStates = new WeakMap();
2
24
  function tryParseJson(s) {
3
25
  try {
4
26
  return JSON.parse(s);
@@ -223,10 +245,14 @@ function renderedContextToSdk(raw) {
223
245
  return ctx;
224
246
  }
225
247
  function mapKernelAction(raw) {
248
+ const effectId = String(raw.effect_id ?? "");
249
+ if (!effectId)
250
+ throw new Error(`kernel action ${String(raw.kind)} is missing effect_id`);
226
251
  switch (raw.kind) {
227
252
  case "call_provider":
228
253
  return {
229
254
  kind: "call_provider",
255
+ effectId,
230
256
  context: renderedContextToSdk(raw.context ?? {}),
231
257
  tools: (raw.tools ?? []).map(t => ({
232
258
  name: String(t.name ?? ""),
@@ -237,15 +263,77 @@ function mapKernelAction(raw) {
237
263
  case "execute_tool":
238
264
  return {
239
265
  kind: "execute_tool",
266
+ effectId,
240
267
  calls: (raw.calls ?? []).map(c => ({
241
268
  id: String(c.id ?? ""),
242
269
  name: String(c.name ?? ""),
243
270
  arguments: JSON.stringify(c.arguments ?? {}),
244
271
  })),
245
272
  };
273
+ case "request_approval":
274
+ return {
275
+ kind: "request_approval",
276
+ effectId,
277
+ requests: (raw.requests ?? []).map(request => ({
278
+ callId: String(request.call_id ?? ""),
279
+ tool: String(request.tool ?? ""),
280
+ arguments: JSON.stringify(request.arguments ?? {}),
281
+ reason: String(request.reason ?? ""),
282
+ })),
283
+ };
284
+ case "spawn_workflow":
285
+ return {
286
+ kind: "spawn_workflow",
287
+ effectId,
288
+ nodes: raw.nodes ?? [],
289
+ ...(raw.budget && typeof raw.budget === "object"
290
+ ? { budget: raw.budget }
291
+ : {}),
292
+ };
293
+ case "preempt_sub_agents":
294
+ return {
295
+ kind: "preempt_sub_agents",
296
+ effectId,
297
+ agentIds: raw.agent_ids ?? [],
298
+ reason: String(raw.reason ?? ""),
299
+ };
300
+ case "persist_memory":
301
+ return {
302
+ kind: "persist_memory",
303
+ effectId,
304
+ memory: raw.memory ?? {},
305
+ };
306
+ case "query_memory":
307
+ return {
308
+ kind: "query_memory",
309
+ effectId,
310
+ query: raw.query ?? {},
311
+ requestedK: Number(raw.requested_k ?? 0),
312
+ };
313
+ case "spool_large_result":
314
+ return {
315
+ kind: "spool_large_result",
316
+ effectId,
317
+ callId: String(raw.call_id ?? ""),
318
+ tool: String(raw.tool ?? ""),
319
+ output: String(raw.output ?? ""),
320
+ originalSize: Number(raw.original_size ?? 0),
321
+ previewSize: Number(raw.preview_size ?? 0),
322
+ };
323
+ case "archive_page_out":
324
+ return {
325
+ kind: "archive_page_out",
326
+ effectId,
327
+ turn: Number(raw.turn ?? 0),
328
+ action: String(raw.action ?? "auto_compact"),
329
+ ...(typeof raw.summary === "string" ? { summary: raw.summary } : {}),
330
+ archived: (raw.archived ?? []).map(kernelMessageToSdk),
331
+ tier: String(raw.tier ?? "durable"),
332
+ };
246
333
  case "evaluate_milestone":
247
334
  return {
248
335
  kind: "evaluate_milestone",
336
+ effectId,
249
337
  phaseId: String(raw.phase_id ?? ""),
250
338
  criteria: raw.criteria ?? [],
251
339
  verifier: raw.verifier,
@@ -256,6 +344,7 @@ function mapKernelAction(raw) {
256
344
  const pace = result.pace_decision;
257
345
  return {
258
346
  kind: "done",
347
+ effectId,
259
348
  result: {
260
349
  termination: String(result.termination ?? "error"),
261
350
  turnsUsed: Number(result.turns_used ?? 0),
@@ -278,11 +367,131 @@ function mapKernelAction(raw) {
278
367
  throw new Error(`unknown KernelAction kind: ${String(raw.kind)}`);
279
368
  }
280
369
  }
281
- function stepInput(event) {
282
- return JSON.stringify({ version: KERNEL_ABI_VERSION, event });
370
+ function stepInput(runtime, event) {
371
+ let state = kernelWireStates.get(runtime);
372
+ if (!state) {
373
+ state = {
374
+ operationId: `node-operation-${nextOperationSequence++}`,
375
+ nextEventSequence: 1,
376
+ };
377
+ kernelWireStates.set(runtime, state);
378
+ }
379
+ const correlatedEvent = event.kind === "cancel_operation"
380
+ ? { ...event, operation_id: state.operationId }
381
+ : event;
382
+ return JSON.stringify({
383
+ version: KERNEL_ABI_VERSION,
384
+ operation_id: state.operationId,
385
+ event_id: `${state.operationId}-event-${state.nextEventSequence++}`,
386
+ observed_at_ms: Date.now(),
387
+ event: correlatedEvent,
388
+ });
389
+ }
390
+ const durableKernelStates = new WeakMap();
391
+ /**
392
+ * Execute one production transition behind the durable action-publish gate. Genesis is persisted
393
+ * before prepare; a newly prepared transaction is CAS-appended before commit; only the committed
394
+ * step is returned to callers, so actions and observations cannot escape early.
395
+ */
396
+ export async function durableKernelStep(runtime, sessionLog, sessionId, event) {
397
+ const inputJson = stepInput(runtime, event);
398
+ const input = JSON.parse(inputJson);
399
+ const operationId = String(input.operation_id ?? "");
400
+ if (!operationId)
401
+ throw new Error("kernel input is missing operation_id");
402
+ let durableState = durableKernelStates.get(runtime);
403
+ if (!durableState) {
404
+ const snapshot = snapshotKernelRuntime(runtime);
405
+ const genesis = await createKernelOperationGenesis({
406
+ abi_version: KERNEL_ABI_VERSION,
407
+ operation_id: operationId,
408
+ initial_scheduler_policy: snapshot.initial_policy,
409
+ resolved_runtime_defaults: {
410
+ snapshot_version: snapshot.snapshot_version,
411
+ snapshot_input_limit: snapshot.snapshot_input_limit,
412
+ max_input_bytes: snapshot.max_input_bytes,
413
+ snapshot_journal_bytes_limit: snapshot.snapshot_journal_bytes_limit,
414
+ },
415
+ default_policy_version: 1,
416
+ });
417
+ const receipt = await sessionLog.appendKernelGenesis(sessionId, genesis);
418
+ durableState = {
419
+ sessionId,
420
+ operationId,
421
+ genesisDigest: receipt.genesis_digest,
422
+ };
423
+ durableKernelStates.set(runtime, durableState);
424
+ }
425
+ else if (durableState.sessionId !== sessionId || durableState.operationId !== operationId) {
426
+ throw new Error("kernel runtime cannot change its durable session or operation identity");
427
+ }
428
+ const prepared = JSON.parse(runtime.prepareStep(inputJson));
429
+ if (prepared.status !== "prepared")
430
+ return prepared.step;
431
+ const token = prepared.prepare_token;
432
+ if (!token)
433
+ throw new Error("prepared kernel transition is missing its commit token");
434
+ let committed = false;
435
+ try {
436
+ const head = await sessionLog.kernelTransactionHead(sessionId, operationId);
437
+ if (!head)
438
+ throw new Error("durable kernel genesis is missing before transaction append");
439
+ const transaction = await createKernelTransaction({
440
+ operation_id: operationId,
441
+ step_seq: prepared.step.step_seq,
442
+ base_generation: prepared.base_generation,
443
+ input: prepared.input,
444
+ step: prepared.step,
445
+ previous_transaction_digest: head,
446
+ });
447
+ await sessionLog.compareAndAppendKernelTransaction(sessionId, head, transaction);
448
+ const committedStep = parseStep(runtime.commitPrepared(token));
449
+ committed = true;
450
+ if (kernelRecordDigest(committedStep) !== transaction.step_digest) {
451
+ throw new Error("committed kernel step does not match the durable prepared step");
452
+ }
453
+ return committedStep;
454
+ }
455
+ catch (transitionError) {
456
+ if (!committed) {
457
+ try {
458
+ runtime.abortPrepared(token);
459
+ }
460
+ catch (abortError) {
461
+ throw new AggregateError([transitionError, abortError], "durable transition failed and the prepared kernel state could not be aborted");
462
+ }
463
+ }
464
+ throw transitionError;
465
+ }
466
+ }
467
+ export async function durableKernelApply(runtime, sessionLog, sessionId, pending, event) {
468
+ const step = await durableKernelStep(runtime, sessionLog, sessionId, event);
469
+ const fault = step.faults?.[0];
470
+ if (fault)
471
+ throw new Error(`${fault.code ?? "kernel_fault"}: ${fault.message ?? "kernel transition failed"}`);
472
+ pending.push(...step.observations);
473
+ return step.observations;
474
+ }
475
+ export async function durableKernelMaybeAction(runtime, sessionLog, sessionId, pending, event) {
476
+ const step = await durableKernelStep(runtime, sessionLog, sessionId, event);
477
+ const fault = step.faults?.[0];
478
+ if (fault)
479
+ throw new Error(`${fault.code ?? "kernel_fault"}: ${fault.message ?? "kernel transition failed"}`);
480
+ pending.push(...step.observations);
481
+ const raw = step.actions[0];
482
+ return raw ? mapKernelAction(raw) : null;
483
+ }
484
+ export async function durableKernelAction(runtime, sessionLog, sessionId, pending, event) {
485
+ const action = await durableKernelMaybeAction(runtime, sessionLog, sessionId, pending, event);
486
+ if (!action)
487
+ throw new Error("kernel transition must return one action");
488
+ return action;
283
489
  }
284
490
  export function kernelApply(runtime, pending, event) {
285
- const step = parseStep(runtime.step(stepInput(event)));
491
+ const step = kernelStep(runtime, event);
492
+ const fault = step.faults?.[0];
493
+ if (fault)
494
+ throw new Error(`${fault.code ?? "kernel_fault"}: ${fault.message ?? "kernel transition failed"}`);
286
495
  pending.push(...step.observations);
287
496
  return step.observations;
288
497
  }
@@ -298,11 +507,15 @@ export function kernelAction(runtime, pending, event) {
298
507
  * or ignores returns no action. Returns `null` in that case.
299
508
  */
300
509
  export function kernelMaybeAction(runtime, pending, event) {
301
- const step = parseStep(runtime.step(stepInput(event)));
510
+ const step = kernelStep(runtime, event);
511
+ const fault = step.faults?.[0];
512
+ if (fault)
513
+ throw new Error(`${fault.code ?? "kernel_fault"}: ${fault.message ?? "kernel transition failed"}`);
302
514
  pending.push(...step.observations);
303
515
  const raw = step.actions[0];
304
516
  return raw ? mapKernelAction(raw) : null;
305
517
  }
306
- export function forceCompact(runtime, pending) {
307
- return kernelApply(runtime, pending, { kind: "force_compact" }).some(o => o.kind === "compressed");
518
+ /** Internal ABI-v2 step primitive shared by SDK adapters and conformance tests. */
519
+ export function kernelStep(runtime, event) {
520
+ return parseStep(runtime.step(stepInput(runtime, event)));
308
521
  }
@@ -0,0 +1,61 @@
1
+ export declare const KERNEL_LOG_RECORD_VERSION: 1;
2
+ export interface KernelOperationGenesisBody {
3
+ record_version: typeof KERNEL_LOG_RECORD_VERSION;
4
+ abi_version: number;
5
+ operation_id: string;
6
+ initial_scheduler_policy: Record<string, unknown>;
7
+ resolved_runtime_defaults: Record<string, unknown>;
8
+ default_policy_version: number;
9
+ }
10
+ export interface KernelOperationGenesis extends KernelOperationGenesisBody {
11
+ genesis_digest: string;
12
+ }
13
+ export interface KernelTransactionBody {
14
+ record_version: typeof KERNEL_LOG_RECORD_VERSION;
15
+ operation_id: string;
16
+ step_seq: number;
17
+ base_generation: number;
18
+ input: Record<string, unknown>;
19
+ input_digest: string;
20
+ previous_transaction_digest: string;
21
+ step_digest: string;
22
+ }
23
+ export interface KernelTransaction extends KernelTransactionBody {
24
+ transaction_digest: string;
25
+ }
26
+ export interface KernelGenesisReceipt {
27
+ log_seq: number;
28
+ genesis_digest: string;
29
+ }
30
+ export interface DurableAppendReceipt {
31
+ log_seq: number;
32
+ transaction_digest: string;
33
+ }
34
+ export interface KernelOperationCursor {
35
+ operation_id: string;
36
+ next_event_sequence: number;
37
+ next_step_seq: number;
38
+ transaction_head_digest: string;
39
+ }
40
+ export declare class KernelLogConflictError extends Error {
41
+ constructor(message: string);
42
+ }
43
+ export declare class KernelLogIntegrityError extends Error {
44
+ constructor(message: string);
45
+ }
46
+ export declare function canonicalKernelJson(value: unknown): string;
47
+ export declare function kernelRecordDigest(value: unknown): string;
48
+ export declare function createKernelOperationGenesis(input: Omit<KernelOperationGenesisBody, "record_version">): Promise<KernelOperationGenesis>;
49
+ export declare function createKernelTransaction(input: {
50
+ operation_id: string;
51
+ step_seq: number;
52
+ base_generation: number;
53
+ input: Record<string, unknown>;
54
+ step: Record<string, unknown>;
55
+ previous_transaction_digest: string;
56
+ }): Promise<KernelTransaction>;
57
+ export declare function verifyKernelOperationGenesis(genesis: KernelOperationGenesis): void;
58
+ export declare function verifyKernelTransaction(transaction: KernelTransaction): void;
59
+ export declare function verifyKernelTransactionSuccessor(previous: KernelTransaction | undefined, transaction: KernelTransaction): void;
60
+ /** Validate one complete authoritative operation stream and derive its next wire cursor. */
61
+ export declare function verifyKernelTransactionStream(genesis: KernelOperationGenesis, transactions: readonly KernelTransaction[]): KernelOperationCursor;