@oyasmi/pipiclaw 0.9.3-beta.3 → 0.9.3-beta.5

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 (126) hide show
  1. package/README.en.md +12 -12
  2. package/README.md +12 -12
  3. package/dist/agent/channel-runner.d.ts +4 -18
  4. package/dist/agent/channel-runner.js +26 -121
  5. package/dist/agent/context-budget.js +1 -1
  6. package/dist/agent/job-manager.d.ts +11 -17
  7. package/dist/agent/job-manager.js +77 -67
  8. package/dist/agent/prompt/builder.js +1 -17
  9. package/dist/agent/prompt/manifest.d.ts +0 -1
  10. package/dist/agent/prompt/manifest.js +2 -2
  11. package/dist/agent/prompt/sections.js +0 -9
  12. package/dist/agent/prompt/types.d.ts +2 -18
  13. package/dist/agent/prompt/types.js +1 -1
  14. package/dist/agent/runner-factory.d.ts +4 -0
  15. package/dist/agent/session-adapter.d.ts +19 -0
  16. package/dist/agent/session-adapter.js +77 -0
  17. package/dist/app-services.d.ts +18 -0
  18. package/dist/app-services.js +43 -0
  19. package/dist/channel/channel-context.d.ts +2 -2
  20. package/dist/channel/channel-context.js +2 -2
  21. package/dist/channel/channel-event.d.ts +3 -3
  22. package/dist/{runtime → events}/events.d.ts +1 -1
  23. package/dist/memory/journal.js +1 -1
  24. package/dist/memory/maintenance-gates.d.ts +0 -3
  25. package/dist/memory/maintenance-gates.js +2 -2
  26. package/dist/memory/maintenance-migration.d.ts +5 -0
  27. package/dist/memory/maintenance-migration.js +91 -0
  28. package/dist/memory/maintenance-state.js +5 -44
  29. package/dist/memory/migrate.js +1 -1
  30. package/dist/memory/reflect-job.d.ts +1 -9
  31. package/dist/memory/reflect-job.js +1 -3
  32. package/dist/memory/reflect.js +1 -1
  33. package/dist/memory/session-corpus.js +1 -1
  34. package/dist/memory/store.js +1 -1
  35. package/dist/models/auth-cli.js +1 -1
  36. package/dist/playbooks/agent-delegation.md +15 -11
  37. package/dist/playbooks/background-jobs.md +1 -1
  38. package/dist/playbooks/runtime-orientation.md +2 -0
  39. package/dist/playbooks/task-loop.md +1 -1
  40. package/dist/runtime/bootstrap.d.ts +5 -15
  41. package/dist/runtime/bootstrap.js +44 -65
  42. package/dist/runtime/delivery.d.ts +1 -2
  43. package/dist/runtime/delivery.js +57 -62
  44. package/dist/runtime/dingtalk.d.ts +15 -8
  45. package/dist/runtime/dingtalk.js +101 -35
  46. package/dist/runtime/subagent-commands.d.ts +2 -1
  47. package/dist/runtime/subagent-commands.js +10 -12
  48. package/dist/runtime/task-wake.d.ts +4 -5
  49. package/dist/runtime/task-wake.js +2 -12
  50. package/dist/security/types.d.ts +7 -0
  51. package/dist/security/types.js +16 -1
  52. package/dist/settings.d.ts +8 -0
  53. package/dist/settings.js +24 -1
  54. package/dist/shared/exact-keys.d.ts +13 -0
  55. package/dist/shared/exact-keys.js +1 -0
  56. package/dist/shared/format.d.ts +20 -0
  57. package/dist/shared/format.js +64 -0
  58. package/dist/shared/{fs-utils.d.ts → os.d.ts} +6 -0
  59. package/dist/shared/{fs-utils.js → os.js} +8 -0
  60. package/dist/subagents/discovery.d.ts +16 -3
  61. package/dist/subagents/discovery.js +13 -9
  62. package/dist/subagents/external/claude-code.js +3 -1
  63. package/dist/subagents/external/harness.d.ts +4 -2
  64. package/dist/subagents/external/run.d.ts +2 -1
  65. package/dist/subagents/external/run.js +13 -5
  66. package/dist/subagents/external/settlement.js +10 -5
  67. package/dist/subagents/format.d.ts +1 -1
  68. package/dist/subagents/format.js +1 -1
  69. package/dist/subagents/runs.d.ts +13 -12
  70. package/dist/subagents/runs.js +109 -91
  71. package/dist/subagents/tool.d.ts +7 -7
  72. package/dist/subagents/tool.js +11 -11
  73. package/dist/tasks/brief.js +1 -0
  74. package/dist/tools/command-optimizer.js +1 -1
  75. package/dist/tools/config.d.ts +7 -0
  76. package/dist/tools/config.js +16 -1
  77. package/dist/tools/event-manage.d.ts +1 -1
  78. package/dist/tools/event-manage.js +3 -3
  79. package/dist/tools/grep.js +1 -1
  80. package/dist/tools/index.d.ts +4 -0
  81. package/dist/tools/index.js +4 -2
  82. package/dist/tools/job.js +1 -1
  83. package/dist/tools/read.js +1 -1
  84. package/dist/tools/registry.d.ts +3 -3
  85. package/dist/tools/registry.js +18 -56
  86. package/dist/tools/skill.js +1 -1
  87. package/dist/tools/subagent-manage.d.ts +2 -0
  88. package/dist/tools/subagent-manage.js +7 -7
  89. package/dist/tools/subagent-tool-names.d.ts +2 -2
  90. package/dist/tools/subagent-tool-names.js +2 -2
  91. package/dist/tools/task-manage/shared.js +4 -9
  92. package/dist/tools/task-manage/types.d.ts +4 -0
  93. package/dist/tui/app.js +22 -7
  94. package/dist/web/config.js +1 -1
  95. package/examples/sub-agents/README.md +65 -81
  96. package/examples/sub-agents/agents/claude-high.md +23 -0
  97. package/examples/sub-agents/agents/claude-main.md +23 -0
  98. package/examples/sub-agents/agents/codex-flash.md +23 -0
  99. package/examples/sub-agents/agents/codex-high.md +23 -0
  100. package/examples/sub-agents/agents/codex-main.md +23 -0
  101. package/examples/sub-agents/agents/glm-flash.md +23 -0
  102. package/examples/sub-agents/agents/glm-high.md +23 -0
  103. package/package.json +2 -1
  104. package/dist/shared/duration.d.ts +0 -2
  105. package/dist/shared/duration.js +0 -7
  106. package/dist/shared/file-stamp.d.ts +0 -10
  107. package/dist/shared/file-stamp.js +0 -19
  108. package/dist/shared/numeric.d.ts +0 -7
  109. package/dist/shared/numeric.js +0 -19
  110. package/dist/shared/shell-escape.d.ts +0 -5
  111. package/dist/shared/shell-escape.js +0 -7
  112. package/dist/shared/token-estimate.d.ts +0 -1
  113. package/dist/shared/token-estimate.js +0 -19
  114. /package/dist/{runtime → events}/event-commands.d.ts +0 -0
  115. /package/dist/{runtime → events}/event-commands.js +0 -0
  116. /package/dist/{runtime → events}/event-validation.d.ts +0 -0
  117. /package/dist/{runtime → events}/event-validation.js +0 -0
  118. /package/dist/{runtime → events}/events.js +0 -0
  119. /package/examples/sub-agents/{builder-hard.md → roles/builder-hard.md} +0 -0
  120. /package/examples/sub-agents/{builder.md → roles/builder.md} +0 -0
  121. /package/examples/sub-agents/{explorer.md → roles/explorer.md} +0 -0
  122. /package/examples/sub-agents/{git-committer.md → roles/git-committer.md} +0 -0
  123. /package/examples/sub-agents/{planner.md → roles/planner.md} +0 -0
  124. /package/examples/sub-agents/{reviewer.md → roles/reviewer.md} +0 -0
  125. /package/examples/sub-agents/{verifier.md → roles/verifier.md} +0 -0
  126. /package/examples/sub-agents/{worker.md → roles/worker.md} +0 -0
@@ -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
  };
@@ -484,9 +484,11 @@ function parseExternalAgent(entryName, filePath, frontmatter, body, name, descri
484
484
  ? `${entryName}: memory: ${memoryMode.value} sends the channel memory index / journal content to this external process`
485
485
  : undefined;
486
486
  const maxWallTimeSec = parsePositiveInteger(frontmatter.maxWallTimeSec, DEFAULT_EXTERNAL_MAX_WALL_TIME_SEC);
487
+ // An empty body is a legitimate declaration for an external role, not a defect: a capability
488
+ // entry ("this agent, this model, this reasoning level") deliberately carries no standing
489
+ // instruction, because the only party that knows what this delegation is for is the main
490
+ // agent writing `task`. Internal roles still require a body — they have no other prompt.
487
491
  const trimmedBody = body.trim();
488
- if (!trimmedBody)
489
- return { warning: `${entryName}: empty system prompt body` };
490
492
  const promptLengthError = validateSubAgentSystemPrompt(trimmedBody, "Sub-agent system prompt");
491
493
  if (promptLengthError)
492
494
  return { warning: `${entryName}: ${promptLengthError}` };
@@ -635,6 +637,14 @@ subagentDefaultModelRef) {
635
637
  if (baseConfig.unavailable) {
636
638
  return { error: `Sub-agent "${baseConfig.name}" is currently unavailable: ${baseConfig.unavailable}` };
637
639
  }
640
+ if (baseConfig.runtime === "external") {
641
+ return {
642
+ config: {
643
+ ...baseConfig,
644
+ thinkingLevel: baseConfig.thinkingLevel ?? (overrides.purpose === "verify" ? DEFAULT_THINKING_LEVEL : undefined),
645
+ },
646
+ };
647
+ }
638
648
  let model = baseConfig.model;
639
649
  let modelRef = baseConfig.modelRef;
640
650
  if (!model && subagentDefaultModelRef) {
@@ -645,13 +655,7 @@ subagentDefaultModelRef) {
645
655
  model = resolved.model;
646
656
  modelRef = formatModelReference(resolved.model);
647
657
  }
648
- const purpose = overrides.purpose === "verify" ? "verify" : "work";
649
- // External work is not defaulted: pipiclaw has no standing to pick a reasoning effort for
650
- // another CLI's own configuration. External verify still defaults — it is the last unattended
651
- // gate before an attestation is trusted, and "whatever that machine happens to have configured"
652
- // is not an acceptable substitute for real reasoning.
653
- const thinkingLevel = baseConfig.thinkingLevel ??
654
- (baseConfig.runtime === "external" && purpose !== "verify" ? undefined : DEFAULT_THINKING_LEVEL);
658
+ const thinkingLevel = baseConfig.thinkingLevel ?? DEFAULT_THINKING_LEVEL;
655
659
  const mutates = baseConfig.mutates ?? inferMutatesFromTools(baseConfig.tools);
656
660
  return {
657
661
  config: {
@@ -56,7 +56,9 @@ export const claudeCodeHarness = {
56
56
  if (!existing.effort && effort && !used.has("$EFFORT")) {
57
57
  args.push("--effort", effort);
58
58
  }
59
- if (!used.has("$SYSTEM_PROMPT_FILE")) {
59
+ // A role with an empty body has no system-prompt file on disk, so the flag is omitted
60
+ // entirely rather than pointed at a path that was never written.
61
+ if (!used.has("$SYSTEM_PROMPT_FILE") && input.systemPromptFile) {
60
62
  args.push("--append-system-prompt-file", input.systemPromptFile);
61
63
  }
62
64
  let presetSessionId;
@@ -16,8 +16,10 @@ export interface ExternalInvocationInput {
16
16
  /** Path to the stdin prompt file (D1 layout: `<artifactDir>/prompt.txt`). */
17
17
  promptFile: string;
18
18
  /** Path to the role's system-prompt file (`<artifactDir>/system-prompt.txt`), for harnesses
19
- * that reference it by flag (e.g. claude-code's `--append-system-prompt-file`). */
20
- systemPromptFile: string;
19
+ * that reference it by flag (e.g. claude-code's `--append-system-prompt-file`). Undefined
20
+ * when the role declares no system prompt at all (a capability entry with an empty body):
21
+ * the file is then not written, so no harness may reference a path that does not exist. */
22
+ systemPromptFile?: string;
21
23
  /** Set when this invocation continues an earlier run (`subagent_run op=follow_up`, D6). */
22
24
  resumeSessionId?: string;
23
25
  }
@@ -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
  /**
@@ -103,7 +102,12 @@ function buildStdinContent(harnessId, systemPrompt, task) {
103
102
  // itself, folded ahead of the task.
104
103
  if (harnessId === "claude-code")
105
104
  return task;
106
- return `${systemPrompt.trim()}\n\n---\n\n${task.trim()}\n`;
105
+ const trimmedPrompt = systemPrompt.trim();
106
+ // A capability entry declares no system prompt at all: the task must then start the prompt,
107
+ // with no leading blank section and no `---` fence separating it from nothing.
108
+ if (!trimmedPrompt)
109
+ return `${task.trim()}\n`;
110
+ return `${trimmedPrompt}\n\n---\n\n${task.trim()}\n`;
107
111
  }
108
112
  /** Launches an external run. Resolves once the process is confirmed spawned (or fails fast if it
109
113
  * never starts, spec 042 D2); the wait-for-exit-and-settle work continues in the background
@@ -121,10 +125,14 @@ export async function launchExternalRun(input) {
121
125
  // either way.
122
126
  await mkdir(input.artifactDir, { recursive: true });
123
127
  const promptFile = join(input.artifactDir, "prompt.txt");
124
- const systemPromptFile = join(input.artifactDir, "system-prompt.txt");
128
+ const trimmedSystemPrompt = input.systemPrompt.trim();
129
+ // Only written when the role actually declares one, so `system-prompt.txt`'s presence in a run's
130
+ // artifacts stays a truthful record of what was sent (D1 layout) instead of an empty decoy.
131
+ const systemPromptFile = trimmedSystemPrompt ? join(input.artifactDir, "system-prompt.txt") : undefined;
125
132
  const stdinContent = buildStdinContent(harness.id, input.systemPrompt, input.task);
126
133
  await writeFile(promptFile, `${input.task.trim()}\n`, "utf-8");
127
- await writeFile(systemPromptFile, `${input.systemPrompt.trim()}\n`, "utf-8");
134
+ if (systemPromptFile)
135
+ await writeFile(systemPromptFile, `${trimmedSystemPrompt}\n`, "utf-8");
128
136
  // D9: an external verifier's advisory attestation needs a before/after subject snapshot the
129
137
  // same way the internal path does — taken here, before the process starts, since this is the
130
138
  // earliest point at which the run is committed to running against this workingDirectory. The
@@ -151,7 +159,7 @@ export async function launchExternalRun(input) {
151
159
  // or host-wide cap still left behind an `external-agent` audit record claiming a process that
152
160
  // never existed. `external-agent` records what was *executed* (D8.1), so the record must not
153
161
  // precede the point where this run is actually admitted to run.
154
- const runManager = getSubAgentRunManager(input.channelId);
162
+ const runManager = input.runManager;
155
163
  await runManager.register({
156
164
  runId: input.runId,
157
165
  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
  }
@@ -710,8 +721,7 @@ export class SubAgentRunManager {
710
721
  ts: String(Date.now()),
711
722
  conversationType: record.channelId.startsWith("group_") ? "2" : "1",
712
723
  dispatchId: `subagent:${record.channelId}:${record.runId}:done`,
713
- // P0-2: a user is genuinely waiting on this result — render the resulting turn's progress
714
- // instead of the "none" style autonomous check-ins get (delivery.ts's `progressStyleOverride`).
724
+ // The result is awaited; the wake itself still runs without a progress card.
715
725
  presentation: "awaited",
716
726
  ...(record.taskId
717
727
  ? {
@@ -1093,6 +1103,8 @@ export class SubAgentRunManager {
1093
1103
  this.externalRecoveryTimers.delete(runId);
1094
1104
  }
1095
1105
  scheduleExternalRecovery(record) {
1106
+ if (this.stopped)
1107
+ return;
1096
1108
  if (!record.deadlineAt)
1097
1109
  return;
1098
1110
  this.clearExternalRecoveryTimer(record.runId);
@@ -1130,61 +1142,6 @@ export class SubAgentRunManager {
1130
1142
  }
1131
1143
  }
1132
1144
  }
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
1145
  /**
1189
1146
  * How deep the scan below looks for record files.
1190
1147
  *
@@ -1265,43 +1222,104 @@ async function adoptRecordDirectory(stateDir, dir) {
1265
1222
  }
1266
1223
  return Array.from(channelIds);
1267
1224
  }
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;
1225
+ /** Owns this application's channel managers and their maintenance timer. */
1226
+ export function createSubAgentRuntime(options = {}) {
1227
+ const config = { ...options };
1228
+ const managers = new Map();
1229
+ let stopped = false;
1230
+ /** Host-wide running count for the D10.2 admission check, summed across every known channel. */
1231
+ function totalRunningSubAgentRuns() {
1232
+ let total = 0;
1233
+ for (const manager of managers.values()) {
1234
+ total += manager.runningCount();
1235
+ }
1236
+ return total;
1287
1237
  }
1288
- for (const dir of recordDirs) {
1238
+ const GARBAGE_COLLECTION_INTERVAL_MS = 24 * 60 * 60_000;
1239
+ let garbageCollectionTimer;
1240
+ let collectingGarbage = false;
1241
+ async function collectGarbageAllChannels() {
1242
+ if (collectingGarbage)
1243
+ return;
1244
+ collectingGarbage = true;
1289
1245
  try {
1290
- for (const channelId of await adoptRecordDirectory(stateDir, dir))
1291
- channelIds.add(channelId);
1246
+ for (const manager of managers.values()) {
1247
+ await manager
1248
+ .collectGarbage()
1249
+ .catch((error) => log.logWarning("Sub-agent garbage collection failed", errorMessage(error)));
1250
+ }
1292
1251
  }
1293
- catch (error) {
1294
- log.logWarning(`Failed to adopt sub-agent run records in ${relative(stateDir, dir)}`, errorMessage(error));
1252
+ finally {
1253
+ collectingGarbage = false;
1295
1254
  }
1296
1255
  }
1297
- let restored = 0;
1298
- for (const channelId of channelIds) {
1299
- restored += await getSubAgentRunManager(channelId).restore();
1256
+ function startSubAgentGarbageCollector() {
1257
+ if (stopped)
1258
+ return;
1259
+ if (garbageCollectionTimer)
1260
+ clearInterval(garbageCollectionTimer);
1261
+ garbageCollectionTimer = setInterval(() => void collectGarbageAllChannels(), GARBAGE_COLLECTION_INTERVAL_MS);
1262
+ garbageCollectionTimer.unref?.();
1263
+ }
1264
+ /** Stop the host-wide daily garbage collector during shutdown or test teardown. */
1265
+ function stop() {
1266
+ stopped = true;
1267
+ for (const manager of managers.values())
1268
+ manager.stop();
1269
+ if (garbageCollectionTimer) {
1270
+ clearInterval(garbageCollectionTimer);
1271
+ garbageCollectionTimer = undefined;
1272
+ }
1300
1273
  }
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)`);
1274
+ function get(channelId) {
1275
+ let manager = managers.get(channelId);
1276
+ if (!manager) {
1277
+ manager = new SubAgentRunManager(channelId, { ...config, runningCount: totalRunningSubAgentRuns });
1278
+ managers.set(channelId, manager);
1279
+ if (stopped)
1280
+ manager.stop();
1281
+ }
1282
+ return manager;
1283
+ }
1284
+ /**
1285
+ * Re-adopt every channel's persisted runs at startup, settling any internal run still marked
1286
+ * `running` as `lost` (D10.3). Channels are discovered from the state directory itself, exactly
1287
+ * like `restoreChannelJobs` — but by reading the records rather than trusting directory names,
1288
+ * so a channel is adopted under the id the rest of the runtime can act on.
1289
+ */
1290
+ async function restore() {
1291
+ const stateDir = config.stateDir;
1292
+ if (!stateDir)
1293
+ return 0;
1294
+ const channelIds = new Set();
1295
+ let recordDirs;
1296
+ try {
1297
+ await mkdir(stateDir, { recursive: true });
1298
+ recordDirs = await findRecordDirectories(stateDir);
1299
+ }
1300
+ catch (error) {
1301
+ log.logWarning("Failed to scan persisted sub-agent runs", errorMessage(error));
1302
+ return 0;
1303
+ }
1304
+ for (const dir of recordDirs) {
1305
+ try {
1306
+ for (const channelId of await adoptRecordDirectory(stateDir, dir))
1307
+ channelIds.add(channelId);
1308
+ }
1309
+ catch (error) {
1310
+ log.logWarning(`Failed to adopt sub-agent run records in ${relative(stateDir, dir)}`, errorMessage(error));
1311
+ }
1312
+ }
1313
+ let restored = 0;
1314
+ for (const channelId of channelIds) {
1315
+ restored += await get(channelId).restore();
1316
+ }
1317
+ // Reclaim stale runs once as a host-wide startup batch; subsequent batches run daily.
1318
+ await collectGarbageAllChannels();
1319
+ if (restored > 0) {
1320
+ log.logInfo(`Restored ${restored} sub-agent run record(s)`);
1321
+ }
1322
+ return restored;
1305
1323
  }
1306
- return restored;
1324
+ return { get, restore, start: startSubAgentGarbageCollector, stop };
1307
1325
  }
@@ -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: {
@@ -150,8 +150,8 @@ export interface SubAgentRunContext {
150
150
  */
151
151
  export declare function assertWithinProjectBoundary(target: string, base: string, requested: string): void;
152
152
  /**
153
- * Build a sub-agent's tool set from the shared tool registry, filtered to tools flagged
154
- * 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
155
155
  * (rooted at the sub-agent workspace) and their own per-invocation bash timeout.
156
156
  */
157
157
  declare function buildSubagentTools(executor: Executor, bashTimeoutSec: number, options: SubAgentToolOptions, runContext: SubAgentRunContext): AgentTool<any>[];