@oyasmi/pipiclaw 0.8.8 → 0.8.9-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +8 -3
  2. package/dist/agent/channel-runner.d.ts +1 -0
  3. package/dist/agent/channel-runner.js +3 -2
  4. package/dist/agent/effect-ledger.d.ts +11 -0
  5. package/dist/agent/effect-ledger.js +42 -0
  6. package/dist/agent/job-manager.d.ts +90 -13
  7. package/dist/agent/job-manager.js +235 -20
  8. package/dist/agent/prompt/sections.js +11 -2
  9. package/dist/agent/prompt/types.d.ts +7 -1
  10. package/dist/agent/runner-factory.d.ts +7 -0
  11. package/dist/agent/session-events.js +20 -1
  12. package/dist/index.d.ts +1 -1
  13. package/dist/log.d.ts +6 -0
  14. package/dist/log.js +12 -0
  15. package/dist/memory/consolidation.d.ts +5 -0
  16. package/dist/memory/consolidation.js +35 -147
  17. package/dist/memory/extraction.d.ts +45 -0
  18. package/dist/memory/extraction.js +227 -0
  19. package/dist/memory/lifecycle.js +5 -0
  20. package/dist/memory/maintenance-jobs.js +7 -0
  21. package/dist/memory/post-turn-review.d.ts +3 -1
  22. package/dist/memory/post-turn-review.js +20 -189
  23. package/dist/memory/recall.d.ts +0 -1
  24. package/dist/memory/recall.js +135 -77
  25. package/dist/memory/sidecar-worker.d.ts +7 -0
  26. package/dist/memory/sidecar-worker.js +23 -5
  27. package/dist/memory/task-digest.js +1 -1
  28. package/dist/paths.d.ts +1 -0
  29. package/dist/paths.js +11 -0
  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 +1 -1
  37. package/dist/playbooks/task-closeout.md +12 -11
  38. package/dist/playbooks/task-delegation.md +11 -5
  39. package/dist/playbooks/task-driving.md +54 -21
  40. package/dist/playbooks/task-planning.md +46 -19
  41. package/dist/runtime/bootstrap.js +29 -4
  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/store.d.ts +1 -1
  52. package/dist/runtime/task-commands.js +29 -51
  53. package/dist/runtime/task-driver.d.ts +5 -8
  54. package/dist/runtime/task-driver.js +120 -93
  55. package/dist/runtime/task-migration.d.ts +11 -0
  56. package/dist/runtime/task-migration.js +70 -0
  57. package/dist/settings.d.ts +11 -0
  58. package/dist/settings.js +12 -0
  59. package/dist/shared/recoverable-error.d.ts +26 -0
  60. package/dist/shared/recoverable-error.js +29 -0
  61. package/dist/shared/task-events.d.ts +0 -26
  62. package/dist/shared/task-events.js +0 -15
  63. package/dist/shared/task-ledger.d.ts +32 -8
  64. package/dist/shared/task-ledger.js +66 -17
  65. package/dist/subagents/builtin/explorer.md +16 -0
  66. package/dist/subagents/builtin/researcher.md +17 -0
  67. package/dist/subagents/builtin/verifier.md +17 -0
  68. package/dist/subagents/discovery.d.ts +17 -3
  69. package/dist/subagents/discovery.js +88 -15
  70. package/dist/subagents/tool.d.ts +21 -1
  71. package/dist/subagents/tool.js +140 -12
  72. package/dist/tasks/control.d.ts +4 -0
  73. package/dist/tasks/control.js +3 -0
  74. package/dist/tasks/store.d.ts +28 -1
  75. package/dist/tasks/store.js +63 -6
  76. package/dist/tasks/transitions.d.ts +40 -0
  77. package/dist/tasks/transitions.js +82 -0
  78. package/dist/tools/bash.d.ts +2 -0
  79. package/dist/tools/bash.js +18 -5
  80. package/dist/tools/event-manage.js +28 -77
  81. package/dist/tools/index.d.ts +4 -0
  82. package/dist/tools/index.js +7 -2
  83. package/dist/tools/job.js +2 -2
  84. package/dist/tools/memory-manage.js +0 -1
  85. package/dist/tools/registry.d.ts +29 -8
  86. package/dist/tools/registry.js +39 -22
  87. package/dist/tools/send-media.d.ts +28 -0
  88. package/dist/tools/send-media.js +88 -0
  89. package/dist/tools/task-manage/create.d.ts +2 -0
  90. package/dist/tools/task-manage/create.js +35 -0
  91. package/dist/tools/task-manage/lifecycle.d.ts +6 -0
  92. package/dist/tools/task-manage/lifecycle.js +197 -0
  93. package/dist/tools/task-manage/schema.d.ts +43 -0
  94. package/dist/tools/task-manage/schema.js +90 -0
  95. package/dist/tools/task-manage/shared.d.ts +36 -0
  96. package/dist/tools/task-manage/shared.js +247 -0
  97. package/dist/tools/task-manage/types.d.ts +53 -0
  98. package/dist/tools/task-manage/types.js +1 -0
  99. package/dist/tools/task-manage/verification.d.ts +16 -0
  100. package/dist/tools/task-manage/verification.js +112 -0
  101. package/dist/tools/task-manage.d.ts +9 -89
  102. package/dist/tools/task-manage.js +8 -696
  103. package/dist/tools/tool-details.d.ts +44 -0
  104. package/dist/tools/tool-details.js +62 -0
  105. package/dist/tui/app.js +2 -0
  106. package/dist/tui/terminal-media-sender.d.ts +9 -0
  107. package/dist/tui/terminal-media-sender.js +15 -0
  108. package/package.json +2 -2
  109. package/dist/playbooks/task-recurring.md +0 -41
  110. 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
 
@@ -234,15 +234,20 @@ pipiclaw
234
234
 
235
235
  ## 文档地图(Documentation)
236
236
 
237
+ 完整索引见 **[docs/README.md](./docs/README.md)**(按使用者 / 管理员 / 开发者分组)。常用入口:
238
+
237
239
  | 文档 | 内容 |
238
240
  |------|------|
241
+ | [docs/tools.md](./docs/tools.md) | 工具总览:每个能力做什么、开关在哪、子代理是否可用 |
242
+ | [docs/memory.md](./docs/memory.md) | 记忆分层:它记得什么、怎么让它记住或忘掉 |
239
243
  | [docs/configuration.md](./docs/configuration.md) | 全部配置项:钉钉、模型、settings、tools、TUI、记忆与工作区文件 |
240
244
  | [docs/events-and-tasks.md](./docs/events-and-tasks.md) | 定时事件(含 `preAction` 门控、`event_manage`)、任务台账、内建 task driver、`/tasks` 控制面与 `task_manage` 工具 |
241
245
  | [docs/sub-agents.md](./docs/sub-agents.md) | 预定义子代理:委派、隔离 worktree 与独立验收 |
242
- | [docs/runtime-playbooks.md](./docs/runtime-playbooks.md) | Runtime playbooks 与知识分层模型 |
246
+ | [docs/security.md](./docs/security.md) | 默认安全策略、`security.json` 配置与已知边界 |
243
247
  | [docs/deployment-and-operations.md](./docs/deployment-and-operations.md) | 长期运行、日志、可观测性、升级、备份与排障 |
244
248
  | [docs/scaling-and-concurrency.md](./docs/scaling-and-concurrency.md) | 并发模型与容量边界 |
245
- | [docs/security.md](./docs/security.md) | 默认安全策略、`security.json` 配置与已知边界 |
249
+ | [docs/architecture.md](./docs/architecture.md) | as-implemented 架构:运行时拓扑、消息生命周期、并发表、磁盘布局 |
250
+ | [docs/runtime-playbooks.md](./docs/runtime-playbooks.md) | Runtime playbooks 与知识分层模型 |
246
251
 
247
252
  ## 开发(Development)
248
253
 
@@ -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;
@@ -24,7 +24,6 @@ import { isRecord } from "../shared/type-guards.js";
24
24
  import { discoverSubAgents } from "../subagents/discovery.js";
25
25
  import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
26
26
  import { createPipiclawTools } from "../tools/index.js";
27
- import { TOOL_PROMPT_HINTS } from "../tools/registry.js";
28
27
  import { getUsageLedger } from "../usage/ledger.js";
29
28
  import { createCommandExtension } from "./command-extension.js";
30
29
  import { isKnownCommandName, renderBuiltInHelp, slashCommandName } from "./commands.js";
@@ -75,6 +74,7 @@ export class ChannelRunner {
75
74
  this.authConfigPath = paths.authConfigPath;
76
75
  this.modelsConfigPath = paths.modelsConfigPath;
77
76
  this.onSessionEvent = paths.onSessionEvent;
77
+ this.mediaSender = paths.mediaSender;
78
78
  const executor = createExecutor();
79
79
  this.executor = executor;
80
80
  this.workspaceDir = resolve(dirname(channelDir));
@@ -865,7 +865,6 @@ export class ChannelRunner {
865
865
  tools: this.currentTools.map((tool) => ({
866
866
  name: tool.name,
867
867
  description: tool.description,
868
- hint: TOOL_PROMPT_HINTS[tool.name],
869
868
  })),
870
869
  soul: resources.soul,
871
870
  agents: resources.agents,
@@ -997,10 +996,12 @@ export class ChannelRunner {
997
996
  channelId: this.channelId,
998
997
  getSubAgentDiscovery: () => this.subAgentDiscovery,
999
998
  getMemoryRecallSettings: () => this.settingsManager.getMemoryRecallSettings(),
999
+ getSubAgentModelReference: () => this.settingsManager.getSubAgentModelReference(),
1000
1000
  getSessionSearchSettings: () => this.settingsManager.getSessionSearchSettings(),
1001
1001
  memoryCandidateStore: this.memoryCandidateStore,
1002
1002
  securityConfig: securityLoad.config,
1003
1003
  toolsConfig: toolsLoad.config,
1004
+ mediaSender: this.mediaSender,
1004
1005
  });
1005
1006
  this.currentTools = tools;
1006
1007
  return tools;
@@ -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 {};
@@ -1,7 +1,11 @@
1
1
  import { randomBytes } from "node:crypto";
2
+ import { chmod, mkdir, readdir, readFile, unlink } from "node:fs/promises";
3
+ import { join } from "node:path";
2
4
  import * as log from "../log.js";
5
+ import { writeFileAtomically } from "../shared/atomic-file.js";
3
6
  import { shellEscape } from "../shared/shell-escape.js";
4
7
  import { errorMessage } from "../shared/text-utils.js";
8
+ import { isRecord } from "../shared/type-guards.js";
5
9
  /** Cap on concurrently running jobs per channel, so a runaway model can't spawn unbounded processes. */
6
10
  export const MAX_RUNNING_JOBS = 5;
7
11
  /** Longest a single `poll` call blocks before returning a snapshot; the model can poll again. */
@@ -11,13 +15,39 @@ const POLL_CHECK_INTERVAL_MS = 3_000;
11
15
  * How often the internal sweeper refreshes running jobs while any are alive. Without it, a job that
12
16
  * finishes (or overruns its timeout) is only reaped when the model happens to call list/poll/cancel —
13
17
  * so a never-polled job would hold a `MAX_RUNNING_JOBS` slot forever, eventually blocking all `async`.
14
- * The sweep only reconciles in-memory state (and enforces the hard timeout); it never wakes the
15
- * channel, so it stays within the design's "no automatic completion delivery" decision.
18
+ * It is also what makes completion wakes timely: the sweep is where a finished job is noticed, and
19
+ * therefore where it announces itself (spec 031, D6, which replaced the earlier "no automatic
20
+ * completion delivery" decision).
16
21
  */
17
22
  export const SWEEP_INTERVAL_MS = 10_000;
23
+ /**
24
+ * How long a finished job's record, spill file, and exit file are kept. The model has to be able
25
+ * to read the output after the completion wake, so they cannot be deleted the moment the job ends.
26
+ */
27
+ export const FINISHED_JOB_RETENTION_MS = 24 * 60 * 60_000;
28
+ /** Bytes of captured output carried inline in the completion wake. */
29
+ const WAKE_OUTPUT_TAIL_BYTES = 2_000;
18
30
  function jobSpillPath(id) {
19
31
  return `/tmp/pipiclaw-job-${id}.log`;
20
32
  }
33
+ function isTerminal(status) {
34
+ return status !== "running";
35
+ }
36
+ /** Accept a persisted record only if the fields the manager actually relies on are intact. */
37
+ function parseJobRecord(raw) {
38
+ const value = JSON.parse(raw);
39
+ if (!isRecord(value) ||
40
+ typeof value.id !== "string" ||
41
+ typeof value.pid !== "number" ||
42
+ typeof value.spillFile !== "string" ||
43
+ typeof value.exitFile !== "string" ||
44
+ typeof value.startedAt !== "number" ||
45
+ typeof value.timeoutSeconds !== "number" ||
46
+ !isRecord(value.contract)) {
47
+ return undefined;
48
+ }
49
+ return value;
50
+ }
21
51
  function sleep(ms, signal) {
22
52
  return new Promise((resolve) => {
23
53
  const timer = setTimeout(resolve, ms);
@@ -39,12 +69,49 @@ function toSnapshot(record) {
39
69
  };
40
70
  }
41
71
  export class ChannelJobManager {
42
- constructor(channelId, executor, sweepIntervalMs = SWEEP_INTERVAL_MS) {
72
+ constructor(channelId, executor, options = {}) {
43
73
  this.channelId = channelId;
44
74
  this.executor = executor;
45
- this.sweepIntervalMs = sweepIntervalMs;
46
75
  this.jobs = new Map();
47
76
  this.sweeping = false;
77
+ // A bare number keeps the original `sweepIntervalMs` positional form working for tests.
78
+ this.options = typeof options === "number" ? { sweepIntervalMs: options } : options;
79
+ this.sweepIntervalMs = this.options.sweepIntervalMs ?? SWEEP_INTERVAL_MS;
80
+ }
81
+ recordPath(id) {
82
+ return this.options.stateDir ? join(this.options.stateDir, `${id}.json`) : undefined;
83
+ }
84
+ /** Mirror a record to disk. Persistence is best-effort: it must never fail a job operation. */
85
+ async persist(record) {
86
+ const path = this.recordPath(record.id);
87
+ if (!path)
88
+ return;
89
+ try {
90
+ await writeFileAtomically(path, `${JSON.stringify(record)}\n`);
91
+ // The record carries the full command line, so keep it owner-only.
92
+ await chmod(path, 0o600).catch(() => undefined);
93
+ }
94
+ catch (error) {
95
+ log.logWarning(`Failed to persist background job ${record.id}`, errorMessage(error));
96
+ }
97
+ }
98
+ async forget(record) {
99
+ this.jobs.delete(record.id);
100
+ const path = this.recordPath(record.id);
101
+ await Promise.all([path, record.spillFile, record.exitFile]
102
+ .filter((target) => Boolean(target))
103
+ .map((target) => unlink(target).catch(() => undefined)));
104
+ }
105
+ /**
106
+ * Drop finished jobs whose retention window has passed, together with their spill files.
107
+ * Called from the sweeper and from restore, so leftovers never outlive a daemon restart.
108
+ */
109
+ async collectGarbage(now = Date.now()) {
110
+ for (const record of Array.from(this.jobs.values())) {
111
+ if (isTerminal(record.status) && record.finishedAt && now - record.finishedAt >= FINISHED_JOB_RETENTION_MS) {
112
+ await this.forget(record);
113
+ }
114
+ }
48
115
  }
49
116
  get channel() {
50
117
  return this.channelId;
@@ -57,7 +124,7 @@ export class ChannelJobManager {
57
124
  * stdout/stderr to a spill file and the command's exit code to a sibling `.exit` file, then
58
125
  * `echo $!` hands back the nohup PID for later probing/cancellation.
59
126
  */
60
- async start(command, label, timeoutSeconds, signal) {
127
+ async start(command, label, timeoutSeconds, options = {}) {
61
128
  if (this.runningCount() >= MAX_RUNNING_JOBS) {
62
129
  throw new Error(`Too many background jobs already running (>= ${MAX_RUNNING_JOBS}). Poll or cancel some with the job tool first.`);
63
130
  }
@@ -68,8 +135,12 @@ export class ChannelJobManager {
68
135
  // exit-capture line still runs; otherwise a command ending in `exit N` would skip it and the
69
136
  // job would look `lost` instead of finished.
70
137
  const inner = `( ${command} )\n__pc_rc=$?; echo "$__pc_rc" > ${shellEscape(exitFile)}`;
71
- const launch = `rm -f ${shellEscape(exitFile)}; nohup sh -c ${shellEscape(inner)} > ${shellEscape(spillFile)} 2>&1 & echo $!`;
72
- const result = await this.executor.exec(launch, { signal });
138
+ // `umask 077` first: the spill file holds whatever the command printed, which routinely
139
+ // includes credentials, and it is created in a world-readable /tmp. Setting the mask rather
140
+ // than chmod-ing afterwards leaves no window where the file is readable by others.
141
+ const launch = `umask 077; rm -f ${shellEscape(exitFile)}; ` +
142
+ `nohup sh -c ${shellEscape(inner)} > ${shellEscape(spillFile)} 2>&1 & echo $!`;
143
+ const result = await this.executor.exec(launch, { signal: options.signal });
73
144
  const pid = Number.parseInt(result.stdout.trim(), 10);
74
145
  if (!Number.isFinite(pid) || pid <= 0) {
75
146
  throw new Error(`Failed to start background job: ${result.stderr.trim() || "no PID returned"}`);
@@ -86,8 +157,10 @@ export class ChannelJobManager {
86
157
  spillFile,
87
158
  exitFile,
88
159
  timeoutSeconds,
160
+ contract: { notify: options.notify ?? true, ...(options.taskId ? { taskId: options.taskId } : {}) },
89
161
  };
90
162
  this.jobs.set(id, record);
163
+ await this.persist(record);
91
164
  this.ensureSweeper();
92
165
  return toSnapshot(record);
93
166
  }
@@ -124,6 +197,7 @@ export class ChannelJobManager {
124
197
  });
125
198
  }
126
199
  }
200
+ await this.collectGarbage();
127
201
  }
128
202
  finally {
129
203
  this.sweeping = false;
@@ -132,8 +206,14 @@ export class ChannelJobManager {
132
206
  }
133
207
  }
134
208
  }
135
- /** Refresh the status of a single running job by consulting its `.exit` file and liveness. */
136
- async refresh(record, signal) {
209
+ /**
210
+ * Refresh the status of a single running job by consulting its `.exit` file and liveness.
211
+ *
212
+ * `announce` is false only on the `poll` path, which hands the model the finished job's output
213
+ * inline: waking the channel for a result the model is already holding would burn a whole turn
214
+ * to say nothing.
215
+ */
216
+ async refresh(record, signal, announce = true) {
137
217
  if (record.status !== "running") {
138
218
  return;
139
219
  }
@@ -144,22 +224,70 @@ export class ChannelJobManager {
144
224
  if (out.startsWith("EXIT:")) {
145
225
  const code = Number.parseInt(out.slice("EXIT:".length).trim(), 10);
146
226
  record.exitCode = Number.isFinite(code) ? code : undefined;
147
- record.status = code === 0 ? "completed" : "failed";
148
- record.durationMs = Date.now() - record.startedAt;
227
+ await this.finish(record, code === 0 ? "completed" : "failed", signal, announce);
149
228
  return;
150
229
  }
151
230
  if (out === "GONE") {
152
- // Process vanished without writing an exit code (killed externally, or manager restarted).
153
- record.status = "lost";
154
- record.durationMs = Date.now() - record.startedAt;
231
+ // Process vanished without writing an exit code (killed externally, or the host rebooted).
232
+ await this.finish(record, "lost", signal, announce);
155
233
  return;
156
234
  }
157
235
  // Still alive: enforce the wall-clock budget from JS so we do not depend on a `timeout` binary.
158
236
  if (Date.now() - record.startedAt > record.timeoutSeconds * 1000) {
159
237
  await this.kill(record, signal);
160
- record.status = "failed";
161
238
  record.exitCode = 124;
162
- record.durationMs = Date.now() - record.startedAt;
239
+ await this.finish(record, "failed", signal, announce);
240
+ }
241
+ }
242
+ /** Move a job to a terminal status: record it, persist it, and wake the channel once. */
243
+ async finish(record, status, signal, announce = true) {
244
+ record.status = status;
245
+ record.durationMs = Date.now() - record.startedAt;
246
+ record.finishedAt = Date.now();
247
+ if (!announce) {
248
+ // The caller is delivering this result to the model right now; mark it announced so no
249
+ // later sweep re-reports it.
250
+ record.notified = true;
251
+ }
252
+ await this.persist(record);
253
+ await this.announce(record, signal);
254
+ }
255
+ /**
256
+ * Wake the channel for a finished job. `notified` is persisted before anything else can run
257
+ * again, so a restart mid-announce cannot produce a second wake; the dispatch id is stable for
258
+ * the same reason (spec 031, D1).
259
+ */
260
+ async announce(record, signal) {
261
+ if (!this.options.dispatch || !record.contract.notify || record.notified) {
262
+ return;
263
+ }
264
+ record.notified = true;
265
+ await this.persist(record);
266
+ const output = await this.readOutput(record.id, signal);
267
+ const tail = output?.text.slice(-WAKE_OUTPUT_TAIL_BYTES).trim();
268
+ const exit = record.exitCode !== undefined ? `exit ${record.exitCode}` : record.status;
269
+ const seconds = Math.round(record.durationMs / 1000);
270
+ const belongsTo = record.contract.taskId ? ` It belongs to task ${record.contract.taskId}.` : "";
271
+ const event = {
272
+ type: this.channelId.startsWith("group_") ? "group" : "dm",
273
+ channelId: this.channelId,
274
+ user: "JOB",
275
+ userName: "JOB",
276
+ text: `[JOB:${record.id}] Background job "${record.label}" finished: ${record.status} (${exit}, ${seconds}s).${belongsTo} ` +
277
+ `Command: ${record.command}\n` +
278
+ `Output tail:\n${tail || "(no output)"}\n` +
279
+ `Full output: ${record.spillFile}\n` +
280
+ "Continue whatever was waiting on this job. If it needs no follow-up, respond with exactly [SILENT].",
281
+ ts: String(Date.now()),
282
+ conversationId: "",
283
+ conversationType: this.channelId.startsWith("group_") ? "2" : "1",
284
+ dispatchId: `job:${this.channelId}:${record.id}:done`,
285
+ };
286
+ try {
287
+ await this.options.dispatch(event);
288
+ }
289
+ catch (error) {
290
+ log.logWarning(`Failed to dispatch completion wake for job ${record.id}`, errorMessage(error));
163
291
  }
164
292
  }
165
293
  async kill(record, signal) {
@@ -187,8 +315,9 @@ export class ChannelJobManager {
187
315
  continue;
188
316
  }
189
317
  await this.kill(record, signal);
190
- record.status = "cancelled";
191
- record.durationMs = Date.now() - record.startedAt;
318
+ // An explicit cancel is the model's own decision, so it needs no wake to learn about it.
319
+ record.contract.notify = false;
320
+ await this.finish(record, "cancelled", signal);
192
321
  results.push({ id, status: "cancelled" });
193
322
  }
194
323
  return results;
@@ -209,7 +338,9 @@ export class ChannelJobManager {
209
338
  for (const id of watchIds()) {
210
339
  const record = this.jobs.get(id);
211
340
  if (record) {
212
- await this.refresh(record, signal);
341
+ // poll returns the finished job's output to the model inline, so it must not
342
+ // also queue a completion wake for the very same result.
343
+ await this.refresh(record, signal, false);
213
344
  }
214
345
  }
215
346
  const watched = watchIds()
@@ -222,6 +353,51 @@ export class ChannelJobManager {
222
353
  await sleep(POLL_CHECK_INTERVAL_MS, signal);
223
354
  }
224
355
  }
356
+ /**
357
+ * Rebuild in-memory state from `state/jobs/<channelId>/` after a restart.
358
+ *
359
+ * `nohup` processes outlive the daemon, so the records — not the process table — are what was
360
+ * lost. Re-adopting them makes a still-running job count toward the concurrency cap again,
361
+ * lets its output be retrieved, and lets its completion wake fire (late, but not never).
362
+ */
363
+ async restore(signal) {
364
+ const stateDir = this.options.stateDir;
365
+ if (!stateDir)
366
+ return 0;
367
+ let filenames;
368
+ try {
369
+ filenames = (await readdir(stateDir)).filter((name) => name.endsWith(".json"));
370
+ }
371
+ catch {
372
+ return 0;
373
+ }
374
+ let restored = 0;
375
+ for (const filename of filenames) {
376
+ const path = join(stateDir, filename);
377
+ let record;
378
+ try {
379
+ record = parseJobRecord(await readFile(path, "utf-8"));
380
+ }
381
+ catch {
382
+ record = undefined;
383
+ }
384
+ if (!record) {
385
+ log.logWarning(`Discarding unreadable background job record: ${filename}`);
386
+ await unlink(path).catch(() => undefined);
387
+ continue;
388
+ }
389
+ this.jobs.set(record.id, record);
390
+ restored++;
391
+ // One probe decides between "still running", "finished while we were down", and "gone";
392
+ // refresh already encodes all three, including the late completion wake.
393
+ await this.refresh(record, signal).catch((error) => {
394
+ log.logWarning(`Failed to reconcile background job ${record?.id}`, errorMessage(error));
395
+ });
396
+ }
397
+ await this.collectGarbage();
398
+ this.ensureSweeper();
399
+ return restored;
400
+ }
225
401
  /** Read the (possibly truncated) captured output of a finished or running job. */
226
402
  async readOutput(id, signal) {
227
403
  const record = this.jobs.get(id);
@@ -235,11 +411,50 @@ export class ChannelJobManager {
235
411
  // One manager per channel, shared across tool rebuilds so job records survive a resource reload —
236
412
  // mirrors the shared singletons used elsewhere in the runtime (e.g. the channel memory queue).
237
413
  const managers = new Map();
414
+ let runtimeConfig = {};
415
+ /**
416
+ * Give background jobs their persistence root and their way to wake a channel. Called once from
417
+ * bootstrap, before any turn runs; the tool layer builds managers lazily and picks this up.
418
+ */
419
+ export function configureJobRuntime(config) {
420
+ runtimeConfig = config;
421
+ }
238
422
  export function getChannelJobManager(channelId, executor) {
239
423
  let manager = managers.get(channelId);
240
424
  if (!manager) {
241
- manager = new ChannelJobManager(channelId, executor);
425
+ manager = new ChannelJobManager(channelId, executor, {
426
+ ...(runtimeConfig.jobsStateDir ? { stateDir: join(runtimeConfig.jobsStateDir, channelId) } : {}),
427
+ ...(runtimeConfig.dispatch ? { dispatch: runtimeConfig.dispatch } : {}),
428
+ });
242
429
  managers.set(channelId, manager);
243
430
  }
244
431
  return manager;
245
432
  }
433
+ /**
434
+ * Re-adopt every channel's persisted jobs at startup. Channels are discovered from the state
435
+ * directory itself, so a job survives even when its channel has had no traffic since the restart.
436
+ */
437
+ export async function restoreChannelJobs(executor) {
438
+ const jobsStateDir = runtimeConfig.jobsStateDir;
439
+ if (!jobsStateDir)
440
+ return 0;
441
+ let channelIds;
442
+ try {
443
+ await mkdir(jobsStateDir, { recursive: true });
444
+ channelIds = (await readdir(jobsStateDir, { withFileTypes: true }))
445
+ .filter((entry) => entry.isDirectory())
446
+ .map((entry) => entry.name);
447
+ }
448
+ catch (error) {
449
+ log.logWarning("Failed to scan persisted background jobs", errorMessage(error));
450
+ return 0;
451
+ }
452
+ let restored = 0;
453
+ for (const channelId of channelIds) {
454
+ restored += await getChannelJobManager(channelId, executor).restore();
455
+ }
456
+ if (restored > 0) {
457
+ log.logInfo(`Restored ${restored} background job record(s)`);
458
+ }
459
+ return restored;
460
+ }