@agimon-ai/po-profile 0.0.0-alpha.41 → 0.0.0-alpha.43

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/README.md CHANGED
@@ -70,6 +70,17 @@ that same file. Directory and persona-file symlinks cannot escape those boundari
70
70
  shipped [profiles contract](./src/prompts/help-how-to-profile/references/profiles-contract.md) for
71
71
  the full configuration model and verification steps.
72
72
 
73
+ ## Memory
74
+
75
+ Each profile has one long-term memory, shared across repositories and keyed by the exact profile
76
+ name. It is stored in SQLite (FTS5) at `<po home>/profile-memory/memory.sqlite` and is reached on
77
+ demand through the `memory` code-mode namespace (`search`, `list`, `read`, `write`, `forget`);
78
+ nothing is added to the system prompt. With no profile selected, `memory` calls fail with "No profile
79
+ is selected". The pinned `codemode-how-to-memory` skill teaches agents when to use it.
80
+
81
+ Set `profileMemory.automatic: true` in the user-global `config.yaml` to let Po extract entries from
82
+ finished turns (off by default; extraction runs locally after the session settles).
83
+
73
84
  ## Help
74
85
 
75
86
  The package registers `help-how-to-profile` with the session's `po/help` Cordis service. Its
@@ -2,13 +2,293 @@ Object.defineProperties(exports, {
2
2
  __esModule: { value: true },
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
- const require_profileText = require("../profileText-eSDL6Q5R.cjs");
5
+ //#region \0rolldown/runtime.js
6
+ var __create = Object.create;
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
+ key = keys[i];
15
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
+ get: ((k) => from[k]).bind(null, key),
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+ //#endregion
27
+ const require_profileText = require("../profileText-CZ1vgSFT.cjs");
6
28
  let _agimon_ai_po_config_profiles = require("@agimon-ai/po-config/profiles");
7
29
  let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
8
30
  let _agimon_ai_po_core_extensionFile = require("@agimon-ai/po-core/extensionFile");
31
+ let node_path = require("node:path");
32
+ node_path = __toESM(node_path, 1);
33
+ let _agimon_ai_po_core_piSettings = require("@agimon-ai/po-core/piSettings");
9
34
  let _agimon_ai_po_core_platform = require("@agimon-ai/po-core/platform");
35
+ let _agimon_ai_po_core_codemode = require("@agimon-ai/po-core/codemode");
10
36
  let _agimon_ai_po_core_headless = require("@agimon-ai/po-core/headless");
11
37
  let _agimon_ai_po_core_profileIdentity = require("@agimon-ai/po-core/profileIdentity");
38
+ let _agimon_ai_po_config = require("@agimon-ai/po-config");
39
+ //#region src/constants/profileMemory.ts
40
+ const PROFILE_MEMORY_STORE_SERVICE = "po/profile-memory-store";
41
+ const PROFILE_MEMORY_NAMESPACE_SOURCE = "@agimon-ai/po-profile/memory";
42
+ const PROFILE_MEMORY_DIRECTORY = "profile-memory";
43
+ const PROFILE_MEMORY_FILE = "memory.sqlite";
44
+ const MEMORY_BODY_MAX = 16384;
45
+ const EXTRACTION_TIMEOUT_MS = 6e4;
46
+ const EXTRACTION_MAX_TOKENS = 2048;
47
+ const EXTRACTION_STATUS_SOURCE = "profile-memory";
48
+ const EXTRACTION_SYSTEM_PROMPT = "You maintain long-term memory about how one person likes to work. From the conversation, extract at most one durable fact: a stable preference, convention, or decision the person stated or clearly showed. Ignore task progress, code details, and anything derivable from a repository. Never include secrets. Reply with JSON only: {\"title\": string, \"body\": string}. Use an empty body when nothing is worth keeping.";
49
+ //#endregion
50
+ //#region src/services/profileMemoryStore/index.ts
51
+ /** Append only: a database at version N applies MIGRATIONS[N..]. */
52
+ const MIGRATIONS = [`
53
+ CREATE TABLE profile_memory_entries (
54
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
55
+ id TEXT NOT NULL UNIQUE,
56
+ profile TEXT NOT NULL,
57
+ title TEXT NOT NULL,
58
+ body TEXT NOT NULL,
59
+ revision INTEGER NOT NULL,
60
+ origin TEXT NOT NULL CHECK (origin IN ('manual', 'extracted')),
61
+ source_key TEXT,
62
+ created_at INTEGER NOT NULL,
63
+ updated_at INTEGER NOT NULL
64
+ );
65
+ CREATE INDEX profile_memory_entries_recent ON profile_memory_entries(profile, updated_at DESC, seq DESC);
66
+ CREATE UNIQUE INDEX profile_memory_entries_source ON profile_memory_entries(profile, source_key)
67
+ WHERE origin = 'extracted';
68
+ CREATE VIRTUAL TABLE profile_memory_fts USING fts5(
69
+ title, body, content='profile_memory_entries', content_rowid='seq'
70
+ );
71
+ CREATE TRIGGER profile_memory_ai AFTER INSERT ON profile_memory_entries BEGIN
72
+ INSERT INTO profile_memory_fts(rowid, title, body) VALUES (new.seq, new.title, new.body);
73
+ END;
74
+ CREATE TRIGGER profile_memory_ad AFTER DELETE ON profile_memory_entries BEGIN
75
+ INSERT INTO profile_memory_fts(profile_memory_fts, rowid, title, body)
76
+ VALUES ('delete', old.seq, old.title, old.body);
77
+ END;
78
+ CREATE TRIGGER profile_memory_au AFTER UPDATE ON profile_memory_entries BEGIN
79
+ INSERT INTO profile_memory_fts(profile_memory_fts, rowid, title, body)
80
+ VALUES ('delete', old.seq, old.title, old.body);
81
+ INSERT INTO profile_memory_fts(rowid, title, body) VALUES (new.seq, new.title, new.body);
82
+ END;
83
+ CREATE TABLE profile_memory_sources (
84
+ profile TEXT NOT NULL,
85
+ source_key TEXT NOT NULL,
86
+ cursor TEXT NOT NULL,
87
+ last_run_at INTEGER NOT NULL,
88
+ suppressed INTEGER NOT NULL DEFAULT 0,
89
+ PRIMARY KEY (profile, source_key)
90
+ );
91
+ CREATE TABLE profile_memory_epochs (profile TEXT PRIMARY KEY, epoch INTEGER NOT NULL);
92
+ `];
93
+ const HIT_COLUMNS = "e.seq, e.id, e.title, substr(e.body, 1, ?) AS excerpt, e.revision, e.origin, e.updated_at";
94
+ function requireText(value, name, max) {
95
+ if (typeof value !== "string" || !value.trim()) throw new Error(`Memory ${name} must be a non-empty string`);
96
+ if (value.length > max) throw new Error(`Memory ${name} must be at most ${max} characters`);
97
+ return value;
98
+ }
99
+ function requireProfile(profile) {
100
+ if (typeof profile !== "string" || !profile) throw new Error("Memory profile must be a non-empty string");
101
+ }
102
+ function clampLimit(limit) {
103
+ if (limit === void 0) return 10;
104
+ if (!Number.isInteger(limit) || limit < 1) throw new Error("Memory limit must be a positive integer");
105
+ return Math.min(limit, 50);
106
+ }
107
+ /** Quoted word tokens only, so FTS operators (`"`, `*`, `NEAR`, `OR`) in user text stay literal. */
108
+ function ftsQuery(query) {
109
+ const tokens = query.match(/[\p{L}\p{N}_]+/gu);
110
+ return tokens ? tokens.map((token) => `"${token}"`).join(" ") : void 0;
111
+ }
112
+ function toHit(row) {
113
+ return {
114
+ id: row.id,
115
+ title: row.title,
116
+ excerpt: row.excerpt,
117
+ revision: row.revision,
118
+ origin: row.origin,
119
+ updatedAt: row.updated_at
120
+ };
121
+ }
122
+ function toEntry(row) {
123
+ return {
124
+ id: row.id,
125
+ title: row.title,
126
+ body: row.body,
127
+ revision: row.revision,
128
+ origin: row.origin,
129
+ createdAt: row.created_at,
130
+ updatedAt: row.updated_at
131
+ };
132
+ }
133
+ async function migrate(db) {
134
+ await db.transaction(async (tx) => {
135
+ await tx.exec("CREATE TABLE IF NOT EXISTS profile_memory_meta (version INTEGER NOT NULL)");
136
+ const current = await tx.get("SELECT version FROM profile_memory_meta");
137
+ if (!current) await tx.run("INSERT INTO profile_memory_meta (version) VALUES (0)");
138
+ const version = current?.version ?? 0;
139
+ if (version > MIGRATIONS.length) throw new Error("Profile memory database is newer than this Po version");
140
+ for (let index = version; index < MIGRATIONS.length; index++) await tx.exec(MIGRATIONS[index]);
141
+ await tx.run("UPDATE profile_memory_meta SET version = ?", MIGRATIONS.length);
142
+ });
143
+ }
144
+ /**
145
+ * Creates the memory directory owner-only, like `mkdirSync(directory, { recursive: true, mode: 0o700 })`.
146
+ * Same behaviour as po-session's `ensurePrivateDirectory`, which is not exported; existing directories keep their mode.
147
+ */
148
+ async function ensurePrivateDirectory(options) {
149
+ const missing = [];
150
+ for (let current = node_path.default.resolve(options.directory); !(0, _agimon_ai_po_core_platform.getOrThrow)(await options.fs.exists(current, options.context));) {
151
+ missing.unshift(current);
152
+ const parent = node_path.default.dirname(current);
153
+ if (parent === current) break;
154
+ current = parent;
155
+ }
156
+ if (missing.length === 0) return;
157
+ (0, _agimon_ai_po_core_platform.getOrThrow)(await options.fs.createDir(options.directory, { recursive: true }, options.context));
158
+ for (const created of missing) await _agimon_ai_po_core_platform.nodeHost.setMode(created, 448);
159
+ }
160
+ async function createProfileMemoryStore(options) {
161
+ const now = options.now ?? Date.now;
162
+ const newId = options.id ?? (() => crypto.randomUUID());
163
+ await ensurePrivateDirectory(options);
164
+ const file = (0, _agimon_ai_po_core_platform.getOrThrow)(await options.fs.joinPath([options.directory, PROFILE_MEMORY_FILE], options.context));
165
+ const db = await options.sqlite.open(file, options.context);
166
+ try {
167
+ await migrate(db);
168
+ } catch (error) {
169
+ await db.close();
170
+ throw error;
171
+ }
172
+ const findRow = (tx, profile, id) => tx.get("SELECT * FROM profile_memory_entries WHERE profile = ? AND id = ?", profile, id);
173
+ const epochOf = async (tx, profile) => (await tx.get("SELECT epoch FROM profile_memory_epochs WHERE profile = ?", profile))?.epoch ?? 0;
174
+ const suppress = (tx, profile, sourceKey) => tx.run("UPDATE profile_memory_sources SET suppressed = 1 WHERE profile = ? AND source_key = ?", profile, sourceKey);
175
+ const checkRevision = (row, expected) => {
176
+ if (!row) throw new Error("Memory not found");
177
+ if (expected !== void 0 && row.revision !== expected) throw new Error("Memory changed since it was read");
178
+ return row;
179
+ };
180
+ return {
181
+ async search(profile, query, limit) {
182
+ requireProfile(profile);
183
+ requireText(query, "query", 512);
184
+ const match = ftsQuery(query);
185
+ if (!match) return [];
186
+ return (await db.all(`SELECT ${HIT_COLUMNS} FROM profile_memory_fts f JOIN profile_memory_entries e ON e.seq = f.rowid
187
+ WHERE profile_memory_fts MATCH ? AND e.profile = ?
188
+ ORDER BY bm25(profile_memory_fts), e.seq DESC LIMIT ?`, 512, match, profile, clampLimit(limit))).map(toHit);
189
+ },
190
+ async list(profile, listOptions = {}) {
191
+ requireProfile(profile);
192
+ const limit = clampLimit(listOptions.limit);
193
+ let at = null;
194
+ let seq = null;
195
+ if (listOptions.cursor !== void 0) {
196
+ const match = /^(\d+)\.(\d+)$/.exec(listOptions.cursor);
197
+ if (!match) throw new Error("Invalid memory cursor");
198
+ at = Number(match[1]);
199
+ seq = Number(match[2]);
200
+ }
201
+ const rows = await db.all(`SELECT ${HIT_COLUMNS} FROM profile_memory_entries e
202
+ WHERE e.profile = ? AND (? IS NULL OR e.updated_at < ? OR (e.updated_at = ? AND e.seq < ?))
203
+ ORDER BY e.updated_at DESC, e.seq DESC LIMIT ?`, 512, profile, at, at, at, seq, limit + 1);
204
+ const page = rows.slice(0, limit);
205
+ const last = page[page.length - 1];
206
+ return {
207
+ entries: page.map(toHit),
208
+ ...rows.length > limit && last ? { nextCursor: `${last.updated_at}.${last.seq}` } : {}
209
+ };
210
+ },
211
+ async read(profile, id) {
212
+ requireProfile(profile);
213
+ const row = await db.get("SELECT * FROM profile_memory_entries WHERE profile = ? AND id = ?", profile, id);
214
+ return row && toEntry(row);
215
+ },
216
+ async write(profile, input) {
217
+ requireProfile(profile);
218
+ const title = requireText(input.title, "title", 256);
219
+ const body = requireText(input.body, "body", MEMORY_BODY_MAX);
220
+ return db.transaction(async (tx) => {
221
+ const at = now();
222
+ if (input.id === void 0) {
223
+ const id = newId();
224
+ await tx.run(`INSERT INTO profile_memory_entries (id, profile, title, body, revision, origin, created_at, updated_at)
225
+ VALUES (?, ?, ?, ?, 1, 'manual', ?, ?)`, id, profile, title, body, at, at);
226
+ return toEntry(await findRow(tx, profile, id));
227
+ }
228
+ const row = checkRevision(await findRow(tx, profile, input.id), input.expectedRevision);
229
+ if (row.origin === "extracted" && row.source_key !== null) await suppress(tx, profile, row.source_key);
230
+ await tx.run(`UPDATE profile_memory_entries
231
+ SET title = ?, body = ?, revision = revision + 1, origin = 'manual', source_key = NULL, updated_at = ?
232
+ WHERE profile = ? AND id = ?`, title, body, at, profile, input.id);
233
+ return toEntry(await findRow(tx, profile, input.id));
234
+ });
235
+ },
236
+ async forget(profile, id, expectedRevision) {
237
+ requireProfile(profile);
238
+ await db.transaction(async (tx) => {
239
+ const row = checkRevision(await findRow(tx, profile, id), expectedRevision);
240
+ await tx.run("DELETE FROM profile_memory_entries WHERE profile = ? AND id = ?", profile, id);
241
+ await tx.run(`INSERT INTO profile_memory_epochs (profile, epoch) VALUES (?, 1)
242
+ ON CONFLICT(profile) DO UPDATE SET epoch = epoch + 1`, profile);
243
+ if (row.origin === "extracted" && row.source_key !== null) await suppress(tx, profile, row.source_key);
244
+ });
245
+ },
246
+ async epoch(profile) {
247
+ return (await db.get("SELECT epoch FROM profile_memory_epochs WHERE profile = ?", profile))?.epoch ?? 0;
248
+ },
249
+ async readSource(profile, sourceKey) {
250
+ const row = await db.get("SELECT cursor, last_run_at, suppressed FROM profile_memory_sources WHERE profile = ? AND source_key = ?", profile, sourceKey);
251
+ return row && {
252
+ cursor: row.cursor,
253
+ lastRunAt: row.last_run_at,
254
+ suppressed: row.suppressed === 1
255
+ };
256
+ },
257
+ async initSource(profile, sourceKey, cursor) {
258
+ return db.transaction(async (tx) => {
259
+ if (await tx.get("SELECT cursor FROM profile_memory_sources WHERE profile = ? AND source_key = ?", profile, sourceKey)) return false;
260
+ await tx.run("INSERT INTO profile_memory_sources (profile, source_key, cursor, last_run_at) VALUES (?, ?, ?, ?)", profile, sourceKey, cursor, now());
261
+ return true;
262
+ });
263
+ },
264
+ async commitExtraction(profile, commit) {
265
+ return db.transaction(async (tx) => {
266
+ if (await epochOf(tx, profile) !== commit.expectedEpoch) return false;
267
+ const source = await tx.get("SELECT cursor, suppressed FROM profile_memory_sources WHERE profile = ? AND source_key = ?", profile, commit.sourceKey);
268
+ if (!source || source.suppressed === 1 || source.cursor !== commit.expectedCursor) return false;
269
+ const at = now();
270
+ if (commit.entry) {
271
+ const title = requireText(commit.entry.title, "title", 256);
272
+ const body = requireText(commit.entry.body, "body", MEMORY_BODY_MAX);
273
+ const existing = await tx.get("SELECT id FROM profile_memory_entries WHERE profile = ? AND origin = 'extracted' AND source_key = ?", profile, commit.sourceKey);
274
+ if (existing) await tx.run("UPDATE profile_memory_entries SET title = ?, body = ?, revision = revision + 1, updated_at = ? WHERE id = ?", title, body, at, existing.id);
275
+ else await tx.run(`INSERT INTO profile_memory_entries
276
+ (id, profile, title, body, revision, origin, source_key, created_at, updated_at)
277
+ VALUES (?, ?, ?, ?, 1, 'extracted', ?, ?, ?)`, newId(), profile, title, body, commit.sourceKey, at, at);
278
+ }
279
+ await tx.run("UPDATE profile_memory_sources SET cursor = ?, last_run_at = ? WHERE profile = ? AND source_key = ?", commit.nextCursor, at, profile, commit.sourceKey);
280
+ return true;
281
+ });
282
+ },
283
+ close: () => db.close()
284
+ };
285
+ }
286
+ function requireProfileMemoryStore(context) {
287
+ const service = context.get(PROFILE_MEMORY_STORE_SERVICE);
288
+ if (!service) throw new Error("Profile memory store is unavailable");
289
+ return service;
290
+ }
291
+ //#endregion
12
292
  //#region src/extensions/(backend)/root.server.ts
13
293
  var root_server_default$1 = (0, _agimon_ai_po_core_extensionFile.defineRoot)(({ host }) => {
14
294
  const environment = Object.freeze({ ...host.context.environment });
@@ -16,10 +296,135 @@ var root_server_default$1 = (0, _agimon_ai_po_core_extensionFile.defineRoot)(({
16
296
  const secrets = require_profileText.createProfileSecrets({ readBinding: (cwd, profile, homeDirectory) => require_profileText.findProfile((0, _agimon_ai_po_config_profiles.loadProfiles)(cwd, homeDirectory ?? environment.HOME ?? _agimon_ai_po_core_platform.nodeHost.homeDirectory()), sources, profile).integration });
17
297
  return {
18
298
  value: secrets,
19
- services: [require_profileText.createProfileSecretsPlugin(secrets), require_profileText.createProfileSourcesPlugin(sources)]
299
+ services: [
300
+ require_profileText.createProfileSecretsPlugin(secrets),
301
+ require_profileText.createProfileSourcesPlugin(sources),
302
+ async (context) => {
303
+ await context.inject([_agimon_ai_po_core_platform.PO_FS_SERVICE, _agimon_ai_po_core_platform.PO_SQLITE_SERVICE], async (scoped) => {
304
+ const homeDirectory = host.context.homeDirectory;
305
+ if (!homeDirectory) throw new Error("Profile memory requires an explicit host home directory.");
306
+ const store = await createProfileMemoryStore({
307
+ fs: (0, _agimon_ai_po_core_platform.requirePoFs)(scoped),
308
+ sqlite: (0, _agimon_ai_po_core_platform.requirePoSqlite)(scoped),
309
+ directory: node_path.default.join((0, _agimon_ai_po_core_piSettings.poHomeDirectory)(homeDirectory, environment), PROFILE_MEMORY_DIRECTORY),
310
+ context: _agimon_ai_po_core_platform.BACKGROUND_CONTEXT
311
+ });
312
+ const release = scoped.provide(PROFILE_MEMORY_STORE_SERVICE, store);
313
+ return async () => {
314
+ await Promise.resolve(release());
315
+ await store.close();
316
+ };
317
+ });
318
+ }
319
+ ]
20
320
  };
21
321
  });
22
322
  //#endregion
323
+ //#region src/services/profileMemoryNamespace/index.ts
324
+ const DECLARATIONS = `interface MemoryHit {
325
+ id: string;
326
+ title: string;
327
+ /** First 512 characters of the body; call memory.read for the rest. */
328
+ excerpt: string;
329
+ revision: number;
330
+ origin: 'manual' | 'extracted';
331
+ updatedAt: number;
332
+ }
333
+
334
+ interface MemoryEntry {
335
+ id: string;
336
+ title: string;
337
+ body: string;
338
+ revision: number;
339
+ origin: 'manual' | 'extracted';
340
+ createdAt: number;
341
+ updatedAt: number;
342
+ }
343
+
344
+ declare const memory: {
345
+ /** Full-text search over the selected profile's memory, best match first. Plain words only; operators are literal. */
346
+ search(input: { query: string; limit?: number }): Promise<MemoryHit[]>;
347
+ /** Newest first. Pass the previous page's nextCursor to continue. */
348
+ list(input?: { cursor?: string; limit?: number }): Promise<{ entries: MemoryHit[]; nextCursor?: string }>;
349
+ /** The whole entry, or null when the id is not in this profile's memory. */
350
+ read(input: { id: string }): Promise<MemoryEntry | null>;
351
+ /** Create an entry, or replace one when id is given. Pass expectedRevision from your last read to avoid overwriting a newer edit. */
352
+ write(input: { title: string; body: string; id?: string; expectedRevision?: number }): Promise<MemoryEntry>;
353
+ /** Delete an entry. expectedRevision is required. */
354
+ forget(input: { id: string; expectedRevision: number }): Promise<{ forgotten: true }>;
355
+ };`;
356
+ function record(input) {
357
+ if (typeof input !== "object" || input === null || Array.isArray(input)) throw new Error("Memory call expects an object");
358
+ return input;
359
+ }
360
+ function text(value, name) {
361
+ if (typeof value !== "string") throw new Error(`Memory ${name} must be a string`);
362
+ return value;
363
+ }
364
+ function optionalNumber(value, name) {
365
+ if (value === void 0) return void 0;
366
+ if (typeof value !== "number" || !Number.isInteger(value)) throw new Error(`Memory ${name} must be an integer`);
367
+ return value;
368
+ }
369
+ function createProfileMemoryNamespace(options) {
370
+ const { store, runtime } = options;
371
+ /** Resolves the selected profile for one call; `recheck` rejects results that outlived a profile switch. */
372
+ const scoped = async (signal, operation, recheck) => {
373
+ options.assertAvailable();
374
+ const before = runtime.readSelection();
375
+ if (before.profileName === void 0) throw new Error("No profile is selected");
376
+ if (signal.aborted) throw new Error("Memory call was cancelled");
377
+ const result = await operation(before.profileName);
378
+ if (recheck && runtime.readSelection().generation !== before.generation) throw new Error("The selected profile changed during the memory call");
379
+ return result;
380
+ };
381
+ return {
382
+ name: "memory",
383
+ summary: `Search and curate the selected profile's long-term memory (full-text search, 10 results by default, 50 at most). Unavailable when no profile is selected.`,
384
+ declarations: DECLARATIONS,
385
+ portable: true,
386
+ bind(run) {
387
+ if (run.sessionId !== options.sessionId) throw new Error("Memory belongs to another session");
388
+ return {
389
+ search: async (input) => {
390
+ const args = record(input);
391
+ return scoped(run.signal, (profile) => store.search(profile, text(args.query, "query"), optionalNumber(args.limit, "limit")), true);
392
+ },
393
+ list: async (input = {}) => {
394
+ const args = record(input);
395
+ const cursor = args.cursor === void 0 ? void 0 : text(args.cursor, "cursor");
396
+ return scoped(run.signal, (profile) => store.list(profile, {
397
+ cursor,
398
+ limit: optionalNumber(args.limit, "limit")
399
+ }), true);
400
+ },
401
+ read: async (input) => {
402
+ const args = record(input);
403
+ return scoped(run.signal, async (profile) => await store.read(profile, text(args.id, "id")) ?? null, true);
404
+ },
405
+ write: async (input) => {
406
+ const args = record(input);
407
+ return scoped(run.signal, (profile) => store.write(profile, {
408
+ title: text(args.title, "title"),
409
+ body: text(args.body, "body"),
410
+ ...args.id === void 0 ? {} : { id: text(args.id, "id") },
411
+ ...args.expectedRevision === void 0 ? {} : { expectedRevision: optionalNumber(args.expectedRevision, "expectedRevision") }
412
+ }), false);
413
+ },
414
+ forget: async (input) => {
415
+ const args = record(input);
416
+ const expectedRevision = optionalNumber(args.expectedRevision, "expectedRevision");
417
+ if (expectedRevision === void 0) throw new Error("Memory expectedRevision is required");
418
+ return scoped(run.signal, async (profile) => {
419
+ await store.forget(profile, text(args.id, "id"), expectedRevision);
420
+ return { forgotten: true };
421
+ }, false);
422
+ }
423
+ };
424
+ }
425
+ };
426
+ }
427
+ //#endregion
23
428
  //#region src/extensions/workspaces/sessions/(backend)/root.server.ts
24
429
  var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)(({ agent, signal, context }) => {
25
430
  if (!agent) return { value: void 0 };
@@ -30,9 +435,9 @@ var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)(({ ag
30
435
  readBinding: (profileName) => readProfile(profileName).integration,
31
436
  readEnv: (profileName) => readProfile(profileName).env
32
437
  });
33
- const unsubscribe = agent.subscribeSelection(async (selection) => {
438
+ const unsubscribe = agent.subscribeSelection(async (selection, applied) => {
34
439
  try {
35
- await runtime.select(selection.profile);
440
+ await runtime.select(selection.profile, { force: applied?.refresh?.includes("profile") === true });
36
441
  } catch (error) {
37
442
  throw new _agimon_ai_po_core_headless.PoHeadlessPromptAdmissionError(error);
38
443
  }
@@ -42,7 +447,21 @@ var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)(({ ag
42
447
  if (signal.aborted) runtime.invalidate();
43
448
  return {
44
449
  value: runtime,
45
- services: [require_profileText.createProfileRuntimePlugin(runtime)],
450
+ services: [require_profileText.createProfileRuntimePlugin(runtime), (serviceContext) => {
451
+ serviceContext.inject([_agimon_ai_po_core_codemode.PO_CODEMODE_SERVICE, PROFILE_MEMORY_STORE_SERVICE], (injected) => {
452
+ const codemode = (0, _agimon_ai_po_core_codemode.readPoCodemode)(injected);
453
+ if (!codemode) return void 0;
454
+ const registration = codemode.register(PROFILE_MEMORY_NAMESPACE_SOURCE, createProfileMemoryNamespace({
455
+ store: requireProfileMemoryStore(injected),
456
+ runtime,
457
+ sessionId: execution.sessionId,
458
+ assertAvailable: () => {
459
+ if (signal.aborted) throw new Error("Profile memory session is unavailable.");
460
+ }
461
+ }));
462
+ return () => registration.dispose();
463
+ });
464
+ }],
46
465
  async onDispose() {
47
466
  await (0, _agimon_ai_po_core_extensionFile.runCleanups)([
48
467
  unsubscribe,
@@ -141,6 +560,149 @@ function createProfileIdentityHook(sources) {
141
560
  //#region src/extensions/workspaces/sessions/(backend)/command/profile.server.ts
142
561
  var profile_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoutedContribution)(({ agent, context }) => agent ? createProfileServerCommand(agent, require_profileText.readProfileSources(context)) : void 0, { cardinality: "optional" });
143
562
  //#endregion
563
+ //#region src/services/profileMemoryExtraction/index.ts
564
+ const ROOT_CURSOR = "root";
565
+ function messageText(content) {
566
+ if (typeof content === "string") return content;
567
+ if (!Array.isArray(content)) return "";
568
+ return content.map((part) => part?.type === "text" && typeof part.text === "string" ? part.text : "").filter(Boolean).join("\n");
569
+ }
570
+ /** Human turns plus the final assistant reply, oldest first. Tool calls and results are never sent. */
571
+ function transcript(newestFirst) {
572
+ const lines = [];
573
+ let assistant = true;
574
+ for (const entry of newestFirst) {
575
+ const message = entry.message;
576
+ const text = messageText(message?.content).trim();
577
+ if (!text) continue;
578
+ if (message?.role === "user") lines.push(`User: ${text}`);
579
+ else if (message?.role === "assistant" && assistant) {
580
+ assistant = false;
581
+ lines.push(`Assistant: ${text}`);
582
+ }
583
+ }
584
+ return lines.reverse().join("\n\n").slice(-65536);
585
+ }
586
+ function parseEntry(raw) {
587
+ const parsed = JSON.parse(raw.replace(/^\s*```(?:json)?\s*|\s*```\s*$/g, ""));
588
+ if (typeof parsed !== "object" || parsed === null) throw new Error("Memory extraction returned a non-object");
589
+ const { title, body } = parsed;
590
+ if (typeof title !== "string" || typeof body !== "string") throw new Error("Memory extraction returned a bad shape");
591
+ if (!body.trim()) return void 0;
592
+ return {
593
+ title: title.trim().slice(0, 256) || "Untitled",
594
+ body: body.trim().slice(0, MEMORY_BODY_MAX)
595
+ };
596
+ }
597
+ function createProfileMemoryExtraction(options) {
598
+ const { store, runtime, now = Date.now } = options;
599
+ let inflight;
600
+ let controller;
601
+ let lastProfile;
602
+ const run = async (execution, profile, generation, env, selectionSignal) => {
603
+ const sourceKey = execution.sessionId;
604
+ const fresh = [];
605
+ let newest;
606
+ const state = await store.readSource(profile, sourceKey);
607
+ let found = false;
608
+ for await (const entry of execution.session.entriesNewestFirst({ type: "message" })) {
609
+ if (typeof entry.id !== "string") continue;
610
+ newest ??= entry.id;
611
+ if (entry.id === state?.cursor) {
612
+ found = true;
613
+ break;
614
+ }
615
+ fresh.push(entry);
616
+ }
617
+ const head = newest ?? ROOT_CURSOR;
618
+ if (!state) {
619
+ await store.initSource(profile, sourceKey, head);
620
+ return;
621
+ }
622
+ const epoch = await store.epoch(profile);
623
+ let boundary = -1;
624
+ for await (const marker of execution.session.entriesNewestFirst({
625
+ type: "custom",
626
+ customType: _agimon_ai_po_core_profileIdentity.PO_PROFILE_IDENTITY_ENTRY_TYPE,
627
+ limit: 50
628
+ })) if (marker.data?.profile !== profile) {
629
+ boundary = Number(marker.id);
630
+ break;
631
+ }
632
+ if (Number.isFinite(boundary)) {
633
+ for (let index = fresh.length - 1; index >= 0; index--) if (Number(fresh[index].id) <= boundary) fresh.splice(index, 1);
634
+ }
635
+ if (!found || lastProfile !== profile || fresh.length === 0 || now() - state.lastRunAt < 3e5) {
636
+ if (!found || lastProfile !== profile) await store.commitExtraction(profile, {
637
+ sourceKey,
638
+ expectedEpoch: epoch,
639
+ expectedCursor: state.cursor,
640
+ nextCursor: head
641
+ });
642
+ return;
643
+ }
644
+ const model = execution.model ? `${execution.model.provider}/${execution.model.id}` : void 0;
645
+ if (!model || !execution.textCompletion?.available(model)) return;
646
+ const input = require_profileText.redactSecrets(transcript(fresh), env);
647
+ if (!input) return;
648
+ controller = new AbortController();
649
+ const raw = await execution.textCompletion.complete(model, {
650
+ systemPrompt: EXTRACTION_SYSTEM_PROMPT,
651
+ input,
652
+ maxTokens: EXTRACTION_MAX_TOKENS,
653
+ signal: AbortSignal.any([
654
+ controller.signal,
655
+ selectionSignal,
656
+ AbortSignal.timeout(EXTRACTION_TIMEOUT_MS)
657
+ ]),
658
+ recordUsage: true
659
+ });
660
+ if (runtime.readSelection().generation !== generation) return;
661
+ const entry = parseEntry(raw);
662
+ await store.commitExtraction(profile, {
663
+ sourceKey,
664
+ expectedEpoch: epoch,
665
+ expectedCursor: state.cursor,
666
+ nextCursor: head,
667
+ ...entry ? { entry: require_profileText.redactSecrets(entry, env) } : {}
668
+ });
669
+ };
670
+ return {
671
+ settle(execution) {
672
+ if (inflight || !options.automatic()) return;
673
+ const selection = runtime.readSelection();
674
+ const profile = selection.profileName;
675
+ if (profile === void 0) return;
676
+ inflight = run(execution, profile, selection.generation, Object.values(selection.env ?? {}), selection.signal).catch((error) => options.onError(error, execution)).finally(() => {
677
+ lastProfile = profile;
678
+ controller = void 0;
679
+ inflight = void 0;
680
+ });
681
+ },
682
+ dispose() {
683
+ controller?.abort();
684
+ }
685
+ };
686
+ }
687
+ //#endregion
688
+ //#region src/extensions/workspaces/sessions/(backend)/hook/agentSettled.server.ts
689
+ var agentSettled_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)(({ root, context }) => {
690
+ let extraction;
691
+ return {
692
+ event: "agent_settled",
693
+ handle(_event, execution) {
694
+ if (!root) return;
695
+ extraction ??= createProfileMemoryExtraction({
696
+ store: requireProfileMemoryStore(context),
697
+ runtime: root,
698
+ automatic: () => context.get(_agimon_ai_po_config.PO_CONFIG_SERVICE)?.getSnapshot().settings.profileMemory?.automatic === true,
699
+ onError: (error, failed) => failed.client.setStatus(EXTRACTION_STATUS_SOURCE, `Memory extraction failed: ${error instanceof Error ? error.message : String(error)}`)
700
+ });
701
+ extraction.settle(execution);
702
+ }
703
+ };
704
+ });
705
+ //#endregion
144
706
  //#region src/extensions/workspaces/sessions/(backend)/hook/beforeAgentStart.server.ts
145
707
  var beforeAgentStart_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)(({ root }) => ({ async handle() {
146
708
  await assertProfileReady(root);
@@ -158,6 +720,16 @@ var sessionStart_server_default = (0, _agimon_ai_po_core_extensionFile.defineHoo
158
720
  };
159
721
  });
160
722
  //#endregion
723
+ //#region src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-memory.server.ts
724
+ var codemode_how_to_memory_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)({
725
+ name: "codemode-how-to-memory",
726
+ description: "Keep and recall durable facts about how the person likes to work, per profile, through the memory namespace. Use when a stable preference, convention, or decision should outlive this session, or when earlier context about the person may help; not for task progress or repository facts.",
727
+ kind: "skill",
728
+ pinned: true,
729
+ path: (0, _agimon_ai_po_core_serverPlugin.packageResourcePath)(require("url").pathToFileURL(__filename).href, "src/prompts/codemode-how-to-memory/SKILL.md"),
730
+ read: () => (0, _agimon_ai_po_core_serverPlugin.readPackageResource)(require("url").pathToFileURL(__filename).href, "src/prompts/codemode-how-to-memory/SKILL.md")
731
+ });
732
+ //#endregion
161
733
  //#region src/extensions/workspaces/sessions/(backend)/resource/help-how-to-profile.server.ts
162
734
  var help_how_to_profile_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)({
163
735
  name: "help-how-to-profile",
@@ -231,10 +803,18 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
231
803
  return defined([via({ name: "profile" }, at(profile_server_default, contextSession))]);
232
804
  },
233
805
  get hooks() {
234
- return [via({ event: "before_agent_start" }, at(beforeAgentStart_server_default, contextSession)), via({ event: "session_start" }, at(sessionStart_server_default, contextSession))];
806
+ return [
807
+ via({ event: "agent_settled" }, at(agentSettled_server_default, contextSession)),
808
+ via({ event: "before_agent_start" }, at(beforeAgentStart_server_default, contextSession)),
809
+ via({ event: "session_start" }, at(sessionStart_server_default, contextSession))
810
+ ];
235
811
  },
236
812
  get resources() {
237
- return [at(help_how_to_profile_server_default, contextSession), at(profileConfig_server_default, contextSession)];
813
+ return [
814
+ at(codemode_how_to_memory_server_default, contextSession),
815
+ at(help_how_to_profile_server_default, contextSession),
816
+ at(profileConfig_server_default, contextSession)
817
+ ];
238
818
  },
239
819
  services: [...scopeGlobal.services ?? [], ...scopeSession.services ?? []],
240
820
  get activities() {