@oh-my-pi/pi-coding-agent 3.20.1 → 3.24.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 (123) hide show
  1. package/CHANGELOG.md +107 -8
  2. package/docs/custom-tools.md +3 -3
  3. package/docs/extensions.md +226 -220
  4. package/docs/hooks.md +2 -2
  5. package/docs/sdk.md +50 -53
  6. package/examples/custom-tools/README.md +2 -17
  7. package/examples/extensions/README.md +76 -74
  8. package/examples/extensions/todo.ts +2 -5
  9. package/examples/hooks/custom-compaction.ts +2 -4
  10. package/examples/hooks/handoff.ts +1 -1
  11. package/examples/hooks/qna.ts +1 -1
  12. package/examples/sdk/02-custom-model.ts +1 -1
  13. package/examples/sdk/README.md +7 -11
  14. package/package.json +6 -6
  15. package/src/cli/args.ts +9 -6
  16. package/src/cli/file-processor.ts +1 -1
  17. package/src/cli/list-models.ts +1 -1
  18. package/src/core/agent-session.ts +16 -5
  19. package/src/core/auth-storage.ts +1 -1
  20. package/src/core/compaction/branch-summarization.ts +2 -2
  21. package/src/core/compaction/compaction.ts +2 -2
  22. package/src/core/compaction/utils.ts +1 -1
  23. package/src/core/custom-tools/types.ts +1 -1
  24. package/src/core/custom-tools/wrapper.ts +0 -1
  25. package/src/core/extensions/index.ts +1 -6
  26. package/src/core/extensions/runner.ts +1 -1
  27. package/src/core/extensions/types.ts +1 -1
  28. package/src/core/extensions/wrapper.ts +1 -8
  29. package/src/core/file-mentions.ts +5 -8
  30. package/src/core/hooks/runner.ts +2 -2
  31. package/src/core/hooks/types.ts +1 -1
  32. package/src/core/messages.ts +1 -1
  33. package/src/core/model-registry.ts +1 -1
  34. package/src/core/model-resolver.ts +1 -1
  35. package/src/core/sdk.ts +64 -105
  36. package/src/core/session-manager.ts +18 -22
  37. package/src/core/settings-manager.ts +66 -1
  38. package/src/core/slash-commands.ts +12 -5
  39. package/src/core/system-prompt.ts +49 -36
  40. package/src/core/title-generator.ts +2 -2
  41. package/src/core/tools/ask.ts +98 -4
  42. package/src/core/tools/bash-interceptor.ts +11 -4
  43. package/src/core/tools/bash.ts +121 -5
  44. package/src/core/tools/context.ts +7 -0
  45. package/src/core/tools/edit-diff.ts +73 -24
  46. package/src/core/tools/edit.ts +221 -34
  47. package/src/core/tools/exa/render.ts +4 -16
  48. package/src/core/tools/find.ts +149 -5
  49. package/src/core/tools/gemini-image.ts +279 -56
  50. package/src/core/tools/git.ts +17 -3
  51. package/src/core/tools/grep.ts +185 -5
  52. package/src/core/tools/index.test.ts +180 -0
  53. package/src/core/tools/index.ts +96 -242
  54. package/src/core/tools/ls.ts +133 -5
  55. package/src/core/tools/lsp/index.ts +32 -29
  56. package/src/core/tools/lsp/render.ts +21 -22
  57. package/src/core/tools/notebook.ts +112 -4
  58. package/src/core/tools/output.ts +175 -15
  59. package/src/core/tools/read.ts +127 -25
  60. package/src/core/tools/render-utils.ts +241 -0
  61. package/src/core/tools/renderers.ts +40 -828
  62. package/src/core/tools/review.ts +26 -25
  63. package/src/core/tools/rulebook.ts +11 -3
  64. package/src/core/tools/task/agents.ts +28 -7
  65. package/src/core/tools/task/discovery.ts +0 -6
  66. package/src/core/tools/task/executor.ts +264 -254
  67. package/src/core/tools/task/index.ts +48 -208
  68. package/src/core/tools/task/render.ts +26 -11
  69. package/src/core/tools/task/types.ts +7 -12
  70. package/src/core/tools/task/worker-protocol.ts +17 -0
  71. package/src/core/tools/task/worker.ts +238 -0
  72. package/src/core/tools/truncate.ts +27 -1
  73. package/src/core/tools/web-fetch.ts +25 -49
  74. package/src/core/tools/web-search/index.ts +132 -46
  75. package/src/core/tools/web-search/providers/anthropic.ts +7 -2
  76. package/src/core/tools/web-search/providers/exa.ts +2 -1
  77. package/src/core/tools/web-search/providers/perplexity.ts +6 -1
  78. package/src/core/tools/web-search/render.ts +6 -4
  79. package/src/core/tools/web-search/types.ts +13 -0
  80. package/src/core/tools/write.ts +96 -14
  81. package/src/core/voice.ts +1 -1
  82. package/src/discovery/helpers.test.ts +1 -1
  83. package/src/index.ts +5 -16
  84. package/src/main.ts +5 -5
  85. package/src/modes/interactive/components/assistant-message.ts +1 -1
  86. package/src/modes/interactive/components/custom-message.ts +1 -1
  87. package/src/modes/interactive/components/extensions/inspector-panel.ts +25 -22
  88. package/src/modes/interactive/components/extensions/state-manager.ts +12 -0
  89. package/src/modes/interactive/components/footer.ts +1 -1
  90. package/src/modes/interactive/components/hook-message.ts +1 -1
  91. package/src/modes/interactive/components/model-selector.ts +1 -1
  92. package/src/modes/interactive/components/oauth-selector.ts +1 -1
  93. package/src/modes/interactive/components/settings-defs.ts +49 -0
  94. package/src/modes/interactive/components/status-line.ts +1 -1
  95. package/src/modes/interactive/components/tool-execution.ts +93 -538
  96. package/src/modes/interactive/interactive-mode.ts +19 -7
  97. package/src/modes/interactive/theme/theme.ts +4 -4
  98. package/src/modes/print-mode.ts +1 -1
  99. package/src/modes/rpc/rpc-client.ts +1 -1
  100. package/src/modes/rpc/rpc-types.ts +1 -1
  101. package/src/prompts/system-prompt.md +4 -0
  102. package/src/prompts/task.md +0 -7
  103. package/src/prompts/tools/gemini-image.md +5 -1
  104. package/src/prompts/tools/output.md +6 -2
  105. package/src/prompts/tools/task.md +68 -0
  106. package/src/prompts/tools/web-fetch.md +1 -0
  107. package/src/prompts/tools/web-search.md +2 -0
  108. package/src/utils/image-convert.ts +8 -2
  109. package/src/utils/image-magick.ts +247 -0
  110. package/src/utils/image-resize.ts +53 -13
  111. package/examples/custom-tools/question/index.ts +0 -84
  112. package/examples/custom-tools/subagent/README.md +0 -172
  113. package/examples/custom-tools/subagent/agents/planner.md +0 -37
  114. package/examples/custom-tools/subagent/agents/scout.md +0 -50
  115. package/examples/custom-tools/subagent/agents/worker.md +0 -24
  116. package/examples/custom-tools/subagent/agents.ts +0 -156
  117. package/examples/custom-tools/subagent/commands/implement-and-review.md +0 -10
  118. package/examples/custom-tools/subagent/commands/implement.md +0 -10
  119. package/examples/custom-tools/subagent/commands/scout-and-plan.md +0 -9
  120. package/examples/custom-tools/subagent/index.ts +0 -1002
  121. package/examples/sdk/05-tools.ts +0 -94
  122. package/examples/sdk/12-full-control.ts +0 -95
  123. package/src/prompts/browser.md +0 -71
@@ -7,6 +7,7 @@ import { type Theme, theme } from "../../../modes/interactive/theme/theme";
7
7
  import lspDescription from "../../../prompts/tools/lsp.md" with { type: "text" };
8
8
  import { logger } from "../../logger";
9
9
  import { once, untilAborted } from "../../utils";
10
+ import type { ToolSession } from "../index";
10
11
  import { resolveToCwd } from "../path-utils";
11
12
  import {
12
13
  ensureFileOpen,
@@ -687,7 +688,7 @@ export function createLspWritethrough(cwd: string, options?: WritethroughOptions
687
688
  }
688
689
 
689
690
  /** Create an LSP tool */
690
- export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolDetails, Theme> {
691
+ export function createLspTool(session: ToolSession): AgentTool<typeof lspSchema, LspToolDetails, Theme> {
691
692
  return {
692
693
  name: "lsp",
693
694
  label: "LSP",
@@ -713,7 +714,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
713
714
  include_declaration,
714
715
  } = params;
715
716
 
716
- const config = await getConfig(cwd);
717
+ const config = await getConfig(session.cwd);
717
718
 
718
719
  // Status action doesn't need a file
719
720
  if (action === "status") {
@@ -730,7 +731,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
730
731
 
731
732
  // Workspace diagnostics - check entire project
732
733
  if (action === "workspace_diagnostics") {
733
- const result = await runWorkspaceDiagnostics(cwd, config);
734
+ const result = await runWorkspaceDiagnostics(session.cwd, config);
734
735
  return {
735
736
  content: [
736
737
  {
@@ -757,7 +758,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
757
758
  const allServerNames = new Set<string>();
758
759
 
759
760
  for (const target of targets) {
760
- const resolved = resolveToCwd(target, cwd);
761
+ const resolved = resolveToCwd(target, session.cwd);
761
762
  const servers = getServersForFile(config, resolved);
762
763
  if (servers.length === 0) {
763
764
  results.push(`${theme.status.error} ${target}: No language server found`);
@@ -765,7 +766,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
765
766
  }
766
767
 
767
768
  const uri = fileToUri(resolved);
768
- const relPath = path.relative(cwd, resolved);
769
+ const relPath = path.relative(session.cwd, resolved);
769
770
  const allDiagnostics: Diagnostic[] = [];
770
771
 
771
772
  // Query all applicable servers for this file
@@ -773,12 +774,12 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
773
774
  allServerNames.add(serverName);
774
775
  try {
775
776
  if (serverConfig.createClient) {
776
- const linterClient = getLinterClient(serverName, serverConfig, cwd);
777
+ const linterClient = getLinterClient(serverName, serverConfig, session.cwd);
777
778
  const diagnostics = await linterClient.lint(resolved);
778
779
  allDiagnostics.push(...diagnostics);
779
780
  continue;
780
781
  }
781
- const client = await getOrCreateClient(serverConfig, cwd);
782
+ const client = await getOrCreateClient(serverConfig, session.cwd);
782
783
  await refreshFile(client, resolved);
783
784
  const diagnostics = await waitForDiagnostics(client, uri);
784
785
  allDiagnostics.push(...diagnostics);
@@ -847,7 +848,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
847
848
  };
848
849
  }
849
850
 
850
- const resolvedFile = file ? resolveToCwd(file, cwd) : null;
851
+ const resolvedFile = file ? resolveToCwd(file, session.cwd) : null;
851
852
  const serverInfo = resolvedFile
852
853
  ? getLspServerForFile(config, resolvedFile)
853
854
  : getServerForWorkspaceAction(config, action);
@@ -862,10 +863,10 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
862
863
  const [serverName, serverConfig] = serverInfo;
863
864
 
864
865
  try {
865
- const client = await getOrCreateClient(serverConfig, cwd);
866
+ const client = await getOrCreateClient(serverConfig, session.cwd);
866
867
  let targetFile = resolvedFile;
867
868
  if (action === "runnables" && !targetFile) {
868
- targetFile = findFileForServer(cwd, serverConfig);
869
+ targetFile = findFileForServer(session.cwd, serverConfig);
869
870
  if (!targetFile) {
870
871
  return {
871
872
  content: [{ type: "text", text: "Error: no matching files found for runnables" }],
@@ -914,7 +915,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
914
915
  output = "No definition found";
915
916
  } else {
916
917
  output = `Found ${locations.length} definition(s):\n${locations
917
- .map((loc) => ` ${formatLocation(loc, cwd)}`)
918
+ .map((loc) => ` ${formatLocation(loc, session.cwd)}`)
918
919
  .join("\n")}`;
919
920
  }
920
921
  }
@@ -931,7 +932,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
931
932
  if (!result || result.length === 0) {
932
933
  output = "No references found";
933
934
  } else {
934
- const lines = result.map((loc) => ` ${formatLocation(loc, cwd)}`);
935
+ const lines = result.map((loc) => ` ${formatLocation(loc, session.cwd)}`);
935
936
  output = `Found ${result.length} reference(s):\n${lines.join("\n")}`;
936
937
  }
937
938
  break;
@@ -964,7 +965,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
964
965
  details: { action, serverName, success: false },
965
966
  };
966
967
  } else {
967
- const relPath = path.relative(cwd, targetFile);
968
+ const relPath = path.relative(session.cwd, targetFile);
968
969
  // Check if hierarchical (DocumentSymbol) or flat (SymbolInformation)
969
970
  if ("selectionRange" in result[0]) {
970
971
  // Hierarchical
@@ -998,10 +999,8 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
998
999
  if (!result || result.length === 0) {
999
1000
  output = `No symbols matching "${query}"`;
1000
1001
  } else {
1001
- const lines = result.map((s) => formatSymbolInformation(s, cwd));
1002
- output = `Found ${result.length} symbol(s) matching "${query}":\n${lines
1003
- .map((l) => ` ${l}`)
1004
- .join("\n")}`;
1002
+ const lines = result.map((s) => formatSymbolInformation(s, session.cwd));
1003
+ output = `Found ${result.length} symbol(s) matching "${query}":\n${lines.map((l) => ` ${l}`).join("\n")}`;
1005
1004
  }
1006
1005
  break;
1007
1006
  }
@@ -1025,10 +1024,10 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
1025
1024
  } else {
1026
1025
  const shouldApply = apply !== false;
1027
1026
  if (shouldApply) {
1028
- const applied = await applyWorkspaceEdit(result, cwd);
1027
+ const applied = await applyWorkspaceEdit(result, session.cwd);
1029
1028
  output = `Applied rename:\n${applied.map((a) => ` ${a}`).join("\n")}`;
1030
1029
  } else {
1031
- const preview = formatWorkspaceEdit(result, cwd);
1030
+ const preview = formatWorkspaceEdit(result, session.cwd);
1032
1031
  output = `Rename preview:\n${preview.map((p) => ` ${p}`).join("\n")}`;
1033
1032
  }
1034
1033
  }
@@ -1114,7 +1113,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
1114
1113
  }
1115
1114
 
1116
1115
  if (isCodeAction(resolvedAction) && resolvedAction.edit) {
1117
- const applied = await applyWorkspaceEdit(resolvedAction.edit, cwd);
1116
+ const applied = await applyWorkspaceEdit(resolvedAction.edit, session.cwd);
1118
1117
  output = `Applied "${codeAction.title}":\n${applied.map((a) => ` ${a}`).join("\n")}`;
1119
1118
  } else {
1120
1119
  const commandPayload = getCommandPayload(resolvedAction);
@@ -1136,9 +1135,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
1136
1135
  }
1137
1136
  return ` [${i}] ${actionItem.title}`;
1138
1137
  });
1139
- output = `Available code actions:\n${lines.join(
1140
- "\n",
1141
- )}\n\nUse action_index parameter to apply a specific action.`;
1138
+ output = `Available code actions:\n${lines.join("\n")}\n\nUse action_index parameter to apply a specific action.`;
1142
1139
  }
1143
1140
  break;
1144
1141
  }
@@ -1169,7 +1166,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
1169
1166
  const lines = calls.map((call) => {
1170
1167
  const loc = { uri: call.from.uri, range: call.from.selectionRange };
1171
1168
  const detail = call.from.detail ? ` (${call.from.detail})` : "";
1172
- return ` ${call.from.name}${detail} @ ${formatLocation(loc, cwd)}`;
1169
+ return ` ${call.from.name}${detail} @ ${formatLocation(loc, session.cwd)}`;
1173
1170
  });
1174
1171
  output = `Found ${calls.length} caller(s) of "${item.name}":\n${lines.join("\n")}`;
1175
1172
  }
@@ -1184,7 +1181,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
1184
1181
  const lines = calls.map((call) => {
1185
1182
  const loc = { uri: call.to.uri, range: call.to.selectionRange };
1186
1183
  const detail = call.to.detail ? ` (${call.to.detail})` : "";
1187
- return ` ${call.to.name}${detail} @ ${formatLocation(loc, cwd)}`;
1184
+ return ` ${call.to.name}${detail} @ ${formatLocation(loc, session.cwd)}`;
1188
1185
  });
1189
1186
  output = `"${item.name}" calls ${calls.length} function(s):\n${lines.join("\n")}`;
1190
1187
  }
@@ -1207,7 +1204,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
1207
1204
  await rustAnalyzer.flycheck(client, resolvedFile ?? undefined);
1208
1205
  const collected: Array<{ filePath: string; diagnostic: Diagnostic }> = [];
1209
1206
  for (const [diagUri, diags] of client.diagnostics.entries()) {
1210
- const relPath = path.relative(cwd, uriToFile(diagUri));
1207
+ const relPath = path.relative(session.cwd, uriToFile(diagUri));
1211
1208
  for (const diag of diags) {
1212
1209
  collected.push({ filePath: relPath, diagnostic: diag });
1213
1210
  }
@@ -1274,13 +1271,13 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
1274
1271
  const result = await rustAnalyzer.ssr(client, query, replacement, !shouldApply);
1275
1272
 
1276
1273
  if (shouldApply) {
1277
- const applied = await applyWorkspaceEdit(result, cwd);
1274
+ const applied = await applyWorkspaceEdit(result, session.cwd);
1278
1275
  output =
1279
1276
  applied.length > 0
1280
1277
  ? `Applied SSR:\n${applied.map((a) => ` ${a}`).join("\n")}`
1281
1278
  : "SSR: no matches found";
1282
1279
  } else {
1283
- const preview = formatWorkspaceEdit(result, cwd);
1280
+ const preview = formatWorkspaceEdit(result, session.cwd);
1284
1281
  output =
1285
1282
  preview.length > 0
1286
1283
  ? `SSR preview:\n${preview.map((p) => ` ${p}`).join("\n")}`
@@ -1366,4 +1363,10 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
1366
1363
  };
1367
1364
  }
1368
1365
 
1369
- export const lspTool = createLspTool(process.cwd());
1366
+ export const lspTool = createLspTool({
1367
+ cwd: process.cwd(),
1368
+ hasUI: false,
1369
+ rulebookRules: [],
1370
+ getSessionFile: () => null,
1371
+ getSessionSpawns: () => null,
1372
+ });
@@ -237,12 +237,12 @@ function renderDiagnostics(
237
237
  }
238
238
  const severityColor = severityToColor(item.severity);
239
239
  const location = formatDiagnosticLocation(item.file, item.line, item.col, theme);
240
- output += `\n ${theme.fg("dim", branch)} ${theme.fg(severityColor, location)} ${theme.fg(
241
- "dim",
242
- `[${item.severity}]`,
243
- )}`;
240
+ output += `\n ${theme.fg("dim", branch)} ${theme.fg(severityColor, location)} ${theme.fg("dim", `[${item.severity}]`)}`;
244
241
  if (item.message) {
245
- output += `\n ${theme.fg("dim", detailPrefix)}${theme.fg("muted", truncate(item.message, TRUNCATE_LENGTHS.LINE, theme.format.ellipsis))}`;
242
+ output += `\n ${theme.fg("dim", detailPrefix)}${theme.fg(
243
+ "muted",
244
+ truncate(item.message, TRUNCATE_LENGTHS.LINE, theme.format.ellipsis),
245
+ )}`;
246
246
  }
247
247
  }
248
248
  return new Text(output, 0, 0);
@@ -326,10 +326,7 @@ function renderReferences(refMatch: RegExpMatchArray, lines: string[], expanded:
326
326
  const isLastLoc = li === locsToShow.length - 1 && locs.length <= maxLocsPerFile;
327
327
  const locBranch = isLastLoc ? theme.tree.last : theme.tree.branch;
328
328
  const locCont = isLastLoc ? " " : `${theme.tree.vertical} `;
329
- output += `\n ${theme.fg("dim", fileCont)}${theme.fg("dim", locBranch)} ${theme.fg(
330
- "muted",
331
- `line ${line}, col ${col}`,
332
- )}`;
329
+ output += `\n ${theme.fg("dim", fileCont)}${theme.fg("dim", locBranch)} ${theme.fg("muted", `line ${line}, col ${col}`)}`;
333
330
  if (expanded) {
334
331
  const context = `at ${file}:${line}:${col}`;
335
332
  output += `\n ${theme.fg("dim", fileCont)}${theme.fg("dim", locCont)}${theme.fg(
@@ -348,10 +345,7 @@ function renderReferences(refMatch: RegExpMatchArray, lines: string[], expanded:
348
345
  }
349
346
 
350
347
  if (files.length > maxFiles) {
351
- output += `\n ${theme.fg("dim", theme.tree.last)} ${theme.fg(
352
- "muted",
353
- formatMoreItems(files.length - maxFiles, "file", theme),
354
- )}`;
348
+ output += `\n ${theme.fg("dim", theme.tree.last)} ${theme.fg("muted", formatMoreItems(files.length - maxFiles, "file", theme))}`;
355
349
  }
356
350
 
357
351
  return output;
@@ -436,10 +430,7 @@ function renderSymbols(symbolsMatch: RegExpMatchArray, lines: string[], expanded
436
430
  const isLast = isLastSibling(i);
437
431
  const branch = isLast ? theme.tree.last : theme.tree.branch;
438
432
  const detailPrefix = isLast ? " " : `${theme.tree.vertical} `;
439
- output += `\n${prefix}${theme.fg("dim", branch)} ${theme.fg("accent", sym.icon)} ${theme.fg(
440
- "accent",
441
- sym.name,
442
- )}`;
433
+ output += `\n${prefix}${theme.fg("dim", branch)} ${theme.fg("accent", sym.icon)} ${theme.fg("accent", sym.name)}`;
443
434
  output += `\n${prefix}${theme.fg("dim", detailPrefix)}${theme.fg("muted", `line ${sym.line}`)}`;
444
435
  }
445
436
  return new Text(output, 0, 0);
@@ -454,10 +445,10 @@ function renderSymbols(symbolsMatch: RegExpMatchArray, lines: string[], expanded
454
445
  const sym = topLevel[i];
455
446
  const isLast = i === topLevel.length - 1 && topLevelCount <= 3;
456
447
  const branch = isLast ? theme.tree.last : theme.tree.branch;
457
- output += `\n ${theme.fg("dim", branch)} ${theme.fg("accent", sym.icon)} ${theme.fg(
458
- "accent",
459
- sym.name,
460
- )} ${theme.fg("muted", `line ${sym.line}`)}`;
448
+ output += `\n ${theme.fg("dim", branch)} ${theme.fg("accent", sym.icon)} ${theme.fg("accent", sym.name)} ${theme.fg(
449
+ "muted",
450
+ `line ${sym.line}`,
451
+ )}`;
461
452
  }
462
453
  if (topLevelCount > 3) {
463
454
  output += `\n ${theme.fg("dim", theme.tree.last)} ${theme.fg("muted", `${theme.format.ellipsis} ${topLevelCount - 3} more`)}`;
@@ -503,7 +494,10 @@ function renderGeneric(text: string, lines: string[], expanded: boolean, theme:
503
494
  for (let i = 0; i < previewLines.length; i++) {
504
495
  const isLast = i === previewLines.length - 1 && lines.length <= 4;
505
496
  const branch = isLast ? theme.tree.last : theme.tree.branch;
506
- output += `\n ${theme.fg("dim", branch)} ${theme.fg("dim", truncate(previewLines[i].trim(), TRUNCATE_LENGTHS.CONTENT, theme.format.ellipsis))}`;
497
+ output += `\n ${theme.fg("dim", branch)} ${theme.fg(
498
+ "dim",
499
+ truncate(previewLines[i].trim(), TRUNCATE_LENGTHS.CONTENT, theme.format.ellipsis),
500
+ )}`;
507
501
  }
508
502
  if (lines.length > 4) {
509
503
  output += `\n ${theme.fg("dim", theme.tree.last)} ${theme.fg("muted", formatMoreItems(lines.length - 4, "line", theme))}`;
@@ -550,3 +544,8 @@ function severityToColor(severity: string): "error" | "warning" | "accent" | "di
550
544
  return "dim";
551
545
  }
552
546
  }
547
+
548
+ export const lspToolRenderer = {
549
+ renderCall,
550
+ renderResult,
551
+ };
@@ -1,7 +1,20 @@
1
1
  import type { AgentTool } from "@oh-my-pi/pi-agent-core";
2
+ import type { Component } from "@oh-my-pi/pi-tui";
3
+ import { Text } from "@oh-my-pi/pi-tui";
2
4
  import { Type } from "@sinclair/typebox";
5
+ import type { Theme } from "../../modes/interactive/theme/theme";
6
+ import type { RenderResultOptions } from "../custom-tools/types";
7
+ import type { ToolSession } from "../sdk";
3
8
  import { untilAborted } from "../utils";
4
9
  import { resolveToCwd } from "./path-utils";
10
+ import {
11
+ formatCount,
12
+ formatErrorMessage,
13
+ formatExpandHint,
14
+ formatMeta,
15
+ formatMoreItems,
16
+ PREVIEW_LIMITS,
17
+ } from "./render-utils";
5
18
 
6
19
  const notebookSchema = Type.Object({
7
20
  action: Type.Union([Type.Literal("edit"), Type.Literal("insert"), Type.Literal("delete")], {
@@ -49,7 +62,7 @@ function splitIntoLines(content: string): string[] {
49
62
  return content.split("\n").map((line, i, arr) => (i < arr.length - 1 ? `${line}\n` : line));
50
63
  }
51
64
 
52
- export function createNotebookTool(cwd: string): AgentTool<typeof notebookSchema> {
65
+ export function createNotebookTool(session: ToolSession): AgentTool<typeof notebookSchema> {
53
66
  return {
54
67
  name: "notebook",
55
68
  label: "Notebook",
@@ -67,7 +80,7 @@ export function createNotebookTool(cwd: string): AgentTool<typeof notebookSchema
67
80
  }: { action: string; notebook_path: string; cell_index: number; content?: string; cell_type?: string },
68
81
  signal?: AbortSignal,
69
82
  ) => {
70
- const absolutePath = resolveToCwd(notebook_path, cwd);
83
+ const absolutePath = resolveToCwd(notebook_path, session.cwd);
71
84
 
72
85
  return untilAborted(signal, async () => {
73
86
  // Check if file exists
@@ -178,5 +191,100 @@ export function createNotebookTool(cwd: string): AgentTool<typeof notebookSchema
178
191
  };
179
192
  }
180
193
 
181
- /** Default notebook tool using process.cwd() */
182
- export const notebookTool = createNotebookTool(process.cwd());
194
+ // =============================================================================
195
+ // TUI Renderer
196
+ // =============================================================================
197
+
198
+ interface NotebookRenderArgs {
199
+ action: string;
200
+ notebookPath: string;
201
+ cellNumber?: number;
202
+ cellType?: string;
203
+ content?: string;
204
+ }
205
+
206
+ const COLLAPSED_TEXT_LIMIT = PREVIEW_LIMITS.COLLAPSED_LINES * 2;
207
+
208
+ function normalizeCellLines(lines: string[]): string[] {
209
+ return lines.map((line) => (line.endsWith("\n") ? line.slice(0, -1) : line));
210
+ }
211
+
212
+ function renderCellPreview(lines: string[], expanded: boolean, uiTheme: Theme): string {
213
+ const normalized = normalizeCellLines(lines);
214
+ if (normalized.length === 0) {
215
+ return `\n ${uiTheme.fg("dim", uiTheme.tree.last)} ${uiTheme.fg("muted", "(empty cell)")}`;
216
+ }
217
+
218
+ const maxLines = expanded ? normalized.length : Math.min(normalized.length, COLLAPSED_TEXT_LIMIT);
219
+ let text = "";
220
+
221
+ for (let i = 0; i < maxLines; i++) {
222
+ const isLast = i === maxLines - 1 && (expanded || normalized.length <= maxLines);
223
+ const branch = isLast ? uiTheme.tree.last : uiTheme.tree.branch;
224
+ const line = normalized[i];
225
+ text += `\n ${uiTheme.fg("dim", branch)} ${uiTheme.fg("toolOutput", line)}`;
226
+ }
227
+
228
+ const remaining = normalized.length - maxLines;
229
+ if (remaining > 0) {
230
+ text += `\n ${uiTheme.fg("dim", uiTheme.tree.last)} ${uiTheme.fg(
231
+ "muted",
232
+ formatMoreItems(remaining, "line", uiTheme),
233
+ )}`;
234
+ }
235
+
236
+ return text;
237
+ }
238
+
239
+ export const notebookToolRenderer = {
240
+ renderCall(args: NotebookRenderArgs, uiTheme: Theme): Component {
241
+ const label = uiTheme.fg("toolTitle", uiTheme.bold("Notebook"));
242
+ let text = `${label} ${uiTheme.fg("accent", args.action || "?")}`;
243
+
244
+ const meta: string[] = [];
245
+ meta.push(`in ${args.notebookPath || "?"}`);
246
+ if (args.cellNumber !== undefined) meta.push(`cell:${args.cellNumber}`);
247
+ if (args.cellType) meta.push(`type:${args.cellType}`);
248
+
249
+ text += formatMeta(meta, uiTheme);
250
+
251
+ return new Text(text, 0, 0);
252
+ },
253
+
254
+ renderResult(
255
+ result: { content: Array<{ type: string; text?: string }>; details?: NotebookToolDetails },
256
+ { expanded }: RenderResultOptions,
257
+ uiTheme: Theme,
258
+ ): Component {
259
+ const content = result.content?.[0];
260
+ if (content?.type === "text" && content.text?.startsWith("Error:")) {
261
+ return new Text(formatErrorMessage(content.text, uiTheme), 0, 0);
262
+ }
263
+
264
+ const details = result.details;
265
+ const action = details?.action ?? "edit";
266
+ const cellIndex = details?.cellIndex;
267
+ const cellType = details?.cellType;
268
+ const totalCells = details?.totalCells;
269
+ const cellSource = details?.cellSource;
270
+ const lineCount = cellSource?.length;
271
+ const canExpand = cellSource !== undefined && cellSource.length > COLLAPSED_TEXT_LIMIT;
272
+
273
+ const icon = uiTheme.styledSymbol("status.success", "success");
274
+ const actionLabel = action === "insert" ? "Inserted" : action === "delete" ? "Deleted" : "Edited";
275
+ const cellLabel = cellType || "cell";
276
+ const summaryParts = [`${actionLabel} ${cellLabel} at index ${cellIndex ?? "?"}`];
277
+ if (lineCount !== undefined) summaryParts.push(formatCount("line", lineCount));
278
+ if (totalCells !== undefined) summaryParts.push(`${totalCells} total`);
279
+ const summaryText = summaryParts.join(uiTheme.sep.dot);
280
+
281
+ const expandHint = formatExpandHint(expanded, canExpand, uiTheme);
282
+ let text = `${icon} ${uiTheme.fg("dim", summaryText)}${expandHint}`;
283
+
284
+ if (cellSource) {
285
+ text += renderCellPreview(cellSource, expanded, uiTheme);
286
+ }
287
+
288
+ return new Text(text, 0, 0);
289
+ },
290
+ };