@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
@@ -1,6 +1,7 @@
1
1
  import { existsSync } from "fs";
2
2
  import { readdir, readFile, unlink } from "fs/promises";
3
3
  import { join, resolve, sep } from "path";
4
+ import { eventNameFromFilename } from "../shared/text-utils.js";
4
5
  import { parseScheduledEventContent } from "./events.js";
5
6
  const EVENT_NAME_PATTERN = /^[A-Za-z0-9._-]+$/;
6
7
  const DEFAULT_HISTORY_LIMIT = 20;
@@ -61,9 +62,6 @@ function resolveEventPath(workspaceDir, name) {
61
62
  }
62
63
  return { eventName, eventPath };
63
64
  }
64
- function eventNameFromFilename(filename) {
65
- return filename.endsWith(".json") ? filename.slice(0, -".json".length) : filename;
66
- }
67
65
  function clipText(text, maxChars = TEXT_PREVIEW_MAX_CHARS) {
68
66
  const normalized = text.replace(/\s+/g, " ").trim();
69
67
  return normalized.length > maxChars ? `${normalized.slice(0, maxChars - 1)}...` : normalized;
@@ -4,6 +4,7 @@ import { readFile } from "fs/promises";
4
4
  import { dirname, join, resolve } from "path";
5
5
  import * as log from "../log.js";
6
6
  import { guardCommand } from "../security/command-guard.js";
7
+ import { eventNameFromFilename } from "../shared/text-utils.js";
7
8
  // ============================================================================
8
9
  // EventsWatcher
9
10
  // ============================================================================
@@ -27,9 +28,6 @@ export function formatLocalTimestamp(date = new Date()) {
27
28
  const offsetRemainderMinutes = absOffsetMinutes % 60;
28
29
  return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}T${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}.${pad3(date.getMilliseconds())}${offsetSign}${pad2(offsetHours)}:${pad2(offsetRemainderMinutes)}`;
29
30
  }
30
- function eventNameFromFilename(filename) {
31
- return filename.endsWith(".json") ? filename.slice(0, -".json".length) : filename;
32
- }
33
31
  function truncateTextPreview(text) {
34
32
  const normalized = text.replace(/\s+/g, " ").trim();
35
33
  return normalized.length > TEXT_PREVIEW_MAX_CHARS
@@ -46,7 +46,7 @@ export declare class ChannelStore {
46
46
  private workingDir;
47
47
  private recentlyLogged;
48
48
  private cleanupTimer;
49
- private writeChains;
49
+ private writeQueue;
50
50
  constructor(config: ChannelStoreConfig);
51
51
  /**
52
52
  * Get or create the directory for a channel/DM
@@ -68,12 +68,6 @@ export declare class ChannelStore {
68
68
  * Log a bot response
69
69
  */
70
70
  logBotResponse(channelId: string, text: string, ts: string): Promise<void>;
71
- /**
72
- * Get the timestamp of the last logged message for a channel
73
- * Returns null if no log exists
74
- */
75
- getLastTimestamp(channelId: string): string | null;
76
- private enqueueWrite;
77
71
  private startCleanupTimer;
78
72
  private cleanupExpiredEntries;
79
73
  }
@@ -1,7 +1,8 @@
1
- import { closeSync, existsSync, mkdirSync, openSync, readSync, renameSync, statSync } from "fs";
1
+ import { existsSync, mkdirSync, renameSync, statSync } from "fs";
2
2
  import { appendFile, writeFile } from "fs/promises";
3
3
  import { dirname, join } from "path";
4
- import { ensureChannelDir, getChannelDir } from "./channel-paths.js";
4
+ import { createSerialQueue } from "../shared/serial-queue.js";
5
+ import { ensureChannelDir } from "./channel-paths.js";
5
6
  const MAX_LOG_SIZE_BYTES = 1_000_000;
6
7
  const DEDUPE_TTL_MS = 60_000;
7
8
  const DEDUPE_CLEANUP_INTERVAL_MS = 30_000;
@@ -9,7 +10,7 @@ export class ChannelStore {
9
10
  constructor(config) {
10
11
  this.recentlyLogged = new Map();
11
12
  this.cleanupTimer = null;
12
- this.writeChains = new Map();
13
+ this.writeQueue = createSerialQueue();
13
14
  this.workingDir = config.workingDir;
14
15
  // Ensure working directory exists
15
16
  if (!existsSync(this.workingDir)) {
@@ -43,7 +44,7 @@ export class ChannelStore {
43
44
  if (!message.date) {
44
45
  message.date = new Date().toISOString();
45
46
  }
46
- await this.enqueueWrite(logPath, async () => {
47
+ await this.writeQueue.run(logPath, async () => {
47
48
  await this.rotateIfNeeded(logPath);
48
49
  const line = `${JSON.stringify(message)}\n`;
49
50
  await appendFile(logPath, line, "utf-8");
@@ -52,7 +53,7 @@ export class ChannelStore {
52
53
  }
53
54
  async logSubAgentRun(channelId, run) {
54
55
  const logPath = join(this.getChannelDir(channelId), "subagent-runs.jsonl");
55
- await this.enqueueWrite(logPath, async () => {
56
+ await this.writeQueue.run(logPath, async () => {
56
57
  await this.rotateIfNeeded(logPath);
57
58
  const line = `${JSON.stringify(run)}\n`;
58
59
  await appendFile(logPath, line, "utf-8");
@@ -94,81 +95,6 @@ export class ChannelStore {
94
95
  isBot: true,
95
96
  });
96
97
  }
97
- /**
98
- * Get the timestamp of the last logged message for a channel
99
- * Returns null if no log exists
100
- */
101
- getLastTimestamp(channelId) {
102
- const logPath = join(getChannelDir(this.workingDir, channelId), "log.jsonl");
103
- if (!existsSync(logPath)) {
104
- return null;
105
- }
106
- try {
107
- const stats = statSync(logPath);
108
- if (stats.size === 0) {
109
- return null;
110
- }
111
- const fd = openSync(logPath, "r");
112
- try {
113
- let end = stats.size;
114
- const trailing = Buffer.alloc(1);
115
- while (end > 0) {
116
- readSync(fd, trailing, 0, 1, end - 1);
117
- if (trailing[0] !== 0x0a && trailing[0] !== 0x0d) {
118
- break;
119
- }
120
- end--;
121
- }
122
- if (end === 0) {
123
- return null;
124
- }
125
- const chunkSize = 4096;
126
- const buffer = Buffer.alloc(chunkSize);
127
- let lineStart = 0;
128
- let position = end;
129
- while (position > 0) {
130
- const bytesToRead = Math.min(chunkSize, position);
131
- position -= bytesToRead;
132
- readSync(fd, buffer, 0, bytesToRead, position);
133
- const newlineIndex = buffer.subarray(0, bytesToRead).lastIndexOf(0x0a);
134
- if (newlineIndex !== -1) {
135
- lineStart = position + newlineIndex + 1;
136
- break;
137
- }
138
- }
139
- const lineLength = end - lineStart;
140
- if (lineLength <= 0) {
141
- return null;
142
- }
143
- const lineBuffer = Buffer.alloc(lineLength);
144
- readSync(fd, lineBuffer, 0, lineLength, lineStart);
145
- const lastLine = lineBuffer.toString("utf-8").replace(/\r+$/, "");
146
- if (!lastLine) {
147
- return null;
148
- }
149
- const message = JSON.parse(lastLine);
150
- return message.ts;
151
- }
152
- finally {
153
- closeSync(fd);
154
- }
155
- }
156
- catch {
157
- return null;
158
- }
159
- }
160
- enqueueWrite(logPath, work) {
161
- const previous = this.writeChains.get(logPath) ?? Promise.resolve();
162
- const result = previous.catch(() => undefined).then(() => work());
163
- const completion = result.then(() => undefined, () => undefined);
164
- this.writeChains.set(logPath, completion);
165
- completion.finally(() => {
166
- if (this.writeChains.get(logPath) === completion) {
167
- this.writeChains.delete(logPath);
168
- }
169
- });
170
- return result;
171
- }
172
98
  startCleanupTimer() {
173
99
  if (this.cleanupTimer) {
174
100
  return;
@@ -7,6 +7,7 @@
7
7
  * This module currently provides only PipiclawSettingsManager.
8
8
  */
9
9
  import type { Transport } from "@earendil-works/pi-ai";
10
+ import type { ResponseMode } from "./runtime/dingtalk.js";
10
11
  import type { ConfigDiagnostic } from "./shared/config-diagnostics.js";
11
12
  type PackageSource = string | {
12
13
  source: string;
@@ -124,6 +125,17 @@ export interface PipiclawSettings {
124
125
  logging?: Partial<Omit<PipiclawLoggingSettings, "file">> & {
125
126
  file?: Partial<PipiclawLoggingSettings["file"]>;
126
127
  };
128
+ tui?: Partial<PipiclawTuiSettings>;
129
+ }
130
+ export interface PipiclawTuiSettings {
131
+ /**
132
+ * Output shape for the terminal TUI, reusing the DingTalk response-mode
133
+ * vocabulary: `full_progress_then_plain_final` (default) streams full progress
134
+ * then a plain final answer; `rolling_progress_then_plain_final` keeps only
135
+ * recent progress; `final_card_only` hides progress. Independent of the
136
+ * DingTalk channel's `responseMode` in `channel.json`.
137
+ */
138
+ responseMode: ResponseMode;
127
139
  }
128
140
  /**
129
141
  * Settings manager for pipiclaw.
@@ -149,6 +161,7 @@ export declare class PipiclawSettingsManager {
149
161
  getMemoryMaintenanceSettings(): PipiclawMemoryMaintenanceSettings;
150
162
  getSessionSearchSettings(): PipiclawSessionSearchSettings;
151
163
  getLoggingSettings(): PipiclawLoggingSettings;
164
+ getTuiSettings(): PipiclawTuiSettings;
152
165
  getRetryEnabled(): boolean;
153
166
  setRetryEnabled(enabled: boolean): void;
154
167
  /**
package/dist/settings.js CHANGED
@@ -9,6 +9,9 @@
9
9
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
10
10
  import { dirname, join } from "path";
11
11
  import * as log from "./log.js";
12
+ const DEFAULT_TUI = {
13
+ responseMode: "full_progress_then_plain_final",
14
+ };
12
15
  const DEFAULT_COMPACTION = {
13
16
  enabled: true,
14
17
  reserveTokens: 16384,
@@ -205,6 +208,9 @@ export class PipiclawSettingsManager {
205
208
  },
206
209
  };
207
210
  }
211
+ getTuiSettings() {
212
+ return { ...DEFAULT_TUI, ...this.settings.tui };
213
+ }
208
214
  getRetryEnabled() {
209
215
  return this.settings.retry?.enabled ?? DEFAULT_RETRY.enabled;
210
216
  }
@@ -0,0 +1,8 @@
1
+ export declare function isNodeError(error: unknown): error is NodeJS.ErrnoException;
2
+ /**
3
+ * Read a UTF-8 text file, returning "" when it does not exist.
4
+ *
5
+ * Only ENOENT is swallowed — permission/IO errors propagate so callers do not
6
+ * silently treat a real read failure as an absent file.
7
+ */
8
+ export declare function readOptionalTextFile(path: string): Promise<string>;
@@ -0,0 +1,21 @@
1
+ import { readFile } from "fs/promises";
2
+ export function isNodeError(error) {
3
+ return error instanceof Error && "code" in error;
4
+ }
5
+ /**
6
+ * Read a UTF-8 text file, returning "" when it does not exist.
7
+ *
8
+ * Only ENOENT is swallowed — permission/IO errors propagate so callers do not
9
+ * silently treat a real read failure as an absent file.
10
+ */
11
+ export async function readOptionalTextFile(path) {
12
+ try {
13
+ return await readFile(path, "utf-8");
14
+ }
15
+ catch (error) {
16
+ if (isNodeError(error) && error.code === "ENOENT") {
17
+ return "";
18
+ }
19
+ throw error;
20
+ }
21
+ }
@@ -5,5 +5,7 @@ export declare function clipText(text: string, maxChars: number, opts?: {
5
5
  }): string;
6
6
  export declare function truncate(text: string, maxLen: number): string;
7
7
  export declare const HAN_REGEX: RegExp;
8
+ /** Strip a trailing `.json` from an event filename to get its logical name. */
9
+ export declare function eventNameFromFilename(filename: string): string;
8
10
  export declare function extractLabelFromArgs(args: unknown): string | null;
9
11
  export declare function extractAssistantText(message: AssistantMessage): string;
@@ -20,6 +20,10 @@ export function truncate(text, maxLen) {
20
20
  return `${text.substring(0, maxLen - 3)}...`;
21
21
  }
22
22
  export const HAN_REGEX = /\p{Script=Han}/u;
23
+ /** Strip a trailing `.json` from an event filename to get its logical name. */
24
+ export function eventNameFromFilename(filename) {
25
+ return filename.endsWith(".json") ? filename.slice(0, -".json".length) : filename;
26
+ }
23
27
  export function extractLabelFromArgs(args) {
24
28
  if (!args || typeof args !== "object" || !("label" in args)) {
25
29
  return null;
@@ -2,7 +2,7 @@ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import type { MemoryCandidateStore } from "../memory/candidates.js";
4
4
  import type { Executor, SandboxConfig } from "../sandbox.js";
5
- import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
5
+ import type { SecurityConfig } from "../security/types.js";
6
6
  import type { PipiclawMemoryRecallSettings, PipiclawSessionSearchSettings } from "../settings.js";
7
7
  import type { SubAgentDiscoveryResult } from "../subagents/discovery.js";
8
8
  import type { PipiclawToolsConfig } from "./config.js";
@@ -23,10 +23,4 @@ export interface CreatePipiclawToolsOptions {
23
23
  securityConfig?: SecurityConfig;
24
24
  toolsConfig?: PipiclawToolsConfig;
25
25
  }
26
- export interface CreatePipiclawBaseToolsOptions {
27
- securityConfig?: SecurityConfig;
28
- securityContext?: SecurityRuntimeContext;
29
- channelId?: string;
30
- }
31
- export declare function createPipiclawBaseTools(executor: Executor, options?: CreatePipiclawBaseToolsOptions): AgentTool<any>[];
32
26
  export declare function createPipiclawTools(options: CreatePipiclawToolsOptions): AgentTool<any>[];
@@ -1,28 +1,8 @@
1
1
  import { APP_HOME_DIR } from "../paths.js";
2
2
  import { loadSecurityConfig } from "../security/config.js";
3
3
  import { createSubAgentTool } from "../subagents/tool.js";
4
- import { createBashTool } from "./bash.js";
5
4
  import { loadToolsConfig } from "./config.js";
6
- import { createEditTool } from "./edit.js";
7
- import { createReadTool } from "./read.js";
8
5
  import { buildToolSet } from "./registry.js";
9
- import { createWriteTool } from "./write.js";
10
- export function createPipiclawBaseTools(executor, options = {}) {
11
- const hasSecurityOptions = options.securityConfig || options.securityContext || options.channelId;
12
- const toolOptions = hasSecurityOptions
13
- ? {
14
- securityConfig: options.securityConfig,
15
- securityContext: options.securityContext,
16
- channelId: options.channelId,
17
- }
18
- : undefined;
19
- return [
20
- createReadTool(executor, toolOptions),
21
- createBashTool(executor, toolOptions),
22
- createEditTool(executor, toolOptions),
23
- createWriteTool(executor, toolOptions),
24
- ];
25
- }
26
6
  export function createPipiclawTools(options) {
27
7
  const securityConfig = options.securityConfig ?? loadSecurityConfig(APP_HOME_DIR);
28
8
  const toolsConfig = options.toolsConfig ?? loadToolsConfig(APP_HOME_DIR);
@@ -3,7 +3,6 @@ import { Type } from "typebox";
3
3
  import type { MemoryCandidateStore } from "../memory/candidates.js";
4
4
  import { type ChannelMemoryQueue } from "../memory/channel-maintenance-queue.js";
5
5
  declare const memorySaveSchema: Type.TObject<{
6
- label: Type.TString;
7
6
  content: Type.TString;
8
7
  kind: Type.TOptional<Type.TUnion<[Type.TLiteral<"preference">, Type.TLiteral<"fact">, Type.TLiteral<"decision">, Type.TLiteral<"constraint">, Type.TLiteral<"open-loop">]>>;
9
8
  }>;
@@ -2,7 +2,6 @@ import { Type } from "typebox";
2
2
  import { getDefaultChannelMemoryQueue } from "../memory/channel-maintenance-queue.js";
3
3
  import { applyChannelMemoryOps, getChannelMemoryPath } from "../memory/files.js";
4
4
  const memorySaveSchema = Type.Object({
5
- label: Type.String({ description: "Brief description of what you're saving and why (shown to user)" }),
6
5
  content: Type.String({
7
6
  description: "The durable fact to remember, as a single self-contained, keyword-rich sentence. Write it so future keyword search can find it.",
8
7
  }),
@@ -0,0 +1,18 @@
1
+ import { type BootstrapIO, type BootstrapPaths } from "../runtime/bootstrap.js";
2
+ import type { SandboxConfig } from "../sandbox.js";
3
+ export interface TuiAppOptions {
4
+ sandbox: SandboxConfig;
5
+ channel?: string;
6
+ /** One-shot, non-interactive run: process a single prompt then exit. */
7
+ print?: boolean;
8
+ /** Suppress progress/notice output (plain frontend). */
9
+ quiet?: boolean;
10
+ /** Force the plain frontend even on a TTY. */
11
+ plain?: boolean;
12
+ /** Initial prompt to run before handing control to the input loop. */
13
+ initialPrompt?: string;
14
+ io?: BootstrapIO;
15
+ paths?: BootstrapPaths;
16
+ }
17
+ export declare function resolveChannelId(raw: string | undefined, io?: BootstrapIO): string;
18
+ export declare function runTuiApp(options: TuiAppOptions): Promise<void>;
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Terminal TUI runtime: transport-neutral app init (no DingTalk gate), channel
3
+ * resolution, and wiring of the collaborators the `TurnController` drives.
4
+ *
5
+ * The heavy lifting is reused as-is: `ChannelRunner` drives each turn, the
6
+ * `ChannelContext` is a terminal one (`terminal-context.ts`), and app
7
+ * preparation shares `prepareAppServices` with the DingTalk path.
8
+ */
9
+ import { userInfo } from "node:os";
10
+ import { renderBuiltInHelp } from "../agent/commands.js";
11
+ import { getOrCreateRunner } from "../agent/index.js";
12
+ import { resetRunner } from "../agent/runner-factory.js";
13
+ import * as log from "../log.js";
14
+ import { ensureChannelMemoryFilesSync } from "../memory/files.js";
15
+ import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, prepareAppServices, printBootstrapSummary, readCliVersion, } from "../runtime/bootstrap.js";
16
+ import { ensureChannelDir } from "../runtime/channel-paths.js";
17
+ import { finalDeliveryOf, progressStyleOf } from "../runtime/dingtalk.js";
18
+ import { handleEventsCommand } from "../runtime/event-commands.js";
19
+ import { ChannelStore } from "../runtime/store.js";
20
+ import { getUsageLedger } from "../usage/ledger.js";
21
+ import { parseUsageMode, renderUsageReport } from "../usage/render.js";
22
+ import { TUI_SLASH_COMMANDS } from "./commands.js";
23
+ import { createFrontend } from "./renderer.js";
24
+ import { TurnController } from "./turn-controller.js";
25
+ const DEFAULT_CHANNEL_ID = "tui_local";
26
+ const CHANNEL_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
27
+ export function resolveChannelId(raw, io = console) {
28
+ const channel = raw?.trim() || DEFAULT_CHANNEL_ID;
29
+ if (!CHANNEL_ID_PATTERN.test(channel)) {
30
+ io.error(`Invalid --channel "${channel}": use letters, digits, dot, dash or underscore.`);
31
+ throw new BootstrapExitError(1);
32
+ }
33
+ return channel;
34
+ }
35
+ function safeUserName() {
36
+ try {
37
+ return userInfo().username || "you";
38
+ }
39
+ catch {
40
+ return "you";
41
+ }
42
+ }
43
+ export async function runTuiApp(options) {
44
+ const io = options.io ?? console;
45
+ const paths = options.paths ?? DEFAULT_BOOTSTRAP_PATHS;
46
+ const { sandbox } = options;
47
+ const channelId = resolveChannelId(options.channel, io);
48
+ // The pi-tui frontend owns stdout; the plain frontend prints only the final
49
+ // answer. Either way the human-readable console log sink would corrupt output,
50
+ // so route logging to the file sink only. Turn progress and errors are still
51
+ // surfaced through the transcript.
52
+ log.setConsoleLoggingEnabled(false);
53
+ // Transport-neutral init. Unlike the DingTalk path, the TUI ignores
54
+ // channelTemplateCreated (it needs no channel.json) and shares app services
55
+ // (settings, diagnostics, sandbox check) with bootstrap via prepareAppServices.
56
+ printBootstrapSummary(bootstrapAppHome(paths), io, paths);
57
+ const { settingsManager } = await prepareAppServices(sandbox, paths, io);
58
+ log.configureLogging(settingsManager.getLoggingSettings());
59
+ log.logStartup(paths.workspaceDir, sandbox.type === "host" ? "host" : `docker:${sandbox.container}`);
60
+ const channelDir = ensureChannelDir(paths.workspaceDir, channelId);
61
+ ensureChannelMemoryFilesSync(channelDir);
62
+ const store = new ChannelStore({ workingDir: paths.workspaceDir });
63
+ const runner = getOrCreateRunner(sandbox, channelId, channelDir, {
64
+ appHomeDir: paths.appHomeDir,
65
+ authConfigPath: paths.authConfigPath,
66
+ modelsConfigPath: paths.modelsConfigPath,
67
+ });
68
+ const tuiSettings = settingsManager.getTuiSettings();
69
+ const traits = {
70
+ progressStyle: progressStyleOf(tuiSettings.responseMode),
71
+ finalDelivery: finalDeliveryOf(tuiSettings.responseMode),
72
+ };
73
+ const interactive = !options.print;
74
+ const frontend = createFrontend({
75
+ plain: options.plain,
76
+ quiet: options.quiet,
77
+ interactive,
78
+ commands: TUI_SLASH_COMMANDS,
79
+ basePath: paths.workspaceDir,
80
+ });
81
+ const controller = new TurnController({
82
+ runner,
83
+ frontend,
84
+ store,
85
+ traits,
86
+ channelId,
87
+ userName: safeUserName(),
88
+ renderHelp: () => renderBuiltInHelp(),
89
+ renderUsage: (args) => renderUsageReport(getUsageLedger(), channelId, parseUsageMode(args), new Date()),
90
+ runEvents: (args) => handleEventsCommand({ args, workspaceDir: paths.workspaceDir, historyPath: paths.eventHistoryPath }),
91
+ statusInfo: { version: readCliVersion(), sandbox, startedAt: Date.now() },
92
+ });
93
+ try {
94
+ if (options.print) {
95
+ await controller.runOnce(options.initialPrompt);
96
+ }
97
+ else {
98
+ await controller.startInteractive(options.initialPrompt);
99
+ }
100
+ }
101
+ finally {
102
+ resetRunner(channelId);
103
+ }
104
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * `pipiclaw tui` CLI: argument parsing and entry. Parsing is a pure function
3
+ * (`parseTuiArgs`) so it can be unit-tested; `runTui` wires it to `runTuiApp`.
4
+ */
5
+ import { type BootstrapIO } from "../runtime/bootstrap.js";
6
+ import { type SandboxConfig } from "../sandbox.js";
7
+ export type ParsedTui = {
8
+ kind: "run";
9
+ channel?: string;
10
+ sandbox: SandboxConfig;
11
+ print: boolean;
12
+ quiet: boolean;
13
+ plain: boolean;
14
+ positional: string[];
15
+ } | {
16
+ kind: "help";
17
+ } | {
18
+ kind: "version";
19
+ };
20
+ /** Parse `pipiclaw tui` arguments (everything after the `tui` subcommand). */
21
+ export declare function parseTuiArgs(args: string[]): ParsedTui;
22
+ export declare function runTui(argv: string[], io?: BootstrapIO): Promise<void>;
@@ -0,0 +1,116 @@
1
+ /**
2
+ * `pipiclaw tui` CLI: argument parsing and entry. Parsing is a pure function
3
+ * (`parseTuiArgs`) so it can be unit-tested; `runTui` wires it to `runTuiApp`.
4
+ */
5
+ import { BootstrapExitError, readCliVersion } from "../runtime/bootstrap.js";
6
+ import { parseSandboxArg, SandboxConfigError } from "../sandbox.js";
7
+ import { runTuiApp } from "./app.js";
8
+ /** Parse `pipiclaw tui` arguments (everything after the `tui` subcommand). */
9
+ export function parseTuiArgs(args) {
10
+ let channel;
11
+ let sandbox = { type: "host" };
12
+ let print = false;
13
+ let quiet = false;
14
+ let plain = false;
15
+ const positional = [];
16
+ for (let index = 0; index < args.length; index += 1) {
17
+ const arg = args[index];
18
+ if (arg === "--channel") {
19
+ channel = args[index + 1];
20
+ index += 1;
21
+ }
22
+ else if (arg.startsWith("--channel=")) {
23
+ channel = arg.slice("--channel=".length);
24
+ }
25
+ else if (arg === "--sandbox") {
26
+ sandbox = parseSandboxArg(args[index + 1] ?? "");
27
+ index += 1;
28
+ }
29
+ else if (arg.startsWith("--sandbox=")) {
30
+ sandbox = parseSandboxArg(arg.slice("--sandbox=".length));
31
+ }
32
+ else if (arg === "--print" || arg === "-p") {
33
+ print = true;
34
+ }
35
+ else if (arg === "--quiet" || arg === "-q") {
36
+ quiet = true;
37
+ }
38
+ else if (arg === "--plain") {
39
+ plain = true;
40
+ }
41
+ else if (arg === "--help" || arg === "-h") {
42
+ return { kind: "help" };
43
+ }
44
+ else if (arg === "--version") {
45
+ return { kind: "version" };
46
+ }
47
+ else {
48
+ positional.push(arg);
49
+ }
50
+ }
51
+ return { kind: "run", channel, sandbox, print, quiet, plain, positional };
52
+ }
53
+ function printTuiHelp(io) {
54
+ io.log("Usage: pipiclaw tui [options] [prompt]");
55
+ io.log("");
56
+ io.log("Chat with the pipiclaw agent in the terminal, reusing the same config,");
57
+ io.log("memory and session as the DingTalk runtime.");
58
+ io.log("");
59
+ io.log("Resume: there is no /resume command — a channel resumes itself.");
60
+ io.log("Re-running with the same --channel restores the previous conversation");
61
+ io.log("automatically (context is persisted per channel); memory carries longer-");
62
+ io.log("term facts across sessions. Use --channel to continue any past conversation.");
63
+ io.log("");
64
+ io.log("Options:");
65
+ io.log(" --channel <id> Channel to attach to (default: tui_local).");
66
+ io.log(" Use dm_<staffId> to share a DingTalk conversation's memory.");
67
+ io.log(" --sandbox=host Run tools on host (default)");
68
+ io.log(" --sandbox=docker:<name> Run tools in a Docker container");
69
+ io.log(" --print, -p One-shot: run [prompt] (or stdin), print the answer, exit");
70
+ io.log(" --quiet, -q Plain mode: print only the final answer");
71
+ io.log(" --plain Force the plain frontend (no full-screen UI)");
72
+ io.log(" --version Print the version and exit");
73
+ io.log("");
74
+ io.log("Note: do not attach --channel to a DingTalk conversation the daemon is actively serving.");
75
+ }
76
+ async function readStdin() {
77
+ const chunks = [];
78
+ for await (const chunk of process.stdin) {
79
+ chunks.push(chunk);
80
+ }
81
+ return Buffer.concat(chunks).toString("utf8");
82
+ }
83
+ export async function runTui(argv, io = console) {
84
+ let parsed;
85
+ try {
86
+ parsed = parseTuiArgs(argv.slice(3));
87
+ }
88
+ catch (err) {
89
+ if (err instanceof SandboxConfigError) {
90
+ io.error(`Error: ${err.message}`);
91
+ throw new BootstrapExitError(1);
92
+ }
93
+ throw err;
94
+ }
95
+ if (parsed.kind === "help") {
96
+ printTuiHelp(io);
97
+ return;
98
+ }
99
+ if (parsed.kind === "version") {
100
+ io.log(readCliVersion());
101
+ return;
102
+ }
103
+ let initialPrompt = parsed.positional.join(" ").trim() || undefined;
104
+ if (parsed.print && !initialPrompt && process.stdin.isTTY !== true) {
105
+ initialPrompt = (await readStdin()).trim() || undefined;
106
+ }
107
+ await runTuiApp({
108
+ sandbox: parsed.sandbox,
109
+ channel: parsed.channel,
110
+ print: parsed.print,
111
+ quiet: parsed.quiet,
112
+ plain: parsed.plain,
113
+ initialPrompt,
114
+ io,
115
+ });
116
+ }
@@ -0,0 +1,9 @@
1
+ export declare const bold: (text: string) => string;
2
+ export declare const dim: (text: string) => string;
3
+ export declare const italic: (text: string) => string;
4
+ export declare const underline: (text: string) => string;
5
+ export declare const strikethrough: (text: string) => string;
6
+ export declare const red: (text: string) => string;
7
+ export declare const yellow: (text: string) => string;
8
+ export declare const cyan: (text: string) => string;
9
+ export declare const gray: (text: string) => string;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Minimal ANSI color helpers for the TUI. pipiclaw has no chalk dependency, so
3
+ * these are hand-rolled SGR wrappers. Honors NO_COLOR (https://no-color.org) and
4
+ * a non-TTY stdout by degrading to identity functions.
5
+ */
6
+ const enabled = !process.env.NO_COLOR && process.stdout.isTTY === true;
7
+ function sgr(open, close = 0) {
8
+ if (!enabled)
9
+ return (text) => text;
10
+ return (text) => `\x1b[${open}m${text}\x1b[${close}m`;
11
+ }
12
+ export const bold = sgr(1, 22);
13
+ export const dim = sgr(2, 22);
14
+ export const italic = sgr(3, 23);
15
+ export const underline = sgr(4, 24);
16
+ export const strikethrough = sgr(9, 29);
17
+ export const red = sgr(31);
18
+ export const yellow = sgr(33);
19
+ export const cyan = sgr(36);
20
+ export const gray = sgr(90);