awel 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.
Files changed (85) hide show
  1. package/LICENSE +200 -0
  2. package/README.md +98 -0
  3. package/babel-plugin-awel-source.cjs +79 -0
  4. package/bin/awel.js +2 -0
  5. package/dist/cli/agent.d.ts +6 -0
  6. package/dist/cli/agent.js +266 -0
  7. package/dist/cli/babel-setup.d.ts +1 -0
  8. package/dist/cli/babel-setup.js +180 -0
  9. package/dist/cli/comment-popup.d.ts +2 -0
  10. package/dist/cli/comment-popup.js +206 -0
  11. package/dist/cli/config.d.ts +14 -0
  12. package/dist/cli/config.js +29 -0
  13. package/dist/cli/devserver.d.ts +17 -0
  14. package/dist/cli/devserver.js +43 -0
  15. package/dist/cli/index.d.ts +1 -0
  16. package/dist/cli/index.js +34 -0
  17. package/dist/cli/inspector.d.ts +2 -0
  18. package/dist/cli/inspector.js +117 -0
  19. package/dist/cli/logger.d.ts +10 -0
  20. package/dist/cli/logger.js +40 -0
  21. package/dist/cli/plan-store.d.ts +14 -0
  22. package/dist/cli/plan-store.js +18 -0
  23. package/dist/cli/providers/registry.d.ts +17 -0
  24. package/dist/cli/providers/registry.js +112 -0
  25. package/dist/cli/providers/types.d.ts +17 -0
  26. package/dist/cli/providers/types.js +1 -0
  27. package/dist/cli/providers/vercel.d.ts +4 -0
  28. package/dist/cli/providers/vercel.js +483 -0
  29. package/dist/cli/proxy.d.ts +5 -0
  30. package/dist/cli/proxy.js +72 -0
  31. package/dist/cli/server.d.ts +7 -0
  32. package/dist/cli/server.js +104 -0
  33. package/dist/cli/session.d.ts +32 -0
  34. package/dist/cli/session.js +77 -0
  35. package/dist/cli/skills/react-best-practices.md +2934 -0
  36. package/dist/cli/skills/skills/react-best-practices.md +2934 -0
  37. package/dist/cli/sse.d.ts +17 -0
  38. package/dist/cli/sse.js +51 -0
  39. package/dist/cli/subprocess.d.ts +30 -0
  40. package/dist/cli/subprocess.js +163 -0
  41. package/dist/cli/tools/ask-user.d.ts +11 -0
  42. package/dist/cli/tools/ask-user.js +28 -0
  43. package/dist/cli/tools/bash.d.ts +4 -0
  44. package/dist/cli/tools/bash.js +30 -0
  45. package/dist/cli/tools/code-search.d.ts +4 -0
  46. package/dist/cli/tools/code-search.js +70 -0
  47. package/dist/cli/tools/edit.d.ts +6 -0
  48. package/dist/cli/tools/edit.js +37 -0
  49. package/dist/cli/tools/glob.d.ts +4 -0
  50. package/dist/cli/tools/glob.js +29 -0
  51. package/dist/cli/tools/grep.d.ts +5 -0
  52. package/dist/cli/tools/grep.js +146 -0
  53. package/dist/cli/tools/index.d.ts +86 -0
  54. package/dist/cli/tools/index.js +41 -0
  55. package/dist/cli/tools/ls.d.ts +3 -0
  56. package/dist/cli/tools/ls.js +31 -0
  57. package/dist/cli/tools/multi-edit.d.ts +8 -0
  58. package/dist/cli/tools/multi-edit.js +53 -0
  59. package/dist/cli/tools/propose-plan.d.ts +4 -0
  60. package/dist/cli/tools/propose-plan.js +21 -0
  61. package/dist/cli/tools/react-best-practices.d.ts +3 -0
  62. package/dist/cli/tools/react-best-practices.js +55 -0
  63. package/dist/cli/tools/read.d.ts +3 -0
  64. package/dist/cli/tools/read.js +24 -0
  65. package/dist/cli/tools/restart-dev-server.d.ts +3 -0
  66. package/dist/cli/tools/restart-dev-server.js +18 -0
  67. package/dist/cli/tools/todo.d.ts +8 -0
  68. package/dist/cli/tools/todo.js +59 -0
  69. package/dist/cli/tools/web-fetch.d.ts +5 -0
  70. package/dist/cli/tools/web-fetch.js +116 -0
  71. package/dist/cli/tools/web-search.d.ts +5 -0
  72. package/dist/cli/tools/web-search.js +74 -0
  73. package/dist/cli/tools/write.d.ts +4 -0
  74. package/dist/cli/tools/write.js +26 -0
  75. package/dist/cli/types.d.ts +16 -0
  76. package/dist/cli/types.js +2 -0
  77. package/dist/cli/undo.d.ts +49 -0
  78. package/dist/cli/undo.js +212 -0
  79. package/dist/cli/verbose.d.ts +7 -0
  80. package/dist/cli/verbose.js +60 -0
  81. package/dist/dashboard/assets/index-Bk--q3wu.js +313 -0
  82. package/dist/dashboard/assets/index-DkWV03So.css +1 -0
  83. package/dist/dashboard/index.html +16 -0
  84. package/dist/host/host.js +274 -0
  85. package/package.json +67 -0
package/LICENSE ADDED
@@ -0,0 +1,200 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. Please also get an original
186
+ source header from http://www.apache.org/legal/apply-license.html.
187
+
188
+ Copyright [yyyy] [name of copyright owner]
189
+
190
+ Licensed under the Apache License, Version 2.0 (the "License");
191
+ you may not use this file except in compliance with the License.
192
+ You may obtain a copy of the License at
193
+
194
+ http://www.apache.org/licenses/LICENSE-2.0
195
+
196
+ Unless required by applicable law or agreed to in writing, software
197
+ distributed under the License is distributed on an "AS IS" BASIS,
198
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
199
+ See the License for the specific language governing permissions and
200
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,98 @@
1
+ # Awel
2
+
3
+ AI-powered development overlay for Next.js. Awel runs a proxy in front of your dev server, injects a floating chat button into your app, and lets you talk to an AI agent that can read, write, and edit files in your project — all from an embedded dashboard.
4
+
5
+ ![Awel dashboard overlay](docs/screenshot.png)
6
+
7
+ ## Quick Start
8
+
9
+ ```bash
10
+ # Skip if you're already in a Next.js app
11
+ npx create-next-app@latest my-app && cd my-app
12
+
13
+ npx awel dev
14
+ ```
15
+
16
+ This starts Awel on port 3001 and proxies your Next.js dev server on port 3000. Open `http://localhost:3001` to see your app with the Awel overlay.
17
+
18
+ ### Options
19
+
20
+ ```
21
+ awel dev [options]
22
+
23
+ -p, --port <port> Target app port (default: 3000)
24
+ -v, --verbose Print LLM stream events to stderr
25
+ ```
26
+
27
+ ## How It Works
28
+
29
+ Awel sits between your browser and your dev server:
30
+
31
+ ```
32
+ Browser → Awel (proxy on :3001) → Your app (dev server on :3000)
33
+ ```
34
+
35
+ 1. Awel intercepts HTML responses and injects a small script into the page
36
+ 2. The script renders a floating button (bottom-right corner, isolated via Shadow DOM)
37
+ 3. Clicking it opens a full-screen chat dashboard in an iframe
38
+ 4. You describe what you want — the AI agent reads your code, makes edits, runs commands, and streams results back in real-time
39
+
40
+ HMR/WebSocket traffic is proxied through transparently and paused during agent file edits to prevent reload interference.
41
+
42
+ ## Supported Models
43
+
44
+ Awel uses the [Vercel AI SDK](https://sdk.vercel.ai) and supports multiple providers. Set the corresponding environment variable to enable a provider:
45
+
46
+ | Provider | Env Var | Example Models |
47
+ |----------|---------|----------------|
48
+ | Claude Code | Claude CLI in PATH | sonnet, opus, haiku |
49
+ | Anthropic API | `ANTHROPIC_API_KEY` | claude-sonnet-4-5, claude-opus-4-5 |
50
+ | OpenAI | `OPENAI_API_KEY` | gpt-5.2-codex, gpt-5.1-codex |
51
+ | Google AI | `GOOGLE_GENERATIVE_AI_API_KEY` | gemini-3-pro-preview, gemini-2.5-pro |
52
+ | Qwen | `DASHSCOPE_API_KEY` | qwen-max, qwen-plus-latest |
53
+ | MiniMax | `MINIMAX_API_KEY` | MiniMax-M2 |
54
+ | Vercel Gateway | `AI_GATEWAY_API_KEY` | Various models via gateway |
55
+
56
+ Switch models at any time from the dropdown in the dashboard header.
57
+
58
+ ## Agent Tools
59
+
60
+ The AI agent has access to:
61
+
62
+ - **Read** / **Write** / **Edit** / **MultiEdit** — file operations
63
+ - **Bash** — run shell commands
64
+ - **Glob** / **Grep** / **CodeSearch** — find files and search code
65
+ - **WebSearch** / **WebFetch** — look things up on the web
66
+ - **ProposePlan** — propose a multi-step plan for your approval before executing
67
+ - **AskUser** — ask you clarifying questions mid-stream
68
+ - **RestartDevServer** — restart your dev server after config changes
69
+ - **TodoRead** / **TodoWrite** — track tasks across the conversation
70
+
71
+ ## Features
72
+
73
+ - **Element inspector** — click the crosshair icon to select an element in your app and attach it as context to your prompt
74
+ - **Image attachments** — attach screenshots or reference images
75
+ - **Plan approval** — the agent can propose plans for you to review before making changes
76
+ - **Undo** — roll back all file changes from an agent session in one click
77
+ - **Diff review** — review a summary of all file changes before accepting
78
+ - **Dark mode** — follows your system preference
79
+ - **i18n** — English and Chinese
80
+
81
+ ## Development
82
+
83
+ ```bash
84
+ npm run build # Build everything
85
+ npm run dev # Watch mode (CLI only)
86
+ ```
87
+
88
+ Individual builds:
89
+
90
+ ```bash
91
+ npm run build:cli # TypeScript → dist/cli/
92
+ npm run build:dashboard # Vite → dist/dashboard/
93
+ npm run build:host # esbuild → dist/host/host.js
94
+ ```
95
+
96
+ ## License
97
+
98
+ MIT
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Babel plugin that injects data-source-loc and data-source-component
3
+ * attributes into JSX elements so the Awel inspector can map DOM nodes
4
+ * back to source code.
5
+ *
6
+ * Only processes user code (skips node_modules) and only targets
7
+ * intrinsic HTML elements (lowercase tags) to avoid passing unknown
8
+ * props into React components.
9
+ */
10
+ module.exports = function ({ types: t }) {
11
+ return {
12
+ name: 'awel-source',
13
+ visitor: {
14
+ JSXOpeningElement(path, state) {
15
+ if (process.env.NODE_ENV === 'production') return;
16
+
17
+ const filename = state.filename;
18
+ if (!filename || filename.includes('node_modules')) return;
19
+
20
+ const name = path.node.name;
21
+
22
+ // Only add to intrinsic HTML elements (lowercase), not React components
23
+ if (!t.isJSXIdentifier(name) || !/^[a-z]/.test(name.name)) return;
24
+
25
+ const attrs = path.node.attributes;
26
+
27
+ // Skip if already annotated
28
+ if (attrs.some(a => t.isJSXAttribute(a) && a.name && a.name.name === 'data-source-loc')) return;
29
+
30
+ const loc = path.node.loc && path.node.loc.start;
31
+ if (!loc) return;
32
+
33
+ // Make path relative to project root
34
+ const cwd = state.cwd || process.cwd();
35
+ const relative = filename.startsWith(cwd)
36
+ ? filename.slice(cwd.length + 1)
37
+ : filename;
38
+
39
+ // data-source-loc="file:line:col"
40
+ attrs.push(
41
+ t.jsxAttribute(
42
+ t.jsxIdentifier('data-source-loc'),
43
+ t.stringLiteral(relative + ':' + loc.line + ':' + (loc.column || 0))
44
+ )
45
+ );
46
+
47
+ // Walk up AST to find the enclosing React component name
48
+ var parent = path.parentPath;
49
+ while (parent) {
50
+ var node = parent.node;
51
+ var componentName = null;
52
+
53
+ if (parent.isFunctionDeclaration() && node.id) {
54
+ componentName = node.id.name;
55
+ } else if (
56
+ (parent.isArrowFunctionExpression() || parent.isFunctionExpression()) &&
57
+ parent.parentPath &&
58
+ parent.parentPath.isVariableDeclarator() &&
59
+ t.isIdentifier(parent.parentPath.node.id)
60
+ ) {
61
+ componentName = parent.parentPath.node.id.name;
62
+ }
63
+
64
+ if (componentName && /^[A-Z]/.test(componentName)) {
65
+ attrs.push(
66
+ t.jsxAttribute(
67
+ t.jsxIdentifier('data-source-component'),
68
+ t.stringLiteral(componentName)
69
+ )
70
+ );
71
+ break;
72
+ }
73
+
74
+ parent = parent.parentPath;
75
+ }
76
+ }
77
+ }
78
+ };
79
+ };
package/bin/awel.js ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import '../dist/cli/index.js';
@@ -0,0 +1,6 @@
1
+ import { Hono } from 'hono';
2
+ /**
3
+ * Creates the agent API routes with SSE streaming.
4
+ * @param projectCwd - The user's project directory (where they ran `awel dev`)
5
+ */
6
+ export declare function createAgentRoute(projectCwd: string, targetPort: number): Hono<import("hono/types").BlankEnv, import("hono/types").BlankSchema, "/">;
@@ -0,0 +1,266 @@
1
+ import { Hono } from 'hono';
2
+ import { streamSSE } from 'hono/streaming';
3
+ import { EventEmitter } from 'node:events';
4
+ import { z } from 'zod';
5
+ import { addToHistory, getHistory, clearHistory } from './sse.js';
6
+ import { getModelCatalogWithAvailability } from './providers/registry.js';
7
+ import { getOrCreateSession, getSessionMessages, appendUserMessage, appendResponseMessages, resetSession } from './session.js';
8
+ import { getActivePlan, approvePlan } from './plan-store.js';
9
+ import { restartDevServer, getDevServerStatus } from './subprocess.js';
10
+ const DEFAULT_MODEL = 'sonnet';
11
+ // ─── Shared SSE Event Bus ────────────────────────────────────
12
+ // Events flow: POST /api/chat → provider → bus → GET /api/stream → client
13
+ const streamBus = new EventEmitter();
14
+ streamBus.setMaxListeners(0);
15
+ // Tracks the active stream so a new request cancels any in-flight LLM call.
16
+ let activeStreamAbort = null;
17
+ // ─── Request Schemas ─────────────────────────────────────────
18
+ const ConsoleEntrySchema = z.object({
19
+ level: z.string(),
20
+ message: z.string(),
21
+ source: z.string().optional(),
22
+ line: z.number().optional(),
23
+ column: z.number().optional(),
24
+ sourceTrace: z.array(z.object({
25
+ source: z.string(),
26
+ line: z.number().optional(),
27
+ })).optional(),
28
+ stack: z.string().optional(),
29
+ count: z.number(),
30
+ });
31
+ const PageContextSchema = z.object({
32
+ url: z.string(),
33
+ title: z.string(),
34
+ routeComponent: z.string().optional(),
35
+ });
36
+ const ChatRequestSchema = z.object({
37
+ prompt: z.string().min(1),
38
+ model: z.string().optional(),
39
+ consoleEntries: z.array(ConsoleEntrySchema).optional(),
40
+ images: z.array(z.string()).optional(),
41
+ pageContext: PageContextSchema.optional(),
42
+ });
43
+ /**
44
+ * Formats console entries into a context block for the LLM prompt.
45
+ */
46
+ function formatConsoleContext(entries) {
47
+ if (entries.length === 0)
48
+ return null;
49
+ const parts = entries.map(entry => {
50
+ const lines = [`[${entry.level}] ${entry.message}`];
51
+ if (entry.sourceTrace && entry.sourceTrace.length > 0) {
52
+ lines.push('Trace:');
53
+ for (const f of entry.sourceTrace) {
54
+ lines.push(` ${f.source}${f.line ? `:${f.line}` : ''}`);
55
+ }
56
+ }
57
+ else if (entry.source) {
58
+ let loc = entry.source;
59
+ if (entry.line)
60
+ loc += `:${entry.line}`;
61
+ if (entry.column)
62
+ loc += `:${entry.column}`;
63
+ lines.push(`Source: ${loc}`);
64
+ }
65
+ if (entry.stack) {
66
+ lines.push(`Stack: ${entry.stack}`);
67
+ }
68
+ if (entry.count > 1) {
69
+ lines.push(`Occurred ${entry.count} times`);
70
+ }
71
+ return lines.join('\n');
72
+ });
73
+ return '[Browser Console Errors]\n\n' + parts.join('\n\n') + '\n\n';
74
+ }
75
+ /**
76
+ * Formats page context into a context block for the LLM prompt.
77
+ */
78
+ function formatPageContext(ctx) {
79
+ const lines = ['[Page Context]'];
80
+ lines.push(`URL: ${ctx.url}`);
81
+ if (ctx.title)
82
+ lines.push(`Title: ${ctx.title}`);
83
+ if (ctx.routeComponent)
84
+ lines.push(`Route component: ${ctx.routeComponent}`);
85
+ return lines.join('\n') + '\n\n';
86
+ }
87
+ /**
88
+ * Sets standard SSE headers on the response
89
+ */
90
+ function setSSEHeaders(c) {
91
+ c.header('Content-Type', 'text/event-stream');
92
+ c.header('Cache-Control', 'no-cache');
93
+ c.header('Connection', 'keep-alive');
94
+ }
95
+ /**
96
+ * Creates the agent API routes with SSE streaming.
97
+ * @param projectCwd - The user's project directory (where they ran `awel dev`)
98
+ */
99
+ export function createAgentRoute(projectCwd, targetPort) {
100
+ const agent = new Hono();
101
+ // ─── Model Catalog ───────────────────────────────────────
102
+ agent.get('/api/models', (c) => {
103
+ return c.json({ models: getModelCatalogWithAvailability() });
104
+ });
105
+ // ─── Chat (trigger LLM) ─────────────────────────────────
106
+ agent.post('/api/chat', async (c) => {
107
+ let body;
108
+ try {
109
+ body = await c.req.json();
110
+ }
111
+ catch {
112
+ return c.json({ success: false, error: 'Invalid request body' }, 400);
113
+ }
114
+ const parsed = ChatRequestSchema.safeParse(body);
115
+ if (!parsed.success) {
116
+ const message = parsed.error.issues.map(i => `${i.path.join('.')}: ${i.message}`).join('; ');
117
+ return c.json({ success: false, error: message }, 400);
118
+ }
119
+ const { prompt, model, consoleEntries, images, pageContext } = parsed.data;
120
+ const modelId = model ?? DEFAULT_MODEL;
121
+ // Prepend context blocks to the prompt
122
+ let augmentedPrompt = prompt;
123
+ if (pageContext) {
124
+ augmentedPrompt = formatPageContext(pageContext) + augmentedPrompt;
125
+ }
126
+ if (consoleEntries && consoleEntries.length > 0) {
127
+ const context = formatConsoleContext(consoleEntries);
128
+ if (context) {
129
+ augmentedPrompt = context + augmentedPrompt;
130
+ }
131
+ }
132
+ // Build user content — multipart if images are present
133
+ const hasImages = images && images.length > 0;
134
+ const userContent = hasImages
135
+ ? [
136
+ { type: 'text', text: augmentedPrompt },
137
+ ...images.map(dataUrl => ({ type: 'image', image: dataUrl })),
138
+ ]
139
+ : augmentedPrompt;
140
+ // Cancel any in-flight stream before starting a new one
141
+ activeStreamAbort?.abort();
142
+ const abortController = new AbortController();
143
+ activeStreamAbort = abortController;
144
+ const { signal } = abortController;
145
+ // Adapter stream that emits events through the bus
146
+ const adapter = {
147
+ writeSSE: async (msg) => {
148
+ if (!signal.aborted) {
149
+ streamBus.emit('sse', { event: msg.event || 'message', data: msg.data });
150
+ }
151
+ },
152
+ };
153
+ try {
154
+ const { provider } = getOrCreateSession(modelId);
155
+ const messages = getSessionMessages(userContent);
156
+ // Fire and forget — events flow through the bus to connected SSE clients.
157
+ // NOTE: appendUserMessage is deferred until we have response messages.
158
+ // Appending eagerly would leave orphan user messages in the session when
159
+ // the stream is aborted or paused for user input, causing consecutive
160
+ // user messages that trigger API 400 errors (especially with Anthropic).
161
+ provider.streamResponse(adapter, messages, { projectCwd, targetPort, signal })
162
+ .then((responseMessages) => {
163
+ if (responseMessages.length > 0) {
164
+ appendUserMessage(userContent);
165
+ appendResponseMessages(responseMessages);
166
+ }
167
+ })
168
+ .finally(() => {
169
+ if (!signal.aborted) {
170
+ streamBus.emit('end');
171
+ }
172
+ });
173
+ }
174
+ catch (error) {
175
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
176
+ return c.json({ success: false, error: errorMessage }, 500);
177
+ }
178
+ return c.json({ success: true });
179
+ });
180
+ // ─── Abort Stream ────────────────────────────────────────
181
+ agent.post('/api/stream/abort', (c) => {
182
+ activeStreamAbort?.abort();
183
+ activeStreamAbort = null;
184
+ return c.json({ ok: true });
185
+ });
186
+ // ─── SSE Stream (listener only) ──────────────────────────
187
+ agent.get('/api/stream', async (c) => {
188
+ setSSEHeaders(c);
189
+ return streamSSE(c, async (stream) => {
190
+ await new Promise((resolve) => {
191
+ const onSSE = async (entry) => {
192
+ try {
193
+ await stream.writeSSE(entry);
194
+ }
195
+ catch {
196
+ cleanup();
197
+ }
198
+ };
199
+ const onEnd = () => cleanup();
200
+ const cleanup = () => {
201
+ streamBus.off('sse', onSSE);
202
+ streamBus.off('end', onEnd);
203
+ resolve();
204
+ };
205
+ stream.onAbort(() => cleanup());
206
+ streamBus.on('sse', onSSE);
207
+ streamBus.once('end', onEnd);
208
+ });
209
+ });
210
+ });
211
+ // ─── Chat History API ────────────────────────────────────
212
+ // Get chat history
213
+ agent.get('/api/chat/history', (c) => {
214
+ return c.json({ history: getHistory() });
215
+ });
216
+ // Add a user message to history (called when user sends a prompt)
217
+ agent.post('/api/chat/history', async (c) => {
218
+ try {
219
+ const body = await c.req.json();
220
+ if (body.eventType && body.data) {
221
+ addToHistory(body.eventType, body.data);
222
+ return c.json({ success: true });
223
+ }
224
+ return c.json({ success: false, error: 'Missing eventType or data' }, 400);
225
+ }
226
+ catch {
227
+ return c.json({ success: false, error: 'Invalid JSON' }, 400);
228
+ }
229
+ });
230
+ // Clear chat history
231
+ agent.delete('/api/chat/history', (c) => {
232
+ clearHistory();
233
+ resetSession();
234
+ return c.json({ success: true });
235
+ });
236
+ // ─── Plan API ────────────────────────────────────────────
237
+ agent.get('/api/plan/active', (c) => {
238
+ const plan = getActivePlan();
239
+ return c.json({ plan });
240
+ });
241
+ agent.post('/api/plan/approve', (c) => {
242
+ const success = approvePlan();
243
+ return c.json({ success });
244
+ });
245
+ agent.post('/api/plan/comment', async (c) => {
246
+ try {
247
+ const body = await c.req.json();
248
+ if (!body.comment || typeof body.comment !== 'string') {
249
+ return c.json({ success: false, error: 'Missing comment' }, 400);
250
+ }
251
+ return c.json({ success: true });
252
+ }
253
+ catch {
254
+ return c.json({ success: false, error: 'Invalid JSON' }, 400);
255
+ }
256
+ });
257
+ // ─── Dev Server Management ──────────────────────────────
258
+ agent.post('/api/dev-server/restart', async (c) => {
259
+ const result = await restartDevServer();
260
+ return c.json(result);
261
+ });
262
+ agent.get('/api/dev-server/status', (c) => {
263
+ return c.json(getDevServerStatus());
264
+ });
265
+ return agent;
266
+ }
@@ -0,0 +1 @@
1
+ export declare function ensureBabelPlugin(projectCwd: string): Promise<void>;