@xzzpig/pi-subagents 0.7.0 → 0.9.0

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 (234) hide show
  1. package/CHANGELOG.md +456 -4
  2. package/README.md +3 -3
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +13 -3
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +154 -42
  12. package/docs/configuration.md +85 -26
  13. package/docs/extension-api.md +81 -16
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +75 -11
  16. package/docs/observability.md +34 -21
  17. package/docs/tool-reference.md +142 -18
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +148 -4
  20. package/index.ts +10 -1
  21. package/install.mjs +1 -1
  22. package/package.json +7 -6
  23. package/prompts/council.md +19 -7
  24. package/prompts/parallel-review.md +5 -1
  25. package/prompts/review-loop.md +11 -7
  26. package/skills/council-mode/SKILL.md +44 -215
  27. package/skills/council-mode/references/pass-contracts.md +150 -0
  28. package/skills/pi-subagents/SKILL.md +90 -32
  29. package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
  30. package/skills/pi-subagents/references/execution-controls.md +104 -19
  31. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  32. package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
  33. package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
  34. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  35. package/src/agents/agent-management.ts +471 -114
  36. package/src/agents/agent-refinements.ts +4 -4
  37. package/src/agents/agent-serializer.ts +16 -4
  38. package/src/agents/agents.ts +1076 -351
  39. package/src/agents/builtin-names.ts +6 -0
  40. package/src/agents/runtime-agent-events.ts +70 -0
  41. package/src/agents/runtime-agent-registry.ts +31 -20
  42. package/src/api/agents.ts +10 -5
  43. package/src/api/background-work.ts +12 -3
  44. package/src/api/capability-ceiling.ts +0 -1
  45. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  46. package/src/api/delegation.ts +0 -7
  47. package/src/api/external-job-provider.ts +10 -1
  48. package/src/api/external-runs.ts +67 -4
  49. package/src/api/preflight.ts +97 -34
  50. package/src/api/project-panes.ts +2 -0
  51. package/src/api/shared-types.ts +6 -0
  52. package/src/extension/config.ts +90 -0
  53. package/src/extension/doctor.ts +15 -13
  54. package/src/extension/fanout-child.ts +17 -16
  55. package/src/extension/index.ts +139 -41
  56. package/src/extension/public-execution.ts +113 -22
  57. package/src/extension/rpc.ts +182 -13
  58. package/src/extension/schemas.ts +63 -21
  59. package/src/extension/tool-description.ts +48 -23
  60. package/src/extension/tool-result.ts +19 -0
  61. package/src/inspectors/herdr/actions.ts +2 -1
  62. package/src/inspectors/herdr/client.ts +3 -3
  63. package/src/inspectors/herdr/focus.ts +55 -0
  64. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  65. package/src/inspectors/herdr/project-panes.ts +228 -44
  66. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  67. package/src/integrations/herdr-status.ts +75 -5
  68. package/src/intercom/native-supervisor-channel.ts +138 -60
  69. package/src/intercom/result-intercom.ts +2 -0
  70. package/src/intercom/supervisor-ui.ts +243 -0
  71. package/src/profiles/profiles.ts +5 -6
  72. package/src/runs/background/active-async-capacity.ts +103 -18
  73. package/src/runs/background/async-execution.ts +492 -125
  74. package/src/runs/background/async-job-tracker.ts +127 -28
  75. package/src/runs/background/async-resume.ts +67 -29
  76. package/src/runs/background/async-retention.ts +21 -4
  77. package/src/runs/background/async-status-snapshot.ts +23 -261
  78. package/src/runs/background/async-status.ts +199 -14
  79. package/src/runs/background/auto-drain.ts +1 -1
  80. package/src/runs/background/chain-append.ts +8 -3
  81. package/src/runs/background/chain-root-attachment.ts +79 -8
  82. package/src/runs/background/control-channel.ts +101 -214
  83. package/src/runs/background/fleet-view.ts +38 -22
  84. package/src/runs/background/inspect-rpc.ts +8 -8
  85. package/src/runs/background/notify.ts +295 -8
  86. package/src/runs/background/process-terminal.ts +16 -0
  87. package/src/runs/background/result-delivery-ownership.ts +45 -0
  88. package/src/runs/background/result-files.ts +28 -14
  89. package/src/runs/background/result-watcher.ts +43 -19
  90. package/src/runs/background/resume-guidance.ts +2 -2
  91. package/src/runs/background/retained-children.ts +1 -1
  92. package/src/runs/background/run-child-session.ts +613 -0
  93. package/src/runs/background/run-status.ts +99 -18
  94. package/src/runs/background/runner-aliases.ts +125 -0
  95. package/src/runs/background/runner-child-sessions.ts +31 -0
  96. package/src/runs/background/scheduled-runs.ts +174 -18
  97. package/src/runs/background/stale-run-reconciler.ts +13 -4
  98. package/src/runs/background/steering.ts +8 -15
  99. package/src/runs/background/subagent-runner.ts +959 -1159
  100. package/src/runs/background/subagent-wait.ts +86 -31
  101. package/src/runs/background/terminal-run-index.ts +1 -1
  102. package/src/runs/background/wait-completions.ts +45 -2
  103. package/src/runs/background/wait-config.ts +23 -9
  104. package/src/runs/background/wait-tool.ts +27 -19
  105. package/src/runs/foreground/async-steering-action.ts +3 -19
  106. package/src/runs/foreground/async-stop-action.ts +23 -2
  107. package/src/runs/foreground/execution.ts +585 -481
  108. package/src/runs/foreground/foreground-control.ts +13 -0
  109. package/src/runs/foreground/foreground-history.ts +26 -3
  110. package/src/runs/foreground/subagent-executor.ts +1549 -410
  111. package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
  112. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  113. package/src/runs/shared/abort-recovery.ts +119 -0
  114. package/src/runs/shared/acceptance.ts +147 -39
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +565 -0
  117. package/src/runs/shared/background-process-options.ts +9 -0
  118. package/src/runs/shared/capability-ceiling.ts +2 -2
  119. package/src/runs/shared/child-hooks.ts +25 -0
  120. package/src/runs/shared/child-identity.ts +62 -0
  121. package/src/runs/shared/child-launch-plan.ts +151 -0
  122. package/src/runs/shared/child-launch.ts +314 -0
  123. package/src/runs/shared/child-lifecycle.ts +25 -0
  124. package/src/runs/shared/child-runtime-config.ts +126 -0
  125. package/src/runs/shared/child-session.ts +342 -0
  126. package/src/runs/shared/child-tool-plan.ts +540 -0
  127. package/src/runs/shared/claude-code-adapter.ts +133 -0
  128. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  129. package/src/runs/shared/completion-evidence.ts +89 -0
  130. package/src/runs/shared/completion-guard.ts +57 -6
  131. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  132. package/src/runs/shared/dynamic-fanout.ts +4 -4
  133. package/src/runs/shared/extension-bindings.ts +78 -0
  134. package/src/runs/shared/external-cli-contract.ts +167 -0
  135. package/src/runs/shared/external-cli-preflight.ts +138 -0
  136. package/src/runs/shared/external-cli-runner.ts +349 -54
  137. package/src/runs/shared/external-job-bridge.ts +53 -37
  138. package/src/runs/shared/external-job-runner.ts +126 -23
  139. package/src/runs/shared/fast-mode-extension.ts +10 -0
  140. package/src/runs/shared/host-step-status.ts +231 -0
  141. package/src/runs/shared/lane-metadata.ts +126 -0
  142. package/src/runs/shared/launch-cwd.ts +16 -0
  143. package/src/runs/shared/long-running-guard.ts +2 -1
  144. package/src/runs/shared/mcp-config-sources.ts +422 -0
  145. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  146. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  147. package/src/runs/shared/model-exclusions.ts +141 -10
  148. package/src/runs/shared/model-fallback.ts +187 -33
  149. package/src/runs/shared/model-scope.ts +106 -39
  150. package/src/runs/shared/mutation-evidence.ts +199 -0
  151. package/src/runs/shared/nested-events.ts +38 -48
  152. package/src/runs/shared/nested-path.ts +0 -14
  153. package/src/runs/shared/nested-render.ts +9 -5
  154. package/src/runs/shared/orca-progress-tabs.ts +83 -16
  155. package/src/runs/shared/parallel-handoff.ts +423 -7
  156. package/src/runs/shared/parallel-utils.ts +28 -5
  157. package/src/runs/shared/permissions.ts +1 -14
  158. package/src/runs/shared/pi-spawn.ts +69 -35
  159. package/src/runs/shared/process-signal.ts +16 -0
  160. package/src/runs/shared/run-fanout-budget.ts +0 -13
  161. package/src/runs/shared/run-history.ts +21 -1
  162. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  163. package/src/runs/shared/single-output.ts +89 -22
  164. package/src/runs/shared/structured-output.ts +61 -7
  165. package/src/runs/shared/subagent-control.ts +6 -2
  166. package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
  167. package/src/runs/shared/task-intent.ts +21 -7
  168. package/src/runs/shared/tool-availability.ts +18 -64
  169. package/src/runs/shared/tool-budget.ts +0 -14
  170. package/src/runs/shared/tool-timeout.ts +1 -1
  171. package/src/runs/shared/workflow-graph.ts +16 -0
  172. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  173. package/src/runs/shared/worktree.ts +571 -62
  174. package/src/shared/atomic-json.ts +3 -1
  175. package/src/shared/child-session-name.ts +46 -0
  176. package/src/shared/extension-context.ts +24 -0
  177. package/src/shared/fork-context.ts +21 -12
  178. package/src/shared/fork-session-cwd.ts +27 -0
  179. package/src/shared/formatters.ts +18 -3
  180. package/src/shared/jsonl-writer.ts +11 -0
  181. package/src/shared/launch-contract.ts +20 -6
  182. package/src/shared/pruned-fork.ts +450 -0
  183. package/src/shared/session-file-trust.ts +19 -0
  184. package/src/shared/session-tokens.ts +14 -3
  185. package/src/shared/settings.ts +21 -102
  186. package/src/shared/shortcuts.ts +17 -0
  187. package/src/shared/thinking-ceiling.ts +46 -0
  188. package/src/shared/types.ts +644 -75
  189. package/src/shared/utils.ts +60 -93
  190. package/src/shared/workflow-child-permit.ts +207 -0
  191. package/src/slash/delegation-adapters.ts +1 -9
  192. package/src/slash/delegation-request.ts +0 -4
  193. package/src/slash/prompt-template-bridge.ts +37 -1
  194. package/src/slash/slash-bridge.ts +1 -2
  195. package/src/slash/slash-commands.ts +383 -116
  196. package/src/slash/slash-live-state.ts +22 -11
  197. package/src/slash/subagents-admin.ts +29 -12
  198. package/src/tui/fleet-native-transcript.ts +4 -0
  199. package/src/tui/fleet-status.ts +278 -90
  200. package/src/tui/fleet-transcript.ts +11 -5
  201. package/src/tui/fleet.ts +54 -28
  202. package/src/tui/render-helpers.ts +31 -0
  203. package/src/tui/render.ts +1433 -166
  204. package/src/watchdog/change-signature.ts +40 -1
  205. package/src/watchdog/child-status.ts +54 -34
  206. package/src/watchdog/diff-tool.ts +77 -0
  207. package/src/watchdog/emission-guard.ts +5 -3
  208. package/src/watchdog/guidance.ts +20 -0
  209. package/src/watchdog/permission-arbiter.ts +59 -52
  210. package/src/watchdog/register-child.ts +28 -25
  211. package/src/watchdog/register-main.ts +10 -9
  212. package/src/watchdog/render.ts +4 -5
  213. package/src/watchdog/review.ts +15 -4
  214. package/src/watchdog/rules.ts +70 -0
  215. package/src/watchdog/runtime.ts +75 -92
  216. package/src/watchdog/scope.ts +0 -11
  217. package/src/watchdog/settings.ts +48 -104
  218. package/src/watchdog/turn-delta.ts +1 -1
  219. package/src/watchdog/types.ts +18 -32
  220. package/src/watchdog/warning-format.ts +0 -1
  221. package/src/workflows/chat-progress.ts +7 -3
  222. package/src/workflows/host-command.ts +235 -0
  223. package/src/workflows/scripted-workflow.ts +1142 -69
  224. package/src/workflows/workflow-checklist.ts +439 -0
  225. package/src/workflows/workflow-child-summary.ts +121 -0
  226. package/src/workflows/workflow-preflight.ts +297 -0
  227. package/src/workflows/workflow-receipt.ts +232 -6
  228. package/src/workflows/workflow-resources.ts +150 -0
  229. package/src/workflows/workflow-settlement.ts +246 -0
  230. package/src/runs/shared/child-protocol.ts +0 -401
  231. package/src/runs/shared/pi-args.ts +0 -858
  232. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  233. package/src/runs/shared/turn-budget.ts +0 -98
  234. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -1,3 +1,4 @@
1
+ import { spawnSync } from "node:child_process";
1
2
  import { createHash, randomUUID } from "node:crypto";
2
3
  import * as fs from "node:fs";
3
4
  import * as path from "node:path";
@@ -11,6 +12,9 @@ import type { SubagentParamsLike } from "../foreground/subagent-executor.ts";
11
12
  import { validateExecutionAcceptance } from "../shared/acceptance.ts";
12
13
  import type { ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
13
14
  import { previewSimpleWorkflowRun } from "../../workflows/scripted-workflow.ts";
15
+ import { resolveGitRepositoryIdentity } from "../../workflows/chat-progress.ts";
16
+ import { getConfigDirName } from "../../shared/utils.ts";
17
+ import { normalizeWorktreeBaseRef } from "../shared/worktree.ts";
14
18
 
15
19
  export const SCHEDULED_RUN_ACTIONS = [
16
20
  "schedule.create",
@@ -36,7 +40,7 @@ export type ScheduleRunState = "running" | "skipped" | "missed" | "completed" |
36
40
  export type ScheduleTrigger =
37
41
  | { kind: "once"; at: string; nextRunAt?: string }
38
42
  | { kind: "interval"; every: string; everyMs: number; anchorAt: string; nextRunAt: string };
39
- export type ScheduleTarget = { workflowScript: string };
43
+ export type ScheduleTarget = { workflowScript: string; baseRef?: string };
40
44
 
41
45
  export interface ScheduleRecord {
42
46
  schemaVersion: 1;
@@ -49,6 +53,8 @@ export interface ScheduleRecord {
49
53
  catchUp: "none" | "latest";
50
54
  timeoutMs?: number;
51
55
  paused: boolean;
56
+ sessionOnly?: boolean;
57
+ ownerSessionFile?: string;
52
58
  createdAt: string;
53
59
  updatedAt: string;
54
60
  activeRunId?: string;
@@ -69,6 +75,8 @@ export interface ScheduleRunRecord {
69
75
  error?: string;
70
76
  }
71
77
 
78
+ type PublicScheduleRecord = Omit<ScheduleRecord, "ownerSessionFile">;
79
+
72
80
  type ScheduledRunManagerDeps = {
73
81
  config: ExtensionConfig;
74
82
  launch(params: SubagentParamsLike, ctx: ExtensionContext, signal: AbortSignal): Promise<AgentToolResult<Details>>;
@@ -142,11 +150,83 @@ function validateScheduleId(id: string): string {
142
150
  return id;
143
151
  }
144
152
 
153
+ function normalizedComparisonPath(value: string): string {
154
+ const absolute = path.resolve(value);
155
+ if (process.platform !== "win32") return absolute;
156
+ let normalized = absolute;
157
+ try { normalized = fs.realpathSync.native(absolute); } catch {}
158
+ normalized = normalized.replaceAll("/", "\\");
159
+ if (normalized.startsWith("\\\\?\\UNC\\")) normalized = `\\\\${normalized.slice(8)}`;
160
+ else if (normalized.startsWith("\\\\?\\")) normalized = normalized.slice(4);
161
+ normalized = path.win32.normalize(normalized).toLowerCase();
162
+ if (normalized.length > 3) normalized = normalized.replace(/[\\]+$/, "");
163
+ return normalized;
164
+ }
165
+
145
166
  function pathWithin(root: string, candidate: string): boolean {
146
- const relative = path.relative(root, candidate);
167
+ const relative = path.relative(normalizedComparisonPath(root), normalizedComparisonPath(candidate));
147
168
  return relative === "" || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
148
169
  }
149
170
 
171
+ function resolveGitCommonDirForCheckout(checkoutRoot: string): string | undefined {
172
+ const gitPath = path.join(checkoutRoot, ".git");
173
+ try {
174
+ const stat = fs.statSync(gitPath);
175
+ if (stat.isDirectory()) return fs.realpathSync.native(gitPath);
176
+ if (!stat.isFile()) return undefined;
177
+ const match = /^gitdir:[ \t]*([^\r\n]+)$/i.exec(fs.readFileSync(gitPath, "utf-8").trim());
178
+ return match?.[1] ? fs.realpathSync.native(path.resolve(checkoutRoot, match[1])) : undefined;
179
+ } catch {
180
+ return undefined;
181
+ }
182
+ }
183
+
184
+ function samePath(left: string, right: string): boolean {
185
+ return normalizedComparisonPath(left) === normalizedComparisonPath(right);
186
+ }
187
+
188
+ function resolveTrustedGitConfigRoot(checkoutRoot: string, commonDir: string): string | undefined {
189
+ const resolvedCommonDir = resolveGitCommonDirForCheckout(checkoutRoot);
190
+ if (!resolvedCommonDir || !samePath(resolvedCommonDir, commonDir)) return undefined;
191
+ const configRoot = path.join(checkoutRoot, getConfigDirName());
192
+ try {
193
+ const resolved = fs.realpathSync.native(configRoot);
194
+ return fs.statSync(resolved).isDirectory() && pathWithin(checkoutRoot, resolved) ? resolved : undefined;
195
+ } catch {
196
+ return undefined;
197
+ }
198
+ }
199
+
200
+ function registeredGitWorktreeRoots(projectCwd: string): string[] {
201
+ const result = spawnSync("git", ["-C", projectCwd, "worktree", "list", "--porcelain"], { encoding: "utf-8", windowsHide: true });
202
+ if (result.status !== 0 || typeof result.stdout !== "string") return [];
203
+ const roots: string[] = [];
204
+ for (const line of result.stdout.split(/\r?\n/)) {
205
+ if (!line.startsWith("worktree ")) continue;
206
+ try { roots.push(fs.realpathSync.native(line.slice("worktree ".length).trim())); } catch {}
207
+ }
208
+ return roots;
209
+ }
210
+
211
+ function resolveSharedGitConfigRoot(projectCwd: string): string | undefined {
212
+ const repository = resolveGitRepositoryIdentity(projectCwd);
213
+ if (!repository) return undefined;
214
+ let projectConfigRoot: string;
215
+ try {
216
+ projectConfigRoot = fs.realpathSync.native(path.join(projectCwd, getConfigDirName()));
217
+ } catch {
218
+ return undefined;
219
+ }
220
+ // Git may report a separate-git-dir primary checkout as its common git
221
+ // directory, not as the checkout root. Without a registered checkout root,
222
+ // do not infer a shared config path from that unprovable layout.
223
+ for (const checkoutRoot of new Set(registeredGitWorktreeRoots(projectCwd))) {
224
+ const resolved = resolveTrustedGitConfigRoot(checkoutRoot, repository.commonDir);
225
+ if (resolved && samePath(resolved, projectConfigRoot)) return resolved;
226
+ }
227
+ return undefined;
228
+ }
229
+
150
230
  function assertScheduleRoot(root: string, projectCwd: string | undefined, create: boolean): void {
151
231
  if (!projectCwd) {
152
232
  if (create) fs.mkdirSync(root, { recursive: true, mode: 0o700 });
@@ -154,7 +234,7 @@ function assertScheduleRoot(root: string, projectCwd: string | undefined, create
154
234
  }
155
235
  let projectPath: string;
156
236
  try {
157
- projectPath = fs.realpathSync(projectCwd);
237
+ projectPath = fs.realpathSync.native(projectCwd);
158
238
  } catch (error) {
159
239
  if (!create && (error as NodeJS.ErrnoException).code === "ENOENT") return;
160
240
  throw error;
@@ -165,10 +245,14 @@ function assertScheduleRoot(root: string, projectCwd: string | undefined, create
165
245
  if (parent === existing) break;
166
246
  existing = parent;
167
247
  }
168
- if (!pathWithin(projectPath, fs.realpathSync(existing))) throw new Error(`Project schedule root '${root}' resolves outside the real project.`);
248
+ const existingPath = fs.realpathSync.native(existing);
249
+ const sharedGitConfigRoot = pathWithin(projectPath, existingPath) ? undefined : resolveSharedGitConfigRoot(projectCwd);
250
+ const isTrustedPath = (candidate: string): boolean => pathWithin(projectPath, candidate)
251
+ || (sharedGitConfigRoot !== undefined && pathWithin(sharedGitConfigRoot, candidate));
252
+ if (!isTrustedPath(existingPath)) throw new Error(`Project schedule root '${root}' resolves outside the real project.`);
169
253
  if (!create) return;
170
254
  fs.mkdirSync(root, { recursive: true, mode: 0o700 });
171
- if (!pathWithin(projectPath, fs.realpathSync(root))) throw new Error(`Project schedule root '${root}' resolves outside the real project.`);
255
+ if (!isTrustedPath(fs.realpathSync.native(root))) throw new Error(`Project schedule root '${root}' resolves outside the real project.`);
172
256
  }
173
257
 
174
258
  function scheduleDir(root: string, id: string, create = false, projectCwd?: string): string {
@@ -182,9 +266,9 @@ function scheduleDir(root: string, id: string, create = false, projectCwd?: stri
182
266
  if (!create) return dir;
183
267
  fs.mkdirSync(dir, { mode: 0o700 });
184
268
  }
185
- const rootPath = fs.realpathSync(root);
186
- const dirPath = fs.realpathSync(dir);
187
- if (dirPath !== path.join(rootPath, id)) throw new Error(`Schedule path '${dir}' escapes the project schedule root.`);
269
+ const rootPath = fs.realpathSync.native(root);
270
+ const dirPath = fs.realpathSync.native(dir);
271
+ if (!samePath(dirPath, path.join(rootPath, id))) throw new Error(`Schedule path '${dir}' escapes the project schedule root.`);
188
272
  return dir;
189
273
  }
190
274
 
@@ -198,8 +282,15 @@ function readJson(file: string, label: string): unknown {
198
282
 
199
283
  function parseScheduleTarget(value: unknown, file: string): ScheduleTarget {
200
284
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Schedule record '${file}' has invalid trigger or target.`);
201
- const target = value as { workflowScript?: unknown; agent?: unknown; task?: unknown };
202
- if (typeof target.workflowScript === "string" && target.workflowScript.trim()) return { workflowScript: target.workflowScript.trim() };
285
+ const target = value as { workflowScript?: unknown; baseRef?: unknown; agent?: unknown; task?: unknown };
286
+ if (typeof target.workflowScript === "string" && target.workflowScript.trim()) {
287
+ try {
288
+ const baseRef = normalizeWorktreeBaseRef(target.baseRef);
289
+ return { workflowScript: target.workflowScript.trim(), ...(baseRef === undefined ? {} : { baseRef }) };
290
+ } catch (error) {
291
+ throw new Error(`Schedule record '${file}' has an invalid baseRef: ${error instanceof Error ? error.message : String(error)}`);
292
+ }
293
+ }
203
294
  if (target.agent !== undefined || target.task !== undefined) throw new Error(`Schedule record '${file}' uses a removed legacy agent target; recreate it with target.workflowScript.`);
204
295
  throw new Error(`Schedule record '${file}' requires a workflowScript target.`);
205
296
  }
@@ -216,6 +307,8 @@ function parseSchedule(value: unknown, file: string): ScheduleRecord {
216
307
  } else if (record.trigger.kind === "interval") {
217
308
  if (typeof record.trigger.every !== "string" || typeof record.trigger.everyMs !== "number" || typeof record.trigger.anchorAt !== "string" || typeof record.trigger.nextRunAt !== "string") throw new Error(`Schedule record '${file}' has an invalid interval trigger.`);
218
309
  } else throw new Error(`Schedule record '${file}' has an unsupported trigger.`);
310
+ if (record.sessionOnly !== undefined && typeof record.sessionOnly !== "boolean") throw new Error(`Schedule record '${file}' has invalid sessionOnly.`);
311
+ if (record.sessionOnly === true && (typeof record.ownerSessionFile !== "string" || !record.ownerSessionFile.trim())) throw new Error(`Schedule record '${file}' is session-only but has no owner session file.`);
219
312
  return { ...record, target: parseScheduleTarget(record.target, file) } as ScheduleRecord;
220
313
  }
221
314
 
@@ -294,6 +387,10 @@ function resolveMaxPending(config: ExtensionConfig): number {
294
387
  return typeof value === "number" && Number.isInteger(value) && value >= 1 ? value : DEFAULT_MAX_PENDING;
295
388
  }
296
389
 
390
+ function hasPendingScheduleWork(schedule: ScheduleRecord): boolean {
391
+ return schedule.activeRunId !== undefined || schedule.trigger.nextRunAt !== undefined;
392
+ }
393
+
297
394
  function nextAfter(trigger: ScheduleTrigger, plannedAt: number, now: number): string | undefined {
298
395
  if (trigger.kind === "once") return undefined;
299
396
  let next = plannedAt + trigger.everyMs;
@@ -316,13 +413,19 @@ function duePlannedAt(schedule: ScheduleRecord, now: number): number | undefined
316
413
  }
317
414
 
318
415
  function textResult(text: string, schedules?: ScheduleRecord[], runs?: ScheduleRunRecord[], isError = false): AgentToolResult<Details> {
416
+ const publicSchedules = schedules?.map(publicScheduleRecord);
319
417
  return {
320
418
  content: [{ type: "text", text }],
321
419
  ...(isError ? { isError: true } : {}),
322
- details: { mode: "management", results: [], schedules: { ...(schedules ? { records: schedules } : {}), ...(runs ? { runs } : {}) } },
420
+ details: { mode: "management", results: [], schedules: { ...(publicSchedules ? { records: publicSchedules } : {}), ...(runs ? { runs } : {}) } },
323
421
  };
324
422
  }
325
423
 
424
+ function publicScheduleRecord(schedule: ScheduleRecord): PublicScheduleRecord {
425
+ const { ownerSessionFile: _ownerSessionFile, ...rest } = schedule;
426
+ return rest;
427
+ }
428
+
326
429
  function targetLabel(target: ScheduleTarget): string {
327
430
  const preview = previewSimpleWorkflowRun(target.workflowScript);
328
431
  return preview?.agent ? `workflowScript -> agent ${preview.agent}` : "workflowScript (dynamic)";
@@ -334,9 +437,15 @@ function sanitizeTarget(params: SubagentParamsLike): { target?: ScheduleTarget;
334
437
  if (typeof params.workflowScript !== "string" || !params.workflowScript.trim()) return { error: "schedule.create requires a non-empty workflowScript." };
335
438
  if (params.context === "fork") return { error: "Scheduled runs require fresh context." };
336
439
  if (params.async === false) return { error: "Scheduled runs are always async." };
440
+ let baseRef: string | undefined;
441
+ try {
442
+ baseRef = normalizeWorktreeBaseRef(params.baseRef);
443
+ } catch (error) {
444
+ return { error: error instanceof Error ? error.message : String(error) };
445
+ }
337
446
  const acceptanceErrors = validateExecutionAcceptance(params as Parameters<typeof validateExecutionAcceptance>[0]);
338
447
  if (acceptanceErrors.length) return { error: acceptanceErrors.join(" ") };
339
- return { target: { workflowScript: params.workflowScript.trim() } };
448
+ return { target: { workflowScript: params.workflowScript.trim(), ...(baseRef === undefined ? {} : { baseRef }) } };
340
449
  }
341
450
 
342
451
  function executionParams(schedule: ScheduleRecord): SubagentParamsLike {
@@ -367,6 +476,32 @@ function snapshotContext(ctx: ExtensionContext, cwd: string): ExtensionContext {
367
476
  return { ...ctx, cwd, sessionManager };
368
477
  }
369
478
 
479
+ /**
480
+ * 规范化会话文件路径, 兼容 Windows 路径大小写差异.
481
+ *
482
+ * @param value 会话文件路径
483
+ * @returns 规范化后的路径, 空值时返回 undefined
484
+ */
485
+ function normalizedSessionFile(value: string | undefined): string | undefined {
486
+ if (!value || !value.trim()) return undefined;
487
+ const normalized = path.normalize(path.resolve(value));
488
+ return process.platform === "win32" ? normalized.toLowerCase() : normalized;
489
+ }
490
+
491
+ /**
492
+ * 判断 Schedule 是否属于当前 Pi 会话.
493
+ *
494
+ * @param schedule Schedule 记录
495
+ * @param ctx 当前 Pi 会话上下文
496
+ * @returns 是否允许当前会话执行该 Schedule
497
+ */
498
+ function scheduleBelongsToSession(schedule: ScheduleRecord, ctx: ExtensionContext): boolean {
499
+ if (schedule.sessionOnly !== true) return true;
500
+ const ownerSessionFile = normalizedSessionFile(schedule.ownerSessionFile);
501
+ const currentSessionFile = normalizedSessionFile(ctx.sessionManager.getSessionFile());
502
+ return ownerSessionFile !== undefined && ownerSessionFile === currentSessionFile;
503
+ }
504
+
370
505
  export function listScheduledRunSummaries(cwd: string, root?: string): ScheduleRecord[] {
371
506
  return new ScheduleStore(scheduledRunStorePath(cwd, undefined, root), root === undefined ? path.resolve(cwd) : undefined).list();
372
507
  }
@@ -477,9 +612,15 @@ export class ScheduledRunManager {
477
612
  if (params.catchUp !== undefined && params.catchUp !== "none" && params.catchUp !== "latest") return textResult("catchUp must be 'none' or 'latest'.", undefined, undefined, true);
478
613
  if (params.missionId !== undefined || params.mission !== undefined || params.missionUpdate !== undefined || params.missionStatus !== undefined || params.missionScope !== undefined) return textResult("Mission attachment is deferred from this first schedule slice.", undefined, undefined, true);
479
614
  if (params.on !== undefined || params.timezone !== undefined || every === "day" || every === "week" || every === "month" || every === "year") return textResult("Calendar schedules are deferred from this first safe slice. Use a fixed interval such as every:'24h' or every:'7d'.", undefined, undefined, true);
615
+ const sessionOnly = params.sessionOnly === true;
616
+ if (sessionOnly && params.cwd !== undefined && !samePath(params.cwd, ctx.cwd)) return textResult("sessionOnly schedules cannot use an explicit cross-project cwd.", undefined, undefined, true);
617
+ const ownerSessionFile = sessionOnly ? ctx.sessionManager.getSessionFile() : undefined;
618
+ if (sessionOnly && !ownerSessionFile) return textResult("sessionOnly schedules require a persisted current session.", undefined, undefined, true);
480
619
  const sessionId = ctx.sessionManager.getSessionId() ?? "unknown";
481
620
  if (this.deps.resolveCapabilityCeiling?.(sessionId)) return textResult("Cannot persist a schedule while a capability ceiling is active.", undefined, undefined, true);
482
- if (store.list().length >= resolveMaxPending(this.deps.config)) return textResult(`Schedule limit reached (${resolveMaxPending(this.deps.config)}).`, undefined, undefined, true);
621
+ const pendingCount = store.list().filter(hasPendingScheduleWork).length;
622
+ const maxPending = resolveMaxPending(this.deps.config);
623
+ if (pendingCount >= maxPending) return textResult(`Schedule limit reached (${maxPending}).`, undefined, undefined, true);
483
624
  const id = validateScheduleId((params.id?.trim() || this.randomId()));
484
625
  if (store.ids().includes(id)) return textResult(`Schedule '${id}' already exists.`, undefined, undefined, true);
485
626
  const now = this.now();
@@ -502,24 +643,25 @@ export class ScheduledRunManager {
502
643
  catchUp: params.catchUp ?? "latest",
503
644
  ...(params.timeoutMs === undefined ? {} : { timeoutMs: params.timeoutMs }),
504
645
  paused: false,
646
+ ...(sessionOnly ? { sessionOnly: true, ownerSessionFile: path.resolve(ownerSessionFile!) } : {}),
505
647
  createdAt: timestamp(now),
506
648
  updatedAt: timestamp(now),
507
649
  };
508
650
  store.write(schedule);
509
651
  store.appendEvent(schedule, "schedule.created");
510
652
  this.arm(schedule, store);
511
- return textResult(`Created schedule ${id}.\nName: ${schedule.name}\nTrigger: ${at ? `at ${at}` : `every ${every}`}\nNext: ${schedule.trigger.nextRunAt}\nTarget: ${targetLabel(schedule.target)}`, [schedule]);
653
+ return textResult(`Created schedule ${id}.\nName: ${schedule.name}\nTrigger: ${at ? `at ${at}` : `every ${every}`}\nSession only: ${schedule.sessionOnly === true ? "yes" : "no"}\nNext: ${schedule.trigger.nextRunAt}\nTarget: ${targetLabel(schedule.target)}`, [schedule]);
512
654
  }
513
655
 
514
656
  private list(): AgentToolResult<Details> {
515
657
  const schedules = this.requireStore().list().sort((a, b) => (a.trigger.nextRunAt ?? "").localeCompare(b.trigger.nextRunAt ?? ""));
516
658
  if (!schedules.length) return textResult("No project schedules.", []);
517
- return textResult([`Project schedules: ${schedules.length}`, ...schedules.map((item) => `- ${item.id} | ${item.paused ? "paused" : item.activeRunId ? "running" : "scheduled"} | ${item.trigger.nextRunAt ?? "no next run"} | ${item.name}`)].join("\n"), schedules);
659
+ return textResult([`Project schedules: ${schedules.length}`, ...schedules.map((item) => `- ${item.id} | ${item.paused ? "paused" : item.activeRunId ? "running" : "scheduled"} | ${item.trigger.nextRunAt ?? "no next run"} | ${item.sessionOnly === true ? "session-only" : "project"} | ${item.name}`)].join("\n"), schedules);
518
660
  }
519
661
 
520
662
  private show(params: SubagentParamsLike): AgentToolResult<Details> {
521
663
  const schedule = this.resolve(params);
522
- return textResult([`Schedule: ${schedule.id}`, `Name: ${schedule.name}`, `State: ${schedule.paused ? "paused" : schedule.activeRunId ? "running" : "scheduled"}`, `Target: ${targetLabel(schedule.target)}`, `CWD: ${shortenPath(schedule.cwd)}`, `Next: ${schedule.trigger.nextRunAt ?? "none"}`, `Catch up: ${schedule.catchUp}`, schedule.activeRunId ? `Active run: ${schedule.activeRunId}` : undefined].filter(Boolean).join("\n"), [schedule]);
664
+ return textResult([`Schedule: ${schedule.id}`, `Name: ${schedule.name}`, `State: ${schedule.paused ? "paused" : schedule.activeRunId ? "running" : "scheduled"}`, `Session only: ${schedule.sessionOnly === true ? "yes" : "no"}`, `Target: ${targetLabel(schedule.target)}`, `CWD: ${shortenPath(schedule.cwd)}`, `Next: ${schedule.trigger.nextRunAt ?? "none"}`, `Catch up: ${schedule.catchUp}`, schedule.activeRunId ? `Active run: ${schedule.activeRunId}` : undefined].filter(Boolean).join("\n"), [schedule]);
523
665
  }
524
666
 
525
667
  private history(params: SubagentParamsLike): AgentToolResult<Details> {
@@ -543,13 +685,18 @@ export class ScheduledRunManager {
543
685
  private async runManual(params: SubagentParamsLike): Promise<AgentToolResult<Details>> {
544
686
  const store = this.requireStore();
545
687
  const schedule = this.resolve(params);
688
+ const context = this.requireContext(store);
689
+ if (!scheduleBelongsToSession(schedule, context)) {
690
+ return textResult(`Skipped schedule ${schedule.id}: current session is not its owner.`, [schedule]);
691
+ }
546
692
  const run = await this.launch(store, schedule, this.now(), "manual", false);
547
693
  return textResult(`Manual schedule run ${run.id}: ${run.state}${run.asyncId ? ` (async ${run.asyncId})` : ""}.`, [store.get(schedule.id)], [run], run.state === "failed_launch");
548
694
  }
549
695
 
550
696
  private async runDue(): Promise<AgentToolResult<Details>> {
551
697
  const store = this.requireStore();
552
- const due = store.list().filter((schedule) => !schedule.paused && nextRunAt(schedule) !== undefined && nextRunAt(schedule)! <= this.now());
698
+ const context = this.requireContext(store);
699
+ const due = store.list().filter((schedule) => scheduleBelongsToSession(schedule, context) && !schedule.paused && nextRunAt(schedule) !== undefined && nextRunAt(schedule)! <= this.now());
553
700
  const runs: ScheduleRunRecord[] = [];
554
701
  for (const schedule of due) {
555
702
  const planned = duePlannedAt(schedule, this.now())!;
@@ -574,6 +721,7 @@ export class ScheduledRunManager {
574
721
  }
575
722
 
576
723
  private restoreOne(store: ScheduleStore, schedule: ScheduleRecord, notBefore?: number, rearm = true): void {
724
+ if (!scheduleBelongsToSession(schedule, this.requireContext(store))) return;
577
725
  if (schedule.activeRunId) {
578
726
  const run = store.history(schedule.id).find((item) => item.id === schedule.activeRunId);
579
727
  if (run?.state === "running" && run.asyncId) this.observedAsyncIds.add(run.asyncId);
@@ -652,6 +800,7 @@ export class ScheduledRunManager {
652
800
  // is then nothing to run and nothing to re-arm.
653
801
  const schedule = store.find(id);
654
802
  if (!schedule) return;
803
+ if (!scheduleBelongsToSession(schedule, this.requireContext(store))) return;
655
804
  const planned = duePlannedAt(schedule, this.now());
656
805
  if (planned === undefined || schedule.paused) return;
657
806
  if (planned > this.now()) return this.arm(schedule, store);
@@ -772,13 +921,20 @@ export class ScheduledRunManager {
772
921
  private selectProject(cwd: string, ctx: ExtensionContext): void {
773
922
  const projectCwd = path.resolve(cwd);
774
923
  const root = scheduledRunStorePath(projectCwd, undefined, this.deps.storeRoot);
775
- if (path.resolve(ctx.cwd) === projectCwd) this.contexts.set(root, snapshotContext(ctx, projectCwd));
924
+ const isBoundContext = path.resolve(ctx.cwd) === projectCwd;
925
+ const previousContext = this.contexts.get(root);
926
+ const contextChanged = isBoundContext
927
+ && previousContext !== undefined
928
+ && normalizedSessionFile(previousContext.sessionManager.getSessionFile()) !== normalizedSessionFile(ctx.sessionManager.getSessionFile());
929
+ if (isBoundContext) this.contexts.set(root, snapshotContext(ctx, projectCwd));
776
930
  else if (!this.contexts.has(root)) throw new Error(`Cannot use project '${projectCwd}' until that project has been opened in this runtime.`);
777
931
  let store = this.stores.get(root);
778
932
  if (!store) {
779
933
  store = new ScheduleStore(root, this.deps.storeRoot === undefined ? projectCwd : undefined);
780
934
  this.stores.set(root, store);
781
935
  this.restore(store);
936
+ } else if (contextChanged) {
937
+ this.restore(store);
782
938
  }
783
939
  this.store = store;
784
940
  }
@@ -8,6 +8,7 @@ import { DIRS, type AsyncParallelGroupStatus, type AsyncStatus, type NestedRunSu
8
8
  import { resolveEffectiveThinking } from "../../shared/model-info.ts";
9
9
  import { normalizeParallelGroups } from "./parallel-groups.ts";
10
10
  import { nestedSummaryFromAsyncStatus, projectNestedEvents, resolveNestedAsyncDir, writeNestedEvent, type NestedRoute } from "../shared/nested-events.ts";
11
+ import { assertWorkflowGraphHostSteps } from "../shared/host-step-status.ts";
11
12
 
12
13
  export type PidLiveness = "alive" | "dead" | "unknown";
13
14
 
@@ -24,6 +25,7 @@ interface StartedRunMetadata {
24
25
  parallelGroups?: AsyncParallelGroupStatus[];
25
26
  startedAt?: number;
26
27
  sessionFile?: string;
28
+ sessionName?: string;
27
29
  }
28
30
 
29
31
  interface ReconcileAsyncRunOptions {
@@ -90,6 +92,7 @@ function appendJsonlBestEffort(filePath: string, payload: object): void {
90
92
 
91
93
  interface ResultChildOutcome {
92
94
  agent?: string;
95
+ sessionName?: string;
93
96
  success?: boolean;
94
97
  error?: string;
95
98
  sessionFile?: string;
@@ -97,10 +100,11 @@ interface ResultChildOutcome {
97
100
  thinking?: string;
98
101
  attemptedModels?: string[];
99
102
  modelAttempts?: NonNullable<AsyncStatus["steps"]>[number]["modelAttempts"];
103
+ contextOverflow?: boolean;
100
104
  }
101
105
 
102
106
  interface ResultRepairData {
103
- state: "complete" | "failed" | "paused" | "stopped" | "rejected";
107
+ state: "complete" | "failed" | "partial" | "paused" | "stopped" | "rejected";
104
108
  results?: ResultChildOutcome[];
105
109
  }
106
110
 
@@ -116,7 +120,7 @@ function regularFileExists(filePath: string): boolean {
116
120
  function readResultRepairData(resultPath: string): ResultRepairData | undefined {
117
121
  try {
118
122
  const data = JSON.parse(fs.readFileSync(resultPath, "utf-8")) as { success?: boolean; state?: string; exitCode?: number; results?: unknown };
119
- const state = data.success ? "complete" : data.state === "stopped" ? "stopped" : data.state === "rejected" ? "rejected" : data.state === "paused" || data.exitCode === 0 ? "paused" : "failed";
123
+ const state = data.success ? "complete" : data.state === "stopped" ? "stopped" : data.state === "rejected" ? "rejected" : data.state === "partial" ? "partial" : data.state === "paused" || data.exitCode === 0 ? "paused" : "failed";
120
124
  const results = Array.isArray(data.results)
121
125
  ? data.results.map((entry, index) => {
122
126
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) return {};
@@ -156,13 +160,15 @@ function terminalStatusFromResult(status: AsyncStatus, resultPath: string, now:
156
160
  endedAt: step.endedAt ?? now,
157
161
  durationMs: step.startedAt !== undefined && step.durationMs === undefined ? Math.max(0, now - step.startedAt) : step.durationMs,
158
162
  exitCode: step.exitCode ?? (state === "complete" || state === "paused" ? 0 : 1),
159
- error: state === "failed" || state === "stopped" ? step.error ?? child?.error : step.error,
163
+ error: state === "failed" || state === "partial" || state === "stopped" ? step.error ?? child?.error : step.error,
160
164
  stopped: state === "stopped" ? true : step.stopped,
165
+ sessionName: step.sessionName ?? child?.sessionName,
161
166
  sessionFile: step.sessionFile ?? child?.sessionFile,
162
167
  model,
163
168
  thinking,
164
169
  attemptedModels: child?.attemptedModels ?? step.attemptedModels,
165
170
  modelAttempts: child?.modelAttempts ?? step.modelAttempts,
171
+ contextOverflow: child?.contextOverflow ?? step.contextOverflow,
166
172
  };
167
173
  });
168
174
  const terminalStatus: AsyncStatus = {
@@ -252,12 +258,14 @@ function buildFailedRepair(status: AsyncStatus, asyncDir: string, now: number, r
252
258
  summary: message,
253
259
  results: repairedSteps.map((step) => ({
254
260
  agent: step.agent,
261
+ ...(step.sessionName ? { sessionName: step.sessionName } : {}),
255
262
  output: step.status === "complete" || step.status === "completed" ? "" : message,
256
263
  error: step.status === "complete" || step.status === "completed" ? undefined : step.error ?? message,
257
264
  success: step.status === "complete" || step.status === "completed",
258
265
  model: step.model,
259
266
  attemptedModels: step.attemptedModels,
260
267
  modelAttempts: step.modelAttempts,
268
+ contextOverflow: step.contextOverflow,
261
269
  sessionFile: step.sessionFile,
262
270
  })),
263
271
  exitCode: 1,
@@ -287,7 +295,7 @@ function writeFailedRepair(asyncDir: string, status: AsyncStatus, resultPath: st
287
295
  }
288
296
 
289
297
  function terminal(state: AsyncStatus["state"]): boolean {
290
- return state === "complete" || state === "failed" || state === "paused" || state === "stopped" || state === "rejected";
298
+ return state === "complete" || state === "failed" || state === "partial" || state === "paused" || state === "stopped" || state === "rejected";
291
299
  }
292
300
 
293
301
  function* nestedRuns(children: NestedRunSummary[] | undefined): Generator<NestedRunSummary> {
@@ -350,6 +358,7 @@ export function reconcileAsyncRun(asyncDir: string, options: ReconcileAsyncRunOp
350
358
  const startedStatus = !status && options.startedRun ? buildStartedStatus(asyncDir, options.startedRun, now) : undefined;
351
359
  const effectiveStatus = status ?? startedStatus;
352
360
  if (!effectiveStatus) return { status: null, repaired: false };
361
+ assertWorkflowGraphHostSteps(effectiveStatus.workflowGraph, path.join(asyncDir, "status.json"), effectiveStatus.runId);
353
362
  const statusPath = path.join(asyncDir, "status.json");
354
363
  for (const [index, step] of (effectiveStatus.steps ?? []).entries()) {
355
364
  const stepRecord = step as Record<string, unknown>;
@@ -4,7 +4,6 @@ import { writePrivateAtomicJson } from "../../shared/atomic-json.ts";
4
4
  import type {
5
5
  AsyncStatus,
6
6
  ResolvedToolBudget,
7
- ResolvedTurnBudget,
8
7
  SteerActionResult,
9
8
  SteeringRecoveryDescriptor,
10
9
  SteeringRequestStatus,
@@ -24,7 +23,10 @@ export function steeringMessagePreview(message: string): string {
24
23
  }
25
24
 
26
25
  export function steeringReceipt(message: string, receipt: string): string {
27
- return `${receipt} Message: ${JSON.stringify(steeringMessagePreview(message))}`;
26
+ const preview = steeringMessagePreview(message);
27
+ const longestFence = Math.max(2, ...[...preview.matchAll(/`{3,}/g)].map((match) => match[0]!.length));
28
+ const fence = "`".repeat(longestFence + 1);
29
+ return `${receipt}\n\nMessage sent:\n${fence}text\n${preview}\n${fence}`;
28
30
  }
29
31
 
30
32
  export function createSteeringStatus(): SteeringStatus {
@@ -195,26 +197,17 @@ export function readSteeringStatus(asyncDir: string): SteeringStatus | undefined
195
197
  }
196
198
 
197
199
  export function remainingSteeringRecoveryLimits(
198
- descriptor: Pick<SteeringRecoveryDescriptor, "absoluteDeadlineAt" | "initialTurnBudget" | "initialToolBudget">,
199
- status: Pick<AsyncStatus, "turnBudget" | "turnCount" | "toolBudget" | "toolCount">,
200
+ descriptor: Pick<SteeringRecoveryDescriptor, "absoluteDeadlineAt" | "initialToolBudget">,
201
+ status: Pick<AsyncStatus, "toolBudget" | "toolCount">,
200
202
  now = Date.now(),
201
- ): { timeoutMs?: number; absoluteDeadlineAt?: number; turnBudget?: ResolvedTurnBudget; toolBudget?: ResolvedToolBudget } {
202
- const limits: { timeoutMs?: number; absoluteDeadlineAt?: number; turnBudget?: ResolvedTurnBudget; toolBudget?: ResolvedToolBudget } = {};
203
+ ): { timeoutMs?: number; absoluteDeadlineAt?: number; toolBudget?: ResolvedToolBudget } {
204
+ const limits: { timeoutMs?: number; absoluteDeadlineAt?: number; toolBudget?: ResolvedToolBudget } = {};
203
205
  if (descriptor.absoluteDeadlineAt !== undefined) {
204
206
  const timeoutMs = descriptor.absoluteDeadlineAt - now;
205
207
  if (timeoutMs <= 0) throw new Error("Source run has no remaining deadline budget; it remains paused.");
206
208
  limits.timeoutMs = timeoutMs;
207
209
  limits.absoluteDeadlineAt = descriptor.absoluteDeadlineAt;
208
210
  }
209
- if (descriptor.initialTurnBudget) {
210
- const consumed = status.turnBudget?.turnCount ?? status.turnCount ?? 0;
211
- const totalRemaining = descriptor.initialTurnBudget.maxTurns + descriptor.initialTurnBudget.graceTurns - consumed;
212
- if (totalRemaining <= 0) throw new Error("Source run has no remaining turn budget; it remains paused.");
213
- const softRemaining = Math.max(0, descriptor.initialTurnBudget.maxTurns - consumed);
214
- limits.turnBudget = softRemaining > 0
215
- ? { maxTurns: softRemaining, graceTurns: totalRemaining - softRemaining }
216
- : { maxTurns: 1, graceTurns: totalRemaining - 1 };
217
- }
218
211
  if (descriptor.initialToolBudget) {
219
212
  const consumed = status.toolBudget?.toolCount ?? status.toolCount ?? 0;
220
213
  const hard = descriptor.initialToolBudget.hard - consumed;