@oyasmi/pipiclaw 0.8.1 → 0.8.3

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.
@@ -2,7 +2,7 @@ import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
2
2
  import type { ChannelContext } from "../runtime/channel-context.js";
3
3
  import type { ChannelStore } from "../runtime/store.js";
4
4
  import type { UsageTotals } from "../shared/types.js";
5
- import { type BuiltInCommand } from "./commands.js";
5
+ import { type RunnerBuiltInCommand } from "./commands.js";
6
6
  import type { RunnerFactoryPaths } from "./runner-factory.js";
7
7
  import { type AgentRunner, type RunnerStatusSnapshot } from "./types.js";
8
8
  export declare class ChannelRunner implements AgentRunner {
@@ -42,7 +42,15 @@ export declare class ChannelRunner implements AgentRunner {
42
42
  usage: UsageTotals;
43
43
  durationMs: number;
44
44
  }>;
45
- handleBuiltinCommand(ctx: ChannelContext, command: BuiltInCommand): Promise<void>;
45
+ handleBuiltinCommand(ctx: ChannelContext, command: RunnerBuiltInCommand): Promise<void>;
46
+ /**
47
+ * True if `text` is a slash command the runtime or session layer can handle:
48
+ * a built-in, a session command (`/model` …), a skill (`/skill:name`), or a
49
+ * file-based prompt template registered on the live session. Unknown slash
50
+ * commands are rejected at dispatch so a typo like `/modle` never becomes a
51
+ * full LLM turn.
52
+ */
53
+ isKnownSlashCommand(text: string): boolean;
46
54
  queueSteer(text: string, userName?: string): Promise<void>;
47
55
  flushMemoryForShutdown(): Promise<void>;
48
56
  getMemoryMaintenanceContext(): Promise<MemoryMaintenanceRuntimeContext>;
@@ -24,7 +24,7 @@ import { createPipiclawTools } from "../tools/index.js";
24
24
  import { TOOL_PROMPT_HINTS } from "../tools/registry.js";
25
25
  import { getUsageLedger } from "../usage/ledger.js";
26
26
  import { createCommandExtension } from "./command-extension.js";
27
- import { renderBuiltInHelp } from "./commands.js";
27
+ import { isKnownCommandName, renderBuiltInHelp, slashCommandName } from "./commands.js";
28
28
  import { estimateIncomingMessageTokens, getPreventiveCompactionDecision } from "./context-budget.js";
29
29
  import { PRIMARY_COOLDOWN_MS, runPromptWithFallback, shouldRestorePrimary, } from "./model-fallback.js";
30
30
  import { clipUserInput, formatProgressEntry } from "./progress-formatter.js";
@@ -152,7 +152,7 @@ export class ChannelRunner {
152
152
  this.resetRunState(ctx, store);
153
153
  this.acceptingBusyMessages = true;
154
154
  this.agentLoopStarted = false;
155
- const runQueue = createRunQueue(ctx);
155
+ const runQueue = createRunQueue();
156
156
  this.runState.queue = runQueue.queue;
157
157
  let promptSubmitted = false;
158
158
  let fallbackAttempted = false;
@@ -429,6 +429,13 @@ export class ChannelRunner {
429
429
  this.requireQueuedMessage(command.args, "followup");
430
430
  await this.sendCommandReply(ctx, "No task is running. Send the message directly now, or use `/followup` while a task is running.");
431
431
  return;
432
+ default: {
433
+ // The four session/query commands (events/tasks/status/usage) are
434
+ // routed to their own handlers upstream and never reach here; the
435
+ // narrowed parameter type makes that a compile-time guarantee.
436
+ const _exhaustive = command.name;
437
+ throw new Error(`Unhandled built-in command: ${String(_exhaustive)}`);
438
+ }
432
439
  }
433
440
  }
434
441
  catch (err) {
@@ -437,6 +444,23 @@ export class ChannelRunner {
437
444
  await this.sendCommandReply(ctx, `命令执行失败:${errMsg}`);
438
445
  }
439
446
  }
447
+ /**
448
+ * True if `text` is a slash command the runtime or session layer can handle:
449
+ * a built-in, a session command (`/model` …), a skill (`/skill:name`), or a
450
+ * file-based prompt template registered on the live session. Unknown slash
451
+ * commands are rejected at dispatch so a typo like `/modle` never becomes a
452
+ * full LLM turn.
453
+ */
454
+ isKnownSlashCommand(text) {
455
+ const name = slashCommandName(text);
456
+ if (!name) {
457
+ return false;
458
+ }
459
+ if (isKnownCommandName(name)) {
460
+ return true;
461
+ }
462
+ return this.session.promptTemplates.some((template) => template.name.toLowerCase() === name);
463
+ }
440
464
  async queueSteer(text, userName) {
441
465
  await this.queueBusyMessage(this.requireQueuedMessage(text, "steer"), userName);
442
466
  }
@@ -1,5 +1,6 @@
1
1
  import { basename } from "path";
2
2
  import { findModelReferenceMatch, formatModelList, formatModelReference } from "../models/utils.js";
3
+ import { sessionCommandDescription } from "./commands.js";
3
4
  export const COMMAND_RESULT_CUSTOM_TYPE = "pipiclaw.command_result";
4
5
  function buildSessionText(stats, currentModel, thinkingLevel, lastResponseModel) {
5
6
  const configuredRef = currentModel ? formatModelReference(currentModel) : null;
@@ -41,13 +42,13 @@ function sendCommandResult(sender, text) {
41
42
  export function createCommandExtension(options) {
42
43
  return (pi) => {
43
44
  pi.registerCommand("session", {
44
- description: "Show current session state, usage, and model info",
45
+ description: sessionCommandDescription("session"),
45
46
  handler: async () => {
46
47
  sendCommandResult(pi, buildSessionText(options.getSessionStats(), options.getCurrentModel(), options.getThinkingLevel(), options.getLastResponseModel?.()));
47
48
  },
48
49
  });
49
50
  pi.registerCommand("model", {
50
- description: "Show the current model or switch models using an exact or uniquely matching substring",
51
+ description: sessionCommandDescription("model"),
51
52
  handler: async (args) => {
52
53
  const availableModels = await options.getAvailableModels();
53
54
  const currentModel = options.getCurrentModel();
@@ -85,7 +86,7 @@ ${available}`);
85
86
  },
86
87
  });
87
88
  pi.registerCommand("new", {
88
- description: "Start a new session",
89
+ description: sessionCommandDescription("new"),
89
90
  handler: async (_args, ctx) => {
90
91
  let sentFromReplacement = false;
91
92
  const result = await ctx.newSession({
@@ -105,7 +106,7 @@ ${available}`);
105
106
  },
106
107
  });
107
108
  pi.registerCommand("compact", {
108
- description: "Manually compact the current session context",
109
+ description: sessionCommandDescription("compact"),
109
110
  handler: async (args, ctx) => {
110
111
  const customInstructions = args.trim() || undefined;
111
112
  const result = await runCompact(ctx, customInstructions);
@@ -1,8 +1,58 @@
1
1
  export type BuiltInCommandName = "help" | "steer" | "followup" | "stop" | "events" | "tasks" | "status" | "usage";
2
+ /** The four transport commands handled by `ChannelRunner.handleBuiltinCommand`. */
3
+ export type RunnerBuiltInCommandName = "help" | "stop" | "steer" | "followup";
2
4
  export interface BuiltInCommand {
3
5
  name: BuiltInCommandName;
4
6
  args: string;
5
7
  rawText: string;
6
8
  }
9
+ /** A parsed built-in whose name is one the runner handles directly. */
10
+ export type RunnerBuiltInCommand = BuiltInCommand & {
11
+ name: RunnerBuiltInCommandName;
12
+ };
13
+ /**
14
+ * Single source of truth for a slash command's metadata. `HELP_TEXT`, the TUI
15
+ * autocomplete list, the busy-time hint, and the known-command set are all
16
+ * derived from these tables — do not hand-maintain those in parallel.
17
+ */
18
+ export interface CommandSpec {
19
+ name: string;
20
+ /** Argument syntax shown after the name, e.g. `<message>` or `[7d|month]`. */
21
+ argumentHint?: string;
22
+ /** One-line description; used for `/help` and for editor autocomplete. */
23
+ description: string;
24
+ /** Concrete invocations shown under the command in `/help`. */
25
+ examples?: string[];
26
+ /** Whether the command is accepted while a task is streaming. */
27
+ availableWhileBusy?: boolean;
28
+ }
29
+ /**
30
+ * Transport commands: handled directly by the runtime layer (never sent to the
31
+ * LLM). All of them are accepted while a task is streaming.
32
+ */
33
+ export declare const BUILT_IN_COMMANDS: readonly CommandSpec[];
34
+ /**
35
+ * Session commands: handled inside the Pipiclaw session layer (SDK command
36
+ * extension) during the turn. Descriptions here are the source shared with the
37
+ * extension registration in `command-extension.ts`.
38
+ */
39
+ export declare const SESSION_COMMANDS: readonly CommandSpec[];
40
+ /** Look up the shared description for a session command (used by the SDK extension). */
41
+ export declare function sessionCommandDescription(name: string): string;
42
+ export declare function isBuiltInCommandName(name: string): name is BuiltInCommandName;
43
+ /** Narrow a parsed built-in to one `ChannelRunner.handleBuiltinCommand` accepts. */
44
+ export declare function isRunnerBuiltInCommand(command: BuiltInCommand): command is RunnerBuiltInCommand;
45
+ /** Comma-separated list of commands usable while a task is streaming (names only). */
46
+ export declare function formatBusyCommandList(): string;
47
+ /** Extract the lower-cased command name from a slash input, or `null` if not a slash command. */
48
+ export declare function slashCommandName(text: string): string | null;
49
+ /**
50
+ * True if `text` is a slash command the runtime or session layer knows how to
51
+ * handle: a built-in transport command, a session command, or a skill
52
+ * invocation (`/skill:name`). Prompt-template names are resolved separately by
53
+ * the runner, which has the session's live template list.
54
+ */
55
+ export declare function isKnownCommandName(name: string): boolean;
56
+ export declare function formatUnknownCommandMessage(name: string): string;
7
57
  export declare function parseBuiltInCommand(text: string): BuiltInCommand | null;
8
58
  export declare function renderBuiltInHelp(): string;
@@ -1,4 +1,142 @@
1
- const HELP_TEXT = `# Slash Commands
1
+ /**
2
+ * Transport commands: handled directly by the runtime layer (never sent to the
3
+ * LLM). All of them are accepted while a task is streaming.
4
+ */
5
+ export const BUILT_IN_COMMANDS = [
6
+ {
7
+ name: "help",
8
+ description: "Show command help",
9
+ examples: ["/help"],
10
+ availableWhileBusy: true,
11
+ },
12
+ {
13
+ name: "stop",
14
+ description: "Stop the current task",
15
+ examples: ["/stop"],
16
+ availableWhileBusy: true,
17
+ },
18
+ {
19
+ name: "steer",
20
+ argumentHint: "<message>",
21
+ description: "Adjust the running task after the current tool step finishes",
22
+ examples: ["/steer Use the Shanghai time zone and summarize only the latest updates"],
23
+ availableWhileBusy: true,
24
+ },
25
+ {
26
+ name: "followup",
27
+ argumentHint: "<message>",
28
+ description: "Queue a request to run after the current task completes",
29
+ examples: ["/followup After that, draft a short executive summary"],
30
+ availableWhileBusy: true,
31
+ },
32
+ {
33
+ name: "events",
34
+ argumentHint: "<list|show|delete|history>",
35
+ description: "Manage scheduled event files and inspect event history",
36
+ examples: [
37
+ "/events list",
38
+ "/events show weekly-review",
39
+ "/events delete weekly-review",
40
+ "/events history weekly-review",
41
+ ],
42
+ availableWhileBusy: true,
43
+ },
44
+ {
45
+ name: "tasks",
46
+ argumentHint: "[show <id>|archive|approve <id>|pause <id>|resume <id>|run <id>|stats [id]|doctor]",
47
+ description: "View and diagnose the channel's task ledger; `approve` gates external side effects",
48
+ examples: [
49
+ "/tasks",
50
+ "/tasks show weekly-report",
51
+ "/tasks archive",
52
+ "/tasks approve publish-release",
53
+ "/tasks pause weekly-report",
54
+ "/tasks resume weekly-report",
55
+ "/tasks run weekly-report",
56
+ "/tasks stats weekly-report",
57
+ "/tasks doctor",
58
+ ],
59
+ availableWhileBusy: true,
60
+ },
61
+ {
62
+ name: "status",
63
+ description: "Show run state, current model, context usage, uptime, and version",
64
+ examples: ["/status"],
65
+ availableWhileBusy: true,
66
+ },
67
+ {
68
+ name: "usage",
69
+ argumentHint: "[7d|month]",
70
+ description: "Show LLM cost for this channel and globally, broken down by kind and top models",
71
+ examples: ["/usage", "/usage 7d", "/usage month"],
72
+ availableWhileBusy: true,
73
+ },
74
+ ];
75
+ /**
76
+ * Session commands: handled inside the Pipiclaw session layer (SDK command
77
+ * extension) during the turn. Descriptions here are the source shared with the
78
+ * extension registration in `command-extension.ts`.
79
+ */
80
+ export const SESSION_COMMANDS = [
81
+ {
82
+ name: "session",
83
+ description: "Show current session state, message stats, token usage, and model info",
84
+ examples: ["/session"],
85
+ },
86
+ {
87
+ name: "model",
88
+ argumentHint: "[provider/modelId|modelId]",
89
+ description: "Show the current model, or switch models using an exact or uniquely matching substring",
90
+ examples: ["/model", "/model anthropic/claude-opus-4-6"],
91
+ },
92
+ {
93
+ name: "new",
94
+ description: "Start a new session",
95
+ examples: ["/new"],
96
+ },
97
+ {
98
+ name: "compact",
99
+ argumentHint: "[instructions]",
100
+ description: "Manually compact the current session context, with optional custom instructions",
101
+ examples: ["/compact", "/compact Keep the latest TODOs and decisions"],
102
+ },
103
+ ];
104
+ const BUILT_IN_NAMES = new Set(BUILT_IN_COMMANDS.map((command) => command.name));
105
+ const KNOWN_COMMAND_NAMES = new Set([...BUILT_IN_NAMES, ...SESSION_COMMANDS.map((command) => command.name)]);
106
+ /** Look up the shared description for a session command (used by the SDK extension). */
107
+ export function sessionCommandDescription(name) {
108
+ const spec = SESSION_COMMANDS.find((command) => command.name === name);
109
+ if (!spec) {
110
+ throw new Error(`Unknown session command: ${name}`);
111
+ }
112
+ return spec.description;
113
+ }
114
+ export function isBuiltInCommandName(name) {
115
+ return BUILT_IN_NAMES.has(name);
116
+ }
117
+ const RUNNER_BUILT_IN_NAMES = new Set(["help", "stop", "steer", "followup"]);
118
+ /** Narrow a parsed built-in to one `ChannelRunner.handleBuiltinCommand` accepts. */
119
+ export function isRunnerBuiltInCommand(command) {
120
+ return RUNNER_BUILT_IN_NAMES.has(command.name);
121
+ }
122
+ /** Comma-separated list of commands usable while a task is streaming (names only). */
123
+ export function formatBusyCommandList() {
124
+ return BUILT_IN_COMMANDS.filter((command) => command.availableWhileBusy)
125
+ .map((command) => `\`/${command.name}\``)
126
+ .join(", ");
127
+ }
128
+ function renderCommandEntry(spec) {
129
+ const header = `- \`/${spec.name}${spec.argumentHint ? ` ${spec.argumentHint}` : ""}\``;
130
+ const lines = [header, ` ${spec.description}`];
131
+ for (const example of spec.examples ?? []) {
132
+ lines.push(` Example: \`${example}\``);
133
+ }
134
+ return lines.join("\n");
135
+ }
136
+ function renderHelpText() {
137
+ const transport = BUILT_IN_COMMANDS.map(renderCommandEntry).join("\n");
138
+ const session = SESSION_COMMANDS.map(renderCommandEntry).join("\n");
139
+ return `# Slash Commands
2
140
 
3
141
  Pipiclaw supports two command groups.
4
142
 
@@ -6,43 +144,7 @@ Pipiclaw supports two command groups.
6
144
 
7
145
  These are handled directly by the DingTalk transport/runtime layer.
8
146
 
9
- - \`/help\`
10
- Show command help
11
- Example: \`/help\`
12
- - \`/stop\`
13
- Stop the current task
14
- Example: \`/stop\`
15
- - \`/steer <message>\`
16
- Change the current task after the current tool step finishes
17
- Example: \`/steer Use the Shanghai time zone and summarize only the latest updates\`
18
- - \`/followup <message>\`
19
- Queue another request to run after the current task completes
20
- Example: \`/followup After that, draft a short executive summary\`
21
- - \`/events <list|show|delete|history>\`
22
- Manage scheduled event files and inspect event history
23
- Example: \`/events list\`
24
- Example: \`/events show weekly-review\`
25
- Example: \`/events delete weekly-review\`
26
- Example: \`/events history weekly-review\`
27
- - \`/tasks [show <id>|archive|approve <id>|pause <id>|resume <id>|run <id>|stats [id]|doctor]\`
28
- View and diagnose the channel's task ledger; \`approve\` is the explicit user gate for external side effects
29
- Example: \`/tasks\`
30
- Example: \`/tasks show weekly-report\`
31
- Example: \`/tasks archive\`
32
- Example: \`/tasks approve publish-release\`
33
- Example: \`/tasks pause weekly-report\`
34
- Example: \`/tasks resume weekly-report\`
35
- Example: \`/tasks run weekly-report\`
36
- Example: \`/tasks stats weekly-report\`
37
- Example: \`/tasks doctor\`
38
- - \`/status\`
39
- Show runtime status: run state, current model, context usage, uptime, version
40
- Example: \`/status\`
41
- - \`/usage [7d|month]\`
42
- Show LLM cost for this channel and globally, broken down by kind and top models
43
- Example: \`/usage\`
44
- Example: \`/usage 7d\`
45
- Example: \`/usage month\`
147
+ ${transport}
46
148
 
47
149
  While a task is running, plain messages use the configured busy-message default. The default is \`steer\`; set \`busyMessageDefault\` in channel.json to \`followUp\` or \`followup\` to queue plain messages after the current task.
48
150
 
@@ -52,42 +154,49 @@ Set \`responseMode\` in channel.json to control output shape: \`full_progress_th
52
154
 
53
155
  These are handled inside the Pipiclaw session layer:
54
156
 
55
- - \`/session\`
56
- Show current session state, message stats, token usage, and model info
57
- Example: \`/session\`
58
- - \`/model [provider/modelId|modelId]\`
59
- Show the current model, or switch models using an exact match or a uniquely matching substring
60
- Example: \`/model\`
61
- Example: \`/model anthropic/claude-opus-4-6\`
62
- - \`/new\`
63
- Start a new session
64
- Example: \`/new\`
65
- - \`/compact [instructions]\`
66
- Manually compact the current session context, with optional custom instructions
67
- Example: \`/compact\`
68
- Example: \`/compact Keep the latest TODOs and decisions\`
157
+ ${session}
69
158
  `;
159
+ }
160
+ const HELP_TEXT = renderHelpText();
161
+ /** Extract the lower-cased command name from a slash input, or `null` if not a slash command. */
162
+ export function slashCommandName(text) {
163
+ const trimmed = text.trim();
164
+ if (!trimmed.startsWith("/")) {
165
+ return null;
166
+ }
167
+ const match = /^\/(\S+)/.exec(trimmed);
168
+ return match ? match[1].toLowerCase() : null;
169
+ }
170
+ /**
171
+ * True if `text` is a slash command the runtime or session layer knows how to
172
+ * handle: a built-in transport command, a session command, or a skill
173
+ * invocation (`/skill:name`). Prompt-template names are resolved separately by
174
+ * the runner, which has the session's live template list.
175
+ */
176
+ export function isKnownCommandName(name) {
177
+ return KNOWN_COMMAND_NAMES.has(name) || name.startsWith("skill:");
178
+ }
179
+ export function formatUnknownCommandMessage(name) {
180
+ return `未知命令 \`/${name}\`。发送 \`/help\` 查看可用命令。`;
181
+ }
70
182
  export function parseBuiltInCommand(text) {
71
183
  const rawText = text.trim();
72
184
  if (!rawText.startsWith("/")) {
73
185
  return null;
74
186
  }
75
- const spaceIndex = rawText.indexOf(" ");
76
- const rawName = spaceIndex === -1 ? rawText.slice(1) : rawText.slice(1, spaceIndex);
77
- const args = spaceIndex === -1 ? "" : rawText.slice(spaceIndex + 1).trim();
78
- switch (rawName) {
79
- case "help":
80
- case "steer":
81
- case "followup":
82
- case "stop":
83
- case "events":
84
- case "tasks":
85
- case "status":
86
- case "usage":
87
- return { name: rawName, args, rawText };
88
- default:
89
- return null;
187
+ // Split on the first run of whitespace (space, tab, or newline) so that a
188
+ // mobile client that inserts a newline after the command — `/steer⏎msg` —
189
+ // still parses instead of silently falling through to the model.
190
+ const match = /^\/(\S+)(?:\s+([\s\S]*))?$/.exec(rawText);
191
+ if (!match) {
192
+ return null;
193
+ }
194
+ const rawName = match[1].toLowerCase();
195
+ const args = (match[2] ?? "").trim();
196
+ if (isBuiltInCommandName(rawName)) {
197
+ return { name: rawName, args, rawText };
90
198
  }
199
+ return null;
91
200
  }
92
201
  export function renderBuiltInHelp() {
93
202
  return HELP_TEXT;
@@ -25,14 +25,10 @@ You are running inside Pipiclaw, a DingTalk-oriented runtime built on pi, direct
25
25
  - Bash working directory: ${process.cwd()}
26
26
  - Be careful with system modifications
27
27
  - Use basic Markdown suitable for DingTalk AI Cards`);
28
- sections.push(`## Knowledge and State Layers
29
- Keep these ownership boundaries clear:
30
- - This system prompt contains only always-on runtime invariants.
31
- - Runtime playbooks under ${PLAYBOOKS_DIR}/ are versioned, read-only Pipiclaw operating knowledge. Read the matching playbook before non-trivial use of a runtime mechanism.
32
- - ${workspaceDir}/AGENTS.md and ${workspaceDir}/skills/ contain user/team behavior and procedures. They may choose how to use Pipiclaw, but must not redefine runtime facts or hard gates.
33
- - ${channelPath}/tasks/ contains per-task goals, acceptance criteria, procedures, evidence, and current control state.
34
-
35
- Do not copy runtime playbooks into workspace instructions or skills; those copies drift across upgrades.`);
28
+ sections.push(`## Knowledge Layers (always-on boundary)
29
+ - Runtime playbooks under ${PLAYBOOKS_DIR}/ are versioned, read-only Pipiclaw mechanism knowledge: read the matching one before non-trivial use of a runtime mechanism, and never copy them into the workspace (copies drift across upgrades).
30
+ - ${workspaceDir}/AGENTS.md and ${workspaceDir}/skills/ hold user/team behavior; they may choose how to use Pipiclaw but must not redefine runtime facts or hard gates.
31
+ - For how these layers fit together and where each file lives, read runtime-orientation.md.`);
36
32
  sections.push(`## Resource Map
37
33
  - Workspace: SOUL.md (identity), AGENTS.md (user/team instructions), MEMORY.md (admin-managed shared background), ENVIRONMENT.md (machine facts), skills/ (user procedural knowledge), sub-agents/ (predefined agents), events/ (schedules).
38
34
  - Current channel ${channelPath}: SESSION.md (current working state), MEMORY.md (durable facts/decisions/preferences), HISTORY.md (older summaries), tasks/ (persistent work), log.jsonl and context.jsonl (cold transcript storage).
@@ -1,7 +1,6 @@
1
- import type { ChannelContext } from "../runtime/channel-context.js";
2
1
  import type { RunQueue } from "./types.js";
3
2
  export interface CreatedRunQueue {
4
3
  queue: RunQueue;
5
4
  drain: () => Promise<void>;
6
5
  }
7
- export declare function createRunQueue(ctx: ChannelContext): CreatedRunQueue;
6
+ export declare function createRunQueue(): CreatedRunQueue;
@@ -1,6 +1,6 @@
1
1
  import * as log from "../log.js";
2
2
  import { errorMessage } from "../shared/text-utils.js";
3
- export function createRunQueue(ctx) {
3
+ export function createRunQueue() {
4
4
  let queueChain = Promise.resolve();
5
5
  const queue = {
6
6
  enqueue: (fn, errorContext) => {
@@ -14,9 +14,6 @@ export function createRunQueue(ctx) {
14
14
  }
15
15
  });
16
16
  },
17
- enqueueMessage: function (text, target, errorContext, doLog = true) {
18
- this.enqueue(() => (target === "main" ? ctx.respond(text, doLog) : ctx.respondInThread(text)), errorContext);
19
- },
20
17
  };
21
18
  return {
22
19
  queue,
@@ -2,7 +2,7 @@ import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
2
2
  import type { ChannelContext } from "../runtime/channel-context.js";
3
3
  import type { ChannelStore } from "../runtime/store.js";
4
4
  import type { UsageTotals } from "../shared/types.js";
5
- import type { BuiltInCommand } from "./commands.js";
5
+ import type { RunnerBuiltInCommand } from "./commands.js";
6
6
  export interface RunnerStatusSnapshot {
7
7
  model: string;
8
8
  contextTokens?: number;
@@ -21,7 +21,9 @@ export interface AgentRunner {
21
21
  usage?: UsageTotals;
22
22
  durationMs?: number;
23
23
  }>;
24
- handleBuiltinCommand(ctx: ChannelContext, command: BuiltInCommand): Promise<void>;
24
+ handleBuiltinCommand(ctx: ChannelContext, command: RunnerBuiltInCommand): Promise<void>;
25
+ /** True if `text` is a slash command the runtime or session layer can handle. */
26
+ isKnownSlashCommand(text: string): boolean;
25
27
  queueSteer(text: string, userName?: string): Promise<void>;
26
28
  flushMemoryForShutdown(): Promise<void>;
27
29
  getMemoryMaintenanceContext(): Promise<MemoryMaintenanceRuntimeContext>;
@@ -43,7 +45,6 @@ export interface PendingTool {
43
45
  }
44
46
  export interface RunQueue {
45
47
  enqueue(fn: () => Promise<void>, errorContext: string): void;
46
- enqueueMessage(text: string, target: "main" | "thread", errorContext: string, doLog?: boolean): void;
47
48
  }
48
49
  export interface RunLogContext {
49
50
  channelId: string;
package/dist/log.d.ts CHANGED
@@ -33,7 +33,6 @@ export declare function configureLogging(config: LoggingConfig): void;
33
33
  * is unaffected, so logs are still captured when file logging is enabled.
34
34
  */
35
35
  export declare function setConsoleLoggingEnabled(enabled: boolean): void;
36
- export declare function logUserMessage(ctx: LogContext, text: string): void;
37
36
  export declare function logToolStart(ctx: LogContext, toolName: string, label: string, args: Record<string, unknown>): void;
38
37
  export declare function logToolSuccess(ctx: LogContext, toolName: string, durationMs: number, result: string): void;
39
38
  export declare function logToolError(ctx: LogContext, toolName: string, durationMs: number, error: string): void;
@@ -42,7 +41,6 @@ export declare function logThinking(ctx: LogContext, thinking: string): void;
42
41
  export declare function logResponse(ctx: LogContext, text: string): void;
43
42
  export declare function logInfo(message: string): void;
44
43
  export declare function logWarning(message: string, details?: string): void;
45
- export declare function logAgentError(ctx: LogContext | "system", error: string): void;
46
44
  export declare function logModelFallback(ctx: LogContext, from: string, to: string, error: string): void;
47
45
  export declare function logUsageSummary(ctx: LogContext, usage: {
48
46
  input: number;
package/dist/log.js CHANGED
@@ -122,11 +122,6 @@ function formatToolArgs(args) {
122
122
  }
123
123
  return lines.join("\n");
124
124
  }
125
- // User messages
126
- export function logUserMessage(ctx, text) {
127
- con(color("green", `${timestamp()} ${formatContext(ctx)} ${text}`));
128
- emit("info", "user_message", text, { ctx });
129
- }
130
125
  // Tool execution
131
126
  export function logToolStart(ctx, toolName, label, args) {
132
127
  const formattedArgs = formatToolArgs(args);
@@ -217,19 +212,6 @@ export function logWarning(message, details) {
217
212
  }
218
213
  emit("warn", "system", message, { details });
219
214
  }
220
- export function logAgentError(ctx, error) {
221
- const context = ctx === "system" ? "[system]" : formatContext(ctx);
222
- con(color("yellow", `${timestamp()} ${context} ✗ Agent error`));
223
- const indented = error
224
- .split("\n")
225
- .map((line) => ` ${line}`)
226
- .join("\n");
227
- con(color("dim", indented));
228
- emit("error", "agent_error", "Agent error", {
229
- ctx: ctx === "system" ? undefined : ctx,
230
- details: error,
231
- });
232
- }
233
215
  // Model fallback (spec 017)
234
216
  export function logModelFallback(ctx, from, to, error) {
235
217
  con(color("yellow", `${timestamp()} ${formatContext(ctx)} ⤳ Fallback ${from} → ${to}`));
package/dist/main.js CHANGED
@@ -8,15 +8,25 @@ function handleError(error) {
8
8
  console.error(error);
9
9
  process.exit(1);
10
10
  }
11
- if (process.argv[2] === "tui") {
11
+ const command = process.argv[2];
12
+ if (command === "tui") {
12
13
  // The TUI resolves when the user exits (Ctrl-C / Ctrl-D / /exit) or a one-shot
13
14
  // --print finishes. Exit explicitly: raw-mode stdin and the runner session
14
15
  // keep the event loop alive, so the process would otherwise hang after the UI
15
16
  // tears down.
16
17
  runTui(process.argv).then(() => process.exit(0), handleError);
17
18
  }
18
- else {
19
- // The DingTalk runtime is a long-lived daemon; it does not resolve, so there
20
- // is no success path to exit on — only surface fatal errors.
19
+ else if (command === undefined || command === "run" || command.startsWith("-")) {
20
+ // Default mode: the long-lived DingTalk daemon. `run` names it explicitly;
21
+ // a bare `pipiclaw` still runs it, and leading flags (--version/--help) are
22
+ // handled by bootstrap's parseArgs. The daemon does not resolve, so there is
23
+ // no success path to exit on — only surface fatal errors.
21
24
  bootstrap(process.argv).catch(handleError);
22
25
  }
26
+ else {
27
+ console.error(`Unknown command: ${command}`);
28
+ console.error("Usage: pipiclaw [run] [options] Run the DingTalk daemon (default)");
29
+ console.error(" pipiclaw tui [options] [prompt] Chat with the agent in the terminal");
30
+ console.error("Run `pipiclaw --help` for options.");
31
+ process.exit(1);
32
+ }