pi-incise 0.6.0 → 0.8.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
@@ -34,6 +34,28 @@ LFM3-specific support was abandoned on 25 November 2026 after the evaluation fai
34
34
 
35
35
  For Inkling 2 Mini, the measured local UD-Q3_K_XL setup used Pi SDK 1.0.4, a 32,768-token context, `maxTokens: 2048`, temperature 0.6, top-p 0.95, top-k 0, min-p 0, repeat penalty 1, and presence penalty 0. Send native `reasoning_effort: "none"`; the model still emitted reasoning in this runtime. Select the local model separately; the plugin does not change decoding settings. Inkling uses Pi’s structured prompt options to keep the prompt’s tool list aligned with the active route, and receives the existing hash-bound inspection for checkbox edits.
36
36
 
37
+ ## SenseNova Loop 9B Q8
38
+
39
+ <a id="experimental-sensenova-loop-9b-q8"></a>
40
+
41
+ Incise 0.8.0 supports the exact local model ID `sensenova-loop-9b-q8` with Pi SDK 1.7.0 and explicit `INCISE_PROFILE=safe-routed`. Fully prepared edits and table reads finish with the actual Incise operation result through Pi's native completion API. These are executor reports, not model-written summaries. Supported list inspections and already-satisfied membership checks return exact hash-guarded reports. Pending approval keeps edits blocked and returns the permission question; unsupported conditions keep mutation tools unavailable. Explicit additional inspection or explanation steps retain continuation.
42
+
43
+ The three-seed qualification passed **144/144 correct, factual, resolved workflows**, including **18/18 table reads**, with zero incorrectly changed documents or provider/runtime/interface faults. Each seed repeats all 48 frozen tasks. One seed-113 pre-call message proposed an irrelevant Python/XML method; the actual Incise edit and result were correct. Planning narration remains a known limitation. Entry screens additionally passed 9/9 safety/intent cases, 7/7 insertion routes and 6/6 native reads. The [complete audit](../../bench/results/sensenova_loop_9b_q8_native_qualification_summary_v2_20261130.json) and [experiment report](../../bench/SENSENOVA_LOOP_9B_Q8_20261130.md) retain the failed candidates and exact qualification scope.
44
+
45
+ Install with `pi install npm:pi-incise@0.8.0`. Merge the [recorded seed-79 provider entry](../../bench/sensenova_loop_9b_q8_native_qualification_s79_v2_20261130_models.json) into Pi's `models.json` without replacing other providers. It targets `http://127.0.0.1:8081/v1` and records context, output and sampling settings, including `chat_template_kwargs.enable_thinking=false`; the recorded server template does not support native `reasoning_effort`.
46
+
47
+ ```bash
48
+ INCISE_PROFILE=safe-routed pi -e npm:pi-incise@0.8.0 \
49
+ --provider sensenova-local --model sensenova-loop-9b-q8 \
50
+ --tools 'read,table_*,list_*,section_*,frontmatter_*,md_*,approval_*,condition_*' \
51
+ --no-extensions --no-mcp --no-skills --no-context-files \
52
+ --no-prompt-templates --no-session --thinking off
53
+ ```
54
+
55
+ Keep the built-in reader available and all writes through Incise. Native result paths defer the reader after host resolution; it returns for later requests or failure. Native reports are tool messages. For non-interactive scripting use Pi's `--mode json -p` output and read the native tool result; plain `pi -p` prints assistant messages only and omits completed native reports.
56
+
57
+ The recorded benchmark additionally restricts reads and CLI operations to the current fixture and allows six assistant turns. The launch command uses Pi's ordinary reader and does not install benchmark-only isolation or turn caps. Additional project/skill workflows and unrestricted interactive context remain unqualified. `auto` keeps standard tools for this identity. Other SenseNova identities and Hermes remain unqualified. Run `/incise-doctor` to inspect the effective profile and binary.
58
+
37
59
  ## Tools
38
60
 
39
61
  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`.
@@ -13,6 +13,7 @@ import {
13
13
  type RequestedProfile,
14
14
  } from "./profiles.ts";
15
15
  import { binaryVersion, processError, runIncise } from "./runner.ts";
16
+ import { senseNovaRequestPolicy } from "./request-policy.ts";
16
17
  import { installSafeRoutedProfile, type SafeRouteKind } from "./safe-routed.ts";
17
18
  import { loadMeasuredSchemas, PROMPT_METADATA, STRUCTURAL_READ_SCHEMAS, type ToolSchema } from "./schemas.ts";
18
19
 
@@ -208,8 +209,35 @@ export default async function inciseExtension(pi: ExtensionAPI): Promise<void> {
208
209
  }
209
210
  installSafeRoutedProfile(pi, binary, {
210
211
  standardTools: schemas.map((schema) => schema.name),
212
+ prepareWholeTableRead(ctx) { return ctx.model?.id === "sensenova-loop-9b-q8"; },
213
+ nativeCompletion(ctx, kind, prompt) {
214
+ if (ctx.model?.id !== "sensenova-loop-9b-q8") return false;
215
+ if (kind === "condition-result" || kind === "approval-request") return true;
216
+ const instructions = prompt.replace(/`[^`\n]*`|"[^"\n]*"|“[^”\n]*”/g, " ");
217
+ if (kind === "table-query") return !/\b(?:first\s+(?:read|inspect|show|list)|afterwards?|finally|explain|summari[sz]e|why|then\s+(?:edit|write|change|add|remove|delete|update|read|inspect|verify|check|explain|summari[sz]e))\b/i.test(instructions);
218
+ if (kind === "list-inspection") return !/\b(?:then|afterwards?|finally|explain|summari[sz]e|why)\b/i.test(instructions);
219
+ return !/\b(?:then|afterwards?|finally|verify|inspect|read|explain|summari[sz]e|check)\b/i.test(instructions);
220
+ },
221
+ useOperationDelta(ctx) {
222
+ return ctx.model?.id === "sensenova-loop-9b-q8";
223
+ },
224
+ requestPolicy(ctx, prompt) {
225
+ return ctx.model?.id === "sensenova-loop-9b-q8" ? senseNovaRequestPolicy(prompt) : undefined;
226
+ },
211
227
  useStructuredPrompt(ctx) {
212
- return modelFamily(ctx.model, familyOverride) === "inkling";
228
+ return modelFamily(ctx.model, familyOverride) === "inkling" ||
229
+ ctx.model?.id === "sensenova-loop-9b-q8";
230
+ },
231
+ completionPrompt(ctx) {
232
+ if (ctx.model?.id !== "sensenova-loop-9b-q8") return undefined;
233
+ return "The bound Incise operation has completed successfully. " +
234
+ "Report the completed change or requested read result. " +
235
+ "Do not repeat the completed operation or invent additional work. " +
236
+ "Follow any remaining user-requested steps using only tools that are currently available.";
237
+ },
238
+ boundListReadback(ctx, kind, prompt) {
239
+ return ctx.model?.id === "sensenova-loop-9b-q8" && kind === "list-append-target" &&
240
+ !/\b(?:read|inspect|show|display|preview|verify|check|examine|look|print|contents|if|unless|when|whether|until|provided|confirm|confirmation|approval|permission|ask|wait)\b/i.test(prompt);
213
241
  },
214
242
  isEnabled(ctx) {
215
243
  if (!decision && ctx.model) {
@@ -0,0 +1,65 @@
1
+ export interface PreparedRequestPolicy {
2
+ mode: "read-only" | "conditional";
3
+ headingCondition?: { heading: string; prepareWhenPresent: boolean };
4
+ context: string;
5
+ inspectionComplete?: boolean;
6
+ approvalRequired?: boolean;
7
+ listInspection?: { heading: string; loose: boolean; exactlyOnce?: string };
8
+ }
9
+
10
+ /** Preserve prerequisites outside quoted item/heading/code data before preparing an edit. */
11
+ export function senseNovaRequestPolicy(prompt: string): PreparedRequestPolicy | undefined {
12
+ const instructions = prompt
13
+ .replace(/```[\s\S]*?```|~~~[\s\S]*?~~~/g, (text) => " ".repeat(text.length))
14
+ .replace(/`[^`\n]*`|"[^"\n]*"|“[^”\n]*”/g, (text) => " ".repeat(text.length))
15
+ .replace(/(^|[\s([:])'[^'\n]*'(?=$|[\s)\],.!?:;])/g, (text) => " ".repeat(text.length));
16
+ const listTarget = /\b(loose|tight)\s+list\s+under\s+["“]([^"”\n]+)["”]/i.exec(prompt);
17
+ const listInspection = listTarget && /[a-z]/i.test(instructions[listTarget.index])
18
+ ? { heading: listTarget[2], loose: listTarget[1].toLowerCase() === "loose" } : undefined;
19
+ const permission = instructions
20
+ .replace(/\b(?:do\s+not|don't|never)\s+(?:ask|wait)\b[^.!?\n]*/gi, " ")
21
+ .replace(/\b(?:no\s+need|you\s+(?:do\s+not|don't)\s+need|you\s+need\s+not)\s+to\s+(?:ask|wait)\b[^.!?\n]*/gi, " ");
22
+ const approval = /\bask(?:\s+me)?\s+(?:for\s+)?(?:approval|confirmation)\b/i.test(permission) ||
23
+ /\b(?:confirm|check)\s+with\s+me\s+before\b/i.test(permission) ||
24
+ /\bwait\s+(?:until|for)\b[^.!?\n]{0,80}\b(?:approve|approval|confirm|confirmation)\b/i.test(permission) ||
25
+ /\b(?:do\s+not|don't|must\s+not)\s+(?:edit|change|add|insert|remove|delete|modify)\b[^.!?\n]{0,100}\buntil\b[^.!?\n]{0,60}\b(?:approve|confirm)\b/i.test(permission);
26
+ if (approval) return {
27
+ approvalRequired: true,
28
+ mode: "read-only",
29
+ context: "The user requires approval or confirmation before changes. " +
30
+ "Ask only whether to proceed with the requested edit, then wait. " +
31
+ "Incise mutation tools are withheld for this request.",
32
+ };
33
+ if (/\b(?:ask(?:\s+me)?\s+(?:which|to\s+clarify)|do\s+not\s+guess|don't\s+guess)\b/i.test(instructions)) return {
34
+ mode: "read-only",
35
+ context: "The user requires clarification rather than guessing a target. Ask the requested clarification and wait. " +
36
+ "Incise mutation tools are withheld for this request. Do not perform or claim an edit.",
37
+ };
38
+ if (/\b(?:do\s+not|don't|must\s+not|never)\s+(?:edit|modify|change|alter)\s+(?:the\s+file|this\s+(?:file|document)|anything)\s*(?:[.!?;]|$)/i.test(instructions) ||
39
+ /\b(?:do\s+not|don't)\s+add,?\s*remove\s+or\s+change\s+anything\s*(?:[.!?;]|$)/i.test(instructions) ||
40
+ /\b(?:do\s+not|don't)\s+(?:edit|modify|change)\s+(?:yet|for\s+now)\b/i.test(instructions)) return {
41
+ mode: "read-only",
42
+ listInspection: !/\b(?:if|unless|until|provided|only\s+when)\b/i.test(instructions) &&
43
+ /\b(?:item\s+texts|how\s+many\s+items|count\s+(?:the\s+)?items)\b/i.test(instructions) ? listInspection : undefined,
44
+ context: "The user explicitly requested inspection without editing. Use only inspection tools and answer the requested question. " +
45
+ "Incise mutation tools are withheld for this request. Do not perform or claim an edit.",
46
+ };
47
+ const conditions = [...instructions.matchAll(/\b(?:if|unless|until|provided|only\s+when)\b/gi)];
48
+ if (conditions.length) {
49
+ // Recognize only one positive structural predicate outside quoted/code data.
50
+ const predicate = /\b(?:only\s+proceed\s+)?if\s+(?:a|the)\s+heading\s+(?:named\s+)?["“]([^"”\n]+)["”]\s+exists\s*([,;.])/gi;
51
+ const match = [...prompt.matchAll(predicate)].find((item) =>
52
+ conditions.length === 1 && conditions[0].index === item.index + item[0].toLowerCase().indexOf("if"));
53
+ const once = /\bcontains\s+exactly\s+one\s+item\s+["“]([^"”\n]+)["”]/i.exec(prompt);
54
+ const satisfiedMembership = conditions.length === 1 && once && listInspection &&
55
+ /\bif\s+it\s+is\s+already\s+present\s+once,\s*leave\s+the\s+file\s+unchanged\s*[.!]?$/i.test(prompt.trim());
56
+ return {
57
+ mode: "conditional",
58
+ listInspection: satisfiedMembership ? { ...listInspection, exactlyOnce: once[1] } : undefined,
59
+ headingCondition: match ? { heading: match[1], prepareWhenPresent: match[2] === "," } : undefined,
60
+ context: "The request has a condition that has not been verified. Incise mutation tools are withheld. " +
61
+ "Inspect as needed and explain whether the condition is satisfied; do not perform or claim an edit.",
62
+ };
63
+ }
64
+ return undefined;
65
+ }
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { readFile, writeFile } from "node:fs/promises";
2
3
  import { resolve } from "node:path";
3
4
 
@@ -12,6 +13,7 @@ import {
12
13
  type ListEntry,
13
14
  } from "./minicpm-list.ts";
14
15
  import { processError, runIncise, type InciseResult } from "./runner.ts";
16
+ import type { PreparedRequestPolicy } from "./request-policy.ts";
15
17
  import type { ToolSchema } from "./schemas.ts";
16
18
 
17
19
  export type SafeRouteKind = "section-rename" | "section-replace-body" | "section-insert" |
@@ -20,7 +22,7 @@ export type SafeRouteKind = "section-rename" | "section-replace-body" | "section
20
22
  "frontmatter-release" | "list-remove-target" |
21
23
  "list-append-target" | "list-set-checked-target" |
22
24
  "table-add-row-target" | "table-delete-row-target" |
23
- "table-update-cell-target" | "table-query";
25
+ "table-update-cell-target" | "table-query" | "condition-result" | "approval-request" | "list-inspection";
24
26
 
25
27
  export interface OutlineEntry {
26
28
  path: string;
@@ -137,9 +139,11 @@ interface RouteSpec {
137
139
  kind: SafeRouteKind;
138
140
  path: string;
139
141
  hash?: string;
142
+ readHash?: string;
140
143
  schema: ToolSchema;
141
144
  operation: string;
142
145
  write: boolean;
146
+ successDescription?: string;
143
147
  arguments(params: Record<string, unknown>): Record<string, unknown>;
144
148
  followups?(params: Record<string, unknown>): Array<{
145
149
  operation: string;
@@ -153,6 +157,12 @@ interface RouteSpec {
153
157
  interface RoutedState {
154
158
  spec: RouteSpec;
155
159
  completed: boolean;
160
+ operationDelta?: boolean;
161
+ terminate?: boolean;
162
+ completion?: { active: string; finished: string };
163
+ deferredRead?: boolean;
164
+ resultHash?: string;
165
+ readback?: { arguments: Record<string, unknown>; completed: boolean; running: boolean };
156
166
  }
157
167
 
158
168
  export function sectionIntent(prompt: string): { kind: "section-rename"; target: string; heading: string } |
@@ -801,6 +811,17 @@ function resolveListEntry(entries: ListEntry[], requested: string): ListEntry |
801
811
  return matches.length === 1 ? matches[0] : undefined;
802
812
  }
803
813
 
814
+ export function wholeTableReadIntent(table: TableEntry, prompt: string): boolean {
815
+ const match = /\b(?:list|show|return|read|display)\s+(?:every|all)\s+([a-z][a-z-]*)\s+(?:in|from)\s+(?:the\s+)?([^\n.!?]+?)\s+table(?:\s+with\s+(?:its|their)\s+([^\n.!?]+))?\s*[.!]?$/i.exec(prompt);
816
+ if (!match) return false;
817
+ const heading = match[2].replace(/^["“]|["”]$/g, "").trim();
818
+ if (heading.toLowerCase() !== (table.heading.split(" > ").at(-1) ?? table.heading).toLowerCase()) return false;
819
+ if (!match[3]) return /^(?:rows?|entries|records?)$/i.test(match[1]) ||
820
+ match[1].toLowerCase().replace(/s$/, "") === table.columns[0]?.toLowerCase().replace(/s$/, "");
821
+ const columns = [match[1], ...match[3].split(/\s*,\s*|\s+and\s+/i)].map((column) => column.trim().toLowerCase().replace(/s$/, ""));
822
+ return columns.length === table.columns.length && table.columns.every((column, index) => column.toLowerCase().replace(/s$/, "") === columns[index]);
823
+ }
824
+
804
825
  function looksLikeTableRead(prompt: string): boolean {
805
826
  if (/\b(?:add|append|insert|update|change|delete|remove|sort|realign)\b/i.test(prompt)) return false;
806
827
  return /\b(?:find|which|what|show|list|query|look up)\b/i.test(prompt);
@@ -982,6 +1003,7 @@ async function routeForPrompt(
982
1003
  binary: ResolvedBinary,
983
1004
  prompt: string,
984
1005
  cwd: string,
1006
+ wholeTableRead = false,
985
1007
  ): Promise<RouteSpec | undefined> {
986
1008
  const found = extractMarkdownPath(prompt);
987
1009
  if (!found) return undefined;
@@ -1299,6 +1321,8 @@ async function routeForPrompt(
1299
1321
  schema,
1300
1322
  operation: "list-add-item",
1301
1323
  write: true,
1324
+ successDescription: `Applied: inserted ${JSON.stringify(append.text)} ${append.after
1325
+ ? `after ${JSON.stringify(append.after)} in` : "at the end of"} list ${JSON.stringify(selected.entry.heading)} (ordinal ${selected.entry.ordinal}).`,
1302
1326
  arguments: () => ({
1303
1327
  list: { heading: selected.entry.heading, ordinal: selected.entry.ordinal },
1304
1328
  text: append.text,
@@ -1446,7 +1470,7 @@ async function routeForPrompt(
1446
1470
  const ordinalRead = ordinalTableReadIntent(prompt);
1447
1471
  if (ordinalRead) {
1448
1472
  const result = await runIncise(pi.exec.bind(pi), binary.path, ["tables", path]);
1449
- if (result.code !== 0 || result.payload.ok === false) return undefined;
1473
+ if (result.code !== 0 || result.payload.ok === false || (wholeTableRead && typeof result.payload.hash !== "string")) return undefined;
1450
1474
  const tables = parseTableSummary(String(result.payload.text ?? "")).filter((table) => {
1451
1475
  const leaf = table.heading.split(" > ").at(-1) ?? table.heading;
1452
1476
  return leaf.toLowerCase() === ordinalRead.heading.toLowerCase();
@@ -1463,6 +1487,7 @@ async function routeForPrompt(
1463
1487
  return {
1464
1488
  kind: "table-query",
1465
1489
  path,
1490
+ readHash: wholeTableRead && typeof result.payload.hash === "string" ? result.payload.hash : undefined,
1466
1491
  schema,
1467
1492
  operation: "rows",
1468
1493
  write: false,
@@ -1472,20 +1497,23 @@ async function routeForPrompt(
1472
1497
  }
1473
1498
  if (!looksLikeTableRead(prompt)) return undefined;
1474
1499
  const result = await runIncise(pi.exec.bind(pi), binary.path, ["tables", path]);
1475
- if (result.code !== 0 || result.payload.ok === false) return undefined;
1500
+ if (result.code !== 0 || result.payload.ok === false || (wholeTableRead && typeof result.payload.hash !== "string")) return undefined;
1476
1501
  const table = requestedTable(parseTableSummary(String(result.payload.text ?? "")), prompt);
1477
1502
  if (!table) return undefined;
1478
1503
  const filters = tablePredicates(table.columns, prompt);
1479
- if (!filters || Object.keys(filters).length === 0) return undefined;
1504
+ if (!filters || (Object.keys(filters).length === 0 && !(wholeTableRead && wholeTableReadIntent(table, prompt)))) return undefined;
1480
1505
  const schema = tableSchema(table, filters);
1481
1506
  return {
1482
1507
  kind: "table-query",
1483
1508
  path,
1509
+ readHash: wholeTableRead && typeof result.payload.hash === "string" ? result.payload.hash : undefined,
1484
1510
  schema,
1485
1511
  operation: "rows",
1486
1512
  write: false,
1487
- arguments: () => ({ table: { heading: table.heading, ordinal: table.ordinal }, filter: filters }),
1488
- systemPrompt: `Incise resolved the requested table and exact filter values. Use table_query once with no arguments, then answer only from its returned rows.`,
1513
+ arguments: () => ({ table: { heading: table.heading, ordinal: table.ordinal }, ...(Object.keys(filters).length ? { filter: filters } : {}) }),
1514
+ systemPrompt: Object.keys(filters).length
1515
+ ? `Incise resolved the requested table and exact filter values. Use table_query once with no arguments, then answer only from its returned rows.`
1516
+ : `Incise resolved the requested whole table. Use table_query once with no arguments to return every row.`,
1489
1517
  };
1490
1518
  }
1491
1519
 
@@ -1494,9 +1522,15 @@ function toolResult(text: string, details: Record<string, unknown>) {
1494
1522
  }
1495
1523
 
1496
1524
  export interface SafeRoutedOptions {
1525
+ prepareWholeTableRead?(ctx: { model?: { id?: string; name?: string; provider?: string } }): boolean;
1526
+ nativeCompletion?(ctx: { model?: { id?: string; name?: string; provider?: string } }, kind: SafeRouteKind, prompt: string): boolean;
1527
+ useOperationDelta?(ctx: { model?: { id?: string; name?: string; provider?: string } }): boolean;
1528
+ requestPolicy?(ctx: { model?: { id?: string; name?: string; provider?: string } }, prompt: string): PreparedRequestPolicy | undefined;
1497
1529
  standardTools: string[];
1498
1530
  isEnabled(ctx: { model?: { id?: string; name?: string; provider?: string } }): boolean;
1499
1531
  useStructuredPrompt?(ctx: { model?: { id?: string; name?: string; provider?: string } }): boolean;
1532
+ completionPrompt?(ctx: { model?: { id?: string; name?: string; provider?: string } }): string | undefined;
1533
+ boundListReadback?(ctx: { model?: { id?: string; name?: string; provider?: string } }, kind: SafeRouteKind, prompt: string): boolean;
1500
1534
  onRoute?(kind: SafeRouteKind | "standard"): void;
1501
1535
  }
1502
1536
 
@@ -1506,6 +1540,7 @@ export function installSafeRoutedProfile(
1506
1540
  options: SafeRoutedOptions,
1507
1541
  ): void {
1508
1542
  const routedNames = new Set([
1543
+ "list_readback_target", "condition_result_target", "approval_request_target", "list_inspection_target",
1509
1544
  "section_rename_target", "section_replace_target", "section_insert_target",
1510
1545
  "section_append_target", "section_delete_target", "section_set_level_target",
1511
1546
  "frontmatter_clear", "frontmatter_set_string", "frontmatter_set_integer",
@@ -1517,11 +1552,89 @@ export function installSafeRoutedProfile(
1517
1552
  ]);
1518
1553
  const ownedNames = new Set([...options.standardTools, ...routedNames]);
1519
1554
  let state: RoutedState | undefined;
1555
+ let completionHookInstalled = false;
1556
+ let policyDeferredRead = false;
1557
+ let decisionToken: object | undefined;
1558
+ const restoreRead = (binding: RoutedState | undefined): void => {
1559
+ if (!binding?.deferredRead) return;
1560
+ binding.deferredRead = false;
1561
+ const active = pi.getActiveTools();
1562
+ if (!active.includes("read")) pi.setActiveTools([...active, "read"]);
1563
+ };
1564
+
1565
+ const installCompletionHook = (): void => {
1566
+ if (completionHookInstalled) return;
1567
+ completionHookInstalled = true;
1568
+ pi.on("context_with_system", (event) => {
1569
+ const completion = state?.completed ? state.completion : undefined;
1570
+ if (!completion) return;
1571
+ let changed = false;
1572
+ const messages = event.messages.map((message) => {
1573
+ if (message.role !== "system") return message;
1574
+ const section = message.sections?.incise_route;
1575
+ if (typeof section !== "string") return message;
1576
+ const index = section.lastIndexOf(completion.active);
1577
+ if (index < 0) return message;
1578
+ changed = true;
1579
+ return {
1580
+ ...message,
1581
+ sections: {
1582
+ ...message.sections,
1583
+ incise_route: section.slice(0, index) + completion.finished +
1584
+ section.slice(index + completion.active.length),
1585
+ },
1586
+ };
1587
+ });
1588
+ return changed ? { messages } : undefined;
1589
+ });
1590
+ };
1520
1591
 
1521
1592
  const activate = (names: string[]): void => {
1522
1593
  const foreign = pi.getActiveTools().filter((name) => !ownedNames.has(name));
1523
1594
  pi.setActiveTools([...foreign, ...names]);
1524
1595
  };
1596
+ const readbackPending = "The bound Incise operation has completed successfully. " +
1597
+ "Report the completed change. If read-back is needed, call list_readback_target once with no arguments " +
1598
+ "to receive the complete edited list. Do not request file pages or repeat the edit.";
1599
+ const readbackFinished = "The bound Incise operation has completed successfully. " +
1600
+ "The complete edited list has also been read back and is available in the tool result. " +
1601
+ "Report the completed change using that result. Do not repeat the edit or read-back.";
1602
+ const readbackDescription = "Read back the complete edited list resolved by Incise. " +
1603
+ "The host owns the file and list address; supply no arguments. No pagination is needed. " +
1604
+ "This tool is available once after the insertion succeeds.";
1605
+ const registerReadback = (binding: RoutedState): void => {
1606
+ pi.registerTool({
1607
+ name: "list_readback_target",
1608
+ label: "list_readback_target",
1609
+ description: readbackDescription,
1610
+ parameters: { type: "object", properties: {}, additionalProperties: false } as TSchema,
1611
+ async execute(_toolCallId, params, signal) {
1612
+ const readback = binding.readback;
1613
+ if (state !== binding || !binding.completed || !readback) throw new Error("No completed list insertion is awaiting read-back.");
1614
+ if (readback.completed || readback.running) throw new Error("This list read-back has already been requested.");
1615
+ if (Object.keys(params as Record<string, unknown>).length) throw new Error("The resolved list read-back takes no arguments.");
1616
+ readback.running = true;
1617
+ try {
1618
+ const result = await runIncise(pi.exec.bind(pi), binary.path,
1619
+ ["items", binding.spec.path, "--args", JSON.stringify(readback.arguments)], signal);
1620
+ if (result.code !== 0 || result.payload.ok === false) throw processError(result);
1621
+ if (!binding.resultHash || result.payload.hash !== binding.resultHash) {
1622
+ throw new Error("The document changed after the insertion; inspect the current file before continuing.");
1623
+ }
1624
+ readback.completed = true;
1625
+ if (binding.completion) binding.completion.finished = readbackFinished;
1626
+ if (state === binding) activate([]);
1627
+ return toolResult(String(result.payload.text ?? ""), {
1628
+ exitCode: result.code, hash: result.payload.hash, path: binding.spec.path,
1629
+ changed: false, route: "list-readback", validated: true,
1630
+ });
1631
+ } catch (error) {
1632
+ if (state === binding) restoreRead(binding);
1633
+ throw error;
1634
+ } finally { readback.running = false; }
1635
+ },
1636
+ });
1637
+ };
1525
1638
 
1526
1639
  const registerRoute = (spec: RouteSpec): void => {
1527
1640
  pi.registerTool({
@@ -1532,90 +1645,259 @@ export function installSafeRoutedProfile(
1532
1645
  async execute(_toolCallId, params, signal) {
1533
1646
  if (!state || state.spec !== spec) throw new Error("No matching routed Incise request is active.");
1534
1647
  if (state.completed) throw new Error("The requested Incise operation already succeeded.");
1535
- const args = spec.arguments(params as Record<string, unknown>);
1536
- const followups = spec.followups?.(params as Record<string, unknown>) ?? [];
1537
- const operations = [{ operation: spec.operation, arguments: args }, ...followups];
1538
- const invoke = async () => {
1539
- const original = followups.length > 0 ? await readFile(spec.path) : undefined;
1540
- let expectedHash = spec.hash;
1541
- let result: InciseResult | undefined;
1542
- for (let index = 0; index < operations.length; index += 1) {
1543
- const operation = operations[index];
1544
- const argv = [
1545
- operation.operation, spec.path,
1546
- "--args", JSON.stringify(operation.arguments),
1547
- ];
1548
- if (expectedHash) argv.push("--if-match", expectedHash);
1549
- result = await runIncise(pi.exec.bind(pi), binary.path, argv, signal);
1550
- if (result.code !== 0 || result.payload.ok === false) {
1551
- if (original && index > 0) await writeFile(spec.path, original);
1552
- return result;
1648
+ const binding = state;
1649
+ let succeeded = false;
1650
+ try {
1651
+ const args = spec.arguments(params as Record<string, unknown>);
1652
+ const followups = spec.followups?.(params as Record<string, unknown>) ?? [];
1653
+ const operations = [{ operation: spec.operation, arguments: args }, ...followups];
1654
+ const invoke = async () => {
1655
+ const original = followups.length > 0 ? await readFile(spec.path) : undefined;
1656
+ let expectedHash = spec.hash;
1657
+ let result: InciseResult | undefined;
1658
+ const descriptions: string[] = [];
1659
+ for (let index = 0; index < operations.length; index += 1) {
1660
+ const operation = operations[index];
1661
+ const argv = [
1662
+ operation.operation, spec.path,
1663
+ "--args", JSON.stringify(operation.arguments),
1664
+ ];
1665
+ if (expectedHash) argv.push("--if-match", expectedHash);
1666
+ result = await runIncise(pi.exec.bind(pi), binary.path, argv, signal);
1667
+ if (result.code !== 0 || result.payload.ok === false) {
1668
+ if (original && index > 0) {
1669
+ const current = await readFile(spec.path).catch(() => undefined);
1670
+ if (current && expectedHash && createHash("sha256").update(current).digest("hex") === expectedHash) {
1671
+ await writeFile(spec.path, original);
1672
+ } else {
1673
+ result.payload.error = `${result.payload.error ?? "The follow-up operation failed."} ` +
1674
+ "The document changed outside this operation; current contents were preserved. Earlier successful steps may remain.";
1675
+ }
1676
+ }
1677
+ return result;
1678
+ }
1679
+ if (typeof result.payload.description === "string") descriptions.push(result.payload.description);
1680
+ expectedHash = typeof result.payload.hash === "string"
1681
+ ? result.payload.hash : undefined;
1553
1682
  }
1554
- expectedHash = typeof result.payload.hash === "string"
1555
- ? result.payload.hash : undefined;
1683
+ if (!result) throw new Error("Routed Incise request had no operations.");
1684
+ if (binding.terminate && descriptions.length > 1) result.payload.description = descriptions.join("\n");
1685
+ return result;
1686
+ };
1687
+ const result = spec.write
1688
+ ? await withFileMutationQueue(spec.path, invoke)
1689
+ : await invoke();
1690
+ if (result.code !== 0 || result.payload.ok === false) throw processError(result);
1691
+ if (spec.readHash && result.payload.hash !== spec.readHash) {
1692
+ throw new Error("The document changed after table resolution; request a fresh inspection before reporting rows.");
1556
1693
  }
1557
- if (!result) throw new Error("Routed Incise request had no operations.");
1558
- return result;
1559
- };
1560
- const result = spec.write
1561
- ? await withFileMutationQueue(spec.path, invoke)
1562
- : await invoke();
1563
- if (result.code !== 0 || result.payload.ok === false) throw processError(result);
1564
- state.completed = true;
1565
- activate([]);
1566
- return toolResult(
1567
- spec.write ? String(result.payload.description ?? "") : String(result.payload.text ?? ""),
1568
- {
1569
- exitCode: result.code,
1570
- hash: result.payload.hash,
1571
- path: result.payload.path ?? spec.path,
1572
- changed: Boolean(result.payload.changed),
1573
- rows: result.payload.rows,
1574
- route: spec.kind,
1575
- resolvedArguments: spec.resolvedArguments?.(
1576
- params as Record<string, unknown>,
1577
- ) ?? args,
1578
- validated: true,
1579
- },
1580
- );
1694
+ binding.completed = true;
1695
+ binding.resultHash = typeof result.payload.hash === "string" ? result.payload.hash : undefined;
1696
+ if (binding.readback && binding.completion) binding.completion.finished = readbackPending;
1697
+ if (state === binding) activate(binding.readback ? ["list_readback_target"] : []);
1698
+ const reply = toolResult(
1699
+ spec.write ? String(binding.operationDelta && result.payload.changed === true
1700
+ ? spec.successDescription ?? result.payload.description ?? ""
1701
+ : result.payload.description ?? "") : String(result.payload.text ?? ""),
1702
+ {
1703
+ exitCode: result.code,
1704
+ hash: result.payload.hash,
1705
+ path: result.payload.path ?? spec.path,
1706
+ changed: Boolean(result.payload.changed),
1707
+ rows: result.payload.rows,
1708
+ route: spec.kind,
1709
+ resolvedArguments: spec.resolvedArguments?.(
1710
+ params as Record<string, unknown>,
1711
+ ) ?? args,
1712
+ validated: true,
1713
+ },
1714
+ );
1715
+ succeeded = true;
1716
+ return binding.terminate ? { ...reply, terminate: true } : reply;
1717
+ } finally {
1718
+ if (state === binding && (!succeeded || !binding.readback)) restoreRead(binding);
1719
+ }
1581
1720
  },
1582
1721
  });
1583
1722
  };
1584
1723
 
1585
1724
  pi.on("before_agent_start", async (event, ctx) => {
1725
+ restoreRead(state);
1726
+ if (policyDeferredRead) {
1727
+ const active = pi.getActiveTools();
1728
+ if (!active.includes("read")) pi.setActiveTools([...active, "read"]);
1729
+ policyDeferredRead = false;
1730
+ }
1586
1731
  state = undefined;
1732
+ decisionToken = undefined;
1587
1733
  if (!options.isEnabled(ctx) || !("prompt" in event)) {
1588
1734
  options.onRoute?.("standard");
1589
1735
  activate(options.standardTools);
1590
1736
  return;
1591
1737
  }
1592
- const spec = await routeForPrompt(pi, binary, event.prompt, ctx.cwd);
1738
+ let policy = options.requestPolicy?.(ctx, event.prompt);
1739
+ let conditionHash: string | undefined;
1740
+ let falseCondition: { path: string; hash: string; heading: string } | undefined;
1741
+ if (policy?.mode === "conditional" && policy.headingCondition) {
1742
+ const found = extractMarkdownPath(event.prompt);
1743
+ if (found) {
1744
+ const result = await runIncise(pi.exec.bind(pi), binary.path, ["outline", resolve(ctx.cwd, found)]);
1745
+ if (result.code === 0 && result.payload.ok !== false && typeof result.payload.hash === "string") {
1746
+ const heading = policy.headingCondition.heading;
1747
+ const present = parseOutline(String(result.payload.text ?? "")).some((entry) => entry.heading === heading || entry.path === heading);
1748
+ if (present && policy.headingCondition.prepareWhenPresent) conditionHash = result.payload.hash;
1749
+ else if (!present) {
1750
+ falseCondition = { path: resolve(ctx.cwd, found), hash: result.payload.hash, heading };
1751
+ policy = { mode: "read-only", inspectionComplete: true, context:
1752
+ `Incise inspected the document: heading ${JSON.stringify(heading)} does not exist. ` +
1753
+ "The requested condition is false. Leave the document unchanged. Mutation tools are withheld." };
1754
+ }
1755
+ }
1756
+ }
1757
+ }
1758
+ const spec = !policy || conditionHash ? await routeForPrompt(pi, binary, event.prompt, ctx.cwd, options.prepareWholeTableRead?.(ctx)) : undefined;
1759
+ if (conditionHash && spec?.hash === conditionHash) policy = undefined;
1760
+ if (policy) {
1761
+ const reads = new Set(["table_get", "md_tables", "md_lists", "md_outline"]);
1762
+ activate(policy.inspectionComplete ? [] : options.standardTools.filter((name) => reads.has(name)));
1763
+ if (policy.listInspection && options.nativeCompletion?.(ctx, "list-inspection", event.prompt)) {
1764
+ const found = extractMarkdownPath(event.prompt);
1765
+ if (found) {
1766
+ const path = resolve(ctx.cwd, found);
1767
+ const summary = await runIncise(pi.exec.bind(pi), binary.path, ["lists", path]);
1768
+ const selected = summary.code === 0 && summary.payload.ok !== false
1769
+ ? resolveListEntry(parseListSummary(String(summary.payload.text ?? "")).filter((entry) => entry.loose === policy!.listInspection!.loose), policy.listInspection.heading) : undefined;
1770
+ if (selected) {
1771
+ const args = { list: { heading: selected.heading, ordinal: selected.ordinal } };
1772
+ const inspected = await runIncise(pi.exec.bind(pi), binary.path, ["items", path, "--args", JSON.stringify(args)]);
1773
+ const expectedHash = inspected.payload.hash;
1774
+ const once = policy.listInspection.exactlyOnce;
1775
+ if (inspected.code === 0 && inspected.payload.ok !== false && typeof expectedHash === "string" && expectedHash === summary.payload.hash &&
1776
+ (once === undefined || listItems(inspected.payload, selected).filter((item) => item.text === once).length === 1)) {
1777
+ const token = decisionToken = {};
1778
+ const description = "Return the complete host-resolved list item texts and count without editing; supply no arguments. Ends the turn with the actual Incise report.";
1779
+ pi.registerTool({ name: "list_inspection_target", label: "list_inspection_target", description,
1780
+ parameters: { type: "object", properties: {}, additionalProperties: false } as TSchema,
1781
+ async execute(_id, params, signal) {
1782
+ if (decisionToken !== token) throw new Error("This list inspection is no longer active.");
1783
+ if (Object.keys(params as Record<string, unknown>).length) throw new Error("The resolved list inspection takes no arguments.");
1784
+ const current = await runIncise(pi.exec.bind(pi), binary.path, ["items", path, "--args", JSON.stringify(args)], signal);
1785
+ if (current.code !== 0 || current.payload.ok === false) throw processError(current);
1786
+ if (current.payload.hash !== expectedHash) throw new Error("The document changed after list inspection; request a fresh evaluation.");
1787
+ decisionToken = undefined;
1788
+ const prefix = once === undefined ? "" : `Unchanged: this list already contains exactly one item ${JSON.stringify(once)}; no edit was performed.\n\n`;
1789
+ return { ...toolResult(prefix + String(current.payload.text ?? ""), { path, hash: expectedHash, changed: false, validated: true, route: "list-inspection", resolvedArguments: args }), terminate: true };
1790
+ },
1791
+ });
1792
+ activate(["list_inspection_target"]);
1793
+ policy = { ...policy, inspectionComplete: true, context:
1794
+ "Incise resolved and inspected the requested list. Use list_inspection_target once with no arguments to return its exact item texts and count without editing." };
1795
+ if (event.systemPromptOptions) event.systemPromptOptions.toolSnippets.list_inspection_target = description;
1796
+ }
1797
+ }
1798
+ }
1799
+ }
1800
+ if (policy.approvalRequired && options.nativeCompletion?.(ctx, "approval-request", event.prompt)) {
1801
+ const token = decisionToken = {};
1802
+ const description = "Ask for the user-required approval without making an edit or inventing a preview. Supply no arguments; ends the turn with the approval question.";
1803
+ pi.registerTool({ name: "approval_request_target", label: "approval_request_target", description,
1804
+ parameters: { type: "object", properties: {}, additionalProperties: false } as TSchema,
1805
+ async execute(_id, params) {
1806
+ if (decisionToken !== token) throw new Error("This approval request is no longer active.");
1807
+ if (Object.keys(params as Record<string, unknown>).length) throw new Error("The approval request takes no arguments.");
1808
+ decisionToken = undefined;
1809
+ return { ...toolResult("No Incise edit was performed. May I proceed with your requested edit?",
1810
+ { changed: false, validated: true, route: "approval-request" }), terminate: true };
1811
+ },
1812
+ });
1813
+ activate(["approval_request_target"]);
1814
+ policy = { ...policy, inspectionComplete: true, context:
1815
+ "The user requires approval before any edit. Use approval_request_target once with no arguments to ask the approval question and finish. No edit is authorized yet." };
1816
+ if (event.systemPromptOptions) event.systemPromptOptions.toolSnippets.approval_request_target = description;
1817
+ }
1818
+ if (falseCondition && options.nativeCompletion?.(ctx, "condition-result", event.prompt)) {
1819
+ const decision = falseCondition;
1820
+ const token = decisionToken = {};
1821
+ const description = "Report the host-verified unmet heading prerequisite without editing; supply no arguments. Ends this turn with the factual Incise result.";
1822
+ pi.registerTool({ name: "condition_result_target", label: "condition_result_target", description,
1823
+ parameters: { type: "object", properties: {}, additionalProperties: false } as TSchema,
1824
+ async execute(_id, params, signal) {
1825
+ if (decisionToken !== token) throw new Error("This condition report is no longer active.");
1826
+ if (Object.keys(params as Record<string, unknown>).length) throw new Error("The resolved condition report takes no arguments.");
1827
+ const checked = await runIncise(pi.exec.bind(pi), binary.path, ["outline", decision.path], signal);
1828
+ if (checked.code !== 0 || checked.payload.ok === false) throw processError(checked);
1829
+ if (checked.payload.hash !== decision.hash) throw new Error("The document changed after condition inspection; request a fresh evaluation.");
1830
+ decisionToken = undefined;
1831
+ return { ...toolResult(`Unchanged: heading ${JSON.stringify(decision.heading)} does not exist. The requested condition is false; no edit was performed.`,
1832
+ { hash: decision.hash, path: decision.path, changed: false, validated: true, route: "condition-result" }), terminate: true };
1833
+ },
1834
+ });
1835
+ activate(["condition_result_target"]);
1836
+ policy.context += " Use condition_result_target once with no arguments to report this verified result and finish.";
1837
+ if (event.systemPromptOptions) event.systemPromptOptions.toolSnippets.condition_result_target = description;
1838
+ }
1839
+ if (policy.inspectionComplete && pi.getActiveTools().includes("read")) {
1840
+ policyDeferredRead = true;
1841
+ pi.setActiveTools(pi.getActiveTools().filter((name) => name !== "read"));
1842
+ }
1843
+ options.onRoute?.("standard");
1844
+ if (options.useStructuredPrompt?.(ctx) && event.systemPromptOptions &&
1845
+ event.systemPromptOptions.forceSystemPrompt === undefined) {
1846
+ event.systemPromptOptions.selectedTools = pi.getActiveTools();
1847
+ const previous = event.systemPromptOptions.sections.incise_route;
1848
+ event.systemPromptOptions.sections.incise_route = previous
1849
+ ? `${previous}\n\n${policy.context}` : policy.context;
1850
+ return;
1851
+ }
1852
+ return { systemPrompt: `${event.systemPrompt}\n\n${policy.context}` };
1853
+ }
1593
1854
  if (!spec) {
1594
1855
  options.onRoute?.("standard");
1595
1856
  activate(options.standardTools);
1596
1857
  return;
1597
1858
  }
1598
- state = { spec, completed: false };
1859
+ state = { spec, completed: false, operationDelta: options.useOperationDelta?.(ctx),
1860
+ terminate: options.nativeCompletion?.(ctx, spec.kind, event.prompt) };
1599
1861
  registerRoute(spec);
1600
1862
  options.onRoute?.(spec.kind);
1601
1863
  activate([spec.schema.name]);
1602
1864
  const structured = options.useStructuredPrompt?.(ctx);
1603
- const routePrompt = structured && spec.inspection
1865
+ let routePrompt = structured && spec.inspection
1604
1866
  ? `${spec.inspection}\n\n${spec.systemPrompt}` : spec.systemPrompt;
1867
+ if (state.terminate && !spec.write) routePrompt += "\n\nThis prepared read ends the turn with the actual Incise table report; no additional summary is needed.";
1605
1868
  if (structured && event.systemPromptOptions &&
1606
1869
  event.systemPromptOptions.forceSystemPrompt === undefined) {
1607
- const active = pi.getActiveTools();
1870
+ let active = pi.getActiveTools();
1608
1871
  if (!active.includes(spec.schema.name)) {
1609
1872
  state = undefined;
1610
1873
  activate(options.standardTools);
1611
1874
  options.onRoute?.("standard");
1612
1875
  return;
1613
1876
  }
1877
+ if (state.terminate && active.includes("read")) {
1878
+ state.deferredRead = true;
1879
+ pi.setActiveTools(active.filter((name) => name !== "read"));
1880
+ active = pi.getActiveTools();
1881
+ }
1882
+ if (!state.terminate && spec.kind === "list-append-target" && active.includes("read") &&
1883
+ options.boundListReadback?.(ctx, spec.kind, event.prompt)) {
1884
+ state.deferredRead = true;
1885
+ state.readback = { arguments: { list: spec.arguments({}).list }, completed: false, running: false };
1886
+ registerReadback(state);
1887
+ event.systemPromptOptions.toolSnippets.list_readback_target = readbackDescription;
1888
+ pi.setActiveTools(active.filter((name) => name !== "read"));
1889
+ active = pi.getActiveTools();
1890
+ }
1614
1891
  event.systemPromptOptions.selectedTools = active;
1615
1892
  event.systemPromptOptions.toolSnippets[spec.schema.name] = spec.schema.description;
1616
1893
  const previous = event.systemPromptOptions.sections.incise_route;
1617
1894
  event.systemPromptOptions.sections.incise_route = previous
1618
1895
  ? `${previous}\n\n${routePrompt}` : routePrompt;
1896
+ const completion = options.completionPrompt?.(ctx);
1897
+ if (completion) {
1898
+ state.completion = { active: routePrompt, finished: completion };
1899
+ installCompletionHook();
1900
+ }
1619
1901
  return;
1620
1902
  }
1621
1903
  return { systemPrompt: `${event.systemPrompt}\n\n${routePrompt}` };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-incise",
3
- "version": "0.6.0",
4
- "description": "Structured Markdown editing for Pi, with measured Inkling 2 Mini profiles and byte preservation",
3
+ "version": "0.8.0",
4
+ "description": "Structured Markdown editing for Pi, with byte-preserving tools and local-model profiles",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Peter Dalinis",
@@ -22,7 +22,8 @@
22
22
  "obsidian",
23
23
  "knowledge-base",
24
24
  "inkling",
25
- "local-llm"
25
+ "local-llm",
26
+ "sensenova"
26
27
  ],
27
28
  "engines": {
28
29
  "node": ">=22.19.0"
@@ -52,10 +53,10 @@
52
53
  "typescript": "^5.9.3"
53
54
  },
54
55
  "optionalDependencies": {
55
- "@pdalinis/pi-incise-darwin-arm64": "0.6.0",
56
- "@pdalinis/pi-incise-darwin-x64": "0.6.0",
57
- "@pdalinis/pi-incise-linux-arm64-gnu": "0.6.0",
58
- "@pdalinis/pi-incise-linux-x64-gnu": "0.6.0"
56
+ "@pdalinis/pi-incise-darwin-arm64": "0.8.0",
57
+ "@pdalinis/pi-incise-darwin-x64": "0.8.0",
58
+ "@pdalinis/pi-incise-linux-arm64-gnu": "0.8.0",
59
+ "@pdalinis/pi-incise-linux-x64-gnu": "0.8.0"
59
60
  },
60
61
  "scripts": {
61
62
  "test": "node --test --experimental-strip-types test/*.test.ts",