@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
@@ -0,0 +1,37 @@
1
+ import { countPromptUnits } from "../shared/prompt-units.js";
2
+ /**
3
+ * Compose one turn's prompt from the pieces `run()` gathered, and measure what each piece cost.
4
+ *
5
+ * The order is a contract, not a preference: durable memory bootstrap → task agenda → recalled
6
+ * memory → channel capsule → the user's message. Everything the runtime supplies precedes the
7
+ * message it is context *for*, and the blocks that change least between turns come first, so the
8
+ * provider's prefix cache keeps as long a match as possible. An empty piece contributes no
9
+ * separator, so a turn with nothing to recall reads exactly like one where recall is disabled.
10
+ *
11
+ * `stats` measures the inputs, never the rendered wrapper — it is what `/context` reports as the
12
+ * previous turn's automatic context, and the per-piece unit caps are enforced upstream by the
13
+ * builders themselves (`memory/recall.ts`, `memory/task-digest.ts`, `memory/bootstrap.ts`).
14
+ */
15
+ export function assembleTurnPrompt(parts) {
16
+ const stats = {
17
+ durableMemoryChars: parts.durableMemoryBootstrap.length,
18
+ durableMemoryUnits: countPromptUnits(parts.durableMemoryBootstrap),
19
+ taskDigestChars: parts.taskDigest.length,
20
+ taskDigestUnits: countPromptUnits(parts.taskDigest),
21
+ recalledMemoryChars: parts.recalledMemory.length,
22
+ recalledMemoryUnits: countPromptUnits(parts.recalledMemory),
23
+ channelCapsuleUnits: countPromptUnits(parts.channelCapsule),
24
+ userMessageChars: parts.clippedInput.length,
25
+ };
26
+ if (parts.preserveRawInput) {
27
+ return { text: parts.clippedInput, stats };
28
+ }
29
+ const blocks = [
30
+ parts.durableMemoryBootstrap,
31
+ parts.taskDigest,
32
+ parts.recalledMemory,
33
+ parts.channelCapsule,
34
+ `<user_message>\n${parts.userMessage}\n</user_message>`,
35
+ ];
36
+ return { text: blocks.filter((block) => block !== "").join("\n\n"), stats };
37
+ }
@@ -1,7 +1,7 @@
1
1
  import { readdir } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { SessionManager } from "@earendil-works/pi-coding-agent";
4
- import { resolveActiveSessionFile } from "../runtime/active-session-store.js";
4
+ import { resolveActiveSessionFile } from "../channel/active-session-store.js";
5
5
  /**
6
6
  * Repairs a session branch left with a declared-but-unfulfilled tool call by a process that
7
7
  * exited between the assistant's tool call and the tool result being recorded (spec 043, D8-D16).
@@ -0,0 +1,60 @@
1
+ import type { TurnPhase, TurnStatus } from "./types.js";
2
+ /**
3
+ * One turn's mutable state. `current()` hands it out so the owning `run()` can address *its own*
4
+ * turn for later phase writes: once `forceEnd()` has released a turn, the machine's current turn
5
+ * is a different object and the stale handle must lose.
6
+ */
7
+ export interface TurnHandle {
8
+ phase: TurnPhase;
9
+ stopRequested: boolean;
10
+ taskText?: string;
11
+ }
12
+ /**
13
+ * The runner's turn state machine (phases documented on `TurnPhase` in types.ts). Busy state has a
14
+ * single owner; transports call `begin`/`end` and everything else — the DingTalk busy routing, the
15
+ * TUI turn controller, the maintenance scheduler's idle check, `/status` — derives from `isBusy()`
16
+ * and `status()` instead of keeping a parallel flag.
17
+ *
18
+ * Extracted from `ChannelRunner` because its two load-bearing rules are invisible at the call sites
19
+ * and were previously reachable only through a live SDK session:
20
+ *
21
+ * 1. **A force-released turn's late `end()` is swallowed.** `forceEnd` hands the channel back to the
22
+ * next message while the wedged turn's epilogue is still running; when that epilogue finally
23
+ * calls `end()`, it would otherwise clear the busy state of whichever turn started in between.
24
+ * `abandoned` counts those outstanding releases so each one absorbs exactly one late `end()`.
25
+ * 2. **Phase writes are addressed to a turn, not to "whatever is current".** `setPhase` is a no-op
26
+ * once its handle is no longer current, for the same reason.
27
+ *
28
+ * No I/O and no logger import: both warning paths report through `onWarn`, so this stays a unit that
29
+ * can be exercised directly.
30
+ */
31
+ export declare class TurnStateMachine {
32
+ private readonly onWarn;
33
+ private turn;
34
+ /** Turns released by `forceEnd` whose owner has not called `end()` yet. */
35
+ private abandoned;
36
+ constructor(onWarn?: (message: string, detail?: string) => void);
37
+ /** Reserve the machine for a turn. Transports must call this in the tick they dequeue a message. */
38
+ begin(taskText: string): void;
39
+ /** Release the turn. Ignored when the turn was already released by `forceEnd`. */
40
+ end(): void;
41
+ /**
42
+ * Release a turn whose owner is wedged, so the channel stops reporting busy. Returns false when
43
+ * already idle. The wedged turn keeps running; its later `end()` is absorbed.
44
+ */
45
+ forceEnd(reason: string): boolean;
46
+ isBusy(): boolean;
47
+ phase(): TurnPhase;
48
+ /** The live handle for the current turn, for `setPhase` and for `run()`'s own-turn capture. */
49
+ current(): TurnHandle;
50
+ /** Advance a turn's phase, unless that turn has since been released. */
51
+ setPhase(turn: TurnHandle, phase: TurnPhase): void;
52
+ /**
53
+ * The agent loop reported its first message. Only a turn still assembling its prompt advances;
54
+ * a `message_start` arriving after the turn was released must not revive the next one.
55
+ */
56
+ markStreaming(): boolean;
57
+ /** Mark the current turn as user-stopped (no-op when idle). */
58
+ requestStop(): void;
59
+ status(): TurnStatus;
60
+ }
@@ -0,0 +1,95 @@
1
+ function idleTurn() {
2
+ return { phase: "idle", stopRequested: false };
3
+ }
4
+ /**
5
+ * The runner's turn state machine (phases documented on `TurnPhase` in types.ts). Busy state has a
6
+ * single owner; transports call `begin`/`end` and everything else — the DingTalk busy routing, the
7
+ * TUI turn controller, the maintenance scheduler's idle check, `/status` — derives from `isBusy()`
8
+ * and `status()` instead of keeping a parallel flag.
9
+ *
10
+ * Extracted from `ChannelRunner` because its two load-bearing rules are invisible at the call sites
11
+ * and were previously reachable only through a live SDK session:
12
+ *
13
+ * 1. **A force-released turn's late `end()` is swallowed.** `forceEnd` hands the channel back to the
14
+ * next message while the wedged turn's epilogue is still running; when that epilogue finally
15
+ * calls `end()`, it would otherwise clear the busy state of whichever turn started in between.
16
+ * `abandoned` counts those outstanding releases so each one absorbs exactly one late `end()`.
17
+ * 2. **Phase writes are addressed to a turn, not to "whatever is current".** `setPhase` is a no-op
18
+ * once its handle is no longer current, for the same reason.
19
+ *
20
+ * No I/O and no logger import: both warning paths report through `onWarn`, so this stays a unit that
21
+ * can be exercised directly.
22
+ */
23
+ export class TurnStateMachine {
24
+ constructor(onWarn = () => { }) {
25
+ this.onWarn = onWarn;
26
+ this.turn = idleTurn();
27
+ /** Turns released by `forceEnd` whose owner has not called `end()` yet. */
28
+ this.abandoned = 0;
29
+ }
30
+ /** Reserve the machine for a turn. Transports must call this in the tick they dequeue a message. */
31
+ begin(taskText) {
32
+ if (this.turn.phase !== "idle") {
33
+ this.onWarn(`beginTurn while phase=${this.turn.phase}; turns must be serialized`);
34
+ }
35
+ this.turn = { phase: "dispatching", stopRequested: false, taskText };
36
+ }
37
+ /** Release the turn. Ignored when the turn was already released by `forceEnd`. */
38
+ end() {
39
+ if (this.abandoned > 0) {
40
+ this.abandoned--;
41
+ return;
42
+ }
43
+ this.turn = idleTurn();
44
+ }
45
+ /**
46
+ * Release a turn whose owner is wedged, so the channel stops reporting busy. Returns false when
47
+ * already idle. The wedged turn keeps running; its later `end()` is absorbed.
48
+ */
49
+ forceEnd(reason) {
50
+ if (this.turn.phase === "idle") {
51
+ return false;
52
+ }
53
+ this.onWarn(`Force-ending a stuck turn (phase=${this.turn.phase})`, `${reason}; its own teardown is still running and will be ignored when it finishes`);
54
+ this.abandoned++;
55
+ this.turn = idleTurn();
56
+ return true;
57
+ }
58
+ isBusy() {
59
+ return this.turn.phase !== "idle";
60
+ }
61
+ phase() {
62
+ return this.turn.phase;
63
+ }
64
+ /** The live handle for the current turn, for `setPhase` and for `run()`'s own-turn capture. */
65
+ current() {
66
+ return this.turn;
67
+ }
68
+ /** Advance a turn's phase, unless that turn has since been released. */
69
+ setPhase(turn, phase) {
70
+ if (this.turn !== turn) {
71
+ return;
72
+ }
73
+ this.turn.phase = phase;
74
+ }
75
+ /**
76
+ * The agent loop reported its first message. Only a turn still assembling its prompt advances;
77
+ * a `message_start` arriving after the turn was released must not revive the next one.
78
+ */
79
+ markStreaming() {
80
+ if (this.turn.phase !== "preparing") {
81
+ return false;
82
+ }
83
+ this.turn.phase = "streaming";
84
+ return true;
85
+ }
86
+ /** Mark the current turn as user-stopped (no-op when idle). */
87
+ requestStop() {
88
+ if (this.turn.phase !== "idle") {
89
+ this.turn.stopRequested = true;
90
+ }
91
+ }
92
+ status() {
93
+ return { ...this.turn };
94
+ }
95
+ }
@@ -1,9 +1,9 @@
1
+ import type { ChannelContext } from "../channel/channel-context.js";
2
+ import type { ChannelStore } from "../channel/store.js";
3
+ import type { RunnerBuiltInCommand } from "../commands/catalog.js";
1
4
  import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
2
- import type { ChannelContext } from "../runtime/channel-context.js";
3
- import type { ChannelStore } from "../runtime/store.js";
4
5
  import { type UsageTotals } from "../shared/types.js";
5
6
  import type { SubAgentDiscoveryResult } from "../subagents/discovery.js";
6
- import type { RunnerBuiltInCommand } from "./commands.js";
7
7
  export interface RunnerStatusSnapshot {
8
8
  model: string;
9
9
  contextTokens?: number;
@@ -9,8 +9,12 @@
9
9
  * transport.
10
10
  *
11
11
  * These declarations previously lived in `runtime/dingtalk.ts` under the name
12
- * `DingTalkContext`; they were lifted here (and renamed) so a second transport
13
- * can implement the contract without importing anything DingTalk-specific.
12
+ * `DingTalkContext`; they were lifted out (and renamed) so a second transport
13
+ * can implement the contract without importing anything DingTalk-specific. They
14
+ * live in `src/channel/` rather than `src/runtime/` because a port belongs with
15
+ * the domain it describes, not with one of its adapters: `agent`, `tools` and
16
+ * `tui` all depend on this file, and none of them should be reading anything out
17
+ * of the DingTalk transport's directory to get it.
14
18
  */
15
19
  /**
16
20
  * How progress is surfaced during a run. Derived from the transport's response
@@ -9,7 +9,11 @@
9
9
  * transport.
10
10
  *
11
11
  * These declarations previously lived in `runtime/dingtalk.ts` under the name
12
- * `DingTalkContext`; they were lifted here (and renamed) so a second transport
13
- * can implement the contract without importing anything DingTalk-specific.
12
+ * `DingTalkContext`; they were lifted out (and renamed) so a second transport
13
+ * can implement the contract without importing anything DingTalk-specific. They
14
+ * live in `src/channel/` rather than `src/runtime/` because a port belongs with
15
+ * the domain it describes, not with one of its adapters: `agent`, `tools` and
16
+ * `tui` all depend on this file, and none of them should be reading anything out
17
+ * of the DingTalk transport's directory to get it.
14
18
  */
15
19
  export {};
@@ -32,4 +32,12 @@ export interface ChannelEvent {
32
32
  taskId: string;
33
33
  dispatchId: string;
34
34
  };
35
+ /**
36
+ * Purely a display hint: `"awaited"` marks a synthetic wake a human is actually waiting on (a
37
+ * delegation or background job finishing), as opposed to an autonomous check-in (task-driver
38
+ * polling, a scheduled event) that normally has nothing to say. The runtime uses it to decide
39
+ * whether the resulting turn renders progress or stays silent until a final answer — it must
40
+ * never gate task activation or any other trust decision; that stays on `internalWake` alone.
41
+ */
42
+ presentation?: "awaited";
35
43
  }
@@ -0,0 +1,16 @@
1
+ export declare function isChannelId(value: string): boolean;
2
+ export declare function getChannelDirName(channelId: string): string;
3
+ export declare function getChannelDir(baseDir: string, channelId: string): string;
4
+ /**
5
+ * Collapse ids that name the same channel directory, keeping the first spelling offered.
6
+ *
7
+ * Background workers assemble their channel list from several sources, and only some of them
8
+ * store a real id: `CHANNELS.md` and the live runner map do, while a directory listing (of the
9
+ * workspace, or of the maintenance state dir) can only report the *escaped* name, which cannot
10
+ * be turned back into the id it came from. Left alone, one channel then appears twice — once
11
+ * under its real id and once under a spelling no transport can deliver to — and every unit of
12
+ * work for it runs twice. Callers pass their sources most-authoritative-first; this keeps that
13
+ * spelling and drops the rest.
14
+ */
15
+ export declare function dedupeChannelIdsByDirectory(channelIds: Iterable<string>): string[];
16
+ export declare function ensureChannelDir(baseDir: string, channelId: string): string;
@@ -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,4 +1,19 @@
1
- export type BuiltInCommandName = "help" | "steer" | "followup" | "stop" | "events" | "tasks" | "status" | "usage" | "context" | "subagents" | "project";
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";
2
17
  /** The four transport commands handled by `ChannelRunner.handleBuiltinCommand`. */
3
18
  export type RunnerBuiltInCommandName = "help" | "stop" | "steer" | "followup" | "context";
4
19
  /**
@@ -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,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";
@@ -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,27 @@ 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
+ function legacyStatePath(appHomeDir, channelId) {
31
+ return getChannelDirName(channelId) === channelId
32
+ ? undefined
33
+ : join(getMemoryMaintenanceStateDir(appHomeDir), `${channelId}.json`);
14
34
  }
15
35
  function createDefaultState(channelId) {
16
36
  return {
@@ -74,19 +94,42 @@ export async function readMemoryMaintenanceState(appHomeDir, channelId) {
74
94
  }
75
95
  catch (error) {
76
96
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
77
- return createDefaultState(channelId);
97
+ const legacy = await readLegacyState(appHomeDir, channelId);
98
+ return legacy ?? createDefaultState(channelId);
78
99
  }
79
100
  const message = errorMessage(error);
80
101
  log.logWarning(`[${channelId}] Failed to read memory maintenance state; rebuilding defaults`, message);
81
102
  return createDefaultState(channelId);
82
103
  }
83
104
  }
105
+ async function readLegacyState(appHomeDir, channelId) {
106
+ const path = legacyStatePath(appHomeDir, channelId);
107
+ if (!path)
108
+ return undefined;
109
+ try {
110
+ return normalizeState(channelId, JSON.parse(await readFile(path, "utf-8")));
111
+ }
112
+ catch {
113
+ return undefined; // absent or unreadable ⇒ the caller falls back to defaults, as before
114
+ }
115
+ }
84
116
  export async function updateMemoryMaintenanceState(appHomeDir, channelId, update) {
85
117
  const path = getMemoryMaintenanceStatePath(appHomeDir, channelId);
86
118
  return stateUpdateQueue.run(path, async () => {
87
119
  const current = await readMemoryMaintenanceState(appHomeDir, channelId);
88
120
  const next = normalizeState(channelId, update(current));
89
121
  await writeFileAtomically(path, `${JSON.stringify(next, null, 2)}\n`);
122
+ // The canonical file now holds everything the legacy one did; leaving it would keep a
123
+ // stale copy around forever, since reads only fall back when the canonical file is gone.
124
+ const legacy = legacyStatePath(appHomeDir, channelId);
125
+ if (legacy) {
126
+ await unlink(legacy).catch(() => { });
127
+ // ...along with the directory the raw id created, which `rmdir` leaves alone if
128
+ // another channel's state still lives there. Tidying only; failure changes nothing.
129
+ const strayDir = dirname(legacy);
130
+ if (strayDir !== getMemoryMaintenanceStateDir(appHomeDir))
131
+ await rmdir(strayDir).catch(() => { });
132
+ }
90
133
  return next;
91
134
  });
92
135
  }
@@ -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;