@deepstrike/sdk 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 (57) hide show
  1. package/dist/index.d.ts +6 -1
  2. package/dist/index.js +2 -0
  3. package/dist/kernel.d.ts +7 -4
  4. package/dist/memory/protocols.d.ts +2 -2
  5. package/dist/providers/anthropic-adapter.d.ts +2 -2
  6. package/dist/providers/anthropic.d.ts +9 -5
  7. package/dist/providers/anthropic.js +20 -5
  8. package/dist/providers/base.d.ts +5 -5
  9. package/dist/providers/content-normalization.d.ts +4 -4
  10. package/dist/providers/gemini-adapter.d.ts +2 -2
  11. package/dist/providers/gemini.d.ts +8 -4
  12. package/dist/providers/gemini.js +20 -7
  13. package/dist/providers/ollama-adapter.d.ts +2 -2
  14. package/dist/providers/ollama.d.ts +6 -3
  15. package/dist/providers/ollama.js +14 -3
  16. package/dist/providers/openai-chat.d.ts +4 -4
  17. package/dist/providers/openai-responses-adapter.d.ts +2 -2
  18. package/dist/providers/openai-responses-adapter.js +1 -1
  19. package/dist/providers/openai-responses.d.ts +7 -3
  20. package/dist/providers/openai-responses.js +19 -6
  21. package/dist/providers/openai.d.ts +8 -5
  22. package/dist/providers/openai.js +14 -3
  23. package/dist/providers/prepared-request.d.ts +4 -0
  24. package/dist/providers/prepared-request.js +78 -0
  25. package/dist/providers/protocol-adapter.d.ts +2 -2
  26. package/dist/providers/replay-validator.d.ts +3 -3
  27. package/dist/providers/request-plan.d.ts +8 -1
  28. package/dist/providers/request-plan.js +4 -3
  29. package/dist/runtime/archive.d.ts +7 -7
  30. package/dist/runtime/canonical-kernel-step.d.ts +4 -3
  31. package/dist/runtime/canonical-kernel-step.js +17 -8
  32. package/dist/runtime/context.d.ts +28 -0
  33. package/dist/runtime/context.js +16 -0
  34. package/dist/runtime/eval.d.ts +2 -2
  35. package/dist/runtime/evolution.d.ts +195 -0
  36. package/dist/runtime/evolution.js +34 -0
  37. package/dist/runtime/execution-plane.d.ts +1 -1
  38. package/dist/runtime/kernel-step.d.ts +7 -6
  39. package/dist/runtime/provider-replay.d.ts +2 -2
  40. package/dist/runtime/provider-replay.js +1 -1
  41. package/dist/runtime/replay-fixture.d.ts +5 -5
  42. package/dist/runtime/replay-fixture.js +3 -3
  43. package/dist/runtime/replay-provider.d.ts +4 -4
  44. package/dist/runtime/replay-provider.js +1 -1
  45. package/dist/runtime/runner.d.ts +8 -6
  46. package/dist/runtime/runner.js +23 -6
  47. package/dist/runtime/session-log.d.ts +9 -4
  48. package/dist/runtime/session-log.js +3 -2
  49. package/dist/runtime/session-repair.d.ts +3 -4
  50. package/dist/runtime/session-repair.js +1 -4
  51. package/dist/runtime/verifiable-report.d.ts +2 -2
  52. package/dist/runtime/verifiable-report.js +2 -2
  53. package/dist/skills/loader.d.ts +1 -1
  54. package/dist/tools/index.d.ts +2 -2
  55. package/dist/types/agent.d.ts +5 -5
  56. package/dist/types.d.ts +20 -11
  57. package/package.json +2 -2
@@ -1,4 +1,4 @@
1
- import type { EntropySample, Message, RenderedContext, TaskUpdate, ToolCall, ToolResult, ToolSchema } from "../types.js";
1
+ import type { EntropySample, ProviderMessage, RenderedContext, TaskUpdate, ToolCall, ToolExecutionResult, ToolSchema } from "../types.js";
2
2
  import type { SkillMetadata } from "../skills/loader.js";
3
3
  import type { RollbackReason } from "./session-log.js";
4
4
  export declare const CANONICAL_CONTENT_PARTS_PREFIX = "[[deepstrike-content-parts]]";
@@ -15,7 +15,7 @@ export interface KernelLoopResult {
15
15
  termination: string;
16
16
  turnsUsed: number;
17
17
  totalTokensUsed: number;
18
- finalMessage?: Message;
18
+ finalMessage?: ProviderMessage;
19
19
  /** ③ loop-agent: the kernel-adjudicated after-round decision (absent on non-loop runs). */
20
20
  paceDecision?: PaceDecision;
21
21
  }
@@ -36,6 +36,7 @@ export type KernelRunnerAction = {
36
36
  effectId: string;
37
37
  context: RenderedContext;
38
38
  tools: ToolSchema[];
39
+ contextEffect: Record<string, unknown>;
39
40
  } | {
40
41
  kind: "execute_tool";
41
42
  effectId: string;
@@ -75,7 +76,7 @@ export type KernelRunnerAction = {
75
76
  } | {
76
77
  kind: "archive_page_out";
77
78
  effectId: string;
78
- archived?: Message[];
79
+ archived?: ProviderMessage[];
79
80
  handleId?: string;
80
81
  payload?: {
81
82
  content: string;
@@ -212,8 +213,8 @@ export declare function archivePresentationFromObservations(observations: readon
212
213
  };
213
214
  export declare function toolSchemaToKernel(schema: ToolSchema): Record<string, unknown>;
214
215
  export declare function skillMetadataToKernel(skill: SkillMetadata): Record<string, unknown>;
215
- export declare function messageToKernelMessage(message: Message): Record<string, unknown>;
216
- export declare function toolResultToKernel(result: ToolResult): Record<string, unknown>;
216
+ export declare function messageToKernelMessage(message: ProviderMessage): Record<string, unknown>;
217
+ export declare function toolResultToKernel(result: ToolExecutionResult): Record<string, unknown>;
217
218
  export declare function taskUpdateToKernel(update: TaskUpdate): Record<string, unknown>;
218
219
  export declare function capabilityTool(schema: ToolSchema): Record<string, unknown>;
219
220
  export declare function capabilitySkill(skill: SkillMetadata): Record<string, unknown>;
@@ -222,5 +223,5 @@ export declare function capabilityCommandMount(capability: Record<string, unknow
222
223
  export declare function capabilityCommandUnmount(capabilityKind: string, id: string): Record<string, unknown>;
223
224
  /** Camel-case an `entropy_sample` kernel observation into the SDK's `EntropySample`. */
224
225
  export declare function entropySampleFromObservation(obs: KernelObservation): EntropySample;
225
- export declare function kernelMessageToSdk(raw: Record<string, unknown>): Message;
226
+ export declare function kernelMessageToSdk(raw: Record<string, unknown>): ProviderMessage;
226
227
  export declare function renderedContextToSdk(raw: Record<string, unknown>): RenderedContext;
@@ -1,10 +1,10 @@
1
- import type { LLMProvider, Message, ProviderDescriptor, ProviderReplay, RenderedContext, ReplayabilityAssessment, ToolCall } from "../types.js";
1
+ import type { LLMProvider, ProviderMessage, ProviderDescriptor, ProviderReplay, RenderedContext, ReplayabilityAssessment, ToolCall } from "../types.js";
2
2
  import type { SessionEvent } from "./session-log.js";
3
3
  export declare class ProviderReplayProtocolMismatchError extends Error {
4
4
  readonly code: "provider_replay_protocol_mismatch";
5
5
  constructor(provider: string, storedProtocol: string, resolvedProtocol: string);
6
6
  }
7
- export declare function assistantReplayKey(message: Pick<Message, "content" | "toolCalls">): string;
7
+ export declare function assistantReplayKey(message: Pick<ProviderMessage, "content" | "toolCalls">): string;
8
8
  /**
9
9
  * A stored replay may only be seeded into a provider speaking the same wire
10
10
  * protocol. On a cross-protocol fallback (provider A -> provider B) the
@@ -67,7 +67,7 @@ export function seedProviderReplayFromEvents(provider, events) {
67
67
  if (event.kind !== "llm_completed")
68
68
  continue;
69
69
  const toolCalls = event.tool_calls ?? [];
70
- const stored = event.provider_replay;
70
+ const stored = event.wire_evidence?.replay_state;
71
71
  if (!stored)
72
72
  continue;
73
73
  if (!isReplayCompatibleWithProvider(stored, descriptor)) {
@@ -6,21 +6,21 @@
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 wire shapes the SDK uses interchangeably:
18
- * - in-memory: `{ toolCalls, providerReplay }` (camelCase)
19
- * - serialised session-log: `{ tool_calls, token_count, provider_replay }` (snake_case; token_count is wire evidence)
18
+ * - in-memory: `{ toolCalls }` (camelCase)
19
+ * - serialised session-log: `{ tool_calls, token_count, wire_evidence }` (snake_case; token_count is wire evidence)
20
20
  *
21
21
  * @param events Session events, in original order. Accepts both `{ event, seq }` (the shape
22
22
  * `SessionLog.read()` returns) and a bare `SessionEvent[]`.
23
23
  */
24
24
  export declare function extractRecordedMessages(events: Array<{
25
25
  event: SessionEvent;
26
- } | SessionEvent>): Message[];
26
+ } | SessionEvent>): ProviderMessage[];
@@ -10,11 +10,11 @@
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 wire shapes the SDK uses interchangeably:
16
- * - in-memory: `{ toolCalls, providerReplay }` (camelCase)
17
- * - serialised session-log: `{ tool_calls, token_count, provider_replay }` (snake_case; token_count is wire evidence)
16
+ * - in-memory: `{ toolCalls }` (camelCase)
17
+ * - serialised session-log: `{ tool_calls, token_count, wire_evidence }` (snake_case; token_count is wire evidence)
18
18
  *
19
19
  * @param events Session events, in original order. Accepts both `{ event, seq }` (the shape
20
20
  * `SessionLog.read()` returns) and a bare `SessionEvent[]`.
@@ -17,14 +17,14 @@
17
17
  * from the original run). That's the point of replay-for-benchmarking: prompt may differ across
18
18
  * variants, response is pinned, so a cost Δ purely reflects the prompt change.
19
19
  * - `outputTokens` is estimated from `message.content.length / 4`; provider usage belongs to
20
- * the session measurement plane, never to the public Message mirror.
20
+ * the session measurement plane, never to the public ProviderMessage mirror.
21
21
  * - `cacheReadInputTokens` / `cacheCreationInputTokens` are emitted as 0 — replay has no real
22
22
  * cache state. Mechanisms whose Δ depends on cache behavior must validate with a live A/B too.
23
23
  *
24
24
  * Tokenizer: by default a `chars/4` estimator (±20% for English; worse for code/JSON). For tighter
25
25
  * numbers plug `opts.tokenizer = tiktokenEncoder` or similar.
26
26
  */
27
- import type { LLMProvider, Message, ProviderDescriptor, ProviderRunState, RenderedContext, StreamEvent, ToolSchema } from "../types.js";
27
+ import type { LLMProvider, ProviderMessage, ProviderDescriptor, ProviderRunState, RenderedContext, StreamEvent, ToolSchema } from "../types.js";
28
28
  export interface ReplayProviderOpts {
29
29
  /**
30
30
  * Maps a rendered-context text payload to a token count. Defaults to `chars / 4`.
@@ -54,7 +54,7 @@ export declare class ReplayProvider implements LLMProvider {
54
54
  * @param messages Ordered list of assistant messages to replay (one per LLM call).
55
55
  * @param opts Optional tokenizer / descriptor / wrap-around behavior.
56
56
  */
57
- constructor(messages: ReadonlyArray<Message>, opts?: ReplayProviderOpts);
57
+ constructor(messages: ReadonlyArray<ProviderMessage>, opts?: ReplayProviderOpts);
58
58
  descriptor(): ProviderDescriptor;
59
59
  /** Number of messages consumed so far. */
60
60
  consumed(): number;
@@ -62,7 +62,7 @@ export declare class ReplayProvider implements LLMProvider {
62
62
  remaining(): number;
63
63
  /** Reset the cursor — useful for re-running the same fixture in a fresh session. */
64
64
  reset(): void;
65
- complete(_context: RenderedContext, _tools: ToolSchema[]): Promise<Message>;
65
+ complete(_context: RenderedContext, _tools: ToolSchema[]): Promise<ProviderMessage>;
66
66
  stream(context: RenderedContext, tools: ToolSchema[], _extensions?: Record<string, unknown>, _state?: ProviderRunState, _signal?: AbortSignal): AsyncIterable<StreamEvent>;
67
67
  private pull;
68
68
  private estimateInputTokens;
@@ -17,7 +17,7 @@
17
17
  * from the original run). That's the point of replay-for-benchmarking: prompt may differ across
18
18
  * variants, response is pinned, so a cost Δ purely reflects the prompt change.
19
19
  * - `outputTokens` is estimated from `message.content.length / 4`; provider usage belongs to
20
- * the session measurement plane, never to the public Message mirror.
20
+ * the session measurement plane, never to the public ProviderMessage mirror.
21
21
  * - `cacheReadInputTokens` / `cacheCreationInputTokens` are emitted as 0 — replay has no real
22
22
  * cache state. Mechanisms whose Δ depends on cache behavior must validate with a live A/B too.
23
23
  *
@@ -1,4 +1,4 @@
1
- import type { LLMProvider, Message, ContentPart, ToolSchema, StreamEvent, ToolSuspendEvent, PermissionRequestEvent, PermissionResponse, AsyncSummarizer, MemorySummarizer, EntropySample, EntropyWatchOptions } from "../types.js";
1
+ import type { LLMProvider, ProviderMessage, ContentPart, ToolSchema, StreamEvent, ToolSuspendEvent, PermissionRequestEvent, PermissionResponse, AsyncSummarizer, MemorySummarizer, EntropySample, EntropyWatchOptions } from "../types.js";
2
2
  import type { MemoryStore, MemoryRecord, MemoryRecall, MemoryScope, MemoryQuery } from "../memory/protocols.js";
3
3
  import type { KnowledgeSource } from "../knowledge/source.js";
4
4
  import type { RuntimeSignalUrgency, SignalSource } from "../signals/types.js";
@@ -95,6 +95,8 @@ export interface KernelReliabilityOptions {
95
95
  export type OperationCancellationReason = "user" | "deadline" | "lease_lost" | "host_shutdown";
96
96
  export interface RuntimeOptions {
97
97
  provider: LLMProvider;
98
+ /** Host-owned artifact set identity captured in operation genesis. */
99
+ artifactSetDigest?: string;
98
100
  /** M4/G5: cumulative token cap for this run (the kernel's `max_total_tokens`). A workflow node's
99
101
  * `tokenBudget` flows here for its child run, so an expensive node self-terminates at the cap.
100
102
  * Undefined ⇒ the kernel default. */
@@ -109,7 +111,7 @@ export interface RuntimeOptions {
109
111
  * Undefined ⇒ worktree nodes fall back to the inherited plane (no isolation). */
110
112
  worktreeManager?: import("./worktree-plane.js").WorktreeManager;
111
113
  sessionLog: SessionLog;
112
- /** ABI v3 transaction capability. Default session logs expose one; custom logs pass it explicitly. */
114
+ /** ABI transaction capability. Default session logs expose one; custom logs pass it explicitly. */
113
115
  kernelJournal?: KernelJournal;
114
116
  executionPlane: ExecutionPlane;
115
117
  /** Receives failures from run-owned best-effort tasks after their semantic owner has committed. */
@@ -486,7 +488,7 @@ export declare class RuntimeRunner {
486
488
  * K1: `opts.key` gives the entry identity — a same-key push upserts (applied at the next
487
489
  * compaction/renewal boundary, where the cached system[1] block is rewritten anyway) instead
488
490
  * of appending a duplicate. `opts.pinned` exempts the entry from the knowledge-budget sweep. */
489
- pushKnowledge(message: Message, tokens?: number, opts?: {
491
+ pushKnowledge(message: ProviderMessage, tokens?: number, opts?: {
490
492
  key?: string;
491
493
  pinned?: boolean;
492
494
  }): Promise<void>;
@@ -601,14 +603,14 @@ export declare class RuntimeRunner {
601
603
  * message exists. A tail assistant tool_call with nothing after it is a genuinely PENDING tool the
602
604
  * run stopped in front of (the wake/recovery case), which must stay unpaired so wake executes it.
603
605
  * Pure. */
604
- export declare function pairOrphanToolCalls(messages: Message[]): Message[];
606
+ export declare function pairOrphanToolCalls(messages: ProviderMessage[]): ProviderMessage[];
605
607
  export declare function replayMessages(events: Array<{
606
608
  seq: number;
607
609
  event: SessionEvent;
608
- }>, maxBytes?: number): Message[];
610
+ }>, maxBytes?: number): ProviderMessage[];
609
611
  export declare function replayMessagesAsync(events: Array<{
610
612
  seq: number;
611
613
  event: SessionEvent;
612
- }>, maxBytes?: number, loadArchive?: (archiveRef: string) => Promise<Message[]>): Promise<Message[]>;
614
+ }>, maxBytes?: number, loadArchive?: (archiveRef: string) => Promise<ProviderMessage[]>): Promise<ProviderMessage[]>;
613
615
  /** Collect all text_delta events from a run into a single string. */
614
616
  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 { createHash } from "node:crypto";
2
4
  import { extractSessionMemories } from "../memory/extraction.js";
3
5
  import { resolvePermissionRequest } from "./execution-plane.js";
@@ -389,6 +391,7 @@ export class RuntimeRunner {
389
391
  maxTurns: this.opts.maxTurns,
390
392
  maxTotalTokens: this.opts.maxTotalTokens,
391
393
  maxWallMs: this.opts.timeoutMs,
394
+ artifactSetDigest: this.opts.artifactSetDigest,
392
395
  memoryBindingId: `node-memory-${this.opts.agentId ?? "root"}`,
393
396
  persistPayload: async (callId, content, previewBytes) => {
394
397
  const digest = `sha256:${createHash("sha256").update(content).digest("hex")}`;
@@ -1077,7 +1080,7 @@ export class RuntimeRunner {
1077
1080
  else if (completionAction) {
1078
1081
  throw new Error(`workflow completion returned unexpected effect: ${completionAction.kind}`);
1079
1082
  }
1080
- // ABI v3: child-authored DAG additions ride on ChildCompleted.parent_requests. Admission is
1083
+ // ABI: child-authored DAG additions ride on ChildCompleted.parent_requests. Admission is
1081
1084
  // independent of the completion fact; only an admitted request emits this observation.
1082
1085
  if (result.submittedNodes?.length) {
1083
1086
  const submitted = obs.find(o => o.kind === "workflow_nodes_submitted");
@@ -1636,13 +1639,16 @@ export class RuntimeRunner {
1636
1639
  // P4 §2: the raw postflight provider usage frame, kept whole so the attempt's
1637
1640
  // measurement carries full fields (only the settlement crosses the kernel boundary, B4).
1638
1641
  let turnProviderUsage;
1639
- const providerPlan = createProviderRequestPlanForProvider(this.opts.provider, context, tools, ext);
1642
+ const preparedRequest = prepareProviderRequest(this.opts.provider, context, tools, ext, providerState);
1643
+ const providerPlan = createProviderRequestPlanForProvider(this.opts.provider, context, tools, ext, {
1644
+ scope: preparedRequest.scope, request: preparedRequest.request, state: preparedRequest.state,
1645
+ });
1640
1646
  const recorded = measurementForPlan(providerPlan, recordedMeasurements.get(providerPlan.fingerprint));
1641
1647
  let promptMeasurement = recorded;
1642
1648
  if (!promptMeasurement && !context.budgetOverflow) {
1643
1649
  try {
1644
- const count = this.opts.provider.countTokens
1645
- ? await withTimeout(this.opts.provider.countTokens(context, tools, Object.keys(ext).length ? ext : undefined), 5_000)
1650
+ const count = preparedRequest.countTokens
1651
+ ? await withTimeout(preparedRequest.countTokens(), 5_000)
1646
1652
  : undefined;
1647
1653
  promptMeasurement = recordPromptMeasurement(providerPlan, count ?? {
1648
1654
  inputTokens: estimateProviderPromptTokens(context, tools),
@@ -1702,9 +1708,21 @@ export class RuntimeRunner {
1702
1708
  this.providerRetryPending = action.kind === "call_provider";
1703
1709
  continue;
1704
1710
  }
1711
+ if (!promptMeasurement)
1712
+ throw new Error("context preparation requires prompt measurement");
1713
+ const contextAdapter = createNativeContextPreparationAdapter();
1714
+ const preparation = contextAdapter.prepare({
1715
+ effect: action.contextEffect,
1716
+ request_fingerprint: providerPlan.fingerprint,
1717
+ provider_route: { ...this.providerRoute, request_fingerprint_scope: preparedRequest.scope },
1718
+ prompt_measurement: promptMeasurement,
1719
+ });
1720
+ await this.opts.sessionLog.append(sessionId, {
1721
+ kind: "context_prepared", turn: runtime.turn(), effect_id: providerEffectId, preparation,
1722
+ });
1705
1723
  const abortSignal = this.abortController?.signal;
1706
1724
  try {
1707
- for await (const evt of this.opts.provider.stream(context, tools, Object.keys(ext).length ? ext : undefined, providerState, abortSignal)) {
1725
+ for await (const evt of preparedRequest.stream(abortSignal)) {
1708
1726
  // #2-B-ii: a preempting `interrupt()` fires `abortController` — stop consuming the live
1709
1727
  // stream immediately (providers that forward `signal` also abort the socket; the rest at
1710
1728
  // least stop here at the next event). The loop-top `interrupted` check then ends the run.
@@ -1959,7 +1977,6 @@ export class RuntimeRunner {
1959
1977
  content: finalText,
1960
1978
  tokenCount: turnOutputTokens || turnTokens || undefined,
1961
1979
  toolCalls: finalToolCalls,
1962
- providerReplay,
1963
1980
  effectId: providerEffectId,
1964
1981
  invocationId,
1965
1982
  wireEvidence,
@@ -1,5 +1,6 @@
1
+ import type { ContextPrepared } from "./context.js";
1
2
  import type { KernelPrimitive } from "./kernel-event-log.js";
2
- import type { ContentPart, ProviderReplay, ProviderWireEvidence, ToolCall, ToolErrorKind } from "../types.js";
3
+ import type { ContentPart, ProviderWireEvidence, ToolCall, ToolErrorKind } from "../types.js";
3
4
  import type { RecordedPromptMeasurement, ResolvedProviderRoute } from "../providers/request-plan.js";
4
5
  import type { ProviderAttemptRecord } from "./execution-evidence.js";
5
6
  import type { MemoryRecall, MemoryScope } from "../memory/protocols.js";
@@ -38,10 +39,14 @@ export type SessionEvent = {
38
39
  content: string;
39
40
  token_count?: number;
40
41
  tool_calls: ToolCall[];
41
- provider_replay?: ProviderReplay;
42
42
  effect_id?: string;
43
43
  invocation_id?: string;
44
44
  wire_evidence?: ProviderWireEvidence;
45
+ } | {
46
+ kind: "context_prepared";
47
+ turn: number;
48
+ effect_id: string;
49
+ preparation: ContextPrepared;
45
50
  } | {
46
51
  kind: "prompt_measured";
47
52
  turn: number;
@@ -274,7 +279,7 @@ export type SessionEvent = {
274
279
  classify_branch?: string;
275
280
  tournament_winner?: string;
276
281
  loop_continue?: boolean;
277
- output?: import("../types.js").Message;
282
+ output?: import("../types.js").ProviderMessage;
278
283
  } | {
279
284
  kind: "workflow_nodes_submitted";
280
285
  turn: number;
@@ -342,7 +347,7 @@ export type SessionEventKind = SessionEvent["kind"];
342
347
  * `tests/fixtures/sdk-conformance/canonical/session-event-vocabulary.json` and the python/wasm
343
348
  * vocabularies turns cross-SDK conformance red. Declared in `SessionEvent` union order.
344
349
  */
345
- 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"];
350
+ 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"];
346
351
  /**
347
352
  * The business-projection log (spec §9.2): run started/terminal, stream events, observations,
348
353
  * provider/tool presentation, audit metadata.
@@ -16,6 +16,7 @@ export const SESSION_EVENT_KINDS = [
16
16
  "run_started",
17
17
  "llm_completed",
18
18
  "prompt_measured",
19
+ "context_prepared",
19
20
  "provider_attempt",
20
21
  "tool_requested",
21
22
  "tool_completed",
@@ -214,8 +215,8 @@ function decodePersistedSessionRecord(value) {
214
215
  if (!record.event || typeof record.event !== "object" || Array.isArray(record.event))
215
216
  throw new Error("session record event must be an object");
216
217
  const event = record.event;
217
- if (event.kind === "llm_completed" && event.provider_replay !== undefined) {
218
- assertCanonicalProviderReplay(event.provider_replay);
218
+ if (event.kind === "llm_completed" && "provider_replay" in event) {
219
+ throw new Error("llm_completed has removed provider_replay field; use wire_evidence.replay_state");
219
220
  }
220
221
  if (event.kind === "llm_completed" && event.wire_evidence !== undefined) {
221
222
  assertCanonicalWireEvidence(event.wire_evidence);
@@ -1,4 +1,4 @@
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";
@@ -6,7 +6,7 @@ export { REPLAY_CONTENT_MAX_BYTES as RECOVERY_CONTENT_MAX_BYTES } from "./replay
6
6
  * Normalize a persisted llm_completed event for recovery.
7
7
  *
8
8
  * Content is sanitized while any existing token_count remains raw evidence, but the stored
9
- * `provider_replay` envelope is passed through verbatim — this layer is
9
+ * `wire_evidence.replay_state` is passed through verbatim — this layer is
10
10
  * provider-neutral and must never synthesize protocol-specific replay shapes
11
11
  * (e.g. Anthropic `native_blocks`). Canonical replay seeding for a given protocol
12
12
  * is the responsibility of that provider's `seedProviderReplay`.
@@ -34,7 +34,6 @@ export declare function buildLlmCompletedEvent(input: {
34
34
  content: string;
35
35
  tokenCount?: number;
36
36
  toolCalls: ToolCall[];
37
- providerReplay?: ProviderReplay;
38
37
  effectId?: string;
39
38
  invocationId?: string;
40
39
  wireEvidence?: ProviderWireEvidence;
@@ -58,7 +57,7 @@ export declare function buildWorkflowNodeCompletedEvent(input: {
58
57
  classifyBranch?: string;
59
58
  tournamentWinner?: string;
60
59
  loopContinue?: boolean;
61
- output?: Message;
60
+ output?: ProviderMessage;
62
61
  }): Extract<SessionEvent, {
63
62
  kind: "workflow_node_completed";
64
63
  }>;
@@ -4,7 +4,7 @@ export { REPLAY_CONTENT_MAX_BYTES as RECOVERY_CONTENT_MAX_BYTES } from "./replay
4
4
  * Normalize a persisted llm_completed event for recovery.
5
5
  *
6
6
  * Content is sanitized while any existing token_count remains raw evidence, but the stored
7
- * `provider_replay` envelope is passed through verbatim — this layer is
7
+ * `wire_evidence.replay_state` is passed through verbatim — this layer is
8
8
  * provider-neutral and must never synthesize protocol-specific replay shapes
9
9
  * (e.g. Anthropic `native_blocks`). Canonical replay seeding for a given protocol
10
10
  * is the responsibility of that provider's `seedProviderReplay`.
@@ -16,14 +16,12 @@ export { REPLAY_CONTENT_MAX_BYTES as RECOVERY_CONTENT_MAX_BYTES } from "./replay
16
16
  export function normalizeLlmCompleted(event, maxBytes) {
17
17
  const content = sanitizeReplayText(event.content ?? "", maxBytes);
18
18
  const toolCalls = event.tool_calls ?? [];
19
- const providerReplay = event.provider_replay;
20
19
  return {
21
20
  kind: "llm_completed",
22
21
  turn: event.turn,
23
22
  content,
24
23
  tool_calls: toolCalls,
25
24
  ...(event.token_count !== undefined ? { token_count: event.token_count } : {}),
26
- ...(providerReplay ? { provider_replay: providerReplay } : {}),
27
25
  ...(event.effect_id !== undefined ? { effect_id: event.effect_id } : {}),
28
26
  ...(event.invocation_id !== undefined ? { invocation_id: event.invocation_id } : {}),
29
27
  ...(event.wire_evidence !== undefined ? { wire_evidence: event.wire_evidence } : {}),
@@ -45,7 +43,6 @@ export function buildLlmCompletedEvent(input) {
45
43
  content: sanitizeReplayText(input.content),
46
44
  tool_calls: input.toolCalls ?? [],
47
45
  token_count: input.tokenCount,
48
- provider_replay: input.providerReplay,
49
46
  ...(input.effectId !== undefined ? { effect_id: input.effectId } : {}),
50
47
  ...(input.invocationId !== undefined ? { invocation_id: input.invocationId } : {}),
51
48
  ...(input.wireEvidence !== undefined ? { wire_evidence: input.wireEvidence } : {}),
@@ -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 = {}) => {
@@ -9,7 +9,7 @@ export interface SkillMetadata {
9
9
  capabilityGrants?: Array<Record<string, unknown>>;
10
10
  /** P1-B tool gating: tool ids this skill needs. When the skill is active, the kernel narrows the
11
11
  * exposed toolset to `stable-core ∪ allowedTools`. Parsed from `allowed_tools:` frontmatter
12
- * (comma-separated or `[a, b]`). Absent ⇒ the skill does not narrow (back-compat). */
12
+ * (comma-separated or `[a, b]`). Absent ⇒ the skill does not narrow. */
13
13
  allowedTools?: string[];
14
14
  }
15
15
  /** Read one skill file and return its body (frontmatter stripped). */
@@ -1,4 +1,4 @@
1
- import type { ToolChunk, ToolSchema, ToolResult } from "../types.js";
1
+ import type { ToolChunk, ToolSchema, ToolExecutionResult } from "../types.js";
2
2
  import type { OperationContext } from "../runtime/reliability.js";
3
3
  /** M3/G4: the runtime context a tool may read when executing. Carries the working directory the tool
4
4
  * should operate in — set to a sub-agent's git worktree for `isolation: "worktree"` nodes. A narrow,
@@ -35,6 +35,6 @@ export declare function executeTools(calls: {
35
35
  id: string;
36
36
  name: string;
37
37
  arguments: string;
38
- }[], registry: Map<string, RegisteredTool>): Promise<ToolResult[]>;
38
+ }[], registry: Map<string, RegisteredTool>): Promise<ToolExecutionResult[]>;
39
39
  export declare function maybeWarnFailureShapedChunk(toolName: string, deltaText: string): void;
40
40
  export declare const readFile: RegisteredTool;
@@ -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";
@@ -86,7 +86,7 @@ export interface AgentProcessChangedObservation {
86
86
  }
87
87
  export interface LoopResult {
88
88
  termination: TerminationReason | string;
89
- finalMessage?: Message;
89
+ finalMessage?: ProviderMessage;
90
90
  turnsUsed: number;
91
91
  totalTokensUsed: number;
92
92
  /** loop-control loop stop signal: a loop iteration sets `false` to end the loop before `max_iters`.
@@ -228,7 +228,7 @@ export interface KernelWorkflowNodeOutcome {
228
228
  status: WorkflowNodeStatus;
229
229
  termination?: TerminationReason;
230
230
  output?: {
231
- role: Message["role"];
231
+ role: ProviderMessage["role"];
232
232
  content: string;
233
233
  tool_calls?: Array<{
234
234
  id: string;
@@ -241,7 +241,7 @@ export interface WorkflowNodeOutcome {
241
241
  nodeId: string;
242
242
  status: WorkflowNodeStatus;
243
243
  termination?: TerminationReason;
244
- output?: Message;
244
+ output?: ProviderMessage;
245
245
  }
246
246
  /** A control-plane request rejected before any workflow effect started. */
247
247
  export interface ControlRequestRejection {
@@ -308,7 +308,7 @@ export interface WorkflowBudget {
308
308
  tokens_used?: number;
309
309
  tokens_max?: number;
310
310
  tokens_remaining?: number;
311
- /** Canonical ABI v3 publishes immutable caps rather than a host-authored remaining snapshot. */
311
+ /** Canonical ABI publishes immutable caps rather than a host-authored remaining snapshot. */
312
312
  max_total_tokens?: string | number;
313
313
  max_turns?: number;
314
314
  max_concurrency?: number;
package/dist/types.d.ts CHANGED
@@ -81,10 +81,10 @@ export interface ContentBlockFile {
81
81
  mediaType?: string;
82
82
  providerOptions?: Record<string, unknown>;
83
83
  }
84
- /** Legal content returned by a tool. Deliberately excludes ToolResult, so nesting is
84
+ /** Legal content returned by a tool. Deliberately excludes ToolExecutionResult, so nesting is
85
85
  * unrepresentable in the canonical type. */
86
86
  export type ToolOutputBlock = ContentBlockText | ContentBlockImage | ContentBlockAudio | ContentBlockVideo | ContentBlockFile;
87
- export interface Message {
87
+ export interface ProviderMessage {
88
88
  role: "system" | "user" | "assistant" | "tool";
89
89
  /** Plain-text content. When `contentParts` is present, this holds only the text segments. */
90
90
  content: string;
@@ -98,7 +98,7 @@ export interface ToolCall {
98
98
  arguments: string;
99
99
  }
100
100
  export type ToolErrorKind = "recoverable" | "fatal" | "governance_denied" | "provider_failure" | "timeout" | "user_interrupt";
101
- export interface ToolResult {
101
+ export interface ToolExecutionResult {
102
102
  callId: string;
103
103
  output: string;
104
104
  isError: boolean;
@@ -450,7 +450,7 @@ export interface ProviderWireEvidence {
450
450
  response_id?: string;
451
451
  /** BoundedJson semantics: producers truncate to ≤4KB before landing it here. */
452
452
  raw_usage?: unknown;
453
- /** The former `llm_completed.provider_replay` field, carried verbatim (P3-S2 migration). */
453
+ /** Provider-native replay state carried inside the wire evidence bundle. */
454
454
  replay_state?: ProviderReplay;
455
455
  }
456
456
  /**
@@ -478,7 +478,7 @@ export interface RenderedContext {
478
478
  /** Knowledge (memory retrievals, skill definitions, artifacts). Anthropic system[1] with cache_control. */
479
479
  systemKnowledge?: string;
480
480
  /** History turns only — the stable, cacheable message prefix. */
481
- turns: Message[];
481
+ turns: ProviderMessage[];
482
482
  /**
483
483
  * Volatile State turn (task_state + signals), rebuilt every call. Providers
484
484
  * render it after the cacheable history (Anthropic: after the cache breakpoint;
@@ -486,7 +486,7 @@ export interface RenderedContext {
486
486
  * older binding that has not been rebuilt — then the State turn is still inside
487
487
  * `turns[0]` and providers render `turns` as-is.
488
488
  */
489
- stateTurn?: Message;
489
+ stateTurn?: ProviderMessage;
490
490
  /**
491
491
  * P1-E: count of leading `turns` forming the frozen prefix — byte-stable until the next
492
492
  * compaction. The Anthropic provider pins a deep cache breakpoint at this boundary (a long-lived
@@ -512,7 +512,16 @@ export interface RuntimePolicy {
512
512
  /** Per-run wall-clock timeout in ms. */
513
513
  timeoutMs?: number;
514
514
  }
515
+ /** Frozen host request; scope distinguishes encoded body from a custom adapter input. */
516
+ export interface PreparedProviderRequest {
517
+ readonly scope: "encoded_body" | "adapter_input";
518
+ readonly request: unknown;
519
+ readonly state: unknown;
520
+ stream(signal?: AbortSignal): AsyncIterable<StreamEvent>;
521
+ countTokens?(): Promise<PromptMeasurement>;
522
+ }
515
523
  export interface LLMProvider {
524
+ prepareRequest?(context: RenderedContext, tools: ToolSchema[], extensions?: Record<string, unknown>, state?: ProviderRunState): PreparedProviderRequest;
516
525
  createRunState?(): ProviderRunState;
517
526
  descriptor?(): ProviderDescriptor;
518
527
  /**
@@ -522,7 +531,7 @@ export interface LLMProvider {
522
531
  */
523
532
  runtimePolicy?(): RuntimePolicy;
524
533
  /** Read provider-native replay fields captured after the most recent assistant turn. */
525
- peekProviderReplay?(message: Pick<Message, "content" | "toolCalls">): ProviderReplay | undefined;
534
+ peekProviderReplay?(message: Pick<ProviderMessage, "content" | "toolCalls">): ProviderReplay | undefined;
526
535
  /**
527
536
  * P4-S1: read the transport facts captured during the most recent execution (HTTP rung count,
528
537
  * wire response id). Optional — a provider without it simply omits the telemetry and the
@@ -531,7 +540,7 @@ export interface LLMProvider {
531
540
  */
532
541
  peekTransportTelemetry?(): ProviderTransportTelemetry | undefined;
533
542
  /** Restore provider-native replay fields when rebuilding history from SessionLog. */
534
- seedProviderReplay?(message: Pick<Message, "content" | "toolCalls">, replay: ProviderReplay): void;
543
+ seedProviderReplay?(message: Pick<ProviderMessage, "content" | "toolCalls">, replay: ProviderReplay): void;
535
544
  /**
536
545
  * Pre-flight query: would this history validate against this provider with the
537
546
  * given extensions, without sending the request? Returns the tool-call ids
@@ -551,7 +560,7 @@ export interface LLMProvider {
551
560
  * fingerprinting and durable measurement semantics are defined.
552
561
  */
553
562
  countTokens?(context: RenderedContext, tools: ToolSchema[], extensions?: Record<string, unknown>, state?: ProviderRunState): Promise<PromptMeasurement>;
554
- complete(context: RenderedContext, tools: ToolSchema[], extensions?: Record<string, unknown>): Promise<Message>;
563
+ complete(context: RenderedContext, tools: ToolSchema[], extensions?: Record<string, unknown>): Promise<ProviderMessage>;
555
564
  stream(context: RenderedContext, tools: ToolSchema[], extensions?: Record<string, unknown>, state?: ProviderRunState,
556
565
  /** #2-B-ii: when provided, a preempting `InterruptNow` (or `interrupt()`) aborts the in-flight
557
566
  * request. SDK-client providers should forward it to the client (`{ signal }`); the runner also
@@ -564,14 +573,14 @@ export interface LLMProvider {
564
573
  * Produces a richer LLM-generated summary that replaces the rule-based one on next wake.
565
574
  */
566
575
  export interface AsyncSummarizer {
567
- summarize(archived: Message[], action: string): Promise<string>;
576
+ summarize(archived: ProviderMessage[], action: string): Promise<string>;
568
577
  }
569
578
  /**
570
579
  * Durable-memory summarizer for semantic `page_out` events (Layer 5 contract).
571
580
  * The kernel emits `page_out { tier_hint: "semantic" }`; the SDK persists an LLM summary to MemoryStore.
572
581
  */
573
582
  export interface MemorySummarizer {
574
- summarize(archived: Message[], context: {
583
+ summarize(archived: ProviderMessage[], context: {
575
584
  action?: string;
576
585
  }): Promise<string>;
577
586
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepstrike/sdk",
3
- "version": "0.2.69",
3
+ "version": "0.2.70",
4
4
  "description": "DeepStrike Node.js SDK",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",
@@ -73,7 +73,7 @@
73
73
  },
74
74
  "dependencies": {
75
75
  "@anthropic-ai/sdk": "^0.99.0",
76
- "@deepstrike/core": "0.2.69",
76
+ "@deepstrike/core": "0.2.70",
77
77
  "@google/generative-ai": "^0.24.1",
78
78
  "openai": "^7.5.0"
79
79
  },