@oyasmi/pipiclaw 0.8.6 → 0.8.7-beta.2

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.
Files changed (57) hide show
  1. package/dist/agent/channel-runner.d.ts +2 -0
  2. package/dist/agent/channel-runner.js +26 -6
  3. package/dist/agent/prompt/builder.d.ts +11 -20
  4. package/dist/agent/prompt/builder.js +40 -87
  5. package/dist/agent/prompt/manifest.d.ts +28 -2
  6. package/dist/agent/prompt/manifest.js +50 -11
  7. package/dist/agent/prompt/resources.d.ts +11 -2
  8. package/dist/agent/prompt/resources.js +51 -12
  9. package/dist/agent/prompt/sections.d.ts +9 -10
  10. package/dist/agent/prompt/sections.js +46 -99
  11. package/dist/agent/prompt/types.d.ts +14 -0
  12. package/dist/agent/session-events.js +17 -5
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.js +1 -1
  15. package/dist/log.d.ts +12 -20
  16. package/dist/log.js +195 -198
  17. package/dist/memory/bootstrap.d.ts +6 -0
  18. package/dist/memory/bootstrap.js +53 -21
  19. package/dist/memory/lifecycle.js +4 -1
  20. package/dist/memory/recall.d.ts +8 -0
  21. package/dist/memory/recall.js +19 -13
  22. package/dist/memory/task-digest.d.ts +4 -0
  23. package/dist/memory/task-digest.js +9 -3
  24. package/dist/playbooks/catalog.d.ts +7 -2
  25. package/dist/playbooks/catalog.js +10 -6
  26. package/dist/playbooks/event-scheduling.md +1 -1
  27. package/dist/playbooks/memory-and-learning.md +1 -1
  28. package/dist/playbooks/runtime-orientation.md +1 -1
  29. package/dist/playbooks/task-closeout.md +1 -1
  30. package/dist/playbooks/task-delegation.md +1 -1
  31. package/dist/playbooks/task-driving.md +1 -1
  32. package/dist/playbooks/task-planning.md +1 -1
  33. package/dist/playbooks/task-recurring.md +1 -1
  34. package/dist/playbooks/task-repair.md +1 -1
  35. package/dist/runtime/bootstrap.d.ts +1 -0
  36. package/dist/runtime/bootstrap.js +41 -11
  37. package/dist/runtime/dingtalk.js +19 -6
  38. package/dist/runtime/events.d.ts +2 -0
  39. package/dist/runtime/events.js +20 -8
  40. package/dist/runtime/store.d.ts +4 -6
  41. package/dist/runtime/store.js +44 -40
  42. package/dist/security/logger.d.ts +3 -1
  43. package/dist/security/logger.js +33 -10
  44. package/dist/shared/jsonl-appender.d.ts +27 -8
  45. package/dist/shared/jsonl-appender.js +128 -41
  46. package/dist/shared/prompt-units.d.ts +46 -0
  47. package/dist/shared/prompt-units.js +153 -0
  48. package/dist/tools/bash.js +1 -1
  49. package/dist/tools/edit.js +1 -1
  50. package/dist/tools/grep.js +1 -1
  51. package/dist/tools/read.js +1 -1
  52. package/dist/tools/write-content.js +1 -1
  53. package/dist/tui/app.js +17 -0
  54. package/dist/usage/ledger.d.ts +2 -0
  55. package/dist/usage/ledger.js +3 -1
  56. package/dist/web/client.js +3 -3
  57. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
- import { existsSync, mkdirSync, renameSync, statSync } from "fs";
2
- import { appendFile, writeFile } from "fs/promises";
3
- import { dirname, join } from "path";
4
- import { createSerialQueue } from "../shared/serial-queue.js";
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.writeQueue = createSerialQueue();
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
- await this.writeQueue.run(logPath, async () => {
48
- await this.rotateIfNeeded(logPath);
49
- const line = `${JSON.stringify(message)}\n`;
50
- await appendFile(logPath, line, "utf-8");
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
- await this.writeQueue.run(logPath, async () => {
57
- await this.rotateIfNeeded(logPath);
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
- export declare function logSecurityEvent(workspaceDir: string, config: SecurityConfig, event: SecurityLogEvent): void;
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>;
@@ -1,18 +1,41 @@
1
- import { appendFileSync, mkdirSync } from "node:fs";
2
- import { dirname, join } from "node:path";
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
- export function logSecurityEvent(workspaceDir, config, event) {
7
- if (!config.audit.logBlocked) {
8
- return;
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
- const logPath = getLogPath(workspaceDir, config);
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
- mkdirSync(dirname(logPath), { recursive: true });
13
- appendFileSync(logPath, `${JSON.stringify({ date: new Date().toISOString(), ...event })}\n`, "utf-8");
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
- catch {
16
- // Audit logging must never break the tool path.
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
- /** Serialize `record` as one JSON line. Never throws. */
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
- * Append-only JSONL writer shared by the runtime log and the usage ledger.
37
+ * Bounded append-only JSONL writer shared by runtime logs, channel archives,
38
+ * audit logs, event history, and the usage ledger.
19
39
  *
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.
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 { existsSync, mkdirSync, renameSync, statSync } from "node:fs";
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
- import { createSerialQueue } from "./serial-queue.js";
5
- import { errorMessage } from "./text-utils.js";
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
- * Append-only JSONL writer shared by the runtime log and the usage ledger.
8
+ * Bounded append-only JSONL writer shared by runtime logs, channel archives,
9
+ * audit logs, event history, and the usage ledger.
8
10
  *
9
- * Writes are serialized per resolved file path, size-tracked in memory (one
10
- * initial stat), and rotated via rename. Observability infrastructure must not
11
- * reach back into the business path, so a failed append only warns once (until
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 queue = createSerialQueue();
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
- let warned = false;
24
- const resolvePath = (now) => (options.pathFor ? options.pathFor(now) : options.path);
25
- const ensureDir = (filePath) => {
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
- mkdirSync(dir, { recursive: true });
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
- if (existsSync(filePath))
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
- if (existsSync(from)) {
51
- renameSync(from, `${filePath}.${i + 1}`);
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
- if (existsSync(filePath)) {
55
- renameSync(filePath, `${filePath}.1`);
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 lineBytes = Buffer.byteLength(line);
62
- if (options.maxSizeBytes && options.maxSizeBytes > 0) {
63
- if (currentSize(filePath) + lineBytes > options.maxSizeBytes && currentSize(filePath) > 0) {
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
- return {
71
- async append(record) {
72
- const filePath = resolvePath(new Date());
73
- const line = `${JSON.stringify(record)}\n`;
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 queue.run(filePath, () => write(filePath, line));
76
- warned = false;
132
+ await write(serialized.filePath, serialized.line, serialized.bytes);
133
+ warnedWrite = false;
77
134
  }
78
- catch (error) {
79
- if (!warned) {
80
- warned = true;
81
- console.warn(`[jsonl-appender] Failed to append to ${filePath}: ${errorMessage(error)}`);
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
  }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Prompt "units": a deterministic, tokenizer-free approximation of prompt size
3
+ * that is stable across models (spec 026 §5.1). Both the system-prompt builder and
4
+ * the per-turn memory context budget against it, so it is a real cross-domain helper
5
+ * — kept out of text-utils.ts on purpose, to avoid growing an unrelated grab bag.
6
+ *
7
+ * Counting rule:
8
+ * - each Han / Hiragana / Katakana / Hangul code point → 1 unit;
9
+ * - each run of Unicode letters/numbers (a non-CJK "word") → 1 unit;
10
+ * - punctuation and whitespace → 0.
11
+ *
12
+ * It never calls a tokenizer, the network or a model, and the same input always
13
+ * produces the same output.
14
+ */
15
+ /**
16
+ * Count prompt units in `text` in a single Unicode-aware pass.
17
+ *
18
+ * Known limitation: a single very long run of letters/numbers with no separators
19
+ * (base64, minified JS, a delimiter-free URL) counts as one unit. Such input is
20
+ * bounded by the character ceiling in `clipTextByPromptUnits` (`maxChars`), which
21
+ * is why every prompt and turn-context budget enforces both units and chars.
22
+ */
23
+ export declare function countPromptUnits(text: string): number;
24
+ export interface ClipByPromptUnitsOptions {
25
+ /** Fraction of the budget kept from the head; the rest is the tail. Default 0.6. */
26
+ headRatio?: number;
27
+ /** Separator shown where the middle was removed. Its own units/chars count against the budget. */
28
+ marker?: string;
29
+ /** Optional hard character ceiling; whichever of units/chars is hit first triggers truncation. */
30
+ maxChars?: number;
31
+ }
32
+ export interface ClipByPromptUnitsResult {
33
+ text: string;
34
+ /** Units in the original input. */
35
+ rawUnits: number;
36
+ /** Units actually kept (head + marker + tail), always ≤ maxUnits. */
37
+ injectedUnits: number;
38
+ truncated: boolean;
39
+ }
40
+ /**
41
+ * Clip `text` to at most `maxUnits` prompt units (and, when given, `maxChars`
42
+ * characters), keeping a head and a tail joined by `marker`. Cuts land only on
43
+ * code-point boundaries, so a surrogate pair is never split, and the marker is
44
+ * paid for out of the budget so the result never exceeds either limit.
45
+ */
46
+ export declare function clipTextByPromptUnits(text: string, maxUnits: number, options?: ClipByPromptUnitsOptions): ClipByPromptUnitsResult;
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Prompt "units": a deterministic, tokenizer-free approximation of prompt size
3
+ * that is stable across models (spec 026 §5.1). Both the system-prompt builder and
4
+ * the per-turn memory context budget against it, so it is a real cross-domain helper
5
+ * — kept out of text-utils.ts on purpose, to avoid growing an unrelated grab bag.
6
+ *
7
+ * Counting rule:
8
+ * - each Han / Hiragana / Katakana / Hangul code point → 1 unit;
9
+ * - each run of Unicode letters/numbers (a non-CJK "word") → 1 unit;
10
+ * - punctuation and whitespace → 0.
11
+ *
12
+ * It never calls a tokenizer, the network or a model, and the same input always
13
+ * produces the same output.
14
+ */
15
+ /** A code point that is its own unit and always ends the surrounding word run. */
16
+ const CJK_REGEX = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
17
+ /** A code point that participates in a non-CJK word run. */
18
+ const WORD_REGEX = /[\p{L}\p{N}]/u;
19
+ function isCjk(codePoint) {
20
+ return CJK_REGEX.test(codePoint);
21
+ }
22
+ function isWord(codePoint) {
23
+ return WORD_REGEX.test(codePoint);
24
+ }
25
+ /**
26
+ * Count prompt units in `text` in a single Unicode-aware pass.
27
+ *
28
+ * Known limitation: a single very long run of letters/numbers with no separators
29
+ * (base64, minified JS, a delimiter-free URL) counts as one unit. Such input is
30
+ * bounded by the character ceiling in `clipTextByPromptUnits` (`maxChars`), which
31
+ * is why every prompt and turn-context budget enforces both units and chars.
32
+ */
33
+ export function countPromptUnits(text) {
34
+ let units = 0;
35
+ let inWord = false;
36
+ // `for...of` iterates code points, so surrogate pairs count as one character.
37
+ for (const char of text) {
38
+ if (isCjk(char)) {
39
+ units++;
40
+ inWord = false;
41
+ }
42
+ else if (isWord(char)) {
43
+ if (!inWord) {
44
+ units++;
45
+ inWord = true;
46
+ }
47
+ }
48
+ else {
49
+ inWord = false;
50
+ }
51
+ }
52
+ return units;
53
+ }
54
+ const DEFAULT_MARKER = "\n\n[... truncated ...]\n\n";
55
+ /**
56
+ * Clip `text` to at most `maxUnits` prompt units (and, when given, `maxChars`
57
+ * characters), keeping a head and a tail joined by `marker`. Cuts land only on
58
+ * code-point boundaries, so a surrogate pair is never split, and the marker is
59
+ * paid for out of the budget so the result never exceeds either limit.
60
+ */
61
+ export function clipTextByPromptUnits(text, maxUnits, options = {}) {
62
+ const headRatio = Math.max(0, Math.min(1, options.headRatio ?? 0.6));
63
+ const marker = options.marker ?? DEFAULT_MARKER;
64
+ const maxChars = options.maxChars;
65
+ const codePoints = Array.from(text);
66
+ const rawUnits = countPromptUnits(text);
67
+ const rawChars = text.length;
68
+ const withinUnits = rawUnits <= maxUnits;
69
+ const withinChars = maxChars === undefined || rawChars <= maxChars;
70
+ if (withinUnits && withinChars) {
71
+ return { text, rawUnits, injectedUnits: rawUnits, truncated: false };
72
+ }
73
+ // Cumulative units and characters after each code point, computed in one pass.
74
+ const cumulativeUnits = new Array(codePoints.length);
75
+ const cumulativeChars = new Array(codePoints.length);
76
+ let units = 0;
77
+ let chars = 0;
78
+ let inWord = false;
79
+ for (let index = 0; index < codePoints.length; index++) {
80
+ const char = codePoints[index];
81
+ if (isCjk(char)) {
82
+ units++;
83
+ inWord = false;
84
+ }
85
+ else if (isWord(char)) {
86
+ if (!inWord) {
87
+ units++;
88
+ inWord = true;
89
+ }
90
+ }
91
+ else {
92
+ inWord = false;
93
+ }
94
+ chars += char.length;
95
+ cumulativeUnits[index] = units;
96
+ cumulativeChars[index] = chars;
97
+ }
98
+ const markerUnits = countPromptUnits(marker);
99
+ const markerChars = marker.length;
100
+ // The marker is paid for out of the budget. If it alone would exceed either ceiling,
101
+ // keep nothing so the documented "injectedUnits ≤ maxUnits" / text ≤ maxChars contract
102
+ // still holds — the caller has sized the budget smaller than its own truncation marker.
103
+ if (markerUnits >= maxUnits || (maxChars !== undefined && markerChars >= maxChars)) {
104
+ return { text: "", rawUnits, injectedUnits: 0, truncated: true };
105
+ }
106
+ const availableUnits = Math.max(0, maxUnits - markerUnits);
107
+ const availableChars = maxChars === undefined ? Number.POSITIVE_INFINITY : Math.max(0, maxChars - markerChars);
108
+ const headUnitBudget = Math.floor(availableUnits * headRatio);
109
+ const tailUnitBudget = availableUnits - headUnitBudget;
110
+ const headCharBudget = Number.isFinite(availableChars) ? Math.floor(availableChars * headRatio) : availableChars;
111
+ const tailCharBudget = Number.isFinite(availableChars) ? availableChars - headCharBudget : availableChars;
112
+ // Largest prefix within both head budgets.
113
+ let headEnd = 0; // exclusive index into codePoints
114
+ for (let index = 0; index < codePoints.length; index++) {
115
+ const prefixUnits = cumulativeUnits[index];
116
+ const prefixChars = cumulativeChars[index];
117
+ if (prefixUnits <= headUnitBudget && prefixChars <= headCharBudget) {
118
+ headEnd = index + 1;
119
+ }
120
+ else {
121
+ break;
122
+ }
123
+ }
124
+ // Units of the suffix starting at `index`, derived from the forward cumulative
125
+ // counts. If a word run straddles the cut, both halves count it, so add one back.
126
+ const totalUnits = rawUnits;
127
+ const unitsFromIndex = (index) => {
128
+ if (index <= 0)
129
+ return totalUnits;
130
+ const prefixUnits = cumulativeUnits[index - 1];
131
+ const left = codePoints[index - 1];
132
+ const right = codePoints[index];
133
+ const split = isWord(left) && !isCjk(left) && isWord(right) && !isCjk(right);
134
+ return totalUnits - prefixUnits + (split ? 1 : 0);
135
+ };
136
+ const charsFromIndex = (index) => {
137
+ if (index <= 0)
138
+ return rawChars;
139
+ return rawChars - cumulativeChars[index - 1];
140
+ };
141
+ // Smallest start index (largest suffix) within both tail budgets and not overlapping the head.
142
+ let tailStart = codePoints.length;
143
+ for (let index = headEnd; index <= codePoints.length; index++) {
144
+ if (unitsFromIndex(index) <= tailUnitBudget && charsFromIndex(index) <= tailCharBudget) {
145
+ tailStart = index;
146
+ break;
147
+ }
148
+ }
149
+ const head = codePoints.slice(0, headEnd).join("");
150
+ const tail = codePoints.slice(tailStart).join("");
151
+ const clipped = `${head.trimEnd()}${marker}${tail.trimStart()}`;
152
+ return { text: clipped, rawUnits, injectedUnits: countPromptUnits(clipped), truncated: true };
153
+ }
@@ -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,