@oyasmi/pipiclaw 0.9.2-beta.3 → 0.9.2-beta.6

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 (142) hide show
  1. package/README.md +3 -0
  2. package/dist/agent/channel-runner.d.ts +45 -19
  3. package/dist/agent/channel-runner.js +156 -102
  4. package/dist/agent/command-extension.js +1 -1
  5. package/dist/agent/context-budget.d.ts +17 -1
  6. package/dist/agent/context-budget.js +20 -6
  7. package/dist/agent/job-manager.d.ts +3 -1
  8. package/dist/agent/job-manager.js +7 -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/session-events.js +2 -22
  17. package/dist/agent/turn-prompt.d.ts +35 -0
  18. package/dist/agent/turn-prompt.js +37 -0
  19. package/dist/agent/turn-recovery.js +1 -1
  20. package/dist/agent/turn-state.d.ts +60 -0
  21. package/dist/agent/turn-state.js +95 -0
  22. package/dist/agent/types.d.ts +5 -4
  23. package/dist/{runtime → channel}/channel-context.d.ts +10 -2
  24. package/dist/{runtime → channel}/channel-context.js +6 -2
  25. package/dist/{runtime → channel}/channel-event.d.ts +39 -0
  26. package/dist/channel/channel-event.js +11 -0
  27. package/dist/channel/channel-paths.d.ts +16 -0
  28. package/dist/{runtime → channel}/channel-paths.js +20 -0
  29. package/dist/{runtime → channel}/project-scope-store.js +6 -11
  30. package/dist/{runtime → channel}/store.d.ts +7 -0
  31. package/dist/{agent/commands.d.ts → commands/catalog.d.ts} +17 -2
  32. package/dist/{agent/commands.js → commands/catalog.js} +30 -0
  33. package/dist/index.d.ts +1 -1
  34. package/dist/log.js +14 -5
  35. package/dist/main.js +29 -0
  36. package/dist/memory/bootstrap.js +3 -5
  37. package/dist/memory/candidates.js +2 -4
  38. package/dist/memory/commands.js +2 -2
  39. package/dist/memory/files.d.ts +0 -1
  40. package/dist/memory/files.js +6 -9
  41. package/dist/memory/maintenance-state.d.ts +8 -0
  42. package/dist/memory/maintenance-state.js +51 -4
  43. package/dist/memory/scheduler.d.ts +6 -0
  44. package/dist/memory/scheduler.js +19 -16
  45. package/dist/playbooks/agent-delegation.md +2 -2
  46. package/dist/runtime/bootstrap.d.ts +14 -8
  47. package/dist/runtime/bootstrap.js +158 -81
  48. package/dist/runtime/delivery.d.ts +3 -3
  49. package/dist/runtime/delivery.js +1 -0
  50. package/dist/runtime/dingtalk.d.ts +62 -6
  51. package/dist/runtime/dingtalk.js +194 -85
  52. package/dist/runtime/durable-dispatch.d.ts +7 -1
  53. package/dist/runtime/durable-dispatch.js +12 -2
  54. package/dist/runtime/event-commands.js +2 -2
  55. package/dist/runtime/events.d.ts +8 -1
  56. package/dist/runtime/events.js +15 -3
  57. package/dist/runtime/inbound-media.d.ts +60 -0
  58. package/dist/runtime/inbound-media.js +95 -0
  59. package/dist/runtime/project-commands.js +2 -2
  60. package/dist/runtime/skill-commands.d.ts +27 -0
  61. package/dist/runtime/skill-commands.js +72 -0
  62. package/dist/runtime/subagent-commands.js +1 -1
  63. package/dist/runtime/task-commands.js +2 -2
  64. package/dist/runtime/task-driver.d.ts +12 -1
  65. package/dist/runtime/task-driver.js +36 -56
  66. package/dist/runtime/task-migration.d.ts +11 -0
  67. package/dist/runtime/task-migration.js +14 -2
  68. package/dist/runtime/task-wake.d.ts +1 -1
  69. package/dist/runtime/task-wake.js +1 -1
  70. package/dist/security/command-guard.js +1 -3
  71. package/dist/security/config.d.ts +1 -1
  72. package/dist/security/config.js +8 -32
  73. package/dist/security/path-guard.js +1 -6
  74. package/dist/security/project-scope.js +1 -3
  75. package/dist/settings.d.ts +3 -2
  76. package/dist/settings.js +82 -20
  77. package/dist/shared/atomic-file.d.ts +2 -3
  78. package/dist/shared/atomic-file.js +8 -9
  79. package/dist/shared/config-diagnostic.d.ts +21 -0
  80. package/dist/shared/config-diagnostic.js +32 -0
  81. package/dist/shared/numeric.d.ts +7 -0
  82. package/dist/shared/numeric.js +19 -0
  83. package/dist/shared/text-utils.d.ts +10 -0
  84. package/dist/shared/text-utils.js +16 -0
  85. package/dist/shared/token-estimate.d.ts +1 -0
  86. package/dist/shared/token-estimate.js +19 -0
  87. package/dist/shared/types.d.ts +23 -0
  88. package/dist/shared/types.js +12 -0
  89. package/dist/shared/with-timeout.d.ts +3 -0
  90. package/dist/shared/with-timeout.js +8 -0
  91. package/dist/subagents/discovery.d.ts +7 -7
  92. package/dist/subagents/discovery.js +27 -59
  93. package/dist/subagents/runs.d.ts +15 -4
  94. package/dist/subagents/runs.js +118 -11
  95. package/dist/subagents/tool.js +199 -131
  96. package/dist/subagents/workspace-lease.js +1 -3
  97. package/dist/tasks/control.d.ts +2 -0
  98. package/dist/tasks/control.js +2 -0
  99. package/dist/tasks/ledger.d.ts +0 -9
  100. package/dist/tasks/ledger.js +92 -158
  101. package/dist/tools/config.d.ts +1 -1
  102. package/dist/tools/config.js +9 -46
  103. package/dist/tools/glob-match.d.ts +25 -4
  104. package/dist/tools/glob-match.js +175 -53
  105. package/dist/tools/glob.js +5 -2
  106. package/dist/tools/index.d.ts +1 -1
  107. package/dist/tools/registry.d.ts +1 -1
  108. package/dist/tools/send-media.d.ts +1 -1
  109. package/dist/tools/skill.d.ts +15 -0
  110. package/dist/tools/skill.js +17 -11
  111. package/dist/tools/truncate.js +24 -28
  112. package/dist/tui/app.js +6 -4
  113. package/dist/tui/commands.d.ts +1 -0
  114. package/dist/tui/commands.js +3 -1
  115. package/dist/tui/terminal-context.d.ts +2 -2
  116. package/dist/tui/terminal-media-sender.d.ts +1 -1
  117. package/dist/tui/turn-controller.d.ts +2 -1
  118. package/dist/tui/turn-controller.js +2 -1
  119. package/dist/web/config.js +3 -15
  120. package/examples/sub-agents/README.md +2 -2
  121. package/examples/sub-agents/builder.md +1 -1
  122. package/examples/sub-agents/documenter.md +1 -1
  123. package/examples/sub-agents/explorer.md +4 -4
  124. package/examples/sub-agents/git-committer.md +5 -4
  125. package/examples/sub-agents/log-sifter.md +4 -4
  126. package/examples/sub-agents/planner.md +1 -1
  127. package/examples/sub-agents/reviewer.md +1 -1
  128. package/examples/sub-agents/verifier.md +1 -1
  129. package/examples/sub-agents/worker.md +3 -3
  130. package/package.json +3 -2
  131. package/dist/agent/index.d.ts +0 -2
  132. package/dist/agent/index.js +0 -1
  133. package/dist/runtime/channel-event.js +0 -1
  134. package/dist/runtime/channel-paths.d.ts +0 -4
  135. /package/dist/{runtime → channel}/active-session-store.d.ts +0 -0
  136. /package/dist/{runtime → channel}/active-session-store.js +0 -0
  137. /package/dist/{runtime → channel}/channel-index.d.ts +0 -0
  138. /package/dist/{runtime → channel}/channel-index.js +0 -0
  139. /package/dist/{runtime → channel}/project-scope-store.d.ts +0 -0
  140. /package/dist/{runtime → channel}/store.js +0 -0
  141. /package/dist/{agent → commands}/reply-limits.d.ts +0 -0
  142. /package/dist/{agent → commands}/reply-limits.js +0 -0
@@ -26,6 +26,26 @@ export function getChannelDirName(channelId) {
26
26
  export function getChannelDir(baseDir, channelId) {
27
27
  return join(baseDir, getChannelDirName(channelId));
28
28
  }
29
+ /**
30
+ * Collapse ids that name the same channel directory, keeping the first spelling offered.
31
+ *
32
+ * Background workers assemble their channel list from several sources, and only some of them
33
+ * store a real id: `CHANNELS.md` and the live runner map do, while a directory listing (of the
34
+ * workspace, or of the maintenance state dir) can only report the *escaped* name, which cannot
35
+ * be turned back into the id it came from. Left alone, one channel then appears twice — once
36
+ * under its real id and once under a spelling no transport can deliver to — and every unit of
37
+ * work for it runs twice. Callers pass their sources most-authoritative-first; this keeps that
38
+ * spelling and drops the rest.
39
+ */
40
+ export function dedupeChannelIdsByDirectory(channelIds) {
41
+ const byDirectory = new Map();
42
+ for (const channelId of channelIds) {
43
+ const dirName = getChannelDirName(channelId);
44
+ if (!byDirectory.has(dirName))
45
+ byDirectory.set(dirName, channelId);
46
+ }
47
+ return Array.from(byDirectory.values()).sort();
48
+ }
29
49
  export function ensureChannelDir(baseDir, channelId) {
30
50
  const channelDir = getChannelDir(baseDir, channelId);
31
51
  mkdirSync(channelDir, { recursive: true });
@@ -1,8 +1,7 @@
1
- import { randomUUID } from "node:crypto";
2
- import { existsSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
1
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
3
2
  import { join } from "node:path";
4
3
  import { currentProjectSandboxStatus, isWithinAllowedRoots, } from "../security/project-scope.js";
5
- import { writeFileAtomically } from "../shared/atomic-file.js";
4
+ import { writeFileAtomically, writeFileAtomicallySync } from "../shared/atomic-file.js";
6
5
  const SELECTION_FILENAME = "project.json";
7
6
  export function getProjectSelectionPath(channelDir) {
8
7
  return join(channelDir, SELECTION_FILENAME);
@@ -29,15 +28,11 @@ export function readProjectSelection(channelDir) {
29
28
  }
30
29
  return raw;
31
30
  }
32
- /** Same durability tradeoff as every other atomic writer in this codebase (temp + rename), minus
33
- * the fsync `writeFileAtomically` does — used only for the one-time, in-constructor migration
34
- * write (D3.3); every explicit mutation (`/project set|reset`) goes through the fsync'd async
35
- * `writeFileAtomically` in `commitProjectSelection` instead. */
31
+ /** Used only for the one-time, in-constructor migration write (D3.3); every explicit mutation
32
+ * (`/project set|reset`) goes through the async `writeFileAtomically` in `commitProjectSelection`
33
+ * instead — that one is on a mutation path that can already afford to await. */
36
34
  function writeProjectSelectionSync(channelDir, selection) {
37
- const path = getProjectSelectionPath(channelDir);
38
- const tempPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
39
- writeFileSync(tempPath, `${JSON.stringify(selection, null, 2)}\n`, "utf-8");
40
- renameSync(tempPath, path);
35
+ writeFileAtomicallySync(getProjectSelectionPath(channelDir), `${JSON.stringify(selection, null, 2)}\n`);
41
36
  }
42
37
  export async function commitProjectSelection(channelDir, projectRoot, updatedBy) {
43
38
  const selection = {
@@ -8,6 +8,13 @@ export interface LoggedMessage {
8
8
  isBot: boolean;
9
9
  deliveryMode?: "steer" | "followUp";
10
10
  skipContextSync?: boolean;
11
+ /**
12
+ * Paths of any images the user sent alongside `text` (spec 049), relative to the channel
13
+ * directory. Kept even for an image that never made it into the model's context (unsupported
14
+ * format, oversized, model without vision support) — this is the only place that record
15
+ * survives once the turn's `[图片N: ...]` marker has scrolled out of `HISTORY.md`.
16
+ */
17
+ images?: string[];
11
18
  }
12
19
  export interface ChannelStoreConfig {
13
20
  workingDir: string;
@@ -1,5 +1,20 @@
1
- export type BuiltInCommandName = "help" | "steer" | "followup" | "stop" | "events" | "tasks" | "status" | "usage" | "context" | "subagents" | "project";
2
- /** The four transport commands handled by `ChannelRunner.handleBuiltinCommand`. */
1
+ /**
2
+ * The product-wide slash-command catalog: every command's name, description, subcommands and
3
+ * examples, plus the parsing and usage/help rendering built on top of them.
4
+ *
5
+ * It lives in its own domain, not in `src/agent/`, because the catalog describes commands handled
6
+ * in three different layers — the runtime (`/tasks`, `/events`, `/subagents`, `/project`,
7
+ * `/skills`), the agent session (`/model`, `/compact`, `/new`) and memory (`/memory`) — and is read
8
+ * by all of them plus the TUI. Only the catalog and the reply shape are shared: each *handler*
9
+ * still lives in the layer that owns the state it touches (`runtime/*-commands.ts`,
10
+ * `memory/commands.ts`, `agent/command-extension.ts`). This file has no imports at all, so nothing
11
+ * here can drag a layer into another one.
12
+ *
13
+ * The six reply conventions these commands follow are recorded in AGENTS.md; `reply-limits.ts`
14
+ * next to this file enforces rule 5 (the length budget).
15
+ */
16
+ export type BuiltInCommandName = "help" | "steer" | "followup" | "stop" | "events" | "tasks" | "status" | "usage" | "context" | "subagents" | "project" | "skills";
17
+ /** The five transport commands handled by `ChannelRunner.handleBuiltinCommand`. */
3
18
  export type RunnerBuiltInCommandName = "help" | "stop" | "steer" | "followup" | "context";
4
19
  /**
5
20
  * The commands with no mid-turn state to touch: each renders a text report from disk/in-memory
@@ -1,3 +1,18 @@
1
+ /**
2
+ * The product-wide slash-command catalog: every command's name, description, subcommands and
3
+ * examples, plus the parsing and usage/help rendering built on top of them.
4
+ *
5
+ * It lives in its own domain, not in `src/agent/`, because the catalog describes commands handled
6
+ * in three different layers — the runtime (`/tasks`, `/events`, `/subagents`, `/project`,
7
+ * `/skills`), the agent session (`/model`, `/compact`, `/new`) and memory (`/memory`) — and is read
8
+ * by all of them plus the TUI. Only the catalog and the reply shape are shared: each *handler*
9
+ * still lives in the layer that owns the state it touches (`runtime/*-commands.ts`,
10
+ * `memory/commands.ts`, `agent/command-extension.ts`). This file has no imports at all, so nothing
11
+ * here can drag a layer into another one.
12
+ *
13
+ * The six reply conventions these commands follow are recorded in AGENTS.md; `reply-limits.ts`
14
+ * next to this file enforces rule 5 (the length budget).
15
+ */
1
16
  /**
2
17
  * Transport commands: handled directly by the runtime layer (never sent to the
3
18
  * LLM). All of them are accepted while a task is streaming.
@@ -177,6 +192,21 @@ export const BUILT_IN_COMMANDS = [
177
192
  { name: "reset", description: "切回 app 默认项目目录", example: "/project reset" },
178
193
  ],
179
194
  },
195
+ {
196
+ name: "skills",
197
+ argumentHint: "[list|show <name>]",
198
+ description: "列出工作区 skills(含未加载及原因),或查看单个 skill 的完整正文",
199
+ availableWhileBusy: true,
200
+ subcommands: [
201
+ { name: "list", description: "列出工作区 skills(默认动作,可省略)", example: "/skills" },
202
+ {
203
+ name: "show",
204
+ args: "<name>",
205
+ description: "查看单个 skill 的元信息与正文",
206
+ example: "/skills show release-checklist",
207
+ },
208
+ ],
209
+ },
180
210
  ];
181
211
  /**
182
212
  * Session commands: handled inside the Pipiclaw session layer (SDK command
package/dist/index.d.ts CHANGED
@@ -9,9 +9,9 @@
9
9
  * Keep this list small. Every name added here also becomes a knip blind spot,
10
10
  * because `src/index.ts` is a knip entry point.
11
11
  */
12
+ export type { ChannelContext, FinalDelivery, ProgressStyle } from "./channel/channel-context.js";
12
13
  export { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "./paths.js";
13
14
  export { type BootstrapPaths, type BootstrapResult, isBootstrapExitError } from "./runtime/app-home.js";
14
15
  export { type AppContext, type BootstrapOptions, bootstrap } from "./runtime/bootstrap.js";
15
- export type { ChannelContext, FinalDelivery, ProgressStyle } from "./runtime/channel-context.js";
16
16
  export { DingTalkBot, type DingTalkConfig, type DingTalkEvent, type DingTalkHandler, type ResponseMode, } from "./runtime/dingtalk.js";
17
17
  export type { PipiclawSettings } from "./settings.js";
package/dist/log.js CHANGED
@@ -6,7 +6,19 @@ const LEVEL_ORDER = { debug: 0, info: 1, warn: 2, error: 3 };
6
6
  const MAX_VALUE_LENGTH = 240;
7
7
  const MAX_COLLECTION_ITEMS = 10;
8
8
  const SENSITIVE_KEY = /(?:api[_-]?key|authorization|cookie|credential|password|secret|private[_-]?key|(?:^|[_-])token(?:$|[_-])|token$|^env(?:ironment)?$)/i;
9
- const SENSITIVE_TEXT = /\b(?:authorization|cookie|token|api[_-]?key|secret|password)\s*[:=]\s*[^\s,;]+|\bbearer\s+[^\s,;]+/gi;
9
+ /**
10
+ * Free-text secret redaction. Group 1 is everything that must survive — the key and its
11
+ * separator, or a bare `bearer` scheme — and everything after it is the value, replaced whole.
12
+ *
13
+ * Two details are load-bearing. The value swallows an optional auth-scheme word, because
14
+ * `Authorization: Bearer <token>` otherwise ends the match at the space after "Bearer": the
15
+ * scheme got redacted, the token survived, and the `bearer` alternative could not re-match a
16
+ * region the first alternative had already consumed. And the surviving prefix comes from a
17
+ * capture group rather than being reconstructed by splitting the match on a guessed separator —
18
+ * a value containing `:` (`token=abc:def`) made that guess pick the wrong one and leave the
19
+ * first half of the secret in the log.
20
+ */
21
+ const SENSITIVE_TEXT = /(\b(?:authorization|cookie|token|api[_-]?key|secret|password)"?\s*[:=]\s*|\bbearer\s+)"?(?:(?:bearer|basic|token|digest)\s+)?[^\s,;"']+"?/gi;
10
22
  function readEnvLevel() {
11
23
  const raw = process.env.PIPICLAW_LOG_LEVEL?.trim().toLowerCase();
12
24
  return raw && raw in LEVEL_ORDER ? raw : undefined;
@@ -46,10 +58,7 @@ function isEnabled(level) {
46
58
  return LEVEL_ORDER[level] >= LEVEL_ORDER[thresholdLevel];
47
59
  }
48
60
  function summarizeString(value) {
49
- const redacted = value.replace(SENSITIVE_TEXT, (match) => {
50
- const separator = match.includes(":") ? ":" : match.includes("=") ? "=" : " ";
51
- return `${match.split(separator, 1)[0]}${separator}[REDACTED]`;
52
- });
61
+ const redacted = value.replace(SENSITIVE_TEXT, (_match, keyAndSeparator) => `${keyAndSeparator}[REDACTED]`);
53
62
  const normalized = redacted.replace(/\s+/g, " ").trim();
54
63
  return normalized.length > MAX_VALUE_LENGTH
55
64
  ? `${normalized.slice(0, MAX_VALUE_LENGTH)}… (length=${normalized.length})`
package/dist/main.js CHANGED
@@ -1,8 +1,36 @@
1
1
  #!/usr/bin/env node
2
+ import * as log from "./log.js";
2
3
  import { runAuth } from "./models/auth-cli.js";
3
4
  import { formatCliCommandsHelp, isBootstrapExitError } from "./runtime/app-home.js";
4
5
  import { bootstrap } from "./runtime/bootstrap.js";
6
+ import { errorMessage } from "./shared/text-utils.js";
5
7
  import { runTui } from "./tui/cli.js";
8
+ /**
9
+ * Node exits the process on an unhandled rejection, and the daemon is long-lived enough that
10
+ * this has to leave a trace: without a handler the crash reaches stderr only, so a daemon that
11
+ * died overnight leaves nothing in the runtime log to explain it.
12
+ *
13
+ * This records and exits — it deliberately does not swallow. An unhandled rejection means some
14
+ * invariant already failed, and a process that keeps serving after one is a worse outcome than
15
+ * a restart. Individual timer/watch callbacks that can fail routinely catch at their own call
16
+ * site; this is the backstop for the ones nobody predicted.
17
+ */
18
+ function installFatalRejectionHandler() {
19
+ process.on("unhandledRejection", (reason) => {
20
+ log.logEvent("error", "system.fatal", "Unhandled promise rejection; shutting down", {
21
+ details: errorMessage(reason),
22
+ });
23
+ // Bound the flush: a sink that cannot drain must not turn a crash into a hang.
24
+ const forceExit = setTimeout(() => process.exit(1), 2000);
25
+ void log
26
+ .flushLogging()
27
+ .catch(() => { })
28
+ .finally(() => {
29
+ clearTimeout(forceExit);
30
+ process.exit(1);
31
+ });
32
+ });
33
+ }
6
34
  function handleError(error) {
7
35
  if (isBootstrapExitError(error)) {
8
36
  process.exit(error.code);
@@ -27,6 +55,7 @@ else if (command === undefined || command === "run" || command.startsWith("-"))
27
55
  // a bare `pipiclaw` still runs it, and leading flags (--version/--help) are
28
56
  // handled by bootstrap's parseArgs. The daemon does not resolve, so there is
29
57
  // no success path to exit on — only surface fatal errors.
58
+ installFatalRejectionHandler();
30
59
  bootstrap(process.argv).catch(handleError);
31
60
  }
32
61
  else {
@@ -1,5 +1,6 @@
1
1
  import { splitH2Sections } from "../shared/markdown-sections.js";
2
2
  import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
3
+ import { stripCrAndTrim } from "../shared/text-utils.js";
3
4
  import { buildMemoryCandidateId } from "./candidates.js";
4
5
  import { parseChannelMemoryEntries } from "./files.js";
5
6
  const FIRST_TURN_MEMORY_SNAPSHOT_MAX_CHARS = 3_000;
@@ -12,9 +13,6 @@ const MIN_SECTION_CHARS = 600;
12
13
  const MIN_SECTION_UNITS = 100;
13
14
  const CHANNEL_MEMORY_WEIGHT = 0.6;
14
15
  const ZERO_BUDGET = { chars: 0, units: 0 };
15
- function normalizeContent(content) {
16
- return content.replace(/\r/g, "").trim();
17
- }
18
16
  function hasVisibleContent(content) {
19
17
  return content.replace(/<!--[\s\S]*?-->/g, "").trim().length > 0;
20
18
  }
@@ -93,8 +91,8 @@ export function buildFirstTurnMemoryBootstrapResult(options) {
93
91
  chars: options.maxChars ?? FIRST_TURN_MEMORY_SNAPSHOT_MAX_CHARS,
94
92
  units: options.maxUnits ?? FIRST_TURN_BOOTSTRAP_MAX_UNITS,
95
93
  };
96
- const channelMemory = normalizeContent(options.channelMemory);
97
- const workspaceMemory = normalizeContent(options.workspaceMemory);
94
+ const channelMemory = stripCrAndTrim(options.channelMemory);
95
+ const workspaceMemory = stripCrAndTrim(options.workspaceMemory);
98
96
  if (!channelMemory && !workspaceMemory) {
99
97
  return { renderedText: "", includedCandidateIds: [] };
100
98
  }
@@ -2,12 +2,10 @@ import { stat } from "fs/promises";
2
2
  import { join } from "path";
3
3
  import { readOptionalTextFile } from "../shared/fs-utils.js";
4
4
  import { splitH1Sections, splitH2Sections } from "../shared/markdown-sections.js";
5
+ import { stripCrAndTrim } from "../shared/text-utils.js";
5
6
  import { getChannelHistoryPath, getChannelMemoryPath, getChannelSessionPath, parseChannelMemoryEntries, parseUpdateHeadingTimestamp, } from "./files.js";
6
- function normalizeContent(content) {
7
- return content.replace(/\r/g, "").trim();
8
- }
9
7
  async function readOptionalFile(path) {
10
- return normalizeContent(await readOptionalTextFile(path));
8
+ return stripCrAndTrim(await readOptionalTextFile(path));
11
9
  }
12
10
  function slugify(value) {
13
11
  return (value
@@ -1,5 +1,5 @@
1
- import { renderSubcommandUsage } from "../agent/commands.js";
2
- import { capReply } from "../agent/reply-limits.js";
1
+ import { renderSubcommandUsage } from "../commands/catalog.js";
2
+ import { capReply } from "../commands/reply-limits.js";
3
3
  import { readOptionalTextFile } from "../shared/fs-utils.js";
4
4
  import { localDayKey, parseLocalTime } from "../shared/local-time.js";
5
5
  import { clipText } from "../shared/text-utils.js";
@@ -59,7 +59,6 @@ export interface HistoryBlock {
59
59
  export declare function getChannelMemoryPath(channelDir: string): string;
60
60
  export declare function getChannelHistoryPath(channelDir: string): string;
61
61
  export declare function getChannelSessionPath(channelDir: string): string;
62
- export declare function ensureChannelMemoryFiles(channelDir: string): Promise<void>;
63
62
  export declare function ensureChannelMemoryFilesSync(channelDir: string): void;
64
63
  export declare function readChannelMemory(channelDir: string): Promise<string>;
65
64
  export declare function readChannelHistory(channelDir: string): Promise<string>;
@@ -149,7 +149,7 @@ export async function applyChannelMemoryOps(channelDir, ops, timestamp = formatL
149
149
  if (ops.length === 0) {
150
150
  return result;
151
151
  }
152
- await ensureChannelMemoryFiles(channelDir);
152
+ ensureChannelMemoryFilesSync(channelDir);
153
153
  const path = getChannelMemoryPath(channelDir);
154
154
  const existing = await readOptionalTextFile(path);
155
155
  const lines = existing.replace(/\r/g, "").split("\n");
@@ -330,9 +330,6 @@ export function getChannelHistoryPath(channelDir) {
330
330
  export function getChannelSessionPath(channelDir) {
331
331
  return join(channelDir, "SESSION.md");
332
332
  }
333
- export async function ensureChannelMemoryFiles(channelDir) {
334
- ensureChannelMemoryFilesSync(channelDir);
335
- }
336
333
  export function ensureChannelMemoryFilesSync(channelDir) {
337
334
  const memoryPath = getChannelMemoryPath(channelDir);
338
335
  const historyPath = getChannelHistoryPath(channelDir);
@@ -358,7 +355,7 @@ export async function readChannelSession(channelDir) {
358
355
  return readOptionalTextFile(getChannelSessionPath(channelDir));
359
356
  }
360
357
  export async function rewriteChannelMemory(channelDir, content) {
361
- await ensureChannelMemoryFiles(channelDir);
358
+ ensureChannelMemoryFilesSync(channelDir);
362
359
  const path = getChannelMemoryPath(channelDir);
363
360
  await backupBeforeRewrite(channelDir, path);
364
361
  const nextContent = normalizeContent(content) || DEFAULT_CHANNEL_MEMORY;
@@ -366,14 +363,14 @@ export async function rewriteChannelMemory(channelDir, content) {
366
363
  await syncMemoryMetadata(channelDir, parseChannelMemoryEntries(nextContent));
367
364
  }
368
365
  export async function rewriteChannelHistory(channelDir, content) {
369
- await ensureChannelMemoryFiles(channelDir);
366
+ ensureChannelMemoryFilesSync(channelDir);
370
367
  const path = getChannelHistoryPath(channelDir);
371
368
  await backupBeforeRewrite(channelDir, path);
372
369
  const nextContent = normalizeContent(content) || DEFAULT_CHANNEL_HISTORY;
373
370
  await writeFileAtomically(path, nextContent);
374
371
  }
375
372
  export async function rewriteChannelSession(channelDir, content) {
376
- await ensureChannelMemoryFiles(channelDir);
373
+ ensureChannelMemoryFilesSync(channelDir);
377
374
  const nextContent = normalizeContent(content) || DEFAULT_CHANNEL_SESSION;
378
375
  await writeFileAtomically(getChannelSessionPath(channelDir), nextContent);
379
376
  }
@@ -390,7 +387,7 @@ export async function appendChannelHistoryArchive(channelDir, block) {
390
387
  if (!trimmedContent) {
391
388
  return;
392
389
  }
393
- await ensureChannelMemoryFiles(channelDir);
390
+ ensureChannelMemoryFilesSync(channelDir);
394
391
  const path = getChannelHistoryArchivePath(channelDir);
395
392
  const renderedBlock = [`## Archived ${block.timestamp}`, trimmedContent].join("\n\n");
396
393
  const currentSize = await stat(path)
@@ -414,7 +411,7 @@ export async function appendChannelHistoryBlock(channelDir, block) {
414
411
  if (!trimmedContent) {
415
412
  return;
416
413
  }
417
- await ensureChannelMemoryFiles(channelDir);
414
+ ensureChannelMemoryFilesSync(channelDir);
418
415
  const path = getChannelHistoryPath(channelDir);
419
416
  const existing = await readOptionalTextFile(path);
420
417
  const renderedBlock = [`## ${block.timestamp}`, trimmedContent].join("\n\n");
@@ -22,6 +22,14 @@ export interface MemoryActivityEvent {
22
22
  latestSessionEntryId?: string;
23
23
  }
24
24
  export declare function getMemoryMaintenanceStateDir(appHomeDir: string): string;
25
+ /**
26
+ * One flat file per channel, named by the same escaped form directories use.
27
+ *
28
+ * The id goes into a filename here, and a DingTalk group id routinely contains `/`, so writing
29
+ * it raw put the file in a subdirectory of the state dir — `group_a/b==.json`. Reads and writes
30
+ * agreed, so nothing was lost, but {@link getMemoryMaintenanceStateDir}'s only listing walks the
31
+ * top level: every such channel was invisible to the scheduler's state-derived discovery.
32
+ */
25
33
  export declare function getMemoryMaintenanceStatePath(appHomeDir: string, channelId: string): string;
26
34
  export declare function readMemoryMaintenanceState(appHomeDir: string, channelId: string): Promise<MemoryMaintenanceState>;
27
35
  export declare function updateMemoryMaintenanceState(appHomeDir: string, channelId: string, update: (state: MemoryMaintenanceState) => MemoryMaintenanceState): Promise<MemoryMaintenanceState>;
@@ -1,5 +1,6 @@
1
- import { readFile } from "node:fs/promises";
2
- import { join } from "node:path";
1
+ import { readFile, rmdir, unlink } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+ import { getChannelDirName } from "../channel/channel-paths.js";
3
4
  import * as log from "../log.js";
4
5
  import { writeFileAtomically } from "../shared/atomic-file.js";
5
6
  import { parseLocalTime } from "../shared/local-time.js";
@@ -9,8 +10,31 @@ const stateUpdateQueue = createSerialQueue();
9
10
  export function getMemoryMaintenanceStateDir(appHomeDir) {
10
11
  return join(appHomeDir, "state", "memory");
11
12
  }
13
+ /**
14
+ * One flat file per channel, named by the same escaped form directories use.
15
+ *
16
+ * The id goes into a filename here, and a DingTalk group id routinely contains `/`, so writing
17
+ * it raw put the file in a subdirectory of the state dir — `group_a/b==.json`. Reads and writes
18
+ * agreed, so nothing was lost, but {@link getMemoryMaintenanceStateDir}'s only listing walks the
19
+ * top level: every such channel was invisible to the scheduler's state-derived discovery.
20
+ */
12
21
  export function getMemoryMaintenanceStatePath(appHomeDir, channelId) {
13
- return join(getMemoryMaintenanceStateDir(appHomeDir), `${channelId}.json`);
22
+ return join(getMemoryMaintenanceStateDir(appHomeDir), `${getChannelDirName(channelId)}.json`);
23
+ }
24
+ /**
25
+ * Where a pre-escaping runtime put the same channel's state. Only differs for ids containing
26
+ * `/`, and only matters until the next write moves the state to its canonical path — but the
27
+ * state carries maintenance cadence and transcript cursors, so dropping it would silently
28
+ * re-run structural maintenance and re-scan the transcript for every affected group.
29
+ *
30
+ * RETIRE AT v0.9.3, same rationale as the header comment in `../runtime/task-migration.js`:
31
+ * by the stable cut, every still-running group channel with a `/` in its id will have had its
32
+ * state folded onto the canonical path at least once, so this fallback read finds nothing.
33
+ */
34
+ function legacyStatePath(appHomeDir, channelId) {
35
+ return getChannelDirName(channelId) === channelId
36
+ ? undefined
37
+ : join(getMemoryMaintenanceStateDir(appHomeDir), `${channelId}.json`);
14
38
  }
15
39
  function createDefaultState(channelId) {
16
40
  return {
@@ -74,19 +98,42 @@ export async function readMemoryMaintenanceState(appHomeDir, channelId) {
74
98
  }
75
99
  catch (error) {
76
100
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
77
- return createDefaultState(channelId);
101
+ const legacy = await readLegacyState(appHomeDir, channelId);
102
+ return legacy ?? createDefaultState(channelId);
78
103
  }
79
104
  const message = errorMessage(error);
80
105
  log.logWarning(`[${channelId}] Failed to read memory maintenance state; rebuilding defaults`, message);
81
106
  return createDefaultState(channelId);
82
107
  }
83
108
  }
109
+ async function readLegacyState(appHomeDir, channelId) {
110
+ const path = legacyStatePath(appHomeDir, channelId);
111
+ if (!path)
112
+ return undefined;
113
+ try {
114
+ return normalizeState(channelId, JSON.parse(await readFile(path, "utf-8")));
115
+ }
116
+ catch {
117
+ return undefined; // absent or unreadable ⇒ the caller falls back to defaults, as before
118
+ }
119
+ }
84
120
  export async function updateMemoryMaintenanceState(appHomeDir, channelId, update) {
85
121
  const path = getMemoryMaintenanceStatePath(appHomeDir, channelId);
86
122
  return stateUpdateQueue.run(path, async () => {
87
123
  const current = await readMemoryMaintenanceState(appHomeDir, channelId);
88
124
  const next = normalizeState(channelId, update(current));
89
125
  await writeFileAtomically(path, `${JSON.stringify(next, null, 2)}\n`);
126
+ // The canonical file now holds everything the legacy one did; leaving it would keep a
127
+ // stale copy around forever, since reads only fall back when the canonical file is gone.
128
+ const legacy = legacyStatePath(appHomeDir, channelId);
129
+ if (legacy) {
130
+ await unlink(legacy).catch(() => { });
131
+ // ...along with the directory the raw id created, which `rmdir` leaves alone if
132
+ // another channel's state still lives there. Tidying only; failure changes nothing.
133
+ const strayDir = dirname(legacy);
134
+ if (strayDir !== getMemoryMaintenanceStateDir(appHomeDir))
135
+ await rmdir(strayDir).catch(() => { });
136
+ }
90
137
  return next;
91
138
  });
92
139
  }
@@ -31,6 +31,12 @@ export interface MemoryMaintenanceSchedulerOptions {
31
31
  };
32
32
  intervalMs?: number;
33
33
  }
34
+ /**
35
+ * Every channel maintenance should visit, most authoritative source first: the live runner map
36
+ * holds real ids, `CHANNELS.md` does too, and the two directory listings can only offer escaped
37
+ * names. Deduplicating by directory keeps one entry per channel, so a group whose id contains
38
+ * `/` is maintained once — under an id the rest of the runtime can act on — rather than twice.
39
+ */
34
40
  export declare function discoverMemoryMaintenanceChannels(input: {
35
41
  appHomeDir: string;
36
42
  workspaceDir: string;
@@ -1,10 +1,10 @@
1
1
  import { readdir } from "node:fs/promises";
2
2
  import { basename } from "node:path";
3
- import * as log from "../log.js";
4
3
  // The channel index is a runtime-owned workspace artifact; the scheduler is one of its two
5
4
  // read-only consumers (see `discoverWorkspaceChannelIds`).
6
- import { discoverWorkspaceChannelIds } from "../runtime/channel-index.js";
7
- import { isChannelId } from "../runtime/channel-paths.js";
5
+ import { discoverWorkspaceChannelIds } from "../channel/channel-index.js";
6
+ import { dedupeChannelIdsByDirectory, isChannelId } from "../channel/channel-paths.js";
7
+ import * as log from "../log.js";
8
8
  import { errorMessage } from "../shared/text-utils.js";
9
9
  import { shouldRunMemoryCheckpoint, shouldRunSessionRefresh, shouldRunStructuralMaintenance, } from "./maintenance-gates.js";
10
10
  import { runMemoryCheckpointJob, runSessionRefreshJob, runStructuralMaintenanceJob } from "./maintenance-jobs.js";
@@ -57,6 +57,11 @@ async function mightAnyMaintenanceJobBeDue(input) {
57
57
  });
58
58
  return structural.allowed;
59
59
  }
60
+ /**
61
+ * Channels with a maintenance state file — the ones nobody has spoken to since this process
62
+ * started and which have no workspace directory yet. Like a directory listing, these names are
63
+ * the escaped form of the id, so they are the least authoritative of the three sources below.
64
+ */
60
65
  async function listStateChannels(appHomeDir) {
61
66
  try {
62
67
  const entries = await readdir(getMemoryMaintenanceStateDir(appHomeDir), { withFileTypes: true });
@@ -69,20 +74,18 @@ async function listStateChannels(appHomeDir) {
69
74
  return [];
70
75
  }
71
76
  }
77
+ /**
78
+ * Every channel maintenance should visit, most authoritative source first: the live runner map
79
+ * holds real ids, `CHANNELS.md` does too, and the two directory listings can only offer escaped
80
+ * names. Deduplicating by directory keeps one entry per channel, so a group whose id contains
81
+ * `/` is maintained once — under an id the rest of the runtime can act on — rather than twice.
82
+ */
72
83
  export async function discoverMemoryMaintenanceChannels(input) {
73
- const channels = new Set();
74
- for (const channelId of input.knownChannelIds ?? []) {
75
- if (isChannelId(channelId)) {
76
- channels.add(channelId);
77
- }
78
- }
79
- for (const channelId of await discoverWorkspaceChannelIds(input.workspaceDir)) {
80
- channels.add(channelId);
81
- }
82
- for (const channelId of await listStateChannels(input.appHomeDir)) {
83
- channels.add(channelId);
84
- }
85
- return Array.from(channels).sort();
84
+ return dedupeChannelIdsByDirectory([
85
+ ...[...(input.knownChannelIds ?? [])].filter(isChannelId),
86
+ ...(await discoverWorkspaceChannelIds(input.workspaceDir)),
87
+ ...(await listStateChannels(input.appHomeDir)),
88
+ ]);
86
89
  }
87
90
  function normalizeMaxConcurrentChannels(value) {
88
91
  return Number.isFinite(value) ? Math.max(1, Math.floor(value)) : 1;
@@ -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,12 @@
1
- import { type AgentRunner } from "../agent/index.js";
1
+ import type { AgentRunner } from "../agent/types.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
+ import { TaskDriver } from "./task-driver.js";
9
10
  export interface BootstrapOptions {
10
11
  env?: NodeJS.ProcessEnv;
11
12
  io?: BootstrapIO;
@@ -55,6 +56,13 @@ export declare function forceEndStuckTurnAfterStop(input: {
55
56
  pollMs?: number;
56
57
  notify?: (text: string) => Promise<unknown>;
57
58
  }): Promise<boolean>;
59
+ /** The real `TaskDriver` class, or the minimal test-injectable shape `createTaskDriver` may
60
+ * supply instead — `taskDriver.nudge?.()` is the only member either side needs to guarantee. */
61
+ type TaskDriverLike = TaskDriver | {
62
+ start(): void;
63
+ stop(): void;
64
+ nudge?(): void;
65
+ };
58
66
  interface RuntimeContextOptions {
59
67
  paths: BootstrapPaths;
60
68
  dingtalkConfig: DingTalkConfig;
@@ -69,11 +77,9 @@ interface RuntimeContextOptions {
69
77
  stop(): void;
70
78
  };
71
79
  memoryMaintenanceSchedulerIntervalMs?: number;
72
- createTaskDriver?: () => {
73
- start(): void;
74
- stop(): void;
75
- nudge?(): void;
76
- };
80
+ /** Background-job sweep cadence override (tests use a short one for timely completion wakes). */
81
+ jobSweepIntervalMs?: number;
82
+ createTaskDriver?: () => TaskDriverLike;
77
83
  /** Receives raw SDK session events after subscription, without changing runtime handling. */
78
84
  observer?: (event: unknown, channelId: string) => void;
79
85
  /** Receives TaskDriver dispatch outcomes; used only by isolated evaluation workers. */