@tbrandenburg/opencode-a2a-lite 0.4.0 → 0.5.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/README.md +22 -4
- package/dist/package.json +1 -1
- package/dist/src/acp-client.js +43 -25
- package/dist/src/activity.js +23 -0
- package/dist/src/cli-options.js +12 -2
- package/dist/src/cli.js +7 -1
- package/dist/src/executor.js +62 -4
- package/dist/src/permission-desk.js +37 -0
- package/dist/src/permission.js +71 -0
- package/dist/src/request-handler.js +8 -1
- package/dist/src/server.js +26 -12
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -89,6 +89,7 @@ launcher still use Linux-specific tooling.
|
|
|
89
89
|
|
|
90
90
|
```text
|
|
91
91
|
opencode-a2a-lite --workspace <path> [--port <0..65535>] [--publish-activity]
|
|
92
|
+
[--permissions <reject|ask>]
|
|
92
93
|
opencode-a2a-lite --help | --version
|
|
93
94
|
```
|
|
94
95
|
|
|
@@ -128,10 +129,27 @@ reusing the ACP session for that context.
|
|
|
128
129
|
underlying OpenCode diagnostic is never published. A bridge failure is permanent until restart.
|
|
129
130
|
- Every task's metadata carries `opencode.sessionId` and `opencode.stopReason` (after a session
|
|
130
131
|
exists). The session id is the key for finding the full transcript in OpenCode itself.
|
|
131
|
-
- `--publish-activity` (off by default) adds an `activity` artifact of data parts
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
132
|
+
- `--publish-activity` (off by default) adds an `activity` artifact of data parts: tool call id,
|
|
133
|
+
title, kind and status, plus the model's reasoning text as `{"thought": "..."}` when OpenCode
|
|
134
|
+
emits it. Tool inputs and outputs are never published. Titles and reasoning may reveal paths,
|
|
135
|
+
commands or workspace data, so enable it only for clients you trust. The Agent Card then
|
|
136
|
+
declares the `urn:opencode-a2a-lite:activity:v1` extension. Reasoning appears only for models
|
|
137
|
+
and effort settings that emit it (for example Claude Haiku 5.5 with `effort=high`).
|
|
138
|
+
- By default the gateway rejects every permission request. A turn stopped by a rejection ends
|
|
139
|
+
`canceled` with the message "Permission request rejected" and `opencode.permissionDenied: "true"`
|
|
140
|
+
in the task metadata; a client cancellation carries neither. Permissions that OpenCode's own
|
|
141
|
+
configuration allows are never asked, so they are never rejected.
|
|
142
|
+
- `--permissions ask` lets a client decide. The task pauses as `input-required` with a text
|
|
143
|
+
question and a data part `{"permission": {requestId, title, kind, options}}`; metadata shows
|
|
144
|
+
`opencode.permissionPending: "true"` and the request id. Answer on the **same task**
|
|
145
|
+
(`a2a send -a <url> --task-id <id> --context-id <ctx> allow`, or `reject`, or a data part
|
|
146
|
+
`{"permissionResponse": {"requestId", "optionId"}}`). A wrong id or option leaves the request
|
|
147
|
+
open; only `allow_once` and the reject options are offered, never `allow_always`. No answer
|
|
148
|
+
within 120 seconds rejects once. While waiting, the single prompt slot stays held (other tasks
|
|
149
|
+
get "busy") and the prompt deadline is suspended; canceling the task cancels the request without
|
|
150
|
+
marking a denial. **Anyone who can reach the unauthenticated port can approve tool runs in this
|
|
151
|
+
mode**, so keep it on loopback and for trusted clients only. The Agent Card declares the
|
|
152
|
+
`urn:opencode-a2a-lite:permissions:v1` extension.
|
|
135
153
|
- Defaults: 30-second startup/session allocation, 120-second prompt, 5-second
|
|
136
154
|
cancellation and 5-second ACP shutdown. Failure retires the unhealthy bridge.
|
|
137
155
|
- Streaming sends stable artifact IDs and ordered append events. Task states are
|
package/dist/package.json
CHANGED
package/dist/src/acp-client.js
CHANGED
|
@@ -3,20 +3,11 @@ import { isAbsolute } from "node:path";
|
|
|
3
3
|
import { Readable, Writable } from "node:stream";
|
|
4
4
|
import * as acp from "@agentclientprotocol/sdk";
|
|
5
5
|
import manifest from "../package.json" with { type: "json" };
|
|
6
|
+
import { activityOf } from "./activity.js";
|
|
6
7
|
import { BridgeError } from "./bridge-error.js";
|
|
8
|
+
import { askOperator, decide } from "./permission.js";
|
|
7
9
|
import { supportedOpenCode } from "./opencode-version.js";
|
|
8
10
|
import { StartupError } from "./startup-error.js";
|
|
9
|
-
// Only identifying fields are forwarded; tool inputs and outputs never leave the bridge.
|
|
10
|
-
function toolActivity(update) {
|
|
11
|
-
if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update")
|
|
12
|
-
return;
|
|
13
|
-
return {
|
|
14
|
-
toolCallId: update.toolCallId,
|
|
15
|
-
...(update.title ? { title: update.title } : {}),
|
|
16
|
-
...(update.kind ? { kind: update.kind } : {}),
|
|
17
|
-
...(update.status ? { status: update.status } : {}),
|
|
18
|
-
};
|
|
19
|
-
}
|
|
20
11
|
export function createAcpBridge(options) {
|
|
21
12
|
if (!isAbsolute(options.cwd))
|
|
22
13
|
throw new Error("ACP workspace must be absolute");
|
|
@@ -50,11 +41,24 @@ export function createAcpBridge(options) {
|
|
|
50
41
|
// Retain the cleanup result for close(); request errors never contain peer diagnostics.
|
|
51
42
|
void close().catch(() => undefined);
|
|
52
43
|
}
|
|
53
|
-
|
|
44
|
+
// While a human decision is pending (hold.count > 0) the deadline is suspended and restarts on release.
|
|
45
|
+
function bounded(operation, ms, label, hold) {
|
|
54
46
|
if (failure.signal.aborted)
|
|
55
47
|
return Promise.reject(failure.signal.reason);
|
|
56
48
|
return new Promise((resolve, reject) => {
|
|
57
|
-
const
|
|
49
|
+
const expire = () => {
|
|
50
|
+
if (hold?.count)
|
|
51
|
+
timer = setTimeout(expire, ms);
|
|
52
|
+
else
|
|
53
|
+
fail(`ACP ${label} timed out`);
|
|
54
|
+
};
|
|
55
|
+
let timer = setTimeout(expire, ms);
|
|
56
|
+
if (hold) {
|
|
57
|
+
hold.rearm = () => {
|
|
58
|
+
clearTimeout(timer);
|
|
59
|
+
timer = setTimeout(expire, ms);
|
|
60
|
+
};
|
|
61
|
+
}
|
|
58
62
|
const cleanup = () => {
|
|
59
63
|
clearTimeout(timer);
|
|
60
64
|
failure.signal.removeEventListener("abort", abort);
|
|
@@ -132,17 +136,25 @@ export function createAcpBridge(options) {
|
|
|
132
136
|
child.stderr.resume();
|
|
133
137
|
const client = acp.client({ name: "opencode-a2a-lite" });
|
|
134
138
|
client.onRequest(acp.methods.client.session.requestPermission, async (request) => {
|
|
135
|
-
|
|
139
|
+
const current = turn;
|
|
140
|
+
const unusable = () => stopping ||
|
|
136
141
|
failure.signal.aborted ||
|
|
137
|
-
!
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
request.params.sessionId !==
|
|
142
|
+
!current ||
|
|
143
|
+
current.settled ||
|
|
144
|
+
current.cancelled ||
|
|
145
|
+
request.params.sessionId !== current.sessionId;
|
|
146
|
+
if (unusable() || !current)
|
|
147
|
+
return { outcome: { outcome: "cancelled" } };
|
|
148
|
+
const options = request.params.options;
|
|
149
|
+
const chosen = await askOperator(current, request.params);
|
|
150
|
+
if (current.onPermission && unusable())
|
|
141
151
|
return { outcome: { outcome: "cancelled" } };
|
|
142
|
-
const
|
|
152
|
+
const decision = decide(options, chosen);
|
|
153
|
+
if (decision.denied)
|
|
154
|
+
current.denied = true;
|
|
143
155
|
return {
|
|
144
|
-
outcome:
|
|
145
|
-
? { outcome: "selected", optionId:
|
|
156
|
+
outcome: decision.outcome === "selected"
|
|
157
|
+
? { outcome: "selected", optionId: decision.optionId }
|
|
146
158
|
: { outcome: "cancelled" },
|
|
147
159
|
};
|
|
148
160
|
});
|
|
@@ -156,7 +168,7 @@ export function createAcpBridge(options) {
|
|
|
156
168
|
if (notification.params._meta?.["opencode/child-session"] !== undefined ||
|
|
157
169
|
update._meta?.["opencode/child-session"] !== undefined)
|
|
158
170
|
return;
|
|
159
|
-
const activity =
|
|
171
|
+
const activity = activityOf(update);
|
|
160
172
|
if (activity) {
|
|
161
173
|
try {
|
|
162
174
|
turn.onActivity?.(activity);
|
|
@@ -205,7 +217,7 @@ export function createAcpBridge(options) {
|
|
|
205
217
|
sessions.add(response.sessionId);
|
|
206
218
|
return response;
|
|
207
219
|
}
|
|
208
|
-
async function prompt(sessionId, text, onText, onActivity) {
|
|
220
|
+
async function prompt(sessionId, text, onText, onActivity, onPermission) {
|
|
209
221
|
const current = requireConnection(sessionId);
|
|
210
222
|
if (turn)
|
|
211
223
|
throw new Error("ACP prompt in progress");
|
|
@@ -213,6 +225,10 @@ export function createAcpBridge(options) {
|
|
|
213
225
|
sessionId,
|
|
214
226
|
onText,
|
|
215
227
|
onActivity,
|
|
228
|
+
onPermission,
|
|
229
|
+
hold: { count: 0 },
|
|
230
|
+
released: Promise.withResolvers(),
|
|
231
|
+
denied: false,
|
|
216
232
|
cancelled: false,
|
|
217
233
|
settled: false,
|
|
218
234
|
cancellation: undefined,
|
|
@@ -222,9 +238,10 @@ export function createAcpBridge(options) {
|
|
|
222
238
|
active.completion = bounded(() => current.agent.request(acp.methods.agent.session.prompt, {
|
|
223
239
|
sessionId,
|
|
224
240
|
prompt: [{ type: "text", text }],
|
|
225
|
-
}), promptTimeout, "prompt");
|
|
241
|
+
}), promptTimeout, "prompt", active.hold);
|
|
226
242
|
try {
|
|
227
|
-
|
|
243
|
+
const response = await active.completion;
|
|
244
|
+
return active.denied ? { ...response, permissionDenied: true } : response;
|
|
228
245
|
}
|
|
229
246
|
finally {
|
|
230
247
|
active.settled = true;
|
|
@@ -246,6 +263,7 @@ export function createAcpBridge(options) {
|
|
|
246
263
|
if (active.cancellation)
|
|
247
264
|
return active.cancellation;
|
|
248
265
|
active.cancelled = true;
|
|
266
|
+
active.released.resolve(undefined);
|
|
249
267
|
active.cancellation = bounded(async () => {
|
|
250
268
|
await current.agent.notify(acp.methods.agent.session.cancel, { sessionId });
|
|
251
269
|
await active.completion;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
function thoughtOf(update) {
|
|
2
|
+
if (update.sessionUpdate !== "agent_thought_chunk")
|
|
3
|
+
return;
|
|
4
|
+
if (update.content.type !== "text" || !update.content.text)
|
|
5
|
+
return;
|
|
6
|
+
if (update.content._meta?.["opencode/child-session"] !== undefined)
|
|
7
|
+
return;
|
|
8
|
+
return { thought: update.content.text };
|
|
9
|
+
}
|
|
10
|
+
function toolOf(update) {
|
|
11
|
+
if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update")
|
|
12
|
+
return;
|
|
13
|
+
return {
|
|
14
|
+
toolCallId: update.toolCallId,
|
|
15
|
+
...(update.title ? { title: update.title } : {}),
|
|
16
|
+
...(update.kind ? { kind: update.kind } : {}),
|
|
17
|
+
...(update.status ? { status: update.status } : {}),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
// Tool inputs and outputs never leave the bridge: only identifying fields and thought text do.
|
|
21
|
+
export function activityOf(update) {
|
|
22
|
+
return thoughtOf(update) ?? toolOf(update);
|
|
23
|
+
}
|
package/dist/src/cli-options.js
CHANGED
|
@@ -17,11 +17,21 @@ export function parseOptions(args, env) {
|
|
|
17
17
|
server: {
|
|
18
18
|
workspace,
|
|
19
19
|
port: parsePort(flags.get("--port") ?? env.A2A_PORT),
|
|
20
|
-
...(flags
|
|
20
|
+
...executorOptions(flags),
|
|
21
21
|
...(identity === undefined ? {} : { identity }),
|
|
22
22
|
},
|
|
23
23
|
};
|
|
24
24
|
}
|
|
25
|
+
function executorOptions(flags) {
|
|
26
|
+
const permissions = flags.get("--permissions");
|
|
27
|
+
if (permissions !== undefined && permissions !== "reject" && permissions !== "ask")
|
|
28
|
+
throw new StartupError("arguments");
|
|
29
|
+
const executor = {
|
|
30
|
+
...(flags.has("--publish-activity") ? { activity: true } : {}),
|
|
31
|
+
...(permissions === "ask" ? { permissions: "ask" } : {}),
|
|
32
|
+
};
|
|
33
|
+
return Object.keys(executor).length ? { executor } : {};
|
|
34
|
+
}
|
|
25
35
|
const VALUELESS = new Set(["--help", "--version", "--publish-activity"]);
|
|
26
36
|
function parseFlags(args) {
|
|
27
37
|
const flags = new Map();
|
|
@@ -34,7 +44,7 @@ function parseFlags(args) {
|
|
|
34
44
|
flags.set(flag, "");
|
|
35
45
|
continue;
|
|
36
46
|
}
|
|
37
|
-
if (flag !== "--workspace" && flag !== "--port")
|
|
47
|
+
if (flag !== "--workspace" && flag !== "--port" && flag !== "--permissions")
|
|
38
48
|
throw new StartupError("arguments");
|
|
39
49
|
flags.set(flag, flagValue(flag, args[index + 1]));
|
|
40
50
|
index += 1;
|
package/dist/src/cli.js
CHANGED
|
@@ -6,6 +6,7 @@ async function main() {
|
|
|
6
6
|
const options = parseOptions(process.argv.slice(2), process.env);
|
|
7
7
|
if (options.action === "help") {
|
|
8
8
|
console.log(`Usage: opencode-a2a-lite --workspace <path> [--port <0..65535>] [--publish-activity]
|
|
9
|
+
[--permissions <reject|ask>]
|
|
9
10
|
|
|
10
11
|
Start the foreground, unauthenticated A2A gateway.
|
|
11
12
|
Linux or macOS (experimental), Bun 1.4.4, stable OpenCode 2.2.7 or newer on PATH, and configured provider required.
|
|
@@ -13,7 +14,12 @@ Linux or macOS (experimental), Bun 1.4.4, stable OpenCode 2.2.7 or newer on PATH
|
|
|
13
14
|
--workspace <path> Explicitly trust this directory; relative paths are resolved.
|
|
14
15
|
--port <0..65535> Port (default 41241; 0 selects a free port).
|
|
15
16
|
--publish-activity Also publish an "activity" artifact with tool call ids, titles, kinds and
|
|
16
|
-
statuses (no inputs or outputs)
|
|
17
|
+
statuses (no inputs or outputs) and the model's reasoning text.
|
|
18
|
+
May reveal paths, commands or workspace data.
|
|
19
|
+
--permissions <reject|ask>
|
|
20
|
+
reject (default) rejects every OpenCode permission request. ask pauses the
|
|
21
|
+
task as input-required until a client answers allow or reject; anyone who
|
|
22
|
+
can reach this unauthenticated port can then approve tool runs.
|
|
17
23
|
--help, -h Show help without starting OpenCode.
|
|
18
24
|
--version, -v Print package version without starting OpenCode.
|
|
19
25
|
|
package/dist/src/executor.js
CHANGED
|
@@ -3,8 +3,19 @@ import { Role, TaskState } from "@a2a-js/sdk";
|
|
|
3
3
|
import { TaskNotCancelableError } from "@a2a-js/sdk/errors";
|
|
4
4
|
import { AgentEvent, } from "@a2a-js/sdk/server";
|
|
5
5
|
import { BridgeError } from "./bridge-error.js";
|
|
6
|
+
import { createPermissionDesk } from "./permission-desk.js";
|
|
7
|
+
import { parseAnswer } from "./permission.js";
|
|
6
8
|
export const EXPLICIT_CONTEXT = "opencode.explicitContext";
|
|
7
9
|
export const ACTIVITY_EXTENSION = "urn:opencode-a2a-lite:activity:v1";
|
|
10
|
+
export const PERMISSIONS_EXTENSION = "urn:opencode-a2a-lite:permissions:v1";
|
|
11
|
+
function permissionPart(requestId, request) {
|
|
12
|
+
return {
|
|
13
|
+
content: { $case: "data", value: { permission: { requestId, ...request } } },
|
|
14
|
+
mediaType: "application/json",
|
|
15
|
+
filename: "",
|
|
16
|
+
metadata: undefined,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
8
19
|
function dataPart(value) {
|
|
9
20
|
return {
|
|
10
21
|
content: { $case: "data", value },
|
|
@@ -26,7 +37,25 @@ export function createAgentExecutor(bridge, options = {}) {
|
|
|
26
37
|
if (!Number.isSafeInteger(maximum) || maximum < 1)
|
|
27
38
|
throw new Error("Invalid context capacity");
|
|
28
39
|
const sessions = new Map();
|
|
40
|
+
const desk = createPermissionDesk(options.permissionTimeoutMs ?? 120_000);
|
|
29
41
|
let active;
|
|
42
|
+
// Handles a message that answers a pending permission request; true when it was consumed.
|
|
43
|
+
async function resume(ctx, status) {
|
|
44
|
+
const state = ctx.task?.status?.state;
|
|
45
|
+
const entry = desk.pending(ctx.taskId);
|
|
46
|
+
if (!entry) {
|
|
47
|
+
// A live task must not be failed by a stray follow-up; the snapshot is the whole reply.
|
|
48
|
+
return (state === TaskState.TASK_STATE_WORKING || state === TaskState.TASK_STATE_INPUT_REQUIRED);
|
|
49
|
+
}
|
|
50
|
+
const answer = parseAnswer(ctx.userMessage.parts, entry.requestId, entry.options);
|
|
51
|
+
if ("error" in answer) {
|
|
52
|
+
status(TaskState.TASK_STATE_INPUT_REQUIRED, `${answer.error}. Reply allow or reject.`);
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
entry.settle(answer.optionId);
|
|
56
|
+
await entry.finished;
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
30
59
|
async function execute(ctx, bus) {
|
|
31
60
|
const taskId = ctx.taskId;
|
|
32
61
|
const contextId = ctx.contextId;
|
|
@@ -36,7 +65,8 @@ export function createAgentExecutor(bridge, options = {}) {
|
|
|
36
65
|
let emitted = false;
|
|
37
66
|
let activityEmitted = false;
|
|
38
67
|
let terminal = false;
|
|
39
|
-
|
|
68
|
+
const finished = Promise.withResolvers();
|
|
69
|
+
function status(state, text, extra = []) {
|
|
40
70
|
bus.publish(AgentEvent.statusUpdate({
|
|
41
71
|
taskId,
|
|
42
72
|
contextId,
|
|
@@ -49,7 +79,7 @@ export function createAgentExecutor(bridge, options = {}) {
|
|
|
49
79
|
taskId,
|
|
50
80
|
contextId,
|
|
51
81
|
role: Role.ROLE_AGENT,
|
|
52
|
-
parts: [textPart(text)],
|
|
82
|
+
parts: [textPart(text), ...extra],
|
|
53
83
|
metadata: undefined,
|
|
54
84
|
extensions: [],
|
|
55
85
|
referenceTaskIds: [],
|
|
@@ -85,7 +115,7 @@ export function createAgentExecutor(bridge, options = {}) {
|
|
|
85
115
|
artifact: {
|
|
86
116
|
artifactId: activityId,
|
|
87
117
|
name: "activity",
|
|
88
|
-
description: "Tool
|
|
118
|
+
description: "Tool call summaries and reasoning text",
|
|
89
119
|
parts: [entry ? dataPart(entry) : textPart("")],
|
|
90
120
|
metadata: undefined,
|
|
91
121
|
extensions: [ACTIVITY_EXTENSION],
|
|
@@ -96,8 +126,15 @@ export function createAgentExecutor(bridge, options = {}) {
|
|
|
96
126
|
}));
|
|
97
127
|
activityEmitted = true;
|
|
98
128
|
}
|
|
129
|
+
function clearPending() {
|
|
130
|
+
if (meta["opencode.permissionPending"] !== "true")
|
|
131
|
+
return;
|
|
132
|
+
meta["opencode.permissionPending"] = "false";
|
|
133
|
+
meta["opencode.permissionRequestId"] = "";
|
|
134
|
+
}
|
|
99
135
|
function finish(state, text) {
|
|
100
136
|
terminal = true;
|
|
137
|
+
clearPending();
|
|
101
138
|
if (emitted)
|
|
102
139
|
chunk("", true);
|
|
103
140
|
if (activityEmitted)
|
|
@@ -116,6 +153,8 @@ export function createAgentExecutor(bridge, options = {}) {
|
|
|
116
153
|
artifacts: [],
|
|
117
154
|
metadata: undefined,
|
|
118
155
|
}));
|
|
156
|
+
if (options.permissions === "ask" && ctx.task && (await resume(ctx, status)))
|
|
157
|
+
return;
|
|
119
158
|
const message = ctx.userMessage;
|
|
120
159
|
if (ctx.task || message.referenceTaskIds.length) {
|
|
121
160
|
finish(TaskState.TASK_STATE_FAILED, "Use contextId without taskId or task references for follow-up turns");
|
|
@@ -167,14 +206,31 @@ export function createAgentExecutor(bridge, options = {}) {
|
|
|
167
206
|
if (!terminal)
|
|
168
207
|
activity(entry);
|
|
169
208
|
}
|
|
209
|
+
: undefined, options.permissions === "ask"
|
|
210
|
+
? async (request) => {
|
|
211
|
+
const entry = desk.open(taskId, request.options, finished.promise);
|
|
212
|
+
meta["opencode.permissionPending"] = "true";
|
|
213
|
+
meta["opencode.permissionRequestId"] = entry.requestId;
|
|
214
|
+
const label = request.kind ? `${request.title} (${request.kind})` : request.title;
|
|
215
|
+
status(TaskState.TASK_STATE_INPUT_REQUIRED, `Allow "${label}"? Reply allow or reject.`, [permissionPart(entry.requestId, request)]);
|
|
216
|
+
const answer = await entry.answer;
|
|
217
|
+
clearPending();
|
|
218
|
+
if (!terminal && !record.cancellation)
|
|
219
|
+
status(TaskState.TASK_STATE_WORKING);
|
|
220
|
+
return answer;
|
|
221
|
+
}
|
|
170
222
|
: undefined);
|
|
171
223
|
meta["opencode.stopReason"] = response.stopReason;
|
|
224
|
+
if (response.permissionDenied)
|
|
225
|
+
meta["opencode.permissionDenied"] = "true";
|
|
172
226
|
if (response.stopReason === "end_turn") {
|
|
173
227
|
finish(TaskState.TASK_STATE_COMPLETED);
|
|
174
228
|
return;
|
|
175
229
|
}
|
|
176
230
|
if (response.stopReason === "cancelled") {
|
|
177
|
-
finish(TaskState.TASK_STATE_CANCELED
|
|
231
|
+
finish(TaskState.TASK_STATE_CANCELED, response.permissionDenied && !record.cancellation
|
|
232
|
+
? "Permission request rejected; the tool run was not approved"
|
|
233
|
+
: undefined);
|
|
178
234
|
return;
|
|
179
235
|
}
|
|
180
236
|
sessions.delete(contextId);
|
|
@@ -187,6 +243,8 @@ export function createAgentExecutor(bridge, options = {}) {
|
|
|
187
243
|
finish(TaskState.TASK_STATE_FAILED, error instanceof BridgeError ? error.message : "ACP execution failed");
|
|
188
244
|
}
|
|
189
245
|
finally {
|
|
246
|
+
desk.release(taskId);
|
|
247
|
+
finished.resolve();
|
|
190
248
|
record.terminal = true;
|
|
191
249
|
await record.cancellation?.catch(() => undefined);
|
|
192
250
|
if (active === record)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
/** Tracks the one permission request awaiting a human answer per task. */
|
|
3
|
+
export function createPermissionDesk(timeoutMs) {
|
|
4
|
+
const waiting = new Map();
|
|
5
|
+
function open(taskId, options, finished) {
|
|
6
|
+
const gate = Promise.withResolvers();
|
|
7
|
+
const entry = {
|
|
8
|
+
requestId: randomUUID(),
|
|
9
|
+
options,
|
|
10
|
+
answer: gate.promise,
|
|
11
|
+
finished,
|
|
12
|
+
answered: false,
|
|
13
|
+
timer: setTimeout(() => entry.settle(undefined), timeoutMs),
|
|
14
|
+
settle(optionId) {
|
|
15
|
+
if (entry.answered)
|
|
16
|
+
return;
|
|
17
|
+
entry.answered = true;
|
|
18
|
+
clearTimeout(entry.timer);
|
|
19
|
+
gate.resolve(optionId);
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
waiting.set(taskId, entry);
|
|
23
|
+
return entry;
|
|
24
|
+
}
|
|
25
|
+
return {
|
|
26
|
+
open,
|
|
27
|
+
// Only an unanswered request can accept an answer; a second answer finds nothing.
|
|
28
|
+
pending(taskId) {
|
|
29
|
+
const entry = waiting.get(taskId);
|
|
30
|
+
return entry && !entry.answered ? entry : undefined;
|
|
31
|
+
},
|
|
32
|
+
release(taskId) {
|
|
33
|
+
waiting.get(taskId)?.settle(undefined);
|
|
34
|
+
waiting.delete(taskId);
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
const OFFERED = new Set(["allow_once", "reject_once", "reject_always"]);
|
|
2
|
+
const ALLOW = new Set(["allow", "approve", "yes"]);
|
|
3
|
+
const REJECT = new Set(["reject", "deny", "no"]);
|
|
4
|
+
// allow_always would change OpenCode's permission rules for later sessions, so it is never offered.
|
|
5
|
+
export function offeredOptions(options) {
|
|
6
|
+
return options.filter((option) => OFFERED.has(option.kind));
|
|
7
|
+
}
|
|
8
|
+
export function decide(options, chosen) {
|
|
9
|
+
const offered = offeredOptions(options);
|
|
10
|
+
const pick = offered.find((option) => option.optionId === chosen);
|
|
11
|
+
if (pick?.kind === "allow_once")
|
|
12
|
+
return { outcome: "selected", optionId: pick.optionId, denied: false };
|
|
13
|
+
const reject = pick ?? offered.find((option) => option.kind.startsWith("reject"));
|
|
14
|
+
return reject
|
|
15
|
+
? { outcome: "selected", optionId: reject.optionId, denied: true }
|
|
16
|
+
: { outcome: "cancelled", denied: true };
|
|
17
|
+
}
|
|
18
|
+
function dataAnswer(value) {
|
|
19
|
+
if (typeof value !== "object" || value === null || !("permissionResponse" in value))
|
|
20
|
+
return;
|
|
21
|
+
const answer = value.permissionResponse;
|
|
22
|
+
if (typeof answer !== "object" || answer === null)
|
|
23
|
+
return;
|
|
24
|
+
const { requestId, optionId } = answer;
|
|
25
|
+
return {
|
|
26
|
+
...(typeof requestId === "string" ? { requestId } : {}),
|
|
27
|
+
...(typeof optionId === "string" ? { optionId } : {}),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
export function parseAnswer(parts, requestId, options) {
|
|
31
|
+
const offered = offeredOptions(options);
|
|
32
|
+
const data = parts.flatMap((part) => part.content?.$case === "data" ? [dataAnswer(part.content.value)] : [])[0];
|
|
33
|
+
if (data) {
|
|
34
|
+
if (data.requestId !== requestId)
|
|
35
|
+
return { error: "The permission request id does not match" };
|
|
36
|
+
const pick = offered.find((option) => option.optionId === data.optionId);
|
|
37
|
+
return pick ? { optionId: pick.optionId } : { error: "The option is not offered" };
|
|
38
|
+
}
|
|
39
|
+
const text = parts
|
|
40
|
+
.map((part) => (part.content?.$case === "text" ? part.content.value : ""))
|
|
41
|
+
.join(" ")
|
|
42
|
+
.trim()
|
|
43
|
+
.toLowerCase();
|
|
44
|
+
const wanted = ALLOW.has(text) ? "allow_once" : REJECT.has(text) ? "reject" : undefined;
|
|
45
|
+
const pick = offered.find((option) => option.kind.startsWith(wanted ?? "\0"));
|
|
46
|
+
return pick ? { optionId: pick.optionId } : { error: "Unrecognized answer" };
|
|
47
|
+
}
|
|
48
|
+
// Asks the operator while holding the prompt deadline; cancellation or a failing callback means no answer.
|
|
49
|
+
export async function askOperator(turn, params) {
|
|
50
|
+
if (!turn.onPermission)
|
|
51
|
+
return;
|
|
52
|
+
turn.hold.count += 1;
|
|
53
|
+
try {
|
|
54
|
+
return await Promise.race([
|
|
55
|
+
turn.released.promise,
|
|
56
|
+
turn.onPermission({
|
|
57
|
+
title: params.toolCall.title ?? "tool",
|
|
58
|
+
...(params.toolCall.kind ? { kind: params.toolCall.kind } : {}),
|
|
59
|
+
options: offeredOptions(params.options),
|
|
60
|
+
}),
|
|
61
|
+
]);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
finally {
|
|
67
|
+
turn.hold.count -= 1;
|
|
68
|
+
if (!turn.hold.count)
|
|
69
|
+
turn.hold.rearm?.();
|
|
70
|
+
}
|
|
71
|
+
}
|
|
@@ -5,6 +5,7 @@ export function createRequestHandler(card, executor, timeout) {
|
|
|
5
5
|
const memory = new InMemoryTaskStore();
|
|
6
6
|
const buses = new DefaultExecutionEventBusManager();
|
|
7
7
|
const listeners = new Map();
|
|
8
|
+
const interrupted = (task) => task.status?.state === TaskState.TASK_STATE_INPUT_REQUIRED;
|
|
8
9
|
const terminal = (task) => task.status &&
|
|
9
10
|
![TaskState.TASK_STATE_SUBMITTED, TaskState.TASK_STATE_WORKING].includes(task.status.state);
|
|
10
11
|
const store = {
|
|
@@ -20,7 +21,8 @@ export function createRequestHandler(card, executor, timeout) {
|
|
|
20
21
|
// SDK 1.3's CancelTask creates a second ResultManager on the live bus, so
|
|
21
22
|
// cancellation-time artifact appends are persisted twice. Keep one consumer;
|
|
22
23
|
// await that consumer's terminal save through the public TaskStore interface.
|
|
23
|
-
handler.cancelTask
|
|
24
|
+
const stock = handler.cancelTask.bind(handler);
|
|
25
|
+
const cancelWithOwner = async (params, context) => {
|
|
24
26
|
const task = await handler.getTask(params, context);
|
|
25
27
|
if (task.status?.state === TaskState.TASK_STATE_CANCELED)
|
|
26
28
|
return task;
|
|
@@ -51,5 +53,10 @@ export function createRequestHandler(card, executor, timeout) {
|
|
|
51
53
|
listeners.delete(params.id);
|
|
52
54
|
}
|
|
53
55
|
};
|
|
56
|
+
// The original event consumer ended at INPUT_REQUIRED, so nothing else would persist the
|
|
57
|
+
// canceled state; the stock path attaches its own single consumer, which cannot duplicate.
|
|
58
|
+
handler.cancelTask = async (params, context) => interrupted(await handler.getTask(params, context))
|
|
59
|
+
? stock(params, context)
|
|
60
|
+
: cancelWithOwner(params, context);
|
|
54
61
|
return handler;
|
|
55
62
|
}
|
package/dist/src/server.js
CHANGED
|
@@ -7,7 +7,7 @@ import manifest from "../package.json" with { type: "json" };
|
|
|
7
7
|
import { A2A_PROTOCOL_VERSION, AGENT_CARD_PATH } from "@a2a-js/sdk";
|
|
8
8
|
import { agentCardHandler, jsonRpcHandler, UserBuilder } from "@a2a-js/sdk/server/express";
|
|
9
9
|
import { createAcpBridge } from "./acp-client.js";
|
|
10
|
-
import { ACTIVITY_EXTENSION, createAgentExecutor, EXPLICIT_CONTEXT, } from "./executor.js";
|
|
10
|
+
import { ACTIVITY_EXTENSION, createAgentExecutor, EXPLICIT_CONTEXT, PERMISSIONS_EXTENSION, } from "./executor.js";
|
|
11
11
|
import { createRequestHandler } from "./request-handler.js";
|
|
12
12
|
import { parseOptions } from "./cli-options.js";
|
|
13
13
|
import { reportStartupError, StartupError } from "./startup-error.js";
|
|
@@ -104,16 +104,28 @@ export function createGateway(options) {
|
|
|
104
104
|
streaming: true,
|
|
105
105
|
pushNotifications: false,
|
|
106
106
|
extendedAgentCard: false,
|
|
107
|
-
extensions:
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
107
|
+
extensions: [
|
|
108
|
+
...(options.executor?.activity
|
|
109
|
+
? [
|
|
110
|
+
{
|
|
111
|
+
uri: ACTIVITY_EXTENSION,
|
|
112
|
+
description: "Adds an optional 'activity' artifact of tool call ids, titles, kinds, statuses and reasoning text.",
|
|
113
|
+
required: false,
|
|
114
|
+
params: undefined,
|
|
115
|
+
},
|
|
116
|
+
]
|
|
117
|
+
: []),
|
|
118
|
+
...(options.executor?.permissions === "ask"
|
|
119
|
+
? [
|
|
120
|
+
{
|
|
121
|
+
uri: PERMISSIONS_EXTENSION,
|
|
122
|
+
description: "A permission request pauses the task as input-required; answer on the same task with 'allow' or 'reject', or a data part {permissionResponse:{requestId,optionId}}.",
|
|
123
|
+
required: false,
|
|
124
|
+
params: undefined,
|
|
125
|
+
},
|
|
126
|
+
]
|
|
127
|
+
: []),
|
|
128
|
+
],
|
|
117
129
|
},
|
|
118
130
|
securitySchemes: {},
|
|
119
131
|
securityRequirements: [],
|
|
@@ -200,8 +212,10 @@ export async function launchGateway(options) {
|
|
|
200
212
|
const cardUrl = new URL(".well-known/agent-card.json", ready.url).href;
|
|
201
213
|
status("ready", `gateway · ${ready.url}`);
|
|
202
214
|
status("workspace", options.workspace);
|
|
215
|
+
if (options.executor?.permissions === "ask")
|
|
216
|
+
status("permissions", "ask · any client that can reach this port can approve tool runs");
|
|
203
217
|
if (options.executor?.activity)
|
|
204
|
-
status("activity", "tool
|
|
218
|
+
status("activity", "tool calls and reasoning text are published; they may reveal paths, commands or workspace data");
|
|
205
219
|
status("agent card", cardUrl);
|
|
206
220
|
status("connect", `a2a send -a ${ready.url} "Reply with a short greeting." --stream`);
|
|
207
221
|
status("stop", "press Ctrl-C to stop the gateway");
|