@kana-ai/edgar-provider-acp 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Kana.ai
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/README.md CHANGED
@@ -1,3 +1,52 @@
1
- # Temporary Holding Version
1
+ # @kana-ai/edgar-provider-acp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The process that runs sessions for the EDGAR engine with any agent that speaks the [Agent Client Protocol](https://agentclientprotocol.com). It speaks the same contract as [`edgar-provider-claude`](/apps/provider-claude/README.md): JSON-RPC 2.0 lines on stdin and stdout, `hello` answers `provider: "acp"`, and the log goes to stderr. The server common to every provider runtime is `@kana-ai/edgar-sdk/provider`.
4
+
5
+ The project names the agent in `edgar.toml`:
6
+
7
+ ```toml
8
+ [providers.acp]
9
+ command = ["claude-agent-acp"] # npm install -g @agentclientprotocol/claude-agent-acp
10
+ env_key = "ANTHROPIC_API_KEY" # the default; another agent names its own, such as GEMINI_API_KEY
11
+ ```
12
+
13
+ The engine reads the key from `[secrets] ACP_API_KEY`, such as `ACP_API_KEY = { env = "ANTHROPIC_API_KEY" }`, and the agent gets it under `env_key`.
14
+
15
+ `edgar check` reports a role on `acp` with no `command` as an error. `edgar init` does not set it.
16
+
17
+ ## How a session runs
18
+
19
+ EDGAR is the ACP client. Each session is one child that runs the command.
20
+
21
+ - `initialize` declines the `fs` and `terminal` client capabilities. Then `session/new` opens the session. When the agent answers `auth_required` (`-32000`), the runtime calls `authenticate` once with the agent's own method and tries again.
22
+ - The role's tools are one MCP stdio server named `edgar`, passed in `mcpServers`. It is the runtime's `bridge.ts`, which joins the agent to a Unix socket under `HOME`. Each `tools/call` goes to the engine as `tool.request`, and the model reads the engine's outcome.
23
+ - The instructions go in `systemPrompt` in the mode that `initialize` lists under `sessionCapabilities.systemPrompt.mode`, `append` before `override`. With no mode listed, or when `session/new` answers `-32602` to the system prompt, the runtime sends the request again without it and puts the instructions before the first prompt.
24
+ - `skills` holds the name and the description of each skill of the role, and no text of a skill. The instructions list them under `# Skills`, one line for each, and say that `edgar__skill` loads one. A role with no skill gets no list.
25
+ - `session/request_permission` is answered by the runtime: allowed once for an engine tool, whose call the engine then decides, and rejected for anything else. The model shapes a title, such as a shell command, so only a title that is exactly an engine tool's name passes (bare, `mcp__edgar__<name>`, or `<name> (<server>)`), and never for the kinds `execute`, `edit`, `delete`, `move` and `fetch`. `fs/*`, `terminal/*` and every other request get "method not found".
26
+ - `resume: {handle, fork: false}` is `session/resume` when the agent supports it, else `session/load`. An agent that supports neither, a fork, and a session the agent does not have (`-32002`) give an `error` event with `session_gone`.
27
+ - `session.send` is `session/prompt`. `agent_message_chunk` updates make `message` events. The turn ends with the prompt's answer.
28
+ - `session.cancel` sends `session/cancel`, waits at most 5 s for the answer, then kills the child's process group. A child that sends nothing for `--idle-seconds` while a request waits is killed, and the turn ends `silence`. The clock stops while the engine runs a tool call of the agent, because the agent then waits for the answer and has nothing to send. The engine's own deadline bounds that call.
29
+
30
+ ## Credentials
31
+
32
+ The child's environment is `PATH`, `HOME` and the API key under `env_key`. The engine's fallback API key, `ACP_FALLBACK_API_KEY`, comes as an `api_key` credential too and reaches the agent under the same `env_key`. The `cli` credential adds no key, and the agent uses its own sign-in, if it finds one. An `oauth` credential ends `unauthenticated` before any child starts, because `authenticate` names a method and carries no token. No credential is in an argument or a log line. A prompt the agent refuses with `-32000` ends `unauthenticated`, and its message names `ACP_API_KEY` in `[secrets]` as the fix, and on the `cli` credential the agent's own login too.
33
+
34
+ ## What the runtime may reach
35
+
36
+ The runtime runs under Node's permission model like the other providers, with `--allow-child-process` for the agent and `--allow-net` for the socket the bridge connects to. It works in `HOME` and names the socket relative to it, because a socket path is short.
37
+
38
+ ## Outcomes and usage
39
+
40
+ - One mapping table in `src/outcome/failures.ts` turns stop reasons and JSON-RPC error codes into outcome kinds and keeps the raw value in `cause` (`stop:<reason>` or `rpc:<code>`). A value the table does not know is `provider_unavailable`.
41
+ - `usage` comes from the prompt answer's `usage`, which the protocol marks unstable: input, output, cache-read and cache-write tokens when the agent reports them. The runtime does not read `limits.max_tokens`: the engine compares each `usage` event with the limit, keeps a finished result of the turn that passed it, and ends anything else `token_budget`. An agent that reports no usage has no limit.
42
+ - `limits.max_turns`, `limits.context_tokens` and a role's `effort` are not applied: the protocol has none of them.
43
+ - The protocol has no rate or usage limit notification, so the runtime sends no `limit` event. A rate limit reaches the engine only as the failure kind of the stop reason or error code.
44
+
45
+ ## Shortcuts
46
+
47
+ - A tool of the agent's own that asks no permission still runs.
48
+ - The empty `HOME` does not hide every login of the agent's own: `claude-agent-acp` also asks the macOS Keychain. When `env_key` is not the variable the agent reads, the agent can run on that login instead of EDGAR's key. Run EDGAR as its own user on a machine where a person is signed in to Claude Code.
49
+ - The title forms of a permission request are those the protocol shows, not checked against each agent.
50
+ - A session id that is not a lowercase UUID is kept under a new UUID in the runtime's memory, so a resume in a new runtime is `session_gone`.
51
+ - `inputTokens` is read as the input without the cached part. The protocol does not say.
52
+ - The protocol has no rate-limit error, so a rate limit ends with the kind of its error code.
@@ -0,0 +1,40 @@
1
+ import type { Duplex } from "node:stream";
2
+ import type { SessionStartParams } from "@kana-ai/edgar-contracts/provider";
3
+ import { type Child } from "@kana-ai/edgar-sdk/child";
4
+ import { type Agent } from "@kana-ai/edgar-sdk/provider";
5
+ /** Starts the project's agent command with exactly `env`. */
6
+ export type Spawn = (env: Readonly<Record<string, string>>) => Child;
7
+ /** A socket the agent's MCP client reaches through the bridge: its path, and a close. */
8
+ export interface Listening {
9
+ readonly path: string;
10
+ close(): void;
11
+ }
12
+ /** Listens for the MCP connections of one session, handing each to `serve`. */
13
+ export type Listen = (serve: (stream: Duplex) => void) => Promise<Listening>;
14
+ /** What the ACP agent needs from its process. */
15
+ export interface AcpOptions {
16
+ readonly spawn: Spawn;
17
+ readonly listen: Listen;
18
+ readonly env: NodeJS.ProcessEnv;
19
+ /** The variable the API key reaches the agent as. */
20
+ readonly envKey: string;
21
+ /** The program and arguments that run the MCP bridge to a socket path, which is appended. */
22
+ readonly bridge: readonly [string, ...string[]];
23
+ readonly version: string;
24
+ readonly log: (line: string) => void;
25
+ /** An agent that sends nothing for this long while a request waits is killed. */
26
+ readonly silenceMs: number;
27
+ }
28
+ /** `initialize`: no file system and no terminal, since the sandbox is the engine's. */
29
+ export declare function initializeParams(version: string): Record<string, unknown>;
30
+ /** The instructions, the list of the role's skills, and the rule that the engine's tools are the only ones. */
31
+ export declare function instructions(spec: SessionStartParams): string;
32
+ /** The agent's environment: `PATH`, `HOME` and the API key under `envKey`; on the `cli` credential no key, so the agent uses its own sign-in. */
33
+ export declare function agentEnv(spec: SessionStartParams, base: NodeJS.ProcessEnv, envKey: string): Record<string, string>;
34
+ /**
35
+ * The agent over one ACP agent process per session, which EDGAR drives as the client.
36
+ *
37
+ * shortcut: a tool of the agent's own that asks no permission still runs; upgrade when the protocol lets a client turn built-in tools off.
38
+ * shortcut: a session id that is not a lowercase UUID is kept under a new UUID in this process's memory, so a resume in a new runtime is `session_gone` and the engine starts fresh; upgrade when the engine's handle takes any id.
39
+ */
40
+ export declare function acp(options: AcpOptions): Agent;
@@ -0,0 +1,350 @@
1
+ import { channel } from "@kana-ai/edgar-sdk/child";
2
+ import { failedSession, skillList } from "@kana-ai/edgar-sdk/provider";
3
+ import { SERVER, permission, serveTools } from "#acp/tools";
4
+ import { AUTH_REQUIRED, INVALID_PARAMS, NOT_FOUND } from "#outcome/failures";
5
+ import { RESULT_TOOL, Reader } from "#outcome/reader";
6
+ import { InitializeAnswer as Initialize, PromptAnswer, SessionAnswer, } from "#schemas/answers";
7
+ import { PermissionRequest, SessionUpdate } from "#schemas/updates";
8
+ /** How long a cancel waits for the prompt's answer before it kills the agent. */
9
+ const CANCEL_WAIT_MS = 5000;
10
+ /** The protocol version this client speaks. */
11
+ const PROTOCOL_VERSION = 1;
12
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
13
+ function errorEvent(failure) {
14
+ return {
15
+ type: "error",
16
+ kind: failure.kind,
17
+ message: failure.message,
18
+ ...(failure.cause === undefined ? {} : { cause: failure.cause }),
19
+ };
20
+ }
21
+ /** `initialize`: no file system and no terminal, since the sandbox is the engine's. */
22
+ export function initializeParams(version) {
23
+ return {
24
+ protocolVersion: PROTOCOL_VERSION,
25
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
26
+ clientInfo: { name: "edgar", title: "EDGAR", version },
27
+ };
28
+ }
29
+ /** The instructions, the list of the role's skills, and the rule that the engine's tools are the only ones. */
30
+ export function instructions(spec) {
31
+ const rule = `Run commands and change files only through the tools of the \`${SERVER}\` MCP server. Tools of your own are refused.`;
32
+ return [spec.instructions, skillList(spec.skills), rule]
33
+ .filter((part) => part.length > 0)
34
+ .join("\n\n");
35
+ }
36
+ /** The agent's environment: `PATH`, `HOME` and the API key under `envKey`; on the `cli` credential no key, so the agent uses its own sign-in. */
37
+ export function agentEnv(spec, base, envKey) {
38
+ const credential = spec.credential;
39
+ const env = credential.kind === "cli" ? {} : { [envKey]: credential.value };
40
+ for (const name of ["PATH", "HOME"]) {
41
+ const value = base[name];
42
+ if (value !== undefined)
43
+ env[name] = value;
44
+ }
45
+ return env;
46
+ }
47
+ /** The system prompt mode the agent lists, `append` before `override`, or `undefined` when it lists none and the instructions go before the first prompt. */
48
+ function promptMode(init) {
49
+ const mode = init.agentCapabilities?.sessionCapabilities?.systemPrompt?.mode;
50
+ if (mode?.append !== undefined && mode.append !== null)
51
+ return "append";
52
+ if (mode?.override !== undefined && mode.override !== null)
53
+ return "override";
54
+ return undefined;
55
+ }
56
+ /** The fields of `session/new`, `session/load` and `session/resume`: the folder, the bridge, and the instructions in the system prompt `mode`. */
57
+ function sessionParams(spec, mode, bridge, socket) {
58
+ const [command, ...args] = bridge;
59
+ return {
60
+ cwd: spec.cwd,
61
+ mcpServers: [{ name: SERVER, command, args: [...args, socket], env: [] }],
62
+ ...(mode === undefined
63
+ ? {}
64
+ : { systemPrompt: { mode, content: [{ type: "text", text: instructions(spec) }] } }),
65
+ };
66
+ }
67
+ /** The method that reopens a session, or `undefined` when the agent can do neither. */
68
+ function reopenMethod(init) {
69
+ const resume = init.agentCapabilities?.sessionCapabilities?.resume;
70
+ if (resume !== undefined && resume !== null)
71
+ return "session/resume";
72
+ return init.agentCapabilities?.loadSession === true ? "session/load" : undefined;
73
+ }
74
+ /** One open ACP session: its turn, why the client stopped it, and the agent it runs in. */
75
+ class Open {
76
+ #rpc;
77
+ #child;
78
+ #reader;
79
+ #id;
80
+ #hooks;
81
+ #listening;
82
+ #listened = true;
83
+ #prefix;
84
+ #turn = false;
85
+ #prompt = Promise.resolve();
86
+ stop;
87
+ constructor(rpc, child, reader, ids, hooks, listening) {
88
+ this.#rpc = rpc;
89
+ this.#child = child;
90
+ this.#reader = reader;
91
+ this.#id = ids.vendor;
92
+ this.#prefix = ids.prefix;
93
+ this.#hooks = hooks;
94
+ this.#listening = listening;
95
+ rpc.ended.then(async () => await this.#ended(), () => hooks.closed());
96
+ }
97
+ get turn() {
98
+ return this.#turn;
99
+ }
100
+ emit(events) {
101
+ for (const event of events) {
102
+ if (event.type === "result")
103
+ this.#turn = false;
104
+ this.#hooks.event(event);
105
+ }
106
+ }
107
+ send(message) {
108
+ this.#turn = true;
109
+ const text = this.#prefix.length === 0 ? message : `${this.#prefix}\n\n${message}`;
110
+ this.#prefix = "";
111
+ const params = { sessionId: this.#id, prompt: [{ type: "text", text }] };
112
+ this.#prompt = this.#rpc.request("session/prompt", params).then((answer) => {
113
+ if (!this.#turn || (!answer.ok && this.stop !== undefined))
114
+ return;
115
+ if (!answer.ok) {
116
+ this.emit([
117
+ ...this.#reader.flush(),
118
+ { type: "result", outcome: this.#reader.refused(answer.code, answer.message) },
119
+ ]);
120
+ return;
121
+ }
122
+ const parsed = PromptAnswer.safeParse(answer.result);
123
+ if (parsed.success)
124
+ this.emit(this.#reader.answered(parsed.data, this.stop));
125
+ else
126
+ this.emit([
127
+ {
128
+ type: "result",
129
+ outcome: this.#reader.refused(undefined, "session/prompt answered no stopReason"),
130
+ },
131
+ ]);
132
+ }, () => this.#child.kill());
133
+ }
134
+ /** Cancels the running prompt, waiting at most `CANCEL_WAIT_MS` for its answer, then ends the agent. */
135
+ async end(stop) {
136
+ this.stop ??= stop;
137
+ if (this.#turn) {
138
+ this.#rpc.notify("session/cancel", { sessionId: this.#id });
139
+ const wait = new Promise((resolve) => setTimeout(resolve, CANCEL_WAIT_MS).unref());
140
+ await Promise.race([this.#prompt, wait]);
141
+ }
142
+ this.#child.kill();
143
+ this.#unlisten();
144
+ await this.#rpc.ended;
145
+ }
146
+ /** Closes the socket once, which removes its file at once, so a runtime that exits right after leaves none. */
147
+ #unlisten() {
148
+ if (this.#listened)
149
+ this.#listening.close();
150
+ this.#listened = false;
151
+ }
152
+ async #ended() {
153
+ await this.#child.exited;
154
+ this.#unlisten();
155
+ const failure = this.#reader.ended(this.stop ?? { thrown: "the ACP agent ended", kind: "runtime_crashed" });
156
+ if (this.#turn)
157
+ this.emit([...this.#reader.flush(), { type: "result", outcome: failure }]);
158
+ else if (this.stop === undefined)
159
+ this.#hooks.event(errorEvent(failure));
160
+ this.#hooks.closed();
161
+ }
162
+ }
163
+ /**
164
+ * The agent over one ACP agent process per session, which EDGAR drives as the client.
165
+ *
166
+ * shortcut: a tool of the agent's own that asks no permission still runs; upgrade when the protocol lets a client turn built-in tools off.
167
+ * shortcut: a session id that is not a lowercase UUID is kept under a new UUID in this process's memory, so a resume in a new runtime is `session_gone` and the engine starts fresh; upgrade when the engine's handle takes any id.
168
+ */
169
+ export function acp(options) {
170
+ const vendorIds = new Map();
171
+ return {
172
+ async start(spec, proposed, bind) {
173
+ const reader = new Reader(spec);
174
+ const failed = (event) => ({
175
+ handle: proposed,
176
+ session: failedSession(bind(proposed), event),
177
+ });
178
+ if (spec.credential.kind === "oauth")
179
+ return failed({
180
+ type: "result",
181
+ outcome: reader.ended({
182
+ thrown: "an ACP agent takes no OAuth token: `authenticate` names a method and carries no credential",
183
+ kind: "unauthenticated",
184
+ }),
185
+ });
186
+ let session;
187
+ let hooks;
188
+ const listened = await options
189
+ .listen((stream) => {
190
+ serveTools(stream, spec.tools, async (tool, input) => {
191
+ if (hooks === undefined)
192
+ return reader.ended({ thrown: "no session holds this tool call", kind: "refused" });
193
+ const release = rpc.hold();
194
+ try {
195
+ const outcome = await hooks.toolRequest(tool, input);
196
+ if (tool === RESULT_TOOL && outcome.outcome === "done")
197
+ reader.capture(input);
198
+ return outcome;
199
+ }
200
+ finally {
201
+ release();
202
+ }
203
+ }, options.log).then(() => { }, () => stream.destroy());
204
+ })
205
+ .then((open) => open, (error) => (error instanceof Error ? error : new Error(String(error))));
206
+ if (listened instanceof Error)
207
+ return failed({
208
+ type: "result",
209
+ outcome: reader.ended({
210
+ thrown: `the socket for the edgar tools did not open: ${listened.message}`,
211
+ kind: "provider_unavailable",
212
+ }),
213
+ });
214
+ const listening = listened;
215
+ const child = options.spawn(agentEnv(spec, options.env, options.envKey));
216
+ let loading = false;
217
+ const onRequest = (method, params) => {
218
+ if (method === "session/request_permission") {
219
+ const asked = PermissionRequest.safeParse(params);
220
+ if (asked.success)
221
+ return Promise.resolve({ result: permission(asked.data, spec.tools) });
222
+ }
223
+ return Promise.resolve({ error: { code: -32601, message: `edgar answers no ${method}` } });
224
+ };
225
+ const onNotify = (method, params) => {
226
+ if (method !== "session/update" || session === undefined || loading)
227
+ return;
228
+ const update = SessionUpdate.safeParse(params);
229
+ if (!update.success)
230
+ return;
231
+ const { sessionUpdate, content, messageId } = update.data.update;
232
+ if (sessionUpdate === "agent_message_chunk" && content?.type === "text")
233
+ session.emit(reader.chunk(content.text ?? "", messageId));
234
+ else if (sessionUpdate === "tool_call")
235
+ session.emit(reader.flush());
236
+ };
237
+ const rpc = channel(child.stdout, child.stdin, {
238
+ jsonrpc: true,
239
+ onRequest,
240
+ onNotify,
241
+ log: options.log,
242
+ silenceMs: options.silenceMs,
243
+ onSilent: () => {
244
+ if (session !== undefined)
245
+ session.stop ??= {
246
+ thrown: `the ACP agent sent nothing for ${options.silenceMs / 1000} s`,
247
+ kind: "silence",
248
+ };
249
+ child.kill();
250
+ },
251
+ });
252
+ const stopAll = () => {
253
+ child.kill();
254
+ listening.close();
255
+ };
256
+ const init = await rpc.request("initialize", initializeParams(options.version));
257
+ const parsed = init.ok ? Initialize.safeParse(init.result) : undefined;
258
+ if (parsed?.success !== true) {
259
+ stopAll();
260
+ const missing = (await child.exited) === "ENOENT";
261
+ const stop = missing
262
+ ? { thrown: "the `[providers.acp] command` program is not on PATH", kind: "refused" }
263
+ : {
264
+ thrown: `the ACP agent did not start: ${init.ok ? "initialize answered no protocolVersion" : init.message}`,
265
+ kind: "provider_unavailable",
266
+ };
267
+ return failed({ type: "result", outcome: reader.ended(stop) });
268
+ }
269
+ const caps = parsed.data;
270
+ let mode = promptMode(caps);
271
+ const ask = async (method, extra = {}) => {
272
+ const params = { ...sessionParams(spec, mode, options.bridge, listening.path), ...extra };
273
+ const answer = await rpc.request(method, params);
274
+ if (answer.ok || answer.code !== INVALID_PARAMS || mode === undefined)
275
+ return answer;
276
+ mode = undefined;
277
+ return await rpc.request(method, {
278
+ ...sessionParams(spec, mode, options.bridge, listening.path),
279
+ ...extra,
280
+ });
281
+ };
282
+ let vendor;
283
+ if (spec.resume !== undefined) {
284
+ const method = reopenMethod(caps);
285
+ const sessionId = vendorIds.get(spec.resume.handle) ?? spec.resume.handle;
286
+ const gone = (message) => {
287
+ stopAll();
288
+ return failed({
289
+ type: "error",
290
+ kind: "session_gone",
291
+ message,
292
+ cause: "edgar:session_gone",
293
+ });
294
+ };
295
+ if (spec.resume.fork)
296
+ return gone("the Agent Client Protocol has no stable fork");
297
+ if (method === undefined)
298
+ return gone("the agent can neither load nor resume a session");
299
+ loading = true;
300
+ const reopened = await ask(method, { sessionId });
301
+ loading = false;
302
+ if (!reopened.ok) {
303
+ if (reopened.code === NOT_FOUND)
304
+ return gone(reopened.message);
305
+ stopAll();
306
+ return failed({
307
+ type: "result",
308
+ outcome: reader.refused(reopened.code, reopened.message),
309
+ });
310
+ }
311
+ vendor = sessionId;
312
+ }
313
+ else {
314
+ let created = await ask("session/new");
315
+ const method = caps.authMethods?.find((m) => m.type === undefined || m.type === "agent");
316
+ if (!created.ok && created.code === AUTH_REQUIRED && method !== undefined) {
317
+ const signed = await rpc.request("authenticate", { methodId: method.id });
318
+ if (signed.ok)
319
+ created = await ask("session/new");
320
+ }
321
+ const id = created.ok ? SessionAnswer.safeParse(created.result) : undefined;
322
+ if (id?.success !== true) {
323
+ stopAll();
324
+ return failed({
325
+ type: "result",
326
+ outcome: created.ok
327
+ ? reader.refused(undefined, "session/new answered no sessionId")
328
+ : reader.refused(created.code, created.message),
329
+ });
330
+ }
331
+ vendor = id.data.sessionId;
332
+ }
333
+ const handle = UUID.test(vendor) ? vendor : (spec.resume?.handle ?? proposed);
334
+ if (handle !== vendor)
335
+ vendorIds.set(handle, vendor);
336
+ hooks = bind(handle);
337
+ hooks.log(`session ${handle}: ACP agent, credential ${spec.credential.kind}, tools ${spec.tools.map((t) => t.name).join(" ")}`);
338
+ const prefix = mode === undefined ? instructions(spec) : "";
339
+ session = new Open(rpc, child, reader, { vendor, prefix: spec.resume === undefined ? prefix : "" }, hooks, listening);
340
+ const live = session;
341
+ return {
342
+ handle,
343
+ session: {
344
+ send: (message) => live.send(message),
345
+ cancel: async () => await live.end("cancelled"),
346
+ },
347
+ };
348
+ },
349
+ };
350
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ import { connect } from "node:net";
3
+ import { basename, dirname } from "node:path";
4
+ /** The agent's MCP stdio server: it pipes stdio to the runtime's socket, reached by its base name so a long folder path fits the socket limit. */
5
+ const socket = process.argv[2];
6
+ if (socket === undefined) {
7
+ process.stderr.write("usage: bridge <socket path>\n");
8
+ process.exit(2);
9
+ }
10
+ process.chdir(dirname(socket));
11
+ const stream = connect(basename(socket));
12
+ stream.on("error", (error) => {
13
+ process.stderr.write(`edgar bridge: ${error.message}\n`);
14
+ process.exit(1);
15
+ });
16
+ stream.on("close", () => process.exit(0));
17
+ process.stdin.pipe(stream).pipe(process.stdout);
@@ -0,0 +1,16 @@
1
+ import type { Duplex } from "node:stream";
2
+ import type { ProviderTool } from "@kana-ai/edgar-contracts/provider";
3
+ import type { Outcome } from "@kana-ai/edgar-sdk";
4
+ import type { PermissionRequest } from "#schemas/updates";
5
+ /** The name of the MCP server that holds the engine's tools. */
6
+ export declare const SERVER = "edgar";
7
+ /** What the model reads: `done.output` as text, any other outcome as an error with its JSON. */
8
+ export declare function toolResult(outcome: Outcome): Record<string, unknown>;
9
+ /** Serves the engine's tools as one MCP server on `stream`, each call answered by `call` until the stream ends. */
10
+ export declare function serveTools(stream: Duplex, tools: readonly ProviderTool[], call: (tool: string, input: unknown) => Promise<Outcome>, log: (line: string) => void): Promise<void>;
11
+ /**
12
+ * The answer to `session/request_permission`: allow once for a call of an engine tool, whose call the engine then decides, and reject anything else. A title is the model's to shape, such as a shell command, so only an exact tool name passes, and never for a kind that acts on the machine.
13
+ *
14
+ * shortcut: the title forms are those the protocol's examples show, not checked against each agent; upgrade with a captured request of each agent a project runs.
15
+ */
16
+ export declare function permission(request: PermissionRequest, tools: readonly ProviderTool[]): Record<string, unknown>;
@@ -0,0 +1,88 @@
1
+ import { channel } from "@kana-ai/edgar-sdk/child";
2
+ import { ToolCall } from "#schemas/updates";
3
+ /** The name of the MCP server that holds the engine's tools. */
4
+ export const SERVER = "edgar";
5
+ /** The MCP protocol version answered to a client that names none. */
6
+ const MCP_VERSION = "2025-06-18";
7
+ /** What the model reads: `done.output` as text, any other outcome as an error with its JSON. */
8
+ export function toolResult(outcome) {
9
+ const text = outcome.outcome !== "done"
10
+ ? JSON.stringify(outcome)
11
+ : typeof outcome.output === "string"
12
+ ? outcome.output
13
+ : JSON.stringify(outcome.output);
14
+ return { content: [{ type: "text", text }], isError: outcome.outcome !== "done" };
15
+ }
16
+ /** Serves the engine's tools as one MCP server on `stream`, each call answered by `call` until the stream ends. */
17
+ export async function serveTools(stream, tools, call, log) {
18
+ const names = new Set(tools.map((tool) => tool.name));
19
+ const onRequest = async (method, params) => {
20
+ switch (method) {
21
+ case "initialize": {
22
+ const version = params["protocolVersion"];
23
+ return {
24
+ result: {
25
+ protocolVersion: typeof version === "string" ? version : MCP_VERSION,
26
+ capabilities: { tools: {} },
27
+ serverInfo: { name: SERVER, version: "1" },
28
+ },
29
+ };
30
+ }
31
+ case "ping":
32
+ return { result: {} };
33
+ case "tools/list":
34
+ return {
35
+ result: {
36
+ tools: tools.map((tool) => ({
37
+ name: tool.name,
38
+ description: tool.description,
39
+ inputSchema: tool.input_schema,
40
+ })),
41
+ },
42
+ };
43
+ case "tools/call": {
44
+ const asked = ToolCall.safeParse(params);
45
+ if (!asked.success || !names.has(asked.data.name))
46
+ return { error: { code: -32602, message: "no such tool of this role" } };
47
+ return { result: toolResult(await call(asked.data.name, asked.data.arguments ?? {})) };
48
+ }
49
+ default:
50
+ return { error: { code: -32601, message: `edgar answers no ${method}` } };
51
+ }
52
+ };
53
+ const served = channel(stream, stream, {
54
+ jsonrpc: true,
55
+ onRequest,
56
+ onNotify: () => { },
57
+ log,
58
+ silenceMs: 1,
59
+ onSilent: () => { },
60
+ });
61
+ await served.ended;
62
+ }
63
+ /** The kinds of the agent's own tools that act on the machine; a permission for one is always rejected. */
64
+ const ACTING = new Set(["execute", "edit", "delete", "move", "fetch"]);
65
+ /** A tool call's title as an engine tool's name: bare, as `mcp__edgar__<name>`, or followed by ` (<server>)`. */
66
+ function named(title) {
67
+ return title.replace(/^mcp__edgar__/, "").replace(/ \([^()]*\)$/, "");
68
+ }
69
+ /**
70
+ * The answer to `session/request_permission`: allow once for a call of an engine tool, whose call the engine then decides, and reject anything else. A title is the model's to shape, such as a shell command, so only an exact tool name passes, and never for a kind that acts on the machine.
71
+ *
72
+ * shortcut: the title forms are those the protocol's examples show, not checked against each agent; upgrade with a captured request of each agent a project runs.
73
+ */
74
+ export function permission(request, tools) {
75
+ const { title, kind } = request.toolCall;
76
+ const ours = typeof title === "string" &&
77
+ (typeof kind !== "string" || !ACTING.has(kind)) &&
78
+ tools.some((tool) => tool.name === named(title));
79
+ const kinds = ours ? ["allow_once", "allow_always"] : ["reject_once", "reject_always"];
80
+ const option = kinds
81
+ .map((wanted) => request.options.find((o) => o.kind === wanted))
82
+ .find((o) => o !== undefined);
83
+ return {
84
+ outcome: option === undefined
85
+ ? { outcome: "cancelled" }
86
+ : { outcome: "selected", optionId: option.optionId },
87
+ };
88
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,76 @@
1
+ #!/usr/bin/env node
2
+ import { randomUUID } from "node:crypto";
3
+ import { readFile } from "node:fs/promises";
4
+ import { findPackageJSON } from "node:module";
5
+ import { createServer } from "node:net";
6
+ import { join } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { parseArgs } from "node:util";
9
+ import { serve } from "@kana-ai/edgar-sdk/provider";
10
+ import { spawnVendor } from "@kana-ai/edgar-sdk/child";
11
+ import { acp } from "#acp/agent";
12
+ import { parseCommand } from "#schemas/command";
13
+ const log = (line) => {
14
+ process.stderr.write(`${line}\n`);
15
+ };
16
+ const usage = () => {
17
+ log("usage: edgar-provider-acp --command <JSON array> [--env-key <NAME>] [--idle-seconds <positive integer>]");
18
+ return process.exit(2);
19
+ };
20
+ const { values } = parseArgs({
21
+ options: {
22
+ "idle-seconds": { type: "string", default: "300" },
23
+ command: { type: "string" },
24
+ "env-key": { type: "string", default: "ANTHROPIC_API_KEY" },
25
+ },
26
+ });
27
+ const idleSeconds = Number(values["idle-seconds"]);
28
+ if (!Number.isInteger(idleSeconds) || idleSeconds < 1)
29
+ usage();
30
+ const [program, ...programArgs] = parseCommand(values.command) ?? usage();
31
+ const envKey = values["env-key"];
32
+ if (!/^[A-Z_][A-Z0-9_]*$/.test(envKey))
33
+ usage();
34
+ const home = process.env["HOME"];
35
+ if (home === undefined) {
36
+ log("edgar-provider-acp needs HOME, where the MCP sockets live");
37
+ process.exit(2);
38
+ }
39
+ process.chdir(home);
40
+ /** The project's command, its stderr in the runtime's log. */
41
+ const spawnAgent = (env) => spawnVendor(program, programArgs, env, "acp", log);
42
+ /** A socket under HOME, named relative to it because a socket path is short; the process works in HOME. */
43
+ const listen = (onStream) => new Promise((resolve, reject) => {
44
+ const name = `mcp-${randomUUID().slice(0, 8)}.sock`;
45
+ const server = createServer(onStream);
46
+ server.once("error", reject);
47
+ server.listen(name, () => resolve({ path: join(home, name), close: () => server.close() }));
48
+ });
49
+ const manifestPath = findPackageJSON(import.meta.url);
50
+ const manifest = manifestPath === undefined ? undefined : JSON.parse(await readFile(manifestPath, "utf8"));
51
+ const version = typeof manifest === "object" && manifest !== null && "version" in manifest
52
+ ? manifest.version
53
+ : undefined;
54
+ if (typeof version !== "string") {
55
+ log("refusing to start: edgar-provider-acp has no readable package.json");
56
+ process.exit(1);
57
+ }
58
+ await serve({
59
+ input: process.stdin,
60
+ output: process.stdout,
61
+ log,
62
+ agent: acp({
63
+ spawn: spawnAgent,
64
+ listen,
65
+ env: process.env,
66
+ envKey,
67
+ bridge: [process.execPath, fileURLToPath(import.meta.resolve("#acp/bridge"))],
68
+ version,
69
+ log,
70
+ silenceMs: idleSeconds * 1000,
71
+ }),
72
+ provider: "acp",
73
+ sdkVersion: program,
74
+ idleSeconds,
75
+ exit: (code) => process.exit(code),
76
+ });
@@ -0,0 +1,38 @@
1
+ import type { FailureKind } from "@kana-ai/edgar-sdk";
2
+ /** The outcome kinds an ACP session can end with. */
3
+ export type Kind = Extract<FailureKind, "provider_unavailable" | "runtime_crashed" | "silence" | "unauthenticated" | "token_budget" | "cancelled" | "invalid" | "not_found" | "refused">;
4
+ /** The kind of a vendor code this table does not know. */
5
+ export declare const UNEXPECTED: Kind;
6
+ /** The stop reasons of `session/prompt` other than `end_turn`. */
7
+ export declare const STOP_REASONS: {
8
+ readonly max_tokens: "token_budget";
9
+ readonly max_turn_requests: "token_budget";
10
+ readonly refusal: "refused";
11
+ readonly cancelled: "cancelled";
12
+ };
13
+ /** The JSON-RPC error codes an agent answers with. `-32002` on a resume is `session_gone`, and elsewhere `not_found`. */
14
+ export declare const ERROR_CODES: {
15
+ readonly "-32000": "unauthenticated";
16
+ readonly "-32002": "not_found";
17
+ readonly "-32800": "cancelled";
18
+ readonly "-32600": "invalid";
19
+ readonly "-32601": "invalid";
20
+ readonly "-32602": "invalid";
21
+ readonly "-32603": "provider_unavailable";
22
+ };
23
+ /** `auth_required`: the agent needs `authenticate` first. */
24
+ export declare const AUTH_REQUIRED = -32000;
25
+ /** Params the agent cannot apply, such as a system prompt mode it does not take. */
26
+ export declare const INVALID_PARAMS = -32602;
27
+ /** A session the agent does not have. */
28
+ export declare const NOT_FOUND = -32002;
29
+ /** The kind and the raw code of a stop reason, kept as `stop:<reason>`. */
30
+ export declare function stopKind(reason: string): {
31
+ kind: Kind;
32
+ cause: string;
33
+ };
34
+ /** The kind and the raw code of an error answer, kept as `rpc:<code>`. */
35
+ export declare function codeKind(code: number | undefined): {
36
+ kind: Kind;
37
+ cause: string;
38
+ };
@@ -0,0 +1,37 @@
1
+ /** The kind of a vendor code this table does not know. */
2
+ export const UNEXPECTED = "provider_unavailable";
3
+ /** The stop reasons of `session/prompt` other than `end_turn`. */
4
+ export const STOP_REASONS = {
5
+ max_tokens: "token_budget",
6
+ max_turn_requests: "token_budget",
7
+ refusal: "refused",
8
+ cancelled: "cancelled",
9
+ };
10
+ /** The JSON-RPC error codes an agent answers with. `-32002` on a resume is `session_gone`, and elsewhere `not_found`. */
11
+ export const ERROR_CODES = {
12
+ "-32000": "unauthenticated",
13
+ "-32002": "not_found",
14
+ "-32800": "cancelled",
15
+ "-32600": "invalid",
16
+ "-32601": "invalid",
17
+ "-32602": "invalid",
18
+ "-32603": "provider_unavailable",
19
+ };
20
+ /** `auth_required`: the agent needs `authenticate` first. */
21
+ export const AUTH_REQUIRED = -32000;
22
+ /** Params the agent cannot apply, such as a system prompt mode it does not take. */
23
+ export const INVALID_PARAMS = -32602;
24
+ /** A session the agent does not have. */
25
+ export const NOT_FOUND = -32002;
26
+ const stopKinds = new Map(Object.entries(STOP_REASONS));
27
+ const codeKinds = new Map(Object.entries(ERROR_CODES));
28
+ /** The kind and the raw code of a stop reason, kept as `stop:<reason>`. */
29
+ export function stopKind(reason) {
30
+ return { kind: stopKinds.get(reason) ?? UNEXPECTED, cause: `stop:${reason}` };
31
+ }
32
+ /** The kind and the raw code of an error answer, kept as `rpc:<code>`. */
33
+ export function codeKind(code) {
34
+ if (code === undefined)
35
+ return { kind: UNEXPECTED, cause: "rpc:none" };
36
+ return { kind: codeKinds.get(String(code)) ?? UNEXPECTED, cause: `rpc:${code}` };
37
+ }
@@ -0,0 +1,28 @@
1
+ import type { SessionEvent, SessionStartParams } from "@kana-ai/edgar-contracts/provider";
2
+ import { type Failure } from "@kana-ai/edgar-sdk";
3
+ import { type Kind } from "#outcome/failures";
4
+ import type { PromptAnswer } from "#schemas/answers";
5
+ /** The engine tool through which a role returns its result. */
6
+ export declare const RESULT_TOOL = "edgar__result";
7
+ /** Why the session stopped a turn itself. */
8
+ export type Stop = "cancelled" | {
9
+ readonly thrown: string;
10
+ readonly kind: Kind;
11
+ };
12
+ /** Reads one session's updates into session events, keeping the turn's facts for the mapping table. */
13
+ export declare class Reader {
14
+ #private;
15
+ constructor(spec: SessionStartParams);
16
+ /** Keeps what the model passed to `edgar__result` once the engine accepted it. */
17
+ capture(output: unknown): void;
18
+ /** One `agent_message_chunk`; a new message id ends the message before it. */
19
+ chunk(text: string, messageId: string | null | undefined): SessionEvent[];
20
+ /** The message the chunks so far make, once. */
21
+ flush(): SessionEvent[];
22
+ /** The events of an answered `session/prompt`: the last message, the usage the agent reported, and the result. */
23
+ answered(answer: PromptAnswer, stop: Stop | undefined): SessionEvent[];
24
+ /** The outcome of a turn that ended before its answer. */
25
+ ended(stop: Stop): Failure;
26
+ /** The outcome of an error answer; an `unauthenticated` one names the sign-in or the secret that fixes it. */
27
+ refused(code: number | undefined, message: string): Failure;
28
+ }
@@ -0,0 +1,91 @@
1
+ import { done, isTemporary, permanentFailure, temporaryFailure, } from "@kana-ai/edgar-sdk";
2
+ import { codeKind, stopKind } from "#outcome/failures";
3
+ /** The engine tool through which a role returns its result. */
4
+ export const RESULT_TOOL = "edgar__result";
5
+ /** Reads one session's updates into session events, keeping the turn's facts for the mapping table. */
6
+ export class Reader {
7
+ #expectsResult;
8
+ #fix;
9
+ #captured;
10
+ #messageId;
11
+ #chunks = "";
12
+ #text = "";
13
+ constructor(spec) {
14
+ this.#fix =
15
+ spec.credential.kind === "cli"
16
+ ? "sign the agent in with its own login, or set `ACP_API_KEY` in the project's `[secrets]`"
17
+ : "set a valid `ACP_API_KEY` in the project's `[secrets]`";
18
+ this.#expectsResult = spec.tools.some((t) => t.name === RESULT_TOOL);
19
+ }
20
+ /** Keeps what the model passed to `edgar__result` once the engine accepted it. */
21
+ capture(output) {
22
+ this.#captured = { value: output };
23
+ }
24
+ /** One `agent_message_chunk`; a new message id ends the message before it. */
25
+ chunk(text, messageId) {
26
+ const events = messageId === this.#messageId ? [] : this.flush();
27
+ this.#messageId = messageId;
28
+ this.#chunks += text;
29
+ return events;
30
+ }
31
+ /** The message the chunks so far make, once. */
32
+ flush() {
33
+ const text = this.#chunks;
34
+ this.#chunks = "";
35
+ if (text.length === 0)
36
+ return [];
37
+ this.#text = text;
38
+ return [{ type: "message", role: "assistant", text }];
39
+ }
40
+ /** The events of an answered `session/prompt`: the last message, the usage the agent reported, and the result. */
41
+ answered(answer, stop) {
42
+ const events = this.flush();
43
+ const usage = answer.usage ?? undefined;
44
+ if (usage !== undefined)
45
+ events.push({
46
+ type: "usage",
47
+ input_tokens: usage.inputTokens,
48
+ output_tokens: usage.outputTokens,
49
+ ...(usage.cachedReadTokens === null || usage.cachedReadTokens === undefined
50
+ ? {}
51
+ : { cache_read_tokens: usage.cachedReadTokens }),
52
+ ...(usage.cachedWriteTokens === null || usage.cachedWriteTokens === undefined
53
+ ? {}
54
+ : { cache_write_tokens: usage.cachedWriteTokens }),
55
+ });
56
+ events.push({ type: "result", outcome: this.#outcome(answer, stop) });
57
+ this.#captured = undefined;
58
+ this.#text = "";
59
+ return events;
60
+ }
61
+ /** The outcome of a turn that ended before its answer. */
62
+ ended(stop) {
63
+ if (stop === "cancelled")
64
+ return failure("cancelled", "the session was cancelled", "edgar:cancelled");
65
+ return failure(stop.kind, stop.thrown, "edgar:thrown");
66
+ }
67
+ /** The outcome of an error answer; an `unauthenticated` one names the sign-in or the secret that fixes it. */
68
+ refused(code, message) {
69
+ const { kind, cause } = codeKind(code);
70
+ const fixed = kind === "unauthenticated" ? `${message.replace(/\.$/, "")}; ${this.#fix}.` : message;
71
+ return failure(kind, fixed, cause);
72
+ }
73
+ #outcome(answer, stop) {
74
+ if (stop !== undefined)
75
+ return this.ended(stop);
76
+ if (answer.stopReason !== "end_turn") {
77
+ const { kind, cause } = stopKind(answer.stopReason);
78
+ return failure(kind, `the turn stopped: ${answer.stopReason}`, cause);
79
+ }
80
+ if (!this.#expectsResult)
81
+ return done(this.#text);
82
+ if (this.#captured !== undefined)
83
+ return done(this.#captured.value);
84
+ return failure("invalid", `the turn ended without ${RESULT_TOOL}`, "edgar:no_result");
85
+ }
86
+ }
87
+ function failure(kind, message, cause) {
88
+ return isTemporary(kind)
89
+ ? temporaryFailure(kind, message, { cause })
90
+ : permanentFailure(kind, message, { cause });
91
+ }
@@ -0,0 +1,45 @@
1
+ import { z } from "zod";
2
+ /** The answer of `initialize`: what the agent can do, and how it signs in. */
3
+ export declare const InitializeAnswer: z.ZodObject<{
4
+ protocolVersion: z.ZodNumber;
5
+ agentCapabilities: z.ZodOptional<z.ZodObject<{
6
+ loadSession: z.ZodOptional<z.ZodBoolean>;
7
+ sessionCapabilities: z.ZodOptional<z.ZodObject<{
8
+ resume: z.ZodOptional<z.ZodNullable<z.ZodObject<{}, z.core.$loose>>>;
9
+ systemPrompt: z.ZodOptional<z.ZodNullable<z.ZodObject<{
10
+ mode: z.ZodOptional<z.ZodObject<{
11
+ append: z.ZodOptional<z.ZodNullable<z.ZodObject<{}, z.core.$loose>>>;
12
+ override: z.ZodOptional<z.ZodNullable<z.ZodObject<{}, z.core.$loose>>>;
13
+ }, z.core.$loose>>;
14
+ }, z.core.$loose>>>;
15
+ }, z.core.$loose>>;
16
+ }, z.core.$loose>>;
17
+ authMethods: z.ZodOptional<z.ZodArray<z.ZodObject<{
18
+ id: z.ZodString;
19
+ type: z.ZodOptional<z.ZodString>;
20
+ }, z.core.$loose>>>;
21
+ }, z.core.$loose>;
22
+ export type InitializeAnswer = z.infer<typeof InitializeAnswer>;
23
+ /** The answer of `session/new`. */
24
+ export declare const SessionAnswer: z.ZodObject<{
25
+ sessionId: z.ZodString;
26
+ }, z.core.$loose>;
27
+ /** Token totals of the session, which the protocol marks unstable. */
28
+ export declare const Usage: z.ZodObject<{
29
+ inputTokens: z.ZodNumber;
30
+ outputTokens: z.ZodNumber;
31
+ cachedReadTokens: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
32
+ cachedWriteTokens: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
33
+ }, z.core.$loose>;
34
+ export type Usage = z.infer<typeof Usage>;
35
+ /** The answer of `session/prompt`: why the turn stopped. */
36
+ export declare const PromptAnswer: z.ZodObject<{
37
+ stopReason: z.ZodString;
38
+ usage: z.ZodOptional<z.ZodNullable<z.ZodObject<{
39
+ inputTokens: z.ZodNumber;
40
+ outputTokens: z.ZodNumber;
41
+ cachedReadTokens: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
42
+ cachedWriteTokens: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
43
+ }, z.core.$loose>>>;
44
+ }, z.core.$loose>;
45
+ export type PromptAnswer = z.infer<typeof PromptAnswer>;
@@ -0,0 +1,43 @@
1
+ import { z } from "zod";
2
+ /** One authentication method of `initialize`; a method with no `type` is the agent's own flow. */
3
+ const AuthMethod = z.looseObject({ id: z.string(), type: z.string().optional() });
4
+ /** The answer of `initialize`: what the agent can do, and how it signs in. */
5
+ export const InitializeAnswer = z.looseObject({
6
+ protocolVersion: z.number().int(),
7
+ agentCapabilities: z
8
+ .looseObject({
9
+ loadSession: z.boolean().optional(),
10
+ sessionCapabilities: z
11
+ .looseObject({
12
+ resume: z.looseObject({}).nullable().optional(),
13
+ systemPrompt: z
14
+ .looseObject({
15
+ mode: z
16
+ .looseObject({
17
+ append: z.looseObject({}).nullable().optional(),
18
+ override: z.looseObject({}).nullable().optional(),
19
+ })
20
+ .optional(),
21
+ })
22
+ .nullable()
23
+ .optional(),
24
+ })
25
+ .optional(),
26
+ })
27
+ .optional(),
28
+ authMethods: z.array(AuthMethod).optional(),
29
+ });
30
+ /** The answer of `session/new`. */
31
+ export const SessionAnswer = z.looseObject({ sessionId: z.string().min(1) });
32
+ /** Token totals of the session, which the protocol marks unstable. */
33
+ export const Usage = z.looseObject({
34
+ inputTokens: z.number().int().nonnegative(),
35
+ outputTokens: z.number().int().nonnegative(),
36
+ cachedReadTokens: z.number().int().nonnegative().nullable().optional(),
37
+ cachedWriteTokens: z.number().int().nonnegative().nullable().optional(),
38
+ });
39
+ /** The answer of `session/prompt`: why the turn stopped. */
40
+ export const PromptAnswer = z.looseObject({
41
+ stopReason: z.string(),
42
+ usage: Usage.nullable().optional(),
43
+ });
@@ -0,0 +1,2 @@
1
+ /** The program and its arguments from the `--command` flag, or `undefined` when the flag is missing, is not JSON, or is not that array. */
2
+ export declare function parseCommand(text: string | undefined): readonly [string, ...string[]] | undefined;
@@ -0,0 +1,12 @@
1
+ import { attempt } from "@kana-ai/edgar-sdk/result";
2
+ import { z } from "zod";
3
+ /** The `--command` flag: a JSON array of non-empty strings, the program first. */
4
+ const Command = z.tuple([z.string().min(1)], z.string().min(1));
5
+ /** The program and its arguments from the `--command` flag, or `undefined` when the flag is missing, is not JSON, or is not that array. */
6
+ export function parseCommand(text) {
7
+ if (text === undefined)
8
+ return undefined;
9
+ const json = attempt(() => JSON.parse(text), () => undefined);
10
+ const parsed = json.ok ? Command.safeParse(json.value) : undefined;
11
+ return parsed?.success === true ? parsed.data : undefined;
12
+ }
@@ -0,0 +1,30 @@
1
+ import { z } from "zod";
2
+ /** `session/update`; only the agent's text and its tool calls are read. */
3
+ export declare const SessionUpdate: z.ZodObject<{
4
+ sessionId: z.ZodString;
5
+ update: z.ZodObject<{
6
+ sessionUpdate: z.ZodString;
7
+ messageId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
8
+ content: z.ZodOptional<z.ZodObject<{
9
+ type: z.ZodString;
10
+ text: z.ZodOptional<z.ZodString>;
11
+ }, z.core.$loose>>;
12
+ }, z.core.$loose>;
13
+ }, z.core.$loose>;
14
+ /** `session/request_permission`: the tool call and the options to pick from. */
15
+ export declare const PermissionRequest: z.ZodObject<{
16
+ toolCall: z.ZodObject<{
17
+ title: z.ZodOptional<z.ZodNullable<z.ZodString>>;
18
+ kind: z.ZodOptional<z.ZodNullable<z.ZodString>>;
19
+ }, z.core.$loose>;
20
+ options: z.ZodArray<z.ZodObject<{
21
+ optionId: z.ZodString;
22
+ kind: z.ZodString;
23
+ }, z.core.$loose>>;
24
+ }, z.core.$loose>;
25
+ export type PermissionRequest = z.infer<typeof PermissionRequest>;
26
+ /** `tools/call` from the agent's MCP client. */
27
+ export declare const ToolCall: z.ZodObject<{
28
+ name: z.ZodString;
29
+ arguments: z.ZodUnknown;
30
+ }, z.core.$loose>;
@@ -0,0 +1,23 @@
1
+ import { z } from "zod";
2
+ /** `session/update`; only the agent's text and its tool calls are read. */
3
+ export const SessionUpdate = z.looseObject({
4
+ sessionId: z.string(),
5
+ update: z.looseObject({
6
+ sessionUpdate: z.string(),
7
+ messageId: z.string().nullable().optional(),
8
+ content: z.looseObject({ type: z.string(), text: z.string().optional() }).optional(),
9
+ }),
10
+ });
11
+ /** `session/request_permission`: the tool call and the options to pick from. */
12
+ export const PermissionRequest = z.looseObject({
13
+ toolCall: z.looseObject({
14
+ title: z.string().nullable().optional(),
15
+ kind: z.string().nullable().optional(),
16
+ }),
17
+ options: z.array(z.looseObject({ optionId: z.string(), kind: z.string() })),
18
+ });
19
+ /** `tools/call` from the agent's MCP client. */
20
+ export const ToolCall = z.looseObject({
21
+ name: z.string(),
22
+ arguments: z.unknown(),
23
+ });
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@kana-ai/edgar-provider-acp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "The process that runs Agent Client Protocol sessions for the EDGAR engine with the agent a project names, over JSON-RPC on stdio.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/kana-ai/edgar",
9
+ "directory": "apps/provider-acp"
10
+ },
11
+ "bin": {
12
+ "edgar-provider-acp": "./dist/src/main.js"
13
+ },
14
+ "files": [
15
+ "dist/src"
16
+ ],
17
+ "type": "module",
18
+ "imports": {
19
+ "#*": "./dist/src/*.js"
20
+ },
21
+ "dependencies": {
22
+ "@kana-ai/edgar-contracts": "0.1.0",
23
+ "@kana-ai/edgar-sdk": "0.1.0",
24
+ "zod": "4.6.7"
25
+ },
26
+ "devDependencies": {
27
+ "@types/node": "24.19.2",
28
+ "oxfmt": "0.76.0",
29
+ "oxlint": "1.91.0",
30
+ "oxlint-tsgolint": "7.0.2005",
31
+ "typescript": "7.0.2"
32
+ },
33
+ "scripts": {
34
+ "check-types": "tsc --noEmit",
35
+ "lint": "oxlint --type-aware --deny-warnings",
36
+ "format:check": "oxfmt --check",
37
+ "test": "node --test"
38
+ }
6
39
  }