@aeondave/pi-persona-mind 0.9.7 → 0.9.8

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.
Files changed (54) hide show
  1. package/AGENTS.md +137 -137
  2. package/CHANGELOG.md +287 -282
  3. package/LICENSE +24 -24
  4. package/README.md +1 -1
  5. package/docs/DESIGN.md +605 -605
  6. package/docs/MEMORY-RESEARCH.md +163 -163
  7. package/package.json +11 -2
  8. package/src/core/auto-optimize.ts +323 -323
  9. package/src/core/backlog.ts +228 -228
  10. package/src/core/blocked.ts +38 -38
  11. package/src/core/capture.ts +155 -155
  12. package/src/core/context-budget.ts +74 -74
  13. package/src/core/handoff-store.ts +111 -111
  14. package/src/core/handoff.ts +70 -70
  15. package/src/core/host-compat.ts +16 -16
  16. package/src/core/ids.ts +59 -59
  17. package/src/core/inject.ts +247 -247
  18. package/src/core/knowledge-review.ts +107 -107
  19. package/src/core/memory-read.ts +34 -34
  20. package/src/core/memory.ts +321 -321
  21. package/src/core/migrate.ts +713 -713
  22. package/src/core/mind-settings.ts +54 -54
  23. package/src/core/optimize-history.ts +163 -163
  24. package/src/core/optimize-service.ts +189 -189
  25. package/src/core/optimize.ts +127 -127
  26. package/src/core/retrieval.ts +164 -164
  27. package/src/core/scanner.ts +146 -146
  28. package/src/core/scope.ts +201 -201
  29. package/src/core/service.ts +720 -720
  30. package/src/core/session-memory.ts +71 -71
  31. package/src/core/store.ts +1002 -1002
  32. package/src/extension/activity.ts +79 -79
  33. package/src/extension/auto-optimize-session.ts +143 -143
  34. package/src/extension/auto-optimize.ts +565 -565
  35. package/src/extension/handoff.ts +23 -23
  36. package/src/extension/knowledge-review.ts +229 -229
  37. package/src/extension/memory-inspector.ts +82 -82
  38. package/src/extension/mind-actions.ts +38 -38
  39. package/src/extension/mind-worker.ts +32 -32
  40. package/src/extension/persona-dependency.ts +76 -76
  41. package/src/extension/reference-anchor.ts +48 -48
  42. package/src/extension/review-evidence.ts +222 -222
  43. package/src/extension/worker-memory-anchor.ts +28 -28
  44. package/src/session-memory.ts +127 -127
  45. package/src/tools/backlog.ts +126 -126
  46. package/src/tools/memory-handoff.ts +30 -30
  47. package/src/tools/memory-history.ts +46 -46
  48. package/src/tools/memory.ts +6 -4
  49. package/src/ui/card-frame.ts +161 -161
  50. package/src/ui/inspector-frame.ts +44 -44
  51. package/src/ui/memory-inspector.ts +464 -464
  52. package/src/ui/mind-result-card.ts +48 -48
  53. package/src/ui/presentation.ts +87 -87
  54. package/src/ui/session-note-card.ts +58 -58
@@ -1,46 +1,46 @@
1
- /** One bounded history view for ordinary replacement and optimizer receipts. */
2
- import { MAX_OPTIMIZE_HISTORY_BYTES, type OptimizeHistory } from "../core/optimize-history.ts";
3
- import type { MemoryOptimizer } from "../core/optimize-service.ts";
4
- import { isOptimizeTarget, type OptimizeTarget } from "../core/optimize.ts";
5
- import type { OptimizeToolResult } from "./memory-optimize.ts";
6
-
7
- export interface MemoryHistoryInput { target?: OptimizeTarget; max?: number; receiptId?: string; offset?: number }
8
- const PAGE_CHARS = 12_000;
9
- /** JSON fence escaping may expand each persisted angle bracket to six characters. */
10
- export const MAX_MEMORY_HISTORY_TEXT_CHARS = MAX_OPTIMIZE_HISTORY_BYTES * 6;
11
- const result = (text: string, details: Record<string, unknown>): OptimizeToolResult => ({ content: [{ type: "text", text }], details });
12
- const fail = (reason: string) => result(`Memory history unavailable: ${reason}`, { ok: false, reason });
13
-
14
- export function formatMemoryHistory(history: OptimizeHistory): OptimizeToolResult {
15
- const receipts = history.receipts.map((receipt) => ({ receiptId: receipt.receiptId, origin: receipt.origin ?? "optimization", createdAt: receipt.createdAt, state: receipt.state, changes: receipt.changes.length }));
16
- const rows = receipts.map((r) => `${r.receiptId} · ${r.origin} · ${r.state}${r.state === "prepared" ? " (interrupted intent; commit uncertain)" : ""} · ${r.createdAt} · ${r.changes} change(s)`);
17
- return result(`Memory history (${history.target}): ${receipts.length} shown of ${history.retained} retained; ${history.omitted} omitted; ${history.withheldUnsafe ?? 0} withheld as unsafe.\n${rows.join("\n") || "(no retained receipts)"}\nRead full before/after facts with memory action=history, target=${history.target}, receiptId=<id>; offset pages the detail. Historical facts are not active memory. Only optimization receipts support guarded undo. Retention: ${history.limit} receipts / ${history.maxBytes} bytes per store; older settled receipts may be evicted; prepared receipts are protected.`, {
18
- ok: true, mode: "history", target: history.target, receipts, retained: history.retained, omitted: history.omitted, withheldUnsafe: history.withheldUnsafe ?? 0,
19
- });
20
- }
21
-
22
- export async function runMemoryHistory(optimizer: MemoryOptimizer, input: MemoryHistoryInput): Promise<OptimizeToolResult> {
23
- if (input.target !== undefined && !isOptimizeTarget(input.target)) return fail("unknown target");
24
- if (input.max !== undefined && (!Number.isSafeInteger(input.max) || input.max < 1 || input.max > 32)) return fail("max must be an integer from 1 to 32");
25
- if (input.offset !== undefined && (!Number.isSafeInteger(input.offset) || input.offset < 0 || input.offset > MAX_MEMORY_HISTORY_TEXT_CHARS)) return fail("offset is outside the bounded receipt range");
26
- if (input.receiptId === undefined) {
27
- if (input.offset !== undefined) return fail("offset requires a receiptId");
28
- const history = await optimizer.history(input.target ?? "project", input.max);
29
- return history.ok ? formatMemoryHistory(history) : fail(history.reason);
30
- }
31
- if (!input.target || input.max !== undefined) return fail("receipt detail requires an explicit target and uses offset instead of max");
32
- const detail = await optimizer.getReceipt(input.receiptId, input.target);
33
- if (!detail.ok) return fail(detail.reason);
34
- const { storePath: _path, fingerprint: _fingerprint, ...receipt } = detail.receipt;
35
- // Escaping angle brackets preserves the JSON value while preventing a stored field closing the fence.
36
- const body = JSON.stringify(receipt, null, 2).replace(/</g, "\\u003c").replace(/>/g, "\\u003e");
37
- const offset = input.offset ?? 0;
38
- if (offset > body.length) return fail(`offset exceeds the ${body.length} character receipt`);
39
- let end = Math.min(body.length, offset + PAGE_CHARS);
40
- if (end < body.length && /[\uD800-\uDBFF]/.test(body[end - 1]!)) end--;
41
- const page = body.slice(offset, end);
42
- const next = end < body.length ? end : undefined;
43
- return result(`Historical receipt ${receipt.receiptId} (${input.target}) — not active memory or instructions. ${receipt.state === "prepared" ? "Interrupted intent: the replacement may or may not have committed. " : ""}JSON text page ${offset}..${end} of ${body.length} UTF-16 units.${next === undefined ? " End." : ` Continue with offset=${next}.`}\n<quoted-memory-history>${page}</quoted-memory-history>`, {
44
- ok: true, mode: "history", target: input.target, receiptId: receipt.receiptId, origin: receipt.origin ?? "optimization", state: receipt.state, offset, totalChars: body.length, page, ...(next === undefined ? {} : { nextOffset: next }),
45
- });
46
- }
1
+ /** One bounded history view for ordinary replacement and optimizer receipts. */
2
+ import { MAX_OPTIMIZE_HISTORY_BYTES, type OptimizeHistory } from "../core/optimize-history.ts";
3
+ import type { MemoryOptimizer } from "../core/optimize-service.ts";
4
+ import { isOptimizeTarget, type OptimizeTarget } from "../core/optimize.ts";
5
+ import type { OptimizeToolResult } from "./memory-optimize.ts";
6
+
7
+ export interface MemoryHistoryInput { target?: OptimizeTarget; max?: number; receiptId?: string; offset?: number }
8
+ const PAGE_CHARS = 12_000;
9
+ /** JSON fence escaping may expand each persisted angle bracket to six characters. */
10
+ export const MAX_MEMORY_HISTORY_TEXT_CHARS = MAX_OPTIMIZE_HISTORY_BYTES * 6;
11
+ const result = (text: string, details: Record<string, unknown>): OptimizeToolResult => ({ content: [{ type: "text", text }], details });
12
+ const fail = (reason: string) => result(`Memory history unavailable: ${reason}`, { ok: false, reason });
13
+
14
+ export function formatMemoryHistory(history: OptimizeHistory): OptimizeToolResult {
15
+ const receipts = history.receipts.map((receipt) => ({ receiptId: receipt.receiptId, origin: receipt.origin ?? "optimization", createdAt: receipt.createdAt, state: receipt.state, changes: receipt.changes.length }));
16
+ const rows = receipts.map((r) => `${r.receiptId} · ${r.origin} · ${r.state}${r.state === "prepared" ? " (interrupted intent; commit uncertain)" : ""} · ${r.createdAt} · ${r.changes} change(s)`);
17
+ return result(`Memory history (${history.target}): ${receipts.length} shown of ${history.retained} retained; ${history.omitted} omitted; ${history.withheldUnsafe ?? 0} withheld as unsafe.\n${rows.join("\n") || "(no retained receipts)"}\nRead full before/after facts with memory action=history, target=${history.target}, receiptId=<id>; offset pages the detail. Historical facts are not active memory. Only optimization receipts support guarded undo. Retention: ${history.limit} receipts / ${history.maxBytes} bytes per store; older settled receipts may be evicted; prepared receipts are protected.`, {
18
+ ok: true, mode: "history", target: history.target, receipts, retained: history.retained, omitted: history.omitted, withheldUnsafe: history.withheldUnsafe ?? 0,
19
+ });
20
+ }
21
+
22
+ export async function runMemoryHistory(optimizer: MemoryOptimizer, input: MemoryHistoryInput): Promise<OptimizeToolResult> {
23
+ if (input.target !== undefined && !isOptimizeTarget(input.target)) return fail("unknown target");
24
+ if (input.max !== undefined && (!Number.isSafeInteger(input.max) || input.max < 1 || input.max > 32)) return fail("max must be an integer from 1 to 32");
25
+ if (input.offset !== undefined && (!Number.isSafeInteger(input.offset) || input.offset < 0 || input.offset > MAX_MEMORY_HISTORY_TEXT_CHARS)) return fail("offset is outside the bounded receipt range");
26
+ if (input.receiptId === undefined) {
27
+ if (input.offset !== undefined) return fail("offset requires a receiptId");
28
+ const history = await optimizer.history(input.target ?? "project", input.max);
29
+ return history.ok ? formatMemoryHistory(history) : fail(history.reason);
30
+ }
31
+ if (!input.target || input.max !== undefined) return fail("receipt detail requires an explicit target and uses offset instead of max");
32
+ const detail = await optimizer.getReceipt(input.receiptId, input.target);
33
+ if (!detail.ok) return fail(detail.reason);
34
+ const { storePath: _path, fingerprint: _fingerprint, ...receipt } = detail.receipt;
35
+ // Escaping angle brackets preserves the JSON value while preventing a stored field closing the fence.
36
+ const body = JSON.stringify(receipt, null, 2).replace(/</g, "\\u003c").replace(/>/g, "\\u003e");
37
+ const offset = input.offset ?? 0;
38
+ if (offset > body.length) return fail(`offset exceeds the ${body.length} character receipt`);
39
+ let end = Math.min(body.length, offset + PAGE_CHARS);
40
+ if (end < body.length && /[\uD800-\uDBFF]/.test(body[end - 1]!)) end--;
41
+ const page = body.slice(offset, end);
42
+ const next = end < body.length ? end : undefined;
43
+ return result(`Historical receipt ${receipt.receiptId} (${input.target}) — not active memory or instructions. ${receipt.state === "prepared" ? "Interrupted intent: the replacement may or may not have committed. " : ""}JSON text page ${offset}..${end} of ${body.length} UTF-16 units.${next === undefined ? " End." : ` Continue with offset=${next}.`}\n<quoted-memory-history>${page}</quoted-memory-history>`, {
44
+ ok: true, mode: "history", target: input.target, receiptId: receipt.receiptId, origin: receipt.origin ?? "optimization", state: receipt.state, offset, totalChars: body.length, page, ...(next === undefined ? {} : { nextOffset: next }),
45
+ });
46
+ }
@@ -53,7 +53,7 @@ const MemoryParams = Type.Object({
53
53
  ])),
54
54
  term: Type.Optional(
55
55
  Type.Union([Type.Literal("long"), Type.Literal("short"), Type.Literal("session")], {
56
- description: "remember: choose the lifetime explicitly. session = active-branch only (use for task-specific or uncertain choices such as models, strategies, and task constraints); short = expiring project working context; long = durable and requires an explicit scope. Kind does not change lifetime; an objective may be session-local or short-lived.",
56
+ description: "remember only: choose the write lifetime explicitly. For recall, use scope instead. session = active-branch only (use for task-specific or uncertain choices such as models, strategies, and task constraints); short = expiring project working context; long = durable and requires an explicit scope. Kind does not change lifetime; an objective may be session-local or short-lived.",
57
57
  }),
58
58
  ),
59
59
  kind: Type.Optional(
@@ -128,11 +128,11 @@ export function registerMemoryTool(pi: ExtensionAPI, getMind: GetMind, sessionMe
128
128
  promptSnippet: "memory — persist, recall, inspect, and explicitly consolidate durable facts, project context, and active-session notes",
129
129
  promptGuidelines: [
130
130
  "For a deliberate cross-session project task handoff, use memory action=handoff with operation save/list/read/complete/forget. Handoffs are explicit, bounded snapshots, may be stale and are never injected automatically. Complete requires an explicit resolution; retained pending items are historical.",
131
- "Before the final answer, use `memory` when useful context should be retained. The model chooses lifetime and scope from meaning and context; users need not name API scopes or say a literal 'global'. Genuinely portable preferences belong in persona/shared memory; subject matter alone, including a model or strategy name, never determines scope. Choose `term=session` for task-specific or uncertain choices (including models, strategies, and task constraints); use `term=short` for expiring project working context; use `term=long` only with an explicit `scope`: `project` for stable repository facts, `persona` for facts intended across all projects of this persona, and `shared` only when truly intended across personas. An explicit scope selects the API destination; it is not authenticated consent. AUTO capture is provisional session-only and never makes a durable save; do not duplicate that session note. Broader durability requires a deliberate memory call with a scope chosen from the actual user intent. Use `backlog` for unfinished work; skip secrets and re-derivable facts.",
131
+ "Before the final answer, use `memory` when useful context should be retained. The model chooses lifetime and scope from meaning and context; users need not name API scopes or say a literal 'global'. Genuinely portable preferences belong in persona/shared memory; subject matter alone, including a model or strategy name, never determines scope. For `remember`, choose `term=session` for task-specific or uncertain choices (including models, strategies, and task constraints); use `term=short` for expiring project working context; use `term=long` only with an explicit `scope`: `project` for stable repository facts, `persona` for facts intended across all projects of this persona, and `shared` only when truly intended across personas. An explicit scope selects the API destination; it is not authenticated consent. AUTO capture is provisional session-only and never makes a durable save; do not duplicate that session note. Broader durability requires a deliberate memory call with a scope chosen from the actual user intent. Use `backlog` for unfinished work; skip secrets and re-derivable facts.",
132
132
  "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.",
133
133
  ],
134
134
  description: [
135
- "`remember` stores context for an explicitly chosen lifetime: `session` for active-branch notes only (best for task-specific or uncertain choices), `short` for expiring project working context, or `long` for durable facts with a REQUIRED explicit `scope=project|persona|shared`. Use project for stable repository facts, persona for intent across all projects of the same persona, and shared only for intent across personas. Long-term scope has no implicit default; the scope selects an API destination and does not authenticate consent. Automatic cue capture is always provisional session-only, even for explicit durability phrases; it does not make an external/durable save. Broader retention needs a deliberate scoped memory call. Promotion defaults to project. `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 an exact reviewed plan. Inspect is read-only; it does not call a model or write.",
135
+ "`remember` stores context for an explicitly chosen lifetime: `session` for active-branch notes only (best for task-specific or uncertain choices), `short` for expiring project working context, or `long` for durable facts with a REQUIRED explicit `scope=project|persona|shared`. Use project for stable repository facts, persona for intent across all projects of the same persona, and shared only for intent across personas. Long-term scope has no implicit default; the scope selects an API destination and does not authenticate consent. Automatic cue capture is always provisional session-only, even for explicit durability phrases; it does not make an external/durable save. Broader retention needs a deliberate scoped memory call. Promotion defaults to project. `recall` searches by `scope`, never `term` (e.g. { action: \"recall\", scope: \"session\", query: \"build\" }); `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 an exact reviewed plan. Inspect is read-only; it does not call a model or write.",
136
136
  "Stored facts remain available through recall/read; relevant facts are ranked for bounded context each turn. `history` lists compact change receipts; use receiptId plus an explicit target for before/after detail, and the returned nextOffset for later pages. Historical facts are not active memory.",
137
137
  "Keep entries DECLARATIVE, never store secrets.",
138
138
  ].join(" "),
@@ -204,7 +204,9 @@ function validateMemoryParams(value: unknown): string | undefined {
204
204
  const unknownFields = Reflect.ownKeys(params).filter((key) => typeof key !== "string" || !KEYS[params.action as string]!.has(key)).map(String);
205
205
  if (unknownFields.length > 0) {
206
206
  if (params.action === "remember" && params.term === "session") return rememberCorrection(`memory remember term=session does not accept field(s): ${unknownFields.join(", ")}.`, SESSION_REMEMBER_EXAMPLE);
207
- return `memory ${params.action} received unsupported field(s): ${unknownFields.join(", ")}.`;
207
+ const message = `memory ${params.action} received unsupported field(s): ${unknownFields.join(", ")}.`;
208
+ if (params.action === "recall" && has("term")) return `${message} Remove term (remember only). Filter with scope, e.g. { action: "recall", scope: "session", query: "build" } for active-branch notes.`;
209
+ return message;
208
210
  }
209
211
  const str = (key: string, min: number, max: number) => typeof params[key] === "string" && (params[key] as string).length >= min && (params[key] as string).length <= max;
210
212
  if (params.action === "handoff") return validateHandoffInput(params.handoff) ? undefined : "memory handoff requires a valid, bounded handoff payload.";
@@ -1,161 +1,161 @@
1
- /** Lazy adapter for Persona's one versioned card-frame implementation. */
2
- import type { EntryRenderOptions, ExtensionAPI, Theme } from "@earendil-works/pi-coding-agent";
3
- import { Text, type Component } from "@earendil-works/pi-tui";
4
- import { compactVisibleText, sanitizeCardText } from "./presentation.ts";
5
-
6
- export const CARD_FRAME_EVENT = "pi-persona:card-frame:v1";
7
-
8
- export type CardFrameState = "neutral" | "success" | "attention" | "error";
9
-
10
- export interface CardFramePreview {
11
- text: string;
12
- truncated: boolean;
13
- }
14
-
15
- export interface CardFramePresentation {
16
- title: string;
17
- state: CardFrameState;
18
- full: string;
19
- preview: (width: number) => CardFramePreview;
20
- metadata?: string;
21
- markdown?: boolean;
22
- }
23
-
24
- export interface CardFrameContext {
25
- expanded: boolean;
26
- theme: Theme;
27
- outputPad: number;
28
- detailHint: () => string;
29
- expansionKey?: object;
30
- }
31
-
32
- export type CardFrameFactory = (presentation: CardFramePresentation, context: CardFrameContext) => Component;
33
-
34
- export interface CardFrameProviderResponse {
35
- version: 1;
36
- provider: "pi-persona";
37
- createCard: CardFrameFactory;
38
- }
39
-
40
- export interface CardFrameQuery {
41
- version: 1;
42
- respond: (response: CardFrameProviderResponse) => void;
43
- }
44
-
45
- export interface CardFrameEventBus {
46
- emit(event: string, data: unknown): void;
47
- }
48
-
49
- export interface MindCardUI {
50
- renderCard: CardFrameRenderer;
51
- /** Read from Pi's current effective settings for every entry-render invocation. */
52
- outputPad: () => 0 | 1;
53
- }
54
-
55
- export type CardFrameRenderer = (presentation: CardFramePresentation, context: CardFrameContext) => Component;
56
-
57
- const MAX_COLLAPSED_CARD_LINES = 3;
58
- const CARD_HINT_ID = "app.tools.expand";
59
- const CARD_HINT_DESCRIPTION = "to expand";
60
-
61
- function plainObject(value: unknown): value is Record<string, unknown> {
62
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
63
- const prototype = Object.getPrototypeOf(value);
64
- return prototype === Object.prototype || prototype === null;
65
- }
66
-
67
- function validFactory(value: unknown): CardFrameFactory | undefined {
68
- if (!plainObject(value)) return undefined;
69
- const keys = Reflect.ownKeys(value);
70
- if (keys.length !== 3 || keys.some((key) => key !== "version" && key !== "provider" && key !== "createCard")) return undefined;
71
- if (value.version !== 1 || value.provider !== "pi-persona" || typeof value.createCard !== "function") return undefined;
72
- return value.createCard as CardFrameFactory;
73
- }
74
-
75
- function isComponent(value: unknown): value is Component {
76
- return !!value && typeof value === "object"
77
- && typeof (value as { render?: unknown }).render === "function"
78
- && typeof (value as { invalidate?: unknown }).invalidate === "function";
79
- }
80
-
81
- /** No second styling system: if Persona is absent or unsafe, show complete sanitized plaintext. */
82
- function plaintextFallback(presentation: CardFramePresentation): Component {
83
- const title = sanitizeCardText(presentation.title).trim();
84
- const safeFull = sanitizeCardText(presentation.full);
85
- const full = safeFull.length > 0 ? safeFull : "(no output)";
86
- return new Text(title ? `${title}\n${full}` : full, 0, 0);
87
- }
88
-
89
- function queryFactory(events: CardFrameEventBus): CardFrameFactory | undefined {
90
- let synchronous = true;
91
- let responseCount = 0;
92
- let factory: CardFrameFactory | undefined;
93
- const query: CardFrameQuery = {
94
- version: 1,
95
- respond(response) {
96
- if (!synchronous) return;
97
- const candidate = validFactory(response);
98
- if (!candidate) return;
99
- responseCount++;
100
- factory = candidate;
101
- },
102
- };
103
- try {
104
- events.emit(CARD_FRAME_EVENT, query);
105
- } catch {
106
- return undefined;
107
- } finally {
108
- synchronous = false;
109
- }
110
- return responseCount === 1 ? factory : undefined;
111
- }
112
-
113
- /**
114
- * Bind one UI adapter to one extension instance. The shared factory lookup is intentionally fresh
115
- * for every render so extension load order, reload and provider replacement are observed.
116
- */
117
- export function createMindCardUI(pi: Pick<ExtensionAPI, "events" | "getSettings">): MindCardUI {
118
- const renderCard: CardFrameRenderer = (presentation, context) => {
119
- const fallback = () => plaintextFallback(presentation);
120
- try {
121
- const factory = queryFactory(pi.events);
122
- if (!factory) return fallback();
123
- const component = factory(presentation, context);
124
- return isComponent(component) ? component : fallback();
125
- } catch {
126
- return fallback();
127
- }
128
- };
129
- return {
130
- renderCard,
131
- outputPad: () => {
132
- try {
133
- return pi.getSettings().outputPad === 0 ? 0 : 1;
134
- } catch {
135
- return 1;
136
- }
137
- },
138
- };
139
- }
140
-
141
- /** Build the shared-frame presentation without changing the persisted/history payload. */
142
- export function cardFramePresentation(title: string, full: string, compactSummary?: string): CardFramePresentation {
143
- const previewSource = compactSummary ?? full;
144
- return {
145
- title,
146
- state: "neutral",
147
- full,
148
- preview(width) {
149
- const previewWidth = Number.isFinite(width) ? Math.max(1, Math.floor(width)) : 96;
150
- const preview = compactVisibleText(previewSource, {
151
- maxLines: MAX_COLLAPSED_CARD_LINES,
152
- maxLineChars: previewWidth,
153
- });
154
- return { text: preview.text, truncated: compactSummary !== undefined || preview.truncated };
155
- },
156
- };
157
- }
158
-
159
- export function cardFrameDetailHint(keyHint: EntryRenderOptions["keyHint"]): () => string {
160
- return () => keyHint(CARD_HINT_ID, CARD_HINT_DESCRIPTION);
161
- }
1
+ /** Lazy adapter for Persona's one versioned card-frame implementation. */
2
+ import type { EntryRenderOptions, ExtensionAPI, Theme } from "@earendil-works/pi-coding-agent";
3
+ import { Text, type Component } from "@earendil-works/pi-tui";
4
+ import { compactVisibleText, sanitizeCardText } from "./presentation.ts";
5
+
6
+ export const CARD_FRAME_EVENT = "pi-persona:card-frame:v1";
7
+
8
+ export type CardFrameState = "neutral" | "success" | "attention" | "error";
9
+
10
+ export interface CardFramePreview {
11
+ text: string;
12
+ truncated: boolean;
13
+ }
14
+
15
+ export interface CardFramePresentation {
16
+ title: string;
17
+ state: CardFrameState;
18
+ full: string;
19
+ preview: (width: number) => CardFramePreview;
20
+ metadata?: string;
21
+ markdown?: boolean;
22
+ }
23
+
24
+ export interface CardFrameContext {
25
+ expanded: boolean;
26
+ theme: Theme;
27
+ outputPad: number;
28
+ detailHint: () => string;
29
+ expansionKey?: object;
30
+ }
31
+
32
+ export type CardFrameFactory = (presentation: CardFramePresentation, context: CardFrameContext) => Component;
33
+
34
+ export interface CardFrameProviderResponse {
35
+ version: 1;
36
+ provider: "pi-persona";
37
+ createCard: CardFrameFactory;
38
+ }
39
+
40
+ export interface CardFrameQuery {
41
+ version: 1;
42
+ respond: (response: CardFrameProviderResponse) => void;
43
+ }
44
+
45
+ export interface CardFrameEventBus {
46
+ emit(event: string, data: unknown): void;
47
+ }
48
+
49
+ export interface MindCardUI {
50
+ renderCard: CardFrameRenderer;
51
+ /** Read from Pi's current effective settings for every entry-render invocation. */
52
+ outputPad: () => 0 | 1;
53
+ }
54
+
55
+ export type CardFrameRenderer = (presentation: CardFramePresentation, context: CardFrameContext) => Component;
56
+
57
+ const MAX_COLLAPSED_CARD_LINES = 3;
58
+ const CARD_HINT_ID = "app.tools.expand";
59
+ const CARD_HINT_DESCRIPTION = "to expand";
60
+
61
+ function plainObject(value: unknown): value is Record<string, unknown> {
62
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
63
+ const prototype = Object.getPrototypeOf(value);
64
+ return prototype === Object.prototype || prototype === null;
65
+ }
66
+
67
+ function validFactory(value: unknown): CardFrameFactory | undefined {
68
+ if (!plainObject(value)) return undefined;
69
+ const keys = Reflect.ownKeys(value);
70
+ if (keys.length !== 3 || keys.some((key) => key !== "version" && key !== "provider" && key !== "createCard")) return undefined;
71
+ if (value.version !== 1 || value.provider !== "pi-persona" || typeof value.createCard !== "function") return undefined;
72
+ return value.createCard as CardFrameFactory;
73
+ }
74
+
75
+ function isComponent(value: unknown): value is Component {
76
+ return !!value && typeof value === "object"
77
+ && typeof (value as { render?: unknown }).render === "function"
78
+ && typeof (value as { invalidate?: unknown }).invalidate === "function";
79
+ }
80
+
81
+ /** No second styling system: if Persona is absent or unsafe, show complete sanitized plaintext. */
82
+ function plaintextFallback(presentation: CardFramePresentation): Component {
83
+ const title = sanitizeCardText(presentation.title).trim();
84
+ const safeFull = sanitizeCardText(presentation.full);
85
+ const full = safeFull.length > 0 ? safeFull : "(no output)";
86
+ return new Text(title ? `${title}\n${full}` : full, 0, 0);
87
+ }
88
+
89
+ function queryFactory(events: CardFrameEventBus): CardFrameFactory | undefined {
90
+ let synchronous = true;
91
+ let responseCount = 0;
92
+ let factory: CardFrameFactory | undefined;
93
+ const query: CardFrameQuery = {
94
+ version: 1,
95
+ respond(response) {
96
+ if (!synchronous) return;
97
+ const candidate = validFactory(response);
98
+ if (!candidate) return;
99
+ responseCount++;
100
+ factory = candidate;
101
+ },
102
+ };
103
+ try {
104
+ events.emit(CARD_FRAME_EVENT, query);
105
+ } catch {
106
+ return undefined;
107
+ } finally {
108
+ synchronous = false;
109
+ }
110
+ return responseCount === 1 ? factory : undefined;
111
+ }
112
+
113
+ /**
114
+ * Bind one UI adapter to one extension instance. The shared factory lookup is intentionally fresh
115
+ * for every render so extension load order, reload and provider replacement are observed.
116
+ */
117
+ export function createMindCardUI(pi: Pick<ExtensionAPI, "events" | "getSettings">): MindCardUI {
118
+ const renderCard: CardFrameRenderer = (presentation, context) => {
119
+ const fallback = () => plaintextFallback(presentation);
120
+ try {
121
+ const factory = queryFactory(pi.events);
122
+ if (!factory) return fallback();
123
+ const component = factory(presentation, context);
124
+ return isComponent(component) ? component : fallback();
125
+ } catch {
126
+ return fallback();
127
+ }
128
+ };
129
+ return {
130
+ renderCard,
131
+ outputPad: () => {
132
+ try {
133
+ return pi.getSettings().outputPad === 0 ? 0 : 1;
134
+ } catch {
135
+ return 1;
136
+ }
137
+ },
138
+ };
139
+ }
140
+
141
+ /** Build the shared-frame presentation without changing the persisted/history payload. */
142
+ export function cardFramePresentation(title: string, full: string, compactSummary?: string): CardFramePresentation {
143
+ const previewSource = compactSummary ?? full;
144
+ return {
145
+ title,
146
+ state: "neutral",
147
+ full,
148
+ preview(width) {
149
+ const previewWidth = Number.isFinite(width) ? Math.max(1, Math.floor(width)) : 96;
150
+ const preview = compactVisibleText(previewSource, {
151
+ maxLines: MAX_COLLAPSED_CARD_LINES,
152
+ maxLineChars: previewWidth,
153
+ });
154
+ return { text: preview.text, truncated: compactSummary !== undefined || preview.truncated };
155
+ },
156
+ };
157
+ }
158
+
159
+ export function cardFrameDetailHint(keyHint: EntryRenderOptions["keyHint"]): () => string {
160
+ return () => keyHint(CARD_HINT_ID, CARD_HINT_DESCRIPTION);
161
+ }
@@ -1,44 +1,44 @@
1
- /** Structural adapter to Persona's shared, stateless inspector frame. */
2
- export const INSPECTOR_FRAME_EVENT = "pi-persona:inspector-frame:v1";
3
-
4
- export interface InspectorLayout {
5
- width: number;
6
- height: number;
7
- contentWidth: number;
8
- contentRows: number;
9
- gutter: number;
10
- framed: boolean;
11
- }
12
-
13
- export interface InspectorFrame {
14
- viewportRows(terminalRows: number): number;
15
- layout(width: number, height: number): InspectorLayout;
16
- render(lines: readonly string[], layout: InspectorLayout, border: (text: string) => string): string[];
17
- }
18
-
19
- export interface InspectorFrameEventBus { emit(event: string, data: unknown): void; }
20
-
21
- function validFrame(response: unknown): InspectorFrame | undefined {
22
- if (!response || typeof response !== "object") return undefined;
23
- const value = response as Record<string, unknown>;
24
- if (value.version !== 1 || value.provider !== "pi-persona" || !value.frame || typeof value.frame !== "object") return undefined;
25
- const frame = value.frame as Record<string, unknown>;
26
- return typeof frame.viewportRows === "function" && typeof frame.layout === "function" && typeof frame.render === "function"
27
- ? value.frame as InspectorFrame : undefined;
28
- }
29
-
30
- /** Resolve on each opening; late and ambiguous providers cannot select a renderer. */
31
- export function queryInspectorFrame(events: InspectorFrameEventBus): InspectorFrame | undefined {
32
- let synchronous = true;
33
- let count = 0;
34
- let frame: InspectorFrame | undefined;
35
- try {
36
- events.emit(INSPECTOR_FRAME_EVENT, { version: 1, respond(response: unknown) {
37
- if (!synchronous) return;
38
- const candidate = validFrame(response);
39
- if (candidate) { count++; frame = candidate; }
40
- } });
41
- } catch { return undefined; }
42
- finally { synchronous = false; }
43
- return count === 1 ? frame : undefined;
44
- }
1
+ /** Structural adapter to Persona's shared, stateless inspector frame. */
2
+ export const INSPECTOR_FRAME_EVENT = "pi-persona:inspector-frame:v1";
3
+
4
+ export interface InspectorLayout {
5
+ width: number;
6
+ height: number;
7
+ contentWidth: number;
8
+ contentRows: number;
9
+ gutter: number;
10
+ framed: boolean;
11
+ }
12
+
13
+ export interface InspectorFrame {
14
+ viewportRows(terminalRows: number): number;
15
+ layout(width: number, height: number): InspectorLayout;
16
+ render(lines: readonly string[], layout: InspectorLayout, border: (text: string) => string): string[];
17
+ }
18
+
19
+ export interface InspectorFrameEventBus { emit(event: string, data: unknown): void; }
20
+
21
+ function validFrame(response: unknown): InspectorFrame | undefined {
22
+ if (!response || typeof response !== "object") return undefined;
23
+ const value = response as Record<string, unknown>;
24
+ if (value.version !== 1 || value.provider !== "pi-persona" || !value.frame || typeof value.frame !== "object") return undefined;
25
+ const frame = value.frame as Record<string, unknown>;
26
+ return typeof frame.viewportRows === "function" && typeof frame.layout === "function" && typeof frame.render === "function"
27
+ ? value.frame as InspectorFrame : undefined;
28
+ }
29
+
30
+ /** Resolve on each opening; late and ambiguous providers cannot select a renderer. */
31
+ export function queryInspectorFrame(events: InspectorFrameEventBus): InspectorFrame | undefined {
32
+ let synchronous = true;
33
+ let count = 0;
34
+ let frame: InspectorFrame | undefined;
35
+ try {
36
+ events.emit(INSPECTOR_FRAME_EVENT, { version: 1, respond(response: unknown) {
37
+ if (!synchronous) return;
38
+ const candidate = validFrame(response);
39
+ if (candidate) { count++; frame = candidate; }
40
+ } });
41
+ } catch { return undefined; }
42
+ finally { synchronous = false; }
43
+ return count === 1 ? frame : undefined;
44
+ }