@oyasmi/pipiclaw 0.7.2 → 0.7.4

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.
package/README.md CHANGED
@@ -19,7 +19,7 @@ npm package: [`@oyasmi/pipiclaw`](https://www.npmjs.com/package/@oyasmi/pipiclaw
19
19
  - 支持终端 TUI:`pipiclaw tui` 直接在命令行对话,复用同一套配置、记忆与会话(见[配置手册](docs/configuration.md)的「终端 TUI」)
20
20
  - 支持 AI Card 过程展示,思考、工具执行和状态更新可以持续流式呈现
21
21
  - 支持 `/help`、`/new`、`/compact`、`/session`、`/model`
22
- - 忙碌时可继续接收 `/steer`、`/followup`、`/stop`、`/events`
22
+ - 忙碌时可继续接收 `/steer`、`/followup`、`/stop`、`/events`、`/status`、`/usage`
23
23
  - 按工作区 / 会话通道(workspace / channel)分层管理 `SOUL.md`、`AGENTS.md`、`SESSION.md`、`MEMORY.md`、`HISTORY.md`
24
24
  - 支持预定义子代理(sub-agent)和临时内联子代理(inline sub-agent)
25
25
  - 支持立即、单次、周期三类事件调度
@@ -53,8 +53,8 @@ Pipiclaw 当前已经内置一轮工具层安全增强:
53
53
  ```text
54
54
  请帮我在这台机器上安装并初始化 Pipiclaw,并尽量把它配置到“可以开始使用”的状态。按下面要求执行:
55
55
 
56
- 1. 先检查 Node.js 是否可用,版本必须 >= 22。
57
- - 如果未安装,或版本低于 22,不要继续安装 Pipiclaw,直接告诉我需要先安装或切换到 Node.js 22+。
56
+ 1. 先检查 Node.js 是否可用,版本必须 >= 22.19.0。
57
+ - 如果未安装,或版本低于 22.19.0,不要继续安装 Pipiclaw,直接告诉我需要先安装或切换到 Node.js 22.19.0+。
58
58
 
59
59
  2. 安装 Pipiclaw:
60
60
  - 优先执行:npm install -g @oyasmi/pipiclaw
@@ -127,20 +127,13 @@ Pipiclaw 当前已经内置一轮工具层安全增强:
127
127
 
128
128
  #### 1. 环境要求(Requirements)
129
129
 
130
- - Node.js `>= 22`
130
+ - Node.js `>= 22.19.0`
131
131
  - 一个可用的钉钉企业内部应用
132
132
  - 至少一种可用的模型接入方式
133
133
  - 直接使用 Anthropic 默认模型
134
134
  - 或在 `models.json` 中配置自定义模型提供方(provider)
135
135
 
136
- Windows 补充说明:
137
-
138
- - Pipiclaw 的工具执行层默认按 POSIX shell 语义工作
139
- - 推荐在 Windows 上使用 WSL2 安装和运行 Pipiclaw
140
- - 不推荐直接在 Windows host 模式下配合 Git Bash 使用;这种方式在工具调用中更容易遇到兼容性问题,尤其是 skills 依赖的外部工具
141
- - 仅在无法使用 WSL2 时,再考虑安装 Git Bash,并确保 `bash` 可在 PATH 中找到
142
- - 如果 Windows host 模式下 `bash` 不在 PATH 中,可以设置 `PIPICLAW_SHELL` 指向具体可执行文件,例如 `C:\Program Files\Git\bin\bash.exe`
143
- - 如果你不想依赖本机 shell 环境,推荐直接使用 Docker sandbox
136
+ Pipiclaw 面向类 Unix 环境(Linux / macOS),不支持 Windows。工具执行层按 POSIX shell 语义工作;如需在 Windows 上运行,请使用 WSL2。
144
137
 
145
138
  #### 2. 安装(Install)
146
139
 
@@ -184,12 +177,6 @@ export PIPICLAW_HOME=/your/custom/pipiclaw-home
184
177
 
185
178
  设置后,`channel.json`、`auth.json`、`models.json`、`settings.json`、`tools.json`、`security.json` 和整个 `workspace/` 都会改为从这个目录读取和写入。
186
179
 
187
- 如果你无法使用 WSL2,选择在 Windows host 模式下配合 Git Bash 运行,并且 `bash` 不在 PATH 中,也可以一并设置:
188
-
189
- ```powershell
190
- $env:PIPICLAW_SHELL = "C:\Program Files\Git\bin\bash.exe"
191
- ```
192
-
193
180
  如果 `channel.json` 仍然是初始化模板,程序会提示你补全配置后再启动。这是正常行为。
194
181
 
195
182
  #### 4. 创建钉钉应用(Create a DingTalk App)
@@ -446,7 +433,6 @@ pipiclaw
446
433
  |----------|------|
447
434
  | `ANTHROPIC_API_KEY` | Anthropic API Key |
448
435
  | `PIPICLAW_HOME` | 覆盖默认的 `~/.pi/pipiclaw/` 根目录 |
449
- | `PIPICLAW_SHELL` | Windows host 模式下指定 POSIX shell,例如 Git Bash 的 `bash.exe` |
450
436
  | `PIPICLAW_DEBUG` | 调试模式,会把上下文写到 `last_prompt.json` |
451
437
  | `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` / `NO_PROXY` | 标准代理环境变量;DingTalk runtime 和 web 工具都会尊重它们 |
452
438
 
@@ -468,6 +454,8 @@ Pipiclaw 有两层命令。
468
454
  | `/events show <name>` | 查看指定事件文件的完整 JSON |
469
455
  | `/events delete <name>` | 删除指定事件文件 |
470
456
  | `/events history [name]` | 查看事件调度历史,可按事件名过滤 |
457
+ | `/status` | 查看运行时状态:执行状态、当前模型、上下文用量、运行时长、版本 |
458
+ | `/usage [7d\|month]` | 查看本通道与全局的 LLM 成本,按类型和 Top 模型拆分 |
471
459
 
472
460
  忙碌时,普通消息默认等价于 `/steer <message>`。
473
461
 
@@ -105,19 +105,25 @@ export async function runPromptWithFallback(promptText, deps) {
105
105
  if (fromRef === toRef) {
106
106
  return false;
107
107
  }
108
- // Surgery only when the failed turn was actually enqueued. A pre-flight throw
109
- // (no API key on the primary) submits nothing, so there is nothing to remove —
110
- // switch straight to the backup, which covers a mis-configured primary key.
108
+ // Pre-compute the truncated transcript, but do not commit it until setModel
109
+ // succeeds. Surgery only when the failed turn was actually enqueued: a pre-flight
110
+ // throw (no API key on the primary) submits nothing, so there is nothing to
111
+ // remove — switch straight to the backup, which covers a mis-configured primary key.
112
+ let truncated = null;
111
113
  if (deps.promptWasSubmitted()) {
112
- const truncated = takeFailedTurn(deps.getMessages());
114
+ truncated = takeFailedTurn(deps.getMessages());
113
115
  if (!truncated) {
114
116
  log.logWarning("[fallback] transcript tail is not [user, assistant(error)]; skipping fallback to avoid corrupting context");
115
117
  return false;
116
118
  }
117
- deps.setMessages(truncated);
118
119
  }
120
+ // Switch the model first: if setModel throws it propagates with the transcript
121
+ // still intact, so the failed turn's context is not silently lost.
119
122
  deps.markPrimaryFailed();
120
123
  await deps.setModel(candidate);
124
+ if (truncated) {
125
+ deps.setMessages(truncated);
126
+ }
121
127
  deps.notifySwitch(fromRef, toRef, summarizeFallbackError(firstError.errorMessage));
122
128
  deps.resetRunError();
123
129
  await deps.prompt(promptText);
@@ -65,12 +65,11 @@ export function isTurnEndEvent(value) {
65
65
  return hasEventType(value, "turn_end") && "message" in value && Array.isArray(value.toolResults);
66
66
  }
67
67
  export function isAutoCompactionStartEvent(value) {
68
- return ((hasEventType(value, "auto_compaction_start") && (value.reason === "threshold" || value.reason === "overflow")) ||
69
- (hasEventType(value, "compaction_start") &&
70
- (value.reason === "threshold" || value.reason === "overflow" || value.reason === "manual")));
68
+ return (hasEventType(value, "compaction_start") &&
69
+ (value.reason === "threshold" || value.reason === "overflow" || value.reason === "manual"));
71
70
  }
72
71
  export function isAutoCompactionEndEvent(value) {
73
- return hasEventType(value, "auto_compaction_end") || hasEventType(value, "compaction_end");
72
+ return hasEventType(value, "compaction_end");
74
73
  }
75
74
  export function isAutoRetryStartEvent(value) {
76
75
  return (hasEventType(value, "auto_retry_start") &&
@@ -131,14 +131,11 @@ export type SessionEvent = {
131
131
  type: "turn_end";
132
132
  message: unknown;
133
133
  toolResults: unknown[];
134
- } | {
135
- type: "auto_compaction_start";
136
- reason: "threshold" | "overflow";
137
134
  } | {
138
135
  type: "compaction_start";
139
136
  reason: "manual" | "threshold" | "overflow";
140
137
  } | {
141
- type: "auto_compaction_end" | "compaction_end";
138
+ type: "compaction_end";
142
139
  reason?: "manual" | "threshold" | "overflow";
143
140
  result?: {
144
141
  tokensBefore: number;
@@ -172,10 +169,10 @@ export type TurnEndEvent = Extract<SessionEvent, {
172
169
  type: "turn_end";
173
170
  }>;
174
171
  export type AutoCompactionStartEvent = Extract<SessionEvent, {
175
- type: "auto_compaction_start" | "compaction_start";
172
+ type: "compaction_start";
176
173
  }>;
177
174
  export type AutoCompactionEndEvent = Extract<SessionEvent, {
178
- type: "auto_compaction_end" | "compaction_end";
175
+ type: "compaction_end";
179
176
  }>;
180
177
  export type AutoRetryStartEvent = Extract<SessionEvent, {
181
178
  type: "auto_retry_start";
package/dist/index.d.ts CHANGED
@@ -24,6 +24,6 @@ export { type PipiclawMemoryGrowthSettings, type PipiclawMemoryMaintenanceSettin
24
24
  export { discoverSubAgents, formatSubAgentList, getSubAgentsDir, type ResolvedSubAgentConfig, resolveSubAgentConfig, type SubAgentConfig, type SubAgentContextMode, type SubAgentDiscoveryResult, type SubAgentInvocationOverrides, type SubAgentMemoryMode, type SubAgentToolName, } from "./subagents/discovery.js";
25
25
  export { createSubAgentTool, type SubAgentToolDetails, type SubAgentToolOptions, } from "./subagents/tool.js";
26
26
  export { DEFAULT_TOOLS_CONFIG, getToolsConfigPath, loadToolsConfig, type PipiclawToolsConfig, type PipiclawWebFetchConfig, type PipiclawWebSearchConfig, type PipiclawWebToolsConfig, } from "./tools/config.js";
27
- export { type CreatePipiclawToolsOptions, createPipiclawBaseTools, createPipiclawTools, } from "./tools/index.js";
27
+ export { type CreatePipiclawToolsOptions, createPipiclawTools, } from "./tools/index.js";
28
28
  export { createUsageLedger, getUsageLedger, type UsageKind, type UsageLedger, type UsageLedgerEntry, type UsageSummary, } from "./usage/ledger.js";
29
29
  export { parseUsageMode, renderUsageReport, type UsageQueryMode, usageWindows } from "./usage/render.js";
package/dist/index.js CHANGED
@@ -23,6 +23,6 @@ export { PipiclawSettingsManager, } from "./settings.js";
23
23
  export { discoverSubAgents, formatSubAgentList, getSubAgentsDir, resolveSubAgentConfig, } from "./subagents/discovery.js";
24
24
  export { createSubAgentTool, } from "./subagents/tool.js";
25
25
  export { DEFAULT_TOOLS_CONFIG, getToolsConfigPath, loadToolsConfig, } from "./tools/config.js";
26
- export { createPipiclawBaseTools, createPipiclawTools, } from "./tools/index.js";
26
+ export { createPipiclawTools, } from "./tools/index.js";
27
27
  export { createUsageLedger, getUsageLedger, } from "./usage/ledger.js";
28
28
  export { parseUsageMode, renderUsageReport, usageWindows } from "./usage/render.js";
@@ -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
  }
@@ -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) {
@@ -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;
@@ -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;
@@ -49,6 +49,7 @@ export interface SubAgentToolOptions {
49
49
  memoryCandidateStore?: MemoryCandidateStore;
50
50
  securityConfig?: SecurityConfig;
51
51
  webConfig?: PipiclawWebToolsConfig;
52
+ rtkEnabled?: boolean;
52
53
  runtimeContext: {
53
54
  workspacePath: string;
54
55
  channelId: string;
@@ -103,6 +103,7 @@ function buildSubagentTools(executor, bashTimeoutSec, options) {
103
103
  workspaceDir: options.workspaceDir,
104
104
  workspacePath: options.runtimeContext.workspacePath,
105
105
  webConfig: options.webConfig,
106
+ rtkEnabled: options.rtkEnabled,
106
107
  bashDefaultTimeoutSeconds: bashTimeoutSec,
107
108
  }, { forSubagent: true });
108
109
  }
@@ -19,6 +19,12 @@ export interface BashToolOptions {
19
19
  securityConfig?: SecurityConfig;
20
20
  securityContext?: SecurityRuntimeContext;
21
21
  channelId?: string;
22
+ /**
23
+ * When true, route each command through the `rtk` command optimizer before executing
24
+ * (best-effort; falls back to the raw command when rtk is unavailable or declines).
25
+ * Gated by `tools.rtk.enabled` in tools.json.
26
+ */
27
+ rtkEnabled?: boolean;
22
28
  }
23
29
  export declare function createBashTool(executor: Executor, options?: BashToolOptions): AgentTool<typeof bashSchema>;
24
30
  export {};
@@ -4,6 +4,7 @@ import { guardCommand } from "../security/command-guard.js";
4
4
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
5
5
  import { logSecurityEvent } from "../security/logger.js";
6
6
  import { shellEscape } from "../shared/shell-escape.js";
7
+ import { maybeOptimizeCommand } from "./command-optimizer.js";
7
8
  import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail } from "./truncate.js";
8
9
  /**
9
10
  * Default wall-clock timeout for bash commands when the caller supplies neither a
@@ -72,8 +73,12 @@ export function createBashTool(executor, options = {}) {
72
73
  throw new Error(formatCommandBlockMessage(command, guardResult.category, guardResult.reason, guardResult.matchedText));
73
74
  }
74
75
  }
76
+ // Optimize *after* the security guard: the guard must inspect the operator's real
77
+ // intent (`command`), while rtk only reshapes a semantically-equivalent command for
78
+ // compact output. Optimizing first would hide the true command from the guard.
79
+ const effectiveCommand = options.rtkEnabled ? await maybeOptimizeCommand(command, executor, signal) : command;
75
80
  const effectiveTimeout = timeout ?? options.defaultTimeoutSeconds ?? DEFAULT_BASH_TIMEOUT_SECONDS;
76
- const result = await executor.exec(command, { timeout: effectiveTimeout, signal });
81
+ const result = await executor.exec(effectiveCommand, { timeout: effectiveTimeout, signal });
77
82
  let output = "";
78
83
  if (result.stdout)
79
84
  output += result.stdout;
@@ -0,0 +1,6 @@
1
+ import type { Executor } from "../sandbox.js";
2
+ /**
3
+ * Return the rtk-optimized form of `command`, or `command` unchanged when rtk is
4
+ * unavailable or declines to rewrite it. Never throws.
5
+ */
6
+ export declare function maybeOptimizeCommand(command: string, executor: Executor, signal?: AbortSignal): Promise<string>;
@@ -0,0 +1,73 @@
1
+ import { shellEscape } from "../shared/shell-escape.js";
2
+ /**
3
+ * Optional "outbound command transform" for the bash tool. When enabled, a command is
4
+ * handed to the `rtk` binary (https://github.com/rtk-ai/rtk) which rewrites known
5
+ * read-only commands to their token-compact equivalents (e.g. `git status` →
6
+ * `rtk git status`) before execution, cutting the output the model has to read.
7
+ *
8
+ * pipiclaw owns none of rtk's rules: `rtk rewrite` is rtk's single source of truth for
9
+ * hooks. It prints the rewritten command on stdout when it can optimize, and prints
10
+ * nothing when it cannot. We key off stdout, not the exit code: the exit code is not a
11
+ * reliable success signal across rtk versions — 0.43.0 exits 3 on a successful rewrite
12
+ * and 1 on "no equivalent", while its own `--help` claims 0/1. Presence of stdout is the
13
+ * stable contract, so a non-empty line is the rewrite and empty means "keep original".
14
+ *
15
+ * This is best-effort by contract: any failure (rtk absent, timeout, empty output) falls
16
+ * back to the original command. Enabling rtk must never make a bash command fail.
17
+ */
18
+ /**
19
+ * rtk rewrite is a pure, local string transform (no network), so a tight bound is safe.
20
+ * On timeout we simply run the original command.
21
+ */
22
+ const RTK_TIMEOUT_SECONDS = 2;
23
+ /**
24
+ * rtk must exist in the *execution environment* — the host PATH for a host executor, or
25
+ * inside the container for a docker executor — not merely on the pipiclaw host. We probe
26
+ * through the executor so the check reflects where the command will actually run, and
27
+ * memoize the probe promise per executor instance so concurrent turns share one probe and
28
+ * we do not re-shell on every command. The instance is stable for a channel's lifetime,
29
+ * so this is effectively "probe once".
30
+ */
31
+ const availabilityByExecutor = new WeakMap();
32
+ function probeRtk(executor) {
33
+ return executor
34
+ .exec("command -v rtk", { timeout: RTK_TIMEOUT_SECONDS })
35
+ .then((result) => result.code === 0 && result.stdout.trim().length > 0)
36
+ .catch(() => false);
37
+ }
38
+ function isRtkAvailable(executor) {
39
+ let probe = availabilityByExecutor.get(executor);
40
+ if (!probe) {
41
+ probe = probeRtk(executor);
42
+ availabilityByExecutor.set(executor, probe);
43
+ }
44
+ return probe;
45
+ }
46
+ /**
47
+ * Return the rtk-optimized form of `command`, or `command` unchanged when rtk is
48
+ * unavailable or declines to rewrite it. Never throws.
49
+ */
50
+ export async function maybeOptimizeCommand(command, executor, signal) {
51
+ if (signal?.aborted) {
52
+ return command;
53
+ }
54
+ if (!(await isRtkAvailable(executor))) {
55
+ return command;
56
+ }
57
+ try {
58
+ const result = await executor.exec(`rtk rewrite ${shellEscape(command)}`, {
59
+ timeout: RTK_TIMEOUT_SECONDS,
60
+ signal,
61
+ });
62
+ // Trust stdout over the exit code (see the module comment): a non-empty line is the
63
+ // rewrite; empty output means rtk had no equivalent, so keep the original command.
64
+ const rewritten = result.stdout.trim();
65
+ if (rewritten.length > 0) {
66
+ return rewritten;
67
+ }
68
+ }
69
+ catch {
70
+ // Any failure — spawn error, timeout, abort — falls back to the original command.
71
+ }
72
+ return command;
73
+ }
@@ -38,6 +38,9 @@ export interface PipiclawToolsConfig {
38
38
  enabled: boolean;
39
39
  };
40
40
  };
41
+ rtk: {
42
+ enabled: boolean;
43
+ };
41
44
  };
42
45
  }
43
46
  export interface LoadedToolsConfig {
@@ -38,6 +38,9 @@ export const DEFAULT_TOOLS_CONFIG = {
38
38
  enabled: true,
39
39
  },
40
40
  },
41
+ rtk: {
42
+ enabled: false,
43
+ },
41
44
  },
42
45
  };
43
46
  function clampInteger(value, fallback, minimum, maximum) {
@@ -86,6 +89,7 @@ function mergeToolsConfig(source, configPath, diagnostics) {
86
89
  const memorySave = isRecord(memory.save) ? memory.save : {};
87
90
  const skills = isRecord(tools.skills) ? tools.skills : {};
88
91
  const manage = isRecord(skills.manage) ? skills.manage : {};
92
+ const rtk = isRecord(tools.rtk) ? tools.rtk : {};
89
93
  const search = isRecord(web.search) ? web.search : {};
90
94
  const fetch = isRecord(web.fetch) ? web.fetch : {};
91
95
  const providerValue = asTrimmedString(search.provider, DEFAULT_TOOLS_CONFIG.tools.web.search.provider).toLowerCase();
@@ -169,6 +173,9 @@ function mergeToolsConfig(source, configPath, diagnostics) {
169
173
  : DEFAULT_TOOLS_CONFIG.tools.skills.manage.enabled,
170
174
  },
171
175
  },
176
+ rtk: {
177
+ enabled: typeof rtk.enabled === "boolean" ? rtk.enabled : DEFAULT_TOOLS_CONFIG.tools.rtk.enabled,
178
+ },
172
179
  },
173
180
  };
174
181
  }
@@ -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);
@@ -45,6 +25,7 @@ export function createPipiclawTools(options) {
45
25
  workspacePath: options.workspacePath,
46
26
  webConfig: toolsConfig.tools.web,
47
27
  toolsConfig,
28
+ rtkEnabled: toolsConfig.tools.rtk.enabled,
48
29
  getCurrentModel: options.getCurrentModel,
49
30
  getAvailableModels: options.getAvailableModels,
50
31
  resolveApiKey: options.resolveApiKey,
@@ -65,6 +46,7 @@ export function createPipiclawTools(options) {
65
46
  memoryCandidateStore: options.memoryCandidateStore,
66
47
  securityConfig,
67
48
  webConfig: toolsConfig.tools.web,
49
+ rtkEnabled: toolsConfig.tools.rtk.enabled,
68
50
  runtimeContext: {
69
51
  workspacePath: options.workspacePath,
70
52
  channelId: options.channelId,
@@ -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
  }),
@@ -28,6 +28,8 @@ export interface ToolBuildContext {
28
28
  toolsConfig?: PipiclawToolsConfig;
29
29
  /** Sub-agent set passes its per-invocation bash timeout; the main set relies on the built-in default. */
30
30
  bashDefaultTimeoutSeconds?: number;
31
+ /** Gates the bash tool's rtk command optimizer (`tools.rtk.enabled`). Threaded to both sets. */
32
+ rtkEnabled?: boolean;
31
33
  getCurrentModel?: () => Model<Api>;
32
34
  getAvailableModels?: () => Model<Api>[];
33
35
  resolveApiKey?: (model: Model<Api>) => Promise<string>;
@@ -44,6 +44,7 @@ export const TOOL_REGISTRY = [
44
44
  availableToSubagents: true,
45
45
  create: (ctx) => createBashTool(ctx.executor, {
46
46
  ...fileToolOptions(ctx),
47
+ rtkEnabled: ctx.rtkEnabled === true,
47
48
  ...(ctx.bashDefaultTimeoutSeconds !== undefined
48
49
  ? { defaultTimeoutSeconds: ctx.bashDefaultTimeoutSeconds }
49
50
  : {}),
@@ -6,7 +6,10 @@ import { PlainFrontend } from "./plain-frontend.js";
6
6
  */
7
7
  export function createFrontend(options = {}) {
8
8
  const isTty = process.stdout.isTTY === true && process.stdin.isTTY === true;
9
- if (options.plain || !isTty) {
9
+ // `--print`/one-shot (interactive === false) must use the plain stream even on a
10
+ // TTY, or the answer is trapped in a full-screen pi-tui frame and never reaches a
11
+ // clean stdout.
12
+ if (options.plain || !isTty || options.interactive === false) {
10
13
  return new PlainFrontend({ quiet: options.quiet, interactive: options.interactive });
11
14
  }
12
15
  return new PiTuiFrontend({ commands: options.commands, basePath: options.basePath });
@@ -158,7 +158,13 @@ export class TurnController {
158
158
  this.updateStatus();
159
159
  }
160
160
  })();
161
- void this.currentTurn.then(() => this.drainFollowups());
161
+ // The turn is over whether it settled or its finally threw (e.g. a frontend
162
+ // method failing); drain either way and never leak an unhandled rejection.
163
+ void this.currentTurn.then(() => this.drainFollowups(), (err) => {
164
+ log.logWarning(`[${this.deps.channelId}] TUI turn finalizer failed`, errorMessage(err));
165
+ this.running = false;
166
+ this.drainFollowups();
167
+ });
162
168
  }
163
169
  drainFollowups() {
164
170
  if (this.exiting || this.running)
@@ -207,7 +213,13 @@ export class TurnController {
207
213
  this.deps.frontend.showNotice("Press Ctrl-C again to exit.");
208
214
  }
209
215
  requestExit() {
210
- void this.shutdown();
216
+ // shutdown() restores the terminal in a finally, so a rejection here means only
217
+ // the memory-flush bookkeeping failed — log it rather than leak an unhandled
218
+ // rejection that could abort the process before exitResolve runs.
219
+ this.shutdown().catch((err) => {
220
+ log.logWarning(`[${this.deps.channelId}] TUI shutdown failed`, errorMessage(err));
221
+ this.exitResolve();
222
+ });
211
223
  }
212
224
  buildWelcome() {
213
225
  let model = "";
@@ -244,23 +256,31 @@ export class TurnController {
244
256
  this.exiting = true;
245
257
  if (this.running) {
246
258
  await this.deps.runner.abort().catch(() => { });
259
+ // Never let a rejected turn (e.g. ctx.close() throwing in the turn's finally)
260
+ // escape the race — that would skip frontend.stop() and strand the terminal in
261
+ // raw mode. The turn already logs its own failures.
247
262
  await Promise.race([
248
- this.currentTurn,
263
+ this.currentTurn.catch(() => { }),
249
264
  new Promise((resolve) => setTimeout(resolve, SHUTDOWN_ABORT_WAIT_MS)),
250
265
  ]);
251
266
  }
252
- // Tear the UI down first so the terminal is restored immediately — the
253
- // memory flush below can take a moment (LLM consolidation), and a frozen
254
- // full-screen frame feels like a hang. A short note on stderr explains the
255
- // pause without polluting stdout (which carries the answer in --print).
256
- this.deps.frontend.stop();
257
- process.stderr.write("Saving session memory…\n");
258
- await Promise.race([
259
- this.deps.runner.flushMemoryForShutdown().catch((err) => {
260
- log.logWarning(`[${this.deps.channelId}] Failed to flush memory on exit`, errorMessage(err));
261
- }),
262
- new Promise((resolve) => setTimeout(resolve, SHUTDOWN_FLUSH_WAIT_MS)),
263
- ]);
264
- this.exitResolve();
267
+ try {
268
+ // Tear the UI down first so the terminal is restored immediately — the
269
+ // memory flush below can take a moment (LLM consolidation), and a frozen
270
+ // full-screen frame feels like a hang. A short note on stderr explains the
271
+ // pause without polluting stdout (which carries the answer in --print).
272
+ // Guaranteed via finally: a flush failure must not leave the terminal raw.
273
+ this.deps.frontend.stop();
274
+ process.stderr.write("Saving session memory…\n");
275
+ await Promise.race([
276
+ this.deps.runner.flushMemoryForShutdown().catch((err) => {
277
+ log.logWarning(`[${this.deps.channelId}] Failed to flush memory on exit`, errorMessage(err));
278
+ }),
279
+ new Promise((resolve) => setTimeout(resolve, SHUTDOWN_FLUSH_WAIT_MS)),
280
+ ]);
281
+ }
282
+ finally {
283
+ this.exitResolve();
284
+ }
265
285
  }
266
286
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oyasmi/pipiclaw",
3
- "version": "0.7.2",
3
+ "version": "0.7.4",
4
4
  "description": "An AI assistant runtime for coding and team workflows, with DingTalk AI Cards, sub-agents, memory, and scheduled events.",
5
5
  "type": "module",
6
6
  "bin": {