juneau 0.3.4 → 0.4.1
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 +64 -2
- package/dist/adapters/dashboardAdapter.d.ts.map +1 -1
- package/dist/adapters/mockAdapter.d.ts.map +1 -1
- package/dist/components/AiChat/AiChat.d.ts +8 -1
- package/dist/components/AiChat/AiChat.d.ts.map +1 -1
- package/dist/components/AiInput/AiInput.d.ts.map +1 -1
- package/dist/components/AiMessageBubble/AiMessageBubble.d.ts +4 -1
- package/dist/components/AiMessageBubble/AiMessageBubble.d.ts.map +1 -1
- package/dist/components/AiMessageList/AiMessageList.d.ts +4 -1
- package/dist/components/AiMessageList/AiMessageList.d.ts.map +1 -1
- package/dist/components/AiSidebar/AiSidebar.d.ts +8 -1
- package/dist/components/AiSidebar/AiSidebar.d.ts.map +1 -1
- package/dist/components/parts/AiMessagePartRenderer.d.ts +11 -1
- package/dist/components/parts/AiMessagePartRenderer.d.ts.map +1 -1
- package/dist/core/types.d.ts +14 -4
- package/dist/core/types.d.ts.map +1 -1
- package/dist/index.cjs +28 -28
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2769 -2743
- package/dist/index.js.map +1 -1
- package/dist/server/createSkillSet.d.ts +0 -6
- package/dist/server/createSkillSet.d.ts.map +1 -1
- package/dist/server/index.cjs +9 -6
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.ts +2 -1
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +156 -123
- package/dist/server/index.js.map +1 -1
- package/dist/server/skillIndex.d.ts +25 -0
- package/dist/server/skillIndex.d.ts.map +1 -0
- package/dist/server/types.d.ts +45 -2
- package/dist/server/types.d.ts.map +1 -1
- package/dist/style.css +1 -1
- package/package.json +1 -1
|
@@ -1,12 +1,6 @@
|
|
|
1
1
|
import type { ZodType } from 'zod';
|
|
2
2
|
import type { SkillDefinition, SkillSet, SkillSetOptions } from './types';
|
|
3
3
|
type SkillMap = Record<string, SkillDefinition<ZodType>>;
|
|
4
|
-
/**
|
|
5
|
-
* Takes a map of skill definitions and returns a SkillSet containing:
|
|
6
|
-
* - tools: ready-made tool definitions for ai-sdk's streamText({ tools })
|
|
7
|
-
* - drainActivities(): flush buffered activity wire SSE strings
|
|
8
|
-
* - hadFailure / failureContext: for driving tool failure recovery
|
|
9
|
-
*/
|
|
10
4
|
export declare function createSkillSet(skills: SkillMap, options?: SkillSetOptions): SkillSet;
|
|
11
5
|
export {};
|
|
12
6
|
//# sourceMappingURL=createSkillSet.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createSkillSet.d.ts","sourceRoot":"","sources":["../../src/server/createSkillSet.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,KAAK,CAAC;AACnC,OAAO,KAAK,EAAE,eAAe,
|
|
1
|
+
{"version":3,"file":"createSkillSet.d.ts","sourceRoot":"","sources":["../../src/server/createSkillSet.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,KAAK,CAAC;AACnC,OAAO,KAAK,EAAE,eAAe,EAAuB,QAAQ,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE/F,KAAK,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,CAAC,CAAC;AAwCzD,wBAAgB,cAAc,CAAC,MAAM,EAAE,QAAQ,EAAE,OAAO,GAAE,eAAoB,GAAG,QAAQ,CAqHxF"}
|
package/dist/server/index.cjs
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function S(o){const n=o.map(e=>{const s=e.parts.filter(t=>t.type==="text").map(t=>t.text).join("");return{role:e.role,content:s}}),i=[];for(let e=0;e<n.length;e++){const s=n[e],t=i[i.length-1];s.role==="user"&&t?.role==="user"&&i.push({role:"assistant",content:"…"}),i.push(s)}return i.filter(e=>e.content.length>0)}function d(o){return`data: ${JSON.stringify(o)}
|
|
2
2
|
|
|
3
|
-
`}function
|
|
3
|
+
`}function p(o,n){return o[n]??o.en}function T(o){const n=new Set(Object.keys(o));for(const[i,e]of Object.entries(o))if(e.tools){for(const s of e.tools)if(!n.has(s))throw new Error(`[juneau] createSkillSet: skill "${i}" references unknown tool "${s}". Known skills: ${[...n].join(", ")}`)}}function x(o,n={}){T(o);const i=n.language??"en",e=n.debug??!1,s=[],t=[];let l=!1,u=null;const a={};for(const[r,f]of Object.entries(o))a[r]={description:f.description,parameters:f.input,execute:async y=>{t.includes(r)||t.push(r),e&&console.debug(`[juneau] skill "${r}" → executing, input:`,y);const m=e?Date.now():0;s.push(d({type:"activity",id:r,title:p(f.labels.running,i),status:"running",metadata:{skill:r}}));const w={emit:c=>{e&&console.debug(`[juneau] skill "${r}" → emitting part "${c.type}"`),s.push(d({type:"part",part:c}))}};try{const c=await f.execute(y,w),h=e?Date.now()-m:0;return e&&console.debug(`[juneau] skill "${r}" → done in ${h}ms, result:`,c),s.push(d({type:"activity",id:r,title:p(f.labels.done,i),status:"done",metadata:{skill:r}})),c}catch(c){const h=e?Date.now()-m:0,b=c instanceof Error?c.message:String(c);e&&console.debug(`[juneau] skill "${r}" → FAILED in ${h}ms: "${b}"`);const $=f.labels.failed??{cs:"Nepodařilo se",en:"Failed"};throw s.push(d({type:"activity",id:r,title:p($,i),status:"failed",metadata:{skill:r}})),l=!0,u=`Tool "${r}" failed: ${b}`,c}}};return{tools:a,skills:o,calledSkillNames:t,drainActivities(){return s.splice(0,s.length)},get hadFailure(){return l},get failureContext(){return u}}}function k(o){return Object.entries(o.skills).map(([n,i])=>{const e=[i.readOnly===!1?"write":"read"];return i.requiresConfirmation&&e.push("requires confirmation"),`- ${n} (${e.join(", ")}): ${i.description}`}).join(`
|
|
4
|
+
`)}function N(o,n){return n.map(i=>o.skills[i]).filter(i=>i?.instructions).map(i=>i.instructions).join(`
|
|
4
5
|
|
|
5
|
-
`)}}if(n){const
|
|
6
|
+
`)}const v=new Set(["text-delta","text"]),R=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*g(o,n,i){const e=i?.debug??!1;for await(const s of o){const t=s,l=t.type;if(e)if(l&&v.has(l)){const u=t.text??t.textDelta;console.debug(`[juneau] streamToWire chunk: ${l} ${JSON.stringify(u??"")}`)}else l==="tool-call"?console.debug(`[juneau] streamToWire chunk: tool-call "${t.toolName??t.name??"?"}"`):l==="tool-result"?console.debug("[juneau] streamToWire chunk: tool-result (ignored)"):l&&(R.has(l)?console.debug(`[juneau] streamToWire chunk: ${l} (ignored)`):console.debug(`[juneau] streamToWire chunk: ${l} (unknown)`));if(l&&v.has(l)){if(n){const a=n.drainActivities();e&&a.length>0&&console.debug(`[juneau] streamToWire → draining ${a.length} activities`);for(const r of a)yield r}const u=t.text??t.textDelta;u&&(e&&console.debug(`[juneau] streamToWire → yielding text ${JSON.stringify(u)}`),yield`data: ${JSON.stringify({type:"text",text:u})}
|
|
6
7
|
|
|
7
|
-
`}
|
|
8
|
+
`)}}if(n){const s=n.drainActivities();e&&s.length>0&&console.debug(`[juneau] streamToWire → draining ${s.length} activities (end of stream)`);for(const t of s)yield t}e&&console.debug("[juneau] streamToWire → end of stream, emitting done"),yield`data: ${JSON.stringify({type:"done"})}
|
|
8
9
|
|
|
9
|
-
`}function
|
|
10
|
+
`}function j(o){return`data: ${JSON.stringify({type:"error",message:o})}
|
|
10
11
|
|
|
11
|
-
`}
|
|
12
|
+
`}function O(){return`data: ${JSON.stringify({type:"done"})}
|
|
13
|
+
|
|
14
|
+
`}async function*A(o){const{phase1:n,phase2:i,phase3:e,skillSet:s,debug:t=!1}=o;t&&console.debug("[juneau] withToolRecovery → phase 1 start");let l=!1;const u=n();for await(const a of g(u.fullStream,s,{debug:t}))a.includes('"type":"text"')&&(l=!0),!a.includes('"type":"done"')&&(yield a);if(t&&console.debug(`[juneau] withToolRecovery → phase 1 complete, textProduced=${l}, hadFailure=${s.hadFailure}`),s.hadFailure&&!l&&s.failureContext){t&&console.debug("[juneau] withToolRecovery → hadFailure=true, textProduced=false → triggering phase 2");try{const a=i(s.failureContext);yield*g(a.fullStream,void 0,{debug:t}),t&&console.debug("[juneau] withToolRecovery → phase 2 complete")}catch(a){const r=a instanceof Error?a.message:String(a);t&&console.debug(`[juneau] withToolRecovery → phase 2 FAILED: "${r}"`),yield j(r)}return}if(!l&&!s.hadFailure&&e){const a=await E(u);if(a){t&&(console.debug(`[juneau] withToolRecovery → phase 3 messages resolved (${a.length}):`,JSON.stringify(a,null,2)),W(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{yield*g(e(a).fullStream,void 0,{debug:t}),t&&console.debug("[juneau] withToolRecovery → phase 3 complete")}catch(r){const f=r instanceof Error?r.message:String(r);t&&console.debug(`[juneau] withToolRecovery → phase 3 FAILED: "${f}"`),yield j(f)}return}t&&console.debug("[juneau] withToolRecovery → phase 3 configured but phase 1 result exposes no message history — emitting done")}else!l&&!s.hadFailure&&t&&console.debug("[juneau] withToolRecovery → no failure, no text, no phase3 — emitting done (Gemini silent response)");yield O()}async function E(o){if(o.messages){const n=await o.messages;if(Array.isArray(n)&&n.length>0)return n}if(o.response){const n=await o.response;if(Array.isArray(n?.messages)&&n.messages.length>0)return n.messages}return null}function W(o){return o.some(n=>{const i=n;return i.role==="tool"?!0:Array.isArray(i.content)?i.content.some(e=>e.type==="tool-result"):!1})}exports.buildSkillIndex=k;exports.createSkillSet=x;exports.selectSkills=N;exports.streamToWire=g;exports.toSdkMessages=S;exports.withToolRecovery=A;
|
|
12
15
|
//# 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\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,IAAI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essages.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,MAAM,IAAI,MACR,mCAAmCF,CAAI,8BAA8BE,CAAQ,oBAC1D,CAAC,GAAGH,CAAU,EAAE,KAAK,IAAI,CA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AI7D,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
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { toSdkMessages } from './toSdkMessages';
|
|
2
2
|
export { createSkillSet } from './createSkillSet';
|
|
3
|
+
export { buildSkillIndex, selectSkills } from './skillIndex';
|
|
3
4
|
export { streamToWire } from './streamToWire';
|
|
4
5
|
export { withToolRecovery } from './withToolRecovery';
|
|
5
|
-
export type { SkillSet, SkillDefinition, SkillSetOptions, ToolRecoveryOptions, ToolRecoveryStreamResult, StreamToWireOptions, CoreMessage } from './types';
|
|
6
|
+
export type { SkillSet, SkillDefinition, SkillExecuteContext, SkillSetOptions, ToolRecoveryOptions, ToolRecoveryStreamResult, StreamToWireOptions, CoreMessage } from './types';
|
|
6
7
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,YAAY,EAAE,QAAQ,EAAE,eAAe,EAAE,eAAe,EAAE,mBAAmB,EAAE,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"}
|
package/dist/server/index.js
CHANGED
|
@@ -1,83 +1,114 @@
|
|
|
1
|
-
function
|
|
2
|
-
const
|
|
3
|
-
const
|
|
4
|
-
return { role:
|
|
5
|
-
}),
|
|
6
|
-
for (let
|
|
7
|
-
const
|
|
8
|
-
|
|
1
|
+
function R(o) {
|
|
2
|
+
const n = o.map((e) => {
|
|
3
|
+
const i = e.parts.filter((t) => t.type === "text").map((t) => t.text).join("");
|
|
4
|
+
return { role: e.role, content: i };
|
|
5
|
+
}), s = [];
|
|
6
|
+
for (let e = 0; e < n.length; e++) {
|
|
7
|
+
const i = n[e], t = s[s.length - 1];
|
|
8
|
+
i.role === "user" && t?.role === "user" && s.push({ role: "assistant", content: "…" }), s.push(i);
|
|
9
9
|
}
|
|
10
|
-
return
|
|
10
|
+
return s.filter((e) => e.content.length > 0);
|
|
11
11
|
}
|
|
12
|
-
function
|
|
13
|
-
return `data: ${JSON.stringify(
|
|
12
|
+
function d(o) {
|
|
13
|
+
return `data: ${JSON.stringify(o)}
|
|
14
14
|
|
|
15
15
|
`;
|
|
16
16
|
}
|
|
17
|
-
function h(
|
|
18
|
-
return
|
|
17
|
+
function h(o, n) {
|
|
18
|
+
return o[n] ?? o.en;
|
|
19
19
|
}
|
|
20
|
-
function
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
20
|
+
function x(o) {
|
|
21
|
+
const n = new Set(Object.keys(o));
|
|
22
|
+
for (const [s, e] of Object.entries(o))
|
|
23
|
+
if (e.tools) {
|
|
24
|
+
for (const i of e.tools)
|
|
25
|
+
if (!n.has(i))
|
|
26
|
+
throw new Error(
|
|
27
|
+
`[juneau] createSkillSet: skill "${s}" references unknown tool "${i}". Known skills: ${[...n].join(", ")}`
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function O(o, n = {}) {
|
|
32
|
+
x(o);
|
|
33
|
+
const s = n.language ?? "en", e = n.debug ?? !1, i = [], t = [];
|
|
34
|
+
let l = !1, u = null;
|
|
35
|
+
const a = {};
|
|
36
|
+
for (const [r, f] of Object.entries(o))
|
|
37
|
+
a[r] = {
|
|
38
|
+
description: f.description,
|
|
39
|
+
parameters: f.input,
|
|
40
|
+
execute: async (y) => {
|
|
41
|
+
t.includes(r) || t.push(r), e && console.debug(`[juneau] skill "${r}" → executing, input:`, y);
|
|
42
|
+
const m = e ? Date.now() : 0;
|
|
43
|
+
i.push(
|
|
44
|
+
d({
|
|
33
45
|
type: "activity",
|
|
34
|
-
id:
|
|
35
|
-
title: h(
|
|
46
|
+
id: r,
|
|
47
|
+
title: h(f.labels.running, s),
|
|
36
48
|
status: "running",
|
|
37
|
-
metadata: { skill:
|
|
49
|
+
metadata: { skill: r }
|
|
38
50
|
})
|
|
39
51
|
);
|
|
52
|
+
const w = {
|
|
53
|
+
emit: (c) => {
|
|
54
|
+
e && console.debug(`[juneau] skill "${r}" → emitting part "${c.type}"`), i.push(d({ type: "part", part: c }));
|
|
55
|
+
}
|
|
56
|
+
};
|
|
40
57
|
try {
|
|
41
|
-
const c = await
|
|
42
|
-
return
|
|
43
|
-
|
|
58
|
+
const c = await f.execute(y, w), g = e ? Date.now() - m : 0;
|
|
59
|
+
return e && console.debug(`[juneau] skill "${r}" → done in ${g}ms, result:`, c), i.push(
|
|
60
|
+
d({
|
|
44
61
|
type: "activity",
|
|
45
|
-
id:
|
|
46
|
-
title: h(
|
|
62
|
+
id: r,
|
|
63
|
+
title: h(f.labels.done, s),
|
|
47
64
|
status: "done",
|
|
48
|
-
metadata: { skill:
|
|
65
|
+
metadata: { skill: r }
|
|
49
66
|
})
|
|
50
67
|
), c;
|
|
51
68
|
} catch (c) {
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
const
|
|
55
|
-
throw
|
|
56
|
-
|
|
69
|
+
const g = e ? Date.now() - m : 0, b = c instanceof Error ? c.message : String(c);
|
|
70
|
+
e && console.debug(`[juneau] skill "${r}" → FAILED in ${g}ms: "${b}"`);
|
|
71
|
+
const $ = f.labels.failed ?? { cs: "Nepodařilo se", en: "Failed" };
|
|
72
|
+
throw i.push(
|
|
73
|
+
d({
|
|
57
74
|
type: "activity",
|
|
58
|
-
id:
|
|
59
|
-
title: h(
|
|
75
|
+
id: r,
|
|
76
|
+
title: h($, s),
|
|
60
77
|
status: "failed",
|
|
61
|
-
metadata: { skill:
|
|
78
|
+
metadata: { skill: r }
|
|
62
79
|
})
|
|
63
|
-
),
|
|
80
|
+
), l = !0, u = `Tool "${r}" failed: ${b}`, c;
|
|
64
81
|
}
|
|
65
82
|
}
|
|
66
83
|
};
|
|
67
84
|
return {
|
|
68
|
-
tools:
|
|
85
|
+
tools: a,
|
|
86
|
+
skills: o,
|
|
87
|
+
calledSkillNames: t,
|
|
69
88
|
drainActivities() {
|
|
70
|
-
return
|
|
89
|
+
return i.splice(0, i.length);
|
|
71
90
|
},
|
|
72
91
|
get hadFailure() {
|
|
73
|
-
return
|
|
92
|
+
return l;
|
|
74
93
|
},
|
|
75
94
|
get failureContext() {
|
|
76
|
-
return
|
|
95
|
+
return u;
|
|
77
96
|
}
|
|
78
97
|
};
|
|
79
98
|
}
|
|
80
|
-
|
|
99
|
+
function A(o) {
|
|
100
|
+
return Object.entries(o.skills).map(([n, s]) => {
|
|
101
|
+
const e = [s.readOnly === !1 ? "write" : "read"];
|
|
102
|
+
return s.requiresConfirmation && e.push("requires confirmation"), `- ${n} (${e.join(", ")}): ${s.description}`;
|
|
103
|
+
}).join(`
|
|
104
|
+
`);
|
|
105
|
+
}
|
|
106
|
+
function E(o, n) {
|
|
107
|
+
return n.map((s) => o.skills[s]).filter((s) => s?.instructions).map((s) => s.instructions).join(`
|
|
108
|
+
|
|
109
|
+
`);
|
|
110
|
+
}
|
|
111
|
+
const v = /* @__PURE__ */ new Set(["text-delta", "text"]), T = /* @__PURE__ */ new Set([
|
|
81
112
|
"tool-call",
|
|
82
113
|
"tool-result",
|
|
83
114
|
"tool-input-start",
|
|
@@ -91,118 +122,120 @@ const b = /* @__PURE__ */ new Set(["text-delta", "text"]), w = /* @__PURE__ */ n
|
|
|
91
122
|
"response-metadata",
|
|
92
123
|
"stream-start"
|
|
93
124
|
]);
|
|
94
|
-
async function*
|
|
95
|
-
const
|
|
96
|
-
for await (const
|
|
97
|
-
const
|
|
98
|
-
if (
|
|
99
|
-
if (
|
|
100
|
-
const u =
|
|
101
|
-
console.debug(`[juneau] streamToWire chunk: ${
|
|
102
|
-
} else
|
|
103
|
-
if (
|
|
104
|
-
if (
|
|
105
|
-
const
|
|
106
|
-
|
|
107
|
-
for (const
|
|
108
|
-
yield
|
|
125
|
+
async function* p(o, n, s) {
|
|
126
|
+
const e = s?.debug ?? !1;
|
|
127
|
+
for await (const i of o) {
|
|
128
|
+
const t = i, l = t.type;
|
|
129
|
+
if (e)
|
|
130
|
+
if (l && v.has(l)) {
|
|
131
|
+
const u = t.text ?? t.textDelta;
|
|
132
|
+
console.debug(`[juneau] streamToWire chunk: ${l} ${JSON.stringify(u ?? "")}`);
|
|
133
|
+
} else l === "tool-call" ? console.debug(`[juneau] streamToWire chunk: tool-call "${t.toolName ?? t.name ?? "?"}"`) : l === "tool-result" ? console.debug("[juneau] streamToWire chunk: tool-result (ignored)") : l && (T.has(l) ? console.debug(`[juneau] streamToWire chunk: ${l} (ignored)`) : console.debug(`[juneau] streamToWire chunk: ${l} (unknown)`));
|
|
134
|
+
if (l && v.has(l)) {
|
|
135
|
+
if (n) {
|
|
136
|
+
const a = n.drainActivities();
|
|
137
|
+
e && a.length > 0 && console.debug(`[juneau] streamToWire → draining ${a.length} activities`);
|
|
138
|
+
for (const r of a)
|
|
139
|
+
yield r;
|
|
109
140
|
}
|
|
110
|
-
const u =
|
|
111
|
-
u && (
|
|
141
|
+
const u = t.text ?? t.textDelta;
|
|
142
|
+
u && (e && console.debug(`[juneau] streamToWire → yielding text ${JSON.stringify(u)}`), yield `data: ${JSON.stringify({ type: "text", text: u })}
|
|
112
143
|
|
|
113
144
|
`);
|
|
114
145
|
}
|
|
115
146
|
}
|
|
116
|
-
if (
|
|
117
|
-
const
|
|
118
|
-
|
|
119
|
-
for (const
|
|
120
|
-
yield
|
|
147
|
+
if (n) {
|
|
148
|
+
const i = n.drainActivities();
|
|
149
|
+
e && i.length > 0 && console.debug(`[juneau] streamToWire → draining ${i.length} activities (end of stream)`);
|
|
150
|
+
for (const t of i)
|
|
151
|
+
yield t;
|
|
121
152
|
}
|
|
122
|
-
|
|
153
|
+
e && console.debug("[juneau] streamToWire → end of stream, emitting done"), yield `data: ${JSON.stringify({ type: "done" })}
|
|
123
154
|
|
|
124
155
|
`;
|
|
125
156
|
}
|
|
126
|
-
function
|
|
127
|
-
return `data: ${JSON.stringify({ type: "error", message:
|
|
157
|
+
function j(o) {
|
|
158
|
+
return `data: ${JSON.stringify({ type: "error", message: o })}
|
|
128
159
|
|
|
129
160
|
`;
|
|
130
161
|
}
|
|
131
|
-
function
|
|
162
|
+
function k() {
|
|
132
163
|
return `data: ${JSON.stringify({ type: "done" })}
|
|
133
164
|
|
|
134
165
|
`;
|
|
135
166
|
}
|
|
136
|
-
async function*
|
|
137
|
-
const { phase1:
|
|
138
|
-
|
|
139
|
-
let
|
|
140
|
-
const u =
|
|
141
|
-
for await (const
|
|
142
|
-
|
|
143
|
-
if (
|
|
144
|
-
`[juneau] withToolRecovery → phase 1 complete, textProduced=${
|
|
145
|
-
),
|
|
146
|
-
|
|
167
|
+
async function* F(o) {
|
|
168
|
+
const { phase1: n, phase2: s, phase3: e, skillSet: i, debug: t = !1 } = o;
|
|
169
|
+
t && console.debug("[juneau] withToolRecovery → phase 1 start");
|
|
170
|
+
let l = !1;
|
|
171
|
+
const u = n();
|
|
172
|
+
for await (const a of p(u.fullStream, i, { debug: t }))
|
|
173
|
+
a.includes('"type":"text"') && (l = !0), !a.includes('"type":"done"') && (yield a);
|
|
174
|
+
if (t && console.debug(
|
|
175
|
+
`[juneau] withToolRecovery → phase 1 complete, textProduced=${l}, hadFailure=${i.hadFailure}`
|
|
176
|
+
), i.hadFailure && !l && i.failureContext) {
|
|
177
|
+
t && console.debug("[juneau] withToolRecovery → hadFailure=true, textProduced=false → triggering phase 2");
|
|
147
178
|
try {
|
|
148
|
-
const
|
|
149
|
-
yield*
|
|
150
|
-
} catch (
|
|
151
|
-
const
|
|
152
|
-
|
|
179
|
+
const a = s(i.failureContext);
|
|
180
|
+
yield* p(a.fullStream, void 0, { debug: t }), t && console.debug("[juneau] withToolRecovery → phase 2 complete");
|
|
181
|
+
} catch (a) {
|
|
182
|
+
const r = a instanceof Error ? a.message : String(a);
|
|
183
|
+
t && console.debug(`[juneau] withToolRecovery → phase 2 FAILED: "${r}"`), yield j(r);
|
|
153
184
|
}
|
|
154
185
|
return;
|
|
155
186
|
}
|
|
156
|
-
if (!
|
|
157
|
-
const
|
|
158
|
-
if (
|
|
159
|
-
|
|
160
|
-
`[juneau] withToolRecovery → phase 3 messages resolved (${
|
|
161
|
-
JSON.stringify(
|
|
162
|
-
),
|
|
187
|
+
if (!l && !i.hadFailure && e) {
|
|
188
|
+
const a = await S(u);
|
|
189
|
+
if (a) {
|
|
190
|
+
t && (console.debug(
|
|
191
|
+
`[juneau] withToolRecovery → phase 3 messages resolved (${a.length}):`,
|
|
192
|
+
JSON.stringify(a, null, 2)
|
|
193
|
+
), N(a) || console.debug(
|
|
163
194
|
"[juneau] withToolRecovery → WARNING: resolved history contains no tool-result turn — Gemini will likely reject it as an invalid conversation structure"
|
|
164
195
|
), console.debug("[juneau] withToolRecovery → no failure, no text → triggering phase 3"));
|
|
165
196
|
try {
|
|
166
|
-
yield*
|
|
167
|
-
} catch (
|
|
168
|
-
const
|
|
169
|
-
|
|
197
|
+
yield* p(e(a).fullStream, void 0, { debug: t }), t && console.debug("[juneau] withToolRecovery → phase 3 complete");
|
|
198
|
+
} catch (r) {
|
|
199
|
+
const f = r instanceof Error ? r.message : String(r);
|
|
200
|
+
t && console.debug(`[juneau] withToolRecovery → phase 3 FAILED: "${f}"`), yield j(f);
|
|
170
201
|
}
|
|
171
202
|
return;
|
|
172
203
|
}
|
|
173
|
-
|
|
204
|
+
t && console.debug(
|
|
174
205
|
"[juneau] withToolRecovery → phase 3 configured but phase 1 result exposes no message history — emitting done"
|
|
175
206
|
);
|
|
176
|
-
} else !
|
|
207
|
+
} else !l && !i.hadFailure && t && console.debug(
|
|
177
208
|
"[juneau] withToolRecovery → no failure, no text, no phase3 — emitting done (Gemini silent response)"
|
|
178
209
|
);
|
|
179
|
-
yield
|
|
210
|
+
yield k();
|
|
180
211
|
}
|
|
181
|
-
async function
|
|
182
|
-
if (
|
|
183
|
-
const
|
|
184
|
-
if (Array.isArray(
|
|
185
|
-
return
|
|
212
|
+
async function S(o) {
|
|
213
|
+
if (o.messages) {
|
|
214
|
+
const n = await o.messages;
|
|
215
|
+
if (Array.isArray(n) && n.length > 0)
|
|
216
|
+
return n;
|
|
186
217
|
}
|
|
187
|
-
if (
|
|
188
|
-
const
|
|
189
|
-
if (Array.isArray(
|
|
190
|
-
return
|
|
218
|
+
if (o.response) {
|
|
219
|
+
const n = await o.response;
|
|
220
|
+
if (Array.isArray(n?.messages) && n.messages.length > 0)
|
|
221
|
+
return n.messages;
|
|
191
222
|
}
|
|
192
223
|
return null;
|
|
193
224
|
}
|
|
194
|
-
function
|
|
195
|
-
return
|
|
196
|
-
const
|
|
197
|
-
return
|
|
198
|
-
(
|
|
225
|
+
function N(o) {
|
|
226
|
+
return o.some((n) => {
|
|
227
|
+
const s = n;
|
|
228
|
+
return s.role === "tool" ? !0 : Array.isArray(s.content) ? s.content.some(
|
|
229
|
+
(e) => e.type === "tool-result"
|
|
199
230
|
) : !1;
|
|
200
231
|
});
|
|
201
232
|
}
|
|
202
233
|
export {
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
234
|
+
A as buildSkillIndex,
|
|
235
|
+
O as createSkillSet,
|
|
236
|
+
E as selectSkills,
|
|
237
|
+
p as streamToWire,
|
|
238
|
+
R as toSdkMessages,
|
|
239
|
+
F as withToolRecovery
|
|
207
240
|
};
|
|
208
241
|
//# sourceMappingURL=index.js.map
|