@oyasmi/pipiclaw 0.9.2-beta.3 → 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 (98) 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 +6 -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/channel/channel-paths.d.ts +16 -0
  25. package/dist/{runtime → channel}/channel-paths.js +20 -0
  26. package/dist/{agent/commands.d.ts → commands/catalog.d.ts} +16 -1
  27. package/dist/{agent/commands.js → commands/catalog.js} +30 -0
  28. package/dist/index.d.ts +1 -1
  29. package/dist/log.js +14 -5
  30. package/dist/main.js +29 -0
  31. package/dist/memory/commands.js +2 -2
  32. package/dist/memory/maintenance-state.d.ts +8 -0
  33. package/dist/memory/maintenance-state.js +47 -4
  34. package/dist/memory/scheduler.d.ts +6 -0
  35. package/dist/memory/scheduler.js +19 -16
  36. package/dist/playbooks/agent-delegation.md +2 -2
  37. package/dist/runtime/bootstrap.d.ts +2 -2
  38. package/dist/runtime/bootstrap.js +14 -6
  39. package/dist/runtime/delivery.d.ts +3 -3
  40. package/dist/runtime/dingtalk.d.ts +4 -4
  41. package/dist/runtime/dingtalk.js +2 -2
  42. package/dist/runtime/durable-dispatch.d.ts +7 -1
  43. package/dist/runtime/durable-dispatch.js +12 -2
  44. package/dist/runtime/event-commands.js +2 -2
  45. package/dist/runtime/events.d.ts +8 -1
  46. package/dist/runtime/events.js +15 -3
  47. package/dist/runtime/project-commands.js +2 -2
  48. package/dist/runtime/skill-commands.d.ts +27 -0
  49. package/dist/runtime/skill-commands.js +72 -0
  50. package/dist/runtime/subagent-commands.js +1 -1
  51. package/dist/runtime/task-commands.js +2 -2
  52. package/dist/runtime/task-driver.d.ts +5 -1
  53. package/dist/runtime/task-driver.js +13 -12
  54. package/dist/runtime/task-migration.js +3 -2
  55. package/dist/runtime/task-wake.d.ts +1 -1
  56. package/dist/runtime/task-wake.js +1 -1
  57. package/dist/settings.d.ts +1 -0
  58. package/dist/settings.js +69 -0
  59. package/dist/shared/token-estimate.d.ts +1 -0
  60. package/dist/shared/token-estimate.js +19 -0
  61. package/dist/subagents/runs.d.ts +9 -4
  62. package/dist/subagents/runs.js +107 -11
  63. package/dist/subagents/tool.js +4 -3
  64. package/dist/tools/glob-match.d.ts +25 -4
  65. package/dist/tools/glob-match.js +175 -53
  66. package/dist/tools/glob.js +5 -2
  67. package/dist/tools/index.d.ts +1 -1
  68. package/dist/tools/registry.d.ts +1 -1
  69. package/dist/tools/send-media.d.ts +1 -1
  70. package/dist/tools/skill.d.ts +15 -0
  71. package/dist/tools/skill.js +16 -8
  72. package/dist/tui/app.js +5 -3
  73. package/dist/tui/commands.d.ts +1 -0
  74. package/dist/tui/commands.js +3 -1
  75. package/dist/tui/terminal-context.d.ts +2 -2
  76. package/dist/tui/terminal-media-sender.d.ts +1 -1
  77. package/dist/tui/turn-controller.d.ts +2 -1
  78. package/dist/tui/turn-controller.js +2 -1
  79. package/examples/sub-agents/README.md +2 -2
  80. package/examples/sub-agents/explorer.md +4 -4
  81. package/examples/sub-agents/git-committer.md +3 -2
  82. package/examples/sub-agents/log-sifter.md +2 -2
  83. package/examples/sub-agents/verifier.md +1 -1
  84. package/examples/sub-agents/worker.md +3 -3
  85. package/package.json +1 -1
  86. package/dist/runtime/channel-paths.d.ts +0 -4
  87. /package/dist/{runtime → channel}/active-session-store.d.ts +0 -0
  88. /package/dist/{runtime → channel}/active-session-store.js +0 -0
  89. /package/dist/{runtime → channel}/channel-event.d.ts +0 -0
  90. /package/dist/{runtime → channel}/channel-event.js +0 -0
  91. /package/dist/{runtime → channel}/channel-index.d.ts +0 -0
  92. /package/dist/{runtime → channel}/channel-index.js +0 -0
  93. /package/dist/{runtime → channel}/project-scope-store.d.ts +0 -0
  94. /package/dist/{runtime → channel}/project-scope-store.js +0 -0
  95. /package/dist/{runtime → channel}/store.d.ts +0 -0
  96. /package/dist/{runtime → channel}/store.js +0 -0
  97. /package/dist/{agent → commands}/reply-limits.d.ts +0 -0
  98. /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,19 +29,15 @@ 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 { handleSkillsCommand as runSkillsCommand } from "./skill-commands.js";
40
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";
@@ -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) {
@@ -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,6 +1,6 @@
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
4
  import { formatDuration } from "../shared/duration.js";
5
5
  import { errorMessage } from "../shared/text-utils.js";
6
6
  import { formatCost, formatRunDuration, harnessLabel } from "../subagents/format.js";
@@ -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 {
@@ -5,10 +5,10 @@
5
5
  * `createRuntimeContext`'s closures.
6
6
  */
7
7
  import { type JobSnapshot } from "../agent/job-manager.js";
8
+ import type { ChannelEvent } from "../channel/channel-event.js";
8
9
  import type { Executor } from "../executor.js";
9
10
  import { type RunRecord } from "../subagents/runs.js";
10
11
  import { type WakeTaskTransitionHooks } from "../tasks/store.js";
11
- import type { ChannelEvent } from "./channel-event.js";
12
12
  /**
13
13
  * Whether a `[JOB:<jobId>] ... belongs to task <taskId>.` wake actually names a job that: exists
14
14
  * on this channel, has actually finished (a still-`running` job cannot have produced this wake —
@@ -5,10 +5,10 @@
5
5
  * `createRuntimeContext`'s closures.
6
6
  */
7
7
  import { getChannelJobManager } from "../agent/job-manager.js";
8
+ import { getChannelDir } from "../channel/channel-paths.js";
8
9
  import { getSubAgentRunManager } from "../subagents/runs.js";
9
10
  import { activateWaitingTask, readStoredTask, rollbackWaitingTask, } from "../tasks/store.js";
10
11
  import { normalizeStoredStatus } from "../tasks/transitions.js";
11
- import { getChannelDir } from "./channel-paths.js";
12
12
  /**
13
13
  * True when `taskId` is currently `active` and enabled — i.e. the task driver already owns
14
14
  * advancing it. A completion wake that could not activate the task (because it was not
@@ -151,6 +151,7 @@ export declare class PipiclawSettingsManager {
151
151
  private settings;
152
152
  private loadErrors;
153
153
  private retiredKeys;
154
+ private invalidEnumValues;
154
155
  /** The file's change token as of the last actual parse; see `reload`. */
155
156
  private loadedStamp;
156
157
  constructor(baseDir: string);
package/dist/settings.js CHANGED
@@ -135,6 +135,69 @@ function hasNestedKey(root, dottedPath) {
135
135
  function findRetiredSettingsKeys(parsed) {
136
136
  return RETIRED_SETTINGS_KEYS.filter((key) => hasNestedKey(parsed, key));
137
137
  }
138
+ /**
139
+ * Every enum-valued key, with the values it accepts.
140
+ *
141
+ * `settings.json` is hand-edited and nothing type-checks it, so a typo used to travel straight
142
+ * into the runtime as a string the code never compares equal to anything. The failure modes were
143
+ * not uniform and none of them said anything: `logging.level: "verbos"` made *every* log record
144
+ * fail its threshold comparison (`LEVEL_ORDER[level] >= NaN`) and silenced the log entirely;
145
+ * `delegation.notices: "liv"` fell through both negative checks and behaved as `live`, the
146
+ * opposite of the "off" a nervous operator was reaching for. Validating here — once, on load —
147
+ * means an unrecognized value is dropped so the documented default applies, and the operator is
148
+ * told which key was ignored.
149
+ *
150
+ * The value lists are literal rather than imported: `ResponseMode` lives in the DingTalk
151
+ * transport, and a value import would tie settings loading to that module's import graph. The
152
+ * `satisfies` clauses keep them honest against the unions they mirror.
153
+ */
154
+ const ENUM_SETTINGS = [
155
+ { path: "logging.level", values: ["debug", "info", "warn", "error"] },
156
+ {
157
+ path: "tui.responseMode",
158
+ values: [
159
+ "full_progress_then_plain_final",
160
+ "rolling_progress_then_plain_final",
161
+ "final_card_only",
162
+ ],
163
+ },
164
+ { path: "delegation.notices", values: ["off", "settled", "live"] },
165
+ ];
166
+ function readNestedKey(root, dottedPath) {
167
+ const segments = dottedPath.split(".");
168
+ const key = segments.pop();
169
+ if (!key)
170
+ return undefined;
171
+ let node = root;
172
+ for (const segment of segments) {
173
+ if (!node || typeof node !== "object" || Array.isArray(node))
174
+ return undefined;
175
+ node = node[segment];
176
+ }
177
+ if (!node || typeof node !== "object" || Array.isArray(node))
178
+ return undefined;
179
+ const parent = node;
180
+ return Object.hasOwn(parent, key) ? { parent, key } : undefined;
181
+ }
182
+ /**
183
+ * Drop every enum key whose value is not one this build understands, and describe what was
184
+ * dropped. Deleting rather than coercing is deliberate: `??` then yields the same default a
185
+ * missing key would, so one bad value cannot produce a state the rest of the code never expects.
186
+ */
187
+ function stripInvalidEnumValues(parsed) {
188
+ const problems = [];
189
+ for (const { path, values } of ENUM_SETTINGS) {
190
+ const found = readNestedKey(parsed, path);
191
+ if (!found)
192
+ continue;
193
+ const value = found.parent[found.key];
194
+ if (value === undefined || values.includes(value))
195
+ continue;
196
+ delete found.parent[found.key];
197
+ problems.push(`${path}: ${JSON.stringify(value)} is not one of ${values.join(" | ")}; using the default instead`);
198
+ }
199
+ return problems;
200
+ }
138
201
  /**
139
202
  * Settings manager for pipiclaw.
140
203
  * Stores global settings in the pipiclaw root directory.
@@ -143,6 +206,7 @@ export class PipiclawSettingsManager {
143
206
  constructor(baseDir) {
144
207
  this.loadErrors = [];
145
208
  this.retiredKeys = [];
209
+ this.invalidEnumValues = [];
146
210
  /** The file's change token as of the last actual parse; see `reload`. */
147
211
  this.loadedStamp = "";
148
212
  this.settingsPath = join(baseDir, "settings.json");
@@ -151,6 +215,7 @@ export class PipiclawSettingsManager {
151
215
  load() {
152
216
  this.loadErrors = [];
153
217
  this.retiredKeys = [];
218
+ this.invalidEnumValues = [];
154
219
  this.loadedStamp = fileStamp(this.settingsPath);
155
220
  if (!existsSync(this.settingsPath)) {
156
221
  return {};
@@ -166,6 +231,7 @@ export class PipiclawSettingsManager {
166
231
  return {};
167
232
  }
168
233
  this.retiredKeys = findRetiredSettingsKeys(parsed);
234
+ this.invalidEnumValues = stripInvalidEnumValues(parsed);
169
235
  return parsed;
170
236
  }
171
237
  catch (error) {
@@ -221,6 +287,9 @@ export class PipiclawSettingsManager {
221
287
  message: `${this.retiredKeys.join(", ")}: no longer configurable; these are now built-in constants and the values here are ignored. Remove them from settings.json.`,
222
288
  });
223
289
  }
290
+ for (const message of this.invalidEnumValues) {
291
+ diagnostics.push({ source: "settings", path: this.settingsPath, severity: "warning", message });
292
+ }
224
293
  return diagnostics;
225
294
  }
226
295
  getCompactionSettings() {
@@ -0,0 +1 @@
1
+ export declare function estimateTokens(text: string): number;