proper-base 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
  }