@oyasmi/pipiclaw 0.6.9 → 0.6.10
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 +33 -6
- package/dist/agent/commands.d.ts +1 -1
- package/dist/agent/commands.js +7 -0
- 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 +17 -3
- package/dist/runtime/dingtalk.d.ts +1 -0
- package/dist/runtime/dingtalk.js +6 -2
- package/dist/runtime/event-commands.d.ts +6 -0
- package/dist/runtime/event-commands.js +206 -0
- package/dist/runtime/events.d.ts +38 -3
- package/dist/runtime/events.js +266 -65
- package/dist/web/config.d.ts +1 -2
- package/dist/web/config.js +0 -3
- package/package.json +4 -2
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,119 @@ 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
|
+
function isRecord(value) {
|
|
40
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
41
|
+
}
|
|
42
|
+
function readRequiredString(data, field, filename) {
|
|
43
|
+
const value = data[field];
|
|
44
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
45
|
+
throw new Error(`Missing required fields (type, channelId, text) in ${filename}`);
|
|
46
|
+
}
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
function parsePreAction(data, filename) {
|
|
50
|
+
if (!data.preAction)
|
|
51
|
+
return undefined;
|
|
52
|
+
if (!isRecord(data.preAction)) {
|
|
53
|
+
throw new Error(`Invalid 'preAction' field in ${filename}, expected an object`);
|
|
54
|
+
}
|
|
55
|
+
const action = data.preAction;
|
|
56
|
+
if (action.type !== "bash") {
|
|
57
|
+
throw new Error(`Unsupported preAction type '${String(action.type)}' in ${filename}, only 'bash' is supported`);
|
|
58
|
+
}
|
|
59
|
+
if (typeof action.command !== "string" || action.command.trim().length === 0) {
|
|
60
|
+
throw new Error(`Missing or empty 'preAction.command' in ${filename}`);
|
|
61
|
+
}
|
|
62
|
+
if (action.timeout !== undefined) {
|
|
63
|
+
if (typeof action.timeout !== "number" || !Number.isFinite(action.timeout) || action.timeout <= 0) {
|
|
64
|
+
throw new Error(`Invalid 'preAction.timeout' in ${filename}, expected a positive millisecond value`);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return {
|
|
68
|
+
type: "bash",
|
|
69
|
+
command: action.command,
|
|
70
|
+
...(typeof action.timeout === "number" ? { timeout: action.timeout } : {}),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
export function parseScheduledEventContent(content, filename) {
|
|
74
|
+
const data = JSON.parse(content);
|
|
75
|
+
if (!isRecord(data)) {
|
|
76
|
+
throw new Error(`Missing required fields (type, channelId, text) in ${filename}`);
|
|
77
|
+
}
|
|
78
|
+
const type = readRequiredString(data, "type", filename);
|
|
79
|
+
const channelId = readRequiredString(data, "channelId", filename);
|
|
80
|
+
const text = readRequiredString(data, "text", filename);
|
|
81
|
+
const preAction = parsePreAction(data, filename);
|
|
82
|
+
switch (type) {
|
|
83
|
+
case "immediate":
|
|
84
|
+
return { type, channelId, text, ...(preAction ? { preAction } : {}) };
|
|
85
|
+
case "one-shot": {
|
|
86
|
+
if (typeof data.at !== "string" || data.at.trim().length === 0) {
|
|
87
|
+
throw new Error(`Missing 'at' field for one-shot event in ${filename}`);
|
|
88
|
+
}
|
|
89
|
+
return { type, channelId, text, at: data.at, ...(preAction ? { preAction } : {}) };
|
|
90
|
+
}
|
|
91
|
+
case "periodic": {
|
|
92
|
+
if (typeof data.schedule !== "string" || data.schedule.trim().length === 0) {
|
|
93
|
+
throw new Error(`Missing 'schedule' field for periodic event in ${filename}`);
|
|
94
|
+
}
|
|
95
|
+
if (typeof data.timezone !== "string" || data.timezone.trim().length === 0) {
|
|
96
|
+
throw new Error(`Missing 'timezone' field for periodic event in ${filename}`);
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
type,
|
|
100
|
+
channelId,
|
|
101
|
+
text,
|
|
102
|
+
schedule: data.schedule,
|
|
103
|
+
timezone: data.timezone,
|
|
104
|
+
...(preAction ? { preAction } : {}),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
default:
|
|
108
|
+
throw new Error(`Unknown event type '${type}' in ${filename}`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
class EventPreActionError extends Error {
|
|
112
|
+
constructor(kind, message, options = {}) {
|
|
113
|
+
super(message);
|
|
114
|
+
this.name = "EventPreActionError";
|
|
115
|
+
this.kind = kind;
|
|
116
|
+
this.exitCode = options.exitCode;
|
|
117
|
+
this.durationMs = options.durationMs;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
14
120
|
export class EventsWatcher {
|
|
15
|
-
constructor(eventsDir, bot, executor, commandGuardConfig) {
|
|
121
|
+
constructor(eventsDir, bot, executor, commandGuardConfig, options = {}) {
|
|
16
122
|
this.eventsDir = eventsDir;
|
|
17
123
|
this.bot = bot;
|
|
18
124
|
this.executor = executor;
|
|
19
125
|
this.commandGuardConfig = commandGuardConfig;
|
|
126
|
+
this.options = options;
|
|
20
127
|
this.timers = new Map();
|
|
21
128
|
this.crons = new Map();
|
|
22
129
|
this.debounceTimers = new Map();
|
|
@@ -28,6 +135,7 @@ export class EventsWatcher {
|
|
|
28
135
|
if (!existsSync(this.eventsDir)) {
|
|
29
136
|
mkdirSync(this.eventsDir, { recursive: true });
|
|
30
137
|
}
|
|
138
|
+
this.ensureHistoryFile();
|
|
31
139
|
log.logInfo(`Events watcher starting, dir: ${this.eventsDir}`);
|
|
32
140
|
this.scanExisting();
|
|
33
141
|
this.watcher = watch(this.eventsDir, (_eventType, filename) => {
|
|
@@ -57,6 +165,52 @@ export class EventsWatcher {
|
|
|
57
165
|
this.knownFiles.clear();
|
|
58
166
|
log.logInfo("Events watcher stopped");
|
|
59
167
|
}
|
|
168
|
+
ensureHistoryFile() {
|
|
169
|
+
if (!this.options.historyPath) {
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
const historyDir = dirname(this.options.historyPath);
|
|
174
|
+
mkdirSync(historyDir, { recursive: true, mode: 0o700 });
|
|
175
|
+
writeFileSync(this.options.historyPath, "", { flag: "a", mode: 0o600 });
|
|
176
|
+
chmodSync(this.options.historyPath, 0o600);
|
|
177
|
+
}
|
|
178
|
+
catch (err) {
|
|
179
|
+
log.logWarning("Failed to initialize event history file", String(err));
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
appendHistory(record) {
|
|
183
|
+
if (!this.options.historyPath) {
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
const { filename, ...rest } = record;
|
|
187
|
+
const fullRecord = {
|
|
188
|
+
ts: formatLocalTimestamp(),
|
|
189
|
+
eventName: eventNameFromFilename(filename),
|
|
190
|
+
eventPath: resolve(this.eventsDir, filename),
|
|
191
|
+
...rest,
|
|
192
|
+
};
|
|
193
|
+
try {
|
|
194
|
+
this.ensureHistoryFile();
|
|
195
|
+
appendFileSync(this.options.historyPath, `${JSON.stringify(fullRecord)}\n`, "utf-8");
|
|
196
|
+
}
|
|
197
|
+
catch (err) {
|
|
198
|
+
log.logWarning("Failed to write event history", String(err));
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
appendEventHistory(filename, event, action, result, extra = {}) {
|
|
202
|
+
this.appendHistory({
|
|
203
|
+
filename,
|
|
204
|
+
eventType: event.type,
|
|
205
|
+
channelId: event.channelId,
|
|
206
|
+
action,
|
|
207
|
+
result,
|
|
208
|
+
textPreview: truncateTextPreview(event.text),
|
|
209
|
+
...(event.type === "one-shot" ? { at: event.at } : {}),
|
|
210
|
+
...(event.type === "periodic" ? { schedule: event.schedule, timezone: event.timezone } : {}),
|
|
211
|
+
...extra,
|
|
212
|
+
});
|
|
213
|
+
}
|
|
60
214
|
debounce(filename, fn) {
|
|
61
215
|
const existing = this.debounceTimers.get(filename);
|
|
62
216
|
if (existing) {
|
|
@@ -99,17 +253,35 @@ export class EventsWatcher {
|
|
|
99
253
|
log.logInfo(`Event file deleted: ${filename}`);
|
|
100
254
|
this.cancelScheduled(filename);
|
|
101
255
|
this.knownFiles.delete(filename);
|
|
256
|
+
this.appendHistory({
|
|
257
|
+
filename,
|
|
258
|
+
eventType: "unknown",
|
|
259
|
+
action: "deleted",
|
|
260
|
+
result: "ok",
|
|
261
|
+
});
|
|
102
262
|
}
|
|
103
263
|
cancelScheduled(filename) {
|
|
264
|
+
let cancelled = false;
|
|
104
265
|
const timer = this.timers.get(filename);
|
|
105
266
|
if (timer) {
|
|
106
267
|
clearTimeout(timer);
|
|
107
268
|
this.timers.delete(filename);
|
|
269
|
+
cancelled = true;
|
|
108
270
|
}
|
|
109
271
|
const cron = this.crons.get(filename);
|
|
110
272
|
if (cron) {
|
|
111
273
|
cron.stop();
|
|
112
274
|
this.crons.delete(filename);
|
|
275
|
+
cancelled = true;
|
|
276
|
+
}
|
|
277
|
+
if (cancelled) {
|
|
278
|
+
this.appendHistory({
|
|
279
|
+
filename,
|
|
280
|
+
eventType: "unknown",
|
|
281
|
+
action: "cancelled",
|
|
282
|
+
result: "ok",
|
|
283
|
+
reason: "event file changed or was removed",
|
|
284
|
+
});
|
|
113
285
|
}
|
|
114
286
|
}
|
|
115
287
|
async handleFile(filename) {
|
|
@@ -131,11 +303,19 @@ export class EventsWatcher {
|
|
|
131
303
|
}
|
|
132
304
|
if (!event) {
|
|
133
305
|
log.logWarning(`Failed to parse event file after ${MAX_RETRIES} retries: ${filename}`, lastError?.message);
|
|
306
|
+
this.appendHistory({
|
|
307
|
+
filename,
|
|
308
|
+
eventType: "unknown",
|
|
309
|
+
action: "invalid",
|
|
310
|
+
result: "error",
|
|
311
|
+
reason: lastError?.message ?? "Unknown event parse error",
|
|
312
|
+
});
|
|
134
313
|
this.markInvalid(filename, lastError?.message ?? "Unknown event parse error");
|
|
135
314
|
return;
|
|
136
315
|
}
|
|
137
316
|
this.knownFiles.add(filename);
|
|
138
317
|
this.clearInvalidMarker(filename);
|
|
318
|
+
this.appendEventHistory(filename, event, "loaded", "ok");
|
|
139
319
|
switch (event.type) {
|
|
140
320
|
case "immediate":
|
|
141
321
|
this.handleImmediate(filename, event);
|
|
@@ -148,62 +328,8 @@ export class EventsWatcher {
|
|
|
148
328
|
break;
|
|
149
329
|
}
|
|
150
330
|
}
|
|
151
|
-
parsePreAction(data, filename) {
|
|
152
|
-
if (!data.preAction)
|
|
153
|
-
return undefined;
|
|
154
|
-
if (typeof data.preAction !== "object" || data.preAction === null) {
|
|
155
|
-
throw new Error(`Invalid 'preAction' field in ${filename}, expected an object`);
|
|
156
|
-
}
|
|
157
|
-
const action = data.preAction;
|
|
158
|
-
if (action.type !== "bash") {
|
|
159
|
-
throw new Error(`Unsupported preAction type '${String(action.type)}' in ${filename}, only 'bash' is supported`);
|
|
160
|
-
}
|
|
161
|
-
if (typeof action.command !== "string" || action.command.trim().length === 0) {
|
|
162
|
-
throw new Error(`Missing or empty 'preAction.command' in ${filename}`);
|
|
163
|
-
}
|
|
164
|
-
if (action.timeout !== undefined) {
|
|
165
|
-
if (typeof action.timeout !== "number" || !Number.isFinite(action.timeout) || action.timeout <= 0) {
|
|
166
|
-
throw new Error(`Invalid 'preAction.timeout' in ${filename}, expected a positive millisecond value`);
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
return {
|
|
170
|
-
type: "bash",
|
|
171
|
-
command: action.command,
|
|
172
|
-
...(typeof action.timeout === "number" ? { timeout: action.timeout } : {}),
|
|
173
|
-
};
|
|
174
|
-
}
|
|
175
331
|
parseEvent(content, filename) {
|
|
176
|
-
|
|
177
|
-
if (!data.type || !data.channelId || !data.text) {
|
|
178
|
-
throw new Error(`Missing required fields (type, channelId, text) in ${filename}`);
|
|
179
|
-
}
|
|
180
|
-
const preAction = this.parsePreAction(data, filename);
|
|
181
|
-
switch (data.type) {
|
|
182
|
-
case "immediate":
|
|
183
|
-
return { type: "immediate", channelId: data.channelId, text: data.text, preAction };
|
|
184
|
-
case "one-shot":
|
|
185
|
-
if (!data.at) {
|
|
186
|
-
throw new Error(`Missing 'at' field for one-shot event in ${filename}`);
|
|
187
|
-
}
|
|
188
|
-
return { type: "one-shot", channelId: data.channelId, text: data.text, at: data.at, preAction };
|
|
189
|
-
case "periodic":
|
|
190
|
-
if (!data.schedule) {
|
|
191
|
-
throw new Error(`Missing 'schedule' field for periodic event in ${filename}`);
|
|
192
|
-
}
|
|
193
|
-
if (!data.timezone) {
|
|
194
|
-
throw new Error(`Missing 'timezone' field for periodic event in ${filename}`);
|
|
195
|
-
}
|
|
196
|
-
return {
|
|
197
|
-
type: "periodic",
|
|
198
|
-
channelId: data.channelId,
|
|
199
|
-
text: data.text,
|
|
200
|
-
schedule: data.schedule,
|
|
201
|
-
timezone: data.timezone,
|
|
202
|
-
preAction,
|
|
203
|
-
};
|
|
204
|
-
default:
|
|
205
|
-
throw new Error(`Unknown event type '${data.type}' in ${filename}`);
|
|
206
|
-
}
|
|
332
|
+
return parseScheduledEventContent(content, filename);
|
|
207
333
|
}
|
|
208
334
|
async handleImmediate(filename, event) {
|
|
209
335
|
const filePath = join(this.eventsDir, filename);
|
|
@@ -211,6 +337,7 @@ export class EventsWatcher {
|
|
|
211
337
|
const stat = statSync(filePath);
|
|
212
338
|
if (stat.mtimeMs < this.startTime) {
|
|
213
339
|
log.logInfo(`Stale immediate event, deleting: ${filename}`);
|
|
340
|
+
this.appendEventHistory(filename, event, "skipped", "skipped", { reason: "stale immediate event" });
|
|
214
341
|
this.deleteFile(filename);
|
|
215
342
|
return;
|
|
216
343
|
}
|
|
@@ -219,6 +346,7 @@ export class EventsWatcher {
|
|
|
219
346
|
return;
|
|
220
347
|
}
|
|
221
348
|
log.logInfo(`Executing immediate event: ${filename}`);
|
|
349
|
+
this.appendEventHistory(filename, event, "triggered", "ok");
|
|
222
350
|
await this.execute(filename, event);
|
|
223
351
|
}
|
|
224
352
|
handleOneShot(filename, event) {
|
|
@@ -226,29 +354,41 @@ export class EventsWatcher {
|
|
|
226
354
|
const now = Date.now();
|
|
227
355
|
if (!Number.isFinite(atTime)) {
|
|
228
356
|
log.logWarning(`Invalid one-shot time for ${filename}: ${event.at}`);
|
|
357
|
+
this.appendEventHistory(filename, event, "invalid", "error", { reason: `Invalid one-shot time: ${event.at}` });
|
|
229
358
|
this.markInvalid(filename, `Invalid one-shot time: ${event.at}`);
|
|
230
359
|
return;
|
|
231
360
|
}
|
|
232
361
|
if (atTime <= now) {
|
|
233
362
|
log.logInfo(`One-shot event in the past, deleting: ${filename}`);
|
|
363
|
+
this.appendEventHistory(filename, event, "skipped", "skipped", { reason: "one-shot event is in the past" });
|
|
234
364
|
this.deleteFile(filename);
|
|
235
365
|
return;
|
|
236
366
|
}
|
|
237
367
|
const delay = atTime - now;
|
|
238
368
|
if (delay > MAX_TIMEOUT_MS) {
|
|
239
369
|
log.logWarning(`One-shot event exceeds maximum supported delay for ${filename}: ${event.at}. Use a periodic cron event instead.`);
|
|
370
|
+
this.appendEventHistory(filename, event, "skipped", "skipped", {
|
|
371
|
+
reason: `One-shot event exceeds maximum supported delay: ${event.at}`,
|
|
372
|
+
});
|
|
240
373
|
this.markInvalid(filename, `One-shot event exceeds maximum supported delay: ${event.at}`);
|
|
241
374
|
return;
|
|
242
375
|
}
|
|
243
376
|
log.logInfo(`Scheduling one-shot event: ${filename} in ${Math.round(delay / 1000)}s`);
|
|
377
|
+
this.appendEventHistory(filename, event, "scheduled", "ok", {
|
|
378
|
+
nextRunAt: formatLocalTimestamp(new Date(atTime)),
|
|
379
|
+
});
|
|
244
380
|
const timer = setTimeout(async () => {
|
|
245
381
|
this.timers.delete(filename);
|
|
246
382
|
try {
|
|
247
383
|
log.logInfo(`Executing one-shot event: ${filename}`);
|
|
384
|
+
this.appendEventHistory(filename, event, "triggered", "ok");
|
|
248
385
|
await this.execute(filename, event);
|
|
249
386
|
}
|
|
250
387
|
catch (err) {
|
|
251
388
|
log.logWarning(`One-shot event execution failed: ${filename}`, String(err));
|
|
389
|
+
this.appendEventHistory(filename, event, "skipped", "error", {
|
|
390
|
+
reason: err instanceof Error ? err.message : String(err),
|
|
391
|
+
});
|
|
252
392
|
}
|
|
253
393
|
}, delay);
|
|
254
394
|
this.timers.set(filename, timer);
|
|
@@ -258,29 +398,64 @@ export class EventsWatcher {
|
|
|
258
398
|
const cron = new Cron(event.schedule, { timezone: event.timezone }, async () => {
|
|
259
399
|
try {
|
|
260
400
|
log.logInfo(`Executing periodic event: ${filename}`);
|
|
401
|
+
this.appendEventHistory(filename, event, "triggered", "ok");
|
|
261
402
|
await this.execute(filename, event, false);
|
|
262
403
|
}
|
|
263
404
|
catch (err) {
|
|
264
405
|
log.logWarning(`Periodic event execution failed: ${filename}`, String(err));
|
|
406
|
+
this.appendEventHistory(filename, event, "skipped", "error", {
|
|
407
|
+
reason: err instanceof Error ? err.message : String(err),
|
|
408
|
+
});
|
|
265
409
|
}
|
|
266
410
|
});
|
|
267
411
|
this.crons.set(filename, cron);
|
|
268
412
|
const next = cron.nextRun();
|
|
269
413
|
log.logInfo(`Scheduled periodic event: ${filename}, next run: ${next?.toISOString() ?? "unknown"}`);
|
|
414
|
+
this.appendEventHistory(filename, event, "scheduled", "ok", next ? { nextRunAt: formatLocalTimestamp(next) } : {});
|
|
270
415
|
}
|
|
271
416
|
catch (err) {
|
|
272
417
|
log.logWarning(`Invalid cron schedule for ${filename}: ${event.schedule}`, String(err));
|
|
418
|
+
this.appendEventHistory(filename, event, "invalid", "error", {
|
|
419
|
+
reason: `Invalid cron schedule: ${event.schedule}\n${String(err)}`,
|
|
420
|
+
});
|
|
273
421
|
this.markInvalid(filename, `Invalid cron schedule: ${event.schedule}\n${String(err)}`);
|
|
274
422
|
}
|
|
275
423
|
}
|
|
276
424
|
async execute(filename, event, deleteAfter = true) {
|
|
277
425
|
if (event.preAction) {
|
|
278
426
|
try {
|
|
279
|
-
|
|
427
|
+
this.appendEventHistory(filename, event, "pre_action_started", "ok", {
|
|
428
|
+
preAction: {
|
|
429
|
+
type: event.preAction.type,
|
|
430
|
+
command: event.preAction.command,
|
|
431
|
+
timeoutMs: event.preAction.timeout ?? DEFAULT_PRE_ACTION_TIMEOUT_MS,
|
|
432
|
+
},
|
|
433
|
+
});
|
|
434
|
+
const result = await this.runPreAction(event.preAction, filename);
|
|
435
|
+
this.appendEventHistory(filename, event, "pre_action_passed", "ok", {
|
|
436
|
+
preAction: {
|
|
437
|
+
type: event.preAction.type,
|
|
438
|
+
command: event.preAction.command,
|
|
439
|
+
timeoutMs: event.preAction.timeout ?? DEFAULT_PRE_ACTION_TIMEOUT_MS,
|
|
440
|
+
exitCode: result.exitCode,
|
|
441
|
+
durationMs: result.durationMs,
|
|
442
|
+
},
|
|
443
|
+
});
|
|
280
444
|
}
|
|
281
445
|
catch (err) {
|
|
282
446
|
const reason = err instanceof Error ? err.message : String(err);
|
|
283
447
|
log.logInfo(`Pre-action gate blocked event: ${filename} (${reason})`);
|
|
448
|
+
const actionResult = err instanceof EventPreActionError ? err : undefined;
|
|
449
|
+
this.appendEventHistory(filename, event, actionResult?.kind === "failed" ? "pre_action_failed" : "pre_action_blocked", actionResult?.kind === "failed" ? "error" : "skipped", {
|
|
450
|
+
reason,
|
|
451
|
+
preAction: {
|
|
452
|
+
type: event.preAction.type,
|
|
453
|
+
command: event.preAction.command,
|
|
454
|
+
timeoutMs: event.preAction.timeout ?? DEFAULT_PRE_ACTION_TIMEOUT_MS,
|
|
455
|
+
...(actionResult?.exitCode !== undefined ? { exitCode: actionResult.exitCode } : {}),
|
|
456
|
+
...(actionResult?.durationMs !== undefined ? { durationMs: actionResult.durationMs } : {}),
|
|
457
|
+
},
|
|
458
|
+
});
|
|
284
459
|
return;
|
|
285
460
|
}
|
|
286
461
|
}
|
|
@@ -310,6 +485,7 @@ export class EventsWatcher {
|
|
|
310
485
|
};
|
|
311
486
|
const enqueued = this.bot.enqueueEvent(syntheticEvent);
|
|
312
487
|
if (enqueued) {
|
|
488
|
+
this.appendEventHistory(filename, event, "enqueued", "ok", { queue: { accepted: true } });
|
|
313
489
|
if (deleteAfter) {
|
|
314
490
|
this.deleteFile(filename);
|
|
315
491
|
}
|
|
@@ -320,24 +496,43 @@ export class EventsWatcher {
|
|
|
320
496
|
// GC'd as "past" with no trace, so leave a visible error marker (and keep
|
|
321
497
|
// the source file) making the loss auditable rather than a silent hole.
|
|
322
498
|
log.logWarning(`Event queue full, could not enqueue: ${filename}`);
|
|
499
|
+
this.appendEventHistory(filename, event, "queue_full", "error", {
|
|
500
|
+
reason: "channel queue full",
|
|
501
|
+
queue: { accepted: false },
|
|
502
|
+
});
|
|
323
503
|
if (deleteAfter) {
|
|
324
504
|
this.markInvalid(filename, `Event queue was full at ${new Date().toISOString()}; this occurrence was not delivered.`);
|
|
325
505
|
}
|
|
326
506
|
}
|
|
327
507
|
async runPreAction(action, filename) {
|
|
508
|
+
const startedAt = Date.now();
|
|
328
509
|
if (this.commandGuardConfig?.enabled) {
|
|
329
510
|
const guardResult = guardCommand(action.command, this.commandGuardConfig);
|
|
330
511
|
if (!guardResult.allowed) {
|
|
331
512
|
log.logWarning(`Pre-action command blocked by guard for ${filename}: ${guardResult.reason}`);
|
|
332
|
-
throw new
|
|
513
|
+
throw new EventPreActionError("blocked", `guard: ${guardResult.reason}`, {
|
|
514
|
+
durationMs: Date.now() - startedAt,
|
|
515
|
+
});
|
|
333
516
|
}
|
|
334
517
|
}
|
|
335
|
-
const timeoutMs = action.timeout ??
|
|
518
|
+
const timeoutMs = action.timeout ?? DEFAULT_PRE_ACTION_TIMEOUT_MS;
|
|
336
519
|
const timeoutSeconds = Math.max(1, Math.ceil(timeoutMs / 1000));
|
|
337
|
-
|
|
520
|
+
let result;
|
|
521
|
+
try {
|
|
522
|
+
result = await this.executor.exec(action.command, { timeout: timeoutSeconds });
|
|
523
|
+
}
|
|
524
|
+
catch (err) {
|
|
525
|
+
throw new EventPreActionError("failed", err instanceof Error ? err.message : String(err), {
|
|
526
|
+
durationMs: Date.now() - startedAt,
|
|
527
|
+
});
|
|
528
|
+
}
|
|
338
529
|
if (result.code !== 0) {
|
|
339
|
-
throw new
|
|
530
|
+
throw new EventPreActionError("blocked", `exit ${result.code}`, {
|
|
531
|
+
exitCode: result.code,
|
|
532
|
+
durationMs: Date.now() - startedAt,
|
|
533
|
+
});
|
|
340
534
|
}
|
|
535
|
+
return { exitCode: result.code, durationMs: Date.now() - startedAt };
|
|
341
536
|
}
|
|
342
537
|
deleteFile(filename) {
|
|
343
538
|
const filePath = join(this.eventsDir, filename);
|
|
@@ -351,6 +546,12 @@ export class EventsWatcher {
|
|
|
351
546
|
}
|
|
352
547
|
this.clearInvalidMarker(filename);
|
|
353
548
|
this.knownFiles.delete(filename);
|
|
549
|
+
this.appendHistory({
|
|
550
|
+
filename,
|
|
551
|
+
eventType: "unknown",
|
|
552
|
+
action: "deleted",
|
|
553
|
+
result: "ok",
|
|
554
|
+
});
|
|
354
555
|
}
|
|
355
556
|
getInvalidMarkerPath(filename) {
|
|
356
557
|
return join(this.eventsDir, `${filename}.error.txt`);
|
|
@@ -382,7 +583,7 @@ export class EventsWatcher {
|
|
|
382
583
|
/**
|
|
383
584
|
* Create and start an events watcher.
|
|
384
585
|
*/
|
|
385
|
-
export function createEventsWatcher(workspaceDir, bot, executor, commandGuardConfig) {
|
|
586
|
+
export function createEventsWatcher(workspaceDir, bot, executor, commandGuardConfig, historyPath) {
|
|
386
587
|
const eventsDir = join(workspaceDir, "events");
|
|
387
|
-
return new EventsWatcher(eventsDir, bot, executor, commandGuardConfig);
|
|
588
|
+
return new EventsWatcher(eventsDir, bot, executor, commandGuardConfig, { historyPath });
|
|
388
589
|
}
|
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",
|
|
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
|
},
|