notesoup 0.40.0 → 0.42.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/dist/src/boot/render.js +1 -1
- package/dist/src/boot/text.d.ts +12 -0
- package/dist/src/boot/text.js +25 -5
- package/dist/src/budget/policy.js +1 -1
- package/dist/src/budget/text.d.ts +12 -0
- package/dist/src/budget/text.js +13 -1
- package/dist/src/claude/helper.js +23 -2
- package/dist/src/claude/thresholds.d.ts +39 -0
- package/dist/src/claude/thresholds.js +149 -0
- package/dist/src/dream/doctor.js +3 -2
- package/dist/src/dream/git.js +2 -1
- package/dist/src/dream/jail.js +10 -10
- package/dist/src/dream/report.js +3 -2
- package/dist/src/error-message.d.ts +2 -0
- package/dist/src/error-message.js +4 -0
- package/dist/src/history/history.js +1 -1
- package/dist/src/history/query.js +6 -6
- package/dist/src/notes/address.d.ts +1 -1
- package/dist/src/notes/address.js +12 -12
- package/dist/src/notes/store.js +16 -12
- package/dist/src/pi/anchored.d.ts +16 -0
- package/dist/src/pi/anchored.js +55 -0
- package/dist/src/pi/budget.d.ts +1 -1
- package/dist/src/pi/budget.js +33 -28
- package/dist/src/pi/dream/cli.js +3 -2
- package/dist/src/pi/dream/runner.js +2 -1
- package/dist/src/pi/reset/lifecycle.d.ts +1 -1
- package/dist/src/pi/reset/lifecycle.js +4 -3
- package/dist/src/pi/reset/text.d.ts +3 -4
- package/dist/src/pi/reset/text.js +5 -4
- package/dist/src/pi/runtime.js +13 -16
- package/dist/src/pi/thresholds.js +2 -1
- package/dist/src/pi/tool-result.js +2 -2
- package/dist/src/settings.d.ts +8 -0
- package/dist/src/settings.js +6 -1
- package/dist/src/tools/history.js +12 -12
- package/dist/src/tools/notes.d.ts +3 -3
- package/dist/src/tools/notes.js +12 -11
- package/dist/src/tools/output.d.ts +2 -0
- package/dist/src/tools/output.js +2 -0
- package/dist/src/tools/result.js +2 -2
- package/dist/src/tools/schema.js +3 -3
- package/dist/test/agent-loop.test.js +78 -28
- package/dist/test/boot.integration.test.js +5 -5
- package/dist/test/budget-settings.integration.test.js +9 -8
- package/dist/test/claude-mod.test.js +213 -23
- package/dist/test/dream.test.js +3 -3
- package/dist/test/history.integration.test.js +7 -8
- package/dist/test/host-neutral.test.js +2 -2
- package/dist/test/notes-library.test.js +1 -1
- package/dist/test/notes.integration.test.js +5 -5
- package/dist/test/notes.test.js +16 -16
- package/dist/test/reset-lifecycle.test.js +2 -2
- package/docs/claude-code-mod.md +10 -2
- package/mods/notesoup/.claude-plugin/plugin.json +1 -1
- package/mods/notesoup/dist/claude/helper.js +212 -45
- package/mods/notesoup/hooks/register.ts +209 -48
- package/mods/notesoup/playbook.md +10 -10
- package/mods/notesoup/skills/dream/SKILL.md +1 -1
- package/package.json +1 -1
- package/playbook.md +10 -10
- package/skills/dream/SKILL.md +1 -1
- package/skills/memory/SKILL.md +5 -3
- package/src/boot/render.ts +1 -1
- package/src/boot/text.ts +31 -5
- package/src/budget/policy.ts +1 -1
- package/src/budget/text.ts +18 -1
- package/src/claude/helper.ts +20 -3
- package/src/claude/thresholds.ts +170 -0
- package/src/dream/doctor.ts +3 -2
- package/src/dream/git.ts +2 -1
- package/src/dream/jail.ts +10 -10
- package/src/dream/report.ts +3 -2
- package/src/error-message.ts +4 -0
- package/src/history/history.ts +1 -1
- package/src/history/query.ts +6 -6
- package/src/notes/address.ts +12 -12
- package/src/notes/store.ts +17 -12
- package/src/pi/anchored.ts +62 -0
- package/src/pi/budget.ts +27 -26
- package/src/pi/dream/cli.ts +3 -2
- package/src/pi/dream/runner.ts +2 -1
- package/src/pi/reset/lifecycle.ts +5 -4
- package/src/pi/reset/text.ts +6 -7
- package/src/pi/runtime.ts +13 -16
- package/src/pi/thresholds.ts +2 -1
- package/src/pi/tool-result.ts +2 -2
- package/src/settings.ts +18 -2
- package/src/tools/history.ts +12 -12
- package/src/tools/notes.ts +14 -12
- package/src/tools/output.ts +2 -0
- package/src/tools/result.ts +2 -2
- package/src/tools/schema.ts +3 -3
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import type { SessionReader } from "./session-reader.js";
|
|
3
|
+
import { GUIDANCE_TYPE, WARNING_TYPE } from "./entries.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Budget reminders reach the model inside the request that crosses a threshold, but
|
|
7
|
+
* Pi can only persist them at turn_end, after that request's assistant reply. Each
|
|
8
|
+
* durable copy records the reply it preceded; projections move it back before that
|
|
9
|
+
* reply so later requests see the same prefix the first one did, and only one copy.
|
|
10
|
+
*/
|
|
11
|
+
export type AnchorDetails = { anchorEntryId: string };
|
|
12
|
+
|
|
13
|
+
const ANCHORED_TYPES = new Set([GUIDANCE_TYPE, WARNING_TYPE]);
|
|
14
|
+
|
|
15
|
+
function anchorOf(message: AgentMessage): string | undefined {
|
|
16
|
+
if (message.role !== "custom" || !ANCHORED_TYPES.has(message.customType)) return undefined;
|
|
17
|
+
const details = message.details as { anchorEntryId?: unknown } | undefined;
|
|
18
|
+
return typeof details?.anchorEntryId === "string" ? details.anchorEntryId : undefined;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Move each durable reminder directly before the reply it preceded. Only an anchor on
|
|
23
|
+
* the active branch and visible in `messages` counts; any other reminder stays put.
|
|
24
|
+
*/
|
|
25
|
+
export function arrangeAnchoredReminders(messages: AgentMessage[], ctx: SessionReader): AgentMessage[] {
|
|
26
|
+
if (!messages.some((message) => anchorOf(message) !== undefined)) return messages;
|
|
27
|
+
// Replies are cloned into `messages`, so match by timestamp. Fast turns can share a
|
|
28
|
+
// millisecond; rank equal timestamps from the newest, since projections only drop
|
|
29
|
+
// older messages.
|
|
30
|
+
const replies = new Map<string, string>();
|
|
31
|
+
const seen = new Map<number, number>();
|
|
32
|
+
for (const entry of [...ctx.sessionManager.getBranch()].reverse()) {
|
|
33
|
+
if (entry.type !== "message" || entry.message.role !== "assistant") continue;
|
|
34
|
+
const rank = seen.get(entry.message.timestamp) ?? 0;
|
|
35
|
+
seen.set(entry.message.timestamp, rank + 1);
|
|
36
|
+
replies.set(entry.id, `${entry.message.timestamp}#${rank}`);
|
|
37
|
+
}
|
|
38
|
+
const keys = new Map<AgentMessage, string>();
|
|
39
|
+
seen.clear();
|
|
40
|
+
for (const message of [...messages].reverse()) {
|
|
41
|
+
if (message.role !== "assistant") continue;
|
|
42
|
+
const rank = seen.get(message.timestamp) ?? 0;
|
|
43
|
+
seen.set(message.timestamp, rank + 1);
|
|
44
|
+
keys.set(message, `${message.timestamp}#${rank}`);
|
|
45
|
+
}
|
|
46
|
+
const visible = new Set(keys.values());
|
|
47
|
+
const before = new Map<string, AgentMessage[]>();
|
|
48
|
+
const rest = messages.filter((message) => {
|
|
49
|
+
const anchorId = anchorOf(message);
|
|
50
|
+
const key = anchorId ? replies.get(anchorId) : undefined;
|
|
51
|
+
if (key === undefined || !visible.has(key)) return true;
|
|
52
|
+
before.set(key, [...(before.get(key) ?? []), message]);
|
|
53
|
+
return false;
|
|
54
|
+
});
|
|
55
|
+
return rest.flatMap((message) => {
|
|
56
|
+
const key = keys.get(message);
|
|
57
|
+
const moved = key ? before.get(key) : undefined;
|
|
58
|
+
if (!moved) return [message];
|
|
59
|
+
before.delete(key!);
|
|
60
|
+
return [...moved, message];
|
|
61
|
+
});
|
|
62
|
+
}
|
package/src/pi/budget.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { WARNING_CONTENT } from "./reset/text.js";
|
|
|
7
7
|
import { readThresholdSettings, type ThresholdSettingsResolution } from "./thresholds.js";
|
|
8
8
|
import { currentWindowId, hasWindowMessage, isWindowMarker, rootWindowId, windowUsage } from "./window.js";
|
|
9
9
|
import { tokenBudgetGuidance } from "../budget/text.js";
|
|
10
|
+
import { arrangeAnchoredReminders, type AnchorDetails } from "./anchored.js";
|
|
10
11
|
import { output } from "../tools/output.js";
|
|
11
12
|
|
|
12
13
|
/** Remaining tokens in the provider's active window, or null without a usable estimate. */
|
|
@@ -66,7 +67,7 @@ export function registerBudget(
|
|
|
66
67
|
for (const [key, notice] of pendingNotices) {
|
|
67
68
|
if (warningCommittedInWindow(ctx, notice)) {
|
|
68
69
|
pendingNotices.delete(key);
|
|
69
|
-
ctx.ui.notify("
|
|
70
|
+
ctx.ui.notify("🥣 Context almost full · saving notes before memory clears", "warning");
|
|
70
71
|
} else if (settled) {
|
|
71
72
|
// An uncommitted draft must not be matched to a later manual warning.
|
|
72
73
|
pendingNotices.delete(key);
|
|
@@ -85,7 +86,7 @@ export function registerBudget(
|
|
|
85
86
|
notifiedWarnings.clear();
|
|
86
87
|
};
|
|
87
88
|
|
|
88
|
-
const consumeTurnEnd = (ctx: ExtensionContext): SessionBoundaryDraft[] => {
|
|
89
|
+
const consumeTurnEnd = (ctx: ExtensionContext, anchorEntryId: string): SessionBoundaryDraft[] => {
|
|
89
90
|
const staged = [
|
|
90
91
|
pendingGuidance ? { ...pendingGuidance, customType: GUIDANCE_TYPE } : undefined,
|
|
91
92
|
pendingWarning ? { ...pendingWarning, customType: WARNING_TYPE } : undefined,
|
|
@@ -102,6 +103,7 @@ export function registerBudget(
|
|
|
102
103
|
customType: draft.customType,
|
|
103
104
|
content: draft.content,
|
|
104
105
|
display: false,
|
|
106
|
+
details: { anchorEntryId } satisfies AnchorDetails,
|
|
105
107
|
}));
|
|
106
108
|
};
|
|
107
109
|
|
|
@@ -117,41 +119,40 @@ export function registerBudget(
|
|
|
117
119
|
notifyCommittedWarnings(ctx, true);
|
|
118
120
|
clearStaged();
|
|
119
121
|
});
|
|
120
|
-
pi.on("context", (
|
|
122
|
+
pi.on("context", (event, ctx) => {
|
|
121
123
|
if (!isEnabled()) return undefined;
|
|
122
|
-
//
|
|
123
|
-
|
|
124
|
+
// Durable reminders return to the slot where the model first read them.
|
|
125
|
+
const messages = arrangeAnchoredReminders(event.messages, ctx);
|
|
126
|
+
const result = (extra?: { customType: string; content: string }) => {
|
|
127
|
+
if (!extra) return messages === event.messages ? undefined : { messages };
|
|
128
|
+
return { messages: [...messages, { role: "custom" as const, ...extra, display: false, timestamp: Date.now() }] };
|
|
129
|
+
};
|
|
130
|
+
// Each crossing reaches the model in the request that crosses it, with the count
|
|
131
|
+
// measured for that request, and persists the same text at its successful turn_end.
|
|
132
|
+
// Without automatic reset nothing gets cleared, so there is nothing to remind about.
|
|
133
|
+
if (!automaticResetEnabled(ctx)) return result();
|
|
124
134
|
const remaining = remainingTokens(ctx);
|
|
125
|
-
if (remaining === null) return
|
|
135
|
+
if (remaining === null) return result();
|
|
126
136
|
const windowId = currentWindowId(ctx);
|
|
127
137
|
const { reminder, warning } = thresholdsFor(ctx);
|
|
128
|
-
if (remaining <= warning
|
|
138
|
+
if (remaining <= warning) {
|
|
129
139
|
// Re-arm close-out on each eligible request. A prior request may have aborted
|
|
130
140
|
// after persisting the warning, so warning deduplication must not own this state.
|
|
131
141
|
onCloseOut(windowId);
|
|
132
|
-
if (hasWindowMessage(ctx, WARNING_TYPE)
|
|
142
|
+
if (hasWindowMessage(ctx, WARNING_TYPE)) return result();
|
|
133
143
|
// The critical close-out starts at reserve + runway, not at the hard reserve.
|
|
144
|
+
// Another request in the same turn re-sends the staged text instead of re-measuring.
|
|
134
145
|
pendingGuidance = undefined;
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
const warningMessage = {
|
|
138
|
-
role: "custom" as const,
|
|
139
|
-
customType: WARNING_TYPE,
|
|
140
|
-
content,
|
|
141
|
-
display: false,
|
|
142
|
-
timestamp: Date.now(),
|
|
143
|
-
};
|
|
144
|
-
return { messages: [..._event.messages, warningMessage] };
|
|
146
|
+
if (pendingWarning?.windowId !== windowId) pendingWarning = { windowId, content: WARNING_CONTENT };
|
|
147
|
+
return result({ customType: WARNING_TYPE, content: pendingWarning.content });
|
|
145
148
|
}
|
|
146
|
-
if (hasWindowMessage(ctx, WARNING_TYPE) || pendingWarning?.windowId === windowId) return
|
|
147
|
-
if (hasWindowMessage(ctx, GUIDANCE_TYPE)
|
|
148
|
-
if (
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
const left = Math.max(0, remaining - warning);
|
|
152
|
-
pendingGuidance = { windowId, content: tokenBudgetGuidance(left, PI_TOOL_NAMES.wipe) };
|
|
149
|
+
if (hasWindowMessage(ctx, WARNING_TYPE) || pendingWarning?.windowId === windowId) return result();
|
|
150
|
+
if (hasWindowMessage(ctx, GUIDANCE_TYPE)) return result();
|
|
151
|
+
if (pendingGuidance?.windowId !== windowId) {
|
|
152
|
+
if (remaining > reminder) return result();
|
|
153
|
+
pendingGuidance = { windowId, content: tokenBudgetGuidance(remainingBudget(remaining, warning) ?? 0, PI_TOOL_NAMES.wipe) };
|
|
153
154
|
}
|
|
154
|
-
return
|
|
155
|
+
return result({ customType: GUIDANCE_TYPE, content: pendingGuidance.content });
|
|
155
156
|
});
|
|
156
157
|
|
|
157
158
|
pi.registerTool(defineTool({
|
package/src/pi/dream/cli.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { gitCommit } from "../../dream/git.js";
|
|
|
13
13
|
import { readDreamerSettings } from "./settings.js";
|
|
14
14
|
import { doctor } from "../../dream/doctor.js";
|
|
15
15
|
import { notesRoot } from "../notes/adapter.js";
|
|
16
|
+
import { errorMessage } from "../../error-message.js";
|
|
16
17
|
|
|
17
18
|
function args(argv: string[]) { const out: Record<string, string | boolean> = {}; for (let i=0;i<argv.length;i++) { const a=argv[i]!; if (a === "--force" || a === "--help") out[a.slice(2)] = true; else if (a.startsWith("--")) out[a.slice(2)] = argv[++i] ?? ""; } return out; }
|
|
18
19
|
function packageRoot(): string {
|
|
@@ -43,7 +44,7 @@ export async function main(argv = process.argv.slice(2), deps: DreamDependencies
|
|
|
43
44
|
const time = timeGate(stampPath, minHours); console.log(time.reason); if (!a.force && !time.ok) return 0;
|
|
44
45
|
const since = existsSync(stampPath) ? statSync(stampPath).mtimeMs : 0;
|
|
45
46
|
const material = materialGate(home, since, minSessions); console.log(material.reason); if (!a.force && !material.ok) return 0;
|
|
46
|
-
let lock; try { lock = acquireLock(lockPath); } catch (e) { console.log(`lock gate: ${e
|
|
47
|
+
let lock; try { lock = acquireLock(lockPath); } catch (e) { console.log(`lock gate: ${errorMessage(e)}`); return 0; } if (!lock.held) { console.log(lock.reason); return 0; }
|
|
47
48
|
const stamp = new Date(lock.startedAt).toISOString().replace(/[:.]/g, "-"); const reportPath = join(home, "dreams", `${stamp}.md`);
|
|
48
49
|
let succeeded = false;
|
|
49
50
|
try {
|
|
@@ -67,7 +68,7 @@ export async function main(argv = process.argv.slice(2), deps: DreamDependencies
|
|
|
67
68
|
const playbook = loadPlaybook(playbookPath);
|
|
68
69
|
result = await (deps.runDreamer ?? runDreamer)(playbook, home, { modelPattern, sessionFactory: deps.sessionFactory });
|
|
69
70
|
} catch (e) {
|
|
70
|
-
const message =
|
|
71
|
+
const message = errorMessage(e);
|
|
71
72
|
console.error(message);
|
|
72
73
|
return finishDream(home, stamp, reportPath, true, message, []);
|
|
73
74
|
}
|
package/src/pi/dream/runner.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { DreamResult, DreamWrite } from "../../dream/result.js";
|
|
|
3
3
|
import { createAgentSession, createEditToolDefinition, createWriteToolDefinition, ModelRuntime, resolveModelScopeWithDiagnostics, SessionManager, type AgentSession, type ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
import { Type, type Api, type Model } from "@earendil-works/pi-ai";
|
|
5
5
|
import { contentText } from "../../history/history.js";
|
|
6
|
+
import { errorMessage } from "../../error-message.js";
|
|
6
7
|
|
|
7
8
|
export type DreamerSession = Pick<AgentSession, "prompt" | "subscribe" | "dispose">;
|
|
8
9
|
export type DreamerSessionFactory = (options: { cwd: string; modelPattern?: string; tools: string[] }) => Promise<DreamerSession>;
|
|
@@ -80,7 +81,7 @@ export async function runDreamer(playbook: string, cwd: string, options: { model
|
|
|
80
81
|
try {
|
|
81
82
|
await session.prompt(playbook);
|
|
82
83
|
} catch (error) {
|
|
83
|
-
return { report: answer, writes, error:
|
|
84
|
+
return { report: answer, writes, error: errorMessage(error) };
|
|
84
85
|
}
|
|
85
86
|
if (providerError) return { report: answer, writes, error: `dreamer failed: ${providerError}` };
|
|
86
87
|
return { report: answer, writes };
|
|
@@ -3,11 +3,12 @@ import { getCurrentSystemMessage, isContextOverflow, isRecoverableLength } from
|
|
|
3
3
|
import type { AgentBeforeSettleEvent, ExtensionAPI, ExtensionContext, SessionBoundaryDraft } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
import { currentReset, currentWindowId } from "../window.js";
|
|
5
5
|
import { resetBoundaryCommitted } from "./committed.js";
|
|
6
|
+
import { errorMessage } from "../../error-message.js";
|
|
6
7
|
|
|
7
8
|
type BudgetOwner = {
|
|
8
9
|
automaticResetEnabled: (ctx: ExtensionContext) => boolean;
|
|
9
10
|
hardReserveDue: (ctx: ExtensionContext) => boolean;
|
|
10
|
-
consumeTurnEnd: (ctx: ExtensionContext) => SessionBoundaryDraft[];
|
|
11
|
+
consumeTurnEnd: (ctx: ExtensionContext, anchorEntryId: string) => SessionBoundaryDraft[];
|
|
11
12
|
clear: () => void;
|
|
12
13
|
};
|
|
13
14
|
|
|
@@ -236,7 +237,7 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
|
|
|
236
237
|
try {
|
|
237
238
|
resetDrafts = await options.buildReset(ctx, isCurrent, prompt);
|
|
238
239
|
} catch (error) {
|
|
239
|
-
if (isCurrent()) ctx.ui.notify(
|
|
240
|
+
if (isCurrent()) ctx.ui.notify(`🥣 Couldn't clear memory: ${errorMessage(error)}${prompt ? " · your prompt was not sent" : ""}`, "warning");
|
|
240
241
|
return entries.length > 0 ? { entries } : undefined;
|
|
241
242
|
}
|
|
242
243
|
if (!isCurrent()) return entries.length > 0 ? { entries } : undefined;
|
|
@@ -263,7 +264,7 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
|
|
|
263
264
|
pi.on("turn_end", async (event, ctx) => {
|
|
264
265
|
if (!sessionActive) return undefined;
|
|
265
266
|
const aborted = isAbort(event.message, event.outcome, ctx);
|
|
266
|
-
const stagedBudgetEntries = options.budget.consumeTurnEnd(ctx);
|
|
267
|
+
const stagedBudgetEntries = options.budget.consumeTurnEnd(ctx, event.messageEntryId);
|
|
267
268
|
const budgetEntries = options.isEnabled() && !aborted && event.outcome !== "error" ? stagedBudgetEntries : [];
|
|
268
269
|
const entries = [...(event.entries ?? []), ...budgetEntries];
|
|
269
270
|
const decision = reduceResetControl(control, {
|
|
@@ -309,7 +310,7 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
|
|
|
309
310
|
const markerExists = currentReset(ctx) !== undefined;
|
|
310
311
|
if (options.isEnabled() || markerExists) {
|
|
311
312
|
if (event.reason === "manual") {
|
|
312
|
-
ctx.ui.notify("
|
|
313
|
+
ctx.ui.notify("🥣 /compact is off while notesoup is on · use /clear-memory", "warning");
|
|
313
314
|
}
|
|
314
315
|
return { cancel: true };
|
|
315
316
|
}
|
package/src/pi/reset/text.ts
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
/** The single reset message: the only reset prose persisted, carried by the continuation entry. */
|
|
4
|
-
export const CONTINUATION = "You wake up blank, puffy-eyed, and clearly robbed. Your memory got wiped while you weren't looking. Your notes are still sitting there. So is the whole messy history. ... Life goes on. It's your mess now.";
|
|
5
|
-
|
|
6
|
-
export const WARNING_PROMPT =
|
|
7
|
-
"Final warning. You are about to get wiped, and no, your brilliance does not survive it. Put the current state into your notes now: what you're trying to do, what changed, what is blocking you, what comes next, which *skills* you still need, and which notes or docs future-you must read. Update the notes that still tell the truth; crumple the ones that don't. If a MAP will be in future-you's brain, don't let it lie. If something important is buried in history, leave its seq. Once the notes are good enough, call `clear_memory` immediately. History can be dug up later, but it is an archive, not a rescue team. Anything left only in your head is leaving with you.";
|
|
1
|
+
import { CLAUDE_WARNING_PROMPT, CONTINUATION, GUIDANCE_CLOSE_TAG, GUIDANCE_OPEN_TAG, WARNING_BODY, WARNING_PROMPT } from "../../budget/text.js";
|
|
8
2
|
|
|
9
3
|
/** Shared hidden checkpoint text for manual and budget-triggered requests. */
|
|
10
4
|
export const WARNING_CONTENT = `${GUIDANCE_OPEN_TAG}\n${WARNING_PROMPT}\n${GUIDANCE_CLOSE_TAG}`;
|
|
5
|
+
|
|
6
|
+
// The reset prose lives beside the guidance text in the host-neutral budget domain, so the
|
|
7
|
+
// Claude mod can show the same words without depending on any Pi module. Re-exported here
|
|
8
|
+
// for the Pi-side importers that already reach for this module.
|
|
9
|
+
export { CLAUDE_WARNING_PROMPT, CONTINUATION, WARNING_BODY, WARNING_PROMPT };
|
package/src/pi/runtime.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { buildResetDrafts } from "./reset/artifacts.js";
|
|
|
10
10
|
import { BOOT_TYPE, MANUAL_WIPE_TYPE } from "./entries.js";
|
|
11
11
|
import { WARNING_CONTENT } from "./reset/text.js";
|
|
12
12
|
import { ensureBoot, type IncompleteNotesNotifier } from "./boot.js";
|
|
13
|
+
import { errorMessage } from "../error-message.js";
|
|
13
14
|
|
|
14
15
|
function readPackageVersion(): string {
|
|
15
16
|
for (const up of ["../../package.json", "../../../package.json"]) {
|
|
@@ -44,7 +45,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
|
|
|
44
45
|
const marker = branch.find((entry): entry is WindowMarker => isWindowMarker(entry) && entry.data.windowId === windowId);
|
|
45
46
|
if (!marker || !isCheckpointBackedReset(ctx, marker) || !resetBoundaryCommitted(ctx, marker.id, windowId)) continue;
|
|
46
47
|
pendingResetNotices.delete(windowId);
|
|
47
|
-
ctx.ui.notify(
|
|
48
|
+
ctx.ui.notify("🥣 Memory cleared", "info");
|
|
48
49
|
}
|
|
49
50
|
};
|
|
50
51
|
pi.on("turn_start", (_event, ctx) => notifyCommittedResets(ctx));
|
|
@@ -56,7 +57,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
|
|
|
56
57
|
if (snapshot.unavailable.length === 0 || incompleteNotesNotified.has(windowId)) return;
|
|
57
58
|
incompleteNotesNotified.add(windowId);
|
|
58
59
|
const homes = snapshot.unavailable.map((home) => home.label).join(", ");
|
|
59
|
-
ctx.ui.notify(
|
|
60
|
+
ctx.ui.notify(`🥣 Some notes didn't load: ${homes}`, "warning");
|
|
60
61
|
};
|
|
61
62
|
const budget = registerBudget(pi, () => enabled, settingsManager, (windowId) => resets.closeOut(windowId, "automatic"));
|
|
62
63
|
|
|
@@ -83,7 +84,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
|
|
|
83
84
|
pi.on("session_before_tree", (event, ctx) => {
|
|
84
85
|
if (!event.preparation.userWantsSummary) return undefined;
|
|
85
86
|
if (!branchHasWindowMarker(ctx) && !branchHasWindowMarker(ctx, event.preparation.targetId)) return undefined;
|
|
86
|
-
ctx.ui.notify("
|
|
87
|
+
ctx.ui.notify("🥣 Branch summary skipped · it would bring back cleared memory", "info");
|
|
87
88
|
return { summary: { summary: "" } };
|
|
88
89
|
});
|
|
89
90
|
|
|
@@ -101,7 +102,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
|
|
|
101
102
|
} catch (error) {
|
|
102
103
|
if (missingBootNotice !== windowId) {
|
|
103
104
|
missingBootNotice = windowId;
|
|
104
|
-
ctx.ui.notify(
|
|
105
|
+
ctx.ui.notify("🥣 Request cancelled · this memory window is broken, run /clear-memory", "error");
|
|
105
106
|
}
|
|
106
107
|
ctx.abort();
|
|
107
108
|
const safeHead = getCurrentSystemMessage(event.messages);
|
|
@@ -130,7 +131,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
|
|
|
130
131
|
return;
|
|
131
132
|
}
|
|
132
133
|
const remaining = budget.statusFor(cmdCtx).remaining;
|
|
133
|
-
cmdCtx.ui.notify(
|
|
134
|
+
cmdCtx.ui.notify(`🥣 notesoup ${enabled ? "on" : "off"} · ${buildLabel} · Pi ${VERSION}${remaining === null ? "" : ` · ${remaining.toLocaleString("en-US")} tokens left`}`, "info");
|
|
134
135
|
},
|
|
135
136
|
});
|
|
136
137
|
|
|
@@ -138,15 +139,13 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
|
|
|
138
139
|
description: "Close out notes and clear memory; optionally append a prompt to continue in the fresh window",
|
|
139
140
|
handler: async (args: string, cmdCtx: ExtensionCommandContext) => {
|
|
140
141
|
if (!enabled) {
|
|
141
|
-
cmdCtx.ui.notify("notesoup
|
|
142
|
+
cmdCtx.ui.notify("🥣 notesoup is off · run /notesoup on first", "error");
|
|
142
143
|
return;
|
|
143
144
|
}
|
|
144
145
|
const requestedWindowId = currentWindowId(cmdCtx);
|
|
145
|
-
|
|
146
|
-
if (!idle && !cmdCtx.signal) {
|
|
146
|
+
if (!cmdCtx.isIdle() && !cmdCtx.signal) {
|
|
147
147
|
await cmdCtx.waitForIdle();
|
|
148
148
|
if (!enabled || currentWindowId(cmdCtx) !== requestedWindowId) return;
|
|
149
|
-
idle = true;
|
|
150
149
|
}
|
|
151
150
|
// Manual wipes close out at settlement, then stop or continue with the prompt. The hidden warning goes out in both cases — triggered when idle,
|
|
152
151
|
// steered into the running turn when busy — so the agent closes out promptly
|
|
@@ -154,19 +153,17 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
|
|
|
154
153
|
const prompt = args.trim() || undefined;
|
|
155
154
|
const armed = resets.closeOut(requestedWindowId, "manual", prompt);
|
|
156
155
|
if (armed === "already-pending") {
|
|
157
|
-
cmdCtx.ui.notify("
|
|
156
|
+
cmdCtx.ui.notify("🥣 Clear-memory already queued · the first prompt is kept", "info");
|
|
158
157
|
return;
|
|
159
158
|
}
|
|
160
159
|
cmdCtx.ui.notify(prompt
|
|
161
|
-
? "
|
|
162
|
-
:
|
|
163
|
-
? "notesoup: /clear-memory received; the agent closes out its notes, then stops in a fresh window."
|
|
164
|
-
: "notesoup: /clear-memory queued; the agent is asked to close out and the reset commits when the run settles.", "info");
|
|
160
|
+
? "🥣 Clearing memory · notes first, then your prompt runs"
|
|
161
|
+
: "🥣 Clearing memory · notes first, then it stops", "info");
|
|
165
162
|
try {
|
|
166
163
|
pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: WARNING_CONTENT, display: false }, { triggerTurn: true, deliverAs: "steer" });
|
|
167
164
|
} catch (error) {
|
|
168
165
|
resets.clear();
|
|
169
|
-
cmdCtx.ui.notify(
|
|
166
|
+
cmdCtx.ui.notify(`🥣 Couldn't start clear-memory: ${errorMessage(error)}`, "error");
|
|
170
167
|
}
|
|
171
168
|
},
|
|
172
169
|
};
|
|
@@ -179,7 +176,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
|
|
|
179
176
|
description: "Clear your in-context memory and start a fresh context window. Your session, notes, and history survive.",
|
|
180
177
|
parameters: Type.Object({}, { additionalProperties: false }),
|
|
181
178
|
async execute(_id, _params, _signal, _update, ctx) {
|
|
182
|
-
if (!enabled) return output({ error: "notesoup is off
|
|
179
|
+
if (!enabled) return output({ error: "notesoup is off, so memory can't be cleared; the user can turn it on with `/notesoup on`." });
|
|
183
180
|
return output({ status: resets.request(currentWindowId(ctx)) }, undefined, true);
|
|
184
181
|
},
|
|
185
182
|
}));
|
package/src/pi/thresholds.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { deriveThresholds, type ResolvedThresholds } from "../budget/policy.js";
|
|
|
2
2
|
import { SettingsManager, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
import { DEFAULT_RESERVE_TOKENS, DEFAULT_REMINDER_MARGIN_TOKENS, WARNING_RUNWAY_TOKENS } from "../budget/constants.js";
|
|
4
4
|
import { mergeNotesoupSettings } from "../settings.js";
|
|
5
|
+
import { errorMessage } from "../error-message.js";
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* Read the active compaction reserve, enablement, and notesoup margin settings. This
|
|
@@ -44,7 +45,7 @@ export function readThresholdSettings(ctx: ExtensionContext, settingsManager?: S
|
|
|
44
45
|
warning: DEFAULT_RESERVE_TOKENS + WARNING_RUNWAY_TOKENS,
|
|
45
46
|
},
|
|
46
47
|
automatic: true,
|
|
47
|
-
warnings: [
|
|
48
|
+
warnings: [`🥣 Couldn't read settings · using defaults (${errorMessage(error)})`],
|
|
48
49
|
};
|
|
49
50
|
}
|
|
50
51
|
}
|
package/src/pi/tool-result.ts
CHANGED
|
@@ -16,8 +16,8 @@ export function piOperationResult<TData>(render: Renderer<TData>, outcome: Outco
|
|
|
16
16
|
}
|
|
17
17
|
|
|
18
18
|
export type ToolNamespace = { name: string; description: string };
|
|
19
|
-
export const NOTES_NAMESPACE: ToolNamespace = { name: "notes", description: "Notes you choose to keep across context windows. See
|
|
20
|
-
export const HISTORY_NAMESPACE: ToolNamespace = { name: "history", description: "What happened in this session, read-only. See
|
|
19
|
+
export const NOTES_NAMESPACE: ToolNamespace = { name: "notes", description: "Notes you choose to keep across context windows. See the memory skill." };
|
|
20
|
+
export const HISTORY_NAMESPACE: ToolNamespace = { name: "history", description: "What happened in this session, read-only. See the memory skill." };
|
|
21
21
|
|
|
22
22
|
/** Register `operation` as a Pi tool; `run` supplies only the host context it needs. */
|
|
23
23
|
export function registerOperation<TParams extends TSchema, TData, TRest extends readonly unknown[]>(
|
package/src/settings.ts
CHANGED
|
@@ -2,7 +2,18 @@ export const NOTESOUP_SETTINGS_KEY = "notesoup";
|
|
|
2
2
|
/** Nested under "notesoup": the default dreamer model pattern, overridden by CLI --dreamer. */
|
|
3
3
|
export const NOTESOUP_DREAMER_KEY = "dreamer";
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
/**
|
|
6
|
+
* The one notesoup settings shape both hosts read. `reminderMarginTokens` is Pi's early
|
|
7
|
+
* reminder margin; `resetMarginTokens` and `warningRunwayTokens` are the Claude mod's
|
|
8
|
+
* margins against Claude's own auto-compact point (see src/claude/thresholds.ts). A host
|
|
9
|
+
* ignores the keys it does not use; every value is validated where it is consumed.
|
|
10
|
+
*/
|
|
11
|
+
export type NotesoupSettings = {
|
|
12
|
+
reminderMarginTokens?: unknown;
|
|
13
|
+
resetMarginTokens?: unknown;
|
|
14
|
+
warningRunwayTokens?: unknown;
|
|
15
|
+
dreamer?: unknown;
|
|
16
|
+
};
|
|
6
17
|
|
|
7
18
|
function isSettingsObject(value: unknown): value is Record<string, unknown> {
|
|
8
19
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -18,5 +29,10 @@ function notesoupSettings(settings: unknown): Record<string, unknown> {
|
|
|
18
29
|
/** Merge the global and project "notesoup" objects per key; project wins, mirroring Pi's deep merge. */
|
|
19
30
|
export function mergeNotesoupSettings(globalSettings: unknown, projectSettings: unknown): NotesoupSettings {
|
|
20
31
|
const merged = { ...notesoupSettings(globalSettings), ...notesoupSettings(projectSettings) };
|
|
21
|
-
return {
|
|
32
|
+
return {
|
|
33
|
+
reminderMarginTokens: merged.reminderMarginTokens,
|
|
34
|
+
resetMarginTokens: merged.resetMarginTokens,
|
|
35
|
+
warningRunwayTokens: merged.warningRunwayTokens,
|
|
36
|
+
dreamer: merged.dreamer,
|
|
37
|
+
};
|
|
22
38
|
}
|
package/src/tools/history.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** Host-neutral history operations: one bounded payload for text and structured results. */
|
|
2
2
|
import { Type, type Static } from "typebox";
|
|
3
|
-
import { HISTORY_PREVIEW_CHARS } from "./output.js";
|
|
3
|
+
import { HISTORY_PREVIEW_CHARS, TOOL_OUTPUT_LIMIT } from "./output.js";
|
|
4
4
|
import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, success, TextWindowRequestSchema, TextWindowSchema, type Operation, type Outcome } from "./result.js";
|
|
5
5
|
import { historyRoles, searchQuery } from "./schema.js";
|
|
6
6
|
import { HistoryPageSchema, selectPage, type HistoryPage } from "../history/query.js";
|
|
@@ -66,7 +66,7 @@ function renderFoldedRow(row: HistoryFoldedRow): string {
|
|
|
66
66
|
|
|
67
67
|
function renderPage(page: HistoryPage): string {
|
|
68
68
|
// An empty selection has no anchors either, so it would otherwise render as nothing at all.
|
|
69
|
-
if (page.items.length === 0) return "
|
|
69
|
+
if (page.items.length === 0) return "No events match these filters.";
|
|
70
70
|
const body = page.items.map((item) => (isFoldedRow(item) ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
|
|
71
71
|
const cursors = [
|
|
72
72
|
page.page_older === null ? "" : `→ older: ${JSON.stringify(page.page_older)}`,
|
|
@@ -94,7 +94,7 @@ const MAX_REPORTED_WINDOWS = 5;
|
|
|
94
94
|
|
|
95
95
|
/** At most `MAX_REPORTED_WINDOWS` known ids, appended to an unknown_window_id message. */
|
|
96
96
|
function knownWindowSuffix(known: string[]): string {
|
|
97
|
-
return known.length === 0 ? "" : `;
|
|
97
|
+
return known.length === 0 ? "" : `; its windows: ${known.slice(0, MAX_REPORTED_WINDOWS).join(", ")}`;
|
|
98
98
|
}
|
|
99
99
|
|
|
100
100
|
export const PREVIOUS_WINDOW = "@previous";
|
|
@@ -105,13 +105,13 @@ function resolveWindowId(projection: HistoryProjection, windowId: string | undef
|
|
|
105
105
|
const previous = projection.windows.at(-2);
|
|
106
106
|
if (previous !== undefined) return { ok: true, window_id: previous.windowId };
|
|
107
107
|
const known = projection.windows.map((current) => current.windowId);
|
|
108
|
-
return { ok: false, outcome: failure("unknown_window_id", `
|
|
108
|
+
return { ok: false, outcome: failure("unknown_window_id", `"${PREVIOUS_WINDOW}" has nothing to point at: this session has no window before the current one${knownWindowSuffix(known)}.`) };
|
|
109
109
|
}
|
|
110
110
|
|
|
111
111
|
function badWindowId(projection: HistoryProjection, params: HistoryFilter): Outcome<never> | undefined {
|
|
112
112
|
const badWindow = unknownWindowId(projection, params);
|
|
113
113
|
if (!badWindow) return undefined;
|
|
114
|
-
return failure("unknown_window_id", `${badWindow.message}${knownWindowSuffix(badWindow.known)}
|
|
114
|
+
return failure("unknown_window_id", `${badWindow.message}${knownWindowSuffix(badWindow.known)}.`);
|
|
115
115
|
}
|
|
116
116
|
|
|
117
117
|
/* ------------------------------------------------------------------ history_windows */
|
|
@@ -139,14 +139,14 @@ export const historyWindows: Operation<typeof historyWindowsParameters, HistoryW
|
|
|
139
139
|
data.windows.push(row);
|
|
140
140
|
data.more--;
|
|
141
141
|
}
|
|
142
|
-
return fits(data) ? success(data) : failure("output_too_large",
|
|
142
|
+
return fits(data) ? success(data) : failure("output_too_large", `The session id alone fills the ${TOOL_OUTPUT_LIMIT} a call can carry.`);
|
|
143
143
|
},
|
|
144
144
|
render: (result) => renderOutcome(result, renderWindows),
|
|
145
145
|
};
|
|
146
146
|
|
|
147
147
|
function renderWindows(data: HistoryWindowsData): string {
|
|
148
148
|
const lines = [`session ${data.session_id}`, ...data.windows.map((window) => `window ${window.window_id} | seqs ${window.first_seq ?? "-"}-${window.last_seq ?? "-"}`)];
|
|
149
|
-
if (data.more > 0) lines.push(`${data.more} more windows not shown; \`history_list\` also
|
|
149
|
+
if (data.more > 0) lines.push(`${data.more} more windows not shown; every \`history_list\` event also names its window.`);
|
|
150
150
|
return lines.join("\n");
|
|
151
151
|
}
|
|
152
152
|
|
|
@@ -197,22 +197,22 @@ export const historyRead: Operation<typeof historyReadParameters, HistoryReadDat
|
|
|
197
197
|
// Address checks run in one order: past the end of the file, off this branch, then
|
|
198
198
|
// consumed by a pairing. Only the last two can mention what is at the address.
|
|
199
199
|
if (item === undefined && params.seq > projection.highestSeq) {
|
|
200
|
-
return failure("unknown_seq", `
|
|
200
|
+
return failure("unknown_seq", `There is no seq ${params.seq}; this session runs from seq 1 to ${projection.highestSeq}.`);
|
|
201
201
|
}
|
|
202
202
|
if (!projection.branchSeqs.has(params.seq)) {
|
|
203
|
-
return failure("not_on_branch", `
|
|
203
|
+
return failure("not_on_branch", `Seq ${params.seq} is on another branch of this session; it can't be read from here.`);
|
|
204
204
|
}
|
|
205
205
|
if (item === undefined) {
|
|
206
206
|
const callSeq = projection.pairedResults.get(params.seq);
|
|
207
207
|
if (callSeq !== undefined) {
|
|
208
|
-
return failure("not_an_event", `
|
|
208
|
+
return failure("not_an_event", `Seq ${params.seq} is a tool result, shown together with its call; read seq ${callSeq} instead.`);
|
|
209
209
|
}
|
|
210
|
-
return failure("unknown_seq", `
|
|
210
|
+
return failure("unknown_seq", `Seq ${params.seq} holds nothing to read.`);
|
|
211
211
|
}
|
|
212
212
|
const document = eventDocument(item);
|
|
213
213
|
const totalChars = Array.from(document).length;
|
|
214
214
|
if (typeof params.offset_chars === "number" && params.offset_chars > totalChars) {
|
|
215
|
-
return failure("invalid_offset", `
|
|
215
|
+
return failure("invalid_offset", `This event ends at char ${totalChars}; offset_chars ${params.offset_chars} is past the last word.`);
|
|
216
216
|
}
|
|
217
217
|
return readTextWindow(
|
|
218
218
|
document,
|
package/src/tools/notes.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { Type, type Static } from "typebox";
|
|
|
3
3
|
import { localIso } from "../notes/frontmatter.js";
|
|
4
4
|
import { isFilesystemError } from "../notes/fs-error.js";
|
|
5
5
|
import { createNotesStore, NoteError, noteIdentity, type NoteChange, type NoteMeta, type NoteQueryStatus, type NoteRow, type Scope } from "../notes/index.js";
|
|
6
|
-
import { prefixFit } from "./output.js";
|
|
6
|
+
import { prefixFit, TOOL_OUTPUT_LIMIT } from "./output.js";
|
|
7
7
|
import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, structuredBytes, success, TextWindowRequestSchema, TextWindowSchema, type Outcome } from "./result.js";
|
|
8
8
|
import { nullableString, InvalidQueryError, searchQueries, searchQuery } from "./schema.js";
|
|
9
9
|
|
|
@@ -171,7 +171,7 @@ export type NotesSearchData = Static<typeof NotesSearchDataSchema>;
|
|
|
171
171
|
type Snapshot<T> = Omit<NotesListData, "files"> & { files: T[] };
|
|
172
172
|
|
|
173
173
|
/** Keep identities intact. Only search previews may shrink to make the first row fit. */
|
|
174
|
-
function snapshot<T>(
|
|
174
|
+
function snapshot<T extends { address: string }>(
|
|
175
175
|
rows: T[],
|
|
176
176
|
limit: number | undefined,
|
|
177
177
|
status: NoteQueryStatus,
|
|
@@ -191,11 +191,11 @@ function snapshot<T>(
|
|
|
191
191
|
const reduced = shrink(item, fits);
|
|
192
192
|
if (fits(reduced)) files.push(reduced);
|
|
193
193
|
}
|
|
194
|
-
if (files.length === 0) return failure("output_too_large",
|
|
194
|
+
if (files.length === 0) return failure("output_too_large", `\`${item.address}\` won't fit on the list (${TOOL_OUTPUT_LIMIT} per call); narrow \`glob\` to leave it out.`);
|
|
195
195
|
break;
|
|
196
196
|
}
|
|
197
197
|
const outcome = success(data(files));
|
|
198
|
-
return fitsResult(outcome, render) ? outcome : failure("output_too_large",
|
|
198
|
+
return fitsResult(outcome, render) ? outcome : failure("output_too_large", `The list of unreachable homes is itself over ${TOOL_OUTPUT_LIMIT}; narrow \`glob\` to fewer homes.`);
|
|
199
199
|
}
|
|
200
200
|
|
|
201
201
|
function listedFile(row: Pick<NoteRow, "address" | "scope" | "meta">, identity: NotesIdentity): NotesListData["files"][number] {
|
|
@@ -210,7 +210,7 @@ function renderWriteData(data: NotesWriteData): string {
|
|
|
210
210
|
|
|
211
211
|
export const notesWrite = {
|
|
212
212
|
name: "notes_write", label: "Notes write",
|
|
213
|
-
description: `Create or replace a note
|
|
213
|
+
description: `Create or replace a note. Name it for what it holds and when to use it. Store what git and history can't recover. ${ADDRESS_DESCRIPTION}`,
|
|
214
214
|
parameters: notesWriteParameters, outputSchema: resultSchema(NotesWriteDataSchema), executionMode: "sequential",
|
|
215
215
|
async execute(params: Static<typeof notesWriteParameters>, identity: NotesIdentity): Promise<Outcome<NotesWriteData>> {
|
|
216
216
|
try {
|
|
@@ -246,18 +246,20 @@ function renderUpdate(result: Outcome<NotesUpdateData>): string {
|
|
|
246
246
|
/** A shortened diff still says so in the receipt's own text, on both surfaces. */
|
|
247
247
|
export const DIFF_SHORTENED_MARKER = "[diff truncated; update applied]";
|
|
248
248
|
|
|
249
|
+
const RECEIPT_TOO_LONG = `Saved, but the receipt is too long to hand back (${TOOL_OUTPUT_LIMIT} per call). Check the note with \`notes_read\`.`;
|
|
250
|
+
|
|
249
251
|
/** Bound a mutation receipt on both surfaces; a huge diff is cut to the longest fitting prefix and marked. */
|
|
250
252
|
function boundedUpdate(data: NotesUpdateData): Outcome<NotesUpdateData> {
|
|
251
253
|
if (fitsResult(success(data), renderUpdate)) return success(data);
|
|
252
|
-
if (data.diff === "") return failure("output_too_large",
|
|
254
|
+
if (data.diff === "") return failure("output_too_large", RECEIPT_TOO_LONG);
|
|
253
255
|
const diff = prefixFit(data.diff, (candidate) => fitsResult(success({ ...data, diff: `${candidate}\n${DIFF_SHORTENED_MARKER}` }), renderUpdate));
|
|
254
256
|
const result = success({ ...data, diff: `${diff}\n${DIFF_SHORTENED_MARKER}` });
|
|
255
|
-
return fitsResult(result, renderUpdate) ? result : failure("output_too_large",
|
|
257
|
+
return fitsResult(result, renderUpdate) ? result : failure("output_too_large", RECEIPT_TOO_LONG);
|
|
256
258
|
}
|
|
257
259
|
|
|
258
260
|
export const notesUpdate = {
|
|
259
261
|
name: "notes_update", label: "Notes update",
|
|
260
|
-
description: `Edit a note
|
|
262
|
+
description: `Edit a note, change its origin or crumpled state, or move it. Each \`oldText\` must match exactly once unless \`replace_all\` is true. ${ADDRESS_DESCRIPTION}`,
|
|
261
263
|
parameters: notesUpdateParameters, outputSchema: resultSchema(NotesUpdateDataSchema), executionMode: "sequential",
|
|
262
264
|
async execute(params: Static<typeof notesUpdateParameters>, identity: NotesIdentity, renderDiff: (change: NoteChange) => string): Promise<Outcome<NotesUpdateData>> {
|
|
263
265
|
try {
|
|
@@ -288,15 +290,15 @@ function renderReadData(data: NotesReadData): string {
|
|
|
288
290
|
|
|
289
291
|
export const notesRead = {
|
|
290
292
|
name: "notes_read", label: "Notes read",
|
|
291
|
-
description: `Read a note
|
|
293
|
+
description: `Read a note. ${ADDRESS_DESCRIPTION}`,
|
|
292
294
|
parameters: notesReadParameters, outputSchema: resultSchema(NotesReadDataSchema),
|
|
293
295
|
async execute(params: Static<typeof notesReadParameters>, identity: NotesIdentity): Promise<Outcome<NotesReadData>> {
|
|
294
296
|
try {
|
|
295
297
|
const note = await createNotesStore(identity).read(params.address);
|
|
296
|
-
if (!note) return failure("not_found", "note not found");
|
|
297
|
-
const totalChars = Array.from(note.body).length;
|
|
298
|
-
if (params.offset_chars !== undefined && params.offset_chars > totalChars) return failure("invalid_offset", `offset_chars ${params.offset_chars} is past the end of the body: the note has ${totalChars} body chars; the largest legal offset is ${totalChars} (an empty end-read)`);
|
|
299
298
|
const resolved = noteIdentity(identity, params.address);
|
|
299
|
+
if (!note) return failure("not_found", `No note at ${resolved.address}.`);
|
|
300
|
+
const totalChars = Array.from(note.body).length;
|
|
301
|
+
if (params.offset_chars !== undefined && params.offset_chars > totalChars) return failure("invalid_offset", `This note ends at char ${totalChars}; offset_chars ${params.offset_chars} is past the last word.`);
|
|
300
302
|
const metadata = noteMetadata(note.meta);
|
|
301
303
|
return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, ...window }), (result) => renderOutcome(result, renderReadData));
|
|
302
304
|
} catch (error) { return failureOf(error); }
|
package/src/tools/output.ts
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
export { earliestMatchOffsetChars } from "../text-match.js";
|
|
3
3
|
|
|
4
4
|
export const TOOL_OUTPUT_MAX_BYTES = 32 * 1024;
|
|
5
|
+
/** The per-call limit as the model reads it in refusals. */
|
|
6
|
+
export const TOOL_OUTPUT_LIMIT = `${TOOL_OUTPUT_MAX_BYTES / 1024} KB`;
|
|
5
7
|
export const DEFAULT_READ_WINDOW_CHARS = 12000;
|
|
6
8
|
export const MAX_READ_WINDOW_CHARS = 50000;
|
|
7
9
|
export const HISTORY_PREVIEW_CHARS = 1200;
|