@agimon-ai/po-profile 0.0.0-alpha.95 → 0.0.0-alpha.97
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 +6 -4
- package/dist/extensions/server.cjs.map +1 -1
- package/dist/extensions/server.mjs +6 -4
- package/dist/extensions/server.mjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.mts +8 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{profileText-DzGJatp2.mjs → profileText-C0kldV5Y.mjs} +23 -7
- package/dist/profileText-C0kldV5Y.mjs.map +1 -0
- package/dist/{profileText-D_VL4Sd4.cjs → profileText-CVvJlSay.cjs} +23 -7
- package/dist/profileText-CVvJlSay.cjs.map +1 -0
- package/package.json +9 -9
- package/dist/profileText-D_VL4Sd4.cjs.map +0 -1
- package/dist/profileText-DzGJatp2.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-CVvJlSay.cjs");
|
|
28
28
|
let _agimon_ai_po_core_extensionFile = require("@agimon-ai/po-core/extensionFile");
|
|
29
29
|
let _agimon_ai_po_config_profiles = require("@agimon-ai/po-config/profiles");
|
|
30
30
|
let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
|
|
@@ -646,12 +646,14 @@ var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)(({ ag
|
|
|
646
646
|
});
|
|
647
647
|
//#endregion
|
|
648
648
|
//#region src/services/launchProfiles/index.ts
|
|
649
|
-
/**
|
|
649
|
+
/** Presentation only: the persona, voice, environment and binding of a profile never leave the host. */
|
|
650
650
|
function launchItem(profile, sourceId) {
|
|
651
|
-
const { name, icon } = profile.identity ?? {};
|
|
651
|
+
const { name, icon, role, contact } = profile.identity ?? {};
|
|
652
652
|
const identity = {
|
|
653
653
|
...name === void 0 ? {} : { name },
|
|
654
|
-
...icon === void 0 ? {} : { icon }
|
|
654
|
+
...icon === void 0 ? {} : { icon },
|
|
655
|
+
...role === void 0 ? {} : { role },
|
|
656
|
+
...contact === void 0 ? {} : { contact }
|
|
655
657
|
};
|
|
656
658
|
return {
|
|
657
659
|
name: profile.name,
|
|
@@ -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","findProfile","loadProfiles","buildPersonaPrompt","PO_PROFILE_IDENTITY_ENTRY_TYPE","profileWarningText","PROFILE_COMMAND","mergeProfiles","profileTitle","profileItems","isPoHeadlessPromptAdmissionError","PoSessionSetupError","PoHeadlessPromptAdmissionError","defineRoot","nodeHost","loadProfiles","findProfile","readProfileSources","readInitialProfileOutcome","mergeProfiles","loadProfilesAsync","requirePoFs","BACKGROUND_CONTEXT","resolveInitialProfile","createProfileRuntime","PoHeadlessPromptAdmissionError","createProfileRuntimePlugin","PROFILE_INITIAL_OUTCOME_SERVICE","PO_CODEMODE_SERVICE","readPoCodemode","runCleanups","createDeadline","FILE_PROFILE_SOURCE_ID","defineRoute","loadProfiles","nodeHost","readProfileSources","defineRoute","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","apiRoute2","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)/_lib/profileServer.ts","../../src/extensions/workspaces/sessions/(backend)/_lib/profileSession.ts","../../src/extensions/workspaces/sessions/(backend)/root.server.ts","../../src/services/launchProfiles/index.ts","../../src/extensions/workspaces/(backend)/api/profile/route.server.ts","../../src/extensions/workspaces/sessions/(backend)/api/profile/route.server.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 { 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 { profileWarningText } from '../../../../../services/profileResolution';\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';\nimport { type ProfileSessionState } from './profileSession';\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 journalIdentity(\n execution: PoHeadlessExecutionContext,\n sources: ProfileSources | undefined,\n profile: string | undefined,\n state: ProfileSessionState,\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 state.journaled = { profile };\n}\n\n/**\n * Journals the marker once per selection: the command and the host both report a change, and the second\n * report finds it already journaled.\n */\nexport async function publishSelectedIdentity(\n execution: PoHeadlessExecutionContext,\n sources: ProfileSources | undefined,\n profile: string | undefined,\n state: ProfileSessionState,\n): Promise<void> {\n if (state.journaled !== undefined && state.journaled.profile === profile) return;\n await journalIdentity(execution, sources, profile, state);\n}\n\n/** Shows why the session started without its profile, exactly once. A notice failure never blocks the session. */\nexport async function deliverProfileWarning(\n execution: PoHeadlessExecutionContext,\n state: ProfileSessionState,\n): Promise<void> {\n const warning = state.warning;\n if (warning === undefined || state.warned) return;\n state.warned = true;\n try {\n await execution.client.notify({ level: 'warning', body: profileWarningText(warning) });\n } catch {\n console.warn('[po-profile] Profile notice delivery unavailable.');\n }\n}\n\nexport function createProfileServerCommand(\n host: PoHeadlessHostService,\n state: ProfileSessionState,\n sources?: ProfileSources,\n): 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, state);\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(\n state: ProfileSessionState,\n sources?: ProfileSources,\n): PoHeadlessHook<'session_start'> {\n return {\n event: 'session_start',\n async handle(_event, execution) {\n // The first marker of a session is always journaled; later ones are journaled as selections change.\n await journalIdentity(execution, sources, execution.selection.profile, state);\n state.started = true;\n await deliverProfileWarning(execution, state);\n },\n };\n}\n","import type { Context } from '@deepseek-ai/cordis';\n\nimport type { InitialProfileWarning } from '../../../../../services/profileResolution/type';\n\n/**\n * Session bookkeeping shared by roots, hooks and commands through Cordis.\n */\nexport interface ProfileSessionState {\n /** True once `session_start` journaled the first identity marker; earlier selections are not journaled. */\n started: boolean;\n /** The profile last journaled as an identity marker. Absent means nothing was journaled yet. */\n journaled?: { readonly profile: string | undefined };\n /** Why the session started without the profile it was meant to have, until the notice is shown. */\n warning?: InitialProfileWarning;\n /** True once the warning was shown, so it appears exactly once. */\n warned: boolean;\n}\n\nconst PROFILE_SESSION_STATE_SERVICE = 'po/profile-session-state';\n\nexport function profileSessionState(context: Context): ProfileSessionState {\n // Contributions read their own service while the package fiber is still mounting.\n let state = context.get(PROFILE_SESSION_STATE_SERVICE, false) as ProfileSessionState | undefined;\n if (state === undefined) {\n state = { started: false, warned: false };\n context.provide(PROFILE_SESSION_STATE_SERVICE, state);\n }\n return state;\n}\n","import { loadProfiles, loadProfilesAsync } 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, type PoHeadlessSelection } from '@agimon-ai/po-core/headless';\nimport { BACKGROUND_CONTEXT, nodeHost, requirePoFs } from '@agimon-ai/po-core/platform';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { PROFILE_INITIAL_OUTCOME_SERVICE } from '../../../../constants/profileInitialOutcome';\nimport { PROFILE_MEMORY_NAMESPACE_SOURCE, PROFILE_MEMORY_STORE_SERVICE } from '../../../../constants/profileMemory';\nimport { createProfileMemoryNamespace } from '../../../../services/profileMemoryNamespace';\nimport { requireProfileMemoryStore } from '../../../../services/profileMemoryStore';\nimport { readInitialProfileOutcome, resolveInitialProfile } from '../../../../services/profileResolution';\nimport type { InitialProfileOutcome, ProfileIntent } from '../../../../services/profileResolution/type';\nimport { createProfileRuntime, createProfileRuntimePlugin } from '../../../../services/profileRuntime';\nimport { findProfile, mergeProfiles, readProfileSources } from '../../../../services/profileSources';\nimport { publishSelectedIdentity } from './_lib/profileServer';\nimport { profileSessionState } from './_lib/profileSession';\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 state = profileSessionState(context);\n const homeDirectory = execution.environment.HOME ?? nodeHost.homeDirectory();\n const readProfiles = () => loadProfiles(execution.repoRoot, homeDirectory);\n const readProfile = (profileName: string) =>\n findProfile(readProfiles(), readProfileSources(context, scope), profileName);\n\n // A launching host that already decided publishes its outcome before the session starts.\n const handoff = readInitialProfileOutcome(context);\n let publishOutcome: ((outcome: InitialProfileOutcome) => void) | undefined;\n\n const applyHandoff = (selection: PoHeadlessSelection, outcome: InitialProfileOutcome): PoHeadlessSelection => {\n state.warning = outcome.warning;\n const name = outcome.resolvedProfile;\n if (name === undefined) return { ...selection, profile: undefined };\n // The sources are read again here: one that dropped the profile since the launcher looked leaves no profile to apply.\n if (mergeProfiles(readProfiles(), readProfileSources(context, scope)).some((profile) => profile.name === name))\n return { ...selection, profile: name };\n state.warning = { code: 'missing', requested: name };\n return { ...selection, profile: undefined };\n };\n\n // Without a handoff nobody could say whether the session asked for no profile, so only a missing name is requested.\n const resolveStartup = async (selection: PoHeadlessSelection): Promise<PoHeadlessSelection> => {\n const intent: ProfileIntent =\n selection.profile === undefined ? { kind: 'unspecified' } : { kind: 'named', name: selection.profile };\n // Every session starts here, the edge included, so read the files through the bound platform.\n const files = await loadProfilesAsync(requirePoFs(context), execution.repoRoot, BACKGROUND_CONTEXT, homeDirectory);\n const outcome = await resolveInitialProfile(files, readProfileSources(context, scope), {\n intent,\n scope,\n signal,\n });\n state.warning = outcome.warning;\n publishOutcome?.(outcome);\n return { ...selection, profile: outcome.resolvedProfile };\n };\n\n const unregisterResolver = agent.registerInitialSelectionResolver((selection) =>\n handoff === undefined ? resolveStartup(selection) : applyHandoff(selection, handoff),\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 // Every applied selection leaves a marker, whoever asked for it; the first one waits for session start.\n if (state.started)\n await publishSelectedIdentity(agent.context, readProfileSources(context, scope), selection.profile, state);\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 // Other packages read the decision from the session context; a launcher that made it already put it there.\n if (handoff !== undefined) return;\n serviceContext.provide(PROFILE_INITIAL_OUTCOME_SERVICE, undefined);\n publishOutcome = (outcome) => serviceContext.set(PROFILE_INITIAL_OUTCOME_SERVICE, outcome);\n },\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","// @scaffold-generated\nimport type { AgentProfile } from '@agimon-ai/po-config/profiles';\n\nimport { createDeadline, PROFILE_RESOLUTION_TIMEOUT_MS } from '../profileResolution';\nimport {\n FILE_PROFILE_SOURCE_ID,\n type LaunchProfileCatalog,\n type LaunchProfileItem,\n type ListLaunchProfilesInput,\n} from './type';\n\n/** Name and icon only: the persona, voice, environment and binding of a profile never leave the host. */\nfunction launchItem(profile: AgentProfile, sourceId: string): LaunchProfileItem {\n const { name, icon } = profile.identity ?? {};\n const identity = {\n ...(name === undefined ? {} : { name }),\n ...(icon === undefined ? {} : { icon }),\n };\n return {\n name: profile.name,\n ...(Object.keys(identity).length === 0 ? {} : { identity }),\n sourceId,\n };\n}\n\n/**\n * The profiles a new session in a workspace can start with, for a launcher to offer.\n *\n * Waits for the sources of the workspace under one deadline, then lists what exists: a source that is slow or\n * failed costs `readiness`, never the profiles that are already there. A file profile keeps a name a source also holds.\n */\nexport async function listLaunchProfiles(input: ListLaunchProfilesInput): Promise<LaunchProfileCatalog> {\n input.signal.throwIfAborted();\n const { files, sources, scope } = input;\n let readiness: LaunchProfileCatalog['readiness'] = 'ready';\n if (sources !== undefined) {\n const deadline = createDeadline(input.signal, input.timeoutMs ?? PROFILE_RESOLUTION_TIMEOUT_MS);\n try {\n const waited = await deadline.within((signal) => sources.ready(scope, signal));\n if (waited.status !== 'done') readiness = 'unavailable';\n } finally {\n deadline.dispose();\n }\n }\n const items = new Map<string, LaunchProfileItem>();\n for (const profile of files) items.set(profile.name, launchItem(profile, FILE_PROFILE_SOURCE_ID));\n for (const { sourceId, profile } of sources?.listSourced(scope) ?? []) {\n if (!items.has(profile.name)) items.set(profile.name, launchItem(profile, sourceId));\n }\n return {\n profiles: [...items.values()].sort((left, right) => left.name.localeCompare(right.name)),\n readiness,\n };\n}\n","import { loadProfiles } from '@agimon-ai/po-config/profiles';\nimport { defineRoute } from '@agimon-ai/po-core/extensionFile';\nimport { nodeHost } from '@agimon-ai/po-core/platform';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { listLaunchProfiles } from '../../../../../services/launchProfiles';\nimport { readProfileSources } from '../../../../../services/profileSources';\n\nconst LAUNCH_PROFILES_PATH = '/launch-profiles';\n\n/** What a launcher may offer before any session exists: names and display data only. */\nexport default defineRoute(({ context, signal }: PoServerPluginContext) => ({\n basePath: 'profile',\n start: (api) => ({\n async fetch(request: Request) {\n if (new URL(request.url).pathname !== LAUNCH_PROFILES_PATH)\n 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 const { workspaceId, workspaceRoot } = api;\n if (workspaceId === undefined || workspaceRoot === undefined)\n return Response.json({ error: 'Workspace unavailable' }, { status: 404 });\n let files;\n try {\n files = loadProfiles(workspaceRoot, api.homeDirectory ?? api.environment?.HOME ?? nodeHost.homeDirectory());\n } catch {\n // The configuration error stays in the host log; a response may not carry file contents.\n return Response.json({ error: 'Profile configuration is unavailable' }, { status: 500 });\n }\n const scope = { workspaceId };\n const catalog = await listLaunchProfiles({\n files,\n sources: readProfileSources(context, scope),\n scope,\n signal: AbortSignal.any([request.signal, signal]),\n });\n return Response.json(catalog);\n },\n close() {},\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 { 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';\nimport { profileSessionState } from '../_lib/profileSession';\nexport default defineRoutedContribution(\n ({ agent, host, context }: PoServerPluginContext) =>\n agent\n ? createProfileServerCommand(\n agent,\n profileSessionState(context),\n readProfileSources(context, { workspaceId: host.context.workspaceId }),\n )\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';\nimport { profileSessionState } from '../_lib/profileSession';\n\nexport default defineHook(({ root, host, context }: WithRoot<PoServerPluginContext, ProfileRuntime | undefined>) => {\n const identityHook = createProfileIdentityHook(\n profileSessionState(context),\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/(backend)/api/profile/route.server';\nimport apiRoute2 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 const contextGlobal = { ...context, root: scopeGlobal.value };\n return {\n ...composeRootHooks(scopeGlobal),\n get api(): PoServerSessionPlugin['api'] { return [at(apiRoute, contextGlobal)]; },\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(apiRoute2, 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,WAAW,OAAmC;CACrD,IAAI,UAAU,KAAA,GAAW,OAAA;CACzB,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GAAG,MAAM,IAAI,MAAM,yCAAyC;CACpG,OAAO,KAAK,IAAI,OAAA,EAAuB;AACzC;;AAGA,SAAS,SAAS,OAAmC;CACnD,MAAM,SAAS,MAAM,MAAM,kBAAkB;CAC7C,OAAO,SAAS,OAAO,KAAK,UAAU,IAAI,MAAM,EAAE,CAAC,CAAC,KAAK,GAAG,IAAI,KAAA;AAClE;AAEA,SAAS,MAAM,KAA+B;CAC5C,OAAO;EACL,IAAI,IAAI;EACR,OAAO,IAAI;EACX,SAAS,IAAI;EACb,UAAU,IAAI;EACd,QAAQ,IAA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Profiles","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","findProfile","loadProfiles","buildPersonaPrompt","PO_PROFILE_IDENTITY_ENTRY_TYPE","profileWarningText","PROFILE_COMMAND","mergeProfiles","profileTitle","profileItems","isPoHeadlessPromptAdmissionError","PoSessionSetupError","PoHeadlessPromptAdmissionError","defineRoot","nodeHost","loadProfiles","findProfile","readProfileSources","readInitialProfileOutcome","mergeProfiles","loadProfilesAsync","requirePoFs","BACKGROUND_CONTEXT","resolveInitialProfile","createProfileRuntime","PoHeadlessPromptAdmissionError","createProfileRuntimePlugin","PROFILE_INITIAL_OUTCOME_SERVICE","PO_CODEMODE_SERVICE","readPoCodemode","runCleanups","createDeadline","FILE_PROFILE_SOURCE_ID","defineRoute","loadProfiles","nodeHost","readProfileSources","defineRoute","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","apiRoute2","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)/_lib/profileServer.ts","../../src/extensions/workspaces/sessions/(backend)/_lib/profileSession.ts","../../src/extensions/workspaces/sessions/(backend)/root.server.ts","../../src/services/launchProfiles/index.ts","../../src/extensions/workspaces/(backend)/api/profile/route.server.ts","../../src/extensions/workspaces/sessions/(backend)/api/profile/route.server.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 { 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 { profileWarningText } from '../../../../../services/profileResolution';\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';\nimport { type ProfileSessionState } from './profileSession';\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 journalIdentity(\n execution: PoHeadlessExecutionContext,\n sources: ProfileSources | undefined,\n profile: string | undefined,\n state: ProfileSessionState,\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 state.journaled = { profile };\n}\n\n/**\n * Journals the marker once per selection: the command and the host both report a change, and the second\n * report finds it already journaled.\n */\nexport async function publishSelectedIdentity(\n execution: PoHeadlessExecutionContext,\n sources: ProfileSources | undefined,\n profile: string | undefined,\n state: ProfileSessionState,\n): Promise<void> {\n if (state.journaled !== undefined && state.journaled.profile === profile) return;\n await journalIdentity(execution, sources, profile, state);\n}\n\n/** Shows why the session started without its profile, exactly once. A notice failure never blocks the session. */\nexport async function deliverProfileWarning(\n execution: PoHeadlessExecutionContext,\n state: ProfileSessionState,\n): Promise<void> {\n const warning = state.warning;\n if (warning === undefined || state.warned) return;\n state.warned = true;\n try {\n await execution.client.notify({ level: 'warning', body: profileWarningText(warning) });\n } catch {\n console.warn('[po-profile] Profile notice delivery unavailable.');\n }\n}\n\nexport function createProfileServerCommand(\n host: PoHeadlessHostService,\n state: ProfileSessionState,\n sources?: ProfileSources,\n): 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, state);\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(\n state: ProfileSessionState,\n sources?: ProfileSources,\n): PoHeadlessHook<'session_start'> {\n return {\n event: 'session_start',\n async handle(_event, execution) {\n // The first marker of a session is always journaled; later ones are journaled as selections change.\n await journalIdentity(execution, sources, execution.selection.profile, state);\n state.started = true;\n await deliverProfileWarning(execution, state);\n },\n };\n}\n","import type { Context } from '@deepseek-ai/cordis';\n\nimport type { InitialProfileWarning } from '../../../../../services/profileResolution/type';\n\n/**\n * Session bookkeeping shared by roots, hooks and commands through Cordis.\n */\nexport interface ProfileSessionState {\n /** True once `session_start` journaled the first identity marker; earlier selections are not journaled. */\n started: boolean;\n /** The profile last journaled as an identity marker. Absent means nothing was journaled yet. */\n journaled?: { readonly profile: string | undefined };\n /** Why the session started without the profile it was meant to have, until the notice is shown. */\n warning?: InitialProfileWarning;\n /** True once the warning was shown, so it appears exactly once. */\n warned: boolean;\n}\n\nconst PROFILE_SESSION_STATE_SERVICE = 'po/profile-session-state';\n\nexport function profileSessionState(context: Context): ProfileSessionState {\n // Contributions read their own service while the package fiber is still mounting.\n let state = context.get(PROFILE_SESSION_STATE_SERVICE, false) as ProfileSessionState | undefined;\n if (state === undefined) {\n state = { started: false, warned: false };\n context.provide(PROFILE_SESSION_STATE_SERVICE, state);\n }\n return state;\n}\n","import { loadProfiles, loadProfilesAsync } 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, type PoHeadlessSelection } from '@agimon-ai/po-core/headless';\nimport { BACKGROUND_CONTEXT, nodeHost, requirePoFs } from '@agimon-ai/po-core/platform';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { PROFILE_INITIAL_OUTCOME_SERVICE } from '../../../../constants/profileInitialOutcome';\nimport { PROFILE_MEMORY_NAMESPACE_SOURCE, PROFILE_MEMORY_STORE_SERVICE } from '../../../../constants/profileMemory';\nimport { createProfileMemoryNamespace } from '../../../../services/profileMemoryNamespace';\nimport { requireProfileMemoryStore } from '../../../../services/profileMemoryStore';\nimport { readInitialProfileOutcome, resolveInitialProfile } from '../../../../services/profileResolution';\nimport type { InitialProfileOutcome, ProfileIntent } from '../../../../services/profileResolution/type';\nimport { createProfileRuntime, createProfileRuntimePlugin } from '../../../../services/profileRuntime';\nimport { findProfile, mergeProfiles, readProfileSources } from '../../../../services/profileSources';\nimport { publishSelectedIdentity } from './_lib/profileServer';\nimport { profileSessionState } from './_lib/profileSession';\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 state = profileSessionState(context);\n const homeDirectory = execution.environment.HOME ?? nodeHost.homeDirectory();\n const readProfiles = () => loadProfiles(execution.repoRoot, homeDirectory);\n const readProfile = (profileName: string) =>\n findProfile(readProfiles(), readProfileSources(context, scope), profileName);\n\n // A launching host that already decided publishes its outcome before the session starts.\n const handoff = readInitialProfileOutcome(context);\n let publishOutcome: ((outcome: InitialProfileOutcome) => void) | undefined;\n\n const applyHandoff = (selection: PoHeadlessSelection, outcome: InitialProfileOutcome): PoHeadlessSelection => {\n state.warning = outcome.warning;\n const name = outcome.resolvedProfile;\n if (name === undefined) return { ...selection, profile: undefined };\n // The sources are read again here: one that dropped the profile since the launcher looked leaves no profile to apply.\n if (mergeProfiles(readProfiles(), readProfileSources(context, scope)).some((profile) => profile.name === name))\n return { ...selection, profile: name };\n state.warning = { code: 'missing', requested: name };\n return { ...selection, profile: undefined };\n };\n\n // Without a handoff nobody could say whether the session asked for no profile, so only a missing name is requested.\n const resolveStartup = async (selection: PoHeadlessSelection): Promise<PoHeadlessSelection> => {\n const intent: ProfileIntent =\n selection.profile === undefined ? { kind: 'unspecified' } : { kind: 'named', name: selection.profile };\n // Every session starts here, the edge included, so read the files through the bound platform.\n const files = await loadProfilesAsync(requirePoFs(context), execution.repoRoot, BACKGROUND_CONTEXT, homeDirectory);\n const outcome = await resolveInitialProfile(files, readProfileSources(context, scope), {\n intent,\n scope,\n signal,\n });\n state.warning = outcome.warning;\n publishOutcome?.(outcome);\n return { ...selection, profile: outcome.resolvedProfile };\n };\n\n const unregisterResolver = agent.registerInitialSelectionResolver((selection) =>\n handoff === undefined ? resolveStartup(selection) : applyHandoff(selection, handoff),\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 // Every applied selection leaves a marker, whoever asked for it; the first one waits for session start.\n if (state.started)\n await publishSelectedIdentity(agent.context, readProfileSources(context, scope), selection.profile, state);\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 // Other packages read the decision from the session context; a launcher that made it already put it there.\n if (handoff !== undefined) return;\n serviceContext.provide(PROFILE_INITIAL_OUTCOME_SERVICE, undefined);\n publishOutcome = (outcome) => serviceContext.set(PROFILE_INITIAL_OUTCOME_SERVICE, outcome);\n },\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","// @scaffold-generated\nimport type { AgentProfile } from '@agimon-ai/po-config/profiles';\n\nimport { createDeadline, PROFILE_RESOLUTION_TIMEOUT_MS } from '../profileResolution';\nimport {\n FILE_PROFILE_SOURCE_ID,\n type LaunchProfileCatalog,\n type LaunchProfileItem,\n type ListLaunchProfilesInput,\n} from './type';\n\n/** Presentation only: the persona, voice, environment and binding of a profile never leave the host. */\nfunction launchItem(profile: AgentProfile, sourceId: string): LaunchProfileItem {\n const { name, icon, role, contact } = profile.identity ?? {};\n const identity = {\n ...(name === undefined ? {} : { name }),\n ...(icon === undefined ? {} : { icon }),\n ...(role === undefined ? {} : { role }),\n ...(contact === undefined ? {} : { contact }),\n };\n return {\n name: profile.name,\n ...(Object.keys(identity).length === 0 ? {} : { identity }),\n sourceId,\n };\n}\n\n/**\n * The profiles a new session in a workspace can start with, for a launcher to offer.\n *\n * Waits for the sources of the workspace under one deadline, then lists what exists: a source that is slow or\n * failed costs `readiness`, never the profiles that are already there. A file profile keeps a name a source also holds.\n */\nexport async function listLaunchProfiles(input: ListLaunchProfilesInput): Promise<LaunchProfileCatalog> {\n input.signal.throwIfAborted();\n const { files, sources, scope } = input;\n let readiness: LaunchProfileCatalog['readiness'] = 'ready';\n if (sources !== undefined) {\n const deadline = createDeadline(input.signal, input.timeoutMs ?? PROFILE_RESOLUTION_TIMEOUT_MS);\n try {\n const waited = await deadline.within((signal) => sources.ready(scope, signal));\n if (waited.status !== 'done') readiness = 'unavailable';\n } finally {\n deadline.dispose();\n }\n }\n const items = new Map<string, LaunchProfileItem>();\n for (const profile of files) items.set(profile.name, launchItem(profile, FILE_PROFILE_SOURCE_ID));\n for (const { sourceId, profile } of sources?.listSourced(scope) ?? []) {\n if (!items.has(profile.name)) items.set(profile.name, launchItem(profile, sourceId));\n }\n return {\n profiles: [...items.values()].sort((left, right) => left.name.localeCompare(right.name)),\n readiness,\n };\n}\n","import { loadProfiles } from '@agimon-ai/po-config/profiles';\nimport { defineRoute } from '@agimon-ai/po-core/extensionFile';\nimport { nodeHost } from '@agimon-ai/po-core/platform';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { listLaunchProfiles } from '../../../../../services/launchProfiles';\nimport { readProfileSources } from '../../../../../services/profileSources';\n\nconst LAUNCH_PROFILES_PATH = '/launch-profiles';\n\n/** What a launcher may offer before any session exists: names and display data only. */\nexport default defineRoute(({ context, signal }: PoServerPluginContext) => ({\n basePath: 'profile',\n start: (api) => ({\n async fetch(request: Request) {\n if (new URL(request.url).pathname !== LAUNCH_PROFILES_PATH)\n 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 const { workspaceId, workspaceRoot } = api;\n if (workspaceId === undefined || workspaceRoot === undefined)\n return Response.json({ error: 'Workspace unavailable' }, { status: 404 });\n let files;\n try {\n files = loadProfiles(workspaceRoot, api.homeDirectory ?? api.environment?.HOME ?? nodeHost.homeDirectory());\n } catch {\n // The configuration error stays in the host log; a response may not carry file contents.\n return Response.json({ error: 'Profile configuration is unavailable' }, { status: 500 });\n }\n const scope = { workspaceId };\n const catalog = await listLaunchProfiles({\n files,\n sources: readProfileSources(context, scope),\n scope,\n signal: AbortSignal.any([request.signal, signal]),\n });\n return Response.json(catalog);\n },\n close() {},\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 { 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';\nimport { profileSessionState } from '../_lib/profileSession';\nexport default defineRoutedContribution(\n ({ agent, host, context }: PoServerPluginContext) =>\n agent\n ? createProfileServerCommand(\n agent,\n profileSessionState(context),\n readProfileSources(context, { workspaceId: host.context.workspaceId }),\n )\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';\nimport { profileSessionState } from '../_lib/profileSession';\n\nexport default defineHook(({ root, host, context }: WithRoot<PoServerPluginContext, ProfileRuntime | undefined>) => {\n const identityHook = createProfileIdentityHook(\n profileSessionState(context),\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/(backend)/api/profile/route.server';\nimport apiRoute2 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 const contextGlobal = { ...context, root: scopeGlobal.value };\n return {\n ...composeRootHooks(scopeGlobal),\n get api(): PoServerSessionPlugin['api'] { return [at(apiRoute, contextGlobal)]; },\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(apiRoute2, 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,CAC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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,GAAGE,sBAAW,cAAc,CAAC;GAAG;GAClF,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 { A as PROFILE_SECRETS_SERVICE, D as resolveInitialProfile, E as readInitialProfileOutcome, M as PROFILE_INITIAL_OUTCOME_SERVICE, O as FILE_PROFILE_SOURCE_ID, T as profileWarningText, b as createProfileRuntimePlugin, f as findProfile, g as createProfileSecrets, i as profileItems, k as PROFILE_SOURCES_SERVICE, l as redactSecrets, m as readProfileSources, p as mergeProfiles, s as profileTitle, t as PROFILE_COMMAND, u as createProfileSources, w as createDeadline, y as createProfileRuntime } from "../profileText-
|
|
1
|
+
import { A as PROFILE_SECRETS_SERVICE, D as resolveInitialProfile, E as readInitialProfileOutcome, M as PROFILE_INITIAL_OUTCOME_SERVICE, O as FILE_PROFILE_SOURCE_ID, T as profileWarningText, b as createProfileRuntimePlugin, f as findProfile, g as createProfileSecrets, i as profileItems, k as PROFILE_SOURCES_SERVICE, l as redactSecrets, m as readProfileSources, p as mergeProfiles, s as profileTitle, t as PROFILE_COMMAND, u as createProfileSources, w as createDeadline, y as createProfileRuntime } from "../profileText-C0kldV5Y.mjs";
|
|
2
2
|
import { composeRootHooks, composeRootInjects, defineHook, defineResource, defineRoot, defineRoute, defineRoutedContribution, defineServiceContract, runCleanups } from "@agimon-ai/po-core/extensionFile";
|
|
3
3
|
import { buildPersonaPrompt, loadProfiles, loadProfilesAsync } from "@agimon-ai/po-config/profiles";
|
|
4
4
|
import { PO_SERVER_SCOPE_SERVICE, composeServerProviderOverrides, defineServerPlugin, packageResourcePath, readPackageResource, requirePoServerScope } from "@agimon-ai/po-core/serverPlugin";
|
|
@@ -619,12 +619,14 @@ var root_server_default = defineRoot(({ agent, host, signal, context }) => {
|
|
|
619
619
|
});
|
|
620
620
|
//#endregion
|
|
621
621
|
//#region src/services/launchProfiles/index.ts
|
|
622
|
-
/**
|
|
622
|
+
/** Presentation only: the persona, voice, environment and binding of a profile never leave the host. */
|
|
623
623
|
function launchItem(profile, sourceId) {
|
|
624
|
-
const { name, icon } = profile.identity ?? {};
|
|
624
|
+
const { name, icon, role, contact } = profile.identity ?? {};
|
|
625
625
|
const identity = {
|
|
626
626
|
...name === void 0 ? {} : { name },
|
|
627
|
-
...icon === void 0 ? {} : { icon }
|
|
627
|
+
...icon === void 0 ? {} : { icon },
|
|
628
|
+
...role === void 0 ? {} : { role },
|
|
629
|
+
...contact === void 0 ? {} : { contact }
|
|
628
630
|
};
|
|
629
631
|
return {
|
|
630
632
|
name: profile.name,
|