@oyasmi/pipiclaw 0.8.10-beta.3 → 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.
@@ -33,7 +33,7 @@ import { PRIMARY_COOLDOWN_MS, runPromptWithFallback, shouldRestorePrimary, } fro
33
33
  import { clipUserInput, formatProgressEntry } from "./progress-formatter.js";
34
34
  import { buildPipiclawSystemPrompt } from "./prompt/builder.js";
35
35
  import { createPromptBoundaryExtension } from "./prompt/extension.js";
36
- import { buildPromptManifest, renderContextReport } from "./prompt/manifest.js";
36
+ import { buildPromptManifest, measureToolSchemas, renderContextReport, TOOL_SCHEMA_TARGET_UNITS, toolSchemaBudgetWarning, } from "./prompt/manifest.js";
37
37
  import { loadWorkspacePromptResources } from "./prompt/resources.js";
38
38
  import { createRunQueue } from "./run-queue.js";
39
39
  import { handleSessionEvent } from "./session-events.js";
@@ -569,7 +569,7 @@ export class ChannelRunner {
569
569
  finalPrompt: this.lastFinalPrompt,
570
570
  skills: this.currentSkills.skills.map((skill) => ({ name: skill.name, description: skill.description })),
571
571
  toolNames: this.currentTools.map((tool) => tool.name),
572
- toolSchemaChars: this.currentTools.reduce((sum, tool) => sum + tool.name.length + tool.description.length + JSON.stringify(tool.parameters ?? {}).length, 0),
572
+ toolSchemas: measureToolSchemas(this.currentTools),
573
573
  soul: this.lastWorkspaceResources?.soul,
574
574
  agents: this.lastWorkspaceResources?.agents,
575
575
  lastTurn: this.lastTurnContextStats,
@@ -1054,6 +1054,12 @@ export class ChannelRunner {
1054
1054
  mediaSender: this.mediaSender,
1055
1055
  });
1056
1056
  this.currentTools = tools;
1057
+ // Tool schemas are billed with the system prompt and, unlike it, nothing trims them.
1058
+ // Warn where the prompt's own budget diagnostics are reported, once per tool rebuild.
1059
+ const schemas = measureToolSchemas(tools);
1060
+ if (schemas.units > TOOL_SCHEMA_TARGET_UNITS) {
1061
+ log.logWarning(`[${this.channelId}] Tool schema budget`, toolSchemaBudgetWarning(schemas));
1062
+ }
1057
1063
  return tools;
1058
1064
  }
1059
1065
  rebuildSessionTools() {
@@ -1,5 +1,17 @@
1
1
  export declare function noteChannelEffect(channelId: string): void;
2
2
  export declare function channelEffectCount(channelId: string): number;
3
+ /**
4
+ * Credit one task-driver turn's effects to that task.
5
+ *
6
+ * The channel tally above answers "how much has happened here", which is the wrong question for
7
+ * the governor: it also counts the user's small talk, so every task in a busy channel looked like
8
+ * it had just made progress (continue at once, futile counter reset) while a genuinely spinning
9
+ * task hid behind its neighbours. The caller measures one turn as a delta of the channel tally —
10
+ * turns are serialized per channel — and credits it to the task that turn was dispatched for.
11
+ */
12
+ export declare function noteTaskEffects(channelId: string, taskId: string, delta: number): void;
13
+ /** Effects produced by this task's own driver turns so far (spec 031, D7). */
14
+ export declare function taskEffectCount(channelId: string, taskId: string): number;
3
15
  /** Test seam: drop all tallies. */
4
16
  export declare function resetChannelEffects(): void;
5
17
  /**
@@ -14,8 +14,12 @@ import { isRecord } from "../shared/type-guards.js";
14
14
  *
15
15
  * The tally lives in process memory, exactly like the driver's futile counter it feeds; a restart
16
16
  * resets both, which costs at most one extra round of patience before the governor intervenes.
17
+ *
18
+ * Two tallies are kept: one per channel (raw, the measurement point) and one per task, credited
19
+ * a turn at a time by the runtime. The governor reads the second — see `noteTaskEffects`.
17
20
  */
18
21
  const counts = new Map();
22
+ const taskCounts = new Map();
19
23
  /** Tools whose successful completion is, by itself, a visible change to the world. */
20
24
  const EFFECT_TOOLS = new Set(["write", "edit", "send_media", "subagent"]);
21
25
  export function noteChannelEffect(channelId) {
@@ -24,9 +28,32 @@ export function noteChannelEffect(channelId) {
24
28
  export function channelEffectCount(channelId) {
25
29
  return counts.get(channelId) ?? 0;
26
30
  }
31
+ function taskKey(channelId, taskId) {
32
+ return `${channelId}\0${taskId}`;
33
+ }
34
+ /**
35
+ * Credit one task-driver turn's effects to that task.
36
+ *
37
+ * The channel tally above answers "how much has happened here", which is the wrong question for
38
+ * the governor: it also counts the user's small talk, so every task in a busy channel looked like
39
+ * it had just made progress (continue at once, futile counter reset) while a genuinely spinning
40
+ * task hid behind its neighbours. The caller measures one turn as a delta of the channel tally —
41
+ * turns are serialized per channel — and credits it to the task that turn was dispatched for.
42
+ */
43
+ export function noteTaskEffects(channelId, taskId, delta) {
44
+ if (delta <= 0)
45
+ return;
46
+ const key = taskKey(channelId, taskId);
47
+ taskCounts.set(key, (taskCounts.get(key) ?? 0) + delta);
48
+ }
49
+ /** Effects produced by this task's own driver turns so far (spec 031, D7). */
50
+ export function taskEffectCount(channelId, taskId) {
51
+ return taskCounts.get(taskKey(channelId, taskId)) ?? 0;
52
+ }
27
53
  /** Test seam: drop all tallies. */
28
54
  export function resetChannelEffects() {
29
55
  counts.clear();
56
+ taskCounts.clear();
30
57
  }
31
58
  /**
32
59
  * Whether a completed tool call counts as an effect.
@@ -82,6 +82,8 @@ export declare class ChannelJobManager {
82
82
  private collectGarbage;
83
83
  get channel(): string;
84
84
  runningCount(): number;
85
+ /** Task ids that a still-running job on this channel promises to wake. See `channelJobTaskIds`. */
86
+ runningTaskIds(): Set<string>;
85
87
  /**
86
88
  * Launch a command in the background and return its job id. The wrapper writes merged
87
89
  * stdout/stderr to a spill file and the command's exit code to a sibling `.exit` file, then
@@ -156,6 +158,15 @@ interface JobRuntimeConfig {
156
158
  * bootstrap, before any turn runs; the tool layer builds managers lazily and picks this up.
157
159
  */
158
160
  export declare function configureJobRuntime(config: JobRuntimeConfig): void;
161
+ /**
162
+ * Which of this channel's tasks a running background job will wake, without needing an `Executor`.
163
+ *
164
+ * Read-only view for `/tasks doctor`: a parked task (`waiting`, no `wake`) is healthy exactly when
165
+ * something is going to call it. Managers are created lazily by the tool layer *and* eagerly at
166
+ * startup by `restoreChannelJobs`, so a channel with live jobs always has one; a channel with no
167
+ * manager simply has no jobs, and the empty set is the right answer.
168
+ */
169
+ export declare function channelJobTaskIds(channelId: string): Set<string>;
159
170
  export declare function getChannelJobManager(channelId: string, executor: Executor): ChannelJobManager;
160
171
  /**
161
172
  * Re-adopt every channel's persisted jobs at startup. Channels are discovered from the state
@@ -119,6 +119,16 @@ export class ChannelJobManager {
119
119
  runningCount() {
120
120
  return Array.from(this.jobs.values()).filter((job) => job.status === "running").length;
121
121
  }
122
+ /** Task ids that a still-running job on this channel promises to wake. See `channelJobTaskIds`. */
123
+ runningTaskIds() {
124
+ const ids = new Set();
125
+ for (const job of this.jobs.values()) {
126
+ if (job.status === "running" && job.contract.notify && job.contract.taskId) {
127
+ ids.add(job.contract.taskId);
128
+ }
129
+ }
130
+ return ids;
131
+ }
122
132
  /**
123
133
  * Launch a command in the background and return its job id. The wrapper writes merged
124
134
  * stdout/stderr to a spill file and the command's exit code to a sibling `.exit` file, then
@@ -454,6 +464,17 @@ let runtimeConfig = {};
454
464
  export function configureJobRuntime(config) {
455
465
  runtimeConfig = config;
456
466
  }
467
+ /**
468
+ * Which of this channel's tasks a running background job will wake, without needing an `Executor`.
469
+ *
470
+ * Read-only view for `/tasks doctor`: a parked task (`waiting`, no `wake`) is healthy exactly when
471
+ * something is going to call it. Managers are created lazily by the tool layer *and* eagerly at
472
+ * startup by `restoreChannelJobs`, so a channel with live jobs always has one; a channel with no
473
+ * manager simply has no jobs, and the empty set is the right answer.
474
+ */
475
+ export function channelJobTaskIds(channelId) {
476
+ return managers.get(channelId)?.runningTaskIds() ?? new Set();
477
+ }
457
478
  export function getChannelJobManager(channelId, executor) {
458
479
  let manager = managers.get(channelId);
459
480
  if (!manager) {
@@ -12,6 +12,37 @@
12
12
  import type { LoadedPromptResource, PromptBuildResult } from "./types.js";
13
13
  /** The design ceiling for everything Pipiclaw auto-appends to a turn (spec 026 §5.3). */
14
14
  export declare const AUTOMATIC_TURN_CONTEXT_BUDGET_UNITS = 3000;
15
+ /**
16
+ * Soft budget for the tool JSON schemas, in the same units as the prompt sections.
17
+ *
18
+ * Tool schemas are the larger half of the fixed per-turn cost and were the only part of it with
19
+ * no budget at all: the runtime-authored prompt is capped at 700 units while the schemas beside it
20
+ * run several thousand. They sit in the provider's cache prefix, so the steady-state price is low —
21
+ * but every `rebuildSessionTools` (a `skill_manage` write, `/reload`, any resource reload) swaps
22
+ * that prefix and pays for all of it again.
23
+ *
24
+ * There is no hard cap on purpose. A schema cannot be auto-trimmed the way a prompt section can:
25
+ * the fix is always a human deciding which tool says less, or which tool should not be registered.
26
+ * So this is a warning line in the log and in `/context`, not an enforcement point. It is set just
27
+ * above the current set (≈2.8k units for 15 tools) — one more heavyweight tool crosses it, which
28
+ * is exactly when someone should be looking.
29
+ */
30
+ export declare const TOOL_SCHEMA_TARGET_UNITS = 3000;
31
+ export interface ToolSchemaMeasurement {
32
+ chars: number;
33
+ units: number;
34
+ }
35
+ /** The one wording for "the tool set is over budget", shared by `/context` and the rebuild log. */
36
+ export declare function toolSchemaBudgetWarning(measurement: ToolSchemaMeasurement): string;
37
+ /**
38
+ * What the tool set costs on top of the system prompt. Counts what the provider is actually sent
39
+ * per tool — name, description and the JSON schema — the same way `/context` has always reported it.
40
+ */
41
+ export declare function measureToolSchemas(tools: Array<{
42
+ name: string;
43
+ description: string;
44
+ parameters?: unknown;
45
+ }>): ToolSchemaMeasurement;
15
46
  export interface PromptTurnContextStats {
16
47
  durableMemoryChars: number;
17
48
  durableMemoryUnits: number;
@@ -31,7 +62,7 @@ export interface PromptContextReportInput {
31
62
  description: string;
32
63
  }>;
33
64
  toolNames: string[];
34
- toolSchemaChars: number;
65
+ toolSchemas: ToolSchemaMeasurement;
35
66
  /** Resolved SOUL.md / AGENTS.md, for the independent body-budget lines. */
36
67
  soul?: LoadedPromptResource;
37
68
  agents?: LoadedPromptResource;
@@ -9,9 +9,44 @@
9
9
  * owns the same list that backs `/skill:name`, so `estimateSkillsPromptChars` lives
10
10
  * next to the report — not in the builder's budget path (spec 026 §9, §10.9).
11
11
  */
12
+ import { countPromptUnits } from "../../shared/prompt-units.js";
12
13
  import { estimateTokens, RUNTIME_PROMPT_TARGET_UNITS, sha256 } from "./builder.js";
13
14
  /** The design ceiling for everything Pipiclaw auto-appends to a turn (spec 026 §5.3). */
14
15
  export const AUTOMATIC_TURN_CONTEXT_BUDGET_UNITS = 3_000;
16
+ /**
17
+ * Soft budget for the tool JSON schemas, in the same units as the prompt sections.
18
+ *
19
+ * Tool schemas are the larger half of the fixed per-turn cost and were the only part of it with
20
+ * no budget at all: the runtime-authored prompt is capped at 700 units while the schemas beside it
21
+ * run several thousand. They sit in the provider's cache prefix, so the steady-state price is low —
22
+ * but every `rebuildSessionTools` (a `skill_manage` write, `/reload`, any resource reload) swaps
23
+ * that prefix and pays for all of it again.
24
+ *
25
+ * There is no hard cap on purpose. A schema cannot be auto-trimmed the way a prompt section can:
26
+ * the fix is always a human deciding which tool says less, or which tool should not be registered.
27
+ * So this is a warning line in the log and in `/context`, not an enforcement point. It is set just
28
+ * above the current set (≈2.8k units for 15 tools) — one more heavyweight tool crosses it, which
29
+ * is exactly when someone should be looking.
30
+ */
31
+ export const TOOL_SCHEMA_TARGET_UNITS = 3_000;
32
+ /** The one wording for "the tool set is over budget", shared by `/context` and the rebuild log. */
33
+ export function toolSchemaBudgetWarning(measurement) {
34
+ return `tool JSON schemas are ${measurement.units} units (${measurement.chars} chars), over the ${TOOL_SCHEMA_TARGET_UNITS} unit target. Shorten a tool description, move detail into a playbook, or unregister a tool; \`/context detail\` lists the set.`;
35
+ }
36
+ /**
37
+ * What the tool set costs on top of the system prompt. Counts what the provider is actually sent
38
+ * per tool — name, description and the JSON schema — the same way `/context` has always reported it.
39
+ */
40
+ export function measureToolSchemas(tools) {
41
+ let chars = 0;
42
+ let units = 0;
43
+ for (const tool of tools) {
44
+ const text = `${tool.name}${tool.description}${JSON.stringify(tool.parameters ?? {})}`;
45
+ chars += text.length;
46
+ units += countPromptUnits(text);
47
+ }
48
+ return { chars, units };
49
+ }
15
50
  /**
16
51
  * What pi's `<available_skills>` block will cost, close enough to report on:
17
52
  * name, description and location inside a five-line XML wrapper, plus the preamble.
@@ -82,7 +117,8 @@ export function renderContextReport(input) {
82
117
  lines.push(agentsLine);
83
118
  }
84
119
  lines.push("");
85
- lines.push(`Tools: ${input.toolNames.length} registered; JSON schemas ≈ ${formatNumber(input.toolSchemaChars)} chars (billed on top of the system prompt)`);
120
+ const overToolBudget = input.toolSchemas.units > TOOL_SCHEMA_TARGET_UNITS;
121
+ lines.push(`Tools: ${input.toolNames.length} registered; JSON schemas ≈ ${formatNumber(input.toolSchemas.units)} / ${formatNumber(TOOL_SCHEMA_TARGET_UNITS)} units, ${formatNumber(input.toolSchemas.chars)} chars${overToolBudget ? " — over target" : ""} (billed on top of the system prompt)`);
86
122
  lines.push(`Skills: ${input.skills.length} visible, ≈${formatNumber(estimateSkillsPromptChars(input.skills))} chars (rendered and managed by pi, not budgeted by Pipiclaw)`);
87
123
  if (input.lastTurn) {
88
124
  const turn = input.lastTurn;
@@ -95,12 +131,15 @@ export function renderContextReport(input) {
95
131
  lines.push(`- durable bootstrap: ${formatNumber(turn.durableMemoryUnits)} units / ${formatNumber(turn.durableMemoryChars)} chars`);
96
132
  lines.push(`- user message: ${formatNumber(turn.userMessageChars)} chars (not automatic; not capped here)`);
97
133
  }
98
- if (build.diagnostics.length > 0) {
134
+ if (build.diagnostics.length > 0 || overToolBudget) {
99
135
  lines.push("");
100
136
  lines.push("Diagnostics:");
101
137
  for (const diagnostic of build.diagnostics) {
102
138
  lines.push(`- [${diagnostic.level}] ${diagnostic.sectionId}: ${diagnostic.message}`);
103
139
  }
140
+ if (overToolBudget) {
141
+ lines.push(`- [warning] tools: ${toolSchemaBudgetWarning(input.toolSchemas)}`);
142
+ }
104
143
  }
105
144
  if (detail) {
106
145
  lines.push("");
@@ -41,6 +41,8 @@ Pipiclaw 不内置或假设第三方 agent 工具的命令、状态 JSON、检
41
41
  2. **稳定的完成态检测命令**:只有状态查询、没有阻塞等待时,按 `event-scheduling.md` 用 periodic + preAction 门控——对方忙就静默跳过,零 token。
42
42
  3. **wake 轮询(兜底)**:两者都没有时才用,`progress` 置 `waiting` + 合理 `wake`,醒来查状态、更新证据、必要时把 wake 推后。
43
43
 
44
+ 两种等待形态就这两个(本节是唯一真相源):**`waiting` 且无 `wake` = 停泊**,driver 不会来打扰,只有后台作业结束、用户消息或 `/tasks run` 会叫醒你;**`waiting` + `wake` = 定时回访**,到点由 driver 接续。
45
+
44
46
  无论走哪条,三条纪律不变:
45
47
 
46
48
  1. 委派时把工具、实例标识、工作目录/分支、预期产物和验收方法写进 task 正文,等谁、等什么写进 `blockedReason`。重启后这些是唯一能恢复现场的东西。
@@ -26,7 +26,9 @@ priority: 41
26
26
 
27
27
  ## 等待与继续
28
28
 
29
- - 等用户/外部系统/委派:`waiting` + 合理 `wake`,把等谁、等什么写进 `blockedReason`。
29
+ - 等一个会自己叫醒你的信号(后台作业结束、用户回话):`waiting` **且不设 `wake`** —— 这是停泊,driver 不会来打扰;等待形态的完整选择见 `task-delegation.md`。
30
+ - 等一个没人会通知的外部状态:`waiting` + 合理 `wake`,到点回访。
31
+ - 两者都把等谁、等什么写进 `blockedReason`。
30
32
  - 当前仍可继续:保持 `active`,清空 `wake`。
31
33
  - 明确停止:由用户 pause;不要用极远的 `wake` 模拟暂停。
32
34
 
@@ -55,9 +57,10 @@ priority: 41
55
57
 
56
58
  ## 不唤醒或频繁唤醒
57
59
 
58
- 可推进 = 非 done/cancelled/paused,且 `wake` 缺失、无效或已到期。
60
+ 可推进 = 非 done/cancelled/paused、非停泊(`waiting` 且无 `wake`),且 `wake` 缺失、无效或已到期。
59
61
 
60
- - `paused`:用户 `/tasks resume <id>`。
62
+ - 停泊中:这是有意的,等外部信号即可;确认没人会来叫时用 `/tasks run <id>` 或改回 `active`。
63
+ - `paused`:用户 `/tasks resume <id>`;若是治理器因预算耗尽暂停,得先 `/tasks set <id> attempts <n>` 放宽,否则 resume 会被拒绝。
61
64
  - `wake` 太远:纠正 `wake`;急催用 `/tasks run <id>`。
62
65
  - TUI 已关闭:没有 daemon,不能自动唤醒。
63
66
  - 反复空转:查最新 note 和 `nextAction`,修 Manual。
@@ -28,7 +28,7 @@ priority: 40
28
28
 
29
29
  - `priority` / `deadline`:表达调度重要性和硬期限,不用 `wake` 冒充 deadline。
30
30
  - `nextAction`:下一条可执行动作,避免写抽象愿望。
31
- - `maxAttempts`:唯一的按任务停止条件,按风险和规模收紧。它在**本周期、回合边界**检查,不会中断正在运行的单个回合。
31
+ - `maxAttempts`:唯一的按任务停止条件,默认 12,按风险和规模调整。它在**本周期、回合边界**检查,不会中断正在运行的单个回合。周期任务每开一个新周期清零,**一次性任务则是终身额度**——预计要十几步以上的长程任务,创建时就把它调高,不要等治理器把任务停掉再补。
32
32
  - `sideEffects`:`workspace` 或 `external`。发送、发布、部署、修改外部系统必须选 `external`,它会要求用户 `/tasks approve` 后才能 done。
33
33
  - 任务之间没有父子或依赖字段。需要表达先后次序时写进 `goal`/`manual`,或用 `wake` 把后续任务排到合适的时间;每个任务只按自己的 DoD 收尾。
34
34
 
@@ -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";
@@ -596,7 +597,9 @@ export function createRuntimeContext(options) {
596
597
  text: event.text,
597
598
  isBot: false,
598
599
  }, "user message");
599
- 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);
600
603
  const builtInCommand = parseBuiltInCommand(event.text);
601
604
  if (builtInCommand) {
602
605
  log.logEvent("info", "runtime.command.started", "Executing command", {
@@ -639,8 +642,15 @@ export function createRuntimeContext(options) {
639
642
  if (!_isEvent) {
640
643
  ctx.primeCard(350);
641
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);
642
649
  const result = await runner.run(ctx, store);
643
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
+ }
644
654
  if (taskDriverMatch?.[1] && result.usage && result.durationMs !== undefined) {
645
655
  await finishTaskAttempt(getChannelDir(options.paths.workspaceDir, event.channelId), taskDriverMatch[1], {
646
656
  tokens: result.usage.total,
@@ -729,6 +739,19 @@ export function createRuntimeContext(options) {
729
739
  },
730
740
  intervalMs: options.memoryMaintenanceSchedulerIntervalMs,
731
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
+ };
732
755
  const taskDriver = options.createTaskDriver
733
756
  ? options.createTaskDriver()
734
757
  : new TaskDriver({
@@ -737,12 +760,12 @@ export function createRuntimeContext(options) {
737
760
  isChannelActive: (channelId) => channelRunners.get(channelId)?.isBusy() ?? false,
738
761
  dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
739
762
  onDispatch: options.onTaskDriverDispatch,
740
- getEffectCount: channelEffectCount,
763
+ getEffectCount: taskEffectCount,
741
764
  getSettings: () => {
742
765
  runtimeSettingsManager.reload();
743
766
  return runtimeSettingsManager.getTaskDriverSettings();
744
767
  },
745
- isEnabled: () => loadToolsConfig(options.paths.appHomeDir).tools.tasks.enabled,
768
+ isEnabled: tasksToolEnabled,
746
769
  });
747
770
  const shutdownWithReason = async (reason = "manual") => {
748
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,7 +129,7 @@ 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);
127
134
  // The header carries elapsed time and a step count, so it changes on every update:
128
135
  // an append-only delta would leave a stale header on the card.
@@ -204,7 +211,7 @@ class ChannelDeliveryController {
204
211
  while (this.appliedRevision < this.desiredRevision) {
205
212
  const mode = this.mode;
206
213
  const body = this.getProgressText();
207
- const progressText = mode === "progress" && this.bot.progressStyle === "rolling" && body
214
+ const progressText = mode === "progress" && this.progressStyle === "rolling" && body
208
215
  ? `${this.buildRollingHeader()}\n\n${body}`
209
216
  : body;
210
217
  const throttleBaseAt = this.lastDeliveredAt > 0 ? this.lastDeliveredAt : this.progressWindowStartedAt;
@@ -245,8 +252,8 @@ class ChannelDeliveryController {
245
252
  }
246
253
  else if (mode === "finalize-existing") {
247
254
  if (content || this.cardWarmupTriggered) {
248
- const finalProgressText = this.bot.progressStyle === "rolling" ? this.buildSummaryText() : progressText;
249
- 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);
250
257
  if (!touchedRemote) {
251
258
  this.bot.discardCard(this.event.channelId);
252
259
  }
@@ -401,6 +408,16 @@ class ChannelDeliveryController {
401
408
  return `完成 · ${this.toolCallCount} 步 · ${this.formatElapsed(this.elapsedMs())}`;
402
409
  }
403
410
  }
404
- export function createDingTalkContext(event, bot, store) {
405
- 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();
406
423
  }
@@ -1,8 +1,9 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { readdir, readFile } from "node:fs/promises";
3
3
  import { join, resolve, sep } from "node:path";
4
+ import { channelJobTaskIds } from "../agent/job-manager.js";
4
5
  import { parseTaskEventName, taskEventPrefix } from "../shared/task-events.js";
5
- import { extractTaskTitle, missingStandardTaskSections, normalizeTaskId, readActiveTasks, } from "../shared/task-ledger.js";
6
+ import { extractTaskTitle, isTaskParked, missingStandardTaskSections, normalizeTaskId, readActiveTasks, } from "../shared/task-ledger.js";
6
7
  import { errorMessage } from "../shared/text-utils.js";
7
8
  import { isRecord } from "../shared/type-guards.js";
8
9
  import { applyTaskControlPatch, createDefaultTaskControl, retiredTaskControlKeys, TASK_PRIORITIES, taskBudgetViolation, } from "../tasks/control.js";
@@ -276,6 +277,29 @@ export async function pauseTask(options, idInput) {
276
277
  await writeStoredTask(task);
277
278
  return `已暂停任务 ${id}。需要继续时用 /tasks resume ${id}。`;
278
279
  }
280
+ /**
281
+ * Why restarting this task would immediately stop it again, or `undefined` when it is free to run.
282
+ *
283
+ * The governor pauses on the same condition it re-checks on the next scan, so a plain resume of a
284
+ * budget/deadline-exhausted task looked like it worked, cost one escalation turn, and landed back
285
+ * in `paused` minutes later — while three separate places (the `/stop` receipt, `/tasks` usage,
286
+ * the driving playbook) told the user resume was the fix. Refuse instead, and name the command
287
+ * that actually unblocks it.
288
+ */
289
+ function restartBlockedMessage(id, control) {
290
+ if (!control)
291
+ return undefined;
292
+ const violation = taskBudgetViolation(control, Date.now());
293
+ if (!violation)
294
+ return undefined;
295
+ return [
296
+ `任务 ${id} 仍然超出治理限额:${violation}。`,
297
+ "直接恢复只会在下一轮扫描中被治理器再次暂停,并白白多花一个回合。",
298
+ `先放宽限额:\`/tasks set ${id} attempts <n>\`(当前上限 ${control.budget.maxAttempts})` +
299
+ `${control.deadline ? `,或 \`/tasks set ${id} deadline <ISO8601>\`(当前 ${control.deadline})` : ""},然后再试一次。`,
300
+ "若这个任务已经不该继续,用 `task_manage cancel` 关掉它。",
301
+ ].join("\n");
302
+ }
279
303
  export async function resumeTask(options, idInput) {
280
304
  const id = normalizeTaskId(idInput);
281
305
  const task = await readStoredTask(options.channelDir, id);
@@ -284,6 +308,9 @@ export async function resumeTask(options, idInput) {
284
308
  const from = normalizeStoredStatus(task.fields.status);
285
309
  if (from !== "paused")
286
310
  return `任务 ${id} 当前是 ${from},并非暂停状态。`;
311
+ const blocked = restartBlockedMessage(id, task.fields.control);
312
+ if (blocked)
313
+ return blocked;
287
314
  resolveTaskTransition("resume", id, from);
288
315
  task.fields.status = "active";
289
316
  task.fields.wake = undefined;
@@ -361,6 +388,9 @@ async function runTask(options, idInput) {
361
388
  catch (error) {
362
389
  return errorMessage(error);
363
390
  }
391
+ const blocked = restartBlockedMessage(id, task.fields.control);
392
+ if (blocked)
393
+ return blocked;
364
394
  task.fields.status = "active";
365
395
  task.fields.wake = undefined;
366
396
  if (task.fields.control) {
@@ -478,6 +508,7 @@ async function doctor(options) {
478
508
  const activeIds = new Set(entries.map((entry) => entry.id));
479
509
  const archivedIds = await readArchivedTaskIds(options.channelDir);
480
510
  const events = await readTaskEvents(options.workspaceDir, options.channelId);
511
+ const runningJobTaskIds = channelJobTaskIds(options.channelId);
481
512
  const issues = [];
482
513
  for (const entry of entries) {
483
514
  const status = entry.frontmatter.status ?? "active";
@@ -534,6 +565,14 @@ async function doctor(options) {
534
565
  issues.push(issue(`tasks/${entry.id}.md is missing standard section(s): ${missing.join(", ")}.`, `Ask the agent to normalize tasks/${entry.id}.md to the standard task skeleton.`));
535
566
  }
536
567
  }
568
+ // A parked task is waiting for someone to call it: a finished background job, a user
569
+ // message, or `/tasks run`. The driver deliberately will not (see `isTaskParked`), so with
570
+ // no running job carrying this id, whether it ever resumes is entirely up to the user.
571
+ // That is legitimate when it is waiting on an answer — and indistinguishable, on disk,
572
+ // from a task everyone has forgotten. Report the fact and name every way out.
573
+ if (isTaskParked(entry.frontmatter) && !runningJobTaskIds.has(entry.id)) {
574
+ issues.push(issue(`tasks/${entry.id}.md is parked (waiting, no wake) and no running background job will wake it.`, `It resumes only when you reply to it, run /tasks run ${entry.id}, or give it a wake with /tasks set ${entry.id} wake <ISO8601>; cancel it if what it waits for is gone.`));
575
+ }
537
576
  if (entry.frontmatter.wake && validWakeMs(entry) === undefined) {
538
577
  issues.push(issue(`tasks/${entry.id}.md has an invalid wake value (${entry.frontmatter.wake}); the native driver will treat it as due.`, `Use task_manage set or progress to replace wake with ISO8601, or clear it if the task should continue now.`));
539
578
  }
@@ -10,10 +10,10 @@ export interface TaskDriverOptions {
10
10
  onDispatch?: (event: DingTalkEvent, accepted: boolean) => void;
11
11
  getSettings: () => PipiclawTaskDriverSettings;
12
12
  /**
13
- * Externally visible effects recorded for a channel so far (spec 031, D7). Defaults to a
14
- * constant, which simply makes the fingerprint depend on ledger fields alone.
13
+ * Externally visible effects produced by this task's own turns so far (spec 031, D7).
14
+ * Defaults to a constant, which simply makes the fingerprint depend on ledger fields alone.
15
15
  */
16
- getEffectCount?: (channelId: string) => number;
16
+ getEffectCount?: (channelId: string, taskId: string) => number;
17
17
  /** Master autonomy switch (`tools.tasks.enabled`); re-read every tick. Defaults to on. */
18
18
  isEnabled?: () => boolean;
19
19
  /** Test-only override for the idle-sleep cap; production uses `settings.maxSleepMinutes`. */
@@ -49,8 +49,9 @@ function attemptKey(channelId, taskId) {
49
49
  *
50
50
  * `latestNote` is deliberately absent (spec 031, D7): it is the model's own account of its work,
51
51
  * so including it let a wake that did nothing but append a note reset the futile counter forever,
52
- * and let a wake that changed real files count as stalled. The channel's effect tally stands in
53
- * for the work itself instead.
52
+ * and let a wake that changed real files count as stalled. The task's own effect tally stands in
53
+ * for the work itself instead — per task, not per channel, so a neighbour's activity (including
54
+ * the user chatting) neither certifies progress here nor hides a task that is spinning.
54
55
  */
55
56
  function taskFingerprint(entry, effects) {
56
57
  const control = entry.frontmatter.control;
@@ -76,7 +77,7 @@ function taskFingerprint(entry, effects) {
76
77
  * fatal for the "drive an external agent in small steps" shape this driver exists for.
77
78
  *
78
79
  * So the tiers are keyed on evidence, not on the boolean "something changed":
79
- * - the channel's effect tally grew ⇒ the last wake actually did something ⇒ continue at once;
80
+ * - this task's effect tally grew ⇒ its last wake actually did something ⇒ continue at once;
80
81
  * - the ledger changed with no effect (status/note churn) ⇒ the ordinary continuation delay;
81
82
  * - nothing changed ⇒ the long stalled-retry backoff, and the futile counter keeps running.
82
83
  *
@@ -397,7 +398,7 @@ export class TaskDriver {
397
398
  log.logInfo(`[${channelId}] Task driver opened cycle ${opened.cycleId} for ${entry.id}`);
398
399
  }
399
400
  const key = attemptKey(channelId, entry.id);
400
- const effects = this.options.getEffectCount?.(channelId) ?? 0;
401
+ const effects = this.options.getEffectCount?.(channelId, entry.id) ?? 0;
401
402
  const fingerprint = taskFingerprint(entry, effects);
402
403
  const previous = this.attempts.get(key);
403
404
  if (!isEligible(previous, fingerprint, effects, nowMs, settings))
@@ -171,9 +171,19 @@ export declare class PipiclawSettingsManager {
171
171
  private settings;
172
172
  private loadErrors;
173
173
  private retiredKeys;
174
+ /** The file's change token as of the last actual parse; see `reload`. */
175
+ private loadedStamp;
174
176
  constructor(baseDir: string);
175
177
  private load;
176
178
  private save;
179
+ /**
180
+ * Re-read `settings.json`, but only when the file actually changed.
181
+ *
182
+ * The task driver and the memory scheduler call this on every tick — and the driver ticks
183
+ * after every turn — so an unchanged file was being read, JSON-parsed and scanned for retired
184
+ * keys many times a minute. Skipping keeps the last parse *and* its diagnostics, which is the
185
+ * same thing a re-parse of identical bytes would produce.
186
+ */
177
187
  reload(): void;
178
188
  drainErrors(): SettingsError[];
179
189
  getDiagnostics(): ConfigDiagnostic[];
package/dist/settings.js CHANGED
@@ -10,6 +10,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
10
10
  import { dirname, join } from "path";
11
11
  import * as log from "./log.js";
12
12
  import { getMemoryMaintenanceTuning, getSessionRefreshCadence, } from "./memory/maintenance-tuning.js";
13
+ import { fileStamp } from "./shared/file-stamp.js";
13
14
  const DEFAULT_TUI = {
14
15
  responseMode: "full_progress_then_plain_final",
15
16
  };
@@ -138,12 +139,15 @@ export class PipiclawSettingsManager {
138
139
  constructor(baseDir) {
139
140
  this.loadErrors = [];
140
141
  this.retiredKeys = [];
142
+ /** The file's change token as of the last actual parse; see `reload`. */
143
+ this.loadedStamp = "";
141
144
  this.settingsPath = join(baseDir, "settings.json");
142
145
  this.settings = this.load();
143
146
  }
144
147
  load() {
145
148
  this.loadErrors = [];
146
149
  this.retiredKeys = [];
150
+ this.loadedStamp = fileStamp(this.settingsPath);
147
151
  if (!existsSync(this.settingsPath)) {
148
152
  return {};
149
153
  }
@@ -180,7 +184,17 @@ export class PipiclawSettingsManager {
180
184
  log.logWarning(`Could not save settings file`, `${this.settingsPath}\n${String(error)}`);
181
185
  }
182
186
  }
187
+ /**
188
+ * Re-read `settings.json`, but only when the file actually changed.
189
+ *
190
+ * The task driver and the memory scheduler call this on every tick — and the driver ticks
191
+ * after every turn — so an unchanged file was being read, JSON-parsed and scanned for retired
192
+ * keys many times a minute. Skipping keeps the last parse *and* its diagnostics, which is the
193
+ * same thing a re-parse of identical bytes would produce.
194
+ */
183
195
  reload() {
196
+ if (fileStamp(this.settingsPath) === this.loadedStamp)
197
+ return;
184
198
  this.settings = this.load();
185
199
  }
186
200
  drainErrors() {
@@ -0,0 +1,10 @@
1
+ /**
2
+ * A cheap change token for a config file: `mtime:ctime:size`, or `""` when the file
3
+ * cannot be stat'ed (missing or unreadable — itself a stable state worth caching).
4
+ *
5
+ * Used by the hot re-read paths (`settings.json` on every driver/maintenance tick,
6
+ * `tools.json` on every driver tick) to skip a JSON parse when nothing changed. Same
7
+ * triple as the task-ledger parse cache: mtime alone misses an atomic-rename overwrite
8
+ * that preserves the timestamp, ctime catches the rename, size catches the rest.
9
+ */
10
+ export declare function fileStamp(path: string): string;
@@ -0,0 +1,19 @@
1
+ import { statSync } from "node:fs";
2
+ /**
3
+ * A cheap change token for a config file: `mtime:ctime:size`, or `""` when the file
4
+ * cannot be stat'ed (missing or unreadable — itself a stable state worth caching).
5
+ *
6
+ * Used by the hot re-read paths (`settings.json` on every driver/maintenance tick,
7
+ * `tools.json` on every driver tick) to skip a JSON parse when nothing changed. Same
8
+ * triple as the task-ledger parse cache: mtime alone misses an atomic-rename overwrite
9
+ * that preserves the timestamp, ctime catches the rename, size catches the rest.
10
+ */
11
+ export function fileStamp(path) {
12
+ try {
13
+ const stats = statSync(path);
14
+ return `${stats.mtimeMs}:${stats.ctimeMs}:${stats.size}`;
15
+ }
16
+ catch {
17
+ return "";
18
+ }
19
+ }
@@ -35,7 +35,7 @@ export interface TaskLedgerEntry {
35
35
  /** First `# ` heading in the body, or the id when none. */
36
36
  title: string;
37
37
  frontmatter: TaskFrontmatter;
38
- /** status ≠ done AND (no valid wake OR wake ≤ now). Matches the sensor exactly. */
38
+ /** Non-terminal, not parked (`waiting` without a wake), and (no valid wake OR wake ≤ now). */
39
39
  actionable: boolean;
40
40
  /** Milliseconds since epoch parsed from `wake`, or undefined when unset/unparseable. */
41
41
  wakeMs?: number;
@@ -93,7 +93,18 @@ export declare function parseTaskFrontmatter(content: string): TaskFrontmatter;
93
93
  * The single shared judgement: is there work to do on this task right now?
94
94
  * Unreadable frontmatter is fail-open (actionable) so a corrupt ledger surfaces
95
95
  * rather than being silently skipped.
96
+ *
97
+ * `waiting` with no `wake` is the *parked* form (`src/tasks/transitions.ts`): the task is
98
+ * blocked on an external signal — a background job finishing, the user answering, `/tasks run` —
99
+ * and only that signal may resume it. Without this the runtime's own recommended shape for
100
+ * delegating work (start a blocking wait as a `bash async` job, park the task, end the turn)
101
+ * was re-dispatched the instant the turn ended, found the job still running, answered
102
+ * `[SILENT]`, and after three such wakes got paused by the governor. A `waiting` task that
103
+ * *does* carry a wake is an ordinary timed re-check and stays gated on that wake; an
104
+ * unparseable wake still fails open so a hand-edited file surfaces rather than parks forever.
96
105
  */
106
+ /** `waiting` with no `wake`: the driver will not come back on its own. See `isTaskActionable`. */
107
+ export declare function isTaskParked(frontmatter: TaskFrontmatter): boolean;
97
108
  export declare function isTaskActionable(frontmatter: TaskFrontmatter, now: number): boolean;
98
109
  /** First `# ` heading after the frontmatter block, or the id when there is none. */
99
110
  export declare function extractTaskTitle(content: string, fallbackId: string): string;
@@ -115,7 +115,20 @@ export function parseTaskFrontmatter(content) {
115
115
  * The single shared judgement: is there work to do on this task right now?
116
116
  * Unreadable frontmatter is fail-open (actionable) so a corrupt ledger surfaces
117
117
  * rather than being silently skipped.
118
+ *
119
+ * `waiting` with no `wake` is the *parked* form (`src/tasks/transitions.ts`): the task is
120
+ * blocked on an external signal — a background job finishing, the user answering, `/tasks run` —
121
+ * and only that signal may resume it. Without this the runtime's own recommended shape for
122
+ * delegating work (start a blocking wait as a `bash async` job, park the task, end the turn)
123
+ * was re-dispatched the instant the turn ended, found the job still running, answered
124
+ * `[SILENT]`, and after three such wakes got paused by the governor. A `waiting` task that
125
+ * *does* carry a wake is an ordinary timed re-check and stays gated on that wake; an
126
+ * unparseable wake still fails open so a hand-edited file surfaces rather than parks forever.
118
127
  */
128
+ /** `waiting` with no `wake`: the driver will not come back on its own. See `isTaskActionable`. */
129
+ export function isTaskParked(frontmatter) {
130
+ return frontmatter.readable && frontmatter.status === "waiting" && !frontmatter.wake;
131
+ }
119
132
  export function isTaskActionable(frontmatter, now) {
120
133
  if (!frontmatter.readable)
121
134
  return true;
@@ -124,6 +137,8 @@ export function isTaskActionable(frontmatter, now) {
124
137
  // status is already canonicalised by parseTaskFrontmatter.
125
138
  if (TERMINAL_TASK_STATUSES.has(frontmatter.status ?? ""))
126
139
  return false;
140
+ if (isTaskParked(frontmatter))
141
+ return false;
127
142
  const wakeAt = parseWakeMs(frontmatter);
128
143
  if (wakeAt !== undefined && wakeAt > now)
129
144
  return false;
@@ -8,7 +8,8 @@
8
8
  * the `/tasks` command handlers, so an illegal transition always fails the same way.
9
9
  *
10
10
  * active → dispatchable now (wake-gated: not yet due ⇒ sleep until wake)
11
- * waiting → sleep until wake, then dispatch
11
+ * waiting → with a wake: sleep until it, then dispatch. Without one: parked — the driver
12
+ * never wakes it; a job completion, a user message or `/tasks run` does.
12
13
  * verifying → dispatch a checker-only turn
13
14
  * paused → never dispatched (excluded at the driver scan layer, zero token)
14
15
  * done → recurring: reopen next cycle at wake; otherwise archived
@@ -9,7 +9,8 @@ import { RecoverableToolError } from "../shared/recoverable-error.js";
9
9
  * the `/tasks` command handlers, so an illegal transition always fails the same way.
10
10
  *
11
11
  * active → dispatchable now (wake-gated: not yet due ⇒ sleep until wake)
12
- * waiting → sleep until wake, then dispatch
12
+ * waiting → with a wake: sleep until it, then dispatch. Without one: parked — the driver
13
+ * never wakes it; a job completion, a user message or `/tasks run` does.
13
14
  * verifying → dispatch a checker-only turn
14
15
  * paused → never dispatched (excluded at the driver scan layer, zero token)
15
16
  * done → recurring: reopen next cycle at wake; otherwise archived
@@ -7,7 +7,7 @@ import { invalidateTaskVerification } from "../../tasks/control.js";
7
7
  import { taskBodyHash } from "../../tasks/store.js";
8
8
  import { normalizeStoredStatus, resolveTaskTransition } from "../../tasks/transitions.js";
9
9
  import { RecoverableToolError } from "../tool-details.js";
10
- import { appendCompletionEvidence, applySet, cleanupTaskEvents, markdownValue, readTaskDocument, renderTaskFile, requiredField, tasksDir, } from "./shared.js";
10
+ import { appendCompletionEvidence, applySet, cleanupTaskEvents, describeTaskSchedule, markdownValue, readTaskDocument, renderTaskFile, requiredField, tasksDir, } from "./shared.js";
11
11
  import { assertVerificationAttestationMatches } from "./verification.js";
12
12
  export async function setTask(options, request) {
13
13
  if (!request.id)
@@ -29,7 +29,7 @@ export async function setTask(options, request) {
29
29
  id,
30
30
  path: taskPath,
31
31
  status: nextFields.status,
32
- notice: `已更新任务 \`${id}\`(status: ${nextFields.status}${nextFields.wake ? `, wake: ${nextFields.wake}` : ""})。`,
32
+ notice: `已更新任务 \`${id}\`(${describeTaskSchedule(nextFields)})。`,
33
33
  };
34
34
  }
35
35
  export async function progressTask(options, request) {
@@ -58,7 +58,7 @@ export async function progressTask(options, request) {
58
58
  id,
59
59
  path: taskPath,
60
60
  status: nextFields.status,
61
- notice: `已记录任务 \`${id}\` 的进展(status: ${nextFields.status}${nextFields.wake ? `, wake: ${nextFields.wake}` : ""})。`,
61
+ notice: `已记录任务 \`${id}\` 的进展(${describeTaskSchedule(nextFields)})。`,
62
62
  };
63
63
  }
64
64
  export async function doneTask(options, request) {
@@ -15,12 +15,10 @@ export declare const taskManageSchema: Type.TObject<{
15
15
  deadline: Type.TOptional<Type.TString>;
16
16
  nextAction: Type.TOptional<Type.TString>;
17
17
  blockedReason: Type.TOptional<Type.TString>;
18
- parent: Type.TOptional<Type.TString>;
19
- dependsOn: Type.TOptional<Type.TArray<Type.TString>>;
20
18
  sideEffects: Type.TOptional<Type.TUnion<[Type.TLiteral<"workspace">, Type.TLiteral<"external">]>>;
21
19
  externalApproval: Type.TOptional<Type.TUnion<[Type.TLiteral<"not-required">, Type.TLiteral<"required">]>>;
22
20
  maxAttempts: Type.TOptional<Type.TInteger>;
23
- verificationMode: Type.TOptional<Type.TUnion<[Type.TLiteral<"evidence">, Type.TLiteral<"independent">]>>;
21
+ verificationRequired: Type.TOptional<Type.TBoolean>;
24
22
  }>>;
25
23
  status: Type.TOptional<Type.TUnion<Type.TLiteral<"active" | "waiting" | "paused">[]>>;
26
24
  wake: Type.TOptional<Type.TString>;
@@ -7,17 +7,18 @@ const taskControlSchema = Type.Object({
7
7
  deadline: Type.Optional(Type.String({ description: "ISO8601 deadline; empty string clears it." })),
8
8
  nextAction: Type.Optional(Type.String({ description: "Concrete next executable step; empty string clears it." })),
9
9
  blockedReason: Type.Optional(Type.String({ description: "Why work cannot currently proceed; empty clears it." })),
10
- parent: Type.Optional(Type.String({ description: "Parent task id; empty clears it." })),
11
- dependsOn: Type.Optional(Type.Array(Type.String(), { description: "Task ids that must be done first." })),
12
10
  sideEffects: Type.Optional(Type.Union([Type.Literal("workspace"), Type.Literal("external")], {
13
11
  description: '"external" (sending, publishing, deploying, changing an outside system) requires user approval via "/tasks approve" before done.',
14
12
  })),
15
13
  externalApproval: Type.Optional(Type.Union([Type.Literal("not-required"), Type.Literal("required")], {
16
14
  description: 'External approval can only be granted by a user with "/tasks approve <id>".',
17
15
  })),
18
- maxAttempts: Type.Optional(Type.Integer({ minimum: 1, description: "Per-cycle attempt stop-loss; the only per-task budget." })),
19
- verificationMode: Type.Optional(Type.Union([Type.Literal("evidence"), Type.Literal("independent")], {
20
- description: 'On create, defaults to "evidence" (maker self-checks the DoD against concrete evidence). Set "independent" only when the task produces a checkable artifact (code, config, a runnable command) that a separate read-only verifier sub-agent can inspect — for research/writing/reminder-style tasks, "evidence" is cheaper and just as trustworthy.',
16
+ maxAttempts: Type.Optional(Type.Integer({
17
+ minimum: 1,
18
+ description: "Attempt stop-loss; the only per-task budget. Default 12, spent over the whole task (recurring: per cycle) — raise it on create for long multi-step work.",
19
+ })),
20
+ verificationRequired: Type.Optional(Type.Boolean({
21
+ description: "Whether done requires an independent verifier attestation. Default false; set true only when the task produces a checkable artifact (code, config, a runnable command) a read-only verifier sub-agent can inspect.",
21
22
  })),
22
23
  });
23
24
  export const taskManageSchema = Type.Object({
@@ -19,6 +19,14 @@ export declare function readTaskDocument(taskPath: string, id: string, allowCont
19
19
  fields: TaskFields;
20
20
  body: string;
21
21
  }>;
22
+ /**
23
+ * The scheduling half of a lifecycle notice: where the task stands and who will wake it.
24
+ *
25
+ * Parking (`waiting` with no wake) is the one state whose consequence is not obvious from the
26
+ * status alone — the driver deliberately never returns to it — so the notice says so at the
27
+ * moment the model chooses it, rather than leaving it to be rediscovered by a task that goes quiet.
28
+ */
29
+ export declare function describeTaskSchedule(fields: TaskFields): string;
22
30
  /** Apply a `set` request's optional fields onto the existing frontmatter. */
23
31
  export declare function applySet(fields: TaskFields, request: TaskManageRequest): TaskFields;
24
32
  /**
@@ -110,10 +110,26 @@ export async function readTaskDocument(taskPath, id, allowControlRepair = false)
110
110
  body: taskBody(content),
111
111
  };
112
112
  }
113
+ /**
114
+ * The scheduling half of a lifecycle notice: where the task stands and who will wake it.
115
+ *
116
+ * Parking (`waiting` with no wake) is the one state whose consequence is not obvious from the
117
+ * status alone — the driver deliberately never returns to it — so the notice says so at the
118
+ * moment the model chooses it, rather than leaving it to be rediscovered by a task that goes quiet.
119
+ */
120
+ export function describeTaskSchedule(fields) {
121
+ if (fields.status === "waiting" && !fields.wake) {
122
+ return "status: waiting(已停泊:driver 不会再叫你,等后台作业结束、用户消息或 /tasks run)";
123
+ }
124
+ return `status: ${fields.status}${fields.wake ? `, wake: ${fields.wake}` : ""}`;
125
+ }
113
126
  /** Apply a `set` request's optional fields onto the existing frontmatter. */
114
127
  export function applySet(fields, request) {
115
128
  const next = { ...fields };
116
- if (request.control?.externalApproval === "granted") {
129
+ // The schema does not offer "granted", but the check stays: this is the only place that
130
+ // guarantees a self-granted approval cannot reach disk, whatever the caller sends.
131
+ const patch = request.control ?? {};
132
+ if (patch.externalApproval === "granted") {
117
133
  throw new Error('Only a user can grant external-action approval with "/tasks approve <id>".');
118
134
  }
119
135
  if (request.status !== undefined) {
@@ -1,5 +1,7 @@
1
- import type { TaskControl, TaskControlPatch } from "../../tasks/control.js";
2
- export type TaskManageAction = "create" | "progress" | "candidate" | "set" | "verify" | "done" | "skip" | "cancel" | "list";
1
+ import type { Static } from "typebox";
2
+ import type { TaskControl } from "../../tasks/control.js";
3
+ import type { taskManageSchema } from "./schema.js";
4
+ export type TaskManageAction = Static<typeof taskManageSchema>["action"];
3
5
  export interface TaskManageResult {
4
6
  action: TaskManageAction;
5
7
  id?: string;
@@ -17,26 +19,23 @@ export interface TaskManageResult {
17
19
  }>;
18
20
  notice: string;
19
21
  }
20
- export interface TaskManageRequest {
21
- action: TaskManageAction;
22
- id?: string;
23
- title?: string;
24
- goal?: string;
25
- dod?: string;
26
- manual?: string;
22
+ /**
23
+ * A `task_manage` call, derived from the schema the model actually sees (spec 036, D8).
24
+ *
25
+ * It used to be a hand-written mirror of `taskManageSchema`, and the two drifted apart in both
26
+ * directions without a single type error: the schema advertised `parent`, `dependsOn` and
27
+ * `verificationMode`, all three silently dropped on write, while the one field that turns on
28
+ * independent acceptance — `verificationRequired` — was read by the implementation and absent
29
+ * from the schema, so no model could ever ask for it. Deriving the request type makes that class
30
+ * of drift a compile error. `label` is the tool's UI affordance, not part of the request.
31
+ *
32
+ * `status` stays a plain string: it is validated in code against the transition table so a legacy
33
+ * or closing value ("open", "done") gets a fixable error naming the right action, rather than a
34
+ * bare schema rejection.
35
+ */
36
+ export type TaskManageRequest = Omit<Static<typeof taskManageSchema>, "label" | "status"> & {
27
37
  status?: string;
28
- wake?: string;
29
- schedule?: string;
30
- recurrence?: string;
31
- note?: string;
32
- verificationPlan?: string;
33
- control?: TaskControlPatch;
34
- verifierRunId?: string;
35
- summary?: string;
36
- evidence?: string;
37
- residualRisk?: string;
38
- reason?: string;
39
- }
38
+ };
40
39
  export interface TaskManageToolOptions {
41
40
  workspaceDir: string;
42
41
  channelDir: string;
@@ -38,27 +38,11 @@ export function createTaskManageTool(options) {
38
38
  "verifier attestation, complete verified work, skip one recurring occurrence, cancel abandoned work, or list tasks. Use progress for routine " +
39
39
  "end-of-turn checkpoints; use write/edit only for substantial Goal/DoD/Manual/Verification changes.",
40
40
  parameters: taskManageSchema,
41
+ // `args` is typed from `taskManageSchema`, and so is `TaskManageRequest`: the request is
42
+ // the validated arguments minus `label`, with no third hand-written copy to drift.
41
43
  execute: async (_toolCallId, args) => {
42
- const result = await manageTask(options, {
43
- action: parseAction(args.action),
44
- id: args.id,
45
- title: args.title,
46
- goal: args.goal,
47
- dod: args.dod,
48
- manual: args.manual,
49
- verificationPlan: args.verificationPlan,
50
- control: args.control,
51
- status: args.status,
52
- wake: args.wake,
53
- schedule: args.schedule,
54
- recurrence: args.recurrence,
55
- note: args.note,
56
- verifierRunId: args.verifierRunId,
57
- summary: args.summary,
58
- evidence: args.evidence,
59
- residualRisk: args.residualRisk,
60
- reason: args.reason,
61
- });
44
+ const { label: _label, ...request } = args;
45
+ const result = await manageTask(options, { ...request, action: parseAction(request.action) });
62
46
  return {
63
47
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
64
48
  details: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oyasmi/pipiclaw",
3
- "version": "0.8.10-beta.3",
3
+ "version": "0.8.10-beta.4",
4
4
  "description": "An AI assistant runtime for coding and team workflows, with DingTalk AI Cards, sub-agents, memory, and scheduled events.",
5
5
  "type": "module",
6
6
  "bin": {