c0de-agent 1.11.0 → 1.12.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/README.md +24 -5
- package/dist/cli/commands/chat.js +87 -1
- package/dist/cli/commands/config.js +17 -3
- package/dist/cli/commands/sessions.js +62 -3
- package/dist/cli/index.js +26 -7
- package/dist/cli/modes/print.js +9 -2
- package/dist/core/compact.d.ts +2 -0
- package/dist/core/compact.js +1 -0
- package/dist/core/config.d.ts +11 -2
- package/dist/core/config.js +73 -6
- package/dist/core/loop/compaction.d.ts +2 -1
- package/dist/core/loop/compaction.js +19 -6
- package/dist/core/loop/stream-collect.js +9 -1
- package/dist/core/loop/subagent.js +23 -5
- package/dist/core/redact.d.ts +11 -0
- package/dist/core/redact.js +49 -0
- package/dist/core/slash.js +93 -51
- package/dist/core/title.js +7 -1
- package/dist/core/types.d.ts +2 -0
- package/dist/db/schema.d.ts +17 -0
- package/dist/db/schema.js +3 -1
- package/dist/kanban/index.d.ts +1 -1
- package/dist/kanban/index.js +1 -1
- package/dist/kanban/store.d.ts +5 -1
- package/dist/kanban/store.js +76 -2
- package/dist/llm/index.d.ts +1 -1
- package/dist/llm/index.js +1 -1
- package/dist/llm/provider.js +1 -1
- package/dist/llm/retry.d.ts +5 -2
- package/dist/llm/retry.js +6 -5
- package/dist/llm/routing.d.ts +24 -1
- package/dist/llm/routing.js +29 -1
- package/dist/project/index.d.ts +1 -1
- package/dist/project/index.js +1 -1
- package/dist/project/project.d.ts +14 -0
- package/dist/project/project.js +77 -1
- package/dist/server/agent-manager.d.ts +10 -1
- package/dist/server/agent-manager.js +14 -1
- package/dist/server/auth-manager.d.ts +11 -5
- package/dist/server/auth-manager.js +39 -20
- package/dist/server/context.js +3 -0
- package/dist/server/permission/interactive.d.ts +6 -3
- package/dist/server/permission/interactive.js +20 -4
- package/dist/server/permission/store.d.ts +12 -2
- package/dist/server/permission/store.js +31 -3
- package/dist/server/registry-config.d.ts +14 -0
- package/dist/server/registry-config.js +44 -0
- package/dist/server/routes/auth.js +32 -2
- package/dist/server/routes/chat.d.ts +12 -0
- package/dist/server/routes/chat.js +216 -38
- package/dist/server/routes/commands.d.ts +4 -2
- package/dist/server/routes/commands.js +10 -3
- package/dist/server/routes/config.js +103 -23
- package/dist/server/routes/files.js +22 -4
- package/dist/server/routes/kanban.js +68 -6
- package/dist/server/routes/permissions.d.ts +0 -4
- package/dist/server/routes/permissions.js +133 -7
- package/dist/server/routes/project.js +59 -10
- package/dist/server/routes/provider.js +48 -3
- package/dist/server/routes/session.js +298 -22
- package/dist/server/routes/update.d.ts +11 -5
- package/dist/server/routes/update.js +88 -28
- package/dist/server/server.d.ts +4 -12
- package/dist/server/server.js +198 -102
- package/dist/server/types.d.ts +7 -0
- package/dist/session/archive.d.ts +3 -1
- package/dist/session/archive.js +13 -1
- package/dist/session/branch.js +20 -2
- package/dist/session/import.d.ts +44 -0
- package/dist/session/import.js +83 -0
- package/dist/session/index.d.ts +1 -1
- package/dist/session/index.js +1 -1
- package/dist/session/jobs.d.ts +12 -0
- package/dist/session/jobs.js +53 -0
- package/dist/session/message.d.ts +7 -1
- package/dist/session/message.js +21 -1
- package/dist/session/session.d.ts +128 -11
- package/dist/session/session.js +461 -30
- package/dist/session/snapshot.d.ts +5 -2
- package/dist/session/snapshot.js +10 -2
- package/dist/session/types.d.ts +11 -1
- package/dist/shared/types/agent.d.ts +11 -0
- package/dist/shared/types/config.d.ts +5 -1
- package/dist/shared/types/kanban.d.ts +13 -0
- package/dist/shared/types/message.d.ts +9 -0
- package/dist/tools/websearch/index.js +6 -3
- package/dist/update/index.d.ts +3 -3
- package/dist/update/index.js +2 -2
- package/dist/update/ipc.d.ts +13 -2
- package/dist/update/ipc.js +36 -2
- package/dist/update/snapshot.d.ts +1 -0
- package/dist/update/snapshot.js +2 -0
- package/dist/update/updater.d.ts +15 -1
- package/dist/update/updater.js +45 -17
- package/drizzle/0008_tranquil_lily_hollister.sql +1 -0
- package/drizzle/meta/0008_snapshot.json +875 -0
- package/drizzle/meta/_journal.json +7 -0
- package/package.json +41 -42
|
@@ -3,18 +3,21 @@ import { readFile, stat } from 'node:fs/promises';
|
|
|
3
3
|
import { Hono } from 'hono';
|
|
4
4
|
import { streamSSE } from 'hono/streaming';
|
|
5
5
|
import { createAgent, runAgent } from '../../core/agent.js';
|
|
6
|
+
import { loadConfigScopes, mergeConfig } from '../../core/config.js';
|
|
6
7
|
import { compactContext } from '../../core/loop.js';
|
|
7
8
|
import { createSlashRegistry, parseSlashInput } from '../../core/slash.js';
|
|
8
9
|
import { injectSteering } from '../../core/steering.js';
|
|
9
10
|
import { buildWorkflowNotice, containsWorkflow } from '../../core/workflow.js';
|
|
10
11
|
import { resolveRoute } from '../../llm/registry.js';
|
|
11
12
|
import { getProject } from '../../project/project.js';
|
|
13
|
+
import { insertEntry } from '../../session/message.js';
|
|
12
14
|
import { getLLMSegments, getSession, updateSessionLastRun } from '../../session/session.js';
|
|
13
15
|
import { upsertFileSnapshot } from '../../session/snapshot.js';
|
|
14
16
|
import { resolveEnabledToolNames } from '../../tools/index.js';
|
|
15
17
|
import { autoAllowChecker } from '../../tools/permission.js';
|
|
16
18
|
import { apiError } from '../middleware/error.js';
|
|
17
19
|
import { createInteractivePermissionChecker } from '../permission/interactive.js';
|
|
20
|
+
import { buildRegistryFromConfig } from '../registry-config.js';
|
|
18
21
|
import { safeResolve } from '../util/safe-path.js';
|
|
19
22
|
/** 按 session.projectId / worktreePath 解析 agent 工作目录:
|
|
20
23
|
* - 有 projectId → 项目 worktree(缺失/目录失效时抛错,由上层转 409)。
|
|
@@ -39,6 +42,22 @@ export async function resolveAgentCwd(ctx, session) {
|
|
|
39
42
|
}
|
|
40
43
|
return project.worktree;
|
|
41
44
|
}
|
|
45
|
+
/**
|
|
46
|
+
* SSE 心跳间隔。前端有 90s 静默看门狗(web/services/chat.ts),而服务端各
|
|
47
|
+
* 等待语义远长于此:bash 默认超时 120s、权限确认 5 分钟、子 agent 执行数分钟。
|
|
48
|
+
* 这些等待期间没有业务事件帧——若无心跳,前端会在 90s 时 abort 连接,
|
|
49
|
+
* 服务端 stream.onAbort 随即中止 agent,长命令/权限弹窗/多 agent 全部误杀。
|
|
50
|
+
* 30s 心跳保证看门狗只对「连接真正死亡」(连续 3 个心跳周期无数据)生效。
|
|
51
|
+
*/
|
|
52
|
+
const SSE_HEARTBEAT_INTERVAL_MS = 30_000;
|
|
53
|
+
/** 启动心跳定时器;返回停止函数(幂等)。流关闭后写入会被吞掉,安全。 */
|
|
54
|
+
function startHeartbeat(stream) {
|
|
55
|
+
const timer = setInterval(() => {
|
|
56
|
+
stream.writeSSE({ event: 'heartbeat', data: '' }).catch(() => { }); // 流已关闭/客户端断开时写入失败,忽略
|
|
57
|
+
}, SSE_HEARTBEAT_INTERVAL_MS);
|
|
58
|
+
return () => clearInterval(timer);
|
|
59
|
+
}
|
|
60
|
+
export { SSE_HEARTBEAT_INTERVAL_MS, startHeartbeat };
|
|
42
61
|
function createChatRoute(ctx) {
|
|
43
62
|
const app = new Hono();
|
|
44
63
|
// POST / — SSE 流式聊天
|
|
@@ -46,8 +65,25 @@ function createChatRoute(ctx) {
|
|
|
46
65
|
const body = await c.req.json().catch(() => ({}));
|
|
47
66
|
const sessionId = body.sessionId;
|
|
48
67
|
const message = body.message;
|
|
49
|
-
|
|
50
|
-
|
|
68
|
+
const images = body.images;
|
|
69
|
+
// P1-5:纯图片消息放行(Composer 允许只带图片不带文本),
|
|
70
|
+
// 仅当文本与图片皆无时拒绝,错误信息说明可操作原因。
|
|
71
|
+
if (!sessionId || (!message && !images?.length)) {
|
|
72
|
+
return apiError(c, 400, 'BAD_REQUEST', '消息内容不能为空:请输入文字或附带图片后再发送');
|
|
73
|
+
}
|
|
74
|
+
// P0:图片大小/数量服务端限额(前端已限制,此为兜底——API 直调/旧客户端)。
|
|
75
|
+
if (images) {
|
|
76
|
+
const MAX_IMAGE_COUNT = 6;
|
|
77
|
+
const MAX_IMAGE_BYTES = 8 * 1024 * 1024;
|
|
78
|
+
if (images.length > MAX_IMAGE_COUNT) {
|
|
79
|
+
return apiError(c, 400, 'TOO_MANY_IMAGES', `最多 ${MAX_IMAGE_COUNT} 张图片(收到 ${images.length} 张)`);
|
|
80
|
+
}
|
|
81
|
+
for (const img of images) {
|
|
82
|
+
if (typeof img.data === 'string' && img.data.length > MAX_IMAGE_BYTES) {
|
|
83
|
+
const mb = (img.data.length / (1024 * 1024)).toFixed(1);
|
|
84
|
+
return apiError(c, 400, 'IMAGE_TOO_LARGE', `图片大小 ${mb}MB 超过上限 ${MAX_IMAGE_BYTES / (1024 * 1024)}MB`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
51
87
|
}
|
|
52
88
|
let session;
|
|
53
89
|
try {
|
|
@@ -59,6 +95,18 @@ function createChatRoute(ctx) {
|
|
|
59
95
|
if (!session) {
|
|
60
96
|
return apiError(c, 404, 'NOT_FOUND', 'Session not found');
|
|
61
97
|
}
|
|
98
|
+
// P2:会话级权限覆盖持久化在 metadata——重启后从 DB 恢复到内存 Map,
|
|
99
|
+
// 使 getMode 的「会话覆盖」优先级跨重启成立。
|
|
100
|
+
if (session.metadata.permissionMode === 'auto' ||
|
|
101
|
+
session.metadata.permissionMode === 'default') {
|
|
102
|
+
ctx.sessionPermissionModes.set(sessionId, session.metadata.permissionMode);
|
|
103
|
+
}
|
|
104
|
+
// P2:会话级「始终允许」白名单同样持久化于 metadata,checker 经 getter 实时读取
|
|
105
|
+
// (run 期间用户可追加;此处仅在本会话 Map 尚未加载时注入,已有值优先)。
|
|
106
|
+
if (!ctx.sessionAlwaysAllow.has(sessionId)) {
|
|
107
|
+
const list = session.metadata.alwaysAllow;
|
|
108
|
+
ctx.sessionAlwaysAllow.set(sessionId, Array.isArray(list) ? list.filter((t) => typeof t === 'string') : []);
|
|
109
|
+
}
|
|
62
110
|
// 提前解析 cwd(slash 拦截与 agent 路径都需使用)
|
|
63
111
|
// P1-9:worktree 失效/项目缺失 → 明确 409,不静默回退服务端 cwd。
|
|
64
112
|
let cwd;
|
|
@@ -75,15 +123,47 @@ function createChatRoute(ctx) {
|
|
|
75
123
|
}
|
|
76
124
|
return apiError(c, 500, 'CWD_RESOLVE_FAILED', msg);
|
|
77
125
|
}
|
|
78
|
-
//
|
|
79
|
-
|
|
126
|
+
// P1 多项目配置:会话级配置按会话工作目录解析(该项目 .c0de/config.json 的原始
|
|
127
|
+
// 作用域合并到服务级配置之上)。此前所有项目共用启动目录配置——在其他项目里
|
|
128
|
+
// 修改「项目配置」实际写的是启动项目。cwd === ctx.cwd 时直接复用服务级配置。
|
|
129
|
+
// 权限默认模式单独取原始 project 作用域:项目文件未显式设置时回退运行时全局
|
|
130
|
+
// 模式(启动默认或 PUT /api/permissions 覆盖),避免启动项目配置泄漏到其他项目。
|
|
131
|
+
const sessionProjectScope = cwd === ctx.cwd ? undefined : loadConfigScopes(cwd).project;
|
|
132
|
+
const sessionConfig = sessionProjectScope
|
|
133
|
+
? mergeConfig(ctx.config, sessionProjectScope)
|
|
134
|
+
: ctx.config;
|
|
135
|
+
const sessionDefaultMode = sessionProjectScope?.permission?.defaultMode;
|
|
136
|
+
// P1-1:会话项目注册表——项目级配置含 providers 时,按该项目合并配置
|
|
137
|
+
// 构建/复用 LLM 注册表(否则项目配置的 provider 永远 NoRoute)。
|
|
138
|
+
// 服务启动目录项目直接复用服务级注册表。
|
|
139
|
+
let sessionRegistry = ctx.llmRegistry;
|
|
140
|
+
if (sessionProjectScope && session.projectId) {
|
|
141
|
+
const pid = session.projectId;
|
|
142
|
+
const cached = ctx.projectRegistries?.get(pid);
|
|
143
|
+
if (cached) {
|
|
144
|
+
sessionRegistry = cached;
|
|
145
|
+
}
|
|
146
|
+
else if (sessionConfig.providers.length > 0) {
|
|
147
|
+
sessionRegistry = buildRegistryFromConfig(sessionConfig);
|
|
148
|
+
ctx.projectRegistries?.set(pid, sessionRegistry);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
// 斜杠命令拦截(纯图片消息无文本,跳过命令解析)
|
|
152
|
+
const parsed = parseSlashInput(message ?? '');
|
|
80
153
|
if (parsed) {
|
|
81
154
|
const registry = createSlashRegistry();
|
|
82
155
|
const cmd = registry.get(parsed.name);
|
|
83
156
|
if (cmd) {
|
|
157
|
+
// P3:变更型命令(清空/压缩/分支直接改写消息树)与活跃 run 的并发
|
|
158
|
+
// 写入存在竞态——斜杠拦截早于 tryAcquire,须在此显式拒绝。
|
|
159
|
+
const MUTATING_SLASH = new Set(['compact', 'clear', 'fork']);
|
|
160
|
+
if (MUTATING_SLASH.has(parsed.name) &&
|
|
161
|
+
(ctx.agentManager.get(sessionId) || ctx.agentManager.isStarting(sessionId))) {
|
|
162
|
+
return apiError(c, 409, 'RUN_ACTIVE', `该会话已有进行中的对话,请等待完成或中止后再执行 /${parsed.name}`);
|
|
163
|
+
}
|
|
84
164
|
// P2-4:执行 config.slashCommands.enabled 过滤(此前该配置无任何消费方)。
|
|
85
165
|
// enabled 为空 = 全部启用(与 tools.enabled 语义一致);名称兼容带/不带前缀斜杠。
|
|
86
|
-
const enabledList =
|
|
166
|
+
const enabledList = sessionConfig.slashCommands?.enabled ?? [];
|
|
87
167
|
const enabledSet = new Set(enabledList.map((n) => (n.startsWith('/') ? n.slice(1) : n)));
|
|
88
168
|
if (enabledSet.size > 0 && !enabledSet.has(parsed.name)) {
|
|
89
169
|
return streamSSE(c, async (stream) => {
|
|
@@ -99,38 +179,79 @@ function createChatRoute(ctx) {
|
|
|
99
179
|
}
|
|
100
180
|
const commandCtx = {
|
|
101
181
|
cwd,
|
|
102
|
-
config:
|
|
182
|
+
config: sessionConfig,
|
|
103
183
|
// 当前会话 id:/clear /fork 等命令默认作用于当前会话(P2-4)。
|
|
104
184
|
sessionId,
|
|
185
|
+
// 消费渠道:/model 等命令按渠道给指引(Web 有底部模型选择器)。
|
|
186
|
+
channel: 'web',
|
|
105
187
|
// 内置斜杠命令(/clear、/fork、/config)仅需 db + config;
|
|
106
188
|
// 但 /workflow run 会走 executeWorkflow → buildWorkflowContext → runSubAgent,
|
|
107
189
|
// 该路径需要 agentRegistry 来派生子 agent,因此必须注入。
|
|
108
|
-
// permission/toolRegistry 用 autoAllow 凑齐类型(子命令不触发交互权限)。
|
|
109
190
|
workflowRegistry: ctx.workflowRegistry,
|
|
110
191
|
deps: {
|
|
111
192
|
db: ctx.db,
|
|
112
|
-
config:
|
|
193
|
+
config: sessionConfig,
|
|
113
194
|
cwd,
|
|
195
|
+
// P1 工作流权限:占位 checker 在 streamSSE 回调内被替换为交互式
|
|
196
|
+
// checker——/workflow run 的子 agent 才能对 ask 工具弹窗确认。
|
|
114
197
|
permission: autoAllowChecker,
|
|
115
198
|
toolRegistry: ctx.toolRegistry,
|
|
116
|
-
llmRegistry:
|
|
199
|
+
llmRegistry: sessionRegistry,
|
|
117
200
|
agentRegistry: ctx.agentRegistry,
|
|
118
201
|
},
|
|
119
202
|
};
|
|
120
203
|
return streamSSE(c, async (stream) => {
|
|
204
|
+
const stopHeartbeat = startHeartbeat(stream);
|
|
121
205
|
try {
|
|
122
|
-
|
|
206
|
+
// P1 工作流权限:子命令(尤其 /workflow run)的子 agent 继承此 checker。
|
|
207
|
+
// 此前用 autoAllowChecker:ask 工具返回 permission_required 结果但无
|
|
208
|
+
// 确认通道(confirm 是 no-op),写/执行工具在工作流里静默不可用。
|
|
209
|
+
// 现在与主 agent 一致:permission_required 经 SSE 弹窗,用户确认后
|
|
210
|
+
// 经 /api/tools/confirm 消费全局 store。
|
|
211
|
+
const permissionChecker = createInteractivePermissionChecker(ctx.permissionStore, {
|
|
212
|
+
getMode: () => ctx.sessionPermissionModes.get(sessionId) ??
|
|
213
|
+
sessionDefaultMode ??
|
|
214
|
+
ctx.permissionMode,
|
|
215
|
+
alwaysAllow: () => ctx.sessionAlwaysAllow.get(sessionId) ?? [],
|
|
216
|
+
onPermissionRequired: async (req) => {
|
|
217
|
+
await stream.writeSSE({
|
|
218
|
+
event: 'permission_required',
|
|
219
|
+
data: JSON.stringify({ _tag: 'permission_required', ...req }),
|
|
220
|
+
});
|
|
221
|
+
},
|
|
222
|
+
onPermissionTimeout: (req) => {
|
|
223
|
+
stream
|
|
224
|
+
.writeSSE({
|
|
225
|
+
event: 'permission_timeout',
|
|
226
|
+
data: JSON.stringify({ _tag: 'permission_timeout', ...req }),
|
|
227
|
+
})
|
|
228
|
+
.catch(() => { });
|
|
229
|
+
},
|
|
230
|
+
onPermissionExpired: (req) => {
|
|
231
|
+
stream
|
|
232
|
+
.writeSSE({
|
|
233
|
+
event: 'permission_expired',
|
|
234
|
+
data: JSON.stringify({ _tag: 'permission_expired', ...req }),
|
|
235
|
+
})
|
|
236
|
+
.catch(() => { });
|
|
237
|
+
},
|
|
238
|
+
});
|
|
239
|
+
const streamCommandCtx = {
|
|
240
|
+
...commandCtx,
|
|
241
|
+
deps: { ...commandCtx.deps, permission: permissionChecker },
|
|
242
|
+
};
|
|
243
|
+
const result = await cmd.execute(parsed.args, streamCommandCtx);
|
|
123
244
|
if (result._tag === 'compact') {
|
|
124
245
|
// /compact:手动触发上下文压缩。复用 loop.compactContext(createSummarizer +
|
|
125
246
|
// runCompaction),不创建主 agent、不进入 LLM turn 循环(不把 /compact 当作
|
|
126
247
|
// user 消息发给模型)。
|
|
127
|
-
const provider = body.provider ??
|
|
128
|
-
const model = body.model ??
|
|
248
|
+
const provider = body.provider ?? sessionConfig.defaultProvider;
|
|
249
|
+
const model = body.model ?? sessionConfig.defaultModel;
|
|
129
250
|
const agentConfig = {
|
|
130
251
|
provider,
|
|
131
252
|
model,
|
|
132
253
|
tools: [],
|
|
133
|
-
plugins:
|
|
254
|
+
plugins: sessionConfig.plugins.enabled,
|
|
134
255
|
agentName: 'default',
|
|
135
256
|
};
|
|
136
257
|
const compactState = await createAgent(session, agentConfig, commandCtx.deps);
|
|
@@ -183,13 +304,16 @@ function createChatRoute(ctx) {
|
|
|
183
304
|
});
|
|
184
305
|
await stream.writeSSE({ event: 'done', data: JSON.stringify({ _tag: 'done' }) });
|
|
185
306
|
}
|
|
307
|
+
finally {
|
|
308
|
+
stopHeartbeat();
|
|
309
|
+
}
|
|
186
310
|
});
|
|
187
311
|
}
|
|
188
312
|
// 未知斜杠命令:回退为正常消息发给 agent
|
|
189
313
|
}
|
|
190
|
-
// 构建多模态 user content
|
|
191
|
-
|
|
192
|
-
const
|
|
314
|
+
// 构建多模态 user content:文本在前(可为空串/缺省,纯图片消息),
|
|
315
|
+
// images(dataURL base64)在后。文本为空时跳过 text part,避免把空文本发给模型。
|
|
316
|
+
const userContent = message ? [{ _tag: 'text', text: message }] : [];
|
|
193
317
|
if (images?.length) {
|
|
194
318
|
for (const img of images) {
|
|
195
319
|
userContent.push({ _tag: 'image', mediaType: img.mediaType, data: img.data });
|
|
@@ -201,12 +325,18 @@ function createChatRoute(ctx) {
|
|
|
201
325
|
const valid = mentionedAgents
|
|
202
326
|
.map((n) => ctx.agentRegistry.get(n))
|
|
203
327
|
.filter((d) => Boolean(d && d.mode !== 'primary'));
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
328
|
+
// P2:全部无效(拼错/未注册/primary)→ 明确 400,此前静默忽略,用户以为已派发
|
|
329
|
+
if (valid.length === 0) {
|
|
330
|
+
return apiError(c, 400, 'INVALID_AGENT_MENTION', `未知或非 subagent 类型的 agent 提及:${mentionedAgents.join(', ')}`);
|
|
331
|
+
}
|
|
332
|
+
const names = valid.map((d) => d.name).join(', ');
|
|
333
|
+
const first = userContent[0];
|
|
334
|
+
if (first && first._tag === 'text') {
|
|
335
|
+
first.text = `[User requested subagent(s): ${names}]\n\n${first.text}`;
|
|
336
|
+
}
|
|
337
|
+
else {
|
|
338
|
+
// 纯图片消息:前置文本 part 承载 subagent 指令,避免指令静默丢失
|
|
339
|
+
userContent.unshift({ _tag: 'text', text: `[User requested subagent(s): ${names}]` });
|
|
210
340
|
}
|
|
211
341
|
}
|
|
212
342
|
// @文件上下文:读取文件内容写入快照,后续 getSessionContext→injectSnapshots 自动注入。
|
|
@@ -232,26 +362,40 @@ function createChatRoute(ctx) {
|
|
|
232
362
|
}
|
|
233
363
|
}
|
|
234
364
|
}
|
|
235
|
-
|
|
236
|
-
|
|
365
|
+
// P1-1:默认 provider/model 按会话项目配置解析(此前用服务启动目录配置,
|
|
366
|
+
// 其他项目的 defaultProvider 设置被静默忽略)。
|
|
367
|
+
const provider = body.provider ?? sessionConfig.defaultProvider;
|
|
368
|
+
const model = body.model ?? sessionConfig.defaultModel;
|
|
237
369
|
// P0-1 首次运行引导:provider 未配置/未注册时立即返回可操作错误,
|
|
238
370
|
// 不让错误延迟到 SSE 流内以英文 NoRoute 冒出。前端据此引导用户去设置页。
|
|
239
371
|
// 注:测试注入 ctx.chatStream 时跳过——测试 registry 空壳不代表生产未配置。
|
|
372
|
+
// P2-4:区分两种失败——完全没有配置 provider vs 配置了但名字不匹配。
|
|
240
373
|
if (!ctx.chatStream) {
|
|
241
374
|
try {
|
|
242
|
-
resolveRoute(
|
|
375
|
+
resolveRoute(sessionRegistry, provider, model);
|
|
243
376
|
}
|
|
244
377
|
catch {
|
|
245
|
-
const configured =
|
|
378
|
+
const configured = sessionConfig.providers
|
|
246
379
|
.map((p) => p.name)
|
|
247
380
|
.filter(Boolean)
|
|
248
381
|
.join(', ');
|
|
249
|
-
|
|
382
|
+
const hasAny = sessionConfig.providers.length > 0;
|
|
383
|
+
return apiError(c, 400, hasAny ? 'PROVIDER_NOT_FOUND' : 'NO_PROVIDER_CONFIGURED', hasAny
|
|
384
|
+
? `未找到名为「${provider}」的 AI 服务。已配置:${configured}。` +
|
|
385
|
+
'请检查拼写,或前往「设置 → Provider」添加该服务。'
|
|
386
|
+
: `未配置可用的 AI 服务(provider: ${provider})。请前往「设置 → Provider」添加 API 服务并测试连接`, {
|
|
250
387
|
provider,
|
|
251
|
-
configuredProviders:
|
|
388
|
+
configuredProviders: sessionConfig.providers.map((p) => p.name).filter(Boolean),
|
|
252
389
|
...(configured ? { hint: `已配置:${configured}` } : {}),
|
|
253
390
|
});
|
|
254
391
|
}
|
|
392
|
+
// P2-4:provider 显式声明了模型清单但请求模型不在其中 → 大概率拼写错误。
|
|
393
|
+
// 未声明清单的 provider(自建网关等)接受任意模型名,不做校验。
|
|
394
|
+
const providerDef = sessionConfig.providers.find((p) => (p.name || p._tag) === provider);
|
|
395
|
+
const modelNames = providerDef?.models ? Object.keys(providerDef.models) : undefined;
|
|
396
|
+
if (modelNames && modelNames.length > 0 && !modelNames.includes(model)) {
|
|
397
|
+
return apiError(c, 400, 'MODEL_NOT_FOUND', `provider「${provider}」没有名为「${model}」的模型。已配置模型:${modelNames.join(', ')}`, { provider, model, knownModels: modelNames });
|
|
398
|
+
}
|
|
255
399
|
}
|
|
256
400
|
// 并发守卫(P0-4):同步原子占位 tryAcquire(Map has+set 一气呵成、无 await)。
|
|
257
401
|
// 旧实现先 get 检查、真正 register 在 SSE 回调内,两者之间隔多个 await
|
|
@@ -269,7 +413,8 @@ function createChatRoute(ctx) {
|
|
|
269
413
|
try {
|
|
270
414
|
// 工具解析(P1-1):config.tools.enabled 非空时作为默认集;空 = 全部注册工具。
|
|
271
415
|
// disabled 已在 registry 层过滤(createDefaultRegistry),此处兜底。
|
|
272
|
-
|
|
416
|
+
// P1 多项目:按会话项目配置解析(此前用启动目录配置)。
|
|
417
|
+
const tools = resolveEnabledToolNames(ctx.toolRegistry, sessionConfig, body.tools);
|
|
273
418
|
// primary agent 解析(spec: agent-frontend-switching §4.3)
|
|
274
419
|
const agentName = body.agent ?? 'default';
|
|
275
420
|
const agentDef = ctx.agentRegistry.get(agentName);
|
|
@@ -307,20 +452,24 @@ function createChatRoute(ctx) {
|
|
|
307
452
|
// P0-4:回调从首行起全部纳入 try/finally——createAgent、updateSessionLastRun
|
|
308
453
|
// 等启动阶段失败同样必须释放占位并补发 error/done(hono 的 stream 包装器
|
|
309
454
|
// 只 console.error 不善后),不得泄漏占位或让前端卡在 streaming 态。
|
|
455
|
+
// P0 心跳:长工具执行/权限确认等待期间无业务帧,心跳防前端 90s 看门狗误杀。
|
|
456
|
+
const stopHeartbeat = startHeartbeat(stream);
|
|
310
457
|
let doneSent = false;
|
|
311
458
|
let runStartedAt;
|
|
312
459
|
try {
|
|
313
460
|
// 权限检查器:ask 权限通过 SSE 通知前端,阻塞等待确认。
|
|
314
|
-
//
|
|
461
|
+
// 模式优先级:会话级覆盖(PUT /:sessionId)> 会话项目配置 defaultMode
|
|
462
|
+
// > 运行时全局模式(启动默认或 PUT / 覆盖)。
|
|
315
463
|
const permissionChecker = createInteractivePermissionChecker(ctx.permissionStore, {
|
|
316
|
-
getMode: () => ctx.sessionPermissionModes.get(sessionId) ?? ctx.permissionMode,
|
|
464
|
+
getMode: () => ctx.sessionPermissionModes.get(sessionId) ?? sessionDefaultMode ?? ctx.permissionMode,
|
|
465
|
+
alwaysAllow: () => ctx.sessionAlwaysAllow.get(sessionId) ?? [],
|
|
317
466
|
onPermissionRequired: async (req) => {
|
|
318
467
|
await stream.writeSSE({
|
|
319
468
|
event: 'permission_required',
|
|
320
469
|
data: JSON.stringify({ _tag: 'permission_required', ...req }),
|
|
321
470
|
});
|
|
322
471
|
},
|
|
323
|
-
//
|
|
472
|
+
// P2-9:确认超时(5 分钟)仅通知前端(pending 保持,重开弹窗不重发消息)
|
|
324
473
|
onPermissionTimeout: (req) => {
|
|
325
474
|
stream
|
|
326
475
|
.writeSSE({
|
|
@@ -329,17 +478,27 @@ function createChatRoute(ctx) {
|
|
|
329
478
|
})
|
|
330
479
|
.catch(() => { });
|
|
331
480
|
},
|
|
481
|
+
// P0 双层超时:提示后仍无响应 → 兜底拒绝,SSE 通知前端清理弹窗状态
|
|
482
|
+
//(run 已继续,重开弹窗/拒绝按钮均失效,必须显式清理)。
|
|
483
|
+
onPermissionExpired: (req) => {
|
|
484
|
+
stream
|
|
485
|
+
.writeSSE({
|
|
486
|
+
event: 'permission_expired',
|
|
487
|
+
data: JSON.stringify({ _tag: 'permission_expired', ...req }),
|
|
488
|
+
})
|
|
489
|
+
.catch(() => { });
|
|
490
|
+
},
|
|
332
491
|
});
|
|
333
492
|
// cwd 已在斜杠拦截前解析,此处直接复用
|
|
334
493
|
// 构建 agent 依赖(注入测试用 chatStream)
|
|
335
494
|
const deps = {
|
|
336
495
|
db: ctx.db,
|
|
337
|
-
llmRegistry:
|
|
496
|
+
llmRegistry: sessionRegistry,
|
|
338
497
|
toolRegistry: ctx.toolRegistry,
|
|
339
498
|
urlRegistry: ctx.urlRegistry,
|
|
340
499
|
hookRunner: ctx.hookRunner,
|
|
341
500
|
permission: permissionChecker,
|
|
342
|
-
config:
|
|
501
|
+
config: sessionConfig,
|
|
343
502
|
agentRegistry: ctx.agentRegistry,
|
|
344
503
|
cwd,
|
|
345
504
|
...(ctx.chatStream ? { chatStream: ctx.chatStream } : {}),
|
|
@@ -348,7 +507,7 @@ function createChatRoute(ctx) {
|
|
|
348
507
|
provider,
|
|
349
508
|
model: resolvedModel,
|
|
350
509
|
tools: resolvedTools,
|
|
351
|
-
plugins:
|
|
510
|
+
plugins: sessionConfig.plugins.enabled,
|
|
352
511
|
agentName,
|
|
353
512
|
...(agentDef.systemPrompt ? { agentRolePrompt: agentDef.systemPrompt } : {}),
|
|
354
513
|
};
|
|
@@ -368,7 +527,7 @@ function createChatRoute(ctx) {
|
|
|
368
527
|
ctx.agentManager.register({ sessionId, state, deps });
|
|
369
528
|
// workflowz 关键词检测:用户消息包含独立关键词时注入工作流通知(steering),
|
|
370
529
|
// 引导模型用 task 工具批量 fan-out 做确定性多子 agent 分解。
|
|
371
|
-
if (containsWorkflow(message)) {
|
|
530
|
+
if (message && containsWorkflow(message)) {
|
|
372
531
|
const wfList = ctx.workflowRegistry
|
|
373
532
|
? ctx.workflowRegistry.list().map((w) => ({
|
|
374
533
|
name: w.meta.name,
|
|
@@ -429,6 +588,7 @@ function createChatRoute(ctx) {
|
|
|
429
588
|
.catch(() => { });
|
|
430
589
|
}
|
|
431
590
|
finally {
|
|
591
|
+
stopHeartbeat();
|
|
432
592
|
// 先从 agentManager 释放(占位与活跃 run 均幂等):必须最先执行,确保
|
|
433
593
|
// 客户端断开使 writeSSE reject 时 agent 状态(state/deps/AbortController)
|
|
434
594
|
// 不会泄漏到 Map(unregister 仅做 Map.delete、不依赖 state,放最前安全)。
|
|
@@ -486,8 +646,26 @@ function createChatRoute(ctx) {
|
|
|
486
646
|
});
|
|
487
647
|
app.post('/steer', async (c) => {
|
|
488
648
|
const body = await c.req.json();
|
|
489
|
-
|
|
490
|
-
|
|
649
|
+
const starting = runStarting(c, body.sessionId);
|
|
650
|
+
if (starting)
|
|
651
|
+
return starting;
|
|
652
|
+
const message = typeof body.message === 'string' ? body.message.trim() : '';
|
|
653
|
+
if (!message)
|
|
654
|
+
return c.json({ steered: false });
|
|
655
|
+
const steered = ctx.agentManager.steer(body.sessionId, message);
|
|
656
|
+
// P0 闭环:steering 持久化为会话条目——用户运行中输入追加指令曾是内存瞬态,
|
|
657
|
+
// 刷新后彻底丢失;现在与消息同样入史(context 重建时作为 system 消息注入,
|
|
658
|
+
// 时间线经 /messages 渲染为 user steering 块)。
|
|
659
|
+
if (steered) {
|
|
660
|
+
await insertEntry(ctx.db, {
|
|
661
|
+
sessionId: body.sessionId,
|
|
662
|
+
tag: 'steering',
|
|
663
|
+
content: { text: message },
|
|
664
|
+
}).catch(() => {
|
|
665
|
+
// 持久化失败不阻塞本轮生效(指令已进入 run 队列)
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
return c.json({ steered });
|
|
491
669
|
});
|
|
492
670
|
return app;
|
|
493
671
|
}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { Hono } from 'hono';
|
|
2
2
|
import type { ServerContext } from '../types.js';
|
|
3
|
-
/** GET / — 返回内置斜杠命令列表(name/description/argsHint)。
|
|
4
|
-
|
|
3
|
+
/** GET / — 返回内置斜杠命令列表(name/description/argsHint)。
|
|
4
|
+
* 按 config.slashCommands.enabled 过滤:enabled 为空 = 全部启用;
|
|
5
|
+
* 否则只返回启用项,保证弹窗发现性 = 可执行性(避免展示必被拒的命令)。 */
|
|
6
|
+
declare function createCommandsRoute(ctx: ServerContext): Hono;
|
|
5
7
|
export { createCommandsRoute };
|
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
import { Hono } from 'hono';
|
|
2
2
|
import { createSlashRegistry } from '../../core/slash.js';
|
|
3
|
-
/** GET / — 返回内置斜杠命令列表(name/description/argsHint)。
|
|
4
|
-
|
|
3
|
+
/** GET / — 返回内置斜杠命令列表(name/description/argsHint)。
|
|
4
|
+
* 按 config.slashCommands.enabled 过滤:enabled 为空 = 全部启用;
|
|
5
|
+
* 否则只返回启用项,保证弹窗发现性 = 可执行性(避免展示必被拒的命令)。 */
|
|
6
|
+
function createCommandsRoute(ctx) {
|
|
5
7
|
const app = new Hono();
|
|
6
8
|
app.get('/', (c) => {
|
|
7
9
|
const registry = createSlashRegistry();
|
|
8
|
-
const
|
|
10
|
+
const enabledList = ctx.config.slashCommands?.enabled ?? [];
|
|
11
|
+
const enabledSet = new Set(enabledList.map((n) => (n.startsWith('/') ? n.slice(1) : n)));
|
|
12
|
+
const commands = registry
|
|
13
|
+
.list()
|
|
14
|
+
.filter((cmd) => enabledSet.size === 0 || enabledSet.has(cmd.name))
|
|
15
|
+
.map((cmd) => ({
|
|
9
16
|
name: cmd.name,
|
|
10
17
|
description: cmd.description,
|
|
11
18
|
...(cmd.argsHint ? { argsHint: cmd.argsHint } : {}),
|