@oyasmi/pipiclaw 0.8.9-beta.1 → 0.8.9-beta.3

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.
Files changed (92) hide show
  1. package/README.md +13 -6
  2. package/dist/agent/channel-runner.d.ts +7 -0
  3. package/dist/agent/channel-runner.js +30 -4
  4. package/dist/agent/command-extension.d.ts +3 -0
  5. package/dist/agent/command-extension.js +37 -0
  6. package/dist/agent/commands.js +6 -0
  7. package/dist/agent/effect-ledger.d.ts +11 -0
  8. package/dist/agent/effect-ledger.js +42 -0
  9. package/dist/agent/job-manager.d.ts +90 -13
  10. package/dist/agent/job-manager.js +235 -20
  11. package/dist/agent/prompt/sections.js +12 -3
  12. package/dist/agent/prompt/types.d.ts +7 -1
  13. package/dist/agent/runner-factory.d.ts +7 -0
  14. package/dist/agent/session-events.js +20 -1
  15. package/dist/index.d.ts +1 -1
  16. package/dist/log.d.ts +6 -0
  17. package/dist/log.js +12 -0
  18. package/dist/memory/consolidation.d.ts +5 -0
  19. package/dist/memory/consolidation.js +35 -147
  20. package/dist/memory/extraction.d.ts +45 -0
  21. package/dist/memory/extraction.js +227 -0
  22. package/dist/memory/lifecycle.js +5 -0
  23. package/dist/memory/maintenance-jobs.js +7 -0
  24. package/dist/memory/post-turn-review.d.ts +3 -1
  25. package/dist/memory/post-turn-review.js +20 -189
  26. package/dist/memory/recall.d.ts +0 -1
  27. package/dist/memory/recall.js +135 -77
  28. package/dist/memory/sidecar-worker.d.ts +7 -0
  29. package/dist/memory/sidecar-worker.js +23 -5
  30. package/dist/playbooks/background-jobs.md +40 -0
  31. package/dist/playbooks/catalog.d.ts +1 -7
  32. package/dist/playbooks/catalog.js +4 -14
  33. package/dist/playbooks/event-scheduling.md +8 -4
  34. package/dist/playbooks/memory-and-learning.md +1 -1
  35. package/dist/playbooks/outbound-media.md +45 -0
  36. package/dist/playbooks/runtime-orientation.md +2 -2
  37. package/dist/playbooks/task-closeout.md +1 -1
  38. package/dist/playbooks/task-delegation.md +11 -5
  39. package/dist/playbooks/task-driving.md +52 -18
  40. package/dist/playbooks/task-planning.md +43 -18
  41. package/dist/runtime/bootstrap.js +24 -3
  42. package/dist/runtime/channel-context.d.ts +33 -0
  43. package/dist/runtime/dingtalk.d.ts +22 -2
  44. package/dist/runtime/dingtalk.js +141 -0
  45. package/dist/runtime/durable-dispatch.d.ts +10 -0
  46. package/dist/runtime/durable-dispatch.js +42 -1
  47. package/dist/runtime/event-validation.d.ts +48 -0
  48. package/dist/runtime/event-validation.js +81 -0
  49. package/dist/runtime/events.d.ts +17 -8
  50. package/dist/runtime/events.js +96 -22
  51. package/dist/runtime/task-driver.d.ts +5 -0
  52. package/dist/runtime/task-driver.js +38 -12
  53. package/dist/settings.d.ts +16 -4
  54. package/dist/settings.js +13 -1
  55. package/dist/shared/recoverable-error.d.ts +26 -0
  56. package/dist/shared/recoverable-error.js +29 -0
  57. package/dist/shared/task-ledger.d.ts +9 -7
  58. package/dist/shared/task-ledger.js +1 -1
  59. package/dist/subagents/discovery.d.ts +16 -2
  60. package/dist/subagents/discovery.js +60 -13
  61. package/dist/subagents/tool.d.ts +20 -0
  62. package/dist/subagents/tool.js +143 -15
  63. package/dist/tasks/transitions.js +3 -2
  64. package/dist/tools/bash.d.ts +2 -0
  65. package/dist/tools/bash.js +18 -5
  66. package/dist/tools/event-manage.js +28 -77
  67. package/dist/tools/index.d.ts +4 -0
  68. package/dist/tools/index.js +7 -2
  69. package/dist/tools/job.js +2 -2
  70. package/dist/tools/memory-manage.js +0 -1
  71. package/dist/tools/registry.d.ts +29 -8
  72. package/dist/tools/registry.js +39 -22
  73. package/dist/tools/send-media.d.ts +28 -0
  74. package/dist/tools/send-media.js +88 -0
  75. package/dist/tools/task-manage/create.js +5 -4
  76. package/dist/tools/task-manage/lifecycle.js +12 -11
  77. package/dist/tools/task-manage/schema.js +2 -1
  78. package/dist/tools/task-manage/shared.js +13 -12
  79. package/dist/tools/task-manage/verification.js +14 -13
  80. package/dist/tools/tool-details.d.ts +44 -0
  81. package/dist/tools/tool-details.js +62 -0
  82. package/dist/tui/app.js +2 -0
  83. package/dist/tui/terminal-media-sender.d.ts +9 -0
  84. package/dist/tui/terminal-media-sender.js +15 -0
  85. package/examples/sub-agents/README.md +21 -0
  86. package/examples/sub-agents/explorer.md +17 -0
  87. package/examples/sub-agents/git-committer.md +50 -0
  88. package/examples/sub-agents/researcher.md +18 -0
  89. package/examples/sub-agents/verifier.md +19 -0
  90. package/package.json +3 -2
  91. package/dist/playbooks/task-recurring.md +0 -44
  92. package/dist/playbooks/task-repair.md +0 -45
package/README.md CHANGED
@@ -16,7 +16,7 @@ npm package: [`@oyasmi/pipiclaw`](https://www.npmjs.com/package/@oyasmi/pipiclaw
16
16
 
17
17
  **自己推进长程工作。** 定时事件支持立即、单次、周期三类,`preAction` 可用脚本做零 token 的触发前门控。语义更高一层的是任务台账(task ledger):任务以 Markdown 文件持久存在,内建 task driver 到点自动恢复、有进展有界续跑、停滞自动退避;配套受预算约束的恢复、独立验收、外部副作用授权,以及 `/tasks` 系列零 LLM 成本的控制面命令。
18
18
 
19
- **会用工具、能委派。** 内建 `bash`(支持 `async` 后台作业)、`read`(含目录树与 PDF)、`write` / `edit`、结构化 `grep`、`web_search` / `web_fetch`(结果缓存与分页续读)。预定义子代理把 reviewer、researcher 这类角色沉淀成可复用能力,支持 worktree 隔离与独立验收(verify);workspace skills 沉淀你自己的流程知识。
19
+ **会用工具、能委派。** 内建 `bash`(支持 `async` 后台作业)、`read`(含目录树与 PDF)、`write` / `edit`、结构化 `grep`、`web_search` / `web_fetch`(结果缓存与分页续读),以及 `send_media`——生成好的报表、截图、导出文件可以作为原生附件直接发回钉钉,而不是丢给你一个打不开的主机路径。工作区配置的子代理可以把 reviewer、researcher 这类角色沉淀成可复用能力,支持 worktree 隔离与独立验收(verify);workspace skills 沉淀你自己的流程知识。完整清单见 [docs/tools.md](./docs/tools.md)。
20
20
 
21
21
  **有安全护栏。** 所有文件、命令、网络工具都经过安全守卫:`bash` 命令拦截、统一路径检查、常见凭据与敏感位置默认拒绝、阻断写入审计日志;可通过 `security.json` 做实例级策略调整。详见 [docs/security.md](./docs/security.md)。
22
22
 
@@ -140,7 +140,8 @@ export ANTHROPIC_API_KEY=sk-ant-...
140
140
  ```json
141
141
  {
142
142
  "defaultProvider": "my-gateway",
143
- "defaultModel": "gpt-4.1"
143
+ "defaultModel": "gpt-4.1",
144
+ "defaultThinkingLevel": "medium"
144
145
  }
145
146
  ```
146
147
 
@@ -222,10 +223,11 @@ pipiclaw
222
223
  | `/compact [instructions]` | 手动压缩当前会话上下文 |
223
224
  | `/session` | 当前会话状态、消息统计、token 使用量 |
224
225
  | `/model [引用]` | 查看或切换模型 |
226
+ | `/thinking [level\|cycle]` | 查看、设置或轮换当前会话的 thinking level(默认 `medium`,按模型能力自动 clamp) |
225
227
 
226
228
  说明:
227
229
 
228
- - 前九条由传输层直接处理,**忙碌时也可用**(`/context` 是只读统计,零 LLM 成本);后四条会话命令仅空闲时可用(忙碌时会收到提示)。
230
+ - 前九条由传输层直接处理,**忙碌时也可用**(`/context` 是只读统计,零 LLM 成本);后五条会话命令仅空闲时可用(忙碌时会收到提示)。
229
231
  - 忙碌时的普通消息默认等价于 `/steer`,可通过 `channel.json` 的 `busyMessageDefault` 改为排队(`followUp`)。
230
232
  - 未知的斜杠命令会被直接拒绝并提示 `/help`,不会作为普通消息发给模型(避免 `/modle` 这类笔误变成一整轮 LLM 调用)。workspace skill 也可作为命令调用(`/skill:<名称>`)。
231
233
  - `/model` 依次尝试精确 `provider/modelId`、精确 `modelId`、对完整引用的子串匹配,只有唯一命中时才切换,例如 `/model turbo`。
@@ -234,15 +236,20 @@ pipiclaw
234
236
 
235
237
  ## 文档地图(Documentation)
236
238
 
239
+ 完整索引见 **[docs/README.md](./docs/README.md)**(按使用者 / 管理员 / 开发者分组)。常用入口:
240
+
237
241
  | 文档 | 内容 |
238
242
  |------|------|
243
+ | [docs/tools.md](./docs/tools.md) | 工具总览:每个能力做什么、开关在哪、子代理是否可用 |
244
+ | [docs/memory.md](./docs/memory.md) | 记忆分层:它记得什么、怎么让它记住或忘掉 |
239
245
  | [docs/configuration.md](./docs/configuration.md) | 全部配置项:钉钉、模型、settings、tools、TUI、记忆与工作区文件 |
240
246
  | [docs/events-and-tasks.md](./docs/events-and-tasks.md) | 定时事件(含 `preAction` 门控、`event_manage`)、任务台账、内建 task driver、`/tasks` 控制面与 `task_manage` 工具 |
241
- | [docs/sub-agents.md](./docs/sub-agents.md) | 预定义子代理:委派、隔离 worktree 与独立验收 |
242
- | [docs/runtime-playbooks.md](./docs/runtime-playbooks.md) | Runtime playbooks 与知识分层模型 |
247
+ | [docs/sub-agents.md](./docs/sub-agents.md) | 工作区配置子代理:委派、隔离 worktree 与独立验收 |
248
+ | [docs/security.md](./docs/security.md) | 默认安全策略、`security.json` 配置与已知边界 |
243
249
  | [docs/deployment-and-operations.md](./docs/deployment-and-operations.md) | 长期运行、日志、可观测性、升级、备份与排障 |
244
250
  | [docs/scaling-and-concurrency.md](./docs/scaling-and-concurrency.md) | 并发模型与容量边界 |
245
- | [docs/security.md](./docs/security.md) | 默认安全策略、`security.json` 配置与已知边界 |
251
+ | [docs/architecture.md](./docs/architecture.md) | as-implemented 架构:运行时拓扑、消息生命周期、并发表、磁盘布局 |
252
+ | [docs/runtime-playbooks.md](./docs/runtime-playbooks.md) | Runtime playbooks 与知识分层模型 |
246
253
 
247
254
  ## 开发(Development)
248
255
 
@@ -13,6 +13,7 @@ export declare class ChannelRunner implements AgentRunner {
13
13
  private readonly authConfigPath;
14
14
  private readonly modelsConfigPath;
15
15
  private readonly onSessionEvent?;
16
+ private readonly mediaSender?;
16
17
  private readonly workspaceDir;
17
18
  private session;
18
19
  private agent;
@@ -133,6 +134,12 @@ export declare class ChannelRunner implements AgentRunner {
133
134
  private createResourceLoader;
134
135
  private createAgentSessionServices;
135
136
  private createEmptyExtensionsResult;
137
+ /**
138
+ * Resolve the initial thinking level using the same precedence as pi's SDK:
139
+ * session history, configured default, then medium. The effective value is
140
+ * clamped to the selected model before the session starts.
141
+ */
142
+ private initializeThinkingLevel;
136
143
  private createSessionRuntime;
137
144
  private buildRuntimeTools;
138
145
  private rebuildSessionTools;
@@ -1,4 +1,5 @@
1
1
  import { Agent } from "@earendil-works/pi-agent-core";
2
+ import { clampThinkingLevel } from "@earendil-works/pi-ai/compat";
2
3
  import { AgentSession, AgentSessionRuntime, convertToLlm, createExtensionRuntime, DefaultResourceLoader, SessionManager, } from "@earendil-works/pi-coding-agent";
3
4
  import { mkdir, readFile, writeFile } from "fs/promises";
4
5
  import { dirname, join, resolve } from "path";
@@ -24,7 +25,6 @@ import { isRecord } from "../shared/type-guards.js";
24
25
  import { discoverSubAgents } from "../subagents/discovery.js";
25
26
  import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
26
27
  import { createPipiclawTools } from "../tools/index.js";
27
- import { TOOL_PROMPT_HINTS } from "../tools/registry.js";
28
28
  import { getUsageLedger } from "../usage/ledger.js";
29
29
  import { createCommandExtension } from "./command-extension.js";
30
30
  import { isKnownCommandName, renderBuiltInHelp, slashCommandName } from "./commands.js";
@@ -53,6 +53,7 @@ function getFinalOutcomeText(outcome) {
53
53
  function asSdkSettingsManager(manager) {
54
54
  return manager;
55
55
  }
56
+ const DEFAULT_MAIN_THINKING_LEVEL = "medium";
56
57
  export class ChannelRunner {
57
58
  constructor(channelId, channelDir, paths) {
58
59
  this.ledger = getUsageLedger();
@@ -75,6 +76,7 @@ export class ChannelRunner {
75
76
  this.authConfigPath = paths.authConfigPath;
76
77
  this.modelsConfigPath = paths.modelsConfigPath;
77
78
  this.onSessionEvent = paths.onSessionEvent;
79
+ this.mediaSender = paths.mediaSender;
78
80
  const executor = createExecutor();
79
81
  this.executor = executor;
80
82
  this.workspaceDir = resolve(dirname(channelDir));
@@ -96,7 +98,7 @@ export class ChannelRunner {
96
98
  initialState: {
97
99
  systemPrompt: "",
98
100
  model: this.activeModel,
99
- thinkingLevel: "off",
101
+ thinkingLevel: DEFAULT_MAIN_THINKING_LEVEL,
100
102
  tools: initialTools,
101
103
  },
102
104
  convertToLlm,
@@ -735,6 +737,7 @@ export class ChannelRunner {
735
737
  // Resolve model: prefer saved global default, fall back to first available model.
736
738
  this.activeModel = resolveInitialModel(this.modelRegistry, this.settingsManager);
737
739
  this.agent.state.model = this.activeModel; // correct the placeholder default
740
+ this.initializeThinkingLevel(this.agent, this.activeModel, this.sessionManager);
738
741
  log.logInfo(`Using model: ${this.activeModel.provider}/${this.activeModel.id} (${this.activeModel.name})`);
739
742
  this.subAgentDiscovery = await this.refreshSubAgentDiscovery();
740
743
  const initialResourceLoader = this.createResourceLoader();
@@ -865,7 +868,6 @@ export class ChannelRunner {
865
868
  tools: this.currentTools.map((tool) => ({
866
869
  name: tool.name,
867
870
  description: tool.description,
868
- hint: TOOL_PROMPT_HINTS[tool.name],
869
871
  })),
870
872
  soul: resources.soul,
871
873
  agents: resources.agents,
@@ -909,6 +911,9 @@ export class ChannelRunner {
909
911
  },
910
912
  getSessionStats: () => this.session.getSessionStats(),
911
913
  getThinkingLevel: () => this.session.thinkingLevel,
914
+ getAvailableThinkingLevels: () => this.session.getAvailableThinkingLevels(),
915
+ setThinkingLevel: (level) => this.session.setThinkingLevel(level),
916
+ cycleThinkingLevel: () => this.session.cycleThinkingLevel(),
912
917
  getLastResponseModel: () => getLastAssistantUsage(this.session.messages)?.responseModel,
913
918
  switchModel: async (model) => {
914
919
  await this.session.setModel(model);
@@ -957,18 +962,37 @@ export class ChannelRunner {
957
962
  runtime: createExtensionRuntime(),
958
963
  };
959
964
  }
965
+ /**
966
+ * Resolve the initial thinking level using the same precedence as pi's SDK:
967
+ * session history, configured default, then medium. The effective value is
968
+ * clamped to the selected model before the session starts.
969
+ */
970
+ initializeThinkingLevel(agent, model, sessionManager) {
971
+ const branch = sessionManager.getBranch();
972
+ const hasThinkingEntry = branch.some((entry) => entry.type === "thinking_level_change");
973
+ const sessionThinkingLevel = sessionManager.buildSessionContext().thinkingLevel;
974
+ const requestedLevel = hasThinkingEntry
975
+ ? sessionThinkingLevel
976
+ : (this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_MAIN_THINKING_LEVEL);
977
+ const effectiveLevel = clampThinkingLevel(model, requestedLevel);
978
+ agent.state.thinkingLevel = effectiveLevel;
979
+ if (!hasThinkingEntry) {
980
+ sessionManager.appendThinkingLevelChange(effectiveLevel);
981
+ }
982
+ }
960
983
  createSessionRuntime(sessionManager, sessionStartEvent) {
961
984
  const tools = this.buildRuntimeTools();
962
985
  const agent = new Agent({
963
986
  initialState: {
964
987
  systemPrompt: "",
965
988
  model: this.activeModel,
966
- thinkingLevel: "off",
989
+ thinkingLevel: DEFAULT_MAIN_THINKING_LEVEL,
967
990
  tools,
968
991
  },
969
992
  convertToLlm,
970
993
  getApiKey: async () => getApiKeyForModel(this.modelRegistry, this.activeModel),
971
994
  });
995
+ this.initializeThinkingLevel(agent, this.activeModel, sessionManager);
972
996
  const resourceLoader = this.createResourceLoader();
973
997
  const session = new AgentSession({
974
998
  agent,
@@ -997,10 +1021,12 @@ export class ChannelRunner {
997
1021
  channelId: this.channelId,
998
1022
  getSubAgentDiscovery: () => this.subAgentDiscovery,
999
1023
  getMemoryRecallSettings: () => this.settingsManager.getMemoryRecallSettings(),
1024
+ getSubAgentModelReference: () => this.settingsManager.getSubAgentModelReference(),
1000
1025
  getSessionSearchSettings: () => this.settingsManager.getSessionSearchSettings(),
1001
1026
  memoryCandidateStore: this.memoryCandidateStore,
1002
1027
  securityConfig: securityLoad.config,
1003
1028
  toolsConfig: toolsLoad.config,
1029
+ mediaSender: this.mediaSender,
1004
1030
  });
1005
1031
  this.currentTools = tools;
1006
1032
  return tools;
@@ -7,6 +7,9 @@ export interface PipiclawCommandExtensionOptions {
7
7
  getAvailableModels: () => Promise<Model<Api>[]>;
8
8
  getSessionStats: () => SessionStats;
9
9
  getThinkingLevel: () => ThinkingLevel;
10
+ getAvailableThinkingLevels: () => ThinkingLevel[];
11
+ setThinkingLevel: (level: ThinkingLevel) => void;
12
+ cycleThinkingLevel: () => ThinkingLevel | undefined;
10
13
  getLastResponseModel?: () => string | undefined;
11
14
  switchModel: (model: Model<Api>) => Promise<void>;
12
15
  refreshSessionResources: () => Promise<void>;
@@ -39,6 +39,14 @@ function sendCommandResult(sender, text) {
39
39
  display: true,
40
40
  });
41
41
  }
42
+ function buildThinkingText(current, available) {
43
+ return `# Thinking
44
+
45
+ Current level: \`${current}\`
46
+ Available levels: ${available.map((level) => `\`${level}\``).join(", ")}
47
+
48
+ Use \`/thinking <level>\` to set a level, or \`/thinking cycle\` to select the next supported level.`;
49
+ }
42
50
  export function createCommandExtension(options) {
43
51
  return (pi) => {
44
52
  pi.registerCommand("memory", {
@@ -53,6 +61,35 @@ export function createCommandExtension(options) {
53
61
  sendCommandResult(pi, buildSessionText(options.getSessionStats(), options.getCurrentModel(), options.getThinkingLevel(), options.getLastResponseModel?.()));
54
62
  },
55
63
  });
64
+ pi.registerCommand("thinking", {
65
+ description: sessionCommandDescription("thinking"),
66
+ handler: async (args) => {
67
+ const available = options.getAvailableThinkingLevels();
68
+ const normalized = args.trim().toLowerCase();
69
+ if (!normalized) {
70
+ sendCommandResult(pi, buildThinkingText(options.getThinkingLevel(), available));
71
+ return;
72
+ }
73
+ if (normalized === "cycle") {
74
+ const next = options.cycleThinkingLevel();
75
+ if (!next) {
76
+ sendCommandResult(pi, "当前模型不支持 thinking/reasoning。");
77
+ return;
78
+ }
79
+ sendCommandResult(pi, `Thinking level 已切换为 \`${next}\`。`);
80
+ return;
81
+ }
82
+ if (!available.includes(normalized)) {
83
+ sendCommandResult(pi, `不支持 thinking level \`${args.trim()}\`。当前模型可用值:${available
84
+ .map((level) => `\`${level}\``)
85
+ .join(", ")}`);
86
+ return;
87
+ }
88
+ const level = normalized;
89
+ options.setThinkingLevel(level);
90
+ sendCommandResult(pi, `Thinking level 已设置为 \`${level}\`。`);
91
+ },
92
+ });
56
93
  pi.registerCommand("model", {
57
94
  description: sessionCommandDescription("model"),
58
95
  handler: async (args) => {
@@ -98,6 +98,12 @@ export const SESSION_COMMANDS = [
98
98
  description: "Show current session state, message stats, token usage, and model info",
99
99
  examples: ["/session"],
100
100
  },
101
+ {
102
+ name: "thinking",
103
+ argumentHint: "[off|minimal|low|medium|high|xhigh|max|cycle]",
104
+ description: "Show or change the thinking level for the current model",
105
+ examples: ["/thinking", "/thinking medium", "/thinking cycle"],
106
+ },
101
107
  {
102
108
  name: "model",
103
109
  argumentHint: "[provider/modelId|modelId]",
@@ -0,0 +1,11 @@
1
+ export declare function noteChannelEffect(channelId: string): void;
2
+ export declare function channelEffectCount(channelId: string): number;
3
+ /** Test seam: drop all tallies. */
4
+ export declare function resetChannelEffects(): void;
5
+ /**
6
+ * Whether a completed tool call counts as an effect. `bash` is the awkward case — the same tool
7
+ * runs `ls` and `rm -rf`, and the runtime cannot tell them apart — so only a background launch
8
+ * (which leaves a job behind) counts. Erring toward "no effect" means a genuinely idle loop is
9
+ * still caught; erring the other way would let any wake claim progress by running `true`.
10
+ */
11
+ export declare function isEffectfulTool(toolName: string, details: unknown): boolean;
@@ -0,0 +1,42 @@
1
+ import { isRecord } from "../shared/type-guards.js";
2
+ /**
3
+ * Per-channel tally of externally visible effects (spec 031, D7).
4
+ *
5
+ * The task governor has to answer "did that wake accomplish anything?". It used to answer by
6
+ * diffing the task file's own metadata — including the model-written progress note — which made
7
+ * the check both bypassable and unfair: a model that appended a note every wake looked productive
8
+ * forever, while a model that changed code without writing a note looked stalled and got paused.
9
+ *
10
+ * Effects are counted here instead, and only for things that change the world outside the task
11
+ * ledger: writes, outbound media, sub-agent runs, background job launches, and a user-visible
12
+ * reply. Self-report tools (`task_manage`, `memory_manage`) and read-only tools deliberately do
13
+ * not count — a claim of progress is not evidence of it.
14
+ *
15
+ * The tally lives in process memory, exactly like the driver's futile counter it feeds; a restart
16
+ * resets both, which costs at most one extra round of patience before the governor intervenes.
17
+ */
18
+ const counts = new Map();
19
+ /** Tools whose successful completion is, by itself, a visible change to the world. */
20
+ const EFFECT_TOOLS = new Set(["write", "edit", "send_media", "subagent"]);
21
+ export function noteChannelEffect(channelId) {
22
+ counts.set(channelId, (counts.get(channelId) ?? 0) + 1);
23
+ }
24
+ export function channelEffectCount(channelId) {
25
+ return counts.get(channelId) ?? 0;
26
+ }
27
+ /** Test seam: drop all tallies. */
28
+ export function resetChannelEffects() {
29
+ counts.clear();
30
+ }
31
+ /**
32
+ * Whether a completed tool call counts as an effect. `bash` is the awkward case — the same tool
33
+ * runs `ls` and `rm -rf`, and the runtime cannot tell them apart — so only a background launch
34
+ * (which leaves a job behind) counts. Erring toward "no effect" means a genuinely idle loop is
35
+ * still caught; erring the other way would let any wake claim progress by running `true`.
36
+ */
37
+ export function isEffectfulTool(toolName, details) {
38
+ if (toolName === "bash") {
39
+ return isRecord(details) && details.async !== undefined;
40
+ }
41
+ return EFFECT_TOOLS.has(toolName);
42
+ }
@@ -1,15 +1,19 @@
1
1
  import type { Executor } from "../executor.js";
2
+ import type { DingTalkEvent } from "../runtime/dingtalk.js";
2
3
  /**
3
4
  * Per-channel manager for background bash jobs. A long command that ran synchronously would hold
4
5
  * the channel's run queue for its whole duration, blocking `/steer`, `/followup`, and every other
5
- * message. A background job instead returns immediately; the model can end its turn (freeing the
6
- * queue) and check back later — typically by scheduling a check-in with `event_manage`, or by
7
- * calling the `job` tool to poll.
6
+ * message. A background job instead returns immediately and the model can end its turn.
8
7
  *
9
- * Jobs live entirely on the host, managed through shell commands (`nohup` to launch, `kill -0` to
10
- * probe, `kill` to cancel) with no in-process child handles. Manager state is in-memory and not
11
- * persisted: after a process restart, prior jobs surface as `lost` rather than being falsely
12
- * resurrected.
8
+ * Jobs live on the host, managed through shell commands (`nohup` to launch, `kill -0` to probe,
9
+ * `kill` to cancel) with no in-process child handles. Records are mirrored to
10
+ * `state/jobs/<channelId>/<id>.json` so they survive a restart: a `nohup` process outlives the
11
+ * daemon, and losing the record while the process kept running meant orphaned work, leaked slots,
12
+ * and unreachable output (spec 031, D6).
13
+ *
14
+ * A finished job wakes its channel by itself. Making the model predict a completion time and
15
+ * arrange its own callback was a judgement call it could not make correctly, so completion is a
16
+ * runtime guarantee instead.
13
17
  */
14
18
  export type JobStatus = "running" | "completed" | "failed" | "cancelled" | "lost";
15
19
  export interface JobSnapshot {
@@ -21,6 +25,25 @@ export interface JobSnapshot {
21
25
  durationMs: number;
22
26
  exitCode?: number;
23
27
  }
28
+ /** What should happen when the job finishes. */
29
+ export interface JobWakeContract {
30
+ /** Wake the channel on completion. Defaults to true — that is the point of the mechanism. */
31
+ notify: boolean;
32
+ /** The task this job is advancing, surfaced in the wake so the model lands in context. */
33
+ taskId?: string;
34
+ }
35
+ export interface JobStartOptions {
36
+ signal?: AbortSignal;
37
+ notify?: boolean;
38
+ taskId?: string;
39
+ }
40
+ export interface JobManagerOptions {
41
+ /** Directory for this channel's persisted job records. Omit to run without persistence. */
42
+ stateDir?: string;
43
+ /** Delivers the completion wake. Omit to disable waking (sub-agent and test paths). */
44
+ dispatch?: (event: DingTalkEvent) => boolean | Promise<boolean>;
45
+ sweepIntervalMs?: number;
46
+ }
24
47
  /** Cap on concurrently running jobs per channel, so a runaway model can't spawn unbounded processes. */
25
48
  export declare const MAX_RUNNING_JOBS = 5;
26
49
  /** Longest a single `poll` call blocks before returning a snapshot; the model can poll again. */
@@ -29,18 +52,34 @@ export declare const POLL_WAIT_MS = 30000;
29
52
  * How often the internal sweeper refreshes running jobs while any are alive. Without it, a job that
30
53
  * finishes (or overruns its timeout) is only reaped when the model happens to call list/poll/cancel —
31
54
  * so a never-polled job would hold a `MAX_RUNNING_JOBS` slot forever, eventually blocking all `async`.
32
- * The sweep only reconciles in-memory state (and enforces the hard timeout); it never wakes the
33
- * channel, so it stays within the design's "no automatic completion delivery" decision.
55
+ * It is also what makes completion wakes timely: the sweep is where a finished job is noticed, and
56
+ * therefore where it announces itself (spec 031, D6, which replaced the earlier "no automatic
57
+ * completion delivery" decision).
34
58
  */
35
59
  export declare const SWEEP_INTERVAL_MS = 10000;
60
+ /**
61
+ * How long a finished job's record, spill file, and exit file are kept. The model has to be able
62
+ * to read the output after the completion wake, so they cannot be deleted the moment the job ends.
63
+ */
64
+ export declare const FINISHED_JOB_RETENTION_MS: number;
36
65
  export declare class ChannelJobManager {
37
66
  private readonly channelId;
38
67
  private readonly executor;
39
- private readonly sweepIntervalMs;
40
68
  private readonly jobs;
41
69
  private sweepTimer?;
42
70
  private sweeping;
43
- constructor(channelId: string, executor: Executor, sweepIntervalMs?: number);
71
+ private readonly options;
72
+ private readonly sweepIntervalMs;
73
+ constructor(channelId: string, executor: Executor, options?: JobManagerOptions | number);
74
+ private recordPath;
75
+ /** Mirror a record to disk. Persistence is best-effort: it must never fail a job operation. */
76
+ private persist;
77
+ private forget;
78
+ /**
79
+ * Drop finished jobs whose retention window has passed, together with their spill files.
80
+ * Called from the sweeper and from restore, so leftovers never outlive a daemon restart.
81
+ */
82
+ private collectGarbage;
44
83
  get channel(): string;
45
84
  runningCount(): number;
46
85
  /**
@@ -48,7 +87,7 @@ export declare class ChannelJobManager {
48
87
  * stdout/stderr to a spill file and the command's exit code to a sibling `.exit` file, then
49
88
  * `echo $!` hands back the nohup PID for later probing/cancellation.
50
89
  */
51
- start(command: string, label: string, timeoutSeconds: number, signal?: AbortSignal): Promise<JobSnapshot>;
90
+ start(command: string, label: string, timeoutSeconds: number, options?: JobStartOptions): Promise<JobSnapshot>;
52
91
  /**
53
92
  * Start the low-frequency sweeper if it is not already running. It reaps finished/timed-out jobs
54
93
  * so their slots free up even when the model never polls, and stops itself once nothing is running.
@@ -56,8 +95,22 @@ export declare class ChannelJobManager {
56
95
  private ensureSweeper;
57
96
  private stopSweeper;
58
97
  private sweep;
59
- /** Refresh the status of a single running job by consulting its `.exit` file and liveness. */
98
+ /**
99
+ * Refresh the status of a single running job by consulting its `.exit` file and liveness.
100
+ *
101
+ * `announce` is false only on the `poll` path, which hands the model the finished job's output
102
+ * inline: waking the channel for a result the model is already holding would burn a whole turn
103
+ * to say nothing.
104
+ */
60
105
  private refresh;
106
+ /** Move a job to a terminal status: record it, persist it, and wake the channel once. */
107
+ private finish;
108
+ /**
109
+ * Wake the channel for a finished job. `notified` is persisted before anything else can run
110
+ * again, so a restart mid-announce cannot produce a second wake; the dispatch id is stable for
111
+ * the same reason (spec 031, D1).
112
+ */
113
+ private announce;
61
114
  private kill;
62
115
  list(signal?: AbortSignal): Promise<JobSnapshot[]>;
63
116
  cancel(ids: string[], signal?: AbortSignal): Promise<Array<{
@@ -70,10 +123,34 @@ export declare class ChannelJobManager {
70
123
  * running jobs.
71
124
  */
72
125
  poll(ids: string[] | undefined, signal?: AbortSignal): Promise<JobSnapshot[]>;
126
+ /**
127
+ * Rebuild in-memory state from `state/jobs/<channelId>/` after a restart.
128
+ *
129
+ * `nohup` processes outlive the daemon, so the records — not the process table — are what was
130
+ * lost. Re-adopting them makes a still-running job count toward the concurrency cap again,
131
+ * lets its output be retrieved, and lets its completion wake fire (late, but not never).
132
+ */
133
+ restore(signal?: AbortSignal): Promise<number>;
73
134
  /** Read the (possibly truncated) captured output of a finished or running job. */
74
135
  readOutput(id: string, signal?: AbortSignal): Promise<{
75
136
  spillFile: string;
76
137
  text: string;
77
138
  } | undefined>;
78
139
  }
140
+ interface JobRuntimeConfig {
141
+ /** Root of the per-channel record directories (`<jobsStateDir>/<channelId>/`). */
142
+ jobsStateDir?: string;
143
+ dispatch?: (event: DingTalkEvent) => boolean | Promise<boolean>;
144
+ }
145
+ /**
146
+ * Give background jobs their persistence root and their way to wake a channel. Called once from
147
+ * bootstrap, before any turn runs; the tool layer builds managers lazily and picks this up.
148
+ */
149
+ export declare function configureJobRuntime(config: JobRuntimeConfig): void;
79
150
  export declare function getChannelJobManager(channelId: string, executor: Executor): ChannelJobManager;
151
+ /**
152
+ * Re-adopt every channel's persisted jobs at startup. Channels are discovered from the state
153
+ * directory itself, so a job survives even when its channel has had no traffic since the restart.
154
+ */
155
+ export declare function restoreChannelJobs(executor: Executor): Promise<number>;
156
+ export {};