@deepstrike/wasm 0.2.69 → 0.2.70

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 (38) hide show
  1. package/dist/index.d.ts +6 -1
  2. package/dist/index.js +2 -0
  3. package/dist/providers/anthropic.d.ts +8 -5
  4. package/dist/providers/anthropic.js +12 -1
  5. package/dist/providers/base.d.ts +5 -5
  6. package/dist/providers/base.js +1 -1
  7. package/dist/providers/openai.d.ts +6 -4
  8. package/dist/providers/openai.js +28 -24
  9. package/dist/providers/prepared-request.d.ts +4 -0
  10. package/dist/providers/prepared-request.js +78 -0
  11. package/dist/providers/request-plan.d.ts +8 -1
  12. package/dist/providers/request-plan.js +4 -3
  13. package/dist/runtime/canonical-kernel-step.d.ts +4 -3
  14. package/dist/runtime/canonical-kernel-step.js +16 -7
  15. package/dist/runtime/context.d.ts +28 -0
  16. package/dist/runtime/context.js +16 -0
  17. package/dist/runtime/eval.d.ts +2 -2
  18. package/dist/runtime/evolution.d.ts +189 -0
  19. package/dist/runtime/evolution.js +25 -0
  20. package/dist/runtime/kernel-step.d.ts +8 -7
  21. package/dist/runtime/provider-replay.d.ts +2 -2
  22. package/dist/runtime/provider-replay.js +1 -1
  23. package/dist/runtime/replay-fixture.d.ts +4 -4
  24. package/dist/runtime/replay-fixture.js +2 -2
  25. package/dist/runtime/replay-provider.d.ts +3 -3
  26. package/dist/runtime/runner.d.ts +8 -6
  27. package/dist/runtime/runner.js +22 -5
  28. package/dist/runtime/session-log.d.ts +9 -4
  29. package/dist/runtime/session-log.js +1 -0
  30. package/dist/runtime/session-repair.d.ts +3 -4
  31. package/dist/runtime/session-repair.js +1 -4
  32. package/dist/runtime/sub-agent-orchestrator.js +1 -1
  33. package/dist/runtime/types/agent.d.ts +4 -4
  34. package/dist/runtime/verifiable-report.d.ts +2 -2
  35. package/dist/runtime/verifiable-report.js +2 -2
  36. package/dist/tools/index.d.ts +2 -2
  37. package/dist/types.d.ts +19 -10
  38. package/package.json +2 -2
@@ -0,0 +1,189 @@
1
+ export type ArtifactKind = "runtime" | "skill" | "prompt" | "policy" | "toolset" | "bundle";
2
+ export interface ArtifactRef {
3
+ readonly kind: ArtifactKind;
4
+ readonly digest: string;
5
+ }
6
+ export interface ArtifactManifest {
7
+ readonly kind: ArtifactKind;
8
+ readonly payload_digest: string;
9
+ readonly parents: readonly string[];
10
+ readonly toolchain_digest: string;
11
+ readonly scope: string;
12
+ }
13
+ export interface ArtifactVersion {
14
+ readonly digest: string;
15
+ readonly manifest: ArtifactManifest;
16
+ }
17
+ export interface ArtifactSet {
18
+ readonly digest: string;
19
+ readonly artifacts: readonly ArtifactRef[];
20
+ }
21
+ export interface EvolutionProposal {
22
+ readonly digest: string;
23
+ readonly base_artifact_set: string;
24
+ readonly candidate_artifact_set: string;
25
+ readonly objective: string;
26
+ readonly change_manifest: string;
27
+ readonly proposer: string;
28
+ readonly constraints: readonly string[];
29
+ }
30
+ export interface EvaluationContextBinding {
31
+ readonly digest: string;
32
+ readonly operation_id: string;
33
+ readonly execution_input: string;
34
+ readonly context_state: string;
35
+ readonly context_policy: string;
36
+ readonly context_plan: string;
37
+ readonly rendered_snapshot: string;
38
+ readonly prompt_measurement: string;
39
+ readonly provider_route: string;
40
+ readonly cache_prefix?: string;
41
+ }
42
+ export type ContextEntrySource = "system" | "knowledge" | "history" | "state" | "signal";
43
+ export type ContextPlanAction = "include" | "excerpt" | "collapse" | "page_out" | "omit";
44
+ export interface ContextEntryRef {
45
+ readonly entry_id: string;
46
+ readonly content_digest: string;
47
+ readonly source: ContextEntrySource;
48
+ readonly ordinal: number;
49
+ }
50
+ export interface ContextState {
51
+ readonly schema: "context/v1";
52
+ readonly generation: number;
53
+ readonly system: readonly ContextEntryRef[];
54
+ readonly knowledge: readonly ContextEntryRef[];
55
+ readonly history: readonly ContextEntryRef[];
56
+ readonly state: readonly ContextEntryRef[];
57
+ readonly task_state: string;
58
+ readonly signals: readonly string[];
59
+ readonly digest: string;
60
+ }
61
+ export interface ContextSelection {
62
+ readonly entry_id: string;
63
+ readonly action: ContextPlanAction;
64
+ readonly reason: string;
65
+ }
66
+ export interface ContextPlan {
67
+ readonly schema: "context/v1";
68
+ readonly plan_id: string;
69
+ readonly operation_id: string;
70
+ readonly step_id: string;
71
+ readonly state_digest: string;
72
+ readonly state_generation: number;
73
+ readonly runtime_inputs: string;
74
+ readonly policy_digest: string;
75
+ readonly provider_profile_digest: string;
76
+ readonly measurement_fingerprints: readonly string[];
77
+ readonly selections: readonly ContextSelection[];
78
+ readonly input_budget_tokens: number;
79
+ readonly projected_tokens: number;
80
+ readonly pressure_ppm: number;
81
+ readonly cache_prefix: {
82
+ readonly digest: string;
83
+ readonly entries: number;
84
+ } | null;
85
+ }
86
+ export interface ContextExecutionInput {
87
+ readonly schema: "context/v1";
88
+ readonly input_digest: string;
89
+ readonly operation_id: string;
90
+ readonly step_id: string;
91
+ readonly input_sequence: number;
92
+ readonly state_digest: string;
93
+ readonly policy_digest: string;
94
+ readonly plan_digest: string;
95
+ readonly rendered_snapshot: string;
96
+ readonly prompt_measurement: string;
97
+ readonly provider_route: string;
98
+ readonly cache_prefix: {
99
+ readonly digest: string;
100
+ readonly entries: number;
101
+ } | null;
102
+ }
103
+ export interface ContextPreparationRequest {
104
+ readonly operation_id: string;
105
+ readonly step_id: string;
106
+ readonly input_sequence: number;
107
+ readonly policy_digest: string;
108
+ readonly prompt_measurement: string;
109
+ readonly provider_route: string;
110
+ }
111
+ export interface EvaluationRun {
112
+ readonly digest: string;
113
+ readonly proposal: string;
114
+ readonly baseline_artifact_set: string;
115
+ readonly candidate_artifact_set: string;
116
+ readonly evaluator: string;
117
+ readonly dataset: string;
118
+ readonly operation_ids: readonly string[];
119
+ readonly contexts: readonly EvaluationContextBinding[];
120
+ readonly evidence_refs: readonly string[];
121
+ }
122
+ export interface EvaluationMetric {
123
+ readonly name: string;
124
+ readonly baseline: string;
125
+ readonly candidate: string;
126
+ readonly improved: boolean;
127
+ }
128
+ export interface EvaluationGate {
129
+ readonly name: string;
130
+ readonly required: boolean;
131
+ readonly passed: boolean;
132
+ }
133
+ export interface EvaluationFact {
134
+ readonly digest: string;
135
+ readonly evaluation: string;
136
+ readonly metrics: readonly EvaluationMetric[];
137
+ readonly gates: readonly EvaluationGate[];
138
+ readonly replay_passed: boolean;
139
+ }
140
+ export type PromotionOutcome = "promote" | "reject" | "hold";
141
+ export interface PromotionDecision {
142
+ readonly digest: string;
143
+ readonly proposal: string;
144
+ readonly evaluation_facts: readonly string[];
145
+ readonly policy: string;
146
+ readonly outcome: PromotionOutcome;
147
+ readonly selected_artifact_set: string;
148
+ }
149
+ export interface ActivationBinding {
150
+ readonly digest: string;
151
+ readonly operation_id: string;
152
+ readonly artifact_set: string;
153
+ readonly promotion_decision: string;
154
+ }
155
+ export interface EvolutionBundle {
156
+ readonly artifacts: readonly ArtifactVersion[];
157
+ readonly artifact_sets: readonly ArtifactSet[];
158
+ readonly proposals: readonly EvolutionProposal[];
159
+ readonly evaluations: readonly EvaluationRun[];
160
+ readonly facts: readonly EvaluationFact[];
161
+ readonly decisions: readonly PromotionDecision[];
162
+ readonly activations: readonly ActivationBinding[];
163
+ }
164
+ export type EvolutionVerdict = "pass" | "fail" | "unavailable";
165
+ export interface EvolutionReport {
166
+ readonly schema: "evolution-report/v1";
167
+ readonly verdict: EvolutionVerdict;
168
+ readonly violations: readonly {
169
+ readonly code: string;
170
+ readonly detail: string;
171
+ }[];
172
+ }
173
+ export type EvolutionValidateJson = (request: string) => string;
174
+ export interface EvolutionStore {
175
+ loadBundle(): Promise<EvolutionBundle> | EvolutionBundle;
176
+ }
177
+ export declare function createEvolutionRuntimeAdapter(validateJson: EvolutionValidateJson): {
178
+ validate: (bundle: EvolutionBundle) => EvolutionReport;
179
+ };
180
+ export declare function createNativeEvolutionRuntimeAdapter(): Promise<{
181
+ validate: (bundle: EvolutionBundle) => EvolutionReport;
182
+ }>;
183
+ export declare class EvolutionRuntime {
184
+ private readonly adapter;
185
+ constructor(adapter: ReturnType<typeof createEvolutionRuntimeAdapter>);
186
+ validate(bundle: EvolutionBundle): EvolutionReport;
187
+ validateStore(store: EvolutionStore): Promise<EvolutionReport>;
188
+ activate(bundle: EvolutionBundle, operationId: string): ActivationBinding;
189
+ }
@@ -0,0 +1,25 @@
1
+ import { getKernel } from "./kernel.js";
2
+ export function createEvolutionRuntimeAdapter(validateJson) {
3
+ return { validate: (bundle) => JSON.parse(validateJson(JSON.stringify(bundle))) };
4
+ }
5
+ export async function createNativeEvolutionRuntimeAdapter() {
6
+ const kernel = await getKernel();
7
+ return createEvolutionRuntimeAdapter(kernel.evolutionValidateJson);
8
+ }
9
+ export class EvolutionRuntime {
10
+ adapter;
11
+ constructor(adapter) {
12
+ this.adapter = adapter;
13
+ }
14
+ validate(bundle) { return this.adapter.validate(bundle); }
15
+ async validateStore(store) { return this.validate(await store.loadBundle()); }
16
+ activate(bundle, operationId) {
17
+ const report = this.validate(bundle);
18
+ if (report.verdict !== "pass")
19
+ throw new Error(`evolution bundle is not activatable: ${report.violations.map(v => v.code).join(", ")}`);
20
+ const activation = bundle.activations.find(value => value.operation_id === operationId);
21
+ if (!activation)
22
+ throw new Error(`no verified activation binding for operation ${operationId}`);
23
+ return activation;
24
+ }
25
+ }
@@ -1,4 +1,4 @@
1
- import type { Message, RenderedContext, ToolCall, ToolResult, ToolSchema } from "../types.js";
1
+ import type { ProviderMessage, RenderedContext, ToolCall, ToolExecutionResult, ToolSchema } from "../types.js";
2
2
  import type { RollbackReason } from "./session-log.js";
3
3
  interface TaskUpdate {
4
4
  plan?: string[];
@@ -15,7 +15,7 @@ interface SkillMetadata {
15
15
  effort?: number;
16
16
  estimatedTokens?: number;
17
17
  /** P1-B tool gating: tool ids this skill needs; when active the kernel narrows the toolset to
18
- * `stable-core ∪ allowedTools`. Absent ⇒ no narrowing (back-compat). */
18
+ * `stable-core ∪ allowedTools`. Absent ⇒ no narrowing. */
19
19
  allowedTools?: string[];
20
20
  }
21
21
  export declare const CANONICAL_CONTENT_PARTS_PREFIX = "[[deepstrike-content-parts]]";
@@ -41,7 +41,7 @@ export interface KernelLoopResult {
41
41
  termination: string;
42
42
  turnsUsed: number;
43
43
  totalTokensUsed: number;
44
- finalMessage?: Message;
44
+ finalMessage?: ProviderMessage;
45
45
  /** ③ loop-agent: the kernel-adjudicated after-round decision (absent on non-loop runs). */
46
46
  paceDecision?: PaceDecision;
47
47
  }
@@ -50,6 +50,7 @@ export type KernelRunnerAction = {
50
50
  effectId: string;
51
51
  context: RenderedContext;
52
52
  tools: ToolSchema[];
53
+ contextEffect: Record<string, unknown>;
53
54
  } | {
54
55
  kind: "execute_tool";
55
56
  effectId: string;
@@ -89,7 +90,7 @@ export type KernelRunnerAction = {
89
90
  } | {
90
91
  kind: "archive_page_out";
91
92
  effectId: string;
92
- archived: Message[];
93
+ archived: ProviderMessage[];
93
94
  handleId?: string;
94
95
  payload?: {
95
96
  content: string;
@@ -218,12 +219,12 @@ export declare function archivePresentationFromObservations(observations: readon
218
219
  };
219
220
  export declare function toolSchemaToKernel(schema: ToolSchema): Record<string, unknown>;
220
221
  export declare function skillMetadataToKernel(skill: SkillMetadata): Record<string, unknown>;
221
- export declare function messageToKernelMessage(message: Message): Record<string, unknown>;
222
- export declare function toolResultToKernel(result: ToolResult): Record<string, unknown>;
222
+ export declare function messageToKernelMessage(message: ProviderMessage): Record<string, unknown>;
223
+ export declare function toolResultToKernel(result: ToolExecutionResult): Record<string, unknown>;
223
224
  export declare function taskUpdateToKernel(update: TaskUpdate): Record<string, unknown>;
224
225
  export declare function capabilityTool(schema: ToolSchema): Record<string, unknown>;
225
226
  export declare function capabilitySkill(skill: SkillMetadata): Record<string, unknown>;
226
227
  export declare function capabilityMarker(kind: string, id: string, description: string): Record<string, unknown>;
227
- export declare function kernelMessageToSdk(raw: Record<string, unknown>): Message;
228
+ export declare function kernelMessageToSdk(raw: Record<string, unknown>): ProviderMessage;
228
229
  export declare function renderedContextToSdk(raw: Record<string, unknown>): RenderedContext;
229
230
  export {};
@@ -1,6 +1,6 @@
1
- import type { LLMProvider, Message, ProviderDescriptor, ProviderReplay, ToolCall } from "../types.js";
1
+ import type { LLMProvider, ProviderMessage, ProviderDescriptor, ProviderReplay, ToolCall } from "../types.js";
2
2
  import type { SessionEvent } from "./session-log.js";
3
- export declare function assistantReplayKey(message: Pick<Message, "content" | "toolCalls">): string;
3
+ export declare function assistantReplayKey(message: Pick<ProviderMessage, "content" | "toolCalls">): string;
4
4
  /**
5
5
  * A stored replay may only be seeded into a provider speaking the same wire
6
6
  * protocol; on a cross-protocol fallback the incompatible envelope is skipped so
@@ -29,7 +29,7 @@ export function seedProviderReplayFromEvents(provider, events) {
29
29
  if (event.kind !== "llm_completed")
30
30
  continue;
31
31
  const toolCalls = event.tool_calls ?? [];
32
- const stored = event.provider_replay;
32
+ const stored = event.wire_evidence?.replay_state;
33
33
  if (!stored || !isReplayCompatibleWithProvider(stored, descriptor))
34
34
  continue;
35
35
  provider.seedProviderReplay({ content: event.content, toolCalls }, stored);
@@ -6,20 +6,20 @@
6
6
  * pulls the assistant turns in order, so the fixture is just "a prior session log + the messages
7
7
  * the LLM produced". No new on-disk format.
8
8
  */
9
- import type { Message } from "../types.js";
9
+ import type { ProviderMessage } from "../types.js";
10
10
  import type { SessionEvent } from "./session-log.js";
11
11
  /**
12
12
  * Extract the ordered list of assistant Messages from a recorded session log.
13
13
  *
14
14
  * Walks `llm_completed` events (which is what the runner appends for every LLM call) and produces
15
- * one Message per event. Pass the result directly to `new ReplayProvider(messages)`.
15
+ * one ProviderMessage per event. Pass the result directly to `new ReplayProvider(messages)`.
16
16
  *
17
17
  * Accepts both camelCase and snake_case tool-call wire shapes. Token usage remains session
18
- * evidence; the returned public Message mirror carries no token projection.
18
+ * evidence; the returned public ProviderMessage mirror carries no token projection.
19
19
  *
20
20
  * @param events Session events, in original order. Accepts both `{ event, seq }` (the shape
21
21
  * `SessionLog.read()` returns) and a bare `SessionEvent[]`.
22
22
  */
23
23
  export declare function extractRecordedMessages(events: Array<{
24
24
  event: SessionEvent;
25
- } | SessionEvent>): Message[];
25
+ } | SessionEvent>): ProviderMessage[];
@@ -10,10 +10,10 @@
10
10
  * Extract the ordered list of assistant Messages from a recorded session log.
11
11
  *
12
12
  * Walks `llm_completed` events (which is what the runner appends for every LLM call) and produces
13
- * one Message per event. Pass the result directly to `new ReplayProvider(messages)`.
13
+ * one ProviderMessage per event. Pass the result directly to `new ReplayProvider(messages)`.
14
14
  *
15
15
  * Accepts both camelCase and snake_case tool-call wire shapes. Token usage remains session
16
- * evidence; the returned public Message mirror carries no token projection.
16
+ * evidence; the returned public ProviderMessage mirror carries no token projection.
17
17
  *
18
18
  * @param events Session events, in original order. Accepts both `{ event, seq }` (the shape
19
19
  * `SessionLog.read()` returns) and a bare `SessionEvent[]`.
@@ -23,7 +23,7 @@
23
23
  * Tokenizer: by default a `chars/4` estimator (±20% for English; worse for code/JSON). For tighter
24
24
  * numbers plug `opts.tokenizer = tiktokenEncoder` or similar.
25
25
  */
26
- import type { LLMProvider, Message, ProviderDescriptor, ProviderRunState, RenderedContext, StreamEvent, ToolSchema } from "../types.js";
26
+ import type { LLMProvider, ProviderMessage, ProviderDescriptor, ProviderRunState, RenderedContext, StreamEvent, ToolSchema } from "../types.js";
27
27
  export interface ReplayProviderOpts {
28
28
  /**
29
29
  * Maps a rendered-context text payload to a token count. Defaults to `chars / 4`.
@@ -53,7 +53,7 @@ export declare class ReplayProvider implements LLMProvider {
53
53
  * @param messages Ordered list of assistant messages to replay (one per LLM call).
54
54
  * @param opts Optional tokenizer / descriptor / wrap-around behavior.
55
55
  */
56
- constructor(messages: ReadonlyArray<Message>, opts?: ReplayProviderOpts);
56
+ constructor(messages: ReadonlyArray<ProviderMessage>, opts?: ReplayProviderOpts);
57
57
  descriptor(): ProviderDescriptor;
58
58
  /** Number of messages consumed so far. */
59
59
  consumed(): number;
@@ -61,7 +61,7 @@ export declare class ReplayProvider implements LLMProvider {
61
61
  remaining(): number;
62
62
  /** Reset the cursor — useful for re-running the same fixture in a fresh session. */
63
63
  reset(): void;
64
- complete(_context: RenderedContext, _tools: ToolSchema[]): Promise<Message>;
64
+ complete(_context: RenderedContext, _tools: ToolSchema[]): Promise<ProviderMessage>;
65
65
  stream(context: RenderedContext, tools: ToolSchema[], _extensions?: Record<string, unknown>, _state?: ProviderRunState, _signal?: AbortSignal): AsyncIterable<StreamEvent>;
66
66
  private pull;
67
67
  private estimateInputTokens;
@@ -1,4 +1,4 @@
1
- import type { LLMProvider, Message, StreamEvent, PermissionRequestEvent, PermissionResponse, EntropySample, EntropyWatchOptions, MemorySummarizer } from "../types.js";
1
+ import type { LLMProvider, ProviderMessage, StreamEvent, PermissionRequestEvent, PermissionResponse, EntropySample, EntropyWatchOptions, MemorySummarizer } from "../types.js";
2
2
  import type { ToolSuspendEvent } from "./execution-plane.js";
3
3
  import type { MemoryStore, MemoryQuery, MemoryRecord, MemoryScope } from "../memory/index.js";
4
4
  import type { KnowledgeSource } from "../knowledge/index.js";
@@ -65,8 +65,8 @@ export interface KernelReliabilityOptions {
65
65
  maxInputBytes?: number;
66
66
  }
67
67
  export interface ArchiveStore {
68
- write(sessionId: string, startSeq: number, messages: Message[]): Promise<string | undefined>;
69
- read?(archiveRef: string): Promise<Message[]>;
68
+ write(sessionId: string, startSeq: number, messages: ProviderMessage[]): Promise<string | undefined>;
69
+ read?(archiveRef: string): Promise<ProviderMessage[]>;
70
70
  }
71
71
  /** P0-C tool-gating telemetry: per-LLM-turn metrics, emitted via `RuntimeOptions.onTurnMetrics`.
72
72
  * Pure observation — no behavior change. `toolsExposed` vs `toolsCalled` quantifies over-exposure;
@@ -99,7 +99,9 @@ export interface ToolResultHookDecision {
99
99
  }
100
100
  export interface RuntimeOptions {
101
101
  provider: LLMProvider;
102
- /** Required for ABI-v3 operation recovery unless the SessionLog embeds one. */
102
+ /** Host-owned artifact set identity captured in operation genesis. */
103
+ artifactSetDigest?: string;
104
+ /** Required for ABI operation recovery unless the SessionLog embeds one. */
103
105
  kernelJournal?: KernelJournal;
104
106
  /** M1/G3 intelligence routing: resolve a per-node provider from a workflow node's `modelHint`.
105
107
  * Returns undefined ⇒ fall back to `provider`. Without this hook the hint is a no-op. */
@@ -342,7 +344,7 @@ export declare class RuntimeRunner {
342
344
  * K1: `opts.key` gives the entry identity — a same-key push upserts (applied at the next
343
345
  * compaction/renewal boundary) instead of appending a duplicate. `opts.pinned` exempts the
344
346
  * entry from the knowledge-budget sweep. */
345
- pushKnowledge(message: Message, tokens?: number, opts?: {
347
+ pushKnowledge(message: ProviderMessage, tokens?: number, opts?: {
346
348
  key?: string;
347
349
  pinned?: boolean;
348
350
  }): Promise<void>;
@@ -414,5 +416,5 @@ export declare class RuntimeRunner {
414
416
  export declare function replayMessages(events: Array<{
415
417
  seq: number;
416
418
  event: SessionEvent;
417
- }>, maxBytes?: number, archiveStore?: ArchiveStore): Promise<Message[]>;
419
+ }>, maxBytes?: number, archiveStore?: ArchiveStore): Promise<ProviderMessage[]>;
418
420
  export declare function collectText(stream: AsyncIterable<StreamEvent>): Promise<string>;
@@ -1,3 +1,5 @@
1
+ import { prepareProviderRequest } from "../providers/prepared-request.js";
2
+ import { createNativeContextPreparationAdapter } from "./context.js";
1
3
  import { extractSessionMemories } from "../memory/extraction.js";
2
4
  import { resolvePermissionRequest } from "./execution-plane.js";
3
5
  import { governancePolicyToKernelEvent, governanceFilterSchema } from "../governance.js";
@@ -168,6 +170,7 @@ export class RuntimeRunner {
168
170
  maxTurns: this.opts.maxTurns,
169
171
  maxTotalTokens: this.opts.maxTotalTokens,
170
172
  maxWallMs: this.opts.timeoutMs,
173
+ artifactSetDigest: this.opts.artifactSetDigest,
171
174
  memoryBindingId: `wasm-memory-${this.opts.agentId ?? "root"}`,
172
175
  persistPayload: async (_callId, content, previewBytes) => {
173
176
  const digest = canonicalSha256(content);
@@ -703,12 +706,15 @@ export class RuntimeRunner {
703
706
  let turnCacheCreationTokens = 0;
704
707
  let turnCacheReadBySlot;
705
708
  let turnStopReason;
706
- const providerPlan = createProviderRequestPlanForProvider(this.opts.provider, context, tools, ext);
709
+ const preparedRequest = prepareProviderRequest(this.opts.provider, context, tools, ext, providerState);
710
+ const providerPlan = createProviderRequestPlanForProvider(this.opts.provider, context, tools, ext, {
711
+ scope: preparedRequest.scope, request: preparedRequest.request, state: preparedRequest.state,
712
+ });
707
713
  let promptMeasurement = measurementForPlan(providerPlan, recordedMeasurements.get(providerPlan.fingerprint));
708
714
  if (!promptMeasurement && !context.budgetOverflow) {
709
715
  try {
710
- const counted = this.opts.provider.countTokens
711
- ? await withTimeout(this.opts.provider.countTokens(context, tools, Object.keys(ext).length ? ext : undefined), 5_000)
716
+ const counted = preparedRequest.countTokens
717
+ ? await withTimeout(preparedRequest.countTokens(), 5_000)
712
718
  : undefined;
713
719
  promptMeasurement = recordPromptMeasurement(providerPlan, counted ?? {
714
720
  inputTokens: estimateProviderPromptTokens(context, tools),
@@ -758,9 +764,21 @@ export class RuntimeRunner {
758
764
  this.providerRetryPending = action.kind === "call_provider";
759
765
  continue;
760
766
  }
767
+ if (!promptMeasurement)
768
+ throw new Error("context preparation requires prompt measurement");
769
+ const contextAdapter = await createNativeContextPreparationAdapter();
770
+ const preparation = contextAdapter.prepare({
771
+ effect: action.contextEffect,
772
+ request_fingerprint: providerPlan.fingerprint,
773
+ provider_route: { ...this.providerRoute, request_fingerprint_scope: preparedRequest.scope },
774
+ prompt_measurement: promptMeasurement,
775
+ });
776
+ await this.opts.sessionLog.append(sessionId, {
777
+ kind: "context_prepared", turn: runtime.turn(), effect_id: providerEffectId, preparation,
778
+ });
761
779
  const abortSignal = this.abortController?.signal;
762
780
  try {
763
- for await (const evt of this.opts.provider.stream(context, tools, Object.keys(ext).length ? ext : undefined, providerState, abortSignal)) {
781
+ for await (const evt of preparedRequest.stream(abortSignal)) {
764
782
  // #2-B-ii: a preempting interrupt fires abortController — stop consuming the live stream.
765
783
  if (abortSignal?.aborted)
766
784
  break;
@@ -919,7 +937,6 @@ export class RuntimeRunner {
919
937
  turn: runtime.turn(),
920
938
  content: finalText,
921
939
  toolCalls: finalToolCalls,
922
- providerReplay,
923
940
  effectId: providerEffectId,
924
941
  invocationId,
925
942
  wireEvidence,
@@ -1,4 +1,5 @@
1
- import type { ProviderReplay, ProviderWireEvidence, ToolCall, ToolErrorKind } from "../types.js";
1
+ import type { ContextPrepared } from "./context.js";
2
+ import type { ProviderWireEvidence, ToolCall, ToolErrorKind } from "../types.js";
2
3
  import type { MemoryRecall, MemoryScope } from "../memory/index.js";
3
4
  import type { KernelPrimitive } from "./kernel-event-log.js";
4
5
  import type { KernelJournal } from "./kernel-journal.js";
@@ -56,10 +57,14 @@ export type SessionEvent = {
56
57
  content: string;
57
58
  token_count?: number;
58
59
  tool_calls: ToolCall[];
59
- provider_replay?: ProviderReplay;
60
60
  effect_id?: string;
61
61
  invocation_id?: string;
62
62
  wire_evidence?: ProviderWireEvidence;
63
+ } | {
64
+ kind: "context_prepared";
65
+ turn: number;
66
+ effect_id: string;
67
+ preparation: ContextPrepared;
63
68
  } | {
64
69
  kind: "prompt_measured";
65
70
  turn: number;
@@ -292,7 +297,7 @@ export type SessionEvent = {
292
297
  classify_branch?: string;
293
298
  tournament_winner?: string;
294
299
  loop_continue?: boolean;
295
- output?: import("../types.js").Message;
300
+ output?: import("../types.js").ProviderMessage;
296
301
  } | {
297
302
  kind: "workflow_nodes_submitted";
298
303
  turn: number;
@@ -360,7 +365,7 @@ export type SessionEventKind = SessionEvent["kind"];
360
365
  * `tests/fixtures/sdk-conformance/canonical/session-event-vocabulary.json` pins both, and any
361
366
  * same-commit desync turns conformance red. Declared in `SessionEvent` union order.
362
367
  */
363
- export declare const SESSION_EVENT_KINDS: readonly ["run_started", "llm_completed", "prompt_measured", "provider_attempt", "tool_requested", "tool_completed", "tool_argument_repaired", "tool_denied", "permission_requested", "permission_resolved", "compressed", "page_out", "semantic_archive_pending", "semantic_archive_completed", "semantic_archive_failed", "page_in", "rollbacked", "capability_changed", "context_renewed", "suspended", "resumed", "tool_gated", "signal_delivery_disposed", "budget_exceeded", "budget_usage_reported", "operation_cancelled", "milestone_advanced", "milestone_blocked", "checkpoint_taken", "entropy_sample", "entropy_alert", "agent_process_changed", "memory_written", "memory_queried", "memory_validation_failed", "memory_write_failed", "memory_query_failed", "memory_retrieval_result", "workflow_node_completed", "workflow_nodes_submitted", "workflow_batch_spawned", "workflow_completed", "kernel_observation", "run_terminal", "summary_upgraded", "group_member_joined", "group_budget_charged", "round_started", "round_paced"];
368
+ export declare const SESSION_EVENT_KINDS: readonly ["run_started", "llm_completed", "prompt_measured", "context_prepared", "provider_attempt", "tool_requested", "tool_completed", "tool_argument_repaired", "tool_denied", "permission_requested", "permission_resolved", "compressed", "page_out", "semantic_archive_pending", "semantic_archive_completed", "semantic_archive_failed", "page_in", "rollbacked", "capability_changed", "context_renewed", "suspended", "resumed", "tool_gated", "signal_delivery_disposed", "budget_exceeded", "budget_usage_reported", "operation_cancelled", "milestone_advanced", "milestone_blocked", "checkpoint_taken", "entropy_sample", "entropy_alert", "agent_process_changed", "memory_written", "memory_queried", "memory_validation_failed", "memory_write_failed", "memory_query_failed", "memory_retrieval_result", "workflow_node_completed", "workflow_nodes_submitted", "workflow_batch_spawned", "workflow_completed", "kernel_observation", "run_terminal", "summary_upgraded", "group_member_joined", "group_budget_charged", "round_started", "round_paced"];
364
369
  /**
365
370
  * The business-projection log (spec §9.2): run started/terminal, stream events, observations,
366
371
  * provider/tool presentation, and audit metadata. Canonical durable records live exclusively in
@@ -10,6 +10,7 @@ export const SESSION_EVENT_KINDS = [
10
10
  "run_started",
11
11
  "llm_completed",
12
12
  "prompt_measured",
13
+ "context_prepared",
13
14
  "provider_attempt",
14
15
  "tool_requested",
15
16
  "tool_completed",
@@ -1,10 +1,10 @@
1
- import type { Message, ProviderReplay, ProviderWireEvidence, ToolCall } from "../types.js";
1
+ import type { ProviderMessage, ProviderWireEvidence, ToolCall } from "../types.js";
2
2
  import type { SessionEvent } from "./session-log.js";
3
3
  import type { WorkflowNodeStatus } from "./types/agent.js";
4
4
  export { REPLAY_CONTENT_MAX_BYTES as RECOVERY_CONTENT_MAX_BYTES } from "./replay-sanitize.js";
5
5
  /**
6
6
  * Normalize a persisted llm_completed event for recovery. Content is sanitized
7
- * and any existing token_count remains raw evidence, but the stored `provider_replay` envelope is
7
+ * and any existing token_count remains raw evidence, but `wire_evidence.replay_state` is
8
8
  * passed through verbatim — this layer is provider-neutral and never
9
9
  * synthesizes protocol-specific replay shapes. Canonical replay seeding is the
10
10
  * responsibility of the target provider's `seedProviderReplay`.
@@ -26,7 +26,6 @@ export declare function buildLlmCompletedEvent(input: {
26
26
  content: string;
27
27
  tokenCount?: number;
28
28
  toolCalls: ToolCall[];
29
- providerReplay?: ProviderReplay;
30
29
  effectId?: string;
31
30
  invocationId?: string;
32
31
  wireEvidence?: ProviderWireEvidence;
@@ -49,7 +48,7 @@ export declare function buildWorkflowNodeCompletedEvent(input: {
49
48
  classifyBranch?: string;
50
49
  tournamentWinner?: string;
51
50
  loopContinue?: boolean;
52
- output?: Message;
51
+ output?: ProviderMessage;
53
52
  }): Extract<SessionEvent, {
54
53
  kind: "workflow_node_completed";
55
54
  }>;
@@ -2,7 +2,7 @@ import { sanitizeReplayText } from "./replay-sanitize.js";
2
2
  export { REPLAY_CONTENT_MAX_BYTES as RECOVERY_CONTENT_MAX_BYTES } from "./replay-sanitize.js";
3
3
  /**
4
4
  * Normalize a persisted llm_completed event for recovery. Content is sanitized
5
- * and any existing token_count remains raw evidence, but the stored `provider_replay` envelope is
5
+ * and any existing token_count remains raw evidence, but `wire_evidence.replay_state` is
6
6
  * passed through verbatim — this layer is provider-neutral and never
7
7
  * synthesizes protocol-specific replay shapes. Canonical replay seeding is the
8
8
  * responsibility of the target provider's `seedProviderReplay`.
@@ -10,14 +10,12 @@ export { REPLAY_CONTENT_MAX_BYTES as RECOVERY_CONTENT_MAX_BYTES } from "./replay
10
10
  export function normalizeLlmCompleted(event, maxBytes) {
11
11
  const content = sanitizeReplayText(event.content ?? "", maxBytes);
12
12
  const toolCalls = event.tool_calls ?? [];
13
- const providerReplay = event.provider_replay;
14
13
  return {
15
14
  kind: "llm_completed",
16
15
  turn: event.turn,
17
16
  content,
18
17
  tool_calls: toolCalls,
19
18
  ...(event.token_count !== undefined ? { token_count: event.token_count } : {}),
20
- ...(providerReplay ? { provider_replay: providerReplay } : {}),
21
19
  // P4 §3: the evidence-plane fields ride along verbatim — recovery never reads them
22
20
  // (SessionLog is evidence, not authority), so normalize must neither synthesize nor drop them.
23
21
  ...(event.effect_id !== undefined ? { effect_id: event.effect_id } : {}),
@@ -39,7 +37,6 @@ export function buildLlmCompletedEvent(input) {
39
37
  content: sanitizeReplayText(input.content),
40
38
  tool_calls: input.toolCalls ?? [],
41
39
  token_count: input.tokenCount,
42
- provider_replay: input.providerReplay,
43
40
  ...(input.effectId !== undefined ? { effect_id: input.effectId } : {}),
44
41
  ...(input.invocationId !== undefined ? { invocation_id: input.invocationId } : {}),
45
42
  ...(input.wireEvidence !== undefined ? { wire_evidence: input.wireEvidence } : {}),
@@ -166,7 +166,7 @@ export const defaultSubAgentOrchestrator = new SubAgentOrchestrator();
166
166
  /** Canonical single-node root workflow for harness / coordinator use. */
167
167
  export async function spawnStandalone(parentOpts, parentSessionId, spec, orchestrator = defaultSubAgentOrchestrator, contextInput) {
168
168
  if (spec.tokenBudget !== undefined || spec.maxTurns !== undefined || spec.maxWallMs !== undefined) {
169
- throw new Error("spawnStandalone cannot represent per-node resource caps under canonical ABI v3");
169
+ throw new Error("spawnStandalone cannot represent per-node resource caps under canonical ABI");
170
170
  }
171
171
  const { RuntimeRunner } = await import("./runner.js");
172
172
  let captured;
@@ -1,4 +1,4 @@
1
- import type { Message, ToolSchema } from "../../types.js";
1
+ import type { ProviderMessage, ToolSchema } from "../../types.js";
2
2
  export type KernelAgentRole = "explore" | "plan" | "implement" | "verify" | "custom";
3
3
  export type AgentIsolation = "shared" | "read_only" | "worktree" | "remote";
4
4
  export type ContextInheritance = "none" | "system_only" | "full";
@@ -81,7 +81,7 @@ export interface AgentProcessChangedObservation {
81
81
  }
82
82
  export interface LoopResult {
83
83
  termination: TerminationReason | string;
84
- finalMessage?: Message;
84
+ finalMessage?: ProviderMessage;
85
85
  turnsUsed: number;
86
86
  totalTokensUsed: number;
87
87
  /** loop-control loop stop signal: a loop iteration sets `false` to end the loop before `max_iters`.
@@ -211,7 +211,7 @@ export interface KernelWorkflowNodeOutcome {
211
211
  status: WorkflowNodeStatus;
212
212
  termination?: TerminationReason;
213
213
  output?: {
214
- role: Message["role"];
214
+ role: ProviderMessage["role"];
215
215
  content: string;
216
216
  tool_calls?: Array<{
217
217
  id: string;
@@ -224,7 +224,7 @@ export interface WorkflowNodeOutcome {
224
224
  nodeId: string;
225
225
  status: WorkflowNodeStatus;
226
226
  termination?: TerminationReason;
227
- output?: Message;
227
+ output?: ProviderMessage;
228
228
  }
229
229
  export interface ControlRequestRejection {
230
230
  operation: string;
@@ -1,6 +1,6 @@
1
1
  /** Framework-facing API plus the Rust verifiable-runtime report ABI. */
2
- export declare const VERIFIABLE_REPORT_SCHEMA: "verifiable-report/v1";
3
- export declare const VERIFIABLE_FORK_SCHEMA: "verifiable-fork/v1";
2
+ export declare const VERIFIABLE_REPORT_SCHEMA: "verifiable-report/v2";
3
+ export declare const VERIFIABLE_FORK_SCHEMA: "verifiable-fork/v2";
4
4
  export type VerifiableCommand = "inspect" | "verify" | "replay" | "fork";
5
5
  export type CheckVerdict = "pass" | "degraded" | "fail" | "unavailable";
6
6
  export type ReplayVerdict = "pass" | "fail" | "unavailable";
@@ -1,7 +1,7 @@
1
1
  import { getKernel } from "./kernel.js";
2
2
  /** Framework-facing API plus the Rust verifiable-runtime report ABI. */
3
- export const VERIFIABLE_REPORT_SCHEMA = "verifiable-report/v1";
4
- export const VERIFIABLE_FORK_SCHEMA = "verifiable-fork/v1";
3
+ export const VERIFIABLE_REPORT_SCHEMA = "verifiable-report/v2";
4
+ export const VERIFIABLE_FORK_SCHEMA = "verifiable-fork/v2";
5
5
  /** Create the SDK adapter backed by the Rust core JSON bridge. */
6
6
  export function createVerifiableRuntimeAdapter(operationJson) {
7
7
  const call = (operationId, evidence, command, options = {}) => {