@oyasmi/pipiclaw 0.9.2-beta.2 → 0.9.2-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 (116) hide show
  1. package/README.md +3 -0
  2. package/dist/agent/channel-runner.d.ts +13 -18
  3. package/dist/agent/channel-runner.js +44 -90
  4. package/dist/agent/command-extension.js +1 -1
  5. package/dist/agent/context-budget.d.ts +8 -0
  6. package/dist/agent/context-budget.js +10 -2
  7. package/dist/agent/job-manager.d.ts +1 -1
  8. package/dist/agent/job-manager.js +9 -1
  9. package/dist/agent/prompt/builder.d.ts +0 -1
  10. package/dist/agent/prompt/builder.js +1 -14
  11. package/dist/agent/prompt/manifest.js +2 -1
  12. package/dist/agent/prompt/sections.js +1 -1
  13. package/dist/agent/runner-factory.d.ts +19 -1
  14. package/dist/agent/runner-factory.js +8 -1
  15. package/dist/agent/session-events.d.ts +2 -2
  16. package/dist/agent/turn-prompt.d.ts +35 -0
  17. package/dist/agent/turn-prompt.js +37 -0
  18. package/dist/agent/turn-recovery.js +1 -1
  19. package/dist/agent/turn-state.d.ts +60 -0
  20. package/dist/agent/turn-state.js +95 -0
  21. package/dist/agent/types.d.ts +3 -3
  22. package/dist/{runtime → channel}/channel-context.d.ts +6 -2
  23. package/dist/{runtime → channel}/channel-context.js +6 -2
  24. package/dist/{runtime → channel}/channel-event.d.ts +8 -0
  25. package/dist/channel/channel-paths.d.ts +16 -0
  26. package/dist/{runtime → channel}/channel-paths.js +20 -0
  27. package/dist/{agent/commands.d.ts → commands/catalog.d.ts} +16 -1
  28. package/dist/{agent/commands.js → commands/catalog.js} +30 -0
  29. package/dist/index.d.ts +1 -1
  30. package/dist/log.js +14 -5
  31. package/dist/main.js +29 -0
  32. package/dist/memory/commands.js +2 -2
  33. package/dist/memory/maintenance-state.d.ts +8 -0
  34. package/dist/memory/maintenance-state.js +47 -4
  35. package/dist/memory/scheduler.d.ts +6 -0
  36. package/dist/memory/scheduler.js +19 -16
  37. package/dist/playbooks/agent-delegation.md +2 -2
  38. package/dist/runtime/bootstrap.d.ts +2 -2
  39. package/dist/runtime/bootstrap.js +43 -13
  40. package/dist/runtime/delivery.d.ts +3 -3
  41. package/dist/runtime/dingtalk.d.ts +4 -4
  42. package/dist/runtime/dingtalk.js +2 -2
  43. package/dist/runtime/durable-dispatch.d.ts +7 -1
  44. package/dist/runtime/durable-dispatch.js +12 -2
  45. package/dist/runtime/event-commands.js +2 -2
  46. package/dist/runtime/events.d.ts +8 -1
  47. package/dist/runtime/events.js +15 -3
  48. package/dist/runtime/project-commands.js +2 -2
  49. package/dist/runtime/skill-commands.d.ts +27 -0
  50. package/dist/runtime/skill-commands.js +72 -0
  51. package/dist/runtime/subagent-commands.d.ts +8 -0
  52. package/dist/runtime/subagent-commands.js +29 -5
  53. package/dist/runtime/task-commands.js +2 -2
  54. package/dist/runtime/task-driver.d.ts +5 -1
  55. package/dist/runtime/task-driver.js +13 -12
  56. package/dist/runtime/task-migration.js +3 -2
  57. package/dist/runtime/task-wake.d.ts +6 -1
  58. package/dist/runtime/task-wake.js +21 -2
  59. package/dist/settings.d.ts +13 -0
  60. package/dist/settings.js +78 -0
  61. package/dist/shared/token-estimate.d.ts +1 -0
  62. package/dist/shared/token-estimate.js +19 -0
  63. package/dist/subagents/external/claude-code.js +20 -0
  64. package/dist/subagents/external/codex-cli.js +33 -0
  65. package/dist/subagents/external/harness.d.ts +8 -0
  66. package/dist/subagents/external/progress-tail.d.ts +14 -0
  67. package/dist/subagents/external/progress-tail.js +84 -0
  68. package/dist/subagents/external/run.js +1 -0
  69. package/dist/subagents/external/settlement.d.ts +4 -1
  70. package/dist/subagents/external/settlement.js +9 -2
  71. package/dist/subagents/runs.d.ts +45 -4
  72. package/dist/subagents/runs.js +187 -14
  73. package/dist/subagents/tool.js +4 -3
  74. package/dist/tasks/artifact-subject.d.ts +8 -0
  75. package/dist/tasks/artifact-subject.js +25 -0
  76. package/dist/tools/glob-match.d.ts +25 -4
  77. package/dist/tools/glob-match.js +175 -53
  78. package/dist/tools/glob.js +5 -2
  79. package/dist/tools/grep.js +4 -1
  80. package/dist/tools/index.d.ts +1 -1
  81. package/dist/tools/registry.d.ts +1 -1
  82. package/dist/tools/send-media.d.ts +1 -1
  83. package/dist/tools/skill.d.ts +15 -0
  84. package/dist/tools/skill.js +16 -8
  85. package/dist/tui/app.js +5 -3
  86. package/dist/tui/commands.d.ts +1 -0
  87. package/dist/tui/commands.js +3 -1
  88. package/dist/tui/terminal-context.d.ts +2 -2
  89. package/dist/tui/terminal-media-sender.d.ts +1 -1
  90. package/dist/tui/turn-controller.d.ts +2 -1
  91. package/dist/tui/turn-controller.js +2 -1
  92. package/examples/sub-agents/README.md +3 -2
  93. package/examples/sub-agents/builder-hard.md +17 -16
  94. package/examples/sub-agents/builder.md +16 -12
  95. package/examples/sub-agents/documenter.md +15 -16
  96. package/examples/sub-agents/explorer.md +16 -17
  97. package/examples/sub-agents/git-committer.md +18 -28
  98. package/examples/sub-agents/log-sifter.md +15 -14
  99. package/examples/sub-agents/planner.md +11 -11
  100. package/examples/sub-agents/reviewer.md +20 -13
  101. package/examples/sub-agents/scout.md +14 -11
  102. package/examples/sub-agents/verifier.md +17 -14
  103. package/examples/sub-agents/worker.md +18 -12
  104. package/package.json +1 -1
  105. package/dist/runtime/channel-paths.d.ts +0 -4
  106. /package/dist/{runtime → channel}/active-session-store.d.ts +0 -0
  107. /package/dist/{runtime → channel}/active-session-store.js +0 -0
  108. /package/dist/{runtime → channel}/channel-event.js +0 -0
  109. /package/dist/{runtime → channel}/channel-index.d.ts +0 -0
  110. /package/dist/{runtime → channel}/channel-index.js +0 -0
  111. /package/dist/{runtime → channel}/project-scope-store.d.ts +0 -0
  112. /package/dist/{runtime → channel}/project-scope-store.js +0 -0
  113. /package/dist/{runtime → channel}/store.d.ts +0 -0
  114. /package/dist/{runtime → channel}/store.js +0 -0
  115. /package/dist/{agent → commands}/reply-limits.d.ts +0 -0
  116. /package/dist/{agent → commands}/reply-limits.js +0 -0
@@ -15,7 +15,7 @@ order: 60
15
15
  两条路径,按有没有合适的现成角色分:
16
16
 
17
17
  - **系统提示的目录里有合适角色**:看活的轻重挑。只读定位、单点事实、小范围检查交给 `light`;跨多文件实现、需要自测、要跑几十分钟的重活交给 `heavy`。目录已经按 `light`/`heavy` 和 `read`/`write` 分好组,`description` 说明各自适用面。按角色能做什么挑,**不按底层 harness(claude-code / codex-cli / exec)挑**——harness 只决定调用细节,比如命令怎么拼。
18
- - **没有合适角色**:直接传 inline `systemPrompt` 起一个临时子代理。这是委派工具的默认路径,不需要先去配角色文件。`systemPrompt` 写执行者**稳定的**身份、纪律和产出格式,`task` 写这一次的终点和证据;需要时用 `tools` 收窄工具面、用 `model` 换模型。
18
+ - **没有合适角色**:才使用 `subagent_inline`,直接传 `systemPrompt` 起一个临时子代理。这是少数需要临时自定义执行面的高级场景,不是默认路径;如果有任何合适的已配置角色,优先调用 `subagent`,不要把 inline 当作它的简写。inline 没有角色文件替你提供工具、模型、预算和上下文策略,调用时要自行组装完整合法的 `task`、`systemPrompt` 和适用控制参数。
19
19
 
20
20
  `light` 通常是内置角色,同回合就返回(超 120 秒自动转异步,这是交互方式优化,不是失败);`heavy` 通常是外部角色,一律异步。标了 `write` 的角色会改宿主文件,工作目录要单独想清楚(第三节)。
21
21
 
@@ -46,7 +46,7 @@ order: 60
46
46
  - **并行的写入分片必须各自显式传 `workingDirectory`**(`git worktree add` 后指向不同 checkout)。默认值不会让它们自动分开,两个 run 会悄悄落到同一棵树上。创建的 worktree 用完记得关闭。
47
47
  - 频道配置了项目边界时,`workingDirectory` 必须落在项目目录内,否则派发前就被拒:`workingDirectory "..." must be inside the project root`。
48
48
  - runtime 只在**委派之间**保证排他写锁:`mutates: write` 的 run 占住目标目录,第二个写入者被拒时错误会点名持有者 runId。锁触发说明分片设计已经出错,它是兜底而不是免于思考的理由。
49
- - **写清 `mutates` 是你的责任。** 这把锁只保护声明了 `mutates: write` 的委派。内置角色的 `mutates` 由 `tools` 推定(只看 `write`/`edit`,看不到 `bash`),外部角色是自述,两者都可能与实际行为不符。配置好的角色改它的角色文件;inline 委派没有角色文件可改,就在 `subagent` 调用上直接传 `mutates: "write"`。
49
+ - **写清 `mutates` 是你的责任。** 这把锁只保护声明了 `mutates: write` 的委派。内置角色的 `mutates` 由 `tools` 推定(只看 `write`/`edit`,看不到 `bash`),外部角色是自述,两者都可能与实际行为不符。配置好的角色改它的角色文件;inline 委派没有角色文件可改,就在 `subagent_inline` 调用上直接传 `mutates: "write"`。
50
50
  - **你自己的 `write` / `edit` / `bash` 不受这把锁保护。** 一个目录上有活跃写委派时,先等它结束,或者换一棵 worktree。
51
51
 
52
52
  ## 四、派发之后:结束回合,等唤醒
@@ -1,11 +1,11 @@
1
1
  import { type AgentRunner } from "../agent/index.js";
2
+ import type { ChannelEvent } from "../channel/channel-event.js";
3
+ import { ChannelStore } from "../channel/store.js";
2
4
  import { type Executor } from "../executor.js";
3
5
  import { PipiclawSettingsManager } from "../settings.js";
4
6
  import type { WakeTaskTransitionHooks } from "../tasks/store.js";
5
7
  import { type BootstrapIO, type BootstrapPaths } from "./app-home.js";
6
- import type { ChannelEvent } from "./channel-event.js";
7
8
  import { DingTalkBot, type DingTalkConfig, type DingTalkHandler } from "./dingtalk.js";
8
- import { ChannelStore } from "./store.js";
9
9
  export interface BootstrapOptions {
10
10
  env?: NodeJS.ProcessEnv;
11
11
  io?: BootstrapIO;
@@ -1,11 +1,16 @@
1
1
  import { join } from "path";
2
- import { BUILT_IN_COMMANDS, formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../agent/commands.js";
3
2
  import { channelEffectCount, noteTaskEffects, taskEffectCount } from "../agent/effect-ledger.js";
4
3
  import { createRunner } from "../agent/index.js";
5
4
  import { channelRunningJobLines, configureJobRuntime, restoreChannelJobs } from "../agent/job-manager.js";
6
5
  import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
7
6
  import { renderStatus } from "../agent/status-render.js";
8
7
  import { scanWorkspaceForInterruptedTurns } from "../agent/turn-recovery.js";
8
+ import { createFreshActiveSession } from "../channel/active-session-store.js";
9
+ import { createChannelIndex } from "../channel/channel-index.js";
10
+ import { ensureChannelDir, getChannelDir } from "../channel/channel-paths.js";
11
+ import { resolveProjectScope } from "../channel/project-scope-store.js";
12
+ import { ChannelStore } from "../channel/store.js";
13
+ import { BUILT_IN_COMMANDS, formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../commands/catalog.js";
9
14
  import { createExecutor } from "../executor.js";
10
15
  import * as log from "../log.js";
11
16
  import { ensureChannelMemoryFilesSync } from "../memory/files.js";
@@ -24,20 +29,16 @@ import { readActiveTasks } from "../tasks/ledger.js";
24
29
  import { getToolsConfigPath, loadToolsConfig, loadToolsConfigWithDiagnostics } from "../tools/config.js";
25
30
  import { getUsageLedger } from "../usage/ledger.js";
26
31
  import { parseUsageMode, renderUsageReport } from "../usage/render.js";
27
- import { createFreshActiveSession } from "./active-session-store.js";
28
32
  import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, loadConfig, parseArgs, printBootstrapSummary, readCliVersion, } from "./app-home.js";
29
- import { createChannelIndex } from "./channel-index.js";
30
- import { ensureChannelDir, getChannelDir } from "./channel-paths.js";
31
33
  import { createDingTalkContext } from "./delivery.js";
32
34
  import { DingTalkBot, } from "./dingtalk.js";
33
35
  import { DurableDispatchService } from "./durable-dispatch.js";
34
36
  import { handleEventsCommand as runEventsCommand } from "./event-commands.js";
35
37
  import { createEventsWatcher } from "./events.js";
36
38
  import { handleProjectCommand as runProjectCommand } from "./project-commands.js";
37
- import { resolveProjectScope } from "./project-scope-store.js";
38
39
  import { installLlmProxy } from "./proxy.js";
39
- import { ChannelStore } from "./store.js";
40
- import { handleSubagentsCommand as runSubagentsCommand } from "./subagent-commands.js";
40
+ import { handleSkillsCommand as runSkillsCommand } from "./skill-commands.js";
41
+ import { renderRunNotice, handleSubagentsCommand as runSubagentsCommand } from "./subagent-commands.js";
41
42
  import { pauseTask, handleTasksCommand as runTasksCommand } from "./task-commands.js";
42
43
  import { createTaskDriverEvent, TaskDriver } from "./task-driver.js";
43
44
  import { migrateLegacyTaskScheduleEvents, migrateLegacyTaskState } from "./task-migration.js";
@@ -392,6 +393,13 @@ export async function createRuntimeContext(options) {
392
393
  });
393
394
  },
394
395
  });
396
+ case "skills":
397
+ return runSkillsCommand({
398
+ args,
399
+ workspaceDir: options.paths.workspaceDir,
400
+ appHomeDir: options.paths.appHomeDir,
401
+ channelId: event.channelId,
402
+ });
395
403
  }
396
404
  },
397
405
  async handleBusyMessage(event, bot, mode, queueText) {
@@ -480,9 +488,12 @@ export async function createRuntimeContext(options) {
480
488
  isBot: false,
481
489
  skipContextSync: Boolean(builtInCommand),
482
490
  }, "user message");
483
- // Background wakes deliver their result, not their process: no progress card,
484
- // no thinking stream, nothing to delete when the check-in ends `[SILENT]`.
485
- const ctx = createDingTalkContext(event, bot, store, _isEvent ? "none" : undefined);
491
+ // Background wakes deliver their result, not their process: no progress card, no
492
+ // thinking stream, nothing to delete when the check-in ends `[SILENT]`. An "awaited"
493
+ // wake (a delegation or job finishing) is the opposite — a human is actually waiting
494
+ // on it — so it renders progress the same way a normal message does (P0-2).
495
+ const backgroundOnly = Boolean(_isEvent) && event.presentation !== "awaited";
496
+ const ctx = createDingTalkContext(event, bot, store, backgroundOnly ? "none" : undefined);
486
497
  if (builtInCommand) {
487
498
  const commandStartedAt = Date.now();
488
499
  const logCtx = { channelId: event.channelId, userName: event.userName };
@@ -534,7 +545,7 @@ export async function createRuntimeContext(options) {
534
545
  ctx: { channelId: event.channelId, userName: event.userName },
535
546
  fields: { messageLength: event.text.length, source: _isEvent ? "event" : "message" },
536
547
  });
537
- if (!_isEvent) {
548
+ if (!backgroundOnly) {
538
549
  ctx.primeCard(350);
539
550
  }
540
551
  // Effects are tallied per channel; the governor needs them per task, so one
@@ -563,7 +574,11 @@ export async function createRuntimeContext(options) {
563
574
  recoveredJobTaskId = claimed.taskId;
564
575
  await claimed.finish();
565
576
  structuredWakeFinalized = true;
566
- if (event.internalWake?.kind === "job" && !claimed.activated)
577
+ // Drop without a turn only when something else is still driving this task (a
578
+ // sibling wake in the same fan-out already activated it); every other case —
579
+ // the task is done, archived, disabled, or gone — has nobody left to see this
580
+ // result if it is dropped here, so it must still reach a normal turn (P3-1).
581
+ if (event.internalWake?.kind === "job" && !claimed.activated && claimed.taskStillDriven)
567
582
  return;
568
583
  }
569
584
  else {
@@ -590,7 +605,9 @@ export async function createRuntimeContext(options) {
590
605
  recoveredDelegationTaskId = claimed.taskId;
591
606
  await claimed.finish();
592
607
  structuredWakeFinalized = true;
593
- if (event.internalWake?.kind === "subagent" && !claimed.activated)
608
+ // See the JOB branch above (P3-1): only skip the turn when the task is still
609
+ // driven by something else.
610
+ if (event.internalWake?.kind === "subagent" && !claimed.activated && claimed.taskStillDriven)
594
611
  return;
595
612
  }
596
613
  else {
@@ -669,6 +686,19 @@ export async function createRuntimeContext(options) {
669
686
  configureSubAgentRuntime({
670
687
  stateDir: join(options.paths.appHomeDir, "state", "subagent-runs"),
671
688
  dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
689
+ // P0-1/P1a: a best-effort out-of-band notice, independent of the completion wake — it reaches
690
+ // the channel in roughly the time the run itself takes, not the wake turn's own LLM latency
691
+ // on top of that. `notices: "off"` (settings.json) restores today's silent behavior.
692
+ notify: (channelId, notice) => {
693
+ const level = runtimeSettingsManager.getDelegationSettings().notices;
694
+ if (level === "off")
695
+ return;
696
+ if (level === "settled" && notice.kind !== "settled")
697
+ return;
698
+ const text = renderRunNotice(notice);
699
+ if (text)
700
+ void bot.sendPlain(channelId, text);
701
+ },
672
702
  ledger: getUsageLedger(),
673
703
  store,
674
704
  });
@@ -1,7 +1,7 @@
1
- import type { ChannelContext, ProgressStyle } from "./channel-context.js";
2
- import type { ChannelEvent } from "./channel-event.js";
1
+ import type { ChannelContext, ProgressStyle } from "../channel/channel-context.js";
2
+ import type { ChannelEvent } from "../channel/channel-event.js";
3
+ import type { ChannelStore } from "../channel/store.js";
3
4
  import type { DingTalkBot } from "./dingtalk.js";
4
- import type { ChannelStore } from "./store.js";
5
5
  /**
6
6
  * Build the delivery contract for one turn.
7
7
  *
@@ -1,7 +1,7 @@
1
- import { type RuntimeCommandName } from "../agent/commands.js";
2
- import type { FinalDelivery, MediaSender, MediaSendResult, OutboundMedia, ProgressStyle } from "./channel-context.js";
3
- import type { ChannelEvent } from "./channel-event.js";
4
- import type { ChannelObservation } from "./channel-index.js";
1
+ import type { FinalDelivery, MediaSender, MediaSendResult, OutboundMedia, ProgressStyle } from "../channel/channel-context.js";
2
+ import type { ChannelEvent } from "../channel/channel-event.js";
3
+ import type { ChannelObservation } from "../channel/channel-index.js";
4
+ import { type RuntimeCommandName } from "../commands/catalog.js";
5
5
  export type BusyMessageMode = "steer" | "followUp";
6
6
  export type BusyMessageDefaultConfig = BusyMessageMode | "followup";
7
7
  export type ResponseMode = "full_progress_then_plain_final" | "rolling_progress_then_plain_final" | "final_card_only";
@@ -11,12 +11,12 @@ import axios from "axios";
11
11
  import { DWClient, TOPIC_ROBOT } from "dingtalk-stream";
12
12
  import { existsSync, mkdirSync, readFileSync } from "fs";
13
13
  import { dirname, join } from "path";
14
- import { formatBusyCommandList, parseBuiltInCommand, renderBuiltInHelp, slashCommandName, } from "../agent/commands.js";
14
+ import { getChannelDir } from "../channel/channel-paths.js";
15
+ import { formatBusyCommandList, parseBuiltInCommand, renderBuiltInHelp, slashCommandName, } from "../commands/catalog.js";
15
16
  import * as log from "../log.js";
16
17
  import { writeFileAtomicallySync } from "../shared/atomic-file.js";
17
18
  import { errorMessage } from "../shared/text-utils.js";
18
19
  import { isRecord } from "../shared/type-guards.js";
19
- import { getChannelDir } from "./channel-paths.js";
20
20
  // Turn serialization is runtime policy; the queue lives in its own module and
21
21
  // this transport only consumes it.
22
22
  import { ChannelQueue } from "./channel-queue.js";
@@ -1,4 +1,4 @@
1
- import type { ChannelEvent } from "./channel-event.js";
1
+ import type { ChannelEvent } from "../channel/channel-event.js";
2
2
  import type { DingTalkBot } from "./dingtalk.js";
3
3
  type DispatchStatus = "pending" | "queued" | "running" | "exhausted";
4
4
  export interface DurableDispatchRecord {
@@ -47,6 +47,12 @@ export declare class DurableDispatchService {
47
47
  private readonly running;
48
48
  constructor(options: DurableDispatchOptions);
49
49
  start(): void;
50
+ /**
51
+ * The drain is timer-driven, so nothing above it can catch a rejection: a record write that
52
+ * fails (ENOSPC, EACCES) would take the process down rather than skip one tick. The next
53
+ * tick retries from the same persisted state, which is the whole point of the store.
54
+ */
55
+ private drainSafely;
50
56
  stop(): void;
51
57
  dispatch(event: ChannelEvent): Promise<boolean>;
52
58
  /** Reset any in-flight records for a channel so a stop/abort can redeliver on the next tick, not after the lease expires. */
@@ -90,10 +90,20 @@ export class DurableDispatchService {
90
90
  start() {
91
91
  if (this.timer)
92
92
  return;
93
- void this.drainOnce();
94
- this.timer = setInterval(() => void this.drainOnce(), this.options.intervalMs ?? DEFAULT_INTERVAL_MS);
93
+ this.drainSafely();
94
+ this.timer = setInterval(() => this.drainSafely(), this.options.intervalMs ?? DEFAULT_INTERVAL_MS);
95
95
  this.timer.unref?.();
96
96
  }
97
+ /**
98
+ * The drain is timer-driven, so nothing above it can catch a rejection: a record write that
99
+ * fails (ENOSPC, EACCES) would take the process down rather than skip one tick. The next
100
+ * tick retries from the same persisted state, which is the whole point of the store.
101
+ */
102
+ drainSafely() {
103
+ this.drainOnce().catch((error) => {
104
+ log.logWarning("Durable dispatch drain failed", errorMessage(error));
105
+ });
106
+ }
97
107
  stop() {
98
108
  if (!this.timer)
99
109
  return;
@@ -1,8 +1,8 @@
1
1
  import { existsSync } from "fs";
2
2
  import { readdir, readFile, unlink } from "fs/promises";
3
3
  import { join } from "path";
4
- import { renderSubcommandUsage } from "../agent/commands.js";
5
- import { capReply } from "../agent/reply-limits.js";
4
+ import { renderSubcommandUsage } from "../commands/catalog.js";
5
+ import { capReply } from "../commands/reply-limits.js";
6
6
  import { normalizeSafeId, resolveSafeIdPath } from "../shared/safe-id.js";
7
7
  import { errorMessage, eventNameFromFilename, clipText as sharedClipText } from "../shared/text-utils.js";
8
8
  import { parseScheduledEventContent } from "./events.js";
@@ -1,6 +1,6 @@
1
+ import type { ChannelEvent } from "../channel/channel-event.js";
1
2
  import type { Executor } from "../executor.js";
2
3
  import type { SecurityConfig } from "../security/types.js";
3
- import type { ChannelEvent } from "./channel-event.js";
4
4
  import type { DingTalkBot } from "./dingtalk.js";
5
5
  export interface EventAction {
6
6
  type: "bash";
@@ -84,6 +84,13 @@ export declare class EventsWatcher {
84
84
  private debounce;
85
85
  private scanExisting;
86
86
  private handleFileChange;
87
+ /**
88
+ * Watch callbacks are the top of their own stack, so a rejection here reaches nobody — and
89
+ * `handleFile` can reject: reloading a due one-shot dispatches it inline, and dispatch
90
+ * writes to disk. `scanExisting` already wraps its own calls; this is the same guard for
91
+ * the live path. One bad file must not take the watcher, or the process, down with it.
92
+ */
93
+ private handleFileSafely;
87
94
  private handleDelete;
88
95
  private cancelScheduled;
89
96
  private handleFile;
@@ -2,6 +2,7 @@ import { Cron } from "croner";
2
2
  import { chmodSync, existsSync, mkdirSync, readdirSync, statSync, unlinkSync, watch, writeFileSync, } from "fs";
3
3
  import { readFile } from "fs/promises";
4
4
  import { dirname, join, resolve } from "path";
5
+ import { getChannelDir } from "../channel/channel-paths.js";
5
6
  import * as log from "../log.js";
6
7
  import { guardCommand } from "../security/command-guard.js";
7
8
  import { writeFileAtomicallySync } from "../shared/atomic-file.js";
@@ -261,12 +262,23 @@ export class EventsWatcher {
261
262
  }
262
263
  else if (this.knownFiles.has(filename)) {
263
264
  this.cancelScheduled(filename);
264
- this.handleFile(filename);
265
+ this.handleFileSafely(filename);
265
266
  }
266
267
  else {
267
- this.handleFile(filename);
268
+ this.handleFileSafely(filename);
268
269
  }
269
270
  }
271
+ /**
272
+ * Watch callbacks are the top of their own stack, so a rejection here reaches nobody — and
273
+ * `handleFile` can reject: reloading a due one-shot dispatches it inline, and dispatch
274
+ * writes to disk. `scanExisting` already wraps its own calls; this is the same guard for
275
+ * the live path. One bad file must not take the watcher, or the process, down with it.
276
+ */
277
+ handleFileSafely(filename) {
278
+ void this.handleFile(filename).catch((err) => {
279
+ log.logWarning(`Failed to load event file: ${filename}`, errorMessage(err));
280
+ });
281
+ }
270
282
  handleDelete(filename) {
271
283
  if (!this.knownFiles.has(filename))
272
284
  return;
@@ -485,7 +497,7 @@ export class EventsWatcher {
485
497
  if (!parsed)
486
498
  return undefined;
487
499
  const taskId = parsed.id;
488
- const taskPath = join(dirname(this.eventsDir), event.channelId, "tasks", `${taskId}.md`);
500
+ const taskPath = join(getChannelDir(dirname(this.eventsDir), event.channelId), "tasks", `${taskId}.md`);
489
501
  let content;
490
502
  try {
491
503
  content = await readFile(taskPath, "utf-8");
@@ -1,8 +1,8 @@
1
- import { renderSubcommandUsage } from "../agent/commands.js";
1
+ import { commitProjectSelection, readProjectSelection } from "../channel/project-scope-store.js";
2
+ import { renderSubcommandUsage } from "../commands/catalog.js";
2
3
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
3
4
  import { currentProjectSandboxStatus, isWithinAllowedRoots, resolveExistingDirectory, resolveProjectAccessPolicy, } from "../security/project-scope.js";
4
5
  import { errorMessage } from "../shared/text-utils.js";
5
- import { commitProjectSelection, readProjectSelection } from "./project-scope-store.js";
6
6
  function usage() {
7
7
  return renderSubcommandUsage("project");
8
8
  }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * `/skills` — the human control path for a workspace's skill catalog (spec 045's read-only
3
+ * `skill` tool has no channel-command counterpart until now). Mirrors `project-commands.ts`'s
4
+ * shape: pure-ish functions returning markdown, no bot/event coupling.
5
+ *
6
+ * Deliberately a disk scan via `listWorkspaceSkills`, not the live `ChannelRunner`'s already-
7
+ * loaded catalog: that keeps `/skills` usable while a turn is streaming and for a channel with no
8
+ * active runner, and — the whole reason this exists rather than reusing `/help`'s discovery tail
9
+ * — it is the only place that shows a skill that failed the content scan and was silently dropped
10
+ * from `<available_skills>` (`src/agent/workspace-resources.ts`).
11
+ */
12
+ export interface HandleSkillsCommandOptions {
13
+ args: string;
14
+ workspaceDir: string;
15
+ appHomeDir: string;
16
+ channelId?: string;
17
+ }
18
+ type SkillsCommand = {
19
+ action: "list";
20
+ } | {
21
+ action: "show";
22
+ name: string;
23
+ };
24
+ /** Exported so `test/commands-subcommands.test.ts` can feed every broadcast example back through it. */
25
+ export declare function parseSkillsCommand(args: string): SkillsCommand;
26
+ export declare function handleSkillsCommand(options: HandleSkillsCommandOptions): Promise<string>;
27
+ export {};
@@ -0,0 +1,72 @@
1
+ import { renderSubcommandUsage } from "../commands/catalog.js";
2
+ import { capReply } from "../commands/reply-limits.js";
3
+ import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
4
+ import { errorMessage } from "../shared/text-utils.js";
5
+ import { listWorkspaceSkills, loadWorkspaceSkillFile } from "../tools/skill.js";
6
+ function usage() {
7
+ return renderSubcommandUsage("skills");
8
+ }
9
+ /** Exported so `test/commands-subcommands.test.ts` can feed every broadcast example back through it. */
10
+ export function parseSkillsCommand(args) {
11
+ const trimmed = args.trim();
12
+ if (!trimmed || trimmed.toLowerCase() === "list")
13
+ return { action: "list" };
14
+ const parts = trimmed.split(/\s+/);
15
+ if (parts[0]?.toLowerCase() === "show") {
16
+ if (!parts[1] || parts.length > 2)
17
+ throw new Error("用法:/skills show <name>");
18
+ return { action: "show", name: parts[1] };
19
+ }
20
+ throw new Error(`未知的 /skills 子命令:${parts[0]}`);
21
+ }
22
+ async function listSkills(workspaceDir) {
23
+ const skills = await listWorkspaceSkills({ workspaceDir });
24
+ if (skills.length === 0) {
25
+ return (`**Workspace skills**\n\n暂无工作区 skill(\`${workspaceDir}/skills/\` 下没有)。\n\n` +
26
+ "用 write/edit 在 `workspace/skills/<name>/SKILL.md` 直接创建,frontmatter 需要非空的 `name`(与目录名一致)和 `description`。");
27
+ }
28
+ const loaded = skills.filter((skill) => !skill.warning);
29
+ const rejected = skills.filter((skill) => skill.warning);
30
+ const lines = [`**Workspace skills**(${loaded.length} 个)· 用 \`/skill:<名称>\` 调用`, ""];
31
+ if (loaded.length > 0) {
32
+ lines.push(...loaded.map((skill) => `- \`${skill.name}\` — ${skill.description || "(无 description)"}`));
33
+ }
34
+ else {
35
+ lines.push("(全部未通过加载,见下)");
36
+ }
37
+ if (rejected.length > 0) {
38
+ lines.push("", "⚠ 未加载(不在 `<available_skills>` 中,也无法通过 `/skill:名称` 调用)", "");
39
+ lines.push(...rejected.map((skill) => `- \`${skill.name}\` — ${skill.warning}`));
40
+ }
41
+ return capReply(lines.join("\n"), { nextStepHint: "用 `/skills show <name>` 查看单个 skill 的完整正文" }).text;
42
+ }
43
+ async function showSkill(options, name) {
44
+ try {
45
+ const securityConfig = loadSecurityConfigWithDiagnostics(options.appHomeDir).config;
46
+ const file = await loadWorkspaceSkillFile({
47
+ workspaceDir: options.workspaceDir,
48
+ securityConfig,
49
+ channelId: options.channelId,
50
+ }, name);
51
+ const body = `**Skill \`${file.name}\`**\n\n路径:\`${file.path}\`\n\n${file.content}`;
52
+ return capReply(body, { nextStepHint: `用 read 工具打开 ${file.path} 继续查看` }).text;
53
+ }
54
+ catch (error) {
55
+ return `无法查看 skill:${errorMessage(error)}`;
56
+ }
57
+ }
58
+ export async function handleSkillsCommand(options) {
59
+ let command;
60
+ try {
61
+ command = parseSkillsCommand(options.args);
62
+ }
63
+ catch (error) {
64
+ return `${errorMessage(error)}\n\n${usage()}`;
65
+ }
66
+ switch (command.action) {
67
+ case "list":
68
+ return listSkills(options.workspaceDir);
69
+ case "show":
70
+ return showSkill(options, command.name);
71
+ }
72
+ }
@@ -1,4 +1,5 @@
1
1
  import type { SubAgentDiscoveryResult } from "../subagents/discovery.js";
2
+ import { type RunNotice } from "../subagents/runs.js";
2
3
  /**
3
4
  * `/subagents` — the human control path that does not depend on the model (spec 040 D6, polished
4
5
  * by spec 041). Mirrors `task-commands.ts`'s shape: pure functions returning markdown, no
@@ -34,4 +35,11 @@ type SubagentsCommand = {
34
35
  /** Exported so `test/commands-subcommands.test.ts` can feed every broadcast example back through it. */
35
36
  export declare function parseSubagentsCommand(args: string): SubagentsCommand;
36
37
  export declare function handleSubagentsCommand(options: HandleSubagentsCommandOptions): Promise<string>;
38
+ /**
39
+ * Render a `RunNotice` (P0-1/P1a) as a one-line reply — a confirmation, per the command reply
40
+ * conventions. `notices: "off"` is enforced by the caller not invoking this at all; a `"settled"`
41
+ * caller filters `kind: "progress"` out before calling. Returns `undefined` for a notice with
42
+ * nothing worth showing (a progress step that never resolved to a label).
43
+ */
44
+ export declare function renderRunNotice(notice: RunNotice): string | undefined;
37
45
  export {};
@@ -1,6 +1,7 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
- import { renderSubcommandUsage } from "../agent/commands.js";
3
+ import { renderSubcommandUsage } from "../commands/catalog.js";
4
+ import { formatDuration } from "../shared/duration.js";
4
5
  import { errorMessage } from "../shared/text-utils.js";
5
6
  import { formatCost, formatRunDuration, harnessLabel } from "../subagents/format.js";
6
7
  import { getSubAgentRunManager } from "../subagents/runs.js";
@@ -262,7 +263,10 @@ function formatRoleSummaryLine(agent) {
262
263
  const kind = agent.runtime === "external" ? `外部/${agent.harness}` : "内置";
263
264
  const mutates = agent.mutates ?? (agent.tools.includes("write") || agent.tools.includes("edit") ? "write" : "read");
264
265
  const unavailable = agent.unavailable ? ` — ⚠ 不可用:${agent.unavailable}` : "";
265
- return `- \`${agent.name}\` (${kind}, ${mutates}) — ${agent.description}${unavailable}`;
266
+ const modelLabel = agent.runtime === "external" ? (agent.externalModelRef ?? "CLI 决定") : (agent.modelRef ?? "默认");
267
+ const thinkingLabel = agent.thinkingLevel ?? (agent.runtime === "external" ? "未设置" : "默认 medium");
268
+ // Keyless by design: the four positions are fixed — runtime, mutates, model, thinking.
269
+ return `- \`${agent.name}\` (${kind}, ${mutates}, ${modelLabel}, ${thinkingLabel}) — ${agent.description}${unavailable}`;
266
270
  }
267
271
  function formatRoleDetail(agent) {
268
272
  const kind = agent.runtime === "external" ? `外部/${agent.harness}` : "内置";
@@ -276,12 +280,12 @@ function formatRoleDetail(agent) {
276
280
  lines.push(`- ⚠ 不可用:${agent.unavailable}`);
277
281
  lines.push(`- mutates:${agent.mutates ?? "(未声明,由 tools 推断)"}`);
278
282
  if (agent.runtime === "internal") {
279
- lines.push(`- 模型:${agent.modelRef ?? "(默认)"}`, `- tools:${agent.tools.join(", ") || "(none)"}`, `- 预算:maxTurns=${agent.maxTurns} maxToolCalls=${agent.maxToolCalls} maxWallTimeSec=${agent.maxWallTimeSec} bashTimeoutSec=${agent.bashTimeoutSec}`, `- contextMode:${agent.contextMode},memory:${agent.memory}`);
283
+ lines.push(`- model:${agent.modelRef ?? "默认"}`, `- thinking:${agent.thinkingLevel ?? "默认 medium"}`, `- tools:${agent.tools.join(", ") || "(none)"}`, `- 预算:maxTurns=${agent.maxTurns} maxToolCalls=${agent.maxToolCalls} maxWallTimeSec=${agent.maxWallTimeSec} bashTimeoutSec=${agent.bashTimeoutSec}`, `- contextMode:${agent.contextMode},memory:${agent.memory}`);
280
284
  }
281
285
  else {
282
286
  lines.push(`- command:\`${agent.command ?? ""}\`${agent.shell ? "(通过 shell 执行)" : ""}`, `- maxWallTimeSec:${agent.maxWallTimeSec}`);
283
- if (agent.externalModelRef)
284
- lines.push(`- 模型:${agent.externalModelRef}`);
287
+ lines.push(`- model:${agent.externalModelRef ?? "CLI 决定"}`);
288
+ lines.push(`- thinking:${agent.thinkingLevel ?? "未设置(verify 派发默认 medium)"}`);
285
289
  // spec 042 D4: contextMode/memory are effective for external roles too (memory 默认 none,
286
290
  // 显式声明 session/relevant 才会把频道会话状态发给外部进程) — 显示出来而不是只在内置分支里说明。
287
291
  lines.push(`- contextMode:${agent.contextMode},memory:${agent.memory}`);
@@ -361,3 +365,23 @@ export async function handleSubagentsCommand(options) {
361
365
  return `执行 /subagents ${command.action} 失败:${errorMessage(error)}`;
362
366
  }
363
367
  }
368
+ /**
369
+ * Render a `RunNotice` (P0-1/P1a) as a one-line reply — a confirmation, per the command reply
370
+ * conventions. `notices: "off"` is enforced by the caller not invoking this at all; a `"settled"`
371
+ * caller filters `kind: "progress"` out before calling. Returns `undefined` for a notice with
372
+ * nothing worth showing (a progress step that never resolved to a label).
373
+ */
374
+ export function renderRunNotice(notice) {
375
+ if (notice.kind === "progress") {
376
+ return notice.step ? `⏳ ${notice.agent} · ${notice.step}` : undefined;
377
+ }
378
+ const durationText = formatDuration(notice.durationMs);
379
+ switch (notice.status) {
380
+ case "completed":
381
+ return `✅ ${notice.agent} 完成 · ${durationText}`;
382
+ case "cancelled":
383
+ return `🛑 ${notice.agent} 已取消 · ${durationText}`;
384
+ default:
385
+ return `⚠️ ${notice.agent} 失败 · ${durationText}`;
386
+ }
387
+ }
@@ -1,9 +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 { renderSubcommandUsage } from "../agent/commands.js";
5
4
  import { channelJobTaskIds } from "../agent/job-manager.js";
6
- import { capReply } from "../agent/reply-limits.js";
5
+ import { renderSubcommandUsage } from "../commands/catalog.js";
6
+ import { capReply } from "../commands/reply-limits.js";
7
7
  import { formatLocalTime, parseLocalTime, parseWakeInput } from "../shared/local-time.js";
8
8
  import { errorMessage } from "../shared/text-utils.js";
9
9
  import { channelDelegationTaskIds, getSubAgentRunManager } from "../subagents/runs.js";
@@ -1,6 +1,6 @@
1
+ import type { ChannelEvent } from "../channel/channel-event.js";
1
2
  import type { PipiclawTaskDriverSettings } from "../settings.js";
2
3
  import { type TaskLedgerEntry } from "../tasks/ledger.js";
3
- import type { ChannelEvent } from "./channel-event.js";
4
4
  export interface TaskDriverOptions {
5
5
  workspaceDir: string;
6
6
  getKnownChannelIds?: () => Iterable<string>;
@@ -21,6 +21,10 @@ export interface TaskDriverOptions {
21
21
  /** Direct, non-LLM receipt for deterministic governor stops. */
22
22
  notify?: (event: ChannelEvent) => boolean | Promise<boolean>;
23
23
  }
24
+ /**
25
+ * Channels this driver should scan. Live ids come first so a channel discovered on disk under
26
+ * its escaped directory name never displaces the real id the runner map already knows.
27
+ */
24
28
  export declare function discoverTaskChannels(workspaceDir: string, knownChannelIds?: Iterable<string>): Promise<string[]>;
25
29
  export declare function createTaskDriverEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number): ChannelEvent;
26
30
  export declare function taskGovernorReceipt(channelId: string, entry: TaskLedgerEntry, reason: string, nowMs: number): ChannelEvent;
@@ -1,5 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { join } from "node:path";
3
+ import { discoverWorkspaceChannelIds } from "../channel/channel-index.js";
4
+ import { dedupeChannelIdsByDirectory, getChannelDir, isChannelId } from "../channel/channel-paths.js";
3
5
  import * as log from "../log.js";
4
6
  import { PLAYBOOKS_DIR } from "../paths.js";
5
7
  import { parseLocalTime } from "../shared/local-time.js";
@@ -8,8 +10,6 @@ import { taskBudgetViolation } from "../tasks/control.js";
8
10
  import { normalizeTaskFields, readActiveTasks, recurringTaskMissedOccurrence, } from "../tasks/ledger.js";
9
11
  import { activateWaitingTask, escalateTask, openRecurringTaskCycle, updateStoredTask } from "../tasks/store.js";
10
12
  import { nextTaskWake } from "../tasks/task-schedule.js";
11
- import { discoverWorkspaceChannelIds } from "./channel-index.js";
12
- import { isChannelId } from "./channel-paths.js";
13
13
  /** Short debounce so a burst of nudges collapses into a single rescan. */
14
14
  const NUDGE_DEBOUNCE_MS = 50;
15
15
  /** Never schedule a scan closer than this, so near-now horizons cannot spin the loop. */
@@ -20,16 +20,15 @@ const FUTILE_WAKE_LIMIT = 3;
20
20
  * path (deadline and futileCount are). Guards only against a task that keeps "progressing"
21
21
  * without ever converging or hitting its deadline. */
22
22
  const MAX_WAKES_PER_CYCLE = 500;
23
+ /**
24
+ * Channels this driver should scan. Live ids come first so a channel discovered on disk under
25
+ * its escaped directory name never displaces the real id the runner map already knows.
26
+ */
23
27
  export async function discoverTaskChannels(workspaceDir, knownChannelIds = []) {
24
- const channels = new Set();
25
- for (const channelId of knownChannelIds) {
26
- if (isChannelId(channelId))
27
- channels.add(channelId);
28
- }
29
- for (const channelId of await discoverWorkspaceChannelIds(workspaceDir)) {
30
- channels.add(channelId);
31
- }
32
- return Array.from(channels).sort();
28
+ return dedupeChannelIdsByDirectory([
29
+ ...[...knownChannelIds].filter(isChannelId),
30
+ ...(await discoverWorkspaceChannelIds(workspaceDir)),
31
+ ]);
33
32
  }
34
33
  function attemptKey(channelId, taskId) {
35
34
  return `${channelId}\0${taskId}`;
@@ -313,7 +312,9 @@ export class TaskDriver {
313
312
  const channelId = channels[(start + offset) % channels.length];
314
313
  if (!channelId)
315
314
  continue;
316
- const channelDir = join(this.options.workspaceDir, channelId);
315
+ // `channelId` is the raw id, which for a DingTalk group routinely contains `/`;
316
+ // only `getChannelDir` folds it into the escaped directory name that exists on disk.
317
+ const channelDir = getChannelDir(this.options.workspaceDir, channelId);
317
318
  let entries = await readActiveTasks(join(channelDir, "tasks"), nowMs);
318
319
  for (const entry of entries)
319
320
  seen.add(attemptKey(channelId, entry.id));
@@ -1,5 +1,6 @@
1
1
  import { mkdir, readdir, readFile, rename, stat, unlink } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
+ import { getChannelDir } from "../channel/channel-paths.js";
3
4
  import * as log from "../log.js";
4
5
  import { formatLocalTime } from "../shared/local-time.js";
5
6
  import { errorMessage } from "../shared/text-utils.js";
@@ -54,7 +55,7 @@ export async function migrateLegacyTaskScheduleEvents(workspaceDir) {
54
55
  }
55
56
  try {
56
57
  let folded = false;
57
- const document = await updateStoredTask(join(workspaceDir, channelId), parsed.id, (task) => {
58
+ const document = await updateStoredTask(getChannelDir(workspaceDir, channelId), parsed.id, (task) => {
58
59
  if (!task.fields.schedule) {
59
60
  task.fields.schedule = cron;
60
61
  folded = true;
@@ -133,7 +134,7 @@ function resolveMigratedControl(frontmatter) {
133
134
  export async function migrateLegacyTaskState(workspaceDir) {
134
135
  const channels = await discoverTaskChannels(workspaceDir);
135
136
  for (const channelId of channels) {
136
- const channelDir = join(workspaceDir, channelId);
137
+ const channelDir = getChannelDir(workspaceDir, channelId);
137
138
  const dir = join(channelDir, "tasks");
138
139
  let filenames;
139
140
  try {