hob-bot 0.0.0-stage → 1.0.2

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.
Files changed (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +111 -2
  3. package/README.zh-CN.md +112 -0
  4. package/bin/hob.mjs +7 -0
  5. package/dist/web/assets/index-D88l35PH.css +1 -0
  6. package/dist/web/assets/index-DUs8nN3E.js +218 -0
  7. package/dist/web/favicon.ico +0 -0
  8. package/dist/web/fonts/inter-latin.woff2 +0 -0
  9. package/dist/web/fonts/jetbrains-mono-latin.woff2 +0 -0
  10. package/dist/web/icons/apple-touch-icon-180.png +0 -0
  11. package/dist/web/icons/favicon-32.png +0 -0
  12. package/dist/web/icons/icon-192.png +0 -0
  13. package/dist/web/icons/icon-512.png +0 -0
  14. package/dist/web/icons/icon-maskable-512.png +0 -0
  15. package/dist/web/index.html +32 -0
  16. package/dist/web/manifest.webmanifest +16 -0
  17. package/dist/web/sw.js +131 -0
  18. package/package.json +62 -4
  19. package/server/src/actions.ts +230 -0
  20. package/server/src/boot.ts +85 -0
  21. package/server/src/bus.ts +21 -0
  22. package/server/src/config.ts +123 -0
  23. package/server/src/cron-text.ts +49 -0
  24. package/server/src/delegations.ts +113 -0
  25. package/server/src/files.ts +142 -0
  26. package/server/src/http.ts +802 -0
  27. package/server/src/ids.ts +19 -0
  28. package/server/src/image.ts +218 -0
  29. package/server/src/imports.ts +302 -0
  30. package/server/src/jobs.ts +730 -0
  31. package/server/src/main.ts +69 -0
  32. package/server/src/memory.ts +272 -0
  33. package/server/src/models.ts +358 -0
  34. package/server/src/overview.ts +116 -0
  35. package/server/src/pages.ts +54 -0
  36. package/server/src/password.ts +23 -0
  37. package/server/src/pi.ts +273 -0
  38. package/server/src/prompt.ts +227 -0
  39. package/server/src/providers.ts +532 -0
  40. package/server/src/push.ts +285 -0
  41. package/server/src/router-tools.ts +549 -0
  42. package/server/src/router.ts +841 -0
  43. package/server/src/routines.ts +129 -0
  44. package/server/src/runtime.ts +104 -0
  45. package/server/src/search.ts +91 -0
  46. package/server/src/secrets.ts +46 -0
  47. package/server/src/settings.ts +452 -0
  48. package/server/src/skills.ts +150 -0
  49. package/server/src/store.ts +324 -0
  50. package/server/src/text.ts +14 -0
  51. package/server/src/time.ts +42 -0
  52. package/server/src/transcript.ts +272 -0
  53. package/server/src/worker-tools.ts +129 -0
  54. package/shared/command.ts +42 -0
  55. package/shared/files.ts +141 -0
  56. package/shared/media.ts +17 -0
  57. package/shared/model-note.ts +32 -0
  58. package/shared/page-shell.ts +108 -0
  59. package/shared/search.ts +19 -0
  60. package/shared/skills.ts +37 -0
  61. package/shared/sprites.ts +422 -0
  62. package/shared/thinking.ts +118 -0
  63. package/shared/types.ts +631 -0
  64. package/vendor/lore-pi-extension/README.md +28 -0
  65. package/vendor/lore-pi-extension/api.ts +140 -0
  66. package/vendor/lore-pi-extension/formatters.ts +204 -0
  67. package/vendor/lore-pi-extension/hooks.ts +195 -0
  68. package/vendor/lore-pi-extension/index.ts +25 -0
  69. package/vendor/lore-pi-extension/package.json +23 -0
  70. package/vendor/lore-pi-extension/skills.ts +447 -0
  71. package/vendor/lore-pi-extension/tools.ts +344 -0
  72. package/vendor/lore-pi-extension/uri.ts +67 -0
  73. package/vendor/lore-pi-extension/vendor/skill-workcopy/index.d.mts +266 -0
  74. package/vendor/lore-pi-extension/vendor/skill-workcopy/index.mjs +1328 -0
  75. package/vendor/lore-pi-extension/vendor/skill-workcopy/skills-sync.d.mts +33 -0
  76. package/vendor/lore-pi-extension/vendor/skill-workcopy/skills-sync.mjs +202 -0
@@ -0,0 +1,140 @@
1
+ import * as fs from 'node:fs';
2
+ import * as os from 'node:os';
3
+ import * as path from 'node:path';
4
+
5
+ const DEFAULT_BASE_URL = 'http://127.0.0.1:18901';
6
+ const DEFAULT_TIMEOUT_MS = 30000;
7
+ const DEFAULT_DOMAIN = 'core';
8
+ const CLIENT_TYPE = 'pi';
9
+
10
+ interface SharedLoreConfig {
11
+ base_url?: string;
12
+ api_token?: string;
13
+ lore_home?: string;
14
+ server_profile?: {
15
+ base_url?: string;
16
+ capabilities?: Record<string, boolean>;
17
+ };
18
+ }
19
+
20
+ export function resolveLoreHome(env: NodeJS.ProcessEnv = process.env): string {
21
+ const fromEnv = typeof env.LORE_HOME === 'string' ? env.LORE_HOME.trim() : '';
22
+ if (fromEnv) return path.resolve(fromEnv);
23
+ return path.join(os.homedir(), '.lore');
24
+ }
25
+
26
+ function sharedConfigPath(env: NodeJS.ProcessEnv = process.env): string {
27
+ return path.join(resolveLoreHome(env), 'config.json');
28
+ }
29
+
30
+ function readSharedLoreConfig(): SharedLoreConfig {
31
+ try {
32
+ const raw = fs.readFileSync(sharedConfigPath(), 'utf-8');
33
+ const data = JSON.parse(raw);
34
+ return data && typeof data === 'object' && !Array.isArray(data) ? data : {};
35
+ } catch {
36
+ return {};
37
+ }
38
+ }
39
+
40
+ function pickString(value: unknown): string {
41
+ return typeof value === 'string' && value.trim() ? value.trim() : '';
42
+ }
43
+
44
+ function pickBaseUrl(cfg: any) {
45
+ const shared = readSharedLoreConfig();
46
+ const raw = pickString(cfg.baseUrl)
47
+ || pickString(shared.base_url)
48
+ || pickString(process.env.LORE_BASE_URL)
49
+ || DEFAULT_BASE_URL;
50
+ return raw.trim().replace(/\/+$/, '');
51
+ }
52
+
53
+ function skillsEnabled(cfg: any, shared: SharedLoreConfig, loreHome: string, baseUrl: string): boolean {
54
+ if (cfg.skillsEnabled === false || process.env.LORE_SKILLS_ENABLED === '0') return false;
55
+ const profileBase = pickString(shared.server_profile?.base_url).replace(/\/+$/, '').toLowerCase();
56
+ const profileMatches = Boolean(profileBase) && profileBase === baseUrl.replace(/\/+$/, '').toLowerCase();
57
+ if (profileMatches) return shared.server_profile?.capabilities?.skills === true;
58
+ if (cfg.skillsEnabled === true || process.env.LORE_SKILLS_ENABLED === '1') return true;
59
+ try {
60
+ return fs.readFileSync(path.join(loreHome, 'pi', '.lore-skills-enabled'), 'utf8').trim() === '1';
61
+ } catch {
62
+ return false;
63
+ }
64
+ }
65
+
66
+ export function pickPluginConfig(pi: any) {
67
+ const cfg = pi?.pluginConfig ?? {};
68
+ const shared = readSharedLoreConfig();
69
+ const loreHome = pickString(cfg.loreHome)
70
+ || pickString(shared.lore_home)
71
+ || resolveLoreHome();
72
+ const baseUrl = pickBaseUrl(cfg);
73
+ return {
74
+ baseUrl,
75
+ apiToken: pickString(cfg.apiToken)
76
+ || pickString(shared.api_token)
77
+ || pickString(process.env.LORE_API_TOKEN)
78
+ || pickString(process.env.API_TOKEN),
79
+ timeoutMs: Number.isFinite(cfg.timeoutMs) ? Number(cfg.timeoutMs) : DEFAULT_TIMEOUT_MS,
80
+ defaultDomain: typeof cfg.defaultDomain === 'string' && cfg.defaultDomain.trim() ? cfg.defaultDomain.trim() : DEFAULT_DOMAIN,
81
+ injectPromptGuidance: cfg.injectPromptGuidance !== false,
82
+ startupHealthcheck: cfg.startupHealthcheck !== false,
83
+ recallEnabled: cfg.recallEnabled !== false,
84
+ skillsEnabled: skillsEnabled(cfg, shared, path.resolve(loreHome), baseUrl),
85
+ loreHome: path.resolve(loreHome),
86
+ };
87
+ }
88
+
89
+ export function textResult(text: string, details?: unknown) {
90
+ return { content: [{ type: 'text', text }], details };
91
+ }
92
+
93
+ export function authHeaders(pluginCfg: any, includeJson = true) {
94
+ const headers: Record<string, string> = {};
95
+ if (includeJson) headers['content-type'] = 'application/json';
96
+ if (pluginCfg.apiToken) headers.authorization = `Bearer ${pluginCfg.apiToken}`;
97
+ return headers;
98
+ }
99
+
100
+ export function buildApiUrl(pluginCfg: any, path: string) {
101
+ const rawPath = String(path || '');
102
+ const normalizedPath = `/api${rawPath.startsWith('/') ? rawPath : `/${rawPath}`}`;
103
+ const url = new URL(normalizedPath, `${pluginCfg.baseUrl}/`);
104
+ url.searchParams.set('client_type', CLIENT_TYPE);
105
+ return url.toString();
106
+ }
107
+
108
+ export async function fetchJson(pluginCfg: any, path: string, options: any = {}) {
109
+ const url = buildApiUrl(pluginCfg, path);
110
+ const response = await fetch(url, {
111
+ ...options,
112
+ headers: {
113
+ ...authHeaders(pluginCfg, options.method && options.method !== 'GET'),
114
+ ...(options.headers || {}),
115
+ },
116
+ signal: AbortSignal.timeout(pluginCfg.timeoutMs || DEFAULT_TIMEOUT_MS),
117
+ });
118
+
119
+ const text = await response.text();
120
+ let data: any = null;
121
+ try {
122
+ data = text ? JSON.parse(text) : null;
123
+ } catch {
124
+ data = text;
125
+ }
126
+
127
+ if (!response.ok) {
128
+ const detail = data?.detail || data?.error || text || `${response.status} ${response.statusText}`;
129
+ const err: any = new Error(typeof detail === 'string' ? detail : JSON.stringify(detail));
130
+ err.status = response.status;
131
+ err.data = data;
132
+ throw err;
133
+ }
134
+
135
+ return data;
136
+ }
137
+
138
+ export function hasRecallConfig(pluginCfg: any) {
139
+ return Boolean(pluginCfg.recallEnabled);
140
+ }
@@ -0,0 +1,204 @@
1
+ const DEFAULT_RECALL_SCORE_PRECISION = 2;
2
+
3
+ export function formatNode(data: any) {
4
+ const node = data?.node || {};
5
+ const children = Array.isArray(data?.children) ? data.children : [];
6
+ const lines: string[] = [];
7
+ lines.push(`URI: ${node.uri || ''}`);
8
+ if (node.node_uuid) lines.push(`Node UUID: ${node.node_uuid}`);
9
+ lines.push(`Priority: ${node.priority ?? ''}`);
10
+ if (node.disclosure) lines.push(`Disclosure: ${node.disclosure}`);
11
+ if (Array.isArray(node.aliases) && node.aliases.length > 0) {
12
+ lines.push(`Aliases: ${node.aliases.join(', ')}`);
13
+ }
14
+ lines.push('');
15
+ lines.push(node.content || '(empty)');
16
+ if (children.length > 0) {
17
+ lines.push('');
18
+ lines.push('Children:');
19
+ for (const child of children) {
20
+ lines.push(`- ${child.uri} (priority: ${child.priority ?? ''})`);
21
+ if (child.content_snippet) lines.push(` ${child.content_snippet}`);
22
+ }
23
+ }
24
+ if (Array.isArray(node.glossary_keywords) && node.glossary_keywords.length > 0) {
25
+ lines.push('');
26
+ lines.push(`Glossary keywords: ${node.glossary_keywords.join(', ')}`);
27
+ }
28
+ return lines.join('\n');
29
+ }
30
+
31
+ export function formatBootView(data: any) {
32
+ const coreMemories = Array.isArray(data?.core_memories) ? data.core_memories : [];
33
+ const recentMemories = Array.isArray(data?.recent_memories) ? data.recent_memories : [];
34
+ const failed = Array.isArray(data?.failed) ? data.failed : [];
35
+ const loaded = Number.isFinite(data?.loaded) ? data.loaded : coreMemories.length;
36
+ const total = Number.isFinite(data?.total) ? data.total : coreMemories.length;
37
+ const clientBootMemories = coreMemories.filter((memory: any) => memory?.scope === 'client');
38
+ const lines: string[] = [];
39
+
40
+ lines.push('# Core Memories');
41
+ lines.push(`# Loaded: ${loaded}/${total} memories`);
42
+ lines.push('');
43
+
44
+ if (failed.length > 0) {
45
+ lines.push('## Failed to load:');
46
+ lines.push(...failed);
47
+ lines.push('');
48
+ }
49
+
50
+ if (coreMemories.length > 0) {
51
+ lines.push('## Fixed boot baseline:');
52
+ lines.push('');
53
+ lines.push('Lore boot deterministically loads three global startup nodes inside Lore:');
54
+ lines.push('- core://agent — workflow constraints');
55
+ lines.push('- core://soul — style / persona / self-definition');
56
+ lines.push('- preferences://user — stable user definition / durable user context');
57
+ lines.push('');
58
+ if (clientBootMemories.length > 0) {
59
+ lines.push(clientBootMemories.length === 1
60
+ ? 'This boot view also includes the active client-specific agent node:'
61
+ : 'This boot view also includes the client-specific agent nodes:');
62
+ for (const memory of clientBootMemories) {
63
+ lines.push(`- ${memory?.uri || ''} — ${memory?.boot_role_label || 'client-specific agent constraints'}`);
64
+ }
65
+ lines.push('');
66
+ }
67
+ for (const memory of coreMemories) {
68
+ lines.push(`### ${memory?.uri || ''}`);
69
+ if (memory?.boot_role_label) lines.push(`Role: ${memory.boot_role_label}`);
70
+ if (memory?.boot_purpose) lines.push(`Purpose: ${memory.boot_purpose}`);
71
+ if (Number.isFinite(memory?.priority)) lines.push(`Priority: ${memory.priority}`);
72
+ if (memory?.disclosure) lines.push(`Disclosure: ${memory.disclosure}`);
73
+ if (memory?.node_uuid) lines.push(`Node UUID: ${memory.node_uuid}`);
74
+ lines.push('');
75
+ lines.push(memory?.content || '(empty)');
76
+ lines.push('');
77
+ }
78
+ } else {
79
+ lines.push('(No core memories loaded.)');
80
+ }
81
+
82
+ if (recentMemories.length > 0) {
83
+ lines.push('---');
84
+ lines.push('');
85
+ lines.push('# Recent Memories');
86
+ lines.push('These are context hints. Some legacy URIs may carry date-shaped segments; read those dates as event time or archive context while ordinary memory identity stays with durable concepts.');
87
+ for (const memory of recentMemories) {
88
+ const meta: string[] = [];
89
+ if (Number.isFinite(memory?.priority)) meta.push(`priority: ${memory.priority}`);
90
+ if (memory?.created_at) meta.push(`created: ${memory.created_at}`);
91
+ const suffix = meta.length > 0 ? ` (${meta.join(', ')})` : '';
92
+ lines.push(`- ${memory?.uri || ''}${suffix}`);
93
+ if (memory?.disclosure) lines.push(` Disclosure: ${memory.disclosure}`);
94
+ }
95
+ }
96
+
97
+ return lines.join('\n').trim();
98
+ }
99
+
100
+ export function readCueList(item: any) {
101
+ const cues = Array.isArray(item?.cues) ? item.cues : [];
102
+ const cleaned = cues.map((x: any) => String(x || '').replace(/\s+/g, ' ').trim()).filter(Boolean);
103
+ return cleaned.slice(0, 3);
104
+ }
105
+
106
+ export function formatRecallBlock(items: any, precision = DEFAULT_RECALL_SCORE_PRECISION, sessionId?: string, queryId?: string) {
107
+ if (!Array.isArray(items) || items.length === 0) return '';
108
+ const attrs = [sessionId && `session_id="${sessionId}"`, queryId && `query_id="${queryId}"`].filter(Boolean).join(' ');
109
+ const lines = [attrs ? `<recall ${attrs}>` : '<recall>'];
110
+ for (const item of items) {
111
+ const score = Number.isFinite(item?.score_display) ? Number(item.score_display).toFixed(precision) : String(item?.score ?? '');
112
+ const cues = readCueList(item);
113
+ const cueText = cues.join(' · ').trim();
114
+ lines.push(`${score} | ${item?.uri || ''}${cueText ? ` | ${cueText}` : ''}`);
115
+ }
116
+ lines.push('</recall>');
117
+ return lines.join('\n');
118
+ }
119
+
120
+ export function normalizeSearchResults(data: any) {
121
+ if (Array.isArray(data)) return data;
122
+ if (Array.isArray(data?.results)) return data.results;
123
+ return [];
124
+ }
125
+
126
+ const SEARCH_SNIPPET_MAX_CHARS = 300;
127
+ const SEARCH_DISCLOSURE_MAX_CHARS = 160;
128
+ const SEARCH_CLOSING_CUE = 'Open a node with lore_get_node for full content.';
129
+
130
+ export function collapseWhitespace(value: unknown) {
131
+ return String(value || '').replace(/\s+/g, ' ').trim();
132
+ }
133
+
134
+ function truncateText(value: string, max: number) {
135
+ return value.length > max ? value.slice(0, max) : value;
136
+ }
137
+
138
+ function searchResultScore(item: any) {
139
+ const score = Number.isFinite(item?.score_display) ? item.score_display : (Number.isFinite(item?.score) ? item.score : null);
140
+ return score === null ? '' : Number(score).toFixed(2);
141
+ }
142
+
143
+ function searchResultDate(item: any) {
144
+ const raw = typeof item?.updated_at === 'string' ? item.updated_at.trim() : '';
145
+ return raw ? raw.slice(0, 10) : '';
146
+ }
147
+
148
+ function searchResultPassage(item: any) {
149
+ const snippet = collapseWhitespace(item?.snippet);
150
+ if (snippet) return truncateText(snippet, SEARCH_SNIPPET_MAX_CHARS);
151
+ return truncateText(collapseWhitespace(item?.content), SEARCH_SNIPPET_MAX_CHARS);
152
+ }
153
+
154
+ export function formatSearchResults(results: any, opts: { full?: boolean } = {}) {
155
+ const items = Array.isArray(results) ? results : [];
156
+ if (items.length === 0) return '';
157
+ const lines: string[] = [];
158
+ items.forEach((item: any, idx: number) => {
159
+ const meta: string[] = [];
160
+ const score = searchResultScore(item);
161
+ if (score) meta.push(score);
162
+ const date = searchResultDate(item);
163
+ if (date) meta.push(date);
164
+ const metaText = meta.length > 0 ? ` (${meta.join(' · ')})` : '';
165
+ lines.push(`${idx + 1}. ${item?.uri || ''}${metaText}`);
166
+ const disclosure = collapseWhitespace(item?.disclosure);
167
+ if (disclosure) lines.push(` when: ${truncateText(disclosure, SEARCH_DISCLOSURE_MAX_CHARS)}`);
168
+ const passage = searchResultPassage(item);
169
+ if (passage) lines.push(` > ${passage}`);
170
+ });
171
+ const first = items[0] || {};
172
+ if (opts.full && typeof first?.content === 'string' && first.content.trim()) {
173
+ lines.push('', '---', '', first.content);
174
+ }
175
+ lines.push('', SEARCH_CLOSING_CUE);
176
+ return lines.join('\n');
177
+ }
178
+
179
+ export const SEARCH_RESULT_LIMIT_MAX = 20;
180
+ export const SEARCH_RESULT_LIMIT_DEFAULT = 5;
181
+
182
+ export function resolveSearchLimit(value: unknown) {
183
+ return Number.isFinite(value as number) ? Math.max(1, Math.min(SEARCH_RESULT_LIMIT_MAX, Number(value))) : SEARCH_RESULT_LIMIT_DEFAULT;
184
+ }
185
+
186
+ export function normalizeKeywordList(values: any) {
187
+ if (!Array.isArray(values)) return [];
188
+ const seen = new Set();
189
+ const out: string[] = [];
190
+ for (const value of values) {
191
+ const keyword = String(value || '').trim();
192
+ if (!keyword) continue;
193
+ const key = keyword.toLowerCase();
194
+ if (seen.has(key)) continue;
195
+ seen.add(key);
196
+ out.push(keyword);
197
+ }
198
+ return out;
199
+ }
200
+
201
+ export function normalizeUriList(items: any) {
202
+ if (!Array.isArray(items)) return [];
203
+ return [...new Set(items.map((item: any) => String(item?.uri || item || '').trim()).filter(Boolean))];
204
+ }
@@ -0,0 +1,195 @@
1
+ import { execSync } from 'node:child_process';
2
+ import { basename } from 'node:path';
3
+ import { readFileSync } from 'node:fs';
4
+ import { fetchJson, hasRecallConfig } from './api';
5
+
6
+ // ---- Message text extraction helpers ----
7
+
8
+ export function extractMessageText(message: any) {
9
+ if (!message || typeof message !== 'object') return '';
10
+ const content = message.content;
11
+ if (typeof content === 'string') return content.trim();
12
+ if (!Array.isArray(content)) return '';
13
+ return content
14
+ .filter((block: any) => block && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string')
15
+ .map((block: any) => block.text.trim())
16
+ .filter(Boolean)
17
+ .join('\n')
18
+ .trim();
19
+ }
20
+
21
+ // ---- Project context detection ----
22
+
23
+ interface ProjectInfo {
24
+ dir_name: string;
25
+ repo_name: string | null;
26
+ }
27
+
28
+ export function detectProjectInfo(cwd?: string): ProjectInfo {
29
+ // Agent sessions can run inside a long-lived host process whose own cwd is
30
+ // unrelated to the session (for example a pi-web server). Prefer the session
31
+ // cwd so project identity, repo grouping, and recall follow the session.
32
+ const dir = typeof cwd === 'string' && cwd.trim() ? cwd : process.cwd();
33
+ const dir_name = basename(dir);
34
+
35
+ let repo_name: string | null = null;
36
+ try {
37
+ const gitOptions = { encoding: 'utf-8', timeout: 2000, stdio: ['pipe', 'pipe', 'pipe'], cwd: dir } as const;
38
+ const remote = execSync('git remote', gitOptions).trim().split('\n')[0];
39
+ const remoteUrl = execSync(`git remote get-url ${remote}`, gitOptions).trim();
40
+ const match = remoteUrl.match(/\/([^/.]+?)(?:\.git)?$/);
41
+ if (match?.[1]) repo_name = match[1];
42
+ } catch {}
43
+
44
+ return { dir_name, repo_name };
45
+ }
46
+
47
+ // ---- Lifecycle helpers ----
48
+
49
+ function pluginVersion(): string | undefined {
50
+ try {
51
+ const version = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'))?.version;
52
+ return typeof version === 'string' && version.trim() ? version.trim() : undefined;
53
+ } catch {
54
+ return undefined;
55
+ }
56
+ }
57
+
58
+ function lifecycleRuntime(): Record<string, string> {
59
+ const runtime: Record<string, string> = { runtime_id: 'pi', runtime_family: 'pi' };
60
+ const version = pluginVersion();
61
+ if (version) runtime.plugin_version = version;
62
+ return runtime;
63
+ }
64
+
65
+ async function fetchLifecycleEvent(pluginCfg: any, body: Record<string, unknown>) {
66
+ return fetchJson(pluginCfg, '/lifecycle/event', {
67
+ method: 'POST',
68
+ body: JSON.stringify(body),
69
+ });
70
+ }
71
+
72
+ async function fetchStartupLifecycle(pluginCfg: any, sessionId: string | undefined, cwd: string | undefined) {
73
+ return fetchLifecycleEvent(pluginCfg, {
74
+ protocol_version: 'lore.lifecycle.v1',
75
+ runtime: lifecycleRuntime(),
76
+ event: { name: 'session.start', native_name: 'session_start' },
77
+ normalized: { session_id: sessionId },
78
+ project: detectProjectInfo(cwd),
79
+ });
80
+ }
81
+
82
+ async function fetchPromptLifecycle(pluginCfg: any, prompt: string, sessionId: string | undefined) {
83
+ return fetchLifecycleEvent(pluginCfg, {
84
+ protocol_version: 'lore.lifecycle.v1',
85
+ runtime: lifecycleRuntime(),
86
+ event: { name: 'prompt.submit', native_name: 'before_agent_start' },
87
+ features: { memory_recall: hasRecallConfig(pluginCfg) },
88
+ normalized: { session_id: sessionId, prompt },
89
+ });
90
+ }
91
+
92
+ function readReturnValue(response: any): any {
93
+ return response?.host_output?.mode === 'return_value' && response.host_output.value
94
+ ? response.host_output.value
95
+ : null;
96
+ }
97
+
98
+ // ---- Session ID helper ----
99
+
100
+ function getSessionId(ctx: any): string | undefined {
101
+ const manager = ctx?.sessionManager;
102
+ if (!manager || typeof manager.getSessionId !== 'function') return undefined;
103
+ const sessionId = manager.getSessionId();
104
+ return typeof sessionId === 'string' && sessionId.trim() ? sessionId.trim() : undefined;
105
+ }
106
+
107
+ // ---- Hook registration ----
108
+
109
+ export function registerHooks(pi: any, pluginCfg: any) {
110
+ const startupRequests = new Map<string, Promise<void>>();
111
+ // Boot baseline is per session, not per first turn: Pi rebuilds the system
112
+ // prompt from its base on every user prompt, so the fixed baseline has to be
113
+ // re-appended on each turn (and several sessions can run in one process).
114
+ const startupAppendBySession = new Map<string, string>();
115
+
116
+ pi.on('session_start', async (_event: any, ctx: any) => {
117
+ if (pluginCfg.startupHealthcheck) {
118
+ try {
119
+ await fetchJson(pluginCfg, '/health', { method: 'GET' });
120
+ ctx?.ui?.notify?.(`Lore connected: ${pluginCfg.baseUrl}`, 'info');
121
+ } catch (error: any) {
122
+ pi.logger?.warn?.(`lore: startup health check failed (${pluginCfg.baseUrl}): ${error.message}`);
123
+ }
124
+ }
125
+
126
+ if (!pluginCfg.injectPromptGuidance) {
127
+ // No lifecycle startup request; skills are handled by
128
+ // registerSkillResourceDiscovery, independent of prompt guidance.
129
+ return;
130
+ }
131
+ const sessionId = getSessionId(ctx);
132
+ if (!sessionId) return;
133
+
134
+ const existing = startupRequests.get(sessionId);
135
+ if (existing) return existing;
136
+
137
+ const request = (async () => {
138
+ try {
139
+ const lifecycleResponse = await fetchStartupLifecycle(pluginCfg, sessionId, ctx?.cwd);
140
+ const value = readReturnValue(lifecycleResponse);
141
+ const systemPromptAppend = typeof value?.systemPromptAppend === 'string'
142
+ ? value.systemPromptAppend.trim()
143
+ : '';
144
+ if (systemPromptAppend && startupRequests.get(sessionId) === request) {
145
+ startupAppendBySession.set(sessionId, systemPromptAppend);
146
+ }
147
+ } catch (error: any) {
148
+ pi.logger?.debug?.(`lore: lifecycle startup failed: ${error.message}`);
149
+ } finally {
150
+ if (startupRequests.get(sessionId) === request) startupRequests.delete(sessionId);
151
+ }
152
+ })();
153
+ startupRequests.set(sessionId, request);
154
+ return request;
155
+ });
156
+
157
+ pi.on('session_shutdown', async (_event: any, ctx: any) => {
158
+ const sessionId = getSessionId(ctx);
159
+ if (!sessionId) return;
160
+ startupAppendBySession.delete(sessionId);
161
+ startupRequests.delete(sessionId);
162
+ });
163
+
164
+ pi.on('before_agent_start', async (event: any, ctx: any) => {
165
+ const sessionId = getSessionId(ctx);
166
+ const out: any = {};
167
+
168
+ if (sessionId) {
169
+ // The first prompt can arrive before session_start finished fetching the
170
+ // baseline; await it so the fixed boot context is never skipped.
171
+ const pending = startupRequests.get(sessionId);
172
+ if (pending) {
173
+ try { await pending; } catch {}
174
+ }
175
+ const systemPromptAppend = startupAppendBySession.get(sessionId);
176
+ if (systemPromptAppend) {
177
+ out.systemPrompt = [event?.systemPrompt || '', systemPromptAppend]
178
+ .filter(Boolean)
179
+ .join('\n\n');
180
+ }
181
+ }
182
+
183
+ if (typeof event?.prompt === 'string' && event.prompt.trim()) {
184
+ try {
185
+ const lifecycleResponse = await fetchPromptLifecycle(pluginCfg, event.prompt, sessionId);
186
+ const message = readReturnValue(lifecycleResponse)?.message;
187
+ if (message) out.message = message;
188
+ } catch (error: any) {
189
+ pi.logger?.debug?.(`lore: lifecycle recall failed: ${error.message}`);
190
+ }
191
+ }
192
+
193
+ return Object.keys(out).length > 0 ? out : undefined;
194
+ });
195
+ }
@@ -0,0 +1,25 @@
1
+ import type { ExtensionAPI } from '@mariozechner/pi-coding-agent';
2
+ import { pickPluginConfig, textResult } from './api';
3
+ import { registerTools } from './tools';
4
+ import { registerHooks } from './hooks';
5
+ import { createSkillsSession, registerSkillResourceDiscovery } from './skills';
6
+
7
+ export default function lorePiExtension(pi: ExtensionAPI) {
8
+ const pluginCfg = pickPluginConfig(pi);
9
+ const skillsSession = pluginCfg.skillsEnabled ? createSkillsSession(pluginCfg) : undefined;
10
+ if (skillsSession) registerSkillResourceDiscovery(pi, pluginCfg, skillsSession);
11
+ registerTools(pi, pluginCfg, skillsSession);
12
+ registerHooks(pi, pluginCfg);
13
+ }
14
+
15
+ export { pickPluginConfig, textResult };
16
+ export { parseMemoryUri, resolveMemoryLocator, splitParentPathAndTitle, trimSlashes, sameLocator } from './uri';
17
+ export { formatNode, formatBootView, formatRecallBlock } from './formatters';
18
+ export {
19
+ createSkillsSession,
20
+ registerSkillTools,
21
+ registerSkillResourceDiscovery,
22
+ resolveLoreHome,
23
+ validateSafeRelativePath,
24
+ computeManifestHash,
25
+ } from './skills';
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@local/lore-pi-extension",
3
+ "version": "1.12.4",
4
+ "description": "Lore memory extension for Pi agent with fixed boot baseline and recall injection",
5
+ "type": "module",
6
+ "private": true,
7
+ "scripts": {
8
+ "test": "vitest run",
9
+ "test:watch": "vitest"
10
+ },
11
+ "pi": {
12
+ "extensions": [
13
+ "./index.ts"
14
+ ]
15
+ },
16
+ "dependencies": {
17
+ "typebox": "^1.0.0"
18
+ },
19
+ "devDependencies": {
20
+ "typescript": "^6.0.2",
21
+ "vitest": "^4.1.2"
22
+ }
23
+ }