@datalabrotterdam/nova-ai-cli 1.0.1-alpha.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.
Files changed (42) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +148 -0
  3. package/dist/acp/agent.d.ts +12 -0
  4. package/dist/acp/agent.js +206 -0
  5. package/dist/acp/auth-server.d.ts +10 -0
  6. package/dist/acp/auth-server.js +67 -0
  7. package/dist/acp/credentials.d.ts +11 -0
  8. package/dist/acp/credentials.js +30 -0
  9. package/dist/acp/index.d.ts +2 -0
  10. package/dist/acp/index.js +20 -0
  11. package/dist/acp/sessions.d.ts +20 -0
  12. package/dist/acp/sessions.js +91 -0
  13. package/dist/acp/tools/index.d.ts +6 -0
  14. package/dist/acp/tools/index.js +5 -0
  15. package/dist/acp/tools/marker.d.ts +17 -0
  16. package/dist/acp/tools/marker.js +43 -0
  17. package/dist/acp/tools/permission.d.ts +2 -0
  18. package/dist/acp/tools/permission.js +20 -0
  19. package/dist/acp/tools/read-file.d.ts +2 -0
  20. package/dist/acp/tools/read-file.js +20 -0
  21. package/dist/acp/tools/registry.d.ts +4 -0
  22. package/dist/acp/tools/registry.js +10 -0
  23. package/dist/acp/tools/reporting.d.ts +3 -0
  24. package/dist/acp/tools/reporting.js +26 -0
  25. package/dist/acp/tools/run-command.d.ts +2 -0
  26. package/dist/acp/tools/run-command.js +29 -0
  27. package/dist/acp/tools/system-prompt.d.ts +2 -0
  28. package/dist/acp/tools/system-prompt.js +23 -0
  29. package/dist/acp/tools/types.d.ts +18 -0
  30. package/dist/acp/tools/types.js +1 -0
  31. package/dist/acp/tools/write-file.d.ts +2 -0
  32. package/dist/acp/tools/write-file.js +20 -0
  33. package/dist/index.d.ts +2 -0
  34. package/dist/index.js +25 -0
  35. package/dist/tui/index.d.ts +7 -0
  36. package/dist/tui/index.js +11 -0
  37. package/dist/webui/index.d.ts +6 -0
  38. package/dist/webui/index.js +9 -0
  39. package/package.json +78 -0
  40. package/src/acp/web/dist/assets/index-B3sTKEem.js +1 -0
  41. package/src/acp/web/dist/assets/index-DwysEXf2.css +1 -0
  42. package/src/acp/web/dist/index.html +13 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
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 [yyyy] [name of copyright owner]
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.
package/README.md ADDED
@@ -0,0 +1,148 @@
1
+ <div align="center">
2
+
3
+ <img src="./assets/logo.png" width="96" height="96" alt="Nova logo" />
4
+
5
+ # @datalabrotterdam/nova-ai-cli
6
+
7
+ **CLI for DataLab Rotterdam's Nova AI — also speaks Agent Client Protocol**
8
+
9
+ [![npm version](https://img.shields.io/npm/v/@datalabrotterdam/nova-ai-cli?style=flat-square&color=f96743)](https://www.npmjs.com/package/@datalabrotterdam/nova-ai-cli)
10
+ [![npm downloads](https://img.shields.io/npm/dm/@datalabrotterdam/nova-ai-cli?style=flat-square)](https://www.npmjs.com/package/@datalabrotterdam/nova-ai-cli)
11
+ [![license](https://img.shields.io/npm/l/@datalabrotterdam/nova-ai-cli?style=flat-square)](./LICENSE)
12
+ [![ACP](https://img.shields.io/badge/ACP-agent-blue?style=flat-square)](https://agentclientprotocol.com)
13
+ [![issues](https://img.shields.io/github/issues/Datalab-Rotterdam/nova-ai-cli?style=flat-square)](https://github.com/Datalab-Rotterdam/nova-ai-cli/issues)
14
+
15
+ Talk to DataLab Rotterdam's Nova AI from your terminal, or point your editor/IDE at it via [Agent Client Protocol](https://agentclientprotocol.com) — both modes share the same auth and run on [`@datalabrotterdam/nova-sdk`](https://www.npmjs.com/package/@datalabrotterdam/nova-sdk).
16
+
17
+ [npm](https://www.npmjs.com/package/@datalabrotterdam/nova-ai-cli) · [Issues](https://github.com/Datalab-Rotterdam/nova-ai-cli/issues) · [ACP docs](https://agentclientprotocol.com)
18
+
19
+ </div>
20
+
21
+ > **⚠️ Work in progress.** ACP mode (`--acp`) is the only fully implemented mode today — agentic tool use, permissions, and session persistence all work there. Interactive terminal chat (no flags) and the standalone browser UI (`--web`) are stubs that print a "not built yet" message. Expect breaking changes before a 1.0.
22
+
23
+ ---
24
+
25
+ ## Installation
26
+
27
+ No install needed — run directly with `npx`:
28
+
29
+ ```sh
30
+ npx @datalabrotterdam/nova-ai-cli --setup # store your Nova API key
31
+ npx @datalabrotterdam/nova-ai-cli # interactive chat (WIP, stub)
32
+ npx @datalabrotterdam/nova-ai-cli --acp # speak ACP over stdio (editors/IDEs) — fully working
33
+ npx @datalabrotterdam/nova-ai-cli --web # standalone browser UI (WIP, stub)
34
+ ```
35
+
36
+ Or install globally / as a project dependency:
37
+
38
+ ```sh
39
+ npm install -g @datalabrotterdam/nova-ai-cli
40
+ ```
41
+
42
+ **Requires:** Node.js >= 18, a [Nova AI](https://api.nova.datalabrotterdam.nl) API key.
43
+
44
+ ---
45
+
46
+ ## Overview
47
+
48
+ `nova-ai-cli` is a terminal client for Nova AI, in the same spirit as `claude`/`codex`. Pass `--acp` to run it in Agent Client Protocol mode, where it reads JSON-RPC requests from stdin and writes responses/notifications to stdout so any ACP-aware editor/IDE can drive it like any other coding agent — with tool calling, permission prompts, and persisted session history. Bare/`--web` modes are placeholders for now. All modes share the same stored credentials.
49
+
50
+ ```sh
51
+ # 1. one-time setup — opens a browser page to verify the key against Nova AI and store it locally
52
+ npx @datalabrotterdam/nova-ai-cli --setup
53
+
54
+ # 2. point your ACP client at this binary
55
+ npx @datalabrotterdam/nova-ai-cli --acp
56
+ ```
57
+
58
+ Most editors invoke `--acp` for you once configured as an agent — `--setup` is the one command you run by hand first.
59
+
60
+ **Status:** `--setup` and `--acp` (including tool calling and session persistence) are fully implemented. Interactive terminal chat (no flags) and `--web` are stubs — see the WIP note above.
61
+
62
+ ---
63
+
64
+ ## Auth
65
+
66
+ This agent advertises **Agent Auth** (per [`AUTHENTICATION.md`](https://github.com/agentclientprotocol/registry/blob/main/AUTHENTICATION.md)): when the client calls `authenticate`, the agent itself spins up a local HTTP server, opens your browser to it, and resolves once you've connected your account.
67
+
68
+ ```json
69
+ {
70
+ "id": "nova-api-key",
71
+ "name": "Nova API Key"
72
+ }
73
+ ```
74
+
75
+ Today the page served at that local URL is a small Svelte form that:
76
+ 1. Collects your Nova API key.
77
+ 2. Validates it against `client.models.list()`.
78
+ 3. Picks a default model (first enabled model) and stores `{ apiKey, defaultModel }` in `~/.nova-ai/credentials.json`.
79
+
80
+ You can also trigger this manually:
81
+
82
+ ```sh
83
+ npx @datalabrotterdam/nova-ai-cli --setup
84
+ ```
85
+
86
+ Overrides, no browser flow required:
87
+
88
+ | Env var | Purpose |
89
+ |---|---|
90
+ | `NOVA_API_KEY` | Skip stored credentials, use this key |
91
+ | `NOVA_MODEL` | Skip stored default model, use this model id |
92
+
93
+ A future version will swap this for real OAuth once DataLab Rotterdam ships an OAuth provider for Nova AI — same local server (`src/acp/auth-server.ts`), same lifecycle, just a different page/flow. Credential handling stays isolated in `src/acp/credentials.ts` either way.
94
+
95
+ ---
96
+
97
+ ## What it implements
98
+
99
+ | ACP method | Behavior |
100
+ |---|---|
101
+ | `initialize` | Returns protocol version + the `nova-api-key` agent auth method |
102
+ | `session/new` | Allocates a session id with in-memory history |
103
+ | `session/load` | Restores a previously-persisted session and replays its turns as `*_message_chunk` notifications |
104
+ | `session/list` | Lists stored sessions, optionally filtered by `cwd` |
105
+ | `authenticate` | Runs the local browser auth flow (`src/acp/auth-server.ts`) and resolves once a valid key is stored |
106
+ | `session/prompt` | Streams a `chat.completions.stream()` call, forwarding `agent_message_chunk` updates as text arrives; drives the tool-calling loop below |
107
+ | `session/cancel` | Aborts the in-flight Nova AI request via `AbortController` |
108
+
109
+ Only `text` and `resource_link` content blocks are read from prompts today — images/audio/embeddings supported by `nova-sdk` aren't wired up yet.
110
+
111
+ Sessions are persisted to disk (`src/acp/sessions.ts`) so `session/load` can rehydrate history, and a title is auto-derived from the conversation.
112
+
113
+ ### Tool calling
114
+
115
+ While streaming a response, the agent watches for a fenced tool-call marker in the model's output (`src/acp/tools/marker.ts`). When one appears, it stops streaming text and instead:
116
+
117
+ 1. Reports the pending call via `session/update` (`tool_call` with status `pending`).
118
+ 2. Requests permission from the client for any **mutating** tool (`allow_once` / `reject_once`), via `session/request_permission`.
119
+ 3. Executes the tool and reports the result/error via a `tool_call_update`.
120
+ 4. Feeds the tool result back into the conversation and loops (up to 10 rounds per prompt) until the model produces a plain answer.
121
+
122
+ Built-in tools (`src/acp/tools/registry.ts`):
123
+
124
+ | Tool | Mutating | Behavior |
125
+ |---|---|---|
126
+ | `read_file` | No | Reads a file's contents, gated by client `fs.readTextFile` capability |
127
+ | `write_file` | Yes | Writes/overwrites a file, gated by client `fs.writeTextFile` capability — requires permission |
128
+ | `run_command` | Yes | Runs a shell command in the session's `cwd` — requires permission |
129
+
130
+ Tools are filtered per-session by the client's advertised `clientCapabilities`, so a client without filesystem support never sees `read_file`/`write_file` offered.
131
+
132
+ ---
133
+
134
+ ## Development
135
+
136
+ ```sh
137
+ npm install
138
+ npm test # tsc --noEmit + node --test on tests/
139
+ npm run build # builds the Svelte setup page, then tsc -> dist/
140
+ ```
141
+
142
+ Releases are automated via `semantic-release` on push to `main` (see `.github/workflows/ci.yml`); commit messages drive version bumps.
143
+
144
+ ---
145
+
146
+ ## License
147
+
148
+ [Apache-2.0](./LICENSE) © DataLab Rotterdam
@@ -0,0 +1,12 @@
1
+ import * as acp from "@agentclientprotocol/sdk";
2
+ export declare class NovaAgent {
3
+ private readonly sessions;
4
+ private clientCapabilities;
5
+ initialize(params: acp.InitializeRequest): acp.InitializeResponse;
6
+ newSession(params: acp.NewSessionRequest): acp.NewSessionResponse;
7
+ loadSession(params: acp.LoadSessionRequest, client: acp.AgentContext): Promise<acp.LoadSessionResponse>;
8
+ listSessions(params: acp.ListSessionsRequest): acp.ListSessionsResponse;
9
+ authenticate(params: acp.AuthenticateRequest): Promise<acp.AuthenticateResponse>;
10
+ prompt(params: acp.PromptRequest, client: acp.AgentContext): Promise<acp.PromptResponse>;
11
+ cancel(params: acp.CancelNotification): void;
12
+ }
@@ -0,0 +1,206 @@
1
+ import * as acp from "@agentclientprotocol/sdk";
2
+ import { NovaAI, NovaAIError } from "@datalabrotterdam/nova-sdk";
3
+ import { runBrowserAuth } from "./auth-server.js";
4
+ import { readCredentials } from "./credentials.js";
5
+ import { appendSessionTurn, deriveTitle, listStoredSessions, loadStoredSession } from "./sessions.js";
6
+ import { availableTools, buildToolsSystemPrompt, extractToolCall, findTool, hasPendingFence, requestPermissionIfNeeded, sendToolCallPending, sendToolCallUpdate, } from "./tools/index.js";
7
+ const AUTH_METHOD_ID = "nova-api-key";
8
+ const MAX_TOOL_ROUNDS = 10;
9
+ export class NovaAgent {
10
+ sessions = new Map();
11
+ clientCapabilities;
12
+ initialize(params) {
13
+ this.clientCapabilities = params.clientCapabilities;
14
+ return {
15
+ protocolVersion: acp.PROTOCOL_VERSION,
16
+ agentCapabilities: {
17
+ loadSession: true,
18
+ sessionCapabilities: {
19
+ list: {},
20
+ },
21
+ },
22
+ authMethods: [
23
+ {
24
+ id: AUTH_METHOD_ID,
25
+ name: "Nova API Key",
26
+ description: "Opens a local page in your browser to connect your DataLab Rotterdam Nova AI account.",
27
+ },
28
+ ],
29
+ };
30
+ }
31
+ newSession(params) {
32
+ const sessionId = crypto.randomUUID();
33
+ this.sessions.set(sessionId, { pendingPrompt: null, cwd: params.cwd, history: [], title: null });
34
+ return { sessionId };
35
+ }
36
+ async loadSession(params, client) {
37
+ const stored = loadStoredSession(params.sessionId);
38
+ if (!stored) {
39
+ throw acp.RequestError.internalError(undefined, `Session ${params.sessionId} not found`);
40
+ }
41
+ this.sessions.set(params.sessionId, {
42
+ pendingPrompt: null,
43
+ cwd: params.cwd,
44
+ history: stored.messages,
45
+ title: stored.title,
46
+ });
47
+ for (const message of stored.messages) {
48
+ if (typeof message.content !== "string" || !message.content)
49
+ continue;
50
+ if (message.role === "user") {
51
+ await client.notify("session/update", {
52
+ sessionId: params.sessionId,
53
+ update: { sessionUpdate: "user_message_chunk", content: { type: "text", text: message.content } },
54
+ });
55
+ }
56
+ else if (message.role === "assistant") {
57
+ await client.notify("session/update", {
58
+ sessionId: params.sessionId,
59
+ update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: message.content } },
60
+ });
61
+ }
62
+ }
63
+ return {};
64
+ }
65
+ listSessions(params) {
66
+ const sessions = listStoredSessions(params.cwd ?? undefined).map((s) => ({
67
+ sessionId: s.sessionId,
68
+ cwd: s.cwd,
69
+ title: s.title,
70
+ updatedAt: s.updatedAt,
71
+ }));
72
+ return { sessions };
73
+ }
74
+ async authenticate(params) {
75
+ if (params.methodId !== AUTH_METHOD_ID) {
76
+ throw new Error(`Unknown auth method: ${params.methodId}`);
77
+ }
78
+ await runBrowserAuth();
79
+ return {};
80
+ }
81
+ async prompt(params, client) {
82
+ const session = this.sessions.get(params.sessionId);
83
+ if (!session) {
84
+ throw new Error(`Session ${params.sessionId} not found`);
85
+ }
86
+ const credentials = readCredentials();
87
+ if (!credentials) {
88
+ throw acp.RequestError.authRequired();
89
+ }
90
+ session.pendingPrompt?.abort();
91
+ const abortController = new AbortController();
92
+ session.pendingPrompt = abortController;
93
+ const novaClient = new NovaAI({ apiKey: credentials.apiKey });
94
+ const model = credentials.defaultModel ?? process.env.NOVA_MODEL;
95
+ if (!model) {
96
+ throw new Error("No Nova model configured. Re-run authentication or set NOVA_MODEL.");
97
+ }
98
+ const tools = availableTools(this.clientCapabilities);
99
+ const systemPrompt = buildToolsSystemPrompt(tools, session.cwd);
100
+ const userMessage = { role: "user", content: contentBlocksToText(params.prompt) };
101
+ session.history.push(userMessage);
102
+ const turnMessages = [userMessage];
103
+ const messages = [
104
+ ...(systemPrompt ? [{ role: "system", content: systemPrompt }] : []),
105
+ ...session.history,
106
+ ];
107
+ const pushTurn = (message) => {
108
+ session.history.push(message);
109
+ messages.push(message);
110
+ turnMessages.push(message);
111
+ };
112
+ try {
113
+ for (let round = 0; round < MAX_TOOL_ROUNDS; round++) {
114
+ if (abortController.signal.aborted) {
115
+ return { stopReason: "cancelled" };
116
+ }
117
+ let buffer = "";
118
+ let flushed = 0;
119
+ for await (const event of novaClient.chat.completions.stream({ model, messages }, { signal: abortController.signal })) {
120
+ if (event.type !== "chunk")
121
+ continue;
122
+ const text = event.data.choices?.[0]?.delta?.content;
123
+ if (typeof text !== "string" || text.length === 0)
124
+ continue;
125
+ buffer += text;
126
+ if (!hasPendingFence(buffer)) {
127
+ const toFlush = buffer.slice(flushed);
128
+ if (toFlush) {
129
+ await client.notify("session/update", {
130
+ sessionId: params.sessionId,
131
+ update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: toFlush } },
132
+ });
133
+ flushed = buffer.length;
134
+ }
135
+ }
136
+ }
137
+ const toolCall = extractToolCall(buffer);
138
+ if (!toolCall) {
139
+ const remaining = buffer.slice(flushed);
140
+ if (remaining) {
141
+ await client.notify("session/update", {
142
+ sessionId: params.sessionId,
143
+ update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: remaining } },
144
+ });
145
+ }
146
+ pushTurn({ role: "assistant", content: buffer });
147
+ return { stopReason: "end_turn" };
148
+ }
149
+ const tool = findTool(toolCall.name);
150
+ const toolCallId = crypto.randomUUID();
151
+ const toolCtx = { client, sessionId: params.sessionId, signal: abortController.signal };
152
+ pushTurn({ role: "assistant", content: buffer });
153
+ if (!tool) {
154
+ pushTurn({ role: "user", content: `Tool "${toolCall.name}" is not available.` });
155
+ continue;
156
+ }
157
+ await sendToolCallPending(toolCtx, toolCallId, tool, toolCall.args);
158
+ const allowed = await requestPermissionIfNeeded(toolCtx, toolCallId, tool, toolCall.args);
159
+ if (!allowed) {
160
+ await sendToolCallUpdate(toolCtx, toolCallId, "failed", "Permission denied by user.");
161
+ pushTurn({ role: "user", content: "Tool call rejected by user." });
162
+ continue;
163
+ }
164
+ const result = await tool.execute(toolCtx, toolCall.args);
165
+ if ("error" in result) {
166
+ await sendToolCallUpdate(toolCtx, toolCallId, "failed", result.error);
167
+ pushTurn({ role: "user", content: `Tool error: ${result.error}` });
168
+ }
169
+ else {
170
+ await sendToolCallUpdate(toolCtx, toolCallId, "completed", result.output);
171
+ pushTurn({ role: "user", content: `Tool result: ${result.output}` });
172
+ }
173
+ }
174
+ return { stopReason: "max_turn_requests" };
175
+ }
176
+ catch (err) {
177
+ if (abortController.signal.aborted) {
178
+ return { stopReason: "cancelled" };
179
+ }
180
+ if (err instanceof NovaAIError) {
181
+ throw new Error(`Nova AI request failed (status ${err.status}, requestId ${err.requestId}): ${err.message}`);
182
+ }
183
+ throw err;
184
+ }
185
+ finally {
186
+ session.pendingPrompt = null;
187
+ session.title ??= deriveTitle(session.history);
188
+ appendSessionTurn(params.sessionId, { cwd: session.cwd, title: session.title }, turnMessages);
189
+ }
190
+ }
191
+ cancel(params) {
192
+ this.sessions.get(params.sessionId)?.pendingPrompt?.abort();
193
+ }
194
+ }
195
+ function contentBlocksToText(prompt) {
196
+ return prompt
197
+ .map((block) => {
198
+ if (block.type === "text")
199
+ return block.text;
200
+ if (block.type === "resource_link")
201
+ return block.uri;
202
+ return "";
203
+ })
204
+ .filter(Boolean)
205
+ .join("\n");
206
+ }
@@ -0,0 +1,10 @@
1
+ import { credentialsPath } from "./credentials.js";
2
+ /**
3
+ * Agent Auth flow (AUTHENTICATION.md, type "agent"): the agent itself runs a
4
+ * local HTTP server and opens the browser. Today the page just collects a
5
+ * Nova API key; swapping to real OAuth later means changing what this page
6
+ * does (redirect to the provider's authorize URL, exchange the callback code)
7
+ * without touching the server lifecycle or the rest of the agent.
8
+ */
9
+ export declare function runBrowserAuth(): Promise<void>;
10
+ export { credentialsPath };
@@ -0,0 +1,67 @@
1
+ import { exec } from "node:child_process";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { NovaAI, NovaAIError } from "@datalabrotterdam/nova-sdk";
5
+ import { dir, json, WebServer } from "@sourceregistry/node-webserver";
6
+ import { credentialsPath, writeCredentials } from "./credentials.js";
7
+ const AUTH_TIMEOUT_MS = 5 * 60 * 1000;
8
+ const UI_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "src", "acp", "web", "dist");
9
+ function openBrowser(url) {
10
+ const cmd = process.platform === "darwin"
11
+ ? `open "${url}"`
12
+ : process.platform === "win32"
13
+ ? `start "" "${url}"`
14
+ : `xdg-open "${url}"`;
15
+ exec(cmd, () => {
16
+ // best-effort; the URL is always printed as a fallback
17
+ });
18
+ }
19
+ /**
20
+ * Agent Auth flow (AUTHENTICATION.md, type "agent"): the agent itself runs a
21
+ * local HTTP server and opens the browser. Today the page just collects a
22
+ * Nova API key; swapping to real OAuth later means changing what this page
23
+ * does (redirect to the provider's authorize URL, exchange the callback code)
24
+ * without touching the server lifecycle or the rest of the agent.
25
+ */
26
+ export function runBrowserAuth() {
27
+ return new Promise((resolve, reject) => {
28
+ const app = new WebServer();
29
+ app.POST("/api/authenticate", async (event) => {
30
+ const body = await event.request.json().catch(() => null);
31
+ const apiKey = typeof body?.apiKey === "string" ? body.apiKey.trim() : "";
32
+ if (!apiKey) {
33
+ return json({ message: "API key is required." }, { status: 400 });
34
+ }
35
+ try {
36
+ const client = new NovaAI({ apiKey });
37
+ const { data: models } = await client.models.list();
38
+ const defaultModel = (models.find((m) => m.enabled !== false) ?? models[0])?.id;
39
+ writeCredentials({ apiKey, defaultModel });
40
+ clearTimeout(timeout);
41
+ const response = json({ ok: true });
42
+ void app.shutdown().then(resolve);
43
+ return response;
44
+ }
45
+ catch (err) {
46
+ const message = err instanceof NovaAIError
47
+ ? `Nova AI rejected this key (status ${err.status}): ${err.message}`
48
+ : "Unexpected error validating the key.";
49
+ return json({ message }, { status: 401 });
50
+ }
51
+ });
52
+ app.GET("/", dir(UI_DIR, { spa: true }));
53
+ app.GET("/[...path]", dir(UI_DIR, { spa: true }));
54
+ const timeout = setTimeout(() => {
55
+ void app.shutdown();
56
+ reject(new Error("Nova AI authentication timed out after 5 minutes."));
57
+ }, AUTH_TIMEOUT_MS);
58
+ app.listen(0, "127.0.0.1", () => {
59
+ const address = app.address();
60
+ const port = typeof address === "object" && address ? address.port : 0;
61
+ const url = `http://127.0.0.1:${port}`;
62
+ console.error(`Opening browser to authenticate with Nova AI: ${url}`);
63
+ openBrowser(url);
64
+ });
65
+ });
66
+ }
67
+ export { credentialsPath };
@@ -0,0 +1,11 @@
1
+ export type StoredCredentials = {
2
+ apiKey: string;
3
+ defaultModel?: string;
4
+ };
5
+ /**
6
+ * Single place that owns "how we get the Nova API key", so swapping this for
7
+ * an OAuth-based Agent Auth flow later only touches this file.
8
+ */
9
+ export declare function readCredentials(): StoredCredentials | null;
10
+ export declare function writeCredentials(credentials: StoredCredentials): void;
11
+ export declare function credentialsPath(): string;