@xzzpig/pi-subagents 0.8.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.
- package/CHANGELOG.md +443 -0
- package/README.md +2 -2
- package/agents/claude-code-writer.md +15 -0
- package/agents/claude-code.md +15 -0
- package/agents/codex-exec-writer.md +15 -0
- package/agents/codex-exec.md +15 -0
- package/agents/cursor-agent-writer.md +14 -0
- package/agents/cursor-agent.md +14 -0
- package/agents/reviewer.md +1 -1
- package/agents/scout.md +1 -1
- package/docs/agents.md +151 -39
- package/docs/configuration.md +81 -22
- package/docs/extension-api.md +69 -14
- package/docs/missions.md +2 -0
- package/docs/models.md +32 -9
- package/docs/observability.md +22 -20
- package/docs/tool-reference.md +123 -14
- package/docs/watchdog.md +92 -114
- package/docs/workflows.md +142 -4
- package/install.mjs +1 -1
- package/package.json +5 -4
- package/prompts/review-loop.md +2 -2
- package/skills/council-mode/SKILL.md +48 -243
- package/skills/council-mode/references/pass-contracts.md +150 -0
- package/skills/pi-subagents/SKILL.md +89 -35
- package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
- package/skills/pi-subagents/references/execution-controls.md +91 -15
- package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
- package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
- package/skills/pi-subagents/references/review-and-validation.md +73 -0
- package/src/agents/agent-management.ts +370 -114
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agent-serializer.ts +12 -2
- package/src/agents/agents.ts +919 -372
- package/src/agents/builtin-names.ts +6 -0
- package/src/agents/runtime-agent-events.ts +70 -0
- package/src/agents/runtime-agent-registry.ts +31 -20
- package/src/api/agents.ts +10 -5
- package/src/api/background-work.ts +12 -3
- package/src/api/capability-ceiling.ts +0 -1
- package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
- package/src/api/delegation.ts +0 -7
- package/src/api/external-runs.ts +67 -4
- package/src/api/preflight.ts +48 -18
- package/src/api/shared-types.ts +6 -0
- package/src/extension/config.ts +90 -0
- package/src/extension/doctor.ts +5 -13
- package/src/extension/fanout-child.ts +14 -14
- package/src/extension/index.ts +115 -37
- package/src/extension/public-execution.ts +103 -15
- package/src/extension/rpc.ts +120 -25
- package/src/extension/schemas.ts +57 -21
- package/src/extension/tool-description.ts +48 -26
- package/src/inspectors/herdr/actions.ts +2 -1
- package/src/inspectors/herdr/inspector-runner.ts +21 -23
- package/src/inspectors/herdr/session-roots-codec.ts +42 -0
- package/src/integrations/herdr-status.ts +51 -3
- package/src/intercom/native-supervisor-channel.ts +138 -60
- package/src/intercom/result-intercom.ts +2 -0
- package/src/intercom/supervisor-ui.ts +243 -0
- package/src/profiles/profiles.ts +5 -6
- package/src/runs/background/active-async-capacity.ts +103 -18
- package/src/runs/background/async-execution.ts +366 -128
- package/src/runs/background/async-job-tracker.ts +95 -15
- package/src/runs/background/async-resume.ts +45 -28
- package/src/runs/background/async-retention.ts +20 -3
- package/src/runs/background/async-status-snapshot.ts +23 -261
- package/src/runs/background/async-status.ts +189 -14
- package/src/runs/background/auto-drain.ts +1 -1
- package/src/runs/background/chain-append.ts +8 -3
- package/src/runs/background/chain-root-attachment.ts +74 -8
- package/src/runs/background/control-channel.ts +4 -205
- package/src/runs/background/fleet-view.ts +38 -22
- package/src/runs/background/inspect-rpc.ts +8 -8
- package/src/runs/background/notify.ts +238 -12
- package/src/runs/background/process-terminal.ts +16 -0
- package/src/runs/background/result-delivery-ownership.ts +45 -0
- package/src/runs/background/result-files.ts +28 -14
- package/src/runs/background/result-watcher.ts +39 -16
- package/src/runs/background/resume-guidance.ts +2 -2
- package/src/runs/background/retained-children.ts +1 -1
- package/src/runs/background/run-child-session.ts +613 -0
- package/src/runs/background/run-status.ts +84 -17
- package/src/runs/background/runner-aliases.ts +125 -0
- package/src/runs/background/runner-child-sessions.ts +31 -0
- package/src/runs/background/scheduled-runs.ts +174 -18
- package/src/runs/background/stale-run-reconciler.ts +10 -4
- package/src/runs/background/steering.ts +8 -15
- package/src/runs/background/subagent-runner.ts +676 -1161
- package/src/runs/background/subagent-wait.ts +86 -31
- package/src/runs/background/terminal-run-index.ts +1 -1
- package/src/runs/background/wait-completions.ts +43 -2
- package/src/runs/background/wait-config.ts +23 -9
- package/src/runs/background/wait-tool.ts +26 -19
- package/src/runs/foreground/async-steering-action.ts +3 -19
- package/src/runs/foreground/execution.ts +468 -499
- package/src/runs/foreground/foreground-control.ts +13 -0
- package/src/runs/foreground/foreground-history.ts +23 -1
- package/src/runs/foreground/subagent-executor.ts +1172 -400
- package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
- package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
- package/src/runs/shared/abort-recovery.ts +119 -0
- package/src/runs/shared/acceptance.ts +138 -36
- package/src/runs/shared/async-status-projection.ts +565 -0
- package/src/runs/shared/background-process-options.ts +9 -0
- package/src/runs/shared/capability-ceiling.ts +2 -2
- package/src/runs/shared/child-hooks.ts +25 -0
- package/src/runs/shared/child-identity.ts +32 -6
- package/src/runs/shared/child-launch-plan.ts +151 -0
- package/src/runs/shared/child-launch.ts +314 -0
- package/src/runs/shared/child-lifecycle.ts +25 -0
- package/src/runs/shared/child-runtime-config.ts +126 -0
- package/src/runs/shared/child-session.ts +342 -0
- package/src/runs/shared/child-tool-plan.ts +540 -0
- package/src/runs/shared/claude-code-adapter.ts +133 -0
- package/src/runs/shared/codex-exec-adapter.ts +129 -0
- package/src/runs/shared/completion-evidence.ts +89 -0
- package/src/runs/shared/completion-guard.ts +6 -5
- package/src/runs/shared/cursor-agent-adapter.ts +114 -0
- package/src/runs/shared/dynamic-fanout.ts +3 -3
- package/src/runs/shared/external-cli-contract.ts +167 -0
- package/src/runs/shared/external-cli-preflight.ts +138 -0
- package/src/runs/shared/external-cli-runner.ts +348 -55
- package/src/runs/shared/fast-mode-extension.ts +5 -5
- package/src/runs/shared/host-step-status.ts +231 -0
- package/src/runs/shared/lane-metadata.ts +126 -0
- package/src/runs/shared/launch-cwd.ts +16 -0
- package/src/runs/shared/long-running-guard.ts +2 -1
- package/src/runs/shared/mcp-config-sources.ts +422 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
- package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
- package/src/runs/shared/model-exclusions.ts +139 -9
- package/src/runs/shared/model-fallback.ts +142 -14
- package/src/runs/shared/mutation-evidence.ts +57 -3
- package/src/runs/shared/nested-events.ts +38 -48
- package/src/runs/shared/nested-path.ts +0 -14
- package/src/runs/shared/nested-render.ts +9 -5
- package/src/runs/shared/orca-progress-tabs.ts +12 -7
- package/src/runs/shared/parallel-handoff.ts +423 -7
- package/src/runs/shared/parallel-utils.ts +15 -7
- package/src/runs/shared/permissions.ts +1 -14
- package/src/runs/shared/pi-spawn.ts +69 -35
- package/src/runs/shared/process-signal.ts +16 -0
- package/src/runs/shared/run-fanout-budget.ts +0 -13
- package/src/runs/shared/run-history.ts +21 -1
- package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
- package/src/runs/shared/single-output.ts +89 -22
- package/src/runs/shared/structured-output.ts +49 -9
- package/src/runs/shared/subagent-control.ts +6 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
- package/src/runs/shared/task-intent.ts +21 -7
- package/src/runs/shared/tool-availability.ts +18 -62
- package/src/runs/shared/tool-budget.ts +0 -14
- package/src/runs/shared/tool-timeout.ts +1 -1
- package/src/runs/shared/workflow-graph.ts +16 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
- package/src/runs/shared/worktree.ts +571 -62
- package/src/shared/atomic-json.ts +3 -1
- package/src/shared/child-session-name.ts +46 -0
- package/src/shared/extension-context.ts +24 -0
- package/src/shared/fork-context.ts +21 -12
- package/src/shared/fork-session-cwd.ts +27 -0
- package/src/shared/formatters.ts +18 -3
- package/src/shared/jsonl-writer.ts +11 -0
- package/src/shared/launch-contract.ts +8 -1
- package/src/shared/pruned-fork.ts +450 -0
- package/src/shared/session-file-trust.ts +19 -0
- package/src/shared/session-tokens.ts +14 -3
- package/src/shared/settings.ts +19 -105
- package/src/shared/shortcuts.ts +17 -0
- package/src/shared/thinking-ceiling.ts +0 -6
- package/src/shared/types.ts +524 -70
- package/src/shared/utils.ts +60 -93
- package/src/shared/workflow-child-permit.ts +207 -0
- package/src/slash/delegation-adapters.ts +1 -9
- package/src/slash/delegation-request.ts +0 -4
- package/src/slash/prompt-template-bridge.ts +37 -1
- package/src/slash/slash-bridge.ts +1 -2
- package/src/slash/slash-commands.ts +383 -116
- package/src/slash/slash-live-state.ts +22 -11
- package/src/slash/subagents-admin.ts +29 -12
- package/src/tui/fleet-native-transcript.ts +4 -0
- package/src/tui/fleet-status.ts +217 -82
- package/src/tui/fleet-transcript.ts +11 -5
- package/src/tui/fleet.ts +54 -28
- package/src/tui/render-helpers.ts +31 -0
- package/src/tui/render.ts +1429 -163
- package/src/watchdog/change-signature.ts +40 -1
- package/src/watchdog/child-status.ts +54 -34
- package/src/watchdog/diff-tool.ts +77 -0
- package/src/watchdog/emission-guard.ts +5 -3
- package/src/watchdog/guidance.ts +20 -0
- package/src/watchdog/register-child.ts +28 -25
- package/src/watchdog/register-main.ts +10 -9
- package/src/watchdog/render.ts +4 -5
- package/src/watchdog/review.ts +15 -4
- package/src/watchdog/rules.ts +70 -0
- package/src/watchdog/runtime.ts +75 -92
- package/src/watchdog/scope.ts +0 -11
- package/src/watchdog/settings.ts +48 -104
- package/src/watchdog/turn-delta.ts +1 -1
- package/src/watchdog/types.ts +18 -32
- package/src/watchdog/warning-format.ts +0 -1
- package/src/workflows/chat-progress.ts +7 -3
- package/src/workflows/host-command.ts +235 -0
- package/src/workflows/scripted-workflow.ts +988 -59
- package/src/workflows/workflow-checklist.ts +439 -0
- package/src/workflows/workflow-child-summary.ts +121 -0
- package/src/workflows/workflow-preflight.ts +297 -0
- package/src/workflows/workflow-receipt.ts +232 -6
- package/src/workflows/workflow-resources.ts +150 -0
- package/src/workflows/workflow-settlement.ts +246 -0
- package/src/runs/shared/child-protocol.ts +0 -401
- package/src/runs/shared/pi-args.ts +0 -935
- package/src/runs/shared/subagent-startup-retry.ts +0 -116
- package/src/runs/shared/turn-budget.ts +0 -98
- 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
|
-
|
|
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 (!
|
|
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
|
|
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())
|
|
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: { ...(
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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" | "
|
|
199
|
-
status: Pick<AsyncStatus, "
|
|
200
|
+
descriptor: Pick<SteeringRecoveryDescriptor, "absoluteDeadlineAt" | "initialToolBudget">,
|
|
201
|
+
status: Pick<AsyncStatus, "toolBudget" | "toolCount">,
|
|
200
202
|
now = Date.now(),
|
|
201
|
-
): { timeoutMs?: number; absoluteDeadlineAt?: number;
|
|
202
|
-
const limits: { timeoutMs?: number; absoluteDeadlineAt?: number;
|
|
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;
|