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,344 @@
1
+ import { textResult, fetchJson, hasRecallConfig } from './api';
2
+ import { resolveMemoryLocator, splitParentPathAndTitle, trimSlashes } from './uri';
3
+ import { formatNode, formatBootView, normalizeSearchResults, normalizeKeywordList, formatSearchResults, resolveSearchLimit } from './formatters';
4
+ import { registerSkillTools, type SkillsSession } from './skills';
5
+
6
+ const Type = {
7
+ String: (meta?: Record<string, unknown>) => ({ type: 'string', ...meta }),
8
+ Number: (meta?: Record<string, unknown>) => ({ type: 'number', ...meta }),
9
+ Boolean: (meta?: Record<string, unknown>) => ({ type: 'boolean', ...meta }),
10
+ Array: (items: Record<string, unknown>, meta?: Record<string, unknown>) => ({ type: 'array', items, ...meta }),
11
+ Optional: (schema: Record<string, unknown>) => ({ ...schema }),
12
+ Object: (properties: Record<string, unknown>, rest?: Record<string, unknown>) => ({
13
+ type: 'object',
14
+ properties,
15
+ ...rest,
16
+ }),
17
+ };
18
+
19
+ const RECALL_GET_NODE_DESCRIPTION = 'Open a memory node. REQUIRED when opening a URI from a <recall>: copy the exact session_id and query_id from that <recall> tag.';
20
+ const RECALL_SESSION_ID_DESCRIPTION = 'REQUIRED when the URI came from <recall>: copy the exact session_id from that <recall> tag.';
21
+ const RECALL_QUERY_ID_DESCRIPTION = 'REQUIRED when the URI came from <recall>: copy the exact query_id from that <recall> tag.';
22
+
23
+ export function registerTools(pi: any, pluginCfg: any, skillsSession?: SkillsSession) {
24
+ pi.registerTool({
25
+ name: 'lore_status',
26
+ label: 'Lore status',
27
+ description: 'Check memory backend availability and connection health.',
28
+ parameters: Type.Object({}, { additionalProperties: false }),
29
+ async execute(_toolCallId: string, _params: any = {}, _signal?: AbortSignal, _onUpdate?: unknown, _ctx?: any) {
30
+ try {
31
+ const data = await fetchJson(pluginCfg, '/health', { method: 'GET' });
32
+ return textResult(`Lore online\n\n${JSON.stringify(data, null, 2)}`, { ok: true, health: data, baseUrl: pluginCfg.baseUrl });
33
+ } catch (error: any) {
34
+ return textResult(`Lore offline: ${error.message}`, { ok: false, error: error.message, baseUrl: pluginCfg.baseUrl });
35
+ }
36
+ },
37
+ });
38
+
39
+ pi.registerTool({
40
+ name: 'lore_boot',
41
+ label: 'Lore boot',
42
+ description: 'Load the fixed boot memory view that restores the deterministic startup baseline and core operating context.',
43
+ parameters: Type.Object({}, { additionalProperties: false }),
44
+ async execute(_toolCallId: string, _params: any = {}, _signal?: AbortSignal, _onUpdate?: unknown, _ctx?: any) {
45
+ try {
46
+ const data = await fetchJson(pluginCfg, '/browse/boot', { method: 'GET' });
47
+ const content = formatBootView(data);
48
+ return textResult(content, { ok: true, content, boot: data });
49
+ } catch (error: any) {
50
+ return textResult(`Lore boot failed: ${error.message}`, { ok: false, error: error.message });
51
+ }
52
+ },
53
+ });
54
+
55
+ pi.registerTool({
56
+ name: 'lore_get_node',
57
+ label: 'Lore get node',
58
+ description: RECALL_GET_NODE_DESCRIPTION,
59
+ parameters: Type.Object({
60
+ uri: Type.String({ description: 'Full memory URI such as core://agent/pi. Use core:// or project:// to browse a domain root; bare words are paths in the default domain.' }),
61
+ nav_only: Type.Optional(Type.Boolean({ description: 'If true, skip expensive glossary processing and only return structure/navigation info.' })),
62
+ session_id: Type.Optional(Type.String({ description: RECALL_SESSION_ID_DESCRIPTION })),
63
+ query_id: Type.Optional(Type.String({ description: RECALL_QUERY_ID_DESCRIPTION })),
64
+ }),
65
+ promptSnippet: 'Open a Lore memory node by URI.',
66
+ promptGuidelines: [
67
+ 'Use lore_get_node to open a recalled Lore URI before relying on it in an answer or code change.',
68
+ 'When opening a URI from a <recall>, copy the exact session_id and query_id from that <recall> tag.',
69
+ ],
70
+ async execute(_toolCallId: string, params: any = {}, _signal?: AbortSignal, _onUpdate?: unknown, _ctx?: any) {
71
+ const navOnly = params?.nav_only === true;
72
+ const sessionId = typeof params?.session_id === 'string' && params.session_id.trim() ? params.session_id.trim() : '';
73
+ const queryId = typeof params?.query_id === 'string' && params.query_id.trim() ? params.query_id.trim() : '';
74
+ let domain = pluginCfg.defaultDomain;
75
+ let path = '';
76
+ try {
77
+ ({ domain, path } = resolveMemoryLocator(params, { defaultDomain: pluginCfg.defaultDomain, pathKey: '__unused_path', allowEmptyPath: true, label: 'uri' }));
78
+ const qs = new URLSearchParams({ domain, path, nav_only: String(navOnly) });
79
+ const data = await fetchJson(pluginCfg, `/browse/node?${qs.toString()}`, { method: 'GET' });
80
+ const node = data?.node || {};
81
+ if (queryId && node?.uri) {
82
+ try {
83
+ await fetchJson(pluginCfg, '/browse/recall/usage', {
84
+ method: 'POST',
85
+ body: JSON.stringify({
86
+ query_id: queryId,
87
+ session_id: sessionId || 'pi-embedded',
88
+ node_uris: [node.uri],
89
+ source: 'tool:lore_get_node',
90
+ success: true,
91
+ }),
92
+ });
93
+ } catch {
94
+ // best effort
95
+ }
96
+ }
97
+ return textResult(formatNode(data), { ok: true, node, children: data?.children || [] });
98
+ } catch (error: any) {
99
+ return textResult(`Lore get node failed: ${error.message}`, { ok: false, error: error.message, domain, path });
100
+ }
101
+ },
102
+ });
103
+
104
+ pi.registerTool({
105
+ name: 'lore_search',
106
+ label: 'Lore search',
107
+ description: 'Search memories by keyword, semantic similarity, or both. Pass full=true to include the full content of the top result.',
108
+ parameters: Type.Object({
109
+ query: Type.String({ description: 'Search query text. Use a meaningful keyword or phrase; passing an empty string or * with a domain filter browses that domain root.' }),
110
+ domain: Type.Optional(Type.String({ description: 'Optional domain filter to narrow the search.' })),
111
+ limit: Type.Optional(Type.Number({ minimum: 1, maximum: 20, description: 'Maximum number of results (1-20, default 5).' })),
112
+ full: Type.Optional(Type.Boolean({ description: 'Include the full content of the top result.' })),
113
+ }),
114
+ promptSnippet: 'Search Lore long-term memory for durable project or user context.',
115
+ promptGuidelines: [
116
+ 'Use lore_search when the user asks about prior decisions, saved preferences, project memory, or durable context.',
117
+ ],
118
+ async execute(_toolCallId: string, params: any = {}, _signal?: AbortSignal, _onUpdate?: unknown, _ctx?: any) {
119
+ const query = String(params?.query || '').trim();
120
+ const domainFilter = typeof params?.domain === 'string' && params.domain.trim() ? params.domain.trim() : null;
121
+ const full = params?.full === true;
122
+ const safeLimit = resolveSearchLimit(params?.limit);
123
+ const safeContentLimit = full ? 1 : 0;
124
+ try {
125
+ if (domainFilter && (!query || query === '*')) {
126
+ const qs = new URLSearchParams({ domain: domainFilter, path: '', nav_only: 'true' });
127
+ const data = await fetchJson(pluginCfg, `/browse/node?${qs.toString()}`, { method: 'GET' });
128
+ const text = `Domain root: ${domainFilter}://\n\n${formatNode(data)}`;
129
+ return textResult(text, { ok: true, mode: 'domain_root', domain: domainFilter, node: data?.node, children: data?.children || [] });
130
+ }
131
+ let data;
132
+ if (hasRecallConfig(pluginCfg)) {
133
+ data = await fetchJson(pluginCfg, '/browse/search', {
134
+ method: 'POST',
135
+ body: JSON.stringify({
136
+ query,
137
+ domain: domainFilter,
138
+ limit: safeLimit,
139
+ content_limit: safeContentLimit,
140
+ full,
141
+ hybrid: true,
142
+ }),
143
+ });
144
+ } else {
145
+ const qs = new URLSearchParams({ query });
146
+ if (domainFilter) qs.set('domain', domainFilter);
147
+ qs.set('limit', String(safeLimit));
148
+ qs.set('content_limit', String(safeContentLimit));
149
+ qs.set('full', String(full));
150
+ data = await fetchJson(pluginCfg, `/browse/search?${qs.toString()}`, { method: 'GET' });
151
+ }
152
+ const results = normalizeSearchResults(data);
153
+ const meta = data?.meta || null;
154
+ const text = results.length > 0
155
+ ? formatSearchResults(results, { full })
156
+ : `No matching memories found${domainFilter ? ` in domain ${domainFilter}` : ''}.`;
157
+ const suffix = meta?.semantic_error ? `\n\nSemantic fallback skipped: ${meta.semantic_error}` : '';
158
+ return textResult(`${text}${suffix}`, { ok: true, results, meta });
159
+ } catch (error: any) {
160
+ return textResult(`Lore search failed: ${error.message}`, { ok: false, error: error.message, query });
161
+ }
162
+ },
163
+ });
164
+
165
+ pi.registerTool({
166
+ name: 'lore_list_domains',
167
+ label: 'Lore list domains',
168
+ description: 'Browse the top-level memory domains available in the memory system.',
169
+ parameters: Type.Object({}, { additionalProperties: false }),
170
+ async execute(_toolCallId: string, _params: any = {}, _signal?: AbortSignal, _onUpdate?: unknown, _ctx?: any) {
171
+ try {
172
+ const data = await fetchJson(pluginCfg, '/browse/domains', { method: 'GET' });
173
+ const text = Array.isArray(data) && data.length > 0
174
+ ? data.map((item: any) => `- ${item.domain} (${item.root_count}) — open root with lore_get_node uri=\"${item.domain}://\" nav_only=true`).join('\n')
175
+ : 'No domains found.';
176
+ return textResult(text, { ok: true, domains: data });
177
+ } catch (error: any) {
178
+ return textResult(`Lore list domains failed: ${error.message}`, { ok: false, error: error.message });
179
+ }
180
+ },
181
+ });
182
+
183
+ pi.registerTool({
184
+ name: 'lore_create_node',
185
+ label: 'Lore create node',
186
+ description: 'Create a new long-term memory concept in the Lore living semantic tree. A URI path names the concept identity with durable snake_case segments; event time belongs in the node narrative or in explicit archive, diary, release, or incident concepts. For multi-segment paths, first make the parent abstraction real with content, disclosure, and glossary, then place the child under that conceptual home. Prefer update or merge when an existing concept already owns the fact.',
187
+ parameters: Type.Object({
188
+ content: Type.String({ description: 'Memory text body.' }),
189
+ priority: Type.Number({ minimum: 0, description: 'Importance tier: 0=core identity (max 5), 1=key facts (max 15), 2+=general.' }),
190
+ glossary: Type.Array(Type.String({ description: 'Search keyword.' }), { maxItems: 12, description: 'Terms a person would actually type to find this; avoid commit hashes, version numbers, IPs/ports, file paths, and ALL_CAPS test tokens.' }),
191
+ uri: Type.Optional(Type.String({ description: 'Optional final memory URI. It names a durable concept identity; event time belongs in content or in explicit archive, diary, release, or incident concepts. Intermediate paths grow from real parent abstractions with content.' })),
192
+ domain: Type.Optional(Type.String({ description: 'Target memory domain when not using uri.' })),
193
+ parent_path: Type.Optional(Type.String({ description: 'Parent concept path inside the chosen domain; for multi-segment paths this parent abstraction explains why the children belong together and carries content, disclosure, and glossary.' })),
194
+ title: Type.Optional(Type.String({ description: 'Final concept segment for the new memory; name the reusable idea, module, decision, preference, or archive concept.' })),
195
+ disclosure: Type.Optional(Type.String({ description: 'When this memory should be recalled.' })),
196
+ }),
197
+ async execute(_toolCallId: string, params: any = {}, _signal?: AbortSignal, _onUpdate?: unknown, _ctx?: any) {
198
+ const glossary = normalizeKeywordList(params?.glossary);
199
+ const body: any = {
200
+ domain: typeof params?.domain === 'string' && params.domain.trim() ? params.domain.trim() : pluginCfg.defaultDomain,
201
+ parent_path: typeof params?.parent_path === 'string' ? trimSlashes(params.parent_path) : '',
202
+ content: String(params?.content || ''),
203
+ priority: Number(params?.priority),
204
+ glossary,
205
+ };
206
+ try {
207
+ if (Array.isArray(params?.glossary) && params.glossary.length > 12) {
208
+ throw new Error(`glossary accepts at most 12 keywords (got ${params.glossary.length})`);
209
+ }
210
+ if (typeof params?.title === 'string') body.title = params.title.trim();
211
+ if (typeof params?.disclosure === 'string') body.disclosure = params.disclosure;
212
+
213
+ if (typeof params?.uri === 'string' && params.uri.trim()) {
214
+ const target = resolveMemoryLocator(params, {
215
+ defaultDomain: pluginCfg.defaultDomain,
216
+ domainKey: 'domain',
217
+ pathKey: 'parent_path',
218
+ uriKey: 'uri',
219
+ allowEmptyPath: false,
220
+ label: 'uri',
221
+ });
222
+ const derived = splitParentPathAndTitle(target.path);
223
+ if (!derived.title) {
224
+ throw new Error('Create target URI must include a final path segment, like project://workflow/browser_policy');
225
+ }
226
+ if (typeof params?.title === 'string' && params.title.trim() && params.title.trim() !== derived.title) {
227
+ throw new Error(`Conflicting uri and title: ${derived.title} vs ${params.title.trim()}`);
228
+ }
229
+ body.domain = target.domain;
230
+ body.parent_path = derived.parentPath;
231
+ body.title = derived.title;
232
+ }
233
+
234
+ const data = await fetchJson(pluginCfg, '/browse/node', { method: 'POST', body: JSON.stringify(body) });
235
+ const suffix = glossary.length > 0 ? `\nGlossary: ${glossary.join(', ')}` : '';
236
+ return textResult(`Created ${data?.uri || `${body.domain}://${body.parent_path}`}${suffix}`, { ok: true, result: data, glossary });
237
+ } catch (error: any) {
238
+ return textResult(`Lore create failed: ${error.message}`, { ok: false, error: error.message, body, glossary });
239
+ }
240
+ },
241
+ });
242
+
243
+ pi.registerTool({
244
+ name: 'lore_update_node',
245
+ label: 'Lore update node',
246
+ description: 'Revise an existing long-term memory node. Prefer targeted edits (old_text/new_text) over replacing the whole content; rewrite the node to keep it current instead of appending dated logs. Omitted content, metadata, and glossary mutation fields are left unchanged.',
247
+ parameters: Type.Object({
248
+ uri: Type.String({ description: 'Full memory URI for the node you want to revise.' }),
249
+ content: Type.Optional(Type.String({ description: 'New content to replace the existing content; omit to leave content unchanged.' })),
250
+ old_text: Type.Optional(Type.String({ description: 'Exact passage in the current content to replace; must match exactly one occurrence.' })),
251
+ new_text: Type.Optional(Type.String({ description: 'Replacement for old_text; empty or omitted deletes the passage.' })),
252
+ priority: Type.Optional(Type.Number({ minimum: 0, description: 'New priority level; omit to leave priority unchanged.' })),
253
+ disclosure: Type.Optional(Type.String({ description: 'New disclosure / trigger condition; omit to leave disclosure unchanged.' })),
254
+ glossary_add: Type.Optional(Type.Array(Type.String({ description: 'Search keyword.' }), { description: 'Keywords to add as part of this same node update event.' })),
255
+ glossary_remove: Type.Optional(Type.Array(Type.String({ description: 'Search keyword.' }), { description: 'Keywords to remove as part of this same node update event.' })),
256
+ }),
257
+ async execute(_toolCallId: string, params: any = {}, _signal?: AbortSignal, _onUpdate?: unknown, _ctx?: any) {
258
+ const glossaryAdd = normalizeKeywordList(params?.glossary_add);
259
+ const glossaryRemove = normalizeKeywordList(params?.glossary_remove);
260
+ let domain = pluginCfg.defaultDomain;
261
+ let path = '';
262
+ try {
263
+ ({ domain, path } = resolveMemoryLocator(params, { defaultDomain: pluginCfg.defaultDomain, pathKey: '__unused_path', allowEmptyPath: false, label: 'uri' }));
264
+ const oldText = typeof params?.old_text === 'string' ? params.old_text : null;
265
+ const body: any = {};
266
+ if (oldText !== null) {
267
+ if (oldText.length === 0) throw new Error('old_text must not be empty');
268
+ if (typeof params?.content === 'string') throw new Error('Pass either content or old_text/new_text, not both');
269
+ const current = await fetchJson(pluginCfg, `/browse/node?${new URLSearchParams({ domain, path }).toString()}`, { method: 'GET' });
270
+ const currentContent = String(current?.node?.content ?? '');
271
+ const occurrences = currentContent.split(oldText).length - 1;
272
+ if (occurrences === 0) throw new Error('old_text not found');
273
+ if (occurrences > 1) throw new Error(`old_text found ${occurrences} times`);
274
+ body.content = currentContent.replace(oldText, typeof params?.new_text === 'string' ? params.new_text : '');
275
+ } else if (typeof params?.content === 'string') {
276
+ body.content = params.content;
277
+ }
278
+ if (Number.isFinite(params?.priority)) body.priority = params.priority;
279
+ if (typeof params?.disclosure === 'string') body.disclosure = params.disclosure;
280
+ if (glossaryAdd.length > 0) body.glossary_add = glossaryAdd;
281
+ if (glossaryRemove.length > 0) body.glossary_remove = glossaryRemove;
282
+ const qs = new URLSearchParams({ domain, path });
283
+ const data = await fetchJson(pluginCfg, `/browse/node?${qs.toString()}`, { method: 'PUT', body: JSON.stringify(body) });
284
+ const suffixParts: string[] = [];
285
+ if (glossaryAdd.length > 0) suffixParts.push(`glossary+ ${glossaryAdd.join(', ')}`);
286
+ if (glossaryRemove.length > 0) suffixParts.push(`glossary- ${glossaryRemove.join(', ')}`);
287
+ const suffix = suffixParts.length > 0 ? `\n${suffixParts.join('\n')}` : '';
288
+ return textResult(`Updated ${data?.uri || `${domain}://${path}`}${suffix}`, { ok: true, result: data, glossary_add: glossaryAdd, glossary_remove: glossaryRemove });
289
+ } catch (error: any) {
290
+ return textResult(`Lore update failed: ${error.message}`, { ok: false, error: error.message, domain, path, glossary_add: glossaryAdd, glossary_remove: glossaryRemove });
291
+ }
292
+ },
293
+ });
294
+
295
+ pi.registerTool({
296
+ name: 'lore_delete_node',
297
+ label: 'Lore delete node',
298
+ description: 'Remove a memory path that is obsolete, duplicated, or no longer wanted.',
299
+ parameters: Type.Object({
300
+ uri: Type.String({ description: 'Full memory URI for the path you want to remove.' }),
301
+ }),
302
+ async execute(_toolCallId: string, params: any = {}, _signal?: AbortSignal, _onUpdate?: unknown, _ctx?: any) {
303
+ let domain = pluginCfg.defaultDomain;
304
+ let path = '';
305
+ try {
306
+ ({ domain, path } = resolveMemoryLocator(params, { defaultDomain: pluginCfg.defaultDomain, pathKey: '__unused_path', allowEmptyPath: false, label: 'uri' }));
307
+ const qs = new URLSearchParams({ domain, path });
308
+ const data = await fetchJson(pluginCfg, `/browse/node?${qs.toString()}`, { method: 'DELETE' });
309
+ const deletedUri = String(data?.deleted_uri || data?.uri || `${domain}://${path}`).trim();
310
+ const canonicalUri = String(data?.uri || deletedUri).trim();
311
+ const suffix = canonicalUri && canonicalUri !== deletedUri ? ` (canonical: ${canonicalUri})` : '';
312
+ return textResult(`Deleted ${deletedUri}${suffix}`, { ok: true, result: data });
313
+ } catch (error: any) {
314
+ return textResult(`Lore delete failed: ${error.message}`, { ok: false, error: error.message, domain, path });
315
+ }
316
+ },
317
+ });
318
+
319
+ pi.registerTool({
320
+ name: 'lore_move_node',
321
+ label: 'Lore move node',
322
+ description: 'Move or rename a memory concept inside the semantic memory tree. The target parent represents the conceptual home; it must already be a real parent abstraction with memory content so the move can reparent the node and its subtree into that abstraction.',
323
+ parameters: Type.Object({
324
+ old_uri: Type.String({ description: 'Current memory URI to move from.' }),
325
+ new_uri: Type.String({ description: 'New memory URI. For multi-segment paths, the target parent is the parent abstraction that becomes the node conceptual home.' }),
326
+ }),
327
+ async execute(_toolCallId: string, params: any = {}, _signal?: AbortSignal, _onUpdate?: unknown, _ctx?: any) {
328
+ const body = {
329
+ old_uri: String(params?.old_uri || '').trim(),
330
+ new_uri: String(params?.new_uri || '').trim(),
331
+ };
332
+ try {
333
+ const data = await fetchJson(pluginCfg, '/browse/move', { method: 'POST', body: JSON.stringify(body) });
334
+ const oldUri = String(data?.old_uri || body.old_uri).trim();
335
+ const newUri = String(data?.new_uri || data?.uri || body.new_uri).trim();
336
+ return textResult(`Moved ${oldUri} → ${newUri}`, { ok: true, result: data });
337
+ } catch (error: any) {
338
+ return textResult(`Lore move failed: ${error.message}`, { ok: false, error: error.message, body });
339
+ }
340
+ },
341
+ });
342
+
343
+ if (pluginCfg.skillsEnabled) registerSkillTools(pi, pluginCfg, skillsSession);
344
+ }
@@ -0,0 +1,67 @@
1
+ const DEFAULT_DOMAIN = 'core';
2
+
3
+ export function trimSlashes(value: any) {
4
+ return String(value || '').trim().replace(/^\/+|\/+$/g, '');
5
+ }
6
+
7
+ export function parseMemoryUri(value: any, fallbackDomain = DEFAULT_DOMAIN) {
8
+ const raw = String(value || '').trim();
9
+ if (!raw) return { domain: fallbackDomain, path: '' };
10
+ if (raw.includes('://')) {
11
+ const [domainPart, pathPart] = raw.split('://', 2);
12
+ return { domain: domainPart.trim() || fallbackDomain, path: trimSlashes(pathPart) };
13
+ }
14
+ return { domain: fallbackDomain, path: trimSlashes(raw) };
15
+ }
16
+
17
+ export function sameLocator(a: any, b: any) {
18
+ return a?.domain === b?.domain && a?.path === b?.path;
19
+ }
20
+
21
+ export function resolveMemoryLocator(params: any, {
22
+ defaultDomain = DEFAULT_DOMAIN,
23
+ domainKey = 'domain',
24
+ pathKey = 'path',
25
+ uriKey = 'uri',
26
+ allowEmptyPath = true,
27
+ label = 'path',
28
+ }: any = {}) {
29
+ const explicitDomain = typeof params?.[domainKey] === 'string' && params[domainKey].trim()
30
+ ? params[domainKey].trim()
31
+ : '';
32
+ const fallbackDomain = explicitDomain || defaultDomain;
33
+ const rawPath = typeof params?.[pathKey] === 'string' ? params[pathKey].trim() : '';
34
+ const rawUri = typeof params?.[uriKey] === 'string' ? params[uriKey].trim() : '';
35
+
36
+ if (rawPath.includes('://')) {
37
+ throw new Error(`Invalid ${pathKey}: expected a relative path inside ${domainKey}, got a full URI. Pass ${uriKey}="domain://path" instead.`);
38
+ }
39
+
40
+ const locatorFromPath = rawPath
41
+ ? { domain: fallbackDomain, path: trimSlashes(rawPath) }
42
+ : { domain: fallbackDomain, path: '' };
43
+ const locatorFromUri = rawUri ? parseMemoryUri(rawUri, fallbackDomain) : null;
44
+
45
+ if (locatorFromUri && rawPath && !sameLocator(locatorFromUri, locatorFromPath)) {
46
+ throw new Error(`Conflicting ${uriKey} and ${pathKey}: ${locatorFromUri.domain}://${locatorFromUri.path} vs ${locatorFromPath.domain}://${locatorFromPath.path}`);
47
+ }
48
+ if (locatorFromUri && explicitDomain && locatorFromUri.domain !== explicitDomain) {
49
+ throw new Error(`Conflicting ${uriKey} and ${domainKey}: ${locatorFromUri.domain} vs ${explicitDomain}`);
50
+ }
51
+
52
+ const locator = locatorFromUri || locatorFromPath;
53
+ if (!allowEmptyPath && !locator.path) {
54
+ throw new Error(`${label} is required. Pass ${uriKey}="domain://path" or ${pathKey}="relative/path".`);
55
+ }
56
+ return locator;
57
+ }
58
+
59
+ export function splitParentPathAndTitle(path: string) {
60
+ const cleanPath = trimSlashes(path);
61
+ const segments = cleanPath.split('/').filter(Boolean);
62
+ if (segments.length === 0) return { parentPath: '', title: '' };
63
+ return {
64
+ parentPath: segments.slice(0, -1).join('/'),
65
+ title: segments[segments.length - 1],
66
+ };
67
+ }
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Lore Skill work-copy core type declarations.
3
+ * Schema: lore.skill.workcopy.v1
4
+ */
5
+
6
+ export const LORE_SKILL_MARKER: '.lore-skill-marker.json';
7
+ export const LEGACY_LORE_SKILL_MARKER: '.lore-skill.json';
8
+ export const LORE_SKILL_SCHEMA: 'lore.skill.workcopy.v1';
9
+ export const LEGACY_MIRROR_SCHEMA: 'lore.skill.mirror.v1';
10
+ export const SKILL_MD: 'SKILL.md';
11
+
12
+ export type WorkCopyState =
13
+ | 'ready'
14
+ | 'missing'
15
+ | 'outdated'
16
+ | 'tampered'
17
+ | 'unmanaged'
18
+ | 'invalid'
19
+ | 'sync_error';
20
+
21
+ /** @deprecated Prefer WorkCopyState. */
22
+ export type MirrorState = WorkCopyState;
23
+
24
+ export interface SkillSummary {
25
+ project_id?: string;
26
+ id: string;
27
+ skill_id?: string;
28
+ name: string;
29
+ description?: string;
30
+ enabled?: boolean;
31
+ version?: string | number;
32
+ expected_version?: string | number;
33
+ revision_hash?: string;
34
+ expected_revision_hash?: string;
35
+ manifest_hash?: string;
36
+ [key: string]: unknown;
37
+ }
38
+
39
+ export interface SkillFile {
40
+ path: string;
41
+ media_type?: string;
42
+ size?: number;
43
+ size_bytes?: number;
44
+ sha256?: string;
45
+ content_sha256?: string;
46
+ content?: string;
47
+ content_base64?: string;
48
+ }
49
+
50
+ export interface SkillDetail extends SkillSummary {
51
+ files?: SkillFile[];
52
+ }
53
+
54
+ export interface SkillCandidate {
55
+ id?: string;
56
+ skill_id?: string;
57
+ name?: string;
58
+ description?: string;
59
+ version?: string | number;
60
+ expected_version?: string | number;
61
+ revision_hash?: string;
62
+ expected_revision_hash?: string;
63
+ manifest_hash?: string;
64
+ [key: string]: unknown;
65
+ }
66
+
67
+ export interface WorkCopyMarker {
68
+ schema: string;
69
+ project_id: string;
70
+ skill_id: string;
71
+ name: string;
72
+ version: string | number;
73
+ /** Relative paths of the server-managed files owned by Core (ownership boundary). */
74
+ managed_files: string[];
75
+ synced_at: string;
76
+ revision_hash?: string;
77
+ manifest_hash?: string;
78
+ /** Server-side manifest of the unadapted payload; present only when a host adapter changed the written file set. */
79
+ source_manifest_hash?: string;
80
+ /** Server-managed package files are read-only; the directory itself is writable for local outputs. */
81
+ readonly?: boolean;
82
+ }
83
+
84
+ /** @deprecated Prefer WorkCopyMarker. */
85
+ export type MirrorMarker = WorkCopyMarker;
86
+
87
+ export interface WorkCopyStatus {
88
+ name: string;
89
+ skill_id?: string;
90
+ state: WorkCopyState;
91
+ path?: string;
92
+ version?: string | number;
93
+ revision_hash?: string;
94
+ message?: string;
95
+ }
96
+
97
+ /** @deprecated Prefer WorkCopyStatus. */
98
+ export type MirrorStatus = WorkCopyStatus;
99
+
100
+ export interface SkillCatalog {
101
+ project_id: string;
102
+ catalog_revision: string;
103
+ }
104
+
105
+ export function resolveLoreHome(env?: NodeJS.ProcessEnv): string;
106
+ export function workCopiesRoot(loreHome: string): string;
107
+ export function projectWorkCopyRoot(loreHome: string, projectId: string): string;
108
+ /** @deprecated Prefer projectWorkCopyRoot. */
109
+ export function skillsRoot(loreHome: string, projectId: string): string;
110
+ /** @deprecated Prefer projectWorkCopyRoot. */
111
+ export function installedRoot(loreHome: string, projectId: string): string;
112
+ export function stagingRoot(loreHome: string, projectId: string): string;
113
+ export function skillInstallPath(loreHome: string, projectId: string, skillName: string): string;
114
+ export function sanitizeSegment(value: string): string;
115
+ export function validateSafeRelativePath(rawPath: string): string;
116
+
117
+ export function skillIdOf(
118
+ value: SkillSummary | SkillCandidate | SkillDetail | null | undefined,
119
+ ): string;
120
+ export function skillVersionOf(
121
+ value: SkillSummary | SkillCandidate | SkillDetail | null | undefined,
122
+ ): string | number | undefined;
123
+ export function skillRevisionOf(
124
+ value: SkillSummary | SkillCandidate | SkillDetail | null | undefined,
125
+ ): string;
126
+
127
+ export function validateManagedFileList(
128
+ rawPaths: unknown,
129
+ opts?: { requireSkillMd?: boolean },
130
+ ): string[];
131
+
132
+ export function normalizeSkillSummary(value: any): SkillSummary;
133
+ export function normalizeSkillDetail(value: any): SkillDetail;
134
+ export function normalizeSkillCandidate(value: any): SkillCandidate;
135
+
136
+ export function sha256Buffer(buf: Buffer): string;
137
+ export function sha256Text(text: string): string;
138
+ export function decodeSkillFileContent(file: SkillFile): Buffer;
139
+ export function computeManifestHash(
140
+ files: Array<{ path: string; sha256: string; size?: number }>,
141
+ ): string;
142
+
143
+ /**
144
+ * Hash ONLY the server-managed files listed in the work-copy marker.
145
+ * Extra local files are never hashed, so they cannot trigger tamper.
146
+ * Throws when a managed file is missing or is not a regular file.
147
+ */
148
+ export function hashLocalSkillFiles(dir: string): {
149
+ files: Array<{ path: string; sha256: string; size: number }>;
150
+ manifest_hash: string;
151
+ };
152
+
153
+ export function readWorkCopyMarker(dir: string): WorkCopyMarker | null;
154
+ /** @deprecated Prefer readWorkCopyMarker. */
155
+ export const readMirrorMarker: typeof readWorkCopyMarker;
156
+
157
+ /**
158
+ * Inspect a local work copy. Returns 'tampered' only when a server-managed file
159
+ * (from marker.managed_files) is missing, is not a regular file, or its hash does not
160
+ * match the marker manifest_hash. Extra local files never trigger tamper.
161
+ */
162
+ export function inspectLocalWorkCopy(
163
+ loreHome: string,
164
+ projectId: string,
165
+ skillName: string,
166
+ expected?: {
167
+ skill_id?: string;
168
+ version?: string | number;
169
+ revision_hash?: string;
170
+ manifest_hash?: string;
171
+ },
172
+ ): WorkCopyStatus;
173
+ /** @deprecated Prefer inspectLocalWorkCopy. */
174
+ export const inspectLocalMirror: typeof inspectLocalWorkCopy;
175
+
176
+ export function validateSkillPayload(detail: SkillDetail): {
177
+ files: Array<{ path: string; buffer: Buffer; sha256: string; media_type?: string }>;
178
+ manifest_hash: string;
179
+ };
180
+
181
+ /**
182
+ * Materialize (or upgrade/migrate) a local work copy from server detail.
183
+ * Existing managed work copies are seeded so extra local files are preserved;
184
+ * obsolete managed files are removed and incoming managed files written. A new
185
+ * managed path that conflicts with a preserved local artifact fails safely.
186
+ * Installed directories are writable (0755 POSIX); server-managed files and the
187
+ * marker are 0444.
188
+ */
189
+ export function materializeSkillWorkCopy(opts: {
190
+ loreHome: string;
191
+ projectId: string;
192
+ detail: SkillDetail;
193
+ }): { installPath: string; marker: WorkCopyMarker };
194
+
195
+ /** @deprecated Prefer materializeSkillWorkCopy. */
196
+ export function writeSkillMirrorAtomic(opts: {
197
+ loreHome: string;
198
+ projectId: string;
199
+ detail: SkillDetail;
200
+ fileMode?: number;
201
+ dirMode?: number;
202
+ }): { installPath: string; marker: WorkCopyMarker };
203
+
204
+ /**
205
+ * Materialize a work copy at an explicit install path and staging base (same
206
+ * filesystem). `sourceManifestHash` records the server-side manifest of the
207
+ * unadapted payload when a host adapter changed the written file set.
208
+ */
209
+ export function materializeSkillWorkCopyAt(opts: {
210
+ installPath: string;
211
+ stagingBase: string;
212
+ projectId: string;
213
+ detail: SkillDetail;
214
+ sourceManifestHash?: string;
215
+ }): { installPath: string; marker: WorkCopyMarker };
216
+
217
+ /**
218
+ * Ensure a local work copy for the skill and return local SKILL.md + absolute skill_dir.
219
+ * Missing/outdated/tampered/legacy copies are rematerialized from server detail
220
+ * (preserving extra local files). Same version with intact managed files reuses the
221
+ * local copy. Installed directories are writable; server-managed files are read-only.
222
+ */
223
+ export function ensureSkillWorkCopy(opts: {
224
+ loreHome?: string;
225
+ skillId: string;
226
+ projectId?: string;
227
+ loadSkill: (skillId: string) => Promise<SkillDetail>;
228
+ loadCatalog?: () => Promise<SkillCatalog>;
229
+ }): Promise<{
230
+ skill_dir: string;
231
+ skill_md: string;
232
+ skill_md_path: string;
233
+ marker: WorkCopyMarker;
234
+ project_id: string;
235
+ skill: SkillDetail;
236
+ server_version: string | number | undefined;
237
+ local_version: string | number;
238
+ downloaded: boolean;
239
+ }>;
240
+
241
+ export function listLocalWorkCopyStatuses(loreHome: string, projectId: string): WorkCopyStatus[];
242
+ export function listAllLocalWorkCopyStatuses(loreHome: string): Array<WorkCopyStatus & { project_id: string }>;
243
+ /** @deprecated Prefer listLocalWorkCopyStatuses. */
244
+ export const listLocalMirrorStatuses: typeof listLocalWorkCopyStatuses;
245
+
246
+ export interface SkillSyncResult {
247
+ created: string[];
248
+ updated: string[];
249
+ unchanged: string[];
250
+ removed: string[];
251
+ conflicts: string[];
252
+ errors: Array<{ name: string; message: string }>;
253
+ }
254
+
255
+ /**
256
+ * Reconcile a host-native skills directory with the server catalog. See
257
+ * shared/skill-workcopy/index.mjs for the full contract (conflicts, unchanged
258
+ * fast path, adaptation, removal, and staging semantics).
259
+ */
260
+ export function syncSkillsToDir(opts: {
261
+ root: string;
262
+ projectId: string;
263
+ skills: SkillSummary[];
264
+ loadSkill: (skillId: string) => Promise<SkillDetail>;
265
+ adapt?: (detail: SkillDetail) => SkillDetail | Promise<SkillDetail>;
266
+ }): Promise<SkillSyncResult>;