@oyasmi/pipiclaw 0.8.5 → 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.d.ts +1 -0
- package/dist/agent/channel-runner.js +27 -10
- package/dist/agent/command-extension.d.ts +1 -0
- package/dist/agent/command-extension.js +6 -0
- package/dist/agent/commands.js +6 -0
- package/dist/agent/session-events.js +17 -5
- package/dist/agent/types.d.ts +1 -0
- package/dist/log.d.ts +12 -20
- package/dist/log.js +195 -198
- package/dist/memory/bootstrap.d.ts +5 -0
- package/dist/memory/bootstrap.js +14 -4
- package/dist/memory/candidates.d.ts +2 -0
- package/dist/memory/candidates.js +13 -3
- package/dist/memory/commands.d.ts +6 -0
- package/dist/memory/commands.js +112 -0
- package/dist/memory/consolidation.d.ts +3 -0
- package/dist/memory/consolidation.js +68 -26
- package/dist/memory/files.d.ts +13 -0
- package/dist/memory/files.js +65 -8
- package/dist/memory/lifecycle.d.ts +2 -1
- package/dist/memory/lifecycle.js +38 -7
- package/dist/memory/maintenance-jobs.js +48 -23
- package/dist/memory/metadata.d.ts +60 -0
- package/dist/memory/metadata.js +135 -0
- package/dist/memory/policy.d.ts +3 -0
- package/dist/memory/policy.js +19 -0
- package/dist/memory/post-turn-review.d.ts +11 -1
- package/dist/memory/post-turn-review.js +78 -19
- package/dist/memory/promotion.d.ts +5 -2
- package/dist/memory/promotion.js +3 -1
- package/dist/memory/recall.d.ts +3 -0
- package/dist/memory/recall.js +27 -5
- package/dist/memory/review-log.d.ts +2 -0
- package/dist/memory/review-log.js +15 -0
- package/dist/memory/session-corpus.js +11 -3
- package/dist/memory/session-search.js +8 -4
- package/dist/memory/session.d.ts +1 -0
- package/dist/memory/session.js +3 -1
- package/dist/memory/sidecar-worker.d.ts +1 -0
- package/dist/memory/sidecar-worker.js +1 -0
- package/dist/memory/source-window.d.ts +25 -0
- package/dist/memory/source-window.js +64 -0
- package/dist/memory/tombstones.d.ts +12 -0
- package/dist/memory/tombstones.js +44 -0
- package/dist/memory/transcript.js +26 -3
- package/dist/runtime/bootstrap.d.ts +1 -0
- package/dist/runtime/bootstrap.js +42 -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/runtime/task-commands.js +1 -1
- package/dist/security/logger.d.ts +3 -1
- package/dist/security/logger.js +33 -10
- package/dist/settings.js +1 -1
- package/dist/shared/jsonl-appender.d.ts +27 -8
- package/dist/shared/jsonl-appender.js +128 -41
- package/dist/tasks/control.js +9 -3
- package/dist/tasks/store.d.ts +1 -0
- package/dist/tasks/store.js +11 -1
- package/dist/tools/bash.js +1 -1
- package/dist/tools/edit.js +1 -1
- package/dist/tools/grep.js +1 -1
- package/dist/tools/memory-manage.d.ts +1 -1
- package/dist/tools/memory-manage.js +27 -6
- package/dist/tools/read.js +1 -1
- package/dist/tools/task-manage.js +2 -2
- package/dist/tools/write-content.js +1 -1
- package/dist/tui/app.js +17 -0
- package/dist/usage/ledger.d.ts +4 -0
- package/dist/usage/ledger.js +3 -1
- package/dist/web/client.js +3 -3
- package/package.json +1 -1
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;
|
|
@@ -435,7 +435,7 @@ async function doctor(options) {
|
|
|
435
435
|
issues.push(issue(`tasks/${entry.id}.md points to missing related task ${relatedId}.`, `Create ${relatedId}, or remove it from parent/dependsOn with task_manage set.`));
|
|
436
436
|
}
|
|
437
437
|
}
|
|
438
|
-
if (control.sideEffects === "external" && control.externalApproval
|
|
438
|
+
if (control.sideEffects === "external" && control.externalApproval === "required") {
|
|
439
439
|
issues.push(issue(`tasks/${entry.id}.md requires external side effects but has no user approval.`, `After reviewing the proposed action, a user must run /tasks approve ${entry.id}.`));
|
|
440
440
|
}
|
|
441
441
|
if (control.externalApproval === "granted" &&
|
|
@@ -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
|
+
}
|
package/dist/settings.js
CHANGED
|
@@ -55,7 +55,7 @@ const DEFAULT_SESSION_MEMORY = {
|
|
|
55
55
|
const DEFAULT_MEMORY_GROWTH = {
|
|
56
56
|
postTurnReviewEnabled: true,
|
|
57
57
|
autoWriteChannelMemory: true,
|
|
58
|
-
autoWriteWorkspaceSkills:
|
|
58
|
+
autoWriteWorkspaceSkills: false,
|
|
59
59
|
minSkillAutoWriteConfidence: 0.9,
|
|
60
60
|
minMemoryAutoWriteConfidence: 0.85,
|
|
61
61
|
idleWritesHistory: false,
|
|
@@ -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;
|
|
@@ -1,15 +1,16 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { appendFile } from "node:fs/promises";
|
|
1
|
+
import { appendFile, mkdir, rename, rm, stat } from "node:fs/promises";
|
|
3
2
|
import { dirname } from "node:path";
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
const DEFAULT_MAX_PENDING_RECORDS = 2_000;
|
|
4
|
+
const DEFAULT_MAX_PENDING_BYTES = 8 * 1024 * 1024;
|
|
5
|
+
const DEFAULT_RESERVED_CRITICAL_RECORDS = 100;
|
|
6
|
+
const DEFAULT_RESERVED_CRITICAL_BYTES = 512 * 1024;
|
|
6
7
|
/**
|
|
7
|
-
*
|
|
8
|
+
* Bounded append-only JSONL writer shared by runtime logs, channel archives,
|
|
9
|
+
* audit logs, event history, and the usage ledger.
|
|
8
10
|
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* the next success) and never rejects.
|
|
11
|
+
* Records are ordered per resolved path. Different paths may write in parallel.
|
|
12
|
+
* Slow or failed observability storage never creates an unbounded in-memory
|
|
13
|
+
* backlog and never rejects into the business path.
|
|
13
14
|
*/
|
|
14
15
|
export function createJsonlAppender(options) {
|
|
15
16
|
if (!options.path && !options.pathFor) {
|
|
@@ -17,26 +18,41 @@ export function createJsonlAppender(options) {
|
|
|
17
18
|
}
|
|
18
19
|
const maxRotations = options.maxRotations ?? 3;
|
|
19
20
|
const mode = options.mode ?? 0o600;
|
|
20
|
-
const
|
|
21
|
+
const maxPendingRecords = options.maxPendingRecords ?? DEFAULT_MAX_PENDING_RECORDS;
|
|
22
|
+
const maxPendingBytes = options.maxPendingBytes ?? DEFAULT_MAX_PENDING_BYTES;
|
|
23
|
+
const reservedCriticalRecords = Math.min(Math.floor(maxPendingRecords / 10), options.reservedCriticalRecords ?? DEFAULT_RESERVED_CRITICAL_RECORDS);
|
|
24
|
+
const reservedCriticalBytes = Math.min(Math.floor(maxPendingBytes / 8), options.reservedCriticalBytes ?? DEFAULT_RESERVED_CRITICAL_BYTES);
|
|
25
|
+
const chains = new Map();
|
|
21
26
|
const sizes = new Map();
|
|
22
27
|
const ensuredDirs = new Set();
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
28
|
+
const pending = new Set();
|
|
29
|
+
let pendingBytes = 0;
|
|
30
|
+
let closed = false;
|
|
31
|
+
let warnedWrite = false;
|
|
32
|
+
let warnedDrop = false;
|
|
33
|
+
const fallbackWarning = (event, message) => {
|
|
34
|
+
try {
|
|
35
|
+
process.stdout.write(`${new Date().toISOString()} WARN ${event} ${message}\n`);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
// Logging fallback failures must not escape into the runtime.
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
const resolvePath = (now, record) => options.pathFor ? options.pathFor(now, record) : options.path;
|
|
42
|
+
const ensureDir = async (filePath) => {
|
|
26
43
|
const dir = dirname(filePath);
|
|
27
44
|
if (ensuredDirs.has(dir))
|
|
28
45
|
return;
|
|
29
|
-
|
|
46
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
30
47
|
ensuredDirs.add(dir);
|
|
31
48
|
};
|
|
32
|
-
const currentSize = (filePath) => {
|
|
49
|
+
const currentSize = async (filePath) => {
|
|
33
50
|
const cached = sizes.get(filePath);
|
|
34
51
|
if (cached !== undefined)
|
|
35
52
|
return cached;
|
|
36
53
|
let size = 0;
|
|
37
54
|
try {
|
|
38
|
-
|
|
39
|
-
size = statSync(filePath).size;
|
|
55
|
+
size = (await stat(filePath)).size;
|
|
40
56
|
}
|
|
41
57
|
catch {
|
|
42
58
|
size = 0;
|
|
@@ -44,43 +60,114 @@ export function createJsonlAppender(options) {
|
|
|
44
60
|
sizes.set(filePath, size);
|
|
45
61
|
return size;
|
|
46
62
|
};
|
|
47
|
-
const rotate = (filePath) => {
|
|
63
|
+
const rotate = async (filePath) => {
|
|
64
|
+
if (maxRotations <= 0) {
|
|
65
|
+
await rm(filePath, { force: true });
|
|
66
|
+
sizes.set(filePath, 0);
|
|
67
|
+
await options.onRotate?.(filePath);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
48
70
|
for (let i = maxRotations - 1; i >= 1; i--) {
|
|
49
71
|
const from = `${filePath}.${i}`;
|
|
50
|
-
|
|
51
|
-
|
|
72
|
+
const to = `${filePath}.${i + 1}`;
|
|
73
|
+
try {
|
|
74
|
+
await rm(to, { force: true });
|
|
75
|
+
await rename(from, to);
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
|
|
79
|
+
throw error;
|
|
52
80
|
}
|
|
53
81
|
}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
}
|
|
82
|
+
await rm(`${filePath}.1`, { force: true });
|
|
83
|
+
await rename(filePath, `${filePath}.1`);
|
|
57
84
|
sizes.set(filePath, 0);
|
|
85
|
+
await options.onRotate?.(filePath);
|
|
58
86
|
};
|
|
59
|
-
const write = async (filePath, line) => {
|
|
60
|
-
ensureDir(filePath);
|
|
61
|
-
const
|
|
62
|
-
if (options.maxSizeBytes && options.maxSizeBytes > 0) {
|
|
63
|
-
|
|
64
|
-
rotate(filePath);
|
|
65
|
-
}
|
|
87
|
+
const write = async (filePath, line, lineBytes) => {
|
|
88
|
+
await ensureDir(filePath);
|
|
89
|
+
const size = await currentSize(filePath);
|
|
90
|
+
if (options.maxSizeBytes && options.maxSizeBytes > 0 && size + lineBytes > options.maxSizeBytes && size > 0) {
|
|
91
|
+
await rotate(filePath);
|
|
66
92
|
}
|
|
67
93
|
await appendFile(filePath, line, { encoding: "utf-8", mode });
|
|
68
|
-
sizes.set(filePath, currentSize(filePath) + lineBytes);
|
|
94
|
+
sizes.set(filePath, (await currentSize(filePath)) + lineBytes);
|
|
69
95
|
};
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
const
|
|
73
|
-
|
|
96
|
+
const serialize = (record) => {
|
|
97
|
+
try {
|
|
98
|
+
const json = JSON.stringify(options.recordForWrite ? options.recordForWrite(record) : record);
|
|
99
|
+
if (json === undefined)
|
|
100
|
+
throw new Error("JSONL records must be JSON-serializable values");
|
|
101
|
+
const line = `${json}\n`;
|
|
102
|
+
return { filePath: resolvePath(new Date(), record), line, bytes: Buffer.byteLength(line) };
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
if (!warnedDrop) {
|
|
106
|
+
warnedDrop = true;
|
|
107
|
+
fallbackWarning("runtime.log_sink.dropped", "Failed to serialize JSONL record; record was dropped");
|
|
108
|
+
}
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
const enqueue = (record, priority) => {
|
|
113
|
+
if (closed)
|
|
114
|
+
return null;
|
|
115
|
+
const serialized = serialize(record);
|
|
116
|
+
if (!serialized)
|
|
117
|
+
return null;
|
|
118
|
+
const recordLimit = priority === "critical" ? maxPendingRecords : maxPendingRecords - reservedCriticalRecords;
|
|
119
|
+
const byteLimit = priority === "critical" ? maxPendingBytes : maxPendingBytes - reservedCriticalBytes;
|
|
120
|
+
if (pending.size >= recordLimit || pendingBytes + serialized.bytes > byteLimit) {
|
|
121
|
+
if (!warnedDrop) {
|
|
122
|
+
warnedDrop = true;
|
|
123
|
+
fallbackWarning("runtime.log_sink.dropped", "JSONL queue limit reached; record was dropped");
|
|
124
|
+
}
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
const previous = chains.get(serialized.filePath) ?? Promise.resolve();
|
|
128
|
+
const result = previous
|
|
129
|
+
.catch(() => undefined)
|
|
130
|
+
.then(async () => {
|
|
74
131
|
try {
|
|
75
|
-
await
|
|
76
|
-
|
|
132
|
+
await write(serialized.filePath, serialized.line, serialized.bytes);
|
|
133
|
+
warnedWrite = false;
|
|
77
134
|
}
|
|
78
|
-
catch
|
|
79
|
-
if (!
|
|
80
|
-
|
|
81
|
-
|
|
135
|
+
catch {
|
|
136
|
+
if (!warnedWrite) {
|
|
137
|
+
warnedWrite = true;
|
|
138
|
+
fallbackWarning("runtime.log_sink.failed", "Failed to append JSONL record; continuing without it");
|
|
82
139
|
}
|
|
83
140
|
}
|
|
141
|
+
});
|
|
142
|
+
const completion = result.finally(() => {
|
|
143
|
+
pending.delete(completion);
|
|
144
|
+
pendingBytes -= serialized.bytes;
|
|
145
|
+
if (chains.get(serialized.filePath) === completion)
|
|
146
|
+
chains.delete(serialized.filePath);
|
|
147
|
+
if (pending.size === 0)
|
|
148
|
+
warnedDrop = false;
|
|
149
|
+
});
|
|
150
|
+
chains.set(serialized.filePath, completion);
|
|
151
|
+
pending.add(completion);
|
|
152
|
+
pendingBytes += serialized.bytes;
|
|
153
|
+
return { ...serialized, completion };
|
|
154
|
+
};
|
|
155
|
+
const flush = async () => {
|
|
156
|
+
while (pending.size > 0) {
|
|
157
|
+
await Promise.allSettled([...pending]);
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
return {
|
|
161
|
+
async append(record, priority = "critical") {
|
|
162
|
+
await enqueue(record, priority)?.completion;
|
|
163
|
+
},
|
|
164
|
+
tryAppend(record, priority = "normal") {
|
|
165
|
+
return enqueue(record, priority) !== null;
|
|
166
|
+
},
|
|
167
|
+
flush,
|
|
168
|
+
async close() {
|
|
169
|
+
closed = true;
|
|
170
|
+
await flush();
|
|
84
171
|
},
|
|
85
172
|
};
|
|
86
173
|
}
|
package/dist/tasks/control.js
CHANGED
|
@@ -166,7 +166,11 @@ export function resetTaskControlForCycle(control, cycleId) {
|
|
|
166
166
|
nextAction: undefined,
|
|
167
167
|
lastOutcome: "pending",
|
|
168
168
|
blockedReason: undefined,
|
|
169
|
-
|
|
169
|
+
// A cycle invalidates a one-time grant, but preserves an explicit policy
|
|
170
|
+
// exemption for recurring automation.
|
|
171
|
+
externalApproval: control.sideEffects === "external" && control.externalApproval !== "not-required"
|
|
172
|
+
? "required"
|
|
173
|
+
: "not-required",
|
|
170
174
|
approvalBy: undefined,
|
|
171
175
|
approvedAt: undefined,
|
|
172
176
|
approvalBodyHash: undefined,
|
|
@@ -193,6 +197,7 @@ function patchPositive(current, value, field) {
|
|
|
193
197
|
export function applyTaskControlPatch(control, patch) {
|
|
194
198
|
const next = structuredClone(control);
|
|
195
199
|
const invalidatesApproval = control.externalApproval === "granted" && Object.keys(patch).length > 0;
|
|
200
|
+
const explicitlySetsExternalApproval = patch.externalApproval !== undefined;
|
|
196
201
|
if (patch.priority !== undefined)
|
|
197
202
|
next.priority = patch.priority;
|
|
198
203
|
if (patch.deadline?.trim() && !Number.isFinite(new Date(patch.deadline).getTime())) {
|
|
@@ -239,11 +244,12 @@ export function applyTaskControlPatch(control, patch) {
|
|
|
239
244
|
next.approvedAt = undefined;
|
|
240
245
|
next.approvalBodyHash = undefined;
|
|
241
246
|
}
|
|
242
|
-
if (
|
|
247
|
+
if (control.sideEffects !== "external" && next.sideEffects === "external" && !explicitlySetsExternalApproval) {
|
|
243
248
|
next.externalApproval = "required";
|
|
244
249
|
}
|
|
245
|
-
if (invalidatesApproval && next.sideEffects === "external")
|
|
250
|
+
if (invalidatesApproval && next.sideEffects === "external" && !explicitlySetsExternalApproval) {
|
|
246
251
|
next.externalApproval = "required";
|
|
252
|
+
}
|
|
247
253
|
if (next.externalApproval !== "granted") {
|
|
248
254
|
next.approvalBy = undefined;
|
|
249
255
|
next.approvedAt = undefined;
|
package/dist/tasks/store.d.ts
CHANGED
|
@@ -23,6 +23,7 @@ export declare function finishTaskAttempt(channelDir: string, id: string, result
|
|
|
23
23
|
costUsd: number;
|
|
24
24
|
wallTimeMinutes: number;
|
|
25
25
|
failed: boolean;
|
|
26
|
+
silent?: boolean;
|
|
26
27
|
finishedAt: Date;
|
|
27
28
|
}): Promise<void>;
|
|
28
29
|
export declare function escalateTask(channelDir: string, id: string, reason: string): Promise<boolean>;
|
package/dist/tasks/store.js
CHANGED
|
@@ -87,7 +87,17 @@ export async function finishTaskAttempt(channelDir, id, result) {
|
|
|
87
87
|
control.usage.costUsd += Math.max(0, result.costUsd);
|
|
88
88
|
control.usage.wallTimeMinutes += Math.max(0, result.wallTimeMinutes);
|
|
89
89
|
control.lastFinishedAt = result.finishedAt.toISOString();
|
|
90
|
-
if (result.
|
|
90
|
+
if (result.silent) {
|
|
91
|
+
// The driver claimed before dispatch to prevent concurrent work. A silent
|
|
92
|
+
// turn performed no task advancement, so retain its cost audit but not its
|
|
93
|
+
// attempt charge.
|
|
94
|
+
control.usage.attempts = Math.max(0, control.usage.attempts - 1);
|
|
95
|
+
if (control.lastOutcome === "running") {
|
|
96
|
+
control.lastOutcome = "pending";
|
|
97
|
+
control.blockedReason = undefined;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
else if (result.failed) {
|
|
91
101
|
control.lastOutcome = "failed";
|
|
92
102
|
control.blockedReason = "The previous agent run failed; inspect the runtime error before retrying.";
|
|
93
103
|
}
|
package/dist/tools/bash.js
CHANGED
|
@@ -96,7 +96,7 @@ export function createBashTool(executor, options = {}) {
|
|
|
96
96
|
if (securityConfig.enabled && securityConfig.commandGuard.enabled) {
|
|
97
97
|
const guardResult = guardCommand(command, securityConfig.commandGuard);
|
|
98
98
|
if (!guardResult.allowed) {
|
|
99
|
-
logSecurityEvent(securityContext.workspaceDir, securityConfig, {
|
|
99
|
+
await logSecurityEvent(securityContext.workspaceDir, securityConfig, {
|
|
100
100
|
type: "command",
|
|
101
101
|
tool: "bash",
|
|
102
102
|
channelId: options.channelId,
|
package/dist/tools/edit.js
CHANGED
|
@@ -128,7 +128,7 @@ export function createEditTool(executor, options = {}) {
|
|
|
128
128
|
if (securityConfig.enabled && securityConfig.pathGuard.enabled) {
|
|
129
129
|
const readGuard = guardPath(path, "read", { ...securityContext, config: securityConfig.pathGuard });
|
|
130
130
|
if (!readGuard.allowed) {
|
|
131
|
-
logSecurityEvent(securityContext.workspaceDir, securityConfig, {
|
|
131
|
+
await logSecurityEvent(securityContext.workspaceDir, securityConfig, {
|
|
132
132
|
type: "path",
|
|
133
133
|
tool: "edit",
|
|
134
134
|
channelId: options.channelId,
|
package/dist/tools/grep.js
CHANGED
|
@@ -152,7 +152,7 @@ export function createGrepTool(executor, options = {}) {
|
|
|
152
152
|
if (securityConfig.enabled && securityConfig.pathGuard.enabled) {
|
|
153
153
|
const guardResult = guardPath(searchPath, "read", { ...securityContext, config: securityConfig.pathGuard });
|
|
154
154
|
if (!guardResult.allowed) {
|
|
155
|
-
logSecurityEvent(securityContext.workspaceDir, securityConfig, {
|
|
155
|
+
await logSecurityEvent(securityContext.workspaceDir, securityConfig, {
|
|
156
156
|
type: "path",
|
|
157
157
|
tool: "grep",
|
|
158
158
|
channelId: options.channelId,
|