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