@oyasmi/pipiclaw 0.9.1-beta.2 → 0.9.2-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. package/dist/agent/channel-runner.d.ts +9 -1
  2. package/dist/agent/channel-runner.js +51 -18
  3. package/dist/agent/command-extension.js +24 -27
  4. package/dist/agent/commands.d.ts +51 -7
  5. package/dist/agent/commands.js +199 -59
  6. package/dist/agent/effect-ledger.js +9 -2
  7. package/dist/agent/job-manager.d.ts +4 -0
  8. package/dist/agent/job-manager.js +17 -2
  9. package/dist/agent/prompt/manifest.d.ts +1 -1
  10. package/dist/agent/prompt/manifest.js +6 -7
  11. package/dist/agent/prompt/sections.js +9 -5
  12. package/dist/agent/reply-limits.d.ts +16 -0
  13. package/dist/agent/reply-limits.js +17 -0
  14. package/dist/agent/session-events.d.ts +2 -0
  15. package/dist/agent/session-events.js +29 -14
  16. package/dist/agent/status-render.js +12 -12
  17. package/dist/agent/turn-recovery.js +2 -2
  18. package/dist/agent/type-guards.js +5 -1
  19. package/dist/agent/workspace-resources.d.ts +2 -2
  20. package/dist/agent/workspace-resources.js +41 -3
  21. package/dist/executor.d.ts +28 -0
  22. package/dist/executor.js +120 -18
  23. package/dist/file-store.d.ts +96 -0
  24. package/dist/file-store.js +189 -0
  25. package/dist/main.js +3 -4
  26. package/dist/memory/commands.js +79 -38
  27. package/dist/memory/consolidation.d.ts +5 -1
  28. package/dist/memory/consolidation.js +35 -38
  29. package/dist/memory/extraction.d.ts +8 -1
  30. package/dist/memory/extraction.js +47 -4
  31. package/dist/memory/files.d.ts +0 -1
  32. package/dist/memory/files.js +31 -12
  33. package/dist/memory/lifecycle.js +9 -2
  34. package/dist/memory/maintenance-jobs.js +16 -38
  35. package/dist/memory/maintenance-state.js +2 -1
  36. package/dist/memory/metadata.d.ts +3 -0
  37. package/dist/memory/metadata.js +7 -0
  38. package/dist/memory/recall.d.ts +19 -0
  39. package/dist/memory/recall.js +116 -24
  40. package/dist/memory/review-log.d.ts +0 -2
  41. package/dist/memory/review-log.js +0 -0
  42. package/dist/memory/session-corpus.js +5 -0
  43. package/dist/memory/session-search.js +15 -22
  44. package/dist/memory/sidecar-worker.js +4 -0
  45. package/dist/memory/source-window.d.ts +0 -1
  46. package/dist/memory/source-window.js +0 -5
  47. package/dist/memory/transcript.d.ts +10 -0
  48. package/dist/memory/transcript.js +39 -0
  49. package/dist/playbooks/agent-delegation.md +34 -25
  50. package/dist/playbooks/background-jobs.md +8 -16
  51. package/dist/playbooks/catalog.d.ts +1 -1
  52. package/dist/playbooks/catalog.js +1 -1
  53. package/dist/playbooks/event-scheduling.md +15 -15
  54. package/dist/playbooks/memory-and-learning.md +30 -23
  55. package/dist/playbooks/outbound-media.md +15 -8
  56. package/dist/playbooks/runtime-orientation.md +40 -37
  57. package/dist/playbooks/task-driving.md +36 -38
  58. package/dist/playbooks/task-planning.md +21 -21
  59. package/dist/runtime/app-home.d.ts +6 -0
  60. package/dist/runtime/app-home.js +16 -7
  61. package/dist/runtime/bootstrap.js +54 -13
  62. package/dist/runtime/channel-context.d.ts +2 -1
  63. package/dist/runtime/delivery.js +3 -3
  64. package/dist/runtime/dingtalk.d.ts +9 -1
  65. package/dist/runtime/dingtalk.js +30 -15
  66. package/dist/runtime/durable-dispatch.d.ts +26 -1
  67. package/dist/runtime/durable-dispatch.js +51 -5
  68. package/dist/runtime/event-commands.d.ts +15 -0
  69. package/dist/runtime/event-commands.js +55 -56
  70. package/dist/runtime/events.d.ts +4 -2
  71. package/dist/runtime/events.js +15 -20
  72. package/dist/runtime/project-commands.d.ts +16 -0
  73. package/dist/runtime/project-commands.js +13 -17
  74. package/dist/runtime/subagent-commands.d.ts +20 -0
  75. package/dist/runtime/subagent-commands.js +61 -58
  76. package/dist/runtime/task-commands.d.ts +37 -0
  77. package/dist/runtime/task-commands.js +108 -66
  78. package/dist/runtime/task-driver.js +2 -2
  79. package/dist/security/block-message.d.ts +11 -0
  80. package/dist/security/block-message.js +12 -0
  81. package/dist/security/path-guard-check.d.ts +13 -0
  82. package/dist/security/path-guard-check.js +39 -0
  83. package/dist/security/path-guard.js +61 -12
  84. package/dist/security/types.d.ts +9 -0
  85. package/dist/settings.js +3 -2
  86. package/dist/shared/atomic-file.d.ts +17 -1
  87. package/dist/shared/atomic-file.js +50 -3
  88. package/dist/shared/duration.d.ts +2 -0
  89. package/dist/shared/duration.js +7 -0
  90. package/dist/shared/safe-id.d.ts +19 -0
  91. package/dist/shared/safe-id.js +24 -0
  92. package/dist/shared/text-utils.d.ts +1 -1
  93. package/dist/shared/text-utils.js +3 -8
  94. package/dist/shared/type-guards.d.ts +2 -0
  95. package/dist/shared/type-guards.js +4 -0
  96. package/dist/subagents/discovery.d.ts +51 -19
  97. package/dist/subagents/discovery.js +93 -98
  98. package/dist/subagents/external/claude-code.js +40 -2
  99. package/dist/subagents/external/harness.d.ts +1 -1
  100. package/dist/subagents/external/run.js +61 -8
  101. package/dist/subagents/format.d.ts +3 -2
  102. package/dist/subagents/format.js +3 -7
  103. package/dist/subagents/runs.d.ts +1 -1
  104. package/dist/subagents/runs.js +10 -9
  105. package/dist/subagents/tool.d.ts +31 -18
  106. package/dist/subagents/tool.js +592 -562
  107. package/dist/subagents/workspace-lease.js +1 -1
  108. package/dist/tasks/control.js +7 -9
  109. package/dist/tasks/ledger.d.ts +2 -2
  110. package/dist/tasks/ledger.js +3 -7
  111. package/dist/tasks/transitions.d.ts +5 -1
  112. package/dist/tasks/transitions.js +2 -2
  113. package/dist/tasks/verification.d.ts +7 -5
  114. package/dist/tools/bash.d.ts +1 -2
  115. package/dist/tools/bash.js +99 -76
  116. package/dist/tools/config.d.ts +6 -1
  117. package/dist/tools/config.js +9 -0
  118. package/dist/tools/edit.d.ts +2 -3
  119. package/dist/tools/edit.js +276 -75
  120. package/dist/tools/event-manage.d.ts +13 -7
  121. package/dist/tools/event-manage.js +52 -14
  122. package/dist/tools/glob-match.d.ts +11 -0
  123. package/dist/tools/glob-match.js +75 -0
  124. package/dist/tools/glob.d.ts +15 -0
  125. package/dist/tools/glob.js +113 -0
  126. package/dist/tools/grep.d.ts +0 -1
  127. package/dist/tools/grep.js +60 -44
  128. package/dist/tools/ignore-dirs.d.ts +6 -0
  129. package/dist/tools/ignore-dirs.js +15 -0
  130. package/dist/tools/index.d.ts +3 -0
  131. package/dist/tools/index.js +54 -40
  132. package/dist/tools/job.d.ts +0 -1
  133. package/dist/tools/job.js +3 -9
  134. package/dist/tools/line-index.d.ts +16 -0
  135. package/dist/tools/line-index.js +76 -0
  136. package/dist/tools/memory-manage.d.ts +21 -8
  137. package/dist/tools/memory-manage.js +114 -103
  138. package/dist/tools/presentation.d.ts +2 -0
  139. package/dist/tools/presentation.js +109 -0
  140. package/dist/tools/read.d.ts +2 -2
  141. package/dist/tools/read.js +100 -120
  142. package/dist/tools/registry.d.ts +4 -1
  143. package/dist/tools/registry.js +89 -22
  144. package/dist/tools/send-media.d.ts +6 -6
  145. package/dist/tools/send-media.js +21 -43
  146. package/dist/tools/session-search.d.ts +0 -1
  147. package/dist/tools/session-search.js +0 -1
  148. package/dist/tools/skill-security.d.ts +0 -2
  149. package/dist/tools/skill-security.js +1 -25
  150. package/dist/tools/skill.d.ts +31 -0
  151. package/dist/tools/skill.js +153 -0
  152. package/dist/tools/subagent-manage.d.ts +6 -5
  153. package/dist/tools/subagent-manage.js +47 -47
  154. package/dist/tools/task-manage/create.d.ts +2 -2
  155. package/dist/tools/task-manage/create.js +1 -3
  156. package/dist/tools/task-manage/lifecycle.d.ts +9 -6
  157. package/dist/tools/task-manage/lifecycle.js +49 -56
  158. package/dist/tools/task-manage/schema.d.ts +27 -15
  159. package/dist/tools/task-manage/schema.js +58 -74
  160. package/dist/tools/task-manage/shared.d.ts +11 -6
  161. package/dist/tools/task-manage/shared.js +30 -21
  162. package/dist/tools/task-manage/types.d.ts +14 -15
  163. package/dist/tools/task-manage/verification.d.ts +4 -4
  164. package/dist/tools/task-manage/verification.js +6 -8
  165. package/dist/tools/task-manage.d.ts +8 -11
  166. package/dist/tools/task-manage.js +63 -50
  167. package/dist/tools/tool-details.d.ts +17 -1
  168. package/dist/tools/tool-details.js +24 -0
  169. package/dist/tools/truncate.d.ts +8 -0
  170. package/dist/tools/truncate.js +8 -0
  171. package/dist/tools/web-fetch.d.ts +0 -1
  172. package/dist/tools/web-fetch.js +9 -2
  173. package/dist/tools/web-search.d.ts +0 -1
  174. package/dist/tools/web-search.js +0 -1
  175. package/dist/tools/write-content.d.ts +3 -3
  176. package/dist/tools/write-content.js +12 -41
  177. package/dist/tools/write.d.ts +2 -3
  178. package/dist/tools/write.js +3 -4
  179. package/dist/tui/app.js +1 -1
  180. package/dist/tui/commands.d.ts +1 -1
  181. package/dist/tui/commands.js +1 -1
  182. package/dist/tui/turn-controller.d.ts +1 -1
  183. package/dist/tui/turn-controller.js +14 -4
  184. package/dist/usage/ledger.js +7 -4
  185. package/dist/usage/render.js +10 -8
  186. package/examples/sub-agents/README.md +2 -0
  187. package/package.json +3 -2
  188. package/dist/tools/skill-manage.d.ts +0 -41
  189. package/dist/tools/skill-manage.js +0 -231
@@ -1,2 +1,18 @@
1
1
  export declare function createAtomicTempPath(path: string): string;
2
- export declare function writeFileAtomically(path: string, content: string, tempPath?: string): Promise<void>;
2
+ export interface WriteFileAtomicallyOptions {
3
+ tempPath?: string;
4
+ /**
5
+ * `fchmod` the temp file to the existing target's permission bits before renaming over it, so
6
+ * an atomic overwrite of an executable file does not silently strip its `x` bit (spec 044,
7
+ * D1.2). A missing target (first write) leaves the temp file's own default mode untouched.
8
+ */
9
+ preserveMode?: boolean;
10
+ }
11
+ export declare function writeFileAtomically(path: string, content: string | Buffer, optionsOrTempPath?: WriteFileAtomicallyOptions | string): Promise<void>;
12
+ /**
13
+ * Synchronous counterpart to {@link writeFileAtomically} for the handful of call sites that
14
+ * cannot go async (a settings-manager `save(): void` and a per-message conversation-meta write
15
+ * called from a sync event handler) — write-temp-then-rename still beats a direct
16
+ * `writeFileSync`, since a crash mid-write can no longer truncate the target in place.
17
+ */
18
+ export declare function writeFileAtomicallySync(path: string, content: string | Buffer, tempPath?: string): void;
@@ -1,16 +1,36 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { mkdir, open, rename, unlink } from "node:fs/promises";
2
+ import { mkdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { mkdir, open, rename, stat, unlink } from "node:fs/promises";
3
4
  import { dirname } from "node:path";
4
5
  export function createAtomicTempPath(path) {
5
6
  return `${path}.${process.pid}.${randomUUID()}.tmp`;
6
7
  }
7
- export async function writeFileAtomically(path, content, tempPath = createAtomicTempPath(path)) {
8
+ async function existingMode(path) {
9
+ try {
10
+ return (await stat(path)).mode & 0o777;
11
+ }
12
+ catch {
13
+ return undefined;
14
+ }
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);
8
19
  const dir = dirname(path);
9
20
  await mkdir(dir, { recursive: true });
10
21
  try {
22
+ const mode = options.preserveMode ? await existingMode(path) : undefined;
11
23
  const handle = await open(tempPath, "w");
12
24
  try {
13
- await handle.writeFile(content, "utf-8");
25
+ if (mode !== undefined) {
26
+ await handle.chmod(mode);
27
+ }
28
+ if (typeof content === "string") {
29
+ await handle.writeFile(content, "utf-8");
30
+ }
31
+ else {
32
+ await handle.writeFile(content);
33
+ }
14
34
  await handle.sync();
15
35
  }
16
36
  finally {
@@ -35,3 +55,30 @@ export async function writeFileAtomically(path, content, tempPath = createAtomic
35
55
  throw error;
36
56
  }
37
57
  }
58
+ /**
59
+ * Synchronous counterpart to {@link writeFileAtomically} for the handful of call sites that
60
+ * cannot go async (a settings-manager `save(): void` and a per-message conversation-meta write
61
+ * called from a sync event handler) — write-temp-then-rename still beats a direct
62
+ * `writeFileSync`, since a crash mid-write can no longer truncate the target in place.
63
+ */
64
+ export function writeFileAtomicallySync(path, content, tempPath) {
65
+ const resolvedTempPath = tempPath ?? createAtomicTempPath(path);
66
+ const dir = dirname(path);
67
+ mkdirSync(dir, { recursive: true });
68
+ try {
69
+ if (typeof content === "string") {
70
+ writeFileSync(resolvedTempPath, content, "utf-8");
71
+ }
72
+ else {
73
+ writeFileSync(resolvedTempPath, content);
74
+ }
75
+ renameSync(resolvedTempPath, path);
76
+ }
77
+ catch (error) {
78
+ try {
79
+ unlinkSync(resolvedTempPath);
80
+ }
81
+ catch { }
82
+ throw error;
83
+ }
84
+ }
@@ -0,0 +1,2 @@
1
+ /** Render a millisecond duration as compact human text (`"42s"`, `"3m7s"`). */
2
+ export declare function formatDuration(ms: number): string;
@@ -0,0 +1,7 @@
1
+ /** Render a millisecond duration as compact human text (`"42s"`, `"3m7s"`). */
2
+ export function formatDuration(ms) {
3
+ const seconds = Math.round(ms / 1000);
4
+ if (seconds < 60)
5
+ return `${seconds}s`;
6
+ return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
7
+ }
@@ -0,0 +1,19 @@
1
+ export interface SafeIdOptions {
2
+ /** File suffix to strip (e.g. `.md`, `.json`) and re-append when resolving a path. */
3
+ suffix: string;
4
+ /** Allowed id characters after suffix stripping. */
5
+ pattern: RegExp;
6
+ /** Used in error messages, e.g. "task id", "event name". */
7
+ label: string;
8
+ }
9
+ /** Validate/normalize an id (a file basename minus its suffix), rejecting path traversal. */
10
+ export declare function normalizeSafeId(id: string, options: SafeIdOptions): string;
11
+ /**
12
+ * {@link normalizeSafeId}, then resolves the id to a path confined under `dir` — defense in
13
+ * depth beyond the pattern check, for the one caller (`event_manage`) whose directory is
14
+ * agent-writable.
15
+ */
16
+ export declare function resolveSafeIdPath(dir: string, id: string, options: SafeIdOptions): {
17
+ id: string;
18
+ path: string;
19
+ };
@@ -0,0 +1,24 @@
1
+ import { join, resolve, sep } from "node:path";
2
+ /** Validate/normalize an id (a file basename minus its suffix), rejecting path traversal. */
3
+ export function normalizeSafeId(id, options) {
4
+ const trimmed = id.trim();
5
+ const normalized = trimmed.endsWith(options.suffix) ? trimmed.slice(0, -options.suffix.length) : trimmed;
6
+ if (!normalized || normalized === "." || normalized === ".." || !options.pattern.test(normalized)) {
7
+ throw new Error(`Invalid ${options.label}: ${id}`);
8
+ }
9
+ return normalized;
10
+ }
11
+ /**
12
+ * {@link normalizeSafeId}, then resolves the id to a path confined under `dir` — defense in
13
+ * depth beyond the pattern check, for the one caller (`event_manage`) whose directory is
14
+ * agent-writable.
15
+ */
16
+ export function resolveSafeIdPath(dir, id, options) {
17
+ const normalizedId = normalizeSafeId(id, options);
18
+ const resolvedDir = resolve(dir);
19
+ const path = resolve(resolvedDir, `${normalizedId}${options.suffix}`);
20
+ if (path !== join(resolvedDir, `${normalizedId}${options.suffix}`) || !path.startsWith(`${resolvedDir}${sep}`)) {
21
+ throw new Error(`Invalid ${options.label}: ${id}`);
22
+ }
23
+ return { id: normalizedId, path };
24
+ }
@@ -2,11 +2,11 @@ import type { AssistantMessage } from "@earendil-works/pi-ai";
2
2
  export declare function clipText(text: string, maxChars: number, opts?: {
3
3
  headRatio?: number;
4
4
  omitHint?: string;
5
+ collapseWhitespace?: boolean;
5
6
  }): string;
6
7
  export declare function truncate(text: string, maxLen: number): string;
7
8
  export declare const HAN_REGEX: RegExp;
8
9
  /** Strip a trailing `.json` from an event filename to get its logical name. */
9
10
  export declare function eventNameFromFilename(filename: string): string;
10
- export declare function extractLabelFromArgs(args: unknown): string | null;
11
11
  export declare function errorMessage(err: unknown): string;
12
12
  export declare function extractAssistantText(message: AssistantMessage): string;
@@ -1,5 +1,7 @@
1
1
  export function clipText(text, maxChars, opts = {}) {
2
- const normalized = text.replace(/\s+\n/g, "\n").replace(/\r/g, "").trim();
2
+ const normalized = opts.collapseWhitespace
3
+ ? text.replace(/\s+/g, " ").trim()
4
+ : text.replace(/\s+\n/g, "\n").replace(/\r/g, "").trim();
3
5
  if (normalized.length <= maxChars) {
4
6
  return normalized;
5
7
  }
@@ -24,13 +26,6 @@ export const HAN_REGEX = /\p{Script=Han}/u;
24
26
  export function eventNameFromFilename(filename) {
25
27
  return filename.endsWith(".json") ? filename.slice(0, -".json".length) : filename;
26
28
  }
27
- export function extractLabelFromArgs(args) {
28
- if (!args || typeof args !== "object" || !("label" in args)) {
29
- return null;
30
- }
31
- const label = args.label;
32
- return typeof label === "string" && label.trim() ? label.trim() : null;
33
- }
34
29
  export function errorMessage(err) {
35
30
  return err instanceof Error ? err.message : String(err);
36
31
  }
@@ -1,5 +1,7 @@
1
1
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
2
  import type { Message } from "@earendil-works/pi-ai";
3
3
  export declare function isRecord(value: unknown): value is Record<string, unknown>;
4
+ /** Like {@link isRecord}, but false for arrays — for parsing JSON where an array is not a valid shape. */
5
+ export declare function isPlainObject(value: unknown): value is Record<string, unknown>;
4
6
  export declare function isStandardAgentMessage(message: AgentMessage): message is Message;
5
7
  export declare function buildStandardMessages(messages: AgentMessage[]): Message[];
@@ -1,6 +1,10 @@
1
1
  export function isRecord(value) {
2
2
  return typeof value === "object" && value !== null;
3
3
  }
4
+ /** Like {@link isRecord}, but false for arrays — for parsing JSON where an array is not a valid shape. */
5
+ export function isPlainObject(value) {
6
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7
+ }
4
8
  export function isStandardAgentMessage(message) {
5
9
  return (typeof message === "object" &&
6
10
  message !== null &&
@@ -43,14 +43,6 @@ export declare const SUB_AGENT_EFFORT_PRESETS: {
43
43
  readonly bashTimeoutSec: 180;
44
44
  };
45
45
  };
46
- /**
47
- * External runs have no turn/tool-call budget (D5) — `effort` only ever moves wall time, and at
48
- * external scale, not the internal tuple above (P1-3: those numbers previously leaked onto
49
- * external roles unchanged, where `deep` at 900s was *shorter* than the external default).
50
- * `standard` and an unset `effort` both keep the role's own `maxWallTimeSec` (or the external
51
- * default), so this only has entries for the two presets that actually override it.
52
- */
53
- export declare const SUB_AGENT_EXTERNAL_EFFORT_WALL_TIME_SEC: Partial<Record<keyof typeof SUB_AGENT_EFFORT_PRESETS, number>>;
54
46
  export type SubAgentEffort = keyof typeof SUB_AGENT_EFFORT_PRESETS;
55
47
  /**
56
48
  * The invocation-side spelling of `contextMode` + `memory`. Those two frontmatter knobs
@@ -100,31 +92,48 @@ export interface SubAgentConfig {
100
92
  * The role is still listed — never silently dropped (D5) — and invocation must explain why. */
101
93
  unavailable?: string;
102
94
  }
103
- export interface ResolvedSubAgentConfig extends Omit<SubAgentConfig, "model" | "modelRef" | "thinkingLevel"> {
95
+ export interface ResolvedSubAgentConfig extends Omit<SubAgentConfig, "model" | "modelRef"> {
104
96
  model: Model<Api>;
105
97
  modelRef: string;
106
- thinkingLevel: SubAgentThinkingLevel;
107
98
  }
108
99
  export interface SubAgentDiscoveryResult {
109
100
  directory: string;
110
101
  agents: SubAgentConfig[];
111
102
  warnings: string[];
112
103
  }
113
- export interface SubAgentInvocationOverrides {
114
- agent?: string;
115
- name?: string;
116
- systemPrompt?: string;
104
+ /**
105
+ * `subagent` (role-based) invocation surface (spec 046, D2.1). Deliberately has no override
106
+ * fields beyond `purpose`: everything else a configured role could vary — tools, model, effort,
107
+ * context, thinkingLevel, mutates — lives in the role file, which is the deployer's decision, not
108
+ * a per-call one. This is what makes "external role + tools/model/mutates" unrepresentable at the
109
+ * type level instead of rejected at runtime (spec 042 D3's three checks are now dead by construction).
110
+ */
111
+ export interface ConfiguredRoleOverrides {
112
+ agent: string;
113
+ /** Drives the thinkingLevel default: "verify" defaults on, everything else stays off. */
114
+ purpose?: string;
115
+ }
116
+ /**
117
+ * `subagent_inline` invocation surface (spec 046, D2.1) — a one-off executor with no role file,
118
+ * so every field a role file would otherwise supply is a call-time override here instead.
119
+ */
120
+ export interface InlineAgentOverrides {
121
+ systemPrompt: string;
117
122
  tools?: string[];
118
123
  model?: string;
119
124
  /** Named budget preset; wins over frontmatter numbers as a whole tuple, never field by field. */
120
125
  effort?: string;
121
126
  /** Collapsed `contextMode` + `memory`; see SubAgentContextChoice. */
122
127
  context?: string;
123
- paths?: string[];
124
128
  thinkingLevel?: string;
125
129
  /** Drives the thinkingLevel default: "verify" defaults on, everything else stays off. */
126
130
  purpose?: string;
131
+ mutates?: string;
127
132
  }
133
+ /** Internal work/verify default, aligned with the main agent's DEFAULT_MAIN_THINKING_LEVEL
134
+ * (channel-runner.ts). External work leaves thinkingLevel unset instead (see resolveSubAgentConfig):
135
+ * pipiclaw has no standing to pick a reasoning effort for another CLI's own configuration. */
136
+ export declare const DEFAULT_THINKING_LEVEL: SubAgentThinkingLevel;
128
137
  export declare function validateSubAgentTask(task: string): string | undefined;
129
138
  export declare function getSubAgentsDir(workspaceDir: string): string;
130
139
  /**
@@ -154,15 +163,38 @@ type FieldSupport = "supported" | "rejected";
154
163
  */
155
164
  export declare const ROLE_FIELD_MATRIX: Record<string, Record<SubAgentRuntime, FieldSupport>>;
156
165
  export declare function discoverSubAgents(workspaceDir: string, availableModels: Model<Api>[]): SubAgentDiscoveryResult;
157
- export declare function resolveSubAgentConfig(availableModels: Model<Api>[], currentModel: Model<Api>, predefinedAgents: SubAgentConfig[], overrides: SubAgentInvocationOverrides,
158
166
  /**
159
- * `settings.subagentModel` (spec 032 D5): used only when neither the invocation nor the
160
- * predefined agent's frontmatter names a model. Unset/blank is "not configured" — the
161
- * caller (tool.ts) already normalizes that, this function just treats undefined as absent.
167
+ * Resolve a `subagent` (role-based) invocation (spec 046, D2.1).
168
+ *
169
+ * Everything the old combined resolver used to override for a configured role — `tools`,
170
+ * `model`, `effort`, `context`, `mutates` — now has nowhere to come from but the role file
171
+ * itself, so this is a lookup plus the two facts a role file cannot pin down: the default model
172
+ * (parent's current model, or `settings.subagentModel`) and the purpose-driven thinkingLevel
173
+ * default. Spec 042 D3's three "external + override" rejections no longer apply: `ConfiguredRoleOverrides`
174
+ * has no `tools`/`model`/`mutates` field to reject in the first place.
175
+ */
176
+ export declare function resolveConfiguredRole(availableModels: Model<Api>[], currentModel: Model<Api>, predefinedAgents: SubAgentConfig[], overrides: ConfiguredRoleOverrides,
177
+ /**
178
+ * `settings.subagentModel` (spec 032 D5): used only when neither the role file's frontmatter
179
+ * nor this call names a model (it cannot — there is no override field for it).
180
+ */
181
+ subagentDefaultModelRef?: string): {
182
+ config?: ResolvedSubAgentConfig;
183
+ error?: string;
184
+ };
185
+ /**
186
+ * Resolve a `subagent_inline` invocation (spec 046, D2.1) — a one-off executor with no role
187
+ * file. `runtime` is always `"internal"` here: only a configured role file can name `external`,
188
+ * and `InlineAgentOverrides` has no field for it, so the old function's external branches
189
+ * (budget table, unset-by-default thinkingLevel, model/tools/mutates rejections) simply do not
190
+ * apply to this path and are not reproduced here.
162
191
  */
192
+ export declare function resolveInlineAgent(availableModels: Model<Api>[], currentModel: Model<Api>, overrides: InlineAgentOverrides,
193
+ /** `settings.subagentModel` (spec 032 D5): used only when this call does not name a model. */
163
194
  subagentDefaultModelRef?: string): {
164
195
  config?: ResolvedSubAgentConfig;
165
196
  error?: string;
197
+ warning?: string;
166
198
  };
167
199
  export declare function formatSubAgentList(agents: SubAgentConfig[], maxItems?: number): string;
168
200
  /**
@@ -43,17 +43,6 @@ export const SUB_AGENT_EFFORT_PRESETS = {
43
43
  },
44
44
  deep: { maxTurns: 48, maxToolCalls: 96, maxWallTimeSec: 900, bashTimeoutSec: 180 },
45
45
  };
46
- /**
47
- * External runs have no turn/tool-call budget (D5) — `effort` only ever moves wall time, and at
48
- * external scale, not the internal tuple above (P1-3: those numbers previously leaked onto
49
- * external roles unchanged, where `deep` at 900s was *shorter* than the external default).
50
- * `standard` and an unset `effort` both keep the role's own `maxWallTimeSec` (or the external
51
- * default), so this only has entries for the two presets that actually override it.
52
- */
53
- export const SUB_AGENT_EXTERNAL_EFFORT_WALL_TIME_SEC = {
54
- quick: 600,
55
- deep: 5400,
56
- };
57
46
  const ALLOWED_EFFORTS = Object.keys(SUB_AGENT_EFFORT_PRESETS);
58
47
  /**
59
48
  * The invocation-side spelling of `contextMode` + `memory`. Those two frontmatter knobs
@@ -62,9 +51,10 @@ const ALLOWED_EFFORTS = Object.keys(SUB_AGENT_EFFORT_PRESETS);
62
51
  * i.e. paths-only injection — remains expressible in frontmatter.
63
52
  */
64
53
  const ALLOWED_CONTEXT_CHOICES = ["none", "session", "relevant"];
65
- /** verify is the last unattended gate before an attestation is trusted; give it real reasoning by default. */
66
- const DEFAULT_VERIFY_THINKING_LEVEL = "medium";
67
- const DEFAULT_WORK_THINKING_LEVEL = "off";
54
+ /** Internal work/verify default, aligned with the main agent's DEFAULT_MAIN_THINKING_LEVEL
55
+ * (channel-runner.ts). External work leaves thinkingLevel unset instead (see resolveSubAgentConfig):
56
+ * pipiclaw has no standing to pick a reasoning effort for another CLI's own configuration. */
57
+ export const DEFAULT_THINKING_LEVEL = "medium";
68
58
  function validateTextLength(value, maxChars, label) {
69
59
  if (value.length <= maxChars) {
70
60
  return undefined;
@@ -639,52 +629,85 @@ export function discoverSubAgents(workspaceDir, availableModels) {
639
629
  const result = loadAgentsFromDir(directory, availableModels);
640
630
  return { directory, agents: result.agents, warnings: result.warnings };
641
631
  }
642
- export function resolveSubAgentConfig(availableModels, currentModel, predefinedAgents, overrides,
643
632
  /**
644
- * `settings.subagentModel` (spec 032 D5): used only when neither the invocation nor the
645
- * predefined agent's frontmatter names a model. Unset/blank is "not configured" — the
646
- * caller (tool.ts) already normalizes that, this function just treats undefined as absent.
633
+ * Resolve a `subagent` (role-based) invocation (spec 046, D2.1).
634
+ *
635
+ * Everything the old combined resolver used to override for a configured role — `tools`,
636
+ * `model`, `effort`, `context`, `mutates` — now has nowhere to come from but the role file
637
+ * itself, so this is a lookup plus the two facts a role file cannot pin down: the default model
638
+ * (parent's current model, or `settings.subagentModel`) and the purpose-driven thinkingLevel
639
+ * default. Spec 042 D3's three "external + override" rejections no longer apply: `ConfiguredRoleOverrides`
640
+ * has no `tools`/`model`/`mutates` field to reject in the first place.
641
+ */
642
+ export function resolveConfiguredRole(availableModels, currentModel, predefinedAgents, overrides,
643
+ /**
644
+ * `settings.subagentModel` (spec 032 D5): used only when neither the role file's frontmatter
645
+ * nor this call names a model (it cannot — there is no override field for it).
647
646
  */
648
647
  subagentDefaultModelRef) {
649
- const baseConfig = overrides.agent ? predefinedAgents.find((agent) => agent.name === overrides.agent) : undefined;
650
- if (overrides.agent && !baseConfig) {
648
+ const baseConfig = predefinedAgents.find((agent) => agent.name === overrides.agent);
649
+ if (!baseConfig) {
651
650
  const available = predefinedAgents.length > 0 ? predefinedAgents.map((agent) => agent.name).join(", ") : "none";
652
651
  return { error: `Unknown sub-agent "${overrides.agent}". Available sub-agents: ${available}.` };
653
652
  }
654
653
  // Listed, never dropped (spec 040, D5) — but refused here with the reason, not a fallback.
655
- if (baseConfig?.unavailable) {
654
+ if (baseConfig.unavailable) {
656
655
  return { error: `Sub-agent "${baseConfig.name}" is currently unavailable: ${baseConfig.unavailable}` };
657
656
  }
658
- if (!baseConfig && (!overrides.systemPrompt || !overrides.systemPrompt.trim())) {
659
- return { error: 'Provide either "agent" or "systemPrompt" to define the sub-agent.' };
657
+ let model = baseConfig.model;
658
+ let modelRef = baseConfig.modelRef;
659
+ if (!model && subagentDefaultModelRef) {
660
+ const resolved = resolveModelReference(subagentDefaultModelRef, availableModels);
661
+ if (!resolved.model) {
662
+ return { error: resolved.error };
663
+ }
664
+ model = resolved.model;
665
+ modelRef = formatModelReference(resolved.model);
660
666
  }
661
- const effectiveRuntime = baseConfig?.runtime ?? "internal";
662
- // Spec 042 D3: the invocation-side counterpart to the role-file field matrix (`ROLE_FIELD_MATRIX`
663
- // above) — a field only meaningful for one runtime is rejected outright when the resolved role
664
- // is the other, not silently ignored. `tools` and `model` were previously accepted and either
665
- // dropped on the floor or — for `model` — resolved against `models.json` and made to fail a
666
- // dispatch for a reason that has nothing to do with the external role actually named.
667
- if (effectiveRuntime === "external" && overrides.tools !== undefined) {
668
- return {
669
- error: `Sub-agent "${baseConfig?.name}" is external; its tool boundary comes from its own ` +
670
- 'command (e.g. "--sandbox read-only"), not the "tools" invocation parameter, which has no effect on external roles.',
671
- };
667
+ const purpose = overrides.purpose === "verify" ? "verify" : "work";
668
+ // External work is not defaulted: pipiclaw has no standing to pick a reasoning effort for
669
+ // another CLI's own configuration. External verify still defaults — it is the last unattended
670
+ // gate before an attestation is trusted, and "whatever that machine happens to have configured"
671
+ // is not an acceptable substitute for real reasoning.
672
+ const thinkingLevel = baseConfig.thinkingLevel ??
673
+ (baseConfig.runtime === "external" && purpose !== "verify" ? undefined : DEFAULT_THINKING_LEVEL);
674
+ const mutates = baseConfig.mutates ?? inferMutatesFromTools(baseConfig.tools);
675
+ return {
676
+ config: {
677
+ ...baseConfig,
678
+ model: model ?? currentModel,
679
+ modelRef: modelRef ?? formatModelReference(model ?? currentModel),
680
+ thinkingLevel,
681
+ source: "predefined",
682
+ mutates,
683
+ },
684
+ };
685
+ }
686
+ /**
687
+ * Resolve a `subagent_inline` invocation (spec 046, D2.1) — a one-off executor with no role
688
+ * file. `runtime` is always `"internal"` here: only a configured role file can name `external`,
689
+ * and `InlineAgentOverrides` has no field for it, so the old function's external branches
690
+ * (budget table, unset-by-default thinkingLevel, model/tools/mutates rejections) simply do not
691
+ * apply to this path and are not reproduced here.
692
+ */
693
+ export function resolveInlineAgent(availableModels, currentModel, overrides,
694
+ /** `settings.subagentModel` (spec 032 D5): used only when this call does not name a model. */
695
+ subagentDefaultModelRef) {
696
+ const systemPrompt = overrides.systemPrompt.trim();
697
+ if (!systemPrompt) {
698
+ return { error: "Sub-agent system prompt cannot be empty." };
672
699
  }
673
- if (effectiveRuntime === "external" && overrides.model?.trim()) {
674
- return {
675
- error: `Sub-agent "${baseConfig?.name}" is external; its model can only be set in the role file's ` +
676
- '"model" frontmatter. The "model" invocation parameter has no effect on external roles and is never resolved against models.json.',
677
- };
700
+ const promptLengthError = validateSubAgentSystemPrompt(systemPrompt, "Inline sub-agent systemPrompt");
701
+ if (promptLengthError) {
702
+ return { error: promptLengthError };
678
703
  }
679
- const tools = overrides.tools
680
- ? validateToolNames(overrides.tools)
681
- : { tools: baseConfig?.tools ?? [...DEFAULT_SUB_AGENT_TOOLS] };
704
+ const tools = overrides.tools ? validateToolNames(overrides.tools) : { tools: [...DEFAULT_SUB_AGENT_TOOLS] };
682
705
  if (tools.error) {
683
706
  return { error: tools.error };
684
707
  }
685
- let model = baseConfig?.model;
686
- let modelRef = baseConfig?.modelRef;
687
- if (effectiveRuntime !== "external" && overrides.model?.trim()) {
708
+ let model;
709
+ let modelRef;
710
+ if (overrides.model?.trim()) {
688
711
  const resolved = resolveModelReference(overrides.model.trim(), availableModels);
689
712
  if (!resolved.model) {
690
713
  return { error: resolved.error };
@@ -692,7 +715,7 @@ subagentDefaultModelRef) {
692
715
  model = resolved.model;
693
716
  modelRef = formatModelReference(resolved.model);
694
717
  }
695
- else if (!model && subagentDefaultModelRef) {
718
+ else if (subagentDefaultModelRef) {
696
719
  const resolved = resolveModelReference(subagentDefaultModelRef, availableModels);
697
720
  if (!resolved.model) {
698
721
  return { error: resolved.error };
@@ -704,60 +727,40 @@ subagentDefaultModelRef) {
704
727
  if (effortOverride.error) {
705
728
  return { error: effortOverride.error };
706
729
  }
707
- // An explicit `effort` replaces the whole budget tuple rather than merging field by
708
- // field, so a preset never produces a combination no preset describes. External is a
709
- // separate branch (P1-3): it has no turn/tool-call budget, and effort's wall-time numbers
710
- // are at external scale, not the internal tuple.
711
- const budget = effectiveRuntime === "external"
712
- ? {
730
+ const budget = effortOverride.value
731
+ ? SUB_AGENT_EFFORT_PRESETS[effortOverride.value]
732
+ : {
713
733
  maxTurns: DEFAULT_MAX_TURNS,
714
734
  maxToolCalls: DEFAULT_MAX_TOOL_CALLS,
715
- maxWallTimeSec: (effortOverride.value && SUB_AGENT_EXTERNAL_EFFORT_WALL_TIME_SEC[effortOverride.value]) ??
716
- baseConfig?.maxWallTimeSec ??
717
- DEFAULT_EXTERNAL_MAX_WALL_TIME_SEC,
735
+ maxWallTimeSec: DEFAULT_MAX_WALL_TIME_SEC,
718
736
  bashTimeoutSec: DEFAULT_BASH_TIMEOUT_SEC,
719
- }
720
- : effortOverride.value
721
- ? SUB_AGENT_EFFORT_PRESETS[effortOverride.value]
722
- : {
723
- maxTurns: baseConfig?.maxTurns ?? DEFAULT_MAX_TURNS,
724
- maxToolCalls: baseConfig?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS,
725
- maxWallTimeSec: baseConfig?.maxWallTimeSec ?? DEFAULT_MAX_WALL_TIME_SEC,
726
- bashTimeoutSec: baseConfig?.bashTimeoutSec ?? DEFAULT_BASH_TIMEOUT_SEC,
727
- };
737
+ };
728
738
  const contextOverride = parseContextChoice(overrides.context);
729
739
  if (contextOverride.error) {
730
740
  return { error: contextOverride.error };
731
741
  }
732
- const contextMode = contextOverride.value?.contextMode ?? baseConfig?.contextMode ?? "isolated";
733
- const memory = contextOverride.value?.memory ?? baseConfig?.memory ?? (contextMode === "contextual" ? "relevant" : "none");
734
- const pathsOverride = overrides.paths ? parseStringList(overrides.paths, "paths") : undefined;
735
- if (pathsOverride?.error) {
736
- return { error: pathsOverride.error };
737
- }
738
- const paths = pathsOverride?.values ?? baseConfig?.paths ?? [];
742
+ const contextMode = contextOverride.value?.contextMode ?? "isolated";
743
+ const memory = contextOverride.value?.memory ?? (contextMode === "contextual" ? "relevant" : "none");
739
744
  const thinkingLevelOverride = overrides.thinkingLevel ? parseThinkingLevel(overrides.thinkingLevel) : undefined;
740
745
  if (thinkingLevelOverride?.error) {
741
746
  return { error: thinkingLevelOverride.error };
742
747
  }
743
- const purpose = overrides.purpose === "verify" ? "verify" : "work";
744
- const thinkingLevel = thinkingLevelOverride?.value ??
745
- baseConfig?.thinkingLevel ??
746
- (purpose === "verify" ? DEFAULT_VERIFY_THINKING_LEVEL : DEFAULT_WORK_THINKING_LEVEL);
747
- const systemPrompt = overrides.systemPrompt?.trim() || baseConfig?.systemPrompt || "";
748
- if (!systemPrompt) {
749
- return { error: "Sub-agent system prompt cannot be empty." };
750
- }
751
- if (overrides.systemPrompt?.trim()) {
752
- const promptLengthError = validateSubAgentSystemPrompt(overrides.systemPrompt.trim(), "Inline sub-agent systemPrompt");
753
- if (promptLengthError) {
754
- return { error: promptLengthError };
755
- }
748
+ const thinkingLevel = thinkingLevelOverride?.value ?? DEFAULT_THINKING_LEVEL;
749
+ const mutatesOverride = parseMutates(overrides.mutates);
750
+ if (mutatesOverride.error) {
751
+ return { error: mutatesOverride.error };
756
752
  }
753
+ const mutates = mutatesOverride.value ?? inferMutatesFromTools(tools.tools);
754
+ // Inline roles have no frontmatter to declare `mutates` in, so this warning goes back to the
755
+ // model in the result text instead of a discovery-time log (D6 in the pre-split resolver).
756
+ const bashWithoutMutatesWarning = tools.tools.includes("bash") && mutatesOverride.value === undefined
757
+ ? 'tools include bash but "mutates" is not declared; if this task writes to the workspace, pass mutates: "write" so it takes the exclusive workspace write lease'
758
+ : undefined;
757
759
  return {
760
+ warning: bashWithoutMutatesWarning,
758
761
  config: {
759
- name: overrides.name?.trim() || baseConfig?.name || "dynamic-subagent",
760
- description: baseConfig?.description || "Inline sub-agent",
762
+ name: "dynamic-subagent",
763
+ description: "Inline sub-agent",
761
764
  systemPrompt,
762
765
  tools: tools.tools,
763
766
  model: model ?? currentModel,
@@ -768,19 +771,11 @@ subagentDefaultModelRef) {
768
771
  bashTimeoutSec: budget.bashTimeoutSec,
769
772
  contextMode,
770
773
  memory,
771
- paths,
774
+ paths: [],
772
775
  thinkingLevel,
773
- filePath: baseConfig?.filePath,
774
- source: baseConfig ? "predefined" : "inline",
775
- runtime: baseConfig?.runtime ?? "internal",
776
- harness: baseConfig?.harness,
777
- command: baseConfig?.command,
778
- shell: baseConfig?.shell,
779
- env: baseConfig?.env,
780
- workload: baseConfig?.workload,
781
- mutates: baseConfig?.mutates ?? inferMutatesFromTools(tools.tools),
782
- externalModelRef: baseConfig?.externalModelRef,
783
- unavailable: baseConfig?.unavailable,
776
+ source: "inline",
777
+ runtime: "internal",
778
+ mutates,
784
779
  },
785
780
  };
786
781
  }