@oyasmi/pipiclaw 0.7.2 → 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.
- package/README.md +7 -19
- package/dist/agent/model-fallback.js +11 -5
- package/dist/agent/type-guards.js +3 -4
- package/dist/agent/types.d.ts +3 -6
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/memory/candidates.js +5 -17
- package/dist/memory/consolidation.js +1 -6
- package/dist/memory/files.d.ts +1 -0
- package/dist/memory/files.js +0 -0
- package/dist/memory/maintenance-jobs.js +1 -0
- package/dist/memory/session-corpus.js +3 -16
- package/dist/runtime/dingtalk.js +1 -1
- package/dist/runtime/event-commands.js +1 -3
- package/dist/runtime/events.js +1 -3
- package/dist/runtime/store.d.ts +1 -7
- package/dist/runtime/store.js +6 -80
- package/dist/shared/fs-utils.d.ts +8 -0
- package/dist/shared/fs-utils.js +21 -0
- package/dist/shared/text-utils.d.ts +2 -0
- package/dist/shared/text-utils.js +4 -0
- package/dist/tools/index.d.ts +1 -7
- package/dist/tools/index.js +0 -20
- package/dist/tools/memory-save.d.ts +0 -1
- package/dist/tools/memory-save.js +0 -1
- package/dist/tui/renderer.js +4 -1
- package/dist/tui/turn-controller.js +36 -16
- package/package.json +1 -1
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
|
-
//
|
|
109
|
-
//
|
|
110
|
-
//
|
|
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
|
-
|
|
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 (
|
|
69
|
-
(
|
|
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, "
|
|
72
|
+
return hasEventType(value, "compaction_end");
|
|
74
73
|
}
|
|
75
74
|
export function isAutoRetryStartEvent(value) {
|
|
76
75
|
return (hasEventType(value, "auto_retry_start") &&
|
package/dist/agent/types.d.ts
CHANGED
|
@@ -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: "
|
|
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: "
|
|
172
|
+
type: "compaction_start";
|
|
176
173
|
}>;
|
|
177
174
|
export type AutoCompactionEndEvent = Extract<SessionEvent, {
|
|
178
|
-
type: "
|
|
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,
|
|
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 {
|
|
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 {
|
|
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
|
-
|
|
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" ?
|
|
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() : "",
|
package/dist/memory/files.d.ts
CHANGED
|
@@ -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;
|
package/dist/memory/files.js
CHANGED
|
Binary file
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { readdir,
|
|
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
|
|
170
|
+
const content = await readOptionalTextFile(path);
|
|
184
171
|
if (!content.trim()) {
|
|
185
172
|
return [];
|
|
186
173
|
}
|
package/dist/runtime/dingtalk.js
CHANGED
|
@@ -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>\`,
|
|
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;
|
package/dist/runtime/events.js
CHANGED
|
@@ -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
|
package/dist/runtime/store.d.ts
CHANGED
|
@@ -46,7 +46,7 @@ export declare class ChannelStore {
|
|
|
46
46
|
private workingDir;
|
|
47
47
|
private recentlyLogged;
|
|
48
48
|
private cleanupTimer;
|
|
49
|
-
private
|
|
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
|
}
|
package/dist/runtime/store.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import {
|
|
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 {
|
|
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.
|
|
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.
|
|
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.
|
|
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;
|
package/dist/tools/index.d.ts
CHANGED
|
@@ -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
|
|
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>[];
|
package/dist/tools/index.js
CHANGED
|
@@ -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
|
}),
|
package/dist/tui/renderer.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
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