@oyasmi/pipiclaw 0.8.0 → 0.8.2

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 (106) hide show
  1. package/README.md +115 -510
  2. package/dist/agent/channel-runner.d.ts +11 -6
  3. package/dist/agent/channel-runner.js +44 -24
  4. package/dist/agent/command-extension.js +5 -4
  5. package/dist/agent/commands.d.ts +50 -0
  6. package/dist/agent/commands.js +176 -67
  7. package/dist/agent/job-manager.d.ts +5 -5
  8. package/dist/agent/prompt-builder.d.ts +3 -13
  9. package/dist/agent/prompt-builder.js +44 -204
  10. package/dist/agent/run-queue.d.ts +1 -2
  11. package/dist/agent/run-queue.js +3 -5
  12. package/dist/agent/runner-factory.d.ts +1 -2
  13. package/dist/agent/runner-factory.js +2 -2
  14. package/dist/agent/status-render.d.ts +0 -7
  15. package/dist/agent/status-render.js +8 -3
  16. package/dist/agent/types.d.ts +4 -3
  17. package/dist/agent/workspace-resources.d.ts +1 -1
  18. package/dist/agent/workspace-resources.js +3 -15
  19. package/dist/executor.d.ts +20 -0
  20. package/dist/{sandbox.js → executor.js} +3 -95
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.js +1 -1
  23. package/dist/log.d.ts +1 -3
  24. package/dist/log.js +1 -20
  25. package/dist/main.js +14 -4
  26. package/dist/memory/files.js +0 -0
  27. package/dist/memory/lifecycle.js +6 -5
  28. package/dist/memory/maintenance-jobs.d.ts +0 -1
  29. package/dist/memory/maintenance-jobs.js +2 -2
  30. package/dist/memory/maintenance-state.js +2 -1
  31. package/dist/memory/post-turn-review.d.ts +0 -1
  32. package/dist/memory/post-turn-review.js +4 -4
  33. package/dist/memory/scheduler.d.ts +0 -1
  34. package/dist/memory/scheduler.js +2 -2
  35. package/dist/memory/session.js +2 -2
  36. package/dist/paths.d.ts +2 -0
  37. package/dist/paths.js +11 -0
  38. package/dist/playbooks/event-scheduling.md +43 -0
  39. package/dist/playbooks/memory-and-learning.md +45 -0
  40. package/dist/playbooks/runtime-orientation.md +48 -0
  41. package/dist/playbooks/task-closeout.md +45 -0
  42. package/dist/playbooks/task-delegation.md +44 -0
  43. package/dist/playbooks/task-driving.md +43 -0
  44. package/dist/playbooks/task-planning.md +47 -0
  45. package/dist/playbooks/task-recurring.md +42 -0
  46. package/dist/playbooks/task-repair.md +43 -0
  47. package/dist/runtime/bootstrap.d.ts +7 -11
  48. package/dist/runtime/bootstrap.js +50 -57
  49. package/dist/runtime/delivery.js +4 -3
  50. package/dist/runtime/dingtalk.js +50 -57
  51. package/dist/runtime/durable-dispatch.d.ts +2 -0
  52. package/dist/runtime/durable-dispatch.js +29 -1
  53. package/dist/runtime/event-commands.js +4 -4
  54. package/dist/runtime/events.d.ts +1 -1
  55. package/dist/runtime/events.js +5 -5
  56. package/dist/runtime/task-commands.js +9 -4
  57. package/dist/runtime/task-driver.js +12 -14
  58. package/dist/security/config.js +2 -1
  59. package/dist/security/network.js +9 -2
  60. package/dist/security/path-guard.js +12 -24
  61. package/dist/security/types.d.ts +0 -1
  62. package/dist/shared/jsonl-appender.js +2 -1
  63. package/dist/shared/task-ledger.d.ts +9 -1
  64. package/dist/shared/task-ledger.js +28 -14
  65. package/dist/shared/text-utils.d.ts +1 -0
  66. package/dist/shared/text-utils.js +3 -0
  67. package/dist/subagents/discovery.js +3 -2
  68. package/dist/subagents/tool.d.ts +2 -3
  69. package/dist/subagents/tool.js +9 -24
  70. package/dist/tasks/control.js +2 -1
  71. package/dist/tasks/verification.js +2 -1
  72. package/dist/tools/bash.d.ts +1 -1
  73. package/dist/tools/bash.js +3 -5
  74. package/dist/tools/command-optimizer.d.ts +1 -1
  75. package/dist/tools/command-optimizer.js +4 -6
  76. package/dist/tools/config.js +4 -3
  77. package/dist/tools/edit.d.ts +1 -1
  78. package/dist/tools/edit.js +0 -0
  79. package/dist/tools/event-manage.d.ts +0 -1
  80. package/dist/tools/event-manage.js +9 -14
  81. package/dist/tools/grep.d.ts +1 -1
  82. package/dist/tools/grep.js +4 -6
  83. package/dist/tools/index.d.ts +1 -3
  84. package/dist/tools/index.js +1 -4
  85. package/dist/tools/read.d.ts +1 -1
  86. package/dist/tools/read.js +1 -2
  87. package/dist/tools/registry.d.ts +1 -2
  88. package/dist/tools/registry.js +3 -10
  89. package/dist/tools/skill-manage.d.ts +0 -1
  90. package/dist/tools/skill-manage.js +7 -14
  91. package/dist/tools/task-manage.d.ts +0 -1
  92. package/dist/tools/task-manage.js +18 -16
  93. package/dist/tools/write-content.d.ts +1 -1
  94. package/dist/tools/write-content.js +0 -1
  95. package/dist/tools/write.d.ts +1 -1
  96. package/dist/tui/app.d.ts +0 -2
  97. package/dist/tui/app.js +12 -7
  98. package/dist/tui/cli.d.ts +3 -2
  99. package/dist/tui/cli.js +12 -24
  100. package/dist/tui/commands.d.ts +4 -1
  101. package/dist/tui/commands.js +10 -14
  102. package/dist/tui/turn-controller.d.ts +7 -3
  103. package/dist/tui/turn-controller.js +18 -6
  104. package/dist/web/client.js +2 -1
  105. package/package.json +2 -2
  106. package/dist/sandbox.d.ts +0 -42
@@ -1,20 +1,17 @@
1
1
  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
- import { type SandboxConfig } from "../sandbox.js";
5
4
  import type { UsageTotals } from "../shared/types.js";
6
- import { type BuiltInCommand } from "./commands.js";
5
+ import { type RunnerBuiltInCommand } from "./commands.js";
7
6
  import type { RunnerFactoryPaths } from "./runner-factory.js";
8
7
  import { type AgentRunner, type RunnerStatusSnapshot } from "./types.js";
9
8
  export declare class ChannelRunner implements AgentRunner {
10
9
  private readonly executor;
11
- private readonly sandboxConfig;
12
10
  private readonly channelId;
13
11
  private readonly channelDir;
14
12
  private readonly appHomeDir;
15
13
  private readonly authConfigPath;
16
14
  private readonly modelsConfigPath;
17
- private readonly workspacePath;
18
15
  private readonly workspaceDir;
19
16
  private session;
20
17
  private agent;
@@ -38,14 +35,22 @@ export declare class ChannelRunner implements AgentRunner {
38
35
  /** When the primary model last failed and we switched to the backup. null = on primary. */
39
36
  private primaryFailedAt;
40
37
  private runState;
41
- constructor(sandboxConfig: SandboxConfig, channelId: string, channelDir: string, paths: RunnerFactoryPaths);
38
+ constructor(channelId: string, channelDir: string, paths: RunnerFactoryPaths);
42
39
  run(ctx: ChannelContext, store: ChannelStore): Promise<{
43
40
  stopReason: string;
44
41
  errorMessage?: string;
45
42
  usage: UsageTotals;
46
43
  durationMs: number;
47
44
  }>;
48
- 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;
49
54
  queueSteer(text: string, userName?: string): Promise<void>;
50
55
  flushMemoryForShutdown(): Promise<void>;
51
56
  getMemoryMaintenanceContext(): Promise<MemoryMaintenanceRuntimeContext>;
@@ -2,6 +2,7 @@ import { Agent } from "@earendil-works/pi-agent-core";
2
2
  import { AgentSession, AgentSessionRuntime, AuthStorage, convertToLlm, createExtensionRuntime, DefaultResourceLoader, ModelRegistry, SessionManager, } from "@earendil-works/pi-coding-agent";
3
3
  import { mkdir, readFile, writeFile } from "fs/promises";
4
4
  import { dirname, join, resolve } from "path";
5
+ import { createExecutor } from "../executor.js";
5
6
  import * as log from "../log.js";
6
7
  import { buildFirstTurnMemoryBootstrap as renderFirstTurnMemoryBootstrap } from "../memory/bootstrap.js";
7
8
  import { createMemoryCandidateStore } from "../memory/candidates.js";
@@ -12,10 +13,10 @@ import { recallRelevantMemory } from "../memory/recall.js";
12
13
  import { buildTaskDigest } from "../memory/task-digest.js";
13
14
  import { getApiKeyForModel } from "../models/api-keys.js";
14
15
  import { findExactModelReferenceMatch, formatModelReference, resolveInitialModel } from "../models/utils.js";
15
- import { createExecutor } from "../sandbox.js";
16
16
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
17
17
  import { PipiclawSettingsManager } from "../settings.js";
18
18
  import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
19
+ import { errorMessage } from "../shared/text-utils.js";
19
20
  import { isRecord } from "../shared/type-guards.js";
20
21
  import { discoverSubAgents, formatSubAgentList } from "../subagents/discovery.js";
21
22
  import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
@@ -23,7 +24,7 @@ import { createPipiclawTools } from "../tools/index.js";
23
24
  import { TOOL_PROMPT_HINTS } from "../tools/registry.js";
24
25
  import { getUsageLedger } from "../usage/ledger.js";
25
26
  import { createCommandExtension } from "./command-extension.js";
26
- import { renderBuiltInHelp } from "./commands.js";
27
+ import { isKnownCommandName, renderBuiltInHelp, slashCommandName } from "./commands.js";
27
28
  import { estimateIncomingMessageTokens, getPreventiveCompactionDecision } from "./context-budget.js";
28
29
  import { PRIMARY_COOLDOWN_MS, runPromptWithFallback, shouldRestorePrimary, } from "./model-fallback.js";
29
30
  import { clipUserInput, formatProgressEntry } from "./progress-formatter.js";
@@ -53,7 +54,7 @@ function asSdkSettingsManager(manager) {
53
54
  return manager;
54
55
  }
55
56
  export class ChannelRunner {
56
- constructor(sandboxConfig, channelId, channelDir, paths) {
57
+ constructor(channelId, channelDir, paths) {
57
58
  this.ledger = getUsageLedger();
58
59
  this.currentTools = [];
59
60
  this.firstTurnMemoryBootstrapPending = true;
@@ -63,18 +64,16 @@ export class ChannelRunner {
63
64
  this.primaryFailedAt = null;
64
65
  // --- Per run ---
65
66
  this.runState = createEmptyRunState();
66
- this.sandboxConfig = sandboxConfig;
67
67
  this.channelId = channelId;
68
68
  this.channelDir = channelDir;
69
69
  this.appHomeDir = paths.appHomeDir;
70
70
  this.authConfigPath = paths.authConfigPath;
71
71
  this.modelsConfigPath = paths.modelsConfigPath;
72
- const executor = createExecutor(sandboxConfig);
72
+ const executor = createExecutor();
73
73
  this.executor = executor;
74
74
  this.workspaceDir = resolve(dirname(channelDir));
75
- this.workspacePath = executor.getWorkspacePath(this.workspaceDir);
76
75
  // Initial skill summaries
77
- const initialSkills = loadPipiclawSkills(channelDir, this.workspacePath);
76
+ const initialSkills = loadPipiclawSkills(channelDir);
78
77
  this.currentSkills = initialSkills;
79
78
  // Create session manager
80
79
  const contextFile = join(channelDir, "context.jsonl");
@@ -153,7 +152,7 @@ export class ChannelRunner {
153
152
  this.resetRunState(ctx, store);
154
153
  this.acceptingBusyMessages = true;
155
154
  this.agentLoopStarted = false;
156
- const runQueue = createRunQueue(ctx);
155
+ const runQueue = createRunQueue();
157
156
  this.runState.queue = runQueue.queue;
158
157
  let promptSubmitted = false;
159
158
  let fallbackAttempted = false;
@@ -244,7 +243,7 @@ export class ChannelRunner {
244
243
  }
245
244
  catch (err) {
246
245
  this.runState.stopReason = "error";
247
- this.runState.errorMessage = err instanceof Error ? err.message : String(err);
246
+ this.runState.errorMessage = errorMessage(err);
248
247
  log.logWarning(`[${this.channelId}] Runner failed`, this.runState.errorMessage);
249
248
  }
250
249
  },
@@ -289,7 +288,7 @@ export class ChannelRunner {
289
288
  }
290
289
  catch (err) {
291
290
  this.runState.stopReason = "error";
292
- this.runState.errorMessage = err instanceof Error ? err.message : String(err);
291
+ this.runState.errorMessage = errorMessage(err);
293
292
  log.logWarning(`[${this.channelId}] Runner failed`, this.runState.errorMessage);
294
293
  }
295
294
  finally {
@@ -329,7 +328,7 @@ export class ChannelRunner {
329
328
  await ctx.replaceMessage(`_Sorry, something went wrong._\n\n${detailLines.join("\n\n")}`);
330
329
  }
331
330
  catch (err) {
332
- const errMsg = err instanceof Error ? err.message : String(err);
331
+ const errMsg = errorMessage(err);
333
332
  log.logWarning("Failed to post error message", errMsg);
334
333
  }
335
334
  }
@@ -339,7 +338,7 @@ export class ChannelRunner {
339
338
  log.logInfo("Silent response - deleted message");
340
339
  }
341
340
  catch (err) {
342
- const errMsg = err instanceof Error ? err.message : String(err);
341
+ const errMsg = errorMessage(err);
343
342
  log.logWarning("Failed to delete message for silent response", errMsg);
344
343
  }
345
344
  }
@@ -349,7 +348,7 @@ export class ChannelRunner {
349
348
  log.logInfo("Aborted response - discarded active delivery state");
350
349
  }
351
350
  catch (err) {
352
- const errMsg = err instanceof Error ? err.message : String(err);
351
+ const errMsg = errorMessage(err);
353
352
  log.logWarning("Failed to discard active delivery state after abort", errMsg);
354
353
  }
355
354
  }
@@ -358,7 +357,7 @@ export class ChannelRunner {
358
357
  await ctx.replaceMessage(finalOutcomeText);
359
358
  }
360
359
  catch (err) {
361
- const errMsg = err instanceof Error ? err.message : String(err);
360
+ const errMsg = errorMessage(err);
362
361
  log.logWarning("Failed to replace message with final text", errMsg);
363
362
  }
364
363
  }
@@ -430,14 +429,38 @@ export class ChannelRunner {
430
429
  this.requireQueuedMessage(command.args, "followup");
431
430
  await this.sendCommandReply(ctx, "No task is running. Send the message directly now, or use `/followup` while a task is running.");
432
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
+ }
433
439
  }
434
440
  }
435
441
  catch (err) {
436
- const errMsg = err instanceof Error ? err.message : String(err);
442
+ const errMsg = errorMessage(err);
437
443
  log.logWarning(`[${this.channelId}] Built-in command failed`, errMsg);
438
444
  await this.sendCommandReply(ctx, `命令执行失败:${errMsg}`);
439
445
  }
440
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
+ }
441
464
  async queueSteer(text, userName) {
442
465
  await this.queueBusyMessage(this.requireQueuedMessage(text, "steer"), userName);
443
466
  }
@@ -451,7 +474,6 @@ export class ChannelRunner {
451
474
  channelId: this.channelId,
452
475
  channelDir: this.channelDir,
453
476
  workspaceDir: this.workspaceDir,
454
- workspacePath: this.workspacePath,
455
477
  messages: [...this.session.messages],
456
478
  sessionEntries: [...this.sessionManager.getBranch()],
457
479
  model: this.session.model ?? this.activeModel,
@@ -511,7 +533,7 @@ export class ChannelRunner {
511
533
  }));
512
534
  }
513
535
  catch (error) {
514
- const message = error instanceof Error ? error.message : String(error);
536
+ const message = errorMessage(error);
515
537
  log.logWarning(`[${this.channelId}] Failed to record memory maintenance state`, message);
516
538
  }
517
539
  }
@@ -595,7 +617,7 @@ export class ChannelRunner {
595
617
  log.logInfo(`[${this.channelId}] Restored primary model ${formatModelReference(this.activeModel)}`);
596
618
  }
597
619
  catch (err) {
598
- log.logWarning(`[${this.channelId}] Failed to restore primary model`, err instanceof Error ? err.message : String(err));
620
+ log.logWarning(`[${this.channelId}] Failed to restore primary model`, errorMessage(err));
599
621
  }
600
622
  }
601
623
  /**
@@ -631,7 +653,7 @@ export class ChannelRunner {
631
653
  async reloadSessionResources() {
632
654
  this.settingsManager.reload();
633
655
  this.reportSettingsDiagnostics();
634
- const skills = loadPipiclawSkills(this.channelDir, this.workspacePath);
656
+ const skills = loadPipiclawSkills(this.channelDir);
635
657
  this.currentSkills = skills;
636
658
  this.subAgentDiscovery = this.refreshSubAgentDiscovery();
637
659
  this.rebuildSessionTools();
@@ -681,7 +703,7 @@ export class ChannelRunner {
681
703
  log.logInfo(`[${this.channelId}] Preventive compaction complete in ${Date.now() - startedAt}ms`);
682
704
  }
683
705
  catch (error) {
684
- const message = error instanceof Error ? error.message : String(error);
706
+ const message = errorMessage(error);
685
707
  log.logWarning(`[${this.channelId}] Preventive compaction failed`, message);
686
708
  }
687
709
  }
@@ -736,7 +758,7 @@ export class ChannelRunner {
736
758
  if (soul) {
737
759
  sections.unshift(soul);
738
760
  }
739
- sections.push(buildAppendSystemPrompt(this.workspacePath, this.channelId, this.sandboxConfig, {
761
+ sections.push(buildAppendSystemPrompt(this.workspaceDir, this.channelId, {
740
762
  subAgentList: formatSubAgentList(this.subAgentDiscovery.agents),
741
763
  tools: this.currentTools.map((tool) => ({
742
764
  name: tool.name,
@@ -749,7 +771,7 @@ export class ChannelRunner {
749
771
  agentsFilesOverride: () => {
750
772
  const agentConfig = getAgentConfig(this.channelDir);
751
773
  return {
752
- agentsFiles: agentConfig ? [{ path: `${this.workspacePath}/AGENTS.md`, content: agentConfig }] : [],
774
+ agentsFiles: agentConfig ? [{ path: `${this.workspaceDir}/AGENTS.md`, content: agentConfig }] : [],
753
775
  };
754
776
  },
755
777
  skillsOverride: (base) => ({
@@ -812,9 +834,7 @@ export class ChannelRunner {
812
834
  resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
813
835
  workspaceDir: this.workspaceDir,
814
836
  channelDir: this.channelDir,
815
- workspacePath: this.workspacePath,
816
837
  channelId: this.channelId,
817
- sandboxConfig: this.sandboxConfig,
818
838
  getSubAgentDiscovery: () => this.subAgentDiscovery,
819
839
  getMemoryRecallSettings: () => this.settingsManager.getMemoryRecallSettings(),
820
840
  getSessionSearchSettings: () => this.settingsManager.getSessionSearchSettings(),
@@ -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;
@@ -1,4 +1,4 @@
1
- import type { Executor } from "../sandbox.js";
1
+ import type { Executor } from "../executor.js";
2
2
  /**
3
3
  * Per-channel manager for background bash jobs. A long command that ran synchronously would hold
4
4
  * the channel's run queue for its whole duration, blocking `/steer`, `/followup`, and every other
@@ -6,10 +6,10 @@ import type { Executor } from "../sandbox.js";
6
6
  * queue) and check back later — typically by scheduling a check-in with `event_manage`, or by
7
7
  * calling the `job` tool to poll.
8
8
  *
9
- * Jobs live entirely in the executor's world (host or Docker), managed through shell commands
10
- * (`nohup` to launch, `kill -0` to probe, `kill` to cancel), so this works identically in both
11
- * sandboxes with no in-process child handles. Manager state is in-memory and not persisted: after a
12
- * process restart, prior jobs surface as `lost` rather than being falsely resurrected.
9
+ * Jobs live entirely on the host, managed through shell commands (`nohup` to launch, `kill -0` to
10
+ * probe, `kill` to cancel) with no in-process child handles. Manager state is in-memory and not
11
+ * persisted: after a process restart, prior jobs surface as `lost` rather than being falsely
12
+ * resurrected.
13
13
  */
14
14
  export type JobStatus = "running" | "completed" | "failed" | "cancelled" | "lost";
15
15
  export interface JobSnapshot {