pi-incise 0.1.3 → 0.2.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 +32 -1
- package/extension/index.ts +88 -6
- package/extension/minicpm-list.ts +363 -0
- package/extension/normalize.ts +41 -0
- package/extension/profiles.ts +94 -0
- package/extension/runner.ts +2 -0
- package/extension/safe-routed.ts +801 -0
- package/extension/schemas.ts +28 -8
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -12,9 +12,40 @@ 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
|
+
* **Gemma (recommended):** `INCISE_PROFILE=auto pi`
|
|
20
|
+
* **MiniCPM general editing:** `INCISE_PROFILE=standard pi`
|
|
21
|
+
* **MiniCPM list-addition evaluation:** `INCISE_PROFILE=minicpm-list pi`
|
|
22
|
+
* **Unknown or changing model families:** `INCISE_PROFILE=standard pi`
|
|
23
|
+
|
|
24
|
+
The package default is `standard` for compatibility. `auto` currently enables the measured `safe-routed` profile only for Gemma; MiniCPM and unknown families stay on `standard`. If a local provider exposes a generic model ID, add `INCISE_MODEL_FAMILY=gemma` or `INCISE_MODEL_FAMILY=minicpm`.
|
|
25
|
+
|
|
26
|
+
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.
|
|
27
|
+
|
|
15
28
|
## Tools
|
|
16
29
|
|
|
17
|
-
The
|
|
30
|
+
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`.
|
|
31
|
+
|
|
32
|
+
Set `INCISE_PROFILE=safe-routed` before starting Pi to use model-agnostic request routing directly. It retains the standard tools as a fallback, but for requests it can prove unambiguous it replaces them for that turn with one small, action-specific tool. The current measured routes are exact section rename, exact section-body replacement, explicit literal section insertion, exact quoted-sentence section append, table reads with explicit column/value predicates, typed edits to existing frontmatter keys, guarded creation of `build.cache`, exact quoted list-item removal, and same-heading list append resolved by an exact existing item. The adapter resolves the file and structural target, owns exact table filters and insertion or append content, constrains existing-key paths to inspected scalar leaves, verifies `build` is a map and `build.cache` is absent before create-only writes, validates exact current list items before removal or containing-item selection, uses a content hash plus `must_exist` or `must_absent` where applicable, permits one successful routed operation, and leaves tools from other extensions active. Ambiguous targets, fuzzy item matches, unsupported append wording, whole-table reads, ordinal reads, other frontmatter creation, frontmatter deletion or multi-key changes, and unsupported requests fall back to the standard profile.
|
|
33
|
+
|
|
34
|
+
`INCISE_PROFILE=auto` is the recommended Gemma setup. It selects capabilities from the active Pi model identity: Gemma uses `safe-routed`, while MiniCPM and unknown families remain on `standard` because no general MiniCPM composition has passed evaluation. Selection is fixed on the first model-bearing turn. If a local provider exposes a generic model ID, set `INCISE_MODEL_FAMILY=gemma`; `minicpm` and `unknown` are also accepted. `/incise-doctor` reports the requested profile, effective profile, detected model family, selection reason, and last route. The latest full Gemma/Pi treatment attempted all 480 trials and retained 479 paired rows after one persistent generation timeout. Correctness rose from 473/479 to 475/479 and harmful outcomes fell from 1 to 0. Lists reached 100/100, sections 145/149 with only loud refusals, frontmatter 110/110, and tables plus table reads 60/60. All 200 routed trials were correct, and all 279 usable fallback trials retained the standard tool surface. The package default remains `standard` for one compatibility release cycle.
|
|
35
|
+
|
|
36
|
+
Set `INCISE_PROFILE=safe-small` only to evaluate the experimental small-model composition. It exposes `md_tables`, `table_get`, `table_add_row`, `table_update_cell`, `md_lists`, `list_get`, `list_add_item`, `md_outline`, `section_insert`, `section_append`, `frontmatter_get`, and `frontmatter_set`. It intentionally omits generic multi-action tools and destructive section/frontmatter operations. A preregistered MiniCPM5 run found a significant list-addition gain but section and frontmatter regressions, including 0/27 correct frontmatter trials, so this profile is not recommended for general use.
|
|
37
|
+
|
|
38
|
+
Set `INCISE_PROFILE=minicpm-list` to evaluate the MiniCPM-specific list-addition pipeline. Each request must name exactly one Markdown path. Pi activates a required heading-and-ordinal selector, reads the selected list, then activates one append, after, or between content tool with exact current-item constraints. The adapter supplies the file and list address, validates relative anchors, writes with the read hash, and permits at most one successful mutation in that user turn. The adapter-independent arm reached 21/21 supported additions, while the real Pi composition reached 16/21; keep this profile opt-in. It supports adding list items only.
|
|
39
|
+
|
|
40
|
+
The preregistered real-Pi run reached 16/21 rather than the adapter-independent result of 21/21. Every executed mutation was correct and no document was damaged, but five trials stopped in prose instead of invoking the sole active phase tool. A paired forced-choice follow-up also reached 16/21 even though every observed active-phase request transmitted the exact advertised tool choice; the local MiniCPM/llama.cpp path did not enforce it. Compact list-only framing reached 19/21 and eliminated all no-call failures, but two previously correct trials wrote the wrong new item text. Neither treatment is shipped, and the profile remains evaluation-only.
|
|
41
|
+
|
|
42
|
+
## Measured results
|
|
43
|
+
|
|
44
|
+
The current Gemma `auto` profile completed **475/479 usable full-composition trials (99.2%) with zero harmful outcomes**. Tables, lists, frontmatter, and table reads were perfect; sections were 145/149 with four loud refusals. All **200/200 routed trials** were correct, and every unsupported request retained the standard tool surface.
|
|
45
|
+
|
|
46
|
+
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.
|
|
47
|
+
|
|
48
|
+
These results are tied to the recorded models, llama.cpp runtime, Pi version, prompts, schemas, tasks, seeds, and graders. See [the full findings](../../bench/FINDINGS.md) and [Gemma v8 analysis](../../bench/results/gemma_safe_routed_full_v8_20260922_analysis.json).
|
|
18
49
|
|
|
19
50
|
## Binary resolution
|
|
20
51
|
|
package/extension/index.ts
CHANGED
|
@@ -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
|
|
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: ${
|
|
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) ||
|
|
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(
|
|
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
|
-
|
|
135
|
-
|
|
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
|
+
}
|
package/extension/normalize.ts
CHANGED
|
@@ -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") {
|