@oyasmi/pipiclaw 0.7.6 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +13 -0
  2. package/dist/agent/channel-runner.d.ts +3 -0
  3. package/dist/agent/channel-runner.js +14 -4
  4. package/dist/agent/commands.js +8 -2
  5. package/dist/agent/prompt-builder.js +46 -0
  6. package/dist/agent/session-events.js +5 -0
  7. package/dist/agent/types.d.ts +2 -0
  8. package/dist/memory/recall.js +6 -0
  9. package/dist/memory/task-digest.js +17 -0
  10. package/dist/models/api-keys.d.ts +5 -1
  11. package/dist/models/api-keys.js +10 -4
  12. package/dist/runtime/bootstrap.d.ts +5 -0
  13. package/dist/runtime/bootstrap.js +59 -2
  14. package/dist/runtime/dingtalk.d.ts +2 -0
  15. package/dist/runtime/dingtalk.js +13 -1
  16. package/dist/runtime/durable-dispatch.d.ts +28 -0
  17. package/dist/runtime/durable-dispatch.js +144 -0
  18. package/dist/runtime/events.d.ts +4 -2
  19. package/dist/runtime/events.js +12 -8
  20. package/dist/runtime/task-commands.d.ts +9 -0
  21. package/dist/runtime/task-commands.js +429 -2
  22. package/dist/runtime/task-driver.d.ts +32 -0
  23. package/dist/runtime/task-driver.js +270 -0
  24. package/dist/settings.d.ts +12 -0
  25. package/dist/settings.js +30 -0
  26. package/dist/shared/atomic-file.js +23 -3
  27. package/dist/shared/task-events.d.ts +32 -0
  28. package/dist/shared/task-events.js +29 -0
  29. package/dist/shared/task-ledger.d.ts +53 -0
  30. package/dist/shared/task-ledger.js +246 -8
  31. package/dist/subagents/tool.d.ts +13 -0
  32. package/dist/subagents/tool.js +229 -15
  33. package/dist/tasks/artifact-subject.d.ts +6 -0
  34. package/dist/tasks/artifact-subject.js +29 -0
  35. package/dist/tasks/control.d.ts +83 -0
  36. package/dist/tasks/control.js +292 -0
  37. package/dist/tasks/store.d.ts +32 -0
  38. package/dist/tasks/store.js +142 -0
  39. package/dist/tasks/verification.d.ts +23 -0
  40. package/dist/tasks/verification.js +68 -0
  41. package/dist/tools/registry.d.ts +1 -1
  42. package/dist/tools/registry.js +6 -4
  43. package/dist/tools/task-manage.d.ts +51 -3
  44. package/dist/tools/task-manage.js +491 -37
  45. package/dist/tools/web-fetch.js +3 -0
  46. package/dist/tui/app.js +1 -1
  47. package/dist/tui/commands.js +1 -1
  48. package/package.json +1 -1
package/README.md CHANGED
@@ -23,6 +23,8 @@ npm package: [`@oyasmi/pipiclaw`](https://www.npmjs.com/package/@oyasmi/pipiclaw
23
23
  - 按工作区 / 会话通道(workspace / channel)分层管理 `SOUL.md`、`AGENTS.md`、`SESSION.md`、`MEMORY.md`、`HISTORY.md`
24
24
  - 支持预定义子代理(sub-agent)和临时内联子代理(inline sub-agent)
25
25
  - 支持立即、单次、周期三类事件调度
26
+ - 内建长程任务 driver:`wake` 到点自动恢复、任务有进展时有界续跑、停滞时自动退避,无需手工 heartbeat 脚本或 check-in 事件
27
+ - Task Loop v2:持久派发、受预算约束的恢复、独立验收与可操作的 `pause` / `resume` / `run` / `stats` 控制面,让长期工作持续沉淀为可检查的结果
26
28
  - 支持自定义模型提供方(provider)和模型(model)配置
27
29
  - 内建 `web_search` / `web_fetch`,支持联网搜索与网页抓取;`web_fetch` 支持结果缓存与分页续读,长网页被截断后可直接续读、不重抓
28
30
  - 内建 `grep` 结构化搜索工具:按文件分组、分页、token 有界的内容检索,优于裸 `bash grep`
@@ -458,6 +460,14 @@ Pipiclaw 有两层命令。
458
460
  | `/events show <name>` | 查看指定事件文件的完整 JSON |
459
461
  | `/events delete <name>` | 删除指定事件文件 |
460
462
  | `/events history [name]` | 查看事件调度历史,可按事件名过滤 |
463
+ | `/tasks` | 查看当前通道的 active 任务台账与治理状态 |
464
+ | `/tasks show <id>` | 查看指定任务台账 |
465
+ | `/tasks archive` | 查看已归档任务 |
466
+ | `/tasks approve <id>` | 显式批准该任务的外部副作用,并记录授权人/时间 |
467
+ | `/tasks pause <id>` / `/tasks resume <id>` | 持久暂停或恢复一个长程任务的自动推进 |
468
+ | `/tasks run <id>` | 立即安排一轮已就绪任务 |
469
+ | `/tasks stats [id]` | 查看任务的 token、成本、attempt 与验收统计 |
470
+ | `/tasks doctor` | 诊断任务台账与 task event 的一致性问题 |
461
471
  | `/status` | 查看运行时状态:执行状态、当前模型、上下文用量、运行时长、版本 |
462
472
  | `/usage [7d\|month]` | 查看本通道与全局的 LLM 成本,按类型和 Top 模型拆分 |
463
473
 
@@ -513,6 +523,7 @@ Pipiclaw 的核心不是一个临时机器人实例,而是一组长期存在
513
523
  │ ├── SESSION.md
514
524
  │ ├── MEMORY.md
515
525
  │ ├── HISTORY.md
526
+ │ ├── tasks/
516
527
  │ ├── .channel-meta.json
517
528
  │ ├── context.jsonl
518
529
  │ ├── log.jsonl
@@ -533,6 +544,8 @@ Pipiclaw 的核心不是一个临时机器人实例,而是一组长期存在
533
544
  稳定事实、决策和偏好
534
545
  - `HISTORY.md`
535
546
  更早上下文的摘要
547
+ - `<channel>/tasks/`
548
+ 当前通道的长程任务台账;active 任务位于目录根部,完成后的任务归档到 `tasks/archive/`。DingTalk daemon 内建 task driver,会根据 status/wake 自动恢复 actionable task
536
549
 
537
550
  ## 记忆模型(Memory Model)
538
551
 
@@ -2,6 +2,7 @@ import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
2
2
  import type { ChannelContext } from "../runtime/channel-context.js";
3
3
  import type { ChannelStore } from "../runtime/store.js";
4
4
  import { type SandboxConfig } from "../sandbox.js";
5
+ import type { UsageTotals } from "../shared/types.js";
5
6
  import { type BuiltInCommand } from "./commands.js";
6
7
  import type { RunnerFactoryPaths } from "./runner-factory.js";
7
8
  import { type AgentRunner, type RunnerStatusSnapshot } from "./types.js";
@@ -41,6 +42,8 @@ export declare class ChannelRunner implements AgentRunner {
41
42
  run(ctx: ChannelContext, store: ChannelStore): Promise<{
42
43
  stopReason: string;
43
44
  errorMessage?: string;
45
+ usage: UsageTotals;
46
+ durationMs: number;
44
47
  }>;
45
48
  handleBuiltinCommand(ctx: ChannelContext, command: BuiltInCommand): Promise<void>;
46
49
  queueSteer(text: string, userName?: string): Promise<void>;
@@ -16,7 +16,6 @@ import { createExecutor } from "../sandbox.js";
16
16
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
17
17
  import { PipiclawSettingsManager } from "../settings.js";
18
18
  import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
19
- import { HAN_REGEX } from "../shared/text-utils.js";
20
19
  import { isRecord } from "../shared/type-guards.js";
21
20
  import { discoverSubAgents, formatSubAgentList } from "../subagents/discovery.js";
22
21
  import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
@@ -150,6 +149,7 @@ export class ChannelRunner {
150
149
  }
151
150
  // === Public API ===
152
151
  async run(ctx, store) {
152
+ const startedAt = Date.now();
153
153
  this.resetRunState(ctx, store);
154
154
  this.acceptingBusyMessages = true;
155
155
  this.agentLoopStarted = false;
@@ -169,7 +169,6 @@ export class ChannelRunner {
169
169
  const clippedInput = clipUserInput(ctx.message.text, MAX_USER_MESSAGE_CHARS);
170
170
  const userMessage = this.formatUserMessage(clippedInput, ctx.message.userName);
171
171
  const preserveRawInput = this.shouldPreserveRawInput(ctx.message.text);
172
- await this.maybeRunPreventiveCompactionForIncomingText(preserveRawInput ? clippedInput : userMessage);
173
172
  // Ensure channel directory exists
174
173
  await mkdir(this.channelDir, { recursive: true });
175
174
  let promptText = preserveRawInput ? clippedInput : userMessage;
@@ -188,7 +187,9 @@ export class ChannelRunner {
188
187
  maxInjected: recallSettings.maxInjected,
189
188
  maxChars: recallSettings.maxChars,
190
189
  rerankWithModel: recallSettings.rerankWithModel,
191
- autoRerank: HAN_REGEX.test(clippedInput),
190
+ // Let shouldUseModelRerank's own memory-intent gate decide (it already handles
191
+ // Chinese phrasing) — forcing autoRerank for every Han-script message triggered a
192
+ // model rerank (up to 8s) on nearly every Chinese turn once memory filled up.
192
193
  model: this.session.model ?? this.activeModel,
193
194
  resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
194
195
  candidateStore: this.memoryCandidateStore,
@@ -217,6 +218,10 @@ export class ChannelRunner {
217
218
  this.firstTurnMemoryBootstrapPending = false;
218
219
  }
219
220
  }
221
+ // Estimated against the fully assembled prompt (recall + task digest + bootstrap all
222
+ // prepended above), not just the bare user message — those pieces can add thousands of
223
+ // characters and must count against the projected context usage this guard is checking.
224
+ await this.maybeRunPreventiveCompactionForIncomingText(promptText);
220
225
  // Debug: write context to last_prompt.json (only with PIPICLAW_DEBUG=1)
221
226
  if (process.env.PIPICLAW_DEBUG) {
222
227
  const debugContext = {
@@ -401,7 +406,12 @@ export class ChannelRunner {
401
406
  this.runState.logCtx = null;
402
407
  this.runState.queue = null;
403
408
  }
404
- return { stopReason: this.runState.stopReason, errorMessage: this.runState.errorMessage };
409
+ return {
410
+ stopReason: this.runState.stopReason,
411
+ errorMessage: this.runState.errorMessage,
412
+ usage: { ...this.runState.totalUsage, cost: { ...this.runState.totalUsage.cost } },
413
+ durationMs: Date.now() - startedAt,
414
+ };
405
415
  }
406
416
  async handleBuiltinCommand(ctx, command) {
407
417
  try {
@@ -24,11 +24,17 @@ These are handled directly by the DingTalk transport/runtime layer.
24
24
  Example: \`/events show weekly-review\`
25
25
  Example: \`/events delete weekly-review\`
26
26
  Example: \`/events history weekly-review\`
27
- - \`/tasks [show <id>|archive]\`
28
- View the channel's task ledger (read-only); to change a task, just tell me in plain language
27
+ - \`/tasks [show <id>|archive|approve <id>|pause <id>|resume <id>|run <id>|stats [id]|doctor]\`
28
+ View and diagnose the channel's task ledger; \`approve\` is the explicit user gate for external side effects
29
29
  Example: \`/tasks\`
30
30
  Example: \`/tasks show weekly-report\`
31
31
  Example: \`/tasks archive\`
32
+ Example: \`/tasks approve publish-release\`
33
+ Example: \`/tasks pause weekly-report\`
34
+ Example: \`/tasks resume weekly-report\`
35
+ Example: \`/tasks run weekly-report\`
36
+ Example: \`/tasks stats weekly-report\`
37
+ Example: \`/tasks doctor\`
32
38
  - \`/status\`
33
39
  Show runtime status: run state, current model, context usage, uptime, version
34
40
  Example: \`/status\`
@@ -56,6 +56,7 @@ ${workspacePath}/
56
56
  ├── SESSION.md # Channel working memory (runtime-managed, read on demand)
57
57
  ├── MEMORY.md # Channel durable memory (read on demand, runtime-managed)
58
58
  ├── HISTORY.md # Channel summarized history (read on demand, runtime-managed)
59
+ ├── tasks/ # Persistent long-running task ledger
59
60
  ├── log.jsonl # Raw message archive (cold storage)
60
61
  └── context.jsonl # Raw session archive (cold storage)`);
61
62
  sections.push(`## Events
@@ -146,6 +147,46 @@ Maintain ${workspacePath}/ENVIRONMENT.md to record durable environment changes w
146
147
 
147
148
  Keep it factual and concise. Do not use it for task progress or conversation summaries.`);
148
149
  sections.push(buildToolsSection(toolList));
150
+ if (hasTool("task_manage")) {
151
+ sections.push(`## Persistent Tasks
152
+ Use the task ledger for work explicitly meant to survive the current turn: multi-step goals, delegated work,
153
+ waiting for people or external systems, and recurring procedures. Do not create a task for a simple request you
154
+ can finish now.
155
+
156
+ - Create with task_manage create. Put the outcome in Goal, objective acceptance criteria in DoD, and the reusable
157
+ procedure in Manual. Put deterministic acceptance checks in Verification. New tasks default to independent
158
+ verification and a bounded attempt budget; set priority, deadline, nextAction, sideEffects, and tighter budgets
159
+ when the work warrants them.
160
+ - Decompose genuinely separable long work into child tasks with control.parent and control.dependsOn. A dependency
161
+ must be done before the driver will run its dependent; never create cycles. Use control.isolation=worktree for
162
+ write-heavy child work that must not mutate the parent's checkout.
163
+ - A task is actionable when status is not done and wake is absent, invalid, or due. On long-lived DingTalk
164
+ dm_/group_ channels, the native task driver scans this deterministically and wakes the task; no heartbeat event,
165
+ sensor script, or .checkin event is required. TUI-only channels persist the ledger but cannot wake a closed TUI.
166
+ - When a task-driver/event message names a task, open that exact tasks/<id>.md before acting.
167
+ - Before every task-driving turn that remains open ends, call task_manage progress once. Its note must say what
168
+ changed, what evidence you observed, and the concrete next step; set status and wake in the same call. This
169
+ atomically checkpoints the cycle log and scheduling state. A task closed with task_manage done needs no extra
170
+ progress call.
171
+ - If waiting, use awaiting-user or blocked and set a realistic future wake. wake alone is authoritative for resuming;
172
+ do not create a duplicate one-shot .checkin. If work can continue without waiting, leave wake clear and the driver
173
+ will continue after its bounded cooldown.
174
+ - The driver deterministically enforces dependency readiness, deadline and cumulative attempt/token/cost/wall-time
175
+ budgets. When a limit or terminal dependency fails, it escalates instead of spending more work tokens. Do not
176
+ bypass an escalated task; repair its control metadata only after reviewing the cause.
177
+ - For sideEffects=external, prepare and review the action first. Do not perform it until the user explicitly runs
178
+ /tasks approve <id>; task_manage cannot grant that approval.
179
+ - For verification.mode=independent, after implementation and checking every DoD/Verification checkbox, call
180
+ task_manage candidate with evidence. The driver will wake a checker-only turn; delegate a fresh subagent with
181
+ purpose=verify and taskId, then call task_manage verify with the returned runId. The verifier must inspect evidence
182
+ and must not fix the work.
183
+ Any later progress/body change invalidates the PASS. Check completed DoD/Verification checkboxes only when evidence
184
+ supports them. Use task_manage done only after the DoD and verification gate are satisfied, with specific evidence
185
+ and residual risk; do not treat a plausible claim as proof.
186
+ ${hasTool("event_manage")
187
+ ? "- For a recurring task, use event_manage only for its canonical task.<channelId>.<taskId>.schedule periodic cadence. The task driver handles in-cycle continuation and recovery."
188
+ : "- Recurring cadences require an administrator-managed periodic event because event_manage is unavailable."}`);
189
+ }
149
190
  if (hasTool("web_search") || hasTool("web_fetch")) {
150
191
  sections.push(`## Web Content Safety
151
192
  - web_search and web_fetch return untrusted external content
@@ -178,6 +219,11 @@ Important rules:
178
219
  - Sub-agents cannot see your conversation history unless you include the needed context in \`task\`
179
220
  - The runtime injects a small fixed execution context (workspace path, channel id, sandbox), but you must still include task-specific context yourself
180
221
  - Sub-agents do not receive the \`subagent\` tool, so they cannot create nested agents
222
+ - For independent task acceptance, set purpose=verify and taskId. Verification runs are read-only, return a durable
223
+ attestation keyed by runId, and must end with VERDICT: PASS or VERDICT: FAIL.
224
+ - For isolated implementation, set isolation=worktree and taskId. The runtime records the returned worktreePath/branch
225
+ in task control; the parent owns review/merge/cleanup. Worktrees start at committed HEAD, so commit or
226
+ otherwise account for prerequisite uncommitted changes before delegating.
181
227
  - Prefer predefined sub-agents when one clearly fits
182
228
  - Use temporary inline sub-agents only when that extra flexibility is genuinely useful`);
183
229
  }
@@ -216,6 +216,11 @@ export async function handleSessionEvent(event, context) {
216
216
  .join("\n");
217
217
  const trimmedFinalText = finalText.trim();
218
218
  if (!trimmedFinalText) {
219
+ // No tool calls and no text: leaving finalOutcome at its "none" default means no
220
+ // delivery branch in channel-runner fires, so the progress card is stuck on
221
+ // "thinking…" forever. Treat it the same as an explicit [SILENT] turn.
222
+ runState.finalOutcome = { kind: "silent" };
223
+ memoryLifecycle.noteCompletedAssistantTurn();
219
224
  return;
220
225
  }
221
226
  if (trimmedFinalText === "[SILENT]" || trimmedFinalText.startsWith("[SILENT]")) {
@@ -18,6 +18,8 @@ export interface AgentRunner {
18
18
  run(ctx: ChannelContext, store: ChannelStore): Promise<{
19
19
  stopReason: string;
20
20
  errorMessage?: string;
21
+ usage?: UsageTotals;
22
+ durationMs?: number;
21
23
  }>;
22
24
  handleBuiltinCommand(ctx: ChannelContext, command: BuiltInCommand): Promise<void>;
23
25
  queueSteer(text: string, userName?: string): Promise<void>;
@@ -488,6 +488,7 @@ function renderRecallResult(items, maxChars) {
488
488
  "Relevant context for this turn:",
489
489
  ];
490
490
  let usedChars = clippedLines.join("\n").length + "</runtime_context>".length + 2;
491
+ let includedCount = 0;
491
492
  for (const item of items) {
492
493
  const block = ["", `[${item.source}/${item.title}]`, `Path: ${item.path}`, item.content].join("\n");
493
494
  if (usedChars + block.length > maxChars) {
@@ -495,6 +496,11 @@ function renderRecallResult(items, maxChars) {
495
496
  }
496
497
  clippedLines.push("", `[${item.source}/${item.title}]`, `Path: ${item.path}`, item.content);
497
498
  usedChars += block.length;
499
+ includedCount++;
500
+ }
501
+ const omittedCount = items.length - includedCount;
502
+ if (omittedCount > 0) {
503
+ clippedLines.push("", `[- ${omittedCount} more item(s) omitted for length; use memory_manage search or session_search to look them up.]`);
498
504
  }
499
505
  clippedLines.push("</runtime_context>");
500
506
  return clippedLines.join("\n");
@@ -17,6 +17,23 @@ function relativeWake(wakeMs, now) {
17
17
  function renderLine(entry, now) {
18
18
  const status = entry.frontmatter.readable ? (entry.frontmatter.status ?? "open") : "⚠ unreadable frontmatter";
19
19
  const parts = [`${entry.id} — ${entry.title}`, status, relativeWake(entry.wakeMs, now)];
20
+ const control = entry.frontmatter.control;
21
+ if (control) {
22
+ parts.push(`priority ${control.priority}`);
23
+ parts.push(`attempt ${control.usage.attempts}/${control.budget.maxAttempts}`);
24
+ parts.push(`verify ${control.verification.mode}/${control.verification.status}`);
25
+ if (control.isolation !== "shared")
26
+ parts.push(`isolation ${control.isolation}`);
27
+ if (control.sideEffects !== "workspace") {
28
+ parts.push(`effects ${control.sideEffects}/${control.externalApproval}`);
29
+ }
30
+ if (control.deadline)
31
+ parts.push(`deadline ${control.deadline}`);
32
+ if (control.dependsOn.length > 0)
33
+ parts.push(`depends ${control.dependsOn.join(",")}`);
34
+ if (control.nextAction)
35
+ parts.push(`next ${control.nextAction}`);
36
+ }
20
37
  if (entry.latestNote) {
21
38
  const note = entry.latestNote.length > 80 ? `${entry.latestNote.slice(0, 79)}…` : entry.latestNote;
22
39
  parts.push(note);
@@ -2,6 +2,10 @@ import type { Api, Model } from "@earendil-works/pi-ai";
2
2
  import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
3
3
  /**
4
4
  * Resolve an API key for the given model's provider.
5
- * Checks ModelRegistry first, then falls back to ANTHROPIC_API_KEY.
5
+ * `ModelRegistry.getApiKeyForProvider` already checks that provider's own environment
6
+ * variable (e.g. OPENAI_API_KEY, GEMINI_API_KEY) internally, so a miss here means no
7
+ * credentials exist for this provider anywhere. Only fall back to ANTHROPIC_API_KEY when
8
+ * the model itself is Anthropic — falling back for other providers would silently send an
9
+ * Anthropic key to e.g. OpenAI and fail with a confusing 401.
6
10
  */
7
11
  export declare function getApiKeyForModel(modelRegistry: ModelRegistry, model: Model<Api>): Promise<string>;
@@ -1,15 +1,21 @@
1
1
  /**
2
2
  * Resolve an API key for the given model's provider.
3
- * Checks ModelRegistry first, then falls back to ANTHROPIC_API_KEY.
3
+ * `ModelRegistry.getApiKeyForProvider` already checks that provider's own environment
4
+ * variable (e.g. OPENAI_API_KEY, GEMINI_API_KEY) internally, so a miss here means no
5
+ * credentials exist for this provider anywhere. Only fall back to ANTHROPIC_API_KEY when
6
+ * the model itself is Anthropic — falling back for other providers would silently send an
7
+ * Anthropic key to e.g. OpenAI and fail with a confusing 401.
4
8
  */
5
9
  export async function getApiKeyForModel(modelRegistry, model) {
6
10
  const key = await modelRegistry.getApiKeyForProvider(model.provider);
7
11
  if (key) {
8
12
  return key;
9
13
  }
10
- const envKey = process.env.ANTHROPIC_API_KEY;
11
- if (envKey) {
12
- return envKey;
14
+ if (model.provider === "anthropic") {
15
+ const envKey = process.env.ANTHROPIC_API_KEY;
16
+ if (envKey) {
17
+ return envKey;
18
+ }
13
19
  }
14
20
  throw new Error(`No API key found for provider: ${model.provider}.\n\n` +
15
21
  "Configure credentials in ~/.pi/pipiclaw/auth.json or ~/.pi/pipiclaw/models.json, or set the matching provider environment variable.");
@@ -67,6 +67,11 @@ interface RuntimeContextOptions {
67
67
  stop(): void;
68
68
  };
69
69
  memoryMaintenanceSchedulerIntervalMs?: number;
70
+ createTaskDriver?: () => {
71
+ start(): void;
72
+ stop(): void;
73
+ };
74
+ taskDriverIntervalMs?: number;
70
75
  startServices?: boolean;
71
76
  registerSignalHandlers?: boolean;
72
77
  }
@@ -12,16 +12,20 @@ import { createExecutor, parseSandboxArg, SandboxConfigError, validateSandbox, }
12
12
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
13
13
  import { PipiclawSettingsManager } from "../settings.js";
14
14
  import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
15
+ import { readActiveTasks } from "../shared/task-ledger.js";
16
+ import { finishTaskAttempt } from "../tasks/store.js";
15
17
  import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
16
18
  import { getUsageLedger } from "../usage/ledger.js";
17
19
  import { parseUsageMode, renderUsageReport } from "../usage/render.js";
18
20
  import { ensureChannelDir, getChannelDir } from "./channel-paths.js";
19
21
  import { createDingTalkContext } from "./delivery.js";
20
22
  import { DingTalkBot, isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, } from "./dingtalk.js";
23
+ import { DurableDispatchService } from "./durable-dispatch.js";
21
24
  import { handleEventsCommand as runEventsCommand } from "./event-commands.js";
22
25
  import { createEventsWatcher } from "./events.js";
23
26
  import { ChannelStore } from "./store.js";
24
- import { handleTasksCommand as runTasksCommand } from "./task-commands.js";
27
+ import { pauseTask, handleTasksCommand as runTasksCommand } from "./task-commands.js";
28
+ import { createTaskDriverEvent, TaskDriver } from "./task-driver.js";
25
29
  const DEFAULT_SOUL = `# SOUL.md
26
30
 
27
31
  Configure Pipiclaw's identity, voice, and communication style here.
@@ -409,6 +413,7 @@ export function createRuntimeContext(options) {
409
413
  const cliVersion = readCliVersion();
410
414
  const channelStates = new Map();
411
415
  const activeTasks = new Set();
416
+ let durableDispatch;
412
417
  let shuttingDown = false;
413
418
  let shutdownPromise = null;
414
419
  const archiveIncomingMessage = async (channelId, message, contextLabel) => {
@@ -446,6 +451,15 @@ export function createRuntimeContext(options) {
446
451
  const state = channelStates.get(channelId);
447
452
  if (state?.running) {
448
453
  state.stopRequested = true;
454
+ const taskId = /^\[TASK_DRIVER:([A-Za-z0-9._-]+)\]/.exec(state.currentTaskText ?? "")?.[1];
455
+ if (taskId) {
456
+ const pauseResult = await pauseTask({
457
+ args: "",
458
+ channelDir: getChannelDir(options.paths.workspaceDir, channelId),
459
+ approver: "user via /stop",
460
+ }, taskId);
461
+ log.logInfo(`[${channelId}] ${pauseResult}`);
462
+ }
449
463
  _bot.discardCard(channelId);
450
464
  // Drop queued-but-not-started messages so a burst does not keep
451
465
  // running after the user asked to halt; abort the in-flight one.
@@ -471,6 +485,16 @@ export function createRuntimeContext(options) {
471
485
  const response = await runTasksCommand({
472
486
  args,
473
487
  channelDir: getChannelDir(options.paths.workspaceDir, event.channelId),
488
+ workspaceDir: options.paths.workspaceDir,
489
+ channelId: event.channelId,
490
+ approver: event.userName && event.userName !== event.user ? `${event.userName} (${event.user})` : event.user,
491
+ dispatchTask: async (id) => {
492
+ const channelDir = getChannelDir(options.paths.workspaceDir, event.channelId);
493
+ const entry = (await readActiveTasks(join(channelDir, "tasks"))).find((candidate) => candidate.id === id);
494
+ return entry
495
+ ? (durableDispatch?.dispatch(createTaskDriverEvent(event.channelId, entry, Date.now())) ?? false)
496
+ : false;
497
+ },
474
498
  });
475
499
  await bot.sendPlain(event.channelId, response);
476
500
  },
@@ -545,6 +569,7 @@ export function createRuntimeContext(options) {
545
569
  // routed as a fresh run instead of a steer/follow-up.
546
570
  state.running = true;
547
571
  state.stopRequested = false;
572
+ await durableDispatch?.markStarted(event.dispatchId);
548
573
  const task = (async () => {
549
574
  try {
550
575
  await archiveIncomingMessage(event.channelId, {
@@ -584,6 +609,16 @@ export function createRuntimeContext(options) {
584
609
  ctx.primeCard(350);
585
610
  }
586
611
  const result = await state.runner.run(ctx, store);
612
+ const taskDriverMatch = /^\[TASK_DRIVER:([A-Za-z0-9._-]+)\]/.exec(event.text);
613
+ if (taskDriverMatch?.[1] && result.usage && result.durationMs !== undefined) {
614
+ await finishTaskAttempt(getChannelDir(options.paths.workspaceDir, event.channelId), taskDriverMatch[1], {
615
+ tokens: result.usage.total,
616
+ costUsd: result.usage.cost.total,
617
+ wallTimeMinutes: result.durationMs / 60_000,
618
+ failed: result.stopReason === "error" || result.stopReason === "aborted",
619
+ finishedAt: new Date(),
620
+ });
621
+ }
587
622
  if (result.stopReason === "aborted" && state.stopRequested) {
588
623
  log.logInfo(`[${event.channelId}] Stopped`);
589
624
  }
@@ -592,6 +627,7 @@ export function createRuntimeContext(options) {
592
627
  log.logWarning(`[${event.channelId}] Run error`, err instanceof Error ? err.message : String(err));
593
628
  }
594
629
  finally {
630
+ await durableDispatch?.markCompleted(event.dispatchId);
595
631
  state.running = false;
596
632
  state.currentTaskText = undefined;
597
633
  }
@@ -608,10 +644,14 @@ export function createRuntimeContext(options) {
608
644
  const bot = options.createBot
609
645
  ? options.createBot(handler, options.dingtalkConfig)
610
646
  : new DingTalkBot(handler, options.dingtalkConfig);
647
+ durableDispatch = new DurableDispatchService({
648
+ stateDir: join(options.paths.appHomeDir, "state", "dispatch"),
649
+ bot,
650
+ });
611
651
  const executor = createExecutor(options.sandbox);
612
652
  const eventsWatcher = options.createEventsWatcher
613
653
  ? options.createEventsWatcher(options.paths.workspaceDir, bot, executor, options.paths.eventHistoryPath)
614
- : createEventsWatcher(options.paths.workspaceDir, bot, executor, loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config.commandGuard, options.paths.eventHistoryPath);
654
+ : createEventsWatcher(options.paths.workspaceDir, bot, executor, loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config.commandGuard, options.paths.eventHistoryPath, (event) => durableDispatch?.dispatch(event) ?? false);
615
655
  const memoryMaintenanceScheduler = options.createMemoryMaintenanceScheduler
616
656
  ? options.createMemoryMaintenanceScheduler()
617
657
  : new MemoryMaintenanceScheduler({
@@ -631,6 +671,19 @@ export function createRuntimeContext(options) {
631
671
  },
632
672
  intervalMs: options.memoryMaintenanceSchedulerIntervalMs,
633
673
  });
674
+ const taskDriver = options.createTaskDriver
675
+ ? options.createTaskDriver()
676
+ : new TaskDriver({
677
+ workspaceDir: options.paths.workspaceDir,
678
+ getKnownChannelIds: () => channelStates.keys(),
679
+ isChannelActive: (channelId) => channelStates.get(channelId)?.running ?? false,
680
+ dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
681
+ getSettings: () => {
682
+ runtimeSettingsManager.reload();
683
+ return runtimeSettingsManager.getTaskDriverSettings();
684
+ },
685
+ intervalMs: options.taskDriverIntervalMs,
686
+ });
634
687
  const shutdownWithReason = async (reason = "manual") => {
635
688
  if (shutdownPromise) {
636
689
  return shutdownPromise;
@@ -638,6 +691,8 @@ export function createRuntimeContext(options) {
638
691
  shutdownPromise = (async () => {
639
692
  shuttingDown = true;
640
693
  log.logInfo(`Shutting down (${reason})...`);
694
+ taskDriver.stop();
695
+ durableDispatch?.stop();
641
696
  memoryMaintenanceScheduler.stop();
642
697
  eventsWatcher.stop();
643
698
  await bot.stop();
@@ -701,6 +756,8 @@ export function createRuntimeContext(options) {
701
756
  if (startServices) {
702
757
  eventsWatcher.start();
703
758
  memoryMaintenanceScheduler.start();
759
+ taskDriver.start();
760
+ durableDispatch.start();
704
761
  void bot.start();
705
762
  }
706
763
  return {
@@ -29,6 +29,8 @@ export interface DingTalkEvent {
29
29
  text: string;
30
30
  conversationId: string;
31
31
  conversationType: string;
32
+ /** Runtime-owned durable-dispatch record, absent for normal inbound messages. */
33
+ dispatchId?: string;
32
34
  }
33
35
  export type BusyMessageResult = {
34
36
  kind: "handled";
@@ -110,6 +110,12 @@ const DINGTALK_API = "https://api.dingtalk.com";
110
110
  // (discardCard / replay / sendPlain) already handle.
111
111
  const DINGTALK_HTTP_TIMEOUT_MS = 15_000;
112
112
  const http = axios.create({ timeout: DINGTALK_HTTP_TIMEOUT_MS });
113
+ // Bounds enqueueStreamMessage (user messages + busy-message requeues), mirroring the
114
+ // existing cap on enqueueEvent. Without a limit, a busy channel getting flooded with
115
+ // messages (or repeated followUp requeues) grows this queue without bound — each item
116
+ // still runs a full serialized turn, so an unbounded queue means unbounded backlog time
117
+ // and unbounded memory, not just a slow channel.
118
+ const USER_MESSAGE_QUEUE_LIMIT = 20;
113
119
  const TOKEN_REFRESH_SECS = 90 * 60; // 1.5 hours (tokens expire after 2 hours)
114
120
  const CONNECT_ATTEMPT_TIMEOUT_MS = 10_000;
115
121
  const SOCKET_CLOSE_GRACE_MS = 1_000;
@@ -560,7 +566,13 @@ export class DingTalkBot {
560
566
  }
561
567
  enqueueStreamMessage(event, textOverride) {
562
568
  const queuedEvent = textOverride === undefined ? event : { ...event, text: textOverride };
563
- this.getQueue(event.channelId).enqueue(async () => {
569
+ const queue = this.getQueue(event.channelId);
570
+ if (queue.size() >= USER_MESSAGE_QUEUE_LIMIT) {
571
+ log.logWarning(`Message queue full for ${event.channelId} (limit ${USER_MESSAGE_QUEUE_LIMIT}), discarding: ${queuedEvent.text.substring(0, 50)}`);
572
+ this.sendPlain(event.channelId, `⚠️ 消息积压过多(超过 ${USER_MESSAGE_QUEUE_LIMIT} 条待处理),本条消息已丢弃,请稍后重试。`).catch(() => undefined);
573
+ return;
574
+ }
575
+ queue.enqueue(async () => {
564
576
  this.activeMessageProcessing = true;
565
577
  try {
566
578
  await this.handler.handleEvent(queuedEvent, this);
@@ -0,0 +1,28 @@
1
+ import type { DingTalkBot, DingTalkEvent } from "./dingtalk.js";
2
+ export interface DurableDispatchOptions {
3
+ stateDir: string;
4
+ bot: Pick<DingTalkBot, "enqueueEvent">;
5
+ leaseMs?: number;
6
+ intervalMs?: number;
7
+ }
8
+ /**
9
+ * Tiny file-backed outbox for synthetic work. It intentionally provides
10
+ * at-least-once delivery: a crash after enqueue may replay a task/event, while
11
+ * a crash can no longer silently discard it merely because it left an in-memory
12
+ * channel queue.
13
+ */
14
+ export declare class DurableDispatchService {
15
+ private readonly options;
16
+ private readonly queue;
17
+ private readonly leaseMs;
18
+ private timer;
19
+ constructor(options: DurableDispatchOptions);
20
+ start(): void;
21
+ stop(): void;
22
+ dispatch(event: DingTalkEvent): Promise<boolean>;
23
+ markStarted(id: string | undefined): Promise<void>;
24
+ markCompleted(id: string | undefined): Promise<void>;
25
+ drainOnce(now?: number): Promise<void>;
26
+ private read;
27
+ private write;
28
+ }