@oyasmi/pipiclaw 0.9.2-beta.3 → 0.9.2-beta.6

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 (142) hide show
  1. package/README.md +3 -0
  2. package/dist/agent/channel-runner.d.ts +45 -19
  3. package/dist/agent/channel-runner.js +156 -102
  4. package/dist/agent/command-extension.js +1 -1
  5. package/dist/agent/context-budget.d.ts +17 -1
  6. package/dist/agent/context-budget.js +20 -6
  7. package/dist/agent/job-manager.d.ts +3 -1
  8. package/dist/agent/job-manager.js +7 -1
  9. package/dist/agent/prompt/builder.d.ts +0 -1
  10. package/dist/agent/prompt/builder.js +1 -14
  11. package/dist/agent/prompt/manifest.js +2 -1
  12. package/dist/agent/prompt/sections.js +1 -1
  13. package/dist/agent/runner-factory.d.ts +19 -1
  14. package/dist/agent/runner-factory.js +8 -1
  15. package/dist/agent/session-events.d.ts +2 -2
  16. package/dist/agent/session-events.js +2 -22
  17. package/dist/agent/turn-prompt.d.ts +35 -0
  18. package/dist/agent/turn-prompt.js +37 -0
  19. package/dist/agent/turn-recovery.js +1 -1
  20. package/dist/agent/turn-state.d.ts +60 -0
  21. package/dist/agent/turn-state.js +95 -0
  22. package/dist/agent/types.d.ts +5 -4
  23. package/dist/{runtime → channel}/channel-context.d.ts +10 -2
  24. package/dist/{runtime → channel}/channel-context.js +6 -2
  25. package/dist/{runtime → channel}/channel-event.d.ts +39 -0
  26. package/dist/channel/channel-event.js +11 -0
  27. package/dist/channel/channel-paths.d.ts +16 -0
  28. package/dist/{runtime → channel}/channel-paths.js +20 -0
  29. package/dist/{runtime → channel}/project-scope-store.js +6 -11
  30. package/dist/{runtime → channel}/store.d.ts +7 -0
  31. package/dist/{agent/commands.d.ts → commands/catalog.d.ts} +17 -2
  32. package/dist/{agent/commands.js → commands/catalog.js} +30 -0
  33. package/dist/index.d.ts +1 -1
  34. package/dist/log.js +14 -5
  35. package/dist/main.js +29 -0
  36. package/dist/memory/bootstrap.js +3 -5
  37. package/dist/memory/candidates.js +2 -4
  38. package/dist/memory/commands.js +2 -2
  39. package/dist/memory/files.d.ts +0 -1
  40. package/dist/memory/files.js +6 -9
  41. package/dist/memory/maintenance-state.d.ts +8 -0
  42. package/dist/memory/maintenance-state.js +51 -4
  43. package/dist/memory/scheduler.d.ts +6 -0
  44. package/dist/memory/scheduler.js +19 -16
  45. package/dist/playbooks/agent-delegation.md +2 -2
  46. package/dist/runtime/bootstrap.d.ts +14 -8
  47. package/dist/runtime/bootstrap.js +158 -81
  48. package/dist/runtime/delivery.d.ts +3 -3
  49. package/dist/runtime/delivery.js +1 -0
  50. package/dist/runtime/dingtalk.d.ts +62 -6
  51. package/dist/runtime/dingtalk.js +194 -85
  52. package/dist/runtime/durable-dispatch.d.ts +7 -1
  53. package/dist/runtime/durable-dispatch.js +12 -2
  54. package/dist/runtime/event-commands.js +2 -2
  55. package/dist/runtime/events.d.ts +8 -1
  56. package/dist/runtime/events.js +15 -3
  57. package/dist/runtime/inbound-media.d.ts +60 -0
  58. package/dist/runtime/inbound-media.js +95 -0
  59. package/dist/runtime/project-commands.js +2 -2
  60. package/dist/runtime/skill-commands.d.ts +27 -0
  61. package/dist/runtime/skill-commands.js +72 -0
  62. package/dist/runtime/subagent-commands.js +1 -1
  63. package/dist/runtime/task-commands.js +2 -2
  64. package/dist/runtime/task-driver.d.ts +12 -1
  65. package/dist/runtime/task-driver.js +36 -56
  66. package/dist/runtime/task-migration.d.ts +11 -0
  67. package/dist/runtime/task-migration.js +14 -2
  68. package/dist/runtime/task-wake.d.ts +1 -1
  69. package/dist/runtime/task-wake.js +1 -1
  70. package/dist/security/command-guard.js +1 -3
  71. package/dist/security/config.d.ts +1 -1
  72. package/dist/security/config.js +8 -32
  73. package/dist/security/path-guard.js +1 -6
  74. package/dist/security/project-scope.js +1 -3
  75. package/dist/settings.d.ts +3 -2
  76. package/dist/settings.js +82 -20
  77. package/dist/shared/atomic-file.d.ts +2 -3
  78. package/dist/shared/atomic-file.js +8 -9
  79. package/dist/shared/config-diagnostic.d.ts +21 -0
  80. package/dist/shared/config-diagnostic.js +32 -0
  81. package/dist/shared/numeric.d.ts +7 -0
  82. package/dist/shared/numeric.js +19 -0
  83. package/dist/shared/text-utils.d.ts +10 -0
  84. package/dist/shared/text-utils.js +16 -0
  85. package/dist/shared/token-estimate.d.ts +1 -0
  86. package/dist/shared/token-estimate.js +19 -0
  87. package/dist/shared/types.d.ts +23 -0
  88. package/dist/shared/types.js +12 -0
  89. package/dist/shared/with-timeout.d.ts +3 -0
  90. package/dist/shared/with-timeout.js +8 -0
  91. package/dist/subagents/discovery.d.ts +7 -7
  92. package/dist/subagents/discovery.js +27 -59
  93. package/dist/subagents/runs.d.ts +15 -4
  94. package/dist/subagents/runs.js +118 -11
  95. package/dist/subagents/tool.js +199 -131
  96. package/dist/subagents/workspace-lease.js +1 -3
  97. package/dist/tasks/control.d.ts +2 -0
  98. package/dist/tasks/control.js +2 -0
  99. package/dist/tasks/ledger.d.ts +0 -9
  100. package/dist/tasks/ledger.js +92 -158
  101. package/dist/tools/config.d.ts +1 -1
  102. package/dist/tools/config.js +9 -46
  103. package/dist/tools/glob-match.d.ts +25 -4
  104. package/dist/tools/glob-match.js +175 -53
  105. package/dist/tools/glob.js +5 -2
  106. package/dist/tools/index.d.ts +1 -1
  107. package/dist/tools/registry.d.ts +1 -1
  108. package/dist/tools/send-media.d.ts +1 -1
  109. package/dist/tools/skill.d.ts +15 -0
  110. package/dist/tools/skill.js +17 -11
  111. package/dist/tools/truncate.js +24 -28
  112. package/dist/tui/app.js +6 -4
  113. package/dist/tui/commands.d.ts +1 -0
  114. package/dist/tui/commands.js +3 -1
  115. package/dist/tui/terminal-context.d.ts +2 -2
  116. package/dist/tui/terminal-media-sender.d.ts +1 -1
  117. package/dist/tui/turn-controller.d.ts +2 -1
  118. package/dist/tui/turn-controller.js +2 -1
  119. package/dist/web/config.js +3 -15
  120. package/examples/sub-agents/README.md +2 -2
  121. package/examples/sub-agents/builder.md +1 -1
  122. package/examples/sub-agents/documenter.md +1 -1
  123. package/examples/sub-agents/explorer.md +4 -4
  124. package/examples/sub-agents/git-committer.md +5 -4
  125. package/examples/sub-agents/log-sifter.md +4 -4
  126. package/examples/sub-agents/planner.md +1 -1
  127. package/examples/sub-agents/reviewer.md +1 -1
  128. package/examples/sub-agents/verifier.md +1 -1
  129. package/examples/sub-agents/worker.md +3 -3
  130. package/package.json +3 -2
  131. package/dist/agent/index.d.ts +0 -2
  132. package/dist/agent/index.js +0 -1
  133. package/dist/runtime/channel-event.js +0 -1
  134. package/dist/runtime/channel-paths.d.ts +0 -4
  135. /package/dist/{runtime → channel}/active-session-store.d.ts +0 -0
  136. /package/dist/{runtime → channel}/active-session-store.js +0 -0
  137. /package/dist/{runtime → channel}/channel-index.d.ts +0 -0
  138. /package/dist/{runtime → channel}/channel-index.js +0 -0
  139. /package/dist/{runtime → channel}/project-scope-store.d.ts +0 -0
  140. /package/dist/{runtime → channel}/store.js +0 -0
  141. /package/dist/{agent → commands}/reply-limits.d.ts +0 -0
  142. /package/dist/{agent → commands}/reply-limits.js +0 -0
package/dist/settings.js CHANGED
@@ -37,14 +37,14 @@ const DEFAULT_MEMORY_RECALL = {
37
37
  };
38
38
  // Cheap and high-value: reading a handful of task frontmatters and always surfacing
39
39
  // the in-flight agenda is worth more than the tokens it costs, so it defaults on.
40
- const DEFAULT_TASK_DIGEST = {
40
+ export const TASK_DIGEST_SETTINGS = {
41
41
  maxTasks: 8,
42
42
  maxChars: 1000,
43
43
  };
44
44
  // The driver makes `wake` an executable task property rather than a convention
45
45
  // that requires users to install a heartbeat event and sensor script. A changed
46
46
  // task can continue promptly; an unchanged task backs off to avoid token loops.
47
- const DEFAULT_TASK_DRIVER = {
47
+ export const TASK_DRIVER_SETTINGS = {
48
48
  continuationDelayMinutes: 5,
49
49
  stalledRetryMinutes: 60,
50
50
  maxDispatchesPerTick: 4,
@@ -121,6 +121,15 @@ const RETIRED_SETTINGS_KEYS = [
121
121
  "taskDriver.maxDispatchesPerTick",
122
122
  "taskDriver.maxSleepMinutes",
123
123
  ];
124
+ /** Shared by `getFallbackModelReference`/`getSubAgentModelReference`: empty or whitespace-only
125
+ * counts as unset, same as the field being absent. */
126
+ function normalizeOptionalModelReference(raw) {
127
+ if (typeof raw !== "string") {
128
+ return null;
129
+ }
130
+ const trimmed = raw.trim();
131
+ return trimmed.length > 0 ? trimmed : null;
132
+ }
124
133
  function hasNestedKey(root, dottedPath) {
125
134
  let node = root;
126
135
  for (const segment of dottedPath.split(".")) {
@@ -135,6 +144,69 @@ function hasNestedKey(root, dottedPath) {
135
144
  function findRetiredSettingsKeys(parsed) {
136
145
  return RETIRED_SETTINGS_KEYS.filter((key) => hasNestedKey(parsed, key));
137
146
  }
147
+ /**
148
+ * Every enum-valued key, with the values it accepts.
149
+ *
150
+ * `settings.json` is hand-edited and nothing type-checks it, so a typo used to travel straight
151
+ * into the runtime as a string the code never compares equal to anything. The failure modes were
152
+ * not uniform and none of them said anything: `logging.level: "verbos"` made *every* log record
153
+ * fail its threshold comparison (`LEVEL_ORDER[level] >= NaN`) and silenced the log entirely;
154
+ * `delegation.notices: "liv"` fell through both negative checks and behaved as `live`, the
155
+ * opposite of the "off" a nervous operator was reaching for. Validating here — once, on load —
156
+ * means an unrecognized value is dropped so the documented default applies, and the operator is
157
+ * told which key was ignored.
158
+ *
159
+ * The value lists are literal rather than imported: `ResponseMode` lives in the DingTalk
160
+ * transport, and a value import would tie settings loading to that module's import graph. The
161
+ * `satisfies` clauses keep them honest against the unions they mirror.
162
+ */
163
+ const ENUM_SETTINGS = [
164
+ { path: "logging.level", values: ["debug", "info", "warn", "error"] },
165
+ {
166
+ path: "tui.responseMode",
167
+ values: [
168
+ "full_progress_then_plain_final",
169
+ "rolling_progress_then_plain_final",
170
+ "final_card_only",
171
+ ],
172
+ },
173
+ { path: "delegation.notices", values: ["off", "settled", "live"] },
174
+ ];
175
+ function readNestedKey(root, dottedPath) {
176
+ const segments = dottedPath.split(".");
177
+ const key = segments.pop();
178
+ if (!key)
179
+ return undefined;
180
+ let node = root;
181
+ for (const segment of segments) {
182
+ if (!node || typeof node !== "object" || Array.isArray(node))
183
+ return undefined;
184
+ node = node[segment];
185
+ }
186
+ if (!node || typeof node !== "object" || Array.isArray(node))
187
+ return undefined;
188
+ const parent = node;
189
+ return Object.hasOwn(parent, key) ? { parent, key } : undefined;
190
+ }
191
+ /**
192
+ * Drop every enum key whose value is not one this build understands, and describe what was
193
+ * dropped. Deleting rather than coercing is deliberate: `??` then yields the same default a
194
+ * missing key would, so one bad value cannot produce a state the rest of the code never expects.
195
+ */
196
+ function stripInvalidEnumValues(parsed) {
197
+ const problems = [];
198
+ for (const { path, values } of ENUM_SETTINGS) {
199
+ const found = readNestedKey(parsed, path);
200
+ if (!found)
201
+ continue;
202
+ const value = found.parent[found.key];
203
+ if (value === undefined || values.includes(value))
204
+ continue;
205
+ delete found.parent[found.key];
206
+ problems.push(`${path}: ${JSON.stringify(value)} is not one of ${values.join(" | ")}; using the default instead`);
207
+ }
208
+ return problems;
209
+ }
138
210
  /**
139
211
  * Settings manager for pipiclaw.
140
212
  * Stores global settings in the pipiclaw root directory.
@@ -143,6 +215,7 @@ export class PipiclawSettingsManager {
143
215
  constructor(baseDir) {
144
216
  this.loadErrors = [];
145
217
  this.retiredKeys = [];
218
+ this.invalidEnumValues = [];
146
219
  /** The file's change token as of the last actual parse; see `reload`. */
147
220
  this.loadedStamp = "";
148
221
  this.settingsPath = join(baseDir, "settings.json");
@@ -151,6 +224,7 @@ export class PipiclawSettingsManager {
151
224
  load() {
152
225
  this.loadErrors = [];
153
226
  this.retiredKeys = [];
227
+ this.invalidEnumValues = [];
154
228
  this.loadedStamp = fileStamp(this.settingsPath);
155
229
  if (!existsSync(this.settingsPath)) {
156
230
  return {};
@@ -166,6 +240,7 @@ export class PipiclawSettingsManager {
166
240
  return {};
167
241
  }
168
242
  this.retiredKeys = findRetiredSettingsKeys(parsed);
243
+ this.invalidEnumValues = stripInvalidEnumValues(parsed);
169
244
  return parsed;
170
245
  }
171
246
  catch (error) {
@@ -221,6 +296,9 @@ export class PipiclawSettingsManager {
221
296
  message: `${this.retiredKeys.join(", ")}: no longer configurable; these are now built-in constants and the values here are ignored. Remove them from settings.json.`,
222
297
  });
223
298
  }
299
+ for (const message of this.invalidEnumValues) {
300
+ diagnostics.push({ source: "settings", path: this.settingsPath, severity: "warning", message });
301
+ }
224
302
  return diagnostics;
225
303
  }
226
304
  getCompactionSettings() {
@@ -249,12 +327,6 @@ export class PipiclawSettingsManager {
249
327
  rerankWithModel: this.settings.memoryRecall?.rerankWithModel ?? DEFAULT_MEMORY_RECALL.rerankWithModel,
250
328
  };
251
329
  }
252
- getTaskDigestSettings() {
253
- return { ...DEFAULT_TASK_DIGEST };
254
- }
255
- getTaskDriverSettings() {
256
- return { ...DEFAULT_TASK_DRIVER };
257
- }
258
330
  getSessionMemorySettings() {
259
331
  return {
260
332
  ...DEFAULT_SESSION_MEMORY,
@@ -305,24 +377,14 @@ export class PipiclawSettingsManager {
305
377
  * Empty / whitespace-only values are treated as unset (fallback disabled).
306
378
  */
307
379
  getFallbackModelReference() {
308
- const raw = this.settings.fallbackModel;
309
- if (typeof raw !== "string") {
310
- return null;
311
- }
312
- const trimmed = raw.trim();
313
- return trimmed.length > 0 ? trimmed : null;
380
+ return normalizeOptionalModelReference(this.settings.fallbackModel);
314
381
  }
315
382
  /**
316
383
  * Default model reference (`provider/model`) for sub-agents, or null when unset.
317
384
  * Empty / whitespace-only values are treated as unset (spec 032 D5).
318
385
  */
319
386
  getSubAgentModelReference() {
320
- const raw = this.settings.subagentModel;
321
- if (typeof raw !== "string") {
322
- return null;
323
- }
324
- const trimmed = raw.trim();
325
- return trimmed.length > 0 ? trimmed : null;
387
+ return normalizeOptionalModelReference(this.settings.subagentModel);
326
388
  }
327
389
  getDefaultModel() {
328
390
  return this.settings.defaultModel;
@@ -1,6 +1,5 @@
1
1
  export declare function createAtomicTempPath(path: string): string;
2
2
  export interface WriteFileAtomicallyOptions {
3
- tempPath?: string;
4
3
  /**
5
4
  * `fchmod` the temp file to the existing target's permission bits before renaming over it, so
6
5
  * an atomic overwrite of an executable file does not silently strip its `x` bit (spec 044,
@@ -8,11 +7,11 @@ export interface WriteFileAtomicallyOptions {
8
7
  */
9
8
  preserveMode?: boolean;
10
9
  }
11
- export declare function writeFileAtomically(path: string, content: string | Buffer, optionsOrTempPath?: WriteFileAtomicallyOptions | string): Promise<void>;
10
+ export declare function writeFileAtomically(path: string, content: string | Buffer, options?: WriteFileAtomicallyOptions): Promise<void>;
12
11
  /**
13
12
  * Synchronous counterpart to {@link writeFileAtomically} for the handful of call sites that
14
13
  * cannot go async (a settings-manager `save(): void` and a per-message conversation-meta write
15
14
  * called from a sync event handler) — write-temp-then-rename still beats a direct
16
15
  * `writeFileSync`, since a crash mid-write can no longer truncate the target in place.
17
16
  */
18
- export declare function writeFileAtomicallySync(path: string, content: string | Buffer, tempPath?: string): void;
17
+ export declare function writeFileAtomicallySync(path: string, content: string | Buffer): void;
@@ -13,9 +13,8 @@ async function existingMode(path) {
13
13
  return undefined;
14
14
  }
15
15
  }
16
- export async function writeFileAtomically(path, content, optionsOrTempPath = {}) {
17
- const options = typeof optionsOrTempPath === "string" ? { tempPath: optionsOrTempPath } : optionsOrTempPath;
18
- const tempPath = options.tempPath ?? createAtomicTempPath(path);
16
+ export async function writeFileAtomically(path, content, options = {}) {
17
+ const tempPath = createAtomicTempPath(path);
19
18
  const dir = dirname(path);
20
19
  await mkdir(dir, { recursive: true });
21
20
  try {
@@ -61,22 +60,22 @@ export async function writeFileAtomically(path, content, optionsOrTempPath = {})
61
60
  * called from a sync event handler) — write-temp-then-rename still beats a direct
62
61
  * `writeFileSync`, since a crash mid-write can no longer truncate the target in place.
63
62
  */
64
- export function writeFileAtomicallySync(path, content, tempPath) {
65
- const resolvedTempPath = tempPath ?? createAtomicTempPath(path);
63
+ export function writeFileAtomicallySync(path, content) {
64
+ const tempPath = createAtomicTempPath(path);
66
65
  const dir = dirname(path);
67
66
  mkdirSync(dir, { recursive: true });
68
67
  try {
69
68
  if (typeof content === "string") {
70
- writeFileSync(resolvedTempPath, content, "utf-8");
69
+ writeFileSync(tempPath, content, "utf-8");
71
70
  }
72
71
  else {
73
- writeFileSync(resolvedTempPath, content);
72
+ writeFileSync(tempPath, content);
74
73
  }
75
- renameSync(resolvedTempPath, path);
74
+ renameSync(tempPath, path);
76
75
  }
77
76
  catch (error) {
78
77
  try {
79
- unlinkSync(resolvedTempPath);
78
+ unlinkSync(tempPath);
80
79
  }
81
80
  catch { }
82
81
  throw error;
@@ -6,3 +6,24 @@ export interface ConfigDiagnostic {
6
6
  message: string;
7
7
  }
8
8
  export declare function formatConfigDiagnostic(diagnostic: ConfigDiagnostic): string;
9
+ /**
10
+ * Push a field-scoped warning, prefixing `field: ` onto the message — shared by every app-level
11
+ * JSON config loader's per-field validators (`tools.json`, `security.json`).
12
+ */
13
+ export declare function pushConfigWarning(diagnostics: ConfigDiagnostic[], source: ConfigDiagnostic["source"], path: string, field: string, message: string): void;
14
+ /**
15
+ * Shared "read JSON, merge onto defaults, collect diagnostics" shape for the app-level config
16
+ * files (`tools.json`, `security.json`, spec 035): defaults when the file is absent, one `error`
17
+ * diagnostic (never a thrown exception) when it fails to parse, otherwise whatever field-level
18
+ * `warning`s `merge` collected. `merge` owns everything past "valid JSON" — structural validation,
19
+ * per-field fallbacks, and pushing its own warnings via {@link pushConfigWarning}.
20
+ */
21
+ export declare function loadJsonConfig<T>(input: {
22
+ source: ConfigDiagnostic["source"];
23
+ path: string;
24
+ defaults: T;
25
+ merge: (raw: unknown, path: string, diagnostics: ConfigDiagnostic[]) => T;
26
+ }): {
27
+ config: T;
28
+ diagnostics: ConfigDiagnostic[];
29
+ };
@@ -1,3 +1,35 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { errorMessage } from "./text-utils.js";
1
3
  export function formatConfigDiagnostic(diagnostic) {
2
4
  return `${diagnostic.source}.json: ${diagnostic.message}`;
3
5
  }
6
+ /**
7
+ * Push a field-scoped warning, prefixing `field: ` onto the message — shared by every app-level
8
+ * JSON config loader's per-field validators (`tools.json`, `security.json`).
9
+ */
10
+ export function pushConfigWarning(diagnostics, source, path, field, message) {
11
+ diagnostics.push({ source, path, severity: "warning", message: `${field}: ${message}` });
12
+ }
13
+ /**
14
+ * Shared "read JSON, merge onto defaults, collect diagnostics" shape for the app-level config
15
+ * files (`tools.json`, `security.json`, spec 035): defaults when the file is absent, one `error`
16
+ * diagnostic (never a thrown exception) when it fails to parse, otherwise whatever field-level
17
+ * `warning`s `merge` collected. `merge` owns everything past "valid JSON" — structural validation,
18
+ * per-field fallbacks, and pushing its own warnings via {@link pushConfigWarning}.
19
+ */
20
+ export function loadJsonConfig(input) {
21
+ if (!existsSync(input.path)) {
22
+ return { config: input.defaults, diagnostics: [] };
23
+ }
24
+ try {
25
+ const raw = JSON.parse(readFileSync(input.path, "utf-8"));
26
+ const diagnostics = [];
27
+ return { config: input.merge(raw, input.path, diagnostics), diagnostics };
28
+ }
29
+ catch (error) {
30
+ return {
31
+ config: input.defaults,
32
+ diagnostics: [{ source: input.source, path: input.path, severity: "error", message: errorMessage(error) }],
33
+ };
34
+ }
35
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Coerce an untrusted numeric config/request value into an integer within `[minimum, maximum]`,
3
+ * falling back to `fallback` for anything not a finite number or out of range. Shared by the
4
+ * app-level config loaders (`tools.json`) and web request parameter resolution — both need the
5
+ * same "trust nothing, fail closed to a safe default" numeric parsing.
6
+ */
7
+ export declare function clampInteger(value: unknown, fallback: number, minimum: number, maximum?: number): number;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Coerce an untrusted numeric config/request value into an integer within `[minimum, maximum]`,
3
+ * falling back to `fallback` for anything not a finite number or out of range. Shared by the
4
+ * app-level config loaders (`tools.json`) and web request parameter resolution — both need the
5
+ * same "trust nothing, fail closed to a safe default" numeric parsing.
6
+ */
7
+ export function clampInteger(value, fallback, minimum, maximum) {
8
+ if (typeof value !== "number" || !Number.isFinite(value)) {
9
+ return fallback;
10
+ }
11
+ const normalized = Math.floor(value);
12
+ if (normalized < minimum) {
13
+ return fallback;
14
+ }
15
+ if (maximum !== undefined && normalized > maximum) {
16
+ return fallback;
17
+ }
18
+ return normalized;
19
+ }
@@ -6,7 +6,17 @@ export declare function clipText(text: string, maxChars: number, opts?: {
6
6
  }): string;
7
7
  export declare function truncate(text: string, maxLen: number): string;
8
8
  export declare const HAN_REGEX: RegExp;
9
+ /** Append a trailing `/` unless the path already has one — the shared prefix-match building
10
+ * block so `/repo-ab` is never mistaken for a path within `/repo-a`. */
11
+ export declare function withTrailingSlash(path: string): string;
12
+ /** Strip embedded NUL bytes and Unicode-normalize to NFKC — the shared first step every path and
13
+ * shell-command guard applies before pattern matching, so a null-byte truncation trick or a
14
+ * confusable-character encoding cannot slip past the check that runs after it. */
15
+ export declare function stripNullAndNormalize(text: string): string;
9
16
  /** Strip a trailing `.json` from an event filename to get its logical name. */
10
17
  export declare function eventNameFromFilename(filename: string): string;
18
+ /** Normalize CRLF to LF and trim surrounding whitespace — the common first step before comparing,
19
+ * hashing, or re-parsing content read from disk. */
20
+ export declare function stripCrAndTrim(content: string): string;
11
21
  export declare function errorMessage(err: unknown): string;
12
22
  export declare function extractAssistantText(message: AssistantMessage): string;
@@ -22,10 +22,26 @@ export function truncate(text, maxLen) {
22
22
  return `${text.substring(0, maxLen - 3)}...`;
23
23
  }
24
24
  export const HAN_REGEX = /\p{Script=Han}/u;
25
+ /** Append a trailing `/` unless the path already has one — the shared prefix-match building
26
+ * block so `/repo-ab` is never mistaken for a path within `/repo-a`. */
27
+ export function withTrailingSlash(path) {
28
+ return path.endsWith("/") ? path : `${path}/`;
29
+ }
30
+ /** Strip embedded NUL bytes and Unicode-normalize to NFKC — the shared first step every path and
31
+ * shell-command guard applies before pattern matching, so a null-byte truncation trick or a
32
+ * confusable-character encoding cannot slip past the check that runs after it. */
33
+ export function stripNullAndNormalize(text) {
34
+ return text.replace(/\0/g, "").normalize("NFKC");
35
+ }
25
36
  /** Strip a trailing `.json` from an event filename to get its logical name. */
26
37
  export function eventNameFromFilename(filename) {
27
38
  return filename.endsWith(".json") ? filename.slice(0, -".json".length) : filename;
28
39
  }
40
+ /** Normalize CRLF to LF and trim surrounding whitespace — the common first step before comparing,
41
+ * hashing, or re-parsing content read from disk. */
42
+ export function stripCrAndTrim(content) {
43
+ return content.replace(/\r/g, "").trim();
44
+ }
29
45
  export function errorMessage(err) {
30
46
  return err instanceof Error ? err.message : String(err);
31
47
  }
@@ -0,0 +1 @@
1
+ export declare function estimateTokens(text: string): number;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Rough token estimate, shared by everything that has to reason about context size without
3
+ * calling a tokenizer. CJK runs about one token per character, Latin text about four characters
4
+ * per token; the provider's real tokenizer is the authority, and the usage ledger records what
5
+ * it billed.
6
+ *
7
+ * The script split matters wherever the estimate gates behavior rather than just reporting: a
8
+ * flat characters-per-token ratio tuned for Latin text underestimates Chinese input roughly
9
+ * threefold, so a budget check would clear a message that in fact does not fit.
10
+ */
11
+ const CJK_REGEX = /\p{Script=Han}|\p{Script=Hiragana}|\p{Script=Katakana}|\p{Script=Hangul}/u;
12
+ export function estimateTokens(text) {
13
+ let cjk = 0;
14
+ for (const char of text) {
15
+ if (CJK_REGEX.test(char))
16
+ cjk++;
17
+ }
18
+ return Math.ceil(cjk + (text.length - cjk) / 4);
19
+ }
@@ -13,3 +13,26 @@ export interface UsageTotals {
13
13
  };
14
14
  }
15
15
  export declare function createEmptyUsageTotals(): UsageTotals;
16
+ /**
17
+ * The minimal shape `addUsage` needs — both the SDK's own `Usage` (`totalTokens` required, no
18
+ * `total`) and this codebase's looser event-message usage shapes (`total` and/or `totalTokens`,
19
+ * both optional) satisfy it structurally, so one accumulator serves every usage-tallying site
20
+ * (assistant turns, sub-agent runs, internal delegation workers) instead of each hand-rolling the
21
+ * same ten-field sum.
22
+ */
23
+ export interface UsageLike {
24
+ input: number;
25
+ output: number;
26
+ cacheRead: number;
27
+ cacheWrite: number;
28
+ total?: number;
29
+ totalTokens?: number;
30
+ cost: {
31
+ input: number;
32
+ output: number;
33
+ cacheRead: number;
34
+ cacheWrite: number;
35
+ total: number;
36
+ };
37
+ }
38
+ export declare function addUsage(target: UsageTotals, usage: UsageLike): void;
@@ -8,3 +8,15 @@ export function createEmptyUsageTotals() {
8
8
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
9
9
  };
10
10
  }
11
+ export function addUsage(target, usage) {
12
+ target.input += usage.input;
13
+ target.output += usage.output;
14
+ target.cacheRead += usage.cacheRead;
15
+ target.cacheWrite += usage.cacheWrite;
16
+ target.total += usage.total ?? usage.totalTokens ?? usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
17
+ target.cost.input += usage.cost.input;
18
+ target.cost.output += usage.cost.output;
19
+ target.cost.cacheRead += usage.cost.cacheRead;
20
+ target.cost.cacheWrite += usage.cost.cacheWrite;
21
+ target.cost.total += usage.cost.total;
22
+ }
@@ -11,4 +11,7 @@ export declare class OperationTimeoutError extends Error {
11
11
  readonly timeoutMs: number;
12
12
  constructor(operation: string, timeoutMs: number);
13
13
  }
14
+ /** A delay that never keeps the process alive on its own — every background-loop backoff and
15
+ * budget wait in the codebase wants this, not a bare `setTimeout` promise. */
16
+ export declare function sleepUnref(ms: number): Promise<void>;
14
17
  export declare function withTimeout<T>(operation: string, timeoutMs: number, run: () => Promise<T>): Promise<T>;
@@ -14,6 +14,14 @@ export class OperationTimeoutError extends Error {
14
14
  this.timeoutMs = timeoutMs;
15
15
  }
16
16
  }
17
+ /** A delay that never keeps the process alive on its own — every background-loop backoff and
18
+ * budget wait in the codebase wants this, not a bare `setTimeout` promise. */
19
+ export function sleepUnref(ms) {
20
+ return new Promise((resolve) => {
21
+ const timer = setTimeout(resolve, ms);
22
+ timer.unref?.();
23
+ });
24
+ }
17
25
  export async function withTimeout(operation, timeoutMs, run) {
18
26
  if (!(timeoutMs > 0)) {
19
27
  return run();
@@ -31,16 +31,16 @@ export declare const SUB_AGENT_EFFORT_PRESETS: {
31
31
  readonly bashTimeoutSec: 60;
32
32
  };
33
33
  readonly standard: {
34
- readonly maxTurns: 24;
35
- readonly maxToolCalls: 48;
36
- readonly maxWallTimeSec: 300;
34
+ readonly maxTurns: 32;
35
+ readonly maxToolCalls: 96;
36
+ readonly maxWallTimeSec: 600;
37
37
  readonly bashTimeoutSec: 120;
38
38
  };
39
39
  readonly deep: {
40
- readonly maxTurns: 48;
41
- readonly maxToolCalls: 96;
42
- readonly maxWallTimeSec: 900;
43
- readonly bashTimeoutSec: 180;
40
+ readonly maxTurns: 64;
41
+ readonly maxToolCalls: 160;
42
+ readonly maxWallTimeSec: 1800;
43
+ readonly bashTimeoutSec: 300;
44
44
  };
45
45
  };
46
46
  export type SubAgentEffort = keyof typeof SUB_AGENT_EFFORT_PRESETS;
@@ -10,12 +10,12 @@ import { splitShellWords } from "../shared/shell-words.js";
10
10
  import { errorMessage } from "../shared/text-utils.js";
11
11
  const ALLOWED_SUB_AGENT_TOOLS = ["read", "grep", "bash", "edit", "write", "web_search", "web_fetch"];
12
12
  const DEFAULT_SUB_AGENT_TOOLS = ["read", "bash"];
13
- const DEFAULT_MAX_TURNS = 24;
14
- const DEFAULT_MAX_TOOL_CALLS = 48;
15
- const DEFAULT_MAX_WALL_TIME_SEC = 300;
13
+ const DEFAULT_MAX_TURNS = 32;
14
+ const DEFAULT_MAX_TOOL_CALLS = 96;
15
+ const DEFAULT_MAX_WALL_TIME_SEC = 600;
16
16
  const DEFAULT_BASH_TIMEOUT_SEC = 120;
17
17
  /** External runs have no turn/tool-call budget (D5); wall time is their only lever. */
18
- const DEFAULT_EXTERNAL_MAX_WALL_TIME_SEC = 1800;
18
+ const DEFAULT_EXTERNAL_MAX_WALL_TIME_SEC = 3600;
19
19
  const MAX_SUB_AGENT_TASK_CHARS = 12000;
20
20
  const MAX_SUB_AGENT_SYSTEM_PROMPT_CHARS = 16000;
21
21
  const ALLOWED_CONTEXT_MODES = ["isolated", "contextual"];
@@ -41,7 +41,7 @@ export const SUB_AGENT_EFFORT_PRESETS = {
41
41
  maxWallTimeSec: DEFAULT_MAX_WALL_TIME_SEC,
42
42
  bashTimeoutSec: DEFAULT_BASH_TIMEOUT_SEC,
43
43
  },
44
- deep: { maxTurns: 48, maxToolCalls: 96, maxWallTimeSec: 900, bashTimeoutSec: 180 },
44
+ deep: { maxTurns: 64, maxToolCalls: 160, maxWallTimeSec: 1800, bashTimeoutSec: 300 },
45
45
  };
46
46
  const ALLOWED_EFFORTS = Object.keys(SUB_AGENT_EFFORT_PRESETS);
47
47
  /**
@@ -145,40 +145,34 @@ function parseStringList(raw, label) {
145
145
  }
146
146
  return { values: [], error: `Invalid "${label}" frontmatter: expected a string or string[]` };
147
147
  }
148
- function parseContextMode(raw) {
148
+ /**
149
+ * Shared shape for every frontmatter/override field whose only validation is "one of a fixed
150
+ * allow-list, else report an error and fall back": `contextMode`, `thinkingLevel`, `effort`,
151
+ * `runtime`, `harness`, `workload`, `mutates` all had their own byte-identical copy of this
152
+ * before (review 2026-08-29) — only the label, allow-list and fallback ever differed.
153
+ */
154
+ function parseEnumField(raw, label, allowed, fallback) {
149
155
  const normalized = readOptionalTrimmedString(raw);
150
156
  if (!normalized) {
151
- return { value: "isolated" };
157
+ return { value: fallback };
152
158
  }
153
- if (ALLOWED_CONTEXT_MODES.includes(normalized)) {
159
+ if (allowed.includes(normalized)) {
154
160
  return { value: normalized };
155
161
  }
156
162
  return {
157
- value: "isolated",
158
- error: `Unknown contextMode "${normalized}". Allowed values: ${ALLOWED_CONTEXT_MODES.join(", ")}`,
163
+ value: fallback,
164
+ error: `Unknown ${label} "${normalized}". Allowed values: ${allowed.join(", ")}`,
159
165
  };
160
166
  }
167
+ function parseContextMode(raw) {
168
+ const result = parseEnumField(raw, "contextMode", ALLOWED_CONTEXT_MODES, "isolated");
169
+ return { value: result.value ?? "isolated", error: result.error };
170
+ }
161
171
  function parseThinkingLevel(raw) {
162
- const normalized = readOptionalTrimmedString(raw);
163
- if (!normalized) {
164
- return {};
165
- }
166
- if (ALLOWED_THINKING_LEVELS.includes(normalized)) {
167
- return { value: normalized };
168
- }
169
- return {
170
- error: `Unknown thinkingLevel "${normalized}". Allowed values: ${ALLOWED_THINKING_LEVELS.join(", ")}`,
171
- };
172
+ return parseEnumField(raw, "thinkingLevel", ALLOWED_THINKING_LEVELS);
172
173
  }
173
174
  function parseEffort(raw) {
174
- const normalized = readOptionalTrimmedString(raw);
175
- if (!normalized) {
176
- return {};
177
- }
178
- if (ALLOWED_EFFORTS.includes(normalized)) {
179
- return { value: normalized };
180
- }
181
- return { error: `Unknown effort "${normalized}". Allowed values: ${ALLOWED_EFFORTS.join(", ")}` };
175
+ return parseEnumField(raw, "effort", ALLOWED_EFFORTS);
182
176
  }
183
177
  function parseContextChoice(raw) {
184
178
  const normalized = readOptionalTrimmedString(raw);
@@ -270,43 +264,17 @@ function resolveModelReference(modelRef, availableModels) {
270
264
  return { error: `Model reference "${modelRef}" was not found among available models.` };
271
265
  }
272
266
  function parseRuntime(raw) {
273
- const normalized = readOptionalTrimmedString(raw);
274
- if (!normalized)
275
- return { value: "internal" };
276
- if (ALLOWED_RUNTIMES.includes(normalized)) {
277
- return { value: normalized };
278
- }
279
- return {
280
- value: "internal",
281
- error: `Unknown runtime "${normalized}". Allowed values: ${ALLOWED_RUNTIMES.join(", ")}`,
282
- };
267
+ const result = parseEnumField(raw, "runtime", ALLOWED_RUNTIMES, "internal");
268
+ return { value: result.value ?? "internal", error: result.error };
283
269
  }
284
270
  function parseHarness(raw) {
285
- const normalized = readOptionalTrimmedString(raw);
286
- if (!normalized)
287
- return {};
288
- if (ALLOWED_HARNESSES.includes(normalized)) {
289
- return { value: normalized };
290
- }
291
- return { error: `Unknown harness "${normalized}". Allowed values: ${ALLOWED_HARNESSES.join(", ")}` };
271
+ return parseEnumField(raw, "harness", ALLOWED_HARNESSES);
292
272
  }
293
273
  function parseWorkload(raw) {
294
- const normalized = readOptionalTrimmedString(raw);
295
- if (!normalized)
296
- return {};
297
- if (ALLOWED_WORKLOADS.includes(normalized)) {
298
- return { value: normalized };
299
- }
300
- return { error: `Unknown workload "${normalized}". Allowed values: ${ALLOWED_WORKLOADS.join(", ")}` };
274
+ return parseEnumField(raw, "workload", ALLOWED_WORKLOADS);
301
275
  }
302
276
  function parseMutates(raw) {
303
- const normalized = readOptionalTrimmedString(raw);
304
- if (!normalized)
305
- return {};
306
- if (ALLOWED_MUTATES.includes(normalized)) {
307
- return { value: normalized };
308
- }
309
- return { error: `Unknown mutates "${normalized}". Allowed values: ${ALLOWED_MUTATES.join(", ")}` };
277
+ return parseEnumField(raw, "mutates", ALLOWED_MUTATES);
310
278
  }
311
279
  function parseBooleanField(raw, label) {
312
280
  if (raw === undefined || raw === null)