@oyasmi/pipiclaw 0.9.3-beta.2 → 0.9.3-beta.4

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 (148) hide show
  1. package/dist/agent/channel-runner.d.ts +4 -18
  2. package/dist/agent/channel-runner.js +25 -120
  3. package/dist/agent/context-budget.js +1 -1
  4. package/dist/agent/job-manager.d.ts +20 -17
  5. package/dist/agent/job-manager.js +95 -70
  6. package/dist/agent/prompt/builder.d.ts +1 -1
  7. package/dist/agent/prompt/builder.js +2 -18
  8. package/dist/agent/prompt/manifest.d.ts +0 -1
  9. package/dist/agent/prompt/manifest.js +2 -2
  10. package/dist/agent/prompt/sections.js +3 -12
  11. package/dist/agent/prompt/types.d.ts +2 -18
  12. package/dist/agent/prompt/types.js +1 -1
  13. package/dist/agent/runner-factory.d.ts +4 -0
  14. package/dist/agent/session-adapter.d.ts +19 -0
  15. package/dist/agent/session-adapter.js +77 -0
  16. package/dist/app-services.d.ts +18 -0
  17. package/dist/app-services.js +43 -0
  18. package/dist/{runtime → events}/events.d.ts +1 -1
  19. package/dist/executor.d.ts +5 -1
  20. package/dist/executor.js +35 -5
  21. package/dist/file-store.d.ts +4 -1
  22. package/dist/file-store.js +5 -0
  23. package/dist/memory/journal.d.ts +13 -0
  24. package/dist/memory/journal.js +47 -4
  25. package/dist/memory/maintenance-gates.d.ts +0 -3
  26. package/dist/memory/maintenance-gates.js +2 -2
  27. package/dist/memory/maintenance-migration.d.ts +5 -0
  28. package/dist/memory/maintenance-migration.js +91 -0
  29. package/dist/memory/maintenance-state.js +5 -44
  30. package/dist/memory/migrate.js +1 -1
  31. package/dist/memory/reflect-job.d.ts +1 -9
  32. package/dist/memory/reflect-job.js +1 -3
  33. package/dist/memory/reflect.js +1 -1
  34. package/dist/memory/search.js +13 -6
  35. package/dist/memory/session-corpus.d.ts +11 -0
  36. package/dist/memory/session-corpus.js +16 -5
  37. package/dist/memory/session-search.d.ts +3 -0
  38. package/dist/memory/session-search.js +45 -8
  39. package/dist/memory/store.d.ts +9 -0
  40. package/dist/memory/store.js +26 -3
  41. package/dist/models/auth-cli.js +1 -1
  42. package/dist/playbooks/agent-delegation.md +35 -76
  43. package/dist/playbooks/background-jobs.md +14 -16
  44. package/dist/playbooks/event-scheduling.md +20 -25
  45. package/dist/playbooks/memory-and-learning.md +28 -61
  46. package/dist/playbooks/outbound-media.md +10 -12
  47. package/dist/playbooks/runtime-orientation.md +34 -53
  48. package/dist/playbooks/task-loop.md +49 -69
  49. package/dist/runtime/bootstrap.d.ts +5 -15
  50. package/dist/runtime/bootstrap.js +57 -67
  51. package/dist/runtime/subagent-commands.d.ts +2 -1
  52. package/dist/runtime/subagent-commands.js +10 -12
  53. package/dist/runtime/task-wake.d.ts +4 -5
  54. package/dist/runtime/task-wake.js +2 -12
  55. package/dist/security/path-guard-filter.d.ts +22 -0
  56. package/dist/security/path-guard-filter.js +35 -0
  57. package/dist/security/types.d.ts +7 -0
  58. package/dist/security/types.js +16 -1
  59. package/dist/settings.d.ts +8 -0
  60. package/dist/settings.js +24 -1
  61. package/dist/shared/exact-keys.d.ts +13 -0
  62. package/dist/shared/exact-keys.js +1 -0
  63. package/dist/shared/format.d.ts +20 -0
  64. package/dist/shared/format.js +64 -0
  65. package/dist/shared/{fs-utils.d.ts → os.d.ts} +6 -0
  66. package/dist/shared/{fs-utils.js → os.js} +8 -0
  67. package/dist/subagents/discovery.d.ts +18 -6
  68. package/dist/subagents/discovery.js +12 -8
  69. package/dist/subagents/external/run.d.ts +2 -1
  70. package/dist/subagents/external/run.js +1 -2
  71. package/dist/subagents/external/settlement.js +10 -5
  72. package/dist/subagents/format.d.ts +1 -1
  73. package/dist/subagents/format.js +1 -1
  74. package/dist/subagents/runs.d.ts +13 -12
  75. package/dist/subagents/runs.js +108 -89
  76. package/dist/subagents/tool.d.ts +13 -7
  77. package/dist/subagents/tool.js +21 -13
  78. package/dist/tasks/brief.d.ts +1 -1
  79. package/dist/tasks/brief.js +12 -2
  80. package/dist/tasks/log.d.ts +4 -0
  81. package/dist/tasks/log.js +13 -1
  82. package/dist/tools/bash.d.ts +13 -0
  83. package/dist/tools/bash.js +123 -20
  84. package/dist/tools/command-optimizer.js +1 -1
  85. package/dist/tools/config.d.ts +7 -0
  86. package/dist/tools/config.js +16 -1
  87. package/dist/tools/edit.js +36 -5
  88. package/dist/tools/event-manage.d.ts +26 -5
  89. package/dist/tools/event-manage.js +84 -36
  90. package/dist/tools/glob.js +57 -4
  91. package/dist/tools/grep.d.ts +2 -0
  92. package/dist/tools/grep.js +188 -15
  93. package/dist/tools/index.d.ts +4 -0
  94. package/dist/tools/index.js +4 -2
  95. package/dist/tools/job.js +17 -5
  96. package/dist/tools/memory-manage.js +80 -41
  97. package/dist/tools/read.js +43 -6
  98. package/dist/tools/registry.d.ts +9 -3
  99. package/dist/tools/registry.js +22 -57
  100. package/dist/tools/send-media.js +6 -4
  101. package/dist/tools/session-search.js +4 -1
  102. package/dist/tools/skill.d.ts +2 -0
  103. package/dist/tools/skill.js +13 -1
  104. package/dist/tools/subagent-manage.d.ts +2 -0
  105. package/dist/tools/subagent-manage.js +8 -8
  106. package/dist/tools/subagent-tool-names.d.ts +11 -0
  107. package/dist/tools/subagent-tool-names.js +19 -0
  108. package/dist/tools/task-manage/log-view.js +6 -3
  109. package/dist/tools/task-manage/schema.d.ts +6 -6
  110. package/dist/tools/task-manage/schema.js +5 -12
  111. package/dist/tools/task-manage/shared.js +20 -11
  112. package/dist/tools/task-manage/step-end.js +22 -5
  113. package/dist/tools/task-manage/types.d.ts +4 -0
  114. package/dist/tools/task-manage.js +9 -1
  115. package/dist/tools/web-cache.d.ts +11 -3
  116. package/dist/tools/web-cache.js +26 -8
  117. package/dist/tools/web-fetch.d.ts +1 -0
  118. package/dist/tools/web-fetch.js +68 -15
  119. package/dist/tools/write.js +3 -0
  120. package/dist/tui/app.js +22 -7
  121. package/dist/web/config.js +1 -1
  122. package/dist/web/fetch.d.ts +5 -0
  123. package/dist/web/fetch.js +36 -1
  124. package/examples/sub-agents/README.md +14 -4
  125. package/examples/sub-agents/builder-hard.md +12 -34
  126. package/examples/sub-agents/builder.md +11 -31
  127. package/examples/sub-agents/explorer.md +10 -16
  128. package/examples/sub-agents/git-committer.md +15 -20
  129. package/examples/sub-agents/planner.md +11 -21
  130. package/examples/sub-agents/reviewer.md +10 -31
  131. package/examples/sub-agents/verifier.md +12 -27
  132. package/examples/sub-agents/worker.md +11 -35
  133. package/package.json +8 -3
  134. package/dist/shared/duration.d.ts +0 -2
  135. package/dist/shared/duration.js +0 -7
  136. package/dist/shared/file-stamp.d.ts +0 -10
  137. package/dist/shared/file-stamp.js +0 -19
  138. package/dist/shared/numeric.d.ts +0 -7
  139. package/dist/shared/numeric.js +0 -19
  140. package/dist/shared/shell-escape.d.ts +0 -5
  141. package/dist/shared/shell-escape.js +0 -7
  142. package/dist/shared/token-estimate.d.ts +0 -1
  143. package/dist/shared/token-estimate.js +0 -19
  144. /package/dist/{runtime → events}/event-commands.d.ts +0 -0
  145. /package/dist/{runtime → events}/event-commands.js +0 -0
  146. /package/dist/{runtime → events}/event-validation.d.ts +0 -0
  147. /package/dist/{runtime → events}/event-validation.js +0 -0
  148. /package/dist/{runtime → events}/events.js +0 -0
@@ -0,0 +1,64 @@
1
+ import { statSync } from "node:fs";
2
+ /** Render a millisecond duration as compact human text (`"42s"`, `"3m7s"`). */
3
+ export function formatDuration(ms) {
4
+ const seconds = Math.round(ms / 1000);
5
+ if (seconds < 60)
6
+ return `${seconds}s`;
7
+ return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
8
+ }
9
+ /**
10
+ * Coerce an untrusted numeric config/request value into an integer within `[minimum, maximum]`,
11
+ * falling back to `fallback` for anything not a finite number or out of range. Shared by the
12
+ * app-level config loaders (`tools.json`) and web request parameter resolution — both need the
13
+ * same "trust nothing, fail closed to a safe default" numeric parsing.
14
+ */
15
+ export function clampInteger(value, fallback, minimum, maximum) {
16
+ if (typeof value !== "number" || !Number.isFinite(value)) {
17
+ return fallback;
18
+ }
19
+ const normalized = Math.floor(value);
20
+ if (normalized < minimum) {
21
+ return fallback;
22
+ }
23
+ if (maximum !== undefined && normalized > maximum) {
24
+ return fallback;
25
+ }
26
+ return normalized;
27
+ }
28
+ /**
29
+ * Rough token estimate, shared by everything that has to reason about context size without
30
+ * calling a tokenizer. CJK runs about one token per character, Latin text about four characters
31
+ * per token; the provider's real tokenizer is the authority, and the usage ledger records what
32
+ * it billed.
33
+ *
34
+ * The script split matters wherever the estimate gates behavior rather than just reporting: a
35
+ * flat characters-per-token ratio tuned for Latin text underestimates Chinese input roughly
36
+ * threefold, so a budget check would clear a message that in fact does not fit.
37
+ */
38
+ const CJK_REGEX = /\p{Script=Han}|\p{Script=Hiragana}|\p{Script=Katakana}|\p{Script=Hangul}/u;
39
+ export function estimateTokens(text) {
40
+ let cjk = 0;
41
+ for (const char of text) {
42
+ if (CJK_REGEX.test(char))
43
+ cjk++;
44
+ }
45
+ return Math.ceil(cjk + (text.length - cjk) / 4);
46
+ }
47
+ /**
48
+ * A cheap change token for a config file: `mtime:ctime:size`, or `""` when the file
49
+ * cannot be stat'ed (missing or unreadable — itself a stable state worth caching).
50
+ *
51
+ * Used by the hot re-read paths (`settings.json` on every driver/maintenance tick,
52
+ * `tools.json` on every driver tick) to skip a JSON parse when nothing changed. Same
53
+ * triple as the task-ledger parse cache: mtime alone misses an atomic-rename overwrite
54
+ * that preserves the timestamp, ctime catches the rename, size catches the rest.
55
+ */
56
+ export function fileStamp(path) {
57
+ try {
58
+ const stats = statSync(path);
59
+ return `${stats.mtimeMs}:${stats.ctimeMs}:${stats.size}`;
60
+ }
61
+ catch {
62
+ return "";
63
+ }
64
+ }
@@ -1,3 +1,4 @@
1
+ /** Small, dependency-free helpers for talking to the host filesystem and shell. */
1
2
  export declare function isNodeError(error: unknown): error is NodeJS.ErrnoException;
2
3
  /**
3
4
  * Read a UTF-8 text file, returning "" when it does not exist.
@@ -6,3 +7,8 @@ export declare function isNodeError(error: unknown): error is NodeJS.ErrnoExcept
6
7
  * silently treat a real read failure as an absent file.
7
8
  */
8
9
  export declare function readOptionalTextFile(path: string): Promise<string>;
10
+ /**
11
+ * Shell-escape a string for safe use in sh -c commands.
12
+ * Wraps in single quotes and escapes internal single quotes.
13
+ */
14
+ export declare function shellEscape(s: string): string;
@@ -1,4 +1,5 @@
1
1
  import { readFile } from "fs/promises";
2
+ /** Small, dependency-free helpers for talking to the host filesystem and shell. */
2
3
  export function isNodeError(error) {
3
4
  return error instanceof Error && "code" in error;
4
5
  }
@@ -19,3 +20,10 @@ export async function readOptionalTextFile(path) {
19
20
  throw error;
20
21
  }
21
22
  }
23
+ /**
24
+ * Shell-escape a string for safe use in sh -c commands.
25
+ * Wraps in single quotes and escapes internal single quotes.
26
+ */
27
+ export function shellEscape(s) {
28
+ return `'${s.replace(/'/g, "'\\''")}'`;
29
+ }
@@ -1,6 +1,6 @@
1
1
  import type { Api, Model } from "@earendil-works/pi-ai";
2
2
  import type { SecurityConfig } from "../security/types.js";
3
- declare const ALLOWED_SUB_AGENT_TOOLS: readonly ["read", "grep", "bash", "edit", "write", "web_search", "web_fetch"];
3
+ import { type SubAgentToolName } from "../tools/subagent-tool-names.js";
4
4
  declare const ALLOWED_CONTEXT_MODES: readonly ["isolated", "contextual"];
5
5
  declare const ALLOWED_MEMORY_MODES: readonly ["none", "index"];
6
6
  declare const ALLOWED_THINKING_LEVELS: readonly ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
@@ -8,7 +8,7 @@ declare const ALLOWED_RUNTIMES: readonly ["internal", "external"];
8
8
  declare const ALLOWED_HARNESSES: readonly ["claude-code", "codex-cli", "exec"];
9
9
  declare const ALLOWED_WORKLOADS: readonly ["light", "heavy"];
10
10
  declare const ALLOWED_MUTATES: readonly ["read", "write"];
11
- export type SubAgentToolName = (typeof ALLOWED_SUB_AGENT_TOOLS)[number];
11
+ export type { SubAgentToolName };
12
12
  export type SubAgentContextMode = (typeof ALLOWED_CONTEXT_MODES)[number];
13
13
  export type SubAgentMemoryMode = (typeof ALLOWED_MEMORY_MODES)[number];
14
14
  export type SubAgentThinkingLevel = (typeof ALLOWED_THINKING_LEVELS)[number];
@@ -52,7 +52,7 @@ export type SubAgentEffort = keyof typeof SUB_AGENT_EFFORT_PRESETS;
52
52
  */
53
53
  declare const ALLOWED_CONTEXT_CHOICES: readonly ["none", "index"];
54
54
  export type SubAgentContextChoice = (typeof ALLOWED_CONTEXT_CHOICES)[number];
55
- export interface SubAgentConfig {
55
+ interface SubAgentConfigFields {
56
56
  name: string;
57
57
  description: string;
58
58
  systemPrompt: string;
@@ -92,10 +92,23 @@ export interface SubAgentConfig {
92
92
  * The role is still listed — never silently dropped (D5) — and invocation must explain why. */
93
93
  unavailable?: string;
94
94
  }
95
- export interface ResolvedSubAgentConfig extends Omit<SubAgentConfig, "model" | "modelRef"> {
95
+ export interface InternalSubAgentConfig extends SubAgentConfigFields {
96
+ runtime: "internal";
97
+ }
98
+ export interface ExternalSubAgentConfig extends SubAgentConfigFields {
99
+ runtime: "external";
100
+ harness: SubAgentHarness;
101
+ command: string;
102
+ mutates: SubAgentMutates;
103
+ model?: never;
104
+ modelRef?: never;
105
+ }
106
+ export type SubAgentConfig = InternalSubAgentConfig | ExternalSubAgentConfig;
107
+ export interface ResolvedInternalSubAgentConfig extends InternalSubAgentConfig {
96
108
  model: Model<Api>;
97
109
  modelRef: string;
98
110
  }
111
+ export type ResolvedSubAgentConfig = ResolvedInternalSubAgentConfig | ExternalSubAgentConfig;
99
112
  export interface SubAgentDiscoveryResult {
100
113
  directory: string;
101
114
  agents: SubAgentConfig[];
@@ -192,7 +205,7 @@ subagentDefaultModelRef?: string): {
192
205
  export declare function resolveInlineAgent(availableModels: Model<Api>[], currentModel: Model<Api>, overrides: InlineAgentOverrides,
193
206
  /** `settings.subagentModel` (spec 032 D5): used only when this call does not name a model. */
194
207
  subagentDefaultModelRef?: string): {
195
- config?: ResolvedSubAgentConfig;
208
+ config?: ResolvedInternalSubAgentConfig;
196
209
  error?: string;
197
210
  warning?: string;
198
211
  };
@@ -210,4 +223,3 @@ export declare function formatSubAgentList(agents: SubAgentConfig[], maxItems?:
210
223
  * rejected for the same reason (spec 042 design doc, "已驳回的方案").
211
224
  */
212
225
  export declare function externalRoleFingerprint(role: Pick<SubAgentConfig, "command" | "externalModelRef" | "shell">): string;
213
- export {};
@@ -8,7 +8,9 @@ import { findExactModelReferenceMatch, formatModelReference } from "../models/ut
8
8
  import { SUB_AGENTS_DIR_NAME } from "../paths.js";
9
9
  import { splitShellWords } from "../shared/shell-words.js";
10
10
  import { errorMessage } from "../shared/text-utils.js";
11
- const ALLOWED_SUB_AGENT_TOOLS = ["read", "grep", "bash", "edit", "write", "web_search", "web_fetch"];
11
+ import { SUBAGENT_TOOL_NAMES } from "../tools/subagent-tool-names.js";
12
+ /** Re-exported from the leaf source of truth so validation and the tool set never drift. */
13
+ const ALLOWED_SUB_AGENT_TOOLS = SUBAGENT_TOOL_NAMES;
12
14
  const DEFAULT_SUB_AGENT_TOOLS = ["read", "bash"];
13
15
  const DEFAULT_MAX_TURNS = 32;
14
16
  const DEFAULT_MAX_TOOL_CALLS = 96;
@@ -633,6 +635,14 @@ subagentDefaultModelRef) {
633
635
  if (baseConfig.unavailable) {
634
636
  return { error: `Sub-agent "${baseConfig.name}" is currently unavailable: ${baseConfig.unavailable}` };
635
637
  }
638
+ if (baseConfig.runtime === "external") {
639
+ return {
640
+ config: {
641
+ ...baseConfig,
642
+ thinkingLevel: baseConfig.thinkingLevel ?? (overrides.purpose === "verify" ? DEFAULT_THINKING_LEVEL : undefined),
643
+ },
644
+ };
645
+ }
636
646
  let model = baseConfig.model;
637
647
  let modelRef = baseConfig.modelRef;
638
648
  if (!model && subagentDefaultModelRef) {
@@ -643,13 +653,7 @@ subagentDefaultModelRef) {
643
653
  model = resolved.model;
644
654
  modelRef = formatModelReference(resolved.model);
645
655
  }
646
- const purpose = overrides.purpose === "verify" ? "verify" : "work";
647
- // External work is not defaulted: pipiclaw has no standing to pick a reasoning effort for
648
- // another CLI's own configuration. External verify still defaults — it is the last unattended
649
- // gate before an attestation is trusted, and "whatever that machine happens to have configured"
650
- // is not an acceptable substitute for real reasoning.
651
- const thinkingLevel = baseConfig.thinkingLevel ??
652
- (baseConfig.runtime === "external" && purpose !== "verify" ? undefined : DEFAULT_THINKING_LEVEL);
656
+ const thinkingLevel = baseConfig.thinkingLevel ?? DEFAULT_THINKING_LEVEL;
653
657
  const mutates = baseConfig.mutates ?? inferMutatesFromTools(baseConfig.tools);
654
658
  return {
655
659
  config: {
@@ -2,7 +2,7 @@ import { spawn as nodeSpawn } from "node:child_process";
2
2
  import type { SecurityConfig } from "../../security/types.js";
3
3
  import { probeCliVersion, readProcessStartTime } from "../../shared/host-process.js";
4
4
  import type { SubAgentThinkingLevel } from "../discovery.js";
5
- import { type RunMutates } from "../runs.js";
5
+ import type { RunMutates, SubAgentRunManager } from "../runs.js";
6
6
  /**
7
7
  * The external-run orchestrator (spec 040, D1/D3/D4). One prompt, one short-lived, argv-direct,
8
8
  * detached process. The launch order matters (D1): admission and the lease are the caller's job
@@ -15,6 +15,7 @@ import { type RunMutates } from "../runs.js";
15
15
  * `sweep()`) reads the same files back once the process is confirmed gone.
16
16
  */
17
17
  export interface LaunchExternalRunInput {
18
+ runManager: SubAgentRunManager;
18
19
  runId: string;
19
20
  channelId: string;
20
21
  /** Needed only for `purpose=verify`: where the attestation gets written. */
@@ -9,7 +9,6 @@ import { splitShellWords } from "../../shared/shell-words.js";
9
9
  import { errorMessage } from "../../shared/text-utils.js";
10
10
  import { createEmptyUsageTotals } from "../../shared/types.js";
11
11
  import { workspaceSubjectSnapshot } from "../../tasks/artifact-subject.js";
12
- import { getSubAgentRunManager } from "../runs.js";
13
12
  import { getExternalHarness } from "./registry.js";
14
13
  import { finalizeExternalRun } from "./settlement.js";
15
14
  /**
@@ -151,7 +150,7 @@ export async function launchExternalRun(input) {
151
150
  // or host-wide cap still left behind an `external-agent` audit record claiming a process that
152
151
  // never existed. `external-agent` records what was *executed* (D8.1), so the record must not
153
152
  // precede the point where this run is actually admitted to run.
154
- const runManager = getSubAgentRunManager(input.channelId);
153
+ const runManager = input.runManager;
155
154
  await runManager.register({
156
155
  runId: input.runId,
157
156
  channelId: input.channelId,
@@ -120,8 +120,13 @@ export async function finalizeExternalRun(input, settle, options) {
120
120
  finalText: outcome.finalText,
121
121
  runFailed: false, // shouldVerify already gates on settleInput.status === "completed".
122
122
  });
123
- const legacySubjectAvailable = input.verifyBaseCommit === undefined && input.verifySubjectBefore !== undefined;
124
- const subjectAvailable = !verification.workspaceChanged && subjectAfter !== undefined && (baseSubjectAvailable || legacySubjectAvailable);
123
+ // `verifySubjectBefore` and `verifyBaseCommit` are always set together at launch (both come
124
+ // from the one all-or-nothing `workspaceSubjectSnapshot()` call in `external/run.ts`), so a
125
+ // freshly launched run can never carry a subject hash without a base commit — there is no
126
+ // live path left that produces a "legacy-head" attestation. `verification.ts` still reads and
127
+ // compares `legacy-head` attestations written before base-relative subjects existed; this is
128
+ // only the write side, for a run happening now.
129
+ const subjectAvailable = !verification.workspaceChanged && subjectAfter !== undefined && baseSubjectAvailable;
125
130
  await writeVerificationAttestation(input.channelDir, {
126
131
  runId: input.runId,
127
132
  taskId: input.taskId,
@@ -131,9 +136,9 @@ export async function finalizeExternalRun(input, settle, options) {
131
136
  workspaceChanged: verification.workspaceChanged,
132
137
  subjectHash: subjectAvailable ? subjectAfter : undefined,
133
138
  subjectDir: subjectAvailable ? input.workingDirectory : undefined,
134
- subjectMode: subjectAvailable ? (baseSubjectAvailable ? "base-relative" : "legacy-head") : undefined,
135
- subjectBaseCommit: subjectAvailable && baseSubjectAvailable ? input.verifyBaseCommit : undefined,
136
- subjectBaselineUntrackedPaths: subjectAvailable && baseSubjectAvailable ? input.verifyBaselineUntrackedPaths : undefined,
139
+ subjectMode: subjectAvailable ? "base-relative" : undefined,
140
+ subjectBaseCommit: subjectAvailable ? input.verifyBaseCommit : undefined,
141
+ subjectBaselineUntrackedPaths: subjectAvailable ? input.verifyBaselineUntrackedPaths : undefined,
137
142
  // External verifiers cannot have their tools structurally removed the way an internal
138
143
  // verifier's are — advisory, not enforced (D9).
139
144
  verificationStrength: "advisory",
@@ -1,4 +1,4 @@
1
- import { formatDuration } from "../shared/duration.js";
1
+ import { formatDuration } from "../shared/format.js";
2
2
  import type { RunRecord } from "./runs.js";
3
3
  /**
4
4
  * Shared display primitives for delegation runs (spec 041), used by both the model-facing
@@ -1,4 +1,4 @@
1
- import { formatDuration } from "../shared/duration.js";
1
+ import { formatDuration } from "../shared/format.js";
2
2
  /**
3
3
  * Shared display primitives for delegation runs (spec 041), used by both the model-facing
4
4
  * `subagent_list`/`subagent_run` tools and the human-facing `/subagents` runtime command. Only the pieces that
@@ -240,6 +240,8 @@ export interface RunManagerOptions {
240
240
  notify?: RunNotifier;
241
241
  ledger?: UsageLedger;
242
242
  store?: ChannelStore;
243
+ /** Application-wide admission count, supplied by the owning runtime. */
244
+ runningCount?: () => number;
243
245
  }
244
246
  /**
245
247
  * Per-channel manager for delegation runs — the single settlement/usage/wake authority for both
@@ -264,9 +266,12 @@ export declare class SubAgentRunManager {
264
266
  /** Live external runs' tail-the-artifact-file progress pollers (P1a). Never persisted or
265
267
  * reconstructed on restore — an adopted run has no fresher information to poll for than
266
268
  * restart reconciliation already reads once from the finished process's own output. */
269
+ private stopped;
267
270
  private readonly externalProgressTails;
268
271
  private readonly queue;
269
272
  constructor(channelId: string, options: RunManagerOptions);
273
+ /** Release observation timers without cancelling dispatched work or its settlement. */
274
+ stop(): void;
270
275
  private recordDir;
271
276
  private recordPath;
272
277
  private persist;
@@ -427,16 +432,12 @@ export declare class SubAgentRunManager {
427
432
  private collectGarbageIfExpired;
428
433
  collectGarbage(now?: number): Promise<void>;
429
434
  }
430
- /** Stop the host-wide daily garbage collector during shutdown or test teardown. */
431
- export declare function stopSubAgentGarbageCollector(): void;
432
- /** Give runs their persistence root, wake delivery, ledger, and archive. Called once from bootstrap. */
433
- export declare function configureSubAgentRuntime(config: RunManagerOptions): void;
434
- export declare function getSubAgentRunManager(channelId: string): SubAgentRunManager;
435
- /**
436
- * Re-adopt every channel's persisted runs at startup, settling any internal run still marked
437
- * `running` as `lost` (D10.3). Channels are discovered from the state directory itself, exactly
438
- * like `restoreChannelJobs` — but by reading the records rather than trusting directory names,
439
- * so a channel is adopted under the id the rest of the runtime can act on.
440
- */
441
- export declare function restoreAllSubAgentRuns(): Promise<number>;
435
+ /** Owns this application's channel managers and their maintenance timer. */
436
+ export declare function createSubAgentRuntime(options?: RunManagerOptions): {
437
+ get: (channelId: string) => SubAgentRunManager;
438
+ restore: () => Promise<number>;
439
+ start: () => void;
440
+ stop: () => void;
441
+ };
442
+ export type SubAgentRuntime = ReturnType<typeof createSubAgentRuntime>;
442
443
  export {};
@@ -3,7 +3,7 @@ import { dirname, join, relative, sep } from "node:path";
3
3
  import { getChannelDir, isChannelId } from "../channel/channel-paths.js";
4
4
  import * as log from "../log.js";
5
5
  import { writeFileAtomically } from "../shared/atomic-file.js";
6
- import { formatDuration } from "../shared/duration.js";
6
+ import { formatDuration } from "../shared/format.js";
7
7
  import { isProcessAlive, killProcessGroup, readProcessStartTime } from "../shared/host-process.js";
8
8
  import { RecoverableToolError } from "../shared/recoverable-error.js";
9
9
  import { createSerialQueue } from "../shared/serial-queue.js";
@@ -164,9 +164,18 @@ export class SubAgentRunManager {
164
164
  /** Live external runs' tail-the-artifact-file progress pollers (P1a). Never persisted or
165
165
  * reconstructed on restore — an adopted run has no fresher information to poll for than
166
166
  * restart reconciliation already reads once from the finished process's own output. */
167
+ this.stopped = false;
167
168
  this.externalProgressTails = new Map();
168
169
  this.queue = createSerialQueue();
169
170
  }
171
+ /** Release observation timers without cancelling dispatched work or its settlement. */
172
+ stop() {
173
+ this.stopped = true;
174
+ for (const runId of this.externalRecoveryTimers.keys())
175
+ this.clearExternalRecoveryTimer(runId);
176
+ for (const runId of this.externalProgressTails.keys())
177
+ this.stopExternalProgressTail(runId);
178
+ }
170
179
  recordDir() {
171
180
  // `getChannelDir`, not a raw join: a DingTalk group id routinely contains `/`, which used
172
181
  // to nest the records one directory deeper than the startup scan ever looked — so a
@@ -221,6 +230,8 @@ export class SubAgentRunManager {
221
230
  /** Start tailing a just-launched external run's artifact file for a human-readable step label
222
231
  * (P1a). Best-effort only — see `progress-tail.ts` for the polling/pacing contract. */
223
232
  startExternalProgressTail(record) {
233
+ if (this.stopped)
234
+ return;
224
235
  if (!record.harness)
225
236
  return;
226
237
  this.stopExternalProgressTail(record.runId);
@@ -321,7 +332,7 @@ export class SubAgentRunManager {
321
332
  throw new RecoverableToolError(`Too many delegation runs already running on this channel (>= ${MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL}). ` +
322
333
  "Wait for one to finish, or cancel one with subagent_run op=cancel first.");
323
334
  }
324
- if (totalRunningSubAgentRuns() >= MAX_RUNNING_SUBAGENT_RUNS_PER_HOST) {
335
+ if ((this.options.runningCount?.() ?? this.runningCount()) >= MAX_RUNNING_SUBAGENT_RUNS_PER_HOST) {
325
336
  throw new RecoverableToolError(`Too many delegation runs already running host-wide (>= ${MAX_RUNNING_SUBAGENT_RUNS_PER_HOST}). ` +
326
337
  "Wait for one to finish before dispatching another.");
327
338
  }
@@ -1093,6 +1104,8 @@ export class SubAgentRunManager {
1093
1104
  this.externalRecoveryTimers.delete(runId);
1094
1105
  }
1095
1106
  scheduleExternalRecovery(record) {
1107
+ if (this.stopped)
1108
+ return;
1096
1109
  if (!record.deadlineAt)
1097
1110
  return;
1098
1111
  this.clearExternalRecoveryTimer(record.runId);
@@ -1130,61 +1143,6 @@ export class SubAgentRunManager {
1130
1143
  }
1131
1144
  }
1132
1145
  }
1133
- const managers = new Map();
1134
- /** Host-wide running count for the D10.2 admission check, summed across every known channel. */
1135
- function totalRunningSubAgentRuns() {
1136
- let total = 0;
1137
- for (const manager of managers.values()) {
1138
- total += manager.runningCount();
1139
- }
1140
- return total;
1141
- }
1142
- let runtimeConfig = {};
1143
- const GARBAGE_COLLECTION_INTERVAL_MS = 24 * 60 * 60_000;
1144
- let garbageCollectionTimer;
1145
- let collectingGarbage = false;
1146
- async function collectGarbageAllChannels() {
1147
- if (collectingGarbage)
1148
- return;
1149
- collectingGarbage = true;
1150
- try {
1151
- for (const manager of managers.values()) {
1152
- await manager
1153
- .collectGarbage()
1154
- .catch((error) => log.logWarning("Sub-agent garbage collection failed", errorMessage(error)));
1155
- }
1156
- }
1157
- finally {
1158
- collectingGarbage = false;
1159
- }
1160
- }
1161
- function startSubAgentGarbageCollector() {
1162
- if (garbageCollectionTimer)
1163
- clearInterval(garbageCollectionTimer);
1164
- garbageCollectionTimer = setInterval(() => void collectGarbageAllChannels(), GARBAGE_COLLECTION_INTERVAL_MS);
1165
- garbageCollectionTimer.unref?.();
1166
- }
1167
- /** Stop the host-wide daily garbage collector during shutdown or test teardown. */
1168
- export function stopSubAgentGarbageCollector() {
1169
- if (garbageCollectionTimer) {
1170
- clearInterval(garbageCollectionTimer);
1171
- garbageCollectionTimer = undefined;
1172
- }
1173
- }
1174
- /** Give runs their persistence root, wake delivery, ledger, and archive. Called once from bootstrap. */
1175
- export function configureSubAgentRuntime(config) {
1176
- runtimeConfig = config;
1177
- stopSubAgentGarbageCollector();
1178
- startSubAgentGarbageCollector();
1179
- }
1180
- export function getSubAgentRunManager(channelId) {
1181
- let manager = managers.get(channelId);
1182
- if (!manager) {
1183
- manager = new SubAgentRunManager(channelId, runtimeConfig);
1184
- managers.set(channelId, manager);
1185
- }
1186
- return manager;
1187
- }
1188
1146
  /**
1189
1147
  * How deep the scan below looks for record files.
1190
1148
  *
@@ -1265,43 +1223,104 @@ async function adoptRecordDirectory(stateDir, dir) {
1265
1223
  }
1266
1224
  return Array.from(channelIds);
1267
1225
  }
1268
- /**
1269
- * Re-adopt every channel's persisted runs at startup, settling any internal run still marked
1270
- * `running` as `lost` (D10.3). Channels are discovered from the state directory itself, exactly
1271
- * like `restoreChannelJobs` — but by reading the records rather than trusting directory names,
1272
- * so a channel is adopted under the id the rest of the runtime can act on.
1273
- */
1274
- export async function restoreAllSubAgentRuns() {
1275
- const stateDir = runtimeConfig.stateDir;
1276
- if (!stateDir)
1277
- return 0;
1278
- const channelIds = new Set();
1279
- let recordDirs;
1280
- try {
1281
- await mkdir(stateDir, { recursive: true });
1282
- recordDirs = await findRecordDirectories(stateDir);
1283
- }
1284
- catch (error) {
1285
- log.logWarning("Failed to scan persisted sub-agent runs", errorMessage(error));
1286
- return 0;
1226
+ /** Owns this application's channel managers and their maintenance timer. */
1227
+ export function createSubAgentRuntime(options = {}) {
1228
+ const config = { ...options };
1229
+ const managers = new Map();
1230
+ let stopped = false;
1231
+ /** Host-wide running count for the D10.2 admission check, summed across every known channel. */
1232
+ function totalRunningSubAgentRuns() {
1233
+ let total = 0;
1234
+ for (const manager of managers.values()) {
1235
+ total += manager.runningCount();
1236
+ }
1237
+ return total;
1287
1238
  }
1288
- for (const dir of recordDirs) {
1239
+ const GARBAGE_COLLECTION_INTERVAL_MS = 24 * 60 * 60_000;
1240
+ let garbageCollectionTimer;
1241
+ let collectingGarbage = false;
1242
+ async function collectGarbageAllChannels() {
1243
+ if (collectingGarbage)
1244
+ return;
1245
+ collectingGarbage = true;
1289
1246
  try {
1290
- for (const channelId of await adoptRecordDirectory(stateDir, dir))
1291
- channelIds.add(channelId);
1247
+ for (const manager of managers.values()) {
1248
+ await manager
1249
+ .collectGarbage()
1250
+ .catch((error) => log.logWarning("Sub-agent garbage collection failed", errorMessage(error)));
1251
+ }
1292
1252
  }
1293
- catch (error) {
1294
- log.logWarning(`Failed to adopt sub-agent run records in ${relative(stateDir, dir)}`, errorMessage(error));
1253
+ finally {
1254
+ collectingGarbage = false;
1295
1255
  }
1296
1256
  }
1297
- let restored = 0;
1298
- for (const channelId of channelIds) {
1299
- restored += await getSubAgentRunManager(channelId).restore();
1257
+ function startSubAgentGarbageCollector() {
1258
+ if (stopped)
1259
+ return;
1260
+ if (garbageCollectionTimer)
1261
+ clearInterval(garbageCollectionTimer);
1262
+ garbageCollectionTimer = setInterval(() => void collectGarbageAllChannels(), GARBAGE_COLLECTION_INTERVAL_MS);
1263
+ garbageCollectionTimer.unref?.();
1264
+ }
1265
+ /** Stop the host-wide daily garbage collector during shutdown or test teardown. */
1266
+ function stop() {
1267
+ stopped = true;
1268
+ for (const manager of managers.values())
1269
+ manager.stop();
1270
+ if (garbageCollectionTimer) {
1271
+ clearInterval(garbageCollectionTimer);
1272
+ garbageCollectionTimer = undefined;
1273
+ }
1300
1274
  }
1301
- // Reclaim stale runs once as a host-wide startup batch; subsequent batches run daily.
1302
- await collectGarbageAllChannels();
1303
- if (restored > 0) {
1304
- log.logInfo(`Restored ${restored} sub-agent run record(s)`);
1275
+ function get(channelId) {
1276
+ let manager = managers.get(channelId);
1277
+ if (!manager) {
1278
+ manager = new SubAgentRunManager(channelId, { ...config, runningCount: totalRunningSubAgentRuns });
1279
+ managers.set(channelId, manager);
1280
+ if (stopped)
1281
+ manager.stop();
1282
+ }
1283
+ return manager;
1284
+ }
1285
+ /**
1286
+ * Re-adopt every channel's persisted runs at startup, settling any internal run still marked
1287
+ * `running` as `lost` (D10.3). Channels are discovered from the state directory itself, exactly
1288
+ * like `restoreChannelJobs` — but by reading the records rather than trusting directory names,
1289
+ * so a channel is adopted under the id the rest of the runtime can act on.
1290
+ */
1291
+ async function restore() {
1292
+ const stateDir = config.stateDir;
1293
+ if (!stateDir)
1294
+ return 0;
1295
+ const channelIds = new Set();
1296
+ let recordDirs;
1297
+ try {
1298
+ await mkdir(stateDir, { recursive: true });
1299
+ recordDirs = await findRecordDirectories(stateDir);
1300
+ }
1301
+ catch (error) {
1302
+ log.logWarning("Failed to scan persisted sub-agent runs", errorMessage(error));
1303
+ return 0;
1304
+ }
1305
+ for (const dir of recordDirs) {
1306
+ try {
1307
+ for (const channelId of await adoptRecordDirectory(stateDir, dir))
1308
+ channelIds.add(channelId);
1309
+ }
1310
+ catch (error) {
1311
+ log.logWarning(`Failed to adopt sub-agent run records in ${relative(stateDir, dir)}`, errorMessage(error));
1312
+ }
1313
+ }
1314
+ let restored = 0;
1315
+ for (const channelId of channelIds) {
1316
+ restored += await get(channelId).restore();
1317
+ }
1318
+ // Reclaim stale runs once as a host-wide startup batch; subsequent batches run daily.
1319
+ await collectGarbageAllChannels();
1320
+ if (restored > 0) {
1321
+ log.logInfo(`Restored ${restored} sub-agent run record(s)`);
1322
+ }
1323
+ return restored;
1305
1324
  }
1306
- return restored;
1325
+ return { get, restore, start: startSubAgentGarbageCollector, stop };
1307
1326
  }
@@ -6,8 +6,8 @@ import type { FileStore } from "../file-store.js";
6
6
  import type { SecurityConfig } from "../security/types.js";
7
7
  import { type UsageTotals } from "../shared/types.js";
8
8
  import type { PipiclawWebToolsConfig } from "../tools/config.js";
9
- import { type ResolvedSubAgentConfig, type SubAgentConfig, type SubAgentDiscoveryResult } from "./discovery.js";
10
- import { getSubAgentRunManager } from "./runs.js";
9
+ import { type ResolvedInternalSubAgentConfig, type ResolvedSubAgentConfig, type SubAgentConfig, type SubAgentDiscoveryResult } from "./discovery.js";
10
+ import { type SubAgentRunManager } from "./runs.js";
11
11
  /**
12
12
  * Role-based delegation (spec 046, D2.1): the common path. No override fields beyond routing
13
13
  * ones — tools, model, effort, context, thinkingLevel and mutates all live in the role file, so
@@ -94,7 +94,7 @@ export interface SubAgentToolOptions {
94
94
  channelId: string;
95
95
  };
96
96
  createWorker?: (config: {
97
- subAgent: ResolvedSubAgentConfig;
97
+ subAgent: ResolvedInternalSubAgentConfig;
98
98
  apiKey: string;
99
99
  tools: AgentTool<any>[];
100
100
  }) => SubAgentWorker;
@@ -104,8 +104,8 @@ export interface SubAgentToolOptions {
104
104
  convergenceWallClockMs?: number;
105
105
  /** Test-only override for the D2 sync grace window; defaults to SYNC_GRACE_MS. */
106
106
  syncGraceMs?: number;
107
- /** Test seam for setup/admission failures. Production uses the process-wide channel manager. */
108
- getRunManager?: typeof getSubAgentRunManager;
107
+ /** Channel manager owned by the application; also a seam for admission failures. */
108
+ getRunManager: (channelId: string) => SubAgentRunManager;
109
109
  }
110
110
  interface SubAgentWorker {
111
111
  state: {
@@ -124,6 +124,12 @@ interface SubAgentWorker {
124
124
  * only caps what gets echoed into the parent's context.
125
125
  */
126
126
  export declare const MAX_SUBAGENT_RESULT_UNITS = 1200;
127
+ /**
128
+ * Character ceiling paired with the unit ceiling. `prompt-units.ts` notes that a long
129
+ * separator-free run of letters/digits counts as a single unit, so a units-only budget can still
130
+ * pass through an unbounded blob — every budget must bound units *and* chars (fix plan §2.4).
131
+ */
132
+ export declare const MAX_SUBAGENT_RESULT_CHARS = 12000;
127
133
  /** Exported for `subagent_run op=follow_up` (spec 042 D7), which constructs one of these for
128
134
  * its own new run rather than a hand-rolled envelope. */
129
135
  export interface SubAgentRunContext {
@@ -144,8 +150,8 @@ export interface SubAgentRunContext {
144
150
  */
145
151
  export declare function assertWithinProjectBoundary(target: string, base: string, requested: string): void;
146
152
  /**
147
- * Build a sub-agent's tool set from the shared tool registry, filtered to tools flagged
148
- * available to sub-agents (files + web). Sub-agents run with their own security context
153
+ * Build a sub-agent's tool set from the shared tool registry, filtered by the shared
154
+ * sub-agent whitelist (files + web). Sub-agents run with their own security context
149
155
  * (rooted at the sub-agent workspace) and their own per-invocation bash timeout.
150
156
  */
151
157
  declare function buildSubagentTools(executor: Executor, bashTimeoutSec: number, options: SubAgentToolOptions, runContext: SubAgentRunContext): AgentTool<any>[];