@tt-a1i/openpi 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 (114) hide show
  1. package/README.md +643 -0
  2. package/SETUP.md +74 -0
  3. package/THIRD_PARTY_NOTICES.md +16 -0
  4. package/assets/openpi-package.png +0 -0
  5. package/assets/readme-hero-mobile.svg +72 -0
  6. package/assets/readme-hero.svg +118 -0
  7. package/assets/readme-runtime-mobile.svg +91 -0
  8. package/assets/readme-runtime.svg +111 -0
  9. package/extensions/ask-user/handoff.ts +205 -0
  10. package/extensions/ask-user/index.ts +1110 -0
  11. package/extensions/ask-user/limits.ts +89 -0
  12. package/extensions/ask-user/prompt.ts +76 -0
  13. package/extensions/background-terminals/index.ts +653 -0
  14. package/extensions/background-terminals/src/domain.ts +99 -0
  15. package/extensions/background-terminals/src/manager.ts +989 -0
  16. package/extensions/background-terminals/src/output.ts +84 -0
  17. package/extensions/background-terminals/src/prompt.ts +195 -0
  18. package/extensions/background-terminals/src/result-delivery.ts +43 -0
  19. package/extensions/background-terminals/src/runtime.ts +36 -0
  20. package/extensions/background-terminals/src/ui/output-view.ts +55 -0
  21. package/extensions/background-terminals/src/ui/ps.ts +642 -0
  22. package/extensions/background-terminals/src/ui/tool-result.ts +146 -0
  23. package/extensions/background-terminals/src/watch.ts +192 -0
  24. package/extensions/context-pivot/index.ts +222 -0
  25. package/extensions/copy-all/index.ts +65 -0
  26. package/extensions/cron/index.ts +173 -0
  27. package/extensions/cron/schedule.ts +127 -0
  28. package/extensions/file-mutation-display/index.ts +105 -0
  29. package/extensions/file-mutation-display/render.ts +107 -0
  30. package/extensions/file-search/index.ts +515 -0
  31. package/extensions/file-search/src/args.ts +129 -0
  32. package/extensions/file-search/src/binaries.ts +419 -0
  33. package/extensions/file-search/src/output.ts +142 -0
  34. package/extensions/file-search/src/process.ts +309 -0
  35. package/extensions/file-search/src/prompt.ts +53 -0
  36. package/extensions/git-info/index.ts +272 -0
  37. package/extensions/git-info/src/changed-files-view.ts +414 -0
  38. package/extensions/git-info/src/process.ts +107 -0
  39. package/extensions/git-info/src/refresh-coordinator.ts +13 -0
  40. package/extensions/git-info/src/runtime.ts +28 -0
  41. package/extensions/goal/controller.ts +794 -0
  42. package/extensions/goal/index.ts +521 -0
  43. package/extensions/goal/prompts.ts +122 -0
  44. package/extensions/goal/state.ts +763 -0
  45. package/extensions/goal/ui.ts +158 -0
  46. package/extensions/model-info/index.ts +234 -0
  47. package/extensions/plan-mode/bash-policy.ts +313 -0
  48. package/extensions/plan-mode/index.ts +539 -0
  49. package/extensions/post-edit/index.ts +129 -0
  50. package/extensions/sessions/LICENSE.upstream +21 -0
  51. package/extensions/sessions/git-stats.ts +226 -0
  52. package/extensions/sessions/index.ts +1092 -0
  53. package/extensions/sessions/sessions.ts +385 -0
  54. package/extensions/setup/index.ts +408 -0
  55. package/extensions/shared/activity-status.ts +65 -0
  56. package/extensions/shared/below-editor-navigation.ts +343 -0
  57. package/extensions/shared/child-session.ts +352 -0
  58. package/extensions/shared/context-utilization.ts +47 -0
  59. package/extensions/shared/dashboard-state.ts +102 -0
  60. package/extensions/shared/plan-mode-state.ts +65 -0
  61. package/extensions/shared/setup-config.ts +971 -0
  62. package/extensions/shared/subagent-roles.ts +22 -0
  63. package/extensions/shared/terminal-text.ts +38 -0
  64. package/extensions/shared/tool-call-timeout.ts +104 -0
  65. package/extensions/shared/worktree.ts +526 -0
  66. package/extensions/subagents/index.ts +1225 -0
  67. package/extensions/subagents/navigation.ts +121 -0
  68. package/extensions/subagents/src/agent-types.ts +543 -0
  69. package/extensions/subagents/src/backend.ts +63 -0
  70. package/extensions/subagents/src/backends/pi.ts +493 -0
  71. package/extensions/subagents/src/backends/stub.ts +296 -0
  72. package/extensions/subagents/src/by-the-way.ts +21 -0
  73. package/extensions/subagents/src/domain.ts +271 -0
  74. package/extensions/subagents/src/format.ts +48 -0
  75. package/extensions/subagents/src/manager.ts +769 -0
  76. package/extensions/subagents/src/prompt.ts +190 -0
  77. package/extensions/subagents/src/result-delivery.ts +20 -0
  78. package/extensions/subagents/src/runtime.ts +51 -0
  79. package/extensions/subagents/src/ui/takeover.ts +615 -0
  80. package/extensions/subagents/src/ui/transcript.ts +293 -0
  81. package/extensions/subagents/src/ui/wait-result.ts +89 -0
  82. package/extensions/suggestions/index.ts +172 -0
  83. package/extensions/suggestions/src/config.ts +12 -0
  84. package/extensions/suggestions/src/predictor.ts +147 -0
  85. package/extensions/suggestions/src/prompt.ts +20 -0
  86. package/extensions/suggestions/src/transcript.ts +233 -0
  87. package/extensions/suggestions/src/ui.ts +224 -0
  88. package/extensions/tasks/index.ts +512 -0
  89. package/extensions/tasks/tasks.ts +649 -0
  90. package/extensions/tasks/ui.ts +421 -0
  91. package/extensions/turn-time/index.ts +61 -0
  92. package/extensions/ui-customization/footer.ts +512 -0
  93. package/extensions/ui-customization/index.ts +217 -0
  94. package/extensions/workflows/acceptance.ts +298 -0
  95. package/extensions/workflows/artifacts.ts +225 -0
  96. package/extensions/workflows/controller.ts +210 -0
  97. package/extensions/workflows/dashboard.ts +1226 -0
  98. package/extensions/workflows/index.ts +1884 -0
  99. package/extensions/workflows/journal.ts +188 -0
  100. package/extensions/workflows/meta.ts +250 -0
  101. package/extensions/workflows/model.ts +423 -0
  102. package/extensions/workflows/navigation.ts +93 -0
  103. package/extensions/workflows/prompt.ts +212 -0
  104. package/extensions/workflows/replay-safety.ts +577 -0
  105. package/extensions/workflows/runner.ts +786 -0
  106. package/extensions/workflows/sandbox-child.cjs +402 -0
  107. package/extensions/workflows/sandbox.ts +397 -0
  108. package/extensions/workflows/serialization.ts +162 -0
  109. package/extensions/workflows/worktree-handoff.ts +216 -0
  110. package/package.json +87 -0
  111. package/scripts/prepare-effect-tsgo.mjs +16 -0
  112. package/skills/background-terminals/SKILL.md +30 -0
  113. package/skills/subagents/SKILL.md +15 -0
  114. package/themes/github-dark-default.json +89 -0
@@ -0,0 +1,309 @@
1
+ import { spawn, type ChildProcess } from "node:child_process";
2
+ import { createWriteStream } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import type { Writable } from "node:stream";
5
+ import {
6
+ DEFAULT_MAX_BYTES,
7
+ DEFAULT_MAX_LINES,
8
+ truncateHead,
9
+ } from "@earendil-works/pi-coding-agent";
10
+ import { Data, Effect, FileSystem } from "effect";
11
+ import { COMPLETE_OUTPUT_MAX_BYTES, type CapturedOutput } from "./output.ts";
12
+
13
+ const STDERR_MAX_BYTES = 64 * 1024;
14
+
15
+ interface PreviewState {
16
+ readonly decoder: TextDecoder;
17
+ preview: string;
18
+ totalBytes: number;
19
+ lineBreaks: number;
20
+ trailingLineBreaks: number;
21
+ truncated: boolean;
22
+ captureLimitExceeded: boolean;
23
+ }
24
+
25
+ function makePreviewState(): PreviewState {
26
+ return {
27
+ decoder: new TextDecoder(),
28
+ preview: "",
29
+ totalBytes: 0,
30
+ lineBreaks: 0,
31
+ trailingLineBreaks: 0,
32
+ truncated: false,
33
+ captureLimitExceeded: false,
34
+ };
35
+ }
36
+
37
+ function observeStdout(state: PreviewState, chunk: Uint8Array) {
38
+ state.totalBytes += chunk.byteLength;
39
+ for (const byte of chunk) {
40
+ if (byte === 0x0a) {
41
+ state.lineBreaks++;
42
+ state.trailingLineBreaks++;
43
+ } else {
44
+ state.trailingLineBreaks = 0;
45
+ }
46
+ }
47
+
48
+ if (state.truncated) return;
49
+ state.preview += state.decoder.decode(chunk, { stream: true });
50
+ const truncation = truncateHead(state.preview, {
51
+ maxLines: DEFAULT_MAX_LINES,
52
+ maxBytes: DEFAULT_MAX_BYTES,
53
+ });
54
+ if (truncation.truncated) {
55
+ state.preview = truncation.content;
56
+ state.truncated = true;
57
+ }
58
+ }
59
+
60
+ function finishStdout(
61
+ state: PreviewState,
62
+ fullOutputPath: string,
63
+ captureLimitBytes: number,
64
+ ) {
65
+ if (!state.truncated) state.preview += state.decoder.decode();
66
+ const totalBytes = state.totalBytes - state.trailingLineBreaks;
67
+ const lineCount =
68
+ totalBytes === 0 ? 0 : state.lineBreaks - state.trailingLineBreaks + 1;
69
+ return {
70
+ preview: state.preview,
71
+ lineCount,
72
+ totalBytes,
73
+ truncated: state.truncated || state.captureLimitExceeded,
74
+ captureLimitExceeded: state.captureLimitExceeded,
75
+ captureLimitBytes,
76
+ fullOutputPath:
77
+ state.truncated && !state.captureLimitExceeded
78
+ ? fullOutputPath
79
+ : undefined,
80
+ } satisfies CapturedOutput;
81
+ }
82
+
83
+ class SearchProcessError extends Data.TaggedError("SearchProcessError")<{
84
+ readonly message: string;
85
+ }> {}
86
+
87
+ function killProcess(child: ChildProcess, signal: NodeJS.Signals) {
88
+ if (process.platform !== "win32" && child.pid) {
89
+ try {
90
+ process.kill(-child.pid, signal);
91
+ return;
92
+ } catch {
93
+ // Fall through when the process group has already exited.
94
+ }
95
+ }
96
+ try {
97
+ child.kill(signal);
98
+ } catch {
99
+ // The child may already be gone.
100
+ }
101
+ }
102
+
103
+ function captureProcess(
104
+ options: {
105
+ readonly command: string;
106
+ readonly args: readonly string[];
107
+ readonly cwd: string;
108
+ readonly createOutput?: (path: string) => Writable;
109
+ },
110
+ fullOutputPath: string,
111
+ captureLimitBytes: number,
112
+ preview: PreviewState,
113
+ ) {
114
+ return Effect.callback<
115
+ { readonly exitCode: number; readonly stderr: string },
116
+ SearchProcessError
117
+ >((resume) => {
118
+ const output = options.createOutput
119
+ ? options.createOutput(fullOutputPath)
120
+ : createWriteStream(fullOutputPath, { flags: "w" });
121
+ const child = spawn(options.command, options.args, {
122
+ cwd: options.cwd,
123
+ detached: process.platform !== "win32",
124
+ stdio: ["ignore", "pipe", "pipe"],
125
+ });
126
+ let closed = false;
127
+ let outputClosed = false;
128
+ let settled = false;
129
+ let stderr = Buffer.alloc(0);
130
+ let forceKillTimer: ReturnType<typeof setTimeout> | undefined;
131
+
132
+ const complete = (
133
+ result: Effect.Effect<
134
+ { readonly exitCode: number; readonly stderr: string },
135
+ SearchProcessError
136
+ >,
137
+ ) => {
138
+ if (settled) return;
139
+ settled = true;
140
+ resume(result);
141
+ };
142
+ const terminate = () => {
143
+ if (closed || forceKillTimer) return;
144
+ killProcess(child, "SIGTERM");
145
+ forceKillTimer = setTimeout(() => killProcess(child, "SIGKILL"), 1_000);
146
+ forceKillTimer.unref();
147
+ };
148
+ const fail = (error: unknown) => {
149
+ terminate();
150
+ output.destroy();
151
+ const message = error instanceof Error ? error.message : String(error);
152
+ if (outputClosed) {
153
+ complete(Effect.fail(new SearchProcessError({ message })));
154
+ } else {
155
+ output.once("close", () =>
156
+ complete(Effect.fail(new SearchProcessError({ message }))),
157
+ );
158
+ }
159
+ };
160
+
161
+ output.on("close", () => {
162
+ outputClosed = true;
163
+ });
164
+ output.on("error", fail);
165
+ child.on("error", fail);
166
+ child.stdout.on("error", fail);
167
+ child.stderr.on("error", fail);
168
+ child.stdout.on("data", (chunk: Buffer) => {
169
+ if (preview.captureLimitExceeded) return;
170
+ const remaining = captureLimitBytes - preview.totalBytes;
171
+ const captured = chunk.subarray(0, Math.max(0, remaining));
172
+ if (captured.byteLength > 0) {
173
+ observeStdout(preview, captured);
174
+ if (!output.write(captured)) {
175
+ child.stdout.pause();
176
+ output.once("drain", () => child.stdout.resume());
177
+ }
178
+ }
179
+ if (captured.byteLength < chunk.byteLength) {
180
+ preview.captureLimitExceeded = true;
181
+ terminate();
182
+ }
183
+ });
184
+ child.stderr.on("data", (chunk: Buffer) => {
185
+ if (stderr.byteLength >= STDERR_MAX_BYTES) return;
186
+ const remaining = STDERR_MAX_BYTES - stderr.byteLength;
187
+ stderr = Buffer.concat([stderr, chunk.subarray(0, remaining)]);
188
+ });
189
+ child.on("close", (code, signal) => {
190
+ closed = true;
191
+ if (forceKillTimer) clearTimeout(forceKillTimer);
192
+ output.end(() => {
193
+ outputClosed = true;
194
+ if (signal && !preview.captureLimitExceeded) {
195
+ complete(
196
+ Effect.fail(
197
+ new SearchProcessError({
198
+ message: `process terminated by ${signal}`,
199
+ }),
200
+ ),
201
+ );
202
+ return;
203
+ }
204
+ complete(
205
+ Effect.succeed({
206
+ exitCode: preview.captureLimitExceeded ? 0 : (code ?? 1),
207
+ stderr: stderr.toString("utf8"),
208
+ }),
209
+ );
210
+ });
211
+ });
212
+
213
+ return Effect.callback<void>((done) => {
214
+ settled = true;
215
+ let cleanupFinished = false;
216
+ let processDeadlineExpired = false;
217
+ let cleanupDeadline: ReturnType<typeof setTimeout> | undefined;
218
+ const finishCleanup = () => {
219
+ if (
220
+ cleanupFinished ||
221
+ !outputClosed ||
222
+ (!closed && !processDeadlineExpired)
223
+ ) {
224
+ return;
225
+ }
226
+ cleanupFinished = true;
227
+ if (cleanupDeadline) clearTimeout(cleanupDeadline);
228
+ child.off("close", finishCleanup);
229
+ output.off("close", finishCleanup);
230
+ done(Effect.void);
231
+ };
232
+
233
+ child.on("close", finishCleanup);
234
+ output.on("close", finishCleanup);
235
+ cleanupDeadline = setTimeout(() => {
236
+ killProcess(child, "SIGKILL");
237
+ processDeadlineExpired = true;
238
+ finishCleanup();
239
+ }, 1_500);
240
+ cleanupDeadline.unref();
241
+ terminate();
242
+ child.stdout.destroy();
243
+ child.stderr.destroy();
244
+ output.destroy();
245
+ finishCleanup();
246
+
247
+ return Effect.sync(() => {
248
+ if (cleanupDeadline) clearTimeout(cleanupDeadline);
249
+ child.off("close", finishCleanup);
250
+ output.off("close", finishCleanup);
251
+ });
252
+ });
253
+ });
254
+ }
255
+
256
+ export function executeSearchProcess(options: {
257
+ readonly command: string;
258
+ readonly args: readonly string[];
259
+ readonly cwd: string;
260
+ readonly tempPrefix: string;
261
+ /** Test overrides; production capture is capped at 10 MiB. */
262
+ readonly maxCaptureBytes?: number;
263
+ readonly createOutput?: (path: string) => Writable;
264
+ }) {
265
+ return Effect.gen(function* () {
266
+ const fs = yield* FileSystem.FileSystem;
267
+ const directory = yield* fs.makeTempDirectory({
268
+ prefix: options.tempPrefix,
269
+ });
270
+ const fullOutputPath = join(directory, "output.txt");
271
+ const captureLimitBytes = Math.max(
272
+ 1,
273
+ Math.floor(options.maxCaptureBytes ?? COMPLETE_OUTPUT_MAX_BYTES),
274
+ );
275
+ const preview = makePreviewState();
276
+ let retainDirectory = false;
277
+
278
+ return yield* captureProcess(
279
+ options,
280
+ fullOutputPath,
281
+ captureLimitBytes,
282
+ preview,
283
+ ).pipe(
284
+ Effect.map((result) => {
285
+ const output = finishStdout(preview, fullOutputPath, captureLimitBytes);
286
+ retainDirectory = output.fullOutputPath !== undefined;
287
+ return { code: result.exitCode, stderr: result.stderr, output };
288
+ }),
289
+ Effect.ensuring(
290
+ Effect.suspend(() =>
291
+ retainDirectory
292
+ ? Effect.void
293
+ : fs
294
+ .remove(directory, { recursive: true, force: true })
295
+ .pipe(Effect.orDie),
296
+ ),
297
+ ),
298
+ );
299
+ });
300
+ }
301
+
302
+ export function discardCapturedOutput(output: CapturedOutput) {
303
+ if (!output.fullOutputPath) return Effect.void;
304
+ const directory = dirname(output.fullOutputPath);
305
+ return Effect.gen(function* () {
306
+ const fs = yield* FileSystem.FileSystem;
307
+ yield* fs.remove(directory, { recursive: true, force: true });
308
+ });
309
+ }
@@ -0,0 +1,53 @@
1
+ /** Model-facing text for the fd and rg tools. */
2
+
3
+ export const FD_TOOL_DESCRIPTION =
4
+ "Find files and directories by name with fd. Respects .gitignore by default. Results are limited to 1000 entries unless a higher limit is given; output is limited to 2000 lines or 50KB, and complete truncated output up to 10 MiB is saved to a temporary file.";
5
+
6
+ export const FD_PROMPT_SNIPPET =
7
+ "Find files and directories by name with fd (fast, gitignore-aware).";
8
+
9
+ export const FD_PROMPT_GUIDELINES = [
10
+ "Use fd as the primary tool for discovering files and directories by name, extension, or glob instead of bash with find or ls -R.",
11
+ "Use rg instead of fd when searching file contents rather than file names.",
12
+ "Keep using bash for complex multi-step workflows that pipe or post-process file listings.",
13
+ ];
14
+
15
+ export const FD_PARAMETER_DESCRIPTIONS = {
16
+ pattern:
17
+ "Regex matched against file names (or a glob when glob is true). Omit to list everything under path.",
18
+ path: "Directory to search. Defaults to the current working directory.",
19
+ type: "Only return entries of this type: file, directory, or symlink.",
20
+ extension: "Only return files with this extension, e.g. 'ts' or 'md'.",
21
+ glob: "Treat pattern as a glob (e.g. '*.test.ts') instead of a regex.",
22
+ hidden: "Include hidden files and directories. Defaults to false.",
23
+ max_depth: "Maximum directory depth to descend (1-64).",
24
+ limit: "Maximum number of results (1-10000). Defaults to 1000.",
25
+ };
26
+
27
+ export const RG_TOOL_DESCRIPTION =
28
+ "Search file contents with ripgrep. Uses smart-case matching, respects .gitignore by default, and returns at most 100 matches per file unless a different max_matches_per_file value is given. Output is limited to 2000 lines or 50KB; complete truncated output up to 10 MiB is saved to a temporary file.";
29
+
30
+ export const RG_PROMPT_SNIPPET =
31
+ "Search file contents with ripgrep (fast regex content search).";
32
+
33
+ export const RG_PROMPT_GUIDELINES = [
34
+ "Use rg as the primary tool for searching file contents instead of bash with grep.",
35
+ "Use fd instead of rg when looking for files by name rather than content.",
36
+ "Set fixed_strings on rg when searching for literal code snippets containing regex metacharacters.",
37
+ "Keep using bash for complex multi-step workflows that combine searching with other commands.",
38
+ ];
39
+
40
+ export const RG_PARAMETER_DESCRIPTIONS = {
41
+ pattern: "Regex to search for (literal text when fixed_strings is true).",
42
+ path: "File or directory to search. Defaults to the current working directory.",
43
+ glob: "Only search files matching this glob, e.g. '*.ts' or 'src/**'.",
44
+ file_type:
45
+ "Only search files of this ripgrep type, e.g. 'ts', 'js', 'py', 'rust'.",
46
+ case_sensitive:
47
+ "true forces case-sensitive matching, false forces case-insensitive. Defaults to smart-case.",
48
+ fixed_strings: "Treat pattern as a literal string instead of a regex.",
49
+ hidden: "Search hidden files and directories. Defaults to false.",
50
+ context: "Lines of context to show around each match (0-20).",
51
+ max_matches_per_file:
52
+ "Maximum matches returned from each file (1-1000). Defaults to 100. This is not a global result limit.",
53
+ };
@@ -0,0 +1,272 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import { Effect, Fiber, Schedule } from "effect";
6
+ import {
7
+ emptyGitInfoState,
8
+ GIT_INFO_CHANNEL,
9
+ REFRESH_CHANNEL,
10
+ type PullRequestInfo,
11
+ } from "../shared/dashboard-state.ts";
12
+ import {
13
+ loadChangedFiles,
14
+ showChangedFiles,
15
+ } from "./src/changed-files-view.ts";
16
+ import { runCommand, type CommandRunner } from "./src/process.ts";
17
+ import { makeRefreshCoordinator } from "./src/refresh-coordinator.ts";
18
+ import {
19
+ createRuntime,
20
+ runEffect,
21
+ type GitInfoRuntime,
22
+ } from "./src/runtime.ts";
23
+
24
+ const POLL_INTERVAL_MS = 5_000;
25
+ const GIT_TIMEOUT_MS = 3_000;
26
+ const GH_TIMEOUT_MS = 10_000;
27
+
28
+ function countChangedFiles(status: string) {
29
+ if (!status.trim()) return 0;
30
+ return status.split("\n").filter(Boolean).length;
31
+ }
32
+
33
+ function parsePullRequest(value: unknown) {
34
+ if (typeof value !== "object" || value === null) return null;
35
+ if (!("number" in value) || typeof value.number !== "number") return null;
36
+ if (!("url" in value) || typeof value.url !== "string") return null;
37
+ if (!("state" in value) || value.state !== "OPEN") return null;
38
+
39
+ return {
40
+ number: value.number,
41
+ url: value.url,
42
+ isDraft: "isDraft" in value && value.isDraft === true,
43
+ } satisfies PullRequestInfo;
44
+ }
45
+
46
+ function parsePullRequestJson(value: string) {
47
+ try {
48
+ return parsePullRequest(JSON.parse(value));
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+
54
+ export default function gitInfo(pi: ExtensionAPI) {
55
+ let state = emptyGitInfoState();
56
+ let runtime: GitInfoRuntime | undefined;
57
+ let pollingFiber: Fiber.Fiber<void> | undefined;
58
+ let currentContext: ExtensionContext | undefined;
59
+ let generation = 0;
60
+ let queriedPrBranch: string | null = null;
61
+ const refreshCoordinator = makeRefreshCoordinator();
62
+
63
+ const getRuntime = () => (runtime ??= createRuntime());
64
+ const publish = () => pi.events.emit(GIT_INFO_CHANNEL, { ...state });
65
+ const run = (
66
+ command: string,
67
+ args: string[],
68
+ ctx: ExtensionContext,
69
+ timeout: number,
70
+ ) => runCommand(command, args, ctx.cwd, timeout);
71
+
72
+ const lookupPullRequest = (ctx: ExtensionContext, branch: string) =>
73
+ Effect.gen(function* () {
74
+ const result = yield* run(
75
+ "gh",
76
+ ["pr", "view", branch, "--json", "number,url,state,isDraft"],
77
+ ctx,
78
+ GH_TIMEOUT_MS,
79
+ );
80
+ if (result.code !== 0) return null;
81
+ return parsePullRequestJson(result.stdout);
82
+ });
83
+
84
+ const refreshEffect = (
85
+ ctx: ExtensionContext,
86
+ forcePullRequest: boolean,
87
+ refreshGeneration: number,
88
+ ) =>
89
+ Effect.suspend(() => {
90
+ if (refreshGeneration !== generation) return Effect.void;
91
+ currentContext = ctx;
92
+
93
+ return Effect.gen(function* () {
94
+ const repo = yield* run(
95
+ "git",
96
+ ["rev-parse", "--is-inside-work-tree"],
97
+ ctx,
98
+ GIT_TIMEOUT_MS,
99
+ );
100
+ if (refreshGeneration !== generation) return;
101
+
102
+ if (repo.code !== 0 || repo.stdout.trim() !== "true") {
103
+ queriedPrBranch = null;
104
+ state = emptyGitInfoState();
105
+ publish();
106
+ return;
107
+ }
108
+
109
+ const [branchResult, headResult, statusResult] = yield* Effect.all(
110
+ [
111
+ run("git", ["branch", "--show-current"], ctx, GIT_TIMEOUT_MS),
112
+ run("git", ["rev-parse", "--short", "HEAD"], ctx, GIT_TIMEOUT_MS),
113
+ run(
114
+ "git",
115
+ ["status", "--porcelain=v1", "--untracked-files=all"],
116
+ ctx,
117
+ GIT_TIMEOUT_MS,
118
+ ),
119
+ ],
120
+ { concurrency: "unbounded" },
121
+ );
122
+ if (refreshGeneration !== generation) return;
123
+
124
+ const branchName = branchResult.stdout.trim();
125
+ const shortHead = headResult.stdout.trim();
126
+ const branch =
127
+ branchName || (shortHead ? `detached@${shortHead}` : "detached");
128
+ const branchChanged = branchName !== queriedPrBranch;
129
+
130
+ state = {
131
+ ...state,
132
+ isRepository: true,
133
+ branch,
134
+ changedFiles:
135
+ statusResult.code === 0
136
+ ? countChangedFiles(statusResult.stdout)
137
+ : 0,
138
+ pullRequest: branchChanged ? null : state.pullRequest,
139
+ };
140
+ publish();
141
+
142
+ if (!branchName) {
143
+ // queriedPrBranch is never "", so branchChanged already cleared pullRequest.
144
+ queriedPrBranch = null;
145
+ return;
146
+ }
147
+
148
+ if (forcePullRequest) {
149
+ queriedPrBranch = branchName;
150
+ const pullRequest = yield* lookupPullRequest(ctx, branchName);
151
+ if (refreshGeneration !== generation) return;
152
+ state = { ...state, pullRequest };
153
+ publish();
154
+ }
155
+ });
156
+ });
157
+
158
+ const refresh = (ctx: ExtensionContext, forcePullRequest = false) =>
159
+ refreshCoordinator.run(refreshEffect(ctx, forcePullRequest, generation));
160
+
161
+ const refreshIfIdle = (ctx: ExtensionContext) =>
162
+ refreshCoordinator.runIfIdle(refreshEffect(ctx, false, generation));
163
+
164
+ const reportBackgroundDefect = (defect: unknown) =>
165
+ Effect.logError("git-info background task defect", defect);
166
+
167
+ const poll = () =>
168
+ Effect.suspend(() =>
169
+ currentContext ? refreshIfIdle(currentContext) : Effect.void,
170
+ ).pipe(
171
+ Effect.catchDefect(reportBackgroundDefect),
172
+ Effect.repeat(Schedule.fixed(POLL_INTERVAL_MS)),
173
+ Effect.delay(POLL_INTERVAL_MS),
174
+ Effect.asVoid,
175
+ );
176
+
177
+ const forkBackground = (effect: Effect.Effect<void, never, CommandRunner>) =>
178
+ getRuntime().runFork(
179
+ effect.pipe(Effect.catchDefect(reportBackgroundDefect)),
180
+ );
181
+
182
+ const refreshInBackground = (ctx: ExtensionContext) => {
183
+ forkBackground(refreshIfIdle(ctx));
184
+ };
185
+
186
+ const stopRefreshListener = pi.events.on(REFRESH_CHANNEL, () => {
187
+ if (currentContext) refreshInBackground(currentContext);
188
+ });
189
+
190
+ pi.on("session_start", async (_event, ctx) => {
191
+ generation += 1;
192
+ queriedPrBranch = null;
193
+
194
+ const previousPollingFiber = pollingFiber;
195
+ pollingFiber = undefined;
196
+ if (previousPollingFiber) {
197
+ await getRuntime().runPromise(Fiber.interrupt(previousPollingFiber));
198
+ }
199
+
200
+ // Do not block Pi startup on GitHub/network I/O. The initial refresh publishes
201
+ // state when it completes; polling continues to keep it current afterwards.
202
+ refreshInBackground(ctx);
203
+ pollingFiber = forkBackground(poll());
204
+ });
205
+
206
+ pi.on("input", (_event, ctx) => {
207
+ refreshInBackground(ctx);
208
+ return { action: "continue" };
209
+ });
210
+
211
+ pi.on("tool_execution_end", (_event, ctx) => {
212
+ refreshInBackground(ctx);
213
+ });
214
+
215
+ pi.on("session_shutdown", async () => {
216
+ stopRefreshListener();
217
+ generation += 1;
218
+ currentContext = undefined;
219
+ pollingFiber = undefined;
220
+ const closing = runtime;
221
+ runtime = undefined;
222
+ await closing?.dispose();
223
+ });
224
+
225
+ pi.registerCommand("lg", {
226
+ description: "Browse changed files and their diffs",
227
+ handler: async (_args, ctx) => {
228
+ if (ctx.mode !== "tui") {
229
+ ctx.ui.notify(
230
+ "The local changes viewer requires the interactive TUI",
231
+ "warning",
232
+ );
233
+ return;
234
+ }
235
+
236
+ const files = await runEffect(getRuntime(), loadChangedFiles(ctx.cwd), {
237
+ signal: ctx.signal,
238
+ interruptMessage: "Loading changed files was cancelled.",
239
+ });
240
+ if (files === null) {
241
+ ctx.ui.notify("Not a git repository", "warning");
242
+ return;
243
+ }
244
+ if (files.length === 0) {
245
+ ctx.ui.notify("Working tree is clean", "info");
246
+ return;
247
+ }
248
+
249
+ await showChangedFiles(ctx, files);
250
+ },
251
+ });
252
+
253
+ pi.registerCommand("pr", {
254
+ description: "Look up pull request information for the current branch",
255
+ handler: async (_args, ctx) => {
256
+ await runEffect(getRuntime(), refresh(ctx, true), {
257
+ signal: ctx.signal,
258
+ interruptMessage: "Git and pull request refresh was cancelled.",
259
+ });
260
+ if (!state.isRepository) {
261
+ ctx.ui.notify("Not a git repository", "warning");
262
+ } else if (state.pullRequest) {
263
+ ctx.ui.notify(
264
+ `PR #${state.pullRequest.number}: ${state.pullRequest.url}`,
265
+ "info",
266
+ );
267
+ } else {
268
+ ctx.ui.notify(`No open PR found for ${state.branch}`, "info");
269
+ }
270
+ },
271
+ });
272
+ }