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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +13 -6
  2. package/dist/agent/channel-runner.d.ts +7 -0
  3. package/dist/agent/channel-runner.js +30 -4
  4. package/dist/agent/command-extension.d.ts +3 -0
  5. package/dist/agent/command-extension.js +37 -0
  6. package/dist/agent/commands.js +6 -0
  7. package/dist/agent/effect-ledger.d.ts +11 -0
  8. package/dist/agent/effect-ledger.js +42 -0
  9. package/dist/agent/job-manager.d.ts +90 -13
  10. package/dist/agent/job-manager.js +235 -20
  11. package/dist/agent/prompt/sections.js +12 -3
  12. package/dist/agent/prompt/types.d.ts +7 -1
  13. package/dist/agent/runner-factory.d.ts +7 -0
  14. package/dist/agent/session-events.js +20 -1
  15. package/dist/index.d.ts +1 -1
  16. package/dist/log.d.ts +6 -0
  17. package/dist/log.js +12 -0
  18. package/dist/memory/consolidation.d.ts +5 -0
  19. package/dist/memory/consolidation.js +35 -147
  20. package/dist/memory/extraction.d.ts +45 -0
  21. package/dist/memory/extraction.js +227 -0
  22. package/dist/memory/lifecycle.js +5 -0
  23. package/dist/memory/maintenance-jobs.js +7 -0
  24. package/dist/memory/post-turn-review.d.ts +3 -1
  25. package/dist/memory/post-turn-review.js +20 -189
  26. package/dist/memory/recall.d.ts +0 -1
  27. package/dist/memory/recall.js +135 -77
  28. package/dist/memory/sidecar-worker.d.ts +7 -0
  29. package/dist/memory/sidecar-worker.js +23 -5
  30. package/dist/playbooks/background-jobs.md +40 -0
  31. package/dist/playbooks/catalog.d.ts +1 -7
  32. package/dist/playbooks/catalog.js +4 -14
  33. package/dist/playbooks/event-scheduling.md +8 -4
  34. package/dist/playbooks/memory-and-learning.md +1 -1
  35. package/dist/playbooks/outbound-media.md +45 -0
  36. package/dist/playbooks/runtime-orientation.md +2 -2
  37. package/dist/playbooks/task-closeout.md +1 -1
  38. package/dist/playbooks/task-delegation.md +11 -5
  39. package/dist/playbooks/task-driving.md +52 -18
  40. package/dist/playbooks/task-planning.md +43 -18
  41. package/dist/runtime/bootstrap.js +24 -3
  42. package/dist/runtime/channel-context.d.ts +33 -0
  43. package/dist/runtime/dingtalk.d.ts +22 -2
  44. package/dist/runtime/dingtalk.js +141 -0
  45. package/dist/runtime/durable-dispatch.d.ts +10 -0
  46. package/dist/runtime/durable-dispatch.js +42 -1
  47. package/dist/runtime/event-validation.d.ts +48 -0
  48. package/dist/runtime/event-validation.js +81 -0
  49. package/dist/runtime/events.d.ts +17 -8
  50. package/dist/runtime/events.js +96 -22
  51. package/dist/runtime/task-driver.d.ts +5 -0
  52. package/dist/runtime/task-driver.js +38 -12
  53. package/dist/settings.d.ts +16 -4
  54. package/dist/settings.js +13 -1
  55. package/dist/shared/recoverable-error.d.ts +26 -0
  56. package/dist/shared/recoverable-error.js +29 -0
  57. package/dist/shared/task-ledger.d.ts +9 -7
  58. package/dist/shared/task-ledger.js +1 -1
  59. package/dist/subagents/discovery.d.ts +16 -2
  60. package/dist/subagents/discovery.js +60 -13
  61. package/dist/subagents/tool.d.ts +20 -0
  62. package/dist/subagents/tool.js +143 -15
  63. package/dist/tasks/transitions.js +3 -2
  64. package/dist/tools/bash.d.ts +2 -0
  65. package/dist/tools/bash.js +18 -5
  66. package/dist/tools/event-manage.js +28 -77
  67. package/dist/tools/index.d.ts +4 -0
  68. package/dist/tools/index.js +7 -2
  69. package/dist/tools/job.js +2 -2
  70. package/dist/tools/memory-manage.js +0 -1
  71. package/dist/tools/registry.d.ts +29 -8
  72. package/dist/tools/registry.js +39 -22
  73. package/dist/tools/send-media.d.ts +28 -0
  74. package/dist/tools/send-media.js +88 -0
  75. package/dist/tools/task-manage/create.js +5 -4
  76. package/dist/tools/task-manage/lifecycle.js +12 -11
  77. package/dist/tools/task-manage/schema.js +2 -1
  78. package/dist/tools/task-manage/shared.js +13 -12
  79. package/dist/tools/task-manage/verification.js +14 -13
  80. package/dist/tools/tool-details.d.ts +44 -0
  81. package/dist/tools/tool-details.js +62 -0
  82. package/dist/tui/app.js +2 -0
  83. package/dist/tui/terminal-media-sender.d.ts +9 -0
  84. package/dist/tui/terminal-media-sender.js +15 -0
  85. package/examples/sub-agents/README.md +21 -0
  86. package/examples/sub-agents/explorer.md +17 -0
  87. package/examples/sub-agents/git-committer.md +50 -0
  88. package/examples/sub-agents/researcher.md +18 -0
  89. package/examples/sub-agents/verifier.md +19 -0
  90. package/package.json +3 -2
  91. package/dist/playbooks/task-recurring.md +0 -44
  92. package/dist/playbooks/task-repair.md +0 -45
@@ -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
+ }
@@ -122,12 +122,21 @@ export const SUBAGENTS_SECTION = {
122
122
  maxChars: 2_400,
123
123
  overflow: "truncate-items",
124
124
  render: (context) => {
125
- // No predefined agents: the section carries nothing worth its cost (spec 026 §6.3).
125
+ // Two-state (spec 032 D1): an empty configured catalog must not delete the runtime
126
+ // guidance that lives in this section — only the catalog itself is optional. This
127
+ // inline-usage text is runtime-authored, not user content; keep it under 40 units
128
+ // (it does not count toward the 700/1200 unit budget — see builder.ts's
129
+ // RUNTIME_AUTHORED_SECTION_IDS — so it must not be padded just because it is "free").
126
130
  if (context.subAgents.length === 0) {
127
- return undefined;
131
+ return [
132
+ "## Sub-Agents",
133
+ "Delegate with `subagent`: pass an inline `systemPrompt` (no configured agent is required).",
134
+ "A sub-agent starts blank — state goal, scope, paths, constraints, acceptance criteria in `task`.",
135
+ "Read task-delegation.md before non-trivial delegation.",
136
+ ].join("\n");
128
137
  }
129
138
  return [
130
- "## Predefined Sub-Agents",
139
+ "## Configured Sub-Agents",
131
140
  "A sub-agent starts blank: state the goal, scope, paths, constraints and acceptance criteria in the task you hand it.",
132
141
  ...context.subAgents.map((agent) => `- ${agent.name} — ${agent.description}`),
133
142
  "",
@@ -27,10 +27,16 @@ export type PromptCacheClass = "runtime-stable" | "workspace-versioned" | "sessi
27
27
  * `error` is for runtime-authored text: overflowing it is a development error, not a user problem.
28
28
  */
29
29
  export type PromptOverflowPolicy = "error" | "truncate-head-tail" | "truncate-items" | "omit";
30
+ /**
31
+ * A registered tool, as the prompt builder sees it. There is no per-tool prose here and no
32
+ * section renders this list: spec 026 §3.2 removed `## Available Tools` because the model
33
+ * already receives each tool's name, description and schema with every request. The list is
34
+ * kept because the builder still needs it to decide whether a mechanism is reachable —
35
+ * gating sections (`requiresAllTools`), filtering playbooks, and reporting via `/context`.
36
+ */
30
37
  export interface ToolDescriptor {
31
38
  name: string;
32
39
  description: string;
33
- hint?: string;
34
40
  }
35
41
  export interface SubAgentSummary {
36
42
  name: string;
@@ -1,3 +1,4 @@
1
+ import type { MediaSender } from "../runtime/channel-context.js";
1
2
  import type { AgentRunner } from "./types.js";
2
3
  export interface RunnerFactoryPaths {
3
4
  appHomeDir: string;
@@ -5,6 +6,12 @@ export interface RunnerFactoryPaths {
5
6
  modelsConfigPath: string;
6
7
  /** Optional, side-effect-free observer used by the behavior-eval harness. */
7
8
  onSessionEvent?: (event: unknown, channelId: string) => void;
9
+ /**
10
+ * Transport that can deliver file attachments (the DingTalk bot, or the terminal).
11
+ * Present enables the `send_media` tool; absent, the tool is not built. Not part
12
+ * of the runner cache key — it is a stable per-process transport handle.
13
+ */
14
+ mediaSender?: MediaSender;
8
15
  }
9
16
  export declare function getOrCreateRunner(channelId: string, channelDir: string, paths: RunnerFactoryPaths): AgentRunner;
10
17
  export declare function resetRunner(channelId: string, paths?: RunnerFactoryPaths, channelDir?: string): void;
@@ -1,6 +1,8 @@
1
1
  import * as log from "../log.js";
2
2
  import { extractLabelFromArgs, truncate } from "../shared/text-utils.js";
3
3
  import { isRecord } from "../shared/type-guards.js";
4
+ import { toolResultDetails } from "../tools/tool-details.js";
5
+ import { isEffectfulTool, noteChannelEffect } from "./effect-ledger.js";
4
6
  import { extractToolResultText, formatProgressEntry } from "./progress-formatter.js";
5
7
  import { extractCustomCommandResultText, isAssistantEventMessage, isAutoCompactionEndEvent, isAutoCompactionStartEvent, isAutoRetryStartEvent, isMessageEndEvent, isMessageStartEvent, isSubAgentToolDetails, isTextPart, isThinkingPart, isToolExecutionEndEvent, isToolExecutionStartEvent, isToolExecutionUpdateEvent, isTurnEndEvent, } from "./type-guards.js";
6
8
  function isSkillManageDetails(value) {
@@ -121,7 +123,7 @@ export async function handleSessionEvent(event, context) {
121
123
  },
122
124
  }) ?? Promise.resolve(), "sub-agent run log");
123
125
  }
124
- const details = isRecord(event.result) && "details" in event.result ? event.result.details : null;
126
+ const details = toolResultDetails(event.result);
125
127
  if (isSkillManageDetails(details)) {
126
128
  if (details.requiresResourceRefresh && context.refreshSessionResources) {
127
129
  queue.enqueue(() => context.refreshSessionResources?.() ?? Promise.resolve(), "refresh skills");
@@ -130,13 +132,27 @@ export async function handleSessionEvent(event, context) {
130
132
  queue.enqueue(() => ctx.respondInThread(details.notice ?? ""), "skill notice");
131
133
  }
132
134
  }
135
+ // A recoverable rejection (bad arguments, unmet precondition the model can fix) is not a
136
+ // fault: the model normally corrects it on the next call. It is logged so the retry is
137
+ // still diagnosable, but never rendered to the user — a red bubble would report a failure
138
+ // that never happened and make the assistant look broken mid-turn. Rejections the *user*
139
+ // must resolve (an approval gate, a guard refusal) stay plain errors and remain visible.
140
+ const rejected = details?.recoverable === true;
133
141
  const treatAsError = event.isError || Boolean(subAgentDetails?.failed);
134
142
  if (treatAsError) {
135
143
  log.logToolError(logCtx, event.toolName, durationMs, resultStr);
136
144
  }
145
+ else if (rejected) {
146
+ log.logToolRejected(logCtx, event.toolName, durationMs, resultStr);
147
+ }
137
148
  else {
138
149
  log.logToolSuccess(logCtx, event.toolName, durationMs, resultStr);
139
150
  }
151
+ // A tool that actually changed something outside the task ledger is the evidence the task
152
+ // governor judges progress by (spec 031, D7).
153
+ if (!treatAsError && !rejected && isEffectfulTool(event.toolName, details)) {
154
+ noteChannelEffect(logCtx.channelId);
155
+ }
140
156
  if (treatAsError && showProgress) {
141
157
  queue.enqueue(() => ctx.respond(formatProgressEntry("error", truncate(resultStr, 200)), false), "tool error");
142
158
  }
@@ -231,6 +247,9 @@ export async function handleSessionEvent(event, context) {
231
247
  if (runState.finalOutcome.kind === "final" && runState.finalOutcome.text.trim() === trimmedFinalText) {
232
248
  return;
233
249
  }
250
+ // A real answer to the user is a visible result even when no file changed (D7);
251
+ // a [SILENT] turn above deliberately does not reach here.
252
+ noteChannelEffect(logCtx.channelId);
234
253
  runState.finalOutcome = { kind: "final", text: finalText };
235
254
  memoryLifecycle.noteCompletedAssistantTurn();
236
255
  log.logResponse(logCtx, finalText);
package/dist/index.d.ts CHANGED
@@ -23,7 +23,7 @@ export type { ChannelContext, ChannelContext as DingTalkContext, FinalDelivery,
23
23
  export { ensureChannelDir, getChannelDir, getChannelDirName, } from "./runtime/channel-paths.js";
24
24
  export { createDingTalkContext } from "./runtime/delivery.js";
25
25
  export { type BusyMessageDefaultConfig, type BusyMessageMode, DingTalkBot, type DingTalkConfig, type DingTalkEvent, type DingTalkHandler, finalDeliveryOf, isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, progressStyleOf, type ResponseMode, } from "./runtime/dingtalk.js";
26
- export { createEventsWatcher, type EventAction, EventsWatcher, type ImmediateEvent, type OneShotEvent, type PeriodicEvent, type ScheduledEvent, } from "./runtime/events.js";
26
+ export { createEventsWatcher, type EventAction, EventsWatcher, type OneShotEvent, type PeriodicEvent, type ScheduledEvent, } from "./runtime/events.js";
27
27
  export { ChannelStore, type LoggedMessage, type LoggedSubAgentRun } from "./runtime/store.js";
28
28
  export { type PipiclawMemoryGrowthSettings, type PipiclawMemoryMaintenanceSettings, type PipiclawMemoryRecallSettings, type PipiclawSessionMemorySettings, type PipiclawSettings, PipiclawSettingsManager, } from "./settings.js";
29
29
  export { discoverSubAgents, formatSubAgentList, getSubAgentsDir, type ResolvedSubAgentConfig, resolveSubAgentConfig, type SubAgentConfig, type SubAgentContextMode, type SubAgentDiscoveryResult, type SubAgentInvocationOverrides, type SubAgentMemoryMode, type SubAgentToolName, } from "./subagents/discovery.js";
package/dist/log.d.ts CHANGED
@@ -27,6 +27,12 @@ export declare function flushLogging(): Promise<void>;
27
27
  export declare function logEvent(level: LogLevel, event: string, message: string, options?: LogOptions): void;
28
28
  export declare function logToolStart(ctx: LogContext, toolName: string, label: string, args: Record<string, unknown>): void;
29
29
  export declare function logToolSuccess(ctx: LogContext, toolName: string, durationMs: number, result: string): void;
30
+ /**
31
+ * A tool call the model can fix itself (bad arguments, unmet precondition). Logged at debug,
32
+ * not warn: it is an expected step in a self-correcting turn, not an operator problem. Kept
33
+ * distinct from success so a model looping on the same rejection is still visible in the log.
34
+ */
35
+ export declare function logToolRejected(ctx: LogContext, toolName: string, durationMs: number, reason: string): void;
30
36
  export declare function logToolError(ctx: LogContext, toolName: string, durationMs: number, error: string): void;
31
37
  export declare function logResponseStart(ctx: LogContext): void;
32
38
  export declare function logThinking(ctx: LogContext, thinking: string): void;
package/dist/log.js CHANGED
@@ -187,6 +187,18 @@ export function logToolSuccess(ctx, toolName, durationMs, result) {
187
187
  fields: { tool: toolName, durationMs, resultLength: result.length },
188
188
  });
189
189
  }
190
+ /**
191
+ * A tool call the model can fix itself (bad arguments, unmet precondition). Logged at debug,
192
+ * not warn: it is an expected step in a self-correcting turn, not an operator problem. Kept
193
+ * distinct from success so a model looping on the same rejection is still visible in the log.
194
+ */
195
+ export function logToolRejected(ctx, toolName, durationMs, reason) {
196
+ logEvent("debug", "agent.tool.rejected", "Tool rejected the call", {
197
+ ctx,
198
+ details: reason,
199
+ fields: { tool: toolName, durationMs, reason },
200
+ });
201
+ }
190
202
  export function logToolError(ctx, toolName, durationMs, error) {
191
203
  logEvent("warn", "agent.tool.failed", "Tool failed", {
192
204
  ctx,
@@ -2,6 +2,7 @@ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
2
  import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import { type SessionEntry } from "@earendil-works/pi-coding-agent";
4
4
  import type { PipiclawMemoryMaintenanceSettings } from "../settings.js";
5
+ import { type MemoryPromotionCandidate } from "./promotion.js";
5
6
  import type { MemorySourceWindow } from "./source-window.js";
6
7
  export type ConsolidationMode = "idle" | "boundary";
7
8
  export interface ConsolidationRunOptions {
@@ -14,11 +15,15 @@ export interface ConsolidationRunOptions {
14
15
  sourceWindow?: MemorySourceWindow;
15
16
  mode?: ConsolidationMode;
16
17
  usageCorrelationId?: string;
18
+ /** Durable-write bar; defaults to the same threshold the growth review uses. */
19
+ minAutoWriteConfidence?: number;
17
20
  }
18
21
  export interface InlineConsolidationResult {
19
22
  skipped: boolean;
20
23
  appendedMemoryEntries: number;
21
24
  appendedHistoryBlock: boolean;
25
+ /** Candidates the confidence gate turned down, surfaced for the review log. */
26
+ rejectedMemoryOps: MemoryPromotionCandidate[];
22
27
  }
23
28
  export interface StructuralMaintenanceStats {
24
29
  memoryCleanupNeeded: boolean;