@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,297 @@
1
+ /**
2
+ * conversation-viewer.ts — Live conversation overlay for viewing agent sessions.
3
+ *
4
+ * Displays a scrollable, live-updating view of an agent's conversation.
5
+ * Subscribes to session events for real-time streaming updates.
6
+ */
7
+
8
+ import type { AgentSession } from "@earendil-works/pi-coding-agent";
9
+ import { type Component, matchesKey, type TUI, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
10
+ import { extractText } from "../context.js";
11
+ import type { AgentRecord } from "../types.js";
12
+ import { getLifetimeTotal, getSessionContextPercent } from "../usage.js";
13
+ import type { Theme } from "./agent-widget.js";
14
+ import { type AgentActivity, buildInvocationTags, describeActivity, formatDuration, formatSessionTokens, getDisplayName, getPromptModeLabel } from "./agent-widget.js";
15
+ import { createViewerKeys, type ViewerKeybindings, type ViewerKeys } from "./viewer-keys.js";
16
+
17
+ /** Base lines consumed by chrome: top border + header + header sep + footer sep + footer + bottom border. */
18
+ const CHROME_LINES_BASE = 6;
19
+ const MIN_VIEWPORT = 3;
20
+ /** Height ceiling shared by the overlay's `maxHeight` and the viewer's internal viewport cap. */
21
+ export const VIEWPORT_HEIGHT_PCT = 70;
22
+
23
+ export class ConversationViewer implements Component {
24
+ private scrollOffset = 0;
25
+ private autoScroll = true;
26
+ private unsubscribe: (() => void) | undefined;
27
+ private lastInnerW = 0;
28
+ private closed = false;
29
+ /** Two-press confirm guard for the stop key, so a stray key can't kill the agent. */
30
+ private stopArmed = false;
31
+ private keys: ViewerKeys;
32
+
33
+ constructor(
34
+ private tui: TUI,
35
+ private session: AgentSession,
36
+ private record: AgentRecord,
37
+ private activity: AgentActivity | undefined,
38
+ private theme: Theme,
39
+ private done: (result: undefined) => void,
40
+ /** Abort the agent shown here. Omitted → no stop affordance (e.g. read-only history). */
41
+ private onStop?: () => void,
42
+ /** User keybindings from `ctx.ui.custom()`. Omitted → hardcoded defaults. */
43
+ keybindings?: ViewerKeybindings,
44
+ ) {
45
+ this.keys = createViewerKeys(keybindings);
46
+ this.unsubscribe = session.subscribe(() => {
47
+ if (this.closed) return;
48
+ this.tui.requestRender();
49
+ });
50
+ }
51
+
52
+ handleInput(data: string): void {
53
+ if (matchesKey(data, "escape") || matchesKey(data, "q")) {
54
+ this.closed = true;
55
+ this.done(undefined);
56
+ return;
57
+ }
58
+
59
+ // Stop/abort the agent (only while it can still be stopped). Two-press:
60
+ // first "x" arms, second confirms — any other key disarms.
61
+ if (matchesKey(data, "x")) {
62
+ if (this.isStoppable()) {
63
+ if (this.stopArmed) {
64
+ this.stopArmed = false;
65
+ this.onStop?.();
66
+ } else {
67
+ this.stopArmed = true;
68
+ }
69
+ this.tui.requestRender();
70
+ }
71
+ return;
72
+ }
73
+ if (this.stopArmed) this.stopArmed = false;
74
+
75
+ const totalLines = this.buildContentLines(this.lastInnerW).length;
76
+ const viewportHeight = this.viewportHeight();
77
+ const maxScroll = Math.max(0, totalLines - viewportHeight);
78
+
79
+ if (this.keys.scrollUp(data)) {
80
+ this.scrollOffset = Math.max(0, this.scrollOffset - 1);
81
+ this.autoScroll = this.scrollOffset >= maxScroll;
82
+ } else if (this.keys.scrollDown(data)) {
83
+ this.scrollOffset = Math.min(maxScroll, this.scrollOffset + 1);
84
+ this.autoScroll = this.scrollOffset >= maxScroll;
85
+ } else if (this.keys.pageUp(data)) {
86
+ this.scrollOffset = Math.max(0, this.scrollOffset - viewportHeight);
87
+ this.autoScroll = false;
88
+ } else if (this.keys.pageDown(data)) {
89
+ this.scrollOffset = Math.min(maxScroll, this.scrollOffset + viewportHeight);
90
+ this.autoScroll = this.scrollOffset >= maxScroll;
91
+ } else if (matchesKey(data, "home")) {
92
+ this.scrollOffset = 0;
93
+ this.autoScroll = false;
94
+ } else if (matchesKey(data, "end")) {
95
+ this.scrollOffset = maxScroll;
96
+ this.autoScroll = true;
97
+ }
98
+ }
99
+
100
+ render(width: number): string[] {
101
+ if (width < 6) return []; // too narrow for any meaningful rendering
102
+ const th = this.theme;
103
+ const innerW = width - 4; // border + padding
104
+ this.lastInnerW = innerW;
105
+ const lines: string[] = [];
106
+
107
+ const pad = (s: string, len: number) => {
108
+ const vis = visibleWidth(s);
109
+ return s + " ".repeat(Math.max(0, len - vis));
110
+ };
111
+ const row = (content: string) =>
112
+ th.fg("border", "│") + " " + truncateToWidth(pad(content, innerW), innerW) + " " + th.fg("border", "│");
113
+ const hrTop = th.fg("border", `╭${"─".repeat(width - 2)}╮`);
114
+ const hrBot = th.fg("border", `╰${"─".repeat(width - 2)}╯`);
115
+ const hrMid = row(th.fg("dim", "─".repeat(innerW)));
116
+
117
+ // Header
118
+ lines.push(hrTop);
119
+ const name = getDisplayName(this.record.type);
120
+ const modeLabel = getPromptModeLabel(this.record.type);
121
+ const modeTag = modeLabel ? ` ${th.fg("dim", `(${modeLabel})`)}` : "";
122
+ const statusIcon = this.record.status === "running"
123
+ ? th.fg("accent", "●")
124
+ : this.record.status === "completed"
125
+ ? th.fg("success", "✓")
126
+ : this.record.status === "error"
127
+ ? th.fg("error", "✗")
128
+ : th.fg("dim", "○");
129
+ const duration = formatDuration(this.record.startedAt, this.record.completedAt);
130
+
131
+ const headerParts: string[] = [duration];
132
+ const toolUses = this.activity?.toolUses ?? this.record.toolUses;
133
+ if (toolUses > 0) headerParts.unshift(`${toolUses} tool${toolUses === 1 ? "" : "s"}`);
134
+ const tokens = getLifetimeTotal(this.activity?.lifetimeUsage);
135
+ if (tokens > 0) {
136
+ const percent = getSessionContextPercent(this.activity?.session);
137
+ headerParts.push(formatSessionTokens(tokens, percent, th, this.record.compactionCount));
138
+ }
139
+
140
+ lines.push(row(
141
+ `${statusIcon} ${th.bold(name)}${modeTag} ${th.fg("muted", this.record.description)} ${th.fg("dim", "·")} ${th.fg("dim", headerParts.join(" · "))}`,
142
+ ));
143
+ const invocationLine = this.invocationLine();
144
+ if (invocationLine) lines.push(row(invocationLine));
145
+ lines.push(hrMid);
146
+
147
+ // Content area — rebuild every render (live data, no cache needed)
148
+ const contentLines = this.buildContentLines(innerW);
149
+ const viewportHeight = this.viewportHeight();
150
+ const maxScroll = Math.max(0, contentLines.length - viewportHeight);
151
+
152
+ if (this.autoScroll) {
153
+ this.scrollOffset = maxScroll;
154
+ }
155
+
156
+ const visibleStart = Math.min(this.scrollOffset, maxScroll);
157
+ const visible = contentLines.slice(visibleStart, visibleStart + viewportHeight);
158
+
159
+ for (let i = 0; i < viewportHeight; i++) {
160
+ lines.push(row(visible[i] ?? ""));
161
+ }
162
+
163
+ // Footer
164
+ lines.push(hrMid);
165
+ const scrollPct = contentLines.length <= viewportHeight
166
+ ? "100%"
167
+ : `${Math.round(((visibleStart + viewportHeight) / contentLines.length) * 100)}%`;
168
+ const footerLeft = th.fg("dim", `${contentLines.length} lines · ${scrollPct}`);
169
+ const scrollHint = th.fg("dim", "↑↓ scroll · PgUp/PgDn or Shift+↑↓ · Esc close");
170
+ // Stop hint goes first in the right group so it survives right-edge
171
+ // truncation on narrow terminals (the scroll hint is the expendable part).
172
+ const footerRight = this.isStoppable()
173
+ ? (this.stopArmed ? th.fg("error", "x again to STOP") : th.fg("dim", "x stop")) +
174
+ th.fg("dim", " · ") + scrollHint
175
+ : scrollHint;
176
+ const footerGap = Math.max(1, innerW - visibleWidth(footerLeft) - visibleWidth(footerRight));
177
+ lines.push(row(footerLeft + " ".repeat(footerGap) + footerRight));
178
+ lines.push(hrBot);
179
+
180
+ return lines;
181
+ }
182
+
183
+ /** Stoppable only when a stop handler exists and the agent is still active. */
184
+ private isStoppable(): boolean {
185
+ return !!this.onStop && (this.record.status === "running" || this.record.status === "queued");
186
+ }
187
+
188
+ invalidate(): void { /* no cached state to clear */ }
189
+
190
+ dispose(): void {
191
+ this.closed = true;
192
+ if (this.unsubscribe) {
193
+ this.unsubscribe();
194
+ this.unsubscribe = undefined;
195
+ }
196
+ }
197
+
198
+ // ---- Private ----
199
+
200
+ private viewportHeight(): number {
201
+ // Cap mirrors the overlay's maxHeight — otherwise the viewer would render
202
+ // more lines than the overlay shows and clip the footer.
203
+ const maxRows = Math.floor((this.tui.terminal.rows * VIEWPORT_HEIGHT_PCT) / 100);
204
+ return Math.max(MIN_VIEWPORT, maxRows - this.chromeLines());
205
+ }
206
+
207
+ private chromeLines(): number {
208
+ return CHROME_LINES_BASE + (this.invocationLine() ? 1 : 0);
209
+ }
210
+
211
+ private invocationLine(): string | undefined {
212
+ const { modelName, tags } = buildInvocationTags(this.record.invocation);
213
+ const parts = modelName ? [modelName, ...tags] : tags;
214
+ if (parts.length === 0) return undefined;
215
+ return this.theme.fg("dim", ` ↳ ${parts.join(" · ")}`);
216
+ }
217
+
218
+ private buildContentLines(width: number): string[] {
219
+ if (width <= 0) return [];
220
+
221
+ const th = this.theme;
222
+ const messages = this.session.messages;
223
+ const lines: string[] = [];
224
+
225
+ if (messages.length === 0) {
226
+ lines.push(th.fg("dim", "(waiting for first message...)"));
227
+ return lines;
228
+ }
229
+
230
+ let needsSeparator = false;
231
+ for (const msg of messages) {
232
+ if (msg.role === "user") {
233
+ const text = typeof msg.content === "string"
234
+ ? msg.content
235
+ : extractText(msg.content);
236
+ if (!text.trim()) continue;
237
+ if (needsSeparator) lines.push(th.fg("dim", "───"));
238
+ lines.push(th.fg("accent", "[User]"));
239
+ for (const line of wrapTextWithAnsi(text.trim(), width)) {
240
+ lines.push(line);
241
+ }
242
+ } else if (msg.role === "assistant") {
243
+ const textParts: string[] = [];
244
+ const toolCalls: string[] = [];
245
+ for (const c of msg.content) {
246
+ if (c.type === "text" && c.text) textParts.push(c.text);
247
+ else if (c.type === "toolCall") {
248
+ toolCalls.push((c as any).name ?? (c as any).toolName ?? "unknown");
249
+ }
250
+ }
251
+ if (needsSeparator) lines.push(th.fg("dim", "───"));
252
+ lines.push(th.bold("[Assistant]"));
253
+ if (textParts.length > 0) {
254
+ for (const line of wrapTextWithAnsi(textParts.join("\n").trim(), width)) {
255
+ lines.push(line);
256
+ }
257
+ }
258
+ for (const name of toolCalls) {
259
+ lines.push(truncateToWidth(th.fg("muted", ` [Tool: ${name}]`), width));
260
+ }
261
+ } else if (msg.role === "toolResult") {
262
+ const text = extractText(msg.content);
263
+ const truncated = text.length > 500 ? text.slice(0, 500) + "... (truncated)" : text;
264
+ if (!truncated.trim()) continue;
265
+ if (needsSeparator) lines.push(th.fg("dim", "───"));
266
+ lines.push(th.fg("dim", "[Result]"));
267
+ for (const line of wrapTextWithAnsi(truncated.trim(), width)) {
268
+ lines.push(th.fg("dim", line));
269
+ }
270
+ } else if ((msg as any).role === "bashExecution") {
271
+ const bash = msg as any;
272
+ if (needsSeparator) lines.push(th.fg("dim", "───"));
273
+ lines.push(truncateToWidth(th.fg("muted", ` $ ${bash.command}`), width));
274
+ if (bash.output?.trim()) {
275
+ const out = bash.output.length > 500
276
+ ? bash.output.slice(0, 500) + "... (truncated)"
277
+ : bash.output;
278
+ for (const line of wrapTextWithAnsi(out.trim(), width)) {
279
+ lines.push(th.fg("dim", line));
280
+ }
281
+ }
282
+ } else {
283
+ continue;
284
+ }
285
+ needsSeparator = true;
286
+ }
287
+
288
+ // Streaming indicator for running agents
289
+ if (this.record.status === "running" && this.activity) {
290
+ const act = describeActivity(this.activity.activeTools, this.activity.responseText);
291
+ lines.push("");
292
+ lines.push(truncateToWidth(th.fg("accent", "▍ ") + th.fg("dim", act), width));
293
+ }
294
+
295
+ return lines.map(l => truncateToWidth(l, width));
296
+ }
297
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * menu-select.ts — Custom select dialog with left/right arrow navigation.
3
+ *
4
+ * Mirrors `ctx.ui.select()` but adds horizontal arrow semantics for nested
5
+ * menus: left arrow goes back (like Esc), right arrow selects (like Enter).
6
+ */
7
+
8
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
9
+ import { getSelectListTheme } from "@earendil-works/pi-coding-agent";
10
+ import { Container, matchesKey, SelectList, Spacer, Text } from "@earendil-works/pi-tui";
11
+
12
+ export interface MenuSelectOptions {
13
+ title: string;
14
+ options: string[];
15
+ /** Optional descriptions keyed by option string. */
16
+ descriptions?: Record<string, string>;
17
+ /** Maximum number of items visible at once. Defaults to all items. */
18
+ maxVisible?: number;
19
+ }
20
+
21
+ /**
22
+ * Show a selectable menu and return the chosen option, or `undefined` if the
23
+ * user backed out with Esc or the left arrow.
24
+ */
25
+ export async function menuSelect(
26
+ ctx: ExtensionCommandContext,
27
+ opts: MenuSelectOptions,
28
+ ): Promise<string | undefined> {
29
+ const items = opts.options.map((value) => ({
30
+ value,
31
+ label: value,
32
+ description: opts.descriptions?.[value],
33
+ }));
34
+
35
+ return ctx.ui.custom<string | undefined>((_tui, theme, _kb, done) => {
36
+ const list = new SelectList(
37
+ items,
38
+ opts.maxVisible ?? items.length,
39
+ getSelectListTheme(),
40
+ );
41
+ list.onSelect = (item) => done(item.value);
42
+ list.onCancel = () => done(undefined);
43
+
44
+ const container = new Container();
45
+ container.addChild(new Text(theme.bold(opts.title), 0, 0));
46
+ container.addChild(new Spacer(1));
47
+ container.addChild(list);
48
+
49
+ return {
50
+ render: (w: number) => container.render(w),
51
+ invalidate: () => container.invalidate(),
52
+ handleInput: (data: string) => {
53
+ if (matchesKey(data, "left") || matchesKey(data, "escape")) {
54
+ done(undefined);
55
+ return;
56
+ }
57
+ if (matchesKey(data, "right") || matchesKey(data, "enter")) {
58
+ const selected = list.getSelectedItem();
59
+ if (selected) {
60
+ done(selected.value);
61
+ }
62
+ return;
63
+ }
64
+ list.handleInput(data);
65
+ },
66
+ };
67
+ });
68
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * schedule-menu.ts — `/agents → Scheduled jobs` submenu.
3
+ *
4
+ * Minimal v1 surface: list scheduled jobs, select one to inspect details +
5
+ * confirm cancellation. No create wizard (the `Agent` tool's `schedule` param
6
+ * is the canonical creation path), no toggle/cleanup (cancel is enough for
7
+ * "I scheduled something dumb, get rid of it"). Add management surfaces here
8
+ * if real demand emerges.
9
+ */
10
+
11
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
12
+ import type { SubagentScheduler } from "../schedule.js";
13
+ import type { ScheduledSubagent } from "../types.js";
14
+ import { menuSelect } from "./menu-select.js";
15
+
16
+ /** Format an ISO timestamp as relative time ("in 4h", "2d ago", "—"). */
17
+ function relTime(iso: string | undefined, now = Date.now()): string {
18
+ if (!iso) return "—";
19
+ const t = new Date(iso).getTime();
20
+ if (Number.isNaN(t)) return "—";
21
+ const diff = t - now;
22
+ const abs = Math.abs(diff);
23
+ const future = diff > 0;
24
+ if (abs < 60_000) return future ? "in <1m" : "<1m ago";
25
+ const m = Math.round(abs / 60_000);
26
+ if (m < 60) return future ? `in ${m}m` : `${m}m ago`;
27
+ const h = Math.round(abs / 3_600_000);
28
+ if (h < 24) return future ? `in ${h}h` : `${h}h ago`;
29
+ const d = Math.round(abs / 86_400_000);
30
+ return future ? `in ${d}d` : `${d}d ago`;
31
+ }
32
+
33
+ /** One-line status icon. */
34
+ function statusIcon(j: ScheduledSubagent): string {
35
+ if (!j.enabled) return "✗";
36
+ if (j.lastStatus === "error") return "!";
37
+ if (j.lastStatus === "running") return "⋯";
38
+ return "✓";
39
+ }
40
+
41
+ /** Compact selectable row — name, schedule, agent type, next/last run, count. */
42
+ function formatJob(j: ScheduledSubagent, scheduler: SubagentScheduler): string {
43
+ const next = scheduler.getNextRun(j.id);
44
+ return [
45
+ statusIcon(j),
46
+ j.name.padEnd(18).slice(0, 18),
47
+ j.schedule.padEnd(14).slice(0, 14),
48
+ `[${j.subagent_type}]`,
49
+ `next ${relTime(next)}`,
50
+ `last ${relTime(j.lastRun)}`,
51
+ `runs ${j.runCount}`,
52
+ ].join(" ");
53
+ }
54
+
55
+ /** Multi-line details block for the cancel confirm. */
56
+ function formatDetails(j: ScheduledSubagent, scheduler: SubagentScheduler): string {
57
+ const next = scheduler.getNextRun(j.id) ?? "—";
58
+ return [
59
+ `name: ${j.name}`,
60
+ `schedule: ${j.schedule} (${j.scheduleType})`,
61
+ `agent: ${j.subagent_type}`,
62
+ `prompt: ${j.prompt.slice(0, 200)}${j.prompt.length > 200 ? "…" : ""}`,
63
+ `created: ${j.createdAt}`,
64
+ `last run: ${j.lastRun ?? "—"} (${j.lastStatus ?? "—"})`,
65
+ `next run: ${next}`,
66
+ `runs: ${j.runCount}`,
67
+ ].join("\n");
68
+ }
69
+
70
+ /**
71
+ * List scheduled jobs; selecting one opens a cancel-confirm with details.
72
+ * Returns when the user backs out or after a cancellation.
73
+ */
74
+ export async function showSchedulesMenu(
75
+ ctx: ExtensionCommandContext,
76
+ scheduler: SubagentScheduler,
77
+ ): Promise<void> {
78
+ if (!scheduler.isActive()) {
79
+ ctx.ui.notify("Scheduler is not active in this session.", "warning");
80
+ return;
81
+ }
82
+
83
+ const jobs = scheduler.list();
84
+ if (jobs.length === 0) {
85
+ ctx.ui.notify("No scheduled jobs.", "info");
86
+ return;
87
+ }
88
+
89
+ const labels = jobs.map(j => formatJob(j, scheduler));
90
+ const choice = await menuSelect(ctx, {
91
+ title: `Scheduled jobs (${jobs.length}) — select to cancel`,
92
+ options: labels,
93
+ });
94
+ if (!choice) return;
95
+
96
+ const idx = labels.indexOf(choice);
97
+ if (idx < 0) return;
98
+ const job = jobs[idx];
99
+
100
+ const ok = await ctx.ui.confirm(`Cancel "${job.name}"?`, formatDetails(job, scheduler));
101
+ if (!ok) return;
102
+
103
+ scheduler.removeJob(job.id);
104
+ ctx.ui.notify(`Cancelled "${job.name}".`, "info");
105
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * viewer-keys.ts — Scroll key matchers for the conversation viewer.
3
+ *
4
+ * Resolves `tui.select.*` through the user's keybindings when pi provides a
5
+ * manager, falling back to the previous hardcoded keys otherwise. The viewer's
6
+ * k/j and shift+arrow aliases always work alongside whatever is bound.
7
+ */
8
+
9
+ import { type KeyId, matchesKey } from "@earendil-works/pi-tui";
10
+
11
+ /** The `tui.select.*` keybinding ids the viewer resolves. */
12
+ export type ViewerScrollKeybinding =
13
+ | "tui.select.up"
14
+ | "tui.select.down"
15
+ | "tui.select.pageUp"
16
+ | "tui.select.pageDown";
17
+
18
+ /** Structural subset of pi-tui's `KeybindingsManager` (which satisfies it). */
19
+ export interface ViewerKeybindings {
20
+ matches(data: string, keybinding: ViewerScrollKeybinding): boolean;
21
+ }
22
+
23
+ export interface ViewerKeys {
24
+ scrollUp(data: string): boolean;
25
+ scrollDown(data: string): boolean;
26
+ pageUp(data: string): boolean;
27
+ pageDown(data: string): boolean;
28
+ }
29
+
30
+ export function createViewerKeys(keybindings?: ViewerKeybindings): ViewerKeys {
31
+ const matches = (data: string, id: ViewerScrollKeybinding, fallback: KeyId): boolean =>
32
+ keybindings ? keybindings.matches(data, id) : matchesKey(data, fallback);
33
+ return {
34
+ scrollUp: (data) => matches(data, "tui.select.up", "up") || matchesKey(data, "k"),
35
+ scrollDown: (data) => matches(data, "tui.select.down", "down") || matchesKey(data, "j"),
36
+ pageUp: (data) => matches(data, "tui.select.pageUp", "pageUp") || matchesKey(data, "shift+up"),
37
+ pageDown: (data) => matches(data, "tui.select.pageDown", "pageDown") || matchesKey(data, "shift+down"),
38
+ };
39
+ }
package/src/usage.ts ADDED
@@ -0,0 +1,60 @@
1
+ /** usage.ts — Token usage: shapes, accumulator operators, session-stats readers. */
2
+
3
+ /**
4
+ * Lifetime usage components, accumulated via `message_end` events. Survives
5
+ * compaction (which replaces session.state.messages and would reset any
6
+ * stats-derived sum). cacheRead is excluded because each turn's cacheRead is
7
+ * the cumulative cached prefix re-read on that one call — summing across
8
+ * turns counts the prefix N times. See issue #38.
9
+ */
10
+ export type LifetimeUsage = { input: number; output: number; cacheWrite: number };
11
+
12
+ /** Sum of lifetime usage components, or 0 if undefined. */
13
+ export function getLifetimeTotal(u?: LifetimeUsage): number {
14
+ return u ? u.input + u.output + u.cacheWrite : 0;
15
+ }
16
+
17
+ /** Add a usage delta into a target accumulator (mutates target). */
18
+ export function addUsage(into: LifetimeUsage, delta: LifetimeUsage): void {
19
+ into.input += delta.input;
20
+ into.output += delta.output;
21
+ into.cacheWrite += delta.cacheWrite;
22
+ }
23
+
24
+ /** Minimal shape we read from upstream `getSessionStats()`. */
25
+ export type SessionStatsLike = {
26
+ tokens: { input: number; output: number; cacheWrite: number };
27
+ contextUsage?: { percent: number | null };
28
+ };
29
+ export type SessionLike = { getSessionStats(): SessionStatsLike };
30
+
31
+ /**
32
+ * Session-scoped token count: input + output + cacheWrite as reported by
33
+ * upstream `getSessionStats().tokens` for the *current* session window.
34
+ *
35
+ * RESETS at compaction — upstream replaces `session.state.messages` and the
36
+ * stats are derived from that array. For a lifetime total that survives
37
+ * compaction, use `getLifetimeTotal(lifetimeUsage)` instead, which reads
38
+ * from an independent accumulator fed by `message_end` events.
39
+ *
40
+ * Avoids upstream's `tokens.total` field, which sums per-turn `cacheRead`
41
+ * and so counts the cumulative cached prefix N times across N turns
42
+ * (issue #38).
43
+ */
44
+ export function getSessionTokens(session: SessionLike | undefined): number {
45
+ if (!session) return 0;
46
+ try {
47
+ const t = session.getSessionStats().tokens;
48
+ return t.input + t.output + t.cacheWrite;
49
+ } catch { return 0; }
50
+ }
51
+
52
+ /**
53
+ * Context-window utilization (0–100), or null when unavailable
54
+ * (no model contextWindow, or post-compaction before the next response).
55
+ */
56
+ export function getSessionContextPercent(session: SessionLike | undefined): number | null {
57
+ if (!session) return null;
58
+ try { return session.getSessionStats().contextUsage?.percent ?? null; }
59
+ catch { return null; }
60
+ }
package/src/wait.ts ADDED
@@ -0,0 +1,44 @@
1
+ export type WaitOutcome = "completed" | "timeout" | "aborted";
2
+
3
+ /** Human-readable "Xm Ys" for a duration in seconds. */
4
+ export function formatWaitTimeout(seconds: number): string {
5
+ const m = Math.floor(seconds / 60);
6
+ const s = seconds % 60;
7
+ return m > 0 ? `${m}m${s > 0 ? ` ${s}s` : ""}` : `${s}s`;
8
+ }
9
+
10
+ /**
11
+ * Race an agent completion promise against the configured wait timeout and the
12
+ * parent abort signal. The subagent is never aborted here.
13
+ */
14
+ export function raceWait(
15
+ promise: Promise<string>,
16
+ signal: AbortSignal | undefined,
17
+ timeoutSeconds: number,
18
+ ): Promise<WaitOutcome> {
19
+ return new Promise((resolve) => {
20
+ let settled = false;
21
+ const finish = (outcome: WaitOutcome) => {
22
+ if (settled) return;
23
+ settled = true;
24
+ clearTimeout(timer);
25
+ signal?.removeEventListener("abort", onAbort);
26
+ resolve(outcome);
27
+ };
28
+ const timer = setTimeout(() => finish("timeout"), timeoutSeconds * 1000);
29
+ const onAbort = () => finish("aborted");
30
+ signal?.addEventListener("abort", onAbort, { once: true });
31
+ promise.then(() => finish("completed"));
32
+ });
33
+ }
34
+
35
+ /** Message returned when a wait ends with the agent still running. */
36
+ export function waitTimeoutMessage(outcome: WaitOutcome, timeoutSeconds: number): string {
37
+ if (outcome === "timeout") {
38
+ return `Agent is still running. The wait timed out after ${formatWaitTimeout(timeoutSeconds)} to avoid blocking the parent session longer than the configured limit.\nCall get_subagent_result with wait: true again to keep waiting, or omit wait to check status.`;
39
+ }
40
+ if (outcome === "aborted") {
41
+ return `Agent is still running. The wait was cancelled by the user (parent turn aborted). The subagent was NOT stopped — it continues in the background.\nCall get_subagent_result with wait: true again to keep waiting, use peek to check progress, or omit wait to check status.`;
42
+ }
43
+ return "Agent is still running. Use peek to check recent progress, wait: true to block until it finishes, or check back later.";
44
+ }