@timmyjl12/pi-subagents 0.20.0 → 0.21.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 (159) hide show
  1. package/CHANGELOG.md +862 -827
  2. package/README.md +1125 -1080
  3. package/dist/active-agents-prompt.d.ts +31 -9
  4. package/dist/active-agents-prompt.js +73 -9
  5. package/dist/agent-color.js +9 -1
  6. package/dist/agent-file-toggle.d.ts +1 -1
  7. package/dist/agent-manager.d.ts +405 -18
  8. package/dist/agent-manager.js +1661 -131
  9. package/dist/agent-runner.d.ts +45 -6
  10. package/dist/agent-runner.js +109 -18
  11. package/dist/agent-types.d.ts +30 -7
  12. package/dist/agent-types.js +38 -9
  13. package/dist/awaited-result.d.ts +37 -0
  14. package/dist/awaited-result.js +150 -0
  15. package/dist/child-session-shutdown.d.ts +19 -1
  16. package/dist/child-session-shutdown.js +60 -11
  17. package/dist/cleanup-plans.d.ts +10 -0
  18. package/dist/cleanup-plans.js +112 -0
  19. package/dist/cross-extension-rpc.d.ts +8 -1
  20. package/dist/cross-extension-rpc.js +59 -5
  21. package/dist/custom-agents.d.ts +34 -9
  22. package/dist/custom-agents.js +308 -111
  23. package/dist/default-agents.d.ts +1 -1
  24. package/dist/env.d.ts +1 -1
  25. package/dist/error-log.d.ts +6 -0
  26. package/dist/error-log.js +8 -0
  27. package/dist/force-main-model.d.ts +21 -0
  28. package/dist/force-main-model.js +28 -0
  29. package/dist/goal-bridge.d.ts +155 -0
  30. package/dist/goal-bridge.js +305 -0
  31. package/dist/group-join.d.ts +5 -1
  32. package/dist/group-join.js +52 -7
  33. package/dist/index.d.ts +5 -5
  34. package/dist/index.js +2827 -333
  35. package/dist/invocation-config.d.ts +30 -3
  36. package/dist/invocation-config.js +30 -1
  37. package/dist/memory.d.ts +1 -1
  38. package/dist/mention-clone.d.ts +1 -1
  39. package/dist/model-scope.d.ts +1 -1
  40. package/dist/nested-tools.d.ts +22 -1
  41. package/dist/nested-tools.js +120 -26
  42. package/dist/output-file.d.ts +15 -4
  43. package/dist/output-file.js +146 -43
  44. package/dist/prompts.d.ts +1 -1
  45. package/dist/recovery.d.ts +1 -1
  46. package/dist/report-cleanup.d.ts +204 -0
  47. package/dist/report-cleanup.js +1632 -0
  48. package/dist/report-store.d.ts +738 -0
  49. package/dist/report-store.js +3612 -0
  50. package/dist/schedule-store.d.ts +14 -6
  51. package/dist/schedule-store.js +88 -58
  52. package/dist/schedule.d.ts +20 -8
  53. package/dist/schedule.js +135 -74
  54. package/dist/settings.d.ts +39 -11
  55. package/dist/settings.js +22 -5
  56. package/dist/status-note.d.ts +1 -1
  57. package/dist/structured-output.d.ts +1 -1
  58. package/dist/types.d.ts +32 -3
  59. package/dist/ui/agent-mention.d.ts +2 -2
  60. package/dist/ui/agent-widget.d.ts +82 -13
  61. package/dist/ui/agent-widget.js +155 -37
  62. package/dist/ui/cleanup-preview.d.ts +59 -0
  63. package/dist/ui/cleanup-preview.js +466 -0
  64. package/dist/ui/conversation-viewer.d.ts +4 -4
  65. package/dist/ui/conversation-viewer.js +10 -6
  66. package/dist/ui/fleet-list.d.ts +3 -3
  67. package/dist/ui/fleet-list.js +3 -3
  68. package/dist/ui/fleet-overlay.d.ts +37 -6
  69. package/dist/ui/fleet-overlay.js +214 -18
  70. package/dist/ui/hub-feed.d.ts +52 -0
  71. package/dist/ui/hub-feed.js +148 -0
  72. package/dist/ui/native-transcript.js +5 -1
  73. package/dist/ui/schedule-menu.d.ts +1 -1
  74. package/dist/ui/schedule-menu.js +1 -1
  75. package/dist/ui/workflow-card.d.ts +4 -4
  76. package/dist/ui/workflow-dialog.d.ts +4 -4
  77. package/dist/ui/workflow-dialog.js +8 -3
  78. package/dist/ui/workflow-menu.d.ts +2 -2
  79. package/dist/usage.d.ts +12 -0
  80. package/dist/usage.js +28 -1
  81. package/dist/workflow/entry.d.ts +3 -3
  82. package/dist/workflow/host.d.ts +7 -4
  83. package/dist/workflow/host.js +162 -48
  84. package/dist/workflow/journal.d.ts +23 -7
  85. package/dist/workflow/journal.js +80 -23
  86. package/dist/workflow/progress.d.ts +1 -1
  87. package/dist/workflow/runtime.d.ts +45 -6
  88. package/dist/workflow/runtime.js +105 -16
  89. package/dist/workflow/task.d.ts +13 -4
  90. package/dist/workflow/task.js +7 -1
  91. package/dist/workflow/tool-description.d.ts +7 -2
  92. package/dist/workflow/tool-description.js +10 -5
  93. package/docs/{FORK.md → DEVELOPMENT.md} +4 -4
  94. package/docs/artifacts.md +93 -0
  95. package/docs/rpc.md +252 -189
  96. package/docs/runtime-performance.md +53 -0
  97. package/docs/workflows.md +48 -18
  98. package/examples/agent-tool-description.md +2 -2
  99. package/examples/workflows/review-panel.js +6 -3
  100. package/package.json +5 -5
  101. package/src/active-agents-prompt.ts +115 -39
  102. package/src/agent-color.ts +10 -2
  103. package/src/agent-file-toggle.ts +2 -2
  104. package/src/agent-manager.ts +3312 -1601
  105. package/src/agent-runner.ts +164 -36
  106. package/src/agent-types.ts +56 -11
  107. package/src/awaited-result.ts +187 -0
  108. package/src/child-session-shutdown.ts +114 -46
  109. package/src/cleanup-plans.ts +112 -0
  110. package/src/cross-extension-rpc.ts +68 -9
  111. package/src/custom-agents.ts +384 -112
  112. package/src/default-agents.ts +1 -1
  113. package/src/enabled-models.ts +1 -1
  114. package/src/env.ts +1 -1
  115. package/src/error-log.ts +10 -1
  116. package/src/force-main-model.ts +29 -0
  117. package/src/goal-bridge.ts +468 -0
  118. package/src/group-join.ts +56 -9
  119. package/src/index.ts +2987 -349
  120. package/src/invocation-config.ts +50 -4
  121. package/src/memory.ts +1 -1
  122. package/src/mention-clone.ts +3 -3
  123. package/src/model-scope.ts +1 -1
  124. package/src/nested-tools.ts +164 -33
  125. package/src/output-file.ts +168 -46
  126. package/src/prompts.ts +1 -1
  127. package/src/recovery.ts +2 -2
  128. package/src/report-cleanup.ts +2044 -0
  129. package/src/report-store.ts +4130 -0
  130. package/src/schedule-store.ts +244 -201
  131. package/src/schedule.ts +144 -80
  132. package/src/settings.ts +61 -16
  133. package/src/skill-loader.ts +1 -1
  134. package/src/standalone-fallback.ts +2 -2
  135. package/src/status-note.ts +1 -1
  136. package/src/structured-output.ts +1 -1
  137. package/src/types.ts +33 -3
  138. package/src/ui/agent-mention.ts +3 -3
  139. package/src/ui/agent-widget.ts +179 -45
  140. package/src/ui/cleanup-preview.ts +518 -0
  141. package/src/ui/conversation-viewer.ts +19 -15
  142. package/src/ui/fleet-list.ts +7 -7
  143. package/src/ui/fleet-overlay.ts +1048 -847
  144. package/src/ui/hub-feed.ts +179 -0
  145. package/src/ui/native-transcript.ts +7 -3
  146. package/src/ui/schedule-menu.ts +4 -4
  147. package/src/ui/workflow-card.ts +4 -4
  148. package/src/ui/workflow-dialog.ts +10 -6
  149. package/src/ui/workflow-menu.ts +4 -4
  150. package/src/usage.ts +53 -3
  151. package/src/workflow/collisions.ts +1 -1
  152. package/src/workflow/entry.ts +3 -3
  153. package/src/workflow/host.ts +174 -54
  154. package/src/workflow/journal.ts +80 -23
  155. package/src/workflow/progress.ts +1 -1
  156. package/src/workflow/runtime.ts +146 -23
  157. package/src/workflow/saved.ts +3 -3
  158. package/src/workflow/task.ts +18 -7
  159. package/src/workflow/tool-description.ts +10 -5
@@ -0,0 +1,179 @@
1
+ /**
2
+ * hub-feed.ts — pure data for the fleet overlay's live panes (omp Agent Hub parity).
3
+ *
4
+ * - `transcriptTail`: the last few events of one agent's child session — prompts,
5
+ * replies, tool calls and failed results — for the right pane under the detail card.
6
+ * - `activityFeed`: the same events across every agent, newest first, for the
7
+ * Activity tab, with All / Errors / Responses / Tools filters.
8
+ * - `treeOrder`: parent → child ordering for the tree view.
9
+ *
10
+ * Everything is derived from `session.messages` on render; no extra state is
11
+ * recorded, so the feed can never disagree with the conversation viewer.
12
+ */
13
+
14
+ import type { AgentRecord } from "../types.ts";
15
+
16
+ export type FeedKind = "prompt" | "response" | "tool" | "error";
17
+ export type ActivityFilter = "all" | "errors" | "responses" | "tools";
18
+ export const ACTIVITY_FILTERS: readonly ActivityFilter[] = ["all", "errors", "responses", "tools"];
19
+
20
+ export interface FeedEvent {
21
+ readonly kind: FeedKind;
22
+ readonly text: string;
23
+ readonly at?: number;
24
+ }
25
+
26
+ export interface ActivityEntry extends FeedEvent {
27
+ readonly agentId: string;
28
+ readonly agent: string;
29
+ }
30
+
31
+ interface MessageLike {
32
+ role?: unknown;
33
+ content?: unknown;
34
+ timestamp?: unknown;
35
+ toolName?: unknown;
36
+ isError?: unknown;
37
+ stopReason?: unknown;
38
+ errorMessage?: unknown;
39
+ }
40
+
41
+ function oneLine(text: string, max = 240): string {
42
+ const flat = text.replace(/\s+/g, " ").trim();
43
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
44
+ }
45
+
46
+ function textOf(content: unknown): string {
47
+ if (typeof content === "string") return content;
48
+ if (!Array.isArray(content)) return "";
49
+ return content
50
+ .map(part => (part && typeof part === "object" && (part as { type?: unknown }).type === "text" ? String((part as { text?: unknown }).text ?? "") : ""))
51
+ .filter(Boolean)
52
+ .join(" ");
53
+ }
54
+
55
+ /** Compact `name(arg)` label: the first string argument says the most (path, pattern, command). */
56
+ function toolLabel(part: { name?: unknown; arguments?: unknown }): string {
57
+ const name = typeof part.name === "string" ? part.name : "tool";
58
+ const args = part.arguments && typeof part.arguments === "object" ? Object.values(part.arguments as Record<string, unknown>) : [];
59
+ const first = args.find(value => typeof value === "string") as string | undefined;
60
+ return first ? `${name}(${oneLine(first, 80)})` : `${name}()`;
61
+ }
62
+
63
+ /** Events of one message, in order. */
64
+ export function eventsOf(message: unknown): FeedEvent[] {
65
+ const m = (message ?? {}) as MessageLike;
66
+ const at = typeof m.timestamp === "number" ? m.timestamp : undefined;
67
+ const events: FeedEvent[] = [];
68
+ if (m.role === "user") {
69
+ const text = oneLine(textOf(m.content));
70
+ if (text) events.push({ kind: "prompt", text, at });
71
+ } else if (m.role === "assistant") {
72
+ if (Array.isArray(m.content)) {
73
+ for (const part of m.content as Array<{ type?: unknown; text?: unknown; name?: unknown; arguments?: unknown }>) {
74
+ if (part?.type === "text" && typeof part.text === "string" && part.text.trim()) {
75
+ events.push({ kind: "response", text: oneLine(part.text), at });
76
+ } else if (part?.type === "toolCall") {
77
+ events.push({ kind: "tool", text: toolLabel(part), at });
78
+ }
79
+ }
80
+ }
81
+ if (m.stopReason === "error" && typeof m.errorMessage === "string") {
82
+ events.push({ kind: "error", text: oneLine(m.errorMessage), at });
83
+ }
84
+ } else if (m.role === "toolResult" && m.isError === true) {
85
+ const name = typeof m.toolName === "string" ? m.toolName : "tool";
86
+ events.push({ kind: "error", text: `${name} failed: ${oneLine(textOf(m.content), 160)}`, at });
87
+ }
88
+ return events;
89
+ }
90
+
91
+ function messagesOf(record: AgentRecord): readonly unknown[] {
92
+ const messages = (record.session as { messages?: unknown } | undefined)?.messages;
93
+ return Array.isArray(messages) ? messages : [];
94
+ }
95
+
96
+ /** The last `max` events of an agent's session, oldest → newest (bottom is live). */
97
+ export function transcriptTail(record: AgentRecord, max: number): FeedEvent[] {
98
+ if (max <= 0) return [];
99
+ const messages = messagesOf(record);
100
+ const out: FeedEvent[] = [];
101
+ // Walk backwards and stop early: a long session never pays for its whole history.
102
+ for (let i = messages.length - 1; i >= 0 && out.length < max; i -= 1) {
103
+ const events = eventsOf(messages[i]);
104
+ for (let j = events.length - 1; j >= 0 && out.length < max; j -= 1) out.push(events[j] as FeedEvent);
105
+ }
106
+ return out.reverse();
107
+ }
108
+
109
+ function matchesFilter(kind: FeedKind, filter: ActivityFilter): boolean {
110
+ if (filter === "all") return true;
111
+ if (filter === "errors") return kind === "error";
112
+ if (filter === "responses") return kind === "response";
113
+ return kind === "tool";
114
+ }
115
+
116
+ /**
117
+ * Combined log across agents, newest first. Each agent contributes at most
118
+ * `perAgent` recent events so one chatty agent cannot crowd out the rest.
119
+ */
120
+ export function activityFeed(
121
+ records: readonly AgentRecord[],
122
+ options: { filter: ActivityFilter; limit: number; perAgent?: number },
123
+ ): ActivityEntry[] {
124
+ const perAgent = options.perAgent ?? 60;
125
+ const entries: Array<ActivityEntry & { order: number }> = [];
126
+ let order = 0;
127
+ for (const record of records) {
128
+ const agent = record.alias ?? record.handle ?? record.type;
129
+ for (const event of transcriptTail(record, perAgent)) {
130
+ if (!matchesFilter(event.kind, options.filter)) continue;
131
+ entries.push({ ...event, agentId: record.id, agent, order: order++ });
132
+ }
133
+ }
134
+ entries.sort((a, b) => (b.at ?? 0) - (a.at ?? 0) || b.order - a.order);
135
+ return entries.slice(0, options.limit).map(({ order: _order, ...entry }) => entry);
136
+ }
137
+
138
+ export interface TreeRow {
139
+ readonly record: AgentRecord;
140
+ readonly depth: number;
141
+ }
142
+
143
+ /**
144
+ * Parent → child order. Roots are the given top-level records in their given
145
+ * order; each child follows its parent, oldest first. Orphans (parent swept)
146
+ * surface as roots so nothing disappears.
147
+ *
148
+ * `hidden` drops a row from the output without dropping what is under it: the
149
+ * subtree is still traversed, one level up, so a view filter (a dismissed row)
150
+ * can never re-insert the row it removed or hide its descendants.
151
+ */
152
+ export function treeOrder(
153
+ roots: readonly AgentRecord[],
154
+ all: readonly AgentRecord[],
155
+ hidden?: (record: AgentRecord) => boolean,
156
+ ): TreeRow[] {
157
+ const children = new Map<string, AgentRecord[]>();
158
+ const ids = new Set(all.map(record => record.id));
159
+ for (const record of all) {
160
+ const parent = record.parentAgentId;
161
+ if (!parent || !ids.has(parent)) continue;
162
+ const list = children.get(parent) ?? [];
163
+ list.push(record);
164
+ children.set(parent, list);
165
+ }
166
+ const out: TreeRow[] = [];
167
+ const seen = new Set<string>();
168
+ const visit = (record: AgentRecord, depth: number) => {
169
+ if (seen.has(record.id)) return;
170
+ seen.add(record.id);
171
+ const hiddenHere = hidden?.(record) ?? false;
172
+ if (!hiddenHere) out.push({ record, depth });
173
+ for (const child of (children.get(record.id) ?? []).sort((a, b) => a.startedAt - b.startedAt)) {
174
+ visit(child, hiddenHere ? depth : depth + 1);
175
+ }
176
+ };
177
+ for (const root of roots) visit(root, 0);
178
+ return out;
179
+ }
@@ -7,8 +7,8 @@ import {
7
7
  createReadToolDefinition, createWriteToolDefinition, ToolExecutionComponent, UserMessageComponent,
8
8
  } from "@earendil-works/pi-coding-agent";
9
9
  import { type Component, type MarkdownTheme, Text, type TUI, type TuiMouseEvent, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
10
- import { extractText } from "../context.js";
11
- import { boundToolResult, getToolProgress, RESULT_MAX_CHARS, type ToolDisplayResult, truncationNote } from "./tool-progress.js";
10
+ import { extractText } from "../context.ts";
11
+ import { boundToolResult, getToolProgress, RESULT_MAX_CHARS, type ToolDisplayResult, truncationNote } from "./tool-progress.ts";
12
12
 
13
13
  type AgentMessage = AgentSession["messages"][number];
14
14
  type Renderers = NonNullable<ConstructorParameters<typeof ToolExecutionComponent>[4]>;
@@ -63,7 +63,10 @@ export class NativeTranscript implements Component {
63
63
  if (event.type === "tool_execution_update") this.updateTool(event.toolCallId, { ...event.partialResult, isError: false }, true);
64
64
  } else if (event.type === "tool_execution_end") {
65
65
  this.ensureTool(event.toolCallId, event.toolName, {});
66
- this.updateTool(event.toolCallId, { ...event.result, isError: event.isError }, false);
66
+ // Same shape pi's own transcript hands the card: renderers read durationMs.
67
+ this.updateTool(event.toolCallId, {
68
+ ...event.result, isError: event.isError, ...(event.durationMs === undefined ? {} : { durationMs: event.durationMs }),
69
+ }, false);
67
70
  } else if (event.type === "compaction_end" && event.result && !event.aborted) {
68
71
  this.hydrate();
69
72
  }
@@ -90,6 +93,7 @@ export class NativeTranscript implements Component {
90
93
  if (existing) return existing;
91
94
  const component = new ToolExecutionComponent(name, id, args, {
92
95
  showImages: this.session.settingsManager?.getShowImages() ?? true,
96
+ outputPad: this.session.settingsManager?.getOutputPad() ?? 1,
93
97
  }, this.renderers(name), this.tui, this.cwd);
94
98
  component.setExpanded(this.expanded);
95
99
  const entry: ToolEntry = {
@@ -9,9 +9,9 @@
9
9
  */
10
10
 
11
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 { selectItem } from "./select-item.js";
12
+ import type { SubagentScheduler } from "../schedule.ts";
13
+ import type { ScheduledSubagent } from "../types.ts";
14
+ import { selectItem } from "./select-item.ts";
15
15
 
16
16
  /** Format an ISO timestamp as relative time ("in 4h", "2d ago", "—"). */
17
17
  function relTime(iso: string | undefined, now = Date.now()): string {
@@ -100,6 +100,6 @@ export async function showSchedulesMenu(
100
100
  const ok = await ctx.ui.confirm(`Cancel "${job.name}"?`, formatDetails(job, scheduler));
101
101
  if (!ok) return;
102
102
 
103
- scheduler.removeJob(job.id);
103
+ await scheduler.removeJob(job.id);
104
104
  ctx.ui.notify(`Cancelled "${job.name}".`, "info");
105
105
  }
@@ -32,8 +32,8 @@
32
32
  */
33
33
 
34
34
  import { stripTerminalSequences, Text, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
35
- import type { WorkflowEntryData } from "../workflow/entry.js";
36
- import type { WorkflowMeta } from "../workflow/meta.js";
35
+ import type { WorkflowEntryData } from "../workflow/entry.ts";
36
+ import type { WorkflowMeta } from "../workflow/meta.ts";
37
37
  import {
38
38
  buildPhaseGroups,
39
39
  collapse,
@@ -44,8 +44,8 @@ import {
44
44
  type WorkflowAgentEntry,
45
45
  type WorkflowEntry,
46
46
  type WorkflowRunStatus,
47
- } from "../workflow/progress.js";
48
- import type { Theme } from "./agent-widget.js";
47
+ } from "../workflow/progress.ts";
48
+ import type { Theme } from "./agent-widget.ts";
49
49
 
50
50
  /**
51
51
  * Header re-render cadence. Claude Code ticks the workflow clock once a second,
@@ -49,7 +49,7 @@ import {
49
49
  visibleWidth,
50
50
  wrapTextWithAnsi,
51
51
  } from "@earendil-works/pi-tui";
52
- import type { WorkflowMeta } from "../workflow/meta.js";
52
+ import type { WorkflowMeta } from "../workflow/meta.ts";
53
53
  import {
54
54
  buildPhaseGroups,
55
55
  displayState,
@@ -60,8 +60,8 @@ import {
60
60
  type WorkflowAgentEntry,
61
61
  type WorkflowDisplayState,
62
62
  type WorkflowEntry,
63
- } from "../workflow/progress.js";
64
- import { SPINNER, type Theme } from "./agent-widget.js";
63
+ } from "../workflow/progress.ts";
64
+ import { flattenRow, SPINNER, type Theme } from "./agent-widget.ts";
65
65
  import {
66
66
  ASCII_GLYPHS,
67
67
  clampLine,
@@ -75,7 +75,7 @@ import {
75
75
  type WorkflowCardLine,
76
76
  type WorkflowCardSegment,
77
77
  type WorkflowCardTask,
78
- } from "./workflow-card.js";
78
+ } from "./workflow-card.ts";
79
79
 
80
80
  /** Fallback width when the caller does not know the terminal's. */
81
81
  const DEFAULT_WIDTH = 80;
@@ -479,7 +479,9 @@ function frameTitle(title: string, width: number, glyphs: WorkflowDialogGlyphs):
479
479
  // own truncation does the width arithmetic, including wide characters; its
480
480
  // ellipsis arrives wrapped in resets, which are stripped for the same reason
481
481
  // `clampLine` strips them — the layout stays plain text until it is themed.
482
- const shown = stripTerminalSequences(truncateToWidth(title, room, glyphs.ellipsis));
482
+ // Flattened first: a title is a workflow/task label (arbitrary text), and a
483
+ // control byte in it would make one frame row occupy two terminal rows.
484
+ const shown = stripTerminalSequences(truncateToWidth(flattenRow(title), room, glyphs.ellipsis));
483
485
  const rule = Math.max(0, width - visibleWidth(shown) - 2);
484
486
  // Clamped as well as computed: at a terminal narrow enough that `room` hits
485
487
  // zero the marker alone is already wider than the cell, and a title that
@@ -622,7 +624,9 @@ function detailHeading(title: string, suffixes: readonly string[], width: number
622
624
 
623
625
  /** A detail body line, indented under its heading. */
624
626
  const detailBody = (text: string, width: number): WorkflowCardLine =>
625
- clampLine([{ text: ` ${text}`, color: "dim" }], width);
627
+ // Flattened, whitespace preserved: the body carries indented report text and
628
+ // an activity body, neither of which may contain a row-breaking character.
629
+ clampLine([{ text: flattenRow(` ${text}`), color: "dim" }], width);
626
630
 
627
631
  /** The row for one agent, as it appears in whichever pane is listing agents. */
628
632
  function agentRow(options: {
@@ -15,9 +15,9 @@
15
15
  */
16
16
 
17
17
  import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
18
- import type { AgentRecord } from "../types.js";
19
- import { pauseWorkflowTask, resumeWorkflowTask, type WorkflowTask } from "../workflow/task.js";
20
- import { WorkflowDialog } from "./workflow-dialog.js";
18
+ import type { AgentRecord } from "../types.ts";
19
+ import { pauseWorkflowTask, resumeWorkflowTask, type WorkflowTask } from "../workflow/task.ts";
20
+ import { WorkflowDialog } from "./workflow-dialog.ts";
21
21
 
22
22
  /** Everything the menu and the inspector need from the extension around them. */
23
23
  export interface WorkflowMenuDeps {
@@ -58,7 +58,7 @@ export async function showWorkflowDialog(
58
58
  // reached the same way: both are rows of the fleet list, and opening one
59
59
  // must not behave unlike opening the other. Inline, the frame would render
60
60
  // into the conversation and stay in the scrollback after it closed.
61
- const { VIEWPORT_HEIGHT_PCT } = await import("./conversation-viewer.js");
61
+ const { VIEWPORT_HEIGHT_PCT } = await import("./conversation-viewer.ts");
62
62
  /**
63
63
  * This dialog's own overlay, so `c` can hide it while the conversation is
64
64
  * up. Overlays stack, so the viewer would render *over* it either way —
package/src/usage.ts CHANGED
@@ -133,7 +133,29 @@ export type SessionStatsLike = {
133
133
  tokens: { input: number; output: number; cacheWrite: number };
134
134
  contextUsage?: { percent: number | null };
135
135
  };
136
- export type SessionLike = { getSessionStats(): SessionStatsLike };
136
+ export type SessionLike = {
137
+ getSessionStats(): SessionStatsLike;
138
+ getContextUsage?(): { percent: number | null } | undefined;
139
+ sessionManager?: { getLeafId(): string | null; getEntryCount?(): number };
140
+ model?: { contextWindow?: number };
141
+ messages?: readonly unknown[];
142
+ isCompacting?: boolean;
143
+ };
144
+
145
+ type ContextDisplayCache = {
146
+ manager: NonNullable<SessionLike["sessionManager"]>;
147
+ leafId: string | null;
148
+ entryCount: number | undefined;
149
+ model: SessionLike["model"];
150
+ contextWindow: number | undefined;
151
+ messages: readonly unknown[] | undefined;
152
+ messageCount: number;
153
+ lastMessage: unknown;
154
+ compacting: boolean | undefined;
155
+ percent: number | null;
156
+ };
157
+
158
+ const contextDisplayCache = new WeakMap<SessionLike, ContextDisplayCache>();
137
159
 
138
160
  /**
139
161
  * Session-scoped token count: input + output + cacheWrite as reported by
@@ -162,6 +184,34 @@ export function getSessionTokens(session: SessionLike | undefined): number {
162
184
  */
163
185
  export function getSessionContextPercent(session: SessionLike | undefined): number | null {
164
186
  if (!session) return null;
165
- try { return session.getSessionStats().contextUsage?.percent ?? null; }
166
- catch { return null; }
187
+ try {
188
+ // These SDK accessors are constant-cost. In particular, routedModel and
189
+ // getContextUsage themselves search/project history and cannot form the key.
190
+ const manager = session.sessionManager;
191
+ const leafId = manager?.getLeafId() ?? null;
192
+ const entryCount = manager?.getEntryCount?.();
193
+ const model = session.model;
194
+ const contextWindow = model?.contextWindow;
195
+ const messages = session.messages;
196
+ const messageCount = messages?.length ?? 0;
197
+ const lastMessage = messages?.[messageCount - 1];
198
+ const compacting = session.isCompacting;
199
+ const cached = manager ? contextDisplayCache.get(session) : undefined;
200
+ if (cached && cached.manager === manager && cached.leafId === leafId
201
+ && cached.entryCount === entryCount && cached.model === model && cached.contextWindow === contextWindow
202
+ && cached.messages === messages && cached.messageCount === messageCount
203
+ && cached.lastMessage === lastMessage && cached.compacting === compacting) return cached.percent;
204
+
205
+ const percent = session.getContextUsage
206
+ ? session.getContextUsage()?.percent ?? null
207
+ : session.getSessionStats().contextUsage?.percent ?? null;
208
+ // Structural session doubles without a revision source must remain live.
209
+ if (manager) contextDisplayCache.set(session, {
210
+ manager, leafId, entryCount, model, contextWindow, messages, messageCount, lastMessage, compacting, percent,
211
+ });
212
+ return percent;
213
+ } catch {
214
+ // A transient read failure must not poison the next frame's cache.
215
+ return null;
216
+ }
167
217
  }
@@ -39,7 +39,7 @@
39
39
  * and the `setActiveTools` — see `resolveWorkflowCollisions` in index.ts.
40
40
  */
41
41
 
42
- import { SUBAGENT_TOOL_NAMES } from "../agent-runner.js";
42
+ import { SUBAGENT_TOOL_NAMES } from "../agent-runner.ts";
43
43
 
44
44
  /**
45
45
  * Tool names that mean "another extension already orchestrates subagents".
@@ -13,9 +13,9 @@
13
13
  * session file stores does not depend on the code that draws it.
14
14
  */
15
15
 
16
- import type { WorkflowMeta } from "./meta.js";
17
- import type { WorkflowEntry, WorkflowRunStatus } from "./progress.js";
18
- import type { WorkflowTask } from "./task.js";
16
+ import type { WorkflowMeta } from "./meta.ts";
17
+ import type { WorkflowEntry, WorkflowRunStatus } from "./progress.ts";
18
+ import type { WorkflowTask } from "./task.ts";
19
19
 
20
20
  /** `customType` of the session entry a flag-launched workflow renders through. */
21
21
  export const WORKFLOW_ENTRY_TYPE = "subagents:workflow";