@mrpatronz/nexusflow 0.2.13 → 0.2.17

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 (186) hide show
  1. package/.github/dependabot.yml +52 -52
  2. package/.github/workflows/dependabot-merge.yml +53 -0
  3. package/.github/workflows/release.yml +112 -100
  4. package/.vscode/launch.json +17 -17
  5. package/.vscode/tasks.json +17 -17
  6. package/GETTING_STARTED.md +114 -109
  7. package/README.md +336 -311
  8. package/desktop/build-installer.js +228 -0
  9. package/desktop/build.js +118 -0
  10. package/desktop/installer/nexusflow.iss +35 -0
  11. package/desktop/neutralino.config.json +39 -0
  12. package/desktop/package-lock.json +1060 -0
  13. package/desktop/package.json +14 -0
  14. package/dist/commands/desktop.d.ts +12 -0
  15. package/dist/commands/desktop.d.ts.map +1 -0
  16. package/dist/commands/desktop.js +119 -0
  17. package/dist/commands/desktop.js.map +1 -0
  18. package/dist/commands/sync.d.ts.map +1 -1
  19. package/dist/commands/sync.js +1 -3
  20. package/dist/commands/sync.js.map +1 -1
  21. package/dist/commands/tui.d.ts +8 -0
  22. package/dist/commands/tui.d.ts.map +1 -0
  23. package/dist/commands/tui.js +386 -0
  24. package/dist/commands/tui.js.map +1 -0
  25. package/dist/commands/ui.d.ts +3 -1
  26. package/dist/commands/ui.d.ts.map +1 -1
  27. package/dist/commands/ui.js +76 -19
  28. package/dist/commands/ui.js.map +1 -1
  29. package/dist/generators/base.d.ts.map +1 -1
  30. package/dist/generators/base.js +78 -66
  31. package/dist/generators/base.js.map +1 -1
  32. package/dist/generators/codex.js +11 -11
  33. package/dist/generators/copilot.js +17 -17
  34. package/dist/generators/cursor.js +5 -5
  35. package/dist/generators/index.js +50 -50
  36. package/dist/generators/map-generator.js +14 -14
  37. package/dist/generators/skills-generator.js +28 -28
  38. package/dist/gui/app_logo.png +0 -0
  39. package/dist/gui/assets/index-Ct3qq-X4.js +25 -0
  40. package/dist/gui/assets/index-P_ZrgHXg.css +1 -0
  41. package/dist/gui/icons.svg +24 -24
  42. package/dist/gui/index.html +18 -18
  43. package/dist/index.js +43 -0
  44. package/dist/index.js.map +1 -1
  45. package/dist/server.d.ts.map +1 -1
  46. package/dist/server.js +182 -1
  47. package/dist/server.js.map +1 -1
  48. package/dist/server.test.js +78 -0
  49. package/dist/server.test.js.map +1 -1
  50. package/dist/types.d.ts +4 -0
  51. package/dist/types.d.ts.map +1 -1
  52. package/dist/utils/git.d.ts +16 -0
  53. package/dist/utils/git.d.ts.map +1 -1
  54. package/dist/utils/git.js +52 -0
  55. package/dist/utils/git.js.map +1 -1
  56. package/dist/utils/multi-git.d.ts +2 -0
  57. package/dist/utils/multi-git.d.ts.map +1 -1
  58. package/dist/utils/multi-git.js +5 -2
  59. package/dist/utils/multi-git.js.map +1 -1
  60. package/dist/utils/update-check.d.ts +3 -1
  61. package/dist/utils/update-check.d.ts.map +1 -1
  62. package/dist/utils/update-check.js +23 -6
  63. package/dist/utils/update-check.js.map +1 -1
  64. package/dist/utils/workflows.d.ts +11 -0
  65. package/dist/utils/workflows.d.ts.map +1 -0
  66. package/dist/utils/workflows.js +156 -0
  67. package/dist/utils/workflows.js.map +1 -0
  68. package/dist/utils/workflows.test.d.ts +2 -0
  69. package/dist/utils/workflows.test.d.ts.map +1 -0
  70. package/dist/utils/workflows.test.js +86 -0
  71. package/dist/utils/workflows.test.js.map +1 -0
  72. package/extension/media/icon.svg +1 -0
  73. package/extension/package-lock.json +2673 -2811
  74. package/extension/package.json +108 -70
  75. package/extension/src/extension.ts +631 -204
  76. package/extension/tsconfig.json +21 -19
  77. package/gui/README.md +73 -73
  78. package/gui/e2e/wizard.spec.ts +346 -327
  79. package/gui/eslint.config.js +26 -26
  80. package/gui/index.html +17 -17
  81. package/gui/package-lock.json +3079 -3118
  82. package/gui/package.json +36 -36
  83. package/gui/playwright.config.ts +41 -41
  84. package/gui/public/app_logo.png +0 -0
  85. package/gui/public/icons.svg +24 -24
  86. package/gui/src/App.css +1 -1
  87. package/gui/src/App.tsx +3407 -2722
  88. package/gui/src/assets/vite.svg +1 -1
  89. package/gui/src/features/changes/ChangesViewer.tsx +388 -388
  90. package/gui/src/features/knowledge/KnowledgeBase.tsx +84 -84
  91. package/gui/src/features/onboarding/OnboardingWizard.tsx +230 -230
  92. package/gui/src/features/plan/ImplementationPlan.tsx +32 -32
  93. package/gui/src/features/services/ServiceConsole.tsx +250 -250
  94. package/gui/src/features/sessions/SessionHistory.tsx +195 -195
  95. package/gui/src/features/workspace/WorkspaceList.tsx +666 -666
  96. package/gui/src/index.css +152 -110
  97. package/gui/src/main.tsx +94 -10
  98. package/gui/src/types.ts +62 -62
  99. package/gui/tsconfig.app.json +25 -25
  100. package/gui/tsconfig.json +7 -7
  101. package/gui/tsconfig.node.json +24 -24
  102. package/gui/vite.config.ts +12 -12
  103. package/package.json +56 -56
  104. package/resources/workflows/plan-implement-review.md +8 -0
  105. package/resources/workflows/research-verify.md +6 -0
  106. package/resources/workflows/solo-developer.md +3 -0
  107. package/scripts/simulate-workspaces.ts +55 -55
  108. package/src/analyzers/detect-apis.ts +290 -290
  109. package/src/analyzers/detect-deps.ts +315 -315
  110. package/src/analyzers/detect-existing.ts +74 -74
  111. package/src/analyzers/detect-ports.ts +110 -110
  112. package/src/analyzers/index.ts +97 -97
  113. package/src/analyzers/messaging-analyzer.ts +254 -254
  114. package/src/analyzers/readme-summarizer.ts +102 -102
  115. package/src/analyzers/run-analyzer.ts +269 -269
  116. package/src/analyzers/tech-stack.ts +283 -283
  117. package/src/commands/add-repo.ts +157 -157
  118. package/src/commands/commands.test.ts +155 -155
  119. package/src/commands/commit.ts +131 -131
  120. package/src/commands/create.ts +207 -207
  121. package/src/commands/desktop.ts +128 -0
  122. package/src/commands/diff.ts +125 -125
  123. package/src/commands/doctor.ts +357 -357
  124. package/src/commands/handoff.ts +266 -266
  125. package/src/commands/init.ts +134 -134
  126. package/src/commands/list.ts +46 -46
  127. package/src/commands/logs.ts +63 -63
  128. package/src/commands/mcp.ts +92 -92
  129. package/src/commands/open.ts +129 -129
  130. package/src/commands/pack.ts +73 -73
  131. package/src/commands/refresh.ts +147 -147
  132. package/src/commands/remove.ts +98 -98
  133. package/src/commands/start.ts +117 -117
  134. package/src/commands/status.ts +54 -54
  135. package/src/commands/stop.ts +55 -55
  136. package/src/commands/sync.ts +151 -153
  137. package/src/commands/tui.ts +424 -0
  138. package/src/commands/ui.ts +111 -47
  139. package/src/core/config.test.ts +96 -96
  140. package/src/core/config.ts +115 -115
  141. package/src/core/graph.ts +344 -344
  142. package/src/core/packer.test.ts +99 -99
  143. package/src/core/packer.ts +107 -107
  144. package/src/core/scanner.test.ts +61 -61
  145. package/src/core/scanner.ts +91 -91
  146. package/src/core/workspace.ts +380 -380
  147. package/src/core/worktree.ts +120 -120
  148. package/src/generators/antigravity.ts +32 -32
  149. package/src/generators/base.ts +240 -227
  150. package/src/generators/claude.ts +34 -34
  151. package/src/generators/codex.ts +48 -48
  152. package/src/generators/copilot.ts +56 -56
  153. package/src/generators/cursor.ts +44 -44
  154. package/src/generators/index.ts +250 -250
  155. package/src/generators/map-generator.test.ts +159 -159
  156. package/src/generators/map-generator.ts +542 -542
  157. package/src/generators/plan-generator.ts +481 -481
  158. package/src/generators/skills-generator.ts +259 -259
  159. package/src/index.ts +426 -382
  160. package/src/mcp/server.ts +294 -294
  161. package/src/orchestration/detect.ts +313 -313
  162. package/src/orchestration/index.ts +7 -7
  163. package/src/orchestration/runner.ts +283 -283
  164. package/src/server.test.ts +555 -464
  165. package/src/server.ts +1308 -1104
  166. package/src/types.ts +408 -403
  167. package/src/utils/detect-ai.test.ts +44 -44
  168. package/src/utils/detect-ai.ts +84 -84
  169. package/src/utils/detect-editors.test.ts +48 -48
  170. package/src/utils/detect-editors.ts +57 -57
  171. package/src/utils/git.test.ts +74 -74
  172. package/src/utils/git.ts +117 -61
  173. package/src/utils/local-ai.test.ts +130 -130
  174. package/src/utils/local-ai.ts +111 -111
  175. package/src/utils/multi-git.ts +313 -306
  176. package/src/utils/prompts.ts +209 -209
  177. package/src/utils/session-finder.ts +483 -483
  178. package/src/utils/system-scanner.test.ts +89 -89
  179. package/src/utils/system-scanner.ts +96 -96
  180. package/src/utils/update-check.ts +309 -275
  181. package/src/utils/workflows.test.ts +114 -0
  182. package/src/utils/workflows.ts +178 -0
  183. package/tsconfig.json +19 -19
  184. package/vitest.config.ts +14 -14
  185. package/dist/gui/assets/index-CFWwqFux.js +0 -23
  186. package/dist/gui/assets/index-Dvc9QMvl.css +0 -2
package/src/server.ts CHANGED
@@ -1,1104 +1,1308 @@
1
- /**
2
- * @module server
3
- * Hono local web server for the NexusFlow GUI.
4
- */
5
-
6
- import { Hono } from 'hono';
7
- import { serve } from '@hono/node-server';
8
- import { serveStatic } from '@hono/node-server/serve-static';
9
- import { cors } from 'hono/cors';
10
- import { streamSSE } from 'hono/streaming';
11
- import * as fs from 'node:fs/promises';
12
- import * as path from 'node:path';
13
- import { fileURLToPath } from 'node:url';
14
- import { execa } from 'execa';
15
-
16
- import { loadConfig, saveConfig, getConfigDir } from './core/config.js';
17
- import { scanForRepos } from './core/scanner.js';
18
- import { createWorkspace, listWorkspaces, loadFeatureConfig, deleteWorkspace, addRepoToWorkspace } from './core/workspace.js';
19
- import { analyzeAllRepos } from './analyzers/index.js';
20
- import { generateContextFiles } from './generators/index.js';
21
- import { packWorkspace } from './core/packer.js';
22
- import { isOllamaModelAvailable, getOpenAiCompatibleUrl, callLocalLlm } from './utils/local-ai.js';
23
- import { detectAIAssistants } from './utils/detect-ai.js';
24
- import { detectEditors } from './utils/detect-editors.js';
25
- import { findSessions, getSessionTranscript } from './utils/session-finder.js';
26
- import { scanSystemSpecs } from './utils/system-scanner.js';
27
- import { getWorkspaceRepos, rebaseRepo, commitAndPush, getRepoStatus } from './utils/multi-git.js';
28
- import {
29
- detectAllServices,
30
- detectOrchestrationTools,
31
- startServices,
32
- stopServices,
33
- loadRunningState,
34
- } from './orchestration/index.js';
35
- import { checkForUpdates, getCurrentVersion, getToolsStatus } from './utils/update-check.js';
36
- import type { Feature, RepoInfo, WorkspaceContext } from './types.js';
37
-
38
- // Resolve static files directory
39
- const __filename = fileURLToPath(import.meta.url);
40
- const __dirname = path.dirname(__filename);
41
-
42
- // In development, the static GUI is built to dist/gui
43
- // In production, it will be served from dist/gui as well
44
- const guiPath = path.join(__dirname, 'gui');
45
-
46
- export const app = new Hono();
47
-
48
- // Allowed editor binaries/scripts to prevent command injection
49
- const ALLOWED_EDITORS = new Set(['code', 'code-insiders', 'cursor', 'antigravity', 'agy', 'idea', 'charm', 'webstorm', 'subl', 'nano', 'vim', 'nvim', 'emacs']);
50
-
51
- // Enable CORS for frontend dev server
52
- app.use('/api/*', cors());
53
-
54
- // ─── API Endpoints ────────────────────────────────────────────────────────
55
-
56
- // 1. Get current configuration
57
- app.get('/api/config', async (c) => {
58
- try {
59
- const configPath = path.join(getConfigDir(), 'config.json');
60
- let exists = false;
61
- try {
62
- await fs.access(configPath);
63
- exists = true;
64
- } catch {}
65
-
66
- const config = await loadConfig();
67
- return c.json({ config, exists });
68
- } catch (error) {
69
- const msg = error instanceof Error ? error.message : String(error);
70
- return c.json({ error: msg }, 500);
71
- }
72
- });
73
-
74
- function isSafeLocalEndpoint(urlStr: string): boolean {
75
- try {
76
- const url = new URL(urlStr);
77
- const hostname = url.hostname.toLowerCase();
78
- if (hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]') {
79
- return true;
80
- }
81
- const ipv4Pattern = /^(?:10|127|192\.168|172\.(?:1[6-9]|2[0-9]|3[01]))\.\d+\.\d+\.\d+$/;
82
- if (ipv4Pattern.test(hostname)) {
83
- return true;
84
- }
85
- return false;
86
- } catch {
87
- return false;
88
- }
89
- }
90
-
91
- // 2. Save configuration
92
- app.post('/api/config', async (c) => {
93
- try {
94
- const newConfig = await c.req.json();
95
- if (newConfig?.localLlm?.enabled && newConfig.localLlm.endpoint) {
96
- if (!isSafeLocalEndpoint(newConfig.localLlm.endpoint)) {
97
- return c.json({ error: 'Local AI endpoint must be localhost, 127.0.0.1, or a private LAN IP.' }, 400);
98
- }
99
- }
100
- await saveConfig(newConfig);
101
- return c.json({ success: true, config: newConfig });
102
- } catch (error) {
103
- const msg = error instanceof Error ? error.message : String(error);
104
- return c.json({ error: msg }, 500);
105
- }
106
- });
107
-
108
- // 3. Scan development directory for repositories
109
- app.get('/api/repos', async (c) => {
110
- try {
111
- const config = await loadConfig();
112
- const repos = await scanForRepos(config.devDir, config.scanDepth);
113
- return c.json(repos);
114
- } catch (error) {
115
- const msg = error instanceof Error ? error.message : String(error);
116
- return c.json({ error: msg }, 500);
117
- }
118
- });
119
-
120
- // 4. List existing workspaces
121
- app.get('/api/workspaces', async (c) => {
122
- try {
123
- const config = await loadConfig();
124
- const workspaces = await listWorkspaces(config.workspacesDir);
125
- return c.json(workspaces);
126
- } catch (error) {
127
- const msg = error instanceof Error ? error.message : String(error);
128
- return c.json({ error: msg }, 500);
129
- }
130
- });
131
-
132
- // 5. Detect available AI assistants
133
- app.get('/api/ai-detect', async (c) => {
134
- try {
135
- const assistants = await detectAIAssistants();
136
- return c.json(assistants);
137
- } catch (error) {
138
- const msg = error instanceof Error ? error.message : String(error);
139
- return c.json({ error: msg }, 500);
140
- }
141
- });
142
-
143
- // 6. Detect available editors
144
- app.get('/api/editor-detect', async (c) => {
145
- try {
146
- const editors = await detectEditors();
147
- return c.json(editors);
148
- } catch (error) {
149
- const msg = error instanceof Error ? error.message : String(error);
150
- return c.json({ error: msg }, 500);
151
- }
152
- });
153
-
154
- // 6.5. Local LLM test & recommendation
155
- app.post('/api/local-llm/test', async (c) => {
156
- try {
157
- const { provider, endpoint, model, shoot } = await c.req.json();
158
- if (!endpoint || !isSafeLocalEndpoint(endpoint)) {
159
- return c.json({ success: false, error: 'Local AI endpoint must be localhost, 127.0.0.1, or a private LAN IP.' }, 400);
160
- }
161
- const cleanEndpoint = endpoint.replace(/\/$/, '');
162
-
163
- if (shoot) {
164
- const responseText = await callLocalLlm(
165
- { enabled: true, provider, endpoint, model },
166
- [{ role: 'user', content: 'Respond with the exact word "OK" and nothing else.' }]
167
- );
168
- const cleanResponse = responseText.trim();
169
- return c.json({
170
- success: true,
171
- modelReady: true,
172
- message: `Inference test succeeded! Response from model: "${cleanResponse}"`
173
- });
174
- }
175
-
176
- if (provider === 'ollama') {
177
- const res = await fetch(`${cleanEndpoint}/api/tags`);
178
- if (!res.ok) throw new Error(`Ollama responded with status ${res.status}`);
179
- const data: any = await res.json();
180
- const models = data?.models || [];
181
- const isModelLoaded = isOllamaModelAvailable(models, model);
182
- return c.json({
183
- success: true,
184
- modelReady: isModelLoaded,
185
- message: isModelLoaded ? 'Connected successfully! Model is ready.' : `Connected successfully, but model "${model}" is not pulled. Run "ollama pull ${model}" to install it.`
186
- });
187
- } else {
188
- const testUrl = getOpenAiCompatibleUrl(cleanEndpoint, '/v1/models');
189
- const res = await fetch(testUrl);
190
- if (!res.ok) throw new Error(`OpenAI-compatible server responded with status ${res.status}`);
191
- return c.json({ success: true, modelReady: true, message: 'Connected successfully to OpenAI-compatible server!' });
192
- }
193
- } catch (error) {
194
- const msg = error instanceof Error ? error.message : String(error);
195
- return c.json({ success: false, error: msg }, 400);
196
- }
197
- });
198
-
199
- app.get('/api/local-llm/recommend', async (c) => {
200
- try {
201
- const specs = await scanSystemSpecs();
202
- return c.json(specs);
203
- } catch (error) {
204
- return c.json({
205
- totalRamGb: 8,
206
- gpuName: 'Unknown/Integrated',
207
- hasHardwareAcceleration: false,
208
- recommendedModel: 'qwen2.5-coder:1.5b',
209
- });
210
- }
211
- });
212
-
213
-
214
- interface JobStep {
215
- id: string;
216
- name: string;
217
- status: 'pending' | 'running' | 'completed' | 'failed';
218
- message: string;
219
- }
220
-
221
- interface CreationJob {
222
- id: string;
223
- status: 'running' | 'completed' | 'failed';
224
- progress: number;
225
- error?: string;
226
- steps: JobStep[];
227
- workspacePath?: string;
228
- feature?: Feature;
229
- listeners: Set<(event: { type: string; data: any }) => void>;
230
- }
231
-
232
- const creationJobs = new Map<string, CreationJob>();
233
-
234
- function updateJobStep(
235
- jobId: string,
236
- stepId: string,
237
- status: 'running' | 'completed' | 'failed',
238
- message: string,
239
- extraData?: any
240
- ) {
241
- const job = creationJobs.get(jobId);
242
- if (!job) return;
243
-
244
- const step = job.steps.find((s) => s.id === stepId);
245
- if (step) {
246
- step.status = status;
247
- step.message = message;
248
- }
249
-
250
- const isLastStep = job.steps[job.steps.length - 1]?.id === stepId;
251
- if (isLastStep && status === 'completed') {
252
- job.status = 'completed';
253
- job.progress = 100;
254
- } else if (status === 'failed') {
255
- job.status = 'failed';
256
- job.error = message;
257
- } else {
258
- const completedCount = job.steps.filter((s) => s.status === 'completed').length;
259
- const runningCount = job.steps.filter((s) => s.status === 'running').length;
260
- job.progress = Math.round(((completedCount + runningCount * 0.5) / job.steps.length) * 100);
261
- }
262
-
263
- const eventPayload = {
264
- type: 'progress',
265
- data: {
266
- id: job.id,
267
- status: job.status,
268
- progress: job.progress,
269
- error: job.error,
270
- steps: job.steps,
271
- workspacePath: job.workspacePath,
272
- feature: job.feature,
273
- ...extraData,
274
- },
275
- };
276
-
277
- for (const listener of job.listeners) {
278
- listener(eventPayload);
279
- }
280
- }
281
-
282
- async function runCreationJob(jobId: string, body: any, config: any) {
283
- try {
284
- const workspacePath = path.join(config.workspacesDir, body.branchName);
285
- const job = creationJobs.get(jobId);
286
- if (job) {
287
- job.workspacePath = workspacePath;
288
- }
289
-
290
- const feature: Feature = {
291
- id: body.branchName,
292
- branchName: body.branchName,
293
- description: body.description,
294
- repos: body.repos.map((r: any) => path.join(workspacePath, r.name)),
295
- originalRepos: body.repos.map((r: any) => r.path),
296
- assistants: body.assistants,
297
- workspacePath,
298
- createdAt: new Date().toISOString(),
299
- resumption: body.resumption,
300
- localLlmEnabled: body.localLlmEnabled,
301
- };
302
- if (job) {
303
- job.feature = feature;
304
- }
305
-
306
- // Step 1: Create worktrees
307
- updateJobStep(jobId, 'worktrees', 'running', 'Creating git worktrees...');
308
- await createWorkspace(feature, body.repos);
309
- updateJobStep(jobId, 'worktrees', 'completed', 'Git worktrees created successfully.');
310
-
311
- // Step 2: Analyze repos
312
- updateJobStep(jobId, 'analysis', 'running', 'Analyzing projects and dependencies...');
313
- const workspaceRepos = body.repos.map((repo: any) => ({
314
- ...repo,
315
- path: path.join(workspacePath, repo.name),
316
- }));
317
- const analysis = await analyzeAllRepos(workspaceRepos);
318
- updateJobStep(jobId, 'analysis', 'completed', 'Project analysis complete.');
319
-
320
- // Step 3: Generate AI context files
321
- updateJobStep(jobId, 'context', 'running', 'Generating AI context files...');
322
- const ctx: WorkspaceContext = {
323
- feature,
324
- repos: workspaceRepos,
325
- analysis,
326
- localLlm: config.localLlm,
327
- };
328
- await generateContextFiles(ctx, body.assistants, workspacePath);
329
- updateJobStep(jobId, 'context', 'completed', 'AI context files generated.');
330
-
331
- // Step 4: Pack codebase context
332
- if (config.packContextXml) {
333
- updateJobStep(jobId, 'pack', 'running', 'Packing codebase context with Repomix...');
334
- const packResult = await packWorkspace(workspacePath);
335
- updateJobStep(jobId, 'pack', 'completed', `Packed codebase context (${packResult.totalFiles} files, ${(packResult.fileSize / 1024).toFixed(2)} KB).`);
336
- }
337
-
338
- } catch (error) {
339
- const msg = error instanceof Error ? error.message : String(error);
340
- const job = creationJobs.get(jobId);
341
- if (job) {
342
- const runningStep = job.steps.find((s) => s.status === 'running');
343
- const failedStepId = runningStep ? runningStep.id : 'worktrees';
344
- updateJobStep(jobId, failedStepId, 'failed', msg);
345
- }
346
- }
347
- }
348
-
349
- // 7. Create workspace
350
- app.post('/api/workspace', async (c) => {
351
- try {
352
- const body = await c.req.json() as {
353
- branchName: string;
354
- description: string;
355
- repos: RepoInfo[];
356
- assistants: any[];
357
- localLlmEnabled?: boolean;
358
- resumption?: {
359
- testCommand?: string;
360
- mockCommand?: string;
361
- startCommand?: string;
362
- };
363
- };
364
-
365
- const config = await loadConfig();
366
- const jobId = body.branchName;
367
-
368
- if (creationJobs.has(jobId)) {
369
- const existing = creationJobs.get(jobId)!;
370
- if (existing.status === 'running') {
371
- return c.json({ success: true, jobId, message: 'Job already running' });
372
- }
373
- }
374
-
375
- const steps: JobStep[] = [
376
- { id: 'worktrees', name: 'Create Git Worktrees', status: 'pending', message: 'Waiting...' },
377
- { id: 'analysis', name: 'Analyze Repositories', status: 'pending', message: 'Waiting...' },
378
- { id: 'context', name: 'Generate AI Context Files', status: 'pending', message: 'Waiting...' },
379
- ];
380
- if (config.packContextXml) {
381
- steps.push({ id: 'pack', name: 'Pack Codebase Context', status: 'pending', message: 'Waiting...' });
382
- }
383
-
384
- const job: CreationJob = {
385
- id: jobId,
386
- status: 'running',
387
- progress: 0,
388
- steps,
389
- listeners: new Set(),
390
- };
391
- creationJobs.set(jobId, job);
392
-
393
- // Run the job in background
394
- runCreationJob(jobId, body, config);
395
-
396
- return c.json({ success: true, jobId });
397
- } catch (error) {
398
- const msg = error instanceof Error ? error.message : String(error);
399
- return c.json({ error: msg }, 500);
400
- }
401
- });
402
-
403
- // 7.5. Create workspace SSE stream
404
- app.get('/api/workspace/create-stream/:jobId', async (c) => {
405
- const jobId = decodeURIComponent(c.req.param('jobId'));
406
- const job = creationJobs.get(jobId);
407
- if (!job) {
408
- return c.json({ error: 'Job not found' }, 404);
409
- }
410
-
411
- c.header('Content-Type', 'text/event-stream');
412
- c.header('Cache-Control', 'no-cache');
413
- c.header('Connection', 'keep-alive');
414
-
415
- return streamSSE(c, async (stream) => {
416
- // Send initial state
417
- await stream.writeSSE({
418
- event: 'progress',
419
- data: JSON.stringify({
420
- id: job.id,
421
- status: job.status,
422
- progress: job.progress,
423
- error: job.error,
424
- steps: job.steps,
425
- workspacePath: job.workspacePath,
426
- feature: job.feature,
427
- }),
428
- });
429
-
430
- if (job.status === 'completed' || job.status === 'failed') {
431
- return;
432
- }
433
-
434
- const listener = async (event: { type: string; data: any }) => {
435
- try {
436
- await stream.writeSSE({
437
- event: event.type,
438
- data: JSON.stringify(event.data),
439
- });
440
- } catch (err) {
441
- job.listeners.delete(listener);
442
- }
443
- };
444
-
445
- job.listeners.add(listener);
446
-
447
- // Keep connection alive until job finishes
448
- while (job.status === 'running') {
449
- await new Promise((resolve) => setTimeout(resolve, 1000));
450
- }
451
-
452
- job.listeners.delete(listener);
453
- });
454
- });
455
-
456
- // 7.6. Delete workspace
457
- app.delete('/api/workspace/:id', async (c) => {
458
- try {
459
- const id = decodeURIComponent(c.req.param('id'));
460
- const config = await loadConfig();
461
- const workspacePath = path.join(config.workspacesDir, id);
462
-
463
- await deleteWorkspace(workspacePath);
464
- return c.json({ success: true });
465
- } catch (error) {
466
- const msg = error instanceof Error ? error.message : String(error);
467
- return c.json({ error: msg }, 500);
468
- }
469
- });
470
-
471
- // 7.7. Add repo to workspace
472
- app.post('/api/workspace/:id/repo', async (c) => {
473
- try {
474
- const id = decodeURIComponent(c.req.param('id'));
475
- const { repoPath } = await c.req.json() as { repoPath: string };
476
- const config = await loadConfig();
477
- const workspacePath = path.join(config.workspacesDir, id);
478
-
479
- await addRepoToWorkspace(workspacePath, repoPath);
480
- return c.json({ success: true });
481
- } catch (error) {
482
- const msg = error instanceof Error ? error.message : String(error);
483
- return c.json({ error: msg }, 500);
484
- }
485
- });
486
-
487
- // 8. Open workspace in editor
488
- app.post('/api/open-editor', async (c) => {
489
- try {
490
- const { workspacePath, command } = await c.req.json() as {
491
- workspacePath: string;
492
- command: string;
493
- };
494
-
495
- if (!ALLOWED_EDITORS.has(command)) {
496
- return c.json({ error: 'Forbidden editor command' }, 400);
497
- }
498
-
499
- // Validate path exists and is a directory
500
- try {
501
- const stats = await fs.stat(workspacePath);
502
- if (!stats.isDirectory()) {
503
- return c.json({ error: 'Workspace path is not a directory' }, 400);
504
- }
505
- } catch {
506
- return c.json({ error: 'Workspace path does not exist' }, 400);
507
- }
508
-
509
- // Spawn editor process
510
- const isWin = process.platform === 'win32';
511
- const child = execa(command, [workspacePath], {
512
- detached: true,
513
- stdio: 'ignore',
514
- shell: isWin,
515
- cleanup: false,
516
- });
517
- child.unref();
518
- child.catch((err) => {
519
- console.error(`Failed to launch editor ${command} for path ${workspacePath}:`, err);
520
- });
521
-
522
- return c.json({ success: true });
523
- } catch (error) {
524
- const msg = error instanceof Error ? error.message : String(error);
525
- return c.json({ error: msg }, 500);
526
- }
527
- });
528
-
529
- // 9. Get status of running services in all/specific workspace
530
- app.get('/api/workspace/:id/services', async (c) => {
531
- try {
532
- const id = c.req.param('id');
533
- const config = await loadConfig();
534
- const workspacePath = path.join(config.workspacesDir, id);
535
-
536
- // Detect all services
537
- const services = await detectAllServices(workspacePath);
538
- // Detect existing tools
539
- const tools = await detectOrchestrationTools(workspacePath);
540
- // Get currently running services from running state
541
- const runningState = await loadRunningState(workspacePath);
542
-
543
- return c.json({
544
- services,
545
- orchestrationTools: tools,
546
- runningState: runningState?.services || [],
547
- });
548
- } catch (error) {
549
- const msg = error instanceof Error ? error.message : String(error);
550
- return c.json({ error: msg }, 500);
551
- }
552
- });
553
-
554
- // 10. Start services in workspace
555
- app.post('/api/workspace/:id/services/start', async (c) => {
556
- try {
557
- const id = c.req.param('id');
558
- const { services } = await c.req.json() as { services: any[] };
559
- const config = await loadConfig();
560
- const workspacePath = path.join(config.workspacesDir, id);
561
- const logDir = path.join(workspacePath, '.nexusflow-logs');
562
-
563
- await startServices(services, workspacePath, logDir);
564
- return c.json({ success: true });
565
- } catch (error) {
566
- const msg = error instanceof Error ? error.message : String(error);
567
- return c.json({ error: msg }, 500);
568
- }
569
- });
570
-
571
- // 11. Stop services in workspace
572
- app.post('/api/workspace/:id/services/stop', async (c) => {
573
- try {
574
- const id = c.req.param('id');
575
- const config = await loadConfig();
576
- const workspacePath = path.join(config.workspacesDir, id);
577
-
578
- await stopServices(workspacePath);
579
- return c.json({ success: true });
580
- } catch (error) {
581
- const msg = error instanceof Error ? error.message : String(error);
582
- return c.json({ error: msg }, 500);
583
- }
584
- });
585
-
586
- // 12. Get service logs
587
- app.get('/api/workspace/:id/services/logs/:serviceName', async (c) => {
588
- try {
589
- const id = c.req.param('id');
590
- const serviceName = c.req.param('serviceName');
591
- const config = await loadConfig();
592
- const workspacePath = path.join(config.workspacesDir, id);
593
- const logFile = path.join(workspacePath, '.nexusflow-logs', `${serviceName}.log`);
594
-
595
- let content = '';
596
- try {
597
- // Read last 200 lines or 50KB
598
- const stats = await fs.stat(logFile);
599
- const size = stats.size;
600
- const start = Math.max(0, size - 50000);
601
- const fd = await fs.open(logFile, 'r');
602
- const buffer = Buffer.alloc(size - start);
603
- await fd.read(buffer, 0, buffer.length, start);
604
- await fd.close();
605
- content = buffer.toString('utf-8');
606
- } catch {
607
- content = 'No logs available yet.';
608
- }
609
-
610
- return c.json({ logs: content });
611
- } catch (error) {
612
- const msg = error instanceof Error ? error.message : String(error);
613
- return c.json({ error: msg }, 500);
614
- }
615
- });
616
-
617
- // 13. Get git changes in workspace sub-repositories
618
- app.get('/api/workspace/:id/changes', async (c) => {
619
- try {
620
- const id = c.req.param('id');
621
- const config = await loadConfig();
622
- const workspacePath = path.join(config.workspacesDir, id);
623
-
624
- // Load feature config to get repo paths
625
- const feature = await loadFeatureConfig(workspacePath);
626
- if (!feature) {
627
- return c.json({ error: 'Workspace configuration not found.' }, 404);
628
- }
629
-
630
- const results: any[] = [];
631
-
632
- // Check git status in each repo
633
- for (const repoPath of feature.repos) {
634
- const repoName = path.basename(repoPath);
635
- const worktreePath = path.join(workspacePath, repoName);
636
-
637
- try {
638
- const { stdout } = await execa('git', ['status', '--porcelain'], { cwd: worktreePath });
639
- const lines = stdout.split('\n').map((l) => l.trim()).filter(Boolean);
640
-
641
- // Get numstat to determine additions and deletions per file
642
- const numstatMap = new Map<string, { additions: number; deletions: number }>();
643
- try {
644
- const { stdout: numstatRaw } = await execa('git', ['diff', 'HEAD', '--numstat'], {
645
- cwd: worktreePath,
646
- });
647
- const numstatLines = numstatRaw.split('\n').filter(Boolean);
648
- for (const numLine of numstatLines) {
649
- const parts = numLine.trim().split(/\s+/);
650
- if (parts.length >= 3) {
651
- const [add, del, file] = parts;
652
- numstatMap.set(file, {
653
- additions: add === '-' ? 0 : parseInt(add, 10) || 0,
654
- deletions: del === '-' ? 0 : parseInt(del, 10) || 0,
655
- });
656
- }
657
- }
658
- } catch (e) {
659
- // Ignore diff errors
660
- }
661
-
662
- const files = lines.map((line) => {
663
- const status = line.slice(0, 2).trim();
664
- const file = line.slice(2).trim();
665
-
666
- let type = 'modified';
667
- if (status === 'A' || status === '??') type = 'added';
668
- else if (status === 'D') type = 'deleted';
669
-
670
- const stats = numstatMap.get(file) || { additions: 0, deletions: 0 };
671
-
672
- return {
673
- file,
674
- type,
675
- rawStatus: status,
676
- additions: stats.additions,
677
- deletions: stats.deletions,
678
- };
679
- });
680
-
681
- results.push({
682
- repoName,
683
- repoPath: worktreePath,
684
- files,
685
- });
686
- } catch (error) {
687
- results.push({
688
- repoName,
689
- repoPath: worktreePath,
690
- files: [],
691
- error: error instanceof Error ? error.message : String(error),
692
- });
693
- }
694
- }
695
-
696
- return c.json({ changes: results });
697
- } catch (error) {
698
- const msg = error instanceof Error ? error.message : String(error);
699
- return c.json({ error: msg }, 500);
700
- }
701
- });
702
-
703
- // 13_diff. Get git diff for a specific file in workspace sub-repositories
704
- app.get('/api/workspace/:id/changes/diff', async (c) => {
705
- try {
706
- const id = c.req.param('id');
707
- const repoName = c.req.query('repo');
708
- const filePath = c.req.query('file');
709
-
710
- if (!repoName || !filePath) {
711
- return c.json({ error: 'Missing repo or file query parameter.' }, 400);
712
- }
713
-
714
- const config = await loadConfig();
715
- const workspacePath = path.join(config.workspacesDir, id);
716
- const worktreePath = path.join(workspacePath, repoName);
717
-
718
- // Security check: ensure path is within workspace directory
719
- const resolvedPath = path.resolve(worktreePath);
720
- if (!resolvedPath.startsWith(path.resolve(workspacePath))) {
721
- return c.json({ error: 'Invalid repository path.' }, 400);
722
- }
723
-
724
- let diff = '';
725
-
726
- // Check git status for the file to know if it's untracked
727
- try {
728
- const { stdout: statusOut } = await execa('git', ['status', '--porcelain', '--', filePath], { cwd: worktreePath });
729
- const statusLine = statusOut.trim();
730
- const isUntracked = statusLine.startsWith('??');
731
-
732
- if (isUntracked) {
733
- const result = await execa('git', ['diff', '--no-index', '--', '/dev/null', filePath], {
734
- cwd: worktreePath,
735
- reject: false
736
- });
737
- diff = result.stdout || result.stderr || '';
738
- } else {
739
- const result = await execa('git', ['diff', 'HEAD', '--', filePath], {
740
- cwd: worktreePath,
741
- reject: false
742
- });
743
- diff = result.stdout || result.stderr || '';
744
- }
745
- } catch (e) {
746
- const result = await execa('git', ['diff', 'HEAD', '--', filePath], {
747
- cwd: worktreePath,
748
- reject: false
749
- });
750
- diff = result.stdout || result.stderr || '';
751
- }
752
-
753
- return c.json({ diff });
754
- } catch (error) {
755
- const msg = error instanceof Error ? error.message : String(error);
756
- return c.json({ error: msg }, 500);
757
- }
758
- });
759
-
760
- // 13a. Get workspace knowledge (nexusflow-knowledge.md)
761
- app.get('/api/workspace/:id/knowledge', async (c) => {
762
- try {
763
- const id = c.req.param('id');
764
- const config = await loadConfig();
765
- const workspacePath = path.join(config.workspacesDir, id);
766
- const knowledgeFile = path.join(workspacePath, 'nexusflow-knowledge.md');
767
-
768
- let content = '';
769
- try {
770
- content = await fs.readFile(knowledgeFile, 'utf-8');
771
- } catch {
772
- content = '# Workspace Knowledge\n\nNo knowledge file yet.';
773
- }
774
-
775
- return c.json({ content });
776
- } catch (error) {
777
- const msg = error instanceof Error ? error.message : String(error);
778
- return c.json({ error: msg }, 500);
779
- }
780
- });
781
-
782
- // 13b. Update workspace knowledge (nexusflow-knowledge.md)
783
- app.put('/api/workspace/:id/knowledge', async (c) => {
784
- try {
785
- const id = c.req.param('id');
786
- const { content } = await c.req.json() as { content: string };
787
- const config = await loadConfig();
788
- const workspacePath = path.join(config.workspacesDir, id);
789
- const knowledgeFile = path.join(workspacePath, 'nexusflow-knowledge.md');
790
-
791
- await fs.writeFile(knowledgeFile, content, 'utf-8');
792
- return c.json({ success: true });
793
- } catch (error) {
794
- const msg = error instanceof Error ? error.message : String(error);
795
- return c.json({ error: msg }, 500);
796
- }
797
- });
798
-
799
- // 13c. Get workspace plan (nexusflow-plan.md)
800
- app.get('/api/workspace/:id/plan', async (c) => {
801
- try {
802
- const id = c.req.param('id');
803
- const config = await loadConfig();
804
- const workspacePath = path.join(config.workspacesDir, id);
805
- const planFile = path.join(workspacePath, 'nexusflow-plan.md');
806
-
807
- let content = '';
808
- try {
809
- content = await fs.readFile(planFile, 'utf-8');
810
- } catch {
811
- content = '# Workspace Plan\n\nNo implementation plan file yet.';
812
- }
813
-
814
- return c.json({ content });
815
- } catch (error) {
816
- const msg = error instanceof Error ? error.message : String(error);
817
- return c.json({ error: msg }, 500);
818
- }
819
- });
820
-
821
- // 13d. Sync all repositories in workspace
822
- app.post('/api/workspace/:id/sync', async (c) => {
823
- try {
824
- const id = c.req.param('id');
825
- const config = await loadConfig();
826
- const workspacePath = path.join(config.workspacesDir, id);
827
-
828
- const repos = await getWorkspaceRepos(workspacePath);
829
- const results = [];
830
-
831
- for (const repo of repos) {
832
- const result = await rebaseRepo(repo.path, 'main');
833
- results.push({
834
- repoName: repo.name,
835
- success: result.success,
836
- message: result.message,
837
- conflict: result.conflict,
838
- });
839
- }
840
-
841
- return c.json({ results });
842
- } catch (error) {
843
- const msg = error instanceof Error ? error.message : String(error);
844
- return c.json({ error: msg }, 500);
845
- }
846
- });
847
-
848
- // 13e. Commit changes in all repositories in workspace
849
- app.post('/api/workspace/:id/commit', async (c) => {
850
- try {
851
- const id = c.req.param('id');
852
- const { message } = await c.req.json() as { message: string };
853
- const config = await loadConfig();
854
- const workspacePath = path.join(config.workspacesDir, id);
855
-
856
- const repos = await getWorkspaceRepos(workspacePath);
857
- const results = [];
858
-
859
- for (const repo of repos) {
860
- const status = await getRepoStatus(repo.path);
861
- if (status.hasChanges) {
862
- const result = await commitAndPush(repo.path, message, repo.branchName);
863
- results.push({
864
- repoName: repo.name,
865
- success: result.success,
866
- commitHash: result.commitHash,
867
- filesChanged: result.filesChanged,
868
- message: result.message,
869
- });
870
- }
871
- }
872
-
873
- return c.json({ results });
874
- } catch (error) {
875
- const msg = error instanceof Error ? error.message : String(error);
876
- return c.json({ error: msg }, 500);
877
- }
878
- });
879
-
880
-
881
- // 14. Resume session in workspace (copies CLI resume command and opens editor)
882
- app.post('/api/workspace/:id/resume', async (c) => {
883
- try {
884
- const id = decodeURIComponent(c.req.param('id'));
885
- const config = await loadConfig();
886
- const workspacePath = path.join(config.workspacesDir, id);
887
-
888
- // Load feature config to get repo paths
889
- const feature = await loadFeatureConfig(workspacePath);
890
- if (!feature) {
891
- return c.json({ error: 'Workspace configuration not found.' }, 404);
892
- }
893
-
894
- const body = await c.req.json().catch(() => ({}));
895
- const targetSessionId = body.sessionId;
896
- const targetAssistant = body.assistant;
897
-
898
- // Find the session to resume
899
- let resumeCommand = '';
900
- let selectedAssistant = targetAssistant || feature.assistants[0] || 'antigravity';
901
- let selectedSessionId = targetSessionId;
902
-
903
- if (!selectedSessionId) {
904
- // Find the most recent session matching this workspace
905
- const sessions = await findSessions(workspacePath, feature.repos);
906
- if (sessions.length > 0) {
907
- selectedSessionId = sessions[0].id;
908
- selectedAssistant = sessions[0].assistant;
909
- }
910
- }
911
-
912
- if (selectedSessionId) {
913
- if (selectedAssistant === 'antigravity') {
914
- resumeCommand = `agy --conversation ${selectedSessionId}`;
915
- } else if (selectedAssistant === 'claude') {
916
- resumeCommand = `claude --resume ${selectedSessionId}`;
917
- } else if (selectedAssistant === 'codex') {
918
- resumeCommand = `codex resume ${selectedSessionId}`;
919
- } else if (selectedAssistant === 'copilot') {
920
- resumeCommand = `copilot --resume ${selectedSessionId}`;
921
- }
922
- } else {
923
- // Fallback to start command (since there's no existing session for this workspace)
924
- if (selectedAssistant === 'antigravity') {
925
- resumeCommand = 'agy --continue';
926
- } else if (selectedAssistant === 'claude') {
927
- resumeCommand = 'claude --resume';
928
- } else if (selectedAssistant === 'codex') {
929
- resumeCommand = 'codex resume';
930
- } else if (selectedAssistant === 'copilot') {
931
- resumeCommand = 'copilot --resume';
932
- } else {
933
- resumeCommand = 'agy --continue';
934
- }
935
- }
936
-
937
- // Open in editor if command is provided
938
- if (body.command) {
939
- if (!ALLOWED_EDITORS.has(body.command)) {
940
- return c.json({ error: 'Forbidden editor command' }, 400);
941
- }
942
- const isWin = process.platform === 'win32';
943
- const child = execa(body.command, [workspacePath], {
944
- detached: true,
945
- stdio: 'ignore',
946
- shell: isWin,
947
- cleanup: false,
948
- });
949
- child.unref();
950
- child.catch((err) => {
951
- console.error(`Failed to launch editor ${body.command} for path ${workspacePath}:`, err);
952
- });
953
- }
954
-
955
- return c.json({ success: true, resumeCommand, workspacePath });
956
- } catch (error) {
957
- const msg = error instanceof Error ? error.message : String(error);
958
- return c.json({ error: msg }, 500);
959
- }
960
- });
961
-
962
- // 15. List past AI sessions for a workspace
963
- app.get('/api/workspace/:id/sessions', async (c) => {
964
- try {
965
- const id = decodeURIComponent(c.req.param('id'));
966
- const config = await loadConfig();
967
- const workspacePath = path.join(config.workspacesDir, id);
968
-
969
- const feature = await loadFeatureConfig(workspacePath);
970
- if (!feature) {
971
- return c.json({ error: 'Workspace configuration not found.' }, 404);
972
- }
973
-
974
- const sessions = await findSessions(workspacePath, feature.repos);
975
- return c.json({ sessions });
976
- } catch (error) {
977
- const msg = error instanceof Error ? error.message : String(error);
978
- return c.json({ error: msg }, 500);
979
- }
980
- });
981
-
982
- // 16. Fetch transcript for a specific AI session
983
- app.get('/api/session/:assistant/:sessionId/transcript', async (c) => {
984
- try {
985
- const assistant = c.req.param('assistant');
986
- const sessionId = c.req.param('sessionId');
987
- const messages = await getSessionTranscript(assistant, sessionId);
988
- return c.json({ messages });
989
- } catch (error) {
990
- const msg = error instanceof Error ? error.message : String(error);
991
- return c.json({ error: msg }, 500);
992
- }
993
- });
994
-
995
- // 17. Check for NexusFlow updates
996
- app.get('/api/update-status', async (c) => {
997
- try {
998
- const status = await checkForUpdates(false);
999
- if (!status) {
1000
- const currentVersion = getCurrentVersion();
1001
- return c.json({ currentVersion, latestVersion: currentVersion, updateAvailable: false });
1002
- }
1003
- return c.json(status);
1004
- } catch (error) {
1005
- const msg = error instanceof Error ? error.message : String(error);
1006
- return c.json({ error: msg }, 500);
1007
- }
1008
- });
1009
-
1010
- // 17.5. Check tools updates status
1011
- app.get('/api/updates/tools', async (c) => {
1012
- try {
1013
- const force = c.req.query('force') === 'true';
1014
- const status = await getToolsStatus(force);
1015
- return c.json(status);
1016
- } catch (error) {
1017
- const msg = error instanceof Error ? error.message : String(error);
1018
- return c.json({ error: msg }, 500);
1019
- }
1020
- });
1021
-
1022
- // 17.6. Install updates for a specific tool
1023
- app.post('/api/updates/install', async (c) => {
1024
- try {
1025
- const { toolId } = await c.req.json() as { toolId: string };
1026
- const tools = [
1027
- { id: 'nexusflow', cmd: 'npm', args: ['install', '-g', '@mrpatronz/nexusflow'] },
1028
- { id: 'repomix', cmd: 'npm', args: ['install', '-g', 'repomix'] },
1029
- { id: 'antigravity', cmd: 'agy', args: ['update'] },
1030
- { id: 'claude', cmd: 'npm', args: ['install', '-g', '@anthropic-ai/claude-code'] },
1031
- ];
1032
-
1033
- const target = tools.find(t => t.id === toolId);
1034
- if (!target) {
1035
- return c.json({ error: 'Tool not found' }, 404);
1036
- }
1037
-
1038
- const result = await execa(target.cmd, target.args, {
1039
- reject: false,
1040
- shell: process.platform === 'win32',
1041
- });
1042
- if (result.exitCode === 0) {
1043
- return c.json({ success: true, output: result.stdout });
1044
- } else {
1045
- return c.json({ error: `Update failed: ${result.stderr || result.stdout}` }, 500);
1046
- }
1047
- } catch (error) {
1048
- const msg = error instanceof Error ? error.message : String(error);
1049
- return c.json({ error: msg }, 500);
1050
- }
1051
- });
1052
-
1053
- // 18. Pack workspace codebase and download
1054
- app.get('/api/workspace/:id/pack', async (c) => {
1055
- try {
1056
- const id = decodeURIComponent(c.req.param('id'));
1057
- const config = await loadConfig();
1058
- const workspacePath = path.join(config.workspacesDir, id);
1059
-
1060
- const feature = await loadFeatureConfig(workspacePath);
1061
- if (!feature) {
1062
- return c.json({ error: 'Workspace configuration not found.' }, 404);
1063
- }
1064
-
1065
- const result = await packWorkspace(workspacePath);
1066
- const content = await fs.readFile(result.outputPath, 'utf-8');
1067
-
1068
- c.header('Content-Disposition', `attachment; filename="nexusflow-context-${id.replace(/[\/\\ ]/g, '-')}.xml"`);
1069
- c.header('Content-Type', 'application/xml');
1070
- return c.text(content);
1071
- } catch (error) {
1072
- const msg = error instanceof Error ? error.message : String(error);
1073
- return c.json({ error: msg }, 500);
1074
- }
1075
- });
1076
-
1077
- // Serve index.html explicitly on root endpoint
1078
- app.get('/', async (c) => {
1079
- try {
1080
- const html = await fs.readFile(path.join(guiPath, 'index.html'), 'utf-8');
1081
- return c.html(html);
1082
- } catch (error) {
1083
- return c.text('GUI dashboard built assets not found. Run "npm run build" first.', 404);
1084
- }
1085
- });
1086
-
1087
- // Serve static assets from GUI build folder
1088
- app.use('/*', serveStatic({ root: path.relative(process.cwd(), guiPath) }));
1089
-
1090
- export function startServer(port = 3000): Promise<{ port: number; server: any }> {
1091
- return new Promise((resolve, reject) => {
1092
- const server = serve({ fetch: app.fetch, port }, (info) => {
1093
- resolve({ port: info.port, server });
1094
- }) as import('node:http').Server;
1095
-
1096
- server.on('error', (e: any) => {
1097
- if (e.code === 'EADDRINUSE') {
1098
- resolve(startServer(port + 1));
1099
- } else {
1100
- reject(e);
1101
- }
1102
- });
1103
- });
1104
- }
1
+ /**
2
+ * @module server
3
+ * Hono local web server for the NexusFlow GUI.
4
+ */
5
+
6
+ import { Hono } from 'hono';
7
+ import { serve } from '@hono/node-server';
8
+ import { serveStatic } from '@hono/node-server/serve-static';
9
+ import { cors } from 'hono/cors';
10
+ import { streamSSE } from 'hono/streaming';
11
+ import * as fs from 'node:fs/promises';
12
+ import { createWriteStream, existsSync } from 'node:fs';
13
+ import * as path from 'node:path';
14
+ import { fileURLToPath } from 'node:url';
15
+ import { execa } from 'execa';
16
+ import * as os from 'node:os';
17
+ import { pipeline } from 'node:stream/promises';
18
+ import { spawn } from 'node:child_process';
19
+
20
+ import { loadConfig, saveConfig, getConfigDir } from './core/config.js';
21
+ import { scanForRepos } from './core/scanner.js';
22
+ import { createWorkspace, listWorkspaces, loadFeatureConfig, deleteWorkspace, addRepoToWorkspace } from './core/workspace.js';
23
+ import { analyzeAllRepos } from './analyzers/index.js';
24
+ import { generateContextFiles } from './generators/index.js';
25
+ import { packWorkspace } from './core/packer.js';
26
+ import { isOllamaModelAvailable, getOpenAiCompatibleUrl, callLocalLlm } from './utils/local-ai.js';
27
+ import { detectAIAssistants } from './utils/detect-ai.js';
28
+ import { detectEditors } from './utils/detect-editors.js';
29
+ import { findSessions, getSessionTranscript } from './utils/session-finder.js';
30
+ import { scanSystemSpecs } from './utils/system-scanner.js';
31
+ import { getWorkspaceRepos, rebaseRepo, commitAndPush, getRepoStatus } from './utils/multi-git.js';
32
+ import {
33
+ detectAllServices,
34
+ detectOrchestrationTools,
35
+ startServices,
36
+ stopServices,
37
+ loadRunningState,
38
+ } from './orchestration/index.js';
39
+ import { checkForUpdates, getCurrentVersion, getToolsStatus } from './utils/update-check.js';
40
+ import { getWorkflowTemplates, saveWorkflowTemplate, deleteWorkflowTemplate } from './utils/workflows.js';
41
+ import type { Feature, RepoInfo, WorkspaceContext } from './types.js';
42
+
43
+ // Resolve static files directory
44
+ const __filename = fileURLToPath(import.meta.url);
45
+ const __dirname = path.dirname(__filename);
46
+
47
+ // In development, the static GUI is built to dist/gui
48
+ // In production, it will be served from dist/gui as well
49
+ const guiPath = path.join(__dirname, 'gui');
50
+
51
+ export const app = new Hono();
52
+
53
+ // Allowed editor binaries/scripts to prevent command injection
54
+ const ALLOWED_EDITORS = new Set(['code', 'code-insiders', 'cursor', 'antigravity', 'agy', 'idea', 'charm', 'webstorm', 'subl', 'nano', 'vim', 'nvim', 'emacs']);
55
+
56
+ // Enable CORS for frontend dev server
57
+ app.use('/api/*', cors());
58
+
59
+ // ─── API Endpoints ────────────────────────────────────────────────────────
60
+
61
+ // 1. Get current configuration
62
+ app.get('/api/config', async (c) => {
63
+ try {
64
+ const configPath = path.join(getConfigDir(), 'config.json');
65
+ let exists = false;
66
+ try {
67
+ await fs.access(configPath);
68
+ exists = true;
69
+ } catch {}
70
+
71
+ const config = await loadConfig();
72
+ return c.json({ config, exists });
73
+ } catch (error) {
74
+ const msg = error instanceof Error ? error.message : String(error);
75
+ return c.json({ error: msg }, 500);
76
+ }
77
+ });
78
+
79
+ function isSafeLocalEndpoint(urlStr: string): boolean {
80
+ try {
81
+ const url = new URL(urlStr);
82
+ const hostname = url.hostname.toLowerCase();
83
+ if (hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]') {
84
+ return true;
85
+ }
86
+ const ipv4Pattern = /^(?:10|127|192\.168|172\.(?:1[6-9]|2[0-9]|3[01]))\.\d+\.\d+\.\d+$/;
87
+ if (ipv4Pattern.test(hostname)) {
88
+ return true;
89
+ }
90
+ return false;
91
+ } catch {
92
+ return false;
93
+ }
94
+ }
95
+
96
+ // 2. Save configuration
97
+ app.post('/api/config', async (c) => {
98
+ try {
99
+ const newConfig = await c.req.json();
100
+ if (newConfig?.localLlm?.enabled && newConfig.localLlm.endpoint) {
101
+ if (!isSafeLocalEndpoint(newConfig.localLlm.endpoint)) {
102
+ return c.json({ error: 'Local AI endpoint must be localhost, 127.0.0.1, or a private LAN IP.' }, 400);
103
+ }
104
+ }
105
+ await saveConfig(newConfig);
106
+ return c.json({ success: true, config: newConfig });
107
+ } catch (error) {
108
+ const msg = error instanceof Error ? error.message : String(error);
109
+ return c.json({ error: msg }, 500);
110
+ }
111
+ });
112
+
113
+ // 3. Scan development directory for repositories
114
+ app.get('/api/repos', async (c) => {
115
+ try {
116
+ const config = await loadConfig();
117
+ const repos = await scanForRepos(config.devDir, config.scanDepth);
118
+ return c.json(repos);
119
+ } catch (error) {
120
+ const msg = error instanceof Error ? error.message : String(error);
121
+ return c.json({ error: msg }, 500);
122
+ }
123
+ });
124
+
125
+ // 4. List existing workspaces
126
+ app.get('/api/workspaces', async (c) => {
127
+ try {
128
+ const config = await loadConfig();
129
+ const workspaces = await listWorkspaces(config.workspacesDir);
130
+ return c.json(workspaces);
131
+ } catch (error) {
132
+ const msg = error instanceof Error ? error.message : String(error);
133
+ return c.json({ error: msg }, 500);
134
+ }
135
+ });
136
+
137
+ // 5. Detect available AI assistants
138
+ app.get('/api/ai-detect', async (c) => {
139
+ try {
140
+ const assistants = await detectAIAssistants();
141
+ return c.json(assistants);
142
+ } catch (error) {
143
+ const msg = error instanceof Error ? error.message : String(error);
144
+ return c.json({ error: msg }, 500);
145
+ }
146
+ });
147
+
148
+ // 6. Detect available editors
149
+ app.get('/api/editor-detect', async (c) => {
150
+ try {
151
+ const editors = await detectEditors();
152
+ return c.json(editors);
153
+ } catch (error) {
154
+ const msg = error instanceof Error ? error.message : String(error);
155
+ return c.json({ error: msg }, 500);
156
+ }
157
+ });
158
+
159
+ // 6.5. Local LLM test & recommendation
160
+ app.post('/api/local-llm/test', async (c) => {
161
+ try {
162
+ const { provider, endpoint, model, shoot } = await c.req.json();
163
+ if (!endpoint || !isSafeLocalEndpoint(endpoint)) {
164
+ return c.json({ success: false, error: 'Local AI endpoint must be localhost, 127.0.0.1, or a private LAN IP.' }, 400);
165
+ }
166
+ const cleanEndpoint = endpoint.replace(/\/$/, '');
167
+
168
+ if (shoot) {
169
+ const responseText = await callLocalLlm(
170
+ { enabled: true, provider, endpoint, model },
171
+ [{ role: 'user', content: 'Respond with the exact word "OK" and nothing else.' }]
172
+ );
173
+ const cleanResponse = responseText.trim();
174
+ return c.json({
175
+ success: true,
176
+ modelReady: true,
177
+ message: `Inference test succeeded! Response from model: "${cleanResponse}"`
178
+ });
179
+ }
180
+
181
+ if (provider === 'ollama') {
182
+ const res = await fetch(`${cleanEndpoint}/api/tags`);
183
+ if (!res.ok) throw new Error(`Ollama responded with status ${res.status}`);
184
+ const data: any = await res.json();
185
+ const models = data?.models || [];
186
+ const isModelLoaded = isOllamaModelAvailable(models, model);
187
+ return c.json({
188
+ success: true,
189
+ modelReady: isModelLoaded,
190
+ message: isModelLoaded ? 'Connected successfully! Model is ready.' : `Connected successfully, but model "${model}" is not pulled. Run "ollama pull ${model}" to install it.`
191
+ });
192
+ } else {
193
+ const testUrl = getOpenAiCompatibleUrl(cleanEndpoint, '/v1/models');
194
+ const res = await fetch(testUrl);
195
+ if (!res.ok) throw new Error(`OpenAI-compatible server responded with status ${res.status}`);
196
+ return c.json({ success: true, modelReady: true, message: 'Connected successfully to OpenAI-compatible server!' });
197
+ }
198
+ } catch (error) {
199
+ const msg = error instanceof Error ? error.message : String(error);
200
+ return c.json({ success: false, error: msg }, 400);
201
+ }
202
+ });
203
+
204
+ app.get('/api/local-llm/recommend', async (c) => {
205
+ try {
206
+ const specs = await scanSystemSpecs();
207
+ return c.json(specs);
208
+ } catch (error) {
209
+ return c.json({
210
+ totalRamGb: 8,
211
+ gpuName: 'Unknown/Integrated',
212
+ hasHardwareAcceleration: false,
213
+ recommendedModel: 'qwen2.5-coder:1.5b',
214
+ });
215
+ }
216
+ });
217
+
218
+
219
+ interface JobStep {
220
+ id: string;
221
+ name: string;
222
+ status: 'pending' | 'running' | 'completed' | 'failed';
223
+ message: string;
224
+ }
225
+
226
+ interface CreationJob {
227
+ id: string;
228
+ status: 'running' | 'completed' | 'failed';
229
+ progress: number;
230
+ error?: string;
231
+ steps: JobStep[];
232
+ workspacePath?: string;
233
+ feature?: Feature;
234
+ listeners: Set<(event: { type: string; data: any }) => void>;
235
+ }
236
+
237
+ const creationJobs = new Map<string, CreationJob>();
238
+
239
+ function updateJobStep(
240
+ jobId: string,
241
+ stepId: string,
242
+ status: 'running' | 'completed' | 'failed',
243
+ message: string,
244
+ extraData?: any
245
+ ) {
246
+ const job = creationJobs.get(jobId);
247
+ if (!job) return;
248
+
249
+ const step = job.steps.find((s) => s.id === stepId);
250
+ if (step) {
251
+ step.status = status;
252
+ step.message = message;
253
+ }
254
+
255
+ const isLastStep = job.steps[job.steps.length - 1]?.id === stepId;
256
+ if (isLastStep && status === 'completed') {
257
+ job.status = 'completed';
258
+ job.progress = 100;
259
+ } else if (status === 'failed') {
260
+ job.status = 'failed';
261
+ job.error = message;
262
+ } else {
263
+ const completedCount = job.steps.filter((s) => s.status === 'completed').length;
264
+ const runningCount = job.steps.filter((s) => s.status === 'running').length;
265
+ job.progress = Math.round(((completedCount + runningCount * 0.5) / job.steps.length) * 100);
266
+ }
267
+
268
+ const eventPayload = {
269
+ type: 'progress',
270
+ data: {
271
+ id: job.id,
272
+ status: job.status,
273
+ progress: job.progress,
274
+ error: job.error,
275
+ steps: job.steps,
276
+ workspacePath: job.workspacePath,
277
+ feature: job.feature,
278
+ ...extraData,
279
+ },
280
+ };
281
+
282
+ for (const listener of job.listeners) {
283
+ listener(eventPayload);
284
+ }
285
+ }
286
+
287
+ async function runCreationJob(jobId: string, body: any, config: any) {
288
+ try {
289
+ const workspacePath = path.join(config.workspacesDir, body.branchName);
290
+ const job = creationJobs.get(jobId);
291
+ if (job) {
292
+ job.workspacePath = workspacePath;
293
+ }
294
+
295
+ const feature: Feature = {
296
+ id: body.branchName,
297
+ branchName: body.branchName,
298
+ description: body.description,
299
+ repos: body.repos.map((r: any) => path.join(workspacePath, r.name)),
300
+ originalRepos: body.repos.map((r: any) => r.path),
301
+ assistants: body.assistants,
302
+ workspacePath,
303
+ createdAt: new Date().toISOString(),
304
+ resumption: body.resumption,
305
+ localLlmEnabled: body.localLlmEnabled,
306
+ teamworkInstructions: body.teamworkInstructions,
307
+ };
308
+ if (job) {
309
+ job.feature = feature;
310
+ }
311
+
312
+ // Step 1: Create worktrees
313
+ updateJobStep(jobId, 'worktrees', 'running', 'Creating git worktrees...');
314
+ await createWorkspace(feature, body.repos);
315
+ updateJobStep(jobId, 'worktrees', 'completed', 'Git worktrees created successfully.');
316
+
317
+ // Step 2: Analyze repos
318
+ updateJobStep(jobId, 'analysis', 'running', 'Analyzing projects and dependencies...');
319
+ const workspaceRepos = body.repos.map((repo: any) => ({
320
+ ...repo,
321
+ path: path.join(workspacePath, repo.name),
322
+ }));
323
+ const analysis = await analyzeAllRepos(workspaceRepos);
324
+ updateJobStep(jobId, 'analysis', 'completed', 'Project analysis complete.');
325
+
326
+ // Step 3: Generate AI context files
327
+ updateJobStep(jobId, 'context', 'running', 'Generating AI context files...');
328
+ const ctx: WorkspaceContext = {
329
+ feature,
330
+ repos: workspaceRepos,
331
+ analysis,
332
+ localLlm: config.localLlm,
333
+ };
334
+ await generateContextFiles(ctx, body.assistants, workspacePath);
335
+ updateJobStep(jobId, 'context', 'completed', 'AI context files generated.');
336
+
337
+ // Step 4: Pack codebase context
338
+ if (config.packContextXml) {
339
+ updateJobStep(jobId, 'pack', 'running', 'Packing codebase context with Repomix...');
340
+ const packResult = await packWorkspace(workspacePath);
341
+ updateJobStep(jobId, 'pack', 'completed', `Packed codebase context (${packResult.totalFiles} files, ${(packResult.fileSize / 1024).toFixed(2)} KB).`);
342
+ }
343
+
344
+ } catch (error) {
345
+ const msg = error instanceof Error ? error.message : String(error);
346
+ const job = creationJobs.get(jobId);
347
+ if (job) {
348
+ const runningStep = job.steps.find((s) => s.status === 'running');
349
+ const failedStepId = runningStep ? runningStep.id : 'worktrees';
350
+ updateJobStep(jobId, failedStepId, 'failed', msg);
351
+ }
352
+ }
353
+ }
354
+
355
+ // 7. Create workspace
356
+ app.post('/api/workspace', async (c) => {
357
+ try {
358
+ const body = await c.req.json() as {
359
+ branchName: string;
360
+ description: string;
361
+ repos: RepoInfo[];
362
+ assistants: any[];
363
+ localLlmEnabled?: boolean;
364
+ teamworkInstructions?: string;
365
+ resumption?: {
366
+ testCommand?: string;
367
+ mockCommand?: string;
368
+ startCommand?: string;
369
+ };
370
+ };
371
+
372
+ const config = await loadConfig();
373
+ const jobId = body.branchName;
374
+
375
+ if (creationJobs.has(jobId)) {
376
+ const existing = creationJobs.get(jobId)!;
377
+ if (existing.status === 'running') {
378
+ return c.json({ success: true, jobId, message: 'Job already running' });
379
+ }
380
+ }
381
+
382
+ const steps: JobStep[] = [
383
+ { id: 'worktrees', name: 'Create Git Worktrees', status: 'pending', message: 'Waiting...' },
384
+ { id: 'analysis', name: 'Analyze Repositories', status: 'pending', message: 'Waiting...' },
385
+ { id: 'context', name: 'Generate AI Context Files', status: 'pending', message: 'Waiting...' },
386
+ ];
387
+ if (config.packContextXml) {
388
+ steps.push({ id: 'pack', name: 'Pack Codebase Context', status: 'pending', message: 'Waiting...' });
389
+ }
390
+
391
+ const job: CreationJob = {
392
+ id: jobId,
393
+ status: 'running',
394
+ progress: 0,
395
+ steps,
396
+ listeners: new Set(),
397
+ };
398
+ creationJobs.set(jobId, job);
399
+
400
+ // Run the job in background
401
+ runCreationJob(jobId, body, config);
402
+
403
+ return c.json({ success: true, jobId });
404
+ } catch (error) {
405
+ const msg = error instanceof Error ? error.message : String(error);
406
+ return c.json({ error: msg }, 500);
407
+ }
408
+ });
409
+
410
+ // 7.5. Create workspace SSE stream
411
+ app.get('/api/workspace/create-stream/:jobId', async (c) => {
412
+ const jobId = decodeURIComponent(c.req.param('jobId'));
413
+ const job = creationJobs.get(jobId);
414
+ if (!job) {
415
+ return c.json({ error: 'Job not found' }, 404);
416
+ }
417
+
418
+ c.header('Content-Type', 'text/event-stream');
419
+ c.header('Cache-Control', 'no-cache');
420
+ c.header('Connection', 'keep-alive');
421
+
422
+ return streamSSE(c, async (stream) => {
423
+ // Send initial state
424
+ await stream.writeSSE({
425
+ event: 'progress',
426
+ data: JSON.stringify({
427
+ id: job.id,
428
+ status: job.status,
429
+ progress: job.progress,
430
+ error: job.error,
431
+ steps: job.steps,
432
+ workspacePath: job.workspacePath,
433
+ feature: job.feature,
434
+ }),
435
+ });
436
+
437
+ if (job.status === 'completed' || job.status === 'failed') {
438
+ return;
439
+ }
440
+
441
+ const listener = async (event: { type: string; data: any }) => {
442
+ try {
443
+ await stream.writeSSE({
444
+ event: event.type,
445
+ data: JSON.stringify(event.data),
446
+ });
447
+ } catch (err) {
448
+ job.listeners.delete(listener);
449
+ }
450
+ };
451
+
452
+ job.listeners.add(listener);
453
+
454
+ // Keep connection alive until job finishes
455
+ while (job.status === 'running') {
456
+ await new Promise((resolve) => setTimeout(resolve, 1000));
457
+ }
458
+
459
+ job.listeners.delete(listener);
460
+ });
461
+ });
462
+
463
+ // 7.6. Delete workspace
464
+ app.delete('/api/workspace/:id', async (c) => {
465
+ try {
466
+ const id = decodeURIComponent(c.req.param('id'));
467
+ const config = await loadConfig();
468
+ const workspacePath = path.join(config.workspacesDir, id);
469
+
470
+ await deleteWorkspace(workspacePath);
471
+ return c.json({ success: true });
472
+ } catch (error) {
473
+ const msg = error instanceof Error ? error.message : String(error);
474
+ return c.json({ error: msg }, 500);
475
+ }
476
+ });
477
+
478
+ // 7.7. Add repo to workspace
479
+ app.post('/api/workspace/:id/repo', async (c) => {
480
+ try {
481
+ const id = decodeURIComponent(c.req.param('id'));
482
+ const { repoPath } = await c.req.json() as { repoPath: string };
483
+ const config = await loadConfig();
484
+ const workspacePath = path.join(config.workspacesDir, id);
485
+
486
+ await addRepoToWorkspace(workspacePath, repoPath);
487
+ return c.json({ success: true });
488
+ } catch (error) {
489
+ const msg = error instanceof Error ? error.message : String(error);
490
+ return c.json({ error: msg }, 500);
491
+ }
492
+ });
493
+
494
+ // 8. Open workspace in editor
495
+ app.post('/api/open-editor', async (c) => {
496
+ try {
497
+ const { workspacePath, command } = await c.req.json() as {
498
+ workspacePath: string;
499
+ command: string;
500
+ };
501
+
502
+ if (!ALLOWED_EDITORS.has(command)) {
503
+ return c.json({ error: 'Forbidden editor command' }, 400);
504
+ }
505
+
506
+ // Validate path exists and is a directory
507
+ try {
508
+ const stats = await fs.stat(workspacePath);
509
+ if (!stats.isDirectory()) {
510
+ return c.json({ error: 'Workspace path is not a directory' }, 400);
511
+ }
512
+ } catch {
513
+ return c.json({ error: 'Workspace path does not exist' }, 400);
514
+ }
515
+
516
+ // Spawn editor process
517
+ const isWin = process.platform === 'win32';
518
+ const child = execa(command, [workspacePath], {
519
+ detached: true,
520
+ stdio: 'ignore',
521
+ shell: isWin,
522
+ cleanup: false,
523
+ });
524
+ child.unref();
525
+ child.catch((err) => {
526
+ console.error(`Failed to launch editor ${command} for path ${workspacePath}:`, err);
527
+ });
528
+
529
+ return c.json({ success: true });
530
+ } catch (error) {
531
+ const msg = error instanceof Error ? error.message : String(error);
532
+ return c.json({ error: msg }, 500);
533
+ }
534
+ });
535
+
536
+ // 9. Get status of running services in all/specific workspace
537
+ app.get('/api/workspace/:id/services', async (c) => {
538
+ try {
539
+ const id = c.req.param('id');
540
+ const config = await loadConfig();
541
+ const workspacePath = path.join(config.workspacesDir, id);
542
+
543
+ // Detect all services
544
+ const services = await detectAllServices(workspacePath);
545
+ // Detect existing tools
546
+ const tools = await detectOrchestrationTools(workspacePath);
547
+ // Get currently running services from running state
548
+ const runningState = await loadRunningState(workspacePath);
549
+
550
+ return c.json({
551
+ services,
552
+ orchestrationTools: tools,
553
+ runningState: runningState?.services || [],
554
+ });
555
+ } catch (error) {
556
+ const msg = error instanceof Error ? error.message : String(error);
557
+ return c.json({ error: msg }, 500);
558
+ }
559
+ });
560
+
561
+ // 10. Start services in workspace
562
+ app.post('/api/workspace/:id/services/start', async (c) => {
563
+ try {
564
+ const id = c.req.param('id');
565
+ const { services } = await c.req.json() as { services: any[] };
566
+ const config = await loadConfig();
567
+ const workspacePath = path.join(config.workspacesDir, id);
568
+ const logDir = path.join(workspacePath, '.nexusflow-logs');
569
+
570
+ await startServices(services, workspacePath, logDir);
571
+ return c.json({ success: true });
572
+ } catch (error) {
573
+ const msg = error instanceof Error ? error.message : String(error);
574
+ return c.json({ error: msg }, 500);
575
+ }
576
+ });
577
+
578
+ // 11. Stop services in workspace
579
+ app.post('/api/workspace/:id/services/stop', async (c) => {
580
+ try {
581
+ const id = c.req.param('id');
582
+ const config = await loadConfig();
583
+ const workspacePath = path.join(config.workspacesDir, id);
584
+
585
+ await stopServices(workspacePath);
586
+ return c.json({ success: true });
587
+ } catch (error) {
588
+ const msg = error instanceof Error ? error.message : String(error);
589
+ return c.json({ error: msg }, 500);
590
+ }
591
+ });
592
+
593
+ // 12. Get service logs
594
+ app.get('/api/workspace/:id/services/logs/:serviceName', async (c) => {
595
+ try {
596
+ const id = c.req.param('id');
597
+ const serviceName = c.req.param('serviceName');
598
+ const config = await loadConfig();
599
+ const workspacePath = path.join(config.workspacesDir, id);
600
+ const logFile = path.join(workspacePath, '.nexusflow-logs', `${serviceName}.log`);
601
+
602
+ let content = '';
603
+ try {
604
+ // Read last 200 lines or 50KB
605
+ const stats = await fs.stat(logFile);
606
+ const size = stats.size;
607
+ const start = Math.max(0, size - 50000);
608
+ const fd = await fs.open(logFile, 'r');
609
+ const buffer = Buffer.alloc(size - start);
610
+ await fd.read(buffer, 0, buffer.length, start);
611
+ await fd.close();
612
+ content = buffer.toString('utf-8');
613
+ } catch {
614
+ content = 'No logs available yet.';
615
+ }
616
+
617
+ return c.json({ logs: content });
618
+ } catch (error) {
619
+ const msg = error instanceof Error ? error.message : String(error);
620
+ return c.json({ error: msg }, 500);
621
+ }
622
+ });
623
+
624
+ // 13. Get git changes in workspace sub-repositories
625
+ app.get('/api/workspace/:id/changes', async (c) => {
626
+ try {
627
+ const id = c.req.param('id');
628
+ const config = await loadConfig();
629
+ const workspacePath = path.join(config.workspacesDir, id);
630
+
631
+ // Load feature config to get repo paths
632
+ const feature = await loadFeatureConfig(workspacePath);
633
+ if (!feature) {
634
+ return c.json({ error: 'Workspace configuration not found.' }, 404);
635
+ }
636
+
637
+ const results: any[] = [];
638
+
639
+ // Check git status in each repo
640
+ for (const repoPath of feature.repos) {
641
+ const repoName = path.basename(repoPath);
642
+ const worktreePath = path.join(workspacePath, repoName);
643
+
644
+ try {
645
+ const { stdout } = await execa('git', ['status', '--porcelain'], { cwd: worktreePath });
646
+ const lines = stdout.split('\n').map((l) => l.trim()).filter(Boolean);
647
+
648
+ // Get numstat to determine additions and deletions per file
649
+ const numstatMap = new Map<string, { additions: number; deletions: number }>();
650
+ try {
651
+ const { stdout: numstatRaw } = await execa('git', ['diff', 'HEAD', '--numstat'], {
652
+ cwd: worktreePath,
653
+ });
654
+ const numstatLines = numstatRaw.split('\n').filter(Boolean);
655
+ for (const numLine of numstatLines) {
656
+ const parts = numLine.trim().split(/\s+/);
657
+ if (parts.length >= 3) {
658
+ const [add, del, file] = parts;
659
+ numstatMap.set(file, {
660
+ additions: add === '-' ? 0 : parseInt(add, 10) || 0,
661
+ deletions: del === '-' ? 0 : parseInt(del, 10) || 0,
662
+ });
663
+ }
664
+ }
665
+ } catch (e) {
666
+ // Ignore diff errors
667
+ }
668
+
669
+ const files = lines.map((line) => {
670
+ const status = line.slice(0, 2).trim();
671
+ const file = line.slice(2).trim();
672
+
673
+ let type = 'modified';
674
+ if (status === 'A' || status === '??') type = 'added';
675
+ else if (status === 'D') type = 'deleted';
676
+
677
+ const stats = numstatMap.get(file) || { additions: 0, deletions: 0 };
678
+
679
+ return {
680
+ file,
681
+ type,
682
+ rawStatus: status,
683
+ additions: stats.additions,
684
+ deletions: stats.deletions,
685
+ };
686
+ });
687
+
688
+ results.push({
689
+ repoName,
690
+ repoPath: worktreePath,
691
+ files,
692
+ });
693
+ } catch (error) {
694
+ results.push({
695
+ repoName,
696
+ repoPath: worktreePath,
697
+ files: [],
698
+ error: error instanceof Error ? error.message : String(error),
699
+ });
700
+ }
701
+ }
702
+
703
+ return c.json({ changes: results });
704
+ } catch (error) {
705
+ const msg = error instanceof Error ? error.message : String(error);
706
+ return c.json({ error: msg }, 500);
707
+ }
708
+ });
709
+
710
+ // 13_diff. Get git diff for a specific file in workspace sub-repositories
711
+ app.get('/api/workspace/:id/changes/diff', async (c) => {
712
+ try {
713
+ const id = c.req.param('id');
714
+ const repoName = c.req.query('repo');
715
+ const filePath = c.req.query('file');
716
+
717
+ if (!repoName || !filePath) {
718
+ return c.json({ error: 'Missing repo or file query parameter.' }, 400);
719
+ }
720
+
721
+ const config = await loadConfig();
722
+ const workspacePath = path.join(config.workspacesDir, id);
723
+ const worktreePath = path.join(workspacePath, repoName);
724
+
725
+ // Security check: ensure path is within workspace directory
726
+ const resolvedPath = path.resolve(worktreePath);
727
+ if (!resolvedPath.startsWith(path.resolve(workspacePath))) {
728
+ return c.json({ error: 'Invalid repository path.' }, 400);
729
+ }
730
+
731
+ let diff = '';
732
+
733
+ // Check git status for the file to know if it's untracked
734
+ try {
735
+ const { stdout: statusOut } = await execa('git', ['status', '--porcelain', '--', filePath], { cwd: worktreePath });
736
+ const statusLine = statusOut.trim();
737
+ const isUntracked = statusLine.startsWith('??');
738
+
739
+ if (isUntracked) {
740
+ const result = await execa('git', ['diff', '--no-index', '--', '/dev/null', filePath], {
741
+ cwd: worktreePath,
742
+ reject: false
743
+ });
744
+ diff = result.stdout || result.stderr || '';
745
+ } else {
746
+ const result = await execa('git', ['diff', 'HEAD', '--', filePath], {
747
+ cwd: worktreePath,
748
+ reject: false
749
+ });
750
+ diff = result.stdout || result.stderr || '';
751
+ }
752
+ } catch (e) {
753
+ const result = await execa('git', ['diff', 'HEAD', '--', filePath], {
754
+ cwd: worktreePath,
755
+ reject: false
756
+ });
757
+ diff = result.stdout || result.stderr || '';
758
+ }
759
+
760
+ return c.json({ diff });
761
+ } catch (error) {
762
+ const msg = error instanceof Error ? error.message : String(error);
763
+ return c.json({ error: msg }, 500);
764
+ }
765
+ });
766
+
767
+ // 13a. Get workspace knowledge (nexusflow-knowledge.md)
768
+ app.get('/api/workspace/:id/knowledge', async (c) => {
769
+ try {
770
+ const id = c.req.param('id');
771
+ const config = await loadConfig();
772
+ const workspacePath = path.join(config.workspacesDir, id);
773
+ const knowledgeFile = path.join(workspacePath, 'nexusflow-knowledge.md');
774
+
775
+ let content = '';
776
+ try {
777
+ content = await fs.readFile(knowledgeFile, 'utf-8');
778
+ } catch {
779
+ content = '# Workspace Knowledge\n\nNo knowledge file yet.';
780
+ }
781
+
782
+ return c.json({ content });
783
+ } catch (error) {
784
+ const msg = error instanceof Error ? error.message : String(error);
785
+ return c.json({ error: msg }, 500);
786
+ }
787
+ });
788
+
789
+ // 13b. Update workspace knowledge (nexusflow-knowledge.md)
790
+ app.put('/api/workspace/:id/knowledge', async (c) => {
791
+ try {
792
+ const id = c.req.param('id');
793
+ const { content } = await c.req.json() as { content: string };
794
+ const config = await loadConfig();
795
+ const workspacePath = path.join(config.workspacesDir, id);
796
+ const knowledgeFile = path.join(workspacePath, 'nexusflow-knowledge.md');
797
+
798
+ await fs.writeFile(knowledgeFile, content, 'utf-8');
799
+ return c.json({ success: true });
800
+ } catch (error) {
801
+ const msg = error instanceof Error ? error.message : String(error);
802
+ return c.json({ error: msg }, 500);
803
+ }
804
+ });
805
+
806
+ // 13c. Get workspace plan (nexusflow-plan.md)
807
+ app.get('/api/workspace/:id/plan', async (c) => {
808
+ try {
809
+ const id = c.req.param('id');
810
+ const config = await loadConfig();
811
+ const workspacePath = path.join(config.workspacesDir, id);
812
+ const planFile = path.join(workspacePath, 'nexusflow-plan.md');
813
+
814
+ let content = '';
815
+ try {
816
+ content = await fs.readFile(planFile, 'utf-8');
817
+ } catch {
818
+ content = '# Workspace Plan\n\nNo implementation plan file yet.';
819
+ }
820
+
821
+ return c.json({ content });
822
+ } catch (error) {
823
+ const msg = error instanceof Error ? error.message : String(error);
824
+ return c.json({ error: msg }, 500);
825
+ }
826
+ });
827
+
828
+ // 13d. Sync all repositories in workspace
829
+ app.post('/api/workspace/:id/sync', async (c) => {
830
+ try {
831
+ const id = c.req.param('id');
832
+ const config = await loadConfig();
833
+ const workspacePath = path.join(config.workspacesDir, id);
834
+
835
+ const repos = await getWorkspaceRepos(workspacePath);
836
+ const results = [];
837
+
838
+ for (const repo of repos) {
839
+ const result = await rebaseRepo(repo.path, repo.defaultBranch || 'main');
840
+ results.push({
841
+ repoName: repo.name,
842
+ success: result.success,
843
+ message: result.message,
844
+ conflict: result.conflict,
845
+ });
846
+ }
847
+
848
+ return c.json({ results });
849
+ } catch (error) {
850
+ const msg = error instanceof Error ? error.message : String(error);
851
+ return c.json({ error: msg }, 500);
852
+ }
853
+ });
854
+
855
+ // 13e. Commit changes in all repositories in workspace
856
+ app.post('/api/workspace/:id/commit', async (c) => {
857
+ try {
858
+ const id = c.req.param('id');
859
+ const { message } = await c.req.json() as { message: string };
860
+ const config = await loadConfig();
861
+ const workspacePath = path.join(config.workspacesDir, id);
862
+
863
+ const repos = await getWorkspaceRepos(workspacePath);
864
+ const results = [];
865
+
866
+ for (const repo of repos) {
867
+ const status = await getRepoStatus(repo.path);
868
+ if (status.hasChanges) {
869
+ const result = await commitAndPush(repo.path, message, repo.branchName);
870
+ results.push({
871
+ repoName: repo.name,
872
+ success: result.success,
873
+ commitHash: result.commitHash,
874
+ filesChanged: result.filesChanged,
875
+ message: result.message,
876
+ });
877
+ }
878
+ }
879
+
880
+ return c.json({ results });
881
+ } catch (error) {
882
+ const msg = error instanceof Error ? error.message : String(error);
883
+ return c.json({ error: msg }, 500);
884
+ }
885
+ });
886
+
887
+
888
+ // 14. Resume session in workspace (copies CLI resume command and opens editor)
889
+ app.post('/api/workspace/:id/resume', async (c) => {
890
+ try {
891
+ const id = decodeURIComponent(c.req.param('id'));
892
+ const config = await loadConfig();
893
+ const workspacePath = path.join(config.workspacesDir, id);
894
+
895
+ // Load feature config to get repo paths
896
+ const feature = await loadFeatureConfig(workspacePath);
897
+ if (!feature) {
898
+ return c.json({ error: 'Workspace configuration not found.' }, 404);
899
+ }
900
+
901
+ const body = await c.req.json().catch(() => ({}));
902
+ const targetSessionId = body.sessionId;
903
+ const targetAssistant = body.assistant;
904
+
905
+ // Find the session to resume
906
+ let resumeCommand = '';
907
+ let selectedAssistant = targetAssistant || feature.assistants[0] || 'antigravity';
908
+ let selectedSessionId = targetSessionId;
909
+
910
+ if (!selectedSessionId) {
911
+ // Find the most recent session matching this workspace
912
+ const sessions = await findSessions(workspacePath, feature.repos);
913
+ if (sessions.length > 0) {
914
+ selectedSessionId = sessions[0].id;
915
+ selectedAssistant = sessions[0].assistant;
916
+ }
917
+ }
918
+
919
+ if (selectedSessionId) {
920
+ if (selectedAssistant === 'antigravity') {
921
+ resumeCommand = `agy --conversation ${selectedSessionId}`;
922
+ } else if (selectedAssistant === 'claude') {
923
+ resumeCommand = `claude --resume ${selectedSessionId}`;
924
+ } else if (selectedAssistant === 'codex') {
925
+ resumeCommand = `codex resume ${selectedSessionId}`;
926
+ } else if (selectedAssistant === 'copilot') {
927
+ resumeCommand = `copilot --resume ${selectedSessionId}`;
928
+ }
929
+ } else {
930
+ // Fallback to start command (since there's no existing session for this workspace)
931
+ if (selectedAssistant === 'antigravity') {
932
+ resumeCommand = 'agy --continue';
933
+ } else if (selectedAssistant === 'claude') {
934
+ resumeCommand = 'claude --resume';
935
+ } else if (selectedAssistant === 'codex') {
936
+ resumeCommand = 'codex resume';
937
+ } else if (selectedAssistant === 'copilot') {
938
+ resumeCommand = 'copilot --resume';
939
+ } else {
940
+ resumeCommand = 'agy --continue';
941
+ }
942
+ }
943
+
944
+ // Open in editor if command is provided
945
+ if (body.command) {
946
+ if (!ALLOWED_EDITORS.has(body.command)) {
947
+ return c.json({ error: 'Forbidden editor command' }, 400);
948
+ }
949
+ const isWin = process.platform === 'win32';
950
+ const child = execa(body.command, [workspacePath], {
951
+ detached: true,
952
+ stdio: 'ignore',
953
+ shell: isWin,
954
+ cleanup: false,
955
+ });
956
+ child.unref();
957
+ child.catch((err) => {
958
+ console.error(`Failed to launch editor ${body.command} for path ${workspacePath}:`, err);
959
+ });
960
+ }
961
+
962
+ return c.json({ success: true, resumeCommand, workspacePath });
963
+ } catch (error) {
964
+ const msg = error instanceof Error ? error.message : String(error);
965
+ return c.json({ error: msg }, 500);
966
+ }
967
+ });
968
+
969
+ // 15. List past AI sessions for a workspace
970
+ app.get('/api/workspace/:id/sessions', async (c) => {
971
+ try {
972
+ const id = decodeURIComponent(c.req.param('id'));
973
+ const config = await loadConfig();
974
+ const workspacePath = path.join(config.workspacesDir, id);
975
+
976
+ const feature = await loadFeatureConfig(workspacePath);
977
+ if (!feature) {
978
+ return c.json({ error: 'Workspace configuration not found.' }, 404);
979
+ }
980
+
981
+ const sessions = await findSessions(workspacePath, feature.repos);
982
+ return c.json({ sessions });
983
+ } catch (error) {
984
+ const msg = error instanceof Error ? error.message : String(error);
985
+ return c.json({ error: msg }, 500);
986
+ }
987
+ });
988
+
989
+ // 16. Fetch transcript for a specific AI session
990
+ app.get('/api/session/:assistant/:sessionId/transcript', async (c) => {
991
+ try {
992
+ const assistant = c.req.param('assistant');
993
+ const sessionId = c.req.param('sessionId');
994
+ const messages = await getSessionTranscript(assistant, sessionId);
995
+ return c.json({ messages });
996
+ } catch (error) {
997
+ const msg = error instanceof Error ? error.message : String(error);
998
+ return c.json({ error: msg }, 500);
999
+ }
1000
+ });
1001
+
1002
+ // 17. Check for NexusFlow updates
1003
+ app.get('/api/update-status', async (c) => {
1004
+ try {
1005
+ const status = await checkForUpdates(false);
1006
+ if (!status) {
1007
+ const currentVersion = getCurrentVersion();
1008
+ return c.json({ currentVersion, latestVersion: currentVersion, updateAvailable: false });
1009
+ }
1010
+ return c.json(status);
1011
+ } catch (error) {
1012
+ const msg = error instanceof Error ? error.message : String(error);
1013
+ return c.json({ error: msg }, 500);
1014
+ }
1015
+ });
1016
+
1017
+ // 17.5. Check tools updates status
1018
+ app.get('/api/updates/tools', async (c) => {
1019
+ try {
1020
+ const force = c.req.query('force') === 'true';
1021
+ const status = await getToolsStatus(force);
1022
+ return c.json(status);
1023
+ } catch (error) {
1024
+ const msg = error instanceof Error ? error.message : String(error);
1025
+ return c.json({ error: msg }, 500);
1026
+ }
1027
+ });
1028
+
1029
+ // 17.6. Install updates for a specific tool
1030
+ app.post('/api/updates/install', async (c) => {
1031
+ try {
1032
+ const { toolId } = await c.req.json() as { toolId: string };
1033
+ const tools = [
1034
+ { id: 'nexusflow', cmd: 'npm', args: ['install', '-g', '@mrpatronz/nexusflow'] },
1035
+ { id: 'repomix', cmd: 'npm', args: ['install', '-g', 'repomix'] },
1036
+ { id: 'antigravity', cmd: 'agy', args: ['update'] },
1037
+ { id: 'claude', cmd: 'npm', args: ['install', '-g', '@anthropic-ai/claude-code'] },
1038
+ ];
1039
+
1040
+ const target = tools.find(t => t.id === toolId);
1041
+ if (!target) {
1042
+ return c.json({ error: 'Tool not found' }, 404);
1043
+ }
1044
+
1045
+ const result = await execa(target.cmd, target.args, {
1046
+ reject: false,
1047
+ shell: process.platform === 'win32',
1048
+ });
1049
+ if (result.exitCode === 0) {
1050
+ return c.json({ success: true, output: result.stdout });
1051
+ } else {
1052
+ return c.json({ error: `Update failed: ${result.stderr || result.stdout}` }, 500);
1053
+ }
1054
+ } catch (error) {
1055
+ const msg = error instanceof Error ? error.message : String(error);
1056
+ return c.json({ error: msg }, 500);
1057
+ }
1058
+ });
1059
+
1060
+ let downloadedInstallerPath: string | null = null;
1061
+
1062
+ // 17.7. Download matching GitHub Release installer to temporary folder
1063
+ app.post('/api/updates/download', async (c) => {
1064
+ try {
1065
+ const { downloadUrl } = await c.req.json() as { downloadUrl: string };
1066
+ if (!downloadUrl) {
1067
+ return c.json({ error: 'Download URL is required' }, 400);
1068
+ }
1069
+
1070
+ const tempDir = os.tmpdir();
1071
+ const fileName = 'NexusFlowSetup_Update.exe';
1072
+ const targetPath = path.join(tempDir, fileName);
1073
+
1074
+ const response = await fetch(downloadUrl);
1075
+ if (!response.ok) {
1076
+ throw new Error(`HTTP error ${response.status}`);
1077
+ }
1078
+
1079
+ // Node fetch body stream download
1080
+ const fileStream = createWriteStream(targetPath);
1081
+ if (!response.body) {
1082
+ throw new Error('Response body is null');
1083
+ }
1084
+
1085
+ // Convert ReadableStream to Node stream
1086
+ await pipeline(response.body as any, fileStream);
1087
+
1088
+ downloadedInstallerPath = targetPath;
1089
+ return c.json({ success: true, path: targetPath });
1090
+ } catch (error) {
1091
+ const msg = error instanceof Error ? error.message : String(error);
1092
+ return c.json({ error: `Download failed: ${msg}` }, 500);
1093
+ }
1094
+ });
1095
+
1096
+ // 17.8. Launch the silent installer detached and exit server
1097
+ app.post('/api/updates/apply', async (c) => {
1098
+ if (!downloadedInstallerPath || !existsSync(downloadedInstallerPath)) {
1099
+ return c.json({ error: 'No downloaded installer found on disk' }, 400);
1100
+ }
1101
+
1102
+ try {
1103
+ const isWin = process.platform === 'win32';
1104
+ if (isWin) {
1105
+ // Inno Setup silent install flags
1106
+ console.log(`Applying update: Spawning detached installer at: ${downloadedInstallerPath}`);
1107
+ const child = spawn(downloadedInstallerPath, ['/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART'], {
1108
+ detached: true,
1109
+ stdio: 'ignore',
1110
+ });
1111
+ child.unref();
1112
+ }
1113
+
1114
+ // Gracefully exit server process in 1 second to release file locks
1115
+ setTimeout(() => {
1116
+ console.log('Update installer successfully spawned. Exiting Hono server process...');
1117
+ process.exit(0);
1118
+ }, 1000);
1119
+
1120
+ return c.json({ success: true, message: 'Installer spawned, app shutting down...' });
1121
+ } catch (error) {
1122
+ const msg = error instanceof Error ? error.message : String(error);
1123
+ return c.json({ error: `Failed to execute update: ${msg}` }, 500);
1124
+ }
1125
+ });
1126
+
1127
+ // 17.9. Get available workflow templates
1128
+ app.get('/api/workflows/templates', async (c) => {
1129
+ try {
1130
+ const templates = await getWorkflowTemplates();
1131
+ return c.json({ templates });
1132
+ } catch (error) {
1133
+ const msg = error instanceof Error ? error.message : String(error);
1134
+ return c.json({ error: msg }, 500);
1135
+ }
1136
+ });
1137
+
1138
+ // Save or update custom teamwork template
1139
+ app.post('/api/workflows/templates', async (c) => {
1140
+ try {
1141
+ const { id, name, content } = await c.req.json();
1142
+ if (!name || !content) {
1143
+ return c.json({ error: 'Name and content are required.' }, 400);
1144
+ }
1145
+ const template = await saveWorkflowTemplate(name, content, id);
1146
+ return c.json({ success: true, template });
1147
+ } catch (error) {
1148
+ const msg = error instanceof Error ? error.message : String(error);
1149
+ return c.json({ error: msg }, 500);
1150
+ }
1151
+ });
1152
+
1153
+ // Delete custom teamwork template
1154
+ app.delete('/api/workflows/templates/:id', async (c) => {
1155
+ try {
1156
+ const id = decodeURIComponent(c.req.param('id'));
1157
+ const templates = await getWorkflowTemplates();
1158
+ const target = templates.find(t => t.id === id);
1159
+ if (!target) {
1160
+ return c.json({ error: 'Template not found.' }, 404);
1161
+ }
1162
+ if (!target.custom) {
1163
+ return c.json({ error: 'Cannot delete built-in templates.' }, 403);
1164
+ }
1165
+ await deleteWorkflowTemplate(id);
1166
+ return c.json({ success: true });
1167
+ } catch (error) {
1168
+ const msg = error instanceof Error ? error.message : String(error);
1169
+ return c.json({ error: msg }, 500);
1170
+ }
1171
+ });
1172
+
1173
+ // Analyze teamwork template rules via selected AI coding assistant harness
1174
+ app.post('/api/workflows/templates/:id/analyze', async (c) => {
1175
+ try {
1176
+ const { content, assistant, comment } = await c.req.json();
1177
+ if (!content) {
1178
+ return c.json({ error: 'Content is required.' }, 400);
1179
+ }
1180
+
1181
+ const selectedAssistant = assistant || 'antigravity';
1182
+ let command = '';
1183
+ let args: string[] = [];
1184
+
1185
+ let prompt = `You are an expert AI system engineering reviewer. Analyze the following Agent Teamwork Strategy guidelines.
1186
+ Evaluate its instructions, identify any ambiguities or contradictions, rate its expected effectiveness for orchestrating subagents, and provide specific recommendations or improvements. Format your analysis in clean Markdown with clear headings (e.g. Overview, Strengths, Weaknesses, Recommendations).
1187
+
1188
+ After your analysis, provide a fully rewritten, optimized, and complete version of the strategy guidelines incorporating all your recommendations. This rewritten version must be suitable for production orchestration.
1189
+ You MUST prefix the rewritten version with the exact delimiter line:
1190
+ === SUGGESTED IMPROVEMENT START ===
1191
+ and suffix it with:
1192
+ === SUGGESTED IMPROVEMENT END ===`;
1193
+
1194
+ if (comment && comment.trim()) {
1195
+ prompt += `\n\nIMPORTANT: The user has provided the following specific instruction/comment that you MUST consider and prioritize during your evaluation and when rewriting the guidelines:\n"${comment.trim()}"`;
1196
+ }
1197
+
1198
+ prompt += `\n\n--- GUIDELINES START ---\n${content}\n--- GUIDELINES END ---`;
1199
+
1200
+ const assistants = await detectAIAssistants();
1201
+ const target = assistants.find(ai => ai.name === selectedAssistant);
1202
+
1203
+ if (!target || !target.detected || !target.command) {
1204
+ return c.json({
1205
+ error: `AI assistant harness '${selectedAssistant}' is not detected or does not support command-line execution.`
1206
+ }, 400);
1207
+ }
1208
+
1209
+ command = target.command;
1210
+ if (command === 'claude') {
1211
+ args = ['-p', prompt];
1212
+ } else if (command === 'agy') {
1213
+ args = [prompt];
1214
+ } else {
1215
+ args = [prompt];
1216
+ }
1217
+
1218
+ const result = await execa(command, args, {
1219
+ input: '',
1220
+ shell: false,
1221
+ reject: false
1222
+ });
1223
+
1224
+ if (result.exitCode !== 0) {
1225
+ return c.json({
1226
+ error: `AI Assistant harness execution failed (exit code ${result.exitCode}): ${result.stderr || result.stdout || 'Unknown error'}`
1227
+ }, 500);
1228
+ }
1229
+
1230
+ // Clean potential warning lines or stdout prefixes if present
1231
+ let cleanText = result.stdout;
1232
+ if (cleanText.includes('Warning: no stdin data received')) {
1233
+ cleanText = cleanText.replace(/Warning: no stdin data received in \d+s, proceeding without it\. If piping from a slow command, redirect stdin explicitly: < \/dev\/null to skip, or wait longer\.\r?\n?/, '');
1234
+ }
1235
+
1236
+ let analysis = cleanText.trim();
1237
+ let suggestedImprovement = '';
1238
+
1239
+ const startDelimiter = '=== SUGGESTED IMPROVEMENT START ===';
1240
+ const endDelimiter = '=== SUGGESTED IMPROVEMENT END ===';
1241
+
1242
+ const startIdx = cleanText.indexOf(startDelimiter);
1243
+ const endIdx = cleanText.indexOf(endDelimiter);
1244
+
1245
+ if (startIdx !== -1 && endIdx !== -1) {
1246
+ analysis = cleanText.substring(0, startIdx).trim();
1247
+ suggestedImprovement = cleanText.substring(startIdx + startDelimiter.length, endIdx).trim();
1248
+ }
1249
+
1250
+ return c.json({ analysis, suggestedImprovement });
1251
+ } catch (error) {
1252
+ const msg = error instanceof Error ? error.message : String(error);
1253
+ return c.json({ error: msg }, 500);
1254
+ }
1255
+ });
1256
+
1257
+ // 18. Pack workspace codebase and download
1258
+ app.get('/api/workspace/:id/pack', async (c) => {
1259
+ try {
1260
+ const id = decodeURIComponent(c.req.param('id'));
1261
+ const config = await loadConfig();
1262
+ const workspacePath = path.join(config.workspacesDir, id);
1263
+
1264
+ const feature = await loadFeatureConfig(workspacePath);
1265
+ if (!feature) {
1266
+ return c.json({ error: 'Workspace configuration not found.' }, 404);
1267
+ }
1268
+
1269
+ const result = await packWorkspace(workspacePath);
1270
+ const content = await fs.readFile(result.outputPath, 'utf-8');
1271
+
1272
+ c.header('Content-Disposition', `attachment; filename="nexusflow-context-${id.replace(/[\/\\ ]/g, '-')}.xml"`);
1273
+ c.header('Content-Type', 'application/xml');
1274
+ return c.text(content);
1275
+ } catch (error) {
1276
+ const msg = error instanceof Error ? error.message : String(error);
1277
+ return c.json({ error: msg }, 500);
1278
+ }
1279
+ });
1280
+
1281
+ // Serve index.html explicitly on root endpoint
1282
+ app.get('/', async (c) => {
1283
+ try {
1284
+ const html = await fs.readFile(path.join(guiPath, 'index.html'), 'utf-8');
1285
+ return c.html(html);
1286
+ } catch (error) {
1287
+ return c.text('GUI dashboard built assets not found. Run "npm run build" first.', 404);
1288
+ }
1289
+ });
1290
+
1291
+ // Serve static assets from GUI build folder
1292
+ app.use('/*', serveStatic({ root: path.relative(process.cwd(), guiPath) }));
1293
+
1294
+ export function startServer(port = 3000): Promise<{ port: number; server: any }> {
1295
+ return new Promise((resolve, reject) => {
1296
+ const server = serve({ fetch: app.fetch, port }, (info) => {
1297
+ resolve({ port: info.port, server });
1298
+ }) as import('node:http').Server;
1299
+
1300
+ server.on('error', (e: any) => {
1301
+ if (e.code === 'EADDRINUSE') {
1302
+ resolve(startServer(port + 1));
1303
+ } else {
1304
+ reject(e);
1305
+ }
1306
+ });
1307
+ });
1308
+ }