@aeondave/pi-persona-mind 0.0.0-stage → 0.8.4
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/AGENTS.md +78 -0
- package/CHANGELOG.md +78 -0
- package/LICENSE +24 -0
- package/README.md +244 -2
- package/assets/banner.png +0 -0
- package/docs/DESIGN.md +282 -0
- package/docs/MEMORY-RESEARCH.md +112 -0
- package/package.json +93 -4
- package/src/core/auto-optimize.ts +239 -0
- package/src/core/backlog.ts +228 -0
- package/src/core/blocked.ts +38 -0
- package/src/core/capture.ts +146 -0
- package/src/core/context-budget.ts +74 -0
- package/src/core/host-compat.ts +13 -0
- package/src/core/ids.ts +59 -0
- package/src/core/inject.ts +247 -0
- package/src/core/memory-read.ts +34 -0
- package/src/core/memory.ts +308 -0
- package/src/core/migrate.ts +713 -0
- package/src/core/mind-settings.ts +54 -0
- package/src/core/optimize-history.ts +101 -0
- package/src/core/optimize-service.ts +182 -0
- package/src/core/optimize.ts +133 -0
- package/src/core/retrieval.ts +108 -0
- package/src/core/scanner.ts +146 -0
- package/src/core/scope.ts +205 -0
- package/src/core/service.ts +644 -0
- package/src/core/session-memory.ts +71 -0
- package/src/core/store.ts +948 -0
- package/src/extension/activity.ts +79 -0
- package/src/extension/auto-optimize-session.ts +118 -0
- package/src/extension/auto-optimize.ts +265 -0
- package/src/extension/mind-command.ts +335 -0
- package/src/extension/mind-worker.ts +32 -0
- package/src/extension/persona-dependency.ts +76 -0
- package/src/index.ts +1231 -0
- package/src/session-memory.ts +118 -0
- package/src/tools/backlog.ts +126 -0
- package/src/tools/memory-optimize.ts +133 -0
- package/src/tools/memory.ts +400 -0
- package/src/ui/mind-result-card.ts +15 -0
- package/src/ui/presentation.ts +97 -0
- package/src/ui/session-note-card.ts +50 -0
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `memory` tool — the agent-facing surface for durable knowledge.
|
|
3
|
+
*
|
|
4
|
+
* remember: store a fact, long-term (durable persona identity) or short-term (decaying project
|
|
5
|
+
* note). recall: keyword + recency search. forget: delete by id. All content is declarative and
|
|
6
|
+
* scanned before it is persisted (the service enforces both). Thin glue: it translates tool
|
|
7
|
+
* parameters into MindService calls and formats the result the model sees.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
11
|
+
import { Type } from "typebox";
|
|
12
|
+
|
|
13
|
+
import { renderExpandableResult, toolResultText } from "../ui/presentation.ts";
|
|
14
|
+
|
|
15
|
+
import {
|
|
16
|
+
clampRecallMax,
|
|
17
|
+
compactMemoryText,
|
|
18
|
+
isMemoryId,
|
|
19
|
+
MEMORY_KINDS,
|
|
20
|
+
MAX_MEMORY_DERIVED_IDS,
|
|
21
|
+
MAX_MEMORY_ID_CHARS,
|
|
22
|
+
MAX_MEMORY_SOURCE_CHARS,
|
|
23
|
+
MAX_MEMORY_TAGS,
|
|
24
|
+
MAX_MEMORY_TAG_CHARS,
|
|
25
|
+
MAX_MEMORY_TEXT_CHARS,
|
|
26
|
+
MAX_RECALL_QUERY_CHARS,
|
|
27
|
+
} from "../core/memory.ts";
|
|
28
|
+
import type { MindService, RememberInput } from "../core/service.ts";
|
|
29
|
+
import type { SessionMemory } from "../session-memory.ts";
|
|
30
|
+
import type { MemoryOptimizer } from "../core/optimize-service.ts";
|
|
31
|
+
import { isOptimizeOperation, MAX_OPTIMIZE_TOTAL_SOURCES, runOptimizeAction } from "./memory-optimize.ts";
|
|
32
|
+
import { isOptimizeTarget, MAX_OPTIMIZE_OPERATIONS } from "../core/optimize.ts";
|
|
33
|
+
import { DEFAULT_STORE_MAX_ENTRIES } from "../core/store.ts";
|
|
34
|
+
import { runMindActivity } from "../extension/activity.ts";
|
|
35
|
+
import type { MindActivityRunner } from "../extension/activity.ts";
|
|
36
|
+
|
|
37
|
+
export type GetMind = (ctx: ExtensionContext) => MindService;
|
|
38
|
+
|
|
39
|
+
const MemoryParams = Type.Object({
|
|
40
|
+
action: Type.Union([Type.Literal("remember"), Type.Literal("recall"), Type.Literal("read"), Type.Literal("forget"), Type.Literal("promote"), Type.Literal("optimize")], {
|
|
41
|
+
description: "remember = store · recall = search · read = retrieve full text · forget = delete/tombstone by id · promote = graduate short-term · optimize = inspect, stage, or explicitly apply a consolidation",
|
|
42
|
+
}),
|
|
43
|
+
term: Type.Optional(
|
|
44
|
+
Type.Union([Type.Literal("long"), Type.Literal("short"), Type.Literal("session")], {
|
|
45
|
+
description: "remember: long = durable persona identity; short = expiring project note; session = active-branch note only, never copied into persona archives. Required for remember.",
|
|
46
|
+
}),
|
|
47
|
+
),
|
|
48
|
+
kind: Type.Optional(
|
|
49
|
+
Type.Union(
|
|
50
|
+
MEMORY_KINDS.map((k) => Type.Literal(k)),
|
|
51
|
+
{ description: "remember: the category of the fact. Required for remember." },
|
|
52
|
+
),
|
|
53
|
+
),
|
|
54
|
+
text: Type.Optional(
|
|
55
|
+
Type.String({
|
|
56
|
+
maxLength: MAX_MEMORY_TEXT_CHARS,
|
|
57
|
+
description:
|
|
58
|
+
"remember: the fact, DECLARATIVE not imperative ('the user prefers verbose recon', never 'always be verbose'). Do not store secrets or anything re-derivable from the repo. Required for remember.",
|
|
59
|
+
}),
|
|
60
|
+
),
|
|
61
|
+
tags: Type.Optional(Type.Array(Type.String({ maxLength: MAX_MEMORY_TAG_CHARS }), { maxItems: MAX_MEMORY_TAGS, description: "optional tags to aid later recall" })),
|
|
62
|
+
ttlHours: Type.Optional(Type.Number({ exclusiveMinimum: 0, description: "remember(short): hours until it is deleted from the store (default 48)" })),
|
|
63
|
+
supersedes: Type.Optional(Type.String({ maxLength: MAX_MEMORY_ID_CHARS, description: "remember: id of an existing entry this one replaces" })),
|
|
64
|
+
source: Type.Optional(Type.String({ maxLength: MAX_MEMORY_SOURCE_CHARS, description: "remember: optional human-citable origin of this fact (e.g. 'the user said', 'child scout')" })),
|
|
65
|
+
derivedFrom: Type.Optional(Type.Array(Type.String({ maxLength: MAX_MEMORY_ID_CHARS }), { maxItems: MAX_MEMORY_DERIVED_IDS, description: "remember: optional ids of memories distilled into this fact" })),
|
|
66
|
+
query: Type.Optional(Type.String({ maxLength: MAX_RECALL_QUERY_CHARS, description: "recall: keywords (empty = most recent); optimize inspect: optional substring filter" })),
|
|
67
|
+
scope: Type.Optional(
|
|
68
|
+
Type.Union([Type.Literal("long"), Type.Literal("short"), Type.Literal("both"), Type.Literal("session"), Type.Literal("project"), Type.Literal("persona"), Type.Literal("shared")], { description: "remember/promote: project|persona|shared; long remember defaults persona, promote defaults project. recall/read/forget: project includes repository durable + working facts; long includes all durable tiers; both includes all active stores; session is branch-local." }),
|
|
69
|
+
),
|
|
70
|
+
max: Type.Optional(Type.Number({ description: "recall: maximum results, clamped to 1..50 (default 8); optimize inspect: entry page 1..100 (default 20)" })),
|
|
71
|
+
offset: Type.Optional(Type.Number({ minimum: 0, maximum: DEFAULT_STORE_MAX_ENTRIES, multipleOf: 1, description: `optimize inspect: zero-based page offset from 0 to ${DEFAULT_STORE_MAX_ENTRIES} (default 0)` })),
|
|
72
|
+
id: Type.Optional(Type.String({ maxLength: MAX_MEMORY_ID_CHARS, description: "read/forget/promote: exact entry id; session:<UUID> addresses an active-session note" })),
|
|
73
|
+
mode: Type.Optional(Type.Union([Type.Literal("inspect"), Type.Literal("stage"), Type.Literal("apply"), Type.Literal("history"), Type.Literal("undo")], { description: "optimize: inspect candidates; stage an immutable proposal; apply a plan; history retrieves bounded durable before/after receipts; undo safely restores a receipt's unchanged affected facts (default inspect)" })),
|
|
74
|
+
target: Type.Optional(Type.Union([Type.Literal("project"), Type.Literal("project-long"), Type.Literal("persona"), Type.Literal("shared")], { description: "optimize: project = working memory, project-long = durable repository knowledge, persona/shared = durable identity/common facts" })),
|
|
75
|
+
fingerprint: Type.Optional(Type.String({ minLength: 1, maxLength: 256, description: "optimize stage: exact fingerprint from the corresponding inspection" })),
|
|
76
|
+
operations: Type.Optional(Type.Array(Type.Object({
|
|
77
|
+
sourceIds: Type.Array(Type.String({ maxLength: MAX_MEMORY_ID_CHARS }), { minItems: 1, maxItems: 16 }),
|
|
78
|
+
kind: Type.Union(MEMORY_KINDS.map((kind) => Type.Literal(kind))),
|
|
79
|
+
text: Type.String({ minLength: 1, maxLength: MAX_MEMORY_TEXT_CHARS }),
|
|
80
|
+
tags: Type.Optional(Type.Array(Type.String({ maxLength: MAX_MEMORY_TAG_CHARS }), { maxItems: MAX_MEMORY_TAGS, description: "optimize stage: omitted tags inherit the normalized union from selected sources; an explicit empty array clears them" })),
|
|
81
|
+
source: Type.Optional(Type.String({ maxLength: MAX_MEMORY_SOURCE_CHARS })),
|
|
82
|
+
}, { additionalProperties: false }), { maxItems: 8, description: "optimize stage: explicit replacements; source IDs must be disjoint and total no more than 64" })),
|
|
83
|
+
planId: Type.Optional(Type.String({ minLength: 1, maxLength: 160, description: "optimize apply: exact unexpired staged plan id" })),
|
|
84
|
+
receiptId: Type.Optional(Type.String({ minLength: 1, maxLength: 160, description: "optimize undo: exact retained durable receipt id; also supply target" })),
|
|
85
|
+
}, { additionalProperties: false });
|
|
86
|
+
|
|
87
|
+
type MemoryToolParams = Type.Static<typeof MemoryParams>;
|
|
88
|
+
|
|
89
|
+
/** How many colliding facts an ambiguity refusal names before it summarizes the rest. */
|
|
90
|
+
const MAX_AMBIGUITY_CANDIDATES_SHOWN = 5;
|
|
91
|
+
|
|
92
|
+
interface ToolResult {
|
|
93
|
+
content: { type: "text"; text: string }[];
|
|
94
|
+
details: Record<string, unknown>;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function say(text: string, details: Record<string, unknown> = {}): ToolResult {
|
|
98
|
+
return { content: [{ type: "text", text }], details };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export type GetOptimizer = (ctx: ExtensionContext) => MemoryOptimizer;
|
|
102
|
+
export type GetMindActivity = (ctx: ExtensionContext) => MindActivityRunner | undefined;
|
|
103
|
+
|
|
104
|
+
export function registerMemoryTool(pi: ExtensionAPI, getMind: GetMind, sessionMemory?: SessionMemory, getOptimizer?: GetOptimizer, getActivity?: GetMindActivity): void {
|
|
105
|
+
pi.registerTool({
|
|
106
|
+
name: "memory",
|
|
107
|
+
label: "Memory",
|
|
108
|
+
promptSnippet: "memory — persist, recall, inspect, and explicitly consolidate durable facts, project context, and active-session notes",
|
|
109
|
+
promptGuidelines: [
|
|
110
|
+
"Before the final answer, use `memory` once when this turn established a durable user preference, architectural decision/invariant, or verified lesson that is not simply re-derivable from the repository. A user who explicitly labels a fact durable/permanent is asking for capture even without the word 'remember'. Use `backlog` for unfinished intent. Skip routine transcript, guesses, and secrets.",
|
|
111
|
+
"For consolidation, inspect first, read the full selected entries, compare them with the newest primary evidence, then stage explicit rewrites/merges that preserve exceptions and provenance. Review the exact before/after plan and character counts; apply the exact staged plan within the user's authorized memory-maintenance scope. Inspect is read-only and never calls a model or applies changes by itself.",
|
|
112
|
+
],
|
|
113
|
+
description: [
|
|
114
|
+
"Your durable, persona-scoped memory. `remember` a fact so it survives context compaction and",
|
|
115
|
+
"restarts — long-term for who this persona is to the user (preferences/conventions/lessons),",
|
|
116
|
+
"long with scope=project for durable repository knowledge, short for project notes that auto-delete after ~48h, or session for active-branch notes only. Scope=shared explicitly shares durable facts across personas. Promotion preserves project scope by default. `recall` searches; `read` gets full text; `forget` retires by id with optional scope. For `optimize`, inspect candidates, read full entries, compare against current evidence, stage explicit reviewed replacements preserving exceptions and provenance, then apply only an authorized exact plan. Inspect is read-only; it does not call a model or write.",
|
|
117
|
+
"Facts are re-injected into your context automatically each turn, so remember what you would",
|
|
118
|
+
"want to know next session. Keep entries DECLARATIVE, never store secrets.",
|
|
119
|
+
].join(" "),
|
|
120
|
+
parameters: MemoryParams,
|
|
121
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
122
|
+
try {
|
|
123
|
+
const invalid = validateMemoryParams(params);
|
|
124
|
+
if (invalid) return say(invalid, { ok: false, reason: "invalid_parameters" });
|
|
125
|
+
return await runMemoryAction(getMind(ctx), params, ctx, sessionMemory, getOptimizer, getActivity);
|
|
126
|
+
} catch (err) {
|
|
127
|
+
// One loud surface for every action. `remember`/`promote` already convert a store failure into
|
|
128
|
+
// a result, but `recall`/`forget` let it throw — so a store written by a different build
|
|
129
|
+
// (StoreVersionError) escapes as a tool crash for two actions and reads as a tidy reason for
|
|
130
|
+
// the other two. The model reads this boundary, so it reports the same way either way.
|
|
131
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
132
|
+
return say(`Memory is unavailable: ${message || "unknown persistence failure"}`, { ok: false, reason: "storage_error" });
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
renderResult(result, { expanded }, theme) {
|
|
136
|
+
const body = toolResultText(result);
|
|
137
|
+
const details = result.details && typeof result.details === "object" ? result.details as Record<string, unknown> : undefined;
|
|
138
|
+
// Recognize old receipts too, so reopening a session does not restore the noisy card.
|
|
139
|
+
const savedTerm = details?.ok === true ? /^Remembered \S+ — (long|short)-term /.exec(body)?.[1] : undefined;
|
|
140
|
+
const savedSession = details?.ok === true && details.action === "remember" && details.storage === "session";
|
|
141
|
+
if (savedTerm || savedSession) {
|
|
142
|
+
const summary = typeof details?.summary === "string"
|
|
143
|
+
? details.summary
|
|
144
|
+
: savedSession ? "Session note saved" : `${savedTerm === "long" ? "Long" : "Short"}-term saved`;
|
|
145
|
+
return renderExpandableResult(summary, true, theme);
|
|
146
|
+
}
|
|
147
|
+
return renderExpandableResult(body, expanded, theme);
|
|
148
|
+
},
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const KEYS: Record<string, ReadonlySet<string>> = {
|
|
153
|
+
remember: new Set(["action", "term", "kind", "text", "tags", "ttlHours", "supersedes", "scope", "source", "derivedFrom"]),
|
|
154
|
+
recall: new Set(["action", "query", "scope", "max"]),
|
|
155
|
+
read: new Set(["action", "id", "scope"]),
|
|
156
|
+
forget: new Set(["action", "id", "scope"]),
|
|
157
|
+
promote: new Set(["action", "id", "scope"]),
|
|
158
|
+
optimize: new Set(["action", "mode", "target", "query", "max", "offset", "fingerprint", "operations", "planId", "receiptId"]),
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
/** The host validates TypeBox schemas, but execute is also callable directly by SDK clients. */
|
|
162
|
+
function validateMemoryParams(value: unknown): string | undefined {
|
|
163
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return "memory expects one object of action parameters.";
|
|
164
|
+
const prototype = Object.getPrototypeOf(value);
|
|
165
|
+
if (prototype !== Object.prototype && prototype !== null) return "memory action parameters must be a plain object.";
|
|
166
|
+
const params = value as Record<string, unknown>;
|
|
167
|
+
if (typeof params.action !== "string" || !Object.hasOwn(KEYS, params.action)) return "Unknown memory action.";
|
|
168
|
+
if (Reflect.ownKeys(params).some((key) => typeof key !== "string" || !KEYS[params.action as string]!.has(key))) return `memory ${params.action} received a field that does not belong to that action.`;
|
|
169
|
+
const has = (key: string) => Object.hasOwn(params, key);
|
|
170
|
+
const str = (key: string, min: number, max: number) => typeof params[key] === "string" && (params[key] as string).length >= min && (params[key] as string).length <= max;
|
|
171
|
+
if (params.action === "remember") {
|
|
172
|
+
if (params.term !== "long" && params.term !== "short" && params.term !== "session") return "memory remember needs term=long|short|session.";
|
|
173
|
+
if (typeof params.kind !== "string" || !(MEMORY_KINDS as readonly string[]).includes(params.kind)) return "memory remember needs a valid kind.";
|
|
174
|
+
if (!str("text", 1, MAX_MEMORY_TEXT_CHARS)) return `memory remember text must contain 1..${MAX_MEMORY_TEXT_CHARS} characters.`;
|
|
175
|
+
if (params.term === "session" && ["tags", "ttlHours", "supersedes", "scope", "derivedFrom"].some(has)) return "session notes accept only kind, text, and optional source.";
|
|
176
|
+
if (params.scope !== undefined && !["project", "persona", "shared"].includes(String(params.scope))) return "remember scope must be project, persona, or shared.";
|
|
177
|
+
if (params.term === "short" && params.scope !== undefined && params.scope !== "project") return "short-term notes belong to project scope.";
|
|
178
|
+
if (params.tags !== undefined && (!Array.isArray(params.tags) || params.tags.length > MAX_MEMORY_TAGS || !Array.from(params.tags).every((tag) => typeof tag === "string" && tag.length <= MAX_MEMORY_TAG_CHARS))) return "memory tags exceed their bounds.";
|
|
179
|
+
if (params.derivedFrom !== undefined && (!Array.isArray(params.derivedFrom) || params.derivedFrom.length > MAX_MEMORY_DERIVED_IDS || !Array.from(params.derivedFrom).every((id) => isMemoryId(id)))) return "memory derivedFrom ids are invalid or exceed their bound.";
|
|
180
|
+
if (params.source !== undefined && (typeof params.source !== "string" || params.source.length > MAX_MEMORY_SOURCE_CHARS)) return "memory source exceeds its bound.";
|
|
181
|
+
if (params.supersedes !== undefined && !isMemoryId(params.supersedes)) return "memory supersedes must be a safe entry id.";
|
|
182
|
+
if (params.ttlHours !== undefined && (typeof params.ttlHours !== "number" || !Number.isFinite(params.ttlHours) || params.ttlHours <= 0)) return "memory ttlHours must be a positive finite number.";
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (params.action === "recall") {
|
|
186
|
+
if (params.query !== undefined && !str("query", 0, MAX_RECALL_QUERY_CHARS)) return `memory recall query exceeds ${MAX_RECALL_QUERY_CHARS} characters.`;
|
|
187
|
+
if (params.scope !== undefined && !["long", "short", "both", "session", "project", "persona", "shared"].includes(String(params.scope))) return "unknown recall scope.";
|
|
188
|
+
if (params.max !== undefined && (typeof params.max !== "number" || !Number.isFinite(params.max))) return "memory max must be a finite number.";
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (params.action === "read" || params.action === "forget" || params.action === "promote") {
|
|
192
|
+
if (!isMemoryId(params.id)) return `memory ${params.action} needs a safe exact id.`;
|
|
193
|
+
if (params.scope !== undefined && !(params.action === "promote" ? ["project", "persona", "shared"] : ["long", "short", "both", "session", "project", "persona", "shared"]).includes(String(params.scope))) return "invalid scope for memory action.";
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
const mode = params.mode ?? "inspect";
|
|
197
|
+
if (!["inspect", "stage", "apply", "history", "undo"].includes(String(mode))) return "memory optimize mode must be inspect, stage, apply, history, or undo.";
|
|
198
|
+
if (params.target !== undefined && !isOptimizeTarget(params.target)) return "memory optimize target must be project, project-long, persona, or shared.";
|
|
199
|
+
if (params.query !== undefined && !str("query", 0, MAX_RECALL_QUERY_CHARS)) return `memory optimize query exceeds ${MAX_RECALL_QUERY_CHARS} characters.`;
|
|
200
|
+
if (params.max !== undefined && (typeof params.max !== "number" || !Number.isSafeInteger(params.max) || params.max < 1 || params.max > 100)) return "memory optimize max must be an integer from 1 to 100.";
|
|
201
|
+
if (params.offset !== undefined && (typeof params.offset !== "number" || !Number.isSafeInteger(params.offset) || params.offset < 0 || params.offset > DEFAULT_STORE_MAX_ENTRIES)) return `memory optimize offset must be an integer from 0 to ${DEFAULT_STORE_MAX_ENTRIES}.`;
|
|
202
|
+
if (mode === "history") {
|
|
203
|
+
if (["query", "offset", "fingerprint", "operations", "planId", "receiptId"].some(has)) return "memory optimize history only accepts target and max.";
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
if (mode === "undo") {
|
|
207
|
+
if (["query", "max", "offset", "fingerprint", "operations", "planId"].some(has)) return "memory optimize undo only accepts receiptId and target.";
|
|
208
|
+
if (!str("receiptId", 1, 160) || params.target === undefined) return "memory optimize undo needs receiptId and an explicit target.";
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
if (mode === "inspect") {
|
|
212
|
+
if (["fingerprint", "operations", "planId", "receiptId"].some(has)) return "memory optimize inspect only accepts target, query, max, and offset.";
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
if (mode === "stage") {
|
|
216
|
+
if (["query", "max", "offset", "planId", "receiptId"].some(has)) return "memory optimize stage only accepts target, fingerprint, and operations.";
|
|
217
|
+
if (!str("fingerprint", 1, 256) || !Array.isArray(params.operations) || params.operations.length < 1 || params.operations.length > MAX_OPTIMIZE_OPERATIONS || !Array.from(params.operations).every(isOptimizeOperation)) return `memory optimize stage needs a fingerprint and 1..${MAX_OPTIMIZE_OPERATIONS} bounded operations.`;
|
|
218
|
+
const sourceCount = params.operations.reduce((sum: number, operation: { sourceIds: string[] }) => sum + operation.sourceIds.length, 0);
|
|
219
|
+
if (sourceCount > MAX_OPTIMIZE_TOTAL_SOURCES || params.operations.length > MAX_OPTIMIZE_OPERATIONS) return `memory optimize stage allows at most ${MAX_OPTIMIZE_OPERATIONS} operations and ${MAX_OPTIMIZE_TOTAL_SOURCES} total source IDs.`;
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
if (["target", "query", "max", "offset", "fingerprint", "operations", "receiptId"].some(has)) return "memory optimize apply only accepts planId.";
|
|
223
|
+
if (!str("planId", 1, 160)) return "memory optimize apply needs the id of a staged plan.";
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function runMemoryAction(mind: MindService, params: MemoryToolParams, ctx: ExtensionContext, sessionMemory?: SessionMemory, getOptimizer?: GetOptimizer, getActivity?: GetMindActivity): Promise<ToolResult> {
|
|
227
|
+
if (params.action === "remember") {
|
|
228
|
+
if (!params.term || !params.kind || !params.text) {
|
|
229
|
+
return say("memory remember needs { term: long|short|session, kind, text }.", { ok: false, reason: "missing required fields" });
|
|
230
|
+
}
|
|
231
|
+
if (params.term === "session") {
|
|
232
|
+
if (!sessionMemory) return say("Active-session memory is unavailable.", { ok: false, reason: "session_memory_unavailable" });
|
|
233
|
+
const result = sessionMemory.remember(ctx, { kind: params.kind, text: params.text, ...(params.source === undefined ? {} : { source: params.source }) });
|
|
234
|
+
return result.ok
|
|
235
|
+
? say(`Remembered session note ${result.entry.id}. It belongs to this active session only.`, { ok: true, action: "remember", storage: result.storage, id: result.entry.id, summary: `Session note saved — ${compactMemoryText(result.entry.text, 80)}` })
|
|
236
|
+
: say(`Not stored: ${result.reason}`, { ok: false, reason: result.reason });
|
|
237
|
+
}
|
|
238
|
+
const input: RememberInput = { term: params.term, kind: params.kind, text: params.text };
|
|
239
|
+
if (params.tags) input.tags = params.tags;
|
|
240
|
+
if (params.ttlHours !== undefined) input.ttlHours = params.ttlHours;
|
|
241
|
+
if (params.supersedes) input.supersedes = params.supersedes;
|
|
242
|
+
if (params.scope === "project" || params.scope === "persona" || params.scope === "shared") input.scope = params.scope;
|
|
243
|
+
if (params.source) input.source = params.source;
|
|
244
|
+
if (params.derivedFrom) input.derivedFrom = params.derivedFrom;
|
|
245
|
+
const r = await mind.remember(input);
|
|
246
|
+
return r.ok
|
|
247
|
+
? say(`Remembered ${r.entry.id} — ${r.entry.expiresAt ? "short" : "long"}-term ${params.kind}. It will re-appear in your context.`, {
|
|
248
|
+
id: r.entry.id,
|
|
249
|
+
ok: true,
|
|
250
|
+
scope: params.scope ?? (r.entry.expiresAt ? "project" : "persona"),
|
|
251
|
+
summary: `${params.scope ?? (r.entry.expiresAt ? "project" : "persona")} · ${r.entry.expiresAt ? "working" : "durable"} saved — ${compactMemoryText(r.entry.text, 80)}`,
|
|
252
|
+
})
|
|
253
|
+
: say(`Not stored: ${r.reason}`, { ok: false, reason: r.reason });
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
if (params.action === "recall") {
|
|
257
|
+
const query = params.query ?? "";
|
|
258
|
+
if (query.length > MAX_RECALL_QUERY_CHARS) {
|
|
259
|
+
return say(`memory recall query exceeds the ${MAX_RECALL_QUERY_CHARS}-character limit.`, {
|
|
260
|
+
ok: false,
|
|
261
|
+
reason: "query_too_long",
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
const max = clampRecallMax(params.max);
|
|
265
|
+
if (params.scope === "session") {
|
|
266
|
+
if (!sessionMemory) return say("Active-session memory is unavailable.", { ok: false, reason: "session_memory_unavailable" });
|
|
267
|
+
const result = sessionMemory.recall(ctx, { query, max });
|
|
268
|
+
if (!result.ok) return say(`Session memory unavailable: ${result.reason ?? "read failed"}`, { ok: false, reason: result.reason ?? "session_read_failed" });
|
|
269
|
+
if (result.hits.length === 0) return say(query ? "No active-session notes match the supplied query." : "There are no active-session notes.", { ok: true, storage: result.storage, count: 0, total: result.total, withheld: result.withheld, max: result.max, ids: [] });
|
|
270
|
+
const lines = result.hits.map((note) => `- [${note.id}] (${note.kind}) ${compactMemoryText(note.text, 120)}`);
|
|
271
|
+
return say(`${result.hits.length} session note(s)${result.withheld ? ` of ${result.total}` : ""}:\n${lines.join("\n")}${result.withheld ? `\n… +${result.withheld} more; narrow the query or raise max.` : ""}`, { ok: true, storage: result.storage, count: result.hits.length, total: result.total, withheld: result.withheld, max: result.max, ids: result.hits.map((note) => note.id) });
|
|
272
|
+
}
|
|
273
|
+
const nativeScope = params.scope ?? "both";
|
|
274
|
+
const { hits, total, withheldUnsafe } = await mind.recall(query, nativeScope, max);
|
|
275
|
+
if (hits.length === 0) return say(query ? "No memory matches the supplied query." : "Your memory is empty.", { count: 0, ok: true });
|
|
276
|
+
const withheld = total - hits.length;
|
|
277
|
+
const more = [
|
|
278
|
+
withheld > 0 ? `… +${withheld} more match(es) — narrow the query or raise max.` : "",
|
|
279
|
+
withheldUnsafe > 0 ? `⚠ ${withheldUnsafe} stored entr${withheldUnsafe === 1 ? "y was" : "ies were"} withheld as unsafe.` : "",
|
|
280
|
+
]
|
|
281
|
+
.filter(Boolean)
|
|
282
|
+
.join("\n");
|
|
283
|
+
const lines = hits.map((e) => `- [${e.id}] (${e.kind}) ${compactMemoryText(e.text, 80)}`);
|
|
284
|
+
return say(`${hits.length} recalled${withheld > 0 ? ` of ${total}` : ""}:\n${lines.join("\n")}${more ? `\n${more}` : ""}`, {
|
|
285
|
+
count: hits.length,
|
|
286
|
+
total,
|
|
287
|
+
max,
|
|
288
|
+
withheld,
|
|
289
|
+
withheldUnsafe,
|
|
290
|
+
ids: hits.map((e) => e.id),
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
if (params.action === "read") {
|
|
295
|
+
if (!params.id) return say("memory read needs { id } (see recall).", { ok: false, reason: "missing id" });
|
|
296
|
+
if (params.id.startsWith("session:")) {
|
|
297
|
+
if (params.scope !== undefined && params.scope !== "session") return say("A session note id can only be read with scope=session.", { ok: false, reason: "scope_mismatch" });
|
|
298
|
+
if (!sessionMemory) return say("Active-session memory is unavailable.", { ok: false, reason: "session_memory_unavailable" });
|
|
299
|
+
const result = sessionMemory.read(ctx, params.id);
|
|
300
|
+
if (!result.ok) return say(`Session note not found: ${result.reason}`, { ok: false, reason: result.reason });
|
|
301
|
+
return say(`${result.entry.id} (${result.entry.kind}) · active session\nrecorded: ${result.entry.recordedAt}\norigin session: ${result.entry.originSessionId} (provenance only; not auto-resolved or imported)${result.entry.source ? `\nsource: ${result.entry.source}` : ""}\n\n${result.entry.text}`, { ok: true, storage: result.storage, entry: result.entry });
|
|
302
|
+
}
|
|
303
|
+
if (params.scope === "session") return say("scope=session requires a session:<UUID> note id.", { ok: false, reason: "scope_mismatch" });
|
|
304
|
+
const nativeScope = params.scope ?? "both";
|
|
305
|
+
const result = await mind.readMemory(params.id, nativeScope);
|
|
306
|
+
if (!result.ok) return say(`Memory read refused: ${result.reason}`, { ok: false, reason: result.reason });
|
|
307
|
+
const lines = result.entries.map(({ entry, target }) => `${entry.id} (${target}/${entry.kind})\nrecorded: ${entry.recordedAt} · last seen: ${entry.lastSeenAt}${entry.expiresAt ? ` · expires: ${entry.expiresAt}` : ""}${entry.source ? `\nsource: ${entry.source}` : ""}${entry.derivedFrom?.length ? `\nderived from: ${entry.derivedFrom.join(", ")}` : ""}${entry.tags.length ? `\ntags: ${entry.tags.join(", ")}` : ""}\n\n${entry.text}`);
|
|
308
|
+
const suffix = result.withheld ? `\n\n${result.withheld} identical-scope copy/copies omitted.` : "";
|
|
309
|
+
return say(`${lines.join("\n\n---\n\n")}${suffix}`, { ok: true, total: result.total, withheld: result.withheld, entries: result.entries });
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
if (params.action === "optimize") {
|
|
313
|
+
if (!getOptimizer) return say("Memory optimization is unavailable.", { ok: false, reason: "optimizer_unavailable" });
|
|
314
|
+
const ownerCurrent = sessionMemory?.captureOwner(ctx);
|
|
315
|
+
if (ownerCurrent && !ownerCurrent()) return say("The active session owner is unavailable; no optimization ran.", { ok: false, reason: "owner_unavailable" });
|
|
316
|
+
const optimizer = getOptimizer(ctx);
|
|
317
|
+
const input = {
|
|
318
|
+
mode: params.mode ?? "inspect",
|
|
319
|
+
...(params.target === undefined ? {} : { target: params.target }),
|
|
320
|
+
...(params.query === undefined ? {} : { query: params.query }),
|
|
321
|
+
...(params.max === undefined ? {} : { max: params.max }),
|
|
322
|
+
...(params.offset === undefined ? {} : { offset: params.offset }),
|
|
323
|
+
...(params.fingerprint === undefined ? {} : { fingerprint: params.fingerprint }),
|
|
324
|
+
...(params.operations === undefined ? {} : { operations: params.operations }),
|
|
325
|
+
...(params.planId === undefined ? {} : { planId: params.planId }),
|
|
326
|
+
...(params.receiptId === undefined ? {} : { receiptId: params.receiptId }),
|
|
327
|
+
} as const;
|
|
328
|
+
const phase = input.mode === "history" ? "inspect" : input.mode === "undo" ? "apply" : input.mode;
|
|
329
|
+
let target = input.target ?? "project";
|
|
330
|
+
let hasTarget = true;
|
|
331
|
+
if (input.mode === "apply") {
|
|
332
|
+
const plan = input.planId ? optimizer.getPlan(input.planId) : undefined;
|
|
333
|
+
if (plan?.ok) target = plan.target;
|
|
334
|
+
else hasTarget = false;
|
|
335
|
+
}
|
|
336
|
+
const operation = () => runOptimizeAction(optimizer, input);
|
|
337
|
+
const result = hasTarget
|
|
338
|
+
? await runMindActivity(getActivity?.(ctx), phase, target, operation, (outcome) => outcome.details.ok === true)
|
|
339
|
+
: await operation();
|
|
340
|
+
let current = false;
|
|
341
|
+
try { current = (!ownerCurrent || ownerCurrent()) && (!sessionMemory || sessionMemory.isCurrent(ctx)) && getOptimizer(ctx) === optimizer; }
|
|
342
|
+
catch { current = false; }
|
|
343
|
+
if (!current) {
|
|
344
|
+
if (params.mode === "undo" && result.details.ok === true) return say("Memory undo completed before the active owner changed. Inspect the target memory before further edits.", { ok: true, outcome: "undone_before_owner_change", receiptId: result.details.receiptId });
|
|
345
|
+
if (params.mode === "undo") return say("The active owner changed while undo was running. Inspect the target memory before retrying; the mutation outcome may be unknown.", { ok: false, outcome: "unknown", reason: "owner_changed" });
|
|
346
|
+
if (params.mode === "apply" && result.details.ok === true) return say("The staged memory plan was applied before the active owner changed. Inspect the target memory before any further edits.", { ok: true, outcome: "applied_before_owner_change", planId: result.details.planId });
|
|
347
|
+
if (params.mode === "apply") return say("The active owner changed while apply was running. Inspect the target memory before retrying; the mutation outcome may be unknown.", { ok: false, outcome: "unknown", reason: "owner_changed" });
|
|
348
|
+
return say("The active memory owner changed while this read-only or staging operation was running; no stale result or plan was returned.", { ok: false, reason: "owner_changed" });
|
|
349
|
+
}
|
|
350
|
+
return result;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
if (params.action === "promote") {
|
|
354
|
+
if (!params.id) return say("memory promote needs { id } (a short-term memory to make durable).", { ok: false, reason: "missing id" });
|
|
355
|
+
const target = params.scope === "persona" || params.scope === "shared" ? params.scope : "project";
|
|
356
|
+
const r = await mind.promote(params.id, target);
|
|
357
|
+
if (!r.ok) return say(r.reason ? `Not promoted: ${r.reason}` : `No live short-term memory with id "${params.id}".`, { ok: false, ...(r.reason ? { reason: r.reason } : {}) });
|
|
358
|
+
// The graduation stands, but the lineage handle it carried over may be one of the shared v1 ids the
|
|
359
|
+
// store refuses to act on — say so, or a bare "Promoted" reads as "and the old fact is retired".
|
|
360
|
+
const skipped = r.ambiguousSupersedes
|
|
361
|
+
? ` Its supersedes id ${r.ambiguousSupersedes} is shared by several stored memories, so nothing was retired — recall them and retire the one you meant by its own id.`
|
|
362
|
+
: "";
|
|
363
|
+
return say(`Promoted ${params.id} to durable ${target} memory — it will no longer decay.${skipped}`, {
|
|
364
|
+
ok: true,
|
|
365
|
+
id: params.id,
|
|
366
|
+
...(r.ambiguousSupersedes ? { ambiguousSupersedes: r.ambiguousSupersedes } : {}),
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// forget
|
|
371
|
+
if (!params.id) return say("memory forget needs { id } (see recall).", { ok: false, reason: "missing id" });
|
|
372
|
+
if (params.id.startsWith("session:")) {
|
|
373
|
+
if (!sessionMemory) return say("Active-session memory is unavailable.", { ok: false, reason: "session_memory_unavailable" });
|
|
374
|
+
const result = sessionMemory.forget(ctx, params.id);
|
|
375
|
+
return result.ok
|
|
376
|
+
? say(`Forgot active-session note ${params.id}. The transcript history remains; the note is tombstoned on this branch.`, { ok: true, storage: result.storage, removed: result.removed })
|
|
377
|
+
: say(`Session note not forgotten: ${result.reason}`, { ok: false, reason: result.reason });
|
|
378
|
+
}
|
|
379
|
+
if (params.scope === "session") return say("scope=session requires a session note id.", { ok: false });
|
|
380
|
+
const { removed, reason, candidates } = await mind.forget(params.id, params.scope ?? "both");
|
|
381
|
+
if (removed > 0) return say(`Forgot ${params.id}.`, { ok: true, removed });
|
|
382
|
+
if (reason !== "ambiguous_id") return say(`No memory with id "${params.id}".`, { ok: false, removed: 0, reason: "not_found" });
|
|
383
|
+
// A refusal the caller cannot act on leaves a store nobody can ever repair, so name each colliding
|
|
384
|
+
// fact by an id of its own. The one still holding the shared handle becomes addressable once the
|
|
385
|
+
// others are gone — the collision shrinks by one with every delete.
|
|
386
|
+
const shown = (candidates ?? []).slice(0, MAX_AMBIGUITY_CANDIDATES_SHOWN);
|
|
387
|
+
const rest = (candidates?.length ?? 0) - shown.length;
|
|
388
|
+
const lines = shown.map((c) => `- [${c.id}] (${c.kind}) ${compactMemoryText(c.text, 120)}${c.resolves ? "" : " — still the shared handle; forget the others first"}`);
|
|
389
|
+
return say(
|
|
390
|
+
[
|
|
391
|
+
`Memory id "${params.id}" is a legacy handle shared by ${candidates?.length ?? 0} distinct memories, so nothing was deleted.`,
|
|
392
|
+
"Forget the one you meant by its own current id:",
|
|
393
|
+
...lines,
|
|
394
|
+
rest > 0 ? `… +${rest} more share that handle.` : "",
|
|
395
|
+
]
|
|
396
|
+
.filter(Boolean)
|
|
397
|
+
.join("\n"),
|
|
398
|
+
{ ok: false, removed: 0, reason, candidates: shown.map((c) => ({ id: c.id, kind: c.kind, resolves: c.resolves })) },
|
|
399
|
+
);
|
|
400
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { renderExpandableCard } from "./presentation.ts";
|
|
3
|
+
|
|
4
|
+
export const MIND_RESULT_ENTRY_TYPE = "pi-persona-mind-result";
|
|
5
|
+
const MAX_TITLE_CHARS = 160;
|
|
6
|
+
const MAX_BODY_CHARS = 1_000_000;
|
|
7
|
+
|
|
8
|
+
/** Register once per factory; command output stays display-only and can be expanded without loss. */
|
|
9
|
+
export function registerMindResultRenderer(pi: ExtensionAPI): void {
|
|
10
|
+
pi.registerEntryRenderer<{ title: string; content: string }>(MIND_RESULT_ENTRY_TYPE, (entry, { expanded }, theme) => {
|
|
11
|
+
const data = entry.data;
|
|
12
|
+
if (!data || typeof data.title !== "string" || data.title.length < 1 || data.title.length > MAX_TITLE_CHARS || typeof data.content !== "string" || data.content.length > MAX_BODY_CHARS) return undefined;
|
|
13
|
+
return renderExpandableCard(data.title, data.content, expanded, theme);
|
|
14
|
+
});
|
|
15
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Human-facing transcript chrome. These helpers never change the model-visible tool payload;
|
|
3
|
+
* they only bound what a collapsed Pi card paints.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { keyHint } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { sliceByColumn, stripTerminalSequences, Text, visibleWidth } from "@earendil-works/pi-tui";
|
|
8
|
+
|
|
9
|
+
export const MAX_COLLAPSED_CARD_LINES = 3;
|
|
10
|
+
export const MAX_COLLAPSED_CARD_CHARS = 100;
|
|
11
|
+
const C0_AND_DEL = /[\u0000-\u0008\u000B-\u001F\u007F]/g;
|
|
12
|
+
|
|
13
|
+
export interface CompactVisibleTextOptions {
|
|
14
|
+
maxLines?: number;
|
|
15
|
+
/** Bound is terminal display columns, matching pi-persona's card chrome. */
|
|
16
|
+
maxLineChars?: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface CompactVisibleTextResult {
|
|
20
|
+
text: string;
|
|
21
|
+
truncated: boolean;
|
|
22
|
+
omittedLines: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface CardTheme {
|
|
26
|
+
fg: (name: "accent" | "toolOutput" | "dim", text: string) => string;
|
|
27
|
+
bold: (text: string) => string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function sanitizeCardText(text: string): string {
|
|
31
|
+
return stripTerminalSequences(text.replace(/\r\n?/g, "\n")).replace(C0_AND_DEL, "");
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Bound a collapsed card: a few semantic lines, each clipped by column, then a drill-down marker. */
|
|
35
|
+
export function compactVisibleText(input: string, opts: CompactVisibleTextOptions = {}): CompactVisibleTextResult {
|
|
36
|
+
const maxLines = Math.max(1, Math.floor(opts.maxLines ?? MAX_COLLAPSED_CARD_LINES));
|
|
37
|
+
const maxLineColumns = Math.max(16, Math.floor(opts.maxLineChars ?? MAX_COLLAPSED_CARD_CHARS));
|
|
38
|
+
const source = sanitizeCardText(input)
|
|
39
|
+
.split("\n")
|
|
40
|
+
.map((line) => line.trim())
|
|
41
|
+
.filter((line) => line.length > 0);
|
|
42
|
+
|
|
43
|
+
let lineTruncated = false;
|
|
44
|
+
const clamp = (line: string): string => {
|
|
45
|
+
if (visibleWidth(line) <= maxLineColumns) return line;
|
|
46
|
+
lineTruncated = true;
|
|
47
|
+
return `${sliceByColumn(line, 0, maxLineColumns - visibleWidth("…"), true)}…`;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
if (source.length > maxLines) {
|
|
51
|
+
const contentLines = Math.max(0, maxLines - 1);
|
|
52
|
+
const omittedLines = source.length - contentLines;
|
|
53
|
+
const visible = source.slice(0, contentLines).map(clamp);
|
|
54
|
+
visible.push(clamp(`… +${omittedLines} more line${omittedLines === 1 ? "" : "s"}`));
|
|
55
|
+
return { text: visible.join("\n") || "(no output)", truncated: true, omittedLines };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const visible = source.map(clamp);
|
|
59
|
+
return {
|
|
60
|
+
text: visible.join("\n") || "(no output)",
|
|
61
|
+
truncated: lineTruncated,
|
|
62
|
+
omittedLines: 0,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Pi's configured expand binding; fall back to the default so a missing keymap still names a key. */
|
|
67
|
+
export function expandDetailHint(): string {
|
|
68
|
+
try {
|
|
69
|
+
return keyHint("app.tools.expand", "to expand");
|
|
70
|
+
} catch {
|
|
71
|
+
return "ctrl+o to expand";
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function formatExpandableBody(body: string, expanded: boolean, theme: CardTheme): string {
|
|
76
|
+
const full = sanitizeCardText(body).trim() || "(no output)";
|
|
77
|
+
if (expanded) return theme.fg("toolOutput", full);
|
|
78
|
+
const preview = compactVisibleText(full);
|
|
79
|
+
const hint = preview.truncated ? `\n${theme.fg("dim", expandDetailHint())}` : "";
|
|
80
|
+
return `${theme.fg("toolOutput", preview.text)}${hint}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Result body only: Pi renders the call title. Expansion is lossless against sanitized `body`. */
|
|
84
|
+
export function renderExpandableResult(body: string, expanded: boolean, theme: CardTheme): Text {
|
|
85
|
+
return new Text(formatExpandableBody(body, expanded, theme), 0, 0);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Standalone entries such as backlog wakes have no Pi tool title and still need their own. */
|
|
89
|
+
export function renderExpandableCard(label: string, body: string, expanded: boolean, theme: CardTheme): Text {
|
|
90
|
+
const title = theme.fg("accent", theme.bold(label));
|
|
91
|
+
return new Text(`${title}\n${formatExpandableBody(body, expanded, theme)}`, 0, 0);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function toolResultText(result: { content?: ReadonlyArray<{ type: string; text?: string }> }): string {
|
|
95
|
+
const first = result.content?.find((part) => part.type === "text");
|
|
96
|
+
return first?.text ?? "";
|
|
97
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
import { MAX_SESSION_NOTE_CHARS, SESSION_MEMORY_KINDS, SESSION_NOTE_ENTRY_TYPE, MAX_SESSION_SOURCE_CHARS } from "../core/session-memory.ts";
|
|
4
|
+
import { renderExpandableCard } from "./presentation.ts";
|
|
5
|
+
|
|
6
|
+
interface SessionNoteCardModel {
|
|
7
|
+
title: string;
|
|
8
|
+
body: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function record(value: unknown): Record<string, unknown> | undefined {
|
|
12
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function sessionNoteCardModel(value: unknown): SessionNoteCardModel | undefined {
|
|
16
|
+
const event = record(value);
|
|
17
|
+
if (event?.version !== 1) return undefined;
|
|
18
|
+
if (event.op === "forget" && typeof event.id === "string" && event.id.startsWith("session:")) {
|
|
19
|
+
return { title: "Session note retired", body: `${event.id}\nNo longer active on this branch.` };
|
|
20
|
+
}
|
|
21
|
+
if (event.op !== "save") return undefined;
|
|
22
|
+
const note = record(event.note);
|
|
23
|
+
if (!note || typeof note.id !== "string" || !note.id.startsWith("session:") ||
|
|
24
|
+
typeof note.kind !== "string" || !(SESSION_MEMORY_KINDS as readonly string[]).includes(note.kind) ||
|
|
25
|
+
typeof note.text !== "string" || note.text.length === 0 || note.text.length > MAX_SESSION_NOTE_CHARS ||
|
|
26
|
+
typeof note.recordedAt !== "string" || !Number.isFinite(Date.parse(note.recordedAt)) ||
|
|
27
|
+
typeof note.originSessionId !== "string" || note.originSessionId.length === 0 || note.originSessionId.length > 256 || /[\s\u0000-\u001f\u007f]/u.test(note.originSessionId) ||
|
|
28
|
+
(note.source !== undefined && (typeof note.source !== "string" || note.source.length > MAX_SESSION_SOURCE_CHARS))) {
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
title: `Session note · ${note.kind}`,
|
|
33
|
+
body: [
|
|
34
|
+
`id: ${note.id}`,
|
|
35
|
+
`recorded: ${note.recordedAt}`,
|
|
36
|
+
`origin session: ${note.originSessionId} (provenance only; not auto-resolved)`,
|
|
37
|
+
note.source === undefined ? "" : `source: ${note.source}`,
|
|
38
|
+
"",
|
|
39
|
+
note.text,
|
|
40
|
+
].filter((line) => line !== "").join("\n"),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Register a semantic standalone card for session-note save and forget events. */
|
|
45
|
+
export function registerSessionNoteRenderer(pi: Pick<ExtensionAPI, "registerEntryRenderer">): void {
|
|
46
|
+
pi.registerEntryRenderer<unknown>(SESSION_NOTE_ENTRY_TYPE, (entry, { expanded }, theme) => {
|
|
47
|
+
const model = sessionNoteCardModel(entry.data);
|
|
48
|
+
return model ? renderExpandableCard(model.title, model.body, expanded, theme) : undefined;
|
|
49
|
+
});
|
|
50
|
+
}
|