@oyasmi/pipiclaw 0.7.1 → 0.7.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.
Files changed (63) hide show
  1. package/README.md +8 -19
  2. package/dist/agent/channel-runner.d.ts +8 -4
  3. package/dist/agent/channel-runner.js +14 -12
  4. package/dist/agent/model-fallback.js +11 -5
  5. package/dist/agent/run-queue.d.ts +2 -2
  6. package/dist/agent/runner-factory.d.ts +7 -2
  7. package/dist/agent/runner-factory.js +18 -6
  8. package/dist/agent/session-events.d.ts +2 -2
  9. package/dist/agent/status-render.d.ts +22 -0
  10. package/dist/agent/status-render.js +61 -0
  11. package/dist/agent/type-guards.js +3 -4
  12. package/dist/agent/types.d.ts +7 -10
  13. package/dist/index.d.ts +3 -2
  14. package/dist/index.js +1 -1
  15. package/dist/log.d.ts +6 -0
  16. package/dist/log.js +38 -25
  17. package/dist/main.js +15 -2
  18. package/dist/memory/candidates.js +5 -17
  19. package/dist/memory/consolidation.js +1 -6
  20. package/dist/memory/files.d.ts +1 -0
  21. package/dist/memory/files.js +0 -0
  22. package/dist/memory/maintenance-jobs.js +1 -0
  23. package/dist/memory/session-corpus.js +3 -16
  24. package/dist/runtime/bootstrap.d.ts +17 -0
  25. package/dist/runtime/bootstrap.js +44 -79
  26. package/dist/runtime/channel-context.d.ts +44 -0
  27. package/dist/runtime/channel-context.js +15 -0
  28. package/dist/runtime/delivery.d.ts +3 -2
  29. package/dist/runtime/dingtalk.d.ts +1 -25
  30. package/dist/runtime/dingtalk.js +1 -1
  31. package/dist/runtime/event-commands.js +1 -3
  32. package/dist/runtime/events.js +1 -3
  33. package/dist/runtime/store.d.ts +1 -7
  34. package/dist/runtime/store.js +6 -80
  35. package/dist/settings.d.ts +13 -0
  36. package/dist/settings.js +6 -0
  37. package/dist/shared/fs-utils.d.ts +8 -0
  38. package/dist/shared/fs-utils.js +21 -0
  39. package/dist/shared/text-utils.d.ts +2 -0
  40. package/dist/shared/text-utils.js +4 -0
  41. package/dist/tools/index.d.ts +1 -7
  42. package/dist/tools/index.js +0 -20
  43. package/dist/tools/memory-save.d.ts +0 -1
  44. package/dist/tools/memory-save.js +0 -1
  45. package/dist/tui/app.d.ts +18 -0
  46. package/dist/tui/app.js +104 -0
  47. package/dist/tui/cli.d.ts +22 -0
  48. package/dist/tui/cli.js +116 -0
  49. package/dist/tui/colors.d.ts +9 -0
  50. package/dist/tui/colors.js +20 -0
  51. package/dist/tui/commands.d.ts +47 -0
  52. package/dist/tui/commands.js +64 -0
  53. package/dist/tui/pitui-frontend.d.ts +47 -0
  54. package/dist/tui/pitui-frontend.js +154 -0
  55. package/dist/tui/plain-frontend.d.ts +23 -0
  56. package/dist/tui/plain-frontend.js +56 -0
  57. package/dist/tui/renderer.d.ts +62 -0
  58. package/dist/tui/renderer.js +16 -0
  59. package/dist/tui/terminal-context.d.ts +27 -0
  60. package/dist/tui/terminal-context.js +84 -0
  61. package/dist/tui/turn-controller.d.ts +68 -0
  62. package/dist/tui/turn-controller.js +286 -0
  63. package/package.json +2 -1
package/README.md CHANGED
@@ -16,9 +16,10 @@ npm package: [`@oyasmi/pipiclaw`](https://www.npmjs.com/package/@oyasmi/pipiclaw
16
16
  ## 功能特性(Features)
17
17
 
18
18
  - 原生支持钉钉 Stream Mode,不需要消息中转服务,不需要公网IP
19
+ - 支持终端 TUI:`pipiclaw tui` 直接在命令行对话,复用同一套配置、记忆与会话(见[配置手册](docs/configuration.md)的「终端 TUI」)
19
20
  - 支持 AI Card 过程展示,思考、工具执行和状态更新可以持续流式呈现
20
21
  - 支持 `/help`、`/new`、`/compact`、`/session`、`/model`
21
- - 忙碌时可继续接收 `/steer`、`/followup`、`/stop`、`/events`
22
+ - 忙碌时可继续接收 `/steer`、`/followup`、`/stop`、`/events`、`/status`、`/usage`
22
23
  - 按工作区 / 会话通道(workspace / channel)分层管理 `SOUL.md`、`AGENTS.md`、`SESSION.md`、`MEMORY.md`、`HISTORY.md`
23
24
  - 支持预定义子代理(sub-agent)和临时内联子代理(inline sub-agent)
24
25
  - 支持立即、单次、周期三类事件调度
@@ -52,8 +53,8 @@ Pipiclaw 当前已经内置一轮工具层安全增强:
52
53
  ```text
53
54
  请帮我在这台机器上安装并初始化 Pipiclaw,并尽量把它配置到“可以开始使用”的状态。按下面要求执行:
54
55
 
55
- 1. 先检查 Node.js 是否可用,版本必须 >= 22。
56
- - 如果未安装,或版本低于 22,不要继续安装 Pipiclaw,直接告诉我需要先安装或切换到 Node.js 22+。
56
+ 1. 先检查 Node.js 是否可用,版本必须 >= 22.19.0。
57
+ - 如果未安装,或版本低于 22.19.0,不要继续安装 Pipiclaw,直接告诉我需要先安装或切换到 Node.js 22.19.0+。
57
58
 
58
59
  2. 安装 Pipiclaw:
59
60
  - 优先执行:npm install -g @oyasmi/pipiclaw
@@ -126,20 +127,13 @@ Pipiclaw 当前已经内置一轮工具层安全增强:
126
127
 
127
128
  #### 1. 环境要求(Requirements)
128
129
 
129
- - Node.js `>= 22`
130
+ - Node.js `>= 22.19.0`
130
131
  - 一个可用的钉钉企业内部应用
131
132
  - 至少一种可用的模型接入方式
132
133
  - 直接使用 Anthropic 默认模型
133
134
  - 或在 `models.json` 中配置自定义模型提供方(provider)
134
135
 
135
- Windows 补充说明:
136
-
137
- - Pipiclaw 的工具执行层默认按 POSIX shell 语义工作
138
- - 推荐在 Windows 上使用 WSL2 安装和运行 Pipiclaw
139
- - 不推荐直接在 Windows host 模式下配合 Git Bash 使用;这种方式在工具调用中更容易遇到兼容性问题,尤其是 skills 依赖的外部工具
140
- - 仅在无法使用 WSL2 时,再考虑安装 Git Bash,并确保 `bash` 可在 PATH 中找到
141
- - 如果 Windows host 模式下 `bash` 不在 PATH 中,可以设置 `PIPICLAW_SHELL` 指向具体可执行文件,例如 `C:\Program Files\Git\bin\bash.exe`
142
- - 如果你不想依赖本机 shell 环境,推荐直接使用 Docker sandbox
136
+ Pipiclaw 面向类 Unix 环境(Linux / macOS),不支持 Windows。工具执行层按 POSIX shell 语义工作;如需在 Windows 上运行,请使用 WSL2。
143
137
 
144
138
  #### 2. 安装(Install)
145
139
 
@@ -183,12 +177,6 @@ export PIPICLAW_HOME=/your/custom/pipiclaw-home
183
177
 
184
178
  设置后,`channel.json`、`auth.json`、`models.json`、`settings.json`、`tools.json`、`security.json` 和整个 `workspace/` 都会改为从这个目录读取和写入。
185
179
 
186
- 如果你无法使用 WSL2,选择在 Windows host 模式下配合 Git Bash 运行,并且 `bash` 不在 PATH 中,也可以一并设置:
187
-
188
- ```powershell
189
- $env:PIPICLAW_SHELL = "C:\Program Files\Git\bin\bash.exe"
190
- ```
191
-
192
180
  如果 `channel.json` 仍然是初始化模板,程序会提示你补全配置后再启动。这是正常行为。
193
181
 
194
182
  #### 4. 创建钉钉应用(Create a DingTalk App)
@@ -445,7 +433,6 @@ pipiclaw
445
433
  |----------|------|
446
434
  | `ANTHROPIC_API_KEY` | Anthropic API Key |
447
435
  | `PIPICLAW_HOME` | 覆盖默认的 `~/.pi/pipiclaw/` 根目录 |
448
- | `PIPICLAW_SHELL` | Windows host 模式下指定 POSIX shell,例如 Git Bash 的 `bash.exe` |
449
436
  | `PIPICLAW_DEBUG` | 调试模式,会把上下文写到 `last_prompt.json` |
450
437
  | `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` / `NO_PROXY` | 标准代理环境变量;DingTalk runtime 和 web 工具都会尊重它们 |
451
438
 
@@ -467,6 +454,8 @@ Pipiclaw 有两层命令。
467
454
  | `/events show <name>` | 查看指定事件文件的完整 JSON |
468
455
  | `/events delete <name>` | 删除指定事件文件 |
469
456
  | `/events history [name]` | 查看事件调度历史,可按事件名过滤 |
457
+ | `/status` | 查看运行时状态:执行状态、当前模型、上下文用量、运行时长、版本 |
458
+ | `/usage [7d\|month]` | 查看本通道与全局的 LLM 成本,按类型和 Top 模型拆分 |
470
459
 
471
460
  忙碌时,普通消息默认等价于 `/steer <message>`。
472
461
 
@@ -1,14 +1,18 @@
1
1
  import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
2
- import type { DingTalkContext } from "../runtime/dingtalk.js";
2
+ import type { ChannelContext } from "../runtime/channel-context.js";
3
3
  import type { ChannelStore } from "../runtime/store.js";
4
4
  import { type SandboxConfig } from "../sandbox.js";
5
5
  import { type BuiltInCommand } from "./commands.js";
6
+ import type { RunnerFactoryPaths } from "./runner-factory.js";
6
7
  import { type AgentRunner, type RunnerStatusSnapshot } from "./types.js";
7
8
  export declare class ChannelRunner implements AgentRunner {
8
9
  private readonly executor;
9
10
  private readonly sandboxConfig;
10
11
  private readonly channelId;
11
12
  private readonly channelDir;
13
+ private readonly appHomeDir;
14
+ private readonly authConfigPath;
15
+ private readonly modelsConfigPath;
12
16
  private readonly workspacePath;
13
17
  private readonly workspaceDir;
14
18
  private session;
@@ -33,12 +37,12 @@ export declare class ChannelRunner implements AgentRunner {
33
37
  /** When the primary model last failed and we switched to the backup. null = on primary. */
34
38
  private primaryFailedAt;
35
39
  private runState;
36
- constructor(sandboxConfig: SandboxConfig, channelId: string, channelDir: string);
37
- run(ctx: DingTalkContext, store: ChannelStore): Promise<{
40
+ constructor(sandboxConfig: SandboxConfig, channelId: string, channelDir: string, paths: RunnerFactoryPaths);
41
+ run(ctx: ChannelContext, store: ChannelStore): Promise<{
38
42
  stopReason: string;
39
43
  errorMessage?: string;
40
44
  }>;
41
- handleBuiltinCommand(ctx: DingTalkContext, command: BuiltInCommand): Promise<void>;
45
+ handleBuiltinCommand(ctx: ChannelContext, command: BuiltInCommand): Promise<void>;
42
46
  queueSteer(text: string, userName?: string): Promise<void>;
43
47
  flushMemoryForShutdown(): Promise<void>;
44
48
  getMemoryMaintenanceContext(): Promise<MemoryMaintenanceRuntimeContext>;
@@ -11,7 +11,6 @@ import { applyMemoryActivityToState, updateMemoryMaintenanceState, } from "../me
11
11
  import { recallRelevantMemory } from "../memory/recall.js";
12
12
  import { getApiKeyForModel } from "../models/api-keys.js";
13
13
  import { findExactModelReferenceMatch, formatModelReference, resolveInitialModel } from "../models/utils.js";
14
- import { APP_HOME_DIR, AUTH_CONFIG_PATH, MODELS_CONFIG_PATH } from "../paths.js";
15
14
  import { createExecutor } from "../sandbox.js";
16
15
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
17
16
  import { PipiclawSettingsManager } from "../settings.js";
@@ -54,7 +53,7 @@ function asSdkSettingsManager(manager) {
54
53
  return manager;
55
54
  }
56
55
  export class ChannelRunner {
57
- constructor(sandboxConfig, channelId, channelDir) {
56
+ constructor(sandboxConfig, channelId, channelDir, paths) {
58
57
  this.ledger = getUsageLedger();
59
58
  this.currentTools = [];
60
59
  this.firstTurnMemoryBootstrapPending = true;
@@ -67,6 +66,9 @@ export class ChannelRunner {
67
66
  this.sandboxConfig = sandboxConfig;
68
67
  this.channelId = channelId;
69
68
  this.channelDir = channelDir;
69
+ this.appHomeDir = paths.appHomeDir;
70
+ this.authConfigPath = paths.authConfigPath;
71
+ this.modelsConfigPath = paths.modelsConfigPath;
70
72
  const executor = createExecutor(sandboxConfig);
71
73
  this.executor = executor;
72
74
  this.workspaceDir = resolve(dirname(channelDir));
@@ -77,12 +79,12 @@ export class ChannelRunner {
77
79
  // Create session manager
78
80
  const contextFile = join(channelDir, "context.jsonl");
79
81
  this.sessionManager = SessionManager.open(contextFile, channelDir);
80
- this.settingsManager = new PipiclawSettingsManager(APP_HOME_DIR);
82
+ this.settingsManager = new PipiclawSettingsManager(this.appHomeDir);
81
83
  this.reportSettingsDiagnostics();
82
84
  this.memoryCandidateStore = createMemoryCandidateStore();
83
85
  // Create AuthStorage and ModelRegistry
84
- const authStorage = AuthStorage.create(AUTH_CONFIG_PATH);
85
- this.modelRegistry = createModelRegistry(authStorage, MODELS_CONFIG_PATH);
86
+ const authStorage = AuthStorage.create(this.authConfigPath);
87
+ this.modelRegistry = createModelRegistry(authStorage, this.modelsConfigPath);
86
88
  // Resolve model: prefer saved global default, fall back to first available model
87
89
  this.activeModel = resolveInitialModel(this.modelRegistry, this.settingsManager);
88
90
  log.logInfo(`Using model: ${this.activeModel.provider}/${this.activeModel.id} (${this.activeModel.name})`);
@@ -479,7 +481,7 @@ export class ChannelRunner {
479
481
  ? new Date(eventTime + Math.max(0, maintenanceSettings.minIdleMinutesBeforeLlmWork) * 60_000).toISOString()
480
482
  : undefined;
481
483
  try {
482
- await updateMemoryMaintenanceState(APP_HOME_DIR, this.channelId, (state) => applyMemoryActivityToState(state, {
484
+ await updateMemoryMaintenanceState(this.appHomeDir, this.channelId, (state) => applyMemoryActivityToState(state, {
483
485
  ...event,
484
486
  eligibleAfter,
485
487
  }));
@@ -669,7 +671,7 @@ export class ChannelRunner {
669
671
  }
670
672
  reportSettingsDiagnostics() {
671
673
  for (const { scope, error } of this.settingsManager.drainErrors()) {
672
- log.logWarning(`[${this.channelId}] Failed to load ${scope} settings`, `${error.message}\n${join(APP_HOME_DIR, "settings.json")}`);
674
+ log.logWarning(`[${this.channelId}] Failed to load ${scope} settings`, `${error.message}\n${join(this.appHomeDir, "settings.json")}`);
673
675
  }
674
676
  }
675
677
  reportConfigDiagnostics(diagnostics) {
@@ -680,7 +682,7 @@ export class ChannelRunner {
680
682
  createResourceLoader() {
681
683
  return new DefaultResourceLoader({
682
684
  cwd: process.cwd(),
683
- agentDir: APP_HOME_DIR,
685
+ agentDir: this.appHomeDir,
684
686
  settingsManager: asSdkSettingsManager(this.settingsManager),
685
687
  extensionFactories: [
686
688
  this.memoryLifecycle.createExtensionFactory(),
@@ -735,8 +737,8 @@ export class ChannelRunner {
735
737
  createAgentSessionServices(resourceLoader) {
736
738
  return {
737
739
  cwd: process.cwd(),
738
- agentDir: APP_HOME_DIR,
739
- authStorage: AuthStorage.create(AUTH_CONFIG_PATH),
740
+ agentDir: this.appHomeDir,
741
+ authStorage: AuthStorage.create(this.authConfigPath),
740
742
  settingsManager: asSdkSettingsManager(this.settingsManager),
741
743
  modelRegistry: this.modelRegistry,
742
744
  resourceLoader,
@@ -776,8 +778,8 @@ export class ChannelRunner {
776
778
  return { agent, session, resourceLoader };
777
779
  }
778
780
  buildRuntimeTools() {
779
- const securityLoad = loadSecurityConfigWithDiagnostics(APP_HOME_DIR);
780
- const toolsLoad = loadToolsConfigWithDiagnostics(APP_HOME_DIR);
781
+ const securityLoad = loadSecurityConfigWithDiagnostics(this.appHomeDir);
782
+ const toolsLoad = loadToolsConfigWithDiagnostics(this.appHomeDir);
781
783
  this.reportConfigDiagnostics([...securityLoad.diagnostics, ...toolsLoad.diagnostics]);
782
784
  const tools = createPipiclawTools({
783
785
  executor: this.executor,
@@ -105,19 +105,25 @@ export async function runPromptWithFallback(promptText, deps) {
105
105
  if (fromRef === toRef) {
106
106
  return false;
107
107
  }
108
- // Surgery only when the failed turn was actually enqueued. A pre-flight throw
109
- // (no API key on the primary) submits nothing, so there is nothing to remove —
110
- // switch straight to the backup, which covers a mis-configured primary key.
108
+ // Pre-compute the truncated transcript, but do not commit it until setModel
109
+ // succeeds. Surgery only when the failed turn was actually enqueued: a pre-flight
110
+ // throw (no API key on the primary) submits nothing, so there is nothing to
111
+ // remove — switch straight to the backup, which covers a mis-configured primary key.
112
+ let truncated = null;
111
113
  if (deps.promptWasSubmitted()) {
112
- const truncated = takeFailedTurn(deps.getMessages());
114
+ truncated = takeFailedTurn(deps.getMessages());
113
115
  if (!truncated) {
114
116
  log.logWarning("[fallback] transcript tail is not [user, assistant(error)]; skipping fallback to avoid corrupting context");
115
117
  return false;
116
118
  }
117
- deps.setMessages(truncated);
118
119
  }
120
+ // Switch the model first: if setModel throws it propagates with the transcript
121
+ // still intact, so the failed turn's context is not silently lost.
119
122
  deps.markPrimaryFailed();
120
123
  await deps.setModel(candidate);
124
+ if (truncated) {
125
+ deps.setMessages(truncated);
126
+ }
121
127
  deps.notifySwitch(fromRef, toRef, summarizeFallbackError(firstError.errorMessage));
122
128
  deps.resetRunError();
123
129
  await deps.prompt(promptText);
@@ -1,7 +1,7 @@
1
- import type { DingTalkContext } from "../runtime/dingtalk.js";
1
+ import type { ChannelContext } from "../runtime/channel-context.js";
2
2
  import type { RunQueue } from "./types.js";
3
3
  export interface CreatedRunQueue {
4
4
  queue: RunQueue;
5
5
  drain: () => Promise<void>;
6
6
  }
7
- export declare function createRunQueue(ctx: DingTalkContext): CreatedRunQueue;
7
+ export declare function createRunQueue(ctx: ChannelContext): CreatedRunQueue;
@@ -1,4 +1,9 @@
1
1
  import type { SandboxConfig } from "../sandbox.js";
2
2
  import type { AgentRunner } from "./types.js";
3
- export declare function getOrCreateRunner(sandboxConfig: SandboxConfig, channelId: string, channelDir: string): AgentRunner;
4
- export declare function resetRunner(channelId: string): void;
3
+ export interface RunnerFactoryPaths {
4
+ appHomeDir: string;
5
+ authConfigPath: string;
6
+ modelsConfigPath: string;
7
+ }
8
+ export declare function getOrCreateRunner(sandboxConfig: SandboxConfig, channelId: string, channelDir: string, paths: RunnerFactoryPaths): AgentRunner;
9
+ export declare function resetRunner(channelId: string, paths?: RunnerFactoryPaths, channelDir?: string): void;
@@ -1,13 +1,25 @@
1
1
  import { ChannelRunner } from "./channel-runner.js";
2
2
  const channelRunners = new Map();
3
- export function getOrCreateRunner(sandboxConfig, channelId, channelDir) {
4
- const existing = channelRunners.get(channelId);
3
+ function runnerKey(paths, channelId, channelDir) {
4
+ return `${paths.appHomeDir}\0${channelDir}\0${channelId}`;
5
+ }
6
+ export function getOrCreateRunner(sandboxConfig, channelId, channelDir, paths) {
7
+ const key = runnerKey(paths, channelId, channelDir);
8
+ const existing = channelRunners.get(key);
5
9
  if (existing)
6
10
  return existing;
7
- const runner = new ChannelRunner(sandboxConfig, channelId, channelDir);
8
- channelRunners.set(channelId, runner);
11
+ const runner = new ChannelRunner(sandboxConfig, channelId, channelDir, paths);
12
+ channelRunners.set(key, runner);
9
13
  return runner;
10
14
  }
11
- export function resetRunner(channelId) {
12
- channelRunners.delete(channelId);
15
+ export function resetRunner(channelId, paths, channelDir) {
16
+ if (paths && channelDir) {
17
+ channelRunners.delete(runnerKey(paths, channelId, channelDir));
18
+ return;
19
+ }
20
+ for (const key of channelRunners.keys()) {
21
+ if (key.endsWith(`\0${channelId}`)) {
22
+ channelRunners.delete(key);
23
+ }
24
+ }
13
25
  }
@@ -1,10 +1,10 @@
1
1
  import type { MemoryLifecycle } from "../memory/lifecycle.js";
2
- import type { DingTalkContext } from "../runtime/dingtalk.js";
2
+ import type { ChannelContext } from "../runtime/channel-context.js";
3
3
  import type { ChannelStore } from "../runtime/store.js";
4
4
  import type { UsageLedger } from "../usage/ledger.js";
5
5
  import type { PendingTool, RunLogContext, RunQueue, RunState } from "./types.js";
6
6
  export interface SessionEventHandlerContext {
7
- ctx: DingTalkContext;
7
+ ctx: ChannelContext;
8
8
  logCtx: RunLogContext;
9
9
  queue: RunQueue;
10
10
  pendingTools: Map<string, PendingTool>;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * `/status` rendering. Extracted verbatim from `runtime/bootstrap.ts` so both
3
+ * the DingTalk runtime and the terminal TUI can render the same status block
4
+ * from an `AgentRunner` status snapshot. Pure functions, no side effects.
5
+ */
6
+ import type { SandboxConfig } from "../sandbox.js";
7
+ import type { AgentRunner } from "./types.js";
8
+ /** Minimal per-channel run state the status renderer needs. */
9
+ export interface StatusRenderState {
10
+ running: boolean;
11
+ currentTaskText?: string;
12
+ runner: Pick<AgentRunner, "getStatusSnapshot">;
13
+ }
14
+ export interface RenderStatusOptions {
15
+ state: StatusRenderState | undefined;
16
+ version: string;
17
+ uptimeMs: number;
18
+ sandbox: SandboxConfig;
19
+ }
20
+ export declare function formatTokenCount(count: number): string;
21
+ export declare function formatUptime(ms: number): string;
22
+ export declare function renderStatus(options: RenderStatusOptions): string;
@@ -0,0 +1,61 @@
1
+ export function formatTokenCount(count) {
2
+ if (count < 1000)
3
+ return count.toString();
4
+ if (count < 1_000_000)
5
+ return `${Math.round(count / 1000)}k`;
6
+ return `${(count / 1_000_000).toFixed(1)}M`;
7
+ }
8
+ export function formatUptime(ms) {
9
+ const totalSeconds = Math.floor(ms / 1000);
10
+ const days = Math.floor(totalSeconds / 86400);
11
+ const hours = Math.floor((totalSeconds % 86400) / 3600);
12
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
13
+ const parts = [];
14
+ if (days > 0)
15
+ parts.push(`${days}d`);
16
+ if (hours > 0)
17
+ parts.push(`${hours}h`);
18
+ parts.push(`${minutes}m`);
19
+ return parts.join(" ");
20
+ }
21
+ export function renderStatus(options) {
22
+ const { state, version, uptimeMs, sandbox } = options;
23
+ const lines = ["# Status"];
24
+ if (state?.running) {
25
+ const task = state.currentTaskText?.trim();
26
+ const preview = task ? `: ${task.length > 80 ? `${task.slice(0, 79)}…` : task}` : "";
27
+ lines.push(`- Run state: running${preview}`);
28
+ }
29
+ else {
30
+ lines.push("- Run state: idle");
31
+ }
32
+ if (state) {
33
+ try {
34
+ const snapshot = state.runner.getStatusSnapshot();
35
+ lines.push(`- Model: ${snapshot.model}`);
36
+ if (snapshot.fallback) {
37
+ const until = new Date(snapshot.fallback.cooldownUntilMs);
38
+ const hh = String(until.getHours()).padStart(2, "0");
39
+ const mm = String(until.getMinutes()).padStart(2, "0");
40
+ lines.push(`- Fallback: active(primary ${snapshot.fallback.primary} 冷却至 ${hh}:${mm})`);
41
+ }
42
+ if (snapshot.thinkingLevel && snapshot.thinkingLevel !== "off") {
43
+ lines.push(`- Thinking: ${snapshot.thinkingLevel}`);
44
+ }
45
+ if (snapshot.contextTokens !== undefined && snapshot.contextWindow > 0) {
46
+ const percent = ((snapshot.contextTokens / snapshot.contextWindow) * 100).toFixed(1);
47
+ lines.push(`- Context: ${formatTokenCount(snapshot.contextTokens)} / ${formatTokenCount(snapshot.contextWindow)} (${percent}%)`);
48
+ }
49
+ }
50
+ catch (err) {
51
+ lines.push(`- Model: unavailable (${err instanceof Error ? err.message : String(err)})`);
52
+ }
53
+ }
54
+ else {
55
+ lines.push("- Model: no session started for this channel yet");
56
+ }
57
+ lines.push(`- Sandbox: ${sandbox.type === "host" ? "host" : `docker:${sandbox.container}`}`);
58
+ lines.push(`- Uptime: ${formatUptime(uptimeMs)}`);
59
+ lines.push(`- Version: ${version}`);
60
+ return lines.join("\n");
61
+ }
@@ -65,12 +65,11 @@ export function isTurnEndEvent(value) {
65
65
  return hasEventType(value, "turn_end") && "message" in value && Array.isArray(value.toolResults);
66
66
  }
67
67
  export function isAutoCompactionStartEvent(value) {
68
- return ((hasEventType(value, "auto_compaction_start") && (value.reason === "threshold" || value.reason === "overflow")) ||
69
- (hasEventType(value, "compaction_start") &&
70
- (value.reason === "threshold" || value.reason === "overflow" || value.reason === "manual")));
68
+ return (hasEventType(value, "compaction_start") &&
69
+ (value.reason === "threshold" || value.reason === "overflow" || value.reason === "manual"));
71
70
  }
72
71
  export function isAutoCompactionEndEvent(value) {
73
- return hasEventType(value, "auto_compaction_end") || hasEventType(value, "compaction_end");
72
+ return hasEventType(value, "compaction_end");
74
73
  }
75
74
  export function isAutoRetryStartEvent(value) {
76
75
  return (hasEventType(value, "auto_retry_start") &&
@@ -1,5 +1,5 @@
1
1
  import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
2
- import type { DingTalkContext } from "../runtime/dingtalk.js";
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
5
  import type { BuiltInCommand } from "./commands.js";
@@ -15,11 +15,11 @@ export interface RunnerStatusSnapshot {
15
15
  };
16
16
  }
17
17
  export interface AgentRunner {
18
- run(ctx: DingTalkContext, store: ChannelStore): Promise<{
18
+ run(ctx: ChannelContext, store: ChannelStore): Promise<{
19
19
  stopReason: string;
20
20
  errorMessage?: string;
21
21
  }>;
22
- handleBuiltinCommand(ctx: DingTalkContext, command: BuiltInCommand): Promise<void>;
22
+ handleBuiltinCommand(ctx: ChannelContext, command: BuiltInCommand): Promise<void>;
23
23
  queueSteer(text: string, userName?: string): Promise<void>;
24
24
  flushMemoryForShutdown(): Promise<void>;
25
25
  getMemoryMaintenanceContext(): Promise<MemoryMaintenanceRuntimeContext>;
@@ -49,7 +49,7 @@ export interface RunLogContext {
49
49
  channelName?: string;
50
50
  }
51
51
  export interface RunState {
52
- ctx: DingTalkContext | null;
52
+ ctx: ChannelContext | null;
53
53
  logCtx: RunLogContext | null;
54
54
  store: ChannelStore | null;
55
55
  queue: RunQueue | null;
@@ -131,14 +131,11 @@ export type SessionEvent = {
131
131
  type: "turn_end";
132
132
  message: unknown;
133
133
  toolResults: unknown[];
134
- } | {
135
- type: "auto_compaction_start";
136
- reason: "threshold" | "overflow";
137
134
  } | {
138
135
  type: "compaction_start";
139
136
  reason: "manual" | "threshold" | "overflow";
140
137
  } | {
141
- type: "auto_compaction_end" | "compaction_end";
138
+ type: "compaction_end";
142
139
  reason?: "manual" | "threshold" | "overflow";
143
140
  result?: {
144
141
  tokensBefore: number;
@@ -172,10 +169,10 @@ export type TurnEndEvent = Extract<SessionEvent, {
172
169
  type: "turn_end";
173
170
  }>;
174
171
  export type AutoCompactionStartEvent = Extract<SessionEvent, {
175
- type: "auto_compaction_start" | "compaction_start";
172
+ type: "compaction_start";
176
173
  }>;
177
174
  export type AutoCompactionEndEvent = Extract<SessionEvent, {
178
- type: "auto_compaction_end" | "compaction_end";
175
+ type: "compaction_end";
179
176
  }>;
180
177
  export type AutoRetryStartEvent = Extract<SessionEvent, {
181
178
  type: "auto_retry_start";
package/dist/index.d.ts CHANGED
@@ -13,9 +13,10 @@ export { runSidecarTask, type SidecarResult, type SidecarTask, } from "./memory/
13
13
  export { getApiKeyForModel } from "./models/api-keys.js";
14
14
  export { findExactModelReferenceMatch, findModelReferenceMatch, formatModelList, formatModelReference, resolveInitialModel, } from "./models/utils.js";
15
15
  export { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, SUB_AGENTS_DIR, SUB_AGENTS_DIR_NAME, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "./paths.js";
16
+ export type { ChannelContext, ChannelContext as DingTalkContext, FinalDelivery, ProgressStyle, } from "./runtime/channel-context.js";
16
17
  export { ensureChannelDir, getChannelDir, getChannelDirName, } from "./runtime/channel-paths.js";
17
18
  export { createDingTalkContext } from "./runtime/delivery.js";
18
- export { type BusyMessageDefaultConfig, type BusyMessageMode, DingTalkBot, type DingTalkConfig, type DingTalkContext, type DingTalkEvent, type DingTalkHandler, type FinalDelivery, finalDeliveryOf, isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, type ProgressStyle, progressStyleOf, type ResponseMode, } from "./runtime/dingtalk.js";
19
+ export { type BusyMessageDefaultConfig, type BusyMessageMode, DingTalkBot, type DingTalkConfig, type DingTalkEvent, type DingTalkHandler, finalDeliveryOf, isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, progressStyleOf, type ResponseMode, } from "./runtime/dingtalk.js";
19
20
  export { createEventsWatcher, type EventAction, EventsWatcher, type ImmediateEvent, type OneShotEvent, type PeriodicEvent, type ScheduledEvent, } from "./runtime/events.js";
20
21
  export { ChannelStore, type LoggedMessage, type LoggedSubAgentRun } from "./runtime/store.js";
21
22
  export { createExecutor, type ExecOptions, type ExecResult, type Executor, parseSandboxArg, type SandboxConfig, validateSandbox, } from "./sandbox.js";
@@ -23,6 +24,6 @@ export { type PipiclawMemoryGrowthSettings, type PipiclawMemoryMaintenanceSettin
23
24
  export { discoverSubAgents, formatSubAgentList, getSubAgentsDir, type ResolvedSubAgentConfig, resolveSubAgentConfig, type SubAgentConfig, type SubAgentContextMode, type SubAgentDiscoveryResult, type SubAgentInvocationOverrides, type SubAgentMemoryMode, type SubAgentToolName, } from "./subagents/discovery.js";
24
25
  export { createSubAgentTool, type SubAgentToolDetails, type SubAgentToolOptions, } from "./subagents/tool.js";
25
26
  export { DEFAULT_TOOLS_CONFIG, getToolsConfigPath, loadToolsConfig, type PipiclawToolsConfig, type PipiclawWebFetchConfig, type PipiclawWebSearchConfig, type PipiclawWebToolsConfig, } from "./tools/config.js";
26
- export { type CreatePipiclawToolsOptions, createPipiclawBaseTools, createPipiclawTools, } from "./tools/index.js";
27
+ export { type CreatePipiclawToolsOptions, createPipiclawTools, } from "./tools/index.js";
27
28
  export { createUsageLedger, getUsageLedger, type UsageKind, type UsageLedger, type UsageLedgerEntry, type UsageSummary, } from "./usage/ledger.js";
28
29
  export { parseUsageMode, renderUsageReport, type UsageQueryMode, usageWindows } from "./usage/render.js";
package/dist/index.js CHANGED
@@ -23,6 +23,6 @@ export { PipiclawSettingsManager, } from "./settings.js";
23
23
  export { discoverSubAgents, formatSubAgentList, getSubAgentsDir, resolveSubAgentConfig, } from "./subagents/discovery.js";
24
24
  export { createSubAgentTool, } from "./subagents/tool.js";
25
25
  export { DEFAULT_TOOLS_CONFIG, getToolsConfigPath, loadToolsConfig, } from "./tools/config.js";
26
- export { createPipiclawBaseTools, createPipiclawTools, } from "./tools/index.js";
26
+ export { createPipiclawTools, } from "./tools/index.js";
27
27
  export { createUsageLedger, getUsageLedger, } from "./usage/ledger.js";
28
28
  export { parseUsageMode, renderUsageReport, usageWindows } from "./usage/render.js";
package/dist/log.d.ts CHANGED
@@ -27,6 +27,12 @@ export interface LoggingConfig {
27
27
  * have already applied at module load; this reconciles the two.
28
28
  */
29
29
  export declare function configureLogging(config: LoggingConfig): void;
30
+ /**
31
+ * Toggle the human-readable console sink. The TUI disables it so structured
32
+ * logging does not corrupt the pi-tui frame (which owns stdout); the file sink
33
+ * is unaffected, so logs are still captured when file logging is enabled.
34
+ */
35
+ export declare function setConsoleLoggingEnabled(enabled: boolean): void;
30
36
  export declare function logUserMessage(ctx: LogContext, text: string): void;
31
37
  export declare function logToolStart(ctx: LogContext, toolName: string, label: string, args: Record<string, unknown>): void;
32
38
  export declare function logToolSuccess(ctx: LogContext, toolName: string, durationMs: number, result: string): void;