@justjoshn/pi-pstack 0.15.36-pi.12 → 0.15.36-pi.14

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.
@@ -2,6 +2,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, w
2
2
  import { join } from 'node:path';
3
3
 
4
4
  import { parseSessionEntries, SessionManager } from '@earendil-works/pi-coding-agent';
5
+ import { acquireLease, alive } from '../process-lock.ts';
5
6
  import type { ModelSpec } from './models.ts';
6
7
  import type { Worktree } from './worktree.ts';
7
8
 
@@ -142,15 +143,6 @@ export function recordIds(dir: string): string[] {
142
143
  .map((name) => name.slice(0, -'.json'.length));
143
144
  }
144
145
 
145
- function alive(pid: number): boolean {
146
- try {
147
- process.kill(pid, 0);
148
- return true;
149
- } catch (error) {
150
- return (error as NodeJS.ErrnoException).code === 'EPERM';
151
- }
152
- }
153
-
154
146
  const isPid = (value: number) => Number.isInteger(value) && value > 0;
155
147
 
156
148
  /** The live pid the agent's run lock names, or undefined when no live process holds it. */
@@ -198,33 +190,46 @@ export interface RunLock {
198
190
  /**
199
191
  * Pi appends to a session file without a lock, so two processes on one agent ID would interleave its transcript.
200
192
  * The lock file holds the pid of the process writing the transcript. A lock without a readable pid counts as held.
201
- * A dead holder's lock is removed only if it still names that holder, then created again exclusively; two
202
- * processes taking over the same stale lock in the narrow window between that re-read and the removal can both succeed.
193
+ * A token-directory lease serializes acquisition and stale recovery without changing the PID file read by stop/status.
203
194
  */
204
195
  export function acquireRunLock(dir: string, agentId: string): RunLock {
205
196
  mkdirSync(dir, { recursive: true, mode: 0o700 });
206
197
  const path = join(dir, `${agentId}.lock`);
207
- for (let attempt = 0; attempt < 2; attempt += 1) {
208
- if (createExclusive(path)) {
209
- let owner = process.pid;
210
- return {
211
- holdFor: (pid) => {
212
- writeAtomically(path, String(pid));
213
- owner = pid;
214
- },
215
- // Best effort: a lock left behind names a pid that will be dead, so the next acquire takes it over.
216
- release: () => {
217
- try {
218
- if (holderOf(path) === owner) rmSync(path, { force: true });
219
- } catch (error) {
220
- if (!['EACCES', 'EPERM', 'EROFS', 'EBUSY', 'EIO'].includes((error as NodeJS.ErrnoException).code ?? '')) throw error;
221
- }
222
- },
223
- };
198
+ const lease = acquireLease(`${path}.owner`);
199
+ if (lease === undefined) throw stillRunning(agentId, runningPid(dir, agentId), path);
200
+ let acquired = false;
201
+ try {
202
+ for (let attempt = 0; attempt < 2; attempt += 1) {
203
+ if (createExclusive(path)) {
204
+ acquired = true;
205
+ let owner = process.pid;
206
+ return {
207
+ holdFor: (pid) => {
208
+ writeAtomically(path, String(pid));
209
+ owner = pid;
210
+ },
211
+ release: () => {
212
+ for (const release of [
213
+ () => {
214
+ if (holderOf(path) === owner) rmSync(path, { force: true });
215
+ },
216
+ lease.release,
217
+ ]) {
218
+ try {
219
+ release();
220
+ } catch (error) {
221
+ if (!['EACCES', 'EPERM', 'EROFS', 'EBUSY', 'EIO'].includes((error as NodeJS.ErrnoException).code ?? '')) throw error;
222
+ }
223
+ }
224
+ },
225
+ };
226
+ }
227
+ const holder = holderOf(path);
228
+ if (holder !== undefined && (!isPid(holder) || alive(holder))) throw stillRunning(agentId, holder, path);
229
+ if (holder !== undefined && holderOf(path) === holder) rmSync(path, { force: true });
224
230
  }
225
- const holder = holderOf(path);
226
- if (holder !== undefined && (!isPid(holder) || alive(holder))) throw stillRunning(agentId, holder, path);
227
- if (holder !== undefined && holderOf(path) === holder) rmSync(path, { force: true });
231
+ throw stillRunning(agentId, holderOf(path), path);
232
+ } finally {
233
+ if (!acquired) lease.release();
228
234
  }
229
- throw stillRunning(agentId, holderOf(path), path);
230
235
  }
package/src/task/tool.ts CHANGED
@@ -5,7 +5,7 @@ import { isAbsolute, join, relative } from 'node:path';
5
5
  import { getSupportedThinkingLevels } from '@earendil-works/pi-ai';
6
6
  import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
7
7
  import { type Static, Type } from 'typebox';
8
- import { childIdentity, childVariables } from '../child-env.ts';
8
+ import { BUILD_PLAN_ENV, childIdentity, childVariables } from '../child-env.ts';
9
9
  import { rootStoreDir, subagentDir, workspaceStateDir, worktreesDir } from '../paths.ts';
10
10
  import { piCommand } from '../pi-command.ts';
11
11
  import { type AgentDefinition, findAgent } from './agents.ts';
@@ -111,6 +111,7 @@ export interface Launch {
111
111
  attachments: string[];
112
112
  notes: string[];
113
113
  description: string;
114
+ buildPlan?: string;
114
115
  }
115
116
 
116
117
  const runsReadonly = (plan: Launch) => plan.readonly || plan.planMode;
@@ -269,7 +270,11 @@ export function planFork(params: TaskInput, ctx: ExtensionContext, agents: reado
269
270
 
270
271
  function launchChild(plan: Launch, input: ChildInput, signal: AbortSignal | undefined, onEvent?: (event: { type: string } & Record<string, unknown>) => void) {
271
272
  const readonly = runsReadonly(plan);
272
- const env = { ...process.env, ...childVariables(plan.agent.type, plan.depth, readonly, plan.rootStore, workspaceStateDir(plan.workspace), plan.rootWorkspace) };
273
+ const env = {
274
+ ...process.env,
275
+ ...childVariables(plan.agent.type, plan.depth, readonly, plan.rootStore, workspaceStateDir(plan.workspace), plan.rootWorkspace),
276
+ ...(plan.buildPlan === undefined ? {} : { [BUILD_PLAN_ENV]: plan.buildPlan }),
277
+ };
273
278
  const transcript = plan.kind === 'fresh' || readonly ? undefined : transcriptFor(subagentDir(plan.workspace), plan.agentId);
274
279
  const restoreTools = transcript === undefined ? [] : readonlyLaunchRestores(transcript);
275
280
  const args = childArgs({
@@ -501,6 +506,8 @@ export interface StartBackgroundOptions {
501
506
  environment?: 'cloud';
502
507
  /** The owner's project-trust decision, used when this subscription fire starts away from its chat. */
503
508
  trusted?: boolean;
509
+ /** Imports the reviewed plan's todos into the worker before its first model request. */
510
+ buildPlan?: string;
504
511
  }
505
512
 
506
513
  export interface TaskHandle {
@@ -582,6 +589,7 @@ export function registerTask(pi: ExtensionAPI, options: TaskToolOptions): TaskHa
582
589
  taskPreflight(params, options.depth);
583
590
  const { plan, lock } = prepare(params, ctx, options, registry.isRunning);
584
591
  if (startOptions?.trusted !== undefined) plan.trusted = startOptions.trusted;
592
+ if (startOptions?.buildPlan !== undefined) plan.buildPlan = startOptions.buildPlan;
585
593
  await createWorktree(plan, lock, undefined);
586
594
  const handle = start(plan, { text: prompt.trim(), images: [] }, undefined, lock);
587
595
  registry.track(plan.agentId, handle, lock.release, runsReadonly(plan), backgroundNotice(plan, prompt, description, ctx, `pstack-${plan.agentId}`));
package/src/todo.ts CHANGED
@@ -8,18 +8,21 @@ export interface TodoItem {
8
8
  id: string;
9
9
  content: string;
10
10
  status: TodoStatus;
11
+ dependencies?: string[];
11
12
  }
12
13
 
13
14
  export interface TodoInput {
14
15
  id: string;
15
16
  content?: string;
16
17
  status?: TodoStatus;
18
+ dependencies?: string[];
17
19
  }
18
20
 
19
21
  interface TodoDetails {
20
22
  todos: TodoItem[];
21
23
  }
22
24
 
25
+ const TODO_ENTRY = 'pstack/todos';
23
26
  const WIDGET_KEY = 'pstack-todos';
24
27
  const MARKS: Record<TodoStatus, string> = { pending: '[ ]', in_progress: '[>]', completed: '[x]', cancelled: '[-]' };
25
28
  const GLYPHS: Record<TodoStatus, string> = { pending: '○', in_progress: '▶', completed: '✓', cancelled: '✗' };
@@ -43,7 +46,8 @@ function complete(item: TodoInput, existing: TodoItem | undefined): TodoItem {
43
46
  const content = item.content ?? existing?.content;
44
47
  const status = item.status ?? existing?.status;
45
48
  if (content === undefined || status === undefined) throw new Error(`Todo "${item.id}" is new, so it needs both content and status.`);
46
- return { id: item.id, content, status };
49
+ const dependencies = item.dependencies ?? existing?.dependencies;
50
+ return { id: item.id, content, status, ...(dependencies === undefined ? {} : { dependencies }) };
47
51
  }
48
52
 
49
53
  /** TodoWrite: merge updates by id and appends new ids; otherwise the call replaces the list. */
@@ -68,18 +72,25 @@ export function formatTodos(todos: readonly TodoItem[]): string {
68
72
  const done = todos.filter((item) => item.status === 'completed').length;
69
73
  const active = todos.filter((item) => item.status === 'in_progress').length;
70
74
  const header = `Todos (${done}/${todos.length} completed${active > 0 ? `, ${active} in progress` : ''}):`;
71
- return [header, ...todos.map((item) => `${MARKS[item.status]} ${item.id}: ${item.content}`)].join('\n');
75
+ return [header, ...todos.map((item) => `${MARKS[item.status]} ${item.id}: ${item.content}${item.dependencies === undefined || item.dependencies.length === 0 ? '' : ` (depends on ${item.dependencies.join(', ')})`}`)].join('\n');
72
76
  }
73
77
 
74
78
  interface BranchEntry {
75
79
  type: string;
80
+ customType?: string;
81
+ data?: unknown;
76
82
  message?: { role?: string; toolName?: string; isError?: boolean; details?: unknown };
77
83
  }
78
84
 
79
- /** The list as of the active branch: the details of the last successful TodoWrite on it. A failed call stores `details: {}`. */
85
+ /** The list as of the active branch, from a plan import or the last successful TodoWrite. */
80
86
  export function todosFromBranch(entries: readonly BranchEntry[]): TodoItem[] {
81
87
  for (let index = entries.length - 1; index >= 0; index -= 1) {
82
- const message = entries[index]?.message;
88
+ const entry = entries[index];
89
+ if (entry?.type === 'custom' && entry.customType === TODO_ENTRY) {
90
+ const todos = (entry.data as Partial<TodoDetails> | undefined)?.todos;
91
+ if (Array.isArray(todos)) return todos;
92
+ }
93
+ const message = entry?.message;
83
94
  const todos = (message?.details as Partial<TodoDetails> | undefined)?.todos;
84
95
  if (entries[index]?.type === 'message' && message?.role === 'toolResult' && message.toolName === 'TodoWrite' && message.isError !== true && Array.isArray(todos)) return todos;
85
96
  }
@@ -116,7 +127,7 @@ const TODO_DESCRIPTION = [
116
127
  'Prefer creating the first todo as in_progress, and start on it with tool calls in the same batch as the write. Batch todo updates with your other tool calls.',
117
128
  ].join('\n');
118
129
 
119
- export function registerTodoWrite(pi: ExtensionAPI): { section: () => string | undefined } {
130
+ export function registerTodoWrite(pi: ExtensionAPI, options: { onWrite?: (todos: readonly TodoItem[]) => void } = {}) {
120
131
  let todos: TodoItem[] = [];
121
132
  const show = (ctx: ExtensionContext) => {
122
133
  if (ctx.hasUI) ctx.ui.setWidget(WIDGET_KEY, widgetLines(todos));
@@ -139,9 +150,21 @@ export function registerTodoWrite(pi: ExtensionAPI): { section: () => string | u
139
150
  annotations: { readOnlyHint: true, openWorldHint: false },
140
151
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
141
152
  todos = applyTodoWrite(todos, params.todos, params.merge);
153
+ try {
154
+ options.onWrite?.(todos);
155
+ } catch (error) {
156
+ ctx.ui.notify(`The todo list was updated, but its plan file could not be synchronized: ${error instanceof Error ? error.message : String(error)}`, 'warning');
157
+ }
142
158
  show(ctx);
143
159
  return { content: [{ type: 'text', text: formatTodos(todos) }], details: { todos } };
144
160
  },
145
161
  });
146
- return { section: () => todoSection(todos) };
162
+ return {
163
+ section: () => todoSection(todos),
164
+ replace: (items: readonly TodoItem[], ctx: ExtensionContext) => {
165
+ todos = applyTodoWrite([], items, false);
166
+ pi.appendEntry(TODO_ENTRY, { todos });
167
+ show(ctx);
168
+ },
169
+ };
147
170
  }