@aeondave/pi-persona-mind 0.9.6 → 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.
- package/AGENTS.md +137 -135
- package/CHANGELOG.md +287 -270
- package/LICENSE +24 -24
- package/README.md +84 -171
- package/docs/DESIGN.md +605 -573
- package/docs/MEMORY-RESEARCH.md +163 -163
- package/package.json +15 -6
- package/src/core/auto-optimize.ts +323 -249
- package/src/core/backlog.ts +228 -228
- package/src/core/blocked.ts +38 -38
- package/src/core/capture.ts +155 -154
- package/src/core/context-budget.ts +74 -74
- package/src/core/handoff-store.ts +111 -111
- package/src/core/handoff.ts +70 -70
- package/src/core/host-compat.ts +16 -16
- package/src/core/ids.ts +59 -59
- package/src/core/inject.ts +247 -247
- package/src/core/knowledge-review.ts +107 -107
- package/src/core/memory-read.ts +34 -34
- package/src/core/memory.ts +321 -321
- package/src/core/migrate.ts +713 -713
- package/src/core/mind-settings.ts +54 -54
- package/src/core/optimize-history.ts +163 -163
- package/src/core/optimize-service.ts +189 -180
- package/src/core/optimize.ts +127 -127
- package/src/core/retrieval.ts +164 -164
- package/src/core/scanner.ts +146 -146
- package/src/core/scope.ts +201 -205
- package/src/core/service.ts +720 -720
- package/src/core/session-memory.ts +71 -71
- package/src/core/store.ts +1002 -1002
- package/src/extension/activity.ts +79 -79
- package/src/extension/auto-optimize-session.ts +143 -143
- package/src/extension/auto-optimize.ts +565 -569
- package/src/extension/handoff.ts +23 -23
- package/src/extension/knowledge-review.ts +229 -229
- package/src/extension/memory-inspector.ts +82 -82
- package/src/extension/mind-actions.ts +38 -38
- package/src/extension/mind-worker.ts +32 -32
- package/src/extension/persona-dependency.ts +76 -76
- package/src/extension/reference-anchor.ts +48 -0
- package/src/extension/review-evidence.ts +222 -222
- package/src/extension/worker-memory-anchor.ts +28 -28
- package/src/index.ts +1357 -1310
- package/src/session-memory.ts +127 -122
- package/src/tools/backlog.ts +126 -126
- package/src/tools/memory-handoff.ts +30 -30
- package/src/tools/memory-history.ts +46 -46
- package/src/tools/memory.ts +6 -4
- package/src/ui/card-frame.ts +161 -161
- package/src/ui/inspector-frame.ts +44 -44
- package/src/ui/memory-inspector.ts +464 -464
- package/src/ui/mind-result-card.ts +48 -48
- package/src/ui/presentation.ts +87 -87
- package/src/ui/session-note-card.ts +58 -56
|
@@ -1,82 +1,82 @@
|
|
|
1
|
-
/** Read-only inspector lifecycle. No persistence, model requests, or replacement retrieval policy. */
|
|
2
|
-
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
-
import { estimateTokens } from "../core/context-budget.ts";
|
|
4
|
-
import type { InspectorPage, InspectorRequest, InspectorTab } from "./inspector-data.ts";
|
|
5
|
-
import type { InspectorActionRequest } from "./mind-actions.ts";
|
|
6
|
-
|
|
7
|
-
export interface InspectorScreenOptions {
|
|
8
|
-
load(request: InspectorRequest): Promise<InspectorPage>;
|
|
9
|
-
isCurrent(): boolean;
|
|
10
|
-
initialTab: InspectorTab;
|
|
11
|
-
signal: AbortSignal;
|
|
12
|
-
onAction?(request: InspectorActionRequest): Promise<void>;
|
|
13
|
-
}
|
|
14
|
-
export interface MemoryInspectorDeps {
|
|
15
|
-
unavailableReason(ctx: ExtensionContext): string | undefined;
|
|
16
|
-
captureOwner(ctx: ExtensionContext): () => boolean;
|
|
17
|
-
load(ctx: ExtensionContext, request: InspectorRequest): Promise<InspectorPage>;
|
|
18
|
-
show(ctx: ExtensionContext, options: InspectorScreenOptions): Promise<void>;
|
|
19
|
-
actions?(ctx: ExtensionContext, request: InspectorActionRequest, isCurrent: () => boolean): Promise<void>;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export function createMemoryInspector(deps: MemoryInspectorDeps) {
|
|
23
|
-
let generation = 0;
|
|
24
|
-
let opening: AbortController | undefined;
|
|
25
|
-
let prepared: { text: string; at: string; current: () => boolean } | undefined;
|
|
26
|
-
const invalidate = (): void => {
|
|
27
|
-
generation++;
|
|
28
|
-
prepared = undefined;
|
|
29
|
-
const old = opening;
|
|
30
|
-
opening = undefined;
|
|
31
|
-
old?.abort();
|
|
32
|
-
};
|
|
33
|
-
const captureContext = (ctx: ExtensionContext): (() => boolean) => {
|
|
34
|
-
const acceptedGeneration = generation;
|
|
35
|
-
const owner = deps.captureOwner(ctx);
|
|
36
|
-
return () => acceptedGeneration === generation && owner();
|
|
37
|
-
};
|
|
38
|
-
return {
|
|
39
|
-
invalidate, captureContext,
|
|
40
|
-
recordContext(ctx: ExtensionContext, text: string, current = captureContext(ctx)): void {
|
|
41
|
-
if (current()) prepared = { text, at: new Date().toISOString(), current };
|
|
42
|
-
},
|
|
43
|
-
async open(ctx: ExtensionContext, initialTab: InspectorTab = "memories"): Promise<void> {
|
|
44
|
-
const unavailable = deps.unavailableReason(ctx);
|
|
45
|
-
if (unavailable) { ctx.ui.notify(unavailable, "warning"); return; }
|
|
46
|
-
if (ctx.mode !== "tui") { ctx.ui.notify("Memory inspector requires the interactive terminal (TUI). Use /mind, /mind session or memory recall/read here.", "info"); return; }
|
|
47
|
-
if (opening) return;
|
|
48
|
-
const owner = deps.captureOwner(ctx);
|
|
49
|
-
if (!owner()) { ctx.ui.notify("Memory session owner is unavailable.", "warning"); return; }
|
|
50
|
-
const acceptedGeneration = generation;
|
|
51
|
-
const controller = new AbortController();
|
|
52
|
-
opening = controller;
|
|
53
|
-
const current = (): boolean => !controller.signal.aborted && acceptedGeneration === generation && owner();
|
|
54
|
-
const requireCurrent = (): void => { if (!current()) throw new Error("Memory inspector session owner changed; reopen it."); };
|
|
55
|
-
try {
|
|
56
|
-
await deps.show(ctx, {
|
|
57
|
-
initialTab, signal: controller.signal, isCurrent: current,
|
|
58
|
-
...(deps.actions ? { onAction: async (request: InspectorActionRequest) => { requireCurrent(); await deps.actions!(ctx, request, current); } } : {}),
|
|
59
|
-
async load(request) {
|
|
60
|
-
requireCurrent();
|
|
61
|
-
if (request.tab === "context") {
|
|
62
|
-
if (!prepared?.current()) return { items: [], total: 0, offset: 0, notice: "No Mind context prepared in this active session/branch yet. Start a turn; reopening does not recompute or persist context." };
|
|
63
|
-
const { text, at } = prepared;
|
|
64
|
-
return {
|
|
65
|
-
items: [{ id: "prepared-context", title: `Last prepared · ${at} · ~${estimateTokens(text)} tokens (estimate)`, body: text || "Mind prepared no additional context for this turn." }],
|
|
66
|
-
total: 1, offset: 0,
|
|
67
|
-
notice: "Exact last block prepared by Mind, not the final provider payload. Later extensions may change it. UTF-8 bytes/3 is a planning estimate, not billing. Omission notices are part of the block; selection uses the existing lexical/tag/path ranker and bounded priority, never a second inspector policy.",
|
|
68
|
-
};
|
|
69
|
-
}
|
|
70
|
-
const page = await deps.load(ctx, request);
|
|
71
|
-
requireCurrent();
|
|
72
|
-
return page;
|
|
73
|
-
},
|
|
74
|
-
});
|
|
75
|
-
} catch (error) {
|
|
76
|
-
if (current()) ctx.ui.notify(`Memory inspector unavailable: ${error instanceof Error ? error.message : "read failed"}`, "warning");
|
|
77
|
-
} finally {
|
|
78
|
-
if (opening === controller) opening = undefined;
|
|
79
|
-
}
|
|
80
|
-
},
|
|
81
|
-
};
|
|
82
|
-
}
|
|
1
|
+
/** Read-only inspector lifecycle. No persistence, model requests, or replacement retrieval policy. */
|
|
2
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { estimateTokens } from "../core/context-budget.ts";
|
|
4
|
+
import type { InspectorPage, InspectorRequest, InspectorTab } from "./inspector-data.ts";
|
|
5
|
+
import type { InspectorActionRequest } from "./mind-actions.ts";
|
|
6
|
+
|
|
7
|
+
export interface InspectorScreenOptions {
|
|
8
|
+
load(request: InspectorRequest): Promise<InspectorPage>;
|
|
9
|
+
isCurrent(): boolean;
|
|
10
|
+
initialTab: InspectorTab;
|
|
11
|
+
signal: AbortSignal;
|
|
12
|
+
onAction?(request: InspectorActionRequest): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
export interface MemoryInspectorDeps {
|
|
15
|
+
unavailableReason(ctx: ExtensionContext): string | undefined;
|
|
16
|
+
captureOwner(ctx: ExtensionContext): () => boolean;
|
|
17
|
+
load(ctx: ExtensionContext, request: InspectorRequest): Promise<InspectorPage>;
|
|
18
|
+
show(ctx: ExtensionContext, options: InspectorScreenOptions): Promise<void>;
|
|
19
|
+
actions?(ctx: ExtensionContext, request: InspectorActionRequest, isCurrent: () => boolean): Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function createMemoryInspector(deps: MemoryInspectorDeps) {
|
|
23
|
+
let generation = 0;
|
|
24
|
+
let opening: AbortController | undefined;
|
|
25
|
+
let prepared: { text: string; at: string; current: () => boolean } | undefined;
|
|
26
|
+
const invalidate = (): void => {
|
|
27
|
+
generation++;
|
|
28
|
+
prepared = undefined;
|
|
29
|
+
const old = opening;
|
|
30
|
+
opening = undefined;
|
|
31
|
+
old?.abort();
|
|
32
|
+
};
|
|
33
|
+
const captureContext = (ctx: ExtensionContext): (() => boolean) => {
|
|
34
|
+
const acceptedGeneration = generation;
|
|
35
|
+
const owner = deps.captureOwner(ctx);
|
|
36
|
+
return () => acceptedGeneration === generation && owner();
|
|
37
|
+
};
|
|
38
|
+
return {
|
|
39
|
+
invalidate, captureContext,
|
|
40
|
+
recordContext(ctx: ExtensionContext, text: string, current = captureContext(ctx)): void {
|
|
41
|
+
if (current()) prepared = { text, at: new Date().toISOString(), current };
|
|
42
|
+
},
|
|
43
|
+
async open(ctx: ExtensionContext, initialTab: InspectorTab = "memories"): Promise<void> {
|
|
44
|
+
const unavailable = deps.unavailableReason(ctx);
|
|
45
|
+
if (unavailable) { ctx.ui.notify(unavailable, "warning"); return; }
|
|
46
|
+
if (ctx.mode !== "tui") { ctx.ui.notify("Memory inspector requires the interactive terminal (TUI). Use /mind, /mind session or memory recall/read here.", "info"); return; }
|
|
47
|
+
if (opening) return;
|
|
48
|
+
const owner = deps.captureOwner(ctx);
|
|
49
|
+
if (!owner()) { ctx.ui.notify("Memory session owner is unavailable.", "warning"); return; }
|
|
50
|
+
const acceptedGeneration = generation;
|
|
51
|
+
const controller = new AbortController();
|
|
52
|
+
opening = controller;
|
|
53
|
+
const current = (): boolean => !controller.signal.aborted && acceptedGeneration === generation && owner();
|
|
54
|
+
const requireCurrent = (): void => { if (!current()) throw new Error("Memory inspector session owner changed; reopen it."); };
|
|
55
|
+
try {
|
|
56
|
+
await deps.show(ctx, {
|
|
57
|
+
initialTab, signal: controller.signal, isCurrent: current,
|
|
58
|
+
...(deps.actions ? { onAction: async (request: InspectorActionRequest) => { requireCurrent(); await deps.actions!(ctx, request, current); } } : {}),
|
|
59
|
+
async load(request) {
|
|
60
|
+
requireCurrent();
|
|
61
|
+
if (request.tab === "context") {
|
|
62
|
+
if (!prepared?.current()) return { items: [], total: 0, offset: 0, notice: "No Mind context prepared in this active session/branch yet. Start a turn; reopening does not recompute or persist context." };
|
|
63
|
+
const { text, at } = prepared;
|
|
64
|
+
return {
|
|
65
|
+
items: [{ id: "prepared-context", title: `Last prepared · ${at} · ~${estimateTokens(text)} tokens (estimate)`, body: text || "Mind prepared no additional context for this turn." }],
|
|
66
|
+
total: 1, offset: 0,
|
|
67
|
+
notice: "Exact last block prepared by Mind, not the final provider payload. Later extensions may change it. UTF-8 bytes/3 is a planning estimate, not billing. Omission notices are part of the block; selection uses the existing lexical/tag/path ranker and bounded priority, never a second inspector policy.",
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
const page = await deps.load(ctx, request);
|
|
71
|
+
requireCurrent();
|
|
72
|
+
return page;
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (current()) ctx.ui.notify(`Memory inspector unavailable: ${error instanceof Error ? error.message : "read failed"}`, "warning");
|
|
77
|
+
} finally {
|
|
78
|
+
if (opening === controller) opening = undefined;
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
@@ -1,38 +1,38 @@
|
|
|
1
|
-
/** Explicit human actions after F10 closes. Browsing itself stays read-only. */
|
|
2
|
-
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
-
import type { InspectorRequest } from "./inspector-data.ts";
|
|
4
|
-
import type { ReviewTarget } from "../core/knowledge-review.ts";
|
|
5
|
-
import type { createKnowledgeReview } from "./knowledge-review.ts";
|
|
6
|
-
|
|
7
|
-
export type InspectorActionRequest = InspectorRequest & { selectedId?: string };
|
|
8
|
-
export interface MindActionDeps {
|
|
9
|
-
consolidate(target: ReviewTarget): boolean;
|
|
10
|
-
review: ReturnType<typeof createKnowledgeReview>;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export async function runMindInspectorActions(ctx: ExtensionContext, request: InspectorActionRequest, current: () => boolean, deps: MindActionDeps): Promise<void> {
|
|
14
|
-
if (!current() || ctx.mode !== "tui" || request.tab !== "memories") return;
|
|
15
|
-
const target = request.scope === "project" || request.scope === "project-long" || request.scope === "persona" ? request.scope : undefined;
|
|
16
|
-
const consolidate = "Consolidate this scope (bounded window)";
|
|
17
|
-
const selected = "Review selected fact against evidence";
|
|
18
|
-
const window = "Review this scope against evidence (bounded window)";
|
|
19
|
-
const show = "Show pending knowledge review";
|
|
20
|
-
const apply = "Approve staged knowledge corrections";
|
|
21
|
-
const discard = "Discard/cancel knowledge review";
|
|
22
|
-
const choices = [...(target ? [consolidate, ...(request.selectedId ? [selected] : []), window] : []), show, apply, discard];
|
|
23
|
-
const choice = await ctx.ui.select(`Mind actions · ${request.scope}${target ? "" : " (choose a project/persona scope to review facts)"}`, choices);
|
|
24
|
-
if (!choice || !current()) return;
|
|
25
|
-
if (choice === show) { await deps.review.show(ctx); return; }
|
|
26
|
-
if (choice === apply) { await deps.review.apply(ctx); return; }
|
|
27
|
-
if (choice === discard) { deps.review.discard(ctx); return; }
|
|
28
|
-
if (!target) return;
|
|
29
|
-
if (choice === consolidate) {
|
|
30
|
-
const accepted = await ctx.ui.confirm("Consolidate memory?", `Review one bounded window of ${target} on the current session model. Compatible facts may be merged and applied through the existing validated optimizer; history and guarded undo are retained. This is not a truth audit or a full-store rewrite. Continue?`);
|
|
31
|
-
if (!accepted || !current()) return;
|
|
32
|
-
const started = deps.consolidate(target);
|
|
33
|
-
ctx.ui.notify(started ? `mind · ${target} consolidation requested; bounded inspection and worker admission are preparing.` : "Mind maintenance or the foreground is busy; no consolidation was accepted.", started ? "info" : "warning");
|
|
34
|
-
return;
|
|
35
|
-
}
|
|
36
|
-
if (choice === selected) await deps.review.start(ctx, target, request.selectedId);
|
|
37
|
-
else if (choice === window) await deps.review.start(ctx, target);
|
|
38
|
-
}
|
|
1
|
+
/** Explicit human actions after F10 closes. Browsing itself stays read-only. */
|
|
2
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import type { InspectorRequest } from "./inspector-data.ts";
|
|
4
|
+
import type { ReviewTarget } from "../core/knowledge-review.ts";
|
|
5
|
+
import type { createKnowledgeReview } from "./knowledge-review.ts";
|
|
6
|
+
|
|
7
|
+
export type InspectorActionRequest = InspectorRequest & { selectedId?: string };
|
|
8
|
+
export interface MindActionDeps {
|
|
9
|
+
consolidate(target: ReviewTarget): boolean;
|
|
10
|
+
review: ReturnType<typeof createKnowledgeReview>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function runMindInspectorActions(ctx: ExtensionContext, request: InspectorActionRequest, current: () => boolean, deps: MindActionDeps): Promise<void> {
|
|
14
|
+
if (!current() || ctx.mode !== "tui" || request.tab !== "memories") return;
|
|
15
|
+
const target = request.scope === "project" || request.scope === "project-long" || request.scope === "persona" ? request.scope : undefined;
|
|
16
|
+
const consolidate = "Consolidate this scope (bounded window)";
|
|
17
|
+
const selected = "Review selected fact against evidence";
|
|
18
|
+
const window = "Review this scope against evidence (bounded window)";
|
|
19
|
+
const show = "Show pending knowledge review";
|
|
20
|
+
const apply = "Approve staged knowledge corrections";
|
|
21
|
+
const discard = "Discard/cancel knowledge review";
|
|
22
|
+
const choices = [...(target ? [consolidate, ...(request.selectedId ? [selected] : []), window] : []), show, apply, discard];
|
|
23
|
+
const choice = await ctx.ui.select(`Mind actions · ${request.scope}${target ? "" : " (choose a project/persona scope to review facts)"}`, choices);
|
|
24
|
+
if (!choice || !current()) return;
|
|
25
|
+
if (choice === show) { await deps.review.show(ctx); return; }
|
|
26
|
+
if (choice === apply) { await deps.review.apply(ctx); return; }
|
|
27
|
+
if (choice === discard) { deps.review.discard(ctx); return; }
|
|
28
|
+
if (!target) return;
|
|
29
|
+
if (choice === consolidate) {
|
|
30
|
+
const accepted = await ctx.ui.confirm("Consolidate memory?", `Review one bounded window of ${target} on the current session model. Compatible facts may be merged and applied through the existing validated optimizer; history and guarded undo are retained. This is not a truth audit or a full-store rewrite. Continue?`);
|
|
31
|
+
if (!accepted || !current()) return;
|
|
32
|
+
const started = deps.consolidate(target);
|
|
33
|
+
ctx.ui.notify(started ? `mind · ${target} consolidation requested; bounded inspection and worker admission are preparing.` : "Mind maintenance or the foreground is busy; no consolidation was accepted.", started ? "info" : "warning");
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
if (choice === selected) await deps.review.start(ctx, target, request.selectedId);
|
|
37
|
+
else if (choice === window) await deps.review.start(ctx, target);
|
|
38
|
+
}
|
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
/** Closed local bridge: Persona owns the real tracked worker and its model/permissions. */
|
|
2
|
-
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
3
|
-
|
|
4
|
-
export type MindWorkerResult = {
|
|
5
|
-
status: "done"; ok: true; output: string; error?: string; resultRef?: string; model?: string; thinking?: string;
|
|
6
|
-
} | {
|
|
7
|
-
status: "failed" | "stopped"; ok: false; output: string; error?: string; resultRef?: string; model?: string; thinking?: string;
|
|
8
|
-
};
|
|
9
|
-
export type MindWorkerAdmission = { ok: false; reason: string } | {
|
|
10
|
-
ok: true; runId: string; model: string; thinking: string;
|
|
11
|
-
completion: Promise<MindWorkerResult>; cancel(): void;
|
|
12
|
-
};
|
|
13
|
-
|
|
14
|
-
export function launchMindWorker(pi: Pick<ExtensionAPI, "events">, sessionId: string, persona: string | null, task: string): MindWorkerAdmission {
|
|
15
|
-
const replies: unknown[] = [];
|
|
16
|
-
let accepting = true;
|
|
17
|
-
let failed = false;
|
|
18
|
-
try { pi.events.emit("pi-persona:mind-worker:v1", { version: 1, sessionId, persona, task, respond: (value: unknown) => { if (accepting) replies.push(value); else cancelReply(value); } }); }
|
|
19
|
-
catch { failed = true; }
|
|
20
|
-
finally { accepting = false; }
|
|
21
|
-
const reply = replies[0] as Partial<Extract<MindWorkerAdmission, { ok: true }>> | undefined;
|
|
22
|
-
if (!failed && replies.length === 1 && reply?.ok === true && typeof reply.runId === "string" && typeof reply.model === "string" && typeof reply.thinking === "string" && typeof reply.cancel === "function" && reply.completion instanceof Promise) return reply as Extract<MindWorkerAdmission, { ok: true }>;
|
|
23
|
-
// Ambiguous admission cannot leave an unowned worker running.
|
|
24
|
-
for (const value of replies) cancelReply(value);
|
|
25
|
-
if (failed) return { ok: false, reason: "Persona worker admission failed" };
|
|
26
|
-
const refusal = replies[0] as { reason?: unknown } | undefined;
|
|
27
|
-
return { ok: false, reason: typeof refusal?.reason === "string" ? refusal.reason : "Compatible Persona worker service unavailable" };
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
function cancelReply(value: unknown): void {
|
|
31
|
-
try { const item = value as { cancel?: unknown }; if (typeof item?.cancel === "function") item.cancel(); } catch { /* bounded cleanup */ }
|
|
32
|
-
}
|
|
1
|
+
/** Closed local bridge: Persona owns the real tracked worker and its model/permissions. */
|
|
2
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
|
|
4
|
+
export type MindWorkerResult = {
|
|
5
|
+
status: "done"; ok: true; output: string; error?: string; resultRef?: string; model?: string; thinking?: string;
|
|
6
|
+
} | {
|
|
7
|
+
status: "failed" | "stopped"; ok: false; output: string; error?: string; resultRef?: string; model?: string; thinking?: string;
|
|
8
|
+
};
|
|
9
|
+
export type MindWorkerAdmission = { ok: false; reason: string } | {
|
|
10
|
+
ok: true; runId: string; model: string; thinking: string;
|
|
11
|
+
completion: Promise<MindWorkerResult>; cancel(): void;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export function launchMindWorker(pi: Pick<ExtensionAPI, "events">, sessionId: string, persona: string | null, task: string): MindWorkerAdmission {
|
|
15
|
+
const replies: unknown[] = [];
|
|
16
|
+
let accepting = true;
|
|
17
|
+
let failed = false;
|
|
18
|
+
try { pi.events.emit("pi-persona:mind-worker:v1", { version: 1, sessionId, persona, task, respond: (value: unknown) => { if (accepting) replies.push(value); else cancelReply(value); } }); }
|
|
19
|
+
catch { failed = true; }
|
|
20
|
+
finally { accepting = false; }
|
|
21
|
+
const reply = replies[0] as Partial<Extract<MindWorkerAdmission, { ok: true }>> | undefined;
|
|
22
|
+
if (!failed && replies.length === 1 && reply?.ok === true && typeof reply.runId === "string" && typeof reply.model === "string" && typeof reply.thinking === "string" && typeof reply.cancel === "function" && reply.completion instanceof Promise) return reply as Extract<MindWorkerAdmission, { ok: true }>;
|
|
23
|
+
// Ambiguous admission cannot leave an unowned worker running.
|
|
24
|
+
for (const value of replies) cancelReply(value);
|
|
25
|
+
if (failed) return { ok: false, reason: "Persona worker admission failed" };
|
|
26
|
+
const refusal = replies[0] as { reason?: unknown } | undefined;
|
|
27
|
+
return { ok: false, reason: typeof refusal?.reason === "string" ? refusal.reason : "Compatible Persona worker service unavailable" };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function cancelReply(value: unknown): void {
|
|
31
|
+
try { const item = value as { cancel?: unknown }; if (typeof item?.cancel === "function") item.cancel(); } catch { /* bounded cleanup */ }
|
|
32
|
+
}
|
|
@@ -1,76 +1,76 @@
|
|
|
1
|
-
/** Mind requires the loaded Persona extension's public, synchronous capability protocol. */
|
|
2
|
-
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
-
|
|
4
|
-
export const PERSONA_COMPANION_CHANNEL = "pi-persona:companion:v1";
|
|
5
|
-
export const PERSONA_MEMORY_OWNER_CHANNEL = "pi-persona:memory-owner:v1";
|
|
6
|
-
export const PERSONA_MEMORY_OWNER_CHANGED = "pi-persona:memory-owner-changed:v1";
|
|
7
|
-
export const PERSONA_REQUIRED_REASON = "Mind is inactive: load a compatible pi-persona extension and /reload.";
|
|
8
|
-
export interface PersonaPresence {
|
|
9
|
-
version: 1;
|
|
10
|
-
provider: "pi-persona";
|
|
11
|
-
role: "supervisor" | "leg" | "disabled";
|
|
12
|
-
capabilities: { memory: 1 | false; activity: 1 | false };
|
|
13
|
-
}
|
|
14
|
-
export type PersonaDependency = { ok: true; presence: PersonaPresence } | { ok: false; reason: string };
|
|
15
|
-
export interface PersonaMemoryOwner { version: 1; provider: "pi-persona"; sessionId: string; ready: boolean; persona: string | null }
|
|
16
|
-
export function parsePersonaMemoryOwner(value: unknown, sessionId: string): PersonaMemoryOwner | undefined {
|
|
17
|
-
try {
|
|
18
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
19
|
-
const row = value as Record<string, unknown>;
|
|
20
|
-
if (Reflect.ownKeys(row).some((key) => !["version", "provider", "sessionId", "ready", "persona"].includes(String(key)))) return undefined;
|
|
21
|
-
if (row.version !== 1 || row.provider !== "pi-persona" || row.sessionId !== sessionId || typeof row.ready !== "boolean" || (row.persona !== null && (typeof row.persona !== "string" || !row.persona.trim() || row.persona.length > 1024))) return undefined;
|
|
22
|
-
return { version: 1, provider: "pi-persona", sessionId, ready: row.ready, persona: row.persona as string | null };
|
|
23
|
-
} catch { return undefined; }
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export function queryPersonaMemoryOwner(pi: Pick<ExtensionAPI, "events">, ctx: ExtensionContext): PersonaMemoryOwner | undefined {
|
|
27
|
-
try {
|
|
28
|
-
const sessionId = ctx.sessionManager.getSessionId();
|
|
29
|
-
const responses: unknown[] = [];
|
|
30
|
-
let accepting = true;
|
|
31
|
-
try { pi.events.emit(PERSONA_MEMORY_OWNER_CHANNEL, { version: 1, sessionId, respond: (owner: unknown) => { if (accepting) responses.push(owner); } }); }
|
|
32
|
-
finally { accepting = false; }
|
|
33
|
-
return responses.length === 1 ? parsePersonaMemoryOwner(responses[0], sessionId) : undefined;
|
|
34
|
-
} catch { return undefined; }
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
function validPresence(value: unknown): value is PersonaPresence {
|
|
38
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
39
|
-
const row = value as Record<string, unknown>;
|
|
40
|
-
if (Object.keys(row).some((key) => !["version", "provider", "role", "capabilities"].includes(key))) return false;
|
|
41
|
-
if (row.version !== 1 || row.provider !== "pi-persona" || typeof row.role !== "string" || !["supervisor", "leg", "disabled"].includes(row.role)) return false;
|
|
42
|
-
if (!row.capabilities || typeof row.capabilities !== "object" || Array.isArray(row.capabilities)) return false;
|
|
43
|
-
const caps = row.capabilities as Record<string, unknown>;
|
|
44
|
-
if (Object.keys(caps).some((key) => key !== "memory" && key !== "activity")) return false;
|
|
45
|
-
if ((caps.memory !== 1 && caps.memory !== false) || (caps.activity !== 1 && caps.activity !== false)) return false;
|
|
46
|
-
return row.role === "supervisor" ? caps.memory === 1 && caps.activity === 1
|
|
47
|
-
: row.role === "leg" ? caps.memory === 1 && caps.activity === false
|
|
48
|
-
: caps.memory === false && caps.activity === false;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
export function queryPersonaDependency(pi: Pick<ExtensionAPI, "events">): PersonaDependency {
|
|
52
|
-
const responses: unknown[] = [];
|
|
53
|
-
let accepting = true;
|
|
54
|
-
try { pi.events.emit(PERSONA_COMPANION_CHANNEL, { version: 1, respond: (presence: unknown) => { if (accepting) responses.push(presence); } }); }
|
|
55
|
-
catch { return { ok: false, reason: PERSONA_REQUIRED_REASON }; }
|
|
56
|
-
finally { accepting = false; }
|
|
57
|
-
try {
|
|
58
|
-
if (responses.length !== 1 || !validPresence(responses[0]) || responses[0].capabilities.memory !== 1) return { ok: false, reason: PERSONA_REQUIRED_REASON };
|
|
59
|
-
return { ok: true, presence: structuredClone(responses[0]) };
|
|
60
|
-
} catch { return { ok: false, reason: PERSONA_REQUIRED_REASON }; }
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
/** Active tool selection is discovery only; this wrapper also guards direct programmatic execution. */
|
|
64
|
-
export function personaGuardedTools(pi: ExtensionAPI, unavailableReason: (ctx: ExtensionContext) => string | undefined): ExtensionAPI {
|
|
65
|
-
const guarded = Object.create(pi) as ExtensionAPI;
|
|
66
|
-
guarded.registerTool = (definition) => pi.registerTool({
|
|
67
|
-
...definition,
|
|
68
|
-
async execute(...args) {
|
|
69
|
-
const reason = unavailableReason(args[4]);
|
|
70
|
-
// Pi converts thrown tool errors to its native error result, also for executeTool().
|
|
71
|
-
if (reason) throw new Error(reason);
|
|
72
|
-
return definition.execute(...args);
|
|
73
|
-
},
|
|
74
|
-
});
|
|
75
|
-
return guarded;
|
|
76
|
-
}
|
|
1
|
+
/** Mind requires the loaded Persona extension's public, synchronous capability protocol. */
|
|
2
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
|
|
4
|
+
export const PERSONA_COMPANION_CHANNEL = "pi-persona:companion:v1";
|
|
5
|
+
export const PERSONA_MEMORY_OWNER_CHANNEL = "pi-persona:memory-owner:v1";
|
|
6
|
+
export const PERSONA_MEMORY_OWNER_CHANGED = "pi-persona:memory-owner-changed:v1";
|
|
7
|
+
export const PERSONA_REQUIRED_REASON = "Mind is inactive: load a compatible pi-persona extension and /reload.";
|
|
8
|
+
export interface PersonaPresence {
|
|
9
|
+
version: 1;
|
|
10
|
+
provider: "pi-persona";
|
|
11
|
+
role: "supervisor" | "leg" | "disabled";
|
|
12
|
+
capabilities: { memory: 1 | false; activity: 1 | false };
|
|
13
|
+
}
|
|
14
|
+
export type PersonaDependency = { ok: true; presence: PersonaPresence } | { ok: false; reason: string };
|
|
15
|
+
export interface PersonaMemoryOwner { version: 1; provider: "pi-persona"; sessionId: string; ready: boolean; persona: string | null }
|
|
16
|
+
export function parsePersonaMemoryOwner(value: unknown, sessionId: string): PersonaMemoryOwner | undefined {
|
|
17
|
+
try {
|
|
18
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
19
|
+
const row = value as Record<string, unknown>;
|
|
20
|
+
if (Reflect.ownKeys(row).some((key) => !["version", "provider", "sessionId", "ready", "persona"].includes(String(key)))) return undefined;
|
|
21
|
+
if (row.version !== 1 || row.provider !== "pi-persona" || row.sessionId !== sessionId || typeof row.ready !== "boolean" || (row.persona !== null && (typeof row.persona !== "string" || !row.persona.trim() || row.persona.length > 1024))) return undefined;
|
|
22
|
+
return { version: 1, provider: "pi-persona", sessionId, ready: row.ready, persona: row.persona as string | null };
|
|
23
|
+
} catch { return undefined; }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function queryPersonaMemoryOwner(pi: Pick<ExtensionAPI, "events">, ctx: ExtensionContext): PersonaMemoryOwner | undefined {
|
|
27
|
+
try {
|
|
28
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
29
|
+
const responses: unknown[] = [];
|
|
30
|
+
let accepting = true;
|
|
31
|
+
try { pi.events.emit(PERSONA_MEMORY_OWNER_CHANNEL, { version: 1, sessionId, respond: (owner: unknown) => { if (accepting) responses.push(owner); } }); }
|
|
32
|
+
finally { accepting = false; }
|
|
33
|
+
return responses.length === 1 ? parsePersonaMemoryOwner(responses[0], sessionId) : undefined;
|
|
34
|
+
} catch { return undefined; }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function validPresence(value: unknown): value is PersonaPresence {
|
|
38
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
39
|
+
const row = value as Record<string, unknown>;
|
|
40
|
+
if (Object.keys(row).some((key) => !["version", "provider", "role", "capabilities"].includes(key))) return false;
|
|
41
|
+
if (row.version !== 1 || row.provider !== "pi-persona" || typeof row.role !== "string" || !["supervisor", "leg", "disabled"].includes(row.role)) return false;
|
|
42
|
+
if (!row.capabilities || typeof row.capabilities !== "object" || Array.isArray(row.capabilities)) return false;
|
|
43
|
+
const caps = row.capabilities as Record<string, unknown>;
|
|
44
|
+
if (Object.keys(caps).some((key) => key !== "memory" && key !== "activity")) return false;
|
|
45
|
+
if ((caps.memory !== 1 && caps.memory !== false) || (caps.activity !== 1 && caps.activity !== false)) return false;
|
|
46
|
+
return row.role === "supervisor" ? caps.memory === 1 && caps.activity === 1
|
|
47
|
+
: row.role === "leg" ? caps.memory === 1 && caps.activity === false
|
|
48
|
+
: caps.memory === false && caps.activity === false;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function queryPersonaDependency(pi: Pick<ExtensionAPI, "events">): PersonaDependency {
|
|
52
|
+
const responses: unknown[] = [];
|
|
53
|
+
let accepting = true;
|
|
54
|
+
try { pi.events.emit(PERSONA_COMPANION_CHANNEL, { version: 1, respond: (presence: unknown) => { if (accepting) responses.push(presence); } }); }
|
|
55
|
+
catch { return { ok: false, reason: PERSONA_REQUIRED_REASON }; }
|
|
56
|
+
finally { accepting = false; }
|
|
57
|
+
try {
|
|
58
|
+
if (responses.length !== 1 || !validPresence(responses[0]) || responses[0].capabilities.memory !== 1) return { ok: false, reason: PERSONA_REQUIRED_REASON };
|
|
59
|
+
return { ok: true, presence: structuredClone(responses[0]) };
|
|
60
|
+
} catch { return { ok: false, reason: PERSONA_REQUIRED_REASON }; }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Active tool selection is discovery only; this wrapper also guards direct programmatic execution. */
|
|
64
|
+
export function personaGuardedTools(pi: ExtensionAPI, unavailableReason: (ctx: ExtensionContext) => string | undefined): ExtensionAPI {
|
|
65
|
+
const guarded = Object.create(pi) as ExtensionAPI;
|
|
66
|
+
guarded.registerTool = (definition) => pi.registerTool({
|
|
67
|
+
...definition,
|
|
68
|
+
async execute(...args) {
|
|
69
|
+
const reason = unavailableReason(args[4]);
|
|
70
|
+
// Pi converts thrown tool errors to its native error result, also for executeTool().
|
|
71
|
+
if (reason) throw new Error(reason);
|
|
72
|
+
return definition.execute(...args);
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
return guarded;
|
|
76
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { BeforeAgentStartEvent, ContextWithSystemEvent } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
type Message = ContextWithSystemEvent["messages"][number];
|
|
4
|
+
|
|
5
|
+
/** Pi emits the starting trigger before queued nextTurn messages. Its context hook receives clones. */
|
|
6
|
+
export class ReferenceAnchor {
|
|
7
|
+
private readonly role: "user" | "custom";
|
|
8
|
+
private readonly customType: string | undefined;
|
|
9
|
+
private timestamp: number | undefined;
|
|
10
|
+
private occurrences = 0;
|
|
11
|
+
private index = -1;
|
|
12
|
+
private compacted = false;
|
|
13
|
+
|
|
14
|
+
constructor(trigger: BeforeAgentStartEvent) {
|
|
15
|
+
this.role = trigger.messageType;
|
|
16
|
+
this.customType = trigger.messageType === "custom" ? trigger.message.customType : undefined;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
observe(message: Message): void {
|
|
20
|
+
if (this.compacted || message.role !== this.role || (message.role === "custom" && message.customType !== this.customType)) return;
|
|
21
|
+
if (message.role === "user") {
|
|
22
|
+
this.timestamp ??= message.timestamp;
|
|
23
|
+
if (message.timestamp !== this.timestamp) return;
|
|
24
|
+
}
|
|
25
|
+
this.occurrences++;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
afterCompaction(): void { this.compacted = true; }
|
|
29
|
+
|
|
30
|
+
position(messages: readonly Message[]): number {
|
|
31
|
+
if (this.compacted) return messages.findIndex((message) => message.role === "compactionSummary");
|
|
32
|
+
// Pi stamps custom messages again when persisting them. Their run-local ordinal and
|
|
33
|
+
// custom type survive projection; user messages also retain the original timestamp.
|
|
34
|
+
const matches = (message: Message | undefined) => message?.role === this.role
|
|
35
|
+
&& (message.role === "custom" ? message.customType === this.customType : message.timestamp === this.timestamp);
|
|
36
|
+
if (matches(messages[this.index])) return this.index;
|
|
37
|
+
// Count collisions from this run (including identical queued customs) from the tail. An
|
|
38
|
+
// identical prior submission, even in the same millisecond, cannot select older history.
|
|
39
|
+
let remaining = this.occurrences;
|
|
40
|
+
for (let i = messages.length - 1; remaining > 0 && i >= 0; i--) {
|
|
41
|
+
if (matches(messages[i]) && --remaining === 0) {
|
|
42
|
+
this.index = i;
|
|
43
|
+
return i;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return -1;
|
|
47
|
+
}
|
|
48
|
+
}
|