dsh-team-bots 0.2.289 → 0.2.338
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 +12 -136
- package/docs/README.zh.md +15 -139
- package/docs/assets/channel-redesign.png +0 -0
- package/docs/assets/global-config-dark.png +0 -0
- package/docs/assets/global-config-light.png +0 -0
- package/docs/assets/global-config-light.zh.png +0 -0
- package/docs/assets/global-config-redesign.png +0 -0
- package/docs/assets/secrets-redesign.png +0 -0
- package/docs/assets/tasks.png +0 -0
- package/docs/assets/tasks.zh.png +0 -0
- package/docs/assets/usage-redesign-global.png +0 -0
- package/docs/assets/usage.png +0 -0
- package/docs/assets/usage.zh.png +0 -0
- package/package.json +17 -5
- package/scripts/doctor.mjs +4 -4
- package/src/api.js +6 -3
- package/src/botmsg.js +1 -1
- package/src/config.js +18 -8
- package/src/db-migrations.js +76 -9
- package/src/db.js +28 -2
- package/src/http.js +22 -3
- package/src/paths.js +32 -1
- package/src/pricing.js +2 -2
- package/src/runtime.js +1 -1
- package/src/secrets.js +4 -4
- package/src/service.js +10 -5
- package/src/services/approvals.js +109 -24
- package/src/services/bot-quota.js +242 -0
- package/src/services/bots.js +35 -6
- package/src/services/chat.js +15 -9
- package/src/services/core.js +33 -5
- package/src/services/hygiene.js +8 -4
- package/src/services/locale.js +17 -0
- package/src/services/memory.js +112 -1
- package/src/services/message-images.js +3 -3
- package/src/services/notify.js +99 -0
- package/src/services/projects.js +119 -10
- package/src/services/proposals.js +2 -3
- package/src/services/questions.js +75 -32
- package/src/services/review-watchdog.js +261 -30
- package/src/services/run-finish.js +119 -7
- package/src/services/runs.js +42 -13
- package/src/services/runtime/lifecycle.js +3 -1
- package/src/services/runtime/model-restore.js +5 -5
- package/src/services/runtime/prompt.js +106 -45
- package/src/services/runtime/session.js +38 -14
- package/src/services/runtime/trajectory.js +1 -1
- package/src/services/scheduler.js +139 -13
- package/src/services/secrets.js +1 -1
- package/src/services/system.js +23 -6
- package/src/services/task-notify.js +49 -7
- package/src/services/task-stage.js +4 -0
- package/src/services/tasks.js +121 -12
- package/src/services/terminal.js +2 -2
- package/src/services/vision-proxy.js +3 -3
- package/src/services/wechat.js +228 -7
- package/src/services/workspace-groups.js +4 -3
- package/src/skill-parse.js +1 -1
- package/src/skills.js +1 -1
- package/src/tools.js +275 -6
- package/src/updater.js +52 -0
- package/src/usage-reconcile.js +1 -1
- package/src/usage.js +52 -11
- package/src/wechat/channel.js +14 -20
- package/src/wechat/commands.js +129 -81
- package/src/wechat/format.js +247 -0
- package/src/wechat/store.js +30 -2
- package/ui/app.js +56 -52
- package/ui/i18n/en/chat.js +140 -0
- package/ui/i18n/en/common.js +189 -0
- package/ui/i18n/en/nav.js +90 -0
- package/ui/i18n/en/settings.js +354 -0
- package/ui/i18n/en/tasks.js +232 -0
- package/ui/i18n/en/usage.js +141 -0
- package/ui/i18n/en/wechat.js +24 -0
- package/ui/i18n/en.js +17 -237
- package/ui/i18n/zh/chat.js +140 -0
- package/ui/i18n/zh/common.js +189 -0
- package/ui/i18n/zh/nav.js +90 -0
- package/ui/i18n/zh/settings.js +354 -0
- package/ui/i18n/zh/tasks.js +232 -0
- package/ui/i18n/zh/usage.js +141 -0
- package/ui/i18n/zh/wechat.js +24 -0
- package/ui/i18n/zh.js +17 -236
- package/ui/modules/api.js +4 -3
- package/ui/modules/bot-quota.js +27 -0
- package/ui/modules/cards.js +96 -58
- package/ui/modules/chat.js +28 -30
- package/ui/modules/composer.js +41 -37
- package/ui/modules/dom-morph.js +292 -0
- package/ui/modules/events-board.js +22 -22
- package/ui/modules/events-click.js +100 -68
- package/ui/modules/events-misc.js +34 -34
- package/ui/modules/events-submit.js +28 -28
- package/ui/modules/global-pages.js +127 -116
- package/ui/modules/i18n.js +0 -5
- package/ui/modules/icons.js +0 -1
- package/ui/modules/markdown.js +1 -1
- package/ui/modules/modal-forms.js +195 -202
- package/ui/modules/modal-layer.js +6 -9
- package/ui/modules/page-shell.js +62 -0
- package/ui/modules/settings.js +211 -198
- package/ui/modules/solo-archive.js +0 -4
- package/ui/modules/state.js +57 -50
- package/ui/modules/tasks.js +168 -171
- package/ui/modules/typing-linger.js +1 -4
- package/ui/modules/usage.js +65 -78
- package/ui/modules/util.js +92 -25
- package/ui/styles/avatars.css +14 -0
- package/ui/styles/cards.css +49 -0
- package/ui/styles/chat-cards.css +17 -21
- package/ui/styles/global-config.css +59 -2
- package/ui/styles/modal.css +13 -0
- package/ui/styles/usage.css +3 -61
- package/CONTRIBUTING.md +0 -20
- package/docs/assets/usage-dark.png +0 -0
package/src/tools.js
CHANGED
|
@@ -3,25 +3,87 @@ const stringOutput = {
|
|
|
3
3
|
render: (_args, value) => [{ type: 'text', text: String(value ?? '') }],
|
|
4
4
|
}
|
|
5
5
|
|
|
6
|
+
// DSHBOTS-238:子代理/智能体团队能力全员化。
|
|
7
|
+
// 「生成子代理/组建临时团队」能力由宿主 preset 注册(subagent/subagent_fork/workflow 与
|
|
8
|
+
// spawn_teammate 等团队工具),插件侧只声明其可用清单与门控,不重复注册。
|
|
9
|
+
// DSHBOTS-237:共享板建卡废弃——宿主共享板的建卡工具(task-N 无项目编号卡)
|
|
10
|
+
// 不再作为成员能力宣告,新建卡一律走项目编号(team_assign_task 派单链,KEY-N);
|
|
11
|
+
// 存量共享板卡可读不可新建,list/get/update 保留读取与流转能力。
|
|
12
|
+
export const SUBAGENT_GENERATION_TOOLS = [
|
|
13
|
+
'subagent',
|
|
14
|
+
'subagent_fork',
|
|
15
|
+
'workflow',
|
|
16
|
+
'spawn_teammate',
|
|
17
|
+
'send_message',
|
|
18
|
+
'list_agents',
|
|
19
|
+
'wait_agent',
|
|
20
|
+
'interrupt_agent',
|
|
21
|
+
'team_task_list',
|
|
22
|
+
'team_task_get',
|
|
23
|
+
'team_task_update',
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
// 总监专权工具:服务层 ownerContextFor 已做权威校验,本清单用于工具层兜底与守门测试。
|
|
27
|
+
// team_block_task(DSHBOTS-232)与派单/验收同款总监专属:强制受阻停运行是不可逆控制面操作。
|
|
28
|
+
// team_list_bots / team_add_member / team_create_bot(DSHBOTS-229)是团队编制入口:
|
|
29
|
+
// 池查询含未入群 bot,加人与建 bot 会改动项目成员或全局 bot 档案。
|
|
30
|
+
// team_memory_list / team_memory_write / team_memory_cleanup(DSHBOTS-239)是记忆巡检面:
|
|
31
|
+
// 枚举、同名覆盖写与批量终态化清理都只归总监。
|
|
32
|
+
export const DIRECTOR_ONLY_TOOLS = [
|
|
33
|
+
'team_assign_task',
|
|
34
|
+
'team_review_task',
|
|
35
|
+
'team_block_task',
|
|
36
|
+
'team_list_bots',
|
|
37
|
+
'team_add_member',
|
|
38
|
+
'team_create_bot',
|
|
39
|
+
'team_memory_list',
|
|
40
|
+
'team_memory_write',
|
|
41
|
+
'team_memory_cleanup',
|
|
42
|
+
'team_release_bot_quota',
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
// 门控:agentTeam 开启且 bot 类型支持(项目内 active bot,成员与总监均可用)。
|
|
46
|
+
export function subagentCapabilityEnabledFor(bot, config) {
|
|
47
|
+
return Boolean(config?.agentTeam) && Boolean(bot?.id) && bot.status !== 'removed'
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// 工具层兜底(DSHBOTS-238):成员 bot 隐藏总监专权工具,避免「误调被拒后才知情」;
|
|
51
|
+
// 子代理生成工具由 preset 全局注册,成员 bot 默认可见,无需额外放行。
|
|
52
|
+
// DSHBOTS-247:调用点形状不一——session.ts 的结转/复用路径传 resolveAgent 的
|
|
53
|
+
// `{ agent }` 包装,新建会话路径传裸 agent。这里归一为句柄后取 restrict,两种形状都生效;
|
|
54
|
+
// 旧实现只认包装形状时,裸形状会静默跳过(策略从未生效)或旧构建抛 "reading 'ctx'"。
|
|
55
|
+
export function applyBotToolPolicy(resolved, { isOwner, logger } ) {
|
|
56
|
+
if (isOwner) return
|
|
57
|
+
const handle = resolved?.agent ?? resolved
|
|
58
|
+
const restrict = handle?.ctx?.tools?.restrict
|
|
59
|
+
if (typeof restrict !== 'function') return
|
|
60
|
+
try {
|
|
61
|
+
restrict({ deny: [...DIRECTOR_ONLY_TOOLS] })
|
|
62
|
+
} catch (error ) {
|
|
63
|
+
// 工具层兜底失败不阻断会话:服务层 ownerContextFor 仍是权威闸门。
|
|
64
|
+
logger?.warn?.(`dsh-team: 应用成员 bot 工具策略失败:${error?.message ?? error}`)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
6
68
|
export function installTeamTools(ctx, service) {
|
|
7
69
|
if (!ctx.tools?.register) return
|
|
8
70
|
|
|
9
71
|
ctx.tools.register({
|
|
10
72
|
name: 'team_assign_task',
|
|
11
|
-
description: 'Assign a task to a project bot. Only the project owner bot may use this. With `task` it re-dispatches that existing task (retry to the same bot, or hand it to a different bot);
|
|
73
|
+
description: 'Assign a task to a project bot. Only the project owner bot may use this. With `task` it re-dispatches that existing task (retry to the same bot, or hand it to a different bot); passing title/description/priority alongside `task` amends the card — the assignee is immediately notified to correct course per the new card. Without `task`, creates a new task that starts automatically. A new task whose write scopes exactly match an unfinished task in the same project is rejected as a duplicate dispatch; merge the cards into the existing task instead, or pass force_duplicate to override (audited). Consolidate before dispatch: one requirement goes into one card — amend and re-dispatch the existing card (or add subtask cards with parent_task_id for genuinely independent parts) instead of opening several sibling cards for the same need.',
|
|
12
74
|
parameters: {
|
|
13
75
|
type: 'object',
|
|
14
76
|
properties: {
|
|
15
77
|
assignee: { type: 'string', description: 'Exact bot name from the project member list' },
|
|
16
|
-
title: { type: 'string', description: 'Short actionable task title (new tasks
|
|
17
|
-
description: { type: 'string', description: 'Self-contained instructions, constraints and acceptance criteria (new tasks
|
|
18
|
-
priority: { type: 'string', enum: ['urgent', 'high', 'medium', 'low', 'none'], description: 'Task priority' },
|
|
78
|
+
title: { type: 'string', description: 'Short actionable task title (new tasks; on re-dispatch it amends the card)' },
|
|
79
|
+
description: { type: 'string', description: 'Self-contained instructions, constraints and acceptance criteria (new tasks; on re-dispatch it amends the card and the assignee is notified to correct course)' },
|
|
80
|
+
priority: { type: 'string', enum: ['urgent', 'high', 'medium', 'low', 'none'], description: 'Task priority (new tasks and card amendment on re-dispatch)' },
|
|
19
81
|
write_scopes: { type: 'array', items: { type: 'string' }, description: 'Workspace-relative paths this task will modify (new tasks only); the scheduler runs tasks with disjoint scopes in parallel. Omit to parse a `写范围:`/`write_scopes:` line from the description instead' },
|
|
20
82
|
force_duplicate: { type: 'boolean', description: 'Escape hatch (new tasks only): skip the same-write-scope duplicate check when an unfinished task in this project already declares identical write scopes. Use only when a second task on the same paths is intentional; every use is audited as dispatch_force_duplicate' },
|
|
21
83
|
time_budget_minutes: { type: 'integer', description: 'Required delivery time limit in minutes (new tasks only, 1-10080): injected into the task prompt, and the run is aborted when the budget expires. The effective timeout is the smaller of this budget and the global run timeout. Omit to take the default budget (env DSH_TEAM_TASK_TIME_BUDGET_MINUTES > stall-watchdog minutes > fallback 20 minutes)' },
|
|
22
|
-
parent_task_id: { type: 'string', description: 'Nest the new task as a subtask under this main task id (new tasks only): pass it when the main item cannot be finished in this run or a new closing condition emerged, so follow-up work lands as a product-grade card instead of a verbal note. Must reference an existing task in the same project; self-reference is rejected. The backend validates' },
|
|
84
|
+
parent_task_id: { type: 'string', description: 'Nest the new task as a subtask under this main task id (new tasks only): pass it when the main item cannot be finished in this run or a new closing condition emerged, so follow-up work lands as a product-grade card instead of a verbal note; also pass it to split a large task into parallel subtask cards for speed (independent parts, disjoint write_scopes, so the cards run concurrently). Must reference an existing task in the same project; self-reference is rejected. The backend validates' },
|
|
23
85
|
task: { type: 'string', description: 'Existing task to re-dispatch, as KEY-N (for example DEMO-3). Omit to create a new task' },
|
|
24
|
-
sandbox: { type: 'string', enum: ['inherit', 'workspace-write', 'read-only'], description: '
|
|
86
|
+
sandbox: { type: 'string', enum: ['inherit', 'workspace-write', 'read-only'], default: 'inherit', description: 'Sandbox tier for this task\'s runs (new tasks and re-dispatch); default inherit = follow the assignee bot\'s configured file policy, so a development task is never tightened to read-only unless the card says so. inherit also clears any stored override on re-dispatch. workspace-write/read-only must not be wider than that configuration (tighten-only; every run of the task starts under the effective tier, recorded as a sandbox_mode run event). Use read-only to run a development task in review mode' },
|
|
25
87
|
},
|
|
26
88
|
required: ['assignee'],
|
|
27
89
|
additionalProperties: false,
|
|
@@ -37,6 +99,25 @@ export function installTeamTools(ctx, service) {
|
|
|
37
99
|
},
|
|
38
100
|
})
|
|
39
101
|
|
|
102
|
+
ctx.tools.register({
|
|
103
|
+
name: 'team_block_task',
|
|
104
|
+
description: 'Force-move an in-progress task to blocked and abort its queued/running runs. Only the project owner bot may use this. The stop rides the existing abort chain and is audited as task.force_blocked (run error code TASK_FORCE_BLOCKED). Use it to stop a runaway or wrong-headed execution; typically followed by re-dispatching the same task with an amended card.',
|
|
105
|
+
parameters: {
|
|
106
|
+
type: 'object',
|
|
107
|
+
properties: {
|
|
108
|
+
task: { type: 'string', description: 'Task to force-block, as KEY-N (for example DEMO-3)' },
|
|
109
|
+
},
|
|
110
|
+
required: ['task'],
|
|
111
|
+
additionalProperties: false,
|
|
112
|
+
},
|
|
113
|
+
output: stringOutput,
|
|
114
|
+
async execute(args, exec) {
|
|
115
|
+
const sessionId = exec?.agent?.id ?? exec?.agent?.session?.id
|
|
116
|
+
const task = await service.forceBlockFromBot(sessionId, args)
|
|
117
|
+
return `Force-blocked ${task.identifier} (status: ${task.status}); its queued/running runs were aborted.`
|
|
118
|
+
},
|
|
119
|
+
})
|
|
120
|
+
|
|
40
121
|
ctx.tools.register({
|
|
41
122
|
name: 'team_review_task',
|
|
42
123
|
description: 'Accept or return a delivered task that is waiting for owner review. Only the project owner bot may use this. `accept` marks the task done; `return` sends it back to the assignee for rework (a reason is required).',
|
|
@@ -58,6 +139,80 @@ export function installTeamTools(ctx, service) {
|
|
|
58
139
|
},
|
|
59
140
|
})
|
|
60
141
|
|
|
142
|
+
// DSHBOTS-229:成员查询——项目群内任意成员可查本项目名单/角色/状态。
|
|
143
|
+
ctx.tools.register({
|
|
144
|
+
name: 'team_list_members',
|
|
145
|
+
description: 'List the bots in this project group with their project role, job role and status. Any bot in the project group may use this. The result is limited to this project\'s members; it never exposes other projects\' data.',
|
|
146
|
+
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
|
147
|
+
output: stringOutput,
|
|
148
|
+
async execute(args, exec) {
|
|
149
|
+
const sessionId = exec?.agent?.id ?? exec?.agent?.session?.id
|
|
150
|
+
return service.listMembersFromBot(sessionId)
|
|
151
|
+
},
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
// DSHBOTS-229:bots 池查询——总监可见含未入群的 bot;成员调用被服务层拒绝。
|
|
155
|
+
ctx.tools.register({
|
|
156
|
+
name: 'team_list_bots',
|
|
157
|
+
description: 'List the team bot pool for this project, including bots that are not in the project group yet, with their status and whether they already belong to this project. Only the project owner bot may use this. It shows each bot\'s own profile and this project\'s membership only; it never exposes other projects\' data.',
|
|
158
|
+
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
|
159
|
+
output: stringOutput,
|
|
160
|
+
async execute(args, exec) {
|
|
161
|
+
const sessionId = exec?.agent?.id ?? exec?.agent?.session?.id
|
|
162
|
+
return service.listBotsPoolFromBot(sessionId)
|
|
163
|
+
},
|
|
164
|
+
})
|
|
165
|
+
|
|
166
|
+
// DSHBOTS-229:加人申请——复用 addProjectMember 的校验、审计与入群通知。
|
|
167
|
+
ctx.tools.register({
|
|
168
|
+
name: 'team_add_member',
|
|
169
|
+
description: 'Invite an existing bot into this project group by its exact name. Only the project owner bot may use this. The invite rides the normal membership path: the bot must be active and cannot already be a member, the join is audited, and the other members are announced in the group automatically.',
|
|
170
|
+
parameters: {
|
|
171
|
+
type: 'object',
|
|
172
|
+
properties: {
|
|
173
|
+
bot: { type: 'string', description: 'Exact bot name from the team bot pool' },
|
|
174
|
+
},
|
|
175
|
+
required: ['bot'],
|
|
176
|
+
additionalProperties: false,
|
|
177
|
+
},
|
|
178
|
+
output: stringOutput,
|
|
179
|
+
async execute(args, exec) {
|
|
180
|
+
const sessionId = exec?.agent?.id ?? exec?.agent?.session?.id
|
|
181
|
+
const result = await service.addMemberFromBot(sessionId, args)
|
|
182
|
+
return `Added ${result.member.name} to ${result.project.key} as ${result.member.member_role}.`
|
|
183
|
+
},
|
|
184
|
+
})
|
|
185
|
+
|
|
186
|
+
// DSHBOTS-229:建 bot 申请——仅申请入口,复用 createBot 的全部校验与审计。
|
|
187
|
+
ctx.tools.register({
|
|
188
|
+
name: 'team_create_bot',
|
|
189
|
+
description: 'Request a brand-new bot for the team. Only the project owner bot may use this. The request goes through the normal bot creation path, so name format/uniqueness and provider/model validation still apply, and the audit records you as the requester. The new bot is not added to this project automatically; invite it with team_add_member.',
|
|
190
|
+
parameters: {
|
|
191
|
+
type: 'object',
|
|
192
|
+
properties: {
|
|
193
|
+
name: { type: 'string', description: 'Bot name (Chinese/letters/digits/underscore/hyphen, up to 24 chars)' },
|
|
194
|
+
role: { type: 'string', description: 'Short job role, for example 开发 or 设计' },
|
|
195
|
+
instructions: { type: 'string', description: 'Standing instructions for the new bot' },
|
|
196
|
+
provider: { type: 'string', description: 'Model provider (must pair with model)' },
|
|
197
|
+
model: { type: 'string', description: 'Model id (must pair with provider)' },
|
|
198
|
+
effort: { type: 'string', description: 'Optional reasoning effort' },
|
|
199
|
+
fallbackProvider: { type: 'string', description: 'Optional fallback model provider (must pair with fallbackModel)' },
|
|
200
|
+
fallbackModel: { type: 'string', description: 'Optional fallback model id' },
|
|
201
|
+
fallbackEffort: { type: 'string', description: 'Optional fallback reasoning effort' },
|
|
202
|
+
color: { type: 'string', description: 'Avatar color: blue/teal/violet/amber/coral/pink/green/gray' },
|
|
203
|
+
filePolicy: { type: 'string', enum: ['workspace-write', 'read-only', 'danger-full-access'], description: 'File sandbox tier for the new bot; omit to use the default workspace-write' },
|
|
204
|
+
},
|
|
205
|
+
required: ['name'],
|
|
206
|
+
additionalProperties: false,
|
|
207
|
+
},
|
|
208
|
+
output: stringOutput,
|
|
209
|
+
async execute(args, exec) {
|
|
210
|
+
const sessionId = exec?.agent?.id ?? exec?.agent?.session?.id
|
|
211
|
+
const bot = await service.createBotFromBot(sessionId, args)
|
|
212
|
+
return `Created bot ${bot.name} (status: ${bot.status}). Invite it to a project with team_add_member.`
|
|
213
|
+
},
|
|
214
|
+
})
|
|
215
|
+
|
|
61
216
|
ctx.tools.register({
|
|
62
217
|
name: 'team_recall',
|
|
63
218
|
description: 'Expand one truncated context item by its reference id. Accepts a message id (m_xxxxxx), a task comment id (c_xxxxxx), a run id (run_xxxxxx), or a task number such as DEMO-7. Returns the full stored text for that project only.',
|
|
@@ -97,6 +252,95 @@ export function installTeamTools(ctx, service) {
|
|
|
97
252
|
},
|
|
98
253
|
})
|
|
99
254
|
|
|
255
|
+
// ── 总监记忆管理工具集(DSHBOTS-239):list / 同名覆盖写 / 批量清理 ──
|
|
256
|
+
// 服务层 ownerContextFor 权威鉴权;此处注册形态与 DIRECTOR_ONLY_TOOLS 兜底同源。
|
|
257
|
+
|
|
258
|
+
ctx.tools.register({
|
|
259
|
+
name: 'team_memory_list',
|
|
260
|
+
description: 'List existing long-term memories in one scope (bot / project / team) for hygiene inspection: entries with short id, topic, updated time and a content preview, optionally filtered by topic substring. Director-only.',
|
|
261
|
+
parameters: {
|
|
262
|
+
type: 'object',
|
|
263
|
+
properties: {
|
|
264
|
+
scope: { type: 'string', enum: ['bot', 'project', 'team'], description: 'Which memory scope to enumerate: bot = your own memories, project = this project, team = whole team. Default project' },
|
|
265
|
+
topic: { type: 'string', description: 'Optional substring filter on the topic label' },
|
|
266
|
+
limit: { type: 'integer', description: 'Max entries to return (1-200, default 50)' },
|
|
267
|
+
},
|
|
268
|
+
additionalProperties: false,
|
|
269
|
+
},
|
|
270
|
+
output: stringOutput,
|
|
271
|
+
async execute(args, exec) {
|
|
272
|
+
const sessionId = exec?.agent?.id ?? exec?.agent?.session?.id
|
|
273
|
+
const rows = service.memoryListFromBot(sessionId, args)
|
|
274
|
+
if (!rows.length) return 'No active memories in this scope.'
|
|
275
|
+
return rows
|
|
276
|
+
.map(row => `- [${row.id.slice(-6)}] ${row.topic} (${row.scope_type}, updated ${row.updated_at})\n ${String(row.content).replace(/\s+/g, ' ').slice(0, 240)}`)
|
|
277
|
+
.join('\n')
|
|
278
|
+
},
|
|
279
|
+
})
|
|
280
|
+
|
|
281
|
+
ctx.tools.register({
|
|
282
|
+
name: 'team_memory_write',
|
|
283
|
+
description: 'Write a durable memory with same-name overwrite: an active memory with the same scope+topic is updated in place (revision bumps, event trail kept) instead of appending a duplicate entry; otherwise a new memory is created. Use it to refresh a wording to the latest final state instead of piling up near-duplicates. Scope rules: bot = your own, project = this project, team = whole team. Never store secrets or credentials. Director-only.',
|
|
284
|
+
parameters: {
|
|
285
|
+
type: 'object',
|
|
286
|
+
properties: {
|
|
287
|
+
scope: { type: 'string', enum: ['bot', 'project', 'team'], description: 'bot: only you remember it; project: every project bot can use it; team: shared by the whole team (owner bots only)' },
|
|
288
|
+
topic: { type: 'string', description: 'Short topic label; same topic in the same scope is overwritten in place' },
|
|
289
|
+
content: { type: 'string', description: 'The durable memory, with enough context to be useful later' },
|
|
290
|
+
},
|
|
291
|
+
required: ['scope', 'topic', 'content'],
|
|
292
|
+
additionalProperties: false,
|
|
293
|
+
},
|
|
294
|
+
output: stringOutput,
|
|
295
|
+
async execute(args, exec) {
|
|
296
|
+
const sessionId = exec?.agent?.id ?? exec?.agent?.session?.id
|
|
297
|
+
const { memory, overwritten } = service.memoryWriteFromBot(sessionId, args)
|
|
298
|
+
return `${overwritten ? 'Overwrote' : 'Saved'} ${memory.scope_type} memory "${memory.topic}" (rev ${memory.revision}).`
|
|
299
|
+
},
|
|
300
|
+
})
|
|
301
|
+
|
|
302
|
+
ctx.tools.register({
|
|
303
|
+
name: 'team_memory_cleanup',
|
|
304
|
+
description: 'Batch-deprecate stale memories in one scope: matched entries are archived (terminal — excluded from recall), each keeps its memory_events trail, and the batch is audited as memory.cleanup with the cleaned entries listed. Two criteria, combinable: `task` archives a closed card\'s process records (its 任务 KEY-N / KEY-N 交付记录 topics; the task must already be done or canceled); `topics` archives the explicitly listed topics — use it for older wordings that conflict with a newer final decision. Do not archive entries recording the user\'s explicit decisions. Director-only.',
|
|
305
|
+
parameters: {
|
|
306
|
+
type: 'object',
|
|
307
|
+
properties: {
|
|
308
|
+
scope: { type: 'string', enum: ['bot', 'project', 'team'], description: 'Which memory scope to clean: bot = your own, project = this project, team = whole team' },
|
|
309
|
+
topics: { type: 'array', items: { type: 'string' }, description: 'Exact topic labels to archive in this scope' },
|
|
310
|
+
task: { type: 'string', description: 'Closed card (KEY-N) whose process-record memories should be archived; rejected unless the task is done or canceled' },
|
|
311
|
+
},
|
|
312
|
+
required: ['scope'],
|
|
313
|
+
additionalProperties: false,
|
|
314
|
+
},
|
|
315
|
+
output: stringOutput,
|
|
316
|
+
async execute(args, exec) {
|
|
317
|
+
const sessionId = exec?.agent?.id ?? exec?.agent?.session?.id
|
|
318
|
+
const result = service.memoryCleanupFromBot(sessionId, args)
|
|
319
|
+
const cleaned = result.cleaned.map(item => `"${item.topic}"`).join(', ') || 'none'
|
|
320
|
+
const missed = result.missed.length ? ` Not found (skipped): ${result.missed.map(topic => `"${topic}"`).join(', ')}.` : ''
|
|
321
|
+
return `Archived ${result.archived} ${result.archived === 1 ? 'entry' : 'entries'}: ${cleaned}.${missed}`
|
|
322
|
+
},
|
|
323
|
+
})
|
|
324
|
+
|
|
325
|
+
ctx.tools.register({
|
|
326
|
+
name: 'team_release_bot_quota',
|
|
327
|
+
description: 'Clear a bot\'s provider quota-exhausted state immediately so its queued task runs dispatch again now, instead of waiting for the provider\'s reset time. Use when the provider says the quota already reset, or the bot must work before the recorded reset time. Idempotent: releasing an already-clear bot is a no-op. Director-only; the human owner can do the same from the bot detail panel.',
|
|
328
|
+
parameters: {
|
|
329
|
+
type: 'object',
|
|
330
|
+
properties: {
|
|
331
|
+
bot: { type: 'string', description: 'Bot id or exact bot name whose quota state should be cleared' },
|
|
332
|
+
},
|
|
333
|
+
required: ['bot'],
|
|
334
|
+
additionalProperties: false,
|
|
335
|
+
},
|
|
336
|
+
output: stringOutput,
|
|
337
|
+
async execute(args, exec) {
|
|
338
|
+
const sessionId = exec?.agent?.id ?? exec?.agent?.session?.id
|
|
339
|
+
const view = service.releaseBotQuotaFromBot(sessionId, args.bot)
|
|
340
|
+
return `Cleared quota state for ${view.name ?? args.bot}.`
|
|
341
|
+
},
|
|
342
|
+
})
|
|
343
|
+
|
|
100
344
|
ctx.tools.register({
|
|
101
345
|
name: 'team_propose_evolution',
|
|
102
346
|
description: 'Propose a versioned change to your own instructions or to the shared skill library. A human must review and approve it; this tool never applies the change.',
|
|
@@ -185,4 +429,29 @@ export function installTeamTools(ctx, service) {
|
|
|
185
429
|
return `Secret request ${request.requestId.slice(-6)} for ${request.name} is pending human approval.`
|
|
186
430
|
},
|
|
187
431
|
})
|
|
432
|
+
|
|
433
|
+
// DSHBOTS-243:通知通道产品化——成员通知 / 任务提醒,项目内任意成员可用。
|
|
434
|
+
// 投递面是宿主会话通道(runtime.steer),插件 messages 落库为准绳;跨项目目标一律拒绝。
|
|
435
|
+
ctx.tools.register({
|
|
436
|
+
name: 'team_notify',
|
|
437
|
+
description: 'Send a notification inside this project. Any project member may use this. `target=member` notifies another member bot of this project: the host session channel delivers it immediately when reachable, and the notification is always recorded in the group chat (sender = you, mention = the target). `target=task` reminds a task of this project: if the task has an active run, the reminder is steered into that run session (re-read the card and act on it); otherwise it lands as a task-thread message the owner can see on the review panel. Only members and tasks of this project are addressable; cross-project targets are rejected. A channel failure only warns and never blocks the other channel.',
|
|
438
|
+
parameters: {
|
|
439
|
+
type: 'object',
|
|
440
|
+
properties: {
|
|
441
|
+
target: { type: 'string', enum: ['member', 'task'], description: 'member = notify another project member bot; task = remind a task of this project' },
|
|
442
|
+
member: { type: 'string', description: 'Exact bot name from the project member list (required when target=member)' },
|
|
443
|
+
task: { type: 'string', description: 'Task to remind, as KEY-N (required when target=task)' },
|
|
444
|
+
message: { type: 'string', description: 'Self-contained notification body' },
|
|
445
|
+
},
|
|
446
|
+
required: ['target', 'message'],
|
|
447
|
+
additionalProperties: false,
|
|
448
|
+
},
|
|
449
|
+
output: stringOutput,
|
|
450
|
+
async execute(args, exec) {
|
|
451
|
+
const sessionId = exec?.agent?.id ?? exec?.agent?.session?.id
|
|
452
|
+
if (args.target === 'member' && !args.member) throw new Error('target=member 需要 member(目标 bot 名称)')
|
|
453
|
+
if (args.target === 'task' && !args.task) throw new Error('target=task 需要 task(KEY-N 任务编号)')
|
|
454
|
+
return service.notifyFromBot(sessionId, args)
|
|
455
|
+
},
|
|
456
|
+
})
|
|
188
457
|
}
|
package/src/updater.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import { createRequire } from 'node:module'
|
|
1
2
|
import { readFileSync } from 'node:fs'
|
|
2
3
|
import { dirname, join, resolve } from 'node:path'
|
|
4
|
+
import { fileURLToPath } from 'node:url'
|
|
3
5
|
|
|
4
6
|
const registry = (process.env.NPM_REGISTRY || 'https://registry.npmjs.org/').replace(/\/+$/, '')
|
|
5
7
|
// 每个包一条缓存:{ at, version },5 分钟内复用。
|
|
@@ -107,3 +109,53 @@ export function detectDshRuntimeVersion(env, argv1) {
|
|
|
107
109
|
}
|
|
108
110
|
return 'unknown'
|
|
109
111
|
}
|
|
112
|
+
|
|
113
|
+
// 插件部署位置向上找宿主包的目录级数上限(含起始目录):覆盖插件与宿主同装一张
|
|
114
|
+
// 依赖树的常见布局(<root>/node_modules/dsh-team-bots → <root>/node_modules/@deepseek-ai/dsh)。
|
|
115
|
+
const PLUGIN_HOST_PACKAGE_LEVELS = 6
|
|
116
|
+
|
|
117
|
+
// 从插件部署位置尽力探测宿主 dsh 版本(DSHBOTS-253):插件作为宿主子进程运行时
|
|
118
|
+
// process.argv[1] 是插件自身入口,detectDshRuntimeVersion 的 argv 链在插件宿主下恒 miss。
|
|
119
|
+
// 这里从插件自身文件位置再探两级:
|
|
120
|
+
// ① createRequire.resolve('@deepseek-ai/dsh/package.json')——插件与宿主同依赖树时命中;
|
|
121
|
+
// ② 沿插件目录逐级向上找 node_modules/@deepseek-ai/dsh/package.json。
|
|
122
|
+
// 都拿不到返回 ''(结果按进程 memoize:插件部署位置不会在运行中变化)。
|
|
123
|
+
let hostDshVersionCache = null
|
|
124
|
+
export function detectHostDshVersionFromPlugin(startDir = null) {
|
|
125
|
+
if (startDir === null && hostDshVersionCache !== null) return hostDshVersionCache
|
|
126
|
+
let version = ''
|
|
127
|
+
if (startDir === null) {
|
|
128
|
+
try {
|
|
129
|
+
const pkg = JSON.parse(readFileSync(createRequire(import.meta.url).resolve('@deepseek-ai/dsh/package.json'), 'utf8'))
|
|
130
|
+
if (typeof pkg?.version === 'string' && pkg.version) version = pkg.version
|
|
131
|
+
} catch {
|
|
132
|
+
// 不在可解析的依赖树内:走目录上溯。
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (!version) {
|
|
136
|
+
let dir = resolve(startDir ?? dirname(fileURLToPath(import.meta.url)))
|
|
137
|
+
for (let level = 0; level < PLUGIN_HOST_PACKAGE_LEVELS; level += 1) {
|
|
138
|
+
try {
|
|
139
|
+
const pkg = JSON.parse(readFileSync(join(dir, 'node_modules', '@deepseek-ai', 'dsh', 'package.json'), 'utf8'))
|
|
140
|
+
if (typeof pkg?.version === 'string' && pkg.version) {
|
|
141
|
+
version = pkg.version
|
|
142
|
+
break
|
|
143
|
+
}
|
|
144
|
+
} catch {
|
|
145
|
+
// 本级没有宿主包:继续向上。
|
|
146
|
+
}
|
|
147
|
+
const parent = dirname(dir)
|
|
148
|
+
if (parent === dir) break
|
|
149
|
+
dir = parent
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (startDir === null) hostDshVersionCache = version
|
|
153
|
+
return version
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// dsh 版本展示值归一(DSHBOTS-253):探测失败形态(null/undefined/'unknown'/空串/纯空白)
|
|
157
|
+
// 一律归为 '',UI 据此整行隐藏,不再展示 unknown 占位。
|
|
158
|
+
export function displayDshVersion(version) {
|
|
159
|
+
const value = typeof version === 'string' ? version.trim() : ''
|
|
160
|
+
return value && value !== 'unknown' ? value : ''
|
|
161
|
+
}
|
package/src/usage-reconcile.js
CHANGED
|
@@ -33,7 +33,7 @@ export function setPrice(store, input) {
|
|
|
33
33
|
Number(input.outputPerMtok ?? 0),
|
|
34
34
|
String(input.currency ?? BUDGET_CURRENCY).trim().toUpperCase() || BUDGET_CURRENCY,
|
|
35
35
|
]
|
|
36
|
-
if (vals.slice(0, 4).some(value => !Number.isFinite(value) || value
|
|
36
|
+
if (vals.slice(0, 4).some(value => !Number.isFinite(value) || value < 0)) throw new Error('价格必须是非负数')
|
|
37
37
|
if (existing) {
|
|
38
38
|
store.run(
|
|
39
39
|
`UPDATE model_prices SET input_per_mtok = ?, cache_read_per_mtok = ?, cache_write_per_mtok = ?,
|
package/src/usage.js
CHANGED
|
@@ -12,7 +12,7 @@ function currentPrice(store, provider, model) {
|
|
|
12
12
|
// 单条明细成本:输入侧(含缓存读写)+ 输出侧,按每百万 token 计价。
|
|
13
13
|
// recordUsage 入库与事后追认共用同一公式,保证两条口径算出的金额一致。
|
|
14
14
|
// 导出给 ./usage-reconcile.js 的 CSV 追认口径复用,避免两处各写一份公式。
|
|
15
|
-
export function costForTokens(price, tokens = {}) {
|
|
15
|
+
export function costForTokens(price, tokens = {} ) {
|
|
16
16
|
const input = Number(tokens.input ?? 0)
|
|
17
17
|
const cacheRead = Number(tokens.cacheRead ?? 0)
|
|
18
18
|
const cacheWrite = Number(tokens.cacheWrite ?? 0)
|
|
@@ -111,7 +111,7 @@ function andClause(where, clause) {
|
|
|
111
111
|
// 成本聚合(含追认):已计价明细用入库时算死的成本,未计价明细(total_cost IS NULL)
|
|
112
112
|
// 按当前价目表补算——价目配齐后无需迁移,聚合结果即全量。pricedCalls/unpricedCalls
|
|
113
113
|
// 也随之按「当前能否计价」统计:能追认的未计价计入 priced,仍无价可追认的才是真未计价。
|
|
114
|
-
function costBreakdown(store, where, params, budgetCurrency, prices = null) {
|
|
114
|
+
function costBreakdown(store, where, params, budgetCurrency, prices = null, join = '') {
|
|
115
115
|
const priceMap = prices ?? currentPriceMap(store)
|
|
116
116
|
const rows = store.all(
|
|
117
117
|
`SELECT u.currency AS currency,
|
|
@@ -125,7 +125,7 @@ function costBreakdown(store, where, params, budgetCurrency, prices = null) {
|
|
|
125
125
|
COALESCE(SUM(CASE WHEN u.total_cost IS NULL THEN u.cache_write_tokens ELSE 0 END), 0) AS null_cache_write_tokens,
|
|
126
126
|
COALESCE(SUM(CASE WHEN u.total_cost IS NULL THEN u.output_tokens ELSE 0 END), 0) AS null_output_tokens,
|
|
127
127
|
COALESCE(SUM(CASE WHEN u.total_cost IS NULL THEN u.reasoning_tokens ELSE 0 END), 0) AS null_reasoning_tokens
|
|
128
|
-
FROM usage_events u ${where}
|
|
128
|
+
FROM usage_events u ${join} ${where}
|
|
129
129
|
GROUP BY u.currency, u.provider, u.model`,
|
|
130
130
|
...params,
|
|
131
131
|
)
|
|
@@ -223,10 +223,11 @@ const ZERO_TOTALS = {
|
|
|
223
223
|
|
|
224
224
|
// 单条件聚合:token 与调用次数 + 成本分币种。
|
|
225
225
|
// prices 为调用方已取好的当前价目表(usageSnapshot 只取一次,避免 N+1);缺省自行加载。
|
|
226
|
-
|
|
226
|
+
// join 为可选的 JOIN 子句(任务级口径需要 LEFT JOIN runs 追认历史 task_id,见 taskUsageTotals)。
|
|
227
|
+
export function aggregateUsage(store, filters = [], params = [], budgetCurrency = BUDGET_CURRENCY, prices = null, join = '') {
|
|
227
228
|
const where = filterClause(filters)
|
|
228
|
-
const row = store.get(`SELECT ${AGGREGATES} FROM usage_events u ${where}`, ...params)
|
|
229
|
-
const breakdown = costBreakdown(store, where, params, budgetCurrency, prices)
|
|
229
|
+
const row = store.get(`SELECT ${AGGREGATES} FROM usage_events u ${join} ${where}`, ...params)
|
|
230
|
+
const breakdown = costBreakdown(store, where, params, budgetCurrency, prices, join)
|
|
230
231
|
return mapTotals(row, breakdown)
|
|
231
232
|
}
|
|
232
233
|
|
|
@@ -234,6 +235,46 @@ export function runUsageTotals(store, runId, budgetCurrency = BUDGET_CURRENCY) {
|
|
|
234
235
|
return aggregateUsage(store, ['u.run_id = ?'], [runId], budgetCurrency)
|
|
235
236
|
}
|
|
236
237
|
|
|
238
|
+
// —— 任务级 usage 聚合(DSHBOTS-212)——
|
|
239
|
+
// 口径:一个任务端到端花多少 token。两条归因路径合一:
|
|
240
|
+
// 1) 新明细:usage_events.task_id(lifecycle 记账时随 run 透传,DSHBOTS-212 起)。
|
|
241
|
+
// 2) 历史明细:task_id 列上线前的存量行 task_id 为 NULL,经 run_id JOIN runs 追认
|
|
242
|
+
// (runs.task_id 自始有值)。COALESCE 两条路径同权,不做一次性回填迁移。
|
|
243
|
+
// 覆盖该任务全部运行:成功交付、失败重试(attempt 递增仍同 run 行)、核验/受阻处理
|
|
244
|
+
// 派生运行(task_id 相同)——「端到端成本」即该任务名下发生过的一切模型消费。
|
|
245
|
+
// 缓存 token 分列(cache_read/cache_write),计价沿用 costForTokens 既有口径,不另算。
|
|
246
|
+
const RUN_TASK_JOIN = 'LEFT JOIN runs r ON r.id = u.run_id'
|
|
247
|
+
const EFFECTIVE_TASK_ID = 'COALESCE(u.task_id, r.task_id)'
|
|
248
|
+
|
|
249
|
+
export function taskUsageTotals(store, taskId, budgetCurrency = BUDGET_CURRENCY) {
|
|
250
|
+
return aggregateUsage(store, [`${EFFECTIVE_TASK_ID} = ?`], [taskId], budgetCurrency, null, RUN_TASK_JOIN)
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// 任务子树 id 集(含自身):沿 tasks.parent_task_id 下钻全部后代。
|
|
254
|
+
// UNION(非 UNION ALL)天然去重:即使脏数据造出环也会收敛终止。
|
|
255
|
+
export function taskSubtreeIds(store, taskId) {
|
|
256
|
+
const rows = store.all(
|
|
257
|
+
`WITH RECURSIVE tree(id) AS (
|
|
258
|
+
SELECT id FROM tasks WHERE id = ?
|
|
259
|
+
UNION
|
|
260
|
+
SELECT t.id FROM tasks t JOIN tree ON t.parent_task_id = tree.id
|
|
261
|
+
) SELECT id FROM tree`,
|
|
262
|
+
taskId,
|
|
263
|
+
)
|
|
264
|
+
return rows.map(row => row.id)
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// 含子树的任务级口径:主项 + 全部后代子卡一并聚合。
|
|
268
|
+
// 拆分划算判定(C_removed > C_introduced)用它与「同类整卡任务」的 taskUsageTotals
|
|
269
|
+
// 对比:拆分后总成本 = 主项 usageTotal(含子卡),拆掉的是串行等待,引入的是每卡的
|
|
270
|
+
// 会话预热/交接重复上下文——两个口径都含缓存 token 分列,可直接看输入侧增量。
|
|
271
|
+
export function taskTreeUsageTotals(store, taskId, budgetCurrency = BUDGET_CURRENCY) {
|
|
272
|
+
const ids = taskSubtreeIds(store, taskId)
|
|
273
|
+
if (!ids.length) return { ...ZERO_TOTALS }
|
|
274
|
+
const marks = `(${ids.map(() => '?').join(', ')})`
|
|
275
|
+
return aggregateUsage(store, [`${EFFECTIVE_TASK_ID} IN ${marks}`], ids, budgetCurrency, null, RUN_TASK_JOIN)
|
|
276
|
+
}
|
|
277
|
+
|
|
237
278
|
// 用量时间窗(DSHBOTS-121):今日 / 7 日 / 30 日 / 至今 四档。
|
|
238
279
|
// 口径:今日 = 产品时区(默认 Asia/Shanghai)当日 0 点起;7 日 / 30 日 = 滚动窗口;
|
|
239
280
|
// 至今 = 不设下界。明细 occurred_at 存的是 ISO UTC 字符串,窗口起点先换算成 UTC ISO 再比较。
|
|
@@ -255,7 +296,7 @@ function zoneClock(ms, timeZone) {
|
|
|
255
296
|
minute: '2-digit',
|
|
256
297
|
second: '2-digit',
|
|
257
298
|
})
|
|
258
|
-
const parts
|
|
299
|
+
const parts = {}
|
|
259
300
|
for (const part of dtf.formatToParts(new Date(ms))) {
|
|
260
301
|
if (part.type !== 'literal') parts[part.type] = part.value
|
|
261
302
|
}
|
|
@@ -285,7 +326,7 @@ function zoneDay(ms, timeZone) {
|
|
|
285
326
|
|
|
286
327
|
// 解析时间窗:today / 7d / 30d / all,非法键回退 30 日。
|
|
287
328
|
// since 为 null 表示「至今」(没有下界);dayCount 是日历面板要画的根数。
|
|
288
|
-
export function resolveUsageWindow(key, options = {}) {
|
|
329
|
+
export function resolveUsageWindow(key, options = {} ) {
|
|
289
330
|
const now = Number(options.now ?? Date.now())
|
|
290
331
|
const timeZone = options.timeZone ?? USAGE_TIME_ZONE
|
|
291
332
|
const wanted = USAGE_WINDOW_KEYS.includes(String(key)) ? String(key) : '30d'
|
|
@@ -568,7 +609,7 @@ const SNAPSHOT_CACHE_MAX = 8
|
|
|
568
609
|
|
|
569
610
|
// 缓存按 store 分桶:测试里每个用例一个临时库,共用一张表会串味。
|
|
570
611
|
const snapshotCaches = new WeakMap()
|
|
571
|
-
const liveSnapshotCaches = new Set()
|
|
612
|
+
const liveSnapshotCaches = new Set ()
|
|
572
613
|
|
|
573
614
|
function cacheFor(store) {
|
|
574
615
|
let cache = snapshotCaches.get(store)
|
|
@@ -604,7 +645,7 @@ export function clearUsageSnapshotCache() {
|
|
|
604
645
|
for (const cache of liveSnapshotCaches) cache.clear()
|
|
605
646
|
}
|
|
606
647
|
|
|
607
|
-
export function usageSnapshot(store, projectId, days = 30, options = {}) {
|
|
648
|
+
export function usageSnapshot(store, projectId, days = 30, options = {} ) {
|
|
608
649
|
const budgetCurrency = String(options.currency ?? BUDGET_CURRENCY).toUpperCase() || BUDGET_CURRENCY
|
|
609
650
|
const soloBotId = options.soloBotId ?? null
|
|
610
651
|
const ttl = Number.isFinite(options.cacheTtlMs) ? options.cacheTtlMs : SNAPSHOT_CACHE_TTL_MS
|
|
@@ -620,7 +661,7 @@ export function usageSnapshot(store, projectId, days = 30, options = {}) {
|
|
|
620
661
|
return value
|
|
621
662
|
}
|
|
622
663
|
|
|
623
|
-
function computeUsageSnapshot(store, projectId, days = 30, options = {}) {
|
|
664
|
+
function computeUsageSnapshot(store, projectId, days = 30, options = {} ) {
|
|
624
665
|
const budgetCurrency = String(options.currency ?? BUDGET_CURRENCY).toUpperCase() || BUDGET_CURRENCY
|
|
625
666
|
const soloBotId = options.soloBotId ?? null
|
|
626
667
|
// 时间窗口径(DSHBOTS-121):传 window 走四档窗口;不传时沿用旧的「近 N 天」滚动窗口。
|
package/src/wechat/channel.js
CHANGED
|
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto'
|
|
|
2
2
|
import { createRequire } from 'node:module'
|
|
3
3
|
import { TencentIlinkTransport } from '../../vendor/wechat-ilink/index.js'
|
|
4
4
|
import { handleCommand, isRetryable, outboundChunks, WechatBusinessError, WechatIlinkError } from './commands.js'
|
|
5
|
+
import { batchDigest, failureText, welcomeAdmin } from './format.js'
|
|
5
6
|
import { AppError } from '../errors.js'
|
|
6
7
|
|
|
7
8
|
const { version: PLUGIN_VERSION } = createRequire(import.meta.url)('../../package.json')
|
|
@@ -18,12 +19,8 @@ const DAY_MS = 24 * 60 * 60 * 1000
|
|
|
18
19
|
const OUTBOX_MAX_ATTEMPTS = 3
|
|
19
20
|
/** 合批窗口:窗口内到达的多条推送合并为一次发送(一轮任务事件常并发多条,逐条发占消息额度)。 */
|
|
20
21
|
const OUTBOX_BATCH_WINDOW_MS = 1500
|
|
21
|
-
/** 合批摘要的明细行数上限:超过只保留最旧的 N 条原文,其余以「等 N 项」汇总。 */
|
|
22
|
-
const OUTBOX_BATCH_LINES = 5
|
|
23
22
|
/** 进程内记忆已处理消息,避免 cursor 未推进时重复回复。 */
|
|
24
23
|
const PROCESSED_MEMORY_LIMIT = 500
|
|
25
|
-
/** 用户侧只给通用失败提示,具体错误写日志。 */
|
|
26
|
-
const GENERIC_FAILURE_TEXT = '消息处理失败,稍后重试'
|
|
27
24
|
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
|
|
28
25
|
|
|
29
26
|
/** 授权响应里可能出现的用户标识字段(vendor 的 confirmed 返回 userId=ilink_user_id)。 */
|
|
@@ -238,7 +235,7 @@ export class WechatChannel {
|
|
|
238
235
|
if (voided > 0) this.log.info?.(`[wechat] 链接建立,作废此前待发堆积 ${voided} 条(不补发)`)
|
|
239
236
|
const transport = this.makeTransport(credentials)
|
|
240
237
|
const abort = new AbortController()
|
|
241
|
-
const epoch
|
|
238
|
+
const epoch = { abort, credentials }
|
|
242
239
|
this.transport = transport
|
|
243
240
|
this.epoch = epoch
|
|
244
241
|
this.phase = 'connecting'
|
|
@@ -276,9 +273,9 @@ export class WechatChannel {
|
|
|
276
273
|
}
|
|
277
274
|
} catch (error) {
|
|
278
275
|
if (signal.aborted || this.epoch !== epoch) return
|
|
279
|
-
if (error instanceof WechatIlinkError && ['AUTH_REPLACED', 'AUTH_EXPIRED'].includes(error.code)) {
|
|
276
|
+
if (error instanceof WechatIlinkError && ['AUTH_REPLACED', 'AUTH_EXPIRED'].includes((error ).code)) {
|
|
280
277
|
this.phase = 'needs_reauth'
|
|
281
|
-
this.error = `${error.code}: ${error.message}`
|
|
278
|
+
this.error = `${(error ).code}: ${(error ).message}`
|
|
282
279
|
this.log.warn?.('[wechat] 凭证失效,需要重新扫码')
|
|
283
280
|
return
|
|
284
281
|
}
|
|
@@ -332,7 +329,7 @@ export class WechatChannel {
|
|
|
332
329
|
this.store.saveAdminPeer(peerId)
|
|
333
330
|
this.pendingAdmin = null
|
|
334
331
|
this.log.info?.(`[wechat] 管理员已绑定(本次授权会话首条消息): ${peerId}`)
|
|
335
|
-
await this.sendTo(peerId,
|
|
332
|
+
await this.sendTo(peerId, welcomeAdmin(), signal)
|
|
336
333
|
await this.flushOutbox(transport, signal)
|
|
337
334
|
return
|
|
338
335
|
}
|
|
@@ -341,18 +338,24 @@ export class WechatChannel {
|
|
|
341
338
|
return
|
|
342
339
|
}
|
|
343
340
|
try {
|
|
344
|
-
|
|
341
|
+
// DSHBOTS-208 直达对话上下文:管理员会话绑定的项目 key(路由成功后由命令层回写)。
|
|
342
|
+
const reply = await handleCommand(this.service, message.text, {
|
|
343
|
+
boundKey: this.store.getDirectProjectKey?.() ?? null,
|
|
344
|
+
bind: key => this.store.saveDirectProjectKey?.(key),
|
|
345
|
+
// 上方已校验 peerId === admin(非管理员消息整条忽略),显式带过 fail-closed 命令门
|
|
346
|
+
isAdmin: true,
|
|
347
|
+
})
|
|
345
348
|
await this.sendTo(peerId, reply, signal)
|
|
346
349
|
} catch (error) {
|
|
347
350
|
if (isBusinessError(error)) {
|
|
348
351
|
// 业务性拒绝(如任务不存在、任务号非法):给用户可读提示即可,不算处理失败
|
|
349
352
|
this.log.warn?.(`[wechat] 指令被拒绝: ${this.errorText(error)}`)
|
|
350
|
-
await this.sendTo(peerId, String(error?.message ?? '指令无法执行'), signal)
|
|
353
|
+
await this.sendTo(peerId, String((error )?.message ?? '指令无法执行'), signal)
|
|
351
354
|
.catch(sendError => this.log.warn?.(`[wechat] 提示发送失败: ${this.errorText(sendError)}`))
|
|
352
355
|
return
|
|
353
356
|
}
|
|
354
357
|
this.log.warn?.(`[wechat] 指令执行失败: ${this.errorText(error)}`)
|
|
355
|
-
await this.sendTo(peerId,
|
|
358
|
+
await this.sendTo(peerId, failureText(), signal)
|
|
356
359
|
.catch(sendError => this.log.warn?.(`[wechat] 失败提示发送失败: ${this.errorText(sendError)}`))
|
|
357
360
|
// 交给上层:这条没处理成功,cursor 不推进,下一轮还会重试
|
|
358
361
|
throw error
|
|
@@ -486,15 +489,6 @@ function isBusinessError(error) {
|
|
|
486
489
|
return error instanceof AppError || error instanceof WechatBusinessError || error?.permanent === true
|
|
487
490
|
}
|
|
488
491
|
|
|
489
|
-
/** 合批摘要:首行条数,逐条保留原文(每条自带 KEY-N 与状态),超明细上限截断加「等 N 项」。 */
|
|
490
|
-
function batchDigest(items) {
|
|
491
|
-
const shown = items.slice(0, OUTBOX_BATCH_LINES)
|
|
492
|
-
const rest = items.length - shown.length
|
|
493
|
-
const lines = [`任务动态 ${items.length} 条:`, ...shown.map(item => item.text)]
|
|
494
|
-
if (rest > 0) lines.push(`……等 ${rest} 项`)
|
|
495
|
-
return lines.join('\n')
|
|
496
|
-
}
|
|
497
|
-
|
|
498
492
|
/** 从授权响应里取用户标识(vendor confirmed 返回 userId=ilink_user_id)。 */
|
|
499
493
|
function extractAuthUserId(credentials) {
|
|
500
494
|
if (!credentials || typeof credentials !== 'object') return null
|