repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

lint: remove non-null assertions

3e40400713f946a8db7655811568fc8d71383b25

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (26)

+114 / −75 text lines

Diff layout

extensions/ctx/__tests__/harness.test.ts

Modified

+4 / −3 text lines

4848 });
5050 it("registers no tools and no commands", () => {
51 const [extension] = t!.session.extensionRunner.extensions;
52 expect([...extension.tools.keys()]).toEqual([]);
53 expect([...extension.commands.keys()]).toEqual([]);
51 const [extension] = t?.session.extensionRunner.extensions ?? [];
52 expect(extension).toBeDefined();
53 expect([...(extension?.tools.keys() ?? [])]).toEqual([]);
54 expect([...(extension?.commands.keys() ?? [])]).toEqual([]);
5455 });
5657 it("compacts huge read output before it reaches the transcript", async () => {

extensions/devil/index.ts

Modified

+2 / −1 text lines

967967 ctx.ui?.notify(`No API key for ${model.provider}`, "error");
968968 return;
969969 }
970 const apiKey = auth.apiKey;
970971 const defenderAuth =
971972 await ctx.modelRegistry.getApiKeyAndHeaders(defenderModel);
972973 if (!defenderAuth.ok || !defenderAuth.apiKey) {
10511052 model,
10521053 defenderModel,
10531054 ctx,
1054 apiKey: auth.apiKey!,
1055 apiKey,
10551056 headers: auth.headers,
10561057 devilThinkingLevel,
10571058 defenderThinkingLevel,

extensions/diff-review/__e2e__/e2e.spec.ts

Modified

+3 / −1 text lines

220220 // verify server received the submission
221221 expect(submittedResults.length).toBe(prevSubmissions + 1);
222 const last = submittedResults[submittedResults.length - 1]!;
222 const last = submittedResults.at(-1);
223 expect(last).toBeDefined();
224 if (!last) throw new Error("expected submitted result");
223225 expect(last.type).toBe("submit");
224226 expect(last.notes).toBe("e2e notes");
225227 expect(last.findings.length).toBeGreaterThanOrEqual(1);

extensions/diff-review/git.ts

Modified

+5 / −4 text lines

234234 .map((line) => {
235235 const quotedDiff =
236236 /^diff --git ("(?:[^"\\]|\\.)+") ("(?:[^"\\]|\\.)+")$/.exec(line);
237 if (quotedDiff)
238 return `diff --git ${gitPathToken(quotedDiff[1]!)} ${gitPathToken(quotedDiff[2]!)}`;
237 const [, oldPath, newPath] = quotedDiff ?? [];
238 if (oldPath && newPath)
239 return `diff --git ${gitPathToken(oldPath)} ${gitPathToken(newPath)}`;
239240 const quotedHeader = /^(---|\+\+\+) ("(?:[^"\\]|\\.)+")$/.exec(line);
240 if (quotedHeader)
241 return `${quotedHeader[1]} ${gitPathToken(quotedHeader[2]!)}`;
241 const [, marker, path] = quotedHeader ?? [];
242 if (marker && path) return `${marker} ${gitPathToken(path)}`;
242243 return line;
243244 })
244245 .join("\n");

extensions/footer/index.ts

Modified

+3 / −3 text lines

230230 let line1Width = 0;
231231 let overflowIndex = -1;
233 for (let i = 0; i < rendered.length; i++) {
234 const segWidth = visibleWidth(rendered[i]!);
233 for (const [i, segment] of rendered.entries()) {
234 const segWidth = visibleWidth(segment);
235235 const prefixWidth = line1Width > 0 ? visibleWidth(sep) : 0;
237237 if (line1Width + prefixWidth + segWidth <= width) {
238 line1 += (line1Width > 0 ? sep : "") + rendered[i];
238 line1 += (line1Width > 0 ? sep : "") + segment;
239239 line1Width += prefixWidth + segWidth;
240240 } else {
241241 overflowIndex = i;

extensions/git-safe/index.ts

Modified

+3 / −2 text lines

119119 if (!content || !Array.isArray(content)) return;
121121 const allText = content
122 .filter((c) => c.type === "text" && typeof c.text === "string")
123 .map((c) => c.text!)
122 .flatMap((c) =>
123 c.type === "text" && typeof c.text === "string" ? [c.text] : [],
124 )
124125 .join("\n");
126127 if (!allText) return;

extensions/goal/index.ts

Modified

+4 / −3 text lines

795795 (_tui, theme) => ({
796796 invalidate() {},
797797 render(width: number): string[] {
798 const s = liveGoalState!;
798 const state = liveGoalState;
799 if (!state) return [];
799800 const m = liveGoalMode;
800 const tone = goalTone(s, m);
801 const lines = goalWidgetLines(s, m, width);
801 const tone = goalTone(state, m);
802 const lines = goalWidgetLines(state, m, width);
802803 return lines.map((rawLine) => theme.fg(tone, rawLine));
803804 },
804805 }),

extensions/llmiterate/__tests__/core.test.ts

Modified

+5 / −3 text lines

2929const tempDirs: string[] = [];
3131afterEach(() => {
32 while (tempDirs.length)
33 rmSync(tempDirs.pop()!, { recursive: true, force: true });
32 for (const dir of tempDirs.splice(0))
33 rmSync(dir, { recursive: true, force: true });
3434});
3636function tempDir(): string {
342342describe("llmiterate output snapshots", () => {
343343 test("agent prompt snapshot", () => {
344344 const [block] = parseMarkerPrompts("a.rs", "// llmiterate: implement foo");
345 expect(buildAgentPrompt(block!)).toMatchSnapshot();
345 expect(block).toBeDefined();
346 if (!block) throw new Error("expected llmiterate block");
347 expect(buildAgentPrompt(block)).toMatchSnapshot();
346348 });
347349});

extensions/llmiterate/__tests__/harness.ts

Modified

+2 / −2 text lines

1919export function cleanupHarness(): void {
2020 process.env.XDG_STATE_HOME = oldXdg;
21 while (tempDirs.length)
22 rmSync(tempDirs.pop()!, { recursive: true, force: true });
21 for (const dir of tempDirs.splice(0))
22 rmSync(dir, { recursive: true, force: true });
2525export class FakeWorker {

extensions/llmiterate/__tests__/lock.test.ts

Modified

+2 / −2 text lines

1313const tempDirs: string[] = [];
1515afterEach(() => {
16 while (tempDirs.length)
17 rmSync(tempDirs.pop()!, { recursive: true, force: true });
16 for (const dir of tempDirs.splice(0))
17 rmSync(dir, { recursive: true, force: true });
1818});
2020function tempDir(): string {

extensions/llmiterate/__tests__/log.test.ts

Modified

+2 / −2 text lines

1919const tempDirs: string[] = [];
2121afterEach(() => {
22 while (tempDirs.length)
23 rmSync(tempDirs.pop()!, { recursive: true, force: true });
22 for (const dir of tempDirs.splice(0))
23 rmSync(dir, { recursive: true, force: true });
2424});
2626describe("editor command parsing", () => {

extensions/llmiterate/__tests__/rpc.test.ts

Modified

+2 / −2 text lines

1414afterEach(() => {
1515 while (workers.length) workers.pop()?.dispose();
16 while (tempDirs.length)
17 rmSync(tempDirs.pop()!, { recursive: true, force: true });
16 for (const dir of tempDirs.splice(0))
17 rmSync(dir, { recursive: true, force: true });
1818});
2020describe("PiRpcWorker args", () => {

extensions/llmiterate/__tests__/ui.test.ts

Modified

+2 / −1 text lines

8888 "src/main.ts",
8989 "// llmiterate: implement foo and bar",
9090 );
91 if (!block) throw new Error("expected llmiterate block");
9192 return {
9293 id: 1,
93 block: block!,
94 block,
9495 projectFile: "src/main.ts",
9596 absoluteFile: "/tmp/project/src/main.ts",
9697 fullPrompt: "prompt",

extensions/llmiterate/__tests__/watcher.test.ts

Modified

+2 / −2 text lines

1717afterEach(() => {
1818 while (watchers.length) watchers.pop()?.stop();
19 while (tempDirs.length)
20 rmSync(tempDirs.pop()!, { recursive: true, force: true });
19 for (const dir of tempDirs.splice(0))
20 rmSync(dir, { recursive: true, force: true });
2121});
2323function tempDir(): string {

extensions/llmiterate/path-filter.ts

Modified

+5 / −2 text lines

181181 } else if (patternIndex >= pattern.length) {
182182 result = false;
183183 } else {
184 const segment = pattern[patternIndex]!;
184 const segment = pattern[patternIndex];
185 const dirSegment = dir[dirIndex];
185186 result =
186187 segment === "**"
187188 ? visit(patternIndex + 1, dirIndex) ||
188189 visit(patternIndex, dirIndex + 1)
189 : segment.test(dir[dirIndex]!) &&
190 : !!segment &&
191 !!dirSegment &&
192 segment.test(dirSegment) &&
190193 visit(patternIndex + 1, dirIndex + 1);
191194 }

extensions/neko/__tests__/lifecycle.test.ts

Modified

+6 / −4 text lines

225225 await h.emit("session_before_compact");
226226 const compactionTimer = timers.find(
227227 (timer) => timer.kind === "timeout" && timer.ms === 180_000,
228 )!;
228 );
229 expect(compactionTimer).toBeDefined();
229230 expect(stripAnsi(editor.render(40)[0])).toContain("[");
231 compactionTimer.fn();
232 compactionTimer?.fn();
232233 expect(stripAnsi(editor.render(40)[0])).toContain("(=^");
233234 });
239240 await h.emit("session_before_compact");
240241 const first = timers.find(
241242 (timer) => timer.kind === "timeout" && timer.ms === 180_000,
242 )!;
243 );
244 expect(first).toBeDefined();
243245 await h.emit("session_before_compact");
244246 const compactionTimers = timers.filter(
245247 (timer) => timer.kind === "timeout" && timer.ms === 180_000,
246248 );
248250 expect(compactionTimers).toHaveLength(2);
249 expect(first.cleared).toBe(true);
251 expect(first?.cleared).toBe(true);
250252 expect(compactionTimers[1]?.cleared).toBe(false);
251253 });

extensions/neko/index.ts

Modified

+3 / −1 text lines

289289 const motion: Motion =
290290 Math.abs(this.targetNoseX - this.noseX) > MOVE_STEP ? "walking" : "idle";
291291 const frames = this.framesFor(motion);
292 return frames[this.frame % frames.length]!;
292 const frame = frames[this.frame % frames.length];
293 if (!frame) throw new Error(`missing neko sprite frame: ${motion}`);
294 return frame;
293295 }
295297 override setPaddingX(padding: number): void {

extensions/nu-bang/__tests__/real-world.test.ts

Modified

+4 / −3 text lines

413413 expect(result.output).toContain("truncated");
414414 expect(result.output).toContain("line-2500");
415415 expect(typeof result.fullOutputPath).toBe("string");
416 if (!result.fullOutputPath) throw new Error("expected full output path");
417418 try {
418 const fullOutputStat = await stat(result.fullOutputPath!);
419 const fullOutputStat = await stat(result.fullOutputPath);
419420 expect(fullOutputStat.mode & 0o777).toBe(0o600);
420 const fullOutput = await readFile(result.fullOutputPath!, "utf8");
421 const fullOutput = await readFile(result.fullOutputPath, "utf8");
421422 expect(fullOutput).toContain("line-1");
422423 expect(fullOutput).toContain("line-2500");
423424 expect(fullOutput.length).toBeGreaterThan(result.output.length);
424425 } finally {
425 await rm(result.fullOutputPath!, { force: true });
426 await rm(result.fullOutputPath, { force: true });
426427 }
427428 });
428429});

extensions/pulse/__tests__/harness.test.ts

Modified

+2 / −2 text lines

2020function pulseCommand() {
21 const [extension] = t!.session.extensionRunner.extensions;
22 return extension.commands.get("pulse");
21 const [extension] = t?.session.extensionRunner.extensions ?? [];
22 return extension?.commands.get("pulse");
2525function ctx(): any {

extensions/session-rename/index.ts

Modified

+3 / −2 text lines

6666 if (typeof content === "string") return content;
6767 if (!Array.isArray(content)) return "";
6868 return (content as ContentBlock[])
69 .filter((p) => p?.type === "text" && typeof p.text === "string")
70 .map((p) => p.text!)
69 .flatMap((p) =>
70 p?.type === "text" && typeof p.text === "string" ? [p.text] : [],
71 )
7172 .join("\n");

extensions/ssh-tools/index.ts

Modified

+7 / −6 text lines

225225// ── helpers (function-scoped to access pi) ─────────────────────────────
226226function makeHelpers(pi: ExtensionAPI) {
227 function assertTarget(): asserts target is Target {
227 function assertTarget(): Target {
228228 if (!target) throw new Error("SSH mode off. Use /ssh <host> first.");
229 return target;
229230 }
230231 function enableTools() {
231232 const next = new Set(pi.getActiveTools());
300301 ? { prepareArguments: editBase.prepareArguments }
301302 : {}),
302303 execute(id, params, signal, onUpdate) {
303 assertTarget();
304 return mkDef(target?.cwd, { operations: ops(target!) }).execute(
304 const active = assertTarget();
305 return mkDef(active.cwd, { operations: ops(active) }).execute(
305306 id,
306307 params,
307308 signal,
321322 promptSnippet: "Run bash on remote SSH host",
322323 parameters: bashBase.parameters,
323324 execute(id, params, signal, onUpdate) {
324 assertTarget();
325 return createBashToolDefinition(target?.cwd, {
326 operations: remoteBash(target!),
325 const active = assertTarget();
326 return createBashToolDefinition(active.cwd, {
327 operations: remoteBash(active),
327328 }).execute(id, params, signal, onUpdate);
328329 },
329330 renderCall(args, theme, ctx) {

extensions/superpowers/__tests__/harness.test.ts

Modified

+14 / −5 text lines

1414});
1616const extPath = () => path.resolve(import.meta.dirname, "../index.ts");
17const command = () =>
18 t!.session.extensionRunner.extensions[0].commands.get("superpowers")!;
19const ctx = () => t!.session.extensionRunner.createCommandContext();
17function command() {
18 const cmd =
19 t?.session.extensionRunner.extensions[0]?.commands.get("superpowers");
20 if (!cmd) throw new Error("superpowers command not registered");
21 return cmd;
22}
23function ctx() {
24 if (!t) throw new Error("test session not initialized");
25 return t.session.extensionRunner.createCommandContext();
26}
2027const notices = () =>
2128 t?.events.uiCallsFor("notify").map((c) => String(c.args[0]));
2229const tasksPath = () => __test.tasksFile(t?.cwd);
292299 await waitFor(() =>
293300 t?.events.messages.some((m: any) => m.customType === "superpowers"),
294301 );
295 const firstNotice = notices().at(-1)!;
302 const firstNotice = notices().at(-1);
303 expect(firstNotice).toBeDefined();
296304 expect(firstNotice).toContain("visual live: http://127.0.0.1:");
297305 expect(firstNotice).toContain("content:");
298306 expect(firstNotice).toContain("events file:");
517525 execSync([_cmd, ..._args].join(" "), { cwd: t.cwd });
518526 },
519527 } as any;
520 const isolate = await __test.createIsolate(t.cwd, "sp-test", repo!, piMock);
528 if (!repo) throw new Error("expected git repo");
529 const isolate = await __test.createIsolate(t.cwd, "sp-test", repo, piMock);
521530 expect(isolate.type).toBe("git-standard");
522531 expect(existsSync(isolate.path)).toBe(true);
523532 const task = { isolate, log: [] as string[] } as any;

extensions/superpowers/index.ts

Modified

+9 / −5 text lines

704704 const { isolate } = task;
705705 try {
706706 if (isolate.type === "jj") {
707 await pi.exec("jj", ["workspace", "forget", isolate.workspaceName!]);
707 if (isolate.workspaceName)
708 await pi.exec("jj", ["workspace", "forget", isolate.workspaceName]);
708709 rmdirSync(isolate.path, { recursive: true });
709710 } else if (isolate.type === "git-bare") {
711 if (!isolate.gitDir || !isolate.branch)
712 throw new Error("git-bare isolate missing cleanup metadata");
710713 await pi.exec("git", [
711714 "-C",
712 isolate.gitDir!,
715 isolate.gitDir,
713716 "worktree",
714717 "remove",
715718 "--force",
717720 ]);
718721 await pi.exec("git", [
719722 "-C",
720 isolate.gitDir!,
723 isolate.gitDir,
721724 "branch",
722725 "-D",
723 isolate.branch!,
726 isolate.branch,
724727 ]);
725728 } else {
729 if (!isolate.branch) throw new Error("git isolate missing branch");
726730 await pi.exec("git", ["worktree", "remove", "--force", isolate.path]);
727 await pi.exec("git", ["branch", "-D", isolate.branch!]);
731 await pi.exec("git", ["branch", "-D", isolate.branch]);
728732 }
729733 } catch {
730734 /* best effort cleanup */

extensions/usage/index.ts

Modified

+13 / −9 text lines

203203 compact: !!c.compact,
204204 };
205205 }
206 const fallback = layouts[layouts.length - 1]!;
206 const fallback = layouts.at(-1);
207 if (!fallback) throw new Error("usage layouts must not be empty");
207208 const fw = fallback.columns.reduce((s, col) => s + col.width, 0);
208209 return {
209210 columns: fallback.columns,
253254 if (i % YIELD_EVERY_N_LINES === 0)
254255 await new Promise<void>((r) => setImmediate(r));
256 const line = lines[i]!;
257 if (!line.trim()) continue;
257 const line = lines[i];
258 if (!line?.trim()) continue;
259260 const entry = parseJsonLine(line);
260261 if (!entry) continue;
520521 left = 0,
521522 right = 0,
522523 parallelCost = 0;
523 for (let i = 0; i < sorted.length; i++) {
524 const cur = sorted[i]!;
524 for (const cur of sorted) {
525525 while (
526526 right < sorted.length &&
527527 sorted[right]?.timestamp <= cur.timestamp + PARALLEL_WINDOW_MS
713713 }
714714 if (matchesKey(data, "tab") || matchesKey(data, "right")) {
715715 const idx = TAB_ORDER.indexOf(this.activeTab);
716 this.activeTab = TAB_ORDER[(idx + 1) % TAB_ORDER.length]!;
716 this.activeTab =
717 TAB_ORDER[(idx + 1) % TAB_ORDER.length] ?? this.activeTab;
717718 this.updateProviderOrder();
718719 this.requestRender();
719720 } else if (matchesKey(data, "shift+tab") || matchesKey(data, "left")) {
720721 const idx = TAB_ORDER.indexOf(this.activeTab);
721722 this.activeTab =
722 TAB_ORDER[(idx - 1 + TAB_ORDER.length) % TAB_ORDER.length]!;
723 TAB_ORDER[(idx - 1 + TAB_ORDER.length) % TAB_ORDER.length] ??
724 this.activeTab;
723725 this.updateProviderOrder();
724726 this.requestRender();
725727 } else if (this.viewMode === "table" && matchesKey(data, "up")) {
834836 lines.push(th.fg("dim", " No usage data"));
835837 }
836838 for (let i = 0; i < this.providerOrder.length; i++) {
837 const name = this.providerOrder[i]!;
838 const prov = stats.providers.get(name)!;
839 const name = this.providerOrder[i];
840 if (!name) continue;
841 const prov = stats.providers.get(name);
842 if (!prov) continue;
839843 const sel = i === this.selectedIndex;
840844 const exp = this.expanded.has(name);
841845 const arrow = sel

extensions/web/extract.ts

Modified

+2 / −1 text lines

112112 const openMatch = html.match(openRe);
113113 if (!openMatch) return null;
115 const startIdx = openMatch.index! + openMatch[0].length;
115 if (openMatch.index === undefined) return null;
116 const startIdx = openMatch.index + openMatch[0].length;
116117 return extractBalanced(html, startIdx, tag);

extensions/web/search.ts

Modified

+5 / −4 text lines

5858): Promise<SearchProvider[]> {
5959 const providers: SearchProvider[] = [];
61 if (options.ctx && (await isCodexAvailable(options.ctx))) {
61 const ctx = options.ctx;
62 if (ctx && (await isCodexAvailable(ctx))) {
6263 providers.push({
6364 source: "codex",
6465 label: "Codex",
6566 search: () =>
66 codexSearch(options.query, options.ctx!, options.signal, options.count),
67 codexSearch(options.query, ctx, options.signal, options.count),
6768 });
6869 }
7980 });
8081 }
82 if (options.ctx && (await isMinimaxAvailable(options.ctx))) {
83 if (ctx && (await isMinimaxAvailable(ctx))) {
8384 providers.push({
8485 source: "minimax",
8586 label: "MiniMax",
86 search: () => searchMinimax(options.query, options.ctx!, options.signal),
87 search: () => searchMinimax(options.query, ctx, options.signal),
8788 });
8889 }