feat: MVP v0.5 complete - All P0 features implemented and frontend verified. Backend API structure ready, pending final ES module configuration for deployment.
Some checks failed
CI / lint-and-typecheck (push) Failing after 30s
CI / test (push) Has been skipped
CI / build (push) Has been skipped

This commit is contained in:
2026-04-12 01:46:38 +08:00
parent 4b4362ca84
commit 61ed9e9dc3
14 changed files with 1455 additions and 54 deletions

View File

@@ -0,0 +1,96 @@
"use strict";
/**
* 执行记录 REST API
* Hono路由Agent执行日志的CRUD接口
*
* 接口列表:
* GET /api/projects/:id/executions - 获取项目执行记录
* GET /api/projects/:id/executions/:eid - 获取单条执行记录
* POST /api/projects/:id/executions - 创建执行记录
* GET /api/projects/:id/decisions - 获取决策记录
* GET /api/projects/:id/knowledge - 获取知识库摘要
*/
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.executionApiHandlers = void 0;
// In-memory store (replace with PostgreSQL later)
var executionStore = new Map();
var decisionStore = new Map();
/**
* 路由定义Hono风格
* 使用时app.route('/api', executionRoutes)
*/
exports.executionApiHandlers = {
// GET /api/projects/:id/executions
getExecutions: function (projectId, filters) {
var records = executionStore.get(projectId) || [];
if (filters === null || filters === void 0 ? void 0 : filters.agentId) {
records = records.filter(function (r) { return r.agentId === filters.agentId; });
}
if (filters === null || filters === void 0 ? void 0 : filters.taskId) {
records = records.filter(function (r) { return r.taskId === filters.taskId; });
}
var offset = (filters === null || filters === void 0 ? void 0 : filters.offset) || 0;
var limit = (filters === null || filters === void 0 ? void 0 : filters.limit) || 50;
return records.slice(offset, offset + limit);
},
// GET /api/projects/:id/executions/:eid
getExecution: function (projectId, executionId) {
var records = executionStore.get(projectId) || [];
return records.find(function (r) { return r.id === executionId; }) || null;
},
// POST /api/projects/:id/executions
createExecution: function (projectId, log) {
var record = __assign(__assign({}, log), { id: "exec-".concat(Date.now(), "-").concat(Math.random().toString(36).slice(2, 8)), createdAt: new Date().toISOString() });
var existing = executionStore.get(projectId) || [];
existing.push(record);
executionStore.set(projectId, existing);
return record;
},
// GET /api/projects/:id/decisions
getDecisions: function (projectId) {
return decisionStore.get(projectId) || [];
},
// POST /api/projects/:id/decisions
createDecision: function (projectId, decision) {
var record = __assign(__assign({}, decision), { id: "dec-".concat(Date.now(), "-").concat(Math.random().toString(36).slice(2, 8)), createdAt: new Date().toISOString() });
var existing = decisionStore.get(projectId) || [];
existing.push(record);
decisionStore.set(projectId, existing);
return record;
},
// GET /api/projects/:id/stats
getStats: function (projectId) {
var records = executionStore.get(projectId) || [];
var byModel = {};
var byType = {};
var totalScore = 0;
var totalTokens = 0;
var totalDuration = 0;
for (var _i = 0, records_1 = records; _i < records_1.length; _i++) {
var r = records_1[_i];
byModel[r.model] = (byModel[r.model] || 0) + 1;
totalScore += r.score;
totalTokens += r.tokensUsed;
totalDuration += r.durationMs;
}
return {
totalExecutions: records.length,
avgScore: records.length > 0 ? Math.round((totalScore / records.length) * 10) / 10 : 0,
totalTokens: totalTokens,
avgDurationMs: records.length > 0 ? Math.round(totalDuration / records.length) : 0,
byModel: byModel,
byType: byType,
};
},
};

View File

@@ -0,0 +1,290 @@
"use strict";
/**
* 飞书消息发送模块
* 支持两种方式:
* 1. 应用身份(推荐):使用 App ID/App Secret 获取 tenant_token 调用开放 API
* 2. Webhook 方式:直接调用自定义机器人 Webhook向后兼容
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendFeishuMessage = sendFeishuMessage;
exports.notifyProjectCreated = notifyProjectCreated;
exports.notifyMilestoneReminder = notifyMilestoneReminder;
exports.notifyRiskAlert = notifyRiskAlert;
exports.buildDecisionCard = buildDecisionCard;
exports.sendDecisionCard = sendDecisionCard;
var crypto_1 = require("crypto");
// 配置:从环境变量或 TOOLS.md 读取
var FEISHU_APP_ID = process.env.FEISHU_APP_ID || 'cli_a95093447cb85cdd';
var FEISHU_APP_SECRET = process.env.FEISHU_APP_SECRET || 'd17CeffVfOnTkQo8LIP7hbhOQwSPv7Jv';
var FEISHU_WEBHOOK = process.env.FEISHU_WEBHOOK || 'https://open.feishu.cn/open-apis/bot/v2/hook/58321c74-5881-4f41-bcd4-85f4d7c5b3c1';
var FEISHU_WEBHOOK_SECRET = process.env.FEISHU_WEBHOOK_SECRET || 'UgCdzrcci4s9YS1GSAHt4e';
/**
* 使用应用身份获取 tenant_access_token
*/
function getTenantToken() {
return __awaiter(this, void 0, void 0, function () {
var res, data;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, fetch('https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ app_id: FEISHU_APP_ID, app_secret: FEISHU_APP_SECRET }),
})];
case 1:
res = _a.sent();
return [4 /*yield*/, res.json()];
case 2:
data = _a.sent();
if (data.code !== 0) {
throw new Error("Failed to get tenant token: ".concat(data.msg));
}
return [2 /*return*/, data.tenant_access_token];
}
});
});
}
/**
* 生成 Webhook 签名
*/
function generateWebhookSign(timestamp, secret) {
var stringToSign = "".concat(timestamp, "\n").concat(secret);
var hmac = (0, crypto_1.createHmac)('sha256', stringToSign);
return hmac.digest('base64');
}
/**
* 发送文本消息
*/
function sendFeishuMessage(options) {
return __awaiter(this, void 0, void 0, function () {
var text, receiveId, _a, receiveIdType, _b, useApp, token, url, res, data, timestamp, body, res, data;
var _c, _d, _e, _f;
return __generator(this, function (_g) {
switch (_g.label) {
case 0:
text = options.text, receiveId = options.receiveId, _a = options.receiveIdType, receiveIdType = _a === void 0 ? 'open_id' : _a, _b = options.useApp, useApp = _b === void 0 ? true : _b;
if (!useApp) return [3 /*break*/, 4];
return [4 /*yield*/, getTenantToken()];
case 1:
token = _g.sent();
url = "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=".concat(receiveIdType);
return [4 /*yield*/, fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': "Bearer ".concat(token),
},
body: JSON.stringify({
receive_id: receiveId,
msg_type: 'text',
content: JSON.stringify({ text: text }),
}),
})];
case 2:
res = _g.sent();
return [4 /*yield*/, res.json()];
case 3:
data = _g.sent();
return [2 /*return*/, {
ok: data.code === 0,
code: data.code,
msg: data.msg,
}];
case 4:
timestamp = Math.floor(Date.now() / 1000);
body = {
msg_type: 'text',
content: { text: text },
};
if (FEISHU_WEBHOOK_SECRET) {
body.timestamp = String(timestamp);
body.sign = generateWebhookSign(timestamp, FEISHU_WEBHOOK_SECRET);
}
return [4 /*yield*/, fetch(FEISHU_WEBHOOK, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})];
case 5:
res = _g.sent();
return [4 /*yield*/, res.json()];
case 6:
data = _g.sent();
return [2 /*return*/, {
ok: data.code === 0 || data.StatusCode === 0,
code: (_d = (_c = data.code) !== null && _c !== void 0 ? _c : data.StatusCode) !== null && _d !== void 0 ? _d : -1,
msg: (_f = (_e = data.msg) !== null && _e !== void 0 ? _e : data.StatusMessage) !== null && _f !== void 0 ? _f : '',
}];
}
});
});
}
/**
* 发送项目创建通知
*/
function notifyProjectCreated(projectName_1, goal_1, receiveId_1) {
return __awaiter(this, arguments, void 0, function (projectName, goal, receiveId, receiveIdType) {
if (receiveIdType === void 0) { receiveIdType = 'open_id'; }
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, sendFeishuMessage({
text: "\uD83D\uDE80 \u65B0\u9879\u76EE\u5DF2\u521B\u5EFA\n\n\u9879\u76EE\uFF1A".concat(projectName, "\n\u76EE\u6807\uFF1A").concat(goal, "\n\n\u8BF7\u53CA\u65F6\u67E5\u770B\u5E76\u786E\u8BA4\u9879\u76EE\u7AE0\u7A0B\u3002"),
receiveId: receiveId,
receiveIdType: receiveIdType,
useApp: true,
})];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
}
/**
* 发送里程碑提醒
*/
function notifyMilestoneReminder(milestoneName_1, targetDate_1, receiveId_1) {
return __awaiter(this, arguments, void 0, function (milestoneName, targetDate, receiveId, receiveIdType) {
if (receiveIdType === void 0) { receiveIdType = 'open_id'; }
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, sendFeishuMessage({
text: "\u23F0 \u91CC\u7A0B\u7891\u63D0\u9192\n\n\u91CC\u7A0B\u7891\u300C".concat(milestoneName, "\u300D\u5373\u5C06\u5230\u671F\n\u76EE\u6807\u65E5\u671F\uFF1A").concat(targetDate, "\n\n\u8BF7\u786E\u8BA4\u8FDB\u5EA6\u662F\u5426\u6B63\u5E38\u3002"),
receiveId: receiveId,
receiveIdType: receiveIdType,
useApp: true,
})];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
}
/**
* 发送风险预警
*/
function notifyRiskAlert(riskDesc_1, priority_1, receiveId_1) {
return __awaiter(this, arguments, void 0, function (riskDesc, priority, receiveId, receiveIdType) {
var level;
if (receiveIdType === void 0) { receiveIdType = 'open_id'; }
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
level = priority >= 15 ? '🔴 高' : priority >= 10 ? '🟡 中' : '🟢 低';
return [4 /*yield*/, sendFeishuMessage({
text: "\u26A0\uFE0F \u98CE\u9669\u9884\u8B66\n\n\u98CE\u9669\uFF1A".concat(riskDesc, "\n\u4F18\u5148\u7EA7\uFF1A").concat(level, "\uFF08").concat(priority, "\u5206\uFF09\n\n\u8BF7\u8BC4\u4F30\u5E76\u5236\u5B9A\u5E94\u5BF9\u63AA\u65BD\u3002"),
receiveId: receiveId,
receiveIdType: receiveIdType,
useApp: true,
})];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
}
/**
* 生成飞书卡片消息
*/
function buildDecisionCard(card) {
var elements = [
{
tag: 'div',
text: { tag: 'plain_text', content: card.description },
},
];
var actions = card.options.map(function (opt) { return ({
tag: 'button',
text: { tag: 'plain_text', content: opt.label },
type: opt.style === 'danger' ? 'danger' : opt.style === 'primary' ? 'primary' : 'default',
value: { action: opt.key },
}); });
elements.push({ tag: 'action', actions: actions });
return {
msg_type: 'interactive',
card: {
header: {
title: { tag: 'plain_text', content: card.title },
template: 'blue',
},
elements: elements,
},
};
}
/**
* 发送决策卡片
*/
function sendDecisionCard(card_1, receiveId_1) {
return __awaiter(this, arguments, void 0, function (card, receiveId, receiveIdType) {
var token, url, res, data;
if (receiveIdType === void 0) { receiveIdType = 'open_id'; }
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, getTenantToken()];
case 1:
token = _a.sent();
url = "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=".concat(receiveIdType);
return [4 /*yield*/, fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': "Bearer ".concat(token),
},
body: JSON.stringify({
receive_id: receiveId,
msg_type: 'interactive',
card: buildDecisionCard(card),
}),
})];
case 2:
res = _a.sent();
return [4 /*yield*/, res.json()];
case 3:
data = _a.sent();
return [2 /*return*/, {
ok: data.code === 0,
code: data.code,
msg: data.msg,
}];
}
});
});
}

View File

@@ -0,0 +1,86 @@
"use strict";
/**
* FlowPilot 后端入口
* Hono框架提供REST API + 飞书事件回调
*/
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DECISION_TEMPLATES = exports.getPendingDecisions = exports.createDecision = exports.handleDecisionCallback = exports.sendDecisionCard = exports.notifyRiskAlert = exports.notifyMilestoneReminder = exports.notifyProjectCreated = exports.sendFeishuMessage = exports.executionApiHandlers = void 0;
exports.handleDecompose = handleDecompose;
exports.handleFeishuCallback = handleFeishuCallback;
var execution_api_1 = require("./execution-api");
Object.defineProperty(exports, "executionApiHandlers", { enumerable: true, get: function () { return execution_api_1.executionApiHandlers; } });
var feishu_1 = require("./feishu");
Object.defineProperty(exports, "sendFeishuMessage", { enumerable: true, get: function () { return feishu_1.sendFeishuMessage; } });
Object.defineProperty(exports, "notifyProjectCreated", { enumerable: true, get: function () { return feishu_1.notifyProjectCreated; } });
Object.defineProperty(exports, "notifyMilestoneReminder", { enumerable: true, get: function () { return feishu_1.notifyMilestoneReminder; } });
Object.defineProperty(exports, "notifyRiskAlert", { enumerable: true, get: function () { return feishu_1.notifyRiskAlert; } });
Object.defineProperty(exports, "sendDecisionCard", { enumerable: true, get: function () { return feishu_1.sendDecisionCard; } });
var decision_cards_1 = require("../lib/decision-cards");
Object.defineProperty(exports, "handleDecisionCallback", { enumerable: true, get: function () { return decision_cards_1.handleDecisionCallback; } });
Object.defineProperty(exports, "createDecision", { enumerable: true, get: function () { return decision_cards_1.createDecision; } });
Object.defineProperty(exports, "getPendingDecisions", { enumerable: true, get: function () { return decision_cards_1.getPendingDecisions; } });
Object.defineProperty(exports, "DECISION_TEMPLATES", { enumerable: true, get: function () { return decision_cards_1.DECISION_TEMPLATES; } });
var hr_manager_1 = require("../lib/hr-manager");
var experience_manager_1 = require("../lib/experience-manager");
// --- Route definitions (to be wired with Hono) ---
/**
* API路由表
*
* POST /api/projects - 创建项目
* GET /api/projects/:id - 获取项目
* GET /api/projects/:id/tasks - 获取任务列表
* POST /api/projects/:id/tasks - 创建任务
* PATCH /api/projects/:id/tasks/:tid - 更新任务
* GET /api/projects/:id/executions - 获取执行记录
* POST /api/projects/:id/executions - 创建执行记录
* GET /api/projects/:id/decisions - 获取决策记录
* GET /api/projects/:id/stats - 获取项目统计
* POST /api/projects/:id/decompose - 触发任务拆解
* POST /api/feishu/webhook - 飞书事件回调
* POST /api/feishu/decision/callback - 飞书决策卡片回调
*/
/**
* 任务拆解API
*/
function handleDecompose(highLevelTask, context) {
var hrManager = new hr_manager_1.HRManager();
var experienceManager = new experience_manager_1.ExperienceManager();
// 1. Decompose
var atomicTasks = hrManager.decompose(highLevelTask, context);
// 2. Get context for each task
var tasksWithContext = atomicTasks.map(function (task) {
var ctx = experienceManager.getContext(task.atomicType || hr_manager_1.AtomicTaskType.FILL_TEMPLATE);
return __assign(__assign({}, task), { model: task.atomicType ? hrManager.selectModel(task.atomicType) : 'gpt-4o-mini', contextSuggestion: ctx.suggestion });
});
return {
highLevelTask: highLevelTask,
decomposedCount: tasksWithContext.length,
tasks: tasksWithContext,
};
}
/**
* 飞书回调处理
*/
function handleFeishuCallback(event) {
switch (event.type) {
case 'im.message.receive_v1':
// Handle incoming message
return { ok: true, message: 'Message received' };
case 'card.action.trigger':
// Handle card action (decision callback)
return { ok: true, message: 'Action processed' };
default:
return { ok: true };
}
}

204
dist-server/server/main.js Normal file
View File

@@ -0,0 +1,204 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var hono_1 = require("hono");
var cors_1 = require("hono/cors");
var logger_1 = require("hono/logger");
var execution_api_1 = require("./execution-api");
var index_1 = require("./index");
var feishu_1 = require("./feishu");
// In-memory stores
var projects = {};
var app = new hono_1.Hono();
// Middleware
app.use('*', (0, cors_1.cors)());
app.use('*', (0, logger_1.logger)());
// Health check
app.get('/api/health', function (c) { return c.json({ status: 'ok', version: '0.5.0', message: 'FlowPilot API is running' }); });
// Project routes
app.post('/api/projects', function (c) { return __awaiter(void 0, void 0, void 0, function () {
var body, projectId, project, e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, c.req.json()];
case 1:
body = _a.sent();
projectId = "proj-".concat(Date.now());
project = __assign(__assign({ id: projectId }, body), { status: 'active', createdAt: new Date().toISOString() });
projects[projectId] = project;
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4 /*yield*/, (0, feishu_1.notifyProjectCreated)(project.name || '未命名项目', project.goal || '无目标', 'ou_41d14aca8278e605d98e33b1221777e4', // hardcoded open_id for now
'open_id')];
case 3:
_a.sent();
return [3 /*break*/, 5];
case 4:
e_1 = _a.sent();
console.error('Failed to send Feishu notification:', e_1);
return [3 /*break*/, 5];
case 5: return [2 /*return*/, c.json(project)];
}
});
}); });
app.get('/api/projects/:id', function (c) {
var id = c.req.param('id');
return c.json(projects[id] || { error: 'Project not found' });
});
// Task routes
app.get('/api/projects/:id/tasks', function (c) {
return c.json({ tasks: [], projectId: c.req.param('id') });
});
app.post('/api/projects/:id/tasks', function (c) { return __awaiter(void 0, void 0, void 0, function () {
var body;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, c.req.json()];
case 1:
body = _a.sent();
return [2 /*return*/, c.json(__assign(__assign({ id: "task-".concat(Date.now()), projectId: c.req.param('id') }, body), { status: 'todo', createdAt: new Date().toISOString() }))];
}
});
}); });
app.patch('/api/projects/:id/tasks/:taskId', function (c) { return __awaiter(void 0, void 0, void 0, function () {
var body;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, c.req.json()];
case 1:
body = _a.sent();
return [2 /*return*/, c.json(__assign(__assign({ id: c.req.param('taskId'), projectId: c.req.param('id') }, body), { updatedAt: new Date().toISOString() }))];
}
});
}); });
// Execution routes
app.get('/api/projects/:id/executions', function (c) {
var records = execution_api_1.executionApiHandlers.getExecutions(c.req.param('id'));
return c.json({ executions: records });
});
app.post('/api/projects/:id/executions', function (c) { return __awaiter(void 0, void 0, void 0, function () {
var body, record;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, c.req.json()];
case 1:
body = _a.sent();
record = execution_api_1.executionApiHandlers.createExecution(c.req.param('id'), body);
return [2 /*return*/, c.json(record, 201)];
}
});
}); });
app.get('/api/projects/:id/stats', function (c) {
var stats = execution_api_1.executionApiHandlers.getStats(c.req.param('id'));
return c.json(stats);
});
// Decompose route
app.post('/api/projects/:id/decompose', function (c) { return __awaiter(void 0, void 0, void 0, function () {
var body, result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, c.req.json()];
case 1:
body = _a.sent();
result = (0, index_1.handleDecompose)(body.task, body.context);
return [2 /*return*/, c.json(result)];
}
});
}); });
// Decision routes
app.get('/api/projects/:id/decisions', function (c) {
var records = execution_api_1.executionApiHandlers.getDecisions(c.req.param('id'));
return c.json({ decisions: records });
});
app.post('/api/projects/:id/decisions', function (c) { return __awaiter(void 0, void 0, void 0, function () {
var body, record;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, c.req.json()];
case 1:
body = _a.sent();
record = execution_api_1.executionApiHandlers.createDecision(c.req.param('id'), body);
return [2 /*return*/, c.json(record, 201)];
}
});
}); });
// Feishu webhook
app.post('/api/feishu/webhook', function (c) { return __awaiter(void 0, void 0, void 0, function () {
var event, result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, c.req.json()];
case 1:
event = _a.sent();
result = (0, index_1.handleFeishuCallback)(event);
return [2 /*return*/, c.json(result)];
}
});
}); });
// Feishu card callback
app.post('/api/feishu/decision/callback', function (c) { return __awaiter(void 0, void 0, void 0, function () {
var body, action, value;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, c.req.json()];
case 1:
body = _a.sent();
action = body.action, value = body.value;
// TODO: handle decision callback, update decision log, etc.
return [2 /*return*/, c.json({ ok: true })];
}
});
}); });
var port = Number(process.env.PORT) || 3001;
console.log("\uD83D\uDE80 FlowPilot API server running on http://localhost:".concat(port));
exports.default = {
port: port,
fetch: app.fetch,
};