vibecodepilot 0.0.0-stage → 1.0.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.
- package/LICENSE +21 -0
- package/README.md +174 -2
- package/apps/dashboard/dist/assets/index-CqhDXwBX.css +1 -0
- package/apps/dashboard/dist/assets/index-DB7dE_Nn.js +493 -0
- package/apps/dashboard/dist/index.html +31 -0
- package/apps/dashboard/dist-server/serve-dashboard.cjs +99 -0
- package/apps/dashboard/package.json +23 -0
- package/apps/server/dist/db/database.d.ts +91 -0
- package/apps/server/dist/db/database.d.ts.map +1 -0
- package/apps/server/dist/db/database.js +902 -0
- package/apps/server/dist/db/database.js.map +1 -0
- package/apps/server/dist/index.d.ts +2 -0
- package/apps/server/dist/index.d.ts.map +1 -0
- package/apps/server/dist/index.js +2262 -0
- package/apps/server/dist/index.js.map +1 -0
- package/apps/server/dist/services/agentWorkspaceService.d.ts +89 -0
- package/apps/server/dist/services/agentWorkspaceService.d.ts.map +1 -0
- package/apps/server/dist/services/agentWorkspaceService.js +243 -0
- package/apps/server/dist/services/agentWorkspaceService.js.map +1 -0
- package/apps/server/dist/services/monitorService.d.ts +118 -0
- package/apps/server/dist/services/monitorService.d.ts.map +1 -0
- package/apps/server/dist/services/monitorService.js +497 -0
- package/apps/server/dist/services/monitorService.js.map +1 -0
- package/apps/server/dist/services/projectFlowGraph.d.ts +70 -0
- package/apps/server/dist/services/projectFlowGraph.d.ts.map +1 -0
- package/apps/server/dist/services/projectFlowGraph.js +254 -0
- package/apps/server/dist/services/projectFlowGraph.js.map +1 -0
- package/apps/server/dist/tech-detector.d.ts +2 -0
- package/apps/server/dist/tech-detector.d.ts.map +1 -0
- package/apps/server/dist/tech-detector.js +154 -0
- package/apps/server/dist/tech-detector.js.map +1 -0
- package/apps/server/dist/workspace-tools.d.ts +43 -0
- package/apps/server/dist/workspace-tools.d.ts.map +1 -0
- package/apps/server/dist/workspace-tools.js +160 -0
- package/apps/server/dist/workspace-tools.js.map +1 -0
- package/apps/server/package.json +24 -0
- package/node_modules/@VibeCodePilot/agent-registry/dist/index.d.ts +21 -0
- package/node_modules/@VibeCodePilot/agent-registry/dist/index.d.ts.map +1 -0
- package/node_modules/@VibeCodePilot/agent-registry/dist/index.js +194 -0
- package/node_modules/@VibeCodePilot/agent-registry/dist/index.js.map +1 -0
- package/node_modules/@VibeCodePilot/agent-registry/package.json +18 -0
- package/node_modules/@VibeCodePilot/git-worktrees/dist/index.d.ts +48 -0
- package/node_modules/@VibeCodePilot/git-worktrees/dist/index.d.ts.map +1 -0
- package/node_modules/@VibeCodePilot/git-worktrees/dist/index.js +121 -0
- package/node_modules/@VibeCodePilot/git-worktrees/dist/index.js.map +1 -0
- package/node_modules/@VibeCodePilot/git-worktrees/package.json +18 -0
- package/node_modules/@VibeCodePilot/inference-gateway/dist/index.d.ts +54 -0
- package/node_modules/@VibeCodePilot/inference-gateway/dist/index.d.ts.map +1 -0
- package/node_modules/@VibeCodePilot/inference-gateway/dist/index.js +157 -0
- package/node_modules/@VibeCodePilot/inference-gateway/dist/index.js.map +1 -0
- package/node_modules/@VibeCodePilot/inference-gateway/package.json +19 -0
- package/node_modules/@VibeCodePilot/integration/dist/index.d.ts +13 -0
- package/node_modules/@VibeCodePilot/integration/dist/index.d.ts.map +1 -0
- package/node_modules/@VibeCodePilot/integration/dist/index.js +83 -0
- package/node_modules/@VibeCodePilot/integration/dist/index.js.map +1 -0
- package/node_modules/@VibeCodePilot/integration/package.json +20 -0
- package/node_modules/@VibeCodePilot/model-manager/dist/index.d.ts +44 -0
- package/node_modules/@VibeCodePilot/model-manager/dist/index.d.ts.map +1 -0
- package/node_modules/@VibeCodePilot/model-manager/dist/index.js +192 -0
- package/node_modules/@VibeCodePilot/model-manager/dist/index.js.map +1 -0
- package/node_modules/@VibeCodePilot/model-manager/package.json +19 -0
- package/node_modules/@VibeCodePilot/permissions/dist/engine.d.ts +95 -0
- package/node_modules/@VibeCodePilot/permissions/dist/engine.d.ts.map +1 -0
- package/node_modules/@VibeCodePilot/permissions/dist/engine.js +294 -0
- package/node_modules/@VibeCodePilot/permissions/dist/engine.js.map +1 -0
- package/node_modules/@VibeCodePilot/permissions/dist/index.d.ts +4 -0
- package/node_modules/@VibeCodePilot/permissions/dist/index.d.ts.map +1 -0
- package/node_modules/@VibeCodePilot/permissions/dist/index.js +20 -0
- package/node_modules/@VibeCodePilot/permissions/dist/index.js.map +1 -0
- package/node_modules/@VibeCodePilot/permissions/dist/security.d.ts +31 -0
- package/node_modules/@VibeCodePilot/permissions/dist/security.d.ts.map +1 -0
- package/node_modules/@VibeCodePilot/permissions/dist/security.js +129 -0
- package/node_modules/@VibeCodePilot/permissions/dist/security.js.map +1 -0
- package/node_modules/@VibeCodePilot/permissions/dist/types.d.ts +108 -0
- package/node_modules/@VibeCodePilot/permissions/dist/types.d.ts.map +1 -0
- package/node_modules/@VibeCodePilot/permissions/dist/types.js +3 -0
- package/node_modules/@VibeCodePilot/permissions/dist/types.js.map +1 -0
- package/node_modules/@VibeCodePilot/permissions/package.json +20 -0
- package/node_modules/@VibeCodePilot/planner/dist/index.d.ts +35 -0
- package/node_modules/@VibeCodePilot/planner/dist/index.d.ts.map +1 -0
- package/node_modules/@VibeCodePilot/planner/dist/index.js +592 -0
- package/node_modules/@VibeCodePilot/planner/dist/index.js.map +1 -0
- package/node_modules/@VibeCodePilot/planner/package.json +19 -0
- package/node_modules/@VibeCodePilot/promoter/dist/index.d.ts +11 -0
- package/node_modules/@VibeCodePilot/promoter/dist/index.d.ts.map +1 -0
- package/node_modules/@VibeCodePilot/promoter/dist/index.js +117 -0
- package/node_modules/@VibeCodePilot/promoter/dist/index.js.map +1 -0
- package/node_modules/@VibeCodePilot/promoter/package.json +19 -0
- package/node_modules/@VibeCodePilot/prompter/dist/index.d.ts +17 -0
- package/node_modules/@VibeCodePilot/prompter/dist/index.d.ts.map +1 -0
- package/node_modules/@VibeCodePilot/prompter/dist/index.js +216 -0
- package/node_modules/@VibeCodePilot/prompter/dist/index.js.map +1 -0
- package/node_modules/@VibeCodePilot/prompter/package.json +20 -0
- package/node_modules/@VibeCodePilot/provider-ollama/dist/index.d.ts +58 -0
- package/node_modules/@VibeCodePilot/provider-ollama/dist/index.d.ts.map +1 -0
- package/node_modules/@VibeCodePilot/provider-ollama/dist/index.js +384 -0
- package/node_modules/@VibeCodePilot/provider-ollama/dist/index.js.map +1 -0
- package/node_modules/@VibeCodePilot/provider-ollama/package.json +18 -0
- package/node_modules/@VibeCodePilot/shared/dist/index.d.ts +595 -0
- package/node_modules/@VibeCodePilot/shared/dist/index.d.ts.map +1 -0
- package/node_modules/@VibeCodePilot/shared/dist/index.js +24 -0
- package/node_modules/@VibeCodePilot/shared/dist/index.js.map +1 -0
- package/node_modules/@VibeCodePilot/shared/dist/version.d.ts +14 -0
- package/node_modules/@VibeCodePilot/shared/dist/version.d.ts.map +1 -0
- package/node_modules/@VibeCodePilot/shared/dist/version.js +17 -0
- package/node_modules/@VibeCodePilot/shared/dist/version.js.map +1 -0
- package/node_modules/@VibeCodePilot/shared/package.json +24 -0
- package/node_modules/@VibeCodePilot/skill-registry/dist/index.d.ts +15 -0
- package/node_modules/@VibeCodePilot/skill-registry/dist/index.d.ts.map +1 -0
- package/node_modules/@VibeCodePilot/skill-registry/dist/index.js +126 -0
- package/node_modules/@VibeCodePilot/skill-registry/dist/index.js.map +1 -0
- package/node_modules/@VibeCodePilot/skill-registry/package.json +18 -0
- package/node_modules/@VibeCodePilot/supervisor/dist/index.d.ts +31 -0
- package/node_modules/@VibeCodePilot/supervisor/dist/index.d.ts.map +1 -0
- package/node_modules/@VibeCodePilot/supervisor/dist/index.js +219 -0
- package/node_modules/@VibeCodePilot/supervisor/dist/index.js.map +1 -0
- package/node_modules/@VibeCodePilot/supervisor/package.json +19 -0
- package/node_modules/@VibeCodePilot/task-scheduler/dist/index.d.ts +29 -0
- package/node_modules/@VibeCodePilot/task-scheduler/dist/index.d.ts.map +1 -0
- package/node_modules/@VibeCodePilot/task-scheduler/dist/index.js +128 -0
- package/node_modules/@VibeCodePilot/task-scheduler/dist/index.js.map +1 -0
- package/node_modules/@VibeCodePilot/task-scheduler/package.json +20 -0
- package/package.json +114 -4
- package/packages/agent-registry/package.json +18 -0
- package/packages/cli/bin/vibepilot.js +28 -0
- package/packages/cli/dist/config.js +143 -0
- package/packages/cli/dist/doctor.js +64 -0
- package/packages/cli/dist/index.js +260 -0
- package/packages/cli/dist/ollama.js +39 -0
- package/packages/cli/dist/pidmanager.js +153 -0
- package/packages/cli/dist/runtime.js +97 -0
- package/packages/cli/dist/servicemanager.js +227 -0
- package/packages/cli/package.json +25 -0
- package/packages/git-worktrees/package.json +18 -0
- package/packages/inference-gateway/package.json +19 -0
- package/packages/integration/package.json +20 -0
- package/packages/model-manager/package.json +19 -0
- package/packages/permissions/package.json +20 -0
- package/packages/planner/package.json +19 -0
- package/packages/promoter/package.json +19 -0
- package/packages/prompter/package.json +20 -0
- package/packages/providers/ollama/package.json +18 -0
- package/packages/shared/package.json +24 -0
- package/packages/skill-registry/package.json +18 -0
- package/packages/supervisor/package.json +19 -0
- package/packages/task-scheduler/package.json +20 -0
- package/skills/ai-ml/aiml-planning.json +22 -0
- package/skills/ai-ml/backend-planning.json +31 -0
- package/skills/ai-ml/frontend-planning.json +19 -0
- package/skills/ai-ml/ollama-local.json +11 -0
- package/skills/ai-ml/prompt-engineering.json +31 -0
- package/skills/ai-ml/task-planning.json +30 -0
- package/skills/backend/python-fastapi.json +11 -0
- package/skills/backend/ruby-rails.json +11 -0
- package/skills/backend/typescript-nodejs.json +11 -0
- package/skills/frontend/react-typescript.json +11 -0
- package/tsconfig.base.json +16 -0
|
@@ -0,0 +1,2262 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
const fastify_1 = __importDefault(require("fastify"));
|
|
40
|
+
const cors_1 = __importDefault(require("@fastify/cors"));
|
|
41
|
+
const websocket_1 = __importDefault(require("@fastify/websocket"));
|
|
42
|
+
const static_1 = __importDefault(require("@fastify/static"));
|
|
43
|
+
const path = __importStar(require("node:path"));
|
|
44
|
+
const fs = __importStar(require("node:fs"));
|
|
45
|
+
const ws_1 = require("ws");
|
|
46
|
+
const database_js_1 = require("./db/database.js");
|
|
47
|
+
const tech_detector_js_1 = require("./tech-detector.js");
|
|
48
|
+
const agentWorkspaceService_js_1 = require("./services/agentWorkspaceService.js");
|
|
49
|
+
const monitorService_js_1 = require("./services/monitorService.js");
|
|
50
|
+
const projectFlowGraph_js_1 = require("./services/projectFlowGraph.js");
|
|
51
|
+
const inference_gateway_1 = require("@VibeCodePilot/inference-gateway");
|
|
52
|
+
const skill_registry_1 = require("@VibeCodePilot/skill-registry");
|
|
53
|
+
const agent_registry_1 = require("@VibeCodePilot/agent-registry");
|
|
54
|
+
const git_worktrees_1 = require("@VibeCodePilot/git-worktrees");
|
|
55
|
+
const task_scheduler_1 = require("@VibeCodePilot/task-scheduler");
|
|
56
|
+
const supervisor_1 = require("@VibeCodePilot/supervisor");
|
|
57
|
+
const planner_1 = require("@VibeCodePilot/planner");
|
|
58
|
+
const prompter_1 = require("@VibeCodePilot/prompter");
|
|
59
|
+
const integration_1 = require("@VibeCodePilot/integration");
|
|
60
|
+
const promoter_1 = require("@VibeCodePilot/promoter");
|
|
61
|
+
const model_manager_1 = require("@VibeCodePilot/model-manager");
|
|
62
|
+
const workspace_tools_js_1 = require("./workspace-tools.js");
|
|
63
|
+
const permissions_1 = require("@VibeCodePilot/permissions");
|
|
64
|
+
const PORT = Number(process.env.VibeCodePilot_PORT || 4311);
|
|
65
|
+
const HOST = process.env.VibeCodePilot_HOST || '127.0.0.1';
|
|
66
|
+
const OLLAMA_ENDPOINT = process.env.VibeCodePilot_OLLAMA_URL || 'http://localhost:11434';
|
|
67
|
+
const DEFAULT_MODEL = process.env.VibeCodePilot_MODEL || 'gemma4:12b';
|
|
68
|
+
const DATA_DIR = process.env.VibeCodePilot_DATA_DIR || path.resolve(process.cwd(), 'data');
|
|
69
|
+
const DB_PATH = path.join(DATA_DIR, 'VibeCodePilot.db');
|
|
70
|
+
const PROJECTS_DIR = path.join(DATA_DIR, 'projects');
|
|
71
|
+
const SKILLS_DIR = [
|
|
72
|
+
process.env.VibeCodePilot_SKILLS_DIR,
|
|
73
|
+
path.resolve(__dirname, '../../../skills'), // apps/server/dist -> package root
|
|
74
|
+
path.resolve(process.cwd(), 'skills')
|
|
75
|
+
].filter((p) => !!p).find(p => fs.existsSync(p)) || path.resolve(process.cwd(), 'skills');
|
|
76
|
+
// The user's project root — never the VibeCodePilot install folder itself.
|
|
77
|
+
// Resolution:
|
|
78
|
+
// 1. VibeCodePilot_PROJECT_DIR env var
|
|
79
|
+
// 2. Walk up from this package's compiled location (__dirname) until we exit
|
|
80
|
+
// node_modules and @VibeCodePilot. When installed via npm into a consumer
|
|
81
|
+
// project, __dirname is
|
|
82
|
+
// <project-root>/node_modules/@VibeCodePilot/server/dist, so the walk lands on
|
|
83
|
+
// the project root itself — the consumer's project root, not a subfolder
|
|
84
|
+
// of this app.
|
|
85
|
+
// When running inside the VibeCodePilot monorepo (apps/server/dist), the walk
|
|
86
|
+
// lands on the VibeCodePilot repo root, which we then skip (see isVibeCodePilotRepo).
|
|
87
|
+
function resolveUserProjectRoot() {
|
|
88
|
+
// 1. Explicit override wins
|
|
89
|
+
if (process.env.VibeCodePilot_PROJECT_DIR && fs.existsSync(process.env.VibeCodePilot_PROJECT_DIR)) {
|
|
90
|
+
return path.resolve(process.env.VibeCodePilot_PROJECT_DIR);
|
|
91
|
+
}
|
|
92
|
+
const MARKER_FILES = ['package.json', '.git', 'VibeCodePilot.config.json', 'pyproject.toml', 'Cargo.toml', 'go.mod'];
|
|
93
|
+
const looksLikeProject = (dir) => MARKER_FILES.some(f => fs.existsSync(path.join(dir, f)));
|
|
94
|
+
const isVibeCodePilotRepo = (dir) => fs.existsSync(path.join(dir, 'apps', 'server')) && fs.existsSync(path.join(dir, 'packages', 'cli'));
|
|
95
|
+
// 2. Walk up from the compiled package location until we leave node_modules
|
|
96
|
+
let dir = path.resolve(__dirname);
|
|
97
|
+
let foundInstallRoot = null;
|
|
98
|
+
while (true) {
|
|
99
|
+
const parent = path.dirname(dir);
|
|
100
|
+
if (parent === dir)
|
|
101
|
+
break; // reached filesystem root
|
|
102
|
+
dir = parent;
|
|
103
|
+
if (path.basename(dir) === 'node_modules') {
|
|
104
|
+
foundInstallRoot = path.dirname(dir); // one above node_modules = project root
|
|
105
|
+
break;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (foundInstallRoot && looksLikeProject(foundInstallRoot) && !isVibeCodePilotRepo(foundInstallRoot)) {
|
|
109
|
+
return foundInstallRoot;
|
|
110
|
+
}
|
|
111
|
+
// 3. Fall back to cwd when it looks like a real consumer project
|
|
112
|
+
const cwd = process.cwd();
|
|
113
|
+
if (looksLikeProject(cwd) && !isVibeCodePilotRepo(cwd)) {
|
|
114
|
+
return path.resolve(cwd);
|
|
115
|
+
}
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
// Locate the bundled dashboard build relative to this compiled file when the
|
|
119
|
+
// package is installed as a dependency (cwd is the consumer project then).
|
|
120
|
+
function resolveDashboardDist() {
|
|
121
|
+
const candidates = [
|
|
122
|
+
process.env.VibeCodePilot_DASHBOARD_DIST,
|
|
123
|
+
path.resolve(__dirname, '../../dashboard/dist'), // apps/server/dist -> apps/dashboard/dist
|
|
124
|
+
path.resolve(process.cwd(), 'apps/dashboard/dist')
|
|
125
|
+
].filter((p) => !!p);
|
|
126
|
+
for (const candidate of candidates) {
|
|
127
|
+
if (fs.existsSync(path.join(candidate, 'index.html')))
|
|
128
|
+
return candidate;
|
|
129
|
+
}
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
async function startServer() {
|
|
133
|
+
const server = (0, fastify_1.default)({ logger: false });
|
|
134
|
+
await server.register(cors_1.default, { origin: true });
|
|
135
|
+
await server.register(websocket_1.default);
|
|
136
|
+
const dashboardDist = resolveDashboardDist();
|
|
137
|
+
if (dashboardDist) {
|
|
138
|
+
await server.register(static_1.default, {
|
|
139
|
+
root: dashboardDist,
|
|
140
|
+
prefix: '/',
|
|
141
|
+
wildcard: false
|
|
142
|
+
});
|
|
143
|
+
server.setNotFoundHandler((req, reply) => {
|
|
144
|
+
if (req.raw.url && req.raw.url.startsWith('/api')) {
|
|
145
|
+
return reply.status(404).send({ error: 'API route not found' });
|
|
146
|
+
}
|
|
147
|
+
return reply.sendFile('index.html');
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
// Initialize DB and registries
|
|
151
|
+
const db = new database_js_1.DatabaseService(DB_PATH);
|
|
152
|
+
const settings = db.getSettings();
|
|
153
|
+
// Environment configuration overrides database defaults on first boot.
|
|
154
|
+
if (process.env.VibeCodePilot_OLLAMA_URL || process.env.VibeCodePilot_MODEL) {
|
|
155
|
+
db.updateSettings({
|
|
156
|
+
ollamaEndpoint: process.env.VibeCodePilot_OLLAMA_URL || settings.ollamaEndpoint,
|
|
157
|
+
defaultModel: process.env.VibeCodePilot_MODEL || settings.defaultModel
|
|
158
|
+
});
|
|
159
|
+
// Re-read so the overrides are actually applied to the runtime objects
|
|
160
|
+
// below (updateSettings persists to the DB but does not mutate `settings`).
|
|
161
|
+
Object.assign(settings, db.getSettings());
|
|
162
|
+
}
|
|
163
|
+
const skillRegistry = new skill_registry_1.SkillRegistry();
|
|
164
|
+
skillRegistry.loadDirectory(SKILLS_DIR);
|
|
165
|
+
// Also sync loaded skills into database
|
|
166
|
+
for (const s of skillRegistry.getAllSkills()) {
|
|
167
|
+
db.saveSkill(s);
|
|
168
|
+
}
|
|
169
|
+
const agentRegistry = new agent_registry_1.AgentRegistry();
|
|
170
|
+
for (const a of agentRegistry.getAllAgents()) {
|
|
171
|
+
db.saveAgent(a);
|
|
172
|
+
}
|
|
173
|
+
const gateway = new inference_gateway_1.InferenceGateway(settings.ollamaEndpoint, settings.maxConcurrentInferences);
|
|
174
|
+
gateway.setDefaultModel(settings.defaultModel);
|
|
175
|
+
gateway.setStreamEnabled(settings.stream ?? true);
|
|
176
|
+
gateway.setAllModelThinkingLevels(settings.modelThinkingLevels || {});
|
|
177
|
+
const modelManager = new model_manager_1.ModelManager(settings.ollamaEndpoint);
|
|
178
|
+
modelManager.setActiveModel(settings.defaultModel);
|
|
179
|
+
const worktreeManager = new git_worktrees_1.GitWorktreeManager();
|
|
180
|
+
// ---- Agent Workspace service: real, persisted per-agent observability ----
|
|
181
|
+
const agentWorkspaceService = new agentWorkspaceService_js_1.AgentWorkspaceService(db, gateway);
|
|
182
|
+
agentWorkspaceService.setAgentRegistry(agentRegistry);
|
|
183
|
+
// ---- Permission Request Engine (user-controlled task execution permissions) ----
|
|
184
|
+
const permissionEngine = new permissions_1.PermissionEngine({
|
|
185
|
+
saveRequest: r => db.savePermissionRequest(r),
|
|
186
|
+
getRequest: id => db.getPermissionRequest(id) || undefined,
|
|
187
|
+
listRequests: f => db.getPermissionRequests({ projectId: f?.projectId, taskId: f?.taskId, status: f?.status }),
|
|
188
|
+
saveGrant: g => db.savePermissionGrant(g),
|
|
189
|
+
listGrants: f => db.getPermissionGrants({ projectId: f?.projectId, taskId: f?.taskId, sessionId: f?.sessionId }),
|
|
190
|
+
saveAudit: e => db.savePermissionAudit(e),
|
|
191
|
+
listAudit: f => db.getPermissionAudit({ projectId: f?.projectId, taskId: f?.taskId })
|
|
192
|
+
}, projectId => db.getProject(projectId)?.path || null, {
|
|
193
|
+
onPermissionRequested: request => {
|
|
194
|
+
broadcastEvent({ type: 'permission.request', permissionId: request.id, taskId: request.taskId, agentId: request.agentId, timestamp: request.requestedAt });
|
|
195
|
+
emitActivity(request.taskId, request.agentId, request.id, 'waiting-user', `Permission required: ${request.operation} ${request.targetPath || ''} — ${request.reason}`);
|
|
196
|
+
broadcastEvent({ type: 'task.status', taskId: request.taskId, status: 'running', timestamp: new Date().toISOString() });
|
|
197
|
+
},
|
|
198
|
+
onPermissionResolved: request => {
|
|
199
|
+
broadcastEvent({ type: 'permission.resolved', permissionId: request.id, decision: request.decision || 'deny', taskId: request.taskId, timestamp: new Date().toISOString() });
|
|
200
|
+
},
|
|
201
|
+
onPermissionExpired: request => {
|
|
202
|
+
broadcastEvent({ type: 'permission.expired', permissionId: request.id, taskId: request.taskId, timestamp: new Date().toISOString() });
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
// Connected WebSocket clients
|
|
206
|
+
const wsClients = new Set();
|
|
207
|
+
const taskStreams = new Map();
|
|
208
|
+
function broadcastEvent(event) {
|
|
209
|
+
if (event.type === 'chat.stream.chunk' && event.taskId) {
|
|
210
|
+
const existing = taskStreams.get(event.taskId);
|
|
211
|
+
const reset = existing && (existing.stage !== event.stage || existing.done);
|
|
212
|
+
const base = (!existing || reset)
|
|
213
|
+
? { text: '', thinking: '', stage: event.stage, done: false, updatedAt: event.timestamp }
|
|
214
|
+
: existing;
|
|
215
|
+
taskStreams.set(event.taskId, {
|
|
216
|
+
text: base.text + (event.chunk || ''),
|
|
217
|
+
thinking: base.thinking + (event.thinkingChunk || ''),
|
|
218
|
+
stage: event.stage || base.stage,
|
|
219
|
+
done: Boolean(event.done),
|
|
220
|
+
updatedAt: event.timestamp
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
db.logEvent(event);
|
|
224
|
+
const msg = JSON.stringify(event);
|
|
225
|
+
for (const client of wsClients) {
|
|
226
|
+
if (client.readyState === ws_1.WebSocket.OPEN) {
|
|
227
|
+
client.send(msg);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
const scheduler = new task_scheduler_1.TaskScheduler(worktreeManager, gateway, broadcastEvent);
|
|
232
|
+
const supervisor = new supervisor_1.SupervisorAgent(gateway, broadcastEvent);
|
|
233
|
+
const monitor = new monitorService_js_1.MonitorService();
|
|
234
|
+
monitor.onEvent((eventType, payload) => {
|
|
235
|
+
if (eventType === 'usage.recorded') {
|
|
236
|
+
broadcastEvent({ type: 'usage.recorded', record: payload, timestamp: new Date().toISOString() });
|
|
237
|
+
}
|
|
238
|
+
else if (eventType === 'usage.summary') {
|
|
239
|
+
broadcastEvent({ type: 'usage.summary', summary: payload, timestamp: new Date().toISOString() });
|
|
240
|
+
}
|
|
241
|
+
else if (eventType === 'context.updated') {
|
|
242
|
+
broadcastEvent({ type: 'context.updated', status: payload, timestamp: new Date().toISOString() });
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
const planner = new planner_1.PlannerAgent(gateway);
|
|
246
|
+
const prompter = new prompter_1.PrompterAgent(gateway);
|
|
247
|
+
const integrationAgent = new integration_1.IntegrationAgent(gateway, worktreeManager);
|
|
248
|
+
const promoter = new promoter_1.PromoterAgent(gateway);
|
|
249
|
+
const appendTaskLog = (task, level, message) => {
|
|
250
|
+
task.executionLogs = [...(task.executionLogs || []), { timestamp: new Date().toISOString(), level, message }].slice(-100);
|
|
251
|
+
};
|
|
252
|
+
// Append a persisted status-transition audit entry (bounded to 100).
|
|
253
|
+
const recordStatusTransition = (task, to, reason) => {
|
|
254
|
+
task.statusHistory = [
|
|
255
|
+
...(task.statusHistory || []),
|
|
256
|
+
{ from: task.status, to, at: new Date().toISOString(), reason }
|
|
257
|
+
].slice(-100);
|
|
258
|
+
task.status = to;
|
|
259
|
+
};
|
|
260
|
+
// Validated task editor helpers -------------------------------------------
|
|
261
|
+
const isValidTaskPriority = (value) => typeof value === 'string' && ['low', 'medium', 'high', 'critical'].includes(value);
|
|
262
|
+
const toStringList = (value) => Array.isArray(value) ? value.filter((v) => typeof v === 'string' && v.trim().length > 0).map(v => v.trim()) : [];
|
|
263
|
+
// Reject dependency updates that would reference missing tasks or create a
|
|
264
|
+
// dependency cycle for the task being edited.
|
|
265
|
+
const validateDependencies = (taskId, dependencies, allTasks) => {
|
|
266
|
+
if (dependencies.includes(taskId))
|
|
267
|
+
return 'A task cannot depend on itself.';
|
|
268
|
+
for (const depId of dependencies) {
|
|
269
|
+
if (!allTasks.some(t => t.id === depId))
|
|
270
|
+
return `Dependency task not found: ${depId}`;
|
|
271
|
+
}
|
|
272
|
+
// Cycle detection over the dependency graph.
|
|
273
|
+
const graph = new Map();
|
|
274
|
+
for (const t of allTasks)
|
|
275
|
+
graph.set(t.id, t.id === taskId ? dependencies : (t.dependencies || []));
|
|
276
|
+
const visiting = new Set();
|
|
277
|
+
const visited = new Set();
|
|
278
|
+
const hasCycle = (node) => {
|
|
279
|
+
if (visiting.has(node))
|
|
280
|
+
return true;
|
|
281
|
+
if (visited.has(node))
|
|
282
|
+
return false;
|
|
283
|
+
visiting.add(node);
|
|
284
|
+
for (const next of graph.get(node) || [])
|
|
285
|
+
if (hasCycle(next))
|
|
286
|
+
return true;
|
|
287
|
+
visiting.delete(node);
|
|
288
|
+
visited.add(node);
|
|
289
|
+
return false;
|
|
290
|
+
};
|
|
291
|
+
return hasCycle(taskId) ? 'The requested dependencies would create a dependency cycle.' : null;
|
|
292
|
+
};
|
|
293
|
+
// Live execution registry + cancellation tokens.
|
|
294
|
+
const runningExecutions = new Set();
|
|
295
|
+
const cancelledTasks = new Set();
|
|
296
|
+
class TaskCancelledError extends Error {
|
|
297
|
+
constructor(message = 'Task was cancelled during execution.') { super(message); this.name = 'TaskCancelledError'; }
|
|
298
|
+
}
|
|
299
|
+
const isCancelled = (taskId) => cancelledTasks.has(taskId);
|
|
300
|
+
const publishTask = (task) => {
|
|
301
|
+
db.saveTask(task);
|
|
302
|
+
scheduler.loadTasks([task]);
|
|
303
|
+
broadcastEvent({ type: 'task.status', taskId: task.id, status: task.status, timestamp: new Date().toISOString() });
|
|
304
|
+
};
|
|
305
|
+
const isTaskStatus = (value) => typeof value === 'string' && ['proposed', 'planned', 'prompting', 'ready', 'running', 'waiting_permission', 'blocked', 'completed', 'failed', 'cancelled'].includes(value);
|
|
306
|
+
// Sync existing tasks to scheduler
|
|
307
|
+
const allTasksAtStartup = db.getTasks();
|
|
308
|
+
// Duplicate-execution protection across restarts: any task recorded as
|
|
309
|
+
// 'running' with no live execution (the process restarted) is marked failed.
|
|
310
|
+
for (const t of allTasksAtStartup) {
|
|
311
|
+
if (t.status === 'running') {
|
|
312
|
+
recordStatusTransition(t, 'failed', 'Server restart while running');
|
|
313
|
+
t.error = 'Execution interrupted by server restart.';
|
|
314
|
+
t.completedAt = new Date().toISOString();
|
|
315
|
+
t.updatedAt = t.completedAt;
|
|
316
|
+
appendTaskLog(t, 'error', 'Execution interrupted by server restart; marked failed to prevent duplicate execution.');
|
|
317
|
+
recordStatusTransition(t, 'failed', 'Server restart while running');
|
|
318
|
+
db.saveTask(t);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
scheduler.loadTasks(db.getTasks());
|
|
322
|
+
// WebSocket route
|
|
323
|
+
server.get('/ws', { websocket: true }, (socket, req) => {
|
|
324
|
+
wsClients.add(socket);
|
|
325
|
+
socket.send(JSON.stringify({
|
|
326
|
+
type: 'system.log',
|
|
327
|
+
level: 'info',
|
|
328
|
+
message: 'Connected to VibeCodePilot real-time WebSocket event bus',
|
|
329
|
+
timestamp: new Date().toISOString()
|
|
330
|
+
}));
|
|
331
|
+
socket.on('close', () => {
|
|
332
|
+
wsClients.delete(socket);
|
|
333
|
+
});
|
|
334
|
+
});
|
|
335
|
+
// REST API Routes
|
|
336
|
+
// Health
|
|
337
|
+
server.get('/api/health', async () => {
|
|
338
|
+
const status = await gateway.checkStatus();
|
|
339
|
+
return {
|
|
340
|
+
status: 'ok',
|
|
341
|
+
timestamp: new Date().toISOString(),
|
|
342
|
+
ollama: status,
|
|
343
|
+
activeProjectsCount: db.getProjects().length,
|
|
344
|
+
activeTasksCount: db.getTasks().filter(t => t.status === 'running').length
|
|
345
|
+
};
|
|
346
|
+
});
|
|
347
|
+
// Projects
|
|
348
|
+
server.get('/api/projects', async () => {
|
|
349
|
+
return db.getProjects();
|
|
350
|
+
});
|
|
351
|
+
// Directory browser for the local dashboard. Browsers intentionally do not
|
|
352
|
+
// reveal absolute paths from their native folder picker, so the local server
|
|
353
|
+
// supplies the directory names and paths needed to register a project.
|
|
354
|
+
server.get('/api/project-directories', async (req, reply) => {
|
|
355
|
+
const { path: requestedPath } = req.query;
|
|
356
|
+
const directory = path.resolve(requestedPath || process.cwd());
|
|
357
|
+
try {
|
|
358
|
+
if (!fs.statSync(directory).isDirectory()) {
|
|
359
|
+
return reply.status(400).send({ error: 'The selected path is not a directory.' });
|
|
360
|
+
}
|
|
361
|
+
const directories = fs.readdirSync(directory, { withFileTypes: true })
|
|
362
|
+
.filter(entry => entry.isDirectory())
|
|
363
|
+
.map(entry => ({ name: entry.name, path: path.join(directory, entry.name) }))
|
|
364
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
365
|
+
return { path: directory, parentPath: path.dirname(directory), directories };
|
|
366
|
+
}
|
|
367
|
+
catch {
|
|
368
|
+
return reply.status(400).send({ error: 'That directory could not be read.' });
|
|
369
|
+
}
|
|
370
|
+
});
|
|
371
|
+
server.post('/api/projects', async (req, reply) => {
|
|
372
|
+
const body = req.body;
|
|
373
|
+
const projectPath = path.resolve(body.path || path.join(PROJECTS_DIR, 'sample-project'));
|
|
374
|
+
if (!fs.existsSync(projectPath) || !fs.statSync(projectPath).isDirectory()) {
|
|
375
|
+
return reply.status(400).send({ error: 'Project directory does not exist or is not readable.' });
|
|
376
|
+
}
|
|
377
|
+
const existingProject = db.getProjects().find(project => path.resolve(project.path) === projectPath);
|
|
378
|
+
if (existingProject)
|
|
379
|
+
return existingProject;
|
|
380
|
+
const detectedTech = (0, tech_detector_js_1.detectTechnologies)(projectPath);
|
|
381
|
+
const project = {
|
|
382
|
+
id: body.id || `proj-${Date.now()}`,
|
|
383
|
+
name: body.name || path.basename(projectPath),
|
|
384
|
+
path: projectPath,
|
|
385
|
+
description: body.description || `Project at ${projectPath}`,
|
|
386
|
+
detectedTechnologies: body.detectedTechnologies || detectedTech,
|
|
387
|
+
assignedSpecialists: body.assignedSpecialists || [],
|
|
388
|
+
createdAt: new Date().toISOString(),
|
|
389
|
+
updatedAt: new Date().toISOString()
|
|
390
|
+
};
|
|
391
|
+
db.saveProject(project);
|
|
392
|
+
broadcastEvent({
|
|
393
|
+
type: 'system.log',
|
|
394
|
+
level: 'info',
|
|
395
|
+
message: `Project created/registered: ${project.name}`,
|
|
396
|
+
timestamp: new Date().toISOString()
|
|
397
|
+
});
|
|
398
|
+
return project;
|
|
399
|
+
});
|
|
400
|
+
server.get('/api/projects/:id', async (req, reply) => {
|
|
401
|
+
const { id } = req.params;
|
|
402
|
+
const project = db.getProject(id);
|
|
403
|
+
if (!project)
|
|
404
|
+
return reply.status(404).send({ error: 'Project not found' });
|
|
405
|
+
return project;
|
|
406
|
+
});
|
|
407
|
+
// Agents
|
|
408
|
+
server.get('/api/agents', async () => {
|
|
409
|
+
return agentRegistry.getAllAgents();
|
|
410
|
+
});
|
|
411
|
+
server.post('/api/agents', async (req) => {
|
|
412
|
+
const agent = req.body;
|
|
413
|
+
agentRegistry.registerAgent(agent);
|
|
414
|
+
db.saveAgent(agent);
|
|
415
|
+
return agent;
|
|
416
|
+
});
|
|
417
|
+
// ---- Agent Workspaces: real per-agent observability data ----
|
|
418
|
+
server.get('/api/agent-workspaces', async () => {
|
|
419
|
+
return agentWorkspaceService.getGrid();
|
|
420
|
+
});
|
|
421
|
+
server.get('/api/agent-workspaces/:agentId', async (req, reply) => {
|
|
422
|
+
const { agentId } = req.params;
|
|
423
|
+
const snapshot = await agentWorkspaceService.getSnapshot(agentId);
|
|
424
|
+
if (!snapshot)
|
|
425
|
+
return reply.status(404).send({ error: 'Agent not found' });
|
|
426
|
+
return snapshot;
|
|
427
|
+
});
|
|
428
|
+
// Skills
|
|
429
|
+
server.get('/api/skills', async () => {
|
|
430
|
+
return skillRegistry.getAllSkills();
|
|
431
|
+
});
|
|
432
|
+
server.post('/api/skills', async (req) => {
|
|
433
|
+
const skill = req.body;
|
|
434
|
+
skillRegistry.registerSkill(skill);
|
|
435
|
+
db.saveSkill(skill);
|
|
436
|
+
return skill;
|
|
437
|
+
});
|
|
438
|
+
// Tasks
|
|
439
|
+
server.get('/api/tasks', async (req) => {
|
|
440
|
+
const { projectId, includeArchived } = req.query;
|
|
441
|
+
const tasks = db.getTasks(projectId);
|
|
442
|
+
return includeArchived === 'true' ? tasks : tasks.filter(t => !t.archived);
|
|
443
|
+
});
|
|
444
|
+
server.post('/api/tasks', async (req, reply) => {
|
|
445
|
+
const body = req.body;
|
|
446
|
+
if (!body.projectId || !body.title?.trim() || !body.description?.trim()) {
|
|
447
|
+
return reply.status(400).send({ error: 'projectId, title, and description are required.' });
|
|
448
|
+
}
|
|
449
|
+
if (!db.getProject(body.projectId))
|
|
450
|
+
return reply.status(400).send({ error: 'Task project not found.' });
|
|
451
|
+
const now = new Date().toISOString();
|
|
452
|
+
const sessionId = body.sessionId || `session-task-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
|
|
453
|
+
if (!body.sessionId) {
|
|
454
|
+
db.saveChatSession({ id: sessionId, projectId: body.projectId, title: `Task Board: ${body.title.trim().slice(0, 40)}`, createdAt: now, updatedAt: now });
|
|
455
|
+
}
|
|
456
|
+
const task = {
|
|
457
|
+
id: body.id || `task-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
|
|
458
|
+
projectId: body.projectId,
|
|
459
|
+
sessionId,
|
|
460
|
+
title: body.title.trim(),
|
|
461
|
+
description: body.description.trim(),
|
|
462
|
+
priority: body.priority || 'medium',
|
|
463
|
+
assignedAgentId: body.assignedAgentId || 'specialist-dynamic',
|
|
464
|
+
requiredSkills: body.requiredSkills || [],
|
|
465
|
+
scope: body.scope || { affectedFiles: [] },
|
|
466
|
+
dependencies: body.dependencies || [],
|
|
467
|
+
acceptanceCriteria: body.acceptanceCriteria || [],
|
|
468
|
+
status: isTaskStatus(body.status) ? body.status : 'planned',
|
|
469
|
+
relatedFiles: body.relatedFiles || body.scope?.affectedFiles || [],
|
|
470
|
+
executionLogs: [{ timestamp: now, level: 'info', message: 'Task created.' }],
|
|
471
|
+
statusHistory: [{ from: null, to: isTaskStatus(body.status) ? body.status : 'planned', at: now, reason: 'Task created.' }],
|
|
472
|
+
createdAt: body.createdAt || now,
|
|
473
|
+
updatedAt: now
|
|
474
|
+
};
|
|
475
|
+
db.saveTask(task);
|
|
476
|
+
db.saveChatMessage({ id: `msg-${Date.now()}-task-created`, sessionId, sender: 'supervisor', text: `Task created from the Task Board: **${task.title}**`, timestamp: now });
|
|
477
|
+
scheduler.loadTasks([task]);
|
|
478
|
+
broadcastEvent({
|
|
479
|
+
type: 'task.created',
|
|
480
|
+
taskId: task.id,
|
|
481
|
+
task,
|
|
482
|
+
timestamp: new Date().toISOString()
|
|
483
|
+
});
|
|
484
|
+
broadcastEvent({ type: 'chat.message.created', sessionId, messageId: `msg-${Date.now()}-task-created`, timestamp: now });
|
|
485
|
+
return task;
|
|
486
|
+
});
|
|
487
|
+
server.get('/api/tasks/:id/stream', async (req) => {
|
|
488
|
+
const { id } = req.params;
|
|
489
|
+
return {
|
|
490
|
+
stream: taskStreams.get(id) || null,
|
|
491
|
+
activities: activityHistory.get(`exec-${id}`) || []
|
|
492
|
+
};
|
|
493
|
+
});
|
|
494
|
+
server.patch('/api/tasks/:id', async (req, reply) => {
|
|
495
|
+
const { id } = req.params;
|
|
496
|
+
const task = db.getTask(id);
|
|
497
|
+
if (!task)
|
|
498
|
+
return reply.status(404).send({ error: 'Task not found' });
|
|
499
|
+
if (task.status === 'running')
|
|
500
|
+
return reply.status(409).send({ error: 'A running task cannot be edited. Cancel it first.' });
|
|
501
|
+
if (['completed', 'failed', 'cancelled'].includes(task.status))
|
|
502
|
+
return reply.status(409).send({ error: `A ${task.status} task cannot be edited. Retry it first.` });
|
|
503
|
+
const body = req.body;
|
|
504
|
+
if (body.priority !== undefined && !isValidTaskPriority(body.priority))
|
|
505
|
+
return reply.status(400).send({ error: 'Invalid task priority.' });
|
|
506
|
+
if (body.dependencies !== undefined) {
|
|
507
|
+
const dependencies = toStringList(body.dependencies);
|
|
508
|
+
const cycleError = validateDependencies(task.id, dependencies, db.getTasks());
|
|
509
|
+
if (cycleError)
|
|
510
|
+
return reply.status(400).send({ error: cycleError });
|
|
511
|
+
body.dependencies = dependencies;
|
|
512
|
+
}
|
|
513
|
+
if (body.acceptanceCriteria !== undefined)
|
|
514
|
+
body.acceptanceCriteria = toStringList(body.acceptanceCriteria);
|
|
515
|
+
if (body.relatedFiles !== undefined)
|
|
516
|
+
body.relatedFiles = toStringList(body.relatedFiles);
|
|
517
|
+
if (body.scope?.affectedFiles !== undefined)
|
|
518
|
+
body.scope = { ...body.scope, affectedFiles: toStringList(body.scope.affectedFiles) };
|
|
519
|
+
if (body.title !== undefined && !body.title.trim())
|
|
520
|
+
return reply.status(400).send({ error: 'Task title cannot be empty.' });
|
|
521
|
+
if (body.description !== undefined && !body.description.trim())
|
|
522
|
+
return reply.status(400).send({ error: 'Task description cannot be empty.' });
|
|
523
|
+
Object.assign(task, {
|
|
524
|
+
title: body.title?.trim() ?? task.title,
|
|
525
|
+
description: body.description?.trim() ?? task.description,
|
|
526
|
+
priority: body.priority ?? task.priority,
|
|
527
|
+
assignedAgentId: body.assignedAgentId ?? task.assignedAgentId,
|
|
528
|
+
dependencies: body.dependencies ?? task.dependencies,
|
|
529
|
+
acceptanceCriteria: body.acceptanceCriteria ?? task.acceptanceCriteria,
|
|
530
|
+
scope: body.scope ?? task.scope,
|
|
531
|
+
relatedFiles: body.relatedFiles ?? body.scope?.affectedFiles ?? task.relatedFiles,
|
|
532
|
+
updatedAt: new Date().toISOString()
|
|
533
|
+
});
|
|
534
|
+
appendTaskLog(task, 'info', 'Task details updated.');
|
|
535
|
+
publishTask(task);
|
|
536
|
+
return task;
|
|
537
|
+
});
|
|
538
|
+
// Archive or remove a task
|
|
539
|
+
server.post('/api/tasks/:id/archive', async (req, reply) => {
|
|
540
|
+
const { id } = req.params;
|
|
541
|
+
const task = db.getTask(id);
|
|
542
|
+
if (!task)
|
|
543
|
+
return reply.status(404).send({ error: 'Task not found' });
|
|
544
|
+
task.archived = true;
|
|
545
|
+
task.updatedAt = new Date().toISOString();
|
|
546
|
+
appendTaskLog(task, 'info', 'Task archived.');
|
|
547
|
+
publishTask(task);
|
|
548
|
+
return task;
|
|
549
|
+
});
|
|
550
|
+
server.post('/api/tasks/:id/unarchive', async (req, reply) => {
|
|
551
|
+
const { id } = req.params;
|
|
552
|
+
const task = db.getTask(id);
|
|
553
|
+
if (!task)
|
|
554
|
+
return reply.status(404).send({ error: 'Task not found' });
|
|
555
|
+
task.archived = false;
|
|
556
|
+
task.updatedAt = new Date().toISOString();
|
|
557
|
+
appendTaskLog(task, 'info', 'Task restored from archive.');
|
|
558
|
+
publishTask(task);
|
|
559
|
+
return task;
|
|
560
|
+
});
|
|
561
|
+
server.post('/api/tasks/:id/cancel', async (req, reply) => {
|
|
562
|
+
const { id } = req.params;
|
|
563
|
+
const task = db.getTask(id);
|
|
564
|
+
if (!task)
|
|
565
|
+
return reply.status(404).send({ error: 'Task not found' });
|
|
566
|
+
if (['completed', 'failed', 'cancelled'].includes(task.status))
|
|
567
|
+
return reply.status(409).send({ error: `Cannot cancel a ${task.status} task.` });
|
|
568
|
+
// Signal any live execution to stop at the next checkpoint; the executor
|
|
569
|
+
// throws TaskCancelledError so no further model/tool stages run.
|
|
570
|
+
cancelledTasks.add(task.id);
|
|
571
|
+
const pending = Array.from(pendingQuestions.values()).find(q => q.taskId === task.id);
|
|
572
|
+
if (pending) {
|
|
573
|
+
pendingQuestions.delete(pending.id);
|
|
574
|
+
broadcastEvent({ type: 'agent.question.resolved', questionId: pending.id, answer: '__cancelled__', timestamp: new Date().toISOString() });
|
|
575
|
+
pending.resolve?.('__cancelled__');
|
|
576
|
+
}
|
|
577
|
+
// Expire any permission request waiting on this (now invalid) execution context.
|
|
578
|
+
for (const pr of db.getPermissionRequests({ taskId: task.id, status: 'pending' })) {
|
|
579
|
+
permissionEngine.expireRequest(pr.id, 'Task cancelled while waiting for permission.');
|
|
580
|
+
}
|
|
581
|
+
permissionEngine.revokeGrants({ taskId: task.id, sessionId: task.sessionId });
|
|
582
|
+
recordStatusTransition(task, 'cancelled', 'Cancelled by user.');
|
|
583
|
+
task.completedAt = new Date().toISOString();
|
|
584
|
+
task.updatedAt = task.completedAt;
|
|
585
|
+
task.error = 'Cancelled by user.';
|
|
586
|
+
appendTaskLog(task, 'info', 'Task cancelled by user.');
|
|
587
|
+
publishTask(task);
|
|
588
|
+
return task;
|
|
589
|
+
});
|
|
590
|
+
server.post('/api/tasks/:id/retry', async (req, reply) => {
|
|
591
|
+
const { id } = req.params;
|
|
592
|
+
const task = db.getTask(id);
|
|
593
|
+
if (!task)
|
|
594
|
+
return reply.status(404).send({ error: 'Task not found' });
|
|
595
|
+
if (!['failed', 'blocked', 'cancelled'].includes(task.status))
|
|
596
|
+
return reply.status(409).send({ error: 'Only failed, blocked, or cancelled tasks can be retried.' });
|
|
597
|
+
if (runningExecutions.has(task.id))
|
|
598
|
+
return reply.status(409).send({ error: 'Task execution is still active.' });
|
|
599
|
+
cancelledTasks.delete(task.id);
|
|
600
|
+
recordStatusTransition(task, task.generatedPromptId ? 'ready' : 'planned', 'Retry requested.');
|
|
601
|
+
task.error = undefined;
|
|
602
|
+
task.completedAt = undefined;
|
|
603
|
+
task.updatedAt = new Date().toISOString();
|
|
604
|
+
appendTaskLog(task, 'info', 'Task queued for retry.');
|
|
605
|
+
publishTask(task);
|
|
606
|
+
return task;
|
|
607
|
+
});
|
|
608
|
+
// ---- Proposed plan review gate ----
|
|
609
|
+
// User approves a proposed task: it becomes planned and is queued for the
|
|
610
|
+
// Prompter. No new task is created.
|
|
611
|
+
server.post('/api/tasks/:id/approve', async (req, reply) => {
|
|
612
|
+
const { id } = req.params;
|
|
613
|
+
const task = db.getTask(id);
|
|
614
|
+
if (!task)
|
|
615
|
+
return reply.status(404).send({ error: 'Task not found' });
|
|
616
|
+
if (task.status !== 'proposed')
|
|
617
|
+
return reply.status(409).send({ error: 'Only proposed tasks can be approved.' });
|
|
618
|
+
const project = db.getProject(task.projectId);
|
|
619
|
+
if (!project)
|
|
620
|
+
return reply.status(400).send({ error: 'Project for this task no longer exists.' });
|
|
621
|
+
recordStatusTransition(task, 'planned', 'Plan approved by user.');
|
|
622
|
+
task.updatedAt = new Date().toISOString();
|
|
623
|
+
appendTaskLog(task, 'info', 'Proposed plan approved — compiling specialist prompt.');
|
|
624
|
+
publishTask(task);
|
|
625
|
+
// Compile the specialist prompt now that the plan is approved.
|
|
626
|
+
try {
|
|
627
|
+
const assignedAgent = agentRegistry.getAgent(task.assignedAgentId) || agentRegistry.getAgentsByRole('specialist')[0] || agentRegistry.getAllAgents()[0];
|
|
628
|
+
const relevantSkills = skillRegistry.resolveSkills(project.detectedTechnologies, task.requiredSkills);
|
|
629
|
+
const autoApprove = db.getSettings().autoApproveRoutinePrompts;
|
|
630
|
+
const prompt = await prompter.compilePrompt(task, project, assignedAgent, relevantSkills, autoApprove);
|
|
631
|
+
emitStage('prompter', 'done', { sessionId: task.sessionId, agentId: assignedAgent?.id, detail: prompt.id });
|
|
632
|
+
task.generatedPromptId = prompt.id;
|
|
633
|
+
recordStatusTransition(task, prompt.isApproved ? 'ready' : 'prompting', 'Specialist prompt compiled after approval.');
|
|
634
|
+
db.saveTask(task);
|
|
635
|
+
db.savePrompt(prompt);
|
|
636
|
+
publishTask(task);
|
|
637
|
+
}
|
|
638
|
+
catch (err) {
|
|
639
|
+
appendTaskLog(task, 'error', `Prompt compilation failed: ${err.message}`);
|
|
640
|
+
db.saveTask(task);
|
|
641
|
+
// The task stays planned; the user can retry compilation via execute.
|
|
642
|
+
}
|
|
643
|
+
return db.getTask(id);
|
|
644
|
+
});
|
|
645
|
+
// User rejects the proposal: the SAME task is re-designed in place by the
|
|
646
|
+
// Planner using the user's feedback. The task keeps its identity.
|
|
647
|
+
server.post('/api/tasks/:id/review-again', async (req, reply) => {
|
|
648
|
+
const { id } = req.params;
|
|
649
|
+
const feedback = String(req.body?.feedback || '').trim();
|
|
650
|
+
const task = db.getTask(id);
|
|
651
|
+
if (!task)
|
|
652
|
+
return reply.status(404).send({ error: 'Task not found' });
|
|
653
|
+
if (task.status !== 'proposed')
|
|
654
|
+
return reply.status(409).send({ error: 'Only proposed tasks can be re-reviewed.' });
|
|
655
|
+
const project = db.getProject(task.projectId);
|
|
656
|
+
if (!project)
|
|
657
|
+
return reply.status(400).send({ error: 'Project for this task no longer exists.' });
|
|
658
|
+
emitStage('planner', 'active', { sessionId: task.sessionId, agentId: 'agent-planner', detail: `Redesigning: ${task.title}` });
|
|
659
|
+
emitActivity(task.id, 'agent-planner', `review-${task.id}`, 'thinking', `Redesigning plan with your feedback: ${feedback || 'none provided'}`);
|
|
660
|
+
try {
|
|
661
|
+
const replan = await planner.createPlan(feedback ? `${task.description || task.title}. USER REVIEW FEEDBACK (apply it exactly): ${feedback}` : task.description || task.title, project, agentRegistry.getAllAgents(), skillRegistry.getAllSkills());
|
|
662
|
+
// Re-design in place: adopt the first proposed task's content but KEEP
|
|
663
|
+
// this task's id/session so history and chat stay linked.
|
|
664
|
+
const replacement = replan.tasks[0];
|
|
665
|
+
if (!replacement)
|
|
666
|
+
throw new Error('The Planner returned no redesigned task.');
|
|
667
|
+
replacement.id = task.id;
|
|
668
|
+
replacement.projectId = task.projectId;
|
|
669
|
+
replacement.sessionId = task.sessionId;
|
|
670
|
+
replacement.createdAt = task.createdAt;
|
|
671
|
+
recordStatusTransition(replacement, 'proposed', `Plan redesigned after review${feedback ? `: ${feedback.slice(0, 120)}` : '.'}`);
|
|
672
|
+
appendTaskLog(replacement, 'info', 'Task re-designed by the Planner after user review.');
|
|
673
|
+
db.saveTask(replacement);
|
|
674
|
+
scheduler.loadTasks([replacement]);
|
|
675
|
+
publishTask(replacement);
|
|
676
|
+
emitStage('planner', 'done', { sessionId: task.sessionId, agentId: 'agent-planner', detail: replacement.title });
|
|
677
|
+
return replacement;
|
|
678
|
+
}
|
|
679
|
+
catch (err) {
|
|
680
|
+
emitStage('planner', 'failed', { sessionId: task.sessionId, agentId: 'agent-planner', detail: err.message });
|
|
681
|
+
emitActivity(task.id, 'agent-planner', `review-${task.id}`, 'failed', `Redesign failed: ${err.message}`);
|
|
682
|
+
return reply.status(502).send({ error: `Planner redesign failed: ${err.message}` });
|
|
683
|
+
}
|
|
684
|
+
});
|
|
685
|
+
server.delete('/api/tasks/:id', async (req, reply) => {
|
|
686
|
+
const { id } = req.params;
|
|
687
|
+
const task = db.getTask(id);
|
|
688
|
+
if (!task)
|
|
689
|
+
return reply.status(404).send({ error: 'Task not found' });
|
|
690
|
+
db.deleteTask(id);
|
|
691
|
+
broadcastEvent({ type: 'system.log', level: 'info', message: `Task removed: ${task.title}`, timestamp: new Date().toISOString() });
|
|
692
|
+
return { success: true, taskId: id };
|
|
693
|
+
});
|
|
694
|
+
// Prompts
|
|
695
|
+
server.get('/api/prompts', async (req) => {
|
|
696
|
+
const { projectId } = req.query;
|
|
697
|
+
return db.getPrompts(projectId);
|
|
698
|
+
});
|
|
699
|
+
server.post('/api/prompts/:id/approve', async (req, reply) => {
|
|
700
|
+
const { id } = req.params;
|
|
701
|
+
const prompts = db.getPrompts();
|
|
702
|
+
const prompt = prompts.find(p => p.id === id);
|
|
703
|
+
if (!prompt)
|
|
704
|
+
return reply.status(404).send({ error: 'Prompt not found' });
|
|
705
|
+
prompt.isApproved = true;
|
|
706
|
+
prompt.status = 'approved';
|
|
707
|
+
prompt.updatedAt = new Date().toISOString();
|
|
708
|
+
db.savePrompt(prompt);
|
|
709
|
+
broadcastEvent({
|
|
710
|
+
type: 'prompt.validated',
|
|
711
|
+
taskId: prompt.taskId,
|
|
712
|
+
promptId: prompt.id,
|
|
713
|
+
isValid: true,
|
|
714
|
+
timestamp: new Date().toISOString()
|
|
715
|
+
});
|
|
716
|
+
return prompt;
|
|
717
|
+
});
|
|
718
|
+
server.post('/api/prompts/:id/reject', async (req, reply) => {
|
|
719
|
+
const { id } = req.params;
|
|
720
|
+
const prompts = db.getPrompts();
|
|
721
|
+
const prompt = prompts.find(p => p.id === id);
|
|
722
|
+
if (!prompt)
|
|
723
|
+
return reply.status(404).send({ error: 'Prompt not found' });
|
|
724
|
+
prompt.isApproved = false;
|
|
725
|
+
prompt.status = 'draft';
|
|
726
|
+
prompt.updatedAt = new Date().toISOString();
|
|
727
|
+
db.savePrompt(prompt);
|
|
728
|
+
return prompt;
|
|
729
|
+
});
|
|
730
|
+
// Approvals
|
|
731
|
+
server.get('/api/approvals', async (req) => {
|
|
732
|
+
const { projectId } = req.query;
|
|
733
|
+
return db.getApprovals(projectId);
|
|
734
|
+
});
|
|
735
|
+
server.post('/api/approvals/:id/resolve', async (req, reply) => {
|
|
736
|
+
const { id } = req.params;
|
|
737
|
+
const { status, comments } = req.body;
|
|
738
|
+
const approvals = db.getApprovals();
|
|
739
|
+
const app = approvals.find(a => a.id === id);
|
|
740
|
+
if (!app)
|
|
741
|
+
return reply.status(404).send({ error: 'Approval request not found' });
|
|
742
|
+
app.status = status;
|
|
743
|
+
app.reviewedAt = new Date().toISOString();
|
|
744
|
+
app.comments = comments;
|
|
745
|
+
db.saveApproval(app);
|
|
746
|
+
broadcastEvent({
|
|
747
|
+
type: 'approval.resolved',
|
|
748
|
+
approvalId: app.id,
|
|
749
|
+
status: app.status,
|
|
750
|
+
timestamp: new Date().toISOString()
|
|
751
|
+
});
|
|
752
|
+
return app;
|
|
753
|
+
});
|
|
754
|
+
// Models
|
|
755
|
+
server.get('/api/models', async () => {
|
|
756
|
+
return gateway.checkStatus();
|
|
757
|
+
});
|
|
758
|
+
server.post('/api/models/active', async (req) => {
|
|
759
|
+
const { model, agentId } = req.body;
|
|
760
|
+
if (agentId) {
|
|
761
|
+
gateway.setAgentModel(agentId, model);
|
|
762
|
+
agentRegistry.updateAgentModel(agentId, model);
|
|
763
|
+
}
|
|
764
|
+
else {
|
|
765
|
+
gateway.setDefaultModel(model);
|
|
766
|
+
modelManager.setActiveModel(model);
|
|
767
|
+
db.updateSettings({ defaultModel: model });
|
|
768
|
+
}
|
|
769
|
+
broadcastEvent({
|
|
770
|
+
type: 'model.changed',
|
|
771
|
+
modelId: model,
|
|
772
|
+
timestamp: new Date().toISOString()
|
|
773
|
+
});
|
|
774
|
+
return { success: true, model, agentId };
|
|
775
|
+
});
|
|
776
|
+
// Delete a locally installed model (destructive — the dashboard asks for
|
|
777
|
+
// confirmation before calling this). Refuses to remove a model that is not
|
|
778
|
+
// installed so the error surface stays honest.
|
|
779
|
+
server.delete('/api/models/:name', async (req, reply) => {
|
|
780
|
+
const { name } = req.params;
|
|
781
|
+
const status = await gateway.checkStatus();
|
|
782
|
+
if (!status.online) {
|
|
783
|
+
return reply.status(503).send({ error: 'Ollama daemon is offline — the model cannot be removed.' });
|
|
784
|
+
}
|
|
785
|
+
const installed = status.installedModels.find(m => m.name === name);
|
|
786
|
+
if (!installed) {
|
|
787
|
+
return reply.status(404).send({ error: `Model "${name}" is not installed on this daemon.` });
|
|
788
|
+
}
|
|
789
|
+
try {
|
|
790
|
+
const result = await modelManager.deleteModel(name);
|
|
791
|
+
broadcastEvent({
|
|
792
|
+
type: 'model.changed',
|
|
793
|
+
modelId: result.activeModelCleared ? modelManager.getActiveModel() : name,
|
|
794
|
+
timestamp: new Date().toISOString()
|
|
795
|
+
});
|
|
796
|
+
broadcastEvent({
|
|
797
|
+
type: 'system.log',
|
|
798
|
+
level: 'info',
|
|
799
|
+
message: `Model removed: ${name}${result.activeModelCleared ? ' (it was the active model — selection reset)' : ''}`,
|
|
800
|
+
timestamp: new Date().toISOString()
|
|
801
|
+
});
|
|
802
|
+
return { success: true, ...result };
|
|
803
|
+
}
|
|
804
|
+
catch (err) {
|
|
805
|
+
return reply.status(502).send({ error: err.message || 'Model deletion failed.' });
|
|
806
|
+
}
|
|
807
|
+
});
|
|
808
|
+
server.post('/api/models/pull', async (req) => {
|
|
809
|
+
const { model } = req.body;
|
|
810
|
+
// Trigger pull in background
|
|
811
|
+
modelManager.pullModel(model).catch(err => {
|
|
812
|
+
broadcastEvent({
|
|
813
|
+
type: 'system.log',
|
|
814
|
+
level: 'error',
|
|
815
|
+
message: `Model pull failed for ${model}: ${err.message}`,
|
|
816
|
+
timestamp: new Date().toISOString()
|
|
817
|
+
});
|
|
818
|
+
});
|
|
819
|
+
return { success: true, message: `Pull initiated for ${model}` };
|
|
820
|
+
});
|
|
821
|
+
// Live pull progress. With no ?model= given, returns every known pull so the
|
|
822
|
+
// dashboard can render progress bars for all in-flight/completed pulls.
|
|
823
|
+
server.get('/api/models/pull-progress', async (req) => {
|
|
824
|
+
const { model } = req.query;
|
|
825
|
+
if (model) {
|
|
826
|
+
return modelManager.getPullProgress(model) || { model, status: 'idle', message: 'No pull recorded for this model.', percentage: 0, bytesPerSecond: null, speed: null, averageBytesPerSecond: null };
|
|
827
|
+
}
|
|
828
|
+
return { pulls: modelManager.getAllPullProgress() };
|
|
829
|
+
});
|
|
830
|
+
// Settings
|
|
831
|
+
server.get('/api/settings', async () => {
|
|
832
|
+
return db.getSettings();
|
|
833
|
+
});
|
|
834
|
+
server.post('/api/settings', async (req) => {
|
|
835
|
+
const newSettings = req.body;
|
|
836
|
+
db.updateSettings(newSettings);
|
|
837
|
+
if (newSettings.ollamaEndpoint) {
|
|
838
|
+
gateway.setEndpoint(newSettings.ollamaEndpoint);
|
|
839
|
+
modelManager.setEndpoint(newSettings.ollamaEndpoint);
|
|
840
|
+
}
|
|
841
|
+
if (newSettings.maxConcurrentInferences) {
|
|
842
|
+
gateway.setMaxConcurrency(newSettings.maxConcurrentInferences);
|
|
843
|
+
}
|
|
844
|
+
if (newSettings.defaultModel) {
|
|
845
|
+
gateway.setDefaultModel(newSettings.defaultModel);
|
|
846
|
+
modelManager.setActiveModel(newSettings.defaultModel);
|
|
847
|
+
}
|
|
848
|
+
if (newSettings.stream !== undefined) {
|
|
849
|
+
gateway.setStreamEnabled(Boolean(newSettings.stream));
|
|
850
|
+
}
|
|
851
|
+
if (newSettings.modelThinkingLevels !== undefined) {
|
|
852
|
+
gateway.setAllModelThinkingLevels(newSettings.modelThinkingLevels || {});
|
|
853
|
+
}
|
|
854
|
+
return db.getSettings();
|
|
855
|
+
});
|
|
856
|
+
// ---- Conversational Supervisor Mode: sessions, history, thinking, quick actions ----
|
|
857
|
+
// Persisted thinking response from Ollama (`` tags)
|
|
858
|
+
function extractThinking(raw) {
|
|
859
|
+
const match = raw.match(/<think>([\s\S]*?)<\/think>/);
|
|
860
|
+
if (!match)
|
|
861
|
+
return { response: raw.trim() };
|
|
862
|
+
return {
|
|
863
|
+
response: raw.replace(/<think>[\s\S]*?<\/think>/g, '').trim(),
|
|
864
|
+
thinking: match[1].trim()
|
|
865
|
+
};
|
|
866
|
+
}
|
|
867
|
+
// List chat sessions (optionally per project)
|
|
868
|
+
server.get('/api/chat/sessions', async (req) => {
|
|
869
|
+
const { projectId } = req.query;
|
|
870
|
+
return db.getChatSessions(projectId);
|
|
871
|
+
});
|
|
872
|
+
// Create a new session (session persists until the user starts a new one)
|
|
873
|
+
server.post('/api/chat/sessions', async (req) => {
|
|
874
|
+
const { projectId, title } = req.body;
|
|
875
|
+
const now = new Date().toISOString();
|
|
876
|
+
const session = {
|
|
877
|
+
id: `session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
|
|
878
|
+
projectId,
|
|
879
|
+
title: title || 'New conversation',
|
|
880
|
+
createdAt: now,
|
|
881
|
+
updatedAt: now
|
|
882
|
+
};
|
|
883
|
+
db.saveChatSession(session);
|
|
884
|
+
return session;
|
|
885
|
+
});
|
|
886
|
+
// Rename a session
|
|
887
|
+
server.patch('/api/chat/sessions/:id', async (req, reply) => {
|
|
888
|
+
const { id } = req.params;
|
|
889
|
+
const session = db.getChatSession(id);
|
|
890
|
+
if (!session)
|
|
891
|
+
return reply.status(404).send({ error: 'Chat session not found' });
|
|
892
|
+
const { title } = req.body;
|
|
893
|
+
if (!title?.trim())
|
|
894
|
+
return reply.status(400).send({ error: 'Title is required.' });
|
|
895
|
+
const updated = { ...session, title: title.trim(), updatedAt: new Date().toISOString() };
|
|
896
|
+
db.saveChatSession(updated);
|
|
897
|
+
broadcastEvent({ type: 'system.log', level: 'info', message: `Session renamed: ${updated.title}`, timestamp: new Date().toISOString() });
|
|
898
|
+
return updated;
|
|
899
|
+
});
|
|
900
|
+
// Delete a session and its messages
|
|
901
|
+
server.delete('/api/chat/sessions/:id', async (req, reply) => {
|
|
902
|
+
const { id } = req.params;
|
|
903
|
+
const session = db.getChatSession(id);
|
|
904
|
+
if (!session)
|
|
905
|
+
return reply.status(404).send({ error: 'Chat session not found' });
|
|
906
|
+
db.deleteChatSession(id);
|
|
907
|
+
broadcastEvent({ type: 'system.log', level: 'info', message: `Session deleted: ${session.title}`, timestamp: new Date().toISOString() });
|
|
908
|
+
return { success: true, id };
|
|
909
|
+
});
|
|
910
|
+
// Full message history for one session
|
|
911
|
+
server.get('/api/chat/sessions/:id/messages', async (req, reply) => {
|
|
912
|
+
const { id } = req.params;
|
|
913
|
+
const session = db.getChatSession(id);
|
|
914
|
+
if (!session)
|
|
915
|
+
return reply.status(404).send({ error: 'Chat session not found' });
|
|
916
|
+
return { session, messages: db.getChatMessages(id) };
|
|
917
|
+
});
|
|
918
|
+
// Hierarchy pipeline stages — the canonical order the request flows through
|
|
919
|
+
const PIPELINE_STAGES = ['supervisor', 'planner', 'prompter', 'scheduler'];
|
|
920
|
+
const pendingPlanBySession = new Map();
|
|
921
|
+
function emitPlanningStatus(sessionId, status, opts = {}) {
|
|
922
|
+
broadcastEvent({
|
|
923
|
+
type: 'planning.status',
|
|
924
|
+
sessionId,
|
|
925
|
+
status,
|
|
926
|
+
message: opts.message,
|
|
927
|
+
questions: opts.questions,
|
|
928
|
+
taskCount: opts.taskCount,
|
|
929
|
+
timestamp: new Date().toISOString()
|
|
930
|
+
});
|
|
931
|
+
}
|
|
932
|
+
/** Materialize a completed planning result into the Task Board. */
|
|
933
|
+
function publishPlanTasks(result, sessionId) {
|
|
934
|
+
const created = [];
|
|
935
|
+
for (const t of result.tasks) {
|
|
936
|
+
t.sessionId = sessionId;
|
|
937
|
+
db.saveTask(t);
|
|
938
|
+
scheduler.loadTasks([t]);
|
|
939
|
+
created.push(t);
|
|
940
|
+
broadcastEvent({ type: 'task.created', taskId: t.id, task: t, timestamp: new Date().toISOString() });
|
|
941
|
+
}
|
|
942
|
+
return created;
|
|
943
|
+
}
|
|
944
|
+
function emitStage(stage, status, opts = {}) {
|
|
945
|
+
broadcastEvent({
|
|
946
|
+
type: 'hierarchy.stage',
|
|
947
|
+
stage,
|
|
948
|
+
status,
|
|
949
|
+
sessionId: opts.sessionId,
|
|
950
|
+
agentId: opts.agentId,
|
|
951
|
+
detail: opts.detail,
|
|
952
|
+
timestamp: new Date().toISOString()
|
|
953
|
+
});
|
|
954
|
+
}
|
|
955
|
+
const pendingQuestions = new Map();
|
|
956
|
+
// Bounded per-activity history so the hierarchy card can render what an agent
|
|
957
|
+
// has been doing over time (thinking → acting → done) rather than just the
|
|
958
|
+
// latest state.
|
|
959
|
+
const activityHistory = new Map();
|
|
960
|
+
function emitActivity(taskId, agentId, activityId, state, message) {
|
|
961
|
+
const timestamp = new Date().toISOString();
|
|
962
|
+
broadcastEvent({
|
|
963
|
+
type: 'execution.activity',
|
|
964
|
+
taskId,
|
|
965
|
+
agentId,
|
|
966
|
+
activityId,
|
|
967
|
+
state,
|
|
968
|
+
message,
|
|
969
|
+
history: activityHistory.get(activityId) || [],
|
|
970
|
+
timestamp
|
|
971
|
+
});
|
|
972
|
+
// Keep a bounded per-activity history so the hierarchy card can show what
|
|
973
|
+
// the agent has been doing (thinking, acting, waiting) as a timeline.
|
|
974
|
+
const history = activityHistory.get(activityId) || [];
|
|
975
|
+
history.push({ state, message, timestamp });
|
|
976
|
+
if (history.length > 30)
|
|
977
|
+
history.splice(0, history.length - 30);
|
|
978
|
+
activityHistory.set(activityId, history);
|
|
979
|
+
// The hierarchy is useful monitoring UI, but chat is the durable primary
|
|
980
|
+
// record. Persist only concise activity summaries, never model reasoning.
|
|
981
|
+
const task = db.getTask(taskId);
|
|
982
|
+
if (task?.sessionId) {
|
|
983
|
+
const chatMessage = {
|
|
984
|
+
id: `msg-${Date.now()}-activity-${Math.random().toString(36).slice(2, 7)}`,
|
|
985
|
+
sessionId: task.sessionId,
|
|
986
|
+
sender: 'supervisor',
|
|
987
|
+
text: `Activity (${state}): ${message}`,
|
|
988
|
+
timestamp
|
|
989
|
+
};
|
|
990
|
+
db.saveChatMessage(chatMessage);
|
|
991
|
+
broadcastEvent({ type: 'chat.message.created', sessionId: task.sessionId, messageId: chatMessage.id, timestamp });
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
// Ask the user a question mid-execution. Returns a promise resolved when the
|
|
995
|
+
// dashboard POSTs the answer to /api/agent-question/:id/answer.
|
|
996
|
+
function askUser(taskId, agentId, question, options) {
|
|
997
|
+
const id = `q-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
998
|
+
return new Promise(resolve => {
|
|
999
|
+
pendingQuestions.set(id, {
|
|
1000
|
+
id,
|
|
1001
|
+
taskId,
|
|
1002
|
+
agentId,
|
|
1003
|
+
question,
|
|
1004
|
+
options,
|
|
1005
|
+
resolve,
|
|
1006
|
+
askedAt: new Date().toISOString()
|
|
1007
|
+
});
|
|
1008
|
+
broadcastEvent({
|
|
1009
|
+
type: 'agent.question',
|
|
1010
|
+
questionId: id,
|
|
1011
|
+
taskId,
|
|
1012
|
+
agentId,
|
|
1013
|
+
question,
|
|
1014
|
+
options,
|
|
1015
|
+
timestamp: new Date().toISOString()
|
|
1016
|
+
});
|
|
1017
|
+
emitActivity(taskId, agentId, id, 'waiting-user', question);
|
|
1018
|
+
});
|
|
1019
|
+
}
|
|
1020
|
+
// Chat with Supervisor (AI Workspace) — session-aware, optionally in background
|
|
1021
|
+
server.post('/api/chat', async (req, reply) => {
|
|
1022
|
+
const { message, projectId, sessionId, background } = req.body;
|
|
1023
|
+
// Background mode: enqueue the work and answer immediately; the UI follows
|
|
1024
|
+
// progress through hierarchy.stage / chat.background.* WebSocket events.
|
|
1025
|
+
if (background) {
|
|
1026
|
+
const bgSessionId = sessionId || `session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
1027
|
+
processChat(message, projectId, bgSessionId).catch(err => {
|
|
1028
|
+
emitStage('supervisor', 'failed', { sessionId: bgSessionId, detail: err.message });
|
|
1029
|
+
});
|
|
1030
|
+
broadcastEvent({ type: 'chat.background.started', sessionId: bgSessionId, timestamp: new Date().toISOString() });
|
|
1031
|
+
return reply.status(202).send({ accepted: true, sessionId: bgSessionId, background: true });
|
|
1032
|
+
}
|
|
1033
|
+
const result = await processChat(message, projectId, sessionId);
|
|
1034
|
+
return result;
|
|
1035
|
+
});
|
|
1036
|
+
async function processChat(message, projectId, sessionId) {
|
|
1037
|
+
const project = projectId ? (db.getProject(projectId) || undefined) : (db.getProjects()[0] || undefined);
|
|
1038
|
+
const activeTasks = db.getTasks(project?.id);
|
|
1039
|
+
const pendingApprovals = db.getApprovals(project?.id).filter(a => a.status === 'pending');
|
|
1040
|
+
// Resolve (or lazily create) the session
|
|
1041
|
+
let session = sessionId ? db.getChatSession(sessionId) : null;
|
|
1042
|
+
if (!session) {
|
|
1043
|
+
const now = new Date().toISOString();
|
|
1044
|
+
session = {
|
|
1045
|
+
id: sessionId || `session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
|
|
1046
|
+
projectId,
|
|
1047
|
+
title: message.slice(0, 60),
|
|
1048
|
+
createdAt: now,
|
|
1049
|
+
updatedAt: now
|
|
1050
|
+
};
|
|
1051
|
+
db.saveChatSession(session);
|
|
1052
|
+
}
|
|
1053
|
+
const userMessage = {
|
|
1054
|
+
id: `msg-${Date.now()}-u`,
|
|
1055
|
+
sessionId: session.id,
|
|
1056
|
+
sender: 'user',
|
|
1057
|
+
text: message,
|
|
1058
|
+
timestamp: new Date().toISOString()
|
|
1059
|
+
};
|
|
1060
|
+
db.saveChatMessage(userMessage);
|
|
1061
|
+
const chatStartMs = Date.now();
|
|
1062
|
+
const existingMsgs = db.getChatMessages(session.id);
|
|
1063
|
+
const supervisorModel = gateway.getModelForAgent('agent-supervisor');
|
|
1064
|
+
const supervisorCtxLen = agentRegistry.getAgent('agent-supervisor')?.modelConfig.contextLength || 8192;
|
|
1065
|
+
const preContextChars = existingMsgs.reduce((sum, m) => sum + (m.text?.length || 0), 0);
|
|
1066
|
+
monitor.setInstanceMeta('chat', session.id, {
|
|
1067
|
+
label: session.title,
|
|
1068
|
+
model: supervisorModel,
|
|
1069
|
+
contextLength: supervisorCtxLen,
|
|
1070
|
+
contextChars: preContextChars,
|
|
1071
|
+
messageCount: existingMsgs.length
|
|
1072
|
+
});
|
|
1073
|
+
emitStage('supervisor', 'active', { sessionId: session.id, agentId: 'agent-supervisor' });
|
|
1074
|
+
const allAgents = agentRegistry.getAllAgents();
|
|
1075
|
+
const decision = await supervisor.processUserMessage(message, project, activeTasks, pendingApprovals, allAgents, (c) => {
|
|
1076
|
+
broadcastEvent({
|
|
1077
|
+
type: 'chat.stream.chunk',
|
|
1078
|
+
sessionId: session.id,
|
|
1079
|
+
agentId: 'agent-supervisor',
|
|
1080
|
+
chunk: c.content || '',
|
|
1081
|
+
thinkingChunk: c.thinking,
|
|
1082
|
+
done: c.done,
|
|
1083
|
+
stage: 'supervisor',
|
|
1084
|
+
timestamp: new Date().toISOString()
|
|
1085
|
+
});
|
|
1086
|
+
});
|
|
1087
|
+
emitStage('supervisor', 'done', { sessionId: session.id, agentId: 'agent-supervisor' });
|
|
1088
|
+
if (decision.intent === 'delegate_agent' && decision.targetAgentId) {
|
|
1089
|
+
const targetAgent = agentRegistry.getAgent(decision.targetAgentId);
|
|
1090
|
+
if (targetAgent) {
|
|
1091
|
+
emitStage(targetAgent.role, 'active', { sessionId: session.id, agentId: targetAgent.id });
|
|
1092
|
+
try {
|
|
1093
|
+
const delegated = await gateway.chat({
|
|
1094
|
+
model: gateway.getModelForAgent(targetAgent.id),
|
|
1095
|
+
messages: [
|
|
1096
|
+
{ role: 'system', content: targetAgent.systemPrompt },
|
|
1097
|
+
{ role: 'user', content: project ? `Project: ${project.name} (${project.detectedTechnologies.join(', ')})\n\n${message}` : message }
|
|
1098
|
+
],
|
|
1099
|
+
temperature: targetAgent.modelConfig.temperature ?? 0.3,
|
|
1100
|
+
onChunk: (chunk) => {
|
|
1101
|
+
const contentPiece = chunk?.message?.content ?? chunk?.response ?? '';
|
|
1102
|
+
const thinkingPiece = chunk?.message?.thinking ?? chunk?.thinking ?? '';
|
|
1103
|
+
if (contentPiece || thinkingPiece || chunk?.done) {
|
|
1104
|
+
broadcastEvent({
|
|
1105
|
+
type: 'chat.stream.chunk',
|
|
1106
|
+
sessionId: session.id,
|
|
1107
|
+
agentId: targetAgent.id,
|
|
1108
|
+
chunk: contentPiece,
|
|
1109
|
+
thinkingChunk: thinkingPiece || undefined,
|
|
1110
|
+
done: Boolean(chunk?.done),
|
|
1111
|
+
stage: targetAgent.role,
|
|
1112
|
+
timestamp: new Date().toISOString()
|
|
1113
|
+
});
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
}, 'high', targetAgent.id);
|
|
1117
|
+
decision.response = delegated.response;
|
|
1118
|
+
decision.thinking = delegated.thinking;
|
|
1119
|
+
emitStage(targetAgent.role, 'done', { sessionId: session.id, agentId: targetAgent.id });
|
|
1120
|
+
}
|
|
1121
|
+
catch (err) {
|
|
1122
|
+
decision.response = `Could not reach **${targetAgent.name}**: ${err.message}`;
|
|
1123
|
+
emitStage(targetAgent.role, 'failed', { sessionId: session.id, agentId: targetAgent.id, detail: err.message });
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
let planCreated = false;
|
|
1128
|
+
let createdTasks = [];
|
|
1129
|
+
// Clarification continuation: if the planner is waiting for answers in
|
|
1130
|
+
// this session, the user's message is the answer — route it straight to
|
|
1131
|
+
// the planner instead of the Supervisor (which could misclassify it).
|
|
1132
|
+
const pendingClarification = pendingPlanBySession.get(session.id);
|
|
1133
|
+
if (pendingClarification && project) {
|
|
1134
|
+
// Treat this message as the clarification answer and resume planning.
|
|
1135
|
+
decision.intent = 'plan_required';
|
|
1136
|
+
decision.proposedPlanGoal = pendingClarification.originalRequest;
|
|
1137
|
+
}
|
|
1138
|
+
if (decision.intent === 'plan_required' && decision.proposedPlanGoal && project) {
|
|
1139
|
+
// Intelligent planning: understand -> (clarify in chat) -> decompose -> validate.
|
|
1140
|
+
const pending = pendingPlanBySession.get(session.id);
|
|
1141
|
+
const isClarificationAnswer = !!pending;
|
|
1142
|
+
// If this message answers a pending clarification, fold the answer into
|
|
1143
|
+
// the planning context instead of treating it as a new request.
|
|
1144
|
+
const originalRequest = isClarificationAnswer ? pending.originalRequest : decision.proposedPlanGoal;
|
|
1145
|
+
const clarificationAnswers = isClarificationAnswer
|
|
1146
|
+
? [...pending.answers, message]
|
|
1147
|
+
: undefined;
|
|
1148
|
+
const roundsUsed = isClarificationAnswer ? pending.roundsUsed + 1 : 0;
|
|
1149
|
+
if (isClarificationAnswer)
|
|
1150
|
+
pendingPlanBySession.delete(session.id);
|
|
1151
|
+
emitStage('planner', 'active', { sessionId: session.id, agentId: 'agent-planner', detail: isClarificationAnswer ? 'Incorporating your answers…' : 'Understanding the request…' });
|
|
1152
|
+
emitPlanningStatus(session.id, 'analyzing');
|
|
1153
|
+
let planResult;
|
|
1154
|
+
try {
|
|
1155
|
+
planResult = await planner.planIntelligently(originalRequest, project, agentRegistry.getAllAgents(), skillRegistry.getAllSkills(), { mode: 'quick', allowClarification: true, clarificationAnswers, clarificationRoundsUsed: roundsUsed });
|
|
1156
|
+
}
|
|
1157
|
+
catch (err) {
|
|
1158
|
+
emitStage('planner', 'failed', { sessionId: session.id, agentId: 'agent-planner', detail: err.message });
|
|
1159
|
+
emitPlanningStatus(session.id, 'failed', { message: err.message });
|
|
1160
|
+
planResult = {
|
|
1161
|
+
status: 'failed',
|
|
1162
|
+
mode: 'quick',
|
|
1163
|
+
originalRequest,
|
|
1164
|
+
tasks: [],
|
|
1165
|
+
dependencyGraph: {},
|
|
1166
|
+
validation: [],
|
|
1167
|
+
summary: `Planning failed: ${err.message}`,
|
|
1168
|
+
usedFallback: false
|
|
1169
|
+
};
|
|
1170
|
+
}
|
|
1171
|
+
if (planResult.status === 'clarification_required' && planResult.clarification) {
|
|
1172
|
+
// Park the plan; the user's next chat message is the answer.
|
|
1173
|
+
pendingPlanBySession.set(session.id, {
|
|
1174
|
+
sessionId: session.id,
|
|
1175
|
+
projectId: project.id,
|
|
1176
|
+
originalRequest,
|
|
1177
|
+
questions: planResult.clarification,
|
|
1178
|
+
answers: clarificationAnswers || [],
|
|
1179
|
+
roundsUsed,
|
|
1180
|
+
lastSummary: planResult.summary,
|
|
1181
|
+
mode: planResult.mode
|
|
1182
|
+
});
|
|
1183
|
+
emitPlanningStatus(session.id, 'clarification_required', { questions: planResult.clarification, message: planResult.summary });
|
|
1184
|
+
emitStage('planner', 'done', { sessionId: session.id, agentId: 'agent-planner', detail: 'waiting for clarification' });
|
|
1185
|
+
}
|
|
1186
|
+
else if (planResult.status === 'ready_for_review') {
|
|
1187
|
+
// NOTE: prompt compilation is intentionally deferred. Planner output is
|
|
1188
|
+
// a PROPOSAL; the Prompter runs only after the user approves the task
|
|
1189
|
+
// on the Task Board (Proposed -> Approve).
|
|
1190
|
+
createdTasks = publishPlanTasks(planResult, session.id);
|
|
1191
|
+
planCreated = true;
|
|
1192
|
+
emitPlanningStatus(session.id, 'ready_for_review', { taskCount: createdTasks.length, message: planResult.summary });
|
|
1193
|
+
emitStage('planner', 'done', { sessionId: session.id, agentId: 'agent-planner', detail: `${createdTasks.length} tasks` });
|
|
1194
|
+
emitStage('scheduler', 'done', { sessionId: session.id, detail: `${createdTasks.length} tasks queued` });
|
|
1195
|
+
}
|
|
1196
|
+
else {
|
|
1197
|
+
emitPlanningStatus(session.id, planResult.status, { message: planResult.summary });
|
|
1198
|
+
emitStage('planner', planResult.status === 'failed' ? 'failed' : 'done', { sessionId: session.id, agentId: 'agent-planner', detail: planResult.summary.slice(0, 120) });
|
|
1199
|
+
}
|
|
1200
|
+
// The chat reply is the planner's concise, user-facing summary — never
|
|
1201
|
+
// internal reasoning or raw JSON.
|
|
1202
|
+
decision.response = planResult.summary;
|
|
1203
|
+
}
|
|
1204
|
+
const { response: cleanResponse, thinking: tagThinking } = extractThinking(decision.response || '');
|
|
1205
|
+
const thinking = decision.thinking || tagThinking;
|
|
1206
|
+
const supervisorMessage = {
|
|
1207
|
+
id: `msg-${Date.now()}-s`,
|
|
1208
|
+
sessionId: session.id,
|
|
1209
|
+
sender: 'supervisor',
|
|
1210
|
+
text: cleanResponse || 'Request received and processed.',
|
|
1211
|
+
thinking,
|
|
1212
|
+
planCreated,
|
|
1213
|
+
createdTasksCount: createdTasks.length,
|
|
1214
|
+
timestamp: new Date().toISOString()
|
|
1215
|
+
};
|
|
1216
|
+
db.saveChatMessage(supervisorMessage);
|
|
1217
|
+
db.saveChatSession({ ...session, updatedAt: new Date().toISOString() });
|
|
1218
|
+
const allSessionMsgs = db.getChatMessages(session.id);
|
|
1219
|
+
const postContextChars = allSessionMsgs.reduce((sum, m) => sum + (m.text?.length || 0), 0);
|
|
1220
|
+
monitor.record({
|
|
1221
|
+
scope: 'chat',
|
|
1222
|
+
instanceId: session.id,
|
|
1223
|
+
stage: planCreated ? 'planner' : (decision.targetAgentId ? 'executor' : 'supervisor'),
|
|
1224
|
+
agentId: decision.targetAgentId || (planCreated ? 'agent-planner' : 'agent-supervisor'),
|
|
1225
|
+
model: gateway.getModelForAgent(decision.targetAgentId || 'agent-supervisor'),
|
|
1226
|
+
promptTokens: monitor.estimateTokens(message + preContextChars.toString()),
|
|
1227
|
+
completionTokens: monitor.estimateTokens(cleanResponse + (thinking || '')),
|
|
1228
|
+
durationMs: Date.now() - chatStartMs,
|
|
1229
|
+
success: true,
|
|
1230
|
+
contextLength: supervisorCtxLen
|
|
1231
|
+
});
|
|
1232
|
+
monitor.updateContext('chat', session.id, {
|
|
1233
|
+
contextChars: postContextChars,
|
|
1234
|
+
messageCount: allSessionMsgs.length,
|
|
1235
|
+
model: supervisorModel,
|
|
1236
|
+
contextLength: supervisorCtxLen
|
|
1237
|
+
});
|
|
1238
|
+
broadcastEvent({
|
|
1239
|
+
type: 'chat.background.completed',
|
|
1240
|
+
sessionId: session.id,
|
|
1241
|
+
planCreated,
|
|
1242
|
+
createdTasksCount: createdTasks.length,
|
|
1243
|
+
timestamp: new Date().toISOString()
|
|
1244
|
+
});
|
|
1245
|
+
return {
|
|
1246
|
+
decision,
|
|
1247
|
+
response: cleanResponse,
|
|
1248
|
+
thinking,
|
|
1249
|
+
planCreated,
|
|
1250
|
+
createdTasksCount: createdTasks.length,
|
|
1251
|
+
sessionId: session.id
|
|
1252
|
+
};
|
|
1253
|
+
}
|
|
1254
|
+
// Quick action: summarize the current session
|
|
1255
|
+
server.post('/api/chat/summarize', async (req) => {
|
|
1256
|
+
const { sessionId } = req.body;
|
|
1257
|
+
const session = db.getChatSession(sessionId);
|
|
1258
|
+
if (!session)
|
|
1259
|
+
return { summary: 'Session not found.' };
|
|
1260
|
+
const messages = db.getChatMessages(sessionId);
|
|
1261
|
+
if (messages.length === 0) {
|
|
1262
|
+
return { summary: 'This session has no messages yet, so there is nothing to summarize.' };
|
|
1263
|
+
}
|
|
1264
|
+
const transcript = messages
|
|
1265
|
+
.map(m => `${m.sender === 'user' ? 'User' : 'Supervisor'}: ${m.text}`)
|
|
1266
|
+
.join('\n')
|
|
1267
|
+
.slice(-6000);
|
|
1268
|
+
let summary;
|
|
1269
|
+
try {
|
|
1270
|
+
const result = await gateway.chat({
|
|
1271
|
+
model: gateway.getModelForAgent('agent-supervisor'),
|
|
1272
|
+
messages: [
|
|
1273
|
+
{ role: 'system', content: 'Summarize the following conversation between a user and the VibeCodePilot Supervisor. Capture the user goals, decisions made, tasks created, and open items. Be concise (max 10 bullet points).' },
|
|
1274
|
+
{ role: 'user', content: transcript }
|
|
1275
|
+
],
|
|
1276
|
+
temperature: 0.2
|
|
1277
|
+
}, 'high', 'agent-supervisor');
|
|
1278
|
+
summary = extractThinking(result.response).response;
|
|
1279
|
+
}
|
|
1280
|
+
catch (err) {
|
|
1281
|
+
// Deterministic fallback when Ollama is offline
|
|
1282
|
+
const userMsgs = messages.filter(m => m.sender === 'user').length;
|
|
1283
|
+
const supMsgs = messages.filter(m => m.sender === 'supervisor').length;
|
|
1284
|
+
summary = `Session "${session.title}" — ${messages.length} messages (${userMsgs} from you, ${supMsgs} from the Supervisor). ` +
|
|
1285
|
+
`Last activity: ${messages[messages.length - 1]?.timestamp}. ` +
|
|
1286
|
+
`(Local model offline — showing a deterministic summary instead of an AI-generated one.)`;
|
|
1287
|
+
}
|
|
1288
|
+
return { summary, sessionId };
|
|
1289
|
+
});
|
|
1290
|
+
// Quick action: review plan files (*.md) in the project directory
|
|
1291
|
+
server.post('/api/chat/plan-review', async (req) => {
|
|
1292
|
+
const { projectId } = req.body;
|
|
1293
|
+
const project = projectId ? db.getProject(projectId) : db.getProjects()[0];
|
|
1294
|
+
if (!project || !fs.existsSync(project.path)) {
|
|
1295
|
+
return { review: 'No valid project directory available for plan review.', planFiles: [] };
|
|
1296
|
+
}
|
|
1297
|
+
// Collect *.md files anywhere in the project (excluding node_modules/.git)
|
|
1298
|
+
const planFiles = [];
|
|
1299
|
+
const skip = new Set(['node_modules', '.git', 'dist', 'build']);
|
|
1300
|
+
const walk = (dir, depth = 0) => {
|
|
1301
|
+
if (depth > 4)
|
|
1302
|
+
return;
|
|
1303
|
+
let entries;
|
|
1304
|
+
try {
|
|
1305
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
1306
|
+
}
|
|
1307
|
+
catch {
|
|
1308
|
+
return;
|
|
1309
|
+
}
|
|
1310
|
+
for (const entry of entries) {
|
|
1311
|
+
if (entry.isDirectory()) {
|
|
1312
|
+
if (!skip.has(entry.name))
|
|
1313
|
+
walk(path.join(dir, entry.name), depth + 1);
|
|
1314
|
+
continue;
|
|
1315
|
+
}
|
|
1316
|
+
if (!entry.name.toLowerCase().endsWith('.md'))
|
|
1317
|
+
continue;
|
|
1318
|
+
const filePath = path.join(dir, entry.name);
|
|
1319
|
+
let content;
|
|
1320
|
+
try {
|
|
1321
|
+
content = fs.readFileSync(filePath, 'utf8');
|
|
1322
|
+
}
|
|
1323
|
+
catch {
|
|
1324
|
+
continue;
|
|
1325
|
+
}
|
|
1326
|
+
// Parse markdown checkboxes: - [ ] (open), - [x] (done)
|
|
1327
|
+
const items = Array.from(content.matchAll(/^-\s*\[( |x|X)\]\s*(.+)$/gm))
|
|
1328
|
+
.map(m => ({ text: m[2].trim(), done: m[1].toLowerCase() === 'x' }));
|
|
1329
|
+
if (items.length === 0)
|
|
1330
|
+
continue; // not a checklist plan file
|
|
1331
|
+
planFiles.push({
|
|
1332
|
+
file: path.relative(project.path, filePath),
|
|
1333
|
+
tasksDone: items.filter(i => i.done).length,
|
|
1334
|
+
tasksLeft: items.filter(i => !i.done).length,
|
|
1335
|
+
items: items.slice(0, 50)
|
|
1336
|
+
});
|
|
1337
|
+
}
|
|
1338
|
+
};
|
|
1339
|
+
walk(project.path);
|
|
1340
|
+
// Sync completed plan items into the application plan section (tasks)
|
|
1341
|
+
let synced = 0;
|
|
1342
|
+
const existingTasks = db.getTasks(project.id);
|
|
1343
|
+
for (const pf of planFiles) {
|
|
1344
|
+
for (const item of pf.items.filter(i => !i.done)) {
|
|
1345
|
+
const already = existingTasks.some(t => t.status !== 'completed' && t.title.toLowerCase().includes(item.text.slice(0, 30).toLowerCase()));
|
|
1346
|
+
if (!already) {
|
|
1347
|
+
const task = {
|
|
1348
|
+
id: `task-plan-${Date.now()}-${synced}`,
|
|
1349
|
+
projectId: project.id,
|
|
1350
|
+
title: item.text.slice(0, 120),
|
|
1351
|
+
description: `Imported from plan file ${pf.file} (quick plan review).`,
|
|
1352
|
+
assignedAgentId: 'specialist-dynamic',
|
|
1353
|
+
requiredSkills: [],
|
|
1354
|
+
scope: { affectedFiles: [] },
|
|
1355
|
+
dependencies: [],
|
|
1356
|
+
acceptanceCriteria: [],
|
|
1357
|
+
status: 'planned',
|
|
1358
|
+
createdAt: new Date().toISOString(),
|
|
1359
|
+
updatedAt: new Date().toISOString()
|
|
1360
|
+
};
|
|
1361
|
+
db.saveTask(task);
|
|
1362
|
+
scheduler.loadTasks([task]);
|
|
1363
|
+
broadcastEvent({ type: 'task.created', taskId: task.id, task, timestamp: new Date().toISOString() });
|
|
1364
|
+
synced++;
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
const totalDone = planFiles.reduce((s, f) => s + f.tasksDone, 0);
|
|
1369
|
+
const totalLeft = planFiles.reduce((s, f) => s + f.tasksLeft, 0);
|
|
1370
|
+
const lines = planFiles.map(f => {
|
|
1371
|
+
const head = `- ${f.file}: ${f.tasksDone} completed, ${f.tasksLeft} remaining`;
|
|
1372
|
+
const open = f.items.filter(i => !i.done);
|
|
1373
|
+
if (open.length === 0)
|
|
1374
|
+
return head;
|
|
1375
|
+
// List each open item on its own indented line — no pipe-chained dump.
|
|
1376
|
+
const items = open.slice(0, 8).map(i => ` - ${i.text.replace(/\s+/g, ' ').trim()}`);
|
|
1377
|
+
const more = open.length > 8 ? [` - …and ${open.length - 8} more`] : [];
|
|
1378
|
+
return [head, ...items, ...more].join('\n');
|
|
1379
|
+
});
|
|
1380
|
+
const mdFiles = [];
|
|
1381
|
+
{
|
|
1382
|
+
// Reuse the walk to know whether ANY markdown file exists at all, so the
|
|
1383
|
+
// no-plan message can tell the two situations apart.
|
|
1384
|
+
const walkMd = (dir, depth = 0) => {
|
|
1385
|
+
if (depth > 4 || mdFiles.length >= 20)
|
|
1386
|
+
return;
|
|
1387
|
+
let entries;
|
|
1388
|
+
try {
|
|
1389
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
1390
|
+
}
|
|
1391
|
+
catch {
|
|
1392
|
+
return;
|
|
1393
|
+
}
|
|
1394
|
+
for (const entry of entries) {
|
|
1395
|
+
if (entry.isDirectory()) {
|
|
1396
|
+
if (!skip.has(entry.name))
|
|
1397
|
+
walkMd(path.join(dir, entry.name), depth + 1);
|
|
1398
|
+
continue;
|
|
1399
|
+
}
|
|
1400
|
+
if (entry.name.toLowerCase().endsWith('.md'))
|
|
1401
|
+
mdFiles.push(path.relative(project.path, path.join(dir, entry.name)));
|
|
1402
|
+
}
|
|
1403
|
+
};
|
|
1404
|
+
walkMd(project.path);
|
|
1405
|
+
}
|
|
1406
|
+
let review;
|
|
1407
|
+
if (planFiles.length === 0) {
|
|
1408
|
+
review = mdFiles.length > 0
|
|
1409
|
+
? `No plan checklists were found. ${mdFiles.length} markdown file(s) exist in this project (e.g. ${mdFiles.slice(0, 3).join(', ')}), but none contain checklist items.\n\n` +
|
|
1410
|
+
'A plan file is any *.md containing GitHub-style checkboxes, one per line:\n' +
|
|
1411
|
+
'```\n- [ ] First step to implement\n- [x] Completed step\n```\n' +
|
|
1412
|
+
'Add items like these to a markdown file in the project (for example PLAN.md), then run Quick Plan Review again — open items are imported onto the Task Board automatically.'
|
|
1413
|
+
: 'No markdown plan files were found in this project.\n\n' +
|
|
1414
|
+
'To use Quick Plan Review, create a markdown file in the project root (for example PLAN.md) with GitHub-style checklist items, one per line:\n' +
|
|
1415
|
+
'```\n- [ ] First step to implement\n- [x] Completed step\n```\n' +
|
|
1416
|
+
'Then run Quick Plan Review again — every open item is imported onto the Task Board as a planned task, and completed items are reported here.';
|
|
1417
|
+
}
|
|
1418
|
+
else {
|
|
1419
|
+
review = `Plan review across ${planFiles.length} file(s): ${totalDone} items completed, ${totalLeft} remaining.\n\n${lines.join('\n')}` +
|
|
1420
|
+
(synced > 0 ? `\n\n${synced} open item(s) were imported onto the Task Board as planned tasks.` : '');
|
|
1421
|
+
}
|
|
1422
|
+
return { review, planFiles, synced, totalDone, totalLeft, mdFileCount: mdFiles.length };
|
|
1423
|
+
});
|
|
1424
|
+
// Task Execution in isolated worktree
|
|
1425
|
+
// Execute a task: staged, observable, background execution.
|
|
1426
|
+
// Each stage broadcasts execution.activity so the dashboard's Execution
|
|
1427
|
+
// Activity section can show what every agent is doing right now.
|
|
1428
|
+
server.post('/api/tasks/:id/execute', async (req, reply) => {
|
|
1429
|
+
const { id } = req.params;
|
|
1430
|
+
const task = db.getTask(id);
|
|
1431
|
+
if (!task)
|
|
1432
|
+
return reply.status(404).send({ error: 'Task not found' });
|
|
1433
|
+
if (task.archived)
|
|
1434
|
+
return reply.status(409).send({ error: 'Restore the task before executing it.' });
|
|
1435
|
+
if (task.status === 'running')
|
|
1436
|
+
return reply.status(409).send({ error: 'Task is already running.' });
|
|
1437
|
+
if (runningExecutions.has(task.id))
|
|
1438
|
+
return reply.status(409).send({ error: 'Task execution is already in progress.' });
|
|
1439
|
+
if (!['planned', 'ready'].includes(task.status))
|
|
1440
|
+
return reply.status(409).send({ error: `Task in ${task.status} state cannot be executed.` });
|
|
1441
|
+
// Dependency gate: every declared dependency must already be completed.
|
|
1442
|
+
// A dependency that no longer exists is stale (e.g. the plan was re-run or
|
|
1443
|
+
// the task was deleted) and must not permanently block execution.
|
|
1444
|
+
const allTasks = db.getTasks();
|
|
1445
|
+
const unmet = (task.dependencies || []).filter(depId => {
|
|
1446
|
+
const dep = allTasks.find(t => t.id === depId);
|
|
1447
|
+
return !!dep && dep.status !== 'completed';
|
|
1448
|
+
});
|
|
1449
|
+
const stale = (task.dependencies || []).filter(depId => !allTasks.find(t => t.id === depId));
|
|
1450
|
+
if (stale.length > 0) {
|
|
1451
|
+
task.dependencies = task.dependencies.filter((d) => !stale.includes(d));
|
|
1452
|
+
db.saveTask(task);
|
|
1453
|
+
appendTaskLog(task, 'info', `Removed stale dependencies (no longer exist): ${stale.join(', ')}`);
|
|
1454
|
+
}
|
|
1455
|
+
if (unmet.length > 0) {
|
|
1456
|
+
recordStatusTransition(task, 'blocked', `Unmet dependencies: ${unmet.join(', ')}`);
|
|
1457
|
+
task.updatedAt = new Date().toISOString();
|
|
1458
|
+
appendTaskLog(task, 'info', `Execution blocked by unmet dependencies: ${unmet.join(', ')}`);
|
|
1459
|
+
publishTask(task);
|
|
1460
|
+
return reply.status(409).send({ error: `Task is blocked by unmet dependencies: ${unmet.join(', ')}` });
|
|
1461
|
+
}
|
|
1462
|
+
const project = db.getProject(task.projectId);
|
|
1463
|
+
if (!project)
|
|
1464
|
+
return reply.status(400).send({ error: 'Task project not found' });
|
|
1465
|
+
// Persist 'running' immediately so the board reflects execution right away.
|
|
1466
|
+
recordStatusTransition(task, 'running', 'Execution started.');
|
|
1467
|
+
task.startedAt = new Date().toISOString();
|
|
1468
|
+
task.completedAt = undefined;
|
|
1469
|
+
task.error = undefined;
|
|
1470
|
+
task.updatedAt = new Date().toISOString();
|
|
1471
|
+
appendTaskLog(task, 'info', 'Execution started.');
|
|
1472
|
+
db.saveTask(task);
|
|
1473
|
+
broadcastEvent({ type: 'task.status', taskId: task.id, status: 'running', timestamp: new Date().toISOString() });
|
|
1474
|
+
// Ensure the scheduler knows the task (e.g. created before a restart).
|
|
1475
|
+
if (!scheduler.getTask(task.id)) {
|
|
1476
|
+
scheduler.loadTasks([task]);
|
|
1477
|
+
}
|
|
1478
|
+
cancelledTasks.delete(task.id);
|
|
1479
|
+
runningExecutions.add(task.id);
|
|
1480
|
+
// Run in the background so the HTTP response is immediate; the dashboard
|
|
1481
|
+
// follows progress via execution.activity / task.* WebSocket events.
|
|
1482
|
+
runTaskExecution(task, project).catch(err => {
|
|
1483
|
+
const cancelled = err instanceof TaskCancelledError || isCancelled(task.id);
|
|
1484
|
+
emitActivity(task.id, task.assignedAgentId || 'specialist-dynamic', `exec-${task.id}`, 'failed', err.message);
|
|
1485
|
+
recordStatusTransition(task, cancelled ? 'cancelled' : 'failed', err.message);
|
|
1486
|
+
task.completionSummary = err.message || 'Execution failed';
|
|
1487
|
+
task.error = task.completionSummary;
|
|
1488
|
+
task.completedAt = new Date().toISOString();
|
|
1489
|
+
task.updatedAt = new Date().toISOString();
|
|
1490
|
+
appendTaskLog(task, 'error', task.completionSummary || 'Execution failed');
|
|
1491
|
+
db.saveTask(task);
|
|
1492
|
+
broadcastEvent({ type: 'task.status', taskId: task.id, status: task.status, timestamp: new Date().toISOString() });
|
|
1493
|
+
}).finally(() => {
|
|
1494
|
+
runningExecutions.delete(task.id);
|
|
1495
|
+
cancelledTasks.delete(task.id);
|
|
1496
|
+
});
|
|
1497
|
+
return reply.status(202).send({ accepted: true, taskId: id });
|
|
1498
|
+
});
|
|
1499
|
+
async function runTaskExecution(task, project) {
|
|
1500
|
+
const agentId = task.assignedAgentId || 'specialist-dynamic';
|
|
1501
|
+
const act = `exec-${task.id}`;
|
|
1502
|
+
broadcastEvent({
|
|
1503
|
+
type: 'agent.started',
|
|
1504
|
+
agentId,
|
|
1505
|
+
timestamp: new Date().toISOString()
|
|
1506
|
+
});
|
|
1507
|
+
const executionResult = await scheduler.runTask(task.id, project, async (t, worktree) => {
|
|
1508
|
+
const ensureNotCancelled = () => {
|
|
1509
|
+
if (isCancelled(t.id))
|
|
1510
|
+
throw new TaskCancelledError();
|
|
1511
|
+
};
|
|
1512
|
+
// Stage 1 — analyze the task
|
|
1513
|
+
ensureNotCancelled();
|
|
1514
|
+
emitActivity(t.id, agentId, act, 'thinking', 'Analyzing task requirements and affected files…');
|
|
1515
|
+
const taskModel = gateway.getModelForAgent(agentId);
|
|
1516
|
+
const taskCtxLen = agentRegistry.getAgent(agentId)?.modelConfig.contextLength || 8192;
|
|
1517
|
+
// Regenerate the project flow graph so it reflects the current tree, then
|
|
1518
|
+
// inline it as context (agents read the map instead of the whole repo).
|
|
1519
|
+
let flowGraphContext = '';
|
|
1520
|
+
try {
|
|
1521
|
+
const fgPath = await (0, projectFlowGraph_js_1.generateFlowGraphFile)(project.path, db.getTasks());
|
|
1522
|
+
flowGraphContext = fs.readFileSync(fgPath, 'utf8');
|
|
1523
|
+
}
|
|
1524
|
+
catch { /* graph is best-effort context */ }
|
|
1525
|
+
const analysisPromptText = `Task: ${t.title}\nDescription: ${t.description}\nAffected files: ${t.scope.affectedFiles.join(', ') || 'none listed'}\nAcceptance criteria: ${t.acceptanceCriteria.join('; ') || 'none listed'}${flowGraphContext ? `\n\n## Project flow graph (what relates to what — use this instead of exploring the repo)\n${flowGraphContext}` : ''}`;
|
|
1526
|
+
monitor.setInstanceMeta('task', t.id, {
|
|
1527
|
+
label: t.title,
|
|
1528
|
+
model: taskModel,
|
|
1529
|
+
contextLength: taskCtxLen,
|
|
1530
|
+
contextChars: analysisPromptText.length,
|
|
1531
|
+
messageCount: 1
|
|
1532
|
+
});
|
|
1533
|
+
const analysisStartMs = Date.now();
|
|
1534
|
+
let implementationPlan = '';
|
|
1535
|
+
try {
|
|
1536
|
+
const analysis = await gateway.chat({
|
|
1537
|
+
model: taskModel,
|
|
1538
|
+
messages: [
|
|
1539
|
+
{ role: 'system', content: 'You are a software specialist agent. Analyze the task and produce a concise step-by-step implementation plan (max 6 bullet points). Respond with the plan only.' },
|
|
1540
|
+
{ role: 'user', content: analysisPromptText }
|
|
1541
|
+
],
|
|
1542
|
+
temperature: 0.3,
|
|
1543
|
+
onChunk: (chunk) => {
|
|
1544
|
+
const contentPiece = chunk?.message?.content ?? chunk?.response ?? '';
|
|
1545
|
+
const thinkingPiece = chunk?.message?.thinking ?? chunk?.thinking ?? '';
|
|
1546
|
+
if (contentPiece || thinkingPiece || chunk?.done) {
|
|
1547
|
+
broadcastEvent({
|
|
1548
|
+
type: 'chat.stream.chunk',
|
|
1549
|
+
sessionId: t.sessionId,
|
|
1550
|
+
taskId: t.id,
|
|
1551
|
+
agentId,
|
|
1552
|
+
chunk: contentPiece,
|
|
1553
|
+
thinkingChunk: thinkingPiece || undefined,
|
|
1554
|
+
done: Boolean(chunk?.done),
|
|
1555
|
+
stage: 'analysis',
|
|
1556
|
+
timestamp: new Date().toISOString()
|
|
1557
|
+
});
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
}, 'normal', agentId);
|
|
1561
|
+
implementationPlan = extractThinking(analysis.response).response;
|
|
1562
|
+
monitor.record({
|
|
1563
|
+
scope: 'task',
|
|
1564
|
+
instanceId: t.id,
|
|
1565
|
+
stage: 'executor',
|
|
1566
|
+
agentId,
|
|
1567
|
+
model: taskModel,
|
|
1568
|
+
promptTokens: monitor.estimateTokens(analysisPromptText),
|
|
1569
|
+
completionTokens: analysis.evalCount || monitor.estimateTokens(analysis.response),
|
|
1570
|
+
durationMs: Date.now() - analysisStartMs,
|
|
1571
|
+
success: true,
|
|
1572
|
+
contextLength: taskCtxLen
|
|
1573
|
+
});
|
|
1574
|
+
monitor.updateContext('task', t.id, {
|
|
1575
|
+
contextChars: analysisPromptText.length + analysis.response.length,
|
|
1576
|
+
messageCount: 2,
|
|
1577
|
+
model: taskModel,
|
|
1578
|
+
contextLength: taskCtxLen
|
|
1579
|
+
});
|
|
1580
|
+
}
|
|
1581
|
+
catch {
|
|
1582
|
+
// Ollama offline — deterministic fallback so execution still completes
|
|
1583
|
+
implementationPlan = t.description || t.title;
|
|
1584
|
+
}
|
|
1585
|
+
emitActivity(t.id, agentId, act, 'acting', `Plan ready: ${implementationPlan.split('\n')[0]?.slice(0, 120) || 'proceeding with task description'}`);
|
|
1586
|
+
// Stage 2 — confirm approach with the user (interactive gate).
|
|
1587
|
+
// Cancellation while waiting resolves with a sentinel that throws here.
|
|
1588
|
+
ensureNotCancelled();
|
|
1589
|
+
const answer = await askUser(t.id, agentId, `Approve the implementation plan for "${t.title}"?`, ['Approve and execute', 'Execute without plan review']);
|
|
1590
|
+
if (answer === '__cancelled__')
|
|
1591
|
+
throw new TaskCancelledError();
|
|
1592
|
+
emitActivity(t.id, agentId, act, 'acting', `User response: "${answer}" — proceeding`);
|
|
1593
|
+
// Stage 3 — lock files & prepare in-place execution context
|
|
1594
|
+
ensureNotCancelled();
|
|
1595
|
+
emitActivity(t.id, agentId, act, 'acting', `Locking affected files and preparing in-place execution (${worktree.branch})…`);
|
|
1596
|
+
broadcastEvent({
|
|
1597
|
+
type: 'tool.executed',
|
|
1598
|
+
agentId,
|
|
1599
|
+
tool: `file-locks acquired for: ${t.scope.affectedFiles.join(', ') || 'no specific files'}`,
|
|
1600
|
+
timestamp: new Date().toISOString()
|
|
1601
|
+
});
|
|
1602
|
+
// Stage 4 — ask the development model for constrained tool operations,
|
|
1603
|
+
// apply them, and verify the actual filesystem state. A model response is
|
|
1604
|
+
// never treated as a successful implementation on its own.
|
|
1605
|
+
emitActivity(t.id, agentId, act, 'acting', 'Generating verified workspace file operations…');
|
|
1606
|
+
ensureNotCancelled();
|
|
1607
|
+
const implUserPrompt = `Project root: ${project.path}\nTask: ${t.title}\nDescription: ${t.description}\nApproved plan: ${implementationPlan}\nAllowed scope: ${t.scope.affectedFiles.join(', ') || 'project workspace (keep changes minimal)'}\nAcceptance criteria: ${t.acceptanceCriteria.join('; ') || 'none listed'}${flowGraphContext ? `\n\n## Project flow graph (file connections — consult this to locate related code)\n${flowGraphContext}` : ''}`;
|
|
1608
|
+
const implStartMs = Date.now();
|
|
1609
|
+
const operationResponse = await gateway.chat({
|
|
1610
|
+
model: taskModel,
|
|
1611
|
+
messages: [
|
|
1612
|
+
{ role: 'system', content: 'You are a development agent. Return JSON only: {"operations":[...]}. Allowed operations are {"op":"mkdir","path":"relative/directory"} and {"op":"write","path":"relative/file","content":"complete UTF-8 content","mode":"create"|"overwrite"|"append"}. Inspect the task scope, make only necessary changes, use relative paths, and never delete files or run commands. Include complete content for every write.' },
|
|
1613
|
+
{ role: 'user', content: implUserPrompt }
|
|
1614
|
+
],
|
|
1615
|
+
temperature: 0.2,
|
|
1616
|
+
onChunk: (chunk) => {
|
|
1617
|
+
const contentPiece = chunk?.message?.content ?? chunk?.response ?? '';
|
|
1618
|
+
const thinkingPiece = chunk?.message?.thinking ?? chunk?.thinking ?? '';
|
|
1619
|
+
if (contentPiece || thinkingPiece || chunk?.done) {
|
|
1620
|
+
broadcastEvent({
|
|
1621
|
+
type: 'chat.stream.chunk',
|
|
1622
|
+
sessionId: t.sessionId,
|
|
1623
|
+
taskId: t.id,
|
|
1624
|
+
agentId,
|
|
1625
|
+
chunk: contentPiece,
|
|
1626
|
+
thinkingChunk: thinkingPiece || undefined,
|
|
1627
|
+
done: Boolean(chunk?.done),
|
|
1628
|
+
stage: 'implementation',
|
|
1629
|
+
timestamp: new Date().toISOString()
|
|
1630
|
+
});
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
}, 'normal', agentId);
|
|
1634
|
+
monitor.record({
|
|
1635
|
+
scope: 'task',
|
|
1636
|
+
instanceId: t.id,
|
|
1637
|
+
stage: 'executor',
|
|
1638
|
+
agentId,
|
|
1639
|
+
model: taskModel,
|
|
1640
|
+
promptTokens: monitor.estimateTokens(implUserPrompt),
|
|
1641
|
+
completionTokens: operationResponse.evalCount || monitor.estimateTokens(operationResponse.response),
|
|
1642
|
+
durationMs: Date.now() - implStartMs,
|
|
1643
|
+
success: true,
|
|
1644
|
+
contextLength: taskCtxLen
|
|
1645
|
+
});
|
|
1646
|
+
monitor.updateContext('task', t.id, {
|
|
1647
|
+
contextChars: analysisPromptText.length + implementationPlan.length + implUserPrompt.length + operationResponse.response.length,
|
|
1648
|
+
messageCount: 4,
|
|
1649
|
+
model: taskModel,
|
|
1650
|
+
contextLength: taskCtxLen
|
|
1651
|
+
});
|
|
1652
|
+
const operations = (0, workspace_tools_js_1.parseFileOperations)(operationResponse.response);
|
|
1653
|
+
const tools = new workspace_tools_js_1.WorkspaceTools(project.path);
|
|
1654
|
+
const results = [];
|
|
1655
|
+
for (const operation of operations) {
|
|
1656
|
+
ensureNotCancelled();
|
|
1657
|
+
// Classify the model-requested operation for the permission engine.
|
|
1658
|
+
const permOperation = operation.op === 'mkdir' ? 'directory.create' : 'file.modify';
|
|
1659
|
+
// An overwrite of an existing file is a file modification; a create is too
|
|
1660
|
+
// (both are protected writes). Use file.modify as the protected class.
|
|
1661
|
+
const inPlannedScope = t.scope.affectedFiles.length === 0 || t.scope.affectedFiles.some(allowed => {
|
|
1662
|
+
const norm = operation.path.replace(/\\/g, '/');
|
|
1663
|
+
const allowedNorm = allowed.replace(/\\/g, '/');
|
|
1664
|
+
return norm === allowedNorm || norm.startsWith(`${allowedNorm}/`);
|
|
1665
|
+
});
|
|
1666
|
+
if (inPlannedScope) {
|
|
1667
|
+
// Planned-scope writes still pass through the engine for path validation
|
|
1668
|
+
// and audit, but resolve without a user prompt (existing behaviour).
|
|
1669
|
+
const planned = await permissionEngine.check({
|
|
1670
|
+
projectId: project.id, taskId: t.id, sessionId: t.sessionId, agentId,
|
|
1671
|
+
operation: permOperation,
|
|
1672
|
+
targetPath: operation.path,
|
|
1673
|
+
reason: 'Inside the Planner-approved task scope.',
|
|
1674
|
+
plannedScope: t.scope.affectedFiles
|
|
1675
|
+
});
|
|
1676
|
+
if (planned.kind !== 'allowed') {
|
|
1677
|
+
throw new Error(`Planned-scope operation was not allowed: ${operation.path} (${planned.kind})`);
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
else {
|
|
1681
|
+
// ---- Scope violation: PAUSE, request permission, wait for a real user decision ----
|
|
1682
|
+
const outcome = await permissionEngine.check({
|
|
1683
|
+
projectId: project.id, taskId: t.id, sessionId: t.sessionId, agentId,
|
|
1684
|
+
operation: permOperation,
|
|
1685
|
+
targetPath: operation.path,
|
|
1686
|
+
reason: `Outside the planned task scope (allowed: ${t.scope.affectedFiles.join(', ') || 'none'}).`,
|
|
1687
|
+
plannedScope: t.scope.affectedFiles
|
|
1688
|
+
});
|
|
1689
|
+
if (outcome.kind === 'denied') {
|
|
1690
|
+
throw new Error(`Permission denied: ${outcome.request?.reason || outcome.reason}`);
|
|
1691
|
+
}
|
|
1692
|
+
if (outcome.kind === 'pending') {
|
|
1693
|
+
const decision = await permissionEngine.waitForDecision(outcome.request.id);
|
|
1694
|
+
ensureNotCancelled();
|
|
1695
|
+
if (decision === null || decision === 'deny') {
|
|
1696
|
+
throw new Error(`User denied the out-of-scope operation: ${operation.path}.`);
|
|
1697
|
+
}
|
|
1698
|
+
emitActivity(t.id, agentId, act, 'acting', `User approved ${operation.path} (${decision}) — resuming`);
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
const result = tools.apply(operation);
|
|
1702
|
+
broadcastEvent({ type: 'tool.executed', agentId, tool: `${operation.op} ${operation.path}`, result: result.detail, timestamp: new Date().toISOString() });
|
|
1703
|
+
results.push(result);
|
|
1704
|
+
}
|
|
1705
|
+
const summary = `Verified ${results.length} workspace operation(s): ${results.map(r => r.path).join(', ')}.`;
|
|
1706
|
+
ensureNotCancelled();
|
|
1707
|
+
emitActivity(t.id, agentId, act, 'done', summary);
|
|
1708
|
+
// ---- Validation layer (Layer 6): run the project's real test suite ----
|
|
1709
|
+
ensureNotCancelled();
|
|
1710
|
+
emitActivity(t.id, agentId, act, 'acting', 'Running automated validation (project test suite)…');
|
|
1711
|
+
let validationSummary = '';
|
|
1712
|
+
try {
|
|
1713
|
+
const runner = new workspace_tools_js_1.TestRunner(project.path);
|
|
1714
|
+
const testResult = await runner.run();
|
|
1715
|
+
const tail = (testResult.stdout || testResult.stderr).split('\n').filter(l => l.trim()).slice(-5).join('\n');
|
|
1716
|
+
validationSummary = testResult.success
|
|
1717
|
+
? `Validation passed (${testResult.command}, ${testResult.durationMs}ms)${tail ? `\nLast output:\n${tail}` : ''}`
|
|
1718
|
+
: `Validation FAILED (${testResult.command}, exit ${testResult.exitCode}, ${testResult.durationMs}ms)${tail ? `\nLast output:\n${tail}` : ''}`;
|
|
1719
|
+
broadcastEvent({
|
|
1720
|
+
type: 'tool.executed',
|
|
1721
|
+
agentId,
|
|
1722
|
+
tool: `test-run ${testResult.command}`,
|
|
1723
|
+
result: testResult.success ? 'passed' : `failed (exit ${testResult.exitCode})`,
|
|
1724
|
+
timestamp: new Date().toISOString()
|
|
1725
|
+
});
|
|
1726
|
+
if (!testResult.success) {
|
|
1727
|
+
throw new Error(`Task completed file operations but automated validation failed:\n${validationSummary}`);
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
catch (err) {
|
|
1731
|
+
if (err instanceof Error && err.message.includes('No test command')) {
|
|
1732
|
+
validationSummary = 'No test command detected — validation skipped.';
|
|
1733
|
+
}
|
|
1734
|
+
else {
|
|
1735
|
+
throw err;
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
const finalSummary = validationSummary
|
|
1739
|
+
? `${summary}\n${validationSummary}`
|
|
1740
|
+
: summary;
|
|
1741
|
+
ensureNotCancelled();
|
|
1742
|
+
emitActivity(t.id, agentId, act, 'done', finalSummary.split('\n')[0]);
|
|
1743
|
+
return { success: true, summary: finalSummary };
|
|
1744
|
+
});
|
|
1745
|
+
recordStatusTransition(task, executionResult.success ? 'completed' : 'failed', executionResult.success ? undefined : executionResult.summary);
|
|
1746
|
+
task.completionSummary = executionResult.summary;
|
|
1747
|
+
task.error = executionResult.success ? undefined : executionResult.summary;
|
|
1748
|
+
task.completedAt = new Date().toISOString();
|
|
1749
|
+
task.updatedAt = new Date().toISOString();
|
|
1750
|
+
appendTaskLog(task, executionResult.success ? 'info' : 'error', executionResult.summary);
|
|
1751
|
+
db.saveTask(task);
|
|
1752
|
+
broadcastEvent({ type: 'task.status', taskId: task.id, status: task.status, timestamp: new Date().toISOString() });
|
|
1753
|
+
if (task.sessionId) {
|
|
1754
|
+
const message = {
|
|
1755
|
+
id: `msg-${Date.now()}-task-${task.id}`,
|
|
1756
|
+
sessionId: task.sessionId,
|
|
1757
|
+
sender: 'supervisor',
|
|
1758
|
+
text: executionResult.success
|
|
1759
|
+
? `Task completed: **${task.title}**\n\n${executionResult.summary}`
|
|
1760
|
+
: `Task failed: **${task.title}**\n\n${executionResult.summary}`,
|
|
1761
|
+
timestamp: new Date().toISOString()
|
|
1762
|
+
};
|
|
1763
|
+
db.saveChatMessage(message);
|
|
1764
|
+
broadcastEvent({ type: 'chat.message.created', sessionId: task.sessionId, messageId: message.id, timestamp: message.timestamp });
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
// Answer an agent question asked during execution
|
|
1768
|
+
server.post('/api/agent-question/:id/answer', async (req, reply) => {
|
|
1769
|
+
const { id } = req.params;
|
|
1770
|
+
const { answer } = req.body;
|
|
1771
|
+
const pending = pendingQuestions.get(id);
|
|
1772
|
+
if (!pending)
|
|
1773
|
+
return reply.status(404).send({ error: 'Question not found or already answered' });
|
|
1774
|
+
pendingQuestions.delete(id);
|
|
1775
|
+
broadcastEvent({
|
|
1776
|
+
type: 'agent.question.resolved',
|
|
1777
|
+
questionId: id,
|
|
1778
|
+
answer,
|
|
1779
|
+
timestamp: new Date().toISOString()
|
|
1780
|
+
});
|
|
1781
|
+
pending.resolve?.(answer);
|
|
1782
|
+
return { success: true };
|
|
1783
|
+
});
|
|
1784
|
+
// Current pending questions (for dashboard refresh)
|
|
1785
|
+
server.get('/api/agent-questions', async () => {
|
|
1786
|
+
return Array.from(pendingQuestions.values()).map(q => ({
|
|
1787
|
+
id: q.id, taskId: q.taskId, agentId: q.agentId, question: q.question, options: q.options, askedAt: q.askedAt
|
|
1788
|
+
}));
|
|
1789
|
+
});
|
|
1790
|
+
// ---- Permission Request Engine: REST surface for the dashboard ----
|
|
1791
|
+
// All permission requests (optionally filtered); pending ones drive the approval UI.
|
|
1792
|
+
server.get('/api/permissions', async (req) => {
|
|
1793
|
+
const { projectId, status } = req.query;
|
|
1794
|
+
permissionEngine.expireStaleRequests({
|
|
1795
|
+
liveTaskIds: new Set(db.getTasks().filter(t => t.status === 'running' || t.status === 'waiting_permission').map(t => t.id))
|
|
1796
|
+
});
|
|
1797
|
+
return db.getPermissionRequests({ projectId, status });
|
|
1798
|
+
});
|
|
1799
|
+
// Audit log.
|
|
1800
|
+
server.get('/api/permissions/audit', async (req) => {
|
|
1801
|
+
const { projectId, taskId } = req.query;
|
|
1802
|
+
return db.getPermissionAudit({ projectId, taskId });
|
|
1803
|
+
});
|
|
1804
|
+
// Resolve a pending permission request with an explicit user decision.
|
|
1805
|
+
server.post('/api/permissions/:id/resolve', async (req, reply) => {
|
|
1806
|
+
const { id } = req.params;
|
|
1807
|
+
const { decision, projectId, taskId, sessionId, comments } = req.body;
|
|
1808
|
+
const validDecisions = ['allow_once', 'allow_current_task', 'allow_current_session', 'deny'];
|
|
1809
|
+
if (!validDecisions.includes(decision)) {
|
|
1810
|
+
return reply.status(400).send({ error: `decision must be one of: ${validDecisions.join(', ')}` });
|
|
1811
|
+
}
|
|
1812
|
+
const request = db.getPermissionRequest(id);
|
|
1813
|
+
if (!request)
|
|
1814
|
+
return reply.status(404).send({ error: 'Permission request not found' });
|
|
1815
|
+
const result = await permissionEngine.resolve(id, decision, {
|
|
1816
|
+
projectId: projectId || request.projectId,
|
|
1817
|
+
taskId: taskId || request.taskId,
|
|
1818
|
+
sessionId: sessionId || request.sessionId,
|
|
1819
|
+
comments
|
|
1820
|
+
});
|
|
1821
|
+
if (!result.ok)
|
|
1822
|
+
return reply.status(409).send({ error: result.reason });
|
|
1823
|
+
// Surface the decision in the originating chat session.
|
|
1824
|
+
if (request.sessionId) {
|
|
1825
|
+
const message = {
|
|
1826
|
+
id: `msg-${Date.now()}-perm-${request.id}`,
|
|
1827
|
+
sessionId: request.sessionId,
|
|
1828
|
+
sender: 'supervisor',
|
|
1829
|
+
text: decision === 'deny'
|
|
1830
|
+
? `Permission DENIED: ${request.operation} on ${request.targetPath || request.detail}. Execution stopped at that step.`
|
|
1831
|
+
: `Permission APPROVED (${decision}): ${request.operation} on ${request.targetPath || request.detail}. Execution resumed.`,
|
|
1832
|
+
timestamp: new Date().toISOString()
|
|
1833
|
+
};
|
|
1834
|
+
db.saveChatMessage(message);
|
|
1835
|
+
broadcastEvent({ type: 'chat.message.created', sessionId: request.sessionId, messageId: message.id, timestamp: message.timestamp });
|
|
1836
|
+
}
|
|
1837
|
+
return result.request;
|
|
1838
|
+
});
|
|
1839
|
+
// Integration Agent
|
|
1840
|
+
server.post('/api/integrate', async (req, reply) => {
|
|
1841
|
+
const { projectId } = req.body;
|
|
1842
|
+
const project = db.getProject(projectId);
|
|
1843
|
+
if (!project)
|
|
1844
|
+
return reply.status(404).send({ error: 'Project not found' });
|
|
1845
|
+
const completedTasks = db.getTasks(projectId).filter(t => t.status === 'completed');
|
|
1846
|
+
if (completedTasks.length === 0) {
|
|
1847
|
+
return reply.status(400).send({ error: 'No completed tasks available to integrate' });
|
|
1848
|
+
}
|
|
1849
|
+
const { result, approvalRequest } = await integrationAgent.reviewAndIntegrate(project, completedTasks, 'main');
|
|
1850
|
+
db.saveIntegration(result);
|
|
1851
|
+
if (approvalRequest) {
|
|
1852
|
+
db.saveApproval(approvalRequest);
|
|
1853
|
+
broadcastEvent({
|
|
1854
|
+
type: 'approval.required',
|
|
1855
|
+
approvalId: approvalRequest.id,
|
|
1856
|
+
actionType: approvalRequest.actionType,
|
|
1857
|
+
timestamp: new Date().toISOString()
|
|
1858
|
+
});
|
|
1859
|
+
}
|
|
1860
|
+
broadcastEvent({
|
|
1861
|
+
type: 'integration.completed',
|
|
1862
|
+
projectId: project.id,
|
|
1863
|
+
summary: result.changelogSummary,
|
|
1864
|
+
timestamp: new Date().toISOString()
|
|
1865
|
+
});
|
|
1866
|
+
return { result, approvalRequest };
|
|
1867
|
+
});
|
|
1868
|
+
// Promoter Agent
|
|
1869
|
+
server.post('/api/promote', async (req, reply) => {
|
|
1870
|
+
const { projectId, mode, featureSummary, channels } = req.body;
|
|
1871
|
+
const project = db.getProject(projectId);
|
|
1872
|
+
if (!project)
|
|
1873
|
+
return reply.status(404).send({ error: 'Project not found' });
|
|
1874
|
+
const { promotion, approvalRequest } = await promoter.generatePromotion(project, mode || 'launch', featureSummary || 'Latest software improvements and features', channels || ['GitHub', 'LinkedIn', 'X/Twitter']);
|
|
1875
|
+
db.savePromotion(promotion);
|
|
1876
|
+
db.saveApproval(approvalRequest);
|
|
1877
|
+
broadcastEvent({
|
|
1878
|
+
type: 'promotion.generated',
|
|
1879
|
+
projectId: project.id,
|
|
1880
|
+
mode: promotion.mode,
|
|
1881
|
+
timestamp: new Date().toISOString()
|
|
1882
|
+
});
|
|
1883
|
+
broadcastEvent({
|
|
1884
|
+
type: 'approval.required',
|
|
1885
|
+
approvalId: approvalRequest.id,
|
|
1886
|
+
actionType: approvalRequest.actionType,
|
|
1887
|
+
timestamp: new Date().toISOString()
|
|
1888
|
+
});
|
|
1889
|
+
return { promotion, approvalRequest };
|
|
1890
|
+
});
|
|
1891
|
+
// Git diff of changes made by agent execution (working tree vs HEAD).
|
|
1892
|
+
// Returns the changed-file list and, per file, a unified patch for rendering.
|
|
1893
|
+
server.get('/api/git-diff', async (req) => {
|
|
1894
|
+
const { exec } = await import('node:child_process');
|
|
1895
|
+
const { promisify } = await import('node:util');
|
|
1896
|
+
const execAsync = promisify(exec);
|
|
1897
|
+
const projects = db.getProjects();
|
|
1898
|
+
const project = projects[0];
|
|
1899
|
+
if (!project)
|
|
1900
|
+
return { available: false, reason: 'No project registered', files: [] };
|
|
1901
|
+
const root = project.path;
|
|
1902
|
+
if (!fs.existsSync(path.join(root, '.git'))) {
|
|
1903
|
+
return { available: false, reason: 'Project is not a git repository', files: [] };
|
|
1904
|
+
}
|
|
1905
|
+
const run = async (args) => {
|
|
1906
|
+
const { stdout } = await execAsync(`git -C "${root}" ${args}`, { maxBuffer: 10 * 1024 * 1024 });
|
|
1907
|
+
return stdout;
|
|
1908
|
+
};
|
|
1909
|
+
try {
|
|
1910
|
+
// Include staged, unstaged and untracked changes.
|
|
1911
|
+
const statusOut = await run('status --porcelain');
|
|
1912
|
+
if (!statusOut.trim()) {
|
|
1913
|
+
return { available: true, files: [], summary: { added: 0, removed: 0, changed: 0 } };
|
|
1914
|
+
}
|
|
1915
|
+
const files = [];
|
|
1916
|
+
const seen = new Set();
|
|
1917
|
+
const parseNumstat = (numstat) => {
|
|
1918
|
+
const out = {};
|
|
1919
|
+
for (const line of numstat.split('\n')) {
|
|
1920
|
+
if (!line.trim())
|
|
1921
|
+
continue;
|
|
1922
|
+
const [a, d, p] = line.split('\t');
|
|
1923
|
+
out[p] = { adds: a === '-' ? 0 : parseInt(a, 10), dels: d === '-' ? 0 : parseInt(d, 10) };
|
|
1924
|
+
}
|
|
1925
|
+
return out;
|
|
1926
|
+
};
|
|
1927
|
+
// Unstaged + staged diffs vs HEAD
|
|
1928
|
+
const numstat = await run('diff HEAD --numstat');
|
|
1929
|
+
const patch = await run('diff HEAD --unified=3');
|
|
1930
|
+
const stats = parseNumstat(numstat);
|
|
1931
|
+
// Split the combined patch into per-file patches
|
|
1932
|
+
const perFile = {};
|
|
1933
|
+
let current = null;
|
|
1934
|
+
for (const line of patch.split('\n')) {
|
|
1935
|
+
const m = line.match(/^diff --git a\/(.+) b\/(.+)$/);
|
|
1936
|
+
if (m) {
|
|
1937
|
+
current = m[2];
|
|
1938
|
+
perFile[current] = line;
|
|
1939
|
+
continue;
|
|
1940
|
+
}
|
|
1941
|
+
if (current)
|
|
1942
|
+
perFile[current] += '\n' + line;
|
|
1943
|
+
}
|
|
1944
|
+
for (const [file, s] of Object.entries(stats)) {
|
|
1945
|
+
seen.add(file);
|
|
1946
|
+
files.push({ path: file, status: 'modified', additions: s.adds, deletions: s.dels, patch: perFile[file] || '' });
|
|
1947
|
+
}
|
|
1948
|
+
// Untracked files — show as fully-new content
|
|
1949
|
+
for (const line of statusOut.split('\n')) {
|
|
1950
|
+
if (!line.trim())
|
|
1951
|
+
continue;
|
|
1952
|
+
const code = line.slice(0, 2);
|
|
1953
|
+
const file = line.slice(3).trim().replace(/^"(.*)"$/, '$1');
|
|
1954
|
+
if (code !== '??' || seen.has(file))
|
|
1955
|
+
continue;
|
|
1956
|
+
let patch = '';
|
|
1957
|
+
let adds = 0;
|
|
1958
|
+
try {
|
|
1959
|
+
const content = fs.readFileSync(path.join(root, file), 'utf8');
|
|
1960
|
+
const lines = content.split('\n');
|
|
1961
|
+
adds = lines.length;
|
|
1962
|
+
patch = `diff --git a/${file} b/${file}\nnew file mode\n--- /dev/null\n+++ b/${file}\n` +
|
|
1963
|
+
lines.map(l => '+' + l).join('\n');
|
|
1964
|
+
}
|
|
1965
|
+
catch { /* binary or unreadable */ }
|
|
1966
|
+
files.push({ path: file, status: 'added', additions: adds, deletions: 0, patch });
|
|
1967
|
+
}
|
|
1968
|
+
const summary = {
|
|
1969
|
+
changed: files.length,
|
|
1970
|
+
added: files.reduce((s, f) => s + f.additions, 0),
|
|
1971
|
+
removed: files.reduce((s, f) => s + f.deletions, 0)
|
|
1972
|
+
};
|
|
1973
|
+
return { available: true, files, summary };
|
|
1974
|
+
}
|
|
1975
|
+
catch (err) {
|
|
1976
|
+
return { available: false, reason: err.message, files: [] };
|
|
1977
|
+
}
|
|
1978
|
+
});
|
|
1979
|
+
// Events
|
|
1980
|
+
server.get('/api/events', async () => {
|
|
1981
|
+
return db.getRecentEvents(50);
|
|
1982
|
+
});
|
|
1983
|
+
// ---- Validation: run the project's real test suite on demand ----
|
|
1984
|
+
server.post('/api/tests/run', async (req, reply) => {
|
|
1985
|
+
const { command } = req.body;
|
|
1986
|
+
const project = db.getProjects()[0];
|
|
1987
|
+
if (!project)
|
|
1988
|
+
return reply.status(400).send({ error: 'No project registered' });
|
|
1989
|
+
const runner = new workspace_tools_js_1.TestRunner(project.path);
|
|
1990
|
+
const detected = runner.detectTestCommand();
|
|
1991
|
+
if (!detected && !command) {
|
|
1992
|
+
return reply.status(400).send({ error: 'No test command detected for this project.' });
|
|
1993
|
+
}
|
|
1994
|
+
const result = await runner.run(command);
|
|
1995
|
+
broadcastEvent({
|
|
1996
|
+
type: 'tool.executed',
|
|
1997
|
+
agentId: 'user',
|
|
1998
|
+
tool: `test-run ${result.command}`,
|
|
1999
|
+
result: result.success ? 'passed' : `failed (exit ${result.exitCode})`,
|
|
2000
|
+
timestamp: new Date().toISOString()
|
|
2001
|
+
});
|
|
2002
|
+
return result;
|
|
2003
|
+
});
|
|
2004
|
+
// ---- Git workspace endpoints (real git operations on the project) ----
|
|
2005
|
+
server.get('/api/git/status', async (req, reply) => {
|
|
2006
|
+
const project = db.getProjects()[0];
|
|
2007
|
+
if (!project)
|
|
2008
|
+
return reply.status(400).send({ error: 'No project registered' });
|
|
2009
|
+
const root = project.path;
|
|
2010
|
+
if (!fs.existsSync(path.join(root, '.git')))
|
|
2011
|
+
return reply.status(200).send({ available: false, reason: 'Not a git repository' });
|
|
2012
|
+
const { exec } = await import('node:child_process');
|
|
2013
|
+
const { promisify } = await import('node:util');
|
|
2014
|
+
const run = promisify(exec);
|
|
2015
|
+
try {
|
|
2016
|
+
const [status, branch] = await Promise.all([
|
|
2017
|
+
run(`git -C "${root}" status --porcelain -b`, { maxBuffer: 10 * 1024 * 1024 }),
|
|
2018
|
+
run(`git -C "${root}" rev-parse --abbrev-ref HEAD`, { maxBuffer: 1024 * 1024 })
|
|
2019
|
+
]);
|
|
2020
|
+
const files = status.stdout.split('\n').filter(l => l.trim()).map(l => ({
|
|
2021
|
+
x: l.slice(0, 2).trim(), path: l.slice(3).trim().replace(/^"(.*)"$/, '$1')
|
|
2022
|
+
}));
|
|
2023
|
+
return {
|
|
2024
|
+
available: true,
|
|
2025
|
+
branch: branch.stdout.trim(),
|
|
2026
|
+
modified: files.filter(f => f.x.includes('M') || f.x === ' M'),
|
|
2027
|
+
staged: files.filter(f => f.x.length === 2 && !f.x.startsWith('??')),
|
|
2028
|
+
untracked: files.filter(f => f.x === '??')
|
|
2029
|
+
};
|
|
2030
|
+
}
|
|
2031
|
+
catch (err) {
|
|
2032
|
+
return reply.status(200).send({ available: false, reason: err.message });
|
|
2033
|
+
}
|
|
2034
|
+
});
|
|
2035
|
+
server.get('/api/git/log', async (req, reply) => {
|
|
2036
|
+
const project = db.getProjects()[0];
|
|
2037
|
+
if (!project)
|
|
2038
|
+
return reply.status(400).send({ error: 'No project registered' });
|
|
2039
|
+
const root = project.path;
|
|
2040
|
+
if (!fs.existsSync(path.join(root, '.git')))
|
|
2041
|
+
return reply.status(200).send({ available: false, commits: [] });
|
|
2042
|
+
const { exec } = await import('node:child_process');
|
|
2043
|
+
const { promisify } = await import('node:util');
|
|
2044
|
+
try {
|
|
2045
|
+
const { stdout } = await promisify(exec)(`git -C "${root}" log --pretty=format:%H|%h|%an|%aI|%s -n 50`, { maxBuffer: 10 * 1024 * 1024 });
|
|
2046
|
+
const commits = stdout.split('\n').filter(l => l.trim()).map(l => {
|
|
2047
|
+
const [hash, short, author, date, ...rest] = l.split('|');
|
|
2048
|
+
return { hash, short, author, date, message: rest.join('|') };
|
|
2049
|
+
});
|
|
2050
|
+
return { available: true, commits };
|
|
2051
|
+
}
|
|
2052
|
+
catch (err) {
|
|
2053
|
+
return reply.status(200).send({ available: false, reason: err.message, commits: [] });
|
|
2054
|
+
}
|
|
2055
|
+
});
|
|
2056
|
+
server.post('/api/git/commit', async (req, reply) => {
|
|
2057
|
+
const { message, includeAll } = req.body;
|
|
2058
|
+
if (!message?.trim())
|
|
2059
|
+
return reply.status(400).send({ error: 'Commit message is required.' });
|
|
2060
|
+
const project = db.getProjects()[0];
|
|
2061
|
+
if (!project)
|
|
2062
|
+
return reply.status(400).send({ error: 'No project registered' });
|
|
2063
|
+
const root = project.path;
|
|
2064
|
+
if (!fs.existsSync(path.join(root, '.git')))
|
|
2065
|
+
return reply.status(400).send({ error: 'Not a git repository' });
|
|
2066
|
+
const { exec } = await import('node:child_process');
|
|
2067
|
+
const { promisify } = await import('node:util');
|
|
2068
|
+
const run = promisify(exec);
|
|
2069
|
+
try {
|
|
2070
|
+
if (includeAll) {
|
|
2071
|
+
await run(`git -C "${root}" add -A`, { maxBuffer: 10 * 1024 * 1024 });
|
|
2072
|
+
}
|
|
2073
|
+
const { stdout } = await run(`git -C "${root}" commit -m "${message.replace(/"/g, '\\"')}"`, { maxBuffer: 10 * 1024 * 1024 });
|
|
2074
|
+
broadcastEvent({ type: 'system.log', level: 'info', message: `Git commit created: ${message.trim().slice(0, 80)}`, timestamp: new Date().toISOString() });
|
|
2075
|
+
return { success: true, output: stdout.trim() };
|
|
2076
|
+
}
|
|
2077
|
+
catch (err) {
|
|
2078
|
+
return reply.status(409).send({ error: err.message.includes('nothing to commit') ? 'Nothing to commit.' : err.message });
|
|
2079
|
+
}
|
|
2080
|
+
});
|
|
2081
|
+
server.post('/api/git/stage', async (req, reply) => {
|
|
2082
|
+
const { paths, action } = (req.body || {});
|
|
2083
|
+
const project = db.getProjects()[0];
|
|
2084
|
+
if (!project)
|
|
2085
|
+
return reply.status(400).send({ error: 'No project registered' });
|
|
2086
|
+
const root = project.path;
|
|
2087
|
+
if (!fs.existsSync(path.join(root, '.git')))
|
|
2088
|
+
return reply.status(400).send({ error: 'Not a git repository' });
|
|
2089
|
+
const { exec } = await import('node:child_process');
|
|
2090
|
+
const { promisify } = await import('node:util');
|
|
2091
|
+
const run = promisify(exec);
|
|
2092
|
+
try {
|
|
2093
|
+
const list = (paths || []).map(p => `"${p.replace(/"/g, '')}"`).join(' ');
|
|
2094
|
+
if (action === 'unstage') {
|
|
2095
|
+
await run(`git -C "${root}" reset HEAD -- ${list || '.'}`, { maxBuffer: 10 * 1024 * 1024 });
|
|
2096
|
+
}
|
|
2097
|
+
else {
|
|
2098
|
+
await run(`git -C "${root}" add ${list || '-A'}`, { maxBuffer: 10 * 1024 * 1024 });
|
|
2099
|
+
}
|
|
2100
|
+
return { success: true };
|
|
2101
|
+
}
|
|
2102
|
+
catch (err) {
|
|
2103
|
+
return reply.status(500).send({ error: err.message });
|
|
2104
|
+
}
|
|
2105
|
+
});
|
|
2106
|
+
server.get('/api/git/diff', async (req, reply) => {
|
|
2107
|
+
const project = db.getProjects()[0];
|
|
2108
|
+
if (!project)
|
|
2109
|
+
return reply.status(400).send({ error: 'No project registered' });
|
|
2110
|
+
const root = project.path;
|
|
2111
|
+
if (!fs.existsSync(path.join(root, '.git')))
|
|
2112
|
+
return reply.status(200).send({ available: false, reason: 'Not a git repository', files: [] });
|
|
2113
|
+
const { exec } = await import('node:child_process');
|
|
2114
|
+
const { promisify } = await import('node:util');
|
|
2115
|
+
try {
|
|
2116
|
+
const { stdout } = await promisify(exec)(`git -C "${root}" diff HEAD --unified=3`, { maxBuffer: 10 * 1024 * 1024 });
|
|
2117
|
+
const files = [];
|
|
2118
|
+
let current = null;
|
|
2119
|
+
for (const line of stdout.split('\n')) {
|
|
2120
|
+
const m = line.startsWith('+++ b/') ? line.slice(6).replace(/^"(.*)"$/, '$1') : null;
|
|
2121
|
+
if (m) {
|
|
2122
|
+
if (current)
|
|
2123
|
+
files.push(current);
|
|
2124
|
+
current = { path: m, patch: '' };
|
|
2125
|
+
}
|
|
2126
|
+
else if (current) {
|
|
2127
|
+
current.patch += line + '\n';
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
if (current)
|
|
2131
|
+
files.push(current);
|
|
2132
|
+
return { available: true, files };
|
|
2133
|
+
}
|
|
2134
|
+
catch (err) {
|
|
2135
|
+
return reply.status(200).send({ available: false, reason: err.message, files: [] });
|
|
2136
|
+
}
|
|
2137
|
+
});
|
|
2138
|
+
server.post('/api/git/push', async (req, reply) => {
|
|
2139
|
+
const project = db.getProjects()[0];
|
|
2140
|
+
if (!project)
|
|
2141
|
+
return reply.status(400).send({ error: 'No project registered' });
|
|
2142
|
+
const root = project.path;
|
|
2143
|
+
if (!fs.existsSync(path.join(root, '.git')))
|
|
2144
|
+
return reply.status(400).send({ error: 'Not a git repository' });
|
|
2145
|
+
const { exec } = await import('node:child_process');
|
|
2146
|
+
const { promisify } = await import('node:util');
|
|
2147
|
+
try {
|
|
2148
|
+
const { stdout, stderr } = await promisify(exec)(`git -C "${root}" push`, { maxBuffer: 10 * 1024 * 1024, timeout: 60000 });
|
|
2149
|
+
broadcastEvent({ type: 'system.log', level: 'info', message: 'Git push completed', timestamp: new Date().toISOString() });
|
|
2150
|
+
return { success: true, output: (stdout + stderr).trim() };
|
|
2151
|
+
}
|
|
2152
|
+
catch (err) {
|
|
2153
|
+
return reply.status(409).send({ error: (err.stderr || err.message || 'Push failed') });
|
|
2154
|
+
}
|
|
2155
|
+
});
|
|
2156
|
+
// ---- Project flow graph (context file mapping what relates to what) ----
|
|
2157
|
+
server.get('/api/flow-graph', async (req, reply) => {
|
|
2158
|
+
const project = db.getProjects()[0];
|
|
2159
|
+
if (!project)
|
|
2160
|
+
return reply.status(400).send({ error: 'No project registered' });
|
|
2161
|
+
const p = (0, projectFlowGraph_js_1.flowGraphPath)(project.path);
|
|
2162
|
+
if (!fs.existsSync(p)) {
|
|
2163
|
+
try {
|
|
2164
|
+
await (0, projectFlowGraph_js_1.generateFlowGraphFile)(project.path, db.getTasks());
|
|
2165
|
+
}
|
|
2166
|
+
catch (err) {
|
|
2167
|
+
return reply.status(500).send({ error: err.message });
|
|
2168
|
+
}
|
|
2169
|
+
}
|
|
2170
|
+
if (!fs.existsSync(p))
|
|
2171
|
+
return reply.status(404).send({ error: 'Flow graph not generated' });
|
|
2172
|
+
return reply.type('text/markdown').send(fs.readFileSync(p, 'utf8'));
|
|
2173
|
+
});
|
|
2174
|
+
server.post('/api/flow-graph/refresh', async (req, reply) => {
|
|
2175
|
+
const project = db.getProjects()[0];
|
|
2176
|
+
if (!project)
|
|
2177
|
+
return reply.status(400).send({ error: 'No project registered' });
|
|
2178
|
+
try {
|
|
2179
|
+
const out = await (0, projectFlowGraph_js_1.generateFlowGraphFile)(project.path, db.getTasks());
|
|
2180
|
+
return { success: true, path: out };
|
|
2181
|
+
}
|
|
2182
|
+
catch (err) {
|
|
2183
|
+
return reply.status(500).send({ error: err.message });
|
|
2184
|
+
}
|
|
2185
|
+
});
|
|
2186
|
+
// Self-heal: drop any previously registered project that points inside the
|
|
2187
|
+
// VibeCodePilot data folder (e.g. an old default sample registration) so
|
|
2188
|
+
// the auto-detected consumer project root takes over.
|
|
2189
|
+
const staleProjects = db
|
|
2190
|
+
.getProjects()
|
|
2191
|
+
.filter(p => path.resolve(p.path).startsWith(path.resolve(DATA_DIR)));
|
|
2192
|
+
for (const stale of staleProjects) {
|
|
2193
|
+
db.deleteProject(stale.id);
|
|
2194
|
+
console.log(`Removed stale default project registration: ${stale.name} (${stale.path})`);
|
|
2195
|
+
}
|
|
2196
|
+
// Create default project if none exist.
|
|
2197
|
+
// The project dir must be the user's project ROOT (never a subfolder of
|
|
2198
|
+
// when VibeCodePilot is npm-installed there) — never a subfolder of VibeCodePilot's own data dir.
|
|
2199
|
+
if (db.getProjects().length === 0) {
|
|
2200
|
+
const resolvedRoot = resolveUserProjectRoot();
|
|
2201
|
+
let defaultProjDir;
|
|
2202
|
+
let defaultProjName;
|
|
2203
|
+
if (resolvedRoot) {
|
|
2204
|
+
defaultProjDir = resolvedRoot;
|
|
2205
|
+
defaultProjName = path.basename(defaultProjDir);
|
|
2206
|
+
}
|
|
2207
|
+
else {
|
|
2208
|
+
// Last resort: scaffold a sample project (previous behaviour).
|
|
2209
|
+
const fallbackDir = path.join(PROJECTS_DIR, 'sample-project');
|
|
2210
|
+
if (!fs.existsSync(fallbackDir)) {
|
|
2211
|
+
fs.mkdirSync(fallbackDir, { recursive: true });
|
|
2212
|
+
fs.writeFileSync(path.join(fallbackDir, 'package.json'), JSON.stringify({
|
|
2213
|
+
name: 'sample-project',
|
|
2214
|
+
version: '0.1.0',
|
|
2215
|
+
dependencies: {
|
|
2216
|
+
'react': '^18.3.1',
|
|
2217
|
+
'fastify': '^5.0.0',
|
|
2218
|
+
'typescript': '^5.0.0'
|
|
2219
|
+
}
|
|
2220
|
+
}, null, 2));
|
|
2221
|
+
}
|
|
2222
|
+
defaultProjDir = fallbackDir;
|
|
2223
|
+
defaultProjName = 'Sample Project';
|
|
2224
|
+
}
|
|
2225
|
+
db.saveProject({
|
|
2226
|
+
id: `proj-${defaultProjName.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`,
|
|
2227
|
+
name: defaultProjName,
|
|
2228
|
+
path: defaultProjDir,
|
|
2229
|
+
description: `Project at ${defaultProjDir}`,
|
|
2230
|
+
detectedTechnologies: (0, tech_detector_js_1.detectTechnologies)(defaultProjDir),
|
|
2231
|
+
assignedSpecialists: ['specialist-backend', 'specialist-frontend'],
|
|
2232
|
+
createdAt: new Date().toISOString(),
|
|
2233
|
+
updatedAt: new Date().toISOString()
|
|
2234
|
+
});
|
|
2235
|
+
}
|
|
2236
|
+
// Usage & Context Monitor API
|
|
2237
|
+
server.get('/api/monitor/usage', async (req) => {
|
|
2238
|
+
const { scope } = req.query;
|
|
2239
|
+
return {
|
|
2240
|
+
summaries: monitor.allSummaries(scope),
|
|
2241
|
+
contexts: monitor.allContexts(scope)
|
|
2242
|
+
};
|
|
2243
|
+
});
|
|
2244
|
+
server.get('/api/monitor/usage/records', async (req) => {
|
|
2245
|
+
const { scope = 'chat', instanceId = '', limit = '100' } = req.query;
|
|
2246
|
+
return monitor.recordsFor(scope, instanceId, Number(limit) || 100);
|
|
2247
|
+
});
|
|
2248
|
+
server.get('/api/monitor/system', async () => {
|
|
2249
|
+
return (0, monitorService_js_1.getSystemUsage)(gateway.getEndpoint());
|
|
2250
|
+
});
|
|
2251
|
+
server.get('/api/monitor/context/:scope/:instanceId', async (req) => {
|
|
2252
|
+
const { scope, instanceId } = req.params;
|
|
2253
|
+
return monitor.contextStatus(scope, instanceId);
|
|
2254
|
+
});
|
|
2255
|
+
await server.listen({ port: PORT, host: HOST });
|
|
2256
|
+
console.log(`VibeCodePilot Fastify & WebSocket server listening on http://${HOST === '0.0.0.0' ? 'localhost' : HOST}:${PORT}`);
|
|
2257
|
+
}
|
|
2258
|
+
startServer().catch(err => {
|
|
2259
|
+
console.error('Failed to start VibeCodePilot server:', err);
|
|
2260
|
+
process.exit(1);
|
|
2261
|
+
});
|
|
2262
|
+
//# sourceMappingURL=index.js.map
|