@designerbyron/lifecode-rag 0.0.0-stage → 1.0.0

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 (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +191 -2
  3. package/bin/lifecode-rag.mjs +449 -0
  4. package/client.js +2801 -0
  5. package/cordis.patch.yml +3 -0
  6. package/docs/ARCHITECTURE-v0.2.md +269 -0
  7. package/docs/AUTO-DISCOVERY.md +111 -0
  8. package/docs/AUTOMATION-POLICIES.md +232 -0
  9. package/docs/CONTRATO-v0.1.md +195 -0
  10. package/docs/EMBEDDING-PROVIDERS.md +105 -0
  11. package/docs/OBSERVABILITY.md +241 -0
  12. package/docs/PA-UI-0-API-CONTRACT.md +802 -0
  13. package/docs/PERFORMANCE-BUDGETS.md +118 -0
  14. package/docs/PROJECT-AWARE-ARCHITECTURE.md +580 -0
  15. package/docs/PROJECT-AWARE-DATA-CONTRACT.md +411 -0
  16. package/docs/PROJECT-AWARE-ERROR-CONTRACT.md +112 -0
  17. package/docs/PROJECT-AWARE-SESSION-CONTRACT.md +120 -0
  18. package/docs/WORKSPACE-API.md +239 -0
  19. package/icon.svg +7 -0
  20. package/index.js +198 -0
  21. package/lib/audit-export.mjs +70 -0
  22. package/lib/audit.mjs +120 -0
  23. package/lib/auto-context.mjs +322 -0
  24. package/lib/automation.mjs +214 -0
  25. package/lib/chunk.mjs +100 -0
  26. package/lib/config-resolve.mjs +119 -0
  27. package/lib/context.mjs +150 -0
  28. package/lib/conversation-events.mjs +145 -0
  29. package/lib/db.mjs +309 -0
  30. package/lib/diagnose.mjs +197 -0
  31. package/lib/discovery.mjs +402 -0
  32. package/lib/doctor.mjs +82 -0
  33. package/lib/embed.mjs +96 -0
  34. package/lib/embedders.mjs +103 -0
  35. package/lib/errors.mjs +227 -0
  36. package/lib/exec-context.mjs +238 -0
  37. package/lib/extract.mjs +260 -0
  38. package/lib/harness-workspaces.mjs +85 -0
  39. package/lib/hash.mjs +34 -0
  40. package/lib/ingest.mjs +239 -0
  41. package/lib/inputs.mjs +67 -0
  42. package/lib/library-state.mjs +252 -0
  43. package/lib/maintenance.mjs +113 -0
  44. package/lib/metrics.mjs +164 -0
  45. package/lib/migrate.mjs +373 -0
  46. package/lib/operations.mjs +132 -0
  47. package/lib/pa-api.mjs +517 -0
  48. package/lib/paths.mjs +345 -0
  49. package/lib/policy.mjs +125 -0
  50. package/lib/profile.mjs +128 -0
  51. package/lib/readmodel.mjs +159 -0
  52. package/lib/recovery.mjs +557 -0
  53. package/lib/registry-schema.mjs +206 -0
  54. package/lib/registry.mjs +406 -0
  55. package/lib/resolve.mjs +311 -0
  56. package/lib/retention.mjs +143 -0
  57. package/lib/revocation.mjs +124 -0
  58. package/lib/roots-structure.mjs +224 -0
  59. package/lib/schema.mjs +173 -0
  60. package/lib/scope-ops.mjs +379 -0
  61. package/lib/scope-stores.mjs +128 -0
  62. package/lib/search.mjs +345 -0
  63. package/lib/selection.mjs +150 -0
  64. package/lib/server.mjs +335 -0
  65. package/lib/session-identity.mjs +51 -0
  66. package/lib/sessions.mjs +343 -0
  67. package/lib/sync-scheduler.mjs +354 -0
  68. package/lib/sync.mjs +755 -0
  69. package/lib/tags.mjs +45 -0
  70. package/lib/tools.mjs +364 -0
  71. package/lib/trusted-roots.mjs +149 -0
  72. package/lib/worker-context.mjs +22 -0
  73. package/package.json +67 -5
package/lib/server.mjs ADDED
@@ -0,0 +1,335 @@
1
+ /**
2
+ * API HTTP local del Workspace de LifeCode RAG.
3
+ *
4
+ * - Sin dependencias: un handler de Node (`http`) que el host monta con `ctx.webServer.register`.
5
+ * - S?lo loopback: se comprueba `Host` para dificultar DNS rebinding; las escrituras exigen adem?s
6
+ * la cabecera `x-lifecode-rag: 1` y `content-type: application/json` (CSRF). **No es autenticaci?n**:
7
+ * un proceso local puede falsificar ambas. Se documenta as? en `WORKSPACE-API.md`.
8
+ * - Toda mutaci?n destructiva exige `confirm: true` en el cuerpo: el bot?n del panel lo pone, una
9
+ * petici?n suelta no lo adivina.
10
+ * - El actor de auditor?a es `ui` para acciones del panel; las herramientas siguen siendo `model`.
11
+ */
12
+
13
+ import { appendAudit } from './audit.mjs';
14
+ import { assembleContextAsync } from './context.mjs';
15
+ import { closeDatabase, openDatabase } from './db.mjs';
16
+ import { createEmbedder } from './embedders.mjs';
17
+ import { RagError, httpStatusFor } from './errors.mjs';
18
+ import { expandInputs } from './inputs.mjs';
19
+ import { ingestFiles } from './ingest.mjs';
20
+ import { forgetSource, reindex } from './maintenance.mjs';
21
+ import { purgeMetrics, retentionCutoff, series as metricSeries, summary as metricsSummary } from './metrics.mjs';
22
+ import { loadConfig, ragRoot, storePaths, writeConfig } from './paths.mjs';
23
+ import { activityFeed, buildSnapshot, listSourceRows } from './readmodel.mjs';
24
+ import { getSource, listSources, search } from './search.mjs';
25
+
26
+ export const API_PREFIX = '/lifecode-rag/api';
27
+ const VERSION = '1.0.0';
28
+ const BODY_LIMIT = 1_000_000;
29
+
30
+ // El status de cada código vive en `lib/errors.mjs` (`httpStatusFor`). Esta API mantiene las
31
+ // diferencias documentadas de su contrato v0.1 mediante `LEGACY_HTTP_OVERRIDES`, no con una tabla propia.
32
+
33
+ export class ApiError extends Error {
34
+ constructor(status, code, message, details = undefined) {
35
+ super(message);
36
+ this.status = status;
37
+ this.code = code;
38
+ this.details = details;
39
+ }
40
+ }
41
+
42
+ function send(res, status, payload) {
43
+ const body = JSON.stringify(payload);
44
+ res.writeHead(status, {
45
+ 'content-type': 'application/json; charset=utf-8',
46
+ 'content-length': Buffer.byteLength(body),
47
+ 'cache-control': 'no-store',
48
+ 'x-content-type-options': 'nosniff',
49
+ });
50
+ res.end(body);
51
+ }
52
+
53
+ function ok(res, data) {
54
+ send(res, 200, { ok: true, data });
55
+ }
56
+
57
+ function fail(res, status, code, message, details) {
58
+ send(res, status, { ok: false, error: { code, message, ...(details === undefined ? {} : { details }) } });
59
+ }
60
+
61
+ function hostOf(req) {
62
+ const header = String(req.headers.host ?? '');
63
+ const host = header.startsWith('[') ? header.slice(0, header.indexOf(']') + 1) : header.split(':')[0];
64
+ return host.toLowerCase();
65
+ }
66
+
67
+ function assertLoopback(req) {
68
+ const host = hostOf(req);
69
+ if (host !== '127.0.0.1' && host !== 'localhost' && host !== '[::1]') {
70
+ throw new ApiError(403, 'forbidden-host', `Host no permitido: ${host || '(vac?o)'}`);
71
+ }
72
+ const origin = req.headers.origin;
73
+ if (typeof origin === 'string' && origin !== '') {
74
+ let parsed;
75
+ try { parsed = new URL(origin); } catch { throw new ApiError(403, 'forbidden-origin', 'Origin inv?lido'); }
76
+ const allowed = ['127.0.0.1', 'localhost', '[::1]'].includes(parsed.hostname)
77
+ && (parsed.protocol === 'http:' || parsed.protocol === 'https:');
78
+ if (!allowed) throw new ApiError(403, 'forbidden-origin', `Origen no permitido: ${origin}`);
79
+ }
80
+ }
81
+
82
+ function assertWrite(req) {
83
+ if (req.headers['x-lifecode-rag'] !== '1') {
84
+ throw new ApiError(403, 'missing-client-header', 'Falta x-lifecode-rag: 1');
85
+ }
86
+ const type = String(req.headers['content-type'] ?? '').toLowerCase();
87
+ if (!type.startsWith('application/json')) {
88
+ throw new ApiError(415, 'unsupported-media-type', 'Se espera application/json');
89
+ }
90
+ }
91
+
92
+ async function readJson(req) {
93
+ const chunks = [];
94
+ let size = 0;
95
+ for await (const chunk of req) {
96
+ size += chunk.length;
97
+ if (size > BODY_LIMIT) throw new ApiError(413, 'body-too-large', `El cuerpo supera ${BODY_LIMIT} bytes`);
98
+ chunks.push(chunk);
99
+ }
100
+ if (size === 0) return {};
101
+ let parsed;
102
+ try { parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch {
103
+ throw new ApiError(400, 'invalid-json', 'El cuerpo no es JSON v?lido');
104
+ }
105
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
106
+ throw new ApiError(400, 'invalid-json', 'El cuerpo debe ser un objeto JSON');
107
+ }
108
+ return parsed;
109
+ }
110
+
111
+ function numberArg(value, { fallback = undefined, min = 0, max = 10_000, label = 'valor' } = {}) {
112
+ if (value === undefined || value === null || value === '') return fallback;
113
+ const number = Number(value);
114
+ if (!Number.isFinite(number) || number < min || number > max) {
115
+ throw new ApiError(400, 'invalid-argument', `${label} fuera de rango [${min}, ${max}]`);
116
+ }
117
+ return number;
118
+ }
119
+
120
+ function textArg(value, { fallback = undefined, max = 4_000, label = 'texto' } = {}) {
121
+ if (value === undefined || value === null) return fallback;
122
+ if (typeof value !== 'string' || value.length > max) {
123
+ throw new ApiError(400, 'invalid-argument', `${label} inv?lido`);
124
+ }
125
+ return value;
126
+ }
127
+
128
+ function arrayArg(value, { fallback = undefined, max = 200, label = 'lista' } = {}) {
129
+ if (value === undefined || value === null) return fallback;
130
+ if (!Array.isArray(value) || value.length > max || value.some((item) => typeof item !== 'string')) {
131
+ throw new ApiError(400, 'invalid-argument', `${label} inv?lido`);
132
+ }
133
+ return value;
134
+ }
135
+
136
+ function auditUi(db, { action, target = '', outcome = 'ok', details = undefined, at = Date.now(), tool = 'lifecode_rag_ui' }) {
137
+ appendAudit(db, { at, actor: 'ui', tool, action, target, outcome, details });
138
+ }
139
+
140
+ function withStore(root, work, { create = false } = {}) {
141
+ const opened = openDatabase({ root, create });
142
+ try { return work(opened.db); } finally { closeDatabase(opened.db); }
143
+ }
144
+
145
+ export function createApiHandler({ root = ragRoot(), env = process.env, now = () => Date.now() } = {}) {
146
+ const paths = storePaths(root);
147
+
148
+ return async function handler(req, res) {
149
+ try {
150
+ assertLoopback(req);
151
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
152
+ if (!url.pathname.startsWith(API_PREFIX)) {
153
+ return fail(res, 404, 'not-found', `Ruta fuera de ${API_PREFIX}`);
154
+ }
155
+ const segments = url.pathname.slice(API_PREFIX.length).split('/').filter(Boolean);
156
+ const method = req.method ?? 'GET';
157
+ const { config } = loadConfig(root);
158
+ const moment = now();
159
+
160
+ // GET -----------------------------------------------------------------------------------
161
+ if (method === 'GET') {
162
+ if (segments.length === 0 || (segments.length === 1 && segments[0] === 'health')) {
163
+ return ok(res, { ok: true, version: VERSION, store: { path: paths.database }, api: API_PREFIX });
164
+ }
165
+ if (segments.length === 1 && segments[0] === 'capabilities') {
166
+ return ok(res, {
167
+ version: VERSION,
168
+ strategies: ['hybrid', 'fts', 'vector'],
169
+ embedding: { providers: ['local-hash-v1', 'remote'], active: config.embedding.provider, dim: config.embedding.dim },
170
+ automation: { supported: true, defaults: config.automation },
171
+ formats: ['md', 'txt', 'html', 'json', 'jsonl', 'csv', 'tsv', 'yaml', 'xml', 'logs', 'code'],
172
+ toolsFrozen: ['lifecode_rag_ingest', 'lifecode_rag_search', 'lifecode_rag_context', 'lifecode_rag_get', 'lifecode_rag_list', 'lifecode_rag_forget', 'lifecode_rag_reindex'],
173
+ });
174
+ }
175
+ if (segments.length === 1 && segments[0] === 'snapshot') {
176
+ return ok(res, buildSnapshot({ root, now: moment }));
177
+ }
178
+ if (segments.length === 1 && segments[0] === 'config') {
179
+ return ok(res, { config });
180
+ }
181
+ if (segments.length === 1 && segments[0] === 'activity') {
182
+ const limit = numberArg(url.searchParams.get('limit'), { fallback: 40, min: 1, max: 200, label: 'limit' });
183
+ const rows = withStore(root, (db) => activityFeed(db, { limit }));
184
+ return ok(res, { rows });
185
+ }
186
+ if (segments.length === 1 && segments[0] === 'sources') {
187
+ const collection = textArg(url.searchParams.get('collection'), { max: 120, label: 'collection' });
188
+ const tag = textArg(url.searchParams.get('tag'), { max: 64, label: 'tag' });
189
+ const limit = numberArg(url.searchParams.get('limit'), { fallback: 50, min: 1, max: 200, label: 'limit' });
190
+ const offset = numberArg(url.searchParams.get('offset'), { fallback: 0, min: 0, max: 100_000, label: 'offset' });
191
+ const page = withStore(root, (db) => listSourceRows(db, { collection: collection || null, tag: tag || null, limit, offset }));
192
+ return ok(res, page);
193
+ }
194
+ if (segments.length === 2 && segments[0] === 'sources') {
195
+ const source = withStore(root, (db) => getSource(db, segments[1]));
196
+ const chunks = withStore(root, (db) => db.prepare('SELECT ordinal, heading, text, char_start, char_end FROM chunks WHERE source_id = ? ORDER BY ordinal ASC').all(source.id));
197
+ return ok(res, { source, chunks });
198
+ }
199
+ if (segments.length === 4 && segments[0] === 'sources' && segments[2] === 'chunks') {
200
+ const chunk = withStore(root, (db) => {
201
+ const row = db.prepare('SELECT chunk_key, ordinal, heading, text, char_start, char_end FROM chunks WHERE source_id = ? AND ordinal = ?')
202
+ .get(segments[1], Number(segments[3]));
203
+ if (!row) throw new RagError('source-not-found', `sin chunk ${segments[3]} en ${segments[1]}`);
204
+ return row;
205
+ });
206
+ return ok(res, chunk);
207
+ }
208
+ if (segments.length === 2 && segments[0] === 'metrics' && segments[1] === 'summary') {
209
+ const days = numberArg(url.searchParams.get('days'), { fallback: 7, min: 1, max: 365, label: 'days' });
210
+ return ok(res, withStore(root, (db) => metricsSummary(db, { days, now: moment })));
211
+ }
212
+ if (segments.length === 2 && segments[0] === 'metrics' && segments[1] === 'series') {
213
+ const metric = textArg(url.searchParams.get('metric'), { max: 64, label: 'metric' });
214
+ if (!metric) throw new ApiError(400, 'invalid-argument', 'metric es obligatorio');
215
+ const days = numberArg(url.searchParams.get('days'), { fallback: 30, min: 1, max: 365, label: 'days' });
216
+ const dim = textArg(url.searchParams.get('dim'), { max: 64, label: 'dim' });
217
+ return ok(res, withStore(root, (db) => metricSeries(db, { metric, days, dim: dim || undefined, now: moment })));
218
+ }
219
+ return fail(res, 404, 'not-found', `Ruta desconocida: ${url.pathname}`);
220
+ }
221
+
222
+ // POST ----------------------------------------------------------------------------------
223
+ if (method !== 'POST') return fail(res, 405, 'method-not-allowed', `M?todo no permitido: ${method}`);
224
+ assertWrite(req);
225
+ const body = await readJson(req);
226
+ const action = url.pathname.slice(API_PREFIX.length);
227
+
228
+ if (action === '/search' || action === '/retrieval') {
229
+ const query = textArg(body.query, { max: 2_000, label: 'query' });
230
+ if (typeof query !== 'string' || query.trim() === '') throw new ApiError(400, 'invalid-argument', 'query es obligatorio');
231
+ const limit = numberArg(body.limit, { fallback: config.search.limit, min: 1, max: config.search.maxLimit, label: 'limit' });
232
+ const tags = arrayArg(body.tags, { max: 20, label: 'tags' });
233
+ const tagMode = body.tagMode === 'all' ? 'all' : 'any';
234
+ const strategy = ['hybrid', 'fts', 'vector'].includes(body.strategy) ? body.strategy : config.search.strategy;
235
+ const collection = textArg(body.collection, { max: 120, label: 'collection' });
236
+ const embedder = createEmbedder(config);
237
+ const found = await withStoreAsync(root, (db) => search(db, {
238
+ query, limit, collection: collection || null, tags, tagMode, strategy, config, embedder, now: moment,
239
+ }));
240
+ return ok(res, { ...found, results: found.results.map((row) => ({ ...row, text: String(row.text ?? '').slice(0, 4_000) })) });
241
+ }
242
+
243
+ if (action === '/context') {
244
+ const query = textArg(body.query, { max: 2_000, label: 'query' });
245
+ if (typeof query !== 'string' || query.trim() === '') throw new ApiError(400, 'invalid-argument', 'query es obligatorio');
246
+ const budgetTokens = numberArg(body.budgetTokens, { fallback: config.context.budgetTokens, min: 16, max: 32_000, label: 'budgetTokens' });
247
+ const maxChunks = numberArg(body.maxChunks, { fallback: config.context.maxChunks, min: 1, max: 40, label: 'maxChunks' });
248
+ const embedder = createEmbedder(config);
249
+ const built = await withStoreAsync(root, async (db) => {
250
+ const found = await search(db, { query, limit: Math.max(maxChunks, 8), strategy: config.search.strategy, config, embedder, record: false, now: moment });
251
+ return assembleContextAsync({ results: found.results, config, budgetTokens, maxChunks, embedder });
252
+ });
253
+ return ok(res, built);
254
+ }
255
+
256
+ if (action === '/actions') {
257
+ const name = textArg(body.action, { max: 40, label: 'action' });
258
+ const payload = body.payload && typeof body.payload === 'object' ? body.payload : {};
259
+ const confirm = body.confirm === true;
260
+
261
+ if (name === 'ingest') {
262
+ const requested = Array.isArray(payload.paths) ? payload.paths.map(String) : [String(payload.path ?? '')];
263
+ if (requested.filter((item) => item.trim() !== '').length === 0) throw new ApiError(400, 'invalid-argument', 'paths es obligatorio');
264
+ const cwd = textArg(payload.cwd, { max: 1_000, label: 'cwd' }) ?? process.cwd();
265
+ const limit = config.maxFilesPerIngest;
266
+ const classified = expandInputs(requested, { cwd, roots: config.roots.extra, ragRootPath: paths.root, limit });
267
+ const outside = classified.filter((item) => item.outsideRoots.length > 0);
268
+ if (outside.length > 0) {
269
+ throw new ApiError(409, 'path-not-allowed', 'Las rutas fuera del proyecto exigen aprobaci?n humana desde la herramienta; el panel no puede aprobarlas');
270
+ }
271
+ const embedder = createEmbedder(config);
272
+ const result = await ingestFiles({
273
+ root, files: classified.map((item) => item.realPath), collection: payload.collection ?? 'default',
274
+ tags: arrayArg(payload.tags, { max: 20, label: 'tags' }) ?? [], force: payload.force === true, config, embedder, now: moment, actor: 'ui',
275
+ });
276
+ return ok(res, result);
277
+ }
278
+
279
+ if (name === 'forget') {
280
+ if (!confirm) throw new ApiError(409, 'confirmation-required', 'forget exige confirm: true con el alcance exacto');
281
+ const ref = textArg(payload.ref, { max: 1_000, label: 'ref' });
282
+ if (!ref) throw new ApiError(400, 'invalid-argument', 'ref es obligatorio');
283
+ const result = withStore(root, (db) => forgetSource(db, { ref, now: moment, actor: 'ui', sessionId: null, callId: null }));
284
+ return ok(res, result);
285
+ }
286
+
287
+ if (name === 'reindex') {
288
+ if (!confirm) throw new ApiError(409, 'confirmation-required', 'reindex exige confirm: true');
289
+ const operation = ['fts', 'vectors', 'all'].includes(payload.operation) ? payload.operation : null;
290
+ if (!operation) throw new ApiError(400, 'invalid-argument', "operation debe ser 'fts', 'vectors' o 'all'");
291
+ const result = await withStoreAsync(root, (db) => reindex(db, { operation, config, now: moment, actor: 'ui', signal: undefined }));
292
+ return ok(res, result);
293
+ }
294
+
295
+ if (name === 'purge') {
296
+ if (!confirm) throw new ApiError(409, 'confirmation-required', 'purge exige confirm: true');
297
+ const before = textArg(payload.beforeDay, { max: 10, label: 'beforeDay' });
298
+ const result = withStore(root, (db) => {
299
+ const beforeDay = before || retentionCutoff(config, moment);
300
+ const removed = purgeMetrics(db, { beforeDay, at: moment });
301
+ auditUi(db, { action: 'metrics.purge', target: beforeDay, details: { removed }, at: moment });
302
+ return { removed, beforeDay };
303
+ });
304
+ return ok(res, result);
305
+ }
306
+
307
+ if (name === 'config') {
308
+ const patch = body.patch;
309
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) throw new ApiError(400, 'invalid-argument', 'patch es obligatorio');
310
+ const merged = { ...config, ...patch };
311
+ const written = writeConfig(root, merged, { now: moment });
312
+ withStore(root, (db) => auditUi(db, { action: 'config.update', target: paths.config, details: { keys: Object.keys(patch) }, at: moment }));
313
+ return ok(res, { config: written.config, path: written.path });
314
+ }
315
+
316
+ return fail(res, 404, 'not-found', `Acci?n desconocida: ${name}`);
317
+ }
318
+
319
+ return fail(res, 404, 'not-found', `Ruta desconocida: ${url.pathname}`);
320
+ } catch (error) {
321
+ if (error instanceof ApiError) return fail(res, error.status, error.code, error.message, error.details);
322
+ if (error instanceof RagError) {
323
+ return fail(res, httpStatusFor(error.code, { legacy: true }), error.code, error.message, error.details);
324
+ }
325
+ return fail(res, 500, 'internal', error?.message ?? 'fallo interno');
326
+ }
327
+ };
328
+ }
329
+
330
+ /** Abre la base, ejecuta trabajo as?ncrono y cierra siempre. */
331
+ async function withStoreAsync(root, work) {
332
+ const opened = openDatabase({ root, create: false });
333
+ try { return await work(opened.db); } finally { closeDatabase(opened.db); }
334
+ }
335
+
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Adaptador de identidad de sesión (PA2.1).
3
+ *
4
+ * El host expone `Agent = { id: SessionId }` (ver `@deepseek-ai/dsh-agent`). Este módulo no
5
+ * inventa propiedades: toma `agent.id` como identidad estable, la valida y la ata al perfil
6
+ * activo en el momento de capturarla. El nombre visible de la conversación no se usa nunca.
7
+ *
8
+ * Si algún día el host cambia la forma de `Agent`, este es el único punto que hay que tocar.
9
+ */
10
+
11
+ import { RagError } from './errors.mjs';
12
+ import { profileKey } from './profile.mjs';
13
+
14
+ /** Un `SessionId` del host es opaco, pero el registro lo guarda como TEXT imprimible de 1..200. */
15
+ export const SESSION_ID_PATTERN = /^[\x20-\x7e]{1,200}$/;
16
+
17
+ export function assertSessionId(sessionId) {
18
+ if (typeof sessionId !== 'string' || !SESSION_ID_PATTERN.test(sessionId)) {
19
+ throw new RagError('session-invalid', 'la identidad de sesión no es válida', {
20
+ details: { reason: typeof sessionId === 'string' ? 'format' : 'missing' },
21
+ });
22
+ }
23
+ return sessionId;
24
+ }
25
+
26
+ /**
27
+ * Captura la identidad estable desde el `Agent` del host. Devuelve también la clave del perfil,
28
+ * para que el registro pueda rechazar una identidad capturada en otro perfil.
29
+ */
30
+ export function captureSession(agent, { env = process.env, now = Date.now() } = {}) {
31
+ if (!agent || typeof agent !== 'object') {
32
+ throw new RagError('session-invalid', 'no hay identidad de sesión en la ejecución', {
33
+ details: { reason: 'missing-agent' },
34
+ });
35
+ }
36
+ const sessionId = assertSessionId(agent.id);
37
+ return { sessionId, profileKey: profileKey(env), capturedAt: now };
38
+ }
39
+
40
+ /** Verifica que una identidad capturada pertenece al perfil del registro abierto. */
41
+ export function assertProfile(identity, expectedProfileKey) {
42
+ if (!identity || typeof identity !== 'object') {
43
+ throw new RagError('session-invalid', 'falta la identidad de sesión', { details: { reason: 'missing-identity' } });
44
+ }
45
+ if (identity.profileKey !== expectedProfileKey) {
46
+ throw new RagError('session-invalid', 'la sesión pertenece a otro perfil', {
47
+ details: { reason: 'profile-mismatch' },
48
+ });
49
+ }
50
+ return identity.sessionId;
51
+ }