@astrosheep/pi-context 0.23.1 → 0.25.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 +52 -5
- package/dist/build-info.json +4 -0
- package/dist/extension.js +1861 -0
- package/dist/src/context/budget.js +150 -0
- package/dist/src/context/context-window.js +97 -0
- package/dist/src/context/prompts.js +94 -0
- package/dist/src/context/reset-lifecycle.js +134 -0
- package/dist/src/context/runtime.js +236 -0
- package/dist/src/context/thresholds.js +62 -0
- package/dist/src/dream/cli.js +1 -1
- package/dist/src/dream/doctor.js +34 -6
- package/dist/src/dream/runner.js +1 -1
- package/dist/src/dream/settings.js +30 -0
- package/dist/src/{history-tools.js → history/history-tools.js} +3 -3
- package/dist/src/{history.js → history/history.js} +8 -46
- package/dist/src/index.js +27 -94
- package/dist/src/notes/address.js +97 -16
- package/dist/src/notes/frontmatter.js +18 -3
- package/dist/src/notes/notes-snapshot.js +30 -0
- package/dist/src/notes/paths.js +64 -7
- package/dist/src/notes/session-replay.js +41 -0
- package/dist/src/notes/store.js +76 -22
- package/dist/src/notes/tools.js +7 -7
- package/dist/src/protocol.js +11 -9
- package/dist/src/settings.js +16 -0
- package/dist/src/tool-schema.js +1 -1
- package/dist/test/agent-loop.test.js +813 -213
- package/dist/test/boot.integration.test.js +167 -0
- package/dist/test/budget-settings.integration.test.js +126 -0
- package/dist/test/doctor.test.js +14 -36
- package/dist/test/dream.test.js +37 -380
- package/dist/test/helpers/extension.js +393 -0
- package/dist/test/history.integration.test.js +316 -0
- package/dist/test/notes.integration.test.js +273 -0
- package/dist/test/notes.test.js +40 -370
- package/dist/test/reset-lifecycle.test.js +248 -180
- package/docs/architecture.md +35 -18
- package/docs/reset-lifecycle.md +16 -14
- package/package.json +11 -10
- package/src/context/budget.ts +148 -0
- package/src/context/context-window.ts +103 -0
- package/src/context/prompts.ts +111 -0
- package/src/context/reset-lifecycle.ts +145 -0
- package/src/context/runtime.ts +246 -0
- package/src/context/thresholds.ts +78 -0
- package/src/dream/cli.ts +1 -1
- package/src/dream/doctor.ts +27 -6
- package/src/dream/runner.ts +1 -1
- package/src/dream/settings.ts +32 -0
- package/src/{history-tools.ts → history/history-tools.ts} +3 -3
- package/src/{history.ts → history/history.ts} +9 -48
- package/src/index.ts +27 -89
- package/src/notes/address.ts +82 -16
- package/src/notes/frontmatter.ts +20 -3
- package/src/notes/notes-snapshot.ts +40 -0
- package/src/notes/paths.ts +64 -7
- package/src/notes/session-replay.ts +53 -0
- package/src/notes/store.ts +78 -25
- package/src/notes/tools.ts +7 -7
- package/src/protocol.ts +11 -9
- package/src/settings.ts +20 -0
- package/src/tool-schema.ts +1 -2
- package/dist/src/budget.js +0 -65
- package/dist/src/notes/model.js +0 -101
- package/dist/src/prompts.js +0 -88
- package/dist/src/reset-lifecycle.js +0 -155
- package/dist/src/thresholds.js +0 -102
- package/dist/src/warning.js +0 -44
- package/dist/test/coherence.test.js +0 -371
- package/dist/test/history.test.js +0 -26
- package/dist/test/integration.test.js +0 -1775
- package/dist/test/pagination.property.test.js +0 -471
- package/src/budget.ts +0 -67
- package/src/notes/model.ts +0 -109
- package/src/prompts.ts +0 -91
- package/src/reset-lifecycle.ts +0 -173
- package/src/thresholds.ts +0 -110
- package/src/warning.ts +0 -46
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { getCurrentSystemMessage, Type } from "@earendil-works/pi-ai";
|
|
2
|
+
import { VERSION, defineTool } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { registerBudget } from "./budget.js";
|
|
5
|
+
import { output } from "../tool-output.js";
|
|
6
|
+
import { BOOT_TYPE, RESET_MARKER_TYPE, CONTINUATION_TYPE, CONTINUATION } from "../protocol.js";
|
|
7
|
+
import { agentSlug, migrateLegacyHomes, modelSlug } from "../notes/paths.js";
|
|
8
|
+
import { loadNotesSnapshot } from "../notes/notes-snapshot.js";
|
|
9
|
+
import { renderBootBlock } from "./prompts.js";
|
|
10
|
+
import { currentReset, currentWindowId, isWindowBoot, isWindowMarker, projectRootWindow, projectWindow, rootWindowId } from "./context-window.js";
|
|
11
|
+
import { registerResetLifecycle } from "./reset-lifecycle.js";
|
|
12
|
+
// The bundle captures its identity; direct source loads must not claim a built hash.
|
|
13
|
+
const buildLabel = typeof __PI_CONTEXT_BUILD__ === "undefined"
|
|
14
|
+
? "unbundled source (build unknown)"
|
|
15
|
+
: `${__PI_CONTEXT_BUILD__.version} · build ${__PI_CONTEXT_BUILD__.sourceHash.slice(0, 12)}`;
|
|
16
|
+
function bootContent(ctx, currentId, previousId, resetLine, notes) {
|
|
17
|
+
return renderBootBlock({
|
|
18
|
+
agentName: agentSlug(ctx),
|
|
19
|
+
modelName: modelSlug(ctx),
|
|
20
|
+
firstWindowId: rootWindowId(ctx.sessionManager.getSessionId()),
|
|
21
|
+
currentWindowId: currentId,
|
|
22
|
+
previousWindowId: previousId,
|
|
23
|
+
resetLine,
|
|
24
|
+
notes,
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
function buildResetDrafts(ctx, notifyIncompleteNotes) {
|
|
28
|
+
const sessionPrefix = ctx.sessionManager.getSessionId().slice(0, 8);
|
|
29
|
+
const usedWindowIds = new Set(ctx.sessionManager.getBranch().filter(isWindowMarker).map((entry) => entry.data.windowId));
|
|
30
|
+
let windowId;
|
|
31
|
+
do {
|
|
32
|
+
windowId = `pcw:${sessionPrefix}:${randomUUID().slice(0, 8)}`;
|
|
33
|
+
} while (usedWindowIds.has(windowId));
|
|
34
|
+
const notes = loadNotesSnapshot(ctx);
|
|
35
|
+
notifyIncompleteNotes?.(ctx, windowId, notes);
|
|
36
|
+
return [
|
|
37
|
+
{ type: "custom", customType: RESET_MARKER_TYPE, data: { windowId } },
|
|
38
|
+
{
|
|
39
|
+
type: "custom_message",
|
|
40
|
+
customType: BOOT_TYPE,
|
|
41
|
+
content: bootContent(ctx, windowId, currentWindowId(ctx), true, notes),
|
|
42
|
+
display: false,
|
|
43
|
+
details: { windowId },
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
type: "custom_message",
|
|
47
|
+
customType: CONTINUATION_TYPE,
|
|
48
|
+
content: CONTINUATION,
|
|
49
|
+
display: false,
|
|
50
|
+
},
|
|
51
|
+
];
|
|
52
|
+
}
|
|
53
|
+
function ensureBoot(pi, ctx, notifyIncompleteNotes) {
|
|
54
|
+
const reset = currentReset(ctx);
|
|
55
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
56
|
+
const windowId = reset?.data?.windowId ?? rootWindowId(sessionId);
|
|
57
|
+
if (ctx.sessionManager.buildSessionProjection().messages.some((message) => isWindowBoot(message, windowId)))
|
|
58
|
+
return;
|
|
59
|
+
if (reset && !resetBootMayBeRepaired(ctx, reset.id, windowId))
|
|
60
|
+
return;
|
|
61
|
+
let previousId = reset ? rootWindowId(sessionId) : undefined;
|
|
62
|
+
if (reset) {
|
|
63
|
+
for (const entry of ctx.sessionManager.getBranch()) {
|
|
64
|
+
if (entry.id === reset.id)
|
|
65
|
+
break;
|
|
66
|
+
if (isWindowMarker(entry))
|
|
67
|
+
previousId = entry.data.windowId;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const notes = loadNotesSnapshot(ctx);
|
|
71
|
+
notifyIncompleteNotes?.(ctx, windowId, notes);
|
|
72
|
+
pi.sendMessage({ customType: BOOT_TYPE, content: bootContent(ctx, windowId, previousId, reset !== undefined, notes), display: false, details: { windowId } }, { triggerTurn: false });
|
|
73
|
+
}
|
|
74
|
+
function persistManualReset(pi, ctx, notifyIncompleteNotes) {
|
|
75
|
+
const [marker, boot] = buildResetDrafts(ctx, notifyIncompleteNotes);
|
|
76
|
+
pi.appendEntry(marker.customType, marker.data);
|
|
77
|
+
pi.sendMessage({ customType: boot.customType, content: boot.content, display: boot.display, details: boot.details }, { triggerTurn: false });
|
|
78
|
+
return boot.details.windowId;
|
|
79
|
+
}
|
|
80
|
+
function resetBootMayBeRepaired(ctx, markerId, windowId) {
|
|
81
|
+
const branch = ctx.sessionManager.getBranch();
|
|
82
|
+
const markerIndex = branch.findIndex((entry) => entry.id === markerId);
|
|
83
|
+
if (markerIndex < 0)
|
|
84
|
+
return false;
|
|
85
|
+
const afterMarker = branch.slice(markerIndex + 1);
|
|
86
|
+
// A raw boot is authoritative even when a later context_edit hides it from the
|
|
87
|
+
// projection. Appending another boot at the tail would move the boundary.
|
|
88
|
+
if (afterMarker.some((entry) => isWindowBootEntry(entry, windowId)))
|
|
89
|
+
return false;
|
|
90
|
+
// Only a genuinely incomplete marker tail can be repaired. Once conversation or
|
|
91
|
+
// a context-bearing custom message follows it, refusing is safer than guessing.
|
|
92
|
+
return !afterMarker.some((entry) => entry.type === "message" || entry.type === "custom_message" || entry.type === "compaction" || entry.type === "branch_summary");
|
|
93
|
+
}
|
|
94
|
+
function isWindowBootEntry(entry, windowId) {
|
|
95
|
+
return entry.type === "custom_message" && entry.customType === BOOT_TYPE &&
|
|
96
|
+
typeof entry.details === "object" && entry.details !== null &&
|
|
97
|
+
typeof entry.details.windowId === "string" &&
|
|
98
|
+
entry.details.windowId === windowId;
|
|
99
|
+
}
|
|
100
|
+
function branchHasWindowMarker(ctx, fromId) {
|
|
101
|
+
return ctx.sessionManager.getBranch(fromId).some((entry) => isWindowMarker(entry));
|
|
102
|
+
}
|
|
103
|
+
/** Register the context-window runtime and its context-owned commands/tools. */
|
|
104
|
+
export function registerContext(pi, settingsManager) {
|
|
105
|
+
let enabled = true;
|
|
106
|
+
let missingBootNotice;
|
|
107
|
+
const incompleteNotesNotified = new Set();
|
|
108
|
+
const pendingResetNotices = new Set();
|
|
109
|
+
const notifyCommittedResets = (ctx, addedWindowId) => {
|
|
110
|
+
if (addedWindowId)
|
|
111
|
+
pendingResetNotices.add(addedWindowId);
|
|
112
|
+
if (pendingResetNotices.size === 0)
|
|
113
|
+
return;
|
|
114
|
+
const branch = ctx.sessionManager.getBranch();
|
|
115
|
+
for (const windowId of pendingResetNotices) {
|
|
116
|
+
if (!branch.some((entry) => isWindowMarker(entry) && entry.data.windowId === windowId) ||
|
|
117
|
+
!branch.some((entry) => isWindowBootEntry(entry, windowId)))
|
|
118
|
+
continue;
|
|
119
|
+
pendingResetNotices.delete(windowId);
|
|
120
|
+
ctx.ui.notify(`pi-context: memory cleared · ${windowId}`, "info");
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
// Announce only a committed reset (marker + boot), not a reset request or boot repair.
|
|
124
|
+
pi.on("turn_start", (_event, ctx) => notifyCommittedResets(ctx));
|
|
125
|
+
pi.on("agent_settled", (_event, ctx) => {
|
|
126
|
+
notifyCommittedResets(ctx);
|
|
127
|
+
pendingResetNotices.clear();
|
|
128
|
+
});
|
|
129
|
+
const notifyIncompleteNotes = (ctx, windowId, snapshot) => {
|
|
130
|
+
if (snapshot.unavailable.length === 0 || incompleteNotesNotified.has(windowId))
|
|
131
|
+
return;
|
|
132
|
+
incompleteNotesNotified.add(windowId);
|
|
133
|
+
const homes = snapshot.unavailable.map((home) => home.label).join(", ");
|
|
134
|
+
ctx.ui.notify(`pi-context: notes index incomplete for ${homes}; notes_list can retry after recovery.`, "warning");
|
|
135
|
+
};
|
|
136
|
+
const migrationWarning = migrateLegacyHomes();
|
|
137
|
+
if (migrationWarning)
|
|
138
|
+
console.warn(`pi-context: ${migrationWarning}`);
|
|
139
|
+
const budget = registerBudget(pi, () => enabled, settingsManager);
|
|
140
|
+
pi.on("session_start", (_event, ctx) => {
|
|
141
|
+
if (!enabled)
|
|
142
|
+
return;
|
|
143
|
+
missingBootNotice = undefined;
|
|
144
|
+
pendingResetNotices.clear();
|
|
145
|
+
ensureBoot(pi, ctx, notifyIncompleteNotes);
|
|
146
|
+
});
|
|
147
|
+
pi.on("session_tree", (_event, ctx) => {
|
|
148
|
+
missingBootNotice = undefined;
|
|
149
|
+
pendingResetNotices.clear();
|
|
150
|
+
if (enabled)
|
|
151
|
+
ensureBoot(pi, ctx, notifyIncompleteNotes);
|
|
152
|
+
});
|
|
153
|
+
// Pi's branch summarizer receives raw entries and bypasses context_with_system. Do not
|
|
154
|
+
// let a summary of a reset branch smuggle erased history back into the destination.
|
|
155
|
+
pi.on("session_before_tree", (event, ctx) => {
|
|
156
|
+
if (!event.preparation.userWantsSummary)
|
|
157
|
+
return undefined;
|
|
158
|
+
if (!branchHasWindowMarker(ctx) && !branchHasWindowMarker(ctx, event.preparation.targetId))
|
|
159
|
+
return undefined;
|
|
160
|
+
ctx.ui.notify("pi-context: skipped branch summary across a reset window; navigation continues without erased history.", "info");
|
|
161
|
+
return { summary: { summary: "" } };
|
|
162
|
+
});
|
|
163
|
+
// This is the final provider-facing projection. Reset windows cut at their matching boot;
|
|
164
|
+
// root windows only refresh a forked boot identity and retain the copied root transcript.
|
|
165
|
+
pi.on("context_with_system", (event, ctx) => {
|
|
166
|
+
const reset = currentReset(ctx);
|
|
167
|
+
const windowId = reset?.data.windowId ?? rootWindowId(ctx.sessionManager.getSessionId());
|
|
168
|
+
try {
|
|
169
|
+
return { messages: reset ? projectWindow(event.messages, windowId) : projectRootWindow(event.messages, windowId) };
|
|
170
|
+
}
|
|
171
|
+
catch (error) {
|
|
172
|
+
if (missingBootNotice !== windowId) {
|
|
173
|
+
missingBootNotice = windowId;
|
|
174
|
+
ctx.ui.notify(`pi-context: active context window ${windowId} has no visible boot; request cancelled safely. Use /wipe-memory to start another window.`, "error");
|
|
175
|
+
}
|
|
176
|
+
ctx.abort();
|
|
177
|
+
const safeHead = getCurrentSystemMessage(event.messages);
|
|
178
|
+
return { messages: safeHead ? [safeHead] : [] };
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
pi.registerCommand("pi-context", {
|
|
182
|
+
description: "Show loaded version/build and toggle pi-context context windows",
|
|
183
|
+
getArgumentCompletions: (prefix) => ["on", "off"].filter((a) => a.startsWith(prefix)).map((a) => ({ value: a, label: a })),
|
|
184
|
+
handler: async (args, cmdCtx) => {
|
|
185
|
+
const arg = args.trim().toLowerCase();
|
|
186
|
+
if (arg === "on") {
|
|
187
|
+
enabled = true;
|
|
188
|
+
ensureBoot(pi, cmdCtx, notifyIncompleteNotes);
|
|
189
|
+
}
|
|
190
|
+
else if (arg === "off") {
|
|
191
|
+
enabled = false;
|
|
192
|
+
budget.clear();
|
|
193
|
+
resets.clear();
|
|
194
|
+
}
|
|
195
|
+
else if (arg !== "") {
|
|
196
|
+
cmdCtx.ui.notify("Usage: /pi-context [on|off]", "error");
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
cmdCtx.ui.notify(`pi-context: ${enabled ? "on" : "off"} · ${buildLabel} · Pi ${VERSION}`, "info");
|
|
200
|
+
},
|
|
201
|
+
});
|
|
202
|
+
pi.registerCommand("wipe-memory", {
|
|
203
|
+
description: "Persist a fresh context window without calling the model",
|
|
204
|
+
handler: async (_args, cmdCtx) => {
|
|
205
|
+
if (!enabled) {
|
|
206
|
+
cmdCtx.ui.notify("pi-context: /wipe-memory requires /pi-context on.", "error");
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
await cmdCtx.waitForIdle();
|
|
210
|
+
if (!enabled)
|
|
211
|
+
return;
|
|
212
|
+
resets.clear();
|
|
213
|
+
notifyCommittedResets(cmdCtx, persistManualReset(pi, cmdCtx, notifyIncompleteNotes));
|
|
214
|
+
},
|
|
215
|
+
});
|
|
216
|
+
pi.registerTool(defineTool({
|
|
217
|
+
name: "wipe_memory",
|
|
218
|
+
label: "Wipe memory",
|
|
219
|
+
description: "Wipe your in-context memory and start a fresh context window. Your session, notes, and history survive.",
|
|
220
|
+
parameters: Type.Object({}, { additionalProperties: false }),
|
|
221
|
+
async execute() {
|
|
222
|
+
if (!enabled)
|
|
223
|
+
return output({ error: "pi-context is off (/pi-context on to enable)" });
|
|
224
|
+
return output({ status: resets.request() }, undefined, true);
|
|
225
|
+
},
|
|
226
|
+
}));
|
|
227
|
+
const resets = registerResetLifecycle(pi, {
|
|
228
|
+
isEnabled: () => enabled,
|
|
229
|
+
buildReset: (ctx) => {
|
|
230
|
+
const drafts = buildResetDrafts(ctx, notifyIncompleteNotes);
|
|
231
|
+
pendingResetNotices.add(drafts[1].details.windowId);
|
|
232
|
+
return drafts;
|
|
233
|
+
},
|
|
234
|
+
budget,
|
|
235
|
+
});
|
|
236
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { SettingsManager } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { PI_CONTEXT_SETTINGS_KEY, DEFAULT_RESERVE_TOKENS, DEFAULT_REMINDER_MARGIN_TOKENS, WARNING_RUNWAY_TOKENS } from "../protocol.js";
|
|
3
|
+
import { mergePiContextSettings } from "../settings.js";
|
|
4
|
+
/** A margin is usable only as a positive integer; anything else is ignored. */
|
|
5
|
+
function validMargin(raw) {
|
|
6
|
+
if (typeof raw !== "number" || !Number.isSafeInteger(raw) || raw <= 0)
|
|
7
|
+
return undefined;
|
|
8
|
+
return raw;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Pure derivation of the thresholds from Pi's reserve: the reminder fires at reserve
|
|
12
|
+
* plus the pi-context margin, the warning steer at reserve plus WARNING_RUNWAY_TOKENS.
|
|
13
|
+
* An invalid margin degrades to the default and reports one warning. Automatic
|
|
14
|
+
* threshold/overflow handling is represented by reset lifecycle boundary drafts;
|
|
15
|
+
* no compaction summary is generated.
|
|
16
|
+
*/
|
|
17
|
+
export function deriveThresholds(reserveTokens, margins) {
|
|
18
|
+
const warnings = [];
|
|
19
|
+
const reminderKey = `${PI_CONTEXT_SETTINGS_KEY}.reminderMarginTokens`;
|
|
20
|
+
let reminderMargin;
|
|
21
|
+
if (margins.reminderMarginTokens === undefined)
|
|
22
|
+
reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
|
|
23
|
+
else {
|
|
24
|
+
const parsed = validMargin(margins.reminderMarginTokens);
|
|
25
|
+
if (parsed === undefined) {
|
|
26
|
+
warnings.push(`pi-context: ${reminderKey} must be a positive integer; using default ${DEFAULT_REMINDER_MARGIN_TOKENS}.`);
|
|
27
|
+
reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
|
|
28
|
+
}
|
|
29
|
+
else
|
|
30
|
+
reminderMargin = parsed;
|
|
31
|
+
}
|
|
32
|
+
return { thresholds: { reminder: reserveTokens + reminderMargin, reserve: reserveTokens, warning: reserveTokens + WARNING_RUNWAY_TOKENS }, warnings };
|
|
33
|
+
}
|
|
34
|
+
function readThresholdSettingsFromManager(ctx, settingsManager) {
|
|
35
|
+
// Resolve the active provider/model override from the public settings API.
|
|
36
|
+
const model = ctx.model;
|
|
37
|
+
const compaction = settingsManager.getCompactionSettings(model ? { provider: model.provider, id: model.id } : undefined);
|
|
38
|
+
const derived = deriveThresholds(compaction.reserveTokens, mergePiContextSettings(settingsManager.getGlobalSettings(), settingsManager.getProjectSettings()));
|
|
39
|
+
return { thresholds: derived.thresholds, automatic: compaction.enabled, warnings: derived.warnings };
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Resolve policy from either the explicitly supplied SDK authority or Pi's default
|
|
43
|
+
* file-backed settings. The caller owns diagnostics and any lifecycle caching.
|
|
44
|
+
*/
|
|
45
|
+
export function readThresholdSettings(ctx, settingsManager) {
|
|
46
|
+
try {
|
|
47
|
+
if (settingsManager)
|
|
48
|
+
return readThresholdSettingsFromManager(ctx, settingsManager);
|
|
49
|
+
return readThresholdSettingsFromManager(ctx, SettingsManager.create(ctx.cwd, undefined, { projectTrusted: ctx.isProjectTrusted() }));
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
return {
|
|
53
|
+
thresholds: {
|
|
54
|
+
reminder: DEFAULT_RESERVE_TOKENS + DEFAULT_REMINDER_MARGIN_TOKENS,
|
|
55
|
+
reserve: DEFAULT_RESERVE_TOKENS,
|
|
56
|
+
warning: DEFAULT_RESERVE_TOKENS + WARNING_RUNWAY_TOKENS,
|
|
57
|
+
},
|
|
58
|
+
automatic: true,
|
|
59
|
+
warnings: [`pi-context: could not read settings; using defaults (${String(error)}).`],
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
}
|
package/dist/src/dream/cli.js
CHANGED
|
@@ -6,7 +6,7 @@ import { acquireLock, failLock, lastRunPath, releaseLock } from "./lock.js";
|
|
|
6
6
|
import { materialGate, timeGate } from "./gates.js";
|
|
7
7
|
import { loadPlaybook, runDreamer } from "./runner.js";
|
|
8
8
|
import { gitCommit } from "./git.js";
|
|
9
|
-
import { readDreamerSettings } from "
|
|
9
|
+
import { readDreamerSettings } from "./settings.js";
|
|
10
10
|
import { doctor } from "./doctor.js";
|
|
11
11
|
import { notesRoot } from "../notes/paths.js";
|
|
12
12
|
function args(argv) { const out = {}; for (let i = 0; i < argv.length; i++) {
|
package/dist/src/dream/doctor.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { existsSync, lstatSync, readFileSync, readdirSync } from "node:fs";
|
|
2
2
|
import { basename, join, relative } from "node:path";
|
|
3
|
-
import { assertAddress } from "../notes/address.js";
|
|
3
|
+
import { ADDRESS_FORMS, assertAddress } from "../notes/address.js";
|
|
4
|
+
import { SLUG_PATTERN } from "../notes/paths.js";
|
|
4
5
|
/** Read-only diagnostics. Never follows symlinks or acquires/removes a dream lock. */
|
|
5
6
|
export function doctor(home) {
|
|
6
7
|
const issues = [];
|
|
@@ -56,7 +57,15 @@ export function doctor(home) {
|
|
|
56
57
|
continue;
|
|
57
58
|
try {
|
|
58
59
|
const parsed = assertAddress(address);
|
|
59
|
-
|
|
60
|
+
// Relative homes (@self/, @model/) name whoever is running; a static doctor
|
|
61
|
+
// cannot resolve them, so only absolute links are checked.
|
|
62
|
+
if ((parsed.scope === "agent" || parsed.scope === "model") && parsed.who === undefined)
|
|
63
|
+
continue;
|
|
64
|
+
const targetHome = parsed.scope === "human" ? join(home, "human")
|
|
65
|
+
: parsed.scope === "project" ? project
|
|
66
|
+
: parsed.scope === "agent" ? join(home, "agents", parsed.who)
|
|
67
|
+
: parsed.scope === "model" ? join(home, "models", parsed.who)
|
|
68
|
+
: root;
|
|
60
69
|
if (!targetHome) {
|
|
61
70
|
report(path, `${address}: project context unavailable; use a resolvable reference`);
|
|
62
71
|
continue;
|
|
@@ -65,7 +74,7 @@ export function doctor(home) {
|
|
|
65
74
|
report(path, `${address}: target missing; update or remove the reference`);
|
|
66
75
|
}
|
|
67
76
|
catch {
|
|
68
|
-
report(path, `${address}: invalid address;
|
|
77
|
+
report(path, `${address}: invalid address; ${ADDRESS_FORMS}`);
|
|
69
78
|
}
|
|
70
79
|
}
|
|
71
80
|
};
|
|
@@ -92,7 +101,11 @@ export function doctor(home) {
|
|
|
92
101
|
const path = join(home, name);
|
|
93
102
|
inspect(path, () => {
|
|
94
103
|
if (name === "global") {
|
|
95
|
-
report(path, "legacy home; manually migrate to
|
|
104
|
+
report(path, "legacy home; manually migrate to human/ without overwriting existing files");
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
if (name === "personal") {
|
|
108
|
+
report(path, "legacy home; migrate to human/ (rename the directory), merging by hand if human/ already exists");
|
|
96
109
|
return;
|
|
97
110
|
}
|
|
98
111
|
if (name === ".dream.lock") {
|
|
@@ -102,11 +115,26 @@ export function doctor(home) {
|
|
|
102
115
|
}
|
|
103
116
|
if ([".git", "dreams", "snapshots", "trash", ".dream.lock.last-run"].includes(name))
|
|
104
117
|
return;
|
|
105
|
-
if (name === "
|
|
118
|
+
if (name === "human") {
|
|
106
119
|
if (directory(path))
|
|
107
120
|
walk(path, path);
|
|
108
121
|
return;
|
|
109
122
|
}
|
|
123
|
+
if (name === "agents" || name === "models") {
|
|
124
|
+
if (!directory(path))
|
|
125
|
+
return;
|
|
126
|
+
for (const slug of readdirSync(path)) {
|
|
127
|
+
const dir = join(path, slug);
|
|
128
|
+
inspect(dir, () => {
|
|
129
|
+
if (!SLUG_PATTERN.test(slug))
|
|
130
|
+
report(dir, `invalid ${name.slice(0, -1)} slug; expected [a-z0-9-]`);
|
|
131
|
+
if (!directory(dir))
|
|
132
|
+
return;
|
|
133
|
+
walk(dir, dir);
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
110
138
|
if (name === "project" || name === "pi") {
|
|
111
139
|
if (!directory(path))
|
|
112
140
|
return;
|
|
@@ -130,7 +158,7 @@ export function doctor(home) {
|
|
|
130
158
|
}
|
|
131
159
|
return;
|
|
132
160
|
}
|
|
133
|
-
report(path, "unexpected root entry; expected
|
|
161
|
+
report(path, "unexpected root entry; expected human/, project/, agents/, models/, pi/session/ or dream artifacts");
|
|
134
162
|
});
|
|
135
163
|
}
|
|
136
164
|
});
|
package/dist/src/dream/runner.js
CHANGED
|
@@ -2,7 +2,7 @@ import { readFileSync } from "node:fs";
|
|
|
2
2
|
import { lstat, mkdir, realpath } from "node:fs/promises";
|
|
3
3
|
import { dirname, isAbsolute, relative, resolve } from "node:path";
|
|
4
4
|
import { createAgentSession, createEditToolDefinition, createWriteToolDefinition, ModelRuntime, resolveModelScopeWithDiagnostics, SessionManager } from "@earendil-works/pi-coding-agent";
|
|
5
|
-
import { contentText } from "../history.js";
|
|
5
|
+
import { contentText } from "../history/history.js";
|
|
6
6
|
export const DREAMER_TOOLS = ["read", "grep", "find", "ls", "write", "edit"];
|
|
7
7
|
function isOutside(notesHome, target) {
|
|
8
8
|
const fromHome = relative(notesHome, target);
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { SettingsManager } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { PI_CONTEXT_DREAMER_KEY, PI_CONTEXT_SETTINGS_KEY } from "../protocol.js";
|
|
3
|
+
import { mergePiContextSettings } from "../settings.js";
|
|
4
|
+
/**
|
|
5
|
+
* `pi-context.dreamer` is a non-empty model pattern. Anything else present is ignored
|
|
6
|
+
* with one warning; absent means no configured pattern, so the automatic model applies.
|
|
7
|
+
*/
|
|
8
|
+
export function deriveDreamer(settings) {
|
|
9
|
+
const raw = settings.dreamer;
|
|
10
|
+
if (raw === undefined)
|
|
11
|
+
return { warnings: [] };
|
|
12
|
+
if (typeof raw !== "string" || raw.trim().length === 0) {
|
|
13
|
+
return { warnings: [`pi-context: ${PI_CONTEXT_SETTINGS_KEY}.${PI_CONTEXT_DREAMER_KEY} must be a non-empty string; ignoring it.`] };
|
|
14
|
+
}
|
|
15
|
+
return { pattern: raw.trim(), warnings: [] };
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Resolve the configurable dreamer model from Pi settings for a CLI invocation: global
|
|
19
|
+
* `~/.pi/agent/settings.json` merged with the project's `.pi/settings.json`, project
|
|
20
|
+
* values winning per key. A settings read failure degrades to no pattern with one warning.
|
|
21
|
+
*/
|
|
22
|
+
export function readDreamerSettings(cwd = process.cwd()) {
|
|
23
|
+
try {
|
|
24
|
+
const settingsManager = SettingsManager.create(cwd, undefined, { projectTrusted: true });
|
|
25
|
+
return deriveDreamer(mergePiContextSettings(settingsManager.getGlobalSettings(), settingsManager.getProjectSettings()));
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
return { warnings: [`pi-context: could not read settings; using the automatic dreamer model (${String(error)}).`] };
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Type } from "@earendil-works/pi-ai";
|
|
2
2
|
import { defineTool } from "@earendil-works/pi-coding-agent";
|
|
3
|
-
import { output, outputRaw, page, middleTruncate, prefixFit, earliestMatchOffsetChars, readCharacterWindow, readWindowBlock, withinTextBudget, DEFAULT_READ_WINDOW_CHARS, HISTORY_PREVIEW_CHARS, MAX_READ_WINDOW_CHARS } from "
|
|
4
|
-
import { positiveInteger, recentFirst, nullableString, role, cursor, searchQuery, searchQueries } from "
|
|
3
|
+
import { output, outputRaw, page, middleTruncate, prefixFit, earliestMatchOffsetChars, readCharacterWindow, readWindowBlock, withinTextBudget, DEFAULT_READ_WINDOW_CHARS, HISTORY_PREVIEW_CHARS, MAX_READ_WINDOW_CHARS } from "../tool-output.js";
|
|
4
|
+
import { positiveInteger, recentFirst, nullableString, role, cursor, searchQuery, searchQueries } from "../tool-schema.js";
|
|
5
5
|
import { historyFromSession, filteredItems, visibleItem, allItems, vacuousRoleToolCombo, unknownWindowId } from "./history.js";
|
|
6
6
|
/**
|
|
7
7
|
* Shrink one page item to fit the wire budget. `truncated`/`total_chars` stay honest: the
|
|
@@ -48,7 +48,7 @@ export function registerHistoryTools(pi) {
|
|
|
48
48
|
pi.registerTool(defineTool({
|
|
49
49
|
name: "history_list",
|
|
50
50
|
label: "History list items",
|
|
51
|
-
description: "List durable session items, including items
|
|
51
|
+
description: "List durable session items, including items from earlier reset windows, using opaque item and window IDs; native compaction and branch summaries remain history items in their current window. The role parameter's description enumerates the six roles. Every item carries truncated and total_chars: when truncated is true, truncated_content is a plain prefix of the item's content with no marker, and total_chars is its full code-point length. max_chars_per_item: 1 therefore yields pure addresses you can resolve with history_read.",
|
|
52
52
|
parameters: Type.Object({ limit: positiveInteger(), cursor: cursor(), recent_first: recentFirst(), role: Type.Optional(role), tool_name: nullableString(), window_id: nullableString(), max_chars_per_item: positiveInteger() }, { additionalProperties: false }),
|
|
53
53
|
async execute(_id, params, _signal, _update, ctx) {
|
|
54
54
|
const invalid = vacuousRoleToolCombo(params);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { HISTORY_PREVIEW_CHARS } from "
|
|
1
|
+
import { isWindowMarker, rootWindowId } from "../context/context-window.js";
|
|
2
|
+
import { HISTORY_PREVIEW_CHARS } from "../tool-output.js";
|
|
3
3
|
function isTextContent(part) {
|
|
4
4
|
return typeof part === "object" && part !== null && part.type === "text" && typeof part.text === "string";
|
|
5
5
|
}
|
|
@@ -69,37 +69,22 @@ function toolCallItems(windowId, entry, message) {
|
|
|
69
69
|
}
|
|
70
70
|
return items;
|
|
71
71
|
}
|
|
72
|
-
/** The extension-owned window id baked onto a reset-v2 compaction entry, if present. */
|
|
73
|
-
export function resetV2WindowId(details) {
|
|
74
|
-
if (typeof details !== "object" || details === null)
|
|
75
|
-
return undefined;
|
|
76
|
-
const candidate = details;
|
|
77
|
-
if (candidate.piContext !== RESET_V2 || typeof candidate.windowId !== "string")
|
|
78
|
-
return undefined;
|
|
79
|
-
return candidate.windowId;
|
|
80
|
-
}
|
|
81
|
-
/** A compaction entry's window id: the extension-minted id for reset-v2, else Pi's entry id. */
|
|
82
|
-
export function windowIdOf(sessionId, entry) {
|
|
83
|
-
return resetV2WindowId(entry.details) ?? `pcw:${sessionId.slice(0, 8)}:${entry.id}`;
|
|
84
|
-
}
|
|
85
|
-
/** Mint the durable identity of a session's root history window. */
|
|
86
|
-
export function rootWindowId(sessionId) {
|
|
87
|
-
return `pcw:${sessionId.slice(0, 8)}:root`;
|
|
88
|
-
}
|
|
89
72
|
/** Build durable, on-demand history directly from every entry on the current session branch. */
|
|
90
73
|
export function historyFromSession(ctx) {
|
|
91
74
|
const sessionId = ctx.sessionManager.getSessionId();
|
|
92
75
|
let window = { windowId: rootWindowId(sessionId), items: [] };
|
|
93
76
|
const windows = [window];
|
|
94
77
|
for (const entry of ctx.sessionManager.getBranch()) {
|
|
95
|
-
if (entry
|
|
96
|
-
window = { windowId:
|
|
78
|
+
if (isWindowMarker(entry)) {
|
|
79
|
+
window = { windowId: entry.data.windowId, createdAt: entry.timestamp, items: [] };
|
|
97
80
|
windows.push(window);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (entry.type === "compaction" || entry.type === "branch_summary") {
|
|
98
84
|
window.items.push({
|
|
99
85
|
windowId: window.windowId,
|
|
100
86
|
itemId: entry.id,
|
|
101
|
-
|
|
102
|
-
role: resetV2WindowId(entry.details) === undefined ? "system" : "developer",
|
|
87
|
+
role: "system",
|
|
103
88
|
content: entry.summary,
|
|
104
89
|
createdAt: entry.timestamp,
|
|
105
90
|
});
|
|
@@ -190,26 +175,3 @@ export function filteredItems(ctx, params) {
|
|
|
190
175
|
items.reverse();
|
|
191
176
|
return items;
|
|
192
177
|
}
|
|
193
|
-
/** Persisted messages in the active window, excluding earlier windows on this branch. */
|
|
194
|
-
export function hasWindowMessage(ctx, customType) {
|
|
195
|
-
const branch = ctx.sessionManager.getBranch();
|
|
196
|
-
for (let i = branch.length - 1; i >= 0; i--) {
|
|
197
|
-
const entry = branch[i];
|
|
198
|
-
if (entry.type === "compaction")
|
|
199
|
-
break;
|
|
200
|
-
if (entry.type === "custom_message" && entry.customType === customType)
|
|
201
|
-
return true;
|
|
202
|
-
}
|
|
203
|
-
return false;
|
|
204
|
-
}
|
|
205
|
-
/** Cheap current-window lookup: scan the branch tail for the latest compaction entry. */
|
|
206
|
-
export function currentWindowId(ctx) {
|
|
207
|
-
const sessionId = ctx.sessionManager.getSessionId();
|
|
208
|
-
const branch = ctx.sessionManager.getBranch();
|
|
209
|
-
for (let i = branch.length - 1; i >= 0; i--) {
|
|
210
|
-
const entry = branch[i];
|
|
211
|
-
if (entry?.type === "compaction")
|
|
212
|
-
return windowIdOf(sessionId, entry);
|
|
213
|
-
}
|
|
214
|
-
return rootWindowId(sessionId);
|
|
215
|
-
}
|