@oyasmi/pipiclaw 0.6.9 → 0.6.10-beta.1
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 +28 -5
- package/dist/agent/index.d.ts +0 -1
- package/dist/agent/index.js +0 -1
- package/dist/agent/progress-formatter.js +1 -1
- package/dist/agent/runner-factory.d.ts +0 -1
- package/dist/agent/runner-factory.js +0 -3
- package/dist/log.d.ts +0 -2
- package/dist/log.js +0 -8
- package/dist/memory/lifecycle.d.ts +3 -0
- package/dist/memory/lifecycle.js +26 -4
- package/dist/memory/maintenance-state.d.ts +0 -1
- package/dist/memory/maintenance-state.js +0 -6
- package/dist/paths.d.ts +3 -0
- package/dist/paths.js +3 -0
- package/dist/runtime/bootstrap.d.ts +2 -1
- package/dist/runtime/bootstrap.js +4 -3
- package/dist/runtime/events.d.ts +37 -2
- package/dist/runtime/events.js +193 -10
- package/dist/web/config.d.ts +1 -2
- package/dist/web/config.js +0 -3
- package/package.json +4 -2
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Pipiclaw
|
|
2
2
|
|
|
3
|
-
Pipiclaw 是一个 AI 助手运行时(AI assistant runtime),以 [`pi-coding-agent`](https://www.npmjs.com/package/@
|
|
3
|
+
Pipiclaw 是一个 AI 助手运行时(AI assistant runtime),以 [`pi-coding-agent`](https://www.npmjs.com/package/@earendil-works/pi-coding-agent) 为核心,补齐了作为工作助手长期使用时最需要的几层能力:钉钉接入、AI Card 过程展示、子代理、分层记忆、定时事件,以及按会话通道持久化的工作区(workspace)。
|
|
4
4
|
|
|
5
5
|
如果你希望 AI 助手不只是聊天,而是能在钉钉里持续工作、保留上下文、执行任务,并且实时告知你它正在做什么,那么 Pipiclaw 就是你需要的。
|
|
6
6
|
|
|
@@ -24,6 +24,8 @@ npm package: [`@oyasmi/pipiclaw`](https://www.npmjs.com/package/@oyasmi/pipiclaw
|
|
|
24
24
|
- 支持立即、单次、周期三类事件调度
|
|
25
25
|
- 支持自定义模型提供方(provider)和模型(model)配置
|
|
26
26
|
- 内建 `web_search` / `web_fetch`,支持联网搜索与网页抓取
|
|
27
|
+
- 内建 `session_search`,可按需检索当前会话通道的冷存储历史
|
|
28
|
+
- 内建 workspace skill 管理工具,可查看、创建和维护 `workspace/skills/`
|
|
27
29
|
- 内置工具层安全防护:`bash` 命令守卫、文件路径守卫、敏感路径拒绝、阻断审计日志
|
|
28
30
|
|
|
29
31
|
## 安全说明(Security)
|
|
@@ -162,6 +164,7 @@ pipiclaw
|
|
|
162
164
|
├── models.json
|
|
163
165
|
├── settings.json
|
|
164
166
|
├── tools.json
|
|
167
|
+
├── security.json
|
|
165
168
|
└── workspace/
|
|
166
169
|
├── SOUL.md
|
|
167
170
|
├── AGENTS.md
|
|
@@ -178,7 +181,7 @@ pipiclaw
|
|
|
178
181
|
export PIPICLAW_HOME=/your/custom/pipiclaw-home
|
|
179
182
|
```
|
|
180
183
|
|
|
181
|
-
设置后,`channel.json`、`auth.json`、`models.json`、`settings.json`、`tools.json` 和整个 `workspace/` 都会改为从这个目录读取和写入。
|
|
184
|
+
设置后,`channel.json`、`auth.json`、`models.json`、`settings.json`、`tools.json`、`security.json` 和整个 `workspace/` 都会改为从这个目录读取和写入。
|
|
182
185
|
|
|
183
186
|
如果你无法使用 WSL2,选择在 Windows host 模式下配合 Git Bash 运行,并且 `bash` 不在 PATH 中,也可以一并设置:
|
|
184
187
|
|
|
@@ -210,7 +213,8 @@ $env:PIPICLAW_SHELL = "C:\Program Files\Git\bin\bash.exe"
|
|
|
210
213
|
"cardTemplateKey": "content",
|
|
211
214
|
"allowFrom": [],
|
|
212
215
|
"busyMessageDefault": "steer",
|
|
213
|
-
"responseMode": "full_progress_then_plain_final"
|
|
216
|
+
"responseMode": "full_progress_then_plain_final",
|
|
217
|
+
"cardAutoLayout": true
|
|
214
218
|
}
|
|
215
219
|
```
|
|
216
220
|
|
|
@@ -233,6 +237,8 @@ $env:PIPICLAW_SHELL = "C:\Program Files\Git\bin\bash.exe"
|
|
|
233
237
|
设为 `"steer"`(默认)或 `"followUp"` / `"followup"`。控制 Agent 忙碌时普通消息的默认处理方式;答疑机器人场景建议设为 `"followUp"`。
|
|
234
238
|
- `responseMode`
|
|
235
239
|
设为 `"full_progress_then_plain_final"`(默认)、`"rolling_progress_then_plain_final"` 或 `"final_card_only"`。统一控制过程展示与最终投递:`rolling` 执行中只显示最近 3 条进展并在完成后收起为一行摘要;`final_card_only` 不展示过程,最终答案直接写入 AI Card。
|
|
240
|
+
- `cardAutoLayout`
|
|
241
|
+
默认为 `true`,透传给钉钉 AI Card 模板的 `autoLayout` 渲染开关。
|
|
236
242
|
|
|
237
243
|
推荐把 AI Card 一起配上,这样在钉钉里能直接看到过程更新。只有在排查接入链路时,才建议临时把 `cardTemplateId` 留空。
|
|
238
244
|
|
|
@@ -344,7 +350,7 @@ pipiclaw
|
|
|
344
350
|
|
|
345
351
|
如果你希望助手直接使用 `web_search` / `web_fetch`,可以编辑 `~/.pi/pipiclaw/tools.json`。
|
|
346
352
|
|
|
347
|
-
第一次启动时,Pipiclaw
|
|
353
|
+
第一次启动时,Pipiclaw 会自动生成一份默认关闭 web 工具、默认启用 `session_search` 和 workspace skill 管理工具的 `tools.json` 模板。它已经带了 Brave 的示例配置,以及可选代理示例,方便你直接改成可用状态:
|
|
348
354
|
|
|
349
355
|
```json
|
|
350
356
|
{
|
|
@@ -354,7 +360,18 @@ pipiclaw
|
|
|
354
360
|
"proxy": null,
|
|
355
361
|
"search": {
|
|
356
362
|
"provider": "brave",
|
|
357
|
-
"apiKey": ""
|
|
363
|
+
"apiKey": "",
|
|
364
|
+
"maxResults": 5
|
|
365
|
+
}
|
|
366
|
+
},
|
|
367
|
+
"memory": {
|
|
368
|
+
"sessionSearch": {
|
|
369
|
+
"enabled": true
|
|
370
|
+
}
|
|
371
|
+
},
|
|
372
|
+
"skills": {
|
|
373
|
+
"manage": {
|
|
374
|
+
"enabled": true
|
|
358
375
|
}
|
|
359
376
|
}
|
|
360
377
|
},
|
|
@@ -373,6 +390,8 @@ pipiclaw
|
|
|
373
390
|
|
|
374
391
|
未设置 `tools.web.proxy` 时,web 工具会回退到标准环境变量:`HTTP_PROXY`、`HTTPS_PROXY`、`ALL_PROXY`、`NO_PROXY`。DingTalk runtime 也会尊重同一套环境变量。
|
|
375
392
|
|
|
393
|
+
`session_search` 只检索当前会话通道的 `context.jsonl`、session JSONL、`log.jsonl` 和轮转日志;它不会跨 channel 搜索。workspace skill 管理工具只作用于 `workspace/skills/`,可通过 `tools.skills.manage.enabled: false` 关闭。
|
|
394
|
+
|
|
376
395
|
#### 10. 在钉钉中验证(Verify in DingTalk)
|
|
377
396
|
|
|
378
397
|
建议先给机器人发送:
|
|
@@ -418,6 +437,7 @@ pipiclaw
|
|
|
418
437
|
| `~/.pi/pipiclaw/models.json` | 自定义模型提供方 / 模型,或覆盖内置模型提供方 |
|
|
419
438
|
| `~/.pi/pipiclaw/settings.json` | 默认模型提供方 / 模型和运行时设置 |
|
|
420
439
|
| `~/.pi/pipiclaw/tools.json` | 内建工具配置,例如 `tools.web` |
|
|
440
|
+
| `~/.pi/pipiclaw/security.json` | 工具层安全策略配置 |
|
|
421
441
|
|
|
422
442
|
### 环境变量(Environment Variables)
|
|
423
443
|
|
|
@@ -425,6 +445,7 @@ pipiclaw
|
|
|
425
445
|
|----------|------|
|
|
426
446
|
| `ANTHROPIC_API_KEY` | Anthropic API Key |
|
|
427
447
|
| `PIPICLAW_HOME` | 覆盖默认的 `~/.pi/pipiclaw/` 根目录 |
|
|
448
|
+
| `PIPICLAW_SHELL` | Windows host 模式下指定 POSIX shell,例如 Git Bash 的 `bash.exe` |
|
|
428
449
|
| `PIPICLAW_DEBUG` | 调试模式,会把上下文写到 `last_prompt.json` |
|
|
429
450
|
| `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` / `NO_PROXY` | 标准代理环境变量;DingTalk runtime 和 web 工具都会尊重它们 |
|
|
430
451
|
|
|
@@ -481,6 +502,8 @@ Pipiclaw 的核心不是一个临时机器人实例,而是一组长期存在
|
|
|
481
502
|
├── auth.json
|
|
482
503
|
├── models.json
|
|
483
504
|
├── settings.json
|
|
505
|
+
├── tools.json
|
|
506
|
+
├── security.json
|
|
484
507
|
└── workspace/
|
|
485
508
|
├── SOUL.md
|
|
486
509
|
├── AGENTS.md
|
package/dist/agent/index.d.ts
CHANGED
package/dist/agent/index.js
CHANGED
|
@@ -2,4 +2,3 @@ import type { SandboxConfig } from "../sandbox.js";
|
|
|
2
2
|
import type { AgentRunner } from "./types.js";
|
|
3
3
|
export declare function getOrCreateRunner(sandboxConfig: SandboxConfig, channelId: string, channelDir: string): AgentRunner;
|
|
4
4
|
export declare function resetRunner(channelId: string): void;
|
|
5
|
-
export declare function resetAllRunners(): void;
|
package/dist/log.d.ts
CHANGED
|
@@ -10,7 +10,6 @@ export declare function logToolError(ctx: LogContext, toolName: string, duration
|
|
|
10
10
|
export declare function logResponseStart(ctx: LogContext): void;
|
|
11
11
|
export declare function logThinking(ctx: LogContext, thinking: string): void;
|
|
12
12
|
export declare function logResponse(ctx: LogContext, text: string): void;
|
|
13
|
-
export declare function logStopRequest(ctx: LogContext): void;
|
|
14
13
|
export declare function logInfo(message: string): void;
|
|
15
14
|
export declare function logWarning(message: string, details?: string): void;
|
|
16
15
|
export declare function logAgentError(ctx: LogContext | "system", error: string): void;
|
|
@@ -29,4 +28,3 @@ export declare function logUsageSummary(ctx: LogContext, usage: {
|
|
|
29
28
|
}, contextTokens?: number, contextWindow?: number): string;
|
|
30
29
|
export declare function logStartup(workingDir: string, sandbox: string): void;
|
|
31
30
|
export declare function logConnected(): void;
|
|
32
|
-
export declare function logDisconnected(): void;
|
package/dist/log.js
CHANGED
|
@@ -111,11 +111,6 @@ export function logResponse(ctx, text) {
|
|
|
111
111
|
.join("\n");
|
|
112
112
|
console.log(color("dim", indented));
|
|
113
113
|
}
|
|
114
|
-
// Control
|
|
115
|
-
export function logStopRequest(ctx) {
|
|
116
|
-
console.log(color("green", `${timestamp()} ${formatContext(ctx)} stop`));
|
|
117
|
-
console.log(color("yellow", `${timestamp()} ${formatContext(ctx)} ⊗ Stop requested - aborting`));
|
|
118
|
-
}
|
|
119
114
|
// System
|
|
120
115
|
export function logInfo(message) {
|
|
121
116
|
console.log(color("blue", `${timestamp()} [system] ${message}`));
|
|
@@ -185,6 +180,3 @@ export function logConnected() {
|
|
|
185
180
|
console.log("⚡️ pipiclaw connected and listening!");
|
|
186
181
|
console.log("");
|
|
187
182
|
}
|
|
188
|
-
export function logDisconnected() {
|
|
189
|
-
console.log("pipiclaw disconnected.");
|
|
190
|
-
}
|
|
@@ -23,6 +23,7 @@ export declare class MemoryLifecycle {
|
|
|
23
23
|
private durableRevision;
|
|
24
24
|
private lastDurableConsolidationRevision;
|
|
25
25
|
private readonly channelMemoryQueue;
|
|
26
|
+
private backgroundNewSessionConsolidation;
|
|
26
27
|
constructor(options: MemoryLifecycleOptions);
|
|
27
28
|
private buildRunOptions;
|
|
28
29
|
createExtensionFactory(): ExtensionFactory;
|
|
@@ -44,6 +45,8 @@ export declare class MemoryLifecycle {
|
|
|
44
45
|
private handleSessionBeforeCompact;
|
|
45
46
|
private handleSessionCompact;
|
|
46
47
|
private handleSessionBeforeSwitch;
|
|
48
|
+
/** Await any in-flight detached new-session consolidation (shutdown/tests). */
|
|
49
|
+
whenNewSessionConsolidationSettled(): Promise<void>;
|
|
47
50
|
private handleSessionStart;
|
|
48
51
|
private recordActivity;
|
|
49
52
|
}
|
package/dist/memory/lifecycle.js
CHANGED
|
@@ -10,6 +10,8 @@ export class MemoryLifecycle {
|
|
|
10
10
|
this.durableDirty = false;
|
|
11
11
|
this.durableRevision = 0;
|
|
12
12
|
this.lastDurableConsolidationRevision = 0;
|
|
13
|
+
// Tracks the detached new-session consolidation so shutdown/tests can await it.
|
|
14
|
+
this.backgroundNewSessionConsolidation = Promise.resolve();
|
|
13
15
|
this.channelMemoryQueue = options.channelMemoryQueue ?? getDefaultChannelMemoryQueue();
|
|
14
16
|
}
|
|
15
17
|
buildRunOptions(messages, sessionEntries) {
|
|
@@ -29,8 +31,8 @@ export class MemoryLifecycle {
|
|
|
29
31
|
pi.on("session_compact", async (event) => {
|
|
30
32
|
this.handleSessionCompact(event);
|
|
31
33
|
});
|
|
32
|
-
pi.on("session_before_switch",
|
|
33
|
-
|
|
34
|
+
pi.on("session_before_switch", (event) => {
|
|
35
|
+
this.handleSessionBeforeSwitch(event);
|
|
34
36
|
});
|
|
35
37
|
pi.on("session_start", async (event) => {
|
|
36
38
|
this.handleSessionStart(event);
|
|
@@ -51,6 +53,9 @@ export class MemoryLifecycle {
|
|
|
51
53
|
this.recordActivity("assistant-turn-completed");
|
|
52
54
|
}
|
|
53
55
|
async flushForShutdown() {
|
|
56
|
+
// Let any detached new-session consolidation finish (and update the durable
|
|
57
|
+
// checkpoint) before deciding whether a final flush is still needed.
|
|
58
|
+
await this.whenNewSessionConsolidationSettled();
|
|
54
59
|
await this.runDurableMemoryJobSerial(async () => {
|
|
55
60
|
// Shutdown is the last chance to persist, so use a looser gate than the
|
|
56
61
|
// idle/compaction path: consolidate any unconsolidated durable activity,
|
|
@@ -202,11 +207,28 @@ export class MemoryLifecycle {
|
|
|
202
207
|
handleSessionCompact(_event) {
|
|
203
208
|
this.recordActivity("boundary");
|
|
204
209
|
}
|
|
205
|
-
|
|
210
|
+
handleSessionBeforeSwitch(event) {
|
|
206
211
|
if (event.reason !== "new") {
|
|
207
212
|
return;
|
|
208
213
|
}
|
|
209
|
-
|
|
214
|
+
// Snapshot the outgoing session synchronously: the switch has not happened
|
|
215
|
+
// yet, so getMessages()/getSessionEntries() still reference the session that
|
|
216
|
+
// is about to be replaced. Once we yield, this.session is rebound to the new
|
|
217
|
+
// (empty) session and the snapshot would be lost.
|
|
218
|
+
const messageSnapshot = [...this.options.getMessages()];
|
|
219
|
+
const sessionEntrySnapshot = [...this.options.getSessionEntries()];
|
|
220
|
+
// Run the LLM-backed consolidation in the background so /new returns
|
|
221
|
+
// immediately. Failures are tolerated: runPreflightConsolidationNow catches
|
|
222
|
+
// and logs its own errors, and the serial queue keeps this from racing with
|
|
223
|
+
// idle/maintenance work on the same channel.
|
|
224
|
+
this.backgroundNewSessionConsolidation = this.runPreflightConsolidation("new-session", messageSnapshot, sessionEntrySnapshot).catch((error) => {
|
|
225
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
226
|
+
log.logWarning(`[${this.options.channelId}] Background new-session consolidation rejected`, message);
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
/** Await any in-flight detached new-session consolidation (shutdown/tests). */
|
|
230
|
+
async whenNewSessionConsolidationSettled() {
|
|
231
|
+
await this.backgroundNewSessionConsolidation;
|
|
210
232
|
}
|
|
211
233
|
handleSessionStart(event) {
|
|
212
234
|
if (event.reason !== "new") {
|
|
@@ -28,6 +28,5 @@ export interface MemoryActivityEvent {
|
|
|
28
28
|
export declare function getMemoryMaintenanceStateDir(appHomeDir: string): string;
|
|
29
29
|
export declare function getMemoryMaintenanceStatePath(appHomeDir: string, channelId: string): string;
|
|
30
30
|
export declare function readMemoryMaintenanceState(appHomeDir: string, channelId: string): Promise<MemoryMaintenanceState>;
|
|
31
|
-
export declare function writeMemoryMaintenanceState(appHomeDir: string, state: MemoryMaintenanceState): Promise<void>;
|
|
32
31
|
export declare function updateMemoryMaintenanceState(appHomeDir: string, channelId: string, update: (state: MemoryMaintenanceState) => MemoryMaintenanceState): Promise<MemoryMaintenanceState>;
|
|
33
32
|
export declare function applyMemoryActivityToState(state: MemoryMaintenanceState, event: MemoryActivityEvent): MemoryMaintenanceState;
|
|
@@ -73,12 +73,6 @@ export async function readMemoryMaintenanceState(appHomeDir, channelId) {
|
|
|
73
73
|
return createDefaultState(channelId);
|
|
74
74
|
}
|
|
75
75
|
}
|
|
76
|
-
export async function writeMemoryMaintenanceState(appHomeDir, state) {
|
|
77
|
-
const path = getMemoryMaintenanceStatePath(appHomeDir, state.channelId);
|
|
78
|
-
await stateUpdateQueue.run(path, async () => {
|
|
79
|
-
await writeFileAtomically(path, `${JSON.stringify(normalizeState(state.channelId, state), null, 2)}\n`);
|
|
80
|
-
});
|
|
81
|
-
}
|
|
82
76
|
export async function updateMemoryMaintenanceState(appHomeDir, channelId, update) {
|
|
83
77
|
const path = getMemoryMaintenanceStatePath(appHomeDir, channelId);
|
|
84
78
|
return stateUpdateQueue.run(path, async () => {
|
package/dist/paths.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
export declare const APP_NAME = "pipiclaw";
|
|
2
2
|
export declare const APP_HOME_DIR: string;
|
|
3
3
|
export declare const WORKSPACE_DIR: string;
|
|
4
|
+
export declare const STATE_DIR: string;
|
|
5
|
+
export declare const EVENT_STATE_DIR: string;
|
|
6
|
+
export declare const EVENT_HISTORY_PATH: string;
|
|
4
7
|
export declare const SUB_AGENTS_DIR_NAME = "sub-agents";
|
|
5
8
|
export declare const SUB_AGENTS_DIR: string;
|
|
6
9
|
export declare const CHANNEL_CONFIG_PATH: string;
|
package/dist/paths.js
CHANGED
|
@@ -3,6 +3,9 @@ import { join } from "path";
|
|
|
3
3
|
export const APP_NAME = "pipiclaw";
|
|
4
4
|
export const APP_HOME_DIR = process.env.PIPICLAW_HOME ?? join(homedir(), ".pi", APP_NAME);
|
|
5
5
|
export const WORKSPACE_DIR = join(APP_HOME_DIR, "workspace");
|
|
6
|
+
export const STATE_DIR = join(APP_HOME_DIR, "state");
|
|
7
|
+
export const EVENT_STATE_DIR = join(STATE_DIR, "events");
|
|
8
|
+
export const EVENT_HISTORY_PATH = join(EVENT_STATE_DIR, "history.jsonl");
|
|
6
9
|
export const SUB_AGENTS_DIR_NAME = "sub-agents";
|
|
7
10
|
export const SUB_AGENTS_DIR = join(WORKSPACE_DIR, SUB_AGENTS_DIR_NAME);
|
|
8
11
|
export const CHANNEL_CONFIG_PATH = join(APP_HOME_DIR, "channel.json");
|
|
@@ -11,6 +11,7 @@ export interface BootstrapPaths {
|
|
|
11
11
|
settingsConfigPath: string;
|
|
12
12
|
toolsConfigPath: string;
|
|
13
13
|
securityConfigPath: string;
|
|
14
|
+
eventHistoryPath: string;
|
|
14
15
|
}
|
|
15
16
|
export interface BootstrapIO {
|
|
16
17
|
log: (...args: unknown[]) => void;
|
|
@@ -55,7 +56,7 @@ interface RuntimeContextOptions {
|
|
|
55
56
|
sandbox: SandboxConfig;
|
|
56
57
|
dingtalkConfig: DingTalkConfig;
|
|
57
58
|
createBot?: (handler: DingTalkHandler, config: DingTalkConfig) => DingTalkBot;
|
|
58
|
-
createEventsWatcher?: (workspaceDir: string, bot: DingTalkBot, executor: Executor) => {
|
|
59
|
+
createEventsWatcher?: (workspaceDir: string, bot: DingTalkBot, executor: Executor, eventHistoryPath: string) => {
|
|
59
60
|
start(): void;
|
|
60
61
|
stop(): void;
|
|
61
62
|
};
|
|
@@ -6,7 +6,7 @@ import { resetRunner } from "../agent/runner-factory.js";
|
|
|
6
6
|
import * as log from "../log.js";
|
|
7
7
|
import { ensureChannelMemoryFilesSync } from "../memory/files.js";
|
|
8
8
|
import { MemoryMaintenanceScheduler } from "../memory/scheduler.js";
|
|
9
|
-
import { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "../paths.js";
|
|
9
|
+
import { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, EVENT_HISTORY_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "../paths.js";
|
|
10
10
|
import { createExecutor, parseSandboxArg, validateSandbox } from "../sandbox.js";
|
|
11
11
|
import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
|
|
12
12
|
import { PipiclawSettingsManager } from "../settings.js";
|
|
@@ -153,6 +153,7 @@ export const DEFAULT_BOOTSTRAP_PATHS = {
|
|
|
153
153
|
settingsConfigPath: SETTINGS_CONFIG_PATH,
|
|
154
154
|
toolsConfigPath: TOOLS_CONFIG_PATH,
|
|
155
155
|
securityConfigPath: SECURITY_CONFIG_PATH,
|
|
156
|
+
eventHistoryPath: EVENT_HISTORY_PATH,
|
|
156
157
|
};
|
|
157
158
|
export class BootstrapExitError extends Error {
|
|
158
159
|
constructor(code, message) {
|
|
@@ -508,8 +509,8 @@ export function createRuntimeContext(options) {
|
|
|
508
509
|
: new DingTalkBot(handler, options.dingtalkConfig);
|
|
509
510
|
const executor = createExecutor(options.sandbox);
|
|
510
511
|
const eventsWatcher = options.createEventsWatcher
|
|
511
|
-
? options.createEventsWatcher(options.paths.workspaceDir, bot, executor)
|
|
512
|
-
: createEventsWatcher(options.paths.workspaceDir, bot, executor, loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config.commandGuard);
|
|
512
|
+
? options.createEventsWatcher(options.paths.workspaceDir, bot, executor, options.paths.eventHistoryPath)
|
|
513
|
+
: createEventsWatcher(options.paths.workspaceDir, bot, executor, loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config.commandGuard, options.paths.eventHistoryPath);
|
|
513
514
|
const memoryMaintenanceScheduler = options.createMemoryMaintenanceScheduler
|
|
514
515
|
? options.createMemoryMaintenanceScheduler()
|
|
515
516
|
: new MemoryMaintenanceScheduler({
|
package/dist/runtime/events.d.ts
CHANGED
|
@@ -28,20 +28,55 @@ export interface PeriodicEvent {
|
|
|
28
28
|
preAction?: EventAction;
|
|
29
29
|
}
|
|
30
30
|
export type ScheduledEvent = ImmediateEvent | OneShotEvent | PeriodicEvent;
|
|
31
|
+
export type EventHistoryAction = "loaded" | "scheduled" | "triggered" | "skipped" | "enqueued" | "queue_full" | "deleted" | "invalid" | "pre_action_started" | "pre_action_passed" | "pre_action_blocked" | "pre_action_failed" | "cancelled";
|
|
32
|
+
export type EventHistoryResult = "ok" | "error" | "skipped";
|
|
33
|
+
export interface EventHistoryRecord {
|
|
34
|
+
ts: string;
|
|
35
|
+
eventName: string;
|
|
36
|
+
eventPath: string;
|
|
37
|
+
eventType: ScheduledEvent["type"] | "unknown";
|
|
38
|
+
channelId?: string;
|
|
39
|
+
action: EventHistoryAction;
|
|
40
|
+
result: EventHistoryResult;
|
|
41
|
+
reason?: string;
|
|
42
|
+
schedule?: string;
|
|
43
|
+
timezone?: string;
|
|
44
|
+
at?: string;
|
|
45
|
+
nextRunAt?: string;
|
|
46
|
+
textPreview?: string;
|
|
47
|
+
preAction?: {
|
|
48
|
+
type: "bash";
|
|
49
|
+
command: string;
|
|
50
|
+
timeoutMs: number;
|
|
51
|
+
exitCode?: number | null;
|
|
52
|
+
durationMs?: number;
|
|
53
|
+
};
|
|
54
|
+
queue?: {
|
|
55
|
+
accepted: boolean;
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
export interface EventsWatcherOptions {
|
|
59
|
+
historyPath?: string;
|
|
60
|
+
}
|
|
61
|
+
export declare function formatLocalTimestamp(date?: Date): string;
|
|
31
62
|
export declare class EventsWatcher {
|
|
32
63
|
private eventsDir;
|
|
33
64
|
private bot;
|
|
34
65
|
private executor;
|
|
35
66
|
private commandGuardConfig?;
|
|
67
|
+
private options;
|
|
36
68
|
private timers;
|
|
37
69
|
private crons;
|
|
38
70
|
private debounceTimers;
|
|
39
71
|
private startTime;
|
|
40
72
|
private watcher;
|
|
41
73
|
private knownFiles;
|
|
42
|
-
constructor(eventsDir: string, bot: DingTalkBot, executor: Executor, commandGuardConfig?: SecurityConfig["commandGuard"] | undefined);
|
|
74
|
+
constructor(eventsDir: string, bot: DingTalkBot, executor: Executor, commandGuardConfig?: SecurityConfig["commandGuard"] | undefined, options?: EventsWatcherOptions);
|
|
43
75
|
start(): void;
|
|
44
76
|
stop(): void;
|
|
77
|
+
private ensureHistoryFile;
|
|
78
|
+
private appendHistory;
|
|
79
|
+
private appendEventHistory;
|
|
45
80
|
private debounce;
|
|
46
81
|
private scanExisting;
|
|
47
82
|
private handleFileChange;
|
|
@@ -64,4 +99,4 @@ export declare class EventsWatcher {
|
|
|
64
99
|
/**
|
|
65
100
|
* Create and start an events watcher.
|
|
66
101
|
*/
|
|
67
|
-
export declare function createEventsWatcher(workspaceDir: string, bot: DingTalkBot, executor: Executor, commandGuardConfig?: SecurityConfig["commandGuard"]): EventsWatcher;
|
|
102
|
+
export declare function createEventsWatcher(workspaceDir: string, bot: DingTalkBot, executor: Executor, commandGuardConfig?: SecurityConfig["commandGuard"], historyPath?: string): EventsWatcher;
|
package/dist/runtime/events.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Cron } from "croner";
|
|
2
|
-
import { existsSync, mkdirSync, readdirSync, statSync, unlinkSync, watch, writeFileSync } from "fs";
|
|
2
|
+
import { appendFileSync, chmodSync, existsSync, mkdirSync, readdirSync, statSync, unlinkSync, watch, writeFileSync, } from "fs";
|
|
3
3
|
import { readFile } from "fs/promises";
|
|
4
|
-
import { join } from "path";
|
|
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
7
|
// ============================================================================
|
|
@@ -11,12 +11,47 @@ const DEBOUNCE_MS = 100;
|
|
|
11
11
|
const MAX_RETRIES = 3;
|
|
12
12
|
const RETRY_BASE_MS = 100;
|
|
13
13
|
const MAX_TIMEOUT_MS = 2_147_483_647;
|
|
14
|
+
const DEFAULT_PRE_ACTION_TIMEOUT_MS = 10_000;
|
|
15
|
+
const TEXT_PREVIEW_MAX_CHARS = 160;
|
|
16
|
+
function pad2(value) {
|
|
17
|
+
return String(value).padStart(2, "0");
|
|
18
|
+
}
|
|
19
|
+
function pad3(value) {
|
|
20
|
+
return String(value).padStart(3, "0");
|
|
21
|
+
}
|
|
22
|
+
export function formatLocalTimestamp(date = new Date()) {
|
|
23
|
+
const offsetMinutes = -date.getTimezoneOffset();
|
|
24
|
+
const offsetSign = offsetMinutes >= 0 ? "+" : "-";
|
|
25
|
+
const absOffsetMinutes = Math.abs(offsetMinutes);
|
|
26
|
+
const offsetHours = Math.floor(absOffsetMinutes / 60);
|
|
27
|
+
const offsetRemainderMinutes = absOffsetMinutes % 60;
|
|
28
|
+
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
|
+
function eventNameFromFilename(filename) {
|
|
31
|
+
return filename.endsWith(".json") ? filename.slice(0, -".json".length) : filename;
|
|
32
|
+
}
|
|
33
|
+
function truncateTextPreview(text) {
|
|
34
|
+
const normalized = text.replace(/\s+/g, " ").trim();
|
|
35
|
+
return normalized.length > TEXT_PREVIEW_MAX_CHARS
|
|
36
|
+
? `${normalized.slice(0, TEXT_PREVIEW_MAX_CHARS - 1)}…`
|
|
37
|
+
: normalized;
|
|
38
|
+
}
|
|
39
|
+
class EventPreActionError extends Error {
|
|
40
|
+
constructor(kind, message, options = {}) {
|
|
41
|
+
super(message);
|
|
42
|
+
this.name = "EventPreActionError";
|
|
43
|
+
this.kind = kind;
|
|
44
|
+
this.exitCode = options.exitCode;
|
|
45
|
+
this.durationMs = options.durationMs;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
14
48
|
export class EventsWatcher {
|
|
15
|
-
constructor(eventsDir, bot, executor, commandGuardConfig) {
|
|
49
|
+
constructor(eventsDir, bot, executor, commandGuardConfig, options = {}) {
|
|
16
50
|
this.eventsDir = eventsDir;
|
|
17
51
|
this.bot = bot;
|
|
18
52
|
this.executor = executor;
|
|
19
53
|
this.commandGuardConfig = commandGuardConfig;
|
|
54
|
+
this.options = options;
|
|
20
55
|
this.timers = new Map();
|
|
21
56
|
this.crons = new Map();
|
|
22
57
|
this.debounceTimers = new Map();
|
|
@@ -28,6 +63,7 @@ export class EventsWatcher {
|
|
|
28
63
|
if (!existsSync(this.eventsDir)) {
|
|
29
64
|
mkdirSync(this.eventsDir, { recursive: true });
|
|
30
65
|
}
|
|
66
|
+
this.ensureHistoryFile();
|
|
31
67
|
log.logInfo(`Events watcher starting, dir: ${this.eventsDir}`);
|
|
32
68
|
this.scanExisting();
|
|
33
69
|
this.watcher = watch(this.eventsDir, (_eventType, filename) => {
|
|
@@ -57,6 +93,52 @@ export class EventsWatcher {
|
|
|
57
93
|
this.knownFiles.clear();
|
|
58
94
|
log.logInfo("Events watcher stopped");
|
|
59
95
|
}
|
|
96
|
+
ensureHistoryFile() {
|
|
97
|
+
if (!this.options.historyPath) {
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
const historyDir = dirname(this.options.historyPath);
|
|
102
|
+
mkdirSync(historyDir, { recursive: true, mode: 0o700 });
|
|
103
|
+
writeFileSync(this.options.historyPath, "", { flag: "a", mode: 0o600 });
|
|
104
|
+
chmodSync(this.options.historyPath, 0o600);
|
|
105
|
+
}
|
|
106
|
+
catch (err) {
|
|
107
|
+
log.logWarning("Failed to initialize event history file", String(err));
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
appendHistory(record) {
|
|
111
|
+
if (!this.options.historyPath) {
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
const { filename, ...rest } = record;
|
|
115
|
+
const fullRecord = {
|
|
116
|
+
ts: formatLocalTimestamp(),
|
|
117
|
+
eventName: eventNameFromFilename(filename),
|
|
118
|
+
eventPath: resolve(this.eventsDir, filename),
|
|
119
|
+
...rest,
|
|
120
|
+
};
|
|
121
|
+
try {
|
|
122
|
+
this.ensureHistoryFile();
|
|
123
|
+
appendFileSync(this.options.historyPath, `${JSON.stringify(fullRecord)}\n`, "utf-8");
|
|
124
|
+
}
|
|
125
|
+
catch (err) {
|
|
126
|
+
log.logWarning("Failed to write event history", String(err));
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
appendEventHistory(filename, event, action, result, extra = {}) {
|
|
130
|
+
this.appendHistory({
|
|
131
|
+
filename,
|
|
132
|
+
eventType: event.type,
|
|
133
|
+
channelId: event.channelId,
|
|
134
|
+
action,
|
|
135
|
+
result,
|
|
136
|
+
textPreview: truncateTextPreview(event.text),
|
|
137
|
+
...(event.type === "one-shot" ? { at: event.at } : {}),
|
|
138
|
+
...(event.type === "periodic" ? { schedule: event.schedule, timezone: event.timezone } : {}),
|
|
139
|
+
...extra,
|
|
140
|
+
});
|
|
141
|
+
}
|
|
60
142
|
debounce(filename, fn) {
|
|
61
143
|
const existing = this.debounceTimers.get(filename);
|
|
62
144
|
if (existing) {
|
|
@@ -99,17 +181,35 @@ export class EventsWatcher {
|
|
|
99
181
|
log.logInfo(`Event file deleted: ${filename}`);
|
|
100
182
|
this.cancelScheduled(filename);
|
|
101
183
|
this.knownFiles.delete(filename);
|
|
184
|
+
this.appendHistory({
|
|
185
|
+
filename,
|
|
186
|
+
eventType: "unknown",
|
|
187
|
+
action: "deleted",
|
|
188
|
+
result: "ok",
|
|
189
|
+
});
|
|
102
190
|
}
|
|
103
191
|
cancelScheduled(filename) {
|
|
192
|
+
let cancelled = false;
|
|
104
193
|
const timer = this.timers.get(filename);
|
|
105
194
|
if (timer) {
|
|
106
195
|
clearTimeout(timer);
|
|
107
196
|
this.timers.delete(filename);
|
|
197
|
+
cancelled = true;
|
|
108
198
|
}
|
|
109
199
|
const cron = this.crons.get(filename);
|
|
110
200
|
if (cron) {
|
|
111
201
|
cron.stop();
|
|
112
202
|
this.crons.delete(filename);
|
|
203
|
+
cancelled = true;
|
|
204
|
+
}
|
|
205
|
+
if (cancelled) {
|
|
206
|
+
this.appendHistory({
|
|
207
|
+
filename,
|
|
208
|
+
eventType: "unknown",
|
|
209
|
+
action: "cancelled",
|
|
210
|
+
result: "ok",
|
|
211
|
+
reason: "event file changed or was removed",
|
|
212
|
+
});
|
|
113
213
|
}
|
|
114
214
|
}
|
|
115
215
|
async handleFile(filename) {
|
|
@@ -131,11 +231,19 @@ export class EventsWatcher {
|
|
|
131
231
|
}
|
|
132
232
|
if (!event) {
|
|
133
233
|
log.logWarning(`Failed to parse event file after ${MAX_RETRIES} retries: ${filename}`, lastError?.message);
|
|
234
|
+
this.appendHistory({
|
|
235
|
+
filename,
|
|
236
|
+
eventType: "unknown",
|
|
237
|
+
action: "invalid",
|
|
238
|
+
result: "error",
|
|
239
|
+
reason: lastError?.message ?? "Unknown event parse error",
|
|
240
|
+
});
|
|
134
241
|
this.markInvalid(filename, lastError?.message ?? "Unknown event parse error");
|
|
135
242
|
return;
|
|
136
243
|
}
|
|
137
244
|
this.knownFiles.add(filename);
|
|
138
245
|
this.clearInvalidMarker(filename);
|
|
246
|
+
this.appendEventHistory(filename, event, "loaded", "ok");
|
|
139
247
|
switch (event.type) {
|
|
140
248
|
case "immediate":
|
|
141
249
|
this.handleImmediate(filename, event);
|
|
@@ -211,6 +319,7 @@ export class EventsWatcher {
|
|
|
211
319
|
const stat = statSync(filePath);
|
|
212
320
|
if (stat.mtimeMs < this.startTime) {
|
|
213
321
|
log.logInfo(`Stale immediate event, deleting: ${filename}`);
|
|
322
|
+
this.appendEventHistory(filename, event, "skipped", "skipped", { reason: "stale immediate event" });
|
|
214
323
|
this.deleteFile(filename);
|
|
215
324
|
return;
|
|
216
325
|
}
|
|
@@ -219,6 +328,7 @@ export class EventsWatcher {
|
|
|
219
328
|
return;
|
|
220
329
|
}
|
|
221
330
|
log.logInfo(`Executing immediate event: ${filename}`);
|
|
331
|
+
this.appendEventHistory(filename, event, "triggered", "ok");
|
|
222
332
|
await this.execute(filename, event);
|
|
223
333
|
}
|
|
224
334
|
handleOneShot(filename, event) {
|
|
@@ -226,29 +336,41 @@ export class EventsWatcher {
|
|
|
226
336
|
const now = Date.now();
|
|
227
337
|
if (!Number.isFinite(atTime)) {
|
|
228
338
|
log.logWarning(`Invalid one-shot time for ${filename}: ${event.at}`);
|
|
339
|
+
this.appendEventHistory(filename, event, "invalid", "error", { reason: `Invalid one-shot time: ${event.at}` });
|
|
229
340
|
this.markInvalid(filename, `Invalid one-shot time: ${event.at}`);
|
|
230
341
|
return;
|
|
231
342
|
}
|
|
232
343
|
if (atTime <= now) {
|
|
233
344
|
log.logInfo(`One-shot event in the past, deleting: ${filename}`);
|
|
345
|
+
this.appendEventHistory(filename, event, "skipped", "skipped", { reason: "one-shot event is in the past" });
|
|
234
346
|
this.deleteFile(filename);
|
|
235
347
|
return;
|
|
236
348
|
}
|
|
237
349
|
const delay = atTime - now;
|
|
238
350
|
if (delay > MAX_TIMEOUT_MS) {
|
|
239
351
|
log.logWarning(`One-shot event exceeds maximum supported delay for ${filename}: ${event.at}. Use a periodic cron event instead.`);
|
|
352
|
+
this.appendEventHistory(filename, event, "skipped", "skipped", {
|
|
353
|
+
reason: `One-shot event exceeds maximum supported delay: ${event.at}`,
|
|
354
|
+
});
|
|
240
355
|
this.markInvalid(filename, `One-shot event exceeds maximum supported delay: ${event.at}`);
|
|
241
356
|
return;
|
|
242
357
|
}
|
|
243
358
|
log.logInfo(`Scheduling one-shot event: ${filename} in ${Math.round(delay / 1000)}s`);
|
|
359
|
+
this.appendEventHistory(filename, event, "scheduled", "ok", {
|
|
360
|
+
nextRunAt: formatLocalTimestamp(new Date(atTime)),
|
|
361
|
+
});
|
|
244
362
|
const timer = setTimeout(async () => {
|
|
245
363
|
this.timers.delete(filename);
|
|
246
364
|
try {
|
|
247
365
|
log.logInfo(`Executing one-shot event: ${filename}`);
|
|
366
|
+
this.appendEventHistory(filename, event, "triggered", "ok");
|
|
248
367
|
await this.execute(filename, event);
|
|
249
368
|
}
|
|
250
369
|
catch (err) {
|
|
251
370
|
log.logWarning(`One-shot event execution failed: ${filename}`, String(err));
|
|
371
|
+
this.appendEventHistory(filename, event, "skipped", "error", {
|
|
372
|
+
reason: err instanceof Error ? err.message : String(err),
|
|
373
|
+
});
|
|
252
374
|
}
|
|
253
375
|
}, delay);
|
|
254
376
|
this.timers.set(filename, timer);
|
|
@@ -258,29 +380,64 @@ export class EventsWatcher {
|
|
|
258
380
|
const cron = new Cron(event.schedule, { timezone: event.timezone }, async () => {
|
|
259
381
|
try {
|
|
260
382
|
log.logInfo(`Executing periodic event: ${filename}`);
|
|
383
|
+
this.appendEventHistory(filename, event, "triggered", "ok");
|
|
261
384
|
await this.execute(filename, event, false);
|
|
262
385
|
}
|
|
263
386
|
catch (err) {
|
|
264
387
|
log.logWarning(`Periodic event execution failed: ${filename}`, String(err));
|
|
388
|
+
this.appendEventHistory(filename, event, "skipped", "error", {
|
|
389
|
+
reason: err instanceof Error ? err.message : String(err),
|
|
390
|
+
});
|
|
265
391
|
}
|
|
266
392
|
});
|
|
267
393
|
this.crons.set(filename, cron);
|
|
268
394
|
const next = cron.nextRun();
|
|
269
395
|
log.logInfo(`Scheduled periodic event: ${filename}, next run: ${next?.toISOString() ?? "unknown"}`);
|
|
396
|
+
this.appendEventHistory(filename, event, "scheduled", "ok", next ? { nextRunAt: formatLocalTimestamp(next) } : {});
|
|
270
397
|
}
|
|
271
398
|
catch (err) {
|
|
272
399
|
log.logWarning(`Invalid cron schedule for ${filename}: ${event.schedule}`, String(err));
|
|
400
|
+
this.appendEventHistory(filename, event, "invalid", "error", {
|
|
401
|
+
reason: `Invalid cron schedule: ${event.schedule}\n${String(err)}`,
|
|
402
|
+
});
|
|
273
403
|
this.markInvalid(filename, `Invalid cron schedule: ${event.schedule}\n${String(err)}`);
|
|
274
404
|
}
|
|
275
405
|
}
|
|
276
406
|
async execute(filename, event, deleteAfter = true) {
|
|
277
407
|
if (event.preAction) {
|
|
278
408
|
try {
|
|
279
|
-
|
|
409
|
+
this.appendEventHistory(filename, event, "pre_action_started", "ok", {
|
|
410
|
+
preAction: {
|
|
411
|
+
type: event.preAction.type,
|
|
412
|
+
command: event.preAction.command,
|
|
413
|
+
timeoutMs: event.preAction.timeout ?? DEFAULT_PRE_ACTION_TIMEOUT_MS,
|
|
414
|
+
},
|
|
415
|
+
});
|
|
416
|
+
const result = await this.runPreAction(event.preAction, filename);
|
|
417
|
+
this.appendEventHistory(filename, event, "pre_action_passed", "ok", {
|
|
418
|
+
preAction: {
|
|
419
|
+
type: event.preAction.type,
|
|
420
|
+
command: event.preAction.command,
|
|
421
|
+
timeoutMs: event.preAction.timeout ?? DEFAULT_PRE_ACTION_TIMEOUT_MS,
|
|
422
|
+
exitCode: result.exitCode,
|
|
423
|
+
durationMs: result.durationMs,
|
|
424
|
+
},
|
|
425
|
+
});
|
|
280
426
|
}
|
|
281
427
|
catch (err) {
|
|
282
428
|
const reason = err instanceof Error ? err.message : String(err);
|
|
283
429
|
log.logInfo(`Pre-action gate blocked event: ${filename} (${reason})`);
|
|
430
|
+
const actionResult = err instanceof EventPreActionError ? err : undefined;
|
|
431
|
+
this.appendEventHistory(filename, event, actionResult?.kind === "failed" ? "pre_action_failed" : "pre_action_blocked", actionResult?.kind === "failed" ? "error" : "skipped", {
|
|
432
|
+
reason,
|
|
433
|
+
preAction: {
|
|
434
|
+
type: event.preAction.type,
|
|
435
|
+
command: event.preAction.command,
|
|
436
|
+
timeoutMs: event.preAction.timeout ?? DEFAULT_PRE_ACTION_TIMEOUT_MS,
|
|
437
|
+
...(actionResult?.exitCode !== undefined ? { exitCode: actionResult.exitCode } : {}),
|
|
438
|
+
...(actionResult?.durationMs !== undefined ? { durationMs: actionResult.durationMs } : {}),
|
|
439
|
+
},
|
|
440
|
+
});
|
|
284
441
|
return;
|
|
285
442
|
}
|
|
286
443
|
}
|
|
@@ -310,6 +467,7 @@ export class EventsWatcher {
|
|
|
310
467
|
};
|
|
311
468
|
const enqueued = this.bot.enqueueEvent(syntheticEvent);
|
|
312
469
|
if (enqueued) {
|
|
470
|
+
this.appendEventHistory(filename, event, "enqueued", "ok", { queue: { accepted: true } });
|
|
313
471
|
if (deleteAfter) {
|
|
314
472
|
this.deleteFile(filename);
|
|
315
473
|
}
|
|
@@ -320,24 +478,43 @@ export class EventsWatcher {
|
|
|
320
478
|
// GC'd as "past" with no trace, so leave a visible error marker (and keep
|
|
321
479
|
// the source file) making the loss auditable rather than a silent hole.
|
|
322
480
|
log.logWarning(`Event queue full, could not enqueue: ${filename}`);
|
|
481
|
+
this.appendEventHistory(filename, event, "queue_full", "error", {
|
|
482
|
+
reason: "channel queue full",
|
|
483
|
+
queue: { accepted: false },
|
|
484
|
+
});
|
|
323
485
|
if (deleteAfter) {
|
|
324
486
|
this.markInvalid(filename, `Event queue was full at ${new Date().toISOString()}; this occurrence was not delivered.`);
|
|
325
487
|
}
|
|
326
488
|
}
|
|
327
489
|
async runPreAction(action, filename) {
|
|
490
|
+
const startedAt = Date.now();
|
|
328
491
|
if (this.commandGuardConfig?.enabled) {
|
|
329
492
|
const guardResult = guardCommand(action.command, this.commandGuardConfig);
|
|
330
493
|
if (!guardResult.allowed) {
|
|
331
494
|
log.logWarning(`Pre-action command blocked by guard for ${filename}: ${guardResult.reason}`);
|
|
332
|
-
throw new
|
|
495
|
+
throw new EventPreActionError("blocked", `guard: ${guardResult.reason}`, {
|
|
496
|
+
durationMs: Date.now() - startedAt,
|
|
497
|
+
});
|
|
333
498
|
}
|
|
334
499
|
}
|
|
335
|
-
const timeoutMs = action.timeout ??
|
|
500
|
+
const timeoutMs = action.timeout ?? DEFAULT_PRE_ACTION_TIMEOUT_MS;
|
|
336
501
|
const timeoutSeconds = Math.max(1, Math.ceil(timeoutMs / 1000));
|
|
337
|
-
|
|
502
|
+
let result;
|
|
503
|
+
try {
|
|
504
|
+
result = await this.executor.exec(action.command, { timeout: timeoutSeconds });
|
|
505
|
+
}
|
|
506
|
+
catch (err) {
|
|
507
|
+
throw new EventPreActionError("failed", err instanceof Error ? err.message : String(err), {
|
|
508
|
+
durationMs: Date.now() - startedAt,
|
|
509
|
+
});
|
|
510
|
+
}
|
|
338
511
|
if (result.code !== 0) {
|
|
339
|
-
throw new
|
|
512
|
+
throw new EventPreActionError("blocked", `exit ${result.code}`, {
|
|
513
|
+
exitCode: result.code,
|
|
514
|
+
durationMs: Date.now() - startedAt,
|
|
515
|
+
});
|
|
340
516
|
}
|
|
517
|
+
return { exitCode: result.code, durationMs: Date.now() - startedAt };
|
|
341
518
|
}
|
|
342
519
|
deleteFile(filename) {
|
|
343
520
|
const filePath = join(this.eventsDir, filename);
|
|
@@ -351,6 +528,12 @@ export class EventsWatcher {
|
|
|
351
528
|
}
|
|
352
529
|
this.clearInvalidMarker(filename);
|
|
353
530
|
this.knownFiles.delete(filename);
|
|
531
|
+
this.appendHistory({
|
|
532
|
+
filename,
|
|
533
|
+
eventType: "unknown",
|
|
534
|
+
action: "deleted",
|
|
535
|
+
result: "ok",
|
|
536
|
+
});
|
|
354
537
|
}
|
|
355
538
|
getInvalidMarkerPath(filename) {
|
|
356
539
|
return join(this.eventsDir, `${filename}.error.txt`);
|
|
@@ -382,7 +565,7 @@ export class EventsWatcher {
|
|
|
382
565
|
/**
|
|
383
566
|
* Create and start an events watcher.
|
|
384
567
|
*/
|
|
385
|
-
export function createEventsWatcher(workspaceDir, bot, executor, commandGuardConfig) {
|
|
568
|
+
export function createEventsWatcher(workspaceDir, bot, executor, commandGuardConfig, historyPath) {
|
|
386
569
|
const eventsDir = join(workspaceDir, "events");
|
|
387
|
-
return new EventsWatcher(eventsDir, bot, executor, commandGuardConfig);
|
|
570
|
+
return new EventsWatcher(eventsDir, bot, executor, commandGuardConfig, { historyPath });
|
|
388
571
|
}
|
package/dist/web/config.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { PipiclawWebFetchConfig, PipiclawWebSearchConfig
|
|
1
|
+
import type { PipiclawWebFetchConfig, PipiclawWebSearchConfig } from "../tools/config.js";
|
|
2
2
|
export interface ResolvedWebSearchRequest {
|
|
3
3
|
query: string;
|
|
4
4
|
count: number;
|
|
@@ -16,4 +16,3 @@ export interface ResolvedWebFetchRequest {
|
|
|
16
16
|
}
|
|
17
17
|
export declare function resolveWebSearchRequest(config: PipiclawWebSearchConfig, query: string, count?: number): ResolvedWebSearchRequest;
|
|
18
18
|
export declare function resolveWebFetchRequest(config: PipiclawWebFetchConfig, url: string, extractMode?: "markdown" | "text", maxChars?: number): ResolvedWebFetchRequest;
|
|
19
|
-
export declare function isWebToolsEnabled(config: PipiclawWebToolsConfig): boolean;
|
package/dist/web/config.js
CHANGED
|
@@ -17,9 +17,6 @@ export function resolveWebFetchRequest(config, url, extractMode, maxChars) {
|
|
|
17
17
|
enableJinaFallback: config.enableJinaFallback,
|
|
18
18
|
};
|
|
19
19
|
}
|
|
20
|
-
export function isWebToolsEnabled(config) {
|
|
21
|
-
return config.enable !== false;
|
|
22
|
-
}
|
|
23
20
|
function clamp(value, fallback, minimum, maximum) {
|
|
24
21
|
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
25
22
|
return fallback;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oyasmi/pipiclaw",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.10-beta.1",
|
|
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": {
|
|
@@ -26,10 +26,11 @@
|
|
|
26
26
|
"dev": "tsc -p tsconfig.build.json --watch --preserveWatchOutput",
|
|
27
27
|
"lint": "biome check .",
|
|
28
28
|
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
29
|
+
"deadcode": "knip",
|
|
29
30
|
"test": "vitest --run",
|
|
30
31
|
"test:e2e": "vitest --run --config vitest.config.e2e.ts",
|
|
31
32
|
"test:coverage": "vitest --run --coverage",
|
|
32
|
-
"check": "npm run lint && npm run typecheck && npm run test",
|
|
33
|
+
"check": "npm run lint && npm run typecheck && npm run deadcode && npm run test",
|
|
33
34
|
"prepublishOnly": "npm run clean && npm run build && npm run check"
|
|
34
35
|
},
|
|
35
36
|
"dependencies": {
|
|
@@ -53,6 +54,7 @@
|
|
|
53
54
|
"@types/jsdom": "^28.0.1",
|
|
54
55
|
"@types/node": "^24.3.0",
|
|
55
56
|
"@vitest/coverage-v8": "^3.2.4",
|
|
57
|
+
"knip": "^6.24.0",
|
|
56
58
|
"typescript": "^5.7.3",
|
|
57
59
|
"vitest": "^3.2.4"
|
|
58
60
|
},
|