@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/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,17 +1,13 @@
1
- import { readFile, stat } from "fs/promises";
1
+ import { stat } from "fs/promises";
2
2
  import { join } from "path";
3
+ import { readOptionalTextFile } from "../shared/fs-utils.js";
3
4
  import { splitH1Sections, splitH2Sections } from "../shared/markdown-sections.js";
4
- import { getChannelHistoryPath, getChannelMemoryPath, getChannelSessionPath } from "./files.js";
5
+ import { getChannelHistoryPath, getChannelMemoryPath, getChannelSessionPath, parseUpdateHeadingTimestamp, } from "./files.js";
5
6
  function normalizeContent(content) {
6
7
  return content.replace(/\r/g, "").trim();
7
8
  }
8
9
  async function readOptionalFile(path) {
9
- try {
10
- return normalizeContent(await readFile(path, "utf-8"));
11
- }
12
- catch {
13
- return "";
14
- }
10
+ return normalizeContent(await readOptionalTextFile(path));
15
11
  }
16
12
  function slugify(value) {
17
13
  return (value
@@ -79,14 +75,6 @@ function buildCandidate(source, path, title, content, timestamp, searchText) {
79
75
  priority: inferPriority(source, title),
80
76
  };
81
77
  }
82
- function parseUpdateBlockTimestamp(heading) {
83
- const match = heading.match(/^Update\s+(.+)$/);
84
- if (!match) {
85
- return undefined;
86
- }
87
- const timestamp = match[1].trim();
88
- return Number.isFinite(Date.parse(timestamp)) ? timestamp : undefined;
89
- }
90
78
  function buildWorkspaceOrChannelMemoryCandidates(source, path, content) {
91
79
  const sections = splitH2Sections(content);
92
80
  if (sections.length === 0 && content) {
@@ -99,7 +87,7 @@ function buildWorkspaceOrChannelMemoryCandidates(source, path, content) {
99
87
  .map((section) => {
100
88
  // `## Update <ISO>` blocks carry their write time in the heading; surfacing it
101
89
  // lets recall apply a recency boost and keeps appended-block ids distinct.
102
- const timestamp = source === "channel-memory" ? parseUpdateBlockTimestamp(section.heading) : undefined;
90
+ const timestamp = source === "channel-memory" ? parseUpdateHeadingTimestamp(section.heading) : undefined;
103
91
  return buildCandidate(source, path, section.heading, section.content, timestamp);
104
92
  });
105
93
  }
@@ -125,12 +125,7 @@ function normalizeMemoryOp(value) {
125
125
  }
126
126
  function parseConsolidationResponse(text) {
127
127
  const parsed = parseJsonObject(text);
128
- const rawOps = Array.isArray(parsed.memoryOps)
129
- ? parsed.memoryOps
130
- : // Back-compat: tolerate the old memoryEntries: string[] shape.
131
- Array.isArray(parsed.memoryEntries)
132
- ? parsed.memoryEntries.map((entry) => ({ op: "add", content: entry }))
133
- : [];
128
+ const rawOps = Array.isArray(parsed.memoryOps) ? parsed.memoryOps : [];
134
129
  return {
135
130
  memoryOps: rawOps.map(normalizeMemoryOp).filter((op) => op !== null),
136
131
  historyBlock: typeof parsed.historyBlock === "string" ? parsed.historyBlock.trim() : "",
@@ -1,5 +1,6 @@
1
1
  export declare function generateMemoryEntryId(): string;
2
2
  export declare function stripMemoryEntryIdComment(text: string): string;
3
+ export declare function parseUpdateHeadingTimestamp(heading: string): string | undefined;
3
4
  export interface ParsedMemoryEntry {
4
5
  id: string;
5
6
  content: string;
Binary file
@@ -114,6 +114,7 @@ export async function runSessionRefreshJob(input) {
114
114
  }
115
115
  try {
116
116
  await updateChannelSessionMemory({
117
+ channelId: input.channelId,
117
118
  channelDir: input.channelDir,
118
119
  messages: input.messages,
119
120
  model: input.model,
@@ -1,5 +1,6 @@
1
- import { readdir, readFile, stat } from "node:fs/promises";
1
+ import { readdir, stat } from "node:fs/promises";
2
2
  import { basename, join } from "node:path";
3
+ import { isNodeError, readOptionalTextFile } from "../shared/fs-utils.js";
3
4
  import { clipText } from "../shared/text-utils.js";
4
5
  import { isRecord } from "../shared/type-guards.js";
5
6
  const DEFAULT_MAX_CHARS_PER_DOCUMENT = 4_000;
@@ -11,20 +12,6 @@ const IGNORED_JSONL_FILES = new Set([
11
12
  "subagent-runs.jsonl",
12
13
  "memory-review.jsonl",
13
14
  ]);
14
- function isNodeError(error) {
15
- return error instanceof Error && "code" in error;
16
- }
17
- async function readOptionalFile(path) {
18
- try {
19
- return await readFile(path, "utf-8");
20
- }
21
- catch (error) {
22
- if (isNodeError(error) && error.code === "ENOENT") {
23
- return "";
24
- }
25
- throw error;
26
- }
27
- }
28
15
  function parseJsonLine(line) {
29
16
  const trimmed = line.trim();
30
17
  if (!trimmed) {
@@ -180,7 +167,7 @@ function parseLogEntry(value, path, lineNumber, maxChars) {
180
167
  });
181
168
  }
182
169
  async function parseJsonlFile(path, source, maxChars) {
183
- const content = await readOptionalFile(path);
170
+ const content = await readOptionalTextFile(path);
184
171
  if (!content.trim()) {
185
172
  return [];
186
173
  }
@@ -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 {};
@@ -3,6 +3,7 @@ import { join } from "path";
3
3
  import { parseBuiltInCommand } from "../agent/commands.js";
4
4
  import { getOrCreateRunner } from "../agent/index.js";
5
5
  import { resetRunner } from "../agent/runner-factory.js";
6
+ import { renderStatus } from "../agent/status-render.js";
6
7
  import * as log from "../log.js";
7
8
  import { ensureChannelMemoryFilesSync } from "../memory/files.js";
8
9
  import { MemoryMaintenanceScheduler } from "../memory/scheduler.js";
@@ -168,7 +169,7 @@ export class BootstrapExitError extends Error {
168
169
  export function isBootstrapExitError(error) {
169
170
  return error instanceof BootstrapExitError;
170
171
  }
171
- function readCliVersion() {
172
+ export function readCliVersion() {
172
173
  try {
173
174
  const raw = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf-8"));
174
175
  return typeof raw.version === "string" && raw.version.trim() ? raw.version : "0.0.0";
@@ -397,67 +398,6 @@ function flushInactiveChannelMemory(channelStates) {
397
398
  function isNoRunningTaskQueueError(err) {
398
399
  return err instanceof Error && err.message === "No task is currently running.";
399
400
  }
400
- function formatTokenCount(count) {
401
- if (count < 1000)
402
- return count.toString();
403
- if (count < 1_000_000)
404
- return `${Math.round(count / 1000)}k`;
405
- return `${(count / 1_000_000).toFixed(1)}M`;
406
- }
407
- function formatUptime(ms) {
408
- const totalSeconds = Math.floor(ms / 1000);
409
- const days = Math.floor(totalSeconds / 86400);
410
- const hours = Math.floor((totalSeconds % 86400) / 3600);
411
- const minutes = Math.floor((totalSeconds % 3600) / 60);
412
- const parts = [];
413
- if (days > 0)
414
- parts.push(`${days}d`);
415
- if (hours > 0)
416
- parts.push(`${hours}h`);
417
- parts.push(`${minutes}m`);
418
- return parts.join(" ");
419
- }
420
- function renderStatus(options) {
421
- const { state, version, uptimeMs, sandbox } = options;
422
- const lines = ["# Status"];
423
- if (state?.running) {
424
- const task = state.currentTaskText?.trim();
425
- const preview = task ? `: ${task.length > 80 ? `${task.slice(0, 79)}…` : task}` : "";
426
- lines.push(`- Run state: running${preview}`);
427
- }
428
- else {
429
- lines.push("- Run state: idle");
430
- }
431
- if (state) {
432
- try {
433
- const snapshot = state.runner.getStatusSnapshot();
434
- lines.push(`- Model: ${snapshot.model}`);
435
- if (snapshot.fallback) {
436
- const until = new Date(snapshot.fallback.cooldownUntilMs);
437
- const hh = String(until.getHours()).padStart(2, "0");
438
- const mm = String(until.getMinutes()).padStart(2, "0");
439
- lines.push(`- Fallback: active(primary ${snapshot.fallback.primary} 冷却至 ${hh}:${mm})`);
440
- }
441
- if (snapshot.thinkingLevel && snapshot.thinkingLevel !== "off") {
442
- lines.push(`- Thinking: ${snapshot.thinkingLevel}`);
443
- }
444
- if (snapshot.contextTokens !== undefined && snapshot.contextWindow > 0) {
445
- const percent = ((snapshot.contextTokens / snapshot.contextWindow) * 100).toFixed(1);
446
- lines.push(`- Context: ${formatTokenCount(snapshot.contextTokens)} / ${formatTokenCount(snapshot.contextWindow)} (${percent}%)`);
447
- }
448
- }
449
- catch (err) {
450
- lines.push(`- Model: unavailable (${err instanceof Error ? err.message : String(err)})`);
451
- }
452
- }
453
- else {
454
- lines.push("- Model: no session started for this channel yet");
455
- }
456
- lines.push(`- Sandbox: ${sandbox.type === "host" ? "host" : `docker:${sandbox.container}`}`);
457
- lines.push(`- Uptime: ${formatUptime(uptimeMs)}`);
458
- lines.push(`- Version: ${version}`);
459
- return lines.join("\n");
460
- }
461
401
  export function createRuntimeContext(options) {
462
402
  const startServices = options.startServices ?? true;
463
403
  const registerSignalHandlers = options.registerSignalHandlers ?? true;
@@ -485,7 +425,11 @@ export function createRuntimeContext(options) {
485
425
  ensureChannelMemoryFilesSync(channelDir);
486
426
  state = {
487
427
  running: false,
488
- runner: getOrCreateRunner(options.sandbox, channelId, channelDir),
428
+ runner: getOrCreateRunner(options.sandbox, channelId, channelDir, {
429
+ appHomeDir: options.paths.appHomeDir,
430
+ authConfigPath: options.paths.authConfigPath,
431
+ modelsConfigPath: options.paths.modelsConfigPath,
432
+ }),
489
433
  stopRequested: false,
490
434
  };
491
435
  channelStates.set(channelId, state);
@@ -720,7 +664,12 @@ export function createRuntimeContext(options) {
720
664
  }
721
665
  }
722
666
  for (const channelId of channelStates.keys()) {
723
- resetRunner(channelId);
667
+ const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
668
+ resetRunner(channelId, {
669
+ appHomeDir: options.paths.appHomeDir,
670
+ authConfigPath: options.paths.authConfigPath,
671
+ modelsConfigPath: options.paths.modelsConfigPath,
672
+ }, channelDir);
724
673
  }
725
674
  })();
726
675
  return shutdownPromise;
@@ -749,21 +698,19 @@ export function createRuntimeContext(options) {
749
698
  shutdown: shutdownWithReason,
750
699
  };
751
700
  }
752
- export async function bootstrap(argv, options = {}) {
753
- const io = options.io ?? console;
754
- const paths = options.paths ?? DEFAULT_BOOTSTRAP_PATHS;
755
- const registerSignalHandlers = options.registerSignalHandlers ?? true;
756
- const startServices = options.startServices ?? true;
757
- const parsedArgs = parseArgs(argv, paths, io);
758
- const sandbox = parsedArgs.sandbox;
759
- const bootstrapResult = bootstrapAppHome(paths);
760
- printBootstrapSummary(bootstrapResult, io, paths);
761
- if (bootstrapResult.channelTemplateCreated) {
762
- io.error(`Fill in ${paths.channelConfigPath} and run \`${paths.appName}\` again.`);
763
- throw new BootstrapExitError(1);
764
- }
765
- const dingtalkConfig = loadConfig(paths, io);
766
- dingtalkConfig.stateDir = paths.workspaceDir;
701
+ /**
702
+ * Transport-neutral app services shared by the DingTalk runtime and the terminal
703
+ * TUI: loads settings (surfacing load errors), reports tool/security config
704
+ * diagnostics, and validates the sandbox. Does NOT touch DingTalk config, so the
705
+ * TUI can call it without any DingTalk credentials.
706
+ *
707
+ * Extracted verbatim from `bootstrap()`; the DingTalk path calls it in the same
708
+ * position (after `loadConfig`, before `logStartup`) so its behavior is
709
+ * unchanged. Logging configuration is intentionally left to each caller
710
+ * (DingTalk: `createRuntimeContext`; TUI: right after this) to preserve the
711
+ * existing "diagnostics logged with default logging config" ordering.
712
+ */
713
+ export async function prepareAppServices(sandbox, paths = DEFAULT_BOOTSTRAP_PATHS, io = console) {
767
714
  const settingsManager = new PipiclawSettingsManager(paths.appHomeDir);
768
715
  for (const { scope, error } of settingsManager.drainErrors()) {
769
716
  log.logWarning(`Failed to load ${scope} settings`, `${error.message}\n${paths.settingsConfigPath}`);
@@ -784,6 +731,24 @@ export async function bootstrap(argv, options = {}) {
784
731
  }
785
732
  throw err;
786
733
  }
734
+ return { settingsManager };
735
+ }
736
+ export async function bootstrap(argv, options = {}) {
737
+ const io = options.io ?? console;
738
+ const paths = options.paths ?? DEFAULT_BOOTSTRAP_PATHS;
739
+ const registerSignalHandlers = options.registerSignalHandlers ?? true;
740
+ const startServices = options.startServices ?? true;
741
+ const parsedArgs = parseArgs(argv, paths, io);
742
+ const sandbox = parsedArgs.sandbox;
743
+ const bootstrapResult = bootstrapAppHome(paths);
744
+ printBootstrapSummary(bootstrapResult, io, paths);
745
+ if (bootstrapResult.channelTemplateCreated) {
746
+ io.error(`Fill in ${paths.channelConfigPath} and run \`${paths.appName}\` again.`);
747
+ throw new BootstrapExitError(1);
748
+ }
749
+ const dingtalkConfig = loadConfig(paths, io);
750
+ dingtalkConfig.stateDir = paths.workspaceDir;
751
+ await prepareAppServices(sandbox, paths, io);
787
752
  log.logStartup(paths.workspaceDir, sandbox.type === "host" ? "host" : `docker:${sandbox.container}`);
788
753
  const runtime = createRuntimeContext({
789
754
  paths,
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Transport-neutral delivery contract.
3
+ *
4
+ * `ChannelContext` is the surface a `ChannelRunner` turn writes to: progress
5
+ * updates, the final answer, side notices, and lifecycle hooks. The DingTalk
6
+ * transport implements it via AI Card streaming (`runtime/delivery.ts`); the
7
+ * terminal TUI implements it by rendering to the console (`tui/`). The runner
8
+ * and `session-events` depend only on this interface, never on a concrete
9
+ * transport.
10
+ *
11
+ * These declarations previously lived in `runtime/dingtalk.ts` under the name
12
+ * `DingTalkContext`; they were lifted here (and renamed) so a second transport
13
+ * can implement the contract without importing anything DingTalk-specific.
14
+ */
15
+ /**
16
+ * How progress is surfaced during a run. Derived from the transport's response
17
+ * mode so callers never branch on the raw enum string.
18
+ */
19
+ export type ProgressStyle = "full" | "rolling" | "none";
20
+ /** How the final answer is delivered. */
21
+ export type FinalDelivery = "plain" | "card";
22
+ export interface ChannelContext {
23
+ message: {
24
+ text: string;
25
+ rawText: string;
26
+ user: string;
27
+ userName?: string;
28
+ channel: string;
29
+ ts: string;
30
+ };
31
+ channelName?: string;
32
+ respond: (text: string, shouldLog?: boolean) => Promise<void>;
33
+ respondPlain: (text: string, shouldLog?: boolean) => Promise<boolean>;
34
+ replaceMessage: (text: string) => Promise<void>;
35
+ respondInThread: (text: string) => Promise<void>;
36
+ setTyping: (isTyping: boolean) => Promise<void>;
37
+ setWorking: (working: boolean) => Promise<void>;
38
+ deleteMessage: () => Promise<void>;
39
+ primeCard: (delayMs: number) => void;
40
+ flush: () => Promise<void>;
41
+ close: () => Promise<void>;
42
+ progressStyle: ProgressStyle;
43
+ finalDelivery: FinalDelivery;
44
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Transport-neutral delivery contract.
3
+ *
4
+ * `ChannelContext` is the surface a `ChannelRunner` turn writes to: progress
5
+ * updates, the final answer, side notices, and lifecycle hooks. The DingTalk
6
+ * transport implements it via AI Card streaming (`runtime/delivery.ts`); the
7
+ * terminal TUI implements it by rendering to the console (`tui/`). The runner
8
+ * and `session-events` depend only on this interface, never on a concrete
9
+ * transport.
10
+ *
11
+ * These declarations previously lived in `runtime/dingtalk.ts` under the name
12
+ * `DingTalkContext`; they were lifted here (and renamed) so a second transport
13
+ * can implement the contract without importing anything DingTalk-specific.
14
+ */
15
+ export {};
@@ -1,3 +1,4 @@
1
- import type { DingTalkBot, DingTalkContext, DingTalkEvent } from "./dingtalk.js";
1
+ import type { ChannelContext } from "./channel-context.js";
2
+ import type { DingTalkBot, DingTalkEvent } from "./dingtalk.js";
2
3
  import type { ChannelStore } from "./store.js";
3
- export declare function createDingTalkContext(event: DingTalkEvent, bot: DingTalkBot, store: ChannelStore): DingTalkContext;
4
+ export declare function createDingTalkContext(event: DingTalkEvent, bot: DingTalkBot, store: ChannelStore): ChannelContext;
@@ -1,8 +1,7 @@
1
+ import type { FinalDelivery, ProgressStyle } from "./channel-context.js";
1
2
  export type BusyMessageMode = "steer" | "followUp";
2
3
  export type BusyMessageDefaultConfig = BusyMessageMode | "followup";
3
4
  export type ResponseMode = "full_progress_then_plain_final" | "rolling_progress_then_plain_final" | "final_card_only";
4
- export type ProgressStyle = "full" | "rolling" | "none";
5
- export type FinalDelivery = "plain" | "card";
6
5
  export declare function progressStyleOf(mode: ResponseMode): ProgressStyle;
7
6
  export declare function finalDeliveryOf(mode: ResponseMode): FinalDelivery;
8
7
  export declare function isBusyMessageDefaultConfig(value: unknown): value is BusyMessageDefaultConfig;
@@ -31,29 +30,6 @@ export interface DingTalkEvent {
31
30
  conversationId: string;
32
31
  conversationType: string;
33
32
  }
34
- export interface DingTalkContext {
35
- message: {
36
- text: string;
37
- rawText: string;
38
- user: string;
39
- userName?: string;
40
- channel: string;
41
- ts: string;
42
- };
43
- channelName?: string;
44
- respond: (text: string, shouldLog?: boolean) => Promise<void>;
45
- respondPlain: (text: string, shouldLog?: boolean) => Promise<boolean>;
46
- replaceMessage: (text: string) => Promise<void>;
47
- respondInThread: (text: string) => Promise<void>;
48
- setTyping: (isTyping: boolean) => Promise<void>;
49
- setWorking: (working: boolean) => Promise<void>;
50
- deleteMessage: () => Promise<void>;
51
- primeCard: (delayMs: number) => void;
52
- flush: () => Promise<void>;
53
- close: () => Promise<void>;
54
- progressStyle: ProgressStyle;
55
- finalDelivery: FinalDelivery;
56
- }
57
33
  export type BusyMessageResult = {
58
34
  kind: "handled";
59
35
  } | {
@@ -999,7 +999,7 @@ export class DingTalkBot {
999
999
  return;
1000
1000
  }
1001
1001
  if (builtInCommand) {
1002
- await this.sendPlain(channelId, `A task is already running. Use \`/stop\`, \`/steer <message>\`, \`/followup <message>\`, or \`/events <action>\`. Plain messages default to ${this.busyMessageDefault}.`);
1002
+ await this.sendPlain(channelId, `A task is already running. Use \`/stop\`, \`/steer <message>\`, \`/followup <message>\`, \`/events <action>\`, \`/status\`, or \`/usage\`. Plain messages default to ${this.busyMessageDefault}.`);
1003
1003
  return;
1004
1004
  }
1005
1005
  if (isSlashCommand) {