@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,419 @@
1
+ /**
2
+ * Startup resolution of the fd and rg executables.
3
+ *
4
+ * Resolution order (per tool, first usable wins):
5
+ * 1. A normally installed system binary (`fd`/`fdfind`, `rg`) — used silently.
6
+ * 2. An existing fallback in this repository's `bin/` directory — used silently.
7
+ * 3. A fresh download of an official release into `bin/` — the only case that
8
+ * should surface a UI notification.
9
+ *
10
+ * The decision logic is an Effect over a small injectable environment
11
+ * (`BinaryEnv`) so tests can drive it without touching the filesystem or the
12
+ * network. `liveBinaryEnv` is the real implementation.
13
+ */
14
+
15
+ import { NodeHttpClient, NodeServices } from "@effect/platform-node";
16
+ import { execFile } from "node:child_process";
17
+ import { tmpdir } from "node:os";
18
+ import { dirname, join } from "node:path";
19
+ import { fileURLToPath } from "node:url";
20
+ import { promisify } from "node:util";
21
+ import { Crypto, Data, Effect, Encoding, FileSystem, Stream } from "effect";
22
+ import { FetchHttpClient, HttpClient } from "effect/unstable/http";
23
+ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
24
+
25
+ const execFileAsync = promisify(execFile);
26
+
27
+ export const FD_VERSION = "10.4.2";
28
+ export const FD_INTEL_DARWIN_VERSION = "10.3.0";
29
+ export const RG_VERSION = "15.2.0";
30
+
31
+ const DOWNLOAD_TIMEOUT_MS = 30_000;
32
+ const MAX_ARCHIVE_BYTES = 25 * 1024 * 1024;
33
+ const MAX_DOWNLOAD_REDIRECTS = 10;
34
+
35
+ const FD_SHA256: Readonly<Record<string, string>> = {
36
+ "aarch64-apple-darwin":
37
+ "623dc0afc81b92e4d4606b380d7bc91916ba7b97814263e554d50923a39e480a",
38
+ "x86_64-apple-darwin":
39
+ "50d30f13fe3d5914b14c4fff5abcbd4d0cdab4b855970a6956f4f006c17117a3",
40
+ "aarch64-unknown-linux-musl":
41
+ "f32d3657473fba74e2600babc8db0b93420d51169223b7e8143b2ed55d8fd9e8",
42
+ "x86_64-unknown-linux-musl":
43
+ "e3257d48e29a6be965187dbd24ce9af564e0fe67b3e73c9bdcd180f4ec11bdde",
44
+ };
45
+
46
+ const RG_SHA256: Readonly<Record<string, string>> = {
47
+ "aarch64-apple-darwin":
48
+ "3750b2e93f37e0c692657da574d7019a101c0084da05a790c83fd335bad973e4",
49
+ "x86_64-apple-darwin":
50
+ "af7825fcc69a2afc7a7aea55fc9af90e26421d8f20fe59df32e233c0b8a231c1",
51
+ "aarch64-unknown-linux-musl":
52
+ "800b1e7206afe799dfb5a6901f23147cfaabe0e52210538100f61e86e1740915",
53
+ "x86_64-unknown-linux-musl":
54
+ "33e15bcf1624b25cdd2a55813a47a2f95dbe126268203e76aa6a585d1e7b149c",
55
+ };
56
+
57
+ export type ToolName = "fd" | "rg";
58
+ export type BinarySource = "system" | "bundled" | "installed";
59
+
60
+ export interface ToolSpec {
61
+ readonly tool: ToolName;
62
+ /** Commands probed on PATH, in order. Debian/Ubuntu install fd as `fdfind`. */
63
+ readonly systemCommands: readonly string[];
64
+ /** Executable name used inside release archives and the repo bin directory. */
65
+ readonly binaryName: string;
66
+ }
67
+
68
+ export const TOOL_SPECS: Record<ToolName, ToolSpec> = {
69
+ fd: { tool: "fd", systemCommands: ["fd", "fdfind"], binaryName: "fd" },
70
+ rg: { tool: "rg", systemCommands: ["rg"], binaryName: "rg" },
71
+ };
72
+
73
+ export interface PlatformTarget {
74
+ readonly os: string;
75
+ readonly arch: string;
76
+ }
77
+
78
+ export interface ReleaseAsset {
79
+ readonly url: string;
80
+ readonly fileName: string;
81
+ /** Top-level directory inside the tarball. */
82
+ readonly archiveDir: string;
83
+ readonly binaryName: string;
84
+ readonly version: string;
85
+ readonly sha256: string;
86
+ }
87
+
88
+ function targetTriple(target: PlatformTarget) {
89
+ const cpu =
90
+ target.arch === "arm64"
91
+ ? "aarch64"
92
+ : target.arch === "x64"
93
+ ? "x86_64"
94
+ : undefined;
95
+ if (!cpu) return undefined;
96
+ if (target.os === "darwin") return `${cpu}-apple-darwin`;
97
+ // musl builds are statically linked, so they run on any Linux distribution.
98
+ if (target.os === "linux") return `${cpu}-unknown-linux-musl`;
99
+ return undefined;
100
+ }
101
+
102
+ /** Official GitHub release asset for a tool on a platform, if supported. */
103
+ export function releaseAsset(
104
+ tool: ToolName,
105
+ target: PlatformTarget,
106
+ ): ReleaseAsset | undefined {
107
+ const triple = targetTriple(target);
108
+ if (!triple) return undefined;
109
+
110
+ if (tool === "fd") {
111
+ const sha256 = FD_SHA256[triple];
112
+ if (!sha256) return undefined;
113
+ // fd 10.4.2 dropped the Intel macOS archive, so retain 10.3.0 there.
114
+ const version =
115
+ triple === "x86_64-apple-darwin" ? FD_INTEL_DARWIN_VERSION : FD_VERSION;
116
+ const archiveDir = `fd-v${version}-${triple}`;
117
+ const fileName = `${archiveDir}.tar.gz`;
118
+ return {
119
+ url: `https://github.com/sharkdp/fd/releases/download/v${version}/${fileName}`,
120
+ fileName,
121
+ archiveDir,
122
+ binaryName: "fd",
123
+ version,
124
+ sha256,
125
+ };
126
+ }
127
+
128
+ const sha256 = RG_SHA256[triple];
129
+ if (!sha256) return undefined;
130
+ const archiveDir = `ripgrep-${RG_VERSION}-${triple}`;
131
+ const fileName = `${archiveDir}.tar.gz`;
132
+ return {
133
+ url: `https://github.com/BurntSushi/ripgrep/releases/download/${RG_VERSION}/${fileName}`,
134
+ fileName,
135
+ archiveDir,
136
+ binaryName: "rg",
137
+ version: RG_VERSION,
138
+ sha256,
139
+ };
140
+ }
141
+
142
+ export function currentTarget(): PlatformTarget {
143
+ return { os: process.platform, arch: process.arch };
144
+ }
145
+
146
+ /** Repository root (`~/.pi/agent`) resolved from this module's location. */
147
+ export function repositoryBinDir() {
148
+ const moduleDir = dirname(fileURLToPath(import.meta.url));
149
+ return join(moduleDir, "..", "..", "..", "bin");
150
+ }
151
+
152
+ export class UnsupportedPlatformError extends Data.TaggedError(
153
+ "UnsupportedPlatformError",
154
+ )<{
155
+ readonly message: string;
156
+ }> {}
157
+
158
+ export class InstallError extends Data.TaggedError("InstallError")<{
159
+ readonly message: string;
160
+ readonly cause?: unknown;
161
+ }> {}
162
+
163
+ export interface BinaryEnv {
164
+ /** True when the executable runs and supports the flags this tool requires. */
165
+ readonly probe: (command: string, tool: ToolName) => Effect.Effect<boolean>;
166
+ /** Download and place a release binary at the destination path. */
167
+ readonly install: (
168
+ asset: ReleaseAsset,
169
+ destination: string,
170
+ ) => Effect.Effect<void, InstallError>;
171
+ }
172
+
173
+ export interface ResolvedBinary {
174
+ readonly tool: ToolName;
175
+ /** Command or absolute path passed to pi.exec. */
176
+ readonly command: string;
177
+ readonly source: BinarySource;
178
+ readonly version?: string;
179
+ }
180
+
181
+ /** Resolve one tool: system binary, existing bin fallback, or fresh install. */
182
+ export function resolveBinary(
183
+ spec: ToolSpec,
184
+ binDir: string,
185
+ target: PlatformTarget,
186
+ env: BinaryEnv,
187
+ ): Effect.Effect<ResolvedBinary, UnsupportedPlatformError | InstallError> {
188
+ return Effect.gen(function* () {
189
+ for (const command of spec.systemCommands) {
190
+ if (yield* env.probe(command, spec.tool)) {
191
+ return { tool: spec.tool, command, source: "system" as const };
192
+ }
193
+ }
194
+
195
+ const bundled = join(binDir, spec.binaryName);
196
+ if (yield* env.probe(bundled, spec.tool)) {
197
+ return { tool: spec.tool, command: bundled, source: "bundled" as const };
198
+ }
199
+
200
+ const asset = releaseAsset(spec.tool, target);
201
+ if (!asset) {
202
+ return yield* new UnsupportedPlatformError({
203
+ message: `No ${spec.tool} binary is available for ${target.os}/${target.arch}. Install ${spec.tool} manually and restart pi.`,
204
+ });
205
+ }
206
+
207
+ yield* env.install(asset, bundled);
208
+
209
+ if (!(yield* env.probe(bundled, spec.tool))) {
210
+ return yield* new InstallError({
211
+ message: `${spec.tool} ${asset.version} was installed to ${bundled} but failed to run.`,
212
+ });
213
+ }
214
+
215
+ return {
216
+ tool: spec.tool,
217
+ command: bundled,
218
+ source: "installed" as const,
219
+ version: asset.version,
220
+ };
221
+ });
222
+ }
223
+
224
+ function errorMessage(error: unknown) {
225
+ return error instanceof Error ? error.message : String(error);
226
+ }
227
+
228
+ /** Read a response incrementally while enforcing the startup memory bound. */
229
+ export function readBoundedResponse<E, R>(
230
+ response: {
231
+ readonly headers: Readonly<Record<string, string | undefined>>;
232
+ readonly stream: Stream.Stream<Uint8Array, E, R>;
233
+ },
234
+ maxBytes = MAX_ARCHIVE_BYTES,
235
+ ) {
236
+ return Effect.gen(function* () {
237
+ const declaredLength = Number(response.headers["content-length"]);
238
+ if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
239
+ return yield* Effect.fail(
240
+ new Error(`download exceeds the ${maxBytes}-byte size limit`),
241
+ );
242
+ }
243
+
244
+ const result = yield* Stream.runFoldEffect(
245
+ response.stream,
246
+ () => ({ chunks: [] as Uint8Array[], totalBytes: 0 }),
247
+ (accumulator, chunk) => {
248
+ const totalBytes = accumulator.totalBytes + chunk.byteLength;
249
+ if (totalBytes > maxBytes) {
250
+ return Effect.fail(
251
+ new Error(`download exceeds the ${maxBytes}-byte size limit`),
252
+ );
253
+ }
254
+ return Effect.sync(() => {
255
+ accumulator.chunks.push(chunk);
256
+ accumulator.totalBytes = totalBytes;
257
+ return accumulator;
258
+ });
259
+ },
260
+ );
261
+
262
+ return Buffer.concat(result.chunks, result.totalBytes);
263
+ });
264
+ }
265
+
266
+ function downloadAsset(client: HttpClient.HttpClient, initialUrl: URL) {
267
+ const scopedClient = client.pipe(HttpClient.withScope);
268
+
269
+ return Effect.gen(function* () {
270
+ let url = initialUrl;
271
+
272
+ for (let redirects = 0; redirects <= MAX_DOWNLOAD_REDIRECTS; redirects++) {
273
+ if (url.protocol !== "https:") {
274
+ return yield* Effect.fail(
275
+ new Error(`refusing non-HTTPS download URL: ${url.href}`),
276
+ );
277
+ }
278
+
279
+ const result = yield* Effect.scoped(
280
+ Effect.gen(function* () {
281
+ const response = yield* scopedClient.get(url);
282
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
283
+ const location = response.headers.location;
284
+ if (!location) {
285
+ return yield* Effect.fail(
286
+ new Error(`redirect from ${url.href} had no location header`),
287
+ );
288
+ }
289
+ if (redirects === MAX_DOWNLOAD_REDIRECTS) {
290
+ return yield* Effect.fail(
291
+ new Error(
292
+ `download exceeded ${MAX_DOWNLOAD_REDIRECTS} redirects`,
293
+ ),
294
+ );
295
+ }
296
+ if (!URL.canParse(location, url)) {
297
+ return yield* Effect.fail(
298
+ new Error(
299
+ `download returned an invalid redirect URL: ${location}`,
300
+ ),
301
+ );
302
+ }
303
+ return { _tag: "Redirect" as const, url: new URL(location, url) };
304
+ }
305
+
306
+ if (response.status < 200 || response.status >= 300) {
307
+ return yield* Effect.fail(
308
+ new Error(`download failed with HTTP ${response.status}`),
309
+ );
310
+ }
311
+ return {
312
+ _tag: "Complete" as const,
313
+ bytes: yield* readBoundedResponse(response),
314
+ };
315
+ }),
316
+ );
317
+
318
+ if (result._tag === "Complete") return result.bytes;
319
+ url = result.url;
320
+ }
321
+
322
+ return yield* Effect.fail(new Error("download redirect handling failed"));
323
+ });
324
+ }
325
+
326
+ /** Real environment: probes via `--version`, installs via HTTPS + tar. */
327
+ export const liveBinaryEnv: BinaryEnv = {
328
+ probe: (command, tool) =>
329
+ Effect.promise(async () => {
330
+ try {
331
+ const args =
332
+ tool === "fd" ? ["--max-results", "1", "--", ""] : ["--version"];
333
+ await execFileAsync(command, args, {
334
+ cwd: tmpdir(),
335
+ timeout: 5_000,
336
+ });
337
+ return true;
338
+ } catch {
339
+ return false;
340
+ }
341
+ }),
342
+
343
+ install: (asset, destination) => {
344
+ const install = Effect.gen(function* () {
345
+ if (!URL.canParse(asset.url)) {
346
+ return yield* Effect.fail(
347
+ new Error(`invalid download URL: ${asset.url}`),
348
+ );
349
+ }
350
+
351
+ const url = new URL(asset.url);
352
+ const client = yield* HttpClient.HttpClient;
353
+ const fs = yield* FileSystem.FileSystem;
354
+ const crypto = yield* Crypto.Crypto;
355
+ const bytes = yield* downloadAsset(client, url).pipe(
356
+ Effect.timeout(DOWNLOAD_TIMEOUT_MS),
357
+ );
358
+
359
+ const digestBytes = yield* crypto.digest("SHA-256", bytes);
360
+ const digest = Encoding.encodeHex(digestBytes);
361
+ if (digest !== asset.sha256) {
362
+ return yield* Effect.fail(
363
+ new Error(
364
+ `SHA-256 mismatch for ${asset.fileName}: expected ${asset.sha256}, received ${digest}`,
365
+ ),
366
+ );
367
+ }
368
+
369
+ const workDir = yield* fs.makeTempDirectoryScoped({
370
+ prefix: "pi-file-search-",
371
+ });
372
+ const archivePath = join(workDir, asset.fileName);
373
+ yield* fs.writeFile(archivePath, bytes);
374
+
375
+ const tarExitCode = yield* Effect.scoped(
376
+ Effect.gen(function* () {
377
+ const tar = yield* ChildProcess.make(
378
+ "tar",
379
+ ["-xzf", archivePath, "-C", workDir],
380
+ { stdin: "ignore", stdout: "ignore", stderr: "ignore" },
381
+ );
382
+ return yield* tar.exitCode;
383
+ }),
384
+ ).pipe(Effect.timeout(60_000));
385
+ if (tarExitCode !== ChildProcessSpawner.ExitCode(0)) {
386
+ return yield* Effect.fail(
387
+ new Error(`tar failed with exit code ${tarExitCode}`),
388
+ );
389
+ }
390
+
391
+ const extracted = join(workDir, asset.archiveDir, asset.binaryName);
392
+ yield* fs.makeDirectory(dirname(destination), { recursive: true });
393
+ const uuid = yield* crypto.randomUUIDv4;
394
+ const stagedDestination = `${destination}.${process.pid}.${uuid}.tmp`;
395
+ yield* Effect.addFinalizer(() =>
396
+ fs.remove(stagedDestination, { force: true }).pipe(Effect.orDie),
397
+ );
398
+ yield* fs.copyFile(extracted, stagedDestination);
399
+ yield* fs.chmod(stagedDestination, 0o755);
400
+ yield* fs.rename(stagedDestination, destination);
401
+ });
402
+
403
+ return install.pipe(
404
+ Effect.scoped,
405
+ Effect.provide(NodeServices.layer),
406
+ Effect.provide(NodeHttpClient.layerFetch),
407
+ Effect.provideService(FetchHttpClient.RequestInit, {
408
+ redirect: "manual",
409
+ }),
410
+ Effect.mapError(
411
+ (cause) =>
412
+ new InstallError({
413
+ message: `Failed to install ${asset.binaryName} ${asset.version} from ${asset.url}: ${errorMessage(cause)}`,
414
+ cause,
415
+ }),
416
+ ),
417
+ );
418
+ },
419
+ };
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Shared output shaping for the fd and rg tools: standard pi truncation
3
+ * (2000 lines / 50KB) with complete output persisted to a temp file up to the
4
+ * documented 10 MiB capture limit.
5
+ */
6
+
7
+ import { mkdtemp, writeFile } from "node:fs/promises";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ import {
11
+ DEFAULT_MAX_BYTES,
12
+ DEFAULT_MAX_LINES,
13
+ formatSize,
14
+ truncateHead,
15
+ } from "@earendil-works/pi-coding-agent";
16
+
17
+ /** Maximum complete fd/rg output retained in a temporary artifact (10 MiB). */
18
+ export const COMPLETE_OUTPUT_MAX_BYTES = 10 * 1024 * 1024;
19
+
20
+ export interface FormattedOutput {
21
+ readonly text: string;
22
+ readonly lineCount: number;
23
+ readonly truncated: boolean;
24
+ readonly fullOutputPath?: string;
25
+ }
26
+
27
+ export interface CapturedOutput {
28
+ readonly preview: string;
29
+ readonly lineCount: number;
30
+ readonly totalBytes: number;
31
+ readonly truncated: boolean;
32
+ readonly captureLimitExceeded: boolean;
33
+ readonly captureLimitBytes: number;
34
+ readonly fullOutputPath?: string;
35
+ }
36
+
37
+ export interface FormatOutputOptions {
38
+ /** Temp-file prefix, e.g. "pi-fd-". */
39
+ readonly tempPrefix: string;
40
+ /** Injectable for tests. */
41
+ readonly persistFullOutput?: (output: string) => Promise<string>;
42
+ }
43
+
44
+ async function persistToTempFile(prefix: string, output: string) {
45
+ const directory = await mkdtemp(join(tmpdir(), prefix));
46
+ const path = join(directory, "output.txt");
47
+ await writeFile(path, output, "utf8");
48
+ return path;
49
+ }
50
+
51
+ function truncationNotice(options: {
52
+ content: string;
53
+ outputLines: number;
54
+ totalLines: number;
55
+ outputBytes: number;
56
+ totalBytes: number;
57
+ fullOutputPath: string;
58
+ }) {
59
+ return (
60
+ `${options.content}\n\n[Output truncated: ${options.outputLines} of ${options.totalLines} lines ` +
61
+ `(${formatSize(options.outputBytes)} of ${formatSize(options.totalBytes)}). ` +
62
+ `Full output saved to: ${options.fullOutputPath}]`
63
+ );
64
+ }
65
+
66
+ /** Format output already captured by a bounded-memory streaming process. */
67
+ export function formatCapturedOutput(captured: CapturedOutput) {
68
+ const trimmed = captured.preview.replace(/\n+$/, "");
69
+ const truncation = truncateHead(trimmed, {
70
+ maxLines: DEFAULT_MAX_LINES,
71
+ maxBytes: DEFAULT_MAX_BYTES,
72
+ });
73
+ const content = truncation.content;
74
+ const outputLines = content === "" ? 0 : content.split("\n").length;
75
+ const outputBytes = Buffer.byteLength(content);
76
+
77
+ if (captured.captureLimitExceeded) {
78
+ return {
79
+ text:
80
+ `${content}\n\n[Output truncated: search output exceeded the ${formatSize(captured.captureLimitBytes)} complete-output capture limit. ` +
81
+ "The search was stopped and its partial temporary artifact was removed.]",
82
+ lineCount: captured.lineCount,
83
+ truncated: true,
84
+ } satisfies FormattedOutput;
85
+ }
86
+
87
+ if (!captured.truncated || !captured.fullOutputPath) {
88
+ return {
89
+ text: trimmed,
90
+ lineCount: captured.lineCount,
91
+ truncated: false,
92
+ } satisfies FormattedOutput;
93
+ }
94
+
95
+ return {
96
+ text: truncationNotice({
97
+ content,
98
+ outputLines,
99
+ totalLines: captured.lineCount,
100
+ outputBytes,
101
+ totalBytes: captured.totalBytes,
102
+ fullOutputPath: captured.fullOutputPath,
103
+ }),
104
+ lineCount: captured.lineCount,
105
+ truncated: true,
106
+ fullOutputPath: captured.fullOutputPath,
107
+ } satisfies FormattedOutput;
108
+ }
109
+
110
+ /** Truncate to pi's standard limits, persisting the full output when cut. */
111
+ export async function formatOutput(
112
+ output: string,
113
+ options: FormatOutputOptions,
114
+ ): Promise<FormattedOutput> {
115
+ const trimmed = output.replace(/\n+$/, "");
116
+ const lineCount = trimmed === "" ? 0 : trimmed.split("\n").length;
117
+
118
+ const truncation = truncateHead(trimmed, {
119
+ maxLines: DEFAULT_MAX_LINES,
120
+ maxBytes: DEFAULT_MAX_BYTES,
121
+ });
122
+
123
+ if (!truncation.truncated) {
124
+ return { text: trimmed, lineCount, truncated: false };
125
+ }
126
+
127
+ const persist =
128
+ options.persistFullOutput ??
129
+ ((full: string) => persistToTempFile(options.tempPrefix, full));
130
+ const fullOutputPath = await persist(trimmed);
131
+
132
+ const text = truncationNotice({
133
+ content: truncation.content,
134
+ outputLines: truncation.outputLines,
135
+ totalLines: truncation.totalLines,
136
+ outputBytes: truncation.outputBytes,
137
+ totalBytes: truncation.totalBytes,
138
+ fullOutputPath,
139
+ });
140
+
141
+ return { text, lineCount, truncated: true, fullOutputPath };
142
+ }