@bismawy/pi-arnative 0.18.2 → 0.19.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.
package/lib/edit-diff.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * Unified and side-by-side (Split) word-level diff renderer for the `edit` tool box.
3
3
  */
4
- import { visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
4
+ import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
5
5
  import { EDIT_DIFF_KEY, choiceSetting } from "./preset-store.ts";
6
6
  import { clearRenderCache } from "./features/render-cache.ts";
7
7
 
8
- const SPLIT_DIFF_MIN_WIDTH = 50;
8
+ const SPLIT_DIFF_MIN_WIDTH = 64;
9
9
  const INTRA_LINE_MAX_TOKENS = 200;
10
10
 
11
11
  export type DiffTheme = {
@@ -30,7 +30,14 @@ export function setEditDiff(mode: EditDiffMode): void {
30
30
  clearRenderCache();
31
31
  }
32
32
 
33
- type DiffSide = { styled: string } | null;
33
+ type DiffSide = { gutter?: string; gutterW?: number; styled: string } | null;
34
+
35
+ const LINE_NUM_PREFIX = /^(\s*\d+\s)(.*)$/;
36
+
37
+ function splitLineNumber(raw: string): { gutter: string; code: string } {
38
+ const m = LINE_NUM_PREFIX.exec(raw);
39
+ return m ? { gutter: m[1]!, code: m[2]! } : { gutter: "", code: raw };
40
+ }
34
41
 
35
42
  function unifiedDiffLines(diff: string, th: DiffTheme): string[] {
36
43
  return diff.split("\n").map((l) =>
@@ -120,7 +127,15 @@ function highlightLinePair(oldText: string, newText: string, th: DiffTheme): { l
120
127
  function wrapDiffCell(side: DiffSide, width: number): string[] {
121
128
  if (!side) return [""];
122
129
  const clean = side.styled.replace(/\t/g, " ");
123
- return clean === "" ? [""] : wrapTextWithAnsi(clean, width);
130
+ const gutterW = side.gutterW ?? 0;
131
+ if (gutterW > 0 && side.gutter && width - gutterW >= 8) {
132
+ const codeW = width - gutterW;
133
+ const wrapped = clean === "" ? [""] : wrapTextWithAnsi(clean, codeW);
134
+ const pad = " ".repeat(gutterW);
135
+ return wrapped.map((line, i) => (i === 0 ? `${side.gutter}${line}` : `${pad}${line}`));
136
+ }
137
+ const combined = side.gutter ? `${side.gutter}${clean}` : clean;
138
+ return combined === "" ? [""] : wrapTextWithAnsi(combined, width);
124
139
  }
125
140
 
126
141
  function renderSplitPair(left: DiffSide, right: DiffSide, leftW: number, rightW: number, sep: string): string[] {
@@ -152,14 +167,35 @@ export function formatEditDiff(r: DiffResult, th: DiffTheme, inner: number, mode
152
167
  if (!diff) return fallbackLines(r, th);
153
168
  if (mode === "Unified" || inner < SPLIT_DIFF_MIN_WIDTH) return unifiedDiffLines(diff, th);
154
169
 
170
+ const rawLines = diff.split("\n");
171
+ let delCount = 0;
172
+ let addCount = 0;
173
+ for (const line of rawLines) {
174
+ if (line.startsWith("-") && !line.startsWith("---")) delCount++;
175
+ else if (line.startsWith("+") && !line.startsWith("+++")) addCount++;
176
+ }
177
+
155
178
  const sep = th.fg("dim", " │ ");
156
179
  const leftW = Math.floor((inner - 3) / 2);
157
180
  const rightW = inner - 3 - leftW;
181
+ const leftHeader =
182
+ delCount > 0 ? `${th.fg("dim", "Before")} ${th.fg("toolDiffRemoved", `-${delCount}`)}` : th.fg("dim", "Before");
183
+ const rightHeader =
184
+ addCount > 0 ? `${th.fg("dim", "After")} ${th.fg("toolDiffAdded", `+${addCount}`)}` : th.fg("dim", "After");
158
185
  const out: string[] = [
159
- `${th.fg("dim", "Before")}${" ".repeat(Math.max(0, leftW - 6))}${sep}${th.fg("dim", "After")}`,
186
+ `${leftHeader}${" ".repeat(Math.max(0, leftW - visibleWidth(leftHeader)))}${sep}${rightHeader}`,
160
187
  th.fg("dim", `${"─".repeat(leftW)}─┼─${"─".repeat(rightW)}`),
161
188
  ];
162
189
 
190
+ const makeSide = (raw: string, color: string): DiffSide => {
191
+ const { gutter, code } = splitLineNumber(raw);
192
+ return {
193
+ gutter: gutter ? th.fg("dim", gutter) : undefined,
194
+ gutterW: gutter.length,
195
+ styled: th.fg(color, code),
196
+ };
197
+ };
198
+
163
199
  let dels: string[] = [];
164
200
  let adds: string[] = [];
165
201
  const flushChanges = () => {
@@ -168,11 +204,29 @@ export function formatEditDiff(r: DiffResult, th: DiffTheme, inner: number, mode
168
204
  const d = dels[i];
169
205
  const a = adds[i];
170
206
  if (d !== undefined && a !== undefined) {
171
- const { left, right } = highlightLinePair(d, a, th);
172
- out.push(...renderSplitPair({ styled: left }, { styled: right }, leftW, rightW, sep));
207
+ const dParts = splitLineNumber(d);
208
+ const aParts = splitLineNumber(a);
209
+ const { left, right } = highlightLinePair(dParts.code, aParts.code, th);
210
+ out.push(
211
+ ...renderSplitPair(
212
+ {
213
+ gutter: dParts.gutter ? th.fg("dim", dParts.gutter) : undefined,
214
+ gutterW: dParts.gutter.length,
215
+ styled: left,
216
+ },
217
+ {
218
+ gutter: aParts.gutter ? th.fg("dim", aParts.gutter) : undefined,
219
+ gutterW: aParts.gutter.length,
220
+ styled: right,
221
+ },
222
+ leftW,
223
+ rightW,
224
+ sep,
225
+ ),
226
+ );
173
227
  } else {
174
- const left: DiffSide = d !== undefined ? { styled: th.fg("toolDiffRemoved", d) } : null;
175
- const right: DiffSide = a !== undefined ? { styled: th.fg("toolDiffAdded", a) } : null;
228
+ const left: DiffSide = d !== undefined ? makeSide(d, "toolDiffRemoved") : null;
229
+ const right: DiffSide = a !== undefined ? makeSide(a, "toolDiffAdded") : null;
176
230
  out.push(...renderSplitPair(left, right, leftW, rightW, sep));
177
231
  }
178
232
  }
@@ -180,18 +234,25 @@ export function formatEditDiff(r: DiffResult, th: DiffTheme, inner: number, mode
180
234
  adds = [];
181
235
  };
182
236
 
183
- for (const line of diff.split("\n")) {
237
+ for (const line of rawLines) {
184
238
  if (line.startsWith("-") && !line.startsWith("---")) {
185
239
  dels.push(line.slice(1));
186
240
  } else if (line.startsWith("+") && !line.startsWith("+++")) {
187
241
  adds.push(line.slice(1));
188
242
  } else if (line.startsWith(" ")) {
189
243
  flushChanges();
190
- const side: DiffSide = { styled: th.fg("toolDiffContext", line.slice(1)) };
244
+ const side = makeSide(line.slice(1), "toolDiffContext");
191
245
  out.push(...renderSplitPair(side, side, leftW, rightW, sep));
192
246
  } else {
193
247
  flushChanges();
194
- out.push(th.fg("toolDiffContext", line));
248
+ const trimmed = line.trim();
249
+ if (trimmed === "...") {
250
+ const dots = th.fg("dim", "···");
251
+ out.push(`${dots}${" ".repeat(Math.max(0, leftW - 3))}${sep}${dots}`);
252
+ } else {
253
+ const meta = th.fg("dim", truncateToWidth(line, leftW, "…"));
254
+ out.push(`${meta}${" ".repeat(Math.max(0, leftW - visibleWidth(meta)))}${sep}`);
255
+ }
195
256
  }
196
257
  }
197
258
  flushChanges();
@@ -25,7 +25,19 @@ import {
25
25
  setSpinnerPreset,
26
26
  type SpinnerPreset,
27
27
  } from "../spinner.ts";
28
- import { CHATBOX_DIALOG_KEY, CHATBOX_PRESET_KEY, CHATBOX_PROMPT_KEY, EDIT_DIFF_KEY, FOOTER_COST_KEY, FOOTER_PRESET_KEY, HEADER_PRESET_KEY, BUDGET_DAY_KEY, BUDGET_ENFORCE_KEY, BUDGET_MONTH_KEY, PAYLOAD_LIMIT_KEY, RENDER_CACHE_KEY, TOOL_LAYOUT_KEY, ensureChoices } from "../preset-store.ts";
28
+ import { ASK_MODE_KEY, ASK_MODEL_KEY, ASK_THINKING_KEY, CHATBOX_DIALOG_KEY, CHATBOX_PRESET_KEY, CHATBOX_PROMPT_KEY, EDIT_DIFF_KEY, FOOTER_COST_KEY, FOOTER_PRESET_KEY, HEADER_PRESET_KEY, BUDGET_DAY_KEY, BUDGET_ENFORCE_KEY, BUDGET_MONTH_KEY, PAYLOAD_LIMIT_KEY, RENDER_CACHE_KEY, TOOL_LAYOUT_KEY, ensureChoices } from "../preset-store.ts";
29
+ import {
30
+ ASK_MODE_CHOICES,
31
+ ASK_THINKING_CHOICES,
32
+ activeAskMode,
33
+ activeAskModel,
34
+ activeAskThinking,
35
+ setAskMode,
36
+ setAskModel,
37
+ setAskThinking,
38
+ type AskMode,
39
+ type AskThinking,
40
+ } from "../ask-user.ts";
29
41
  import { EDIT_DIFF_CHOICES, activeEditDiff, setEditDiff, type EditDiffMode } from "./tools.ts";
30
42
  import { CHATBOX_PRESETS, CHATBOX_PROMPTS, DEFAULT_CHATBOX_DIALOG, FOOTER_PRESETS, activeChatboxDialog, activeChatboxPreset, activeChatboxPrompt, activeFooterCost, activeFooterPreset, nextChatboxDialog, nextChatboxPrompt, setChatboxDialog, setChatboxPreset, setChatboxPrompt, setFooterCost, setFooterPreset, type ChatboxPreset } from "./footer.ts";
31
43
  import { activeBudgetDay, activeBudgetEnforce, activeBudgetMonth, openBudget } from "./budget.ts";
@@ -74,7 +86,7 @@ export interface MenuCategory {
74
86
  export const MENU_CATEGORIES: readonly MenuCategory[] = [
75
87
  { label: "Appearance", description: "themes, headers, footers, chatbox" },
76
88
  { label: "Display", description: "animations, diffs, tool layout, render cache" },
77
- { label: "Models & Context", description: "custom providers, model heal, auto-compact, payload limit" },
89
+ { label: "Models & Context", description: "custom providers, ask model, model heal, auto-compact, payload limit" },
78
90
  { label: "Spend", description: "usage dashboard, budget caps" },
79
91
  ];
80
92
 
@@ -100,7 +112,7 @@ export function categoryMenus(group: MenuGroup, menus: readonly ArnativeMenu[] =
100
112
  /** Title of the settings menu, derived from `screenTitle` so the format lives in one place. */
101
113
  export const MENU_TITLE = screenTitle("Settings");
102
114
  /** One-line description under the menu title. */
103
- export const MENU_DESC = "Themes, headers, footers, chatbox, animations, auto-compact, render, payload, providers, usage, budget";
115
+ export const MENU_DESC = "Themes, headers, footers, chatbox, animations, ask, auto-compact, render, payload, providers, usage, budget";
104
116
 
105
117
  const THEMES_PICKER_TEXT: ListPickerText = {
106
118
  title: screenTitle("Themes"),
@@ -698,6 +710,226 @@ const openPayloadLimit = async (ctx: ExtensionCommandContext): Promise<boolean |
698
710
  }
699
711
  };
700
712
 
713
+ const ASK_ACTIVE_MODEL_LABEL = "Active model (default)";
714
+
715
+ const ASK_MODE_NOTES: Record<AskMode, string> = {
716
+ Hybrid: "refine drafted questions AND author from goal/ambiguities (recommended)",
717
+ Refine: "audit & upgrade drafted questions from the active model only",
718
+ Off: "never delegate — always show the active model's questions directly",
719
+ };
720
+
721
+ const ASK_THINKING_NOTES: Record<AskThinking, string> = {
722
+ off: "fastest — no reasoning tokens",
723
+ low: "quick quality pass (default)",
724
+ medium: "deeper trade-off analysis for complex specs",
725
+ high: "thorough architecture-grade question synthesis",
726
+ };
727
+
728
+ export function askSettingsRows(model: string, mode: AskMode, thinking: AskThinking): ListRow[] {
729
+ return [
730
+ { label: "Question model", note: model || ASK_ACTIVE_MODEL_LABEL },
731
+ { label: "Mode", note: `${mode} — ${ASK_MODE_NOTES[mode]}` },
732
+ { label: "Thinking", note: `${thinking} — ${ASK_THINKING_NOTES[thinking]}` },
733
+ ];
734
+ }
735
+
736
+ export function askModeRows(opened: AskMode): ListRow[] {
737
+ return ASK_MODE_CHOICES.map((c) => ({ label: c, note: ASK_MODE_NOTES[c], chosen: c === opened }));
738
+ }
739
+
740
+ export function askThinkingRows(opened: AskThinking): ListRow[] {
741
+ return ASK_THINKING_CHOICES.map((c) => ({ label: c, note: ASK_THINKING_NOTES[c], chosen: c === opened }));
742
+ }
743
+
744
+ function availableAskModels(ctx: ExtensionCommandContext): { spec: string; scoped: boolean }[] {
745
+ const scoped = (ctx as { scopedModels?: readonly { model: { provider: string; id: string } }[] }).scopedModels ?? [];
746
+ const available = ctx.modelRegistry?.getAvailable?.() ?? [];
747
+ const seen = new Set<string>();
748
+ const out: { spec: string; scoped: boolean }[] = [];
749
+ for (const entry of scoped) {
750
+ const m = entry?.model;
751
+ if (!m?.provider || !m?.id) continue;
752
+ const spec = `${m.provider}/${m.id}`;
753
+ if (seen.has(spec)) continue;
754
+ seen.add(spec);
755
+ out.push({ spec, scoped: true });
756
+ }
757
+ for (const m of available) {
758
+ if (!m?.provider || !m?.id) continue;
759
+ const spec = `${m.provider}/${m.id}`;
760
+ if (seen.has(spec)) continue;
761
+ seen.add(spec);
762
+ out.push({ spec, scoped: false });
763
+ }
764
+ return out;
765
+ }
766
+
767
+ const openAskModelPicker = async (ctx: ExtensionCommandContext): Promise<void> => {
768
+ const current = activeAskModel();
769
+ const entries = availableAskModels(ctx);
770
+ const specs = entries.map((e) => e.spec);
771
+ const rows: ListRow[] = [
772
+ {
773
+ label: ASK_ACTIVE_MODEL_LABEL,
774
+ note: "use the session's active model (no delegation)",
775
+ chosen: current === "",
776
+ },
777
+ ...entries.map((entry) => ({
778
+ label: entry.spec,
779
+ ...(entry.scoped ? { note: "scoped" } : {}),
780
+ chosen: entry.spec === current,
781
+ })),
782
+ ];
783
+ if (current && !specs.includes(current)) {
784
+ rows.splice(1, 0, { label: current, note: "configured (not currently available)", chosen: true });
785
+ }
786
+ const cursor = current || ASK_ACTIVE_MODEL_LABEL;
787
+ const pickerText: ListPickerText = {
788
+ title: screenTitle("Ask Model"),
789
+ description: "Model used to refine or author ask_user_question dialogs (press / to filter).",
790
+ legend: "[/] Filter [↑↓] Move [Enter] Select [Esc] Back",
791
+ };
792
+
793
+ if (ctx.mode !== "tui") {
794
+ const labels = rows.map((r) => (r.chosen ? `${r.label} ✓` : r.label));
795
+ const pick = await ctx.ui.select(pickerText.title, labels);
796
+ if (pick === undefined) return;
797
+ const idx = labels.indexOf(pick);
798
+ const chosen = idx === 0 ? "" : rows[idx]?.label ?? "";
799
+ setAskModel(chosen);
800
+ ctx.ui.notify(`[arnative] Ask model: ${chosen || ASK_ACTIVE_MODEL_LABEL}`, "info");
801
+ return;
802
+ }
803
+
804
+ const picked = await ctx.ui.custom<number | null>((tui, theme, _kb, done) => {
805
+ const picker = new ListPicker(
806
+ theme,
807
+ rows,
808
+ cursor,
809
+ {
810
+ preview: () => {},
811
+ revert: () => {},
812
+ done: () => done(picker.index),
813
+ cancel: () => done(null),
814
+ back: () => done(null),
815
+ requestRender: () => tui.requestRender(),
816
+ search: "models",
817
+ },
818
+ pickerText,
819
+ false,
820
+ ctx.thinkingLevel,
821
+ 10,
822
+ );
823
+ return picker;
824
+ });
825
+ if (picked === null || picked === undefined || picked < 0) return;
826
+ const chosen = picked === 0 ? "" : rows[picked]?.label ?? "";
827
+ setAskModel(chosen);
828
+ announce(ctx.ui, `Ask model: ${chosen || ASK_ACTIVE_MODEL_LABEL}.`);
829
+ };
830
+
831
+ const openAsk = async (ctx: ExtensionCommandContext): Promise<boolean | void> => {
832
+ let cursor: string | undefined;
833
+ for (;;) {
834
+ const model = activeAskModel();
835
+ const mode = activeAskMode();
836
+ const thinking = activeAskThinking();
837
+ const rows = askSettingsRows(model, mode, thinking);
838
+ const text: ListPickerText = {
839
+ title: screenTitle("Ask"),
840
+ description: "Delegate ask_user_question refinement/authoring to a flagship model.",
841
+ legend: LIST_LEGEND_MOVE,
842
+ };
843
+
844
+ if (ctx.mode !== "tui") {
845
+ const labels = rows.map(rowText);
846
+ const pick = await ctx.ui.select(text.title, labels);
847
+ if (pick === undefined) return;
848
+ const idx = labels.indexOf(pick);
849
+ if (idx === 0) await openAskModelPicker(ctx);
850
+ else if (idx === 1) {
851
+ const mPick = await ctx.ui.select(screenTitle("Ask Mode"), ASK_MODE_CHOICES.map((c) => (c === mode ? `${c} ✓` : c)));
852
+ if (mPick) {
853
+ const val = ASK_MODE_CHOICES[ASK_MODE_CHOICES.findIndex((c) => mPick.startsWith(c))];
854
+ if (val) {
855
+ setAskMode(val);
856
+ ctx.ui.notify(`[arnative] Ask mode: ${val}`, "info");
857
+ }
858
+ }
859
+ } else if (idx === 2) {
860
+ const tPick = await ctx.ui.select(screenTitle("Ask Thinking"), ASK_THINKING_CHOICES.map((c) => (c === thinking ? `${c} ✓` : c)));
861
+ if (tPick) {
862
+ const val = ASK_THINKING_CHOICES[ASK_THINKING_CHOICES.findIndex((c) => tPick.startsWith(c))];
863
+ if (val) {
864
+ setAskThinking(val);
865
+ ctx.ui.notify(`[arnative] Ask thinking: ${val}`, "info");
866
+ }
867
+ }
868
+ }
869
+ return;
870
+ }
871
+
872
+ const choice = await ctx.ui.custom<{ index?: number; back?: boolean }>((tui, theme, _kb, done) => {
873
+ const picker = new ListPicker(
874
+ theme,
875
+ rows,
876
+ cursor,
877
+ {
878
+ preview: () => {},
879
+ revert: () => {},
880
+ done: () => done({ index: picker.index }),
881
+ cancel: () => done({ back: false }),
882
+ back: () => done({ back: true }),
883
+ requestRender: () => tui.requestRender(),
884
+ },
885
+ text,
886
+ false,
887
+ ctx.thinkingLevel,
888
+ );
889
+ return picker;
890
+ });
891
+ if (choice.index === undefined) return choice.back === true;
892
+ cursor = rows[choice.index]?.label;
893
+ if (choice.index === 0) {
894
+ await openAskModelPicker(ctx);
895
+ } else if (choice.index === 1) {
896
+ await openChoicePicker(ctx, {
897
+ choices: ASK_MODE_CHOICES,
898
+ rows: askModeRows(mode),
899
+ opened: mode,
900
+ text: {
901
+ title: screenTitle("Ask Mode"),
902
+ description: "How the custom question model participates in ask_user_question.",
903
+ legend: LIST_LEGEND_MOVE,
904
+ },
905
+ onCommit: (idx, isTui) => {
906
+ const val = ASK_MODE_CHOICES[idx]!;
907
+ setAskMode(val);
908
+ if (isTui) announce(ctx.ui, `Ask mode: ${val}.`);
909
+ else ctx.ui.notify(`[arnative] Ask mode: ${val}`, "info");
910
+ },
911
+ });
912
+ } else if (choice.index === 2) {
913
+ await openChoicePicker(ctx, {
914
+ choices: ASK_THINKING_CHOICES,
915
+ rows: askThinkingRows(thinking),
916
+ opened: thinking,
917
+ text: {
918
+ title: screenTitle("Ask Thinking"),
919
+ description: "Reasoning level passed to the delegated question model.",
920
+ legend: LIST_LEGEND_MOVE,
921
+ },
922
+ onCommit: (idx, isTui) => {
923
+ const val = ASK_THINKING_CHOICES[idx]!;
924
+ setAskThinking(val);
925
+ if (isTui) announce(ctx.ui, `Ask thinking: ${val}.`);
926
+ else ctx.ui.notify(`[arnative] Ask thinking: ${val}`, "info");
927
+ },
928
+ });
929
+ }
930
+ }
931
+ };
932
+
701
933
  export const MENUS: ArnativeMenu[] = [
702
934
  {
703
935
  value: "themes",
@@ -762,6 +994,13 @@ export const MENUS: ArnativeMenu[] = [
762
994
  group: "Models & Context",
763
995
  open: openProviders,
764
996
  },
997
+ {
998
+ value: "ask",
999
+ label: "Ask",
1000
+ description: "custom flagship model, mode & thinking level for ask_user_question",
1001
+ group: "Models & Context",
1002
+ open: openAsk,
1003
+ },
765
1004
  {
766
1005
  value: "heal",
767
1006
  label: "Model heal",
@@ -921,7 +1160,7 @@ export function shouldApplyDefaultTheme(
921
1160
  * set without starting a session. */
922
1161
  export function registerCommands(pi: Pick<ExtensionAPI, "registerCommand">): void {
923
1162
  pi.registerCommand("arnative", {
924
- description: "Arnative settings menu: themes, headers, footers, chatbox, animations, auto-compact, model heal, render cache, payload limit, providers, usage, budget",
1163
+ description: "Arnative settings menu: themes, headers, footers, chatbox, animations, ask, auto-compact, model heal, render cache, payload limit, providers, usage, budget",
925
1164
  getArgumentCompletions: arnativeCompletions,
926
1165
  handler: arnativeHandler,
927
1166
  });
@@ -947,6 +1186,9 @@ export function recordProfile(): void {
947
1186
  [SPINNER_GRADIENT_KEY]: activeSpinnerGradient() ? "on" : "off",
948
1187
  [EDIT_DIFF_KEY]: activeEditDiff(),
949
1188
  [TOOL_LAYOUT_KEY]: activeToolLayout(),
1189
+ [ASK_MODEL_KEY]: activeAskModel(),
1190
+ [ASK_MODE_KEY]: activeAskMode(),
1191
+ [ASK_THINKING_KEY]: activeAskThinking(),
950
1192
  [AUTO_COMPACT_KEY]: activeAutoCompact(),
951
1193
  [PAYLOAD_LIMIT_KEY]: savedPayloadLimit(),
952
1194
  [MODEL_HEAL_KEY]: activeModelHeal(),