juneau 0.3.1 → 0.3.3

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.
@@ -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,EAAE,QAAQ,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE1E,KAAK,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,CAAC,CAAC;AAUzD;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,QAAQ,EAAE,OAAO,GAAE,eAAoB,GAAG,QAAQ,CA8ExF"}
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,EAAE,QAAQ,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE1E,KAAK,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,CAAC,CAAC;AAUzD;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,QAAQ,EAAE,OAAO,GAAE,eAAoB,GAAG,QAAQ,CAiGxF"}
@@ -1,10 +1,10 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function g(a){const i=a.map(t=>{const n=t.parts.filter(r=>r.type==="text").map(r=>r.text).join("");return{role:t.role,content:n}}),e=[];for(let t=0;t<i.length;t++){const n=i[t],r=e[e.length-1];n.role==="user"&&r?.role==="user"&&e.push({role:"assistant",content:"…"}),e.push(n)}return e.filter(t=>t.content.length>0)}function u(a){return`data: ${JSON.stringify(a)}
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function T(a){const s=a.map(n=>{const o=n.parts.filter(e=>e.type==="text").map(e=>e.text).join("");return{role:n.role,content:o}}),r=[];for(let n=0;n<s.length;n++){const o=s[n],e=r[r.length-1];o.role==="user"&&e?.role==="user"&&r.push({role:"assistant",content:"…"}),r.push(o)}return r.filter(n=>n.content.length>0)}function g(a){return`data: ${JSON.stringify(a)}
2
2
 
3
- `}function f(a,i){return a[i]??a.en}function h(a,i={}){const e=i.language??"en",t=[];let n=!1,r=null;const o={};for(const[s,l]of Object.entries(a))o[s]={description:l.description,parameters:l.input,execute:async y=>{t.push(u({type:"activity",id:s,title:f(l.labels.running,e),status:"running",metadata:{skill:s}}));try{const c=await l.execute(y);return t.push(u({type:"activity",id:s,title:f(l.labels.done,e),status:"done",metadata:{skill:s}})),c}catch(c){const p=l.labels.failed??{cs:"Nepodařilo se",en:"Failed"};throw t.push(u({type:"activity",id:s,title:f(p,e),status:"failed",metadata:{skill:s}})),n=!0,r=`Tool "${s}" failed: ${c instanceof Error?c.message:String(c)}`,c}}};return{tools:o,drainActivities(){return t.splice(0,t.length)},get hadFailure(){return n},get failureContext(){return r}}}async function*d(a,i){for await(const e of a){const t=e;if(t.type==="text-delta"){if(i)for(const r of i.drainActivities())yield r;const n=t.text??t.textDelta;n&&(yield`data: ${JSON.stringify({type:"text",text:n})}
3
+ `}function h(a,s){return a[s]??a.en}function x(a,s={}){const r=s.language??"en",n=s.debug??!1,o=[];let e=!1,i=null;const l={};for(const[t,u]of Object.entries(a))l[t]={description:u.description,parameters:u.input,execute:async p=>{n&&console.debug(`[juneau] skill "${t}" → executing, input:`,p);const y=n?Date.now():0;o.push(g({type:"activity",id:t,title:h(u.labels.running,r),status:"running",metadata:{skill:t}}));try{const c=await u.execute(p),f=n?Date.now()-y:0;return n&&console.debug(`[juneau] skill "${t}" → done in ${f}ms, result:`,c),o.push(g({type:"activity",id:t,title:h(u.labels.done,r),status:"done",metadata:{skill:t}})),c}catch(c){const f=n?Date.now()-y:0,m=c instanceof Error?c.message:String(c);n&&console.debug(`[juneau] skill "${t}" → FAILED in ${f}ms: "${m}"`);const v=u.labels.failed??{cs:"Nepodařilo se",en:"Failed"};throw o.push(g({type:"activity",id:t,title:h(v,r),status:"failed",metadata:{skill:t}})),e=!0,i=`Tool "${t}" failed: ${m}`,c}}};return{tools:l,drainActivities(){return o.splice(0,o.length)},get hadFailure(){return e},get failureContext(){return i}}}const b=new Set(["text-delta","text"]),w=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*d(a,s,r){const n=r?.debug??!1;for await(const o of a){const e=o,i=e.type;if(n)if(i&&b.has(i)){const l=e.text??e.textDelta;console.debug(`[juneau] streamToWire chunk: ${i} ${JSON.stringify(l??"")}`)}else i==="tool-call"?console.debug(`[juneau] streamToWire chunk: tool-call "${e.toolName??e.name??"?"}"`):i==="tool-result"?console.debug("[juneau] streamToWire chunk: tool-result (ignored)"):i&&(w.has(i)?console.debug(`[juneau] streamToWire chunk: ${i} (ignored)`):console.debug(`[juneau] streamToWire chunk: ${i} (unknown)`));if(i&&b.has(i)){if(s){const t=s.drainActivities();n&&t.length>0&&console.debug(`[juneau] streamToWire → draining ${t.length} activities`);for(const u of t)yield u}const l=e.text??e.textDelta;l&&(n&&console.debug(`[juneau] streamToWire → yielding text ${JSON.stringify(l)}`),yield`data: ${JSON.stringify({type:"text",text:l})}
4
4
 
5
- `)}}if(i)for(const e of i.drainActivities())yield e;yield`data: ${JSON.stringify({type:"done"})}
5
+ `)}}if(s){const o=s.drainActivities();n&&o.length>0&&console.debug(`[juneau] streamToWire → draining ${o.length} activities (end of stream)`);for(const e of o)yield e}n&&console.debug("[juneau] streamToWire → end of stream, emitting done"),yield`data: ${JSON.stringify({type:"done"})}
6
6
 
7
- `}async function*x(a){const{phase1:i,phase2:e,skillSet:t}=a;let n=!1;const r=i();for await(const o of d(r.fullStream,t))o.includes('"type":"text"')&&(n=!0),!o.includes('"type":"done"')&&(yield o);if(t.hadFailure&&!n&&t.failureContext){const o=e(t.failureContext);yield*d(o.fullStream)}else yield`data: ${JSON.stringify({type:"done"})}
7
+ `}async function*j(a){const{phase1:s,phase2:r,phase3:n,skillSet:o,debug:e=!1}=a;e&&console.debug("[juneau] withToolRecovery → phase 1 start");let i=!1;const l=s();for await(const t of d(l.fullStream,o,{debug:e}))t.includes('"type":"text"')&&(i=!0),!t.includes('"type":"done"')&&(yield t);if(e&&console.debug(`[juneau] withToolRecovery → phase 1 complete, textProduced=${i}, hadFailure=${o.hadFailure}`),o.hadFailure&&!i&&o.failureContext){e&&console.debug("[juneau] withToolRecovery → hadFailure=true, textProduced=false → triggering phase 2");const t=r(o.failureContext);yield*d(t.fullStream,void 0,{debug:e}),e&&console.debug("[juneau] withToolRecovery → phase 2 complete");return}if(!i&&!o.hadFailure&&n){const t=await $(l);if(t){e&&console.debug(`[juneau] withToolRecovery → no failure, no text → triggering phase 3 with ${t.length} messages`),yield*d(n(t).fullStream,void 0,{debug:e}),e&&console.debug("[juneau] withToolRecovery → phase 3 complete");return}e&&console.debug("[juneau] withToolRecovery → phase 3 configured but phase 1 result exposes no message history — emitting done")}else!i&&!o.hadFailure&&e&&console.debug("[juneau] withToolRecovery → no failure, no text, no phase3 — emitting done (Gemini silent response)");yield`data: ${JSON.stringify({type:"done"})}
8
8
 
9
- `}exports.createSkillSet=h;exports.streamToWire=d;exports.toSdkMessages=g;exports.withToolRecovery=x;
9
+ `}async function $(a){if(a.response){const s=await a.response;if(Array.isArray(s?.messages))return s.messages}if(a.messages){const s=await a.messages;if(Array.isArray(s))return s}return null}exports.createSkillSet=x;exports.streamToWire=d;exports.toSdkMessages=T;exports.withToolRecovery=j;
10
10
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../../src/server/toSdkMessages.ts","../../src/server/createSkillSet.ts","../../src/server/streamToWire.ts","../../src/server/withToolRecovery.ts"],"sourcesContent":["import type { AiMessage } from '../core/types';\nimport type { CoreMessage } from './types';\n\n/**\n * Converts Juneau's AiMessage[] to the CoreMessage[] format expected by\n * ai-sdk's generateText / streamText.\n *\n * - Extracts plain text from parts (joins all type: \"text\" parts)\n * - Replaces activity-only assistant messages with an empty assistant turn\n * so conversation alternation stays valid\n * - Injects a placeholder assistant turn between consecutive user messages\n * - Filters out empty turns (unless they are a required alternation filler)\n */\nexport function toSdkMessages(messages: AiMessage[]): CoreMessage[] {\n // First pass: map each AiMessage to a CoreMessage, replacing activity-only\n // assistant messages with an empty-text assistant turn.\n const mapped: CoreMessage[] = messages.map(msg => {\n const text = msg.parts\n .filter(p => p.type === 'text')\n .map(p => (p as { type: 'text'; text: string }).text)\n .join('');\n\n return { role: msg.role as CoreMessage['role'], content: text };\n });\n\n // Second pass: inject a placeholder assistant turn between consecutive user\n // messages as a safety net for history bugs that would cause model errors.\n const result: CoreMessage[] = [];\n for (let i = 0; i < mapped.length; i++) {\n const current = mapped[i];\n const prev = result[result.length - 1];\n\n if (current.role === 'user' && prev?.role === 'user') {\n result.push({ role: 'assistant', content: '…' });\n }\n\n result.push(current);\n }\n\n // Third pass: filter out empty turns, but keep assistant placeholders that\n // serve as alternation fillers (they have content '…' set above, so they\n // won't be filtered). Only drop genuinely empty content strings.\n return result.filter(msg => msg.content.length > 0);\n}\n","import type { ZodType } from 'zod';\nimport type { SkillDefinition, SkillSet, SkillSetOptions } from './types';\n\ntype SkillMap = Record<string, SkillDefinition<ZodType>>;\n\nfunction formatActivityEvent(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 wire SSE strings\n * - hadFailure / failureContext: for driving tool failure recovery\n */\nexport function createSkillSet(skills: SkillMap, options: SkillSetOptions = {}): SkillSet {\n const language = options.language ?? 'en';\n const activityBuffer: 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 // Emit a \"running\" activity event into the buffer\n activityBuffer.push(\n formatActivityEvent({\n type: 'activity',\n id: name,\n title: pickLabel(skill.labels.running, language),\n status: 'running',\n metadata: { skill: name },\n })\n );\n\n try {\n const result = await skill.execute(input as never);\n\n // Emit a \"done\" activity event\n activityBuffer.push(\n formatActivityEvent({\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 failedLabels = skill.labels.failed ?? { cs: 'Nepodařilo se', en: 'Failed' };\n\n // Emit a \"failed\" activity event\n activityBuffer.push(\n formatActivityEvent({\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: ${err instanceof Error ? err.message : String(err)}`;\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 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 * Converts ai-sdk's fullStream AsyncIterable into Juneau wire SSE strings.\n *\n * Handles:\n * - ai-sdk v7 chunk property rename (chunk.text) with fallback to v6 (chunk.textDelta)\n * - Flushing skillSet.drainActivities() before each text chunk\n * - A final drain after the loop ends (catches last tool call activities)\n * - Emitting the done event when the stream finishes\n */\nexport async function* streamToWire(\n fullStream: AsyncIterable<unknown>,\n skillSet?: SkillSet\n): AsyncIterable<string> {\n for await (const chunk of fullStream) {\n const c = chunk as Record<string, unknown>;\n\n if (c.type === 'text-delta') {\n // Flush any buffered activity events before emitting text\n if (skillSet) {\n for (const event of skillSet.drainActivities()) {\n yield event;\n }\n }\n\n // ai-sdk v7 uses `text`, v6 used `textDelta`\n const text = (c.text ?? c.textDelta) as string | undefined;\n if (text) {\n yield `data: ${JSON.stringify({ type: 'text', text })}\\n\\n`;\n }\n }\n\n // tool-call and tool-result chunks are handled silently — the SkillSet\n // execute fn emits activity events into its buffer which we drain above.\n }\n\n // Final drain — catches activity events from the last tool call that fired\n // after the last text-delta (or when there were no text deltas at all).\n if (skillSet) {\n for (const event of skillSet.drainActivities()) {\n yield event;\n }\n }\n\n yield `data: ${JSON.stringify({ type: 'done' })}\\n\\n`;\n}\n","import type { ToolRecoveryOptions } from './types';\nimport { streamToWire } from './streamToWire';\n\n/**\n * Encapsulates the two-phase streaming pattern needed when a tool fails and\n * the model retries the tool instead of writing text (observed with Gemini 2.5 Flash).\n *\n * Phase 1: Stream with tools, maxSteps: 1. Collect whether any text was produced.\n * Phase 2: If a tool failed and no text was produced, call the model again without\n * tools, injecting the failure context as an assistant message so the model\n * is forced to write a text response.\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, skillSet } = options;\n\n let producedText = false;\n\n const result1 = phase1();\n\n for await (const chunk of streamToWire(result1.fullStream, skillSet)) {\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 // Don't yield the done event yet — we may need to continue with phase 2\n if (chunk.includes('\"type\":\"done\"')) {\n continue;\n }\n\n yield chunk;\n }\n\n // If a tool failed and the model produced no text, run phase 2 to force a\n // text response without tools available.\n if (skillSet.hadFailure && !producedText && skillSet.failureContext) {\n const result2 = phase2(skillSet.failureContext);\n\n // Phase 2 has no skillSet — plain text stream, no tool calls\n yield* streamToWire(result2.fullStream);\n } else {\n // All good — emit done\n yield `data: ${JSON.stringify({ type: 'done' })}\\n\\n`;\n }\n}\n"],"names":["toSdkMessages","messages","mapped","msg","text","p","result","i","current","prev","formatActivityEvent","event","pickLabel","labels","language","createSkillSet","skills","options","activityBuffer","hadFailure","failureContext","tools","name","skill","input","err","failedLabels","streamToWire","fullStream","skillSet","chunk","c","withToolRecovery","phase1","phase2","producedText","result1","result2"],"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,EAAoBC,EAAwC,CACnE,MAAO,SAAS,KAAK,UAAUA,CAAK,CAAC;AAAA;AAAA,CACvC,CAEA,SAASC,EAAUC,EAAoCC,EAA0B,CAC/E,OAAQD,EAAkCC,CAAQ,GAAKD,EAAO,EAChE,CAQO,SAASE,EAAeC,EAAkBC,EAA2B,GAAc,CACxF,MAAMH,EAAWG,EAAQ,UAAY,KAC/BC,EAA2B,CAAA,EACjC,IAAIC,EAAa,GACbC,EAAgC,KAEpC,MAAMC,EAAiC,CAAA,EAEvC,SAAW,CAACC,EAAMC,CAAK,IA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MP,EAAQ2B,EAAE,MAAQA,EAAE,UACtB3B,IACF,KAAM,SAAS,KAAK,UAAU,CAAE,KAAM,OAAQ,KAAAA,EAAM,CAAC;AAAA;AAAA,EAEzD,CAIF,CAIA,GAAIyB,EACF,UAAWlB,KAASkB,EAAS,kBAC3B,MAAMlB,EAIV,KAAM,SAAS,KAAK,UAAU,CAAE,KAAM,OAAQ,CAAC;AAAA;AAAA,CACjD,CChCA,eAAuBqB,EAAiBf,EAAqD,CAC3F,KAAM,CAAE,OAAAgB,EAAQ,OAAAC,EAAQ,SAAAL,CAAA,EAAaZ,EAErC,IAAIkB,EAAe,GAEnB,MAAMC,EAAUH,EAAA,EAEhB,gBAAiBH,KAASH,EAAaS,EAAQ,WAAYP,CAAQ,EAE7DC,EAAM,SAAS,eAAe,IAChCK,EAAe,IAIb,CAAAL,EAAM,SAAS,eAAe,IAIlC,MAAMA,GAKR,GAAID,EAAS,YAAc,CAACM,GAAgBN,EAAS,eAAgB,CACnE,MAAMQ,EAAUH,EAAOL,EAAS,cAAc,EAG9C,MAAOF,EAAaU,EAAQ,UAAU,CACxC,MAEE,KAAM,SAAS,KAAK,UAAU,CAAE,KAAM,OAAQ,CAAC;AAAA;AAAA,CAEnD"}
1
+ {"version":3,"file":"index.cjs","sources":["../../src/server/toSdkMessages.ts","../../src/server/createSkillSet.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, SkillSet, SkillSetOptions } from './types';\n\ntype SkillMap = Record<string, SkillDefinition<ZodType>>;\n\nfunction formatActivityEvent(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 wire SSE strings\n * - hadFailure / failureContext: for driving tool failure recovery\n */\nexport function createSkillSet(skills: SkillMap, options: SkillSetOptions = {}): SkillSet {\n const language = options.language ?? 'en';\n const debug = options.debug ?? false;\n const activityBuffer: 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 (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 formatActivityEvent({\n type: 'activity',\n id: name,\n title: pickLabel(skill.labels.running, language),\n status: 'running',\n metadata: { skill: name },\n })\n );\n\n try {\n const result = await skill.execute(input as never);\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 formatActivityEvent({\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 formatActivityEvent({\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 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, 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\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 * resolved from the ai-sdk result's `response`/`messages` promise) so the model\n * can be called again without tools and forced to summarise the tool result.\n * If phase3 is not provided, falls back to emitting done (previous behaviour).\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, debug = false } = options;\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 1 start');\n }\n\n let producedText = false;\n\n const result1 = phase1();\n\n for await (const chunk of streamToWire(result1.fullStream, skillSet, { debug })) {\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 const result2 = phase2(skillSet.failureContext);\n\n // Phase 2 has no skillSet — plain text response, no tool calls expected\n yield* streamToWire(result2.fullStream, undefined, { debug });\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 2 complete');\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 → no failure, no text → triggering phase 3 with ${fullMessages.length} messages`\n );\n }\n\n yield* streamToWire(phase3(fullMessages).fullStream, undefined, { debug });\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 3 complete');\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 yield `data: ${JSON.stringify({ type: 'done' })}\\n\\n`;\n}\n\n/**\n * Resolves the full message history (incl. tool-call/tool-result turns) from a\n * consumed ai-sdk StreamTextResult. ai-sdk v7 exposes it as `response.messages`;\n * some versions expose a `messages` promise directly. Both resolve only after\n * the fullStream has been fully consumed, which is guaranteed at the call site.\n */\nasync function resolvePhase1Messages(result: {\n response?: Promise<{ messages: unknown[] }>;\n messages?: Promise<unknown[]>;\n}): Promise<unknown[] | null> {\n if (result.response) {\n const response = await result.response;\n if (Array.isArray(response?.messages)) {\n return response.messages;\n }\n }\n\n if (result.messages) {\n const messages = await result.messages;\n if (Array.isArray(messages)) {\n return messages;\n }\n }\n\n return null;\n}\n"],"names":["toSdkMessages","messages","mapped","msg","text","p","result","i","current","prev","formatActivityEvent","event","pickLabel","labels","language","createSkillSet","skills","options","debug","activityBuffer","hadFailure","failureContext","tools","name","skill","input","startMs","durationMs","err","message","failedLabels","TEXT_CHUNK_TYPES","IGNORED_CHUNK_TYPES","streamToWire","fullStream","skillSet","chunk","c","type","activities","remaining","withToolRecovery","phase1","phase2","phase3","producedText","result1","result2","fullMessages","resolvePhase1Messages","response"],"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,I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Ib,CAAAT,EAAM,SAAS,eAAe,IAIlC,MAAMA,GASR,GANIlB,GACF,QAAQ,MACN,8DAA8D2B,CAAY,gBAAgBV,EAAS,UAAU,EAAA,EAI7GA,EAAS,YAAc,CAACU,GAAgBV,EAAS,eAAgB,CAE/DjB,GACF,QAAQ,MAAM,sFAAsF,EAGtG,MAAM6B,EAAUJ,EAAOR,EAAS,cAAc,EAG9C,MAAOF,EAAac,EAAQ,WAAY,OAAW,CAAE,MAAA7B,EAAO,EAExDA,GACF,QAAQ,MAAM,8CAA8C,EAE9D,MACF,CAEA,GAAI,CAAC2B,GAAgB,CAACV,EAAS,YAAcS,EAAQ,CAInD,MAAMI,EAAe,MAAMC,EAAsBH,CAAO,EAExD,GAAIE,EAAc,CACZ9B,GACF,QAAQ,MACN,6EAA6E8B,EAAa,MAAM,WAAA,EAIpG,MAAOf,EAAaW,EAAOI,CAAY,EAAE,WAAY,OAAW,CAAE,MAAA9B,EAAO,EAErEA,GACF,QAAQ,MAAM,8CAA8C,EAE9D,MACF,CAEIA,GACF,QAAQ,MACN,8GAAA,CAGN,KAAW,CAAC2B,GAAgB,CAACV,EAAS,YAAcjB,GAClD,QAAQ,MACN,qGAAA,EAIJ,KAAM,SAAS,KAAK,UAAU,CAAE,KAAM,OAAQ,CAAC;AAAA;AAAA,CACjD,CAQA,eAAe+B,EAAsB3C,EAGP,CAC5B,GAAIA,EAAO,SAAU,CACnB,MAAM4C,EAAW,MAAM5C,EAAO,SAC9B,GAAI,MAAM,QAAQ4C,GAAU,QAAQ,EAClC,OAAOA,EAAS,QAEpB,CAEA,GAAI5C,EAAO,SAAU,CACnB,MAAML,EAAW,MAAMK,EAAO,SAC9B,GAAI,MAAM,QAAQL,CAAQ,EACxB,OAAOA,CAEX,CAEA,OAAO,IACT"}
@@ -2,5 +2,5 @@ export { toSdkMessages } from './toSdkMessages';
2
2
  export { createSkillSet } from './createSkillSet';
3
3
  export { streamToWire } from './streamToWire';
4
4
  export { withToolRecovery } from './withToolRecovery';
5
- export type { SkillSet, SkillDefinition, SkillSetOptions, ToolRecoveryOptions, CoreMessage } from './types';
5
+ export type { SkillSet, SkillDefinition, SkillSetOptions, ToolRecoveryOptions, ToolRecoveryStreamResult, StreamToWireOptions, CoreMessage } from './types';
6
6
  //# 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,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,YAAY,EAAE,QAAQ,EAAE,eAAe,EAAE,eAAe,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,SAAS,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,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,YAAY,EAAE,QAAQ,EAAE,eAAe,EAAE,eAAe,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC"}
@@ -1,116 +1,178 @@
1
- function h(a) {
2
- const n = a.map((t) => {
3
- const i = t.parts.filter((r) => r.type === "text").map((r) => r.text).join("");
4
- return { role: t.role, content: i };
5
- }), e = [];
6
- for (let t = 0; t < n.length; t++) {
7
- const i = n[t], r = e[e.length - 1];
8
- i.role === "user" && r?.role === "user" && e.push({ role: "assistant", content: "…" }), e.push(i);
1
+ function w(a) {
2
+ const s = a.map((n) => {
3
+ const o = n.parts.filter((e) => e.type === "text").map((e) => e.text).join("");
4
+ return { role: n.role, content: o };
5
+ }), r = [];
6
+ for (let n = 0; n < s.length; n++) {
7
+ const o = s[n], e = r[r.length - 1];
8
+ o.role === "user" && e?.role === "user" && r.push({ role: "assistant", content: "…" }), r.push(o);
9
9
  }
10
- return e.filter((t) => t.content.length > 0);
10
+ return r.filter((n) => n.content.length > 0);
11
11
  }
12
- function u(a) {
12
+ function f(a) {
13
13
  return `data: ${JSON.stringify(a)}
14
14
 
15
15
  `;
16
16
  }
17
- function f(a, n) {
18
- return a[n] ?? a.en;
17
+ function g(a, s) {
18
+ return a[s] ?? a.en;
19
19
  }
20
- function g(a, n = {}) {
21
- const e = n.language ?? "en", t = [];
22
- let i = !1, r = null;
23
- const s = {};
24
- for (const [o, l] of Object.entries(a))
25
- s[o] = {
26
- description: l.description,
27
- parameters: l.input,
20
+ function $(a, s = {}) {
21
+ const r = s.language ?? "en", n = s.debug ?? !1, o = [];
22
+ let e = !1, i = null;
23
+ const l = {};
24
+ for (const [t, u] of Object.entries(a))
25
+ l[t] = {
26
+ description: u.description,
27
+ parameters: u.input,
28
28
  execute: async (p) => {
29
- t.push(
30
- u({
29
+ n && console.debug(`[juneau] skill "${t}" → executing, input:`, p);
30
+ const y = n ? Date.now() : 0;
31
+ o.push(
32
+ f({
31
33
  type: "activity",
32
- id: o,
33
- title: f(l.labels.running, e),
34
+ id: t,
35
+ title: g(u.labels.running, r),
34
36
  status: "running",
35
- metadata: { skill: o }
37
+ metadata: { skill: t }
36
38
  })
37
39
  );
38
40
  try {
39
- const c = await l.execute(p);
40
- return t.push(
41
- u({
41
+ const c = await u.execute(p), d = n ? Date.now() - y : 0;
42
+ return n && console.debug(`[juneau] skill "${t}" → done in ${d}ms, result:`, c), o.push(
43
+ f({
42
44
  type: "activity",
43
- id: o,
44
- title: f(l.labels.done, e),
45
+ id: t,
46
+ title: g(u.labels.done, r),
45
47
  status: "done",
46
- metadata: { skill: o }
48
+ metadata: { skill: t }
47
49
  })
48
50
  ), c;
49
51
  } catch (c) {
50
- const y = l.labels.failed ?? { cs: "Nepodařilo se", en: "Failed" };
51
- throw t.push(
52
- u({
52
+ const d = n ? Date.now() - y : 0, m = c instanceof Error ? c.message : String(c);
53
+ n && console.debug(`[juneau] skill "${t}" → FAILED in ${d}ms: "${m}"`);
54
+ const v = u.labels.failed ?? { cs: "Nepodařilo se", en: "Failed" };
55
+ throw o.push(
56
+ f({
53
57
  type: "activity",
54
- id: o,
55
- title: f(y, e),
58
+ id: t,
59
+ title: g(v, r),
56
60
  status: "failed",
57
- metadata: { skill: o }
61
+ metadata: { skill: t }
58
62
  })
59
- ), i = !0, r = `Tool "${o}" failed: ${c instanceof Error ? c.message : String(c)}`, c;
63
+ ), e = !0, i = `Tool "${t}" failed: ${m}`, c;
60
64
  }
61
65
  }
62
66
  };
63
67
  return {
64
- tools: s,
68
+ tools: l,
65
69
  drainActivities() {
66
- return t.splice(0, t.length);
70
+ return o.splice(0, o.length);
67
71
  },
68
72
  get hadFailure() {
69
- return i;
73
+ return e;
70
74
  },
71
75
  get failureContext() {
72
- return r;
76
+ return i;
73
77
  }
74
78
  };
75
79
  }
76
- async function* d(a, n) {
77
- for await (const e of a) {
78
- const t = e;
79
- if (t.type === "text-delta") {
80
- if (n)
81
- for (const r of n.drainActivities())
82
- yield r;
83
- const i = t.text ?? t.textDelta;
84
- i && (yield `data: ${JSON.stringify({ type: "text", text: i })}
80
+ const b = /* @__PURE__ */ new Set(["text-delta", "text"]), x = /* @__PURE__ */ new Set([
81
+ "tool-call",
82
+ "tool-result",
83
+ "tool-input-start",
84
+ "tool-input-delta",
85
+ "tool-input-available",
86
+ "tool-output-available",
87
+ "step-start",
88
+ "finish-step",
89
+ "start",
90
+ "finish",
91
+ "response-metadata",
92
+ "stream-start"
93
+ ]);
94
+ async function* h(a, s, r) {
95
+ const n = r?.debug ?? !1;
96
+ for await (const o of a) {
97
+ const e = o, i = e.type;
98
+ if (n)
99
+ if (i && b.has(i)) {
100
+ const l = e.text ?? e.textDelta;
101
+ console.debug(`[juneau] streamToWire chunk: ${i} ${JSON.stringify(l ?? "")}`);
102
+ } else i === "tool-call" ? console.debug(`[juneau] streamToWire chunk: tool-call "${e.toolName ?? e.name ?? "?"}"`) : i === "tool-result" ? console.debug("[juneau] streamToWire chunk: tool-result (ignored)") : i && (x.has(i) ? console.debug(`[juneau] streamToWire chunk: ${i} (ignored)`) : console.debug(`[juneau] streamToWire chunk: ${i} (unknown)`));
103
+ if (i && b.has(i)) {
104
+ if (s) {
105
+ const t = s.drainActivities();
106
+ n && t.length > 0 && console.debug(`[juneau] streamToWire → draining ${t.length} activities`);
107
+ for (const u of t)
108
+ yield u;
109
+ }
110
+ const l = e.text ?? e.textDelta;
111
+ l && (n && console.debug(`[juneau] streamToWire → yielding text ${JSON.stringify(l)}`), yield `data: ${JSON.stringify({ type: "text", text: l })}
85
112
 
86
113
  `);
87
114
  }
88
115
  }
89
- if (n)
90
- for (const e of n.drainActivities())
116
+ if (s) {
117
+ const o = s.drainActivities();
118
+ n && o.length > 0 && console.debug(`[juneau] streamToWire → draining ${o.length} activities (end of stream)`);
119
+ for (const e of o)
91
120
  yield e;
92
- yield `data: ${JSON.stringify({ type: "done" })}
121
+ }
122
+ n && console.debug("[juneau] streamToWire → end of stream, emitting done"), yield `data: ${JSON.stringify({ type: "done" })}
93
123
 
94
124
  `;
95
125
  }
96
- async function* x(a) {
97
- const { phase1: n, phase2: e, skillSet: t } = a;
126
+ async function* j(a) {
127
+ const { phase1: s, phase2: r, phase3: n, skillSet: o, debug: e = !1 } = a;
128
+ e && console.debug("[juneau] withToolRecovery → phase 1 start");
98
129
  let i = !1;
99
- const r = n();
100
- for await (const s of d(r.fullStream, t))
101
- s.includes('"type":"text"') && (i = !0), !s.includes('"type":"done"') && (yield s);
102
- if (t.hadFailure && !i && t.failureContext) {
103
- const s = e(t.failureContext);
104
- yield* d(s.fullStream);
105
- } else
106
- yield `data: ${JSON.stringify({ type: "done" })}
130
+ const l = s();
131
+ for await (const t of h(l.fullStream, o, { debug: e }))
132
+ t.includes('"type":"text"') && (i = !0), !t.includes('"type":"done"') && (yield t);
133
+ if (e && console.debug(
134
+ `[juneau] withToolRecovery phase 1 complete, textProduced=${i}, hadFailure=${o.hadFailure}`
135
+ ), o.hadFailure && !i && o.failureContext) {
136
+ e && console.debug("[juneau] withToolRecovery → hadFailure=true, textProduced=false → triggering phase 2");
137
+ const t = r(o.failureContext);
138
+ yield* h(t.fullStream, void 0, { debug: e }), e && console.debug("[juneau] withToolRecovery → phase 2 complete");
139
+ return;
140
+ }
141
+ if (!i && !o.hadFailure && n) {
142
+ const t = await T(l);
143
+ if (t) {
144
+ e && console.debug(
145
+ `[juneau] withToolRecovery → no failure, no text → triggering phase 3 with ${t.length} messages`
146
+ ), yield* h(n(t).fullStream, void 0, { debug: e }), e && console.debug("[juneau] withToolRecovery → phase 3 complete");
147
+ return;
148
+ }
149
+ e && console.debug(
150
+ "[juneau] withToolRecovery → phase 3 configured but phase 1 result exposes no message history — emitting done"
151
+ );
152
+ } else !i && !o.hadFailure && e && console.debug(
153
+ "[juneau] withToolRecovery → no failure, no text, no phase3 — emitting done (Gemini silent response)"
154
+ );
155
+ yield `data: ${JSON.stringify({ type: "done" })}
107
156
 
108
157
  `;
109
158
  }
159
+ async function T(a) {
160
+ if (a.response) {
161
+ const s = await a.response;
162
+ if (Array.isArray(s?.messages))
163
+ return s.messages;
164
+ }
165
+ if (a.messages) {
166
+ const s = await a.messages;
167
+ if (Array.isArray(s))
168
+ return s;
169
+ }
170
+ return null;
171
+ }
110
172
  export {
111
- g as createSkillSet,
112
- d as streamToWire,
113
- h as toSdkMessages,
114
- x as withToolRecovery
173
+ $ as createSkillSet,
174
+ h as streamToWire,
175
+ w as toSdkMessages,
176
+ j as withToolRecovery
115
177
  };
116
178
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../src/server/toSdkMessages.ts","../../src/server/createSkillSet.ts","../../src/server/streamToWire.ts","../../src/server/withToolRecovery.ts"],"sourcesContent":["import type { AiMessage } from '../core/types';\nimport type { CoreMessage } from './types';\n\n/**\n * Converts Juneau's AiMessage[] to the CoreMessage[] format expected by\n * ai-sdk's generateText / streamText.\n *\n * - Extracts plain text from parts (joins all type: \"text\" parts)\n * - Replaces activity-only assistant messages with an empty assistant turn\n * so conversation alternation stays valid\n * - Injects a placeholder assistant turn between consecutive user messages\n * - Filters out empty turns (unless they are a required alternation filler)\n */\nexport function toSdkMessages(messages: AiMessage[]): CoreMessage[] {\n // First pass: map each AiMessage to a CoreMessage, replacing activity-only\n // assistant messages with an empty-text assistant turn.\n const mapped: CoreMessage[] = messages.map(msg => {\n const text = msg.parts\n .filter(p => p.type === 'text')\n .map(p => (p as { type: 'text'; text: string }).text)\n .join('');\n\n return { role: msg.role as CoreMessage['role'], content: text };\n });\n\n // Second pass: inject a placeholder assistant turn between consecutive user\n // messages as a safety net for history bugs that would cause model errors.\n const result: CoreMessage[] = [];\n for (let i = 0; i < mapped.length; i++) {\n const current = mapped[i];\n const prev = result[result.length - 1];\n\n if (current.role === 'user' && prev?.role === 'user') {\n result.push({ role: 'assistant', content: '…' });\n }\n\n result.push(current);\n }\n\n // Third pass: filter out empty turns, but keep assistant placeholders that\n // serve as alternation fillers (they have content '…' set above, so they\n // won't be filtered). Only drop genuinely empty content strings.\n return result.filter(msg => msg.content.length > 0);\n}\n","import type { ZodType } from 'zod';\nimport type { SkillDefinition, SkillSet, SkillSetOptions } from './types';\n\ntype SkillMap = Record<string, SkillDefinition<ZodType>>;\n\nfunction formatActivityEvent(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 wire SSE strings\n * - hadFailure / failureContext: for driving tool failure recovery\n */\nexport function createSkillSet(skills: SkillMap, options: SkillSetOptions = {}): SkillSet {\n const language = options.language ?? 'en';\n const activityBuffer: 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 // Emit a \"running\" activity event into the buffer\n activityBuffer.push(\n formatActivityEvent({\n type: 'activity',\n id: name,\n title: pickLabel(skill.labels.running, language),\n status: 'running',\n metadata: { skill: name },\n })\n );\n\n try {\n const result = await skill.execute(input as never);\n\n // Emit a \"done\" activity event\n activityBuffer.push(\n formatActivityEvent({\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 failedLabels = skill.labels.failed ?? { cs: 'Nepodařilo se', en: 'Failed' };\n\n // Emit a \"failed\" activity event\n activityBuffer.push(\n formatActivityEvent({\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: ${err instanceof Error ? err.message : String(err)}`;\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 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 * Converts ai-sdk's fullStream AsyncIterable into Juneau wire SSE strings.\n *\n * Handles:\n * - ai-sdk v7 chunk property rename (chunk.text) with fallback to v6 (chunk.textDelta)\n * - Flushing skillSet.drainActivities() before each text chunk\n * - A final drain after the loop ends (catches last tool call activities)\n * - Emitting the done event when the stream finishes\n */\nexport async function* streamToWire(\n fullStream: AsyncIterable<unknown>,\n skillSet?: SkillSet\n): AsyncIterable<string> {\n for await (const chunk of fullStream) {\n const c = chunk as Record<string, unknown>;\n\n if (c.type === 'text-delta') {\n // Flush any buffered activity events before emitting text\n if (skillSet) {\n for (const event of skillSet.drainActivities()) {\n yield event;\n }\n }\n\n // ai-sdk v7 uses `text`, v6 used `textDelta`\n const text = (c.text ?? c.textDelta) as string | undefined;\n if (text) {\n yield `data: ${JSON.stringify({ type: 'text', text })}\\n\\n`;\n }\n }\n\n // tool-call and tool-result chunks are handled silently — the SkillSet\n // execute fn emits activity events into its buffer which we drain above.\n }\n\n // Final drain — catches activity events from the last tool call that fired\n // after the last text-delta (or when there were no text deltas at all).\n if (skillSet) {\n for (const event of skillSet.drainActivities()) {\n yield event;\n }\n }\n\n yield `data: ${JSON.stringify({ type: 'done' })}\\n\\n`;\n}\n","import type { ToolRecoveryOptions } from './types';\nimport { streamToWire } from './streamToWire';\n\n/**\n * Encapsulates the two-phase streaming pattern needed when a tool fails and\n * the model retries the tool instead of writing text (observed with Gemini 2.5 Flash).\n *\n * Phase 1: Stream with tools, maxSteps: 1. Collect whether any text was produced.\n * Phase 2: If a tool failed and no text was produced, call the model again without\n * tools, injecting the failure context as an assistant message so the model\n * is forced to write a text response.\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, skillSet } = options;\n\n let producedText = false;\n\n const result1 = phase1();\n\n for await (const chunk of streamToWire(result1.fullStream, skillSet)) {\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 // Don't yield the done event yet — we may need to continue with phase 2\n if (chunk.includes('\"type\":\"done\"')) {\n continue;\n }\n\n yield chunk;\n }\n\n // If a tool failed and the model produced no text, run phase 2 to force a\n // text response without tools available.\n if (skillSet.hadFailure && !producedText && skillSet.failureContext) {\n const result2 = phase2(skillSet.failureContext);\n\n // Phase 2 has no skillSet — plain text stream, no tool calls\n yield* streamToWire(result2.fullStream);\n } else {\n // All good — emit done\n yield `data: ${JSON.stringify({ type: 'done' })}\\n\\n`;\n }\n}\n"],"names":["toSdkMessages","messages","mapped","msg","text","p","result","i","current","prev","formatActivityEvent","event","pickLabel","labels","language","createSkillSet","skills","options","activityBuffer","hadFailure","failureContext","tools","name","skill","input","err","failedLabels","streamToWire","fullStream","skillSet","chunk","c","withToolRecovery","phase1","phase2","producedText","result1","result2"],"mappings":"AAaO,SAASA,EAAcC,GAAsC;AAGlE,QAAMC,IAAwBD,EAAS,IAAI,CAAAE,MAAO;AAChD,UAAMC,IAAOD,EAAI,MACd,OAAO,OAAKE,EAAE,SAAS,MAAM,EAC7B,IAAI,CAAAA,MAAMA,EAAqC,IAAI,EACnD,KAAK,EAAE;AAEV,WAAO,EAAE,MAAMF,EAAI,MAA6B,SAASC,EAAA;AAAA,EAC3D,CAAC,GAIKE,IAAwB,CAAA;AAC9B,WAASC,IAAI,GAAGA,IAAIL,EAAO,QAAQK,KAAK;AACtC,UAAMC,IAAUN,EAAOK,CAAC,GAClBE,IAAOH,EAAOA,EAAO,SAAS,CAAC;AAErC,IAAIE,EAAQ,SAAS,UAAUC,GAAM,SAAS,UAC5CH,EAAO,KAAK,EAAE,MAAM,aAAa,SAAS,KAAK,GAGjDA,EAAO,KAAKE,CAAO;AAAA,EACrB;AAKA,SAAOF,EAAO,OAAO,CAAAH,MAAOA,EAAI,QAAQ,SAAS,CAAC;AACpD;ACtCA,SAASO,EAAoBC,GAAwC;AACnE,SAAO,SAAS,KAAK,UAAUA,CAAK,CAAC;AAAA;AAAA;AACvC;AAEA,SAASC,EAAUC,GAAoCC,GAA0B;AAC/E,SAAQD,EAAkCC,CAAQ,KAAKD,EAAO;AAChE;AAQO,SAASE,EAAeC,GAAkBC,IAA2B,IAAc;AACxF,QAAMH,IAAWG,EAAQ,YAAY,MAC/BC,IAA2B,CAAA;AACj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H,EAAe,OAAO,GAAGA,EAAe,MAAM;AAAA,IACvD;AAAA,IAEA,IAAI,aAAa;AACf,aAAOC;AAAA,IACT;AAAA,IAEA,IAAI,iBAAiB;AACnB,aAAOC;AAAA,IACT;AAAA,EAAA;AAEJ;ACtFA,gBAAuBO,EACrBC,GACAC,GACuB;AACvB,mBAAiBC,KAASF,GAAY;AACpC,UAAMG,IAAID;AAEV,QAAIC,EAAE,SAAS,cAAc;AAE3B,UAAIF;AACF,mBAAWlB,KAASkB,EAAS;AAC3B,gBAAMlB;AAKV,YAAMP,IAAQ2B,EAAE,QAAQA,EAAE;AAC1B,MAAI3B,MACF,MAAM,SAAS,KAAK,UAAU,EAAE,MAAM,QAAQ,MAAAA,GAAM,CAAC;AAAA;AAAA;AAAA,IAEzD;AAAA,EAIF;AAIA,MAAIyB;AACF,eAAWlB,KAASkB,EAAS;AAC3B,YAAMlB;AAIV,QAAM,SAAS,KAAK,UAAU,EAAE,MAAM,QAAQ,CAAC;AAAA;AAAA;AACjD;AChCA,gBAAuBqB,EAAiBf,GAAqD;AAC3F,QAAM,EAAE,QAAAgB,GAAQ,QAAAC,GAAQ,UAAAL,EAAA,IAAaZ;AAErC,MAAIkB,IAAe;AAEnB,QAAMC,IAAUH,EAAA;AAEhB,mBAAiBH,KAASH,EAAaS,EAAQ,YAAYP,CAAQ;AAOjE,IALIC,EAAM,SAAS,eAAe,MAChCK,IAAe,KAIb,CAAAL,EAAM,SAAS,eAAe,MAIlC,MAAMA;AAKR,MAAID,EAAS,cAAc,CAACM,KAAgBN,EAAS,gBAAgB;AACnE,UAAMQ,IAAUH,EAAOL,EAAS,cAAc;AAG9C,WAAOF,EAAaU,EAAQ,UAAU;AAAA,EACxC;AAEE,UAAM,SAAS,KAAK,UAAU,EAAE,MAAM,QAAQ,CAAC;AAAA;AAAA;AAEnD;"}
1
+ {"version":3,"file":"index.js","sources":["../../src/server/toSdkMessages.ts","../../src/server/createSkillSet.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, SkillSet, SkillSetOptions } from './types';\n\ntype SkillMap = Record<string, SkillDefinition<ZodType>>;\n\nfunction formatActivityEvent(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 wire SSE strings\n * - hadFailure / failureContext: for driving tool failure recovery\n */\nexport function createSkillSet(skills: SkillMap, options: SkillSetOptions = {}): SkillSet {\n const language = options.language ?? 'en';\n const debug = options.debug ?? false;\n const activityBuffer: 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 (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 formatActivityEvent({\n type: 'activity',\n id: name,\n title: pickLabel(skill.labels.running, language),\n status: 'running',\n metadata: { skill: name },\n })\n );\n\n try {\n const result = await skill.execute(input as never);\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 formatActivityEvent({\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 formatActivityEvent({\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 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, 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\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 * resolved from the ai-sdk result's `response`/`messages` promise) so the model\n * can be called again without tools and forced to summarise the tool result.\n * If phase3 is not provided, falls back to emitting done (previous behaviour).\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, debug = false } = options;\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 1 start');\n }\n\n let producedText = false;\n\n const result1 = phase1();\n\n for await (const chunk of streamToWire(result1.fullStream, skillSet, { debug })) {\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 const result2 = phase2(skillSet.failureContext);\n\n // Phase 2 has no skillSet — plain text response, no tool calls expected\n yield* streamToWire(result2.fullStream, undefined, { debug });\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 2 complete');\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 → no failure, no text → triggering phase 3 with ${fullMessages.length} messages`\n );\n }\n\n yield* streamToWire(phase3(fullMessages).fullStream, undefined, { debug });\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 3 complete');\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 yield `data: ${JSON.stringify({ type: 'done' })}\\n\\n`;\n}\n\n/**\n * Resolves the full message history (incl. tool-call/tool-result turns) from a\n * consumed ai-sdk StreamTextResult. ai-sdk v7 exposes it as `response.messages`;\n * some versions expose a `messages` promise directly. Both resolve only after\n * the fullStream has been fully consumed, which is guaranteed at the call site.\n */\nasync function resolvePhase1Messages(result: {\n response?: Promise<{ messages: unknown[] }>;\n messages?: Promise<unknown[]>;\n}): Promise<unknown[] | null> {\n if (result.response) {\n const response = await result.response;\n if (Array.isArray(response?.messages)) {\n return response.messages;\n }\n }\n\n if (result.messages) {\n const messages = await result.messages;\n if (Array.isArray(messages)) {\n return messages;\n }\n }\n\n return null;\n}\n"],"names":["toSdkMessages","messages","mapped","msg","text","p","result","i","current","prev","formatActivityEvent","event","pickLabel","labels","language","createSkillSet","skills","options","debug","activityBuffer","hadFailure","failureContext","tools","name","skill","input","startMs","durationMs","err","message","failedLabels","TEXT_CHUNK_TYPES","IGNORED_CHUNK_TYPES","streamToWire","fullStream","skillSet","chunk","c","type","activities","remaining","withToolRecovery","phase1","phase2","phase3","producedText","result1","result2","fullMessages","resolvePhase1Messages","response"],"mappings":"AAaO,SAASA,EAAcC,GAAsC;AAGlE,QAAMC,IAAwBD,EAAS,IAAI,CAAAE,MAAO;AAChD,UAAMC,IAAOD,EAAI,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B,CAACV,EAAS,cAAcS,GAAQ;AAInD,UAAMI,IAAe,MAAMC,EAAsBH,CAAO;AAExD,QAAIE,GAAc;AAChB,MAAI9B,KACF,QAAQ;AAAA,QACN,6EAA6E8B,EAAa,MAAM;AAAA,MAAA,GAIpG,OAAOf,EAAaW,EAAOI,CAAY,EAAE,YAAY,QAAW,EAAE,OAAA9B,GAAO,GAErEA,KACF,QAAQ,MAAM,8CAA8C;AAE9D;AAAA,IACF;AAEA,IAAIA,KACF,QAAQ;AAAA,MACN;AAAA,IAAA;AAAA,EAGN,OAAW,CAAC2B,KAAgB,CAACV,EAAS,cAAcjB,KAClD,QAAQ;AAAA,IACN;AAAA,EAAA;AAIJ,QAAM,SAAS,KAAK,UAAU,EAAE,MAAM,QAAQ,CAAC;AAAA;AAAA;AACjD;AAQA,eAAe+B,EAAsB3C,GAGP;AAC5B,MAAIA,EAAO,UAAU;AACnB,UAAM4C,IAAW,MAAM5C,EAAO;AAC9B,QAAI,MAAM,QAAQ4C,GAAU,QAAQ;AAClC,aAAOA,EAAS;AAAA,EAEpB;AAEA,MAAI5C,EAAO,UAAU;AACnB,UAAML,IAAW,MAAMK,EAAO;AAC9B,QAAI,MAAM,QAAQL,CAAQ;AACxB,aAAOA;AAAA,EAEX;AAEA,SAAO;AACT;"}
@@ -1,12 +1,15 @@
1
- import type { SkillSet } from './types';
1
+ import type { SkillSet, StreamToWireOptions } from './types';
2
2
  /**
3
3
  * Converts ai-sdk's fullStream AsyncIterable into Juneau wire SSE strings.
4
4
  *
5
5
  * Handles:
6
- * - ai-sdk v7 chunk property rename (chunk.text) with fallback to v6 (chunk.textDelta)
7
- * - Flushing skillSet.drainActivities() before each text chunk
8
- * - A final drain after the loop ends (catches last tool call activities)
6
+ * - All text chunk types used by ai-sdk v7 (text-delta, text) incl. v6 textDelta fallback
7
+ * - Flushing skillSet.drainActivities() before each text chunk so activities
8
+ * always appear before the text they precede
9
+ * - A final drain after the loop ends (catches last-tool-call activities when
10
+ * no text follows the tool result — the Gemini silent-response scenario)
9
11
  * - Emitting the done event when the stream finishes
12
+ * - Structured debug logging of every chunk when options.debug is true
10
13
  */
11
- export declare function streamToWire(fullStream: AsyncIterable<unknown>, skillSet?: SkillSet): AsyncIterable<string>;
14
+ export declare function streamToWire(fullStream: AsyncIterable<unknown>, skillSet?: SkillSet, options?: StreamToWireOptions): AsyncIterable<string>;
12
15
  //# sourceMappingURL=streamToWire.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"streamToWire.d.ts","sourceRoot":"","sources":["../../src/server/streamToWire.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAExC;;;;;;;;GAQG;AACH,wBAAuB,YAAY,CACjC,UAAU,EAAE,aAAa,CAAC,OAAO,CAAC,EAClC,QAAQ,CAAC,EAAE,QAAQ,GAClB,aAAa,CAAC,MAAM,CAAC,CAgCvB"}
1
+ {"version":3,"file":"streamToWire.d.ts","sourceRoot":"","sources":["../../src/server/streamToWire.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAyB7D;;;;;;;;;;;GAWG;AACH,wBAAuB,YAAY,CACjC,UAAU,EAAE,aAAa,CAAC,OAAO,CAAC,EAClC,QAAQ,CAAC,EAAE,QAAQ,EACnB,OAAO,CAAC,EAAE,mBAAmB,GAC5B,aAAa,CAAC,MAAM,CAAC,CAqEvB"}
@@ -46,15 +46,48 @@ export interface SkillSet {
46
46
  export interface SkillSetOptions {
47
47
  /** Language code — determines which label variant to use. Default: 'en' */
48
48
  language?: string;
49
+ /** Emit structured console.debug logs for each skill execution. Default: false */
50
+ debug?: boolean;
51
+ }
52
+ /**
53
+ * Structural match for ai-sdk v7's StreamTextResult — only the members
54
+ * withToolRecovery needs. Juneau does not import ai-sdk; passing the result
55
+ * of streamText() satisfies this shape.
56
+ */
57
+ export interface ToolRecoveryStreamResult {
58
+ fullStream: AsyncIterable<unknown>;
59
+ /**
60
+ * ai-sdk v7: resolves after the stream is consumed to the response metadata,
61
+ * including the full message history (tool calls + tool results).
62
+ */
63
+ response?: Promise<{
64
+ messages: unknown[];
65
+ }>;
66
+ /** Some ai-sdk versions expose the message history directly. */
67
+ messages?: Promise<unknown[]>;
49
68
  }
50
69
  export interface ToolRecoveryOptions {
51
- phase1: () => {
70
+ phase1: () => ToolRecoveryStreamResult;
71
+ phase2: (failureContext: string) => {
52
72
  fullStream: AsyncIterable<unknown>;
53
73
  };
54
- phase2: (failureContext: string) => {
74
+ /**
75
+ * Silent-success recovery — called when a tool succeeded but the model wrote
76
+ * no text (observed with Gemini 2.5 Flash, which treats the tool call as its
77
+ * complete response). Receives the full phase 1 message history including
78
+ * tool-call and tool-result turns; call the model again without tools so it
79
+ * is forced to summarise the tool result as text.
80
+ */
81
+ phase3?: (messages: unknown[]) => {
55
82
  fullStream: AsyncIterable<unknown>;
56
83
  };
57
84
  skillSet: SkillSet;
85
+ /** Emit structured console.debug logs for phase decisions and chunk flow. Default: false */
86
+ debug?: boolean;
87
+ }
88
+ export interface StreamToWireOptions {
89
+ /** Emit structured console.debug logs for every ai-sdk chunk received. Default: false */
90
+ debug?: boolean;
58
91
  }
59
92
  /**
60
93
  * CoreMessage — structural match for ai-sdk's CoreMessage type.
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/server/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAEtC;;GAEG;AACH,MAAM,WAAW,eAAe,CAAC,MAAM,SAAS,OAAO,GAAG,OAAO;IAC/D,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE;QACN,OAAO,EAAE;YAAE,EAAE,EAAE,MAAM,CAAC;YAAC,EAAE,EAAE,MAAM,CAAA;SAAE,CAAC;QACpC,IAAI,EAAK;YAAE,EA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,CAAC;IACvC,MAAM,EAAE,CAAC,cAAc,EAAE,MAAM,KAAK;QAAE,UAAU,EAAE,aAAa,CAAC,OAAO,CAAC,CAAA;KAAE,CAAC;IAC3E;;;;;;OAMG;IACH,MAAM,CAAC,EAAE,CAAC,QAAQ,EAAE,OAAO,EAAE,KAAK;QAAE,UAAU,EAAE,aAAa,CAAC,OAAO,CAAC,CAAA;KAAE,CAAC;IACzE,QAAQ,EAAE,QAAQ,CAAC;IACnB,4FAA4F;IAC5F,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,mBAAmB;IAClC,yFAAyF;IACzF,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED;;;GAGG;AACH,MAAM,MAAM,WAAW,GAAG;IACxB,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,QAAQ,CAAC;IACtC,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC"}
@@ -1,12 +1,24 @@
1
1
  import type { ToolRecoveryOptions } from './types';
2
2
  /**
3
- * Encapsulates the two-phase streaming pattern needed when a tool fails and
4
- * the model retries the tool instead of writing text (observed with Gemini 2.5 Flash).
3
+ * Encapsulates the multi-phase streaming pattern needed for Gemini 2.5 Flash
4
+ * tool call scenarios where the model either fails or silently succeeds without
5
+ * emitting any text in the same stream pass.
5
6
  *
6
- * Phase 1: Stream with tools, maxSteps: 1. Collect whether any text was produced.
7
- * Phase 2: If a tool failed and no text was produced, call the model again without
8
- * tools, injecting the failure context as an assistant message so the model
9
- * is forced to write a text response.
7
+ * Phase 1: Stream with tools. Collect whether any text was produced and whether
8
+ * a tool failure occurred.
9
+ *
10
+ * Phase 2 (failure recovery) — triggers when a tool failed AND no text was produced:
11
+ * - Injects failureContext as an assistant message so the model is forced to
12
+ * write a recovery text response (no tools available in phase 2).
13
+ *
14
+ * Phase 3 (silent-success recovery) — triggers when the tool succeeded but the
15
+ * model wrote no text. Confirmed Gemini 2.5 Flash behaviour: the fullStream ends
16
+ * with tool-call → tool-result → finish-step → finish and no text-delta ever
17
+ * arrives — Gemini treats the tool call as its complete response. Phase 3 receives
18
+ * the full phase 1 message history (including tool-call and tool-result turns,
19
+ * resolved from the ai-sdk result's `response`/`messages` promise) so the model
20
+ * can be called again without tools and forced to summarise the tool result.
21
+ * If phase3 is not provided, falls back to emitting done (previous behaviour).
10
22
  *
11
23
  * @returns AsyncIterable<string> of Juneau wire SSE strings (activities + text + done)
12
24
  */
@@ -1 +1 @@
1
- {"version":3,"file":"withToolRecovery.d.ts","sourceRoot":"","sources":["../../src/server/withToolRecovery.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAGnD;;;;;;;;;;GAUG;AACH,wBAAuB,gBAAgB,CAAC,OAAO,EAAE,mBAAmB,GAAG,aAAa,CAAC,MAAM,CAAC,CAgC3F"}
1
+ {"version":3,"file":"withToolRecovery.d.ts","sourceRoot":"","sources":["../../src/server/withToolRecovery.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAGnD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAuB,gBAAgB,CAAC,OAAO,EAAE,mBAAmB,GAAG,aAAa,CAAC,MAAM,CAAC,CAiF3F"}