@lune_99/pi-subagent 0.0.0-stage → 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.
Files changed (46) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +21 -0
  3. package/README.md +169 -2
  4. package/docs/capture.json +30 -0
  5. package/docs/previews.md +22 -0
  6. package/docs/reference.md +240 -0
  7. package/docs/subagent-auto-tiers.png +0 -0
  8. package/docs/subagent-inspector.png +0 -0
  9. package/docs/subagent-overview.png +0 -0
  10. package/package.json +82 -5
  11. package/skills/create-lune-subagent/SKILL.md +186 -0
  12. package/src/auto-model.ts +592 -0
  13. package/src/catalog.ts +111 -0
  14. package/src/definition-file.ts +112 -0
  15. package/src/definitions.ts +324 -0
  16. package/src/dock/dock-alert.ts +78 -0
  17. package/src/dock/dock-contribution.ts +318 -0
  18. package/src/extension-tools.ts +46 -0
  19. package/src/index.ts +168 -0
  20. package/src/inspector/details.ts +113 -0
  21. package/src/inspector/inspector.ts +653 -0
  22. package/src/inspector/layout.ts +119 -0
  23. package/src/inspector/transcript.ts +735 -0
  24. package/src/inspector/viewport.ts +62 -0
  25. package/src/inspector/wrap.ts +136 -0
  26. package/src/models.ts +54 -0
  27. package/src/notify/notification-box.ts +381 -0
  28. package/src/notify/notifier.ts +569 -0
  29. package/src/paths.ts +34 -0
  30. package/src/render/lune-theme.ts +68 -0
  31. package/src/render/text.ts +121 -0
  32. package/src/run/guide.ts +26 -0
  33. package/src/run/report-tool.ts +90 -0
  34. package/src/run/run-file.ts +193 -0
  35. package/src/run/run-manager.ts +838 -0
  36. package/src/run/run-session.ts +307 -0
  37. package/src/run/run.ts +681 -0
  38. package/src/run/session-start.ts +283 -0
  39. package/src/run/types.ts +167 -0
  40. package/src/run/worktree.ts +138 -0
  41. package/src/schema.ts +9 -0
  42. package/src/settings/agents-menu.ts +363 -0
  43. package/src/settings/panel.ts +179 -0
  44. package/src/settings/schema.ts +71 -0
  45. package/src/tools/format.ts +375 -0
  46. package/src/tools/subagent-tools.ts +467 -0
@@ -0,0 +1,283 @@
1
+ import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
2
+ import {
3
+ SettingsManager,
4
+ type AgentSession,
5
+ type AgentSessionEvent,
6
+ type AgentSessionServices,
7
+ type ModelRuntime,
8
+ type SessionManager,
9
+ type Theme,
10
+ } from "@earendil-works/pi-coding-agent";
11
+
12
+ import { isSyntheticPath, type ExtensionTool } from "../extension-tools.ts";
13
+ import type { ModelRef } from "../models.ts";
14
+ import { createReportTool, REPORT_TOOL_NAME } from "./report-tool.ts";
15
+ import {
16
+ createRunServices,
17
+ openLiveSession,
18
+ resolveRunModel,
19
+ type Diagnostic,
20
+ type LiveSession,
21
+ } from "./run-session.ts";
22
+ import type { RunReport } from "./types.ts";
23
+
24
+ /** How long `subagent_start` waits for a selected MCP tool to register. */
25
+ const MCP_DISCOVERY_TIMEOUT_MS = 30_000;
26
+ const MCP_POLL_INTERVAL_MS = 200;
27
+
28
+ export interface RunEventTarget {
29
+ handleEvent(event: AgentSessionEvent): void;
30
+ addDiagnostic(diagnostic: Diagnostic): void;
31
+ recordReport(report: RunReport): void;
32
+ }
33
+
34
+ /**
35
+ * Routes a session's events to its run. A new run's session starts, and is checked, before the run
36
+ * exists, so diagnostics from that phase are kept and handed over on attach.
37
+ */
38
+ export class SessionSink {
39
+ private target: RunEventTarget | undefined;
40
+ private pending: Diagnostic[] = [];
41
+ /** Every diagnostic so far; startup checks read it while they wait. */
42
+ readonly seen: Diagnostic[] = [];
43
+
44
+ attach(target: RunEventTarget): void {
45
+ this.target = target;
46
+
47
+ for (const diagnostic of this.pending.splice(0)) {
48
+ target.addDiagnostic(diagnostic);
49
+ }
50
+ }
51
+
52
+ event(event: AgentSessionEvent): void {
53
+ this.target?.handleEvent(event);
54
+ }
55
+
56
+ diagnostic(diagnostic: Diagnostic): void {
57
+ this.seen.push(diagnostic);
58
+
59
+ if (this.target) {
60
+ this.target.addDiagnostic(diagnostic);
61
+ } else {
62
+ this.pending.push(diagnostic);
63
+ }
64
+ }
65
+
66
+ report(report: RunReport): void {
67
+ this.target?.recordReport(report);
68
+ }
69
+ }
70
+
71
+ export interface StartSessionOptions {
72
+ cwd: string;
73
+ agentDir: string;
74
+ projectTrusted: boolean;
75
+ appendSystemPrompt: readonly string[];
76
+ modelRuntime?: ModelRuntime;
77
+ model: ModelRef;
78
+ thinkingLevel: ThinkingLevel | undefined;
79
+ /** The SDK `tools` option: an allowlist with `report`, or `["+report"]` for the default selection. */
80
+ tools: string[];
81
+ /** Task tools that must exist once the session runs; "default" checks the defaultTools setting. */
82
+ check: readonly string[] | "default";
83
+ /** The parent's extension tools; the run loads the extensions of those that `check` names. */
84
+ extensionTools: readonly ExtensionTool[];
85
+ reason: "startup" | "resume";
86
+ theme: Theme;
87
+ /** Called once the model resolved, so a failed resolution leaves no run file behind. */
88
+ openSessionManager: () => SessionManager;
89
+ sink: SessionSink;
90
+ signal?: AbortSignal;
91
+ onProgress?: (text: string) => void;
92
+ }
93
+
94
+ /** Create a run's session, start its extensions, and check its tools; the session is closed on failure. */
95
+ export async function startRunSession(options: StartSessionOptions): Promise<LiveSession> {
96
+ options.onProgress?.("Preparing the run session");
97
+
98
+ // The services load the extensions of the selected tools, so the default selection is read
99
+ // from the run's own settings before they exist.
100
+ const settingsManager = SettingsManager.create(options.cwd, options.agentDir, {
101
+ projectTrusted: options.projectTrusted,
102
+ });
103
+ const check =
104
+ options.check === "default" ? (settingsManager.getDefaultTools() ?? []) : options.check;
105
+ const extensionTools = options.extensionTools.filter((tool) => check.includes(tool.name));
106
+ const services = await createRunServices({
107
+ cwd: options.cwd,
108
+ agentDir: options.agentDir,
109
+ projectTrusted: options.projectTrusted,
110
+ appendSystemPrompt: options.appendSystemPrompt,
111
+ modelRuntime: options.modelRuntime,
112
+ settingsManager,
113
+ extensionTools,
114
+ });
115
+
116
+ for (const diagnostic of services.diagnostics) {
117
+ options.sink.diagnostic({ ...diagnostic, level: diagnostic.type, at: Date.now() });
118
+ }
119
+
120
+ checkExtensionsLoaded(services, extensionTools, options.sink);
121
+
122
+ const model = await resolveRunModel(services, options.model.provider, options.model.id);
123
+ const sessionManager = options.openSessionManager();
124
+ const live = await openLiveSession({
125
+ services,
126
+ sessionManager,
127
+ model,
128
+ thinkingLevel: options.thinkingLevel,
129
+ tools: options.tools,
130
+ customTools: [createReportTool((report) => options.sink.report(report))],
131
+ reason: options.reason,
132
+ theme: options.theme,
133
+ onEvent: (event) => options.sink.event(event),
134
+ onDiagnostic: (diagnostic) => options.sink.diagnostic(diagnostic),
135
+ });
136
+
137
+ try {
138
+ await checkTools(live.session, check, extensionTools, options);
139
+ } catch (error) {
140
+ await live.close();
141
+ throw error;
142
+ }
143
+
144
+ return live;
145
+ }
146
+
147
+ /**
148
+ * An extension of a selected tool that fails to load fails the start. With `noExtensions`, every
149
+ * load error with a file path belongs to one of them; the built-ins report theirs at session start.
150
+ */
151
+ function checkExtensionsLoaded(
152
+ services: AgentSessionServices,
153
+ extensionTools: readonly ExtensionTool[],
154
+ sink: SessionSink,
155
+ ): void {
156
+ if (extensionTools.length === 0) {
157
+ return;
158
+ }
159
+
160
+ const errors = services.resourceLoader
161
+ .getExtensions()
162
+ .errors.filter((error) => !isSyntheticPath(error.path));
163
+
164
+ if (errors.length > 0) {
165
+ throw new Error(
166
+ "The extensions of the run's tools failed to load:\n" +
167
+ errors.map((error) => `${error.path}: ${error.error}`).join("\n"),
168
+ );
169
+ }
170
+
171
+ const byPath = new Map<string, string[]>();
172
+
173
+ for (const tool of extensionTools) {
174
+ byPath.set(tool.path, [...(byPath.get(tool.path) ?? []), tool.name]);
175
+ }
176
+
177
+ for (const [path, names] of byPath) {
178
+ sink.diagnostic({
179
+ level: "info",
180
+ message: `Loaded the extension ${path} for ${names.join(", ")}.`,
181
+ at: Date.now(),
182
+ });
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Every selected tool must exist in the run itself; a missing one fails the start rather than
188
+ * being dropped. MCP tools register only once their server connects, so they are waited for.
189
+ */
190
+ async function checkTools(
191
+ session: AgentSession,
192
+ names: readonly string[],
193
+ extensionTools: readonly ExtensionTool[],
194
+ options: StartSessionOptions,
195
+ ): Promise<void> {
196
+ const registered = (): Set<string> => new Set(session.getAllTools().map((tool) => tool.name));
197
+ const missing = names.filter((name) => name !== REPORT_TOOL_NAME && !registered().has(name));
198
+ // An extension can register a tool depending on its working directory or settings.
199
+ const unregistered = extensionTools.filter((tool) => missing.includes(tool.name));
200
+
201
+ if (unregistered.length > 0) {
202
+ throw new Error(
203
+ unregistered
204
+ .map(
205
+ (tool) =>
206
+ `The extension ${tool.path} did not register ${tool.name} in the run.`,
207
+ )
208
+ .join("\n"),
209
+ );
210
+ }
211
+
212
+ const other = missing.filter((name) => !name.startsWith("mcp__"));
213
+
214
+ if (other.length > 0) {
215
+ throw new Error(
216
+ `Not available in a run: ${other.join(", ")}. Runs have Pi's native tools, codemode, ` +
217
+ "tool_search, the MCP tools of the run's configured servers and the tools of your " +
218
+ "extensions, except the subagent tools.",
219
+ );
220
+ }
221
+
222
+ if (missing.length === 0) {
223
+ return;
224
+ }
225
+
226
+ options.onProgress?.(`Waiting for MCP tools: ${missing.join(", ")}`);
227
+
228
+ const deadline = Date.now() + MCP_DISCOVERY_TIMEOUT_MS;
229
+ let checked = 0;
230
+
231
+ for (;;) {
232
+ const tools = registered();
233
+ const waiting = missing.filter((name) => !tools.has(name));
234
+
235
+ if (waiting.length === 0) {
236
+ return;
237
+ }
238
+
239
+ // A connected server registers all of its tools together, so a namespace that has tools
240
+ // but not this one means the server does not offer it.
241
+ const namespaces = session
242
+ .getAllTools()
243
+ .flatMap((tool) => (tool.namespace ? [tool.namespace] : []));
244
+ const absent = waiting.filter((name) =>
245
+ namespaces.some((namespace) => name.startsWith(`${namespace}__`)),
246
+ );
247
+
248
+ if (absent.length > 0) {
249
+ throw new Error(`The run's MCP servers do not offer: ${absent.join(", ")}.`);
250
+ }
251
+
252
+ const failures = options.sink.seen
253
+ .slice(checked)
254
+ .filter((diagnostic) =>
255
+ /^MCP (servers need attention|failed to load)/.test(diagnostic.message),
256
+ );
257
+
258
+ checked = options.sink.seen.length;
259
+
260
+ if (failures.length > 0) {
261
+ throw new Error(
262
+ `MCP tools ${waiting.join(", ")} are not available: ` +
263
+ failures.map((diagnostic) => diagnostic.message).join("\n"),
264
+ );
265
+ }
266
+
267
+ if (options.signal?.aborted) {
268
+ throw new Error("Cancelled while waiting for MCP tools.");
269
+ }
270
+
271
+ if (Date.now() >= deadline) {
272
+ const recent = options.sink.seen.map((diagnostic) => diagnostic.message);
273
+
274
+ throw new Error(
275
+ `MCP tools ${waiting.join(", ")} did not register within ` +
276
+ `${MCP_DISCOVERY_TIMEOUT_MS / 1000} s.` +
277
+ (recent.length > 0 ? ` Run diagnostics:\n${recent.join("\n")}` : ""),
278
+ );
279
+ }
280
+
281
+ await new Promise((resolve) => setTimeout(resolve, MCP_POLL_INTERVAL_MS));
282
+ }
283
+ }
@@ -0,0 +1,167 @@
1
+ import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
2
+
3
+ /** Custom type of the parent's spawn entry and of the snapshot entry in the run file. */
4
+ export const RUN_ENTRY_TYPE = "lune-subagent-run";
5
+
6
+ /** Custom type of the entry a run file gets when one of its turns ends. */
7
+ export const TURN_ENTRY_TYPE = "lune-subagent-turn";
8
+
9
+ export const ISOLATION_MODES = ["shared", "worktree"] as const;
10
+ export type Isolation = (typeof ISOLATION_MODES)[number];
11
+
12
+ export const REPORT_STATUSES = ["done", "blocked", "needs_input"] as const;
13
+ export type ReportStatus = (typeof REPORT_STATUSES)[number];
14
+
15
+ export const THINKING_LEVELS = [
16
+ "off",
17
+ "minimal",
18
+ "low",
19
+ "medium",
20
+ "high",
21
+ "xhigh",
22
+ "max",
23
+ ] as const satisfies readonly ThinkingLevel[];
24
+
25
+ // Pi exports no list of its levels; this fails to compile when Pi adds one.
26
+ const _allLevelsListed: [Exclude<ThinkingLevel, (typeof THINKING_LEVELS)[number]>] extends [never]
27
+ ? true
28
+ : never = true;
29
+ void _allLevelsListed;
30
+
31
+ /** The state describes the session; the report status describes the task. */
32
+ export type RunState = "running" | "idle" | "failed" | "interrupted";
33
+ export type SettledState = Exclude<RunState, "running">;
34
+
35
+ export interface RunReport {
36
+ status: ReportStatus;
37
+ summary: string;
38
+ /** Set for `blocked`. */
39
+ reason?: string;
40
+ /** Set for `needs_input`. */
41
+ question?: string;
42
+ }
43
+
44
+ /** Where a start value came from; `auto` is the classifier of a `model: auto` run. */
45
+ export type ValueSource = "call" | "definition" | "parent" | "settings" | "default" | "auto";
46
+
47
+ /** How demanding an auto run's task is, from the least; each tier can have its own model. */
48
+ export const AUTO_TIERS = ["light", "standard", "complex", "deep"] as const;
49
+ export type AutoTier = (typeof AUTO_TIERS)[number];
50
+
51
+ /** How much an auto run's task must reason, from the least; it sets the thinking level. */
52
+
53
+ export interface RunWorktree {
54
+ repoRoot: string;
55
+ path: string;
56
+ baseCommit: string;
57
+ }
58
+
59
+ /** The classifier's answer to one auto question, and the level the run used. */
60
+ export interface AutoRating<T extends string> {
61
+ /** The option the classifier chose. */
62
+ rated: T;
63
+ /** `rated`, or the next level up when the classifier was unsure. */
64
+ used: T;
65
+ /** Pi's measure of how clear the choice was, from 0 (an even split) to 1. */
66
+ confidence: number;
67
+ /** Each option's share of the answer, from 0 to 1. */
68
+ probabilities: Partial<Record<T, number>>;
69
+ }
70
+
71
+ /** The high-risk answer of a rating. */
72
+ export interface AutoRisk {
73
+ /** The classifier's probability that a mistake in the task could cause serious harm. */
74
+ probability: number;
75
+ /** The probability from which a task counts as high risk, from the settings. */
76
+ threshold: number;
77
+ high: boolean;
78
+ /** The high-risk floor, when it raised the tier that the model comes from. */
79
+ floor?: AutoTier;
80
+ }
81
+
82
+ /** How `model: auto` resolved the run's model and, unless the start set it, its thinking. */
83
+ export type AutoModelChoice =
84
+ | {
85
+ by: "rating";
86
+ /** `provider/id` of the classifier. */
87
+ classifier: string;
88
+ tier: AutoRating<AutoTier>;
89
+ /** The tier whose model the run got, or `main` for the main agent's model. */
90
+ modelFrom: AutoTier | "main";
91
+ /** Absent when the start set the thinking or the run's model supports one level. */
92
+ thinking?: AutoRating<ThinkingLevel>;
93
+ /** Absent for a run that an earlier version started. */
94
+ risk?: AutoRisk;
95
+ }
96
+ /** No classifier is selected, so the run got the main agent's model. */
97
+ | { by: "no-classifier" }
98
+ /** No tier has a model and the start set the thinking, so no classifier ran. */
99
+ | { by: "nothing-to-rate" }
100
+ /** The classifier failed, so the run got the main agent's model, and thinking if unset. */
101
+ | { by: "classifier-failed"; classifier: string; error: string };
102
+
103
+ /** The values a run started with. Later edits to its definition never change an existing run. */
104
+ export interface RunSnapshot {
105
+ runId: string;
106
+ /** The definition name, or `run-<n>` for an inline run. */
107
+ name: string;
108
+ /** Only for a run started from a definition. */
109
+ definition?: { name: string; body: string; file: string };
110
+ task: string;
111
+ /** `provider/id`. */
112
+ model: string;
113
+ /** Set when the call or definition asked for `auto`; `sources.model` says which. */
114
+ autoModel?: AutoModelChoice;
115
+ thinking: ThinkingLevel;
116
+ /** The effective SDK allowlist, `report` included. */
117
+ tools: string[];
118
+ sources: {
119
+ model: ValueSource;
120
+ thinking: ValueSource;
121
+ tools: ValueSource;
122
+ isolation: ValueSource;
123
+ };
124
+ isolation: Isolation;
125
+ /** The run's working directory: the parent's, or the matching folder in the worktree. */
126
+ cwd: string;
127
+ worktree?: RunWorktree;
128
+ parentSessionId: string;
129
+ parentSessionFile?: string;
130
+ spawnEntryId: string;
131
+ createdAt: string;
132
+ }
133
+
134
+ /** The parent's branch entry. A run's state lives only in its own file. */
135
+ export interface SpawnEntryData {
136
+ runId: string;
137
+ sessionFile: string;
138
+ parentSessionId: string;
139
+ }
140
+
141
+ /** Who stopped a turn. */
142
+ export type StopSource = "main-agent" | "user" | "branch" | "shutdown";
143
+
144
+ export interface TurnRecord {
145
+ state: SettledState;
146
+ /** The turn's last report. */
147
+ report?: RunReport;
148
+ /** Reports that a later report of the same turn replaced, oldest first. */
149
+ earlierReports?: RunReport[];
150
+ error?: string;
151
+ /** The run's last text, kept when the turn ended without `report`. */
152
+ unreportedMessage?: string;
153
+ /** The user wrote to the run from the inspector during this turn. */
154
+ userWrote: boolean;
155
+ stoppedBy?: StopSource;
156
+ startedAt: string;
157
+ endedAt: string;
158
+ }
159
+
160
+ export interface RunUsage {
161
+ input: number;
162
+ output: number;
163
+ cacheRead: number;
164
+ cacheWrite: number;
165
+ total: number;
166
+ cost: number;
167
+ }
@@ -0,0 +1,138 @@
1
+ import { execFile } from "node:child_process";
2
+ import { existsSync, mkdirSync, statSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { promisify } from "node:util";
5
+
6
+ import type { RunWorktree } from "./types.ts";
7
+
8
+ const execFileAsync = promisify(execFile);
9
+
10
+ export interface CreatedWorktree extends RunWorktree {
11
+ /** The worktree folder that matches the parent's working directory. */
12
+ cwd: string;
13
+ }
14
+
15
+ async function git(args: string[], signal?: AbortSignal): Promise<string> {
16
+ try {
17
+ const { stdout } = await execFileAsync("git", args, { signal, maxBuffer: 1024 * 1024 });
18
+
19
+ return stdout.trim();
20
+ } catch (error) {
21
+ const stderr = (error as { stderr?: unknown }).stderr;
22
+ const detail =
23
+ typeof stderr === "string" && stderr.trim() !== ""
24
+ ? stderr.trim()
25
+ : error instanceof Error
26
+ ? error.message
27
+ : String(error);
28
+
29
+ throw new Error(`git ${args.join(" ")} failed: ${detail}`, { cause: error });
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Check out the parent repository's current HEAD in a detached worktree.
35
+ *
36
+ * The worktree holds the commit only: the parent's staged, unstaged, untracked and ignored files
37
+ * stay where they are, and nothing is stashed or committed for the run.
38
+ */
39
+ export async function createRunWorktree(
40
+ parentCwd: string,
41
+ worktreePath: string,
42
+ signal?: AbortSignal,
43
+ ): Promise<CreatedWorktree> {
44
+ let repoRoot: string;
45
+ let prefix: string;
46
+
47
+ try {
48
+ repoRoot = await git(["-C", parentCwd, "rev-parse", "--show-toplevel"], signal);
49
+ // The prefix, not a path relative to repoRoot: the parent's cwd may reach the repository
50
+ // through a symlink that --show-toplevel resolves. Git ends it with a slash.
51
+ prefix = (await git(["-C", parentCwd, "rev-parse", "--show-prefix"], signal)).replace(
52
+ /\/+$/,
53
+ "",
54
+ );
55
+ } catch (error) {
56
+ throw new Error(
57
+ `Worktree isolation needs a Git repository at ${parentCwd}. ${errorMessage(error)}`,
58
+ { cause: error },
59
+ );
60
+ }
61
+
62
+ let baseCommit: string;
63
+
64
+ try {
65
+ baseCommit = await git(["-C", repoRoot, "rev-parse", "--verify", "HEAD^{commit}"], signal);
66
+ } catch (error) {
67
+ throw new Error(
68
+ `Worktree isolation needs a HEAD commit in ${repoRoot}. ${errorMessage(error)}`,
69
+ { cause: error },
70
+ );
71
+ }
72
+
73
+ if (existsSync(worktreePath)) {
74
+ throw new Error(`The worktree path already exists: ${worktreePath}`);
75
+ }
76
+
77
+ mkdirSync(dirname(worktreePath), { recursive: true });
78
+ await git(["-C", repoRoot, "worktree", "add", "--detach", worktreePath, baseCommit], signal);
79
+
80
+ const cwd = prefix === "" ? worktreePath : join(worktreePath, prefix);
81
+
82
+ if (!isDirectory(cwd)) {
83
+ await removeRunWorktree(repoRoot, worktreePath);
84
+
85
+ throw new Error(
86
+ `The working directory ${prefix} does not exist in commit ${baseCommit.slice(0, 12)}, ` +
87
+ "so the worktree has no matching folder for the run. Use shared isolation, or " +
88
+ "commit the folder first.",
89
+ );
90
+ }
91
+
92
+ return { repoRoot, path: worktreePath, baseCommit, cwd };
93
+ }
94
+
95
+ /** Only for a worktree this package just created and no run uses yet. */
96
+ export async function removeRunWorktree(repoRoot: string, worktreePath: string): Promise<void> {
97
+ await git(["-C", repoRoot, "worktree", "remove", "--force", worktreePath]);
98
+ }
99
+
100
+ /** A continued run must find its own checkout; it is never recreated from a clean commit. */
101
+ export async function assertWorktreeUsable(worktree: RunWorktree, cwd: string): Promise<void> {
102
+ if (!isDirectory(worktree.path)) {
103
+ throw new Error(
104
+ `The run's worktree is missing: ${worktree.path}. It cannot continue; start a new run.`,
105
+ );
106
+ }
107
+
108
+ let inside: string;
109
+
110
+ try {
111
+ inside = await git(["-C", worktree.path, "rev-parse", "--is-inside-work-tree"]);
112
+ } catch (error) {
113
+ throw new Error(
114
+ `The run's worktree is not a usable Git worktree: ${worktree.path}. ${errorMessage(error)}`,
115
+ { cause: error },
116
+ );
117
+ }
118
+
119
+ if (inside !== "true") {
120
+ throw new Error(`The run's worktree is not a Git work tree: ${worktree.path}.`);
121
+ }
122
+
123
+ if (!isDirectory(cwd)) {
124
+ throw new Error(`The run's working directory is missing: ${cwd}.`);
125
+ }
126
+ }
127
+
128
+ function isDirectory(path: string): boolean {
129
+ try {
130
+ return statSync(path).isDirectory();
131
+ } catch {
132
+ return false;
133
+ }
134
+ }
135
+
136
+ function errorMessage(error: unknown): string {
137
+ return error instanceof Error ? error.message : String(error);
138
+ }
package/src/schema.ts ADDED
@@ -0,0 +1,9 @@
1
+ import Type from "typebox";
2
+
3
+ /** A plain `enum` keyword, which every provider accepts, instead of TypeBox's union of literals. */
4
+ export function stringEnum<const T extends readonly string[]>(
5
+ values: T,
6
+ options: { description?: string } = {},
7
+ ) {
8
+ return Type.Unsafe<T[number]>({ type: "string", enum: [...values], ...options });
9
+ }