pi-incise 0.1.3 → 0.3.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/README.md CHANGED
@@ -12,9 +12,43 @@ pi install npm:pi-incise
12
12
 
13
13
  Prebuilt binaries are provided for macOS arm64/x64 and glibc Linux arm64/x64. Windows and musl Linux are not supported in v1.
14
14
 
15
+ ## Recommended model setups
16
+
17
+ Choose the profile when starting Pi:
18
+
19
+ * **Ornith 1.5 9B (recommended):** `INCISE_PROFILE=auto pi --thinking off`
20
+ * **Gemma (recommended):** `INCISE_PROFILE=auto pi`
21
+ * **MiniCPM general editing:** `INCISE_PROFILE=standard pi`
22
+ * **MiniCPM list-addition evaluation:** `INCISE_PROFILE=minicpm-list pi`
23
+ * **Unknown or changing model families:** `INCISE_PROFILE=standard pi`
24
+
25
+ For Ornith, configure its Pi model entry with `maxTokens: 2048` and `samplingParams.parallel_tool_calls: false`. The measured result used temperature 0.6, top-p 0.95, top-k 20, min-p 0, presence penalty 0, and repeat penalty 1 through llama.cpp. The profile does not silently change provider decoding settings.
26
+
27
+ The package default is `standard` for compatibility. `auto` enables the measured `safe-routed` profile for Gemma and Ornith; MiniCPM and unknown families stay on `standard`. If a local provider exposes a generic model ID, set `INCISE_MODEL_FAMILY=gemma`, `INCISE_MODEL_FAMILY=ornith`, `INCISE_MODEL_FAMILY=minicpm`, or `INCISE_MODEL_FAMILY=unknown`.
28
+
29
+ After Pi starts, run `/incise-doctor`. It reports the requested and effective profiles, detected model family, selected binary, schema state, registered tools, and last route.
30
+
15
31
  ## Tools
16
32
 
17
- The package registers `table_edit`, `list_edit`, `section_edit`, `frontmatter_edit`, `table_get`, `md_tables`, `md_lists`, and `md_outline`. Inspect document structure with the relevant read tool before editing, and follow the remedy in any Incise refusal.
33
+ The default `standard` profile registers `table_edit`, `list_edit`, `section_edit`, `frontmatter_edit`, `table_get`, `md_tables`, `md_lists`, and `md_outline`. Inspect document structure with the relevant read tool before editing, and follow the remedy in any Incise refusal. The former `measured` profile name remains an alias for `standard`.
34
+
35
+ Set `INCISE_PROFILE=safe-routed` to use guarded request routing directly, or use `auto` with a measured Gemma or Ornith identity. The routed profile retains standard tools as fallback. For requests it can prove unambiguous, it inspects current structure and replaces the broad surface for that turn with one small action-specific tool. Host-owned routes cover measured table predicates, exact list relations and checkbox state, literal section insertion, append, rename, level changes and qualified body replacement, plus typed, create-only, delete, and compound frontmatter edits. Each write carries the inspected hash and permits one successful routed mutation. Ambiguous, unsupported, or structurally inconsistent requests fall back without reinterpretation.
36
+
37
+ `auto` selects once on the first model-bearing turn. Gemma and Ornith use `safe-routed`; MiniCPM and unknown identities use `standard`. `/incise-doctor` reports the requested profile, effective profile, model family, selection reason, and last route.
38
+
39
+ Set `INCISE_PROFILE=safe-small` only to evaluate the experimental small-model composition. It omits generic multi-action tools and destructive section/frontmatter operations, but a preregistered MiniCPM5 run failed its family and safety gates, so it is not recommended for general use.
40
+
41
+ Set `INCISE_PROFILE=minicpm-list` to evaluate the MiniCPM-specific list-addition pipeline. It requires one Markdown path, performs structural selection and item inspection, validates relative anchors, writes with the read hash, and permits at most one successful mutation. The adapter-independent arm reached 21/21 supported additions, while the real Pi composition reached 16/21; it remains opt-in and supports list additions only.
42
+
43
+ ## Measured results
44
+
45
+ The current Ornith 1.5 9B `auto` profile completed **480/480 full-composition trials (100%) with zero harmful outcomes**. Tables were 60/60, lists 100/100, sections 150/150, frontmatter 110/110, and table reads 60/60. All **360/360 routed trials** passed the exact route audit; all 120 fallback trials retained the standard tool surface. The recorded configuration used the official Q8 checkpoint through llama.cpp, thinking off, `maxTokens: 2048`, and `parallel_tool_calls: false`.
46
+
47
+ The current Gemma `auto` profile completed **475/479 usable trials (99.2%) with zero harmful outcomes**. Tables, lists, frontmatter, and table reads were perfect; sections were 145/149 with four loud refusals. The later Ornith route additions also passed **60/60 targeted Gemma compatibility trials** across the residual and qualified-preamble changes.
48
+
49
+ The MiniCPM-specific list pipeline is narrower. Its adapter-independent arm reached **21/21** supported additions from a 13/21 control, while the real Pi profile reached **16/21**. Every executed Pi mutation was correct and no document was damaged; the remaining failures were model no-calls. Keep it opt-in.
50
+
51
+ These results are tied to the recorded models, llama.cpp runtime, Pi version, prompts, schemas, tasks, seeds, graders, and inference settings. See [the full findings](../../bench/FINDINGS.md), [Ornith final analysis](../../bench/results/ornith_final_v2_safe_routed_20260923_analysis.json), [Ornith route audit](../../bench/results/ornith_final_v2_routes_20260923_analysis.json), and [Gemma v8 analysis](../../bench/results/gemma_safe_routed_full_v8_20260922_analysis.json).
18
52
 
19
53
  ## Binary resolution
20
54
 
@@ -2,8 +2,16 @@ import { withFileMutationQueue, type ExtensionAPI } from "@earendil-works/pi-cod
2
2
  import type { TSchema } from "typebox";
3
3
 
4
4
  import { packageVersion, resolveBinary, type ResolvedBinary } from "./binary.ts";
5
+ import { installMiniCpmListProfile, MINICPM_LIST_TOOL_NAMES } from "./minicpm-list.ts";
5
6
  import { prepareInvocation, READ_SUBCOMMAND, type ToolArguments } from "./normalize.ts";
7
+ import {
8
+ requestedProfile,
9
+ selectProfile,
10
+ type ProfileDecision,
11
+ type RequestedProfile,
12
+ } from "./profiles.ts";
6
13
  import { binaryVersion, processError, runIncise } from "./runner.ts";
14
+ import { installSafeRoutedProfile, type SafeRouteKind } from "./safe-routed.ts";
7
15
  import { loadMeasuredSchemas, PROMPT_METADATA, STRUCTURAL_READ_SCHEMAS, type ToolSchema } from "./schemas.ts";
8
16
 
9
17
  interface Diagnostics {
@@ -13,10 +21,18 @@ interface Diagnostics {
13
21
  schemas: ToolSchema[];
14
22
  error?: string;
15
23
  fatalMismatch: boolean;
24
+ registeredTools?: string[];
25
+ schemasAvailable?: boolean;
26
+ requestedProfile?: RequestedProfile;
27
+ profileDecision?: ProfileDecision;
28
+ activeRoute?: SafeRouteKind | "standard";
16
29
  }
17
30
 
18
31
  function diagnosticText(diagnostics: Diagnostics): string {
19
- const registered = diagnostics.schemas.length === 5 && !diagnostics.fatalMismatch
32
+ const schemasAvailable = diagnostics.schemasAvailable ?? diagnostics.schemas.length > 0;
33
+ const registered = diagnostics.registeredTools && !diagnostics.fatalMismatch
34
+ ? diagnostics.registeredTools.join(", ")
35
+ : diagnostics.schemas.length > 0 && !diagnostics.fatalMismatch
20
36
  ? [...diagnostics.schemas, ...STRUCTURAL_READ_SCHEMAS].map((schema) => schema.name).join(", ")
21
37
  : "none";
22
38
  const lines = [
@@ -24,9 +40,19 @@ function diagnosticText(diagnostics: Diagnostics): string {
24
40
  `binary: ${diagnostics.binary?.path ?? "not found"}`,
25
41
  `binary source: ${diagnostics.binary?.source ?? "none"}`,
26
42
  `binary version: ${diagnostics.binaryVersion ?? "unknown"}`,
27
- `schemas: ${diagnostics.schemas.length === 5 ? "available" : "unavailable"}`,
43
+ `schemas: ${schemasAvailable ? "available" : "unavailable"}`,
28
44
  `registered tools: ${registered}`,
29
45
  ];
46
+ if (diagnostics.requestedProfile) {
47
+ lines.push(`profile requested: ${diagnostics.requestedProfile}`);
48
+ lines.push(`profile effective: ${diagnostics.profileDecision?.effective ?? "pending first model-bearing turn"}`);
49
+ }
50
+ if (diagnostics.profileDecision) {
51
+ lines.push(`model: ${diagnostics.profileDecision.model}`);
52
+ lines.push(`model family: ${diagnostics.profileDecision.family}`);
53
+ lines.push(`profile reason: ${diagnostics.profileDecision.reason}`);
54
+ }
55
+ if (diagnostics.activeRoute) lines.push(`last route: ${diagnostics.activeRoute}`);
30
56
  if (diagnostics.binaryVersion && diagnostics.binaryVersion !== diagnostics.packageVersion) {
31
57
  lines.push(`warning: package ${diagnostics.packageVersion} is using incise ${diagnostics.binaryVersion}`);
32
58
  }
@@ -48,7 +74,7 @@ function registerDoctor(pi: ExtensionAPI, diagnostics: Diagnostics): void {
48
74
 
49
75
  function argvFor(name: string, operation: string, path: string, args: ToolArguments): string[] {
50
76
  const argv = [operation, path];
51
- if (!(name in READ_SUBCOMMAND) || name === "table_get") {
77
+ if (!(name in READ_SUBCOMMAND) || ["table_get", "list_get", "frontmatter_get"].includes(name)) {
52
78
  argv.push("--args", JSON.stringify(args));
53
79
  }
54
80
  return argv;
@@ -93,6 +119,9 @@ function registerTool(pi: ExtensionAPI, binary: ResolvedBinary, schema: ToolSche
93
119
  exitCode: result.code,
94
120
  hash: result.payload.hash,
95
121
  path: result.payload.path ?? invocation.path,
122
+ rows: result.payload.rows,
123
+ list: result.payload.list,
124
+ frontmatter: result.payload.frontmatter,
96
125
  },
97
126
  };
98
127
  },
@@ -108,6 +137,15 @@ export default async function inciseExtension(pi: ExtensionAPI): Promise<void> {
108
137
  schemas: [],
109
138
  fatalMismatch: false,
110
139
  };
140
+ let profile: RequestedProfile;
141
+ try {
142
+ profile = requestedProfile(process.env.INCISE_PROFILE);
143
+ diagnostics.requestedProfile = profile;
144
+ } catch (error) {
145
+ diagnostics.error = error instanceof Error ? error.message : String(error);
146
+ registerDoctor(pi, diagnostics);
147
+ return;
148
+ }
111
149
 
112
150
  if (!binary) {
113
151
  diagnostics.error = "No Incise binary is available for this platform. Set INCISE_BIN or install incise on PATH.";
@@ -122,17 +160,61 @@ export default async function inciseExtension(pi: ExtensionAPI): Promise<void> {
122
160
  registerDoctor(pi, diagnostics);
123
161
  return;
124
162
  }
163
+ if (profile === "minicpm-list") {
164
+ diagnostics.profileDecision = selectProfile(profile, undefined);
165
+ diagnostics.schemasAvailable = true;
166
+ diagnostics.registeredTools = [...MINICPM_LIST_TOOL_NAMES];
167
+ registerDoctor(pi, diagnostics);
168
+ installMiniCpmListProfile(pi, binary);
169
+ return;
170
+ }
125
171
 
126
172
  try {
127
- diagnostics.schemas = await loadMeasuredSchemas(pi.exec.bind(pi), binary.path);
173
+ diagnostics.schemas = await loadMeasuredSchemas(
174
+ pi.exec.bind(pi),
175
+ binary.path,
176
+ profile === "safe-small" ? "safe-small" : "measured",
177
+ );
128
178
  } catch (error) {
129
179
  diagnostics.error = error instanceof Error ? error.message : String(error);
130
180
  registerDoctor(pi, diagnostics);
131
181
  return;
132
182
  }
133
183
 
134
- registerDoctor(pi, diagnostics);
135
- for (const schema of [...diagnostics.schemas, ...STRUCTURAL_READ_SCHEMAS]) {
184
+ const structural = profile === "safe-small" ? [] : STRUCTURAL_READ_SCHEMAS;
185
+ const schemas = [...diagnostics.schemas, ...structural];
186
+ diagnostics.registeredTools = schemas.map((schema) => schema.name);
187
+ for (const schema of schemas) {
136
188
  registerTool(pi, binary, schema);
137
189
  }
190
+
191
+ if (profile !== "auto") diagnostics.profileDecision = selectProfile(profile, undefined);
192
+ if (profile === "auto" || profile === "safe-routed") {
193
+ let decision = diagnostics.profileDecision;
194
+ const familyOverride = profile === "auto" ? process.env.INCISE_MODEL_FAMILY : undefined;
195
+ if (profile === "auto" && familyOverride) {
196
+ try {
197
+ decision = selectProfile(profile, undefined, familyOverride);
198
+ diagnostics.profileDecision = decision;
199
+ } catch (error) {
200
+ diagnostics.error = error instanceof Error ? error.message : String(error);
201
+ }
202
+ }
203
+ if (diagnostics.error) {
204
+ registerDoctor(pi, diagnostics);
205
+ return;
206
+ }
207
+ installSafeRoutedProfile(pi, binary, {
208
+ standardTools: schemas.map((schema) => schema.name),
209
+ isEnabled(ctx) {
210
+ if (!decision && ctx.model) {
211
+ decision = selectProfile(profile, ctx.model, familyOverride);
212
+ diagnostics.profileDecision = decision;
213
+ }
214
+ return decision?.effective === "safe-routed";
215
+ },
216
+ onRoute(route) { diagnostics.activeRoute = route; },
217
+ });
218
+ }
219
+ registerDoctor(pi, diagnostics);
138
220
  }
@@ -0,0 +1,363 @@
1
+ import { resolve } from "node:path";
2
+
3
+ import { withFileMutationQueue, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
+ import type { TSchema } from "typebox";
5
+
6
+ import type { ResolvedBinary } from "./binary.ts";
7
+ import { stripPiPathPrefix, type ToolArguments } from "./normalize.ts";
8
+ import { processError, runIncise, type IncisePayload } from "./runner.ts";
9
+ import type { ToolSchema } from "./schemas.ts";
10
+
11
+ export type ListRoute = "append" | "after" | "between";
12
+
13
+ export interface ListEntry {
14
+ heading: string;
15
+ ordinal: number;
16
+ }
17
+
18
+ export interface ListItem {
19
+ text: string;
20
+ depth: number;
21
+ parent: number | null;
22
+ checked: boolean | null;
23
+ }
24
+
25
+ interface PipelineState {
26
+ path: string;
27
+ route: ListRoute;
28
+ entries: ListEntry[];
29
+ selected?: ListEntry;
30
+ items?: ListItem[];
31
+ hash?: string;
32
+ successfulMutation: boolean;
33
+ }
34
+
35
+ export const MINICPM_LIST_TOOL_NAMES = [
36
+ "list_select",
37
+ "list_append_item",
38
+ "list_insert_after",
39
+ "list_insert_between",
40
+ ] as const;
41
+
42
+ export function extractMarkdownPath(prompt: string): string | undefined {
43
+ const found = new Set<string>();
44
+ const patterns = [
45
+ /`([^`\n]+\.md)`/gi,
46
+ /(?:^|\s)@([^\s`"'<>]+\.md)(?=$|[\s,.;:!?])/gi,
47
+ /(?:^|[\s("'])((?:\.{0,2}\/)?[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*\.md)(?=$|[\s)"',.;:!?])/gi,
48
+ ];
49
+ for (const pattern of patterns) {
50
+ for (const match of prompt.matchAll(pattern)) {
51
+ const value = match[1]?.trim();
52
+ if (value) found.add(stripPiPathPrefix(value));
53
+ }
54
+ }
55
+ return found.size === 1 ? [...found][0] : undefined;
56
+ }
57
+
58
+ export function routeListRequest(prompt: string): ListRoute {
59
+ const normalized = ` ${prompt.toLowerCase().replace(/\s+/g, " ")} `;
60
+ if (normalized.includes(" insert ") && normalized.includes(" between ")) return "between";
61
+ if (normalized.includes(" immediately after ")) return "after";
62
+ return "append";
63
+ }
64
+
65
+ export function parseListSummary(text: string): ListEntry[] {
66
+ const entries: ListEntry[] = [];
67
+ const pattern = /^ heading "(.*)" ordinal ([0-9]+)$/gm;
68
+ for (const match of text.matchAll(pattern)) {
69
+ entries.push({ heading: match[1], ordinal: Number(match[2]) });
70
+ }
71
+ return entries;
72
+ }
73
+
74
+ export function selectEntry(
75
+ entries: ListEntry[],
76
+ args: ToolArguments,
77
+ ): ListEntry {
78
+ const heading = args.heading;
79
+ const ordinal = args.ordinal;
80
+ if (typeof heading !== "string" || typeof ordinal !== "number" ||
81
+ !Number.isSafeInteger(ordinal) || ordinal < 0) {
82
+ throw new Error("list_select requires an exact heading and non-negative integer ordinal.");
83
+ }
84
+ const matches = entries.filter((entry) => entry.heading === heading && entry.ordinal === ordinal);
85
+ if (matches.length !== 1) {
86
+ throw new Error("The selected heading and ordinal do not identify one current list.");
87
+ }
88
+ return matches[0];
89
+ }
90
+
91
+ export function selectionSchema(entries: ListEntry[]): ToolSchema {
92
+ const headings = [...new Set(entries.map((entry) => entry.heading))];
93
+ const ordinals = [...new Set(entries.map((entry) => entry.ordinal))].sort((a, b) => a - b);
94
+ return {
95
+ name: "list_select",
96
+ description: "Choose the one existing list matching every constraint in the request. Copy its exact full heading and ordinal from the summary.",
97
+ parameters: {
98
+ type: "object",
99
+ properties: {
100
+ heading: {
101
+ type: "string",
102
+ enum: headings,
103
+ description: "Exact full heading path of the target list.",
104
+ },
105
+ ordinal: {
106
+ type: "integer",
107
+ enum: ordinals,
108
+ description: "Exact ordinal of the target list under that heading.",
109
+ },
110
+ },
111
+ required: ["heading", "ordinal"],
112
+ },
113
+ };
114
+ }
115
+
116
+ function exactItemTexts(items: ListItem[]): string[] {
117
+ return [...new Set(items.map((item) => item.text))];
118
+ }
119
+
120
+ export function contentSchema(route: ListRoute, items: ListItem[]): ToolSchema {
121
+ if (route === "append") {
122
+ return {
123
+ name: "list_append_item",
124
+ description: "Supply the text of the one new item to append. The host already knows the exact file and list.",
125
+ parameters: {
126
+ type: "object",
127
+ properties: { text: { type: "string", description: "New item text." } },
128
+ required: ["text"],
129
+ },
130
+ };
131
+ }
132
+ const itemTexts = exactItemTexts(items);
133
+ if (route === "after") {
134
+ return {
135
+ name: "list_insert_after",
136
+ description: "Supply the new item text and choose the exact existing item after which it belongs. The host already knows the file and list.",
137
+ parameters: {
138
+ type: "object",
139
+ properties: {
140
+ text: { type: "string", description: "Text of the new list item." },
141
+ after: {
142
+ type: "string",
143
+ enum: itemTexts,
144
+ description: "Existing item after which the new item belongs. Copy one exact item text from this enum, not its index.",
145
+ },
146
+ },
147
+ required: ["text", "after"],
148
+ },
149
+ };
150
+ }
151
+ const boundary = { type: "string", enum: itemTexts };
152
+ return {
153
+ name: "list_insert_between",
154
+ description: "Supply the new item and both existing boundary items named by the request. Copy the boundaries in request order. The host already knows the file and list.",
155
+ parameters: {
156
+ type: "object",
157
+ properties: {
158
+ text: { type: "string", description: "Text of the new list item." },
159
+ after: {
160
+ ...boundary,
161
+ description: "First named boundary: the existing item the new item follows.",
162
+ },
163
+ before: {
164
+ ...boundary,
165
+ description: "Second named boundary: the existing item the new item precedes.",
166
+ },
167
+ },
168
+ required: ["text", "after", "before"],
169
+ },
170
+ };
171
+ }
172
+
173
+ function oneItemIndex(items: ListItem[], text: unknown, field: string): number {
174
+ if (typeof text !== "string") throw new Error(`${field} must be exact returned item text.`);
175
+ const hits = items.flatMap((item, index) => item.text === text ? [index] : []);
176
+ if (hits.length !== 1) throw new Error(`${field} must identify one exact current item.`);
177
+ return hits[0];
178
+ }
179
+
180
+ export function composeListAdd(
181
+ path: string,
182
+ entry: ListEntry,
183
+ route: ListRoute,
184
+ items: ListItem[],
185
+ args: ToolArguments,
186
+ ): ToolArguments {
187
+ if (typeof args.text !== "string") throw new Error("text must be a string.");
188
+ const composed: ToolArguments = {
189
+ path,
190
+ list: { heading: entry.heading, ordinal: entry.ordinal },
191
+ text: args.text,
192
+ };
193
+ if (route === "append") {
194
+ composed.position = "end";
195
+ return composed;
196
+ }
197
+ const afterIndex = oneItemIndex(items, args.after, "after");
198
+ composed.after = args.after;
199
+ if (route === "after") return composed;
200
+
201
+ const beforeIndex = oneItemIndex(items, args.before, "before");
202
+ if (beforeIndex !== afterIndex + 1) {
203
+ throw new Error("The selected boundaries are not adjacent and ordered.");
204
+ }
205
+ if (items[afterIndex].depth !== items[beforeIndex].depth ||
206
+ items[afterIndex].parent !== items[beforeIndex].parent) {
207
+ throw new Error("The selected boundaries are not structural siblings.");
208
+ }
209
+ return composed;
210
+ }
211
+
212
+ export function listItems(payload: IncisePayload, selected: ListEntry): ListItem[] {
213
+ const list = payload.list;
214
+ if (!list || typeof list !== "object" || Array.isArray(list)) {
215
+ throw new Error("incise items did not return a structured list.");
216
+ }
217
+ const value = list as Record<string, unknown>;
218
+ if (value.heading !== selected.heading || value.ordinal !== selected.ordinal ||
219
+ !Array.isArray(value.items)) {
220
+ throw new Error("incise items returned a different list than the validated selection.");
221
+ }
222
+ const items: ListItem[] = [];
223
+ for (const raw of value.items) {
224
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
225
+ throw new Error("incise items returned a malformed item.");
226
+ }
227
+ const item = raw as Record<string, unknown>;
228
+ if (typeof item.text !== "string" || typeof item.depth !== "number" ||
229
+ !Number.isSafeInteger(item.depth) ||
230
+ !(item.parent === null || (typeof item.parent === "number" && Number.isSafeInteger(item.parent))) ||
231
+ !(item.checked === null || typeof item.checked === "boolean")) {
232
+ throw new Error("incise items returned a malformed item.");
233
+ }
234
+ items.push(item as unknown as ListItem);
235
+ }
236
+ return items;
237
+ }
238
+
239
+ function toolResult(text: string, details: Record<string, unknown>) {
240
+ return { content: [{ type: "text" as const, text }], details };
241
+ }
242
+
243
+ export function installMiniCpmListProfile(
244
+ pi: ExtensionAPI,
245
+ binary: ResolvedBinary,
246
+ ): void {
247
+ let state: PipelineState | undefined;
248
+
249
+ const registerContentTool = (schema: ToolSchema): void => {
250
+ pi.registerTool({
251
+ name: schema.name,
252
+ label: schema.name,
253
+ description: schema.description,
254
+ parameters: schema.parameters as TSchema,
255
+ async execute(_toolCallId, params, signal) {
256
+ if (!state?.selected || !state.items || !state.hash) {
257
+ throw new Error("No validated list selection is active.");
258
+ }
259
+ if (state.successfulMutation) {
260
+ throw new Error("This turn already completed one successful list mutation.");
261
+ }
262
+ const args = composeListAdd(
263
+ state.path, state.selected, state.route, state.items,
264
+ params as ToolArguments,
265
+ );
266
+ const call = async () => runIncise(
267
+ pi.exec.bind(pi),
268
+ binary.path,
269
+ ["list-add-item", state!.path, "--args", JSON.stringify(args), "--if-match", state!.hash!],
270
+ signal,
271
+ );
272
+ const result = await withFileMutationQueue(state.path, call);
273
+ if (result.code !== 0 || result.payload.ok === false) throw processError(result);
274
+ state.successfulMutation = true;
275
+ pi.setActiveTools([]);
276
+ return toolResult(String(result.payload.description ?? ""), {
277
+ exitCode: result.code,
278
+ hash: result.payload.hash,
279
+ path: result.payload.path ?? state.path,
280
+ changed: Boolean(result.payload.changed),
281
+ route: state.route,
282
+ validated: true,
283
+ });
284
+ },
285
+ });
286
+ };
287
+
288
+ const registerSelectionTool = (schema: ToolSchema): void => {
289
+ pi.registerTool({
290
+ name: schema.name,
291
+ label: schema.name,
292
+ description: schema.description,
293
+ parameters: schema.parameters as TSchema,
294
+ async execute(_toolCallId, params, signal) {
295
+ if (!state) throw new Error("No MiniCPM list request is active.");
296
+ const selected = selectEntry(state.entries, params as ToolArguments);
297
+ const readArgs = {
298
+ path: state.path,
299
+ list: { heading: selected.heading, ordinal: selected.ordinal },
300
+ };
301
+ const result = await runIncise(
302
+ pi.exec.bind(pi),
303
+ binary.path,
304
+ ["items", state.path, "--args", JSON.stringify(readArgs)],
305
+ signal,
306
+ );
307
+ if (result.code !== 0 || result.payload.ok === false) throw processError(result);
308
+ const items = listItems(result.payload, selected);
309
+ if (typeof result.payload.hash !== "string" || !result.payload.hash) {
310
+ throw new Error("incise items did not return a content hash.");
311
+ }
312
+ state.selected = selected;
313
+ state.items = items;
314
+ state.hash = result.payload.hash;
315
+ const next = contentSchema(state.route, items);
316
+ registerContentTool(next);
317
+ pi.setActiveTools([next.name]);
318
+ return toolResult(String(result.payload.text ?? ""), {
319
+ hash: result.payload.hash,
320
+ path: state.path,
321
+ list: result.payload.list,
322
+ route: state.route,
323
+ validated: true,
324
+ });
325
+ },
326
+ });
327
+ };
328
+
329
+ pi.on("before_agent_start", async (event, ctx) => {
330
+ state = undefined;
331
+ const found = extractMarkdownPath(event.prompt);
332
+ if (!found) {
333
+ pi.setActiveTools([]);
334
+ return {
335
+ systemPrompt: `${event.systemPrompt}\n\nThe MiniCPM list profile requires exactly one explicit Markdown file path in the user request. Do not edit a file.`,
336
+ };
337
+ }
338
+ const path = resolve(ctx.cwd, found);
339
+ const result = await runIncise(pi.exec.bind(pi), binary.path, ["lists", path]);
340
+ if (result.code !== 0 || result.payload.ok === false) {
341
+ pi.setActiveTools([]);
342
+ throw processError(result);
343
+ }
344
+ const text = String(result.payload.text ?? "");
345
+ const entries = parseListSummary(text);
346
+ if (entries.length === 0) {
347
+ pi.setActiveTools([]);
348
+ throw new Error("incise found no existing Markdown list to select.");
349
+ }
350
+ state = {
351
+ path,
352
+ route: routeListRequest(event.prompt),
353
+ entries,
354
+ successfulMutation: false,
355
+ };
356
+ const schema = selectionSchema(entries);
357
+ registerSelectionTool(schema);
358
+ pi.setActiveTools([schema.name]);
359
+ return {
360
+ systemPrompt: `${event.systemPrompt}\n\n${text}\n\nUse list_select once. Copy the exact full heading and ordinal for the requested list.`,
361
+ };
362
+ });
363
+ }
@@ -7,6 +7,12 @@ export const WRITE_TOOLS = new Set([
7
7
  "list_edit",
8
8
  "section_edit",
9
9
  "frontmatter_edit",
10
+ "table_add_row",
11
+ "table_update_cell",
12
+ "list_add_item",
13
+ "section_insert",
14
+ "section_append",
15
+ "frontmatter_set",
10
16
  ]);
11
17
 
12
18
  export const READ_SUBCOMMAND: Readonly<Record<string, string>> = {
@@ -14,6 +20,8 @@ export const READ_SUBCOMMAND: Readonly<Record<string, string>> = {
14
20
  md_tables: "tables",
15
21
  md_lists: "lists",
16
22
  table_get: "rows",
23
+ list_get: "items",
24
+ frontmatter_get: "keys",
17
25
  };
18
26
 
19
27
  function actionName(value: unknown): string {
@@ -21,6 +29,39 @@ function actionName(value: unknown): string {
21
29
  }
22
30
 
23
31
  export function normalizeEdit(name: string, input: ToolArguments): { operation: string; args: ToolArguments } {
32
+ const narrow: Readonly<Record<string, string>> = {
33
+ table_add_row: "table-add-row",
34
+ table_update_cell: "table-update-cell",
35
+ list_add_item: "list-add-item",
36
+ section_append: "section-append",
37
+ frontmatter_set: "frontmatter-set",
38
+ };
39
+ const narrowOperation = narrow[name];
40
+ if (narrowOperation) return { operation: narrowOperation, args: input };
41
+ if (name === "section_insert") {
42
+ const args: ToolArguments = { ...input };
43
+ if ("parent" in args) {
44
+ args.section = args.parent;
45
+ delete args.parent;
46
+ }
47
+ if ("new_heading" in args) {
48
+ args.heading = args.new_heading;
49
+ delete args.new_heading;
50
+ }
51
+ if ("body" in args) {
52
+ args.text = args.body;
53
+ delete args.body;
54
+ }
55
+ if (args.section && typeof args.section === "object" && !Array.isArray(args.section)) {
56
+ const section = { ...(args.section as ToolArguments) };
57
+ if ("heading" in section && !("path" in section)) {
58
+ section.path = section.heading;
59
+ delete section.heading;
60
+ }
61
+ args.section = section;
62
+ }
63
+ return { operation: "section-insert", args };
64
+ }
24
65
  if (name === "table_edit") return { operation: `table-${actionName(input.action)}`, args: input };
25
66
  if (name === "list_edit") return { operation: `list-${actionName(input.action)}`, args: input };
26
67
  if (name === "frontmatter_edit") {