pi-chalin 0.1.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.
@@ -0,0 +1,105 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { estimateBudgetPreflight } from "./budget.ts";
4
+ import { resolveChalinPaths, type ChalinPathsOptions } from "./paths.ts";
5
+ import type { AgentStep, RouteDecision, RoutePlan, RunState, RunStepState } from "./schemas.ts";
6
+
7
+ export function createRunState(route: RouteDecision, cwd: string): RunState {
8
+ const id = `chalin-${Date.now().toString(36)}`;
9
+ return {
10
+ id,
11
+ route,
12
+ status: "running",
13
+ startedAt: new Date().toISOString(),
14
+ steps: route.plan ? planSteps(route.plan) : [],
15
+ logsPath: path.join(resolveChalinPaths({ cwd }).projectRoot, ".pi-chalin", "runs", `${id}.json`),
16
+ warnings: [],
17
+ budgetPreflight: estimateBudgetPreflight({
18
+ task: route.reason,
19
+ routeKind: route.kind,
20
+ steps: route.plan ? planAgentSteps(route.plan) : undefined,
21
+ risk: route.risk,
22
+ needsArtifacts: route.needsArtifacts,
23
+ }),
24
+ };
25
+ }
26
+
27
+ export function prepareRunForResume(run: RunState): RunState {
28
+ run.status = "running";
29
+ run.endedAt = undefined;
30
+ run.warnings = [...run.warnings, `Resumed paused pi-chalin run ${run.id}.`];
31
+ for (const step of run.steps) {
32
+ if (isUsableStepHandoff(step) || step.status === "failed") continue;
33
+ step.status = "pending";
34
+ step.error = undefined;
35
+ step.currentTool = undefined;
36
+ step.endedAt = undefined;
37
+ }
38
+ persistRun(run);
39
+ return run;
40
+ }
41
+
42
+ export function loadResumableRunState(options: ChalinPathsOptions & { runId?: string }): RunState | undefined {
43
+ const runsDir = path.join(resolveChalinPaths(options).projectRoot, ".pi-chalin", "runs");
44
+ if (!fs.existsSync(runsDir)) return undefined;
45
+ const files = fs.readdirSync(runsDir)
46
+ .filter((name) => name.endsWith(".json"))
47
+ .map((name) => path.join(runsDir, name))
48
+ .sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs);
49
+ for (const file of files) {
50
+ try {
51
+ const parsed = JSON.parse(fs.readFileSync(file, "utf-8")) as RunState;
52
+ if (options.runId && parsed.id !== options.runId) continue;
53
+ if (isResumableRun(parsed)) {
54
+ parsed.logsPath ??= file;
55
+ if (parsed.status === "running") {
56
+ parsed.status = "paused";
57
+ parsed.warnings = [...(parsed.warnings ?? []), "Recovered stale running run from disk after process shutdown."];
58
+ persistRun(parsed);
59
+ }
60
+ return parsed;
61
+ }
62
+ } catch {
63
+ // Ignore corrupt run files; a newer/older run may still be resumable.
64
+ }
65
+ }
66
+ return undefined;
67
+ }
68
+
69
+ export function persistRun(run: RunState): void {
70
+ if (!run.logsPath) return;
71
+ fs.mkdirSync(path.dirname(run.logsPath), { recursive: true });
72
+ fs.writeFileSync(run.logsPath, `${JSON.stringify(run, null, 2)}\n`, "utf-8");
73
+ }
74
+
75
+ export function isUsableStepHandoff(step: Pick<RunStepState, "status">): boolean {
76
+ return step.status === "complete" || step.status === "budget-capped";
77
+ }
78
+
79
+ function isResumableRun(run: RunState): boolean {
80
+ if (!run.route?.plan) return false;
81
+ if (run.status !== "paused" && run.status !== "running") return false;
82
+ if (run.steps.some((step) => !isUsableStepHandoff(step) && step.status !== "failed")) return true;
83
+ return run.status === "running" && run.steps.length > 0 && run.steps.every((step) => isUsableStepHandoff(step));
84
+ }
85
+
86
+ function planSteps(plan: RoutePlan): RunStepState[] {
87
+ if (plan.kind === "dag") {
88
+ return plan.stages.flatMap((stage) => stage.tasks.map((step, index) => ({
89
+ id: `${stage.id}:step-${index + 1}`,
90
+ agent: step.agent,
91
+ task: step.task,
92
+ budget: step.budget,
93
+ status: "pending" as const,
94
+ })));
95
+ }
96
+ const rawSteps = plan.kind === "single" ? [{ agent: plan.agent, task: plan.task }] : plan.kind === "chain" ? plan.steps : plan.tasks;
97
+ return rawSteps.map((step, index) => ({ id: `step-${index + 1}`, agent: step.agent, task: step.task, budget: step.budget, status: "pending" }));
98
+ }
99
+
100
+ function planAgentSteps(plan: RoutePlan): AgentStep[] {
101
+ if (plan.kind === "single") return [{ agent: plan.agent, task: plan.task, budget: plan.budget }];
102
+ if (plan.kind === "chain") return plan.steps;
103
+ if (plan.kind === "parallel") return plan.tasks;
104
+ return plan.stages.flatMap((stage) => stage.tasks);
105
+ }