@oyasmi/pipiclaw 0.8.9-beta.1 → 0.8.9-beta.2
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 +8 -3
- package/dist/agent/channel-runner.d.ts +1 -0
- package/dist/agent/channel-runner.js +3 -2
- package/dist/agent/effect-ledger.d.ts +11 -0
- package/dist/agent/effect-ledger.js +42 -0
- package/dist/agent/job-manager.d.ts +90 -13
- package/dist/agent/job-manager.js +235 -20
- package/dist/agent/prompt/sections.js +11 -2
- package/dist/agent/prompt/types.d.ts +7 -1
- package/dist/agent/runner-factory.d.ts +7 -0
- package/dist/agent/session-events.js +20 -1
- package/dist/index.d.ts +1 -1
- package/dist/log.d.ts +6 -0
- package/dist/log.js +12 -0
- package/dist/memory/consolidation.d.ts +5 -0
- package/dist/memory/consolidation.js +35 -147
- package/dist/memory/extraction.d.ts +45 -0
- package/dist/memory/extraction.js +227 -0
- package/dist/memory/lifecycle.js +5 -0
- package/dist/memory/maintenance-jobs.js +7 -0
- package/dist/memory/post-turn-review.d.ts +3 -1
- package/dist/memory/post-turn-review.js +20 -189
- package/dist/memory/recall.d.ts +0 -1
- package/dist/memory/recall.js +135 -77
- package/dist/memory/sidecar-worker.d.ts +7 -0
- package/dist/memory/sidecar-worker.js +23 -5
- package/dist/paths.d.ts +1 -0
- package/dist/paths.js +11 -0
- package/dist/playbooks/background-jobs.md +40 -0
- package/dist/playbooks/catalog.d.ts +1 -7
- package/dist/playbooks/catalog.js +4 -14
- package/dist/playbooks/event-scheduling.md +8 -4
- package/dist/playbooks/memory-and-learning.md +1 -1
- package/dist/playbooks/outbound-media.md +45 -0
- package/dist/playbooks/runtime-orientation.md +1 -1
- package/dist/playbooks/task-closeout.md +1 -1
- package/dist/playbooks/task-delegation.md +10 -4
- package/dist/playbooks/task-driving.md +52 -18
- package/dist/playbooks/task-planning.md +43 -18
- package/dist/runtime/bootstrap.js +24 -3
- package/dist/runtime/channel-context.d.ts +33 -0
- package/dist/runtime/dingtalk.d.ts +22 -2
- package/dist/runtime/dingtalk.js +141 -0
- package/dist/runtime/durable-dispatch.d.ts +10 -0
- package/dist/runtime/durable-dispatch.js +42 -1
- package/dist/runtime/event-validation.d.ts +48 -0
- package/dist/runtime/event-validation.js +81 -0
- package/dist/runtime/events.d.ts +17 -8
- package/dist/runtime/events.js +96 -22
- package/dist/runtime/store.d.ts +1 -1
- package/dist/runtime/task-driver.d.ts +5 -0
- package/dist/runtime/task-driver.js +38 -12
- package/dist/settings.d.ts +11 -0
- package/dist/settings.js +12 -0
- package/dist/shared/recoverable-error.d.ts +26 -0
- package/dist/shared/recoverable-error.js +29 -0
- package/dist/shared/task-ledger.d.ts +9 -7
- package/dist/shared/task-ledger.js +1 -1
- package/dist/subagents/builtin/explorer.md +16 -0
- package/dist/subagents/builtin/researcher.md +17 -0
- package/dist/subagents/builtin/verifier.md +17 -0
- package/dist/subagents/discovery.d.ts +17 -3
- package/dist/subagents/discovery.js +88 -15
- package/dist/subagents/tool.d.ts +21 -1
- package/dist/subagents/tool.js +140 -12
- package/dist/tasks/transitions.js +3 -2
- package/dist/tools/bash.d.ts +2 -0
- package/dist/tools/bash.js +18 -5
- package/dist/tools/event-manage.js +28 -77
- package/dist/tools/index.d.ts +4 -0
- package/dist/tools/index.js +7 -2
- package/dist/tools/job.js +2 -2
- package/dist/tools/memory-manage.js +0 -1
- package/dist/tools/registry.d.ts +29 -8
- package/dist/tools/registry.js +39 -22
- package/dist/tools/send-media.d.ts +28 -0
- package/dist/tools/send-media.js +88 -0
- package/dist/tools/task-manage/create.js +5 -4
- package/dist/tools/task-manage/lifecycle.js +12 -11
- package/dist/tools/task-manage/schema.js +2 -1
- package/dist/tools/task-manage/shared.js +13 -12
- package/dist/tools/task-manage/verification.js +14 -13
- package/dist/tools/tool-details.d.ts +44 -0
- package/dist/tools/tool-details.js +62 -0
- package/dist/tui/app.js +2 -0
- package/dist/tui/terminal-media-sender.d.ts +9 -0
- package/dist/tui/terminal-media-sender.js +15 -0
- package/package.json +2 -2
- package/dist/playbooks/task-recurring.md +0 -44
- package/dist/playbooks/task-repair.md +0 -45
|
@@ -1,44 +1,78 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: task-driving
|
|
3
|
-
description:
|
|
3
|
+
description: 被 TASK_DRIVER 唤醒推进任务、留检查点,或任务停滞、被治理器暂停、元数据损坏时。
|
|
4
4
|
requires-tools: task_manage
|
|
5
5
|
priority: 41
|
|
6
6
|
---
|
|
7
7
|
|
|
8
|
-
#
|
|
8
|
+
# 任务(task)推进、断点恢复与修复
|
|
9
9
|
|
|
10
10
|
## 每次唤醒先恢复真相
|
|
11
11
|
|
|
12
|
-
1. 打开消息指定的 `tasks/<id>.md
|
|
13
|
-
2. 核对 status、最新 Current Cycle note
|
|
14
|
-
3.
|
|
12
|
+
1. 打开消息指定的 `tasks/<id>.md`,不要只依赖唤醒文本、旧对话或记忆。
|
|
13
|
+
2. 核对 status、最新 Current Cycle note、`nextAction`、`wake`、预算、依赖、`sideEffects` 和 verification。
|
|
14
|
+
3. 检查上一步产物**是否已经存在**。派发语义是 at-least-once,宕机或租约重放可能让同一步再次到达。
|
|
15
15
|
4. 只推进一个清晰的下一阶段;不要在未知状态下重复外部动作。
|
|
16
16
|
|
|
17
17
|
依赖未完成时 driver 跳过任务且不消耗 attempt;依赖缺失/cancelled/被治理器暂停、deadline 或累计预算耗尽会令任务被治理器暂停(`paused` + `pausedBy=governor`)。
|
|
18
18
|
|
|
19
19
|
## 回合结束必须留下确定性状态
|
|
20
20
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
- 发生了什么;
|
|
24
|
-
- 看到了什么证据;
|
|
25
|
-
- 下一步是什么;
|
|
26
|
-
- status 与 wake。
|
|
21
|
+
仍开放且正文或进展发生变化时,用 `task_manage progress` 一次性记录:发生了什么、看到了什么证据、下一步是什么、status 与 `wake`。
|
|
27
22
|
|
|
28
23
|
以下生命周期动作本身就是原子 checkpoint,不要再追加 progress:`candidate`、`done`、`cancel`。
|
|
29
24
|
|
|
30
|
-
`verify` 只更新 control
|
|
25
|
+
`verify` 只更新 control、不改正文。PASS 后若还要等外部审批(approval),用 `task_manage set wake=<合理时间>` 停留在 `verifying` 车道——**只改 wake、不换状态**,离开 verifying 会作废 PASS——并请用户 `/tasks approve <id>`。门禁的绑定规则见 `task-closeout.md`。除此之外不要用 `set` 代替正常进度日志。
|
|
31
26
|
|
|
32
27
|
## 等待与继续
|
|
33
28
|
|
|
34
|
-
- 等用户/外部系统/委派:`waiting` + 合理 wake
|
|
35
|
-
- 当前仍可继续:保持 `active`,清空 wake
|
|
36
|
-
- 明确停止:由用户 pause
|
|
29
|
+
- 等用户/外部系统/委派:`waiting` + 合理 `wake`,把等谁、等什么写进 `blockedReason`。
|
|
30
|
+
- 当前仍可继续:保持 `active`,清空 `wake`。
|
|
31
|
+
- 明确停止:由用户 pause;不要用极远的 `wake` 模拟暂停。
|
|
37
32
|
|
|
38
|
-
内建 driver 分钟级扫描 DingTalk `dm_*/group_*` channel
|
|
33
|
+
内建 driver 分钟级扫描 DingTalk `dm_*/group_*` channel,`wake` 到期后接续;无需 heartbeat、`.checkin` 或额外传感器。TUI 关闭后没有 daemon,不能自动唤醒。
|
|
39
34
|
|
|
40
|
-
有语义 checkpoint 时按较短 continuation delay 接续;只有用量变化、没有任务变化时按 stalled retry
|
|
35
|
+
有语义 checkpoint 时按较短 continuation delay 接续;只有用量变化、没有任务变化时按 stalled retry 退避。**不要为了拿到短退避而伪造 progress。**
|
|
41
36
|
|
|
42
37
|
## 汇报与静默
|
|
43
38
|
|
|
44
|
-
有用户需要知道的结果、风险、审批请求时正常汇报。纯内部周期检查且没有新结果时返回 `[SILENT]
|
|
39
|
+
有用户需要知道的结果、风险、审批请求时正常汇报。纯内部周期检查且没有新结果时返回 `[SILENT]`,避免发空状态卡。完成时走 `task-closeout.md`。
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
# 诊断与修复
|
|
44
|
+
|
|
45
|
+
先用 `task_manage list` 看结构化状态;让用户用 `/tasks doctor` 看带 Next step 的一致性检查,用 `/tasks stats <id>` 看 attempts/token/cost/wall time、最近结果和 verifier 状态。
|
|
46
|
+
|
|
47
|
+
## 被治理器暂停(paused + pausedBy=governor)
|
|
48
|
+
|
|
49
|
+
治理器在 deadline、累计预算耗尽、终态依赖,或**连续 3 次唤醒都没有可见进展**(fingerprint 未变,含 silent)时暂停任务(旧称 escalated)。先读 Current Cycle 和 stats,判断是空转、范围错误、预算过小还是依赖终止:
|
|
50
|
+
|
|
51
|
+
- 方向错:修 Manual/`nextAction`、重新拆解或 cancel。
|
|
52
|
+
- 预算确实不足:向用户说明后用 `task_manage set` 调整 budget/deadline,并把 status 设回 `active`。
|
|
53
|
+
- 依赖终止:恢复或重建依赖,或 `set` 更新 `dependsOn`。
|
|
54
|
+
|
|
55
|
+
被暂停的任务不能 progress/candidate;`set`(或 `/tasks resume`)是审查原因后的修复入口,**不要反射性加预算**。
|
|
56
|
+
|
|
57
|
+
## 不唤醒或频繁唤醒
|
|
58
|
+
|
|
59
|
+
可推进 = 非 done/cancelled/paused,且 `wake` 缺失、无效或已到期。
|
|
60
|
+
|
|
61
|
+
- `paused`:用户 `/tasks resume <id>`。
|
|
62
|
+
- `wake` 太远:纠正 `wake`;急催用 `/tasks run <id>`。
|
|
63
|
+
- TUI 已关闭:没有 daemon,不能自动唤醒。
|
|
64
|
+
- 反复空转:查最新 note 和 `nextAction`,修 Manual。
|
|
65
|
+
|
|
66
|
+
## 坏 frontmatter / control
|
|
67
|
+
|
|
68
|
+
frontmatter 只认开头 `---` 块中的 status/wake/schedule/recurrence/control;`control` 必须是单行 JSON。driver 对不可读 frontmatter fail-open 以便唤醒修复,`task_manage` 对坏 control fail-closed 防止覆盖。
|
|
69
|
+
|
|
70
|
+
先 `read`,**只有此场景**才用 `edit` 修合法 frontmatter;随后用 `task_manage set` 让后续更新回到工具轨道。control 不确定时删除坏行,再用 `set` 重建默认结构。
|
|
71
|
+
|
|
72
|
+
## 失效的门禁与孤儿事件
|
|
73
|
+
|
|
74
|
+
改动契约段或产物后 done 被拒绝:重跑 verifier 或请用户重新 approve,不绕过。完整绑定规则和无失效顺序见 `task-closeout.md`。
|
|
75
|
+
|
|
76
|
+
done/cancel 会清理 `task.<channelId>.<id>.*` 事件;孤儿事件用 `event_manage` 删除。旧的 `.checkin` / `.schedule` 事件是 legacy——把 cron 折进 frontmatter 的 `schedule` 后删除事件,以 `wake` 为单一恢复条件(`/tasks doctor` 会给出迁移提示)。
|
|
77
|
+
|
|
78
|
+
daemon 重启会清空内存 cooldown,可推进任务可能很快重放。任务文件是恢复真相:每次先核对已完成产物,避免重复外部动作。
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: task-planning
|
|
3
|
-
description:
|
|
3
|
+
description: 创建或重构长程任务(task)、在 task 与事件(event)之间取舍,或设定周期节奏(schedule)。
|
|
4
4
|
requires-tools: task_manage
|
|
5
5
|
priority: 40
|
|
6
6
|
---
|
|
7
7
|
|
|
8
|
-
#
|
|
8
|
+
# 长程任务(task)规划与建档
|
|
9
9
|
|
|
10
10
|
## 什么时候创建 task
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
只有工作需要**跨回合恢复**时才建:多步骤目标、等待人或外部系统、委派工作、周期性产出。当前回合能完成的简单请求不要建台账;纯提醒(无产出、无验收)用事件(event),见 `event-scheduling.md`。
|
|
13
13
|
|
|
14
14
|
## 创建内容
|
|
15
15
|
|
|
@@ -17,35 +17,60 @@ priority: 40
|
|
|
17
17
|
|
|
18
18
|
- `id`:稳定的 kebab-case。
|
|
19
19
|
- `title`:一句话标题。
|
|
20
|
-
- `goal
|
|
21
|
-
- `dod`:客观验收标准,每项必须是 `- [ ]` checkbox;纯 prose
|
|
20
|
+
- `goal`:最终要成立的**结果**,不写行动清单。
|
|
21
|
+
- `dod`:客观验收标准,每项必须是 `- [ ]` checkbox;纯 prose 或编号列表会被拒。
|
|
22
22
|
- `manual`:可复用的执行步骤、预检与返工教训。
|
|
23
23
|
- `verificationPlan`:验收者能独立执行的确定性检查。
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
默认独立验收(independent verification)加有限尝试预算。轻量记录性任务确实无需独立验收时,创建时设 `control.verificationMode: evidence`。
|
|
26
26
|
|
|
27
27
|
## control 决策
|
|
28
28
|
|
|
29
|
-
- `priority` / `deadline`:表达调度重要性和硬期限,不用 wake 冒充 deadline。
|
|
29
|
+
- `priority` / `deadline`:表达调度重要性和硬期限,不用 `wake` 冒充 deadline。
|
|
30
30
|
- `nextAction`:下一条可执行动作,避免写抽象愿望。
|
|
31
31
|
- `maxAttempts` / `maxTokens` / `maxCostUsd` / `maxWallTimeMinutes`:按风险和规模收紧;预算是停止条件,不是目标。
|
|
32
|
-
- `sideEffects`:`read-only`、`workspace` 或 `external`。发送、发布、部署、修改外部系统必须选 external
|
|
33
|
-
- `isolation: worktree`:写密集型子任务需要隔离共享 checkout
|
|
34
|
-
- `parent` / `dependsOn
|
|
32
|
+
- `sideEffects`:`read-only`、`workspace` 或 `external`。发送、发布、部署、修改外部系统必须选 `external`。
|
|
33
|
+
- `isolation: worktree`:写密集型子任务需要隔离共享 checkout 时使用,见 `task-delegation.md`。
|
|
34
|
+
- `parent` / `dependsOn`:只用于真实分解;`parent` 表归属,`dependsOn` 表执行前置。
|
|
35
35
|
|
|
36
|
-
创建和 set 会拒绝不存在的关联、自指、parent 环和 dependency 环。父任务可以 dependsOn 自己的 child
|
|
36
|
+
创建和 `set` 会拒绝不存在的关联、自指、parent 环和 dependency 环。父任务可以 `dependsOn` 自己的 child 表达 join;父任务有未闭环 child 时不能 done。
|
|
37
37
|
|
|
38
|
-
|
|
38
|
+
外部副作用与独立验收并存时,DoD/Verification 要验收"**待执行动作及其输入已准备正确**"(内容、目标、参数、预演、回滚方案),不要把尚未获批的外部动作本身写成 candidate 前必须勾选的项——否则会形成"先执行才能勾选"与"先验收批准才能执行"的死循环。实际执行结果由审批记录和 done evidence 收口。
|
|
39
39
|
|
|
40
|
-
|
|
40
|
+
## 六个状态与时间
|
|
41
41
|
|
|
42
|
-
|
|
42
|
+
每个状态只对应一种 driver 行为:
|
|
43
|
+
|
|
44
|
+
- `active`:可推进(受 `wake` 门控)。
|
|
43
45
|
- `waiting`:等用户/外部条件/委派结果;等谁、等什么写进 `control.blockedReason`。
|
|
44
46
|
- `verifying`:只做独立验收,不继续实现。
|
|
45
|
-
- `paused
|
|
46
|
-
- `done`:完成;有 schedule 则原地睡到下次 occurrence,否则归档。
|
|
47
|
+
- `paused`:driver 不运行。用户暂停记 `pausedBy=user`,治理器停止记 `pausedBy=governor`。
|
|
48
|
+
- `done`:完成;有 `schedule` 则原地睡到下次 occurrence,否则归档。
|
|
47
49
|
- `cancelled`:放弃并归档。
|
|
48
50
|
|
|
49
|
-
`wake`
|
|
51
|
+
`wake` 是**最早重新检查时间**,不是截止时间。等待时设置现实的 `wake`;可继续时清空 `wake`,让 driver 按 cooldown 接续。
|
|
52
|
+
|
|
53
|
+
## 周期性任务(schedule)
|
|
54
|
+
|
|
55
|
+
一个周期任务就是**一个文件**:`tasks/<id>.md`。节奏写在 frontmatter 的 `schedule`(五段 cron,按主机时区解释),做法与跨周期经验写在正文。没有配套事件,也没有 `.schedule` 命名约定。`recurrence` 只是给人看的可选标注(如 `每周一`),没有机器语义——**周期性 = `schedule` 是否存在**。
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
task_manage create id=weekly-report title=... goal=... dod=... schedule="30 9 * * 1"
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
cron 最密每 30 分钟一次,落盘前校验。纯提醒不建 task,用普通 periodic 事件。
|
|
62
|
+
|
|
63
|
+
**首次执行遵循 cron 语义**:不显式传 `wake` 时,create 会把 `wake` 预约到下一次 occurrence,任务处于 `active` + 未来 `wake`——像 crontab 一样,创建不等于立刻跑。需要立刻开跑就显式传一个当下或过去的 `wake`。
|
|
64
|
+
|
|
65
|
+
到点后 **runtime 直接开下一周期**,不需要(也没有)手工开周期的动作:折叠上一周期日志入 History、清空本周期用量与验收授权元数据、置 `active`,然后派发一条普通驱动唤醒。你醒来面对的就是一个待推进的新周期,和其他唤醒无异。
|
|
66
|
+
|
|
67
|
+
- 改节奏:`task_manage set schedule="<新 cron>"`;任务当前是 done 时写盘会重算 `wake`。一处真相。
|
|
68
|
+
- 暂停 / 恢复:`/tasks pause <id>` / `/tasks resume <id>`。
|
|
69
|
+
- 退役:`task_manage cancel`,归档任务并清理全部 task-owned 事件。
|
|
70
|
+
- 上周期未完成:不要覆盖或虚勾 DoD。先完成、如实缩小本轮范围并验收,或与用户确认后 cancel 整项任务。
|
|
71
|
+
|
|
72
|
+
每轮闭环前把返工原因、预检步骤和格式偏好写回 Manual;跨任务可复用时才沉淀成 workspace skill。
|
|
73
|
+
|
|
74
|
+
## 建档后自检
|
|
50
75
|
|
|
51
|
-
|
|
76
|
+
创建后读取落盘文件,确认 Goal、DoD、Manual、Verification 和 control 与真实意图一致。后续每个驱动回合按 `task-driving.md` 推进。
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "fs";
|
|
2
2
|
import { join } from "path";
|
|
3
3
|
import { formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../agent/commands.js";
|
|
4
|
+
import { channelEffectCount } from "../agent/effect-ledger.js";
|
|
4
5
|
import { getOrCreateRunner } from "../agent/index.js";
|
|
6
|
+
import { configureJobRuntime, restoreChannelJobs } from "../agent/job-manager.js";
|
|
5
7
|
import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
|
|
6
8
|
import { resetRunner } from "../agent/runner-factory.js";
|
|
7
9
|
import { renderStatus } from "../agent/status-render.js";
|
|
@@ -425,6 +427,10 @@ export function createRuntimeContext(options) {
|
|
|
425
427
|
authConfigPath: options.paths.authConfigPath,
|
|
426
428
|
modelsConfigPath: options.paths.modelsConfigPath,
|
|
427
429
|
onSessionEvent: options.observer,
|
|
430
|
+
// The DingTalk bot is the media sender for this transport; enables `send_media`.
|
|
431
|
+
// `bot` is defined below in this same scope and initialized before any message
|
|
432
|
+
// (and thus any getRunner call) can arrive.
|
|
433
|
+
mediaSender: bot,
|
|
428
434
|
});
|
|
429
435
|
channelRunners.set(channelId, runner);
|
|
430
436
|
}
|
|
@@ -482,9 +488,16 @@ export function createRuntimeContext(options) {
|
|
|
482
488
|
dispatchTask: async (id) => {
|
|
483
489
|
const channelDir = getChannelDir(options.paths.workspaceDir, event.channelId);
|
|
484
490
|
const entry = (await readActiveTasks(join(channelDir, "tasks"))).find((candidate) => candidate.id === id);
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
491
|
+
if (!entry)
|
|
492
|
+
return false;
|
|
493
|
+
// A human asking to run a task twice means twice, so this key is deliberately
|
|
494
|
+
// unique per invocation rather than sharing the driver's occurrence key (D1).
|
|
495
|
+
const now = Date.now();
|
|
496
|
+
const driverEvent = createTaskDriverEvent(event.channelId, entry, now);
|
|
497
|
+
return ((await durableDispatch?.dispatch({
|
|
498
|
+
...driverEvent,
|
|
499
|
+
dispatchId: `task:${event.channelId}:${entry.id}:manual:${new Date(now).toISOString()}`,
|
|
500
|
+
})) ?? false);
|
|
488
501
|
},
|
|
489
502
|
});
|
|
490
503
|
await bot.sendPlain(event.channelId, response);
|
|
@@ -670,6 +683,13 @@ export function createRuntimeContext(options) {
|
|
|
670
683
|
bot,
|
|
671
684
|
});
|
|
672
685
|
const executor = createExecutor();
|
|
686
|
+
// Background jobs get their persistence root and their way to wake a channel before any turn
|
|
687
|
+
// can start one, then re-adopt whatever survived the last shutdown (spec 031, D6).
|
|
688
|
+
configureJobRuntime({
|
|
689
|
+
jobsStateDir: join(options.paths.appHomeDir, "state", "jobs"),
|
|
690
|
+
dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
|
|
691
|
+
});
|
|
692
|
+
void restoreChannelJobs(executor);
|
|
673
693
|
const eventsWatcher = options.createEventsWatcher
|
|
674
694
|
? options.createEventsWatcher(options.paths.workspaceDir, bot, executor, options.paths.eventHistoryPath)
|
|
675
695
|
: createEventsWatcher(options.paths.workspaceDir, bot, executor, loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config.commandGuard, options.paths.eventHistoryPath, (event) => durableDispatch?.dispatch(event) ?? false);
|
|
@@ -717,6 +737,7 @@ export function createRuntimeContext(options) {
|
|
|
717
737
|
isChannelActive: (channelId) => channelRunners.get(channelId)?.isBusy() ?? false,
|
|
718
738
|
dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
|
|
719
739
|
onDispatch: options.onTaskDriverDispatch,
|
|
740
|
+
getEffectCount: channelEffectCount,
|
|
720
741
|
getSettings: () => {
|
|
721
742
|
runtimeSettingsManager.reload();
|
|
722
743
|
return runtimeSettingsManager.getTaskDriverSettings();
|
|
@@ -19,6 +19,39 @@
|
|
|
19
19
|
export type ProgressStyle = "full" | "rolling" | "none";
|
|
20
20
|
/** How the final answer is delivered. */
|
|
21
21
|
export type FinalDelivery = "plain" | "card";
|
|
22
|
+
/**
|
|
23
|
+
* A file the agent wants to push to a channel as a native attachment (image or
|
|
24
|
+
* downloadable file), as opposed to text/markdown in the transcript.
|
|
25
|
+
*
|
|
26
|
+
* Bytes travel in-band (`data`) rather than as a path so the sender is decoupled
|
|
27
|
+
* from where the file physically lives — the `send_media` tool reads the file
|
|
28
|
+
* through its `Executor` (which may be remote) and hands over the bytes, exactly
|
|
29
|
+
* as `read` does for images.
|
|
30
|
+
*/
|
|
31
|
+
export interface OutboundMedia {
|
|
32
|
+
/** Raw file contents. */
|
|
33
|
+
data: Buffer;
|
|
34
|
+
/** Display name shown to the recipient (e.g. "report.pdf"). */
|
|
35
|
+
fileName: string;
|
|
36
|
+
/** `image` renders inline; `file` is a downloadable attachment. */
|
|
37
|
+
kind: "image" | "file";
|
|
38
|
+
}
|
|
39
|
+
export interface MediaSendResult {
|
|
40
|
+
ok: boolean;
|
|
41
|
+
/** Human-readable failure reason, surfaced to the agent on `ok: false`. */
|
|
42
|
+
error?: string;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Transport-neutral outbound-attachment port. Implemented by each transport that
|
|
46
|
+
* can deliver files: the DingTalk bot uploads media and sends an image/file
|
|
47
|
+
* message; the terminal writes the file to disk and prints its path. The
|
|
48
|
+
* `send_media` tool depends only on this interface — never on a concrete
|
|
49
|
+
* transport — and is bound to its channel at build time (like `read`/`bash`),
|
|
50
|
+
* so `channelId` is supplied by the runtime, not by the model.
|
|
51
|
+
*/
|
|
52
|
+
export interface MediaSender {
|
|
53
|
+
sendMedia(channelId: string, media: OutboundMedia): Promise<MediaSendResult>;
|
|
54
|
+
}
|
|
22
55
|
export interface ChannelContext {
|
|
23
56
|
message: {
|
|
24
57
|
text: string;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { FinalDelivery, ProgressStyle } from "./channel-context.js";
|
|
1
|
+
import type { FinalDelivery, MediaSender, MediaSendResult, OutboundMedia, ProgressStyle } from "./channel-context.js";
|
|
2
2
|
export type BusyMessageMode = "steer" | "followUp";
|
|
3
3
|
export type BusyMessageDefaultConfig = BusyMessageMode | "followup";
|
|
4
4
|
export type ResponseMode = "full_progress_then_plain_final" | "rolling_progress_then_plain_final" | "final_card_only";
|
|
@@ -49,7 +49,7 @@ export interface DingTalkHandler {
|
|
|
49
49
|
handleContextCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
|
|
50
50
|
handleBusyMessage(event: DingTalkEvent, bot: DingTalkBot, mode: BusyMessageMode, queueText: string): Promise<BusyMessageResult>;
|
|
51
51
|
}
|
|
52
|
-
export declare class DingTalkBot {
|
|
52
|
+
export declare class DingTalkBot implements MediaSender {
|
|
53
53
|
private handler;
|
|
54
54
|
private config;
|
|
55
55
|
private accessToken;
|
|
@@ -129,6 +129,26 @@ export declare class DingTalkBot {
|
|
|
129
129
|
* Send a normal message natively mapping DM and Group to correct endpoints (fallback when no card).
|
|
130
130
|
*/
|
|
131
131
|
sendPlain(channelId: string, text: string): Promise<boolean>;
|
|
132
|
+
/**
|
|
133
|
+
* Deliver a local file to a channel as a native attachment. Uploads the bytes
|
|
134
|
+
* to get a `media_id`, then sends a `sampleImageMsg` (inline image) or
|
|
135
|
+
* `sampleFile` (downloadable file) robot message. `channelId` is supplied by
|
|
136
|
+
* the runtime (the tool is bound to its channel at build time), never by the
|
|
137
|
+
* model, so an agent cannot target a channel other than its own.
|
|
138
|
+
*/
|
|
139
|
+
sendMedia(channelId: string, media: OutboundMedia): Promise<MediaSendResult>;
|
|
140
|
+
/**
|
|
141
|
+
* Upload raw bytes to DingTalk and return the reusable `media_id`, or null on
|
|
142
|
+
* failure. The upload endpoint lives on the legacy oapi host and answers 200
|
|
143
|
+
* with a non-zero `errcode` on failure, so the body is inspected explicitly.
|
|
144
|
+
*/
|
|
145
|
+
private uploadMedia;
|
|
146
|
+
/**
|
|
147
|
+
* POST a robot message with an arbitrary msgKey/msgParam, routing DM vs group
|
|
148
|
+
* to the correct endpoint. Shared by the media path; `sendPlain` predates this
|
|
149
|
+
* and keeps its own inlined copy to avoid a regression-prone refactor.
|
|
150
|
+
*/
|
|
151
|
+
private sendRobotMessage;
|
|
132
152
|
private createCard;
|
|
133
153
|
private createCardUncached;
|
|
134
154
|
private streamCard;
|
package/dist/runtime/dingtalk.js
CHANGED
|
@@ -61,10 +61,31 @@ export function normalizeResponseMode(value) {
|
|
|
61
61
|
}
|
|
62
62
|
throw new Error('Invalid `responseMode`: expected "full_progress_then_plain_final", "rolling_progress_then_plain_final", or "final_card_only".');
|
|
63
63
|
}
|
|
64
|
+
/** Lowercased extension without the dot ("Report.PDF" → "pdf"); "" when none. */
|
|
65
|
+
function extractFileExtension(fileName) {
|
|
66
|
+
const dot = fileName.lastIndexOf(".");
|
|
67
|
+
if (dot < 0 || dot === fileName.length - 1)
|
|
68
|
+
return "";
|
|
69
|
+
return fileName.slice(dot + 1).toLowerCase();
|
|
70
|
+
}
|
|
64
71
|
// ============================================================================
|
|
65
72
|
// Constants
|
|
66
73
|
// ============================================================================
|
|
67
74
|
const DINGTALK_API = "https://api.dingtalk.com";
|
|
75
|
+
// Media upload lives on the legacy oapi host, not the v1.0 api host. It returns a
|
|
76
|
+
// reusable `media_id` that the v1.0 robot send endpoints reference (photoURL /
|
|
77
|
+
// mediaId). The `access_token` query param is the same app access token minted by
|
|
78
|
+
// `/v1.0/oauth2/accessToken` — DingTalk unified the internal-app token across both
|
|
79
|
+
// hosts — so `getAccessToken()` is reused rather than fetching a second token.
|
|
80
|
+
const DINGTALK_OAPI = "https://oapi.dingtalk.com";
|
|
81
|
+
// DingTalk caps robot image messages at 1MB and file messages at 20MB. We reject
|
|
82
|
+
// oversized files before spending an upload round-trip on a request the API rejects.
|
|
83
|
+
const MAX_IMAGE_BYTES = 1024 * 1024;
|
|
84
|
+
const MAX_FILE_BYTES = 20 * 1024 * 1024;
|
|
85
|
+
// Uploads can move up to 20MB; the 15s default HTTP timeout is too tight for that.
|
|
86
|
+
const MEDIA_UPLOAD_TIMEOUT_MS = 60_000;
|
|
87
|
+
// File extensions the `sampleFile` message type accepts (per DingTalk docs).
|
|
88
|
+
const SUPPORTED_FILE_TYPES = new Set(["xlsx", "pdf", "zip", "rar", "doc", "docx", "ppt", "pptx", "csv", "txt"]);
|
|
68
89
|
// Bound every outbound DingTalk HTTP call. Without this, axios waits forever on a
|
|
69
90
|
// hung connection, and a stalled card-streaming request would wedge the delivery
|
|
70
91
|
// sync loop (never resolving flush()), leaving the whole channel permanently busy.
|
|
@@ -686,6 +707,126 @@ export class DingTalkBot {
|
|
|
686
707
|
}
|
|
687
708
|
}
|
|
688
709
|
// ==========================================================================
|
|
710
|
+
// Media (image / file) delivery — MediaSender contract
|
|
711
|
+
// ==========================================================================
|
|
712
|
+
/**
|
|
713
|
+
* Deliver a local file to a channel as a native attachment. Uploads the bytes
|
|
714
|
+
* to get a `media_id`, then sends a `sampleImageMsg` (inline image) or
|
|
715
|
+
* `sampleFile` (downloadable file) robot message. `channelId` is supplied by
|
|
716
|
+
* the runtime (the tool is bound to its channel at build time), never by the
|
|
717
|
+
* model, so an agent cannot target a channel other than its own.
|
|
718
|
+
*/
|
|
719
|
+
async sendMedia(channelId, media) {
|
|
720
|
+
const isImage = media.kind === "image";
|
|
721
|
+
const limit = isImage ? MAX_IMAGE_BYTES : MAX_FILE_BYTES;
|
|
722
|
+
if (media.data.length > limit) {
|
|
723
|
+
return {
|
|
724
|
+
ok: false,
|
|
725
|
+
error: `File is ${(media.data.length / 1024 / 1024).toFixed(1)}MB, exceeds the ${limit / 1024 / 1024}MB DingTalk limit for ${media.kind} messages.`,
|
|
726
|
+
};
|
|
727
|
+
}
|
|
728
|
+
const fileType = extractFileExtension(media.fileName);
|
|
729
|
+
if (!isImage && !SUPPORTED_FILE_TYPES.has(fileType)) {
|
|
730
|
+
return {
|
|
731
|
+
ok: false,
|
|
732
|
+
error: `DingTalk file messages do not support the "${fileType || "(none)"}" type. Supported: ${[...SUPPORTED_FILE_TYPES].join(", ")}.`,
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
const meta = this.getConversationMeta(channelId);
|
|
736
|
+
if (!meta) {
|
|
737
|
+
return { ok: false, error: "No conversation is known for this channel yet; cannot deliver a file." };
|
|
738
|
+
}
|
|
739
|
+
const mediaId = await this.uploadMedia(isImage ? "image" : "file", media.data, media.fileName);
|
|
740
|
+
if (!mediaId) {
|
|
741
|
+
return { ok: false, error: "Failed to upload the file to DingTalk (see server logs)." };
|
|
742
|
+
}
|
|
743
|
+
const { msgKey, msgParam } = isImage
|
|
744
|
+
? { msgKey: "sampleImageMsg", msgParam: JSON.stringify({ photoURL: mediaId }) }
|
|
745
|
+
: {
|
|
746
|
+
msgKey: "sampleFile",
|
|
747
|
+
msgParam: JSON.stringify({ mediaId, fileName: media.fileName, fileType }),
|
|
748
|
+
};
|
|
749
|
+
const sent = await this.sendRobotMessage(meta, msgKey, msgParam);
|
|
750
|
+
return sent ? { ok: true } : { ok: false, error: "DingTalk rejected the file message (see server logs)." };
|
|
751
|
+
}
|
|
752
|
+
/**
|
|
753
|
+
* Upload raw bytes to DingTalk and return the reusable `media_id`, or null on
|
|
754
|
+
* failure. The upload endpoint lives on the legacy oapi host and answers 200
|
|
755
|
+
* with a non-zero `errcode` on failure, so the body is inspected explicitly.
|
|
756
|
+
*/
|
|
757
|
+
async uploadMedia(type, data, fileName) {
|
|
758
|
+
const token = await this.getAccessToken();
|
|
759
|
+
if (!token)
|
|
760
|
+
return null;
|
|
761
|
+
const form = new FormData();
|
|
762
|
+
form.append("media", new Blob([new Uint8Array(data)]), fileName);
|
|
763
|
+
try {
|
|
764
|
+
const resp = await http.post(`${DINGTALK_OAPI}/media/upload?access_token=${encodeURIComponent(token)}&type=${type}`, form,
|
|
765
|
+
// Override the 15s default: a multi-MB upload over a slow link can take
|
|
766
|
+
// longer, and unlike card streaming this call is not on the delivery loop.
|
|
767
|
+
{ timeout: MEDIA_UPLOAD_TIMEOUT_MS });
|
|
768
|
+
const body = isRecord(resp.data) ? resp.data : {};
|
|
769
|
+
if (body.errcode && body.errcode !== 0) {
|
|
770
|
+
log.logWarning(`DingTalk media upload failed (errcode=${body.errcode})`, String(body.errmsg ?? ""));
|
|
771
|
+
return null;
|
|
772
|
+
}
|
|
773
|
+
const mediaId = typeof body.media_id === "string" ? body.media_id : null;
|
|
774
|
+
if (!mediaId) {
|
|
775
|
+
log.logWarning("DingTalk media upload returned no media_id", JSON.stringify(body));
|
|
776
|
+
}
|
|
777
|
+
return mediaId;
|
|
778
|
+
}
|
|
779
|
+
catch (err) {
|
|
780
|
+
if (axios.isAxiosError(err) && err.response) {
|
|
781
|
+
log.logWarning(`DingTalk media upload error (${err.response.status})`, JSON.stringify(err.response.data));
|
|
782
|
+
}
|
|
783
|
+
else {
|
|
784
|
+
log.logWarning("DingTalk media upload error", errorMessage(err));
|
|
785
|
+
}
|
|
786
|
+
return null;
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
/**
|
|
790
|
+
* POST a robot message with an arbitrary msgKey/msgParam, routing DM vs group
|
|
791
|
+
* to the correct endpoint. Shared by the media path; `sendPlain` predates this
|
|
792
|
+
* and keeps its own inlined copy to avoid a regression-prone refactor.
|
|
793
|
+
*/
|
|
794
|
+
async sendRobotMessage(meta, msgKey, msgParam) {
|
|
795
|
+
const token = await this.getAccessToken();
|
|
796
|
+
if (!token)
|
|
797
|
+
return false;
|
|
798
|
+
const robotCode = this.config.robotCode || this.config.clientId;
|
|
799
|
+
const isGroup = meta.conversationType === "2";
|
|
800
|
+
const url = isGroup
|
|
801
|
+
? `${DINGTALK_API}/v1.0/robot/groupMessages/send`
|
|
802
|
+
: `${DINGTALK_API}/v1.0/robot/oToMessages/batchSend`;
|
|
803
|
+
const body = { robotCode, msgKey, msgParam };
|
|
804
|
+
if (isGroup) {
|
|
805
|
+
body.openConversationId = meta.conversationId;
|
|
806
|
+
}
|
|
807
|
+
else {
|
|
808
|
+
body.userIds = [meta.senderId];
|
|
809
|
+
}
|
|
810
|
+
try {
|
|
811
|
+
await http.post(url, body, {
|
|
812
|
+
headers: {
|
|
813
|
+
"x-acs-dingtalk-access-token": token,
|
|
814
|
+
"Content-Type": "application/json",
|
|
815
|
+
},
|
|
816
|
+
});
|
|
817
|
+
return true;
|
|
818
|
+
}
|
|
819
|
+
catch (err) {
|
|
820
|
+
if (axios.isAxiosError(err) && err.response) {
|
|
821
|
+
log.logWarning(`DingTalk ${msgKey} send failed (${err.response.status})`, JSON.stringify(err.response.data));
|
|
822
|
+
}
|
|
823
|
+
else {
|
|
824
|
+
log.logWarning(`DingTalk ${msgKey} send error`, errorMessage(err));
|
|
825
|
+
}
|
|
826
|
+
return false;
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
// ==========================================================================
|
|
689
830
|
// Private - AI Card implementation
|
|
690
831
|
// ==========================================================================
|
|
691
832
|
async createCard(channelId) {
|
|
@@ -16,6 +16,16 @@ export declare class DurableDispatchService {
|
|
|
16
16
|
private readonly queue;
|
|
17
17
|
private readonly leaseMs;
|
|
18
18
|
private timer;
|
|
19
|
+
/**
|
|
20
|
+
* Dispatch ids whose turn this process is still running (spec 031, D2).
|
|
21
|
+
*
|
|
22
|
+
* The lease expresses "the holder is alive", not "a turn takes at most N minutes". A fixed
|
|
23
|
+
* lease is a guess about turn duration, and any turn that outran it redelivered its own wake.
|
|
24
|
+
* Membership here is renewed on every drain instead, so a long turn is safe; the set is empty
|
|
25
|
+
* after a restart, so a turn that died with the process is correctly redelivered once its
|
|
26
|
+
* lease lapses.
|
|
27
|
+
*/
|
|
28
|
+
private readonly running;
|
|
19
29
|
constructor(options: DurableDispatchOptions);
|
|
20
30
|
start(): void;
|
|
21
31
|
stop(): void;
|
|
@@ -9,6 +9,25 @@ const DEFAULT_INTERVAL_MS = 30_000;
|
|
|
9
9
|
function recordPath(stateDir, id) {
|
|
10
10
|
return join(stateDir, `${id}.json`);
|
|
11
11
|
}
|
|
12
|
+
/**
|
|
13
|
+
* Prefix a redelivered wake with what the runtime already knows (spec 031, D3).
|
|
14
|
+
*
|
|
15
|
+
* At-least-once delivery means a wake can arrive after a previous attempt already ran part of
|
|
16
|
+
* it. The runtime knows this; the model did not. Surfacing the delivery count is the whole
|
|
17
|
+
* mechanism — no new protocol, no reply marker, just enough for the model to check for its own
|
|
18
|
+
* prior side effects before repeating them. The stored record keeps the original text, so the
|
|
19
|
+
* dispatch id is unaffected.
|
|
20
|
+
*/
|
|
21
|
+
function withRedeliveryNotice(event, deliveries) {
|
|
22
|
+
if (deliveries <= 1)
|
|
23
|
+
return event;
|
|
24
|
+
return {
|
|
25
|
+
...event,
|
|
26
|
+
text: `[REDELIVERY:${deliveries}] This wake is delivery #${deliveries}; a previous delivery may have partially run. ` +
|
|
27
|
+
"Before acting, check whether its side effects (files, messages, external calls) already exist, and do not repeat them.\n" +
|
|
28
|
+
event.text,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
12
31
|
function dispatchId(event) {
|
|
13
32
|
return createHash("sha256")
|
|
14
33
|
.update(JSON.stringify([event.channelId, event.user, event.ts, event.text, event.conversationId]))
|
|
@@ -45,6 +64,16 @@ export class DurableDispatchService {
|
|
|
45
64
|
this.options = options;
|
|
46
65
|
this.queue = createSerialQueue();
|
|
47
66
|
this.timer = null;
|
|
67
|
+
/**
|
|
68
|
+
* Dispatch ids whose turn this process is still running (spec 031, D2).
|
|
69
|
+
*
|
|
70
|
+
* The lease expresses "the holder is alive", not "a turn takes at most N minutes". A fixed
|
|
71
|
+
* lease is a guess about turn duration, and any turn that outran it redelivered its own wake.
|
|
72
|
+
* Membership here is renewed on every drain instead, so a long turn is safe; the set is empty
|
|
73
|
+
* after a restart, so a turn that died with the process is correctly redelivered once its
|
|
74
|
+
* lease lapses.
|
|
75
|
+
*/
|
|
76
|
+
this.running = new Set();
|
|
48
77
|
this.leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS;
|
|
49
78
|
}
|
|
50
79
|
start() {
|
|
@@ -100,6 +129,9 @@ export class DurableDispatchService {
|
|
|
100
129
|
return;
|
|
101
130
|
if (record.status !== "queued" && record.status !== "running")
|
|
102
131
|
return;
|
|
132
|
+
// Drop the liveness claim too, or the renew branch above would keep this record
|
|
133
|
+
// alive forever and the cancelled turn would never be redelivered.
|
|
134
|
+
this.running.delete(id);
|
|
103
135
|
record.leaseExpiresAt = undefined;
|
|
104
136
|
await this.write(record);
|
|
105
137
|
canceled++;
|
|
@@ -110,6 +142,7 @@ export class DurableDispatchService {
|
|
|
110
142
|
async markStarted(id) {
|
|
111
143
|
if (!id)
|
|
112
144
|
return;
|
|
145
|
+
this.running.add(id);
|
|
113
146
|
await this.queue.run(id, async () => {
|
|
114
147
|
const record = await this.read(id);
|
|
115
148
|
if (!record)
|
|
@@ -122,6 +155,7 @@ export class DurableDispatchService {
|
|
|
122
155
|
async markCompleted(id) {
|
|
123
156
|
if (!id)
|
|
124
157
|
return;
|
|
158
|
+
this.running.delete(id);
|
|
125
159
|
await this.queue.run(id, async () => {
|
|
126
160
|
await unlink(recordPath(this.options.stateDir, id)).catch(() => undefined);
|
|
127
161
|
});
|
|
@@ -140,6 +174,13 @@ export class DurableDispatchService {
|
|
|
140
174
|
const record = await this.read(id);
|
|
141
175
|
if (!record)
|
|
142
176
|
return;
|
|
177
|
+
// The turn is still running in this process: renew its lease rather than treating a
|
|
178
|
+
// long turn as a lost one and redelivering the wake underneath it (D2).
|
|
179
|
+
if (record.status === "running" && this.running.has(id)) {
|
|
180
|
+
record.leaseExpiresAt = new Date(now + this.leaseMs).toISOString();
|
|
181
|
+
await this.write(record);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
143
184
|
const leaseMs = record.leaseExpiresAt ? new Date(record.leaseExpiresAt).getTime() : undefined;
|
|
144
185
|
if ((record.status === "queued" || record.status === "running") && leaseMs && leaseMs > now)
|
|
145
186
|
return;
|
|
@@ -147,7 +188,7 @@ export class DurableDispatchService {
|
|
|
147
188
|
record.deliveries++;
|
|
148
189
|
record.leaseExpiresAt = new Date(now + this.leaseMs).toISOString();
|
|
149
190
|
await this.write(record);
|
|
150
|
-
const accepted = this.options.bot.enqueueEvent({ ...record.event, dispatchId: record.id });
|
|
191
|
+
const accepted = this.options.bot.enqueueEvent(withRedeliveryNotice({ ...record.event, dispatchId: record.id }, record.deliveries));
|
|
151
192
|
if (accepted)
|
|
152
193
|
return;
|
|
153
194
|
record.status = "pending";
|