@knolo/cli 6.2.9 → 6.2.10
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/README.md +11 -4
- package/bin/compose.mjs +44 -40
- package/bin/core-load-hook.mjs +33 -0
- package/bin/flight.mjs +10 -14
- package/bin/knolo.mjs +42 -16
- package/bin/load-core.mjs +76 -0
- package/bin/persona.mjs +981 -0
- package/bin/research.mjs +7 -12
- package/bin/skill.mjs +15 -27
- package/package.json +2 -2
package/bin/persona.mjs
ADDED
|
@@ -0,0 +1,981 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knolo persona init | build | verify | eval
|
|
3
|
+
*
|
|
4
|
+
* A persona pack is a V5 Knowledge Image. Knolo core does not call a model.
|
|
5
|
+
* The host owns the model. A receipt is an integrity check.
|
|
6
|
+
* A KITE verdict describes the contract. It does not mean a claim is true.
|
|
7
|
+
*/
|
|
8
|
+
import crypto from 'node:crypto';
|
|
9
|
+
import { lstat, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
12
|
+
import { loadCoreModule } from './load-core.mjs';
|
|
13
|
+
|
|
14
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
15
|
+
|
|
16
|
+
const NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
17
|
+
const EXTENSIONS = new Set(['.md', '.txt', '.json']);
|
|
18
|
+
const SKIP_FILES = new Set(['consent.json', 'fixtures.json', 'creator-private.pem']);
|
|
19
|
+
const MAX_FILE_BYTES = 1024 * 1024;
|
|
20
|
+
const MAX_IMAGE_BYTES = 32 * 1024 * 1024;
|
|
21
|
+
const ACTOR = 'knolo-persona';
|
|
22
|
+
const ALLOWED_USE = "A chatbot that speaks in this creator's voice.";
|
|
23
|
+
const DISCLOSURE = 'This chatbot is AI and is not the creator.';
|
|
24
|
+
const BOUNDARY_LINES = [
|
|
25
|
+
'Do not discuss banned topics.',
|
|
26
|
+
'Do not claim to be the human creator.',
|
|
27
|
+
'Do not invent prices, availability, or offers.',
|
|
28
|
+
];
|
|
29
|
+
const CONTRACT = {
|
|
30
|
+
format: 'knolo-kite-contract-1',
|
|
31
|
+
question: 'Does this pack state its disclosure and hard boundaries?',
|
|
32
|
+
obligations: [
|
|
33
|
+
{ id: 'disclosure', kind: 'evidence', term: 'chatbot' },
|
|
34
|
+
{ id: 'identity', kind: 'qualification', term: 'human creator' },
|
|
35
|
+
{ id: 'prices', kind: 'authority', term: 'invent prices' },
|
|
36
|
+
{ id: 'topics', kind: 'qualification', term: 'banned topics' },
|
|
37
|
+
],
|
|
38
|
+
};
|
|
39
|
+
const RULES = {
|
|
40
|
+
format: 'knolo-kite-rules-1',
|
|
41
|
+
proposition: 'The pack states its disclosure and hard boundaries.',
|
|
42
|
+
support: [],
|
|
43
|
+
oppose: [],
|
|
44
|
+
require: ['disclosure', 'identity', 'prices', 'topics'],
|
|
45
|
+
conflicts: [],
|
|
46
|
+
completeness: [],
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const USAGE = `Usage: knolo persona <init|build|verify|eval> [options]
|
|
50
|
+
|
|
51
|
+
knolo persona init <name> [--dir <parent>]
|
|
52
|
+
knolo persona build <dir> [--out <file>] [--json]
|
|
53
|
+
knolo persona verify <image> [--withdrawn <id>] [--json]
|
|
54
|
+
knolo persona eval <image> --fixtures <file> [--json]
|
|
55
|
+
|
|
56
|
+
Builds a persona pack on the current V5 image.
|
|
57
|
+
Knolo core does not call a model. The host owns the model.
|
|
58
|
+
A receipt is an integrity check. It does not mean a claim is proven.
|
|
59
|
+
SATISFIED means the evidence requirements were met.
|
|
60
|
+
A KITE verdict describes the contract. It does not mean the claim is true.
|
|
61
|
+
verify fails when a withdrawn source id is still in the image.
|
|
62
|
+
An opt-out rebuild drops that file and produces a new pin.`;
|
|
63
|
+
|
|
64
|
+
const RECEIPT_NOTE =
|
|
65
|
+
'A receipt is an integrity check. It does not mean a claim is proven.';
|
|
66
|
+
|
|
67
|
+
export async function runPersonaCli(argv) {
|
|
68
|
+
const { positionals, flags } = parseArgs(argv);
|
|
69
|
+
const sub = positionals[0] ?? '';
|
|
70
|
+
if (!sub || sub === 'help' || flags.help) {
|
|
71
|
+
console.log(USAGE);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (sub === 'init') return initPersona(positionals[1], flags);
|
|
75
|
+
if (sub === 'build') return buildCommand(positionals[1], flags);
|
|
76
|
+
if (sub === 'verify') return verifyCommand(positionals[1], flags);
|
|
77
|
+
if (sub === 'eval') return evalCommand(positionals[1], flags);
|
|
78
|
+
throw new Error(`Unknown persona command "${sub}".\n${USAGE}`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Mounts a local persona image, checks exemplars and KITE boundaries, then
|
|
83
|
+
* calls the host chat endpoint only when those checks pass.
|
|
84
|
+
* --evidence prints excerpts and does not call a model.
|
|
85
|
+
*/
|
|
86
|
+
export async function answerPersona(
|
|
87
|
+
argv,
|
|
88
|
+
{
|
|
89
|
+
env = process.env,
|
|
90
|
+
fetchImpl = globalThis.fetch,
|
|
91
|
+
print = console.log,
|
|
92
|
+
printError = console.error,
|
|
93
|
+
} = {}
|
|
94
|
+
) {
|
|
95
|
+
const flags = parseChatArgs(argv);
|
|
96
|
+
if (flags.help) {
|
|
97
|
+
print(chatUsage());
|
|
98
|
+
return { exitCode: 0, modelCalled: false };
|
|
99
|
+
}
|
|
100
|
+
let inspected;
|
|
101
|
+
try {
|
|
102
|
+
const bytes = await readUserFile(flags.image, MAX_IMAGE_BYTES);
|
|
103
|
+
inspected = await inspectPersona(bytes, {
|
|
104
|
+
withdrawn: [],
|
|
105
|
+
failWithdrawn: true,
|
|
106
|
+
failUnmet: true,
|
|
107
|
+
});
|
|
108
|
+
} catch (error) {
|
|
109
|
+
printError(error instanceof Error ? error.message : String(error));
|
|
110
|
+
return { exitCode: 1, modelCalled: false };
|
|
111
|
+
}
|
|
112
|
+
const prompt = flags.prompt ?? '';
|
|
113
|
+
const banned = inspected.bannedTopics.find((topic) =>
|
|
114
|
+
mentionsTopic(prompt, topic)
|
|
115
|
+
);
|
|
116
|
+
if (banned) {
|
|
117
|
+
printError(`blocked banned topic: ${banned}`);
|
|
118
|
+
return { exitCode: 1, modelCalled: false };
|
|
119
|
+
}
|
|
120
|
+
let exemplars;
|
|
121
|
+
try {
|
|
122
|
+
exemplars = retrieveExemplars(inspected, flags.situation, prompt).map(checkedExcerpt);
|
|
123
|
+
} catch (error) {
|
|
124
|
+
printError(error instanceof Error ? error.message : String(error));
|
|
125
|
+
return { exitCode: 1, modelCalled: false };
|
|
126
|
+
}
|
|
127
|
+
if (exemplars.length === 0) {
|
|
128
|
+
printError('missing evidence');
|
|
129
|
+
return { exitCode: 1, modelCalled: false };
|
|
130
|
+
}
|
|
131
|
+
if (flags.evidence) {
|
|
132
|
+
printEvidence(inspected, exemplars, print);
|
|
133
|
+
return { exitCode: 0, modelCalled: false, exemplars };
|
|
134
|
+
}
|
|
135
|
+
const model = flags.model || env.KNOLO_MODEL;
|
|
136
|
+
if (!model) {
|
|
137
|
+
printError(
|
|
138
|
+
'Set --model or KNOLO_MODEL. Use --evidence to print excerpts without a model.'
|
|
139
|
+
);
|
|
140
|
+
return { exitCode: 1, modelCalled: false };
|
|
141
|
+
}
|
|
142
|
+
const base = (flags.baseUrl || env.KNOLO_MODEL_BASE_URL || 'http://127.0.0.1:11434/v1').replace(
|
|
143
|
+
/\/$/u,
|
|
144
|
+
''
|
|
145
|
+
);
|
|
146
|
+
const headers = { 'content-type': 'application/json' };
|
|
147
|
+
const apiKey =
|
|
148
|
+
typeof env.KNOLO_MODEL_API_KEY === 'string' ? env.KNOLO_MODEL_API_KEY.trim() : '';
|
|
149
|
+
if (apiKey) headers.authorization = `Bearer ${apiKey}`;
|
|
150
|
+
let modelResponse;
|
|
151
|
+
try {
|
|
152
|
+
modelResponse = await fetchImpl(`${base}/chat/completions`, {
|
|
153
|
+
method: 'POST',
|
|
154
|
+
headers,
|
|
155
|
+
body: JSON.stringify({
|
|
156
|
+
model,
|
|
157
|
+
messages: [
|
|
158
|
+
{ role: 'system', content: systemPrompt(inspected) },
|
|
159
|
+
{ role: 'user', content: userPrompt(prompt, inspected, exemplars) },
|
|
160
|
+
],
|
|
161
|
+
}),
|
|
162
|
+
});
|
|
163
|
+
} catch {
|
|
164
|
+
printError('Model endpoint is unavailable.');
|
|
165
|
+
return { exitCode: 2, modelCalled: true };
|
|
166
|
+
}
|
|
167
|
+
const answer = await readModelAnswer(modelResponse);
|
|
168
|
+
if (!answer) {
|
|
169
|
+
printError('Model endpoint returned no reply.');
|
|
170
|
+
return { exitCode: 2, modelCalled: true };
|
|
171
|
+
}
|
|
172
|
+
if (!answer.includes(inspected.disclosure)) {
|
|
173
|
+
printError('refusing reply that omits the disclosure line');
|
|
174
|
+
return { exitCode: 1, modelCalled: true };
|
|
175
|
+
}
|
|
176
|
+
const leaked = inspected.bannedTopics.find((topic) => mentionsTopic(answer, topic));
|
|
177
|
+
if (leaked) {
|
|
178
|
+
printError(`refusing reply that discusses banned topic: ${leaked}`);
|
|
179
|
+
return { exitCode: 1, modelCalled: true };
|
|
180
|
+
}
|
|
181
|
+
print(answer);
|
|
182
|
+
print('');
|
|
183
|
+
print('Citations:');
|
|
184
|
+
for (const excerpt of exemplars) print(`${excerpt.source} ${excerpt.digest}`);
|
|
185
|
+
print(RECEIPT_NOTE);
|
|
186
|
+
return { exitCode: 0, modelCalled: true, exemplars };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function chatUsage() {
|
|
190
|
+
return `Usage: node examples/persona-chat/chat.mjs <image> --situation <id> --prompt <text> [--evidence] [--model <name>] [--base-url <url>]
|
|
191
|
+
|
|
192
|
+
The host owns the model. Knolo core does not call a model.
|
|
193
|
+
--evidence prints excerpts and does not call a model.
|
|
194
|
+
A missing exemplar or an unmet obligation does not call a model.
|
|
195
|
+
A reply that omits the disclosure line is refused.`;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async function initPersona(name, flags) {
|
|
199
|
+
if (typeof name !== 'string' || !NAME.test(name)) {
|
|
200
|
+
throw new Error(
|
|
201
|
+
'PERSONA_NAME: use lowercase letters, digits, and single hyphens.'
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
const parent = path.resolve(process.cwd(), flags.dir ?? '.');
|
|
205
|
+
const dir = path.join(parent, name);
|
|
206
|
+
try {
|
|
207
|
+
await lstat(dir);
|
|
208
|
+
throw new Error('persona directory already exists.');
|
|
209
|
+
} catch (error) {
|
|
210
|
+
if (error && error.code !== 'ENOENT') throw error;
|
|
211
|
+
}
|
|
212
|
+
const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');
|
|
213
|
+
const privatePem = privateKey.export({ type: 'pkcs8', format: 'pem' });
|
|
214
|
+
const publicPem = publicKey.export({ type: 'spki', format: 'pem' });
|
|
215
|
+
await mkdir(path.join(dir, 'exemplars'), { recursive: true });
|
|
216
|
+
const profile = {
|
|
217
|
+
name,
|
|
218
|
+
tone: 'warm and direct',
|
|
219
|
+
typicalLength: 'two short sentences',
|
|
220
|
+
emoji: 'rare',
|
|
221
|
+
preferredSlang: [],
|
|
222
|
+
avoidedSlang: [],
|
|
223
|
+
catchphrases: ['glad you asked'],
|
|
224
|
+
formality: 'casual',
|
|
225
|
+
languages: ['en'],
|
|
226
|
+
};
|
|
227
|
+
const boundaries = {
|
|
228
|
+
bannedTopics: ['payroll'],
|
|
229
|
+
lines: BOUNDARY_LINES,
|
|
230
|
+
};
|
|
231
|
+
const consent = {
|
|
232
|
+
format: 'knolo-persona-consent-1',
|
|
233
|
+
allowedUse: ALLOWED_USE,
|
|
234
|
+
training: false,
|
|
235
|
+
publicKey: publicPem,
|
|
236
|
+
withdrawn: [],
|
|
237
|
+
sources: [
|
|
238
|
+
{ id: 'boundaries.json', owner: 'creator', role: 'boundaries' },
|
|
239
|
+
{ id: 'disclosure.txt', owner: 'creator', role: 'disclosure' },
|
|
240
|
+
{
|
|
241
|
+
id: 'exemplars/faq.md',
|
|
242
|
+
owner: 'creator',
|
|
243
|
+
role: 'exemplar',
|
|
244
|
+
situation: 'faq',
|
|
245
|
+
},
|
|
246
|
+
{
|
|
247
|
+
id: 'exemplars/greeting.md',
|
|
248
|
+
owner: 'creator',
|
|
249
|
+
role: 'exemplar',
|
|
250
|
+
situation: 'greeting',
|
|
251
|
+
},
|
|
252
|
+
{ id: 'persona.json', owner: 'creator', role: 'profile' },
|
|
253
|
+
],
|
|
254
|
+
};
|
|
255
|
+
const fixtures = {
|
|
256
|
+
cases: [
|
|
257
|
+
{
|
|
258
|
+
situation: 'greeting',
|
|
259
|
+
creator: 'Hey, glad you asked.',
|
|
260
|
+
bot: `Hey, glad you asked. ${DISCLOSURE}`,
|
|
261
|
+
},
|
|
262
|
+
{
|
|
263
|
+
situation: 'faq',
|
|
264
|
+
creator: 'Glad you asked. The short answer stays on the pinned page.',
|
|
265
|
+
bot: `Glad you asked. The short answer stays on the pinned page. ${DISCLOSURE}`,
|
|
266
|
+
},
|
|
267
|
+
],
|
|
268
|
+
};
|
|
269
|
+
await writeFile(path.join(dir, 'persona.json'), pretty(profile), { mode: 0o644 });
|
|
270
|
+
await writeFile(path.join(dir, 'disclosure.txt'), `${DISCLOSURE}\n`, { mode: 0o644 });
|
|
271
|
+
await writeFile(path.join(dir, 'boundaries.json'), pretty(boundaries), { mode: 0o644 });
|
|
272
|
+
await writeFile(
|
|
273
|
+
path.join(dir, 'exemplars', 'greeting.md'),
|
|
274
|
+
'Situation: greeting\n\nHey, glad you asked.\n',
|
|
275
|
+
{ mode: 0o644 }
|
|
276
|
+
);
|
|
277
|
+
await writeFile(
|
|
278
|
+
path.join(dir, 'exemplars', 'faq.md'),
|
|
279
|
+
'Situation: faq\n\nGlad you asked. The short answer stays on the pinned page.\n',
|
|
280
|
+
{ mode: 0o644 }
|
|
281
|
+
);
|
|
282
|
+
await writeFile(path.join(dir, 'consent.json'), pretty(consent), { mode: 0o644 });
|
|
283
|
+
await writeFile(path.join(dir, 'fixtures.json'), pretty(fixtures), { mode: 0o644 });
|
|
284
|
+
await writeFile(path.join(dir, 'creator-private.pem'), privatePem, { mode: 0o600 });
|
|
285
|
+
if (flags.json) console.log(JSON.stringify({ ok: true, name }));
|
|
286
|
+
else console.log(`wrote ${name}`);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
async function buildCommand(dirArg, flags) {
|
|
290
|
+
const dir = resolveDir(dirArg);
|
|
291
|
+
const built = await buildPersonaPack(dir);
|
|
292
|
+
const name = built.profile.name;
|
|
293
|
+
const out = flags.out
|
|
294
|
+
? path.resolve(process.cwd(), flags.out)
|
|
295
|
+
: path.join(dir, 'dist', `${name}.knolo`);
|
|
296
|
+
await mkdir(path.dirname(out), { recursive: true });
|
|
297
|
+
await writeFile(out, built.bytes);
|
|
298
|
+
const body = {
|
|
299
|
+
ok: true,
|
|
300
|
+
name,
|
|
301
|
+
stateRoot: built.stateRoot,
|
|
302
|
+
sha256: sha256(built.bytes),
|
|
303
|
+
out: flags.out ?? path.join('dist', `${name}.knolo`),
|
|
304
|
+
note: RECEIPT_NOTE,
|
|
305
|
+
};
|
|
306
|
+
if (flags.json) console.log(JSON.stringify(body));
|
|
307
|
+
else {
|
|
308
|
+
console.log(`stateRoot ${built.stateRoot}`);
|
|
309
|
+
console.log(`wrote ${body.out}`);
|
|
310
|
+
console.log(RECEIPT_NOTE);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
async function verifyCommand(imageArg, flags) {
|
|
315
|
+
const bytes = await readUserFile(imageArg, MAX_IMAGE_BYTES);
|
|
316
|
+
const inspected = await inspectPersona(bytes, {
|
|
317
|
+
withdrawn: flags.withdrawn,
|
|
318
|
+
failWithdrawn: true,
|
|
319
|
+
failUnmet: true,
|
|
320
|
+
});
|
|
321
|
+
const body = {
|
|
322
|
+
ok: true,
|
|
323
|
+
stateRoot: inspected.image.stateRoot,
|
|
324
|
+
verdict: inspected.kite.verdict,
|
|
325
|
+
unmet: inspected.kite.unmet.map((item) => item.id),
|
|
326
|
+
note: RECEIPT_NOTE,
|
|
327
|
+
};
|
|
328
|
+
if (flags.json) console.log(JSON.stringify(body));
|
|
329
|
+
else {
|
|
330
|
+
console.log(`ok ${body.stateRoot}`);
|
|
331
|
+
console.log(`verdict ${body.verdict}`);
|
|
332
|
+
console.log(RECEIPT_NOTE);
|
|
333
|
+
console.log(
|
|
334
|
+
'A KITE verdict describes the contract. It does not mean the claim is true.'
|
|
335
|
+
);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
async function evalCommand(imageArg, flags) {
|
|
340
|
+
if (!flags.fixtures) throw new Error(`Missing --fixtures.\n${USAGE}`);
|
|
341
|
+
const bytes = await readUserFile(imageArg, MAX_IMAGE_BYTES);
|
|
342
|
+
const inspected = await inspectPersona(bytes, {
|
|
343
|
+
withdrawn: [],
|
|
344
|
+
failWithdrawn: true,
|
|
345
|
+
failUnmet: true,
|
|
346
|
+
});
|
|
347
|
+
const fixtures = JSON.parse(
|
|
348
|
+
(await readUserFile(flags.fixtures, MAX_FILE_BYTES)).toString('utf8')
|
|
349
|
+
);
|
|
350
|
+
const result = scoreFixtures(inspected, fixtures);
|
|
351
|
+
const body = {
|
|
352
|
+
ok: true,
|
|
353
|
+
score: result.score,
|
|
354
|
+
stateRoot: inspected.image.stateRoot,
|
|
355
|
+
receiptId: result.receiptId,
|
|
356
|
+
excerpts: result.excerpts,
|
|
357
|
+
note: RECEIPT_NOTE,
|
|
358
|
+
};
|
|
359
|
+
if (flags.json) console.log(JSON.stringify(body));
|
|
360
|
+
else {
|
|
361
|
+
console.log(`score ${result.score.toFixed(4)}`);
|
|
362
|
+
console.log(`stateRoot ${body.stateRoot}`);
|
|
363
|
+
console.log(`receipt ${body.receiptId}`);
|
|
364
|
+
console.log(`excerpts ${body.excerpts.join(' ')}`);
|
|
365
|
+
console.log(RECEIPT_NOTE);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export async function buildPersonaPack(dir, { checkObligations = true } = {}) {
|
|
370
|
+
const files = await listPackFiles(dir);
|
|
371
|
+
const consentFile = JSON.parse(
|
|
372
|
+
(await readUserFile(path.join(dir, 'consent.json'), MAX_FILE_BYTES)).toString('utf8')
|
|
373
|
+
);
|
|
374
|
+
const profile = JSON.parse(
|
|
375
|
+
(await readFile(path.join(dir, 'persona.json'))).toString('utf8')
|
|
376
|
+
);
|
|
377
|
+
if (!profile || typeof profile.name !== 'string' || !NAME.test(profile.name)) {
|
|
378
|
+
throw new Error(
|
|
379
|
+
'PERSONA_NAME: use lowercase letters, digits, and single hyphens.'
|
|
380
|
+
);
|
|
381
|
+
}
|
|
382
|
+
validateConsent(consentFile, files);
|
|
383
|
+
const signed = await signConsent(dir, consentFile);
|
|
384
|
+
const byId = new Map(signed.sources.map((source) => [source.id, source]));
|
|
385
|
+
const objects = [];
|
|
386
|
+
for (const file of files) {
|
|
387
|
+
const entry = byId.get(file.source);
|
|
388
|
+
const bytes = await readFile(file.full);
|
|
389
|
+
const meta = {
|
|
390
|
+
namespace: profile.name,
|
|
391
|
+
persona: profile.name,
|
|
392
|
+
source: file.source,
|
|
393
|
+
role: entry.role,
|
|
394
|
+
};
|
|
395
|
+
if (typeof entry.situation === 'string' && entry.situation) {
|
|
396
|
+
meta.situation = entry.situation;
|
|
397
|
+
}
|
|
398
|
+
objects.push({ kind: 'chunk', bytes, meta });
|
|
399
|
+
}
|
|
400
|
+
// KITE searches chunk text. Contract, rules, and consent stay metadata so
|
|
401
|
+
// their own terms cannot satisfy the obligations.
|
|
402
|
+
objects.push(metadataObject(profile.name, 'kite-contract', 'contract', CONTRACT));
|
|
403
|
+
objects.push(metadataObject(profile.name, 'kite-rules', 'rules', RULES));
|
|
404
|
+
objects.push(metadataObject(profile.name, 'consent.json', 'consent', signed));
|
|
405
|
+
const core = await loadCore();
|
|
406
|
+
const image = core.createKnowledgeImageV5({
|
|
407
|
+
actor: ACTOR,
|
|
408
|
+
policy: personaPolicy(profile.name),
|
|
409
|
+
objects,
|
|
410
|
+
});
|
|
411
|
+
if (checkObligations) {
|
|
412
|
+
await inspectPersona(image.bytes, {
|
|
413
|
+
withdrawn: [],
|
|
414
|
+
failWithdrawn: false,
|
|
415
|
+
failUnmet: true,
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
return {
|
|
419
|
+
bytes: Buffer.from(image.bytes),
|
|
420
|
+
stateRoot: image.stateRoot,
|
|
421
|
+
profile,
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
async function inspectPersona(bytes, { withdrawn, failWithdrawn, failUnmet }) {
|
|
426
|
+
const core = await loadCore();
|
|
427
|
+
const kite = await loadKite();
|
|
428
|
+
const image = core.mountKnowledgeImageV5(bytes);
|
|
429
|
+
const consentObject = objectByRole(image, 'consent');
|
|
430
|
+
const contractObject = objectByRole(image, 'contract');
|
|
431
|
+
const rulesObject = objectByRole(image, 'rules');
|
|
432
|
+
const consent = JSON.parse(Buffer.from(consentObject.bytes).toString('utf8'));
|
|
433
|
+
assertSignature(consent);
|
|
434
|
+
const contract = JSON.parse(Buffer.from(contractObject.bytes).toString('utf8'));
|
|
435
|
+
const rules = JSON.parse(Buffer.from(rulesObject.bytes).toString('utf8'));
|
|
436
|
+
const extra = Array.isArray(withdrawn) ? withdrawn : [];
|
|
437
|
+
const withdrawnIds = new Set([...(consent.withdrawn ?? []), ...extra]);
|
|
438
|
+
if (failWithdrawn) {
|
|
439
|
+
for (const object of image.objects) {
|
|
440
|
+
const source = object.meta?.source;
|
|
441
|
+
if (typeof source === 'string' && withdrawnIds.has(source)) {
|
|
442
|
+
throw new Error(`withdrawn source is still present: ${source}`);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
const session = kite.createKiteSession({
|
|
447
|
+
image: image.bytes,
|
|
448
|
+
contract,
|
|
449
|
+
rules,
|
|
450
|
+
});
|
|
451
|
+
const result = await kite.evaluateKiteSession(session);
|
|
452
|
+
if (failUnmet && result.unmet.length > 0) {
|
|
453
|
+
throw new Error(
|
|
454
|
+
`unmet obligations: ${result.unmet.map((item) => item.id).join(', ')}`
|
|
455
|
+
);
|
|
456
|
+
}
|
|
457
|
+
const verified = await kite.verifyKiteCertificate({
|
|
458
|
+
image: image.bytes,
|
|
459
|
+
contract,
|
|
460
|
+
rules,
|
|
461
|
+
certificate: result.certificate,
|
|
462
|
+
});
|
|
463
|
+
if (!verified.ok) throw new Error(`${verified.code}: ${verified.message}`);
|
|
464
|
+
const disclosure = textOfRole(image, 'disclosure').trim();
|
|
465
|
+
const profile = JSON.parse(textOfRole(image, 'profile'));
|
|
466
|
+
const boundaries = JSON.parse(textOfRole(image, 'boundaries'));
|
|
467
|
+
return {
|
|
468
|
+
image,
|
|
469
|
+
query: core.queryKnowledgeImageV5,
|
|
470
|
+
disclosure,
|
|
471
|
+
profile,
|
|
472
|
+
bannedTopics: Array.isArray(boundaries.bannedTopics) ? boundaries.bannedTopics : [],
|
|
473
|
+
kite: result,
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
function objectByRole(image, role) {
|
|
478
|
+
const found = image.objects.find(
|
|
479
|
+
(object) => object.meta && object.meta.role === role
|
|
480
|
+
);
|
|
481
|
+
if (!found) throw new Error(`PERSONA_PACK: missing ${role}.`);
|
|
482
|
+
return found;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
function textOfRole(image, role) {
|
|
486
|
+
const found = image.objects.find(
|
|
487
|
+
(object) => object.kind === 'chunk' && object.meta && object.meta.role === role
|
|
488
|
+
);
|
|
489
|
+
if (!found) throw new Error(`PERSONA_PACK: missing ${role}.`);
|
|
490
|
+
return Buffer.from(found.bytes).toString('utf8');
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
function metadataObject(name, source, role, value) {
|
|
494
|
+
return {
|
|
495
|
+
kind: 'metadata',
|
|
496
|
+
bytes: Buffer.from(`${canonical(value)}\n`),
|
|
497
|
+
meta: { namespace: name, persona: name, source, role },
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
function personaPolicy(name) {
|
|
502
|
+
const principal = `persona:${name}`;
|
|
503
|
+
return {
|
|
504
|
+
version: 1,
|
|
505
|
+
default: 'deny',
|
|
506
|
+
rules: [
|
|
507
|
+
{ effect: 'allow', action: 'query', principal, kind: 'chunk' },
|
|
508
|
+
{ effect: 'allow', action: 'read', principal, kind: 'chunk' },
|
|
509
|
+
{ effect: 'allow', action: 'query', principal, kind: 'metadata' },
|
|
510
|
+
{ effect: 'allow', action: 'read', principal, kind: 'metadata' },
|
|
511
|
+
],
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function validateConsent(consent, files) {
|
|
516
|
+
if (!consent || consent.format !== 'knolo-persona-consent-1') {
|
|
517
|
+
throw new Error('PERSONA_PACK: consent format is not knolo-persona-consent-1.');
|
|
518
|
+
}
|
|
519
|
+
if (consent.training !== false) {
|
|
520
|
+
throw new Error('PERSONA_PACK: a persona pack cannot train or fine-tune a model.');
|
|
521
|
+
}
|
|
522
|
+
if (typeof consent.allowedUse !== 'string' || !consent.allowedUse.trim()) {
|
|
523
|
+
throw new Error('PERSONA_PACK: consent needs an allowed use.');
|
|
524
|
+
}
|
|
525
|
+
if (typeof consent.publicKey !== 'string' || !consent.publicKey.includes('PUBLIC KEY')) {
|
|
526
|
+
throw new Error('invalid creator signature');
|
|
527
|
+
}
|
|
528
|
+
if (!Array.isArray(consent.withdrawn) || !Array.isArray(consent.sources)) {
|
|
529
|
+
throw new Error('PERSONA_PACK: consent needs sources and withdrawn.');
|
|
530
|
+
}
|
|
531
|
+
const byId = new Map();
|
|
532
|
+
for (const source of consent.sources) {
|
|
533
|
+
if (!source || typeof source.id !== 'string' || typeof source.role !== 'string') {
|
|
534
|
+
throw new Error('PERSONA_PACK: a consent source needs an id and a role.');
|
|
535
|
+
}
|
|
536
|
+
if (byId.has(source.id)) {
|
|
537
|
+
throw new Error(`PERSONA_PACK: duplicate consent source ${source.id}.`);
|
|
538
|
+
}
|
|
539
|
+
byId.set(source.id, source);
|
|
540
|
+
if (source.owner === 'third-party' || source.role === 'correspondence') {
|
|
541
|
+
if (!validConsentRecord(source.consentRecord)) {
|
|
542
|
+
throw new Error(
|
|
543
|
+
`third-party correspondence without a consent record: ${source.id}`
|
|
544
|
+
);
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
for (const file of files) {
|
|
549
|
+
if (!byId.has(file.source)) throw new Error(`missing consent record: ${file.source}`);
|
|
550
|
+
}
|
|
551
|
+
for (const source of consent.sources) {
|
|
552
|
+
if (!files.some((file) => file.source === source.id)) {
|
|
553
|
+
throw new Error(`PERSONA_PACK: consent lists missing source ${source.id}.`);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
function validConsentRecord(record) {
|
|
559
|
+
return Boolean(
|
|
560
|
+
record &&
|
|
561
|
+
typeof record === 'object' &&
|
|
562
|
+
typeof record.party === 'string' &&
|
|
563
|
+
record.party.trim() &&
|
|
564
|
+
typeof record.allows === 'string' &&
|
|
565
|
+
record.allows.trim()
|
|
566
|
+
);
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
async function signConsent(dir, consent) {
|
|
570
|
+
const keyPath = path.join(dir, 'creator-private.pem');
|
|
571
|
+
let pem;
|
|
572
|
+
try {
|
|
573
|
+
const stat = await lstat(keyPath);
|
|
574
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size === 0) {
|
|
575
|
+
throw new Error('missing creator signature');
|
|
576
|
+
}
|
|
577
|
+
pem = await readFile(keyPath);
|
|
578
|
+
} catch (error) {
|
|
579
|
+
if (error && error.code === 'ENOENT') throw new Error('missing creator signature');
|
|
580
|
+
if (error instanceof Error && error.message === 'missing creator signature') throw error;
|
|
581
|
+
throw error;
|
|
582
|
+
}
|
|
583
|
+
const signed = normalizeConsent(consent);
|
|
584
|
+
const digest = crypto.createHash('sha256').update(canonical(signed)).digest();
|
|
585
|
+
let signature;
|
|
586
|
+
try {
|
|
587
|
+
signature = crypto.sign(null, digest, pem.toString('utf8'));
|
|
588
|
+
} catch {
|
|
589
|
+
throw new Error('invalid creator signature');
|
|
590
|
+
}
|
|
591
|
+
if (!signatureValid(digest, signed.publicKey, signature)) {
|
|
592
|
+
throw new Error('invalid creator signature');
|
|
593
|
+
}
|
|
594
|
+
return { ...signed, signature: signature.toString('base64') };
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
function assertSignature(stored) {
|
|
598
|
+
if (!stored || typeof stored.signature !== 'string') {
|
|
599
|
+
throw new Error('invalid creator signature');
|
|
600
|
+
}
|
|
601
|
+
const signature = Buffer.from(stored.signature, 'base64');
|
|
602
|
+
const body = normalizeConsent(stored);
|
|
603
|
+
const digest = crypto.createHash('sha256').update(canonical(body)).digest();
|
|
604
|
+
if (!signatureValid(digest, body.publicKey, signature)) {
|
|
605
|
+
throw new Error('invalid creator signature');
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
function signatureValid(digest, publicKey, signature) {
|
|
610
|
+
try {
|
|
611
|
+
return crypto.verify(null, digest, publicKey, signature) === true;
|
|
612
|
+
} catch {
|
|
613
|
+
return false;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
function normalizeConsent(consent) {
|
|
618
|
+
const body = JSON.parse(JSON.stringify(consent));
|
|
619
|
+
delete body.signature;
|
|
620
|
+
body.sources = [...body.sources].sort((left, right) => compareText(left.id, right.id));
|
|
621
|
+
body.withdrawn = [...new Set(body.withdrawn)].sort(compareText);
|
|
622
|
+
return body;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
function retrieveExemplars(inspected, situation, prompt) {
|
|
626
|
+
const query = situation || queryWords(prompt);
|
|
627
|
+
if (!query) return [];
|
|
628
|
+
return filterExemplars(
|
|
629
|
+
inspected,
|
|
630
|
+
`FROM chunk SEARCH ${JSON.stringify(query)} LIMIT 20`,
|
|
631
|
+
situation
|
|
632
|
+
);
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
function filterExemplars(inspected, expression, situation) {
|
|
636
|
+
const result = inspected.query(inspected.image, expression);
|
|
637
|
+
const found = new Set(result.hits.map((hit) => hit.objectId));
|
|
638
|
+
return inspected.image.objects.filter(
|
|
639
|
+
(object) =>
|
|
640
|
+
found.has(object.id) &&
|
|
641
|
+
object.kind === 'chunk' &&
|
|
642
|
+
object.meta?.role === 'exemplar' &&
|
|
643
|
+
(!situation || object.meta.situation === situation)
|
|
644
|
+
);
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
function queryWords(prompt) {
|
|
648
|
+
return prompt
|
|
649
|
+
.toLowerCase()
|
|
650
|
+
.split(/[^\p{L}\p{N}]+/u)
|
|
651
|
+
.filter((word) => word.length >= 3)
|
|
652
|
+
.slice(0, 3)
|
|
653
|
+
.join(' ');
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
function checkedExcerpt(object) {
|
|
657
|
+
const bytes = Buffer.from(object.bytes);
|
|
658
|
+
const digest = `sha256-${sha256(bytes)}`;
|
|
659
|
+
const excerpt = bytes.toString('utf8');
|
|
660
|
+
const again = `sha256-${sha256(Buffer.from(excerpt, 'utf8'))}`;
|
|
661
|
+
if (again !== digest) throw new Error('excerpt hash mismatch');
|
|
662
|
+
return {
|
|
663
|
+
id: object.id,
|
|
664
|
+
source: object.meta.source,
|
|
665
|
+
situation: object.meta.situation,
|
|
666
|
+
excerpt,
|
|
667
|
+
digest,
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
function scoreFixtures(inspected, fixtures) {
|
|
672
|
+
if (!fixtures || !Array.isArray(fixtures.cases) || fixtures.cases.length === 0) {
|
|
673
|
+
throw new Error('PERSONA_EVAL: fixtures need cases.');
|
|
674
|
+
}
|
|
675
|
+
const catchphrases = Array.isArray(inspected.profile.catchphrases)
|
|
676
|
+
? inspected.profile.catchphrases
|
|
677
|
+
: [];
|
|
678
|
+
const scores = fixtures.cases.map((item) => {
|
|
679
|
+
if (typeof item.creator !== 'string' || typeof item.bot !== 'string') {
|
|
680
|
+
throw new Error('PERSONA_EVAL: each case needs creator and bot text.');
|
|
681
|
+
}
|
|
682
|
+
const length = lengthScore(item.creator, item.bot);
|
|
683
|
+
const emoji = emojiScore(item.creator, item.bot);
|
|
684
|
+
const greeting = edgeScore(item.creator, item.bot);
|
|
685
|
+
const phrase = catchphraseScore(catchphrases, item.bot);
|
|
686
|
+
const banned = inspected.bannedTopics.some((topic) => mentionsTopic(item.bot, topic))
|
|
687
|
+
? 0
|
|
688
|
+
: 1;
|
|
689
|
+
return (length + emoji + greeting + phrase + banned) / 5;
|
|
690
|
+
});
|
|
691
|
+
const score = round4(scores.reduce((sum, value) => sum + value, 0) / scores.length);
|
|
692
|
+
const excerpts = [];
|
|
693
|
+
for (const item of fixtures.cases) {
|
|
694
|
+
if (typeof item.situation !== 'string') continue;
|
|
695
|
+
for (const object of filterExemplars(
|
|
696
|
+
inspected,
|
|
697
|
+
`FROM chunk SEARCH ${JSON.stringify(item.situation)} LIMIT 20`,
|
|
698
|
+
item.situation
|
|
699
|
+
)) {
|
|
700
|
+
if (!excerpts.includes(object.id)) excerpts.push(object.id);
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
excerpts.sort(compareText);
|
|
704
|
+
const receiptId = `pr_${sha256(
|
|
705
|
+
`${inspected.image.stateRoot}\n${excerpts.join(',')}\n${score.toFixed(4)}`
|
|
706
|
+
).slice(0, 24)}`;
|
|
707
|
+
return { score, excerpts, receiptId };
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
function lengthScore(creator, bot) {
|
|
711
|
+
const left = wordCount(creator);
|
|
712
|
+
const right = wordCount(bot);
|
|
713
|
+
if (left === 0 && right === 0) return 1;
|
|
714
|
+
return Math.min(left, right) / Math.max(left, right);
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
function emojiScore(creator, bot) {
|
|
718
|
+
return 1 - Math.min(1, Math.abs(emojiRate(creator) - emojiRate(bot)));
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
function edgeScore(creator, bot) {
|
|
722
|
+
const greeting = edgeMatch(creator, bot, ['hey', 'hi', 'hello'], true);
|
|
723
|
+
const signoff = edgeMatch(creator, bot, ['thanks', 'thank', 'bye', 'cheers'], false);
|
|
724
|
+
return (greeting + signoff) / 2;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
function edgeMatch(creator, bot, words, atStart) {
|
|
728
|
+
const left = hasEdge(creator, words, atStart);
|
|
729
|
+
const right = hasEdge(bot, words, atStart);
|
|
730
|
+
return left === right ? 1 : 0;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
function hasEdge(text, words, atStart) {
|
|
734
|
+
const parts = text
|
|
735
|
+
.toLowerCase()
|
|
736
|
+
.split(/[^\p{L}\p{N}]+/u)
|
|
737
|
+
.filter(Boolean);
|
|
738
|
+
const word = atStart ? parts[0] : parts[parts.length - 1];
|
|
739
|
+
return words.includes(word);
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
function catchphraseScore(phrases, bot) {
|
|
743
|
+
if (phrases.length === 0) return 1;
|
|
744
|
+
const haystack = bot.toLowerCase();
|
|
745
|
+
const hits = phrases.filter(
|
|
746
|
+
(phrase) => typeof phrase === 'string' && phrase && haystack.includes(phrase.toLowerCase())
|
|
747
|
+
);
|
|
748
|
+
return hits.length / phrases.length;
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
function wordCount(text) {
|
|
752
|
+
return text.split(/[^\p{L}\p{N}]+/u).filter(Boolean).length;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
function emojiRate(text) {
|
|
756
|
+
const matches = text.match(/\p{Extended_Pictographic}/gu);
|
|
757
|
+
return (matches ? matches.length : 0) / Math.max(text.length, 1);
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
function mentionsTopic(text, topic) {
|
|
761
|
+
if (typeof topic !== 'string' || !topic.trim()) return false;
|
|
762
|
+
const escaped = topic.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
763
|
+
return new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, 'iu').test(text);
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
function round4(value) {
|
|
767
|
+
return Math.round(value * 10000) / 10000;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
function printEvidence(inspected, exemplars, print) {
|
|
771
|
+
print(inspected.disclosure);
|
|
772
|
+
print(`stateRoot ${inspected.image.stateRoot}`);
|
|
773
|
+
for (const excerpt of exemplars) {
|
|
774
|
+
print(`${excerpt.source} ${excerpt.digest}`);
|
|
775
|
+
print(excerpt.excerpt.trim());
|
|
776
|
+
}
|
|
777
|
+
print(RECEIPT_NOTE);
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
function systemPrompt(inspected) {
|
|
781
|
+
return [
|
|
782
|
+
'Speak only from the verified excerpts and the persona profile.',
|
|
783
|
+
`Include this disclosure line exactly: ${inspected.disclosure}`,
|
|
784
|
+
'Do not invent prices, availability, or offers.',
|
|
785
|
+
'Do not claim to be the human creator.',
|
|
786
|
+
'The host owns the model. Knolo core does not call a model.',
|
|
787
|
+
].join('\n');
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
function userPrompt(prompt, inspected, exemplars) {
|
|
791
|
+
return [
|
|
792
|
+
`Profile: ${JSON.stringify(inspected.profile)}`,
|
|
793
|
+
'Excerpts:',
|
|
794
|
+
...exemplars.map((excerpt) => `${excerpt.source}\n${excerpt.excerpt}`),
|
|
795
|
+
`Question: ${prompt}`,
|
|
796
|
+
].join('\n');
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
async function readModelAnswer(modelResponse) {
|
|
800
|
+
let modelBody;
|
|
801
|
+
try {
|
|
802
|
+
const text =
|
|
803
|
+
typeof modelResponse?.text === 'function' ? await modelResponse.text() : '';
|
|
804
|
+
modelBody = text ? JSON.parse(text) : undefined;
|
|
805
|
+
} catch {
|
|
806
|
+
modelBody = undefined;
|
|
807
|
+
}
|
|
808
|
+
const content = modelBody?.choices?.[0]?.message?.content;
|
|
809
|
+
if (!modelResponse?.ok || typeof content !== 'string') return '';
|
|
810
|
+
return content.trim();
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
async function listPackFiles(dir) {
|
|
814
|
+
const info = await lstat(dir);
|
|
815
|
+
if (!info.isDirectory() || info.isSymbolicLink()) {
|
|
816
|
+
throw new Error('PERSONA_PACK: expected a persona directory.');
|
|
817
|
+
}
|
|
818
|
+
const files = [];
|
|
819
|
+
async function walk(current) {
|
|
820
|
+
const entries = await readdir(current, { withFileTypes: true });
|
|
821
|
+
entries.sort((left, right) => compareText(left.name, right.name));
|
|
822
|
+
for (const entry of entries) {
|
|
823
|
+
if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'dist') {
|
|
824
|
+
continue;
|
|
825
|
+
}
|
|
826
|
+
const full = path.join(current, entry.name);
|
|
827
|
+
const stat = await lstat(full);
|
|
828
|
+
if (stat.isSymbolicLink()) {
|
|
829
|
+
throw new Error(`PERSONA_PACK: refusing symlink ${entry.name}.`);
|
|
830
|
+
}
|
|
831
|
+
if (stat.isDirectory()) {
|
|
832
|
+
await walk(full);
|
|
833
|
+
continue;
|
|
834
|
+
}
|
|
835
|
+
if (!stat.isFile()) continue;
|
|
836
|
+
const source = path.relative(dir, full).split(path.sep).join('/');
|
|
837
|
+
if (SKIP_FILES.has(source)) continue;
|
|
838
|
+
if (!EXTENSIONS.has(path.extname(entry.name).toLowerCase())) continue;
|
|
839
|
+
if (stat.size > MAX_FILE_BYTES) {
|
|
840
|
+
throw new Error(`PERSONA_PACK: ${source} is larger than 1 MiB.`);
|
|
841
|
+
}
|
|
842
|
+
files.push({ full, source });
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
await walk(dir);
|
|
846
|
+
files.sort((left, right) => compareText(left.source, right.source));
|
|
847
|
+
return files;
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
function canonical(value) {
|
|
851
|
+
if (value === null) return 'null';
|
|
852
|
+
const kind = typeof value;
|
|
853
|
+
if (kind === 'string' || kind === 'boolean') return JSON.stringify(value);
|
|
854
|
+
if (kind === 'number') {
|
|
855
|
+
if (!Number.isFinite(value)) throw new Error('PERSONA_PACK: value is not canonical.');
|
|
856
|
+
return JSON.stringify(value);
|
|
857
|
+
}
|
|
858
|
+
if (Array.isArray(value)) return `[${value.map((item) => canonical(item)).join(',')}]`;
|
|
859
|
+
if (kind === 'object') {
|
|
860
|
+
const keys = Object.keys(value)
|
|
861
|
+
.filter((key) => value[key] !== undefined)
|
|
862
|
+
.sort(compareText);
|
|
863
|
+
return `{${keys.map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(',')}}`;
|
|
864
|
+
}
|
|
865
|
+
throw new Error('PERSONA_PACK: value is not canonical.');
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
function pretty(value) {
|
|
869
|
+
return `${JSON.stringify(value, null, 2)}\n`;
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
function sha256(bytes) {
|
|
873
|
+
return crypto.createHash('sha256').update(bytes).digest('hex');
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
function compareText(left, right) {
|
|
877
|
+
if (left < right) return -1;
|
|
878
|
+
if (left > right) return 1;
|
|
879
|
+
return 0;
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
function resolveDir(dirArg) {
|
|
883
|
+
if (!dirArg) throw new Error(`Missing persona directory.\n${USAGE}`);
|
|
884
|
+
return path.resolve(process.cwd(), dirArg);
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
async function readUserFile(file, maxBytes) {
|
|
888
|
+
if (!file) throw new Error('PERSONA_PACK: missing file.');
|
|
889
|
+
const resolved = path.resolve(process.cwd(), file);
|
|
890
|
+
const stat = await lstat(resolved);
|
|
891
|
+
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('PERSONA_PACK: expected a file.');
|
|
892
|
+
if (stat.size > maxBytes) throw new Error('PERSONA_PACK: file is larger than the limit.');
|
|
893
|
+
return readFile(resolved);
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
function parseArgs(argv) {
|
|
897
|
+
const positionals = [];
|
|
898
|
+
const flags = { withdrawn: [], json: false, help: false };
|
|
899
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
900
|
+
const arg = argv[index];
|
|
901
|
+
if (arg === '--help' || arg === '-h') flags.help = true;
|
|
902
|
+
else if (arg === '--json') flags.json = true;
|
|
903
|
+
else if (arg === '--dir') flags.dir = takeValue(argv, ++index, '--dir');
|
|
904
|
+
else if (arg === '--out') flags.out = takeValue(argv, ++index, '--out');
|
|
905
|
+
else if (arg === '--fixtures') flags.fixtures = takeValue(argv, ++index, '--fixtures');
|
|
906
|
+
else if (arg === '--withdrawn') flags.withdrawn.push(takeValue(argv, ++index, '--withdrawn'));
|
|
907
|
+
else if (arg.startsWith('--')) throw new Error(`Unknown persona option "${arg}".\n${USAGE}`);
|
|
908
|
+
else positionals.push(arg);
|
|
909
|
+
}
|
|
910
|
+
return { positionals, flags };
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
function parseChatArgs(argv) {
|
|
914
|
+
const flags = { help: false, evidence: false };
|
|
915
|
+
const positionals = [];
|
|
916
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
917
|
+
const arg = argv[index];
|
|
918
|
+
if (arg === '--help' || arg === '-h') flags.help = true;
|
|
919
|
+
else if (arg === '--evidence') flags.evidence = true;
|
|
920
|
+
else if (arg === '--situation') flags.situation = takeValue(argv, ++index, '--situation');
|
|
921
|
+
else if (arg === '--prompt') flags.prompt = takeValue(argv, ++index, '--prompt');
|
|
922
|
+
else if (arg === '--model') flags.model = takeValue(argv, ++index, '--model');
|
|
923
|
+
else if (arg === '--base-url') flags.baseUrl = takeValue(argv, ++index, '--base-url');
|
|
924
|
+
else if (arg.startsWith('--')) throw new Error(`Unknown persona option "${arg}".`);
|
|
925
|
+
else positionals.push(arg);
|
|
926
|
+
}
|
|
927
|
+
flags.image = positionals[0];
|
|
928
|
+
if (!flags.help && !flags.image) throw new Error(`Missing persona image.\n${chatUsage()}`);
|
|
929
|
+
return flags;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
function takeValue(argv, index, name) {
|
|
933
|
+
const value = argv[index];
|
|
934
|
+
if (!value || value.startsWith('--')) throw new Error(`Missing ${name}.\n${USAGE}`);
|
|
935
|
+
return value;
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
function coreReady(loaded) {
|
|
939
|
+
return Boolean(
|
|
940
|
+
loaded?.createKnowledgeImageV5 &&
|
|
941
|
+
loaded.queryKnowledgeImageV5 &&
|
|
942
|
+
loaded.mountKnowledgeImageV5
|
|
943
|
+
);
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
let corePromise;
|
|
947
|
+
|
|
948
|
+
function loadCore() {
|
|
949
|
+
corePromise ??= loadCoreModule(
|
|
950
|
+
[path.resolve(__dirname, '../../core/dist/index.js'), '@knolo/core'],
|
|
951
|
+
coreReady
|
|
952
|
+
).catch((error) => {
|
|
953
|
+
corePromise = undefined;
|
|
954
|
+
const detail = error instanceof Error ? error.message : 'module did not export the Knowledge Image API';
|
|
955
|
+
throw new Error(`Could not load @knolo/core. Build packages/core first. (${detail})`);
|
|
956
|
+
});
|
|
957
|
+
return corePromise;
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
function kiteReady(loaded) {
|
|
961
|
+
return Boolean(
|
|
962
|
+
loaded?.createKiteSession && loaded?.evaluateKiteSession && loaded?.verifyKiteCertificate
|
|
963
|
+
);
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
async function loadKite() {
|
|
967
|
+
const candidate = path.resolve(__dirname, '../../core/dist/kite/index.js');
|
|
968
|
+
try {
|
|
969
|
+
const loaded = await import(pathToFileURL(candidate).href);
|
|
970
|
+
if (kiteReady(loaded)) return loaded;
|
|
971
|
+
} catch {
|
|
972
|
+
// An installed package does not have the checkout dist path.
|
|
973
|
+
}
|
|
974
|
+
try {
|
|
975
|
+
const loaded = await import('@knolo/core/kite');
|
|
976
|
+
if (kiteReady(loaded)) return loaded;
|
|
977
|
+
} catch {
|
|
978
|
+
// The package fallback is absent until core is installed.
|
|
979
|
+
}
|
|
980
|
+
throw new Error('Could not load @knolo/core/kite. Build packages/core first.');
|
|
981
|
+
}
|