@oyasmi/pipiclaw 0.8.10-beta.5 → 0.8.10
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 +26 -23
- package/dist/memory/scheduler.js +5 -14
- package/dist/playbooks/runtime-orientation.md +1 -0
- package/dist/playbooks/task-closeout.md +2 -2
- package/dist/playbooks/task-driving.md +3 -3
- package/dist/runtime/bootstrap.js +14 -2
- package/dist/runtime/channel-index.d.ts +94 -0
- package/dist/runtime/channel-index.js +300 -0
- package/dist/runtime/channel-paths.d.ts +1 -0
- package/dist/runtime/channel-paths.js +20 -0
- package/dist/runtime/delivery.js +3 -1
- package/dist/runtime/dingtalk.d.ts +18 -0
- package/dist/runtime/dingtalk.js +14 -0
- package/dist/runtime/task-commands.d.ts +1 -1
- package/dist/runtime/task-commands.js +1 -1
- package/dist/runtime/task-driver.d.ts +1 -1
- package/dist/runtime/task-driver.js +7 -16
- package/dist/shared/local-time.js +34 -3
- package/dist/tasks/store.d.ts +9 -0
- package/dist/tasks/store.js +2 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Pipiclaw
|
|
2
2
|
|
|
3
|
-
Pipiclaw
|
|
3
|
+
Pipiclaw 是一个钉钉优先、可长期运行的 AI coding assistant runtime,个人和团队都可以使用。它以 [`pi-coding-agent`](https://www.npmjs.com/package/@earendil-works/pi-coding-agent) 为核心,把一个编码代理变成可以长期使用的工作助手:接入钉钉、保留跨会话记忆、按计划自主推进任务,并实时告诉你它正在做什么。
|
|
4
4
|
|
|
5
5
|
如果你希望 AI 助手不只是聊天,而是能在钉钉里持续工作、记住上下文、到点自己干活,那么 Pipiclaw 就是为此设计的。
|
|
6
6
|
|
|
@@ -14,13 +14,13 @@ npm package: [`@oyasmi/pipiclaw`](https://www.npmjs.com/package/@oyasmi/pipiclaw
|
|
|
14
14
|
|
|
15
15
|
**记得住事。** 每个会话通道(channel)有自己的分层记忆:`SESSION.md`(当前工作态)、`MEMORY.md`(稳定事实与偏好)、`HISTORY.md`(更早摘要),工作区层还有 `SOUL.md`(身份语气)与 `AGENTS.md`(工作规则)。运行时按当前请求做相关召回(relevant recall),后台维护调度器在本地闸门通过后才做 LLM 整理,不烧无谓的 token。冷存储历史可用 `session_search` 按需检索,`memory_manage` 支持按需保存、检索、忘记。
|
|
16
16
|
|
|
17
|
-
**自己推进长程工作。**
|
|
17
|
+
**自己推进长程工作。** 定时事件支持单次、周期两类,`preAction` 可用脚本做零 token 的触发前门控;当前回合能做的事直接做,不再创建 immediate 事件。语义更高一层的是任务台账(task ledger):任务以 Markdown 文件持久存在,内建 task driver 到点自动恢复、有进展有界续跑、停滞自动退避;配套受预算约束的恢复、独立验收、外部副作用授权,以及 `/tasks` 系列零 LLM 成本的控制面命令。
|
|
18
18
|
|
|
19
|
-
**会用工具、能委派。** 内建 `bash`(支持 `async` 后台作业)、`read`(含目录树与 PDF)、`write` / `edit`、结构化 `grep`、`web_search` / `web_fetch`(结果缓存与分页续读),以及 `send_media`——生成好的报表、截图、导出文件可以作为原生附件直接发回钉钉,而不是丢给你一个打不开的主机路径。工作区配置的子代理可以把 reviewer、researcher 这类角色沉淀成可复用能力,支持独立验收(verify);workspace skills 沉淀你自己的流程知识。完整清单见 [docs/tools.md](
|
|
19
|
+
**会用工具、能委派。** 内建 `bash`(支持 `async` 后台作业)、`read`(含目录树与 PDF)、`write` / `edit`、结构化 `grep`、`web_search` / `web_fetch`(结果缓存与分页续读),以及 `send_media`——生成好的报表、截图、导出文件可以作为原生附件直接发回钉钉,而不是丢给你一个打不开的主机路径。工作区配置的子代理可以把 reviewer、researcher 这类角色沉淀成可复用能力,支持独立验收(verify);workspace skills 沉淀你自己的流程知识。完整清单见 [docs/tools.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/tools.md)。
|
|
20
20
|
|
|
21
|
-
**有安全护栏。** 所有文件、命令、网络工具都经过安全守卫:`bash` 命令拦截、统一路径检查、常见凭据与敏感位置默认拒绝、阻断写入审计日志;可通过 `security.json` 做实例级策略调整。详见 [docs/security.md](
|
|
21
|
+
**有安全护栏。** 所有文件、命令、网络工具都经过安全守卫:`bash` 命令拦截、统一路径检查、常见凭据与敏感位置默认拒绝、阻断写入审计日志;可通过 `security.json` 做实例级策略调整。详见 [docs/security.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/security.md)。
|
|
22
22
|
|
|
23
|
-
**知识不随升级漂移。** Runtime 机制知识以 playbooks 随 npm 包发布、按需加载,系统提示只保留小型索引;`AGENTS.md` 与 workspace skills 完全归你和团队所有,升级不会覆盖,也不需要抄录产品文档。详见 [docs/runtime-playbooks.md](
|
|
23
|
+
**知识不随升级漂移。** Runtime 机制知识以 playbooks 随 npm 包发布、按需加载,系统提示只保留小型索引;`AGENTS.md` 与 workspace skills 完全归你和团队所有,升级不会覆盖,也不需要抄录产品文档。详见 [docs/runtime-playbooks.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/runtime-playbooks.md)。
|
|
24
24
|
|
|
25
25
|
## 快速开始(Quickstart)
|
|
26
26
|
|
|
@@ -92,7 +92,7 @@ pipiclaw
|
|
|
92
92
|
- `robotCode` 留空时回退到 `clientId`。
|
|
93
93
|
- `cardTemplateId` 建议配置(正常使用推荐启用 AI Card);示例先留空是为了让第一轮接入更稳,排查链路时也建议临时留空。
|
|
94
94
|
- `allowFrom` 为 `[]` 或省略时允许所有人;灰度期可填测试人员的 staff ID。
|
|
95
|
-
- 更多字段(`busyMessageDefault`、`responseMode`、`cardAutoLayout`)见[
|
|
95
|
+
- 更多字段(`busyMessageDefault`、`responseMode`、`cardAutoLayout`)见[配置速查](https://github.com/oyasmi/pipiclaw/blob/main/docs/configuration.md)和[字段参考](https://github.com/oyasmi/pipiclaw/blob/main/docs/configuration-reference.md)。
|
|
96
96
|
|
|
97
97
|
### 6. 配置模型(Configure Models)
|
|
98
98
|
|
|
@@ -131,7 +131,7 @@ export ANTHROPIC_API_KEY=sk-ant-...
|
|
|
131
131
|
|
|
132
132
|
- `apiKey` 可以写真实 key、环境变量名,或 `!command`;不想把凭据写进 `models.json`,可在 `auth.json` 写同名 provider 的凭据。
|
|
133
133
|
- 很多 OpenAI-compatible 服务不支持 `developer` role / `reasoning_effort`,遇到兼容问题先保留上面的 `compat`。
|
|
134
|
-
- 完整字段与更多场景(Ollama、企业代理等)见[
|
|
134
|
+
- 完整字段与更多场景(Ollama、企业代理等)见[配置速查](https://github.com/oyasmi/pipiclaw/blob/main/docs/configuration.md)和[字段参考](https://github.com/oyasmi/pipiclaw/blob/main/docs/configuration-reference.md)。
|
|
135
135
|
|
|
136
136
|
### 7. 可选:设置默认模型(Optional: Set a Default Model)
|
|
137
137
|
|
|
@@ -163,7 +163,7 @@ pipiclaw
|
|
|
163
163
|
2. 填入搜索 provider 的 `apiKey`(默认示例为 Brave)
|
|
164
164
|
3. 如需代理,设置 `tools.web.proxy`(未设置时回退到标准的 `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` / `NO_PROXY`)
|
|
165
165
|
|
|
166
|
-
搜索后端支持 `duckduckgo`、`brave`、`tavily`、`jina`、`searxng`,完整字段见[
|
|
166
|
+
搜索后端支持 `duckduckgo`、`brave`、`tavily`、`jina`、`searxng`,完整字段见[配置速查](https://github.com/oyasmi/pipiclaw/blob/main/docs/configuration.md)和[字段参考](https://github.com/oyasmi/pipiclaw/blob/main/docs/configuration-reference.md)。
|
|
167
167
|
|
|
168
168
|
### 10. 在钉钉中验证(Verify in DingTalk)
|
|
169
169
|
|
|
@@ -175,7 +175,7 @@ pipiclaw
|
|
|
175
175
|
|
|
176
176
|
如果一切正常,配置了 AI Card 时你会看到过程更新,否则机器人直接发普通消息回复;Pipiclaw 会在本地创建对应的会话通道目录,后续会话复用该通道的工作区与记忆。
|
|
177
177
|
|
|
178
|
-
**第一次没跑通?** 最常见的三类原因:`channel.json` 残留 `your-*` 占位值(进程启动即退出);模型凭据或 `models.json` 配置不可用(能收消息但首次调用失败);`allowFrom` 挡住了你的账号或 Stream Mode 未开启(收到消息但不回复)。系统化排查见[部署与运维指南](
|
|
178
|
+
**第一次没跑通?** 最常见的三类原因:`channel.json` 残留 `your-*` 占位值(进程启动即退出);模型凭据或 `models.json` 配置不可用(能收消息但首次调用失败);`allowFrom` 挡住了你的账号或 Stream Mode 未开启(收到消息但不回复)。系统化排查见[部署与运维指南](https://github.com/oyasmi/pipiclaw/blob/main/docs/deployment-and-operations.md);设置 `PIPICLAW_DEBUG=1` 可在会话通道目录写出 `last_prompt.json` 检查精确提示词。
|
|
179
179
|
|
|
180
180
|
### 让 AI Agent 帮你完成安装(For AI Agent)
|
|
181
181
|
|
|
@@ -215,41 +215,44 @@ pipiclaw
|
|
|
215
215
|
| `/steer <message>` | 当前任务继续执行时追加引导信息 |
|
|
216
216
|
| `/followup <message>` | 排队新请求,等当前任务结束后执行 |
|
|
217
217
|
| `/events list\|show\|delete\|history` | 查看与管理 `workspace/events/` 中的定时事件 |
|
|
218
|
-
| `/tasks [show\|archive\|approve\|pause\|resume\|run\|stats\|doctor]` | 查看与治理任务台账,`approve`
|
|
218
|
+
| `/tasks [show\|archive\|approve\|pause\|resume\|run\|set\|stats\|doctor]` | 查看与治理任务台账,`approve` 是外部副作用的唯一授权入口,`set` 可零 LLM 成本直改 wake/next/priority/attempts/deadline |
|
|
219
219
|
| `/status` | 运行时状态:执行状态、当前模型、上下文用量、运行时长、版本 |
|
|
220
220
|
| `/usage [7d\|month]` | 本通道与全局的 LLM 成本,按类型和 Top 模型拆分 |
|
|
221
221
|
| `/context [detail]` | 当前发给模型的上下文构成:system prompt 各 section 体量与 fingerprint、工具 schema 开销、上一轮动态上下文 |
|
|
222
222
|
| `/new` | 开启新会话 |
|
|
223
223
|
| `/compact [instructions]` | 手动压缩当前会话上下文 |
|
|
224
|
+
| `/memory [status\|list\|show\|pending]` | 查看当前频道的活动记忆、metadata、墓碑和待处理建议 |
|
|
224
225
|
| `/session` | 当前会话状态、消息统计、token 使用量 |
|
|
225
226
|
| `/model [引用]` | 查看或切换模型 |
|
|
226
227
|
| `/thinking [level\|cycle]` | 查看、设置或轮换当前会话的 thinking level(默认 `medium`,按模型能力自动 clamp) |
|
|
227
228
|
|
|
228
229
|
说明:
|
|
229
230
|
|
|
230
|
-
- 前九条由传输层直接处理,**忙碌时也可用**(`/context` 是只读统计,零 LLM
|
|
231
|
+
- 前九条由传输层直接处理,**忙碌时也可用**(`/context` 是只读统计,零 LLM 成本);后六条会话命令仅空闲时可用(忙碌时会收到提示)。
|
|
231
232
|
- 忙碌时的普通消息默认等价于 `/steer`,可通过 `channel.json` 的 `busyMessageDefault` 改为排队(`followUp`)。
|
|
232
233
|
- 未知的斜杠命令会被直接拒绝并提示 `/help`,不会作为普通消息发给模型(避免 `/modle` 这类笔误变成一整轮 LLM 调用)。workspace skill 也可作为命令调用(`/skill:<名称>`)。
|
|
233
234
|
- `/model` 依次尝试精确 `provider/modelId`、精确 `modelId`、对完整引用的子串匹配,只有唯一命中时才切换,例如 `/model turbo`。
|
|
234
235
|
|
|
235
|
-
事件与任务的详细用法见 [docs/events-and-tasks.md](
|
|
236
|
+
事件与任务的详细用法见 [docs/events-and-tasks.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/events-and-tasks.md);子代理见 [docs/sub-agents.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/sub-agents.md)。
|
|
236
237
|
|
|
237
238
|
## 文档地图(Documentation)
|
|
238
239
|
|
|
239
|
-
完整索引见 **[docs/README.md](
|
|
240
|
+
完整索引见 **[docs/README.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/README.md)**(按使用者 / 管理员 / 开发者分组)。常用入口:
|
|
240
241
|
|
|
241
242
|
| 文档 | 内容 |
|
|
242
243
|
|------|------|
|
|
243
|
-
| [docs/tools.md](
|
|
244
|
-
| [docs/memory.md](
|
|
245
|
-
| [docs/configuration.md](
|
|
246
|
-
| [docs/
|
|
247
|
-
| [docs/
|
|
248
|
-
| [docs/
|
|
249
|
-
| [docs/
|
|
250
|
-
| [docs/
|
|
251
|
-
| [docs/
|
|
252
|
-
| [docs/
|
|
244
|
+
| [docs/tools.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/tools.md) | 工具总览:每个能力做什么、开关在哪、子代理是否可用 |
|
|
245
|
+
| [docs/memory.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/memory.md) | 记忆分层:它记得什么、怎么让它记住或忘掉 |
|
|
246
|
+
| [docs/configuration.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/configuration.md) | 配置速查:现在该改哪个文件 |
|
|
247
|
+
| [docs/configuration-reference.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/configuration-reference.md) | 字段参考:钉钉、模型、settings、tools、TUI、记忆与工作区文件 |
|
|
248
|
+
| [docs/runtime-mechanisms.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/runtime-mechanisms.md) | 机制说明:fallback、记忆维护、事件、后台作业、任务 driver |
|
|
249
|
+
| [docs/events-and-tasks.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/events-and-tasks.md) | 定时事件(含 `preAction` 门控、`event_manage`)、任务台账、内建 task driver、`/tasks` 控制面与 `task_manage` 工具 |
|
|
250
|
+
| [docs/sub-agents.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/sub-agents.md) | 工作区配置子代理:委派与独立验收 |
|
|
251
|
+
| [docs/security.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/security.md) | 默认安全策略、`security.json` 配置与已知边界 |
|
|
252
|
+
| [docs/deployment-and-operations.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/deployment-and-operations.md) | 长期运行、日志、可观测性、升级、备份与排障 |
|
|
253
|
+
| [docs/scaling-and-concurrency.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/scaling-and-concurrency.md) | 并发模型与容量边界 |
|
|
254
|
+
| [docs/architecture.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/architecture.md) | as-implemented 架构:运行时拓扑、消息生命周期、并发表、磁盘布局 |
|
|
255
|
+
| [docs/runtime-playbooks.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/runtime-playbooks.md) | Runtime playbooks 与知识分层模型 |
|
|
253
256
|
|
|
254
257
|
## 开发(Development)
|
|
255
258
|
|
package/dist/memory/scheduler.js
CHANGED
|
@@ -1,23 +1,14 @@
|
|
|
1
1
|
import { readdir } from "node:fs/promises";
|
|
2
2
|
import { basename } from "node:path";
|
|
3
3
|
import * as log from "../log.js";
|
|
4
|
+
// The channel index is a runtime-owned workspace artifact; the scheduler is one of its two
|
|
5
|
+
// read-only consumers (see `discoverWorkspaceChannelIds`).
|
|
6
|
+
import { discoverWorkspaceChannelIds } from "../runtime/channel-index.js";
|
|
7
|
+
import { isChannelId } from "../runtime/channel-paths.js";
|
|
4
8
|
import { errorMessage } from "../shared/text-utils.js";
|
|
5
9
|
import { runMemoryCheckpointJob, runSessionRefreshJob, runStructuralMaintenanceJob } from "./maintenance-jobs.js";
|
|
6
10
|
import { getMemoryMaintenanceStateDir } from "./maintenance-state.js";
|
|
7
11
|
const DEFAULT_TICK_INTERVAL_MS = 60_000;
|
|
8
|
-
const CHANNEL_ID_PATTERN = /^(dm|group)_[A-Za-z0-9._:-]+$/;
|
|
9
|
-
function isChannelId(value) {
|
|
10
|
-
return CHANNEL_ID_PATTERN.test(value);
|
|
11
|
-
}
|
|
12
|
-
async function listWorkspaceChannels(workspaceDir) {
|
|
13
|
-
try {
|
|
14
|
-
const entries = await readdir(workspaceDir, { withFileTypes: true });
|
|
15
|
-
return entries.filter((entry) => entry.isDirectory() && isChannelId(entry.name)).map((entry) => entry.name);
|
|
16
|
-
}
|
|
17
|
-
catch {
|
|
18
|
-
return [];
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
12
|
async function listStateChannels(appHomeDir) {
|
|
22
13
|
try {
|
|
23
14
|
const entries = await readdir(getMemoryMaintenanceStateDir(appHomeDir), { withFileTypes: true });
|
|
@@ -37,7 +28,7 @@ export async function discoverMemoryMaintenanceChannels(input) {
|
|
|
37
28
|
channels.add(channelId);
|
|
38
29
|
}
|
|
39
30
|
}
|
|
40
|
-
for (const channelId of await
|
|
31
|
+
for (const channelId of await discoverWorkspaceChannelIds(input.workspaceDir)) {
|
|
41
32
|
channels.add(channelId);
|
|
42
33
|
}
|
|
43
34
|
for (const channelId of await listStateChannels(input.appHomeDir)) {
|
|
@@ -25,6 +25,7 @@ Workspace 根目录:
|
|
|
25
25
|
- `AGENTS.md`:用户/团队工作原则,只读注入。
|
|
26
26
|
- `MEMORY.md`:管理员维护的共享背景,按需读取。
|
|
27
27
|
- `ENVIRONMENT.md`:机器环境事实和重要变更,按需读取、可维护。
|
|
28
|
+
- `CHANNELS.md`:runtime 维护的频道索引(频道 ID / 名称 / 最近消息 / 主题)。需要知道还有哪些频道、某个 `group_...` ID 对应哪个群时读它;「主题」一列可以补写,其余三列会被重写覆盖。
|
|
28
29
|
- `skills/`:workspace 级程序性知识;通过 `skill_manage` 管理。
|
|
29
30
|
- `sub-agents/`:工作区配置的子代理;只加载实际存在的 Markdown 文件。
|
|
30
31
|
- `events/`:全 workspace 的调度事件。
|
|
@@ -43,10 +43,10 @@ FAIL 后用 progress 记录失败证据、status 回 active,修复后重新 ca
|
|
|
43
43
|
|
|
44
44
|
## done / cancel
|
|
45
45
|
|
|
46
|
-
`task_manage done` 需要 summary 和可查证 evidence,可附 residualRisk
|
|
46
|
+
`task_manage done` 需要 summary 和可查证 evidence,可附 residualRisk。它检查未勾选 checkbox、外部授权、独立 PASS、body/artifact hash,再记录收尾、清理临时 task events;一次性任务归档,有 `schedule` frontmatter 的周期任务算出下一次 `wake` 并原地睡眠。
|
|
47
47
|
|
|
48
48
|
周期 occurrence 因去重、同一产物已由更早触发完成等原因无需执行时,用 `task_manage skip` + reason。skip 只关闭本次 occurrence,不要求虚勾 DoD、不写 completion evidence,也不会取消后续 schedule。
|
|
49
49
|
|
|
50
|
-
放弃用 `cancel` + reason,不伪装 done。cancel
|
|
50
|
+
放弃用 `cancel` + reason,不伪装 done。cancel 会归档任务并删除全部 task-owned events。
|
|
51
51
|
|
|
52
52
|
完成结论必须来自证据:具体命令、测试结果、review、外部确认或明确的未运行理由。“看起来可以”不是 evidence。
|
|
@@ -10,11 +10,11 @@ priority: 41
|
|
|
10
10
|
## 每次唤醒先恢复真相
|
|
11
11
|
|
|
12
12
|
1. 打开消息指定的 `tasks/<id>.md`,不要只依赖唤醒文本、旧对话或记忆。
|
|
13
|
-
2. 核对 status、最新 Current Cycle note、`nextAction`、`wake
|
|
13
|
+
2. 核对 status、最新 Current Cycle note、`nextAction`、`wake`、deadline / attempt budget、`sideEffects` 和 verification。
|
|
14
14
|
3. 检查上一步产物**是否已经存在**。派发语义是 at-least-once,宕机或租约重放可能让同一步再次到达。
|
|
15
15
|
4. 只推进一个清晰的下一阶段;不要在未知状态下重复外部动作。
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
deadline 或 attempt budget 耗尽会令任务被治理器暂停(`paused` + `pausedBy=governor`);连续 3 次唤醒都没有可见进展也会触发同样的暂停。
|
|
18
18
|
|
|
19
19
|
## 回合结束必须留下确定性状态
|
|
20
20
|
|
|
@@ -48,7 +48,7 @@ priority: 41
|
|
|
48
48
|
|
|
49
49
|
## 被治理器暂停(paused + pausedBy=governor)
|
|
50
50
|
|
|
51
|
-
治理器在 deadline
|
|
51
|
+
治理器在 deadline、attempt budget 耗尽,或**连续 3 次唤醒都没有可见进展**(fingerprint 未变,含 silent)时暂停任务(旧称 escalated)。先读 Current Cycle 和 stats,判断是空转、范围错误还是预算过小:
|
|
52
52
|
|
|
53
53
|
- 方向错:修 Manual/`nextAction`、重新拆解或 cancel。
|
|
54
54
|
- 预算确实不足:向用户说明后用 `task_manage set` 调整 budget/deadline,并把 status 设回 `active`。
|
|
@@ -23,6 +23,7 @@ import { finishTaskAttempt } from "../tasks/store.js";
|
|
|
23
23
|
import { getToolsConfigPath, loadToolsConfig, loadToolsConfigWithDiagnostics } from "../tools/config.js";
|
|
24
24
|
import { getUsageLedger } from "../usage/ledger.js";
|
|
25
25
|
import { parseUsageMode, renderUsageReport } from "../usage/render.js";
|
|
26
|
+
import { createChannelIndex } from "./channel-index.js";
|
|
26
27
|
import { ensureChannelDir, getChannelDir } from "./channel-paths.js";
|
|
27
28
|
import { createDingTalkContext } from "./delivery.js";
|
|
28
29
|
import { DingTalkBot, isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, } from "./dingtalk.js";
|
|
@@ -407,6 +408,9 @@ export function createRuntimeContext(options) {
|
|
|
407
408
|
const cliVersion = readCliVersion();
|
|
408
409
|
const channelRunners = new Map();
|
|
409
410
|
const activeTasks = new Set();
|
|
411
|
+
// `workspace/CHANNELS.md`: names every channel id so the workspace, the logs and the agent
|
|
412
|
+
// stop dealing in `group_cid...`. Writes are debounced internally (see channel-index.ts).
|
|
413
|
+
const channelIndex = createChannelIndex({ workspaceDir: options.paths.workspaceDir });
|
|
410
414
|
let durableDispatch;
|
|
411
415
|
let shuttingDown = false;
|
|
412
416
|
let shutdownPromise = null;
|
|
@@ -441,6 +445,11 @@ export function createRuntimeContext(options) {
|
|
|
441
445
|
isRunning(channelId) {
|
|
442
446
|
return channelRunners.get(channelId)?.isBusy() ?? false;
|
|
443
447
|
},
|
|
448
|
+
noteChannelActivity(observation) {
|
|
449
|
+
if (shuttingDown)
|
|
450
|
+
return;
|
|
451
|
+
channelIndex.note(observation);
|
|
452
|
+
},
|
|
444
453
|
async handleStop(channelId, _bot) {
|
|
445
454
|
const runner = channelRunners.get(channelId);
|
|
446
455
|
let pausedTaskId;
|
|
@@ -489,7 +498,7 @@ export function createRuntimeContext(options) {
|
|
|
489
498
|
workspaceDir: options.paths.workspaceDir,
|
|
490
499
|
channelId: event.channelId,
|
|
491
500
|
approver: event.userName && event.userName !== event.user ? `${event.userName} (${event.user})` : event.user,
|
|
492
|
-
dispatchTask: async (id) => {
|
|
501
|
+
dispatchTask: async (id, attemptGeneration) => {
|
|
493
502
|
const channelDir = getChannelDir(options.paths.workspaceDir, event.channelId);
|
|
494
503
|
const entry = (await readActiveTasks(join(channelDir, "tasks"))).find((candidate) => candidate.id === id);
|
|
495
504
|
if (!entry)
|
|
@@ -497,7 +506,7 @@ export function createRuntimeContext(options) {
|
|
|
497
506
|
// A human asking to run a task twice means twice, so this key is deliberately
|
|
498
507
|
// unique per invocation rather than sharing the driver's occurrence key (D1).
|
|
499
508
|
const now = Date.now();
|
|
500
|
-
const driverEvent = createTaskDriverEvent(event.channelId, entry, now);
|
|
509
|
+
const driverEvent = createTaskDriverEvent(event.channelId, entry, now, attemptGeneration);
|
|
501
510
|
return ((await durableDispatch?.dispatch({
|
|
502
511
|
...driverEvent,
|
|
503
512
|
dispatchId: `task:${event.channelId}:${entry.id}:manual:${new Date(now).toISOString()}`,
|
|
@@ -659,6 +668,7 @@ export function createRuntimeContext(options) {
|
|
|
659
668
|
failed: result.stopReason === "error" || result.stopReason === "aborted",
|
|
660
669
|
silent: result.silent,
|
|
661
670
|
finishedAt: new Date(),
|
|
671
|
+
generation: event.taskAttemptGeneration,
|
|
662
672
|
});
|
|
663
673
|
}
|
|
664
674
|
if (result.stopReason === "aborted" && runner.getTurnStatus().stopRequested) {
|
|
@@ -823,6 +833,8 @@ export function createRuntimeContext(options) {
|
|
|
823
833
|
}
|
|
824
834
|
const storageFlushes = [
|
|
825
835
|
store.close(),
|
|
836
|
+
// Cancels the debounce timer and lands the last activity times.
|
|
837
|
+
channelIndex.close(),
|
|
826
838
|
getUsageLedger().flush?.() ?? Promise.resolve(),
|
|
827
839
|
flushSecurityLogs(),
|
|
828
840
|
...(eventsWatcher.flush ? [eventsWatcher.flush()] : []),
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `workspace/CHANNELS.md` — the readable map of every channel this runtime knows.
|
|
3
|
+
*
|
|
4
|
+
* A channel's on-disk identity is its raw id (`group_cidYDhGqxhJOzS7VDv/eDInUw==`), which is
|
|
5
|
+
* unreadable in a directory listing, in `/events` output and in the logs. This index gives
|
|
6
|
+
* every id a name and a last-seen time in one place, so the operator browsing the workspace
|
|
7
|
+
* and the agent asking "what other channels are there?" both have something to read.
|
|
8
|
+
*
|
|
9
|
+
* ## Maintenance contract
|
|
10
|
+
*
|
|
11
|
+
* - **What is recorded**: only real inbound human messages — the DingTalk transport calls
|
|
12
|
+
* `noteChannelActivity` once per accepted message, before command/busy routing splits the
|
|
13
|
+
* path. Background wakes (scheduled events, the task driver, durable re-dispatch) are
|
|
14
|
+
* deliberately *not* recorded: they would keep every dormant channel looking fresh and
|
|
15
|
+
* destroy the one signal this file carries.
|
|
16
|
+
* - **When it is written**: immediately on a structural change — a channel seen for the first
|
|
17
|
+
* time, or a group that changed its name — because those are rare and are the whole point
|
|
18
|
+
* of the file. A change to the timestamp alone is debounced to at most one write per
|
|
19
|
+
* {@link DEFAULT_DEBOUNCE_MS} however busy the channel gets, plus a final flush from
|
|
20
|
+
* `close()` at shutdown.
|
|
21
|
+
* - **What survives a rewrite**: every flush re-reads the file first, so the hand-written
|
|
22
|
+
* `主题` column — and any row for a channel this process never saw — is carried over
|
|
23
|
+
* verbatim. The runtime owns three columns; the fourth belongs to whoever edits it.
|
|
24
|
+
*
|
|
25
|
+
* The index is the durable store for channel names: the transport learns a name only while a
|
|
26
|
+
* message is being handled, so nothing else outlives a restart. It fills in from the first
|
|
27
|
+
* message in each channel rather than being seeded from disk — a channel *directory* name is
|
|
28
|
+
* the escaped form of the id (`/` → `__`, see `channel-paths.ts`) and cannot be turned back
|
|
29
|
+
* into one, so scanning the workspace would populate rows keyed by ids that do not exist.
|
|
30
|
+
*/
|
|
31
|
+
export declare const CHANNELS_INDEX_FILENAME = "CHANNELS.md";
|
|
32
|
+
/**
|
|
33
|
+
* Timestamp-only debounce. Five minutes is far below the resolution anyone reads this file at,
|
|
34
|
+
* and it caps the file at 12 writes/hour no matter how many messages arrive.
|
|
35
|
+
*/
|
|
36
|
+
export declare const DEFAULT_DEBOUNCE_MS: number;
|
|
37
|
+
export interface ChannelObservation {
|
|
38
|
+
channelId: string;
|
|
39
|
+
/** Group title, or the peer's nickname for a DM. Absent when the transport had none. */
|
|
40
|
+
name?: string;
|
|
41
|
+
/** Epoch milliseconds of the message that triggered this observation. */
|
|
42
|
+
at: number;
|
|
43
|
+
}
|
|
44
|
+
export interface ChannelIndexEntry {
|
|
45
|
+
channelId: string;
|
|
46
|
+
name: string;
|
|
47
|
+
/** Local wall-clock time of the last human message, or `""` when never observed. */
|
|
48
|
+
lastMessageAt: string;
|
|
49
|
+
/** Hand-written; the runtime only ever copies it forward. */
|
|
50
|
+
topic: string;
|
|
51
|
+
}
|
|
52
|
+
export interface ChannelIndex {
|
|
53
|
+
/** Record one inbound human message. Cheap and synchronous; writing is decided internally. */
|
|
54
|
+
note(observation: ChannelObservation): void;
|
|
55
|
+
/** Write pending changes now. No-op when nothing changed. */
|
|
56
|
+
flush(): Promise<void>;
|
|
57
|
+
/** Cancel the debounce timer and write one last time. */
|
|
58
|
+
close(): Promise<void>;
|
|
59
|
+
}
|
|
60
|
+
export declare function renderChannelIndex(entries: ChannelIndexEntry[]): string;
|
|
61
|
+
/**
|
|
62
|
+
* Read back whatever a previous render — or a human editing the file — left behind.
|
|
63
|
+
*
|
|
64
|
+
* Rows are identified structurally (a pipe-delimited line that is neither the header nor the
|
|
65
|
+
* separator) rather than by matching the id against a pattern: DingTalk conversation ids are
|
|
66
|
+
* base64 and routinely contain `/` and `=`, so any shape check here would quietly discard real
|
|
67
|
+
* channels. Anything unparseable is skipped instead of throwing — a mangled index must never
|
|
68
|
+
* stop the runtime from recording the next message.
|
|
69
|
+
*/
|
|
70
|
+
export declare function parseChannelIndex(content: string): ChannelIndexEntry[];
|
|
71
|
+
/** Channel ids recorded in the index, i.e. every channel that has ever received a message. */
|
|
72
|
+
export declare function readChannelIndexIds(workspaceDir: string): Promise<string[]>;
|
|
73
|
+
/**
|
|
74
|
+
* Every channel this workspace knows about, for the background workers that must visit
|
|
75
|
+
* channels nobody has spoken to since the process started (memory maintenance, the task
|
|
76
|
+
* driver). Live channels come from the caller's runner map; this covers the rest.
|
|
77
|
+
*
|
|
78
|
+
* The index is the accurate source — it stores real ids. Scanning the workspace root is the
|
|
79
|
+
* fallback for a workspace that predates the index, and it is inherently lossy: a channel
|
|
80
|
+
* *directory* is the escaped form of the id (`/` → `__`), which cannot be turned back into the
|
|
81
|
+
* original. It is still kept alongside the index rather than only when the file is missing,
|
|
82
|
+
* because the index fills in one channel at a time: on the first run after an upgrade the file
|
|
83
|
+
* exists with a single row, and treating that as "the index has answers now" would drop every
|
|
84
|
+
* other pre-existing channel until each of them happened to be spoken in. Directories whose
|
|
85
|
+
* name is the escaped form of an already-indexed id are skipped, so a channel is never visited
|
|
86
|
+
* twice under two spellings.
|
|
87
|
+
*/
|
|
88
|
+
export declare function discoverWorkspaceChannelIds(workspaceDir: string): Promise<string[]>;
|
|
89
|
+
export interface CreateChannelIndexOptions {
|
|
90
|
+
workspaceDir: string;
|
|
91
|
+
/** Override the timestamp-only debounce; tests use a short one. */
|
|
92
|
+
debounceMs?: number;
|
|
93
|
+
}
|
|
94
|
+
export declare function createChannelIndex(options: CreateChannelIndexOptions): ChannelIndex;
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `workspace/CHANNELS.md` — the readable map of every channel this runtime knows.
|
|
3
|
+
*
|
|
4
|
+
* A channel's on-disk identity is its raw id (`group_cidYDhGqxhJOzS7VDv/eDInUw==`), which is
|
|
5
|
+
* unreadable in a directory listing, in `/events` output and in the logs. This index gives
|
|
6
|
+
* every id a name and a last-seen time in one place, so the operator browsing the workspace
|
|
7
|
+
* and the agent asking "what other channels are there?" both have something to read.
|
|
8
|
+
*
|
|
9
|
+
* ## Maintenance contract
|
|
10
|
+
*
|
|
11
|
+
* - **What is recorded**: only real inbound human messages — the DingTalk transport calls
|
|
12
|
+
* `noteChannelActivity` once per accepted message, before command/busy routing splits the
|
|
13
|
+
* path. Background wakes (scheduled events, the task driver, durable re-dispatch) are
|
|
14
|
+
* deliberately *not* recorded: they would keep every dormant channel looking fresh and
|
|
15
|
+
* destroy the one signal this file carries.
|
|
16
|
+
* - **When it is written**: immediately on a structural change — a channel seen for the first
|
|
17
|
+
* time, or a group that changed its name — because those are rare and are the whole point
|
|
18
|
+
* of the file. A change to the timestamp alone is debounced to at most one write per
|
|
19
|
+
* {@link DEFAULT_DEBOUNCE_MS} however busy the channel gets, plus a final flush from
|
|
20
|
+
* `close()` at shutdown.
|
|
21
|
+
* - **What survives a rewrite**: every flush re-reads the file first, so the hand-written
|
|
22
|
+
* `主题` column — and any row for a channel this process never saw — is carried over
|
|
23
|
+
* verbatim. The runtime owns three columns; the fourth belongs to whoever edits it.
|
|
24
|
+
*
|
|
25
|
+
* The index is the durable store for channel names: the transport learns a name only while a
|
|
26
|
+
* message is being handled, so nothing else outlives a restart. It fills in from the first
|
|
27
|
+
* message in each channel rather than being seeded from disk — a channel *directory* name is
|
|
28
|
+
* the escaped form of the id (`/` → `__`, see `channel-paths.ts`) and cannot be turned back
|
|
29
|
+
* into one, so scanning the workspace would populate rows keyed by ids that do not exist.
|
|
30
|
+
*/
|
|
31
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
32
|
+
import { join } from "node:path";
|
|
33
|
+
import * as log from "../log.js";
|
|
34
|
+
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
35
|
+
import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
|
|
36
|
+
import { createSerialQueue } from "../shared/serial-queue.js";
|
|
37
|
+
import { errorMessage } from "../shared/text-utils.js";
|
|
38
|
+
import { getChannelDirName, isChannelId } from "./channel-paths.js";
|
|
39
|
+
export const CHANNELS_INDEX_FILENAME = "CHANNELS.md";
|
|
40
|
+
/**
|
|
41
|
+
* Timestamp-only debounce. Five minutes is far below the resolution anyone reads this file at,
|
|
42
|
+
* and it caps the file at 12 writes/hour no matter how many messages arrive.
|
|
43
|
+
*/
|
|
44
|
+
export const DEFAULT_DEBOUNCE_MS = 5 * 60_000;
|
|
45
|
+
/** Names come from a chat platform; clip so one absurd group title cannot deform the table. */
|
|
46
|
+
const MAX_NAME_CHARS = 80;
|
|
47
|
+
// === Rendering and parsing ===
|
|
48
|
+
const HEADER_CELLS = ["频道 ID", "名称", "最近消息", "主题"];
|
|
49
|
+
const FILE_HEADER = `# Channels
|
|
50
|
+
|
|
51
|
+
<!--
|
|
52
|
+
运行时自动维护的频道索引。
|
|
53
|
+
|
|
54
|
+
- 「频道 ID」「名称」「最近消息」三列由运行时在收到消息时更新,手工改动会在下次重写时被覆盖。
|
|
55
|
+
- 「主题」一列留给你(或 agent)填写,重写索引时原样保留 — 用一句话写清这个频道是干什么的。
|
|
56
|
+
- 「最近消息」只统计真人消息,不含定时事件和任务驱动的后台唤醒,所以它能反映频道是否还活跃。
|
|
57
|
+
- 行按最近消息时间倒序排列。
|
|
58
|
+
-->
|
|
59
|
+
`;
|
|
60
|
+
/** Local time at second precision: exact round-trip through `parseLocalTime`, no millisecond noise. */
|
|
61
|
+
function renderTimestamp(atMs) {
|
|
62
|
+
return formatLocalTime(new Date(atMs)).replace(/\.\d{3}(?=[+-]\d{2}:\d{2}$)/, "");
|
|
63
|
+
}
|
|
64
|
+
function escapeCell(value) {
|
|
65
|
+
return value
|
|
66
|
+
.replace(/[\r\n]+/g, " ")
|
|
67
|
+
.replace(/\\/g, "\\\\")
|
|
68
|
+
.replace(/\|/g, "\\|")
|
|
69
|
+
.trim();
|
|
70
|
+
}
|
|
71
|
+
/** Split one markdown table row, honouring the `\|` escapes {@link escapeCell} writes. */
|
|
72
|
+
function splitRow(line) {
|
|
73
|
+
const cells = [];
|
|
74
|
+
let current = "";
|
|
75
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
76
|
+
const char = line[index];
|
|
77
|
+
if (char === "\\" && index + 1 < line.length) {
|
|
78
|
+
current += line[index + 1];
|
|
79
|
+
index += 1;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (char === "|") {
|
|
83
|
+
cells.push(current);
|
|
84
|
+
current = "";
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
current += char;
|
|
88
|
+
}
|
|
89
|
+
cells.push(current);
|
|
90
|
+
// A well-formed row is bounded by pipes, so the first and last cells are empty padding.
|
|
91
|
+
if (cells.length >= 2 && cells[0].trim() === "" && cells[cells.length - 1].trim() === "") {
|
|
92
|
+
return cells.slice(1, -1).map((cell) => cell.trim());
|
|
93
|
+
}
|
|
94
|
+
return cells.map((cell) => cell.trim());
|
|
95
|
+
}
|
|
96
|
+
function isSeparatorRow(cells) {
|
|
97
|
+
return cells.length > 0 && cells.every((cell) => /^:?-{2,}:?$/.test(cell));
|
|
98
|
+
}
|
|
99
|
+
export function renderChannelIndex(entries) {
|
|
100
|
+
const rows = entries.map((entry) => `| \`${escapeCell(entry.channelId)}\` | ${escapeCell(entry.name)} | ${escapeCell(entry.lastMessageAt)} | ${escapeCell(entry.topic)} |`);
|
|
101
|
+
return [
|
|
102
|
+
FILE_HEADER,
|
|
103
|
+
`| ${HEADER_CELLS.join(" | ")} |`,
|
|
104
|
+
`| ${HEADER_CELLS.map(() => "---").join(" | ")} |`,
|
|
105
|
+
...rows,
|
|
106
|
+
"",
|
|
107
|
+
].join("\n");
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Read back whatever a previous render — or a human editing the file — left behind.
|
|
111
|
+
*
|
|
112
|
+
* Rows are identified structurally (a pipe-delimited line that is neither the header nor the
|
|
113
|
+
* separator) rather than by matching the id against a pattern: DingTalk conversation ids are
|
|
114
|
+
* base64 and routinely contain `/` and `=`, so any shape check here would quietly discard real
|
|
115
|
+
* channels. Anything unparseable is skipped instead of throwing — a mangled index must never
|
|
116
|
+
* stop the runtime from recording the next message.
|
|
117
|
+
*/
|
|
118
|
+
export function parseChannelIndex(content) {
|
|
119
|
+
const entries = [];
|
|
120
|
+
const seen = new Set();
|
|
121
|
+
for (const line of content.split("\n")) {
|
|
122
|
+
const trimmed = line.trim();
|
|
123
|
+
if (!trimmed.startsWith("|"))
|
|
124
|
+
continue;
|
|
125
|
+
const cells = splitRow(trimmed);
|
|
126
|
+
if (isSeparatorRow(cells))
|
|
127
|
+
continue;
|
|
128
|
+
const channelId = cells[0]?.replace(/`/g, "").trim() ?? "";
|
|
129
|
+
if (!channelId || channelId === HEADER_CELLS[0] || seen.has(channelId))
|
|
130
|
+
continue;
|
|
131
|
+
seen.add(channelId);
|
|
132
|
+
entries.push({
|
|
133
|
+
channelId,
|
|
134
|
+
name: cells[1] ?? "",
|
|
135
|
+
lastMessageAt: cells[2] ?? "",
|
|
136
|
+
topic: cells[3] ?? "",
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
return entries;
|
|
140
|
+
}
|
|
141
|
+
// === Discovery ===
|
|
142
|
+
/** Channel ids recorded in the index, i.e. every channel that has ever received a message. */
|
|
143
|
+
export async function readChannelIndexIds(workspaceDir) {
|
|
144
|
+
try {
|
|
145
|
+
const content = await readFile(join(workspaceDir, CHANNELS_INDEX_FILENAME), "utf-8");
|
|
146
|
+
return parseChannelIndex(content)
|
|
147
|
+
.map((entry) => entry.channelId)
|
|
148
|
+
.filter(isChannelId);
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
return [];
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Every channel this workspace knows about, for the background workers that must visit
|
|
156
|
+
* channels nobody has spoken to since the process started (memory maintenance, the task
|
|
157
|
+
* driver). Live channels come from the caller's runner map; this covers the rest.
|
|
158
|
+
*
|
|
159
|
+
* The index is the accurate source — it stores real ids. Scanning the workspace root is the
|
|
160
|
+
* fallback for a workspace that predates the index, and it is inherently lossy: a channel
|
|
161
|
+
* *directory* is the escaped form of the id (`/` → `__`), which cannot be turned back into the
|
|
162
|
+
* original. It is still kept alongside the index rather than only when the file is missing,
|
|
163
|
+
* because the index fills in one channel at a time: on the first run after an upgrade the file
|
|
164
|
+
* exists with a single row, and treating that as "the index has answers now" would drop every
|
|
165
|
+
* other pre-existing channel until each of them happened to be spoken in. Directories whose
|
|
166
|
+
* name is the escaped form of an already-indexed id are skipped, so a channel is never visited
|
|
167
|
+
* twice under two spellings.
|
|
168
|
+
*/
|
|
169
|
+
export async function discoverWorkspaceChannelIds(workspaceDir) {
|
|
170
|
+
const channelIds = new Set(await readChannelIndexIds(workspaceDir));
|
|
171
|
+
const indexedDirNames = new Set([...channelIds].map(getChannelDirName));
|
|
172
|
+
try {
|
|
173
|
+
const dirents = await readdir(workspaceDir, { withFileTypes: true });
|
|
174
|
+
for (const entry of dirents) {
|
|
175
|
+
if (!entry.isDirectory() || indexedDirNames.has(entry.name) || !isChannelId(entry.name))
|
|
176
|
+
continue;
|
|
177
|
+
channelIds.add(entry.name);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
// A missing or unreadable workspace simply has no channels to report.
|
|
182
|
+
}
|
|
183
|
+
return [...channelIds].sort();
|
|
184
|
+
}
|
|
185
|
+
function entryTime(entry) {
|
|
186
|
+
return entry.lastMessageAt ? (parseLocalTime(entry.lastMessageAt) ?? 0) : 0;
|
|
187
|
+
}
|
|
188
|
+
function sortEntries(entries) {
|
|
189
|
+
return [...entries].sort((a, b) => {
|
|
190
|
+
const delta = entryTime(b) - entryTime(a);
|
|
191
|
+
return delta !== 0 ? delta : a.channelId.localeCompare(b.channelId);
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
function normalizeName(name) {
|
|
195
|
+
if (!name)
|
|
196
|
+
return "";
|
|
197
|
+
const collapsed = name.replace(/\s+/g, " ").trim();
|
|
198
|
+
return collapsed.length > MAX_NAME_CHARS ? `${collapsed.slice(0, MAX_NAME_CHARS - 1)}…` : collapsed;
|
|
199
|
+
}
|
|
200
|
+
export function createChannelIndex(options) {
|
|
201
|
+
const indexPath = join(options.workspaceDir, CHANNELS_INDEX_FILENAME);
|
|
202
|
+
const debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;
|
|
203
|
+
// Serialized so two flushes can never interleave their read-merge-write.
|
|
204
|
+
const queue = createSerialQueue();
|
|
205
|
+
const observed = new Map();
|
|
206
|
+
let dirty = false;
|
|
207
|
+
let closed = false;
|
|
208
|
+
let timer = null;
|
|
209
|
+
/** The most recently started write, so a caller can await work it did not start itself. */
|
|
210
|
+
let pending = Promise.resolve();
|
|
211
|
+
const cancelTimer = () => {
|
|
212
|
+
if (timer) {
|
|
213
|
+
clearTimeout(timer);
|
|
214
|
+
timer = null;
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
const scheduleFlush = () => {
|
|
218
|
+
if (timer || closed)
|
|
219
|
+
return;
|
|
220
|
+
timer = setTimeout(() => {
|
|
221
|
+
timer = null;
|
|
222
|
+
void flush();
|
|
223
|
+
}, debounceMs);
|
|
224
|
+
// Never keep the process alive just to update an index file.
|
|
225
|
+
timer.unref?.();
|
|
226
|
+
};
|
|
227
|
+
/** Merge the file on disk with this process's observations. Disk wins on `主题`, we win on the rest. */
|
|
228
|
+
const merge = async () => {
|
|
229
|
+
const byId = new Map();
|
|
230
|
+
try {
|
|
231
|
+
for (const entry of parseChannelIndex(await readFile(indexPath, "utf-8"))) {
|
|
232
|
+
byId.set(entry.channelId, entry);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
// No index yet, or it is unreadable: start from what this process knows.
|
|
237
|
+
}
|
|
238
|
+
for (const [channelId, channel] of observed) {
|
|
239
|
+
const existing = byId.get(channelId);
|
|
240
|
+
byId.set(channelId, {
|
|
241
|
+
channelId,
|
|
242
|
+
// An observation without a name (a DM from a nameless sender) must not erase a
|
|
243
|
+
// name the file already carries.
|
|
244
|
+
name: channel.name || existing?.name || "",
|
|
245
|
+
lastMessageAt: renderTimestamp(Math.max(channel.atMs, existing ? entryTime(existing) : 0)),
|
|
246
|
+
topic: existing?.topic ?? "",
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
return sortEntries([...byId.values()]);
|
|
250
|
+
};
|
|
251
|
+
const flush = () => {
|
|
252
|
+
// A structural change starts its write without awaiting it, so "nothing to do" still has
|
|
253
|
+
// to resolve behind whatever is already in flight — otherwise `await flush()` can return
|
|
254
|
+
// before the write it was meant to wait for has landed.
|
|
255
|
+
if (!dirty)
|
|
256
|
+
return pending;
|
|
257
|
+
// Cleared up front so observations arriving during the write are not swallowed by it;
|
|
258
|
+
// restored on failure so the next note retries instead of silently dropping them.
|
|
259
|
+
dirty = false;
|
|
260
|
+
pending = queue
|
|
261
|
+
.run(indexPath, async () => {
|
|
262
|
+
await writeFileAtomically(indexPath, renderChannelIndex(await merge()));
|
|
263
|
+
})
|
|
264
|
+
.catch((error) => {
|
|
265
|
+
dirty = true;
|
|
266
|
+
log.logWarning(`Failed to update ${CHANNELS_INDEX_FILENAME}`, errorMessage(error));
|
|
267
|
+
});
|
|
268
|
+
return pending;
|
|
269
|
+
};
|
|
270
|
+
return {
|
|
271
|
+
note(observation) {
|
|
272
|
+
if (closed || !observation.channelId)
|
|
273
|
+
return;
|
|
274
|
+
const name = normalizeName(observation.name);
|
|
275
|
+
const previous = observed.get(observation.channelId);
|
|
276
|
+
// A first sighting or a rename is the information this file exists to carry, so it
|
|
277
|
+
// bypasses the debounce; a fresher timestamp on an already-named channel can wait.
|
|
278
|
+
const structural = !previous || (name !== "" && name !== previous.name);
|
|
279
|
+
observed.set(observation.channelId, {
|
|
280
|
+
name: name || previous?.name || "",
|
|
281
|
+
atMs: Math.max(observation.at, previous?.atMs ?? 0),
|
|
282
|
+
});
|
|
283
|
+
dirty = true;
|
|
284
|
+
if (structural) {
|
|
285
|
+
cancelTimer();
|
|
286
|
+
void flush();
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
scheduleFlush();
|
|
290
|
+
},
|
|
291
|
+
async flush() {
|
|
292
|
+
await flush();
|
|
293
|
+
},
|
|
294
|
+
async close() {
|
|
295
|
+
cancelTimer();
|
|
296
|
+
await flush();
|
|
297
|
+
closed = true;
|
|
298
|
+
},
|
|
299
|
+
};
|
|
300
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export declare function isChannelId(value: string): boolean;
|
|
1
2
|
export declare function getChannelDirName(channelId: string): string;
|
|
2
3
|
export declare function getChannelDir(baseDir: string, channelId: string): string;
|
|
3
4
|
export declare function ensureChannelDir(baseDir: string, channelId: string): string;
|
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
import { mkdirSync } from "fs";
|
|
2
2
|
import { join } from "path";
|
|
3
|
+
/**
|
|
4
|
+
* Every channel id is `dm_<staffId>` or `group_<conversationId>`.
|
|
5
|
+
*
|
|
6
|
+
* The remainder is deliberately unconstrained apart from path-safety: a DingTalk
|
|
7
|
+
* conversation id is base64 and routinely contains `/` and `=`, so the charset allowlist this
|
|
8
|
+
* check used to carry (`[A-Za-z0-9._:-]+`) rejected every real group. Anything that filtered
|
|
9
|
+
* ids through it — workspace scans, the maintenance scheduler's known-channel filter — silently
|
|
10
|
+
* dropped those channels.
|
|
11
|
+
*
|
|
12
|
+
* What still has to hold is that an id can never escape the directory it names. `getChannelDir`
|
|
13
|
+
* folds `/` into `__`, but not every consumer escapes (the memory-maintenance state file
|
|
14
|
+
* interpolates the id straight into a filename), so a `..` segment and the path separators that
|
|
15
|
+
* survive escaping are rejected here, once, for everyone.
|
|
16
|
+
*/
|
|
17
|
+
const CHANNEL_ID_PATTERN = /^(dm|group)_[^\0\\]+$/;
|
|
18
|
+
export function isChannelId(value) {
|
|
19
|
+
if (!CHANNEL_ID_PATTERN.test(value))
|
|
20
|
+
return false;
|
|
21
|
+
return !value.split("/").includes("..");
|
|
22
|
+
}
|
|
3
23
|
export function getChannelDirName(channelId) {
|
|
4
24
|
return channelId.replaceAll("/", "__");
|
|
5
25
|
}
|
package/dist/runtime/delivery.js
CHANGED
|
@@ -51,7 +51,9 @@ class ChannelDeliveryController {
|
|
|
51
51
|
channel: this.event.channelId,
|
|
52
52
|
ts: this.event.ts,
|
|
53
53
|
},
|
|
54
|
-
|
|
54
|
+
// The group title when the transport supplied one; the raw id is the fallback so a
|
|
55
|
+
// synthetic event (which carries no conversation payload) still names its channel.
|
|
56
|
+
channelName: this.event.channelName ?? this.event.channelId,
|
|
55
57
|
respond: async (text, shouldLog = true) => this.appendProgress(text, shouldLog),
|
|
56
58
|
respondPlain: async (text, shouldLog = true) => this.sendFinal(text, shouldLog),
|
|
57
59
|
replaceMessage: async (text) => this.replaceWithFinal(text),
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { FinalDelivery, MediaSender, MediaSendResult, OutboundMedia, ProgressStyle } from "./channel-context.js";
|
|
2
|
+
import type { ChannelObservation } from "./channel-index.js";
|
|
2
3
|
export type BusyMessageMode = "steer" | "followUp";
|
|
3
4
|
export type BusyMessageDefaultConfig = BusyMessageMode | "followup";
|
|
4
5
|
export type ResponseMode = "full_progress_then_plain_final" | "rolling_progress_then_plain_final" | "final_card_only";
|
|
@@ -29,8 +30,19 @@ export interface DingTalkEvent {
|
|
|
29
30
|
text: string;
|
|
30
31
|
conversationId: string;
|
|
31
32
|
conversationType: string;
|
|
33
|
+
/**
|
|
34
|
+
* Human-readable channel name: the group title, or the peer's nickname for a DM. Absent on
|
|
35
|
+
* synthetic events (scheduled events, task-driver wakes), which carry no conversation payload.
|
|
36
|
+
*/
|
|
37
|
+
channelName?: string;
|
|
32
38
|
/** Runtime-owned durable-dispatch record, absent for normal inbound messages. */
|
|
33
39
|
dispatchId?: string;
|
|
40
|
+
/**
|
|
41
|
+
* The `attemptGeneration` this event's claim recorded, for `[TASK_DRIVER:id]` events only.
|
|
42
|
+
* Carried through durable dispatch so `finishTaskAttempt` can tell a stale, superseded claim's
|
|
43
|
+
* turn from the current one, even when redelivery or claim races reorder completions.
|
|
44
|
+
*/
|
|
45
|
+
taskAttemptGeneration?: number;
|
|
34
46
|
}
|
|
35
47
|
export type BusyMessageResult = {
|
|
36
48
|
kind: "handled";
|
|
@@ -48,6 +60,12 @@ export interface StopOutcome {
|
|
|
48
60
|
}
|
|
49
61
|
export interface DingTalkHandler {
|
|
50
62
|
isRunning(channelId: string): boolean;
|
|
63
|
+
/**
|
|
64
|
+
* Note that a real person just wrote in this channel. Called once per accepted inbound
|
|
65
|
+
* message, before any busy/command routing, and never for synthetic wakes — see the
|
|
66
|
+
* maintenance contract in `channel-index.ts`. Must stay synchronous and cheap.
|
|
67
|
+
*/
|
|
68
|
+
noteChannelActivity?(observation: ChannelObservation): void;
|
|
51
69
|
/**
|
|
52
70
|
* Synchronously reserve an inbound turn before the queued async body yields.
|
|
53
71
|
* The transport calls this hook, when provided, immediately before `handleEvent`.
|
package/dist/runtime/dingtalk.js
CHANGED
|
@@ -290,6 +290,9 @@ export class DingTalkBot {
|
|
|
290
290
|
return;
|
|
291
291
|
}
|
|
292
292
|
socket.removeAllListeners?.();
|
|
293
|
+
// ws emits an asynchronous error when close() aborts a CONNECTING socket.
|
|
294
|
+
const ignoreCleanupError = () => { };
|
|
295
|
+
socket.on("error", ignoreCleanupError);
|
|
293
296
|
if ((socket.readyState ?? SOCKET_STATE_CLOSED) !== SOCKET_STATE_CLOSED) {
|
|
294
297
|
try {
|
|
295
298
|
socket.close?.();
|
|
@@ -309,6 +312,9 @@ export class DingTalkBot {
|
|
|
309
312
|
await this.waitForSocketState(socket, SOCKET_STATE_CLOSED, SOCKET_TERMINATE_GRACE_MS);
|
|
310
313
|
}
|
|
311
314
|
}
|
|
315
|
+
if ((socket.readyState ?? SOCKET_STATE_CLOSED) === SOCKET_STATE_CLOSED) {
|
|
316
|
+
socket.removeListener?.("error", ignoreCleanupError);
|
|
317
|
+
}
|
|
312
318
|
this.clearClientSocketReference();
|
|
313
319
|
}
|
|
314
320
|
async connectWithTimeout() {
|
|
@@ -1069,12 +1075,19 @@ export class DingTalkBot {
|
|
|
1069
1075
|
ctx: { channelId, userName: senderName },
|
|
1070
1076
|
fields: { messageType: conversationType === "2" ? "group" : "dm", messageLength: content.length },
|
|
1071
1077
|
});
|
|
1078
|
+
// A group carries its title on every message; a DM has none, so the peer's nickname is
|
|
1079
|
+
// the only human-readable handle that channel will ever have.
|
|
1080
|
+
const conversationTitle = typeof data.conversationTitle === "string" ? data.conversationTitle.trim() : "";
|
|
1081
|
+
const channelName = (conversationType === "2" ? conversationTitle : senderName) || undefined;
|
|
1072
1082
|
// Cache conversation metadata for card creation
|
|
1073
1083
|
this.setConversationMeta(channelId, {
|
|
1074
1084
|
conversationId,
|
|
1075
1085
|
conversationType,
|
|
1076
1086
|
senderId,
|
|
1077
1087
|
});
|
|
1088
|
+
// The one place a real person's message is seen before command/busy routing splits the
|
|
1089
|
+
// path, so the channel index counts every human message and no synthetic wake.
|
|
1090
|
+
this.handler.noteChannelActivity?.({ channelId, name: channelName, at: Date.now() });
|
|
1078
1091
|
// Build event
|
|
1079
1092
|
const event = {
|
|
1080
1093
|
type: conversationType === "2" ? "group" : "dm",
|
|
@@ -1085,6 +1098,7 @@ export class DingTalkBot {
|
|
|
1085
1098
|
text: content,
|
|
1086
1099
|
conversationId,
|
|
1087
1100
|
conversationType,
|
|
1101
|
+
...(channelName ? { channelName } : {}),
|
|
1088
1102
|
};
|
|
1089
1103
|
const builtInCommand = parseBuiltInCommand(content);
|
|
1090
1104
|
const isSlashCommand = content.trim().startsWith("/");
|
|
@@ -8,7 +8,7 @@ export interface HandleTasksCommandOptions {
|
|
|
8
8
|
/** Direct command issuer; used to create an auditable external-action approval. */
|
|
9
9
|
approver?: string;
|
|
10
10
|
/** Optional immediate task wake, available in the long-lived DingTalk runtime. */
|
|
11
|
-
dispatchTask?: (id: string) => Promise<boolean>;
|
|
11
|
+
dispatchTask?: (id: string, attemptGeneration?: number) => Promise<boolean>;
|
|
12
12
|
}
|
|
13
13
|
export declare function pauseTask(options: HandleTasksCommandOptions, idInput: string): Promise<string>;
|
|
14
14
|
export declare function resumeTask(options: HandleTasksCommandOptions, idInput: string): Promise<string>;
|
|
@@ -424,7 +424,7 @@ async function runTask(options, idInput) {
|
|
|
424
424
|
await writeStoredTask(task);
|
|
425
425
|
}
|
|
426
426
|
const claim = claimedControl ? await claimTaskAttempt(options.channelDir, id, now) : undefined;
|
|
427
|
-
const enqueued = await options.dispatchTask?.(id);
|
|
427
|
+
const enqueued = await options.dispatchTask?.(id, claim?.generation);
|
|
428
428
|
if (!enqueued && claim)
|
|
429
429
|
await releaseTaskAttemptClaim(options.channelDir, id, claim);
|
|
430
430
|
return enqueued
|
|
@@ -20,7 +20,7 @@ export interface TaskDriverOptions {
|
|
|
20
20
|
intervalMs?: number;
|
|
21
21
|
}
|
|
22
22
|
export declare function discoverTaskChannels(workspaceDir: string, knownChannelIds?: Iterable<string>): Promise<string[]>;
|
|
23
|
-
export declare function createTaskDriverEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number): DingTalkEvent;
|
|
23
|
+
export declare function createTaskDriverEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number, attemptGeneration?: number): DingTalkEvent;
|
|
24
24
|
/**
|
|
25
25
|
* Native, token-gated driver for the persistent task ledger.
|
|
26
26
|
*
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
-
import { readdir } from "node:fs/promises";
|
|
3
2
|
import { join } from "node:path";
|
|
4
3
|
import * as log from "../log.js";
|
|
5
4
|
import { PLAYBOOKS_DIR } from "../paths.js";
|
|
@@ -9,32 +8,23 @@ import { taskBudgetViolation } from "../tasks/control.js";
|
|
|
9
8
|
import { normalizeTaskFields, readActiveTasks } from "../tasks/ledger.js";
|
|
10
9
|
import { claimTaskAttempt, escalateTask, openRecurringTaskCycle, releaseTaskAttemptClaim, updateStoredTask, } from "../tasks/store.js";
|
|
11
10
|
import { TERMINAL_TASK_STATUSES } from "../tasks/transitions.js";
|
|
11
|
+
import { discoverWorkspaceChannelIds } from "./channel-index.js";
|
|
12
|
+
import { isChannelId } from "./channel-paths.js";
|
|
12
13
|
/** Short debounce so a burst of nudges collapses into a single rescan. */
|
|
13
14
|
const NUDGE_DEBOUNCE_MS = 50;
|
|
14
15
|
/** Never schedule a scan closer than this, so near-now horizons cannot spin the loop. */
|
|
15
16
|
const MIN_SLEEP_MS = 250;
|
|
16
17
|
/** Consecutive no-progress wakes before the governor pauses a task (spec 029, D5). */
|
|
17
18
|
const FUTILE_WAKE_LIMIT = 3;
|
|
18
|
-
const CHANNEL_ID_PATTERN = /^(dm|group)_[A-Za-z0-9._:-]+$/;
|
|
19
19
|
const TERMINAL_STATUSES = TERMINAL_TASK_STATUSES;
|
|
20
|
-
function isChannelId(value) {
|
|
21
|
-
return CHANNEL_ID_PATTERN.test(value);
|
|
22
|
-
}
|
|
23
20
|
export async function discoverTaskChannels(workspaceDir, knownChannelIds = []) {
|
|
24
21
|
const channels = new Set();
|
|
25
22
|
for (const channelId of knownChannelIds) {
|
|
26
23
|
if (isChannelId(channelId))
|
|
27
24
|
channels.add(channelId);
|
|
28
25
|
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
for (const entry of entries) {
|
|
32
|
-
if (entry.isDirectory() && isChannelId(entry.name))
|
|
33
|
-
channels.add(entry.name);
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
catch {
|
|
37
|
-
// A missing/unreadable workspace simply has no tasks to drive this tick.
|
|
26
|
+
for (const channelId of await discoverWorkspaceChannelIds(workspaceDir)) {
|
|
27
|
+
channels.add(channelId);
|
|
38
28
|
}
|
|
39
29
|
return Array.from(channels).sort();
|
|
40
30
|
}
|
|
@@ -113,7 +103,7 @@ function taskDispatchId(channelId, entry, nowMs) {
|
|
|
113
103
|
const occurrence = entry.frontmatter.wake ?? `t${nowMs}`;
|
|
114
104
|
return `task:${channelId}:${entry.id}:${occurrence}`;
|
|
115
105
|
}
|
|
116
|
-
export function createTaskDriverEvent(channelId, entry, nowMs) {
|
|
106
|
+
export function createTaskDriverEvent(channelId, entry, nowMs, attemptGeneration) {
|
|
117
107
|
const verification = entry.frontmatter.control?.verification;
|
|
118
108
|
const verificationInstruction = entry.frontmatter.status === "verifying"
|
|
119
109
|
? verification?.status === "passed"
|
|
@@ -147,6 +137,7 @@ export function createTaskDriverEvent(channelId, entry, nowMs) {
|
|
|
147
137
|
conversationId: "",
|
|
148
138
|
conversationType: channelId.startsWith("group_") ? "2" : "1",
|
|
149
139
|
dispatchId: taskDispatchId(channelId, entry, nowMs),
|
|
140
|
+
taskAttemptGeneration: attemptGeneration,
|
|
150
141
|
};
|
|
151
142
|
}
|
|
152
143
|
/** status done + a schedule cadence + a valid wake that is due → time to open the next cycle. */
|
|
@@ -426,7 +417,7 @@ export class TaskDriver {
|
|
|
426
417
|
// Claiming an attempt only touches usage bookkeeping, which the fingerprint
|
|
427
418
|
// deliberately excludes, so there is nothing to recompute here.
|
|
428
419
|
const claim = entry.frontmatter.control ? await claimTaskAttempt(channelDir, entry.id, now) : undefined;
|
|
429
|
-
const event = createTaskDriverEvent(channelId, entry, nowMs);
|
|
420
|
+
const event = createTaskDriverEvent(channelId, entry, nowMs, claim?.generation);
|
|
430
421
|
const accepted = await this.options.dispatch(event);
|
|
431
422
|
this.observeDispatch(event, accepted);
|
|
432
423
|
if (!accepted && claim)
|
|
@@ -12,7 +12,22 @@
|
|
|
12
12
|
* in this module goes through one explicit format instead.
|
|
13
13
|
*/
|
|
14
14
|
const LOCAL_TIME_PATTERN = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?(Z|[+-]\d{2}:?\d{2})?$/;
|
|
15
|
+
/** A bare calendar date with no time component, e.g. `2026-07-27` — local midnight, never UTC midnight. */
|
|
16
|
+
const DATE_ONLY_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
15
17
|
const RELATIVE_TIME_PATTERN = /^([+-])(\d+(?:\.\d+)?)(s|m|h|d)$/i;
|
|
18
|
+
function isValidDateParts(year, month, day) {
|
|
19
|
+
if (month < 0 || month > 11)
|
|
20
|
+
return false;
|
|
21
|
+
if (day < 1 || day > 31)
|
|
22
|
+
return false;
|
|
23
|
+
// Reject calendar overflow (e.g. day 31 in a 30-day month) instead of letting Date silently
|
|
24
|
+
// roll it into the next month.
|
|
25
|
+
const probe = new Date(year, month, day);
|
|
26
|
+
return probe.getFullYear() === year && probe.getMonth() === month && probe.getDate() === day;
|
|
27
|
+
}
|
|
28
|
+
function isValidTimeParts(hour, minute, second) {
|
|
29
|
+
return hour >= 0 && hour <= 23 && minute >= 0 && minute <= 59 && second >= 0 && second <= 59;
|
|
30
|
+
}
|
|
16
31
|
function pad2(value) {
|
|
17
32
|
return String(value).padStart(2, "0");
|
|
18
33
|
}
|
|
@@ -49,11 +64,23 @@ export function localDayKey(date = new Date()) {
|
|
|
49
64
|
*/
|
|
50
65
|
export function parseLocalTime(value) {
|
|
51
66
|
const trimmed = value.trim();
|
|
67
|
+
const dateOnly = DATE_ONLY_PATTERN.exec(trimmed);
|
|
68
|
+
if (dateOnly) {
|
|
69
|
+
const [, y, mo, d] = dateOnly;
|
|
70
|
+
const year = Number(y);
|
|
71
|
+
const month = Number(mo) - 1;
|
|
72
|
+
const day = Number(d);
|
|
73
|
+
if (!isValidDateParts(year, month, day))
|
|
74
|
+
return undefined;
|
|
75
|
+
// A bare date has no time component to be ambiguous about: local midnight, same as
|
|
76
|
+
// `new Date(year, month, day)` — never the UTC-midnight reading `new Date(trimmed)` gives.
|
|
77
|
+
return new Date(year, month, day).getTime();
|
|
78
|
+
}
|
|
52
79
|
const match = LOCAL_TIME_PATTERN.exec(trimmed);
|
|
53
80
|
if (!match) {
|
|
54
|
-
// Fall back to a permissive parse for other legitimate ISO-ish inputs (e.g.
|
|
55
|
-
//
|
|
56
|
-
//
|
|
81
|
+
// Fall back to a permissive parse for other legitimate ISO-ish inputs (e.g. a
|
|
82
|
+
// datetime with no seconds, `2026-07-27T07:30`). The bare-date UTC-midnight trap this
|
|
83
|
+
// module exists to avoid is handled above, before this fallback is ever reached.
|
|
57
84
|
const fallback = new Date(trimmed).getTime();
|
|
58
85
|
return Number.isFinite(fallback) ? fallback : undefined;
|
|
59
86
|
}
|
|
@@ -65,6 +92,8 @@ export function parseLocalTime(value) {
|
|
|
65
92
|
const minute = Number(mi);
|
|
66
93
|
const second = Number(s);
|
|
67
94
|
const millis = ms ? Number(ms.padEnd(3, "0")) : 0;
|
|
95
|
+
if (!isValidDateParts(year, month, day) || !isValidTimeParts(hour, minute, second))
|
|
96
|
+
return undefined;
|
|
68
97
|
if (!offset) {
|
|
69
98
|
const local = new Date(year, month, day, hour, minute, second, millis);
|
|
70
99
|
return local.getTime();
|
|
@@ -76,6 +105,8 @@ export function parseLocalTime(value) {
|
|
|
76
105
|
if (!offsetMatch)
|
|
77
106
|
return undefined;
|
|
78
107
|
const [, sign, offH, offM] = offsetMatch;
|
|
108
|
+
if (Number(offH) > 23 || Number(offM) > 59)
|
|
109
|
+
return undefined;
|
|
79
110
|
const offsetMinutesTotal = (Number(offH) * 60 + Number(offM)) * (sign === "-" ? -1 : 1);
|
|
80
111
|
const utcMs = Date.UTC(year, month, day, hour, minute, second, millis);
|
|
81
112
|
return utcMs - offsetMinutesTotal * 60_000;
|
package/dist/tasks/store.d.ts
CHANGED
|
@@ -34,6 +34,15 @@ export declare function finishTaskAttempt(channelDir: string, id: string, result
|
|
|
34
34
|
failed: boolean;
|
|
35
35
|
silent?: boolean;
|
|
36
36
|
finishedAt: Date;
|
|
37
|
+
/**
|
|
38
|
+
* The `attemptGeneration` this turn's claim recorded (spec 029's monotonic claim
|
|
39
|
+
* identity, see `TaskControl.attemptGeneration`). When present and stale — a newer
|
|
40
|
+
* claim has since superseded it — usage is still tallied (the spend genuinely
|
|
41
|
+
* happened), but the outcome/finish fields are left alone so a slow, superseded turn
|
|
42
|
+
* cannot overwrite the newer attempt's in-flight or already-finished state. Absent
|
|
43
|
+
* (e.g. legacy callers) means "apply unconditionally", matching prior behavior.
|
|
44
|
+
*/
|
|
45
|
+
generation?: number;
|
|
37
46
|
}): Promise<void>;
|
|
38
47
|
/**
|
|
39
48
|
* A governor stop: the deterministic task governor pauses the task (spec 029, D3 — this is
|
package/dist/tasks/store.js
CHANGED
|
@@ -103,6 +103,8 @@ export async function finishTaskAttempt(channelDir, id, result) {
|
|
|
103
103
|
control.usage.costUsd += Math.max(0, result.costUsd);
|
|
104
104
|
control.usage.costKnown &&= result.costKnown;
|
|
105
105
|
control.usage.wallTimeMinutes += Math.max(0, result.wallTimeMinutes);
|
|
106
|
+
if (result.generation !== undefined && control.attemptGeneration !== result.generation)
|
|
107
|
+
return;
|
|
106
108
|
control.lastFinishedAt = formatLocalTime(result.finishedAt);
|
|
107
109
|
if (result.silent) {
|
|
108
110
|
// The driver claimed before dispatch to prevent concurrent work. A silent
|
package/package.json
CHANGED