@oyasmi/pipiclaw 0.9.2-beta.4 → 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 (76) hide show
  1. package/dist/agent/channel-runner.d.ts +32 -1
  2. package/dist/agent/channel-runner.js +112 -12
  3. package/dist/agent/context-budget.d.ts +9 -1
  4. package/dist/agent/context-budget.js +11 -5
  5. package/dist/agent/job-manager.d.ts +2 -0
  6. package/dist/agent/job-manager.js +1 -0
  7. package/dist/agent/session-events.js +2 -22
  8. package/dist/agent/types.d.ts +2 -1
  9. package/dist/channel/channel-context.d.ts +4 -0
  10. package/dist/channel/channel-event.d.ts +39 -0
  11. package/dist/channel/channel-event.js +11 -1
  12. package/dist/channel/project-scope-store.js +6 -11
  13. package/dist/channel/store.d.ts +7 -0
  14. package/dist/commands/catalog.d.ts +1 -1
  15. package/dist/memory/bootstrap.js +3 -5
  16. package/dist/memory/candidates.js +2 -4
  17. package/dist/memory/files.d.ts +0 -1
  18. package/dist/memory/files.js +6 -9
  19. package/dist/memory/maintenance-state.js +4 -0
  20. package/dist/runtime/bootstrap.d.ts +12 -6
  21. package/dist/runtime/bootstrap.js +144 -75
  22. package/dist/runtime/delivery.js +1 -0
  23. package/dist/runtime/dingtalk.d.ts +59 -3
  24. package/dist/runtime/dingtalk.js +192 -83
  25. package/dist/runtime/inbound-media.d.ts +60 -0
  26. package/dist/runtime/inbound-media.js +95 -0
  27. package/dist/runtime/task-driver.d.ts +7 -0
  28. package/dist/runtime/task-driver.js +23 -44
  29. package/dist/runtime/task-migration.d.ts +11 -0
  30. package/dist/runtime/task-migration.js +11 -0
  31. package/dist/security/command-guard.js +1 -3
  32. package/dist/security/config.d.ts +1 -1
  33. package/dist/security/config.js +8 -32
  34. package/dist/security/path-guard.js +1 -6
  35. package/dist/security/project-scope.js +1 -3
  36. package/dist/settings.d.ts +2 -2
  37. package/dist/settings.js +13 -20
  38. package/dist/shared/atomic-file.d.ts +2 -3
  39. package/dist/shared/atomic-file.js +8 -9
  40. package/dist/shared/config-diagnostic.d.ts +21 -0
  41. package/dist/shared/config-diagnostic.js +32 -0
  42. package/dist/shared/numeric.d.ts +7 -0
  43. package/dist/shared/numeric.js +19 -0
  44. package/dist/shared/text-utils.d.ts +10 -0
  45. package/dist/shared/text-utils.js +16 -0
  46. package/dist/shared/types.d.ts +23 -0
  47. package/dist/shared/types.js +12 -0
  48. package/dist/shared/with-timeout.d.ts +3 -0
  49. package/dist/shared/with-timeout.js +8 -0
  50. package/dist/subagents/discovery.d.ts +7 -7
  51. package/dist/subagents/discovery.js +27 -59
  52. package/dist/subagents/runs.d.ts +6 -0
  53. package/dist/subagents/runs.js +11 -0
  54. package/dist/subagents/tool.js +195 -128
  55. package/dist/subagents/workspace-lease.js +1 -3
  56. package/dist/tasks/control.d.ts +2 -0
  57. package/dist/tasks/control.js +2 -0
  58. package/dist/tasks/ledger.d.ts +0 -9
  59. package/dist/tasks/ledger.js +92 -158
  60. package/dist/tools/config.d.ts +1 -1
  61. package/dist/tools/config.js +9 -46
  62. package/dist/tools/skill.js +1 -3
  63. package/dist/tools/truncate.js +24 -28
  64. package/dist/tui/app.js +1 -1
  65. package/dist/web/config.js +3 -15
  66. package/examples/sub-agents/builder.md +1 -1
  67. package/examples/sub-agents/documenter.md +1 -1
  68. package/examples/sub-agents/explorer.md +4 -4
  69. package/examples/sub-agents/git-committer.md +4 -4
  70. package/examples/sub-agents/log-sifter.md +3 -3
  71. package/examples/sub-agents/planner.md +1 -1
  72. package/examples/sub-agents/reviewer.md +1 -1
  73. package/examples/sub-agents/worker.md +1 -1
  74. package/package.json +3 -2
  75. package/dist/agent/index.d.ts +0 -2
  76. package/dist/agent/index.js +0 -1
@@ -12,6 +12,17 @@ import { parseTaskEventName, taskEventPrefix } from "../tasks/task-events.js";
12
12
  import { TASK_STATUSES } from "../tasks/transitions.js";
13
13
  import { parseScheduledEventContent } from "./events.js";
14
14
  import { discoverTaskChannels } from "./task-driver.js";
15
+ /**
16
+ * RETIRE AT v0.9.3 (code review 2026-08-30): both migrations in this file are startup self-heal
17
+ * passes for on-disk state written by pre-0.9 betas (the pre-spec-029 `.schedule` event format,
18
+ * and pre-spec-043 v1/v2 task control blocks and status vocabulary). Every 0.9.2-beta install is
19
+ * a small, actively-developed fleet; by the 0.9.3 stable cut every install will have booted at
20
+ * least once on a version that already runs these passes, so there is no longer any on-disk
21
+ * state left for them to find. At 0.9.3: delete both exported functions here, their call sites
22
+ * in `bootstrap.ts`, `parseLegacyTaskControl` in `../tasks/control.js` (this file's only caller),
23
+ * and the paired legacy-state fold in `../memory/maintenance-state.js` (same rationale, unrelated
24
+ * subsystem). Confirm first that no currently-supported version predates the pass being removed.
25
+ */
15
26
  /**
16
27
  * One-time migration closing the 027 window (spec 029, D6).
17
28
  *
@@ -1,8 +1,6 @@
1
1
  import { basename } from "node:path";
2
+ import { stripNullAndNormalize } from "../shared/text-utils.js";
2
3
  const WHITESPACE = /\s+/;
3
- function stripNullAndNormalize(text) {
4
- return text.replace(/\0/g, "").normalize("NFKC");
5
- }
6
4
  function stripComments(command) {
7
5
  let result = "";
8
6
  let inSingle = false;
@@ -1,4 +1,4 @@
1
- import type { ConfigDiagnostic } from "../shared/config-diagnostic.js";
1
+ import { type ConfigDiagnostic } from "../shared/config-diagnostic.js";
2
2
  import type { SecurityConfig } from "./types.js";
3
3
  export interface LoadedSecurityConfig {
4
4
  config: SecurityConfig;
@@ -1,6 +1,6 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
1
  import { join } from "node:path";
3
2
  import { APP_HOME_DIR } from "../paths.js";
3
+ import { loadJsonConfig, pushConfigWarning } from "../shared/config-diagnostic.js";
4
4
  import { errorMessage } from "../shared/text-utils.js";
5
5
  import { isRecord } from "../shared/type-guards.js";
6
6
  export const DEFAULT_SECURITY_CONFIG = {
@@ -51,12 +51,7 @@ function asDenyPatternArray(value, diagnostics, configPath, field) {
51
51
  });
52
52
  }
53
53
  function pushInvalidSecurityDiagnostic(diagnostics, configPath, field, message) {
54
- diagnostics.push({
55
- source: "security",
56
- path: configPath,
57
- severity: "warning",
58
- message: `${field}: ${message}`,
59
- });
54
+ pushConfigWarning(diagnostics, "security", configPath, field, message);
60
55
  }
61
56
  function mergeSecurityConfig(source, configPath, diagnostics) {
62
57
  if (!isRecord(source)) {
@@ -128,31 +123,12 @@ export function getSecurityConfigPath(appHomeDir = APP_HOME_DIR) {
128
123
  return join(appHomeDir, "security.json");
129
124
  }
130
125
  export function loadSecurityConfigWithDiagnostics(appHomeDir = APP_HOME_DIR) {
131
- const configPath = getSecurityConfigPath(appHomeDir);
132
- if (!existsSync(configPath)) {
133
- return { config: DEFAULT_SECURITY_CONFIG, diagnostics: [] };
134
- }
135
- try {
136
- const raw = JSON.parse(readFileSync(configPath, "utf-8"));
137
- const diagnostics = [];
138
- return {
139
- config: mergeSecurityConfig(raw, configPath, diagnostics),
140
- diagnostics,
141
- };
142
- }
143
- catch (error) {
144
- return {
145
- config: DEFAULT_SECURITY_CONFIG,
146
- diagnostics: [
147
- {
148
- source: "security",
149
- path: configPath,
150
- severity: "error",
151
- message: errorMessage(error),
152
- },
153
- ],
154
- };
155
- }
126
+ return loadJsonConfig({
127
+ source: "security",
128
+ path: getSecurityConfigPath(appHomeDir),
129
+ defaults: DEFAULT_SECURITY_CONFIG,
130
+ merge: mergeSecurityConfig,
131
+ });
156
132
  }
157
133
  export function loadSecurityConfig(appHomeDir = APP_HOME_DIR) {
158
134
  return loadSecurityConfigWithDiagnostics(appHomeDir).config;
@@ -2,6 +2,7 @@ import { existsSync, lstatSync, realpathSync } from "node:fs";
2
2
  import { homedir, tmpdir } from "node:os";
3
3
  import { basename, dirname, isAbsolute, join, normalize, resolve } from "node:path";
4
4
  import { PLAYBOOKS_DIR } from "../paths.js";
5
+ import { stripNullAndNormalize, withTrailingSlash } from "../shared/text-utils.js";
5
6
  const PRIVATE_KEY_EXTENSIONS = new Set([".pem", ".key", ".p12", ".pfx"]);
6
7
  const PRIVATE_KEY_NAME_HINTS = /(id_rsa|id_ed25519|private|secret|credentials)/i;
7
8
  const PROC_MEM_PATH = /^\/proc\/\d+\/mem(?:\/|$)/;
@@ -43,12 +44,6 @@ const SYSTEM_DENY_PREFIXES = [
43
44
  "/Library/",
44
45
  "/var/",
45
46
  ];
46
- function stripNullAndNormalize(text) {
47
- return text.replace(/\0/g, "").normalize("NFKC");
48
- }
49
- function withTrailingSlash(path) {
50
- return path.endsWith("/") ? path : `${path}/`;
51
- }
52
47
  function startsWithPathPrefix(path, prefix) {
53
48
  return path === prefix || path.startsWith(withTrailingSlash(prefix));
54
49
  }
@@ -1,6 +1,7 @@
1
1
  import { realpathSync, statSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { isAbsolute, resolve } from "node:path";
4
+ import { withTrailingSlash } from "../shared/text-utils.js";
4
5
  const DIAGNOSTIC_SOURCE = "security";
5
6
  function expandHome(path) {
6
7
  if (path === "~")
@@ -86,9 +87,6 @@ export function resolveProjectAccessPolicy(config, startupCwd) {
86
87
  diagnostics,
87
88
  };
88
89
  }
89
- function withTrailingSlash(path) {
90
- return path.endsWith("/") ? path : `${path}/`;
91
- }
92
90
  /** Prefix match with a path-separator boundary, so `/repo-ab` is not treated as within `/repo-a`. */
93
91
  export function isWithinAllowedRoots(root, policy) {
94
92
  return policy.allowedRoots.some((allowed) => root === allowed || root.startsWith(withTrailingSlash(allowed)));
@@ -142,6 +142,8 @@ export interface PipiclawTuiSettings {
142
142
  */
143
143
  responseMode: ResponseMode;
144
144
  }
145
+ export declare const TASK_DIGEST_SETTINGS: PipiclawTaskDigestSettings;
146
+ export declare const TASK_DRIVER_SETTINGS: PipiclawTaskDriverSettings;
145
147
  /**
146
148
  * Settings manager for pipiclaw.
147
149
  * Stores global settings in the pipiclaw root directory.
@@ -173,8 +175,6 @@ export declare class PipiclawSettingsManager {
173
175
  setCompactionEnabled(enabled: boolean): void;
174
176
  getRetrySettings(): PipiclawRetrySettings;
175
177
  getMemoryRecallSettings(): PipiclawMemoryRecallSettings;
176
- getTaskDigestSettings(): PipiclawTaskDigestSettings;
177
- getTaskDriverSettings(): PipiclawTaskDriverSettings;
178
178
  getSessionMemorySettings(): PipiclawSessionMemorySettings;
179
179
  getMemoryMaintenanceSettings(): PipiclawMemoryMaintenanceSettings;
180
180
  getSessionSearchSettings(): PipiclawSessionSearchSettings;
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(".")) {
@@ -318,12 +327,6 @@ export class PipiclawSettingsManager {
318
327
  rerankWithModel: this.settings.memoryRecall?.rerankWithModel ?? DEFAULT_MEMORY_RECALL.rerankWithModel,
319
328
  };
320
329
  }
321
- getTaskDigestSettings() {
322
- return { ...DEFAULT_TASK_DIGEST };
323
- }
324
- getTaskDriverSettings() {
325
- return { ...DEFAULT_TASK_DRIVER };
326
- }
327
330
  getSessionMemorySettings() {
328
331
  return {
329
332
  ...DEFAULT_SESSION_MEMORY,
@@ -374,24 +377,14 @@ export class PipiclawSettingsManager {
374
377
  * Empty / whitespace-only values are treated as unset (fallback disabled).
375
378
  */
376
379
  getFallbackModelReference() {
377
- const raw = this.settings.fallbackModel;
378
- if (typeof raw !== "string") {
379
- return null;
380
- }
381
- const trimmed = raw.trim();
382
- return trimmed.length > 0 ? trimmed : null;
380
+ return normalizeOptionalModelReference(this.settings.fallbackModel);
383
381
  }
384
382
  /**
385
383
  * Default model reference (`provider/model`) for sub-agents, or null when unset.
386
384
  * Empty / whitespace-only values are treated as unset (spec 032 D5).
387
385
  */
388
386
  getSubAgentModelReference() {
389
- const raw = this.settings.subagentModel;
390
- if (typeof raw !== "string") {
391
- return null;
392
- }
393
- const trimmed = raw.trim();
394
- return trimmed.length > 0 ? trimmed : null;
387
+ return normalizeOptionalModelReference(this.settings.subagentModel);
395
388
  }
396
389
  getDefaultModel() {
397
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
  }
@@ -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)