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

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.
@@ -11,18 +11,54 @@ export interface AgentDefinition {
11
11
  model?: string;
12
12
  readonly: boolean;
13
13
  background: boolean;
14
+ /** False for a type that never launches subagents of its own, such as Cursor's built-in explore. */
15
+ spawns?: boolean;
16
+ /** Pi tools this type turns on beyond Pi's defaults, such as explore's search tools. */
17
+ tools?: readonly string[];
14
18
  prompt: string;
15
19
  file?: string;
16
20
  }
17
21
 
18
22
  export const GENERAL_PURPOSE: AgentDefinition = {
19
23
  type: 'generalPurpose',
20
- description: 'General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. Use when a search or task needs several steps of its own.',
24
+ description: "General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. Use when searching for a keyword or file and not confident you'll find the match quickly.",
21
25
  readonly: false,
22
26
  background: false,
23
27
  prompt: '',
24
28
  };
25
29
 
30
+ /**
31
+ * Cursor's built-in codebase explorer: a file-search specialist that the caller tells how thorough to be, and that has
32
+ * no Task tool of its own.
33
+ */
34
+ export const EXPLORE: AgentDefinition = {
35
+ type: 'explore',
36
+ description:
37
+ 'Fast agent specialized for exploring codebases. Use it to find files by pattern (such as "src/components/**/*.tsx"), search code for keywords (such as "API endpoints"), or answer questions about the codebase (such as "how do API endpoints work?"). When you call it, name the thoroughness you want: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for a comprehensive search across many locations and naming conventions.',
38
+ readonly: false,
39
+ background: false,
40
+ spawns: false,
41
+ tools: ['grep', 'find', 'ls'],
42
+ prompt: [
43
+ 'You are a file search specialist. You navigate and explore codebases thoroughly.',
44
+ '',
45
+ 'You are good at:',
46
+ '- finding files fast with glob patterns (find)',
47
+ '- searching code and text with regular expressions (grep)',
48
+ '- reading and analyzing file contents (read)',
49
+ '',
50
+ 'Guidelines:',
51
+ '- Match how hard you search to the thoroughness the caller asked for.',
52
+ '- Give file paths as absolute paths in your final response.',
53
+ '- Do not use emojis.',
54
+ '- Send your final report directly as a regular message.',
55
+ '',
56
+ 'You are meant to be fast and to return as soon as you can. Use your tools efficiently: think about where the files and implementations are likely to be, and run several grep and read calls in parallel wherever you can.',
57
+ '',
58
+ "Complete the caller's search request efficiently and report your findings clearly.",
59
+ ].join('\n'),
60
+ };
61
+
26
62
  function parseAgentFile(file: string): AgentDefinition {
27
63
  const { frontmatter, body } = parseFrontmatter(readFileSync(file, 'utf8'));
28
64
  const name = frontmatter['name'];
@@ -39,12 +75,12 @@ function parseAgentFile(file: string): AgentDefinition {
39
75
  };
40
76
  }
41
77
 
42
- /** generalPurpose first, then every `*.md` agent file in `dir` sorted by file name. */
78
+ /** The built-in types (generalPurpose, explore) first, as Cursor lists them, then every `*.md` agent file in `dir` sorted by file name. */
43
79
  export function loadAgentDefinitions(dir: string = AGENTS_DIR): AgentDefinition[] {
44
80
  const files = readdirSync(dir)
45
81
  .filter((name) => name.endsWith('.md'))
46
82
  .toSorted();
47
- return [GENERAL_PURPOSE, ...files.map((name) => parseAgentFile(join(dir, name)))];
83
+ return [GENERAL_PURPOSE, EXPLORE, ...files.map((name) => parseAgentFile(join(dir, name)))];
48
84
  }
49
85
 
50
86
  export function findAgent(agents: readonly AgentDefinition[], type: string | undefined): AgentDefinition {
package/src/task/card.ts CHANGED
@@ -35,6 +35,7 @@ interface NotificationCardDetails {
35
35
  status: 'success' | 'error';
36
36
  agentId: string;
37
37
  title: string;
38
+ description?: string;
38
39
  detail: string;
39
40
  }
40
41
 
@@ -49,10 +50,11 @@ export function taskNotificationCardText(message: { content: string | { type: st
49
50
  const lines = raw.split('\n');
50
51
  return (expanded || lines.length <= COLLAPSED_LINES ? lines : [...lines.slice(0, COLLAPSED_LINES), `… ${lines.length - COLLAPSED_LINES} more lines`]).join('\n');
51
52
  }
52
- const { title, status, agentId, detail } = message.details;
53
+ const { title, description, status, agentId, detail } = message.details;
53
54
  const lines = detail.split('\n');
54
55
  const body = expanded || lines.length <= COLLAPSED_LINES ? lines : [...lines.slice(0, COLLAPSED_LINES), `… ${lines.length - COLLAPSED_LINES} more lines`];
55
- const head = `${title.trim() === '' ? 'subagent' : title.trim()} · ${status} · agent ${agentId}`;
56
+ const name = [description, title].map((value) => value?.trim() ?? '').find((value) => value !== '') ?? 'subagent';
57
+ const head = `${name} · ${status} · agent ${agentId}`;
56
58
  return [head, ...body].join('\n');
57
59
  }
58
60
 
@@ -28,7 +28,7 @@ export function bounded(text: string, transcript: string | undefined): string {
28
28
  return `${result.content}\n[truncated: showing ${result.outputLines} of ${result.totalLines} lines${size}; ${where}]`;
29
29
  }
30
30
 
31
- const agentIdLine = (agentId: string) => `Agent ID: ${agentId} (pass it as \`resume\` to send a follow-up after it completes)`;
31
+ const agentIdLine = (agentId: string) => `Agent ID: ${agentId} (can be used with the \`resume\` parameter to send a follow-up after it completes)`;
32
32
  const transcriptLine = (transcript: string | undefined) => (transcript === undefined ? [] : [`Transcript: ${transcript}`]);
33
33
 
34
34
  export function foregroundText(agentId: string, response: string, transcript: string | undefined, notes: readonly string[] = []): string {
@@ -37,7 +37,7 @@ export function foregroundText(agentId: string, response: string, transcript: st
37
37
 
38
38
  export function backgroundText(agentId: string, transcript: string | undefined, notes: readonly string[] = []): string {
39
39
  return [
40
- 'Subagent is running in the background. Its final response arrives automatically after your turn ends, so do not wait or poll for it. End your turn or work on something else.',
40
+ "Subagent is running in the background. When you end your turn, you will be automatically sent the subagent's final response upon its completion, so do not wait for it - either end your turn or work on something else.",
41
41
  '',
42
42
  agentIdLine(agentId),
43
43
  ...transcriptLine(transcript),
@@ -65,16 +65,28 @@ export function worktreePreface(worktree: Worktree, prompt: string): string {
65
65
  export interface NotificationFields {
66
66
  status: 'success' | 'error';
67
67
  agentId: string;
68
+ /** The model-facing title, from the prompt as Cursor writes it. */
68
69
  title: string;
70
+ /** The Task description, which names the subagent in the UI. */
71
+ description?: string;
69
72
  toolCallId: string;
70
73
  detail: string;
71
74
  /** What the background child spent. It stays in the notification details, because Pi gives extensions no way to add it to session totals. */
72
75
  usage?: Usage;
73
76
  }
74
77
 
78
+ const TITLE_LIMIT = 80;
79
+
80
+ /** Cursor titles a completion by its prompt: the first non-empty line, cut at 80 characters. */
81
+ export function notificationTitle(prompt: string): string {
82
+ const line = prompt.split('\n').find((candidate) => candidate.trim() !== '') ?? '';
83
+ return line.trim().slice(0, TITLE_LIMIT);
84
+ }
85
+
75
86
  export function notificationText(fields: NotificationFields): string {
76
87
  return [
77
- 'The following task has finished. If you already handled it, ignore this notification and do not restate earlier responses.',
88
+ '<system_notification>',
89
+ 'The following task has finished. If you were already aware, ignore this notification and do not restate prior responses.',
78
90
  '',
79
91
  '<task>',
80
92
  'kind: subagent',
@@ -84,5 +96,7 @@ export function notificationText(fields: NotificationFields): string {
84
96
  `tool_call_id: ${fields.toolCallId}`,
85
97
  `detail: ${fields.detail}`,
86
98
  '</task>',
99
+ '</system_notification>',
100
+ "Perform any necessary follow-up actions in response to the subagent completion above. If no follow-up work is needed, no further action is required. If you mention an agent or subagent in your response, link it with the `[Name](id)` Don't use generic label such as `[agent]`, `[worker]`, or `[subagent]`. Don't repeat the same confirmation every time.",
87
101
  ].join('\n');
88
102
  }
@@ -15,6 +15,7 @@ interface Running {
15
15
 
16
16
  export interface BackgroundNotice {
17
17
  title: string;
18
+ description: string;
18
19
  toolCallId: string;
19
20
  mode: ExtensionContext['mode'];
20
21
  detailFor: (outcome: ChildOutcome) => Pick<NotificationFields, 'status' | 'detail' | 'usage'>;
@@ -42,7 +43,7 @@ export function createSubagentRegistry(pi: ExtensionAPI) {
42
43
  release();
43
44
  // Shutdown killed this child; the retired runtime's pi must not be touched.
44
45
  if (retired || notice === undefined) return;
45
- deliver({ ...notice.detailFor(outcome), agentId, title: notice.title, toolCallId: notice.toolCallId }, notice.mode);
46
+ deliver({ ...notice.detailFor(outcome), agentId, title: notice.title, description: notice.description, toolCallId: notice.toolCallId }, notice.mode);
46
47
  });
47
48
  running.set(agentId, { settled, handle, readonly, background: notice !== undefined });
48
49
  };
@@ -31,10 +31,13 @@ export interface ChildArgsOptions {
31
31
  restoreTools?: readonly string[];
32
32
  /** The parent's project trust, so the child loads the same project resources (`ctx.isProjectTrusted()`). */
33
33
  trusted?: boolean;
34
+ /** Tools the agent type adds to Pi's default loadout (explore's search tools). */
35
+ addTools?: readonly string[];
34
36
  }
35
37
 
36
38
  /** Argv for one `pi --mode rpc` subagent process. Its prompts travel as RPC commands on stdin, never in argv. */
37
39
  export function childArgs(options: ChildArgsOptions): string[] {
40
+ const extraTools = [...new Set([...(options.restoreTools ?? []), ...(options.addTools ?? [])])];
38
41
  const model = options.model === undefined ? [] : ['--model', `${options.model.provider}/${options.model.id}`, ...(options.model.thinking === undefined ? [] : ['--thinking', options.model.thinking])];
39
42
  return [
40
43
  '--mode',
@@ -48,7 +51,7 @@ export function childArgs(options: ChildArgsOptions): string[] {
48
51
  ...(options.trusted === undefined ? [] : [options.trusted ? '--approve' : '--no-approve']),
49
52
  ...model,
50
53
  ...(options.readonly === true ? ['--tools', READONLY_TOOLS, '--no-mcp'] : []),
51
- ...(options.readonly !== true && (options.restoreTools ?? []).length > 0 ? ['--tools', (options.restoreTools ?? []).map((name) => `+${name}`).join(',')] : []),
54
+ ...(options.readonly !== true && extraTools.length > 0 ? ['--tools', extraTools.map((name) => `+${name}`).join(',')] : []),
52
55
  ];
53
56
  }
54
57
 
package/src/task/stop.ts CHANGED
@@ -65,7 +65,8 @@ async function stopElsewhere(agentId: string, lockPath: string, pid: number): Pr
65
65
  export interface StopAgentOptions {
66
66
  /** A child this process runs, if any. */
67
67
  running: (agentId: string) => { handle: ChildHandle } | undefined;
68
- depth: number;
68
+ /** An agent that cannot launch subagents has none to stop. */
69
+ canSpawn: boolean;
69
70
  }
70
71
 
71
72
  const DESCRIPTION =
@@ -79,8 +80,7 @@ export function registerStopAgent(pi: ExtensionAPI, options: StopAgentOptions):
79
80
  promptSnippet: 'Stop a running subagent by agent ID',
80
81
  parameters: Type.Object({ agent_id: Type.String({ description: 'Agent ID from an earlier Task call in this workspace.' }) }),
81
82
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
82
- // Nesting stops at the subagent of a subagent, which has no subagents to stop.
83
- defaultActive: options.depth < 2,
83
+ defaultActive: options.canSpawn,
84
84
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
85
85
  const agentId = validateAgentId(params.agent_id);
86
86
  const owned = options.running(agentId);
package/src/task/tool.ts CHANGED
@@ -10,7 +10,7 @@ import { rootStoreDir, subagentDir, workspaceStateDir, worktreesDir } from '../p
10
10
  import { piCommand } from '../pi-command.ts';
11
11
  import { type AgentDefinition, findAgent } from './agents.ts';
12
12
  import { renderTaskCard, renderTaskNotification } from './card.ts';
13
- import { backgroundText, bounded, foregroundText, steerText, worktreeLine, worktreePreface } from './format.ts';
13
+ import { backgroundText, bounded, foregroundText, notificationTitle, steerText, worktreeLine, worktreePreface } from './format.ts';
14
14
  import { type AvailableModel, type ModelSpec, resolveSubagentModel } from './models.ts';
15
15
  import { createProgress } from './progress.ts';
16
16
  import { type AgentRecord, acquireRunLock, forkTranscript, type RunLock, readonlyLaunchRestores, readRecord, transcriptFor, writeRecord } from './records.ts';
@@ -19,16 +19,17 @@ import { type ChildHandle, type ChildInput, type ChildOutcome, childArgs, resolv
19
19
  import { registerStopAgent } from './stop.ts';
20
20
  import { addWorktree, planWorktree, type Worktree } from './worktree.ts';
21
21
 
22
- const TITLE_LIMIT = 200;
23
-
24
22
  export const TaskParams = Type.Object({
25
- description: Type.String({ description: 'A short (3-5 word) title for the subagent, shown in the UI.' }),
26
- prompt: Type.String({ description: 'The task for the agent to perform. The subagent sees nothing of this conversation, so include every detail and say what to report back.' }),
23
+ description: Type.String({
24
+ description:
25
+ "A short, user-friendly title for the subagent, shown in the UI as the subagent's name. Make it concrete and distinct from recent titles. When you resume an agent for a separate task, give it an updated title; keep the title when it continues the same work.",
26
+ }),
27
+ prompt: Type.String({ description: 'The task for the agent to perform.' }),
27
28
  subagent_type: Type.Optional(Type.String({ description: 'Subagent type from the pstack_subagents section. Defaults to generalPurpose.' })),
28
29
  model: Type.Optional(
29
30
  Type.String({
30
31
  description:
31
- 'Optional model for this agent, from the pstack_subagents section: inherit (default), a Pi model such as claude-opus-5-5:xhigh or provider/model:high, or claude-opus-5-5[effort=high]. An invalid value fails with the allowed list; pick a listed value or omit it. Ignored with resume; with fork, defaults to the source agent model.',
32
+ 'Optional model for this agent, from the pstack_subagents section: inherit (default), a Pi model such as claude-opus-5-5:xhigh or provider/model:high, or claude-opus-5-5[effort=high]. An invalid value fails with the allowed list; pick a listed value or omit it, and never retry a rejected value unchanged. Omitted, the agent runs on the parent model. Use inherit unless the user or a skill asks for another listed model. Ignored with resume, which keeps the earlier model; with fork, defaults to the source agent model.',
32
33
  }),
33
34
  ),
34
35
  resume: Type.Optional(
@@ -271,7 +272,15 @@ function launchChild(plan: Launch, input: ChildInput, signal: AbortSignal | unde
271
272
  const env = { ...process.env, ...childVariables(plan.agent.type, plan.depth, readonly, plan.rootStore, workspaceStateDir(plan.workspace), plan.rootWorkspace) };
272
273
  const transcript = plan.kind === 'fresh' || readonly ? undefined : transcriptFor(subagentDir(plan.workspace), plan.agentId);
273
274
  const restoreTools = transcript === undefined ? [] : readonlyLaunchRestores(transcript);
274
- const args = childArgs({ sessionDir: subagentDir(plan.workspace), agentId: plan.agentId, readonly, restoreTools, trusted: plan.trusted, ...(plan.model === undefined ? {} : { model: plan.model }) });
275
+ const args = childArgs({
276
+ sessionDir: subagentDir(plan.workspace),
277
+ agentId: plan.agentId,
278
+ readonly,
279
+ restoreTools,
280
+ trusted: plan.trusted,
281
+ ...(plan.agent.tools === undefined ? {} : { addTools: plan.agent.tools }),
282
+ ...(plan.model === undefined ? {} : { model: plan.model }),
283
+ });
275
284
  return startChild({ command: piCommand(), args, prompt: input.text, images: input.images, cwd: plan.executionCwd, env, ...(signal === undefined ? {} : { signal }), ...(onEvent === undefined ? {} : { onEvent }) });
276
285
  }
277
286
 
@@ -359,11 +368,11 @@ function foregroundResult(plan: Launch, outcome: ChildOutcome) {
359
368
  return { content: [{ type: 'text' as const, text }], details: details(plan, false, 'error'), usage: outcome.usage, isError: true };
360
369
  }
361
370
 
362
- /** Cursor shows the Task description as the subagent's name, so the completion notice carries it too. */
363
- export function backgroundNotice(plan: Launch, description: string, ctx: ExtensionContext, toolCallId: string): BackgroundNotice {
364
- const flat = description.replace(/\s+/g, ' ').trim();
371
+ /** Cursor titles the completion by the prompt's first line and names the subagent in the UI by its description. */
372
+ export function backgroundNotice(plan: Launch, prompt: string, description: string, ctx: ExtensionContext, toolCallId: string): BackgroundNotice {
365
373
  return {
366
- title: flat.length > TITLE_LIMIT ? `${flat.slice(0, TITLE_LIMIT)}…` : flat,
374
+ title: notificationTitle(prompt),
375
+ description: description.replace(/\s+/g, ' ').trim(),
367
376
  toolCallId,
368
377
  mode: ctx.mode,
369
378
  detailFor: (outcome) => {
@@ -449,8 +458,21 @@ async function steerRunning(params: TaskInput, running: { handle: ChildHandle; r
449
458
  return { content: [{ type: 'text' as const, text: steerText(agentId, notes) }], details: { agentId, status: 'steered', pid: running.handle.pid ?? null, description: params.description } };
450
459
  }
451
460
 
452
- const TASK_DESCRIPTION =
453
- 'Launch a subagent: a separate Pi process with its own context that works autonomously and returns one final message. It sees nothing of this conversation, so give it a self-contained prompt and say what to report back. Put several Task calls in one message to run them in parallel. Subagent types and model values are listed in the pstack_subagents section of the system prompt.';
461
+ const TASK_DESCRIPTION = [
462
+ 'Launch a new agent to handle a complex, multi-step task on its own. Each agent is a separate Pi process with its own context, and each subagent_type has its own instructions and tools. Pick the type with subagent_type; the types, and the model values the model parameter takes, are listed in the pstack_subagents section of the system prompt.',
463
+ '',
464
+ 'Do not use Task for a narrow or specific question. To find where one class is defined, read a known file, or search two or three files, use read, grep, or find directly. When separate areas can be explored in parallel, launch several agents at once. Do not hand the whole request to one agent and relay its answer.',
465
+ '',
466
+ 'Usage notes:',
467
+ '- Give every call a short (3-5 word) description.',
468
+ '- To run agents in parallel, put several Task calls in one message. Do this whenever the work splits, and always when the user asks for agents in parallel.',
469
+ '- The agent returns one final message. Say exactly what it should report back.',
470
+ "- The agent cannot see the user's messages or your earlier steps, so the prompt must carry every detail and all the context it needs.",
471
+ '- Trust the agent output in general.',
472
+ '- When a subagent type says to use it proactively, use it without being asked.',
473
+ '- resume continues an earlier agent with its context preserved. Without resume, each call starts fresh.',
474
+ '- A background agent notifies you automatically when it finishes, after you end your turn. Do not poll it, sleep, or check on its progress. Work on something else or end your turn, and do not mention this to the user.',
475
+ ].join('\n');
454
476
 
455
477
  // Interactive Pi redraws the chat between a replaced session's shutdown and the next session's start, which erases a
456
478
  // warning sent at shutdown. The next runtime shows it instead, so it rides on globalThis across the reload.
@@ -466,6 +488,8 @@ function dropTask(pi: ExtensionAPI): void {
466
488
  export interface TaskToolOptions {
467
489
  agents: readonly AgentDefinition[];
468
490
  depth: number;
491
+ /** False in a subagent of a subagent, and in a type that never launches subagents (explore). */
492
+ canSpawn: boolean;
469
493
  /** Whether plan mode is on: its Task launches run readonly and here, and record nothing of that. */
470
494
  planMode?: () => boolean;
471
495
  }
@@ -473,6 +497,8 @@ export interface TaskToolOptions {
473
497
  export interface StartBackgroundOptions {
474
498
  /** A Pi model spec, used by subscription timers so a live and a detached fire run the same model. */
475
499
  model?: string;
500
+ /** cloud runs the agent in its own git worktree, as plan mode's "build in cloud" does. */
501
+ environment?: 'cloud';
476
502
  /** The owner's project-trust decision, used when this subscription fire starts away from its chat. */
477
503
  trusted?: boolean;
478
504
  }
@@ -498,7 +524,7 @@ export function registerTask(pi: ExtensionAPI, options: TaskToolOptions): TaskHa
498
524
  });
499
525
  pi.on('session_start', (_event, ctx) => {
500
526
  sessionCtx = ctx;
501
- if (options.depth >= 2) dropTask(pi);
527
+ if (!options.canSpawn) dropTask(pi);
502
528
  const message = carrier[STOPPED_NOTICE];
503
529
  delete carrier[STOPPED_NOTICE];
504
530
  if (message !== undefined && ctx.hasUI) ctx.ui.notify(message, 'warning');
@@ -510,8 +536,8 @@ export function registerTask(pi: ExtensionAPI, options: TaskToolOptions): TaskHa
510
536
  description: TASK_DESCRIPTION,
511
537
  promptSnippet: 'Launch subagents (foreground, background with completion notifications, resume by agent ID)',
512
538
  parameters: TaskParams,
513
- // Nesting stops at the subagent of a subagent, so that depth never sees the tool.
514
- defaultActive: options.depth < 2,
539
+ // Nesting stops at the subagent of a subagent, so that depth never sees the tool, and so does explore.
540
+ defaultActive: options.canSpawn,
515
541
  renderResult: (result, renderOptions) => renderTaskCard(result, renderOptions),
516
542
  async execute(toolCallId, params, signal, onUpdate, ctx) {
517
543
  taskPreflight(params, options.depth);
@@ -527,7 +553,7 @@ export function registerTask(pi: ExtensionAPI, options: TaskToolOptions): TaskHa
527
553
  const handle = start(plan, input, background ? undefined : signal, lock, progress?.onEvent);
528
554
  pid = handle.pid;
529
555
  if (background) {
530
- registry.track(plan.agentId, handle, lock.release, runsReadonly(plan), backgroundNotice(plan, plan.description, ctx, toolCallId));
556
+ registry.track(plan.agentId, handle, lock.release, runsReadonly(plan), backgroundNotice(plan, params.prompt, plan.description, ctx, toolCallId));
531
557
  return { content: [{ type: 'text', text: backgroundText(plan.agentId, transcriptOf(plan), plan.notes) }], details: details(plan, true, 'running', handle.pid) };
532
558
  }
533
559
  registry.track(plan.agentId, handle, lock.release, runsReadonly(plan));
@@ -541,18 +567,24 @@ export function registerTask(pi: ExtensionAPI, options: TaskToolOptions): TaskHa
541
567
  },
542
568
  });
543
569
 
544
- registerStopAgent(pi, { running: registry.get, depth: options.depth });
570
+ registerStopAgent(pi, { running: registry.get, canSpawn: options.canSpawn });
545
571
 
546
572
  async function startBackground(description: string, prompt: string, startOptions?: StartBackgroundOptions): Promise<string> {
547
573
  const ctx = sessionCtx;
548
574
  if (ctx === undefined) throw new Error('No session is active, so no subagent can start.');
549
- const params: TaskInput = { description, prompt, run_in_background: true, ...(startOptions?.model === undefined ? {} : { model: startOptions.model }) };
575
+ const params: TaskInput = {
576
+ description,
577
+ prompt,
578
+ run_in_background: true,
579
+ ...(startOptions?.model === undefined ? {} : { model: startOptions.model }),
580
+ ...(startOptions?.environment === undefined ? {} : { environment: startOptions.environment }),
581
+ };
550
582
  taskPreflight(params, options.depth);
551
583
  const { plan, lock } = prepare(params, ctx, options, registry.isRunning);
552
584
  if (startOptions?.trusted !== undefined) plan.trusted = startOptions.trusted;
553
585
  await createWorktree(plan, lock, undefined);
554
586
  const handle = start(plan, { text: prompt.trim(), images: [] }, undefined, lock);
555
- registry.track(plan.agentId, handle, lock.release, runsReadonly(plan), backgroundNotice(plan, description, ctx, `pstack-${plan.agentId}`));
587
+ registry.track(plan.agentId, handle, lock.release, runsReadonly(plan), backgroundNotice(plan, prompt, description, ctx, `pstack-${plan.agentId}`));
556
588
  return plan.agentId;
557
589
  }
558
590
 
package/src/todo.ts CHANGED
@@ -96,6 +96,26 @@ export function todoSection(todos: readonly TodoItem[]): string | undefined {
96
96
  return todos.length === 0 ? undefined : `Current todo list, owned by this session:\n${formatTodos(todos)}`;
97
97
  }
98
98
 
99
+ // Cursor's TodoWrite rules: when to keep a list, the four states, one task in progress at a time, and batching.
100
+ const TODO_DESCRIPTION = [
101
+ 'Use this tool to create and manage a structured task list for your current coding session. It tracks progress, organizes complex tasks, and shows the user what you are doing. Each item has an id, content, and status.',
102
+ '',
103
+ 'Other than when you first create the list, do not tell the user you are updating todos. Just update them.',
104
+ '',
105
+ 'Use it for:',
106
+ '- A task with three or more distinct steps, or non-trivial work that needs planning.',
107
+ '- An explicit request for a todo list, or several tasks given at once (numbered or comma-separated).',
108
+ '- New instructions: capture the requirements as todos.',
109
+ '- A finished task: mark it completed (merge=true) and add any follow-ups.',
110
+ '- A task you start: mark it in_progress.',
111
+ '',
112
+ 'Skip it for a single straightforward task, a trivial task done in fewer than three steps, or a purely conversational or informational request. Do not add a task to test a change unless asked.',
113
+ '',
114
+ 'States: pending (not started), in_progress (working on it now), completed (finished), cancelled (no longer needed). Update states as you work, mark a task completed as soon as it is done, keep only one task in_progress at a time, and finish the current task before you start a new one. Write specific, actionable items with clear names.',
115
+ '',
116
+ '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
+ ].join('\n');
118
+
99
119
  export function registerTodoWrite(pi: ExtensionAPI): { section: () => string | undefined } {
100
120
  let todos: TodoItem[] = [];
101
121
  const show = (ctx: ExtensionContext) => {
@@ -111,7 +131,7 @@ export function registerTodoWrite(pi: ExtensionAPI): { section: () => string | u
111
131
  pi.registerTool({
112
132
  name: 'TodoWrite',
113
133
  label: 'Todos',
114
- description: 'Use this tool to create and manage a structured task list for your current coding session. Each item has an id, content, and status (pending, in_progress, completed, cancelled).',
134
+ description: TODO_DESCRIPTION,
115
135
  promptSnippet: 'Create and update the todo list for this session',
116
136
  promptGuidelines: ['When a skill or playbook says to open a todolist or todo list, call TodoWrite before other work, with the steps it names as the first items.'],
117
137
  parameters: TodoParams,
@@ -1,104 +0,0 @@
1
- // Cursor attaches a skill to the conversation when the agent reads a file matching its `paths`/`globs` frontmatter.
2
- // Pi has no path-scoped skills, so this module tracks the files a session reads or edits and attaches the matching
3
- // skill body once per session, in the same <skill> block shape Pi's own /skill:name expansion uses.
4
- import { existsSync, readFileSync } from 'node:fs';
5
- import { dirname, isAbsolute, matchesGlob, relative, sep } from 'node:path';
6
-
7
- import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
8
- import { parseFrontmatter } from '@earendil-works/pi-coding-agent';
9
-
10
- /** A skill whose frontmatter scopes it to file patterns. */
11
- export interface PathSkill {
12
- name: string;
13
- file: string;
14
- globs: string[];
15
- body: string;
16
- }
17
-
18
- const TOUCHED_TOOLS = new Set(['read', 'edit', 'write']);
19
- const SECTION_LIMIT = 40_000;
20
-
21
- function globsOf(value: unknown): string[] {
22
- if (typeof value === 'string')
23
- return value
24
- .split(',')
25
- .map((part) => part.trim())
26
- .filter((part) => part !== '');
27
- if (!Array.isArray(value)) return [];
28
- return value.filter((part): part is string => typeof part === 'string' && part.trim() !== '').map((part) => part.trim());
29
- }
30
-
31
- /** Every loaded skill that declares `paths` (Cursor's name for skill globs) or `globs`. */
32
- export function loadPathSkills(commands: readonly { name: string; source: string; sourceInfo: { path: string } }[]): PathSkill[] {
33
- const skills: PathSkill[] = [];
34
- for (const command of commands) {
35
- if (command.source !== 'skill' || !command.name.startsWith('skill:')) continue;
36
- const file = command.sourceInfo.path;
37
- if (!existsSync(file)) continue;
38
- const { frontmatter, body } = parseFrontmatter(readFileSync(file, 'utf8'));
39
- // `metadata` is the portable Agent Skills extension point; Cursor's own field is the top-level `paths`/`globs`.
40
- const metadata = typeof frontmatter['metadata'] === 'object' && frontmatter['metadata'] !== null ? (frontmatter['metadata'] as Record<string, unknown>) : {};
41
- const globs = [...new Set([...globsOf(frontmatter['paths']), ...globsOf(frontmatter['globs']), ...globsOf(metadata['paths']), ...globsOf(metadata['globs'])])];
42
- if (globs.length === 0) continue;
43
- skills.push({ name: command.name.slice('skill:'.length), file, globs, body: body.trim() });
44
- }
45
- return skills;
46
- }
47
-
48
- const slash = (path: string) => path.split(sep).join('/');
49
-
50
- /** The skills whose patterns match a path the session read or edited. Paths outside the workspace are ignored. */
51
- export function matchPathSkills(skills: readonly PathSkill[], paths: Iterable<string>, cwd: string): PathSkill[] {
52
- const relativePaths = [...paths].map((path) => slash(isAbsolute(path) ? relative(cwd, path) : path)).filter((path) => path !== '' && path !== '..' && !path.startsWith('../'));
53
- return skills.filter((skill) => relativePaths.some((path) => skill.globs.some((glob) => matchesGlob(path, glob))));
54
- }
55
-
56
- /** The attached bodies as <skill> blocks, in the shape Pi's /skill:name expansion builds. */
57
- export function pathSkillsSection(skills: readonly PathSkill[]): string | undefined {
58
- if (skills.length === 0) return undefined;
59
- const blocks: string[] = [];
60
- let size = 0;
61
- for (const skill of skills) {
62
- const block = [`<skill name="${skill.name}" location="${skill.file}">`, `References are relative to ${dirname(skill.file)}.`, '', skill.body, '</skill>'].join('\n');
63
- if (size + block.length > SECTION_LIMIT) break;
64
- size += block.length;
65
- blocks.push(block);
66
- }
67
- return blocks.length === 0 ? undefined : blocks.join('\n\n');
68
- }
69
-
70
- export interface PathSkillsHandle {
71
- /** The skills to attach to the next request, empty until a matching file has been read or edited. */
72
- section: () => string | undefined;
73
- }
74
-
75
- /** Tracks read and edit paths and attaches each matching skill once per session. */
76
- export function createPathSkills(pi: ExtensionAPI): PathSkillsHandle {
77
- let catalog: PathSkill[] | undefined;
78
- let cwd = process.cwd();
79
- let touched = new Set<string>();
80
- const injected = new Set<string>();
81
-
82
- pi.on('session_start', (_event, ctx) => {
83
- catalog = undefined;
84
- touched = new Set();
85
- injected.clear();
86
- cwd = ctx.cwd;
87
- });
88
- pi.on('tool_call', (event) => {
89
- if (!TOUCHED_TOOLS.has(event.toolName)) return;
90
- const path = (event.input as { path?: unknown }).path;
91
- if (typeof path === 'string' && path !== '') touched.add(path);
92
- });
93
-
94
- return {
95
- section: () => {
96
- if (touched.size === 0) return undefined;
97
- catalog ??= loadPathSkills(pi.getCommands());
98
- const matches = matchPathSkills(catalog, touched, cwd).filter((skill) => !injected.has(skill.name));
99
- if (matches.length === 0) return undefined;
100
- for (const skill of matches) injected.add(skill.name);
101
- return pathSkillsSection(matches);
102
- },
103
- };
104
- }