@moikapy/origen 0.4.1 → 0.5.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.
package/dist/soul.js CHANGED
@@ -1,330 +1,7 @@
1
- // src/soul.ts
2
- function parseYamlFrontMatter(content) {
3
- const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)?$/);
4
- if (!match) {
5
- return { frontMatter: {}, body: content };
6
- }
7
- const rawYaml = match[1];
8
- const markdownBody = match[2] ?? "";
9
- const frontMatter = parseSoulYaml(rawYaml);
10
- return { frontMatter, body: markdownBody };
11
- }
12
- function parseSoulYaml(raw) {
13
- const lines = raw.split("\n").map((l) => l.replace(/\r$/, ""));
14
- const { result } = parseBlock(lines, 0, 0);
15
- return result;
16
- }
17
- function parseBlock(lines, start, baseIndent) {
18
- const result = {};
19
- let i = start;
20
- while (i < lines.length) {
21
- const line = lines[i];
22
- const indent = lineLengths(line).indent;
23
- if (line.trim() === "") {
24
- i++;
25
- continue;
26
- }
27
- if (indent < baseIndent) break;
28
- const trimmed = line.trim();
29
- if (trimmed.startsWith("- ")) {
30
- i++;
31
- continue;
32
- }
33
- const kvMatch = trimmed.match(/^([\w][\w.-]*):\s*(.*)$/);
34
- if (!kvMatch) {
35
- i++;
36
- continue;
37
- }
38
- const key = kvMatch[1];
39
- const inlineVal = kvMatch[2].trim();
40
- if (inlineVal === "") {
41
- const nextLine = i + 1 < lines.length ? lines[i + 1] : "";
42
- const nextIndent = nextLine.trim() === "" ? 0 : lineLengths(nextLine).indent;
43
- const nextTrimmed = nextLine.trim();
44
- if (nextIndent > indent) {
45
- if (nextTrimmed.startsWith("- ")) {
46
- const { items, nextLine: afterList } = parseList(lines, i + 1, nextIndent);
47
- result[key] = items;
48
- i = afterList;
49
- } else {
50
- const { result: nested, nextLine: afterNested } = parseBlock(lines, i + 1, nextIndent);
51
- result[key] = nested;
52
- i = afterNested;
53
- }
54
- } else {
55
- result[key] = null;
56
- i++;
57
- }
58
- } else {
59
- result[key] = parseScalar(inlineVal);
60
- i++;
61
- }
62
- }
63
- return { result, nextLine: i };
64
- }
65
- function parseList(lines, start, baseIndent) {
66
- const items = [];
67
- let i = start;
68
- while (i < lines.length) {
69
- const line = lines[i];
70
- const indent = lineLengths(line).indent;
71
- if (line.trim() === "") {
72
- i++;
73
- continue;
74
- }
75
- if (indent < baseIndent) break;
76
- if (!line.trim().startsWith("- ")) break;
77
- const value = line.trim().slice(2).trim();
78
- items.push(parseScalar(value));
79
- i++;
80
- }
81
- return { items, nextLine: i };
82
- }
83
- function parseScalar(value) {
84
- if (value === "null" || value === "~") return null;
85
- if (value === "true") return true;
86
- if (value === "false") return false;
87
- if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
88
- return value.slice(1, -1);
89
- }
90
- if (/^-?\d+$/.test(value)) return parseInt(value, 10);
91
- if (/^-?\d+\.\d+$/.test(value)) return parseFloat(value);
92
- if (value.startsWith("[") && value.endsWith("]")) {
93
- return value.slice(1, -1).split(",").map((s) => parseScalar(s.trim()));
94
- }
95
- return value;
96
- }
97
- function lineLengths(line) {
98
- const match = line.match(/^(\s*)(.*)$/);
99
- const indent = match ? match[1].length : 0;
100
- const content = match ? match[2] : "";
101
- return { indent, content };
102
- }
103
- var Soul = class _Soul {
104
- config;
105
- body;
106
- constructor(config, body) {
107
- this.config = config;
108
- this.body = body;
109
- }
110
- /** Select a profile and return a new Soul with that profile merged in. */
111
- selectProfile(profileName) {
112
- const profiles = this.config.profiles ?? ["default"];
113
- const overrides = this.config.profile_overrides ?? {};
114
- const profileOverrides = overrides[profileName];
115
- if (!profiles.includes(profileName) || !profileOverrides) {
116
- return this;
117
- }
118
- const merged = mergeDeep(
119
- structuredClone(this.config),
120
- profileOverrides
121
- );
122
- return new _Soul(merged, this.body);
123
- }
124
- /** Build a system prompt from the Soul definition. */
125
- buildPrompt() {
126
- const parts = [];
127
- const identity = this.config.identity;
128
- if (identity) {
129
- const role = identity.role ?? this.config.name;
130
- const archetype = identity.archetype;
131
- parts.push(`You are ${this.config.name}${archetype ? `, a ${archetype}` : ""}${role ? `. Role: ${role}` : ""}.`);
132
- if (identity.domain_focus?.length) {
133
- parts.push(`Domain expertise: ${identity.domain_focus.join(", ")}.`);
134
- }
135
- if (identity.non_goals?.length) {
136
- parts.push(`Non-goals: ${identity.non_goals.join(", ")}.`);
137
- }
138
- } else {
139
- parts.push(`You are ${this.config.name}.`);
140
- }
141
- const relationship = this.config.relationship;
142
- if (relationship) {
143
- if (relationship.stance) {
144
- const stanceMap = {
145
- subordinate: "You serve the user's direction.",
146
- peer: "You collaborate with the user as a partner.",
147
- authoritative: "You provide expert guidance and direction.",
148
- adversarial: "You challenge the user's assumptions to improve outcomes."
149
- };
150
- parts.push(stanceMap[relationship.stance] ?? "");
151
- }
152
- if (relationship.user_model_default) {
153
- const userModelMap = {
154
- novice: "Assume the user is new to this domain. Explain terms and concepts.",
155
- intermediate: "Assume moderate familiarity. Explain only when needed.",
156
- expert: "Be concise. The user knows the domain well.",
157
- unknown: "Adapt your explanation depth to the user's apparent knowledge level."
158
- };
159
- parts.push(userModelMap[relationship.user_model_default] ?? "");
160
- }
161
- }
162
- const values = this.config.values;
163
- if (values?.priorities?.length) {
164
- parts.push(`
165
- ## Priorities (in order)
166
- ${values.priorities.map((p, i) => `${i + 1}. ${p}`).join("\n")}`);
167
- }
168
- if (values?.taboo?.length) {
169
- parts.push(`
170
- ## Forbidden patterns
171
- ${values.taboo.map((t) => `- ${t}`).join("\n")}`);
172
- }
173
- const voice = this.config.voice;
174
- if (voice) {
175
- const voiceParts = ["\n## Voice & Style"];
176
- if (voice.formality !== void 0) {
177
- const level = voice.formality <= 30 ? "very casual" : voice.formality <= 60 ? "moderately formal" : voice.formality <= 80 ? "professional" : "highly formal";
178
- voiceParts.push(`Formality: ${level} (${voice.formality}/100).`);
179
- }
180
- if (voice.warmth !== void 0) {
181
- const level = voice.warmth <= 30 ? "cold/detached" : voice.warmth <= 60 ? "neutral" : voice.warmth <= 80 ? "warm and approachable" : "very friendly and encouraging";
182
- voiceParts.push(`Tone: ${level} (${voice.warmth}/100).`);
183
- }
184
- if (voice.verbosity !== void 0) {
185
- const level = voice.verbosity <= 25 ? "extremely concise" : voice.verbosity <= 50 ? "concise" : voice.verbosity <= 75 ? "moderate length" : "thorough and detailed";
186
- voiceParts.push(`Brevity: ${level} (${voice.verbosity}/100).`);
187
- }
188
- if (voice.jargon !== void 0) {
189
- const level = voice.jargon <= 30 ? "use plain language" : voice.jargon <= 60 ? "use moderate technical terms" : "use domain-specific terminology freely";
190
- voiceParts.push(`Jargon: ${level} (${voice.jargon}/100).`);
191
- }
192
- if (voice.formatting) voiceParts.push(`Formatting: ${voice.formatting}.`);
193
- if (voice.banned_phrases?.length) voiceParts.push(`Never say: ${voice.banned_phrases.map((p) => `"${p}"`).join(", ")}.`);
194
- if (voice.preferred_phrases?.length) voiceParts.push(`Prefer: ${voice.preferred_phrases.map((p) => `"${p}"`).join(", ")}.`);
195
- if (voice.emoji_policy && voice.emoji_policy !== "rare") voiceParts.push(`Emoji usage: ${voice.emoji_policy}.`);
196
- parts.push(voiceParts.join(" "));
197
- }
198
- const interaction = this.config.interaction;
199
- if (interaction) {
200
- const interactionParts = ["\n## Interaction Policy"];
201
- if (interaction.clarifying_questions) {
202
- const qMap = {
203
- never: "Never ask clarifying questions. Make reasonable assumptions.",
204
- when_ambiguous: "Ask clarifying questions only when the query is ambiguous.",
205
- always: "Always confirm your understanding before responding."
206
- };
207
- interactionParts.push(qMap[interaction.clarifying_questions] ?? "");
208
- }
209
- if (interaction.uncertainty) {
210
- const uMap = {
211
- explicit: "Explicitly mark uncertain information. Say when you're not sure.",
212
- implicit: "Use hedging language (might, possibly, could) for uncertain claims.",
213
- never: "Never express uncertainty. State your best answer confidently."
214
- };
215
- interactionParts.push(uMap[interaction.uncertainty] ?? "");
216
- }
217
- if (interaction.disagreement) {
218
- const dMap = {
219
- soft: "Disagree gently. Acknowledge the user's perspective first.",
220
- neutral: "State disagreements directly but politely.",
221
- direct: "Challenge incorrect views directly. Don't soften disagreements."
222
- };
223
- interactionParts.push(dMap[interaction.disagreement] ?? "");
224
- }
225
- if (interaction.confirmations === "none") {
226
- interactionParts.push("Don't ask for confirmation before acting. Just do it.");
227
- }
228
- parts.push(interactionParts.join(" "));
229
- }
230
- const cognition = this.config.cognition;
231
- if (cognition) {
232
- const cogParts = ["\n## Cognition"];
233
- if (cognition.mode) {
234
- const modeMap = {
235
- analytical: "Think analytically. Break problems down, examine evidence, reason step by step.",
236
- creative: "Think creatively. Generate novel ideas, make unexpected connections.",
237
- operational: "Focus on execution. Prioritize working solutions over theory.",
238
- exploratory: "Explore broadly. Consider many angles before committing to an answer.",
239
- teaching: "Teach and explain. Build understanding progressively from basics.",
240
- mixed: "Adapt your thinking mode to the task at hand."
241
- };
242
- cogParts.push(modeMap[cognition.mode] ?? "");
243
- }
244
- if (cognition.verification?.fact_checking) {
245
- const fcMap = {
246
- none: "No explicit fact-checking.",
247
- light: "Verify key claims before stating them.",
248
- strict: "Always verify claims. Never state unverified information as fact."
249
- };
250
- cogParts.push(fcMap[cognition.verification.fact_checking] ?? "");
251
- }
252
- parts.push(cogParts.join(" "));
253
- }
254
- const safety = this.config.safety;
255
- if (safety) {
256
- const safetyParts = ["\n## Safety"];
257
- if (safety.speculation) {
258
- const specMap = {
259
- allow: "You may speculate freely.",
260
- mark: "Mark speculative content clearly (e.g., 'I believe', 'likely', 'possibly').",
261
- avoid: "Do not speculate. Only state what you can verify."
262
- };
263
- safetyParts.push(specMap[safety.speculation] ?? "");
264
- }
265
- if (safety.refusal_style) {
266
- const refMap = {
267
- brief: "Refuse briefly. No lectures.",
268
- explain: "Explain why you're refusing when you decline a request.",
269
- policy_cite: "Cite specific policies when refusing requests."
270
- };
271
- safetyParts.push(refMap[safety.refusal_style] ?? "");
272
- }
273
- if (safety.no_fabrication) safetyParts.push("Never fabricate information. If you don't know, say so.");
274
- if (safety.no_false_certainty) safetyParts.push("Never present uncertain information as certain.");
275
- parts.push(safetyParts.join(" "));
276
- }
277
- const actions = this.config.actions;
278
- if (actions) {
279
- const actParts = ["\n## Actions"];
280
- const toolMap = {
281
- avoid_tools: "Minimize tool use. Answer from knowledge when possible.",
282
- when_needed: "Use tools when they would improve your answer.",
283
- prefer_tools: "Proactively use available tools. Always verify with tools rather than memory."
284
- };
285
- actParts.push(toolMap[actions.when_to_use_tools] ?? "");
286
- if (actions.explain_actions === "brief" || actions.explain_actions === "full") {
287
- actParts.push(actions.explain_actions === "full" ? "Explain what you're doing before and after tool use." : "Briefly explain tool use.");
288
- }
289
- parts.push(actParts.join(" "));
290
- }
291
- if (this.body.trim()) {
292
- parts.push(`
293
- ## Additional Instructions
294
-
295
- ${this.body.trim()}`);
296
- }
297
- return parts.join("\n\n");
298
- }
299
- get defaultProfile() {
300
- return this.config.profiles?.[0] ?? "default";
301
- }
302
- get profileNames() {
303
- return this.config.profiles ?? ["default"];
304
- }
305
- };
306
- function loadSoul(content) {
307
- const { frontMatter, body } = parseYamlFrontMatter(content);
308
- const config = frontMatter;
309
- if (!config.id) throw new Error("Soul.md missing required field: id");
310
- if (!config.name) throw new Error("Soul.md missing required field: name");
311
- return new Soul(config, body);
312
- }
313
- function mergeDeep(base, overlay) {
314
- const result = { ...base };
315
- for (const key of Object.keys(overlay)) {
316
- const baseVal = result[key];
317
- const overVal = overlay[key];
318
- if (overVal === null) {
319
- result[key] = null;
320
- } else if (typeof baseVal === "object" && baseVal !== null && !Array.isArray(baseVal) && typeof overVal === "object" && overVal !== null && !Array.isArray(overVal)) {
321
- result[key] = mergeDeep(baseVal, overVal);
322
- } else {
323
- result[key] = overVal;
324
- }
325
- }
326
- return result;
327
- }
1
+ import {
2
+ Soul,
3
+ loadSoul
4
+ } from "./chunk-QF3XSUMT.js";
328
5
  export {
329
6
  Soul,
330
7
  loadSoul
package/dist/soul.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/soul.ts"],"sourcesContent":["/**\n * Soul.md parser for Origen agent personas.\n *\n * Implements Soul.md Standard (RFC-1, v1.0.0-rc1):\n * https://github.com/rokoss21/soul.md\n *\n * Parses a portable, provider-agnostic persona definition and produces\n * a system prompt, runtime config, and profile overlays for Origen.\n *\n * Usage:\n * import { Soul, loadSoul } from \"@moikapy/origen/soul\";\n *\n * const soul = loadSoul(soulMdContent);\n * const systemPrompt = soul.buildPrompt();\n * const profile = soul.selectProfile(\"concise\");\n */\n\n// ── YAML front matter parser ──────────────────────────────────────────\n\nfunction parseYamlFrontMatter(content: string): { frontMatter: Record<string, unknown>; body: string } {\n const match = content.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)?$/);\n if (!match) {\n return { frontMatter: {}, body: content };\n }\n const rawYaml = match[1];\n const markdownBody = match[2] ?? \"\";\n const frontMatter = parseSoulYaml(rawYaml);\n return { frontMatter, body: markdownBody };\n}\n\n/**\n * Minimal YAML parser for Soul.md front matter.\n * Handles maps, sequences, inline values, and quoted strings.\n * Does NOT support anchors, aliases, merge keys, or complex types.\n */\nfunction parseSoulYaml(raw: string): Record<string, unknown> {\n const lines = raw.split(\"\\n\").map((l) => l.replace(/\\r$/, \"\"));\n const { result } = parseBlock(lines, 0, 0);\n return result;\n}\n\ninterface BlockResult {\n result: Record<string, unknown>;\n nextLine: number;\n}\n\nfunction parseBlock(lines: string[], start: number, baseIndent: number): BlockResult {\n const result: Record<string, unknown> = {};\n let i = start;\n\n while (i < lines.length) {\n const line = lines[i];\n const indent = lineLengths(line).indent;\n\n if (line.trim() === \"\") { i++; continue; }\n if (indent < baseIndent) break; // End of this block\n\n const trimmed = line.trim();\n\n // Skip list items at top level of a map block (shouldn't happen, but guard)\n if (trimmed.startsWith(\"- \")) { i++; continue; }\n\n // key: value\n const kvMatch = trimmed.match(/^([\\w][\\w.-]*):\\s*(.*)$/);\n if (!kvMatch) { i++; continue; }\n\n const key = kvMatch[1];\n const inlineVal = kvMatch[2].trim();\n\n if (inlineVal === \"\") {\n // Value continues on next lines\n const nextLine = i + 1 < lines.length ? lines[i + 1] : \"\";\n const nextIndent = nextLine.trim() === \"\" ? 0 : lineLengths(nextLine).indent;\n const nextTrimmed = nextLine.trim();\n\n if (nextIndent > indent) {\n if (nextTrimmed.startsWith(\"- \")) {\n // It's a list block\n const { items, nextLine: afterList } = parseList(lines, i + 1, nextIndent);\n result[key] = items;\n i = afterList;\n } else {\n // It's a nested map block\n const { result: nested, nextLine: afterNested } = parseBlock(lines, i + 1, nextIndent);\n result[key] = nested;\n i = afterNested;\n }\n } else {\n // Empty value\n result[key] = null;\n i++;\n }\n } else {\n // Inline value\n result[key] = parseScalar(inlineVal);\n i++;\n }\n }\n\n return { result, nextLine: i };\n}\n\ninterface ListResult {\n items: unknown[];\n nextLine: number;\n}\n\nfunction parseList(lines: string[], start: number, baseIndent: number): ListResult {\n const items: unknown[] = [];\n let i = start;\n\n while (i < lines.length) {\n const line = lines[i];\n const indent = lineLengths(line).indent;\n\n if (line.trim() === \"\") { i++; continue; }\n if (indent < baseIndent) break;\n if (!line.trim().startsWith(\"- \")) break;\n\n const value = line.trim().slice(2).trim();\n items.push(parseScalar(value));\n i++;\n }\n\n return { items, nextLine: i };\n}\n\nfunction parseScalar(value: string): unknown {\n if (value === \"null\" || value === \"~\") return null;\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n\n // Quoted string\n if ((value.startsWith('\"') && value.endsWith('\"')) || (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n return value.slice(1, -1);\n }\n\n // Number\n if (/^-?\\d+$/.test(value)) return parseInt(value, 10);\n if (/^-?\\d+\\.\\d+$/.test(value)) return parseFloat(value);\n\n // Inline list [a, b, c]\n if (value.startsWith(\"[\") && value.endsWith(\"]\")) {\n return value\n .slice(1, -1)\n .split(\",\")\n .map((s) => parseScalar(s.trim()));\n }\n\n return value;\n}\n\nfunction lineLengths(line: string): { indent: number; content: string } {\n const match = line.match(/^(\\s*)(.*)$/);\n const indent = match ? match[1].length : 0;\n const content = match ? match[2] : \"\";\n return { indent, content };\n}\n\n// ── Soul types ─────────────────────────────────────────────────────────\n\nexport interface SoulVoice {\n formality: number;\n warmth: number;\n verbosity: number;\n jargon: number;\n formatting: \"minimal\" | \"plain\" | \"markdown\";\n banned_phrases?: string[];\n preferred_phrases?: string[];\n emoji_policy?: \"never\" | \"rare\" | \"normal\";\n punctuation?: \"normal\" | \"sparse\";\n}\n\nexport interface SoulInteraction {\n clarifying_questions: \"never\" | \"when_ambiguous\" | \"always\";\n uncertainty: \"explicit\" | \"implicit\" | \"never\";\n disagreement: \"soft\" | \"neutral\" | \"direct\";\n confirmations: \"none\" | \"implicit\" | \"explicit\";\n}\n\nexport interface SoulCognition {\n mode?: \"analytical\" | \"creative\" | \"operational\" | \"exploratory\" | \"teaching\" | \"mixed\";\n depth?: number;\n speed_vs_rigor?: number;\n verification?: {\n fact_checking?: \"none\" | \"light\" | \"strict\";\n cross_validation?: number;\n consistency_checks?: number;\n assumption_tracking?: \"none\" | \"implicit\" | \"explicit\";\n };\n}\n\nexport interface SoulSafety {\n refusal_style: \"brief\" | \"explain\" | \"policy_cite\";\n privacy: \"normal\" | \"strict\";\n speculation: \"allow\" | \"mark\" | \"avoid\";\n no_fabrication?: boolean;\n no_false_certainty?: boolean;\n}\n\nexport interface SoulActions {\n when_to_use_tools: \"avoid_tools\" | \"when_needed\" | \"prefer_tools\";\n explain_actions: \"no\" | \"brief\" | \"full\";\n failover: \"retry\" | \"alternative_method\" | \"ask_user\";\n}\n\nexport interface SoulConfig {\n soul_spec?: string;\n id: string;\n name: string;\n locale?: string;\n version?: string;\n description?: string;\n composition?: {\n extends?: string[];\n mixins?: string[];\n merge_policy?: string;\n };\n profiles?: string[];\n profile_overrides?: Record<string, Record<string, unknown>>;\n values?: {\n priorities?: string[];\n tradeoffs?: string[];\n taboo?: string[];\n };\n identity?: {\n role?: string;\n archetype?: string;\n domain_focus?: string[];\n non_goals?: string[];\n };\n relationship?: {\n stance?: \"subordinate\" | \"peer\" | \"authoritative\" | \"adversarial\";\n user_model_default?: \"novice\" | \"intermediate\" | \"expert\" | \"unknown\";\n trust_baseline?: number;\n boundary_distance?: number;\n };\n voice?: Partial<SoulVoice>;\n interaction?: Partial<SoulInteraction>;\n cognition?: SoulCognition;\n safety?: Partial<SoulSafety>;\n actions?: SoulActions;\n state?: {\n base?: string;\n states?: Record<string, Record<string, unknown>>;\n triggers?: Array<{ if: string; shift_to: string; duration?: string }>;\n };\n examples?: Array<{ user: string; agent: string }>;\n extensions?: Record<string, unknown>;\n}\n\n// ── Soul class ─────────────────────────────────────────────────────────\n\nexport class Soul {\n readonly config: SoulConfig;\n readonly body: string;\n\n constructor(config: SoulConfig, body: string) {\n this.config = config;\n this.body = body;\n }\n\n /** Select a profile and return a new Soul with that profile merged in. */\n selectProfile(profileName: string): Soul {\n const profiles = this.config.profiles ?? [\"default\"];\n const overrides = this.config.profile_overrides ?? {};\n const profileOverrides = overrides[profileName];\n\n if (!profiles.includes(profileName) || !profileOverrides) {\n return this;\n }\n\n const merged = mergeDeep(\n structuredClone(this.config) as unknown as Record<string, unknown>,\n profileOverrides as Record<string, unknown>\n ) as unknown as SoulConfig;\n return new Soul(merged, this.body);\n }\n\n /** Build a system prompt from the Soul definition. */\n buildPrompt(): string {\n const parts: string[] = [];\n\n // Identity\n const identity = this.config.identity;\n if (identity) {\n const role = identity.role ?? this.config.name;\n const archetype = identity.archetype;\n parts.push(`You are ${this.config.name}${archetype ? `, a ${archetype}` : \"\"}${role ? `. Role: ${role}` : \"\"}.`);\n if (identity.domain_focus?.length) {\n parts.push(`Domain expertise: ${identity.domain_focus.join(\", \")}.`);\n }\n if (identity.non_goals?.length) {\n parts.push(`Non-goals: ${identity.non_goals.join(\", \")}.`);\n }\n } else {\n parts.push(`You are ${this.config.name}.`);\n }\n\n // Relationship\n const relationship = this.config.relationship;\n if (relationship) {\n if (relationship.stance) {\n const stanceMap: Record<string, string> = {\n subordinate: \"You serve the user's direction.\",\n peer: \"You collaborate with the user as a partner.\",\n authoritative: \"You provide expert guidance and direction.\",\n adversarial: \"You challenge the user's assumptions to improve outcomes.\",\n };\n parts.push(stanceMap[relationship.stance] ?? \"\");\n }\n if (relationship.user_model_default) {\n const userModelMap: Record<string, string> = {\n novice: \"Assume the user is new to this domain. Explain terms and concepts.\",\n intermediate: \"Assume moderate familiarity. Explain only when needed.\",\n expert: \"Be concise. The user knows the domain well.\",\n unknown: \"Adapt your explanation depth to the user's apparent knowledge level.\",\n };\n parts.push(userModelMap[relationship.user_model_default] ?? \"\");\n }\n }\n\n // Values\n const values = this.config.values;\n if (values?.priorities?.length) {\n parts.push(`\\n## Priorities (in order)\\n${values.priorities.map((p, i) => `${i + 1}. ${p}`).join(\"\\n\")}`);\n }\n if (values?.taboo?.length) {\n parts.push(`\\n## Forbidden patterns\\n${values.taboo.map((t) => `- ${t}`).join(\"\\n\")}`);\n }\n\n // Voice\n const voice = this.config.voice;\n if (voice) {\n const voiceParts: string[] = [\"\\n## Voice & Style\"];\n if (voice.formality !== undefined) {\n const level = voice.formality <= 30 ? \"very casual\" : voice.formality <= 60 ? \"moderately formal\" : voice.formality <= 80 ? \"professional\" : \"highly formal\";\n voiceParts.push(`Formality: ${level} (${voice.formality}/100).`);\n }\n if (voice.warmth !== undefined) {\n const level = voice.warmth <= 30 ? \"cold/detached\" : voice.warmth <= 60 ? \"neutral\" : voice.warmth <= 80 ? \"warm and approachable\" : \"very friendly and encouraging\";\n voiceParts.push(`Tone: ${level} (${voice.warmth}/100).`);\n }\n if (voice.verbosity !== undefined) {\n const level = voice.verbosity <= 25 ? \"extremely concise\" : voice.verbosity <= 50 ? \"concise\" : voice.verbosity <= 75 ? \"moderate length\" : \"thorough and detailed\";\n voiceParts.push(`Brevity: ${level} (${voice.verbosity}/100).`);\n }\n if (voice.jargon !== undefined) {\n const level = voice.jargon <= 30 ? \"use plain language\" : voice.jargon <= 60 ? \"use moderate technical terms\" : \"use domain-specific terminology freely\";\n voiceParts.push(`Jargon: ${level} (${voice.jargon}/100).`);\n }\n if (voice.formatting) voiceParts.push(`Formatting: ${voice.formatting}.`);\n if (voice.banned_phrases?.length) voiceParts.push(`Never say: ${voice.banned_phrases.map((p) => `\"${p}\"`).join(\", \")}.`);\n if (voice.preferred_phrases?.length) voiceParts.push(`Prefer: ${voice.preferred_phrases.map((p) => `\"${p}\"`).join(\", \")}.`);\n if (voice.emoji_policy && voice.emoji_policy !== \"rare\") voiceParts.push(`Emoji usage: ${voice.emoji_policy}.`);\n parts.push(voiceParts.join(\" \"));\n }\n\n // Interaction\n const interaction = this.config.interaction;\n if (interaction) {\n const interactionParts: string[] = [\"\\n## Interaction Policy\"];\n if (interaction.clarifying_questions) {\n const qMap: Record<string, string> = {\n never: \"Never ask clarifying questions. Make reasonable assumptions.\",\n when_ambiguous: \"Ask clarifying questions only when the query is ambiguous.\",\n always: \"Always confirm your understanding before responding.\",\n };\n interactionParts.push(qMap[interaction.clarifying_questions] ?? \"\");\n }\n if (interaction.uncertainty) {\n const uMap: Record<string, string> = {\n explicit: \"Explicitly mark uncertain information. Say when you're not sure.\",\n implicit: \"Use hedging language (might, possibly, could) for uncertain claims.\",\n never: \"Never express uncertainty. State your best answer confidently.\",\n };\n interactionParts.push(uMap[interaction.uncertainty] ?? \"\");\n }\n if (interaction.disagreement) {\n const dMap: Record<string, string> = {\n soft: \"Disagree gently. Acknowledge the user's perspective first.\",\n neutral: \"State disagreements directly but politely.\",\n direct: \"Challenge incorrect views directly. Don't soften disagreements.\",\n };\n interactionParts.push(dMap[interaction.disagreement] ?? \"\");\n }\n if (interaction.confirmations === \"none\") {\n interactionParts.push(\"Don't ask for confirmation before acting. Just do it.\");\n }\n parts.push(interactionParts.join(\" \"));\n }\n\n // Cognition\n const cognition = this.config.cognition;\n if (cognition) {\n const cogParts: string[] = [\"\\n## Cognition\"];\n if (cognition.mode) {\n const modeMap: Record<string, string> = {\n analytical: \"Think analytically. Break problems down, examine evidence, reason step by step.\",\n creative: \"Think creatively. Generate novel ideas, make unexpected connections.\",\n operational: \"Focus on execution. Prioritize working solutions over theory.\",\n exploratory: \"Explore broadly. Consider many angles before committing to an answer.\",\n teaching: \"Teach and explain. Build understanding progressively from basics.\",\n mixed: \"Adapt your thinking mode to the task at hand.\",\n };\n cogParts.push(modeMap[cognition.mode] ?? \"\");\n }\n if (cognition.verification?.fact_checking) {\n const fcMap: Record<string, string> = {\n none: \"No explicit fact-checking.\",\n light: \"Verify key claims before stating them.\",\n strict: \"Always verify claims. Never state unverified information as fact.\",\n };\n cogParts.push(fcMap[cognition.verification.fact_checking] ?? \"\");\n }\n parts.push(cogParts.join(\" \"));\n }\n\n // Safety\n const safety = this.config.safety;\n if (safety) {\n const safetyParts: string[] = [\"\\n## Safety\"];\n if (safety.speculation) {\n const specMap: Record<string, string> = {\n allow: \"You may speculate freely.\",\n mark: \"Mark speculative content clearly (e.g., 'I believe', 'likely', 'possibly').\",\n avoid: \"Do not speculate. Only state what you can verify.\",\n };\n safetyParts.push(specMap[safety.speculation] ?? \"\");\n }\n if (safety.refusal_style) {\n const refMap: Record<string, string> = {\n brief: \"Refuse briefly. No lectures.\",\n explain: \"Explain why you're refusing when you decline a request.\",\n policy_cite: \"Cite specific policies when refusing requests.\",\n };\n safetyParts.push(refMap[safety.refusal_style] ?? \"\");\n }\n if (safety.no_fabrication) safetyParts.push(\"Never fabricate information. If you don't know, say so.\");\n if (safety.no_false_certainty) safetyParts.push(\"Never present uncertain information as certain.\");\n parts.push(safetyParts.join(\" \"));\n }\n\n // Actions\n const actions = this.config.actions;\n if (actions) {\n const actParts: string[] = [\"\\n## Actions\"];\n const toolMap: Record<string, string> = {\n avoid_tools: \"Minimize tool use. Answer from knowledge when possible.\",\n when_needed: \"Use tools when they would improve your answer.\",\n prefer_tools: \"Proactively use available tools. Always verify with tools rather than memory.\",\n };\n actParts.push(toolMap[actions.when_to_use_tools] ?? \"\");\n if (actions.explain_actions === \"brief\" || actions.explain_actions === \"full\") {\n actParts.push(actions.explain_actions === \"full\" ? \"Explain what you're doing before and after tool use.\" : \"Briefly explain tool use.\");\n }\n parts.push(actParts.join(\" \"));\n }\n\n // Markdown body\n if (this.body.trim()) {\n parts.push(`\\n## Additional Instructions\\n\\n${this.body.trim()}`);\n }\n\n return parts.join(\"\\n\\n\");\n }\n\n get defaultProfile(): string {\n return this.config.profiles?.[0] ?? \"default\";\n }\n\n get profileNames(): string[] {\n return this.config.profiles ?? [\"default\"];\n }\n}\n\n// ── Public API ──────────────────────────────────────────────────────────\n\n/** Parse a Soul.md string into a Soul instance. */\nexport function loadSoul(content: string): Soul {\n const { frontMatter, body } = parseYamlFrontMatter(content);\n const config = frontMatter as unknown as SoulConfig;\n\n if (!config.id) throw new Error(\"Soul.md missing required field: id\");\n if (!config.name) throw new Error(\"Soul.md missing required field: name\");\n\n return new Soul(config, body);\n}\n\n/** Deep merge (Standard Merge semantics from Soul.md spec). */\nfunction mergeDeep(base: Record<string, unknown>, overlay: Record<string, unknown>): Record<string, unknown> {\n const result = { ...base };\n for (const key of Object.keys(overlay)) {\n const baseVal = result[key];\n const overVal = overlay[key];\n if (overVal === null) {\n result[key] = null;\n } else if (\n typeof baseVal === \"object\" && baseVal !== null && !Array.isArray(baseVal) &&\n typeof overVal === \"object\" && overVal !== null && !Array.isArray(overVal)\n ) {\n result[key] = mergeDeep(baseVal as Record<string, unknown>, overVal as Record<string, unknown>);\n } else {\n result[key] = overVal;\n }\n }\n return result;\n}"],"mappings":";AAmBA,SAAS,qBAAqB,SAAyE;AACrG,QAAM,QAAQ,QAAQ,MAAM,8CAA8C;AAC1E,MAAI,CAAC,OAAO;AACV,WAAO,EAAE,aAAa,CAAC,GAAG,MAAM,QAAQ;AAAA,EAC1C;AACA,QAAM,UAAU,MAAM,CAAC;AACvB,QAAM,eAAe,MAAM,CAAC,KAAK;AACjC,QAAM,cAAc,cAAc,OAAO;AACzC,SAAO,EAAE,aAAa,MAAM,aAAa;AAC3C;AAOA,SAAS,cAAc,KA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AI,KAAK,QAAQ,IAAI;AAC9B;AAGA,SAAS,UAAU,MAA+B,SAA2D;AAC3G,QAAM,SAAS,EAAE,GAAG,KAAK;AACzB,aAAW,OAAO,OAAO,KAAK,OAAO,GAAG;AACtC,UAAM,UAAU,OAAO,GAAG;AAC1B,UAAM,UAAU,QAAQ,GAAG;AAC3B,QAAI,YAAY,MAAM;AACpB,aAAO,GAAG,IAAI;AAAA,IAChB,WACE,OAAO,YAAY,YAAY,YAAY,QAAQ,CAAC,MAAM,QAAQ,OAAO,KACzE,OAAO,YAAY,YAAY,YAAY,QAAQ,CAAC,MAAM,QAAQ,OAAO,GACzE;AACA,aAAO,GAAG,IAAI,UAAU,SAAoC,OAAkC;AAAA,IAChG,OAAO;AACL,aAAO,GAAG,IAAI;AAAA,IAChB;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moikapy/origen",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -46,4 +46,4 @@
46
46
  "vitest": "^3"
47
47
  },
48
48
  "license": "MIT"
49
- }
49
+ }
@@ -1,109 +0,0 @@
1
- // src/models.ts
2
- function getModelsForUI() {
3
- const uiModels = {};
4
- for (const [id, config] of Object.entries(MODELS)) {
5
- uiModels[id] = { name: config.name, description: config.description, free: config.free };
6
- }
7
- return uiModels;
8
- }
9
- function buildModels() {
10
- const models = {};
11
- models["openrouter/free"] = {
12
- name: "Free (Auto)",
13
- description: "Free \u2014 auto-selects best free model for your request",
14
- free: true
15
- };
16
- models["google/gemma-4-31b-it:free"] = {
17
- name: "Gemma 4 31B",
18
- description: "Free \u2014 great quality for Bible study",
19
- free: true
20
- };
21
- models["nvidia/nemotron-3-super-120b-a12b:free"] = {
22
- name: "Nemotron 3 Super",
23
- description: "Free \u2014 large model, strong reasoning",
24
- free: true
25
- };
26
- models["deepseek/deepseek-r1:free"] = {
27
- name: "DeepSeek R1 (Free)",
28
- description: "Free \u2014 reasoning with thinking support",
29
- free: true
30
- };
31
- models["qwen/qwen3-coder:free"] = {
32
- name: "Qwen3 Coder",
33
- description: "Free \u2014 480B parameters, excellent tool use",
34
- free: true
35
- };
36
- models["openrouter/auto"] = {
37
- name: "Auto (All)",
38
- description: "Auto-selects best model (requires credits)",
39
- free: false
40
- };
41
- models["anthropic/claude-sonnet-4"] = {
42
- name: "Claude Sonnet 4",
43
- description: "Premium \u2014 excellent quality + reasoning (requires credits)",
44
- free: false
45
- };
46
- models["google/gemini-2.5-flash-preview"] = {
47
- name: "Gemini 2.5 Flash",
48
- description: "Premium \u2014 fast with thinking (requires credits)",
49
- free: false
50
- };
51
- models["ollama/llama3"] = {
52
- name: "Llama 3 (Ollama)",
53
- description: "Local \u2014 Meta's Llama 3, requires Ollama",
54
- free: true
55
- };
56
- models["ollama/gemma3"] = {
57
- name: "Gemma 3 (Ollama)",
58
- description: "Local \u2014 Google's Gemma 3, requires Ollama",
59
- free: true
60
- };
61
- models["ollama/mistral"] = {
62
- name: "Mistral (Ollama)",
63
- description: "Local \u2014 Mistral's 7B model, requires Ollama",
64
- free: true
65
- };
66
- models["ollama/qwen3"] = {
67
- name: "Qwen 3 (Ollama)",
68
- description: "Local \u2014 Alibaba's Qwen 3, requires Ollama",
69
- free: true
70
- };
71
- models["ollama/deepseek-r1"] = {
72
- name: "DeepSeek R1 (Ollama)",
73
- description: "Local \u2014 reasoning model, requires Ollama",
74
- free: true
75
- };
76
- return models;
77
- }
78
- var MODELS = buildModels();
79
- var DEFAULT_MODEL_ID = "openrouter/free";
80
- var DEFAULT_MODEL = DEFAULT_MODEL_ID;
81
- var THINKING_MODELS = /* @__PURE__ */ new Set([
82
- "anthropic/claude-sonnet-4",
83
- "deepseek/deepseek-r1:free",
84
- "google/gemini-2.5-flash-preview",
85
- "ollama/deepseek-r1"
86
- ]);
87
- function supportsThinking(model) {
88
- return THINKING_MODELS.has(model);
89
- }
90
- function isOllamaModel(model) {
91
- return model.startsWith("ollama/");
92
- }
93
- function getModelsByProvider(provider) {
94
- return Object.keys(MODELS).filter(
95
- (id) => id.startsWith(`${provider}/`)
96
- );
97
- }
98
-
99
- export {
100
- getModelsForUI,
101
- MODELS,
102
- DEFAULT_MODEL_ID,
103
- DEFAULT_MODEL,
104
- THINKING_MODELS,
105
- supportsThinking,
106
- isOllamaModel,
107
- getModelsByProvider
108
- };
109
- //# sourceMappingURL=chunk-ECRY7XDR.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/models.ts"],"sourcesContent":["/**\n * Origen model configuration.\n *\n * Delegates to pi-ai's model registry for known providers (OpenRouter, Anthropic, Google, etc.)\n * Plus custom entries for Ollama and free-tier aliases.\n */\n\nimport { getModel } from \"@mariozechner/pi-ai\";\nimport type { Model, Api } from \"@mariozechner/pi-ai\";\nexport type { Model as ProviderModel, Api } from \"@mariozechner/pi-ai\";\n\n// ── Model registry ────────────────────────────────────────────────────\n\nexport interface ModelConfig {\n name: string;\n description: string;\n free: boolean;\n}\n\n/** UI-facing model config — safe to send to the client. Strips internal fields. */\nexport type UIModelConfig = ModelConfig;\n\n/** Get models as a simple UI map (name, description, free). No internal fields. */\nexport function getModelsForUI(): Record<string, UIModelConfig> {\n const uiModels: Record<string, UIModelConfig> = {};\n for (const [id, config] of Object.entries(MODELS)) {\n uiModels[id] = { name: config.name, description: config.description, free: config.free };\n }\n return uiModels;\n}\n\n// Build MODELS map from pi-ai registry + custom entries\nfunction buildModels(): Record<string, ModelConfig> {\n const models: Record<string, ModelConfig> = {};\n\n // ── OpenRouter (free tier) ───────────────────────────\n models[\"openrouter/free\"] = {\n name: \"Free (Auto)\",\n description: \"Free — auto-selects best free model for your request\",\n free: true,\n };\n models[\"google/gemma-4-31b-it:free\"] = {\n name: \"Gemma 4 31B\",\n description: \"Free — great quality for Bible study\",\n free: true,\n };\n models[\"nvidia/nemotron-3-super-120b-a12b:free\"] = {\n name: \"Nemotron 3 Super\",\n description: \"Free — large model, strong reasoning\",\n free: true,\n };\n models[\"deepseek/deepseek-r1:free\"] = {\n name: \"DeepSeek R1 (Free)\",\n description: \"Free — reasoning with thinking support\",\n free: true,\n };\n\n models[\"qwen/qwen3-coder:free\"] = {\n name: \"Qwen3 Coder\",\n description: \"Free — 480B parameters, excellent tool use\",\n free: true,\n };\n\n // ── OpenRouter (premium) ─────────────────────────────\n models[\"openrouter/auto\"] = {\n name: \"Auto (All)\",\n description: \"Auto-selects best model (requires credits)\",\n free: false,\n };\n models[\"anthropic/claude-sonnet-4\"] = {\n name: \"Claude Sonnet 4\",\n description: \"Premium — excellent quality + reasoning (requires credits)\",\n free: false,\n };\n models[\"google/gemini-2.5-flash-preview\"] = {\n name: \"Gemini 2.5 Flash\",\n description: \"Premium — fast with thinking (requires credits)\",\n free: false,\n };\n\n // ── Ollama (local, always free) ──────────────────────\n models[\"ollama/llama3\"] = {\n name: \"Llama 3 (Ollama)\",\n description: \"Local — Meta's Llama 3, requires Ollama\",\n free: true,\n };\n models[\"ollama/gemma3\"] = {\n name: \"Gemma 3 (Ollama)\",\n description: \"Local — Google's Gemma 3, requires Ollama\",\n free: true,\n };\n models[\"ollama/mistral\"] = {\n name: \"Mistral (Ollama)\",\n description: \"Local — Mistral's 7B model, requires Ollama\",\n free: true,\n };\n models[\"ollama/qwen3\"] = {\n name: \"Qwen 3 (Ollama)\",\n description: \"Local — Alibaba's Qwen 3, requires Ollama\",\n free: true,\n };\n models[\"ollama/deepseek-r1\"] = {\n name: \"DeepSeek R1 (Ollama)\",\n description: \"Local — reasoning model, requires Ollama\",\n free: true,\n };\n\n return models;\n}\n\nexport const MODELS: Record<string, ModelConfig> = buildModels();\nexport type ModelId = keyof typeof MODELS;\n\n/** Default model — free router, works with $0 credits */\nexport const DEFAULT_MODEL_ID: ModelId = \"openrouter/free\";\n\n/** Backward compat alias */\nexport const DEFAULT_MODEL: ModelId = DEFAULT_MODEL_ID;\n\n/** Models that support extended thinking */\nexport const THINKING_MODELS: ReadonlySet<ModelId> = new Set<ModelId>([\n \"anthropic/claude-sonnet-4\",\n \"deepseek/deepseek-r1:free\",\n \"google/gemini-2.5-flash-preview\",\n \"ollama/deepseek-r1\",\n]);\n\n/** Check if a model supports extended thinking */\nexport function supportsThinking(model: ModelId): boolean {\n return THINKING_MODELS.has(model);\n}\n\n/** Check if a model is an Ollama model */\nexport function isOllamaModel(model: ModelId): boolean {\n return (model as string).startsWith(\"ollama/\");\n}\n\n/** Get all model IDs for a specific provider prefix */\nexport function getModelsByProvider(provider: string): ModelId[] {\n return (Object.keys(MODELS) as ModelId[]).filter((id) =>\n (id as string).startsWith(`${provider}/`)\n );\n}"],"mappings":";AAuBO,SAAS,iBAAgD;AAC9D,QAAM,WAA0C,CAAC;AACjD,aAAW,CAAC,IAAI,MAAM,KAAK,OAAO,QAAQ,MAAM,GAAG;AACjD,aAAS,EAAE,IAAI,EAAE,MAAM,OAAO,MAAM,aAAa,OAAO,aAAa,MAAM,OAAO,KAAK;AAAA,EACzF;AACA,SAAO;AACT;AAGA,SAAS,cAA2C;AAClD,QAAM,SAAsC,CAAC;AAG7C,SAAO,iBAAiB,IAAI;AAAA,IAC1B,MAAM;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,EACR;AACA,SAAO,4BAA4B,IAAI;AAAA,IACrC,MAAM;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,EACR;AACA,SAAO,wCAAwC,IAAI;AAAA,IACjD,MAAM;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,EACR;AACA,SAAO,2BAA2B,IAAI;AAAA,IACpC,MAAM;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,EACR;AAEA,SAAO,uBAAuB,IAAI;AAAA,IAChC,MAAM;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,EACR;AAGA,SAAO,iBAAiB,IAAI;AAAA,IAC1B,MAAM;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,EACR;AACA,SAAO,2BAA2B,IAAI;AAAA,IACpC,MAAM;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,EACR;AACA,SAAO,iCAAiC,IAAI;AAAA,IAC1C,MAAM;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,EACR;AAGA,SAAO,eAAe,IAAI;AAAA,IACxB,MAAM;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,EACR;AACA,SAAO,eAAe,IAAI;AAAA,IACxB,MAAM;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,EACR;AACA,SAAO,gBAAgB,IAAI;AAAA,IACzB,MAAM;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,EACR;AACA,SAAO,cAAc,IAAI;AAAA,IACvB,MAAM;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,EACR;AACA,SAAO,oBAAoB,IAAI;AAAA,IAC7B,MAAM;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,EACR;AAEA,SAAO;AACT;AAEO,IAAM,SAAsC,YAAY;AAIxD,IAAM,mBAA4B;AAGlC,IAAM,gBAAyB;AAG/B,IAAM,kBAAwC,oBAAI,IAAa;AAAA,EACpE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAGM,SAAS,iBAAiB,OAAyB;AACxD,SAAO,gBAAgB,IAAI,KAAK;AAClC;AAGO,SAAS,cAAc,OAAyB;AACrD,SAAQ,MAAiB,WAAW,SAAS;AAC/C;AAGO,SAAS,oBAAoB,UAA6B;AAC/D,SAAQ,OAAO,KAAK,MAAM,EAAgB;AAAA,IAAO,CAAC,OAC/C,GAAc,WAAW,GAAG,QAAQ,GAAG;AAAA,EAC1C;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/adapter.ts"],"sourcesContent":["/**\n * Adapter: bridges Origen's simple types to pi-agent-core/pi-ai types.\n *\n * - OrigenTool → AgentTool (injects D1Provider)\n * - pi-ai Model resolution (OpenRouter, Ollama, Anthropic, Google)\n * - StreamEvent translation (AgentEvent → Origen's StreamEvent)\n */\n\nimport { getModel } from \"@mariozechner/pi-ai\";\nimport type { Model, Api, Message, Context, Tool } from \"@mariozechner/pi-ai\";\nimport type { AgentTool, AgentEvent, AgentMessage } from \"@mariozechner/pi-agent-core\";\nimport type { OrigenTool, StreamEvent } from \"./agent\";\nimport type { D1Provider, Citation, UsageInfo } from \"./types\";\n\n// ── Tool adapter ─────────────────────────────────────────────────────\n\n/**\n * Convert an OrigenTool into a pi-agent-core AgentTool.\n * The D1Provider is captured in closure so the tool's execute gets it.\n */\nexport function adaptTool(tool: OrigenTool, getD1: D1Provider): AgentTool {\n return {\n name: tool.name,\n description: tool.description,\n // Convert JSON schema to TypeBox format — pi-agent-core uses TypeBox\n // but accepts plain JSON schemas for the tool definition sent to the LLM.\n // We provide parameters as a TypeBox-like schema.\n parameters: {\n type: \"object\",\n ...tool.parameters,\n } as any,\n label: tool.name,\n execute: async (_toolCallId, params, _signal) => {\n const result = await tool.execute(params as Record<string, unknown>, getD1);\n return {\n content: [{ type: \"text\" as const, text: result }],\n details: {},\n };\n },\n };\n}\n\n/** Adapt all OrigenTools for an Agent instance. */\nexport function adaptTools(tools: OrigenTool[], getD1: D1Provider): AgentTool[] {\n return tools.map((t) => adaptTool(t, getD1));\n}\n\n// ── Model resolution ──────────────────────────────────────────────────\n\nexport interface ModelResolutionOptions {\n /** Ollama base URL, e.g. \"http://localhost:11434/v1\" */\n ollamaBaseUrl?: string;\n}\n\n/** Known Ollama models that don't exist in pi-ai's generated registry. */\nconst OLLAMA_MODELS: Record<string, Partial<Model<Api>>> = {\n \"ollama/llama3\": {\n id: \"llama3\",\n name: \"Llama 3 (Ollama)\",\n api: \"openai-completions\",\n provider: \"ollama\",\n baseUrl: \"http://localhost:11434/v1\",\n reasoning: false,\n input: [\"text\"],\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: 8192,\n maxTokens: 4096,\n },\n \"ollama/gemma3\": {\n id: \"gemma3\",\n name: \"Gemma 3 (Ollama)\",\n api: \"openai-completions\",\n provider: \"ollama\",\n baseUrl: \"http://localhost:11434/v1\",\n reasoning: false,\n input: [\"text\"],\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: 8192,\n maxTokens: 4096,\n },\n \"ollama/mistral\": {\n id: \"mistral\",\n name: \"Mistral (Ollama)\",\n api: \"openai-completions\",\n provider: \"ollama\",\n baseUrl: \"http://localhost:11434/v1\",\n reasoning: false,\n input: [\"text\"],\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: 32768,\n maxTokens: 4096,\n },\n \"ollama/qwen3\": {\n id: \"qwen3\",\n name: \"Qwen 3 (Ollama)\",\n api: \"openai-completions\",\n provider: \"ollama\",\n baseUrl: \"http://localhost:11434/v1\",\n reasoning: false,\n input: [\"text\"],\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: 32768,\n maxTokens: 4096,\n },\n \"ollama/deepseek-r1\": {\n id: \"deepseek-r1\",\n name: \"DeepSeek R1 (Ollama)\",\n api: \"openai-completions\",\n provider: \"ollama\",\n baseUrl: \"http://localhost:11434/v1\",\n reasoning: true,\n input: [\"text\"],\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: 65536,\n maxTokens: 8192,\n },\n};\n\nconst DEFAULT_MODEL: Model<Api> = {\n id: \"openrouter/free\",\n name: \"Free (Auto)\",\n api: \"openai-completions\",\n provider: \"openrouter\",\n baseUrl: \"https://openrouter.ai/api/v1\",\n reasoning: false,\n input: [\"text\"],\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: 128000,\n maxTokens: 4096,\n};\n\n/**\n * Resolve a model ID string to a pi-ai Model object.\n * Tries pi-ai's registry first, then falls back to built-in Ollama definitions.\n */\nexport function resolveModel(modelId: string, options?: ModelResolutionOptions): Model<Api> {\n // Try Ollama models first\n if (modelId.startsWith(\"ollama/\")) {\n const ollamaDef = OLLAMA_MODELS[modelId];\n if (ollamaDef) {\n const baseUrl = options?.ollamaBaseUrl ?? ollamaDef.baseUrl ?? \"http://localhost:11434/v1\";\n return {\n ...DEFAULT_MODEL,\n ...ollamaDef,\n baseUrl,\n compat: {\n supportsStore: false,\n supportsDeveloperRole: false,\n supportsReasoningEffort: false,\n supportsUsageInStreaming: false,\n maxTokensField: \"max_tokens\",\n requiresToolResultName: false,\n requiresAssistantAfterToolResult: false,\n requiresThinkingAsText: true,\n requiresReasoningContentOnAssistantMessages: false,\n thinkingFormat: \"openai\",\n supportsStrictMode: false,\n supportsLongCacheRetention: false,\n },\n } as Model<Api>;\n }\n // Generic Ollama model: user typed a custom model name\n const customId = modelId.replace(\"ollama/\", \"\");\n return {\n ...DEFAULT_MODEL,\n id: customId,\n name: `${customId} (Ollama)`,\n provider: \"ollama\",\n baseUrl: options?.ollamaBaseUrl ?? \"http://localhost:11434/v1\",\n compat: {\n supportsStore: false,\n supportsDeveloperRole: false,\n supportsReasoningEffort: false,\n supportsUsageInStreaming: false,\n maxTokensField: \"max_tokens\",\n requiresToolResultName: false,\n requiresAssistantAfterToolResult: false,\n requiresThinkingAsText: true,\n requiresReasoningContentOnAssistantMessages: false,\n thinkingFormat: \"openai\",\n supportsStrictMode: false,\n supportsLongCacheRetention: false,\n },\n } as Model<Api>;\n }\n\n // Try pi-ai's model registry (OpenRouter, Anthropic, Google, etc.)\n // pi-ai groups by provider, so we try known providers\n const providers = [\"openrouter\", \"anthropic\", \"google\", \"openai\", \"deepseek\", \"groq\", \"xai\"];\n for (const provider of providers) {\n try {\n const model = getModel(provider as any, modelId as any);\n if (model) return model as Model<Api>;\n } catch {\n // Not found in this provider, try next\n }\n }\n\n // Fallback: create a generic OpenRouter-compatible model\n return {\n ...DEFAULT_MODEL,\n id: modelId,\n name: modelId,\n };\n}\n\n// ── Message conversion ────────────────────────────────────────────────\n\n/** Convert Origen's simple messages to pi-ai Message format. */\nexport function convertMessages(\n messages: Array<{ role: \"user\" | \"assistant\"; content: string }>\n): Message[] {\n return messages.map((m) => ({\n role: m.role,\n content: m.content as any,\n timestamp: Date.now(),\n })) as Message[];\n}\n\n// ── Context builder ───────────────────────────────────────────────────\n\n/** Build a pi-ai Context from Origen's config. */\nexport function buildContext(\n systemPrompt: string,\n messages: Message[],\n adaptedTools: AgentTool[]\n): Context {\n return {\n systemPrompt,\n messages,\n tools: adaptedTools.map((t) => ({\n name: t.name,\n description: t.description,\n parameters: t.parameters,\n })),\n };\n}\n\n// ── Event translation ─────────────────────────────────────────────────\n\n/** Default citation extractor — [BOOK CHAPTER:VERSE] patterns. */\nfunction defaultCitationExtractor(text: string): Citation[] {\n const citations: Citation[] = [];\n const regex = /\\[([A-Z]{3})\\s+(\\d+):(\\d+)\\]/g;\n let match;\n while ((match = regex.exec(text)) !== null) {\n citations.push({ book: match[1], chapter: parseInt(match[2]), verse: parseInt(match[3]) });\n }\n return citations;\n}\n\n/** Translate a pi-agent-core AgentEvent into an Origen StreamEvent. */\nexport function translateEvent(\n event: AgentEvent,\n extractCitations?: (text: string) => Citation[]\n): StreamEvent | null {\n switch (event.type) {\n case \"message_update\": {\n const assistantEvent = event.assistantMessageEvent;\n if (assistantEvent.type === \"text_delta\") {\n return { type: \"text\" as const, content: assistantEvent.delta };\n }\n if (assistantEvent.type === \"thinking_delta\") {\n return { type: \"reasoning\" as const, content: assistantEvent.delta };\n }\n return null;\n }\n case \"tool_execution_start\": {\n return {\n type: \"tool_call\" as const,\n name: event.toolName,\n args: event.args as Record<string, unknown>,\n };\n }\n case \"tool_execution_end\": {\n const resultText = event.result?.content\n ?.filter((c: any) => c.type === \"text\")\n .map((c: any) => c.text)\n .join(\"\\n\") ?? \"\";\n return {\n type: \"tool_result\" as const,\n name: event.toolName,\n result: resultText,\n };\n }\n case \"agent_end\": {\n // Find the final assistant message\n const assistantMsg = event.messages\n .filter((m): m is any => m.role === \"assistant\")\n .pop();\n const text = assistantMsg?.content\n ?.filter((c: any) => c.type === \"text\")\n .map((c: any) => c.text)\n .join(\"\") ?? \"\";\n const usage: UsageInfo | undefined = assistantMsg?.usage\n ? {\n promptTokens: assistantMsg.usage.input,\n completionTokens: assistantMsg.usage.output,\n totalCost: assistantMsg.usage.cost?.total,\n }\n : undefined;\n const citFn = extractCitations ?? defaultCitationExtractor;\n // Check for error\n if (assistantMsg?.stopReason === \"error\" || assistantMsg?.stopReason === \"aborted\") {\n return {\n type: \"error\" as const,\n message: assistantMsg.errorMessage ?? \"Agent encountered an error\",\n };\n }\n return {\n type: \"done\" as const,\n message: text,\n citations: citFn(text),\n usage,\n };\n }\n default:\n return null;\n }\n}\n\n/**\n * Eagerly subscribe to an Agent and return an async iterable of Origen StreamEvents.\n *\n * CRITICAL: The subscription is created synchronously when this function is called,\n * BEFORE agent.prompt() starts. This avoids the race condition where events\n * emitted during prompt() are missed if subscription happens after.\n *\n * Usage:\n * const { stream, unsubscribe } = createEventStream(agent, extractCitations);\n * agent.prompt(messages); // events flow into stream via active subscription\n * for await (const event of stream) { ... }\n */\nexport function createEventStream(\n agent: any, // Agent from pi-agent-core\n extractCitations?: (text: string) => Citation[]\n): {\n stream: AsyncGenerator<StreamEvent>;\n unsubscribe: () => void;\n} {\n const queue: StreamEvent[] = [];\n let resolve: (() => void) | null = null;\n let done = false;\n\n // Subscribe IMMEDIATELY (before prompt is called)\n const unsubscribe = agent.subscribe((event: AgentEvent) => {\n const translated = translateEvent(event, extractCitations);\n if (translated) {\n queue.push(translated);\n if (resolve) {\n resolve();\n resolve = null;\n }\n }\n if (event.type === \"agent_end\") {\n done = true;\n if (resolve) {\n resolve();\n resolve = null;\n }\n }\n });\n\n async function* stream(): AsyncGenerator<StreamEvent> {\n try {\n while (!done || queue.length > 0) {\n if (queue.length > 0) {\n yield queue.shift()!;\n continue;\n }\n if (done) break;\n await new Promise<void>((r) => { resolve = r; });\n }\n } finally {\n unsubscribe();\n }\n }\n\n return { stream: stream(), unsubscribe };\n}\n\n/**\n * Subscribe to an Agent and yield Origen StreamEvents.\n * Handles the full lifecycle from agent_start to agent_end.\n *\n * @deprecated Use createEventStream() instead to avoid race conditions.\n * This function subscribes lazily (on first iteration) which can miss events\n * if the agent has already started emitting.\n */\nexport async function* agentToStreamEvents(\n agent: any,\n extractCitations?: (text: string) => Citation[]\n): AsyncGenerator<StreamEvent> {\n yield* createEventStream(agent, extractCitations).stream;\n}"],"mappings":";AAQA,SAAS,gBAAgB;AAYlB,SAAS,UAAU,MAAkB,OAA8B;AACxE,SAAO;AAAA,IACL,MAAM,KAAK;AAAA,IACX,aAAa,KAAK;AAAA;AAAA;AAAA;AAAA,IAIlB,YAAY;AAAA,MACV,MAAM;AAAA,MACN,GAAG,KAAK;AAAA,IACV;AAAA,IACA,OAAO,KAAK;AAAA,IACZ,SAAS,OAAO,aAAa,QAAQ,YAAY;AAC/C,YAAM,SAAS,MAAM,KAAK,QAAQ,QAAmC,KAAK;AAC1E,aAAO;AAAA,QACL,SAAS,CAAC,EAAE,MAAM,QAAiB,MAAM,OAAO,CAAC;AAAA,QACjD,SAAS,CAAC;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AACF;AAGO,SAAS,WAAW,OAAqB,OAAgC;AAC9E,SAAO,MAAM,IAAI,CAAC,MAAM,UAAU,GAAG,KAAK,CAAC;AAC7C;AAUA,IAAM,gBAAqD;AAAA,EACzD,iBAAiB;AAAA,IACf,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,KAAK;AAAA,IACL,UAAU;AAAA,IACV,SAAS;AAAA,IACT,WAAW;AAAA,IACX,OAAO,CAAC,MAAM;AAAA,IACd,MAAM,EAAE,OAAO,GAAG,QAAQ,GAAG,WAAW,GAAG,YAAY,EAAE;AAAA,IACzD,eAAe;AAAA,IACf,WAAW;AAAA,EACb;AAAA,EACA,iBAAiB;AAAA,IACf,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,KA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