pi-incise 0.7.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,25 +34,27 @@ 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
- ## Experimental SenseNova Loop 9B Q8
37
+ ## SenseNova Loop 9B Q8
38
38
 
39
- Incise 0.7.0 adds an experimental Pi 1.7.0 path for the exact local model ID `sensenova-loop-9b-q8`. The broader qualification did not pass: eight of ten attempted tasks completed correctly, then the run stopped after two read loops left their files unchanged; 38 of the planned 48 tasks remain untested. Explicitly select `INCISE_PROFILE=safe-routed` to use structured framing and completed-operation context. The `auto` profile retains standard tools for this unqualified identity; other model identities retain their existing prompt paths.
39
+ <a id="experimental-sensenova-loop-9b-q8"></a>
40
40
 
41
- Install with `pi install npm:pi-incise@0.7.0`. Merge the [provider example](../../bench/sensenova_loop_9b_q8_pi_models.example.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. This recipe explicitly sends `chat_template_kwargs.enable_thinking=false`; the recorded server template does not support native `reasoning_effort`.
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
42
 
43
- For an isolated experiment after installation and provider setup:
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`.
44
46
 
45
47
  ```bash
46
- INCISE_PROFILE=safe-routed pi -e npm:pi-incise@0.7.0 \
48
+ INCISE_PROFILE=safe-routed pi -e npm:pi-incise@0.8.0 \
47
49
  --provider sensenova-local --model sensenova-loop-9b-q8 \
48
- --tools 'read,table_*,list_*,section_*,frontmatter_*,md_*' \
50
+ --tools 'read,table_*,list_*,section_*,frontmatter_*,md_*,approval_*,condition_*' \
49
51
  --no-extensions --no-mcp --no-skills --no-context-files \
50
52
  --no-prompt-templates --no-session --thinking off
51
53
  ```
52
54
 
53
- Keep the real built-in reader available and all writes through Incise. The actual CLI allowlist was checked against a fake provider with a byte-correct edit and real post-edit read; this is packaging evidence, not model accuracy. Live SDK tests additionally restrict reads to the current fixture and allow six assistant turns. The command above uses Pi's ordinary reader; it does not install the benchmark-only read restriction or turn cap. Unrestricted interactive use remains unqualified.
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.
54
56
 
55
- The selected feasibility screen completed four cases, one per editing family, with correct documents, resolved replies and no tool errors. Median latency was 99.43 seconds, range 38.94–192.32. Its list reply finished on turn six with the worker cap flag retained. Earlier configurations produced correct edits followed by unexecuted tool markup. The [experiment report](../../bench/SENSENOVA_LOOP_9B_Q8_20261130.md) retains these failures and records the separate full-population release gate at fresh seed 3. Automatic-family, multi-seed and Hermes support remain unqualified. Run `/incise-doctor` to inspect the effective profile and binary.
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.
56
58
 
57
59
  ## Tools
58
60
 
@@ -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,6 +209,21 @@ 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
228
  return modelFamily(ctx.model, familyOverride) === "inkling" ||
213
229
  ctx.model?.id === "sensenova-loop-9b-q8";
@@ -219,6 +235,10 @@ export default async function inciseExtension(pi: ExtensionAPI): Promise<void> {
219
235
  "Do not repeat the completed operation or invent additional work. " +
220
236
  "Follow any remaining user-requested steps using only tools that are currently available.";
221
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);
241
+ },
222
242
  isEnabled(ctx) {
223
243
  if (!decision && ctx.model) {
224
244
  decision = selectProfile(profile, ctx.model, familyOverride);
@@ -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,7 +157,12 @@ interface RouteSpec {
153
157
  interface RoutedState {
154
158
  spec: RouteSpec;
155
159
  completed: boolean;
160
+ operationDelta?: boolean;
161
+ terminate?: boolean;
156
162
  completion?: { active: string; finished: string };
163
+ deferredRead?: boolean;
164
+ resultHash?: string;
165
+ readback?: { arguments: Record<string, unknown>; completed: boolean; running: boolean };
157
166
  }
158
167
 
159
168
  export function sectionIntent(prompt: string): { kind: "section-rename"; target: string; heading: string } |
@@ -802,6 +811,17 @@ function resolveListEntry(entries: ListEntry[], requested: string): ListEntry |
802
811
  return matches.length === 1 ? matches[0] : undefined;
803
812
  }
804
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
+
805
825
  function looksLikeTableRead(prompt: string): boolean {
806
826
  if (/\b(?:add|append|insert|update|change|delete|remove|sort|realign)\b/i.test(prompt)) return false;
807
827
  return /\b(?:find|which|what|show|list|query|look up)\b/i.test(prompt);
@@ -983,6 +1003,7 @@ async function routeForPrompt(
983
1003
  binary: ResolvedBinary,
984
1004
  prompt: string,
985
1005
  cwd: string,
1006
+ wholeTableRead = false,
986
1007
  ): Promise<RouteSpec | undefined> {
987
1008
  const found = extractMarkdownPath(prompt);
988
1009
  if (!found) return undefined;
@@ -1300,6 +1321,8 @@ async function routeForPrompt(
1300
1321
  schema,
1301
1322
  operation: "list-add-item",
1302
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}).`,
1303
1326
  arguments: () => ({
1304
1327
  list: { heading: selected.entry.heading, ordinal: selected.entry.ordinal },
1305
1328
  text: append.text,
@@ -1447,7 +1470,7 @@ async function routeForPrompt(
1447
1470
  const ordinalRead = ordinalTableReadIntent(prompt);
1448
1471
  if (ordinalRead) {
1449
1472
  const result = await runIncise(pi.exec.bind(pi), binary.path, ["tables", path]);
1450
- 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;
1451
1474
  const tables = parseTableSummary(String(result.payload.text ?? "")).filter((table) => {
1452
1475
  const leaf = table.heading.split(" > ").at(-1) ?? table.heading;
1453
1476
  return leaf.toLowerCase() === ordinalRead.heading.toLowerCase();
@@ -1464,6 +1487,7 @@ async function routeForPrompt(
1464
1487
  return {
1465
1488
  kind: "table-query",
1466
1489
  path,
1490
+ readHash: wholeTableRead && typeof result.payload.hash === "string" ? result.payload.hash : undefined,
1467
1491
  schema,
1468
1492
  operation: "rows",
1469
1493
  write: false,
@@ -1473,20 +1497,23 @@ async function routeForPrompt(
1473
1497
  }
1474
1498
  if (!looksLikeTableRead(prompt)) return undefined;
1475
1499
  const result = await runIncise(pi.exec.bind(pi), binary.path, ["tables", path]);
1476
- 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;
1477
1501
  const table = requestedTable(parseTableSummary(String(result.payload.text ?? "")), prompt);
1478
1502
  if (!table) return undefined;
1479
1503
  const filters = tablePredicates(table.columns, prompt);
1480
- if (!filters || Object.keys(filters).length === 0) return undefined;
1504
+ if (!filters || (Object.keys(filters).length === 0 && !(wholeTableRead && wholeTableReadIntent(table, prompt)))) return undefined;
1481
1505
  const schema = tableSchema(table, filters);
1482
1506
  return {
1483
1507
  kind: "table-query",
1484
1508
  path,
1509
+ readHash: wholeTableRead && typeof result.payload.hash === "string" ? result.payload.hash : undefined,
1485
1510
  schema,
1486
1511
  operation: "rows",
1487
1512
  write: false,
1488
- arguments: () => ({ table: { heading: table.heading, ordinal: table.ordinal }, filter: filters }),
1489
- 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.`,
1490
1517
  };
1491
1518
  }
1492
1519
 
@@ -1495,10 +1522,15 @@ function toolResult(text: string, details: Record<string, unknown>) {
1495
1522
  }
1496
1523
 
1497
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;
1498
1529
  standardTools: string[];
1499
1530
  isEnabled(ctx: { model?: { id?: string; name?: string; provider?: string } }): boolean;
1500
1531
  useStructuredPrompt?(ctx: { model?: { id?: string; name?: string; provider?: string } }): boolean;
1501
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;
1502
1534
  onRoute?(kind: SafeRouteKind | "standard"): void;
1503
1535
  }
1504
1536
 
@@ -1508,6 +1540,7 @@ export function installSafeRoutedProfile(
1508
1540
  options: SafeRoutedOptions,
1509
1541
  ): void {
1510
1542
  const routedNames = new Set([
1543
+ "list_readback_target", "condition_result_target", "approval_request_target", "list_inspection_target",
1511
1544
  "section_rename_target", "section_replace_target", "section_insert_target",
1512
1545
  "section_append_target", "section_delete_target", "section_set_level_target",
1513
1546
  "frontmatter_clear", "frontmatter_set_string", "frontmatter_set_integer",
@@ -1520,6 +1553,14 @@ export function installSafeRoutedProfile(
1520
1553
  const ownedNames = new Set([...options.standardTools, ...routedNames]);
1521
1554
  let state: RoutedState | undefined;
1522
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
+ };
1523
1564
 
1524
1565
  const installCompletionHook = (): void => {
1525
1566
  if (completionHookInstalled) return;
@@ -1552,6 +1593,48 @@ export function installSafeRoutedProfile(
1552
1593
  const foreign = pi.getActiveTools().filter((name) => !ownedNames.has(name));
1553
1594
  pi.setActiveTools([...foreign, ...names]);
1554
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
+ };
1555
1638
 
1556
1639
  const registerRoute = (spec: RouteSpec): void => {
1557
1640
  pi.registerTool({
@@ -1563,85 +1646,248 @@ export function installSafeRoutedProfile(
1563
1646
  if (!state || state.spec !== spec) throw new Error("No matching routed Incise request is active.");
1564
1647
  if (state.completed) throw new Error("The requested Incise operation already succeeded.");
1565
1648
  const binding = state;
1566
- const args = spec.arguments(params as Record<string, unknown>);
1567
- const followups = spec.followups?.(params as Record<string, unknown>) ?? [];
1568
- const operations = [{ operation: spec.operation, arguments: args }, ...followups];
1569
- const invoke = async () => {
1570
- const original = followups.length > 0 ? await readFile(spec.path) : undefined;
1571
- let expectedHash = spec.hash;
1572
- let result: InciseResult | undefined;
1573
- for (let index = 0; index < operations.length; index += 1) {
1574
- const operation = operations[index];
1575
- const argv = [
1576
- operation.operation, spec.path,
1577
- "--args", JSON.stringify(operation.arguments),
1578
- ];
1579
- if (expectedHash) argv.push("--if-match", expectedHash);
1580
- result = await runIncise(pi.exec.bind(pi), binary.path, argv, signal);
1581
- if (result.code !== 0 || result.payload.ok === false) {
1582
- if (original && index > 0) await writeFile(spec.path, original);
1583
- return result;
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;
1584
1682
  }
1585
- expectedHash = typeof result.payload.hash === "string"
1586
- ? 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.");
1587
1693
  }
1588
- if (!result) throw new Error("Routed Incise request had no operations.");
1589
- return result;
1590
- };
1591
- const result = spec.write
1592
- ? await withFileMutationQueue(spec.path, invoke)
1593
- : await invoke();
1594
- if (result.code !== 0 || result.payload.ok === false) throw processError(result);
1595
- binding.completed = true;
1596
- if (state === binding) activate([]);
1597
- return toolResult(
1598
- spec.write ? String(result.payload.description ?? "") : String(result.payload.text ?? ""),
1599
- {
1600
- exitCode: result.code,
1601
- hash: result.payload.hash,
1602
- path: result.payload.path ?? spec.path,
1603
- changed: Boolean(result.payload.changed),
1604
- rows: result.payload.rows,
1605
- route: spec.kind,
1606
- resolvedArguments: spec.resolvedArguments?.(
1607
- params as Record<string, unknown>,
1608
- ) ?? args,
1609
- validated: true,
1610
- },
1611
- );
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
+ }
1612
1720
  },
1613
1721
  });
1614
1722
  };
1615
1723
 
1616
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
+ }
1617
1731
  state = undefined;
1732
+ decisionToken = undefined;
1618
1733
  if (!options.isEnabled(ctx) || !("prompt" in event)) {
1619
1734
  options.onRoute?.("standard");
1620
1735
  activate(options.standardTools);
1621
1736
  return;
1622
1737
  }
1623
- 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
+ }
1624
1854
  if (!spec) {
1625
1855
  options.onRoute?.("standard");
1626
1856
  activate(options.standardTools);
1627
1857
  return;
1628
1858
  }
1629
- state = { spec, completed: false };
1859
+ state = { spec, completed: false, operationDelta: options.useOperationDelta?.(ctx),
1860
+ terminate: options.nativeCompletion?.(ctx, spec.kind, event.prompt) };
1630
1861
  registerRoute(spec);
1631
1862
  options.onRoute?.(spec.kind);
1632
1863
  activate([spec.schema.name]);
1633
1864
  const structured = options.useStructuredPrompt?.(ctx);
1634
- const routePrompt = structured && spec.inspection
1865
+ let routePrompt = structured && spec.inspection
1635
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.";
1636
1868
  if (structured && event.systemPromptOptions &&
1637
1869
  event.systemPromptOptions.forceSystemPrompt === undefined) {
1638
- const active = pi.getActiveTools();
1870
+ let active = pi.getActiveTools();
1639
1871
  if (!active.includes(spec.schema.name)) {
1640
1872
  state = undefined;
1641
1873
  activate(options.standardTools);
1642
1874
  options.onRoute?.("standard");
1643
1875
  return;
1644
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
+ }
1645
1891
  event.systemPromptOptions.selectedTools = active;
1646
1892
  event.systemPromptOptions.toolSnippets[spec.schema.name] = spec.schema.description;
1647
1893
  const previous = event.systemPromptOptions.sections.incise_route;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-incise",
3
- "version": "0.7.0",
4
- "description": "Structured Markdown editing for Pi, with qualified local-model profiles and experimental SenseNova Loop 9B integration",
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",
@@ -53,10 +53,10 @@
53
53
  "typescript": "^5.9.3"
54
54
  },
55
55
  "optionalDependencies": {
56
- "@pdalinis/pi-incise-darwin-arm64": "0.7.0",
57
- "@pdalinis/pi-incise-darwin-x64": "0.7.0",
58
- "@pdalinis/pi-incise-linux-arm64-gnu": "0.7.0",
59
- "@pdalinis/pi-incise-linux-x64-gnu": "0.7.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"
60
60
  },
61
61
  "scripts": {
62
62
  "test": "node --test --experimental-strip-types test/*.test.ts",