@oyasmi/pipiclaw 0.8.6 → 0.8.7-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/dist/agent/channel-runner.js +8 -2
- package/dist/agent/session-events.js +17 -5
- package/dist/log.d.ts +12 -20
- package/dist/log.js +195 -198
- package/dist/memory/lifecycle.js +4 -1
- package/dist/runtime/bootstrap.d.ts +1 -0
- package/dist/runtime/bootstrap.js +41 -11
- package/dist/runtime/dingtalk.js +19 -6
- package/dist/runtime/events.d.ts +2 -0
- package/dist/runtime/events.js +14 -7
- package/dist/runtime/store.d.ts +4 -6
- package/dist/runtime/store.js +44 -40
- package/dist/security/logger.d.ts +3 -1
- package/dist/security/logger.js +33 -10
- package/dist/shared/jsonl-appender.d.ts +27 -8
- package/dist/shared/jsonl-appender.js +128 -41
- package/dist/tools/bash.js +1 -1
- package/dist/tools/edit.js +1 -1
- package/dist/tools/grep.js +1 -1
- package/dist/tools/read.js +1 -1
- package/dist/tools/write-content.js +1 -1
- package/dist/tui/app.js +17 -0
- package/dist/usage/ledger.d.ts +2 -0
- package/dist/usage/ledger.js +3 -1
- package/dist/web/client.js +3 -3
- package/package.json +1 -1
|
@@ -11,6 +11,7 @@ import { ensureChannelMemoryFilesSync } from "../memory/files.js";
|
|
|
11
11
|
import { MemoryMaintenanceScheduler } from "../memory/scheduler.js";
|
|
12
12
|
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";
|
|
13
13
|
import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
|
|
14
|
+
import { flushSecurityLogs } from "../security/logger.js";
|
|
14
15
|
import { PipiclawSettingsManager } from "../settings.js";
|
|
15
16
|
import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
|
|
16
17
|
import { readActiveTasks } from "../shared/task-ledger.js";
|
|
@@ -122,6 +123,7 @@ const SECURITY_CONFIG_TEMPLATE = {
|
|
|
122
123
|
const SHUTDOWN_WAIT_MS = 15000;
|
|
123
124
|
const SHUTDOWN_FLUSH_WAIT_MS = 45000;
|
|
124
125
|
const SHUTDOWN_ABORT_WAIT_MS = 5000;
|
|
126
|
+
const SHUTDOWN_LOG_FLUSH_WAIT_MS = 10_000;
|
|
125
127
|
export const DEFAULT_BOOTSTRAP_PATHS = {
|
|
126
128
|
appName: APP_NAME,
|
|
127
129
|
appHomeDir: APP_HOME_DIR,
|
|
@@ -342,12 +344,14 @@ function waitForTasks(tasks, timeoutMs) {
|
|
|
342
344
|
if (tasks.length === 0) {
|
|
343
345
|
return Promise.resolve(true);
|
|
344
346
|
}
|
|
345
|
-
return Promise
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
347
|
+
return new Promise((resolve) => {
|
|
348
|
+
const timer = setTimeout(() => resolve(false), timeoutMs);
|
|
349
|
+
timer.unref?.();
|
|
350
|
+
void Promise.allSettled(tasks).then(() => {
|
|
351
|
+
clearTimeout(timer);
|
|
352
|
+
resolve(true);
|
|
353
|
+
});
|
|
354
|
+
});
|
|
351
355
|
}
|
|
352
356
|
function flushInactiveChannelMemory(channelRunners) {
|
|
353
357
|
const flushes = [];
|
|
@@ -487,7 +491,10 @@ export function createRuntimeContext(options) {
|
|
|
487
491
|
return { kind: "handled" };
|
|
488
492
|
}
|
|
489
493
|
if (mode === "followUp") {
|
|
490
|
-
log.
|
|
494
|
+
log.logEvent("info", "agent.turn.followup_queued", "Follow-up queued", {
|
|
495
|
+
ctx: { channelId: event.channelId, userName: event.userName },
|
|
496
|
+
fields: { messageLength: trimmedQueueText.length },
|
|
497
|
+
});
|
|
491
498
|
return { kind: "requeue", text: trimmedQueueText };
|
|
492
499
|
}
|
|
493
500
|
try {
|
|
@@ -506,7 +513,10 @@ export function createRuntimeContext(options) {
|
|
|
506
513
|
? "Queued as steer. I’ll apply it after the current tool step finishes."
|
|
507
514
|
: "Queued as steer. I’ll apply this after the current tool step finishes. Use `/followup <message>` to queue it after completion.";
|
|
508
515
|
await bot.sendPlain(event.channelId, confirmation);
|
|
509
|
-
log.
|
|
516
|
+
log.logEvent("info", "agent.turn.steer_queued", "Steer queued", {
|
|
517
|
+
ctx: { channelId: event.channelId, userName: event.userName },
|
|
518
|
+
fields: { messageLength: trimmedQueueText.length },
|
|
519
|
+
});
|
|
510
520
|
return { kind: "handled" };
|
|
511
521
|
}
|
|
512
522
|
catch (err) {
|
|
@@ -546,7 +556,10 @@ export function createRuntimeContext(options) {
|
|
|
546
556
|
const ctx = createDingTalkContext(event, bot, store);
|
|
547
557
|
const builtInCommand = parseBuiltInCommand(event.text);
|
|
548
558
|
if (builtInCommand) {
|
|
549
|
-
log.
|
|
559
|
+
log.logEvent("info", "runtime.command.started", "Executing command", {
|
|
560
|
+
ctx: { channelId: event.channelId, userName: event.userName },
|
|
561
|
+
fields: { command: builtInCommand.name },
|
|
562
|
+
});
|
|
550
563
|
if (builtInCommand.name === "events") {
|
|
551
564
|
await handler.handleEventsCommand(event, bot, builtInCommand.args);
|
|
552
565
|
return;
|
|
@@ -576,7 +589,10 @@ export function createRuntimeContext(options) {
|
|
|
576
589
|
await bot.sendPlain(event.channelId, formatUnknownCommandMessage(name));
|
|
577
590
|
return;
|
|
578
591
|
}
|
|
579
|
-
log.
|
|
592
|
+
log.logEvent("info", "agent.turn.started", "Starting turn", {
|
|
593
|
+
ctx: { channelId: event.channelId, userName: event.userName },
|
|
594
|
+
fields: { messageLength: event.text.length, source: _isEvent ? "event" : "message" },
|
|
595
|
+
});
|
|
580
596
|
if (!_isEvent) {
|
|
581
597
|
ctx.primeCard(350);
|
|
582
598
|
}
|
|
@@ -597,7 +613,10 @@ export function createRuntimeContext(options) {
|
|
|
597
613
|
}
|
|
598
614
|
}
|
|
599
615
|
catch (err) {
|
|
600
|
-
log.
|
|
616
|
+
log.logEvent("error", "agent.turn.failed", "Turn failed", {
|
|
617
|
+
ctx: { channelId: event.channelId, userName: event.userName },
|
|
618
|
+
fields: { error: errorMessage(err) },
|
|
619
|
+
});
|
|
601
620
|
}
|
|
602
621
|
finally {
|
|
603
622
|
await durableDispatch?.markCompleted(event.dispatchId);
|
|
@@ -728,6 +747,17 @@ export function createRuntimeContext(options) {
|
|
|
728
747
|
modelsConfigPath: options.paths.modelsConfigPath,
|
|
729
748
|
}, channelDir);
|
|
730
749
|
}
|
|
750
|
+
const storageFlushes = [
|
|
751
|
+
store.close(),
|
|
752
|
+
getUsageLedger().flush?.() ?? Promise.resolve(),
|
|
753
|
+
flushSecurityLogs(),
|
|
754
|
+
...(eventsWatcher.flush ? [eventsWatcher.flush()] : []),
|
|
755
|
+
];
|
|
756
|
+
const storageFlushed = await waitForTasks(storageFlushes, SHUTDOWN_LOG_FLUSH_WAIT_MS);
|
|
757
|
+
if (!storageFlushed) {
|
|
758
|
+
log.logWarning(`Shutdown log flush exceeded ${SHUTDOWN_LOG_FLUSH_WAIT_MS}ms`);
|
|
759
|
+
}
|
|
760
|
+
await waitForTasks([log.flushLogging()], SHUTDOWN_LOG_FLUSH_WAIT_MS);
|
|
731
761
|
})();
|
|
732
762
|
return shutdownPromise;
|
|
733
763
|
};
|
package/dist/runtime/dingtalk.js
CHANGED
|
@@ -335,7 +335,9 @@ export class DingTalkBot {
|
|
|
335
335
|
if (!this.config.cardTemplateId) {
|
|
336
336
|
log.logWarning("DingTalk: cardTemplateId not configured — AI Card streaming will not work");
|
|
337
337
|
}
|
|
338
|
-
log.
|
|
338
|
+
log.logEvent("info", "runtime.dingtalk.connecting", "Initializing stream client", {
|
|
339
|
+
fields: { clientIdPrefix: this.config.clientId.substring(0, 8) },
|
|
340
|
+
});
|
|
339
341
|
this.clearAllTimers();
|
|
340
342
|
const clientOptions = {
|
|
341
343
|
clientId: this.config.clientId,
|
|
@@ -390,7 +392,9 @@ export class DingTalkBot {
|
|
|
390
392
|
this.clearKeepAliveTimer();
|
|
391
393
|
if (!immediate && this.reconnectAttempts > 0) {
|
|
392
394
|
const delay = Math.min(1000 * 2 ** this.reconnectAttempts + Math.random() * 1000, 30000);
|
|
393
|
-
log.
|
|
395
|
+
log.logEvent("info", "runtime.dingtalk.reconnect_scheduled", "Reconnect scheduled", {
|
|
396
|
+
fields: { delayMs: delay },
|
|
397
|
+
});
|
|
394
398
|
await this.waitForDelay(delay);
|
|
395
399
|
if (this.isStopped || !this.client) {
|
|
396
400
|
this.isReconnecting = false;
|
|
@@ -409,7 +413,7 @@ export class DingTalkBot {
|
|
|
409
413
|
await this.connectWithTimeout();
|
|
410
414
|
this.lastSocketAvailableTime = Date.now();
|
|
411
415
|
this.reconnectAttempts = 0; // Success, reset backoff
|
|
412
|
-
log.
|
|
416
|
+
log.logEvent("info", "runtime.dingtalk.stream_connected", "Connected to stream");
|
|
413
417
|
if (!this.hasReportedReady) {
|
|
414
418
|
log.logConnected();
|
|
415
419
|
this.hasReportedReady = true;
|
|
@@ -510,10 +514,16 @@ export class DingTalkBot {
|
|
|
510
514
|
}
|
|
511
515
|
const queue = this.getQueue(event.channelId);
|
|
512
516
|
if (queue.size() >= 5) {
|
|
513
|
-
log.
|
|
517
|
+
log.logEvent("warn", "runtime.channel_queue.full", "Discarding incoming event", {
|
|
518
|
+
ctx: { channelId: event.channelId, userName: event.userName },
|
|
519
|
+
fields: { messageLength: event.text.length },
|
|
520
|
+
});
|
|
514
521
|
return false;
|
|
515
522
|
}
|
|
516
|
-
log.
|
|
523
|
+
log.logEvent("debug", "runtime.channel_queue.enqueued", "Incoming event queued", {
|
|
524
|
+
ctx: { channelId: event.channelId, userName: event.userName },
|
|
525
|
+
fields: { messageLength: event.text.length },
|
|
526
|
+
});
|
|
517
527
|
queue.enqueue(async () => {
|
|
518
528
|
this.activeMessageProcessing = true;
|
|
519
529
|
try {
|
|
@@ -915,7 +925,10 @@ export class DingTalkBot {
|
|
|
915
925
|
}
|
|
916
926
|
// Determine channel ID
|
|
917
927
|
const channelId = conversationType === "2" ? `group_${conversationId}` : `dm_${senderId}`;
|
|
918
|
-
log.
|
|
928
|
+
log.logEvent("info", "runtime.dingtalk.message_received", "Accepted incoming message", {
|
|
929
|
+
ctx: { channelId, userName: senderName },
|
|
930
|
+
fields: { messageType: conversationType === "2" ? "group" : "dm", messageLength: content.length },
|
|
931
|
+
});
|
|
919
932
|
// Cache conversation metadata for card creation
|
|
920
933
|
this.setConversationMeta(channelId, {
|
|
921
934
|
conversationId,
|
package/dist/runtime/events.d.ts
CHANGED
|
@@ -74,9 +74,11 @@ export declare class EventsWatcher {
|
|
|
74
74
|
private startTime;
|
|
75
75
|
private watcher;
|
|
76
76
|
private knownFiles;
|
|
77
|
+
private readonly historyAppender?;
|
|
77
78
|
constructor(eventsDir: string, bot: DingTalkBot, executor: Executor, commandGuardConfig?: SecurityConfig["commandGuard"] | undefined, options?: EventsWatcherOptions);
|
|
78
79
|
start(): void;
|
|
79
80
|
stop(): void;
|
|
81
|
+
flush(): Promise<void>;
|
|
80
82
|
private ensureHistoryFile;
|
|
81
83
|
private appendHistory;
|
|
82
84
|
private appendEventHistory;
|
package/dist/runtime/events.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { Cron } from "croner";
|
|
2
|
-
import {
|
|
2
|
+
import { chmodSync, existsSync, mkdirSync, readdirSync, statSync, unlinkSync, watch, writeFileSync, } from "fs";
|
|
3
3
|
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 { createJsonlAppender } from "../shared/jsonl-appender.js";
|
|
7
8
|
import { errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
|
|
8
9
|
// ============================================================================
|
|
9
10
|
// EventsWatcher
|
|
@@ -128,6 +129,13 @@ export class EventsWatcher {
|
|
|
128
129
|
this.watcher = null;
|
|
129
130
|
this.knownFiles = new Set();
|
|
130
131
|
this.startTime = Date.now();
|
|
132
|
+
this.historyAppender = options.historyPath
|
|
133
|
+
? createJsonlAppender({
|
|
134
|
+
path: options.historyPath,
|
|
135
|
+
maxPendingRecords: 4_000,
|
|
136
|
+
maxPendingBytes: 8 * 1024 * 1024,
|
|
137
|
+
})
|
|
138
|
+
: undefined;
|
|
131
139
|
}
|
|
132
140
|
start() {
|
|
133
141
|
if (!existsSync(this.eventsDir)) {
|
|
@@ -163,6 +171,9 @@ export class EventsWatcher {
|
|
|
163
171
|
this.knownFiles.clear();
|
|
164
172
|
log.logInfo("Events watcher stopped");
|
|
165
173
|
}
|
|
174
|
+
async flush() {
|
|
175
|
+
await this.historyAppender?.flush();
|
|
176
|
+
}
|
|
166
177
|
ensureHistoryFile() {
|
|
167
178
|
if (!this.options.historyPath) {
|
|
168
179
|
return;
|
|
@@ -188,12 +199,8 @@ export class EventsWatcher {
|
|
|
188
199
|
eventPath: resolve(this.eventsDir, filename),
|
|
189
200
|
...rest,
|
|
190
201
|
};
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
appendFileSync(this.options.historyPath, `${JSON.stringify(fullRecord)}\n`, "utf-8");
|
|
194
|
-
}
|
|
195
|
-
catch (err) {
|
|
196
|
-
log.logWarning("Failed to write event history", String(err));
|
|
202
|
+
if (!this.historyAppender?.tryAppend(fullRecord, "critical")) {
|
|
203
|
+
log.logWarning("Failed to queue event history", "Retry after pending event history writes drain");
|
|
197
204
|
}
|
|
198
205
|
}
|
|
199
206
|
appendEventHistory(filename, event, action, result, extra = {}) {
|
package/dist/runtime/store.d.ts
CHANGED
|
@@ -46,7 +46,8 @@ export declare class ChannelStore {
|
|
|
46
46
|
private workingDir;
|
|
47
47
|
private recentlyLogged;
|
|
48
48
|
private cleanupTimer;
|
|
49
|
-
private
|
|
49
|
+
private archiveAppender;
|
|
50
|
+
private closed;
|
|
50
51
|
constructor(config: ChannelStoreConfig);
|
|
51
52
|
/**
|
|
52
53
|
* Get or create the directory for a channel/DM
|
|
@@ -59,15 +60,12 @@ export declare class ChannelStore {
|
|
|
59
60
|
*/
|
|
60
61
|
logMessage(channelId: string, message: LoggedMessage): Promise<boolean>;
|
|
61
62
|
logSubAgentRun(channelId: string, run: LoggedSubAgentRun): Promise<void>;
|
|
62
|
-
/**
|
|
63
|
-
* Rotate log file if it exceeds 1MB.
|
|
64
|
-
* Keeps one backup (log.jsonl.1) and resets the sync offset.
|
|
65
|
-
*/
|
|
66
|
-
private rotateIfNeeded;
|
|
67
63
|
/**
|
|
68
64
|
* Log a bot response
|
|
69
65
|
*/
|
|
70
66
|
logBotResponse(channelId: string, text: string, ts: string): Promise<void>;
|
|
67
|
+
flush(): Promise<void>;
|
|
68
|
+
close(): Promise<void>;
|
|
71
69
|
private startCleanupTimer;
|
|
72
70
|
private cleanupExpiredEntries;
|
|
73
71
|
}
|
package/dist/runtime/store.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { existsSync, mkdirSync
|
|
2
|
-
import {
|
|
3
|
-
import { dirname, join } from "path";
|
|
4
|
-
import {
|
|
1
|
+
import { existsSync, mkdirSync } from "fs";
|
|
2
|
+
import { writeFile } from "fs/promises";
|
|
3
|
+
import { basename, dirname, join } from "path";
|
|
4
|
+
import { createJsonlAppender } from "../shared/jsonl-appender.js";
|
|
5
5
|
import { ensureChannelDir } from "./channel-paths.js";
|
|
6
6
|
const MAX_LOG_SIZE_BYTES = 1_000_000;
|
|
7
7
|
const DEDUPE_TTL_MS = 60_000;
|
|
@@ -10,8 +10,24 @@ export class ChannelStore {
|
|
|
10
10
|
constructor(config) {
|
|
11
11
|
this.recentlyLogged = new Map();
|
|
12
12
|
this.cleanupTimer = null;
|
|
13
|
-
this.
|
|
13
|
+
this.closed = false;
|
|
14
14
|
this.workingDir = config.workingDir;
|
|
15
|
+
this.archiveAppender = createJsonlAppender({
|
|
16
|
+
pathFor: (_now, record) => record.filePath,
|
|
17
|
+
recordForWrite: (record) => record.value,
|
|
18
|
+
maxSizeBytes: MAX_LOG_SIZE_BYTES,
|
|
19
|
+
maxRotations: 1,
|
|
20
|
+
onRotate: async (filePath) => {
|
|
21
|
+
if (basename(filePath) !== "log.jsonl")
|
|
22
|
+
return;
|
|
23
|
+
try {
|
|
24
|
+
await writeFile(join(dirname(filePath), ".sync-offset"), "0", "utf-8");
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
// A stale sync offset only causes the cold-storage importer to rescan.
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
});
|
|
15
31
|
// Ensure working directory exists
|
|
16
32
|
if (!existsSync(this.workingDir)) {
|
|
17
33
|
mkdirSync(this.workingDir, { recursive: true });
|
|
@@ -29,6 +45,9 @@ export class ChannelStore {
|
|
|
29
45
|
* Returns false if message was already logged (duplicate)
|
|
30
46
|
*/
|
|
31
47
|
async logMessage(channelId, message) {
|
|
48
|
+
if (this.closed) {
|
|
49
|
+
throw new Error("Channel archive is closed. Retry after the runtime has restarted.");
|
|
50
|
+
}
|
|
32
51
|
const dedupeKey = `${channelId}:${message.ts}`;
|
|
33
52
|
const now = Date.now();
|
|
34
53
|
const previousLogTime = this.recentlyLogged.get(dedupeKey);
|
|
@@ -38,49 +57,23 @@ export class ChannelStore {
|
|
|
38
57
|
}
|
|
39
58
|
this.recentlyLogged.delete(dedupeKey);
|
|
40
59
|
}
|
|
41
|
-
this.recentlyLogged.set(dedupeKey, now);
|
|
42
|
-
this.startCleanupTimer();
|
|
43
60
|
const logPath = join(this.getChannelDir(channelId), "log.jsonl");
|
|
44
61
|
if (!message.date) {
|
|
45
62
|
message.date = new Date().toISOString();
|
|
46
63
|
}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
64
|
+
if (!this.archiveAppender.tryAppend({ filePath: logPath, value: message }, "critical")) {
|
|
65
|
+
throw new Error("Channel archive queue is full. Retry this message after pending log writes drain.");
|
|
66
|
+
}
|
|
67
|
+
this.recentlyLogged.set(dedupeKey, now);
|
|
68
|
+
this.startCleanupTimer();
|
|
52
69
|
return true;
|
|
53
70
|
}
|
|
54
71
|
async logSubAgentRun(channelId, run) {
|
|
72
|
+
if (this.closed)
|
|
73
|
+
return;
|
|
55
74
|
const logPath = join(this.getChannelDir(channelId), "subagent-runs.jsonl");
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
const line = `${JSON.stringify(run)}\n`;
|
|
59
|
-
await appendFile(logPath, line, "utf-8");
|
|
60
|
-
});
|
|
61
|
-
}
|
|
62
|
-
/**
|
|
63
|
-
* Rotate log file if it exceeds 1MB.
|
|
64
|
-
* Keeps one backup (log.jsonl.1) and resets the sync offset.
|
|
65
|
-
*/
|
|
66
|
-
async rotateIfNeeded(logPath) {
|
|
67
|
-
try {
|
|
68
|
-
if (!existsSync(logPath))
|
|
69
|
-
return;
|
|
70
|
-
const stats = statSync(logPath);
|
|
71
|
-
if (stats.size > MAX_LOG_SIZE_BYTES) {
|
|
72
|
-
renameSync(logPath, `${logPath}.1`);
|
|
73
|
-
const syncOffsetPath = join(dirname(logPath), ".sync-offset");
|
|
74
|
-
try {
|
|
75
|
-
await writeFile(syncOffsetPath, "0", "utf-8");
|
|
76
|
-
}
|
|
77
|
-
catch {
|
|
78
|
-
/* ignore */
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
catch {
|
|
83
|
-
// Ignore rotation errors
|
|
75
|
+
if (!this.archiveAppender.tryAppend({ filePath: logPath, value: run })) {
|
|
76
|
+
throw new Error("Sub-agent archive queue is full. Retry after pending log writes drain.");
|
|
84
77
|
}
|
|
85
78
|
}
|
|
86
79
|
/**
|
|
@@ -95,6 +88,17 @@ export class ChannelStore {
|
|
|
95
88
|
isBot: true,
|
|
96
89
|
});
|
|
97
90
|
}
|
|
91
|
+
async flush() {
|
|
92
|
+
await this.archiveAppender.flush();
|
|
93
|
+
}
|
|
94
|
+
async close() {
|
|
95
|
+
this.closed = true;
|
|
96
|
+
if (this.cleanupTimer) {
|
|
97
|
+
clearInterval(this.cleanupTimer);
|
|
98
|
+
this.cleanupTimer = null;
|
|
99
|
+
}
|
|
100
|
+
await this.archiveAppender.close();
|
|
101
|
+
}
|
|
98
102
|
startCleanupTimer() {
|
|
99
103
|
if (this.cleanupTimer) {
|
|
100
104
|
return;
|
|
@@ -1,2 +1,4 @@
|
|
|
1
1
|
import type { SecurityConfig, SecurityLogEvent } from "./types.js";
|
|
2
|
-
|
|
2
|
+
/** Persist a blocked operation without synchronously stalling the Node event loop. */
|
|
3
|
+
export declare function logSecurityEvent(workspaceDir: string, config: SecurityConfig, event: SecurityLogEvent): Promise<void>;
|
|
4
|
+
export declare function flushSecurityLogs(): Promise<void>;
|
package/dist/security/logger.js
CHANGED
|
@@ -1,18 +1,41 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { createJsonlAppender } from "../shared/jsonl-appender.js";
|
|
3
|
+
const AUDIT_WRITE_TIMEOUT_MS = 1_000;
|
|
4
|
+
const appenders = new Map();
|
|
3
5
|
function getLogPath(workspaceDir, config) {
|
|
4
6
|
return config.audit.logFile?.trim() ? config.audit.logFile : join(workspaceDir, ".pipiclaw", "security.log");
|
|
5
7
|
}
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
8
|
+
function getAppender(path) {
|
|
9
|
+
let appender = appenders.get(path);
|
|
10
|
+
if (!appender) {
|
|
11
|
+
appender = createJsonlAppender({
|
|
12
|
+
path,
|
|
13
|
+
maxPendingRecords: 4_000,
|
|
14
|
+
maxPendingBytes: 16 * 1024 * 1024,
|
|
15
|
+
});
|
|
16
|
+
appenders.set(path, appender);
|
|
9
17
|
}
|
|
10
|
-
|
|
18
|
+
return appender;
|
|
19
|
+
}
|
|
20
|
+
/** Persist a blocked operation without synchronously stalling the Node event loop. */
|
|
21
|
+
export async function logSecurityEvent(workspaceDir, config, event) {
|
|
22
|
+
if (!config.audit.logBlocked)
|
|
23
|
+
return;
|
|
24
|
+
let timer;
|
|
11
25
|
try {
|
|
12
|
-
|
|
13
|
-
|
|
26
|
+
await Promise.race([
|
|
27
|
+
getAppender(getLogPath(workspaceDir, config)).append({ date: new Date().toISOString(), ...event }),
|
|
28
|
+
new Promise((resolve) => {
|
|
29
|
+
timer = setTimeout(resolve, AUDIT_WRITE_TIMEOUT_MS);
|
|
30
|
+
timer.unref?.();
|
|
31
|
+
}),
|
|
32
|
+
]);
|
|
14
33
|
}
|
|
15
|
-
|
|
16
|
-
|
|
34
|
+
finally {
|
|
35
|
+
if (timer)
|
|
36
|
+
clearTimeout(timer);
|
|
17
37
|
}
|
|
18
38
|
}
|
|
39
|
+
export async function flushSecurityLogs() {
|
|
40
|
+
await Promise.allSettled([...appenders.values()].map((appender) => appender.flush()));
|
|
41
|
+
}
|
|
@@ -1,25 +1,44 @@
|
|
|
1
|
+
export type JsonlPriority = "normal" | "critical";
|
|
1
2
|
export interface JsonlAppenderOptions {
|
|
2
3
|
/** Fixed target file. Mutually exclusive with `pathFor`. */
|
|
3
4
|
path?: string;
|
|
4
5
|
/** Resolve the target file per append (e.g. monthly ledger files). */
|
|
5
|
-
pathFor?: (now: Date) => string;
|
|
6
|
+
pathFor?: (now: Date, record: unknown) => string;
|
|
7
|
+
/** Transform an internal routing envelope into the value written to JSON. */
|
|
8
|
+
recordForWrite?: (record: unknown) => unknown;
|
|
6
9
|
/** Rotate when the file would exceed this size (bytes). Omit to disable. */
|
|
7
10
|
maxSizeBytes?: number;
|
|
8
11
|
/** Number of rotated backups to keep (`.1`..`.N`). Default 3. */
|
|
9
12
|
maxRotations?: number;
|
|
10
13
|
/** File mode for created files. Default 0o600. */
|
|
11
14
|
mode?: number;
|
|
15
|
+
/** Maximum accepted records waiting for disk. Default 2,000. */
|
|
16
|
+
maxPendingRecords?: number;
|
|
17
|
+
/** Maximum accepted UTF-8 bytes waiting for disk. Default 8 MiB. */
|
|
18
|
+
maxPendingBytes?: number;
|
|
19
|
+
/** Capacity unavailable to normal records, reserved for critical records. */
|
|
20
|
+
reservedCriticalRecords?: number;
|
|
21
|
+
/** Byte capacity unavailable to normal records, reserved for critical records. */
|
|
22
|
+
reservedCriticalBytes?: number;
|
|
23
|
+
/** Optional work that must follow a successful rotation in the same file queue. */
|
|
24
|
+
onRotate?: (filePath: string) => Promise<void>;
|
|
12
25
|
}
|
|
13
26
|
export interface JsonlAppender {
|
|
14
|
-
/**
|
|
15
|
-
append(record: unknown): Promise<void>;
|
|
27
|
+
/** Queue and await one record. Never throws; a full or closed writer drops it. */
|
|
28
|
+
append(record: unknown, priority?: JsonlPriority): Promise<void>;
|
|
29
|
+
/** Queue one record without waiting for disk. Returns false when it cannot be accepted. */
|
|
30
|
+
tryAppend(record: unknown, priority?: JsonlPriority): boolean;
|
|
31
|
+
/** Wait until every currently accepted record has finished. */
|
|
32
|
+
flush(): Promise<void>;
|
|
33
|
+
/** Stop accepting records and drain the queue. */
|
|
34
|
+
close(): Promise<void>;
|
|
16
35
|
}
|
|
17
36
|
/**
|
|
18
|
-
*
|
|
37
|
+
* Bounded append-only JSONL writer shared by runtime logs, channel archives,
|
|
38
|
+
* audit logs, event history, and the usage ledger.
|
|
19
39
|
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
* the next success) and never rejects.
|
|
40
|
+
* Records are ordered per resolved path. Different paths may write in parallel.
|
|
41
|
+
* Slow or failed observability storage never creates an unbounded in-memory
|
|
42
|
+
* backlog and never rejects into the business path.
|
|
24
43
|
*/
|
|
25
44
|
export declare function createJsonlAppender(options: JsonlAppenderOptions): JsonlAppender;
|