@oyasmi/pipiclaw 0.8.10-beta.2 → 0.8.10-beta.4

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 (60) hide show
  1. package/dist/agent/channel-runner.d.ts +12 -0
  2. package/dist/agent/channel-runner.js +54 -15
  3. package/dist/agent/commands.js +30 -28
  4. package/dist/agent/effect-ledger.d.ts +25 -4
  5. package/dist/agent/effect-ledger.js +45 -5
  6. package/dist/agent/job-manager.d.ts +20 -0
  7. package/dist/agent/job-manager.js +66 -10
  8. package/dist/agent/maintenance-context.js +3 -2
  9. package/dist/agent/progress-formatter.d.ts +10 -1
  10. package/dist/agent/progress-formatter.js +14 -2
  11. package/dist/agent/prompt/manifest.d.ts +32 -1
  12. package/dist/agent/prompt/manifest.js +41 -2
  13. package/dist/executor.d.ts +2 -0
  14. package/dist/executor.js +1 -0
  15. package/dist/memory/maintenance-gates.d.ts +24 -10
  16. package/dist/memory/maintenance-gates.js +11 -9
  17. package/dist/memory/maintenance-jobs.d.ts +3 -2
  18. package/dist/memory/maintenance-jobs.js +33 -21
  19. package/dist/memory/scheduler.d.ts +7 -2
  20. package/dist/playbooks/task-closeout.md +2 -0
  21. package/dist/playbooks/task-delegation.md +14 -8
  22. package/dist/playbooks/task-driving.md +8 -5
  23. package/dist/playbooks/task-planning.md +2 -2
  24. package/dist/runtime/bootstrap.js +35 -9
  25. package/dist/runtime/delivery.d.ts +12 -2
  26. package/dist/runtime/delivery.js +55 -13
  27. package/dist/runtime/dingtalk.d.ts +9 -1
  28. package/dist/runtime/dingtalk.js +7 -4
  29. package/dist/runtime/task-commands.js +170 -54
  30. package/dist/runtime/task-driver.d.ts +3 -3
  31. package/dist/runtime/task-driver.js +42 -12
  32. package/dist/settings.d.ts +10 -0
  33. package/dist/settings.js +14 -0
  34. package/dist/shared/file-stamp.d.ts +10 -0
  35. package/dist/shared/file-stamp.js +19 -0
  36. package/dist/shared/task-ledger.d.ts +12 -1
  37. package/dist/shared/task-ledger.js +34 -3
  38. package/dist/subagents/tool.d.ts +1 -0
  39. package/dist/subagents/tool.js +33 -3
  40. package/dist/tasks/control.d.ts +1 -0
  41. package/dist/tasks/control.js +2 -2
  42. package/dist/tasks/transitions.d.ts +2 -1
  43. package/dist/tasks/transitions.js +2 -1
  44. package/dist/tasks/verification.d.ts +8 -0
  45. package/dist/tasks/verification.js +4 -1
  46. package/dist/tools/bash.js +12 -12
  47. package/dist/tools/task-manage/lifecycle.js +9 -6
  48. package/dist/tools/task-manage/schema.d.ts +1 -3
  49. package/dist/tools/task-manage/schema.js +6 -5
  50. package/dist/tools/task-manage/shared.d.ts +8 -0
  51. package/dist/tools/task-manage/shared.js +17 -1
  52. package/dist/tools/task-manage/types.d.ts +20 -21
  53. package/dist/tools/task-manage/verification.d.ts +2 -1
  54. package/dist/tools/task-manage/verification.js +2 -1
  55. package/dist/tools/task-manage.js +4 -20
  56. package/dist/tui/turn-controller.js +3 -3
  57. package/dist/usage/ledger.d.ts +2 -0
  58. package/dist/usage/ledger.js +7 -2
  59. package/dist/usage/render.js +17 -8
  60. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "fs";
2
2
  import { join } from "path";
3
3
  import { formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../agent/commands.js";
4
- import { channelEffectCount } from "../agent/effect-ledger.js";
4
+ import { channelEffectCount, noteTaskEffects, taskEffectCount } from "../agent/effect-ledger.js";
5
5
  import { getOrCreateRunner } from "../agent/index.js";
6
6
  import { configureJobRuntime, restoreChannelJobs } from "../agent/job-manager.js";
7
7
  import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
@@ -16,10 +16,11 @@ import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
16
16
  import { flushSecurityLogs } from "../security/logger.js";
17
17
  import { PipiclawSettingsManager } from "../settings.js";
18
18
  import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
19
+ import { fileStamp } from "../shared/file-stamp.js";
19
20
  import { readActiveTasks } from "../shared/task-ledger.js";
20
21
  import { errorMessage } from "../shared/text-utils.js";
21
22
  import { finishTaskAttempt } from "../tasks/store.js";
22
- import { loadToolsConfig, loadToolsConfigWithDiagnostics } from "../tools/config.js";
23
+ import { getToolsConfigPath, loadToolsConfig, loadToolsConfigWithDiagnostics } from "../tools/config.js";
23
24
  import { getUsageLedger } from "../usage/ledger.js";
24
25
  import { parseUsageMode, renderUsageReport } from "../usage/render.js";
25
26
  import { ensureChannelDir, getChannelDir } from "./channel-paths.js";
@@ -442,6 +443,7 @@ export function createRuntimeContext(options) {
442
443
  },
443
444
  async handleStop(channelId, _bot) {
444
445
  const runner = channelRunners.get(channelId);
446
+ let pausedTaskId;
445
447
  if (runner?.isBusy()) {
446
448
  runner.requestStop();
447
449
  const taskId = /^\[TASK_(?:DRIVER|CYCLE):([A-Za-z0-9._-]+)\]/.exec(runner.getTurnStatus().taskText ?? "")?.[1];
@@ -451,6 +453,7 @@ export function createRuntimeContext(options) {
451
453
  channelDir: getChannelDir(options.paths.workspaceDir, channelId),
452
454
  approver: "user via /stop",
453
455
  }, taskId);
456
+ pausedTaskId = taskId;
454
457
  log.logInfo(`[${channelId}] ${pauseResult}`);
455
458
  }
456
459
  _bot.discardCard(channelId);
@@ -469,6 +472,7 @@ export function createRuntimeContext(options) {
469
472
  });
470
473
  log.logInfo(`[${channelId}] Stop requested`);
471
474
  }
475
+ return { pausedTaskId };
472
476
  },
473
477
  async handleEventsCommand(event, bot, args) {
474
478
  const response = await runEventsCommand({
@@ -527,7 +531,7 @@ export function createRuntimeContext(options) {
527
531
  const trimmedQueueText = queueText.trim();
528
532
  if (!trimmedQueueText) {
529
533
  const commandName = mode === "followUp" ? "followup" : "steer";
530
- await bot.sendPlain(event.channelId, `Could not queue this message: /${commandName} requires a message.`);
534
+ await bot.sendPlain(event.channelId, `无法排队:/${commandName} 需要带上消息内容。`);
531
535
  return { kind: "handled" };
532
536
  }
533
537
  if (mode === "followUp") {
@@ -550,8 +554,8 @@ export function createRuntimeContext(options) {
550
554
  skipContextSync: true,
551
555
  }, `${mode} message`);
552
556
  const confirmation = event.text.trim().startsWith("/")
553
- ? "Queued as steer. I’ll apply it after the current tool step finishes."
554
- : "Queued as steer. I’ll apply this after the current tool step finishes. Use `/followup <message>` to queue it after completion.";
557
+ ? "已作为 steer 排队,当前工具步骤结束后生效。"
558
+ : "已作为 steer 排队,当前工具步骤结束后生效。想等整个回合结束再执行,用 `/followup <消息>`。";
555
559
  await bot.sendPlain(event.channelId, confirmation);
556
560
  log.logEvent("info", "agent.turn.steer_queued", "Steer queued", {
557
561
  ctx: { channelId: event.channelId, userName: event.userName },
@@ -566,7 +570,7 @@ export function createRuntimeContext(options) {
566
570
  return { kind: "requeue", text: trimmedQueueText };
567
571
  }
568
572
  log.logWarning(`[${event.channelId}] Failed to queue ${mode}`, errMsg);
569
- await bot.sendPlain(event.channelId, `Could not queue this message: ${errMsg}`);
573
+ await bot.sendPlain(event.channelId, `无法排队这条消息:${errMsg}`);
570
574
  return { kind: "handled" };
571
575
  }
572
576
  },
@@ -593,7 +597,9 @@ export function createRuntimeContext(options) {
593
597
  text: event.text,
594
598
  isBot: false,
595
599
  }, "user message");
596
- const ctx = createDingTalkContext(event, bot, store);
600
+ // Background wakes deliver their result, not their process: no progress card,
601
+ // no thinking stream, nothing to delete when the check-in ends `[SILENT]`.
602
+ const ctx = createDingTalkContext(event, bot, store, _isEvent ? "none" : undefined);
597
603
  const builtInCommand = parseBuiltInCommand(event.text);
598
604
  if (builtInCommand) {
599
605
  log.logEvent("info", "runtime.command.started", "Executing command", {
@@ -636,8 +642,15 @@ export function createRuntimeContext(options) {
636
642
  if (!_isEvent) {
637
643
  ctx.primeCard(350);
638
644
  }
645
+ // Effects are tallied per channel; the governor needs them per task, so one
646
+ // task-driver turn is measured as a delta (turns on a channel are serialized)
647
+ // and credited to the task it was dispatched for.
648
+ const effectsBefore = channelEffectCount(event.channelId);
639
649
  const result = await runner.run(ctx, store);
640
650
  const taskDriverMatch = /^\[TASK_DRIVER:([A-Za-z0-9._-]+)\]/.exec(event.text);
651
+ if (taskDriverMatch?.[1]) {
652
+ noteTaskEffects(event.channelId, taskDriverMatch[1], channelEffectCount(event.channelId) - effectsBefore);
653
+ }
641
654
  if (taskDriverMatch?.[1] && result.usage && result.durationMs !== undefined) {
642
655
  await finishTaskAttempt(getChannelDir(options.paths.workspaceDir, event.channelId), taskDriverMatch[1], {
643
656
  tokens: result.usage.total,
@@ -726,6 +739,19 @@ export function createRuntimeContext(options) {
726
739
  },
727
740
  intervalMs: options.memoryMaintenanceSchedulerIntervalMs,
728
741
  });
742
+ // `tools.json` is re-read on every driver tick — and a tick follows every turn — so cache the
743
+ // parse behind the file's change token. `settings.json` gets the same treatment inside
744
+ // `PipiclawSettingsManager.reload()`, which is why the getSettings closure below stays as-is.
745
+ let cachedToolsStamp;
746
+ let cachedTasksEnabled = true;
747
+ const tasksToolEnabled = () => {
748
+ const stamp = fileStamp(getToolsConfigPath(options.paths.appHomeDir));
749
+ if (stamp !== cachedToolsStamp) {
750
+ cachedToolsStamp = stamp;
751
+ cachedTasksEnabled = loadToolsConfig(options.paths.appHomeDir).tools.tasks.enabled;
752
+ }
753
+ return cachedTasksEnabled;
754
+ };
729
755
  const taskDriver = options.createTaskDriver
730
756
  ? options.createTaskDriver()
731
757
  : new TaskDriver({
@@ -734,12 +760,12 @@ export function createRuntimeContext(options) {
734
760
  isChannelActive: (channelId) => channelRunners.get(channelId)?.isBusy() ?? false,
735
761
  dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
736
762
  onDispatch: options.onTaskDriverDispatch,
737
- getEffectCount: channelEffectCount,
763
+ getEffectCount: taskEffectCount,
738
764
  getSettings: () => {
739
765
  runtimeSettingsManager.reload();
740
766
  return runtimeSettingsManager.getTaskDriverSettings();
741
767
  },
742
- isEnabled: () => loadToolsConfig(options.paths.appHomeDir).tools.tasks.enabled,
768
+ isEnabled: tasksToolEnabled,
743
769
  });
744
770
  const shutdownWithReason = async (reason = "manual") => {
745
771
  if (shutdownPromise) {
@@ -1,4 +1,14 @@
1
- import type { ChannelContext } from "./channel-context.js";
1
+ import type { ChannelContext, ProgressStyle } from "./channel-context.js";
2
2
  import type { DingTalkBot, DingTalkEvent } from "./dingtalk.js";
3
3
  import type { ChannelStore } from "./store.js";
4
- export declare function createDingTalkContext(event: DingTalkEvent, bot: DingTalkBot, store: ChannelStore): ChannelContext;
4
+ /**
5
+ * Build the delivery contract for one turn.
6
+ *
7
+ * `progressStyleOverride` lets the caller quiet a turn the user did not ask for. Background wakes
8
+ * (task driver, finished jobs, scheduled events) pass `"none"`: without it every autonomous step
9
+ * created an AI card in the human's conversation, streamed the model's thinking into it, and — for
10
+ * the `[SILENT]` turns that are the *normal* outcome of a check-in — deleted the card again. The
11
+ * final answer is unaffected; it is delivered by `respondPlain`/`replaceMessage` either way, so a
12
+ * background turn that has something to say still says it.
13
+ */
14
+ export declare function createDingTalkContext(event: DingTalkEvent, bot: DingTalkBot, store: ChannelStore, progressStyleOverride?: ProgressStyle): ChannelContext;
@@ -8,10 +8,13 @@ const NO_CONTENT = "";
8
8
  // an unforeseen stall so run()'s finally can never hang the channel forever.
9
9
  const FLUSH_DEADLINE_MS = 60_000;
10
10
  class ChannelDeliveryController {
11
- constructor(event, bot, store) {
11
+ constructor(event, bot, store,
12
+ /** Per-turn override of the channel's configured progress style; see `createDingTalkContext`. */
13
+ progressStyleOverride) {
12
14
  this.event = event;
13
15
  this.bot = bot;
14
16
  this.store = store;
17
+ this.progressStyleOverride = progressStyleOverride;
15
18
  this.progressSegments = [];
16
19
  this.cachedProgressText = "";
17
20
  this.progressTextDirty = false;
@@ -34,6 +37,10 @@ class ChannelDeliveryController {
34
37
  this.replayRequired = false;
35
38
  this.finalReplacementText = "";
36
39
  }
40
+ /** The style this turn actually delivers with: the override when present, else the channel's. */
41
+ get progressStyle() {
42
+ return this.progressStyleOverride ?? this.bot.progressStyle;
43
+ }
37
44
  buildContext() {
38
45
  return {
39
46
  message: {
@@ -63,7 +70,7 @@ class ChannelDeliveryController {
63
70
  primeCard: (delayMs) => this.primeCard(delayMs),
64
71
  flush: async () => this.flush(),
65
72
  close: async () => this.close(),
66
- progressStyle: this.bot.progressStyle,
73
+ progressStyle: this.progressStyle,
67
74
  finalDelivery: this.bot.finalDelivery,
68
75
  };
69
76
  }
@@ -108,7 +115,7 @@ class ChannelDeliveryController {
108
115
  return;
109
116
  // Final-card-only mode shows no progress; ignore any stray progress writes
110
117
  // so we never create or flicker a card before the final replacement.
111
- if (this.bot.progressStyle === "none")
118
+ if (this.progressStyle === "none")
112
119
  return;
113
120
  this.clearCardWarmup();
114
121
  if (this.progressStartedAt === 0) {
@@ -122,8 +129,12 @@ class ChannelDeliveryController {
122
129
  }
123
130
  this.progressSegments.push(text);
124
131
  this.progressTextDirty = true;
125
- if (this.bot.progressStyle === "rolling") {
132
+ if (this.progressStyle === "rolling") {
126
133
  this.trimToRecentEntries(ROLLING_WINDOW_SIZE);
134
+ // The header carries elapsed time and a step count, so it changes on every update:
135
+ // an append-only delta would leave a stale header on the card.
136
+ this.replayRequired = true;
137
+ this.sentProgressChars = 0;
127
138
  }
128
139
  if (this.progressWindowStartedAt === 0) {
129
140
  this.progressWindowStartedAt = Date.now();
@@ -199,7 +210,10 @@ class ChannelDeliveryController {
199
210
  try {
200
211
  while (this.appliedRevision < this.desiredRevision) {
201
212
  const mode = this.mode;
202
- const progressText = this.getProgressText();
213
+ const body = this.getProgressText();
214
+ const progressText = mode === "progress" && this.progressStyle === "rolling" && body
215
+ ? `${this.buildRollingHeader()}\n\n${body}`
216
+ : body;
203
217
  const throttleBaseAt = this.lastDeliveredAt > 0 ? this.lastDeliveredAt : this.progressWindowStartedAt;
204
218
  if (mode === "progress" && throttleBaseAt > 0) {
205
219
  const remaining = MIN_UPDATE_INTERVAL_MS - (Date.now() - throttleBaseAt);
@@ -238,8 +252,8 @@ class ChannelDeliveryController {
238
252
  }
239
253
  else if (mode === "finalize-existing") {
240
254
  if (content || this.cardWarmupTriggered) {
241
- const finalProgressText = this.bot.progressStyle === "rolling" ? this.buildSummaryText("Done") : progressText;
242
- touchedRemote = await this.bot.replaceCard(this.event.channelId, content || this.bot.progressStyle === "rolling" ? finalProgressText : NO_CONTENT, true);
255
+ const finalProgressText = this.progressStyle === "rolling" ? this.buildSummaryText() : progressText;
256
+ touchedRemote = await this.bot.replaceCard(this.event.channelId, content || this.progressStyle === "rolling" ? finalProgressText : NO_CONTENT, true);
243
257
  if (!touchedRemote) {
244
258
  this.bot.discardCard(this.event.channelId);
245
259
  }
@@ -345,6 +359,26 @@ class ChannelDeliveryController {
345
359
  this.progressTextDirty = false;
346
360
  return this.cachedProgressText;
347
361
  }
362
+ formatElapsed(ms) {
363
+ const seconds = Math.max(0, Math.round(ms / 1000));
364
+ if (seconds < 60)
365
+ return `${seconds}s`;
366
+ const minutes = Math.floor(seconds / 60);
367
+ if (minutes < 60)
368
+ return `${minutes}m${String(seconds % 60).padStart(2, "0")}s`;
369
+ return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, "0")}m`;
370
+ }
371
+ elapsedMs() {
372
+ return this.progressStartedAt > 0 ? Date.now() - this.progressStartedAt : 0;
373
+ }
374
+ /**
375
+ * Standing first line for rolling mode. The window only keeps the last few entries, so a long
376
+ * turn otherwise gave no way to tell "still working, 14 steps in" from "stuck": every visible
377
+ * line looked the same as a minute ago. The numbers are already tracked for the closing summary.
378
+ */
379
+ buildRollingHeader() {
380
+ return `⏱ ${this.formatElapsed(this.elapsedMs())} · ${this.toolCallCount} 步`;
381
+ }
348
382
  trimToRecentEntries(maxEntries) {
349
383
  let entryCount = 0;
350
384
  for (const segment of this.progressSegments) {
@@ -370,12 +404,20 @@ class ChannelDeliveryController {
370
404
  this.replayRequired = true;
371
405
  this.sentProgressChars = 0;
372
406
  }
373
- buildSummaryText(status) {
374
- const elapsedSeconds = this.progressStartedAt > 0 ? Math.round((Date.now() - this.progressStartedAt) / 1000) : 0;
375
- const toolLabel = this.toolCallCount === 1 ? "1 tool call" : `${this.toolCallCount} tool calls`;
376
- return `${status} · ${toolLabel} · ${elapsedSeconds}s`;
407
+ buildSummaryText() {
408
+ return `完成 · ${this.toolCallCount} 步 · ${this.formatElapsed(this.elapsedMs())}`;
377
409
  }
378
410
  }
379
- export function createDingTalkContext(event, bot, store) {
380
- return new ChannelDeliveryController(event, bot, store).buildContext();
411
+ /**
412
+ * Build the delivery contract for one turn.
413
+ *
414
+ * `progressStyleOverride` lets the caller quiet a turn the user did not ask for. Background wakes
415
+ * (task driver, finished jobs, scheduled events) pass `"none"`: without it every autonomous step
416
+ * created an AI card in the human's conversation, streamed the model's thinking into it, and — for
417
+ * the `[SILENT]` turns that are the *normal* outcome of a check-in — deleted the card again. The
418
+ * final answer is unaffected; it is delivered by `respondPlain`/`replaceMessage` either way, so a
419
+ * background turn that has something to say still says it.
420
+ */
421
+ export function createDingTalkContext(event, bot, store, progressStyleOverride) {
422
+ return new ChannelDeliveryController(event, bot, store, progressStyleOverride).buildContext();
381
423
  }
@@ -38,10 +38,18 @@ export type BusyMessageResult = {
38
38
  kind: "requeue";
39
39
  text: string;
40
40
  };
41
+ /**
42
+ * What `/stop` actually did. Stopping a task-driven turn also pauses that task, which the user
43
+ * has to be told: a paused task is never picked up again until `/tasks resume <id>`, so silence
44
+ * here reads as "the turn was interrupted" while the whole task has in fact gone quiet.
45
+ */
46
+ export interface StopOutcome {
47
+ pausedTaskId?: string;
48
+ }
41
49
  export interface DingTalkHandler {
42
50
  isRunning(channelId: string): boolean;
43
51
  handleEvent(event: DingTalkEvent, bot: DingTalkBot, isEvent?: boolean): Promise<void>;
44
- handleStop(channelId: string, bot: DingTalkBot): Promise<void>;
52
+ handleStop(channelId: string, bot: DingTalkBot): Promise<StopOutcome>;
45
53
  handleEventsCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
46
54
  handleTasksCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
47
55
  handleStatusCommand(event: DingTalkEvent, bot: DingTalkBot): Promise<void>;
@@ -1080,10 +1080,13 @@ export class DingTalkBot {
1080
1080
  case "help":
1081
1081
  await this.sendPlain(channelId, renderBuiltInHelp());
1082
1082
  return;
1083
- case "stop":
1084
- await this.handler.handleStop(channelId, this);
1085
- await this.sendPlain(channelId, "Stopping the current task.");
1083
+ case "stop": {
1084
+ const outcome = await this.handler.handleStop(channelId, this);
1085
+ await this.sendPlain(channelId, outcome.pausedTaskId
1086
+ ? `已停止当前回合。任务 \`${outcome.pausedTaskId}\` 已暂停,用 \`/tasks resume ${outcome.pausedTaskId}\` 继续。`
1087
+ : "已停止当前回合。");
1086
1088
  return;
1089
+ }
1087
1090
  case "steer":
1088
1091
  case "followup": {
1089
1092
  const mode = builtInCommand.name === "steer" ? "steer" : "followUp";
@@ -1113,7 +1116,7 @@ export class DingTalkBot {
1113
1116
  // Session commands (/model, /new, …) and unknown slash commands cannot
1114
1117
  // run mid-turn: they would need the idle session layer.
1115
1118
  if (isSlashCommand) {
1116
- await this.sendPlain(channelId, `A task is already running. While streaming you can use: ${formatBusyCommandList()}. Session commands (\`/model\`, \`/new\`, \`/compact\`, \`/session\`) are available when idle.`);
1119
+ await this.sendPlain(channelId, `当前已有回合在运行。运行中可用:${formatBusyCommandList()}。会话命令(\`/model\`、\`/new\`、\`/compact\`、\`/session\`)需要等空闲后再用。`);
1117
1120
  return;
1118
1121
  }
1119
1122
  const result = await this.handler.handleBusyMessage(event, this, this.busyMessageDefault, content);