juneau 0.3.2 → 0.3.4

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 CHANGED
@@ -236,7 +236,16 @@ Converts ai-sdk `fullStream` to Juneau wire SSE strings. Handles all ai-sdk v7 t
236
236
 
237
237
  #### `withToolRecovery(options)`
238
238
 
239
- Two-phase pattern for Gemini-style tool calls. Phase 1 streams with tools. Phase 2 triggers only when a tool failed **and** no text was produced — it calls the model without tools and injects the failure context to force a text response. Pass `debug: true` to log phase decisions and the `textProduced` / `hadFailure` state at each decision point.
239
+ Multi-phase pattern for Gemini-style tool calls. Phase 1 streams with tools. Phase 2 triggers only when a tool failed **and** no text was produced — it calls the model without tools and injects the failure context to force a text response. Phase 3 (optional) handles the silent-success case — Gemini 2.5 Flash often treats a successful tool call as its complete response and never writes text. When the tool succeeded but no text was produced, `phase3` receives the full phase 1 message history (resolved from the ai-sdk result's `messages` promise — includes tool-call and tool-result turns, which Gemini requires to accept the history) so a second model call without tools can summarise the result. Errors thrown by phase 2/3 are emitted as wire `error` events instead of a silent `done`. Pass `debug: true` to log phase decisions, the resolved phase 3 history, and the `textProduced` / `hadFailure` state at each decision point.
240
+
241
+ ```ts
242
+ yield* withToolRecovery({
243
+ phase1: () => streamText({ model, system, messages, tools: skillSet.tools, maxSteps: 2 }),
244
+ phase2: (ctx) => streamText({ model, system, messages: [...messages, { role: 'assistant', content: ctx }] }),
245
+ phase3: (fullMessages) => streamText({ model, system, messages: fullMessages }), // no tools — forced text
246
+ skillSet,
247
+ });
248
+ ```
240
249
 
241
250
  ---
242
251
 
@@ -1,12 +1,12 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function x(r){const s=r.map(e=>{const t=e.parts.filter(n=>n.type==="text").map(n=>n.text).join("");return{role:e.role,content:t}}),l=[];for(let e=0;e<s.length;e++){const t=s[e],n=l[l.length-1];t.role==="user"&&n?.role==="user"&&l.push({role:"assistant",content:"…"}),l.push(t)}return l.filter(e=>e.content.length>0)}function f(r){return`data: ${JSON.stringify(r)}
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function w(i){const n=i.map(o=>{const s=o.parts.filter(e=>e.type==="text").map(e=>e.text).join("");return{role:o.role,content:s}}),r=[];for(let o=0;o<n.length;o++){const s=n[o],e=r[r.length-1];s.role==="user"&&e?.role==="user"&&r.push({role:"assistant",content:"…"}),r.push(s)}return r.filter(o=>o.content.length>0)}function h(i){return`data: ${JSON.stringify(i)}
2
2
 
3
- `}function g(r,s){return r[s]??r.en}function T(r,s={}){const l=s.language??"en",e=s.debug??!1,t=[];let n=!1,o=null;const a={};for(const[i,u]of Object.entries(r))a[i]={description:u.description,parameters:u.input,execute:async h=>{e&&console.debug(`[juneau] skill "${i}" → executing, input:`,h);const y=e?Date.now():0;t.push(f({type:"activity",id:i,title:g(u.labels.running,l),status:"running",metadata:{skill:i}}));try{const c=await u.execute(h),d=e?Date.now()-y:0;return e&&console.debug(`[juneau] skill "${i}" → done in ${d}ms, result:`,c),t.push(f({type:"activity",id:i,title:g(u.labels.done,l),status:"done",metadata:{skill:i}})),c}catch(c){const d=e?Date.now()-y:0,m=c instanceof Error?c.message:String(c);e&&console.debug(`[juneau] skill "${i}" → FAILED in ${d}ms: "${m}"`);const v=u.labels.failed??{cs:"Nepodařilo se",en:"Failed"};throw t.push(f({type:"activity",id:i,title:g(v,l),status:"failed",metadata:{skill:i}})),n=!0,o=`Tool "${i}" failed: ${m}`,c}}};return{tools:a,drainActivities(){return t.splice(0,t.length)},get hadFailure(){return n},get failureContext(){return o}}}const b=new Set(["text-delta","text"]),$=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(r,s,l){const e=l?.debug??!1;for await(const t of r){const n=t,o=n.type;if(e)if(o&&b.has(o)){const a=n.text??n.textDelta;console.debug(`[juneau] streamToWire chunk: ${o} ${JSON.stringify(a??"")}`)}else o==="tool-call"?console.debug(`[juneau] streamToWire chunk: tool-call "${n.toolName??n.name??"?"}"`):o==="tool-result"?console.debug("[juneau] streamToWire chunk: tool-result (ignored)"):o&&($.has(o)?console.debug(`[juneau] streamToWire chunk: ${o} (ignored)`):console.debug(`[juneau] streamToWire chunk: ${o} (unknown)`));if(o&&b.has(o)){if(s){const i=s.drainActivities();e&&i.length>0&&console.debug(`[juneau] streamToWire → draining ${i.length} activities`);for(const u of i)yield u}const a=n.text??n.textDelta;a&&(e&&console.debug(`[juneau] streamToWire → yielding text ${JSON.stringify(a)}`),yield`data: ${JSON.stringify({type:"text",text:a})}
3
+ `}function y(i,n){return i[n]??i.en}function j(i,n={}){const r=n.language??"en",o=n.debug??!1,s=[];let e=!1,a=null;const u={};for(const[t,l]of Object.entries(i))u[t]={description:l.description,parameters:l.input,execute:async d=>{o&&console.debug(`[juneau] skill "${t}" → executing, input:`,d);const p=o?Date.now():0;s.push(h({type:"activity",id:t,title:y(l.labels.running,r),status:"running",metadata:{skill:t}}));try{const c=await l.execute(d),g=o?Date.now()-p:0;return o&&console.debug(`[juneau] skill "${t}" → done in ${g}ms, result:`,c),s.push(h({type:"activity",id:t,title:y(l.labels.done,r),status:"done",metadata:{skill:t}})),c}catch(c){const g=o?Date.now()-p:0,m=c instanceof Error?c.message:String(c);o&&console.debug(`[juneau] skill "${t}" → FAILED in ${g}ms: "${m}"`);const T=l.labels.failed??{cs:"Nepodařilo se",en:"Failed"};throw s.push(h({type:"activity",id:t,title:y(T,r),status:"failed",metadata:{skill:t}})),e=!0,a=`Tool "${t}" failed: ${m}`,c}}};return{tools:u,drainActivities(){return s.splice(0,s.length)},get hadFailure(){return e},get failureContext(){return a}}}const b=new Set(["text-delta","text"]),x=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*f(i,n,r){const o=r?.debug??!1;for await(const s of i){const e=s,a=e.type;if(o)if(a&&b.has(a)){const u=e.text??e.textDelta;console.debug(`[juneau] streamToWire chunk: ${a} ${JSON.stringify(u??"")}`)}else a==="tool-call"?console.debug(`[juneau] streamToWire chunk: tool-call "${e.toolName??e.name??"?"}"`):a==="tool-result"?console.debug("[juneau] streamToWire chunk: tool-result (ignored)"):a&&(x.has(a)?console.debug(`[juneau] streamToWire chunk: ${a} (ignored)`):console.debug(`[juneau] streamToWire chunk: ${a} (unknown)`));if(a&&b.has(a)){if(n){const t=n.drainActivities();o&&t.length>0&&console.debug(`[juneau] streamToWire → draining ${t.length} activities`);for(const l of t)yield l}const u=e.text??e.textDelta;u&&(o&&console.debug(`[juneau] streamToWire → yielding text ${JSON.stringify(u)}`),yield`data: ${JSON.stringify({type:"text",text:u})}
4
4
 
5
- `)}}if(s){const t=s.drainActivities();e&&t.length>0&&console.debug(`[juneau] streamToWire → draining ${t.length} activities (end of stream)`);for(const n of t)yield n}e&&console.debug("[juneau] streamToWire → end of stream, emitting done"),yield`data: ${JSON.stringify({type:"done"})}
5
+ `)}}if(n){const s=n.drainActivities();o&&s.length>0&&console.debug(`[juneau] streamToWire → draining ${s.length} activities (end of stream)`);for(const e of s)yield e}o&&console.debug("[juneau] streamToWire → end of stream, emitting done"),yield`data: ${JSON.stringify({type:"done"})}
6
6
 
7
- `}async function*j(r){const{phase1:s,phase2:l,skillSet:e,debug:t=!1}=r;t&&console.debug("[juneau] withToolRecovery → phase 1 start");let n=!1;const o=s();for await(const a of p(o.fullStream,e,{debug:t}))a.includes('"type":"text"')&&(n=!0),!a.includes('"type":"done"')&&(yield a);if(t&&console.debug(`[juneau] withToolRecovery → phase 1 complete, textProduced=${n}, hadFailure=${e.hadFailure}`),e.hadFailure&&!n&&e.failureContext){t&&console.debug("[juneau] withToolRecovery → hadFailure=true, textProduced=false → triggering phase 2");const a=l(e.failureContext);yield*p(a.fullStream,void 0,{debug:t}),t&&console.debug("[juneau] withToolRecovery → phase 2 complete")}else!n&&!e.hadFailure?(t&&console.debug("[juneau] withToolRecovery → no failure, no text — emitting done (possible Gemini silent response)"),yield`data: ${JSON.stringify({type:"done"})}
7
+ `}function v(i){return`data: ${JSON.stringify({type:"error",message:i})}
8
8
 
9
- `):yield`data: ${JSON.stringify({type:"done"})}
9
+ `}function $(){return`data: ${JSON.stringify({type:"done"})}
10
10
 
11
- `}exports.createSkillSet=T;exports.streamToWire=p;exports.toSdkMessages=x;exports.withToolRecovery=j;
11
+ `}async function*S(i){const{phase1:n,phase2:r,phase3:o,skillSet:s,debug:e=!1}=i;e&&console.debug("[juneau] withToolRecovery → phase 1 start");let a=!1;const u=n();for await(const t of f(u.fullStream,s,{debug:e}))t.includes('"type":"text"')&&(a=!0),!t.includes('"type":"done"')&&(yield t);if(e&&console.debug(`[juneau] withToolRecovery → phase 1 complete, textProduced=${a}, hadFailure=${s.hadFailure}`),s.hadFailure&&!a&&s.failureContext){e&&console.debug("[juneau] withToolRecovery → hadFailure=true, textProduced=false → triggering phase 2");try{const t=r(s.failureContext);yield*f(t.fullStream,void 0,{debug:e}),e&&console.debug("[juneau] withToolRecovery → phase 2 complete")}catch(t){const l=t instanceof Error?t.message:String(t);e&&console.debug(`[juneau] withToolRecovery → phase 2 FAILED: "${l}"`),yield v(l)}return}if(!a&&!s.hadFailure&&o){const t=await k(u);if(t){e&&(console.debug(`[juneau] withToolRecovery → phase 3 messages resolved (${t.length}):`,JSON.stringify(t,null,2)),R(t)||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{yield*f(o(t).fullStream,void 0,{debug:e}),e&&console.debug("[juneau] withToolRecovery → phase 3 complete")}catch(l){const d=l instanceof Error?l.message:String(l);e&&console.debug(`[juneau] withToolRecovery → phase 3 FAILED: "${d}"`),yield v(d)}return}e&&console.debug("[juneau] withToolRecovery → phase 3 configured but phase 1 result exposes no message history — emitting done")}else!a&&!s.hadFailure&&e&&console.debug("[juneau] withToolRecovery → no failure, no text, no phase3 — emitting done (Gemini silent response)");yield $()}async function k(i){if(i.messages){const n=await i.messages;if(Array.isArray(n)&&n.length>0)return n}if(i.response){const n=await i.response;if(Array.isArray(n?.messages)&&n.messages.length>0)return n.messages}return null}function R(i){return i.some(n=>{const r=n;return r.role==="tool"?!0:Array.isArray(r.content)?r.content.some(o=>o.type==="tool-result"):!1})}exports.createSkillSet=j;exports.streamToWire=f;exports.toSdkMessages=w;exports.withToolRecovery=S;
12
12
  //# 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';\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 two-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, maxSteps: 2 (or higher). Collect whether any\n * text was produced and whether a tool failure occurred.\n *\n * Phase 2 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 * Silent-success path (hadFailure=false, textProduced=false):\n * - Gemini called the tool successfully but wrote nothing. This is a known\n * Gemini 2.5 Flash behaviour when maxSteps > 1: the tool result and the\n * model's reply text arrive as separate steps, and text-delta may not be\n * emitted by the time phase 1's fullStream is exhausted. The debug logs\n * will reveal the exact chunk sequence. In this state we still emit done\n * cleanly — the consumer can decide whether to retry.\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, 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\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 } else if (!producedText && !skillSet.hadFailure) {\n // Tool succeeded but model emitted no text — Gemini silent-response scenario.\n // Log clearly so the consumer can see this in debug output and diagnose\n // whether text arrived in a different chunk type or was simply not generated.\n if (debug) {\n console.debug(\n '[juneau] withToolRecovery → no failure, no text — emitting done (possible Gemini silent response)'\n );\n }\n\n yield `data: ${JSON.stringify({ type: 'done' })}\\n\\n`;\n } else {\n // Normal success — text was produced, 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","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","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,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A,CAAO,EAExEkB,EAAM,SAAS,eAAe,IAChCQ,EAAe,IAIb,CAAAR,EAAM,SAAS,eAAe,IAIlC,MAAMA,GASR,GANIlB,GACF,QAAQ,MACN,8DAA8D0B,CAAY,gBAAgBT,EAAS,UAAU,EAAA,EAI7GA,EAAS,YAAc,CAACS,GAAgBT,EAAS,eAAgB,CAE/DjB,GACF,QAAQ,MAAM,sFAAsF,EAGtG,MAAM4B,EAAUH,EAAOR,EAAS,cAAc,EAG9C,MAAOF,EAAaa,EAAQ,WAAY,OAAW,CAAE,MAAA5B,EAAO,EAExDA,GACF,QAAQ,MAAM,8CAA8C,CAEhE,KAAW,CAAC0B,GAAgB,CAACT,EAAS,YAIhCjB,GACF,QAAQ,MACN,mGAAA,EAIJ,KAAM,SAAS,KAAK,UAAU,CAAE,KAAM,OAAQ,CAAC;AAAA;AAAA,GAG/C,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\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 * 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, 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 try {\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 } 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 yield* streamToWire(phase3(fullMessages).fullStream, undefined, { debug });\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 3 complete');\n }\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 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?: Promise<unknown[]>;\n response?: Promise<{ 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","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","wireError","wireDone","withToolRecovery","phase1","phase2","phase3","producedText","result1","result2","fullMessages","resolvePhase1Messages","containsToolResult","response","m","part"],"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,E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AIA,EAAO,SAAU,CACnB,MAAML,EAAW,MAAMK,EAAO,SAC9B,GAAI,MAAM,QAAQL,CAAQ,GAAKA,EAAS,OAAS,EAC/C,OAAOA,CAEX,CAEA,GAAIK,EAAO,SAAU,CACnB,MAAM+C,EAAW,MAAM/C,EAAO,SAC9B,GAAI,MAAM,QAAQ+C,GAAU,QAAQ,GAAKA,EAAS,SAAS,OAAS,EAClE,OAAOA,EAAS,QAEpB,CAEA,OAAO,IACT,CAOA,SAASD,EAAmBnD,EAA8B,CACxD,OAAOA,EAAS,KAAMqD,GAAM,CAC1B,MAAMnD,EAAMmD,EACZ,OAAInD,EAAI,OAAS,OAAe,GAC5B,MAAM,QAAQA,EAAI,OAAO,EACpBA,EAAI,QAAQ,KAChBoD,GAAUA,EAA2B,OAAS,aAAA,EAG5C,EACT,CAAC,CACH"}
@@ -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, StreamToWireOptions, 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,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,83 +1,83 @@
1
- function $(r) {
2
- const s = r.map((e) => {
3
- const t = e.parts.filter((n) => n.type === "text").map((n) => n.text).join("");
4
- return { role: e.role, content: t };
5
- }), l = [];
6
- for (let e = 0; e < s.length; e++) {
7
- const t = s[e], n = l[l.length - 1];
8
- t.role === "user" && n?.role === "user" && l.push({ role: "assistant", content: "…" }), l.push(t);
1
+ function S(i) {
2
+ const o = i.map((n) => {
3
+ const s = n.parts.filter((e) => e.type === "text").map((e) => e.text).join("");
4
+ return { role: n.role, content: s };
5
+ }), r = [];
6
+ for (let n = 0; n < o.length; n++) {
7
+ const s = o[n], e = r[r.length - 1];
8
+ s.role === "user" && e?.role === "user" && r.push({ role: "assistant", content: "…" }), r.push(s);
9
9
  }
10
- return l.filter((e) => e.content.length > 0);
10
+ return r.filter((n) => n.content.length > 0);
11
11
  }
12
- function f(r) {
13
- return `data: ${JSON.stringify(r)}
12
+ function g(i) {
13
+ return `data: ${JSON.stringify(i)}
14
14
 
15
15
  `;
16
16
  }
17
- function g(r, s) {
18
- return r[s] ?? r.en;
17
+ function h(i, o) {
18
+ return i[o] ?? i.en;
19
19
  }
20
- function T(r, s = {}) {
21
- const l = s.language ?? "en", e = s.debug ?? !1, t = [];
22
- let n = !1, o = null;
23
- const a = {};
24
- for (const [i, u] of Object.entries(r))
25
- a[i] = {
26
- description: u.description,
27
- parameters: u.input,
28
- execute: async (p) => {
29
- e && console.debug(`[juneau] skill "${i}" → executing, input:`, p);
30
- const h = e ? Date.now() : 0;
31
- t.push(
32
- f({
20
+ function k(i, o = {}) {
21
+ const r = o.language ?? "en", n = o.debug ?? !1, s = [];
22
+ let e = !1, a = null;
23
+ const u = {};
24
+ for (const [t, l] of Object.entries(i))
25
+ u[t] = {
26
+ description: l.description,
27
+ parameters: l.input,
28
+ execute: async (d) => {
29
+ n && console.debug(`[juneau] skill "${t}" → executing, input:`, d);
30
+ const p = n ? Date.now() : 0;
31
+ s.push(
32
+ g({
33
33
  type: "activity",
34
- id: i,
35
- title: g(u.labels.running, l),
34
+ id: t,
35
+ title: h(l.labels.running, r),
36
36
  status: "running",
37
- metadata: { skill: i }
37
+ metadata: { skill: t }
38
38
  })
39
39
  );
40
40
  try {
41
- const c = await u.execute(p), d = e ? Date.now() - h : 0;
42
- return e && console.debug(`[juneau] skill "${i}" → done in ${d}ms, result:`, c), t.push(
43
- f({
41
+ const c = await l.execute(d), f = n ? Date.now() - p : 0;
42
+ return n && console.debug(`[juneau] skill "${t}" → done in ${f}ms, result:`, c), s.push(
43
+ g({
44
44
  type: "activity",
45
- id: i,
46
- title: g(u.labels.done, l),
45
+ id: t,
46
+ title: h(l.labels.done, r),
47
47
  status: "done",
48
- metadata: { skill: i }
48
+ metadata: { skill: t }
49
49
  })
50
50
  ), c;
51
51
  } catch (c) {
52
- const d = e ? Date.now() - h : 0, y = c instanceof Error ? c.message : String(c);
53
- e && console.debug(`[juneau] skill "${i}" → FAILED in ${d}ms: "${y}"`);
54
- const x = u.labels.failed ?? { cs: "Nepodařilo se", en: "Failed" };
55
- throw t.push(
56
- f({
52
+ const f = n ? Date.now() - p : 0, m = c instanceof Error ? c.message : String(c);
53
+ n && console.debug(`[juneau] skill "${t}" → FAILED in ${f}ms: "${m}"`);
54
+ const T = l.labels.failed ?? { cs: "Nepodařilo se", en: "Failed" };
55
+ throw s.push(
56
+ g({
57
57
  type: "activity",
58
- id: i,
59
- title: g(x, l),
58
+ id: t,
59
+ title: h(T, r),
60
60
  status: "failed",
61
- metadata: { skill: i }
61
+ metadata: { skill: t }
62
62
  })
63
- ), n = !0, o = `Tool "${i}" failed: ${y}`, c;
63
+ ), e = !0, a = `Tool "${t}" failed: ${m}`, c;
64
64
  }
65
65
  }
66
66
  };
67
67
  return {
68
- tools: a,
68
+ tools: u,
69
69
  drainActivities() {
70
- return t.splice(0, t.length);
70
+ return s.splice(0, s.length);
71
71
  },
72
72
  get hadFailure() {
73
- return n;
73
+ return e;
74
74
  },
75
75
  get failureContext() {
76
- return o;
76
+ return a;
77
77
  }
78
78
  };
79
79
  }
80
- const m = /* @__PURE__ */ new Set(["text-delta", "text"]), v = /* @__PURE__ */ new Set([
80
+ const b = /* @__PURE__ */ new Set(["text-delta", "text"]), w = /* @__PURE__ */ new Set([
81
81
  "tool-call",
82
82
  "tool-result",
83
83
  "tool-input-start",
@@ -91,63 +91,118 @@ const m = /* @__PURE__ */ new Set(["text-delta", "text"]), v = /* @__PURE__ */ n
91
91
  "response-metadata",
92
92
  "stream-start"
93
93
  ]);
94
- async function* b(r, s, l) {
95
- const e = l?.debug ?? !1;
96
- for await (const t of r) {
97
- const n = t, o = n.type;
98
- if (e)
99
- if (o && m.has(o)) {
100
- const a = n.text ?? n.textDelta;
101
- console.debug(`[juneau] streamToWire chunk: ${o} ${JSON.stringify(a ?? "")}`);
102
- } else o === "tool-call" ? console.debug(`[juneau] streamToWire chunk: tool-call "${n.toolName ?? n.name ?? "?"}"`) : o === "tool-result" ? console.debug("[juneau] streamToWire chunk: tool-result (ignored)") : o && (v.has(o) ? console.debug(`[juneau] streamToWire chunk: ${o} (ignored)`) : console.debug(`[juneau] streamToWire chunk: ${o} (unknown)`));
103
- if (o && m.has(o)) {
104
- if (s) {
105
- const i = s.drainActivities();
106
- e && i.length > 0 && console.debug(`[juneau] streamToWire → draining ${i.length} activities`);
107
- for (const u of i)
108
- yield u;
94
+ async function* y(i, o, r) {
95
+ const n = r?.debug ?? !1;
96
+ for await (const s of i) {
97
+ const e = s, a = e.type;
98
+ if (n)
99
+ if (a && b.has(a)) {
100
+ const u = e.text ?? e.textDelta;
101
+ console.debug(`[juneau] streamToWire chunk: ${a} ${JSON.stringify(u ?? "")}`);
102
+ } else a === "tool-call" ? console.debug(`[juneau] streamToWire chunk: tool-call "${e.toolName ?? e.name ?? "?"}"`) : a === "tool-result" ? console.debug("[juneau] streamToWire chunk: tool-result (ignored)") : a && (w.has(a) ? console.debug(`[juneau] streamToWire chunk: ${a} (ignored)`) : console.debug(`[juneau] streamToWire chunk: ${a} (unknown)`));
103
+ if (a && b.has(a)) {
104
+ if (o) {
105
+ const t = o.drainActivities();
106
+ n && t.length > 0 && console.debug(`[juneau] streamToWire → draining ${t.length} activities`);
107
+ for (const l of t)
108
+ yield l;
109
109
  }
110
- const a = n.text ?? n.textDelta;
111
- a && (e && console.debug(`[juneau] streamToWire → yielding text ${JSON.stringify(a)}`), yield `data: ${JSON.stringify({ type: "text", text: a })}
110
+ const u = e.text ?? e.textDelta;
111
+ u && (n && console.debug(`[juneau] streamToWire → yielding text ${JSON.stringify(u)}`), yield `data: ${JSON.stringify({ type: "text", text: u })}
112
112
 
113
113
  `);
114
114
  }
115
115
  }
116
- if (s) {
117
- const t = s.drainActivities();
118
- e && t.length > 0 && console.debug(`[juneau] streamToWire → draining ${t.length} activities (end of stream)`);
119
- for (const n of t)
120
- yield n;
116
+ if (o) {
117
+ const s = o.drainActivities();
118
+ n && s.length > 0 && console.debug(`[juneau] streamToWire → draining ${s.length} activities (end of stream)`);
119
+ for (const e of s)
120
+ yield e;
121
121
  }
122
- e && console.debug("[juneau] streamToWire → end of stream, emitting done"), yield `data: ${JSON.stringify({ type: "done" })}
122
+ n && console.debug("[juneau] streamToWire → end of stream, emitting done"), yield `data: ${JSON.stringify({ type: "done" })}
123
123
 
124
124
  `;
125
125
  }
126
- async function* j(r) {
127
- const { phase1: s, phase2: l, skillSet: e, debug: t = !1 } = r;
128
- t && console.debug("[juneau] withToolRecovery → phase 1 start");
129
- let n = !1;
130
- const o = s();
131
- for await (const a of b(o.fullStream, e, { debug: t }))
132
- a.includes('"type":"text"') && (n = !0), !a.includes('"type":"done"') && (yield a);
133
- if (t && console.debug(
134
- `[juneau] withToolRecovery → phase 1 complete, textProduced=${n}, hadFailure=${e.hadFailure}`
135
- ), e.hadFailure && !n && e.failureContext) {
136
- t && console.debug("[juneau] withToolRecovery → hadFailure=true, textProduced=false → triggering phase 2");
137
- const a = l(e.failureContext);
138
- yield* b(a.fullStream, void 0, { debug: t }), t && console.debug("[juneau] withToolRecovery → phase 2 complete");
139
- } else !n && !e.hadFailure ? (t && console.debug(
140
- "[juneau] withToolRecovery → no failure, no text — emitting done (possible Gemini silent response)"
141
- ), yield `data: ${JSON.stringify({ type: "done" })}
126
+ function v(i) {
127
+ return `data: ${JSON.stringify({ type: "error", message: i })}
142
128
 
143
- `) : yield `data: ${JSON.stringify({ type: "done" })}
129
+ `;
130
+ }
131
+ function x() {
132
+ return `data: ${JSON.stringify({ type: "done" })}
144
133
 
145
134
  `;
146
135
  }
136
+ async function* R(i) {
137
+ const { phase1: o, phase2: r, phase3: n, skillSet: s, debug: e = !1 } = i;
138
+ e && console.debug("[juneau] withToolRecovery → phase 1 start");
139
+ let a = !1;
140
+ const u = o();
141
+ for await (const t of y(u.fullStream, s, { debug: e }))
142
+ t.includes('"type":"text"') && (a = !0), !t.includes('"type":"done"') && (yield t);
143
+ if (e && console.debug(
144
+ `[juneau] withToolRecovery → phase 1 complete, textProduced=${a}, hadFailure=${s.hadFailure}`
145
+ ), s.hadFailure && !a && s.failureContext) {
146
+ e && console.debug("[juneau] withToolRecovery → hadFailure=true, textProduced=false → triggering phase 2");
147
+ try {
148
+ const t = r(s.failureContext);
149
+ yield* y(t.fullStream, void 0, { debug: e }), e && console.debug("[juneau] withToolRecovery → phase 2 complete");
150
+ } catch (t) {
151
+ const l = t instanceof Error ? t.message : String(t);
152
+ e && console.debug(`[juneau] withToolRecovery → phase 2 FAILED: "${l}"`), yield v(l);
153
+ }
154
+ return;
155
+ }
156
+ if (!a && !s.hadFailure && n) {
157
+ const t = await j(u);
158
+ if (t) {
159
+ e && (console.debug(
160
+ `[juneau] withToolRecovery → phase 3 messages resolved (${t.length}):`,
161
+ JSON.stringify(t, null, 2)
162
+ ), $(t) || console.debug(
163
+ "[juneau] withToolRecovery → WARNING: resolved history contains no tool-result turn — Gemini will likely reject it as an invalid conversation structure"
164
+ ), console.debug("[juneau] withToolRecovery → no failure, no text → triggering phase 3"));
165
+ try {
166
+ yield* y(n(t).fullStream, void 0, { debug: e }), e && console.debug("[juneau] withToolRecovery → phase 3 complete");
167
+ } catch (l) {
168
+ const d = l instanceof Error ? l.message : String(l);
169
+ e && console.debug(`[juneau] withToolRecovery → phase 3 FAILED: "${d}"`), yield v(d);
170
+ }
171
+ return;
172
+ }
173
+ e && console.debug(
174
+ "[juneau] withToolRecovery → phase 3 configured but phase 1 result exposes no message history — emitting done"
175
+ );
176
+ } else !a && !s.hadFailure && e && console.debug(
177
+ "[juneau] withToolRecovery → no failure, no text, no phase3 — emitting done (Gemini silent response)"
178
+ );
179
+ yield x();
180
+ }
181
+ async function j(i) {
182
+ if (i.messages) {
183
+ const o = await i.messages;
184
+ if (Array.isArray(o) && o.length > 0)
185
+ return o;
186
+ }
187
+ if (i.response) {
188
+ const o = await i.response;
189
+ if (Array.isArray(o?.messages) && o.messages.length > 0)
190
+ return o.messages;
191
+ }
192
+ return null;
193
+ }
194
+ function $(i) {
195
+ return i.some((o) => {
196
+ const r = o;
197
+ return r.role === "tool" ? !0 : Array.isArray(r.content) ? r.content.some(
198
+ (n) => n.type === "tool-result"
199
+ ) : !1;
200
+ });
201
+ }
147
202
  export {
148
- T as createSkillSet,
149
- b as streamToWire,
150
- $ as toSdkMessages,
151
- j as withToolRecovery
203
+ k as createSkillSet,
204
+ y as streamToWire,
205
+ S as toSdkMessages,
206
+ R as withToolRecovery
152
207
  };
153
208
  //# 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';\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 two-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, maxSteps: 2 (or higher). Collect whether any\n * text was produced and whether a tool failure occurred.\n *\n * Phase 2 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 * Silent-success path (hadFailure=false, textProduced=false):\n * - Gemini called the tool successfully but wrote nothing. This is a known\n * Gemini 2.5 Flash behaviour when maxSteps > 1: the tool result and the\n * model's reply text arrive as separate steps, and text-delta may not be\n * emitted by the time phase 1's fullStream is exhausted. The debug logs\n * will reveal the exact chunk sequence. In this state we still emit done\n * cleanly — the consumer can decide whether to retry.\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, 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\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 } else if (!producedText && !skillSet.hadFailure) {\n // Tool succeeded but model emitted no text — Gemini silent-response scenario.\n // Log clearly so the consumer can see this in debug output and diagnose\n // whether text arrived in a different chunk type or was simply not generated.\n if (debug) {\n console.debug(\n '[juneau] withToolRecovery → no failure, no text — emitting done (possible Gemini silent response)'\n );\n }\n\n yield `data: ${JSON.stringify({ type: 'done' })}\\n\\n`;\n } else {\n // Normal success — text was produced, 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","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","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,UA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AU,OAAAjB,IAAQ,OAAUD;AAEpD,EAAIC,KACF,QAAQ,MAAM,2CAA2C;AAG3D,MAAI0B,IAAe;AAEnB,QAAMC,IAAUH,EAAA;AAEhB,mBAAiBN,KAASH,EAAaY,EAAQ,YAAYV,GAAU,EAAE,OAAAjB,EAAA,CAAO;AAO5E,IALIkB,EAAM,SAAS,eAAe,MAChCQ,IAAe,KAIb,CAAAR,EAAM,SAAS,eAAe,MAIlC,MAAMA;AASR,MANIlB,KACF,QAAQ;AAAA,IACN,8DAA8D0B,CAAY,gBAAgBT,EAAS,UAAU;AAAA,EAAA,GAI7GA,EAAS,cAAc,CAACS,KAAgBT,EAAS,gBAAgB;AAEnE,IAAIjB,KACF,QAAQ,MAAM,sFAAsF;AAGtG,UAAM4B,IAAUH,EAAOR,EAAS,cAAc;AAG9C,WAAOF,EAAaa,EAAQ,YAAY,QAAW,EAAE,OAAA5B,GAAO,GAExDA,KACF,QAAQ,MAAM,8CAA8C;AAAA,EAEhE,MAAA,CAAW,CAAC0B,KAAgB,CAACT,EAAS,cAIhCjB,KACF,QAAQ;AAAA,IACN;AAAA,EAAA,GAIJ,MAAM,SAAS,KAAK,UAAU,EAAE,MAAM,QAAQ,CAAC;AAAA;AAAA,KAG/C,MAAM,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\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 * 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, 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 try {\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 } 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 yield* streamToWire(phase3(fullMessages).fullStream, undefined, { debug });\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 3 complete');\n }\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 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?: Promise<unknown[]>;\n response?: Promise<{ 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","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","wireError","wireDone","withToolRecovery","phase1","phase2","phase3","producedText","result1","result2","fullMessages","resolvePhase1Messages","containsToolResult","response","m","part"],"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,MAA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D,EAAI,SAAS,SAAe,KAC5B,MAAM,QAAQA,EAAI,OAAO,IACpBA,EAAI,QAAQ;AAAA,MACjB,CAACoD,MAAUA,EAA2B,SAAS;AAAA,IAAA,IAG5C;AAAA,EACT,CAAC;AACH;"}
@@ -49,11 +49,41 @@ export interface SkillSetOptions {
49
49
  /** Emit structured console.debug logs for each skill execution. Default: false */
50
50
  debug?: boolean;
51
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 FULL message
61
+ * history — user, assistant(tool-call), and tool(tool-result) turns.
62
+ * Preferred source for phase 3; Gemini rejects histories where a tool-call
63
+ * turn is not followed by its tool-result turn.
64
+ */
65
+ messages?: Promise<unknown[]>;
66
+ /**
67
+ * Fallback only — may resolve to an incomplete subset of the history
68
+ * (observed: missing tool-result turns). Used when `messages` is unavailable.
69
+ */
70
+ response?: Promise<{
71
+ messages?: unknown[];
72
+ }>;
73
+ }
52
74
  export interface ToolRecoveryOptions {
53
- phase1: () => {
75
+ phase1: () => ToolRecoveryStreamResult;
76
+ phase2: (failureContext: string) => {
54
77
  fullStream: AsyncIterable<unknown>;
55
78
  };
56
- phase2: (failureContext: string) => {
79
+ /**
80
+ * Silent-success recovery — called when a tool succeeded but the model wrote
81
+ * no text (observed with Gemini 2.5 Flash, which treats the tool call as its
82
+ * complete response). Receives the full phase 1 message history including
83
+ * tool-call and tool-result turns; call the model again without tools so it
84
+ * is forced to summarise the tool result as text.
85
+ */
86
+ phase3?: (messages: unknown[]) => {
57
87
  fullStream: AsyncIterable<unknown>;
58
88
  };
59
89
  skillSet: SkillSet;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/server/types.ts"],"names":[],"mappings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GG;IACH,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;CAC/B;AAED,MAAM,WAAW,eAAe;IAC9B,2EAA2E;IAC3E,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,kFAAkF;IAClF,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED;;;;GAIG;AACH,MAAM,WAAW,wBAAwB;IACvC,UAAU,EAAE,aAAa,CAAC,OAAO,CAAC,CAAC;IACnC;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;IAC9B;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;QAAE,QAAQ,CAAC,EAAE,OAAO,EAAE,CAAA;KAAE,CAAC,CAAC;CAC9C;AAED,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,MAAM,wBAAwB,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,23 +1,30 @@
1
1
  import type { ToolRecoveryOptions } from './types';
2
2
  /**
3
- * Encapsulates the two-phase streaming pattern needed for Gemini 2.5 Flash
3
+ * Encapsulates the multi-phase streaming pattern needed for Gemini 2.5 Flash
4
4
  * tool call scenarios where the model either fails or silently succeeds without
5
5
  * emitting any text in the same stream pass.
6
6
  *
7
- * Phase 1: Stream with tools, maxSteps: 2 (or higher). Collect whether any
8
- * text was produced and whether a tool failure occurred.
7
+ * Phase 1: Stream with tools. Collect whether any text was produced and whether
8
+ * a tool failure occurred.
9
9
  *
10
- * Phase 2 triggers when a tool failed AND no text was produced:
10
+ * Phase 2 (failure recovery) — triggers when a tool failed AND no text was produced:
11
11
  * - Injects failureContext as an assistant message so the model is forced to
12
12
  * write a recovery text response (no tools available in phase 2).
13
13
  *
14
- * Silent-success path (hadFailure=false, textProduced=false):
15
- * - Gemini called the tool successfully but wrote nothing. This is a known
16
- * Gemini 2.5 Flash behaviour when maxSteps > 1: the tool result and the
17
- * model's reply text arrive as separate steps, and text-delta may not be
18
- * emitted by the time phase 1's fullStream is exhausted. The debug logs
19
- * will reveal the exact chunk sequence. In this state we still emit done
20
- * cleanly the consumer can decide whether to retry.
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
+ * Gemini rejects histories where a tool-call turn is not immediately followed by
20
+ * a tool-result turn ("function call turn must come immediately after a user turn
21
+ * or after a function response turn"). The history is resolved from the consumed
22
+ * phase 1 result's `messages` promise (ai-sdk v7 — resolves to all turns after
23
+ * the stream is consumed), with `response.messages` as fallback.
24
+ * If phase3 is not provided, falls back to emitting done (previous behaviour).
25
+ *
26
+ * Errors thrown by phase 2 / phase 3 model calls are surfaced as wire error
27
+ * events — never swallowed into a silent done.
21
28
  *
22
29
  * @returns AsyncIterable<string> of Juneau wire SSE strings (activities + text + done)
23
30
  */
@@ -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;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAuB,gBAAgB,CAAC,OAAO,EAAE,mBAAmB,GAAG,aAAa,CAAC,MAAM,CAAC,CA4D3F"}
1
+ {"version":3,"file":"withToolRecovery.d.ts","sourceRoot":"","sources":["../../src/server/withToolRecovery.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAWnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAuB,gBAAgB,CAAC,OAAO,EAAE,mBAAmB,GAAG,aAAa,CAAC,MAAM,CAAC,CAwG3F"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "juneau",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "description": "Open-source React/TypeScript library for AI chat UI components",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",