@bridgebrew/harness-acp 0.0.0-stage → 0.0.1
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/acp.ts +126 -0
- package/package.json +71 -4
- package/server.ts +843 -0
- package/tsconfig.json +1 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 bridgebrew
|
|
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/acp.ts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// A small JSON-RPC 2.0 client over newline-delimited JSON (ACP's stdio framing: one message per line on stdout, logs on
|
|
2
|
+
// stderr): requests by id, notifications, and the agent's own requests answered by a handler map (an unknown one gets
|
|
3
|
+
// -32601). Protocol-agnostic, so later ACP features (cancel, load, decisions) only add methods and handlers.
|
|
4
|
+
|
|
5
|
+
import { isRecord } from '@bridge/kernel/json';
|
|
6
|
+
|
|
7
|
+
export type Handler = (params: unknown) => unknown;
|
|
8
|
+
|
|
9
|
+
export interface Connection {
|
|
10
|
+
request(method: string, params: unknown): Promise<unknown>;
|
|
11
|
+
notify(method: string, params: unknown): void;
|
|
12
|
+
/** Feeds stdout text, in any chunking. */
|
|
13
|
+
receive(text: string): void;
|
|
14
|
+
/** Rejects every pending request with `error` and refuses new ones. */
|
|
15
|
+
close(error: Error): void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** `write` sends one framed line; `onNotification` hears the agent's notifications; `handlers` answer its requests. */
|
|
19
|
+
export function connect({
|
|
20
|
+
write,
|
|
21
|
+
onNotification,
|
|
22
|
+
handlers = {},
|
|
23
|
+
log = console,
|
|
24
|
+
}: {
|
|
25
|
+
write: (line: string) => unknown;
|
|
26
|
+
onNotification: (method: string, params: unknown) => void;
|
|
27
|
+
handlers?: Record<string, Handler>;
|
|
28
|
+
/** Where a dispatch failure is said: the plugin's `ctx.logger` (AD-21). */
|
|
29
|
+
log?: { error: (...args: unknown[]) => void };
|
|
30
|
+
}): Connection {
|
|
31
|
+
const pending = new Map<
|
|
32
|
+
number,
|
|
33
|
+
{ resolve: (value: unknown) => void; reject: (error: Error) => void }
|
|
34
|
+
>();
|
|
35
|
+
let next = 0;
|
|
36
|
+
let closed: Error | undefined;
|
|
37
|
+
let partial = '';
|
|
38
|
+
const send = (message: object) => {
|
|
39
|
+
if (closed) return;
|
|
40
|
+
// A write that fails (the process is gone) shows up as its exit; nothing to do here.
|
|
41
|
+
Promise.resolve(write(`${JSON.stringify({ jsonrpc: '2.0', ...message })}\n`)).catch(() => {});
|
|
42
|
+
};
|
|
43
|
+
const dispatch = (message: Record<string, unknown>) => {
|
|
44
|
+
if (typeof message.method === 'string') {
|
|
45
|
+
if (message.id === undefined || message.id === null)
|
|
46
|
+
return onNotification(message.method, message.params);
|
|
47
|
+
const handler = Object.hasOwn(handlers, message.method)
|
|
48
|
+
? handlers[message.method]
|
|
49
|
+
: undefined;
|
|
50
|
+
if (!handler)
|
|
51
|
+
return send({
|
|
52
|
+
id: message.id,
|
|
53
|
+
error: { code: -32601, message: `method not found: ${message.method}` },
|
|
54
|
+
});
|
|
55
|
+
Promise.resolve()
|
|
56
|
+
.then(() => handler(message.params))
|
|
57
|
+
.then(
|
|
58
|
+
(result) => send({ id: message.id, result: result ?? null }),
|
|
59
|
+
(error: unknown) =>
|
|
60
|
+
send({
|
|
61
|
+
id: message.id,
|
|
62
|
+
error: {
|
|
63
|
+
code: -32603,
|
|
64
|
+
message: error instanceof Error ? error.message : String(error),
|
|
65
|
+
},
|
|
66
|
+
}),
|
|
67
|
+
);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
const id = message.id;
|
|
71
|
+
if (typeof id !== 'number') return;
|
|
72
|
+
const call = pending.get(id);
|
|
73
|
+
if (!call) return;
|
|
74
|
+
pending.delete(id);
|
|
75
|
+
// The error keeps the agent's code (ACP's auth-required is -32000).
|
|
76
|
+
const failure = message.error;
|
|
77
|
+
if (failure) {
|
|
78
|
+
const detail = isRecord(failure) ? failure : {};
|
|
79
|
+
const said = detail.message ?? `error ${detail.code}`;
|
|
80
|
+
call.reject(
|
|
81
|
+
Object.assign(new Error(typeof said === 'string' ? said : String(said)), {
|
|
82
|
+
code: detail.code,
|
|
83
|
+
}),
|
|
84
|
+
);
|
|
85
|
+
} else call.resolve(message.result);
|
|
86
|
+
};
|
|
87
|
+
const parse = (line: string) => {
|
|
88
|
+
if (!line.trim()) return;
|
|
89
|
+
let message: unknown;
|
|
90
|
+
try {
|
|
91
|
+
message = JSON.parse(line);
|
|
92
|
+
} catch {
|
|
93
|
+
return; // ponytail: a non-JSON line on stdout is dropped; log it if agents turn out to print there
|
|
94
|
+
}
|
|
95
|
+
// A throw (a listener's bug) loses this message only; the chunk's other lines still go through.
|
|
96
|
+
try {
|
|
97
|
+
if (isRecord(message)) dispatch(message);
|
|
98
|
+
} catch (error) {
|
|
99
|
+
log.error('acp: a message failed to dispatch', error);
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
return {
|
|
103
|
+
request(method, params) {
|
|
104
|
+
if (closed) return Promise.reject(closed);
|
|
105
|
+
const id = ++next;
|
|
106
|
+
return new Promise((resolve, reject) => {
|
|
107
|
+
pending.set(id, { resolve, reject });
|
|
108
|
+
send({ id, method, params });
|
|
109
|
+
});
|
|
110
|
+
},
|
|
111
|
+
notify: (method, params) => send({ method, params }),
|
|
112
|
+
receive(text) {
|
|
113
|
+
const lines = (partial + text).split('\n');
|
|
114
|
+
partial = lines.pop()!;
|
|
115
|
+
for (const line of lines) parse(line);
|
|
116
|
+
},
|
|
117
|
+
close(error) {
|
|
118
|
+
// The agent's last line, written without its newline just before it exited, is still read.
|
|
119
|
+
if (!closed) parse(partial);
|
|
120
|
+
partial = '';
|
|
121
|
+
closed ??= error;
|
|
122
|
+
for (const call of pending.values()) call.reject(error);
|
|
123
|
+
pending.clear();
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,73 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bridgebrew/harness-acp",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"description": "Lets the harness run any agent that speaks the Agent Client Protocol, such as Hermes.",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"bridge-plugin"
|
|
8
|
+
],
|
|
9
|
+
"type": "module",
|
|
10
|
+
"files": [
|
|
11
|
+
"*.json",
|
|
12
|
+
"*.ts",
|
|
13
|
+
"!**/*.test.ts",
|
|
14
|
+
"!**/*.test.tsx"
|
|
15
|
+
],
|
|
16
|
+
"bridge": {
|
|
17
|
+
"kind": "service",
|
|
18
|
+
"category": "standard",
|
|
19
|
+
"title": "ACP driver",
|
|
20
|
+
"icon": "plug",
|
|
21
|
+
"domain": "agents",
|
|
22
|
+
"server": "./server.ts",
|
|
23
|
+
"requires": {
|
|
24
|
+
"harness": {}
|
|
25
|
+
},
|
|
26
|
+
"driver": {
|
|
27
|
+
"name": "acp",
|
|
28
|
+
"title": "ACP agent",
|
|
29
|
+
"description": "Any agent that speaks the Agent Client Protocol over its standard input and output (Hermes: hermes acp).",
|
|
30
|
+
"config": {
|
|
31
|
+
"type": "object",
|
|
32
|
+
"properties": {
|
|
33
|
+
"command": {
|
|
34
|
+
"type": "string",
|
|
35
|
+
"title": "Command",
|
|
36
|
+
"minLength": 1,
|
|
37
|
+
"description": "The program to start, on the PATH or as an absolute path."
|
|
38
|
+
},
|
|
39
|
+
"args": {
|
|
40
|
+
"type": "array",
|
|
41
|
+
"items": {
|
|
42
|
+
"type": "string"
|
|
43
|
+
},
|
|
44
|
+
"title": "Arguments",
|
|
45
|
+
"description": "Passed to the command, in order (Hermes: acp)."
|
|
46
|
+
},
|
|
47
|
+
"decisionTimeoutMs": {
|
|
48
|
+
"type": "integer",
|
|
49
|
+
"minimum": 0,
|
|
50
|
+
"title": "Decision timeout (ms)",
|
|
51
|
+
"description": "How long a permission request waits for an answer; empty = until the turn ends."
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
"required": [
|
|
55
|
+
"command"
|
|
56
|
+
]
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
"provenance": "official"
|
|
60
|
+
},
|
|
61
|
+
"peerDependencies": {
|
|
62
|
+
"@bridge/kernel": ">=0.0.1",
|
|
63
|
+
"cordis": "4.0.0-rc.11"
|
|
64
|
+
},
|
|
65
|
+
"releaseStage": "dev",
|
|
66
|
+
"scripts": {
|
|
67
|
+
"test": "node ../bridge/node_modules/vitest/vitest.mjs run --config ../scripts/vitest.config.ts",
|
|
68
|
+
"typecheck": "bridge plugin check ."
|
|
69
|
+
},
|
|
70
|
+
"engines": {
|
|
71
|
+
"bridge": ">=0.0.1-nightly.20261117.1"
|
|
72
|
+
}
|
|
73
|
+
}
|
package/server.ts
ADDED
|
@@ -0,0 +1,843 @@
|
|
|
1
|
+
// The `acp` driver (AD-28): runs an ACP agent (`command args`, from the harness's settings) through the host
|
|
2
|
+
// (`processes`, AD-27), one process per session, and speaks ACP over its stdio with ./acp.ts. Every `session/update`
|
|
3
|
+
// kind Bridge has an event for is mapped; a permission request becomes a `decision` answered through `answer` (or
|
|
4
|
+
// `cancelled` once the harness's `decisionTimeoutMs` passes, its `expiresAt`); a
|
|
5
|
+
// session resumes with `session/load` when the agent can (its replay is dropped: Bridge's log is the history, AD-29).
|
|
6
|
+
// Models (the current one first), permission modes and capabilities come from a probe (a throwaway `session/new`), cached
|
|
7
|
+
// for the plugin's life. A mode given to `open` is set with `session/set_mode` once the session is created (unless already
|
|
8
|
+
// current) or loaded (always: an agent such as Hermes forgets it across a load); `setMode` sets it the same way, with the request deadline.
|
|
9
|
+
// A session is `closed` once its process exited; a turn whose process is killed because this plugin disposes (a reload)
|
|
10
|
+
// ends `interrupted`. An agent that stops answering is ended: every request but `session/prompt` has a deadline
|
|
11
|
+
// (`requestMs`, restarted by each `session/update` of a `session/load` replay; a load past it starts a fresh agent with
|
|
12
|
+
// `session/new`), and a turn still running `stopMs` after `interrupt` is ended `interrupted`. `session/prompt` has no
|
|
13
|
+
// total deadline (a working turn may stream for hours), but a turn whose agent sends nothing for `silentMs` (restarted
|
|
14
|
+
// by each `session/update`, paused while a decision is open or a tool call is pending or running) ends `failed`: the
|
|
15
|
+
// agent is sent `session/cancel`, killed `stopMs` later, and the session is closed so the next turn starts a fresh
|
|
16
|
+
// agent. The harness entry's `environment` is set in the agent's process. `status` (plan-providers slice 3) runs
|
|
17
|
+
// `command --version`.
|
|
18
|
+
import { readFileSync } from 'node:fs';
|
|
19
|
+
import { isRecord, listOf } from '@bridge/kernel/json';
|
|
20
|
+
import { tailText } from '@bridge/kernel/text';
|
|
21
|
+
import type { Context } from 'cordis';
|
|
22
|
+
import { connect } from './acp.ts';
|
|
23
|
+
|
|
24
|
+
export const name = 'harness-acp';
|
|
25
|
+
export const inject = ['harness', 'processes'];
|
|
26
|
+
|
|
27
|
+
/** The `harness` contract's driver (`ctx.harness`, typed by the harness plugin; never imported, AD-8). */
|
|
28
|
+
type Driver = Parameters<Context['harness']['register']>[1];
|
|
29
|
+
type Spawn = (options: {
|
|
30
|
+
command: string;
|
|
31
|
+
args: string[];
|
|
32
|
+
cwd: string;
|
|
33
|
+
env?: Record<string, string>;
|
|
34
|
+
}) => ReturnType<Context['processes']['spawn']>;
|
|
35
|
+
type McpServer = Parameters<Driver['open']>[0]['mcpServers'][number];
|
|
36
|
+
type Session = Awaited<ReturnType<Driver['open']>>;
|
|
37
|
+
type HarnessEvent = Parameters<Parameters<Session['prompt']>[1]>[0];
|
|
38
|
+
type Config = Parameters<Driver['capabilities']>[0];
|
|
39
|
+
type Model = { id: string; name: string };
|
|
40
|
+
type Mode = { id: string; name: string; description?: string; current?: true };
|
|
41
|
+
/** The agent's modes in a `session/new` or `session/load` answer, in its order, its current one marked. */
|
|
42
|
+
const modesOf = (result: unknown): Mode[] => {
|
|
43
|
+
const modes = isRecord(result) && isRecord(result.modes) ? result.modes : {};
|
|
44
|
+
return listOf(modes.availableModes).flatMap((each) =>
|
|
45
|
+
isRecord(each) && typeof each.id === 'string'
|
|
46
|
+
? [
|
|
47
|
+
{
|
|
48
|
+
id: each.id,
|
|
49
|
+
name: typeof each.name === 'string' ? each.name : each.id,
|
|
50
|
+
...(typeof each.description === 'string' && { description: each.description }),
|
|
51
|
+
...(each.id === modes.currentModeId && { current: true as const }),
|
|
52
|
+
},
|
|
53
|
+
]
|
|
54
|
+
: [],
|
|
55
|
+
);
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
/** A `session/new` or `session/load` answer's `models`, when it has one. */
|
|
59
|
+
const modelsOf = (result: unknown) =>
|
|
60
|
+
isRecord(result) && isRecord(result.models) ? result.models : {};
|
|
61
|
+
/** An `initialize` answer's `agentCapabilities`, when it has one. */
|
|
62
|
+
const agentCapabilitiesOf = (init: unknown) =>
|
|
63
|
+
isRecord(init) && isRecord(init.agentCapabilities) ? init.agentCapabilities : {};
|
|
64
|
+
|
|
65
|
+
/** The runtime line: who the agent is talking to (T3's `<runtime_info>`). ACP has no system channel, so it is sent
|
|
66
|
+
* with the prompt text; only the harness's own name varies (Hermes, and the like). */
|
|
67
|
+
const runtimeInfo = (harness: string) =>
|
|
68
|
+
`<runtime_info>In case you're asked: you are running in Bridge through the ${harness} harness. No need to mention this otherwise.</runtime_info>`;
|
|
69
|
+
/** The prompt prefix after each `open`: the runtime line, then the session's `instructions`, then each MCP server's,
|
|
70
|
+
* non-empty parts joined by a blank line. Later prompts of the same session carry the runtime line alone (T3 does the
|
|
71
|
+
* same with its `<t3_code_instructions>`). */
|
|
72
|
+
const instructionsText = (
|
|
73
|
+
harness: string,
|
|
74
|
+
instructions: string | undefined,
|
|
75
|
+
servers: McpServer[],
|
|
76
|
+
) =>
|
|
77
|
+
[runtimeInfo(harness), instructions, ...servers.map((each) => each.instructions)]
|
|
78
|
+
.filter((part): part is string => typeof part === 'string' && part !== '')
|
|
79
|
+
.join('\n\n');
|
|
80
|
+
|
|
81
|
+
/** The entry's `environment` as variables, the well-formed names only (T3's rule), later ones winning. */
|
|
82
|
+
export const environmentOf = (entries: unknown): Record<string, string> =>
|
|
83
|
+
Object.fromEntries(
|
|
84
|
+
listOf(entries).flatMap((each) =>
|
|
85
|
+
isRecord(each) &&
|
|
86
|
+
typeof each.name === 'string' &&
|
|
87
|
+
/^[A-Za-z_][A-Za-z0-9_]*$/.test(each.name) &&
|
|
88
|
+
typeof each.value === 'string'
|
|
89
|
+
? [[each.name, each.value]]
|
|
90
|
+
: [],
|
|
91
|
+
),
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
/** ACP's shape of an MCP server: env and headers as `{name, value}` lists. */
|
|
95
|
+
export const toAcp = (server: McpServer) => {
|
|
96
|
+
const pairs = (record: Record<string, string> = {}) =>
|
|
97
|
+
Object.entries(record).map(([name, value]) => ({ name, value }));
|
|
98
|
+
return 'url' in server
|
|
99
|
+
? { type: 'http', name: server.name, url: server.url, headers: pairs(server.headers) }
|
|
100
|
+
: { name: server.name, command: server.command, args: server.args, env: pairs(server.env) };
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
/** The stderr tail an error message carries. */
|
|
104
|
+
const tailOf = (stderr: string) => {
|
|
105
|
+
const lines = stderr.trim().split('\n').slice(-5).join(' | ');
|
|
106
|
+
return lines ? `: ${lines}` : '';
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const STATUS = {
|
|
110
|
+
pending: 'pending',
|
|
111
|
+
in_progress: 'running',
|
|
112
|
+
completed: 'completed',
|
|
113
|
+
failed: 'failed',
|
|
114
|
+
// ACP's newer schema; agents send it on v1 too. The call is over without its outcome.
|
|
115
|
+
cancelled: 'failed',
|
|
116
|
+
} as const;
|
|
117
|
+
const statusOf = (status: unknown) =>
|
|
118
|
+
typeof status === 'string' && Object.hasOwn(STATUS, status)
|
|
119
|
+
? STATUS[status as keyof typeof STATUS]
|
|
120
|
+
: undefined;
|
|
121
|
+
const textOf = (content: unknown) =>
|
|
122
|
+
isRecord(content) && content.type === 'text' && typeof content.text === 'string'
|
|
123
|
+
? content.text
|
|
124
|
+
: undefined;
|
|
125
|
+
/** The text of a tool call's `content` list (`{type: 'content', content: {type: 'text', text}}` entries). */
|
|
126
|
+
const contentText = (content: unknown) => {
|
|
127
|
+
const texts = listOf(content).flatMap((each) => {
|
|
128
|
+
const text = isRecord(each) && each.type === 'content' ? textOf(each.content) : undefined;
|
|
129
|
+
return text === undefined ? [] : [text];
|
|
130
|
+
});
|
|
131
|
+
return texts.length ? texts.join('') : undefined;
|
|
132
|
+
};
|
|
133
|
+
/** Kinds of tool call whose `locations` are files it writes. */
|
|
134
|
+
const WRITES = new Set(['edit', 'delete', 'move']);
|
|
135
|
+
/** The files a tool call writes: its `diff` content's paths, and its `locations` when its kind writes. */
|
|
136
|
+
const pathsOf = (update: Record<string, unknown>, kind: string | undefined) => {
|
|
137
|
+
const diffs = listOf(update.content).map((each) =>
|
|
138
|
+
isRecord(each) && each.type === 'diff' ? each.path : undefined,
|
|
139
|
+
);
|
|
140
|
+
const located = WRITES.has(kind ?? '')
|
|
141
|
+
? listOf(update.locations).map((each) => (isRecord(each) ? each.path : undefined))
|
|
142
|
+
: [];
|
|
143
|
+
const paths = [
|
|
144
|
+
...new Set(
|
|
145
|
+
[...diffs, ...located].filter(
|
|
146
|
+
(path): path is string => typeof path === 'string' && path !== '',
|
|
147
|
+
),
|
|
148
|
+
),
|
|
149
|
+
];
|
|
150
|
+
return paths.length ? paths : undefined;
|
|
151
|
+
};
|
|
152
|
+
/** A tool call's `diff` content as edits, when it has any. */
|
|
153
|
+
const diffsOf = (content: unknown) => {
|
|
154
|
+
const diffs = listOf(content).flatMap((each) =>
|
|
155
|
+
isRecord(each) &&
|
|
156
|
+
each.type === 'diff' &&
|
|
157
|
+
typeof each.path === 'string' &&
|
|
158
|
+
typeof each.newText === 'string'
|
|
159
|
+
? [
|
|
160
|
+
{
|
|
161
|
+
path: each.path,
|
|
162
|
+
...(typeof each.oldText === 'string' && { oldText: each.oldText }),
|
|
163
|
+
newText: each.newText,
|
|
164
|
+
},
|
|
165
|
+
]
|
|
166
|
+
: [],
|
|
167
|
+
);
|
|
168
|
+
return diffs.length ? diffs : undefined;
|
|
169
|
+
};
|
|
170
|
+
const kindOf = (kind: unknown): 'allow' | 'deny' | 'other' =>
|
|
171
|
+
kind === 'allow_once' || kind === 'allow_always'
|
|
172
|
+
? 'allow'
|
|
173
|
+
: kind === 'reject_once' || kind === 'reject_always'
|
|
174
|
+
? 'deny'
|
|
175
|
+
: 'other';
|
|
176
|
+
const CANCELLED = { outcome: { outcome: 'cancelled' } };
|
|
177
|
+
/** The longest `setTimeout` delay (2^31 - 1 ms); a longer one fires at once. */
|
|
178
|
+
const TIMEOUT_MAX = 2_147_483_647;
|
|
179
|
+
/** How long the agent has to answer a request other than `session/prompt`, and to end a turn after `session/cancel`;
|
|
180
|
+
* past either, its process is killed. `silentMs`: how long a running turn's agent may send nothing (no update, no
|
|
181
|
+
* request) while no decision is open and no tool call is pending or running; past it the turn ends `failed`.
|
|
182
|
+
* ponytail: driver constants; a harness setting if an agent needs more. A hung tool call still waits for Stop. */
|
|
183
|
+
const DEADLINES = { requestMs: 60_000, stopMs: 10_000, silentMs: 15 * 60_000 };
|
|
184
|
+
/** A duration as the turn's error says it: whole minutes, else seconds. */
|
|
185
|
+
const spoken = (ms: number) =>
|
|
186
|
+
ms >= 120_000 && !(ms % 60_000) ? `${ms / 60_000} minutes` : `${ms / 1000} s`;
|
|
187
|
+
|
|
188
|
+
/** One `session/update` as a Bridge event, or undefined for a kind Bridge does not map. `tools` holds the turn's tool
|
|
189
|
+
* calls, so an update (only the fields that changed) is sent merged with its call. */
|
|
190
|
+
export function toEvent(
|
|
191
|
+
update: unknown,
|
|
192
|
+
tools: Map<string, Extract<HarnessEvent, { type: 'tool' }>>,
|
|
193
|
+
): HarnessEvent | undefined {
|
|
194
|
+
if (!isRecord(update)) return undefined;
|
|
195
|
+
switch (update.sessionUpdate) {
|
|
196
|
+
case 'agent_message_chunk':
|
|
197
|
+
case 'agent_thought_chunk': {
|
|
198
|
+
const text = textOf(update.content);
|
|
199
|
+
if (text === undefined) return undefined;
|
|
200
|
+
return { type: update.sessionUpdate === 'agent_message_chunk' ? 'text' : 'thought', text };
|
|
201
|
+
}
|
|
202
|
+
case 'tool_call':
|
|
203
|
+
case 'tool_call_update': {
|
|
204
|
+
if (typeof update.toolCallId !== 'string') return undefined;
|
|
205
|
+
const known = tools.get(update.toolCallId);
|
|
206
|
+
const output = update.rawOutput ?? contentText(update.content);
|
|
207
|
+
const kind = typeof update.kind === 'string' ? update.kind : known?.kind;
|
|
208
|
+
const found = pathsOf(update, kind);
|
|
209
|
+
const paths =
|
|
210
|
+
found || known?.paths
|
|
211
|
+
? [...new Set([...(known?.paths ?? []), ...(found ?? [])])]
|
|
212
|
+
: undefined;
|
|
213
|
+
const diffs = diffsOf(update.content) ?? known?.diffs;
|
|
214
|
+
const tool = {
|
|
215
|
+
type: 'tool' as const,
|
|
216
|
+
id: update.toolCallId,
|
|
217
|
+
title: typeof update.title === 'string' ? update.title : (known?.title ?? ''),
|
|
218
|
+
status: statusOf(update.status) ?? known?.status ?? 'pending',
|
|
219
|
+
...(kind !== undefined && { kind }),
|
|
220
|
+
...((update.rawInput ?? known?.input) !== undefined && {
|
|
221
|
+
input: update.rawInput ?? known?.input,
|
|
222
|
+
}),
|
|
223
|
+
...((output ?? known?.output) !== undefined && { output: output ?? known?.output }),
|
|
224
|
+
...(paths && { paths }),
|
|
225
|
+
...(diffs && { diffs }),
|
|
226
|
+
};
|
|
227
|
+
tools.set(tool.id, tool);
|
|
228
|
+
return tool;
|
|
229
|
+
}
|
|
230
|
+
case 'plan': {
|
|
231
|
+
if (!Array.isArray(update.entries)) return undefined;
|
|
232
|
+
return {
|
|
233
|
+
type: 'plan',
|
|
234
|
+
entries: listOf(update.entries).flatMap((entry) =>
|
|
235
|
+
isRecord(entry) && typeof entry.content === 'string'
|
|
236
|
+
? [{ content: entry.content, status: String(entry.status ?? '') }]
|
|
237
|
+
: [],
|
|
238
|
+
),
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
case 'usage_update':
|
|
242
|
+
return {
|
|
243
|
+
type: 'usage',
|
|
244
|
+
...(typeof update.used === 'number' && { used: update.used }),
|
|
245
|
+
...(typeof update.size === 'number' && { size: update.size }),
|
|
246
|
+
};
|
|
247
|
+
default:
|
|
248
|
+
return undefined;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** `disposing` tells whether this plugin is disposing: a turn its agent's exit ends is then `interrupted`. */
|
|
253
|
+
/** `log`: the plugin's `ctx.logger` (AD-21); tests pass their own. */
|
|
254
|
+
/** How long a status check waits for `command --version`. */
|
|
255
|
+
const STATUS_MS = 10_000;
|
|
256
|
+
|
|
257
|
+
export const acpDriver = (
|
|
258
|
+
spawn: Spawn,
|
|
259
|
+
disposing = () => false,
|
|
260
|
+
deadlines: Partial<typeof DEADLINES> = {},
|
|
261
|
+
log: { error: (...args: unknown[]) => void } = console,
|
|
262
|
+
): Driver => {
|
|
263
|
+
const { requestMs, stopMs, silentMs } = { ...DEADLINES, ...deadlines };
|
|
264
|
+
/** Capabilities by config, recorded by every `initialize`: all false until a probe or an `open` ran. */
|
|
265
|
+
const capabilities = new Map<
|
|
266
|
+
string,
|
|
267
|
+
{ resume: boolean; images: boolean; models: boolean; modes: boolean }
|
|
268
|
+
>();
|
|
269
|
+
/** Models by harness + config: the probe, kept for the plugin's life once it succeeded. */
|
|
270
|
+
// ponytail: cached per harness + config for the plugin's life, probed in the first caller's cwd; reload harness-acp
|
|
271
|
+
// to refresh (an agent whose models change, or depend on cwd, needs an expiry or a per-cwd key).
|
|
272
|
+
const probes = new Map<string, Promise<{ models: Model[]; modes: Mode[] }>>();
|
|
273
|
+
const keyOf = (config: Config) => JSON.stringify(config);
|
|
274
|
+
/** Configs whose `decisionTimeoutMs` was refused, said once each. */
|
|
275
|
+
const warned = new Set<string>();
|
|
276
|
+
const record = (config: Config, init: unknown, probed?: { models: Model[]; modes: Mode[] }) => {
|
|
277
|
+
const known = capabilities.get(keyOf(config));
|
|
278
|
+
const agentCapabilities = agentCapabilitiesOf(init);
|
|
279
|
+
capabilities.set(keyOf(config), {
|
|
280
|
+
resume: agentCapabilities.loadSession === true,
|
|
281
|
+
images:
|
|
282
|
+
isRecord(agentCapabilities.promptCapabilities) &&
|
|
283
|
+
agentCapabilities.promptCapabilities.image === true,
|
|
284
|
+
models: probed ? probed.models.length > 0 : (known?.models ?? false),
|
|
285
|
+
modes: probed ? probed.modes.length > 0 : (known?.modes ?? false),
|
|
286
|
+
});
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
/** Starts the agent and initializes it. A missing command and an agent that wants authentication are refused with
|
|
290
|
+
* a fix hint; `ready` maps an error of `session/new` the same way. */
|
|
291
|
+
const start = async ({
|
|
292
|
+
harness,
|
|
293
|
+
config,
|
|
294
|
+
cwd,
|
|
295
|
+
onNotification,
|
|
296
|
+
handlers,
|
|
297
|
+
agentEnv,
|
|
298
|
+
}: {
|
|
299
|
+
harness: string;
|
|
300
|
+
config: Config;
|
|
301
|
+
cwd: string;
|
|
302
|
+
onNotification: (method: string, params: unknown) => void;
|
|
303
|
+
handlers: Record<string, (params: unknown) => unknown>;
|
|
304
|
+
agentEnv?: Record<string, string> | undefined;
|
|
305
|
+
}) => {
|
|
306
|
+
const { command, args = [] } = config;
|
|
307
|
+
if (typeof command !== 'string' || !command)
|
|
308
|
+
throw new Error(`harness ${harness}: settings need a command`);
|
|
309
|
+
if (!Array.isArray(args) || args.some((arg) => typeof arg !== 'string'))
|
|
310
|
+
throw new Error(`harness ${harness}: args must be a list of strings`);
|
|
311
|
+
const env = { ...environmentOf(config.environment), ...agentEnv };
|
|
312
|
+
const agent = await spawn({
|
|
313
|
+
command,
|
|
314
|
+
args: args as string[],
|
|
315
|
+
cwd,
|
|
316
|
+
...(Object.keys(env).length && { env }),
|
|
317
|
+
});
|
|
318
|
+
let stderr = '';
|
|
319
|
+
/** Restarts the deadline of a running `session/load`: its replay is activity. */
|
|
320
|
+
const replaying = new Set<() => void>();
|
|
321
|
+
const connection = connect({
|
|
322
|
+
log,
|
|
323
|
+
write: (line) => agent.write(line),
|
|
324
|
+
onNotification: (method, params) => {
|
|
325
|
+
if (method === 'session/update') for (const restart of replaying) restart();
|
|
326
|
+
onNotification(method, params);
|
|
327
|
+
},
|
|
328
|
+
handlers,
|
|
329
|
+
});
|
|
330
|
+
agent.onOutput((stream, chunk) => {
|
|
331
|
+
if (stream === 'stdout') connection.receive(chunk);
|
|
332
|
+
else stderr = tailText(stderr + chunk, 4096);
|
|
333
|
+
});
|
|
334
|
+
// Output comes before the exit: the tail is complete. 127 is the guard's "could not start the command".
|
|
335
|
+
void agent.exited.then(({ code, signal }) =>
|
|
336
|
+
connection.close(
|
|
337
|
+
new Error(
|
|
338
|
+
code === 127
|
|
339
|
+
? `harness ${harness}: command ${command} could not start${tailOf(stderr)} — install it or fix the harness's command in the harness settings`
|
|
340
|
+
: `${harness} exited (${signal ?? `code ${code}`})${tailOf(stderr)}`,
|
|
341
|
+
),
|
|
342
|
+
),
|
|
343
|
+
);
|
|
344
|
+
/** A request with a deadline: past `requestMs` the agent is killed and the call fails (marked `deadline`). */
|
|
345
|
+
const ask = (method: string, params: unknown) =>
|
|
346
|
+
new Promise<unknown>((resolve, reject) => {
|
|
347
|
+
const expire = () => {
|
|
348
|
+
reject(
|
|
349
|
+
Object.assign(
|
|
350
|
+
new Error(
|
|
351
|
+
`harness ${harness}: the agent did not answer ${method} within ${requestMs / 1000} s`,
|
|
352
|
+
),
|
|
353
|
+
{ deadline: true },
|
|
354
|
+
),
|
|
355
|
+
);
|
|
356
|
+
void agent.kill();
|
|
357
|
+
};
|
|
358
|
+
let timer = setTimeout(expire, requestMs);
|
|
359
|
+
const restart = () => {
|
|
360
|
+
clearTimeout(timer);
|
|
361
|
+
timer = setTimeout(expire, requestMs);
|
|
362
|
+
};
|
|
363
|
+
if (method === 'session/load') replaying.add(restart);
|
|
364
|
+
connection
|
|
365
|
+
.request(method, params)
|
|
366
|
+
.then(resolve, reject)
|
|
367
|
+
.finally(() => {
|
|
368
|
+
clearTimeout(timer);
|
|
369
|
+
replaying.delete(restart);
|
|
370
|
+
});
|
|
371
|
+
});
|
|
372
|
+
/** `initialize`'s auth methods, once it answered. */
|
|
373
|
+
let authMethods: unknown;
|
|
374
|
+
/** Refuses a JSON-RPC error from the agent that asks for authentication (ACP's -32000, or its message says so),
|
|
375
|
+
* with how to set it up: the agent's terminal auth method when it has one. */
|
|
376
|
+
const ready = async <T>(call: Promise<T>) => {
|
|
377
|
+
try {
|
|
378
|
+
return await call;
|
|
379
|
+
} catch (error) {
|
|
380
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
381
|
+
const code = (error as { code?: unknown }).code;
|
|
382
|
+
if (typeof code === 'number' && (code === -32000 || /authenticat/i.test(message))) {
|
|
383
|
+
const terminal = listOf(authMethods).find(
|
|
384
|
+
(method) => isRecord(method) && method.type === 'terminal',
|
|
385
|
+
);
|
|
386
|
+
const extra = isRecord(terminal)
|
|
387
|
+
? listOf(terminal.args).flatMap((arg) => (typeof arg === 'string' ? [arg] : []))
|
|
388
|
+
: [];
|
|
389
|
+
const hint = terminal
|
|
390
|
+
? `run \`${[command, ...(args as string[]), ...extra].join(' ')}\` in a terminal`
|
|
391
|
+
: 'set the agent up in a terminal';
|
|
392
|
+
throw new Error(
|
|
393
|
+
`harness ${harness}: the agent needs authentication — ${message}; ${hint}`,
|
|
394
|
+
);
|
|
395
|
+
}
|
|
396
|
+
throw error;
|
|
397
|
+
}
|
|
398
|
+
};
|
|
399
|
+
try {
|
|
400
|
+
const init = await ready(ask('initialize', { protocolVersion: 1, clientCapabilities: {} }));
|
|
401
|
+
authMethods = isRecord(init) ? init.authMethods : undefined;
|
|
402
|
+
record(config, init);
|
|
403
|
+
return { agent, connection, init, ready, ask };
|
|
404
|
+
} catch (error) {
|
|
405
|
+
await agent.kill();
|
|
406
|
+
throw error;
|
|
407
|
+
}
|
|
408
|
+
};
|
|
409
|
+
|
|
410
|
+
const probe = async ({
|
|
411
|
+
harness,
|
|
412
|
+
config,
|
|
413
|
+
cwd,
|
|
414
|
+
}: {
|
|
415
|
+
harness: string;
|
|
416
|
+
config: Config;
|
|
417
|
+
cwd: string;
|
|
418
|
+
}) => {
|
|
419
|
+
const { agent, init, ready, ask } = await start({
|
|
420
|
+
harness,
|
|
421
|
+
config,
|
|
422
|
+
cwd,
|
|
423
|
+
onNotification: () => {},
|
|
424
|
+
handlers: { 'session/request_permission': () => CANCELLED },
|
|
425
|
+
});
|
|
426
|
+
try {
|
|
427
|
+
const result = await ready(ask('session/new', { cwd, mcpServers: [] }));
|
|
428
|
+
const found = modelsOf(result);
|
|
429
|
+
const models: Model[] = listOf(found.availableModels).flatMap((each) =>
|
|
430
|
+
isRecord(each) && typeof each.modelId === 'string'
|
|
431
|
+
? [
|
|
432
|
+
{
|
|
433
|
+
id: each.modelId,
|
|
434
|
+
name: typeof each.name === 'string' ? each.name : each.modelId,
|
|
435
|
+
...(typeof each.description === 'string' &&
|
|
436
|
+
each.description !== '' && { description: each.description }),
|
|
437
|
+
...(each.modelId === found.currentModelId && { current: true as const }),
|
|
438
|
+
},
|
|
439
|
+
]
|
|
440
|
+
: [],
|
|
441
|
+
);
|
|
442
|
+
// The agent's current model first: a picker's default.
|
|
443
|
+
models.sort(
|
|
444
|
+
(a, b) => Number(b.id === found.currentModelId) - Number(a.id === found.currentModelId),
|
|
445
|
+
);
|
|
446
|
+
const probed = { models, modes: modesOf(result) };
|
|
447
|
+
record(config, init, probed);
|
|
448
|
+
return probed;
|
|
449
|
+
} finally {
|
|
450
|
+
await agent.kill();
|
|
451
|
+
}
|
|
452
|
+
};
|
|
453
|
+
|
|
454
|
+
const probed = (input: { harness: string; config: Config; cwd: string }) => {
|
|
455
|
+
const key = `${input.harness}\n${keyOf(input.config)}`;
|
|
456
|
+
let result = probes.get(key);
|
|
457
|
+
if (!result) {
|
|
458
|
+
result = probe(input);
|
|
459
|
+
probes.set(key, result);
|
|
460
|
+
// A failed probe is not kept: the next call tries again (the agent may be installed or set up since).
|
|
461
|
+
result.catch(() => probes.delete(key));
|
|
462
|
+
}
|
|
463
|
+
return result;
|
|
464
|
+
};
|
|
465
|
+
|
|
466
|
+
const driver: Driver = {
|
|
467
|
+
name: 'acp',
|
|
468
|
+
capabilities: (config) =>
|
|
469
|
+
capabilities.get(keyOf(config)) ?? {
|
|
470
|
+
resume: false,
|
|
471
|
+
images: false,
|
|
472
|
+
models: false,
|
|
473
|
+
modes: false,
|
|
474
|
+
},
|
|
475
|
+
// Cheap: the command found and its `--version`, never an ACP session (the models probe does that). An agent without
|
|
476
|
+
// the flag is installed, its version unknown; 127 is the guard's "could not start".
|
|
477
|
+
async status({ config, cwd }) {
|
|
478
|
+
const { command } = config;
|
|
479
|
+
if (typeof command !== 'string' || !command)
|
|
480
|
+
return {
|
|
481
|
+
installed: false,
|
|
482
|
+
message: 'No command is set.',
|
|
483
|
+
fix: "Set Command to the agent's program (found on the PATH, or an absolute path), e.g. hermes with Arguments acp.",
|
|
484
|
+
};
|
|
485
|
+
const env = environmentOf(config.environment);
|
|
486
|
+
const agent = await spawn({
|
|
487
|
+
command,
|
|
488
|
+
args: ['--version'],
|
|
489
|
+
cwd,
|
|
490
|
+
...(Object.keys(env).length && { env }),
|
|
491
|
+
});
|
|
492
|
+
let stdout = '';
|
|
493
|
+
let stderr = '';
|
|
494
|
+
agent.onOutput((stream, chunk) => {
|
|
495
|
+
if (stream === 'stdout') stdout += chunk;
|
|
496
|
+
else stderr += chunk;
|
|
497
|
+
});
|
|
498
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
499
|
+
const ended = await Promise.race([
|
|
500
|
+
agent.exited,
|
|
501
|
+
new Promise<null>((resolve) => {
|
|
502
|
+
timer = setTimeout(() => resolve(null), STATUS_MS);
|
|
503
|
+
}),
|
|
504
|
+
]);
|
|
505
|
+
clearTimeout(timer);
|
|
506
|
+
if (ended === null) {
|
|
507
|
+
await agent.kill();
|
|
508
|
+
return {
|
|
509
|
+
installed: true,
|
|
510
|
+
message: `${command} --version did not answer in ${STATUS_MS / 1000} s.`,
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
if (ended.code === 127)
|
|
514
|
+
return {
|
|
515
|
+
installed: false,
|
|
516
|
+
message: `${command} could not start${tailOf(stderr)}`,
|
|
517
|
+
fix: `Install ${command}, or set Command to its absolute path.`,
|
|
518
|
+
};
|
|
519
|
+
const version = ended.code === 0 ? stdout.trim().split('\n')[0]?.trim() : undefined;
|
|
520
|
+
return { installed: true, ...(version && { version }) };
|
|
521
|
+
},
|
|
522
|
+
models: async (input) => (await probed(input)).models,
|
|
523
|
+
modes: async (input) => (await probed(input)).modes,
|
|
524
|
+
async open({
|
|
525
|
+
harness,
|
|
526
|
+
config,
|
|
527
|
+
cwd,
|
|
528
|
+
model,
|
|
529
|
+
mode,
|
|
530
|
+
mcpServers,
|
|
531
|
+
resume,
|
|
532
|
+
env: agentEnv,
|
|
533
|
+
instructions,
|
|
534
|
+
}) {
|
|
535
|
+
/** The running turn's listener; also the "a turn is running" flag. */
|
|
536
|
+
let onEvent: ((event: HarnessEvent) => void) | undefined;
|
|
537
|
+
const tools = new Map<string, Extract<HarnessEvent, { type: 'tool' }>>();
|
|
538
|
+
/** Open permission requests by decision id: how to answer, and the option ids offered. */
|
|
539
|
+
const decisions = new Map<
|
|
540
|
+
string,
|
|
541
|
+
{ settle: (answer: unknown) => void; offered: Set<string> }
|
|
542
|
+
>();
|
|
543
|
+
let decided = 0;
|
|
544
|
+
// A `decisionTimeoutMs` that is no positive finite number means no timeout, said once per config.
|
|
545
|
+
const raw = config.decisionTimeoutMs;
|
|
546
|
+
const valid = typeof raw === 'number' && Number.isFinite(raw) && raw > 0;
|
|
547
|
+
if (raw !== undefined && !valid && !warned.has(keyOf(config))) {
|
|
548
|
+
warned.add(keyOf(config));
|
|
549
|
+
log.error(
|
|
550
|
+
`harness ${harness}: decisionTimeoutMs must be a positive number of milliseconds, got ${JSON.stringify(raw) ?? String(raw)}; decisions wait without a timeout`,
|
|
551
|
+
);
|
|
552
|
+
}
|
|
553
|
+
const timeout = valid ? Math.min(raw, TIMEOUT_MAX) : undefined;
|
|
554
|
+
/** Set while a turn runs: ends it once its agent has been silent `silentMs`; `silence` is that end pending. */
|
|
555
|
+
let onSilent: (() => void) | undefined;
|
|
556
|
+
let silence: ReturnType<typeof setTimeout> | undefined;
|
|
557
|
+
/** (Re)starts the running turn's silence bound, paused while a decision is open or a tool call pending or running. */
|
|
558
|
+
const watch = () => {
|
|
559
|
+
clearTimeout(silence);
|
|
560
|
+
silence = undefined;
|
|
561
|
+
const busy = [...tools.values()].some(
|
|
562
|
+
(tool) => tool.status === 'pending' || tool.status === 'running',
|
|
563
|
+
);
|
|
564
|
+
if (onSilent && !decisions.size && !busy) silence = setTimeout(onSilent, silentMs);
|
|
565
|
+
};
|
|
566
|
+
const cancelDecisions = () => {
|
|
567
|
+
for (const { settle } of decisions.values()) settle(CANCELLED);
|
|
568
|
+
decisions.clear();
|
|
569
|
+
};
|
|
570
|
+
const { agent, connection, init, ready, ask } = await start({
|
|
571
|
+
harness,
|
|
572
|
+
config,
|
|
573
|
+
cwd,
|
|
574
|
+
agentEnv,
|
|
575
|
+
// Updates outside a turn (a `session/load` replay included) have no listener and are dropped.
|
|
576
|
+
onNotification: (method, params) => {
|
|
577
|
+
if (method !== 'session/update' || !onEvent) return;
|
|
578
|
+
const event = toEvent(isRecord(params) ? params.update : undefined, tools);
|
|
579
|
+
if (event) onEvent(event);
|
|
580
|
+
watch();
|
|
581
|
+
},
|
|
582
|
+
handlers: {
|
|
583
|
+
'session/request_permission': (params) => {
|
|
584
|
+
if (!onEvent) return CANCELLED;
|
|
585
|
+
const id = `decision-${++decided}`;
|
|
586
|
+
const options = listOf(isRecord(params) ? params.options : undefined).flatMap(
|
|
587
|
+
(option) =>
|
|
588
|
+
isRecord(option) && typeof option.optionId === 'string'
|
|
589
|
+
? [
|
|
590
|
+
{
|
|
591
|
+
id: option.optionId,
|
|
592
|
+
label: typeof option.name === 'string' ? option.name : option.optionId,
|
|
593
|
+
kind: kindOf(option.kind),
|
|
594
|
+
},
|
|
595
|
+
]
|
|
596
|
+
: [],
|
|
597
|
+
);
|
|
598
|
+
// Past the harness's `decisionTimeoutMs` the agent no longer waits: the request is answered cancelled.
|
|
599
|
+
const answer = new Promise((resolve) => {
|
|
600
|
+
const timer =
|
|
601
|
+
timeout === undefined
|
|
602
|
+
? undefined
|
|
603
|
+
: setTimeout(() => {
|
|
604
|
+
decisions.delete(id);
|
|
605
|
+
resolve(CANCELLED);
|
|
606
|
+
watch();
|
|
607
|
+
}, timeout);
|
|
608
|
+
decisions.set(id, {
|
|
609
|
+
settle: (value) => {
|
|
610
|
+
clearTimeout(timer);
|
|
611
|
+
resolve(value);
|
|
612
|
+
},
|
|
613
|
+
offered: new Set(options.map((option) => option.id)),
|
|
614
|
+
});
|
|
615
|
+
});
|
|
616
|
+
watch();
|
|
617
|
+
const toolCall = isRecord(params) && isRecord(params.toolCall) ? params.toolCall : {};
|
|
618
|
+
const title = typeof toolCall.title === 'string' ? toolCall.title : 'Permission';
|
|
619
|
+
onEvent({
|
|
620
|
+
type: 'decision',
|
|
621
|
+
id,
|
|
622
|
+
title,
|
|
623
|
+
options,
|
|
624
|
+
...(timeout !== undefined && {
|
|
625
|
+
expiresAt: new Date(Date.now() + timeout).toISOString(),
|
|
626
|
+
}),
|
|
627
|
+
...(typeof toolCall.toolCallId === 'string' && { tool: toolCall.toolCallId }),
|
|
628
|
+
});
|
|
629
|
+
return answer;
|
|
630
|
+
},
|
|
631
|
+
},
|
|
632
|
+
});
|
|
633
|
+
let closed = false;
|
|
634
|
+
void agent.exited.then(() => {
|
|
635
|
+
closed = true;
|
|
636
|
+
cancelDecisions();
|
|
637
|
+
});
|
|
638
|
+
try {
|
|
639
|
+
const servers = mcpServers.map(toAcp);
|
|
640
|
+
let sessionId: unknown;
|
|
641
|
+
let result: unknown;
|
|
642
|
+
let resumed = false;
|
|
643
|
+
if (
|
|
644
|
+
resume !== undefined &&
|
|
645
|
+
(agentCapabilitiesOf(init).loadSession === true ||
|
|
646
|
+
capabilities.get(keyOf(config))?.resume)
|
|
647
|
+
) {
|
|
648
|
+
try {
|
|
649
|
+
result = await ask('session/load', { sessionId: resume, cwd, mcpServers: servers });
|
|
650
|
+
sessionId = resume;
|
|
651
|
+
resumed = true;
|
|
652
|
+
} catch (error) {
|
|
653
|
+
// An agent past the load's deadline is being killed: a fresh one starts a new session (not resumed).
|
|
654
|
+
if ((error as { deadline?: boolean }).deadline) {
|
|
655
|
+
await agent.kill();
|
|
656
|
+
return driver.open({ harness, config, cwd, model, mode, mcpServers, instructions });
|
|
657
|
+
}
|
|
658
|
+
// ponytail: any other load error falls back to a new session; an agent that died shows up at session/new
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
if (sessionId === undefined) {
|
|
662
|
+
result = await ready(ask('session/new', { cwd, mcpServers: servers }));
|
|
663
|
+
sessionId = isRecord(result) ? result.sessionId : undefined;
|
|
664
|
+
if (typeof sessionId !== 'string')
|
|
665
|
+
throw new Error(`${harness}: session/new answered no sessionId`);
|
|
666
|
+
}
|
|
667
|
+
if (model !== undefined) await ask('session/set_model', { sessionId, modelId: model });
|
|
668
|
+
// A `session/load` answer may leave its modes out: the probe's then.
|
|
669
|
+
const modes = modesOf(result).length
|
|
670
|
+
? modesOf(result)
|
|
671
|
+
: ((await probes.get(`${harness}\n${keyOf(config)}`)?.catch(() => undefined))?.modes ??
|
|
672
|
+
[]);
|
|
673
|
+
let currentMode = modes.find((each) => each.current)?.id;
|
|
674
|
+
// Sent unless a new session answered it current; always after a load (the agent may not have kept it).
|
|
675
|
+
if (mode !== undefined && (resumed || mode !== currentMode)) {
|
|
676
|
+
await ask('session/set_mode', { sessionId, modeId: mode });
|
|
677
|
+
currentMode = mode;
|
|
678
|
+
}
|
|
679
|
+
const current = modelsOf(result).currentModelId;
|
|
680
|
+
/** Set when the agent was killed for not stopping after `interrupt`; `stopTimer` is that kill pending. */
|
|
681
|
+
let forced = false;
|
|
682
|
+
let stopTimer: ReturnType<typeof setTimeout> | undefined;
|
|
683
|
+
/** The next prompt is the first since this `open`: it carries the whole block, later ones the runtime line. */
|
|
684
|
+
let first = true;
|
|
685
|
+
/** The whole block, built once: the runtime line, the session's instructions, each MCP server's. */
|
|
686
|
+
const full = instructionsText(harness, instructions, mcpServers);
|
|
687
|
+
return {
|
|
688
|
+
resume: sessionId as string,
|
|
689
|
+
model: model ?? (typeof current === 'string' ? current : undefined),
|
|
690
|
+
get closed() {
|
|
691
|
+
return closed;
|
|
692
|
+
},
|
|
693
|
+
exited: agent.exited.then(
|
|
694
|
+
() => {},
|
|
695
|
+
() => {},
|
|
696
|
+
),
|
|
697
|
+
get mode() {
|
|
698
|
+
return currentMode;
|
|
699
|
+
},
|
|
700
|
+
resumed,
|
|
701
|
+
async prompt(text, listener, images = []) {
|
|
702
|
+
onEvent = listener;
|
|
703
|
+
forced = false;
|
|
704
|
+
// Past `silentMs` of silence (`watch`) the agent is sent `session/cancel` and killed `stopMs` later; the
|
|
705
|
+
// connection closes now, which fails this turn's `session/prompt` and ends the session.
|
|
706
|
+
onSilent = () => {
|
|
707
|
+
closed = true;
|
|
708
|
+
connection.notify('session/cancel', { sessionId });
|
|
709
|
+
connection.close(
|
|
710
|
+
new Error(`${harness} sent nothing for ${spoken(silentMs)}; the agent was stopped`),
|
|
711
|
+
);
|
|
712
|
+
cancelDecisions();
|
|
713
|
+
setTimeout(() => void agent.kill(), stopMs);
|
|
714
|
+
};
|
|
715
|
+
watch();
|
|
716
|
+
// ACP has no system channel: the first prompt after this open carries the whole block, later ones the
|
|
717
|
+
// runtime line alone (compaction can still drop the block: known limit).
|
|
718
|
+
const block = first ? full : runtimeInfo(harness);
|
|
719
|
+
first = false;
|
|
720
|
+
try {
|
|
721
|
+
// Images only to an agent that said it takes them (`promptCapabilities.image`); the text names their files.
|
|
722
|
+
const pictures = capabilities.get(keyOf(config))?.images
|
|
723
|
+
? images.map(({ type, data }) => ({
|
|
724
|
+
type: 'image',
|
|
725
|
+
mimeType: type,
|
|
726
|
+
data: Buffer.from(data).toString('base64'),
|
|
727
|
+
}))
|
|
728
|
+
: [];
|
|
729
|
+
const answer = await connection.request('session/prompt', {
|
|
730
|
+
sessionId,
|
|
731
|
+
prompt: [
|
|
732
|
+
...pictures,
|
|
733
|
+
{
|
|
734
|
+
type: 'text',
|
|
735
|
+
text: `<bridge_instructions>\n${block}\n</bridge_instructions>\n\n${text}`,
|
|
736
|
+
},
|
|
737
|
+
],
|
|
738
|
+
});
|
|
739
|
+
const stopReason = isRecord(answer) ? answer.stopReason : undefined;
|
|
740
|
+
if (stopReason === 'end_turn') return { reason: 'completed' };
|
|
741
|
+
if (stopReason === 'cancelled') return { reason: 'interrupted' };
|
|
742
|
+
return { reason: 'failed', message: `${harness} stopped: ${String(stopReason)}` };
|
|
743
|
+
} catch (error) {
|
|
744
|
+
if (disposing())
|
|
745
|
+
return {
|
|
746
|
+
reason: 'interrupted',
|
|
747
|
+
message: 'Harness driver stopped during this turn',
|
|
748
|
+
};
|
|
749
|
+
if (forced)
|
|
750
|
+
return { reason: 'interrupted', message: 'the agent did not stop; it was ended' };
|
|
751
|
+
return {
|
|
752
|
+
reason: 'failed',
|
|
753
|
+
message: error instanceof Error ? error.message : String(error),
|
|
754
|
+
};
|
|
755
|
+
} finally {
|
|
756
|
+
clearTimeout(stopTimer);
|
|
757
|
+
stopTimer = undefined;
|
|
758
|
+
onSilent = undefined;
|
|
759
|
+
clearTimeout(silence);
|
|
760
|
+
silence = undefined;
|
|
761
|
+
onEvent = undefined;
|
|
762
|
+
tools.clear();
|
|
763
|
+
cancelDecisions();
|
|
764
|
+
}
|
|
765
|
+
},
|
|
766
|
+
// The agent then answers the prompt `cancelled`, which ends the turn `interrupted`; one that does not within
|
|
767
|
+
// `stopMs` is killed, and its exit ends the turn.
|
|
768
|
+
async interrupt() {
|
|
769
|
+
if (!onEvent) return;
|
|
770
|
+
// Stop owns the turn's end now: the silence bound no longer runs (nor rearms).
|
|
771
|
+
onSilent = undefined;
|
|
772
|
+
clearTimeout(silence);
|
|
773
|
+
connection.notify('session/cancel', { sessionId });
|
|
774
|
+
cancelDecisions();
|
|
775
|
+
stopTimer ??= setTimeout(() => {
|
|
776
|
+
forced = true;
|
|
777
|
+
void agent.kill();
|
|
778
|
+
}, stopMs);
|
|
779
|
+
},
|
|
780
|
+
async answer(decision, option) {
|
|
781
|
+
const pending = decisions.get(decision);
|
|
782
|
+
// ACP asks permissions only: one option, never a question's answers.
|
|
783
|
+
if (typeof option === 'object' && option !== null) return false;
|
|
784
|
+
if (!pending || (option !== null && !pending.offered.has(option))) return false;
|
|
785
|
+
decisions.delete(decision);
|
|
786
|
+
pending.settle(
|
|
787
|
+
option === null ? CANCELLED : { outcome: { outcome: 'selected', optionId: option } },
|
|
788
|
+
);
|
|
789
|
+
watch();
|
|
790
|
+
return true;
|
|
791
|
+
},
|
|
792
|
+
async setMode(id) {
|
|
793
|
+
if (!modes.some((each) => each.id === id))
|
|
794
|
+
throw new Error(`harness ${harness}: the agent has no mode ${id}`);
|
|
795
|
+
await ask('session/set_mode', { sessionId, modeId: id });
|
|
796
|
+
currentMode = id;
|
|
797
|
+
},
|
|
798
|
+
close: async () => {
|
|
799
|
+
closed = true;
|
|
800
|
+
cancelDecisions();
|
|
801
|
+
await agent.kill();
|
|
802
|
+
},
|
|
803
|
+
};
|
|
804
|
+
} catch (error) {
|
|
805
|
+
await agent.kill();
|
|
806
|
+
throw error;
|
|
807
|
+
}
|
|
808
|
+
},
|
|
809
|
+
};
|
|
810
|
+
return driver;
|
|
811
|
+
};
|
|
812
|
+
|
|
813
|
+
/** The manifest's `bridge.driver` (title, description, settings schema), for the Providers screen. */
|
|
814
|
+
const infoOf = () => {
|
|
815
|
+
// oxlint-disable-next-line bridge/no-new-unchecked-cast -- the plugin's own bundled package.json
|
|
816
|
+
const manifest = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')) as {
|
|
817
|
+
bridge?: { driver?: Record<string, unknown> };
|
|
818
|
+
};
|
|
819
|
+
const { title, description, config } = manifest.bridge?.driver ?? {};
|
|
820
|
+
return {
|
|
821
|
+
...(typeof title === 'string' && { title }),
|
|
822
|
+
...(typeof description === 'string' && { description }),
|
|
823
|
+
...(typeof config === 'object' &&
|
|
824
|
+
config !== null && { config: config as Record<string, unknown> }),
|
|
825
|
+
};
|
|
826
|
+
};
|
|
827
|
+
|
|
828
|
+
export function apply(ctx: Context) {
|
|
829
|
+
// Set as this plugin disposes, before its processes' exits come back (the kill goes through the host).
|
|
830
|
+
let disposing = false;
|
|
831
|
+
ctx.effect(() => () => {
|
|
832
|
+
disposing = true;
|
|
833
|
+
});
|
|
834
|
+
ctx.harness.register(ctx, {
|
|
835
|
+
...acpDriver(
|
|
836
|
+
(options) => ctx.processes.spawn(ctx, options),
|
|
837
|
+
() => disposing,
|
|
838
|
+
DEADLINES,
|
|
839
|
+
ctx.logger,
|
|
840
|
+
),
|
|
841
|
+
info: infoOf(),
|
|
842
|
+
});
|
|
843
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{ "extends": "./.bridge/tsconfig.json" }
|
package/README.md
DELETED