juneau 0.7.0 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1051 -1006
- package/dist/components/AiMessageBubble/AiMessageBubble.d.ts.map +1 -1
- package/dist/index.cjs +23 -23
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +469 -445
- package/dist/index.js.map +1 -1
- package/dist/server/createSkillSet.d.ts.map +1 -1
- package/dist/server/index.cjs +16 -9
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.ts +3 -2
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +228 -146
- package/dist/server/index.js.map +1 -1
- package/dist/server/skillIndex.d.ts +20 -4
- package/dist/server/skillIndex.d.ts.map +1 -1
- package/dist/server/types.d.ts +43 -0
- package/dist/server/types.d.ts.map +1 -1
- package/dist/server/withSkillDispatch.d.ts +24 -0
- package/dist/server/withSkillDispatch.d.ts.map +1 -0
- package/dist/style.css +1 -1
- package/package.json +86 -86
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createSkillSet.d.ts","sourceRoot":"","sources":["../../src/server/createSkillSet.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,KAAK,CAAC;AACnC,OAAO,KAAK,EAAE,eAAe,EAAuB,QAAQ,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE/F,KAAK,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,CAAC,CAAC;AAwCzD,wBAAgB,cAAc,CAAC,MAAM,EAAE,QAAQ,EAAE,OAAO,GAAE,eAAoB,GAAG,QAAQ,
|
|
1
|
+
{"version":3,"file":"createSkillSet.d.ts","sourceRoot":"","sources":["../../src/server/createSkillSet.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,KAAK,CAAC;AACnC,OAAO,KAAK,EAAE,eAAe,EAAuB,QAAQ,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE/F,KAAK,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,CAAC,CAAC;AAwCzD,wBAAgB,cAAc,CAAC,MAAM,EAAE,QAAQ,EAAE,OAAO,GAAE,eAAoB,GAAG,QAAQ,CAwIxF"}
|
package/dist/server/index.cjs
CHANGED
|
@@ -1,16 +1,23 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function E(n){const e=n.map(t=>{const r=t.parts.filter(s=>s.type==="text").map(s=>s.text).join("");return{role:t.role,content:r}}),i=[];for(let t=0;t<e.length;t++){const r=e[t],s=i[i.length-1];r.role==="user"&&s?.role==="user"&&i.push({role:"assistant",content:"…"}),i.push(r)}return i.filter(t=>t.content.length>0)}function y(n){return`data: ${JSON.stringify(n)}
|
|
2
2
|
|
|
3
|
-
`}function
|
|
4
|
-
`)}function
|
|
3
|
+
`}function w(n,e){return n[e]??n.en}function R(n){const e=new Set(Object.keys(n));for(const[i,t]of Object.entries(n))if(t.tools){for(const r of t.tools)if(!e.has(r))throw new Error(`[juneau] createSkillSet: skill "${i}" references unknown tool "${r}". Known skills: ${[...e].join(", ")}`)}}function W(n,e={}){R(n);const i=e.language??"en",t=e.debug??!1,r=[],s=[],o=[];let c=!1,d=null;const g=new Map,u=new Map;for(const[l,f]of Object.entries(n)){if(g.has(f.id))throw new Error(`[juneau] createSkillSet: skills "${u.get(f.id)}" and "${l}" share the same ID (${f.id}). IDs must be unique.`);g.set(f.id,f),u.set(f.id,l)}const a={};for(const[l,f]of Object.entries(n))a[l]={description:f.description,parameters:f.input,execute:async b=>{s.includes(l)||(s.push(l),o.push(f.id)),t&&console.debug(`[juneau] skill "${l}" → executing, input:`,b);const x=t?Date.now():0;r.push(y({type:"activity",id:l,title:w(f.labels.running,i),status:"running",metadata:{skill:l}}));const I={emit:h=>{t&&console.debug(`[juneau] skill "${l}" → emitting part "${h.type}"`),r.push(y({type:"part",part:h}))}};try{const h=await f.execute(b,I),m=t?Date.now()-x:0;return t&&console.debug(`[juneau] skill "${l}" → done in ${m}ms, result:`,h),r.push(y({type:"activity",id:l,title:w(f.labels.done,i),status:"done",metadata:{skill:l}})),h}catch(h){const m=t?Date.now()-x:0,$=h instanceof Error?h.message:String(h);t&&console.debug(`[juneau] skill "${l}" → FAILED in ${m}ms: "${$}"`);const A=f.labels.failed??{cs:"Nepodařilo se",en:"Failed"};throw r.push(y({type:"activity",id:l,title:w(A,i),status:"failed",metadata:{skill:l}})),c=!0,d=`Tool "${l}" failed: ${$}`,h}}};return{tools:a,skills:n,calledSkillNames:s,calledSkillIds:o,skillsById:g,drainActivities(){return r.splice(0,r.length)},get hadFailure(){return c},get failureContext(){return d}}}function F(n){return Object.entries(n.skills).map(([e,i])=>{const t=[i.readOnly===!1?"write":"read"];return i.requiresConfirmation&&t.push("requires confirmation"),`${`[${i.id}] `}${e} (${t.join(", ")}): ${i.description}`}).join(`
|
|
4
|
+
`)}function J(n,e){return e.map(i=>n.skills[i]).filter(i=>i?.instructions).map(i=>i.instructions).join(`
|
|
5
5
|
|
|
6
|
-
`)}
|
|
6
|
+
`)}function O(n,e){return e.map(i=>n.skillsById.get(i)).filter(i=>i?.instructions).map(i=>i.instructions).join(`
|
|
7
7
|
|
|
8
|
-
`)}
|
|
8
|
+
`)}const j=new Set(["text-delta","text"]),M=new Set(["tool-call","tool-result","tool-input-start","tool-input-delta","tool-input-available","tool-output-available","step-start","finish-step","start","finish","response-metadata","stream-start"]);async function*p(n,e,i){const t=i?.debug??!1;for await(const r of n){const s=r,o=s.type;if(t)if(o&&j.has(o)){const c=s.text??s.textDelta;console.debug(`[juneau] streamToWire chunk: ${o} ${JSON.stringify(c??"")}`)}else o==="tool-call"?console.debug(`[juneau] streamToWire chunk: tool-call "${s.toolName??s.name??"?"}"`):o==="tool-result"?console.debug("[juneau] streamToWire chunk: tool-result (ignored)"):o&&(M.has(o)?console.debug(`[juneau] streamToWire chunk: ${o} (ignored)`):console.debug(`[juneau] streamToWire chunk: ${o} (unknown)`));if(o&&j.has(o)){if(e){const d=e.drainActivities();t&&d.length>0&&console.debug(`[juneau] streamToWire → draining ${d.length} activities`);for(const g of d)yield g}const c=s.text??s.textDelta;c&&(t&&console.debug(`[juneau] streamToWire → yielding text ${JSON.stringify(c)}`),yield`data: ${JSON.stringify({type:"text",text:c})}
|
|
9
9
|
|
|
10
|
-
`}
|
|
10
|
+
`)}}if(e){const r=e.drainActivities();t&&r.length>0&&console.debug(`[juneau] streamToWire → draining ${r.length} activities (end of stream)`);for(const s of r)yield s}t&&console.debug("[juneau] streamToWire → end of stream, emitting done"),yield`data: ${JSON.stringify({type:"done"})}
|
|
11
11
|
|
|
12
|
-
`}function
|
|
12
|
+
`}function v(n){return`data: ${JSON.stringify({type:"error",message:n})}
|
|
13
13
|
|
|
14
|
-
`}function
|
|
15
|
-
|
|
14
|
+
`}function S(){return`data: ${JSON.stringify({type:"done"})}
|
|
15
|
+
|
|
16
|
+
`}function k(n){let e="";for(const i of n.split(`
|
|
17
|
+
`))if(i.startsWith("data: "))try{const t=JSON.parse(i.slice(6));t.type==="text"&&typeof t.text=="string"&&(e+=t.text)}catch{}return e}async function*P(n){const{phase1:e,phase2:i,phase3:t,skillSet:r,onFinish:s,debug:o=!1}=n;o&&console.debug("[juneau] withToolRecovery → phase 1 start");let c=!1,d="";const g=e();for await(const u of p(g.fullStream,r,{debug:o}))d+=k(u),u.includes('"type":"text"')&&(c=!0),!u.includes('"type":"done"')&&(yield u);if(o&&console.debug(`[juneau] withToolRecovery → phase 1 complete, textProduced=${c}, hadFailure=${r.hadFailure}`),r.hadFailure&&!c&&r.failureContext){o&&console.debug("[juneau] withToolRecovery → hadFailure=true, textProduced=false → triggering phase 2");try{const u=i(r.failureContext);for await(const a of p(u.fullStream,void 0,{debug:o}))d+=k(a),!a.includes('"type":"done"')&&(yield a);o&&console.debug("[juneau] withToolRecovery → phase 2 complete"),s?.({text:d}),yield S()}catch(u){const a=u instanceof Error?u.message:String(u);o&&console.debug(`[juneau] withToolRecovery → phase 2 FAILED: "${a}"`),yield v(a)}return}if(!c&&!r.hadFailure&&t){const u=await C(g);if(u){o&&(console.debug(`[juneau] withToolRecovery → phase 3 messages resolved (${u.length}):`,JSON.stringify(u,null,2)),L(u)||console.debug("[juneau] withToolRecovery → WARNING: resolved history contains no tool-result turn — Gemini will likely reject it as an invalid conversation structure"),console.debug("[juneau] withToolRecovery → no failure, no text → triggering phase 3"));try{for await(const a of p(t(u).fullStream,void 0,{debug:o}))d+=k(a),!a.includes('"type":"done"')&&(yield a);o&&console.debug("[juneau] withToolRecovery → phase 3 complete"),s?.({text:d}),yield S()}catch(a){const l=a instanceof Error?a.message:String(a);o&&console.debug(`[juneau] withToolRecovery → phase 3 FAILED: "${l}"`),yield v(l)}return}o&&console.debug("[juneau] withToolRecovery → phase 3 configured but phase 1 result exposes no message history — emitting done")}else!c&&!r.hadFailure&&o&&console.debug("[juneau] withToolRecovery → no failure, no text, no phase3 — emitting done (Gemini silent response)");s?.({text:d}),yield S()}async function C(n){if(n.messages){const e=await n.messages;if(Array.isArray(e)&&e.length>0)return e}if(n.response){const e=await n.response;if(Array.isArray(e?.messages)&&e.messages.length>0)return e.messages}return null}function L(n){return n.some(e=>{const i=e;return i.role==="tool"?!0:Array.isArray(i.content)?i.content.some(t=>t.type==="tool-result"):!1})}function T(n){return`data: ${JSON.stringify({type:"error",message:n})}
|
|
18
|
+
|
|
19
|
+
`}function D(){return`data: ${JSON.stringify({type:"done"})}
|
|
20
|
+
|
|
21
|
+
`}function N(n){let e="";for(const i of n.split(`
|
|
22
|
+
`))if(i.startsWith("data: "))try{const t=JSON.parse(i.slice(6));t.type==="text"&&typeof t.text=="string"&&(e+=t.text)}catch{}return e}async function B(n){if(n.messages){const e=await n.messages;if(Array.isArray(e)&&e.length>0)return e}if(n.response){const e=await n.response;if(Array.isArray(e?.messages)&&e.messages.length>0)return e.messages}return null}async function*G(n){const{phase1:e,phase2:i,skillSet:t,onFinish:r,debug:s=!1}=n;s&&console.debug("[juneau] withSkillDispatch → phase 1 start");let o="",c=!1;const d=e();for await(const a of p(d.fullStream,t,{debug:s}))o+=N(a),a.includes('"type":"text"')&&(c=!0),!a.includes('"type":"done"')&&(yield a);if(s&&console.debug(`[juneau] withSkillDispatch → phase 1 complete, calledSkillIds=[${t.calledSkillIds.join(", ")}], textProduced=${c}`),t.calledSkillIds.length===0){s&&console.debug("[juneau] withSkillDispatch → no skill called, emitting done"),r?.({text:o}),yield D();return}const g=await B(d);if(!g){s&&console.debug("[juneau] withSkillDispatch → could not resolve phase 1 history, emitting error"),yield T("withSkillDispatch: could not resolve phase 1 message history for phase 2");return}const u=O(t,t.calledSkillIds);s&&console.debug(`[juneau] withSkillDispatch → phase 2 start, instructions length=${u.length}, history turns=${g.length}`);try{for await(const a of p(i(u,g).fullStream,void 0,{debug:s}))o+=N(a),!a.includes('"type":"done"')&&(yield a);s&&console.debug("[juneau] withSkillDispatch → phase 2 complete"),r?.({text:o}),yield D()}catch(a){const l=a instanceof Error?a.message:String(a);s&&console.debug(`[juneau] withSkillDispatch → phase 2 FAILED: "${l}"`),yield T(l)}}exports.buildSkillIndex=F;exports.createSkillSet=W;exports.selectSkills=J;exports.selectSkillsById=O;exports.streamToWire=p;exports.toSdkMessages=E;exports.withSkillDispatch=G;exports.withToolRecovery=P;
|
|
16
23
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../../src/server/toSdkMessages.ts","../../src/server/createSkillSet.ts","../../src/server/skillIndex.ts","../../src/server/streamToWire.ts","../../src/server/withToolRecovery.ts"],"sourcesContent":["import type { AiMessage } from '../core/types';\r\nimport type { CoreMessage } from './types';\r\n\r\n/**\r\n * Converts Juneau's AiMessage[] to the CoreMessage[] format expected by\r\n * ai-sdk's generateText / streamText.\r\n *\r\n * - Extracts plain text from parts (joins all type: \"text\" parts)\r\n * - Replaces activity-only assistant messages with an empty assistant turn\r\n * so conversation alternation stays valid\r\n * - Injects a placeholder assistant turn between consecutive user messages\r\n * - Filters out empty turns (unless they are a required alternation filler)\r\n */\r\nexport function toSdkMessages(messages: AiMessage[]): CoreMessage[] {\r\n // First pass: map each AiMessage to a CoreMessage, replacing activity-only\r\n // assistant messages with an empty-text assistant turn.\r\n const mapped: CoreMessage[] = messages.map(msg => {\r\n const text = msg.parts\r\n .filter(p => p.type === 'text')\r\n .map(p => (p as { type: 'text'; text: string }).text)\r\n .join('');\r\n\r\n return { role: msg.role as CoreMessage['role'], content: text };\r\n });\r\n\r\n // Second pass: inject a placeholder assistant turn between consecutive user\r\n // messages as a safety net for history bugs that would cause model errors.\r\n const result: CoreMessage[] = [];\r\n for (let i = 0; i < mapped.length; i++) {\r\n const current = mapped[i];\r\n const prev = result[result.length - 1];\r\n\r\n if (current.role === 'user' && prev?.role === 'user') {\r\n result.push({ role: 'assistant', content: '…' });\r\n }\r\n\r\n result.push(current);\r\n }\r\n\r\n // Third pass: filter out empty turns, but keep assistant placeholders that\r\n // serve as alternation fillers (they have content '…' set above, so they\r\n // won't be filtered). Only drop genuinely empty content strings.\r\n return result.filter(msg => msg.content.length > 0);\r\n}\r\n","import type { ZodType } from 'zod';\nimport type { SkillDefinition, SkillExecuteContext, SkillSet, SkillSetOptions } from './types';\n\ntype SkillMap = Record<string, SkillDefinition<ZodType>>;\n\nfunction formatWireEvent(event: Record<string, unknown>): string {\n return `data: ${JSON.stringify(event)}\\n\\n`;\n}\n\nfunction pickLabel(labels: { cs: string; en: string }, language: string): string {\n return (labels as Record<string, string>)[language] ?? labels.en;\n}\n\n/**\n * Takes a map of skill definitions and returns a SkillSet containing:\n * - tools: ready-made tool definitions for ai-sdk's streamText({ tools })\n * - drainActivities(): flush buffered activity + part wire SSE strings\n * - hadFailure / failureContext: for driving tool failure recovery\n *\n * Each skill's execute fn receives a SkillExecuteContext as its second\n * argument with an `emit(part)` callback — parts are pushed into the same\n * buffer as activities and drained by streamToWire at the same points.\n */\n/**\n * Validates skill definitions at startup — throws immediately (not at runtime)\n * so a broken registry fails the server boot, not a user request.\n */\nfunction validateSkills(skills: SkillMap): void {\n const knownNames = new Set(Object.keys(skills));\n\n for (const [name, skill] of Object.entries(skills)) {\n if (!skill.tools) continue;\n for (const toolName of skill.tools) {\n if (!knownNames.has(toolName)) {\n throw new Error(\n `[juneau] createSkillSet: skill \"${name}\" references unknown tool \"${toolName}\". ` +\n `Known skills: ${[...knownNames].join(', ')}`\n );\n }\n }\n }\n}\n\nexport function createSkillSet(skills: SkillMap, options: SkillSetOptions = {}): SkillSet {\n validateSkills(skills);\n\n const language = options.language ?? 'en';\n const debug = options.debug ?? false;\n const activityBuffer: string[] = [];\n const calledSkillNames: string[] = [];\n let hadFailure = false;\n let failureContext: string | null = null;\n\n const tools: Record<string, unknown> = {};\n\n for (const [name, skill] of Object.entries(skills)) {\n tools[name] = {\n description: skill.description,\n parameters: skill.input,\n execute: async (input: unknown) => {\n if (!calledSkillNames.includes(name)) {\n calledSkillNames.push(name);\n }\n\n if (debug) {\n console.debug(`[juneau] skill \"${name}\" → executing, input:`, input);\n }\n\n const startMs = debug ? Date.now() : 0;\n\n // Emit a \"running\" activity event into the buffer\n activityBuffer.push(\n formatWireEvent({\n type: 'activity',\n id: name,\n title: pickLabel(skill.labels.running, language),\n status: 'running',\n metadata: { skill: name },\n })\n );\n\n const executeContext: SkillExecuteContext = {\n emit: (part) => {\n if (debug) {\n console.debug(`[juneau] skill \"${name}\" → emitting part \"${part.type}\"`);\n }\n activityBuffer.push(formatWireEvent({ type: 'part', part }));\n },\n };\n\n try {\n const result = await skill.execute(input as never, executeContext);\n\n const durationMs = debug ? Date.now() - startMs : 0;\n if (debug) {\n console.debug(`[juneau] skill \"${name}\" → done in ${durationMs}ms, result:`, result);\n }\n\n // Emit a \"done\" activity event\n activityBuffer.push(\n formatWireEvent({\n type: 'activity',\n id: name,\n title: pickLabel(skill.labels.done, language),\n status: 'done',\n metadata: { skill: name },\n })\n );\n\n return result;\n } catch (err) {\n const durationMs = debug ? Date.now() - startMs : 0;\n const message = err instanceof Error ? err.message : String(err);\n\n if (debug) {\n console.debug(`[juneau] skill \"${name}\" → FAILED in ${durationMs}ms: \"${message}\"`);\n }\n\n const failedLabels = skill.labels.failed ?? { cs: 'Nepodařilo se', en: 'Failed' };\n\n // Emit a \"failed\" activity event\n activityBuffer.push(\n formatWireEvent({\n type: 'activity',\n id: name,\n title: pickLabel(failedLabels, language),\n status: 'failed',\n metadata: { skill: name },\n })\n );\n\n hadFailure = true;\n failureContext = `Tool \"${name}\" failed: ${message}`;\n\n // Re-throw so ai-sdk knows the tool call failed\n throw err;\n }\n },\n };\n }\n\n return {\n tools,\n\n skills,\n\n calledSkillNames,\n\n drainActivities(): string[] {\n return activityBuffer.splice(0, activityBuffer.length);\n },\n\n get hadFailure() {\n return hadFailure;\n },\n\n get failureContext() {\n return failureContext;\n },\n };\n}\n","import type { SkillSet } from './types';\n\n/**\n * Builds a compact one-liner-per-skill index for the system prompt.\n * Inject the output into your system prompt instead of hand-maintaining a\n * skill list — adding a skill to the registry updates the index automatically.\n *\n * Output format:\n * - invoiceSearch (read): Find invoices by number, supplier, date, or status.\n * - invoiceApprove (write, requires confirmation): Approve an invoice.\n */\nexport function buildSkillIndex(skillSet: SkillSet): string {\n return Object.entries(skillSet.skills)\n .map(([name, skill]) => {\n const traits: string[] = [skill.readOnly === false ? 'write' : 'read'];\n if (skill.requiresConfirmation) {\n traits.push('requires confirmation');\n }\n return `- ${name} (${traits.join(', ')}): ${skill.description}`;\n })\n .join('\\n');\n}\n\n/**\n * Returns the concatenated workflow instructions for the given skill names —\n * typically skillSet.calledSkillNames after phase 1. Skills without\n * instructions and unknown names are skipped. Returns '' when nothing matches.\n *\n * This is the lazy-loading half of the skill format: full instructions enter\n * the prompt only for skills the model actually used.\n *\n * @example\n * const instructions = selectSkills(skillSet, skillSet.calledSkillNames);\n * // → inject into phase 3's system prompt as additional context\n */\nexport function selectSkills(skillSet: SkillSet, skillNames: string[]): string {\n return skillNames\n .map(name => skillSet.skills[name])\n .filter(skill => skill?.instructions)\n .map(skill => skill.instructions as string)\n .join('\\n\\n');\n}\n","import type { SkillSet, StreamToWireOptions } from './types';\n\n// ai-sdk v7 chunk types that carry the model's text output.\n// - 'text-delta': standard streaming text (v6 + v7)\n// - 'text': emitted by some v7 model/provider combos as a completed text chunk\n// Both may appear in the same stream; we handle either.\nconst TEXT_CHUNK_TYPES = new Set(['text-delta', 'text']);\n\n// Chunk types we recognise but intentionally ignore — activities are driven by\n// the SkillSet execute fn, not by these wire events.\nconst IGNORED_CHUNK_TYPES = new Set([\n 'tool-call',\n 'tool-result',\n 'tool-input-start',\n 'tool-input-delta',\n 'tool-input-available',\n 'tool-output-available',\n 'step-start',\n 'finish-step',\n 'start',\n 'finish',\n 'response-metadata',\n 'stream-start',\n]);\n\n/**\n * Converts ai-sdk's fullStream AsyncIterable into Juneau wire SSE strings.\n *\n * Handles:\n * - All text chunk types used by ai-sdk v7 (text-delta, text) incl. v6 textDelta fallback\n * - Flushing skillSet.drainActivities() before each text chunk so activities\n * always appear before the text they precede\n * - A final drain after the loop ends (catches last-tool-call activities when\n * no text follows the tool result — the Gemini silent-response scenario)\n * - Emitting the done event when the stream finishes\n * - Structured debug logging of every chunk when options.debug is true\n */\nexport async function* streamToWire(\n fullStream: AsyncIterable<unknown>,\n skillSet?: SkillSet,\n options?: StreamToWireOptions\n): AsyncIterable<string> {\n const debug = options?.debug ?? false;\n\n for await (const chunk of fullStream) {\n const c = chunk as Record<string, unknown>;\n const type = c.type as string | undefined;\n\n if (debug) {\n if (type && TEXT_CHUNK_TYPES.has(type)) {\n const text = (c.text ?? c.textDelta) as string | undefined;\n console.debug(`[juneau] streamToWire chunk: ${type} ${JSON.stringify(text ?? '')}`);\n } else if (type === 'tool-call') {\n console.debug(`[juneau] streamToWire chunk: tool-call \"${c.toolName ?? c.name ?? '?'}\"`);\n } else if (type === 'tool-result') {\n console.debug(`[juneau] streamToWire chunk: tool-result (ignored)`);\n } else if (type) {\n if (IGNORED_CHUNK_TYPES.has(type)) {\n console.debug(`[juneau] streamToWire chunk: ${type} (ignored)`);\n } else {\n console.debug(`[juneau] streamToWire chunk: ${type} (unknown)`);\n }\n }\n }\n\n if (type && TEXT_CHUNK_TYPES.has(type)) {\n // Flush any buffered activity events before emitting text so the UI\n // shows running/done indicators before the model's reply appears.\n if (skillSet) {\n const activities = skillSet.drainActivities();\n if (debug && activities.length > 0) {\n console.debug(`[juneau] streamToWire → draining ${activities.length} activities`);\n }\n for (const event of activities) {\n yield event;\n }\n }\n\n // ai-sdk v7 uses `text`, v6 used `textDelta` — support both\n const text = (c.text ?? c.textDelta) as string | undefined;\n if (text) {\n if (debug) {\n console.debug(`[juneau] streamToWire → yielding text ${JSON.stringify(text)}`);\n }\n yield `data: ${JSON.stringify({ type: 'text', text })}\\n\\n`;\n }\n }\n\n // All other chunk types are intentionally silent — the SkillSet execute fn\n // emits activity events into its buffer which we drain above.\n }\n\n // Final drain — catches activity events from the last tool call when no\n // text-delta followed (Gemini sometimes calls a tool successfully but emits\n // the reply text in a subsequent step that never arrives as text-delta here).\n if (skillSet) {\n const remaining = skillSet.drainActivities();\n if (debug && remaining.length > 0) {\n console.debug(`[juneau] streamToWire → draining ${remaining.length} activities (end of stream)`);\n }\n for (const event of remaining) {\n yield event;\n }\n }\n\n if (debug) {\n console.debug('[juneau] streamToWire → end of stream, emitting done');\n }\n\n yield `data: ${JSON.stringify({ type: 'done' })}\\n\\n`;\n}\n","import type { ToolRecoveryOptions } from './types';\nimport { streamToWire } from './streamToWire';\n\nfunction wireError(message: string): string {\n return `data: ${JSON.stringify({ type: 'error', message })}\\n\\n`;\n}\n\nfunction wireDone(): string {\n return `data: ${JSON.stringify({ type: 'done' })}\\n\\n`;\n}\n\n/**\n * Extracts the text payload from a wire SSE chunk's `data: {json}` lines.\n * Returns '' for non-text events or unparseable lines.\n */\nfunction extractWireText(chunk: string): string {\n let text = '';\n for (const line of chunk.split('\\n')) {\n if (!line.startsWith('data: ')) continue;\n try {\n const event = JSON.parse(line.slice(6)) as { type?: string; text?: string };\n if (event.type === 'text' && typeof event.text === 'string') {\n text += event.text;\n }\n } catch {\n // Not JSON — ignore, only well-formed text events count\n }\n }\n return text;\n}\n\n/**\n * Encapsulates the multi-phase streaming pattern needed for Gemini 2.5 Flash\n * tool call scenarios where the model either fails or silently succeeds without\n * emitting any text in the same stream pass.\n *\n * Phase 1: Stream with tools. Collect whether any text was produced and whether\n * a tool failure occurred.\n *\n * Phase 2 (failure recovery) — triggers when a tool failed AND no text was produced:\n * - Injects failureContext as an assistant message so the model is forced to\n * write a recovery text response (no tools available in phase 2).\n *\n * Phase 3 (silent-success recovery) — triggers when the tool succeeded but the\n * model wrote no text. Confirmed Gemini 2.5 Flash behaviour: the fullStream ends\n * with tool-call → tool-result → finish-step → finish and no text-delta ever\n * arrives — Gemini treats the tool call as its complete response. Phase 3 receives\n * the full phase 1 message history including tool-call AND tool-result turns —\n * Gemini rejects histories where a tool-call turn is not immediately followed by\n * a tool-result turn (\"function call turn must come immediately after a user turn\n * or after a function response turn\"). The history is resolved from the consumed\n * phase 1 result's `messages` promise (ai-sdk v7 — resolves to all turns after\n * the stream is consumed), with `response.messages` as fallback.\n * If phase3 is not provided, falls back to emitting done (previous behaviour).\n *\n * Errors thrown by phase 2 / phase 3 model calls are surfaced as wire error\n * events — never swallowed into a silent done.\n *\n * @returns AsyncIterable<string> of Juneau wire SSE strings (activities + text + done)\n */\nexport async function* withToolRecovery(options: ToolRecoveryOptions): AsyncIterable<string> {\n const { phase1, phase2, phase3, skillSet, onFinish, debug = false } = options;\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 1 start');\n }\n\n let producedText = false;\n // Assistant text accumulated across all phases — handed to onFinish on completion\n let accumulatedText = '';\n\n const result1 = phase1();\n\n for await (const chunk of streamToWire(result1.fullStream, skillSet, { debug })) {\n accumulatedText += extractWireText(chunk);\n\n // Track whether any text reached the wire (done event doesn't count)\n if (chunk.includes('\"type\":\"text\"')) {\n producedText = true;\n }\n\n // Hold back the done event — we may need to continue with phase 2 or 3\n if (chunk.includes('\"type\":\"done\"')) {\n continue;\n }\n\n yield chunk;\n }\n\n if (debug) {\n console.debug(\n `[juneau] withToolRecovery → phase 1 complete, textProduced=${producedText}, hadFailure=${skillSet.hadFailure}`\n );\n }\n\n if (skillSet.hadFailure && !producedText && skillSet.failureContext) {\n // Tool failed and model wrote nothing — run phase 2 to force a text response\n if (debug) {\n console.debug('[juneau] withToolRecovery → hadFailure=true, textProduced=false → triggering phase 2');\n }\n\n try {\n const result2 = phase2(skillSet.failureContext);\n\n // Phase 2 has no skillSet — plain text response, no tool calls expected.\n // Chunks are re-yielded one by one so we can accumulate their text; the\n // final done event is held back until onFinish has fired.\n for await (const chunk of streamToWire(result2.fullStream, undefined, { debug })) {\n accumulatedText += extractWireText(chunk);\n if (chunk.includes('\"type\":\"done\"')) continue;\n yield chunk;\n }\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 2 complete');\n }\n\n onFinish?.({ text: accumulatedText });\n yield wireDone();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (debug) {\n console.debug(`[juneau] withToolRecovery → phase 2 FAILED: \"${message}\"`);\n }\n yield wireError(message);\n }\n return;\n }\n\n if (!producedText && !skillSet.hadFailure && phase3) {\n // Tool succeeded but model emitted no text — Gemini silent-response scenario.\n // Resolve the full message history from the consumed phase 1 result and let\n // phase 3 call the model again (no tools) to summarise the tool result.\n const fullMessages = await resolvePhase1Messages(result1);\n\n if (fullMessages) {\n if (debug) {\n console.debug(\n `[juneau] withToolRecovery → phase 3 messages resolved (${fullMessages.length}):`,\n JSON.stringify(fullMessages, null, 2)\n );\n if (!containsToolResult(fullMessages)) {\n console.debug(\n '[juneau] withToolRecovery → WARNING: resolved history contains no tool-result turn — Gemini will likely reject it as an invalid conversation structure'\n );\n }\n console.debug('[juneau] withToolRecovery → no failure, no text → triggering phase 3');\n }\n\n try {\n // Re-yield chunk by chunk to accumulate text; done is held back until\n // onFinish has fired.\n for await (const chunk of streamToWire(phase3(fullMessages).fullStream, undefined, { debug })) {\n accumulatedText += extractWireText(chunk);\n if (chunk.includes('\"type\":\"done\"')) continue;\n yield chunk;\n }\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 3 complete');\n }\n\n onFinish?.({ text: accumulatedText });\n yield wireDone();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (debug) {\n console.debug(`[juneau] withToolRecovery → phase 3 FAILED: \"${message}\"`);\n }\n yield wireError(message);\n }\n return;\n }\n\n if (debug) {\n console.debug(\n '[juneau] withToolRecovery → phase 3 configured but phase 1 result exposes no message history — emitting done'\n );\n }\n } else if (!producedText && !skillSet.hadFailure && debug) {\n console.debug(\n '[juneau] withToolRecovery → no failure, no text, no phase3 — emitting done (Gemini silent response)'\n );\n }\n\n onFinish?.({ text: accumulatedText });\n yield wireDone();\n}\n\n/**\n * Resolves the full message history (incl. tool-call/tool-result turns) from a\n * consumed ai-sdk StreamTextResult.\n *\n * ai-sdk v7: `result.messages` is the promise that resolves to ALL turns —\n * user, assistant(tool-call), tool(tool-result) — after the stream is consumed.\n * `result.response.messages` may resolve to an incomplete subset (observed:\n * tool-call turn without the following tool-result turn, which Gemini rejects),\n * so it is only used as a fallback when `messages` is unavailable.\n *\n * Both promises resolve only after the fullStream has been fully consumed,\n * which is guaranteed at the call site.\n */\nasync function resolvePhase1Messages(result: {\n messages?: PromiseLike<unknown[]>;\n response?: PromiseLike<{ messages?: unknown[] }>;\n}): Promise<unknown[] | null> {\n if (result.messages) {\n const messages = await result.messages;\n if (Array.isArray(messages) && messages.length > 0) {\n return messages;\n }\n }\n\n if (result.response) {\n const response = await result.response;\n if (Array.isArray(response?.messages) && response.messages.length > 0) {\n return response.messages;\n }\n }\n\n return null;\n}\n\n/**\n * Checks whether the resolved history contains a tool-result turn — either as\n * a `role: 'tool'` message or a content part with `type: 'tool-result'`.\n * Used only for the debug warning; the messages themselves are passed through opaquely.\n */\nfunction containsToolResult(messages: unknown[]): boolean {\n return messages.some((m) => {\n const msg = m as { role?: string; content?: unknown };\n if (msg.role === 'tool') return true;\n if (Array.isArray(msg.content)) {\n return msg.content.some(\n (part) => (part as { type?: string }).type === 'tool-result'\n );\n }\n return false;\n });\n}\n"],"names":["toSdkMessages","messages","mapped","msg","text","p","result","i","current","prev","formatWireEvent","event","pickLabel","labels","language","validateSkills","skills","knownNames","name","skill","toolName","createSkillSet","options","debug","activityBuffer","calledSkillNames","hadFailure","failureContext","tools","input","startMs","executeContext","part","durationMs","err","message","failedLabels","buildSkillIndex","skillSet","traits","selectSkills","skillNames","TEXT_CHUNK_TYPES","IGNORED_CHUNK_TYPES","streamToWire","fullStream","chunk","c","type","activities","remaining","wireError","wireDone","extractWireText","line","withToolRecovery","phase1","phase2","phase3","onFinish","producedText","accumulatedText","result1","result2","fullMessages","resolvePhase1Messages","containsToolResult","response","m"],"mappings":"gFAaO,SAASA,EAAcC,EAAsC,CAGlE,MAAMC,EAAwBD,EAAS,IAAIE,GAAO,CAChD,MAAMC,EAAOD,EAAI,MACd,UAAYE,EAAE,OAAS,MAAM,EAC7B,IAAIA,GAAMA,EAAqC,IAAI,EACnD,KAAK,EAAE,EAEV,MAAO,CAAE,KAAMF,EAAI,KAA6B,QAASC,CAAA,CAC3D,CAAC,EAIKE,EAAwB,CAAA,EAC9B,QAASC,EAAI,EAAGA,EAAIL,EAAO,OAAQK,IAAK,CACtC,MAAMC,EAAUN,EAAOK,CAAC,EAClBE,EAAOH,EAAOA,EAAO,OAAS,CAAC,EAEjCE,EAAQ,OAAS,QAAUC,GAAM,OAAS,QAC5CH,EAAO,KAAK,CAAE,KAAM,YAAa,QAAS,IAAK,EAGjDA,EAAO,KAAKE,CAAO,CACrB,CAKA,OAAOF,EAAO,OAAO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EACZ,OAAIjE,EAAI,OAAS,OAAe,GAC5B,MAAM,QAAQA,EAAI,OAAO,EACpBA,EAAI,QAAQ,KAChB6B,GAAUA,EAA2B,OAAS,aAAA,EAG5C,EACT,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../../src/server/toSdkMessages.ts","../../src/server/createSkillSet.ts","../../src/server/skillIndex.ts","../../src/server/streamToWire.ts","../../src/server/withToolRecovery.ts","../../src/server/withSkillDispatch.ts"],"sourcesContent":["import type { AiMessage } from '../core/types';\r\nimport type { CoreMessage } from './types';\r\n\r\n/**\r\n * Converts Juneau's AiMessage[] to the CoreMessage[] format expected by\r\n * ai-sdk's generateText / streamText.\r\n *\r\n * - Extracts plain text from parts (joins all type: \"text\" parts)\r\n * - Replaces activity-only assistant messages with an empty assistant turn\r\n * so conversation alternation stays valid\r\n * - Injects a placeholder assistant turn between consecutive user messages\r\n * - Filters out empty turns (unless they are a required alternation filler)\r\n */\r\nexport function toSdkMessages(messages: AiMessage[]): CoreMessage[] {\r\n // First pass: map each AiMessage to a CoreMessage, replacing activity-only\r\n // assistant messages with an empty-text assistant turn.\r\n const mapped: CoreMessage[] = messages.map(msg => {\r\n const text = msg.parts\r\n .filter(p => p.type === 'text')\r\n .map(p => (p as { type: 'text'; text: string }).text)\r\n .join('');\r\n\r\n return { role: msg.role as CoreMessage['role'], content: text };\r\n });\r\n\r\n // Second pass: inject a placeholder assistant turn between consecutive user\r\n // messages as a safety net for history bugs that would cause model errors.\r\n const result: CoreMessage[] = [];\r\n for (let i = 0; i < mapped.length; i++) {\r\n const current = mapped[i];\r\n const prev = result[result.length - 1];\r\n\r\n if (current.role === 'user' && prev?.role === 'user') {\r\n result.push({ role: 'assistant', content: '…' });\r\n }\r\n\r\n result.push(current);\r\n }\r\n\r\n // Third pass: filter out empty turns, but keep assistant placeholders that\r\n // serve as alternation fillers (they have content '…' set above, so they\r\n // won't be filtered). Only drop genuinely empty content strings.\r\n return result.filter(msg => msg.content.length > 0);\r\n}\r\n","import type { ZodType } from 'zod';\r\nimport type { SkillDefinition, SkillExecuteContext, SkillSet, SkillSetOptions } from './types';\r\n\r\ntype SkillMap = Record<string, SkillDefinition<ZodType>>;\r\n\r\nfunction formatWireEvent(event: Record<string, unknown>): string {\r\n return `data: ${JSON.stringify(event)}\\n\\n`;\r\n}\r\n\r\nfunction pickLabel(labels: { cs: string; en: string }, language: string): string {\r\n return (labels as Record<string, string>)[language] ?? labels.en;\r\n}\r\n\r\n/**\r\n * Takes a map of skill definitions and returns a SkillSet containing:\r\n * - tools: ready-made tool definitions for ai-sdk's streamText({ tools })\r\n * - drainActivities(): flush buffered activity + part wire SSE strings\r\n * - hadFailure / failureContext: for driving tool failure recovery\r\n *\r\n * Each skill's execute fn receives a SkillExecuteContext as its second\r\n * argument with an `emit(part)` callback — parts are pushed into the same\r\n * buffer as activities and drained by streamToWire at the same points.\r\n */\r\n/**\r\n * Validates skill definitions at startup — throws immediately (not at runtime)\r\n * so a broken registry fails the server boot, not a user request.\r\n */\r\nfunction validateSkills(skills: SkillMap): void {\r\n const knownNames = new Set(Object.keys(skills));\r\n\r\n for (const [name, skill] of Object.entries(skills)) {\r\n if (!skill.tools) continue;\r\n for (const toolName of skill.tools) {\r\n if (!knownNames.has(toolName)) {\r\n throw new Error(\r\n `[juneau] createSkillSet: skill \"${name}\" references unknown tool \"${toolName}\". ` +\r\n `Known skills: ${[...knownNames].join(', ')}`\r\n );\r\n }\r\n }\r\n }\r\n}\r\n\r\nexport function createSkillSet(skills: SkillMap, options: SkillSetOptions = {}): SkillSet {\r\n validateSkills(skills);\r\n\r\n const language = options.language ?? 'en';\r\n const debug = options.debug ?? false;\r\n const activityBuffer: string[] = [];\r\n const calledSkillNames: string[] = [];\r\n const calledSkillIds: number[] = [];\r\n let hadFailure = false;\r\n let failureContext: string | null = null;\r\n\r\n // Validate ID uniqueness and build lookup map\r\n const skillsById = new Map<number, SkillDefinition>();\r\n const idToName = new Map<number, string>();\r\n for (const [name, skill] of Object.entries(skills)) {\r\n if (skillsById.has(skill.id)) {\r\n throw new Error(\r\n `[juneau] createSkillSet: skills \"${idToName.get(skill.id)}\" and \"${name}\" share the same ID (${skill.id}). IDs must be unique.`\r\n );\r\n }\r\n skillsById.set(skill.id, skill);\r\n idToName.set(skill.id, name);\r\n }\r\n\r\n const tools: Record<string, unknown> = {};\r\n\r\n for (const [name, skill] of Object.entries(skills)) {\r\n tools[name] = {\r\n description: skill.description,\r\n parameters: skill.input,\r\n execute: async (input: unknown) => {\r\n if (!calledSkillNames.includes(name)) {\r\n calledSkillNames.push(name);\r\n calledSkillIds.push(skill.id);\r\n }\r\n\r\n if (debug) {\r\n console.debug(`[juneau] skill \"${name}\" → executing, input:`, input);\r\n }\r\n\r\n const startMs = debug ? Date.now() : 0;\r\n\r\n // Emit a \"running\" activity event into the buffer\r\n activityBuffer.push(\r\n formatWireEvent({\r\n type: 'activity',\r\n id: name,\r\n title: pickLabel(skill.labels.running, language),\r\n status: 'running',\r\n metadata: { skill: name },\r\n })\r\n );\r\n\r\n const executeContext: SkillExecuteContext = {\r\n emit: (part) => {\r\n if (debug) {\r\n console.debug(`[juneau] skill \"${name}\" → emitting part \"${part.type}\"`);\r\n }\r\n activityBuffer.push(formatWireEvent({ type: 'part', part }));\r\n },\r\n };\r\n\r\n try {\r\n const result = await skill.execute(input as never, executeContext);\r\n\r\n const durationMs = debug ? Date.now() - startMs : 0;\r\n if (debug) {\r\n console.debug(`[juneau] skill \"${name}\" → done in ${durationMs}ms, result:`, result);\r\n }\r\n\r\n // Emit a \"done\" activity event\r\n activityBuffer.push(\r\n formatWireEvent({\r\n type: 'activity',\r\n id: name,\r\n title: pickLabel(skill.labels.done, language),\r\n status: 'done',\r\n metadata: { skill: name },\r\n })\r\n );\r\n\r\n return result;\r\n } catch (err) {\r\n const durationMs = debug ? Date.now() - startMs : 0;\r\n const message = err instanceof Error ? err.message : String(err);\r\n\r\n if (debug) {\r\n console.debug(`[juneau] skill \"${name}\" → FAILED in ${durationMs}ms: \"${message}\"`);\r\n }\r\n\r\n const failedLabels = skill.labels.failed ?? { cs: 'Nepodařilo se', en: 'Failed' };\r\n\r\n // Emit a \"failed\" activity event\r\n activityBuffer.push(\r\n formatWireEvent({\r\n type: 'activity',\r\n id: name,\r\n title: pickLabel(failedLabels, language),\r\n status: 'failed',\r\n metadata: { skill: name },\r\n })\r\n );\r\n\r\n hadFailure = true;\r\n failureContext = `Tool \"${name}\" failed: ${message}`;\r\n\r\n // Re-throw so ai-sdk knows the tool call failed\r\n throw err;\r\n }\r\n },\r\n };\r\n }\r\n\r\n return {\r\n tools,\r\n\r\n skills,\r\n\r\n calledSkillNames,\r\n\r\n calledSkillIds,\r\n\r\n skillsById,\r\n\r\n drainActivities(): string[] {\r\n return activityBuffer.splice(0, activityBuffer.length);\r\n },\r\n\r\n get hadFailure() {\r\n return hadFailure;\r\n },\r\n\r\n get failureContext() {\r\n return failureContext;\r\n },\r\n };\r\n}\r\n","import type { SkillSet } from './types';\r\n\r\n/**\r\n * Builds a compact one-liner-per-skill index for the system prompt.\r\n * Inject the output into your system prompt instead of hand-maintaining a\r\n * skill list — adding a skill to the registry updates the index automatically.\r\n *\r\n * Each line includes the numeric ID so the model can request a skill by ID\r\n * (avoids brittle string comparisons when routing phase 2 dispatch).\r\n *\r\n * Output format:\r\n * [1] invoiceSearch (read): Find invoices by number, supplier, date, or status.\r\n * [2] invoiceApprove (write, requires confirmation): Approve an invoice.\r\n */\r\nexport function buildSkillIndex(skillSet: SkillSet): string {\r\n return Object.entries(skillSet.skills)\r\n .map(([name, skill]) => {\r\n const traits: string[] = [skill.readOnly === false ? 'write' : 'read'];\r\n if (skill.requiresConfirmation) {\r\n traits.push('requires confirmation');\r\n }\r\n const idPrefix = `[${skill.id}] `;\r\n return `${idPrefix}${name} (${traits.join(', ')}): ${skill.description}`;\r\n })\r\n .join('\\n');\r\n}\r\n\r\n/**\r\n * Returns the concatenated workflow instructions for the given skill names —\r\n * typically skillSet.calledSkillNames after phase 1. Skills without\r\n * instructions and unknown names are skipped. Returns '' when nothing matches.\r\n *\r\n * This is the lazy-loading half of the skill pattern: full instructions enter\r\n * the prompt only for skills the model actually used.\r\n *\r\n * @example\r\n * const instructions = selectSkills(skillSet, skillSet.calledSkillNames);\r\n * // → inject into phase 2's system prompt as additional context\r\n */\r\nexport function selectSkills(skillSet: SkillSet, skillNames: string[]): string {\r\n return skillNames\r\n .map(name => skillSet.skills[name])\r\n .filter(skill => skill?.instructions)\r\n .map(skill => skill.instructions as string)\r\n .join('\\n\\n');\r\n}\r\n\r\n/**\r\n * Returns the concatenated workflow instructions for the given skill IDs —\r\n * typically skillSet.calledSkillIds after phase 1. Skills without instructions\r\n * and unknown IDs are skipped. Returns '' when nothing matches.\r\n *\r\n * Prefer this over selectSkills when routing dispatch by numeric ID — avoids\r\n * string comparisons entirely.\r\n *\r\n * @example\r\n * const instructions = selectSkillsById(skillSet, skillSet.calledSkillIds);\r\n * // → inject into phase 2's system prompt as additional context\r\n */\r\nexport function selectSkillsById(skillSet: SkillSet, skillIds: number[]): string {\r\n return skillIds\r\n .map(id => skillSet.skillsById.get(id))\r\n .filter(skill => skill?.instructions)\r\n .map(skill => skill!.instructions as string)\r\n .join('\\n\\n');\r\n}\r\n","import type { SkillSet, StreamToWireOptions } from './types';\n\n// ai-sdk v7 chunk types that carry the model's text output.\n// - 'text-delta': standard streaming text (v6 + v7)\n// - 'text': emitted by some v7 model/provider combos as a completed text chunk\n// Both may appear in the same stream; we handle either.\nconst TEXT_CHUNK_TYPES = new Set(['text-delta', 'text']);\n\n// Chunk types we recognise but intentionally ignore — activities are driven by\n// the SkillSet execute fn, not by these wire events.\nconst IGNORED_CHUNK_TYPES = new Set([\n 'tool-call',\n 'tool-result',\n 'tool-input-start',\n 'tool-input-delta',\n 'tool-input-available',\n 'tool-output-available',\n 'step-start',\n 'finish-step',\n 'start',\n 'finish',\n 'response-metadata',\n 'stream-start',\n]);\n\n/**\n * Converts ai-sdk's fullStream AsyncIterable into Juneau wire SSE strings.\n *\n * Handles:\n * - All text chunk types used by ai-sdk v7 (text-delta, text) incl. v6 textDelta fallback\n * - Flushing skillSet.drainActivities() before each text chunk so activities\n * always appear before the text they precede\n * - A final drain after the loop ends (catches last-tool-call activities when\n * no text follows the tool result — the Gemini silent-response scenario)\n * - Emitting the done event when the stream finishes\n * - Structured debug logging of every chunk when options.debug is true\n */\nexport async function* streamToWire(\n fullStream: AsyncIterable<unknown>,\n skillSet?: SkillSet,\n options?: StreamToWireOptions\n): AsyncIterable<string> {\n const debug = options?.debug ?? false;\n\n for await (const chunk of fullStream) {\n const c = chunk as Record<string, unknown>;\n const type = c.type as string | undefined;\n\n if (debug) {\n if (type && TEXT_CHUNK_TYPES.has(type)) {\n const text = (c.text ?? c.textDelta) as string | undefined;\n console.debug(`[juneau] streamToWire chunk: ${type} ${JSON.stringify(text ?? '')}`);\n } else if (type === 'tool-call') {\n console.debug(`[juneau] streamToWire chunk: tool-call \"${c.toolName ?? c.name ?? '?'}\"`);\n } else if (type === 'tool-result') {\n console.debug(`[juneau] streamToWire chunk: tool-result (ignored)`);\n } else if (type) {\n if (IGNORED_CHUNK_TYPES.has(type)) {\n console.debug(`[juneau] streamToWire chunk: ${type} (ignored)`);\n } else {\n console.debug(`[juneau] streamToWire chunk: ${type} (unknown)`);\n }\n }\n }\n\n if (type && TEXT_CHUNK_TYPES.has(type)) {\n // Flush any buffered activity events before emitting text so the UI\n // shows running/done indicators before the model's reply appears.\n if (skillSet) {\n const activities = skillSet.drainActivities();\n if (debug && activities.length > 0) {\n console.debug(`[juneau] streamToWire → draining ${activities.length} activities`);\n }\n for (const event of activities) {\n yield event;\n }\n }\n\n // ai-sdk v7 uses `text`, v6 used `textDelta` — support both\n const text = (c.text ?? c.textDelta) as string | undefined;\n if (text) {\n if (debug) {\n console.debug(`[juneau] streamToWire → yielding text ${JSON.stringify(text)}`);\n }\n yield `data: ${JSON.stringify({ type: 'text', text })}\\n\\n`;\n }\n }\n\n // All other chunk types are intentionally silent — the SkillSet execute fn\n // emits activity events into its buffer which we drain above.\n }\n\n // Final drain — catches activity events from the last tool call when no\n // text-delta followed (Gemini sometimes calls a tool successfully but emits\n // the reply text in a subsequent step that never arrives as text-delta here).\n if (skillSet) {\n const remaining = skillSet.drainActivities();\n if (debug && remaining.length > 0) {\n console.debug(`[juneau] streamToWire → draining ${remaining.length} activities (end of stream)`);\n }\n for (const event of remaining) {\n yield event;\n }\n }\n\n if (debug) {\n console.debug('[juneau] streamToWire → end of stream, emitting done');\n }\n\n yield `data: ${JSON.stringify({ type: 'done' })}\\n\\n`;\n}\n","import type { ToolRecoveryOptions } from './types';\nimport { streamToWire } from './streamToWire';\n\nfunction wireError(message: string): string {\n return `data: ${JSON.stringify({ type: 'error', message })}\\n\\n`;\n}\n\nfunction wireDone(): string {\n return `data: ${JSON.stringify({ type: 'done' })}\\n\\n`;\n}\n\n/**\n * Extracts the text payload from a wire SSE chunk's `data: {json}` lines.\n * Returns '' for non-text events or unparseable lines.\n */\nfunction extractWireText(chunk: string): string {\n let text = '';\n for (const line of chunk.split('\\n')) {\n if (!line.startsWith('data: ')) continue;\n try {\n const event = JSON.parse(line.slice(6)) as { type?: string; text?: string };\n if (event.type === 'text' && typeof event.text === 'string') {\n text += event.text;\n }\n } catch {\n // Not JSON — ignore, only well-formed text events count\n }\n }\n return text;\n}\n\n/**\n * Encapsulates the multi-phase streaming pattern needed for Gemini 2.5 Flash\n * tool call scenarios where the model either fails or silently succeeds without\n * emitting any text in the same stream pass.\n *\n * Phase 1: Stream with tools. Collect whether any text was produced and whether\n * a tool failure occurred.\n *\n * Phase 2 (failure recovery) — triggers when a tool failed AND no text was produced:\n * - Injects failureContext as an assistant message so the model is forced to\n * write a recovery text response (no tools available in phase 2).\n *\n * Phase 3 (silent-success recovery) — triggers when the tool succeeded but the\n * model wrote no text. Confirmed Gemini 2.5 Flash behaviour: the fullStream ends\n * with tool-call → tool-result → finish-step → finish and no text-delta ever\n * arrives — Gemini treats the tool call as its complete response. Phase 3 receives\n * the full phase 1 message history including tool-call AND tool-result turns —\n * Gemini rejects histories where a tool-call turn is not immediately followed by\n * a tool-result turn (\"function call turn must come immediately after a user turn\n * or after a function response turn\"). The history is resolved from the consumed\n * phase 1 result's `messages` promise (ai-sdk v7 — resolves to all turns after\n * the stream is consumed), with `response.messages` as fallback.\n * If phase3 is not provided, falls back to emitting done (previous behaviour).\n *\n * Errors thrown by phase 2 / phase 3 model calls are surfaced as wire error\n * events — never swallowed into a silent done.\n *\n * @returns AsyncIterable<string> of Juneau wire SSE strings (activities + text + done)\n */\nexport async function* withToolRecovery(options: ToolRecoveryOptions): AsyncIterable<string> {\n const { phase1, phase2, phase3, skillSet, onFinish, debug = false } = options;\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 1 start');\n }\n\n let producedText = false;\n // Assistant text accumulated across all phases — handed to onFinish on completion\n let accumulatedText = '';\n\n const result1 = phase1();\n\n for await (const chunk of streamToWire(result1.fullStream, skillSet, { debug })) {\n accumulatedText += extractWireText(chunk);\n\n // Track whether any text reached the wire (done event doesn't count)\n if (chunk.includes('\"type\":\"text\"')) {\n producedText = true;\n }\n\n // Hold back the done event — we may need to continue with phase 2 or 3\n if (chunk.includes('\"type\":\"done\"')) {\n continue;\n }\n\n yield chunk;\n }\n\n if (debug) {\n console.debug(\n `[juneau] withToolRecovery → phase 1 complete, textProduced=${producedText}, hadFailure=${skillSet.hadFailure}`\n );\n }\n\n if (skillSet.hadFailure && !producedText && skillSet.failureContext) {\n // Tool failed and model wrote nothing — run phase 2 to force a text response\n if (debug) {\n console.debug('[juneau] withToolRecovery → hadFailure=true, textProduced=false → triggering phase 2');\n }\n\n try {\n const result2 = phase2(skillSet.failureContext);\n\n // Phase 2 has no skillSet — plain text response, no tool calls expected.\n // Chunks are re-yielded one by one so we can accumulate their text; the\n // final done event is held back until onFinish has fired.\n for await (const chunk of streamToWire(result2.fullStream, undefined, { debug })) {\n accumulatedText += extractWireText(chunk);\n if (chunk.includes('\"type\":\"done\"')) continue;\n yield chunk;\n }\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 2 complete');\n }\n\n onFinish?.({ text: accumulatedText });\n yield wireDone();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (debug) {\n console.debug(`[juneau] withToolRecovery → phase 2 FAILED: \"${message}\"`);\n }\n yield wireError(message);\n }\n return;\n }\n\n if (!producedText && !skillSet.hadFailure && phase3) {\n // Tool succeeded but model emitted no text — Gemini silent-response scenario.\n // Resolve the full message history from the consumed phase 1 result and let\n // phase 3 call the model again (no tools) to summarise the tool result.\n const fullMessages = await resolvePhase1Messages(result1);\n\n if (fullMessages) {\n if (debug) {\n console.debug(\n `[juneau] withToolRecovery → phase 3 messages resolved (${fullMessages.length}):`,\n JSON.stringify(fullMessages, null, 2)\n );\n if (!containsToolResult(fullMessages)) {\n console.debug(\n '[juneau] withToolRecovery → WARNING: resolved history contains no tool-result turn — Gemini will likely reject it as an invalid conversation structure'\n );\n }\n console.debug('[juneau] withToolRecovery → no failure, no text → triggering phase 3');\n }\n\n try {\n // Re-yield chunk by chunk to accumulate text; done is held back until\n // onFinish has fired.\n for await (const chunk of streamToWire(phase3(fullMessages).fullStream, undefined, { debug })) {\n accumulatedText += extractWireText(chunk);\n if (chunk.includes('\"type\":\"done\"')) continue;\n yield chunk;\n }\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 3 complete');\n }\n\n onFinish?.({ text: accumulatedText });\n yield wireDone();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (debug) {\n console.debug(`[juneau] withToolRecovery → phase 3 FAILED: \"${message}\"`);\n }\n yield wireError(message);\n }\n return;\n }\n\n if (debug) {\n console.debug(\n '[juneau] withToolRecovery → phase 3 configured but phase 1 result exposes no message history — emitting done'\n );\n }\n } else if (!producedText && !skillSet.hadFailure && debug) {\n console.debug(\n '[juneau] withToolRecovery → no failure, no text, no phase3 — emitting done (Gemini silent response)'\n );\n }\n\n onFinish?.({ text: accumulatedText });\n yield wireDone();\n}\n\n/**\n * Resolves the full message history (incl. tool-call/tool-result turns) from a\n * consumed ai-sdk StreamTextResult.\n *\n * ai-sdk v7: `result.messages` is the promise that resolves to ALL turns —\n * user, assistant(tool-call), tool(tool-result) — after the stream is consumed.\n * `result.response.messages` may resolve to an incomplete subset (observed:\n * tool-call turn without the following tool-result turn, which Gemini rejects),\n * so it is only used as a fallback when `messages` is unavailable.\n *\n * Both promises resolve only after the fullStream has been fully consumed,\n * which is guaranteed at the call site.\n */\nasync function resolvePhase1Messages(result: {\n messages?: PromiseLike<unknown[]>;\n response?: PromiseLike<{ messages?: unknown[] }>;\n}): Promise<unknown[] | null> {\n if (result.messages) {\n const messages = await result.messages;\n if (Array.isArray(messages) && messages.length > 0) {\n return messages;\n }\n }\n\n if (result.response) {\n const response = await result.response;\n if (Array.isArray(response?.messages) && response.messages.length > 0) {\n return response.messages;\n }\n }\n\n return null;\n}\n\n/**\n * Checks whether the resolved history contains a tool-result turn — either as\n * a `role: 'tool'` message or a content part with `type: 'tool-result'`.\n * Used only for the debug warning; the messages themselves are passed through opaquely.\n */\nfunction containsToolResult(messages: unknown[]): boolean {\n return messages.some((m) => {\n const msg = m as { role?: string; content?: unknown };\n if (msg.role === 'tool') return true;\n if (Array.isArray(msg.content)) {\n return msg.content.some(\n (part) => (part as { type?: string }).type === 'tool-result'\n );\n }\n return false;\n });\n}\n","import type { SkillDispatchOptions } from './types';\r\nimport { selectSkillsById } from './skillIndex';\r\nimport { streamToWire } from './streamToWire';\r\n\r\nfunction wireError(message: string): string {\r\n return `data: ${JSON.stringify({ type: 'error', message })}\\n\\n`;\r\n}\r\n\r\nfunction wireDone(): string {\r\n return `data: ${JSON.stringify({ type: 'done' })}\\n\\n`;\r\n}\r\n\r\n/**\r\n * Extracts the text payload from wire SSE chunks' `data: {json}` lines.\r\n * Returns '' for non-text events or unparseable lines.\r\n */\r\nfunction extractWireText(chunk: string): string {\r\n let text = '';\r\n for (const line of chunk.split('\\n')) {\r\n if (!line.startsWith('data: ')) continue;\r\n try {\r\n const event = JSON.parse(line.slice(6)) as { type?: string; text?: string };\r\n if (event.type === 'text' && typeof event.text === 'string') {\r\n text += event.text;\r\n }\r\n } catch {\r\n // Not JSON — ignore\r\n }\r\n }\r\n return text;\r\n}\r\n\r\n/**\r\n * Resolves the full message history from a consumed ai-sdk StreamTextResult.\r\n * Mirrors the same logic used in withToolRecovery — see that file for rationale.\r\n */\r\nasync function resolveMessages(result: {\r\n messages?: PromiseLike<unknown[]>;\r\n response?: PromiseLike<{ messages?: unknown[] }>;\r\n}): Promise<unknown[] | null> {\r\n if (result.messages) {\r\n const messages = await result.messages;\r\n if (Array.isArray(messages) && messages.length > 0) return messages;\r\n }\r\n if (result.response) {\r\n const response = await result.response;\r\n if (Array.isArray(response?.messages) && response.messages.length > 0) {\r\n return response.messages;\r\n }\r\n }\r\n return null;\r\n}\r\n\r\n/**\r\n * Deliberate 2-phase skill dispatch pattern.\r\n *\r\n * Phase 1: stream with a compact skill index (buildSkillIndex) as the system\r\n * prompt and thin tool definitions. The model picks a skill by calling one\r\n * of the tools — calledSkillIds is populated as tools fire.\r\n *\r\n * Phase 2: always runs when at least one skill was called. Receives:\r\n * - the full workflow instructions for the called skills (selectSkillsById)\r\n * - the complete phase 1 message history (user + tool-call + tool-result turns)\r\n * The model is called again without tools so it reads the instructions and\r\n * produces a text response.\r\n *\r\n * If no skill was called in phase 1 (the model answered directly), the phase 1\r\n * text is emitted as-is and the stream ends — no phase 2 needed.\r\n *\r\n * This is distinct from withToolRecovery: phase 2 here is unconditional and\r\n * intentional, not a fallback for failure or Gemini silent-response scenarios.\r\n *\r\n * Errors thrown by phase 2 are emitted as wire error events, never swallowed.\r\n */\r\nexport async function* withSkillDispatch(options: SkillDispatchOptions): AsyncIterable<string> {\r\n const { phase1, phase2, skillSet, onFinish, debug = false } = options;\r\n\r\n if (debug) {\r\n console.debug('[juneau] withSkillDispatch → phase 1 start');\r\n }\r\n\r\n let accumulatedText = '';\r\n let producedText = false;\r\n\r\n const result1 = phase1();\r\n\r\n for await (const chunk of streamToWire(result1.fullStream, skillSet, { debug })) {\r\n accumulatedText += extractWireText(chunk);\r\n if (chunk.includes('\"type\":\"text\"')) producedText = true;\r\n\r\n // Hold back the done event — we may continue with phase 2\r\n if (chunk.includes('\"type\":\"done\"')) continue;\r\n\r\n yield chunk;\r\n }\r\n\r\n if (debug) {\r\n console.debug(\r\n `[juneau] withSkillDispatch → phase 1 complete, calledSkillIds=[${skillSet.calledSkillIds.join(', ')}], textProduced=${producedText}`\r\n );\r\n }\r\n\r\n // No skill was called — model answered directly, we're done\r\n if (skillSet.calledSkillIds.length === 0) {\r\n if (debug) {\r\n console.debug('[juneau] withSkillDispatch → no skill called, emitting done');\r\n }\r\n onFinish?.({ text: accumulatedText });\r\n yield wireDone();\r\n return;\r\n }\r\n\r\n // Resolve the full phase 1 history (incl. tool-call + tool-result turns)\r\n const fullMessages = await resolveMessages(result1);\r\n\r\n if (!fullMessages) {\r\n // Shouldn't happen in practice, but fail loudly rather than silently\r\n if (debug) {\r\n console.debug('[juneau] withSkillDispatch → could not resolve phase 1 history, emitting error');\r\n }\r\n yield wireError('withSkillDispatch: could not resolve phase 1 message history for phase 2');\r\n return;\r\n }\r\n\r\n const instructions = selectSkillsById(skillSet, skillSet.calledSkillIds);\r\n\r\n if (debug) {\r\n console.debug(\r\n `[juneau] withSkillDispatch → phase 2 start, instructions length=${instructions.length}, history turns=${fullMessages.length}`\r\n );\r\n }\r\n\r\n try {\r\n for await (const chunk of streamToWire(phase2(instructions, fullMessages).fullStream, undefined, { debug })) {\r\n accumulatedText += extractWireText(chunk);\r\n if (chunk.includes('\"type\":\"done\"')) continue;\r\n yield chunk;\r\n }\r\n\r\n if (debug) {\r\n console.debug('[juneau] withSkillDispatch → phase 2 complete');\r\n }\r\n\r\n onFinish?.({ text: accumulatedText });\r\n yield wireDone();\r\n } catch (err) {\r\n const message = err instanceof Error ? err.message : String(err);\r\n if (debug) {\r\n console.debug(`[juneau] withSkillDispatch → phase 2 FAILED: \"${message}\"`);\r\n }\r\n yield wireError(message);\r\n }\r\n}\r\n"],"names":["toSdkMessages","messages","mapped","msg","text","p","result","i","current","prev","formatWireEvent","event","pickLabel","labels","language","validateSkills","skills","knownNames","name","skill","toolName","createSkillSet","options","debug","activityBuffer","calledSkillNames","calledSkillIds","hadFailure","failureContext","skillsById","idToName","tools","input","startMs","executeContext","part","durationMs","err","message","failedLabels","buildSkillIndex","skillSet","traits","selectSkills","skillNames","selectSkillsById","skillIds","id","TEXT_CHUNK_TYPES","IGNORED_CHUNK_TYPES","streamToWire","fullStream","chunk","c","type","activities","remaining","wireError","wireDone","extractWireText","line","withToolRecovery","phase1","phase2","phase3","onFinish","producedText","accumulatedText","result1","result2","fullMessages","resolvePhase1Messages","containsToolResult","response","m","resolveMessages","withSkillDispatch","instructions"],"mappings":"gFAaO,SAASA,EAAcC,EAAsC,CAGlE,MAAMC,EAAwBD,EAAS,IAAIE,GAAO,CAChD,MAAMC,EAAOD,EAAI,MACd,UAAYE,EAAE,OAAS,MAAM,EAC7B,IAAIA,GAAMA,EAAqC,IAAI,EACnD,KAAK,EAAE,EAEV,MAAO,CAAE,KAAMF,EAAI,KAA6B,QAASC,CAAA,CAC3D,CAAC,EAIKE,EAAwB,CAAA,EAC9B,QAASC,EAAI,EAAGA,EAAIL,EAAO,OAAQK,IAAK,CACtC,MAAMC,EAAUN,EAAOK,CAAC,EAClBE,EAAOH,EAAOA,EAAO,OAAS,CAAC,EAEjCE,EAAQ,OAAS,QAAUC,GAAM,OAAS,QAC5CH,EAAO,KAAK,CAAE,KAAM,YAAa,QAAS,IAAK,EAGjDA,EAAO,KAAKE,CAAO,CACrB,CAKA,OAAOF,EAAO,OAAOH,GAAOA,EAAI,QAAQ,OAAS,CAAC,CACpD,CCtCA,SAASO,EAAgBC,EAAwC,CAC/D,MAAO,SAAS,KAAK,UAAUA,CAAK,CAAC;AAAA;AAAA,CACvC,CAEA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,EAAOc,EAAcP,CAAY,EAAE,WAAY,OAAW,CAAE,MAAA/C,CAAA,CAAO,EACxG4C,GAAmBR,EAAgBP,CAAK,EACpC,CAAAA,EAAM,SAAS,eAAe,IAClC,MAAMA,GAGJ7B,GACF,QAAQ,MAAM,+CAA+C,EAG/D0C,IAAW,CAAE,KAAME,EAAiB,EACpC,MAAMT,EAAA,CACR,OAASrB,EAAK,CACZ,MAAMC,EAAUD,aAAe,MAAQA,EAAI,QAAU,OAAOA,CAAG,EAC3Dd,GACF,QAAQ,MAAM,iDAAiDe,CAAO,GAAG,EAE3E,MAAMmB,EAAUnB,CAAO,CACzB,CACF"}
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
export { toSdkMessages } from './toSdkMessages';
|
|
2
2
|
export { createSkillSet } from './createSkillSet';
|
|
3
|
-
export { buildSkillIndex, selectSkills } from './skillIndex';
|
|
3
|
+
export { buildSkillIndex, selectSkills, selectSkillsById } from './skillIndex';
|
|
4
4
|
export { streamToWire } from './streamToWire';
|
|
5
5
|
export { withToolRecovery } from './withToolRecovery';
|
|
6
|
-
export
|
|
6
|
+
export { withSkillDispatch } from './withSkillDispatch';
|
|
7
|
+
export type { SkillSet, SkillDefinition, SkillExecuteContext, SkillSetOptions, ToolRecoveryOptions, ToolRecoveryStreamResult, SkillDispatchOptions, StreamToWireOptions, CoreMessage } from './types';
|
|
7
8
|
export type { AiMessage, AiMessageRole, AiMessagePart, AiTextPart, AiEntity, AiEntityField, AiEntityBadgeTone, AiEntityPart, AiEntityListPart, AiSerializedMessage, AiStreamEvent, JuneauWireEvent, JuneauWireText, JuneauWireActivity, JuneauWirePart, JuneauWireDone, JuneauWireError, } from '../core/types';
|
|
8
9
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAC/E,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,YAAY,EAAE,QAAQ,EAAE,eAAe,EAAE,mBAAmB,EAAE,eAAe,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAGtM,YAAY,EACV,SAAS,EACT,aAAa,EACb,aAAa,EACb,UAAU,EACV,QAAQ,EACR,aAAa,EACb,iBAAiB,EACjB,YAAY,EACZ,gBAAgB,EAChB,mBAAmB,EACnB,aAAa,EACb,eAAe,EACf,cAAc,EACd,kBAAkB,EAClB,cAAc,EACd,cAAc,EACd,eAAe,GAChB,MAAM,eAAe,CAAC"}
|