@oyasmi/pipiclaw 0.7.1 → 0.7.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 (41) hide show
  1. package/README.md +1 -0
  2. package/dist/agent/channel-runner.d.ts +8 -4
  3. package/dist/agent/channel-runner.js +14 -12
  4. package/dist/agent/run-queue.d.ts +2 -2
  5. package/dist/agent/runner-factory.d.ts +7 -2
  6. package/dist/agent/runner-factory.js +18 -6
  7. package/dist/agent/session-events.d.ts +2 -2
  8. package/dist/agent/status-render.d.ts +22 -0
  9. package/dist/agent/status-render.js +61 -0
  10. package/dist/agent/types.d.ts +4 -4
  11. package/dist/index.d.ts +2 -1
  12. package/dist/log.d.ts +6 -0
  13. package/dist/log.js +38 -25
  14. package/dist/main.js +15 -2
  15. package/dist/runtime/bootstrap.d.ts +17 -0
  16. package/dist/runtime/bootstrap.js +44 -79
  17. package/dist/runtime/channel-context.d.ts +44 -0
  18. package/dist/runtime/channel-context.js +15 -0
  19. package/dist/runtime/delivery.d.ts +3 -2
  20. package/dist/runtime/dingtalk.d.ts +1 -25
  21. package/dist/settings.d.ts +13 -0
  22. package/dist/settings.js +6 -0
  23. package/dist/tui/app.d.ts +18 -0
  24. package/dist/tui/app.js +104 -0
  25. package/dist/tui/cli.d.ts +22 -0
  26. package/dist/tui/cli.js +116 -0
  27. package/dist/tui/colors.d.ts +9 -0
  28. package/dist/tui/colors.js +20 -0
  29. package/dist/tui/commands.d.ts +47 -0
  30. package/dist/tui/commands.js +64 -0
  31. package/dist/tui/pitui-frontend.d.ts +47 -0
  32. package/dist/tui/pitui-frontend.js +154 -0
  33. package/dist/tui/plain-frontend.d.ts +23 -0
  34. package/dist/tui/plain-frontend.js +56 -0
  35. package/dist/tui/renderer.d.ts +62 -0
  36. package/dist/tui/renderer.js +13 -0
  37. package/dist/tui/terminal-context.d.ts +27 -0
  38. package/dist/tui/terminal-context.js +84 -0
  39. package/dist/tui/turn-controller.d.ts +68 -0
  40. package/dist/tui/turn-controller.js +266 -0
  41. package/package.json +2 -1
package/README.md CHANGED
@@ -16,6 +16,7 @@ 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
22
  - 忙碌时可继续接收 `/steer`、`/followup`、`/stop`、`/events`
@@ -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,
@@ -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
+ }
@@ -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;
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";
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;
package/dist/log.js CHANGED
@@ -57,6 +57,19 @@ function emit(level, event, message, extra) {
57
57
  };
58
58
  void fileSink.append(record);
59
59
  }
60
+ let consoleEnabled = true;
61
+ /**
62
+ * Toggle the human-readable console sink. The TUI disables it so structured
63
+ * logging does not corrupt the pi-tui frame (which owns stdout); the file sink
64
+ * is unaffected, so logs are still captured when file logging is enabled.
65
+ */
66
+ export function setConsoleLoggingEnabled(enabled) {
67
+ consoleEnabled = enabled;
68
+ }
69
+ function con(...args) {
70
+ if (consoleEnabled)
71
+ console.log(...args);
72
+ }
60
73
  function color(style, text) {
61
74
  return styleText(style, text);
62
75
  }
@@ -111,19 +124,19 @@ function formatToolArgs(args) {
111
124
  }
112
125
  // User messages
113
126
  export function logUserMessage(ctx, text) {
114
- console.log(color("green", `${timestamp()} ${formatContext(ctx)} ${text}`));
127
+ con(color("green", `${timestamp()} ${formatContext(ctx)} ${text}`));
115
128
  emit("info", "user_message", text, { ctx });
116
129
  }
117
130
  // Tool execution
118
131
  export function logToolStart(ctx, toolName, label, args) {
119
132
  const formattedArgs = formatToolArgs(args);
120
- console.log(color("yellow", `${timestamp()} ${formatContext(ctx)} ↳ ${toolName}: ${label}`));
133
+ con(color("yellow", `${timestamp()} ${formatContext(ctx)} ↳ ${toolName}: ${label}`));
121
134
  if (formattedArgs) {
122
135
  const indented = formattedArgs
123
136
  .split("\n")
124
137
  .map((line) => ` ${line}`)
125
138
  .join("\n");
126
- console.log(color("dim", indented));
139
+ con(color("dim", indented));
127
140
  }
128
141
  emit("debug", "tool_start", `${toolName}: ${label}`, {
129
142
  ctx,
@@ -133,14 +146,14 @@ export function logToolStart(ctx, toolName, label, args) {
133
146
  }
134
147
  export function logToolSuccess(ctx, toolName, durationMs, result) {
135
148
  const duration = (durationMs / 1000).toFixed(1);
136
- console.log(color("yellow", `${timestamp()} ${formatContext(ctx)} ✓ ${toolName} (${duration}s)`));
149
+ con(color("yellow", `${timestamp()} ${formatContext(ctx)} ✓ ${toolName} (${duration}s)`));
137
150
  const truncated = truncate(result, 1000);
138
151
  if (truncated) {
139
152
  const indented = truncated
140
153
  .split("\n")
141
154
  .map((line) => ` ${line}`)
142
155
  .join("\n");
143
- console.log(color("dim", indented));
156
+ con(color("dim", indented));
144
157
  }
145
158
  emit("info", "tool_end", toolName, {
146
159
  ctx,
@@ -150,13 +163,13 @@ export function logToolSuccess(ctx, toolName, durationMs, result) {
150
163
  }
151
164
  export function logToolError(ctx, toolName, durationMs, error) {
152
165
  const duration = (durationMs / 1000).toFixed(1);
153
- console.log(color("yellow", `${timestamp()} ${formatContext(ctx)} ✗ ${toolName} (${duration}s)`));
166
+ con(color("yellow", `${timestamp()} ${formatContext(ctx)} ✗ ${toolName} (${duration}s)`));
154
167
  const truncated = truncate(error, 1000);
155
168
  const indented = truncated
156
169
  .split("\n")
157
170
  .map((line) => ` ${line}`)
158
171
  .join("\n");
159
- console.log(color("dim", indented));
172
+ con(color("dim", indented));
160
173
  emit("error", "tool_end", toolName, {
161
174
  ctx,
162
175
  details: truncated,
@@ -165,53 +178,53 @@ export function logToolError(ctx, toolName, durationMs, error) {
165
178
  }
166
179
  // Response streaming
167
180
  export function logResponseStart(ctx) {
168
- console.log(color("yellow", `${timestamp()} ${formatContext(ctx)} → Streaming response...`));
181
+ con(color("yellow", `${timestamp()} ${formatContext(ctx)} → Streaming response...`));
169
182
  emit("debug", "response_start", "Streaming response...", { ctx });
170
183
  }
171
184
  export function logThinking(ctx, thinking) {
172
- console.log(color("yellow", `${timestamp()} ${formatContext(ctx)} 💭 Thinking`));
185
+ con(color("yellow", `${timestamp()} ${formatContext(ctx)} 💭 Thinking`));
173
186
  const truncated = truncate(thinking, 1000);
174
187
  const indented = truncated
175
188
  .split("\n")
176
189
  .map((line) => ` ${line}`)
177
190
  .join("\n");
178
- console.log(color("dim", indented));
191
+ con(color("dim", indented));
179
192
  emit("debug", "thinking", "Thinking", { ctx, details: truncated });
180
193
  }
181
194
  export function logResponse(ctx, text) {
182
- console.log(color("yellow", `${timestamp()} ${formatContext(ctx)} 💬 Response`));
195
+ con(color("yellow", `${timestamp()} ${formatContext(ctx)} 💬 Response`));
183
196
  const truncated = truncate(text, 1000);
184
197
  const indented = truncated
185
198
  .split("\n")
186
199
  .map((line) => ` ${line}`)
187
200
  .join("\n");
188
- console.log(color("dim", indented));
201
+ con(color("dim", indented));
189
202
  emit("info", "response", "Response", { ctx, details: truncated });
190
203
  }
191
204
  // System
192
205
  export function logInfo(message) {
193
- console.log(color("blue", `${timestamp()} [system] ${message}`));
206
+ con(color("blue", `${timestamp()} [system] ${message}`));
194
207
  emit("info", "system", message);
195
208
  }
196
209
  export function logWarning(message, details) {
197
- console.log(color("yellow", `${timestamp()} [system] ⚠ ${message}`));
210
+ con(color("yellow", `${timestamp()} [system] ⚠ ${message}`));
198
211
  if (details) {
199
212
  const indented = details
200
213
  .split("\n")
201
214
  .map((line) => ` ${line}`)
202
215
  .join("\n");
203
- console.log(color("dim", indented));
216
+ con(color("dim", indented));
204
217
  }
205
218
  emit("warn", "system", message, { details });
206
219
  }
207
220
  export function logAgentError(ctx, error) {
208
221
  const context = ctx === "system" ? "[system]" : formatContext(ctx);
209
- console.log(color("yellow", `${timestamp()} ${context} ✗ Agent error`));
222
+ con(color("yellow", `${timestamp()} ${context} ✗ Agent error`));
210
223
  const indented = error
211
224
  .split("\n")
212
225
  .map((line) => ` ${line}`)
213
226
  .join("\n");
214
- console.log(color("dim", indented));
227
+ con(color("dim", indented));
215
228
  emit("error", "agent_error", "Agent error", {
216
229
  ctx: ctx === "system" ? undefined : ctx,
217
230
  details: error,
@@ -219,7 +232,7 @@ export function logAgentError(ctx, error) {
219
232
  }
220
233
  // Model fallback (spec 017)
221
234
  export function logModelFallback(ctx, from, to, error) {
222
- console.log(color("yellow", `${timestamp()} ${formatContext(ctx)} ⤳ Fallback ${from} → ${to}`));
235
+ con(color("yellow", `${timestamp()} ${formatContext(ctx)} ⤳ Fallback ${from} → ${to}`));
223
236
  emit("warn", "model_fallback", `Fallback ${from} → ${to}`, {
224
237
  ctx,
225
238
  details: error,
@@ -254,8 +267,8 @@ export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
254
267
  lines.push(`**Total: $${usage.cost.total.toFixed(4)}** (incl. sub-agents)`);
255
268
  const summary = lines.join("\n");
256
269
  // Log to console
257
- console.log(color("yellow", `${timestamp()} ${formatContext(ctx)} 💰 Usage`));
258
- console.log(color("dim", ` ${usage.input.toLocaleString()} in + ${usage.output.toLocaleString()} out` +
270
+ con(color("yellow", `${timestamp()} ${formatContext(ctx)} 💰 Usage`));
271
+ con(color("dim", ` ${usage.input.toLocaleString()} in + ${usage.output.toLocaleString()} out` +
259
272
  (usage.cacheRead > 0 || usage.cacheWrite > 0
260
273
  ? ` (${usage.cacheRead.toLocaleString()} cache read, ${usage.cacheWrite.toLocaleString()} cache write)`
261
274
  : "") +
@@ -276,11 +289,11 @@ export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
276
289
  }
277
290
  // Startup
278
291
  export function logStartup(workingDir, sandbox) {
279
- console.log("Starting pipiclaw...");
280
- console.log(` Working directory: ${workingDir}`);
281
- console.log(` Sandbox: ${sandbox}`);
292
+ con("Starting pipiclaw...");
293
+ con(` Working directory: ${workingDir}`);
294
+ con(` Sandbox: ${sandbox}`);
282
295
  }
283
296
  export function logConnected() {
284
- console.log("⚡️ pipiclaw connected and listening!");
285
- console.log("");
297
+ con("⚡️ pipiclaw connected and listening!");
298
+ con("");
286
299
  }
package/dist/main.js CHANGED
@@ -1,9 +1,22 @@
1
1
  #!/usr/bin/env node
2
2
  import { bootstrap, isBootstrapExitError } from "./runtime/bootstrap.js";
3
- void bootstrap(process.argv).catch((error) => {
3
+ import { runTui } from "./tui/cli.js";
4
+ function handleError(error) {
4
5
  if (isBootstrapExitError(error)) {
5
6
  process.exit(error.code);
6
7
  }
7
8
  console.error(error);
8
9
  process.exit(1);
9
- });
10
+ }
11
+ if (process.argv[2] === "tui") {
12
+ // The TUI resolves when the user exits (Ctrl-C / Ctrl-D / /exit) or a one-shot
13
+ // --print finishes. Exit explicitly: raw-mode stdin and the runner session
14
+ // keep the event loop alive, so the process would otherwise hang after the UI
15
+ // tears down.
16
+ runTui(process.argv).then(() => process.exit(0), handleError);
17
+ }
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.
21
+ bootstrap(process.argv).catch(handleError);
22
+ }
@@ -1,4 +1,5 @@
1
1
  import { type Executor, type SandboxConfig } from "../sandbox.js";
2
+ import { PipiclawSettingsManager } from "../settings.js";
2
3
  import { DingTalkBot, type DingTalkConfig, type DingTalkHandler } from "./dingtalk.js";
3
4
  import { ChannelStore } from "./store.js";
4
5
  export interface BootstrapPaths {
@@ -47,6 +48,7 @@ export declare class BootstrapExitError extends Error {
47
48
  constructor(code: number, message?: string);
48
49
  }
49
50
  export declare function isBootstrapExitError(error: unknown): error is BootstrapExitError;
51
+ export declare function readCliVersion(): string;
50
52
  export declare function bootstrapAppHome(paths?: BootstrapPaths): BootstrapResult;
51
53
  export declare function printBootstrapSummary(result: BootstrapResult, io?: BootstrapIO, paths?: BootstrapPaths): void;
52
54
  export declare function loadConfig(paths?: BootstrapPaths, io?: BootstrapIO): DingTalkConfig;
@@ -71,5 +73,20 @@ interface RuntimeContextOptions {
71
73
  export declare function createRuntimeContext(options: RuntimeContextOptions): RuntimeContext & {
72
74
  bot: DingTalkBot;
73
75
  };
76
+ /**
77
+ * Transport-neutral app services shared by the DingTalk runtime and the terminal
78
+ * TUI: loads settings (surfacing load errors), reports tool/security config
79
+ * diagnostics, and validates the sandbox. Does NOT touch DingTalk config, so the
80
+ * TUI can call it without any DingTalk credentials.
81
+ *
82
+ * Extracted verbatim from `bootstrap()`; the DingTalk path calls it in the same
83
+ * position (after `loadConfig`, before `logStartup`) so its behavior is
84
+ * unchanged. Logging configuration is intentionally left to each caller
85
+ * (DingTalk: `createRuntimeContext`; TUI: right after this) to preserve the
86
+ * existing "diagnostics logged with default logging config" ordering.
87
+ */
88
+ export declare function prepareAppServices(sandbox: SandboxConfig, paths?: BootstrapPaths, io?: BootstrapIO): Promise<{
89
+ settingsManager: PipiclawSettingsManager;
90
+ }>;
74
91
  export declare function bootstrap(argv: string[], options?: BootstrapOptions): Promise<AppContext>;
75
92
  export {};