@lune_99/pi-subagent 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +21 -0
  3. package/README.md +169 -2
  4. package/docs/capture.json +30 -0
  5. package/docs/previews.md +22 -0
  6. package/docs/reference.md +240 -0
  7. package/docs/subagent-auto-tiers.png +0 -0
  8. package/docs/subagent-inspector.png +0 -0
  9. package/docs/subagent-overview.png +0 -0
  10. package/package.json +82 -5
  11. package/skills/create-lune-subagent/SKILL.md +186 -0
  12. package/src/auto-model.ts +592 -0
  13. package/src/catalog.ts +111 -0
  14. package/src/definition-file.ts +112 -0
  15. package/src/definitions.ts +324 -0
  16. package/src/dock/dock-alert.ts +78 -0
  17. package/src/dock/dock-contribution.ts +318 -0
  18. package/src/extension-tools.ts +46 -0
  19. package/src/index.ts +168 -0
  20. package/src/inspector/details.ts +113 -0
  21. package/src/inspector/inspector.ts +653 -0
  22. package/src/inspector/layout.ts +119 -0
  23. package/src/inspector/transcript.ts +735 -0
  24. package/src/inspector/viewport.ts +62 -0
  25. package/src/inspector/wrap.ts +136 -0
  26. package/src/models.ts +54 -0
  27. package/src/notify/notification-box.ts +381 -0
  28. package/src/notify/notifier.ts +569 -0
  29. package/src/paths.ts +34 -0
  30. package/src/render/lune-theme.ts +68 -0
  31. package/src/render/text.ts +121 -0
  32. package/src/run/guide.ts +26 -0
  33. package/src/run/report-tool.ts +90 -0
  34. package/src/run/run-file.ts +193 -0
  35. package/src/run/run-manager.ts +838 -0
  36. package/src/run/run-session.ts +307 -0
  37. package/src/run/run.ts +681 -0
  38. package/src/run/session-start.ts +283 -0
  39. package/src/run/types.ts +167 -0
  40. package/src/run/worktree.ts +138 -0
  41. package/src/schema.ts +9 -0
  42. package/src/settings/agents-menu.ts +363 -0
  43. package/src/settings/panel.ts +179 -0
  44. package/src/settings/schema.ts +71 -0
  45. package/src/tools/format.ts +375 -0
  46. package/src/tools/subagent-tools.ts +467 -0
@@ -0,0 +1,121 @@
1
+ import type { Theme, ThemeBg } from "@earendil-works/pi-coding-agent";
2
+ import { sliceByColumn, stripTerminalSequences, visibleWidth } from "@earendil-works/pi-tui";
3
+
4
+ /**
5
+ * Pi's expand key, written out rather than read from `keyHint()`: that helper colours with the
6
+ * theme module's own global, which an extension's copy of the module never initializes.
7
+ */
8
+ export const EXPAND_KEY = "ctrl+o";
9
+
10
+ /**
11
+ * Clip one line to the columns a row has left.
12
+ *
13
+ * `truncateToWidth` closes a cut with a full reset, which would drop a band's background from
14
+ * everything after the ellipsis.
15
+ */
16
+ export function clipToWidth(text: string, width: number): string {
17
+ const ellipsis = "…";
18
+
19
+ if (width <= 0) {
20
+ return "";
21
+ }
22
+
23
+ if (visibleWidth(text) <= width) {
24
+ return text;
25
+ }
26
+
27
+ const ellipsisWidth = visibleWidth(ellipsis);
28
+
29
+ if (width <= ellipsisWidth) {
30
+ return sliceByColumn(ellipsis, 0, width, true);
31
+ }
32
+
33
+ return `${sliceByColumn(text, 0, width - ellipsisWidth, true)}${ellipsis}`;
34
+ }
35
+
36
+ /** A part of a one-line summary; parts with a lower rank give way first when the line is too long. */
37
+ export interface RankedPart {
38
+ text: string;
39
+ rank: number;
40
+ }
41
+
42
+ /**
43
+ * The richest line that fits in `width`. `compose` gets the kept parts in their original order;
44
+ * the lowest-ranked part, the last one among equals, is left out until the line fits. So a narrow
45
+ * row shows fewer complete parts instead of a cut one. Undefined when not even `compose([])` fits.
46
+ */
47
+ export function fitRanked(
48
+ parts: readonly RankedPart[],
49
+ width: number,
50
+ compose: (texts: readonly string[]) => string,
51
+ ): string | undefined {
52
+ const kept = [...parts];
53
+
54
+ for (;;) {
55
+ const line = compose(kept.map((part) => part.text));
56
+
57
+ if (visibleWidth(line) <= width) {
58
+ return line;
59
+ }
60
+
61
+ if (kept.length === 0) {
62
+ return undefined;
63
+ }
64
+
65
+ let lowest = 0;
66
+
67
+ for (let index = 1; index < kept.length; index++) {
68
+ if (kept[index]!.rank <= kept[lowest]!.rank) {
69
+ lowest = index;
70
+ }
71
+ }
72
+
73
+ kept.splice(lowest, 1);
74
+ }
75
+ }
76
+
77
+ // Tab, newline and carriage return stay for screenLine. A lone ESC, a backspace or a C1 byte the
78
+ // sequence parser leaves behind would move the terminal cursor and shift the frame around the row.
79
+ const CONTROL_CHARACTERS = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g;
80
+
81
+ /**
82
+ * Text from a run as plain display lines: terminal sequences and control characters removed, a
83
+ * carriage return keeping what a terminal would leave on screen, and tabs expanded because rows
84
+ * are measured in cells.
85
+ */
86
+ export function displayLines(text: string): string[] {
87
+ return stripTerminalSequences(text).replace(CONTROL_CHARACTERS, "").split("\n").map(screenLine);
88
+ }
89
+
90
+ /** Text from a run as one display line, with every run of whitespace collapsed to a space. */
91
+ export function displayLine(text: string): string {
92
+ return displayLines(text).join(" ").replace(/\s+/g, " ").trim();
93
+ }
94
+
95
+ function screenLine(line: string): string {
96
+ const segments = line.split("\r");
97
+
98
+ for (let index = segments.length - 1; index >= 0; index -= 1) {
99
+ const segment = segments[index]!;
100
+
101
+ if (segment.length > 0) {
102
+ return segment.replace(/\t/g, " ");
103
+ }
104
+ }
105
+
106
+ return "";
107
+ }
108
+
109
+ /** One row of a full-width band with side padding, like Pi's tool result box. */
110
+ export function bandRow(
111
+ theme: Theme,
112
+ token: ThemeBg,
113
+ row: string,
114
+ inner: number,
115
+ paddingX: number,
116
+ ): string {
117
+ const margin = " ".repeat(paddingX);
118
+ const fill = " ".repeat(Math.max(0, inner - visibleWidth(row)));
119
+
120
+ return theme.bg(token, `${margin}${row}${fill}${margin}`);
121
+ }
@@ -0,0 +1,26 @@
1
+ /** Marks a message the user wrote from the inspector; every other message comes from the main agent. */
2
+ export const USER_MESSAGE_MARKER = "[From the user]";
3
+
4
+ /** Fixed text after Pi's system prompt and the definition body. */
5
+ export const SUBAGENT_GUIDE = `# Subagent
6
+
7
+ You are a subagent. A main agent started this session and gave you its task in the first message. You work for the main agent and have no access to the user.
8
+
9
+ - Messages come from the main agent. A message that starts with "${USER_MESSAGE_MARKER}" comes from the user, who can write to you directly.
10
+ - End every turn with the report tool as your last action. The main agent receives the report when your turn ends.
11
+ - Use status "done" when the task is complete. Put the result in summary.
12
+ - Use status "blocked" when you cannot finish, for example because you decline the task or finish only part of it. Say why in reason and what you did in summary.
13
+ - Use status "needs_input" when you need something before you can continue, such as a clarification, a decision or missing configuration. Ask in question. The answer arrives as a new message in this session.
14
+ - Do not ask questions in plain text. Ask with needs_input.`;
15
+
16
+ export function markUserMessage(text: string): string {
17
+ return `${USER_MESSAGE_MARKER}\n${text}`;
18
+ }
19
+
20
+ export function isUserMessage(text: string): boolean {
21
+ return text.startsWith(USER_MESSAGE_MARKER);
22
+ }
23
+
24
+ export function stripUserMarker(text: string): string {
25
+ return isUserMessage(text) ? text.slice(USER_MESSAGE_MARKER.length).replace(/^\n/, "") : text;
26
+ }
@@ -0,0 +1,90 @@
1
+ import { defineTool } from "@earendil-works/pi-coding-agent";
2
+ import Type from "typebox";
3
+
4
+ import { stringEnum } from "../schema.ts";
5
+ import { REPORT_STATUSES, type RunReport } from "./types.ts";
6
+
7
+ export const REPORT_TOOL_NAME = "report";
8
+
9
+ const reportParameters = Type.Object({
10
+ status: stringEnum(REPORT_STATUSES, {
11
+ description:
12
+ '"done": the task is complete. "blocked": you cannot finish, for example because you ' +
13
+ 'decline the task or finish only part of it. "needs_input": you need something before ' +
14
+ "you can continue.",
15
+ }),
16
+ summary: Type.String({
17
+ description:
18
+ "Concise result with relevant evidence (file references, sources or artifacts), " +
19
+ "checks actually run and their outcomes, and important limitations or unverified " +
20
+ "work. For blocked, include what you completed.",
21
+ }),
22
+ reason: Type.Optional(
23
+ Type.String({ description: "Required for blocked: why you cannot finish." }),
24
+ ),
25
+ question: Type.Optional(
26
+ Type.String({ description: "Required for needs_input: what you need to continue." }),
27
+ ),
28
+ });
29
+
30
+ /**
31
+ * The run's only own tool, given to the SDK as a plain custom tool. `terminate` ends the turn when
32
+ * `report` is the only call in its batch. A later report in the same turn becomes the turn's report;
33
+ * the earlier ones still reach the main agent.
34
+ */
35
+ export function createReportTool(onReport: (report: RunReport) => void) {
36
+ return defineTool({
37
+ name: REPORT_TOOL_NAME,
38
+ label: "Report",
39
+ description:
40
+ "Report your result to the main agent. Call it as the last action of every turn. " +
41
+ "The main agent receives the report when your turn ends.",
42
+ parameters: reportParameters,
43
+ async execute(_toolCallId, params) {
44
+ const report = normalizeReport(params);
45
+
46
+ onReport(report);
47
+
48
+ return {
49
+ content: [
50
+ {
51
+ type: "text",
52
+ text: "Report recorded. The main agent receives it when this turn ends.",
53
+ },
54
+ ],
55
+ details: report,
56
+ terminate: true,
57
+ };
58
+ },
59
+ });
60
+ }
61
+
62
+ /** Throws for the model to retry, because a blocked or needs_input report without its field is useless. */
63
+ export function normalizeReport(params: {
64
+ status: RunReport["status"];
65
+ summary: string;
66
+ reason?: string;
67
+ question?: string;
68
+ }): RunReport {
69
+ const report: RunReport = { status: params.status, summary: params.summary.trim() };
70
+ const reason = params.reason?.trim();
71
+ const question = params.question?.trim();
72
+
73
+ if (params.status === "blocked" && !reason) {
74
+ throw new Error('A "blocked" report needs a reason.');
75
+ }
76
+
77
+ if (params.status === "needs_input" && !question) {
78
+ throw new Error('A "needs_input" report needs a question.');
79
+ }
80
+
81
+ if (reason) {
82
+ report.reason = reason;
83
+ }
84
+
85
+ if (question) {
86
+ report.question = question;
87
+ }
88
+
89
+ return report;
90
+ }
@@ -0,0 +1,193 @@
1
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+
4
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
5
+ import type { Usage } from "@earendil-works/pi-ai";
6
+ import {
7
+ CURRENT_SESSION_VERSION,
8
+ SessionManager,
9
+ type SessionEntry,
10
+ type SessionHeader,
11
+ } from "@earendil-works/pi-coding-agent";
12
+
13
+ import {
14
+ RUN_ENTRY_TYPE,
15
+ TURN_ENTRY_TYPE,
16
+ type RunSnapshot,
17
+ type RunUsage,
18
+ type TurnRecord,
19
+ } from "./types.ts";
20
+
21
+ /**
22
+ * Create the run file with only its session header, then open it.
23
+ *
24
+ * `SessionManager.create()` names files `<timestamp>_<id>.jsonl` and writes nothing until the first
25
+ * message; an opened file is already flushed, so every entry, the snapshot included, is written at
26
+ * once and the file exists even when the first prompt fails before any message.
27
+ */
28
+ export function createRunFile(
29
+ file: string,
30
+ header: { runId: string; cwd: string; parentSessionFile?: string },
31
+ ): SessionManager {
32
+ const sessionHeader: SessionHeader = {
33
+ type: "session",
34
+ version: CURRENT_SESSION_VERSION,
35
+ id: header.runId,
36
+ timestamp: new Date().toISOString(),
37
+ cwd: header.cwd,
38
+ ...(header.parentSessionFile ? { parentSession: header.parentSessionFile } : {}),
39
+ };
40
+
41
+ mkdirSync(dirname(file), { recursive: true });
42
+ writeFileSync(file, `${JSON.stringify(sessionHeader)}\n`, { flag: "wx" });
43
+
44
+ return SessionManager.open(file, dirname(file));
45
+ }
46
+
47
+ export interface RunFileState {
48
+ snapshot: RunSnapshot;
49
+ lastTurn: TurnRecord | undefined;
50
+ turns: number;
51
+ /**
52
+ * A message follows the last recorded turn end: the parent stopped while the turn ran, before
53
+ * the run could record how it ended.
54
+ */
55
+ unfinishedTurn: boolean;
56
+ usage: RunUsage;
57
+ }
58
+
59
+ /** Open an existing run file. Pi's own `open()` would quietly start an empty session for a missing path. */
60
+ export function openRunFile(file: string): SessionManager {
61
+ if (!existsSync(file)) {
62
+ throw new Error(`The run file is missing: ${file}`);
63
+ }
64
+
65
+ return SessionManager.open(file, dirname(file));
66
+ }
67
+
68
+ export function readRunFile(file: string): RunFileState {
69
+ return readRunEntries(openRunFile(file).getEntries(), file);
70
+ }
71
+
72
+ export function readRunEntries(entries: readonly SessionEntry[], file: string): RunFileState {
73
+ let snapshot: RunSnapshot | undefined;
74
+ let lastTurn: TurnRecord | undefined;
75
+ let turns = 0;
76
+ let messageAfterTurn = false;
77
+
78
+ for (const entry of entries) {
79
+ if (entry.type === "custom" && entry.customType === RUN_ENTRY_TYPE && !snapshot) {
80
+ snapshot = parseSnapshot(entry.data, file);
81
+ } else if (entry.type === "custom" && entry.customType === TURN_ENTRY_TYPE) {
82
+ lastTurn = parseTurnRecord(entry.data, file);
83
+ turns += 1;
84
+ messageAfterTurn = false;
85
+ } else if (
86
+ entry.type === "message" &&
87
+ (entry.message.role === "user" || entry.message.role === "assistant")
88
+ ) {
89
+ messageAfterTurn = true;
90
+ }
91
+ }
92
+
93
+ if (!snapshot) {
94
+ throw new Error(`The run file has no ${RUN_ENTRY_TYPE} entry: ${file}`);
95
+ }
96
+
97
+ return {
98
+ snapshot,
99
+ lastTurn,
100
+ turns,
101
+ unfinishedTurn: messageAfterTurn,
102
+ usage: usageFromEntries(entries),
103
+ };
104
+ }
105
+
106
+ /** The run's own token usage; it is never added to the parent session's totals. */
107
+ export function usageFromEntries(entries: readonly SessionEntry[]): RunUsage {
108
+ const totals: RunUsage = {
109
+ input: 0,
110
+ output: 0,
111
+ cacheRead: 0,
112
+ cacheWrite: 0,
113
+ total: 0,
114
+ cost: 0,
115
+ };
116
+ const add = (usage: Usage | undefined): void => {
117
+ if (!usage) {
118
+ return;
119
+ }
120
+
121
+ totals.input += usage.input;
122
+ totals.output += usage.output;
123
+ totals.cacheRead += usage.cacheRead;
124
+ totals.cacheWrite += usage.cacheWrite;
125
+ totals.cost += usage.cost.total;
126
+ };
127
+
128
+ // The same entries Pi's own getSessionStats() counts.
129
+ for (const entry of entries) {
130
+ if (entry.type === "usage") {
131
+ add(entry.usage);
132
+ } else if (entry.type === "compaction" || entry.type === "branch_summary") {
133
+ add(entry.usage);
134
+ } else if (entry.type === "message") {
135
+ const message = entry.message;
136
+
137
+ if (message.role === "assistant") {
138
+ add(message.usage);
139
+ } else if (message.role === "toolResult") {
140
+ add((message as { usage?: Usage }).usage);
141
+ }
142
+ }
143
+ }
144
+
145
+ totals.total = totals.input + totals.output + totals.cacheRead + totals.cacheWrite;
146
+
147
+ return totals;
148
+ }
149
+
150
+ /** Every message of the run, in order; a run session never branches. */
151
+ export function transcriptMessages(entries: readonly SessionEntry[]): AgentMessage[] {
152
+ const messages: AgentMessage[] = [];
153
+
154
+ for (const entry of entries) {
155
+ if (entry.type === "message") {
156
+ messages.push(entry.message);
157
+ }
158
+ }
159
+
160
+ return messages;
161
+ }
162
+
163
+ function parseSnapshot(data: unknown, file: string): RunSnapshot {
164
+ const snapshot = data as Partial<RunSnapshot> | undefined;
165
+
166
+ if (
167
+ !snapshot ||
168
+ typeof snapshot.runId !== "string" ||
169
+ typeof snapshot.name !== "string" ||
170
+ typeof snapshot.task !== "string" ||
171
+ typeof snapshot.model !== "string" ||
172
+ typeof snapshot.cwd !== "string" ||
173
+ !Array.isArray(snapshot.tools) ||
174
+ (snapshot.isolation !== "shared" && snapshot.isolation !== "worktree")
175
+ ) {
176
+ throw new Error(`The run file has an invalid ${RUN_ENTRY_TYPE} entry: ${file}`);
177
+ }
178
+
179
+ return snapshot as RunSnapshot;
180
+ }
181
+
182
+ function parseTurnRecord(data: unknown, file: string): TurnRecord {
183
+ const record = data as Partial<TurnRecord> | undefined;
184
+
185
+ if (
186
+ !record ||
187
+ (record.state !== "idle" && record.state !== "failed" && record.state !== "interrupted")
188
+ ) {
189
+ throw new Error(`The run file has an invalid ${TURN_ENTRY_TYPE} entry: ${file}`);
190
+ }
191
+
192
+ return record as TurnRecord;
193
+ }