@clanker-code/pi-subagents 0.10.5

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 (130) hide show
  1. package/.plans/PLAN-next-changes.md +183 -0
  2. package/.plans/README.md +14 -0
  3. package/AGENTS.md +31 -0
  4. package/CHANGELOG.md +583 -0
  5. package/CLAUDE.md +1 -0
  6. package/LICENSE +21 -0
  7. package/README.md +630 -0
  8. package/RELEASE.md +39 -0
  9. package/dist/abort-resend.d.ts +35 -0
  10. package/dist/abort-resend.js +71 -0
  11. package/dist/agent-details.d.ts +17 -0
  12. package/dist/agent-details.js +22 -0
  13. package/dist/agent-manager.d.ts +132 -0
  14. package/dist/agent-manager.js +493 -0
  15. package/dist/agent-runner.d.ts +165 -0
  16. package/dist/agent-runner.js +732 -0
  17. package/dist/agent-tool-description.d.ts +9 -0
  18. package/dist/agent-tool-description.js +147 -0
  19. package/dist/agent-types.d.ts +60 -0
  20. package/dist/agent-types.js +157 -0
  21. package/dist/context.d.ts +12 -0
  22. package/dist/context.js +56 -0
  23. package/dist/cross-extension-rpc.d.ts +46 -0
  24. package/dist/cross-extension-rpc.js +76 -0
  25. package/dist/custom-agents.d.ts +14 -0
  26. package/dist/custom-agents.js +149 -0
  27. package/dist/default-agents.d.ts +7 -0
  28. package/dist/default-agents.js +119 -0
  29. package/dist/enabled-models.d.ts +49 -0
  30. package/dist/enabled-models.js +145 -0
  31. package/dist/env.d.ts +6 -0
  32. package/dist/env.js +28 -0
  33. package/dist/group-join.d.ts +32 -0
  34. package/dist/group-join.js +116 -0
  35. package/dist/index.d.ts +36 -0
  36. package/dist/index.js +1918 -0
  37. package/dist/invocation-config.d.ts +25 -0
  38. package/dist/invocation-config.js +19 -0
  39. package/dist/memory.d.ts +49 -0
  40. package/dist/memory.js +151 -0
  41. package/dist/model-resolver.d.ts +19 -0
  42. package/dist/model-resolver.js +62 -0
  43. package/dist/notifications.d.ts +6 -0
  44. package/dist/notifications.js +107 -0
  45. package/dist/output-file.d.ts +24 -0
  46. package/dist/output-file.js +86 -0
  47. package/dist/peek.d.ts +37 -0
  48. package/dist/peek.js +121 -0
  49. package/dist/prompts.d.ts +40 -0
  50. package/dist/prompts.js +95 -0
  51. package/dist/schedule-store.d.ts +38 -0
  52. package/dist/schedule-store.js +155 -0
  53. package/dist/schedule.d.ts +109 -0
  54. package/dist/schedule.js +338 -0
  55. package/dist/settings.d.ts +135 -0
  56. package/dist/settings.js +168 -0
  57. package/dist/skill-loader.d.ts +24 -0
  58. package/dist/skill-loader.js +93 -0
  59. package/dist/status-note.d.ts +13 -0
  60. package/dist/status-note.js +24 -0
  61. package/dist/types.d.ts +184 -0
  62. package/dist/types.js +7 -0
  63. package/dist/ui/agent-tool-rendering.d.ts +34 -0
  64. package/dist/ui/agent-tool-rendering.js +154 -0
  65. package/dist/ui/agent-widget-tree.d.ts +33 -0
  66. package/dist/ui/agent-widget-tree.js +130 -0
  67. package/dist/ui/agent-widget.d.ts +156 -0
  68. package/dist/ui/agent-widget.js +408 -0
  69. package/dist/ui/conversation-viewer.d.ts +47 -0
  70. package/dist/ui/conversation-viewer.js +290 -0
  71. package/dist/ui/menu-select.d.ts +20 -0
  72. package/dist/ui/menu-select.js +46 -0
  73. package/dist/ui/schedule-menu.d.ts +16 -0
  74. package/dist/ui/schedule-menu.js +99 -0
  75. package/dist/ui/viewer-keys.d.ts +20 -0
  76. package/dist/ui/viewer-keys.js +17 -0
  77. package/dist/usage.d.ts +50 -0
  78. package/dist/usage.js +49 -0
  79. package/dist/wait.d.ts +10 -0
  80. package/dist/wait.js +37 -0
  81. package/dist/worktree.d.ts +45 -0
  82. package/dist/worktree.js +160 -0
  83. package/docs/design/default-extension-tool-exposure.md +56 -0
  84. package/docs/superpowers/plans/2026-06-19-recursive-subagent-widget.md +600 -0
  85. package/docs/superpowers/specs/2026-06-19-recursive-subagent-widget-design.md +189 -0
  86. package/examples/agent-tool-description.md +45 -0
  87. package/package.json +56 -0
  88. package/reviews/proposal-structured-output-schema.md +135 -0
  89. package/reviews/recursive-subagent-widget-preview-rev2.png +0 -0
  90. package/reviews/recursive-subagent-widget-preview.html +137 -0
  91. package/reviews/recursive-subagent-widget-preview.png +0 -0
  92. package/reviews/subagent-features-comparison.md +350 -0
  93. package/src/abort-resend.ts +75 -0
  94. package/src/agent-details.ts +31 -0
  95. package/src/agent-manager.ts +596 -0
  96. package/src/agent-runner.ts +872 -0
  97. package/src/agent-tool-description.ts +163 -0
  98. package/src/agent-types.ts +189 -0
  99. package/src/context.ts +58 -0
  100. package/src/cross-extension-rpc.ts +122 -0
  101. package/src/custom-agents.ts +160 -0
  102. package/src/default-agents.ts +123 -0
  103. package/src/enabled-models.ts +180 -0
  104. package/src/env.ts +33 -0
  105. package/src/group-join.ts +141 -0
  106. package/src/index.ts +2115 -0
  107. package/src/invocation-config.ts +42 -0
  108. package/src/memory.ts +165 -0
  109. package/src/model-resolver.ts +81 -0
  110. package/src/notifications.ts +120 -0
  111. package/src/output-file.ts +96 -0
  112. package/src/peek.ts +155 -0
  113. package/src/prompts.ts +129 -0
  114. package/src/schedule-store.ts +153 -0
  115. package/src/schedule.ts +365 -0
  116. package/src/settings.ts +289 -0
  117. package/src/skill-loader.ts +102 -0
  118. package/src/status-note.ts +25 -0
  119. package/src/types.ts +195 -0
  120. package/src/ui/agent-tool-rendering.ts +175 -0
  121. package/src/ui/agent-widget-tree.ts +169 -0
  122. package/src/ui/agent-widget.ts +497 -0
  123. package/src/ui/conversation-viewer.ts +297 -0
  124. package/src/ui/menu-select.ts +68 -0
  125. package/src/ui/schedule-menu.ts +105 -0
  126. package/src/ui/viewer-keys.ts +39 -0
  127. package/src/usage.ts +60 -0
  128. package/src/wait.ts +44 -0
  129. package/src/worktree.ts +191 -0
  130. package/vitest.config.ts +25 -0
@@ -0,0 +1,25 @@
1
+ import type { AgentConfig, IsolationMode, JoinMode, ThinkingLevel } from "./types.js";
2
+ interface AgentInvocationParams {
3
+ model?: string;
4
+ thinking?: string;
5
+ max_turns?: number;
6
+ inherit_context?: boolean;
7
+ isolated?: boolean;
8
+ isolation?: IsolationMode;
9
+ }
10
+ export declare function resolveAgentInvocationConfig(agentConfig: AgentConfig | undefined, params: AgentInvocationParams): {
11
+ modelInput?: string;
12
+ modelFromParams: boolean;
13
+ thinking?: ThinkingLevel;
14
+ maxTurns?: number;
15
+ inheritContext: boolean;
16
+ isolated: boolean;
17
+ isolation?: IsolationMode;
18
+ };
19
+ /**
20
+ * Resolve the join mode for a spawned agent. This fork runs every agent in the
21
+ * background, so the join mode is always the configured default (no foreground
22
+ * case to suppress it).
23
+ */
24
+ export declare function resolveJoinMode(defaultJoinMode: JoinMode): JoinMode;
25
+ export {};
@@ -0,0 +1,19 @@
1
+ export function resolveAgentInvocationConfig(agentConfig, params) {
2
+ return {
3
+ modelInput: agentConfig?.model ?? params.model,
4
+ modelFromParams: agentConfig?.model == null && params.model != null,
5
+ thinking: (agentConfig?.thinking ?? params.thinking),
6
+ maxTurns: agentConfig?.maxTurns ?? params.max_turns,
7
+ inheritContext: agentConfig?.inheritContext ?? params.inherit_context ?? false,
8
+ isolated: agentConfig?.isolated ?? params.isolated ?? false,
9
+ isolation: agentConfig?.isolation ?? params.isolation,
10
+ };
11
+ }
12
+ /**
13
+ * Resolve the join mode for a spawned agent. This fork runs every agent in the
14
+ * background, so the join mode is always the configured default (no foreground
15
+ * case to suppress it).
16
+ */
17
+ export function resolveJoinMode(defaultJoinMode) {
18
+ return defaultJoinMode;
19
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * memory.ts — Persistent agent memory: per-agent memory directories that persist across sessions.
3
+ *
4
+ * Memory scopes:
5
+ * - "user" → ~/.pi/agent-memory/{agent-name}/
6
+ * - "project" → .pi/agent-memory/{agent-name}/
7
+ * - "local" → .pi/agent-memory-local/{agent-name}/
8
+ */
9
+ import type { MemoryScope } from "./types.js";
10
+ /**
11
+ * Returns true if a name contains characters not allowed in agent/skill names.
12
+ * Uses a whitelist: only alphanumeric, hyphens, underscores, and dots (no leading dot).
13
+ */
14
+ export declare function isUnsafeName(name: string): boolean;
15
+ /**
16
+ * Returns true if the given path is a symlink (defense against symlink attacks).
17
+ */
18
+ export declare function isSymlink(filePath: string): boolean;
19
+ /**
20
+ * Safely read a file, rejecting symlinks.
21
+ * Returns undefined if the file doesn't exist, is a symlink, or can't be read.
22
+ */
23
+ export declare function safeReadFile(filePath: string): string | undefined;
24
+ /**
25
+ * Resolve the memory directory path for a given agent + scope + cwd.
26
+ * Throws if agentName contains path traversal characters.
27
+ */
28
+ export declare function resolveMemoryDir(agentName: string, scope: MemoryScope, cwd: string): string;
29
+ /**
30
+ * Ensure the memory directory exists, creating it if needed.
31
+ * Refuses to create directories if any component in the path is a symlink
32
+ * to prevent symlink-based directory traversal attacks.
33
+ */
34
+ export declare function ensureMemoryDir(memoryDir: string): void;
35
+ /**
36
+ * Read the first N lines of MEMORY.md from the memory directory, if it exists.
37
+ * Returns undefined if no MEMORY.md exists or if the path is a symlink.
38
+ */
39
+ export declare function readMemoryIndex(memoryDir: string): string | undefined;
40
+ /**
41
+ * Build the memory block to inject into the agent's system prompt.
42
+ * Also ensures the memory directory exists (creates it if needed).
43
+ */
44
+ export declare function buildMemoryBlock(agentName: string, scope: MemoryScope, cwd: string): string;
45
+ /**
46
+ * Build a read-only memory block for agents that lack write/edit tools.
47
+ * Does NOT create the memory directory — agents can only consume existing memory.
48
+ */
49
+ export declare function buildReadOnlyMemoryBlock(agentName: string, scope: MemoryScope, cwd: string): string;
package/dist/memory.js ADDED
@@ -0,0 +1,151 @@
1
+ /**
2
+ * memory.ts — Persistent agent memory: per-agent memory directories that persist across sessions.
3
+ *
4
+ * Memory scopes:
5
+ * - "user" → ~/.pi/agent-memory/{agent-name}/
6
+ * - "project" → .pi/agent-memory/{agent-name}/
7
+ * - "local" → .pi/agent-memory-local/{agent-name}/
8
+ */
9
+ import { existsSync, lstatSync, mkdirSync, readFileSync } from "node:fs";
10
+ import { homedir } from "node:os";
11
+ import { join, } from "node:path";
12
+ /** Maximum lines to read from MEMORY.md */
13
+ const MAX_MEMORY_LINES = 200;
14
+ /**
15
+ * Returns true if a name contains characters not allowed in agent/skill names.
16
+ * Uses a whitelist: only alphanumeric, hyphens, underscores, and dots (no leading dot).
17
+ */
18
+ export function isUnsafeName(name) {
19
+ if (!name || name.length > 128)
20
+ return true;
21
+ return !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name);
22
+ }
23
+ /**
24
+ * Returns true if the given path is a symlink (defense against symlink attacks).
25
+ */
26
+ export function isSymlink(filePath) {
27
+ try {
28
+ return lstatSync(filePath).isSymbolicLink();
29
+ }
30
+ catch {
31
+ return false;
32
+ }
33
+ }
34
+ /**
35
+ * Safely read a file, rejecting symlinks.
36
+ * Returns undefined if the file doesn't exist, is a symlink, or can't be read.
37
+ */
38
+ export function safeReadFile(filePath) {
39
+ if (!existsSync(filePath))
40
+ return undefined;
41
+ if (isSymlink(filePath))
42
+ return undefined;
43
+ try {
44
+ return readFileSync(filePath, "utf-8");
45
+ }
46
+ catch {
47
+ return undefined;
48
+ }
49
+ }
50
+ /**
51
+ * Resolve the memory directory path for a given agent + scope + cwd.
52
+ * Throws if agentName contains path traversal characters.
53
+ */
54
+ export function resolveMemoryDir(agentName, scope, cwd) {
55
+ if (isUnsafeName(agentName)) {
56
+ throw new Error(`Unsafe agent name for memory directory: "${agentName}"`);
57
+ }
58
+ switch (scope) {
59
+ case "user":
60
+ return join(homedir(), ".pi", "agent-memory", agentName);
61
+ case "project":
62
+ return join(cwd, ".pi", "agent-memory", agentName);
63
+ case "local":
64
+ return join(cwd, ".pi", "agent-memory-local", agentName);
65
+ }
66
+ }
67
+ /**
68
+ * Ensure the memory directory exists, creating it if needed.
69
+ * Refuses to create directories if any component in the path is a symlink
70
+ * to prevent symlink-based directory traversal attacks.
71
+ */
72
+ export function ensureMemoryDir(memoryDir) {
73
+ // If the directory already exists, verify it's not a symlink
74
+ if (existsSync(memoryDir)) {
75
+ if (isSymlink(memoryDir)) {
76
+ throw new Error(`Refusing to use symlinked memory directory: ${memoryDir}`);
77
+ }
78
+ return;
79
+ }
80
+ mkdirSync(memoryDir, { recursive: true });
81
+ }
82
+ /**
83
+ * Read the first N lines of MEMORY.md from the memory directory, if it exists.
84
+ * Returns undefined if no MEMORY.md exists or if the path is a symlink.
85
+ */
86
+ export function readMemoryIndex(memoryDir) {
87
+ // Reject symlinked memory directories
88
+ if (isSymlink(memoryDir))
89
+ return undefined;
90
+ const memoryFile = join(memoryDir, "MEMORY.md");
91
+ const content = safeReadFile(memoryFile);
92
+ if (content === undefined)
93
+ return undefined;
94
+ const lines = content.split("\n");
95
+ if (lines.length > MAX_MEMORY_LINES) {
96
+ return lines.slice(0, MAX_MEMORY_LINES).join("\n") + "\n... (truncated at 200 lines)";
97
+ }
98
+ return content;
99
+ }
100
+ /**
101
+ * Build the memory block to inject into the agent's system prompt.
102
+ * Also ensures the memory directory exists (creates it if needed).
103
+ */
104
+ export function buildMemoryBlock(agentName, scope, cwd) {
105
+ const memoryDir = resolveMemoryDir(agentName, scope, cwd);
106
+ // Create the memory directory so the agent can immediately write to it
107
+ ensureMemoryDir(memoryDir);
108
+ const existingMemory = readMemoryIndex(memoryDir);
109
+ const header = `# Agent Memory
110
+
111
+ You have a persistent memory directory at: ${memoryDir}/
112
+ Memory scope: ${scope}
113
+
114
+ This memory persists across sessions. Use it to build up knowledge over time.`;
115
+ const memoryContent = existingMemory
116
+ ? `\n\n## Current MEMORY.md\n${existingMemory}`
117
+ : `\n\nNo MEMORY.md exists yet. Create one at ${join(memoryDir, "MEMORY.md")} to start building persistent memory.`;
118
+ const instructions = `
119
+
120
+ ## Memory Instructions
121
+ - MEMORY.md is an index file — keep it concise (under 200 lines). Lines after 200 are truncated.
122
+ - Store detailed memories in separate files within ${memoryDir}/ and link to them from MEMORY.md.
123
+ - Each memory file should use this frontmatter format:
124
+ \`\`\`markdown
125
+ ---
126
+ name: <memory name>
127
+ description: <one-line description>
128
+ type: <user|feedback|project|reference>
129
+ ---
130
+ <memory content>
131
+ \`\`\`
132
+ - Update or remove memories that become outdated. Check for existing memories before creating duplicates.
133
+ - You have Read, Write, and Edit tools available for managing memory files.`;
134
+ return header + memoryContent + instructions;
135
+ }
136
+ /**
137
+ * Build a read-only memory block for agents that lack write/edit tools.
138
+ * Does NOT create the memory directory — agents can only consume existing memory.
139
+ */
140
+ export function buildReadOnlyMemoryBlock(agentName, scope, cwd) {
141
+ const memoryDir = resolveMemoryDir(agentName, scope, cwd);
142
+ const existingMemory = readMemoryIndex(memoryDir);
143
+ const header = `# Agent Memory (read-only)
144
+
145
+ Memory scope: ${scope}
146
+ You have read-only access to memory. You can reference existing memories but cannot create or modify them.`;
147
+ const memoryContent = existingMemory
148
+ ? `\n\n## Current MEMORY.md\n${existingMemory}`
149
+ : `\n\nNo memory is available yet. Other agents or sessions with write access can create memories for you to consume.`;
150
+ return header + memoryContent;
151
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Model resolution: exact match ("provider/modelId") with fuzzy fallback.
3
+ */
4
+ export interface ModelEntry {
5
+ id: string;
6
+ name: string;
7
+ provider: string;
8
+ }
9
+ export interface ModelRegistry {
10
+ find(provider: string, modelId: string): any;
11
+ getAll(): any[];
12
+ getAvailable?(): any[];
13
+ }
14
+ /**
15
+ * Resolve a model string to a Model instance.
16
+ * Tries exact match first ("provider/modelId"), then fuzzy match against all available models.
17
+ * Returns the Model on success, or an error message string on failure.
18
+ */
19
+ export declare function resolveModel(input: string, registry: ModelRegistry): any | string;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Model resolution: exact match ("provider/modelId") with fuzzy fallback.
3
+ */
4
+ /**
5
+ * Resolve a model string to a Model instance.
6
+ * Tries exact match first ("provider/modelId"), then fuzzy match against all available models.
7
+ * Returns the Model on success, or an error message string on failure.
8
+ */
9
+ export function resolveModel(input, registry) {
10
+ // Available models (those with auth configured)
11
+ const all = (registry.getAvailable?.() ?? registry.getAll());
12
+ const availableSet = new Set(all.map(m => `${m.provider}/${m.id}`.toLowerCase()));
13
+ // 1. Exact match: "provider/modelId" — only if available (has auth)
14
+ const slashIdx = input.indexOf("/");
15
+ if (slashIdx !== -1) {
16
+ const provider = input.slice(0, slashIdx);
17
+ const modelId = input.slice(slashIdx + 1);
18
+ if (availableSet.has(input.toLowerCase())) {
19
+ const found = registry.find(provider, modelId);
20
+ if (found)
21
+ return found;
22
+ }
23
+ }
24
+ // 2. Fuzzy match against available models
25
+ const query = input.toLowerCase();
26
+ // Score each model: prefer exact id match > id contains > name contains > provider+id contains
27
+ let bestMatch;
28
+ let bestScore = 0;
29
+ for (const m of all) {
30
+ const id = m.id.toLowerCase();
31
+ const name = m.name.toLowerCase();
32
+ const full = `${m.provider}/${m.id}`.toLowerCase();
33
+ let score = 0;
34
+ if (id === query || full === query) {
35
+ score = 100; // exact
36
+ }
37
+ else if (id.includes(query) || full.includes(query)) {
38
+ score = 60 + (query.length / id.length) * 30; // substring, prefer tighter matches
39
+ }
40
+ else if (name.includes(query)) {
41
+ score = 40 + (query.length / name.length) * 20;
42
+ }
43
+ else if (query.split(/[\s\-/]+/).every(part => id.includes(part) || name.includes(part) || m.provider.toLowerCase().includes(part))) {
44
+ score = 20; // all parts present somewhere
45
+ }
46
+ if (score > bestScore) {
47
+ bestScore = score;
48
+ bestMatch = m;
49
+ }
50
+ }
51
+ if (bestMatch && bestScore >= 20) {
52
+ const found = registry.find(bestMatch.provider, bestMatch.id);
53
+ if (found)
54
+ return found;
55
+ }
56
+ // 3. No match — list available models
57
+ const modelList = all
58
+ .map(m => ` ${m.provider}/${m.id}`)
59
+ .sort()
60
+ .join("\n");
61
+ return `Model not found: "${input}".\n\nAvailable models:\n${modelList}`;
62
+ }
@@ -0,0 +1,6 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import type { AgentRecord, NotificationDetails } from "./types.js";
3
+ import type { AgentActivity } from "./ui/agent-widget.js";
4
+ export declare function formatTaskNotification(record: AgentRecord, resultMaxLen: number): string;
5
+ export declare function buildNotificationDetails(record: AgentRecord, resultMaxLen: number, activity?: AgentActivity): NotificationDetails;
6
+ export declare function registerSubagentNotificationRenderer(pi: ExtensionAPI): void;
@@ -0,0 +1,107 @@
1
+ import { Text } from "@earendil-works/pi-tui";
2
+ import { getStatusNote } from "./status-note.js";
3
+ import { formatMs, formatTokens, formatTurns } from "./ui/agent-widget.js";
4
+ import { getLifetimeTotal, getSessionContextPercent } from "./usage.js";
5
+ function getStatusLabel(status, error) {
6
+ switch (status) {
7
+ case "error": return `Error: ${error ?? "unknown"}`;
8
+ case "aborted": return "Aborted (max turns exceeded)";
9
+ case "steered": return "Wrapped up (turn limit)";
10
+ case "stopped": return "Stopped";
11
+ default: return "Done";
12
+ }
13
+ }
14
+ function escapeXml(s) {
15
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
16
+ }
17
+ export function formatTaskNotification(record, resultMaxLen) {
18
+ const status = getStatusLabel(record.status, record.error);
19
+ const durationMs = record.completedAt ? record.completedAt - record.startedAt : 0;
20
+ const totalTokens = getLifetimeTotal(record.lifetimeUsage);
21
+ const contextPercent = getSessionContextPercent(record.session);
22
+ const ctxXml = contextPercent !== null ? `<context_percent>${Math.round(contextPercent)}</context_percent>` : "";
23
+ const compactXml = record.compactionCount ? `<compactions>${record.compactionCount}</compactions>` : "";
24
+ const resultPreview = record.result
25
+ ? record.result.length > resultMaxLen
26
+ ? record.result.slice(0, resultMaxLen) + "\n...(truncated, use get_subagent_result for full output)"
27
+ : record.result
28
+ : "No output.";
29
+ const fullOutputInstruction = record.outputFile
30
+ ? `Read the full output/log with get_subagent_result for agent ${record.id}, or inspect the transcript file: ${record.outputFile}`
31
+ : `Read the full output/log with get_subagent_result for agent ${record.id}.`;
32
+ return [
33
+ `<task-notification>`,
34
+ `<task-id>${record.id}</task-id>`,
35
+ record.toolCallId ? `<tool-use-id>${escapeXml(record.toolCallId)}</tool-use-id>` : null,
36
+ record.outputFile ? `<output-file>${escapeXml(record.outputFile)}</output-file>` : null,
37
+ `<status>${escapeXml(status)}</status>`,
38
+ `<summary>Agent "${escapeXml(record.description)}" ${record.status}${getStatusNote(record.status)}</summary>`,
39
+ `<result>${escapeXml(resultPreview)}</result>`,
40
+ `<full-output>${escapeXml(fullOutputInstruction)}</full-output>`,
41
+ `<usage><total_tokens>${totalTokens}</total_tokens><tool_uses>${record.toolUses}</tool_uses>${ctxXml}${compactXml}<duration_ms>${durationMs}</duration_ms></usage>`,
42
+ `</task-notification>`,
43
+ ].filter(Boolean).join("\n");
44
+ }
45
+ export function buildNotificationDetails(record, resultMaxLen, activity) {
46
+ const totalTokens = getLifetimeTotal(record.lifetimeUsage);
47
+ return {
48
+ id: record.id,
49
+ description: record.description,
50
+ status: record.status,
51
+ toolUses: record.toolUses,
52
+ turnCount: activity?.turnCount ?? 0,
53
+ maxTurns: activity?.maxTurns,
54
+ totalTokens,
55
+ durationMs: record.completedAt ? record.completedAt - record.startedAt : 0,
56
+ outputFile: record.outputFile,
57
+ error: record.error,
58
+ resultPreview: record.result
59
+ ? record.result.length > resultMaxLen
60
+ ? record.result.slice(0, resultMaxLen) + "…"
61
+ : record.result
62
+ : "No output.",
63
+ };
64
+ }
65
+ export function registerSubagentNotificationRenderer(pi) {
66
+ pi.registerMessageRenderer("subagent-notification", (message, { expanded }, theme) => {
67
+ const d = message.details;
68
+ if (!d)
69
+ return undefined;
70
+ function renderOne(d) {
71
+ const isError = d.status === "error" || d.status === "stopped" || d.status === "aborted";
72
+ const icon = isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
73
+ const statusText = isError ? d.status
74
+ : d.status === "steered" ? "completed (steered)"
75
+ : "completed";
76
+ let line = `${icon} ${theme.bold(d.description)} ${theme.fg("dim", statusText)}`;
77
+ const parts = [];
78
+ if (d.turnCount > 0)
79
+ parts.push(formatTurns(d.turnCount, d.maxTurns));
80
+ if (d.toolUses > 0)
81
+ parts.push(`${d.toolUses} tool use${d.toolUses === 1 ? "" : "s"}`);
82
+ if (d.totalTokens > 0)
83
+ parts.push(formatTokens(d.totalTokens));
84
+ if (d.durationMs > 0)
85
+ parts.push(formatMs(d.durationMs));
86
+ if (parts.length) {
87
+ line += "\n " + parts.map(p => theme.fg("dim", p)).join(" " + theme.fg("dim", "·") + " ");
88
+ }
89
+ if (expanded) {
90
+ const lines = d.resultPreview.split("\n").slice(0, 30);
91
+ for (const resultLine of lines)
92
+ line += "\n" + theme.fg("dim", ` ${resultLine}`);
93
+ }
94
+ else {
95
+ const preview = d.resultPreview.split("\n")[0]?.slice(0, 80) ?? "";
96
+ line += "\n " + theme.fg("dim", `⎿ ${preview}`);
97
+ }
98
+ const fullOutputHint = d.outputFile
99
+ ? `full output: get_subagent_result ${d.id} or transcript: ${d.outputFile}`
100
+ : `full output: get_subagent_result ${d.id}`;
101
+ line += "\n " + theme.fg("muted", fullOutputHint);
102
+ return line;
103
+ }
104
+ const all = [d, ...(d.others ?? [])];
105
+ return new Text(all.map(renderOne).join("\n"), 0, 0);
106
+ });
107
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * output-file.ts — Streaming JSONL output file for agent transcripts.
3
+ *
4
+ * Creates a per-agent output file that streams conversation turns as JSONL,
5
+ * matching Claude Code's task output file format.
6
+ */
7
+ import type { AgentSession } from "@earendil-works/pi-coding-agent";
8
+ /**
9
+ * Encode a cwd path as a filesystem-safe directory name. Handles:
10
+ * - POSIX: "/home/user/project" → "home-user-project"
11
+ * - Windows: "C:\Users\foo\project" → "Users-foo-project"
12
+ * - UNC: "\\\\server\\share\\project" → "server-share-project"
13
+ */
14
+ export declare function encodeCwd(cwd: string): string;
15
+ /** Create the output file path, ensuring the directory exists.
16
+ * Mirrors Claude Code's layout: /tmp/{prefix}-{uid}/{encoded-cwd}/{sessionId}/tasks/{agentId}.output */
17
+ export declare function createOutputFilePath(cwd: string, agentId: string, sessionId: string): string;
18
+ /** Write the initial user prompt entry. */
19
+ export declare function writeInitialEntry(path: string, agentId: string, prompt: string, cwd: string): void;
20
+ /**
21
+ * Subscribe to session events and flush new messages to the output file on each turn_end.
22
+ * Returns a cleanup function that does a final flush and unsubscribes.
23
+ */
24
+ export declare function streamToOutputFile(session: AgentSession, path: string, agentId: string, cwd: string): () => void;
@@ -0,0 +1,86 @@
1
+ /**
2
+ * output-file.ts — Streaming JSONL output file for agent transcripts.
3
+ *
4
+ * Creates a per-agent output file that streams conversation turns as JSONL,
5
+ * matching Claude Code's task output file format.
6
+ */
7
+ import { appendFileSync, chmodSync, mkdirSync, writeFileSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ /**
11
+ * Encode a cwd path as a filesystem-safe directory name. Handles:
12
+ * - POSIX: "/home/user/project" → "home-user-project"
13
+ * - Windows: "C:\Users\foo\project" → "Users-foo-project"
14
+ * - UNC: "\\\\server\\share\\project" → "server-share-project"
15
+ */
16
+ export function encodeCwd(cwd) {
17
+ return cwd
18
+ .replace(/[/\\]/g, "-") // both separators → dash
19
+ .replace(/^[A-Za-z]:-/, "") // strip Windows drive prefix ("C:-")
20
+ .replace(/^-+/, ""); // strip leading dashes (POSIX root, UNC)
21
+ }
22
+ /** Create the output file path, ensuring the directory exists.
23
+ * Mirrors Claude Code's layout: /tmp/{prefix}-{uid}/{encoded-cwd}/{sessionId}/tasks/{agentId}.output */
24
+ export function createOutputFilePath(cwd, agentId, sessionId) {
25
+ const encoded = encodeCwd(cwd);
26
+ const root = join(tmpdir(), `pi-subagents-${process.getuid?.() ?? 0}`);
27
+ mkdirSync(root, { recursive: true, mode: 0o700 });
28
+ // chmod is a no-op on Windows and throws on some Windows filesystems.
29
+ // On Unix we still want to enforce 0o700 past umask, so only swallow on Windows.
30
+ try {
31
+ chmodSync(root, 0o700);
32
+ }
33
+ catch (err) {
34
+ if (process.platform !== "win32")
35
+ throw err;
36
+ }
37
+ const dir = join(root, encoded, sessionId, "tasks");
38
+ mkdirSync(dir, { recursive: true });
39
+ return join(dir, `${agentId}.output`);
40
+ }
41
+ /** Write the initial user prompt entry. */
42
+ export function writeInitialEntry(path, agentId, prompt, cwd) {
43
+ const entry = {
44
+ isSidechain: true,
45
+ agentId,
46
+ type: "user",
47
+ message: { role: "user", content: prompt },
48
+ timestamp: new Date().toISOString(),
49
+ cwd,
50
+ };
51
+ writeFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
52
+ }
53
+ /**
54
+ * Subscribe to session events and flush new messages to the output file on each turn_end.
55
+ * Returns a cleanup function that does a final flush and unsubscribes.
56
+ */
57
+ export function streamToOutputFile(session, path, agentId, cwd) {
58
+ let writtenCount = 1; // initial user prompt already written
59
+ const flush = () => {
60
+ const messages = session.messages;
61
+ while (writtenCount < messages.length) {
62
+ const msg = messages[writtenCount];
63
+ const entry = {
64
+ isSidechain: true,
65
+ agentId,
66
+ type: msg.role === "assistant" ? "assistant" : msg.role === "user" ? "user" : "toolResult",
67
+ message: msg,
68
+ timestamp: new Date().toISOString(),
69
+ cwd,
70
+ };
71
+ try {
72
+ appendFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
73
+ }
74
+ catch { /* ignore write errors */ }
75
+ writtenCount++;
76
+ }
77
+ };
78
+ const unsubscribe = session.subscribe((event) => {
79
+ if (event.type === "turn_end")
80
+ flush();
81
+ });
82
+ return () => {
83
+ flush();
84
+ unsubscribe();
85
+ };
86
+ }
package/dist/peek.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * peek.ts — Lightweight tail/filter view of an agent's result or streaming
3
+ * output file for `get_subagent_result`'s `peek` parameter.
4
+ *
5
+ * Design:
6
+ * - Source precedence: streaming output file (best for running agents) → record
7
+ * result (finished agents) → "no output yet".
8
+ * - The output file is JSONL (one entry per message). We extract human-readable
9
+ * text lines (assistant text + tool-result text) so a peek shows useful
10
+ * progress, not raw JSON.
11
+ * - Semantics: filter-then-tail. If `regex` is given, only matching source lines
12
+ * are kept; then `after` (return all lines past an index) or `lines` (last N)
13
+ * is applied. Line numbers always refer to the FULL source so callers can use
14
+ * `after` for incremental updates without missing anything.
15
+ */
16
+ import type { AgentRecord } from "./types.js";
17
+ export interface PeekOptions {
18
+ /** Number of trailing lines to return. Default 20. Minimum 1. */
19
+ lines?: number;
20
+ /** Optional regex filter applied to each source line (filter-then-tail). */
21
+ regex?: string;
22
+ /** Return all source lines after this 1-based line number (matches the [N] prefixes in peek output). Use the last line number you saw to fetch only new lines. Overrides `lines`. */
23
+ after?: number;
24
+ }
25
+ export interface PeekResult {
26
+ /** The formatted peek text (with line-number prefixes and a header). */
27
+ text: string;
28
+ /** Number of source lines available (before filtering). */
29
+ totalLines: number;
30
+ /** Whether the source was the output file (live) or the result. */
31
+ source: "outputFile" | "result";
32
+ }
33
+ /**
34
+ * Produce a peek view of an agent's output. Returns null when there is no
35
+ * source content at all (the caller renders a "no output yet" message).
36
+ */
37
+ export declare function peekAgentOutput(record: AgentRecord, opts?: PeekOptions): PeekResult | null;