pi-crew 0.9.68 → 0.10.1

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 (217) hide show
  1. package/CHANGELOG.md +124 -0
  2. package/agents/analyst.md +1 -1
  3. package/agents/cold-verifier.md +3 -1
  4. package/agents/critic.md +1 -1
  5. package/agents/executor.md +1 -1
  6. package/agents/explorer.md +1 -1
  7. package/agents/planner.md +1 -1
  8. package/agents/reviewer.md +1 -1
  9. package/agents/security-reviewer.md +1 -1
  10. package/agents/test-engineer.md +1 -1
  11. package/agents/verifier.md +1 -1
  12. package/agents/writer.md +1 -1
  13. package/dist/index.mjs +65838 -60331
  14. package/docs/README.md +2 -0
  15. package/docs/actions-reference.md +31 -0
  16. package/docs/commands-reference.md +17 -6
  17. package/docs/resource-formats.md +13 -0
  18. package/package.json +4 -2
  19. package/schema.json +15 -1
  20. package/scripts/resource-sampler.mjs +36 -2
  21. package/skills/requirements-to-task-packet/SKILL.md +26 -0
  22. package/skills/widget-rendering/SKILL.md +7 -7
  23. package/src/agents/agent-config.ts +2 -1
  24. package/src/agents/discover-agents.ts +23 -14
  25. package/src/config/config-merge.ts +183 -0
  26. package/src/config/config-validation.ts +681 -0
  27. package/src/config/config.ts +22 -864
  28. package/src/config/defaults.ts +35 -1
  29. package/src/config/drift-detector.ts +1 -1
  30. package/src/config/env-vars.ts +691 -0
  31. package/src/config/role-tools.ts +8 -8
  32. package/src/config/sanitize-project-config.ts +172 -0
  33. package/src/config/types.ts +30 -0
  34. package/src/extension/async-notifier.ts +25 -2
  35. package/src/extension/crew-vibes/config.ts +2 -1
  36. package/src/extension/plan-orchestrate.ts +132 -0
  37. package/src/extension/registration/commands/dashboard.ts +158 -0
  38. package/src/extension/registration/commands/index.ts +35 -0
  39. package/src/extension/registration/commands/manage.ts +303 -0
  40. package/src/extension/registration/commands/run.ts +214 -0
  41. package/src/extension/registration/commands/shared.ts +631 -0
  42. package/src/extension/registration/commands/status.ts +60 -0
  43. package/src/extension/registration/commands.ts +13 -1224
  44. package/src/extension/registration/lifecycle-handlers.ts +126 -15
  45. package/src/extension/registration/subagent-tools.ts +218 -9
  46. package/src/extension/rpc-hmac.ts +5 -3
  47. package/src/extension/team-tool/api/heartbeat.ts +47 -10
  48. package/src/extension/team-tool/api/plan-approval.ts +9 -0
  49. package/src/extension/team-tool/api/task-claims.ts +109 -40
  50. package/src/extension/team-tool/cancel.ts +84 -50
  51. package/src/extension/team-tool/dispatch/index.ts +1 -0
  52. package/src/extension/team-tool/dispatch/run.ts +4 -1
  53. package/src/extension/team-tool/doctor.ts +103 -1
  54. package/src/extension/team-tool/orchestrate.ts +66 -1
  55. package/src/extension/team-tool/plans.ts +192 -0
  56. package/src/extension/team-tool/respond.ts +197 -65
  57. package/src/extension/team-tool/run-deadline.ts +16 -1
  58. package/src/extension/team-tool/run-intent.ts +63 -0
  59. package/src/extension/team-tool/run.ts +48 -18
  60. package/src/extension/team-tool/status.ts +84 -26
  61. package/src/extension/team-tool.ts +11 -2
  62. package/src/hooks/registry.ts +1 -6
  63. package/src/i18n.ts +9 -0
  64. package/src/prompt/prompt-runtime.ts +521 -2
  65. package/src/prompt/worker-events-channel.ts +173 -0
  66. package/src/runtime/README.md +8 -8
  67. package/src/runtime/async-runner.ts +7 -3
  68. package/src/runtime/background-runner.ts +42 -14
  69. package/src/runtime/broker/broker-issuer.ts +9 -2
  70. package/src/runtime/broker/crew-broker-tokens.ts +43 -6
  71. package/src/runtime/broker/crew-broker.ts +838 -10
  72. package/src/runtime/broker/wait-status-cache.ts +157 -0
  73. package/src/runtime/budget-enforcement.ts +281 -0
  74. package/src/runtime/child-pi/child-pi-spawn.ts +60 -14
  75. package/src/runtime/child-pi/child-pi-timers.ts +324 -0
  76. package/src/runtime/child-pi/child-pi.ts +97 -201
  77. package/src/runtime/child-pi/mock-fixtures.ts +16 -2
  78. package/src/runtime/crew-agent-records.ts +259 -14
  79. package/src/runtime/delegate-spawn.ts +148 -0
  80. package/src/runtime/deterministic-ast.ts +2 -1
  81. package/src/runtime/dispatch-batch.ts +945 -0
  82. package/src/runtime/finalize-run.ts +557 -0
  83. package/src/runtime/goal-workflow/adaptive-plan.ts +87 -13
  84. package/src/runtime/goal-workflow/dynamic-workflow-runner.ts +3 -2
  85. package/src/runtime/goal-workflow/goal-state-store.ts +1 -1
  86. package/src/runtime/group-join.ts +11 -125
  87. package/src/runtime/live-session/live-session-runtime.ts +26 -1
  88. package/src/runtime/merge-gate.ts +7 -1
  89. package/src/runtime/merge-loop.ts +130 -0
  90. package/src/runtime/model/model-budget-summary.ts +53 -0
  91. package/src/runtime/model/model-fallback.ts +32 -2
  92. package/src/runtime/model/pi-args.ts +10 -0
  93. package/src/runtime/model/provider-extensions.ts +10 -0
  94. package/src/runtime/orphan-worker-registry.ts +1 -1
  95. package/src/runtime/output/output-validator.ts +45 -0
  96. package/src/runtime/parent-guard.ts +3 -1
  97. package/src/runtime/peer-dep.ts +2 -1
  98. package/src/runtime/per-write-validator.ts +0 -5
  99. package/src/runtime/pi-spawn.ts +61 -15
  100. package/src/runtime/plan-approval.ts +125 -0
  101. package/src/runtime/plan-replan.ts +151 -0
  102. package/src/runtime/recovery/checkpoint.ts +0 -18
  103. package/src/runtime/recovery/crash-recovery.ts +95 -46
  104. package/src/runtime/scheduler-context.ts +98 -0
  105. package/src/runtime/scheduling/coalesce-tasks.ts +5 -0
  106. package/src/runtime/scheduling/global-worker-cap.ts +2 -1
  107. package/src/runtime/scheduling/nested-slots.ts +70 -0
  108. package/src/runtime/scheduling/run-coalesced-task-group.ts +64 -13
  109. package/src/runtime/scheduling/task-graph-scheduler.ts +0 -10
  110. package/src/runtime/settings-store.ts +219 -0
  111. package/src/runtime/spawn-policy.ts +217 -0
  112. package/src/runtime/stale-reconciler.ts +87 -6
  113. package/src/runtime/subagent-manager.ts +25 -1
  114. package/src/runtime/task-output-context.ts +230 -9
  115. package/src/runtime/task-packet.ts +23 -1
  116. package/src/runtime/task-runner/child-executor.ts +106 -7
  117. package/src/runtime/task-runner/post-execution.ts +125 -1
  118. package/src/runtime/task-runner/pre-execution.ts +39 -1
  119. package/src/runtime/task-runner/prompt-builder.ts +51 -1
  120. package/src/runtime/task-runner/retrieval-orchestrator.ts +72 -18
  121. package/src/runtime/task-runner/spec-evidence.ts +403 -0
  122. package/src/runtime/task-runner/state-helpers.ts +26 -24
  123. package/src/runtime/task-runner.ts +11 -0
  124. package/src/runtime/team-runner.ts +129 -1671
  125. package/src/runtime/verification/spec-sandbox.ts +255 -0
  126. package/src/runtime/verification/verification-gates.ts +3 -2
  127. package/src/runtime/verification/verification-worktree.ts +2 -1
  128. package/src/runtime/workflow-phase-advance.ts +100 -0
  129. package/src/runtime/workspace-tree.ts +9 -0
  130. package/src/schema/config-schema.ts +65 -25
  131. package/src/schema/sensitive-config-paths.ts +64 -0
  132. package/src/schema/team-tool-schema.ts +13 -3
  133. package/src/state/README.md +4 -10
  134. package/src/state/atomic-write.ts +20 -3
  135. package/src/state/contracts.ts +38 -0
  136. package/src/state/coordination/mailbox.ts +12 -2
  137. package/src/state/event-log/cursor.ts +223 -0
  138. package/src/state/event-log/event-log-rotation.ts +12 -4
  139. package/src/state/event-log/event-log.ts +152 -369
  140. package/src/state/event-log/sequence-cache.ts +373 -0
  141. package/src/state/event-log/worker-atomic-writer.ts +2 -1
  142. package/src/state/stores/active-run-registry.ts +3 -2
  143. package/src/state/stores/manifest-io.ts +237 -0
  144. package/src/state/stores/ownership-map.ts +162 -0
  145. package/src/state/stores/plan-store.ts +241 -0
  146. package/src/state/stores/run-cache.ts +0 -90
  147. package/src/state/stores/spec-store.ts +189 -0
  148. package/src/state/stores/state-store.ts +66 -229
  149. package/src/state/types.ts +197 -0
  150. package/src/ui/dashboard-panes/plan-pane.ts +136 -0
  151. package/src/ui/dashboard-panes/progress-pane.ts +6 -0
  152. package/src/ui/dashboard-panes/transcript-pane.ts +31 -0
  153. package/src/ui/heartbeat-aggregator.ts +9 -1
  154. package/src/ui/keybinding-map.ts +54 -13
  155. package/src/ui/powerbar-publisher.ts +52 -1
  156. package/src/ui/run-dashboard.ts +31 -5
  157. package/src/ui/run-snapshot-cache.ts +57 -30
  158. package/src/ui/snapshot-types.ts +6 -1
  159. package/src/ui/widget/widget-renderer.ts +9 -1
  160. package/src/utils/file-coalescer.ts +0 -4
  161. package/src/utils/fs-errno.ts +66 -0
  162. package/src/utils/fs-watch.ts +1 -1
  163. package/src/utils/internal-error.ts +3 -1
  164. package/src/utils/paths.ts +11 -3
  165. package/src/utils/task-name-generator.ts +1 -8
  166. package/src/workflows/discover-workflows.ts +19 -2
  167. package/src/workflows/validate-workflow.ts +7 -1
  168. package/src/workflows/workflow-config.ts +10 -0
  169. package/src/workflows/workflow-serializer.ts +3 -0
  170. package/src/worktree/worktree-manager.ts +22 -0
  171. package/src/agents/agent-search.ts +0 -98
  172. package/src/benchmark/benchmark-runner.ts +0 -313
  173. package/src/benchmark/feedback-loop.ts +0 -73
  174. package/src/config/resilient-parser.ts +0 -117
  175. package/src/extension/crew-vibes/cat-frames.ts +0 -18
  176. package/src/extension/result-watcher.ts +0 -139
  177. package/src/observability/exporters/prometheus-exporter.ts +0 -54
  178. package/src/observability/metric-retention.ts +0 -64
  179. package/src/runtime/compaction/compaction-summary.ts +0 -278
  180. package/src/runtime/errors/crew-errors.ts +0 -162
  181. package/src/runtime/live-session/intercom-bridge.ts +0 -187
  182. package/src/runtime/loop-gates.ts +0 -128
  183. package/src/runtime/metric-parser.ts +0 -36
  184. package/src/runtime/output/stream-preview.ts +0 -184
  185. package/src/runtime/output/tool-progress.ts +0 -278
  186. package/src/runtime/phase-tracker.ts +0 -385
  187. package/src/runtime/pipeline-runner.ts +0 -523
  188. package/src/runtime/process/process-lifecycle.ts +0 -491
  189. package/src/runtime/recovery/retry-runner.ts +0 -330
  190. package/src/runtime/run-drift.ts +0 -219
  191. package/src/runtime/task-quality.ts +0 -199
  192. package/src/runtime/task-runner/run-projection.ts +0 -128
  193. package/src/runtime/verification/post-checks.ts +0 -142
  194. package/src/state/coordination/schedule.ts +0 -166
  195. package/src/state/event-log/jsonl-writer.ts +0 -115
  196. package/src/state/hook-instinct-bridge.ts +0 -94
  197. package/src/state/hook-integrations.ts +0 -51
  198. package/src/state/session-state-map.ts +0 -51
  199. package/src/state/stores/blob-store.ts +0 -308
  200. package/src/state/stores/instinct-store.ts +0 -275
  201. package/src/state/stores/observation-store.ts +0 -176
  202. package/src/state/tiered-eval.ts +0 -480
  203. package/src/state/types-eval.ts +0 -58
  204. package/src/tools/safe-bash-extension.ts +0 -54
  205. package/src/tools/safe-bash.ts +0 -505
  206. package/src/ui/agent-management-overlay.ts +0 -160
  207. package/src/ui/crew-footer.ts +0 -102
  208. package/src/ui/crew-select-list.ts +0 -114
  209. package/src/ui/dashboard-panes/capability-pane.ts +0 -77
  210. package/src/ui/transcript-entries.ts +0 -256
  211. package/src/utils/conflict-detect.ts +0 -721
  212. package/src/utils/fingerprint.ts +0 -180
  213. package/src/utils/gh-protocol.ts +0 -556
  214. package/src/utils/project-detector.ts +0 -160
  215. package/src/utils/sse-parser.ts +0 -131
  216. package/src/workflows/cost-estimator.ts +0 -34
  217. package/src/workflows/intermediate-store.ts +0 -166
@@ -1,102 +0,0 @@
1
- import type { UsageState } from "../state/types.ts";
2
- import { pad, truncate } from "../utils/visual.ts";
3
- import type { RunStatus } from "./status-colors.ts";
4
- import type { CrewTheme } from "./theme-adapter.ts";
5
-
6
- export interface CrewFooterData {
7
- pwd: string;
8
- branch?: string;
9
- runId?: string;
10
- status?: RunStatus;
11
- usage?: UsageState;
12
- contextWindow?: number;
13
- contextPercent?: number;
14
- badges?: string[];
15
- }
16
-
17
- function formatCount(value: number | undefined): string {
18
- if (value === undefined || !Number.isFinite(value)) return "?";
19
- if (Math.abs(value) >= 1000) return `${(value / 1000).toFixed(Math.abs(value) >= 10_000 ? 0 : 1)}k`;
20
- return `${value}`;
21
- }
22
-
23
- function formatCost(value: number | undefined): string {
24
- return value === undefined || !Number.isFinite(value) ? "$0.0000" : `$${value.toFixed(4)}`;
25
- }
26
-
27
- function displayPwd(pwd: string): string {
28
- const home = process.env.HOME || process.env.USERPROFILE;
29
- if (home && pwd.startsWith(home)) return `~${pwd.slice(home.length) || "/"}`;
30
- return pwd || ".";
31
- }
32
-
33
- function contextText(data: CrewFooterData): string {
34
- const windowText = data.contextWindow && Number.isFinite(data.contextWindow) ? formatCount(data.contextWindow) : "window";
35
- const percent = data.contextPercent;
36
- if (percent === undefined || !Number.isFinite(percent)) return `?/${windowText}`;
37
- return `${percent.toFixed(1)}%/${windowText}`;
38
- }
39
-
40
- export class CrewFooter {
41
- private data: CrewFooterData;
42
- private readonly theme: CrewTheme;
43
- private cacheKey = "";
44
- private cacheWidth = 0;
45
- private cacheLines: string[] = [];
46
-
47
- constructor(data: CrewFooterData, theme: CrewTheme) {
48
- this.data = data;
49
- this.theme = theme;
50
- }
51
-
52
- setData(data: CrewFooterData): void {
53
- this.data = data;
54
- this.invalidate();
55
- }
56
-
57
- invalidate(): void {
58
- this.cacheKey = "";
59
- this.cacheLines = [];
60
- }
61
-
62
- render(width: number): string[] {
63
- const key = JSON.stringify(this.data);
64
- if (this.cacheKey === key && this.cacheWidth === width && this.cacheLines.length) return this.cacheLines;
65
- const lineWidth = Math.max(1, width);
66
- const firstParts = [
67
- displayPwd(this.data.pwd),
68
- this.data.branch ? `(${this.data.branch})` : undefined,
69
- this.data.runId,
70
- this.data.status,
71
- ].filter((part): part is string => Boolean(part));
72
- const usage = this.data.usage;
73
- const context = contextText(this.data);
74
- const contextPercent = this.data.contextPercent;
75
- const contextColor =
76
- contextPercent !== undefined && Number.isFinite(contextPercent)
77
- ? contextPercent > 90
78
- ? "error"
79
- : contextPercent > 70
80
- ? "warning"
81
- : undefined
82
- : undefined;
83
- const contextRendered = contextColor ? this.theme.fg(contextColor, context) : context;
84
- const usageLine = [
85
- `↑${formatCount(usage?.input)}`,
86
- `↓${formatCount(usage?.output)}`,
87
- `R ${formatCount(usage?.cacheRead)} cache`,
88
- `W ${formatCount(usage?.cacheWrite)} cache`,
89
- formatCost(usage?.cost),
90
- contextRendered,
91
- ].join(" • ");
92
- const badges = this.data.badges?.length ? this.data.badges.map((badge) => `[${badge}]`).join(" ") : "";
93
- this.cacheLines = [
94
- this.theme.fg("dim", pad(truncate(firstParts.join(" • "), lineWidth), lineWidth)),
95
- this.theme.fg("dim", pad(truncate(usageLine, lineWidth), lineWidth)),
96
- this.theme.fg("dim", pad(truncate(badges, lineWidth), lineWidth)),
97
- ];
98
- this.cacheKey = key;
99
- this.cacheWidth = width;
100
- return this.cacheLines;
101
- }
102
- }
@@ -1,114 +0,0 @@
1
- import { pad, truncate } from "../utils/visual.ts";
2
- import { keyOf } from "./key-utils.ts";
3
- import type { CrewTheme } from "./theme-adapter.ts";
4
-
5
- export interface CrewSelectItem<T = string> {
6
- value: T;
7
- label: string;
8
- description?: string;
9
- }
10
-
11
- export interface CrewSelectListOptions<T = string> {
12
- onSelect: (item: CrewSelectItem<T>) => void;
13
- onCancel: () => void;
14
- onPreview?: (item: CrewSelectItem<T>) => void;
15
- maxHeight?: number;
16
- }
17
-
18
- export class CrewSelectList<T = string> {
19
- private readonly items: CrewSelectItem<T>[];
20
- private readonly theme: CrewTheme;
21
- private readonly options: CrewSelectListOptions<T>;
22
- private selectedIndex = 0;
23
- private scrollOffset = 0;
24
-
25
- constructor(items: CrewSelectItem<T>[], theme: CrewTheme, options: CrewSelectListOptions<T>) {
26
- this.items = [...items];
27
- this.theme = theme;
28
- this.options = options;
29
- this.selectedIndex = this.items.length ? 0 : -1;
30
- }
31
-
32
- invalidate(): void {
33
- /* no-op */
34
- }
35
-
36
- getSelected(): CrewSelectItem<T> | undefined {
37
- return this.selectedIndex >= 0 ? this.items[this.selectedIndex] : undefined;
38
- }
39
-
40
- setSelectedIndex(index: number): void {
41
- if (!this.items.length) {
42
- this.selectedIndex = -1;
43
- this.scrollOffset = 0;
44
- return;
45
- }
46
- const next = Math.min(this.items.length - 1, Math.max(0, index));
47
- const changed = next !== this.selectedIndex;
48
- this.selectedIndex = next;
49
- this.ensureVisible();
50
- if (changed) {
51
- const selected = this.getSelected();
52
- if (selected) this.options.onPreview?.(selected);
53
- }
54
- }
55
-
56
- handleInput(data: string): void {
57
- if (data === "q" || data === "\u001b") {
58
- this.options.onCancel();
59
- return;
60
- }
61
- if (data === "j" || keyOf(data) === "down") {
62
- this.setSelectedIndex(this.selectedIndex + 1);
63
- return;
64
- }
65
- if (data === "k" || keyOf(data) === "up") {
66
- this.setSelectedIndex(this.selectedIndex - 1);
67
- return;
68
- }
69
- if (data === "\r" || data === "\n") {
70
- const selected = this.getSelected();
71
- if (selected) this.options.onSelect(selected);
72
- }
73
- }
74
-
75
- render(width: number): string[] {
76
- if (!this.items.length) return [this.theme.fg("muted", "(no items)")];
77
- const maxHeight = Math.max(1, Math.floor(this.options.maxHeight ?? this.items.length));
78
- this.ensureVisible();
79
- const hasTop = this.scrollOffset > 0;
80
- const availableWithoutBottom = Math.max(1, maxHeight - (hasTop ? 1 : 0));
81
- const hasBottom = this.scrollOffset + availableWithoutBottom < this.items.length;
82
- const slots = this.visibleItemSlots(maxHeight, hasTop, hasBottom);
83
- const visibleItems = this.items.slice(this.scrollOffset, this.scrollOffset + slots);
84
- const lines: string[] = [];
85
- if (hasTop) lines.push(this.theme.fg("muted", `↑ ${this.scrollOffset} more`));
86
- for (const [offset, item] of visibleItems.entries()) {
87
- const index = this.scrollOffset + offset;
88
- const prefix = index === this.selectedIndex ? " → " : " ";
89
- const suffix = item.description ? this.theme.fg("dim", ` — ${item.description}`) : "";
90
- const raw = `${prefix}${item.label}${suffix}`;
91
- const line = index === this.selectedIndex ? (this.theme.inverse?.(raw) ?? raw) : raw;
92
- lines.push(pad(truncate(line, width), Math.max(1, width)));
93
- }
94
- if (hasBottom) lines.push(this.theme.fg("muted", `↓ ${this.items.length - (this.scrollOffset + slots)} more`));
95
- return lines.slice(0, maxHeight);
96
- }
97
-
98
- private visibleItemSlots(maxHeight: number, hasTop: boolean, hasBottom: boolean): number {
99
- return Math.max(1, maxHeight - (hasTop ? 1 : 0) - (hasBottom ? 1 : 0));
100
- }
101
-
102
- private ensureVisible(): void {
103
- if (this.selectedIndex < 0) return;
104
- const maxHeight = Math.max(1, Math.floor(this.options.maxHeight ?? this.items.length));
105
- const reservedTop = this.scrollOffset > 0 ? 1 : 0;
106
- const visibleSlots = Math.max(1, maxHeight - reservedTop - 1);
107
- if (this.selectedIndex < this.scrollOffset) {
108
- this.scrollOffset = this.selectedIndex;
109
- } else if (this.selectedIndex >= this.scrollOffset + visibleSlots) {
110
- this.scrollOffset = Math.max(0, this.selectedIndex - visibleSlots + 1);
111
- }
112
- this.scrollOffset = Math.min(this.scrollOffset, Math.max(0, this.items.length - 1));
113
- }
114
- }
@@ -1,77 +0,0 @@
1
- import type { PiTeamsConfig } from "../../config/config.ts";
2
- import type { CapabilityItem } from "../../runtime/capability-inventory.ts";
3
- import { buildCapabilityInventory } from "../../runtime/capability-inventory.ts";
4
-
5
- export interface CapabilityPaneOptions {
6
- config?: PiTeamsConfig;
7
- filter?: string;
8
- }
9
-
10
- function kindIcon(kind: string): string {
11
- switch (kind) {
12
- case "team":
13
- return "👥";
14
- case "workflow":
15
- return "📋";
16
- case "agent":
17
- return "🤖";
18
- case "skill":
19
- return "🔧";
20
- case "tool":
21
- return "🛠";
22
- case "runtime":
23
- return "⚙";
24
- default:
25
- return "•";
26
- }
27
- }
28
-
29
- function stateLabel(state: string): string {
30
- switch (state) {
31
- case "active":
32
- return "";
33
- case "disabled":
34
- return " [DISABLED]";
35
- case "shadowed":
36
- return " [SHADOWED]";
37
- case "missing":
38
- return " [MISSING]";
39
- default:
40
- return "";
41
- }
42
- }
43
-
44
- export function renderCapabilityPane(cwd: string, opts: CapabilityPaneOptions = {}): string[] {
45
- const inventory = buildCapabilityInventory(cwd, opts.config);
46
- const filtered = opts.filter
47
- ? inventory.filter(
48
- (item) =>
49
- item.kind.includes(opts.filter!.toLowerCase()) ||
50
- item.name.toLowerCase().includes(opts.filter!.toLowerCase()) ||
51
- item.id.toLowerCase().includes(opts.filter!.toLowerCase()),
52
- )
53
- : inventory;
54
-
55
- if (filtered.length === 0) return ["Capability pane: no items found"];
56
-
57
- const byKind = new Map<string, CapabilityItem[]>();
58
- for (const item of filtered) {
59
- const group = byKind.get(item.kind) ?? [];
60
- group.push(item);
61
- byKind.set(item.kind, group);
62
- }
63
-
64
- const lines = [`Capability pane: ${filtered.length} item(s) (filter: ${opts.filter ?? "none"})`];
65
- for (const [kind, items] of byKind) {
66
- lines.push(` ${kindIcon(kind)} ${kind} (${items.length}):`);
67
- for (const item of items.slice(0, 10)) {
68
- const icon = item.state === "active" ? "✓" : "✗";
69
- lines.push(` ${icon} ${item.name}${stateLabel(item.state)} [${item.source}]`);
70
- }
71
- if (items.length > 10) lines.push(` ... and ${items.length - 10} more`);
72
- }
73
-
74
- const disabled = filtered.filter((i) => i.state === "disabled").length;
75
- if (disabled > 0) lines.push(` Disabled: ${disabled}`);
76
- return lines;
77
- }
@@ -1,256 +0,0 @@
1
- import { truncate } from "../utils/visual.ts";
2
-
3
- export interface TranscriptEntry {
4
- id: number;
5
- type: "message" | "tool_call" | "tool_result" | "system";
6
- role?: string;
7
- toolName?: string;
8
- summary: string;
9
- content: string;
10
- expanded: boolean;
11
- timestamp?: number;
12
- }
13
-
14
- /** Extract plain text from Pi-style content (string or array of content parts). */
15
- function textFromContent(content: unknown): string {
16
- if (typeof content === "string") return content;
17
- if (!Array.isArray(content)) return "";
18
- return content
19
- .map((part: unknown) => {
20
- if (!part || typeof part !== "object" || Array.isArray(part)) return "";
21
- const obj = part as Record<string, unknown>;
22
- if (typeof obj.text === "string") return obj.text;
23
- if (typeof obj.content === "string") return obj.content;
24
- if (typeof obj.name === "string") return `[tool:${obj.name}]`;
25
- return "";
26
- })
27
- .filter(Boolean)
28
- .join("\n");
29
- }
30
-
31
- /** Safely cast unknown to a record for property access. */
32
- function asRecord(value: unknown): Record<string, unknown> | undefined {
33
- return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
34
- }
35
-
36
- /** Detect if an event type is a tool invocation (call/use/start). */
37
- function isToolCallType(type: string): boolean {
38
- return type === "tool_call" || type === "tool_use" || type === "toolCall" || type === "tool_execution_start";
39
- }
40
-
41
- /** Detect if an event type is a tool response (result/end). */
42
- function isToolResultType(type: string): boolean {
43
- return type === "tool_result" || type === "toolCallEnd" || type === "tool_result_end";
44
- }
45
-
46
- /** Extract tool name from various event shapes. */
47
- function extractToolName(obj: Record<string, unknown>): string | undefined {
48
- const name =
49
- typeof obj.toolName === "string"
50
- ? obj.toolName
51
- : typeof obj.name === "string"
52
- ? obj.name
53
- : typeof obj.tool === "string"
54
- ? obj.tool
55
- : undefined;
56
- return name;
57
- }
58
-
59
- /** Create a single-line summary from text, truncating if needed. */
60
- function summarize(text: string, maxLength: number): string {
61
- const oneLine = text.replace(/\r?\n/g, " ").trim();
62
- if (oneLine.length <= maxLength) return oneLine;
63
- return oneLine.slice(0, maxLength - 1) + "…";
64
- }
65
-
66
- const SUMMARY_MAX = 120;
67
-
68
- /** Parse raw JSONL lines into TranscriptEntry[].
69
- *
70
- * Grouping rules:
71
- * - tool_call events are grouped with their subsequent tool_result into one entry.
72
- * - message events (message_end, etc.) become their own entry.
73
- * - Everything else becomes a system entry.
74
- */
75
- export function parseTranscriptEntries(lines: string[]): TranscriptEntry[] {
76
- const entries: TranscriptEntry[] = [];
77
- let id = 0;
78
-
79
- // Pre-parse valid JSON lines
80
- const parsed: Array<{ raw: string; obj: Record<string, unknown> }> = [];
81
- for (const line of lines) {
82
- const trimmed = line.trim();
83
- if (!trimmed) continue;
84
- try {
85
- const json: unknown = JSON.parse(trimmed);
86
- const obj = asRecord(json);
87
- if (obj) parsed.push({ raw: trimmed, obj });
88
- } catch {
89
- // Non-JSON line → treat as a system entry
90
- entries.push({
91
- id: id++,
92
- type: "system",
93
- summary: summarize(trimmed, SUMMARY_MAX),
94
- content: trimmed,
95
- expanded: false,
96
- });
97
- }
98
- }
99
-
100
- // FIND-18: single linear pass to match each tool_call with the next
101
- // tool-flavored event after it. Replaces the previous O(n²) lookahead that
102
- // re-scanned the suffix of the array for every tool_call. The pending slot
103
- // holds the most recent tool_call awaiting its result. A new tool_call
104
- // arriving before any result flushes the previous one as no-result (same
105
- // semantic as the old lookahead hitting the next tool_call). Non-tool
106
- // events are emitted in order and do not interrupt the pending slot,
107
- // matching the old lookahead's behaviour of skipping over messages.
108
- let pending: { obj: Record<string, unknown>; toolName: string; inputText: string; timestamp?: number } | null = null;
109
-
110
- const flushPending = (isError: boolean, resultText: string, resultTimestamp: number | undefined): void => {
111
- if (!pending) return;
112
- const callSummary = summarize(
113
- `🔧 ${pending.toolName}${pending.inputText ? `: ${summarize(pending.inputText, 60)}` : ""}`,
114
- SUMMARY_MAX,
115
- );
116
- const callContent = [
117
- `[Tool Call: ${pending.toolName}]`,
118
- pending.inputText || "(no input)",
119
- `[Result${isError ? " ✗" : " ✓"}]`,
120
- resultText || "(no output)",
121
- ].join("\n");
122
- entries.push({
123
- id: id++,
124
- type: "tool_call",
125
- toolName: pending.toolName,
126
- summary: callSummary,
127
- content: callContent,
128
- expanded: false,
129
- timestamp: resultTimestamp ?? pending.timestamp,
130
- });
131
- pending = null;
132
- };
133
-
134
- for (let i = 0; i < parsed.length; i++) {
135
- const { obj } = parsed[i]!;
136
- const type = typeof obj.type === "string" ? obj.type : "";
137
- const timestamp = typeof obj.timestamp === "number" ? obj.timestamp : undefined;
138
-
139
- if (isToolCallType(type)) {
140
- // A new tool_call interrupts any pending one (same as the old
141
- // lookahead breaking on the next tool_call). Flush as no-result.
142
- if (pending) flushPending(false, "", undefined);
143
- const inputText = typeof obj.input === "string" ? obj.input : obj.input !== undefined ? JSON.stringify(obj.input) : "";
144
- pending = {
145
- obj,
146
- toolName: extractToolName(obj) ?? "unknown",
147
- inputText,
148
- timestamp,
149
- };
150
- continue;
151
- }
152
-
153
- if (isToolResultType(type) || /tool/i.test(type)) {
154
- const rt =
155
- typeof obj.text === "string"
156
- ? obj.text
157
- : typeof obj.result === "string"
158
- ? obj.result
159
- : obj.result !== undefined
160
- ? JSON.stringify(obj.result)
161
- : "";
162
- const isError = obj.isError === true;
163
- const resultTimestamp = typeof obj.timestamp === "number" ? obj.timestamp : undefined;
164
- if (pending) {
165
- flushPending(isError, rt, resultTimestamp);
166
- } else {
167
- // Standalone tool result (no preceding tool_call consumed it)
168
- const toolName = extractToolName(obj) ?? "unknown";
169
- const summary = summarize(`${isError ? "✗" : "✓"} ${toolName}${rt ? `: ${summarize(rt, 60)}` : ""}`, SUMMARY_MAX);
170
- const content = [`[Tool Result: ${toolName}${isError ? " (error)" : ""}]`, rt || "(no output)"].join("\n");
171
- entries.push({
172
- id: id++,
173
- type: "tool_result",
174
- toolName,
175
- summary,
176
- content,
177
- expanded: false,
178
- timestamp,
179
- });
180
- }
181
- continue;
182
- }
183
-
184
- // Message events (message_end, message_start, etc.)
185
- const message = asRecord(obj.message);
186
- if (message || type.startsWith("message")) {
187
- const msg = message ?? obj;
188
- const role = typeof msg.role === "string" ? msg.role : "unknown";
189
- const text = textFromContent(msg.content);
190
-
191
- const label = role === "assistant" ? "🤖" : role === "user" ? "👤" : "💬";
192
- const summary = summarize(`${label} ${role}${text ? `: ${summarize(text, 80)}` : ""}`, SUMMARY_MAX);
193
- const content = `[${role.charAt(0).toUpperCase()}${role.slice(1)}]:\n${text || "(empty)"}`;
194
-
195
- entries.push({
196
- id: id++,
197
- type: "message",
198
- role,
199
- summary,
200
- content,
201
- expanded: false,
202
- timestamp,
203
- });
204
- continue;
205
- }
206
-
207
- // Everything else → system entry
208
- const text = textFromContent(obj.content) || (typeof obj.text === "string" ? obj.text : "");
209
- const displayText = text || type || JSON.stringify(obj);
210
- entries.push({
211
- id: id++,
212
- type: "system",
213
- summary: summarize(`⚙ ${type ? `[${type}]` : ""} ${summarize(displayText, 80)}`, SUMMARY_MAX),
214
- content: displayText,
215
- expanded: false,
216
- timestamp,
217
- });
218
- }
219
-
220
- // End of input: any pending tool_call never received a result.
221
- if (pending) flushPending(false, "", undefined);
222
-
223
- return entries;
224
- }
225
-
226
- /** Toggle expand/collapse for an entry by index. Returns a new array. */
227
- export function toggleEntry(entries: TranscriptEntry[], index: number): TranscriptEntry[] {
228
- return entries.map((entry, i) => (i === index ? { ...entry, expanded: !entry.expanded } : entry));
229
- }
230
-
231
- /** Render entries into display lines, respecting expand/collapse.
232
- * Collapsed entries produce 1 line (summary). Expanded entries produce multi-line content.
233
- * Every line is truncated to maxWidth.
234
- */
235
- export function renderEntries(entries: TranscriptEntry[], maxWidth: number): string[] {
236
- const effectiveWidth = Math.max(1, maxWidth);
237
- const lines: string[] = [];
238
-
239
- for (const entry of entries) {
240
- if (entry.expanded) {
241
- const contentLines = entry.content.split(/\r?\n/);
242
- if (contentLines.length === 0 || (contentLines.length === 1 && contentLines[0] === "")) {
243
- lines.push(truncate(`▸ ${entry.summary}`, effectiveWidth));
244
- } else {
245
- lines.push(truncate(`▾ ${entry.summary}`, effectiveWidth));
246
- for (const line of contentLines) {
247
- lines.push(truncate(` ${line}`, effectiveWidth));
248
- }
249
- }
250
- } else {
251
- lines.push(truncate(`▸ ${entry.summary}`, effectiveWidth));
252
- }
253
- }
254
-
255
- return lines;
256
- }