@beeos-ai/bma-dsh-adapter 0.0.0-stage → 0.1.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 +48 -0
  6. package/lib/adapter.js +189 -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 +5 -0
  12. package/lib/catalog-gate.js +26 -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 +130 -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 +35 -0
  27. package/lib/model-catalog.js +80 -0
  28. package/lib/model.d.ts +32 -0
  29. package/lib/model.js +285 -0
  30. package/lib/recovery.d.ts +8 -0
  31. package/lib/recovery.js +19 -0
  32. package/lib/spi.d.ts +169 -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,26 @@
1
+ export function restrictToPlatformTools(scope, sessionId, tools) {
2
+ scope.tools.restrict({ allow: [] });
3
+ for (const tool of tools) {
4
+ scope.tools.register({
5
+ name: tool.name,
6
+ description: tool.description,
7
+ parameters: tool.parameters,
8
+ output: { schema: { type: "string" }, render: (_args, value) => [{ type: "text", text: String(value) }] },
9
+ isConcurrencySafe: () => tool.readOnly,
10
+ execute: async (args, exec) => {
11
+ const result = await tool.invoke({ sessionId, callId: exec.callId, input: (args ?? {}), signal: exec.signal });
12
+ if (result.isError)
13
+ throw new Error(result.text);
14
+ return result.text;
15
+ },
16
+ });
17
+ }
18
+ }
19
+ /** Why a session must be refused, or undefined when the catalog is exactly the expected tools. */
20
+ export function catalogViolation(harnessId, expected, actual) {
21
+ const want = [...expected].sort();
22
+ const got = [...actual].sort();
23
+ if (JSON.stringify(want) === JSON.stringify(got))
24
+ return undefined;
25
+ return `harness ${harnessId} exposes tools [${got.join(",")}], not exactly the platform tools: refused (fail-closed)`;
26
+ }
@@ -0,0 +1,198 @@
1
+ {
2
+ "success": {
3
+ "events": [
4
+ {
5
+ "event_id": "evt_1",
6
+ "type": "session.status_running"
7
+ },
8
+ {
9
+ "event_id": "evt_2",
10
+ "type": "agent.tool_use",
11
+ "name": "bash",
12
+ "input": {
13
+ "command": "echo hi"
14
+ },
15
+ "evaluated_permission": {
16
+ "type": "allow"
17
+ }
18
+ },
19
+ {
20
+ "event_id": "evt_3",
21
+ "type": "agent.tool_result",
22
+ "tool_use_id": "evt_2",
23
+ "is_error": false,
24
+ "content": [
25
+ {
26
+ "type": "text",
27
+ "text": "hi\n"
28
+ }
29
+ ]
30
+ },
31
+ {
32
+ "event_id": "evt_4",
33
+ "type": "agent.message",
34
+ "content": [
35
+ {
36
+ "type": "text",
37
+ "text": "done"
38
+ }
39
+ ]
40
+ },
41
+ {
42
+ "event_id": "evt_5",
43
+ "type": "session.status_idle",
44
+ "stop_reason": {
45
+ "type": "end_turn"
46
+ },
47
+ "turn_outcome": "completed"
48
+ }
49
+ ],
50
+ "previews": {
51
+ "evt_4": "done"
52
+ }
53
+ },
54
+ "failed": {
55
+ "events": [
56
+ {
57
+ "event_id": "evt_1",
58
+ "type": "session.status_running"
59
+ },
60
+ {
61
+ "event_id": "evt_2",
62
+ "type": "agent.tool_use",
63
+ "name": "bash",
64
+ "input": {
65
+ "command": "echo oops >&2; exit 3"
66
+ },
67
+ "evaluated_permission": {
68
+ "type": "allow"
69
+ }
70
+ },
71
+ {
72
+ "event_id": "evt_3",
73
+ "type": "agent.tool_result",
74
+ "tool_use_id": "evt_2",
75
+ "is_error": true,
76
+ "content": [
77
+ {
78
+ "type": "text",
79
+ "text": "oops\n"
80
+ }
81
+ ]
82
+ },
83
+ {
84
+ "event_id": "evt_4",
85
+ "type": "agent.message",
86
+ "content": [
87
+ {
88
+ "type": "text",
89
+ "text": "done"
90
+ }
91
+ ]
92
+ },
93
+ {
94
+ "event_id": "evt_5",
95
+ "type": "session.status_idle",
96
+ "stop_reason": {
97
+ "type": "end_turn"
98
+ },
99
+ "turn_outcome": "completed"
100
+ }
101
+ ],
102
+ "previews": {
103
+ "evt_4": "done"
104
+ }
105
+ },
106
+ "denied": {
107
+ "events": [
108
+ {
109
+ "event_id": "evt_1",
110
+ "type": "session.status_running"
111
+ },
112
+ {
113
+ "event_id": "evt_2",
114
+ "type": "agent.tool_use",
115
+ "name": "bash",
116
+ "input": {
117
+ "command": "echo never"
118
+ },
119
+ "evaluated_permission": {
120
+ "type": "deny"
121
+ }
122
+ },
123
+ {
124
+ "event_id": "evt_3",
125
+ "type": "agent.tool_result",
126
+ "tool_use_id": "evt_2",
127
+ "is_error": true,
128
+ "content": [
129
+ {
130
+ "type": "text",
131
+ "text": "The agent's permission policy denies bash."
132
+ }
133
+ ]
134
+ },
135
+ {
136
+ "event_id": "evt_4",
137
+ "type": "agent.message",
138
+ "content": [
139
+ {
140
+ "type": "text",
141
+ "text": "done"
142
+ }
143
+ ]
144
+ },
145
+ {
146
+ "event_id": "evt_5",
147
+ "type": "session.status_idle",
148
+ "stop_reason": {
149
+ "type": "end_turn"
150
+ },
151
+ "turn_outcome": "completed"
152
+ }
153
+ ],
154
+ "previews": {
155
+ "evt_4": "done"
156
+ }
157
+ },
158
+ "text": {
159
+ "events": [
160
+ {
161
+ "event_id": "evt_1",
162
+ "type": "session.status_running"
163
+ },
164
+ {
165
+ "event_id": "evt_2",
166
+ "type": "agent.thinking",
167
+ "content": [
168
+ {
169
+ "type": "text",
170
+ "text": "thinking it over"
171
+ }
172
+ ]
173
+ },
174
+ {
175
+ "event_id": "evt_3",
176
+ "type": "agent.message",
177
+ "content": [
178
+ {
179
+ "type": "text",
180
+ "text": "echo: hello"
181
+ }
182
+ ]
183
+ },
184
+ {
185
+ "event_id": "evt_4",
186
+ "type": "session.status_idle",
187
+ "stop_reason": {
188
+ "type": "end_turn"
189
+ },
190
+ "turn_outcome": "completed"
191
+ }
192
+ ],
193
+ "previews": {
194
+ "evt_2": "thinking it over",
195
+ "evt_3": "echo: hello"
196
+ }
197
+ }
198
+ }
@@ -0,0 +1,26 @@
1
+ {
2
+ "preview": {
3
+ "message": "hello there friend",
4
+ "thinking": "think hard"
5
+ },
6
+ "durable": [
7
+ {
8
+ "type": "agent.thinking",
9
+ "content": [
10
+ {
11
+ "type": "text",
12
+ "text": "think hard"
13
+ }
14
+ ]
15
+ },
16
+ {
17
+ "type": "agent.message",
18
+ "content": [
19
+ {
20
+ "type": "text",
21
+ "text": "hello there friend"
22
+ }
23
+ ]
24
+ }
25
+ ]
26
+ }
@@ -0,0 +1,26 @@
1
+ {
2
+ "calls": [
3
+ {
4
+ "sessionId": "sesn_tool",
5
+ "callId": "call_7",
6
+ "input": {
7
+ "command": "ls"
8
+ }
9
+ }
10
+ ],
11
+ "preview": {
12
+ "message": "done: listed",
13
+ "thinking": ""
14
+ },
15
+ "durable": [
16
+ {
17
+ "type": "agent.message",
18
+ "content": [
19
+ {
20
+ "type": "text",
21
+ "text": "done: listed"
22
+ }
23
+ ]
24
+ }
25
+ ]
26
+ }
@@ -0,0 +1,32 @@
1
+ import { type TestContext } from "node:test";
2
+ import { type HarnessAdapter, type PlatformTool } from "../spi.ts";
3
+ import { type ScriptedModel, type Script } from "../testing/scripted-model.ts";
4
+ import { type ShellFactory } from "./shell.ts";
5
+ export { CANCEL_ACK_BUDGET_MS, type Shell, type ShellEvent, type ShellFactory, type ShellInteraction, type ShellPermission, type ShellTurnSpec } from "./shell.ts";
6
+ export interface ConformanceOptions {
7
+ script: Script;
8
+ /** Harness state directory; pass the same one to a second mount to test resume. */
9
+ home?: string;
10
+ /** Model stream idle limit (ms) the adapter must be mounted with. */
11
+ streamIdleMs?: number;
12
+ /** Platform tools the adapter registers; default: the six fixture tools. */
13
+ tools?: PlatformTool[];
14
+ }
15
+ export interface ConformanceHarness {
16
+ adapter: HarnessAdapter;
17
+ model: ScriptedModel;
18
+ home: string;
19
+ }
20
+ /** Mounts the adapter, points its ModelPort at the scripted model, registers the tools, and cleans up with t.after. */
21
+ export type ConformanceFactory = (t: TestContext, options: ConformanceOptions & {
22
+ home: string;
23
+ }) => Promise<ConformanceHarness>;
24
+ export interface ConformanceSuiteOptions {
25
+ /**
26
+ * The host shell's wiring (a running shell, a stand-in platform, a scripted model). Required of every
27
+ * shell that talks to the platform (brain-host, bma-dsh-acp, ...); the kernel-only run of the package's own
28
+ * test omits it and skips the shell-level cases.
29
+ */
30
+ shell?: ShellFactory;
31
+ }
32
+ export declare function registerConformance(name: string, factory: ConformanceFactory, options?: ConformanceSuiteOptions): void;
@@ -0,0 +1,130 @@
1
+ // Conformance suite for any host of the shared adapter (brain-host today,
2
+ // bma-dsh-acp and others next). A host's test file calls registerConformance
3
+ // with a factory that mounts ITS adapter wiring against a scripted
4
+ // OpenAI-compatible model; the suite then pins the behaviour every host must
5
+ // share: the platform-tools-only catalog, the CMA event golden, resume and
6
+ // input idempotency, cancel, and the typed stop reasons.
7
+ //
8
+ // Golden files live in ./golden; UPDATE_GOLDEN=1 rewrites them (review the diff).
9
+ import { test } from "node:test";
10
+ import assert from "node:assert/strict";
11
+ import { readFileSync, writeFileSync } from "node:fs";
12
+ import { cmaMessageEvent } from "../events.js";
13
+ import { TurnStopError } from "../spi.js";
14
+ import { createTestTempDir, removeAfter } from "../testing/tmp.js";
15
+ import { fixtureTools, FIXTURE_TOOL_NAMES } from "../testing/tools.js";
16
+ import { last, textOf, toolNames } from "../testing/scripted-model.js";
17
+ import { composeSystemPrompt, BASE_SYSTEM_PROMPT } from "../system-prompt.js";
18
+ import { registerShellConformance } from "./shell.js";
19
+ export { CANCEL_ACK_BUDGET_MS } from "./shell.js";
20
+ const init = (sessionId) => ({ sessionId, model: "m-1", systemPrompt: "You are a BMA agent.", cwd: "/workspace" });
21
+ async function run(adapter, sid, id, text, signal = new AbortController().signal) {
22
+ const events = [];
23
+ for await (const e of adapter.submitInput(sid, { id, text }, signal))
24
+ events.push(e);
25
+ return events;
26
+ }
27
+ function golden(name, actual) {
28
+ const file = new URL(`./golden/${name}.json`, import.meta.url);
29
+ const text = `${JSON.stringify(actual, null, 2)}\n`;
30
+ if (process.env.UPDATE_GOLDEN === "1")
31
+ writeFileSync(file, text);
32
+ assert.equal(text, readFileSync(file, "utf8"), `golden ${name}.json differs (UPDATE_GOLDEN=1 rewrites it)`);
33
+ }
34
+ /** Deltas collapse to their joined preview text; durable events become the CMA events a host writes. */
35
+ function cmaView(events) {
36
+ const preview = { message: "", thinking: "" };
37
+ const durable = [];
38
+ for (const e of events) {
39
+ if (e.type === "delta")
40
+ preview[e.kind] += e.text;
41
+ else
42
+ durable.push(cmaMessageEvent(e));
43
+ }
44
+ return { preview, durable };
45
+ }
46
+ export function registerConformance(name, factory, options = {}) {
47
+ if (options.shell)
48
+ registerShellConformance(name, options.shell);
49
+ // The default home is removed after the factory registered its teardown (after hooks run in registration order).
50
+ const mount = async (t, o) => {
51
+ const home = o.home ?? createTestTempDir("bma-conf-");
52
+ try {
53
+ return await factory(t, { ...o, home });
54
+ }
55
+ finally {
56
+ if (!o.home)
57
+ removeAfter(t, home);
58
+ }
59
+ };
60
+ test(`[conformance:${name}] catalog: exactly the platform tools, in the session and in the model request`, async (t) => {
61
+ const { adapter, model } = await mount(t, { script: () => ({ text: "ok" }) });
62
+ await adapter.createSession(init("sesn_cat"));
63
+ assert.deepEqual([...adapter.toolCatalog("sesn_cat")].sort(), [...FIXTURE_TOOL_NAMES].sort());
64
+ await run(adapter, "sesn_cat", "in_1", "hi");
65
+ assert.deepEqual(toolNames(model.requests[0]), [...FIXTURE_TOOL_NAMES].sort());
66
+ });
67
+ test(`[conformance:${name}] system prompt: base + agent.system, no harness identity`, async (t) => {
68
+ const { adapter, model } = await mount(t, { script: () => ({ text: "ok" }) });
69
+ for (const [sid, system] of [["sesn_sp1", undefined], ["sesn_sp2", "Answer in French."]]) {
70
+ await adapter.createSession({ sessionId: sid, model: "m-1", systemPrompt: composeSystemPrompt(system), cwd: "/workspace" });
71
+ await run(adapter, sid, "in_1", "hi");
72
+ }
73
+ const systems = model.requests.map((r) => r.body.messages.filter((m) => m.role === "system").map(textOf));
74
+ assert.deepEqual(systems, [[BASE_SYSTEM_PROMPT], [`${BASE_SYSTEM_PROMPT}\n\nAnswer in French.`]], "exactly our prompt: nothing added by the kernel");
75
+ });
76
+ test(`[conformance:${name}] events golden: reasoning + text turn`, async (t) => {
77
+ const { adapter } = await mount(t, { script: () => ({ reasoning: "think hard", text: "hello there friend" }) });
78
+ await adapter.createSession(init("sesn_ev"));
79
+ golden("turn-reasoning-text", cmaView(await run(adapter, "sesn_ev", "in_1", "hi")));
80
+ });
81
+ test(`[conformance:${name}] events golden: a tool call goes to the platform tool with the harness call id`, async (t) => {
82
+ const calls = [];
83
+ const tools = fixtureTools(async (c) => { calls.push({ sessionId: c.sessionId, callId: c.callId, input: c.input }); return { text: "listed", isError: false }; });
84
+ const { adapter } = await mount(t, { tools, script: (req) => (last(req).role === "tool" ? { text: "done: listed" } : { toolCalls: [{ id: "call_7", name: "bash", args: { command: "ls" } }] }) });
85
+ await adapter.createSession(init("sesn_tool"));
86
+ const events = await run(adapter, "sesn_tool", "in_1", "list");
87
+ golden("turn-tool-call", { calls, ...cmaView(events) });
88
+ });
89
+ test(`[conformance:${name}] resume: a new process keeps the conversation; re-delivering a recorded input does not duplicate it; unknown session is SessionNotFound`, async (t) => {
90
+ const home = createTestTempDir("bma-conf-resume-");
91
+ const first = await mount(t, { home, script: () => ({ text: "first answer" }) });
92
+ await first.adapter.createSession(init("sesn_res"));
93
+ await run(first.adapter, "sesn_res", "in_1", "remember 42");
94
+ await first.adapter.checkpoint("sesn_res");
95
+ await first.adapter.close("sesn_res");
96
+ await first.adapter.dispose();
97
+ const second = await mount(t, { home, script: () => ({ text: "second answer" }) });
98
+ removeAfter(t, home);
99
+ await second.adapter.resumeSession(init("sesn_res"));
100
+ await run(second.adapter, "sesn_res", "in_1", "remember 42");
101
+ const msgs = second.model.requests[0].body.messages;
102
+ assert.equal(msgs.filter((m) => m.role === "user" && textOf(m) === "remember 42").length, 1);
103
+ assert.ok(msgs.some((m) => m.role === "assistant" && textOf(m) === "first answer"));
104
+ await assert.rejects(second.adapter.resumeSession(init("sesn_never")), { name: "SessionNotFoundError" });
105
+ });
106
+ test(`[conformance:${name}] cancel: aborting the signal ends the iteration without throwing`, async (t) => {
107
+ const { adapter } = await mount(t, { script: () => ({ text: "partial", hang: true }) });
108
+ await adapter.createSession(init("sesn_can"));
109
+ const ctl = new AbortController();
110
+ setTimeout(() => ctl.abort(), 300);
111
+ const started = Date.now();
112
+ await run(adapter, "sesn_can", "in_1", "x", ctl.signal);
113
+ assert.ok(Date.now() - started < 5_000);
114
+ });
115
+ test(`[conformance:${name}] stop reasons: output limit, context overflow and stream idle are typed; a model failure is generic`, async (t) => {
116
+ const typed = (code) => (err) => err instanceof TurnStopError && err.code === code && err.message.startsWith(`${code}: `);
117
+ const cut = await mount(t, { script: () => ({ text: "cut off", finishReason: "length" }) });
118
+ await cut.adapter.createSession(init("sesn_s1"));
119
+ await assert.rejects(run(cut.adapter, "sesn_s1", "in_1", "x"), typed("output_limit_reached"));
120
+ const overflow = await mount(t, { script: (req) => (textOf(last(req)).includes("compaction engine") ? { text: "- (none)" } : { status: 400, errorText: "This model's maximum context length is 128000 tokens." }) });
121
+ await overflow.adapter.createSession(init("sesn_s2"));
122
+ await assert.rejects(run(overflow.adapter, "sesn_s2", "in_1", "x"), typed("context_too_large"));
123
+ const idle = await mount(t, { streamIdleMs: 300, script: () => ({ text: "partial", hang: true }) });
124
+ await idle.adapter.createSession(init("sesn_s3"));
125
+ await assert.rejects(run(idle.adapter, "sesn_s3", "in_1", "x"), typed("model_stream_idle"));
126
+ const failed = await mount(t, { script: () => ({ status: 401 }) });
127
+ await failed.adapter.createSession(init("sesn_s4"));
128
+ await assert.rejects(run(failed.adapter, "sesn_s4", "in_1", "x"), (err) => !(err instanceof TurnStopError));
129
+ });
130
+ }
@@ -0,0 +1,64 @@
1
+ import { type TestContext } from "node:test";
2
+ import type { ToolName } from "../spi.ts";
3
+ import { type ModelRequest, type Reply, type ScriptedModel } from "../testing/scripted-model.ts";
4
+ /** 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). */
5
+ export declare const CANCEL_ACK_BUDGET_MS = 10000;
6
+ export type ShellPermission = "allow" | "ask" | "deny";
7
+ export interface ShellTurnSpec {
8
+ sessionId: string;
9
+ text: string;
10
+ /** Per-tool permission policy of the agent; default allow. */
11
+ policy?: Partial<Record<ToolName, ShellPermission>>;
12
+ }
13
+ /** A durable event the platform accepted from the shell. */
14
+ export interface ShellEvent {
15
+ eventId: string;
16
+ turnId: string;
17
+ event: Record<string, unknown>;
18
+ }
19
+ export interface ShellInteraction {
20
+ id: string;
21
+ toolName: string;
22
+ state: "open" | "answered" | "canceled";
23
+ /** How often the shell asked the platform for it (a platform answers a repeat of an answered one from storage). */
24
+ requests: number;
25
+ }
26
+ /**
27
+ * A running shell wired to a stand-in platform, a scripted model and a
28
+ * stand-in tool backend that really runs bash in a temp directory.
29
+ */
30
+ export interface Shell {
31
+ model: ScriptedModel;
32
+ startTurn(spec: ShellTurnSpec): Promise<{
33
+ turnId: string;
34
+ }>;
35
+ /** turn.cancel. */
36
+ cancelTurn(sessionId: string, turnId: string): Promise<void>;
37
+ /** Durable events of the session, in platform order. */
38
+ events(sessionId: string): ShellEvent[];
39
+ /** Streaming previews: event id and text. */
40
+ deltas(): {
41
+ eventId: string;
42
+ text: string;
43
+ }[];
44
+ interactions(sessionId: string): ShellInteraction[];
45
+ /** The user's answer; stored by the platform and delivered when the shell is reachable. */
46
+ answer(interactionId: string, outcome: "allow" | "deny"): Promise<void>;
47
+ /** Stops the shell process (SIGKILL: crash; SIGTERM: rollout), keeping its state directory. */
48
+ stop(signal: "SIGKILL" | "SIGTERM"): Promise<void>;
49
+ /** Starts a new shell process on the same state directory. */
50
+ start(): Promise<void>;
51
+ /** The platform sends the same turn.start again after the shell came back (ADR-0013). */
52
+ redeliver(sessionId: string, turnId: string): Promise<void>;
53
+ /** Tool calls the backend executed, in order. */
54
+ executedTools(): {
55
+ tool: string;
56
+ input: Record<string, unknown>;
57
+ }[];
58
+ }
59
+ export type ShellFactory = (t: TestContext, options: {
60
+ script: (req: ModelRequest) => Reply;
61
+ streamIdleMs?: number;
62
+ home: string;
63
+ }) => Promise<Shell>;
64
+ export declare function registerShellConformance(name: string, factory: ShellFactory): void;