50 Commits

Author SHA1 Message Date
Sybil Codex
9572d0320f ios: add pull to refresh 2026-05-03 19:27:06 +00:00
bca408c971 ios: specify product name 2026-05-03 00:17:08 -07:00
2f265fd847 ios: mac catalyst kb shortcuts 2026-05-02 23:50:51 -07:00
29e340fd08 quick question feature 2026-05-02 23:48:01 -07:00
6fbcaecbf8 sidebar: move settings 2026-05-02 23:20:32 -07:00
519ebd15dd ios: mac catalyst target 2026-05-02 23:18:00 -07:00
8051dd2c71 web: nicer tables 2026-05-02 23:17:52 -07:00
2313e560e8 fix streaming 2026-05-02 23:09:39 -07:00
94565298d8 better new chat animation 2026-05-02 22:51:59 -07:00
7360604136 ios: swipe to create new conversation 2026-05-02 22:46:25 -07:00
ca6b5e0807 web: keyboard shortcuts 2026-05-02 22:45:15 -07:00
4b0cc3fbf7 ios: better fix for scroll 2026-05-02 22:25:24 -07:00
2da73f802c ios: scroll without animation when clicking 2026-05-02 22:21:18 -07:00
4ad36d9bf6 ios: better backgrounding/resume 2026-05-02 22:18:45 -07:00
cf9832ca3b tool call in-flight resume 2026-05-02 22:03:43 -07:00
2c32ca66e2 codex no sandbox (its already sandboxed) 2026-05-02 21:50:17 -07:00
015253c0af oai responses api, tool call retries 2026-05-02 21:44:32 -07:00
8d6c069a33 Various fixes for tool calling 2026-05-02 21:19:52 -07:00
d579b5bf75 adds shell tool 2026-05-02 19:52:19 -07:00
01ee807991 ios: adds file uploading 2026-05-02 19:47:47 -07:00
fd9ee455fb experimental devbox support 2026-05-02 19:38:15 -07:00
38da3cea72 adds attachment support 2026-05-02 19:21:06 -07:00
11e6875de9 ios: proj bump 2026-05-02 18:26:20 -07:00
5a690b276f web: transcript improvements 2026-05-02 18:25:20 -07:00
d7967eaa75 Adds searxng support for tool calling 2026-05-02 18:15:14 -07:00
2125c5dfa4 web: tweak scrolling behavior 2026-05-02 18:15:14 -07:00
815655a73c ios: fix api endpoint change 2026-05-02 18:09:22 -07:00
b85409d977 ios: xcode proj changes 2026-05-02 17:40:41 -07:00
d9f27213e7 Merge pull request 'Add chat flow for search results' (#8) from codex/chat-with-search-results into master
Reviewed-on: #8
2026-05-03 00:23:30 +00:00
3a6c40cb3c Merge pull request 'ios: right-align user bubbles on iPad' (#7) from codex/ios-right-align-user-bubbles into master
Reviewed-on: #7
2026-05-03 00:20:22 +00:00
188c460826 ios: use editor toolbar title 2026-05-02 17:19:34 -07:00
90278020f5 ios: pin Sybil navigation theme 2026-05-02 17:10:32 -07:00
cafe4bb9ae ios: unify iPad chat toolbar 2026-05-02 17:03:02 -07:00
57a6287b2b Merge pull request 'ios: stop refocusing composer after send' (#5) from codex/ios-no-autofocus-after-send into master
Reviewed-on: #5
2026-05-02 23:53:32 +00:00
dc9336acf9 add chat flow for search results 2026-05-02 16:48:01 -07:00
ba6fc9c660 ios: right-align user bubbles on iPad 2026-05-02 16:40:50 -07:00
fa429dcbb3 Tiltfile: read .env 2026-05-02 16:39:31 -07:00
85f8d6b5f3 ios: stop refocusing composer after send 2026-05-02 16:37:55 -07:00
05989e9fae ios: line spacing 2026-05-02 16:32:32 -07:00
70b831557f web: move indicator to left column 2026-05-02 16:23:08 -07:00
cb368a4005 ios: update style 2026-05-02 16:23:00 -07:00
adb9e15b6c new look 2026-05-02 15:44:31 -07:00
dacab2f6ee ios: prepare for testflight 2026-05-02 15:21:08 -07:00
a31c053298 Adds ability to manually enter model name 2026-04-01 18:13:04 -07:00
be6641de24 pgup/pgdown in transcript 2026-03-11 01:23:13 -07:00
72b3a0902a Fix de-dup of user messages 2026-03-10 17:40:22 -07:00
49e30296b9 add TUI 2026-03-02 20:33:41 -08:00
e3253d1741 Enable streaming for tool call logs 2026-03-02 16:39:05 -08:00
991316e692 untested: iOS change for tool call logging 2026-03-02 16:18:10 -08:00
d5b06ce22a [feature] adds web_search and fetch_url tool calls 2026-03-02 16:13:34 -08:00
68 changed files with 10861 additions and 744 deletions

View File

@@ -24,6 +24,10 @@ COPY server/package.json server/package-lock.json ./
COPY server/scripts ./scripts
COPY server/prisma ./prisma
RUN apt-get update \
&& apt-get install -y --no-install-recommends openssh-client \
&& rm -rf /var/lib/apt/lists/*
RUN npm ci --omit=dev --no-audit --no-fund
COPY --from=server-build /app/server/dist ./dist

View File

@@ -1,5 +1,8 @@
update_settings(max_parallel_updates=4)
load('ext://dotenv', 'dotenv')
dotenv() # defaults to .env in the current directory
local_resource(
"server",
cmd="npm ci --no-audit --no-fund",

1
dist/default.conf vendored
View File

@@ -1,6 +1,7 @@
server {
listen 80;
server_name _;
client_max_body_size 32m;
root /usr/share/nginx/html;
index index.html;

View File

@@ -13,8 +13,24 @@ services:
ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}
XAI_API_KEY: ${XAI_API_KEY:-}
EXA_API_KEY: ${EXA_API_KEY:-}
CHAT_WEB_SEARCH_ENGINE: ${CHAT_WEB_SEARCH_ENGINE:-exa}
SEARXNG_BASE_URL: ${SEARXNG_BASE_URL:-}
CHAT_MAX_TOOL_ROUNDS: ${CHAT_MAX_TOOL_ROUNDS:-100}
CHAT_CODEX_TOOL_ENABLED: ${CHAT_CODEX_TOOL_ENABLED:-false}
CHAT_CODEX_REMOTE_HOST: ${CHAT_CODEX_REMOTE_HOST:-}
CHAT_CODEX_REMOTE_USER: ${CHAT_CODEX_REMOTE_USER:-}
CHAT_CODEX_REMOTE_PORT: ${CHAT_CODEX_REMOTE_PORT:-22}
CHAT_CODEX_REMOTE_WORKDIR: ${CHAT_CODEX_REMOTE_WORKDIR:-/workspace/sybil-codex}
# Prefer mounting a private key read-only and pointing CHAT_CODEX_SSH_KEY_PATH at it.
CHAT_CODEX_SSH_KEY_PATH: ${CHAT_CODEX_SSH_KEY_PATH:-}
CHAT_CODEX_SSH_PRIVATE_KEY_B64: ${CHAT_CODEX_SSH_PRIVATE_KEY_B64:-}
CHAT_CODEX_EXEC_TIMEOUT_MS: ${CHAT_CODEX_EXEC_TIMEOUT_MS:-600000}
CHAT_SHELL_TOOL_ENABLED: ${CHAT_SHELL_TOOL_ENABLED:-false}
CHAT_SHELL_EXEC_TIMEOUT_MS: ${CHAT_SHELL_EXEC_TIMEOUT_MS:-120000}
volumes:
- sybil_data:/data
# Example key mount for codex_exec:
# - ./secrets/devbox_id_ed25519:/run/secrets/codex_ssh_key:ro
expose:
- "8787"
restart: unless-stopped

View File

@@ -10,6 +10,12 @@ Content type:
- Requests with bodies use `application/json`.
- Responses are JSON unless noted otherwise.
Chat upload limits:
- Chat completion and direct message payloads support inline attachments up to a 32 MB request body.
- Up to 8 attachments per message.
- Image attachments: PNG or JPEG only, max 6 MB each.
- Text attachments: up to 8 MB source size each; server accepts at most 200,000 characters of inlined text content per attachment.
## Health + Auth
### `GET /health`
@@ -31,6 +37,7 @@ Content type:
}
}
```
- OpenAI model lists are filtered to models that are expected to work with the backend's Responses API implementation.
## Chats
@@ -38,9 +45,29 @@ Content type:
- Response: `{ "chats": ChatSummary[] }`
### `POST /v1/chats`
- Body: `{ "title"?: string }`
- Body:
```json
{
"title": "optional title",
"provider": "optional openai|anthropic|xai",
"model": "optional model id",
"messages": [
{
"role": "system|user|assistant|tool",
"content": "string",
"name": "optional",
"attachments": []
}
]
}
```
- Response: `{ "chat": ChatSummary }`
Behavior notes:
- `provider` and `model` must be supplied together when present.
- When `provider`/`model` are supplied, the new chat initializes `initiatedProvider`/`initiatedModel` and `lastUsedProvider`/`lastUsedModel`.
- Optional `messages` are inserted as the initial transcript. Attachment metadata uses the same schema and limits as chat completion messages.
### `PATCH /v1/chats/:chatId`
- Body: `{ "title": string }`
- Response: `{ "chat": ChatSummary }`
@@ -74,11 +101,34 @@ Behavior notes:
"role": "system|user|assistant|tool",
"content": "string",
"name": "optional",
"metadata": {}
"metadata": {},
"attachments": [
{
"kind": "image",
"id": "attachment-id",
"filename": "photo.jpg",
"mimeType": "image/jpeg",
"sizeBytes": 12345,
"dataUrl": "data:image/jpeg;base64,..."
},
{
"kind": "text",
"id": "attachment-id",
"filename": "notes.md",
"mimeType": "text/markdown",
"sizeBytes": 4567,
"text": "# Notes\\n...",
"truncated": false
}
]
}
```
- Response: `{ "message": Message }`
Notes:
- `attachments` is optional and is merged into stored `message.metadata.attachments`.
- Tool messages should not include attachments.
## Chat Completions (non-streaming)
### `POST /v1/chat-completions`
@@ -89,7 +139,30 @@ Behavior notes:
"provider": "openai|anthropic|xai",
"model": "string",
"messages": [
{ "role": "system|user|assistant|tool", "content": "string", "name": "optional" }
{
"role": "system|user|assistant|tool",
"content": "string",
"name": "optional",
"attachments": [
{
"kind": "image",
"id": "attachment-id",
"filename": "photo.jpg",
"mimeType": "image/jpeg",
"sizeBytes": 12345,
"dataUrl": "data:image/jpeg;base64,..."
},
{
"kind": "text",
"id": "attachment-id",
"filename": "notes.md",
"mimeType": "text/markdown",
"sizeBytes": 4567,
"text": "# Notes\\n...",
"truncated": false
}
]
}
],
"temperature": 0.2,
"maxTokens": 256
@@ -112,6 +185,34 @@ Behavior notes:
- For `chatId` calls, server stores only *new* non-assistant messages from provided history to avoid duplicates.
- Server persists final assistant output and call metadata (`LlmCall`) in DB.
- Server updates chat-level model metadata on each call: `lastUsedProvider`/`lastUsedModel`; first successful/failed call also initializes `initiatedProvider`/`initiatedModel` if unset.
- Attachments are optional and currently apply to `user` messages. Persisted chat history stores them under `message.metadata.attachments`.
- Images are forwarded inline to providers as multimodal image parts. Use PNG or JPEG for cross-provider compatibility.
- Text files are forwarded as explicit text blocks rather than provider-managed file references. Large text attachments should already be truncated client-side before submission.
- For `openai`, backend calls OpenAI's Responses API and enables internal tool use with an internal system instruction.
- For `xai`, backend calls xAI's OpenAI-compatible Chat Completions API and enables internal tool use with the same internal system instruction.
- For `openai`, image attachments are sent as Responses `input_image` items and text attachments are sent as `input_text` items.
- For `xai`, image attachments are sent as Chat Completions content parts alongside text.
- For `openai`, Responses calls that can enter the server-managed tool loop use `store: true` so reasoning and function-call items can be passed between tool rounds.
- For `anthropic`, image attachments are sent as Messages API `image` blocks using base64 source data; text attachments are added as `text` blocks.
- Available tool calls for chat: `web_search` and `fetch_url`. When `CHAT_CODEX_TOOL_ENABLED=true`, `codex_exec` is also available. When `CHAT_SHELL_TOOL_ENABLED=true`, `shell_exec` is also available.
- `web_search` returns ranked results with per-result summaries/snippets. Its backend engine is selected by `CHAT_WEB_SEARCH_ENGINE` (`exa` default, or `searxng` with `SEARXNG_BASE_URL` set). SearXNG mode requires the instance to allow `format=json`.
- `fetch_url` fetches a URL and returns plaintext page content (HTML converted to text server-side).
- `codex_exec` delegates coding, shell, repository inspection, and other complex software tasks to a persistent remote Codex CLI workspace over SSH. The server runs `codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check <non-interactive wrapped prompt>` on the configured devbox inside `CHAT_CODEX_REMOTE_WORKDIR`, with SSH stdin closed.
- `shell_exec` runs arbitrary non-interactive shell commands on the same configured devbox, starting in `CHAT_CODEX_REMOTE_WORKDIR`. It uses `bash -lc` when bash exists, otherwise `sh -lc`, closes SSH stdin, and does not run inside the Sybil server container.
- Devbox tool configuration:
- `CHAT_MAX_TOOL_ROUNDS=100` (optional; maximum model/tool result cycles before the backend returns a limit message)
- `CHAT_CODEX_TOOL_ENABLED=true`
- `CHAT_SHELL_TOOL_ENABLED=true`
- `CHAT_CODEX_REMOTE_HOST=<host-or-ip>` (required when enabled)
- `CHAT_CODEX_REMOTE_USER=<ssh-user>` (optional; omitted if `CHAT_CODEX_REMOTE_HOST` already contains `user@host`)
- `CHAT_CODEX_REMOTE_PORT=22` (optional)
- `CHAT_CODEX_REMOTE_WORKDIR=/workspace/sybil-codex` (optional; created on the remote host if missing)
- `CHAT_CODEX_SSH_KEY_PATH=/run/secrets/codex_ssh_key` (recommended private-key delivery via read-only volume mount)
- `CHAT_CODEX_SSH_PRIVATE_KEY_B64=<base64-private-key>` (optional fallback when a volume mount is not practical)
- `CHAT_CODEX_EXEC_TIMEOUT_MS=600000` (optional)
- `CHAT_SHELL_EXEC_TIMEOUT_MS=120000` (optional)
- When a tool call is executed, backend stores a chat `Message` with `role: "tool"` and tool metadata (`metadata.kind = "tool_call"`). Streaming requests persist each completed tool call as its SSE `tool_call` event is emitted, then store the assistant output when the completion finishes.
- `anthropic` currently runs without server-managed tool calls.
## Searches
@@ -129,6 +230,16 @@ Behavior notes:
### `GET /v1/searches/:searchId`
- Response: `{ "search": SearchDetail }`
### `POST /v1/searches/:searchId/chat`
- Body: `{ "title"?: string }`
- Response: `{ "chat": ChatSummary }`
- Not found: `404 { "message": "search not found" }`
Behavior notes:
- Creates a new chat seeded with a hidden `system` message containing the search query, answer text, answer citations, and top search results.
- Clients should include existing `system` messages when sending the chat history to `/v1/chat-completions` or `/v1/chat-completions/stream`; they may hide those messages in the transcript UI.
- The default chat title is `Search: <query-or-title>`, unless `title` is supplied.
### `POST /v1/searches/:searchId/run`
- Body:
```json
@@ -145,6 +256,7 @@ Behavior notes:
Search run notes:
- Backend executes Exa search and Exa answer.
- Search mode is independent from chat `web_search` tool configuration and remains Exa-only.
- Persists answer text/citations + ranked results.
- If both search and answer fail, endpoint returns an error.
@@ -171,10 +283,33 @@ Search run notes:
"createdAt": "...",
"role": "system|user|assistant|tool",
"content": "...",
"name": null
"name": null,
"metadata": {
"attachments": [
{
"kind": "image",
"id": "attachment-id",
"filename": "photo.jpg",
"mimeType": "image/jpeg",
"sizeBytes": 12345,
"dataUrl": "data:image/jpeg;base64,..."
},
{
"kind": "text",
"id": "attachment-id",
"filename": "notes.md",
"mimeType": "text/markdown",
"sizeBytes": 4567,
"text": "# Notes\\n...",
"truncated": false
}
]
}
}
```
`metadata` remains nullable. Tool-call log messages still use `metadata.kind = "tool_call"`; regular user messages with attachments use `metadata.attachments`.
`ChatDetail`
```json
{

View File

@@ -9,6 +9,7 @@ Transport:
- HTTP response uses `Content-Type: text/event-stream; charset=utf-8`
- Events are emitted in SSE format (`event: ...`, `data: ...`)
- Request body is JSON
- Request body supports the same inline attachment schema and limits documented in `docs/api/rest.md`.
Authentication:
- Same as REST endpoints (`Authorization: Bearer <token>` when token mode is enabled)
@@ -18,10 +19,34 @@ Authentication:
```json
{
"chatId": "optional-chat-id",
"persist": true,
"provider": "openai|anthropic|xai",
"model": "string",
"messages": [
{ "role": "system|user|assistant|tool", "content": "string", "name": "optional" }
{
"role": "system|user|assistant|tool",
"content": "string",
"name": "optional",
"attachments": [
{
"kind": "image",
"id": "attachment-id",
"filename": "photo.jpg",
"mimeType": "image/jpeg",
"sizeBytes": 12345,
"dataUrl": "data:image/jpeg;base64,..."
},
{
"kind": "text",
"id": "attachment-id",
"filename": "notes.md",
"mimeType": "text/markdown",
"sizeBytes": 4567,
"text": "# Notes\\n...",
"truncated": false
}
]
}
],
"temperature": 0.2,
"maxTokens": 256
@@ -29,29 +54,35 @@ Authentication:
```
Notes:
- If `chatId` is omitted, backend creates a new chat.
- `persist` defaults to `true`.
- If `persist` is `true` and `chatId` is omitted, backend creates a new chat.
- If `chatId` is provided, backend validates it exists.
- Backend stores only new non-assistant input history rows to avoid duplicates.
- If `persist` is `false`, `chatId` must be omitted. Backend does not create a chat and does not persist input messages, tool-call messages, assistant output, or `LlmCall` metadata.
- For persisted streams, backend stores only new non-assistant input history rows to avoid duplicates.
- Attachments are optional and are persisted under `message.metadata.attachments` on stored user messages when `persist` is `true`.
## Event Stream Contract
Event order:
1. Exactly one `meta`
2. Zero or more `delta`
3. Exactly one terminal event: `done` or `error`
2. Zero or more `tool_call`
3. Zero or more `delta`
4. Exactly one terminal event: `done` or `error`
### `meta`
```json
{
"type": "meta",
"chatId": "chat-id",
"callId": "llm-call-id",
"chatId": "chat-id-or-null",
"callId": "llm-call-id-or-null",
"provider": "openai",
"model": "gpt-4.1-mini"
}
```
For `persist: false` streams, `chatId` and `callId` are `null`.
### `delta`
```json
@@ -60,6 +91,23 @@ Event order:
`text` may contain partial words, punctuation, or whitespace.
### `tool_call`
```json
{
"toolCallId": "call_123",
"name": "web_search",
"status": "completed",
"summary": "Performed web search for 'latest CPI release'.",
"args": { "query": "latest CPI release" },
"startedAt": "2026-03-02T10:00:00.000Z",
"completedAt": "2026-03-02T10:00:00.820Z",
"durationMs": 820,
"error": null,
"resultPreview": "{\"ok\":true,...}"
}
```
### `done`
```json
@@ -84,24 +132,43 @@ Event order:
## Provider Streaming Behavior
- `openai`: streamed via OpenAI chat completion chunks; emits `delta` from `choices[0].delta.content`.
- `xai`: uses OpenAI-compatible API, same chunk extraction as OpenAI.
- `anthropic`: streamed via event stream; emits `delta` from `content_block_delta` with `text_delta`.
- `openai`: backend uses OpenAI's Responses API and may execute internal function tool calls (`web_search`, `fetch_url`, optional `codex_exec`, and optional `shell_exec`) before producing final text.
- `xai`: backend uses xAI's OpenAI-compatible Chat Completions API and may execute the same internal tool calls before producing final text.
- `openai`: image attachments are sent as Responses `input_image` items; text attachments are sent as `input_text` items.
- `xai`: image attachments are sent as Chat Completions content parts; text attachments are inlined as text parts.
- `openai`: Responses calls that can enter the server-managed tool loop use `store: true` so reasoning and function-call items can be passed between tool rounds.
- `anthropic`: streamed via event stream; emits `delta` from `content_block_delta` with `text_delta`. Image attachments are sent as base64 `image` blocks and text attachments are appended as `text` blocks.
- `web_search` uses `CHAT_WEB_SEARCH_ENGINE` (`exa` default, or `searxng` with `SEARXNG_BASE_URL` set). SearXNG mode requires the instance to allow `format=json`. This only affects chat-mode tool calls, not search-mode endpoints.
- `codex_exec` is available only when `CHAT_CODEX_TOOL_ENABLED=true`. It SSHes to `CHAT_CODEX_REMOTE_HOST`, creates/uses `CHAT_CODEX_REMOTE_WORKDIR`, and runs `codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check <non-interactive wrapped prompt>` there with SSH stdin closed. Prefer `CHAT_CODEX_SSH_KEY_PATH` with a read-only mounted private key; `CHAT_CODEX_SSH_PRIVATE_KEY_B64` is also supported.
- `shell_exec` is available only when `CHAT_SHELL_TOOL_ENABLED=true`. It uses the same devbox SSH configuration, starts in `CHAT_CODEX_REMOTE_WORKDIR`, and runs non-interactive shell commands there with SSH stdin closed, not inside the Sybil server container.
- `CHAT_MAX_TOOL_ROUNDS` controls how many model/tool result cycles may occur before the backend returns a tool-call limit message; default is 100.
Tool-enabled streaming notes (`openai`/`xai`):
- Stream still emits standard `meta`, `delta`, `done|error` events.
- Stream may emit `tool_call` events while tool calls are executed.
- `delta` events carry assistant text and are emitted incrementally for normal text rounds. The backend may buffer model-native text briefly while determining whether a provider round contains tool calls.
- OpenAI Responses stream events are normalized by the backend into this SSE contract; clients do not consume OpenAI's raw Responses stream event names.
## Persistence + Consistency Model
Backend database remains source of truth.
During stream:
For persisted streams:
- Client may optimistically render accumulated `delta` text.
- Backend persists each completed tool call as a `tool` message before emitting its `tool_call` SSE event, so chat detail refreshes can show completed tool calls while the assistant response is still running.
On successful completion:
On successful persisted completion:
- Backend persists assistant `Message` and updates `LlmCall` usage/latency in a transaction.
- Backend then emits `done`.
On failure:
On persisted failure:
- Backend records call error and emits `error`.
For `persist: false` streams:
- Client may render the same `meta`, `tool_call`, `delta`, and terminal events.
- Backend does not write any chat, message, tool-call log, assistant output, or call metadata rows.
- `done.text` is the canonical assistant text if the client later imports the result into a saved chat.
Client recommendation (for iOS/web):
1. Render deltas in real time for UX.
2. On `done`, refresh chat detail from REST (`GET /v1/chats/:chatId`) and use DB-backed data as canonical.

View File

@@ -34,7 +34,8 @@ Instructions for work under `/Users/buzzert/src/sybil-2/ios`.
- If backend contract changes (request/response shapes, SSE events, auth semantics), update docs in the same change.
## Practical Notes
- Default API URL is `http://127.0.0.1:8787/api` (configurable in-app).
- Default API URL is `http://127.0.0.1:8787` (configurable in-app).
- The iOS client preserves an explicit `/api` base path for proxied deployments.
- Provider fallback models:
- OpenAI: `gpt-4.1-mini`
- Anthropic: `claude-3-5-sonnet-latest`

Binary file not shown.

Binary file not shown.

View File

@@ -9,5 +9,8 @@ struct SybilApp: App
WindowGroup {
SplitView()
}
.commands {
SybilCommands()
}
}
}

View File

@@ -1,7 +1,9 @@
targets:
SybilApp:
type: application
platform: iOS
supportedDestinations:
- iOS
- macCatalyst
deploymentTarget: "18.0"
sources:
- Sources
@@ -11,17 +13,20 @@ targets:
product: Sybil
settings:
base:
PRODUCT_BUNDLE_IDENTIFIER: com.sybil.app
PRODUCT_BUNDLE_IDENTIFIER: net.buzzert.sybil2
PRODUCT_NAME: Sybil
PRODUCT_MODULE_NAME: SybilApp
DEVELOPMENT_TEAM: ""
DEVELOPMENT_TEAM: DQQH5H6GBD
CODE_SIGN_STYLE: Automatic
SWIFT_VERSION: 6.0
TARGETED_DEVICE_FAMILY: "1,2"
SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD: NO
TARGETED_DEVICE_FAMILY: "1,2,6"
GENERATE_INFOPLIST_FILE: YES
ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
MARKETING_VERSION: 1.0
CURRENT_PROJECT_VERSION: 1
MARKETING_VERSION: 1.4
CURRENT_PROJECT_VERSION: 5
INFOPLIST_KEY_CFBundleDisplayName: Sybil
INFOPLIST_KEY_ITSAppUsesNonExemptEncryption: NO
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents: YES
INFOPLIST_KEY_UILaunchScreen_Generation: YES
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone: UIInterfaceOrientationPortrait

View File

@@ -0,0 +1,33 @@
{
"originHash" : "a6321e2b291c1094ca66f749c90095f05aac7f8c6b4a6e54e0e77a1bb0e1a79f",
"pins" : [
{
"identity" : "networkimage",
"kind" : "remoteSourceControl",
"location" : "https://github.com/gonzalezreal/NetworkImage",
"state" : {
"revision" : "2849f5323265386e200484b0d0f896e73c3411b9",
"version" : "6.0.1"
}
},
{
"identity" : "swift-cmark",
"kind" : "remoteSourceControl",
"location" : "https://github.com/swiftlang/swift-cmark",
"state" : {
"revision" : "5d9bdaa4228b381639fff09403e39a04926e2dbe",
"version" : "0.7.1"
}
},
{
"identity" : "swift-markdown-ui",
"kind" : "remoteSourceControl",
"location" : "https://github.com/gonzalezreal/swift-markdown-ui.git",
"state" : {
"revision" : "5f613358148239d0292c0cef674a3c2314737f9e",
"version" : "2.4.1"
}
}
],
"version" : 3
}

View File

@@ -3,8 +3,37 @@ import SwiftUI
public struct SplitView: View {
@State private var viewModel = SybilViewModel()
@Environment(\.horizontalSizeClass) private var horizontalSizeClass
@Environment(\.scenePhase) private var scenePhase
@State private var shouldRefreshOnForeground = false
@State private var composerFocusRequest = 0
public init() {}
private var keyboardActions: SybilKeyboardActions? {
guard !viewModel.isCheckingSession, viewModel.isAuthenticated else {
return nil
}
return SybilKeyboardActions(
newChat: {
viewModel.startNewChat()
composerFocusRequest += 1
},
newSearch: {
viewModel.startNewSearch()
composerFocusRequest += 1
},
previousConversation: {
viewModel.selectPreviousSidebarItem()
},
nextConversation: {
viewModel.selectNextSidebarItem()
}
)
}
@MainActor public init() {
SybilFontRegistry.registerIfNeeded()
SybilTheme.applySystemAppearance()
}
public var body: some View {
ZStack {
@@ -23,16 +52,96 @@ public struct SplitView: View {
} else {
NavigationSplitView {
SybilSidebarView(viewModel: viewModel)
.navigationTitle("Sybil")
} detail: {
SybilWorkspaceView(viewModel: viewModel)
SybilWorkspaceView(viewModel: viewModel, composerFocusRequest: composerFocusRequest) {
viewModel.startNewChat()
composerFocusRequest += 1
}
}
.navigationSplitViewStyle(.balanced)
.tint(SybilTheme.primary)
}
}
.font(.sybil(.body))
.preferredColorScheme(.dark)
.focusedSceneValue(\.sybilKeyboardActions, keyboardActions)
.task {
await viewModel.bootstrap()
}
.onChange(of: scenePhase) { _, nextPhase in
switch nextPhase {
case .background:
shouldRefreshOnForeground = true
case .active:
guard shouldRefreshOnForeground, horizontalSizeClass != .compact else {
return
}
shouldRefreshOnForeground = false
Task {
await viewModel.refreshVisibleContent(
refreshCollections: true,
refreshSelection: viewModel.hasRefreshableSelection
)
}
case .inactive:
break
@unknown default:
break
}
}
}
}
public struct SybilCommands: Commands {
@FocusedValue(\.sybilKeyboardActions) private var keyboardActions
public init() {}
public var body: some Commands {
CommandGroup(replacing: .newItem) {
Button("New Chat") {
keyboardActions?.newChat()
}
.keyboardShortcut("n", modifiers: .command)
.disabled(keyboardActions == nil)
Button("New Search") {
keyboardActions?.newSearch()
}
.keyboardShortcut("n", modifiers: [.command, .shift])
.disabled(keyboardActions == nil)
}
CommandMenu("Conversation") {
Button("Previous Conversation") {
keyboardActions?.previousConversation()
}
.keyboardShortcut("[", modifiers: .command)
.disabled(keyboardActions == nil)
Button("Next Conversation") {
keyboardActions?.nextConversation()
}
.keyboardShortcut("]", modifiers: .command)
.disabled(keyboardActions == nil)
}
}
}
private struct SybilKeyboardActions {
var newChat: () -> Void
var newSearch: () -> Void
var previousConversation: () -> Void
var nextConversation: () -> Void
}
private struct SybilKeyboardActionsKey: FocusedValueKey {
typealias Value = SybilKeyboardActions
}
private extension FocusedValues {
var sybilKeyboardActions: SybilKeyboardActions? {
get { self[SybilKeyboardActionsKey.self] }
set { self[SybilKeyboardActionsKey.self] = newValue }
}
}

View File

@@ -17,16 +17,18 @@ struct AnyEncodable: Encodable {
}
}
actor SybilAPIClient {
actor SybilAPIClient: SybilAPIClienting {
private let configuration: APIConfiguration
private let session: URLSession
@MainActor
private static let iso8601FormatterWithFractional: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
return formatter
}()
@MainActor
private static let iso8601Formatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime]
@@ -96,6 +98,16 @@ actor SybilAPIClient {
return response.search
}
func createChatFromSearch(searchID: String, title: String? = nil) async throws -> ChatSummary {
let response = try await request(
"/v1/searches/\(searchID)/chat",
method: "POST",
body: AnyEncodable(SearchChatCreateBody(title: title)),
responseType: ChatCreateResponse.self
)
return response.chat
}
func deleteSearch(searchID: String) async throws {
_ = try await request("/v1/searches/\(searchID)", method: "DELETE", responseType: DeleteResponse.self)
}
@@ -125,6 +137,9 @@ actor SybilAPIClient {
case "meta":
let payload: CompletionStreamMeta = try Self.decodeEvent(dataText, as: CompletionStreamMeta.self, eventName: eventName)
await onEvent(.meta(payload))
case "tool_call":
let payload: CompletionStreamToolCall = try Self.decodeEvent(dataText, as: CompletionStreamToolCall.self, eventName: eventName)
await onEvent(.toolCall(payload))
case "delta":
let payload: CompletionStreamDelta = try Self.decodeEvent(dataText, as: CompletionStreamDelta.self, eventName: eventName)
await onEvent(.delta(payload))
@@ -549,3 +564,7 @@ private struct SearchCreateBody: Encodable {
var title: String?
var query: String?
}
private struct SearchChatCreateBody: Encodable {
var title: String?
}

View File

@@ -0,0 +1,25 @@
import Foundation
protocol SybilAPIClienting: Sendable {
func verifySession() async throws -> AuthSession
func listChats() async throws -> [ChatSummary]
func createChat(title: String?) async throws -> ChatSummary
func getChat(chatID: String) async throws -> ChatDetail
func deleteChat(chatID: String) async throws
func suggestChatTitle(chatID: String, content: String) async throws -> ChatSummary
func listSearches() async throws -> [SearchSummary]
func createSearch(title: String?, query: String?) async throws -> SearchSummary
func getSearch(searchID: String) async throws -> SearchDetail
func createChatFromSearch(searchID: String, title: String?) async throws -> ChatSummary
func deleteSearch(searchID: String) async throws
func listModels() async throws -> ModelCatalogResponse
func runCompletionStream(
body: CompletionStreamRequest,
onEvent: @escaping @Sendable (CompletionStreamEvent) async -> Void
) async throws
func runSearchStream(
searchID: String,
body: SearchRunRequest,
onEvent: @escaping @Sendable (SearchStreamEvent) async -> Void
) async throws
}

View File

@@ -0,0 +1,222 @@
import SwiftUI
enum SybilAttachmentTone {
case composer
case user
case assistant
}
struct SybilAttachmentListView: View {
var attachments: [ChatAttachment]
var tone: SybilAttachmentTone
var onRemove: ((String) -> Void)? = nil
var body: some View {
VStack(alignment: .leading, spacing: 8) {
ForEach(attachments) { attachment in
Group {
if attachment.kind == .image {
imageCard(attachment)
} else {
textCard(attachment)
}
}
}
}
}
@ViewBuilder
private func imageCard(_ attachment: ChatAttachment) -> some View {
VStack(alignment: .leading, spacing: 0) {
if let image = SybilChatAttachmentSupport.image(for: attachment) {
Image(uiImage: image)
.resizable()
.scaledToFill()
.frame(maxWidth: .infinity)
.frame(height: 180)
.clipped()
} else {
ZStack {
RoundedRectangle(cornerRadius: 14)
.fill(Color.black.opacity(0.18))
Image(systemName: "photo")
.font(.system(size: 22, weight: .medium))
.foregroundStyle(SybilTheme.textMuted)
}
.frame(height: 140)
}
HStack(alignment: .top, spacing: 10) {
Image(systemName: "photo")
.font(.system(size: 13, weight: .semibold))
.foregroundStyle(titleColor.opacity(0.92))
.frame(width: 26, height: 26)
.background(
RoundedRectangle(cornerRadius: 8)
.fill(Color.white.opacity(0.06))
.overlay(
RoundedRectangle(cornerRadius: 8)
.stroke(Color.white.opacity(0.08), lineWidth: 1)
)
)
VStack(alignment: .leading, spacing: 2) {
Text(attachment.filename)
.font(.sybil(.footnote, weight: .medium))
.foregroundStyle(titleColor)
.lineLimit(1)
Text(attachment.mimeType)
.font(.sybil(.caption2))
.foregroundStyle(SybilTheme.textMuted)
.lineLimit(1)
}
Spacer(minLength: 0)
if let onRemove {
removeButton(for: attachment.id, onRemove: onRemove)
}
}
.padding(12)
}
.background(cardBackground)
.clipShape(RoundedRectangle(cornerRadius: 14))
.overlay(
RoundedRectangle(cornerRadius: 14)
.stroke(cardBorder, lineWidth: 1)
)
}
@ViewBuilder
private func textCard(_ attachment: ChatAttachment) -> some View {
VStack(alignment: .leading, spacing: 10) {
HStack(alignment: .top, spacing: 10) {
Image(systemName: "doc.text")
.font(.system(size: 13, weight: .semibold))
.foregroundStyle(titleColor.opacity(0.92))
.frame(width: 26, height: 26)
.background(
RoundedRectangle(cornerRadius: 8)
.fill(Color.white.opacity(0.06))
.overlay(
RoundedRectangle(cornerRadius: 8)
.stroke(Color.white.opacity(0.08), lineWidth: 1)
)
)
VStack(alignment: .leading, spacing: 2) {
Text(attachment.filename)
.font(.sybil(.footnote, weight: .medium))
.foregroundStyle(titleColor)
.lineLimit(1)
Text(
attachment.truncated == true
? "\(attachment.mimeType) • truncated"
: attachment.mimeType
)
.font(.sybil(.caption2))
.foregroundStyle(SybilTheme.textMuted)
.lineLimit(1)
}
Spacer(minLength: 0)
if let onRemove {
removeButton(for: attachment.id, onRemove: onRemove)
}
}
Text(SybilChatAttachmentSupport.previewText(for: attachment))
.font(.system(.caption, design: .monospaced))
.foregroundStyle(bodyColor)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(10)
.background(
RoundedRectangle(cornerRadius: 10)
.fill(Color.black.opacity(0.16))
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.white.opacity(0.05), lineWidth: 1)
)
)
}
.padding(12)
.background(cardBackground)
.clipShape(RoundedRectangle(cornerRadius: 14))
.overlay(
RoundedRectangle(cornerRadius: 14)
.stroke(cardBorder, lineWidth: 1)
)
}
private func removeButton(for attachmentID: String, onRemove: @escaping (String) -> Void) -> some View {
Button {
onRemove(attachmentID)
} label: {
Image(systemName: "xmark")
.font(.system(size: 11, weight: .bold))
.foregroundStyle(SybilTheme.textMuted)
.frame(width: 24, height: 24)
.background(
Circle()
.fill(Color.white.opacity(0.06))
)
}
.buttonStyle(.plain)
.accessibilityLabel("Remove attachment")
}
private var cardBackground: some ShapeStyle {
switch tone {
case .composer:
return AnyShapeStyle(
LinearGradient(
colors: [SybilTheme.surface.opacity(0.86), SybilTheme.surfaceStrong.opacity(0.78)],
startPoint: .topLeading,
endPoint: .bottomTrailing
)
)
case .user:
return AnyShapeStyle(Color.black.opacity(0.14))
case .assistant:
return AnyShapeStyle(
LinearGradient(
colors: [SybilTheme.surface.opacity(0.58), SybilTheme.surfaceStrong.opacity(0.42)],
startPoint: .topLeading,
endPoint: .bottomTrailing
)
)
}
}
private var cardBorder: Color {
switch tone {
case .composer:
return SybilTheme.border.opacity(0.82)
case .user:
return Color.white.opacity(0.12)
case .assistant:
return SybilTheme.border.opacity(0.58)
}
}
private var titleColor: Color {
switch tone {
case .composer, .assistant:
return SybilTheme.text
case .user:
return SybilTheme.text
}
}
private var bodyColor: Color {
switch tone {
case .composer, .assistant:
return SybilTheme.text.opacity(0.94)
case .user:
return SybilTheme.text.opacity(0.96)
}
}
}

View File

@@ -0,0 +1,36 @@
import UIKit
@MainActor
final class SybilBackgroundTaskAssertion {
private let name: String
private var identifier: UIBackgroundTaskIdentifier = .invalid
init?(name: String, onExpiration: @escaping @MainActor () -> Void = {}) {
self.name = name
identifier = UIApplication.shared.beginBackgroundTask(withName: name) { [weak self] in
Task { @MainActor in
guard let self else { return }
SybilLog.warning(SybilLog.app, "Background task expired: \(self.name)")
onExpiration()
self.end()
}
}
guard identifier != .invalid else {
SybilLog.warning(SybilLog.app, "Failed to acquire background task: \(name)")
return nil
}
SybilLog.debug(SybilLog.app, "Acquired background task: \(name)")
}
func end() {
guard identifier != .invalid else {
return
}
UIApplication.shared.endBackgroundTask(identifier)
identifier = .invalid
SybilLog.debug(SybilLog.app, "Ended background task: \(name)")
}
}

View File

@@ -0,0 +1,354 @@
import Foundation
import UniformTypeIdentifiers
import UIKit
enum ChatAttachmentError: LocalizedError {
case unsupportedType(String)
case imageTooLarge(String)
case textTooLarge(String)
case unreadableFile(String)
case unsupportedImageFormat(String)
case tooManyAttachments(Int)
var errorDescription: String? {
switch self {
case let .unsupportedType(filename):
return "Unsupported file type for '\(filename)'. Use PNG/JPEG images or text-based files."
case let .imageTooLarge(filename):
return "Image '\(filename)' exceeds the 6 MB upload limit."
case let .textTooLarge(filename):
return "Text file '\(filename)' exceeds the 8 MB upload limit."
case let .unreadableFile(filename):
return "Could not read '\(filename)'."
case let .unsupportedImageFormat(filename):
return "Image '\(filename)' could not be converted to PNG or JPEG."
case let .tooManyAttachments(limit):
return "You can attach up to \(limit) files per message."
}
}
}
enum SybilChatAttachmentSupport {
static let maxAttachmentsPerMessage = 8
static let maxImageBytes = 6 * 1024 * 1024
static let maxTextBytes = 8 * 1024 * 1024
static let maxTextCharacters = 200_000
private static let supportedTextExtensions: Set<String> = [
"txt", "md", "markdown", "csv", "tsv", "json", "jsonl", "xml", "yaml", "yml", "html", "htm",
"css", "js", "jsx", "ts", "tsx", "py", "rb", "java", "c", "cc", "cpp", "h", "hpp", "go",
"rs", "sh", "sql", "log", "toml", "ini", "cfg", "conf", "swift", "kt", "m", "mm"
]
private static let supportedTextMimeTypes: Set<String> = [
"application/json",
"application/ld+json",
"application/sql",
"application/toml",
"application/x-httpd-php",
"application/x-javascript",
"application/x-sh",
"application/xml",
"application/yaml",
"application/x-yaml",
"image/svg+xml"
]
static func attachmentSummary(_ attachments: [ChatAttachment]) -> String {
guard !attachments.isEmpty else { return "" }
let names = attachments.map(\.filename).joined(separator: ", ")
return attachments.count == 1 ? names : "Attached: \(names)"
}
static func metadataValue(for attachments: [ChatAttachment]) -> JSONValue? {
guard !attachments.isEmpty else { return nil }
return .object([
"attachments": .array(attachments.map(\.jsonValue))
])
}
static func buildAttachments(from urls: [URL]) throws -> [ChatAttachment] {
try urls.map { try buildAttachment(fromFileURL: $0) }
}
static func buildImageAttachment(image: UIImage, filename: String = "pasted-image.jpg") throws -> ChatAttachment {
if let pngData = image.pngData(), pngData.count <= maxImageBytes {
return try buildImageAttachment(data: pngData, filename: filename, contentType: .png)
}
guard let jpegData = image.jpegData(compressionQuality: 0.92) else {
throw ChatAttachmentError.unsupportedImageFormat(filename)
}
return try buildImageAttachment(data: jpegData, filename: filename, contentType: .jpeg)
}
static func buildTextAttachment(text: String, filename: String = "pasted-text.txt", mimeType: String = "text/plain") throws -> ChatAttachment {
let data = Data(text.utf8)
return try buildTextAttachment(data: data, filename: filename, mimeType: mimeType)
}
@MainActor
static func buildAttachments(from itemProviders: [NSItemProvider]) async throws -> [ChatAttachment] {
var attachments: [ChatAttachment] = []
for provider in itemProviders {
if let fileURL = try await loadFileURL(from: provider) {
attachments.append(try buildAttachment(fromFileURL: fileURL))
continue
}
if provider.hasItemConformingToTypeIdentifier(UTType.image.identifier) {
if let attachment = try await loadImageAttachment(from: provider) {
attachments.append(attachment)
}
}
}
return attachments
}
static func previewText(for attachment: ChatAttachment) -> String {
let normalized = (attachment.text ?? "")
.replacingOccurrences(of: "\r", with: "")
.trimmingCharacters(in: .whitespacesAndNewlines)
if normalized.isEmpty {
return "(empty file)"
}
if normalized.count <= 280 {
return normalized
}
let endIndex = normalized.index(normalized.startIndex, offsetBy: 280)
return normalized[..<endIndex].trimmingCharacters(in: .whitespacesAndNewlines) + "..."
}
static func image(for attachment: ChatAttachment) -> UIImage? {
guard attachment.kind == .image,
let dataURL = attachment.dataUrl,
let data = decodeDataURL(dataURL)
else {
return nil
}
return UIImage(data: data)
}
private static func buildAttachment(fromFileURL url: URL) throws -> ChatAttachment {
let accessed = url.startAccessingSecurityScopedResource()
defer {
if accessed {
url.stopAccessingSecurityScopedResource()
}
}
let filename = url.lastPathComponent.isEmpty ? "attachment" : url.lastPathComponent
let resourceValues = try? url.resourceValues(forKeys: [.contentTypeKey])
let contentType = resourceValues?.contentType ?? UTType(filenameExtension: url.pathExtension)
let data: Data
do {
data = try Data(contentsOf: url)
} catch {
throw ChatAttachmentError.unreadableFile(filename)
}
if contentType?.conforms(to: .image) == true {
return try buildImageAttachment(data: data, filename: filename, contentType: contentType)
}
if isTextLike(contentType: contentType, mimeType: contentType?.preferredMIMEType, filename: filename) {
return try buildTextAttachment(data: data, filename: filename, mimeType: contentType?.preferredMIMEType ?? "text/plain")
}
throw ChatAttachmentError.unsupportedType(filename)
}
static func buildImageAttachment(data: Data, filename: String, contentType: UTType?) throws -> ChatAttachment {
var mimeType = contentType?.preferredMIMEType
var payload = data
if mimeType != "image/png" && mimeType != "image/jpeg" {
guard let image = UIImage(data: data) else {
throw ChatAttachmentError.unsupportedImageFormat(filename)
}
if let pngData = image.pngData(), pngData.count <= maxImageBytes {
payload = pngData
mimeType = "image/png"
} else if let jpegData = image.jpegData(compressionQuality: 0.92) {
payload = jpegData
mimeType = "image/jpeg"
} else {
throw ChatAttachmentError.unsupportedImageFormat(filename)
}
}
if payload.count > maxImageBytes {
throw ChatAttachmentError.imageTooLarge(filename)
}
let normalizedMimeType = (mimeType == "image/png") ? "image/png" : "image/jpeg"
let dataUrl = "data:\(normalizedMimeType);base64,\(payload.base64EncodedString())"
return .image(
filename: filename,
mimeType: normalizedMimeType,
sizeBytes: payload.count,
dataUrl: dataUrl
)
}
private static func buildTextAttachment(data: Data, filename: String, mimeType: String) throws -> ChatAttachment {
if data.count > maxTextBytes {
throw ChatAttachmentError.textTooLarge(filename)
}
let normalized = String(decoding: data, as: UTF8.self)
.replacingOccurrences(of: "\r\n", with: "\n")
.replacingOccurrences(of: "\u{0000}", with: "")
let truncated = normalized.count > maxTextCharacters
let trimmedText: String
if truncated {
let endIndex = normalized.index(normalized.startIndex, offsetBy: maxTextCharacters)
trimmedText = String(normalized[..<endIndex])
} else {
trimmedText = normalized
}
return .text(
filename: filename,
mimeType: mimeType,
sizeBytes: data.count,
text: trimmedText,
truncated: truncated
)
}
private static func isTextLike(contentType: UTType?, mimeType: String?, filename: String) -> Bool {
if let contentType {
if contentType.conforms(to: .text) || contentType.conforms(to: .plainText) || contentType.conforms(to: .sourceCode) {
return true
}
if contentType.conforms(to: .json) || contentType.conforms(to: .xml) {
return true
}
}
if let mimeType {
if mimeType.hasPrefix("text/") {
return true
}
if supportedTextMimeTypes.contains(mimeType.lowercased()) {
return true
}
}
let ext = URL(fileURLWithPath: filename).pathExtension.lowercased()
return supportedTextExtensions.contains(ext)
}
private static func decodeDataURL(_ value: String) -> Data? {
guard let separator = value.firstIndex(of: ",") else {
return nil
}
let encoded = value[value.index(after: separator)...]
return Data(base64Encoded: String(encoded))
}
@MainActor
private static func loadFileURL(from provider: NSItemProvider) async throws -> URL? {
guard provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) else {
return nil
}
return try await withCheckedThrowingContinuation { continuation in
provider.loadItem(forTypeIdentifier: UTType.fileURL.identifier, options: nil) { item, error in
if let error {
continuation.resume(throwing: error)
return
}
if let url = item as? URL {
continuation.resume(returning: url)
return
}
if let data = item as? Data,
let url = URL(dataRepresentation: data, relativeTo: nil) {
continuation.resume(returning: url)
return
}
if let string = item as? String,
let url = URL(string: string) {
continuation.resume(returning: url)
return
}
continuation.resume(returning: nil)
}
}
}
@MainActor
private static func loadImageAttachment(from provider: NSItemProvider) async throws -> ChatAttachment? {
let preferredImageType: UTType = if provider.hasItemConformingToTypeIdentifier(UTType.png.identifier) {
.png
} else if provider.hasItemConformingToTypeIdentifier(UTType.jpeg.identifier) {
.jpeg
} else {
.image
}
if let data = try await loadDataRepresentation(from: provider, type: preferredImageType) {
let filenameExtension = preferredImageType.preferredFilenameExtension ?? "jpg"
let filename = "pasted-image.\(filenameExtension)"
return try buildImageAttachment(data: data, filename: filename, contentType: preferredImageType)
}
if let image = try await loadUIImage(from: provider),
let jpegData = image.jpegData(compressionQuality: 0.92) {
return try buildImageAttachment(data: jpegData, filename: "pasted-image.jpg", contentType: .jpeg)
}
return nil
}
@MainActor
private static func loadDataRepresentation(from provider: NSItemProvider, type: UTType) async throws -> Data? {
guard provider.hasItemConformingToTypeIdentifier(type.identifier) else {
return nil
}
return try await withCheckedThrowingContinuation { continuation in
provider.loadDataRepresentation(forTypeIdentifier: type.identifier) { data, error in
if let error {
continuation.resume(throwing: error)
return
}
continuation.resume(returning: data)
}
}
}
@MainActor
private static func loadUIImage(from provider: NSItemProvider) async throws -> UIImage? {
guard provider.canLoadObject(ofClass: UIImage.self) else {
return nil
}
return try await withCheckedThrowingContinuation { continuation in
provider.loadObject(ofClass: UIImage.self) { object, error in
if let error {
continuation.resume(throwing: error)
return
}
continuation.resume(returning: object as? UIImage)
}
}
}
}

View File

@@ -5,6 +5,8 @@ struct SybilChatTranscriptView: View {
var messages: [Message]
var isLoading: Bool
var isSending: Bool
var onRefresh: (() async -> Void)? = nil
@State private var hasHandledInitialTranscriptScroll = false
private var hasPendingAssistant: Bool {
messages.contains { message in
@@ -15,16 +17,17 @@ struct SybilChatTranscriptView: View {
var body: some View {
ScrollViewReader { proxy in
ScrollView {
LazyVStack(alignment: .leading, spacing: 24) {
LazyVStack(alignment: .leading, spacing: 26) {
if isLoading && messages.isEmpty {
Text("Loading messages…")
.font(.footnote)
.font(.sybil(.footnote))
.foregroundStyle(SybilTheme.textMuted)
.padding(.top, 24)
}
ForEach(messages) { message in
MessageBubble(message: message, isSending: isSending)
.frame(maxWidth: .infinity)
.id(message.id)
}
@@ -34,7 +37,7 @@ struct SybilChatTranscriptView: View {
.controlSize(.small)
.tint(SybilTheme.textMuted)
Text("Assistant is typing…")
.font(.footnote)
.font(.sybil(.footnote))
.foregroundStyle(SybilTheme.textMuted)
}
.id("typing-indicator")
@@ -49,28 +52,43 @@ struct SybilChatTranscriptView: View {
.padding(.vertical, 18)
}
.frame(maxWidth: .infinity, alignment: .leading)
.refreshable {
await onRefresh?()
}
.tint(SybilTheme.primary)
.scrollDismissesKeyboard(.interactively)
.onAppear {
proxy.scrollTo("chat-bottom-anchor", anchor: .bottom)
scrollToBottom(with: proxy, animated: false)
}
.onChange(of: messages.map(\.id)) { _, _ in
withAnimation(.easeOut(duration: 0.22)) {
proxy.scrollTo("chat-bottom-anchor", anchor: .bottom)
}
scrollToBottom(with: proxy, animated: hasHandledInitialTranscriptScroll && !isLoading)
hasHandledInitialTranscriptScroll = true
}
.onChange(of: isSending) { _, _ in
withAnimation(.easeOut(duration: 0.22)) {
proxy.scrollTo("chat-bottom-anchor", anchor: .bottom)
}
scrollToBottom(with: proxy, animated: hasHandledInitialTranscriptScroll)
}
}
}
private func scrollToBottom(with proxy: ScrollViewProxy, animated: Bool) {
if animated {
withAnimation(.easeOut(duration: 0.22)) {
proxy.scrollTo("chat-bottom-anchor", anchor: .bottom)
}
} else {
proxy.scrollTo("chat-bottom-anchor", anchor: .bottom)
}
}
}
private struct MessageBubble: View {
var message: Message
var isSending: Bool
private var toolCallMetadata: ToolCallMetadata? {
message.toolCallMetadata
}
private var isUser: Bool {
message.role == .user
}
@@ -82,45 +100,185 @@ private struct MessageBubble: View {
}
var body: some View {
HStack {
VStack(alignment: .leading, spacing: 8) {
if isPendingAssistant {
HStack(spacing: 8) {
ProgressView()
.controlSize(.small)
.tint(SybilTheme.textMuted)
Text("Thinking…")
.font(.footnote)
.foregroundStyle(SybilTheme.textMuted)
HStack(alignment: .top, spacing: 0) {
leadingSpacer
if let toolCallMetadata {
ToolCallActivityChip(
metadata: toolCallMetadata,
fallbackContent: message.content,
createdAt: message.createdAt
)
} else {
VStack(alignment: .leading, spacing: 8) {
if !message.attachments.isEmpty {
SybilAttachmentListView(
attachments: message.attachments,
tone: isUser ? .user : .assistant
)
}
.padding(.vertical, 2)
} else {
Markdown(message.content)
.tint(SybilTheme.primary)
.foregroundStyle(isUser ? SybilTheme.text : SybilTheme.text.opacity(0.95))
.markdownTextStyle {
FontSize(15)
if isPendingAssistant {
HStack(spacing: 8) {
ProgressView()
.controlSize(.small)
.tint(SybilTheme.primary)
Text("Thinking…")
.font(.sybil(.footnote))
.foregroundStyle(SybilTheme.textMuted)
}
}
}
.padding(.horizontal, isUser ? 14 : 2)
.padding(.vertical, isUser ? 11 : 2)
.background(
Group {
if isUser {
RoundedRectangle(cornerRadius: 16)
.fill(SybilTheme.userBubble.opacity(0.86))
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(SybilTheme.primary.opacity(0.45), lineWidth: 1)
)
} else {
RoundedRectangle(cornerRadius: 0)
.fill(Color.clear)
.padding(.vertical, 2)
} else if !message.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
Markdown(message.content)
.tint(SybilTheme.primary)
.foregroundStyle(isUser ? SybilTheme.text : SybilTheme.text.opacity(0.95))
.markdownTheme(.sybilReadable)
}
}
)
.frame(maxWidth: isUser ? 420 : nil, alignment: isUser ? .trailing : .leading)
.padding(.horizontal, isUser ? 14 : 2)
.padding(.vertical, isUser ? 13 : 2)
.background(
Group {
if isUser {
RoundedRectangle(cornerRadius: 16)
.fill(SybilTheme.userBubbleGradient)
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(SybilTheme.primary.opacity(0.45), lineWidth: 1)
)
} else {
RoundedRectangle(cornerRadius: 0)
.fill(Color.clear)
}
}
)
.frame(maxWidth: isUser ? 420 : nil, alignment: isUser ? .trailing : .leading)
}
trailingSpacer
}
.frame(maxWidth: .infinity, alignment: isUser ? .trailing : .leading)
}
@ViewBuilder
private var leadingSpacer: some View {
if isUser {
Spacer(minLength: 44)
}
}
@ViewBuilder
private var trailingSpacer: some View {
if !isUser {
Spacer(minLength: 0)
}
}
}
private struct ToolCallActivityChip: View {
var metadata: ToolCallMetadata
var fallbackContent: String
var createdAt: Date
private var summary: String {
if let text = metadata.summary?.trimmingCharacters(in: .whitespacesAndNewlines), !text.isEmpty {
return text
}
if (metadata.status ?? "").lowercased() == "failed",
let error = metadata.error?.trimmingCharacters(in: .whitespacesAndNewlines),
!error.isEmpty {
return "Tool failed: \(error)"
}
if let preview = metadata.resultPreview?.trimmingCharacters(in: .whitespacesAndNewlines), !preview.isEmpty {
return preview
}
if !fallbackContent.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
return fallbackContent
}
return "Ran tool '\(metadata.toolName ?? "unknown_tool")'."
}
private var toolLabel: String {
let raw = metadata.toolName?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard !raw.isEmpty else { return "Tool call" }
return raw
.replacingOccurrences(of: "_", with: " ")
.split(separator: " ")
.map { word in
word.prefix(1).uppercased() + word.dropFirst()
}
.joined(separator: " ")
}
private var iconName: String {
let name = (metadata.toolName ?? "").lowercased()
if name.contains("search") {
return "globe"
}
if name.contains("url") || name.contains("fetch") || name.contains("http") {
return "link"
}
return "wrench.and.screwdriver"
}
private var isFailed: Bool {
(metadata.status ?? "").lowercased() == "failed"
}
private var detailLabel: String {
var pieces: [String] = [isFailed ? "Failed" : "Completed"]
if let durationMs = metadata.durationMs, durationMs > 0 {
pieces.append("\(durationMs) ms")
}
pieces.append(createdAt.sybilShortTimeLabel)
return pieces.joined(separator: "")
}
var body: some View {
HStack(alignment: .top, spacing: 11) {
ZStack {
RoundedRectangle(cornerRadius: 9)
.fill((isFailed ? SybilTheme.danger : SybilTheme.accent).opacity(0.13))
.overlay(
RoundedRectangle(cornerRadius: 9)
.stroke((isFailed ? SybilTheme.danger : SybilTheme.accent).opacity(0.34), lineWidth: 1)
)
Image(systemName: iconName)
.font(.system(size: 14, weight: .semibold))
.foregroundStyle(isFailed ? SybilTheme.danger : SybilTheme.accent)
}
.frame(width: 30, height: 30)
VStack(alignment: .leading, spacing: 4) {
Text(summary)
.font(.sybil(.subheadline))
.foregroundStyle(isFailed ? SybilTheme.danger.opacity(0.96) : SybilTheme.text.opacity(0.94))
.lineSpacing(3)
.fixedSize(horizontal: false, vertical: true)
HStack(spacing: 6) {
Text(toolLabel)
.font(.sybil(.caption2, weight: .semibold))
.foregroundStyle(isFailed ? SybilTheme.danger.opacity(0.84) : SybilTheme.accent.opacity(0.90))
.lineLimit(1)
Text(detailLabel)
.font(.sybil(.caption2))
.foregroundStyle(SybilTheme.textMuted)
.lineLimit(1)
}
}
}
.padding(.horizontal, 12)
.padding(.vertical, 10)
.background(
RoundedRectangle(cornerRadius: 12)
.fill(isFailed ? SybilTheme.failedToolCallGradient : SybilTheme.toolCallGradient)
.overlay(
RoundedRectangle(cornerRadius: 12)
.stroke((isFailed ? SybilTheme.danger : SybilTheme.accent).opacity(0.34), lineWidth: 1)
)
)
.frame(maxWidth: 520, alignment: .leading)
}
}

View File

@@ -8,23 +8,32 @@ struct SybilConnectionView: View {
@Bindable var settings = viewModel.settings
VStack(spacing: 20) {
HStack {
SybilWordmark(size: 34)
Spacer()
}
HStack(alignment: .top, spacing: 12) {
Image(systemName: "shield.lefthalf.filled")
.font(.title3.weight(.semibold))
.foregroundStyle(SybilTheme.primary)
.font(.system(size: 20, weight: .semibold))
.foregroundStyle(SybilTheme.accent)
.frame(width: 34, height: 34)
.background(
RoundedRectangle(cornerRadius: 10)
.fill(SybilTheme.primary.opacity(0.18))
.fill(SybilTheme.accent.opacity(0.12))
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(SybilTheme.accent.opacity(0.28), lineWidth: 1)
)
)
VStack(alignment: .leading, spacing: 4) {
Text("Connect to Sybil")
.font(.title3.weight(.semibold))
.font(.sybil(.title3, weight: .semibold))
.foregroundStyle(SybilTheme.text)
Text("Point the app at your backend and sign in with ADMIN_TOKEN if token mode is enabled.")
.font(.callout)
.font(.sybil(.callout))
.foregroundStyle(SybilTheme.textMuted)
.fixedSize(horizontal: false, vertical: true)
}
@@ -32,25 +41,25 @@ struct SybilConnectionView: View {
VStack(alignment: .leading, spacing: 10) {
Text("API URL")
.font(.caption.weight(.semibold))
.font(.sybil(.caption, weight: .semibold))
.foregroundStyle(SybilTheme.textMuted)
TextField("http://127.0.0.1:8787/api", text: $settings.apiBaseURL)
TextField("http://127.0.0.1:8787", text: $settings.apiBaseURL)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.keyboardType(.URL)
.padding(12)
.background(
RoundedRectangle(cornerRadius: 12)
.fill(SybilTheme.surface)
.fill(SybilTheme.surface.opacity(0.78))
)
.overlay(
RoundedRectangle(cornerRadius: 12)
.stroke(SybilTheme.border, lineWidth: 1)
.stroke(SybilTheme.border.opacity(0.88), lineWidth: 1)
)
Text("Admin Token")
.font(.caption.weight(.semibold))
.font(.sybil(.caption, weight: .semibold))
.foregroundStyle(SybilTheme.textMuted)
SecureField("ADMIN_TOKEN (optional in open mode)", text: $settings.adminToken)
@@ -59,11 +68,11 @@ struct SybilConnectionView: View {
.padding(12)
.background(
RoundedRectangle(cornerRadius: 12)
.fill(SybilTheme.surface)
.fill(SybilTheme.surface.opacity(0.78))
)
.overlay(
RoundedRectangle(cornerRadius: 12)
.stroke(SybilTheme.border, lineWidth: 1)
.stroke(SybilTheme.border.opacity(0.88), lineWidth: 1)
)
}
@@ -94,7 +103,7 @@ struct SybilConnectionView: View {
if let authError = viewModel.authError {
Text(authError)
.font(.footnote)
.font(.sybil(.footnote))
.foregroundStyle(SybilTheme.danger)
.frame(maxWidth: .infinity, alignment: .leading)
}
@@ -103,10 +112,10 @@ struct SybilConnectionView: View {
.frame(maxWidth: 520)
.background(
RoundedRectangle(cornerRadius: 20)
.fill(SybilTheme.card)
.fill(SybilTheme.panelGradient)
.overlay(
RoundedRectangle(cornerRadius: 20)
.stroke(SybilTheme.border, lineWidth: 1)
.stroke(SybilTheme.border.opacity(0.9), lineWidth: 1)
)
)
}

View File

@@ -0,0 +1,165 @@
import MarkdownUI
import SwiftUI
@MainActor
extension Theme {
static let sybilReadable: Theme = {
SybilFontRegistry.registerIfNeeded()
return Theme()
.text {
FontFamily(.custom("Inter"))
FontSize(15)
ForegroundColor(SybilTheme.text)
}
.code {
FontFamilyVariant(.monospaced)
FontSize(.em(0.88))
BackgroundColor(SybilTheme.surfaceStrong.opacity(0.78))
}
.strong {
FontWeight(.semibold)
}
.link {
ForegroundColor(SybilTheme.accent)
}
.heading1 { configuration in
configuration.label
.fixedSize(horizontal: false, vertical: true)
.relativeLineSpacing(.em(0.18))
.markdownMargin(top: .em(1.1), bottom: .em(0.5))
.markdownTextStyle {
FontWeight(.semibold)
FontSize(.em(1.45))
}
}
.heading2 { configuration in
configuration.label
.fixedSize(horizontal: false, vertical: true)
.relativeLineSpacing(.em(0.18))
.markdownMargin(top: .em(1.0), bottom: .em(0.45))
.markdownTextStyle {
FontWeight(.semibold)
FontSize(.em(1.25))
}
}
.heading3 { configuration in
configuration.label
.fixedSize(horizontal: false, vertical: true)
.relativeLineSpacing(.em(0.18))
.markdownMargin(top: .em(0.9), bottom: .em(0.4))
.markdownTextStyle {
FontWeight(.semibold)
FontSize(.em(1.12))
}
}
.heading4 { configuration in
configuration.label
.fixedSize(horizontal: false, vertical: true)
.relativeLineSpacing(.em(0.18))
.markdownMargin(top: .em(0.85), bottom: .em(0.35))
.markdownTextStyle {
FontWeight(.semibold)
}
}
.heading5 { configuration in
configuration.label
.fixedSize(horizontal: false, vertical: true)
.relativeLineSpacing(.em(0.18))
.markdownMargin(top: .em(0.8), bottom: .em(0.35))
.markdownTextStyle {
FontWeight(.semibold)
FontSize(.em(0.92))
}
}
.heading6 { configuration in
configuration.label
.fixedSize(horizontal: false, vertical: true)
.relativeLineSpacing(.em(0.18))
.markdownMargin(top: .em(0.8), bottom: .em(0.35))
.markdownTextStyle {
FontWeight(.semibold)
FontSize(.em(0.86))
}
}
.paragraph { configuration in
configuration.label
.fixedSize(horizontal: false, vertical: true)
.relativeLineSpacing(.em(0.36))
.markdownMargin(top: .zero, bottom: .em(0.82))
}
.blockquote { configuration in
HStack(alignment: .top, spacing: 10) {
RoundedRectangle(cornerRadius: 2)
.fill(SybilTheme.primary.opacity(0.55))
.frame(width: 3)
configuration.label
.markdownTextStyle {
ForegroundColor(SybilTheme.textMuted)
}
}
.fixedSize(horizontal: false, vertical: true)
.markdownMargin(top: .em(0.25), bottom: .em(0.9))
}
.codeBlock { configuration in
ScrollView(.horizontal) {
configuration.label
.fixedSize(horizontal: false, vertical: true)
.relativeLineSpacing(.em(0.28))
.markdownTextStyle {
FontFamilyVariant(.monospaced)
FontSize(.em(0.88))
}
.padding(12)
}
.background(
RoundedRectangle(cornerRadius: 10)
.fill(SybilTheme.surfaceStrong.opacity(0.82))
)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(SybilTheme.border.opacity(0.72), lineWidth: 1)
)
.markdownMargin(top: .em(0.2), bottom: .em(1))
}
.list { configuration in
configuration.label
.fixedSize(horizontal: false, vertical: true)
.markdownMargin(top: .em(0.08), bottom: .em(0.78))
}
.listItem { configuration in
configuration.label
.markdownMargin(top: .em(0.28))
}
.table { configuration in
configuration.label
.fixedSize(horizontal: false, vertical: true)
.markdownTableBorderStyle(.init(color: SybilTheme.border.opacity(0.85)))
.markdownTableBackgroundStyle(
.alternatingRows(
SybilTheme.surface.opacity(0.72),
SybilTheme.surfaceStrong.opacity(0.62)
)
)
.markdownMargin(top: .em(0.2), bottom: .em(1))
}
.tableCell { configuration in
configuration.label
.markdownTextStyle {
if configuration.row == 0 {
FontWeight(.semibold)
}
BackgroundColor(nil)
}
.fixedSize(horizontal: false, vertical: true)
.relativeLineSpacing(.em(0.30))
.padding(.vertical, 7)
.padding(.horizontal, 11)
}
.thematicBreak {
Divider()
.overlay(SybilTheme.border.opacity(0.82))
.markdownMargin(top: .em(1.2), bottom: .em(1.2))
}
}()
}

View File

@@ -21,6 +21,132 @@ public enum MessageRole: String, Codable, Hashable, Sendable {
case tool
}
public struct ChatAttachment: Codable, Hashable, Identifiable, Sendable {
public enum Kind: String, Codable, Hashable, Sendable {
case image
case text
}
public var id: String
public var kind: Kind
public var filename: String
public var mimeType: String
public var sizeBytes: Int
public var dataUrl: String?
public var text: String?
public var truncated: Bool?
public init(
id: String,
kind: Kind,
filename: String,
mimeType: String,
sizeBytes: Int,
dataUrl: String? = nil,
text: String? = nil,
truncated: Bool? = nil
) {
self.id = id
self.kind = kind
self.filename = filename
self.mimeType = mimeType
self.sizeBytes = sizeBytes
self.dataUrl = dataUrl
self.text = text
self.truncated = truncated
}
public static func image(
id: String = UUID().uuidString,
filename: String,
mimeType: String,
sizeBytes: Int,
dataUrl: String
) -> ChatAttachment {
ChatAttachment(
id: id,
kind: .image,
filename: filename,
mimeType: mimeType,
sizeBytes: sizeBytes,
dataUrl: dataUrl
)
}
public static func text(
id: String = UUID().uuidString,
filename: String,
mimeType: String,
sizeBytes: Int,
text: String,
truncated: Bool
) -> ChatAttachment {
ChatAttachment(
id: id,
kind: .text,
filename: filename,
mimeType: mimeType,
sizeBytes: sizeBytes,
text: text,
truncated: truncated
)
}
var jsonValue: JSONValue {
var object: [String: JSONValue] = [
"kind": .string(kind.rawValue),
"id": .string(id),
"filename": .string(filename),
"mimeType": .string(mimeType),
"sizeBytes": .number(Double(sizeBytes))
]
if let dataUrl {
object["dataUrl"] = .string(dataUrl)
}
if let text {
object["text"] = .string(text)
}
if let truncated {
object["truncated"] = .bool(truncated)
}
return .object(object)
}
static func attachments(from metadata: JSONValue?) -> [ChatAttachment] {
guard let metadataObject = metadata?.objectValue,
let values = metadataObject["attachments"]?.arrayValue
else {
return []
}
return values.compactMap { value in
guard let object = value.objectValue,
let kindRaw = object["kind"]?.stringValue,
let kind = Kind(rawValue: kindRaw),
let id = object["id"]?.stringValue,
let filename = object["filename"]?.stringValue,
let mimeType = object["mimeType"]?.stringValue,
let sizeNumber = object["sizeBytes"]?.numberValue
else {
return nil
}
return ChatAttachment(
id: id,
kind: kind,
filename: filename,
mimeType: mimeType,
sizeBytes: Int(sizeNumber),
dataUrl: object["dataUrl"]?.stringValue,
text: object["text"]?.stringValue,
truncated: object["truncated"]?.boolValue
)
}
}
}
public struct ChatSummary: Codable, Identifiable, Hashable, Sendable {
public var id: String
public var title: String?
@@ -46,6 +172,133 @@ public struct Message: Codable, Identifiable, Hashable, Sendable {
public var role: MessageRole
public var content: String
public var name: String?
public var metadata: JSONValue? = nil
public var attachments: [ChatAttachment] {
ChatAttachment.attachments(from: metadata)
}
public var toolCallMetadata: ToolCallMetadata? {
guard role == .tool,
let object = metadata?.objectValue,
object["kind"]?.stringValue == "tool_call"
else { return nil }
return ToolCallMetadata(
toolCallId: object["toolCallId"]?.stringValue,
toolName: object["toolName"]?.stringValue ?? name,
status: object["status"]?.stringValue,
summary: object["summary"]?.stringValue,
durationMs: object["durationMs"]?.numberValue.map(Int.init),
error: object["error"]?.stringValue,
resultPreview: object["resultPreview"]?.stringValue
)
}
public var isToolCallLog: Bool {
toolCallMetadata != nil
}
}
public struct ToolCallMetadata: Hashable, Sendable {
public var toolCallId: String?
public var toolName: String?
public var status: String?
public var summary: String?
public var durationMs: Int?
public var error: String?
public var resultPreview: String?
}
public enum JSONValue: Codable, Hashable, Sendable {
case string(String)
case number(Double)
case bool(Bool)
case object([String: JSONValue])
case array([JSONValue])
case null
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if container.decodeNil() {
self = .null
return
}
if let value = try? container.decode(Bool.self) {
self = .bool(value)
return
}
if let value = try? container.decode(Double.self) {
self = .number(value)
return
}
if let value = try? container.decode(String.self) {
self = .string(value)
return
}
if let value = try? container.decode([String: JSONValue].self) {
self = .object(value)
return
}
if let value = try? container.decode([JSONValue].self) {
self = .array(value)
return
}
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unsupported JSON value")
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case let .string(value):
try container.encode(value)
case let .number(value):
try container.encode(value)
case let .bool(value):
try container.encode(value)
case let .object(value):
try container.encode(value)
case let .array(value):
try container.encode(value)
case .null:
try container.encodeNil()
}
}
public var stringValue: String? {
if case let .string(value) = self {
return value
}
return nil
}
public var numberValue: Double? {
if case let .number(value) = self {
return value
}
return nil
}
public var objectValue: [String: JSONValue]? {
if case let .object(value) = self {
return value
}
return nil
}
public var arrayValue: [JSONValue]? {
if case let .array(value) = self {
return value
}
return nil
}
public var boolValue: Bool? {
if case let .bool(value) = self {
return value
}
return nil
}
}
public struct ChatDetail: Codable, Identifiable, Hashable, Sendable {
@@ -130,11 +383,13 @@ public struct CompletionRequestMessage: Codable, Sendable {
public var role: MessageRole
public var content: String
public var name: String?
public var attachments: [ChatAttachment]?
public init(role: MessageRole, content: String, name: String? = nil) {
public init(role: MessageRole, content: String, name: String? = nil, attachments: [ChatAttachment]? = nil) {
self.role = role
self.content = content
self.name = name
self.attachments = attachments
}
}
@@ -153,12 +408,26 @@ public struct CompletionStreamDone: Codable, Sendable {
public var text: String
}
public struct CompletionStreamToolCall: Codable, Sendable {
public var toolCallId: String
public var name: String
public var status: String
public var summary: String
public var args: [String: JSONValue]
public var startedAt: String
public var completedAt: String
public var durationMs: Int
public var error: String?
public var resultPreview: String?
}
public struct StreamErrorPayload: Codable, Sendable {
public var message: String
}
public enum CompletionStreamEvent: Sendable {
case meta(CompletionStreamMeta)
case toolCall(CompletionStreamToolCall)
case delta(CompletionStreamDelta)
case done(CompletionStreamDone)
case error(StreamErrorPayload)
@@ -302,6 +571,14 @@ extension DateFormatter {
formatter.timeStyle = .short
return formatter
}()
static let sybilShortTime: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = .autoupdatingCurrent
formatter.dateStyle = .none
formatter.timeStyle = .short
return formatter
}()
}
extension Date {
@@ -311,4 +588,8 @@ extension Date {
formatter.unitsStyle = .abbreviated
return formatter.localizedString(for: self, relativeTo: Date())
}
var sybilShortTimeLabel: String {
DateFormatter.sybilShortTime.string(from: self)
}
}

View File

@@ -23,17 +23,51 @@ enum PhoneRoute: Hashable {
struct SybilPhoneShellView: View {
@Bindable var viewModel: SybilViewModel
@State private var path: [PhoneRoute] = []
@Environment(\.scenePhase) private var scenePhase
@State private var shouldRefreshOnForeground = false
@State private var composerFocusRequest = 0
var body: some View {
NavigationStack(path: $path) {
SybilPhoneSidebarRoot(viewModel: viewModel, path: $path)
.navigationTitle("Sybil")
.navigationTitle("")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .topBarLeading) {
SybilWordmark(size: 18)
}
}
.navigationDestination(for: PhoneRoute.self) { route in
SybilPhoneDestinationView(viewModel: viewModel, route: route)
SybilPhoneDestinationView(
viewModel: viewModel,
path: $path,
composerFocusRequest: $composerFocusRequest,
route: route
)
}
}
.tint(SybilTheme.primary)
.onChange(of: scenePhase) { _, nextPhase in
switch nextPhase {
case .background:
shouldRefreshOnForeground = true
case .active:
guard shouldRefreshOnForeground else {
return
}
shouldRefreshOnForeground = false
Task {
await viewModel.refreshVisibleContent(
refreshCollections: path.isEmpty,
refreshSelection: !path.isEmpty && viewModel.hasRefreshableSelection
)
}
case .inactive:
break
@unknown default:
break
}
}
}
}
@@ -43,14 +77,9 @@ private struct SybilPhoneSidebarRoot: View {
var body: some View {
VStack(spacing: 0) {
buttonRow
Divider()
.overlay(SybilTheme.border)
if let errorMessage = viewModel.errorMessage {
Text(errorMessage)
.font(.footnote)
.font(.sybil(.footnote))
.foregroundStyle(SybilTheme.danger)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 12)
@@ -65,7 +94,7 @@ private struct SybilPhoneSidebarRoot: View {
ProgressView()
.tint(SybilTheme.primary)
Text("Loading conversations…")
.font(.footnote)
.font(.sybil(.footnote))
.foregroundStyle(SybilTheme.textMuted)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
@@ -73,10 +102,10 @@ private struct SybilPhoneSidebarRoot: View {
} else if viewModel.sidebarItems.isEmpty {
VStack(spacing: 10) {
Image(systemName: "message.badge")
.font(.title3)
.font(.system(size: 20, weight: .medium))
.foregroundStyle(SybilTheme.textMuted)
Text("Start a chat or run your first search.")
.font(.footnote)
.font(.sybil(.footnote))
.multilineTextAlignment(.center)
.foregroundStyle(SybilTheme.textMuted)
}
@@ -103,49 +132,72 @@ private struct SybilPhoneSidebarRoot: View {
}
.padding(10)
}
.refreshable {
await viewModel.refreshCollectionsFromUser()
}
.tint(SybilTheme.primary)
}
}
.background(SybilTheme.panelGradient)
.safeAreaInset(edge: .bottom, spacing: 0) {
bottomToolbar
}
}
private var bottomToolbar: some View {
VStack(spacing: 0) {
Divider()
.overlay(SybilTheme.border)
NavigationLink(value: PhoneRoute.settings) {
Label("Settings", systemImage: "gearshape")
.font(.subheadline.weight(.medium))
.foregroundStyle(SybilTheme.text)
.padding(.horizontal, 12)
.padding(.vertical, 10)
.frame(maxWidth: .infinity, alignment: .leading)
HStack(spacing: 12) {
toolbarIconButton(systemImage: "gearshape", accessibilityLabel: "Settings") {
path = [.settings]
}
Spacer()
toolbarIconButton(systemImage: "magnifyingglass", accessibilityLabel: "New search") {
viewModel.startNewSearch()
path = [.draftSearch]
}
toolbarIconButton(systemImage: "plus", accessibilityLabel: "New chat", isPrimary: true) {
viewModel.startNewChat()
path = [.draftChat]
}
}
.buttonStyle(.plain)
.padding(10)
.padding(.horizontal, 18)
.padding(.vertical, 10)
.background(SybilTheme.panelGradient)
}
.background(SybilTheme.surfaceStrong.opacity(0.84))
}
private var buttonRow: some View {
HStack(spacing: 10) {
Button {
viewModel.startNewChat()
path.append(.draftChat)
} label: {
Label("New chat", systemImage: "plus")
.frame(maxWidth: .infinity)
}
.buttonStyle(.borderedProminent)
.tint(SybilTheme.primarySoft)
Button {
viewModel.startNewSearch()
path.append(.draftSearch)
} label: {
Label("New search", systemImage: "magnifyingglass")
.frame(maxWidth: .infinity)
}
.buttonStyle(.bordered)
.tint(SybilTheme.textMuted)
private func toolbarIconButton(
systemImage: String,
accessibilityLabel: String,
isPrimary: Bool = false,
action: @escaping () -> Void
) -> some View {
Button(action: action) {
Image(systemName: systemImage)
.font(.system(size: 18, weight: .semibold))
.foregroundStyle(isPrimary ? SybilTheme.text : SybilTheme.textMuted)
.frame(width: 42, height: 42)
.background(
Circle()
.fill(
isPrimary
? AnyShapeStyle(SybilTheme.primaryGradient)
: AnyShapeStyle(SybilTheme.surface.opacity(0.78))
)
)
.overlay(
Circle()
.stroke(isPrimary ? SybilTheme.primary.opacity(0.42) : SybilTheme.border.opacity(0.76), lineWidth: 1)
)
}
.padding(.horizontal, 12)
.padding(.vertical, 12)
.buttonStyle(.plain)
.accessibilityLabel(accessibilityLabel)
}
}
@@ -156,24 +208,36 @@ private struct SybilPhoneSidebarRow: View {
VStack(alignment: .leading, spacing: 6) {
HStack(spacing: 8) {
Image(systemName: item.kind == .chat ? "message" : "globe")
.font(.caption.weight(.semibold))
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(SybilTheme.textMuted)
.frame(width: 22, height: 22)
.background(
RoundedRectangle(cornerRadius: 7)
.fill(SybilTheme.surface.opacity(0.72))
.overlay(
RoundedRectangle(cornerRadius: 7)
.stroke(SybilTheme.border.opacity(0.72), lineWidth: 1)
)
)
Text(item.title)
.font(.subheadline.weight(.medium))
.font(.sybil(.subheadline, weight: .semibold))
.lineLimit(1)
}
HStack(spacing: 8) {
Text(item.updatedAt.sybilRelativeLabel)
.font(.caption2)
.font(.sybil(.caption2))
.foregroundStyle(SybilTheme.textMuted)
if let initiated = item.initiatedLabel {
Spacer(minLength: 0)
Text(initiated)
.font(.caption2)
.font(.sybil(.caption2))
.foregroundStyle(SybilTheme.textMuted.opacity(0.88))
.lineLimit(1)
.multilineTextAlignment(.trailing)
.frame(maxWidth: .infinity, alignment: .trailing)
}
}
}
@@ -183,7 +247,7 @@ private struct SybilPhoneSidebarRow: View {
.frame(maxWidth: .infinity, alignment: .leading)
.background(
RoundedRectangle(cornerRadius: 12)
.fill(SybilTheme.surface.opacity(0.55))
.fill(LinearGradient(colors: [SybilTheme.surface.opacity(0.56), SybilTheme.surface.opacity(0.36)], startPoint: .topLeading, endPoint: .bottomTrailing))
)
.overlay(
RoundedRectangle(cornerRadius: 12)
@@ -194,15 +258,25 @@ private struct SybilPhoneSidebarRow: View {
private struct SybilPhoneDestinationView: View {
@Bindable var viewModel: SybilViewModel
@Binding var path: [PhoneRoute]
@Binding var composerFocusRequest: Int
let route: PhoneRoute
var body: some View {
SybilWorkspaceView(viewModel: viewModel)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.navigationBarTitleDisplayMode(.inline)
.task(id: route) {
applyRoute()
SybilWorkspaceView(viewModel: viewModel, composerFocusRequest: composerFocusRequest) {
viewModel.startNewChat()
composerFocusRequest += 1
if path.isEmpty {
path = [.draftChat]
} else {
path[path.index(before: path.endIndex)] = .draftChat
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.navigationBarTitleDisplayMode(.inline)
.task(id: route) {
applyRoute()
}
}
private func applyRoute() {

View File

@@ -5,23 +5,61 @@ struct SybilSearchResultsView: View {
var search: SearchDetail?
var isLoading: Bool
var isRunning: Bool
var isStartingChat: Bool = false
var onRefresh: (() async -> Void)? = nil
var onStartChat: (() -> Void)? = nil
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 16) {
if let query = search?.query, !query.isEmpty {
VStack(alignment: .leading, spacing: 4) {
Text("Results for")
.font(.footnote)
.foregroundStyle(SybilTheme.textMuted)
Text(query)
.font(.title3.weight(.semibold))
.foregroundStyle(SybilTheme.text)
.fixedSize(horizontal: false, vertical: true)
VStack(alignment: .leading, spacing: 12) {
VStack(alignment: .leading, spacing: 4) {
Text("Results for")
.font(.sybil(.footnote))
.foregroundStyle(SybilTheme.textMuted)
Text(query)
.font(.sybil(.title3, weight: .semibold))
.foregroundStyle(SybilTheme.text)
.fixedSize(horizontal: false, vertical: true)
Text(resultCountLabel)
.font(.caption)
.foregroundStyle(SybilTheme.textMuted)
Text(resultCountLabel)
.font(.sybil(.caption))
.foregroundStyle(SybilTheme.textMuted)
}
if let onStartChat {
Button {
onStartChat()
} label: {
HStack(spacing: 8) {
if isStartingChat {
ProgressView()
.controlSize(.small)
.tint(SybilTheme.text)
} else {
Image(systemName: "bubble.left.and.text.bubble.right")
.font(.system(size: 14, weight: .semibold))
}
Text(isStartingChat ? "Starting chat..." : "Chat with results")
.font(.sybil(.caption, weight: .semibold))
}
.foregroundStyle(SybilTheme.text)
.padding(.horizontal, 12)
.padding(.vertical, 9)
.background(
RoundedRectangle(cornerRadius: 10)
.fill(SybilTheme.primary.opacity(0.14))
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(SybilTheme.primary.opacity(0.30), lineWidth: 1)
)
)
}
.buttonStyle(.plain)
.disabled(!canStartChat)
.opacity(canStartChat ? 1 : 0.55)
}
}
}
@@ -36,14 +74,14 @@ struct SybilSearchResultsView: View {
.controlSize(.small)
.tint(SybilTheme.textMuted)
Text(isRunning ? "Searching Exa…" : "Loading search…")
.font(.footnote)
.font(.sybil(.footnote))
.foregroundStyle(SybilTheme.textMuted)
}
}
if !isLoading, !isRunning, let search, !search.query.orEmpty.isEmpty, search.results.isEmpty {
Text("No results found.")
.font(.footnote)
.font(.sybil(.footnote))
.foregroundStyle(SybilTheme.textMuted)
}
@@ -55,7 +93,7 @@ struct SybilSearchResultsView: View {
if let error = search?.error, !error.isEmpty {
Text(error)
.font(.footnote)
.font(.sybil(.footnote))
.foregroundStyle(SybilTheme.danger)
}
}
@@ -63,6 +101,10 @@ struct SybilSearchResultsView: View {
.padding(.horizontal, 14)
.padding(.vertical, 20)
}
.refreshable {
await onRefresh?()
}
.tint(SybilTheme.primary)
.scrollDismissesKeyboard(.interactively)
.frame(maxWidth: .infinity, alignment: .leading)
}
@@ -76,13 +118,20 @@ struct SybilSearchResultsView: View {
return "\(count) result\(count == 1 ? "" : "s")"
}
private var canStartChat: Bool {
guard let search, !isLoading, !isRunning, !isStartingChat else {
return false
}
return search.answerText?.isEmpty == false || !search.results.isEmpty
}
@ViewBuilder
private var answerCard: some View {
VStack(alignment: .leading, spacing: 10) {
Text("Answer")
.font(.caption.weight(.semibold))
.font(.sybil(.caption, weight: .semibold))
.textCase(.uppercase)
.foregroundStyle(SybilTheme.primary)
.foregroundStyle(SybilTheme.primary.opacity(0.92))
if isRunning && (search?.answerText.orEmpty.isEmpty ?? true) {
HStack(spacing: 8) {
@@ -90,21 +139,19 @@ struct SybilSearchResultsView: View {
.controlSize(.small)
.tint(SybilTheme.textMuted)
Text("Generating answer…")
.font(.footnote)
.font(.sybil(.footnote))
.foregroundStyle(SybilTheme.textMuted)
}
} else if let answer = search?.answerText, !answer.isEmpty {
Markdown(answer)
.tint(SybilTheme.primary)
.foregroundStyle(SybilTheme.text)
.markdownTextStyle {
FontSize(15)
}
.markdownTheme(.sybilReadable)
}
if let answerError = search?.answerError, !answerError.isEmpty {
Text(answerError)
.font(.footnote)
.font(.sybil(.footnote))
.foregroundStyle(SybilTheme.danger)
}
@@ -115,23 +162,23 @@ struct SybilSearchResultsView: View {
Link(destination: URL(string: link) ?? URL(string: "https://example.com")!) {
HStack(spacing: 6) {
Text("[\(index + 1)]")
.font(.caption2.weight(.semibold))
.font(.sybil(.caption2, weight: .semibold))
.foregroundStyle(SybilTheme.primary)
Text(citation.title.orEmpty.isEmpty ? host(for: link) : citation.title.orEmpty)
.font(.caption)
.font(.sybil(.caption))
.lineLimit(1)
.foregroundStyle(SybilTheme.text)
}
.padding(.horizontal, 10)
.padding(.vertical, 6)
.background(
Capsule()
.fill(SybilTheme.surface)
.overlay(
Capsule()
.stroke(SybilTheme.border, lineWidth: 1)
)
)
.padding(.horizontal, 10)
.padding(.vertical, 6)
.background(
Capsule()
.fill(SybilTheme.primary.opacity(0.10))
.overlay(
Capsule()
.stroke(SybilTheme.primary.opacity(0.28), lineWidth: 1)
)
)
}
.buttonStyle(.plain)
}
@@ -142,10 +189,10 @@ struct SybilSearchResultsView: View {
.padding(14)
.background(
RoundedRectangle(cornerRadius: 16)
.fill(SybilTheme.searchCard)
.fill(LinearGradient(colors: [SybilTheme.searchCard.opacity(0.98), SybilTheme.surface.opacity(0.78)], startPoint: .topLeading, endPoint: .bottomTrailing))
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(SybilTheme.border, lineWidth: 1)
.stroke(SybilTheme.border.opacity(0.88), lineWidth: 1)
)
)
.frame(maxWidth: .infinity, alignment: .leading)
@@ -171,45 +218,49 @@ private struct SearchResultCard: View {
HStack {
VStack(alignment: .leading, spacing: 7) {
Text(host)
.font(.caption)
.foregroundStyle(SybilTheme.primary.opacity(0.9))
.font(.sybil(.caption))
.foregroundStyle(SybilTheme.accent.opacity(0.9))
.lineLimit(1)
if let resolvedURL {
Link(destination: resolvedURL) {
Text(result.title.orEmpty.orFallback(result.url))
.font(.headline)
.foregroundStyle(SybilTheme.primary)
.font(.sybil(.headline))
.foregroundStyle(SybilTheme.primary.opacity(0.96))
.lineSpacing(2)
.multilineTextAlignment(.leading)
}
.buttonStyle(.plain)
} else {
Text(result.title.orEmpty.orFallback(result.url))
.font(.headline)
.foregroundStyle(SybilTheme.primary)
.font(.sybil(.headline))
.foregroundStyle(SybilTheme.primary.opacity(0.96))
.lineSpacing(2)
}
if let date = result.publishedDate, !date.isEmpty {
Text(date + (result.author.orEmpty.isEmpty ? "" : "\(result.author.orEmpty)"))
.font(.caption)
.font(.sybil(.caption))
.foregroundStyle(SybilTheme.textMuted)
} else if let author = result.author, !author.isEmpty {
Text(author)
.font(.caption)
.font(.sybil(.caption))
.foregroundStyle(SybilTheme.textMuted)
}
Text(result.url)
.font(.footnote)
.font(.sybil(.footnote))
.foregroundStyle(SybilTheme.text.opacity(0.92))
.lineSpacing(2)
.lineLimit(3)
.textSelection(.enabled)
if let highlights = result.highlights, !highlights.isEmpty {
ForEach(Array(highlights.prefix(2).enumerated()), id: \.offset) { _, highlight in
Text("\(highlight)")
.font(.caption)
.font(.sybil(.caption))
.foregroundStyle(SybilTheme.textMuted)
.lineSpacing(2)
.fixedSize(horizontal: false, vertical: true)
}
}
@@ -220,10 +271,10 @@ private struct SearchResultCard: View {
.padding(14)
.background(
RoundedRectangle(cornerRadius: 14)
.fill(SybilTheme.searchCard.opacity(0.95))
.fill(LinearGradient(colors: [SybilTheme.searchCard.opacity(0.96), SybilTheme.surface.opacity(0.72)], startPoint: .topLeading, endPoint: .bottomTrailing))
.overlay(
RoundedRectangle(cornerRadius: 14)
.stroke(SybilTheme.border, lineWidth: 1)
.stroke(SybilTheme.border.opacity(0.84), lineWidth: 1)
)
)
.frame(maxWidth: .infinity, alignment: .leading)

View File

@@ -24,7 +24,7 @@ final class SybilSettingsStore {
self.defaults = defaults
let storedBaseURL = defaults.string(forKey: Keys.apiBaseURL)?.trimmingCharacters(in: .whitespacesAndNewlines)
let fallbackBaseURL = "http://127.0.0.1:8787/api"
let fallbackBaseURL = "http://127.0.0.1:8787"
self.apiBaseURL = storedBaseURL?.isEmpty == false ? storedBaseURL! : fallbackBaseURL
self.adminToken = defaults.string(forKey: Keys.adminToken) ?? ""
@@ -64,10 +64,14 @@ final class SybilSettingsStore {
var raw = apiBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)
guard !raw.isEmpty else { return nil }
if raw.hasSuffix("/") {
while raw.hasSuffix("/") {
raw.removeLast()
}
return URL(string: raw)
guard var components = URLComponents(string: raw) else {
return nil
}
return components.url
}
}

View File

@@ -11,19 +11,19 @@ struct SybilSettingsView: View {
VStack(alignment: .leading, spacing: 18) {
VStack(alignment: .leading, spacing: 6) {
Text("Connection")
.font(.title3.weight(.semibold))
.font(.sybil(.title3, weight: .semibold))
.foregroundStyle(SybilTheme.text)
Text("Use the same API root as the web client. Example: `http://127.0.0.1:8787/api`")
.font(.footnote)
Text("Use the API server root. Example: `http://127.0.0.1:8787`")
.font(.sybil(.footnote))
.foregroundStyle(SybilTheme.textMuted)
}
VStack(alignment: .leading, spacing: 8) {
Text("API URL")
.font(.caption.weight(.semibold))
.font(.sybil(.caption, weight: .semibold))
.foregroundStyle(SybilTheme.textMuted)
TextField("http://127.0.0.1:8787/api", text: $settings.apiBaseURL)
TextField("http://127.0.0.1:8787", text: $settings.apiBaseURL)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.keyboardType(.URL)
@@ -38,7 +38,7 @@ struct SybilSettingsView: View {
)
Text("Admin Token")
.font(.caption.weight(.semibold))
.font(.sybil(.caption, weight: .semibold))
.foregroundStyle(SybilTheme.textMuted)
SecureField("ADMIN_TOKEN (optional in open mode)", text: $settings.adminToken)
@@ -82,19 +82,19 @@ struct SybilSettingsView: View {
if let mode = viewModel.authMode {
Label(mode == "open" ? "Server is in open mode" : "Server requires token", systemImage: "dot.radiowaves.left.and.right")
.font(.footnote)
.font(.sybil(.footnote))
.foregroundStyle(SybilTheme.textMuted)
}
if let authError = viewModel.authError {
Text(authError)
.font(.footnote)
.font(.sybil(.footnote))
.foregroundStyle(SybilTheme.danger)
}
if let runtimeError = viewModel.errorMessage {
Text(runtimeError)
.font(.footnote)
.font(.sybil(.footnote))
.foregroundStyle(SybilTheme.danger)
}
}

View File

@@ -17,27 +17,29 @@ struct SybilSidebarView: View {
var body: some View {
VStack(spacing: 0) {
HStack(spacing: 10) {
Button {
viewModel.startNewChat()
} label: {
Label("New chat", systemImage: "plus")
.frame(maxWidth: .infinity)
}
.buttonStyle(.borderedProminent)
.tint(viewModel.draftKind == .chat ? SybilTheme.primary : SybilTheme.primarySoft)
VStack(alignment: .leading, spacing: 14) {
VStack(spacing: 10) {
sidebarActionButton(
title: "New chat",
systemImage: "plus",
isPrimary: true,
isActive: viewModel.draftKind == .chat
) {
viewModel.startNewChat()
}
Button {
viewModel.startNewSearch()
} label: {
Label("New search", systemImage: "magnifyingglass")
.frame(maxWidth: .infinity)
sidebarActionButton(
title: "New search",
systemImage: "magnifyingglass",
isPrimary: false,
isActive: viewModel.draftKind == .search
) {
viewModel.startNewSearch()
}
}
.buttonStyle(.bordered)
.tint(viewModel.draftKind == .search ? SybilTheme.primary : SybilTheme.textMuted)
}
.padding(.horizontal, 12)
.padding(.top, 12)
.padding(.top, 18)
.padding(.bottom, 10)
Divider()
@@ -45,7 +47,7 @@ struct SybilSidebarView: View {
if let errorMessage = viewModel.errorMessage {
Text(errorMessage)
.font(.footnote)
.font(.sybil(.footnote))
.foregroundStyle(SybilTheme.danger)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 12)
@@ -60,7 +62,7 @@ struct SybilSidebarView: View {
ProgressView()
.tint(SybilTheme.primary)
Text("Loading conversations…")
.font(.footnote)
.font(.sybil(.footnote))
.foregroundStyle(SybilTheme.textMuted)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
@@ -68,10 +70,10 @@ struct SybilSidebarView: View {
} else if viewModel.sidebarItems.isEmpty {
VStack(spacing: 10) {
Image(systemName: "message.badge")
.font(.title3)
.font(.system(size: 20, weight: .medium))
.foregroundStyle(SybilTheme.textMuted)
Text("Start a chat or run your first search.")
.font(.footnote)
.font(.sybil(.footnote))
.multilineTextAlignment(.center)
.foregroundStyle(SybilTheme.textMuted)
}
@@ -87,24 +89,36 @@ struct SybilSidebarView: View {
VStack(alignment: .leading, spacing: 6) {
HStack(spacing: 8) {
Image(systemName: iconName(for: item))
.font(.caption.weight(.semibold))
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(isSelected(item) ? SybilTheme.accent : SybilTheme.textMuted)
.frame(width: 22, height: 22)
.background(
RoundedRectangle(cornerRadius: 7)
.fill(isSelected(item) ? SybilTheme.accent.opacity(0.12) : SybilTheme.surface.opacity(0.72))
.overlay(
RoundedRectangle(cornerRadius: 7)
.stroke(isSelected(item) ? SybilTheme.accent.opacity(0.36) : SybilTheme.border.opacity(0.72), lineWidth: 1)
)
)
Text(item.title)
.font(.subheadline.weight(.medium))
.font(.sybil(.subheadline, weight: .semibold))
.lineLimit(1)
}
HStack(spacing: 8) {
Text(item.updatedAt.sybilRelativeLabel)
.font(.caption2)
.font(.sybil(.caption2))
.foregroundStyle(SybilTheme.textMuted)
if let initiated = item.initiatedLabel {
Spacer(minLength: 0)
Text(initiated)
.font(.caption2)
.font(.sybil(.caption2))
.foregroundStyle(SybilTheme.textMuted.opacity(0.88))
.lineLimit(1)
.multilineTextAlignment(.trailing)
.frame(maxWidth: .infinity, alignment: .trailing)
}
}
}
@@ -114,7 +128,7 @@ struct SybilSidebarView: View {
.frame(maxWidth: .infinity, alignment: .leading)
.background(
RoundedRectangle(cornerRadius: 12)
.fill(isSelected(item) ? SybilTheme.primary.opacity(0.28) : SybilTheme.surface.opacity(0.4))
.fill(isSelected(item) ? SybilTheme.selectedRowGradient : LinearGradient(colors: [SybilTheme.surface.opacity(0.56), SybilTheme.surface.opacity(0.36)], startPoint: .topLeading, endPoint: .bottomTrailing))
)
.overlay(
RoundedRectangle(cornerRadius: 12)
@@ -135,28 +149,57 @@ struct SybilSidebarView: View {
}
.padding(10)
}
.refreshable {
await viewModel.refreshCollectionsFromUser()
}
.tint(SybilTheme.primary)
}
Divider()
.overlay(SybilTheme.border)
Button {
viewModel.openSettings()
} label: {
Label("Settings", systemImage: "gearshape")
.font(.subheadline.weight(.medium))
.foregroundStyle(SybilTheme.text)
.padding(.horizontal, 12)
.padding(.vertical, 10)
.frame(maxWidth: .infinity, alignment: .leading)
.background(
RoundedRectangle(cornerRadius: 12)
.fill(viewModel.selectedItem == .settings ? SybilTheme.primary.opacity(0.28) : Color.clear)
)
}
.buttonStyle(.plain)
.padding(10)
}
.background(SybilTheme.surfaceStrong.opacity(0.84))
.background(SybilTheme.panelGradient)
.navigationTitle("")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .topBarLeading) {
SybilWordmark(size: 18)
}
ToolbarItem(placement: .topBarTrailing) {
Button {
viewModel.openSettings()
} label: {
Image(systemName: viewModel.selectedItem == .settings ? "gearshape.fill" : "gearshape")
.font(.system(size: 16, weight: .semibold))
.foregroundStyle(viewModel.selectedItem == .settings ? SybilTheme.primary : SybilTheme.textMuted)
}
.accessibilityLabel("Settings")
}
}
}
private func sidebarActionButton(
title: String,
systemImage: String,
isPrimary: Bool,
isActive: Bool,
action: @escaping () -> Void
) -> some View {
Button(action: action) {
Label(title, systemImage: systemImage)
.font(.sybil(.subheadline, weight: .semibold))
.foregroundStyle(isPrimary ? SybilTheme.text : SybilTheme.text.opacity(0.92))
.padding(.horizontal, 13)
.padding(.vertical, 11)
.frame(maxWidth: .infinity, alignment: .leading)
.background(
RoundedRectangle(cornerRadius: 11)
.fill(isPrimary ? SybilTheme.primaryGradient : LinearGradient(colors: [SybilTheme.surface.opacity(0.86), SybilTheme.surface.opacity(0.62)], startPoint: .topLeading, endPoint: .bottomTrailing))
)
.overlay(
RoundedRectangle(cornerRadius: 11)
.stroke(isActive ? SybilTheme.primary.opacity(0.70) : SybilTheme.border.opacity(isPrimary ? 0.28 : 0.72), lineWidth: 1)
)
}
.buttonStyle(.plain)
}
}

View File

@@ -1,28 +1,212 @@
import CoreText
import Foundation
import SwiftUI
import UIKit
enum SybilFontRegistry {
static func registerIfNeeded() {
_ = registeredFonts
}
private static let registeredFonts: Void = {
for fontName in ["Inter", "Orbitron"] {
guard let url = Bundle.main.url(forResource: fontName, withExtension: "ttf", subdirectory: "Fonts") ??
Bundle.main.url(forResource: fontName, withExtension: "ttf")
else {
continue
}
CTFontManagerRegisterFontsForURL(url as CFURL, .process, nil)
}
}()
}
extension Font {
static func sybil(_ textStyle: Font.TextStyle, weight: Font.Weight = .regular) -> Font {
SybilFontRegistry.registerIfNeeded()
return .custom("Inter", size: Self.sybilPointSize(for: textStyle), relativeTo: textStyle)
.weight(weight)
}
static func sybil(size: CGFloat, weight: Font.Weight = .regular) -> Font {
SybilFontRegistry.registerIfNeeded()
return .custom("Inter", size: size)
.weight(weight)
}
private static func sybilPointSize(for textStyle: Font.TextStyle) -> CGFloat {
switch textStyle {
case .largeTitle:
return 34
case .title:
return 28
case .title2:
return 22
case .title3:
return 20
case .headline:
return 17
case .subheadline:
return 15
case .callout:
return 16
case .caption:
return 12
case .caption2:
return 11
case .footnote:
return 13
case .body:
return 17
@unknown default:
return 17
}
}
}
enum SybilTheme {
static let background = Color(red: 0.07, green: 0.05, blue: 0.11)
static let surface = Color(red: 0.14, green: 0.09, blue: 0.19)
static let surfaceStrong = Color(red: 0.17, green: 0.10, blue: 0.23)
static let card = Color(red: 0.12, green: 0.08, blue: 0.17)
static let border = Color(red: 0.30, green: 0.22, blue: 0.39)
static let primary = Color(red: 0.66, green: 0.47, blue: 0.94)
static let primarySoft = Color(red: 0.53, green: 0.37, blue: 0.78)
static let text = Color(red: 0.95, green: 0.91, blue: 0.98)
static let textMuted = Color(red: 0.72, green: 0.65, blue: 0.80)
static let searchCard = Color(red: 0.16, green: 0.10, blue: 0.22)
static let userBubble = Color(red: 0.35, green: 0.20, blue: 0.62)
static let danger = Color(red: 0.93, green: 0.38, blue: 0.42)
static let background = Color(red: 0.02, green: 0.02, blue: 0.05)
static let surface = Color(red: 0.05, green: 0.04, blue: 0.10)
static let surfaceStrong = Color(red: 0.07, green: 0.06, blue: 0.14)
static let card = Color(red: 0.06, green: 0.05, blue: 0.12)
static let border = Color(red: 0.24, green: 0.20, blue: 0.38)
static let primary = Color(red: 0.57, green: 0.38, blue: 0.96)
static let primarySoft = Color(red: 0.43, green: 0.25, blue: 0.76)
static let accent = Color(red: 0.31, green: 0.88, blue: 0.95)
static let text = Color(red: 0.96, green: 0.94, blue: 1.0)
static let textMuted = Color(red: 0.65, green: 0.62, blue: 0.76)
static let searchCard = Color(red: 0.07, green: 0.06, blue: 0.14)
static let userBubble = Color(red: 0.29, green: 0.13, blue: 0.65)
static let danger = Color(red: 0.96, green: 0.32, blue: 0.40)
@MainActor static func applySystemAppearance() {
let navAppearance = UINavigationBarAppearance()
navAppearance.configureWithOpaqueBackground()
navAppearance.backgroundColor = UIColor(red: 0.02, green: 0.02, blue: 0.05, alpha: 1)
navAppearance.shadowColor = UIColor(red: 0.24, green: 0.20, blue: 0.38, alpha: 0.9)
navAppearance.titleTextAttributes = [
.foregroundColor: UIColor(red: 0.96, green: 0.94, blue: 1.0, alpha: 1)
]
navAppearance.largeTitleTextAttributes = navAppearance.titleTextAttributes
UINavigationBar.appearance().prefersLargeTitles = false
UINavigationBar.appearance().standardAppearance = navAppearance
UINavigationBar.appearance().compactAppearance = navAppearance
UINavigationBar.appearance().scrollEdgeAppearance = navAppearance
UINavigationBar.appearance().compactScrollEdgeAppearance = navAppearance
}
static var backgroundGradient: LinearGradient {
LinearGradient(
colors: [
Color(red: 0.27, green: 0.12, blue: 0.36),
Color(red: 0.15, green: 0.09, blue: 0.23),
Color(red: 0.07, green: 0.05, blue: 0.11)
Color(red: 0.12, green: 0.08, blue: 0.28),
Color(red: 0.04, green: 0.03, blue: 0.09),
background
],
startPoint: .top,
endPoint: .bottom
)
}
static var brandGradient: LinearGradient {
LinearGradient(
colors: [
Color(red: 1.0, green: 0.55, blue: 0.97),
Color(red: 0.60, green: 0.43, blue: 1.0),
Color(red: 0.40, green: 0.87, blue: 1.0)
],
startPoint: .leading,
endPoint: .trailing
)
}
static var panelGradient: LinearGradient {
LinearGradient(
colors: [
Color(red: 0.07, green: 0.06, blue: 0.15).opacity(0.94),
Color(red: 0.03, green: 0.03, blue: 0.08).opacity(0.96)
],
startPoint: .top,
endPoint: .bottom
)
}
static var primaryGradient: LinearGradient {
LinearGradient(
colors: [
Color(red: 0.43, green: 0.27, blue: 0.92),
Color(red: 0.45, green: 0.09, blue: 0.63)
],
startPoint: .topLeading,
endPoint: .bottomTrailing
)
}
static var selectedRowGradient: LinearGradient {
LinearGradient(
colors: [
primary.opacity(0.56),
primarySoft.opacity(0.48)
],
startPoint: .topLeading,
endPoint: .bottomTrailing
)
}
static var userBubbleGradient: LinearGradient {
LinearGradient(
colors: [
Color(red: 0.38, green: 0.16, blue: 0.80),
Color(red: 0.25, green: 0.08, blue: 0.55)
],
startPoint: .topLeading,
endPoint: .bottomTrailing
)
}
static var composerGradient: LinearGradient {
LinearGradient(
colors: [
Color(red: 0.04, green: 0.04, blue: 0.10).opacity(0.98),
Color(red: 0.09, green: 0.06, blue: 0.16).opacity(0.94)
],
startPoint: .topLeading,
endPoint: .bottomTrailing
)
}
static var toolCallGradient: LinearGradient {
LinearGradient(
colors: [
Color(red: 0.01, green: 0.15, blue: 0.17).opacity(0.70),
Color(red: 0.03, green: 0.09, blue: 0.15).opacity(0.78)
],
startPoint: .leading,
endPoint: .trailing
)
}
static var failedToolCallGradient: LinearGradient {
LinearGradient(
colors: [
danger.opacity(0.18),
Color(red: 0.15, green: 0.03, blue: 0.07).opacity(0.72)
],
startPoint: .leading,
endPoint: .trailing
)
}
}
struct SybilWordmark: View {
var size: CGFloat = 30
var body: some View {
Text("SYBIL")
.font(.custom("Orbitron", size: size))
.fontWeight(.black)
.tracking(0)
.foregroundStyle(SybilTheme.brandGradient)
.accessibilityLabel("Sybil")
}
}

View File

@@ -87,16 +87,24 @@ final class SybilViewModel {
var isLoadingCollections = false
var isLoadingSelection = false
var isSending = false
var isCreatingSearchChat = false
var errorMessage: String?
var composer = ""
var composerAttachments: [ChatAttachment] = []
var provider: Provider
var modelCatalog: [Provider: ProviderModelInfo] = [:]
var model: String
@ObservationIgnored
private var hasBootstrapped = false
private var pendingChatState: PendingChatState?
@ObservationIgnored
private var selectionTask: Task<Void, Never>?
@ObservationIgnored
private var chatBackgroundTask: SybilBackgroundTaskAssertion?
@ObservationIgnored
private let clientFactory: (APIConfiguration) -> any SybilAPIClienting
private let fallbackModels: [Provider: [String]] = [
.openai: ["gpt-4.1-mini"],
@@ -104,18 +112,28 @@ final class SybilViewModel {
.xai: ["grok-3-mini"]
]
init(settings: SybilSettingsStore = SybilSettingsStore()) {
init(
settings: SybilSettingsStore = SybilSettingsStore(),
clientFactory: @escaping (APIConfiguration) -> any SybilAPIClienting = { configuration in
SybilAPIClient(configuration: configuration)
}
) {
self.settings = settings
self.clientFactory = clientFactory
self.provider = settings.preferredProvider
self.model = settings.preferredModelByProvider[settings.preferredProvider] ?? "gpt-4.1-mini"
}
var providerModelOptions: [String] {
let serverModels = modelCatalog[provider]?.models ?? []
modelOptions(for: provider)
}
func modelOptions(for candidate: Provider) -> [String] {
let serverModels = modelCatalog[candidate]?.models ?? []
if !serverModels.isEmpty {
return serverModels
}
return fallbackModels[provider] ?? []
return fallbackModels[candidate] ?? []
}
var selectedTitle: String {
@@ -197,21 +215,34 @@ final class SybilViewModel {
return draftKind != nil || selectedItem != nil
}
var canSendComposer: Bool {
if isSending {
return false
}
let content = composer.trimmingCharacters(in: .whitespacesAndNewlines)
if isSearchMode {
return !content.isEmpty
}
return !content.isEmpty || !composerAttachments.isEmpty
}
var displayedMessages: [Message] {
let canonical = selectedChat?.messages ?? []
let canonical = displayableMessages(selectedChat?.messages ?? [])
guard let pending = pendingChatState else {
return canonical
}
if let pendingID = pending.chatID {
if case let .chat(selectedID) = selectedItem, selectedID == pendingID {
return pending.messages
return displayableMessages(pending.messages)
}
return canonical
}
if draftKind == .chat {
return pending.messages
return displayableMessages(pending.messages)
}
return canonical
@@ -222,7 +253,7 @@ final class SybilViewModel {
let initiatedLabel: String?
if let model = chat.initiatedModel?.trimmingCharacters(in: .whitespacesAndNewlines), !model.isEmpty {
if let provider = chat.initiatedProvider {
initiatedLabel = "\(provider.displayName) · \(model)"
initiatedLabel = "\(provider.displayName) \(model)"
} else {
initiatedLabel = model
}
@@ -262,6 +293,19 @@ final class SybilViewModel {
return searches.first(where: { $0.id == searchID })
}
var hasRefreshableSelection: Bool {
guard draftKind == nil, let selectedItem else {
return false
}
switch selectedItem {
case .chat, .search:
return true
case .settings:
return false
}
}
func bootstrap() async {
guard !hasBootstrapped else {
return
@@ -277,6 +321,7 @@ final class SybilViewModel {
authError = nil
errorMessage = nil
pendingChatState = nil
composerAttachments = []
settings.persist()
SybilLog.info(
@@ -336,6 +381,15 @@ final class SybilViewModel {
SybilLog.info(SybilLog.ui, "Model changed to \(nextModel)")
}
func setProvider(_ nextProvider: Provider, model nextModel: String) {
provider = nextProvider
model = nextModel
settings.preferredProvider = nextProvider
settings.preferredModelByProvider[nextProvider] = nextModel
settings.persist()
SybilLog.info(SybilLog.ui, "Provider changed to \(nextProvider.rawValue), model=\(nextModel)")
}
func startNewChat() {
SybilLog.debug(SybilLog.ui, "Starting draft chat")
draftKind = .chat
@@ -344,6 +398,7 @@ final class SybilViewModel {
selectedSearch = nil
errorMessage = nil
composer = ""
composerAttachments = []
}
func startNewSearch() {
@@ -354,6 +409,7 @@ final class SybilViewModel {
selectedSearch = nil
errorMessage = nil
composer = ""
composerAttachments = []
}
func openSettings() {
@@ -363,6 +419,7 @@ final class SybilViewModel {
selectedChat = nil
selectedSearch = nil
errorMessage = nil
composerAttachments = []
}
func select(_ selection: SidebarSelection) {
@@ -370,6 +427,9 @@ final class SybilViewModel {
draftKind = nil
selectedItem = selection
errorMessage = nil
if case .search = selection {
composerAttachments = []
}
if case .settings = selection {
selectedChat = nil
@@ -383,6 +443,62 @@ final class SybilViewModel {
}
}
func selectPreviousSidebarItem() {
selectAdjacentSidebarItem(offset: -1)
}
func selectNextSidebarItem() {
selectAdjacentSidebarItem(offset: 1)
}
private func selectAdjacentSidebarItem(offset: Int) {
let items = sidebarItems
guard !items.isEmpty else {
return
}
let currentIndex = selectedItem.flatMap { selection in
items.firstIndex { $0.selection == selection }
}
let startingIndex = currentIndex ?? (offset < 0 ? items.count : -1)
let nextIndex = (startingIndex + offset + items.count) % items.count
let nextSelection = items[nextIndex].selection
guard draftKind != nil || selectedItem != nextSelection else {
return
}
select(nextSelection)
}
func refreshCollectionsFromUser() async {
guard isAuthenticated else {
return
}
errorMessage = nil
guard draftKind == nil else {
await refreshCollectionsPreservingDraft()
return
}
await refreshCollections(preferredSelection: selectedItem)
}
func refreshSelectionFromUser() async {
guard isAuthenticated, !isSending, !isCreatingSearchChat else {
return
}
guard selectedItem != nil, draftKind == nil else {
return
}
errorMessage = nil
await refreshSelectionIfNeeded()
}
func deleteItem(_ selection: SidebarSelection) async {
guard isAuthenticated else {
return
@@ -414,13 +530,46 @@ final class SybilViewModel {
await reconnect()
}
func refreshVisibleContent(refreshCollections shouldRefreshCollections: Bool, refreshSelection shouldRefreshSelection: Bool) async {
guard isAuthenticated, !isCheckingSession else {
return
}
guard shouldRefreshCollections || shouldRefreshSelection else {
return
}
SybilLog.info(
SybilLog.ui,
"Foreground refresh requested (collections=\(shouldRefreshCollections), selection=\(shouldRefreshSelection))"
)
if shouldRefreshCollections {
await refreshCollections(preferredSelection: selectedItem, refreshSelection: shouldRefreshSelection)
return
}
if shouldRefreshSelection {
await refreshSelectionIfNeeded()
}
}
func sendComposer() async {
let content = composer.trimmingCharacters(in: .whitespacesAndNewlines)
guard !content.isEmpty, !isSending else {
let attachments = composerAttachments
guard !isSending else {
return
}
if isSearchMode {
guard !content.isEmpty else { return }
} else if content.isEmpty && attachments.isEmpty {
return
}
composer = ""
composerAttachments = []
errorMessage = nil
isSending = true
@@ -430,7 +579,7 @@ final class SybilViewModel {
try await sendSearch(query: content)
} else {
SybilLog.info(SybilLog.ui, "Sending chat prompt")
try await sendChat(content: content)
try await sendChat(content: content, attachments: attachments)
}
} catch {
errorMessage = normalizeAPIError(error)
@@ -454,13 +603,70 @@ final class SybilViewModel {
}
}
pendingChatState = nil
if !isSearchMode {
composer = content
composerAttachments = attachments
pendingChatState = nil
}
}
isSending = false
}
private func loadInitialData(using client: SybilAPIClient) async {
func appendComposerAttachments(_ attachments: [ChatAttachment]) throws {
guard !attachments.isEmpty else {
return
}
guard !isSearchMode else {
errorMessage = "Attachments are only available in chat mode."
return
}
if composerAttachments.count + attachments.count > SybilChatAttachmentSupport.maxAttachmentsPerMessage {
throw ChatAttachmentError.tooManyAttachments(SybilChatAttachmentSupport.maxAttachmentsPerMessage)
}
composerAttachments += attachments
errorMessage = nil
}
func removeComposerAttachment(id: String) {
composerAttachments.removeAll { $0.id == id }
}
func startChatFromSelectedSearch() async {
guard let search = selectedSearch, !isCreatingSearchChat, !isSending else {
return
}
isCreatingSearchChat = true
errorMessage = nil
do {
let client = try client()
let chat = try await client.createChatFromSearch(searchID: search.id, title: nil)
draftKind = nil
pendingChatState = nil
composer = ""
composerAttachments = []
chats.removeAll(where: { $0.id == chat.id })
chats.insert(chat, at: 0)
selectedItem = .chat(chat.id)
selectedSearch = nil
await refreshCollections(preferredSelection: .chat(chat.id))
} catch {
errorMessage = normalizeAPIError(error)
SybilLog.error(SybilLog.ui, "Create chat from search failed", error: error)
}
isCreatingSearchChat = false
}
private func loadInitialData(using client: any SybilAPIClienting) async {
isLoadingCollections = true
errorMessage = nil
@@ -532,7 +738,34 @@ final class SybilViewModel {
settings.persist()
}
private func refreshCollections(preferredSelection: SidebarSelection?) async {
private func refreshCollectionsPreservingDraft() async {
isLoadingCollections = true
do {
let client = try client()
async let chatsValue = client.listChats()
async let searchesValue = client.listSearches()
let (nextChats, nextSearches) = try await (chatsValue, searchesValue)
chats = nextChats
searches = nextSearches
SybilLog.info(
SybilLog.app,
"Refreshed collections for draft: \(nextChats.count) chats, \(nextSearches.count) searches"
)
} catch {
errorMessage = normalizeAPIError(error)
SybilLog.error(SybilLog.app, "Refresh draft collections failed", error: error)
}
isLoadingCollections = false
}
private func refreshCollections(
preferredSelection: SidebarSelection?,
refreshSelection: Bool = true
) async {
isLoadingCollections = true
do {
@@ -564,7 +797,7 @@ final class SybilViewModel {
selectedItem = sidebarItems.first?.selection
}
if selectedItem != nil {
if refreshSelection, selectedItem != nil {
await refreshSelectionIfNeeded()
}
} catch {
@@ -624,13 +857,14 @@ final class SybilViewModel {
selectedSearch = nil
}
private func sendChat(content: String) async throws {
private func sendChat(content: String, attachments: [ChatAttachment]) async throws {
let optimisticUser = Message(
id: "temp-user-\(UUID().uuidString)",
createdAt: Date(),
role: .user,
content: content,
name: nil
name: nil,
metadata: SybilChatAttachmentSupport.metadataValue(for: attachments)
)
let optimisticAssistant = Message(
@@ -650,7 +884,7 @@ final class SybilViewModel {
var chatID = currentChatID
if chatID == nil {
let created = try await client.createChat()
let created = try await client.createChat(title: nil)
chatID = created.id
draftKind = nil
selectedItem = .chat(created.id)
@@ -693,9 +927,11 @@ final class SybilViewModel {
}
let requestMessages: [CompletionRequestMessage] =
baseChat.messages.map {
CompletionRequestMessage(role: $0.role, content: $0.content, name: $0.name)
} + [CompletionRequestMessage(role: .user, content: content)]
baseChat.messages
.filter { !$0.isToolCallLog }
.map {
CompletionRequestMessage(role: $0.role, content: $0.content, name: $0.name, attachments: $0.attachments.isEmpty ? nil : $0.attachments)
} + [CompletionRequestMessage(role: .user, content: content, attachments: attachments.isEmpty ? nil : attachments)]
let streamStatus = CompletionStreamStatus()
@@ -703,7 +939,8 @@ final class SybilViewModel {
Task { [weak self] in
guard let self else { return }
do {
let updated = try await client.suggestChatTitle(chatID: chatID, content: content)
let titleSeed = !content.isEmpty ? content : SybilChatAttachmentSupport.attachmentSummary(attachments)
let updated = try await client.suggestChatTitle(chatID: chatID, content: titleSeed.isEmpty ? "Uploaded files" : titleSeed)
await MainActor.run {
self.chats = self.chats.map { existing in
if existing.id == updated.id {
@@ -723,6 +960,15 @@ final class SybilViewModel {
}
}
chatBackgroundTask?.end()
chatBackgroundTask = SybilBackgroundTaskAssertion(name: "Sybil Chat Response") {
SybilLog.warning(SybilLog.app, "Chat response background time expired")
}
defer {
chatBackgroundTask?.end()
chatBackgroundTask = nil
}
try await client.runCompletionStream(
body: CompletionStreamRequest(
chatId: chatID,
@@ -749,6 +995,9 @@ final class SybilViewModel {
case let .meta(payload):
pendingChatState?.chatID = payload.chatId
case let .toolCall(payload):
insertPendingToolCallMessage(payload)
case let .delta(payload):
guard !payload.text.isEmpty else { return }
mutatePendingAssistantMessage { existing in
@@ -880,6 +1129,51 @@ final class SybilViewModel {
pendingChatState = pending
}
private func insertPendingToolCallMessage(_ payload: CompletionStreamToolCall) {
guard var pending = pendingChatState else {
return
}
if pending.messages.contains(where: { $0.toolCallMetadata?.toolCallId == payload.toolCallId }) {
return
}
let metadata: JSONValue = .object([
"kind": .string("tool_call"),
"toolCallId": .string(payload.toolCallId),
"toolName": .string(payload.name),
"status": .string(payload.status),
"summary": .string(payload.summary),
"args": .object(payload.args),
"startedAt": .string(payload.startedAt),
"completedAt": .string(payload.completedAt),
"durationMs": .number(Double(payload.durationMs)),
"error": payload.error.map { .string($0) } ?? .null,
"resultPreview": payload.resultPreview.map { .string($0) } ?? .null
])
let summary = payload.summary.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
? "Ran tool '\(payload.name)'."
: payload.summary
let message = Message(
id: "temp-tool-\(payload.toolCallId)",
createdAt: Date(),
role: .tool,
content: summary,
name: payload.name,
metadata: metadata
)
if let assistantIndex = pending.messages.indices.last(where: { pending.messages[$0].id.hasPrefix("temp-assistant-") }) {
pending.messages.insert(message, at: assistantIndex)
} else {
pending.messages.append(message)
}
pendingChatState = pending
}
private var currentChatID: String? {
if draftKind == .chat {
return nil
@@ -911,6 +1205,10 @@ final class SybilViewModel {
}
}
private func displayableMessages(_ messages: [Message]) -> [Message] {
messages.filter { $0.role != .system }
}
private func chatTitle(title: String?, messages: [Message]?) -> String {
if let title = title?.trimmingCharacters(in: .whitespacesAndNewlines), !title.isEmpty {
return title
@@ -921,6 +1219,13 @@ final class SybilViewModel {
return String(firstUserMessage.prefix(48))
}
if let firstUserMessage = messages?.first(where: { $0.role == .user }) {
let attachmentSummary = SybilChatAttachmentSupport.attachmentSummary(firstUserMessage.attachments)
if !attachmentSummary.isEmpty {
return String(attachmentSummary.prefix(48))
}
}
return "New chat"
}
@@ -1007,7 +1312,7 @@ final class SybilViewModel {
return false
}
private func client() throws -> SybilAPIClient {
private func client() throws -> any SybilAPIClienting {
guard let baseURL = settings.normalizedAPIBaseURL else {
throw APIError.invalidBaseURL
}
@@ -1017,8 +1322,8 @@ final class SybilViewModel {
"Creating API client for \(baseURL.absoluteString) (token: \(settings.trimmedTokenOrNil == nil ? "none" : "set"))"
)
return SybilAPIClient(
configuration: APIConfiguration(
return clientFactory(
APIConfiguration(
baseURL: baseURL,
authToken: settings.trimmedTokenOrNil
)

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,286 @@
import CoreGraphics
import Foundation
import Testing
@testable import Sybil
@Test func example() async throws {
// Write your test here and use APIs like `#expect(...)` to check expected conditions.
private struct MockClientCallSnapshot: Sendable {
var listChats = 0
var listSearches = 0
var getChat = 0
var getSearch = 0
}
private struct UnexpectedClientCall: Error {}
private actor MockSybilClient: SybilAPIClienting {
private let chatsResponse: [ChatSummary]
private let searchesResponse: [SearchSummary]
private let chatDetails: [String: ChatDetail]
private let searchDetails: [String: SearchDetail]
private var snapshot = MockClientCallSnapshot()
init(
chatsResponse: [ChatSummary] = [],
searchesResponse: [SearchSummary] = [],
chatDetails: [String: ChatDetail] = [:],
searchDetails: [String: SearchDetail] = [:]
) {
self.chatsResponse = chatsResponse
self.searchesResponse = searchesResponse
self.chatDetails = chatDetails
self.searchDetails = searchDetails
}
func currentSnapshot() -> MockClientCallSnapshot {
snapshot
}
func verifySession() async throws -> AuthSession {
AuthSession(authenticated: true, mode: "open")
}
func listChats() async throws -> [ChatSummary] {
snapshot.listChats += 1
return chatsResponse
}
func createChat(title: String?) async throws -> ChatSummary {
throw UnexpectedClientCall()
}
func getChat(chatID: String) async throws -> ChatDetail {
snapshot.getChat += 1
guard let detail = chatDetails[chatID] else {
throw UnexpectedClientCall()
}
return detail
}
func deleteChat(chatID: String) async throws {
throw UnexpectedClientCall()
}
func suggestChatTitle(chatID: String, content: String) async throws -> ChatSummary {
throw UnexpectedClientCall()
}
func listSearches() async throws -> [SearchSummary] {
snapshot.listSearches += 1
return searchesResponse
}
func createSearch(title: String?, query: String?) async throws -> SearchSummary {
throw UnexpectedClientCall()
}
func getSearch(searchID: String) async throws -> SearchDetail {
snapshot.getSearch += 1
guard let detail = searchDetails[searchID] else {
throw UnexpectedClientCall()
}
return detail
}
func createChatFromSearch(searchID: String, title: String?) async throws -> ChatSummary {
throw UnexpectedClientCall()
}
func deleteSearch(searchID: String) async throws {
throw UnexpectedClientCall()
}
func listModels() async throws -> ModelCatalogResponse {
ModelCatalogResponse(providers: [:])
}
func runCompletionStream(
body: CompletionStreamRequest,
onEvent: @escaping @Sendable (CompletionStreamEvent) async -> Void
) async throws {
throw UnexpectedClientCall()
}
func runSearchStream(
searchID: String,
body: SearchRunRequest,
onEvent: @escaping @Sendable (SearchStreamEvent) async -> Void
) async throws {
throw UnexpectedClientCall()
}
}
@MainActor
private func testSettings(named name: String) -> SybilSettingsStore {
let defaults = UserDefaults(suiteName: name)!
defaults.removePersistentDomain(forName: name)
let settings = SybilSettingsStore(defaults: defaults)
settings.apiBaseURL = "http://127.0.0.1:8787"
return settings
}
private func makeChatSummary(id: String, date: Date) -> ChatSummary {
ChatSummary(
id: id,
title: "Chat \(id)",
createdAt: date,
updatedAt: date,
initiatedProvider: .openai,
initiatedModel: "gpt-4.1-mini",
lastUsedProvider: .openai,
lastUsedModel: "gpt-4.1-mini"
)
}
private func makeChatDetail(id: String, date: Date, body: String) -> ChatDetail {
ChatDetail(
id: id,
title: "Chat \(id)",
createdAt: date,
updatedAt: date,
initiatedProvider: .openai,
initiatedModel: "gpt-4.1-mini",
lastUsedProvider: .openai,
lastUsedModel: "gpt-4.1-mini",
messages: [
Message(
id: "message-\(id)",
createdAt: date,
role: .assistant,
content: body,
name: nil
)
]
)
}
private func makeSearchSummary(id: String, date: Date) -> SearchSummary {
SearchSummary(
id: id,
title: "Search \(id)",
query: "query-\(id)",
createdAt: date,
updatedAt: date
)
}
private func makeSearchDetail(id: String, date: Date, answer: String) -> SearchDetail {
SearchDetail(
id: id,
title: "Search \(id)",
query: "query-\(id)",
createdAt: date,
updatedAt: date,
requestId: "request-\(id)",
latencyMs: 42,
error: nil,
answerText: answer,
answerRequestId: "answer-\(id)",
answerCitations: [],
answerError: nil,
results: []
)
}
@MainActor
@Test func normalizedAPIBaseURLPreservesExplicitAPIPath() async throws {
let defaults = UserDefaults(suiteName: #function)!
defaults.removePersistentDomain(forName: #function)
let settings = SybilSettingsStore(defaults: defaults)
settings.apiBaseURL = "https://sybil.bajor.cloud/api/"
#expect(settings.normalizedAPIBaseURL?.absoluteString == "https://sybil.bajor.cloud/api")
}
@MainActor
@Test func normalizedAPIBaseURLTrimsWhitespaceAndTrailingSlashes() async throws {
let defaults = UserDefaults(suiteName: #function)!
defaults.removePersistentDomain(forName: #function)
let settings = SybilSettingsStore(defaults: defaults)
settings.apiBaseURL = " http://127.0.0.1:8787/// "
#expect(settings.normalizedAPIBaseURL?.absoluteString == "http://127.0.0.1:8787")
}
@MainActor
@Test func foregroundListRefreshDoesNotReloadHiddenSelection() async throws {
let date = Date(timeIntervalSince1970: 1_700_000_000)
let chat = makeChatSummary(id: "chat-1", date: date)
let search = makeSearchSummary(id: "search-1", date: date)
let client = MockSybilClient(
chatsResponse: [chat],
searchesResponse: [search],
chatDetails: ["chat-1": makeChatDetail(id: "chat-1", date: date, body: "fresh chat body")]
)
let viewModel = SybilViewModel(settings: testSettings(named: #function)) { _ in client }
viewModel.isAuthenticated = true
viewModel.isCheckingSession = false
viewModel.selectedItem = .chat("chat-1")
await viewModel.refreshVisibleContent(refreshCollections: true, refreshSelection: false)
let snapshot = await client.currentSnapshot()
#expect(snapshot.listChats == 1)
#expect(snapshot.listSearches == 1)
#expect(snapshot.getChat == 0)
#expect(snapshot.getSearch == 0)
#expect(viewModel.selectedItem == .chat("chat-1"))
}
@MainActor
@Test func foregroundChatRefreshReloadsSelectedTranscript() async throws {
let date = Date(timeIntervalSince1970: 1_700_000_100)
let detail = makeChatDetail(id: "chat-2", date: date, body: "refreshed transcript")
let client = MockSybilClient(chatDetails: ["chat-2": detail])
let viewModel = SybilViewModel(settings: testSettings(named: #function)) { _ in client }
viewModel.isAuthenticated = true
viewModel.isCheckingSession = false
viewModel.selectedItem = .chat("chat-2")
await viewModel.refreshVisibleContent(refreshCollections: false, refreshSelection: true)
let snapshot = await client.currentSnapshot()
#expect(snapshot.listChats == 0)
#expect(snapshot.listSearches == 0)
#expect(snapshot.getChat == 1)
#expect(viewModel.selectedChat?.messages.first?.content == "refreshed transcript")
}
@MainActor
@Test func foregroundSearchRefreshReloadsSelectedSearch() async throws {
let date = Date(timeIntervalSince1970: 1_700_000_200)
let detail = makeSearchDetail(id: "search-2", date: date, answer: "fresh answer")
let client = MockSybilClient(searchDetails: ["search-2": detail])
let viewModel = SybilViewModel(settings: testSettings(named: #function)) { _ in client }
viewModel.isAuthenticated = true
viewModel.isCheckingSession = false
viewModel.selectedItem = .search("search-2")
await viewModel.refreshVisibleContent(refreshCollections: false, refreshSelection: true)
let snapshot = await client.currentSnapshot()
#expect(snapshot.listChats == 0)
#expect(snapshot.listSearches == 0)
#expect(snapshot.getSearch == 1)
#expect(viewModel.selectedSearch?.answerText == "fresh answer")
}
@Test func newChatSwipeMetricsClampProgressAndLatch() async throws {
let width: CGFloat = 390
let maxTravel = NewChatSwipeMetrics.maxTravel(for: width)
let latchDistance = NewChatSwipeMetrics.latchDistance(for: width)
#expect(NewChatSwipeMetrics.clampedOffset(for: -500, width: width) == -maxTravel)
#expect(NewChatSwipeMetrics.progress(for: -maxTravel / 2, width: width) == 0.5)
#expect(NewChatSwipeMetrics.blurRadius(for: -maxTravel, width: width) == 10)
#expect(NewChatSwipeMetrics.isLatched(offset: -(latchDistance + 1), width: width))
#expect(!NewChatSwipeMetrics.isLatched(offset: -(latchDistance - 1), width: width))
#expect(NewChatSwipeMetrics.isLatched(offset: -(latchDistance - 1), width: width, isCurrentlyLatched: true))
#expect(!NewChatSwipeMetrics.isLatched(offset: -(NewChatSwipeMetrics.latchReleaseDistance(for: width) - 1), width: width, isCurrentlyLatched: true))
#expect(NewChatSwipeMetrics.shouldBeginPan(leftwardTravel: 24, verticalTravel: 8, leftwardVelocity: 0, verticalVelocity: 0))
#expect(NewChatSwipeMetrics.shouldBeginPan(leftwardTravel: 2, verticalTravel: 1, leftwardVelocity: 120, verticalVelocity: 30))
#expect(!NewChatSwipeMetrics.shouldBeginPan(leftwardTravel: 8, verticalTravel: 24, leftwardVelocity: 20, verticalVelocity: 140))
#expect(!NewChatSwipeMetrics.shouldBeginPan(leftwardTravel: 18, verticalTravel: 18, leftwardVelocity: 80, verticalVelocity: 90))
}

View File

@@ -1,7 +1,7 @@
# Sybil Server
Backend API for:
- LLM multiplexer (OpenAI / Anthropic / xAI (Grok))
- LLM multiplexer (OpenAI Responses / Anthropic / xAI Chat Completions-compatible Grok)
- Personal chat database (chats/messages + LLM call log)
## Stack
@@ -44,6 +44,19 @@ If `ADMIN_TOKEN` is not set, the server runs in open mode (dev).
- `ANTHROPIC_API_KEY`
- `XAI_API_KEY`
- `EXA_API_KEY`
- `CHAT_WEB_SEARCH_ENGINE` (`exa` by default, or `searxng` for chat tool calls only)
- `SEARXNG_BASE_URL` (required when `CHAT_WEB_SEARCH_ENGINE=searxng`; instance must allow `format=json`)
- `CHAT_MAX_TOOL_ROUNDS` (`100` by default; maximum model/tool result cycles per chat completion)
- `CHAT_CODEX_TOOL_ENABLED` (`false` by default; enables the `codex_exec` chat tool for OpenAI/xAI)
- `CHAT_CODEX_REMOTE_HOST` (required when Codex tool is enabled; SSH host/IP or `user@host`)
- `CHAT_CODEX_REMOTE_USER` (optional SSH user when host does not include one)
- `CHAT_CODEX_REMOTE_PORT` (`22` by default)
- `CHAT_CODEX_REMOTE_WORKDIR` (`/workspace/sybil-codex` by default; created and reused on the devbox)
- `CHAT_CODEX_SSH_KEY_PATH` (recommended: path to a read-only mounted private key)
- `CHAT_CODEX_SSH_PRIVATE_KEY_B64` (optional fallback private key delivery)
- `CHAT_CODEX_EXEC_TIMEOUT_MS` (`600000` by default)
- `CHAT_SHELL_TOOL_ENABLED` (`false` by default; enables the `shell_exec` chat tool for OpenAI/xAI on the same devbox)
- `CHAT_SHELL_EXEC_TIMEOUT_MS` (`120000` by default)
## API
- `GET /health`

168
server/package-lock.json generated
View File

@@ -18,6 +18,7 @@
"dotenv": "^17.2.3",
"exa-js": "^2.4.0",
"fastify": "^5.7.2",
"html-to-text": "^9.0.5",
"openai": "^6.16.0",
"pino-pretty": "^13.1.3",
"prisma": "^6.6.0",
@@ -852,6 +853,19 @@
"@prisma/debug": "6.6.0"
}
},
"node_modules/@selderee/plugin-htmlparser2": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@selderee/plugin-htmlparser2/-/plugin-htmlparser2-0.11.0.tgz",
"integrity": "sha512-P33hHGdldxGabLFjPPpaTxVolMrzrcegejx+0GxjrIb9Zv48D8yAIA/QTDR2dFl7Uz7urX8aX6+5bCZslr+gWQ==",
"license": "MIT",
"dependencies": {
"domhandler": "^5.0.3",
"selderee": "^0.11.0"
},
"funding": {
"url": "https://ko-fi.com/killymxi"
}
},
"node_modules/@types/node": {
"version": "25.0.10",
"resolved": "https://registry.npmjs.org/@types/node/-/node-25.0.10.tgz",
@@ -996,6 +1010,15 @@
}
}
},
"node_modules/deepmerge": {
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz",
"integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
@@ -1014,6 +1037,61 @@
"node": ">=6"
}
},
"node_modules/dom-serializer": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
"integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==",
"license": "MIT",
"dependencies": {
"domelementtype": "^2.3.0",
"domhandler": "^5.0.2",
"entities": "^4.2.0"
},
"funding": {
"url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
}
},
"node_modules/domelementtype": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz",
"integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"license": "BSD-2-Clause"
},
"node_modules/domhandler": {
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz",
"integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==",
"license": "BSD-2-Clause",
"dependencies": {
"domelementtype": "^2.3.0"
},
"engines": {
"node": ">= 4"
},
"funding": {
"url": "https://github.com/fb55/domhandler?sponsor=1"
}
},
"node_modules/domutils": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
"integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==",
"license": "BSD-2-Clause",
"dependencies": {
"dom-serializer": "^2.0.0",
"domelementtype": "^2.3.0",
"domhandler": "^5.0.3"
},
"funding": {
"url": "https://github.com/fb55/domutils?sponsor=1"
}
},
"node_modules/dotenv": {
"version": "17.2.3",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.3.tgz",
@@ -1035,6 +1113,18 @@
"once": "^1.4.0"
}
},
"node_modules/entities": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
"integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=0.12"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/esbuild": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.2.tgz",
@@ -1353,6 +1443,41 @@
"integrity": "sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg==",
"license": "MIT"
},
"node_modules/html-to-text": {
"version": "9.0.5",
"resolved": "https://registry.npmjs.org/html-to-text/-/html-to-text-9.0.5.tgz",
"integrity": "sha512-qY60FjREgVZL03vJU6IfMV4GDjGBIoOyvuFdpBDIX9yTlDw0TjxVBQp+P8NvpdIXNJvfWBTNul7fsAQJq2FNpg==",
"license": "MIT",
"dependencies": {
"@selderee/plugin-htmlparser2": "^0.11.0",
"deepmerge": "^4.3.1",
"dom-serializer": "^2.0.0",
"htmlparser2": "^8.0.2",
"selderee": "^0.11.0"
},
"engines": {
"node": ">=14"
}
},
"node_modules/htmlparser2": {
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.2.tgz",
"integrity": "sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==",
"funding": [
"https://github.com/fb55/htmlparser2?sponsor=1",
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"license": "MIT",
"dependencies": {
"domelementtype": "^2.3.0",
"domhandler": "^5.0.3",
"domutils": "^3.0.1",
"entities": "^4.4.0"
}
},
"node_modules/http-errors": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
@@ -1452,6 +1577,15 @@
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
"license": "MIT"
},
"node_modules/leac": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/leac/-/leac-0.6.0.tgz",
"integrity": "sha512-y+SqErxb8h7nE/fiEX07jsbuhrpO9lL8eca7/Y1nuWV2moNlXhyd59iDGcRf6moVyDMbmTNzL40SUyrFU/yDpg==",
"license": "MIT",
"funding": {
"url": "https://ko-fi.com/killymxi"
}
},
"node_modules/light-my-request": {
"version": "6.6.0",
"resolved": "https://registry.npmjs.org/light-my-request/-/light-my-request-6.6.0.tgz",
@@ -1648,6 +1782,19 @@
"integrity": "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw==",
"license": "MIT"
},
"node_modules/parseley": {
"version": "0.12.1",
"resolved": "https://registry.npmjs.org/parseley/-/parseley-0.12.1.tgz",
"integrity": "sha512-e6qHKe3a9HWr0oMRVDTRhKce+bRO8VGQR3NyVwcjwrbhMmFCX9KszEV35+rn4AdilFAq9VPxP/Fe1wC9Qjd2lw==",
"license": "MIT",
"dependencies": {
"leac": "^0.6.0",
"peberminta": "^0.9.0"
},
"funding": {
"url": "https://ko-fi.com/killymxi"
}
},
"node_modules/path-scurry": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.1.tgz",
@@ -1664,6 +1811,15 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/peberminta": {
"version": "0.9.0",
"resolved": "https://registry.npmjs.org/peberminta/-/peberminta-0.9.0.tgz",
"integrity": "sha512-XIxfHpEuSJbITd1H3EeQwpcZbTLHc+VVr8ANI9t5sit565tsI4/xK3KWTUFE2e6QiangUkh3B0jihzmGnNrRsQ==",
"license": "MIT",
"funding": {
"url": "https://ko-fi.com/killymxi"
}
},
"node_modules/pino": {
"version": "10.3.0",
"resolved": "https://registry.npmjs.org/pino/-/pino-10.3.0.tgz",
@@ -1882,6 +2038,18 @@
],
"license": "BSD-3-Clause"
},
"node_modules/selderee": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/selderee/-/selderee-0.11.0.tgz",
"integrity": "sha512-5TF+l7p4+OsnP8BCCvSyZiSPc4x4//p5uPwK8TCnVPJYRmU2aYKMpOXvw8zM5a5JvuuCGN1jmsMwuU2W02ukfA==",
"license": "MIT",
"dependencies": {
"parseley": "^0.12.0"
},
"funding": {
"url": "https://ko-fi.com/killymxi"
}
},
"node_modules/semver": {
"version": "7.7.3",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",

View File

@@ -11,6 +11,7 @@
"prebuild": "node scripts/ensure-prisma-client.mjs",
"dev": "node ./node_modules/tsx/dist/cli.mjs watch src/index.ts",
"start": "node dist/index.js",
"test": "node --test --import tsx tests/**/*.test.ts",
"build": "node ./node_modules/typescript/bin/tsc -p tsconfig.json",
"prisma:generate": "node ./node_modules/prisma/build/index.js generate",
"db:migrate": "node ./node_modules/prisma/build/index.js migrate dev",
@@ -26,6 +27,7 @@
"dotenv": "^17.2.3",
"exa-js": "^2.4.0",
"fastify": "^5.7.2",
"html-to-text": "^9.0.5",
"openai": "^6.16.0",
"pino-pretty": "^13.1.3",
"prisma": "^6.6.0",

View File

@@ -1,5 +1,52 @@
import path from "node:path";
import { fileURLToPath } from "node:url";
import { config as loadDotenv } from "dotenv";
import { z } from "zod";
import "dotenv/config";
loadDotenv({ quiet: true });
loadDotenv({ path: path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../.env"), quiet: true });
const OptionalUrlSchema = z.preprocess(
(value) => (typeof value === "string" && value.trim() === "" ? undefined : value),
z.string().trim().url().optional()
);
const ChatWebSearchEngineSchema = z.preprocess(
(value) => {
if (typeof value !== "string") return value;
const trimmed = value.trim();
return trimmed ? trimmed.toLowerCase() : undefined;
},
z.enum(["exa", "searxng"]).default("exa")
);
const BooleanFlagSchema = z.preprocess((value) => {
if (typeof value !== "string") return value;
const normalized = value.trim().toLowerCase();
if (!normalized) return undefined;
if (["1", "true", "yes", "on"].includes(normalized)) return true;
if (["0", "false", "no", "off"].includes(normalized)) return false;
return value;
}, z.boolean().default(false));
const OptionalTrimmedStringSchema = z.preprocess(
(value) => (typeof value === "string" && value.trim() === "" ? undefined : value),
z.string().trim().min(1).optional()
);
function defaultedPositiveInt(defaultValue: number) {
return z.preprocess(
(value) => (typeof value === "string" && value.trim() === "" ? undefined : value),
z.coerce.number().int().positive().default(defaultValue)
);
}
function defaultedTrimmedString(defaultValue: string) {
return z.preprocess(
(value) => (typeof value === "string" && value.trim() === "" ? undefined : value),
z.string().trim().min(1).default(defaultValue)
);
}
const EnvSchema = z.object({
PORT: z.coerce.number().int().positive().default(8787),
@@ -13,6 +60,42 @@ const EnvSchema = z.object({
ANTHROPIC_API_KEY: z.string().optional(),
XAI_API_KEY: z.string().optional(),
EXA_API_KEY: z.string().optional(),
// Chat-mode web_search tool configuration. Search mode remains Exa-only for now.
CHAT_WEB_SEARCH_ENGINE: ChatWebSearchEngineSchema,
SEARXNG_BASE_URL: OptionalUrlSchema,
CHAT_MAX_TOOL_ROUNDS: defaultedPositiveInt(100),
// Optional chat-mode Codex tool. When enabled, the server SSHes into a remote
// devbox and runs `codex exec` in a persistent scratch directory there.
CHAT_CODEX_TOOL_ENABLED: BooleanFlagSchema,
CHAT_CODEX_REMOTE_HOST: OptionalTrimmedStringSchema,
CHAT_CODEX_REMOTE_USER: OptionalTrimmedStringSchema,
CHAT_CODEX_REMOTE_PORT: defaultedPositiveInt(22),
CHAT_CODEX_REMOTE_WORKDIR: defaultedTrimmedString("/workspace/sybil-codex"),
CHAT_CODEX_SSH_KEY_PATH: OptionalTrimmedStringSchema,
CHAT_CODEX_SSH_PRIVATE_KEY_B64: OptionalTrimmedStringSchema,
CHAT_CODEX_EXEC_TIMEOUT_MS: defaultedPositiveInt(600_000),
// Optional arbitrary shell tool that runs only on the configured devbox.
CHAT_SHELL_TOOL_ENABLED: BooleanFlagSchema,
CHAT_SHELL_EXEC_TIMEOUT_MS: defaultedPositiveInt(120_000),
}).superRefine((value, ctx) => {
if (value.CHAT_WEB_SEARCH_ENGINE === "searxng" && !value.SEARXNG_BASE_URL) {
ctx.addIssue({
code: "custom",
path: ["SEARXNG_BASE_URL"],
message: "SEARXNG_BASE_URL is required when CHAT_WEB_SEARCH_ENGINE=searxng",
});
}
if ((value.CHAT_CODEX_TOOL_ENABLED || value.CHAT_SHELL_TOOL_ENABLED) && !value.CHAT_CODEX_REMOTE_HOST) {
ctx.addIssue({
code: "custom",
path: ["CHAT_CODEX_REMOTE_HOST"],
message: "CHAT_CODEX_REMOTE_HOST is required when CHAT_CODEX_TOOL_ENABLED=true or CHAT_SHELL_TOOL_ENABLED=true",
});
}
});
export type Env = z.infer<typeof EnvSchema>;

View File

@@ -9,6 +9,7 @@ import { warmModelCatalog } from "./llm/model-catalog.js";
import { registerRoutes } from "./routes.js";
const app = Fastify({
bodyLimit: 32 * 1024 * 1024,
disableRequestLogging: true,
logger: {
transport: {

1356
server/src/llm/chat-tools.ts Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,268 @@
import type { ChatAttachment, ChatImageAttachment, ChatMessage, ChatTextAttachment } from "./types.js";
function escapeAttribute(value: string) {
return value.replace(/"/g, "&quot;");
}
function getImageAttachments(message: ChatMessage) {
return (message.attachments ?? []).filter((attachment): attachment is ChatImageAttachment => attachment.kind === "image");
}
function getTextAttachments(message: ChatMessage) {
return (message.attachments ?? []).filter((attachment): attachment is ChatTextAttachment => attachment.kind === "text");
}
function buildImageSummaryText(attachments: ChatImageAttachment[]) {
if (!attachments.length) return null;
const label = attachments.length === 1 ? "Attached image" : "Attached images";
return `${label}: ${attachments.map((attachment) => attachment.filename).join(", ")}.`;
}
function buildTextAttachmentPrompt(attachment: ChatTextAttachment) {
const truncationNote = attachment.truncated ? ' truncated="true"' : "";
return [
`Attached text file: ${attachment.filename}${attachment.truncated ? " (content truncated)" : ""}`,
`<attached_file filename="${escapeAttribute(attachment.filename)}" mime_type="${escapeAttribute(attachment.mimeType)}"${truncationNote}>`,
attachment.text,
"</attached_file>",
].join("\n");
}
function toOpenAIContent(message: ChatMessage) {
const imageAttachments = getImageAttachments(message);
const textAttachments = getTextAttachments(message);
if (!imageAttachments.length && !textAttachments.length) {
return message.content;
}
const parts: Array<Record<string, unknown>> = [];
for (const attachment of imageAttachments) {
parts.push({
type: "image_url",
image_url: {
url: attachment.dataUrl,
detail: "auto",
},
});
}
const imageSummary = buildImageSummaryText(imageAttachments);
if (imageSummary) {
parts.push({ type: "text", text: imageSummary });
}
for (const attachment of textAttachments) {
parts.push({ type: "text", text: buildTextAttachmentPrompt(attachment) });
}
if (message.content.trim()) {
parts.push({ type: "text", text: message.content });
}
if (parts.length === 1 && parts[0]?.type === "text" && typeof parts[0].text === "string") {
return parts[0].text;
}
return parts;
}
function toOpenAIResponsesContent(message: ChatMessage) {
const imageAttachments = getImageAttachments(message);
const textAttachments = getTextAttachments(message);
if (!imageAttachments.length && !textAttachments.length) {
return message.content;
}
const parts: Array<Record<string, unknown>> = [];
for (const attachment of imageAttachments) {
parts.push({
type: "input_image",
image_url: attachment.dataUrl,
detail: "auto",
});
}
const imageSummary = buildImageSummaryText(imageAttachments);
if (imageSummary) {
parts.push({ type: "input_text", text: imageSummary });
}
for (const attachment of textAttachments) {
parts.push({ type: "input_text", text: buildTextAttachmentPrompt(attachment) });
}
if (message.content.trim()) {
parts.push({ type: "input_text", text: message.content });
}
if (parts.length === 1 && parts[0]?.type === "input_text" && typeof parts[0].text === "string") {
return parts[0].text;
}
return parts;
}
function parseImageDataUrl(attachment: ChatImageAttachment) {
const match = attachment.dataUrl.match(/^data:(image\/(?:png|jpeg));base64,([a-z0-9+/=\s]+)$/i);
if (!match) {
throw new Error(`Invalid image attachment data URL for '${attachment.filename}'.`);
}
const mediaType = match[1].toLowerCase();
if (mediaType !== attachment.mimeType) {
throw new Error(`Image attachment MIME type mismatch for '${attachment.filename}'.`);
}
return {
mediaType,
data: match[2].replace(/\s+/g, ""),
};
}
function toAnthropicContent(message: ChatMessage) {
const imageAttachments = getImageAttachments(message);
const textAttachments = getTextAttachments(message);
if (!imageAttachments.length && !textAttachments.length) {
return message.content;
}
const blocks: Array<Record<string, unknown>> = [];
for (const attachment of imageAttachments) {
const source = parseImageDataUrl(attachment);
blocks.push({
type: "image",
source: {
type: "base64",
media_type: source.mediaType,
data: source.data,
},
});
}
const imageSummary = buildImageSummaryText(imageAttachments);
if (imageSummary) {
blocks.push({ type: "text", text: imageSummary });
}
for (const attachment of textAttachments) {
blocks.push({ type: "text", text: buildTextAttachmentPrompt(attachment) });
}
if (message.content.trim()) {
blocks.push({ type: "text", text: message.content });
}
if (blocks.length === 1 && blocks[0]?.type === "text" && typeof blocks[0].text === "string") {
return blocks[0].text;
}
return blocks;
}
export function buildOpenAIConversationMessage(message: ChatMessage) {
if (message.role === "tool") {
const name = message.name?.trim() || "tool";
return {
role: "user",
content: `Tool output (${name}):\n${message.content}`,
};
}
const out: Record<string, unknown> = {
role: message.role,
content: toOpenAIContent(message),
};
if (message.name && (message.role === "assistant" || message.role === "user")) {
out.name = message.name;
}
return out;
}
export function buildOpenAIResponsesInputMessage(message: ChatMessage) {
if (message.role === "tool") {
const name = message.name?.trim() || "tool";
return {
role: "user",
content: `Tool output (${name}):\n${message.content}`,
};
}
return {
role: message.role,
content: toOpenAIResponsesContent(message),
};
}
const ANTHROPIC_NO_SERVER_TOOLS_PROMPT =
"This Anthropic backend path does not have server-managed tool calls. Do not claim to run shell commands, Codex tasks, web searches, or fetch URLs. If the user asks for tool execution, explain that they should switch to OpenAI or xAI in this app for tool-enabled chat.";
export function getAnthropicSystemPrompt(messages: ChatMessage[]) {
return [ANTHROPIC_NO_SERVER_TOOLS_PROMPT, messages.find((message) => message.role === "system")?.content]
.filter(Boolean)
.join("\n\n");
}
export function buildAnthropicConversationMessage(message: ChatMessage) {
if (message.role === "system") {
throw new Error("System messages must be handled separately for Anthropic.");
}
if (message.role === "tool") {
const name = message.name?.trim() || "tool";
return {
role: "user",
content: `Tool output (${name}):\n${message.content}`,
};
}
return {
role: message.role === "assistant" ? "assistant" : "user",
content: toAnthropicContent(message),
};
}
export function buildComparableAttachments(input: unknown): ChatAttachment[] {
if (!Array.isArray(input)) return [];
const attachments: ChatAttachment[] = [];
for (const entry of input) {
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
const record = entry as Record<string, unknown>;
const kind = record.kind;
const id = typeof record.id === "string" ? record.id : "";
const filename = typeof record.filename === "string" ? record.filename : "";
const mimeType = typeof record.mimeType === "string" ? record.mimeType : "";
const sizeBytes = typeof record.sizeBytes === "number" ? record.sizeBytes : 0;
if (kind === "image" && typeof record.dataUrl === "string") {
attachments.push({
kind,
id,
filename,
mimeType: mimeType === "image/png" ? "image/png" : "image/jpeg",
sizeBytes,
dataUrl: record.dataUrl,
});
continue;
}
if (kind === "text" && typeof record.text === "string") {
attachments.push({
kind,
id,
filename,
mimeType,
sizeBytes,
text: record.text,
truncated: record.truncated === true,
});
}
}
return attachments;
}

View File

@@ -23,6 +23,15 @@ function uniqSorted(models: string[]) {
return [...new Set(models.map((value) => value.trim()).filter(Boolean))].sort((a, b) => a.localeCompare(b));
}
function isLikelyOpenAIResponsesModel(model: string) {
const id = model.toLowerCase();
if (id.includes("embedding") || id.includes("moderation")) return false;
if (id.includes("audio") || id.includes("realtime") || id.includes("transcribe") || id.includes("tts")) return false;
if (id.includes("image") || id.includes("dall-e") || id.includes("sora")) return false;
if (id.includes("search") || id.includes("computer-use")) return false;
return /^(gpt-|o\d|chatgpt-)/.test(id);
}
async function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string) {
let timeoutId: NodeJS.Timeout | null = null;
try {
@@ -42,7 +51,7 @@ async function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: str
async function fetchProviderModels(provider: Provider) {
if (provider === "openai") {
const page = await openaiClient().models.list();
return uniqSorted(page.data.map((model) => model.id));
return uniqSorted(page.data.map((model) => model.id).filter(isLikelyOpenAIResponsesModel));
}
if (provider === "anthropic") {

View File

@@ -1,6 +1,8 @@
import { performance } from "node:perf_hooks";
import { prisma } from "../db.js";
import { anthropicClient, openaiClient, xaiClient } from "./providers.js";
import { buildToolLogMessageData, runToolAwareChatCompletions, runToolAwareOpenAIChat } from "./chat-tools.js";
import { buildAnthropicConversationMessage, getAnthropicSystemPrompt } from "./message-content.js";
import type { MultiplexRequest, MultiplexResponse, Provider } from "./types.js";
function asProviderEnum(p: Provider) {
@@ -44,33 +46,49 @@ export async function runMultiplex(req: MultiplexRequest): Promise<MultiplexResp
let outText = "";
let usage: MultiplexResponse["usage"] | undefined;
let raw: unknown;
let toolMessages: ReturnType<typeof buildToolLogMessageData>[] = [];
if (req.provider === "openai" || req.provider === "xai") {
const client = req.provider === "openai" ? openaiClient() : xaiClient();
const r = await client.chat.completions.create({
if (req.provider === "openai") {
const client = openaiClient();
const r = await runToolAwareOpenAIChat({
client,
model: req.model,
// OpenAI SDK has very specific message union types; our normalized schema is compatible.
messages: req.messages.map((m) => ({ role: m.role, content: m.content, name: m.name })) as any,
messages: req.messages,
temperature: req.temperature,
max_tokens: req.maxTokens,
maxTokens: req.maxTokens,
logContext: {
provider: req.provider,
model: req.model,
chatId,
},
});
raw = r;
outText = r.choices?.[0]?.message?.content ?? "";
usage = r.usage
? {
inputTokens: r.usage.prompt_tokens,
outputTokens: r.usage.completion_tokens,
totalTokens: r.usage.total_tokens,
}
: undefined;
raw = r.raw;
outText = r.text;
usage = r.usage;
toolMessages = r.toolEvents.map((event) => buildToolLogMessageData(call.chatId, event));
} else if (req.provider === "xai") {
const client = xaiClient();
const r = await runToolAwareChatCompletions({
client,
model: req.model,
messages: req.messages,
temperature: req.temperature,
maxTokens: req.maxTokens,
logContext: {
provider: req.provider,
model: req.model,
chatId,
},
});
raw = r.raw;
outText = r.text;
usage = r.usage;
toolMessages = r.toolEvents.map((event) => buildToolLogMessageData(call.chatId, event));
} else if (req.provider === "anthropic") {
const client = anthropicClient();
// Anthropic splits system prompt. We'll convert first system message into system string.
const system = req.messages.find((m) => m.role === "system")?.content;
const msgs = req.messages
.filter((m) => m.role !== "system")
.map((m) => ({ role: m.role === "assistant" ? "assistant" : "user", content: m.content }));
const system = getAnthropicSystemPrompt(req.messages);
const msgs = req.messages.filter((message) => message.role !== "system").map((message) => buildAnthropicConversationMessage(message));
const r = await client.messages.create({
model: req.model,
@@ -100,16 +118,27 @@ export async function runMultiplex(req: MultiplexRequest): Promise<MultiplexResp
const latencyMs = Math.round(performance.now() - t0);
// Store assistant message + call record
await prisma.$transaction([
prisma.message.create({
// Store tool activity (if any), assistant message, and call record.
await prisma.$transaction(async (tx) => {
if (toolMessages.length) {
await tx.message.createMany({
data: toolMessages.map((message) => ({
chatId: message.chatId,
role: message.role as any,
content: message.content,
name: message.name,
metadata: message.metadata as any,
})),
});
}
await tx.message.create({
data: {
chatId: call.chatId,
role: "assistant" as any,
content: outText,
},
}),
prisma.llmCall.update({
});
await tx.llmCall.update({
where: { id: call.id },
data: {
response: raw as any,
@@ -118,8 +147,8 @@ export async function runMultiplex(req: MultiplexRequest): Promise<MultiplexResp
outputTokens: usage?.outputTokens,
totalTokens: usage?.totalTokens,
},
}),
]);
});
});
return {
provider: req.provider,

View File

@@ -1,13 +1,26 @@
import { performance } from "node:perf_hooks";
import type OpenAI from "openai";
import { prisma } from "../db.js";
import { anthropicClient, openaiClient, xaiClient } from "./providers.js";
import {
buildToolLogMessageData,
runToolAwareChatCompletionsStream,
runToolAwareOpenAIChatStream,
type ToolExecutionEvent,
} from "./chat-tools.js";
import { buildAnthropicConversationMessage, getAnthropicSystemPrompt } from "./message-content.js";
import type { MultiplexRequest, Provider } from "./types.js";
type StreamUsage = {
inputTokens?: number;
outputTokens?: number;
totalTokens?: number;
};
export type StreamEvent =
| { type: "meta"; chatId: string; callId: string; provider: Provider; model: string }
| { type: "meta"; chatId: string | null; callId: string | null; provider: Provider; model: string }
| { type: "tool_call"; event: ToolExecutionEvent }
| { type: "delta"; text: string }
| { type: "done"; text: string; usage?: { inputTokens?: number; outputTokens?: number; totalTokens?: number } }
| { type: "done"; text: string; usage?: StreamUsage }
| { type: "error"; message: string };
function getChatIdOrCreate(chatId?: string) {
@@ -17,69 +30,109 @@ function getChatIdOrCreate(chatId?: string) {
export async function* runMultiplexStream(req: MultiplexRequest): AsyncGenerator<StreamEvent> {
const t0 = performance.now();
const chatId = await getChatIdOrCreate(req.chatId);
const shouldPersist = req.persist !== false;
const chatId = shouldPersist ? await getChatIdOrCreate(req.chatId) : null;
const call = await prisma.llmCall.create({
data: {
chatId,
provider: req.provider as any,
model: req.model,
request: req as any,
},
select: { id: true },
});
const call =
shouldPersist && chatId
? await prisma.llmCall.create({
data: {
chatId,
provider: req.provider as any,
model: req.model,
request: req as any,
},
select: { id: true },
})
: null;
await prisma.$transaction([
prisma.chat.update({
where: { id: chatId },
data: {
lastUsedProvider: req.provider as any,
lastUsedModel: req.model,
},
}),
prisma.chat.updateMany({
where: { id: chatId, initiatedProvider: null },
data: {
initiatedProvider: req.provider as any,
initiatedModel: req.model,
},
}),
]);
if (shouldPersist && chatId) {
await prisma.$transaction([
prisma.chat.update({
where: { id: chatId },
data: {
lastUsedProvider: req.provider as any,
lastUsedModel: req.model,
},
}),
prisma.chat.updateMany({
where: { id: chatId, initiatedProvider: null },
data: {
initiatedProvider: req.provider as any,
initiatedModel: req.model,
},
}),
]);
}
yield { type: "meta", chatId, callId: call.id, provider: req.provider, model: req.model };
yield { type: "meta", chatId, callId: call?.id ?? null, provider: req.provider, model: req.model };
let text = "";
let usage: StreamEvent extends any ? any : never;
let usage: StreamUsage | undefined;
let raw: unknown = { streamed: true };
try {
if (req.provider === "openai" || req.provider === "xai") {
const client = req.provider === "openai" ? openaiClient() : xaiClient();
const stream = await client.chat.completions.create({
model: req.model,
messages: req.messages.map((m) => ({ role: m.role, content: m.content, name: m.name })) as any,
temperature: req.temperature,
max_tokens: req.maxTokens,
stream: true,
});
for await (const chunk of stream as any as AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>) {
const delta = chunk.choices?.[0]?.delta?.content ?? "";
if (delta) {
text += delta;
yield { type: "delta", text: delta };
const streamEvents =
req.provider === "openai"
? runToolAwareOpenAIChatStream({
client,
model: req.model,
messages: req.messages,
temperature: req.temperature,
maxTokens: req.maxTokens,
logContext: {
provider: req.provider,
model: req.model,
chatId: chatId ?? undefined,
},
})
: runToolAwareChatCompletionsStream({
client,
model: req.model,
messages: req.messages,
temperature: req.temperature,
maxTokens: req.maxTokens,
logContext: {
provider: req.provider,
model: req.model,
chatId: chatId ?? undefined,
},
});
for await (const ev of streamEvents) {
if (ev.type === "delta") {
text += ev.text;
yield { type: "delta", text: ev.text };
continue;
}
}
// no guaranteed usage in stream mode across providers; leave empty for now
if (ev.type === "tool_call") {
if (shouldPersist && chatId) {
const toolMessage = buildToolLogMessageData(chatId, ev.event);
await prisma.message.create({
data: {
chatId: toolMessage.chatId,
role: toolMessage.role as any,
content: toolMessage.content,
name: toolMessage.name,
metadata: toolMessage.metadata as any,
},
});
}
yield { type: "tool_call", event: ev.event };
continue;
}
raw = ev.result.raw;
usage = ev.result.usage;
text = ev.result.text;
}
} else if (req.provider === "anthropic") {
const client = anthropicClient();
const system = req.messages.find((m) => m.role === "system")?.content;
const msgs = req.messages
.filter((m) => m.role !== "system")
.map((m) => ({ role: m.role === "assistant" ? "assistant" : "user", content: m.content }));
const system = getAnthropicSystemPrompt(req.messages);
const msgs = req.messages.filter((message) => message.role !== "system").map((message) => buildAnthropicConversationMessage(message));
const stream = await client.messages.create({
model: req.model,
@@ -110,38 +163,43 @@ export async function* runMultiplexStream(req: MultiplexRequest): AsyncGenerator
}
// some streams end with message_stop
}
raw = { streamed: true, provider: "anthropic" };
} else {
throw new Error(`unknown provider: ${req.provider}`);
}
const latencyMs = Math.round(performance.now() - t0);
await prisma.$transaction([
prisma.message.create({
data: { chatId, role: "assistant" as any, content: text },
}),
prisma.llmCall.update({
where: { id: call.id },
data: {
response: raw as any,
latencyMs,
inputTokens: usage?.inputTokens,
outputTokens: usage?.outputTokens,
totalTokens: usage?.totalTokens,
},
}),
]);
if (shouldPersist && chatId && call) {
await prisma.$transaction(async (tx) => {
await tx.message.create({
data: { chatId, role: "assistant" as any, content: text },
});
await tx.llmCall.update({
where: { id: call.id },
data: {
response: raw as any,
latencyMs,
inputTokens: usage?.inputTokens,
outputTokens: usage?.outputTokens,
totalTokens: usage?.totalTokens,
},
});
});
}
yield { type: "done", text, usage };
} catch (e: any) {
const latencyMs = Math.round(performance.now() - t0);
await prisma.llmCall.update({
where: { id: call.id },
data: {
error: e?.message ?? String(e),
latencyMs,
},
});
if (shouldPersist && call) {
await prisma.llmCall.update({
where: { id: call.id },
data: {
error: e?.message ?? String(e),
latencyMs,
},
});
}
yield { type: "error", message: e?.message ?? String(e) };
}
}

View File

@@ -1,13 +1,36 @@
export type Provider = "openai" | "anthropic" | "xai";
export type ChatImageAttachment = {
kind: "image";
id: string;
filename: string;
mimeType: "image/png" | "image/jpeg";
sizeBytes: number;
dataUrl: string;
};
export type ChatTextAttachment = {
kind: "text";
id: string;
filename: string;
mimeType: string;
sizeBytes: number;
text: string;
truncated?: boolean;
};
export type ChatAttachment = ChatImageAttachment | ChatTextAttachment;
export type ChatMessage = {
role: "system" | "user" | "assistant" | "tool";
content: string;
name?: string;
attachments?: ChatAttachment[];
};
export type MultiplexRequest = {
chatId?: string;
persist?: boolean;
provider: Provider;
model: string;
messages: ChatMessage[];

View File

@@ -4,20 +4,43 @@ import type { FastifyInstance } from "fastify";
import { prisma } from "./db.js";
import { requireAdmin } from "./auth.js";
import { env } from "./env.js";
import { buildComparableAttachments } from "./llm/message-content.js";
import { runMultiplex } from "./llm/multiplexer.js";
import { runMultiplexStream } from "./llm/streaming.js";
import { getModelCatalogSnapshot } from "./llm/model-catalog.js";
import { openaiClient } from "./llm/providers.js";
import { exaClient } from "./search/exa.js";
import type { ChatAttachment } from "./llm/types.js";
type IncomingChatMessage = {
role: "system" | "user" | "assistant" | "tool";
content: string;
name?: string;
attachments?: ChatAttachment[];
};
function sameMessage(a: IncomingChatMessage, b: IncomingChatMessage) {
return a.role === b.role && a.content === b.content && (a.name ?? null) === (b.name ?? null);
function sameMessage(
a: { role: string; content: string; name?: string | null; metadata?: unknown },
b: { role: string; content: string; name?: string | null; attachments?: ChatAttachment[] }
) {
const existingAttachments = JSON.stringify(buildComparableAttachments((a.metadata as Record<string, unknown> | null)?.attachments ?? null));
const incomingAttachments = JSON.stringify(b.attachments ?? []);
return (
a.role === b.role &&
a.content === b.content &&
(a.name ?? null) === (b.name ?? null) &&
existingAttachments === incomingAttachments
);
}
function isToolCallLogMetadata(value: unknown) {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const record = value as Record<string, unknown>;
return record.kind === "tool_call";
}
function isToolCallLogMessage(message: { role: string; metadata: unknown }) {
return message.role === "tool" && isToolCallLogMetadata(message.metadata);
}
async function storeNonAssistantMessages(chatId: string, messages: IncomingChatMessage[]) {
@@ -27,13 +50,13 @@ async function storeNonAssistantMessages(chatId: string, messages: IncomingChatM
const existing = await prisma.message.findMany({
where: { chatId },
orderBy: { createdAt: "asc" },
select: { role: true, content: true, name: true },
select: { role: true, content: true, name: true, metadata: true },
});
const existingNonAssistant = existing.filter((m) => m.role !== "assistant");
const existingNonAssistant = existing.filter((m) => m.role !== "assistant" && !isToolCallLogMessage(m));
let sharedPrefix = 0;
const max = Math.min(existingNonAssistant.length, incoming.length);
while (sharedPrefix < max && sameMessage(existingNonAssistant[sharedPrefix] as IncomingChatMessage, incoming[sharedPrefix])) {
while (sharedPrefix < max && sameMessage(existingNonAssistant[sharedPrefix], incoming[sharedPrefix])) {
sharedPrefix += 1;
}
@@ -47,10 +70,67 @@ async function storeNonAssistantMessages(chatId: string, messages: IncomingChatM
role: m.role as any,
content: m.content,
name: m.name,
metadata: m.attachments?.length ? ({ attachments: m.attachments } as any) : undefined,
})),
});
}
const MAX_CHAT_ATTACHMENTS = 8;
const MAX_IMAGE_ATTACHMENT_BYTES = 6 * 1024 * 1024;
const MAX_TEXT_ATTACHMENT_CHARS = 200_000;
const MAX_IMAGE_DATA_URL_CHARS = 8_500_000;
const ChatAttachmentSchema = z.discriminatedUnion("kind", [
z.object({
kind: z.literal("image"),
id: z.string().trim().min(1).max(128),
filename: z.string().trim().min(1).max(255),
mimeType: z.enum(["image/png", "image/jpeg"]),
sizeBytes: z.number().int().positive().max(MAX_IMAGE_ATTACHMENT_BYTES),
dataUrl: z
.string()
.max(MAX_IMAGE_DATA_URL_CHARS)
.regex(/^data:image\/(?:png|jpeg);base64,[a-z0-9+/=\s]+$/i, "Invalid image data URL"),
}),
z.object({
kind: z.literal("text"),
id: z.string().trim().min(1).max(128),
filename: z.string().trim().min(1).max(255),
mimeType: z.string().trim().min(1).max(127),
sizeBytes: z.number().int().positive().max(8 * 1024 * 1024),
text: z.string().max(MAX_TEXT_ATTACHMENT_CHARS),
truncated: z.boolean().optional(),
}),
]);
const CompletionMessageSchema = z
.object({
role: z.enum(["system", "user", "assistant", "tool"]),
content: z.string(),
name: z.string().optional(),
attachments: z.array(ChatAttachmentSchema).max(MAX_CHAT_ATTACHMENTS).optional(),
})
.superRefine((value, ctx) => {
if (value.attachments?.length && value.role === "tool") {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Tool messages cannot include attachments.",
path: ["attachments"],
});
}
});
function mergeAttachmentsIntoMetadata(metadata: unknown, attachments?: ChatAttachment[]) {
if (!attachments?.length) return metadata as any;
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) {
return { attachments };
}
return {
...(metadata as Record<string, unknown>),
attachments,
};
}
const SearchRunBody = z.object({
query: z.string().trim().min(1).optional(),
title: z.string().trim().min(1).optional(),
@@ -95,6 +175,13 @@ function mapSearchResultPreview(result: any, index: number) {
};
}
function truncateContextPart(value: string | null | undefined, maxLength: number) {
const trimmed = value?.trim();
if (!trimmed) return null;
if (trimmed.length <= maxLength) return trimmed;
return `${trimmed.slice(0, maxLength - 1).trimEnd()}...`;
}
function parseAnswerText(answerResponse: any) {
if (typeof answerResponse?.answer === "string") return answerResponse.answer;
if (answerResponse?.answer) return JSON.stringify(answerResponse.answer, null, 2);
@@ -116,16 +203,15 @@ async function generateChatTitle(content: string) {
const systemPrompt =
"You create short chat titles. Return exactly one line, maximum 4 words, no quotes, no trailing punctuation.";
const userPrompt = `User request:\n${content}\n\nTitle:`;
const response = await openaiClient().chat.completions.create({
const response = await openaiClient().responses.create({
model: "gpt-4.1-mini",
temperature: 0,
max_completion_tokens: 20,
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: userPrompt },
],
max_output_tokens: 20,
instructions: systemPrompt,
input: userPrompt,
store: false,
});
return response.choices?.[0]?.message?.content ?? "";
return response.output_text ?? "";
}
function normalizeUrlForMatch(input: string | null | undefined) {
@@ -140,6 +226,57 @@ function normalizeUrlForMatch(input: string | null | undefined) {
}
}
function buildSearchChatContext(search: any) {
const query = truncateContextPart(search.query, 500) ?? truncateContextPart(search.title, 500) ?? "Untitled search";
const lines: string[] = [
"You are Sybil. The user started this chat from a saved web search. Use the search answer and result context below when answering follow-up questions. If the context is insufficient, say so and use available tools when appropriate.",
"",
`Search query: ${query}`,
];
const answer = truncateContextPart(search.answerText, 6000);
if (answer) {
lines.push("", "Search answer:", answer);
}
if (Array.isArray(search.answerCitations) && search.answerCitations.length) {
lines.push("", "Answer citations:");
for (const [index, citation] of search.answerCitations.slice(0, 8).entries()) {
const title = truncateContextPart(citation?.title, 160);
const url = truncateContextPart(citation?.url ?? citation?.id, 400);
if (title || url) {
lines.push(`${index + 1}. ${[title, url].filter(Boolean).join(" - ")}`);
}
}
}
if (Array.isArray(search.results) && search.results.length) {
lines.push("", "Search results:");
for (const result of search.results.slice(0, 10)) {
const title = truncateContextPart(result.title, 180) ?? result.url;
const url = truncateContextPart(result.url, 500);
const published = truncateContextPart(result.publishedDate, 80);
const author = truncateContextPart(result.author, 120);
const text = truncateContextPart(result.text, 1000);
const highlights = Array.isArray(result.highlights)
? result.highlights
.map((highlight: unknown) => truncateContextPart(typeof highlight === "string" ? highlight : null, 360))
.filter(Boolean)
: [];
lines.push(`${result.rank + 1}. ${title}`);
if (url) lines.push(` URL: ${url}`);
if (published || author) lines.push(` Source detail: ${[published, author].filter(Boolean).join(" - ")}`);
if (text) lines.push(` Text: ${text}`);
for (const highlight of highlights.slice(0, 2)) {
lines.push(` Highlight: ${highlight}`);
}
}
}
return lines.join("\n");
}
function buildSseHeaders(originHeader: string | undefined) {
const origin = originHeader && originHeader !== "null" ? originHeader : "*";
const headers: Record<string, string> = {
@@ -190,10 +327,50 @@ export async function registerRoutes(app: FastifyInstance) {
app.post("/v1/chats", async (req) => {
requireAdmin(req);
const Body = z.object({ title: z.string().optional() });
const body = Body.parse(req.body ?? {});
const Body = z
.object({
title: z.string().optional(),
provider: z.enum(["openai", "anthropic", "xai"]).optional(),
model: z.string().trim().min(1).optional(),
messages: z.array(CompletionMessageSchema).optional(),
})
.superRefine((value, ctx) => {
if (value.provider && !value.model) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "model is required when provider is supplied",
path: ["model"],
});
}
if (!value.provider && value.model) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "provider is required when model is supplied",
path: ["provider"],
});
}
});
const parsed = Body.safeParse(req.body ?? {});
if (!parsed.success) return app.httpErrors.badRequest(parsed.error.message);
const body = parsed.data;
const chat = await prisma.chat.create({
data: { title: body.title },
data: {
title: body.title,
initiatedProvider: body.provider as any,
initiatedModel: body.model,
lastUsedProvider: body.provider as any,
lastUsedModel: body.model,
messages: body.messages?.length
? {
create: body.messages.map((message) => ({
role: message.role as any,
content: message.content,
name: message.name,
metadata: message.attachments?.length ? ({ attachments: message.attachments } as any) : undefined,
})),
}
: undefined,
},
select: {
id: true,
title: true,
@@ -357,6 +534,54 @@ export async function registerRoutes(app: FastifyInstance) {
return { search };
});
app.post("/v1/searches/:searchId/chat", async (req) => {
requireAdmin(req);
const Params = z.object({ searchId: z.string() });
const Body = z.object({ title: z.string().optional() });
const { searchId } = Params.parse(req.params);
const body = Body.parse(req.body ?? {});
const search = await prisma.search.findUnique({
where: { id: searchId },
include: { results: { orderBy: { rank: "asc" } } },
});
if (!search) return app.httpErrors.notFound("search not found");
const fallbackTitle = search.query?.trim() || search.title?.trim() || "Search results";
const title = body.title?.trim() || `Search: ${fallbackTitle.slice(0, 72)}`;
const context = buildSearchChatContext(search);
const chat = await prisma.chat.create({
data: {
title,
messages: {
create: {
role: "system" as any,
content: context,
metadata: {
kind: "search_context",
searchId: search.id,
query: search.query,
resultCount: search.results.length,
},
},
},
},
select: {
id: true,
title: true,
createdAt: true,
updatedAt: true,
initiatedProvider: true,
initiatedModel: true,
lastUsedProvider: true,
lastUsedModel: true,
},
});
return { chat };
});
app.post("/v1/searches/:searchId/run", async (req) => {
requireAdmin(req);
const Params = z.object({ searchId: z.string() });
@@ -649,10 +874,13 @@ export async function registerRoutes(app: FastifyInstance) {
content: z.string(),
name: z.string().optional(),
metadata: z.unknown().optional(),
attachments: z.array(ChatAttachmentSchema).max(MAX_CHAT_ATTACHMENTS).optional(),
});
const { chatId } = Params.parse(req.params);
const body = Body.parse(req.body);
const parsed = Body.safeParse(req.body);
if (!parsed.success) return app.httpErrors.badRequest(parsed.error.message);
const body = parsed.data;
const msg = await prisma.message.create({
data: {
@@ -660,7 +888,7 @@ export async function registerRoutes(app: FastifyInstance) {
role: body.role as any,
content: body.content,
name: body.name,
metadata: body.metadata as any,
metadata: mergeAttachmentsIntoMetadata(body.metadata, body.attachments) as any,
},
});
@@ -675,18 +903,14 @@ export async function registerRoutes(app: FastifyInstance) {
chatId: z.string().optional(),
provider: z.enum(["openai", "anthropic", "xai"]),
model: z.string().min(1),
messages: z.array(
z.object({
role: z.enum(["system", "user", "assistant", "tool"]),
content: z.string(),
name: z.string().optional(),
})
),
messages: z.array(CompletionMessageSchema),
temperature: z.number().min(0).max(2).optional(),
maxTokens: z.number().int().positive().optional(),
});
const body = Body.parse(req.body);
const parsed = Body.safeParse(req.body);
if (!parsed.success) return app.httpErrors.badRequest(parsed.error.message);
const body = parsed.data;
// ensure chat exists if provided
if (body.chatId) {
@@ -711,22 +935,29 @@ export async function registerRoutes(app: FastifyInstance) {
app.post("/v1/chat-completions/stream", async (req, reply) => {
requireAdmin(req);
const Body = z.object({
chatId: z.string().optional(),
provider: z.enum(["openai", "anthropic", "xai"]),
model: z.string().min(1),
messages: z.array(
z.object({
role: z.enum(["system", "user", "assistant", "tool"]),
content: z.string(),
name: z.string().optional(),
})
),
temperature: z.number().min(0).max(2).optional(),
maxTokens: z.number().int().positive().optional(),
});
const Body = z
.object({
chatId: z.string().optional(),
persist: z.boolean().optional(),
provider: z.enum(["openai", "anthropic", "xai"]),
model: z.string().min(1),
messages: z.array(CompletionMessageSchema),
temperature: z.number().min(0).max(2).optional(),
maxTokens: z.number().int().positive().optional(),
})
.superRefine((value, ctx) => {
if (value.persist === false && value.chatId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "chatId must be omitted when persist is false",
path: ["chatId"],
});
}
});
const body = Body.parse(req.body);
const parsed = Body.safeParse(req.body);
if (!parsed.success) return app.httpErrors.badRequest(parsed.error.message);
const body = parsed.data;
// ensure chat exists if provided
if (body.chatId) {
@@ -735,11 +966,12 @@ export async function registerRoutes(app: FastifyInstance) {
}
// Store only new non-assistant messages to avoid duplicate history entries.
if (body.chatId) {
if (body.persist !== false && body.chatId) {
await storeNonAssistantMessages(body.chatId, body.messages);
}
reply.raw.writeHead(200, buildSseHeaders(typeof req.headers.origin === "string" ? req.headers.origin : undefined));
reply.raw.flushHeaders();
const send = (event: string, data: any) => {
reply.raw.write(`event: ${event}\n`);
@@ -748,6 +980,7 @@ export async function registerRoutes(app: FastifyInstance) {
for await (const ev of runMultiplexStream(body)) {
if (ev.type === "meta") send("meta", ev);
else if (ev.type === "tool_call") send("tool_call", ev.event);
else if (ev.type === "delta") send("delta", ev);
else if (ev.type === "done") send("done", ev);
else if (ev.type === "error") send("error", ev);

View File

@@ -0,0 +1,160 @@
import { env } from "../env.js";
const SEARXNG_TIMEOUT_MS = 12_000;
const DEFAULT_SEARXNG_CATEGORIES = "general";
export type SearxngSearchOptions = {
numResults: number;
includeDomains?: string[];
excludeDomains?: string[];
};
export type SearxngSearchResult = {
title: string | null;
url: string | null;
publishedDate: string | null;
summary: string | null;
text: string | null;
engines: string[];
};
export type SearxngSearchResponse = {
query: string;
requestId: null;
results: SearxngSearchResult[];
};
function clipText(input: string, maxCharacters: number) {
return input.length <= maxCharacters ? input : `${input.slice(0, maxCharacters)}...`;
}
function compactWhitespace(input: string) {
return input.replace(/\r/g, "").replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").replace(/\s+/g, " ").trim();
}
function requireSearxngBaseUrl() {
if (!env.SEARXNG_BASE_URL) {
throw new Error("SEARXNG_BASE_URL not set");
}
return env.SEARXNG_BASE_URL.endsWith("/") ? env.SEARXNG_BASE_URL : `${env.SEARXNG_BASE_URL}/`;
}
function normalizeDomain(input: string) {
const trimmed = input.trim().toLowerCase();
if (!trimmed) return null;
try {
const parsed = new URL(trimmed.includes("://") ? trimmed : `https://${trimmed}`);
return parsed.hostname.replace(/^www\./, "");
} catch {
return trimmed.split(/[/?#]/, 1)[0]?.replace(/^www\./, "") || null;
}
}
function normalizeDomains(input: string[] | undefined) {
return Array.from(new Set((input ?? []).map(normalizeDomain).filter((domain): domain is string => Boolean(domain))));
}
function hostnameMatchesDomain(urlRaw: string | null, domain: string) {
if (!urlRaw) return false;
try {
const hostname = new URL(urlRaw).hostname.toLowerCase().replace(/^www\./, "");
return hostname === domain || hostname.endsWith(`.${domain}`);
} catch {
return false;
}
}
function filterResultsByDomains(results: SearxngSearchResult[], options: SearxngSearchOptions) {
const includeDomains = normalizeDomains(options.includeDomains);
const excludeDomains = normalizeDomains(options.excludeDomains);
return results.filter((result) => {
if (includeDomains.length && !includeDomains.some((domain) => hostnameMatchesDomain(result.url, domain))) return false;
if (excludeDomains.some((domain) => hostnameMatchesDomain(result.url, domain))) return false;
return true;
});
}
function buildSearxngQuery(query: string, options: SearxngSearchOptions) {
const includeDomains = normalizeDomains(options.includeDomains);
const excludeDomains = normalizeDomains(options.excludeDomains);
const includeClause =
includeDomains.length === 0
? ""
: includeDomains.length === 1
? `site:${includeDomains[0]}`
: `(${includeDomains.map((domain) => `site:${domain}`).join(" OR ")})`;
const excludeClause = excludeDomains.map((domain) => `-site:${domain}`).join(" ");
return [query, includeClause, excludeClause].filter(Boolean).join(" ");
}
function buildSearchUrl(query: string, options: SearxngSearchOptions) {
const url = new URL("search", requireSearxngBaseUrl());
url.searchParams.set("q", buildSearxngQuery(query, options));
url.searchParams.set("categories", DEFAULT_SEARXNG_CATEGORIES);
url.searchParams.set("language", "auto");
url.searchParams.set("safesearch", "1");
url.searchParams.set("format", "json");
return url;
}
async function fetchSearxng(url: URL, accept: string) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), SEARXNG_TIMEOUT_MS);
try {
return await fetch(url, {
redirect: "follow",
signal: controller.signal,
headers: {
"User-Agent": "SybilBot/1.0 (+https://sybil.local)",
Accept: accept,
},
});
} finally {
clearTimeout(timeout);
}
}
function stringOrNull(value: unknown) {
if (typeof value !== "string") return null;
const normalized = compactWhitespace(value);
return normalized || null;
}
function stringArray(value: unknown) {
if (!Array.isArray(value)) return [];
return value.filter((item): item is string => typeof item === "string").map(compactWhitespace).filter(Boolean);
}
function mapJsonResult(result: any): SearxngSearchResult {
const summary = stringOrNull(result?.content) ?? stringOrNull(result?.snippet);
const text = summary ? clipText(summary, 700) : null;
return {
title: stringOrNull(result?.title),
url: stringOrNull(result?.url),
publishedDate: stringOrNull(result?.publishedDate) ?? stringOrNull(result?.published_date),
summary: summary ? clipText(summary, 1_400) : null,
text,
engines: stringArray(result?.engines ?? (typeof result?.engine === "string" ? [result.engine] : [])),
};
}
export async function searchSearxng(query: string, options: SearxngSearchOptions): Promise<SearxngSearchResponse> {
const url = buildSearchUrl(query, options);
const response = await fetchSearxng(url, "application/json");
if (!response.ok) {
await response.arrayBuffer();
throw new Error(`SearXNG JSON search failed with status ${response.status}. Verify search.formats includes json.`);
}
const contentType = response.headers.get("content-type")?.toLowerCase() ?? "";
if (!contentType.includes("application/json")) {
await response.arrayBuffer();
throw new Error(`SearXNG JSON search returned ${contentType || "unknown content type"}.`);
}
const data: any = await response.json();
const results = Array.isArray(data?.results) ? data.results.map(mapJsonResult) : [];
return { query, requestId: null, results: filterResultsByDomains(results, options).slice(0, options.numResults) };
}

3
server/src/types/html-to-text.d.ts vendored Normal file
View File

@@ -0,0 +1,3 @@
declare module "html-to-text" {
export function convert(html: string, options?: unknown): string;
}

View File

@@ -0,0 +1,107 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
runToolAwareChatCompletionsStream,
runToolAwareOpenAIChatStream,
type ToolAwareStreamingEvent,
} from "../src/llm/chat-tools.js";
async function* streamFrom(events: any[]) {
for (const event of events) {
await Promise.resolve();
yield event;
}
}
async function collectEvents(iterable: AsyncIterable<ToolAwareStreamingEvent>) {
const events: ToolAwareStreamingEvent[] = [];
for await (const event of iterable) {
events.push(event);
}
return events;
}
test("OpenAI Responses stream emits text deltas as they arrive", async () => {
const outputMessage = {
id: "msg_1",
type: "message",
role: "assistant",
status: "completed",
content: [{ type: "output_text", text: "Hello" }],
};
const client = {
responses: {
create: async () =>
streamFrom([
{ type: "response.output_item.added", item: { ...outputMessage, content: [] }, output_index: 0 },
{ type: "response.output_text.delta", delta: "Hel", output_index: 0, content_index: 0 },
{ type: "response.output_text.delta", delta: "lo", output_index: 0, content_index: 0 },
{ type: "response.output_item.done", item: outputMessage, output_index: 0 },
{
type: "response.completed",
response: {
status: "completed",
output_text: "Hello",
output: [outputMessage],
usage: { input_tokens: 2, output_tokens: 1, total_tokens: 3 },
},
},
]),
},
};
const events = await collectEvents(
runToolAwareOpenAIChatStream({
client: client as any,
model: "gpt-test",
messages: [{ role: "user", content: "Say hello" }],
})
);
assert.deepEqual(
events.map((event) => event.type),
["delta", "delta", "done"]
);
assert.deepEqual(
events.filter((event) => event.type === "delta").map((event) => event.text),
["Hel", "lo"]
);
assert.equal(events.at(-1)?.type === "done" ? events.at(-1)?.result.text : null, "Hello");
});
test("OpenAI-compatible Chat Completions stream emits text deltas as they arrive", async () => {
const client = {
chat: {
completions: {
create: async () =>
streamFrom([
{ choices: [{ delta: { role: "assistant" } }] },
{ choices: [{ delta: { content: "Hel" } }] },
{ choices: [{ delta: { content: "lo" } }] },
{
choices: [{ delta: {}, finish_reason: "stop" }],
usage: { prompt_tokens: 2, completion_tokens: 1, total_tokens: 3 },
},
]),
},
},
};
const events = await collectEvents(
runToolAwareChatCompletionsStream({
client: client as any,
model: "grok-test",
messages: [{ role: "user", content: "Say hello" }],
})
);
assert.deepEqual(
events.map((event) => event.type),
["delta", "delta", "done"]
);
assert.deepEqual(
events.filter((event) => event.type === "delta").map((event) => event.text),
["Hel", "lo"]
);
assert.equal(events.at(-1)?.type === "done" ? events.at(-1)?.result.text : null, "Hello");
});

2
tui/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
node_modules/
dist/

49
tui/README.md Normal file
View File

@@ -0,0 +1,49 @@
# Sybil TUI
Terminal UI client for Sybil with a sidebar + workspace flow similar to the web app.
## Setup
```bash
cd tui
npm install
npm run dev
```
Build/start:
```bash
npm run build
npm run start
```
## Environment Variables
Configuration is environment-only (no in-app settings).
- `SYBIL_TUI_API_BASE_URL`: API base URL. Default: `http://127.0.0.1:8787`
- `SYBIL_TUI_ADMIN_TOKEN`: optional bearer token for token-mode servers
- `SYBIL_TUI_DEFAULT_PROVIDER`: `openai` | `anthropic` | `xai` (default: `openai`)
- `SYBIL_TUI_DEFAULT_MODEL`: optional default model name
- `SYBIL_TUI_SEARCH_NUM_RESULTS`: results per search run (default: `10`)
Compatibility aliases:
- `SYBIL_API_BASE_URL` (fallback for API URL)
- `SYBIL_ADMIN_TOKEN` (fallback for token)
## Key Bindings
- `Tab` / `Shift+Tab`: move focus between sidebar, transcript, and composer
- `Esc` (in composer): exit input mode and focus sidebar
- `Up` / `Down` (in sidebar): move highlight
- `Page Up` / `Page Down` (in transcript): scroll the transcript by one page
- `Enter` in sidebar: load highlighted conversation/search
- `Enter` in composer: send message/search
- `n`: new chat draft
- `/`: new search draft
- `d`: delete selected chat/search
- `p`: cycle provider (chat mode)
- `m`: cycle model (chat mode)
- `r`: refresh collections + models
- `q` or `Ctrl+C`: quit

616
tui/package-lock.json generated Normal file
View File

@@ -0,0 +1,616 @@
{
"name": "sybil-tui",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sybil-tui",
"version": "0.1.0",
"dependencies": {
"blessed": "^0.1.81"
},
"devDependencies": {
"@types/blessed": "^0.1.25",
"@types/node": "^25.0.10",
"tsx": "^4.21.0",
"typescript": "^5.9.3"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.3.tgz",
"integrity": "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.3.tgz",
"integrity": "sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.3.tgz",
"integrity": "sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.3.tgz",
"integrity": "sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.3.tgz",
"integrity": "sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.3.tgz",
"integrity": "sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.3.tgz",
"integrity": "sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.3.tgz",
"integrity": "sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.3.tgz",
"integrity": "sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.3.tgz",
"integrity": "sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.3.tgz",
"integrity": "sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.3.tgz",
"integrity": "sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.3.tgz",
"integrity": "sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.3.tgz",
"integrity": "sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.3.tgz",
"integrity": "sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.3.tgz",
"integrity": "sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.3.tgz",
"integrity": "sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.3.tgz",
"integrity": "sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.3.tgz",
"integrity": "sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.3.tgz",
"integrity": "sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.3.tgz",
"integrity": "sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.3.tgz",
"integrity": "sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.3.tgz",
"integrity": "sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.3.tgz",
"integrity": "sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.3.tgz",
"integrity": "sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.3.tgz",
"integrity": "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@types/blessed": {
"version": "0.1.27",
"resolved": "https://registry.npmjs.org/@types/blessed/-/blessed-0.1.27.tgz",
"integrity": "sha512-ZOQGjLvWDclAXp0rW5iuUBXeD6Gr1PkitN7tj7/G8FCoSzTsij6OhXusOzMKhwrZ9YlL2Pmu0d6xJ9zVvk+Hsg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/node": {
"version": "25.3.3",
"resolved": "https://registry.npmjs.org/@types/node/-/node-25.3.3.tgz",
"integrity": "sha512-DpzbrH7wIcBaJibpKo9nnSQL0MTRdnWttGyE5haGwK86xgMOkFLp7vEyfQPGLOJh5wNYiJ3V9PmUMDhV9u8kkQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~7.18.0"
}
},
"node_modules/blessed": {
"version": "0.1.81",
"resolved": "https://registry.npmjs.org/blessed/-/blessed-0.1.81.tgz",
"integrity": "sha512-LoF5gae+hlmfORcG1M5+5XZi4LBmvlXTzwJWzUlPryN/SJdSflZvROM2TwkT0GMpq7oqT48NRd4GS7BiVBc5OQ==",
"license": "MIT",
"bin": {
"blessed": "bin/tput.js"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/esbuild": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.3.tgz",
"integrity": "sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.27.3",
"@esbuild/android-arm": "0.27.3",
"@esbuild/android-arm64": "0.27.3",
"@esbuild/android-x64": "0.27.3",
"@esbuild/darwin-arm64": "0.27.3",
"@esbuild/darwin-x64": "0.27.3",
"@esbuild/freebsd-arm64": "0.27.3",
"@esbuild/freebsd-x64": "0.27.3",
"@esbuild/linux-arm": "0.27.3",
"@esbuild/linux-arm64": "0.27.3",
"@esbuild/linux-ia32": "0.27.3",
"@esbuild/linux-loong64": "0.27.3",
"@esbuild/linux-mips64el": "0.27.3",
"@esbuild/linux-ppc64": "0.27.3",
"@esbuild/linux-riscv64": "0.27.3",
"@esbuild/linux-s390x": "0.27.3",
"@esbuild/linux-x64": "0.27.3",
"@esbuild/netbsd-arm64": "0.27.3",
"@esbuild/netbsd-x64": "0.27.3",
"@esbuild/openbsd-arm64": "0.27.3",
"@esbuild/openbsd-x64": "0.27.3",
"@esbuild/openharmony-arm64": "0.27.3",
"@esbuild/sunos-x64": "0.27.3",
"@esbuild/win32-arm64": "0.27.3",
"@esbuild/win32-ia32": "0.27.3",
"@esbuild/win32-x64": "0.27.3"
}
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/get-tsconfig": {
"version": "4.13.6",
"resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.6.tgz",
"integrity": "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw==",
"dev": true,
"license": "MIT",
"dependencies": {
"resolve-pkg-maps": "^1.0.0"
},
"funding": {
"url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
}
},
"node_modules/resolve-pkg-maps": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",
"integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"
}
},
"node_modules/tsx": {
"version": "4.21.0",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz",
"integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==",
"dev": true,
"license": "MIT",
"dependencies": {
"esbuild": "~0.27.0",
"get-tsconfig": "^4.7.5"
},
"bin": {
"tsx": "dist/cli.mjs"
},
"engines": {
"node": ">=18.0.0"
},
"optionalDependencies": {
"fsevents": "~2.3.3"
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici-types": {
"version": "7.18.2",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
"integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
"dev": true,
"license": "MIT"
}
}
}

21
tui/package.json Normal file
View File

@@ -0,0 +1,21 @@
{
"name": "sybil-tui",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "tsx src/index.ts",
"build": "tsc -p tsconfig.json",
"start": "node dist/index.js",
"typecheck": "tsc --noEmit -p tsconfig.json"
},
"dependencies": {
"blessed": "^0.1.81"
},
"devDependencies": {
"@types/blessed": "^0.1.25",
"@types/node": "^25.0.10",
"tsx": "^4.21.0",
"typescript": "^5.9.3"
}
}

272
tui/src/api.ts Normal file
View File

@@ -0,0 +1,272 @@
import type {
ChatDetail,
ChatSummary,
CompletionRequestMessage,
CompletionStreamHandlers,
ModelCatalogResponse,
Provider,
SearchDetail,
SearchRunRequest,
SearchStreamHandlers,
SearchSummary,
SessionStatus,
} from "./types.js";
type RequestOptions = {
method?: "GET" | "POST" | "PATCH" | "DELETE";
body?: unknown;
signal?: AbortSignal;
headers?: Record<string, string>;
};
export class SybilApiClient {
private readonly baseUrl: string;
private readonly token: string | null;
constructor(baseUrl: string, token: string | null) {
this.baseUrl = baseUrl;
this.token = token;
}
async verifySession() {
return this.request<SessionStatus>("/v1/auth/session");
}
async listModels() {
return this.request<ModelCatalogResponse>("/v1/models");
}
async listChats() {
const data = await this.request<{ chats: ChatSummary[] }>("/v1/chats");
return data.chats;
}
async createChat(title?: string) {
const data = await this.request<{ chat: ChatSummary }>("/v1/chats", {
method: "POST",
body: { title },
});
return data.chat;
}
async getChat(chatId: string) {
const data = await this.request<{ chat: ChatDetail }>(`/v1/chats/${chatId}`);
return data.chat;
}
async suggestChatTitle(body: { chatId: string; content: string }) {
const data = await this.request<{ chat: ChatSummary }>("/v1/chats/title/suggest", {
method: "POST",
body,
});
return data.chat;
}
async deleteChat(chatId: string) {
await this.request<{ deleted: true }>(`/v1/chats/${chatId}`, { method: "DELETE" });
}
async listSearches() {
const data = await this.request<{ searches: SearchSummary[] }>("/v1/searches");
return data.searches;
}
async createSearch(body?: { title?: string; query?: string }) {
const data = await this.request<{ search: SearchSummary }>("/v1/searches", {
method: "POST",
body: body ?? {},
});
return data.search;
}
async getSearch(searchId: string) {
const data = await this.request<{ search: SearchDetail }>(`/v1/searches/${searchId}`);
return data.search;
}
async deleteSearch(searchId: string) {
await this.request<{ deleted: true }>(`/v1/searches/${searchId}`, { method: "DELETE" });
}
async runCompletionStream(
body: {
chatId: string;
provider: Provider;
model: string;
messages: CompletionRequestMessage[];
},
handlers: CompletionStreamHandlers,
options?: { signal?: AbortSignal }
) {
await this.runSse(
"/v1/chat-completions/stream",
body,
{
meta: handlers.onMeta,
tool_call: handlers.onToolCall,
delta: handlers.onDelta,
done: handlers.onDone,
error: handlers.onError,
},
options
);
}
async runSearchStream(
searchId: string,
body: SearchRunRequest,
handlers: SearchStreamHandlers,
options?: { signal?: AbortSignal }
) {
await this.runSse(
`/v1/searches/${searchId}/run/stream`,
body,
{
search_results: handlers.onSearchResults,
search_error: handlers.onSearchError,
answer: handlers.onAnswer,
answer_error: handlers.onAnswerError,
done: handlers.onDone,
error: handlers.onError,
},
options
);
}
private async request<T>(path: string, options?: RequestOptions): Promise<T> {
const headers = new Headers(options?.headers ?? {});
const hasBody = options?.body !== undefined;
if (hasBody && !headers.has("Content-Type")) {
headers.set("Content-Type", "application/json");
}
if (this.token) {
headers.set("Authorization", `Bearer ${this.token}`);
}
const init: RequestInit = {
method: options?.method ?? "GET",
headers,
};
if (hasBody) {
init.body = JSON.stringify(options?.body);
}
if (options?.signal) {
init.signal = options.signal;
}
const response = await fetch(`${this.baseUrl}${path}`, init);
if (!response.ok) {
throw new Error(await this.readErrorMessage(response));
}
return (await response.json()) as T;
}
private async runSse(
path: string,
body: unknown,
handlers: Record<string, ((payload: any) => void) | undefined>,
options?: { signal?: AbortSignal }
) {
const headers = new Headers({
Accept: "text/event-stream",
"Content-Type": "application/json",
});
if (this.token) {
headers.set("Authorization", `Bearer ${this.token}`);
}
const init: RequestInit = {
method: "POST",
headers,
body: JSON.stringify(body),
};
if (options?.signal) {
init.signal = options.signal;
}
const response = await fetch(`${this.baseUrl}${path}`, init);
if (!response.ok) {
throw new Error(await this.readErrorMessage(response));
}
if (!response.body) {
throw new Error("No response stream");
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let eventName = "message";
let dataLines: string[] = [];
const flushEvent = () => {
if (!dataLines.length) {
eventName = "message";
return;
}
const dataText = dataLines.join("\n");
let payload: any = null;
try {
payload = JSON.parse(dataText);
} catch {
payload = { message: dataText };
}
handlers[eventName]?.(payload);
dataLines = [];
eventName = "message";
};
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let newlineIndex = buffer.indexOf("\n");
while (newlineIndex >= 0) {
const rawLine = buffer.slice(0, newlineIndex);
buffer = buffer.slice(newlineIndex + 1);
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
if (!line) {
flushEvent();
} else if (line.startsWith("event:")) {
eventName = line.slice("event:".length).trim();
} else if (line.startsWith("data:")) {
dataLines.push(line.slice("data:".length).trimStart());
}
newlineIndex = buffer.indexOf("\n");
}
}
buffer += decoder.decode();
if (buffer.length) {
const line = buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer;
if (line.startsWith("event:")) {
eventName = line.slice("event:".length).trim();
} else if (line.startsWith("data:")) {
dataLines.push(line.slice("data:".length).trimStart());
}
}
flushEvent();
}
private async readErrorMessage(response: Response) {
const fallback = `${response.status} ${response.statusText}`;
try {
const body = (await response.json()) as { message?: string };
if (typeof body.message === "string" && body.message.trim()) {
return body.message;
}
return fallback;
} catch {
return fallback;
}
}
}

48
tui/src/config.ts Normal file
View File

@@ -0,0 +1,48 @@
import type { Provider } from "./types.js";
const PROVIDERS: Provider[] = ["openai", "anthropic", "xai"];
function normalizeBaseUrl(value: string) {
const trimmed = value.trim();
if (!trimmed) {
throw new Error("SYBIL_TUI_API_BASE_URL cannot be empty");
}
let parsed: URL;
try {
parsed = new URL(trimmed);
} catch {
throw new Error(`Invalid SYBIL_TUI_API_BASE_URL: ${trimmed}`);
}
const normalizedPath = parsed.pathname.replace(/\/+$/, "");
parsed.pathname = normalizedPath || "/";
return parsed.toString().replace(/\/$/, "");
}
function parseProvider(value: string | undefined): Provider {
const trimmed = value?.trim().toLowerCase();
if (!trimmed) return "openai";
if (PROVIDERS.includes(trimmed as Provider)) return trimmed as Provider;
throw new Error(`Invalid SYBIL_TUI_DEFAULT_PROVIDER: ${value}`);
}
function parsePositiveInt(value: string | undefined, fallback: number) {
if (!value?.trim()) return fallback;
const parsed = Number.parseInt(value, 10);
if (!Number.isFinite(parsed) || parsed <= 0) {
throw new Error(`Invalid positive integer value: ${value}`);
}
return parsed;
}
const apiBaseUrlValue =
process.env.SYBIL_TUI_API_BASE_URL?.trim() || process.env.SYBIL_API_BASE_URL?.trim() || "http://127.0.0.1:8787";
export const config = {
apiBaseUrl: normalizeBaseUrl(apiBaseUrlValue),
adminToken: process.env.SYBIL_TUI_ADMIN_TOKEN?.trim() || process.env.SYBIL_ADMIN_TOKEN?.trim() || null,
defaultProvider: parseProvider(process.env.SYBIL_TUI_DEFAULT_PROVIDER),
defaultModel: process.env.SYBIL_TUI_DEFAULT_MODEL?.trim() || null,
searchNumResults: parsePositiveInt(process.env.SYBIL_TUI_SEARCH_NUM_RESULTS, 10),
};

1450
tui/src/index.ts Normal file

File diff suppressed because it is too large Load Diff

140
tui/src/types.ts Normal file
View File

@@ -0,0 +1,140 @@
export type Provider = "openai" | "anthropic" | "xai";
export type ProviderModelInfo = {
models: string[];
loadedAt: string | null;
error: string | null;
};
export type ModelCatalogResponse = {
providers: Record<Provider, ProviderModelInfo>;
};
export type ChatSummary = {
id: string;
title: string | null;
createdAt: string;
updatedAt: string;
initiatedProvider: Provider | null;
initiatedModel: string | null;
lastUsedProvider: Provider | null;
lastUsedModel: string | null;
};
export type SearchSummary = {
id: string;
title: string | null;
query: string | null;
createdAt: string;
updatedAt: string;
};
export type Message = {
id: string;
createdAt: string;
role: "system" | "user" | "assistant" | "tool";
content: string;
name: string | null;
metadata: unknown | null;
};
export type ToolCallEvent = {
toolCallId: string;
name: string;
status: "completed" | "failed";
summary: string;
args: Record<string, unknown>;
startedAt: string;
completedAt: string;
durationMs: number;
error?: string;
resultPreview?: string;
};
export type ChatDetail = {
id: string;
title: string | null;
createdAt: string;
updatedAt: string;
initiatedProvider: Provider | null;
initiatedModel: string | null;
lastUsedProvider: Provider | null;
lastUsedModel: string | null;
messages: Message[];
};
export type SearchResultItem = {
id: string;
createdAt: string;
rank: number;
title: string | null;
url: string;
publishedDate: string | null;
author: string | null;
text: string | null;
highlights: string[] | null;
highlightScores: number[] | null;
score: number | null;
favicon: string | null;
image: string | null;
};
export type SearchDetail = {
id: string;
title: string | null;
query: string | null;
createdAt: string;
updatedAt: string;
requestId: string | null;
latencyMs: number | null;
error: string | null;
answerText: string | null;
answerRequestId: string | null;
answerCitations: Array<{
id?: string;
url?: string;
title?: string | null;
publishedDate?: string | null;
author?: string | null;
text?: string | null;
}> | null;
answerError: string | null;
results: SearchResultItem[];
};
export type SearchRunRequest = {
query?: string;
title?: string;
type?: "auto" | "fast" | "deep" | "instant";
numResults?: number;
includeDomains?: string[];
excludeDomains?: string[];
};
export type CompletionRequestMessage = {
role: "system" | "user" | "assistant" | "tool";
content: string;
name?: string;
};
export type CompletionStreamHandlers = {
onMeta?: (payload: { chatId: string; callId: string; provider: Provider; model: string }) => void;
onToolCall?: (payload: ToolCallEvent) => void;
onDelta?: (payload: { text: string }) => void;
onDone?: (payload: { text: string; usage?: { inputTokens?: number; outputTokens?: number; totalTokens?: number } }) => void;
onError?: (payload: { message: string }) => void;
};
export type SearchStreamHandlers = {
onSearchResults?: (payload: { requestId: string | null; results: SearchResultItem[] }) => void;
onSearchError?: (payload: { error: string }) => void;
onAnswer?: (payload: { answerText: string | null; answerRequestId: string | null; answerCitations: SearchDetail["answerCitations"] }) => void;
onAnswerError?: (payload: { error: string }) => void;
onDone?: (payload: { search: SearchDetail }) => void;
onError?: (payload: { message: string }) => void;
};
export type SessionStatus = {
authenticated: true;
mode: "open" | "token";
};

16
tui/tsconfig.json Normal file
View File

@@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"esModuleInterop": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": ["src/**/*.ts"]
}

View File

@@ -40,6 +40,10 @@ Default dev URL: `http://localhost:5173`
- Composer adapts to the active item:
- Chat sends `POST /v1/chat-completions/stream` (SSE).
- Search sends `POST /v1/searches/:searchId/run/stream` (SSE).
- Keyboard shortcuts:
- `Cmd/Ctrl+J`: start a new chat.
- `Shift+Cmd/Ctrl+J`: start a new search.
- `Cmd/Ctrl+Up/Down`: move through the sidebar list.
Client API contract docs:
- `../docs/api/rest.md`

File diff suppressed because it is too large Load Diff

View File

@@ -12,14 +12,20 @@ type Props = {
export function AuthScreen({ authTokenInput, setAuthTokenInput, isSigningIn, authError, onSignIn }: Props) {
return (
<div className="flex h-full items-center justify-center bg-[radial-gradient(circle_at_top,#45215f_0%,#2a183d_45%,#191227_100%)] p-4">
<div className="w-full max-w-md rounded-2xl border bg-[hsl(276_32%_14%)] p-6 shadow-xl shadow-violet-950/45">
<div className="app-grid-surface flex h-full items-center justify-center p-4">
<div className="glass-panel w-full max-w-md rounded-2xl border border-violet-300/18 p-6">
<div className="mb-6">
<div className="sybil-wordmark bg-[linear-gradient(90deg,#ff8df8,#9a6dff_54%,#67dfff)] bg-clip-text text-3xl text-transparent">
SYBIL
</div>
</div>
<div className="mb-5 flex items-start gap-3">
<div className="rounded-lg bg-violet-200 p-2 text-violet-900">
<div className="rounded-lg border border-cyan-300/25 bg-cyan-400/12 p-2 text-cyan-200">
<ShieldCheck className="h-4 w-4" />
</div>
<div>
<h1 className="text-lg font-semibold">Sign in to Sybil</h1>
<h1 className="text-lg font-semibold text-violet-50">Sign in to Sybil</h1>
<p className="mt-1 text-sm text-muted-foreground">Use your backend admin token.</p>
</div>
</div>
@@ -38,6 +44,7 @@ export function AuthScreen({ authTokenInput, setAuthTokenInput, isSigningIn, aut
value={authTokenInput}
onInput={(event) => setAuthTokenInput(event.currentTarget.value)}
disabled={isSigningIn}
className="bg-[hsl(235_48%_6%_/_0.84)] text-violet-50"
/>
<Button className="w-full" type="submit" disabled={isSigningIn}>
{isSigningIn ? "Signing in..." : "Sign in"}

View File

@@ -0,0 +1,103 @@
import { FileText, Image as ImageIcon, X } from "lucide-preact";
import type { ChatAttachment } from "@/lib/api";
import { cn } from "@/lib/utils";
type Props = {
attachments: ChatAttachment[];
tone?: "composer" | "user" | "assistant";
onRemove?: (id: string) => void;
};
function getTextPreview(value: string) {
const normalized = value.replace(/\r/g, "").trim();
if (!normalized) return "(empty file)";
return normalized.length <= 280 ? normalized : `${normalized.slice(0, 280).trimEnd()}...`;
}
function getSurfaceClasses(tone: Props["tone"]) {
if (tone === "user") {
return "border-white/12 bg-black/16 text-fuchsia-50";
}
if (tone === "assistant") {
return "border-violet-300/16 bg-violet-400/8 text-violet-50";
}
return "border-violet-300/18 bg-background/40 text-violet-50";
}
export function ChatAttachmentList({ attachments, tone = "composer", onRemove }: Props) {
if (!attachments.length) return null;
const surfaceClasses = getSurfaceClasses(tone);
return (
<div className="space-y-2">
{attachments.map((attachment) => {
const isImage = attachment.kind === "image";
return (
<div key={attachment.id} className={cn("overflow-hidden rounded-xl border", surfaceClasses)}>
{isImage ? (
<div className="grid gap-0 md:grid-cols-[minmax(0,220px)_minmax(0,1fr)]">
<div className="border-b border-white/10 bg-black/10 md:border-b-0 md:border-r">
<img src={attachment.dataUrl} alt={attachment.filename} className="block max-h-56 w-full object-cover" />
</div>
<div className="flex min-w-0 flex-col gap-2 p-3">
<div className="flex items-start gap-2">
<span className="mt-0.5 rounded-md border border-white/12 bg-white/5 p-1.5">
<ImageIcon className="h-3.5 w-3.5" />
</span>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{attachment.filename}</p>
<p className="text-xs text-muted-foreground">{attachment.mimeType}</p>
</div>
{onRemove ? (
<button
type="button"
className="rounded-md border border-white/10 p-1 text-muted-foreground transition hover:bg-white/8 hover:text-foreground"
onClick={() => onRemove(attachment.id)}
aria-label={`Remove ${attachment.filename}`}
>
<X className="h-3.5 w-3.5" />
</button>
) : null}
</div>
</div>
</div>
) : (
<div className="p-3">
<div className="flex items-start gap-2">
<span className="mt-0.5 rounded-md border border-white/12 bg-white/5 p-1.5">
<FileText className="h-3.5 w-3.5" />
</span>
<div className="min-w-0 flex-1">
<div className="flex items-start gap-2">
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{attachment.filename}</p>
<p className="text-xs text-muted-foreground">
{attachment.mimeType}
{attachment.truncated ? " · truncated" : ""}
</p>
</div>
{onRemove ? (
<button
type="button"
className="rounded-md border border-white/10 p-1 text-muted-foreground transition hover:bg-white/8 hover:text-foreground"
onClick={() => onRemove(attachment.id)}
aria-label={`Remove ${attachment.filename}`}
>
<X className="h-3.5 w-3.5" />
</button>
) : null}
</div>
<pre className="mt-2 overflow-x-auto rounded-lg border border-white/8 bg-black/16 p-3 text-xs leading-5 text-inherit whitespace-pre-wrap">
{getTextPreview(attachment.text)}
</pre>
</div>
</div>
</div>
)}
</div>
);
})}
</div>
);
}

View File

@@ -1,6 +1,8 @@
import { cn } from "@/lib/utils";
import type { Message } from "@/lib/api";
import { ChatAttachmentList } from "@/components/chat/chat-attachment-list";
import { getMessageAttachments, type Message } from "@/lib/api";
import { MarkdownContent } from "@/components/markdown/markdown-content";
import { Globe2, Link2, Wrench } from "lucide-preact";
type Props = {
messages: Message[];
@@ -8,43 +10,161 @@ type Props = {
isSending: boolean;
};
type ToolLogMetadata = {
kind: "tool_call";
toolCallId?: string;
toolName?: string;
status?: "completed" | "failed";
summary?: string;
args?: Record<string, unknown>;
startedAt?: string;
completedAt?: string;
durationMs?: number;
error?: string | null;
resultPreview?: string | null;
};
function asToolLogMetadata(value: unknown): ToolLogMetadata | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const record = value as Record<string, unknown>;
if (record.kind !== "tool_call") return null;
return record as ToolLogMetadata;
}
function getToolSummary(message: Message, metadata: ToolLogMetadata) {
if (typeof metadata.summary === "string" && metadata.summary.trim()) return metadata.summary.trim();
if (metadata.status === "failed" && typeof metadata.error === "string" && metadata.error.trim()) {
return `Tool failed: ${metadata.error.trim()}`;
}
if (typeof metadata.resultPreview === "string" && metadata.resultPreview.trim()) return metadata.resultPreview.trim();
if (message.content.trim()) return message.content.trim();
const toolName = metadata.toolName?.trim() || message.name?.trim() || "unknown_tool";
return `Ran tool '${toolName}'.`;
}
function getToolLabel(message: Message, metadata: ToolLogMetadata) {
const raw = metadata.toolName?.trim() || message.name?.trim();
if (!raw) return "Tool call";
return raw
.replace(/_/g, " ")
.split(/\s+/)
.filter(Boolean)
.map((word) => `${word.slice(0, 1).toUpperCase()}${word.slice(1)}`)
.join(" ");
}
function getToolIconName(toolName: string | null | undefined) {
const lowered = toolName?.toLowerCase() ?? "";
if (lowered.includes("search")) return "search";
if (lowered.includes("url") || lowered.includes("fetch") || lowered.includes("http")) return "fetch";
return "generic";
}
function formatDuration(durationMs: unknown) {
if (typeof durationMs !== "number" || !Number.isFinite(durationMs) || durationMs <= 0) return null;
return `${Math.round(durationMs)} ms`;
}
function formatToolTimestamp(...values: Array<string | null | undefined>) {
const value = values.find((candidate) => candidate && !Number.isNaN(new Date(candidate).getTime()));
if (!value) return null;
return new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit" }).format(new Date(value));
}
function getToolDetailLabel(message: Message, metadata: ToolLogMetadata, isFailed: boolean) {
return [
isFailed ? "Failed" : "Completed",
formatDuration(metadata.durationMs),
formatToolTimestamp(message.createdAt, metadata.completedAt, metadata.startedAt),
]
.filter(Boolean)
.join(" • ");
}
export function ChatMessagesPanel({ messages, isLoading, isSending }: Props) {
const hasPendingAssistant = messages.some((message) => message.id.startsWith("temp-assistant-") && message.content.trim().length === 0);
return (
<>
{isLoading && messages.length === 0 ? <p className="text-sm text-muted-foreground">Loading messages...</p> : null}
<div className="mx-auto max-w-3xl space-y-6">
<div className="mx-auto max-w-4xl space-y-6">
{messages.map((message) => {
const toolLogMetadata = asToolLogMetadata(message.metadata);
if (message.role === "tool" && toolLogMetadata) {
const iconKind = getToolIconName(toolLogMetadata.toolName ?? message.name);
const Icon = iconKind === "search" ? Globe2 : iconKind === "fetch" ? Link2 : Wrench;
const isFailed = toolLogMetadata.status === "failed";
const toolSummary = getToolSummary(message, toolLogMetadata);
const toolLabel = getToolLabel(message, toolLogMetadata);
const toolDetailLabel = getToolDetailLabel(message, toolLogMetadata, isFailed);
return (
<div key={message.id} className="flex justify-start">
<div
className={cn(
"inline-flex max-w-[85%] min-w-0 items-start gap-3 overflow-hidden rounded-xl border px-3 py-2.5 shadow-[inset_0_1px_0_hsl(180_100%_88%_/_0.06)]",
isFailed
? "border-rose-400/34 bg-[linear-gradient(90deg,hsl(350_72%_44%_/_0.18),hsl(342_66%_9%_/_0.72))]"
: "border-cyan-400/34 bg-[linear-gradient(90deg,hsl(184_89%_21%_/_0.70),hsl(208_66%_12%_/_0.78))]"
)}
title={`${toolSummary}\n${toolLabel}${toolDetailLabel}`}
>
<span
className={cn(
"mt-0.5 flex h-[30px] w-[30px] shrink-0 items-center justify-center rounded-lg border",
isFailed ? "border-rose-400/34 bg-rose-400/13 text-rose-300" : "border-cyan-300/34 bg-cyan-300/13 text-cyan-300"
)}
>
<Icon className="h-4 w-4" />
</span>
<span className="min-w-0 flex-1 space-y-1">
<span className={cn("block truncate text-sm leading-5", isFailed ? "text-rose-200" : "text-violet-50/95")}>
{toolSummary}
</span>
<span className="flex min-w-0 items-center gap-1.5 text-[11px] leading-4">
<span className={cn("min-w-0 truncate font-semibold", isFailed ? "text-rose-300/85" : "text-cyan-200/90")}>
{toolLabel}
</span>
<span className="min-w-0 truncate text-violet-200/64">{toolDetailLabel}</span>
</span>
</span>
</div>
</div>
);
}
const isUser = message.role === "user";
const isPendingAssistant = message.id.startsWith("temp-assistant-") && isSending && message.content.trim().length === 0;
const attachments = getMessageAttachments(message.metadata);
return (
<div key={message.id} className={cn("flex", isUser ? "justify-end" : "justify-start")}>
<div
className={cn(
"max-w-[85%]",
isUser ? "rounded-2xl bg-violet-900/80 px-4 py-3 text-sm leading-6 text-fuchsia-50" : "text-base leading-7 text-fuchsia-100"
"max-w-[85%] space-y-3",
isUser
? "rounded-xl border border-violet-300/24 bg-[linear-gradient(135deg,hsl(258_86%_48%_/_0.86),hsl(278_72%_29%_/_0.86))] px-4 py-3 text-sm leading-6 text-fuchsia-50 shadow-sm"
: "text-base leading-7 text-violet-50"
)}
>
{attachments.length ? <ChatAttachmentList attachments={attachments} tone={isUser ? "user" : "assistant"} /> : null}
{isPendingAssistant ? (
<span className="inline-flex items-center gap-1" aria-label="Assistant is typing" role="status">
<span className="inline-block h-1.5 w-1.5 animate-bounce rounded-full bg-muted-foreground [animation-delay:0ms]" />
<span className="inline-block h-1.5 w-1.5 animate-bounce rounded-full bg-muted-foreground [animation-delay:140ms]" />
<span className="inline-block h-1.5 w-1.5 animate-bounce rounded-full bg-muted-foreground [animation-delay:280ms]" />
</span>
) : (
) : message.content.trim() ? (
<MarkdownContent
markdown={message.content}
className={cn("[&_a]:text-inherit [&_a]:underline", isUser ? "leading-[1.78] text-fuchsia-50" : "leading-[1.82] text-fuchsia-100")}
className={cn("[&_a]:text-inherit [&_a]:underline", isUser ? "leading-[1.78] text-fuchsia-50" : "leading-[1.82] text-violet-50")}
/>
)}
) : null}
</div>
</div>
);
})}
{isSending && !hasPendingAssistant ? (
<div className="flex justify-start">
<div className="max-w-[85%] text-base leading-7 text-fuchsia-100">
<div className="max-w-[85%] text-base leading-7 text-violet-50">
<span className="inline-flex items-center gap-1" aria-label="Assistant is typing" role="status">
<span className="inline-block h-1.5 w-1.5 animate-bounce rounded-full bg-muted-foreground [animation-delay:0ms]" />
<span className="inline-block h-1.5 w-1.5 animate-bounce rounded-full bg-muted-foreground [animation-delay:140ms]" />

View File

@@ -1,6 +1,6 @@
import { useMemo } from "preact/hooks";
import DOMPurify from "dompurify";
import { marked } from "marked";
import { marked, Renderer } from "marked";
import { cn } from "@/lib/utils";
type MarkdownMode = "default" | "citationTokens";
@@ -21,8 +21,15 @@ function replaceMarkdownLinksWithCitationTokens(markdown: string, resolveCitatio
});
}
const markdownRenderer = new Renderer();
const renderTable = markdownRenderer.table.bind(markdownRenderer);
markdownRenderer.table = (token) => {
return `<div class="md-table-scroll">${renderTable(token)}</div>`;
};
function renderMarkdown(markdown: string) {
const rawHtml = marked.parse(markdown, { gfm: true, breaks: true }) as string;
const rawHtml = marked.parse(markdown, { gfm: true, breaks: true, renderer: markdownRenderer }) as string;
return DOMPurify.sanitize(rawHtml, { ADD_ATTR: ["class", "target", "rel"] });
}

View File

@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "preact/hooks";
import type { SearchDetail } from "@/lib/api";
import { MarkdownContent } from "@/components/markdown/markdown-content";
import { cn } from "@/lib/utils";
import { MessageSquare } from "lucide-preact";
function formatHost(url: string) {
try {
@@ -29,6 +30,8 @@ type Props = {
className?: string;
enableKeyboardNavigation?: boolean;
openLinksInNewTab?: boolean;
isStartingChat?: boolean;
onStartChat?: () => void;
};
export function SearchResultsPanel({
@@ -38,6 +41,8 @@ export function SearchResultsPanel({
className,
enableKeyboardNavigation = false,
openLinksInNewTab = true,
isStartingChat = false,
onStartChat,
}: Props) {
const ANSWER_COLLAPSED_HEIGHT_CLASS = "h-[3rem]";
const [isAnswerExpanded, setIsAnswerExpanded] = useState(false);
@@ -133,23 +138,37 @@ export function SearchResultsPanel({
const isAnswerLoading = isRunning && !hasAnswerText;
const hasCitations = citationEntries.length > 0;
const isExpandable = hasAnswerText && (canExpandAnswer || hasCitations);
const canStartChat = !!search && !isLoading && !isRunning && !isStartingChat && (!!search.answerText || search.results.length > 0);
return (
<div className={className ?? "mx-auto w-full max-w-4xl"}>
{search?.query ? (
<div className="mb-5">
<p className="text-sm text-muted-foreground">Results for</p>
<h2 className="mt-1 break-words text-xl font-semibold">{search.query}</h2>
<p className="mt-1 text-xs text-muted-foreground">
{search.results.length} result{search.results.length === 1 ? "" : "s"}
{search.latencyMs ? `${search.latencyMs} ms` : ""}
</p>
<div className="mb-5 flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
<div className="min-w-0">
<p className="text-sm text-muted-foreground">Results for</p>
<h2 className="mt-1 break-words text-xl font-semibold text-violet-50">{search.query}</h2>
<p className="mt-1 text-xs text-muted-foreground">
{search.results.length} result{search.results.length === 1 ? "" : "s"}
{search.latencyMs ? `${search.latencyMs} ms` : ""}
</p>
</div>
{onStartChat ? (
<button
type="button"
className="inline-flex h-10 shrink-0 items-center justify-center gap-2 rounded-lg border border-violet-300/24 bg-violet-300/10 px-3 text-sm font-medium text-violet-50 transition hover:bg-violet-300/16 disabled:cursor-not-allowed disabled:opacity-50"
onClick={onStartChat}
disabled={!canStartChat}
>
<MessageSquare className="h-4 w-4" />
{isStartingChat ? "Starting chat..." : "Chat with results"}
</button>
) : null}
</div>
) : null}
{(isRunning || !!search?.answerText || !!search?.answerError) && (
<section className="mb-6 rounded-xl border border-violet-400/35 bg-[hsl(276_31%_15%)] p-4">
<p className="text-xs font-semibold uppercase tracking-wide text-violet-300/90">Answer</p>
<section className="mb-6 rounded-xl border border-violet-300/24 bg-[linear-gradient(135deg,hsl(240_46%_8%_/_0.94),hsl(260_40%_12%_/_0.88))] p-4 shadow-[inset_0_1px_0_hsl(255_100%_92%_/_0.06)]">
<p className="text-xs font-semibold uppercase text-violet-300/90">Answer</p>
{(isAnswerLoading || hasAnswerText) ? (
<div className="mt-2">
<div className="relative">
@@ -172,7 +191,7 @@ export function SearchResultsPanel({
)}
</div>
{!isAnswerExpanded && (isExpandable || isAnswerLoading) ? (
<div className="pointer-events-none absolute inset-x-0 bottom-0 h-7 bg-gradient-to-t from-[hsl(276_31%_15%)] to-transparent" />
<div className="pointer-events-none absolute inset-x-0 bottom-0 h-7 bg-gradient-to-t from-[hsl(252_42%_10%)] to-transparent" />
) : null}
</div>
<div className="mt-2 h-5">
@@ -199,7 +218,7 @@ export function SearchResultsPanel({
href={citation.href}
target={openLinksInNewTab ? "_blank" : undefined}
rel={openLinksInNewTab ? "noreferrer" : undefined}
className="max-w-full truncate rounded-md border border-violet-400/40 px-2 py-1 text-xs text-violet-200 hover:bg-violet-500/20"
className="max-w-full truncate rounded-md border border-violet-300/28 bg-violet-300/8 px-2 py-1 text-xs text-violet-200 hover:bg-violet-500/20"
>
<span className="mr-1 rounded bg-violet-900/70 px-1 py-0.5 text-[10px] text-violet-100">{citation.index}</span>
{citation.label}
@@ -225,23 +244,23 @@ export function SearchResultsPanel({
<article
key={result.id}
className={cn(
"rounded-lg border border-border bg-[hsl(276_30%_13%)] px-4 py-4 shadow-sm transition-colors",
index === activeResultIndex && "border-violet-300 ring-1 ring-violet-300/80"
"rounded-lg border border-violet-300/16 bg-[linear-gradient(135deg,hsl(238_44%_7%_/_0.92),hsl(250_34%_10%_/_0.86))] px-4 py-4 shadow-sm transition-colors",
index === activeResultIndex && "border-violet-300/55 ring-1 ring-violet-300/70"
)}
>
<p className="truncate text-xs text-violet-300/85">{formatHost(result.url)}</p>
<p className="truncate text-xs text-cyan-200/85">{formatHost(result.url)}</p>
<a
href={result.url}
target={openLinksInNewTab ? "_blank" : undefined}
rel={openLinksInNewTab ? "noreferrer" : undefined}
className="mt-1 block break-words text-lg font-medium text-violet-300 hover:underline"
className="mt-1 block break-words text-lg font-medium text-violet-200 hover:underline"
>
{result.title || result.url}
</a>
{(result.publishedDate || result.author) && (
<p className="mt-1 text-xs text-muted-foreground">{[result.publishedDate, result.author].filter(Boolean).join(" • ")}</p>
)}
{result.url ? <p className="mt-2 break-all text-sm leading-6 text-violet-100/90">{result.url}</p> : null}
{result.url ? <p className="mt-2 break-all text-sm leading-6 text-violet-100/82">{result.url}</p> : null}
</article>
);
})}

View File

@@ -3,14 +3,16 @@ import type { JSX } from "preact";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors disabled:pointer-events-none disabled:opacity-50 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground shadow hover:bg-primary/90",
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
outline: "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
ghost: "hover:bg-accent hover:text-accent-foreground",
default:
"border border-violet-300/35 bg-[linear-gradient(135deg,hsl(252_92%_64%_/_0.95),hsl(274_84%_35%_/_0.95))] text-primary-foreground shadow-sm hover:border-violet-200/55 hover:brightness-110",
secondary:
"border border-violet-300/18 bg-secondary/78 text-secondary-foreground shadow-[inset_0_1px_0_hsl(255_100%_92%_/_0.06)] hover:border-violet-300/32 hover:bg-secondary",
outline: "border border-input bg-background/76 hover:border-violet-300/45 hover:bg-accent/65 hover:text-accent-foreground",
ghost: "text-muted-foreground hover:bg-accent/65 hover:text-accent-foreground",
},
size: {
default: "h-10 px-4 py-2",

View File

@@ -5,7 +5,7 @@ export function Input({ className, ...props }: JSX.InputHTMLAttributes<HTMLInput
return (
<input
className={cn(
"flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
"flex h-9 w-full rounded-md border border-input bg-background/78 px-3 py-1 text-sm shadow-sm transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
className
)}
{...props}

View File

@@ -5,7 +5,7 @@ export function Textarea({ className, ...props }: JSX.TextareaHTMLAttributes<HTM
return (
<textarea
className={cn(
"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
"flex min-h-[80px] w-full rounded-md border border-input bg-background/78 px-3 py-2 text-sm shadow-sm transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
className
)}
{...props}

View File

@@ -1,26 +1,31 @@
@import url("https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Orbitron:wght@700;800;900&display=swap");
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--background: 282 33% 8%;
--foreground: 300 35% 95%;
--muted: 287 24% 16%;
--muted-foreground: 297 16% 72%;
--border: 287 24% 24%;
--input: 287 24% 24%;
--ring: 264 76% 70%;
--primary: 266 72% 67%;
--primary-foreground: 296 45% 12%;
--secondary: 277 24% 19%;
--secondary-foreground: 302 42% 94%;
--accent: 279 24% 22%;
--accent-foreground: 305 45% 94%;
--radius: 0.65rem;
color-scheme: dark;
--background: 235 45% 4%;
--foreground: 258 36% 96%;
--muted: 246 30% 13%;
--muted-foreground: 247 18% 68%;
--border: 251 35% 20%;
--input: 252 42% 24%;
--ring: 258 92% 70%;
--primary: 264 93% 66%;
--primary-foreground: 265 55% 98%;
--secondary: 244 32% 14%;
--secondary-foreground: 254 38% 94%;
--accent: 188 86% 50%;
--accent-foreground: 230 45% 8%;
--radius: 0.5rem;
}
* {
@apply border-border;
scrollbar-color: hsl(263 92% 68% / 0.42) transparent;
scrollbar-width: thin;
}
html,
@@ -31,14 +36,124 @@ body,
body {
@apply bg-background text-foreground antialiased;
background-image: radial-gradient(circle at top, hsl(274 42% 18%) 0%, hsl(271 34% 12%) 42%, hsl(266 32% 7%) 100%);
font-family: "Soehne", "Avenir Next", "Segoe UI", sans-serif;
background-color: hsl(var(--background));
background-image:
linear-gradient(90deg, hsl(187 92% 49% / 0.08), transparent 24%, hsl(264 92% 59% / 0.12) 74%, transparent),
linear-gradient(180deg, hsl(250 60% 16% / 0.68), hsl(235 45% 4%) 48%, hsl(235 54% 3%));
font-family: "Inter", "Avenir Next", "Segoe UI", sans-serif;
}
button,
input,
select,
textarea {
font: inherit;
color-scheme: dark;
}
::selection {
background: hsl(264 92% 68% / 0.45);
color: hsl(258 36% 98%);
}
.sybil-wordmark {
font-family: "Orbitron", "Inter", sans-serif;
font-weight: 900;
letter-spacing: 0;
line-height: 1;
}
.app-grid-surface {
background-image:
linear-gradient(hsl(244 48% 20% / 0.18) 1px, transparent 1px),
linear-gradient(90deg, hsl(244 48% 20% / 0.14) 1px, transparent 1px);
background-size: 48px 48px;
}
.glass-panel {
background:
linear-gradient(180deg, hsl(243 42% 12% / 0.88), hsl(236 48% 5% / 0.92)),
hsl(236 48% 6%);
box-shadow:
inset 0 1px 0 hsl(252 90% 86% / 0.08),
0 14px 36px hsl(240 80% 2% / 0.28);
}
.md-content {
word-break: break-word;
}
.md-table-scroll {
max-width: 100%;
margin: 0.35rem 0 1rem;
overflow-x: auto;
overflow-y: hidden;
border: 1px solid hsl(var(--border) / 0.86);
border-radius: 0.625rem;
background: hsl(246 34% 10% / 0.76);
box-shadow: inset 0 1px 0 hsl(258 80% 88% / 0.06);
}
.md-content table {
width: max-content;
min-width: 100%;
border-collapse: separate;
border-spacing: 0;
font-size: 0.94em;
line-height: 1.48;
}
.md-table-scroll::-webkit-scrollbar {
height: 0.45rem;
}
.md-table-scroll::-webkit-scrollbar-thumb {
border-radius: 9999px;
background: hsl(263 78% 72% / 0.34);
}
.md-content th,
.md-content td {
padding: 0.48rem 0.7rem;
border-right: 1px solid hsl(var(--border) / 0.72);
border-bottom: 1px solid hsl(var(--border) / 0.7);
text-align: left;
vertical-align: top;
word-break: normal;
}
.md-content th:last-child,
.md-content td:last-child {
border-right: 0;
}
.md-content tr:last-child td {
border-bottom: 0;
}
.md-content th {
background: hsl(251 40% 15% / 0.92);
color: hsl(258 36% 98%);
font-weight: 700;
white-space: nowrap;
}
.md-content td {
color: hsl(258 34% 94% / 0.96);
}
.md-content tbody tr:nth-child(odd) td {
background: hsl(242 32% 10% / 0.58);
}
.md-content tbody tr:nth-child(even) td {
background: hsl(252 36% 13% / 0.46);
}
.md-content tbody tr:hover td {
background: hsl(263 46% 20% / 0.48);
}
.md-content p + p {
margin-top: 0.85rem;
}

View File

@@ -23,6 +23,20 @@ export type Message = {
role: "system" | "user" | "assistant" | "tool";
content: string;
name: string | null;
metadata: unknown | null;
};
export type ToolCallEvent = {
toolCallId: string;
name: string;
status: "completed" | "failed";
summary: string;
args: Record<string, unknown>;
startedAt: string;
completedAt: string;
durationMs: number;
error?: string;
resultPreview?: string;
};
export type ChatDetail = {
@@ -76,6 +90,27 @@ export type SearchDetail = {
results: SearchResultItem[];
};
export type ChatImageAttachment = {
kind: "image";
id: string;
filename: string;
mimeType: "image/png" | "image/jpeg";
sizeBytes: number;
dataUrl: string;
};
export type ChatTextAttachment = {
kind: "text";
id: string;
filename: string;
mimeType: string;
sizeBytes: number;
text: string;
truncated?: boolean;
};
export type ChatAttachment = ChatImageAttachment | ChatTextAttachment;
export type SearchRunRequest = {
query?: string;
title?: string;
@@ -89,6 +124,7 @@ export type CompletionRequestMessage = {
role: "system" | "user" | "assistant" | "tool";
content: string;
name?: string;
attachments?: ChatAttachment[];
};
export type Provider = "openai" | "anthropic" | "xai";
@@ -112,12 +148,20 @@ type CompletionResponse = {
};
type CompletionStreamHandlers = {
onMeta?: (payload: { chatId: string; callId: string; provider: Provider; model: string }) => void;
onMeta?: (payload: { chatId: string | null; callId: string | null; provider: Provider; model: string }) => void;
onToolCall?: (payload: ToolCallEvent) => void;
onDelta?: (payload: { text: string }) => void;
onDone?: (payload: { text: string; usage?: { inputTokens?: number; outputTokens?: number; totalTokens?: number } }) => void;
onError?: (payload: { message: string }) => void;
};
type CreateChatRequest = {
title?: string;
provider?: Provider;
model?: string;
messages?: CompletionRequestMessage[];
};
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL ?? "/api";
const ENV_ADMIN_TOKEN = (import.meta.env.VITE_ADMIN_TOKEN as string | undefined)?.trim() || null;
let authToken: string | null = ENV_ADMIN_TOKEN;
@@ -173,10 +217,11 @@ export async function listModels() {
return api<ModelCatalogResponse>("/v1/models");
}
export async function createChat(title?: string) {
export async function createChat(input?: string | CreateChatRequest) {
const body = typeof input === "string" ? { title: input } : input ?? {};
const data = await api<{ chat: ChatSummary }>("/v1/chats", {
method: "POST",
body: JSON.stringify({ title }),
body: JSON.stringify(body),
});
return data.chat;
}
@@ -224,10 +269,61 @@ export async function getSearch(searchId: string) {
return data.search;
}
export async function createChatFromSearch(searchId: string, body?: { title?: string }) {
const data = await api<{ chat: ChatSummary }>(`/v1/searches/${searchId}/chat`, {
method: "POST",
body: JSON.stringify(body ?? {}),
});
return data.chat;
}
export async function deleteSearch(searchId: string) {
await api<{ deleted: true }>(`/v1/searches/${searchId}`, { method: "DELETE" });
}
export function getMessageAttachments(metadata: unknown): ChatAttachment[] {
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
const attachments = (metadata as Record<string, unknown>).attachments;
if (!Array.isArray(attachments)) return [];
const parsed: ChatAttachment[] = [];
for (const entry of attachments) {
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
const record = entry as Record<string, unknown>;
const kind = record.kind;
const id = typeof record.id === "string" ? record.id : "";
const filename = typeof record.filename === "string" ? record.filename : "";
const mimeType = typeof record.mimeType === "string" ? record.mimeType : "";
const sizeBytes = typeof record.sizeBytes === "number" ? record.sizeBytes : 0;
if (kind === "image" && typeof record.dataUrl === "string" && (mimeType === "image/png" || mimeType === "image/jpeg")) {
parsed.push({
kind,
id,
filename,
mimeType,
sizeBytes,
dataUrl: record.dataUrl,
} satisfies ChatImageAttachment);
continue;
}
if (kind === "text" && typeof record.text === "string") {
parsed.push({
kind,
id,
filename,
mimeType,
sizeBytes,
text: record.text,
truncated: record.truncated === true,
} satisfies ChatTextAttachment);
}
}
return parsed;
}
type RunSearchStreamHandlers = {
onSearchResults?: (payload: { requestId: string | null; results: SearchResultItem[] }) => void;
onSearchError?: (payload: { error: string }) => void;
@@ -355,7 +451,8 @@ export async function runCompletion(body: {
export async function runCompletionStream(
body: {
chatId: string;
chatId?: string | null;
persist?: boolean;
provider: Provider;
model: string;
messages: CompletionRequestMessage[];
@@ -415,6 +512,7 @@ export async function runCompletionStream(
}
if (eventName === "meta") handlers.onMeta?.(payload);
else if (eventName === "tool_call") handlers.onToolCall?.(payload);
else if (eventName === "delta") handlers.onDelta?.(payload);
else if (eventName === "done") handlers.onDone?.(payload);
else if (eventName === "error") handlers.onError?.(payload);

View File

@@ -1 +1 @@
{"root":["./src/App.tsx","./src/main.tsx","./src/root-router.tsx","./src/vite-env.d.ts","./src/components/auth/auth-screen.tsx","./src/components/chat/chat-messages-panel.tsx","./src/components/markdown/markdown-content.tsx","./src/components/search/search-results-panel.tsx","./src/components/ui/button.tsx","./src/components/ui/input.tsx","./src/components/ui/scroll-area.tsx","./src/components/ui/separator.tsx","./src/components/ui/textarea.tsx","./src/hooks/use-session-auth.ts","./src/lib/api.ts","./src/lib/utils.ts","./src/pages/search-route-page.tsx"],"version":"5.9.3"}
{"root":["./src/app.tsx","./src/main.tsx","./src/root-router.tsx","./src/vite-env.d.ts","./src/components/auth/auth-screen.tsx","./src/components/chat/chat-attachment-list.tsx","./src/components/chat/chat-messages-panel.tsx","./src/components/markdown/markdown-content.tsx","./src/components/search/search-results-panel.tsx","./src/components/ui/button.tsx","./src/components/ui/input.tsx","./src/components/ui/scroll-area.tsx","./src/components/ui/separator.tsx","./src/components/ui/textarea.tsx","./src/hooks/use-session-auth.ts","./src/lib/api.ts","./src/lib/utils.ts","./src/pages/search-route-page.tsx"],"version":"5.9.3"}