@beeos-ai/bma-dsh-adapter 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +11 -0
  3. package/README.md +32 -2
  4. package/UPGRADING.md +25 -0
  5. package/lib/adapter.d.ts +58 -0
  6. package/lib/adapter.js +212 -0
  7. package/lib/approval.d.ts +31 -0
  8. package/lib/approval.js +24 -0
  9. package/lib/async-queue.d.ts +12 -0
  10. package/lib/async-queue.js +41 -0
  11. package/lib/catalog-gate.d.ts +7 -0
  12. package/lib/catalog-gate.js +28 -0
  13. package/lib/conformance/golden/shell-tool-events.json +198 -0
  14. package/lib/conformance/golden/turn-reasoning-text.json +26 -0
  15. package/lib/conformance/golden/turn-tool-call.json +26 -0
  16. package/lib/conformance/index.d.ts +32 -0
  17. package/lib/conformance/index.js +155 -0
  18. package/lib/conformance/shell.d.ts +64 -0
  19. package/lib/conformance/shell.js +202 -0
  20. package/lib/events.d.ts +21 -0
  21. package/lib/events.js +30 -0
  22. package/lib/index.d.ts +12 -0
  23. package/lib/index.js +13 -0
  24. package/lib/kernel.d.ts +18 -0
  25. package/lib/kernel.js +54 -0
  26. package/lib/model-catalog.d.ts +51 -0
  27. package/lib/model-catalog.js +98 -0
  28. package/lib/model.d.ts +62 -0
  29. package/lib/model.js +366 -0
  30. package/lib/recovery.d.ts +8 -0
  31. package/lib/recovery.js +19 -0
  32. package/lib/spi.d.ts +179 -0
  33. package/lib/spi.js +24 -0
  34. package/lib/stop.d.ts +21 -0
  35. package/lib/stop.js +53 -0
  36. package/lib/system-prompt.d.ts +3 -0
  37. package/lib/system-prompt.js +13 -0
  38. package/lib/testing/index.d.ts +3 -0
  39. package/lib/testing/index.js +3 -0
  40. package/lib/testing/scripted-model.d.ts +78 -0
  41. package/lib/testing/scripted-model.js +56 -0
  42. package/lib/testing/tmp.d.ts +24 -0
  43. package/lib/testing/tmp.js +55 -0
  44. package/lib/testing/tools.d.ts +3 -0
  45. package/lib/testing/tools.js +11 -0
  46. package/lib/version.d.ts +1 -0
  47. package/lib/version.js +4 -0
  48. package/package.json +75 -3
package/lib/model.js ADDED
@@ -0,0 +1,366 @@
1
+ // dsh LlmAdapter over OpenAI Chat Completions. Every request is routed by the
2
+ // session that issued it (GenerateOptions.sessionId) through the host's
3
+ // ModelPort: each session carries its own platform-issued token, so the
4
+ // platform attributes each request to exactly one session. A request without
5
+ // a session is never sent (fail closed). No provider key lives in the brain.
6
+ import { LlmAdapter, LlmError, CONTEXT_WINDOW_EXCEEDED_CODE, attributionHeaders, isContextWindowExceededError, offloadedImageText, projectOffloadedImages, } from "@deepseek-ai/dsh-llm";
7
+ import { requestMaxTokens } from "./model-catalog.js";
8
+ export const PROVIDER = "bma";
9
+ /** Error code of a model stream that sent no data for the idle limit (typed stop model_stream_idle). */
10
+ export const MODEL_STREAM_IDLE = "MODEL_STREAM_IDLE";
11
+ /**
12
+ * Tool result images (computer_observe screenshots) are kept in memory for the
13
+ * most recent TOOL_IMAGE_CALLS calls of a session and sent with those results
14
+ * only; older ones, and all of them after a restart, are left out (the result
15
+ * text stays). Basis: Anthropic's computer-use reference loop keeps only the N
16
+ * most recent screenshots in the request (only_n_most_recent_images, default
17
+ * 3) — screenshots are large and only the latest describe the screen.
18
+ */
19
+ export const TOOL_IMAGE_CALLS = 3;
20
+ export class RecentToolImages {
21
+ bySession = new Map();
22
+ remember(sessionId, callId, images) {
23
+ const list = this.bySession.get(sessionId) ?? [];
24
+ list.push({ callId, images: images.map((i) => ({ mediaType: i.mediaType, data: i.data })) });
25
+ this.bySession.set(sessionId, list.slice(-TOOL_IMAGE_CALLS));
26
+ }
27
+ get(sessionId, callId) {
28
+ return this.bySession.get(sessionId)?.find((e) => e.callId === callId)?.images;
29
+ }
30
+ forget(sessionId) {
31
+ this.bySession.delete(sessionId);
32
+ }
33
+ }
34
+ /**
35
+ * Idle before any content delta (no text / reasoning / tool-call delta yet) is retried
36
+ * once on a fresh request after this pause. Basis: the official Anthropic and OpenAI SDKs
37
+ * retry connection errors and timeouts automatically only while no response content has
38
+ * been received (max_retries=2 by default, exponential backoff 0.5s..8s with jitter);
39
+ * we use 1 retry and 1-2s (Lead ruling). Once any content arrived nothing is retried.
40
+ */
41
+ export const DEFAULT_IDLE_RETRY_BACKOFF_MS = [1_000, 2_000];
42
+ /**
43
+ * Default stream idle limit. Same value as the Beework Desktop brain's model
44
+ * stream guard (behaviour description only); no industry basis. Any received
45
+ * bytes count, SSE keep-alive comments included.
46
+ */
47
+ export const DEFAULT_STREAM_IDLE_MS = 90_000;
48
+ function text(blocks) {
49
+ return blocks.map((b) => (b.type === "text" ? b.text : b.type === "file" ? "[file omitted]" : b.type === "image" ? "[image omitted]" : "")).join("");
50
+ }
51
+ /** A user message's content: a string, or text + image_url parts when it carries images. */
52
+ async function userContent(blocks, options, signal) {
53
+ if (!blocks.some((b) => b.type === "image"))
54
+ return text(blocks);
55
+ const parts = [];
56
+ for (const b of blocks) {
57
+ if (b.type === "image") {
58
+ const image = await options.readImage(b, signal);
59
+ parts.push({ type: "image_url", image_url: { url: `data:${image.mediaType};base64,${image.data}` } });
60
+ }
61
+ else {
62
+ const t = text([b]);
63
+ if (t)
64
+ parts.push({ type: "text", text: t });
65
+ }
66
+ }
67
+ return parts;
68
+ }
69
+ async function toOpenAi(input, options, sessionId, system, signal) {
70
+ const messages = projectOffloadedImages(input, (ref) => offloadedImageText(ref));
71
+ const out = system ? [{ role: "system", content: system }] : [];
72
+ // Chat Completions tool messages carry text only: the images of a run of
73
+ // tool results follow it as one user message (text naming the call + image).
74
+ let toolImages = [];
75
+ const flushToolImages = () => {
76
+ if (toolImages.length)
77
+ out.push({ role: "user", content: toolImages });
78
+ toolImages = [];
79
+ };
80
+ for (const m of messages) {
81
+ if (m.role !== "tool")
82
+ flushToolImages();
83
+ switch (m.role) {
84
+ case "system":
85
+ case "developer": {
86
+ const t = text(m.content);
87
+ if (t)
88
+ out.push({ role: "system", content: t });
89
+ break;
90
+ }
91
+ case "user":
92
+ out.push({ role: "user", content: await userContent(m.content, options, signal) });
93
+ break;
94
+ case "assistant": {
95
+ const calls = m.content.filter((b) => b.type === "tool-call");
96
+ out.push({
97
+ role: "assistant",
98
+ content: text(m.content) || null,
99
+ ...(calls.length ? { tool_calls: calls.map((c) => ({ id: c.id, type: "function", function: { name: c.name, arguments: c.arguments || "{}" } })) } : {}),
100
+ });
101
+ break;
102
+ }
103
+ case "tool": {
104
+ const images = options.toolImages?.(sessionId, m.toolCallId) ?? [];
105
+ out.push({ role: "tool", tool_call_id: m.toolCallId, content: text(m.content) + (images.length ? `\n[${images.length} image(s) of this result follow]` : "") });
106
+ if (images.length) {
107
+ toolImages.push({ type: "text", text: `Image(s) returned by tool call ${m.toolCallId}:` });
108
+ for (const image of images)
109
+ toolImages.push({ type: "image_url", image_url: { url: `data:${image.mediaType};base64,${image.data}` } });
110
+ }
111
+ break;
112
+ }
113
+ }
114
+ }
115
+ flushToolImages();
116
+ return out;
117
+ }
118
+ function failure(status, body) {
119
+ // The canonical overflow code lets dsh compact and retry (compaction-basic reacts to it).
120
+ const code = isContextWindowExceededError(body) ? CONTEXT_WINDOW_EXCEEDED_CODE
121
+ : status === 401 || status === 403 ? "AUTH" : status === 429 ? "RATE_LIMIT" : "PROVIDER_HTTP";
122
+ return new LlmError(`model endpoint HTTP ${status}: ${body.slice(0, 300)}`, code, { status });
123
+ }
124
+ export class ChatCompletionsAdapter extends LlmAdapter {
125
+ port;
126
+ options;
127
+ constructor(port, options) {
128
+ super();
129
+ this.port = port;
130
+ this.options = options;
131
+ }
132
+ /** Window and output cap come from the host's model catalog, never from constants here. */
133
+ async resolveModel(provider, model) {
134
+ const limits = this.port.limits(model);
135
+ return { provider, id: model, name: model, context: { contextWindow: limits.contextWindow }, defaultMaxTokens: requestMaxTokens(limits) };
136
+ }
137
+ async *stream(request) {
138
+ const sessionId = request.sessionId;
139
+ if (!sessionId)
140
+ throw new LlmError("model request without a session id", "NO_SESSION");
141
+ let route;
142
+ try {
143
+ route = this.port.route(sessionId);
144
+ }
145
+ catch (err) {
146
+ throw new LlmError(`no model route for session ${sessionId}: ${err.message}`, "NO_SESSION");
147
+ }
148
+ const started = performance.now();
149
+ const limits = this.port.limits(route.model);
150
+ // An ordinary request asks for the per-request cap, not the model's ceiling; whatever the
151
+ // caller (loop or compaction) asked for is never above the ceiling, the model's real output limit.
152
+ const maxTokens = Math.min(request.maxTokens ?? requestMaxTokens(limits), limits.maxOutputTokens);
153
+ const [minPause, maxPause] = this.options.idleRetryBackoffMs ?? DEFAULT_IDLE_RETRY_BACKOFF_MS;
154
+ for (let attempt = 0;; attempt++) {
155
+ const idle = new IdleGuard(this.options.streamIdleMs, request.signal);
156
+ let content = false;
157
+ try {
158
+ for await (const chunk of this.run(request, sessionId, route, maxTokens, idle, started)) {
159
+ content = true; // the first chunk is a block-start, only ever produced by a content delta
160
+ yield chunk;
161
+ }
162
+ if (attempt > 0)
163
+ this.port.idleRetry?.(sessionId, "recovered");
164
+ return;
165
+ }
166
+ catch (err) {
167
+ if (!idle.fired)
168
+ throw err;
169
+ const stop = new LlmError(`model stream idle: no data for ${this.options.streamIdleMs} ms`, MODEL_STREAM_IDLE, { cause: err });
170
+ if (content || request.signal?.aborted)
171
+ throw stop;
172
+ if (attempt > 0) {
173
+ this.port.idleRetry?.(sessionId, "exhausted");
174
+ throw stop;
175
+ }
176
+ this.port.idleRetry?.(sessionId, "retry");
177
+ await pause(minPause + Math.random() * (maxPause - minPause), request.signal);
178
+ if (request.signal?.aborted)
179
+ throw stop; // cancelled while waiting: give up, no new request
180
+ }
181
+ finally {
182
+ idle.stop();
183
+ }
184
+ }
185
+ }
186
+ async *run(request, sessionId, route, maxTokens, idle, started) {
187
+ const messages = await toOpenAi(request.messages, this.options, sessionId, request.system, idle.signal);
188
+ const response = await fetch(`${route.baseUrl.replace(/\/$/, "")}/chat/completions`, {
189
+ method: "POST",
190
+ signal: idle.signal,
191
+ headers: { ...attributionHeaders(), "content-type": "application/json", authorization: `Bearer ${route.token}` },
192
+ body: JSON.stringify({
193
+ model: route.model,
194
+ stream: true,
195
+ stream_options: { include_usage: true },
196
+ messages,
197
+ ...(request.tools?.length ? { tools: request.tools.map((t) => ({ type: "function", function: { name: t.name, description: t.description, parameters: t.parameters } })) } : {}),
198
+ max_tokens: maxTokens,
199
+ ...(request.temperature !== undefined ? { temperature: request.temperature } : {}),
200
+ ...(request.stop?.length ? { stop: request.stop } : {}),
201
+ }),
202
+ });
203
+ if (!response.ok || !response.body)
204
+ throw failure(response.status, await response.text().catch(() => ""));
205
+ let next = 0;
206
+ let textIdx;
207
+ let reasoningIdx;
208
+ const texts = new Map();
209
+ const calls = new Map();
210
+ const order = [];
211
+ let finish;
212
+ let usage;
213
+ let first = true;
214
+ const open = (type) => {
215
+ const index = next++;
216
+ order.push({ index, type });
217
+ return { type: "block-start", index, blockType: type };
218
+ };
219
+ const decoder = new TextDecoder();
220
+ let buffer = "";
221
+ for await (const bytes of response.body) {
222
+ idle.touch();
223
+ buffer += decoder.decode(bytes, { stream: true });
224
+ let nl;
225
+ while ((nl = buffer.indexOf("\n")) >= 0) {
226
+ const line = buffer.slice(0, nl).trim();
227
+ buffer = buffer.slice(nl + 1);
228
+ if (!line.startsWith("data:"))
229
+ continue;
230
+ const data = line.slice(5).trim();
231
+ if (data === "[DONE]")
232
+ continue;
233
+ const json = JSON.parse(data);
234
+ if (json.error)
235
+ throw new LlmError(`model stream error: ${JSON.stringify(json.error).slice(0, 300)}`, "PROVIDER_STREAM");
236
+ if (json.usage) {
237
+ // dsh requires losslessly JSON-serializable chunks: no undefined members.
238
+ const u = json.usage;
239
+ usage = {
240
+ inputTokens: u.prompt_tokens ?? 0,
241
+ outputTokens: u.completion_tokens ?? 0,
242
+ ...(u.total_tokens !== undefined ? { totalTokens: u.total_tokens } : {}),
243
+ ...(u.prompt_tokens_details?.cached_tokens !== undefined ? { cacheReadTokens: u.prompt_tokens_details.cached_tokens } : {}),
244
+ ...(u.completion_tokens_details?.reasoning_tokens !== undefined ? { reasoningTokens: u.completion_tokens_details.reasoning_tokens } : {}),
245
+ };
246
+ }
247
+ const choice = json.choices?.[0];
248
+ if (!choice)
249
+ continue;
250
+ const delta = choice.delta ?? {};
251
+ const reasoning = delta.reasoning_content ?? delta.reasoning;
252
+ if (first && (delta.content || reasoning || delta.tool_calls)) {
253
+ first = false;
254
+ this.port.firstChunk(sessionId, performance.now() - started);
255
+ }
256
+ if (reasoning) {
257
+ if (reasoningIdx === undefined) {
258
+ const s = open("reasoning");
259
+ reasoningIdx = s.index;
260
+ yield s;
261
+ }
262
+ texts.set(reasoningIdx, (texts.get(reasoningIdx) ?? "") + reasoning);
263
+ yield { type: "reasoning-delta", index: reasoningIdx, text: reasoning };
264
+ }
265
+ if (delta.content) {
266
+ if (textIdx === undefined) {
267
+ const s = open("text");
268
+ textIdx = s.index;
269
+ yield s;
270
+ }
271
+ texts.set(textIdx, (texts.get(textIdx) ?? "") + delta.content);
272
+ yield { type: "text-delta", index: textIdx, text: delta.content };
273
+ }
274
+ for (const tc of delta.tool_calls ?? []) {
275
+ let call = calls.get(tc.index);
276
+ if (!call) {
277
+ const s = open("tool-call");
278
+ call = { index: s.index, id: tc.id ?? `call_${s.index}`, name: tc.function?.name ?? "", args: "" };
279
+ calls.set(tc.index, call);
280
+ yield s;
281
+ }
282
+ if (tc.function?.name && !call.name)
283
+ call.name = tc.function.name;
284
+ const piece = tc.function?.arguments ?? "";
285
+ call.args += piece;
286
+ yield { type: "tool-call-delta", index: call.index, id: call.id, ...(call.name ? { name: call.name } : {}), argumentsDelta: piece };
287
+ }
288
+ if (choice.finish_reason)
289
+ finish = choice.finish_reason;
290
+ }
291
+ }
292
+ for (const { index, type } of order) {
293
+ let block;
294
+ if (type === "tool-call") {
295
+ const call = [...calls.values()].find((c) => c.index === index);
296
+ block = { type: "tool-call", id: call.id, name: call.name, arguments: call.args };
297
+ }
298
+ else if (type === "reasoning") {
299
+ block = { type: "reasoning", text: texts.get(index) ?? "" };
300
+ }
301
+ else {
302
+ block = { type: "text", text: texts.get(index) ?? "" };
303
+ }
304
+ yield { type: "block-end", index, block };
305
+ }
306
+ if (usage) {
307
+ this.port.usage(sessionId, {
308
+ inputTokens: usage.inputTokens,
309
+ outputTokens: usage.outputTokens,
310
+ ...(usage.cacheReadTokens !== undefined ? { cacheReadTokens: usage.cacheReadTokens } : {}),
311
+ ...(usage.reasoningTokens !== undefined ? { reasoningTokens: usage.reasoningTokens } : {}),
312
+ });
313
+ yield { type: "usage", usage };
314
+ }
315
+ // A cut-off reply wins over its (possibly truncated) tool calls: they cannot be trusted.
316
+ const reason = finish === "length" ? { kind: "max-tokens" } : calls.size > 0 || finish === "tool_calls" ? { kind: "tool-calls" } : { kind: "stop" };
317
+ yield { type: "finish", reason };
318
+ }
319
+ }
320
+ /** Resolves after ms, or at once when the signal aborts. */
321
+ function pause(ms, signal) {
322
+ return new Promise((resolve) => {
323
+ if (signal?.aborted)
324
+ return resolve();
325
+ const done = () => { clearTimeout(timer); signal?.removeEventListener("abort", done); resolve(); };
326
+ const timer = setTimeout(done, ms);
327
+ signal?.addEventListener("abort", done, { once: true });
328
+ });
329
+ }
330
+ /** Aborts the request when nothing arrived for `ms`; touch() on every received chunk. Chains the caller's signal. */
331
+ class IdleGuard {
332
+ #ms;
333
+ #controller = new AbortController();
334
+ #timer;
335
+ #fired = false;
336
+ #stopCaller;
337
+ constructor(ms, caller) {
338
+ this.#ms = ms;
339
+ if (caller) {
340
+ const onAbort = () => this.#controller.abort(caller.reason);
341
+ if (caller.aborted)
342
+ onAbort();
343
+ else
344
+ caller.addEventListener("abort", onAbort, { once: true });
345
+ this.#stopCaller = () => caller.removeEventListener("abort", onAbort);
346
+ }
347
+ this.touch();
348
+ }
349
+ get signal() {
350
+ return this.#controller.signal;
351
+ }
352
+ get fired() {
353
+ return this.#fired;
354
+ }
355
+ touch() {
356
+ if (this.#ms <= 0)
357
+ return;
358
+ clearTimeout(this.#timer);
359
+ this.#timer = setTimeout(() => { this.#fired = true; this.#controller.abort(); }, this.#ms);
360
+ this.#timer.unref();
361
+ }
362
+ stop() {
363
+ clearTimeout(this.#timer);
364
+ this.#stopCaller?.();
365
+ }
366
+ }
@@ -0,0 +1,8 @@
1
+ import type { Context } from "@deepseek-ai/cordis";
2
+ import { type SessionEvent } from "@deepseek-ai/dsh-session";
3
+ export declare const CONTINUE_NOTE = "[platform] The brain host restarted while it was handling the message above. Continue it from where it stopped.";
4
+ export declare function assertResumable(ctx: Context, sessionId: string): Promise<void>;
5
+ /** The log already holds this user input. */
6
+ export declare function hasRecordedInput(events: readonly Pick<SessionEvent, "type" | "data">[], inputId: string): boolean;
7
+ /** A fresh id for the continuation note of an already recorded input. */
8
+ export declare const continuationId: (inputId: string) => string;
@@ -0,0 +1,19 @@
1
+ // Resume and input idempotency over dsh's own JSONL session log.
2
+ // - a session is resumable when its log exists (SessionNotFoundError otherwise);
3
+ // - a user input is identified by its platform input id: when the log already
4
+ // holds it (the host restarted mid-turn and the platform re-delivered it),
5
+ // the turn continues with a one-line note instead of adding the input twice.
6
+ import { randomUUID } from "node:crypto";
7
+ import { SessionId } from "@deepseek-ai/dsh-session";
8
+ import { SessionNotFoundError } from "./spi.js";
9
+ export const CONTINUE_NOTE = "[platform] The brain host restarted while it was handling the message above. Continue it from where it stopped.";
10
+ export async function assertResumable(ctx, sessionId) {
11
+ if (!(await ctx.sessionPersistence.stat(SessionId(sessionId))))
12
+ throw new SessionNotFoundError(sessionId);
13
+ }
14
+ /** The log already holds this user input. */
15
+ export function hasRecordedInput(events, inputId) {
16
+ return events.some((e) => e.type === "user/message" && e.data.id === inputId);
17
+ }
18
+ /** A fresh id for the continuation note of an already recorded input. */
19
+ export const continuationId = (inputId) => `${inputId}:continue:${randomUUID()}`;
package/lib/spi.d.ts ADDED
@@ -0,0 +1,179 @@
1
+ /** The six official agent_toolset tools a server-side brain may call (ADR 0005). */
2
+ export type ToolName = "bash" | "read" | "write" | "edit" | "glob" | "grep";
3
+ /** One model tool call handed to the platform. */
4
+ export interface ToolCall {
5
+ readonly sessionId: string;
6
+ /** The harness's id of the call; stable across a host restart (it is in the harness transcript). */
7
+ readonly callId: string;
8
+ readonly input: Record<string, unknown>;
9
+ /** Aborted when the harness stops waiting for the call. */
10
+ readonly signal: AbortSignal;
11
+ }
12
+ /** What the model reads back. Tool failures are results, never exceptions. */
13
+ export interface ToolResult {
14
+ readonly text: string;
15
+ readonly isError: boolean;
16
+ /** Images the model sees with the result (for example a computer_observe screenshot). */
17
+ readonly images?: readonly InputImage[];
18
+ }
19
+ /**
20
+ * A tool the platform provides. invoke() runs the whole platform path: the
21
+ * agent.tool_use event, the approval before the call, the execute-only
22
+ * gateway and the agent.tool_result event. The adapter only forwards calls.
23
+ */
24
+ export interface PlatformTool {
25
+ /** One of the six ToolName, or a tool the host declares for its machine (such as computer_action). */
26
+ readonly name: string;
27
+ readonly description: string;
28
+ /** JSON Schema of the input object. */
29
+ readonly parameters: Readonly<Record<string, unknown>>;
30
+ /** No side effects: the harness may run it concurrently with other calls. */
31
+ readonly readOnly: boolean;
32
+ invoke(call: ToolCall): Promise<ToolResult>;
33
+ }
34
+ /** Where one session's model requests go: the platform model endpoint with a session-scoped token. */
35
+ export interface ModelRoute {
36
+ /** OpenAI-compatible base URL ending in /v1. */
37
+ readonly baseUrl: string;
38
+ /** Session-scoped bearer token; the platform attributes every request carrying it to the session. */
39
+ readonly token: string;
40
+ readonly model: string;
41
+ }
42
+ export interface ModelUsage {
43
+ readonly inputTokens: number;
44
+ readonly outputTokens: number;
45
+ readonly cacheReadTokens?: number;
46
+ readonly reasoningTokens?: number;
47
+ }
48
+ /** Token limits of one model, from the host's model catalog. */
49
+ export interface ModelLimits {
50
+ /** Combined request + response context, in tokens. */
51
+ readonly contextWindow: number;
52
+ /** Largest completion the model can produce (a ceiling). An ordinary request asks for less: requestMaxTokens(). */
53
+ readonly maxOutputTokens: number;
54
+ /** declared: the platform said so in turn.start; catalog: operator catalog; default: neither knew the model (conservative values). */
55
+ readonly source: "declared" | "catalog" | "default";
56
+ }
57
+ /** Per-session model routing. No provider key ever reaches the harness. */
58
+ export interface ModelPort {
59
+ /** Limits of a model (never throws: unknown models get the conservative defaults and are recorded by the host). */
60
+ limits(model: string): ModelLimits;
61
+ /** Throws for a session the host does not hold: a request that cannot be attributed is never sent. */
62
+ route(sessionId: string): ModelRoute;
63
+ /** The first streamed model chunk of a request arrived, ms after it was sent. */
64
+ firstChunk(sessionId: string, ms: number): void;
65
+ usage(sessionId: string, usage: ModelUsage): void;
66
+ /**
67
+ * The model stream went idle before any content and the adapter reacted:
68
+ * "retry" (a fresh request follows), "recovered" (the retry delivered content),
69
+ * "exhausted" (the retry idled too; the turn fails with model_stream_idle).
70
+ * Hosts count it as model_stream_idle_retry_total{result} and log it.
71
+ */
72
+ idleRetry?(sessionId: string, result: "retry" | "recovered" | "exhausted"): void;
73
+ }
74
+ export interface HarnessCapabilities {
75
+ /** Continues a session from the harness's own durable state in a fresh process. */
76
+ readonly resume: boolean;
77
+ /** Streams "delta" events before each message/thinking event. */
78
+ readonly deltas: boolean;
79
+ /** Accepts more user input while a turn runs (turn.input → appendInput). */
80
+ readonly midTurnInput: boolean;
81
+ /** Passes HarnessInput.images to the model. */
82
+ readonly imageInput: boolean;
83
+ }
84
+ export interface SessionInit {
85
+ readonly sessionId: string;
86
+ readonly model: string;
87
+ /** The platform's system prompt; the harness adds nothing of its own (no identity, no runtime context). */
88
+ readonly systemPrompt: string;
89
+ /** Working directory on the session's machine, for the prompt only (tools run on the machine). */
90
+ readonly cwd: string;
91
+ }
92
+ /** One image of a user input, already fetched by the host. */
93
+ export interface InputImage {
94
+ readonly mediaType: "image/png" | "image/jpeg" | "image/webp" | "image/gif";
95
+ /** Canonical base64 of the encoded image. */
96
+ readonly data: string;
97
+ readonly name?: string;
98
+ }
99
+ export interface HarnessInput {
100
+ /** Platform input id, or a host-made id for a recovery note. */
101
+ readonly id: string;
102
+ readonly text: string;
103
+ /** Images the model sees with the text; only when capabilities().imageInput. */
104
+ readonly images?: readonly InputImage[];
105
+ }
106
+ /**
107
+ * Typed reasons a turn stops without finishing its work. They are the
108
+ * externally visible "bma_*" extension of the CMA stop reasons: the CMA set
109
+ * (end_turn, requires_action, retries_exhausted) has no member for them, and
110
+ * executor SDK 1.1.0 can only carry a typed error as the leading word of the
111
+ * session.error message ("<code>: <detail>", the same convention as the Go
112
+ * ACP harness). Anything else a harness throws stays a generic agent_error.
113
+ */
114
+ export type StopCode =
115
+ /** The model hit its output-token ceiling (finish_reason length / DSH max-tokens). */
116
+ "output_limit_reached"
117
+ /** The conversation no longer fits the context window after compaction. */
118
+ | "context_too_large"
119
+ /** The model stream sent no data for the idle limit. */
120
+ | "model_stream_idle";
121
+ export declare class TurnStopError extends Error {
122
+ readonly name = "TurnStopError";
123
+ readonly code: StopCode;
124
+ constructor(code: StopCode, detail: string);
125
+ }
126
+ /** What a turn streams back. Tool events are written by the host (PlatformTool.invoke), not here. */
127
+ export type HarnessEvent =
128
+ /** Preview text of the next message/thinking event; transient. */
129
+ {
130
+ readonly type: "delta";
131
+ readonly kind: "message" | "thinking";
132
+ readonly text: string;
133
+ } | {
134
+ readonly type: "thinking";
135
+ readonly text: string;
136
+ } | {
137
+ readonly type: "message";
138
+ readonly text: string;
139
+ };
140
+ /** resumeSession found no durable state for the session. */
141
+ export declare class SessionNotFoundError extends Error {
142
+ readonly name = "SessionNotFoundError";
143
+ constructor(sessionId: string);
144
+ }
145
+ export interface HarnessAdapter {
146
+ /** Stable id, for example "dsh". */
147
+ readonly id: string;
148
+ capabilities(): HarnessCapabilities;
149
+ /** Called once, before any session. */
150
+ configureModel(port: ModelPort): void;
151
+ /**
152
+ * Called once, before any session. Every session must expose exactly these
153
+ * tools and nothing else (fail-closed); the host checks toolCatalog() and
154
+ * refuses a session that differs.
155
+ */
156
+ registerTools(tools: readonly PlatformTool[]): void;
157
+ /** Starts a new harness session; durable once checkpoint() resolves. */
158
+ createSession(init: SessionInit): Promise<void>;
159
+ /** Loads a session this or an earlier process created (capabilities().resume). */
160
+ resumeSession(init: SessionInit): Promise<void>;
161
+ /** The tool names the model will see in this session. */
162
+ toolCatalog(sessionId: string): readonly string[];
163
+ /**
164
+ * Runs one turn for input and streams its events; the iteration ends when
165
+ * the turn ends. Throws when the turn fails. signal aborts the turn
166
+ * (cancel), after which the iteration ends without throwing.
167
+ * Idempotent per input.id: after a host restart the host may submit an
168
+ * input the harness already recorded; the harness then continues that
169
+ * input instead of adding it twice.
170
+ */
171
+ submitInput(sessionId: string, input: HarnessInput, signal: AbortSignal): AsyncIterable<HarnessEvent>;
172
+ /** Adds input to the running turn; only when capabilities().midTurnInput. */
173
+ appendInput(sessionId: string, input: HarnessInput): void;
174
+ /** Durability barrier over the session's harness state (used before an approval wait). */
175
+ checkpoint(sessionId: string): Promise<void>;
176
+ /** Releases the in-memory session; its durable state stays for a later resume. */
177
+ close(sessionId: string): Promise<void>;
178
+ dispose(): Promise<void>;
179
+ }
package/lib/spi.js ADDED
@@ -0,0 +1,24 @@
1
+ // HarnessAdapter SPI: the only code a new harness (DSH, Claude Agent SDK, ...)
2
+ // has to write. Everything platform-shaped — the executor agent channel,
3
+ // session lifecycle, the six platform tools and their approval/gateway path,
4
+ // per-session model routing, recovery after a host restart, limits, logs and
5
+ // metrics — lives in the host framework (src/host/) and reaches the harness
6
+ // only through these interfaces.
7
+ //
8
+ // Shape follows duyet/oma HarnessInterface/HarnessRuntime/HarnessContext and
9
+ // BMA H0 driver.Harness (ADR 0001/0004).
10
+ export class TurnStopError extends Error {
11
+ name = "TurnStopError";
12
+ code;
13
+ constructor(code, detail) {
14
+ super(`${code}: ${detail}`);
15
+ this.code = code;
16
+ }
17
+ }
18
+ /** resumeSession found no durable state for the session. */
19
+ export class SessionNotFoundError extends Error {
20
+ name = "SessionNotFoundError";
21
+ constructor(sessionId) {
22
+ super(`no durable harness state for session ${sessionId}`);
23
+ }
24
+ }
package/lib/stop.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ export interface DshTurnEndReason {
2
+ kind: string;
3
+ error?: {
4
+ message: string;
5
+ code?: string;
6
+ };
7
+ }
8
+ export declare function stopForTurnEnd(reason: DshTurnEndReason, context?: {
9
+ maxOutputTokens?: number;
10
+ streamIdleMs?: number;
11
+ }): Error | undefined;
12
+ /** The contract's stop code table (AgentErrorCode), in contract order. */
13
+ export declare const AGENT_ERROR_CODES: readonly ["output_limit_reached", "context_too_large", "model_stream_idle", "agent_error", "agent_unavailable", "agent_auth_required", "agent_protocol_error"];
14
+ export type AgentErrorCode = (typeof AGENT_ERROR_CODES)[number];
15
+ /**
16
+ * The contract code a failed turn reports: a typed stop is its own code, any
17
+ * other failure is agent_error. A host puts it first in the session.error
18
+ * message ("<code>: <detail>", which TurnStopError already does) or, with
19
+ * structured_errors, in error.type.
20
+ */
21
+ export declare function agentErrorCode(err: unknown): AgentErrorCode;