@tbrandenburg/opencode-a2a-lite 0.0.0-stage → 0.2.5
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 +173 -2
- package/dist/package.json +57 -0
- package/dist/src/acp-client.js +287 -0
- package/dist/src/cli-options.js +56 -0
- package/dist/src/cli.js +35 -0
- package/dist/src/executor.js +170 -0
- package/dist/src/identity.js +33 -0
- package/dist/src/opencode-version.js +14 -0
- package/dist/src/request-handler.js +55 -0
- package/dist/src/server.js +201 -0
- package/dist/src/startup-error.js +22 -0
- package/package.json +55 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tom Brandenburg
|
|
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,174 @@
|
|
|
1
|
-
#
|
|
1
|
+
# opencode-a2a-lite
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> Expose OpenCode through A2A, with ACP doing the heavy lifting.
|
|
4
|
+
|
|
5
|
+
[](https://github.com/tbrandenburg/opencode-a2a-lite/actions/workflows/ci.yml)
|
|
6
|
+
[](https://github.com/tbrandenburg/opencode-a2a-lite/releases/latest)
|
|
7
|
+
[](LICENSE)
|
|
8
|
+

|
|
9
|
+

|
|
10
|
+
|
|
11
|
+
A small OpenCode ACP → A2A 1.0 gateway for trusted Linux workspaces: point any A2A
|
|
12
|
+
client at it and it drives OpenCode. It uses the official A2A and ACP SDKs: OpenCode
|
|
13
|
+
owns coding-session behavior, the gateway translates plain-text tasks, streamed output
|
|
14
|
+
and context continuity.
|
|
15
|
+
|
|
16
|
+
```text
|
|
17
|
+
A2A client ──HTTP/SSE──▶ opencode-a2a-lite ──ACP (stdio)──▶ opencode ──▶ trusted workspace
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
**Not included:** HTTP OpenCode adapter, database, orchestrator, retries, sandbox.
|
|
21
|
+
|
|
22
|
+
> [!WARNING]
|
|
23
|
+
> The gateway has no authentication (it binds to `127.0.0.1`) and must **never** be
|
|
24
|
+
> exposed through a public proxy. It inherits OpenCode configuration, tools, plugins and MCP. Rejecting ACP
|
|
25
|
+
> permission requests is **not** an OS sandbox, and cancellation does not roll back work.
|
|
26
|
+
|
|
27
|
+
## Contents
|
|
28
|
+
|
|
29
|
+
- [Quick start](#quick-start)
|
|
30
|
+
- [Requirements](#requirements)
|
|
31
|
+
- [Usage](#usage)
|
|
32
|
+
- [Behavior and limitations](#behavior-and-limitations)
|
|
33
|
+
- [Development](#development)
|
|
34
|
+
- [Multi-agent coordination](#multi-agent-coordination)
|
|
35
|
+
- [Contributing and security](#contributing-and-security)
|
|
36
|
+
|
|
37
|
+
## Quick start
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
make install # frozen Bun lockfile
|
|
41
|
+
make check # format, lint, typecheck, deterministic tests, build
|
|
42
|
+
bun src/cli.ts --workspace /absolute/path/to/trusted/workspace --port 0
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Wait for a JSON stdout record such as `{"ready":true,"url":"http://127.0.0.1:.../"}`,
|
|
46
|
+
then in a second terminal use the **actual** URL (default port 41241):
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
a2a card get http://127.0.0.1:41241
|
|
50
|
+
a2a send -a http://127.0.0.1:41241 "Reply with a short greeting." --stream
|
|
51
|
+
a2a send -a http://127.0.0.1:41241 --context-id <returned-context-id> "Follow up"
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
The server runs in the foreground and terminates its owned ACP process group on
|
|
55
|
+
SIGINT/SIGTERM.
|
|
56
|
+
|
|
57
|
+
## Requirements
|
|
58
|
+
|
|
59
|
+
- Linux, **Bun 1.4.4**, and stable **`opencode` v2.2.7 or newer** on `PATH`
|
|
60
|
+
(live acceptance recorded on 2.2.7).
|
|
61
|
+
- An explicitly trusted workspace and reviewed OpenCode provider, model, tools,
|
|
62
|
+
plugins, MCP servers and configuration.
|
|
63
|
+
- The separate [official A2A CLI](https://github.com/a2aproject/a2a-cli)
|
|
64
|
+
(tested with 0.3.1) to talk to the running gateway.
|
|
65
|
+
|
|
66
|
+
Runtime security and compatibility evidence is tracked for
|
|
67
|
+
[Bun](docs/bun-runtime-security.md) and [OpenCode](docs/opencode-runtime-upgrade.md).
|
|
68
|
+
Standalone Bun and OpenCode's embedded runtime are separate upgrade boundaries;
|
|
69
|
+
historical acceptance results do not establish compatibility of a new pair.
|
|
70
|
+
|
|
71
|
+
## Usage
|
|
72
|
+
|
|
73
|
+
```text
|
|
74
|
+
opencode-a2a-lite --workspace <path> [--port <0..65535>]
|
|
75
|
+
opencode-a2a-lite --help | --version
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
| Option / variable | Meaning |
|
|
79
|
+
| ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
|
|
80
|
+
| `--workspace`, `A2A_WORKSPACE` | Explicitly trusted directory. The env var must be an **absolute** path. No implicit current-directory trust. |
|
|
81
|
+
| `--port`, `A2A_PORT` | Listen port (bound to `127.0.0.1`). Default 41241; `0` requests an OS-assigned port. Flags override env. |
|
|
82
|
+
| `A2A_NAME` (128), `A2A_DESCRIPTION` (1024), `A2A_TAGS` (16 tags, 64 chars each) | Agent card metadata only, **not** access control. Nonblank, control-free. |
|
|
83
|
+
|
|
84
|
+
Run the compiled server with `A2A_WORKSPACE=/absolute/trusted/path make run`;
|
|
85
|
+
use `make dev` for development.
|
|
86
|
+
|
|
87
|
+
### Package distribution
|
|
88
|
+
|
|
89
|
+
`@tbrandenburg/opencode-a2a-lite` is released on GitHub (see the release badge above).
|
|
90
|
+
**npm registry publication has not been verified**; do not assume these work until
|
|
91
|
+
the scope/registry is checked:
|
|
92
|
+
|
|
93
|
+
```sh
|
|
94
|
+
bunx @tbrandenburg/opencode-a2a-lite --workspace .
|
|
95
|
+
npx --yes @tbrandenburg/opencode-a2a-lite --workspace .
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Both runners still require Bun. `make package-smoke` tests an installed tarball,
|
|
99
|
+
**not** registry publication. See [distribution and release policy](docs/distribution.md).
|
|
100
|
+
|
|
101
|
+
## Behavior and limitations
|
|
102
|
+
|
|
103
|
+
The official A2A SDK owns HTTP JSON-RPC, Agent Cards, task persistence and SSE.
|
|
104
|
+
The executor accepts nonempty plain text only; multiple text parts are joined with
|
|
105
|
+
newlines. A new conversation omits `contextId`; follow-ups pass the returned
|
|
106
|
+
`contextId` **without an old task ID**. Each turn creates a new A2A task while
|
|
107
|
+
reusing the ACP session for that context.
|
|
108
|
+
|
|
109
|
+
- Exactly one prompt is active globally; another request fails busy without a queue.
|
|
110
|
+
- Contexts/tasks live in memory. Default context capacity is 100; restarting clears
|
|
111
|
+
them. No durable recovery, multi-tenancy or parallel model execution.
|
|
112
|
+
- Only ACP `end_turn` means completed; confirmed `cancelled` means canceled.
|
|
113
|
+
Errors and other stop reasons fail the task without publishing private diagnostics.
|
|
114
|
+
- Permission requests are rejected/canceled, not silently approved.
|
|
115
|
+
- Defaults: 30-second startup/session allocation, 120-second prompt, 5-second
|
|
116
|
+
cancellation and 5-second ACP shutdown. Failure retires the unhealthy bridge.
|
|
117
|
+
- Streaming sends stable artifact IDs and ordered append events. Task states are
|
|
118
|
+
SDK-owned; the small [request-handler adapter](src/request-handler.ts) is retained
|
|
119
|
+
for a documented upstream cancellation persistence defect.
|
|
120
|
+
|
|
121
|
+
See [architecture](docs/architecture.md), [pitfalls](docs/pitfalls.md) and
|
|
122
|
+
[SDK cancellation removal criteria](docs/sdk-cancellation.md).
|
|
123
|
+
Full A2A TCK certification, interactive approval, rich media, push notifications
|
|
124
|
+
and runtime-selected workspaces are not claimed.
|
|
125
|
+
|
|
126
|
+
## Development
|
|
127
|
+
|
|
128
|
+
| Command | Purpose |
|
|
129
|
+
| ---------------------------------------------------------------------- | -------------------------------------------------------------------- |
|
|
130
|
+
| `make check` | Formatting, lint, strict types, deterministic regressions, build |
|
|
131
|
+
| `make package-smoke` | Installed-tarball and subprocess lifecycle checks, without provider |
|
|
132
|
+
| `A2ABRIDGE_BIN=/absolute/path/to/verified/a2abridge make interop-test` | Pinned, provider-free guarded MCP/bridge/gateway acceptance |
|
|
133
|
+
| `make demo` | Isolated official A2A CLI two-turn smoke (**live, billable**) |
|
|
134
|
+
| `make e2e` | Production live-model acceptance (**live, billable**) |
|
|
135
|
+
| `TCK_DIR=/absolute/path/to/pinned/a2a-tck make e2e-tck` | Applicable external A2A TCK checks |
|
|
136
|
+
| `make release BUMP=patch` | Check, commit and push tag for npm publication and a GitHub release. |
|
|
137
|
+
| `make clean` | Remove build, coverage and test results |
|
|
138
|
+
|
|
139
|
+
CI checks deterministic tests, the provider-free team launcher fixtures, installed
|
|
140
|
+
packaging and the checksummed provider-free MCP bridge. Live demo/E2E are explicit manual commands requiring a provider key,
|
|
141
|
+
OpenCode and the official A2A CLI; `make demo` also needs `jq` and GNU `timeout`.
|
|
142
|
+
For the exact live evidence/limitations see [acceptance](docs/acceptance.md).
|
|
143
|
+
For quality measurement see [quality baseline](docs/quality-baseline.md).
|
|
144
|
+
|
|
145
|
+
## Multi-agent coordination
|
|
146
|
+
|
|
147
|
+
The **gateway does not orchestrate other agents**. Optional guarded MCP interoperability
|
|
148
|
+
helpers and their independent gate live in [`interop/`](interop/README.md).
|
|
149
|
+
The experimental [team examples](examples/teams/README.md) provide a local roster
|
|
150
|
+
launcher; read their supervision and cleanup limitations before use.
|
|
151
|
+
For a manually owned model-issued MCP → A2A flow use the
|
|
152
|
+
[one-worker recipe](docs/manual-one-worker.md), or the
|
|
153
|
+
[explicit two-worker pipeline recipe](docs/manual-two-worker-pipeline.md) and
|
|
154
|
+
[passive supervision](docs/passive-mcp-supervision.md). The
|
|
155
|
+
[portable OpenCode multi-agent skill](.opencode/skills/multi-a2a-agent/SKILL.md)
|
|
156
|
+
includes eight topology procedures; the
|
|
157
|
+
[topology study pages](docs/topology-studies/topology-pipeline.md) contain scoped
|
|
158
|
+
observations, not proof of general reliability.
|
|
159
|
+
|
|
160
|
+
The managed network/topology research lab has been **retired, not fixed**. Its
|
|
161
|
+
original failures and unverified outcomes are linked in the
|
|
162
|
+
[historical research index](docs/history.md). Do not treat provider-free passing
|
|
163
|
+
checks as evidence of real-model outcome quality.
|
|
164
|
+
|
|
165
|
+
## Contributing and security
|
|
166
|
+
|
|
167
|
+
Review [AGENTS.md](AGENTS.md) for repository boundaries and safe test practices.
|
|
168
|
+
Run `make check` and focused tests before proposing changes. Changes to streaming,
|
|
169
|
+
cancellation, permissions or lifecycle also require the relevant authorized live
|
|
170
|
+
acceptance evidence. Do not publish credentials, raw prompts, private reasoning or
|
|
171
|
+
provider diagnostics in issues, CI logs or PRs. Report vulnerabilities through
|
|
172
|
+
[GitHub security reporting](https://github.com/tbrandenburg/opencode-a2a-lite/security).
|
|
173
|
+
|
|
174
|
+
[MIT License](LICENSE).
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tbrandenburg/opencode-a2a-lite",
|
|
3
|
+
"version": "0.2.5",
|
|
4
|
+
"description": "OpenCode ACP to A2A gateway for trusted workspaces",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/tbrandenburg/opencode-a2a-lite.git"
|
|
9
|
+
},
|
|
10
|
+
"bin": {
|
|
11
|
+
"opencode-a2a-lite": "dist/src/cli.js"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"dist/src/*.js",
|
|
15
|
+
"dist/package.json",
|
|
16
|
+
"README.md",
|
|
17
|
+
"LICENSE"
|
|
18
|
+
],
|
|
19
|
+
"os": [
|
|
20
|
+
"linux"
|
|
21
|
+
],
|
|
22
|
+
"type": "module",
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"scripts": {
|
|
27
|
+
"dev": "bun --watch src/server.ts",
|
|
28
|
+
"start": "bun dist/src/server.js",
|
|
29
|
+
"build": "tsc --noEmit false --outDir dist --rootDir .",
|
|
30
|
+
"prepack": "rm -rf dist/src && bun run build && chmod +x dist/src/cli.js",
|
|
31
|
+
"package-smoke": "bun scripts/package-smoke.ts",
|
|
32
|
+
"fmt": "oxfmt",
|
|
33
|
+
"fmt-check": "oxfmt --check",
|
|
34
|
+
"lint": "oxlint .",
|
|
35
|
+
"typecheck": "tsc --noEmit",
|
|
36
|
+
"test": "bun test ./tests"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@a2a-js/sdk": "1.3.0",
|
|
40
|
+
"@agentclientprotocol/sdk": "2.0.2",
|
|
41
|
+
"express": "5.3.0"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@modelcontextprotocol/sdk": "1.29.0",
|
|
45
|
+
"@types/bun": "1.4.4",
|
|
46
|
+
"@types/express": "5.0.6",
|
|
47
|
+
"@types/node": "24.10.0",
|
|
48
|
+
"oxfmt": "0.74.0",
|
|
49
|
+
"oxlint": "1.89.0",
|
|
50
|
+
"typescript": "7.0.2"
|
|
51
|
+
},
|
|
52
|
+
"engines": {
|
|
53
|
+
"bun": "1.4.4",
|
|
54
|
+
"node": ">=22"
|
|
55
|
+
},
|
|
56
|
+
"packageManager": "bun@1.4.4"
|
|
57
|
+
}
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { isAbsolute } from "node:path";
|
|
3
|
+
import { Readable, Writable } from "node:stream";
|
|
4
|
+
import * as acp from "@agentclientprotocol/sdk";
|
|
5
|
+
import manifest from "../package.json" with { type: "json" };
|
|
6
|
+
import { supportedOpenCode } from "./opencode-version.js";
|
|
7
|
+
import { StartupError } from "./startup-error.js";
|
|
8
|
+
export function createAcpBridge(options) {
|
|
9
|
+
if (!isAbsolute(options.cwd))
|
|
10
|
+
throw new Error("ACP workspace must be absolute");
|
|
11
|
+
const cwd = options.cwd;
|
|
12
|
+
const executable = options.executable ?? "opencode";
|
|
13
|
+
const args = [...(options.args ?? ["acp"])];
|
|
14
|
+
const env = { ...(options.env ?? process.env) };
|
|
15
|
+
const startup = options.startupTimeoutMs ?? 30_000;
|
|
16
|
+
const promptTimeout = options.promptTimeoutMs ?? 120_000;
|
|
17
|
+
const cancelTimeout = options.cancelTimeoutMs ?? 5_000;
|
|
18
|
+
const closeTimeout = options.closeTimeoutMs ?? 5_000;
|
|
19
|
+
if ([startup, promptTimeout, cancelTimeout, closeTimeout].some((ms) => !Number.isSafeInteger(ms) || ms < 30 || ms > 2_147_483_647))
|
|
20
|
+
throw new Error("ACP timeouts must be integers between 30 and 2147483647ms");
|
|
21
|
+
if (process.platform === "win32")
|
|
22
|
+
throw new Error("ACP process ownership requires POSIX");
|
|
23
|
+
const failure = new AbortController();
|
|
24
|
+
const sessions = new Set();
|
|
25
|
+
let child;
|
|
26
|
+
let connection;
|
|
27
|
+
let starting;
|
|
28
|
+
let closing;
|
|
29
|
+
let ready = false;
|
|
30
|
+
let stopping = false;
|
|
31
|
+
let turn;
|
|
32
|
+
function fail(message) {
|
|
33
|
+
if (failure.signal.aborted)
|
|
34
|
+
return;
|
|
35
|
+
failure.abort(message instanceof StartupError ? message : new Error(message));
|
|
36
|
+
ready = false;
|
|
37
|
+
connection?.close();
|
|
38
|
+
// Retain the cleanup result for close(); request errors never contain peer diagnostics.
|
|
39
|
+
void close().catch(() => undefined);
|
|
40
|
+
}
|
|
41
|
+
function bounded(operation, ms, label) {
|
|
42
|
+
if (failure.signal.aborted)
|
|
43
|
+
return Promise.reject(failure.signal.reason);
|
|
44
|
+
return new Promise((resolve, reject) => {
|
|
45
|
+
const timer = setTimeout(() => fail(`ACP ${label} timed out`), ms);
|
|
46
|
+
const cleanup = () => {
|
|
47
|
+
clearTimeout(timer);
|
|
48
|
+
failure.signal.removeEventListener("abort", abort);
|
|
49
|
+
};
|
|
50
|
+
const abort = () => {
|
|
51
|
+
cleanup();
|
|
52
|
+
reject(failure.signal.reason);
|
|
53
|
+
};
|
|
54
|
+
failure.signal.addEventListener("abort", abort, { once: true });
|
|
55
|
+
Promise.resolve()
|
|
56
|
+
.then(() => {
|
|
57
|
+
if (failure.signal.aborted)
|
|
58
|
+
throw failure.signal.reason;
|
|
59
|
+
return operation();
|
|
60
|
+
})
|
|
61
|
+
.then((result) => {
|
|
62
|
+
cleanup();
|
|
63
|
+
resolve(result);
|
|
64
|
+
}, (error) => {
|
|
65
|
+
cleanup();
|
|
66
|
+
fail(error instanceof StartupError ? error : `ACP ${label} failed`);
|
|
67
|
+
reject(failure.signal.reason);
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
function requireConnection(sessionId) {
|
|
72
|
+
if (!ready || !connection || failure.signal.aborted || stopping)
|
|
73
|
+
throw new Error("ACP bridge unavailable");
|
|
74
|
+
if (sessionId !== undefined && !sessions.has(sessionId))
|
|
75
|
+
throw new Error("Unknown ACP session");
|
|
76
|
+
return connection;
|
|
77
|
+
}
|
|
78
|
+
function start() {
|
|
79
|
+
if (failure.signal.aborted || stopping)
|
|
80
|
+
return Promise.reject(new Error("ACP bridge unavailable"));
|
|
81
|
+
if (starting)
|
|
82
|
+
return starting;
|
|
83
|
+
starting = bounded(async () => {
|
|
84
|
+
// Probe the executable itself, not configuration or the ACP protocol version.
|
|
85
|
+
child = spawn(executable, [...(options.versionArgs ?? ["--version"])], {
|
|
86
|
+
cwd,
|
|
87
|
+
env,
|
|
88
|
+
detached: true,
|
|
89
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
90
|
+
});
|
|
91
|
+
const probe = child;
|
|
92
|
+
probe.stderr.resume();
|
|
93
|
+
probe.stdin.end();
|
|
94
|
+
const version = await new Promise((resolve, reject) => {
|
|
95
|
+
let output = "";
|
|
96
|
+
probe.stdout.on("data", (data) => {
|
|
97
|
+
if (output.length + data.length > 256) {
|
|
98
|
+
fail("ACP executable version invalid");
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
output += data.toString();
|
|
102
|
+
});
|
|
103
|
+
probe.once("error", () => reject(new StartupError("executable")));
|
|
104
|
+
probe.once("close", (code) => code === 0 ? resolve(output.trim()) : reject(new StartupError("executable")));
|
|
105
|
+
});
|
|
106
|
+
if (!supportedOpenCode(version))
|
|
107
|
+
throw new StartupError("version");
|
|
108
|
+
if (failure.signal.aborted || stopping)
|
|
109
|
+
throw new Error("ACP bridge closed");
|
|
110
|
+
if (signalGroup(0))
|
|
111
|
+
throw new Error("ACP executable left owned descendants");
|
|
112
|
+
child = spawn(executable, args, {
|
|
113
|
+
cwd,
|
|
114
|
+
env,
|
|
115
|
+
detached: true,
|
|
116
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
117
|
+
});
|
|
118
|
+
child.once("error", () => fail("ACP process failed"));
|
|
119
|
+
child.once("exit", () => fail("ACP process exited"));
|
|
120
|
+
child.stderr.resume();
|
|
121
|
+
const client = acp.client({ name: "opencode-a2a-lite" });
|
|
122
|
+
client.onRequest(acp.methods.client.session.requestPermission, async (request) => {
|
|
123
|
+
if (stopping ||
|
|
124
|
+
failure.signal.aborted ||
|
|
125
|
+
!turn ||
|
|
126
|
+
turn.settled ||
|
|
127
|
+
turn.cancelled ||
|
|
128
|
+
request.params.sessionId !== turn.sessionId)
|
|
129
|
+
return { outcome: { outcome: "cancelled" } };
|
|
130
|
+
const reject = request.params.options.find((option) => option.kind === "reject_once" || option.kind === "reject_always");
|
|
131
|
+
return {
|
|
132
|
+
outcome: reject
|
|
133
|
+
? { outcome: "selected", optionId: reject.optionId }
|
|
134
|
+
: { outcome: "cancelled" },
|
|
135
|
+
};
|
|
136
|
+
});
|
|
137
|
+
client.onNotification(acp.methods.client.session.update, (notification) => {
|
|
138
|
+
const update = notification.params.update;
|
|
139
|
+
if (!turn ||
|
|
140
|
+
turn.settled ||
|
|
141
|
+
failure.signal.aborted ||
|
|
142
|
+
notification.params.sessionId !== turn.sessionId)
|
|
143
|
+
return;
|
|
144
|
+
if (notification.params._meta?.["opencode/child-session"] !== undefined ||
|
|
145
|
+
update._meta?.["opencode/child-session"] !== undefined)
|
|
146
|
+
return;
|
|
147
|
+
if (update.sessionUpdate !== "agent_message_chunk" || update.content.type !== "text")
|
|
148
|
+
return;
|
|
149
|
+
if (update.content._meta?.["opencode/child-session"] !== undefined)
|
|
150
|
+
return;
|
|
151
|
+
try {
|
|
152
|
+
turn.onText(update.content.text);
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
fail("ACP text callback failed");
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
connection = client.connect(acp.ndJsonStream(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout)));
|
|
159
|
+
connection.signal.addEventListener("abort", () => fail("ACP connection closed"), {
|
|
160
|
+
once: true,
|
|
161
|
+
});
|
|
162
|
+
void connection.closed.then(() => fail("ACP connection closed"));
|
|
163
|
+
const response = await connection.agent.request(acp.methods.agent.initialize, {
|
|
164
|
+
protocolVersion: 1,
|
|
165
|
+
clientCapabilities: {},
|
|
166
|
+
clientInfo: { name: "opencode-a2a-lite", version: manifest.version },
|
|
167
|
+
});
|
|
168
|
+
if (response.protocolVersion !== 1)
|
|
169
|
+
throw new Error("Unsupported ACP version");
|
|
170
|
+
ready = true;
|
|
171
|
+
}, startup, "startup");
|
|
172
|
+
return starting;
|
|
173
|
+
}
|
|
174
|
+
async function newSession() {
|
|
175
|
+
const current = requireConnection();
|
|
176
|
+
const response = await bounded(() => current.agent.request(acp.methods.agent.session.new, { cwd, mcpServers: [] }), startup, "session creation");
|
|
177
|
+
if (typeof response.sessionId !== "string" ||
|
|
178
|
+
!response.sessionId ||
|
|
179
|
+
sessions.has(response.sessionId)) {
|
|
180
|
+
fail("ACP invalid session");
|
|
181
|
+
throw failure.signal.reason;
|
|
182
|
+
}
|
|
183
|
+
sessions.add(response.sessionId);
|
|
184
|
+
return response;
|
|
185
|
+
}
|
|
186
|
+
async function prompt(sessionId, text, onText) {
|
|
187
|
+
const current = requireConnection(sessionId);
|
|
188
|
+
if (turn)
|
|
189
|
+
throw new Error("ACP prompt in progress");
|
|
190
|
+
const active = {
|
|
191
|
+
sessionId,
|
|
192
|
+
onText,
|
|
193
|
+
cancelled: false,
|
|
194
|
+
settled: false,
|
|
195
|
+
cancellation: undefined,
|
|
196
|
+
completion: undefined,
|
|
197
|
+
};
|
|
198
|
+
turn = active;
|
|
199
|
+
active.completion = bounded(() => current.agent.request(acp.methods.agent.session.prompt, {
|
|
200
|
+
sessionId,
|
|
201
|
+
prompt: [{ type: "text", text }],
|
|
202
|
+
}), promptTimeout, "prompt");
|
|
203
|
+
try {
|
|
204
|
+
return await active.completion;
|
|
205
|
+
}
|
|
206
|
+
finally {
|
|
207
|
+
active.settled = true;
|
|
208
|
+
// A late cancel write must settle before another prompt can acquire this session.
|
|
209
|
+
await active.cancellation;
|
|
210
|
+
if (turn === active)
|
|
211
|
+
turn = undefined;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
async function cancel(sessionId) {
|
|
215
|
+
if (!sessions.has(sessionId))
|
|
216
|
+
throw new Error("Unknown ACP session");
|
|
217
|
+
if (!connection || !ready || failure.signal.aborted)
|
|
218
|
+
throw new Error("ACP bridge unavailable");
|
|
219
|
+
if (!turn || turn.settled || turn.sessionId !== sessionId)
|
|
220
|
+
return;
|
|
221
|
+
const current = connection;
|
|
222
|
+
const active = turn;
|
|
223
|
+
if (active.cancellation)
|
|
224
|
+
return active.cancellation;
|
|
225
|
+
active.cancelled = true;
|
|
226
|
+
active.cancellation = bounded(async () => {
|
|
227
|
+
await current.agent.notify(acp.methods.agent.session.cancel, { sessionId });
|
|
228
|
+
await active.completion;
|
|
229
|
+
}, cancelTimeout, "cancel");
|
|
230
|
+
return active.cancellation;
|
|
231
|
+
}
|
|
232
|
+
function signalGroup(signal) {
|
|
233
|
+
if (!child?.pid)
|
|
234
|
+
return false;
|
|
235
|
+
try {
|
|
236
|
+
process.kill(-child.pid, signal);
|
|
237
|
+
return true;
|
|
238
|
+
}
|
|
239
|
+
catch (error) {
|
|
240
|
+
if (error instanceof Error && "code" in error && error.code === "ESRCH")
|
|
241
|
+
return false;
|
|
242
|
+
throw new Error("ACP owned process cleanup failed");
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
async function stopped(ms) {
|
|
246
|
+
const deadline = Date.now() + ms;
|
|
247
|
+
while (signalGroup(0)) {
|
|
248
|
+
if (Date.now() >= deadline)
|
|
249
|
+
return false;
|
|
250
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(10, deadline - Date.now())));
|
|
251
|
+
}
|
|
252
|
+
return true;
|
|
253
|
+
}
|
|
254
|
+
function close() {
|
|
255
|
+
if (closing)
|
|
256
|
+
return closing;
|
|
257
|
+
stopping = true;
|
|
258
|
+
closing = Promise.resolve().then(async () => {
|
|
259
|
+
if (!failure.signal.aborted && turn && !turn.settled) {
|
|
260
|
+
// cancel() is bounded and retires the bridge on failure; cleanup still follows.
|
|
261
|
+
await cancel(turn.sessionId).catch(() => undefined);
|
|
262
|
+
}
|
|
263
|
+
if (!failure.signal.aborted)
|
|
264
|
+
failure.abort(new Error("ACP bridge closed"));
|
|
265
|
+
ready = false;
|
|
266
|
+
// OpenCode owns a private server lease. EOF releases it; do not tear down
|
|
267
|
+
// the SDK transport before giving the process its stdin-EOF grace period.
|
|
268
|
+
child?.stdin.end();
|
|
269
|
+
const slice = Math.floor(closeTimeout / 3);
|
|
270
|
+
try {
|
|
271
|
+
if (await stopped(slice))
|
|
272
|
+
return;
|
|
273
|
+
signalGroup("SIGTERM");
|
|
274
|
+
if (await stopped(slice))
|
|
275
|
+
return;
|
|
276
|
+
signalGroup("SIGKILL");
|
|
277
|
+
if (!(await stopped(slice)))
|
|
278
|
+
throw new Error("ACP owned process did not stop");
|
|
279
|
+
}
|
|
280
|
+
finally {
|
|
281
|
+
connection?.close();
|
|
282
|
+
}
|
|
283
|
+
});
|
|
284
|
+
return closing;
|
|
285
|
+
}
|
|
286
|
+
return { start, newSession, prompt, cancel, close };
|
|
287
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { isAbsolute, resolve } from "node:path";
|
|
2
|
+
import { StartupError } from "./startup-error.js";
|
|
3
|
+
import { parseIdentity } from "./identity.js";
|
|
4
|
+
export function parseOptions(args, env) {
|
|
5
|
+
const flags = parseFlags(args);
|
|
6
|
+
if (flags.has("--help"))
|
|
7
|
+
return { action: "help" };
|
|
8
|
+
if (flags.has("--version"))
|
|
9
|
+
return { action: "version" };
|
|
10
|
+
const explicit = flags.get("--workspace");
|
|
11
|
+
const workspace = explicit === undefined ? env.A2A_WORKSPACE : resolve(explicit);
|
|
12
|
+
if (!workspace || !isAbsolute(workspace))
|
|
13
|
+
throw new StartupError("workspace");
|
|
14
|
+
const identity = parseIdentity(env);
|
|
15
|
+
return {
|
|
16
|
+
action: "run",
|
|
17
|
+
server: {
|
|
18
|
+
workspace,
|
|
19
|
+
port: parsePort(flags.get("--port") ?? env.A2A_PORT),
|
|
20
|
+
...(identity === undefined ? {} : { identity }),
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function parseFlags(args) {
|
|
25
|
+
const flags = new Map();
|
|
26
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
27
|
+
const token = args[index];
|
|
28
|
+
const flag = token === "-h" ? "--help" : token === "-v" ? "--version" : token;
|
|
29
|
+
if (flag === undefined || flags.has(flag))
|
|
30
|
+
throw new StartupError("arguments");
|
|
31
|
+
if (flag === "--help" || flag === "--version") {
|
|
32
|
+
flags.set(flag, "");
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
if (flag !== "--workspace" && flag !== "--port")
|
|
36
|
+
throw new StartupError("arguments");
|
|
37
|
+
flags.set(flag, flagValue(flag, args[index + 1]));
|
|
38
|
+
index += 1;
|
|
39
|
+
}
|
|
40
|
+
return flags;
|
|
41
|
+
}
|
|
42
|
+
function flagValue(flag, value) {
|
|
43
|
+
if (!value ||
|
|
44
|
+
(value.startsWith("-") && flag === "--workspace") ||
|
|
45
|
+
value.startsWith("--") ||
|
|
46
|
+
["-h", "-v"].includes(value))
|
|
47
|
+
throw new StartupError("arguments");
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
function parsePort(value) {
|
|
51
|
+
const port = value === undefined ? 41241 : Number(value);
|
|
52
|
+
if (value !== undefined &&
|
|
53
|
+
(!value || /[^0-9]/.test(value) || !Number.isSafeInteger(port) || port > 65535))
|
|
54
|
+
throw new StartupError("port");
|
|
55
|
+
return port;
|
|
56
|
+
}
|
package/dist/src/cli.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import manifest from "../package.json" with { type: "json" };
|
|
3
|
+
import { parseOptions } from "./cli-options.js";
|
|
4
|
+
import { reportStartupError } from "./startup-error.js";
|
|
5
|
+
async function main() {
|
|
6
|
+
const options = parseOptions(process.argv.slice(2), process.env);
|
|
7
|
+
if (options.action === "help") {
|
|
8
|
+
console.log(`Usage: opencode-a2a-lite --workspace <path> [--port <0..65535>]
|
|
9
|
+
|
|
10
|
+
Start the foreground, unauthenticated A2A gateway.
|
|
11
|
+
Linux, Bun 1.4.4, stable OpenCode 2.2.7 or newer on PATH, and configured provider required.
|
|
12
|
+
|
|
13
|
+
--workspace <path> Explicitly trust this directory; relative paths are resolved.
|
|
14
|
+
--port <0..65535> Port (default 41241; 0 selects a free port).
|
|
15
|
+
--help, -h Show help without starting OpenCode.
|
|
16
|
+
--version, -v Print package version without starting OpenCode.
|
|
17
|
+
|
|
18
|
+
Flags override A2A_WORKSPACE (absolute only) and A2A_PORT.
|
|
19
|
+
Optional identity: A2A_NAME (128 characters), A2A_DESCRIPTION (1024),
|
|
20
|
+
and A2A_TAGS (up to 16 comma-separated tags, 64 characters each; no escaping).
|
|
21
|
+
Values are trimmed, nonblank and control-free; tags deduplicate after text.
|
|
22
|
+
Identity describes the worker, not authentication or permissions.
|
|
23
|
+
No implicit current-directory trust. OpenCode configuration is inherited;
|
|
24
|
+
review tools/plugins/MCP and provider configuration. This is not a sandbox.
|
|
25
|
+
Never expose through a public proxy. Use the separate official a2a CLI as client.`);
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
if (options.action === "version") {
|
|
29
|
+
console.log(manifest.version);
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
const { launchGateway } = await import("./server.js");
|
|
33
|
+
await launchGateway(options.server);
|
|
34
|
+
}
|
|
35
|
+
void main().catch(reportStartupError);
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { Role, TaskState } from "@a2a-js/sdk";
|
|
3
|
+
import { TaskNotCancelableError } from "@a2a-js/sdk/errors";
|
|
4
|
+
import { AgentEvent, } from "@a2a-js/sdk/server";
|
|
5
|
+
export const EXPLICIT_CONTEXT = "opencode.explicitContext";
|
|
6
|
+
function textPart(text) {
|
|
7
|
+
return {
|
|
8
|
+
content: { $case: "text", value: text },
|
|
9
|
+
mediaType: "text/plain",
|
|
10
|
+
filename: "",
|
|
11
|
+
metadata: undefined,
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
export function createAgentExecutor(bridge, options = {}) {
|
|
15
|
+
const maximum = options.maxContexts ?? 100;
|
|
16
|
+
if (!Number.isSafeInteger(maximum) || maximum < 1)
|
|
17
|
+
throw new Error("Invalid context capacity");
|
|
18
|
+
const sessions = new Map();
|
|
19
|
+
let active;
|
|
20
|
+
async function execute(ctx, bus) {
|
|
21
|
+
const taskId = ctx.taskId;
|
|
22
|
+
const contextId = ctx.contextId;
|
|
23
|
+
const artifactId = randomUUID();
|
|
24
|
+
let emitted = false;
|
|
25
|
+
let terminal = false;
|
|
26
|
+
function status(state, text) {
|
|
27
|
+
bus.publish(AgentEvent.statusUpdate({
|
|
28
|
+
taskId,
|
|
29
|
+
contextId,
|
|
30
|
+
status: {
|
|
31
|
+
state,
|
|
32
|
+
timestamp: new Date().toISOString(),
|
|
33
|
+
message: text
|
|
34
|
+
? {
|
|
35
|
+
messageId: randomUUID(),
|
|
36
|
+
taskId,
|
|
37
|
+
contextId,
|
|
38
|
+
role: Role.ROLE_AGENT,
|
|
39
|
+
parts: [textPart(text)],
|
|
40
|
+
metadata: undefined,
|
|
41
|
+
extensions: [],
|
|
42
|
+
referenceTaskIds: [],
|
|
43
|
+
}
|
|
44
|
+
: undefined,
|
|
45
|
+
},
|
|
46
|
+
metadata: undefined,
|
|
47
|
+
}));
|
|
48
|
+
}
|
|
49
|
+
function chunk(text, lastChunk = false) {
|
|
50
|
+
bus.publish(AgentEvent.artifactUpdate({
|
|
51
|
+
taskId,
|
|
52
|
+
contextId,
|
|
53
|
+
artifact: {
|
|
54
|
+
artifactId,
|
|
55
|
+
name: "response",
|
|
56
|
+
description: "Assistant text",
|
|
57
|
+
parts: [textPart(text)],
|
|
58
|
+
metadata: undefined,
|
|
59
|
+
extensions: [],
|
|
60
|
+
},
|
|
61
|
+
append: emitted,
|
|
62
|
+
lastChunk,
|
|
63
|
+
metadata: undefined,
|
|
64
|
+
}));
|
|
65
|
+
emitted = true;
|
|
66
|
+
}
|
|
67
|
+
function finish(state, text) {
|
|
68
|
+
terminal = true;
|
|
69
|
+
if (emitted)
|
|
70
|
+
chunk("", true);
|
|
71
|
+
status(state, text);
|
|
72
|
+
}
|
|
73
|
+
bus.publish(AgentEvent.task(ctx.task ?? {
|
|
74
|
+
id: taskId,
|
|
75
|
+
contextId,
|
|
76
|
+
status: {
|
|
77
|
+
state: TaskState.TASK_STATE_SUBMITTED,
|
|
78
|
+
timestamp: new Date().toISOString(),
|
|
79
|
+
message: undefined,
|
|
80
|
+
},
|
|
81
|
+
history: [ctx.userMessage],
|
|
82
|
+
artifacts: [],
|
|
83
|
+
metadata: undefined,
|
|
84
|
+
}));
|
|
85
|
+
const message = ctx.userMessage;
|
|
86
|
+
if (ctx.task || message.referenceTaskIds.length) {
|
|
87
|
+
finish(TaskState.TASK_STATE_FAILED, "Use contextId without taskId or task references for follow-up turns");
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
const parts = message.parts;
|
|
91
|
+
if (message.role !== Role.ROLE_USER ||
|
|
92
|
+
!parts.length ||
|
|
93
|
+
parts.some((part) => part.content?.$case !== "text" ||
|
|
94
|
+
(part.mediaType !== "" && part.mediaType !== "text/plain"))) {
|
|
95
|
+
finish(TaskState.TASK_STATE_FAILED, "Only non-empty plain text input is supported");
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const text = parts
|
|
99
|
+
.map((part) => (part.content?.$case === "text" ? part.content.value : ""))
|
|
100
|
+
.join("\n");
|
|
101
|
+
if (!text.trim()) {
|
|
102
|
+
finish(TaskState.TASK_STATE_FAILED, "Only non-empty plain text input is supported");
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
const existing = sessions.get(contextId);
|
|
106
|
+
const explicit = ctx.context.state.get(EXPLICIT_CONTEXT) ?? Boolean(message.contextId);
|
|
107
|
+
if (active) {
|
|
108
|
+
finish(TaskState.TASK_STATE_FAILED, "Gateway busy; retry after the active turn finishes");
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
if (explicit && !existing) {
|
|
112
|
+
finish(TaskState.TASK_STATE_FAILED, "Unknown or expired context; omit contextId to start a new conversation");
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (!existing && sessions.size >= maximum) {
|
|
116
|
+
finish(TaskState.TASK_STATE_FAILED, "Context capacity reached; restart the gateway to clear contexts");
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
// Reserve synchronously before session allocation: there is no queue.
|
|
120
|
+
const record = { taskId, terminal: false };
|
|
121
|
+
active = record;
|
|
122
|
+
status(TaskState.TASK_STATE_WORKING);
|
|
123
|
+
try {
|
|
124
|
+
const sessionId = existing ?? (await bridge.newSession()).sessionId;
|
|
125
|
+
record.sessionId = sessionId;
|
|
126
|
+
sessions.set(contextId, sessionId);
|
|
127
|
+
const response = await bridge.prompt(sessionId, text, (value) => {
|
|
128
|
+
if (!terminal && value)
|
|
129
|
+
chunk(value);
|
|
130
|
+
});
|
|
131
|
+
if (response.stopReason === "end_turn") {
|
|
132
|
+
finish(TaskState.TASK_STATE_COMPLETED);
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
if (response.stopReason === "cancelled") {
|
|
136
|
+
finish(TaskState.TASK_STATE_CANCELED);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
sessions.delete(contextId);
|
|
140
|
+
finish(TaskState.TASK_STATE_FAILED, "ACP did not complete the turn");
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
sessions.delete(contextId);
|
|
144
|
+
if (!terminal)
|
|
145
|
+
finish(TaskState.TASK_STATE_FAILED, "ACP execution failed");
|
|
146
|
+
}
|
|
147
|
+
finally {
|
|
148
|
+
record.terminal = true;
|
|
149
|
+
await record.cancellation?.catch(() => undefined);
|
|
150
|
+
if (active === record)
|
|
151
|
+
active = undefined;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
async function cancelTask(taskId) {
|
|
155
|
+
const record = active;
|
|
156
|
+
if (!record || record.taskId !== taskId || record.terminal)
|
|
157
|
+
throw new TaskNotCancelableError("Task has no active ACP prompt");
|
|
158
|
+
if (!record.sessionId)
|
|
159
|
+
throw new TaskNotCancelableError("ACP session allocation is not cancelable; retry after allocation finishes");
|
|
160
|
+
try {
|
|
161
|
+
// execute() publishes the terminal state only after ACP confirms its stop reason.
|
|
162
|
+
record.cancellation ??= bridge.cancel(record.sessionId);
|
|
163
|
+
await record.cancellation;
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
throw new TaskNotCancelableError("ACP cancellation failed");
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return { execute, cancelTask };
|
|
170
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { StartupError } from "./startup-error.js";
|
|
2
|
+
function text(value, limit) {
|
|
3
|
+
if (typeof value !== "string" || /\p{Cc}/u.test(value))
|
|
4
|
+
throw new StartupError("identity");
|
|
5
|
+
const trimmed = value.trim();
|
|
6
|
+
if (!trimmed || trimmed.length > limit)
|
|
7
|
+
throw new StartupError("identity");
|
|
8
|
+
return trimmed;
|
|
9
|
+
}
|
|
10
|
+
export function validateIdentity(identity = {}) {
|
|
11
|
+
if (!identity || typeof identity !== "object" || Array.isArray(identity))
|
|
12
|
+
throw new StartupError("identity");
|
|
13
|
+
const result = {};
|
|
14
|
+
if (identity.name !== undefined)
|
|
15
|
+
result.name = text(identity.name, 128);
|
|
16
|
+
if (identity.description !== undefined)
|
|
17
|
+
result.description = text(identity.description, 1_024);
|
|
18
|
+
if (identity.tags !== undefined) {
|
|
19
|
+
if (!Array.isArray(identity.tags) || identity.tags.length > 16)
|
|
20
|
+
throw new StartupError("identity");
|
|
21
|
+
result.tags = [...new Set(Array.from(identity.tags, (tag) => text(tag, 64)))];
|
|
22
|
+
}
|
|
23
|
+
return result;
|
|
24
|
+
}
|
|
25
|
+
export function parseIdentity(env) {
|
|
26
|
+
if ([env.A2A_NAME, env.A2A_DESCRIPTION, env.A2A_TAGS].every((value) => value === undefined))
|
|
27
|
+
return undefined;
|
|
28
|
+
return validateIdentity({
|
|
29
|
+
...(env.A2A_NAME === undefined ? {} : { name: env.A2A_NAME }),
|
|
30
|
+
...(env.A2A_DESCRIPTION === undefined ? {} : { description: env.A2A_DESCRIPTION }),
|
|
31
|
+
...(env.A2A_TAGS === undefined ? {} : { tags: env.A2A_TAGS.split(",") }),
|
|
32
|
+
});
|
|
33
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
const stable = /^opencode v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/;
|
|
2
|
+
const floor = [2, 2, 7];
|
|
3
|
+
export function supportedOpenCode(output) {
|
|
4
|
+
const match = stable.exec(output);
|
|
5
|
+
if (!match)
|
|
6
|
+
return false;
|
|
7
|
+
const parts = match.slice(1).map(Number);
|
|
8
|
+
for (const [index, minimum] of floor.entries()) {
|
|
9
|
+
const part = parts[index] ?? 0;
|
|
10
|
+
if (part !== minimum)
|
|
11
|
+
return part > minimum;
|
|
12
|
+
}
|
|
13
|
+
return true;
|
|
14
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { TaskState } from "@a2a-js/sdk";
|
|
2
|
+
import { TaskNotCancelableError } from "@a2a-js/sdk/errors";
|
|
3
|
+
import { DefaultExecutionEventBusManager, DefaultRequestHandler, InMemoryTaskStore, } from "@a2a-js/sdk/server";
|
|
4
|
+
export function createRequestHandler(card, executor, timeout) {
|
|
5
|
+
const memory = new InMemoryTaskStore();
|
|
6
|
+
const buses = new DefaultExecutionEventBusManager();
|
|
7
|
+
const listeners = new Map();
|
|
8
|
+
const terminal = (task) => task.status &&
|
|
9
|
+
![TaskState.TASK_STATE_SUBMITTED, TaskState.TASK_STATE_WORKING].includes(task.status.state);
|
|
10
|
+
const store = {
|
|
11
|
+
load: (id, context) => memory.load(id, context),
|
|
12
|
+
list: (params, context) => memory.list(params, context),
|
|
13
|
+
async save(task, context) {
|
|
14
|
+
await memory.save(task, context);
|
|
15
|
+
if (terminal(task))
|
|
16
|
+
listeners.get(task.id)?.forEach((notify) => notify());
|
|
17
|
+
},
|
|
18
|
+
};
|
|
19
|
+
const handler = new DefaultRequestHandler(card, store, executor, buses);
|
|
20
|
+
// SDK 1.3's CancelTask creates a second ResultManager on the live bus, so
|
|
21
|
+
// cancellation-time artifact appends are persisted twice. Keep one consumer;
|
|
22
|
+
// await that consumer's terminal save through the public TaskStore interface.
|
|
23
|
+
handler.cancelTask = async (params, context) => {
|
|
24
|
+
const task = await handler.getTask(params, context);
|
|
25
|
+
if (task.status?.state === TaskState.TASK_STATE_CANCELED)
|
|
26
|
+
return task;
|
|
27
|
+
const bus = buses.getByTaskId(params.id, context);
|
|
28
|
+
if (terminal(task) || !bus)
|
|
29
|
+
throw new TaskNotCancelableError("Task has no active ACP prompt");
|
|
30
|
+
const pending = Promise.withResolvers();
|
|
31
|
+
const callbacks = listeners.get(params.id) ?? new Set();
|
|
32
|
+
const notify = () => pending.resolve();
|
|
33
|
+
callbacks.add(notify);
|
|
34
|
+
listeners.set(params.id, callbacks);
|
|
35
|
+
const timer = setTimeout(() => pending.reject(new TaskNotCancelableError("Cancellation did not settle")), timeout);
|
|
36
|
+
try {
|
|
37
|
+
// Recheck after subscribing in case the original event consumer won the race.
|
|
38
|
+
const current = await handler.getTask(params, context);
|
|
39
|
+
if (terminal(current))
|
|
40
|
+
notify();
|
|
41
|
+
await Promise.all([executor.cancelTask(params.id, bus), pending.promise]);
|
|
42
|
+
const result = await handler.getTask(params, context);
|
|
43
|
+
if (result.status?.state !== TaskState.TASK_STATE_CANCELED)
|
|
44
|
+
throw new TaskNotCancelableError("ACP did not cancel the task");
|
|
45
|
+
return result;
|
|
46
|
+
}
|
|
47
|
+
finally {
|
|
48
|
+
clearTimeout(timer);
|
|
49
|
+
callbacks.delete(notify);
|
|
50
|
+
if (!callbacks.size)
|
|
51
|
+
listeners.delete(params.id);
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
return handler;
|
|
55
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { stat } from "node:fs/promises";
|
|
2
|
+
import { createServer } from "node:http";
|
|
3
|
+
import { isAbsolute, resolve } from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import express from "express";
|
|
6
|
+
import manifest from "../package.json" with { type: "json" };
|
|
7
|
+
import { A2A_PROTOCOL_VERSION, AGENT_CARD_PATH } from "@a2a-js/sdk";
|
|
8
|
+
import { agentCardHandler, jsonRpcHandler, UserBuilder } from "@a2a-js/sdk/server/express";
|
|
9
|
+
import { createAcpBridge } from "./acp-client.js";
|
|
10
|
+
import { createAgentExecutor, EXPLICIT_CONTEXT } from "./executor.js";
|
|
11
|
+
import { createRequestHandler } from "./request-handler.js";
|
|
12
|
+
import { parseOptions } from "./cli-options.js";
|
|
13
|
+
import { reportStartupError, StartupError } from "./startup-error.js";
|
|
14
|
+
import { validateIdentity } from "./identity.js";
|
|
15
|
+
export function createGateway(options) {
|
|
16
|
+
const identity = validateIdentity(options.identity);
|
|
17
|
+
if (!isAbsolute(options.workspace))
|
|
18
|
+
throw new StartupError("workspace");
|
|
19
|
+
const host = options.host ?? "127.0.0.1";
|
|
20
|
+
if (!["127.0.0.1", "::1"].includes(host))
|
|
21
|
+
throw new Error("Only loopback hosts are supported");
|
|
22
|
+
const port = options.port ?? 41241;
|
|
23
|
+
if (!Number.isSafeInteger(port) || port < 0 || port > 65535)
|
|
24
|
+
throw new StartupError("port");
|
|
25
|
+
const bridge = createAcpBridge({ ...options.acp, cwd: options.workspace });
|
|
26
|
+
const app = express();
|
|
27
|
+
app.disable("x-powered-by");
|
|
28
|
+
app.use((_request, response, next) => {
|
|
29
|
+
if (closing)
|
|
30
|
+
return response.status(503).end();
|
|
31
|
+
next();
|
|
32
|
+
});
|
|
33
|
+
const server = createServer(app);
|
|
34
|
+
let starting;
|
|
35
|
+
let closing;
|
|
36
|
+
function close() {
|
|
37
|
+
if (closing)
|
|
38
|
+
return closing;
|
|
39
|
+
closing = Promise.resolve().then(async () => {
|
|
40
|
+
const http = new Promise((resolve, reject) => {
|
|
41
|
+
if (!server.listening)
|
|
42
|
+
return resolve();
|
|
43
|
+
let timer;
|
|
44
|
+
let ended = false;
|
|
45
|
+
const finish = (error) => {
|
|
46
|
+
ended = true;
|
|
47
|
+
clearTimeout(timer);
|
|
48
|
+
server.removeListener("close", finish);
|
|
49
|
+
if (error)
|
|
50
|
+
return reject(new Error("HTTP shutdown failed"));
|
|
51
|
+
resolve();
|
|
52
|
+
};
|
|
53
|
+
const grace = () => {
|
|
54
|
+
if (ended)
|
|
55
|
+
return;
|
|
56
|
+
timer = setTimeout(() => {
|
|
57
|
+
try {
|
|
58
|
+
server.closeAllConnections();
|
|
59
|
+
if (process.versions.bun)
|
|
60
|
+
server.close(finish);
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
finish(new Error("HTTP force-close failed"));
|
|
64
|
+
}
|
|
65
|
+
}, 1_000);
|
|
66
|
+
};
|
|
67
|
+
void bridge.close().then(grace, grace);
|
|
68
|
+
// Bun close() loses the handle needed to force-close incomplete HTTP headers.
|
|
69
|
+
// Keep the listener through the drain, then explicitly close it.
|
|
70
|
+
// closeAllConnections() only drains clients; closing middleware rejects new work.
|
|
71
|
+
if (process.versions.bun)
|
|
72
|
+
return;
|
|
73
|
+
server.close(finish);
|
|
74
|
+
});
|
|
75
|
+
const results = await Promise.allSettled([http, bridge.close()]);
|
|
76
|
+
if (results.some((result) => result.status === "rejected"))
|
|
77
|
+
throw new Error("Gateway owned shutdown failed");
|
|
78
|
+
});
|
|
79
|
+
return closing;
|
|
80
|
+
}
|
|
81
|
+
function start() {
|
|
82
|
+
if (closing)
|
|
83
|
+
return Promise.reject(new Error("Gateway closed"));
|
|
84
|
+
if (starting)
|
|
85
|
+
return starting;
|
|
86
|
+
starting = Promise.resolve().then(async () => {
|
|
87
|
+
try {
|
|
88
|
+
const workspace = await stat(options.workspace).catch(() => undefined);
|
|
89
|
+
if (!workspace?.isDirectory())
|
|
90
|
+
throw new StartupError("directory");
|
|
91
|
+
await bridge.start();
|
|
92
|
+
if (closing)
|
|
93
|
+
throw new Error("Gateway closed");
|
|
94
|
+
const executor = options.createExecutor?.(bridge) ?? createAgentExecutor(bridge, options.executor);
|
|
95
|
+
const card = {
|
|
96
|
+
name: identity.name ?? "OpenCode A2A Lite",
|
|
97
|
+
description: identity.description ??
|
|
98
|
+
"OpenCode ACP gateway for contextual plain text prompts and streamed responses.",
|
|
99
|
+
supportedInterfaces: [],
|
|
100
|
+
provider: undefined,
|
|
101
|
+
version: manifest.version,
|
|
102
|
+
capabilities: {
|
|
103
|
+
streaming: true,
|
|
104
|
+
pushNotifications: false,
|
|
105
|
+
extendedAgentCard: false,
|
|
106
|
+
extensions: [],
|
|
107
|
+
},
|
|
108
|
+
securitySchemes: {},
|
|
109
|
+
securityRequirements: [],
|
|
110
|
+
defaultInputModes: ["text/plain"],
|
|
111
|
+
defaultOutputModes: ["text/plain"],
|
|
112
|
+
skills: [
|
|
113
|
+
{
|
|
114
|
+
id: "text-prompt",
|
|
115
|
+
name: "Text prompt",
|
|
116
|
+
description: "Run a plain text prompt or context follow-up in the trusted workspace.",
|
|
117
|
+
tags: [...new Set(["text", ...(identity.tags ?? [])])],
|
|
118
|
+
examples: ["Reply with a short greeting."],
|
|
119
|
+
inputModes: ["text/plain"],
|
|
120
|
+
outputModes: ["text/plain"],
|
|
121
|
+
securityRequirements: [],
|
|
122
|
+
},
|
|
123
|
+
],
|
|
124
|
+
signatures: [],
|
|
125
|
+
};
|
|
126
|
+
const handler = createRequestHandler(card, executor, (options.acp?.cancelTimeoutMs ?? 5_000) + 1_000);
|
|
127
|
+
// Preserve caller intent before the SDK fills in missing context IDs.
|
|
128
|
+
// SDK 1.3 has no public RequestContextBuilder; routing remains SDK-owned.
|
|
129
|
+
const send = handler.sendMessage.bind(handler);
|
|
130
|
+
handler.sendMessage = (request, context) => {
|
|
131
|
+
context.state.set(EXPLICIT_CONTEXT, Boolean(request.message?.contextId));
|
|
132
|
+
return send(request, context);
|
|
133
|
+
};
|
|
134
|
+
const stream = handler.sendMessageStream.bind(handler);
|
|
135
|
+
handler.sendMessageStream = (request, context) => {
|
|
136
|
+
context.state.set(EXPLICIT_CONTEXT, Boolean(request.message?.contextId));
|
|
137
|
+
return stream(request, context);
|
|
138
|
+
};
|
|
139
|
+
app.use(`/${AGENT_CARD_PATH}`, agentCardHandler({ agentCardProvider: handler }));
|
|
140
|
+
app.use("/", jsonRpcHandler({ requestHandler: handler, userBuilder: UserBuilder.noAuthentication }));
|
|
141
|
+
await new Promise((resolve, reject) => {
|
|
142
|
+
const onError = (error) => reject(error.code === "EADDRINUSE" ? new StartupError("occupied") : error);
|
|
143
|
+
server.once("error", onError);
|
|
144
|
+
server.listen(port, host, () => {
|
|
145
|
+
server.removeListener("error", onError);
|
|
146
|
+
resolve();
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
if (closing)
|
|
150
|
+
throw new Error("Gateway closed");
|
|
151
|
+
const address = server.address();
|
|
152
|
+
if (!address || typeof address === "string")
|
|
153
|
+
throw new Error("HTTP listener unavailable");
|
|
154
|
+
const url = `http://${host === "::1" ? "[::1]" : host}:${address.port}/`;
|
|
155
|
+
card.supportedInterfaces.push({
|
|
156
|
+
url,
|
|
157
|
+
protocolBinding: "JSONRPC",
|
|
158
|
+
tenant: "",
|
|
159
|
+
protocolVersion: A2A_PROTOCOL_VERSION,
|
|
160
|
+
});
|
|
161
|
+
return { url, card };
|
|
162
|
+
}
|
|
163
|
+
catch (error) {
|
|
164
|
+
await close();
|
|
165
|
+
throw error;
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
return starting;
|
|
169
|
+
}
|
|
170
|
+
return { start, close };
|
|
171
|
+
}
|
|
172
|
+
export async function launchGateway(options) {
|
|
173
|
+
const gateway = createGateway(options);
|
|
174
|
+
const stop = () => {
|
|
175
|
+
void gateway.close().catch(() => {
|
|
176
|
+
console.error("Gateway shutdown failed");
|
|
177
|
+
process.exitCode = 1;
|
|
178
|
+
});
|
|
179
|
+
};
|
|
180
|
+
process.once("SIGINT", stop);
|
|
181
|
+
process.once("SIGTERM", stop);
|
|
182
|
+
try {
|
|
183
|
+
const ready = await gateway.start();
|
|
184
|
+
console.log(JSON.stringify({ ready: true, url: ready.url }));
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
process.removeListener("SIGINT", stop);
|
|
188
|
+
process.removeListener("SIGTERM", stop);
|
|
189
|
+
await gateway.close();
|
|
190
|
+
throw error;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
|
|
194
|
+
void Promise.resolve()
|
|
195
|
+
.then(() => parseOptions([], process.env))
|
|
196
|
+
.then((options) => {
|
|
197
|
+
if (options.action === "run")
|
|
198
|
+
return launchGateway(options.server);
|
|
199
|
+
})
|
|
200
|
+
.catch(reportStartupError);
|
|
201
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
const messages = {
|
|
2
|
+
arguments: "Invalid arguments. Use --help for --workspace <path> and --port <0..65535>.",
|
|
3
|
+
workspace: "A trusted absolute workspace is required: pass --workspace <path> or set A2A_WORKSPACE to an absolute directory.",
|
|
4
|
+
directory: "Workspace must be an existing directory; select a trusted directory with --workspace or A2A_WORKSPACE.",
|
|
5
|
+
port: "Invalid port: use an integer from 0 through 65535 with --port or A2A_PORT.",
|
|
6
|
+
identity: "Invalid worker identity: use nonblank strings without control characters; name <=128, description <=1024, and up to 16 tags of <=64 characters (A2A_TAGS is comma-separated).",
|
|
7
|
+
occupied: "Port is in use; choose another --port or A2A_PORT (0 selects a free port).",
|
|
8
|
+
executable: "ACP startup failed: OpenCode is unavailable; install a stable OpenCode 2.2.7 or newer executable on PATH.",
|
|
9
|
+
version: "ACP startup failed: Unsupported OpenCode version; PATH must provide stable opencode v2.2.7 or newer.",
|
|
10
|
+
};
|
|
11
|
+
export class StartupError extends Error {
|
|
12
|
+
constructor(code) {
|
|
13
|
+
super(messages[code]);
|
|
14
|
+
this.name = "StartupError";
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export function reportStartupError(error) {
|
|
18
|
+
console.error(error instanceof StartupError
|
|
19
|
+
? error.message
|
|
20
|
+
: "Gateway startup failed; check trusted workspace and isolated OpenCode/provider configuration.");
|
|
21
|
+
process.exitCode = 1;
|
|
22
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,57 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tbrandenburg/opencode-a2a-lite",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.5",
|
|
4
|
+
"description": "OpenCode ACP to A2A gateway for trusted workspaces",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/tbrandenburg/opencode-a2a-lite.git"
|
|
9
|
+
},
|
|
10
|
+
"bin": {
|
|
11
|
+
"opencode-a2a-lite": "dist/src/cli.js"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"dist/src/*.js",
|
|
15
|
+
"dist/package.json",
|
|
16
|
+
"README.md",
|
|
17
|
+
"LICENSE"
|
|
18
|
+
],
|
|
19
|
+
"os": [
|
|
20
|
+
"linux"
|
|
21
|
+
],
|
|
22
|
+
"type": "module",
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"scripts": {
|
|
27
|
+
"dev": "bun --watch src/server.ts",
|
|
28
|
+
"start": "bun dist/src/server.js",
|
|
29
|
+
"build": "tsc --noEmit false --outDir dist --rootDir .",
|
|
30
|
+
"prepack": "rm -rf dist/src && bun run build && chmod +x dist/src/cli.js",
|
|
31
|
+
"package-smoke": "bun scripts/package-smoke.ts",
|
|
32
|
+
"fmt": "oxfmt",
|
|
33
|
+
"fmt-check": "oxfmt --check",
|
|
34
|
+
"lint": "oxlint .",
|
|
35
|
+
"typecheck": "tsc --noEmit",
|
|
36
|
+
"test": "bun test ./tests"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@a2a-js/sdk": "1.3.0",
|
|
40
|
+
"@agentclientprotocol/sdk": "2.0.2",
|
|
41
|
+
"express": "5.3.0"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@modelcontextprotocol/sdk": "1.29.0",
|
|
45
|
+
"@types/bun": "1.4.4",
|
|
46
|
+
"@types/express": "5.0.6",
|
|
47
|
+
"@types/node": "24.10.0",
|
|
48
|
+
"oxfmt": "0.74.0",
|
|
49
|
+
"oxlint": "1.89.0",
|
|
50
|
+
"typescript": "7.0.2"
|
|
51
|
+
},
|
|
52
|
+
"engines": {
|
|
53
|
+
"bun": "1.4.4",
|
|
54
|
+
"node": ">=22"
|
|
55
|
+
},
|
|
56
|
+
"packageManager": "bun@1.4.4"
|
|
57
|
+
}
|