juneau 0.5.2 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -0
- package/dist/context/AiChatContext.d.ts +13 -1
- package/dist/context/AiChatContext.d.ts.map +1 -1
- package/dist/context/AiChatProvider.d.ts.map +1 -1
- package/dist/core/history.d.ts +0 -12
- package/dist/core/history.d.ts.map +1 -1
- package/dist/core/types.d.ts +5 -1
- package/dist/core/types.d.ts.map +1 -1
- package/dist/hooks/useAiChat.d.ts.map +1 -1
- package/dist/index.cjs +28 -28
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2735 -2713
- package/dist/index.js.map +1 -1
- package/dist/server/index.cjs +9 -8
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +145 -129
- package/dist/server/index.js.map +1 -1
- package/dist/server/types.d.ts +8 -0
- package/dist/server/types.d.ts.map +1 -1
- package/dist/server/withToolRecovery.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/server/index.cjs
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function $(n){const t=n.map(e=>{const i=e.parts.filter(r=>r.type==="text").map(r=>r.text).join("");return{role:e.role,content:i}}),o=[];for(let e=0;e<t.length;e++){const i=t[e],r=o[o.length-1];i.role==="user"&&r?.role==="user"&&o.push({role:"assistant",content:"…"}),o.push(i)}return o.filter(e=>e.content.length>0)}function h(n){return`data: ${JSON.stringify(n)}
|
|
2
2
|
|
|
3
|
-
`}function
|
|
4
|
-
`)}function
|
|
3
|
+
`}function m(n,t){return n[t]??n.en}function k(n){const t=new Set(Object.keys(n));for(const[o,e]of Object.entries(n))if(e.tools){for(const i of e.tools)if(!t.has(i))throw new Error(`[juneau] createSkillSet: skill "${o}" references unknown tool "${i}". Known skills: ${[...t].join(", ")}`)}}function N(n,t={}){k(n);const o=t.language??"en",e=t.debug??!1,i=[],r=[];let s=!1,c=null;const f={};for(const[l,a]of Object.entries(n))f[l]={description:a.description,parameters:a.input,execute:async u=>{r.includes(l)||r.push(l),e&&console.debug(`[juneau] skill "${l}" → executing, input:`,u);const g=e?Date.now():0;i.push(h({type:"activity",id:l,title:m(a.labels.running,o),status:"running",metadata:{skill:l}}));const T={emit:d=>{e&&console.debug(`[juneau] skill "${l}" → emitting part "${d.type}"`),i.push(h({type:"part",part:d}))}};try{const d=await a.execute(u,T),p=e?Date.now()-g:0;return e&&console.debug(`[juneau] skill "${l}" → done in ${p}ms, result:`,d),i.push(h({type:"activity",id:l,title:m(a.labels.done,o),status:"done",metadata:{skill:l}})),d}catch(d){const p=e?Date.now()-g:0,v=d instanceof Error?d.message:String(d);e&&console.debug(`[juneau] skill "${l}" → FAILED in ${p}ms: "${v}"`);const S=a.labels.failed??{cs:"Nepodařilo se",en:"Failed"};throw i.push(h({type:"activity",id:l,title:m(S,o),status:"failed",metadata:{skill:l}})),s=!0,c=`Tool "${l}" failed: ${v}`,d}}};return{tools:f,skills:n,calledSkillNames:r,drainActivities(){return i.splice(0,i.length)},get hadFailure(){return s},get failureContext(){return c}}}function R(n){return Object.entries(n.skills).map(([t,o])=>{const e=[o.readOnly===!1?"write":"read"];return o.requiresConfirmation&&e.push("requires confirmation"),`- ${t} (${e.join(", ")}): ${o.description}`}).join(`
|
|
4
|
+
`)}function O(n,t){return t.map(o=>n.skills[o]).filter(o=>o?.instructions).map(o=>o.instructions).join(`
|
|
5
5
|
|
|
6
|
-
`)}const
|
|
6
|
+
`)}const w=new Set(["text-delta","text"]),W=new Set(["tool-call","tool-result","tool-input-start","tool-input-delta","tool-input-available","tool-output-available","step-start","finish-step","start","finish","response-metadata","stream-start"]);async function*y(n,t,o){const e=o?.debug??!1;for await(const i of n){const r=i,s=r.type;if(e)if(s&&w.has(s)){const c=r.text??r.textDelta;console.debug(`[juneau] streamToWire chunk: ${s} ${JSON.stringify(c??"")}`)}else s==="tool-call"?console.debug(`[juneau] streamToWire chunk: tool-call "${r.toolName??r.name??"?"}"`):s==="tool-result"?console.debug("[juneau] streamToWire chunk: tool-result (ignored)"):s&&(W.has(s)?console.debug(`[juneau] streamToWire chunk: ${s} (ignored)`):console.debug(`[juneau] streamToWire chunk: ${s} (unknown)`));if(s&&w.has(s)){if(t){const f=t.drainActivities();e&&f.length>0&&console.debug(`[juneau] streamToWire → draining ${f.length} activities`);for(const l of f)yield l}const c=r.text??r.textDelta;c&&(e&&console.debug(`[juneau] streamToWire → yielding text ${JSON.stringify(c)}`),yield`data: ${JSON.stringify({type:"text",text:c})}
|
|
7
7
|
|
|
8
|
-
`)}}if(
|
|
8
|
+
`)}}if(t){const i=t.drainActivities();e&&i.length>0&&console.debug(`[juneau] streamToWire → draining ${i.length} activities (end of stream)`);for(const r of i)yield r}e&&console.debug("[juneau] streamToWire → end of stream, emitting done"),yield`data: ${JSON.stringify({type:"done"})}
|
|
9
9
|
|
|
10
|
-
`}function j(
|
|
10
|
+
`}function j(n){return`data: ${JSON.stringify({type:"error",message:n})}
|
|
11
11
|
|
|
12
|
-
`}function
|
|
12
|
+
`}function b(){return`data: ${JSON.stringify({type:"done"})}
|
|
13
13
|
|
|
14
|
-
`}
|
|
14
|
+
`}function x(n){let t="";for(const o of n.split(`
|
|
15
|
+
`))if(o.startsWith("data: "))try{const e=JSON.parse(o.slice(6));e.type==="text"&&typeof e.text=="string"&&(t+=e.text)}catch{}return t}async function*A(n){const{phase1:t,phase2:o,phase3:e,skillSet:i,onFinish:r,debug:s=!1}=n;s&&console.debug("[juneau] withToolRecovery → phase 1 start");let c=!1,f="";const l=t();for await(const a of y(l.fullStream,i,{debug:s}))f+=x(a),a.includes('"type":"text"')&&(c=!0),!a.includes('"type":"done"')&&(yield a);if(s&&console.debug(`[juneau] withToolRecovery → phase 1 complete, textProduced=${c}, hadFailure=${i.hadFailure}`),i.hadFailure&&!c&&i.failureContext){s&&console.debug("[juneau] withToolRecovery → hadFailure=true, textProduced=false → triggering phase 2");try{const a=o(i.failureContext);for await(const u of y(a.fullStream,void 0,{debug:s}))f+=x(u),!u.includes('"type":"done"')&&(yield u);s&&console.debug("[juneau] withToolRecovery → phase 2 complete"),r?.({text:f}),yield b()}catch(a){const u=a instanceof Error?a.message:String(a);s&&console.debug(`[juneau] withToolRecovery → phase 2 FAILED: "${u}"`),yield j(u)}return}if(!c&&!i.hadFailure&&e){const a=await E(l);if(a){s&&(console.debug(`[juneau] withToolRecovery → phase 3 messages resolved (${a.length}):`,JSON.stringify(a,null,2)),F(a)||console.debug("[juneau] withToolRecovery → WARNING: resolved history contains no tool-result turn — Gemini will likely reject it as an invalid conversation structure"),console.debug("[juneau] withToolRecovery → no failure, no text → triggering phase 3"));try{for await(const u of y(e(a).fullStream,void 0,{debug:s}))f+=x(u),!u.includes('"type":"done"')&&(yield u);s&&console.debug("[juneau] withToolRecovery → phase 3 complete"),r?.({text:f}),yield b()}catch(u){const g=u instanceof Error?u.message:String(u);s&&console.debug(`[juneau] withToolRecovery → phase 3 FAILED: "${g}"`),yield j(g)}return}s&&console.debug("[juneau] withToolRecovery → phase 3 configured but phase 1 result exposes no message history — emitting done")}else!c&&!i.hadFailure&&s&&console.debug("[juneau] withToolRecovery → no failure, no text, no phase3 — emitting done (Gemini silent response)");r?.({text:f}),yield b()}async function E(n){if(n.messages){const t=await n.messages;if(Array.isArray(t)&&t.length>0)return t}if(n.response){const t=await n.response;if(Array.isArray(t?.messages)&&t.messages.length>0)return t.messages}return null}function F(n){return n.some(t=>{const o=t;return o.role==="tool"?!0:Array.isArray(o.content)?o.content.some(e=>e.type==="tool-result"):!1})}exports.buildSkillIndex=R;exports.createSkillSet=N;exports.selectSkills=O;exports.streamToWire=y;exports.toSdkMessages=$;exports.withToolRecovery=A;
|
|
15
16
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../../src/server/toSdkMessages.ts","../../src/server/createSkillSet.ts","../../src/server/skillIndex.ts","../../src/server/streamToWire.ts","../../src/server/withToolRecovery.ts"],"sourcesContent":["import type { AiMessage } from '../core/types';\r\nimport type { CoreMessage } from './types';\r\n\r\n/**\r\n * Converts Juneau's AiMessage[] to the CoreMessage[] format expected by\r\n * ai-sdk's generateText / streamText.\r\n *\r\n * - Extracts plain text from parts (joins all type: \"text\" parts)\r\n * - Replaces activity-only assistant messages with an empty assistant turn\r\n * so conversation alternation stays valid\r\n * - Injects a placeholder assistant turn between consecutive user messages\r\n * - Filters out empty turns (unless they are a required alternation filler)\r\n */\r\nexport function toSdkMessages(messages: AiMessage[]): CoreMessage[] {\r\n // First pass: map each AiMessage to a CoreMessage, replacing activity-only\r\n // assistant messages with an empty-text assistant turn.\r\n const mapped: CoreMessage[] = messages.map(msg => {\r\n const text = msg.parts\r\n .filter(p => p.type === 'text')\r\n .map(p => (p as { type: 'text'; text: string }).text)\r\n .join('');\r\n\r\n return { role: msg.role as CoreMessage['role'], content: text };\r\n });\r\n\r\n // Second pass: inject a placeholder assistant turn between consecutive user\r\n // messages as a safety net for history bugs that would cause model errors.\r\n const result: CoreMessage[] = [];\r\n for (let i = 0; i < mapped.length; i++) {\r\n const current = mapped[i];\r\n const prev = result[result.length - 1];\r\n\r\n if (current.role === 'user' && prev?.role === 'user') {\r\n result.push({ role: 'assistant', content: '…' });\r\n }\r\n\r\n result.push(current);\r\n }\r\n\r\n // Third pass: filter out empty turns, but keep assistant placeholders that\r\n // serve as alternation fillers (they have content '…' set above, so they\r\n // won't be filtered). Only drop genuinely empty content strings.\r\n return result.filter(msg => msg.content.length > 0);\r\n}\r\n","import type { ZodType } from 'zod';\nimport type { SkillDefinition, SkillExecuteContext, SkillSet, SkillSetOptions } from './types';\n\ntype SkillMap = Record<string, SkillDefinition<ZodType>>;\n\nfunction formatWireEvent(event: Record<string, unknown>): string {\n return `data: ${JSON.stringify(event)}\\n\\n`;\n}\n\nfunction pickLabel(labels: { cs: string; en: string }, language: string): string {\n return (labels as Record<string, string>)[language] ?? labels.en;\n}\n\n/**\n * Takes a map of skill definitions and returns a SkillSet containing:\n * - tools: ready-made tool definitions for ai-sdk's streamText({ tools })\n * - drainActivities(): flush buffered activity + part wire SSE strings\n * - hadFailure / failureContext: for driving tool failure recovery\n *\n * Each skill's execute fn receives a SkillExecuteContext as its second\n * argument with an `emit(part)` callback — parts are pushed into the same\n * buffer as activities and drained by streamToWire at the same points.\n */\n/**\n * Validates skill definitions at startup — throws immediately (not at runtime)\n * so a broken registry fails the server boot, not a user request.\n */\nfunction validateSkills(skills: SkillMap): void {\n const knownNames = new Set(Object.keys(skills));\n\n for (const [name, skill] of Object.entries(skills)) {\n if (!skill.tools) continue;\n for (const toolName of skill.tools) {\n if (!knownNames.has(toolName)) {\n throw new Error(\n `[juneau] createSkillSet: skill \"${name}\" references unknown tool \"${toolName}\". ` +\n `Known skills: ${[...knownNames].join(', ')}`\n );\n }\n }\n }\n}\n\nexport function createSkillSet(skills: SkillMap, options: SkillSetOptions = {}): SkillSet {\n validateSkills(skills);\n\n const language = options.language ?? 'en';\n const debug = options.debug ?? false;\n const activityBuffer: string[] = [];\n const calledSkillNames: string[] = [];\n let hadFailure = false;\n let failureContext: string | null = null;\n\n const tools: Record<string, unknown> = {};\n\n for (const [name, skill] of Object.entries(skills)) {\n tools[name] = {\n description: skill.description,\n parameters: skill.input,\n execute: async (input: unknown) => {\n if (!calledSkillNames.includes(name)) {\n calledSkillNames.push(name);\n }\n\n if (debug) {\n console.debug(`[juneau] skill \"${name}\" → executing, input:`, input);\n }\n\n const startMs = debug ? Date.now() : 0;\n\n // Emit a \"running\" activity event into the buffer\n activityBuffer.push(\n formatWireEvent({\n type: 'activity',\n id: name,\n title: pickLabel(skill.labels.running, language),\n status: 'running',\n metadata: { skill: name },\n })\n );\n\n const executeContext: SkillExecuteContext = {\n emit: (part) => {\n if (debug) {\n console.debug(`[juneau] skill \"${name}\" → emitting part \"${part.type}\"`);\n }\n activityBuffer.push(formatWireEvent({ type: 'part', part }));\n },\n };\n\n try {\n const result = await skill.execute(input as never, executeContext);\n\n const durationMs = debug ? Date.now() - startMs : 0;\n if (debug) {\n console.debug(`[juneau] skill \"${name}\" → done in ${durationMs}ms, result:`, result);\n }\n\n // Emit a \"done\" activity event\n activityBuffer.push(\n formatWireEvent({\n type: 'activity',\n id: name,\n title: pickLabel(skill.labels.done, language),\n status: 'done',\n metadata: { skill: name },\n })\n );\n\n return result;\n } catch (err) {\n const durationMs = debug ? Date.now() - startMs : 0;\n const message = err instanceof Error ? err.message : String(err);\n\n if (debug) {\n console.debug(`[juneau] skill \"${name}\" → FAILED in ${durationMs}ms: \"${message}\"`);\n }\n\n const failedLabels = skill.labels.failed ?? { cs: 'Nepodařilo se', en: 'Failed' };\n\n // Emit a \"failed\" activity event\n activityBuffer.push(\n formatWireEvent({\n type: 'activity',\n id: name,\n title: pickLabel(failedLabels, language),\n status: 'failed',\n metadata: { skill: name },\n })\n );\n\n hadFailure = true;\n failureContext = `Tool \"${name}\" failed: ${message}`;\n\n // Re-throw so ai-sdk knows the tool call failed\n throw err;\n }\n },\n };\n }\n\n return {\n tools,\n\n skills,\n\n calledSkillNames,\n\n drainActivities(): string[] {\n return activityBuffer.splice(0, activityBuffer.length);\n },\n\n get hadFailure() {\n return hadFailure;\n },\n\n get failureContext() {\n return failureContext;\n },\n };\n}\n","import type { SkillSet } from './types';\n\n/**\n * Builds a compact one-liner-per-skill index for the system prompt.\n * Inject the output into your system prompt instead of hand-maintaining a\n * skill list — adding a skill to the registry updates the index automatically.\n *\n * Output format:\n * - invoiceSearch (read): Find invoices by number, supplier, date, or status.\n * - invoiceApprove (write, requires confirmation): Approve an invoice.\n */\nexport function buildSkillIndex(skillSet: SkillSet): string {\n return Object.entries(skillSet.skills)\n .map(([name, skill]) => {\n const traits: string[] = [skill.readOnly === false ? 'write' : 'read'];\n if (skill.requiresConfirmation) {\n traits.push('requires confirmation');\n }\n return `- ${name} (${traits.join(', ')}): ${skill.description}`;\n })\n .join('\\n');\n}\n\n/**\n * Returns the concatenated workflow instructions for the given skill names —\n * typically skillSet.calledSkillNames after phase 1. Skills without\n * instructions and unknown names are skipped. Returns '' when nothing matches.\n *\n * This is the lazy-loading half of the skill format: full instructions enter\n * the prompt only for skills the model actually used.\n *\n * @example\n * const instructions = selectSkills(skillSet, skillSet.calledSkillNames);\n * // → inject into phase 3's system prompt as additional context\n */\nexport function selectSkills(skillSet: SkillSet, skillNames: string[]): string {\n return skillNames\n .map(name => skillSet.skills[name])\n .filter(skill => skill?.instructions)\n .map(skill => skill.instructions as string)\n .join('\\n\\n');\n}\n","import type { SkillSet, StreamToWireOptions } from './types';\n\n// ai-sdk v7 chunk types that carry the model's text output.\n// - 'text-delta': standard streaming text (v6 + v7)\n// - 'text': emitted by some v7 model/provider combos as a completed text chunk\n// Both may appear in the same stream; we handle either.\nconst TEXT_CHUNK_TYPES = new Set(['text-delta', 'text']);\n\n// Chunk types we recognise but intentionally ignore — activities are driven by\n// the SkillSet execute fn, not by these wire events.\nconst IGNORED_CHUNK_TYPES = new Set([\n 'tool-call',\n 'tool-result',\n 'tool-input-start',\n 'tool-input-delta',\n 'tool-input-available',\n 'tool-output-available',\n 'step-start',\n 'finish-step',\n 'start',\n 'finish',\n 'response-metadata',\n 'stream-start',\n]);\n\n/**\n * Converts ai-sdk's fullStream AsyncIterable into Juneau wire SSE strings.\n *\n * Handles:\n * - All text chunk types used by ai-sdk v7 (text-delta, text) incl. v6 textDelta fallback\n * - Flushing skillSet.drainActivities() before each text chunk so activities\n * always appear before the text they precede\n * - A final drain after the loop ends (catches last-tool-call activities when\n * no text follows the tool result — the Gemini silent-response scenario)\n * - Emitting the done event when the stream finishes\n * - Structured debug logging of every chunk when options.debug is true\n */\nexport async function* streamToWire(\n fullStream: AsyncIterable<unknown>,\n skillSet?: SkillSet,\n options?: StreamToWireOptions\n): AsyncIterable<string> {\n const debug = options?.debug ?? false;\n\n for await (const chunk of fullStream) {\n const c = chunk as Record<string, unknown>;\n const type = c.type as string | undefined;\n\n if (debug) {\n if (type && TEXT_CHUNK_TYPES.has(type)) {\n const text = (c.text ?? c.textDelta) as string | undefined;\n console.debug(`[juneau] streamToWire chunk: ${type} ${JSON.stringify(text ?? '')}`);\n } else if (type === 'tool-call') {\n console.debug(`[juneau] streamToWire chunk: tool-call \"${c.toolName ?? c.name ?? '?'}\"`);\n } else if (type === 'tool-result') {\n console.debug(`[juneau] streamToWire chunk: tool-result (ignored)`);\n } else if (type) {\n if (IGNORED_CHUNK_TYPES.has(type)) {\n console.debug(`[juneau] streamToWire chunk: ${type} (ignored)`);\n } else {\n console.debug(`[juneau] streamToWire chunk: ${type} (unknown)`);\n }\n }\n }\n\n if (type && TEXT_CHUNK_TYPES.has(type)) {\n // Flush any buffered activity events before emitting text so the UI\n // shows running/done indicators before the model's reply appears.\n if (skillSet) {\n const activities = skillSet.drainActivities();\n if (debug && activities.length > 0) {\n console.debug(`[juneau] streamToWire → draining ${activities.length} activities`);\n }\n for (const event of activities) {\n yield event;\n }\n }\n\n // ai-sdk v7 uses `text`, v6 used `textDelta` — support both\n const text = (c.text ?? c.textDelta) as string | undefined;\n if (text) {\n if (debug) {\n console.debug(`[juneau] streamToWire → yielding text ${JSON.stringify(text)}`);\n }\n yield `data: ${JSON.stringify({ type: 'text', text })}\\n\\n`;\n }\n }\n\n // All other chunk types are intentionally silent — the SkillSet execute fn\n // emits activity events into its buffer which we drain above.\n }\n\n // Final drain — catches activity events from the last tool call when no\n // text-delta followed (Gemini sometimes calls a tool successfully but emits\n // the reply text in a subsequent step that never arrives as text-delta here).\n if (skillSet) {\n const remaining = skillSet.drainActivities();\n if (debug && remaining.length > 0) {\n console.debug(`[juneau] streamToWire → draining ${remaining.length} activities (end of stream)`);\n }\n for (const event of remaining) {\n yield event;\n }\n }\n\n if (debug) {\n console.debug('[juneau] streamToWire → end of stream, emitting done');\n }\n\n yield `data: ${JSON.stringify({ type: 'done' })}\\n\\n`;\n}\n","import type { ToolRecoveryOptions } from './types';\nimport { streamToWire } from './streamToWire';\n\nfunction wireError(message: string): string {\n return `data: ${JSON.stringify({ type: 'error', message })}\\n\\n`;\n}\n\nfunction wireDone(): string {\n return `data: ${JSON.stringify({ type: 'done' })}\\n\\n`;\n}\n\n/**\n * 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","formatWireEvent","event","pickLabel","labels","language","validateSkills","skills","knownNames","name","skill","toolName","createSkillSet","options","debug","activityBuffer","calledSkillNames","hadFailure","failureContext","tools","input","startMs","executeContext","part","durationMs","err","message","failedLabels","buildSkillIndex","skillSet","traits","selectSkills","skillNames","TEXT_CHUNK_TYPES","IGNORED_CHUNK_TYPES","streamToWire","fullStream","chunk","c","type","activities","remaining","wireError","wireDone","withToolRecovery","phase1","phase2","phase3","producedText","result1","result2","fullMessages","resolvePhase1Messages","containsToolResult","response","m"],"mappings":"gFAaO,SAASA,EAAcC,EAAsC,CAGlE,MAAMC,EAAwBD,EAAS,IAAIE,GAAO,CAChD,MAAMC,EAAOD,EAAI,MACd,UAAYE,EAAE,OAAS,MAAM,EAC7B,IAAIA,GAAMA,EAAqC,IAAI,EACnD,KAAK,EAAE,EAEV,MAAO,CAAE,KAAMF,EAAI,KAA6B,QAASC,CAAA,CAC3D,CAAC,EAIKE,EAAwB,CAAA,EAC9B,QAASC,EAAI,EAAGA,EAAIL,EAAO,OAAQK,IAAK,CACtC,MAAMC,EAAUN,EAAOK,CAAC,EAClBE,EAAOH,EAAOA,EAAO,OAAS,CAAC,EAEjCE,EAAQ,OAAS,QAAUC,GAAM,OAAS,QAC5CH,EAAO,KAAK,CAAE,KAAM,YAAa,QAAS,IAAK,EAGjDA,EAAO,KAAKE,CAAO,CACrB,CAKA,OAAOF,EAAO,OAAOH,GAAOA,EAAI,QAAQ,OAAS,CAAC,CACpD,CCtCA,SAASO,EAAgBC,EAAwC,CAC/D,MAAO,SAAS,KAAK,UAAUA,CAAK,CAAC;AAAA;AAAA,CACvC,CAEA,SAASC,EAAUC,EAAoCC,EAA0B,CAC/E,OAAQD,EAAkCC,CAAQ,GAAKD,EAAO,EAChE,CAgBA,SAASE,EAAeC,EAAwB,CAC9C,MAAMC,EAAa,IAAI,IAAI,OAAO,KAAKD,CAAM,CAAC,EAE9C,SAAW,CAACE,EAAMC,CAAK,IAAK,OAAO,QAAQH,CAAM,EAC/C,GAAKG,EAAM,OACX,UAAWC,KAAYD,EAAM,MAC3B,GAAI,CAACF,EAAW,IAAIG,CAAQ,EAC1B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ACT,CAOA,SAASD,EAAmB7D,EAA8B,CACxD,OAAOA,EAAS,KAAM+D,GAAM,CAC1B,MAAM7D,EAAM6D,EACZ,OAAI7D,EAAI,OAAS,OAAe,GAC5B,MAAM,QAAQA,EAAI,OAAO,EACpBA,EAAI,QAAQ,KAChB6B,GAAUA,EAA2B,OAAS,aAAA,EAG5C,EACT,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../../src/server/toSdkMessages.ts","../../src/server/createSkillSet.ts","../../src/server/skillIndex.ts","../../src/server/streamToWire.ts","../../src/server/withToolRecovery.ts"],"sourcesContent":["import type { AiMessage } from '../core/types';\r\nimport type { CoreMessage } from './types';\r\n\r\n/**\r\n * Converts Juneau's AiMessage[] to the CoreMessage[] format expected by\r\n * ai-sdk's generateText / streamText.\r\n *\r\n * - Extracts plain text from parts (joins all type: \"text\" parts)\r\n * - Replaces activity-only assistant messages with an empty assistant turn\r\n * so conversation alternation stays valid\r\n * - Injects a placeholder assistant turn between consecutive user messages\r\n * - Filters out empty turns (unless they are a required alternation filler)\r\n */\r\nexport function toSdkMessages(messages: AiMessage[]): CoreMessage[] {\r\n // First pass: map each AiMessage to a CoreMessage, replacing activity-only\r\n // assistant messages with an empty-text assistant turn.\r\n const mapped: CoreMessage[] = messages.map(msg => {\r\n const text = msg.parts\r\n .filter(p => p.type === 'text')\r\n .map(p => (p as { type: 'text'; text: string }).text)\r\n .join('');\r\n\r\n return { role: msg.role as CoreMessage['role'], content: text };\r\n });\r\n\r\n // Second pass: inject a placeholder assistant turn between consecutive user\r\n // messages as a safety net for history bugs that would cause model errors.\r\n const result: CoreMessage[] = [];\r\n for (let i = 0; i < mapped.length; i++) {\r\n const current = mapped[i];\r\n const prev = result[result.length - 1];\r\n\r\n if (current.role === 'user' && prev?.role === 'user') {\r\n result.push({ role: 'assistant', content: '…' });\r\n }\r\n\r\n result.push(current);\r\n }\r\n\r\n // Third pass: filter out empty turns, but keep assistant placeholders that\r\n // serve as alternation fillers (they have content '…' set above, so they\r\n // won't be filtered). Only drop genuinely empty content strings.\r\n return result.filter(msg => msg.content.length > 0);\r\n}\r\n","import type { ZodType } from 'zod';\nimport type { SkillDefinition, SkillExecuteContext, SkillSet, SkillSetOptions } from './types';\n\ntype SkillMap = Record<string, SkillDefinition<ZodType>>;\n\nfunction formatWireEvent(event: Record<string, unknown>): string {\n return `data: ${JSON.stringify(event)}\\n\\n`;\n}\n\nfunction pickLabel(labels: { cs: string; en: string }, language: string): string {\n return (labels as Record<string, string>)[language] ?? labels.en;\n}\n\n/**\n * Takes a map of skill definitions and returns a SkillSet containing:\n * - tools: ready-made tool definitions for ai-sdk's streamText({ tools })\n * - drainActivities(): flush buffered activity + part wire SSE strings\n * - hadFailure / failureContext: for driving tool failure recovery\n *\n * Each skill's execute fn receives a SkillExecuteContext as its second\n * argument with an `emit(part)` callback — parts are pushed into the same\n * buffer as activities and drained by streamToWire at the same points.\n */\n/**\n * Validates skill definitions at startup — throws immediately (not at runtime)\n * so a broken registry fails the server boot, not a user request.\n */\nfunction validateSkills(skills: SkillMap): void {\n const knownNames = new Set(Object.keys(skills));\n\n for (const [name, skill] of Object.entries(skills)) {\n if (!skill.tools) continue;\n for (const toolName of skill.tools) {\n if (!knownNames.has(toolName)) {\n throw new Error(\n `[juneau] createSkillSet: skill \"${name}\" references unknown tool \"${toolName}\". ` +\n `Known skills: ${[...knownNames].join(', ')}`\n );\n }\n }\n }\n}\n\nexport function createSkillSet(skills: SkillMap, options: SkillSetOptions = {}): SkillSet {\n validateSkills(skills);\n\n const language = options.language ?? 'en';\n const debug = options.debug ?? false;\n const activityBuffer: string[] = [];\n const calledSkillNames: string[] = [];\n let hadFailure = false;\n let failureContext: string | null = null;\n\n const tools: Record<string, unknown> = {};\n\n for (const [name, skill] of Object.entries(skills)) {\n tools[name] = {\n description: skill.description,\n parameters: skill.input,\n execute: async (input: unknown) => {\n if (!calledSkillNames.includes(name)) {\n calledSkillNames.push(name);\n }\n\n if (debug) {\n console.debug(`[juneau] skill \"${name}\" → executing, input:`, input);\n }\n\n const startMs = debug ? Date.now() : 0;\n\n // Emit a \"running\" activity event into the buffer\n activityBuffer.push(\n formatWireEvent({\n type: 'activity',\n id: name,\n title: pickLabel(skill.labels.running, language),\n status: 'running',\n metadata: { skill: name },\n })\n );\n\n const executeContext: SkillExecuteContext = {\n emit: (part) => {\n if (debug) {\n console.debug(`[juneau] skill \"${name}\" → emitting part \"${part.type}\"`);\n }\n activityBuffer.push(formatWireEvent({ type: 'part', part }));\n },\n };\n\n try {\n const result = await skill.execute(input as never, executeContext);\n\n const durationMs = debug ? Date.now() - startMs : 0;\n if (debug) {\n console.debug(`[juneau] skill \"${name}\" → done in ${durationMs}ms, result:`, result);\n }\n\n // Emit a \"done\" activity event\n activityBuffer.push(\n formatWireEvent({\n type: 'activity',\n id: name,\n title: pickLabel(skill.labels.done, language),\n status: 'done',\n metadata: { skill: name },\n })\n );\n\n return result;\n } catch (err) {\n const durationMs = debug ? Date.now() - startMs : 0;\n const message = err instanceof Error ? err.message : String(err);\n\n if (debug) {\n console.debug(`[juneau] skill \"${name}\" → FAILED in ${durationMs}ms: \"${message}\"`);\n }\n\n const failedLabels = skill.labels.failed ?? { cs: 'Nepodařilo se', en: 'Failed' };\n\n // Emit a \"failed\" activity event\n activityBuffer.push(\n formatWireEvent({\n type: 'activity',\n id: name,\n title: pickLabel(failedLabels, language),\n status: 'failed',\n metadata: { skill: name },\n })\n );\n\n hadFailure = true;\n failureContext = `Tool \"${name}\" failed: ${message}`;\n\n // Re-throw so ai-sdk knows the tool call failed\n throw err;\n }\n },\n };\n }\n\n return {\n tools,\n\n skills,\n\n calledSkillNames,\n\n drainActivities(): string[] {\n return activityBuffer.splice(0, activityBuffer.length);\n },\n\n get hadFailure() {\n return hadFailure;\n },\n\n get failureContext() {\n return failureContext;\n },\n };\n}\n","import type { SkillSet } from './types';\n\n/**\n * Builds a compact one-liner-per-skill index for the system prompt.\n * Inject the output into your system prompt instead of hand-maintaining a\n * skill list — adding a skill to the registry updates the index automatically.\n *\n * Output format:\n * - invoiceSearch (read): Find invoices by number, supplier, date, or status.\n * - invoiceApprove (write, requires confirmation): Approve an invoice.\n */\nexport function buildSkillIndex(skillSet: SkillSet): string {\n return Object.entries(skillSet.skills)\n .map(([name, skill]) => {\n const traits: string[] = [skill.readOnly === false ? 'write' : 'read'];\n if (skill.requiresConfirmation) {\n traits.push('requires confirmation');\n }\n return `- ${name} (${traits.join(', ')}): ${skill.description}`;\n })\n .join('\\n');\n}\n\n/**\n * Returns the concatenated workflow instructions for the given skill names —\n * typically skillSet.calledSkillNames after phase 1. Skills without\n * instructions and unknown names are skipped. Returns '' when nothing matches.\n *\n * This is the lazy-loading half of the skill format: full instructions enter\n * the prompt only for skills the model actually used.\n *\n * @example\n * const instructions = selectSkills(skillSet, skillSet.calledSkillNames);\n * // → inject into phase 3's system prompt as additional context\n */\nexport function selectSkills(skillSet: SkillSet, skillNames: string[]): string {\n return skillNames\n .map(name => skillSet.skills[name])\n .filter(skill => skill?.instructions)\n .map(skill => skill.instructions as string)\n .join('\\n\\n');\n}\n","import type { SkillSet, StreamToWireOptions } from './types';\n\n// ai-sdk v7 chunk types that carry the model's text output.\n// - 'text-delta': standard streaming text (v6 + v7)\n// - 'text': emitted by some v7 model/provider combos as a completed text chunk\n// Both may appear in the same stream; we handle either.\nconst TEXT_CHUNK_TYPES = new Set(['text-delta', 'text']);\n\n// Chunk types we recognise but intentionally ignore — activities are driven by\n// the SkillSet execute fn, not by these wire events.\nconst IGNORED_CHUNK_TYPES = new Set([\n 'tool-call',\n 'tool-result',\n 'tool-input-start',\n 'tool-input-delta',\n 'tool-input-available',\n 'tool-output-available',\n 'step-start',\n 'finish-step',\n 'start',\n 'finish',\n 'response-metadata',\n 'stream-start',\n]);\n\n/**\n * Converts ai-sdk's fullStream AsyncIterable into Juneau wire SSE strings.\n *\n * Handles:\n * - All text chunk types used by ai-sdk v7 (text-delta, text) incl. v6 textDelta fallback\n * - Flushing skillSet.drainActivities() before each text chunk so activities\n * always appear before the text they precede\n * - A final drain after the loop ends (catches last-tool-call activities when\n * no text follows the tool result — the Gemini silent-response scenario)\n * - Emitting the done event when the stream finishes\n * - Structured debug logging of every chunk when options.debug is true\n */\nexport async function* streamToWire(\n fullStream: AsyncIterable<unknown>,\n skillSet?: SkillSet,\n options?: StreamToWireOptions\n): AsyncIterable<string> {\n const debug = options?.debug ?? false;\n\n for await (const chunk of fullStream) {\n const c = chunk as Record<string, unknown>;\n const type = c.type as string | undefined;\n\n if (debug) {\n if (type && TEXT_CHUNK_TYPES.has(type)) {\n const text = (c.text ?? c.textDelta) as string | undefined;\n console.debug(`[juneau] streamToWire chunk: ${type} ${JSON.stringify(text ?? '')}`);\n } else if (type === 'tool-call') {\n console.debug(`[juneau] streamToWire chunk: tool-call \"${c.toolName ?? c.name ?? '?'}\"`);\n } else if (type === 'tool-result') {\n console.debug(`[juneau] streamToWire chunk: tool-result (ignored)`);\n } else if (type) {\n if (IGNORED_CHUNK_TYPES.has(type)) {\n console.debug(`[juneau] streamToWire chunk: ${type} (ignored)`);\n } else {\n console.debug(`[juneau] streamToWire chunk: ${type} (unknown)`);\n }\n }\n }\n\n if (type && TEXT_CHUNK_TYPES.has(type)) {\n // Flush any buffered activity events before emitting text so the UI\n // shows running/done indicators before the model's reply appears.\n if (skillSet) {\n const activities = skillSet.drainActivities();\n if (debug && activities.length > 0) {\n console.debug(`[juneau] streamToWire → draining ${activities.length} activities`);\n }\n for (const event of activities) {\n yield event;\n }\n }\n\n // ai-sdk v7 uses `text`, v6 used `textDelta` — support both\n const text = (c.text ?? c.textDelta) as string | undefined;\n if (text) {\n if (debug) {\n console.debug(`[juneau] streamToWire → yielding text ${JSON.stringify(text)}`);\n }\n yield `data: ${JSON.stringify({ type: 'text', text })}\\n\\n`;\n }\n }\n\n // All other chunk types are intentionally silent — the SkillSet execute fn\n // emits activity events into its buffer which we drain above.\n }\n\n // Final drain — catches activity events from the last tool call when no\n // text-delta followed (Gemini sometimes calls a tool successfully but emits\n // the reply text in a subsequent step that never arrives as text-delta here).\n if (skillSet) {\n const remaining = skillSet.drainActivities();\n if (debug && remaining.length > 0) {\n console.debug(`[juneau] streamToWire → draining ${remaining.length} activities (end of stream)`);\n }\n for (const event of remaining) {\n yield event;\n }\n }\n\n if (debug) {\n console.debug('[juneau] streamToWire → end of stream, emitting done');\n }\n\n yield `data: ${JSON.stringify({ type: 'done' })}\\n\\n`;\n}\n","import type { ToolRecoveryOptions } from './types';\nimport { streamToWire } from './streamToWire';\n\nfunction wireError(message: string): string {\n return `data: ${JSON.stringify({ type: 'error', message })}\\n\\n`;\n}\n\nfunction wireDone(): string {\n return `data: ${JSON.stringify({ type: 'done' })}\\n\\n`;\n}\n\n/**\n * Extracts the text payload from a wire SSE chunk's `data: {json}` lines.\n * Returns '' for non-text events or unparseable lines.\n */\nfunction extractWireText(chunk: string): string {\n let text = '';\n for (const line of chunk.split('\\n')) {\n if (!line.startsWith('data: ')) continue;\n try {\n const event = JSON.parse(line.slice(6)) as { type?: string; text?: string };\n if (event.type === 'text' && typeof event.text === 'string') {\n text += event.text;\n }\n } catch {\n // Not JSON — ignore, only well-formed text events count\n }\n }\n return text;\n}\n\n/**\n * Encapsulates the multi-phase streaming pattern needed for Gemini 2.5 Flash\n * tool call scenarios where the model either fails or silently succeeds without\n * emitting any text in the same stream pass.\n *\n * Phase 1: Stream with tools. Collect whether any text was produced and whether\n * a tool failure occurred.\n *\n * Phase 2 (failure recovery) — triggers when a tool failed AND no text was produced:\n * - Injects failureContext as an assistant message so the model is forced to\n * write a recovery text response (no tools available in phase 2).\n *\n * Phase 3 (silent-success recovery) — triggers when the tool succeeded but the\n * model wrote no text. Confirmed Gemini 2.5 Flash behaviour: the fullStream ends\n * with tool-call → tool-result → finish-step → finish and no text-delta ever\n * arrives — Gemini treats the tool call as its complete response. Phase 3 receives\n * the full phase 1 message history including tool-call AND tool-result turns —\n * Gemini rejects histories where a tool-call turn is not immediately followed by\n * a tool-result turn (\"function call turn must come immediately after a user turn\n * or after a function response turn\"). The history is resolved from the consumed\n * phase 1 result's `messages` promise (ai-sdk v7 — resolves to all turns after\n * the stream is consumed), with `response.messages` as fallback.\n * If phase3 is not provided, falls back to emitting done (previous behaviour).\n *\n * Errors thrown by phase 2 / phase 3 model calls are surfaced as wire error\n * events — never swallowed into a silent done.\n *\n * @returns AsyncIterable<string> of Juneau wire SSE strings (activities + text + done)\n */\nexport async function* withToolRecovery(options: ToolRecoveryOptions): AsyncIterable<string> {\n const { phase1, phase2, phase3, skillSet, onFinish, debug = false } = options;\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 1 start');\n }\n\n let producedText = false;\n // Assistant text accumulated across all phases — handed to onFinish on completion\n let accumulatedText = '';\n\n const result1 = phase1();\n\n for await (const chunk of streamToWire(result1.fullStream, skillSet, { debug })) {\n accumulatedText += extractWireText(chunk);\n\n // Track whether any text reached the wire (done event doesn't count)\n if (chunk.includes('\"type\":\"text\"')) {\n producedText = true;\n }\n\n // Hold back the done event — we may need to continue with phase 2 or 3\n if (chunk.includes('\"type\":\"done\"')) {\n continue;\n }\n\n yield chunk;\n }\n\n if (debug) {\n console.debug(\n `[juneau] withToolRecovery → phase 1 complete, textProduced=${producedText}, hadFailure=${skillSet.hadFailure}`\n );\n }\n\n if (skillSet.hadFailure && !producedText && skillSet.failureContext) {\n // Tool failed and model wrote nothing — run phase 2 to force a text response\n if (debug) {\n console.debug('[juneau] withToolRecovery → hadFailure=true, textProduced=false → triggering phase 2');\n }\n\n try {\n const result2 = phase2(skillSet.failureContext);\n\n // Phase 2 has no skillSet — plain text response, no tool calls expected.\n // Chunks are re-yielded one by one so we can accumulate their text; the\n // final done event is held back until onFinish has fired.\n for await (const chunk of streamToWire(result2.fullStream, undefined, { debug })) {\n accumulatedText += extractWireText(chunk);\n if (chunk.includes('\"type\":\"done\"')) continue;\n yield chunk;\n }\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 2 complete');\n }\n\n onFinish?.({ text: accumulatedText });\n yield wireDone();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (debug) {\n console.debug(`[juneau] withToolRecovery → phase 2 FAILED: \"${message}\"`);\n }\n yield wireError(message);\n }\n return;\n }\n\n if (!producedText && !skillSet.hadFailure && phase3) {\n // Tool succeeded but model emitted no text — Gemini silent-response scenario.\n // Resolve the full message history from the consumed phase 1 result and let\n // phase 3 call the model again (no tools) to summarise the tool result.\n const fullMessages = await resolvePhase1Messages(result1);\n\n if (fullMessages) {\n if (debug) {\n console.debug(\n `[juneau] withToolRecovery → phase 3 messages resolved (${fullMessages.length}):`,\n JSON.stringify(fullMessages, null, 2)\n );\n if (!containsToolResult(fullMessages)) {\n console.debug(\n '[juneau] withToolRecovery → WARNING: resolved history contains no tool-result turn — Gemini will likely reject it as an invalid conversation structure'\n );\n }\n console.debug('[juneau] withToolRecovery → no failure, no text → triggering phase 3');\n }\n\n try {\n // Re-yield chunk by chunk to accumulate text; done is held back until\n // onFinish has fired.\n for await (const chunk of streamToWire(phase3(fullMessages).fullStream, undefined, { debug })) {\n accumulatedText += extractWireText(chunk);\n if (chunk.includes('\"type\":\"done\"')) continue;\n yield chunk;\n }\n\n if (debug) {\n console.debug('[juneau] withToolRecovery → phase 3 complete');\n }\n\n onFinish?.({ text: accumulatedText });\n yield wireDone();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (debug) {\n console.debug(`[juneau] withToolRecovery → phase 3 FAILED: \"${message}\"`);\n }\n yield wireError(message);\n }\n return;\n }\n\n if (debug) {\n console.debug(\n '[juneau] withToolRecovery → phase 3 configured but phase 1 result exposes no message history — emitting done'\n );\n }\n } else if (!producedText && !skillSet.hadFailure && debug) {\n console.debug(\n '[juneau] withToolRecovery → no failure, no text, no phase3 — emitting done (Gemini silent response)'\n );\n }\n\n onFinish?.({ text: accumulatedText });\n yield wireDone();\n}\n\n/**\n * Resolves the full message history (incl. tool-call/tool-result turns) from a\n * consumed ai-sdk StreamTextResult.\n *\n * ai-sdk v7: `result.messages` is the promise that resolves to ALL turns —\n * user, assistant(tool-call), tool(tool-result) — after the stream is consumed.\n * `result.response.messages` may resolve to an incomplete subset (observed:\n * tool-call turn without the following tool-result turn, which Gemini rejects),\n * so it is only used as a fallback when `messages` is unavailable.\n *\n * Both promises resolve only after the fullStream has been fully consumed,\n * which is guaranteed at the call site.\n */\nasync function resolvePhase1Messages(result: {\n messages?: 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","formatWireEvent","event","pickLabel","labels","language","validateSkills","skills","knownNames","name","skill","toolName","createSkillSet","options","debug","activityBuffer","calledSkillNames","hadFailure","failureContext","tools","input","startMs","executeContext","part","durationMs","err","message","failedLabels","buildSkillIndex","skillSet","traits","selectSkills","skillNames","TEXT_CHUNK_TYPES","IGNORED_CHUNK_TYPES","streamToWire","fullStream","chunk","c","type","activities","remaining","wireError","wireDone","extractWireText","line","withToolRecovery","phase1","phase2","phase3","onFinish","producedText","accumulatedText","result1","result2","fullMessages","resolvePhase1Messages","containsToolResult","response","m"],"mappings":"gFAaO,SAASA,EAAcC,EAAsC,CAGlE,MAAMC,EAAwBD,EAAS,IAAIE,G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EAIJoC,IAAW,CAAE,KAAME,EAAiB,EACpC,MAAMT,EAAA,CACR,CAeA,eAAea,EAAsB3D,EAGP,CAC5B,GAAIA,EAAO,SAAU,CACnB,MAAML,EAAW,MAAMK,EAAO,SAC9B,GAAI,MAAM,QAAQL,CAAQ,GAAKA,EAAS,OAAS,EAC/C,OAAOA,CAEX,CAEA,GAAIK,EAAO,SAAU,CACnB,MAAM6D,EAAW,MAAM7D,EAAO,SAC9B,GAAI,MAAM,QAAQ6D,GAAU,QAAQ,GAAKA,EAAS,SAAS,OAAS,EAClE,OAAOA,EAAS,QAEpB,CAEA,OAAO,IACT,CAOA,SAASD,EAAmBjE,EAA8B,CACxD,OAAOA,EAAS,KAAMmE,GAAM,CAC1B,MAAMjE,EAAMiE,EACZ,OAAIjE,EAAI,OAAS,OAAe,GAC5B,MAAM,QAAQA,EAAI,OAAO,EACpBA,EAAI,QAAQ,KAChB6B,GAAUA,EAA2B,OAAS,aAAA,EAG5C,EACT,CAAC,CACH"}
|
package/dist/server/index.d.ts
CHANGED
|
@@ -4,4 +4,5 @@ export { buildSkillIndex, selectSkills } from './skillIndex';
|
|
|
4
4
|
export { streamToWire } from './streamToWire';
|
|
5
5
|
export { withToolRecovery } from './withToolRecovery';
|
|
6
6
|
export type { SkillSet, SkillDefinition, SkillExecuteContext, SkillSetOptions, ToolRecoveryOptions, ToolRecoveryStreamResult, StreamToWireOptions, CoreMessage } from './types';
|
|
7
|
+
export type { AiMessage, AiMessageRole, AiMessagePart, AiTextPart, AiSerializedMessage, AiStreamEvent, JuneauWireEvent, JuneauWireText, JuneauWireActivity, JuneauWirePart, JuneauWireDone, JuneauWireError, } from '../core/types';
|
|
7
8
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,YAAY,EAAE,QAAQ,EAAE,eAAe,EAAE,mBAAmB,EAAE,eAAe,EAAE,mBAAmB,EAAE,wBAAwB,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,eAAe,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,YAAY,EAAE,QAAQ,EAAE,eAAe,EAAE,mBAAmB,EAAE,eAAe,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAGhL,YAAY,EACV,SAAS,EACT,aAAa,EACb,aAAa,EACb,UAAU,EACV,mBAAmB,EACnB,aAAa,EACb,eAAe,EACf,cAAc,EACd,kBAAkB,EAClB,cAAc,EACd,cAAc,EACd,eAAe,GAChB,MAAM,eAAe,CAAC"}
|
package/dist/server/index.js
CHANGED
|
@@ -1,114 +1,114 @@
|
|
|
1
|
-
function
|
|
2
|
-
const
|
|
3
|
-
const i = e.parts.filter((
|
|
1
|
+
function O(n) {
|
|
2
|
+
const t = n.map((e) => {
|
|
3
|
+
const i = e.parts.filter((r) => r.type === "text").map((r) => r.text).join("");
|
|
4
4
|
return { role: e.role, content: i };
|
|
5
|
-
}),
|
|
6
|
-
for (let e = 0; e <
|
|
7
|
-
const i =
|
|
8
|
-
i.role === "user" &&
|
|
5
|
+
}), o = [];
|
|
6
|
+
for (let e = 0; e < t.length; e++) {
|
|
7
|
+
const i = t[e], r = o[o.length - 1];
|
|
8
|
+
i.role === "user" && r?.role === "user" && o.push({ role: "assistant", content: "…" }), o.push(i);
|
|
9
9
|
}
|
|
10
|
-
return
|
|
10
|
+
return o.filter((e) => e.content.length > 0);
|
|
11
11
|
}
|
|
12
|
-
function
|
|
13
|
-
return `data: ${JSON.stringify(
|
|
12
|
+
function h(n) {
|
|
13
|
+
return `data: ${JSON.stringify(n)}
|
|
14
14
|
|
|
15
15
|
`;
|
|
16
16
|
}
|
|
17
|
-
function
|
|
18
|
-
return
|
|
17
|
+
function y(n, t) {
|
|
18
|
+
return n[t] ?? n.en;
|
|
19
19
|
}
|
|
20
|
-
function
|
|
21
|
-
const
|
|
22
|
-
for (const [
|
|
20
|
+
function k(n) {
|
|
21
|
+
const t = new Set(Object.keys(n));
|
|
22
|
+
for (const [o, e] of Object.entries(n))
|
|
23
23
|
if (e.tools) {
|
|
24
24
|
for (const i of e.tools)
|
|
25
|
-
if (!
|
|
25
|
+
if (!t.has(i))
|
|
26
26
|
throw new Error(
|
|
27
|
-
`[juneau] createSkillSet: skill "${
|
|
27
|
+
`[juneau] createSkillSet: skill "${o}" references unknown tool "${i}". Known skills: ${[...t].join(", ")}`
|
|
28
28
|
);
|
|
29
29
|
}
|
|
30
30
|
}
|
|
31
|
-
function
|
|
32
|
-
|
|
33
|
-
const
|
|
34
|
-
let
|
|
35
|
-
const
|
|
36
|
-
for (const [
|
|
37
|
-
|
|
38
|
-
description:
|
|
39
|
-
parameters:
|
|
40
|
-
execute: async (
|
|
41
|
-
|
|
42
|
-
const
|
|
31
|
+
function W(n, t = {}) {
|
|
32
|
+
k(n);
|
|
33
|
+
const o = t.language ?? "en", e = t.debug ?? !1, i = [], r = [];
|
|
34
|
+
let s = !1, c = null;
|
|
35
|
+
const f = {};
|
|
36
|
+
for (const [l, a] of Object.entries(n))
|
|
37
|
+
f[l] = {
|
|
38
|
+
description: a.description,
|
|
39
|
+
parameters: a.input,
|
|
40
|
+
execute: async (u) => {
|
|
41
|
+
r.includes(l) || r.push(l), e && console.debug(`[juneau] skill "${l}" → executing, input:`, u);
|
|
42
|
+
const g = e ? Date.now() : 0;
|
|
43
43
|
i.push(
|
|
44
|
-
|
|
44
|
+
h({
|
|
45
45
|
type: "activity",
|
|
46
|
-
id:
|
|
47
|
-
title:
|
|
46
|
+
id: l,
|
|
47
|
+
title: y(a.labels.running, o),
|
|
48
48
|
status: "running",
|
|
49
|
-
metadata: { skill:
|
|
49
|
+
metadata: { skill: l }
|
|
50
50
|
})
|
|
51
51
|
);
|
|
52
|
-
const
|
|
53
|
-
emit: (
|
|
54
|
-
e && console.debug(`[juneau] skill "${
|
|
52
|
+
const $ = {
|
|
53
|
+
emit: (d) => {
|
|
54
|
+
e && console.debug(`[juneau] skill "${l}" → emitting part "${d.type}"`), i.push(h({ type: "part", part: d }));
|
|
55
55
|
}
|
|
56
56
|
};
|
|
57
57
|
try {
|
|
58
|
-
const
|
|
59
|
-
return e && console.debug(`[juneau] skill "${
|
|
60
|
-
|
|
58
|
+
const d = await a.execute(u, $), p = e ? Date.now() - g : 0;
|
|
59
|
+
return e && console.debug(`[juneau] skill "${l}" → done in ${p}ms, result:`, d), i.push(
|
|
60
|
+
h({
|
|
61
61
|
type: "activity",
|
|
62
|
-
id:
|
|
63
|
-
title:
|
|
62
|
+
id: l,
|
|
63
|
+
title: y(a.labels.done, o),
|
|
64
64
|
status: "done",
|
|
65
|
-
metadata: { skill:
|
|
65
|
+
metadata: { skill: l }
|
|
66
66
|
})
|
|
67
|
-
),
|
|
68
|
-
} catch (
|
|
69
|
-
const
|
|
70
|
-
e && console.debug(`[juneau] skill "${
|
|
71
|
-
const
|
|
67
|
+
), d;
|
|
68
|
+
} catch (d) {
|
|
69
|
+
const p = e ? Date.now() - g : 0, v = d instanceof Error ? d.message : String(d);
|
|
70
|
+
e && console.debug(`[juneau] skill "${l}" → FAILED in ${p}ms: "${v}"`);
|
|
71
|
+
const T = a.labels.failed ?? { cs: "Nepodařilo se", en: "Failed" };
|
|
72
72
|
throw i.push(
|
|
73
|
-
|
|
73
|
+
h({
|
|
74
74
|
type: "activity",
|
|
75
|
-
id:
|
|
76
|
-
title:
|
|
75
|
+
id: l,
|
|
76
|
+
title: y(T, o),
|
|
77
77
|
status: "failed",
|
|
78
|
-
metadata: { skill:
|
|
78
|
+
metadata: { skill: l }
|
|
79
79
|
})
|
|
80
|
-
),
|
|
80
|
+
), s = !0, c = `Tool "${l}" failed: ${v}`, d;
|
|
81
81
|
}
|
|
82
82
|
}
|
|
83
83
|
};
|
|
84
84
|
return {
|
|
85
|
-
tools:
|
|
86
|
-
skills:
|
|
87
|
-
calledSkillNames:
|
|
85
|
+
tools: f,
|
|
86
|
+
skills: n,
|
|
87
|
+
calledSkillNames: r,
|
|
88
88
|
drainActivities() {
|
|
89
89
|
return i.splice(0, i.length);
|
|
90
90
|
},
|
|
91
91
|
get hadFailure() {
|
|
92
|
-
return
|
|
92
|
+
return s;
|
|
93
93
|
},
|
|
94
94
|
get failureContext() {
|
|
95
|
-
return
|
|
95
|
+
return c;
|
|
96
96
|
}
|
|
97
97
|
};
|
|
98
98
|
}
|
|
99
|
-
function A(
|
|
100
|
-
return Object.entries(
|
|
101
|
-
const e = [
|
|
102
|
-
return
|
|
99
|
+
function A(n) {
|
|
100
|
+
return Object.entries(n.skills).map(([t, o]) => {
|
|
101
|
+
const e = [o.readOnly === !1 ? "write" : "read"];
|
|
102
|
+
return o.requiresConfirmation && e.push("requires confirmation"), `- ${t} (${e.join(", ")}): ${o.description}`;
|
|
103
103
|
}).join(`
|
|
104
104
|
`);
|
|
105
105
|
}
|
|
106
|
-
function E(
|
|
107
|
-
return
|
|
106
|
+
function E(n, t) {
|
|
107
|
+
return t.map((o) => n.skills[o]).filter((o) => o?.instructions).map((o) => o.instructions).join(`
|
|
108
108
|
|
|
109
109
|
`);
|
|
110
110
|
}
|
|
111
|
-
const
|
|
111
|
+
const w = /* @__PURE__ */ new Set(["text-delta", "text"]), S = /* @__PURE__ */ new Set([
|
|
112
112
|
"tool-call",
|
|
113
113
|
"tool-result",
|
|
114
114
|
"tool-input-start",
|
|
@@ -122,120 +122,136 @@ const v = /* @__PURE__ */ new Set(["text-delta", "text"]), T = /* @__PURE__ */ n
|
|
|
122
122
|
"response-metadata",
|
|
123
123
|
"stream-start"
|
|
124
124
|
]);
|
|
125
|
-
async function*
|
|
126
|
-
const e =
|
|
127
|
-
for await (const i of
|
|
128
|
-
const
|
|
125
|
+
async function* m(n, t, o) {
|
|
126
|
+
const e = o?.debug ?? !1;
|
|
127
|
+
for await (const i of n) {
|
|
128
|
+
const r = i, s = r.type;
|
|
129
129
|
if (e)
|
|
130
|
-
if (
|
|
131
|
-
const
|
|
132
|
-
console.debug(`[juneau] streamToWire chunk: ${
|
|
133
|
-
} else
|
|
134
|
-
if (
|
|
135
|
-
if (
|
|
136
|
-
const
|
|
137
|
-
e &&
|
|
138
|
-
for (const
|
|
139
|
-
yield
|
|
130
|
+
if (s && w.has(s)) {
|
|
131
|
+
const c = r.text ?? r.textDelta;
|
|
132
|
+
console.debug(`[juneau] streamToWire chunk: ${s} ${JSON.stringify(c ?? "")}`);
|
|
133
|
+
} else s === "tool-call" ? console.debug(`[juneau] streamToWire chunk: tool-call "${r.toolName ?? r.name ?? "?"}"`) : s === "tool-result" ? console.debug("[juneau] streamToWire chunk: tool-result (ignored)") : s && (S.has(s) ? console.debug(`[juneau] streamToWire chunk: ${s} (ignored)`) : console.debug(`[juneau] streamToWire chunk: ${s} (unknown)`));
|
|
134
|
+
if (s && w.has(s)) {
|
|
135
|
+
if (t) {
|
|
136
|
+
const f = t.drainActivities();
|
|
137
|
+
e && f.length > 0 && console.debug(`[juneau] streamToWire → draining ${f.length} activities`);
|
|
138
|
+
for (const l of f)
|
|
139
|
+
yield l;
|
|
140
140
|
}
|
|
141
|
-
const
|
|
142
|
-
|
|
141
|
+
const c = r.text ?? r.textDelta;
|
|
142
|
+
c && (e && console.debug(`[juneau] streamToWire → yielding text ${JSON.stringify(c)}`), yield `data: ${JSON.stringify({ type: "text", text: c })}
|
|
143
143
|
|
|
144
144
|
`);
|
|
145
145
|
}
|
|
146
146
|
}
|
|
147
|
-
if (
|
|
148
|
-
const i =
|
|
147
|
+
if (t) {
|
|
148
|
+
const i = t.drainActivities();
|
|
149
149
|
e && i.length > 0 && console.debug(`[juneau] streamToWire → draining ${i.length} activities (end of stream)`);
|
|
150
|
-
for (const
|
|
151
|
-
yield
|
|
150
|
+
for (const r of i)
|
|
151
|
+
yield r;
|
|
152
152
|
}
|
|
153
153
|
e && console.debug("[juneau] streamToWire → end of stream, emitting done"), yield `data: ${JSON.stringify({ type: "done" })}
|
|
154
154
|
|
|
155
155
|
`;
|
|
156
156
|
}
|
|
157
|
-
function j(
|
|
158
|
-
return `data: ${JSON.stringify({ type: "error", message:
|
|
157
|
+
function j(n) {
|
|
158
|
+
return `data: ${JSON.stringify({ type: "error", message: n })}
|
|
159
159
|
|
|
160
160
|
`;
|
|
161
161
|
}
|
|
162
|
-
function
|
|
162
|
+
function b() {
|
|
163
163
|
return `data: ${JSON.stringify({ type: "done" })}
|
|
164
164
|
|
|
165
165
|
`;
|
|
166
166
|
}
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
167
|
+
function x(n) {
|
|
168
|
+
let t = "";
|
|
169
|
+
for (const o of n.split(`
|
|
170
|
+
`))
|
|
171
|
+
if (o.startsWith("data: "))
|
|
172
|
+
try {
|
|
173
|
+
const e = JSON.parse(o.slice(6));
|
|
174
|
+
e.type === "text" && typeof e.text == "string" && (t += e.text);
|
|
175
|
+
} catch {
|
|
176
|
+
}
|
|
177
|
+
return t;
|
|
178
|
+
}
|
|
179
|
+
async function* F(n) {
|
|
180
|
+
const { phase1: t, phase2: o, phase3: e, skillSet: i, onFinish: r, debug: s = !1 } = n;
|
|
181
|
+
s && console.debug("[juneau] withToolRecovery → phase 1 start");
|
|
182
|
+
let c = !1, f = "";
|
|
183
|
+
const l = t();
|
|
184
|
+
for await (const a of m(l.fullStream, i, { debug: s }))
|
|
185
|
+
f += x(a), a.includes('"type":"text"') && (c = !0), !a.includes('"type":"done"') && (yield a);
|
|
186
|
+
if (s && console.debug(
|
|
187
|
+
`[juneau] withToolRecovery → phase 1 complete, textProduced=${c}, hadFailure=${i.hadFailure}`
|
|
188
|
+
), i.hadFailure && !c && i.failureContext) {
|
|
189
|
+
s && console.debug("[juneau] withToolRecovery → hadFailure=true, textProduced=false → triggering phase 2");
|
|
178
190
|
try {
|
|
179
|
-
const a =
|
|
180
|
-
|
|
191
|
+
const a = o(i.failureContext);
|
|
192
|
+
for await (const u of m(a.fullStream, void 0, { debug: s }))
|
|
193
|
+
f += x(u), !u.includes('"type":"done"') && (yield u);
|
|
194
|
+
s && console.debug("[juneau] withToolRecovery → phase 2 complete"), r?.({ text: f }), yield b();
|
|
181
195
|
} catch (a) {
|
|
182
|
-
const
|
|
183
|
-
|
|
196
|
+
const u = a instanceof Error ? a.message : String(a);
|
|
197
|
+
s && console.debug(`[juneau] withToolRecovery → phase 2 FAILED: "${u}"`), yield j(u);
|
|
184
198
|
}
|
|
185
199
|
return;
|
|
186
200
|
}
|
|
187
|
-
if (!
|
|
188
|
-
const a = await
|
|
201
|
+
if (!c && !i.hadFailure && e) {
|
|
202
|
+
const a = await N(l);
|
|
189
203
|
if (a) {
|
|
190
|
-
|
|
204
|
+
s && (console.debug(
|
|
191
205
|
`[juneau] withToolRecovery → phase 3 messages resolved (${a.length}):`,
|
|
192
206
|
JSON.stringify(a, null, 2)
|
|
193
|
-
),
|
|
207
|
+
), R(a) || console.debug(
|
|
194
208
|
"[juneau] withToolRecovery → WARNING: resolved history contains no tool-result turn — Gemini will likely reject it as an invalid conversation structure"
|
|
195
209
|
), console.debug("[juneau] withToolRecovery → no failure, no text → triggering phase 3"));
|
|
196
210
|
try {
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
211
|
+
for await (const u of m(e(a).fullStream, void 0, { debug: s }))
|
|
212
|
+
f += x(u), !u.includes('"type":"done"') && (yield u);
|
|
213
|
+
s && console.debug("[juneau] withToolRecovery → phase 3 complete"), r?.({ text: f }), yield b();
|
|
214
|
+
} catch (u) {
|
|
215
|
+
const g = u instanceof Error ? u.message : String(u);
|
|
216
|
+
s && console.debug(`[juneau] withToolRecovery → phase 3 FAILED: "${g}"`), yield j(g);
|
|
201
217
|
}
|
|
202
218
|
return;
|
|
203
219
|
}
|
|
204
|
-
|
|
220
|
+
s && console.debug(
|
|
205
221
|
"[juneau] withToolRecovery → phase 3 configured but phase 1 result exposes no message history — emitting done"
|
|
206
222
|
);
|
|
207
|
-
} else !
|
|
223
|
+
} else !c && !i.hadFailure && s && console.debug(
|
|
208
224
|
"[juneau] withToolRecovery → no failure, no text, no phase3 — emitting done (Gemini silent response)"
|
|
209
225
|
);
|
|
210
|
-
yield
|
|
226
|
+
r?.({ text: f }), yield b();
|
|
211
227
|
}
|
|
212
|
-
async function
|
|
213
|
-
if (
|
|
214
|
-
const
|
|
215
|
-
if (Array.isArray(
|
|
216
|
-
return
|
|
228
|
+
async function N(n) {
|
|
229
|
+
if (n.messages) {
|
|
230
|
+
const t = await n.messages;
|
|
231
|
+
if (Array.isArray(t) && t.length > 0)
|
|
232
|
+
return t;
|
|
217
233
|
}
|
|
218
|
-
if (
|
|
219
|
-
const
|
|
220
|
-
if (Array.isArray(
|
|
221
|
-
return
|
|
234
|
+
if (n.response) {
|
|
235
|
+
const t = await n.response;
|
|
236
|
+
if (Array.isArray(t?.messages) && t.messages.length > 0)
|
|
237
|
+
return t.messages;
|
|
222
238
|
}
|
|
223
239
|
return null;
|
|
224
240
|
}
|
|
225
|
-
function
|
|
226
|
-
return
|
|
227
|
-
const
|
|
228
|
-
return
|
|
241
|
+
function R(n) {
|
|
242
|
+
return n.some((t) => {
|
|
243
|
+
const o = t;
|
|
244
|
+
return o.role === "tool" ? !0 : Array.isArray(o.content) ? o.content.some(
|
|
229
245
|
(e) => e.type === "tool-result"
|
|
230
246
|
) : !1;
|
|
231
247
|
});
|
|
232
248
|
}
|
|
233
249
|
export {
|
|
234
250
|
A as buildSkillIndex,
|
|
235
|
-
|
|
251
|
+
W as createSkillSet,
|
|
236
252
|
E as selectSkills,
|
|
237
|
-
|
|
238
|
-
|
|
253
|
+
m as streamToWire,
|
|
254
|
+
O as toSdkMessages,
|
|
239
255
|
F as withToolRecovery
|
|
240
256
|
};
|
|
241
257
|
//# sourceMappingURL=index.js.map
|