@pi-unipi/unipi 2.6.3 → 2.7.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 (51) hide show
  1. package/package.json +16 -10
  2. package/packages/autocomplete/src/constants.ts +5 -0
  3. package/packages/core/tui-overlay.ts +1 -1
  4. package/packages/subagents/README.md +89 -78
  5. package/packages/subagents/package.json +14 -16
  6. package/packages/subagents/skills/council-mode/SKILL.md +230 -0
  7. package/packages/subagents/skills/subagents/SKILL.md +49 -0
  8. package/packages/subagents/skills/subagents/references/constraints-and-recipes.md +259 -0
  9. package/packages/subagents/skills/subagents/references/execution-controls.md +454 -0
  10. package/packages/subagents/skills/subagents/references/management-authoring-rpc.md +161 -0
  11. package/packages/subagents/skills/subagents/references/multi-lane-orchestration.md +39 -0
  12. package/packages/subagents/skills/subagents/references/prompting-and-roles.md +267 -0
  13. package/packages/subagents/src/acceptance.ts +331 -0
  14. package/packages/subagents/src/agent-manager.ts +89 -6
  15. package/packages/subagents/src/agent-memory.ts +300 -0
  16. package/packages/subagents/src/agent-overrides.ts +183 -0
  17. package/packages/subagents/src/agent-runner.ts +10 -0
  18. package/packages/subagents/src/async-runner.ts +417 -0
  19. package/packages/subagents/src/authority-policy.ts +47 -0
  20. package/packages/subagents/src/budgets.ts +285 -0
  21. package/packages/subagents/src/child-safety.ts +140 -0
  22. package/packages/subagents/src/config.ts +80 -1
  23. package/packages/subagents/src/custom-agents.ts +236 -38
  24. package/packages/subagents/src/file-system-retry.ts +50 -0
  25. package/packages/subagents/src/fleet-data.ts +61 -0
  26. package/packages/subagents/src/fleet-view.ts +316 -0
  27. package/packages/subagents/src/foreground-detach.ts +59 -0
  28. package/packages/subagents/src/fork-context.ts +285 -0
  29. package/packages/subagents/src/guide.ts +129 -0
  30. package/packages/subagents/src/index.ts +515 -197
  31. package/packages/subagents/src/mission-state.ts +133 -0
  32. package/packages/subagents/src/mission-store.ts +434 -0
  33. package/packages/subagents/src/output-limits.ts +142 -0
  34. package/packages/subagents/src/parity-types.ts +315 -0
  35. package/packages/subagents/src/pi-args.ts +161 -0
  36. package/packages/subagents/src/pi-spawn.ts +147 -0
  37. package/packages/subagents/src/result-files.ts +232 -0
  38. package/packages/subagents/src/result-watcher.ts +221 -0
  39. package/packages/subagents/src/retained-children.ts +176 -0
  40. package/packages/subagents/src/run-fanout-budget.ts +356 -0
  41. package/packages/subagents/src/scheduled-runs.ts +351 -0
  42. package/packages/subagents/src/schemas.ts +263 -0
  43. package/packages/subagents/src/slash-commands.ts +77 -0
  44. package/packages/subagents/src/supervisor-channel.ts +249 -0
  45. package/packages/subagents/src/tool-handler.ts +1144 -0
  46. package/packages/subagents/src/types.ts +103 -2
  47. package/packages/subagents/src/workflow-script.ts +737 -0
  48. package/packages/subagents/src/workflow-worker.ts +384 -0
  49. package/packages/subagents/src/worktree.ts +614 -0
  50. package/packages/unipi/bundled.js +6577 -1093
  51. package/packages/unipi/index.ts +3 -3
@@ -4,13 +4,18 @@
4
4
  * Discovers agent types from:
5
5
  * - <workspace>/.unipi/config/agents/*.md (project, highest priority)
6
6
  * - ~/.unipi/config/agents/*.md (global)
7
+ * - packages/subagents/agents/*.md (builtin, lowest priority — pi-subagents parity)
8
+ *
9
+ * Recursive subdirectory discovery: project wins name collisions.
7
10
  */
8
11
 
9
12
  import { existsSync, readdirSync, readFileSync, renameSync } from "node:fs";
10
- import { join } from "node:path";
13
+ import { dirname, join, relative } from "node:path";
11
14
  import { homedir } from "node:os";
15
+ import { fileURLToPath } from "node:url";
12
16
  import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
13
17
  import type { AgentConfig } from "./types.js";
18
+ import { parseMemoryFrontmatter } from "./agent-memory.js";
14
19
 
15
20
  function compareCodeUnits(a: string, b: string): number {
16
21
  return a < b ? -1 : a > b ? 1 : 0;
@@ -39,10 +44,132 @@ function getGlobalAgentsDir(): string {
39
44
  /** All known built-in tool names. */
40
45
  const BUILTIN_TOOL_NAMES = ["read", "bash", "edit", "write", "grep", "find", "ls"];
41
46
 
47
+ /** Known frontmatter fields (pi-subagents KNOWN_FIELDS + our unipi extensions). */
48
+ const KNOWN_FIELDS = new Set([
49
+ "name",
50
+ "display_name",
51
+ "description",
52
+ "alias",
53
+ "aliases",
54
+ "tools",
55
+ "disallowed_tools",
56
+ "model",
57
+ "fallbackModels",
58
+ "thinking",
59
+ "extensions",
60
+ "skills",
61
+ "max_turns",
62
+ "systemPromptMode",
63
+ "prompt_mode",
64
+ "inheritProjectContext",
65
+ "inheritSkills",
66
+ "defaultContext",
67
+ "async",
68
+ "run_in_background",
69
+ "isolated",
70
+ "timeoutMs",
71
+ "toolTimeoutMs",
72
+ "turnBudget",
73
+ "skill",
74
+ "skillPath",
75
+ "subagentOnlyExtensions",
76
+ "output",
77
+ "outputMode",
78
+ "defaultReads",
79
+ "defaultProgress",
80
+ "interactive",
81
+ "maxSubagentDepth",
82
+ "completionGuard",
83
+ "toolBudget",
84
+ "memory",
85
+ "enabled",
86
+ "runner",
87
+ ]);
88
+
89
+ /** Parse a comma-separated frontmatter list (reference parseFrontmatterList). */
90
+ function parseList(raw: unknown): string[] | undefined {
91
+ if (raw === undefined || raw === null) return undefined;
92
+ if (Array.isArray(raw)) return raw.map(String).map((s) => s.trim()).filter(Boolean);
93
+ if (typeof raw === "string") return raw.split(",").map((s) => s.trim()).filter(Boolean);
94
+ return undefined;
95
+ }
96
+
97
+ /** Default systemPromptMode per reference (delegate appends, others replace). */
98
+ function defaultSystemPromptMode(name: string): "replace" | "append" {
99
+ return name === "delegate" || name === "explore" ? "append" : "replace";
100
+ }
101
+
102
+ /** Default inheritProjectContext per reference (delegate only). */
103
+ function defaultInheritProjectContext(name: string): boolean {
104
+ return name === "delegate";
105
+ }
106
+
107
+ /** Parse a boolean-ish frontmatter value ("true"/"false" strings or actual booleans). */
108
+ function parseBool(raw: unknown): boolean | undefined {
109
+ if (raw === "true" || raw === true) return true;
110
+ if (raw === "false" || raw === false) return false;
111
+ return undefined;
112
+ }
113
+
114
+ /** Parse a positive-integer frontmatter value with a visible error. */
115
+ function parsePositiveInt(raw: unknown, label: string): number | undefined {
116
+ if (raw === undefined || raw === null || raw === "") return undefined;
117
+ const parsed = Number(raw);
118
+ if (!Number.isInteger(parsed) || parsed <= 0 || parsed > 2_147_483_647) {
119
+ throw new Error(`${label} must be a positive integer no greater than 2147483647 (got ${JSON.stringify(raw)})`);
120
+ }
121
+ return parsed;
122
+ }
123
+
124
+ /** Directory names pruned during recursive discovery. */
125
+ const DISCOVERY_PRUNED_DIR_NAMES = new Set(["node_modules", ".git", ".pi", ".unipi"]);
126
+
127
+ /** List agent .md files recursively under a directory (skips .chain.md, prunes node_modules). */
128
+ function listAgentFilesRecursive(dir: string): string[] {
129
+ const files: string[] = [];
130
+ if (!existsSync(dir)) return files;
131
+ let entries: import("node:fs").Dirent[];
132
+ try {
133
+ entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) =>
134
+ a.name < b.name ? -1 : a.name > b.name ? 1 : 0,
135
+ );
136
+ } catch {
137
+ return files;
138
+ }
139
+ for (const entry of entries) {
140
+ const filePath = join(dir, entry.name);
141
+ if (entry.isDirectory()) {
142
+ if (!DISCOVERY_PRUNED_DIR_NAMES.has(entry.name)) {
143
+ files.push(...listAgentFilesRecursive(filePath));
144
+ }
145
+ continue;
146
+ }
147
+ if (!entry.isFile() && !entry.isSymbolicLink()) continue;
148
+ if (!entry.name.endsWith(".md") || entry.name.endsWith(".chain.md")) continue;
149
+ files.push(filePath);
150
+ }
151
+ return files;
152
+ }
153
+
154
+ /** Builtin agent definition files shipped in packages/subagents/agents/. */
155
+ const BUILTIN_AGENTS_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "agents");
156
+
157
+ /** Frontmatter fields stored as-is on the config for later phases. */
158
+ function collectExtraFields(frontmatter: Record<string, unknown>): Record<string, string> | undefined {
159
+ const extra: Record<string, string> = {};
160
+ for (const [key, value] of Object.entries(frontmatter)) {
161
+ if (!KNOWN_FIELDS.has(key)) extra[key] = String(value);
162
+ }
163
+ return Object.keys(extra).length ? extra : undefined;
164
+ }
165
+
42
166
  /**
43
- * Load a single agent from a .md file.
167
+ * Load a single agent from a .md file. Accepts both our legacy unipi frontmatter
168
+ * (display_name, disallowed_tools, prompt_mode, max_turns, run_in_background,
169
+ * isolated, enabled) and the pi-subagents reference frontmatter (aliases,
170
+ * systemPromptMode, inheritProjectContext, defaultContext, timeoutMs, ...).
44
171
  */
45
- function loadAgentFromFile(filePath: string, source: "project" | "global"): AgentConfig | null {
172
+ function loadAgentFromFile(filePath: string, source: "project" | "global" | "builtin"): AgentConfig | null {
46
173
  try {
47
174
  const content = readFileSync(filePath, "utf-8");
48
175
  const { frontmatter, body } = parseFrontmatter(content);
@@ -50,71 +177,142 @@ function loadAgentFromFile(filePath: string, source: "project" | "global"): Agen
50
177
  if (!frontmatter || typeof frontmatter !== "object") {
51
178
  return null;
52
179
  }
180
+ const fm = frontmatter as Record<string, unknown>;
181
+
182
+ // Name: frontmatter name wins; else filename (our legacy convention).
183
+ const name =
184
+ (typeof fm.name === "string" && fm.name.trim()) ||
185
+ filePath.split("/").pop()?.replace(/\.md$/, "") ||
186
+ "unknown";
187
+
188
+ const description =
189
+ (typeof fm.description === "string" && fm.description) || `${name} agent`;
190
+
191
+ // Tools: comma-separated string; unknown tool names kept (mcp/extension tools).
192
+ const toolsList = parseList(fm.tools);
193
+ const builtinToolNames = toolsList ?? [...BUILTIN_TOOL_NAMES];
194
+
195
+ const aliases = parseList(fm.aliases ?? fm.alias);
53
196
 
54
- const name = filePath.split("/").pop()?.replace(/\.md$/, "") ?? "unknown";
197
+ // Prompt mode: reference systemPromptMode or our legacy prompt_mode.
198
+ const promptModeRaw = fm.systemPromptMode ?? fm.prompt_mode;
199
+ const promptMode: "replace" | "append" =
200
+ promptModeRaw === "replace" || promptModeRaw === "append"
201
+ ? promptModeRaw
202
+ : defaultSystemPromptMode(name);
55
203
 
56
- // Parse tools from comma-separated string
57
- const toolsStr = (frontmatter as any).tools as string | undefined;
58
- const builtinToolNames = toolsStr
59
- ? toolsStr.split(",").map((t) => t.trim()).filter((t) => BUILTIN_TOOL_NAMES.includes(t))
60
- : [...BUILTIN_TOOL_NAMES];
204
+ const inheritProjectContext =
205
+ parseBool(fm.inheritProjectContext) ?? defaultInheritProjectContext(name);
206
+ const inheritSkills = parseBool(fm.inheritSkills) ?? false;
207
+
208
+ const defaultContext =
209
+ fm.defaultContext === "fork" ? "fork" : fm.defaultContext === "fresh" ? "fresh" : undefined;
210
+
211
+ const timeoutMs = parsePositiveInt(fm.timeoutMs, `Agent '${name}' timeoutMs`);
212
+ const toolTimeoutMs = parsePositiveInt(fm.toolTimeoutMs, `Agent '${name}' toolTimeoutMs`);
213
+ const maxSubagentDepth =
214
+ fm.maxSubagentDepth !== undefined && fm.maxSubagentDepth !== null && fm.maxSubagentDepth !== ""
215
+ ? parsePositiveInt(fm.maxSubagentDepth, `Agent '${name}' maxSubagentDepth`)
216
+ : undefined;
217
+
218
+ let defaultAsync: boolean | undefined;
219
+ if (fm.async !== undefined) {
220
+ const parsed = parseBool(fm.async);
221
+ if (parsed === undefined) {
222
+ throw new Error(`Agent '${name}' has invalid async frontmatter; expected true or false.`);
223
+ }
224
+ defaultAsync = parsed;
225
+ }
226
+
227
+ let outputMode: "inline" | "file-only" | undefined;
228
+ if (fm.outputMode !== undefined && fm.outputMode !== "") {
229
+ if (fm.outputMode === "inline" || fm.outputMode === "file-only") outputMode = fm.outputMode;
230
+ else throw new Error(`Agent '${name}' has invalid outputMode frontmatter; expected 'inline' or 'file-only'.`);
231
+ }
61
232
 
62
233
  return {
63
234
  name,
64
- displayName: (frontmatter as any).display_name as string | undefined,
65
- description: ((frontmatter as any).description as string) ?? `${name} agent`,
235
+ displayName: (fm.display_name as string | undefined) ?? undefined,
236
+ description,
237
+ ...(aliases?.length ? { aliases } : {}),
66
238
  builtinToolNames,
67
- disallowedTools: ((frontmatter as any).disallowed_tools as string | undefined)
68
- ?.split(",")
69
- .map((t) => t.trim()),
70
- extensions: (frontmatter as any).extensions !== false,
71
- skills: (frontmatter as any).skills !== false,
72
- model: (frontmatter as any).model as string | undefined,
73
- thinking: (frontmatter as any).thinking as any,
74
- maxTurns: (frontmatter as any).max_turns as number | undefined,
239
+ disallowedTools: parseList(fm.disallowed_tools),
240
+ extensions: fm.extensions !== false,
241
+ skills: fm.skills !== false,
242
+ ...(parseList(fm.skillPath)?.length ? { skillPath: parseList(fm.skillPath) } : {}),
243
+ model: (fm.model as string | undefined) || undefined,
244
+ ...(parseList(fm.fallbackModels)?.length ? { fallbackModels: parseList(fm.fallbackModels) } : {}),
245
+ thinking: fm.thinking as any,
246
+ maxTurns: parsePositiveInt(fm.max_turns, `Agent '${name}' max_turns`),
75
247
  systemPrompt: body.trim(),
76
- promptMode: ((frontmatter as any).prompt_mode as "replace" | "append") ?? "replace",
77
- runInBackground: (frontmatter as any).run_in_background as boolean | undefined,
78
- isolated: (frontmatter as any).isolated as boolean | undefined,
79
- enabled: (frontmatter as any).enabled !== false,
248
+ promptMode,
249
+ inheritProjectContext,
250
+ inheritSkills,
251
+ ...(defaultContext !== undefined ? { defaultContext } : {}),
252
+ ...(defaultAsync !== undefined ? { runInBackground: defaultAsync } : {}),
253
+ runInBackground: (fm.run_in_background as boolean | undefined) ?? defaultAsync,
254
+ isolated: fm.isolated as boolean | undefined,
255
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
256
+ ...(toolTimeoutMs !== undefined ? { toolTimeoutMs } : {}),
257
+ ...(maxSubagentDepth !== undefined ? { maxSubagentDepth } : {}),
258
+ ...(outputMode !== undefined ? { outputMode } : {}),
259
+ ...(typeof fm.output === "string" && fm.output ? { output: fm.output } : {}),
260
+ ...(parseList(fm.defaultReads)?.length ? { defaultReads: parseList(fm.defaultReads) } : {}),
261
+ ...(parseBool(fm.defaultProgress) !== undefined ? { defaultProgress: parseBool(fm.defaultProgress) } : {}),
262
+ ...(parseMemoryFrontmatter(fm.memory) ? { memory: parseMemoryFrontmatter(fm.memory)! } : undefined),
263
+ enabled: fm.enabled !== false,
80
264
  source,
265
+ ...(collectExtraFields(fm) ? { extraFields: collectExtraFields(fm) } : {}),
81
266
  };
82
- } catch {
83
- // Corrupted file — backup and skip
267
+ } catch (err) {
268
+ // Corrupted file — backup and skip (builtin files rethrow: they ship with us)
269
+ if (source === "builtin") throw err;
84
270
  backupCorrupted(filePath);
85
271
  return null;
86
272
  }
87
273
  }
88
274
 
275
+ /**
276
+ * Load builtin definition-file agents from packages/subagents/agents/.
277
+ * Loaded at the LOWEST priority: user/global and project agents override by name.
278
+ */
279
+ export function loadBuiltinFileAgents(): Map<string, AgentConfig> {
280
+ const agents = new Map<string, AgentConfig>();
281
+ for (const filePath of listAgentFilesRecursive(BUILTIN_AGENTS_DIR)) {
282
+ const agent = loadAgentFromFile(filePath, "builtin");
283
+ if (agent) agents.set(agent.name, agent);
284
+ }
285
+ return agents;
286
+ }
287
+
89
288
  /**
90
289
  * Load all custom agents from project and global directories.
91
- * Project agents override global agents with the same name.
290
+ * Priority: project > global > builtin (code BUILTIN_CONFIGS last).
92
291
  */
93
292
  export function loadCustomAgents(cwd: string): Map<string, AgentConfig> {
94
293
  const agents = new Map<string, AgentConfig>();
95
294
 
96
- // Load global agents first
295
+ // Builtin file agents first (lowest priority)
296
+ for (const [name, agent] of loadBuiltinFileAgents()) {
297
+ agents.set(name, agent);
298
+ }
299
+
300
+ // Global agents (override builtins)
97
301
  const globalDir = getGlobalAgentsDir();
98
302
  if (existsSync(globalDir)) {
99
- const files = readdirSync(globalDir)
100
- .filter((f) => f.endsWith(".md"))
101
- .sort(compareCodeUnits);
102
- for (const file of files) {
103
- const agent = loadAgentFromFile(join(globalDir, file), "global");
303
+ for (const filePath of listAgentFilesRecursive(globalDir)) {
304
+ const agent = loadAgentFromFile(filePath, "global");
104
305
  if (agent) {
105
306
  agents.set(agent.name, agent);
106
307
  }
107
308
  }
108
309
  }
109
310
 
110
- // Load project agents (overrides global)
311
+ // Project agents (override global + builtin)
111
312
  const projectDir = getProjectAgentsDir(cwd);
112
313
  if (existsSync(projectDir)) {
113
- const files = readdirSync(projectDir)
114
- .filter((f) => f.endsWith(".md"))
115
- .sort(compareCodeUnits);
116
- for (const file of files) {
117
- const agent = loadAgentFromFile(join(projectDir, file), "project");
314
+ for (const filePath of listAgentFilesRecursive(projectDir)) {
315
+ const agent = loadAgentFromFile(filePath, "project");
118
316
  if (agent) {
119
317
  agents.set(agent.name, agent);
120
318
  }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @pi-unipi/subagents — File-system retry ladder
3
+ *
4
+ * Ported from pi-subagents src/shared/file-system-retry.ts (the blocking
5
+ * waitForFileSystemRetry primitive + ladder constants). Env override uses OUR
6
+ * prefix: UNIPI_SUBAGENT_FS_RETRY_MAX_TOTAL_MS.
7
+ */
8
+
9
+ const WAIT_BUFFER = typeof SharedArrayBuffer !== "undefined" ? new SharedArrayBuffer(4) : undefined;
10
+ const WAIT_VIEW = WAIT_BUFFER ? new Int32Array(WAIT_BUFFER) : undefined;
11
+
12
+ export const FS_RETRY_MAX_TOTAL_MS_ENV = "UNIPI_SUBAGENT_FS_RETRY_MAX_TOTAL_MS";
13
+ export const BASE_FILE_SYSTEM_RETRY_DELAYS_MS = [10, 25, 50, 100, 200, 500, 1000, 2000, 4000] as const;
14
+
15
+ export function resolveFileSystemRetryDelays(
16
+ env: NodeJS.ProcessEnv = process.env,
17
+ base: readonly number[] = BASE_FILE_SYSTEM_RETRY_DELAYS_MS,
18
+ ): readonly number[] {
19
+ const raw = env[FS_RETRY_MAX_TOTAL_MS_ENV];
20
+ if (raw === undefined || raw.trim() === "") return base;
21
+ const budget = Number(raw);
22
+ if (!Number.isInteger(budget) || budget < 0) {
23
+ throw new Error(`${FS_RETRY_MAX_TOTAL_MS_ENV} must be a non-negative integer number of milliseconds.`);
24
+ }
25
+ let spent = 0;
26
+ return base.map((delay) => {
27
+ const remaining = budget - spent;
28
+ spent += delay;
29
+ if (remaining <= 0) return 0;
30
+ return Math.min(delay, remaining);
31
+ });
32
+ }
33
+
34
+ export const DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS = resolveFileSystemRetryDelays();
35
+
36
+ export function waitForFileSystemRetry(delayMs: number): void {
37
+ if (delayMs <= 0) return;
38
+ if (WAIT_VIEW) {
39
+ try {
40
+ Atomics.wait(WAIT_VIEW, 0, 0, delayMs);
41
+ return;
42
+ } catch {
43
+ // fall through to setTimeout-free busy wait fallback below
44
+ }
45
+ }
46
+ const end = Date.now() + delayMs;
47
+ while (Date.now() < end) {
48
+ // Blocking sleep fallback for runtimes without Atomics.wait
49
+ }
50
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * @pi-unipi/subagents — Async run summaries for the fleet panel
3
+ *
4
+ * Reads run dirs (status.json) into lightweight summaries. Ported essence of
5
+ * pi-subagents async-status.ts listAsyncRuns.
6
+ */
7
+
8
+ import * as fs from "node:fs";
9
+ import * as path from "node:path";
10
+ import { readStatus } from "./async-runner.js";
11
+
12
+ export interface AsyncRunSummary {
13
+ runId: string;
14
+ runDir: string;
15
+ agent: string;
16
+ state: string;
17
+ startedAt: number;
18
+ taskSummary?: string;
19
+ }
20
+
21
+ const MAX_CANDIDATES = 100;
22
+
23
+ /** List async runs (any state), newest first. */
24
+ export function listAsyncRunSummaries(asyncDirRoot: string): AsyncRunSummary[] {
25
+ let entries: fs.Dirent[];
26
+ try {
27
+ entries = fs.readdirSync(asyncDirRoot, { withFileTypes: true });
28
+ } catch {
29
+ return [];
30
+ }
31
+
32
+ const summaries: AsyncRunSummary[] = [];
33
+ for (const entry of entries.slice(0, MAX_CANDIDATES)) {
34
+ if (!entry.isDirectory()) continue;
35
+ const runDir = path.join(asyncDirRoot, entry.name);
36
+ const status = readStatus(runDir);
37
+ if (!status.status) continue;
38
+ summaries.push({
39
+ runId: entry.name,
40
+ runDir,
41
+ agent: typeof status.agent === "string" ? status.agent : "unknown",
42
+ state: String(status.status),
43
+ startedAt:
44
+ typeof status.startedAt === "number"
45
+ ? status.startedAt
46
+ : typeof status.updatedAt === "number"
47
+ ? status.updatedAt
48
+ : statMtime(runDir),
49
+ ...(typeof status.task === "string" ? { taskSummary: status.task.slice(0, 120) } : {}),
50
+ });
51
+ }
52
+ return summaries.sort((left, right) => right.startedAt - left.startedAt);
53
+ }
54
+
55
+ function statMtime(dir: string): number {
56
+ try {
57
+ return fs.statSync(dir).mtimeMs;
58
+ } catch {
59
+ return Date.now();
60
+ }
61
+ }