@theopenbee/engine-sdk 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.
- package/LICENSE +21 -0
- package/README.md +143 -2
- package/dist/cli.d.ts +15 -0
- package/dist/cli.js +169 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/main.d.ts +7 -0
- package/dist/main.js +90 -0
- package/dist/types.d.ts +47 -0
- package/dist/types.js +1 -0
- package/package.json +40 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 TENGYONGZHI
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,144 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @theopenbee/engine-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Node.js SDK for building openbee engine plugins. An engine plugin wraps one agent CLI (Claude Code, Codex, pi, ...) so openbee can run it. The SDK implements the one-shot JSON protocol between openbee and the plugin and ships the helpers every wrapper needs: locating the CLI, spawning it with a log file, and reading its version.
|
|
4
|
+
|
|
5
|
+
Requires Node.js 20 or newer. Plugins also run on Bun.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @theopenbee/engine-sdk
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## How openbee calls a plugin
|
|
12
|
+
|
|
13
|
+
For every engine call openbee starts the plugin command (for example `node dist/index.js`) as a new process group, writes **one JSON request line** to its stdin and closes stdin, then reads **one JSON response line** from its stdout. The plugin starts the agent CLI as a child process, waits for it and answers. One process serves one call.
|
|
14
|
+
|
|
15
|
+
Request (protocol version `1`):
|
|
16
|
+
|
|
17
|
+
```json
|
|
18
|
+
{
|
|
19
|
+
"protocol_version": 1,
|
|
20
|
+
"method": "run",
|
|
21
|
+
"openbee_version": "0.9.0",
|
|
22
|
+
"engine_id": "claude",
|
|
23
|
+
"language": "en",
|
|
24
|
+
"config": { "path": "/usr/local/bin/claude" },
|
|
25
|
+
"data_dir": "~/.openbee/plugins/data/claude/",
|
|
26
|
+
"state_dir": "~/.openbee/.claude/",
|
|
27
|
+
"params": {}
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
| Field | Description |
|
|
32
|
+
|---|---|
|
|
33
|
+
| `method` | `check`, `run` or `usage` |
|
|
34
|
+
| `config` | The plugin's configuration as set by the user (for example `path`) |
|
|
35
|
+
| `data_dir` | Private directory for the plugin, deleted when the plugin is uninstalled |
|
|
36
|
+
| `state_dir` | Directory for state that must survive an uninstall; openbee never deletes it |
|
|
37
|
+
| `params` | Method specific, see below |
|
|
38
|
+
|
|
39
|
+
Response, exactly one line:
|
|
40
|
+
|
|
41
|
+
```json
|
|
42
|
+
{"result": {}}
|
|
43
|
+
{"error": {"message": "what went wrong"}}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`runEngine` produces the response and exits with code 0, including for errors. An unknown method, an unsupported `protocol_version` or an exception thrown by the engine becomes an `{"error": ...}` response.
|
|
47
|
+
|
|
48
|
+
| Method | `params` | `result` |
|
|
49
|
+
|---|---|---|
|
|
50
|
+
| `check` | `{}` | `{ version, path }` |
|
|
51
|
+
| `run` | `{ role, work_dir, prompt, session_id, resume, extra_args, log_path, mcp? }` | `{ text, error? }` |
|
|
52
|
+
| `usage` | `{ session_ids }` | `{ usage: { <session_id>: TokenUsage[] } }` |
|
|
53
|
+
|
|
54
|
+
`mcp` is `{ name, url, api_key_env }`: the MCP server the CLI should use and the name of the environment variable that holds its API key. `check` must finish within 30 seconds and `usage` within 60 seconds; `run` is only bounded by openbee stopping the task.
|
|
55
|
+
|
|
56
|
+
## The Engine interface
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
interface Engine {
|
|
60
|
+
check(req: EngineRequest<Record<string, never>>): Promise<CheckResult>;
|
|
61
|
+
run(req: EngineRequest<RunParams>): Promise<RunResult>;
|
|
62
|
+
usage(req: EngineRequest<{ session_ids: string[] }>): Promise<Record<string, TokenUsage[]>>;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
interface CheckResult { version: string; path: string }
|
|
66
|
+
interface RunResult { text: string; error?: string }
|
|
67
|
+
interface TokenUsage {
|
|
68
|
+
model: string;
|
|
69
|
+
input_tokens: number;
|
|
70
|
+
output_tokens: number;
|
|
71
|
+
cache_creation_tokens: number;
|
|
72
|
+
cache_read_tokens: number;
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
`runEngine(engine)` reads the request, dispatches on `method` and writes the response. `usage` returns a map from session id to its token usage; `runEngine` wraps it as `{ "usage": ... }` for you.
|
|
77
|
+
|
|
78
|
+
## Minimal plugin
|
|
79
|
+
|
|
80
|
+
```js
|
|
81
|
+
import { runEngine, findCli, spawnCli, cliVersion } from "@theopenbee/engine-sdk";
|
|
82
|
+
|
|
83
|
+
runEngine({
|
|
84
|
+
async check(req) {
|
|
85
|
+
const path = findCli(req.config, "mycli");
|
|
86
|
+
return { version: await cliVersion(path), path };
|
|
87
|
+
},
|
|
88
|
+
|
|
89
|
+
async run(req) {
|
|
90
|
+
const { work_dir, prompt, extra_args, log_path } = req.params;
|
|
91
|
+
const command = findCli(req.config, "mycli");
|
|
92
|
+
let text = "";
|
|
93
|
+
const res = await spawnCli({
|
|
94
|
+
command,
|
|
95
|
+
args: ["--print", ...extra_args],
|
|
96
|
+
cwd: work_dir,
|
|
97
|
+
input: prompt,
|
|
98
|
+
logPath: log_path,
|
|
99
|
+
onStdoutLine(line) {
|
|
100
|
+
text += line + "\n";
|
|
101
|
+
return line;
|
|
102
|
+
},
|
|
103
|
+
});
|
|
104
|
+
if (res.code !== 0) {
|
|
105
|
+
return { text: text.trim(), error: res.stderrTail || `mycli exited with code ${res.code}` };
|
|
106
|
+
}
|
|
107
|
+
return { text: text.trim() };
|
|
108
|
+
},
|
|
109
|
+
|
|
110
|
+
async usage() {
|
|
111
|
+
return {};
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## Helpers
|
|
117
|
+
|
|
118
|
+
| Helper | Description |
|
|
119
|
+
|---|---|
|
|
120
|
+
| `findCli(config, name)` | Returns `config.path` when it is set and exists, otherwise searches `PATH` (honouring `PATHEXT` on Windows). Throws `<path> not found` or `<name> not found on PATH`. |
|
|
121
|
+
| `spawnCli(opts)` | Spawns the CLI in the plugin's process group, writes `input` to stdin and closes it, and appends stdout lines and stderr to `logPath` (created or truncated). `onStdoutLine` sees every stdout line before it is logged: return the text to log or `null` to drop it. Resolves with `{ code, signal, stderrTail }` where `stderrTail` is the last 4 KB of stderr. `opts.env` is merged over the plugin's environment; a key set to `undefined` is removed. |
|
|
122
|
+
| `cliVersion(path, args?)` | Runs `<path> --version` (or `args`) with a 10 second timeout and returns the trimmed first line. |
|
|
123
|
+
| `log.info/warn/error(msg)` | Writes a line to stderr. |
|
|
124
|
+
|
|
125
|
+
## Process rules
|
|
126
|
+
|
|
127
|
+
- **stdout carries only the response.** The SDK redirects `console.log`, `console.info` and `console.debug` to stderr as soon as `runEngine` starts, but never write to `process.stdout` yourself and do not let the CLI inherit your stdout.
|
|
128
|
+
- **Logs go to stderr.** Use `log.info/warn/error` or `console.error`; openbee collects the plugin's stderr.
|
|
129
|
+
- **Never spawn the CLI detached.** openbee starts the plugin as its own process group and kills the whole group when a task is stopped or times out. A detached child, a `setsid` wrapper or a daemonised helper escapes that and is left running. `spawnCli` never detaches.
|
|
130
|
+
- **Exit once you have answered.** `runEngine` exits with code 0 right after writing the response; a plugin that exits without a response, or non-zero, counts as failed.
|
|
131
|
+
- **Stay portable.** Use `node:` built-ins only so the plugin runs on Node 20+ and on Bun.
|
|
132
|
+
|
|
133
|
+
## Development
|
|
134
|
+
|
|
135
|
+
```sh
|
|
136
|
+
npm install
|
|
137
|
+
npm test
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
`npm install` also builds `dist/`; run `npm run build` after changing `src/`. The tests run the engine fixture in child `node` processes, and under Bun when it is installed (`bun` on `PATH` or `~/.openbee/runtime/bun-*/bun`).
|
|
141
|
+
|
|
142
|
+
## License
|
|
143
|
+
|
|
144
|
+
MIT
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export declare function findCli(config: Record<string, unknown>, name: string): string;
|
|
2
|
+
export declare function spawnCli(opts: {
|
|
3
|
+
command: string;
|
|
4
|
+
args: string[];
|
|
5
|
+
cwd: string;
|
|
6
|
+
env?: NodeJS.ProcessEnv;
|
|
7
|
+
input?: string;
|
|
8
|
+
logPath: string;
|
|
9
|
+
onStdoutLine?: (line: string) => string | null;
|
|
10
|
+
}): Promise<{
|
|
11
|
+
code: number | null;
|
|
12
|
+
signal: NodeJS.Signals | null;
|
|
13
|
+
stderrTail: string;
|
|
14
|
+
}>;
|
|
15
|
+
export declare function cliVersion(path: string, args?: string[]): Promise<string>;
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { execFile, spawn } from "node:child_process";
|
|
2
|
+
import { accessSync, constants, createWriteStream, mkdirSync, statSync } from "node:fs";
|
|
3
|
+
import { delimiter, dirname, extname, join } from "node:path";
|
|
4
|
+
import { StringDecoder } from "node:string_decoder";
|
|
5
|
+
import { log } from "./main.js";
|
|
6
|
+
const STDERR_TAIL_BYTES = 4096;
|
|
7
|
+
const VERSION_TIMEOUT_MS = 10_000;
|
|
8
|
+
function isFile(path) {
|
|
9
|
+
try {
|
|
10
|
+
return statSync(path).isFile();
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function isExecutable(path) {
|
|
17
|
+
if (!isFile(path))
|
|
18
|
+
return false;
|
|
19
|
+
if (process.platform === "win32")
|
|
20
|
+
return true;
|
|
21
|
+
try {
|
|
22
|
+
accessSync(path, constants.X_OK);
|
|
23
|
+
return true;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function candidateNames(name) {
|
|
30
|
+
if (process.platform !== "win32")
|
|
31
|
+
return [name];
|
|
32
|
+
const exts = (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
|
|
33
|
+
const own = extname(name).toLowerCase();
|
|
34
|
+
if (own && exts.some((ext) => ext.toLowerCase() === own))
|
|
35
|
+
return [name];
|
|
36
|
+
return exts.map((ext) => name + ext);
|
|
37
|
+
}
|
|
38
|
+
export function findCli(config, name) {
|
|
39
|
+
const configured = typeof config.path === "string" ? config.path.trim() : "";
|
|
40
|
+
if (configured) {
|
|
41
|
+
if (!isFile(configured))
|
|
42
|
+
throw new Error(`${configured} not found`);
|
|
43
|
+
return configured;
|
|
44
|
+
}
|
|
45
|
+
const dirs = (process.env.PATH ?? process.env.Path ?? "")
|
|
46
|
+
.split(delimiter)
|
|
47
|
+
.map((dir) => dir.replace(/^"(.*)"$/, "$1"))
|
|
48
|
+
.filter(Boolean);
|
|
49
|
+
const names = candidateNames(name);
|
|
50
|
+
for (const dir of dirs) {
|
|
51
|
+
for (const candidate of names) {
|
|
52
|
+
const full = join(dir, candidate);
|
|
53
|
+
if (isExecutable(full))
|
|
54
|
+
return full;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
throw new Error(`${name} not found on PATH`);
|
|
58
|
+
}
|
|
59
|
+
function lineSplitter(onLine) {
|
|
60
|
+
const decoder = new StringDecoder("utf8");
|
|
61
|
+
let pending = "";
|
|
62
|
+
const emit = (line) => onLine(line.endsWith("\r") ? line.slice(0, -1) : line);
|
|
63
|
+
return {
|
|
64
|
+
push(chunk) {
|
|
65
|
+
pending += decoder.write(chunk);
|
|
66
|
+
let start = 0;
|
|
67
|
+
for (let idx = pending.indexOf("\n", start); idx >= 0; idx = pending.indexOf("\n", start)) {
|
|
68
|
+
emit(pending.slice(start, idx));
|
|
69
|
+
start = idx + 1;
|
|
70
|
+
}
|
|
71
|
+
pending = pending.slice(start);
|
|
72
|
+
},
|
|
73
|
+
end() {
|
|
74
|
+
pending += decoder.end();
|
|
75
|
+
if (pending)
|
|
76
|
+
emit(pending);
|
|
77
|
+
pending = "";
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
function decodeTail(tail) {
|
|
82
|
+
let start = 0;
|
|
83
|
+
while (start < tail.length && (tail[start] & 0xc0) === 0x80)
|
|
84
|
+
start++;
|
|
85
|
+
return tail.subarray(start).toString("utf8");
|
|
86
|
+
}
|
|
87
|
+
export function spawnCli(opts) {
|
|
88
|
+
return new Promise((resolve, reject) => {
|
|
89
|
+
mkdirSync(dirname(opts.logPath), { recursive: true });
|
|
90
|
+
const logStream = createWriteStream(opts.logPath, { flags: "w" });
|
|
91
|
+
logStream.on("error", (err) => log.warn(`writing ${opts.logPath} failed: ${err.message}`));
|
|
92
|
+
const logClosed = new Promise((done) => logStream.once("close", () => done()));
|
|
93
|
+
const child = spawn(opts.command, opts.args, {
|
|
94
|
+
cwd: opts.cwd,
|
|
95
|
+
env: opts.env ? { ...process.env, ...opts.env } : process.env,
|
|
96
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
97
|
+
detached: false,
|
|
98
|
+
windowsHide: true,
|
|
99
|
+
});
|
|
100
|
+
let settled = false;
|
|
101
|
+
const stdoutLines = lineSplitter((line) => {
|
|
102
|
+
let out = line;
|
|
103
|
+
if (opts.onStdoutLine) {
|
|
104
|
+
try {
|
|
105
|
+
out = opts.onStdoutLine(line);
|
|
106
|
+
}
|
|
107
|
+
catch (err) {
|
|
108
|
+
log.warn(`onStdoutLine failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
if (out !== null)
|
|
112
|
+
logStream.write(out + "\n");
|
|
113
|
+
});
|
|
114
|
+
const stderrLines = lineSplitter((line) => {
|
|
115
|
+
logStream.write(line + "\n");
|
|
116
|
+
});
|
|
117
|
+
let tail = Buffer.alloc(0);
|
|
118
|
+
child.stdout.on("data", (chunk) => stdoutLines.push(chunk));
|
|
119
|
+
child.stderr.on("data", (chunk) => {
|
|
120
|
+
stderrLines.push(chunk);
|
|
121
|
+
const joined = Buffer.concat([tail, chunk]);
|
|
122
|
+
tail = Buffer.from(joined.subarray(Math.max(0, joined.length - STDERR_TAIL_BYTES)));
|
|
123
|
+
});
|
|
124
|
+
child.stdin.on("error", () => { });
|
|
125
|
+
child.stdout.on("error", () => { });
|
|
126
|
+
child.stderr.on("error", () => { });
|
|
127
|
+
child.on("error", (err) => {
|
|
128
|
+
if (settled)
|
|
129
|
+
return;
|
|
130
|
+
settled = true;
|
|
131
|
+
logStream.end();
|
|
132
|
+
void logClosed.then(() => reject(err));
|
|
133
|
+
});
|
|
134
|
+
child.on("close", (code, signal) => {
|
|
135
|
+
if (settled)
|
|
136
|
+
return;
|
|
137
|
+
settled = true;
|
|
138
|
+
stdoutLines.end();
|
|
139
|
+
stderrLines.end();
|
|
140
|
+
logStream.end();
|
|
141
|
+
void logClosed.then(() => resolve({ code, signal, stderrTail: decodeTail(tail) }));
|
|
142
|
+
});
|
|
143
|
+
child.stdin.end(opts.input);
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
function firstLine(text) {
|
|
147
|
+
return text.trim().split(/\r?\n/)[0]?.trim() ?? "";
|
|
148
|
+
}
|
|
149
|
+
export async function cliVersion(path, args = ["--version"]) {
|
|
150
|
+
const command = [path, ...args].join(" ");
|
|
151
|
+
return new Promise((resolve, reject) => {
|
|
152
|
+
execFile(path, args, { timeout: VERSION_TIMEOUT_MS, killSignal: "SIGKILL", windowsHide: true, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
|
|
153
|
+
if (err) {
|
|
154
|
+
if (err.killed) {
|
|
155
|
+
reject(new Error(`${command} timed out after ${VERSION_TIMEOUT_MS / 1000}s`));
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
const detail = firstLine(String(stderr));
|
|
159
|
+
if (detail && typeof err.code === "number") {
|
|
160
|
+
reject(new Error(`${command} failed: ${detail}`));
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
reject(err);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
resolve(firstLine(String(stdout)) || firstLine(String(stderr)));
|
|
167
|
+
});
|
|
168
|
+
});
|
|
169
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/main.d.ts
ADDED
package/dist/main.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { format } from "node:util";
|
|
2
|
+
const PROTOCOL_VERSION = 1;
|
|
3
|
+
function writeStderr(line) {
|
|
4
|
+
process.stderr.write(line + "\n");
|
|
5
|
+
}
|
|
6
|
+
export const log = {
|
|
7
|
+
info(msg) {
|
|
8
|
+
writeStderr(`[info] ${msg}`);
|
|
9
|
+
},
|
|
10
|
+
warn(msg) {
|
|
11
|
+
writeStderr(`[warn] ${msg}`);
|
|
12
|
+
},
|
|
13
|
+
error(msg) {
|
|
14
|
+
writeStderr(`[error] ${msg}`);
|
|
15
|
+
},
|
|
16
|
+
};
|
|
17
|
+
function redirectConsole() {
|
|
18
|
+
const toStderr = (...args) => {
|
|
19
|
+
writeStderr(format(...args));
|
|
20
|
+
};
|
|
21
|
+
console.log = toStderr;
|
|
22
|
+
console.info = toStderr;
|
|
23
|
+
console.debug = toStderr;
|
|
24
|
+
}
|
|
25
|
+
function installCrashHandlers() {
|
|
26
|
+
const crash = (err) => {
|
|
27
|
+
writeStderr(`fatal: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`);
|
|
28
|
+
process.exit(1);
|
|
29
|
+
};
|
|
30
|
+
process.on("uncaughtException", crash);
|
|
31
|
+
process.on("unhandledRejection", crash);
|
|
32
|
+
}
|
|
33
|
+
function errorMessage(err) {
|
|
34
|
+
return err instanceof Error ? err.message : String(err);
|
|
35
|
+
}
|
|
36
|
+
async function readStdin() {
|
|
37
|
+
const chunks = [];
|
|
38
|
+
for await (const chunk of process.stdin) {
|
|
39
|
+
chunks.push(typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk);
|
|
40
|
+
}
|
|
41
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
42
|
+
}
|
|
43
|
+
function parseRequest(raw) {
|
|
44
|
+
let parsed;
|
|
45
|
+
try {
|
|
46
|
+
parsed = JSON.parse(raw);
|
|
47
|
+
}
|
|
48
|
+
catch (err) {
|
|
49
|
+
throw new Error(`invalid request: ${errorMessage(err)}`);
|
|
50
|
+
}
|
|
51
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
52
|
+
throw new Error("invalid request: expected a JSON object");
|
|
53
|
+
}
|
|
54
|
+
const req = parsed;
|
|
55
|
+
if (req.protocol_version !== PROTOCOL_VERSION) {
|
|
56
|
+
throw new Error(`unsupported protocol version ${String(req.protocol_version)}`);
|
|
57
|
+
}
|
|
58
|
+
return req;
|
|
59
|
+
}
|
|
60
|
+
async function dispatch(engine, req) {
|
|
61
|
+
switch (req.method) {
|
|
62
|
+
case "check":
|
|
63
|
+
return engine.check(req);
|
|
64
|
+
case "run":
|
|
65
|
+
return engine.run(req);
|
|
66
|
+
case "usage":
|
|
67
|
+
return { usage: await engine.usage(req) };
|
|
68
|
+
default:
|
|
69
|
+
throw new Error(`unknown method "${String(req.method)}"`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async function handle(engine) {
|
|
73
|
+
try {
|
|
74
|
+
const req = parseRequest(await readStdin());
|
|
75
|
+
const result = await dispatch(engine, req);
|
|
76
|
+
return JSON.stringify({ result: result ?? {} });
|
|
77
|
+
}
|
|
78
|
+
catch (err) {
|
|
79
|
+
return JSON.stringify({ error: { message: errorMessage(err) } });
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
export async function runEngine(engine) {
|
|
83
|
+
redirectConsole();
|
|
84
|
+
installCrashHandlers();
|
|
85
|
+
const line = await handle(engine);
|
|
86
|
+
await new Promise((resolve) => {
|
|
87
|
+
process.stdout.write(line + "\n", () => resolve());
|
|
88
|
+
});
|
|
89
|
+
process.exit(0);
|
|
90
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export interface EngineRequest<P> {
|
|
2
|
+
protocol_version: number;
|
|
3
|
+
method: "run" | "check" | "usage";
|
|
4
|
+
openbee_version: string;
|
|
5
|
+
engine_id: string;
|
|
6
|
+
language: string;
|
|
7
|
+
config: Record<string, unknown>;
|
|
8
|
+
data_dir: string;
|
|
9
|
+
state_dir: string;
|
|
10
|
+
params: P;
|
|
11
|
+
}
|
|
12
|
+
export interface RunParams {
|
|
13
|
+
role: "bee" | "worker";
|
|
14
|
+
work_dir: string;
|
|
15
|
+
prompt: string;
|
|
16
|
+
session_id: string;
|
|
17
|
+
resume: boolean;
|
|
18
|
+
extra_args: string[];
|
|
19
|
+
log_path: string;
|
|
20
|
+
mcp?: {
|
|
21
|
+
name: string;
|
|
22
|
+
url: string;
|
|
23
|
+
api_key_env: string;
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export interface RunResult {
|
|
27
|
+
text: string;
|
|
28
|
+
error?: string;
|
|
29
|
+
}
|
|
30
|
+
export interface CheckResult {
|
|
31
|
+
version: string;
|
|
32
|
+
path: string;
|
|
33
|
+
}
|
|
34
|
+
export interface TokenUsage {
|
|
35
|
+
model: string;
|
|
36
|
+
input_tokens: number;
|
|
37
|
+
output_tokens: number;
|
|
38
|
+
cache_creation_tokens: number;
|
|
39
|
+
cache_read_tokens: number;
|
|
40
|
+
}
|
|
41
|
+
export interface Engine {
|
|
42
|
+
check(req: EngineRequest<Record<string, never>>): Promise<CheckResult>;
|
|
43
|
+
run(req: EngineRequest<RunParams>): Promise<RunResult>;
|
|
44
|
+
usage(req: EngineRequest<{
|
|
45
|
+
session_ids: string[];
|
|
46
|
+
}>): Promise<Record<string, TokenUsage[]>>;
|
|
47
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theopenbee/engine-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "SDK for building openbee engine plugins",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/theopenbee/engine-sdk.git"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/theopenbee/engine-sdk#readme",
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/theopenbee/engine-sdk/issues"
|
|
13
|
+
},
|
|
14
|
+
"type": "module",
|
|
15
|
+
"main": "./dist/index.js",
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"default": "./dist/index.js"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist"
|
|
25
|
+
],
|
|
26
|
+
"engines": {
|
|
27
|
+
"node": ">=20"
|
|
28
|
+
},
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public",
|
|
31
|
+
"registry": "https://registry.npmjs.org/"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "tsc -p tsconfig.json",
|
|
35
|
+
"test": "node --test test/*.test.mjs",
|
|
36
|
+
"prepare": "npm run build"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@types/node": "^22.10.0",
|
|
40
|
+
"typescript": "^5.7.0"
|
|
41
|
+
}
|
|
42
|
+
}
|