@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.
- package/AGENTS.md +137 -137
- package/CHANGELOG.md +287 -282
- package/LICENSE +24 -24
- package/README.md +1 -1
- package/docs/DESIGN.md +605 -605
- package/docs/MEMORY-RESEARCH.md +163 -163
- package/package.json +11 -2
- package/src/core/auto-optimize.ts +323 -323
- package/src/core/backlog.ts +228 -228
- package/src/core/blocked.ts +38 -38
- package/src/core/capture.ts +155 -155
- 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 -189
- 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 -201
- 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 -565
- 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 -48
- package/src/extension/review-evidence.ts +222 -222
- package/src/extension/worker-memory-anchor.ts +28 -28
- package/src/session-memory.ts +127 -127
- 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 -58
|
@@ -1,79 +1,79 @@
|
|
|
1
|
-
import { randomUUID } from "node:crypto";
|
|
2
|
-
|
|
3
|
-
export const MIND_ACTIVITY_EVENT = "pi-persona:activity:v1";
|
|
4
|
-
|
|
5
|
-
export type MindActivityPhase = "inspect" | "stage" | "apply";
|
|
6
|
-
export type MindActivityState = "running" | "staged" | "done" | "failed";
|
|
7
|
-
export type MindActivityTarget = "project" | "project-long" | "persona" | "shared";
|
|
8
|
-
|
|
9
|
-
export interface MindActivityEvent {
|
|
10
|
-
version: 1;
|
|
11
|
-
producerId: "pi-persona-mind";
|
|
12
|
-
activityId: string;
|
|
13
|
-
sessionId: string;
|
|
14
|
-
phase: MindActivityPhase;
|
|
15
|
-
state: MindActivityState;
|
|
16
|
-
target: MindActivityTarget;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export interface MindActivityRunner {
|
|
20
|
-
run<T>(phase: MindActivityPhase, target: MindActivityTarget, work: () => T | Promise<T>, isSuccess?: (result: T) => boolean): Promise<T>;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export interface MindActivityOptions {
|
|
24
|
-
sessionId: string;
|
|
25
|
-
enabled(): boolean;
|
|
26
|
-
isCurrent(): boolean;
|
|
27
|
-
emit(channel: string, payload: MindActivityEvent): void;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Adapts a real local optimize operation to Persona's public activity protocol. The event deliberately
|
|
32
|
-
* carries no memory contents, model/provider, token counts, file paths, or completion claims beyond
|
|
33
|
-
* the operation's own explicit result.
|
|
34
|
-
*/
|
|
35
|
-
export function createMindActivityRunner(options: MindActivityOptions): MindActivityRunner {
|
|
36
|
-
function publish(event: MindActivityEvent): void {
|
|
37
|
-
try {
|
|
38
|
-
if (!options.sessionId.trim() || !options.enabled() || !options.isCurrent()) return;
|
|
39
|
-
options.emit(MIND_ACTIVITY_EVENT, event);
|
|
40
|
-
} catch {
|
|
41
|
-
// Activity is a best-effort UI projection. A companion listener cannot alter a memory operation.
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
return {
|
|
45
|
-
async run<T>(phase: MindActivityPhase, target: MindActivityTarget, work: () => T | Promise<T>, isSuccess?: (result: T) => boolean): Promise<T> {
|
|
46
|
-
const base = { version: 1 as const, producerId: "pi-persona-mind" as const, activityId: randomUUID(), sessionId: options.sessionId, phase, target };
|
|
47
|
-
publish({ ...base, state: "running" });
|
|
48
|
-
try {
|
|
49
|
-
const result = await work();
|
|
50
|
-
let succeeded = false;
|
|
51
|
-
try { succeeded = (isSuccess ?? defaultSuccess)(result); } catch { /* malformed caller predicate is failure-shaped */ }
|
|
52
|
-
const state: MindActivityState = !succeeded ? "failed" : phase === "stage" ? "staged" : "done";
|
|
53
|
-
publish({ ...base, state });
|
|
54
|
-
return result;
|
|
55
|
-
} catch (error) {
|
|
56
|
-
publish({ ...base, state: "failed" });
|
|
57
|
-
throw error;
|
|
58
|
-
}
|
|
59
|
-
},
|
|
60
|
-
};
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
/** Run normally when no compatible Persona activity runner is available. Entry access is gated elsewhere. */
|
|
64
|
-
export function runMindActivity<T>(
|
|
65
|
-
runner: MindActivityRunner | undefined,
|
|
66
|
-
phase: MindActivityPhase,
|
|
67
|
-
target: MindActivityTarget,
|
|
68
|
-
work: () => T | Promise<T>,
|
|
69
|
-
isSuccess?: (result: T) => boolean,
|
|
70
|
-
): Promise<T> {
|
|
71
|
-
if (runner) return runner.run(phase, target, work, isSuccess);
|
|
72
|
-
try { return Promise.resolve(work()); }
|
|
73
|
-
catch (error) { return Promise.reject(error); }
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
function defaultSuccess<T>(value: T): boolean {
|
|
77
|
-
const result: unknown = value;
|
|
78
|
-
return !result || typeof result !== "object" || !("ok" in result) || result.ok === true;
|
|
79
|
-
}
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
export const MIND_ACTIVITY_EVENT = "pi-persona:activity:v1";
|
|
4
|
+
|
|
5
|
+
export type MindActivityPhase = "inspect" | "stage" | "apply";
|
|
6
|
+
export type MindActivityState = "running" | "staged" | "done" | "failed";
|
|
7
|
+
export type MindActivityTarget = "project" | "project-long" | "persona" | "shared";
|
|
8
|
+
|
|
9
|
+
export interface MindActivityEvent {
|
|
10
|
+
version: 1;
|
|
11
|
+
producerId: "pi-persona-mind";
|
|
12
|
+
activityId: string;
|
|
13
|
+
sessionId: string;
|
|
14
|
+
phase: MindActivityPhase;
|
|
15
|
+
state: MindActivityState;
|
|
16
|
+
target: MindActivityTarget;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface MindActivityRunner {
|
|
20
|
+
run<T>(phase: MindActivityPhase, target: MindActivityTarget, work: () => T | Promise<T>, isSuccess?: (result: T) => boolean): Promise<T>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface MindActivityOptions {
|
|
24
|
+
sessionId: string;
|
|
25
|
+
enabled(): boolean;
|
|
26
|
+
isCurrent(): boolean;
|
|
27
|
+
emit(channel: string, payload: MindActivityEvent): void;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Adapts a real local optimize operation to Persona's public activity protocol. The event deliberately
|
|
32
|
+
* carries no memory contents, model/provider, token counts, file paths, or completion claims beyond
|
|
33
|
+
* the operation's own explicit result.
|
|
34
|
+
*/
|
|
35
|
+
export function createMindActivityRunner(options: MindActivityOptions): MindActivityRunner {
|
|
36
|
+
function publish(event: MindActivityEvent): void {
|
|
37
|
+
try {
|
|
38
|
+
if (!options.sessionId.trim() || !options.enabled() || !options.isCurrent()) return;
|
|
39
|
+
options.emit(MIND_ACTIVITY_EVENT, event);
|
|
40
|
+
} catch {
|
|
41
|
+
// Activity is a best-effort UI projection. A companion listener cannot alter a memory operation.
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
async run<T>(phase: MindActivityPhase, target: MindActivityTarget, work: () => T | Promise<T>, isSuccess?: (result: T) => boolean): Promise<T> {
|
|
46
|
+
const base = { version: 1 as const, producerId: "pi-persona-mind" as const, activityId: randomUUID(), sessionId: options.sessionId, phase, target };
|
|
47
|
+
publish({ ...base, state: "running" });
|
|
48
|
+
try {
|
|
49
|
+
const result = await work();
|
|
50
|
+
let succeeded = false;
|
|
51
|
+
try { succeeded = (isSuccess ?? defaultSuccess)(result); } catch { /* malformed caller predicate is failure-shaped */ }
|
|
52
|
+
const state: MindActivityState = !succeeded ? "failed" : phase === "stage" ? "staged" : "done";
|
|
53
|
+
publish({ ...base, state });
|
|
54
|
+
return result;
|
|
55
|
+
} catch (error) {
|
|
56
|
+
publish({ ...base, state: "failed" });
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Run normally when no compatible Persona activity runner is available. Entry access is gated elsewhere. */
|
|
64
|
+
export function runMindActivity<T>(
|
|
65
|
+
runner: MindActivityRunner | undefined,
|
|
66
|
+
phase: MindActivityPhase,
|
|
67
|
+
target: MindActivityTarget,
|
|
68
|
+
work: () => T | Promise<T>,
|
|
69
|
+
isSuccess?: (result: T) => boolean,
|
|
70
|
+
): Promise<T> {
|
|
71
|
+
if (runner) return runner.run(phase, target, work, isSuccess);
|
|
72
|
+
try { return Promise.resolve(work()); }
|
|
73
|
+
catch (error) { return Promise.reject(error); }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function defaultSuccess<T>(value: T): boolean {
|
|
77
|
+
const result: unknown = value;
|
|
78
|
+
return !result || typeof result !== "object" || !("ok" in result) || result.ok === true;
|
|
79
|
+
}
|
|
@@ -1,143 +1,143 @@
|
|
|
1
|
-
/** Pi lifecycle adapter. The scheduler never wakes the supervisor or owns its conversation. */
|
|
2
|
-
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
-
import type { MindService } from "../core/service.ts";
|
|
4
|
-
import type { Scope } from "../core/scope.ts";
|
|
5
|
-
import type { AutoOptimizeTarget } from "../core/auto-optimize.ts";
|
|
6
|
-
import { AUTO_ATTEMPT_ENTRY, AutoOptimizeScheduler, SHUTDOWN_WORKER_WAIT_MS, type AutoAttempt, type AutoOptimizeReportContext, type ReviewReservation } from "./auto-optimize.ts";
|
|
7
|
-
import { launchMindWorker } from "./mind-worker.ts";
|
|
8
|
-
import { MIND_RESULT_ENTRY_TYPE } from "../ui/mind-result-card.ts";
|
|
9
|
-
|
|
10
|
-
interface Dependencies {
|
|
11
|
-
isDelegatedLeg: boolean;
|
|
12
|
-
available(ctx: ExtensionContext): boolean;
|
|
13
|
-
captureOwner(ctx: ExtensionContext): () => boolean;
|
|
14
|
-
scope(ctx: ExtensionContext): Scope;
|
|
15
|
-
persona(ctx: ExtensionContext): string | null;
|
|
16
|
-
mind(ctx: ExtensionContext): MindService;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
/** Maps successful memory writes to their owned optimizer tier; shared LTM is never automatic. */
|
|
20
|
-
export function autoOptimizeTarget(input: unknown): AutoOptimizeTarget | undefined {
|
|
21
|
-
if (!input || typeof input !== "object" || Array.isArray(input)) return undefined;
|
|
22
|
-
const value = input as Record<string, unknown>;
|
|
23
|
-
const scope = value.scope;
|
|
24
|
-
if (scope !== undefined && scope !== "project" && scope !== "persona" && scope !== "shared") return undefined;
|
|
25
|
-
if (value.action === "remember") {
|
|
26
|
-
if (value.term === "short") return scope === undefined || scope === "project" ? "project" : undefined;
|
|
27
|
-
if (value.term !== "long" || scope === undefined || scope === "shared") return undefined;
|
|
28
|
-
return scope === "project" ? "project-long" : "persona";
|
|
29
|
-
}
|
|
30
|
-
if (value.action === "promote") {
|
|
31
|
-
if (scope === "shared") return undefined;
|
|
32
|
-
return scope === "persona" ? "persona" : "project-long";
|
|
33
|
-
}
|
|
34
|
-
return undefined;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export interface AutoOptimizeSession {
|
|
38
|
-
activate(ctx: ExtensionContext, resetPreference?: boolean): void;
|
|
39
|
-
revoke(): void;
|
|
40
|
-
memoryAdded(ctx: ExtensionContext, target: AutoOptimizeTarget): void;
|
|
41
|
-
status(): string;
|
|
42
|
-
setEnabled(enabled: boolean): void;
|
|
43
|
-
targets(): readonly AutoOptimizeTarget[];
|
|
44
|
-
startExplicit(target?: AutoOptimizeTarget): boolean;
|
|
45
|
-
reserveReview(target: AutoOptimizeTarget): ReviewReservation | undefined;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
export function installAutoOptimize(pi: ExtensionAPI, deps: Dependencies): AutoOptimizeSession {
|
|
49
|
-
const scheduler = new AutoOptimizeScheduler();
|
|
50
|
-
let boundKey: string | undefined;
|
|
51
|
-
let boundContext: ExtensionContext | undefined;
|
|
52
|
-
const tokenEvents = new Set<string>();
|
|
53
|
-
const safeAvailable = (ctx: ExtensionContext): boolean => {
|
|
54
|
-
try { return !deps.isDelegatedLeg && ctx.hasUI && ctx.mode !== "print" && deps.available(ctx); }
|
|
55
|
-
catch { return false; }
|
|
56
|
-
};
|
|
57
|
-
const revoke = (): void => { boundKey = undefined; boundContext = undefined; tokenEvents.clear(); scheduler.stop(); };
|
|
58
|
-
const activate = (ctx: ExtensionContext, resetPreference = false): void => {
|
|
59
|
-
if (!safeAvailable(ctx)) { revoke(); return; }
|
|
60
|
-
const scope = deps.scope(ctx);
|
|
61
|
-
// Automatic project maintenance never creates home-directory stores.
|
|
62
|
-
const key = JSON.stringify([ctx.sessionManager.getSessionId(), ctx.sessionManager.getSessionFile(), scope.persona, scope.paths]);
|
|
63
|
-
if (!resetPreference && boundKey === key && boundContext?.sessionManager === ctx.sessionManager) return;
|
|
64
|
-
boundKey = key; boundContext = ctx; tokenEvents.clear();
|
|
65
|
-
const captured = deps.captureOwner(ctx);
|
|
66
|
-
const current = () => boundKey === key && boundContext?.sessionManager === ctx.sessionManager && safeAvailable(ctx) && captured();
|
|
67
|
-
const attempts: AutoAttempt[] = [];
|
|
68
|
-
for (const entry of ctx.sessionManager.getBranch()) {
|
|
69
|
-
if (entry.type !== "custom" || entry.customType !== AUTO_ATTEMPT_ENTRY || !entry.data || typeof entry.data !== "object") continue;
|
|
70
|
-
const data = entry.data as Record<string, unknown>;
|
|
71
|
-
if (data.version === 1 && data.owner === key && typeof data.digest === "string" && /^[a-f0-9]{64}$/.test(data.digest) && typeof data.at === "number" && Number.isFinite(data.at) && data.at >= 0 && data.at <= Date.now() && (data.state === "started" || data.state === "settled")) {
|
|
72
|
-
const target = data.target === "project" || data.target === "project-long" || data.target === "persona" ? data.target : undefined;
|
|
73
|
-
attempts.push({ digest: data.digest, at: data.at, state: data.state, ...(target ? { target } : {}), ...(data.explicit === true ? { explicit: true } : {}) });
|
|
74
|
-
if (attempts.length > 64) attempts.shift();
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
const owner = {
|
|
78
|
-
key, persona: scope.persona, current,
|
|
79
|
-
allowedTargets: scope.homeWorkspace ? ["persona"] as const : ["project", "project-long", "persona"] as const,
|
|
80
|
-
idle: () => ctx.isIdle() && !ctx.hasPendingMessages(),
|
|
81
|
-
optimizer: () => deps.mind(ctx).createOptimizer(),
|
|
82
|
-
launch: (task: string) => launchMindWorker(pi, ctx.sessionManager.getSessionId(), deps.persona(ctx), task),
|
|
83
|
-
recordAttempt: (attempt: AutoAttempt) => { if (!current()) throw new Error("automatic memory owner changed"); pi.appendEntry(AUTO_ATTEMPT_ENTRY, { version: 1, owner: key, ...attempt }); },
|
|
84
|
-
report: (title: string, body: string, reportContext?: AutoOptimizeReportContext) => {
|
|
85
|
-
if (!current()) throw new Error("automatic memory owner changed");
|
|
86
|
-
if (reportContext?.automatic && reportContext.phase === "proposal") {
|
|
87
|
-
pi.appendEntry("pi-persona-mind-auto-proposal", { title, content: body });
|
|
88
|
-
return;
|
|
89
|
-
}
|
|
90
|
-
if (reportContext?.automatic && !reportContext.attention) {
|
|
91
|
-
ctx.ui.notify(`mind · ${reportContext.target} · ${reportContext.summary}`, "info");
|
|
92
|
-
return;
|
|
93
|
-
}
|
|
94
|
-
pi.appendEntry(MIND_RESULT_ENTRY_TYPE, { title, content: body, ...(reportContext?.automatic ? { reportContext } : {}) });
|
|
95
|
-
if (reportContext?.automatic) {
|
|
96
|
-
if (reportContext.attention) ctx.ui.notify(`mind · ${reportContext.target} review needs attention`, "warning");
|
|
97
|
-
return;
|
|
98
|
-
}
|
|
99
|
-
if (title !== "Mind automatic proposal") {
|
|
100
|
-
const target = / — (project(?:-long)?|persona)$/.exec(title)?.[1];
|
|
101
|
-
const kind = title.includes("proposal") ? "proposal" : "review";
|
|
102
|
-
ctx.ui.notify(`mind · ${target ? `${target} ` : ""}${kind} update`, "info");
|
|
103
|
-
}
|
|
104
|
-
}, attempts,
|
|
105
|
-
};
|
|
106
|
-
if (resetPreference) scheduler.activate(owner, process.env.PI_PERSONA_MIND_OPTIMIZE !== "off");
|
|
107
|
-
else scheduler.activate(owner);
|
|
108
|
-
};
|
|
109
|
-
const memoryAdded = (ctx: ExtensionContext, target: AutoOptimizeTarget): void => {
|
|
110
|
-
if (!safeAvailable(ctx)) return;
|
|
111
|
-
activate(ctx);
|
|
112
|
-
if ((target === "persona") || !deps.scope(ctx).homeWorkspace) scheduler.memoryAdded(target);
|
|
113
|
-
};
|
|
114
|
-
pi.on("input", () => { scheduler.interrupt(); });
|
|
115
|
-
pi.on("agent_start", () => { scheduler.interrupt(); });
|
|
116
|
-
pi.on("model_select", () => { scheduler.interrupt(); });
|
|
117
|
-
// Native /tree preserves the session manager/id/file but revokes work accepted on its old branch.
|
|
118
|
-
pi.on("session_tree", () => { scheduler.interrupt(); });
|
|
119
|
-
pi.on("ui_prompt_start", () => { scheduler.interrupt(); });
|
|
120
|
-
pi.on("turn_end", (event, ctx) => {
|
|
121
|
-
if (!safeAvailable(ctx) || event.message.role !== "assistant" || tokenEvents.has(event.messageEntryId)) return;
|
|
122
|
-
activate(ctx);
|
|
123
|
-
tokenEvents.add(event.messageEntryId);
|
|
124
|
-
while (tokenEvents.size > 256) tokenEvents.delete(tokenEvents.values().next().value!);
|
|
125
|
-
const usage = event.message.usage;
|
|
126
|
-
scheduler.tokensUsed(Math.max(0, usage.input));
|
|
127
|
-
});
|
|
128
|
-
pi.on("tool_result", (event, ctx) => {
|
|
129
|
-
if (event.toolName !== "memory" || event.isError || !event.details || typeof event.details !== "object" || (event.details as { ok?: unknown }).ok !== true) return;
|
|
130
|
-
const target = autoOptimizeTarget(event.input);
|
|
131
|
-
if (target) memoryAdded(ctx, target);
|
|
132
|
-
});
|
|
133
|
-
pi.on("agent_settled", (event, ctx) => { if (!event.aborted && safeAvailable(ctx)) { activate(ctx); scheduler.settled(); } });
|
|
134
|
-
// Bounded because Mind cannot rely on Persona's shutdown handler running first to force-settle the worker.
|
|
135
|
-
pi.on("session_shutdown", async () => { revoke(); await scheduler.join(SHUTDOWN_WORKER_WAIT_MS); });
|
|
136
|
-
return { activate, revoke, memoryAdded,
|
|
137
|
-
status: () => boundContext ? scheduler.status() : "inactive · automatic work requires an interactive Persona session",
|
|
138
|
-
setEnabled: (enabled) => scheduler.setEnabled(enabled),
|
|
139
|
-
targets: () => scheduler.targets(),
|
|
140
|
-
startExplicit: (target) => scheduler.startExplicit(target),
|
|
141
|
-
reserveReview: (target) => scheduler.reserveReview(target),
|
|
142
|
-
};
|
|
143
|
-
}
|
|
1
|
+
/** Pi lifecycle adapter. The scheduler never wakes the supervisor or owns its conversation. */
|
|
2
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import type { MindService } from "../core/service.ts";
|
|
4
|
+
import type { Scope } from "../core/scope.ts";
|
|
5
|
+
import type { AutoOptimizeTarget } from "../core/auto-optimize.ts";
|
|
6
|
+
import { AUTO_ATTEMPT_ENTRY, AutoOptimizeScheduler, SHUTDOWN_WORKER_WAIT_MS, type AutoAttempt, type AutoOptimizeReportContext, type ReviewReservation } from "./auto-optimize.ts";
|
|
7
|
+
import { launchMindWorker } from "./mind-worker.ts";
|
|
8
|
+
import { MIND_RESULT_ENTRY_TYPE } from "../ui/mind-result-card.ts";
|
|
9
|
+
|
|
10
|
+
interface Dependencies {
|
|
11
|
+
isDelegatedLeg: boolean;
|
|
12
|
+
available(ctx: ExtensionContext): boolean;
|
|
13
|
+
captureOwner(ctx: ExtensionContext): () => boolean;
|
|
14
|
+
scope(ctx: ExtensionContext): Scope;
|
|
15
|
+
persona(ctx: ExtensionContext): string | null;
|
|
16
|
+
mind(ctx: ExtensionContext): MindService;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Maps successful memory writes to their owned optimizer tier; shared LTM is never automatic. */
|
|
20
|
+
export function autoOptimizeTarget(input: unknown): AutoOptimizeTarget | undefined {
|
|
21
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) return undefined;
|
|
22
|
+
const value = input as Record<string, unknown>;
|
|
23
|
+
const scope = value.scope;
|
|
24
|
+
if (scope !== undefined && scope !== "project" && scope !== "persona" && scope !== "shared") return undefined;
|
|
25
|
+
if (value.action === "remember") {
|
|
26
|
+
if (value.term === "short") return scope === undefined || scope === "project" ? "project" : undefined;
|
|
27
|
+
if (value.term !== "long" || scope === undefined || scope === "shared") return undefined;
|
|
28
|
+
return scope === "project" ? "project-long" : "persona";
|
|
29
|
+
}
|
|
30
|
+
if (value.action === "promote") {
|
|
31
|
+
if (scope === "shared") return undefined;
|
|
32
|
+
return scope === "persona" ? "persona" : "project-long";
|
|
33
|
+
}
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface AutoOptimizeSession {
|
|
38
|
+
activate(ctx: ExtensionContext, resetPreference?: boolean): void;
|
|
39
|
+
revoke(): void;
|
|
40
|
+
memoryAdded(ctx: ExtensionContext, target: AutoOptimizeTarget): void;
|
|
41
|
+
status(): string;
|
|
42
|
+
setEnabled(enabled: boolean): void;
|
|
43
|
+
targets(): readonly AutoOptimizeTarget[];
|
|
44
|
+
startExplicit(target?: AutoOptimizeTarget): boolean;
|
|
45
|
+
reserveReview(target: AutoOptimizeTarget): ReviewReservation | undefined;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function installAutoOptimize(pi: ExtensionAPI, deps: Dependencies): AutoOptimizeSession {
|
|
49
|
+
const scheduler = new AutoOptimizeScheduler();
|
|
50
|
+
let boundKey: string | undefined;
|
|
51
|
+
let boundContext: ExtensionContext | undefined;
|
|
52
|
+
const tokenEvents = new Set<string>();
|
|
53
|
+
const safeAvailable = (ctx: ExtensionContext): boolean => {
|
|
54
|
+
try { return !deps.isDelegatedLeg && ctx.hasUI && ctx.mode !== "print" && deps.available(ctx); }
|
|
55
|
+
catch { return false; }
|
|
56
|
+
};
|
|
57
|
+
const revoke = (): void => { boundKey = undefined; boundContext = undefined; tokenEvents.clear(); scheduler.stop(); };
|
|
58
|
+
const activate = (ctx: ExtensionContext, resetPreference = false): void => {
|
|
59
|
+
if (!safeAvailable(ctx)) { revoke(); return; }
|
|
60
|
+
const scope = deps.scope(ctx);
|
|
61
|
+
// Automatic project maintenance never creates home-directory stores.
|
|
62
|
+
const key = JSON.stringify([ctx.sessionManager.getSessionId(), ctx.sessionManager.getSessionFile(), scope.persona, scope.paths]);
|
|
63
|
+
if (!resetPreference && boundKey === key && boundContext?.sessionManager === ctx.sessionManager) return;
|
|
64
|
+
boundKey = key; boundContext = ctx; tokenEvents.clear();
|
|
65
|
+
const captured = deps.captureOwner(ctx);
|
|
66
|
+
const current = () => boundKey === key && boundContext?.sessionManager === ctx.sessionManager && safeAvailable(ctx) && captured();
|
|
67
|
+
const attempts: AutoAttempt[] = [];
|
|
68
|
+
for (const entry of ctx.sessionManager.getBranch()) {
|
|
69
|
+
if (entry.type !== "custom" || entry.customType !== AUTO_ATTEMPT_ENTRY || !entry.data || typeof entry.data !== "object") continue;
|
|
70
|
+
const data = entry.data as Record<string, unknown>;
|
|
71
|
+
if (data.version === 1 && data.owner === key && typeof data.digest === "string" && /^[a-f0-9]{64}$/.test(data.digest) && typeof data.at === "number" && Number.isFinite(data.at) && data.at >= 0 && data.at <= Date.now() && (data.state === "started" || data.state === "settled")) {
|
|
72
|
+
const target = data.target === "project" || data.target === "project-long" || data.target === "persona" ? data.target : undefined;
|
|
73
|
+
attempts.push({ digest: data.digest, at: data.at, state: data.state, ...(target ? { target } : {}), ...(data.explicit === true ? { explicit: true } : {}) });
|
|
74
|
+
if (attempts.length > 64) attempts.shift();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const owner = {
|
|
78
|
+
key, persona: scope.persona, current,
|
|
79
|
+
allowedTargets: scope.homeWorkspace ? ["persona"] as const : ["project", "project-long", "persona"] as const,
|
|
80
|
+
idle: () => ctx.isIdle() && !ctx.hasPendingMessages(),
|
|
81
|
+
optimizer: () => deps.mind(ctx).createOptimizer(),
|
|
82
|
+
launch: (task: string) => launchMindWorker(pi, ctx.sessionManager.getSessionId(), deps.persona(ctx), task),
|
|
83
|
+
recordAttempt: (attempt: AutoAttempt) => { if (!current()) throw new Error("automatic memory owner changed"); pi.appendEntry(AUTO_ATTEMPT_ENTRY, { version: 1, owner: key, ...attempt }); },
|
|
84
|
+
report: (title: string, body: string, reportContext?: AutoOptimizeReportContext) => {
|
|
85
|
+
if (!current()) throw new Error("automatic memory owner changed");
|
|
86
|
+
if (reportContext?.automatic && reportContext.phase === "proposal") {
|
|
87
|
+
pi.appendEntry("pi-persona-mind-auto-proposal", { title, content: body });
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
if (reportContext?.automatic && !reportContext.attention) {
|
|
91
|
+
ctx.ui.notify(`mind · ${reportContext.target} · ${reportContext.summary}`, "info");
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
pi.appendEntry(MIND_RESULT_ENTRY_TYPE, { title, content: body, ...(reportContext?.automatic ? { reportContext } : {}) });
|
|
95
|
+
if (reportContext?.automatic) {
|
|
96
|
+
if (reportContext.attention) ctx.ui.notify(`mind · ${reportContext.target} review needs attention`, "warning");
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
if (title !== "Mind automatic proposal") {
|
|
100
|
+
const target = / — (project(?:-long)?|persona)$/.exec(title)?.[1];
|
|
101
|
+
const kind = title.includes("proposal") ? "proposal" : "review";
|
|
102
|
+
ctx.ui.notify(`mind · ${target ? `${target} ` : ""}${kind} update`, "info");
|
|
103
|
+
}
|
|
104
|
+
}, attempts,
|
|
105
|
+
};
|
|
106
|
+
if (resetPreference) scheduler.activate(owner, process.env.PI_PERSONA_MIND_OPTIMIZE !== "off");
|
|
107
|
+
else scheduler.activate(owner);
|
|
108
|
+
};
|
|
109
|
+
const memoryAdded = (ctx: ExtensionContext, target: AutoOptimizeTarget): void => {
|
|
110
|
+
if (!safeAvailable(ctx)) return;
|
|
111
|
+
activate(ctx);
|
|
112
|
+
if ((target === "persona") || !deps.scope(ctx).homeWorkspace) scheduler.memoryAdded(target);
|
|
113
|
+
};
|
|
114
|
+
pi.on("input", () => { scheduler.interrupt(); });
|
|
115
|
+
pi.on("agent_start", () => { scheduler.interrupt(); });
|
|
116
|
+
pi.on("model_select", () => { scheduler.interrupt(); });
|
|
117
|
+
// Native /tree preserves the session manager/id/file but revokes work accepted on its old branch.
|
|
118
|
+
pi.on("session_tree", () => { scheduler.interrupt(); });
|
|
119
|
+
pi.on("ui_prompt_start", () => { scheduler.interrupt(); });
|
|
120
|
+
pi.on("turn_end", (event, ctx) => {
|
|
121
|
+
if (!safeAvailable(ctx) || event.message.role !== "assistant" || tokenEvents.has(event.messageEntryId)) return;
|
|
122
|
+
activate(ctx);
|
|
123
|
+
tokenEvents.add(event.messageEntryId);
|
|
124
|
+
while (tokenEvents.size > 256) tokenEvents.delete(tokenEvents.values().next().value!);
|
|
125
|
+
const usage = event.message.usage;
|
|
126
|
+
scheduler.tokensUsed(Math.max(0, usage.input));
|
|
127
|
+
});
|
|
128
|
+
pi.on("tool_result", (event, ctx) => {
|
|
129
|
+
if (event.toolName !== "memory" || event.isError || !event.details || typeof event.details !== "object" || (event.details as { ok?: unknown }).ok !== true) return;
|
|
130
|
+
const target = autoOptimizeTarget(event.input);
|
|
131
|
+
if (target) memoryAdded(ctx, target);
|
|
132
|
+
});
|
|
133
|
+
pi.on("agent_settled", (event, ctx) => { if (!event.aborted && safeAvailable(ctx)) { activate(ctx); scheduler.settled(); } });
|
|
134
|
+
// Bounded because Mind cannot rely on Persona's shutdown handler running first to force-settle the worker.
|
|
135
|
+
pi.on("session_shutdown", async () => { revoke(); await scheduler.join(SHUTDOWN_WORKER_WAIT_MS); });
|
|
136
|
+
return { activate, revoke, memoryAdded,
|
|
137
|
+
status: () => boundContext ? scheduler.status() : "inactive · automatic work requires an interactive Persona session",
|
|
138
|
+
setEnabled: (enabled) => scheduler.setEnabled(enabled),
|
|
139
|
+
targets: () => scheduler.targets(),
|
|
140
|
+
startExplicit: (target) => scheduler.startExplicit(target),
|
|
141
|
+
reserveReview: (target) => scheduler.reserveReview(target),
|
|
142
|
+
};
|
|
143
|
+
}
|