@deepstrike/sdk 0.2.30 → 0.2.32

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 (48) hide show
  1. package/dist/harness/harness.d.ts +3 -2
  2. package/dist/harness/harness.js +15 -35
  3. package/dist/harness/judge.d.ts +42 -0
  4. package/dist/harness/judge.js +58 -0
  5. package/dist/index.d.ts +8 -0
  6. package/dist/index.js +4 -0
  7. package/dist/kernel.d.ts +7 -1
  8. package/dist/providers/anthropic-compatible.d.ts +23 -0
  9. package/dist/providers/anthropic-compatible.js +29 -0
  10. package/dist/providers/catalog.js +5 -53
  11. package/dist/providers/deepseek.d.ts +28 -8
  12. package/dist/providers/deepseek.js +38 -157
  13. package/dist/providers/factories.js +10 -22
  14. package/dist/providers/gemini.d.ts +12 -0
  15. package/dist/providers/gemini.js +38 -3
  16. package/dist/providers/glm.d.ts +7 -4
  17. package/dist/providers/glm.js +27 -24
  18. package/dist/providers/kimi.d.ts +5 -4
  19. package/dist/providers/kimi.js +8 -22
  20. package/dist/providers/minimax.d.ts +26 -12
  21. package/dist/providers/minimax.js +33 -159
  22. package/dist/providers/openai-responses.d.ts +6 -0
  23. package/dist/providers/openai-responses.js +22 -2
  24. package/dist/providers/openai.d.ts +52 -0
  25. package/dist/providers/openai.js +145 -66
  26. package/dist/providers/profiles.d.ts +60 -0
  27. package/dist/providers/profiles.js +22 -0
  28. package/dist/providers/qwen.d.ts +20 -19
  29. package/dist/providers/qwen.js +49 -176
  30. package/dist/providers/registry.d.ts +18 -0
  31. package/dist/providers/registry.js +35 -0
  32. package/dist/providers/vendor-profiles.d.ts +54 -0
  33. package/dist/providers/vendor-profiles.js +66 -0
  34. package/dist/runtime/event-stream.d.ts +44 -0
  35. package/dist/runtime/event-stream.js +39 -0
  36. package/dist/runtime/reactive-session.d.ts +125 -0
  37. package/dist/runtime/reactive-session.js +127 -0
  38. package/dist/runtime/run-group.d.ts +74 -0
  39. package/dist/runtime/run-group.js +72 -0
  40. package/dist/runtime/runner.d.ts +9 -0
  41. package/dist/runtime/runner.js +56 -7
  42. package/dist/runtime/session-log.d.ts +8 -0
  43. package/dist/runtime/turn-policy.d.ts +33 -0
  44. package/dist/runtime/turn-policy.js +58 -0
  45. package/dist/signals/gateway.d.ts +7 -2
  46. package/dist/signals/gateway.js +13 -3
  47. package/dist/signals/types.d.ts +10 -1
  48. package/package.json +2 -2
@@ -1,54 +1,29 @@
1
- import OpenAI from "openai";
2
- import { withServerRuntimeGuard } from "../runtime/server.js";
3
- import { AnthropicProvider } from "./anthropic.js";
4
- import { CircuitBreaker, omitExtensionKeys, openAICachedPromptTokens } from "./base.js";
5
- import { OpenAIChatAdapter } from "./openai-chat.js";
1
+ import { OpenAIChatProvider } from "./openai.js";
2
+ import { AnthropicCompatibleProvider } from "./anthropic-compatible.js";
3
+ import { omitExtensionKeys } from "./base.js";
6
4
  import { endpointProfiles } from "./profiles.js";
7
- const QWEN_POLICIES = {
8
- "qwen3.7-max-preview": { maxTurns: 45 },
9
- "qwen3.7-plus-preview": { maxTurns: 40 },
10
- "qwen3.6-max-preview": { maxTurns: 40 },
11
- "qwen3.6-plus": { maxTurns: 35 },
12
- "qwen3.6-flash": { maxTurns: 20 },
13
- "qwen3.6-35b-a3b": { maxTurns: 25 },
14
- "qwen3.6-27b": { maxTurns: 25 },
15
- "qwen3.5-plus": { maxTurns: 35 },
16
- "qwen3.5-flash": { maxTurns: 20 },
17
- "qwen3.5-397b-a17b": { maxTurns: 35 },
18
- "qwen3.5-122b-a10b": { maxTurns: 25 },
19
- "qwen3.5-35b-a3b": { maxTurns: 20 },
20
- "qwen3.5-27b": { maxTurns: 20 },
21
- };
5
+ import { QWEN_POLICIES, anthropicVendorProfiles } from "./vendor-profiles.js";
22
6
  /**
23
7
  * Qwen over its Anthropic-compatible endpoint.
8
+ * @deprecated Prefer `qwen({ protocol: "anthropic" })`. Behavior is now fully
9
+ * data-driven via `anthropicVendorProfiles.qwen`; this thin shim is kept for
10
+ * backward compatibility and `instanceof` checks.
24
11
  */
25
- export class QwenAnthropicProvider extends AnthropicProvider {
26
- constructor(apiKey, model = "qwen3.6-plus", retry, baseURL = endpointProfiles["qwen.anthropic"].baseURL) {
27
- super(apiKey, model, retry, {
28
- baseURL,
29
- authMode: "api-key",
30
- });
31
- }
32
- providerName() {
33
- return "qwen";
34
- }
35
- runtimePolicy() {
36
- return QWEN_POLICIES[this.model] ?? {};
12
+ export class QwenAnthropicProvider extends AnthropicCompatibleProvider {
13
+ constructor(apiKey, model, retry, baseURL) {
14
+ super(anthropicVendorProfiles.qwen, apiKey, model, retry, baseURL);
37
15
  }
38
16
  }
39
- export class QwenProvider {
40
- model;
41
- client;
42
- circuit;
43
- maxRetries;
44
- baseDelay;
45
- chat = new OpenAIChatAdapter();
46
- constructor(apiKey, model = "qwen3.6-plus", retry = { maxRetries: 3, baseDelay: 1000 }, baseURL = endpointProfiles["qwen.dashscope"].baseURL) {
47
- this.model = model;
48
- this.client = withServerRuntimeGuard(() => new OpenAI({ apiKey, baseURL }));
49
- this.circuit = new CircuitBreaker();
50
- this.maxRetries = retry.maxRetries;
51
- this.baseDelay = retry.baseDelay;
17
+ /**
18
+ * Qwen / DashScope over its OpenAI-compatible (DashScope) endpoint. Reasoning is carried
19
+ * out-of-band as `reasoning_content`; thinking is opted into via `enable_thinking` /
20
+ * `thinking_budget` (sent under `extra_body`). The streaming / tool-call machinery and the
21
+ * default `{ reasoning_content }` replay are inherited from OpenAIChatProvider; only request
22
+ * shaping and the (string-coerced) replay peek differ, supplied via the Template-Method hooks.
23
+ */
24
+ export class QwenProvider extends OpenAIChatProvider {
25
+ constructor(apiKey, model = "qwen3.6-plus", retry, baseURL = endpointProfiles["qwen.dashscope"].baseURL) {
26
+ super(apiKey, model, retry, baseURL);
52
27
  }
53
28
  runtimePolicy() {
54
29
  return QWEN_POLICIES[this.model] ?? {};
@@ -68,8 +43,35 @@ export class QwenProvider {
68
43
  },
69
44
  };
70
45
  }
71
- buildChatMessages(context) {
72
- return this.chat.buildMessages(context, { descriptor: this.descriptor() });
46
+ // DashScope auto prefix-caches and does not accept OpenAI's `prompt_cache_key`; omit it.
47
+ cacheKeyParams() {
48
+ return {};
49
+ }
50
+ // Reasoning arrives out-of-band as `reasoning_content`, never as inline <thinking> tags.
51
+ usesInlineThinkingTags() {
52
+ return false;
53
+ }
54
+ requestBodyExtras(extensions) {
55
+ // DashScope vendor knobs travel under `extra_body` in OpenAI-compat mode: thinking + web search.
56
+ const extraBody = { ...this.thinkingExtraBody(extensions), ...this.searchExtraBody(extensions) };
57
+ return Object.keys(extraBody).length ? { extra_body: extraBody } : {};
58
+ }
59
+ requestExtensions(extensions) {
60
+ return omitExtensionKeys(extensions, [
61
+ "model", "messages", "tools", "stream", "stream_options", "extra_body",
62
+ "enableThinking", "enable_thinking", "thinkingBudget", "thinking_budget",
63
+ "enable_search", "search_options",
64
+ ]);
65
+ }
66
+ // DashScope web search (Qwen vendor feature): `extensions={ enable_search: true }` + optional
67
+ // `search_options` (forced_search / search_strategy / enable_citation …). Mirrors the Python provider.
68
+ searchExtraBody(extensions) {
69
+ if (!extensions?.enable_search)
70
+ return {};
71
+ return {
72
+ enable_search: true,
73
+ ...(extensions.search_options != null ? { search_options: extensions.search_options } : {}),
74
+ };
73
75
  }
74
76
  peekProviderReplay(message) {
75
77
  const fields = this.chat.peekReplayFields(message);
@@ -82,129 +84,6 @@ export class QwenProvider {
82
84
  this.chat.rememberReplayFields(message, { reasoning_content: replay.reasoning_content });
83
85
  }
84
86
  }
85
- async complete(context, tools, extensions) {
86
- if (this.circuit.isOpen())
87
- throw new Error("Circuit breaker open");
88
- const msgs = this.buildChatMessages(context);
89
- const extraBody = this.thinkingExtraBody(extensions);
90
- let lastErr;
91
- for (let i = 0; i < this.maxRetries; i++) {
92
- try {
93
- const resp = await this.client.chat.completions.create({
94
- ...this.requestExtensions(extensions),
95
- model: this.model,
96
- messages: msgs,
97
- ...(tools.length ? { tools: this.chat.buildTools(tools) } : {}),
98
- ...(extraBody ? { extra_body: extraBody } : {}),
99
- });
100
- this.circuit.recordSuccess();
101
- const choice = resp.choices[0].message;
102
- const toolCalls = this.chat.normalizeToolCalls(choice.tool_calls ?? []);
103
- return { role: "assistant", content: choice.content ?? "", tokenCount: resp.usage?.completion_tokens ?? resp.usage?.total_tokens, toolCalls };
104
- }
105
- catch (err) {
106
- lastErr = err;
107
- this.circuit.recordFailure();
108
- if (i < this.maxRetries - 1)
109
- await new Promise(r => setTimeout(r, this.baseDelay * 2 ** i));
110
- }
111
- }
112
- throw lastErr;
113
- }
114
- async *stream(context, tools, extensions) {
115
- const msgs = this.buildChatMessages(context);
116
- const toolCallBufs = {};
117
- const emittedToolCallIndexes = new Set();
118
- let reasoningContent = "";
119
- let finalText = "";
120
- const extraBody = this.thinkingExtraBody(extensions);
121
- const stream = await this.client.chat.completions.create({
122
- ...this.requestExtensions(extensions),
123
- model: this.model,
124
- messages: msgs,
125
- ...(tools.length ? { tools: this.chat.buildTools(tools) } : {}),
126
- stream: true,
127
- stream_options: { include_usage: true },
128
- ...(extraBody ? { extra_body: extraBody } : {}),
129
- });
130
- let totalTokens = 0;
131
- let inputTokens = 0;
132
- let outputTokens = 0;
133
- let cacheReadTokens = 0;
134
- for await (const chunk of stream) {
135
- if (chunk.usage) {
136
- totalTokens = chunk.usage.total_tokens;
137
- inputTokens = chunk.usage.prompt_tokens ?? 0;
138
- outputTokens = chunk.usage.completion_tokens ?? 0;
139
- cacheReadTokens = openAICachedPromptTokens(chunk.usage);
140
- continue;
141
- }
142
- const choice = chunk.choices[0];
143
- if (!choice)
144
- continue;
145
- const delta = choice.delta;
146
- if (!delta)
147
- continue;
148
- if (delta.reasoning_content) {
149
- reasoningContent += String(delta.reasoning_content);
150
- yield { type: "thinking_delta", delta: delta.reasoning_content };
151
- }
152
- if (delta.content) {
153
- finalText += String(delta.content);
154
- yield { type: "text_delta", delta: delta.content };
155
- }
156
- for (const tc of delta.tool_calls ?? []) {
157
- const idx = tc.index;
158
- if (!toolCallBufs[idx])
159
- toolCallBufs[idx] = { id: tc.id ?? "", name: "", argsBuf: "" };
160
- if (tc.function?.name)
161
- toolCallBufs[idx].name += tc.function.name;
162
- toolCallBufs[idx].argsBuf += tc.function?.arguments ?? "";
163
- }
164
- if (choice.finish_reason === "tool_calls") {
165
- const toolCalls = Object.values(toolCallBufs).map(tb => ({
166
- id: tb.id, name: tb.name, arguments: tb.argsBuf || "{}",
167
- }));
168
- this.chat.rememberReplayFields({ content: finalText, toolCalls }, { reasoning_content: reasoningContent });
169
- for (const [index, tb] of Object.entries(toolCallBufs)) {
170
- const idx = Number(index);
171
- if (emittedToolCallIndexes.has(idx))
172
- continue;
173
- let args = {};
174
- try {
175
- args = JSON.parse(tb.argsBuf || "{}");
176
- }
177
- catch {
178
- args = {};
179
- }
180
- emittedToolCallIndexes.add(idx);
181
- yield { type: "tool_call", id: tb.id, name: tb.name, arguments: args };
182
- }
183
- }
184
- }
185
- const toolCalls = Object.values(toolCallBufs).map(tb => ({
186
- id: tb.id, name: tb.name, arguments: tb.argsBuf || "{}",
187
- }));
188
- if (toolCalls.length || reasoningContent) {
189
- this.chat.rememberReplayFields({ content: finalText, toolCalls }, { reasoning_content: reasoningContent });
190
- }
191
- for (const [index, tb] of Object.entries(toolCallBufs)) {
192
- const idx = Number(index);
193
- if (emittedToolCallIndexes.has(idx))
194
- continue;
195
- let args = {};
196
- try {
197
- args = JSON.parse(tb.argsBuf || "{}");
198
- }
199
- catch {
200
- args = {};
201
- }
202
- emittedToolCallIndexes.add(idx);
203
- yield { type: "tool_call", id: tb.id, name: tb.name, arguments: args };
204
- }
205
- if (totalTokens > 0)
206
- yield { type: "usage", totalTokens, inputTokens, outputTokens, ...(cacheReadTokens > 0 ? { cacheReadInputTokens: cacheReadTokens } : {}) };
207
- }
208
87
  thinkingExtraBody(extensions) {
209
88
  const enableThinking = Boolean(extensions?.enableThinking ?? extensions?.enable_thinking);
210
89
  const thinkingBudget = extensions?.thinkingBudget ?? extensions?.thinking_budget;
@@ -215,10 +94,4 @@ export class QwenProvider {
215
94
  ...(typeof thinkingBudget === "number" ? { thinking_budget: thinkingBudget } : {}),
216
95
  };
217
96
  }
218
- requestExtensions(extensions) {
219
- return omitExtensionKeys(extensions, [
220
- "model", "messages", "tools", "stream", "stream_options", "extra_body",
221
- "enableThinking", "enable_thinking", "thinkingBudget", "thinking_budget",
222
- ]);
223
- }
224
97
  }
@@ -0,0 +1,18 @@
1
+ import type { LLMProvider } from "../types.js";
2
+ export type ProviderRetry = {
3
+ maxRetries: number;
4
+ baseDelay: number;
5
+ };
6
+ /** Constructs a provider for one `(providerId, endpointProtocol)` pair. The lambda absorbs the
7
+ * per-class constructor-shape differences (e.g. AnthropicProvider takes a `{ baseURL }` options
8
+ * object, the rest take a positional `baseURL` string). */
9
+ export type ProviderMaker = (apiKey: string, model: string | undefined, retry: ProviderRetry | undefined, baseURL: string | undefined) => LLMProvider;
10
+ /** Build the registry key for a `(providerId, endpointProtocol)` pair. */
11
+ export declare function providerRegistryKey(providerId: string, protocol: string): string;
12
+ /**
13
+ * Single source of truth for which provider class backs each `(vendor, wire)` pair. Consumed by
14
+ * both `createProvider` (catalog) and the per-backend factory functions, so the two can no longer
15
+ * drift. Adding a vendor/wire = add a row here (+ its `vendor-profiles` / `endpointProfiles` data) —
16
+ * no dispatch branch to edit. Values are the same named classes as before, so `instanceof` holds.
17
+ */
18
+ export declare const PROVIDER_REGISTRY: Record<string, ProviderMaker>;
@@ -0,0 +1,35 @@
1
+ import { AnthropicProvider } from "./anthropic.js";
2
+ import { OpenAIChatProvider } from "./openai.js";
3
+ import { OpenAIResponsesProvider } from "./openai-responses.js";
4
+ import { DeepSeekProvider, DeepSeekAnthropicProvider } from "./deepseek.js";
5
+ import { KimiProvider, KimiAnthropicProvider } from "./kimi.js";
6
+ import { QwenProvider, QwenAnthropicProvider } from "./qwen.js";
7
+ import { GLMProvider, GLMAnthropicProvider } from "./glm.js";
8
+ import { MiniMaxOpenAIProvider, MiniMaxAnthropicProvider } from "./minimax.js";
9
+ import { GeminiProvider } from "./gemini.js";
10
+ /** Build the registry key for a `(providerId, endpointProtocol)` pair. */
11
+ export function providerRegistryKey(providerId, protocol) {
12
+ return `${providerId}:${protocol}`;
13
+ }
14
+ /**
15
+ * Single source of truth for which provider class backs each `(vendor, wire)` pair. Consumed by
16
+ * both `createProvider` (catalog) and the per-backend factory functions, so the two can no longer
17
+ * drift. Adding a vendor/wire = add a row here (+ its `vendor-profiles` / `endpointProfiles` data) —
18
+ * no dispatch branch to edit. Values are the same named classes as before, so `instanceof` holds.
19
+ */
20
+ export const PROVIDER_REGISTRY = {
21
+ "anthropic:anthropic-messages": (k, m, r, b) => new AnthropicProvider(k, m, r, { baseURL: b }),
22
+ "openai:openai-chat": (k, m, r, b) => new OpenAIChatProvider(k, m, r, b),
23
+ "openai:openai-responses": (k, m, r, b) => new OpenAIResponsesProvider(k, m, r, b),
24
+ "deepseek:openai-chat": (k, m, r, b) => new DeepSeekProvider(k, m, r, b),
25
+ "deepseek:anthropic-messages": (k, m, r, b) => new DeepSeekAnthropicProvider(k, m, r, b),
26
+ "kimi:openai-chat": (k, m, r, b) => new KimiProvider(k, m, r, b),
27
+ "kimi:anthropic-messages": (k, m, r, b) => new KimiAnthropicProvider(k, m, r, b),
28
+ "qwen:openai-chat": (k, m, r, b) => new QwenProvider(k, m, r, b),
29
+ "qwen:anthropic-messages": (k, m, r, b) => new QwenAnthropicProvider(k, m, r, b),
30
+ "glm:openai-chat": (k, m, r, b) => new GLMProvider(k, m, r, b),
31
+ "glm:anthropic-messages": (k, m, r, b) => new GLMAnthropicProvider(k, m, r, b),
32
+ "minimax:openai-chat": (k, m, r, b) => new MiniMaxOpenAIProvider(k, m, r, b),
33
+ "minimax:anthropic-messages": (k, m, r, b) => new MiniMaxAnthropicProvider(k, m, r, b),
34
+ "gemini:gemini": (k, m, r, b) => new GeminiProvider(k, m, r, b),
35
+ };
@@ -0,0 +1,54 @@
1
+ import type { RuntimePolicy } from "../types.js";
2
+ import { endpointProfiles } from "./profiles.js";
3
+ import type { ProviderId } from "./profiles.js";
4
+ export type EndpointProfileKey = keyof typeof endpointProfiles;
5
+ export interface AnthropicVendorProfile {
6
+ /** Identity advertised in `descriptor().provider`. */
7
+ providerId: ProviderId;
8
+ /** Model used when the caller does not pass one. */
9
+ defaultModel: string;
10
+ /** Endpoint profile whose `baseURL` is the Anthropic-compatible wire for this vendor. */
11
+ baseURLProfileKey: EndpointProfileKey;
12
+ /** Recommended `maxTurns` per model id; missing model → empty policy. */
13
+ policies: Record<string, RuntimePolicy>;
14
+ }
15
+ export declare const DEEPSEEK_POLICIES: Record<string, RuntimePolicy>;
16
+ export declare const KIMI_POLICIES: Record<string, RuntimePolicy>;
17
+ export declare const QWEN_POLICIES: Record<string, RuntimePolicy>;
18
+ export declare const GLM_POLICIES: Record<string, RuntimePolicy>;
19
+ export declare const MINIMAX_POLICIES: Record<string, RuntimePolicy>;
20
+ export declare const anthropicVendorProfiles: {
21
+ deepseek: {
22
+ providerId: "deepseek";
23
+ defaultModel: string;
24
+ baseURLProfileKey: "deepseek.anthropic";
25
+ policies: Record<string, RuntimePolicy>;
26
+ };
27
+ kimi: {
28
+ providerId: "kimi";
29
+ defaultModel: string;
30
+ baseURLProfileKey: "kimi.anthropic";
31
+ policies: Record<string, RuntimePolicy>;
32
+ };
33
+ qwen: {
34
+ providerId: "qwen";
35
+ defaultModel: string;
36
+ baseURLProfileKey: "qwen.anthropic";
37
+ policies: Record<string, RuntimePolicy>;
38
+ };
39
+ glm: {
40
+ providerId: "glm";
41
+ defaultModel: string;
42
+ baseURLProfileKey: "glm.anthropic";
43
+ policies: Record<string, RuntimePolicy>;
44
+ };
45
+ minimax: {
46
+ providerId: "minimax";
47
+ defaultModel: string;
48
+ baseURLProfileKey: "minimax.anthropic";
49
+ policies: Record<string, RuntimePolicy>;
50
+ };
51
+ };
52
+ export type AnthropicVendorId = keyof typeof anthropicVendorProfiles;
53
+ /** Resolve the Anthropic-compatible base URL for a vendor profile. */
54
+ export declare function anthropicVendorBaseURL(profile: AnthropicVendorProfile): string;
@@ -0,0 +1,66 @@
1
+ import { endpointProfiles } from "./profiles.js";
2
+ export const DEEPSEEK_POLICIES = {
3
+ "deepseek-chat": { maxTurns: 25 },
4
+ "deepseek-reasoner": { maxTurns: 50 },
5
+ "deepseek-v4-flash": { maxTurns: 20 },
6
+ "deepseek-v4-pro": { maxTurns: 35 },
7
+ };
8
+ export const KIMI_POLICIES = {
9
+ "moonshot-v1-8k": { maxTurns: 15 },
10
+ "moonshot-v1-32k": { maxTurns: 20 },
11
+ "moonshot-v1-128k": { maxTurns: 30 },
12
+ "kimi-k2.5": { maxTurns: 30 },
13
+ "kimi-k2.6": { maxTurns: 35 },
14
+ "kimi-k2-thinking": { maxTurns: 50 },
15
+ "kimi-k2-thinking-turbo": { maxTurns: 40 },
16
+ };
17
+ export const QWEN_POLICIES = {
18
+ "qwen3.7-max-preview": { maxTurns: 45 },
19
+ "qwen3.7-plus-preview": { maxTurns: 40 },
20
+ "qwen3.6-max-preview": { maxTurns: 40 },
21
+ "qwen3.6-plus": { maxTurns: 35 },
22
+ "qwen3.6-flash": { maxTurns: 20 },
23
+ "qwen3.6-35b-a3b": { maxTurns: 25 },
24
+ "qwen3.6-27b": { maxTurns: 25 },
25
+ "qwen3.5-plus": { maxTurns: 35 },
26
+ "qwen3.5-flash": { maxTurns: 20 },
27
+ "qwen3.5-397b-a17b": { maxTurns: 35 },
28
+ "qwen3.5-122b-a10b": { maxTurns: 25 },
29
+ "qwen3.5-35b-a3b": { maxTurns: 20 },
30
+ "qwen3.5-27b": { maxTurns: 20 },
31
+ };
32
+ export const GLM_POLICIES = {
33
+ "glm-5.2": { maxTurns: 50 },
34
+ "glm/glm-5.2": { maxTurns: 50 },
35
+ "glm-5.1": { maxTurns: 50 },
36
+ "glm/glm-5.1": { maxTurns: 50 },
37
+ "glm-4-plus": { maxTurns: 35 },
38
+ "glm/glm-4-plus": { maxTurns: 35 },
39
+ "glm-4-flash": { maxTurns: 15 },
40
+ "glm/glm-4-flash": { maxTurns: 15 },
41
+ "glm-4-air": { maxTurns: 20 },
42
+ "glm/glm-4-air": { maxTurns: 20 },
43
+ };
44
+ export const MINIMAX_POLICIES = {
45
+ "MiniMax-M3": { maxTurns: 35 },
46
+ "MiniMax-M3-highspeed": { maxTurns: 35 },
47
+ "MiniMax-M2.7": { maxTurns: 35 },
48
+ "MiniMax-M2.7-highspeed": { maxTurns: 35 },
49
+ "MiniMax-M2.5": { maxTurns: 25 },
50
+ "MiniMax-M2.5-highspeed": { maxTurns: 25 },
51
+ "MiniMax-M2.1": { maxTurns: 25 },
52
+ "MiniMax-M2.1-highspeed": { maxTurns: 25 },
53
+ "MiniMax-M2": { maxTurns: 20 },
54
+ "MiniMax-Text-01": { maxTurns: 20 },
55
+ };
56
+ export const anthropicVendorProfiles = {
57
+ deepseek: { providerId: "deepseek", defaultModel: "deepseek-v4-flash", baseURLProfileKey: "deepseek.anthropic", policies: DEEPSEEK_POLICIES },
58
+ kimi: { providerId: "kimi", defaultModel: "kimi-k2.6", baseURLProfileKey: "kimi.anthropic", policies: KIMI_POLICIES },
59
+ qwen: { providerId: "qwen", defaultModel: "qwen3.6-plus", baseURLProfileKey: "qwen.anthropic", policies: QWEN_POLICIES },
60
+ glm: { providerId: "glm", defaultModel: "glm-5.2", baseURLProfileKey: "glm.anthropic", policies: GLM_POLICIES },
61
+ minimax: { providerId: "minimax", defaultModel: "MiniMax-M3", baseURLProfileKey: "minimax.anthropic", policies: MINIMAX_POLICIES },
62
+ };
63
+ /** Resolve the Anthropic-compatible base URL for a vendor profile. */
64
+ export function anthropicVendorBaseURL(profile) {
65
+ return endpointProfiles[profile.baseURLProfileKey].baseURL;
66
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * L2 (Blackboard) — a shared, append-only event stream that N peer agent sessions of one logical run
3
+ * observe. This is the pluggable storage seam (like `SessionLog`): the default `InMemoryEventStream`
4
+ * is process-local; back it with Postgres/Redis to span replicas/restarts.
5
+ *
6
+ * Visibility (spec §6.1): events are shared by default. Optional `channel` / `audience` tags scope an
7
+ * event to a subset of personas, enforced at the framework boundary (`readSince(seq, viewer)` + the
8
+ * `read_recent` tool) — context isolation, not convention.
9
+ */
10
+ /** One entry on the shared blackboard. `channel`/`audience` are optional visibility scoping. */
11
+ export interface BlackboardEvent {
12
+ seq: number;
13
+ payload: unknown;
14
+ /** Emitting persona id (or external source), for audit / `reactByMention`. */
15
+ source?: string;
16
+ /** Channel this event belongs to; only personas subscribed to it see it. Omit ⇒ all see it. */
17
+ channel?: string;
18
+ /** Explicit recipient persona ids; only they see it. Omit ⇒ all see it (subject to `channel`). */
19
+ audience?: string[];
20
+ }
21
+ /** A reader's identity for visibility filtering. */
22
+ export interface EventViewer {
23
+ personaId: string;
24
+ /** Channels this persona is subscribed to. */
25
+ channels?: string[];
26
+ }
27
+ /** Default full-share visibility rule (spec §6.1). */
28
+ export declare function isVisibleTo(event: Pick<BlackboardEvent, "channel" | "audience">, viewer: EventViewer): boolean;
29
+ export interface EventStream {
30
+ /** Append an event; returns it stamped with its assigned `seq`. */
31
+ append(event: Omit<BlackboardEvent, "seq">): Promise<BlackboardEvent>;
32
+ /** Events after `seq`. With a `viewer`, only those visible to it (default: all). */
33
+ readSince(seq: number, viewer?: EventViewer): Promise<BlackboardEvent[]>;
34
+ /** Notify a listener on each appended event. Returns an unsubscribe fn. */
35
+ subscribe(cb: (e: BlackboardEvent) => void): () => void;
36
+ }
37
+ /** Process-local default blackboard. */
38
+ export declare class InMemoryEventStream implements EventStream {
39
+ private readonly events;
40
+ private readonly listeners;
41
+ append(event: Omit<BlackboardEvent, "seq">): Promise<BlackboardEvent>;
42
+ readSince(seq: number, viewer?: EventViewer): Promise<BlackboardEvent[]>;
43
+ subscribe(cb: (e: BlackboardEvent) => void): () => void;
44
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * L2 (Blackboard) — a shared, append-only event stream that N peer agent sessions of one logical run
3
+ * observe. This is the pluggable storage seam (like `SessionLog`): the default `InMemoryEventStream`
4
+ * is process-local; back it with Postgres/Redis to span replicas/restarts.
5
+ *
6
+ * Visibility (spec §6.1): events are shared by default. Optional `channel` / `audience` tags scope an
7
+ * event to a subset of personas, enforced at the framework boundary (`readSince(seq, viewer)` + the
8
+ * `read_recent` tool) — context isolation, not convention.
9
+ */
10
+ /** Default full-share visibility rule (spec §6.1). */
11
+ export function isVisibleTo(event, viewer) {
12
+ if (event.audience === undefined && event.channel === undefined)
13
+ return true;
14
+ if (event.audience?.includes(viewer.personaId))
15
+ return true;
16
+ if (event.channel !== undefined && viewer.channels?.includes(event.channel))
17
+ return true;
18
+ return false;
19
+ }
20
+ /** Process-local default blackboard. */
21
+ export class InMemoryEventStream {
22
+ events = [];
23
+ listeners = new Set();
24
+ async append(event) {
25
+ const stamped = { ...event, seq: this.events.length };
26
+ this.events.push(stamped);
27
+ for (const l of this.listeners)
28
+ l(stamped);
29
+ return stamped;
30
+ }
31
+ async readSince(seq, viewer) {
32
+ const after = this.events.filter(e => e.seq > seq);
33
+ return viewer ? after.filter(e => isVisibleTo(e, viewer)) : after;
34
+ }
35
+ subscribe(cb) {
36
+ this.listeners.add(cb);
37
+ return () => this.listeners.delete(cb);
38
+ }
39
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * L2 (ReactiveSession) — the user-facing primitive for "N peer agents over a shared event stream"
3
+ * (spec §6). It composes the lower layers so teams don't hand-roll the pattern:
4
+ * - L1 `RunGroup` — shared governance domain (cumulative budget + lineage) across the personas.
5
+ * - L0 `SignalGateway`— recipient-routed signals (targeted `interrupt` / `broadcast`).
6
+ * - `EventStream` — the shared blackboard (pluggable; default in-memory).
7
+ * - `TurnPolicy` — who reacts to each event (the one caller-customizable seam).
8
+ *
9
+ * Stateless-friendly: `emit` can run inside an HTTP handler; each persona's turn is a normal
10
+ * `run({sessionId})` whose continuity comes from its `SessionLog`, and `resume()` rebuilds the peer
11
+ * set from the persisted `RunGroup` membership — no hot in-process loop required.
12
+ */
13
+ import type { RuntimeRunner } from "./runner.js";
14
+ import type { RunGroup } from "./run-group.js";
15
+ import type { SignalSource, RuntimeSignal } from "../signals/types.js";
16
+ import { SignalGateway } from "../os/public.js";
17
+ import type { BlackboardEvent, EventStream, EventViewer } from "./event-stream.js";
18
+ import type { TurnPolicy } from "./turn-policy.js";
19
+ import type { RegisteredTool } from "../tools/index.js";
20
+ /**
21
+ * How a persona executes one reactive turn. The default body is a single `runner.run(...)` agent turn;
22
+ * override it to make a persona's turn a *different orchestration form* — e.g. drive a DAG via
23
+ * `ctx.runner.runWorkflow(spec)` (DAG-in-Peer) or any composite. The runner is already wired to the
24
+ * shared `RunGroup`, so whatever the body spawns stays under one governance domain. Must return the
25
+ * persona's reaction text.
26
+ */
27
+ export interface ReactorContext {
28
+ personaId: string;
29
+ goal: string;
30
+ event: BlackboardEvent;
31
+ /** The persona's runner — wired to the shared RunGroup / signal gateway / blackboard. */
32
+ runner: RuntimeRunner;
33
+ }
34
+ export type ReactorTurn = (ctx: ReactorContext) => Promise<string>;
35
+ /** Per-persona registration: its base reaction goal, role, channel subscriptions, and turn body. */
36
+ export interface ReactivePeerSpec {
37
+ goal?: string;
38
+ role?: string;
39
+ channels?: string[];
40
+ /**
41
+ * Override this persona's turn body (the seam for composing other mechanisms into a peer). Defaults
42
+ * to the session `reactWith`, then to a single `run()` agent turn. Use to make this peer's reaction
43
+ * a workflow DAG, a nested ensemble, etc. — all under the shared `RunGroup`.
44
+ */
45
+ react?: ReactorTurn;
46
+ }
47
+ /** What the caller appends to the blackboard via `emit`. */
48
+ export interface EmitEvent {
49
+ payload: unknown;
50
+ source?: string;
51
+ channel?: string;
52
+ audience?: string[];
53
+ }
54
+ export interface ReactiveSessionOptions {
55
+ /** Shared governance domain — all personas run under it (L1). */
56
+ runGroup: RunGroup;
57
+ /** Who reacts to each event (L2). */
58
+ turnPolicy: TurnPolicy;
59
+ /** Shared blackboard. Defaults to a process-local `InMemoryEventStream`. */
60
+ eventStream?: EventStream;
61
+ /** Shared signal gateway for targeted interrupt / broadcast (L0). Defaults to a fresh one. */
62
+ signalGateway?: SignalGateway;
63
+ /**
64
+ * Build a runner for a persona, wiring in the shared governance + signal routing. The app owns the
65
+ * provider / execution plane / tools; spread `shared` into the `RuntimeRunner` options and register
66
+ * `readRecentTool(shared.eventStream, viewer)` so the persona can read the blackboard.
67
+ */
68
+ makeRunner: (personaId: string, shared: {
69
+ runGroup: RunGroup;
70
+ signalSource: SignalSource;
71
+ eventStream: EventStream;
72
+ }) => RuntimeRunner;
73
+ /** Goal for a persona's reactive turn. Defaults to a generic "react to the blackboard" prompt. */
74
+ goalFor?: (personaId: string, event: BlackboardEvent) => string;
75
+ /**
76
+ * Default turn body for peers that don't set their own `react`. Defaults to a single `run()` agent
77
+ * turn. Override to make every peer's turn a different orchestration form (e.g. a workflow DAG).
78
+ */
79
+ reactWith?: ReactorTurn;
80
+ }
81
+ /** A persona's reaction to an emitted event. */
82
+ export interface Reaction {
83
+ personaId: string;
84
+ output: string;
85
+ }
86
+ export declare class ReactiveSession {
87
+ private readonly opts;
88
+ private readonly peerSpecs;
89
+ private readonly runners;
90
+ private readonly policyState;
91
+ private readonly eventStream;
92
+ private readonly gateway;
93
+ constructor(opts: ReactiveSessionOptions);
94
+ /** Register a peer persona and record it in the group membership (lineage). */
95
+ addPeer(personaId: string, spec?: ReactivePeerSpec): void;
96
+ peers(): string[];
97
+ blackboard(): EventStream;
98
+ /**
99
+ * Append an event to the blackboard, ask the `TurnPolicy` which (visible) peers react, and drive one
100
+ * turn for each — returning their outputs. Each turn runs under the shared `RunGroup` governance.
101
+ */
102
+ emit(event: EmitEvent): Promise<Reaction[]>;
103
+ /** Targeted preemption: deliver a critical signal to one persona's loop only (L0 recipient routing). */
104
+ interrupt(personaId: string, signal: Partial<RuntimeSignal> & {
105
+ payload?: Record<string, unknown>;
106
+ }): Promise<void>;
107
+ /** Broadcast a signal to every persona (each sees it on its next turn). */
108
+ broadcast(signal: Partial<RuntimeSignal> & {
109
+ payload?: Record<string, unknown>;
110
+ }): Promise<void>;
111
+ private getRunner;
112
+ private driveTurn;
113
+ /**
114
+ * Rebuild a session from a persisted `RunGroup`: load its members (lineage) as peers. The blackboard
115
+ * continuity comes from the (persistent) `EventStream`. Turn-policy cursor state is not restored.
116
+ */
117
+ static resume(opts: ReactiveSessionOptions & {
118
+ peerSpecs?: Record<string, ReactivePeerSpec>;
119
+ }): Promise<ReactiveSession>;
120
+ }
121
+ /**
122
+ * A `read_recent` tool a persona uses to read the shared blackboard, scoped to what it may see. Register
123
+ * one per persona inside `makeRunner`. `viewer` is the reading persona (id + subscribed channels).
124
+ */
125
+ export declare function readRecentTool(eventStream: EventStream, viewer: EventViewer): RegisteredTool;