Files
llama.cpp/ui/apps/chat/src/lib/services/tools.service.ts
T
Aleksander Grygier 67cf8967eb ui: move Llama Chat to SvelteKit 3 and its built-in service worker (#32463)
* ui: replace deprecated packages and fix npm audit findings

Swap the mdast stub for @types/mdast, move the katex override to 0.19.0,
and override glob, source-map and html-encoding-sniffer under
workbox-build and http-server so installs no longer pull deprecated
packages. Apply the non-breaking npm audit fixes to the lockfile.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: migrate Llama Chat to SvelteKit 3 and its built-in service worker

Move to SvelteKit 3, Vite 8, TypeScript 6 and Storybook 10.6. The
SvelteKit options move from svelte.config.js into sveltekit() in
vite.config.ts, $lib imports become #lib subpath imports from
package.json, and $app/environment becomes $app/env. Modules named
server.* or living under a server/ folder are server-only in SvelteKit 3,
so the llama-server components, store and enums move to llama-server
names.

@vite-pwa/sveltekit and Workbox give way to SvelteKit's own service
worker in src/service-worker, registered by usePwa(), which precaches the
app files and leaves API requests to the network. A small plugin emits
manifest.webmanifest. static/sw.js removes the worker of older builds, and
llama-server serves a self-removing service-worker.js as well as sw.js
when the built-in UI is off or replaced.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: use SvelteKit 3's update detection and Svelte 5's current patterns

A page the service worker doesn't control now learns of a new build
from SvelteKit itself: `updated` from $app/state checks
_app/version.json on navigation, on focus and every hour. It replaces
the version Llama Chat kept in localStorage and compared by hand.
Reload on the update prompt pulls in the new worker and activates it
before reloading, so one click lands on the new build, whether or not
a worker controlled the page.

Following Svelte's current guidance:
- usePwa keeps its state in $state rather than a store, and no effect
  checks `browser`
- nearViewport, autoResizeTextarea and the custom CSS injection are
  attachments ({@attach}) rather than actions (use:)
- class lists use arrays rather than class: directives
- the chat contexts come from createContext, typed, in place of
  setContext/getContext with string keys
- ActionIconCopyToClipboard takes $props() rather than `export let`

Assisted-by: Claude (Opus 5.5 Medium)

* ui: move to ESLint 10

ESLint 9 is out of support. Every plugin the app uses supports 10:
typescript-eslint, eslint-plugin-svelte, perfectionist,
simple-import-sort, eslint-plugin-storybook and eslint-config-prettier.
@eslint/js and @eslint/compat follow.

ESLint 10's recommended rules ask for two things the code now does:
errors rethrown from a catch keep the caught error as their `cause`,
and no variable starts with a value that every path overwrites.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: override minimatch to clear npm audit's last finding

ESLint 10.14, @eslint/config-array 0.23.5 and typescript-eslint 8.72
depend on minimatch 10, which GHSA-g3hv-75wg-m249 (denial of service
via globparts amplification) affects below 11.0.1. Their fixed releases
move to minimatch 11 but are all younger than the repo's 7-day
min-release-age, so an override pins minimatch 11.0.5, the newest the
rule allows. The three only call new Minimatch(), match() and
minimatch(), which minimatch 11 keeps. npm audit now finds nothing.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-17 11:43:36 +01:00

216 lines
6.7 KiB
TypeScript

/**
* ToolsService - Stateless server tools API layer
*
* Fetches the server's /tools listing and streams tool execution results.
* No reactive state; consumed by toolsStore.
*/
import { API_TOOLS, HEADERS, HOME_TILDE, SEARCH } from '#lib/constants/index.ts';
import { BuiltInTool, GlobSearchType, ToolResponseField } from '#lib/enums/index.ts';
import type { GlobEntry, ServerToolInfo, ToolExecutionResult } from '#lib/types/index.ts';
import { getJsonHeaders } from '#lib/utils/api-headers.ts';
import { withBase } from '#lib/utils/base-path.ts';
import { apiFetch, buildCaseInsensitiveGlob, joinPath, lastPathSegment } from '#lib/utils/index.ts';
import { parseSseJsonStream, type SseJsonEvent } from '#lib/utils/sse.ts';
export class ToolsService {
/**
* Execute a server tool on the server.
*
* @param cwd - Working directory for the tool call, sent as the
* x-tool-cwd request header. The server resolves relative paths
* against it; the model cannot override it.
*/
static async executeTool(
toolName: string,
params: Record<string, unknown>,
signal?: AbortSignal,
cwd?: string
): Promise<ToolExecutionResult> {
const result = await apiFetch<Record<string, unknown>>(API_TOOLS.EXECUTE, {
body: JSON.stringify({ params, tool: toolName }),
headers: cwd ? { [HEADERS.X_TOOL_CWD_HEADER]: cwd } : undefined,
method: 'POST',
signal
});
if (ToolResponseField.ERROR in result) {
return { content: String(result[ToolResponseField.ERROR]), isError: true };
}
if (ToolResponseField.PLAIN_TEXT in result) {
return { content: String(result[ToolResponseField.PLAIN_TEXT]), isError: false };
}
return { content: JSON.stringify(result), isError: false };
}
/**
* Execute a server tool and return the raw JSON response. Unlike
* executeTool, this preserves structured fields (e.g. file_glob_search's
* `entries` and `base`) that the flattened ToolExecutionResult drops.
*
* @param respType - sent as the x-resp-type request header. Only read_file
* honors it, with `base64` to get the raw bytes instead of decoded text.
*/
static async executeToolRaw(
toolName: string,
params: Record<string, unknown>,
signal?: AbortSignal,
cwd?: string,
respType?: string
): Promise<Record<string, unknown>> {
const headers: Record<string, string> = {};
if (cwd) headers[HEADERS.X_TOOL_CWD_HEADER] = cwd;
if (respType) headers[HEADERS.X_RESP_TYPE_HEADER] = respType;
return apiFetch<Record<string, unknown>>(API_TOOLS.EXECUTE, {
body: JSON.stringify({ params, tool: toolName }),
headers: Object.keys(headers).length > 0 ? headers : undefined,
method: 'POST',
signal
});
}
/**
* Fetch the list of server tools from the server.
*
* @returns Array of tool definitions in OpenAI-compatible format
*/
static async list(): Promise<ServerToolInfo[]> {
return apiFetch<ServerToolInfo[]>(API_TOOLS.LIST);
}
/**
* Resolve a folder name picked in the browser (a native directory picker
* exposes only the leaf name) to a server-side absolute path. Returns null
* when the server cannot find it.
*/
static async resolveDirectoryPath(
name: string,
homeBase: string | null = null
): Promise<string | null> {
try {
const res = await ToolsService.executeToolRaw(BuiltInTool.SERVER_FILE_GLOB_SEARCH, {
include: buildCaseInsensitiveGlob(name),
limit: SEARCH.NATIVE_LIMIT,
max_depth: SEARCH.NATIVE_MAX_DEPTH,
path: homeBase ?? HOME_TILDE,
type: GlobSearchType.DIR
});
const base = typeof res.base === 'string' ? res.base : '';
const entries = Array.isArray(res.entries) ? (res.entries as GlobEntry[]) : [];
const match = entries.find(
(entry) => lastPathSegment(entry.path).toLowerCase() === name.toLowerCase()
);
return match ? joinPath(base, match.path) : null;
} catch {
return null;
}
}
/**
* Stream a server tool's output chunks from the server. The server
* `POST /tools` endpoint with `{stream: true}` emits `data: {"chunk": "..."}`
* events followed by a terminal `data: {"done": true}` (optionally with
* `error`). Yields the chunk string for each partial event.
*
* The terminal event's `error` field, if present, is yielded as a final
* synthetic chunk prefixed with an error marker so the accumulated content
* already carries the failure context for the caller.
*
* Throws synchronously if the server rejects the request (e.g. tool does
* not support streaming, or 4xx/5xx response). The HTTP fetch goes through
* a minimal text/event-stream reader since the chat SSE parser in
* chat.service.ts embeds extra resume logic that is unnecessary here.
*/
static async *streamTool(
toolName: string,
params: Record<string, unknown>,
signal?: AbortSignal,
cwd?: string
): AsyncGenerator<ToolStreamEvent> {
const headers = getJsonHeaders();
if (cwd) headers[HEADERS.X_TOOL_CWD_HEADER] = cwd;
const response = await fetch(withBase(API_TOOLS.EXECUTE), {
body: JSON.stringify({ params, stream: true, tool: toolName }),
headers,
method: 'POST',
signal
});
if (!response.ok || !response.body) {
const detail = await formatNonOkResponse(response);
throw new Error(detail);
}
const iterator = parseSseJsonStream<ToolServerEvent>(response, signal);
while (true) {
const next: IteratorResult<SseJsonEvent<ToolServerEvent>> = await iterator.next();
if (next.done) return;
const event = next.value.data;
if (event.chunk !== undefined) {
yield { chunk: event.chunk, done: false };
}
if (event.done) {
yield { chunk: null, done: true, error: event.error };
return;
}
}
}
}
/**
* One event from streaming a tool's output.
* - During execution: `chunk` is a non-empty text fragment, `done: false`.
* - On terminal event: `done: true`, `error` populated if the call failed,
* and `chunk` is null.
*/
export interface ToolStreamEvent {
chunk: string | null;
done: boolean;
error?: string;
}
/** Wire shape of one SSE event from `POST /tools?stream=true`. */
interface ToolServerEvent {
chunk?: string;
done?: boolean;
error?: string;
}
async function formatNonOkResponse(response: Response): Promise<string> {
const status = `${response.status} ${response.statusText}`.trim();
try {
const errBody = (await response.clone().json()) as { error?: string; message?: string };
if (errBody?.error) return `${status}: ${errBody.error}`;
if (errBody?.message) return `${status}: ${errBody.message}`;
} catch (error) {
console.error('[tools] Non-JSON error response, falling back to raw text:', error);
try {
const text = await response.text();
if (text.trim()) return `${status}: ${text.trim()}`;
} catch (error) {
console.error('[tools] Failed to read error response as text:', error);
}
}
return status || `HTTP ${response.status}`;
}