juneau 0.3.3 → 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 +1 -1
- package/dist/server/index.cjs +7 -5
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.js +120 -90
- package/dist/server/index.js.map +1 -1
- package/dist/server/types.d.ts +10 -5
- package/dist/server/types.d.ts.map +1 -1
- package/dist/server/withToolRecovery.d.ts +9 -3
- package/dist/server/withToolRecovery.d.ts.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -236,7 +236,7 @@ Converts ai-sdk `fullStream` to Juneau wire SSE strings. Handles all ai-sdk v7 t
|
|
|
236
236
|
|
|
237
237
|
#### `withToolRecovery(options)`
|
|
238
238
|
|
|
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 (
|
|
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
240
|
|
|
241
241
|
```ts
|
|
242
242
|
yield* withToolRecovery({
|
package/dist/server/index.cjs
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function
|
|
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
|
|
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(
|
|
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
|
-
`}
|
|
7
|
+
`}function v(i){return`data: ${JSON.stringify({type:"error",message:i})}
|
|
8
8
|
|
|
9
|
-
`}
|
|
9
|
+
`}function $(){return`data: ${JSON.stringify({type:"done"})}
|
|
10
|
+
|
|
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;
|
|
10
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 multi-phase streaming pattern needed for Gemini 2.5 Flash\n * tool call scenarios where the model either fails or silently succeeds without\n * emitting any text in the same stream pass.\n *\n * Phase 1: Stream with tools. Collect whether any text was produced and whether\n * a tool failure occurred.\n *\n * Phase 2 (failure recovery) — triggers when a tool failed AND no text was produced:\n * - Injects failureContext as an assistant message so the model is forced to\n * write a recovery text response (no tools available in phase 2).\n *\n * Phase 3 (silent-success recovery) — triggers when the tool succeeded but the\n * model wrote no text. Confirmed Gemini 2.5 Flash behaviour: the fullStream ends\n * with tool-call → tool-result → finish-step → finish and no text-delta ever\n * arrives — Gemini treats the tool call as its complete response. Phase 3 receives\n * the full phase 1 message history (including tool-call and tool-result turns,\n * resolved from the ai-sdk result's `response`/`messages` promise) so the model\n * can be called again without tools and forced to summarise the tool result.\n * If phase3 is not provided, falls back to emitting done (previous behaviour).\n *\n * @returns AsyncIterable<string> of Juneau wire SSE strings (activities + text + done)\n */\nexport async function* withToolRecovery(options: ToolRecoveryOptions): AsyncIterable<string> {\n const { phase1, phase2, phase3, skillSet, debug = false } = options;\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 1 start');\n }\n\n let producedText = false;\n\n const result1 = phase1();\n\n for await (const chunk of streamToWire(result1.fullStream, skillSet, { debug })) {\n // Track whether any text reached the wire (done event doesn't count)\n if (chunk.includes('\"type\":\"text\"')) {\n producedText = true;\n }\n\n // Hold back the done event — we may need to continue with phase 2 or 3\n if (chunk.includes('\"type\":\"done\"')) {\n continue;\n }\n\n yield chunk;\n }\n\n if (debug) {\n console.debug(\n `[juneau] withToolRecovery → phase 1 complete, textProduced=${producedText}, hadFailure=${skillSet.hadFailure}`\n );\n }\n\n if (skillSet.hadFailure && !producedText && skillSet.failureContext) {\n // Tool failed and model wrote nothing — run phase 2 to force a text response\n if (debug) {\n console.debug('[juneau] withToolRecovery → hadFailure=true, textProduced=false → triggering phase 2');\n }\n\n const result2 = phase2(skillSet.failureContext);\n\n // Phase 2 has no skillSet — plain text response, no tool calls expected\n yield* streamToWire(result2.fullStream, undefined, { debug });\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 2 complete');\n }\n return;\n }\n\n if (!producedText && !skillSet.hadFailure && phase3) {\n // Tool succeeded but model emitted no text — Gemini silent-response scenario.\n // Resolve the full message history from the consumed phase 1 result and let\n // phase 3 call the model again (no tools) to summarise the tool result.\n const fullMessages = await resolvePhase1Messages(result1);\n\n if (fullMessages) {\n if (debug) {\n console.debug(\n `[juneau] withToolRecovery → no failure, no text → triggering phase 3 with ${fullMessages.length} messages`\n );\n }\n\n yield* streamToWire(phase3(fullMessages).fullStream, undefined, { debug });\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 3 complete');\n }\n return;\n }\n\n if (debug) {\n console.debug(\n '[juneau] withToolRecovery → phase 3 configured but phase 1 result exposes no message history — emitting done'\n );\n }\n } else if (!producedText && !skillSet.hadFailure && debug) {\n console.debug(\n '[juneau] withToolRecovery → no failure, no text, no phase3 — emitting done (Gemini silent response)'\n );\n }\n\n yield `data: ${JSON.stringify({ type: 'done' })}\\n\\n`;\n}\n\n/**\n * Resolves the full message history (incl. tool-call/tool-result turns) from a\n * consumed ai-sdk StreamTextResult. ai-sdk v7 exposes it as `response.messages`;\n * some versions expose a `messages` promise directly. Both resolve only after\n * the fullStream has been fully consumed, which is guaranteed at the call site.\n */\nasync function resolvePhase1Messages(result: {\n response?: Promise<{ messages: unknown[] }>;\n messages?: Promise<unknown[]>;\n}): Promise<unknown[] | null> {\n if (result.response) {\n const response = await result.response;\n if (Array.isArray(response?.messages)) {\n return response.messages;\n }\n }\n\n if (result.messages) {\n const messages = await result.messages;\n if (Array.isArray(messages)) {\n return messages;\n }\n }\n\n return null;\n}\n"],"names":["toSdkMessages","messages","mapped","msg","text","p","result","i","current","prev","formatActivityEvent","event","pickLabel","labels","language","createSkillSet","skills","options","debug","activityBuffer","hadFailure","failureContext","tools","name","skill","input","startMs","durationMs","err","message","failedLabels","TEXT_CHUNK_TYPES","IGNORED_CHUNK_TYPES","streamToWire","fullStream","skillSet","chunk","c","type","activities","remaining","withToolRecovery","phase1","phase2","phase3","producedText","result1","result2","fullMessages","resolvePhase1Messages","response"],"mappings":"gFAaO,SAASA,EAAcC,EAAsC,CAGlE,MAAMC,EAAwBD,EAAS,IAAIE,GAAO,CAChD,MAAMC,EAAOD,EAAI,MACd,UAAYE,EAAE,OAAS,MAAM,EAC7B,IAAIA,GAAMA,EAAqC,IAAI,EACnD,KAAK,EAAE,EAEV,MAAO,CAAE,KAAMF,EAAI,KAA6B,QAASC,CAAA,CAC3D,CAAC,EAIKE,EAAwB,CAAA,EAC9B,QAASC,EAAI,EAAGA,EAAIL,EAAO,OAAQK,IAAK,CACtC,MAAMC,EAAUN,EAAOK,CAAC,EAClBE,EAAOH,EAAOA,EAAO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.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,OAA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: n.role, content:
|
|
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
5
|
}), r = [];
|
|
6
|
-
for (let n = 0; n <
|
|
7
|
-
const
|
|
8
|
-
|
|
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
10
|
return r.filter((n) => n.content.length > 0);
|
|
11
11
|
}
|
|
12
|
-
function
|
|
13
|
-
return `data: ${JSON.stringify(
|
|
12
|
+
function g(i) {
|
|
13
|
+
return `data: ${JSON.stringify(i)}
|
|
14
14
|
|
|
15
15
|
`;
|
|
16
16
|
}
|
|
17
|
-
function
|
|
18
|
-
return
|
|
17
|
+
function h(i, o) {
|
|
18
|
+
return i[o] ?? i.en;
|
|
19
19
|
}
|
|
20
|
-
function
|
|
21
|
-
const r =
|
|
22
|
-
let e = !1,
|
|
23
|
-
const
|
|
24
|
-
for (const [t,
|
|
25
|
-
|
|
26
|
-
description:
|
|
27
|
-
parameters:
|
|
28
|
-
execute: async (
|
|
29
|
-
n && console.debug(`[juneau] skill "${t}" → executing, input:`,
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
|
|
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
34
|
id: t,
|
|
35
|
-
title:
|
|
35
|
+
title: h(l.labels.running, r),
|
|
36
36
|
status: "running",
|
|
37
37
|
metadata: { skill: t }
|
|
38
38
|
})
|
|
39
39
|
);
|
|
40
40
|
try {
|
|
41
|
-
const c = await
|
|
42
|
-
return n && console.debug(`[juneau] skill "${t}" → done in ${
|
|
43
|
-
|
|
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
45
|
id: t,
|
|
46
|
-
title:
|
|
46
|
+
title: h(l.labels.done, r),
|
|
47
47
|
status: "done",
|
|
48
48
|
metadata: { skill: t }
|
|
49
49
|
})
|
|
50
50
|
), c;
|
|
51
51
|
} catch (c) {
|
|
52
|
-
const
|
|
53
|
-
n && console.debug(`[juneau] skill "${t}" → FAILED in ${
|
|
54
|
-
const
|
|
55
|
-
throw
|
|
56
|
-
|
|
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
58
|
id: t,
|
|
59
|
-
title:
|
|
59
|
+
title: h(T, r),
|
|
60
60
|
status: "failed",
|
|
61
61
|
metadata: { skill: t }
|
|
62
62
|
})
|
|
63
|
-
), e = !0,
|
|
63
|
+
), e = !0, a = `Tool "${t}" failed: ${m}`, c;
|
|
64
64
|
}
|
|
65
65
|
}
|
|
66
66
|
};
|
|
67
67
|
return {
|
|
68
|
-
tools:
|
|
68
|
+
tools: u,
|
|
69
69
|
drainActivities() {
|
|
70
|
-
return
|
|
70
|
+
return s.splice(0, s.length);
|
|
71
71
|
},
|
|
72
72
|
get hadFailure() {
|
|
73
73
|
return e;
|
|
74
74
|
},
|
|
75
75
|
get failureContext() {
|
|
76
|
-
return
|
|
76
|
+
return a;
|
|
77
77
|
}
|
|
78
78
|
};
|
|
79
79
|
}
|
|
80
|
-
const b = /* @__PURE__ */ new Set(["text-delta", "text"]),
|
|
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,88 +91,118 @@ const b = /* @__PURE__ */ new Set(["text-delta", "text"]), x = /* @__PURE__ */ n
|
|
|
91
91
|
"response-metadata",
|
|
92
92
|
"stream-start"
|
|
93
93
|
]);
|
|
94
|
-
async function*
|
|
94
|
+
async function* y(i, o, r) {
|
|
95
95
|
const n = r?.debug ?? !1;
|
|
96
|
-
for await (const
|
|
97
|
-
const e =
|
|
96
|
+
for await (const s of i) {
|
|
97
|
+
const e = s, a = e.type;
|
|
98
98
|
if (n)
|
|
99
|
-
if (
|
|
100
|
-
const
|
|
101
|
-
console.debug(`[juneau] streamToWire chunk: ${
|
|
102
|
-
} else
|
|
103
|
-
if (
|
|
104
|
-
if (
|
|
105
|
-
const t =
|
|
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
106
|
n && t.length > 0 && console.debug(`[juneau] streamToWire → draining ${t.length} activities`);
|
|
107
|
-
for (const
|
|
108
|
-
yield
|
|
107
|
+
for (const l of t)
|
|
108
|
+
yield l;
|
|
109
109
|
}
|
|
110
|
-
const
|
|
111
|
-
|
|
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 (
|
|
117
|
-
const
|
|
118
|
-
n &&
|
|
119
|
-
for (const e of
|
|
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
120
|
yield e;
|
|
121
121
|
}
|
|
122
122
|
n && console.debug("[juneau] streamToWire → end of stream, emitting done"), yield `data: ${JSON.stringify({ type: "done" })}
|
|
123
123
|
|
|
124
124
|
`;
|
|
125
125
|
}
|
|
126
|
-
|
|
127
|
-
|
|
126
|
+
function v(i) {
|
|
127
|
+
return `data: ${JSON.stringify({ type: "error", message: i })}
|
|
128
|
+
|
|
129
|
+
`;
|
|
130
|
+
}
|
|
131
|
+
function x() {
|
|
132
|
+
return `data: ${JSON.stringify({ type: "done" })}
|
|
133
|
+
|
|
134
|
+
`;
|
|
135
|
+
}
|
|
136
|
+
async function* R(i) {
|
|
137
|
+
const { phase1: o, phase2: r, phase3: n, skillSet: s, debug: e = !1 } = i;
|
|
128
138
|
e && console.debug("[juneau] withToolRecovery → phase 1 start");
|
|
129
|
-
let
|
|
130
|
-
const
|
|
131
|
-
for await (const t of
|
|
132
|
-
t.includes('"type":"text"') && (
|
|
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);
|
|
133
143
|
if (e && console.debug(
|
|
134
|
-
`[juneau] withToolRecovery → phase 1 complete, textProduced=${
|
|
135
|
-
),
|
|
144
|
+
`[juneau] withToolRecovery → phase 1 complete, textProduced=${a}, hadFailure=${s.hadFailure}`
|
|
145
|
+
), s.hadFailure && !a && s.failureContext) {
|
|
136
146
|
e && console.debug("[juneau] withToolRecovery → hadFailure=true, textProduced=false → triggering phase 2");
|
|
137
|
-
|
|
138
|
-
|
|
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
|
+
}
|
|
139
154
|
return;
|
|
140
155
|
}
|
|
141
|
-
if (!
|
|
142
|
-
const t = await
|
|
156
|
+
if (!a && !s.hadFailure && n) {
|
|
157
|
+
const t = await j(u);
|
|
143
158
|
if (t) {
|
|
144
|
-
e && console.debug(
|
|
145
|
-
`[juneau] withToolRecovery →
|
|
146
|
-
|
|
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
|
+
}
|
|
147
171
|
return;
|
|
148
172
|
}
|
|
149
173
|
e && console.debug(
|
|
150
174
|
"[juneau] withToolRecovery → phase 3 configured but phase 1 result exposes no message history — emitting done"
|
|
151
175
|
);
|
|
152
|
-
} else !
|
|
176
|
+
} else !a && !s.hadFailure && e && console.debug(
|
|
153
177
|
"[juneau] withToolRecovery → no failure, no text, no phase3 — emitting done (Gemini silent response)"
|
|
154
178
|
);
|
|
155
|
-
yield
|
|
156
|
-
|
|
157
|
-
`;
|
|
179
|
+
yield x();
|
|
158
180
|
}
|
|
159
|
-
async function
|
|
160
|
-
if (
|
|
161
|
-
const
|
|
162
|
-
if (Array.isArray(
|
|
163
|
-
return
|
|
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;
|
|
164
186
|
}
|
|
165
|
-
if (
|
|
166
|
-
const
|
|
167
|
-
if (Array.isArray(
|
|
168
|
-
return
|
|
187
|
+
if (i.response) {
|
|
188
|
+
const o = await i.response;
|
|
189
|
+
if (Array.isArray(o?.messages) && o.messages.length > 0)
|
|
190
|
+
return o.messages;
|
|
169
191
|
}
|
|
170
192
|
return null;
|
|
171
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
|
+
}
|
|
172
202
|
export {
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
203
|
+
k as createSkillSet,
|
|
204
|
+
y as streamToWire,
|
|
205
|
+
S as toSdkMessages,
|
|
206
|
+
R as withToolRecovery
|
|
177
207
|
};
|
|
178
208
|
//# sourceMappingURL=index.js.map
|
package/dist/server/index.js.map
CHANGED
|
@@ -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 multi-phase streaming pattern needed for Gemini 2.5 Flash\n * tool call scenarios where the model either fails or silently succeeds without\n * emitting any text in the same stream pass.\n *\n * Phase 1: Stream with tools. Collect whether any text was produced and whether\n * a tool failure occurred.\n *\n * Phase 2 (failure recovery) — triggers when a tool failed AND no text was produced:\n * - Injects failureContext as an assistant message so the model is forced to\n * write a recovery text response (no tools available in phase 2).\n *\n * Phase 3 (silent-success recovery) — triggers when the tool succeeded but the\n * model wrote no text. Confirmed Gemini 2.5 Flash behaviour: the fullStream ends\n * with tool-call → tool-result → finish-step → finish and no text-delta ever\n * arrives — Gemini treats the tool call as its complete response. Phase 3 receives\n * the full phase 1 message history (including tool-call and tool-result turns,\n * resolved from the ai-sdk result's `response`/`messages` promise) so the model\n * can be called again without tools and forced to summarise the tool result.\n * If phase3 is not provided, falls back to emitting done (previous behaviour).\n *\n * @returns AsyncIterable<string> of Juneau wire SSE strings (activities + text + done)\n */\nexport async function* withToolRecovery(options: ToolRecoveryOptions): AsyncIterable<string> {\n const { phase1, phase2, phase3, skillSet, debug = false } = options;\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 1 start');\n }\n\n let producedText = false;\n\n const result1 = phase1();\n\n for await (const chunk of streamToWire(result1.fullStream, skillSet, { debug })) {\n // Track whether any text reached the wire (done event doesn't count)\n if (chunk.includes('\"type\":\"text\"')) {\n producedText = true;\n }\n\n // Hold back the done event — we may need to continue with phase 2 or 3\n if (chunk.includes('\"type\":\"done\"')) {\n continue;\n }\n\n yield chunk;\n }\n\n if (debug) {\n console.debug(\n `[juneau] withToolRecovery → phase 1 complete, textProduced=${producedText}, hadFailure=${skillSet.hadFailure}`\n );\n }\n\n if (skillSet.hadFailure && !producedText && skillSet.failureContext) {\n // Tool failed and model wrote nothing — run phase 2 to force a text response\n if (debug) {\n console.debug('[juneau] withToolRecovery → hadFailure=true, textProduced=false → triggering phase 2');\n }\n\n const result2 = phase2(skillSet.failureContext);\n\n // Phase 2 has no skillSet — plain text response, no tool calls expected\n yield* streamToWire(result2.fullStream, undefined, { debug });\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 2 complete');\n }\n return;\n }\n\n if (!producedText && !skillSet.hadFailure && phase3) {\n // Tool succeeded but model emitted no text — Gemini silent-response scenario.\n // Resolve the full message history from the consumed phase 1 result and let\n // phase 3 call the model again (no tools) to summarise the tool result.\n const fullMessages = await resolvePhase1Messages(result1);\n\n if (fullMessages) {\n if (debug) {\n console.debug(\n `[juneau] withToolRecovery → no failure, no text → triggering phase 3 with ${fullMessages.length} messages`\n );\n }\n\n yield* streamToWire(phase3(fullMessages).fullStream, undefined, { debug });\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 3 complete');\n }\n return;\n }\n\n if (debug) {\n console.debug(\n '[juneau] withToolRecovery → phase 3 configured but phase 1 result exposes no message history — emitting done'\n );\n }\n } else if (!producedText && !skillSet.hadFailure && debug) {\n console.debug(\n '[juneau] withToolRecovery → no failure, no text, no phase3 — emitting done (Gemini silent response)'\n );\n }\n\n yield `data: ${JSON.stringify({ type: 'done' })}\\n\\n`;\n}\n\n/**\n * Resolves the full message history (incl. tool-call/tool-result turns) from a\n * consumed ai-sdk StreamTextResult. ai-sdk v7 exposes it as `response.messages`;\n * some versions expose a `messages` promise directly. Both resolve only after\n * the fullStream has been fully consumed, which is guaranteed at the call site.\n */\nasync function resolvePhase1Messages(result: {\n response?: Promise<{ messages: unknown[] }>;\n messages?: Promise<unknown[]>;\n}): Promise<unknown[] | null> {\n if (result.response) {\n const response = await result.response;\n if (Array.isArray(response?.messages)) {\n return response.messages;\n }\n }\n\n if (result.messages) {\n const messages = await result.messages;\n if (Array.isArray(messages)) {\n return messages;\n }\n }\n\n return null;\n}\n"],"names":["toSdkMessages","messages","mapped","msg","text","p","result","i","current","prev","formatActivityEvent","event","pickLabel","labels","language","createSkillSet","skills","options","debug","activityBuffer","hadFailure","failureContext","tools","name","skill","input","startMs","durationMs","err","message","failedLabels","TEXT_CHUNK_TYPES","IGNORED_CHUNK_TYPES","streamToWire","fullStream","skillSet","chunk","c","type","activities","remaining","withToolRecovery","phase1","phase2","phase3","producedText","result1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AAG9C,WAAOF,EAAac,EAAQ,YAAY,QAAW,EAAE,OAAA7B,GAAO,GAExDA,KACF,QAAQ,MAAM,8CAA8C;AAE9D;AAAA,EACF;AAEA,MAAI,CAAC2B,KAAgB,CAACV,EAAS,cAAcS,GAAQ;AAInD,UAAMI,IAAe,MAAMC,EAAsBH,CAAO;AAExD,QAAIE,GAAc;AAChB,MAAI9B,KACF,QAAQ;AAAA,QACN,6EAA6E8B,EAAa,MAAM;AAAA,MAAA,GAIpG,OAAOf,EAAaW,EAAOI,CAAY,EAAE,YAAY,QAAW,EAAE,OAAA9B,GAAO,GAErEA,KACF,QAAQ,MAAM,8CAA8C;AAE9D;AAAA,IACF;AAEA,IAAIA,KACF,QAAQ;AAAA,MACN;AAAA,IAAA;AAAA,EAGN,OAAW,CAAC2B,KAAgB,CAACV,EAAS,cAAcjB,KAClD,QAAQ;AAAA,IACN;AAAA,EAAA;AAIJ,QAAM,SAAS,KAAK,UAAU,EAAE,MAAM,QAAQ,CAAC;AAAA;AAAA;AACjD;AAQA,eAAe+B,EAAsB3C,GAGP;AAC5B,MAAIA,EAAO,UAAU;AACnB,UAAM4C,IAAW,MAAM5C,EAAO;AAC9B,QAAI,MAAM,QAAQ4C,GAAU,QAAQ;AAClC,aAAOA,EAAS;AAAA,EAEpB;AAEA,MAAI5C,EAAO,UAAU;AACnB,UAAML,IAAW,MAAMK,EAAO;AAC9B,QAAI,MAAM,QAAQL,CAAQ;AACxB,aAAOA;AAAA,EAEX;AAEA,SAAO;AACT;"}
|
|
1
|
+
{"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,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AOA,SAASD,EAAmBnD,GAA8B;AACxD,SAAOA,EAAS,KAAK,CAACqD,MAAM;AAC1B,UAAMnD,IAAMmD;AACZ,WAAInD,EAAI,SAAS,SAAe,KAC5B,MAAM,QAAQA,EAAI,OAAO,IACpBA,EAAI,QAAQ;AAAA,MACjB,CAACoD,MAAUA,EAA2B,SAAS;AAAA,IAAA,IAG5C;AAAA,EACT,CAAC;AACH;"}
|
package/dist/server/types.d.ts
CHANGED
|
@@ -57,14 +57,19 @@ export interface SkillSetOptions {
|
|
|
57
57
|
export interface ToolRecoveryStreamResult {
|
|
58
58
|
fullStream: AsyncIterable<unknown>;
|
|
59
59
|
/**
|
|
60
|
-
* ai-sdk v7: resolves after the stream is consumed to the
|
|
61
|
-
*
|
|
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.
|
|
62
69
|
*/
|
|
63
70
|
response?: Promise<{
|
|
64
|
-
messages
|
|
71
|
+
messages?: unknown[];
|
|
65
72
|
}>;
|
|
66
|
-
/** Some ai-sdk versions expose the message history directly. */
|
|
67
|
-
messages?: Promise<unknown[]>;
|
|
68
73
|
}
|
|
69
74
|
export interface ToolRecoveryOptions {
|
|
70
75
|
phase1: () => ToolRecoveryStreamResult;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/server/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAEtC;;GAEG;AACH,MAAM,WAAW,eAAe,CA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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"}
|
|
@@ -15,11 +15,17 @@ import type { ToolRecoveryOptions } from './types';
|
|
|
15
15
|
* model wrote no text. Confirmed Gemini 2.5 Flash behaviour: the fullStream ends
|
|
16
16
|
* with tool-call → tool-result → finish-step → finish and no text-delta ever
|
|
17
17
|
* arrives — Gemini treats the tool call as its complete response. Phase 3 receives
|
|
18
|
-
* the full phase 1 message history
|
|
19
|
-
*
|
|
20
|
-
*
|
|
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.
|
|
21
24
|
* If phase3 is not provided, falls back to emitting done (previous behaviour).
|
|
22
25
|
*
|
|
26
|
+
* Errors thrown by phase 2 / phase 3 model calls are surfaced as wire error
|
|
27
|
+
* events — never swallowed into a silent done.
|
|
28
|
+
*
|
|
23
29
|
* @returns AsyncIterable<string> of Juneau wire SSE strings (activities + text + done)
|
|
24
30
|
*/
|
|
25
31
|
export declare function withToolRecovery(options: ToolRecoveryOptions): AsyncIterable<string>;
|
|
@@ -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;
|
|
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"}
|