@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/stop.js ADDED
@@ -0,0 +1,53 @@
1
+ // Maps how a dsh turn ended (turn/end reason) to the platform-visible stop:
2
+ // undefined for a normal end, a typed TurnStopError for the reasons the
3
+ // platform can explain to the user, a generic Error otherwise.
4
+ //
5
+ // dsh reason platform
6
+ // completed end_turn (no error)
7
+ // max-tokens output_limit_reached
8
+ // error, code CONTEXT_WINDOW_EXCEEDED context_too_large (compaction could not make it fit)
9
+ // error, code MODEL_STREAM_IDLE model_stream_idle
10
+ // anything else not completed agent_error: "dsh turn ended: <kind>[: <message>]"
11
+ //
12
+ // The codes are the executor contract's stop code table (contracts/bma/schemas/agent.json,
13
+ // $defs.AgentErrorCode); stop-contract.test.ts fails when the two drift.
14
+ import { CONTEXT_WINDOW_EXCEEDED_CODE } from "@deepseek-ai/dsh-llm";
15
+ import { TurnStopError } from "./spi.js";
16
+ import { MODEL_STREAM_IDLE } from "./model.js";
17
+ export function stopForTurnEnd(reason, context = {}) {
18
+ switch (reason.kind) {
19
+ case "completed":
20
+ return undefined;
21
+ case "max-tokens":
22
+ return new TurnStopError("output_limit_reached", `the model reply was cut at its output limit${context.maxOutputTokens ? ` (${context.maxOutputTokens} tokens)` : ""}; ask for a shorter answer, or to continue`);
23
+ case "error": {
24
+ const code = reason.error?.code;
25
+ if (code === CONTEXT_WINDOW_EXCEEDED_CODE)
26
+ return new TurnStopError("context_too_large", "the conversation no longer fits the model context window even after compaction");
27
+ if (code === MODEL_STREAM_IDLE)
28
+ return new TurnStopError("model_stream_idle", `the model stream sent no data${context.streamIdleMs ? ` for ${context.streamIdleMs / 1000}s` : ""}`);
29
+ return new Error(`dsh turn ended: error${reason.error ? `: ${reason.error.message}` : ""}`);
30
+ }
31
+ default:
32
+ return new Error(`dsh turn ended: ${reason.kind}${reason.error ? `: ${reason.error.message}` : ""}`);
33
+ }
34
+ }
35
+ /** The contract's stop code table (AgentErrorCode), in contract order. */
36
+ export const AGENT_ERROR_CODES = [
37
+ "output_limit_reached",
38
+ "context_too_large",
39
+ "model_stream_idle",
40
+ "agent_error",
41
+ "agent_unavailable",
42
+ "agent_auth_required",
43
+ "agent_protocol_error",
44
+ ];
45
+ /**
46
+ * The contract code a failed turn reports: a typed stop is its own code, any
47
+ * other failure is agent_error. A host puts it first in the session.error
48
+ * message ("<code>: <detail>", which TurnStopError already does) or, with
49
+ * structured_errors, in error.type.
50
+ */
51
+ export function agentErrorCode(err) {
52
+ return err instanceof TurnStopError ? err.code : "agent_error";
53
+ }
@@ -0,0 +1,3 @@
1
+ export declare const BASE_SYSTEM_PROMPT: string;
2
+ /** Base prompt, then the agent's `system` after one blank line; no `system` (or an empty one) is the base prompt alone. */
3
+ export declare function composeSystemPrompt(agentSystem?: string): string;
@@ -0,0 +1,13 @@
1
+ // The platform system prompt of a server-side brain: BMA's base prompt plus
2
+ // the agent's own `system` (CMA agent config). Every host shell assembles it
3
+ // here, never itself, so a tenant-defined agent behaves the same in each one.
4
+ // The kernel adds nothing of its own (no harness identity, no runtime context).
5
+ export const BASE_SYSTEM_PROMPT = [
6
+ "You are an agent running on BMA (BeeOS Managed Agents).",
7
+ "Your tools run on the session's machine; use absolute paths. Files meant for the user go under /mnt/session/outputs.",
8
+ "Be concise. When a task is done, say what you did.",
9
+ ].join("\n");
10
+ /** Base prompt, then the agent's `system` after one blank line; no `system` (or an empty one) is the base prompt alone. */
11
+ export function composeSystemPrompt(agentSystem) {
12
+ return agentSystem ? `${BASE_SYSTEM_PROMPT}\n\n${agentSystem}` : BASE_SYSTEM_PROMPT;
13
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./scripted-model.ts";
2
+ export * from "./tools.ts";
3
+ export * from "./tmp.ts";
@@ -0,0 +1,3 @@
1
+ export * from "./scripted-model.js";
2
+ export * from "./tools.js";
3
+ export * from "./tmp.js";
@@ -0,0 +1,78 @@
1
+ export interface ModelRequest {
2
+ token: string;
3
+ body: {
4
+ model: string;
5
+ max_tokens?: number;
6
+ messages: {
7
+ role: string;
8
+ content: string | null | {
9
+ type: string;
10
+ text?: string;
11
+ image_url?: {
12
+ url: string;
13
+ };
14
+ }[];
15
+ tool_calls?: {
16
+ id: string;
17
+ function: {
18
+ name: string;
19
+ arguments: string;
20
+ };
21
+ }[];
22
+ tool_call_id?: string;
23
+ }[];
24
+ tools?: {
25
+ function: {
26
+ name: string;
27
+ };
28
+ }[];
29
+ };
30
+ }
31
+ export interface Reply {
32
+ reasoning?: string;
33
+ text?: string;
34
+ toolCalls?: {
35
+ id: string;
36
+ name: string;
37
+ args: Record<string, unknown>;
38
+ }[];
39
+ /** Delay before the first chunk. */
40
+ delayMs?: number;
41
+ /** Never finish (until the client disconnects). */
42
+ hang?: boolean;
43
+ status?: number;
44
+ /** HTTP status plus this error text (default "scripted failure"). */
45
+ errorText?: string;
46
+ /** finish_reason of a non-tool reply (default "stop"); "length" simulates a max_tokens cut. */
47
+ finishReason?: string;
48
+ }
49
+ export type Script = (req: ModelRequest, index: number) => Reply;
50
+ export interface ScriptedModel {
51
+ baseUrl: string;
52
+ requests: ModelRequest[];
53
+ script: Script;
54
+ close(): Promise<void>;
55
+ }
56
+ /** Last message of the request (user text or tool result). */
57
+ export declare const last: (req: ModelRequest) => {
58
+ role: string;
59
+ content: string | null | {
60
+ type: string;
61
+ text?: string;
62
+ image_url?: {
63
+ url: string;
64
+ };
65
+ }[];
66
+ tool_calls?: {
67
+ id: string;
68
+ function: {
69
+ name: string;
70
+ arguments: string;
71
+ };
72
+ }[];
73
+ tool_call_id?: string;
74
+ };
75
+ /** Text of a message whose content may be a string or parts. */
76
+ export declare const textOf: (m: ModelRequest["body"]["messages"][number]) => string;
77
+ export declare const toolNames: (req: ModelRequest) => string[];
78
+ export declare function startScriptedModel(script: Script, listen?: string): Promise<ScriptedModel>;
@@ -0,0 +1,56 @@
1
+ // Scripted OpenAI-compatible model (POST /v1/chat/completions, SSE). The
2
+ // script sees each request (body + bearer token) and returns the reply
3
+ // steps; every request is recorded for assertions (tools, system prompt,
4
+ // attribution).
5
+ import http from "node:http";
6
+ /** Last message of the request (user text or tool result). */
7
+ export const last = (req) => req.body.messages.at(-1);
8
+ /** Text of a message whose content may be a string or parts. */
9
+ export const textOf = (m) => typeof m.content === "string" ? m.content : Array.isArray(m.content) ? m.content.map((p) => p.text ?? "").join("") : "";
10
+ export const toolNames = (req) => (req.body.tools ?? []).map((t) => t.function.name).sort();
11
+ export async function startScriptedModel(script, listen = "127.0.0.1") {
12
+ const requests = [];
13
+ const sockets = new Set();
14
+ const model = {
15
+ baseUrl: "",
16
+ requests,
17
+ script,
18
+ close: () => new Promise((resolve) => { for (const s of sockets)
19
+ s.destroy(); server.close(() => resolve()); }),
20
+ };
21
+ const server = http.createServer(async (req, res) => {
22
+ const chunks = [];
23
+ for await (const c of req)
24
+ chunks.push(c);
25
+ if (req.url !== "/v1/chat/completions") {
26
+ res.writeHead(404).end();
27
+ return;
28
+ }
29
+ const request = { token: (req.headers.authorization ?? "").replace(/^Bearer /, ""), body: JSON.parse(Buffer.concat(chunks).toString("utf8")) };
30
+ requests.push(request);
31
+ const reply = model.script(request, requests.length - 1);
32
+ if (reply.status) {
33
+ res.writeHead(reply.status).end(JSON.stringify({ error: { message: reply.errorText ?? "scripted failure" } }));
34
+ return;
35
+ }
36
+ res.writeHead(200, { "content-type": "text/event-stream" });
37
+ if (reply.delayMs)
38
+ await new Promise((r) => setTimeout(r, reply.delayMs));
39
+ const send = (delta, finish = null) => res.write(`data: ${JSON.stringify({ choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`);
40
+ if (reply.reasoning)
41
+ send({ reasoning_content: reply.reasoning });
42
+ if (reply.text)
43
+ for (const piece of reply.text.match(/.{1,8}/gs) ?? [])
44
+ send({ content: piece });
45
+ if (reply.hang)
46
+ return;
47
+ (reply.toolCalls ?? []).forEach((c, i) => send({ tool_calls: [{ index: i, id: c.id, type: "function", function: { name: c.name, arguments: JSON.stringify(c.args) } }] }));
48
+ send({}, reply.toolCalls?.length && !reply.finishReason ? "tool_calls" : (reply.finishReason ?? "stop"));
49
+ res.write(`data: ${JSON.stringify({ choices: [], usage: { prompt_tokens: 11, completion_tokens: 7, total_tokens: 18 } })}\n\n`);
50
+ res.end("data: [DONE]\n\n");
51
+ });
52
+ server.on("connection", (s) => { sockets.add(s); s.on("close", () => sockets.delete(s)); });
53
+ await new Promise((resolve) => server.listen(0, listen, resolve));
54
+ model.baseUrl = `http://127.0.0.1:${server.address().port}/v1`;
55
+ return model;
56
+ }
@@ -0,0 +1,24 @@
1
+ /** Name prefixes a test directory may carry; the clean script refuses any other. */
2
+ export declare const TEST_TMP_PREFIXES: readonly ["bma-conf-", "bma-shell-", "bma-acp-"];
3
+ export declare const ledgerPath: () => string;
4
+ type Prefix = (typeof TEST_TMP_PREFIXES)[number] | `${(typeof TEST_TMP_PREFIXES)[number]}${string}`;
5
+ /** Creates a temp dir under tmpdir() and records its exact path in the ledger. */
6
+ export declare function createTestTempDir(prefix: Prefix): string;
7
+ /**
8
+ * Removes exactly dir when the test or suite ends. node:test runs after hooks
9
+ * in registration order: call this AFTER whatever uses the dir has registered
10
+ * its own teardown (adapter dispose, process stop), or the dir goes first.
11
+ */
12
+ export declare function removeAfter(t: {
13
+ after(fn: () => void): void;
14
+ }, dir: string): void;
15
+ /** createTestTempDir + removeAfter, for a dir nothing outlives. */
16
+ export declare function testTempDir(t: {
17
+ after(fn: () => void): void;
18
+ }, prefix: Prefix): string;
19
+ /** Removes every path recorded in the ledger, then the ledger. Returns the removed and refused paths. */
20
+ export declare function cleanRecordedTempDirs(): {
21
+ removed: string[];
22
+ refused: string[];
23
+ };
24
+ export {};
@@ -0,0 +1,55 @@
1
+ // Temp directories of the conformance suites and shells. Every directory is
2
+ // recorded by its exact path in a ledger and removed when its test ends; what a
3
+ // killed run leaves behind is removed by scripts/clean-test-tmp.ts from the
4
+ // ledger, never by a pattern.
5
+ import { appendFileSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { basename, dirname, isAbsolute, join } from "node:path";
8
+ /** Name prefixes a test directory may carry; the clean script refuses any other. */
9
+ export const TEST_TMP_PREFIXES = ["bma-conf-", "bma-shell-", "bma-acp-"];
10
+ export const ledgerPath = () => join(tmpdir(), "bma-test-tmp.ledger");
11
+ /** Creates a temp dir under tmpdir() and records its exact path in the ledger. */
12
+ export function createTestTempDir(prefix) {
13
+ const dir = mkdtempSync(join(tmpdir(), prefix));
14
+ appendFileSync(ledgerPath(), `${dir}\n`);
15
+ return dir;
16
+ }
17
+ /**
18
+ * Removes exactly dir when the test or suite ends. node:test runs after hooks
19
+ * in registration order: call this AFTER whatever uses the dir has registered
20
+ * its own teardown (adapter dispose, process stop), or the dir goes first.
21
+ */
22
+ export function removeAfter(t, dir) {
23
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
24
+ }
25
+ /** createTestTempDir + removeAfter, for a dir nothing outlives. */
26
+ export function testTempDir(t, prefix) {
27
+ const dir = createTestTempDir(prefix);
28
+ removeAfter(t, dir);
29
+ return dir;
30
+ }
31
+ /** Removes every path recorded in the ledger, then the ledger. Returns the removed and refused paths. */
32
+ export function cleanRecordedTempDirs() {
33
+ const removed = [];
34
+ const refused = [];
35
+ let recorded;
36
+ try {
37
+ recorded = readFileSync(ledgerPath(), "utf8").split("\n").filter(Boolean);
38
+ }
39
+ catch (e) {
40
+ if (e.code === "ENOENT")
41
+ return { removed, refused };
42
+ throw e;
43
+ }
44
+ for (const dir of new Set(recorded)) {
45
+ const ours = isAbsolute(dir) && dirname(dir) === tmpdir().replace(/\/$/, "") && TEST_TMP_PREFIXES.some((p) => basename(dir).startsWith(p));
46
+ if (!ours) {
47
+ refused.push(dir);
48
+ continue;
49
+ }
50
+ rmSync(dir, { recursive: true, force: true });
51
+ removed.push(dir);
52
+ }
53
+ rmSync(ledgerPath(), { force: true });
54
+ return { removed, refused };
55
+ }
@@ -0,0 +1,3 @@
1
+ import type { PlatformTool, ToolName } from "../spi.ts";
2
+ export declare const FIXTURE_TOOL_NAMES: readonly ToolName[];
3
+ export declare function fixtureTools(invoke?: PlatformTool["invoke"]): PlatformTool[];
@@ -0,0 +1,11 @@
1
+ export const FIXTURE_TOOL_NAMES = ["bash", "read", "write", "edit", "glob", "grep"];
2
+ const READ_ONLY = new Set(["read", "glob", "grep"]);
3
+ export function fixtureTools(invoke = async () => ({ text: "ok", isError: false })) {
4
+ return FIXTURE_TOOL_NAMES.map((name) => ({
5
+ name,
6
+ description: `fixture ${name}`,
7
+ parameters: { type: "object", properties: { command: { type: "string" }, file_path: { type: "string" } }, additionalProperties: false },
8
+ readOnly: READ_ONLY.has(name),
9
+ invoke,
10
+ }));
11
+ }
@@ -0,0 +1 @@
1
+ export declare const DSH_VERSION = "0.2.2-rc.1";
package/lib/version.js ADDED
@@ -0,0 +1,4 @@
1
+ // The DSH version this adapter is pinned to (test `pins` keeps it equal to package.json).
2
+ // A constant, not an import of package.json: a bundle of a host would inline the
3
+ // whole manifest, so every manifest edit (a release bump) would change the bundle.
4
+ export const DSH_VERSION = "0.2.2-rc.1";
package/package.json CHANGED
@@ -1,6 +1,78 @@
1
1
  {
2
2
  "name": "@beeos-ai/bma-dsh-adapter",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "BMA's shared DSH adapter: kernel assembly, platform-tools-only catalog gate, event translation, approval ids, JSONL resume, typed stop reasons, plus a conformance suite for hosts.",
5
+ "keywords": [
6
+ "dsh",
7
+ "deepseek",
8
+ "agent",
9
+ "acp",
10
+ "managed-agents"
11
+ ],
12
+ "homepage": "https://staging.bma.beeos.ai",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/beeos-ai/beeos-managed-agents.git",
16
+ "directory": "brain-host/packages/dsh-adapter"
17
+ },
18
+ "license": "Apache-2.0",
19
+ "type": "module",
20
+ "engines": {
21
+ "node": ">=24"
22
+ },
23
+ "exports": {
24
+ ".": {
25
+ "types": "./lib/index.d.ts",
26
+ "default": "./lib/index.js"
27
+ },
28
+ "./testing": {
29
+ "types": "./lib/testing/index.d.ts",
30
+ "default": "./lib/testing/index.js"
31
+ },
32
+ "./conformance": {
33
+ "types": "./lib/conformance/index.d.ts",
34
+ "default": "./lib/conformance/index.js"
35
+ }
36
+ },
37
+ "dependencies": {
38
+ "@deepseek-ai/cordis": "4.1.0",
39
+ "@deepseek-ai/cosmokit": "1.9.0",
40
+ "@deepseek-ai/dsh-agent": "0.2.2-rc.1",
41
+ "@deepseek-ai/dsh-agent-loop": "0.2.2-rc.1",
42
+ "@deepseek-ai/dsh-attachment": "0.2.2-rc.1",
43
+ "@deepseek-ai/dsh-attachment-local": "0.2.2-rc.1",
44
+ "@deepseek-ai/dsh-brand": "0.2.2-rc.1",
45
+ "@deepseek-ai/dsh-commands": "0.2.2-rc.1",
46
+ "@deepseek-ai/dsh-compaction": "0.2.2-rc.1",
47
+ "@deepseek-ai/dsh-compaction-basic": "0.2.2-rc.1",
48
+ "@deepseek-ai/dsh-compaction-image-offload": "0.2.2-rc.1",
49
+ "@deepseek-ai/dsh-compaction-tool-result-pruner": "0.2.2-rc.1",
50
+ "@deepseek-ai/dsh-home-paths": "0.2.2-rc.1",
51
+ "@deepseek-ai/dsh-llm": "0.2.2-rc.1",
52
+ "@deepseek-ai/dsh-session": "0.2.2-rc.1",
53
+ "@deepseek-ai/dsh-session-persistence": "0.2.2-rc.1",
54
+ "@deepseek-ai/dsh-session-persistence-jsonl": "0.2.2-rc.1",
55
+ "@deepseek-ai/dsh-session-projection": "0.2.2-rc.1",
56
+ "@deepseek-ai/dsh-system-prompt": "0.2.2-rc.1",
57
+ "@deepseek-ai/dsh-token-meter": "0.2.2-rc.1",
58
+ "@deepseek-ai/dsh-tool-executor-native": "0.2.2-rc.1",
59
+ "@deepseek-ai/dsh-tools": "0.2.2-rc.1",
60
+ "@deepseek-ai/node-addon-system": "0.1.2",
61
+ "@deepseek-ai/schemastery": "3.19.0"
62
+ },
63
+ "files": [
64
+ "lib",
65
+ "LICENSE",
66
+ "NOTICE",
67
+ "README.md",
68
+ "UPGRADING.md"
69
+ ],
70
+ "publishConfig": {
71
+ "access": "public",
72
+ "provenance": true
73
+ },
74
+ "scripts": {
75
+ "test": "node --test --test-concurrency=1 'test/**/*.test.ts'",
76
+ "build": "node scripts/build.ts"
77
+ }
6
78
  }