@oyasmi/pipiclaw 0.7.4 → 0.7.6

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 (59) hide show
  1. package/README.md +5 -1
  2. package/dist/agent/channel-runner.js +14 -0
  3. package/dist/agent/commands.d.ts +1 -1
  4. package/dist/agent/commands.js +6 -0
  5. package/dist/agent/job-manager.d.ts +79 -0
  6. package/dist/agent/job-manager.js +241 -0
  7. package/dist/agent/prompt-builder.js +13 -4
  8. package/dist/memory/review-log.d.ts +1 -1
  9. package/dist/memory/task-digest.d.ts +21 -0
  10. package/dist/memory/task-digest.js +66 -0
  11. package/dist/runtime/bootstrap.js +13 -1
  12. package/dist/runtime/dingtalk.d.ts +1 -0
  13. package/dist/runtime/dingtalk.js +6 -2
  14. package/dist/runtime/event-commands.d.ts +5 -0
  15. package/dist/runtime/event-commands.js +2 -2
  16. package/dist/runtime/task-commands.d.ts +6 -0
  17. package/dist/runtime/task-commands.js +133 -0
  18. package/dist/settings.d.ts +7 -0
  19. package/dist/settings.js +13 -0
  20. package/dist/shared/task-ledger.d.ts +53 -0
  21. package/dist/shared/task-ledger.js +149 -0
  22. package/dist/tools/bash.d.ts +12 -0
  23. package/dist/tools/bash.js +67 -1
  24. package/dist/tools/config.d.ts +15 -0
  25. package/dist/tools/config.js +37 -0
  26. package/dist/tools/edit.js +0 -0
  27. package/dist/tools/event-manage.d.ts +35 -0
  28. package/dist/tools/event-manage.js +238 -0
  29. package/dist/tools/grep.d.ts +19 -0
  30. package/dist/tools/grep.js +262 -0
  31. package/dist/tools/index.js +5 -0
  32. package/dist/tools/job.d.ts +13 -0
  33. package/dist/tools/job.js +92 -0
  34. package/dist/tools/memory-manage.d.ts +24 -0
  35. package/dist/tools/memory-manage.js +150 -0
  36. package/dist/tools/read.js +103 -16
  37. package/dist/tools/registry.d.ts +7 -1
  38. package/dist/tools/registry.js +54 -17
  39. package/dist/tools/session-search.js +4 -1
  40. package/dist/tools/skill-manage.d.ts +12 -5
  41. package/dist/tools/skill-manage.js +113 -15
  42. package/dist/tools/task-manage.d.ts +43 -0
  43. package/dist/tools/task-manage.js +226 -0
  44. package/dist/tools/web-cache.d.ts +11 -0
  45. package/dist/tools/web-cache.js +62 -0
  46. package/dist/tools/web-fetch.d.ts +3 -0
  47. package/dist/tools/web-fetch.js +70 -5
  48. package/dist/tui/app.js +2 -0
  49. package/dist/tui/commands.d.ts +1 -0
  50. package/dist/tui/commands.js +3 -0
  51. package/dist/tui/turn-controller.d.ts +1 -0
  52. package/dist/tui/turn-controller.js +1 -0
  53. package/package.json +1 -1
  54. package/dist/tools/memory-save.d.ts +0 -16
  55. package/dist/tools/memory-save.js +0 -42
  56. package/dist/tools/skill-list.d.ts +0 -18
  57. package/dist/tools/skill-list.js +0 -86
  58. package/dist/tools/skill-view.d.ts +0 -13
  59. package/dist/tools/skill-view.js +0 -44
package/README.md CHANGED
@@ -24,7 +24,11 @@ npm package: [`@oyasmi/pipiclaw`](https://www.npmjs.com/package/@oyasmi/pipiclaw
24
24
  - 支持预定义子代理(sub-agent)和临时内联子代理(inline sub-agent)
25
25
  - 支持立即、单次、周期三类事件调度
26
26
  - 支持自定义模型提供方(provider)和模型(model)配置
27
- - 内建 `web_search` / `web_fetch`,支持联网搜索与网页抓取
27
+ - 内建 `web_search` / `web_fetch`,支持联网搜索与网页抓取;`web_fetch` 支持结果缓存与分页续读,长网页被截断后可直接续读、不重抓
28
+ - 内建 `grep` 结构化搜索工具:按文件分组、分页、token 有界的内容检索,优于裸 `bash grep`
29
+ - 支持后台作业:`bash async` + `job` 工具,长命令后台运行、不阻塞频道,可 poll / cancel
30
+ - 内建 `memory_manage` 记忆管理:按需保存 / 检索 / 忘记稳定记忆,写操作串行化,避免与后台整理竞态
31
+ - `read` 支持读取目录树与 PDF 文档(`pdftotext`)
28
32
  - 内建 `session_search`,可按需检索当前会话通道的冷存储历史
29
33
  - 内建 workspace skill 管理工具,可查看、创建和维护 `workspace/skills/`
30
34
  - 内置工具层安全防护:`bash` 命令守卫、文件路径守卫、敏感路径拒绝、阻断审计日志
@@ -9,6 +9,7 @@ import { getChannelMemoryPath } from "../memory/files.js";
9
9
  import { MemoryLifecycle } from "../memory/lifecycle.js";
10
10
  import { applyMemoryActivityToState, updateMemoryMaintenanceState, } from "../memory/maintenance-state.js";
11
11
  import { recallRelevantMemory } from "../memory/recall.js";
12
+ import { buildTaskDigest } from "../memory/task-digest.js";
12
13
  import { getApiKeyForModel } from "../models/api-keys.js";
13
14
  import { findExactModelReferenceMatch, formatModelReference, resolveInitialModel } from "../models/utils.js";
14
15
  import { createExecutor } from "../sandbox.js";
@@ -173,6 +174,7 @@ export class ChannelRunner {
173
174
  await mkdir(this.channelDir, { recursive: true });
174
175
  let promptText = preserveRawInput ? clippedInput : userMessage;
175
176
  let recalledContextText = "";
177
+ let taskDigestText = "";
176
178
  let durableMemoryBootstrapText = "";
177
179
  if (!preserveRawInput) {
178
180
  const recallSettings = this.settingsManager.getMemoryRecallSettings();
@@ -196,6 +198,17 @@ export class ChannelRunner {
196
198
  promptText = `${recall.renderedText}\n\n<user_message>\n${promptText}\n</user_message>`;
197
199
  }
198
200
  }
201
+ const taskDigestSettings = this.settingsManager.getTaskDigestSettings();
202
+ if (taskDigestSettings.enabled) {
203
+ taskDigestText = await buildTaskDigest({
204
+ channelDir: this.channelDir,
205
+ maxTasks: taskDigestSettings.maxTasks,
206
+ maxChars: taskDigestSettings.maxChars,
207
+ });
208
+ if (taskDigestText) {
209
+ promptText = `${taskDigestText}\n\n${promptText}`;
210
+ }
211
+ }
199
212
  if (this.firstTurnMemoryBootstrapPending) {
200
213
  durableMemoryBootstrapText = await this.buildFirstTurnMemoryBootstrap();
201
214
  if (durableMemoryBootstrapText) {
@@ -210,6 +223,7 @@ export class ChannelRunner {
210
223
  systemPrompt: this.agent.state.systemPrompt,
211
224
  messages: this.session.messages,
212
225
  durableMemoryBootstrap: durableMemoryBootstrapText || undefined,
226
+ taskDigest: taskDigestText || undefined,
213
227
  recalledContext: recalledContextText || undefined,
214
228
  newUserMessage: promptText,
215
229
  };
@@ -1,4 +1,4 @@
1
- export type BuiltInCommandName = "help" | "steer" | "followup" | "stop" | "events" | "status" | "usage";
1
+ export type BuiltInCommandName = "help" | "steer" | "followup" | "stop" | "events" | "tasks" | "status" | "usage";
2
2
  export interface BuiltInCommand {
3
3
  name: BuiltInCommandName;
4
4
  args: string;
@@ -24,6 +24,11 @@ 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
29
+ Example: \`/tasks\`
30
+ Example: \`/tasks show weekly-report\`
31
+ Example: \`/tasks archive\`
27
32
  - \`/status\`
28
33
  Show runtime status: run state, current model, context usage, uptime, version
29
34
  Example: \`/status\`
@@ -70,6 +75,7 @@ export function parseBuiltInCommand(text) {
70
75
  case "followup":
71
76
  case "stop":
72
77
  case "events":
78
+ case "tasks":
73
79
  case "status":
74
80
  case "usage":
75
81
  return { name: rawName, args, rawText };
@@ -0,0 +1,79 @@
1
+ import type { Executor } from "../sandbox.js";
2
+ /**
3
+ * Per-channel manager for background bash jobs. A long command that ran synchronously would hold
4
+ * 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.
8
+ *
9
+ * Jobs live entirely in the executor's world (host or Docker), managed through shell commands
10
+ * (`nohup` to launch, `kill -0` to probe, `kill` to cancel), so this works identically in both
11
+ * sandboxes with no in-process child handles. Manager state is in-memory and not persisted: after a
12
+ * process restart, prior jobs surface as `lost` rather than being falsely resurrected.
13
+ */
14
+ export type JobStatus = "running" | "completed" | "failed" | "cancelled" | "lost";
15
+ export interface JobSnapshot {
16
+ id: string;
17
+ label: string;
18
+ command: string;
19
+ status: JobStatus;
20
+ startedAt: number;
21
+ durationMs: number;
22
+ exitCode?: number;
23
+ }
24
+ /** Cap on concurrently running jobs per channel, so a runaway model can't spawn unbounded processes. */
25
+ export declare const MAX_RUNNING_JOBS = 5;
26
+ /** Longest a single `poll` call blocks before returning a snapshot; the model can poll again. */
27
+ export declare const POLL_WAIT_MS = 30000;
28
+ /**
29
+ * How often the internal sweeper refreshes running jobs while any are alive. Without it, a job that
30
+ * finishes (or overruns its timeout) is only reaped when the model happens to call list/poll/cancel —
31
+ * 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.
34
+ */
35
+ export declare const SWEEP_INTERVAL_MS = 10000;
36
+ export declare class ChannelJobManager {
37
+ private readonly channelId;
38
+ private readonly executor;
39
+ private readonly sweepIntervalMs;
40
+ private readonly jobs;
41
+ private sweepTimer?;
42
+ private sweeping;
43
+ constructor(channelId: string, executor: Executor, sweepIntervalMs?: number);
44
+ get channel(): string;
45
+ runningCount(): number;
46
+ /**
47
+ * Launch a command in the background and return its job id. The wrapper writes merged
48
+ * stdout/stderr to a spill file and the command's exit code to a sibling `.exit` file, then
49
+ * `echo $!` hands back the nohup PID for later probing/cancellation.
50
+ */
51
+ start(command: string, label: string, timeoutSeconds: number, signal?: AbortSignal): Promise<JobSnapshot>;
52
+ /**
53
+ * Start the low-frequency sweeper if it is not already running. It reaps finished/timed-out jobs
54
+ * so their slots free up even when the model never polls, and stops itself once nothing is running.
55
+ */
56
+ private ensureSweeper;
57
+ private stopSweeper;
58
+ private sweep;
59
+ /** Refresh the status of a single running job by consulting its `.exit` file and liveness. */
60
+ private refresh;
61
+ private kill;
62
+ list(signal?: AbortSignal): Promise<JobSnapshot[]>;
63
+ cancel(ids: string[], signal?: AbortSignal): Promise<Array<{
64
+ id: string;
65
+ status: JobStatus | "not_found";
66
+ }>>;
67
+ /**
68
+ * Wait until at least one watched job finishes or the wait window elapses, then return a
69
+ * snapshot. Returns immediately if a watched job is already finished. `ids` omitted watches all
70
+ * running jobs.
71
+ */
72
+ poll(ids: string[] | undefined, signal?: AbortSignal): Promise<JobSnapshot[]>;
73
+ /** Read the (possibly truncated) captured output of a finished or running job. */
74
+ readOutput(id: string, signal?: AbortSignal): Promise<{
75
+ spillFile: string;
76
+ text: string;
77
+ } | undefined>;
78
+ }
79
+ export declare function getChannelJobManager(channelId: string, executor: Executor): ChannelJobManager;
@@ -0,0 +1,241 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { shellEscape } from "../shared/shell-escape.js";
3
+ /** Cap on concurrently running jobs per channel, so a runaway model can't spawn unbounded processes. */
4
+ export const MAX_RUNNING_JOBS = 5;
5
+ /** Longest a single `poll` call blocks before returning a snapshot; the model can poll again. */
6
+ export const POLL_WAIT_MS = 30_000;
7
+ const POLL_CHECK_INTERVAL_MS = 3_000;
8
+ /**
9
+ * How often the internal sweeper refreshes running jobs while any are alive. Without it, a job that
10
+ * finishes (or overruns its timeout) is only reaped when the model happens to call list/poll/cancel —
11
+ * so a never-polled job would hold a `MAX_RUNNING_JOBS` slot forever, eventually blocking all `async`.
12
+ * The sweep only reconciles in-memory state (and enforces the hard timeout); it never wakes the
13
+ * channel, so it stays within the design's "no automatic completion delivery" decision.
14
+ */
15
+ export const SWEEP_INTERVAL_MS = 10_000;
16
+ function jobSpillPath(id) {
17
+ return `/tmp/pipiclaw-job-${id}.log`;
18
+ }
19
+ function sleep(ms, signal) {
20
+ return new Promise((resolve) => {
21
+ const timer = setTimeout(resolve, ms);
22
+ signal?.addEventListener("abort", () => {
23
+ clearTimeout(timer);
24
+ resolve();
25
+ }, { once: true });
26
+ });
27
+ }
28
+ function toSnapshot(record) {
29
+ return {
30
+ id: record.id,
31
+ label: record.label,
32
+ command: record.command,
33
+ status: record.status,
34
+ startedAt: record.startedAt,
35
+ durationMs: record.status === "running" ? Date.now() - record.startedAt : record.durationMs,
36
+ exitCode: record.exitCode,
37
+ };
38
+ }
39
+ export class ChannelJobManager {
40
+ constructor(channelId, executor, sweepIntervalMs = SWEEP_INTERVAL_MS) {
41
+ this.channelId = channelId;
42
+ this.executor = executor;
43
+ this.sweepIntervalMs = sweepIntervalMs;
44
+ this.jobs = new Map();
45
+ this.sweeping = false;
46
+ }
47
+ get channel() {
48
+ return this.channelId;
49
+ }
50
+ runningCount() {
51
+ return Array.from(this.jobs.values()).filter((job) => job.status === "running").length;
52
+ }
53
+ /**
54
+ * Launch a command in the background and return its job id. The wrapper writes merged
55
+ * stdout/stderr to a spill file and the command's exit code to a sibling `.exit` file, then
56
+ * `echo $!` hands back the nohup PID for later probing/cancellation.
57
+ */
58
+ async start(command, label, timeoutSeconds, signal) {
59
+ if (this.runningCount() >= MAX_RUNNING_JOBS) {
60
+ throw new Error(`Too many background jobs already running (>= ${MAX_RUNNING_JOBS}). Poll or cancel some with the job tool first.`);
61
+ }
62
+ const id = randomBytes(6).toString("hex");
63
+ const spillFile = jobSpillPath(id);
64
+ const exitFile = `${spillFile}.exit`;
65
+ // Run the user command inside a subshell so its own `exit` only leaves the subshell and the
66
+ // exit-capture line still runs; otherwise a command ending in `exit N` would skip it and the
67
+ // job would look `lost` instead of finished.
68
+ const inner = `( ${command} )\n__pc_rc=$?; echo "$__pc_rc" > ${shellEscape(exitFile)}`;
69
+ const launch = `rm -f ${shellEscape(exitFile)}; nohup sh -c ${shellEscape(inner)} > ${shellEscape(spillFile)} 2>&1 & echo $!`;
70
+ const result = await this.executor.exec(launch, { signal });
71
+ const pid = Number.parseInt(result.stdout.trim(), 10);
72
+ if (!Number.isFinite(pid) || pid <= 0) {
73
+ throw new Error(`Failed to start background job: ${result.stderr.trim() || "no PID returned"}`);
74
+ }
75
+ const now = Date.now();
76
+ const record = {
77
+ id,
78
+ label,
79
+ command,
80
+ status: "running",
81
+ startedAt: now,
82
+ durationMs: 0,
83
+ pid,
84
+ spillFile,
85
+ exitFile,
86
+ timeoutSeconds,
87
+ };
88
+ this.jobs.set(id, record);
89
+ this.ensureSweeper();
90
+ return toSnapshot(record);
91
+ }
92
+ /**
93
+ * Start the low-frequency sweeper if it is not already running. It reaps finished/timed-out jobs
94
+ * so their slots free up even when the model never polls, and stops itself once nothing is running.
95
+ */
96
+ ensureSweeper() {
97
+ if (this.sweepTimer || this.runningCount() === 0) {
98
+ return;
99
+ }
100
+ this.sweepTimer = setInterval(() => {
101
+ void this.sweep();
102
+ }, this.sweepIntervalMs);
103
+ // Do not keep the process alive just for the sweeper.
104
+ this.sweepTimer.unref?.();
105
+ }
106
+ stopSweeper() {
107
+ if (this.sweepTimer) {
108
+ clearInterval(this.sweepTimer);
109
+ this.sweepTimer = undefined;
110
+ }
111
+ }
112
+ async sweep() {
113
+ if (this.sweeping) {
114
+ return; // A prior sweep is still awaiting the executor; skip this tick.
115
+ }
116
+ this.sweeping = true;
117
+ try {
118
+ for (const record of this.jobs.values()) {
119
+ if (record.status === "running") {
120
+ await this.refresh(record).catch(() => { });
121
+ }
122
+ }
123
+ }
124
+ finally {
125
+ this.sweeping = false;
126
+ if (this.runningCount() === 0) {
127
+ this.stopSweeper();
128
+ }
129
+ }
130
+ }
131
+ /** Refresh the status of a single running job by consulting its `.exit` file and liveness. */
132
+ async refresh(record, signal) {
133
+ if (record.status !== "running") {
134
+ return;
135
+ }
136
+ // Read the exit-code file if present, and separately check whether the PID is still alive.
137
+ const probe = await this.executor.exec(`if [ -f ${shellEscape(record.exitFile)} ]; then echo "EXIT:$(cat ${shellEscape(record.exitFile)})"; ` +
138
+ `elif kill -0 ${record.pid} 2>/dev/null; then echo ALIVE; else echo GONE; fi`, { signal });
139
+ const out = probe.stdout.trim();
140
+ if (out.startsWith("EXIT:")) {
141
+ const code = Number.parseInt(out.slice("EXIT:".length).trim(), 10);
142
+ record.exitCode = Number.isFinite(code) ? code : undefined;
143
+ record.status = code === 0 ? "completed" : "failed";
144
+ record.durationMs = Date.now() - record.startedAt;
145
+ return;
146
+ }
147
+ if (out === "GONE") {
148
+ // Process vanished without writing an exit code (killed externally, or manager restarted).
149
+ record.status = "lost";
150
+ record.durationMs = Date.now() - record.startedAt;
151
+ return;
152
+ }
153
+ // Still alive: enforce the wall-clock budget from JS so we do not depend on a `timeout` binary.
154
+ if (Date.now() - record.startedAt > record.timeoutSeconds * 1000) {
155
+ await this.kill(record, signal);
156
+ record.status = "failed";
157
+ record.exitCode = 124;
158
+ record.durationMs = Date.now() - record.startedAt;
159
+ }
160
+ }
161
+ async kill(record, signal) {
162
+ await this.executor
163
+ .exec(`kill ${record.pid} 2>/dev/null; sleep 0.2; kill -9 ${record.pid} 2>/dev/null; true`, { signal })
164
+ .catch(() => { });
165
+ }
166
+ async list(signal) {
167
+ for (const record of this.jobs.values()) {
168
+ await this.refresh(record, signal);
169
+ }
170
+ return Array.from(this.jobs.values()).map(toSnapshot);
171
+ }
172
+ async cancel(ids, signal) {
173
+ const results = [];
174
+ for (const id of ids) {
175
+ const record = this.jobs.get(id);
176
+ if (!record) {
177
+ results.push({ id, status: "not_found" });
178
+ continue;
179
+ }
180
+ await this.refresh(record, signal);
181
+ if (record.status !== "running") {
182
+ results.push({ id, status: record.status });
183
+ continue;
184
+ }
185
+ await this.kill(record, signal);
186
+ record.status = "cancelled";
187
+ record.durationMs = Date.now() - record.startedAt;
188
+ results.push({ id, status: "cancelled" });
189
+ }
190
+ return results;
191
+ }
192
+ /**
193
+ * Wait until at least one watched job finishes or the wait window elapses, then return a
194
+ * snapshot. Returns immediately if a watched job is already finished. `ids` omitted watches all
195
+ * running jobs.
196
+ */
197
+ async poll(ids, signal) {
198
+ const deadline = Date.now() + POLL_WAIT_MS;
199
+ const watchIds = () => ids && ids.length > 0
200
+ ? ids.filter((id) => this.jobs.has(id))
201
+ : Array.from(this.jobs.values())
202
+ .filter((job) => job.status === "running")
203
+ .map((job) => job.id);
204
+ while (true) {
205
+ for (const id of watchIds()) {
206
+ const record = this.jobs.get(id);
207
+ if (record) {
208
+ await this.refresh(record, signal);
209
+ }
210
+ }
211
+ const watched = watchIds()
212
+ .map((id) => this.jobs.get(id))
213
+ .filter((record) => record !== undefined);
214
+ const anyDone = watched.some((record) => record.status !== "running");
215
+ if (watched.length === 0 || anyDone || Date.now() >= deadline || signal?.aborted) {
216
+ return watched.map(toSnapshot);
217
+ }
218
+ await sleep(POLL_CHECK_INTERVAL_MS, signal);
219
+ }
220
+ }
221
+ /** Read the (possibly truncated) captured output of a finished or running job. */
222
+ async readOutput(id, signal) {
223
+ const record = this.jobs.get(id);
224
+ if (!record) {
225
+ return undefined;
226
+ }
227
+ const result = await this.executor.exec(`cat ${shellEscape(record.spillFile)} 2>/dev/null || true`, { signal });
228
+ return { spillFile: record.spillFile, text: result.stdout };
229
+ }
230
+ }
231
+ // One manager per channel, shared across tool rebuilds so job records survive a resource reload —
232
+ // mirrors the shared singletons used elsewhere in the runtime (e.g. the channel memory queue).
233
+ const managers = new Map();
234
+ export function getChannelJobManager(channelId, executor) {
235
+ let manager = managers.get(channelId);
236
+ if (!manager) {
237
+ manager = new ChannelJobManager(channelId, executor);
238
+ managers.set(channelId, manager);
239
+ }
240
+ return manager;
241
+ }
@@ -81,7 +81,16 @@ You can schedule events that wake you up at specific times or when external thin
81
81
  ### Cron Format
82
82
  \`minute hour day-of-month month day-of-week\`
83
83
 
84
- ### Creating Events
84
+ ${hasTool("event_manage")
85
+ ? `### Creating Events
86
+ Prefer the event_manage tool to create, update, or delete your own scheduled events: it validates the payload on write (an invalid event would otherwise be silently dropped) and enforces the scheduling guards below. Editing the JSON files directly with the file tools still works but skips that validation.
87
+
88
+ ### Silent Completion
89
+ For periodic events where there's nothing to report, respond with just \`[SILENT]\`. This deletes the status message. Use this to avoid spam when periodic checks find nothing.
90
+
91
+ ### Limits
92
+ event_manage rejects self-triggering loops: no immediate events (do that work in the current turn), one-shot at least 2 minutes out, periodic no more often than every 30 minutes (5 minutes when it carries a preAction gate), and at most 50 event files. Name task-owned events \`task.<channelId>.<taskId>.<use>\` so they clean up together.`
93
+ : `### Creating Events
85
94
  Create a JSON file under \`${workspacePath}/events/\` with the appropriate event payload.
86
95
  Prefer the file tools for creating or editing the event file. Use shell commands only when they are the clearest option.
87
96
 
@@ -89,14 +98,14 @@ Prefer the file tools for creating or editing the event file. Use shell commands
89
98
  For periodic events where there's nothing to report, respond with just \`[SILENT]\`. This deletes the status message. Use this to avoid spam when periodic checks find nothing.
90
99
 
91
100
  ### Limits
92
- Maximum 5 events can be queued.`);
101
+ The scheduler ignores invalid files and de-duplicates by filename; keep the events directory tidy.`}`);
93
102
  const runtimeBehaviorLines = [
94
103
  "- The runtime may inject a small amount of relevant memory context from SESSION.md / MEMORY.md / HISTORY.md into a turn when it is clearly useful.",
95
104
  "- SESSION.md is the primary runtime-managed working-state artifact for current active work.",
96
105
  "- The runtime automatically consolidates channel MEMORY.md and HISTORY.md before compaction or session trimming, and sweeps durable facts into MEMORY.md in the background.",
97
106
  ];
98
- if (hasTool("memory_save")) {
99
- runtimeBehaviorLines.push("- When the user explicitly asks you to remember, prefer, default to, or stop doing something durable, call memory_save right away instead of waiting for background consolidation. Use it only for durable facts/preferences/decisions/constraints, not transient task state.");
107
+ if (hasTool("memory_manage")) {
108
+ runtimeBehaviorLines.push("- When the user explicitly asks you to remember, prefer, default to, or stop doing something durable, call memory_manage (op: save) right away instead of waiting for background consolidation. Use it only for durable facts/preferences/decisions/constraints, not transient task state.", "- When the user asks you to forget or drop something durable, use memory_manage (op: forget) rather than editing MEMORY.md directly, so the change serializes with background consolidation. To look something up mid-task, use memory_manage (op: search).", "- Do not use edit or write to change channel MEMORY.md or HISTORY.md directly; those files are runtime-managed and must go through memory_manage, which serializes with background consolidation.");
100
109
  }
101
110
  runtimeBehaviorLines.push("- Workspace MEMORY.md is not updated by normal runtime consolidation.", "- ENVIRONMENT.md is not normal conversational memory. Read it only when environment history or machine state matters.");
102
111
  const coldStorageLines = [
@@ -1,4 +1,4 @@
1
- export type MemoryReviewReason = "idle" | "compaction" | "new-session" | "shutdown" | "post-turn" | "session-refresh-job" | "durable-consolidation-job" | "growth-review-job" | "structural-maintenance-job";
1
+ export type MemoryReviewReason = "idle" | "compaction" | "new-session" | "shutdown" | "post-turn" | "session-refresh-job" | "durable-consolidation-job" | "growth-review-job" | "structural-maintenance-job" | "user-forget";
2
2
  export interface MemoryReviewLogEntry {
3
3
  timestamp: string;
4
4
  channelId: string;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Builds the `<task_agenda>` block injected into each main-agent turn (spec 020 §2).
3
+ *
4
+ * Unlike memory recall — which is relevance-gated because candidate memory can be large —
5
+ * the agenda is deterministic and always-on: the candidate set is a handful of task
6
+ * frontmatters, and the in-flight agenda is universally relevant to an agent that drives
7
+ * work across turns. The block is bounded (maxTasks / maxChars) and framed as background
8
+ * reference, not instruction, so it can never turn an unrelated user turn into task work.
9
+ */
10
+ export interface TaskDigestOptions {
11
+ /** The channel directory; tasks live in `<channelDir>/tasks/`. */
12
+ channelDir: string;
13
+ maxTasks: number;
14
+ maxChars: number;
15
+ now?: number;
16
+ }
17
+ /**
18
+ * Render the in-flight task agenda, or `""` when there is nothing actionable to show.
19
+ * Only status ≠ done tasks are included (a done periodic task is sleeping, not on the agenda).
20
+ */
21
+ export declare function buildTaskDigest(options: TaskDigestOptions): Promise<string>;
@@ -0,0 +1,66 @@
1
+ import { join } from "node:path";
2
+ import { readActiveTasks } from "../shared/task-ledger.js";
3
+ function relativeWake(wakeMs, now) {
4
+ if (wakeMs === undefined)
5
+ return "wake —";
6
+ const diffMs = wakeMs - now;
7
+ if (diffMs <= 0)
8
+ return "wake due";
9
+ const minutes = Math.round(diffMs / 60000);
10
+ if (minutes < 60)
11
+ return `wake ${minutes}m`;
12
+ const hours = Math.round(minutes / 60);
13
+ if (hours < 24)
14
+ return `wake ${hours}h`;
15
+ return `wake ${Math.round(hours / 24)}d`;
16
+ }
17
+ function renderLine(entry, now) {
18
+ const status = entry.frontmatter.readable ? (entry.frontmatter.status ?? "open") : "⚠ unreadable frontmatter";
19
+ const parts = [`${entry.id} — ${entry.title}`, status, relativeWake(entry.wakeMs, now)];
20
+ if (entry.latestNote) {
21
+ const note = entry.latestNote.length > 80 ? `${entry.latestNote.slice(0, 79)}…` : entry.latestNote;
22
+ parts.push(note);
23
+ }
24
+ return `- ${parts.join(" · ")}`;
25
+ }
26
+ /**
27
+ * Render the in-flight task agenda, or `""` when there is nothing actionable to show.
28
+ * Only status ≠ done tasks are included (a done periodic task is sleeping, not on the agenda).
29
+ */
30
+ export async function buildTaskDigest(options) {
31
+ const now = options.now ?? Date.now();
32
+ const tasksDir = join(options.channelDir, "tasks");
33
+ const all = await readActiveTasks(tasksDir, now);
34
+ // done periodic tasks are asleep; only non-done tasks form the agenda.
35
+ const agenda = all.filter((entry) => entry.frontmatter.status !== "done" || !entry.frontmatter.readable);
36
+ if (agenda.length === 0)
37
+ return "";
38
+ const shown = agenda.slice(0, Math.max(1, options.maxTasks));
39
+ const omitted = agenda.length - shown.length;
40
+ const header = [
41
+ "<task_agenda>",
42
+ "Your in-flight tasks for this channel (background reference, not a new instruction).",
43
+ "Act on these only if the user's message is about them, or if there is nothing else to",
44
+ "do this turn. Full detail lives in the matching tasks/<id>.md file.",
45
+ "",
46
+ ];
47
+ const lines = shown.map((entry) => renderLine(entry, now));
48
+ if (omitted > 0)
49
+ lines.push(`- (+${omitted} more)`);
50
+ const footer = ["</task_agenda>"];
51
+ let rendered = [...header, ...lines, ...footer].join("\n");
52
+ if (rendered.length <= options.maxChars)
53
+ return rendered;
54
+ // Over budget: drop lines from the end until it fits, keeping actionable-first order.
55
+ const kept = [];
56
+ for (const line of lines) {
57
+ const candidate = [...header, ...kept, line, `- (+${agenda.length - kept.length - 1} more)`, ...footer].join("\n");
58
+ if (candidate.length > options.maxChars && kept.length > 0)
59
+ break;
60
+ kept.push(line);
61
+ }
62
+ const droppedCount = agenda.length - kept.length;
63
+ const tail = droppedCount > 0 ? [`- (+${droppedCount} more)`] : [];
64
+ rendered = [...header, ...kept, ...tail, ...footer].join("\n");
65
+ return rendered;
66
+ }
@@ -15,12 +15,13 @@ import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
15
15
  import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
16
16
  import { getUsageLedger } from "../usage/ledger.js";
17
17
  import { parseUsageMode, renderUsageReport } from "../usage/render.js";
18
- import { ensureChannelDir } from "./channel-paths.js";
18
+ import { ensureChannelDir, getChannelDir } from "./channel-paths.js";
19
19
  import { createDingTalkContext } from "./delivery.js";
20
20
  import { DingTalkBot, isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, } from "./dingtalk.js";
21
21
  import { handleEventsCommand as runEventsCommand } from "./event-commands.js";
22
22
  import { createEventsWatcher } from "./events.js";
23
23
  import { ChannelStore } from "./store.js";
24
+ import { handleTasksCommand as runTasksCommand } from "./task-commands.js";
24
25
  const DEFAULT_SOUL = `# SOUL.md
25
26
 
26
27
  Configure Pipiclaw's identity, voice, and communication style here.
@@ -466,6 +467,13 @@ export function createRuntimeContext(options) {
466
467
  });
467
468
  await bot.sendPlain(event.channelId, response);
468
469
  },
470
+ async handleTasksCommand(event, bot, args) {
471
+ const response = await runTasksCommand({
472
+ args,
473
+ channelDir: getChannelDir(options.paths.workspaceDir, event.channelId),
474
+ });
475
+ await bot.sendPlain(event.channelId, response);
476
+ },
469
477
  async handleStatusCommand(event, bot) {
470
478
  const response = renderStatus({
471
479
  state: channelStates.get(event.channelId),
@@ -555,6 +563,10 @@ export function createRuntimeContext(options) {
555
563
  await handler.handleEventsCommand(event, bot, builtInCommand.args);
556
564
  return;
557
565
  }
566
+ if (builtInCommand.name === "tasks") {
567
+ await handler.handleTasksCommand(event, bot, builtInCommand.args);
568
+ return;
569
+ }
558
570
  if (builtInCommand.name === "status") {
559
571
  await handler.handleStatusCommand(event, bot);
560
572
  return;
@@ -41,6 +41,7 @@ export interface DingTalkHandler {
41
41
  handleEvent(event: DingTalkEvent, bot: DingTalkBot, isEvent?: boolean): Promise<void>;
42
42
  handleStop(channelId: string, bot: DingTalkBot): Promise<void>;
43
43
  handleEventsCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
44
+ handleTasksCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
44
45
  handleStatusCommand(event: DingTalkEvent, bot: DingTalkBot): Promise<void>;
45
46
  handleUsageCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
46
47
  handleBusyMessage(event: DingTalkEvent, bot: DingTalkBot, mode: BusyMessageMode, queueText: string): Promise<BusyMessageResult>;
@@ -990,6 +990,10 @@ export class DingTalkBot {
990
990
  await this.handler.handleEventsCommand(event, this, builtInCommand.args);
991
991
  return;
992
992
  }
993
+ if (builtInCommand?.name === "tasks") {
994
+ await this.handler.handleTasksCommand(event, this, builtInCommand.args);
995
+ return;
996
+ }
993
997
  if (builtInCommand?.name === "status") {
994
998
  await this.handler.handleStatusCommand(event, this);
995
999
  return;
@@ -999,11 +1003,11 @@ export class DingTalkBot {
999
1003
  return;
1000
1004
  }
1001
1005
  if (builtInCommand) {
1002
- await this.sendPlain(channelId, `A task is already running. Use \`/stop\`, \`/steer <message>\`, \`/followup <message>\`, \`/events <action>\`, \`/status\`, or \`/usage\`. Plain messages default to ${this.busyMessageDefault}.`);
1006
+ await this.sendPlain(channelId, `A task is already running. Use \`/stop\`, \`/steer <message>\`, \`/followup <message>\`, \`/events <action>\`, \`/tasks\`, \`/status\`, or \`/usage\`. Plain messages default to ${this.busyMessageDefault}.`);
1003
1007
  return;
1004
1008
  }
1005
1009
  if (isSlashCommand) {
1006
- await this.sendPlain(channelId, "A task is already running. Only `/stop`, `/steer <message>`, `/followup <message>`, and `/events <action>` are available while streaming.");
1010
+ await this.sendPlain(channelId, "A task is already running. Only `/stop`, `/steer <message>`, `/followup <message>`, `/events <action>`, and `/tasks` are available while streaming.");
1007
1011
  return;
1008
1012
  }
1009
1013
  const result = await this.handler.handleBusyMessage(event, this, this.busyMessageDefault, content);
@@ -3,4 +3,9 @@ export interface HandleEventsCommandOptions {
3
3
  workspaceDir: string;
4
4
  historyPath: string;
5
5
  }
6
+ export declare function normalizeEventName(name: string): string;
7
+ export declare function resolveEventPath(workspaceDir: string, name: string): {
8
+ eventName: string;
9
+ eventPath: string;
10
+ };
6
11
  export declare function handleEventsCommand(options: HandleEventsCommandOptions): Promise<string>;
@@ -45,7 +45,7 @@ function parseEventsCommand(args) {
45
45
  function eventsDir(workspaceDir) {
46
46
  return join(workspaceDir, "events");
47
47
  }
48
- function normalizeEventName(name) {
48
+ export function normalizeEventName(name) {
49
49
  const trimmed = name.trim();
50
50
  const normalized = trimmed.endsWith(".json") ? trimmed.slice(0, -".json".length) : trimmed;
51
51
  if (!normalized || normalized === "." || normalized === ".." || !EVENT_NAME_PATTERN.test(normalized)) {
@@ -53,7 +53,7 @@ function normalizeEventName(name) {
53
53
  }
54
54
  return normalized;
55
55
  }
56
- function resolveEventPath(workspaceDir, name) {
56
+ export function resolveEventPath(workspaceDir, name) {
57
57
  const eventName = normalizeEventName(name);
58
58
  const dir = resolve(eventsDir(workspaceDir));
59
59
  const eventPath = resolve(dir, `${eventName}.json`);
@@ -0,0 +1,6 @@
1
+ export interface HandleTasksCommandOptions {
2
+ args: string;
3
+ /** The channel directory; tasks live in `<channelDir>/tasks/`. */
4
+ channelDir: string;
5
+ }
6
+ export declare function handleTasksCommand(options: HandleTasksCommandOptions): Promise<string>;