@oyasmi/pipiclaw 0.7.0-beta.1 → 0.7.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 +14 -0
- package/dist/agent/channel-runner.js +139 -6
- package/dist/agent/commands.d.ts +1 -1
- package/dist/agent/commands.js +6 -0
- package/dist/agent/model-fallback.d.ts +64 -0
- package/dist/agent/model-fallback.js +125 -0
- package/dist/agent/session-events.d.ts +2 -0
- package/dist/agent/session-events.js +31 -12
- package/dist/agent/types.d.ts +7 -0
- package/dist/agent/types.js +8 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/log.d.ts +25 -0
- package/dist/log.js +105 -1
- package/dist/memory/consolidation.d.ts +1 -0
- package/dist/memory/consolidation.js +8 -3
- package/dist/memory/lifecycle.js +2 -0
- package/dist/memory/maintenance-jobs.js +1 -0
- package/dist/memory/post-turn-review.js +1 -0
- package/dist/memory/recall.d.ts +1 -0
- package/dist/memory/recall.js +1 -0
- package/dist/memory/session-search.d.ts +1 -0
- package/dist/memory/session-search.js +1 -0
- package/dist/memory/session.d.ts +1 -0
- package/dist/memory/session.js +1 -0
- package/dist/memory/sidecar-worker.d.ts +4 -0
- package/dist/memory/sidecar-worker.js +29 -0
- package/dist/paths.d.ts +3 -0
- package/dist/paths.js +3 -0
- package/dist/runtime/bootstrap.js +19 -3
- package/dist/runtime/dingtalk.d.ts +1 -0
- package/dist/runtime/dingtalk.js +4 -0
- package/dist/sandbox.js +7 -77
- package/dist/security/command-guard.js +0 -4
- package/dist/security/path-guard.js +0 -4
- package/dist/settings.d.ts +19 -0
- package/dist/settings.js +32 -0
- package/dist/shared/jsonl-appender.d.ts +25 -0
- package/dist/shared/jsonl-appender.js +85 -0
- package/dist/shared/shell-escape.d.ts +0 -7
- package/dist/shared/shell-escape.js +0 -11
- package/dist/subagents/tool.js +1 -0
- package/dist/tools/bash.js +2 -2
- package/dist/tools/edit.js +2 -2
- package/dist/tools/read.js +6 -6
- package/dist/tools/registry.js +1 -0
- package/dist/tools/session-search.d.ts +1 -0
- package/dist/tools/session-search.js +1 -0
- package/dist/tools/write-content.js +3 -3
- package/dist/usage/ledger.d.ts +47 -0
- package/dist/usage/ledger.js +95 -0
- package/dist/usage/render.d.ts +11 -0
- package/dist/usage/render.js +67 -0
- package/package.json +1 -1
- package/dist/security/platform.d.ts +0 -1
- package/dist/security/platform.js +0 -3
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { existsSync, lstatSync, realpathSync } from "node:fs";
|
|
2
2
|
import { homedir, tmpdir } from "node:os";
|
|
3
3
|
import { basename, dirname, isAbsolute, normalize, resolve } from "node:path";
|
|
4
|
-
import { isWindowsPlatform } from "./platform.js";
|
|
5
4
|
const PRIVATE_KEY_EXTENSIONS = new Set([".pem", ".key", ".p12", ".pfx"]);
|
|
6
5
|
const PRIVATE_KEY_NAME_HINTS = /(id_rsa|id_ed25519|private|secret|credentials)/i;
|
|
7
6
|
const PROC_MEM_PATH = /^\/proc\/\d+\/mem(?:\/|$)/;
|
|
@@ -198,9 +197,6 @@ export function guardPath(rawPath, operation, ctx) {
|
|
|
198
197
|
if (!ctx.config.enabled) {
|
|
199
198
|
return { allowed: true, operation, rawPath };
|
|
200
199
|
}
|
|
201
|
-
if (isWindowsPlatform()) {
|
|
202
|
-
return { allowed: true, operation, rawPath };
|
|
203
|
-
}
|
|
204
200
|
const homeDir = ctx.homeDir ?? homedir();
|
|
205
201
|
const effectiveCtx = {
|
|
206
202
|
...ctx,
|
package/dist/settings.d.ts
CHANGED
|
@@ -92,6 +92,14 @@ export interface PipiclawMemoryMaintenanceSettings {
|
|
|
92
92
|
/** Only apply the shrink guard when the original exceeds this length (chars). */
|
|
93
93
|
cleanupShrinkGuardMinChars: number;
|
|
94
94
|
}
|
|
95
|
+
export interface PipiclawLoggingSettings {
|
|
96
|
+
level: "debug" | "info" | "warn" | "error";
|
|
97
|
+
file: {
|
|
98
|
+
enabled: boolean;
|
|
99
|
+
maxSizeBytes: number;
|
|
100
|
+
maxFiles: number;
|
|
101
|
+
};
|
|
102
|
+
}
|
|
95
103
|
export interface PipiclawSessionSearchSettings {
|
|
96
104
|
enabled: boolean;
|
|
97
105
|
maxFiles: number;
|
|
@@ -104,6 +112,8 @@ export interface PipiclawSettings {
|
|
|
104
112
|
defaultProvider?: string;
|
|
105
113
|
defaultModel?: string;
|
|
106
114
|
defaultThinkingLevel?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
|
|
115
|
+
/** Single backup model reference (`provider/model`) used when the primary model's turn fails. */
|
|
116
|
+
fallbackModel?: string | null;
|
|
107
117
|
compaction?: Partial<PipiclawCompactionSettings>;
|
|
108
118
|
retry?: Partial<PipiclawRetrySettings>;
|
|
109
119
|
memoryRecall?: Partial<PipiclawMemoryRecallSettings>;
|
|
@@ -111,6 +121,9 @@ export interface PipiclawSettings {
|
|
|
111
121
|
memoryGrowth?: Partial<PipiclawMemoryGrowthSettings>;
|
|
112
122
|
memoryMaintenance?: Partial<PipiclawMemoryMaintenanceSettings>;
|
|
113
123
|
sessionSearch?: Partial<PipiclawSessionSearchSettings>;
|
|
124
|
+
logging?: Partial<Omit<PipiclawLoggingSettings, "file">> & {
|
|
125
|
+
file?: Partial<PipiclawLoggingSettings["file"]>;
|
|
126
|
+
};
|
|
114
127
|
}
|
|
115
128
|
/**
|
|
116
129
|
* Settings manager for pipiclaw.
|
|
@@ -135,8 +148,14 @@ export declare class PipiclawSettingsManager {
|
|
|
135
148
|
getMemoryGrowthSettings(): PipiclawMemoryGrowthSettings;
|
|
136
149
|
getMemoryMaintenanceSettings(): PipiclawMemoryMaintenanceSettings;
|
|
137
150
|
getSessionSearchSettings(): PipiclawSessionSearchSettings;
|
|
151
|
+
getLoggingSettings(): PipiclawLoggingSettings;
|
|
138
152
|
getRetryEnabled(): boolean;
|
|
139
153
|
setRetryEnabled(enabled: boolean): void;
|
|
154
|
+
/**
|
|
155
|
+
* Backup model reference (`provider/model`) for fallback, or null when unset.
|
|
156
|
+
* Empty / whitespace-only values are treated as unset (fallback disabled).
|
|
157
|
+
*/
|
|
158
|
+
getFallbackModelReference(): string | null;
|
|
140
159
|
getDefaultModel(): string | undefined;
|
|
141
160
|
getDefaultProvider(): string | undefined;
|
|
142
161
|
setDefaultModelAndProvider(provider: string, modelId: string): void;
|
package/dist/settings.js
CHANGED
|
@@ -66,6 +66,16 @@ const DEFAULT_MEMORY_MAINTENANCE = {
|
|
|
66
66
|
cleanupShrinkGuardMinRatio: 0.4,
|
|
67
67
|
cleanupShrinkGuardMinChars: 2_000,
|
|
68
68
|
};
|
|
69
|
+
// `file.enabled` defaults to true: for a long-lived daemon, persisting logs is
|
|
70
|
+
// worth more than the surprise of a new file under state/logs/. See docs.
|
|
71
|
+
const DEFAULT_LOGGING = {
|
|
72
|
+
level: "info",
|
|
73
|
+
file: {
|
|
74
|
+
enabled: true,
|
|
75
|
+
maxSizeBytes: 5_000_000,
|
|
76
|
+
maxFiles: 3,
|
|
77
|
+
},
|
|
78
|
+
};
|
|
69
79
|
/**
|
|
70
80
|
* Settings manager for pipiclaw.
|
|
71
81
|
* Stores global settings in the pipiclaw root directory.
|
|
@@ -185,6 +195,16 @@ export class PipiclawSettingsManager {
|
|
|
185
195
|
...this.settings.sessionSearch,
|
|
186
196
|
};
|
|
187
197
|
}
|
|
198
|
+
getLoggingSettings() {
|
|
199
|
+
return {
|
|
200
|
+
...DEFAULT_LOGGING,
|
|
201
|
+
...this.settings.logging,
|
|
202
|
+
file: {
|
|
203
|
+
...DEFAULT_LOGGING.file,
|
|
204
|
+
...this.settings.logging?.file,
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
}
|
|
188
208
|
getRetryEnabled() {
|
|
189
209
|
return this.settings.retry?.enabled ?? DEFAULT_RETRY.enabled;
|
|
190
210
|
}
|
|
@@ -192,6 +212,18 @@ export class PipiclawSettingsManager {
|
|
|
192
212
|
this.settings.retry = { ...this.settings.retry, enabled };
|
|
193
213
|
this.save();
|
|
194
214
|
}
|
|
215
|
+
/**
|
|
216
|
+
* Backup model reference (`provider/model`) for fallback, or null when unset.
|
|
217
|
+
* Empty / whitespace-only values are treated as unset (fallback disabled).
|
|
218
|
+
*/
|
|
219
|
+
getFallbackModelReference() {
|
|
220
|
+
const raw = this.settings.fallbackModel;
|
|
221
|
+
if (typeof raw !== "string") {
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
const trimmed = raw.trim();
|
|
225
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
226
|
+
}
|
|
195
227
|
getDefaultModel() {
|
|
196
228
|
return this.settings.defaultModel;
|
|
197
229
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export interface JsonlAppenderOptions {
|
|
2
|
+
/** Fixed target file. Mutually exclusive with `pathFor`. */
|
|
3
|
+
path?: string;
|
|
4
|
+
/** Resolve the target file per append (e.g. monthly ledger files). */
|
|
5
|
+
pathFor?: (now: Date) => string;
|
|
6
|
+
/** Rotate when the file would exceed this size (bytes). Omit to disable. */
|
|
7
|
+
maxSizeBytes?: number;
|
|
8
|
+
/** Number of rotated backups to keep (`.1`..`.N`). Default 3. */
|
|
9
|
+
maxRotations?: number;
|
|
10
|
+
/** File mode for created files. Default 0o600. */
|
|
11
|
+
mode?: number;
|
|
12
|
+
}
|
|
13
|
+
export interface JsonlAppender {
|
|
14
|
+
/** Serialize `record` as one JSON line. Never throws. */
|
|
15
|
+
append(record: unknown): Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Append-only JSONL writer shared by the runtime log and the usage ledger.
|
|
19
|
+
*
|
|
20
|
+
* Writes are serialized per resolved file path, size-tracked in memory (one
|
|
21
|
+
* initial stat), and rotated via rename. Observability infrastructure must not
|
|
22
|
+
* reach back into the business path, so a failed append only warns once (until
|
|
23
|
+
* the next success) and never rejects.
|
|
24
|
+
*/
|
|
25
|
+
export declare function createJsonlAppender(options: JsonlAppenderOptions): JsonlAppender;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, renameSync, statSync } from "node:fs";
|
|
2
|
+
import { appendFile } from "node:fs/promises";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import { createSerialQueue } from "./serial-queue.js";
|
|
5
|
+
/**
|
|
6
|
+
* Append-only JSONL writer shared by the runtime log and the usage ledger.
|
|
7
|
+
*
|
|
8
|
+
* Writes are serialized per resolved file path, size-tracked in memory (one
|
|
9
|
+
* initial stat), and rotated via rename. Observability infrastructure must not
|
|
10
|
+
* reach back into the business path, so a failed append only warns once (until
|
|
11
|
+
* the next success) and never rejects.
|
|
12
|
+
*/
|
|
13
|
+
export function createJsonlAppender(options) {
|
|
14
|
+
if (!options.path && !options.pathFor) {
|
|
15
|
+
throw new Error("createJsonlAppender requires either `path` or `pathFor`");
|
|
16
|
+
}
|
|
17
|
+
const maxRotations = options.maxRotations ?? 3;
|
|
18
|
+
const mode = options.mode ?? 0o600;
|
|
19
|
+
const queue = createSerialQueue();
|
|
20
|
+
const sizes = new Map();
|
|
21
|
+
const ensuredDirs = new Set();
|
|
22
|
+
let warned = false;
|
|
23
|
+
const resolvePath = (now) => (options.pathFor ? options.pathFor(now) : options.path);
|
|
24
|
+
const ensureDir = (filePath) => {
|
|
25
|
+
const dir = dirname(filePath);
|
|
26
|
+
if (ensuredDirs.has(dir))
|
|
27
|
+
return;
|
|
28
|
+
mkdirSync(dir, { recursive: true });
|
|
29
|
+
ensuredDirs.add(dir);
|
|
30
|
+
};
|
|
31
|
+
const currentSize = (filePath) => {
|
|
32
|
+
const cached = sizes.get(filePath);
|
|
33
|
+
if (cached !== undefined)
|
|
34
|
+
return cached;
|
|
35
|
+
let size = 0;
|
|
36
|
+
try {
|
|
37
|
+
if (existsSync(filePath))
|
|
38
|
+
size = statSync(filePath).size;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
size = 0;
|
|
42
|
+
}
|
|
43
|
+
sizes.set(filePath, size);
|
|
44
|
+
return size;
|
|
45
|
+
};
|
|
46
|
+
const rotate = (filePath) => {
|
|
47
|
+
for (let i = maxRotations - 1; i >= 1; i--) {
|
|
48
|
+
const from = `${filePath}.${i}`;
|
|
49
|
+
if (existsSync(from)) {
|
|
50
|
+
renameSync(from, `${filePath}.${i + 1}`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (existsSync(filePath)) {
|
|
54
|
+
renameSync(filePath, `${filePath}.1`);
|
|
55
|
+
}
|
|
56
|
+
sizes.set(filePath, 0);
|
|
57
|
+
};
|
|
58
|
+
const write = async (filePath, line) => {
|
|
59
|
+
ensureDir(filePath);
|
|
60
|
+
const lineBytes = Buffer.byteLength(line);
|
|
61
|
+
if (options.maxSizeBytes && options.maxSizeBytes > 0) {
|
|
62
|
+
if (currentSize(filePath) + lineBytes > options.maxSizeBytes && currentSize(filePath) > 0) {
|
|
63
|
+
rotate(filePath);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
await appendFile(filePath, line, { encoding: "utf-8", mode });
|
|
67
|
+
sizes.set(filePath, currentSize(filePath) + lineBytes);
|
|
68
|
+
};
|
|
69
|
+
return {
|
|
70
|
+
async append(record) {
|
|
71
|
+
const filePath = resolvePath(new Date());
|
|
72
|
+
const line = `${JSON.stringify(record)}\n`;
|
|
73
|
+
try {
|
|
74
|
+
await queue.run(filePath, () => write(filePath, line));
|
|
75
|
+
warned = false;
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (!warned) {
|
|
79
|
+
warned = true;
|
|
80
|
+
console.warn(`[jsonl-appender] Failed to append to ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
@@ -3,10 +3,3 @@
|
|
|
3
3
|
* Wraps in single quotes and escapes internal single quotes.
|
|
4
4
|
*/
|
|
5
5
|
export declare function shellEscape(s: string): string;
|
|
6
|
-
/**
|
|
7
|
-
* Normalize filesystem paths for POSIX-style shells.
|
|
8
|
-
* On Windows we convert backslashes to forward slashes so Git Bash/MSYS tools
|
|
9
|
-
* can consume the path consistently.
|
|
10
|
-
*/
|
|
11
|
-
export declare function toShellPath(path: string): string;
|
|
12
|
-
export declare function shellEscapePath(path: string): string;
|
|
@@ -5,14 +5,3 @@
|
|
|
5
5
|
export function shellEscape(s) {
|
|
6
6
|
return `'${s.replace(/'/g, "'\\''")}'`;
|
|
7
7
|
}
|
|
8
|
-
/**
|
|
9
|
-
* Normalize filesystem paths for POSIX-style shells.
|
|
10
|
-
* On Windows we convert backslashes to forward slashes so Git Bash/MSYS tools
|
|
11
|
-
* can consume the path consistently.
|
|
12
|
-
*/
|
|
13
|
-
export function toShellPath(path) {
|
|
14
|
-
return process.platform === "win32" ? path.replace(/\\/g, "/") : path;
|
|
15
|
-
}
|
|
16
|
-
export function shellEscapePath(path) {
|
|
17
|
-
return shellEscape(toShellPath(path));
|
|
18
|
-
}
|
package/dist/subagents/tool.js
CHANGED
|
@@ -183,6 +183,7 @@ async function buildContextualBlocks(task, config, options, currentModel) {
|
|
|
183
183
|
const recallQuery = [task.trim(), config.description.trim(), ...config.paths].filter(Boolean).join("\n");
|
|
184
184
|
const recalled = await recallRelevantMemory({
|
|
185
185
|
query: recallQuery,
|
|
186
|
+
channelId: options.runtimeContext.channelId,
|
|
186
187
|
workspaceDir: options.workspaceDir,
|
|
187
188
|
channelDir: options.channelDir,
|
|
188
189
|
maxCandidates: recallSettings.maxCandidates,
|
package/dist/tools/bash.js
CHANGED
|
@@ -3,7 +3,7 @@ import { Type } from "typebox";
|
|
|
3
3
|
import { guardCommand } from "../security/command-guard.js";
|
|
4
4
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
5
5
|
import { logSecurityEvent } from "../security/logger.js";
|
|
6
|
-
import {
|
|
6
|
+
import { shellEscape } from "../shared/shell-escape.js";
|
|
7
7
|
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail } from "./truncate.js";
|
|
8
8
|
/**
|
|
9
9
|
* Default wall-clock timeout for bash commands when the caller supplies neither a
|
|
@@ -90,7 +90,7 @@ export function createBashTool(executor, options = {}) {
|
|
|
90
90
|
if (totalBytes > DEFAULT_MAX_BYTES) {
|
|
91
91
|
const candidatePath = getSpillFilePath();
|
|
92
92
|
try {
|
|
93
|
-
const spillResult = await executor.exec(`cat > ${
|
|
93
|
+
const spillResult = await executor.exec(`cat > ${shellEscape(candidatePath)}`, {
|
|
94
94
|
signal,
|
|
95
95
|
stdin: output,
|
|
96
96
|
});
|
package/dist/tools/edit.js
CHANGED
|
@@ -3,7 +3,7 @@ import { Type } from "typebox";
|
|
|
3
3
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
4
4
|
import { logSecurityEvent } from "../security/logger.js";
|
|
5
5
|
import { guardPath } from "../security/path-guard.js";
|
|
6
|
-
import {
|
|
6
|
+
import { shellEscape } from "../shared/shell-escape.js";
|
|
7
7
|
import { writeContent } from "./write-content.js";
|
|
8
8
|
/**
|
|
9
9
|
* Generate a unified diff string with line numbers and context
|
|
@@ -126,7 +126,7 @@ export function createEditTool(executor, options = {}) {
|
|
|
126
126
|
}
|
|
127
127
|
}
|
|
128
128
|
// Read the file
|
|
129
|
-
const readResult = await executor.exec(`cat ${
|
|
129
|
+
const readResult = await executor.exec(`cat ${shellEscape(path)}`, { signal });
|
|
130
130
|
if (readResult.code !== 0) {
|
|
131
131
|
throw new Error(readResult.stderr || `File not found: ${path}`);
|
|
132
132
|
}
|
package/dist/tools/read.js
CHANGED
|
@@ -3,7 +3,7 @@ import { Type } from "typebox";
|
|
|
3
3
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
4
4
|
import { logSecurityEvent } from "../security/logger.js";
|
|
5
5
|
import { guardPath } from "../security/path-guard.js";
|
|
6
|
-
import {
|
|
6
|
+
import { shellEscape } from "../shared/shell-escape.js";
|
|
7
7
|
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateHead } from "./truncate.js";
|
|
8
8
|
/**
|
|
9
9
|
* Map of file extensions to MIME types for common image formats
|
|
@@ -76,7 +76,7 @@ export function createReadTool(executor, options = {}) {
|
|
|
76
76
|
const mimeType = isImageFile(path);
|
|
77
77
|
if (mimeType) {
|
|
78
78
|
// Read as image (binary) - use base64
|
|
79
|
-
const result = await executor.exec(`base64 < ${
|
|
79
|
+
const result = await executor.exec(`base64 < ${shellEscape(path)}`, { signal });
|
|
80
80
|
if (result.code !== 0) {
|
|
81
81
|
throw new Error(result.stderr || `Failed to read file: ${path}`);
|
|
82
82
|
}
|
|
@@ -90,7 +90,7 @@ export function createReadTool(executor, options = {}) {
|
|
|
90
90
|
};
|
|
91
91
|
}
|
|
92
92
|
// Get total line count first
|
|
93
|
-
const countResult = await executor.exec(`awk 'END { print NR }' ${
|
|
93
|
+
const countResult = await executor.exec(`awk 'END { print NR }' ${shellEscape(path)}`, { signal });
|
|
94
94
|
if (countResult.code !== 0) {
|
|
95
95
|
throw new Error(countResult.stderr || `Failed to read file: ${path}`);
|
|
96
96
|
}
|
|
@@ -106,10 +106,10 @@ export function createReadTool(executor, options = {}) {
|
|
|
106
106
|
// Read content with offset
|
|
107
107
|
let cmd;
|
|
108
108
|
if (startLine === 1) {
|
|
109
|
-
cmd = `cat ${
|
|
109
|
+
cmd = `cat ${shellEscape(path)}`;
|
|
110
110
|
}
|
|
111
111
|
else {
|
|
112
|
-
cmd = `tail -n +${startLine} ${
|
|
112
|
+
cmd = `tail -n +${startLine} ${shellEscape(path)}`;
|
|
113
113
|
}
|
|
114
114
|
const result = await executor.exec(cmd, { signal });
|
|
115
115
|
if (result.code !== 0) {
|
|
@@ -131,7 +131,7 @@ export function createReadTool(executor, options = {}) {
|
|
|
131
131
|
if (truncation.firstLineExceedsLimit) {
|
|
132
132
|
// First line at offset exceeds 50KB - tell model to use bash
|
|
133
133
|
const firstLineSize = formatSize(Buffer.byteLength(selectedContent.split("\n")[0], "utf-8"));
|
|
134
|
-
outputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${
|
|
134
|
+
outputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${path} | head -c ${DEFAULT_MAX_BYTES}]`;
|
|
135
135
|
details = { truncation };
|
|
136
136
|
}
|
|
137
137
|
else if (truncation.truncated) {
|
package/dist/tools/registry.js
CHANGED
|
@@ -91,6 +91,7 @@ export const TOOL_REGISTRY = [
|
|
|
91
91
|
availableToSubagents: false,
|
|
92
92
|
enabledBy: (ctx) => ctx.toolsConfig?.tools.memory.sessionSearch.enabled !== false,
|
|
93
93
|
create: (ctx) => createSessionSearchTool({
|
|
94
|
+
channelId: ctx.channelId,
|
|
94
95
|
channelDir: ctx.channelDir,
|
|
95
96
|
getCurrentModel: req(ctx.getCurrentModel, "getCurrentModel"),
|
|
96
97
|
resolveApiKey: req(ctx.resolveApiKey, "resolveApiKey"),
|
|
@@ -9,6 +9,7 @@ declare const sessionSearchSchema: Type.TObject<{
|
|
|
9
9
|
roleFilter: Type.TOptional<Type.TArray<Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"system">, Type.TLiteral<"unknown">]>>>;
|
|
10
10
|
}>;
|
|
11
11
|
export interface SessionSearchToolOptions {
|
|
12
|
+
channelId?: string;
|
|
12
13
|
channelDir: string;
|
|
13
14
|
getCurrentModel: () => Model<Api>;
|
|
14
15
|
resolveApiKey: (model: Model<Api>) => Promise<string>;
|
|
@@ -30,6 +30,7 @@ export function createSessionSearchTool(options) {
|
|
|
30
30
|
const settings = options.getSessionSearchSettings();
|
|
31
31
|
const model = options.getCurrentModel();
|
|
32
32
|
const response = await searchChannelSessions({
|
|
33
|
+
channelId: options.channelId,
|
|
33
34
|
channelDir: options.channelDir,
|
|
34
35
|
query: query ?? "",
|
|
35
36
|
roleFilter,
|
|
@@ -2,7 +2,7 @@ import { dirname } from "node:path";
|
|
|
2
2
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
3
3
|
import { logSecurityEvent } from "../security/logger.js";
|
|
4
4
|
import { guardPath } from "../security/path-guard.js";
|
|
5
|
-
import {
|
|
5
|
+
import { shellEscape } from "../shared/shell-escape.js";
|
|
6
6
|
function getDir(path) {
|
|
7
7
|
return dirname(path);
|
|
8
8
|
}
|
|
@@ -42,8 +42,8 @@ export async function writeContent(executor, path, content, signal, options) {
|
|
|
42
42
|
throw new Error(lines.join("\n"));
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
|
-
const dirPrefix = createParentDir ? `mkdir -p ${
|
|
46
|
-
const result = await executor.exec(`${dirPrefix}cat > ${
|
|
45
|
+
const dirPrefix = createParentDir ? `mkdir -p ${shellEscape(getDir(path))} && ` : "";
|
|
46
|
+
const result = await executor.exec(`${dirPrefix}cat > ${shellEscape(path)}`, {
|
|
47
47
|
signal,
|
|
48
48
|
stdin: content,
|
|
49
49
|
});
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export type UsageKind = "turn" | "subagent" | "sidecar";
|
|
2
|
+
export interface UsageTokens {
|
|
3
|
+
input: number;
|
|
4
|
+
output: number;
|
|
5
|
+
cacheRead: number;
|
|
6
|
+
cacheWrite: number;
|
|
7
|
+
total: number;
|
|
8
|
+
}
|
|
9
|
+
export interface UsageCost {
|
|
10
|
+
input: number;
|
|
11
|
+
output: number;
|
|
12
|
+
cacheRead: number;
|
|
13
|
+
cacheWrite: number;
|
|
14
|
+
total: number;
|
|
15
|
+
}
|
|
16
|
+
export interface UsageLedgerEntry {
|
|
17
|
+
ts: string;
|
|
18
|
+
channelId: string;
|
|
19
|
+
kind: UsageKind;
|
|
20
|
+
model: string;
|
|
21
|
+
label?: string;
|
|
22
|
+
usage: UsageTokens;
|
|
23
|
+
cost: UsageCost;
|
|
24
|
+
}
|
|
25
|
+
export interface UsageSummary {
|
|
26
|
+
totalCost: number;
|
|
27
|
+
entryCount: number;
|
|
28
|
+
byKind: Record<string, number>;
|
|
29
|
+
byModel: Record<string, number>;
|
|
30
|
+
byChannel: Record<string, number>;
|
|
31
|
+
}
|
|
32
|
+
export interface UsageSummaryQuery {
|
|
33
|
+
since: Date;
|
|
34
|
+
until?: Date;
|
|
35
|
+
channelId?: string;
|
|
36
|
+
}
|
|
37
|
+
export declare const UNTRACKED_CHANNEL_ID = "(untracked)";
|
|
38
|
+
export interface UsageLedger {
|
|
39
|
+
record(entry: Omit<UsageLedgerEntry, "ts">): void;
|
|
40
|
+
summarize(query: UsageSummaryQuery): UsageSummary;
|
|
41
|
+
}
|
|
42
|
+
export interface CreateUsageLedgerOptions {
|
|
43
|
+
baseDir?: string;
|
|
44
|
+
}
|
|
45
|
+
export declare function createUsageLedger(options?: CreateUsageLedgerOptions): UsageLedger;
|
|
46
|
+
/** Process-wide ledger (single-process runtime). Tests use createUsageLedger. */
|
|
47
|
+
export declare function getUsageLedger(): UsageLedger;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import * as log from "../log.js";
|
|
4
|
+
import { USAGE_STATE_DIR } from "../paths.js";
|
|
5
|
+
import { createJsonlAppender } from "../shared/jsonl-appender.js";
|
|
6
|
+
export const UNTRACKED_CHANNEL_ID = "(untracked)";
|
|
7
|
+
function monthKey(date) {
|
|
8
|
+
return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}`;
|
|
9
|
+
}
|
|
10
|
+
function monthKeysBetween(since, until) {
|
|
11
|
+
const keys = [];
|
|
12
|
+
const cursor = new Date(Date.UTC(since.getUTCFullYear(), since.getUTCMonth(), 1));
|
|
13
|
+
const end = new Date(Date.UTC(until.getUTCFullYear(), until.getUTCMonth(), 1));
|
|
14
|
+
while (cursor <= end) {
|
|
15
|
+
keys.push(monthKey(cursor));
|
|
16
|
+
cursor.setUTCMonth(cursor.getUTCMonth() + 1);
|
|
17
|
+
}
|
|
18
|
+
return keys;
|
|
19
|
+
}
|
|
20
|
+
export function createUsageLedger(options = {}) {
|
|
21
|
+
const baseDir = options.baseDir ?? USAGE_STATE_DIR;
|
|
22
|
+
const fileFor = (date) => join(baseDir, `usage-${monthKey(date)}.jsonl`);
|
|
23
|
+
const appender = createJsonlAppender({ pathFor: fileFor });
|
|
24
|
+
return {
|
|
25
|
+
record(entry) {
|
|
26
|
+
// No API billing (local models) → no ledger noise.
|
|
27
|
+
if (!(entry.cost.total > 0))
|
|
28
|
+
return;
|
|
29
|
+
if (!entry.channelId) {
|
|
30
|
+
log.logWarning("Usage ledger entry missing channelId; recording as untracked", `kind=${entry.kind}`);
|
|
31
|
+
}
|
|
32
|
+
const full = {
|
|
33
|
+
ts: new Date().toISOString(),
|
|
34
|
+
...entry,
|
|
35
|
+
channelId: entry.channelId || UNTRACKED_CHANNEL_ID,
|
|
36
|
+
};
|
|
37
|
+
void appender.append(full);
|
|
38
|
+
},
|
|
39
|
+
summarize(query) {
|
|
40
|
+
const until = query.until ?? new Date();
|
|
41
|
+
const sinceMs = query.since.getTime();
|
|
42
|
+
const untilMs = until.getTime();
|
|
43
|
+
const summary = {
|
|
44
|
+
totalCost: 0,
|
|
45
|
+
entryCount: 0,
|
|
46
|
+
byKind: {},
|
|
47
|
+
byModel: {},
|
|
48
|
+
byChannel: {},
|
|
49
|
+
};
|
|
50
|
+
for (const key of monthKeysBetween(query.since, until)) {
|
|
51
|
+
const path = join(baseDir, `usage-${key}.jsonl`);
|
|
52
|
+
if (!existsSync(path))
|
|
53
|
+
continue;
|
|
54
|
+
let content;
|
|
55
|
+
try {
|
|
56
|
+
content = readFileSync(path, "utf-8");
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
for (const line of content.split("\n")) {
|
|
62
|
+
if (!line)
|
|
63
|
+
continue;
|
|
64
|
+
let entry;
|
|
65
|
+
try {
|
|
66
|
+
entry = JSON.parse(line);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
continue; // tolerate a torn trailing line
|
|
70
|
+
}
|
|
71
|
+
const tsMs = Date.parse(entry.ts);
|
|
72
|
+
if (Number.isNaN(tsMs) || tsMs < sinceMs || tsMs > untilMs)
|
|
73
|
+
continue;
|
|
74
|
+
if (query.channelId && entry.channelId !== query.channelId)
|
|
75
|
+
continue;
|
|
76
|
+
const cost = entry.cost?.total ?? 0;
|
|
77
|
+
summary.totalCost += cost;
|
|
78
|
+
summary.entryCount += 1;
|
|
79
|
+
summary.byKind[entry.kind] = (summary.byKind[entry.kind] ?? 0) + cost;
|
|
80
|
+
summary.byModel[entry.model] = (summary.byModel[entry.model] ?? 0) + cost;
|
|
81
|
+
summary.byChannel[entry.channelId] = (summary.byChannel[entry.channelId] ?? 0) + cost;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return summary;
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
let singleton = null;
|
|
89
|
+
/** Process-wide ledger (single-process runtime). Tests use createUsageLedger. */
|
|
90
|
+
export function getUsageLedger() {
|
|
91
|
+
if (!singleton) {
|
|
92
|
+
singleton = createUsageLedger();
|
|
93
|
+
}
|
|
94
|
+
return singleton;
|
|
95
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { UsageLedger } from "./ledger.js";
|
|
2
|
+
export type UsageQueryMode = "default" | "7d" | "month";
|
|
3
|
+
export declare function parseUsageMode(args: string): UsageQueryMode;
|
|
4
|
+
interface UsageWindow {
|
|
5
|
+
title: string;
|
|
6
|
+
since: Date;
|
|
7
|
+
until: Date;
|
|
8
|
+
}
|
|
9
|
+
export declare function usageWindows(mode: UsageQueryMode, now: Date): UsageWindow[];
|
|
10
|
+
export declare function renderUsageReport(ledger: UsageLedger, channelId: string, mode: UsageQueryMode, now: Date): string;
|
|
11
|
+
export {};
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
export function parseUsageMode(args) {
|
|
2
|
+
const normalized = args.trim().toLowerCase();
|
|
3
|
+
if (normalized === "7d" || normalized === "7")
|
|
4
|
+
return "7d";
|
|
5
|
+
if (normalized === "month" || normalized === "monthly")
|
|
6
|
+
return "month";
|
|
7
|
+
return "default";
|
|
8
|
+
}
|
|
9
|
+
function startOfUtcDay(now) {
|
|
10
|
+
return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
|
|
11
|
+
}
|
|
12
|
+
function startOfUtcMonth(now) {
|
|
13
|
+
return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
|
|
14
|
+
}
|
|
15
|
+
export function usageWindows(mode, now) {
|
|
16
|
+
const monthTitle = `This month (${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, "0")})`;
|
|
17
|
+
switch (mode) {
|
|
18
|
+
case "7d":
|
|
19
|
+
return [{ title: "Last 7 days", since: new Date(now.getTime() - 7 * 86_400_000), until: now }];
|
|
20
|
+
case "month":
|
|
21
|
+
return [{ title: monthTitle, since: startOfUtcMonth(now), until: now }];
|
|
22
|
+
default:
|
|
23
|
+
return [
|
|
24
|
+
{ title: "Today (UTC)", since: startOfUtcDay(now), until: now },
|
|
25
|
+
{ title: monthTitle, since: startOfUtcMonth(now), until: now },
|
|
26
|
+
];
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function money(n) {
|
|
30
|
+
return `$${n.toFixed(4)}`;
|
|
31
|
+
}
|
|
32
|
+
function topEntries(map, limit) {
|
|
33
|
+
return Object.entries(map)
|
|
34
|
+
.filter(([, cost]) => cost > 0)
|
|
35
|
+
.sort((a, b) => b[1] - a[1])
|
|
36
|
+
.slice(0, limit);
|
|
37
|
+
}
|
|
38
|
+
function renderKindBreakdown(summary) {
|
|
39
|
+
const parts = topEntries(summary.byKind, 3).map(([kind, cost]) => `${kind} ${money(cost)}`);
|
|
40
|
+
return parts.length > 0 ? parts.join(" · ") : null;
|
|
41
|
+
}
|
|
42
|
+
function renderWindow(window, ledger, channelId) {
|
|
43
|
+
const global = ledger.summarize({ since: window.since, until: window.until });
|
|
44
|
+
const channel = ledger.summarize({ since: window.since, until: window.until, channelId });
|
|
45
|
+
const lines = [`## ${window.title}`];
|
|
46
|
+
if (global.entryCount === 0) {
|
|
47
|
+
lines.push("No recorded usage.");
|
|
48
|
+
return lines.join("\n");
|
|
49
|
+
}
|
|
50
|
+
lines.push(`This channel: ${money(channel.totalCost)}`);
|
|
51
|
+
const channelKinds = renderKindBreakdown(channel);
|
|
52
|
+
if (channelKinds) {
|
|
53
|
+
lines.push(` ${channelKinds}`);
|
|
54
|
+
}
|
|
55
|
+
const channelCount = Object.keys(global.byChannel).length;
|
|
56
|
+
lines.push(`Global: ${money(global.totalCost)} across ${channelCount} channel${channelCount === 1 ? "" : "s"}`);
|
|
57
|
+
const topModels = topEntries(global.byModel, 3);
|
|
58
|
+
if (topModels.length > 0) {
|
|
59
|
+
lines.push(` Top models: ${topModels.map(([model, cost]) => `${model} ${money(cost)}`).join(", ")}`);
|
|
60
|
+
}
|
|
61
|
+
return lines.join("\n");
|
|
62
|
+
}
|
|
63
|
+
export function renderUsageReport(ledger, channelId, mode, now) {
|
|
64
|
+
const windows = usageWindows(mode, now);
|
|
65
|
+
const body = windows.map((window) => renderWindow(window, ledger, channelId)).join("\n\n");
|
|
66
|
+
return `# Usage\n\n${body}`;
|
|
67
|
+
}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare function isWindowsPlatform(): boolean;
|