@mrquake/quakecode-cli 0.64.0 → 0.64.2

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 (180) hide show
  1. package/dist/bun/cli.d.ts.map +1 -1
  2. package/dist/bun/cli.js +1 -1
  3. package/dist/bun/cli.js.map +1 -1
  4. package/dist/config.d.ts.map +1 -1
  5. package/dist/config.js +7 -10
  6. package/dist/config.js.map +1 -1
  7. package/dist/core/extensions/loader.d.ts.map +1 -1
  8. package/dist/core/extensions/loader.js +21 -7
  9. package/dist/core/extensions/loader.js.map +1 -1
  10. package/dist/core/settings-manager.d.ts.map +1 -1
  11. package/dist/core/settings-manager.js +2 -2
  12. package/dist/core/settings-manager.js.map +1 -1
  13. package/dist/core/slash-commands.d.ts.map +1 -1
  14. package/dist/core/slash-commands.js +1 -1
  15. package/dist/core/slash-commands.js.map +1 -1
  16. package/dist/core/system-prompt.d.ts.map +1 -1
  17. package/dist/core/system-prompt.js +5 -5
  18. package/dist/core/system-prompt.js.map +1 -1
  19. package/dist/main.d.ts.map +1 -1
  20. package/dist/main.js +7 -7
  21. package/dist/main.js.map +1 -1
  22. package/dist/migrations.d.ts.map +1 -1
  23. package/dist/migrations.js +2 -2
  24. package/dist/migrations.js.map +1 -1
  25. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  26. package/dist/modes/interactive/components/config-selector.js +1 -1
  27. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  28. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  29. package/dist/modes/interactive/components/session-selector.js +82 -105
  30. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  31. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  32. package/dist/modes/interactive/interactive-mode.js +10 -5
  33. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  34. package/dist/utils/clipboard-image.d.ts.map +1 -1
  35. package/dist/utils/clipboard-image.js +3 -3
  36. package/dist/utils/clipboard-image.js.map +1 -1
  37. package/package.json +14 -7
  38. package/docs/compaction.md +0 -394
  39. package/docs/custom-provider.md +0 -596
  40. package/docs/development.md +0 -71
  41. package/docs/extensions.md +0 -2286
  42. package/docs/images/doom-extension.png +0 -0
  43. package/docs/images/exy.png +0 -0
  44. package/docs/images/interactive-mode.png +0 -0
  45. package/docs/images/tree-view.png +0 -0
  46. package/docs/json.md +0 -82
  47. package/docs/keybindings.md +0 -175
  48. package/docs/models.md +0 -341
  49. package/docs/packages.md +0 -218
  50. package/docs/prompt-templates.md +0 -67
  51. package/docs/providers.md +0 -195
  52. package/docs/rpc.md +0 -1377
  53. package/docs/sdk.md +0 -1064
  54. package/docs/session.md +0 -412
  55. package/docs/settings.md +0 -246
  56. package/docs/shell-aliases.md +0 -13
  57. package/docs/skills.md +0 -232
  58. package/docs/terminal-setup.md +0 -106
  59. package/docs/termux.md +0 -127
  60. package/docs/themes.md +0 -295
  61. package/docs/tmux.md +0 -61
  62. package/docs/tree.md +0 -231
  63. package/docs/tui.md +0 -887
  64. package/docs/windows.md +0 -17
  65. package/examples/README.md +0 -25
  66. package/examples/extensions/README.md +0 -206
  67. package/examples/extensions/antigravity-image-gen.ts +0 -418
  68. package/examples/extensions/auto-commit-on-exit.ts +0 -49
  69. package/examples/extensions/bash-spawn-hook.ts +0 -30
  70. package/examples/extensions/bookmark.ts +0 -50
  71. package/examples/extensions/built-in-tool-renderer.ts +0 -246
  72. package/examples/extensions/claude-rules.ts +0 -86
  73. package/examples/extensions/commands.ts +0 -72
  74. package/examples/extensions/confirm-destructive.ts +0 -59
  75. package/examples/extensions/custom-compaction.ts +0 -127
  76. package/examples/extensions/custom-footer.ts +0 -64
  77. package/examples/extensions/custom-header.ts +0 -73
  78. package/examples/extensions/custom-provider-anthropic/index.ts +0 -604
  79. package/examples/extensions/custom-provider-anthropic/package-lock.json +0 -24
  80. package/examples/extensions/custom-provider-anthropic/package.json +0 -19
  81. package/examples/extensions/custom-provider-gitlab-duo/index.ts +0 -349
  82. package/examples/extensions/custom-provider-gitlab-duo/package.json +0 -16
  83. package/examples/extensions/custom-provider-gitlab-duo/test.ts +0 -82
  84. package/examples/extensions/custom-provider-qwen-cli/index.ts +0 -345
  85. package/examples/extensions/custom-provider-qwen-cli/package.json +0 -16
  86. package/examples/extensions/dirty-repo-guard.ts +0 -56
  87. package/examples/extensions/doom-overlay/README.md +0 -46
  88. package/examples/extensions/doom-overlay/doom/build/doom.js +0 -21
  89. package/examples/extensions/doom-overlay/doom/build/doom.wasm +0 -0
  90. package/examples/extensions/doom-overlay/doom/build.sh +0 -152
  91. package/examples/extensions/doom-overlay/doom/doomgeneric_pi.c +0 -72
  92. package/examples/extensions/doom-overlay/doom-component.ts +0 -132
  93. package/examples/extensions/doom-overlay/doom-engine.ts +0 -173
  94. package/examples/extensions/doom-overlay/doom-keys.ts +0 -104
  95. package/examples/extensions/doom-overlay/index.ts +0 -74
  96. package/examples/extensions/doom-overlay/wad-finder.ts +0 -51
  97. package/examples/extensions/dynamic-resources/SKILL.md +0 -8
  98. package/examples/extensions/dynamic-resources/dynamic.json +0 -79
  99. package/examples/extensions/dynamic-resources/dynamic.md +0 -5
  100. package/examples/extensions/dynamic-resources/index.ts +0 -15
  101. package/examples/extensions/dynamic-tools.ts +0 -74
  102. package/examples/extensions/event-bus.ts +0 -43
  103. package/examples/extensions/file-trigger.ts +0 -41
  104. package/examples/extensions/git-checkpoint.ts +0 -53
  105. package/examples/extensions/handoff.ts +0 -153
  106. package/examples/extensions/hello.ts +0 -26
  107. package/examples/extensions/hidden-thinking-label.ts +0 -53
  108. package/examples/extensions/inline-bash.ts +0 -94
  109. package/examples/extensions/input-transform.ts +0 -43
  110. package/examples/extensions/interactive-shell.ts +0 -196
  111. package/examples/extensions/mac-system-theme.ts +0 -47
  112. package/examples/extensions/message-renderer.ts +0 -59
  113. package/examples/extensions/minimal-mode.ts +0 -426
  114. package/examples/extensions/modal-editor.ts +0 -85
  115. package/examples/extensions/model-status.ts +0 -31
  116. package/examples/extensions/notify.ts +0 -55
  117. package/examples/extensions/overlay-qa-tests.ts +0 -1348
  118. package/examples/extensions/overlay-test.ts +0 -150
  119. package/examples/extensions/permission-gate.ts +0 -34
  120. package/examples/extensions/pirate.ts +0 -47
  121. package/examples/extensions/plan-mode/README.md +0 -65
  122. package/examples/extensions/plan-mode/index.ts +0 -340
  123. package/examples/extensions/plan-mode/utils.ts +0 -168
  124. package/examples/extensions/preset.ts +0 -397
  125. package/examples/extensions/protected-paths.ts +0 -30
  126. package/examples/extensions/provider-payload.ts +0 -14
  127. package/examples/extensions/qna.ts +0 -122
  128. package/examples/extensions/question.ts +0 -264
  129. package/examples/extensions/questionnaire.ts +0 -427
  130. package/examples/extensions/rainbow-editor.ts +0 -88
  131. package/examples/extensions/reload-runtime.ts +0 -37
  132. package/examples/extensions/rpc-demo.ts +0 -118
  133. package/examples/extensions/sandbox/index.ts +0 -321
  134. package/examples/extensions/sandbox/package-lock.json +0 -92
  135. package/examples/extensions/sandbox/package.json +0 -19
  136. package/examples/extensions/send-user-message.ts +0 -97
  137. package/examples/extensions/session-name.ts +0 -27
  138. package/examples/extensions/shutdown-command.ts +0 -63
  139. package/examples/extensions/snake.ts +0 -343
  140. package/examples/extensions/space-invaders.ts +0 -560
  141. package/examples/extensions/ssh.ts +0 -220
  142. package/examples/extensions/status-line.ts +0 -32
  143. package/examples/extensions/subagent/README.md +0 -172
  144. package/examples/extensions/subagent/agents/planner.md +0 -37
  145. package/examples/extensions/subagent/agents/reviewer.md +0 -35
  146. package/examples/extensions/subagent/agents/scout.md +0 -50
  147. package/examples/extensions/subagent/agents/worker.md +0 -24
  148. package/examples/extensions/subagent/agents.ts +0 -126
  149. package/examples/extensions/subagent/index.ts +0 -986
  150. package/examples/extensions/subagent/prompts/implement-and-review.md +0 -10
  151. package/examples/extensions/subagent/prompts/implement.md +0 -10
  152. package/examples/extensions/subagent/prompts/scout-and-plan.md +0 -9
  153. package/examples/extensions/summarize.ts +0 -206
  154. package/examples/extensions/system-prompt-header.ts +0 -17
  155. package/examples/extensions/timed-confirm.ts +0 -70
  156. package/examples/extensions/titlebar-spinner.ts +0 -58
  157. package/examples/extensions/todo.ts +0 -297
  158. package/examples/extensions/tool-override.ts +0 -144
  159. package/examples/extensions/tools.ts +0 -141
  160. package/examples/extensions/trigger-compact.ts +0 -50
  161. package/examples/extensions/truncated-tool.ts +0 -195
  162. package/examples/extensions/widget-placement.ts +0 -9
  163. package/examples/extensions/with-deps/index.ts +0 -32
  164. package/examples/extensions/with-deps/package-lock.json +0 -31
  165. package/examples/extensions/with-deps/package.json +0 -22
  166. package/examples/rpc-extension-ui.ts +0 -632
  167. package/examples/sdk/01-minimal.ts +0 -22
  168. package/examples/sdk/02-custom-model.ts +0 -49
  169. package/examples/sdk/03-custom-prompt.ts +0 -55
  170. package/examples/sdk/04-skills.ts +0 -52
  171. package/examples/sdk/05-tools.ts +0 -56
  172. package/examples/sdk/06-extensions.ts +0 -88
  173. package/examples/sdk/07-context-files.ts +0 -40
  174. package/examples/sdk/08-prompt-templates.ts +0 -48
  175. package/examples/sdk/09-api-keys-and-oauth.ts +0 -48
  176. package/examples/sdk/10-settings.ts +0 -51
  177. package/examples/sdk/11-sessions.ts +0 -48
  178. package/examples/sdk/12-full-control.ts +0 -81
  179. package/examples/sdk/13-session-runtime.ts +0 -49
  180. package/examples/sdk/README.md +0 -145
@@ -1,144 +0,0 @@
1
- /**
2
- * Tool Override Example - Demonstrates overriding built-in tools
3
- *
4
- * Extensions can register tools with the same name as built-in tools to replace them.
5
- * This is useful for:
6
- * - Adding logging or auditing to tool calls
7
- * - Implementing access control or sandboxing
8
- * - Routing tool calls to remote systems (e.g., pi-ssh-remote)
9
- * - Modifying tool behavior for specific workflows
10
- *
11
- * This example overrides the `read` tool to:
12
- * 1. Log all file access to a log file
13
- * 2. Block access to sensitive paths (e.g., .env files)
14
- * 3. Delegate to the original read implementation for allowed files
15
- *
16
- * Since no custom renderCall/renderResult are provided, the built-in renderer
17
- * is used automatically (syntax highlighting, line numbers, truncation warnings).
18
- *
19
- * Usage:
20
- * pi -e ./tool-override.ts
21
- */
22
-
23
- import type { TextContent } from "@mariozechner/pi-ai";
24
- import { type ExtensionAPI, getAgentDir, withFileMutationQueue } from "@mariozechner/pi-coding-agent";
25
- import { Type } from "@sinclair/typebox";
26
- import { constants, readFileSync } from "fs";
27
- import { access, appendFile, readFile } from "fs/promises";
28
- import { join, resolve } from "path";
29
-
30
- const LOG_FILE = join(getAgentDir(), "read-access.log");
31
-
32
- // Paths that are blocked from reading
33
- const BLOCKED_PATTERNS = [
34
- /\.env$/,
35
- /\.env\..+$/,
36
- /secrets?\.(json|yaml|yml|toml)$/i,
37
- /credentials?\.(json|yaml|yml|toml)$/i,
38
- /\/\.ssh\//,
39
- /\/\.aws\//,
40
- /\/\.gnupg\//,
41
- ];
42
-
43
- function isBlockedPath(path: string): boolean {
44
- return BLOCKED_PATTERNS.some((pattern) => pattern.test(path));
45
- }
46
-
47
- async function logAccess(path: string, allowed: boolean, reason?: string) {
48
- const timestamp = new Date().toISOString();
49
- const status = allowed ? "ALLOWED" : "BLOCKED";
50
- const msg = reason ? ` (${reason})` : "";
51
- const line = `[${timestamp}] ${status}: ${path}${msg}\n`;
52
-
53
- try {
54
- await withFileMutationQueue(LOG_FILE, async () => {
55
- await appendFile(LOG_FILE, line);
56
- });
57
- } catch {
58
- // Ignore logging errors
59
- }
60
- }
61
-
62
- const readSchema = Type.Object({
63
- path: Type.String({ description: "Path to the file to read (relative or absolute)" }),
64
- offset: Type.Optional(Type.Number({ description: "Line number to start reading from (1-indexed)" })),
65
- limit: Type.Optional(Type.Number({ description: "Maximum number of lines to read" })),
66
- });
67
-
68
- export default function (pi: ExtensionAPI) {
69
- pi.registerTool({
70
- name: "read", // Same name as built-in - this will override it
71
- label: "read (audited)",
72
- description:
73
- "Read the contents of a file with access logging. Some sensitive paths (.env, secrets, credentials) are blocked.",
74
- parameters: readSchema,
75
-
76
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
77
- const { path, offset, limit } = params;
78
- const absolutePath = resolve(ctx.cwd, path);
79
-
80
- // Check if path is blocked
81
- if (isBlockedPath(absolutePath)) {
82
- await logAccess(absolutePath, false, "matches blocked pattern");
83
- return {
84
- content: [
85
- {
86
- type: "text",
87
- text: `Access denied: "${path}" matches a blocked pattern (sensitive file). This tool blocks access to .env files, secrets, credentials, and SSH/AWS/GPG directories.`,
88
- },
89
- ],
90
- details: { blocked: true },
91
- };
92
- }
93
-
94
- // Log allowed access
95
- await logAccess(absolutePath, true);
96
-
97
- // Perform the actual read (simplified implementation)
98
- try {
99
- await access(absolutePath, constants.R_OK);
100
- const content = await readFile(absolutePath, "utf-8");
101
- const lines = content.split("\n");
102
-
103
- // Apply offset and limit
104
- const startLine = offset ? Math.max(0, offset - 1) : 0;
105
- const endLine = limit ? startLine + limit : lines.length;
106
- const selectedLines = lines.slice(startLine, endLine);
107
-
108
- // Basic truncation (50KB limit)
109
- let text = selectedLines.join("\n");
110
- const maxBytes = 50 * 1024;
111
- if (Buffer.byteLength(text, "utf-8") > maxBytes) {
112
- text = `${text.slice(0, maxBytes)}\n\n[Output truncated at 50KB]`;
113
- }
114
-
115
- return {
116
- content: [{ type: "text", text }] as TextContent[],
117
- details: { lines: lines.length },
118
- };
119
- } catch (error: any) {
120
- return {
121
- content: [{ type: "text", text: `Error reading file: ${error.message}` }] as TextContent[],
122
- details: { error: true },
123
- };
124
- }
125
- },
126
-
127
- // No renderCall/renderResult - uses built-in renderer automatically
128
- // (syntax highlighting, line numbers, truncation warnings, etc.)
129
- });
130
-
131
- // Also register a command to view the access log
132
- pi.registerCommand("read-log", {
133
- description: "View the file access log",
134
- handler: async (_args, ctx) => {
135
- try {
136
- const log = readFileSync(LOG_FILE, "utf-8");
137
- const lines = log.trim().split("\n").slice(-20); // Last 20 entries
138
- ctx.ui.notify(`Recent file access:\n${lines.join("\n")}`, "info");
139
- } catch {
140
- ctx.ui.notify("No access log found", "info");
141
- }
142
- },
143
- });
144
- }
@@ -1,141 +0,0 @@
1
- /**
2
- * Tools Extension
3
- *
4
- * Provides a /tools command to enable/disable tools interactively.
5
- * Tool selection persists across session reloads and respects branch navigation.
6
- *
7
- * Usage:
8
- * 1. Copy this file to ~/.pi/agent/extensions/ or your project's .pi/extensions/
9
- * 2. Use /tools to open the tool selector
10
- */
11
-
12
- import type { ExtensionAPI, ExtensionContext, ToolInfo } from "@mariozechner/pi-coding-agent";
13
- import { getSettingsListTheme } from "@mariozechner/pi-coding-agent";
14
- import { Container, type SettingItem, SettingsList } from "@mariozechner/pi-tui";
15
-
16
- // State persisted to session
17
- interface ToolsState {
18
- enabledTools: string[];
19
- }
20
-
21
- export default function toolsExtension(pi: ExtensionAPI) {
22
- // Track enabled tools
23
- let enabledTools: Set<string> = new Set();
24
- let allTools: ToolInfo[] = [];
25
-
26
- // Persist current state
27
- function persistState() {
28
- pi.appendEntry<ToolsState>("tools-config", {
29
- enabledTools: Array.from(enabledTools),
30
- });
31
- }
32
-
33
- // Apply current tool selection
34
- function applyTools() {
35
- pi.setActiveTools(Array.from(enabledTools));
36
- }
37
-
38
- // Find the last tools-config entry in the current branch
39
- function restoreFromBranch(ctx: ExtensionContext) {
40
- allTools = pi.getAllTools();
41
-
42
- // Get entries in current branch only
43
- const branchEntries = ctx.sessionManager.getBranch();
44
- let savedTools: string[] | undefined;
45
-
46
- for (const entry of branchEntries) {
47
- if (entry.type === "custom" && entry.customType === "tools-config") {
48
- const data = entry.data as ToolsState | undefined;
49
- if (data?.enabledTools) {
50
- savedTools = data.enabledTools;
51
- }
52
- }
53
- }
54
-
55
- if (savedTools) {
56
- // Restore saved tool selection (filter to only tools that still exist)
57
- const allToolNames = allTools.map((t) => t.name);
58
- enabledTools = new Set(savedTools.filter((t: string) => allToolNames.includes(t)));
59
- applyTools();
60
- } else {
61
- // No saved state - sync with currently active tools
62
- enabledTools = new Set(pi.getActiveTools());
63
- }
64
- }
65
-
66
- // Register /tools command
67
- pi.registerCommand("tools", {
68
- description: "Enable/disable tools",
69
- handler: async (_args, ctx) => {
70
- // Refresh tool list
71
- allTools = pi.getAllTools();
72
-
73
- await ctx.ui.custom((tui, theme, _kb, done) => {
74
- // Build settings items for each tool
75
- const items: SettingItem[] = allTools.map((tool) => ({
76
- id: tool.name,
77
- label: tool.name,
78
- currentValue: enabledTools.has(tool.name) ? "enabled" : "disabled",
79
- values: ["enabled", "disabled"],
80
- }));
81
-
82
- const container = new Container();
83
- container.addChild(
84
- new (class {
85
- render(_width: number) {
86
- return [theme.fg("accent", theme.bold("Tool Configuration")), ""];
87
- }
88
- invalidate() {}
89
- })(),
90
- );
91
-
92
- const settingsList = new SettingsList(
93
- items,
94
- Math.min(items.length + 2, 15),
95
- getSettingsListTheme(),
96
- (id, newValue) => {
97
- // Update enabled state and apply immediately
98
- if (newValue === "enabled") {
99
- enabledTools.add(id);
100
- } else {
101
- enabledTools.delete(id);
102
- }
103
- applyTools();
104
- persistState();
105
- },
106
- () => {
107
- // Close dialog
108
- done(undefined);
109
- },
110
- );
111
-
112
- container.addChild(settingsList);
113
-
114
- const component = {
115
- render(width: number) {
116
- return container.render(width);
117
- },
118
- invalidate() {
119
- container.invalidate();
120
- },
121
- handleInput(data: string) {
122
- settingsList.handleInput?.(data);
123
- tui.requestRender();
124
- },
125
- };
126
-
127
- return component;
128
- });
129
- },
130
- });
131
-
132
- // Restore state on session start
133
- pi.on("session_start", async (_event, ctx) => {
134
- restoreFromBranch(ctx);
135
- });
136
-
137
- // Restore state when navigating the session tree
138
- pi.on("session_tree", async (_event, ctx) => {
139
- restoreFromBranch(ctx);
140
- });
141
- }
@@ -1,50 +0,0 @@
1
- import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
2
-
3
- const COMPACT_THRESHOLD_TOKENS = 100_000;
4
-
5
- export default function (pi: ExtensionAPI) {
6
- let previousTokens: number | null | undefined;
7
-
8
- const triggerCompaction = (ctx: ExtensionContext, customInstructions?: string) => {
9
- if (ctx.hasUI) {
10
- ctx.ui.notify("Compaction started", "info");
11
- }
12
- ctx.compact({
13
- customInstructions,
14
- onComplete: () => {
15
- if (ctx.hasUI) {
16
- ctx.ui.notify("Compaction completed", "info");
17
- }
18
- },
19
- onError: (error) => {
20
- if (ctx.hasUI) {
21
- ctx.ui.notify(`Compaction failed: ${error.message}`, "error");
22
- }
23
- },
24
- });
25
- };
26
-
27
- pi.on("turn_end", (_event, ctx) => {
28
- const usage = ctx.getContextUsage();
29
- const currentTokens = usage?.tokens ?? null;
30
- if (currentTokens === null) {
31
- return;
32
- }
33
-
34
- const crossedThreshold =
35
- previousTokens !== undefined && previousTokens !== null && previousTokens <= COMPACT_THRESHOLD_TOKENS;
36
- previousTokens = currentTokens;
37
- if (!crossedThreshold || currentTokens <= COMPACT_THRESHOLD_TOKENS) {
38
- return;
39
- }
40
- triggerCompaction(ctx);
41
- });
42
-
43
- pi.registerCommand("trigger-compact", {
44
- description: "Trigger compaction immediately",
45
- handler: async (args, ctx) => {
46
- const instructions = args.trim() || undefined;
47
- triggerCompaction(ctx, instructions);
48
- },
49
- });
50
- }
@@ -1,195 +0,0 @@
1
- /**
2
- * Truncated Tool Example - Demonstrates proper output truncation for custom tools
3
- *
4
- * Custom tools MUST truncate their output to avoid overwhelming the LLM context.
5
- * The built-in limit is 50KB (~10k tokens) and 2000 lines, whichever is hit first.
6
- *
7
- * This example shows how to:
8
- * 1. Use the built-in truncation utilities
9
- * 2. Write full output to a temp file when truncated
10
- * 3. Inform the LLM where to find the complete output
11
- * 4. Custom rendering of tool calls and results
12
- *
13
- * The `rg` tool here wraps ripgrep with proper truncation. Compare this to the
14
- * built-in `grep` tool in src/core/tools/grep.ts for a more complete implementation.
15
- */
16
-
17
- import { mkdtemp, writeFile } from "node:fs/promises";
18
- import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
19
- import {
20
- DEFAULT_MAX_BYTES,
21
- DEFAULT_MAX_LINES,
22
- formatSize,
23
- type TruncationResult,
24
- truncateHead,
25
- withFileMutationQueue,
26
- } from "@mariozechner/pi-coding-agent";
27
- import { Text } from "@mariozechner/pi-tui";
28
- import { Type } from "@sinclair/typebox";
29
- import { execSync } from "child_process";
30
- import { tmpdir } from "os";
31
- import { join } from "path";
32
-
33
- const RgParams = Type.Object({
34
- pattern: Type.String({ description: "Search pattern (regex)" }),
35
- path: Type.Optional(Type.String({ description: "Directory to search (default: current directory)" })),
36
- glob: Type.Optional(Type.String({ description: "File glob pattern, e.g. '*.ts'" })),
37
- });
38
-
39
- interface RgDetails {
40
- pattern: string;
41
- path?: string;
42
- glob?: string;
43
- matchCount: number;
44
- truncation?: TruncationResult;
45
- fullOutputPath?: string;
46
- }
47
-
48
- export default function (pi: ExtensionAPI) {
49
- pi.registerTool({
50
- name: "rg",
51
- label: "ripgrep",
52
- // Document the truncation limits in the tool description so the LLM knows
53
- description: `Search file contents using ripgrep. Output is truncated to ${DEFAULT_MAX_LINES} lines or ${formatSize(DEFAULT_MAX_BYTES)} (whichever is hit first). If truncated, full output is saved to a temp file.`,
54
- parameters: RgParams,
55
-
56
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
57
- const { pattern, path: searchPath, glob } = params;
58
-
59
- // Build the ripgrep command
60
- const args = ["rg", "--line-number", "--color=never"];
61
- if (glob) args.push("--glob", glob);
62
- args.push(pattern);
63
- args.push(searchPath || ".");
64
-
65
- let output: string;
66
- try {
67
- output = execSync(args.join(" "), {
68
- cwd: ctx.cwd,
69
- encoding: "utf-8",
70
- maxBuffer: 100 * 1024 * 1024, // 100MB buffer to capture full output
71
- });
72
- } catch (err: any) {
73
- // ripgrep exits with 1 when no matches found
74
- if (err.status === 1) {
75
- return {
76
- content: [{ type: "text", text: "No matches found" }],
77
- details: { pattern, path: searchPath, glob, matchCount: 0 } as RgDetails,
78
- };
79
- }
80
- throw new Error(`ripgrep failed: ${err.message}`);
81
- }
82
-
83
- if (!output.trim()) {
84
- return {
85
- content: [{ type: "text", text: "No matches found" }],
86
- details: { pattern, path: searchPath, glob, matchCount: 0 } as RgDetails,
87
- };
88
- }
89
-
90
- // Apply truncation using built-in utilities
91
- // truncateHead keeps the first N lines/bytes (good for search results)
92
- // truncateTail keeps the last N lines/bytes (good for logs/command output)
93
- const truncation = truncateHead(output, {
94
- maxLines: DEFAULT_MAX_LINES,
95
- maxBytes: DEFAULT_MAX_BYTES,
96
- });
97
-
98
- // Count matches (each non-empty line with a match)
99
- const matchCount = output.split("\n").filter((line) => line.trim()).length;
100
-
101
- const details: RgDetails = {
102
- pattern,
103
- path: searchPath,
104
- glob,
105
- matchCount,
106
- };
107
-
108
- let resultText = truncation.content;
109
-
110
- if (truncation.truncated) {
111
- // Save full output to a temp file so LLM can access it if needed
112
- const tempDir = await mkdtemp(join(tmpdir(), "pi-rg-"));
113
- const tempFile = join(tempDir, "output.txt");
114
- await withFileMutationQueue(tempFile, async () => {
115
- await writeFile(tempFile, output, "utf8");
116
- });
117
-
118
- details.truncation = truncation;
119
- details.fullOutputPath = tempFile;
120
-
121
- // Add truncation notice - this helps the LLM understand the output is incomplete
122
- const truncatedLines = truncation.totalLines - truncation.outputLines;
123
- const truncatedBytes = truncation.totalBytes - truncation.outputBytes;
124
-
125
- resultText += `\n\n[Output truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`;
126
- resultText += ` (${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)}).`;
127
- resultText += ` ${truncatedLines} lines (${formatSize(truncatedBytes)}) omitted.`;
128
- resultText += ` Full output saved to: ${tempFile}]`;
129
- }
130
-
131
- return {
132
- content: [{ type: "text", text: resultText }],
133
- details,
134
- };
135
- },
136
-
137
- // Custom rendering of the tool call (shown before/during execution)
138
- renderCall(args, theme, _context) {
139
- let text = theme.fg("toolTitle", theme.bold("rg "));
140
- text += theme.fg("accent", `"${args.pattern}"`);
141
- if (args.path) {
142
- text += theme.fg("muted", ` in ${args.path}`);
143
- }
144
- if (args.glob) {
145
- text += theme.fg("dim", ` --glob ${args.glob}`);
146
- }
147
- return new Text(text, 0, 0);
148
- },
149
-
150
- // Custom rendering of the tool result
151
- renderResult(result, { expanded, isPartial }, theme, _context) {
152
- const details = result.details as RgDetails | undefined;
153
-
154
- // Handle streaming/partial results
155
- if (isPartial) {
156
- return new Text(theme.fg("warning", "Searching..."), 0, 0);
157
- }
158
-
159
- // No matches
160
- if (!details || details.matchCount === 0) {
161
- return new Text(theme.fg("dim", "No matches found"), 0, 0);
162
- }
163
-
164
- // Build result display
165
- let text = theme.fg("success", `${details.matchCount} matches`);
166
-
167
- // Show truncation warning if applicable
168
- if (details.truncation?.truncated) {
169
- text += theme.fg("warning", " (truncated)");
170
- }
171
-
172
- // In expanded view, show the actual matches
173
- if (expanded) {
174
- const content = result.content[0];
175
- if (content?.type === "text") {
176
- // Show first 20 lines in expanded view, or all if fewer
177
- const lines = content.text.split("\n").slice(0, 20);
178
- for (const line of lines) {
179
- text += `\n${theme.fg("dim", line)}`;
180
- }
181
- if (content.text.split("\n").length > 20) {
182
- text += `\n${theme.fg("muted", "... (use read tool to see full output)")}`;
183
- }
184
- }
185
-
186
- // Show temp file path if truncated
187
- if (details.fullOutputPath) {
188
- text += `\n${theme.fg("dim", `Full output: ${details.fullOutputPath}`)}`;
189
- }
190
- }
191
-
192
- return new Text(text, 0, 0);
193
- },
194
- });
195
- }
@@ -1,9 +0,0 @@
1
- import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
2
-
3
- export default function widgetPlacementExtension(pi: ExtensionAPI) {
4
- pi.on("session_start", (_event, ctx) => {
5
- if (!ctx.hasUI) return;
6
- ctx.ui.setWidget("widget-above", ["Above editor widget"]);
7
- ctx.ui.setWidget("widget-below", ["Below editor widget"], { placement: "belowEditor" });
8
- });
9
- }
@@ -1,32 +0,0 @@
1
- /**
2
- * Example extension with its own npm dependencies.
3
- * Tests that jiti resolves modules from the extension's own node_modules.
4
- *
5
- * Requires: npm install in this directory
6
- */
7
-
8
- import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
9
- import { Type } from "@sinclair/typebox";
10
- import ms from "ms";
11
-
12
- export default function (pi: ExtensionAPI) {
13
- // Register a tool that uses ms
14
- pi.registerTool({
15
- name: "parse_duration",
16
- label: "Parse Duration",
17
- description: "Parse a human-readable duration string (e.g., '2 days', '1h', '5m') to milliseconds",
18
- parameters: Type.Object({
19
- duration: Type.String({ description: "Duration string like '2 days', '1h', '5m'" }),
20
- }),
21
- execute: async (_toolCallId, params) => {
22
- const result = ms(params.duration as ms.StringValue);
23
- if (result === undefined) {
24
- throw new Error(`Invalid duration: "${params.duration}"`);
25
- }
26
- return {
27
- content: [{ type: "text", text: `${params.duration} = ${result} milliseconds` }],
28
- details: {},
29
- };
30
- },
31
- });
32
- }
@@ -1,31 +0,0 @@
1
- {
2
- "name": "pi-extension-with-deps",
3
- "version": "1.28.0",
4
- "lockfileVersion": 3,
5
- "requires": true,
6
- "packages": {
7
- "": {
8
- "name": "pi-extension-with-deps",
9
- "version": "1.28.0",
10
- "dependencies": {
11
- "ms": "^2.1.3"
12
- },
13
- "devDependencies": {
14
- "@types/ms": "^2.1.0"
15
- }
16
- },
17
- "node_modules/@types/ms": {
18
- "version": "2.1.0",
19
- "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",
20
- "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
21
- "dev": true,
22
- "license": "MIT"
23
- },
24
- "node_modules/ms": {
25
- "version": "2.1.3",
26
- "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
27
- "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
28
- "license": "MIT"
29
- }
30
- }
31
- }
@@ -1,22 +0,0 @@
1
- {
2
- "name": "pi-extension-with-deps",
3
- "private": true,
4
- "version": "1.28.0",
5
- "type": "module",
6
- "scripts": {
7
- "clean": "echo 'nothing to clean'",
8
- "build": "echo 'nothing to build'",
9
- "check": "echo 'nothing to check'"
10
- },
11
- "pi": {
12
- "extensions": [
13
- "./index.ts"
14
- ]
15
- },
16
- "dependencies": {
17
- "ms": "^2.1.3"
18
- },
19
- "devDependencies": {
20
- "@types/ms": "^2.1.0"
21
- }
22
- }