@mrpatronz/nexusflow 0.2.18 → 1.3.0

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