@ferris1225/pi-subagents 7.0.0 → 7.0.1

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.
@@ -13,7 +13,7 @@
13
13
  * through the same cross-process manifest lock as recovery records.
14
14
  */
15
15
 
16
- import { createHash, randomUUID } from "node:crypto";
16
+ import { randomUUID } from "node:crypto";
17
17
  import { replaceManifestFile, withManifestMutation } from "../isolation/manifest-mutation.ts";
18
18
  import { existsSync, type Dirent, readdirSync, statSync } from "node:fs";
19
19
  import { mkdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
@@ -71,8 +71,8 @@ export interface ThreadResultSummary {
71
71
  }
72
72
 
73
73
  export interface ThreadRecord {
74
- /** Stable identity across windows and locally renumbered restores. Absent in legacy records. */
75
- durableId?: string;
74
+ /** Stable identity across windows and locally renumbered restores. */
75
+ durableId: string;
76
76
  runId: number;
77
77
  createdAt: number;
78
78
  updatedAt: number;
@@ -102,11 +102,7 @@ function currentBootId(now = Date.now()): number {
102
102
  return Math.round(now - uptime() * 1_000);
103
103
  }
104
104
 
105
- /** Whether a record's `childPids` can still name processes of this boot. Pids
106
- * are only unique within a boot: after a restart the same number belongs to
107
- * whatever claimed it, so restore must not signal them. Records written before
108
- * this field existed carry no boot id and count as unverifiable; leaving a
109
- * stray child alive is safer than killing an unrelated process tree. */
105
+ /** Only verified process identities from this boot can authorize signaling. */
110
106
  export function isCurrentBoot(record: ThreadRecord, now = Date.now()): boolean {
111
107
  if (record.bootId === undefined) return false;
112
108
  return Math.abs(record.bootId - currentBootId(now)) <= BOOT_ID_TOLERANCE_MS;
@@ -158,18 +154,20 @@ function normalizeResultSummary(value: unknown): ThreadResultSummary | undefined
158
154
  function normalizeRecord(value: unknown): ThreadRecord | undefined {
159
155
  if (!value || typeof value !== "object") return undefined;
160
156
  const raw = value as Record<string, unknown>;
157
+ if (typeof raw.durableId !== "string" || !raw.durableId) throw new Error("Unsupported thread record: durableId is required. Recovery artifacts were left untouched.");
161
158
  if (typeof raw.runId !== "number" || !Number.isInteger(raw.runId) || raw.runId < 1) return undefined;
162
159
  if (typeof raw.createdAt !== "number" || !Number.isFinite(raw.createdAt)) return undefined;
163
160
  if (typeof raw.updatedAt !== "number" || !Number.isFinite(raw.updatedAt)) return undefined;
164
161
  if (typeof raw.agentName !== "string" || !raw.agentName) return undefined;
165
162
  if (typeof raw.task !== "string" || !raw.task) return undefined;
166
163
  if (typeof raw.cwd !== "string" || !raw.cwd) return undefined;
164
+ if (typeof raw.executionCwd !== "string" || !raw.executionCwd) return undefined;
167
165
  if (raw.isolation !== "shared" && raw.isolation !== "worktree") return undefined;
168
166
  if (raw.state !== "parked" && raw.state !== "completed" && raw.state !== "failed") return undefined;
169
167
  const worktree = raw.worktree === undefined ? undefined : normalizeWorktreeSnapshot(raw.worktree);
170
168
  if (worktree === null) return undefined;
171
169
  return {
172
- ...(typeof raw.durableId === "string" && raw.durableId ? { durableId: raw.durableId } : {}),
170
+ durableId: raw.durableId,
173
171
  runId: raw.runId,
174
172
  createdAt: raw.createdAt,
175
173
  updatedAt: raw.updatedAt,
@@ -177,7 +175,7 @@ function normalizeRecord(value: unknown): ThreadRecord | undefined {
177
175
  agentName: raw.agentName,
178
176
  task: raw.task,
179
177
  cwd: raw.cwd,
180
- executionCwd: typeof raw.executionCwd === "string" && raw.executionCwd ? raw.executionCwd : raw.cwd,
178
+ executionCwd: raw.executionCwd,
181
179
  ...(typeof raw.thinkingLevel === "string" && raw.thinkingLevel ? { thinkingLevel: raw.thinkingLevel } : {}),
182
180
  isolation: raw.isolation,
183
181
  state: raw.state,
@@ -201,8 +199,8 @@ interface ThreadManifestRead {
201
199
 
202
200
  async function readManifest(path: string): Promise<ThreadManifestRead> {
203
201
  try {
204
- const parsed = JSON.parse(await readFile(path, "utf8")) as { records?: unknown } | null;
205
- if (!Array.isArray(parsed?.records)) throw new Error(`Invalid thread manifest: ${path}`);
202
+ const parsed = JSON.parse(await readFile(path, "utf8")) as { version?: unknown; records?: unknown } | null;
203
+ if (parsed?.version !== THREADS_MANIFEST_VERSION || !Array.isArray(parsed.records)) throw new Error(`Invalid thread manifest: ${path}`);
206
204
  return {
207
205
  sourceCount: parsed.records.length,
208
206
  records: parsed.records.flatMap((record) => {
@@ -282,15 +280,6 @@ export async function isThreadSourceAvailable(record: ThreadRecord): Promise<boo
282
280
  }
283
281
  }
284
282
 
285
- /** Legacy identities include immutable source/artifact metadata, so adopting a
286
- * record does not let a fresh run with the same display id overwrite it. */
287
- export function threadRecordIdentity(record: ThreadRecord): string {
288
- return record.durableId ?? `legacy-${createHash("sha256").update(JSON.stringify([
289
- record.cwd, record.runId, record.createdAt, record.ownerPid, record.bootId,
290
- record.sessionDir, record.worktree?.tempDir,
291
- ])).digest("hex")}`;
292
- }
293
-
294
283
  async function validatedManifestRecords(
295
284
  configPath: string,
296
285
  path: string,
@@ -350,11 +339,10 @@ export async function upsertThreadRecord(configPath: string, record: ThreadRecor
350
339
  const path = getThreadsManifestPath(configPath, record.cwd);
351
340
  await withManifestMutation(path, async () => {
352
341
  const records = await readManifestRecords(path);
353
- const identity = threadRecordIdentity(record);
354
- const index = records.findIndex((candidate) => threadRecordIdentity(candidate) === identity);
342
+ const index = records.findIndex((candidate) => candidate.durableId === record.durableId);
355
343
  const merged: ThreadRecord = index === -1
356
- ? { ...record, durableId: identity }
357
- : { ...record, durableId: identity, createdAt: records[index]!.createdAt };
344
+ ? record
345
+ : { ...record, createdAt: records[index]!.createdAt };
358
346
  if (index === -1) records.push(merged);
359
347
  else records[index] = merged;
360
348
  await writeManifest(path, records);
@@ -365,7 +353,7 @@ export async function removeThreadRecord(configPath: string, identity: string, c
365
353
  const path = getThreadsManifestPath(configPath, cwd);
366
354
  await withManifestMutation(path, async () => {
367
355
  const records = await readManifestRecords(path);
368
- const next = records.filter((record) => threadRecordIdentity(record) !== identity);
356
+ const next = records.filter((record) => record.durableId !== identity);
369
357
  if (next.length === records.length) return;
370
358
  await writeManifest(path, next);
371
359
  });
@@ -418,7 +406,7 @@ export function threadRecordFromThread(
418
406
  elapsedMs: thread.elapsedMs,
419
407
  ...(thread.sessionId && thread.sessionDir ? { sessionId: thread.sessionId, sessionDir: thread.sessionDir } : {}),
420
408
  ...(worktree ? { worktree } : {}),
421
- childPids: thread.control?.getChildPids?.() ?? [],
409
+ childPids: thread.control.getChildPids(),
422
410
  ownerPid: process.pid,
423
411
  bootId: currentBootId(now),
424
412
  ...(thread.lastResult ? { resultSummary: summarizeResult(thread.lastResult) } : {}),
@@ -136,7 +136,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
136
136
  finalizationCompletion,
137
137
  new Promise<undefined>((resolve) => {
138
138
  const timer = setTimeout(() => resolve(undefined), CONTROL_QUIESCE_TIMEOUT_MS);
139
- if (typeof timer.unref === "function") timer.unref();
139
+ timer.unref();
140
140
  }),
141
141
  ]);
142
142
  } catch {
@@ -158,7 +158,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
158
158
  ...(existsSync(worktree.worktreePath) ? { worktreePath: worktree.worktreePath } : {}),
159
159
  ...(existsSync(worktree.patchPath) ? { patchPath: worktree.patchPath } : {}),
160
160
  error: "subagent_stop timed out waiting for worktree integration; it continues in the background",
161
- }, Date.now(), thread.durableId),
161
+ }, thread.durableId!),
162
162
  ]).catch(() => undefined);
163
163
  pendingIntegration.push(`#${runId}`);
164
164
  }
@@ -100,7 +100,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
100
100
  const originalCwd = resolve(cwd ?? runCtx.cwd);
101
101
  if (isolation === "worktree" && !isWriteCapableAgent(agent, toolInfos)) {
102
102
  return {
103
- ...failedStartResult(agentName, task, `Agent "${agentName}" is read-only; worktree isolation is available only to write-capable agents such as artisan.`),
103
+ ...failedStartResult(agentName, task, `Agent "${agentName}" is read-only; worktree isolation is available only to write-capable agents such as worker.`),
104
104
  isolation,
105
105
  };
106
106
  }
@@ -516,7 +516,7 @@ export function installThreadLifecycle(thread: SubagentThread, deps: ThreadLifec
516
516
  // Every retained finalization gets a durable recovery record, so the
517
517
  // artifacts stay findable even when the owning process dies next.
518
518
  void persistRecoveryRecords(runtime.configPath, [
519
- recoveryRecordFromFinalization(runId, finalization, Date.now(), thread.durableId),
519
+ recoveryRecordFromFinalization(runId, finalization, thread.durableId!),
520
520
  ]).catch(() => undefined);
521
521
  }
522
522
  return finalization;
@@ -11,7 +11,6 @@ import {
11
11
  readThreadRecords,
12
12
  removeThreadRecord,
13
13
  restoredResultFromSummary,
14
- threadRecordIdentity,
15
14
  type ThreadRecord,
16
15
  } from "./durable.ts";
17
16
  import { monitor } from "../presentation/monitor.ts";
@@ -38,7 +37,7 @@ import { installThreadLifecycle } from "./thread-lifecycle.ts";
38
37
  async function discardRestoredRecord(runtime: SubagentRuntime, record: ThreadRecord): Promise<void> {
39
38
  await discardRecordArtifacts(record);
40
39
  if (record.sessionDir) runtime.sessionDirs.delete(record.sessionDir);
41
- await removeThreadRecord(runtime.configPath, threadRecordIdentity(record), record.cwd).catch(() => undefined);
40
+ await removeThreadRecord(runtime.configPath, record.durableId, record.cwd).catch(() => undefined);
42
41
  }
43
42
 
44
43
  function createRestoredThread(
@@ -48,7 +47,7 @@ function createRestoredThread(
48
47
  state: ThreadState,
49
48
  ): SubagentThread {
50
49
  const thread: SubagentThread = {
51
- durableId: threadRecordIdentity(record),
50
+ durableId: record.durableId,
52
51
  id: record.runId,
53
52
  generation: record.generation,
54
53
  agentName: record.agentName,
@@ -80,15 +79,14 @@ function belongsToSessionProject(configPath: string, cwd: string, record: Thread
80
79
  * Other projects' parked threads stay on disk for their own window; this process
81
80
  * must not restore them or kill their children. Records with a live owner or
82
81
  * child are left alone; missing session files do not discard isolated
83
- * edits. Already-settled records from older versions are removed with their
84
- * managed artifacts. */
82
+ * edits. Settled records are removed with their managed artifacts. */
85
83
  export async function restoreDurableThreads(runtime: SubagentRuntime, cwd: string): Promise<number[]> {
86
84
  const records = await readThreadRecords(runtime.configPath);
87
85
  const restoredIds: number[] = [];
88
86
  const localRecords = records.filter((record) => belongsToSessionProject(runtime.configPath, cwd, record));
89
87
  for (const record of localRecords) monitor.ensureNextIdAbove(record.runId);
90
88
  for (let record of localRecords) {
91
- const identity = threadRecordIdentity(record);
89
+ const identity = record.durableId;
92
90
  if ([...runtime.threads.values()].some((thread) => thread.durableId === identity)) continue;
93
91
  // Another Pi window may own this checkpoint, and PID reuse means a live
94
92
  // recorded child is not proof of ownership. Never kill either on restore.
@@ -5,8 +5,8 @@ import { realpath } from "node:fs/promises";
5
5
  import { join, resolve } from "node:path";
6
6
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
7
7
  import type { AgentConfig } from "../delegation/agents.ts";
8
- import type { SubagentsConfig, ThinkingLevel } from "../configuration/config.ts";
9
- import { removeThreadRecord, threadRecordFromThread, threadRecordIdentity, upsertThreadRecord } from "./durable.ts";
8
+ import { BUILTIN_AGENT_NAMES, type AgentName, type SubagentsConfig, type ThinkingLevel } from "../configuration/config.ts";
9
+ import { removeThreadRecord, threadRecordFromThread, upsertThreadRecord } from "./durable.ts";
10
10
  import {
11
11
  availableModelsInScope,
12
12
  currentModelRef,
@@ -32,7 +32,7 @@ export function quiesced(promise: Promise<unknown>, timeoutMs: number = CONTROL_
32
32
  promise.then(() => true, () => true),
33
33
  new Promise<boolean>((resolve) => {
34
34
  const timer = setTimeout(() => resolve(false), timeoutMs);
35
- if (typeof timer.unref === "function") timer.unref();
35
+ timer.unref();
36
36
  }),
37
37
  ]);
38
38
  }
@@ -98,7 +98,7 @@ export function persistThreadCheckpoint(
98
98
  const record = threadRecordFromThread(thread, state);
99
99
  const write = state === "parked"
100
100
  ? upsertThreadRecord(runtime.configPath, record)
101
- : removeThreadRecord(runtime.configPath, threadRecordIdentity(record), thread.cwd);
101
+ : removeThreadRecord(runtime.configPath, record.durableId, thread.cwd);
102
102
  void write.catch(() => undefined);
103
103
  }
104
104
 
@@ -152,10 +152,12 @@ export function resolveDispatchModelRoute(
152
152
  config: SubagentsConfig,
153
153
  ctx: ExtensionContext,
154
154
  ): DispatchModelRoute {
155
+ if (!(BUILTIN_AGENT_NAMES as readonly string[]).includes(agent.name)) throw new Error(`Unknown subagent role: ${agent.name}`);
156
+ const settings = config[agent.name as AgentName];
155
157
  const availableModels = availableModelsInScope(ctx);
156
158
  const mainRef = currentModelRef(ctx);
157
159
  const route = resolveAgentModelRoute({
158
- selectedRef: config.model,
160
+ selectedRef: settings.model,
159
161
  mainRef,
160
162
  availableRefs: availableModels.map(modelRef),
161
163
  });
@@ -163,8 +165,8 @@ export function resolveDispatchModelRoute(
163
165
  ? ctx.model : findModelByRef(availableModels, route.primaryRef);
164
166
  return {
165
167
  agent: { ...agent, model: route.primaryRef },
166
- thinkingLevel: resolveThinkingLevel(model, config.thinking),
167
- ...(route.unavailableSelectedRef ? { error: `Worker model ${route.unavailableSelectedRef} is unavailable in this session. Dispatch paused; restore availability or choose a worker with /subagents-setup. No main-model worker was started.` } : {}),
168
+ thinkingLevel: resolveThinkingLevel(model, settings.thinking),
169
+ ...(route.unavailableSelectedRef ? { error: `${agent.name} model ${route.unavailableSelectedRef} is unavailable in this session. Dispatch paused; restore availability or choose another model with /subagents-setup. No main-model worker was started.` } : {}),
168
170
  };
169
171
  }
170
172
 
@@ -189,7 +189,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
189
189
  pi.registerTool({
190
190
  name: "subagent_message",
191
191
  label: "Subagent Message",
192
- description: "Steer a running subagent, or continue a successfully completed run with a new bounded step in the same role and workspace. Steering waits for the child's RPC acknowledgement and reports queued, handled by an input hook, or accepted with queue state unknown; receipt is not proof of model execution, and status retains the latest acknowledgement. A continuation chooses its history with the context parameter. Use wait:true to receive its result in this call; one-shot print/JSON sessions wait by default.",
192
+ description: "Steer a running subagent, or continue a successfully completed run with a new bounded step in the same role and workspace. Steering waits for the child's RPC acknowledgement and reports queued or handled by an input hook; receipt is not proof of model execution, and status retains the latest acknowledgement. A continuation chooses its history with the context parameter. Use wait:true to receive its result in this call; one-shot print/JSON sessions wait by default.",
193
193
  exposure: "model-only",
194
194
  executionMode: "parallel",
195
195
  parameters: Type.Object({
@@ -210,9 +210,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
210
210
  thread.lastSteering = { ...receipt, message: formatTaskSummary(params.message, 160, false) };
211
211
  const status = receipt.disposition === "queued"
212
212
  ? `Received by #${thread.id} · queued for the next steering boundary. Model execution is not yet confirmed.`
213
- : receipt.disposition === "handled"
214
- ? `Received by #${thread.id} · handled by an input hook. Delivery to the model is not confirmed.`
215
- : `Accepted by #${thread.id} · queue state unconfirmed. Model execution is not yet confirmed.`;
213
+ : `Received by #${thread.id} · handled by an input hook. Delivery to the model is not confirmed.`;
216
214
  monitor.setActivity(thread.id, `steering ${receipt.disposition}`);
217
215
  return {
218
216
  content: [{ type: "text" as const, text: `${status}${receipt.requestId ? `\nChild RPC acknowledgement: ${receipt.requestId}` : ""}` }],
@@ -1,10 +1,10 @@
1
1
  /** Session-start recovery, worker availability, and progress-surface installation. */
2
2
 
3
3
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
- import { loadConfig, saveConfig } from "../configuration/config.ts";
5
- import { findModelByRef, modelRef } from "../configuration/models.ts";
4
+ import { BUILTIN_AGENT_NAMES, loadConfig } from "../configuration/config.ts";
5
+ import { findModelByRef } from "../configuration/models.ts";
6
6
  import { ensureDefaultConfig } from "../configuration/setup.ts";
7
- import { announceRecoveryRecords, relocateRecoveryManifest } from "../isolation/recovery.ts";
7
+ import { announceRecoveryRecords } from "../isolation/recovery.ts";
8
8
  import type { SubagentRuntime } from "../lifecycle/runtime.ts";
9
9
  import { installActiveRunsWidget } from "./widget.ts";
10
10
 
@@ -15,18 +15,15 @@ async function checkWorkerModel(
15
15
  ): Promise<void> {
16
16
  try {
17
17
  const config = await loadConfig(runtime.configPath);
18
- if (!config.model) return;
19
- const selected = findModelByRef(ctx.modelRegistry.getAvailable(), config.model);
20
- const liveRef = selected ? modelRef(selected) : undefined;
21
- if (liveRef === config.model) return;
22
- if (liveRef) {
23
- await saveConfig({ ...config, model: liveRef }, runtime.configPath);
24
- return;
18
+ const models = ctx.modelRegistry.getAvailable();
19
+ for (const role of BUILTIN_AGENT_NAMES) {
20
+ const ref = config[role].model;
21
+ if (!ref || findModelByRef(models, ref)) continue;
22
+ ctx.ui.notify(
23
+ `pi-subagents: ${role} model ${ref} is unavailable. Its setting is preserved and dispatch is paused for this role. Restore availability or run /subagents-setup to choose another.`,
24
+ "warning",
25
+ );
25
26
  }
26
- ctx.ui.notify(
27
- `pi-subagents: worker model ${config.model} is unavailable. Its setting is preserved and dispatch is paused. Restore availability or run /subagents-setup to choose another.`,
28
- "warning",
29
- );
30
27
  } catch {
31
28
  /* availability notices are non-fatal */
32
29
  }
@@ -36,7 +33,6 @@ export function registerAnnouncements(pi: ExtensionAPI, runtime: SubagentRuntime
36
33
  pi.on("session_start", async (_event, ctx) => {
37
34
  await ensureDefaultConfig(ctx, runtime.configPath);
38
35
  try {
39
- await relocateRecoveryManifest(runtime.configPath);
40
36
  await announceRecoveryRecords(runtime.configPath, ctx);
41
37
  } catch (error) {
42
38
  // Recovery readers must fail closed for cleanup, but a failed notice
@@ -164,7 +164,7 @@ export function formatCompletionBlock(
164
164
  );
165
165
  }
166
166
  if (failed && isModelLevelFailure(result)) lines.push("", modelLevelTakeoverNote(result));
167
- if (!failed && result.agent === "artisan") {
167
+ if (!failed && result.agent === "worker") {
168
168
  lines.push("", "Review handoff: main. Worker completion is not review approval. Inspect the actual diff, affected callers, acceptance criteria, and check evidence. Send confirmed corrections to the owning worker with subagent_message; main owns acceptance and release.");
169
169
  }
170
170
  return lines.join("\n");
@@ -161,7 +161,7 @@ function tailGraphemes(segments: string[], maxWidth: number): string {
161
161
  * One-line task preview, capped by `maxWidth` display columns (default 80).
162
162
  * `keysOnly` (default): extracted key fragments (paths, quoted phrases,
163
163
  * symbols) are shown bare — the agent name is already displayed next to the
164
- * task line, so templated prose ("scout: trace how ...") adds nothing.
164
+ * task line, so templated prose ("researcher: trace how ...") adds nothing.
165
165
  * `keysOnly: false` keeps the prose as `head…tail` (used for completion
166
166
  * messages, where the Task line is the reader's only context).
167
167
  * Grapheme-safe — CJK, ZWJ emoji and combining sequences are never split.
@@ -303,13 +303,8 @@ export function formatDuration(ms: number): string {
303
303
  }
304
304
 
305
305
  function elapsedMilliseconds(run: RunView, now: number = Date.now()): number {
306
- let elapsed = run.elapsedMs ?? 0;
306
+ let elapsed = run.elapsedMs;
307
307
  if (run.activeSince !== undefined) elapsed += Math.max(0, now - run.activeSince);
308
- // Keep formatting tolerant of older/synthetic RunView values that predate
309
- // segmented timing and carry only startedAt/endedAt.
310
- if (elapsed === 0 && run.startedAt !== undefined && run.activeSince === undefined) {
311
- elapsed = Math.max(0, (run.endedAt ?? now) - run.startedAt);
312
- }
313
308
  return elapsed;
314
309
  }
315
310