@agimon-ai/po-profile 0.0.0-alpha.85 → 0.0.0-alpha.87
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/dist/extensions/server.cjs +10 -9
- package/dist/extensions/server.cjs.map +1 -1
- package/dist/extensions/server.mjs +10 -9
- package/dist/extensions/server.mjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.mts +10 -4
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{profileText-CH8MRgvJ.cjs → profileText-CiTmnfKH.cjs} +13 -7
- package/dist/profileText-CiTmnfKH.cjs.map +1 -0
- package/dist/{profileText-w8sUO66z.mjs → profileText-DCMunq1f.mjs} +13 -7
- package/dist/profileText-DCMunq1f.mjs.map +1 -0
- package/package.json +9 -9
- package/src/prompts/help-how-to-profile/references/profiles-contract.md +3 -0
- package/dist/profileText-CH8MRgvJ.cjs.map +0 -1
- package/dist/profileText-w8sUO66z.mjs.map +0 -1
|
@@ -24,7 +24,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
24
24
|
enumerable: true
|
|
25
25
|
}) : target, mod));
|
|
26
26
|
//#endregion
|
|
27
|
-
const require_profileText = require("../profileText-
|
|
27
|
+
const require_profileText = require("../profileText-CiTmnfKH.cjs");
|
|
28
28
|
let _agimon_ai_po_config_profiles = require("@agimon-ai/po-config/profiles");
|
|
29
29
|
let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
|
|
30
30
|
let _agimon_ai_po_core_extensionFile = require("@agimon-ai/po-core/extensionFile");
|
|
@@ -439,14 +439,15 @@ function createProfileMemoryNamespace(options) {
|
|
|
439
439
|
}
|
|
440
440
|
//#endregion
|
|
441
441
|
//#region src/extensions/workspaces/sessions/(backend)/root.server.ts
|
|
442
|
-
var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)(({ agent, signal, context }) => {
|
|
442
|
+
var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)(({ agent, host, signal, context }) => {
|
|
443
443
|
if (!agent) return { value: void 0 };
|
|
444
444
|
const execution = agent.context;
|
|
445
|
+
const scope = { workspaceId: host.context.workspaceId };
|
|
445
446
|
const readProfiles = () => (0, _agimon_ai_po_config_profiles.loadProfiles)(execution.repoRoot, execution.environment.HOME ?? _agimon_ai_po_core_platform.nodeHost.homeDirectory());
|
|
446
|
-
const readProfile = (profileName) => require_profileText.findProfile(readProfiles(), require_profileText.readProfileSources(context), profileName);
|
|
447
|
+
const readProfile = (profileName) => require_profileText.findProfile(readProfiles(), require_profileText.readProfileSources(context, scope), profileName);
|
|
447
448
|
const unregisterResolver = agent.registerInitialSelectionResolver((selection) => {
|
|
448
449
|
if (selection.profile === void 0) return selection;
|
|
449
|
-
return require_profileText.mergeProfiles(readProfiles(), require_profileText.readProfileSources(context)).some(({ name }) => name === selection.profile) ? selection : {
|
|
450
|
+
return require_profileText.mergeProfiles(readProfiles(), require_profileText.readProfileSources(context, scope)).some(({ name }) => name === selection.profile) ? selection : {
|
|
450
451
|
...selection,
|
|
451
452
|
profile: void 0
|
|
452
453
|
};
|
|
@@ -579,7 +580,7 @@ function createProfileIdentityHook(sources) {
|
|
|
579
580
|
}
|
|
580
581
|
//#endregion
|
|
581
582
|
//#region src/extensions/workspaces/sessions/(backend)/command/profile.server.ts
|
|
582
|
-
var profile_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoutedContribution)(({ agent, context }) => agent ? createProfileServerCommand(agent, require_profileText.readProfileSources(context)) : void 0, { cardinality: "optional" });
|
|
583
|
+
var profile_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoutedContribution)(({ agent, host, context }) => agent ? createProfileServerCommand(agent, require_profileText.readProfileSources(context, { workspaceId: host.context.workspaceId })) : void 0, { cardinality: "optional" });
|
|
583
584
|
//#endregion
|
|
584
585
|
//#region src/services/profileMemoryExtraction/index.ts
|
|
585
586
|
const ROOT_CURSOR = "root";
|
|
@@ -730,8 +731,8 @@ var beforeAgentStart_server_default = (0, _agimon_ai_po_core_extensionFile.defin
|
|
|
730
731
|
} }));
|
|
731
732
|
//#endregion
|
|
732
733
|
//#region src/extensions/workspaces/sessions/(backend)/hook/sessionStart.server.ts
|
|
733
|
-
var sessionStart_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)(({ root, context }) => {
|
|
734
|
-
const identityHook = createProfileIdentityHook(require_profileText.readProfileSources(context));
|
|
734
|
+
var sessionStart_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)(({ root, host, context }) => {
|
|
735
|
+
const identityHook = createProfileIdentityHook(require_profileText.readProfileSources(context, { workspaceId: host.context.workspaceId }));
|
|
735
736
|
return {
|
|
736
737
|
...identityHook,
|
|
737
738
|
async handle(event, execution) {
|
|
@@ -768,10 +769,10 @@ var help_how_to_profile_server_default = (0, _agimon_ai_po_core_extensionFile.de
|
|
|
768
769
|
});
|
|
769
770
|
//#endregion
|
|
770
771
|
//#region src/extensions/workspaces/sessions/(backend)/resource/profileConfig.server.ts
|
|
771
|
-
var profileConfig_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)(({ context }) => ({
|
|
772
|
+
var profileConfig_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)(({ host, context }) => ({
|
|
772
773
|
name: "po/profile-config",
|
|
773
774
|
kind: "context",
|
|
774
|
-
read: (execution) => readSelectedPersona(execution, require_profileText.readProfileSources(context))
|
|
775
|
+
read: (execution) => readSelectedPersona(execution, require_profileText.readProfileSources(context, { workspaceId: host.context.workspaceId }))
|
|
775
776
|
}));
|
|
776
777
|
//#endregion
|
|
777
778
|
//#region generated/server.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.cjs","names":["path","getOrThrow","nodeHost","defineRoot","createProfileSources","createProfileSecrets","findProfile","loadProfiles","nodeHost","PO_SERVER_SCOPE_SERVICE","requirePoServerScope","defineServiceContract","PROFILE_SECRETS_SERVICE","PROFILE_SOURCES_SERVICE","PO_FS_SERVICE","PO_SQLITE_SERVICE","requirePoFs","requirePoSqlite","path","poHomeDirectory","BACKGROUND_CONTEXT","defineRoot","loadProfiles","nodeHost","findProfile","readProfileSources","mergeProfiles","createProfileRuntime","PoHeadlessPromptAdmissionError","createProfileRuntimePlugin","PO_CODEMODE_SERVICE","readPoCodemode","runCleanups","defineRoute","findProfile","loadProfiles","buildPersonaPrompt","PO_PROFILE_IDENTITY_ENTRY_TYPE","PROFILE_COMMAND","mergeProfiles","profileTitle","profileItems","isPoHeadlessPromptAdmissionError","PoSessionSetupError","PoHeadlessPromptAdmissionError","defineRoutedContribution","readProfileSources","PO_PROFILE_IDENTITY_ENTRY_TYPE","redactSecrets","defineHook","PO_CONFIG_SERVICE","defineHook","defineHook","readProfileSources","defineResource","packageResourcePath","readPackageResource","defineResource","packageResourcePath","readPackageResource","defineResource","readProfileSources","defineServerPlugin","composeServerProviderOverrides","rootGlobal","rootSession","composeRootInjects","composeRootHooks","apiRoute","commandProfile","hookAgentSettled","hookBeforeAgentStart","hookSessionStart","resourceCodemodeHowToMemory","resourceHelpHowToProfile","resourceProfileConfig"],"sources":["../../src/constants/profileMemory.ts","../../src/services/profileMemoryStore/index.ts","../../src/extensions/(backend)/root.server.ts","../../src/services/profileMemoryNamespace/index.ts","../../src/extensions/workspaces/sessions/(backend)/root.server.ts","../../src/extensions/workspaces/sessions/(backend)/api/profile/route.server.ts","../../src/extensions/workspaces/sessions/(backend)/_lib/profileServer.ts","../../src/extensions/workspaces/sessions/(backend)/command/profile.server.ts","../../src/services/profileMemoryExtraction/index.ts","../../src/extensions/workspaces/sessions/(backend)/hook/agentSettled.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/beforeAgentStart.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/sessionStart.server.ts","../../src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-memory.server.ts","../../src/extensions/workspaces/sessions/(backend)/resource/help-how-to-profile.server.ts","../../src/extensions/workspaces/sessions/(backend)/resource/profileConfig.server.ts","../../generated/server.ts"],"sourcesContent":["export const PROFILE_MEMORY_STORE_SERVICE = 'po/profile-memory-store';\n\nexport const PROFILE_MEMORY_NAMESPACE_SOURCE = '@agimon-ai/po-profile/memory';\n\nexport const PROFILE_MEMORY_DIRECTORY = 'profile-memory';\nexport const PROFILE_MEMORY_FILE = 'memory.sqlite';\nexport const PROFILE_MEMORY_DIRECTORY_MODE = 0o700;\n\nexport const MEMORY_TITLE_MAX = 256;\nexport const MEMORY_BODY_MAX = 16 * 1024;\nexport const MEMORY_QUERY_MAX = 512;\nexport const MEMORY_EXCERPT_MAX = 512;\nexport const MEMORY_LIMIT_DEFAULT = 10;\nexport const MEMORY_LIMIT_MAX = 50;\n\nexport const EXTRACTION_COOLDOWN_MS = 5 * 60 * 1000;\nexport const EXTRACTION_TIMEOUT_MS = 60 * 1000;\nexport const EXTRACTION_INPUT_MAX = 64 * 1024;\nexport const EXTRACTION_MAX_TOKENS = 2048;\nexport const EXTRACTION_STATUS_SOURCE = 'profile-memory';\nexport const EXTRACTION_SYSTEM_PROMPT =\n 'You maintain long-term memory about how one person likes to work. ' +\n 'From the conversation, extract at most one durable fact: a stable preference, convention, or decision the person stated or clearly showed. ' +\n 'Ignore task progress, code details, and anything derivable from a repository. Never include secrets. ' +\n 'Reply with JSON only: {\"title\": string, \"body\": string}. Use an empty body when nothing is worth keeping.';\n","import path from 'node:path';\n\nimport { getOrThrow, nodeHost } from '@agimon-ai/po-core/platform';\nimport type { Context } from '@deepseek-ai/cordis';\n\nimport {\n MEMORY_BODY_MAX,\n MEMORY_EXCERPT_MAX,\n MEMORY_LIMIT_DEFAULT,\n MEMORY_LIMIT_MAX,\n MEMORY_QUERY_MAX,\n MEMORY_TITLE_MAX,\n PROFILE_MEMORY_DIRECTORY_MODE,\n PROFILE_MEMORY_FILE,\n PROFILE_MEMORY_STORE_SERVICE,\n} from '../../constants/profileMemory';\nimport type {\n ProfileMemoryEntry,\n ProfileMemoryHit,\n ProfileMemoryOrigin,\n ProfileMemoryStore,\n ProfileMemoryStoreOptions,\n} from './type';\n\ntype Database = Awaited<ReturnType<ProfileMemoryStoreOptions['sqlite']['open']>>;\ntype Executor = Parameters<Parameters<Database['transaction']>[0]>[0];\n\n/** Append only: a database at version N applies MIGRATIONS[N..]. */\nconst MIGRATIONS: readonly string[] = [\n `\n CREATE TABLE profile_memory_entries (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n profile TEXT NOT NULL,\n title TEXT NOT NULL,\n body TEXT NOT NULL,\n revision INTEGER NOT NULL,\n origin TEXT NOT NULL CHECK (origin IN ('manual', 'extracted')),\n source_key TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n );\n CREATE INDEX profile_memory_entries_recent ON profile_memory_entries(profile, updated_at DESC, seq DESC);\n CREATE UNIQUE INDEX profile_memory_entries_source ON profile_memory_entries(profile, source_key)\n WHERE origin = 'extracted';\n CREATE VIRTUAL TABLE profile_memory_fts USING fts5(\n title, body, content='profile_memory_entries', content_rowid='seq'\n );\n CREATE TRIGGER profile_memory_ai AFTER INSERT ON profile_memory_entries BEGIN\n INSERT INTO profile_memory_fts(rowid, title, body) VALUES (new.seq, new.title, new.body);\n END;\n CREATE TRIGGER profile_memory_ad AFTER DELETE ON profile_memory_entries BEGIN\n INSERT INTO profile_memory_fts(profile_memory_fts, rowid, title, body)\n VALUES ('delete', old.seq, old.title, old.body);\n END;\n CREATE TRIGGER profile_memory_au AFTER UPDATE ON profile_memory_entries BEGIN\n INSERT INTO profile_memory_fts(profile_memory_fts, rowid, title, body)\n VALUES ('delete', old.seq, old.title, old.body);\n INSERT INTO profile_memory_fts(rowid, title, body) VALUES (new.seq, new.title, new.body);\n END;\n CREATE TABLE profile_memory_sources (\n profile TEXT NOT NULL,\n source_key TEXT NOT NULL,\n cursor TEXT NOT NULL,\n last_run_at INTEGER NOT NULL,\n suppressed INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (profile, source_key)\n );\n CREATE TABLE profile_memory_epochs (profile TEXT PRIMARY KEY, epoch INTEGER NOT NULL);\n `,\n];\n\ninterface EntryRow {\n seq: number;\n id: string;\n title: string;\n body: string;\n revision: number;\n origin: ProfileMemoryOrigin;\n source_key: string | null;\n created_at: number;\n updated_at: number;\n}\n\ninterface HitRow {\n seq: number;\n id: string;\n title: string;\n excerpt: string;\n revision: number;\n origin: ProfileMemoryOrigin;\n updated_at: number;\n}\n\nconst HIT_COLUMNS = 'e.seq, e.id, e.title, substr(e.body, 1, ?) AS excerpt, e.revision, e.origin, e.updated_at';\n\nfunction requireText(value: unknown, name: string, max: number): string {\n if (typeof value !== 'string' || !value.trim()) throw new Error(`Memory ${name} must be a non-empty string`);\n if (value.length > max) throw new Error(`Memory ${name} must be at most ${max} characters`);\n return value;\n}\n\nfunction requireProfile(profile: unknown): void {\n if (typeof profile !== 'string' || !profile) throw new Error('Memory profile must be a non-empty string');\n}\n\nfunction clampLimit(limit: number | undefined): number {\n if (limit === undefined) return MEMORY_LIMIT_DEFAULT;\n if (!Number.isInteger(limit) || limit < 1) throw new Error('Memory limit must be a positive integer');\n return Math.min(limit, MEMORY_LIMIT_MAX);\n}\n\n/** Quoted word tokens only, so FTS operators (`\"`, `*`, `NEAR`, `OR`) in user text stay literal. */\nfunction ftsQuery(query: string): string | undefined {\n const tokens = query.match(/[\\p{L}\\p{N}_]+/gu);\n return tokens ? tokens.map((token) => `\"${token}\"`).join(' ') : undefined;\n}\n\nfunction toHit(row: HitRow): ProfileMemoryHit {\n return {\n id: row.id,\n title: row.title,\n excerpt: row.excerpt,\n revision: row.revision,\n origin: row.origin,\n updatedAt: row.updated_at,\n };\n}\n\nfunction toEntry(row: EntryRow): ProfileMemoryEntry {\n return {\n id: row.id,\n title: row.title,\n body: row.body,\n revision: row.revision,\n origin: row.origin,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nasync function migrate(db: Database): Promise<void> {\n await db.transaction(async (tx) => {\n await tx.exec('CREATE TABLE IF NOT EXISTS profile_memory_meta (version INTEGER NOT NULL)');\n const current = await tx.get<{ version: number }>('SELECT version FROM profile_memory_meta');\n if (!current) await tx.run('INSERT INTO profile_memory_meta (version) VALUES (0)');\n const version = current?.version ?? 0;\n if (version > MIGRATIONS.length) throw new Error('Profile memory database is newer than this Po version');\n for (let index = version; index < MIGRATIONS.length; index++) await tx.exec(MIGRATIONS[index]!);\n await tx.run('UPDATE profile_memory_meta SET version = ?', MIGRATIONS.length);\n });\n}\n\n/**\n * Creates the memory directory owner-only, like `mkdirSync(directory, { recursive: true, mode: 0o700 })`.\n * Same behaviour as po-session's `ensurePrivateDirectory`, which is not exported; existing directories keep their mode.\n */\nasync function ensurePrivateDirectory(options: ProfileMemoryStoreOptions): Promise<void> {\n const missing: string[] = [];\n for (let current = path.resolve(options.directory); !getOrThrow(await options.fs.exists(current, options.context));) {\n missing.unshift(current);\n const parent = path.dirname(current);\n if (parent === current) break;\n current = parent;\n }\n if (missing.length === 0) return;\n getOrThrow(await options.fs.createDir(options.directory, { recursive: true }, options.context));\n for (const created of missing) await nodeHost.setMode(created, PROFILE_MEMORY_DIRECTORY_MODE);\n}\n\nexport async function createProfileMemoryStore(options: ProfileMemoryStoreOptions): Promise<ProfileMemoryStore> {\n const now = options.now ?? Date.now;\n const newId = options.id ?? (() => crypto.randomUUID());\n await ensurePrivateDirectory(options);\n const file = getOrThrow(await options.fs.joinPath([options.directory, PROFILE_MEMORY_FILE], options.context));\n const db = await options.sqlite.open(file, options.context);\n try {\n await migrate(db);\n } catch (error) {\n await db.close();\n throw error;\n }\n\n const findRow = (tx: Executor, profile: string, id: string) =>\n tx.get<EntryRow>('SELECT * FROM profile_memory_entries WHERE profile = ? AND id = ?', profile, id);\n const epochOf = async (tx: Executor, profile: string) =>\n (await tx.get<{ epoch: number }>('SELECT epoch FROM profile_memory_epochs WHERE profile = ?', profile))?.epoch ?? 0;\n const suppress = (tx: Executor, profile: string, sourceKey: string) =>\n tx.run('UPDATE profile_memory_sources SET suppressed = 1 WHERE profile = ? AND source_key = ?', profile, sourceKey);\n const checkRevision = (row: EntryRow | undefined, expected: number | undefined): EntryRow => {\n if (!row) throw new Error('Memory not found');\n if (expected !== undefined && row.revision !== expected) throw new Error('Memory changed since it was read');\n return row;\n };\n\n return {\n async search(profile, query, limit) {\n requireProfile(profile);\n requireText(query, 'query', MEMORY_QUERY_MAX);\n const match = ftsQuery(query);\n if (!match) return [];\n const rows = await db.all<HitRow>(\n `SELECT ${HIT_COLUMNS} FROM profile_memory_fts f JOIN profile_memory_entries e ON e.seq = f.rowid\n WHERE profile_memory_fts MATCH ? AND e.profile = ?\n ORDER BY bm25(profile_memory_fts), e.seq DESC LIMIT ?`,\n MEMORY_EXCERPT_MAX,\n match,\n profile,\n clampLimit(limit),\n );\n return rows.map(toHit);\n },\n\n async list(profile, listOptions = {}) {\n requireProfile(profile);\n const limit = clampLimit(listOptions.limit);\n let at: number | null = null;\n let seq: number | null = null;\n if (listOptions.cursor !== undefined) {\n const match = /^(\\d+)\\.(\\d+)$/.exec(listOptions.cursor);\n if (!match) throw new Error('Invalid memory cursor');\n at = Number(match[1]);\n seq = Number(match[2]);\n }\n const rows = await db.all<HitRow>(\n `SELECT ${HIT_COLUMNS} FROM profile_memory_entries e\n WHERE e.profile = ? AND (? IS NULL OR e.updated_at < ? OR (e.updated_at = ? AND e.seq < ?))\n ORDER BY e.updated_at DESC, e.seq DESC LIMIT ?`,\n MEMORY_EXCERPT_MAX,\n profile,\n at,\n at,\n at,\n seq,\n limit + 1,\n );\n const page = rows.slice(0, limit);\n const last = page[page.length - 1];\n return {\n entries: page.map(toHit),\n ...(rows.length > limit && last ? { nextCursor: `${last.updated_at}.${last.seq}` } : {}),\n };\n },\n\n async read(profile, id) {\n requireProfile(profile);\n const row = await db.get<EntryRow>(\n 'SELECT * FROM profile_memory_entries WHERE profile = ? AND id = ?',\n profile,\n id,\n );\n return row && toEntry(row);\n },\n\n async write(profile, input) {\n requireProfile(profile);\n const title = requireText(input.title, 'title', MEMORY_TITLE_MAX);\n const body = requireText(input.body, 'body', MEMORY_BODY_MAX);\n return db.transaction(async (tx) => {\n const at = now();\n if (input.id === undefined) {\n const id = newId();\n await tx.run(\n `INSERT INTO profile_memory_entries (id, profile, title, body, revision, origin, created_at, updated_at)\n VALUES (?, ?, ?, ?, 1, 'manual', ?, ?)`,\n id,\n profile,\n title,\n body,\n at,\n at,\n );\n return toEntry((await findRow(tx, profile, id))!);\n }\n const row = checkRevision(await findRow(tx, profile, input.id), input.expectedRevision);\n // A person-curated edit takes the entry over, so extraction must not rewrite or recreate it.\n if (row.origin === 'extracted' && row.source_key !== null) await suppress(tx, profile, row.source_key);\n await tx.run(\n `UPDATE profile_memory_entries\n SET title = ?, body = ?, revision = revision + 1, origin = 'manual', source_key = NULL, updated_at = ?\n WHERE profile = ? AND id = ?`,\n title,\n body,\n at,\n profile,\n input.id,\n );\n return toEntry((await findRow(tx, profile, input.id))!);\n });\n },\n\n async forget(profile, id, expectedRevision) {\n requireProfile(profile);\n await db.transaction(async (tx) => {\n const row = checkRevision(await findRow(tx, profile, id), expectedRevision);\n await tx.run('DELETE FROM profile_memory_entries WHERE profile = ? AND id = ?', profile, id);\n await tx.run(\n `INSERT INTO profile_memory_epochs (profile, epoch) VALUES (?, 1)\n ON CONFLICT(profile) DO UPDATE SET epoch = epoch + 1`,\n profile,\n );\n if (row.origin === 'extracted' && row.source_key !== null) await suppress(tx, profile, row.source_key);\n });\n },\n\n async epoch(profile) {\n return (\n (await db.get<{ epoch: number }>('SELECT epoch FROM profile_memory_epochs WHERE profile = ?', profile))\n ?.epoch ?? 0\n );\n },\n\n async readSource(profile, sourceKey) {\n const row = await db.get<{ cursor: string; last_run_at: number; suppressed: number }>(\n 'SELECT cursor, last_run_at, suppressed FROM profile_memory_sources WHERE profile = ? AND source_key = ?',\n profile,\n sourceKey,\n );\n return row && { cursor: row.cursor, lastRunAt: row.last_run_at, suppressed: row.suppressed === 1 };\n },\n\n async initSource(profile, sourceKey, cursor) {\n return db.transaction(async (tx) => {\n const existing = await tx.get<{ cursor: string }>(\n 'SELECT cursor FROM profile_memory_sources WHERE profile = ? AND source_key = ?',\n profile,\n sourceKey,\n );\n if (existing) return false;\n await tx.run(\n 'INSERT INTO profile_memory_sources (profile, source_key, cursor, last_run_at) VALUES (?, ?, ?, ?)',\n profile,\n sourceKey,\n cursor,\n now(),\n );\n return true;\n });\n },\n\n async commitExtraction(profile, commit) {\n return db.transaction(async (tx) => {\n if ((await epochOf(tx, profile)) !== commit.expectedEpoch) return false;\n const source = await tx.get<{ cursor: string; suppressed: number }>(\n 'SELECT cursor, suppressed FROM profile_memory_sources WHERE profile = ? AND source_key = ?',\n profile,\n commit.sourceKey,\n );\n if (!source || source.suppressed === 1 || source.cursor !== commit.expectedCursor) return false;\n const at = now();\n if (commit.entry) {\n const title = requireText(commit.entry.title, 'title', MEMORY_TITLE_MAX);\n const body = requireText(commit.entry.body, 'body', MEMORY_BODY_MAX);\n const existing = await tx.get<{ id: string }>(\n \"SELECT id FROM profile_memory_entries WHERE profile = ? AND origin = 'extracted' AND source_key = ?\",\n profile,\n commit.sourceKey,\n );\n if (existing)\n await tx.run(\n 'UPDATE profile_memory_entries SET title = ?, body = ?, revision = revision + 1, updated_at = ? WHERE id = ?',\n title,\n body,\n at,\n existing.id,\n );\n else\n await tx.run(\n `INSERT INTO profile_memory_entries\n (id, profile, title, body, revision, origin, source_key, created_at, updated_at)\n VALUES (?, ?, ?, ?, 1, 'extracted', ?, ?, ?)`,\n newId(),\n profile,\n title,\n body,\n commit.sourceKey,\n at,\n at,\n );\n }\n await tx.run(\n 'UPDATE profile_memory_sources SET cursor = ?, last_run_at = ? WHERE profile = ? AND source_key = ?',\n commit.nextCursor,\n at,\n profile,\n commit.sourceKey,\n );\n return true;\n });\n },\n\n close: () => db.close(),\n };\n}\n\nexport function createProfileMemoryStorePlugin(store: ProfileMemoryStore): (context: Context) => void {\n return (context) => {\n context.provide(PROFILE_MEMORY_STORE_SERVICE, store);\n };\n}\n\nexport function requireProfileMemoryStore(context: Context): ProfileMemoryStore {\n const service = context.get(PROFILE_MEMORY_STORE_SERVICE);\n if (!service) throw new Error('Profile memory store is unavailable');\n return service;\n}\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n 'po/profile-memory-store': ProfileMemoryStore;\n }\n}\n","import path from 'node:path';\n\nimport { loadProfiles } from '@agimon-ai/po-config/profiles';\nimport { defineRoot, defineServiceContract } from '@agimon-ai/po-core/extensionFile';\nimport { poHomeDirectory } from '@agimon-ai/po-core/piSettings';\nimport {\n BACKGROUND_CONTEXT,\n nodeHost,\n PO_FS_SERVICE,\n PO_SQLITE_SERVICE,\n requirePoFs,\n requirePoSqlite,\n} from '@agimon-ai/po-core/platform';\nimport {\n PO_SERVER_SCOPE_SERVICE,\n requirePoServerScope,\n type PoServerPluginContext,\n} from '@agimon-ai/po-core/serverPlugin';\n\nimport { PROFILE_MEMORY_DIRECTORY, PROFILE_MEMORY_STORE_SERVICE } from '../../constants/profileMemory';\nimport { PROFILE_SECRETS_SERVICE } from '../../constants/profileSecrets';\nimport { PROFILE_SOURCES_SERVICE } from '../../constants/profileSources';\nimport { createProfileMemoryStore } from '../../services/profileMemoryStore';\nimport { createProfileSecrets } from '../../services/profileSecrets';\nimport { createProfileSources, findProfile } from '../../services/profileSources';\n\nexport default defineRoot(({ host }: PoServerPluginContext) => {\n const environment = Object.freeze({ ...host.context.environment });\n const sources = createProfileSources();\n const secrets = createProfileSecrets({\n readBinding: (cwd, profile, homeDirectory) =>\n findProfile(loadProfiles(cwd, homeDirectory ?? environment.HOME ?? nodeHost.homeDirectory()), sources, profile)\n .integration,\n });\n return {\n value: secrets,\n services: [\n async (context) => {\n // Each server level has its own Cordis root, so a plain Cordis service here never reaches\n // sessions. Publish through the scope; the bindings unwind with this fiber.\n await context.inject([PO_SERVER_SCOPE_SERVICE], async (scoped) => {\n const scope = requirePoServerScope(scoped);\n await scope.provide(defineServiceContract(PROFILE_SECRETS_SERVICE, { scope: host.scope }), secrets);\n await scope.provide(defineServiceContract(PROFILE_SOURCES_SERVICE, { scope: host.scope }), sources);\n });\n },\n async (context) => {\n // Each server level has its own Cordis root. Publish through the scope so descendants\n // see the store even when they reuse this root instead of rerunning its services.\n await context.inject([PO_FS_SERVICE, PO_SQLITE_SERVICE, PO_SERVER_SCOPE_SERVICE], async (scoped) => {\n const homeDirectory = host.context.homeDirectory;\n if (!homeDirectory) throw new Error('Profile memory requires an explicit host home directory.');\n const store = await createProfileMemoryStore({\n fs: requirePoFs(scoped),\n sqlite: requirePoSqlite(scoped),\n directory: path.join(poHomeDirectory(homeDirectory, environment), PROFILE_MEMORY_DIRECTORY),\n context: BACKGROUND_CONTEXT,\n });\n // A standalone workspace or session can build this root too, and owns its binding there.\n const contract = defineServiceContract(PROFILE_MEMORY_STORE_SERVICE, { scope: host.scope });\n let release: () => Promise<void>;\n try {\n release = await requirePoServerScope(scoped).provide(contract, store);\n } catch (error) {\n await store.close();\n throw error;\n }\n return async () => {\n await release();\n await store.close();\n };\n });\n },\n ],\n };\n});\n","import type { PoCodemodeNamespace } from '@agimon-ai/po-core/codemode';\n\nimport { MEMORY_LIMIT_DEFAULT, MEMORY_LIMIT_MAX } from '../../constants/profileMemory';\nimport type { ProfileMemoryNamespaceOptions } from './type';\n\nconst DECLARATIONS = `interface MemoryHit {\n id: string;\n title: string;\n /** First 512 characters of the body; call memory.read for the rest. */\n excerpt: string;\n revision: number;\n origin: 'manual' | 'extracted';\n updatedAt: number;\n}\n\ninterface MemoryEntry {\n id: string;\n title: string;\n body: string;\n revision: number;\n origin: 'manual' | 'extracted';\n createdAt: number;\n updatedAt: number;\n}\n\ndeclare const memory: {\n /** Full-text search over the selected profile's memory, best match first. Plain words only; operators are literal. */\n search(input: { query: string; limit?: number }): Promise<MemoryHit[]>;\n /** Newest first. Pass the previous page's nextCursor to continue. */\n list(input?: { cursor?: string; limit?: number }): Promise<{ entries: MemoryHit[]; nextCursor?: string }>;\n /** The whole entry, or null when the id is not in this profile's memory. */\n read(input: { id: string }): Promise<MemoryEntry | null>;\n /** Create an entry, or replace one when id is given. Pass expectedRevision from your last read to avoid overwriting a newer edit. */\n write(input: { title: string; body: string; id?: string; expectedRevision?: number }): Promise<MemoryEntry>;\n /** Delete an entry. expectedRevision is required. */\n forget(input: { id: string; expectedRevision: number }): Promise<{ forgotten: true }>;\n};`;\n\nfunction record(input: unknown): Record<string, unknown> {\n if (typeof input !== 'object' || input === null || Array.isArray(input))\n throw new Error('Memory call expects an object');\n return input as Record<string, unknown>;\n}\n\nfunction text(value: unknown, name: string): string {\n if (typeof value !== 'string') throw new Error(`Memory ${name} must be a string`);\n return value;\n}\n\nfunction optionalNumber(value: unknown, name: string): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== 'number' || !Number.isInteger(value)) throw new Error(`Memory ${name} must be an integer`);\n return value;\n}\n\nexport function createProfileMemoryNamespace(options: ProfileMemoryNamespaceOptions): PoCodemodeNamespace {\n const { store, runtime } = options;\n /** Resolves the selected profile for one call; `recheck` rejects results that outlived a profile switch. */\n const scoped = async <T>(\n signal: AbortSignal,\n operation: (profile: string) => Promise<T>,\n recheck: boolean,\n ): Promise<T> => {\n options.assertAvailable();\n const before = runtime.readSelection();\n if (before.profileName === undefined) throw new Error('No profile is selected');\n if (signal.aborted) throw new Error('Memory call was cancelled');\n const result = await operation(before.profileName);\n if (recheck && runtime.readSelection().generation !== before.generation)\n throw new Error('The selected profile changed during the memory call');\n return result;\n };\n\n return {\n name: 'memory',\n summary: `Search and curate the selected profile's long-term memory (full-text search, ${MEMORY_LIMIT_DEFAULT} results by default, ${MEMORY_LIMIT_MAX} at most). Unavailable when no profile is selected.`,\n declarations: DECLARATIONS,\n portable: true,\n bind(run) {\n if (run.sessionId !== options.sessionId) throw new Error('Memory belongs to another session');\n return {\n search: async (input: unknown) => {\n const args = record(input);\n return scoped(\n run.signal,\n (profile) => store.search(profile, text(args.query, 'query'), optionalNumber(args.limit, 'limit')),\n true,\n );\n },\n list: async (input: unknown = {}) => {\n const args = record(input);\n const cursor = args.cursor === undefined ? undefined : text(args.cursor, 'cursor');\n return scoped(\n run.signal,\n (profile) => store.list(profile, { cursor, limit: optionalNumber(args.limit, 'limit') }),\n true,\n );\n },\n read: async (input: unknown) => {\n const args = record(input);\n return scoped(run.signal, async (profile) => (await store.read(profile, text(args.id, 'id'))) ?? null, true);\n },\n write: async (input: unknown) => {\n const args = record(input);\n return scoped(\n run.signal,\n (profile) =>\n store.write(profile, {\n title: text(args.title, 'title'),\n body: text(args.body, 'body'),\n ...(args.id === undefined ? {} : { id: text(args.id, 'id') }),\n ...(args.expectedRevision === undefined\n ? {}\n : { expectedRevision: optionalNumber(args.expectedRevision, 'expectedRevision') }),\n }),\n false,\n );\n },\n forget: async (input: unknown) => {\n const args = record(input);\n const expectedRevision = optionalNumber(args.expectedRevision, 'expectedRevision');\n if (expectedRevision === undefined) throw new Error('Memory expectedRevision is required');\n return scoped(\n run.signal,\n async (profile) => {\n await store.forget(profile, text(args.id, 'id'), expectedRevision);\n return { forgotten: true as const };\n },\n false,\n );\n },\n };\n },\n };\n}\n","import { loadProfiles } from '@agimon-ai/po-config/profiles';\nimport { PO_CODEMODE_SERVICE, readPoCodemode } from '@agimon-ai/po-core/codemode';\nimport { defineRoot, runCleanups } from '@agimon-ai/po-core/extensionFile';\nimport { PoHeadlessPromptAdmissionError } from '@agimon-ai/po-core/headless';\nimport { nodeHost } from '@agimon-ai/po-core/platform';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { PROFILE_MEMORY_NAMESPACE_SOURCE, PROFILE_MEMORY_STORE_SERVICE } from '../../../../constants/profileMemory';\nimport { createProfileMemoryNamespace } from '../../../../services/profileMemoryNamespace';\nimport { requireProfileMemoryStore } from '../../../../services/profileMemoryStore';\nimport { createProfileRuntime, createProfileRuntimePlugin } from '../../../../services/profileRuntime';\nimport { findProfile, mergeProfiles, readProfileSources } from '../../../../services/profileSources';\n\nexport default defineRoot(({ agent, signal, context }: PoServerPluginContext) => {\n if (!agent) return { value: undefined };\n const execution = agent.context;\n const readProfiles = () => loadProfiles(execution.repoRoot, execution.environment.HOME ?? nodeHost.homeDirectory());\n const readProfile = (profileName: string) => findProfile(readProfiles(), readProfileSources(context), profileName);\n const unregisterResolver = agent.registerInitialSelectionResolver((selection) => {\n if (selection.profile === undefined) return selection;\n const profiles = mergeProfiles(readProfiles(), readProfileSources(context));\n return profiles.some(({ name }) => name === selection.profile) ? selection : { ...selection, profile: undefined };\n });\n // The host validates the restored name before applying its first selection.\n const runtime = createProfileRuntime({\n readBinding: (profileName) => readProfile(profileName).integration,\n readEnv: (profileName) => readProfile(profileName).env,\n });\n const unsubscribe = agent.subscribeSelection(async (selection, applied) => {\n try {\n // A refresh re-reads the same profile's env and binding after it was edited on disk.\n await runtime.select(selection.profile, { force: applied?.refresh?.includes('profile') === true });\n } catch (error) {\n throw new PoHeadlessPromptAdmissionError(error);\n }\n });\n const invalidate = () => runtime.invalidate();\n signal.addEventListener('abort', invalidate, { once: true });\n if (signal.aborted) runtime.invalidate();\n return {\n value: runtime,\n services: [\n createProfileRuntimePlugin(runtime),\n (serviceContext) => {\n serviceContext.inject([PO_CODEMODE_SERVICE, PROFILE_MEMORY_STORE_SERVICE], (injected) => {\n const codemode = readPoCodemode(injected);\n if (!codemode) return undefined;\n const registration = codemode.register(\n PROFILE_MEMORY_NAMESPACE_SOURCE,\n createProfileMemoryNamespace({\n store: requireProfileMemoryStore(injected),\n runtime,\n sessionId: execution.sessionId,\n assertAvailable: () => {\n if (signal.aborted) throw new Error('Profile memory session is unavailable.');\n },\n }),\n );\n return () => registration.dispose();\n });\n },\n ],\n async onDispose() {\n await runCleanups(\n [\n unregisterResolver,\n unsubscribe,\n () => signal.removeEventListener('abort', invalidate),\n () => runtime.dispose(),\n ],\n 'Profile cleanup failed.',\n );\n },\n };\n});\n","import { defineRoute } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nexport default defineRoute(({ agent }: PoServerPluginContext) => ({\n basePath: 'profile',\n start: () => ({\n fetch(request: Request) {\n if (new URL(request.url).pathname !== '/current') return Response.json({ error: 'Not found' }, { status: 404 });\n if (request.method !== 'GET')\n return Response.json({ error: 'Method not allowed' }, { status: 405, headers: { Allow: 'GET' } });\n if (!agent) return Response.json({ error: 'Session agent unavailable' }, { status: 404 });\n const selection = agent.context.selection;\n return Response.json({ profile: selection.profile ?? null });\n },\n close() {},\n }),\n}));\n","import { buildPersonaPrompt, loadProfiles } from '@agimon-ai/po-config/profiles';\nimport {\n PoHeadlessPromptAdmissionError,\n PoSessionSetupError,\n isPoHeadlessPromptAdmissionError,\n type PoHeadlessCommand,\n type PoHeadlessExecutionContext,\n type PoHeadlessHostService,\n type PoHeadlessHook,\n} from '@agimon-ai/po-core/headless';\nimport { PO_PROFILE_IDENTITY_ENTRY_TYPE } from '@agimon-ai/po-core/profileIdentity';\n\nimport type { ProfileRuntime } from '../../../../../services/profileRuntime/type';\nimport { findProfile, mergeProfiles } from '../../../../../services/profileSources';\nimport type { ProfileSources } from '../../../../../services/profileSources/type';\nimport { PROFILE_COMMAND, profileItems, profileTitle } from '../../../../../services/profileText';\n\ntype ProfileExecution = {\n readonly repoRoot: string;\n readonly environment?: Readonly<Record<string, string | undefined>>;\n};\n\nconst resolveSelected = (execution: ProfileExecution, sources: ProfileSources | undefined, name: string) =>\n findProfile(loadProfiles(execution.repoRoot, execution.environment?.HOME), sources, name);\n\nexport async function readSelectedPersona(\n execution: ProfileExecution & { readonly selection: { readonly profile?: string } },\n sources?: ProfileSources,\n): Promise<string> {\n const name = execution.selection.profile;\n if (!name) return '(no active profile)';\n const profile = resolveSelected(execution, sources, name);\n const prompt = profile.personaPrompt ?? buildPersonaPrompt(profile.personaRoot, profile.persona);\n if (!prompt) throw new Error(`Profile \"${name}\" has no readable persona text`);\n return prompt;\n}\n\nasync function publishSelectedIdentity(\n execution: PoHeadlessExecutionContext,\n sources: ProfileSources | undefined,\n profile: string | undefined,\n): Promise<void> {\n const identity = profile === undefined ? undefined : resolveSelected(execution, sources, profile).identity;\n await execution.session.appendCustomEntry(PO_PROFILE_IDENTITY_ENTRY_TYPE, {\n profile: profile ?? null,\n ...(identity?.name === undefined ? {} : { name: identity.name }),\n ...(identity?.icon === undefined ? {} : { icon: identity.icon }),\n });\n}\n\nexport function createProfileServerCommand(host: PoHeadlessHostService, sources?: ProfileSources): PoHeadlessCommand {\n return {\n name: PROFILE_COMMAND,\n description: 'Show or change the active Po profile.',\n selectionRecovery: true,\n async execute(args, execution) {\n const profiles = mergeProfiles(loadProfiles(execution.repoRoot, execution.environment.HOME), sources);\n let requested = args.trim();\n if (!requested) {\n const selected = await execution.client.request({\n kind: 'select',\n title: profileTitle(execution.selection.profile),\n options: profileItems(profiles),\n });\n if (typeof selected !== 'string') return;\n requested = selected;\n }\n if (requested && !profiles.some(({ name }) => name === requested))\n throw new Error(`Unknown profile: ${requested}`);\n const profile = requested || undefined;\n if (profile === execution.selection.profile && host.inspectCapabilities().ready) return;\n try {\n await host.changeSelection({ axis: 'profile', profile });\n } catch (error) {\n if (isPoHeadlessPromptAdmissionError(error))\n throw new PoSessionSetupError(\n 'Profile integration is unavailable. Restore its credential or choose another profile.',\n );\n throw error;\n }\n await publishSelectedIdentity(execution, sources, profile);\n },\n };\n}\nexport async function assertProfileReady(runtime: ProfileRuntime | undefined): Promise<void> {\n try {\n await runtime?.ready();\n } catch (error) {\n // Ordinary hook failures are advisory. This is a fail-closed admission boundary.\n throw new PoHeadlessPromptAdmissionError(error);\n }\n}\n\nexport function createProfileIdentityHook(sources?: ProfileSources): PoHeadlessHook<'session_start'> {\n return {\n event: 'session_start',\n async handle(_event, execution) {\n await publishSelectedIdentity(execution, sources, execution.selection.profile);\n },\n };\n}\n","import { defineRoutedContribution } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { readProfileSources } from '../../../../../services/profileSources';\nimport { createProfileServerCommand } from '../_lib/profileServer';\nexport default defineRoutedContribution(\n ({ agent, context }: PoServerPluginContext) =>\n agent ? createProfileServerCommand(agent, readProfileSources(context)) : undefined,\n { cardinality: 'optional' },\n);\n","import type { PoHeadlessExecutionContext } from '@agimon-ai/po-core/headless';\nimport { PO_PROFILE_IDENTITY_ENTRY_TYPE } from '@agimon-ai/po-core/profileIdentity';\n\nimport {\n EXTRACTION_COOLDOWN_MS,\n EXTRACTION_INPUT_MAX,\n EXTRACTION_MAX_TOKENS,\n EXTRACTION_SYSTEM_PROMPT,\n EXTRACTION_TIMEOUT_MS,\n MEMORY_BODY_MAX,\n MEMORY_TITLE_MAX,\n} from '../../constants/profileMemory';\nimport { redactSecrets } from '../secretRedaction';\nimport type { ProfileMemoryExtraction, ProfileMemoryExtractionOptions } from './type';\n\nconst ROOT_CURSOR = 'root';\n\nfunction messageText(content: unknown): string {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return '';\n return content\n .map((part) => (part?.type === 'text' && typeof part.text === 'string' ? part.text : ''))\n .filter(Boolean)\n .join('\\n');\n}\n\n/** Human turns plus the final assistant reply, oldest first. Tool calls and results are never sent. */\nfunction transcript(newestFirst: readonly Record<string, unknown>[]): string {\n const lines: string[] = [];\n let assistant = true;\n for (const entry of newestFirst) {\n const message = entry.message as { role?: string; content?: unknown } | undefined;\n const text = messageText(message?.content).trim();\n if (!text) continue;\n if (message?.role === 'user') lines.push(`User: ${text}`);\n else if (message?.role === 'assistant' && assistant) {\n assistant = false;\n lines.push(`Assistant: ${text}`);\n }\n }\n return lines.reverse().join('\\n\\n').slice(-EXTRACTION_INPUT_MAX);\n}\n\nfunction parseEntry(raw: string): { title: string; body: string } | undefined {\n const parsed: unknown = JSON.parse(raw.replace(/^\\s*```(?:json)?\\s*|\\s*```\\s*$/g, ''));\n if (typeof parsed !== 'object' || parsed === null) throw new Error('Memory extraction returned a non-object');\n const { title, body } = parsed as Record<string, unknown>;\n if (typeof title !== 'string' || typeof body !== 'string') throw new Error('Memory extraction returned a bad shape');\n if (!body.trim()) return undefined;\n return { title: title.trim().slice(0, MEMORY_TITLE_MAX) || 'Untitled', body: body.trim().slice(0, MEMORY_BODY_MAX) };\n}\n\nexport function createProfileMemoryExtraction(options: ProfileMemoryExtractionOptions): ProfileMemoryExtraction {\n const { store, runtime, now = Date.now } = options;\n let inflight: Promise<void> | undefined;\n let controller: AbortController | undefined;\n let lastProfile: string | undefined;\n\n const run = async (\n execution: PoHeadlessExecutionContext,\n profile: string,\n generation: number,\n env: string[],\n selectionSignal: AbortSignal,\n ) => {\n const sourceKey = execution.sessionId;\n const fresh: Record<string, unknown>[] = [];\n let newest: string | undefined;\n const state = await store.readSource(profile, sourceKey);\n let found = false;\n for await (const entry of execution.session.entriesNewestFirst({ type: 'message' })) {\n if (typeof entry.id !== 'string') continue;\n newest ??= entry.id;\n if (entry.id === state?.cursor) {\n found = true;\n break;\n }\n fresh.push(entry);\n }\n const head = newest ?? ROOT_CURSOR;\n // First sight or a missing cursor: start from now instead of reading history nobody asked to keep.\n if (!state) {\n await store.initSource(profile, sourceKey, head);\n return;\n }\n const epoch = await store.epoch(profile);\n // Stop at the newest identity marker of a different profile, so its turns never feed this profile.\n let boundary = -1;\n for await (const marker of execution.session.entriesNewestFirst({\n type: 'custom',\n customType: PO_PROFILE_IDENTITY_ENTRY_TYPE,\n limit: 50,\n })) {\n if ((marker.data as { profile?: unknown } | undefined)?.profile !== profile) {\n boundary = Number(marker.id);\n break;\n }\n }\n if (Number.isFinite(boundary)) {\n for (let index = fresh.length - 1; index >= 0; index--)\n if (Number(fresh[index]!.id) <= boundary) fresh.splice(index, 1);\n }\n // Turns written under another profile are skipped, never sent to this profile's memory.\n if (!found || lastProfile !== profile || fresh.length === 0 || now() - state.lastRunAt < EXTRACTION_COOLDOWN_MS) {\n if (!found || lastProfile !== profile) {\n await store.commitExtraction(profile, {\n sourceKey,\n expectedEpoch: epoch,\n expectedCursor: state.cursor,\n nextCursor: head,\n });\n }\n return;\n }\n const model = execution.model ? `${execution.model.provider}/${execution.model.id}` : undefined;\n if (!model || !execution.textCompletion?.available(model)) return;\n const input = redactSecrets(transcript(fresh), env);\n if (!input) return;\n controller = new AbortController();\n const raw = await execution.textCompletion.complete(model, {\n systemPrompt: EXTRACTION_SYSTEM_PROMPT,\n input,\n maxTokens: EXTRACTION_MAX_TOKENS,\n signal: AbortSignal.any([controller.signal, selectionSignal, AbortSignal.timeout(EXTRACTION_TIMEOUT_MS)]),\n recordUsage: true,\n });\n if (runtime.readSelection().generation !== generation) return;\n const entry = parseEntry(raw);\n await store.commitExtraction(profile, {\n sourceKey,\n expectedEpoch: epoch,\n expectedCursor: state.cursor,\n nextCursor: head,\n ...(entry ? { entry: redactSecrets(entry, env) } : {}),\n });\n };\n\n return {\n settle(execution) {\n if (inflight || !options.automatic()) return;\n const selection = runtime.readSelection();\n const profile = selection.profileName;\n if (profile === undefined) return;\n inflight = run(execution, profile, selection.generation, Object.values(selection.env ?? {}), selection.signal)\n .catch((error: unknown) => options.onError(error, execution))\n .finally(() => {\n lastProfile = profile;\n controller = undefined;\n inflight = undefined;\n });\n },\n dispose() {\n controller?.abort();\n },\n };\n}\n","import { PO_CONFIG_SERVICE } from '@agimon-ai/po-config';\nimport { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoHeadlessExecutionContext, PoHeadlessHook } from '@agimon-ai/po-core/headless';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { EXTRACTION_STATUS_SOURCE } from '../../../../../constants/profileMemory';\nimport { createProfileMemoryExtraction } from '../../../../../services/profileMemoryExtraction';\nimport type { ProfileMemoryExtraction } from '../../../../../services/profileMemoryExtraction/type';\nimport { requireProfileMemoryStore } from '../../../../../services/profileMemoryStore';\nimport type { ProfileRuntime } from '../../../../../services/profileRuntime/type';\n\nexport default defineHook(\n ({ root, context }: WithRoot<PoServerPluginContext, ProfileRuntime | undefined>): PoHeadlessHook<'agent_settled'> => {\n let extraction: ProfileMemoryExtraction | undefined;\n return {\n event: 'agent_settled',\n handle(_event: Readonly<Record<string, unknown>>, execution: PoHeadlessExecutionContext) {\n if (!root) return;\n extraction ??= createProfileMemoryExtraction({\n store: requireProfileMemoryStore(context),\n runtime: root,\n automatic: () => context.get(PO_CONFIG_SERVICE)?.getSnapshot().settings.profileMemory?.automatic === true,\n onError: (error, failed) =>\n failed.client.setStatus(\n EXTRACTION_STATUS_SOURCE,\n `Memory extraction failed: ${error instanceof Error ? error.message : String(error)}`,\n ),\n });\n extraction.settle(execution);\n },\n };\n },\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { ProfileRuntime } from '../../../../../services/profileRuntime/type';\nimport { assertProfileReady } from '../_lib/profileServer';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, ProfileRuntime | undefined>) => ({\n async handle() {\n await assertProfileReady(root);\n },\n}));\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoHeadlessExecutionContext } from '@agimon-ai/po-core/headless';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { ProfileRuntime } from '../../../../../services/profileRuntime/type';\nimport { readProfileSources } from '../../../../../services/profileSources';\nimport { assertProfileReady, createProfileIdentityHook } from '../_lib/profileServer';\n\nexport default defineHook(({ root, context }: WithRoot<PoServerPluginContext, ProfileRuntime | undefined>) => {\n const identityHook = createProfileIdentityHook(readProfileSources(context));\n return {\n ...identityHook,\n async handle(event: Readonly<Record<string, unknown>>, execution: PoHeadlessExecutionContext) {\n await assertProfileReady(root);\n await identityHook.handle(event, execution);\n },\n };\n});\n","import { defineResource } from '@agimon-ai/po-core/extensionFile';\nimport { packageResourcePath, readPackageResource } from '@agimon-ai/po-core/serverPlugin';\n\nexport default defineResource({\n name: 'codemode-how-to-memory',\n description:\n '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.',\n kind: 'skill' as const,\n pinned: true,\n path: packageResourcePath(import.meta.url, 'src/prompts/codemode-how-to-memory/SKILL.md'),\n read: () => readPackageResource(import.meta.url, 'src/prompts/codemode-how-to-memory/SKILL.md'),\n});\n","import { defineResource } from '@agimon-ai/po-core/extensionFile';\nimport { packageResourcePath, readPackageResource } from '@agimon-ai/po-core/serverPlugin';\n\nexport default defineResource({\n name: 'help-how-to-profile',\n description:\n 'Configure Po profile discovery, personas, environment defaults, and precedence in profiles.yaml. Use when creating or changing personal or repository profiles. Do not use for config.yaml runtime settings, modes.yaml, or domains.yaml.',\n when: { state: { 'minor-mode': 'help' }, attribution: { kind: 'minor' as const, mode: 'help' } },\n kind: 'skill' as const,\n path: packageResourcePath(import.meta.url, 'src/prompts/help-how-to-profile/SKILL.md'),\n read: () => readPackageResource(import.meta.url, 'src/prompts/help-how-to-profile/SKILL.md'),\n});\n","import { defineResource } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { readProfileSources } from '../../../../../services/profileSources';\nimport { readSelectedPersona } from '../_lib/profileServer';\nexport default defineResource(({ context }: PoServerPluginContext) => ({\n name: 'po/profile-config',\n kind: 'context' as const,\n read: (execution: Parameters<typeof readSelectedPersona>[0]) =>\n readSelectedPersona(execution, readProfileSources(context)),\n}));\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type PoServerSessionPlugin } from '@agimon-ai/po-core/serverPlugin';\nimport { composeServerProviderOverrides } from '@agimon-ai/po-core/serverPlugin';\nimport { composeRootHooks, composeRootInjects } from '@agimon-ai/po-core/extensionFile';\n\nimport rootGlobal from '../src/extensions/(backend)/root.server';\nimport rootSession from '../src/extensions/workspaces/sessions/(backend)/root.server';\nimport apiRoute from '../src/extensions/workspaces/sessions/(backend)/api/profile/route.server';\nimport commandProfile from '../src/extensions/workspaces/sessions/(backend)/command/profile.server';\nimport hookAgentSettled from '../src/extensions/workspaces/sessions/(backend)/hook/agentSettled.server';\nimport hookBeforeAgentStart from '../src/extensions/workspaces/sessions/(backend)/hook/beforeAgentStart.server';\nimport hookSessionStart from '../src/extensions/workspaces/sessions/(backend)/hook/sessionStart.server';\nimport resourceCodemodeHowToMemory from '../src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-memory.server';\nimport resourceHelpHowToProfile from '../src/extensions/workspaces/sessions/(backend)/resource/help-how-to-profile.server';\nimport resourceProfileConfig from '../src/extensions/workspaces/sessions/(backend)/resource/profileConfig.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\n/* v8 ignore next -- generated normalization branch */\nconst defined = <T>(values: readonly (T | undefined)[]): T[] =>\n values.filter((value): value is T => value !== undefined);\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nexport const serverPlugin = defineServerPlugin({\n name: '@agimon-ai/po-profile',\n providerOverrides: composeServerProviderOverrides(rootGlobal, rootSession),\n injects: composeRootInjects({ global: [rootGlobal], workspace: [rootGlobal], session: [rootGlobal, rootSession] }),\n global: async (context) => {\n const scopeGlobal = await context.scopeRoot('global', rootGlobal, context);\n return {\n ...composeRootHooks(scopeGlobal),\n services: [...(scopeGlobal.services ?? [])],\n };\n },\n workspace: async (context) => {\n const scopeGlobal = await context.scopeRoot('global', rootGlobal, context);\n return {\n ...composeRootHooks(scopeGlobal),\n services: [...(scopeGlobal.services ?? [])],\n };\n },\n session: async (context) => {\n const scopeGlobal = await context.scopeRoot('global', rootGlobal, context);\n const contextGlobal = { ...context, root: scopeGlobal.value };\n const scopeSession = await context.scopeRoot('session', rootSession, contextGlobal);\n const contextSession = { ...contextGlobal, root: scopeSession.value };\n return {\n ...composeRootHooks(scopeGlobal, scopeSession),\n get api(): PoServerSessionPlugin['api'] { return [at(apiRoute, contextSession)]; },\n get commands(): PoServerSessionPlugin['commands'] { return defined([via({ name: 'profile' }, at(commandProfile, contextSession))]); },\n get hooks(): PoServerSessionPlugin['hooks'] { return [via({ event: 'agent_settled' }, at(hookAgentSettled, contextSession)), via({ event: 'before_agent_start' }, at(hookBeforeAgentStart, contextSession)), via({ event: 'session_start' }, at(hookSessionStart, contextSession))]; },\n get resources(): PoServerSessionPlugin['resources'] { return [at(resourceCodemodeHowToMemory, contextSession), at(resourceHelpHowToProfile, contextSession), at(resourceProfileConfig, contextSession)]; },\n services: [...(scopeGlobal.services ?? []), ...(scopeSession.services ?? [])],\n get activities(): PoServerSessionPlugin['activities'] { return [...(scopeGlobal.activities ?? []), ...(scopeSession.activities ?? [])]; },\n };\n },\n});\n\nexport default serverPlugin;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,MAAa,+BAA+B;AAE5C,MAAa,kCAAkC;AAE/C,MAAa,2BAA2B;AACxC,MAAa,sBAAsB;AAInC,MAAa,kBAAkB;AAO/B,MAAa,wBAAwB;AAErC,MAAa,wBAAwB;AACrC,MAAa,2BAA2B;AACxC,MAAa,2BACX;;;;ACOF,MAAM,aAAgC,CACpC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCF;AAwBA,MAAM,cAAc;AAEpB,SAAS,YAAY,OAAgB,MAAc,KAAqB;CACtE,IAAI,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,GAAG,MAAM,IAAI,MAAM,UAAU,KAAK,4BAA4B;CAC3G,IAAI,MAAM,SAAS,KAAK,MAAM,IAAI,MAAM,UAAU,KAAK,mBAAmB,IAAI,YAAY;CAC1F,OAAO;AACT;AAEA,SAAS,eAAe,SAAwB;CAC9C,IAAI,OAAO,YAAY,YAAY,CAAC,SAAS,MAAM,IAAI,MAAM,2CAA2C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AWC,qBAAa,aAAa;EAClF,MAAM,iBAAiB;GAAE,GAAG;GAAe,MAAM,aAAa;EAAM;EACpE,OAAO;GACL,IAAA,GAAGE,iCAAAA,iBAAAA,CAAiB,aAAa,YAAY;GAC7C,IAAI,MAAoC;IAAE,OAAO,CAAC,GAAGC,sBAAU,cAAc,CAAC;GAAG;GACjF,IAAI,WAA8C;IAAE,OAAO,QAAQ,CAAC,IAAI,EAAE,MAAM,UAAU,GAAG,GAAGC,wBAAgB,cAAc,CAAC,CAAC,CAAC;GAAG;GACpI,IAAI,QAAwC;IAAE,OAAO;KAAC,IAAI,EAAE,OAAO,gBAAgB,GAAG,GAAGC,6BAAkB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,qBAAqB,GAAG,GAAGC,iCAAsB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,gBAAgB,GAAG,GAAGC,6BAAkB,cAAc,CAAC;IAAC;GAAG;GACrR,IAAI,YAAgD;IAAE,OAAO;KAAC,GAAGC,uCAA6B,cAAc;KAAG,GAAGC,oCAA0B,cAAc;KAAG,GAAGC,8BAAuB,cAAc;IAAC;GAAG;GACzM,UAAU,CAAC,GAAI,YAAY,YAAY,CAAC,GAAI,GAAI,aAAa,YAAY,CAAC,CAAE;GAC5E,IAAI,aAAkD;IAAE,OAAO,CAAC,GAAI,YAAY,cAAc,CAAC,GAAI,GAAI,aAAa,cAAc,CAAC,CAAE;GAAG;EAC1I;CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"server.cjs","names":["path","getOrThrow","nodeHost","defineRoot","createProfileSources","createProfileSecrets","findProfile","loadProfiles","nodeHost","PO_SERVER_SCOPE_SERVICE","requirePoServerScope","defineServiceContract","PROFILE_SECRETS_SERVICE","PROFILE_SOURCES_SERVICE","PO_FS_SERVICE","PO_SQLITE_SERVICE","requirePoFs","requirePoSqlite","path","poHomeDirectory","BACKGROUND_CONTEXT","defineRoot","loadProfiles","nodeHost","findProfile","readProfileSources","mergeProfiles","createProfileRuntime","PoHeadlessPromptAdmissionError","createProfileRuntimePlugin","PO_CODEMODE_SERVICE","readPoCodemode","runCleanups","defineRoute","findProfile","loadProfiles","buildPersonaPrompt","PO_PROFILE_IDENTITY_ENTRY_TYPE","PROFILE_COMMAND","mergeProfiles","profileTitle","profileItems","isPoHeadlessPromptAdmissionError","PoSessionSetupError","PoHeadlessPromptAdmissionError","defineRoutedContribution","readProfileSources","PO_PROFILE_IDENTITY_ENTRY_TYPE","redactSecrets","defineHook","PO_CONFIG_SERVICE","defineHook","defineHook","readProfileSources","defineResource","packageResourcePath","readPackageResource","defineResource","packageResourcePath","readPackageResource","defineResource","readProfileSources","defineServerPlugin","composeServerProviderOverrides","rootGlobal","rootSession","composeRootInjects","composeRootHooks","apiRoute","commandProfile","hookAgentSettled","hookBeforeAgentStart","hookSessionStart","resourceCodemodeHowToMemory","resourceHelpHowToProfile","resourceProfileConfig"],"sources":["../../src/constants/profileMemory.ts","../../src/services/profileMemoryStore/index.ts","../../src/extensions/(backend)/root.server.ts","../../src/services/profileMemoryNamespace/index.ts","../../src/extensions/workspaces/sessions/(backend)/root.server.ts","../../src/extensions/workspaces/sessions/(backend)/api/profile/route.server.ts","../../src/extensions/workspaces/sessions/(backend)/_lib/profileServer.ts","../../src/extensions/workspaces/sessions/(backend)/command/profile.server.ts","../../src/services/profileMemoryExtraction/index.ts","../../src/extensions/workspaces/sessions/(backend)/hook/agentSettled.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/beforeAgentStart.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/sessionStart.server.ts","../../src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-memory.server.ts","../../src/extensions/workspaces/sessions/(backend)/resource/help-how-to-profile.server.ts","../../src/extensions/workspaces/sessions/(backend)/resource/profileConfig.server.ts","../../generated/server.ts"],"sourcesContent":["export const PROFILE_MEMORY_STORE_SERVICE = 'po/profile-memory-store';\n\nexport const PROFILE_MEMORY_NAMESPACE_SOURCE = '@agimon-ai/po-profile/memory';\n\nexport const PROFILE_MEMORY_DIRECTORY = 'profile-memory';\nexport const PROFILE_MEMORY_FILE = 'memory.sqlite';\nexport const PROFILE_MEMORY_DIRECTORY_MODE = 0o700;\n\nexport const MEMORY_TITLE_MAX = 256;\nexport const MEMORY_BODY_MAX = 16 * 1024;\nexport const MEMORY_QUERY_MAX = 512;\nexport const MEMORY_EXCERPT_MAX = 512;\nexport const MEMORY_LIMIT_DEFAULT = 10;\nexport const MEMORY_LIMIT_MAX = 50;\n\nexport const EXTRACTION_COOLDOWN_MS = 5 * 60 * 1000;\nexport const EXTRACTION_TIMEOUT_MS = 60 * 1000;\nexport const EXTRACTION_INPUT_MAX = 64 * 1024;\nexport const EXTRACTION_MAX_TOKENS = 2048;\nexport const EXTRACTION_STATUS_SOURCE = 'profile-memory';\nexport const EXTRACTION_SYSTEM_PROMPT =\n 'You maintain long-term memory about how one person likes to work. ' +\n 'From the conversation, extract at most one durable fact: a stable preference, convention, or decision the person stated or clearly showed. ' +\n 'Ignore task progress, code details, and anything derivable from a repository. Never include secrets. ' +\n 'Reply with JSON only: {\"title\": string, \"body\": string}. Use an empty body when nothing is worth keeping.';\n","import path from 'node:path';\n\nimport { getOrThrow, nodeHost } from '@agimon-ai/po-core/platform';\nimport type { Context } from '@deepseek-ai/cordis';\n\nimport {\n MEMORY_BODY_MAX,\n MEMORY_EXCERPT_MAX,\n MEMORY_LIMIT_DEFAULT,\n MEMORY_LIMIT_MAX,\n MEMORY_QUERY_MAX,\n MEMORY_TITLE_MAX,\n PROFILE_MEMORY_DIRECTORY_MODE,\n PROFILE_MEMORY_FILE,\n PROFILE_MEMORY_STORE_SERVICE,\n} from '../../constants/profileMemory';\nimport type {\n ProfileMemoryEntry,\n ProfileMemoryHit,\n ProfileMemoryOrigin,\n ProfileMemoryStore,\n ProfileMemoryStoreOptions,\n} from './type';\n\ntype Database = Awaited<ReturnType<ProfileMemoryStoreOptions['sqlite']['open']>>;\ntype Executor = Parameters<Parameters<Database['transaction']>[0]>[0];\n\n/** Append only: a database at version N applies MIGRATIONS[N..]. */\nconst MIGRATIONS: readonly string[] = [\n `\n CREATE TABLE profile_memory_entries (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n profile TEXT NOT NULL,\n title TEXT NOT NULL,\n body TEXT NOT NULL,\n revision INTEGER NOT NULL,\n origin TEXT NOT NULL CHECK (origin IN ('manual', 'extracted')),\n source_key TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n );\n CREATE INDEX profile_memory_entries_recent ON profile_memory_entries(profile, updated_at DESC, seq DESC);\n CREATE UNIQUE INDEX profile_memory_entries_source ON profile_memory_entries(profile, source_key)\n WHERE origin = 'extracted';\n CREATE VIRTUAL TABLE profile_memory_fts USING fts5(\n title, body, content='profile_memory_entries', content_rowid='seq'\n );\n CREATE TRIGGER profile_memory_ai AFTER INSERT ON profile_memory_entries BEGIN\n INSERT INTO profile_memory_fts(rowid, title, body) VALUES (new.seq, new.title, new.body);\n END;\n CREATE TRIGGER profile_memory_ad AFTER DELETE ON profile_memory_entries BEGIN\n INSERT INTO profile_memory_fts(profile_memory_fts, rowid, title, body)\n VALUES ('delete', old.seq, old.title, old.body);\n END;\n CREATE TRIGGER profile_memory_au AFTER UPDATE ON profile_memory_entries BEGIN\n INSERT INTO profile_memory_fts(profile_memory_fts, rowid, title, body)\n VALUES ('delete', old.seq, old.title, old.body);\n INSERT INTO profile_memory_fts(rowid, title, body) VALUES (new.seq, new.title, new.body);\n END;\n CREATE TABLE profile_memory_sources (\n profile TEXT NOT NULL,\n source_key TEXT NOT NULL,\n cursor TEXT NOT NULL,\n last_run_at INTEGER NOT NULL,\n suppressed INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (profile, source_key)\n );\n CREATE TABLE profile_memory_epochs (profile TEXT PRIMARY KEY, epoch INTEGER NOT NULL);\n `,\n];\n\ninterface EntryRow {\n seq: number;\n id: string;\n title: string;\n body: string;\n revision: number;\n origin: ProfileMemoryOrigin;\n source_key: string | null;\n created_at: number;\n updated_at: number;\n}\n\ninterface HitRow {\n seq: number;\n id: string;\n title: string;\n excerpt: string;\n revision: number;\n origin: ProfileMemoryOrigin;\n updated_at: number;\n}\n\nconst HIT_COLUMNS = 'e.seq, e.id, e.title, substr(e.body, 1, ?) AS excerpt, e.revision, e.origin, e.updated_at';\n\nfunction requireText(value: unknown, name: string, max: number): string {\n if (typeof value !== 'string' || !value.trim()) throw new Error(`Memory ${name} must be a non-empty string`);\n if (value.length > max) throw new Error(`Memory ${name} must be at most ${max} characters`);\n return value;\n}\n\nfunction requireProfile(profile: unknown): void {\n if (typeof profile !== 'string' || !profile) throw new Error('Memory profile must be a non-empty string');\n}\n\nfunction clampLimit(limit: number | undefined): number {\n if (limit === undefined) return MEMORY_LIMIT_DEFAULT;\n if (!Number.isInteger(limit) || limit < 1) throw new Error('Memory limit must be a positive integer');\n return Math.min(limit, MEMORY_LIMIT_MAX);\n}\n\n/** Quoted word tokens only, so FTS operators (`\"`, `*`, `NEAR`, `OR`) in user text stay literal. */\nfunction ftsQuery(query: string): string | undefined {\n const tokens = query.match(/[\\p{L}\\p{N}_]+/gu);\n return tokens ? tokens.map((token) => `\"${token}\"`).join(' ') : undefined;\n}\n\nfunction toHit(row: HitRow): ProfileMemoryHit {\n return {\n id: row.id,\n title: row.title,\n excerpt: row.excerpt,\n revision: row.revision,\n origin: row.origin,\n updatedAt: row.updated_at,\n };\n}\n\nfunction toEntry(row: EntryRow): ProfileMemoryEntry {\n return {\n id: row.id,\n title: row.title,\n body: row.body,\n revision: row.revision,\n origin: row.origin,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nasync function migrate(db: Database): Promise<void> {\n await db.transaction(async (tx) => {\n await tx.exec('CREATE TABLE IF NOT EXISTS profile_memory_meta (version INTEGER NOT NULL)');\n const current = await tx.get<{ version: number }>('SELECT version FROM profile_memory_meta');\n if (!current) await tx.run('INSERT INTO profile_memory_meta (version) VALUES (0)');\n const version = current?.version ?? 0;\n if (version > MIGRATIONS.length) throw new Error('Profile memory database is newer than this Po version');\n for (let index = version; index < MIGRATIONS.length; index++) await tx.exec(MIGRATIONS[index]!);\n await tx.run('UPDATE profile_memory_meta SET version = ?', MIGRATIONS.length);\n });\n}\n\n/**\n * Creates the memory directory owner-only, like `mkdirSync(directory, { recursive: true, mode: 0o700 })`.\n * Same behaviour as po-session's `ensurePrivateDirectory`, which is not exported; existing directories keep their mode.\n */\nasync function ensurePrivateDirectory(options: ProfileMemoryStoreOptions): Promise<void> {\n const missing: string[] = [];\n for (let current = path.resolve(options.directory); !getOrThrow(await options.fs.exists(current, options.context));) {\n missing.unshift(current);\n const parent = path.dirname(current);\n if (parent === current) break;\n current = parent;\n }\n if (missing.length === 0) return;\n getOrThrow(await options.fs.createDir(options.directory, { recursive: true }, options.context));\n for (const created of missing) await nodeHost.setMode(created, PROFILE_MEMORY_DIRECTORY_MODE);\n}\n\nexport async function createProfileMemoryStore(options: ProfileMemoryStoreOptions): Promise<ProfileMemoryStore> {\n const now = options.now ?? Date.now;\n const newId = options.id ?? (() => crypto.randomUUID());\n await ensurePrivateDirectory(options);\n const file = getOrThrow(await options.fs.joinPath([options.directory, PROFILE_MEMORY_FILE], options.context));\n const db = await options.sqlite.open(file, options.context);\n try {\n await migrate(db);\n } catch (error) {\n await db.close();\n throw error;\n }\n\n const findRow = (tx: Executor, profile: string, id: string) =>\n tx.get<EntryRow>('SELECT * FROM profile_memory_entries WHERE profile = ? AND id = ?', profile, id);\n const epochOf = async (tx: Executor, profile: string) =>\n (await tx.get<{ epoch: number }>('SELECT epoch FROM profile_memory_epochs WHERE profile = ?', profile))?.epoch ?? 0;\n const suppress = (tx: Executor, profile: string, sourceKey: string) =>\n tx.run('UPDATE profile_memory_sources SET suppressed = 1 WHERE profile = ? AND source_key = ?', profile, sourceKey);\n const checkRevision = (row: EntryRow | undefined, expected: number | undefined): EntryRow => {\n if (!row) throw new Error('Memory not found');\n if (expected !== undefined && row.revision !== expected) throw new Error('Memory changed since it was read');\n return row;\n };\n\n return {\n async search(profile, query, limit) {\n requireProfile(profile);\n requireText(query, 'query', MEMORY_QUERY_MAX);\n const match = ftsQuery(query);\n if (!match) return [];\n const rows = await db.all<HitRow>(\n `SELECT ${HIT_COLUMNS} FROM profile_memory_fts f JOIN profile_memory_entries e ON e.seq = f.rowid\n WHERE profile_memory_fts MATCH ? AND e.profile = ?\n ORDER BY bm25(profile_memory_fts), e.seq DESC LIMIT ?`,\n MEMORY_EXCERPT_MAX,\n match,\n profile,\n clampLimit(limit),\n );\n return rows.map(toHit);\n },\n\n async list(profile, listOptions = {}) {\n requireProfile(profile);\n const limit = clampLimit(listOptions.limit);\n let at: number | null = null;\n let seq: number | null = null;\n if (listOptions.cursor !== undefined) {\n const match = /^(\\d+)\\.(\\d+)$/.exec(listOptions.cursor);\n if (!match) throw new Error('Invalid memory cursor');\n at = Number(match[1]);\n seq = Number(match[2]);\n }\n const rows = await db.all<HitRow>(\n `SELECT ${HIT_COLUMNS} FROM profile_memory_entries e\n WHERE e.profile = ? AND (? IS NULL OR e.updated_at < ? OR (e.updated_at = ? AND e.seq < ?))\n ORDER BY e.updated_at DESC, e.seq DESC LIMIT ?`,\n MEMORY_EXCERPT_MAX,\n profile,\n at,\n at,\n at,\n seq,\n limit + 1,\n );\n const page = rows.slice(0, limit);\n const last = page[page.length - 1];\n return {\n entries: page.map(toHit),\n ...(rows.length > limit && last ? { nextCursor: `${last.updated_at}.${last.seq}` } : {}),\n };\n },\n\n async read(profile, id) {\n requireProfile(profile);\n const row = await db.get<EntryRow>(\n 'SELECT * FROM profile_memory_entries WHERE profile = ? AND id = ?',\n profile,\n id,\n );\n return row && toEntry(row);\n },\n\n async write(profile, input) {\n requireProfile(profile);\n const title = requireText(input.title, 'title', MEMORY_TITLE_MAX);\n const body = requireText(input.body, 'body', MEMORY_BODY_MAX);\n return db.transaction(async (tx) => {\n const at = now();\n if (input.id === undefined) {\n const id = newId();\n await tx.run(\n `INSERT INTO profile_memory_entries (id, profile, title, body, revision, origin, created_at, updated_at)\n VALUES (?, ?, ?, ?, 1, 'manual', ?, ?)`,\n id,\n profile,\n title,\n body,\n at,\n at,\n );\n return toEntry((await findRow(tx, profile, id))!);\n }\n const row = checkRevision(await findRow(tx, profile, input.id), input.expectedRevision);\n // A person-curated edit takes the entry over, so extraction must not rewrite or recreate it.\n if (row.origin === 'extracted' && row.source_key !== null) await suppress(tx, profile, row.source_key);\n await tx.run(\n `UPDATE profile_memory_entries\n SET title = ?, body = ?, revision = revision + 1, origin = 'manual', source_key = NULL, updated_at = ?\n WHERE profile = ? AND id = ?`,\n title,\n body,\n at,\n profile,\n input.id,\n );\n return toEntry((await findRow(tx, profile, input.id))!);\n });\n },\n\n async forget(profile, id, expectedRevision) {\n requireProfile(profile);\n await db.transaction(async (tx) => {\n const row = checkRevision(await findRow(tx, profile, id), expectedRevision);\n await tx.run('DELETE FROM profile_memory_entries WHERE profile = ? AND id = ?', profile, id);\n await tx.run(\n `INSERT INTO profile_memory_epochs (profile, epoch) VALUES (?, 1)\n ON CONFLICT(profile) DO UPDATE SET epoch = epoch + 1`,\n profile,\n );\n if (row.origin === 'extracted' && row.source_key !== null) await suppress(tx, profile, row.source_key);\n });\n },\n\n async epoch(profile) {\n return (\n (await db.get<{ epoch: number }>('SELECT epoch FROM profile_memory_epochs WHERE profile = ?', profile))\n ?.epoch ?? 0\n );\n },\n\n async readSource(profile, sourceKey) {\n const row = await db.get<{ cursor: string; last_run_at: number; suppressed: number }>(\n 'SELECT cursor, last_run_at, suppressed FROM profile_memory_sources WHERE profile = ? AND source_key = ?',\n profile,\n sourceKey,\n );\n return row && { cursor: row.cursor, lastRunAt: row.last_run_at, suppressed: row.suppressed === 1 };\n },\n\n async initSource(profile, sourceKey, cursor) {\n return db.transaction(async (tx) => {\n const existing = await tx.get<{ cursor: string }>(\n 'SELECT cursor FROM profile_memory_sources WHERE profile = ? AND source_key = ?',\n profile,\n sourceKey,\n );\n if (existing) return false;\n await tx.run(\n 'INSERT INTO profile_memory_sources (profile, source_key, cursor, last_run_at) VALUES (?, ?, ?, ?)',\n profile,\n sourceKey,\n cursor,\n now(),\n );\n return true;\n });\n },\n\n async commitExtraction(profile, commit) {\n return db.transaction(async (tx) => {\n if ((await epochOf(tx, profile)) !== commit.expectedEpoch) return false;\n const source = await tx.get<{ cursor: string; suppressed: number }>(\n 'SELECT cursor, suppressed FROM profile_memory_sources WHERE profile = ? AND source_key = ?',\n profile,\n commit.sourceKey,\n );\n if (!source || source.suppressed === 1 || source.cursor !== commit.expectedCursor) return false;\n const at = now();\n if (commit.entry) {\n const title = requireText(commit.entry.title, 'title', MEMORY_TITLE_MAX);\n const body = requireText(commit.entry.body, 'body', MEMORY_BODY_MAX);\n const existing = await tx.get<{ id: string }>(\n \"SELECT id FROM profile_memory_entries WHERE profile = ? AND origin = 'extracted' AND source_key = ?\",\n profile,\n commit.sourceKey,\n );\n if (existing)\n await tx.run(\n 'UPDATE profile_memory_entries SET title = ?, body = ?, revision = revision + 1, updated_at = ? WHERE id = ?',\n title,\n body,\n at,\n existing.id,\n );\n else\n await tx.run(\n `INSERT INTO profile_memory_entries\n (id, profile, title, body, revision, origin, source_key, created_at, updated_at)\n VALUES (?, ?, ?, ?, 1, 'extracted', ?, ?, ?)`,\n newId(),\n profile,\n title,\n body,\n commit.sourceKey,\n at,\n at,\n );\n }\n await tx.run(\n 'UPDATE profile_memory_sources SET cursor = ?, last_run_at = ? WHERE profile = ? AND source_key = ?',\n commit.nextCursor,\n at,\n profile,\n commit.sourceKey,\n );\n return true;\n });\n },\n\n close: () => db.close(),\n };\n}\n\nexport function createProfileMemoryStorePlugin(store: ProfileMemoryStore): (context: Context) => void {\n return (context) => {\n context.provide(PROFILE_MEMORY_STORE_SERVICE, store);\n };\n}\n\nexport function requireProfileMemoryStore(context: Context): ProfileMemoryStore {\n const service = context.get(PROFILE_MEMORY_STORE_SERVICE);\n if (!service) throw new Error('Profile memory store is unavailable');\n return service;\n}\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n 'po/profile-memory-store': ProfileMemoryStore;\n }\n}\n","import path from 'node:path';\n\nimport { loadProfiles } from '@agimon-ai/po-config/profiles';\nimport { defineRoot, defineServiceContract } from '@agimon-ai/po-core/extensionFile';\nimport { poHomeDirectory } from '@agimon-ai/po-core/piSettings';\nimport {\n BACKGROUND_CONTEXT,\n nodeHost,\n PO_FS_SERVICE,\n PO_SQLITE_SERVICE,\n requirePoFs,\n requirePoSqlite,\n} from '@agimon-ai/po-core/platform';\nimport {\n PO_SERVER_SCOPE_SERVICE,\n requirePoServerScope,\n type PoServerPluginContext,\n} from '@agimon-ai/po-core/serverPlugin';\n\nimport { PROFILE_MEMORY_DIRECTORY, PROFILE_MEMORY_STORE_SERVICE } from '../../constants/profileMemory';\nimport { PROFILE_SECRETS_SERVICE } from '../../constants/profileSecrets';\nimport { PROFILE_SOURCES_SERVICE } from '../../constants/profileSources';\nimport { createProfileMemoryStore } from '../../services/profileMemoryStore';\nimport { createProfileSecrets } from '../../services/profileSecrets';\nimport { createProfileSources, findProfile } from '../../services/profileSources';\n\nexport default defineRoot(({ host }: PoServerPluginContext) => {\n const environment = Object.freeze({ ...host.context.environment });\n const sources = createProfileSources();\n const secrets = createProfileSecrets({\n readBinding: (cwd, profile, homeDirectory) =>\n findProfile(loadProfiles(cwd, homeDirectory ?? environment.HOME ?? nodeHost.homeDirectory()), sources, profile)\n .integration,\n });\n return {\n value: secrets,\n services: [\n async (context) => {\n // Each server level has its own Cordis root, so a plain Cordis service here never reaches\n // sessions. Publish through the scope; the bindings unwind with this fiber.\n await context.inject([PO_SERVER_SCOPE_SERVICE], async (scoped) => {\n const scope = requirePoServerScope(scoped);\n await scope.provide(defineServiceContract(PROFILE_SECRETS_SERVICE, { scope: host.scope }), secrets);\n await scope.provide(defineServiceContract(PROFILE_SOURCES_SERVICE, { scope: host.scope }), sources);\n });\n },\n async (context) => {\n // Each server level has its own Cordis root. Publish through the scope so descendants\n // see the store even when they reuse this root instead of rerunning its services.\n await context.inject([PO_FS_SERVICE, PO_SQLITE_SERVICE, PO_SERVER_SCOPE_SERVICE], async (scoped) => {\n const homeDirectory = host.context.homeDirectory;\n if (!homeDirectory) throw new Error('Profile memory requires an explicit host home directory.');\n const store = await createProfileMemoryStore({\n fs: requirePoFs(scoped),\n sqlite: requirePoSqlite(scoped),\n directory: path.join(poHomeDirectory(homeDirectory, environment), PROFILE_MEMORY_DIRECTORY),\n context: BACKGROUND_CONTEXT,\n });\n // A standalone workspace or session can build this root too, and owns its binding there.\n const contract = defineServiceContract(PROFILE_MEMORY_STORE_SERVICE, { scope: host.scope });\n let release: () => Promise<void>;\n try {\n release = await requirePoServerScope(scoped).provide(contract, store);\n } catch (error) {\n await store.close();\n throw error;\n }\n return async () => {\n await release();\n await store.close();\n };\n });\n },\n ],\n };\n});\n","import type { PoCodemodeNamespace } from '@agimon-ai/po-core/codemode';\n\nimport { MEMORY_LIMIT_DEFAULT, MEMORY_LIMIT_MAX } from '../../constants/profileMemory';\nimport type { ProfileMemoryNamespaceOptions } from './type';\n\nconst DECLARATIONS = `interface MemoryHit {\n id: string;\n title: string;\n /** First 512 characters of the body; call memory.read for the rest. */\n excerpt: string;\n revision: number;\n origin: 'manual' | 'extracted';\n updatedAt: number;\n}\n\ninterface MemoryEntry {\n id: string;\n title: string;\n body: string;\n revision: number;\n origin: 'manual' | 'extracted';\n createdAt: number;\n updatedAt: number;\n}\n\ndeclare const memory: {\n /** Full-text search over the selected profile's memory, best match first. Plain words only; operators are literal. */\n search(input: { query: string; limit?: number }): Promise<MemoryHit[]>;\n /** Newest first. Pass the previous page's nextCursor to continue. */\n list(input?: { cursor?: string; limit?: number }): Promise<{ entries: MemoryHit[]; nextCursor?: string }>;\n /** The whole entry, or null when the id is not in this profile's memory. */\n read(input: { id: string }): Promise<MemoryEntry | null>;\n /** Create an entry, or replace one when id is given. Pass expectedRevision from your last read to avoid overwriting a newer edit. */\n write(input: { title: string; body: string; id?: string; expectedRevision?: number }): Promise<MemoryEntry>;\n /** Delete an entry. expectedRevision is required. */\n forget(input: { id: string; expectedRevision: number }): Promise<{ forgotten: true }>;\n};`;\n\nfunction record(input: unknown): Record<string, unknown> {\n if (typeof input !== 'object' || input === null || Array.isArray(input))\n throw new Error('Memory call expects an object');\n return input as Record<string, unknown>;\n}\n\nfunction text(value: unknown, name: string): string {\n if (typeof value !== 'string') throw new Error(`Memory ${name} must be a string`);\n return value;\n}\n\nfunction optionalNumber(value: unknown, name: string): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== 'number' || !Number.isInteger(value)) throw new Error(`Memory ${name} must be an integer`);\n return value;\n}\n\nexport function createProfileMemoryNamespace(options: ProfileMemoryNamespaceOptions): PoCodemodeNamespace {\n const { store, runtime } = options;\n /** Resolves the selected profile for one call; `recheck` rejects results that outlived a profile switch. */\n const scoped = async <T>(\n signal: AbortSignal,\n operation: (profile: string) => Promise<T>,\n recheck: boolean,\n ): Promise<T> => {\n options.assertAvailable();\n const before = runtime.readSelection();\n if (before.profileName === undefined) throw new Error('No profile is selected');\n if (signal.aborted) throw new Error('Memory call was cancelled');\n const result = await operation(before.profileName);\n if (recheck && runtime.readSelection().generation !== before.generation)\n throw new Error('The selected profile changed during the memory call');\n return result;\n };\n\n return {\n name: 'memory',\n summary: `Search and curate the selected profile's long-term memory (full-text search, ${MEMORY_LIMIT_DEFAULT} results by default, ${MEMORY_LIMIT_MAX} at most). Unavailable when no profile is selected.`,\n declarations: DECLARATIONS,\n portable: true,\n bind(run) {\n if (run.sessionId !== options.sessionId) throw new Error('Memory belongs to another session');\n return {\n search: async (input: unknown) => {\n const args = record(input);\n return scoped(\n run.signal,\n (profile) => store.search(profile, text(args.query, 'query'), optionalNumber(args.limit, 'limit')),\n true,\n );\n },\n list: async (input: unknown = {}) => {\n const args = record(input);\n const cursor = args.cursor === undefined ? undefined : text(args.cursor, 'cursor');\n return scoped(\n run.signal,\n (profile) => store.list(profile, { cursor, limit: optionalNumber(args.limit, 'limit') }),\n true,\n );\n },\n read: async (input: unknown) => {\n const args = record(input);\n return scoped(run.signal, async (profile) => (await store.read(profile, text(args.id, 'id'))) ?? null, true);\n },\n write: async (input: unknown) => {\n const args = record(input);\n return scoped(\n run.signal,\n (profile) =>\n store.write(profile, {\n title: text(args.title, 'title'),\n body: text(args.body, 'body'),\n ...(args.id === undefined ? {} : { id: text(args.id, 'id') }),\n ...(args.expectedRevision === undefined\n ? {}\n : { expectedRevision: optionalNumber(args.expectedRevision, 'expectedRevision') }),\n }),\n false,\n );\n },\n forget: async (input: unknown) => {\n const args = record(input);\n const expectedRevision = optionalNumber(args.expectedRevision, 'expectedRevision');\n if (expectedRevision === undefined) throw new Error('Memory expectedRevision is required');\n return scoped(\n run.signal,\n async (profile) => {\n await store.forget(profile, text(args.id, 'id'), expectedRevision);\n return { forgotten: true as const };\n },\n false,\n );\n },\n };\n },\n };\n}\n","import { loadProfiles } from '@agimon-ai/po-config/profiles';\nimport { PO_CODEMODE_SERVICE, readPoCodemode } from '@agimon-ai/po-core/codemode';\nimport { defineRoot, runCleanups } from '@agimon-ai/po-core/extensionFile';\nimport { PoHeadlessPromptAdmissionError } from '@agimon-ai/po-core/headless';\nimport { nodeHost } from '@agimon-ai/po-core/platform';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { PROFILE_MEMORY_NAMESPACE_SOURCE, PROFILE_MEMORY_STORE_SERVICE } from '../../../../constants/profileMemory';\nimport { createProfileMemoryNamespace } from '../../../../services/profileMemoryNamespace';\nimport { requireProfileMemoryStore } from '../../../../services/profileMemoryStore';\nimport { createProfileRuntime, createProfileRuntimePlugin } from '../../../../services/profileRuntime';\nimport { findProfile, mergeProfiles, readProfileSources } from '../../../../services/profileSources';\n\nexport default defineRoot(({ agent, host, signal, context }: PoServerPluginContext) => {\n if (!agent) return { value: undefined };\n const execution = agent.context;\n const scope = { workspaceId: host.context.workspaceId };\n const readProfiles = () => loadProfiles(execution.repoRoot, execution.environment.HOME ?? nodeHost.homeDirectory());\n const readProfile = (profileName: string) =>\n findProfile(readProfiles(), readProfileSources(context, scope), profileName);\n const unregisterResolver = agent.registerInitialSelectionResolver((selection) => {\n if (selection.profile === undefined) return selection;\n const profiles = mergeProfiles(readProfiles(), readProfileSources(context, scope));\n return profiles.some(({ name }) => name === selection.profile) ? selection : { ...selection, profile: undefined };\n });\n // The host validates the restored name before applying its first selection.\n const runtime = createProfileRuntime({\n readBinding: (profileName) => readProfile(profileName).integration,\n readEnv: (profileName) => readProfile(profileName).env,\n });\n const unsubscribe = agent.subscribeSelection(async (selection, applied) => {\n try {\n // A refresh re-reads the same profile's env and binding after it was edited on disk.\n await runtime.select(selection.profile, { force: applied?.refresh?.includes('profile') === true });\n } catch (error) {\n throw new PoHeadlessPromptAdmissionError(error);\n }\n });\n const invalidate = () => runtime.invalidate();\n signal.addEventListener('abort', invalidate, { once: true });\n if (signal.aborted) runtime.invalidate();\n return {\n value: runtime,\n services: [\n createProfileRuntimePlugin(runtime),\n (serviceContext) => {\n serviceContext.inject([PO_CODEMODE_SERVICE, PROFILE_MEMORY_STORE_SERVICE], (injected) => {\n const codemode = readPoCodemode(injected);\n if (!codemode) return undefined;\n const registration = codemode.register(\n PROFILE_MEMORY_NAMESPACE_SOURCE,\n createProfileMemoryNamespace({\n store: requireProfileMemoryStore(injected),\n runtime,\n sessionId: execution.sessionId,\n assertAvailable: () => {\n if (signal.aborted) throw new Error('Profile memory session is unavailable.');\n },\n }),\n );\n return () => registration.dispose();\n });\n },\n ],\n async onDispose() {\n await runCleanups(\n [\n unregisterResolver,\n unsubscribe,\n () => signal.removeEventListener('abort', invalidate),\n () => runtime.dispose(),\n ],\n 'Profile cleanup failed.',\n );\n },\n };\n});\n","import { defineRoute } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nexport default defineRoute(({ agent }: PoServerPluginContext) => ({\n basePath: 'profile',\n start: () => ({\n fetch(request: Request) {\n if (new URL(request.url).pathname !== '/current') return Response.json({ error: 'Not found' }, { status: 404 });\n if (request.method !== 'GET')\n return Response.json({ error: 'Method not allowed' }, { status: 405, headers: { Allow: 'GET' } });\n if (!agent) return Response.json({ error: 'Session agent unavailable' }, { status: 404 });\n const selection = agent.context.selection;\n return Response.json({ profile: selection.profile ?? null });\n },\n close() {},\n }),\n}));\n","import { buildPersonaPrompt, loadProfiles } from '@agimon-ai/po-config/profiles';\nimport {\n PoHeadlessPromptAdmissionError,\n PoSessionSetupError,\n isPoHeadlessPromptAdmissionError,\n type PoHeadlessCommand,\n type PoHeadlessExecutionContext,\n type PoHeadlessHostService,\n type PoHeadlessHook,\n} from '@agimon-ai/po-core/headless';\nimport { PO_PROFILE_IDENTITY_ENTRY_TYPE } from '@agimon-ai/po-core/profileIdentity';\n\nimport type { ProfileRuntime } from '../../../../../services/profileRuntime/type';\nimport { findProfile, mergeProfiles } from '../../../../../services/profileSources';\nimport type { ProfileSources } from '../../../../../services/profileSources/type';\nimport { PROFILE_COMMAND, profileItems, profileTitle } from '../../../../../services/profileText';\n\ntype ProfileExecution = {\n readonly repoRoot: string;\n readonly environment?: Readonly<Record<string, string | undefined>>;\n};\n\nconst resolveSelected = (execution: ProfileExecution, sources: ProfileSources | undefined, name: string) =>\n findProfile(loadProfiles(execution.repoRoot, execution.environment?.HOME), sources, name);\n\nexport async function readSelectedPersona(\n execution: ProfileExecution & { readonly selection: { readonly profile?: string } },\n sources?: ProfileSources,\n): Promise<string> {\n const name = execution.selection.profile;\n if (!name) return '(no active profile)';\n const profile = resolveSelected(execution, sources, name);\n const prompt = profile.personaPrompt ?? buildPersonaPrompt(profile.personaRoot, profile.persona);\n if (!prompt) throw new Error(`Profile \"${name}\" has no readable persona text`);\n return prompt;\n}\n\nasync function publishSelectedIdentity(\n execution: PoHeadlessExecutionContext,\n sources: ProfileSources | undefined,\n profile: string | undefined,\n): Promise<void> {\n const identity = profile === undefined ? undefined : resolveSelected(execution, sources, profile).identity;\n await execution.session.appendCustomEntry(PO_PROFILE_IDENTITY_ENTRY_TYPE, {\n profile: profile ?? null,\n ...(identity?.name === undefined ? {} : { name: identity.name }),\n ...(identity?.icon === undefined ? {} : { icon: identity.icon }),\n });\n}\n\nexport function createProfileServerCommand(host: PoHeadlessHostService, sources?: ProfileSources): PoHeadlessCommand {\n return {\n name: PROFILE_COMMAND,\n description: 'Show or change the active Po profile.',\n selectionRecovery: true,\n async execute(args, execution) {\n const profiles = mergeProfiles(loadProfiles(execution.repoRoot, execution.environment.HOME), sources);\n let requested = args.trim();\n if (!requested) {\n const selected = await execution.client.request({\n kind: 'select',\n title: profileTitle(execution.selection.profile),\n options: profileItems(profiles),\n });\n if (typeof selected !== 'string') return;\n requested = selected;\n }\n if (requested && !profiles.some(({ name }) => name === requested))\n throw new Error(`Unknown profile: ${requested}`);\n const profile = requested || undefined;\n if (profile === execution.selection.profile && host.inspectCapabilities().ready) return;\n try {\n await host.changeSelection({ axis: 'profile', profile });\n } catch (error) {\n if (isPoHeadlessPromptAdmissionError(error))\n throw new PoSessionSetupError(\n 'Profile integration is unavailable. Restore its credential or choose another profile.',\n );\n throw error;\n }\n await publishSelectedIdentity(execution, sources, profile);\n },\n };\n}\nexport async function assertProfileReady(runtime: ProfileRuntime | undefined): Promise<void> {\n try {\n await runtime?.ready();\n } catch (error) {\n // Ordinary hook failures are advisory. This is a fail-closed admission boundary.\n throw new PoHeadlessPromptAdmissionError(error);\n }\n}\n\nexport function createProfileIdentityHook(sources?: ProfileSources): PoHeadlessHook<'session_start'> {\n return {\n event: 'session_start',\n async handle(_event, execution) {\n await publishSelectedIdentity(execution, sources, execution.selection.profile);\n },\n };\n}\n","import { defineRoutedContribution } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { readProfileSources } from '../../../../../services/profileSources';\nimport { createProfileServerCommand } from '../_lib/profileServer';\nexport default defineRoutedContribution(\n ({ agent, host, context }: PoServerPluginContext) =>\n agent\n ? createProfileServerCommand(agent, readProfileSources(context, { workspaceId: host.context.workspaceId }))\n : undefined,\n { cardinality: 'optional' },\n);\n","import type { PoHeadlessExecutionContext } from '@agimon-ai/po-core/headless';\nimport { PO_PROFILE_IDENTITY_ENTRY_TYPE } from '@agimon-ai/po-core/profileIdentity';\n\nimport {\n EXTRACTION_COOLDOWN_MS,\n EXTRACTION_INPUT_MAX,\n EXTRACTION_MAX_TOKENS,\n EXTRACTION_SYSTEM_PROMPT,\n EXTRACTION_TIMEOUT_MS,\n MEMORY_BODY_MAX,\n MEMORY_TITLE_MAX,\n} from '../../constants/profileMemory';\nimport { redactSecrets } from '../secretRedaction';\nimport type { ProfileMemoryExtraction, ProfileMemoryExtractionOptions } from './type';\n\nconst ROOT_CURSOR = 'root';\n\nfunction messageText(content: unknown): string {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return '';\n return content\n .map((part) => (part?.type === 'text' && typeof part.text === 'string' ? part.text : ''))\n .filter(Boolean)\n .join('\\n');\n}\n\n/** Human turns plus the final assistant reply, oldest first. Tool calls and results are never sent. */\nfunction transcript(newestFirst: readonly Record<string, unknown>[]): string {\n const lines: string[] = [];\n let assistant = true;\n for (const entry of newestFirst) {\n const message = entry.message as { role?: string; content?: unknown } | undefined;\n const text = messageText(message?.content).trim();\n if (!text) continue;\n if (message?.role === 'user') lines.push(`User: ${text}`);\n else if (message?.role === 'assistant' && assistant) {\n assistant = false;\n lines.push(`Assistant: ${text}`);\n }\n }\n return lines.reverse().join('\\n\\n').slice(-EXTRACTION_INPUT_MAX);\n}\n\nfunction parseEntry(raw: string): { title: string; body: string } | undefined {\n const parsed: unknown = JSON.parse(raw.replace(/^\\s*```(?:json)?\\s*|\\s*```\\s*$/g, ''));\n if (typeof parsed !== 'object' || parsed === null) throw new Error('Memory extraction returned a non-object');\n const { title, body } = parsed as Record<string, unknown>;\n if (typeof title !== 'string' || typeof body !== 'string') throw new Error('Memory extraction returned a bad shape');\n if (!body.trim()) return undefined;\n return { title: title.trim().slice(0, MEMORY_TITLE_MAX) || 'Untitled', body: body.trim().slice(0, MEMORY_BODY_MAX) };\n}\n\nexport function createProfileMemoryExtraction(options: ProfileMemoryExtractionOptions): ProfileMemoryExtraction {\n const { store, runtime, now = Date.now } = options;\n let inflight: Promise<void> | undefined;\n let controller: AbortController | undefined;\n let lastProfile: string | undefined;\n\n const run = async (\n execution: PoHeadlessExecutionContext,\n profile: string,\n generation: number,\n env: string[],\n selectionSignal: AbortSignal,\n ) => {\n const sourceKey = execution.sessionId;\n const fresh: Record<string, unknown>[] = [];\n let newest: string | undefined;\n const state = await store.readSource(profile, sourceKey);\n let found = false;\n for await (const entry of execution.session.entriesNewestFirst({ type: 'message' })) {\n if (typeof entry.id !== 'string') continue;\n newest ??= entry.id;\n if (entry.id === state?.cursor) {\n found = true;\n break;\n }\n fresh.push(entry);\n }\n const head = newest ?? ROOT_CURSOR;\n // First sight or a missing cursor: start from now instead of reading history nobody asked to keep.\n if (!state) {\n await store.initSource(profile, sourceKey, head);\n return;\n }\n const epoch = await store.epoch(profile);\n // Stop at the newest identity marker of a different profile, so its turns never feed this profile.\n let boundary = -1;\n for await (const marker of execution.session.entriesNewestFirst({\n type: 'custom',\n customType: PO_PROFILE_IDENTITY_ENTRY_TYPE,\n limit: 50,\n })) {\n if ((marker.data as { profile?: unknown } | undefined)?.profile !== profile) {\n boundary = Number(marker.id);\n break;\n }\n }\n if (Number.isFinite(boundary)) {\n for (let index = fresh.length - 1; index >= 0; index--)\n if (Number(fresh[index]!.id) <= boundary) fresh.splice(index, 1);\n }\n // Turns written under another profile are skipped, never sent to this profile's memory.\n if (!found || lastProfile !== profile || fresh.length === 0 || now() - state.lastRunAt < EXTRACTION_COOLDOWN_MS) {\n if (!found || lastProfile !== profile) {\n await store.commitExtraction(profile, {\n sourceKey,\n expectedEpoch: epoch,\n expectedCursor: state.cursor,\n nextCursor: head,\n });\n }\n return;\n }\n const model = execution.model ? `${execution.model.provider}/${execution.model.id}` : undefined;\n if (!model || !execution.textCompletion?.available(model)) return;\n const input = redactSecrets(transcript(fresh), env);\n if (!input) return;\n controller = new AbortController();\n const raw = await execution.textCompletion.complete(model, {\n systemPrompt: EXTRACTION_SYSTEM_PROMPT,\n input,\n maxTokens: EXTRACTION_MAX_TOKENS,\n signal: AbortSignal.any([controller.signal, selectionSignal, AbortSignal.timeout(EXTRACTION_TIMEOUT_MS)]),\n recordUsage: true,\n });\n if (runtime.readSelection().generation !== generation) return;\n const entry = parseEntry(raw);\n await store.commitExtraction(profile, {\n sourceKey,\n expectedEpoch: epoch,\n expectedCursor: state.cursor,\n nextCursor: head,\n ...(entry ? { entry: redactSecrets(entry, env) } : {}),\n });\n };\n\n return {\n settle(execution) {\n if (inflight || !options.automatic()) return;\n const selection = runtime.readSelection();\n const profile = selection.profileName;\n if (profile === undefined) return;\n inflight = run(execution, profile, selection.generation, Object.values(selection.env ?? {}), selection.signal)\n .catch((error: unknown) => options.onError(error, execution))\n .finally(() => {\n lastProfile = profile;\n controller = undefined;\n inflight = undefined;\n });\n },\n dispose() {\n controller?.abort();\n },\n };\n}\n","import { PO_CONFIG_SERVICE } from '@agimon-ai/po-config';\nimport { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoHeadlessExecutionContext, PoHeadlessHook } from '@agimon-ai/po-core/headless';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { EXTRACTION_STATUS_SOURCE } from '../../../../../constants/profileMemory';\nimport { createProfileMemoryExtraction } from '../../../../../services/profileMemoryExtraction';\nimport type { ProfileMemoryExtraction } from '../../../../../services/profileMemoryExtraction/type';\nimport { requireProfileMemoryStore } from '../../../../../services/profileMemoryStore';\nimport type { ProfileRuntime } from '../../../../../services/profileRuntime/type';\n\nexport default defineHook(\n ({ root, context }: WithRoot<PoServerPluginContext, ProfileRuntime | undefined>): PoHeadlessHook<'agent_settled'> => {\n let extraction: ProfileMemoryExtraction | undefined;\n return {\n event: 'agent_settled',\n handle(_event: Readonly<Record<string, unknown>>, execution: PoHeadlessExecutionContext) {\n if (!root) return;\n extraction ??= createProfileMemoryExtraction({\n store: requireProfileMemoryStore(context),\n runtime: root,\n automatic: () => context.get(PO_CONFIG_SERVICE)?.getSnapshot().settings.profileMemory?.automatic === true,\n onError: (error, failed) =>\n failed.client.setStatus(\n EXTRACTION_STATUS_SOURCE,\n `Memory extraction failed: ${error instanceof Error ? error.message : String(error)}`,\n ),\n });\n extraction.settle(execution);\n },\n };\n },\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { ProfileRuntime } from '../../../../../services/profileRuntime/type';\nimport { assertProfileReady } from '../_lib/profileServer';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, ProfileRuntime | undefined>) => ({\n async handle() {\n await assertProfileReady(root);\n },\n}));\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoHeadlessExecutionContext } from '@agimon-ai/po-core/headless';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { ProfileRuntime } from '../../../../../services/profileRuntime/type';\nimport { readProfileSources } from '../../../../../services/profileSources';\nimport { assertProfileReady, createProfileIdentityHook } from '../_lib/profileServer';\n\nexport default defineHook(({ root, host, context }: WithRoot<PoServerPluginContext, ProfileRuntime | undefined>) => {\n const identityHook = createProfileIdentityHook(\n readProfileSources(context, { workspaceId: host.context.workspaceId }),\n );\n return {\n ...identityHook,\n async handle(event: Readonly<Record<string, unknown>>, execution: PoHeadlessExecutionContext) {\n await assertProfileReady(root);\n await identityHook.handle(event, execution);\n },\n };\n});\n","import { defineResource } from '@agimon-ai/po-core/extensionFile';\nimport { packageResourcePath, readPackageResource } from '@agimon-ai/po-core/serverPlugin';\n\nexport default defineResource({\n name: 'codemode-how-to-memory',\n description:\n '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.',\n kind: 'skill' as const,\n pinned: true,\n path: packageResourcePath(import.meta.url, 'src/prompts/codemode-how-to-memory/SKILL.md'),\n read: () => readPackageResource(import.meta.url, 'src/prompts/codemode-how-to-memory/SKILL.md'),\n});\n","import { defineResource } from '@agimon-ai/po-core/extensionFile';\nimport { packageResourcePath, readPackageResource } from '@agimon-ai/po-core/serverPlugin';\n\nexport default defineResource({\n name: 'help-how-to-profile',\n description:\n 'Configure Po profile discovery, personas, environment defaults, and precedence in profiles.yaml. Use when creating or changing personal or repository profiles. Do not use for config.yaml runtime settings, modes.yaml, or domains.yaml.',\n when: { state: { 'minor-mode': 'help' }, attribution: { kind: 'minor' as const, mode: 'help' } },\n kind: 'skill' as const,\n path: packageResourcePath(import.meta.url, 'src/prompts/help-how-to-profile/SKILL.md'),\n read: () => readPackageResource(import.meta.url, 'src/prompts/help-how-to-profile/SKILL.md'),\n});\n","import { defineResource } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { readProfileSources } from '../../../../../services/profileSources';\nimport { readSelectedPersona } from '../_lib/profileServer';\nexport default defineResource(({ host, context }: PoServerPluginContext) => ({\n name: 'po/profile-config',\n kind: 'context' as const,\n read: (execution: Parameters<typeof readSelectedPersona>[0]) =>\n readSelectedPersona(execution, readProfileSources(context, { workspaceId: host.context.workspaceId })),\n}));\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type PoServerSessionPlugin } from '@agimon-ai/po-core/serverPlugin';\nimport { composeServerProviderOverrides } from '@agimon-ai/po-core/serverPlugin';\nimport { composeRootHooks, composeRootInjects } from '@agimon-ai/po-core/extensionFile';\n\nimport rootGlobal from '../src/extensions/(backend)/root.server';\nimport rootSession from '../src/extensions/workspaces/sessions/(backend)/root.server';\nimport apiRoute from '../src/extensions/workspaces/sessions/(backend)/api/profile/route.server';\nimport commandProfile from '../src/extensions/workspaces/sessions/(backend)/command/profile.server';\nimport hookAgentSettled from '../src/extensions/workspaces/sessions/(backend)/hook/agentSettled.server';\nimport hookBeforeAgentStart from '../src/extensions/workspaces/sessions/(backend)/hook/beforeAgentStart.server';\nimport hookSessionStart from '../src/extensions/workspaces/sessions/(backend)/hook/sessionStart.server';\nimport resourceCodemodeHowToMemory from '../src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-memory.server';\nimport resourceHelpHowToProfile from '../src/extensions/workspaces/sessions/(backend)/resource/help-how-to-profile.server';\nimport resourceProfileConfig from '../src/extensions/workspaces/sessions/(backend)/resource/profileConfig.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\n/* v8 ignore next -- generated normalization branch */\nconst defined = <T>(values: readonly (T | undefined)[]): T[] =>\n values.filter((value): value is T => value !== undefined);\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nexport const serverPlugin = defineServerPlugin({\n name: '@agimon-ai/po-profile',\n providerOverrides: composeServerProviderOverrides(rootGlobal, rootSession),\n injects: composeRootInjects({ global: [rootGlobal], workspace: [rootGlobal], session: [rootGlobal, rootSession] }),\n global: async (context) => {\n const scopeGlobal = await context.scopeRoot('global', rootGlobal, context);\n return {\n ...composeRootHooks(scopeGlobal),\n services: [...(scopeGlobal.services ?? [])],\n };\n },\n workspace: async (context) => {\n const scopeGlobal = await context.scopeRoot('global', rootGlobal, context);\n return {\n ...composeRootHooks(scopeGlobal),\n services: [...(scopeGlobal.services ?? [])],\n };\n },\n session: async (context) => {\n const scopeGlobal = await context.scopeRoot('global', rootGlobal, context);\n const contextGlobal = { ...context, root: scopeGlobal.value };\n const scopeSession = await context.scopeRoot('session', rootSession, contextGlobal);\n const contextSession = { ...contextGlobal, root: scopeSession.value };\n return {\n ...composeRootHooks(scopeGlobal, scopeSession),\n get api(): PoServerSessionPlugin['api'] { return [at(apiRoute, contextSession)]; },\n get commands(): PoServerSessionPlugin['commands'] { return defined([via({ name: 'profile' }, at(commandProfile, contextSession))]); },\n get hooks(): PoServerSessionPlugin['hooks'] { return [via({ event: 'agent_settled' }, at(hookAgentSettled, contextSession)), via({ event: 'before_agent_start' }, at(hookBeforeAgentStart, contextSession)), via({ event: 'session_start' }, at(hookSessionStart, contextSession))]; },\n get resources(): PoServerSessionPlugin['resources'] { return [at(resourceCodemodeHowToMemory, contextSession), at(resourceHelpHowToProfile, contextSession), at(resourceProfileConfig, contextSession)]; },\n services: [...(scopeGlobal.services ?? []), ...(scopeSession.services ?? [])],\n get activities(): PoServerSessionPlugin['activities'] { return [...(scopeGlobal.activities ?? []), ...(scopeSession.activities ?? [])]; },\n };\n },\n});\n\nexport default serverPlugin;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,MAAa,+BAA+B;AAE5C,MAAa,kCAAkC;AAE/C,MAAa,2BAA2B;AACxC,MAAa,sBAAsB;AAInC,MAAa,kBAAkB;AAO/B,MAAa,wBAAwB;AAErC,MAAa,wBAAwB;AACrC,MAAa,2BAA2B;AACxC,MAAa,2BACX;;;;ACOF,MAAM,aAAgC,CACpC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCF;AAwBA,MAAM,cAAc;AAEpB,SAAS,YAAY,OAAgB,MAAc,KAAqB;CACtE,IAAI,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,GAAG,MAAM,IAAI,MAAM,UAAU,KAAK,4BAA4B;CAC3G,IAAI,MAAM,SAAS,KAAK,MAAM,IAAI,MAAM,UAAU,KAAK,mBAAmB,IAAI,YAAY;CAC1F,OAAO;AACT;AAEA,SAAS,eAAe,SAAwB;CAC9C,IAAI,OAAO,YAAY,YAAY,CAAC,SAAS,MAAM,IAAI,MAAM,2CAA2C;AAC1G;AAEA,SAAS,WA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,YAAY;EAC1B,MAAM,cAAc,MAAM,QAAQ,UAAU,UAAUH,uBAAY,OAAO;EACzE,MAAM,gBAAgB;GAAE,GAAG;GAAS,MAAM,YAAY;EAAM;EAC5D,MAAM,eAAe,MAAM,QAAQ,UAAU,WAAWC,qBAAa,aAAa;EAClF,MAAM,iBAAiB;GAAE,GAAG;GAAe,MAAM,aAAa;EAAM;EACpE,OAAO;GACL,IAAA,GAAGE,iCAAAA,iBAAAA,CAAiB,aAAa,YAAY;GAC7C,IAAI,MAAoC;IAAE,OAAO,CAAC,GAAGC,sBAAU,cAAc,CAAC;GAAG;GACjF,IAAI,WAA8C;IAAE,OAAO,QAAQ,CAAC,IAAI,EAAE,MAAM,UAAU,GAAG,GAAGC,wBAAgB,cAAc,CAAC,CAAC,CAAC;GAAG;GACpI,IAAI,QAAwC;IAAE,OAAO;KAAC,IAAI,EAAE,OAAO,gBAAgB,GAAG,GAAGC,6BAAkB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,qBAAqB,GAAG,GAAGC,iCAAsB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,gBAAgB,GAAG,GAAGC,6BAAkB,cAAc,CAAC;IAAC;GAAG;GACrR,IAAI,YAAgD;IAAE,OAAO;KAAC,GAAGC,uCAA6B,cAAc;KAAG,GAAGC,oCAA0B,cAAc;KAAG,GAAGC,8BAAuB,cAAc;IAAC;GAAG;GACzM,UAAU,CAAC,GAAI,YAAY,YAAY,CAAC,GAAI,GAAI,aAAa,YAAY,CAAC,CAAE;GAC5E,IAAI,aAAkD;IAAE,OAAO,CAAC,GAAI,YAAY,cAAc,CAAC,GAAI,GAAI,aAAa,cAAc,CAAC,CAAE;GAAG;EAC1I;CACF;AACF,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as PROFILE_SECRETS_SERVICE, S as PROFILE_SOURCES_SERVICE, b as createProfileRuntimePlugin, f as findProfile, g as createProfileSecrets, i as profileItems, l as redactSecrets, m as readProfileSources, p as mergeProfiles, s as profileTitle, t as PROFILE_COMMAND, u as createProfileSources, y as createProfileRuntime } from "../profileText-
|
|
1
|
+
import { C as PROFILE_SECRETS_SERVICE, S as PROFILE_SOURCES_SERVICE, b as createProfileRuntimePlugin, f as findProfile, g as createProfileSecrets, i as profileItems, l as redactSecrets, m as readProfileSources, p as mergeProfiles, s as profileTitle, t as PROFILE_COMMAND, u as createProfileSources, y as createProfileRuntime } from "../profileText-DCMunq1f.mjs";
|
|
2
2
|
import { buildPersonaPrompt, loadProfiles } from "@agimon-ai/po-config/profiles";
|
|
3
3
|
import { PO_SERVER_SCOPE_SERVICE, composeServerProviderOverrides, defineServerPlugin, packageResourcePath, readPackageResource, requirePoServerScope } from "@agimon-ai/po-core/serverPlugin";
|
|
4
4
|
import { composeRootHooks, composeRootInjects, defineHook, defineResource, defineRoot, defineRoute, defineRoutedContribution, defineServiceContract, runCleanups } from "@agimon-ai/po-core/extensionFile";
|
|
@@ -412,14 +412,15 @@ function createProfileMemoryNamespace(options) {
|
|
|
412
412
|
}
|
|
413
413
|
//#endregion
|
|
414
414
|
//#region src/extensions/workspaces/sessions/(backend)/root.server.ts
|
|
415
|
-
var root_server_default = defineRoot(({ agent, signal, context }) => {
|
|
415
|
+
var root_server_default = defineRoot(({ agent, host, signal, context }) => {
|
|
416
416
|
if (!agent) return { value: void 0 };
|
|
417
417
|
const execution = agent.context;
|
|
418
|
+
const scope = { workspaceId: host.context.workspaceId };
|
|
418
419
|
const readProfiles = () => loadProfiles(execution.repoRoot, execution.environment.HOME ?? nodeHost.homeDirectory());
|
|
419
|
-
const readProfile = (profileName) => findProfile(readProfiles(), readProfileSources(context), profileName);
|
|
420
|
+
const readProfile = (profileName) => findProfile(readProfiles(), readProfileSources(context, scope), profileName);
|
|
420
421
|
const unregisterResolver = agent.registerInitialSelectionResolver((selection) => {
|
|
421
422
|
if (selection.profile === void 0) return selection;
|
|
422
|
-
return mergeProfiles(readProfiles(), readProfileSources(context)).some(({ name }) => name === selection.profile) ? selection : {
|
|
423
|
+
return mergeProfiles(readProfiles(), readProfileSources(context, scope)).some(({ name }) => name === selection.profile) ? selection : {
|
|
423
424
|
...selection,
|
|
424
425
|
profile: void 0
|
|
425
426
|
};
|
|
@@ -552,7 +553,7 @@ function createProfileIdentityHook(sources) {
|
|
|
552
553
|
}
|
|
553
554
|
//#endregion
|
|
554
555
|
//#region src/extensions/workspaces/sessions/(backend)/command/profile.server.ts
|
|
555
|
-
var profile_server_default = defineRoutedContribution(({ agent, context }) => agent ? createProfileServerCommand(agent, readProfileSources(context)) : void 0, { cardinality: "optional" });
|
|
556
|
+
var profile_server_default = defineRoutedContribution(({ agent, host, context }) => agent ? createProfileServerCommand(agent, readProfileSources(context, { workspaceId: host.context.workspaceId })) : void 0, { cardinality: "optional" });
|
|
556
557
|
//#endregion
|
|
557
558
|
//#region src/services/profileMemoryExtraction/index.ts
|
|
558
559
|
const ROOT_CURSOR = "root";
|
|
@@ -703,8 +704,8 @@ var beforeAgentStart_server_default = defineHook(({ root }) => ({ async handle()
|
|
|
703
704
|
} }));
|
|
704
705
|
//#endregion
|
|
705
706
|
//#region src/extensions/workspaces/sessions/(backend)/hook/sessionStart.server.ts
|
|
706
|
-
var sessionStart_server_default = defineHook(({ root, context }) => {
|
|
707
|
-
const identityHook = createProfileIdentityHook(readProfileSources(context));
|
|
707
|
+
var sessionStart_server_default = defineHook(({ root, host, context }) => {
|
|
708
|
+
const identityHook = createProfileIdentityHook(readProfileSources(context, { workspaceId: host.context.workspaceId }));
|
|
708
709
|
return {
|
|
709
710
|
...identityHook,
|
|
710
711
|
async handle(event, execution) {
|
|
@@ -741,10 +742,10 @@ var help_how_to_profile_server_default = defineResource({
|
|
|
741
742
|
});
|
|
742
743
|
//#endregion
|
|
743
744
|
//#region src/extensions/workspaces/sessions/(backend)/resource/profileConfig.server.ts
|
|
744
|
-
var profileConfig_server_default = defineResource(({ context }) => ({
|
|
745
|
+
var profileConfig_server_default = defineResource(({ host, context }) => ({
|
|
745
746
|
name: "po/profile-config",
|
|
746
747
|
kind: "context",
|
|
747
|
-
read: (execution) => readSelectedPersona(execution, readProfileSources(context))
|
|
748
|
+
read: (execution) => readSelectedPersona(execution, readProfileSources(context, { workspaceId: host.context.workspaceId }))
|
|
748
749
|
}));
|
|
749
750
|
//#endregion
|
|
750
751
|
//#region generated/server.ts
|