@hover-dev/core 0.2.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.
Files changed (55) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +59 -0
  3. package/dist/agents/argv.d.ts +11 -0
  4. package/dist/agents/argv.d.ts.map +1 -0
  5. package/dist/agents/argv.js +23 -0
  6. package/dist/agents/claude.d.ts +3 -0
  7. package/dist/agents/claude.d.ts.map +1 -0
  8. package/dist/agents/claude.js +145 -0
  9. package/dist/agents/detect.d.ts +16 -0
  10. package/dist/agents/detect.d.ts.map +1 -0
  11. package/dist/agents/detect.js +34 -0
  12. package/dist/agents/index.d.ts +6 -0
  13. package/dist/agents/index.d.ts.map +1 -0
  14. package/dist/agents/index.js +5 -0
  15. package/dist/agents/invoke.d.ts +10 -0
  16. package/dist/agents/invoke.d.ts.map +1 -0
  17. package/dist/agents/invoke.js +70 -0
  18. package/dist/agents/registry.d.ts +12 -0
  19. package/dist/agents/registry.d.ts.map +1 -0
  20. package/dist/agents/registry.js +15 -0
  21. package/dist/agents/types.d.ts +88 -0
  22. package/dist/agents/types.d.ts.map +1 -0
  23. package/dist/agents/types.js +23 -0
  24. package/dist/index.d.ts +3 -0
  25. package/dist/index.d.ts.map +1 -0
  26. package/dist/index.js +2 -0
  27. package/dist/playwright/cdpStatus.d.ts +29 -0
  28. package/dist/playwright/cdpStatus.d.ts.map +1 -0
  29. package/dist/playwright/cdpStatus.js +96 -0
  30. package/dist/playwright/launchChrome.d.ts +29 -0
  31. package/dist/playwright/launchChrome.d.ts.map +1 -0
  32. package/dist/playwright/launchChrome.js +137 -0
  33. package/dist/playwright/preflight.d.ts +31 -0
  34. package/dist/playwright/preflight.d.ts.map +1 -0
  35. package/dist/playwright/preflight.js +71 -0
  36. package/dist/scripts/start-chrome.d.ts +3 -0
  37. package/dist/scripts/start-chrome.d.ts.map +1 -0
  38. package/dist/scripts/start-chrome.js +23 -0
  39. package/dist/service.d.ts +22 -0
  40. package/dist/service.d.ts.map +1 -0
  41. package/dist/service.js +485 -0
  42. package/dist/skills/writeSkill.d.ts +50 -0
  43. package/dist/skills/writeSkill.d.ts.map +1 -0
  44. package/dist/skills/writeSkill.js +169 -0
  45. package/dist/specs/humanSteps.d.ts +25 -0
  46. package/dist/specs/humanSteps.d.ts.map +1 -0
  47. package/dist/specs/humanSteps.js +97 -0
  48. package/dist/specs/writeCaseCsv.d.ts +28 -0
  49. package/dist/specs/writeCaseCsv.d.ts.map +1 -0
  50. package/dist/specs/writeCaseCsv.js +140 -0
  51. package/dist/specs/writeSpec.d.ts +27 -0
  52. package/dist/specs/writeSpec.d.ts.map +1 -0
  53. package/dist/specs/writeSpec.js +265 -0
  54. package/mcp.config.json +12 -0
  55. package/package.json +78 -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 describing the origin of the Work and
141
+ 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 Hyperyond Studio
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,59 @@
1
+ # @hover-dev/core
2
+
3
+ The local Node service. Owns:
4
+
5
+ - **Agent invocation** (`src/agents/`) — Local CLI Agent First. Spawns `claude` / `codex` / `cursor` / ... and normalizes their output into a single `InvokeEvent` stream.
6
+ - **Playwright preflight** (`src/playwright/`) — verifies CDP connection to the user's Chrome.
7
+ - **Smoke test** (`src/smoke.ts`) — end-to-end verification of the whole chain.
8
+
9
+ ## Architecture (agents/)
10
+
11
+ "Local CLI Agent First" — Hover bundles no AI runtime. It spawns whichever coding-agent CLI is on the user's `PATH` and normalizes its output to a single event stream:
12
+
13
+ | File | Purpose |
14
+ |---|---|
15
+ | `types.ts` | `AgentDescriptor`, `InvokeOptions`, `InvokeEvent`, protocol/format enums, error classes |
16
+ | `registry.ts` | `AGENTS` constant — single source of truth for supported agents |
17
+ | `detect.ts` | `detectAgents()`, `resolveBinForAgent()`, `resolveOnPath()` — PATH scanning |
18
+ | `argv.ts` | `buildArgv()` — protocol-aware argv construction, throws `UnsupportedAgentProtocolError` for `acp` / `pi-rpc` |
19
+ | `invoke.ts` | `invokeAgent()` — async-iterable spawning + stdout streaming |
20
+ | `claude.ts` | Claude Code descriptor: `claude -p`, stream-json parser, sandbox flags |
21
+
22
+ To add an agent: implement an `AgentDescriptor`, register it in `registry.ts`. Done.
23
+
24
+ ## Smoke test
25
+
26
+ ```bash
27
+ # Terminal 1: run basic-app — also spawns a debug Chrome (the example sets
28
+ # `autoLaunchChrome: true`) navigated to http://localhost:5173
29
+ pnpm dev:example:basic-app # from repo root
30
+
31
+ # Terminal 2: run the smoke test
32
+ pnpm smoke # from repo root, defaults to http://localhost:5173
33
+ ```
34
+
35
+ Need the debug Chrome standalone (no example)? `pnpm smoke:chrome` (or `pnpm exec hover-chrome`).
36
+
37
+ Override the target or prompt:
38
+
39
+ ```bash
40
+ pnpm smoke http://localhost:5173/ "log in then add a todo named 'verify hover'"
41
+ ```
42
+
43
+ Environment variables:
44
+
45
+ - `HOVER_CDP` — CDP URL (default `http://localhost:9222`)
46
+ - `HOVER_AGENT` — agent id (default `claude`)
47
+ - `HOVER_MODEL` — model for the agent (default `sonnet`, much cheaper than opus)
48
+
49
+ ## Sandboxing (what the smoke test enforces)
50
+
51
+ The `claude -p` invocation is locked down so Claude can only drive the browser:
52
+
53
+ - `--strict-mcp-config` — ignore any MCP servers in `~/.claude/` or `.mcp.json`
54
+ - `--allowedTools mcp__playwright` — only Playwright MCP is callable
55
+ - `--disallowedTools Bash Edit Write Read Grep Glob Task WebFetch WebSearch` — every built-in tool explicitly denied
56
+ - `--permission-mode dontAsk` — anything not whitelisted aborts the run
57
+ - `--max-budget-usd 0.50` — hard ceiling per session
58
+
59
+ Together these enforce the rule that the spawned agent can only reach the browser via Playwright MCP — never the host filesystem, shell, or network. A hijacked prompt or hallucinated destructive action has nowhere to land.
@@ -0,0 +1,11 @@
1
+ import type { AgentDescriptor, InvokeOptions } from './types.js';
2
+ /**
3
+ * Build argv for spawning an agent.
4
+ *
5
+ * Per-agent argument logic lives on the descriptor (e.g. claude.ts owns its
6
+ * own `--mcp-config`, `--permission-mode` etc.). This dispatcher only
7
+ * gates by protocol — `acp` and `pi-rpc` are not yet implemented because
8
+ * they require a long-lived bidirectional channel rather than argv.
9
+ */
10
+ export declare function buildArgv(descriptor: AgentDescriptor, opts: InvokeOptions): string[];
11
+ //# sourceMappingURL=argv.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"argv.d.ts","sourceRoot":"","sources":["../../src/agents/argv.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAGjE;;;;;;;GAOG;AACH,wBAAgB,SAAS,CAAC,UAAU,EAAE,eAAe,EAAE,IAAI,EAAE,aAAa,GAAG,MAAM,EAAE,CAepF"}
@@ -0,0 +1,23 @@
1
+ import { UnsupportedAgentProtocolError } from './types.js';
2
+ /**
3
+ * Build argv for spawning an agent.
4
+ *
5
+ * Per-agent argument logic lives on the descriptor (e.g. claude.ts owns its
6
+ * own `--mcp-config`, `--permission-mode` etc.). This dispatcher only
7
+ * gates by protocol — `acp` and `pi-rpc` are not yet implemented because
8
+ * they require a long-lived bidirectional channel rather than argv.
9
+ */
10
+ export function buildArgv(descriptor, opts) {
11
+ switch (descriptor.protocol) {
12
+ case 'argv':
13
+ case 'stdin':
14
+ return descriptor.buildArgs(opts);
15
+ case 'acp':
16
+ case 'pi-rpc':
17
+ throw new UnsupportedAgentProtocolError(`Agent protocol "${descriptor.protocol}" is not yet implemented (agent: ${descriptor.id})`);
18
+ default: {
19
+ const exhaustive = descriptor.protocol;
20
+ throw new UnsupportedAgentProtocolError(`Unknown protocol: ${String(exhaustive)}`);
21
+ }
22
+ }
23
+ }
@@ -0,0 +1,3 @@
1
+ import type { AgentDescriptor } from './types.js';
2
+ export declare const claudeAgent: AgentDescriptor;
3
+ //# sourceMappingURL=claude.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"claude.d.ts","sourceRoot":"","sources":["../../src/agents/claude.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAA8B,MAAM,YAAY,CAAC;AA2E9E,eAAO,MAAM,WAAW,EAAE,eA4GzB,CAAC"}
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Running-cost accumulator across one parser lifecycle. Claude Code's
3
+ * stream-json sometimes carries `total_cost_usd` on intermediate events; when
4
+ * it does we just forward it. When it doesn't, we estimate from token usage
5
+ * using public per-million pricing. Hardcoded rates because they change
6
+ * rarely and we'd rather not network-fetch a price table from a sandbox.
7
+ *
8
+ * The estimate is empirically about 1.5–2× the authoritative
9
+ * `total_cost_usd` that arrives on the final `result` event (overhead from
10
+ * tool-definition tokens we don't see + Claude's actual cache hit ratios
11
+ * vs. our pessimistic accounting). That's fine for the widget's purpose:
12
+ * give the user a signal of cost direction and order-of-magnitude so they
13
+ * know when to hit Stop. The done card displays the final authoritative
14
+ * number from `total_cost_usd`, so the user always sees the ground truth.
15
+ */
16
+ const PRICE_PER_M_USD = {
17
+ // claude-sonnet-4 / 4.5 / 4.6 / 4.7 — all priced the same as of 2026
18
+ sonnet: { in: 3, out: 15, cacheCreate: 3.75, cacheRead: 0.3 },
19
+ opus: { in: 15, out: 75, cacheCreate: 18.75, cacheRead: 1.5 },
20
+ haiku: { in: 1, out: 5, cacheCreate: 1.25, cacheRead: 0.1 },
21
+ };
22
+ function estimateCostUsd(modelHint, usage) {
23
+ // Match the most specific tier by substring. e.g. 'claude-sonnet-4-6' → sonnet.
24
+ const m = (modelHint ?? 'sonnet').toLowerCase();
25
+ const tier = m.includes('opus') ? PRICE_PER_M_USD.opus :
26
+ m.includes('haiku') ? PRICE_PER_M_USD.haiku :
27
+ PRICE_PER_M_USD.sonnet;
28
+ return ((usage.input_tokens ?? 0) * tier.in +
29
+ (usage.output_tokens ?? 0) * tier.out +
30
+ (usage.cache_creation_input_tokens ?? 0) * tier.cacheCreate +
31
+ (usage.cache_read_input_tokens ?? 0) * tier.cacheRead) / 1_000_000;
32
+ }
33
+ /**
34
+ * Per-session running totals. Reset on every `system/init` event (one per
35
+ * agent invocation). Safe as module-level state because service.ts enforces
36
+ * one in-flight invocation per Hover service via its `busy` lock, and each
37
+ * Vite dev server spawns its own Node process with its own module instance.
38
+ */
39
+ let runningCost = 0;
40
+ let runningTurns = 0;
41
+ let runningModel;
42
+ export const claudeAgent = {
43
+ id: 'claude',
44
+ binName: 'claude',
45
+ protocol: 'argv',
46
+ streamFormat: 'stream-json',
47
+ buildArgs(opts) {
48
+ const args = ['-p', opts.prompt];
49
+ args.push('--output-format', 'stream-json', '--verbose');
50
+ args.push('--permission-mode', 'dontAsk');
51
+ if (opts.mcpConfig) {
52
+ args.push('--mcp-config', opts.mcpConfig, '--strict-mcp-config');
53
+ }
54
+ if (opts.allowedTools?.length) {
55
+ args.push('--allowedTools', ...opts.allowedTools);
56
+ }
57
+ if (opts.disallowedTools?.length) {
58
+ args.push('--disallowedTools', ...opts.disallowedTools);
59
+ }
60
+ if (opts.maxBudgetUsd != null) {
61
+ args.push('--max-budget-usd', String(opts.maxBudgetUsd));
62
+ }
63
+ if (opts.model) {
64
+ args.push('--model', opts.model);
65
+ }
66
+ if (opts.sessionId) {
67
+ args.push('--resume', opts.sessionId);
68
+ }
69
+ if (opts.appendSystemPrompt && opts.appendSystemPrompt.trim().length > 0) {
70
+ args.push('--append-system-prompt', opts.appendSystemPrompt);
71
+ }
72
+ return args;
73
+ },
74
+ parseEvent(line) {
75
+ if (!line.trim())
76
+ return [];
77
+ let ev;
78
+ try {
79
+ ev = JSON.parse(line);
80
+ }
81
+ catch {
82
+ return [{ kind: 'raw', line }];
83
+ }
84
+ const out = [];
85
+ if (ev.type === 'system' && ev.subtype === 'init') {
86
+ // Fresh session — reset the cost/turn accumulator.
87
+ runningCost = 0;
88
+ runningTurns = 0;
89
+ runningModel = ev.model;
90
+ if (ev.session_id) {
91
+ out.push({ kind: 'session_start', sessionId: ev.session_id, model: ev.model });
92
+ }
93
+ for (const server of ev.mcp_servers ?? []) {
94
+ out.push({ kind: 'mcp_status', server: server.name, status: server.status });
95
+ }
96
+ return out;
97
+ }
98
+ if (ev.type === 'assistant') {
99
+ runningTurns += 1;
100
+ // Claude Code sometimes carries `total_cost_usd` on intermediate events;
101
+ // when present it's authoritative (server-computed, includes anything
102
+ // we'd miss). When absent, estimate from this turn's usage so the widget
103
+ // still shows a growing $ counter on long runs.
104
+ if (typeof ev.total_cost_usd === 'number') {
105
+ runningCost = ev.total_cost_usd;
106
+ }
107
+ else if (ev.message?.usage) {
108
+ runningCost += estimateCostUsd(runningModel ?? ev.message.model, ev.message.usage);
109
+ }
110
+ out.push({ kind: 'usage', costUsd: runningCost, turns: runningTurns });
111
+ for (const block of ev.message?.content ?? []) {
112
+ if (block.type === 'tool_use') {
113
+ const name = block.name ?? '';
114
+ const tool = name.replace(/^mcp__playwright__/, '');
115
+ out.push({ kind: 'tool_use', tool, input: block.input });
116
+ }
117
+ else if (block.type === 'text') {
118
+ const text = block.text?.trim();
119
+ if (text)
120
+ out.push({ kind: 'text', text });
121
+ }
122
+ }
123
+ return out;
124
+ }
125
+ if (ev.type === 'user') {
126
+ for (const block of ev.message?.content ?? []) {
127
+ if (block.type === 'tool_result') {
128
+ out.push({ kind: 'tool_result', isError: block.is_error });
129
+ }
130
+ }
131
+ return out;
132
+ }
133
+ if (ev.type === 'result') {
134
+ out.push({
135
+ kind: 'session_end',
136
+ turns: ev.num_turns,
137
+ costUsd: ev.total_cost_usd,
138
+ isError: ev.is_error,
139
+ summary: ev.result,
140
+ });
141
+ return out;
142
+ }
143
+ return [];
144
+ },
145
+ };
@@ -0,0 +1,16 @@
1
+ import type { AgentDescriptor } from './types.js';
2
+ /**
3
+ * Find a binary on PATH. Returns absolute path or null.
4
+ * macOS/Linux uses `which`; Windows uses `where`.
5
+ */
6
+ export declare function resolveOnPath(binName: string): Promise<string | null>;
7
+ export declare function resolveBinForAgent(descriptor: AgentDescriptor): Promise<string | null>;
8
+ export interface DetectedAgent {
9
+ descriptor: AgentDescriptor;
10
+ binPath: string;
11
+ }
12
+ /**
13
+ * Scan PATH for every agent in the registry. Returns only the ones found.
14
+ */
15
+ export declare function detectAgents(): Promise<DetectedAgent[]>;
16
+ //# sourceMappingURL=detect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"detect.d.ts","sourceRoot":"","sources":["../../src/agents/detect.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAIlD;;;GAGG;AACH,wBAAsB,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAS3E;AAED,wBAAsB,kBAAkB,CAAC,UAAU,EAAE,eAAe,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAE5F;AAED,MAAM,WAAW,aAAa;IAC5B,UAAU,EAAE,eAAe,CAAC;IAC5B,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;GAEG;AACH,wBAAsB,YAAY,IAAI,OAAO,CAAC,aAAa,EAAE,CAAC,CAO7D"}
@@ -0,0 +1,34 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { AGENTS } from './registry.js';
4
+ const execFileAsync = promisify(execFile);
5
+ /**
6
+ * Find a binary on PATH. Returns absolute path or null.
7
+ * macOS/Linux uses `which`; Windows uses `where`.
8
+ */
9
+ export async function resolveOnPath(binName) {
10
+ const tool = process.platform === 'win32' ? 'where' : 'which';
11
+ try {
12
+ const { stdout } = await execFileAsync(tool, [binName]);
13
+ const first = stdout.split('\n')[0]?.trim();
14
+ return first && first.length > 0 ? first : null;
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ }
20
+ export async function resolveBinForAgent(descriptor) {
21
+ return resolveOnPath(descriptor.binName);
22
+ }
23
+ /**
24
+ * Scan PATH for every agent in the registry. Returns only the ones found.
25
+ */
26
+ export async function detectAgents() {
27
+ const detected = [];
28
+ for (const descriptor of Object.values(AGENTS)) {
29
+ const binPath = await resolveBinForAgent(descriptor);
30
+ if (binPath)
31
+ detected.push({ descriptor, binPath });
32
+ }
33
+ return detected;
34
+ }
@@ -0,0 +1,6 @@
1
+ export * from './types.js';
2
+ export * from './detect.js';
3
+ export * from './invoke.js';
4
+ export * from './registry.js';
5
+ export * from './argv.js';
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/agents/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,eAAe,CAAC;AAC9B,cAAc,WAAW,CAAC"}
@@ -0,0 +1,5 @@
1
+ export * from './types.js';
2
+ export * from './detect.js';
3
+ export * from './invoke.js';
4
+ export * from './registry.js';
5
+ export * from './argv.js';
@@ -0,0 +1,10 @@
1
+ import type { InvokeEvent, InvokeOptions } from './types.js';
2
+ /**
3
+ * Spawn an agent and yield normalized InvokeEvents as they arrive.
4
+ *
5
+ * Caller is responsible for the lifecycle of `AsyncIterable`: iterating
6
+ * to completion drains stdout; aborting via `break` will leave the child
7
+ * running (use AbortController in a future iteration if needed).
8
+ */
9
+ export declare function invokeAgent(opts: InvokeOptions): AsyncIterable<InvokeEvent>;
10
+ //# sourceMappingURL=invoke.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invoke.d.ts","sourceRoot":"","sources":["../../src/agents/invoke.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAE7D;;;;;;GAMG;AACH,wBAAuB,WAAW,CAAC,IAAI,EAAE,aAAa,GAAG,aAAa,CAAC,WAAW,CAAC,CAwDlF"}
@@ -0,0 +1,70 @@
1
+ // cross-spawn is a drop-in for child_process.spawn that fixes Windows behaviour
2
+ // around `.cmd`/`.bat` shims (e.g. npm-installed `claude.cmd`). The return type
3
+ // is identical to node:child_process so call sites are unchanged.
4
+ import spawn from 'cross-spawn';
5
+ import { createInterface } from 'node:readline';
6
+ import { buildArgv } from './argv.js';
7
+ import { resolveBinForAgent } from './detect.js';
8
+ import { getAgent } from './registry.js';
9
+ import { AgentNotInstalledError, UnsupportedAgentProtocolError, } from './types.js';
10
+ /**
11
+ * Spawn an agent and yield normalized InvokeEvents as they arrive.
12
+ *
13
+ * Caller is responsible for the lifecycle of `AsyncIterable`: iterating
14
+ * to completion drains stdout; aborting via `break` will leave the child
15
+ * running (use AbortController in a future iteration if needed).
16
+ */
17
+ export async function* invokeAgent(opts) {
18
+ const descriptor = getAgent(opts.agentId);
19
+ if (!descriptor) {
20
+ throw new UnsupportedAgentProtocolError(`Unknown agent: ${opts.agentId}`);
21
+ }
22
+ const bin = await resolveBinForAgent(descriptor);
23
+ if (!bin)
24
+ throw new AgentNotInstalledError(opts.agentId);
25
+ const argv = buildArgv(descriptor, opts);
26
+ const usesStdinPrompt = descriptor.protocol === 'stdin';
27
+ const child = spawn(bin, argv, {
28
+ stdio: [usesStdinPrompt ? 'pipe' : 'ignore', 'pipe', 'inherit'],
29
+ cwd: opts.cwd,
30
+ // Clear CLAUDECODE so spawning `claude` from inside a Claude Code session
31
+ // doesn't trip the nested-session guard. Harmless for other agents.
32
+ env: { ...process.env, CLAUDECODE: '' },
33
+ });
34
+ // Wire abort: when the caller signals (e.g. WS disconnect), terminate the
35
+ // child so we don't leak orphan agent processes that keep driving the
36
+ // browser after the user has navigated away.
37
+ const onAbort = () => {
38
+ if (!child.killed)
39
+ child.kill('SIGTERM');
40
+ };
41
+ if (opts.signal) {
42
+ if (opts.signal.aborted)
43
+ onAbort();
44
+ else
45
+ opts.signal.addEventListener('abort', onAbort, { once: true });
46
+ }
47
+ if (usesStdinPrompt && child.stdin) {
48
+ child.stdin.write(opts.prompt);
49
+ child.stdin.end();
50
+ }
51
+ const rl = createInterface({ input: child.stdout });
52
+ const exitPromise = new Promise(res => child.on('exit', c => res(c ?? -1)));
53
+ let sawSessionEnd = false;
54
+ for await (const line of rl) {
55
+ for (const ev of descriptor.parseEvent(line)) {
56
+ if (ev.kind === 'session_end')
57
+ sawSessionEnd = true;
58
+ yield ev;
59
+ }
60
+ }
61
+ const code = await exitPromise;
62
+ opts.signal?.removeEventListener('abort', onAbort);
63
+ if (!sawSessionEnd && code !== 0 && !opts.signal?.aborted) {
64
+ yield {
65
+ kind: 'session_end',
66
+ isError: true,
67
+ summary: `agent exited with code ${code}`,
68
+ };
69
+ }
70
+ }
@@ -0,0 +1,12 @@
1
+ import type { AgentDescriptor } from './types.js';
2
+ /**
3
+ * Registry of agents Hover can drive. Currently only `claude` is fully wired.
4
+ *
5
+ * To add support for another agent (e.g. codex, cursor-agent, aider, gemini,
6
+ * cline, continue, qwen, kilo), implement its AgentDescriptor in its own
7
+ * file and register it here. The rest of the system — detect, argv, invoke,
8
+ * smoke — works without further changes.
9
+ */
10
+ export declare const AGENTS: Record<string, AgentDescriptor>;
11
+ export declare function getAgent(id: string): AgentDescriptor | undefined;
12
+ //# sourceMappingURL=registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/agents/registry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAGlD;;;;;;;GAOG;AACH,eAAO,MAAM,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAElD,CAAC;AAEF,wBAAgB,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,eAAe,GAAG,SAAS,CAEhE"}
@@ -0,0 +1,15 @@
1
+ import { claudeAgent } from './claude.js';
2
+ /**
3
+ * Registry of agents Hover can drive. Currently only `claude` is fully wired.
4
+ *
5
+ * To add support for another agent (e.g. codex, cursor-agent, aider, gemini,
6
+ * cline, continue, qwen, kilo), implement its AgentDescriptor in its own
7
+ * file and register it here. The rest of the system — detect, argv, invoke,
8
+ * smoke — works without further changes.
9
+ */
10
+ export const AGENTS = {
11
+ [claudeAgent.id]: claudeAgent,
12
+ };
13
+ export function getAgent(id) {
14
+ return AGENTS[id];
15
+ }