@beeos-ai/bma-dsh-acp 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.
- package/LICENSE +201 -0
- package/NOTICE +11 -0
- package/README.md +81 -2
- package/lib/agent.js +409 -0
- package/lib/main.js +39 -0
- package/lib/protocol.js +17 -0
- package/lib/tools.js +78 -0
- package/package.json +47 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
@beeos-ai/bma-dsh-acp
|
|
2
|
+
Copyright 2026 BeeOS
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0 (see LICENSE).
|
|
5
|
+
|
|
6
|
+
This package contains original BeeOS code (it is not derived from the
|
|
7
|
+
Omnara-based platform sources). It does not contain code from the BeeOS
|
|
8
|
+
desktop application or any other code under an internal license.
|
|
9
|
+
|
|
10
|
+
The DSH libraries (@deepseek-ai/*, MIT) and the other dependencies are not
|
|
11
|
+
bundled: they are installed from the npm registry under their own licenses.
|
package/README.md
CHANGED
|
@@ -1,3 +1,82 @@
|
|
|
1
|
-
#
|
|
1
|
+
# bma-dsh-acp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The shared DSH adapter (`@beeos-ai/bma-dsh-adapter`) served as an [Agent Client Protocol](https://agentclientprotocol.com) agent on stdio ([ADR-0027](../../../docs/adr/0027-one-dsh-kernel-many-host-shells.md)). The BMA executor (bma-executor-sdk, Go) starts it and drives it with its ACP client; it replaces `dsh --profile acp` on users' computers and in sandboxes. Apache-2.0.
|
|
4
|
+
|
|
5
|
+
It has no DSH dependency of its own (test `pins`), runs the shared conformance suite through a real child process over ACP (`test/conformance.test.ts`), and never runs a tool itself: tools run on the executor's machine (its execution core), so the hands are the same as for a platform brain.
|
|
6
|
+
|
|
7
|
+
## Install and run (npm)
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npx --yes @beeos-ai/bma-dsh-acp@0.2.0 # one-off; or: npm install -g @beeos-ai/bma-dsh-acp
|
|
11
|
+
BMA_DSH_ACP_HOME=$HOME/.bma-dsh-acp bma-dsh-acp # ACP (JSON-RPC, newline-delimited) on stdin/stdout
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
- **Node >= 24** (the package ships JavaScript; no TypeScript flags needed). Tested on Linux x64 and macOS arm64 (the ACP and conformance suites run against the npm-installed bin, `scripts/check-npm.sh`); Windows is untested.
|
|
15
|
+
- `BMA_DSH_ACP_HOME` is required (the agent's state directory, see Environment below). stdout carries ACP only.
|
|
16
|
+
- **DSH is not bundled.** npm installs the official [`@deepseek-ai/*`](https://www.npmjs.com/org/deepseek-ai) packages. Their versions are pinned exactly by `@beeos-ai/bma-dsh-adapter` (today DSH `0.2.2-rc.1`, also reported as `_meta.bma.dsh` by `initialize`), including the transitive ranges DSH leaves open (cosmokit, schemastery, the flock addon), so one package version always installs the same DSH. The native parts come from those dependencies: the flock Node-API addon from the per-platform `@deepseek-ai/node-addon-system-<platform>-<arch>` package (installed through `optionalDependencies`, so do not install with `--omit=optional`), the JSONL verification worker as a plain file of `dsh-session-persistence-jsonl`.
|
|
17
|
+
- Pin the version in your launcher (`@0.1.0` above): `npx` without a version takes the newest release.
|
|
18
|
+
|
|
19
|
+
Which form to use:
|
|
20
|
+
|
|
21
|
+
| | npm package (this section) | Single-file bundle (`scripts/build.ts`) |
|
|
22
|
+
|---|---|---|
|
|
23
|
+
| For | developers, CLI, a local brain on your own computer | BMA Desktop, the sandbox machine templates |
|
|
24
|
+
| DSH | official npm packages, exact-pinned, installed by npm | inlined into `bma-dsh-acp.mjs` / SEA, sha256-pinned by the template |
|
|
25
|
+
| Needs | Node >= 24 and network access to npm at install | Node >= 24 (`.mjs`) or nothing (SEA) |
|
|
26
|
+
| Releases | tag `dsh-acp-vX.Y.Z` (`.github/workflows/dsh-acp-release.yaml`), versions of the two packages move together | built with the host application / template |
|
|
27
|
+
|
|
28
|
+
Using it from the BMA executor SDK (`bma-executor-sdk`, Go `ACPAgent`; the SDK never looks the command up on `PATH`, so `Command[0]` is an absolute path):
|
|
29
|
+
|
|
30
|
+
```go
|
|
31
|
+
agent, err := bmaexecutor.NewACPAgent(ctx, bmaexecutor.ACPAgentOptions{
|
|
32
|
+
// installed once with `npm install -g @beeos-ai/bma-dsh-acp@0.2.0` (the `bma-dsh-acp` bin of that prefix):
|
|
33
|
+
Command: []string{"/usr/local/bin/bma-dsh-acp"},
|
|
34
|
+
// or fetched on first use (slow first start; the cache keeps it afterwards):
|
|
35
|
+
// Command: []string{"/usr/local/bin/npx", "--yes", "@beeos-ai/bma-dsh-acp@0.2.0"},
|
|
36
|
+
StateDir: stateDir, // becomes BMA_DSH_ACP_HOME
|
|
37
|
+
Core: core,
|
|
38
|
+
Upstream: bmaexecutor.ACPModelUpstream{BaseURL: "https://api.example.com/v1", Model: "my-model"},
|
|
39
|
+
})
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Protocol
|
|
43
|
+
|
|
44
|
+
Standard ACP v1 (`@agentclientprotocol/sdk`), plus BMA additions under the `bma` `_meta` key and `_bma/` methods (ACP extensibility). Shapes: `src/protocol.ts`.
|
|
45
|
+
|
|
46
|
+
| ACP | bma-dsh-acp |
|
|
47
|
+
|---|---|
|
|
48
|
+
| `initialize` | `loadSession`, image prompts; `_meta.bma` = `{dsh, tools, hostTools, streaming: "token", permissionRelay: "full", modes}`. Request `_meta.bma.hostTools` = `[{name, description, parameters, readOnly, kind, permission?}]`: tools the client's machine adds to the six (for example `computer_observe`, `computer_action`, `ask_user_question`); registered for every session, asked for by `permission` (`ask` by default, `allow`), run by the client like the six |
|
|
49
|
+
| `session/new`, `session/load` | `_meta.bma` = `{sessionId?, systemPrompt?, model: {baseUrl, token, model, contextWindow?, maxOutputTokens?}}` (required: no model request without an attributable route). `sessionId` = platform session id = DSH session id. Response `_meta.bma.toolCatalog` (the six CMA tools plus the declared host tools; anything else is refused, fail-closed). `load` replays the conversation as `session/update`; an unknown session is `-32002` |
|
|
50
|
+
| `session/set_mode` | `default` (ask before bash/write/edit) or `accept_edits` (ask before bash); read/glob/grep never ask |
|
|
51
|
+
| `session/prompt` | `_meta.bma` = `{inputId?, toolPolicy?}` (`toolPolicy`: per-tool allow/ask/deny for this prompt, e.g. from turn.start `tool_policy`). Streams `agent_message_chunk` / `agent_thought_chunk` with a `messageId`; the durable text of that message is the notification `_bma/message {sessionId, messageId, kind, text}` |
|
|
52
|
+
| tool call | `tool_call` (`kind`, full `rawInput`, `_meta.bma {name, permission}`) → `session/request_permission` (full input; `allow_once` / `reject_once`) when the policy says ask → request `_bma/tools/call {sessionId, toolCallId, name, input}` → `{text, isError, images?: [{mimeType, data}]}` (the client runs it; images are shown to the model after the tool message, as a user message — Chat Completions tool messages carry text only) → `tool_call_update` completed/failed with the result |
|
|
53
|
+
| `session/cancel` | the turn ends with `stopReason: cancelled`; a pending permission or tool call is abandoned (`$/cancel_request` is sent for it) |
|
|
54
|
+
| stops | `output_limit_reached` → `stopReason: max_tokens` + `_meta.bma {stopCode, detail}`; `context_too_large`, `model_stream_idle` → JSON-RPC error `-32603` with `data.bma {stopCode, detail}`; other failures → `-32603` |
|
|
55
|
+
| `session/close` | releases the session (its JSONL stays for a later load) |
|
|
56
|
+
|
|
57
|
+
Sessions share one DSH kernel in the process; each session is its own agent scope (conversation, tool catalog, model route, permissions): session-level isolation, not one DSH context per session.
|
|
58
|
+
|
|
59
|
+
Environment: `BMA_DSH_ACP_HOME` (state directory, required), `BMA_DSH_ACP_STREAM_IDLE_MS`, `BRAIN_MODEL_CATALOG`. stdout carries ACP only (console output goes to stderr).
|
|
60
|
+
|
|
61
|
+
## Build (bundle and npm form)
|
|
62
|
+
|
|
63
|
+
```sh
|
|
64
|
+
node scripts/build.ts # dist/bma-dsh-acp.mjs + dist/bma-dsh-acp (SEA; needs an official Node >= 25.5 with --build-sea)
|
|
65
|
+
node scripts/build.ts --no-sea # dist/bma-dsh-acp.mjs only (run with node >= 24)
|
|
66
|
+
BMA_DSH_ACP_BIN=/somewhere/else/bma-dsh-acp node --test --test-concurrency=1 'test/**/*.test.ts' # the suites against a build
|
|
67
|
+
BMA_DSH_ACP_BIN=$PWD/dist/bma-dsh-acp node scripts/measure.ts # startup and RSS
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`pnpm --filter @beeos-ai/bma-dsh-adapter run build && pnpm --filter @beeos-ai/bma-dsh-acp run build:npm` produces the npm form (`lib/`, JavaScript; `bash scripts/check-npm.sh` packs, installs and tests it).
|
|
71
|
+
|
|
72
|
+
The bundle builds are for the build host's OS/arch. The DSH JSONL verification worker and the flock Node-API addon are embedded and written once to `$BMA_DSH_ACP_HOME/.runtime/` (see `scripts/build.ts`).
|
|
73
|
+
|
|
74
|
+
Measured on macOS arm64 (2026-11-09, scripted model, `scripts/measure.ts`):
|
|
75
|
+
|
|
76
|
+
| Build | Size | Start → initialized | RSS idle | RSS 1 session + turn | RSS 10 sessions |
|
|
77
|
+
|---|---|---|---|---|---|
|
|
78
|
+
| `src/main.ts` (node 26.7) | — | 340–470 ms | 125–131 MiB | 130–134 MiB | 144–150 MiB |
|
|
79
|
+
| `dist/bma-dsh-acp.mjs` (node 26.7) | 2.97 MB | 300–325 ms | 84 MiB | 90 MiB | 114 MiB |
|
|
80
|
+
| `dist/bma-dsh-acp` SEA (node 26.13) | 148.7 MB | 260–350 ms | 91–92 MiB | 102 MiB | 124 MiB |
|
|
81
|
+
|
|
82
|
+
For comparison, `dsh --profile acp` measured about 280 MB per process (LB0 spike).
|
package/lib/agent.js
ADDED
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
// bma-dsh-acp: the shared DSH adapter served as an ACP agent (ADR 0027).
|
|
2
|
+
//
|
|
3
|
+
// ACP shared adapter / client
|
|
4
|
+
// initialize capabilities + _meta.bma facts (dsh version, tools, streaming, permission relay);
|
|
5
|
+
// request _meta.bma.hostTools adds the client machine's own tools to the six
|
|
6
|
+
// session/new | load createSession | resumeSession (+ history replay); _meta.bma carries the model route
|
|
7
|
+
// session/set_mode per-session tool policy (default | accept_edits)
|
|
8
|
+
// session/prompt submitInput: deltas -> agent_*_chunk (messageId), durable -> _bma/message
|
|
9
|
+
// tool call tool_call -> [request_permission] -> _bma/tools/call (client runs it) -> tool_call_update
|
|
10
|
+
// session/cancel aborts the turn: pending permission / tool call are abandoned, stopReason cancelled
|
|
11
|
+
// stops output_limit_reached -> max_tokens; other typed stops -> JSON-RPC error data.bma
|
|
12
|
+
//
|
|
13
|
+
// Tools never run in this process: the executor runs them on its machine
|
|
14
|
+
// (its execution core), so the hands are the same as for a platform brain.
|
|
15
|
+
import { randomUUID } from "node:crypto";
|
|
16
|
+
import { agent as acpAgent, PROTOCOL_VERSION, RequestError } from "@agentclientprotocol/sdk";
|
|
17
|
+
import { DSH_VERSION, DshAdapter, ModelCatalog, SessionNotFoundError, TurnStopError, catalogViolation, refusalFor, } from "@beeos-ai/bma-dsh-adapter";
|
|
18
|
+
import shellPkg from "../package.json" with { type: "json" };
|
|
19
|
+
import { MESSAGE, META, MODES, TOOLS_CALL, TOOL_NAMES, modePolicy, } from "./protocol.js";
|
|
20
|
+
import { TOOL_SPECS } from "./tools.js";
|
|
21
|
+
export const VERSION = shellPkg.version;
|
|
22
|
+
const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
|
|
23
|
+
const MEDIA = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
|
|
24
|
+
const HOST_TOOL_NAME = /^[a-z][a-z0-9_]{0,63}$/;
|
|
25
|
+
const KINDS = new Set(["read", "edit", "delete", "move", "search", "execute", "think", "fetch", "switch_mode", "other"]);
|
|
26
|
+
export class DshAcpShell {
|
|
27
|
+
app;
|
|
28
|
+
client;
|
|
29
|
+
sessions = new Map();
|
|
30
|
+
declared = new Map();
|
|
31
|
+
adapter;
|
|
32
|
+
catalog;
|
|
33
|
+
/** This build decodes images (DshAdapter.probeImageInput); without it image prompts are refused. */
|
|
34
|
+
imageInput = false;
|
|
35
|
+
/** The client machine's tools (initialize _meta.bma.hostTools). */
|
|
36
|
+
hostTools = [];
|
|
37
|
+
constructor(adapter, catalog) {
|
|
38
|
+
this.adapter = adapter;
|
|
39
|
+
this.catalog = catalog;
|
|
40
|
+
this.app = acpAgent({ name: "bma-dsh-acp" })
|
|
41
|
+
.onConnect((conn) => { this.client = conn.client; })
|
|
42
|
+
.onRequest("initialize", ({ params }) => this.initialize(params))
|
|
43
|
+
.onRequest("session/new", ({ params }) => this.open(params, false))
|
|
44
|
+
.onRequest("session/load", ({ params }) => this.open(params, true))
|
|
45
|
+
.onRequest("session/set_mode", ({ params }) => this.setMode(params))
|
|
46
|
+
.onRequest("session/prompt", ({ params }) => this.prompt(params))
|
|
47
|
+
.onRequest("session/close", ({ params }) => this.close(params.sessionId))
|
|
48
|
+
.onNotification("session/cancel", ({ params }) => { this.sessions.get(params.sessionId)?.running?.abort(); });
|
|
49
|
+
}
|
|
50
|
+
static async create(options) {
|
|
51
|
+
const adapter = await DshAdapter.mount({ home: options.home, ...(options.streamIdleMs !== undefined ? { streamIdleMs: options.streamIdleMs } : {}) });
|
|
52
|
+
const shell = new DshAcpShell(adapter, options.catalog ?? new ModelCatalog());
|
|
53
|
+
adapter.configureModel({
|
|
54
|
+
limits: (model) => shell.declared.get(model) ?? shell.catalog.resolve(model),
|
|
55
|
+
route: (sessionId) => {
|
|
56
|
+
const s = shell.sessions.get(sessionId);
|
|
57
|
+
if (!s)
|
|
58
|
+
throw new Error(`no model route for session ${sessionId}`);
|
|
59
|
+
return { baseUrl: s.model.baseUrl, token: s.model.token, model: s.model.model };
|
|
60
|
+
},
|
|
61
|
+
firstChunk: () => { },
|
|
62
|
+
idleRetry: (sid, result) => { process.stderr.write(`bma-dsh-acp: model stream idle before any content (session ${sid}): ${result}\n`); },
|
|
63
|
+
usage: () => { }, // metered by the client's model proxy
|
|
64
|
+
});
|
|
65
|
+
shell.registerTools();
|
|
66
|
+
shell.imageInput = await adapter.probeImageInput();
|
|
67
|
+
if (!shell.imageInput)
|
|
68
|
+
process.stderr.write("bma-dsh-acp: image input is unavailable in this build (the image decoder could not be loaded); image prompts are refused\n");
|
|
69
|
+
return shell;
|
|
70
|
+
}
|
|
71
|
+
async dispose() {
|
|
72
|
+
for (const s of this.sessions.values())
|
|
73
|
+
s.running?.abort();
|
|
74
|
+
await this.adapter.dispose();
|
|
75
|
+
}
|
|
76
|
+
registerTools() {
|
|
77
|
+
this.adapter.registerTools([...TOOL_SPECS, ...this.hostTools].map((spec) => this.tool(spec)));
|
|
78
|
+
}
|
|
79
|
+
toolNames() {
|
|
80
|
+
return [...TOOL_NAMES, ...this.hostTools.map((t) => t.name)];
|
|
81
|
+
}
|
|
82
|
+
initialize(params) {
|
|
83
|
+
if (this.sessions.size)
|
|
84
|
+
throw RequestError.invalidRequest(undefined, "initialize after a session was opened");
|
|
85
|
+
this.hostTools = hostToolsMeta(params._meta);
|
|
86
|
+
this.registerTools();
|
|
87
|
+
return {
|
|
88
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
89
|
+
agentCapabilities: { loadSession: true, promptCapabilities: { image: this.imageInput, audio: false, embeddedContext: false }, mcpCapabilities: { http: false, sse: false } },
|
|
90
|
+
agentInfo: { name: "bma-dsh-acp", title: "BMA DSH", version: VERSION },
|
|
91
|
+
authMethods: [],
|
|
92
|
+
_meta: { [META]: { dsh: DSH_VERSION, tools: TOOL_NAMES, hostTools: this.hostTools.map((t) => t.name), streaming: "token", permissionRelay: "full", modes: Object.keys(MODES) } },
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
async open(params, load) {
|
|
96
|
+
const meta = sessionMeta(params._meta);
|
|
97
|
+
const id = load ? params.sessionId : (meta.sessionId ?? randomUUID());
|
|
98
|
+
if (!SESSION_ID.test(id))
|
|
99
|
+
throw RequestError.invalidParams(undefined, "session id");
|
|
100
|
+
const open = this.sessions.get(id);
|
|
101
|
+
if (open && !load)
|
|
102
|
+
throw RequestError.invalidParams(undefined, `session ${id} is already open`);
|
|
103
|
+
if (meta.model.contextWindow && meta.model.maxOutputTokens) {
|
|
104
|
+
this.declared.set(meta.model.model, { contextWindow: meta.model.contextWindow, maxOutputTokens: Math.min(meta.model.maxOutputTokens, Math.floor(meta.model.contextWindow / 2)), source: "declared" });
|
|
105
|
+
}
|
|
106
|
+
if (open) {
|
|
107
|
+
open.model = meta.model; // a reload in the same process: new route, same conversation
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
const s = { id, model: meta.model, mode: "default", policy: modePolicy("default", this.hostTools), ids: freshIds(), chain: Promise.resolve() };
|
|
111
|
+
this.sessions.set(id, s); // the route must exist before the first model request
|
|
112
|
+
const init = { sessionId: id, model: meta.model.model, systemPrompt: meta.systemPrompt ?? "", cwd: params.cwd };
|
|
113
|
+
try {
|
|
114
|
+
if (load)
|
|
115
|
+
await this.adapter.resumeSession(init);
|
|
116
|
+
else
|
|
117
|
+
await this.adapter.createSession(init);
|
|
118
|
+
}
|
|
119
|
+
catch (err) {
|
|
120
|
+
this.sessions.delete(id);
|
|
121
|
+
if (err instanceof SessionNotFoundError)
|
|
122
|
+
throw RequestError.sessionNotFound(id);
|
|
123
|
+
throw err;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
const catalog = [...this.adapter.toolCatalog(id)];
|
|
127
|
+
const violation = catalogViolation("dsh", this.toolNames(), catalog);
|
|
128
|
+
if (violation) {
|
|
129
|
+
await this.close(id);
|
|
130
|
+
throw RequestError.internalError(undefined, violation);
|
|
131
|
+
}
|
|
132
|
+
if (load)
|
|
133
|
+
await this.replay(this.sessions.get(id));
|
|
134
|
+
const s = this.sessions.get(id);
|
|
135
|
+
return {
|
|
136
|
+
sessionId: id,
|
|
137
|
+
modes: { currentModeId: s.mode, availableModes: Object.entries(MODES).map(([modeId, m]) => ({ id: modeId, name: m.name, description: m.description })) },
|
|
138
|
+
_meta: { [META]: { toolCatalog: catalog } },
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/** ACP session/load: the agent MUST stream the whole conversation back before answering. */
|
|
142
|
+
async replay(s) {
|
|
143
|
+
for (const item of this.adapter.history(s.id)) {
|
|
144
|
+
const sessionUpdate = item.role === "user" ? "user_message_chunk" : item.type === "thinking" ? "agent_thought_chunk" : "agent_message_chunk";
|
|
145
|
+
this.send(s, "session/update", { sessionId: s.id, update: { sessionUpdate, content: { type: "text", text: item.text } } });
|
|
146
|
+
}
|
|
147
|
+
await s.chain;
|
|
148
|
+
}
|
|
149
|
+
setMode(params) {
|
|
150
|
+
const s = this.get(params.sessionId);
|
|
151
|
+
if (!(params.modeId in MODES))
|
|
152
|
+
throw RequestError.invalidParams(undefined, `unknown mode ${params.modeId}`);
|
|
153
|
+
s.mode = params.modeId;
|
|
154
|
+
if (!s.running)
|
|
155
|
+
s.policy = modePolicy(s.mode, this.hostTools);
|
|
156
|
+
return {};
|
|
157
|
+
}
|
|
158
|
+
async prompt(params) {
|
|
159
|
+
const s = this.get(params.sessionId);
|
|
160
|
+
if (s.running)
|
|
161
|
+
throw RequestError.invalidRequest(undefined, "a prompt is already running in this session");
|
|
162
|
+
const meta = promptMeta(params._meta, this.toolNames());
|
|
163
|
+
s.policy = { ...modePolicy(s.mode, this.hostTools), ...meta.toolPolicy };
|
|
164
|
+
const input = { id: meta.inputId ?? randomUUID(), ...promptInput(params.prompt) };
|
|
165
|
+
if (input.images && !this.imageInput)
|
|
166
|
+
throw RequestError.invalidParams(undefined, "image input is unavailable in this build of bma-dsh-acp");
|
|
167
|
+
const ctl = new AbortController();
|
|
168
|
+
s.running = ctl;
|
|
169
|
+
try {
|
|
170
|
+
try {
|
|
171
|
+
for await (const event of this.adapter.submitInput(s.id, input, ctl.signal))
|
|
172
|
+
this.emit(s, event);
|
|
173
|
+
}
|
|
174
|
+
finally {
|
|
175
|
+
await s.chain;
|
|
176
|
+
}
|
|
177
|
+
return { stopReason: ctl.signal.aborted ? "cancelled" : "end_turn" };
|
|
178
|
+
}
|
|
179
|
+
catch (err) {
|
|
180
|
+
if (ctl.signal.aborted)
|
|
181
|
+
return { stopReason: "cancelled" };
|
|
182
|
+
if (err instanceof TurnStopError) {
|
|
183
|
+
const stop = { stopCode: err.code, detail: err.message.slice(err.code.length + 2) };
|
|
184
|
+
if (err.code === "output_limit_reached")
|
|
185
|
+
return { stopReason: "max_tokens", _meta: { [META]: stop } };
|
|
186
|
+
throw new RequestError(-32603, err.message, { [META]: stop });
|
|
187
|
+
}
|
|
188
|
+
throw new RequestError(-32603, err.message);
|
|
189
|
+
}
|
|
190
|
+
finally {
|
|
191
|
+
s.running = undefined;
|
|
192
|
+
s.policy = modePolicy(s.mode, this.hostTools);
|
|
193
|
+
s.ids = freshIds();
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
async close(sessionId) {
|
|
197
|
+
const s = this.sessions.get(sessionId);
|
|
198
|
+
if (!s)
|
|
199
|
+
throw RequestError.sessionNotFound(sessionId);
|
|
200
|
+
s.running?.abort();
|
|
201
|
+
this.sessions.delete(sessionId);
|
|
202
|
+
await this.adapter.close(sessionId);
|
|
203
|
+
return {};
|
|
204
|
+
}
|
|
205
|
+
get(sessionId) {
|
|
206
|
+
const s = this.sessions.get(sessionId);
|
|
207
|
+
if (!s)
|
|
208
|
+
throw RequestError.sessionNotFound(sessionId);
|
|
209
|
+
return s;
|
|
210
|
+
}
|
|
211
|
+
send(s, method, params) {
|
|
212
|
+
const client = this.client;
|
|
213
|
+
s.chain = s.chain.then(() => client.notify(method, params)).catch(() => { });
|
|
214
|
+
}
|
|
215
|
+
emit(s, event) {
|
|
216
|
+
if (event.type === "delta") {
|
|
217
|
+
const sessionUpdate = event.kind === "message" ? "agent_message_chunk" : "agent_thought_chunk";
|
|
218
|
+
this.send(s, "session/update", { sessionId: s.id, update: { sessionUpdate, messageId: s.ids[event.kind], content: { type: "text", text: event.text } } });
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
this.send(s, MESSAGE, { sessionId: s.id, messageId: s.ids[event.type], kind: event.type, text: event.text });
|
|
222
|
+
s.ids[event.type] = randomUUID();
|
|
223
|
+
}
|
|
224
|
+
tool(spec) {
|
|
225
|
+
return {
|
|
226
|
+
name: spec.name,
|
|
227
|
+
description: spec.description,
|
|
228
|
+
parameters: spec.parameters,
|
|
229
|
+
readOnly: spec.readOnly,
|
|
230
|
+
invoke: (call) => this.invoke(spec, call),
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
/** tool_call -> [request_permission] -> _bma/tools/call -> tool_call_update. Every outcome is a result the model reads. */
|
|
234
|
+
async invoke(spec, call) {
|
|
235
|
+
const s = this.get(call.sessionId);
|
|
236
|
+
const client = this.client;
|
|
237
|
+
const permission = s.policy[spec.name] ?? "ask";
|
|
238
|
+
// Let the turn's queued message events go out first (they were produced before this call).
|
|
239
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
240
|
+
s.ids = freshIds();
|
|
241
|
+
const toolCall = { toolCallId: call.callId, title: spec.name, kind: spec.kind, status: "pending", rawInput: call.input };
|
|
242
|
+
this.send(s, "session/update", { sessionId: s.id, update: { sessionUpdate: "tool_call", ...toolCall, _meta: { [META]: { name: spec.name, permission } } } });
|
|
243
|
+
const finish = async (result) => {
|
|
244
|
+
this.send(s, "session/update", {
|
|
245
|
+
sessionId: s.id,
|
|
246
|
+
update: { sessionUpdate: "tool_call_update", toolCallId: call.callId, status: result.isError ? "failed" : "completed", content: [{ type: "content", content: { type: "text", text: result.text } }] },
|
|
247
|
+
});
|
|
248
|
+
await s.chain;
|
|
249
|
+
return result;
|
|
250
|
+
};
|
|
251
|
+
const aborted = () => ({ text: "The tool call was cancelled.", isError: true });
|
|
252
|
+
if (permission === "deny")
|
|
253
|
+
return finish({ text: `The ${spec.name} tool is not allowed in this session.`, isError: true });
|
|
254
|
+
if (permission === "ask") {
|
|
255
|
+
await s.chain;
|
|
256
|
+
const answer = await untilAborted(client.request("session/request_permission", {
|
|
257
|
+
sessionId: s.id,
|
|
258
|
+
toolCall,
|
|
259
|
+
options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }, { optionId: "reject", name: "Reject", kind: "reject_once" }],
|
|
260
|
+
}, { cancellationSignal: call.signal }), call.signal);
|
|
261
|
+
if (!answer || answer.outcome.outcome === "cancelled")
|
|
262
|
+
return finish(aborted());
|
|
263
|
+
const refusal = refusalFor(spec.name, { outcome: answer.outcome.optionId === "allow" ? "allow" : "deny" });
|
|
264
|
+
if (refusal)
|
|
265
|
+
return finish(refusal);
|
|
266
|
+
}
|
|
267
|
+
this.send(s, "session/update", { sessionId: s.id, update: { sessionUpdate: "tool_call_update", toolCallId: call.callId, status: "in_progress" } });
|
|
268
|
+
await s.chain;
|
|
269
|
+
try {
|
|
270
|
+
const result = await untilAborted(client.request(TOOLS_CALL, { sessionId: s.id, toolCallId: call.callId, name: spec.name, input: call.input }, { cancellationSignal: call.signal }), call.signal);
|
|
271
|
+
if (!result)
|
|
272
|
+
return finish(aborted());
|
|
273
|
+
const images = (result.images ?? []).filter((i) => MEDIA.has(i.mimeType) && typeof i.data === "string" && i.data)
|
|
274
|
+
.map((i) => ({ mediaType: i.mimeType, data: i.data }));
|
|
275
|
+
return finish({ text: String(result.text ?? ""), isError: Boolean(result.isError), ...(images.length ? { images } : {}) });
|
|
276
|
+
}
|
|
277
|
+
catch (err) {
|
|
278
|
+
if (call.signal.aborted)
|
|
279
|
+
return finish(aborted());
|
|
280
|
+
return finish({ text: `The tool call failed on the executor: ${err.message}`, isError: true });
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
function freshIds() {
|
|
285
|
+
return { message: randomUUID(), thinking: randomUUID() };
|
|
286
|
+
}
|
|
287
|
+
/** Resolves undefined once signal aborts; the request's own settlement is then ignored. */
|
|
288
|
+
function untilAborted(p, signal) {
|
|
289
|
+
if (signal.aborted) {
|
|
290
|
+
p.catch(() => { });
|
|
291
|
+
return Promise.resolve(undefined);
|
|
292
|
+
}
|
|
293
|
+
return new Promise((resolve, reject) => {
|
|
294
|
+
const onAbort = () => resolve(undefined);
|
|
295
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
296
|
+
p.then((v) => { signal.removeEventListener("abort", onAbort); resolve(v); }, (e) => { signal.removeEventListener("abort", onAbort); if (signal.aborted)
|
|
297
|
+
resolve(undefined);
|
|
298
|
+
else
|
|
299
|
+
reject(e); });
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
// --- validation at the protocol boundary ---
|
|
303
|
+
function bmaMeta(meta) {
|
|
304
|
+
const value = meta?.[META];
|
|
305
|
+
if (value === undefined)
|
|
306
|
+
return undefined;
|
|
307
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
308
|
+
throw RequestError.invalidParams(undefined, "_meta.bma must be an object");
|
|
309
|
+
return value;
|
|
310
|
+
}
|
|
311
|
+
function sessionMeta(raw) {
|
|
312
|
+
const meta = bmaMeta(raw);
|
|
313
|
+
const model = meta?.model;
|
|
314
|
+
if (!model || typeof model.model !== "string" || !model.model || typeof model.token !== "string" || !model.token) {
|
|
315
|
+
throw RequestError.invalidParams(undefined, "_meta.bma.model {baseUrl, token, model} is required");
|
|
316
|
+
}
|
|
317
|
+
let url;
|
|
318
|
+
try {
|
|
319
|
+
url = new URL(String(model.baseUrl));
|
|
320
|
+
}
|
|
321
|
+
catch {
|
|
322
|
+
throw RequestError.invalidParams(undefined, "_meta.bma.model.baseUrl must be an http(s) URL");
|
|
323
|
+
}
|
|
324
|
+
if (url.protocol !== "http:" && url.protocol !== "https:")
|
|
325
|
+
throw RequestError.invalidParams(undefined, "_meta.bma.model.baseUrl must be an http(s) URL");
|
|
326
|
+
const count = (v, name) => {
|
|
327
|
+
if (v === undefined)
|
|
328
|
+
return undefined;
|
|
329
|
+
if (!Number.isSafeInteger(v) || v <= 0)
|
|
330
|
+
throw RequestError.invalidParams(undefined, `_meta.bma.model.${name} must be a positive integer`);
|
|
331
|
+
return v;
|
|
332
|
+
};
|
|
333
|
+
const contextWindow = count(model.contextWindow, "contextWindow");
|
|
334
|
+
const maxOutputTokens = count(model.maxOutputTokens, "maxOutputTokens");
|
|
335
|
+
if (meta.sessionId !== undefined && typeof meta.sessionId !== "string")
|
|
336
|
+
throw RequestError.invalidParams(undefined, "_meta.bma.sessionId must be a string");
|
|
337
|
+
if (meta.systemPrompt !== undefined && typeof meta.systemPrompt !== "string")
|
|
338
|
+
throw RequestError.invalidParams(undefined, "_meta.bma.systemPrompt must be a string");
|
|
339
|
+
return {
|
|
340
|
+
...(meta.sessionId !== undefined ? { sessionId: meta.sessionId } : {}),
|
|
341
|
+
...(meta.systemPrompt !== undefined ? { systemPrompt: meta.systemPrompt } : {}),
|
|
342
|
+
model: { baseUrl: String(model.baseUrl), token: model.token, model: model.model, ...(contextWindow ? { contextWindow } : {}), ...(maxOutputTokens ? { maxOutputTokens } : {}) },
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
function hostToolsMeta(raw) {
|
|
346
|
+
const tools = bmaMeta(raw)?.hostTools;
|
|
347
|
+
if (tools === undefined)
|
|
348
|
+
return [];
|
|
349
|
+
if (!Array.isArray(tools))
|
|
350
|
+
throw RequestError.invalidParams(undefined, "_meta.bma.hostTools must be an array");
|
|
351
|
+
const seen = new Set(TOOL_NAMES);
|
|
352
|
+
return tools.map((t, i) => {
|
|
353
|
+
const at = `_meta.bma.hostTools[${i}]`;
|
|
354
|
+
if (typeof t !== "object" || t === null)
|
|
355
|
+
throw RequestError.invalidParams(undefined, `${at} must be an object`);
|
|
356
|
+
if (typeof t.name !== "string" || !HOST_TOOL_NAME.test(t.name) || seen.has(t.name))
|
|
357
|
+
throw RequestError.invalidParams(undefined, `${at}.name must be a new snake_case tool name`);
|
|
358
|
+
seen.add(t.name);
|
|
359
|
+
if (typeof t.description !== "string" || !t.description)
|
|
360
|
+
throw RequestError.invalidParams(undefined, `${at}.description is required`);
|
|
361
|
+
const p = t.parameters;
|
|
362
|
+
if (typeof p !== "object" || p === null || p.type !== "object")
|
|
363
|
+
throw RequestError.invalidParams(undefined, `${at}.parameters must be an object JSON Schema`);
|
|
364
|
+
if (typeof t.readOnly !== "boolean")
|
|
365
|
+
throw RequestError.invalidParams(undefined, `${at}.readOnly must be a boolean`);
|
|
366
|
+
if (typeof t.kind !== "string" || !KINDS.has(t.kind))
|
|
367
|
+
throw RequestError.invalidParams(undefined, `${at}.kind must be an ACP tool kind`);
|
|
368
|
+
if (t.permission !== undefined && t.permission !== "allow" && t.permission !== "ask")
|
|
369
|
+
throw RequestError.invalidParams(undefined, `${at}.permission must be allow or ask`);
|
|
370
|
+
return { name: t.name, description: t.description, parameters: p, readOnly: t.readOnly, kind: t.kind, ...(t.permission ? { permission: t.permission } : {}) };
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
function promptMeta(raw, names) {
|
|
374
|
+
const meta = bmaMeta(raw) ?? {};
|
|
375
|
+
const out = {};
|
|
376
|
+
if (meta.inputId !== undefined) {
|
|
377
|
+
if (typeof meta.inputId !== "string" || !meta.inputId)
|
|
378
|
+
throw RequestError.invalidParams(undefined, "_meta.bma.inputId must be a non-empty string");
|
|
379
|
+
out.inputId = meta.inputId;
|
|
380
|
+
}
|
|
381
|
+
if (meta.toolPolicy !== undefined) {
|
|
382
|
+
const policy = meta.toolPolicy;
|
|
383
|
+
if (typeof policy !== "object" || policy === null)
|
|
384
|
+
throw RequestError.invalidParams(undefined, "_meta.bma.toolPolicy must be an object");
|
|
385
|
+
for (const [name, value] of Object.entries(policy)) {
|
|
386
|
+
if (!names.includes(name) || !["allow", "ask", "deny"].includes(value)) {
|
|
387
|
+
throw RequestError.invalidParams(undefined, `_meta.bma.toolPolicy.${name} must be allow, ask or deny for a known tool`);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
out.toolPolicy = policy;
|
|
391
|
+
}
|
|
392
|
+
return out;
|
|
393
|
+
}
|
|
394
|
+
function promptInput(blocks) {
|
|
395
|
+
const text = [];
|
|
396
|
+
const images = [];
|
|
397
|
+
for (const b of blocks) {
|
|
398
|
+
if (b.type === "text")
|
|
399
|
+
text.push(b.text);
|
|
400
|
+
else if (b.type === "image") {
|
|
401
|
+
if (!MEDIA.has(b.mimeType))
|
|
402
|
+
throw RequestError.invalidParams(undefined, `image type ${b.mimeType} is not supported`);
|
|
403
|
+
images.push({ mediaType: b.mimeType, data: b.data });
|
|
404
|
+
}
|
|
405
|
+
else
|
|
406
|
+
throw RequestError.invalidParams(undefined, `prompt content ${b.type} is not supported`);
|
|
407
|
+
}
|
|
408
|
+
return { text: text.join("\n"), ...(images.length ? { images } : {}) };
|
|
409
|
+
}
|
package/lib/main.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// bma-dsh-acp: ACP agent on stdio. stdout carries ACP messages only, so every
|
|
3
|
+
// console method is sent to stderr before anything else loads.
|
|
4
|
+
//
|
|
5
|
+
// Environment:
|
|
6
|
+
// BMA_DSH_ACP_HOME DSH state directory (required)
|
|
7
|
+
// BMA_DSH_ACP_STREAM_IDLE_MS model stream idle limit (ms, 0 disables)
|
|
8
|
+
// BRAIN_MODEL_CATALOG operator model catalog file (limits per model)
|
|
9
|
+
import { format } from "node:util";
|
|
10
|
+
import { Readable, Writable } from "node:stream";
|
|
11
|
+
const toStderr = (...args) => { process.stderr.write(`${format(...args)}\n`); };
|
|
12
|
+
console.log = console.info = console.debug = console.warn = console.error = console.trace = toStderr;
|
|
13
|
+
const { ndJsonStream } = await import("@agentclientprotocol/sdk");
|
|
14
|
+
const { ModelCatalog, loadCatalogFile } = await import("@beeos-ai/bma-dsh-adapter");
|
|
15
|
+
const { DshAcpShell } = await import("./agent.js");
|
|
16
|
+
const home = process.env.BMA_DSH_ACP_HOME;
|
|
17
|
+
if (!home) {
|
|
18
|
+
process.stderr.write("bma-dsh-acp: BMA_DSH_ACP_HOME is required\n");
|
|
19
|
+
process.exit(2);
|
|
20
|
+
}
|
|
21
|
+
const idle = process.env.BMA_DSH_ACP_STREAM_IDLE_MS;
|
|
22
|
+
if (idle !== undefined && !/^\d{1,9}$/.test(idle)) {
|
|
23
|
+
process.stderr.write("bma-dsh-acp: BMA_DSH_ACP_STREAM_IDLE_MS must be a non-negative integer\n");
|
|
24
|
+
process.exit(2);
|
|
25
|
+
}
|
|
26
|
+
const catalogFile = process.env.BRAIN_MODEL_CATALOG;
|
|
27
|
+
const shell = await DshAcpShell.create({
|
|
28
|
+
home,
|
|
29
|
+
...(idle !== undefined ? { streamIdleMs: Number(idle) } : {}),
|
|
30
|
+
...(catalogFile ? { catalog: new ModelCatalog({ entries: loadCatalogFile(catalogFile), onDefault: (m) => process.stderr.write(`bma-dsh-acp: model ${m} is not in the catalog; conservative limits\n`) }) } : {}),
|
|
31
|
+
});
|
|
32
|
+
const conn = shell.app.connect(ndJsonStream(Writable.toWeb(process.stdout), Readable.toWeb(process.stdin)));
|
|
33
|
+
const stop = async () => {
|
|
34
|
+
await shell.dispose();
|
|
35
|
+
process.exit(0);
|
|
36
|
+
};
|
|
37
|
+
process.once("SIGTERM", () => void stop());
|
|
38
|
+
await conn.closed;
|
|
39
|
+
await stop();
|
package/lib/protocol.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export const META = "bma";
|
|
2
|
+
export const TOOLS_CALL = "_bma/tools/call";
|
|
3
|
+
export const MESSAGE = "_bma/message";
|
|
4
|
+
export const TOOL_NAMES = ["bash", "read", "write", "edit", "glob", "grep"];
|
|
5
|
+
/** Session modes (ACP session/set_mode). Ids follow the executor contract's permission_mode examples. */
|
|
6
|
+
export const MODES = {
|
|
7
|
+
default: { name: "Ask before changes", description: "Ask before bash, write and edit; read, glob and grep run without asking." },
|
|
8
|
+
accept_edits: { name: "Accept edits", description: "Ask before bash; write, edit and the read-only tools run without asking." },
|
|
9
|
+
};
|
|
10
|
+
export function modePolicy(mode, hostTools = []) {
|
|
11
|
+
const ask = "ask";
|
|
12
|
+
const edits = mode === "accept_edits" ? "allow" : "ask";
|
|
13
|
+
const policy = { bash: ask, write: edits, edit: edits, read: "allow", glob: "allow", grep: "allow" };
|
|
14
|
+
for (const tool of hostTools)
|
|
15
|
+
policy[tool.name] = tool.permission ?? "ask";
|
|
16
|
+
return policy;
|
|
17
|
+
}
|
package/lib/tools.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
export const MAX_TOOL_TIMEOUT_MS = 600_000;
|
|
2
|
+
export const DEFAULT_BASH_TIMEOUT_MS = 120_000;
|
|
3
|
+
const object = (required, properties) => ({ type: "object", properties, required, additionalProperties: false });
|
|
4
|
+
const str = (description) => ({ type: "string", description });
|
|
5
|
+
const int = (description, minimum, maximum) => ({ type: "integer", description, minimum, maximum });
|
|
6
|
+
const bool = (description) => ({ type: "boolean", description });
|
|
7
|
+
export const TOOL_SPECS = [
|
|
8
|
+
{
|
|
9
|
+
name: "bash",
|
|
10
|
+
kind: "execute",
|
|
11
|
+
readOnly: false,
|
|
12
|
+
description: "Run a shell command with bash in the working directory on this computer and return its output and exit code.",
|
|
13
|
+
parameters: object(["command"], {
|
|
14
|
+
command: str("The command to run."),
|
|
15
|
+
timeout: int(`Stop the command after this many milliseconds (default ${DEFAULT_BASH_TIMEOUT_MS}).`, 1, MAX_TOOL_TIMEOUT_MS),
|
|
16
|
+
}),
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
name: "read",
|
|
20
|
+
kind: "read",
|
|
21
|
+
readOnly: true,
|
|
22
|
+
description: "Read a text file under the working directory.",
|
|
23
|
+
parameters: object(["file_path"], {
|
|
24
|
+
file_path: str("Absolute path of the file."),
|
|
25
|
+
offset: int("First line to return (1-based).", 1, 2147483647),
|
|
26
|
+
limit: int("Maximum number of lines to return.", 1, 2147483647),
|
|
27
|
+
}),
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
name: "write",
|
|
31
|
+
kind: "edit",
|
|
32
|
+
readOnly: false,
|
|
33
|
+
description: "Create or overwrite a file under the working directory; parent directories are created.",
|
|
34
|
+
parameters: object(["file_path", "content"], {
|
|
35
|
+
file_path: str("Absolute path of the file."),
|
|
36
|
+
content: str("The full file content."),
|
|
37
|
+
}),
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
name: "edit",
|
|
41
|
+
kind: "edit",
|
|
42
|
+
readOnly: false,
|
|
43
|
+
description: "Replace text in a file under the working directory. old_string must match exactly once unless replace_all is true.",
|
|
44
|
+
parameters: object(["file_path", "old_string", "new_string"], {
|
|
45
|
+
file_path: str("Absolute path of the file."),
|
|
46
|
+
old_string: str("The exact text to replace."),
|
|
47
|
+
new_string: str("The replacement text."),
|
|
48
|
+
replace_all: bool("Replace every occurrence (default false)."),
|
|
49
|
+
}),
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
name: "glob",
|
|
53
|
+
kind: "search",
|
|
54
|
+
readOnly: true,
|
|
55
|
+
description: "List files under the working directory matching a glob pattern.",
|
|
56
|
+
parameters: object(["pattern"], {
|
|
57
|
+
pattern: str("The glob pattern, such as *.go or src/*.ts."),
|
|
58
|
+
path: str("Absolute directory to search (default: the working directory)."),
|
|
59
|
+
}),
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
name: "grep",
|
|
63
|
+
kind: "search",
|
|
64
|
+
readOnly: true,
|
|
65
|
+
description: "Search file contents under the working directory with a regular expression.",
|
|
66
|
+
parameters: object(["pattern"], {
|
|
67
|
+
pattern: str("The regular expression."),
|
|
68
|
+
path: str("Absolute file or directory to search (default: the working directory)."),
|
|
69
|
+
glob: str("Only search files whose name matches this glob, such as *.go."),
|
|
70
|
+
output_mode: {
|
|
71
|
+
type: "string",
|
|
72
|
+
enum: ["content", "files_with_matches", "count"],
|
|
73
|
+
description: "content (default) shows matching lines; files_with_matches lists files; count counts matches per file.",
|
|
74
|
+
},
|
|
75
|
+
case_insensitive: bool("Ignore case."),
|
|
76
|
+
}),
|
|
77
|
+
},
|
|
78
|
+
];
|
package/package.json
CHANGED
|
@@ -1,6 +1,50 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@beeos-ai/bma-dsh-acp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "bma-dsh-acp: the shared DSH adapter served as an Agent Client Protocol (stdio) agent, driven by the BMA executor's ACP client.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"dsh",
|
|
7
|
+
"deepseek",
|
|
8
|
+
"agent",
|
|
9
|
+
"acp",
|
|
10
|
+
"agent-client-protocol",
|
|
11
|
+
"managed-agents"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://staging.bma.beeos.ai",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/beeos-ai/beeos-managed-agents.git",
|
|
17
|
+
"directory": "brain-host/packages/dsh-acp"
|
|
18
|
+
},
|
|
19
|
+
"license": "Apache-2.0",
|
|
20
|
+
"type": "module",
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=24"
|
|
23
|
+
},
|
|
24
|
+
"bin": {
|
|
25
|
+
"bma-dsh-acp": "./lib/main.js"
|
|
26
|
+
},
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"@agentclientprotocol/sdk": "2.2.0",
|
|
29
|
+
"zod": "4.6.7",
|
|
30
|
+
"@beeos-ai/bma-dsh-adapter": "0.2.0"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"esbuild": "0.28.2"
|
|
34
|
+
},
|
|
35
|
+
"files": [
|
|
36
|
+
"lib",
|
|
37
|
+
"LICENSE",
|
|
38
|
+
"NOTICE",
|
|
39
|
+
"README.md"
|
|
40
|
+
],
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public",
|
|
43
|
+
"provenance": true
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"test": "node --test --test-concurrency=1 'test/**/*.test.ts'",
|
|
47
|
+
"build": "node scripts/build.ts",
|
|
48
|
+
"build:npm": "node scripts/build-npm.ts"
|
|
49
|
+
}
|
|
6
50
|
}
|