@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
@@ -0,0 +1,202 @@
1
+ // Shell-level conformance: what a host SHELL (brain-host, bma-dsh-acp, ...)
2
+ // must show the platform, whatever its transport. The adapter-level cases in
3
+ // index.ts pin the kernel; these pin the platform-visible behaviour:
4
+ // - tool events (agent.tool_use / agent.tool_result, CMA tool names, error
5
+ // results, streaming previews) are golden;
6
+ // - every turn_id ends with exactly one terminal (completed | canceled | failed),
7
+ // a typed failure carries its stop code (contract AgentErrorCode);
8
+ // - cancel is confirmed within CANCEL_ACK_BUDGET_MS even when the model hangs,
9
+ // and withdraws a pending approval;
10
+ // - a stalled model stream ends the turn as model_stream_idle (not a platform timeout);
11
+ // - an approval survives a shell restart: the same interaction id is asked
12
+ // again, an answered one is not asked of the user again, the call runs once.
13
+ // The platform side (G1 #614 "bma_outcome_unknown" after a cancel/close
14
+ // deadline) covers an unreachable shell; it is not testable from here.
15
+ import { test } from "node:test";
16
+ import assert from "node:assert/strict";
17
+ import { readFileSync, writeFileSync } from "node:fs";
18
+ import { approvalId } from "../approval.js";
19
+ import { createTestTempDir, removeAfter } from "../testing/tmp.js";
20
+ import { AGENT_ERROR_CODES } from "../stop.js";
21
+ import { last, textOf } from "../testing/scripted-model.js";
22
+ /** Budget for a canceled terminal after turn.cancel (docs/architecture/dsh-brain-best-practices.md 2.10: 10 s shell wait + 3 s kill, no industry basis). */
23
+ export const CANCEL_ACK_BUDGET_MS = 10_000;
24
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
25
+ async function until(check, timeoutMs, what) {
26
+ const end = Date.now() + timeoutMs;
27
+ for (;;) {
28
+ const v = check();
29
+ if (v)
30
+ return v;
31
+ if (Date.now() > end)
32
+ throw new Error(`timed out waiting for ${what}`);
33
+ await sleep(50);
34
+ }
35
+ }
36
+ const turnEvents = (shell, sid, turnId) => shell.events(sid).filter((e) => e.turnId === turnId);
37
+ const idleOf = (shell, sid, turnId) => turnEvents(shell, sid, turnId).find((e) => e.event.type === "session.status_idle");
38
+ /** The model: "TOOL <name> <json>" calls that tool, then reports; "FAIL" is cut at the output limit; "HANG" never answers; the rest is echoed. */
39
+ function shellScript(req) {
40
+ const m = last(req);
41
+ if (m.role === "tool")
42
+ return { text: "done" };
43
+ const text = textOf(m);
44
+ if (text.startsWith("[platform]"))
45
+ return { text: "recovered and continued" };
46
+ const call = /^TOOL (\w+) (.*)$/s.exec(text);
47
+ if (call)
48
+ return { toolCalls: [{ id: `call_${call[1]}_${text.length}`, name: call[1], args: JSON.parse(call[2]) }] };
49
+ if (text === "FAIL")
50
+ return { text: "cut off", finishReason: "length" };
51
+ if (text === "HANG")
52
+ return { text: "partial", hang: true };
53
+ return { reasoning: "thinking it over", text: `echo: ${text}` };
54
+ }
55
+ function golden(name, actual) {
56
+ const file = new URL(`./golden/${name}.json`, import.meta.url);
57
+ const text = `${JSON.stringify(actual, null, 2)}\n`;
58
+ if (process.env.UPDATE_GOLDEN === "1")
59
+ writeFileSync(file, text);
60
+ assert.equal(text, readFileSync(file, "utf8"), `golden ${name}.json differs (UPDATE_GOLDEN=1 rewrites it)`);
61
+ }
62
+ /**
63
+ * What the platform saw of one turn, free of volatile ids: event ids become
64
+ * evt_N by first appearance (tool_use_id follows), previews are joined per
65
+ * event, platform-added fields are dropped.
66
+ */
67
+ function platformView(shell, sid, turnId) {
68
+ const alias = new Map();
69
+ const name = (id) => alias.get(id) ?? (alias.set(id, `evt_${alias.size + 1}`), alias.get(id));
70
+ const events = turnEvents(shell, sid, turnId).map((e) => {
71
+ const { id: _id, processed_at: _p, bma_sequence: _s, ...rest } = e.event;
72
+ if (typeof rest.tool_use_id === "string")
73
+ rest.tool_use_id = name(rest.tool_use_id);
74
+ return { event_id: name(e.eventId), ...rest };
75
+ });
76
+ const previews = {};
77
+ for (const d of shell.deltas())
78
+ if (alias.has(d.eventId))
79
+ previews[name(d.eventId)] = (previews[name(d.eventId)] ?? "") + d.text;
80
+ return { events, previews };
81
+ }
82
+ export function registerShellConformance(name, factory) {
83
+ // The default home is removed after the factory registered its teardown (after hooks run in registration order).
84
+ const mount = async (t, o = {}) => {
85
+ const home = o.home ?? createTestTempDir("bma-shell-");
86
+ try {
87
+ return await factory(t, { script: shellScript, home, ...(o.streamIdleMs !== undefined ? { streamIdleMs: o.streamIdleMs } : {}) });
88
+ }
89
+ finally {
90
+ if (!o.home)
91
+ removeAfter(t, home);
92
+ }
93
+ };
94
+ const run = async (shell, sid, text, policy) => (await shell.startTurn({ sessionId: sid, text, ...(policy ? { policy } : {}) })).turnId;
95
+ const finished = (shell, sid, turnId, timeoutMs = 30_000) => until(() => idleOf(shell, sid, turnId), timeoutMs, `terminal of ${turnId}`);
96
+ test(`[conformance:${name}] shell events golden: tool_use / tool_result with CMA tool names, previews, a failed call and a denied call`, async (t) => {
97
+ const shell = await mount(t);
98
+ const sid = "sesn_gold";
99
+ const ok = await run(shell, sid, `TOOL bash {"command":"echo hi"}`);
100
+ await finished(shell, sid, ok);
101
+ const failing = await run(shell, sid, `TOOL bash {"command":"echo oops >&2; exit 3"}`);
102
+ await finished(shell, sid, failing);
103
+ const denied = await run(shell, sid, `TOOL bash {"command":"echo never"}`, { bash: "deny" });
104
+ await finished(shell, sid, denied);
105
+ const text = await run(shell, sid, "hello");
106
+ await finished(shell, sid, text);
107
+ golden("shell-tool-events", { success: platformView(shell, sid, ok), failed: platformView(shell, sid, failing), denied: platformView(shell, sid, denied), text: platformView(shell, sid, text) });
108
+ assert.deepEqual(shell.executedTools().map((c) => c.tool), ["bash", "bash"], "the denied call never reaches the tool backend");
109
+ });
110
+ test(`[conformance:${name}] terminal: every turn ends with exactly one terminal (completed | canceled | failed), and it is the last event`, async (t) => {
111
+ const shell = await mount(t);
112
+ const typed = (e) => {
113
+ const err = e.error;
114
+ return AGENT_ERROR_CODES.find((c) => err.type === c || err.message?.startsWith(`${c}: `));
115
+ };
116
+ const cases = [
117
+ { sid: "sesn_t1", text: "hi", outcome: "completed" },
118
+ { sid: "sesn_t2", text: "FAIL", outcome: "failed", code: "output_limit_reached" },
119
+ { sid: "sesn_t3", text: "HANG", outcome: "canceled" },
120
+ ];
121
+ for (const c of cases) {
122
+ const turnId = await run(shell, c.sid, c.text);
123
+ if (c.outcome === "canceled") {
124
+ await until(() => shell.model.requests.some((r) => textOf(last(r)) === "HANG"), 20_000, "model request");
125
+ await shell.cancelTurn(c.sid, turnId);
126
+ }
127
+ await finished(shell, c.sid, turnId);
128
+ await sleep(500); // a duplicate terminal would show up now
129
+ const events = turnEvents(shell, c.sid, turnId);
130
+ const idles = events.filter((e) => e.event.type === "session.status_idle");
131
+ assert.equal(idles.length, 1, `${c.outcome}: exactly one terminal`);
132
+ assert.equal(idles[0].event.turn_outcome, c.outcome);
133
+ assert.equal(events.at(-1), idles[0], "the terminal is the last event of its turn");
134
+ const errors = events.filter((e) => e.event.type === "session.error");
135
+ if (c.outcome === "failed") {
136
+ assert.equal(errors.length, 1, "a failed turn explains itself with one session.error");
137
+ assert.equal(typed(errors[0].event), c.code, "the error carries the contract stop code");
138
+ }
139
+ else
140
+ assert.equal(errors.length, 0);
141
+ }
142
+ });
143
+ test(`[conformance:${name}] cancel ack: canceled within the budget even when the model hangs; a pending approval is withdrawn`, async (t) => {
144
+ const shell = await mount(t);
145
+ const hang = await run(shell, "sesn_c1", "HANG");
146
+ await until(() => shell.model.requests.some((r) => textOf(last(r)) === "HANG"), 20_000, "model request");
147
+ let started = Date.now();
148
+ await shell.cancelTurn("sesn_c1", hang);
149
+ assert.equal((await finished(shell, "sesn_c1", hang, CANCEL_ACK_BUDGET_MS)).event.turn_outcome, "canceled");
150
+ assert.ok(Date.now() - started < CANCEL_ACK_BUDGET_MS);
151
+ const asked = await run(shell, "sesn_c2", `TOOL bash {"command":"echo asked"}`, { bash: "ask" });
152
+ const interaction = await until(() => shell.interactions("sesn_c2").find((i) => i.state === "open"), 20_000, "approval request");
153
+ started = Date.now();
154
+ await shell.cancelTurn("sesn_c2", asked);
155
+ assert.equal((await finished(shell, "sesn_c2", asked, CANCEL_ACK_BUDGET_MS)).event.turn_outcome, "canceled");
156
+ assert.ok(Date.now() - started < CANCEL_ACK_BUDGET_MS);
157
+ await until(() => shell.interactions("sesn_c2").find((i) => i.id === interaction.id)?.state === "canceled", 5_000, "interaction withdrawn");
158
+ assert.equal(shell.executedTools().length, 0, "nothing ran");
159
+ });
160
+ test(`[conformance:${name}] stream idle: a stalled model stream ends the turn as model_stream_idle, once`, async (t) => {
161
+ const shell = await mount(t, { streamIdleMs: 1_000 });
162
+ const turnId = await run(shell, "sesn_i1", "HANG");
163
+ const idle = await finished(shell, "sesn_i1", turnId, 20_000);
164
+ assert.equal(idle.event.turn_outcome, "failed");
165
+ const errors = turnEvents(shell, "sesn_i1", turnId).filter((e) => e.event.type === "session.error");
166
+ assert.equal(errors.length, 1);
167
+ const err = errors[0].event.error;
168
+ assert.ok(err.type === "model_stream_idle" || err.message?.startsWith("model_stream_idle: "), JSON.stringify(err));
169
+ await sleep(500);
170
+ assert.equal(turnEvents(shell, "sesn_i1", turnId).filter((e) => e.event.type === "session.status_idle").length, 1);
171
+ });
172
+ for (const answered of ["after the restart", "while the shell is down"]) {
173
+ test(`[conformance:${name}] approval: a restarted shell re-asks the same interaction id; an answered one is not asked of the user again (answer ${answered})`, async (t) => {
174
+ const shell = await mount(t);
175
+ const sid = `sesn_a_${answered.length}`;
176
+ const file = `approved-${answered.length}.txt`;
177
+ const turnId = await run(shell, sid, `TOOL bash {"command":"echo survived >> ${file}"}`, { bash: "ask" });
178
+ const first = await until(() => shell.interactions(sid).find((i) => i.state === "open"), 20_000, "approval request");
179
+ assert.equal(first.toolName, "bash");
180
+ assert.equal(first.id, approvalId(sid, turnId, `call_bash_${`TOOL bash {"command":"echo survived >> ${file}"}`.length}`), "the id is derived from session, turn and harness call id");
181
+ assert.equal(shell.executedTools().length, 0, "nothing ran before the answer");
182
+ await shell.stop("SIGKILL");
183
+ if (answered === "while the shell is down")
184
+ await shell.answer(first.id, "allow");
185
+ assert.notEqual(shell.interactions(sid).find((i) => i.id === first.id)?.state, "canceled", "a crash does not withdraw the approval");
186
+ await shell.start();
187
+ await shell.redeliver(sid, turnId);
188
+ if (answered === "after the restart") {
189
+ await until(() => (shell.interactions(sid).find((i) => i.id === first.id)?.requests ?? 0) >= 2, 20_000, "the same interaction asked again");
190
+ assert.equal(shell.interactions(sid).find((i) => i.id === first.id)?.state, "open");
191
+ await shell.answer(first.id, "allow");
192
+ }
193
+ assert.equal((await finished(shell, sid, turnId)).event.turn_outcome, "completed");
194
+ assert.deepEqual(shell.interactions(sid).map((i) => i.id), [first.id], "one interaction, one id");
195
+ assert.equal(shell.interactions(sid)[0].state, "answered", "an answered interaction is never reopened for the user");
196
+ assert.equal(shell.executedTools().length, 1, "executed once");
197
+ const uses = turnEvents(shell, sid, turnId).filter((e) => e.event.type === "agent.tool_use");
198
+ assert.equal(uses.length, 1, "no second agent.tool_use for the recovered call");
199
+ assert.equal(turnEvents(shell, sid, turnId).filter((e) => e.event.type === "session.status_idle").length, 1);
200
+ });
201
+ }
202
+ }
@@ -0,0 +1,21 @@
1
+ import type { AssistantStreamFrame } from "@deepseek-ai/dsh-agent";
2
+ import type { SessionEvent } from "@deepseek-ai/dsh-session";
3
+ import type { HarnessEvent } from "./spi.ts";
4
+ type Kind = "message" | "thinking";
5
+ /** What a finished assistant/message event contributes: thinking first, then the visible text; whitespace-only text is dropped. */
6
+ export declare function harnessEventsFromSessionEvent(event: Pick<SessionEvent, "type" | "data">): HarnessEvent[];
7
+ /** The preview text of a streamed chunk, or undefined for every other frame. */
8
+ export declare function harnessEventFromStreamFrame(frame: AssistantStreamFrame): HarnessEvent | undefined;
9
+ export type CmaMessageEventType = "agent.message" | "agent.thinking";
10
+ export declare const cmaEventType: (kind: Kind) => CmaMessageEventType;
11
+ /** The durable CMA event for a finished thinking / message. */
12
+ export declare function cmaMessageEvent(event: Extract<HarnessEvent, {
13
+ type: "message" | "thinking";
14
+ }>): {
15
+ type: CmaMessageEventType;
16
+ content: {
17
+ type: "text";
18
+ text: string;
19
+ }[];
20
+ };
21
+ export {};
package/lib/events.js ADDED
@@ -0,0 +1,30 @@
1
+ /** What a finished assistant/message event contributes: thinking first, then the visible text; whitespace-only text is dropped. */
2
+ export function harnessEventsFromSessionEvent(event) {
3
+ if (event.type !== "assistant/message")
4
+ return [];
5
+ const content = event.data.message.content;
6
+ const thinking = content.filter((b) => b.type === "reasoning").map((b) => b.text).join("");
7
+ const text = content.filter((b) => b.type === "text").map((b) => b.text).join("");
8
+ const out = [];
9
+ if (thinking)
10
+ out.push({ type: "thinking", text: thinking });
11
+ if (text.trim())
12
+ out.push({ type: "message", text });
13
+ return out;
14
+ }
15
+ /** The preview text of a streamed chunk, or undefined for every other frame. */
16
+ export function harnessEventFromStreamFrame(frame) {
17
+ if (frame.type !== "chunk")
18
+ return undefined;
19
+ const chunk = frame.chunk;
20
+ if (chunk.type === "text-delta")
21
+ return { type: "delta", kind: "message", text: chunk.text };
22
+ if (chunk.type === "reasoning-delta")
23
+ return { type: "delta", kind: "thinking", text: chunk.text };
24
+ return undefined;
25
+ }
26
+ export const cmaEventType = (kind) => (kind === "message" ? "agent.message" : "agent.thinking");
27
+ /** The durable CMA event for a finished thinking / message. */
28
+ export function cmaMessageEvent(event) {
29
+ return { type: cmaEventType(event.type), content: [{ type: "text", text: event.text }] };
30
+ }
package/lib/index.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ export * from "./spi.ts";
2
+ export { DshAdapter, type DshAdapterOptions } from "./adapter.ts";
3
+ export { mountKernel, COMPACTION_HEADROOM_TOKENS, COMPACTION_SUMMARY_MAX_TOKENS, type KernelOptions } from "./kernel.ts";
4
+ export { ChatCompletionsAdapter, DEFAULT_IDLE_RETRY_BACKOFF_MS, DEFAULT_STREAM_IDLE_MS, MODEL_STREAM_IDLE, PROVIDER, RecentToolImages, TOOL_IMAGE_CALLS, type ModelAdapterOptions, type RequestImage } from "./model.ts";
5
+ export { ModelCatalog, DEFAULT_LIMITS, DEFAULT_REQUEST_MAX_TOKENS, requestMaxTokens, loadCatalogFile, parseLimits, type CatalogDefaults, type LimitsInput } from "./model-catalog.ts";
6
+ export { restrictToPlatformTools, catalogViolation } from "./catalog-gate.ts";
7
+ export { harnessEventsFromSessionEvent, harnessEventFromStreamFrame, cmaMessageEvent, cmaEventType, type CmaMessageEventType } from "./events.ts";
8
+ export { approvalId, permissionRequest, refusalFor, type PermissionAnswer, type PermissionRequest } from "./approval.ts";
9
+ export { CONTINUE_NOTE, assertResumable, hasRecordedInput, continuationId } from "./recovery.ts";
10
+ export { stopForTurnEnd, agentErrorCode, AGENT_ERROR_CODES, type AgentErrorCode, type DshTurnEndReason } from "./stop.ts";
11
+ export { BASE_SYSTEM_PROMPT, composeSystemPrompt } from "./system-prompt.ts";
12
+ export { DSH_VERSION } from "./version.ts";
package/lib/index.js ADDED
@@ -0,0 +1,13 @@
1
+ // @beeos-ai/bma-dsh-adapter: the shared DSH adapter of BMA hosts.
2
+ export * from "./spi.js";
3
+ export { DshAdapter } from "./adapter.js";
4
+ export { mountKernel, COMPACTION_HEADROOM_TOKENS, COMPACTION_SUMMARY_MAX_TOKENS } from "./kernel.js";
5
+ export { ChatCompletionsAdapter, DEFAULT_IDLE_RETRY_BACKOFF_MS, DEFAULT_STREAM_IDLE_MS, MODEL_STREAM_IDLE, PROVIDER, RecentToolImages, TOOL_IMAGE_CALLS } from "./model.js";
6
+ export { ModelCatalog, DEFAULT_LIMITS, DEFAULT_REQUEST_MAX_TOKENS, requestMaxTokens, loadCatalogFile, parseLimits } from "./model-catalog.js";
7
+ export { restrictToPlatformTools, catalogViolation } from "./catalog-gate.js";
8
+ export { harnessEventsFromSessionEvent, harnessEventFromStreamFrame, cmaMessageEvent, cmaEventType } from "./events.js";
9
+ export { approvalId, permissionRequest, refusalFor } from "./approval.js";
10
+ export { CONTINUE_NOTE, assertResumable, hasRecordedInput, continuationId } from "./recovery.js";
11
+ export { stopForTurnEnd, agentErrorCode, AGENT_ERROR_CODES } from "./stop.js";
12
+ export { BASE_SYSTEM_PROMPT, composeSystemPrompt } from "./system-prompt.js";
13
+ export { DSH_VERSION } from "./version.js";
@@ -0,0 +1,18 @@
1
+ import { Context } from "@deepseek-ai/cordis";
2
+ export interface KernelOptions {
3
+ /** Directory of this process's dsh session logs (the harness transcript). */
4
+ home: string;
5
+ /** Concurrent read-only tool calls per step; omitted = dsh's own default (10 in 0.2.2-rc.1). */
6
+ maxParallelToolCalls?: number;
7
+ }
8
+ /**
9
+ * Compaction headroom below the window, beyond the output reservation (dsh
10
+ * default 65,536 leaves no room under a 128k window once 8k output is
11
+ * reserved, so compaction would start at ~54k). 8,192 keeps the trigger at
12
+ * 80% of the window for windows >= ~64k and still works down to ~11k. No
13
+ * industry basis; tuned against the dsh formula min(0.8W, W-O-headroom).
14
+ */
15
+ export declare const COMPACTION_HEADROOM_TOKENS = 8192;
16
+ /** Summary output cap (ADR 0009 preferredSummaryOutputTokens); the model adapter clamps it to the route's real output limit. */
17
+ export declare const COMPACTION_SUMMARY_MAX_TOKENS = 32768;
18
+ export declare function mountKernel(options: KernelOptions): Promise<Context>;
package/lib/kernel.js ADDED
@@ -0,0 +1,54 @@
1
+ // Mounts the dsh agent runtime from its public npm plugins (pinned
2
+ // 0.2.2-rc.1). No dsh CLI, no ACP, no dsh tool packages: the only tools that
3
+ // exist are the platform tools the adapter registers per agent scope.
4
+ // Upgrading dsh: the breaking points so far were all in this file (export
5
+ // shapes, plugin options, newly required plugins) — see README "升级 dsh".
6
+ import { join } from "node:path";
7
+ import { Context } from "@deepseek-ai/cordis";
8
+ import LlmRuntime from "@deepseek-ai/dsh-llm";
9
+ import SessionStore from "@deepseek-ai/dsh-session";
10
+ import SessionProjectionRegistry from "@deepseek-ai/dsh-session-projection";
11
+ import * as JsonlPersistence from "@deepseek-ai/dsh-session-persistence-jsonl";
12
+ import SystemPrompt from "@deepseek-ai/dsh-system-prompt";
13
+ import ToolRuntime from "@deepseek-ai/dsh-tools";
14
+ import * as NativeToolExecutor from "@deepseek-ai/dsh-tool-executor-native";
15
+ import AgentRegistry from "@deepseek-ai/dsh-agent";
16
+ import AgentLoop from "@deepseek-ai/dsh-agent-loop";
17
+ import TokenMeter from "@deepseek-ai/dsh-token-meter";
18
+ import ToolResultPruner from "@deepseek-ai/dsh-compaction-tool-result-pruner";
19
+ import CompactionBasic from "@deepseek-ai/dsh-compaction-basic";
20
+ import * as ImageOffload from "@deepseek-ai/dsh-compaction-image-offload";
21
+ import LocalAttachmentStore from "@deepseek-ai/dsh-attachment-local";
22
+ /**
23
+ * Compaction headroom below the window, beyond the output reservation (dsh
24
+ * default 65,536 leaves no room under a 128k window once 8k output is
25
+ * reserved, so compaction would start at ~54k). 8,192 keeps the trigger at
26
+ * 80% of the window for windows >= ~64k and still works down to ~11k. No
27
+ * industry basis; tuned against the dsh formula min(0.8W, W-O-headroom).
28
+ */
29
+ export const COMPACTION_HEADROOM_TOKENS = 8192;
30
+ /** Summary output cap (ADR 0009 preferredSummaryOutputTokens); the model adapter clamps it to the route's real output limit. */
31
+ export const COMPACTION_SUMMARY_MAX_TOKENS = 32_768;
32
+ export async function mountKernel(options) {
33
+ const ctx = new Context();
34
+ await ctx.plugin(LlmRuntime);
35
+ await ctx.plugin(SessionStore);
36
+ await ctx.plugin(SessionProjectionRegistry);
37
+ await ctx.plugin(JsonlPersistence, { root: join(options.home, "sessions") });
38
+ // No harness identity and no runtime context: the platform owns the prompt.
39
+ await ctx.plugin(SystemPrompt, { includeHarnessIdentity: false, includeRuntimeContext: false });
40
+ await ctx.plugin(ToolRuntime);
41
+ await ctx.plugin(NativeToolExecutor);
42
+ // Image inputs: validated, normalized and stored under <home>/attachments.
43
+ await ctx.plugin(LocalAttachmentStore, { dshHome: options.home });
44
+ await ctx.plugin(AgentRegistry);
45
+ // Long sessions (OMA's public composition): measure pressure, trim oversized
46
+ // tool results, then summarize the oldest history; image offload recovers
47
+ // from a route's image budget.
48
+ await ctx.plugin(TokenMeter);
49
+ await ctx.plugin(ToolResultPruner);
50
+ await ctx.plugin(CompactionBasic, { headroomTokens: COMPACTION_HEADROOM_TOKENS, maxTokens: COMPACTION_SUMMARY_MAX_TOKENS });
51
+ await ctx.plugin(ImageOffload, {});
52
+ await ctx.plugin(AgentLoop, { agents: [], ...(options.maxParallelToolCalls !== undefined ? { maxParallelToolCalls: options.maxParallelToolCalls } : {}) });
53
+ return ctx;
54
+ }
@@ -0,0 +1,51 @@
1
+ import type { ModelLimits } from "./spi.ts";
2
+ export interface LimitsInput {
3
+ contextWindow?: number;
4
+ maxOutputTokens?: number;
5
+ }
6
+ export interface CatalogDefaults {
7
+ contextWindow: number;
8
+ maxOutputTokens: number;
9
+ }
10
+ /**
11
+ * Conservative defaults for a model nobody described (no industry basis for
12
+ * the exact values): 128k is the window ADR 0009 falls back to; 8192 output
13
+ * tokens is accepted by every mainstream chat model, so the request is never
14
+ * refused for an oversized max_tokens. A longer reply is then cut and reported
15
+ * as output_limit_reached rather than failing obscurely.
16
+ */
17
+ export declare const DEFAULT_LIMITS: CatalogDefaults;
18
+ /**
19
+ * What an ordinary model request asks for as max_tokens, at most: the lower of
20
+ * this and the model's output ceiling (ModelLimits.maxOutputTokens, what the
21
+ * model CAN produce). Asking for the ceiling on every call is wrong for
22
+ * upstreams that prepay: OpenRouter holds input + max_tokens against the
23
+ * balance and refuses a request whose maximum it cannot cover (402), even
24
+ * though the reply would have been short. 32000 is Claude Code's default for a
25
+ * model it does not know (CLAUDE_CODE_MAX_OUTPUT_TOKENS) and leaves room for
26
+ * the reasoning that counts against max_tokens (OpenAI advises 25k+). A reply
27
+ * that still hits it ends the turn as output_limit_reached. The compaction
28
+ * summary asks for its own, larger amount (COMPACTION_SUMMARY_MAX_TOKENS) and
29
+ * is only bounded by the ceiling.
30
+ */
31
+ export declare const DEFAULT_REQUEST_MAX_TOKENS = 32000;
32
+ /** The max_tokens an ordinary request carries for a model with these limits. */
33
+ export declare function requestMaxTokens(limits: ModelLimits): number;
34
+ export declare function parseLimits(raw: unknown, where: string): LimitsInput;
35
+ /** Reads the operator catalog: {"<model id>": {"context_window": N, "max_output_tokens": N}, "*": {...}}. */
36
+ export declare function loadCatalogFile(path: string): Record<string, LimitsInput>;
37
+ export declare class ModelCatalog {
38
+ private readonly entries;
39
+ private readonly defaults;
40
+ private readonly onDefault;
41
+ private readonly declared;
42
+ private readonly reported;
43
+ constructor(options?: {
44
+ entries?: Record<string, LimitsInput>;
45
+ defaults?: CatalogDefaults;
46
+ onDefault?: (model: string, limits: ModelLimits) => void;
47
+ });
48
+ /** The platform's explicit statement about a model (latest wins). */
49
+ declare(model: string, limits: LimitsInput): void;
50
+ resolve(model: string): ModelLimits;
51
+ }
@@ -0,0 +1,98 @@
1
+ // Token limits per model: what max_tokens to ask for and how large the context
2
+ // window is. Resolution order, per field (ADR 0009: explicit > metadata >
3
+ // catalog > conservative default):
4
+ // 1. declared by the platform in turn.start metadata (model_context_window,
5
+ // model_max_output_tokens) — the platform knows the real model behind
6
+ // the routed name;
7
+ // 2. the operator catalog file (BRAIN_MODEL_CATALOG: exact model id, then "*");
8
+ // 3. the conservative defaults, recorded once per model so the operator can
9
+ // add a catalog entry.
10
+ // The completion cap is never above half the window (ADR 0009's bound for
11
+ // compaction output), so a tiny declared window cannot ask for an impossible cap.
12
+ import { readFileSync } from "node:fs";
13
+ /**
14
+ * Conservative defaults for a model nobody described (no industry basis for
15
+ * the exact values): 128k is the window ADR 0009 falls back to; 8192 output
16
+ * tokens is accepted by every mainstream chat model, so the request is never
17
+ * refused for an oversized max_tokens. A longer reply is then cut and reported
18
+ * as output_limit_reached rather than failing obscurely.
19
+ */
20
+ export const DEFAULT_LIMITS = { contextWindow: 128_000, maxOutputTokens: 8192 };
21
+ /**
22
+ * What an ordinary model request asks for as max_tokens, at most: the lower of
23
+ * this and the model's output ceiling (ModelLimits.maxOutputTokens, what the
24
+ * model CAN produce). Asking for the ceiling on every call is wrong for
25
+ * upstreams that prepay: OpenRouter holds input + max_tokens against the
26
+ * balance and refuses a request whose maximum it cannot cover (402), even
27
+ * though the reply would have been short. 32000 is Claude Code's default for a
28
+ * model it does not know (CLAUDE_CODE_MAX_OUTPUT_TOKENS) and leaves room for
29
+ * the reasoning that counts against max_tokens (OpenAI advises 25k+). A reply
30
+ * that still hits it ends the turn as output_limit_reached. The compaction
31
+ * summary asks for its own, larger amount (COMPACTION_SUMMARY_MAX_TOKENS) and
32
+ * is only bounded by the ceiling.
33
+ */
34
+ export const DEFAULT_REQUEST_MAX_TOKENS = 32_000;
35
+ /** The max_tokens an ordinary request carries for a model with these limits. */
36
+ export function requestMaxTokens(limits) {
37
+ return Math.min(limits.maxOutputTokens, DEFAULT_REQUEST_MAX_TOKENS);
38
+ }
39
+ function positive(value, where) {
40
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0)
41
+ throw new Error(`${where} must be a positive integer`);
42
+ return value;
43
+ }
44
+ export function parseLimits(raw, where) {
45
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
46
+ throw new Error(`${where} must be an object`);
47
+ const o = raw;
48
+ for (const k of Object.keys(o))
49
+ if (k !== "context_window" && k !== "max_output_tokens")
50
+ throw new Error(`${where}: unknown field ${JSON.stringify(k.slice(0, 40))}`);
51
+ return {
52
+ ...(o.context_window !== undefined ? { contextWindow: positive(o.context_window, `${where}.context_window`) } : {}),
53
+ ...(o.max_output_tokens !== undefined ? { maxOutputTokens: positive(o.max_output_tokens, `${where}.max_output_tokens`) } : {}),
54
+ };
55
+ }
56
+ /** Reads the operator catalog: {"<model id>": {"context_window": N, "max_output_tokens": N}, "*": {...}}. */
57
+ export function loadCatalogFile(path) {
58
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
59
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
60
+ throw new Error(`${path}: expected a JSON object keyed by model id`);
61
+ return Object.fromEntries(Object.entries(parsed).map(([model, v]) => [model, parseLimits(v, `${path}: ${JSON.stringify(model)}`)]));
62
+ }
63
+ export class ModelCatalog {
64
+ entries;
65
+ defaults;
66
+ onDefault;
67
+ declared = new Map();
68
+ reported = new Set();
69
+ constructor(options = {}) {
70
+ this.entries = new Map(Object.entries(options.entries ?? {}));
71
+ this.defaults = options.defaults ?? DEFAULT_LIMITS;
72
+ this.onDefault = options.onDefault ?? (() => { });
73
+ }
74
+ /** The platform's explicit statement about a model (latest wins). */
75
+ declare(model, limits) {
76
+ this.declared.set(model, limits);
77
+ }
78
+ resolve(model) {
79
+ const declared = this.declared.get(model);
80
+ const entry = this.entries.get(model) ?? this.entries.get("*");
81
+ const pick = (field) => {
82
+ if (declared?.[field] !== undefined)
83
+ return { value: declared[field], source: "declared" };
84
+ if (entry?.[field] !== undefined)
85
+ return { value: entry[field], source: "catalog" };
86
+ return { value: this.defaults[field], source: "default" };
87
+ };
88
+ const window = pick("contextWindow");
89
+ const output = pick("maxOutputTokens");
90
+ const source = window.source === "default" || output.source === "default" ? "default" : window.source === "declared" && output.source === "declared" ? "declared" : "catalog";
91
+ const limits = { contextWindow: window.value, maxOutputTokens: Math.min(output.value, Math.floor(window.value / 2)), source };
92
+ if (source === "default" && !this.reported.has(model)) {
93
+ this.reported.add(model);
94
+ this.onDefault(model, limits);
95
+ }
96
+ return limits;
97
+ }
98
+ }
package/lib/model.d.ts ADDED
@@ -0,0 +1,62 @@
1
+ import { LlmAdapter, type GenerateOptions, type ImageBlock, type LlmResolvedModelInfo, type StreamChunk } from "@deepseek-ai/dsh-llm";
2
+ import type { ModelPort } from "./spi.ts";
3
+ export declare const PROVIDER = "bma";
4
+ /** Error code of a model stream that sent no data for the idle limit (typed stop model_stream_idle). */
5
+ export declare const MODEL_STREAM_IDLE = "MODEL_STREAM_IDLE";
6
+ /** One image as the request carries it. */
7
+ export interface RequestImage {
8
+ mediaType: string;
9
+ /** Canonical base64. */
10
+ data: string;
11
+ }
12
+ export interface ModelAdapterOptions {
13
+ /** Abort a model request that has received no bytes for this long (ms); 0 disables. */
14
+ streamIdleMs: number;
15
+ /** Encodes one stored image as a request version for this route. */
16
+ readImage: (block: ImageBlock, signal?: AbortSignal) => Promise<RequestImage>;
17
+ /** Pause before the one idle retry, uniform in [min, max] ms; default DEFAULT_IDLE_RETRY_BACKOFF_MS. */
18
+ idleRetryBackoffMs?: readonly [number, number];
19
+ /** The images of a tool result the model still sees (RecentToolImages), by session and call. */
20
+ toolImages?: (sessionId: string, callId: string) => readonly RequestImage[] | undefined;
21
+ }
22
+ /**
23
+ * Tool result images (computer_observe screenshots) are kept in memory for the
24
+ * most recent TOOL_IMAGE_CALLS calls of a session and sent with those results
25
+ * only; older ones, and all of them after a restart, are left out (the result
26
+ * text stays). Basis: Anthropic's computer-use reference loop keeps only the N
27
+ * most recent screenshots in the request (only_n_most_recent_images, default
28
+ * 3) — screenshots are large and only the latest describe the screen.
29
+ */
30
+ export declare const TOOL_IMAGE_CALLS = 3;
31
+ export declare class RecentToolImages {
32
+ private readonly bySession;
33
+ remember(sessionId: string, callId: string, images: readonly {
34
+ mediaType: string;
35
+ data: string;
36
+ }[]): void;
37
+ get(sessionId: string, callId: string): readonly RequestImage[] | undefined;
38
+ forget(sessionId: string): void;
39
+ }
40
+ /**
41
+ * Idle before any content delta (no text / reasoning / tool-call delta yet) is retried
42
+ * once on a fresh request after this pause. Basis: the official Anthropic and OpenAI SDKs
43
+ * retry connection errors and timeouts automatically only while no response content has
44
+ * been received (max_retries=2 by default, exponential backoff 0.5s..8s with jitter);
45
+ * we use 1 retry and 1-2s (Lead ruling). Once any content arrived nothing is retried.
46
+ */
47
+ export declare const DEFAULT_IDLE_RETRY_BACKOFF_MS: readonly [number, number];
48
+ /**
49
+ * Default stream idle limit. Same value as the Beework Desktop brain's model
50
+ * stream guard (behaviour description only); no industry basis. Any received
51
+ * bytes count, SSE keep-alive comments included.
52
+ */
53
+ export declare const DEFAULT_STREAM_IDLE_MS = 90000;
54
+ export declare class ChatCompletionsAdapter extends LlmAdapter {
55
+ private readonly port;
56
+ private readonly options;
57
+ constructor(port: ModelPort, options: ModelAdapterOptions);
58
+ /** Window and output cap come from the host's model catalog, never from constants here. */
59
+ resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo>;
60
+ stream(request: GenerateOptions): AsyncIterable<StreamChunk>;
61
+ private run;
62
+ }