@xzzpig/pi-subagents 0.8.0 → 0.10.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 (221) hide show
  1. package/CHANGELOG.md +477 -0
  2. package/README.md +2 -2
  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 +1 -1
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +195 -39
  12. package/docs/configuration.md +81 -22
  13. package/docs/extension-api.md +69 -14
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +32 -9
  16. package/docs/observability.md +22 -20
  17. package/docs/tool-reference.md +123 -14
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +142 -4
  20. package/install.mjs +1 -1
  21. package/package.json +7 -6
  22. package/prompts/review-loop.md +2 -2
  23. package/skills/council-mode/SKILL.md +48 -243
  24. package/skills/council-mode/references/pass-contracts.md +150 -0
  25. package/skills/pi-subagents/SKILL.md +89 -35
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
  27. package/skills/pi-subagents/references/execution-controls.md +91 -15
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
  31. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  32. package/src/agents/agent-management.ts +384 -115
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +14 -2
  35. package/src/agents/agents.ts +935 -372
  36. package/src/agents/builtin-names.ts +6 -0
  37. package/src/agents/runtime-agent-events.ts +70 -0
  38. package/src/agents/runtime-agent-registry.ts +42 -21
  39. package/src/api/agents.ts +10 -5
  40. package/src/api/background-work.ts +12 -3
  41. package/src/api/capability-ceiling.ts +0 -1
  42. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  43. package/src/api/delegation.ts +0 -7
  44. package/src/api/external-runs.ts +67 -4
  45. package/src/api/preflight.ts +77 -21
  46. package/src/api/shared-types.ts +6 -0
  47. package/src/extension/config.ts +90 -0
  48. package/src/extension/doctor.ts +5 -13
  49. package/src/extension/fanout-child.ts +14 -14
  50. package/src/extension/index.ts +115 -37
  51. package/src/extension/public-execution.ts +103 -15
  52. package/src/extension/rpc.ts +120 -25
  53. package/src/extension/schemas.ts +65 -29
  54. package/src/extension/tool-description.ts +48 -26
  55. package/src/inspectors/herdr/actions.ts +2 -1
  56. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  57. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  58. package/src/integrations/herdr-status.ts +51 -3
  59. package/src/intercom/native-supervisor-channel.ts +138 -60
  60. package/src/intercom/result-intercom.ts +7 -0
  61. package/src/intercom/supervisor-ui.ts +243 -0
  62. package/src/profiles/profiles.ts +5 -6
  63. package/src/runs/background/active-async-capacity.ts +103 -18
  64. package/src/runs/background/async-execution.ts +417 -133
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +60 -28
  67. package/src/runs/background/async-retention.ts +20 -3
  68. package/src/runs/background/async-status-snapshot.ts +23 -261
  69. package/src/runs/background/async-status.ts +204 -14
  70. package/src/runs/background/auto-drain.ts +1 -1
  71. package/src/runs/background/chain-append.ts +8 -3
  72. package/src/runs/background/chain-root-attachment.ts +74 -8
  73. package/src/runs/background/control-channel.ts +4 -205
  74. package/src/runs/background/fleet-view.ts +38 -22
  75. package/src/runs/background/inspect-rpc.ts +8 -8
  76. package/src/runs/background/notify.ts +238 -12
  77. package/src/runs/background/process-terminal.ts +16 -0
  78. package/src/runs/background/result-delivery-ownership.ts +45 -0
  79. package/src/runs/background/result-files.ts +28 -14
  80. package/src/runs/background/result-watcher.ts +39 -16
  81. package/src/runs/background/resume-guidance.ts +2 -2
  82. package/src/runs/background/retained-children.ts +1 -1
  83. package/src/runs/background/run-child-session.ts +613 -0
  84. package/src/runs/background/run-status.ts +84 -17
  85. package/src/runs/background/runner-aliases.ts +125 -0
  86. package/src/runs/background/runner-child-sessions.ts +31 -0
  87. package/src/runs/background/scheduled-runs.ts +174 -18
  88. package/src/runs/background/stale-run-reconciler.ts +10 -4
  89. package/src/runs/background/steering.ts +8 -15
  90. package/src/runs/background/subagent-runner.ts +718 -1161
  91. package/src/runs/background/subagent-wait.ts +86 -31
  92. package/src/runs/background/terminal-run-index.ts +1 -1
  93. package/src/runs/background/wait-completions.ts +43 -2
  94. package/src/runs/background/wait-config.ts +23 -9
  95. package/src/runs/background/wait-tool.ts +26 -19
  96. package/src/runs/foreground/async-steering-action.ts +3 -19
  97. package/src/runs/foreground/execution.ts +489 -499
  98. package/src/runs/foreground/foreground-control.ts +13 -0
  99. package/src/runs/foreground/foreground-history.ts +23 -1
  100. package/src/runs/foreground/subagent-executor.ts +1223 -402
  101. package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
  102. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  103. package/src/runs/shared/abort-recovery.ts +119 -0
  104. package/src/runs/shared/acceptance.ts +138 -36
  105. package/src/runs/shared/async-status-projection.ts +565 -0
  106. package/src/runs/shared/background-process-options.ts +9 -0
  107. package/src/runs/shared/capability-ceiling.ts +2 -2
  108. package/src/runs/shared/child-hooks.ts +25 -0
  109. package/src/runs/shared/child-identity.ts +32 -6
  110. package/src/runs/shared/child-launch-plan.ts +151 -0
  111. package/src/runs/shared/child-launch.ts +364 -0
  112. package/src/runs/shared/child-lifecycle.ts +25 -0
  113. package/src/runs/shared/child-runtime-config.ts +126 -0
  114. package/src/runs/shared/child-session.ts +366 -0
  115. package/src/runs/shared/child-tool-plan.ts +632 -0
  116. package/src/runs/shared/claude-code-adapter.ts +133 -0
  117. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  118. package/src/runs/shared/completion-evidence.ts +89 -0
  119. package/src/runs/shared/completion-guard.ts +6 -5
  120. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  121. package/src/runs/shared/dynamic-fanout.ts +3 -3
  122. package/src/runs/shared/external-cli-contract.ts +167 -0
  123. package/src/runs/shared/external-cli-preflight.ts +138 -0
  124. package/src/runs/shared/external-cli-runner.ts +348 -55
  125. package/src/runs/shared/fast-mode-extension.ts +5 -5
  126. package/src/runs/shared/host-step-status.ts +231 -0
  127. package/src/runs/shared/lane-metadata.ts +126 -0
  128. package/src/runs/shared/launch-cwd.ts +16 -0
  129. package/src/runs/shared/long-running-guard.ts +2 -1
  130. package/src/runs/shared/mcp-config-sources.ts +422 -0
  131. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  132. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  133. package/src/runs/shared/model-exclusions.ts +139 -9
  134. package/src/runs/shared/model-fallback.ts +146 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +99 -77
  137. package/src/runs/shared/nested-path.ts +0 -14
  138. package/src/runs/shared/nested-render.ts +9 -5
  139. package/src/runs/shared/orca-progress-tabs.ts +12 -7
  140. package/src/runs/shared/parallel-handoff.ts +423 -7
  141. package/src/runs/shared/parallel-utils.ts +20 -7
  142. package/src/runs/shared/permissions.ts +1 -14
  143. package/src/runs/shared/pi-spawn.ts +69 -35
  144. package/src/runs/shared/process-signal.ts +16 -0
  145. package/src/runs/shared/run-fanout-budget.ts +0 -13
  146. package/src/runs/shared/run-history.ts +21 -1
  147. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  148. package/src/runs/shared/sandbox-profile-guard.ts +85 -0
  149. package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
  150. package/src/runs/shared/single-output.ts +89 -22
  151. package/src/runs/shared/structured-output.ts +49 -9
  152. package/src/runs/shared/subagent-control.ts +6 -2
  153. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  154. package/src/runs/shared/task-intent.ts +21 -7
  155. package/src/runs/shared/tool-availability.ts +18 -62
  156. package/src/runs/shared/tool-budget.ts +0 -14
  157. package/src/runs/shared/tool-timeout.ts +1 -1
  158. package/src/runs/shared/workflow-graph.ts +16 -0
  159. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  160. package/src/runs/shared/worktree.ts +571 -62
  161. package/src/shared/atomic-json.ts +3 -1
  162. package/src/shared/child-session-name.ts +46 -0
  163. package/src/shared/extension-context.ts +24 -0
  164. package/src/shared/fork-context.ts +21 -12
  165. package/src/shared/fork-session-cwd.ts +27 -0
  166. package/src/shared/formatters.ts +18 -3
  167. package/src/shared/jsonl-writer.ts +11 -0
  168. package/src/shared/launch-contract.ts +11 -1
  169. package/src/shared/pruned-fork.ts +450 -0
  170. package/src/shared/sandbox-profile.ts +23 -0
  171. package/src/shared/session-file-trust.ts +19 -0
  172. package/src/shared/session-tokens.ts +14 -3
  173. package/src/shared/settings.ts +19 -105
  174. package/src/shared/shortcuts.ts +17 -0
  175. package/src/shared/thinking-ceiling.ts +0 -6
  176. package/src/shared/types.ts +545 -70
  177. package/src/shared/utils.ts +60 -93
  178. package/src/shared/workflow-child-permit.ts +207 -0
  179. package/src/slash/delegation-adapters.ts +1 -9
  180. package/src/slash/delegation-request.ts +0 -4
  181. package/src/slash/prompt-template-bridge.ts +37 -1
  182. package/src/slash/slash-bridge.ts +1 -2
  183. package/src/slash/slash-commands.ts +383 -116
  184. package/src/slash/slash-live-state.ts +22 -11
  185. package/src/slash/subagents-admin.ts +29 -12
  186. package/src/tui/fleet-native-transcript.ts +4 -0
  187. package/src/tui/fleet-status.ts +217 -82
  188. package/src/tui/fleet-transcript.ts +11 -5
  189. package/src/tui/fleet.ts +54 -28
  190. package/src/tui/render-helpers.ts +31 -0
  191. package/src/tui/render.ts +1429 -163
  192. package/src/watchdog/change-signature.ts +40 -1
  193. package/src/watchdog/child-status.ts +54 -34
  194. package/src/watchdog/diff-tool.ts +77 -0
  195. package/src/watchdog/emission-guard.ts +5 -3
  196. package/src/watchdog/guidance.ts +20 -0
  197. package/src/watchdog/register-child.ts +28 -25
  198. package/src/watchdog/register-main.ts +10 -9
  199. package/src/watchdog/render.ts +4 -5
  200. package/src/watchdog/review.ts +15 -4
  201. package/src/watchdog/rules.ts +70 -0
  202. package/src/watchdog/runtime.ts +75 -92
  203. package/src/watchdog/scope.ts +0 -11
  204. package/src/watchdog/settings.ts +48 -104
  205. package/src/watchdog/turn-delta.ts +1 -1
  206. package/src/watchdog/types.ts +18 -32
  207. package/src/watchdog/warning-format.ts +0 -1
  208. package/src/workflows/chat-progress.ts +7 -3
  209. package/src/workflows/host-command.ts +235 -0
  210. package/src/workflows/scripted-workflow.ts +988 -59
  211. package/src/workflows/workflow-checklist.ts +439 -0
  212. package/src/workflows/workflow-child-summary.ts +121 -0
  213. package/src/workflows/workflow-preflight.ts +297 -0
  214. package/src/workflows/workflow-receipt.ts +232 -6
  215. package/src/workflows/workflow-resources.ts +150 -0
  216. package/src/workflows/workflow-settlement.ts +246 -0
  217. package/src/runs/shared/child-protocol.ts +0 -401
  218. package/src/runs/shared/pi-args.ts +0 -935
  219. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  220. package/src/runs/shared/turn-budget.ts +0 -98
  221. 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;
@@ -101,7 +104,7 @@ interface ResultChildOutcome {
101
104
  }
102
105
 
103
106
  interface ResultRepairData {
104
- state: "complete" | "failed" | "paused" | "stopped" | "rejected";
107
+ state: "complete" | "failed" | "partial" | "paused" | "stopped" | "rejected";
105
108
  results?: ResultChildOutcome[];
106
109
  }
107
110
 
@@ -117,7 +120,7 @@ function regularFileExists(filePath: string): boolean {
117
120
  function readResultRepairData(resultPath: string): ResultRepairData | undefined {
118
121
  try {
119
122
  const data = JSON.parse(fs.readFileSync(resultPath, "utf-8")) as { success?: boolean; state?: string; exitCode?: number; results?: unknown };
120
- 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";
121
124
  const results = Array.isArray(data.results)
122
125
  ? data.results.map((entry, index) => {
123
126
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) return {};
@@ -157,8 +160,9 @@ function terminalStatusFromResult(status: AsyncStatus, resultPath: string, now:
157
160
  endedAt: step.endedAt ?? now,
158
161
  durationMs: step.startedAt !== undefined && step.durationMs === undefined ? Math.max(0, now - step.startedAt) : step.durationMs,
159
162
  exitCode: step.exitCode ?? (state === "complete" || state === "paused" ? 0 : 1),
160
- 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,
161
164
  stopped: state === "stopped" ? true : step.stopped,
165
+ sessionName: step.sessionName ?? child?.sessionName,
162
166
  sessionFile: step.sessionFile ?? child?.sessionFile,
163
167
  model,
164
168
  thinking,
@@ -254,6 +258,7 @@ function buildFailedRepair(status: AsyncStatus, asyncDir: string, now: number, r
254
258
  summary: message,
255
259
  results: repairedSteps.map((step) => ({
256
260
  agent: step.agent,
261
+ ...(step.sessionName ? { sessionName: step.sessionName } : {}),
257
262
  output: step.status === "complete" || step.status === "completed" ? "" : message,
258
263
  error: step.status === "complete" || step.status === "completed" ? undefined : step.error ?? message,
259
264
  success: step.status === "complete" || step.status === "completed",
@@ -290,7 +295,7 @@ function writeFailedRepair(asyncDir: string, status: AsyncStatus, resultPath: st
290
295
  }
291
296
 
292
297
  function terminal(state: AsyncStatus["state"]): boolean {
293
- 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";
294
299
  }
295
300
 
296
301
  function* nestedRuns(children: NestedRunSummary[] | undefined): Generator<NestedRunSummary> {
@@ -353,6 +358,7 @@ export function reconcileAsyncRun(asyncDir: string, options: ReconcileAsyncRunOp
353
358
  const startedStatus = !status && options.startedRun ? buildStartedStatus(asyncDir, options.startedRun, now) : undefined;
354
359
  const effectiveStatus = status ?? startedStatus;
355
360
  if (!effectiveStatus) return { status: null, repaired: false };
361
+ assertWorkflowGraphHostSteps(effectiveStatus.workflowGraph, path.join(asyncDir, "status.json"), effectiveStatus.runId);
356
362
  const statusPath = path.join(asyncDir, "status.json");
357
363
  for (const [index, step] of (effectiveStatus.steps ?? []).entries()) {
358
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;