proper-base 0.7.0 → 0.8.1

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/src/settings.ts CHANGED
@@ -1,4 +1,11 @@
1
- import { readFileSync, writeFileSync } from "node:fs";
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ mkdirSync,
4
+ readFileSync,
5
+ renameSync,
6
+ rmSync,
7
+ writeFileSync,
8
+ } from "node:fs";
2
9
  import { join } from "node:path";
3
10
 
4
11
  import type { Component, TUI } from "@earendil-works/pi-tui";
@@ -23,6 +30,13 @@ const TOGGLES = [
23
30
  description:
24
31
  "proper-base: clicking the prompt moves the cursor; off leaves the cursor where typing put it",
25
32
  },
33
+ {
34
+ id: "proper-base-skill-context",
35
+ key: "skillContext",
36
+ label: "Skill context management",
37
+ description:
38
+ "proper-base: load multiple skills, manage snapshots and restore full instructions after compaction; applies to the next run",
39
+ },
26
40
  ] as const;
27
41
  type ToggleKey = (typeof TOGGLES)[number]["key"];
28
42
 
@@ -64,8 +78,13 @@ function readToggle(agentDir: string, key: ToggleKey): boolean {
64
78
  readFileSync(configPath(agentDir), "utf8"),
65
79
  ) as unknown;
66
80
  return (parsed as Record<string, unknown> | null)?.[key] !== false;
67
- } catch {
68
- return true;
81
+ } catch (error) {
82
+ if (
83
+ error instanceof SyntaxError ||
84
+ typeof (error as NodeJS.ErrnoException).code === "string"
85
+ )
86
+ return true;
87
+ throw error;
69
88
  }
70
89
  }
71
90
 
@@ -77,28 +96,59 @@ export function readEditorMouseEnabled(agentDir: string): boolean {
77
96
  return readToggle(agentDir, "editorMouse");
78
97
  }
79
98
 
80
- /** Fail-open like the history store: a read-only agent dir only costs
81
- * persistence, never the session. Other keys in the file are preserved. */
99
+ export function readSkillContextEnabled(agentDir: string): boolean {
100
+ try {
101
+ const parsed: unknown = JSON.parse(
102
+ readFileSync(configPath(agentDir), "utf8"),
103
+ );
104
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
105
+ return false;
106
+ const value = (parsed as Record<string, unknown>).skillContext;
107
+ return value === undefined || value === true;
108
+ } catch (error) {
109
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return true;
110
+ if (
111
+ error instanceof SyntaxError ||
112
+ typeof (error as NodeJS.ErrnoException).code === "string"
113
+ )
114
+ return false;
115
+ throw error;
116
+ }
117
+ }
118
+
119
+ export function writeSkillContextEnabled(
120
+ agentDir: string,
121
+ enabled: boolean,
122
+ ): void {
123
+ writeToggle(agentDir, "skillContext", enabled);
124
+ }
125
+
126
+ /** Fresh-disk merge and atomic replacement; failed saves keep the live value. */
82
127
  function writeToggle(agentDir: string, key: ToggleKey, enabled: boolean): void {
128
+ let parsed: Record<string, unknown> = {};
83
129
  try {
84
- let parsed: Record<string, unknown> = {};
85
- try {
86
- const existing = JSON.parse(
87
- readFileSync(configPath(agentDir), "utf8"),
88
- ) as unknown;
89
- if (existing && typeof existing === "object") {
90
- parsed = existing as Record<string, unknown>;
91
- }
92
- } catch {
93
- // Damaged or absent config starts fresh.
94
- }
95
- parsed[key] = enabled;
96
- writeFileSync(
97
- configPath(agentDir),
98
- `${JSON.stringify(parsed, null, "\t")}\n`,
130
+ const existing: unknown = JSON.parse(
131
+ readFileSync(configPath(agentDir), "utf8"),
99
132
  );
100
- } catch {
101
- // Persistence is best-effort.
133
+ if (!existing || typeof existing !== "object" || Array.isArray(existing))
134
+ throw new SyntaxError(
135
+ "proper-base.json must contain an object; preference was not saved.",
136
+ );
137
+ parsed = existing as Record<string, unknown>;
138
+ } catch (error) {
139
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
140
+ }
141
+ parsed[key] = enabled;
142
+ mkdirSync(agentDir, { recursive: true });
143
+ const temporary = `${configPath(agentDir)}.${randomUUID()}.tmp`;
144
+ try {
145
+ writeFileSync(temporary, `${JSON.stringify(parsed, null, "\t")}\n`, {
146
+ flag: "wx",
147
+ mode: 0o600,
148
+ });
149
+ renameSync(temporary, configPath(agentDir));
150
+ } finally {
151
+ rmSync(temporary, { force: true });
102
152
  }
103
153
  }
104
154
 
@@ -139,8 +189,7 @@ function findEditorContainer(
139
189
  }
140
190
 
141
191
  /**
142
- * Add proper-base's toggles to Pi's native `/settings` menu: the session
143
- * action rail and prompt mouse clicks.
192
+ * Add proper-base's toggles to Pi's native `/settings` menu.
144
193
  *
145
194
  * Pi has no extension hook into that menu, so this is a guarded
146
195
  * compatibility layer in the house style: the container Pi mounts selectors
@@ -148,11 +197,11 @@ function findEditorContainer(
148
197
  * settings selector that mounts receives the extra items spliced into its
149
198
  * `SettingsList`, whose instance-held `onChange` is wrapped to keep the
150
199
  * toggles out of Pi's own switch. A renamed component or list shape installs
151
- * or injects nothing and both features simply stay enabled.
200
+ * or injects nothing; config-file and command controls remain available.
152
201
  *
153
- * Choices persist as `sessionRail` and `editorMouse` in the agent
154
- * directory's `proper-base.json`; other sessions pick a change up at their
155
- * next start.
202
+ * Choices persist as `sessionRail`, `editorMouse` and `skillContext` in the
203
+ * agent directory's `proper-base.json`. Skill management reads its preference
204
+ * at the next run; the editor toggles remain cached for the session.
156
205
  *
157
206
  * @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Session action rail]]
158
207
  * @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Prompt mouse clicks]]
@@ -161,15 +210,18 @@ export function installSettings(
161
210
  tui: TUI,
162
211
  editor: Component,
163
212
  agentDir: string,
213
+ onError?: (error: Error) => void,
164
214
  ): SettingsController {
165
215
  const state: Record<ToggleKey, boolean> = {
166
216
  sessionRail: readToggle(agentDir, "sessionRail"),
167
217
  editorMouse: readToggle(agentDir, "editorMouse"),
218
+ skillContext: readSkillContextEnabled(agentDir),
168
219
  };
169
220
  let disposed = false;
170
221
  let uninstall: (() => void) | undefined;
171
222
 
172
223
  const inject = (selector: SettingsHost): void => {
224
+ state.skillContext = readSkillContextEnabled(agentDir);
173
225
  const list = selector.settingsList;
174
226
  const items = list?.items;
175
227
  if (!list || !Array.isArray(items) || typeof list.onChange !== "function")
@@ -188,8 +240,20 @@ export function installSettings(
188
240
  list.onChange = (id, value) => {
189
241
  const toggle = TOGGLES.find((entry) => entry.id === id);
190
242
  if (toggle) {
191
- state[toggle.key] = value === "true";
192
- writeToggle(agentDir, toggle.key, state[toggle.key]);
243
+ if (disposed || (value !== "true" && value !== "false")) return;
244
+ try {
245
+ writeToggle(agentDir, toggle.key, value === "true");
246
+ state[toggle.key] = value === "true";
247
+ } catch (error) {
248
+ if (
249
+ !(error instanceof SyntaxError) &&
250
+ typeof (error as NodeJS.ErrnoException).code !== "string"
251
+ )
252
+ throw error;
253
+ onError?.(error as Error);
254
+ }
255
+ const item = items.find((entry) => entry.id === id);
256
+ if (item) item.currentValue = String(state[toggle.key]);
193
257
  return;
194
258
  }
195
259
  native(id, value);
@@ -1,31 +1,79 @@
1
+ import { createHash } from "node:crypto";
1
2
  import {
2
3
  type ContextEditEntry,
3
4
  parseSkillBlock,
4
5
  } from "@earendil-works/pi-coding-agent";
5
6
 
6
- /**
7
- * Characters kept from a complete skill block when it is carried across a
8
- * compaction. Roughly four characters per token, matching the estimate Pi's
9
- * own compaction uses.
10
- */
11
- const MAX_SKILL_CHARS = 16000;
12
- /** Combined character budget for every skill carried across one compaction. */
13
- const MAX_CARRY_CHARS = 24000;
14
- const TRUNCATED = "\n\n[skill content truncated to fit the context budget]";
7
+ export const SKILL_CONTEXT_ENTRY = "proper-base-skill-context";
8
+ export const SKILL_CONTEXT_TOOL = "skill_context";
9
+ /** Full instruction bodies above this threshold require user confirmation. */
10
+ export const SKILL_CONTEXT_WARNING_CHARS = 200_000;
11
+ const RESTORE_START = "<proper_base_skill_context>\n";
12
+ const RESTORE_END = "\n</proper_base_skill_context>\n\n";
15
13
 
16
- type ContextMessage = {
14
+ export type SkillSnapshot = {
15
+ name: string;
16
+ location: string;
17
+ block: string;
18
+ hash: string;
19
+ };
20
+ export type SkillSelection = SkillSnapshot & {
21
+ selected: boolean;
22
+ source: "user" | "model";
23
+ };
24
+ export type SkillChange =
25
+ | { action: "load"; blocks: string[] }
26
+ | { action: "remove"; locations: string[] }
27
+ | { action: "clear" };
28
+ export type ContextMessage = {
17
29
  role: string;
18
30
  content?: unknown;
31
+ summary?: string;
32
+ toolName?: string;
33
+ isError?: boolean;
19
34
  };
20
- type TextPart = { type: "text"; text: string };
21
- type BranchEntry = {
35
+ export type SkillBranchEntry = {
22
36
  type: string;
23
37
  id?: string;
24
38
  targetId?: string;
25
39
  replacement?: ContextEditEntry["replacement"];
26
- message?: { role?: string; content?: unknown };
40
+ message?: ContextMessage;
41
+ customType?: string;
42
+ data?: unknown;
27
43
  };
28
- type Invocation = { name: string; block: string };
44
+ type TextPart = { type: "text"; text: string };
45
+
46
+ export class SkillContextError extends Error {}
47
+
48
+ export function skillSnapshot(block: string): SkillSnapshot | undefined {
49
+ const parsed = parseSkillBlock(block);
50
+ if (!parsed || parsed.userMessage) return undefined;
51
+ return {
52
+ name: parsed.name,
53
+ location: parsed.location,
54
+ block,
55
+ hash: createHash("sha256").update(block).digest("hex"),
56
+ };
57
+ }
58
+
59
+ /** Only leading Pi skill blocks are instructions, never quoted inline examples. */
60
+ export function splitSkillText(text: string): {
61
+ skills: SkillSnapshot[];
62
+ request: string;
63
+ } {
64
+ const skills: SkillSnapshot[] = [];
65
+ let request = text;
66
+ while (request.startsWith('<skill name="')) {
67
+ const parsed = parseSkillBlock(request);
68
+ if (!parsed) break;
69
+ const block = `<skill name="${parsed.name}" location="${parsed.location}">\n${parsed.content}\n</skill>`;
70
+ const snapshot = skillSnapshot(block);
71
+ if (!snapshot) break;
72
+ skills.push(snapshot);
73
+ request = parsed.userMessage ?? "";
74
+ }
75
+ return { skills, request };
76
+ }
29
77
 
30
78
  function isTextPart(value: unknown): value is TextPart {
31
79
  return (
@@ -36,203 +84,196 @@ function isTextPart(value: unknown): value is TextPart {
36
84
  );
37
85
  }
38
86
 
39
- /**
40
- * Pi renders a skill invocation as one text part holding the block followed by
41
- * the user's own request, so both live in a single message.
42
- */
43
- function readInvocation(
44
- text: string,
45
- ): { name: string; block: string; request: string } | undefined {
46
- const parsed = parseSkillBlock(text);
47
- if (!parsed) return undefined;
48
- return {
49
- name: parsed.name,
50
- block: `<skill name="${parsed.name}" location="${parsed.location}">\n${parsed.content}\n</skill>`,
51
- request: parsed.userMessage ?? "",
52
- };
87
+ function texts(message: ContextMessage): string[] {
88
+ if (typeof message.content === "string") return [message.content];
89
+ return Array.isArray(message.content)
90
+ ? message.content.filter(isTextPart).map((part) => part.text)
91
+ : [];
53
92
  }
54
93
 
55
- function messageInvocation(
56
- message: ContextMessage | BranchEntry["message"],
57
- ): ReturnType<typeof readInvocation> {
58
- const content = message?.content;
59
- if (typeof content === "string") return readInvocation(content);
60
- if (!Array.isArray(content)) return undefined;
61
- for (const part of content) {
62
- if (!isTextPart(part)) continue;
63
- const invocation = readInvocation(part.text);
64
- if (invocation) return invocation;
65
- }
66
- return undefined;
94
+ function skillMessage(message: ContextMessage): boolean {
95
+ return (
96
+ message.role === "user" ||
97
+ (message.role === "toolResult" &&
98
+ message.toolName === SKILL_CONTEXT_TOOL &&
99
+ message.isError !== true)
100
+ );
67
101
  }
68
102
 
69
- function replaceInvocationText(
70
- message: ContextMessage,
71
- replacement: string,
72
- ): ContextMessage {
73
- const content = message.content;
74
- if (typeof content === "string") {
75
- return { ...message, content: replacement };
103
+ function mapText<T extends ContextMessage>(
104
+ message: T,
105
+ transform: (text: string) => string,
106
+ ): T {
107
+ if (typeof message.content === "string") {
108
+ const content = transform(message.content);
109
+ return content === message.content ? message : { ...message, content };
76
110
  }
77
- if (!Array.isArray(content)) return message;
78
- let done = false;
79
- const next = content.map((part) => {
80
- if (done || !isTextPart(part) || !parseSkillBlock(part.text)) return part;
81
- done = true;
82
- return { ...part, text: replacement };
111
+ if (!Array.isArray(message.content)) return message;
112
+ let changed = false;
113
+ const content = message.content.map((part) => {
114
+ if (!isTextPart(part)) return part;
115
+ const text = transform(part.text);
116
+ if (text === part.text) return part;
117
+ changed = true;
118
+ return { ...part, text };
83
119
  });
84
- return done ? { ...message, content: next } : message;
120
+ return changed ? { ...message, content } : message;
85
121
  }
86
122
 
87
- function prependText(message: ContextMessage, prefix: string): ContextMessage {
88
- const content = message.content;
89
- if (typeof content === "string") {
90
- return { ...message, content: `${prefix}${content}` };
123
+ /** Apply branch-local edits before interpreting invocation or control records. */
124
+ export function selectedSkills(branch: SkillBranchEntry[]): SkillSelection[] {
125
+ const edits = new Map<string, ContextEditEntry["replacement"]>();
126
+ for (const entry of branch) {
127
+ if (entry.type === "context_edit" && entry.targetId)
128
+ edits.set(entry.targetId, entry.replacement ?? null);
91
129
  }
92
- if (!Array.isArray(content)) return message;
93
- const index = content.findIndex(isTextPart);
94
- if (index < 0) {
95
- return {
96
- ...message,
97
- content: [{ type: "text", text: prefix }, ...content],
98
- };
130
+ const state = new Map<string, SkillSelection>();
131
+ const load = (block: string, source: SkillSelection["source"]) => {
132
+ for (const skill of splitSkillText(block).skills) {
133
+ const previous = state.get(skill.location);
134
+ state.delete(skill.location);
135
+ state.set(skill.location, {
136
+ ...skill,
137
+ selected: true,
138
+ source:
139
+ previous?.selected && previous.source === "user" ? "user" : source,
140
+ });
141
+ }
142
+ };
143
+ for (const entry of branch) {
144
+ if (entry.type === "message" && entry.message) {
145
+ let message = entry.message;
146
+ if (entry.id && edits.has(entry.id)) {
147
+ const replacement = edits.get(entry.id);
148
+ if (!replacement) continue;
149
+ message = { ...message, content: replacement.content };
150
+ }
151
+ if (skillMessage(message))
152
+ for (const text of texts(message))
153
+ load(text, message.role === "user" ? "user" : "model");
154
+ } else if (
155
+ entry.type === "custom" &&
156
+ entry.customType === SKILL_CONTEXT_ENTRY &&
157
+ entry.data &&
158
+ typeof entry.data === "object"
159
+ ) {
160
+ const data = entry.data as Partial<SkillChange>;
161
+ if (data.action === "load" && Array.isArray(data.blocks)) {
162
+ for (const block of data.blocks)
163
+ if (typeof block === "string") load(block, "user");
164
+ } else if (data.action === "clear") {
165
+ for (const skill of state.values()) skill.selected = false;
166
+ } else if (data.action === "remove" && Array.isArray(data.locations)) {
167
+ for (const location of data.locations) {
168
+ const skill = state.get(location);
169
+ if (skill) skill.selected = false;
170
+ }
171
+ }
172
+ }
99
173
  }
100
- const part = content[index] as TextPart;
101
- const next = [...content];
102
- next[index] = { ...part, text: `${prefix}${part.text}` };
103
- return { ...message, content: next };
174
+ return [...state.values()];
104
175
  }
105
176
 
106
- function truncate(block: string, limit: number): string | undefined {
107
- if (block.length <= limit) return block;
108
- const suffix = `${TRUNCATED}\n</skill>`;
109
- // Never cut the opening tag or omit the closing tag. An oversized header
110
- // cannot fit safely, so leave that skill out rather than emit broken markup.
111
- if (block.indexOf("\n") + 1 + suffix.length > limit) return undefined;
112
- return block.slice(0, limit - suffix.length) + suffix;
113
- }
114
-
115
- function contextEdits(
116
- branch: BranchEntry[],
117
- ): Map<string, ContextEditEntry["replacement"]> {
118
- const edits = new Map<string, ContextEditEntry["replacement"]>();
119
- for (const entry of branch) {
120
- if (entry.type !== "context_edit" || typeof entry.targetId !== "string")
121
- continue;
122
- edits.set(entry.targetId, entry.replacement ?? null);
123
- }
124
- return edits;
177
+ export function skillContextChars(skills: SkillSnapshot[]): number {
178
+ return skills.reduce((sum, skill) => sum + skill.block.length + 2, 0);
125
179
  }
126
180
 
127
- function visibleBranchMessage(
128
- entry: BranchEntry,
129
- edits: Map<string, ContextEditEntry["replacement"]>,
130
- ): BranchEntry["message"] | undefined {
131
- if (entry.type !== "message" || entry.message?.role !== "user")
132
- return undefined;
133
- if (!entry.id || !edits.has(entry.id)) return entry.message;
134
- const replacement = edits.get(entry.id);
135
- if (replacement === null || !replacement) return undefined;
136
- return { ...entry.message, content: replacement.content };
181
+ function stripRestore(text: string): string {
182
+ const start = text.indexOf(RESTORE_START);
183
+ if (start < 0) return text;
184
+ const end = text.indexOf(RESTORE_END, start);
185
+ return end < 0
186
+ ? text
187
+ : text.slice(0, start) + text.slice(end + RESTORE_END.length);
137
188
  }
138
189
 
139
190
  /**
140
- * Keep every invoked skill present exactly once in the outgoing context.
141
- *
142
- * Pi inlines the whole `SKILL.md` body into a user message and then treats that
143
- * message like any other: re-invoking a skill appends a second full copy, and
144
- * compaction summarizes the copy away while the model keeps working under
145
- * instructions it can no longer read. This collapses repeats to a short note
146
- * and carries the most recent body across a compaction boundary, bounded by a
147
- * character budget so the restored text cannot re-trigger the compaction that
148
- * just ran.
149
- *
150
- * The first copy is never rewritten, so the cached request prefix stays byte
151
- * stable across turns.
191
+ * Project full selected snapshots without changing stored messages. Restoring
192
+ * reference instructions is not a new workflow invocation. The branch is the
193
+ * registry, so resume, forks, context edits and /clear need no second store.
194
+ * @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Skill context]]
152
195
  */
153
196
  export function pinSkillContext<T extends ContextMessage>(
154
197
  messages: T[],
155
- branch: BranchEntry[],
198
+ branch: SkillBranchEntry[],
156
199
  ): T[] {
157
- const seen = new Set<string>();
158
- let changed = false;
159
-
160
- let next = messages.map((message) => {
161
- if (message.role !== "user") return message;
162
- const invocation = messageInvocation(message);
163
- if (!invocation) return message;
164
- if (!seen.has(invocation.block)) {
165
- seen.add(invocation.block);
166
- return message;
200
+ const selections = selectedSkills(branch);
201
+ const active = selections.filter((skill) => skill.selected);
202
+ const state = new Map(selections.map((skill) => [skill.location, skill]));
203
+ const present = new Set<string>();
204
+ const next = messages.map((original) => {
205
+ let message = original;
206
+ if (message.role === "compactionSummary" && message.summary) {
207
+ const summary = stripRestore(message.summary);
208
+ if (summary !== message.summary) message = { ...message, summary };
167
209
  }
168
- changed = true;
169
- const note = `[skill "${invocation.name}" is already loaded earlier in this conversation]`;
170
- return replaceInvocationText(
171
- message,
172
- invocation.request ? `${note}\n\n${invocation.request}` : note,
173
- ) as T;
210
+ if (!skillMessage(message)) return message;
211
+ return mapText(message, (raw) => {
212
+ const text = stripRestore(raw);
213
+ const { skills, request } = splitSkillText(text);
214
+ if (!skills.length) return text;
215
+ let changed = false;
216
+ const blocks: string[] = [];
217
+ const notes: string[] = [];
218
+ for (const skill of skills) {
219
+ const selection = state.get(skill.location);
220
+ let reason: string | undefined;
221
+ if (selection && !selection.selected) reason = "inactive";
222
+ else if (selection && selection.hash !== skill.hash)
223
+ reason = "superseded";
224
+ else if (present.has(skill.hash))
225
+ reason = "already loaded earlier in this conversation";
226
+ else present.add(skill.hash);
227
+ if (!reason) blocks.push(skill.block);
228
+ else {
229
+ changed = true;
230
+ notes.push(
231
+ `[skill ${JSON.stringify(skill.name)} is ${reason}; this request remains a separate request]`,
232
+ );
233
+ }
234
+ }
235
+ return changed
236
+ ? [...blocks, ...notes, ...(request ? [request] : [])].join("\n\n")
237
+ : text;
238
+ });
174
239
  });
175
-
176
- const carried = carryAcrossCompaction(next, branch, seen);
177
- if (!carried) return changed ? next : messages;
178
-
179
- const anchor = restoreAnchor(next);
180
- if (anchor < 0) return changed ? next : messages;
181
- next = [...next];
182
- next[anchor] = prependText(next[anchor] as ContextMessage, carried) as T;
183
- return next;
184
- }
185
-
186
- /**
187
- * Collect the newest body of each skill that the branch invoked but the
188
- * compacted context no longer carries, newest first until the budget runs out.
189
- */
190
- function carryAcrossCompaction(
191
- messages: ContextMessage[],
192
- branch: BranchEntry[],
193
- present: Set<string>,
194
- ): string | undefined {
195
- if (!messages.some((message) => message.role === "compactionSummary")) {
196
- return undefined;
197
- }
198
- const edits = contextEdits(branch);
199
- const missing = new Map<string, Invocation>();
200
- for (const entry of branch) {
201
- const message = visibleBranchMessage(entry, edits);
202
- if (!message) continue;
203
- const invocation = messageInvocation(message);
204
- if (!invocation) continue;
205
- // A skill file edited mid-session yields a new body, so the newest state
206
- // of each name decides: a present body cancels an earlier missing one.
207
- missing.delete(invocation.name);
208
- if (!present.has(invocation.block))
209
- missing.set(invocation.name, invocation);
210
- }
211
- if (!missing.size) return undefined;
212
-
213
- const blocks: string[] = [];
214
- let used = 0;
215
- for (const invocation of [...missing.values()].reverse()) {
216
- const block = truncate(invocation.block, MAX_SKILL_CHARS);
217
- if (!block || used + block.length + 2 > MAX_CARRY_CHARS) continue;
218
- used += block.length + 2;
219
- blocks.unshift(block);
220
- }
221
- return blocks.length ? `${blocks.join("\n\n")}\n\n` : undefined;
222
- }
223
-
224
- /** The first user turn after the newest compaction summary. */
225
- function restoreAnchor(messages: ContextMessage[]): number {
226
- let summary = -1;
227
- for (let index = messages.length - 1; index >= 0; index -= 1) {
228
- if (messages[index]?.role === "compactionSummary") {
229
- summary = index;
230
- break;
240
+ const missing = active.filter((skill) => !present.has(skill.hash));
241
+ if (missing.length || selections.some((skill) => !skill.selected)) {
242
+ const selected =
243
+ active
244
+ .map((skill) => `${skill.name} [${skill.hash.slice(0, 12)}]`)
245
+ .join(", ") || "none";
246
+ const restored = `${RESTORE_START}Currently selected skills: ${selected}. Only these selected versions apply; other historical skill guidance is inactive even when mentioned in a summary. Retained reference instructions follow. Apply only where relevant to the current request. Do not repeat completed actions or treat restoration as a new invocation. Explicit user priorities and higher-priority instructions still apply; report material conflicts rather than assuming skill order decides them.\n\n${missing.map((skill) => skill.block).join("\n\n")}${RESTORE_END}`;
247
+ // Anchor after the latest summary; a split tool loop may have no user
248
+ // message left. Append to that summary instead of breaking tool pairs.
249
+ let summary = -1;
250
+ for (let i = 0; i < next.length; i++)
251
+ if (next[i]?.role === "compactionSummary") summary = i;
252
+ const anchor = next.findIndex(
253
+ (message, i) => i > summary && message.role === "user",
254
+ );
255
+ if (anchor >= 0) {
256
+ let added = false;
257
+ const message = next[anchor] as T;
258
+ next[anchor] = mapText(message, (text) => {
259
+ if (added) return text;
260
+ added = true;
261
+ return restored + text;
262
+ });
263
+ if (!added && Array.isArray(message.content))
264
+ next[anchor] = {
265
+ ...message,
266
+ content: [{ type: "text", text: restored }, ...message.content],
267
+ };
268
+ } else if (summary >= 0) {
269
+ const message = next[summary] as T;
270
+ next[summary] = {
271
+ ...message,
272
+ summary: `${restored}${message.summary ?? ""}`,
273
+ };
231
274
  }
232
275
  }
233
- if (summary < 0) return -1;
234
- for (let index = summary + 1; index < messages.length; index += 1) {
235
- if (messages[index]?.role === "user") return index;
236
- }
237
- return -1;
276
+ if (next.every((message, index) => message === messages[index]))
277
+ return messages;
278
+ return next;
238
279
  }