3 Commits
Author SHA1 Message Date
WHC e0b0eddf3a v0.8.6: general mode, clipboard text, PDF text extraction
ci / tcc-check (push) Successful in 59s
ci / linux (aarch64, 0) (push) Successful in 19m11s
ci / linux (x86, 1) (push) Successful in 11m31s
ci / linux (x86_64, 1) (push) Successful in 11m11s
ci / windows (push) Successful in 9m24s
Working mode: --mode coding|general (CST_MODE, settings.json, /mode,
WebUI run settings). general swaps the default framing for a general
assistant one -- workflow, safety notes, tool wording (run_shell, the
subagents) -- and /status shows it; minimal (the paper profile) stays
byte-frozen. The prompt state carries the mode so a switch leaves a
system note in history.

Clipboard: clipboard_read / clipboard_write tools (16 MiB cap read,
default 64 KiB window; writing is a WRITE permission with a preview) on
pbcopy / wl-copy / xclip / pbpaste / wl-paste / xclip and the Win32
clipboard. In the TUI, /attach paste falls back to clipboard text when
there is no image on it.

PDF: a dependency-free text extractor (src/pdf_text.c): inflate,
Flate/ASCIIHex/ASCII85, PNG/TIFF predictors, layout-independent object
scan, object streams, page tree walk with inherited resources, content
lexer (Tj/TJ/'/" and the Td/TD/T*/Tm spacing heuristics), per-font
ToUnicode CMaps and inline images skipped. Encrypted files and pages
with no text layer are refused with the reason.

Attachments: /attach (a path or files dropped on the terminal) now take
images, PDFs and text. A PDF is stored as its text layer with the mime
still saying application/pdf and its page count; anything else has to be
UTF-8 text. Documents travel inline as text parts, so CST_NO_IMAGES and
text-only models no longer drop them, while images keep their old path.

Tests: test_pdf_text (plain, bare and zlib-framed Flate, inline image,
CID + ToUnicode, object stream, error paths), documents in test_attach,
inlined documents in test_llm_body, mode in test_config.
2026-10-11 11:09:39 +08:00
WHC 50abcf1a91 build: finish cross-platform release tooling
ci / tcc-check (push) Successful in 1m9s
ci / linux (aarch64, 0) (push) Failing after 58m44s
ci / linux (x86, 1) (push) Successful in 13m47s
ci / linux (x86_64, 1) (push) Failing after 1h0m2s
ci / windows (push) Successful in 10m46s
2026-10-10 16:21:00 +08:00
WHC 9bf7707912 v0.8.5: WebUI process timeline, Gemini-style images, aligned layout
ci / linux (clang) (push) Successful in 6m15s
ci / linux (gcc) (push) Successful in 7m14s
ci / musl (push) Successful in 7m14s
ci / windows-cross (push) Successful in 11m4s
Process timeline: a run of consecutive thinking and tool calls is one
block that folds to a single line ("思考 4 次 · 工具 6 次"; while running
it shows the current action) and opens into a compact timeline, one row
per thought or call. Visible text, a note or the next prompt closes the
block; history and the live stream follow the same rule. show_thinking
now also applies while streaming instead of forcing thoughts open.

Layout: the avatar gutter and the flex-wrap that dropped it under long
answers are gone, so answer, process blocks, notes and composer share one
left edge. The text column and composer are both 720px (--content); the
rail and run panel grow with clamp() on wide screens. A rebuild after
each turn no longer replays every entrance animation, and the turn time
survives it. Message actions are icon buttons and only appear under text.

Images: a prompt's images sit above the bubble, right-aligned (one keeps
its shape, several are 152px rounded tiles) and open in a lightbox (Esc,
arrow keys). Images uploaded from the page show as thumbnails over the
composer and appear on the prompt as soon as it is sent.

Also: ?theme= is no longer overridden by app.js, the user bubble is
visible in the light theme, and the narrow top bar no longer wraps.
2026-10-10 14:54:36 +08:00
53 changed files with 4750 additions and 502 deletions
+101 -63
View File
@@ -11,13 +11,11 @@ concurrency:
cancel-in-progress: true
jobs:
linux:
# Verification: TinyCC builds and tests everything in seconds. tcc warns on
# `#pragma GCC`, so no -Werror here; the gcc release builds below carry it.
tcc-check:
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
cc: [gcc, clang]
steps:
- name: Checkout
env:
@@ -34,21 +32,14 @@ jobs:
$SUDO bash scripts/ci_pkg_mirror.sh
$SUDO apt-get update
$SUDO apt-get install -y --no-install-recommends \
build-essential clang cmake pkg-config python3 \
build-essential pkg-config python3 curl ca-certificates \
libcurl4-openssl-dev libncurses-dev
- name: Build (warnings are errors)
run: make CC=${{ matrix.cc }} CFLAGS="-std=c11 -Wall -Wextra -O2 -g -Werror" -j"$(nproc)"
- name: Build TinyCC
run: bash scripts/ci_tcc.sh
- name: Build
run: make CC=tcc AR=ar CFLAGS="-std=c11 -Wall -O2 -g" -j"$(nproc)"
- name: Unit tests
run: |
# Same -Werror as the build step so undeclared libc helpers cannot
# silently return int and truncate pointers (see test_subagent).
make CC=${{ matrix.cc }} \
CFLAGS="-std=c11 -Wall -Wextra -O2 -g -Werror" check
- name: CMake build + ctest
run: |
cmake -B build -DCMAKE_C_COMPILER=${{ matrix.cc }} -DCST_BUILD_TUI=ON
cmake --build build -j"$(nproc)"
ctest --test-dir build --output-on-failure
run: make CC=tcc AR=ar CFLAGS="-std=c11 -Wall -O2 -g" check
- name: Smoke test
run: |
./cst-agent --help
@@ -57,39 +48,22 @@ jobs:
- name: WebUI end-to-end (recorded stream, no API key)
run: sh scripts/e2e_webui.sh
musl:
# Release: static musl binaries, gcc with -Werror.
# dist/cst-agent-VERSION-linux-ARCH.tar.gz
linux:
needs: tcc-check
runs-on: ubuntu-latest
timeout-minutes: 30
container: alpine:3.20
steps:
- name: Install tools + mirror
run: |
sed -i 's#https\?://dl-cdn.alpinelinux.org/alpine#https://mirrors.tuna.tsinghua.edu.cn/alpine#g' \
/etc/apk/repositories
apk add --no-cache curl git bash
- name: Checkout
env:
GITHUB_SERVER_URL: ${{ github.server_url }}
GITHUB_REPOSITORY: ${{ github.repository }}
GITHUB_SHA: ${{ github.sha }}
run: |
curl -fsSL "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/raw/commit/$GITHUB_SHA/scripts/ci_checkout.sh" \
-o /tmp/ci_checkout.sh
bash /tmp/ci_checkout.sh
- name: Install build dependencies
run: |
# linux-headers provides linux/audit.h for the seccomp probe path
apk add --no-cache build-base pkgconf curl-dev ncurses-dev \
linux-headers git nodejs bash python3
- name: Build + unit tests
run: |
make CFLAGS="-std=c11 -Wall -Wextra -O2 -Werror" -j"$(nproc)"
make check
# MinGW-w64 UCRT cross build → dist/cst-agent-*-windows-x86_64.zip
windows-cross:
runs-on: ubuntu-latest
timeout-minutes: 120
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
include:
- arch: x86_64
check: 1
- arch: x86
check: 1
- arch: aarch64
check: 0
steps:
- name: Checkout
env:
@@ -105,20 +79,29 @@ jobs:
SUDO=$(command -v sudo || true)
$SUDO bash scripts/ci_pkg_mirror.sh
$SUDO apt-get update
# ncurses-bin/-term: tic, infocmp and the fallback terminal entries
$SUDO apt-get install -y --no-install-recommends \
ca-certificates curl git cmake ninja-build make pkg-config \
python3 zip unzip perl xz-utils
- name: Cross-build Windows zip
run: bash scripts/ci_windows_cross.sh
- name: Verify zip
build-essential cmake ninja-build pkg-config python3 perl \
curl ca-certificates xz-utils bzip2 file ncurses-bin ncurses-term
if [ "${{ matrix.arch }}" = aarch64 ]; then
$SUDO apt-get install -y --no-install-recommends qemu-user-static
fi
- name: Build (static, -Werror)
env:
CST_LINUX_CHECK: ${{ matrix.check }}
run: bash scripts/package_linux.sh ${{ matrix.arch }}
- name: Smoke test
run: |
ls -lah dist/windows-x86_64/
ls -lah dist/cst-agent-*-windows-x86_64.zip
cat dist/cst-agent-*-windows-x86_64.zip.sha256
unzip -l dist/cst-agent-*-windows-x86_64.zip | head -20
# Auto-publish to Gitea Releases (v$CST_VERSION from include/cst_version.h).
# Prefer repo secret RELEASE_TOKEN (write:repository); fall back to the
# job token. Skipped on pull_request and when no token is available.
d=$(ls -d dist/cst-agent-*-linux-${{ matrix.arch }})
file "$d/cst-agent"
run=""
[ "${{ matrix.arch }}" = aarch64 ] && run=qemu-aarch64-static
$run "$d/cst-agent" --version
$run "$d/cst-agent" --help >/dev/null
$run "$d/cst-agent" --workspace "$PWD" --list-sessions
cat dist/cst-agent-*-linux-${{ matrix.arch }}.tar.gz.sha256
# Release vVERSION (from include/cst_version.h) on Gitea. Prefer repo
# secret RELEASE_TOKEN (write:repository); fall back to the job token.
- name: Publish Gitea Release
if: github.event_name == 'push'
env:
@@ -134,4 +117,59 @@ jobs:
echo "::warning::no RELEASE_TOKEN / GITHUB_TOKEN; skip auto-release"
exit 0
fi
bash scripts/release_windows.sh
bash scripts/release.sh dist/cst-agent-*-linux-${{ matrix.arch }}.tar.gz
# Release: mingw-w64 UCRT gcc (Debian trixie) with -Werror.
# dist/cst-agent-VERSION-windows-x86_64.zip and -setup.exe (NSIS)
windows:
needs: tcc-check
runs-on: ubuntu-latest
timeout-minutes: 120
container: debian:trixie
steps:
- name: Install tools
run: |
# No CA certificates in the image yet, so the mirror is plain http.
sed -i 's#https\?://deb.debian.org#http://mirrors.tuna.tsinghua.edu.cn#g' \
/etc/apt/sources.list.d/debian.sources
apt-get update
apt-get install -y --no-install-recommends \
ca-certificates curl git build-essential cmake ninja-build make \
pkg-config python3 perl zip unzip xz-utils patch file \
gcc-mingw-w64-ucrt64 binutils-mingw-w64-ucrt64 nsis
- name: Checkout
env:
GITHUB_SERVER_URL: ${{ github.server_url }}
GITHUB_REPOSITORY: ${{ github.repository }}
GITHUB_SHA: ${{ github.sha }}
run: |
curl -fsSL "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/raw/commit/$GITHUB_SHA/scripts/ci_checkout.sh" \
-o /tmp/ci_checkout.sh
bash /tmp/ci_checkout.sh
- name: Cross-build zip and installer
env:
CST_WIN_CFLAGS: -Wall -Wextra -Werror
run: bash scripts/ci_windows_cross.sh
- name: Verify
run: |
ls -lah dist/windows-x86_64/
file dist/windows-x86_64/cst-agent.exe dist/cst-agent-*-windows-x86_64-setup.exe
cat dist/cst-agent-*-windows-x86_64.zip.sha256 dist/cst-agent-*-windows-x86_64-setup.exe.sha256
unzip -l dist/cst-agent-*-windows-x86_64.zip
- name: Publish Gitea Release
if: github.event_name == 'push'
env:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CST_GITEA: ${{ github.server_url }}
CST_REPO: ${{ github.repository }}
GITHUB_REF: ${{ github.ref }}
CI: "true"
run: |
export GITEA_TOKEN="${RELEASE_TOKEN:-${GITHUB_TOKEN:-}}"
if [[ -z "${GITEA_TOKEN}" ]]; then
echo "::warning::no RELEASE_TOKEN / GITHUB_TOKEN; skip auto-release"
exit 0
fi
bash scripts/release.sh dist/cst-agent-*-windows-x86_64.zip \
dist/cst-agent-*-windows-x86_64-setup.exe
+3
View File
@@ -26,6 +26,9 @@ third_party/ncurses-*.tar.gz
third_party/busybox-w32/
third_party/busybox-src/
third_party/prefix-mingw/
third_party/prefix-linux-*/
third_party/build-linux-*/
third_party/src/
vendor/sashidown/*.o
vendor/sashidown/src/*.o
vendor/sashidown/libsashidown.a
+13 -3
View File
@@ -95,6 +95,7 @@ set(CST_CORE_SOURCES
src/subagent.c
src/attach.c
src/clipboard.c
src/pdf_text.c
src/session.c
src/tools/tools.c
src/tools/patch.c
@@ -172,9 +173,12 @@ endif()
if(WIN32)
# MinGW has no <regex.h>: musl's TRE engine, UTF-8 aware (vendor/tre-regex)
include_directories(vendor/tre-regex)
list(APPEND CST_CORE_SOURCES
set(_CST_TRE_SOURCES
vendor/tre-regex/regcomp.c vendor/tre-regex/regexec.c
vendor/tre-regex/regerror.c vendor/tre-regex/tre-mem.c)
list(APPEND CST_CORE_SOURCES ${_CST_TRE_SOURCES})
# Upstream code, kept as is: CST_WIN_CFLAGS=-Werror must not apply to it.
set_source_files_properties(${_CST_TRE_SOURCES} PROPERTIES COMPILE_OPTIONS "-w")
endif()
set(CST_SOURCES ${CST_CORE_SOURCES} src/main.c)
@@ -276,7 +280,7 @@ endif()
enable_testing()
set(_CST_SMALL_TESTS test_ctl_frontier test_ctl_heredoc test_json_baseline
test_replay_starvation test_replay_real test_mm_tool test_textsel
test_markdown)
test_pdf_text test_markdown)
foreach(t ${_CST_SMALL_TESTS})
if(t STREQUAL test_textsel)
add_executable(${t} tests/${t}.c src/textsel.c src/os_compat.c src/os_win.c
@@ -284,6 +288,12 @@ foreach(t ${_CST_SMALL_TESTS})
if(WIN32)
target_link_libraries(${t} PRIVATE advapi32 user32)
endif()
elseif(t STREQUAL test_pdf_text)
add_executable(${t} tests/${t}.c src/pdf_text.c src/os_compat.c src/os_win.c
src/util.c)
if(WIN32)
target_link_libraries(${t} PRIVATE advapi32 user32)
endif()
elseif(t STREQUAL test_markdown)
add_executable(${t} tests/${t}.c)
target_include_directories(${t} PRIVATE "${SD_DIR}/include")
@@ -307,7 +317,7 @@ foreach(t ${_CST_SMALL_TESTS})
target_include_directories(${t} PRIVATE include "${CJSON_DIR}")
target_compile_definitions(${t} PRIVATE _GNU_SOURCE)
if(NOT WIN32)
target_link_libraries(${t} PRIVATE m)
target_link_libraries(${t} PRIVATE m Threads::Threads)
endif()
cst_win_exe(${t})
add_test(NAME ${t} COMMAND ${t} WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
+46 -17
View File
@@ -7,6 +7,7 @@ PREFIX ?= /usr/local
DESTDIR ?=
UNAME_S := $(shell uname -s 2>/dev/null)
UNAME_O := $(shell uname -o 2>/dev/null)
comma := ,
# Android (Termux): pthreads live in libc.
PTHREAD_LIBS := -lpthread
@@ -26,6 +27,15 @@ CPPFLAGS += -D_DARWIN_C_SOURCE
endif
PKGC = $(PKG_ENV) $(PKG_CONFIG)
# STATIC=1: fully static link (the musl release builds).
STATIC ?= 0
LINK_STATIC :=
ifeq ($(STATIC),1)
PKGC += --static
LINK_STATIC := -static
endif
LDFLAGS += $(LINK_STATIC)
# Wide-character curses: ncursesw, else ncurses (macOS/BSD build it wide).
CURSES_PC := $(shell for p in ncursesw ncurses; do $(PKGC) --exists $$p 2>/dev/null && { echo $$p; exit 0; }; done)
ifneq ($(CURSES_PC),)
@@ -50,9 +60,19 @@ CST_WEBUI ?= 1
PKG_CFLAGS := $(CURL_CFLAGS) $(CURSES_CFLAGS)
PKG_LIBS := $(CURL_LIBS) $(CURSES_LIBS)
CPPFLAGS += -Iinclude -I.gen -I$(SD_DIR)/include -I$(CJSON_DIR) -D_XOPEN_SOURCE_EXTENDED $(PKG_CFLAGS)
# tcc writes no rpath of its own, so shared libs found via pkg-config -L
# (Nix store, /opt prefixes) would not load at run time.
RPATH_LIBS :=
ifneq ($(findstring tcc,$(notdir $(CC))),)
ifneq ($(STATIC),1)
RPATH_LIBS := $(patsubst -L%,-Wl$(comma)-rpath$(comma)%,$(filter -L%,$(PKG_LIBS)))
endif
endif
# Keep POSIX declarations visible for shared test helpers (notably symlink()).
CPPFLAGS += -Iinclude -I.gen -I$(SD_DIR)/include -I$(CJSON_DIR) -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE_EXTENDED $(PKG_CFLAGS)
LDFLAGS += -L$(SD_DIR)
LDLIBS += -lsashidown -lm $(PKG_LIBS) $(PTHREAD_LIBS)
LDLIBS += -lsashidown -lm $(PKG_LIBS) $(PTHREAD_LIBS) $(RPATH_LIBS)
WEB_DIR := web
WEB_ASSETS := $(wildcard $(WEB_DIR)/*.html) $(wildcard $(WEB_DIR)/*.js) \
@@ -76,6 +96,7 @@ CORE_SRC = \
src/keymap.c \
src/skills.c \
src/extensions.c src/plugins.c src/mcp.c src/subagent.c src/attach.c src/clipboard.c \
src/pdf_text.c \
src/session.c \
src/tools/tools.c \
src/tools/patch.c \
@@ -115,6 +136,7 @@ TESTS = \
tests/test_apply_patch \
tests/test_session_roundtrip \
tests/test_attach \
tests/test_pdf_text \
tests/test_shell \
tests/test_diff \
tests/test_tools_fs \
@@ -141,7 +163,11 @@ ifneq ($(CST_WEBUI),0)
TESTS += tests/test_webui
endif
TEST_LIBS = -L$(SD_DIR) -lsashidown -lm $(CURL_LIBS) $(PTHREAD_LIBS)
TEST_SYS_LIBS = -lm $(PTHREAD_LIBS) $(LINK_STATIC)
TEST_LIBS = -L$(SD_DIR) -lsashidown $(CURL_LIBS) $(RPATH_LIBS) $(TEST_SYS_LIBS)
# cst_test_util.h has static os_* helpers; gcc drops them when unused, tcc
# keeps them, so the small tests link the OS layer too.
TEST_OS_SRC = src/os_compat.c src/os_win.c src/util.c
.PHONY: all clean check demo sashidown-lib FORCE cmake-gcc cmake-clang asan install uninstall
@@ -184,26 +210,29 @@ cst-agent: $(OBJ) $(SD_DIR)/libsashidown.a
src/tui.o: src/tui.c $(HDRS) $(SD_DIR)/include/sashidown.h
$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<
tests/test_ctl_frontier: tests/test_ctl_frontier.c src/ctl_parse.c include/ctl.h
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_ctl_frontier.c src/ctl_parse.c
tests/test_ctl_frontier: tests/test_ctl_frontier.c src/ctl_parse.c include/ctl.h $(TEST_OS_SRC)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_ctl_frontier.c src/ctl_parse.c $(TEST_OS_SRC) $(TEST_SYS_LIBS)
tests/test_ctl_heredoc: tests/test_ctl_heredoc.c src/ctl_parse.c include/ctl.h
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_ctl_heredoc.c src/ctl_parse.c
tests/test_ctl_heredoc: tests/test_ctl_heredoc.c src/ctl_parse.c include/ctl.h $(TEST_OS_SRC)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_ctl_heredoc.c src/ctl_parse.c $(TEST_OS_SRC) $(TEST_SYS_LIBS)
tests/test_json_baseline: tests/test_json_baseline.c src/json_baseline.c $(CJSON_DIR)/cJSON.c $(HDRS)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_json_baseline.c src/json_baseline.c $(CJSON_DIR)/cJSON.c -lm
tests/test_json_baseline: tests/test_json_baseline.c src/json_baseline.c $(CJSON_DIR)/cJSON.c $(HDRS) $(TEST_OS_SRC)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_json_baseline.c src/json_baseline.c $(CJSON_DIR)/cJSON.c $(TEST_OS_SRC) $(TEST_SYS_LIBS)
tests/test_replay_starvation: tests/test_replay_starvation.c src/ctl_parse.c src/json_baseline.c $(CJSON_DIR)/cJSON.c
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_replay_starvation.c src/ctl_parse.c src/json_baseline.c $(CJSON_DIR)/cJSON.c -lm
tests/test_replay_starvation: tests/test_replay_starvation.c src/ctl_parse.c src/json_baseline.c $(CJSON_DIR)/cJSON.c $(TEST_OS_SRC)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_replay_starvation.c src/ctl_parse.c src/json_baseline.c $(CJSON_DIR)/cJSON.c $(TEST_OS_SRC) $(TEST_SYS_LIBS)
tests/test_replay_real: tests/test_replay_real.c src/ctl_parse.c src/json_baseline.c $(CJSON_DIR)/cJSON.c
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_replay_real.c src/ctl_parse.c src/json_baseline.c $(CJSON_DIR)/cJSON.c -lm
tests/test_replay_real: tests/test_replay_real.c src/ctl_parse.c src/json_baseline.c $(CJSON_DIR)/cJSON.c $(TEST_OS_SRC)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_replay_real.c src/ctl_parse.c src/json_baseline.c $(CJSON_DIR)/cJSON.c $(TEST_OS_SRC) $(TEST_SYS_LIBS)
tests/test_mm_tool: tests/test_mm_tool.c src/mm_tool.c include/mm_tool.h
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_mm_tool.c src/mm_tool.c
tests/test_mm_tool: tests/test_mm_tool.c src/mm_tool.c include/mm_tool.h $(TEST_OS_SRC)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_mm_tool.c src/mm_tool.c $(TEST_OS_SRC) $(TEST_SYS_LIBS)
tests/test_textsel: tests/test_textsel.c src/textsel.c src/os_compat.c src/os_win.c src/util.c include/cst_textsel.h
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_textsel.c src/textsel.c src/os_compat.c src/os_win.c src/util.c
tests/test_textsel: tests/test_textsel.c src/textsel.c $(TEST_OS_SRC) include/cst_textsel.h
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_textsel.c src/textsel.c $(TEST_OS_SRC) $(TEST_SYS_LIBS)
tests/test_pdf_text: tests/test_pdf_text.c src/pdf_text.c include/cst_pdf.h $(TEST_OS_SRC)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_pdf_text.c src/pdf_text.c $(TEST_OS_SRC) $(TEST_SYS_LIBS)
tests/test_markdown: tests/test_markdown.c $(SD_DIR)/libsashidown.a
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_markdown.c $(LDFLAGS) -lsashidown -lm
+61 -8
View File
@@ -27,6 +27,10 @@ cst-agent --version
cd ~/my-project && cst-agent
```
不想编译:[Release](https://git.whcself.xyz/WHC/CST-agent/releases) 里有静态链接的 Linux 单文件
(`cst-agent-VERSION-linux-{x86_64,x86,aarch64}.tar.gz`,musl,任何发行版都能直接跑),解压后把 `cst-agent`
放进 `PATH` 即可;每个文件旁边有 `.sha256`。
Windows 10 1903+(PowerShell,不需要管理员):
```powershell
@@ -34,7 +38,8 @@ irm https://git.whcself.xyz/WHC/CST-agent/raw/branch/main/scripts/install_window
# 新开终端后:cd 到项目目录运行 cst-agent;升级用 cst-agent-update
```
详见 [docs/README-windows.md](docs/README-windows.md)。
也可以下载 Release 里的安装包 `cst-agent-VERSION-windows-x86_64-setup.exe`(按用户安装、自动加 PATH、
开始菜单有 WebUI 入口),或便携版 zip。详见 [docs/README-windows.md](docs/README-windows.md)。
一键脚本可以重复运行:已有仓库会 `git pull --ff-only`,代码有更新时干净重编,然后重新安装;
同时装一个 `cst-agent-update` 命令(等同重跑脚本)。NixOS 上会自动进 `nix-shell` 编译。
@@ -49,7 +54,8 @@ irm https://git.whcself.xyz/WHC/CST-agent/raw/branch/main/scripts/install_window
| Linux | [`scripts/bootstrap_linux.sh`](scripts/bootstrap_linux.sh) |
| Termux | [`scripts/bootstrap_termux.sh`](scripts/bootstrap_termux.sh) |
| Windows 安装 / 升级 | [`scripts/install_windows.ps1`](scripts/install_windows.ps1)(从 Release 安装),之后 `cst-agent-update` |
| Windows 交叉构建(在 Linux 上) | [`scripts/bootstrap_windows.sh`](scripts/bootstrap_windows.sh) → `dist/windows-x86_64/` |
| Linux 静态发行包(musl 交叉) | [`scripts/package_linux.sh`](scripts/package_linux.sh) `x86_64\|x86\|aarch64` → `dist/*.tar.gz` |
| Windows 交叉构建(在 Linux 上) | [`scripts/bootstrap_windows.sh`](scripts/bootstrap_windows.sh) → `dist/windows-x86_64/`、zip 和安装包 |
| Windows 原生构建(MSYS2 UCRT64) | [`scripts/bootstrap_msys2.sh`](scripts/bootstrap_msys2.sh) → `dist/windows-x86_64/` |
### 迷你验收工程(论文案例)
@@ -86,6 +92,7 @@ cd CST-agent
make # 依赖 pkg-config 找 libcurl / ncursesw(找不到时退回 ncurses)
make check # 单元测试 + 截断实验(含真实录制流)
make asan # AddressSanitizer + UBSan 构建并跑全部测试
make CC=tcc AR=ar check # TinyCC:整套构建 + 测试十几秒(CI 的校验就是这条)
make install PREFIX=$HOME/.local # 或 sudo make install(默认 /usr/local)
```
@@ -111,7 +118,7 @@ cmake -B build-hd -DCST_BUILD_TUI=OFF && cmake --build build-hd
./scripts/bootstrap_windows.sh
```
依赖:`gcc` 或 `clang`、`libcurl`、TUI 需 `ncursesw`(Windows 版用打过补丁的 ncurses 6.6,脚本自动编译)。
依赖:`gcc`、`clang` 或 `tcc`(0.9.27 mob 以上)、`libcurl`、TUI 需 `ncursesw`(Windows 版用打过补丁的 ncurses 6.6,脚本自动编译)。
Sashidown(`vendor/sashidown`)与 cJSON(`vendor/cjson`,MIT)已随仓库提供。
API Key:TUI 里输入并按 provider 保存到配置目录的 `credentials`(权限 0600);`/key` 更换,`--ask-key` 在命令行输入。
`--api-key` 只用于本次进程、不落盘;`DEEPSEEK_API_KEY` 等环境变量和 `CST_API_KEY` 仅作为没有保存 key 时的兜底(方便 CI)。
@@ -120,7 +127,7 @@ API Key:TUI 里输入并按 provider 保存到配置目录的 `credentials`(
| OS | Arch | 编译器 | Headless | TUI | Shell |
|---|---|---|---|---|---|
| Linux(glibc / musl) | x86_64 / aarch64 | GCC, Clang | yes | ncursesw | `/bin/sh` 或旁路 `busybox` |
| Linux(glibc / musl) | x86_64 / x86 / aarch64 | GCC, Clang, TinyCC | yes | ncursesw | `/bin/sh` 或旁路 `busybox` |
| WSL2 | x86_64 | 同 Linux | yes | ncursesw | `/bin/sh`(工作区建议放在 Linux 文件系统内) |
| macOS | arm64 / x86_64 | Apple Clang | yes | ncurses(Homebrew) | `/bin/sh` |
| Android Termux | aarch64 / … | Clang (Termux) | yes | ncurses(Termux 包) | `$PREFIX/bin/sh`;可旁路 busybox |
@@ -164,6 +171,18 @@ make && make install # 装到 Termux 的 $PREFIX/bin,之后任意目录
临时目录:依次试 `$TMPDIR`、`$PREFIX/tmp`、`/tmp`、`/var/tmp`、`~/.cache/cst-agent/tmp`,用第一个真能建文件的,
并写回 `TMPDIR` 给 shell 子进程和沙箱用(Termux 的 `/tmp` 常常不存在或被 SELinux 拒绝)。
### Linux 静态发行包
```bash
scripts/package_linux.sh x86_64 # 或 x86 / aarch64;CST_LINUX_CHECK=1 顺便跑 make check
```
用 Bootlin 的 musl 交叉 gcc(固定版本、校验 sha256)静态编译 mbedTLS、curl 8.22(只开 HTTP/HTTPS)和宽字符 ncurses,
再以 `STATIC=1` 和 `-Werror` 编出 `cst-agent`,产物是 `dist/cst-agent-VERSION-linux-ARCH.tar.gz`(+ `.sha256`)。
宿主需要 `cmake ninja make perl` 以及 `tic`/`infocmp` 和终端条目(Debian:`ncurses-bin ncurses-term`)。
ncurses 会去常见目录找 terminfo,找不到时用编进去的 `xterm-256color`、`xterm`、`screen-256color`、`tmux-256color`、`linux`、`vt100`。
CA 证书:`CST_CA_BUNDLE` → `SSL_CERT_FILE` → 各发行版的常见位置(Debian/Ubuntu、Fedora/RHEL、openSUSE、Alpine)。
### Windows 发行包
见 [docs/README-windows.md](docs/README-windows.md)(安装、编码、沙箱、构建、已知限制)。
@@ -172,10 +191,17 @@ make && make install # 装到 Termux 的 $PREFIX/bin,之后任意目录
./scripts/bootstrap_windows.sh # Linux 交叉编译;Windows 上在 MSYS2 UCRT64 里用 scripts/bootstrap_msys2.sh
```
产物:`dist/windows-x86_64/`(静态链接的 `cst-agent.exe` + `busybox.exe`,无其他 DLL)和
`dist/cst-agent-VERSION-windows-x86_64.zip`。CI 在 `main` / `v*` tag 推送且交叉构建成功后会自动上传到
Gitea Release `vVERSION`(同名资源会被替换);仓库可设 `RELEASE_TOKEN`(`write:repository`),否则用任务自带 token。
本地:`GITEA_TOKEN=... scripts/release_windows.sh`。
产物:`dist/windows-x86_64/`(静态链接的 `cst-agent.exe` + `busybox.exe`,无其他 DLL)、
`dist/cst-agent-VERSION-windows-x86_64.zip`,以及装了 `makensis` 时的安装包 `dist/cst-agent-VERSION-windows-x86_64-setup.exe`。
### CI 与 Release
CI 用 TinyCC 校验(构建、`make check`、WebUI 端到端),通过后用 gcc(`-Werror`)出发行包:
Linux x86_64 / x86 / aarch64 静态包(x86 两种跑 `make check`,aarch64 用 qemu 冒烟),
Windows x86_64 的 zip 和安装包(Debian 的 mingw-w64 UCRT gcc + NSIS)。
推送到 `main` 或 `v*` tag 时每个任务把自己的产物上传到 Gitea Release `vVERSION`(同名资源会被替换);
仓库可设 `RELEASE_TOKEN`(`write:repository`),否则用任务自带 token。
本地:`GITEA_TOKEN=... scripts/release.sh dist/cst-agent-*.tar.gz dist/cst-agent-*.zip dist/cst-agent-*-setup.exe`。
环境变量:`CST_SHELL`、`CST_EXE_DIR`、`CST_AUTO_APPROVE` 等。
@@ -207,6 +233,7 @@ Gitea Release `vVERSION`(同名资源会被替换);仓库可设 `RELEASE_T
|---|---|
| `CST_PROTOCOL` / `--protocol` | 工具调用协议(`native-eos`) |
| `CST_TOOLS` / `--tools` | 工具集:`default`(全部)/ `minimal`(论文 4 件套) |
| `CST_MODE` / `--mode` | 工作模式:`coding`(默认,代码口径)/ `general`(通用助手口径) |
| `CST_EFFORT` / `--effort` | 推理强度 `low` / `medium` / `high` / `max` |
| `CST_CONFIRM` / `--confirm` | 哪些类别要确认:`shell,write,net`(默认)或 `none` |
| `CST_MAX_STEPS` / `--max-steps` | 每个用户回合最多调用模型几次(30) |
@@ -219,6 +246,7 @@ Gitea Release `vVERSION`(同名资源会被替换);仓库可设 `RELEASE_T
| `CST_METRICS=0` / `CST_METRICS_PATH` | 关闭 / 指定计时埋点 JSONL(默认 `.agent/metrics/<session>.jsonl`) |
| `CST_RECORD_SSE=DIR` / `CST_REPLAY_SSE=DIR` | 录制 / 回放原始 SSE 流(`NNNN.sse` + `NNNN.req.json`) |
| `CST_APPROVAL=ask\|auto\|yolo` / `CST_SANDBOX=off\|landlock\|seccomp` | 审批模式 / 关闭沙箱(回落到只读白名单规则)或只用指定沙箱 |
| `CST_CA_BUNDLE` | HTTPS 用的 CA 证书文件(默认:`SSL_CERT_FILE`、libcurl 自带路径、常见发行版位置;Windows 用系统证书库) |
| `CST_MODELS`、`CST_AUTO_APPROVE=1`、`CST_SHELL`、`CST_EXE_DIR` | 模型列表、自动批准(= yolo)、shell、旁路 busybox |
## Run
@@ -249,6 +277,7 @@ cst-agent --headless --prompt 'List files'
| `-y` / `--yolo` | 等同 `--approval yolo`,只对本次运行有效 |
| `-C LIST` / `--confirm LIST` | 需要确认的类别:`shell,write,net` 的任意组合或 `none` |
| `-T PROFILE` / `--tools PROFILE` | `default` 或 `minimal` |
| `-M MODE` / `--mode MODE` | 工作模式 `coding`(默认)/ `general`,也读 `CST_MODE`,并记进 `settings.json` |
| `-P NAME` / `-m NAME` / `-e LEVEL` | 本次使用的 provider / 模型 / 推理强度(不传则用上次的) |
| `-a` / `--ask-key` | 在命令行输入并保存当前 provider 的 key |
@@ -270,6 +299,8 @@ cst-agent --headless --prompt 'List files'
| `delete_file` / `move_file` | 写 | 删除 / 移动(重命名)文件 |
| `run_shell` | shell | 非交互命令,超时整组进程被杀,Esc 可中断 |
| `web_fetch` | 网络 | 抓取 URL,HTML 转纯文本 |
| `clipboard_read` | 读 | 读系统剪贴板里的文本(`max_bytes` 默认 64 KiB,超出截断并说明) |
| `clipboard_write` | 写 | 把文本放进系统剪贴板(按写类权限确认;本机走 pbcopy / wl-copy / xclip / Win32 API) |
| `todo_write` | 元 | 维护任务清单(TUI 右侧面板,Ctrl+T 开关) |
| `ask_user` | 询问 | 向用户提问(可给选项);headless 下返回错误让模型自行决定 |
| `skill` | 元 | 加载一个 skill 的说明(`SKILL.md`)或其中的文件;有 skill 时才出现 |
@@ -281,6 +312,26 @@ cst-agent --headless --prompt 'List files'
`--tools minimal` 只保留 `read_file` / `run_shell` / `write_file` / `apply_patch`(论文实验口径)。
TUI 中 `/tools off NAME`、`/tools on NAME` 可临时开关单个工具。
### 工作模式(coding / general)
`--mode general`(或 TUI 里 `/mode general`、WebUI 运行设置里的「工作模式」、`CST_MODE=general`)把默认口径
从"代码助手"换成"通用助手":工作流从改代码/跑测试换成"先弄清要什么、再动手、给出处和不确定的地方",
工具说明从"仓库"改成"文件与数据",并说明 `web_fetch` 可以拿外部资料;`/status` 第一行显示当前模式,
切换后 history 里会留一条系统提示。默认仍是 `coding`,选择记在 `settings.json`;
`--tools minimal`(论文口径)的提示词按字节冻结,不受模式影响。
### 剪贴板与文档附件
- **剪贴板**:`clipboard_read` / `clipboard_write` 两个工具(写剪贴板是不可逆发射,要确认);
TUI 里 `/attach paste` 在剪贴板里没有图片时,把剪贴板的**文本**放进输入框(丢掉 CR 与控制字节,尊重输入长度上限)。
- **附件**(`/attach <path>`、拖入终端、剪贴板图片都算):图片按原样存进会话目录,发给模型时是 image part;
**PDF 在摄取时就抽出文本层**(零依赖解析器:Flate / ASCIIHex / ASCII85、对象流、CID 字体 ToUnicode、
内联图像跳过),存的是文本、`mime` 仍是 `application/pdf`;其余文件必须是 UTF-8 文本。
文档以 **text part 内联**发出,所以不受 `CST_NO_IMAGES` 或非视觉模型影响;图片照旧会被换成一行"未发送"说明。
上限:单个附件 ≤16 MB(文档文本 ≤4 MiB),每条消息最多 8 个。
加密 PDF、扫描件(无文本层)会被明确拒绝并说明原因;
`view_image` 仍只收图片,文本/PDF 走 `/attach`。
### 权限、撤销与项目说明
- **审批模式**(Shift+Tab 循环切换,`/approval`,`--approval`,`CST_APPROVAL`):
@@ -399,6 +450,7 @@ Thought(推理过程)默认折叠成一行“Thought · 3.2s”,生成中
| `/provider [name]`、`/model [name]`、`/effort [level]` | 切换 provider(缺 key 时当场输入并用 `/models` 校验)、模型(列表优先显示 API 实际返回的模型,标 `(api)`)、推理强度;都会记住 |
| `/key` | 输入或更换当前 provider 的 API key(遮罩输入并保存) |
| `/protocol [name]` | 切换工具调用协议 |
| `/mode [coding\|general]` | 工作模式(通用助手 / 代码助手口径) |
| `/tools [on\|off NAME\|minimal\|default]` | 查看或开关工具 |
| `/approval [ask\|auto\|yolo]` *、`/yolo` * | 审批模式;本次开关 yolo |
| `/permissions [reset]` *、`/max-steps [N]` * | 权限规则、每轮步数 |
@@ -408,6 +460,7 @@ Thought(推理过程)默认折叠成一行“Thought · 3.2s”,生成中
| `/diff [path]` * | `git status` + `git diff` |
| `/compact` | 手动压缩上下文 |
| `/export [file]` *、`/copy` * | 导出 Markdown 记录;复制上一条回复(OSC 52,需终端支持) |
| `/attach [path\|paste\|list\|clear]` | 给下一条消息带附件:图片、PDF(自动取文本层)、文本文件;`paste` 优先取剪贴板图片,没有就把剪贴板文本放进输入框 |
| `/web` * | 后台起一个 WebUI 进程(同 workspace、新会话,日志写到 `.agent/webui.log`) |
| `/init` | 让 agent 写 `AGENTS.md` |
| `/details` *、`/thinking [on\|off]`、`/keys` * | 展开全部 tool 输出;Thought 默认展开/折叠;快捷键列表 |
+12 -4
View File
@@ -2,17 +2,25 @@
# ./scripts/build_third_party_mingw.sh curl
# cmake -B build-win -DCMAKE_TOOLCHAIN_FILE=cmake/mingw-w64-x86_64.cmake \
# -DCST_BUILD_TUI=OFF
# $MINGW_HOST picks the tool prefix (default x86_64-w64-mingw32; Debian's UCRT
# cross gcc is x86_64-w64-mingw32ucrt).
set(CMAKE_SYSTEM_NAME Windows)
set(CMAKE_SYSTEM_PROCESSOR x86_64)
set(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc)
set(CMAKE_CXX_COMPILER x86_64-w64-mingw32-g++)
set(CMAKE_RC_COMPILER x86_64-w64-mingw32-windres)
if(DEFINED ENV{MINGW_HOST} AND NOT "$ENV{MINGW_HOST}" STREQUAL "")
set(_MINGW_HOST "$ENV{MINGW_HOST}")
else()
set(_MINGW_HOST x86_64-w64-mingw32)
endif()
set(CMAKE_C_COMPILER ${_MINGW_HOST}-gcc)
set(CMAKE_CXX_COMPILER ${_MINGW_HOST}-g++)
set(CMAKE_RC_COMPILER ${_MINGW_HOST}-windres)
get_filename_component(_AGENT_ROOT "${CMAKE_CURRENT_LIST_DIR}/.." ABSOLUTE)
set(_MINGW_PREFIX "${_AGENT_ROOT}/third_party/prefix-mingw")
list(APPEND CMAKE_PREFIX_PATH "${_MINGW_PREFIX}")
set(CMAKE_FIND_ROOT_PATH "/usr/x86_64-w64-mingw32" "${_MINGW_PREFIX}")
set(CMAKE_FIND_ROOT_PATH "/usr/${_MINGW_HOST}" "${_MINGW_PREFIX}")
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY BOTH)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE BOTH)
+31 -6
View File
@@ -5,6 +5,20 @@
## 安装
### 安装包
从 [Release](https://git.whcself.xyz/WHC/CST-agent/releases) 下载
`cst-agent-VERSION-windows-x86_64-setup.exe` 运行即可:按当前用户安装到
`%LOCALAPPDATA%\Programs\cst-agent`(不需要管理员),把这个目录加进**用户** PATH,
开始菜单里放一个“CST-Agent WebUI”(在用户目录启动 `cst-agent --web --web-open`)。
系统低于 Windows 10 1903 时安装包会直接拒绝。
卸载:设置 → 应用 → CST-Agent,或运行安装目录里的 `uninstall.exe`;会去掉 PATH 里的这一项。
API key 和设置在 `%APPDATA%\cst-agent`,卸载时保留。
安装包装的文件和 zip 一样,所以之后也能用 `cst-agent-update` 升级,或者重新运行新版安装包覆盖。
### PowerShell 脚本
在 PowerShell 里(Windows PowerShell 5.1 或 PowerShell 7 都行):
```powershell
@@ -123,7 +137,9 @@ windows-x86_64/
## 从源码构建
两种方式产物一样:`dist/windows-x86_64/` 和 `dist/cst-agent-VERSION-windows-x86_64.zip`。
两种方式产物一样:`dist/windows-x86_64/` 和 `dist/cst-agent-VERSION-windows-x86_64.zip`;
装了 `makensis`(NSIS)时还有安装包 `dist/cst-agent-VERSION-windows-x86_64-setup.exe`
(脚本在 `scripts/windows/cst-agent.nsi`)。
第三方依赖(curl、ncurses、busybox-w32)都按固定版本从源码编译、静态链接。
### 在 Linux 上交叉编译
@@ -134,8 +150,16 @@ cd CST-agent
scripts/bootstrap_windows.sh
```
NixOS / 有 Nix 时自动进 `shell-win.nix`(`pkgsCross.ucrt64`);否则需要 UCRT 版的
`x86_64-w64-mingw32-gcc`(带 winpthreads)、cmake、ninja、git、perl。
NixOS / 有 Nix 时自动进 `shell-win.nix`(`pkgsCross.ucrt64`,带 NSIS);否则需要 UCRT 版的
mingw-w64 gcc(带 winpthreads)、cmake、ninja、git、perl。工具前缀由 `MINGW_HOST` 指定,默认
`x86_64-w64-mingw32`;Debian trixie 起的 `gcc-mingw-w64-ucrt64` 是 `x86_64-w64-mingw32ucrt`:
```bash
sudo apt install gcc-mingw-w64-ucrt64 binutils-mingw-w64-ucrt64 nsis cmake ninja-build perl
MINGW_HOST=x86_64-w64-mingw32ucrt scripts/bootstrap_windows.sh
```
`CST_WIN_CFLAGS` 给 `cst-agent.exe` 追加编译选项(CI 用 `-Wall -Wextra -Werror`)。
### 在 Windows 上用 MSYS2 原生编译
@@ -159,17 +183,18 @@ scripts/bootstrap_msys2.sh
### 发布
CI:推 `main` 或 `v*` tag 且 `windows-cross` 成功后,自动把 zip / `.sha256` 发到
CI:推 `main` 或 `v*` tag 且 `windows` 任务成功后,自动把 zip、安装包和各自的 `.sha256` 发到
Gitea Release `vVERSION`(版本来自 `include/cst_version.h`;同名资源替换)。仓库 Secrets
可设 `RELEASE_TOKEN`(`write:repository`),没有则用 Actions 自带 token。
本地:
```bash
GITEA_TOKEN=... scripts/release_windows.sh --build
scripts/bootstrap_windows.sh
GITEA_TOKEN=... scripts/release.sh dist/cst-agent-*-windows-x86_64.zip dist/cst-agent-*-windows-x86_64-setup.exe
```
创建(或复用)`vVERSION` Release,上传 zip 和 `.sha256`。token 只从环境变量读取,经 stdin
创建(或复用)`vVERSION` Release,上传给出的文件和旁边的 `.sha256`。token 只从环境变量读取,经 stdin
交给 curl,不会出现在命令行参数、磁盘或输出里。发版前先 bump `cst_version.h`;推
`vX.Y.Z` tag 时必须与头文件一致。
+5 -5
View File
@@ -21,11 +21,11 @@ The Makefile picks `ncursesw`, then `ncurses`, through pkg-config. On macOS it
adds Homebrew's keg-only `ncurses`/`curl` to `PKG_CONFIG_PATH`; without
Homebrew it falls back to the system `-lncurses` (wide-character capable).
Verified so far: NixOS x86_64 with gcc and clang (`-Werror`, `make check`,
`make asan`, ctest), and every source compiled `-fsyntax-only` with
`x86_64-unknown-linux-musl-gcc` without warnings. Full musl, macOS and WSL
builds run in CI (`.gitea/workflows/ci.yml`; the macOS job needs a runner and
the `HAVE_MACOS_RUNNER` variable) or by hand with the checklist below.
Verified so far: NixOS x86_64 with gcc, clang and TinyCC (`-Werror` except
tcc, `make check`, `make asan`, ctest). CI (`.gitea/workflows/ci.yml`) checks
with TinyCC on Debian and builds the static musl releases for x86_64, x86 and
aarch64 with gcc `-Werror` (`make check` on both x86 targets, a qemu smoke
test on aarch64). macOS and WSL are checked by hand with the list below.
## Files
+20 -3
View File
@@ -209,6 +209,22 @@ Markdown 在**服务端**渲染(复用 TUI 用的 sashidown 流式 API),
对话开始后自动隐去;右栏只给三件事——任务清单、本轮文件改动行数(`+N −M`)、上下文
占用与 prompt cache 命中率。布局类在页面脚本之前就写进 `<body>`,避免首帧闪一下再收起。
对话列:正文、过程块、提示行和输入框共用同一条左边线,正文宽度上限 720px(`--content`);
左右两栏随屏宽在 `clamp()` 范围内变宽,超宽屏下中间列不会无限拉开。
过程时间线:一段**连续**的思考和工具调用合成一个过程块,折叠时只有一行
("思考 4 次 · 工具 6 次";运行中显示当前动作,比如"执行 run_shell…"),展开后是一条
细竖线串起的时间线,每次思考、每个工具调用各占一行,思考只露第一行,点开看全文。
出现可见的正文(或引擎提示、下一句提问)时过程块就此结束,后面的思考/工具另起一块——
历史重建(`/api/session`)和实时事件流用的是同一条规则,所以刷新前后看到的一样。
`/thinking on|off`(`show_thinking`)决定过程块和其中的思考默认展开还是收起,流式输出时也照此执行;
`/details` 只管工具行是否展开。
图片:提问附带的图片显示在气泡**上方**、靠右,一张保持原比例(最长 260px),多张是
152px 的圆角方块;点开是大图预览(Esc 关闭,←/→ 切换)。从本页上传/粘贴/拖入的图片在
输入框上方显示缩略图,发送后立刻出现在新提问上(本地预览,本轮结束后换成 `/api/attach/<rel>`);
从别的客户端加的待发图片仍然显示为文字条。
### 命令与快捷键
输入框以 `/` 开头时是命令,在页面里执行,不发给模型:打 `/` 弹出列表(↑↓ 选,Tab 补全,
@@ -259,10 +275,11 @@ sh scripts/e2e_webui.sh tests/fixtures/sse/deepseek-ctl-heredoc ctl-heredoc
1. 打开首页 → 顶部显示 workspace/模型/审批模式,右下状态"就绪"。
2. 输入一句话 → 助手气泡逐字出现;工具卡片自动展开、结束后带 `exit=` 标记。
3. 切到 `ask` 审批 → 写文件时弹窗;点"允许一次"后继续,点"拒绝"则该工具返回失败但对话继续。
4. `会话` 按钮:新建/切换后历史正确重建(刷新页面也一样):工具调用折叠成"本轮工具调用",
点开能看到参数和输出;搜索、重命名、删除可用。
4. `会话` 按钮:新建/切换后历史正确重建(刷新页面也一样):连续的思考和工具调用折叠成一行
过程块,展开是时间线,工具行点开能看到参数和输出;搜索、重命名、删除可用。
`/thinking off` 时流式输出的思考也保持收起。
4a. 最后一句提问上有"编辑重发",最后一个回答上有"重新生成";右栏文件行点开是真实 diff。
5. 拖入一张图片 → 底部出现待发送提示,发送后历史里能看到图。
5. 拖入一张图片 → 输入框上方出现缩略图,发送后图片立刻出现在提问气泡上方,点开是大图预览。
6. 关掉标签页再打开 → 事件流自动续传,不丢已完成的消息。
## 限制与已知问题
+23 -6
View File
@@ -47,15 +47,18 @@ int cst_protocol_is_text(cst_protocol_t p);
/* Eager protocols execute a call during the stream, at confirmation time. */
int cst_protocol_is_eager(cst_protocol_t p);
/* One image carried by a message (see cst_attach.h). The bytes live beside
* the session; this is the metadata plus the name of the stored copy. */
/* One file carried by a message (see cst_attach.h): an image, or a document
* whose stored payload is its text. The payload lives beside the session;
* this is the metadata plus the name of the stored copy. */
typedef struct {
char id[32]; /* unique inside the session ("img-1a2b3c4d") */
char name[256]; /* display name (original file name) */
char mime[32]; /* image/png, image/jpeg, image/gif, image/webp, image/bmp */
char mime[32]; /* image/png, ...; application/pdf for a PDF whose text
* layer the stored file holds; text/plain for text */
char rel[256]; /* file name inside the session's attachment directory */
long long bytes; /* stored size */
long long bytes; /* stored size (the text, for documents) */
int width, height; /* pixels, 0 when the header could not be read */
int pages; /* PDF page count, 0 for anything else */
char detail[8]; /* auto | low | high (wire hint, "" = auto) */
char origin[32]; /* user | view_image | mcp (for display only) */
} cst_attachment_t;
@@ -82,6 +85,7 @@ typedef struct {
char model[128];
char provider[32];
char effort[16]; /* low | medium | high | max */
char mode[16]; /* coding | general (CST_DEFAULT_MODE) */
cst_protocol_t protocol;
int max_steps; /* model calls per user turn */
size_t tool_out_cap; /* bytes of one tool output sent to the model */
@@ -114,6 +118,14 @@ typedef enum {
const char *cst_approval_name(int a);
int cst_approval_parse(const char *s, int *out);
/* Working mode: how the system prompt frames the agent. "coding" (default)
* is code framed; "general" is for tasks that are not about a codebase
* (documents, data, research, everyday files). Orthogonal to plan mode. */
#define CST_DEFAULT_MODE "coding"
int cst_mode_valid(const char *m);
/* Canonical name of m, or the default when m is unknown / empty. */
const char *cst_mode_name(const char *m);
typedef struct cst_session cst_session_t;
typedef struct cst_agent cst_agent_t;
@@ -278,6 +290,8 @@ int cst_llm_list_models(const char *api_base, const char *api_key,
char *cst_llm_build_body(const cst_llm_request_t *req);
/* Reset the CST_RECORD_SSE / CST_REPLAY_SSE sequence counter. */
void cst_llm_trace_reset(void);
/* Set CURLOPT_CAINFO on a CURL * when a CA bundle file is known. */
void cst_curl_apply_ca(void *curl);
/* on_permission answers */
#define CST_PERM_DENY 0
@@ -404,13 +418,14 @@ int cst_creds_resolve(const char *provider, char *out, size_t out_sz,
/* Hidden console prompt (no echo). */
int cst_creds_prompt_console(const char *provider, char *out, size_t out_sz);
/* Last used provider, model per provider and effort, in
/* Last used provider, model per provider, effort and working mode, in
* <config>/settings.json. */
#define CST_SETTINGS_MAX_MODELS 16
#define CST_SETTINGS_MAX_TRUSTED 32
typedef struct {
char provider[32];
char effort[16];
char mode[16]; /* coding | general, "" = not chosen yet */
char approval[8]; /* "" = not chosen yet */
int show_thinking; /* TUI: Thought blocks start expanded */
/* workspaces whose .agent/plugins and .agent/mcp.json may run */
@@ -425,11 +440,13 @@ typedef struct {
int cst_settings_load(cst_settings_t *s);
int cst_settings_save(const cst_settings_t *s);
const char *cst_settings_model(const cst_settings_t *s, const char *provider);
/* Record cfg's provider, model and effort as the last used ones. */
/* Record cfg's provider, model, effort and mode as the last used ones. */
int cst_settings_remember(const cst_agent_config_t *cfg);
/* Record an approval mode the user picked (CST_APPROVAL_*). */
int cst_settings_remember_approval(int approval);
int cst_settings_remember_thinking(int show_thinking);
/* Record the working mode the user picked (coding | general). */
int cst_settings_remember_mode(const char *mode);
/* Workspace trust for project plugins / MCP servers (by real path). */
int cst_settings_trusted(const char *workspace);
int cst_settings_trust(const char *workspace, int on);
+24 -14
View File
@@ -9,16 +9,24 @@
extern "C" {
#endif
/* --- image attachments ---------------------------------------------------
* An attachment is a validated copy of an image file, stored beside the
* session so the bytes a model is shown stay the bytes that were picked.
* Only the metadata travels in the JSONL; the bytes are encoded into the
* request when it is built. */
/* --- attachments ---------------------------------------------------------
* An attachment is a validated copy of a file, stored beside the session so
* what a model is shown stays what was picked. Images are stored as they are
* and encoded into the request when it is built; a PDF is reduced to its text
* layer and a text file is stored as is, both of which travel inline as text
* (so a text-only model still gets them). Only the metadata goes in the
* JSONL. */
/* Supported: PNG, JPEG, GIF, WebP, BMP (static images). */
#define CST_ATTACH_MAX_BYTES (16 * 1024 * 1024) /* one stored image */
/* Supported: PNG, JPEG, GIF, WebP, BMP (static images), PDF, UTF-8 text. */
#define CST_ATTACH_MAX_BYTES (16 * 1024 * 1024) /* one picked file */
#define CST_ATTACH_MAX_TOTAL (32 * 1024 * 1024) /* per request */
#define CST_ATTACH_MAX_COUNT 8 /* per message */
/* Text stored and inlined per document (a PDF also caps its text here). */
#define CST_ATTACH_TEXT_MAX (4 * 1024 * 1024)
/* Images go on the wire as image parts; everything else is inlined as text. */
int cst_attach_is_image(const cst_attachment_t *a);
int cst_attach_is_text(const cst_attachment_t *a);
/* Magic-byte test: 0 and a canonical mime when data holds a supported
* image, -1 otherwise (an extension alone never decides). */
@@ -35,23 +43,25 @@ int cst_attach_dir(const char *session_path, char *out, size_t out_sz);
int cst_attach_full_path(const char *session_path, const cst_attachment_t *a,
char *out, size_t out_sz);
/* Read src_path, verify it is a supported image within limits, and copy it
* into the session's attachment directory. Returns a malloc'd entry the
* caller owns (cst_attach_free), or NULL with err filled. */
/* Read src_path and copy it into the session's attachment directory: an image
* as it is, a PDF as its extracted text, anything else only when it is text.
* Returns a malloc'd entry the caller owns (cst_attach_free), or NULL with
* err filled. */
cst_attachment_t *cst_attach_import_file(const char *session_path,
const char *src_path, char *err,
size_t err_sz);
/* Store already-read bytes (clipboard, downloads); name is display-only. */
/* Store already-read image bytes (clipboard, downloads); name is
* display-only. */
cst_attachment_t *cst_attach_import_bytes(const char *session_path,
const char *name, const char *data,
size_t n, char *err, size_t err_sz);
/* Validate and read back a stored image, or NULL when it is gone. */
/* Validate and read back a stored payload, or NULL when it is gone. */
char *cst_attach_read(const char *session_path, const cst_attachment_t *a,
size_t *out_len, char *err, size_t err_sz);
/* "data:image/png;base64,...." for the wire; NULL when the file is gone. */
/* "data:image/png;base64,...." for the wire; images only, NULL otherwise. */
char *cst_attach_data_url(const char *session_path, const cst_attachment_t *a);
/* "1920x1080 PNG 412 KB" style one-liner for prompts and the UI. */
/* "1920x1080 png 412 KB" / "pdf 1.2 MB, 12 pages" one-liner for prompts. */
void cst_attach_describe(const cst_attachment_t *a, char *out, size_t out_sz);
void cst_attach_free(cst_attachment_t *a);
+14
View File
@@ -13,6 +13,20 @@ extern "C" {
* ("no image on the clipboard", "install wl-clipboard", ...). */
int cst_clipboard_image(char **data, size_t *n, char *err, size_t err_sz);
/* Cap on text moved through the clipboard (read and write). */
#define CST_CLIPBOARD_TEXT_MAX (1024 * 1024)
/* UTF-8 text on the system clipboard: Wayland (wl-paste), X11 (xclip),
* macOS (pbpaste), Windows (CF_UNICODETEXT). Returns 0 with *data malloc'd
* and NUL-terminated, or -1 with err filled in ("no text on the clipboard",
* "reading the clipboard needs wl-clipboard", ...). */
int cst_clipboard_text(char **data, size_t *n, char *err, size_t err_sz);
/* Replace the clipboard with UTF-8 text: wl-copy / xclip / pbcopy, or the
* Windows clipboard API. Returns 0 on success, else -1 with err. */
int cst_clipboard_set_text(const char *text, size_t n, char *err,
size_t err_sz);
/* Windows CF_DIB bytes (BITMAPINFOHEADER + pixels) as an image file: a PNG
* for uncompressed 24/32-bit bitmaps, else a BMP. NULL when malformed. */
char *cst_dib_to_image(const void *dib, size_t sz, size_t *n);
+27
View File
@@ -0,0 +1,27 @@
#ifndef CST_PDF_H
#define CST_PDF_H
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Text layer of a PDF, in page order, with no external dependency (no
* poppler, no zlib): classic objects and object streams, FlateDecode plus
* ASCIIHex/ASCII85, PNG/TIFF predictors, Tj/TJ/'/" text with per-font
* ToUnicode CMaps and a WinAnsi / Latin-1 fallback. Scanned pages have no
* text layer and are reported as such.
* Returns a malloc'd NUL-terminated UTF-8 string, or NULL with err filled in
* ("PDF is encrypted ...", "no extractable text ..."). *pages (optional) gets
* the page count; the result is truncated at CST_PDF_TEXT_MAX bytes. */
char *cst_pdf_text(const void *data, size_t n, int *pages, char *err,
size_t err_sz);
#define CST_PDF_TEXT_MAX (4u * 1024u * 1024u)
#ifdef __cplusplus
}
#endif
#endif
+1 -1
View File
@@ -3,7 +3,7 @@
#define CST_VERSION_MAJOR 0
#define CST_VERSION_MINOR 8
#define CST_VERSION_PATCH 4
#define CST_VERSION_PATCH 6
#define CST_VERSION_STR_(x) #x
#define CST_VERSION_STR(x) CST_VERSION_STR_(x)
+11 -7
View File
@@ -1,8 +1,9 @@
#!/usr/bin/env bash
# Linux host: cross-build the Windows x86_64 release (mingw-w64, UCRT, static).
# scripts/bootstrap_windows.sh [repo-dir]
# With Nix the toolchain comes from shell-win.nix; otherwise x86_64-w64-mingw32-gcc
# (UCRT flavour, with winpthreads), cmake, ninja, git and perl must be installed.
# With Nix the toolchain comes from shell-win.nix; otherwise $MINGW_HOST-gcc
# (default x86_64-w64-mingw32; UCRT flavour, with winpthreads), cmake, ninja,
# git and perl must be installed. CST_WIN_CFLAGS adds C flags (CI: -Werror).
# Output: dist/windows-x86_64/ and dist/cst-agent-VERSION-windows-x86_64.zip
set -euo pipefail
@@ -21,15 +22,17 @@ if [[ ! -f "$DIR/CMakeLists.txt" ]]; then
fi
cd "$DIR"
if ! command -v x86_64-w64-mingw32-gcc >/dev/null && [[ -z "${IN_NIX_SHELL:-}" ]] &&
H="${MINGW_HOST:-x86_64-w64-mingw32}"
if ! command -v "$H-gcc" >/dev/null && [[ -z "${IN_NIX_SHELL:-}" ]] &&
command -v nix-shell >/dev/null; then
exec nix-shell shell-win.nix --run "$(printf '%q ' "$0" "$PWD")"
fi
need() { command -v "$1" >/dev/null || { echo "missing $1 (mingw-w64 UCRT gcc, cmake, ninja, git, perl)" >&2; exit 1; }; }
need git; need cmake; need ninja; need perl; need x86_64-w64-mingw32-gcc
if ! printf '#include <stdio.h>\n' | x86_64-w64-mingw32-gcc -dM -E - | grep -qw _UCRT; then
echo "x86_64-w64-mingw32-gcc targets msvcrt; the UTF-8 manifest needs a UCRT toolchain" >&2
export MINGW_HOST="$H"
need git; need cmake; need ninja; need perl; need "$H-gcc"
if ! printf '#include <stdio.h>\n' | "$H-gcc" -dM -E - | grep -qw _UCRT; then
echo "$H-gcc targets msvcrt; the UTF-8 manifest needs a UCRT toolchain" >&2
exit 1
fi
@@ -40,7 +43,8 @@ fi
echo "==> cmake (Windows, TUI)"
cmake -S . -B build-win-tui -G Ninja \
-DCMAKE_TOOLCHAIN_FILE=cmake/mingw-w64-x86_64.cmake \
-DCMAKE_BUILD_TYPE=Release -DCST_BUILD_TUI=ON
-DCMAKE_BUILD_TYPE=Release -DCST_BUILD_TUI=ON \
-DCMAKE_C_FLAGS="${CST_WIN_CFLAGS:-}"
# Package only needs the agent binary; skip host-unrunnable Win32 tests.
cmake --build build-win-tui --target cst-agent
+164
View File
@@ -0,0 +1,164 @@
#!/usr/bin/env bash
# Build pinned static deps for a Linux release into third_party/prefix-linux-ARCH:
# mbedTLS, libcurl (HTTP(S) only, mbedTLS) and wide ncurses.
# scripts/build_third_party_linux.sh x86_64|x86|aarch64 [all|mbedtls|curl|ncurses]
# Uses LINUX_HOST-gcc from PATH, else fetches it via ci_linux_toolchain.sh.
# Host tools: cmake ninja make perl, and tic/infocmp with the fallback
# terminal entries (Debian: ncurses-bin ncurses-term).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
ARCH="${1:?usage: $0 x86_64|x86|aarch64 [all|mbedtls|curl|ncurses]}"
TP="$ROOT/third_party"
PREFIX="$TP/prefix-linux-$ARCH"
SRC="$TP/src"
WORK="$TP/build-linux-$ARCH"
JOBS="${JOBS:-$(nproc 2>/dev/null || echo 4)}"
MBEDTLS_VER=3.6.7
MBEDTLS_SHA=a7e8bcbec0e6f761b4af24f25677626b35f762f68eef79c08677a363212d11f6
CURL_VER=8.22.0
CURL_SHA=f7ef3ae8a22e521f289803fe93543eb64c329b58aa73a9e224dfd915a2a5f4f7
NCURSES_VER=6.6
NCURSES_SHA=355b4cbbed880b0381a04c46617b7656e362585d52e9cf84a67e2009b749ff11
# Compiled in, so the TUI starts even where no terminfo database is found.
NCURSES_FALLBACKS=xterm-256color,xterm,screen-256color,tmux-256color,linux,vt100
if [[ -z "${LINUX_HOST:-}" ]] || ! command -v "$LINUX_HOST-gcc" >/dev/null; then
read -r LINUX_HOST bindir < <(bash "$ROOT/scripts/ci_linux_toolchain.sh" "$ARCH")
export PATH="$bindir:$PATH"
fi
T="$LINUX_HOST-"
need() { command -v "$1" >/dev/null || { echo "missing: $1" >&2; exit 1; }; }
need "${T}gcc"
need cmake
need ninja
need make
need tic
need infocmp
mkdir -p "$PREFIX" "$SRC" "$WORK"
fetch() { # file sha url...
local file="$1" sha="$2" u
shift 2
if [[ -f "$SRC/$file" ]] && echo "$sha $SRC/$file" | sha256sum -c --quiet - 2>/dev/null; then
return 0
fi
for u in "$@"; do
echo " try $u"
if curl -fsSL --retry 2 --connect-timeout 15 --max-time 600 -o "$SRC/$file.part" "$u" &&
echo "$sha $SRC/$file.part" | sha256sum -c --quiet -; then
mv "$SRC/$file.part" "$SRC/$file"
return 0
fi
done
rm -f "$SRC/$file.part"
echo "download failed: $file" >&2
exit 1
}
unpack() { # file dir
rm -rf "${WORK:?}/$2"
tar -C "$WORK" -xf "$SRC/$1"
}
gh() { # path -> GitHub URL candidates (CN proxies first)
printf '%s\n' "https://ghfast.top/https://github.com/$1" \
"https://ghproxy.net/https://github.com/$1" "https://github.com/$1"
}
cmake_cross() { # src build args...
local s="$1" b="$2"
shift 2
cmake -S "$s" -B "$b" -G Ninja \
-DCMAKE_SYSTEM_NAME=Linux \
-DCMAKE_C_COMPILER="${T}gcc" -DCMAKE_AR="$(command -v "${T}ar")" \
-DCMAKE_RANLIB="$(command -v "${T}ranlib")" \
-DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$PREFIX" \
-DCMAKE_INSTALL_LIBDIR=lib -DCMAKE_PREFIX_PATH="$PREFIX" \
-DCMAKE_FIND_ROOT_PATH="$PREFIX" \
-DCMAKE_FIND_ROOT_PATH_MODE_PROGRAM=NEVER \
-DCMAKE_FIND_ROOT_PATH_MODE_LIBRARY=ONLY \
-DCMAKE_FIND_ROOT_PATH_MODE_INCLUDE=ONLY \
-DCMAKE_POSITION_INDEPENDENT_CODE=OFF \
"$@"
cmake --build "$b" -j"$JOBS"
cmake --install "$b"
}
build_mbedtls() {
local f="mbedtls-$MBEDTLS_VER.tar.bz2"
mapfile -t urls < <(gh "Mbed-TLS/mbedtls/releases/download/mbedtls-$MBEDTLS_VER/$f")
fetch "$f" "$MBEDTLS_SHA" "${urls[@]}"
unpack "$f" "mbedtls-$MBEDTLS_VER"
cmake_cross "$WORK/mbedtls-$MBEDTLS_VER" "$WORK/mbedtls-$MBEDTLS_VER/build" \
-DENABLE_TESTING=OFF -DENABLE_PROGRAMS=OFF -DGEN_FILES=OFF \
-DUSE_STATIC_MBEDTLS_LIBRARY=ON -DUSE_SHARED_MBEDTLS_LIBRARY=OFF \
-DMBEDTLS_FATAL_WARNINGS=OFF
echo "mbedTLS $MBEDTLS_VER -> $PREFIX"
}
build_curl() {
local f="curl-$CURL_VER.tar.xz"
mapfile -t urls < <(gh "curl/curl/releases/download/curl-${CURL_VER//./_}/$f")
fetch "$f" "$CURL_SHA" "https://curl.se/download/$f" "${urls[@]}"
unpack "$f" "curl-$CURL_VER"
# Cross builds skip CA detection; this is only libcurl's default, the
# program probes the usual distro paths when it is missing.
cmake_cross "$WORK/curl-$CURL_VER" "$WORK/curl-$CURL_VER/build" \
-DBUILD_SHARED_LIBS=OFF -DBUILD_STATIC_LIBS=ON \
-DCURL_USE_MBEDTLS=ON -DCURL_USE_OPENSSL=OFF \
-DMBEDTLS_INCLUDE_DIR="$PREFIX/include" \
-DMBEDTLS_LIBRARY="$PREFIX/lib/libmbedtls.a" \
-DMBEDX509_LIBRARY="$PREFIX/lib/libmbedx509.a" \
-DMBEDCRYPTO_LIBRARY="$PREFIX/lib/libmbedcrypto.a" \
-DCURL_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt -DCURL_CA_PATH=none \
-DHTTP_ONLY=ON -DCURL_DISABLE_LDAP=ON -DCURL_USE_LIBPSL=OFF \
-DCURL_USE_LIBSSH2=OFF -DCURL_USE_LIBSSH=OFF -DUSE_LIBIDN2=OFF \
-DUSE_NGHTTP2=OFF -DCURL_ZLIB=OFF -DCURL_BROTLI=OFF -DCURL_ZSTD=OFF \
-DCURL_USE_GSSAPI=OFF -DENABLE_THREADED_RESOLVER=ON \
-DBUILD_CURL_EXE=OFF -DBUILD_TESTING=OFF -DBUILD_EXAMPLES=OFF \
-DBUILD_LIBCURL_DOCS=OFF -DBUILD_MISC_DOCS=OFF -DENABLE_CURL_MANUAL=OFF
echo "curl $CURL_VER -> $PREFIX"
}
build_ncurses() {
local f="ncurses-$NCURSES_VER.tar.gz"
fetch "$f" "$NCURSES_SHA" \
"https://invisible-island.net/archives/ncurses/$f" \
"https://mirrors.tuna.tsinghua.edu.cn/gnu/ncurses/$f" \
"https://ftp.gnu.org/gnu/ncurses/$f"
unpack "$f" "ncurses-$NCURSES_VER"
local b="$WORK/ncurses-$NCURSES_VER/build"
mkdir -p "$b"
cd "$b"
CC="${T}gcc" AR="${T}ar" RANLIB="${T}ranlib" STRIP="${T}strip" \
../configure --host="$LINUX_HOST" --prefix="$PREFIX" \
--without-ada --without-cxx --without-cxx-binding --without-manpages \
--without-progs --without-tests --without-debug --without-shared \
--with-normal --enable-widec --disable-db-install \
--with-default-terminfo-dir=/usr/share/terminfo \
--with-terminfo-dirs=/etc/terminfo:/lib/terminfo:/usr/share/terminfo:/usr/lib/terminfo \
--with-fallbacks="$NCURSES_FALLBACKS" \
--with-tic-path="$(command -v tic)" --with-infocmp-path="$(command -v infocmp)" \
--enable-pc-files --with-pkg-config-libdir="$PREFIX/lib/pkgconfig" \
--with-build-cc="${BUILD_CC:-cc}" >/dev/null
make -j"$JOBS" libs >/dev/null
make install.libs >/dev/null
echo "ncurses $NCURSES_VER -> $PREFIX"
}
case "${2:-all}" in
mbedtls) build_mbedtls ;;
curl) build_curl ;;
ncurses) build_ncurses ;;
all)
build_mbedtls
build_curl
build_ncurses
;;
*)
echo "usage: $0 ARCH [all|mbedtls|curl|ncurses]" >&2
exit 1
;;
esac
echo "DONE $ARCH"
+4 -1
View File
@@ -106,7 +106,10 @@ build_ncurses() {
rm -rf "$src/build-mingw"
mkdir -p "$src/build-mingw"
cd "$src/build-mingw"
../configure --host="${HOST:-x86_64-w64-mingw32}" --prefix="$PREFIX" \
# --host stays canonical (config.sub may not know Debian's "mingw32ucrt");
# the tools themselves come from $HOST.
CC="${T}gcc" AR="${T}ar" RANLIB="${T}ranlib" STRIP="${T}strip" WINDRES="${T}windres" \
../configure --host=x86_64-w64-mingw32 --prefix="$PREFIX" \
--without-ada --without-cxx --without-cxx-binding --without-manpages \
--without-progs --without-tests --without-debug --without-shared \
--enable-widec --enable-sp-funcs --enable-term-driver \
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env bash
# Fetch a musl cross gcc for a static Linux release build.
# scripts/ci_linux_toolchain.sh x86_64|x86|aarch64
# Prints "HOST BINDIR" on stdout (e.g. "x86_64-buildroot-linux-musl
# /opt/x86-64--musl--stable-2025.08-1/bin"); progress goes to stderr.
# Bootlin's pinned stable release first, musl.cc as a fallback.
set -euo pipefail
ARCH="${1:?usage: $0 x86_64|x86|aarch64}"
BOOTLIN_VER="${CST_BOOTLIN_VER:-2025.08-1}"
case "$ARCH" in
x86_64)
bl=x86-64 bl_host=x86_64-buildroot-linux-musl mc=x86_64-linux-musl
sha=09fca3aa89540f1b01b5f4210d488cbeb00f522044c53e9989b1dd8a38076912
;;
x86)
bl=x86-i686 bl_host=i686-buildroot-linux-musl mc=i686-linux-musl
sha=3a340ebc386a057f5ddb24d8f4bbde07d2c013c99cebc02ac38565e2849bfda0
;;
aarch64)
bl=aarch64 bl_host=aarch64-buildroot-linux-musl mc=aarch64-linux-musl
sha=defba831ffa1175236f137069333e21ed46d4d19feb5080a90cf248b6fc2cb08
;;
*)
echo "unknown arch: $ARCH" >&2
exit 1
;;
esac
[[ "$BOOTLIN_VER" == 2025.08-1 ]] || sha="" # other releases: no pinned hash
if [[ -n "${CST_TOOLCHAIN_ROOT:-}" ]]; then
ROOT_DIR="$CST_TOOLCHAIN_ROOT"
elif [[ -w /opt || "$(id -u)" -eq 0 ]]; then
ROOT_DIR=/opt
else
ROOT_DIR="$HOME/.local/toolchains"
fi
mkdir -p "$ROOT_DIR"
fetch() { # out url...
local out="$1" u
shift
for u in "$@"; do
echo " try $u" >&2
if curl -fsSL --retry 2 --connect-timeout 15 --max-time 900 -o "$out" "$u"; then
return 0
fi
done
return 1
}
emit() { # host bindir
"$2/$1-gcc" -dumpmachine >&2
[[ -n "${GITHUB_PATH:-}" ]] && echo "$2" >>"$GITHUB_PATH"
echo "$1 $2"
}
name="$bl--musl--stable-$BOOTLIN_VER"
dir="$ROOT_DIR/$name"
if [[ -x "$dir/bin/$bl_host-gcc" ]]; then
emit "$bl_host" "$dir/bin"
exit 0
fi
echo "==> toolchain $name" >&2
tmp="$ROOT_DIR/$name.tar.xz"
if fetch "$tmp" "https://toolchains.bootlin.com/downloads/releases/toolchains/$bl/tarballs/$name.tar.xz" &&
{ [[ -z "$sha" ]] || echo "$sha $tmp" | sha256sum -c --quiet - >&2; }; then
tar -C "$ROOT_DIR" -xJf "$tmp"
rm -f "$tmp"
# Bootlin toolchains are relocatable but must be told once where they are.
[[ -x "$dir/relocate-sdk.sh" ]] && "$dir/relocate-sdk.sh" >&2
emit "$bl_host" "$dir/bin"
exit 0
fi
rm -f "$tmp"
echo "==> bootlin unavailable, falling back to musl.cc" >&2
mdir="$ROOT_DIR/$mc-cross"
if [[ ! -x "$mdir/bin/$mc-gcc" ]]; then
tgz="$ROOT_DIR/$mc-cross.tgz"
fetch "$tgz" "https://musl.cc/$mc-cross.tgz" "https://more.musl.cc/x86_64-linux-musl/$mc-cross.tgz" ||
{ echo "no musl toolchain for $ARCH" >&2; exit 1; }
tar -C "$ROOT_DIR" -xzf "$tgz"
rm -f "$tgz"
fi
emit "$mc" "$mdir/bin"
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env bash
# CI helper: build the pinned TinyCC used for the verification job.
# Distro tcc packages are too old (no <stdatomic.h>), so this builds the same
# mob snapshot nixpkgs ships. Installs to $CST_TCC_PREFIX (default ~/.local/tcc)
# and, under Actions, puts its bin/ on $GITHUB_PATH.
set -euo pipefail
COMMIT="${CST_TCC_COMMIT:-f6385c05308f715bdd2c06336801193a21d69b50}"
PREFIX="${CST_TCC_PREFIX:-$HOME/.local/tcc}"
WORK="${TMPDIR:-/tmp}/tcc-build"
if [[ -x "$PREFIX/bin/tcc" ]]; then
echo "==> tcc already at $PREFIX"
else
rm -rf "$WORK"
mkdir -p "$WORK"
TGZ="$WORK/tinycc.tar.gz"
# repo.or.cz is upstream but often unreachable from CN runners; the GitHub
# mirror carries the same commits.
urls=(
"https://ghfast.top/https://github.com/TinyCC/tinycc/archive/${COMMIT}.tar.gz"
"https://ghproxy.net/https://github.com/TinyCC/tinycc/archive/${COMMIT}.tar.gz"
"https://github.com/TinyCC/tinycc/archive/${COMMIT}.tar.gz"
"https://repo.or.cz/tinycc.git/snapshot/${COMMIT}.tar.gz"
)
ok=0
for u in "${urls[@]}"; do
echo " try $u"
if curl -fsSL --retry 2 --connect-timeout 15 --max-time 300 -o "$TGZ" "$u" &&
tar -tzf "$TGZ" 2>/dev/null | sed -n 1p | grep -q "${COMMIT:0:7}"; then
ok=1
break
fi
done
[[ $ok -eq 1 ]] || { echo "failed to download tinycc $COMMIT" >&2; exit 1; }
tar -C "$WORK" -xzf "$TGZ"
src=$(find "$WORK" -mindepth 1 -maxdepth 1 -type d -name 'tinycc*' | head -1)
cd "$src"
./configure --prefix="$PREFIX" --cc="${BUILD_CC:-cc}"
make -j"$(nproc)"
make install
fi
"$PREFIX/bin/tcc" -v
if [[ -n "${GITHUB_PATH:-}" ]]; then
echo "$PREFIX/bin" >>"$GITHUB_PATH"
fi
+12 -50
View File
@@ -1,64 +1,26 @@
#!/usr/bin/env bash
# CI helper: MinGW-w64 UCRT toolchain via llvm-mingw (no Nix / no /nix).
# Downloads a pinned release, puts it on PATH, then runs bootstrap_windows.sh.
# CI helper: Windows x86_64 release with Debian's mingw-w64 UCRT gcc.
# apt-get install gcc-mingw-w64-ucrt64 binutils-mingw-w64-ucrt64 nsis (trixie+)
# Checks the toolchain, then runs bootstrap_windows.sh, which builds the
# third-party libs, cst-agent.exe, the zip and the NSIS installer.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
VER="${CST_LLVM_MINGW_VER:-20241030}"
NAME="llvm-mingw-${VER}-ucrt-ubuntu-20.04-x86_64"
TGZ="/tmp/${NAME}.tar.xz"
# Prefer /opt when writable (root CI); else unpack under $HOME.
if [[ -w /opt || "$(id -u)" -eq 0 ]]; then
DIR="/opt/${NAME}"
PARENT=/opt
else
DIR="${HOME}/${NAME}"
PARENT="$HOME"
fi
if [[ ! -x "$DIR/bin/x86_64-w64-mingw32-gcc" ]]; then
echo "==> download $NAME"
# Prefer CN-reachable GitHub proxies; raw github.com is often unreachable.
urls=(
"https://ghfast.top/https://github.com/mstorsjo/llvm-mingw/releases/download/${VER}/${NAME}.tar.xz"
"https://ghproxy.net/https://github.com/mstorsjo/llvm-mingw/releases/download/${VER}/${NAME}.tar.xz"
"https://gitclone.com/github.com/mstorsjo/llvm-mingw/releases/download/${VER}/${NAME}.tar.xz"
"https://github.com/mstorsjo/llvm-mingw/releases/download/${VER}/${NAME}.tar.xz"
)
ok=0
for u in "${urls[@]}"; do
echo " try $u"
if curl -fL --retry 2 --connect-timeout 15 --max-time 600 \
--retry-delay 2 -o "$TGZ" "$u"; then
# Reject tiny error pages that some proxies return with HTTP 200.
sz=$(wc -c <"$TGZ")
if [[ "$sz" -gt 10000000 ]]; then
ok=1
break
fi
echo " too small ($sz bytes), next mirror"
fi
done
[[ $ok -eq 1 ]] || { echo "failed to download llvm-mingw" >&2; exit 1; }
rm -rf "$DIR"
mkdir -p "$PARENT"
tar -C "$PARENT" -xf "$TGZ"
fi
export PATH="$DIR/bin:$PATH"
export MINGW_HOST=x86_64-w64-mingw32
export MINGW_HOST="${MINGW_HOST:-x86_64-w64-mingw32ucrt}"
export BUILD_CC="${BUILD_CC:-cc}"
export CST_REQUIRE_NSIS=1
need() { command -v "$1" >/dev/null || { echo "missing $1" >&2; exit 1; }; }
need x86_64-w64-mingw32-gcc
need x86_64-w64-mingw32-windres
need cmake; need ninja; need perl; need zip; need git; need make
need "$MINGW_HOST-gcc"
need "$MINGW_HOST-windres"
need cmake; need ninja; need perl; need zip; need git; need make; need makensis
if ! printf '#include <stdio.h>\n' | x86_64-w64-mingw32-gcc -dM -E - | grep -qw _UCRT; then
echo "toolchain is not UCRT" >&2
if ! printf '#include <stdio.h>\n' | "$MINGW_HOST-gcc" -dM -E - | grep -qw _UCRT; then
echo "$MINGW_HOST-gcc is not UCRT" >&2
exit 1
fi
"$MINGW_HOST-gcc" --version | head -1
# Do not set a global insteadOf: a single broken proxy (e.g. gitclone 502)
# would take down every third_party clone. build_third_party_mingw.sh tries
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
# Static musl build of cst-agent for one architecture, packed as
# dist/cst-agent-VERSION-linux-ARCH.tar.gz (+ .sha256).
# scripts/package_linux.sh x86_64|x86|aarch64
# CST_LINUX_CHECK=1 also runs `make check` (only where the binaries can run).
# Builds in the source tree, so the tree is cleaned first.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
ARCH="${1:?usage: $0 x86_64|x86|aarch64}"
PREFIX="$ROOT/third_party/prefix-linux-$ARCH"
cd "$ROOT"
read -r LINUX_HOST bindir < <(bash scripts/ci_linux_toolchain.sh "$ARCH")
export PATH="$bindir:$PATH" LINUX_HOST
T="$LINUX_HOST-"
if [[ ! -f "$PREFIX/lib/libcurl.a" || ! -f "$PREFIX/lib/libncursesw.a" ]]; then
bash scripts/build_third_party_linux.sh "$ARCH"
fi
# Only the static prefix: no host .pc file may leak into the link.
export PKG_CONFIG_LIBDIR="$PREFIX/lib/pkgconfig"
unset PKG_CONFIG_PATH CC CFLAGS LDFLAGS
mk=(make CC="${T}gcc" AR="${T}ar" STATIC=1
CFLAGS="-std=c11 -Wall -Wextra -O2 -g -Werror")
make clean >/dev/null
make -C vendor/sashidown clean >/dev/null 2>&1 || true
"${mk[@]}" -j"$(nproc)" cst-agent
if "${T}readelf" -l cst-agent | grep -q 'Requesting program interpreter'; then
echo "cst-agent is dynamically linked" >&2
exit 1
fi
if [[ "${CST_LINUX_CHECK:-0}" == 1 ]]; then
"${mk[@]}" check
fi
ver="$(sed -n 's/^#define CST_VERSION_\(MAJOR\|MINOR\|PATCH\) \([0-9]*\)$/\2/p' include/cst_version.h | paste -sd.)"
name="cst-agent-$ver-linux-$ARCH"
rel="dist/$name"
rm -rf "$rel"
mkdir -p "$rel"
cp -f cst-agent "$rel/cst-agent"
"${T}strip" "$rel/cst-agent"
cp -f README.md "$rel/README.md"
echo "$ver" >"$rel/VERSION"
tgz="dist/$name.tar.gz"
tar -C dist -czf "$tgz" "$name"
(cd dist && sha256sum "$name.tar.gz" >"$name.tar.gz.sha256")
ls -la "$rel"
echo "$ROOT/$tgz"
+15
View File
@@ -36,3 +36,18 @@ rm -f "$zip"
(cd "$ROOT/dist" && sha256sum "$(basename "$zip")" >"$(basename "$zip").sha256")
ls -la "$REL"
echo "$zip"
# NSIS installer from the same folder (CST_REQUIRE_NSIS=1: fail without makensis).
setup="$ROOT/dist/cst-agent-$ver-windows-x86_64-setup.exe"
if command -v makensis >/dev/null; then
rm -f "$setup"
makensis -V2 -WX -INPUTCHARSET UTF8 -DVERSION="$ver" -DSRCDIR="$REL" \
-DOUTFILE="$setup" "$ROOT/scripts/windows/cst-agent.nsi"
(cd "$ROOT/dist" && sha256sum "$(basename "$setup")" >"$(basename "$setup").sha256")
echo "$setup"
elif [[ "${CST_REQUIRE_NSIS:-0}" == 1 ]]; then
echo "makensis not found" >&2
exit 1
else
echo "makensis not found; skipping the installer" >&2
fi
@@ -1,10 +1,12 @@
#!/usr/bin/env bash
# Publish dist/cst-agent-VERSION-windows-x86_64.zip (+ .sha256) to the Gitea
# release vVERSION, creating the release (and its tag at HEAD) when missing.
# GITEA_TOKEN=... scripts/release_windows.sh [--build]
# --build runs scripts/bootstrap_windows.sh first. The token is only read from
# the environment and handed to curl on stdin: it never appears in argv, on
# disk or in the output. Assets of the same name are replaced.
# Upload release files to the Gitea release vVERSION, creating the release
# (and its tag at HEAD) when missing.
# GITEA_TOKEN=... scripts/release.sh FILE...
# Each FILE's FILE.sha256 is uploaded too when it exists; assets of the same
# name are replaced. Several CI jobs may call this at once: the first creates
# the release, the others find it. The token is only read from the
# environment and handed to curl on stdin: it never appears in argv, on disk
# or in the output.
#
# CI: set GITEA_TOKEN (or GITHUB_TOKEN), CST_GITEA, CST_REPO. The remote-branch
# check is skipped under GITEA_ACTIONS / GITHUB_ACTIONS / CI.
@@ -19,16 +21,20 @@ TOKEN="${GITEA_TOKEN:-${GITHUB_TOKEN:-}}"
echo "set GITEA_TOKEN (a Gitea token with write:repository)" >&2
exit 1
}
[[ $# -gt 0 ]] || { echo "usage: $0 FILE..." >&2; exit 1; }
command -v python3 >/dev/null || { echo "missing python3" >&2; exit 1; }
files=()
for f in "$@"; do
[[ -f "$f" ]] || { echo "missing $f" >&2; exit 1; }
f="$(cd "$(dirname "$f")" && pwd)/$(basename "$f")"
files+=("$f")
[[ "$f" != *.sha256 && -f "$f.sha256" ]] && files+=("$f.sha256")
done
cd "$ROOT"
[[ "${1:-}" == --build ]] && scripts/bootstrap_windows.sh "$ROOT"
ver="$(sed -n 's/^#define CST_VERSION_\(MAJOR\|MINOR\|PATCH\) \([0-9]*\)$/\2/p' include/cst_version.h | paste -sd.)"
tag="v$ver"
zip="dist/cst-agent-$ver-windows-x86_64.zip"
for f in "$zip" "$zip.sha256"; do
[[ -f "$f" ]] || { echo "missing $f (scripts/package_windows.sh, or --build)" >&2; exit 1; }
done
# If this job was triggered by a version tag, it must match cst_version.h.
if [[ "${GITHUB_REF:-}" == refs/tags/v* ]]; then
@@ -51,6 +57,12 @@ json() { # CODE [ARGS...]: d = the JSON on stdin, ARGS in sys.argv[1:]
python3 -c "import json,sys; d=json.load(sys.stdin); $code" "$@"
}
BODY="Linux (static, musl, any distro): cst-agent-$ver-linux-{x86_64,x86,aarch64}.tar.gz -- extract and run ./cst-agent, or copy it onto PATH.
Windows x86_64: cst-agent-$ver-windows-x86_64-setup.exe installs per user (no admin rights) and adds PATH; cst-agent-$ver-windows-x86_64.zip is the portable build (install_windows.ps1 inside).
Every file has a .sha256 next to it."
if rel="$(api GET "/releases/tags/$tag" 2>/dev/null)"; then
echo "==> release $tag exists"
else
@@ -62,12 +74,22 @@ else
fi
fi
echo "==> creating release $tag at $head"
body="$(python3 -c 'import json,sys; print(json.dumps({"tag_name": sys.argv[1], "target_commitish": sys.argv[2], "name": "CST-Agent " + sys.argv[1], "body": "Windows x86_64: unzip, or install with install_windows.ps1 from the zip.\\n\\nArtifacts: `cst-agent-VERSION-windows-x86_64.zip` + `.sha256`."}))' "$tag" "$head")"
rel="$(api POST /releases -H 'Content-Type: application/json' -d "$body")"
body="$(python3 -c 'import json,sys; print(json.dumps({"tag_name": sys.argv[1], "target_commitish": sys.argv[2], "name": "CST-Agent " + sys.argv[1], "body": sys.argv[3]}))' "$tag" "$head" "$BODY")"
if ! rel="$(api POST /releases -H 'Content-Type: application/json' -d "$body" 2>/dev/null)"; then
# Another job created it first (409).
rel=""
for _ in 1 2 3 4 5 6; do
sleep 5
rel="$(api GET "/releases/tags/$tag" 2>/dev/null)" && break
rel=""
done
[[ -n "$rel" ]] || { echo "could not create or find release $tag" >&2; exit 1; }
echo "==> release $tag created by another job"
fi
fi
id="$(json 'print(d["id"])' <<<"$rel")"
for f in "$zip" "$zip.sha256"; do
for f in "${files[@]}"; do
name="$(basename "$f")"
old="$(json "print(' '.join(str(a['id']) for a in d.get('assets') or [] if a['name'] == sys.argv[1]))" "$name" <<<"$rel")"
for aid in $old; do
+151
View File
@@ -0,0 +1,151 @@
; CST-Agent per-user installer (no admin rights).
; makensis -INPUTCHARSET UTF8 -DVERSION=0.8.5 -DSRCDIR=dist/windows-x86_64 -DOUTFILE=setup.exe cst-agent.nsi
; Installs the same files as the zip into %LOCALAPPDATA%\Programs\cst-agent,
; adds that folder to the user PATH and registers an uninstaller under HKCU.
Unicode true
SetCompressor /SOLID lzma
RequestExecutionLevel user
!ifndef VERSION
!error "pass -DVERSION=x.y.z"
!endif
!ifndef SRCDIR
!error "pass -DSRCDIR=<dist/windows-x86_64>"
!endif
!ifndef OUTFILE
!define OUTFILE "cst-agent-${VERSION}-windows-x86_64-setup.exe"
!endif
!define APP "CST-Agent"
!define UNINST_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\cst-agent"
!include "MUI2.nsh"
!include "LogicLib.nsh"
!include "x64.nsh"
Name "${APP} ${VERSION}"
OutFile "${OUTFILE}"
InstallDir "$LOCALAPPDATA\Programs\cst-agent"
InstallDirRegKey HKCU "${UNINST_KEY}" "InstallLocation"
BrandingText "${APP} ${VERSION}"
VIProductVersion "${VERSION}.0"
VIAddVersionKey /LANG=1033 "ProductName" "${APP}"
VIAddVersionKey /LANG=1033 "ProductVersion" "${VERSION}"
VIAddVersionKey /LANG=1033 "FileVersion" "${VERSION}"
VIAddVersionKey /LANG=1033 "FileDescription" "${APP} installer"
VIAddVersionKey /LANG=1033 "LegalCopyright" "WHC"
!define MUI_ABORTWARNING
!define MUI_FINISHPAGE_RUN
!define MUI_FINISHPAGE_RUN_TEXT "$(RunWebUI)"
!define MUI_FINISHPAGE_RUN_FUNCTION LaunchWebUI
!insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_PAGE_FINISH
!insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES
!insertmacro MUI_LANGUAGE "English"
!insertmacro MUI_LANGUAGE "SimpChinese"
LangString NeedX64 ${LANG_ENGLISH} "${APP} needs 64-bit Windows."
LangString NeedX64 ${LANG_SIMPCHINESE} "${APP} 需要 64 位 Windows。"
LangString NeedBuild ${LANG_ENGLISH} "${APP} needs Windows 10 1903 (build 18362) or newer; this is build $0."
LangString NeedBuild ${LANG_SIMPCHINESE} "${APP} 需要 Windows 10 1903(内部版本 18362)或更新版本,当前为 $0。"
LangString RunWebUI ${LANG_ENGLISH} "Open the ${APP} WebUI"
LangString RunWebUI ${LANG_SIMPCHINESE} "打开 ${APP} WebUI"
LangString PathFail ${LANG_ENGLISH} "Could not add $INSTDIR to the user PATH; add it by hand."
LangString PathFail ${LANG_SIMPCHINESE} "未能把 $INSTDIR 加入用户 PATH,请手动添加。"
; PowerShell edits the user PATH: NSIS strings are capped at 1024 chars, and
; .NET broadcasts the change so new terminals see it. The folder is passed in
; the environment, so quotes in it cannot break the command.
!macro EditUserPath ACTION
System::Call 'Kernel32::SetEnvironmentVariable(t "CST_INSTDIR", t "$INSTDIR")'
nsExec::ExecToLog `powershell -NoProfile -ExecutionPolicy Bypass -Command "$$d = $$env:CST_INSTDIR.TrimEnd('\'); $$p = [Environment]::GetEnvironmentVariable('Path', 'User'); $$parts = @([string]$$p -split ';' | Where-Object { $$_ -and $$_.TrimEnd('\') -ine $$d }); if ('${ACTION}' -eq 'add') { $$parts += $$d }; [Environment]::SetEnvironmentVariable('Path', ($$parts -join ';'), 'User')"`
Pop $0
!macroend
; A running exe cannot be overwritten but can be renamed out of the way.
!macro MoveAside NAME
Delete "$INSTDIR\${NAME}.old"
ClearErrors
Delete "$INSTDIR\${NAME}"
${If} ${Errors}
Rename "$INSTDIR\${NAME}" "$INSTDIR\${NAME}.old"
${EndIf}
!macroend
Function .onInit
${IfNot} ${RunningX64}
MessageBox MB_ICONSTOP "$(NeedX64)"
Abort
${EndIf}
SetRegView 64
ReadRegStr $0 HKLM "SOFTWARE\Microsoft\Windows NT\CurrentVersion" "CurrentBuildNumber"
${If} $0 < 18362
MessageBox MB_ICONSTOP "$(NeedBuild)"
Abort
${EndIf}
FunctionEnd
Function LaunchWebUI
SetOutPath "$PROFILE"
Exec '"$INSTDIR\cst-agent.exe" --web --web-open'
FunctionEnd
Section "Install"
SetShellVarContext current
SetOutPath "$INSTDIR"
!insertmacro MoveAside "cst-agent.exe"
!insertmacro MoveAside "busybox.exe"
File "${SRCDIR}/cst-agent.exe"
File "${SRCDIR}/busybox.exe"
File "${SRCDIR}/LICENSE.busybox"
File "${SRCDIR}/README.md"
File "${SRCDIR}/cst-agent-update.cmd"
File "${SRCDIR}/install_windows.ps1"
File "${SRCDIR}/VERSION"
WriteUninstaller "$INSTDIR\uninstall.exe"
!insertmacro EditUserPath "add"
${If} $0 != 0
DetailPrint "$(PathFail)"
${EndIf}
; The WebUI's workspace is the shortcut's start folder.
SetOutPath "$PROFILE"
CreateShortCut "$SMPROGRAMS\${APP} WebUI.lnk" "$INSTDIR\cst-agent.exe" "--web --web-open" "$INSTDIR\cst-agent.exe" 0
SetOutPath "$INSTDIR"
WriteRegStr HKCU "${UNINST_KEY}" "DisplayName" "${APP}"
WriteRegStr HKCU "${UNINST_KEY}" "DisplayVersion" "${VERSION}"
WriteRegStr HKCU "${UNINST_KEY}" "Publisher" "WHC"
WriteRegStr HKCU "${UNINST_KEY}" "DisplayIcon" "$INSTDIR\cst-agent.exe"
WriteRegStr HKCU "${UNINST_KEY}" "InstallLocation" "$INSTDIR"
WriteRegStr HKCU "${UNINST_KEY}" "UninstallString" '"$INSTDIR\uninstall.exe"'
WriteRegStr HKCU "${UNINST_KEY}" "QuietUninstallString" '"$INSTDIR\uninstall.exe" /S'
WriteRegStr HKCU "${UNINST_KEY}" "URLInfoAbout" "https://git.whcself.xyz/WHC/CST-agent"
WriteRegDWORD HKCU "${UNINST_KEY}" "NoModify" 1
WriteRegDWORD HKCU "${UNINST_KEY}" "NoRepair" 1
SectionEnd
Section "Uninstall"
SetShellVarContext current
!insertmacro EditUserPath "remove"
Delete "$SMPROGRAMS\${APP} WebUI.lnk"
Delete "$INSTDIR\cst-agent.exe"
Delete "$INSTDIR\cst-agent.exe.old"
Delete "$INSTDIR\busybox.exe"
Delete "$INSTDIR\busybox.exe.old"
Delete "$INSTDIR\LICENSE.busybox"
Delete "$INSTDIR\README.md"
Delete "$INSTDIR\cst-agent-update.cmd"
Delete "$INSTDIR\install_windows.ps1"
Delete "$INSTDIR\VERSION"
Delete "$INSTDIR\uninstall.exe"
RMDir "$INSTDIR"
DeleteRegKey HKCU "${UNINST_KEY}"
SectionEnd
+1
View File
@@ -15,6 +15,7 @@ win.mkShell {
pkg-config
zip
curl
nsis
];
buildInputs = [ win.windows.pthreads ];
# mkShell exports CC/AR for the target; the build scripts call the prefixed tools directly.
+108 -6
View File
@@ -177,8 +177,62 @@ static int tool_on(const cst_agent_config_t *cfg, const char *name) {
return cst_tool_active(cfg, cst_tool_find(name));
}
/* /mode general (cst_mode_name covers "" and unknown values). */
static int general_mode(const cst_agent_config_t *cfg) {
return cfg && strcmp(cst_mode_name(cfg->mode), "general") == 0;
}
/* Workflow for /mode general: gather, then do the work, then check it. */
static void put_workflow_general(cst_buf_t *b, const cst_agent_config_t *cfg) {
cst_buf_puts(b, "\nWorkflow:\n1) Gather what you need");
const char *explore[] = {"list_dir", "glob", "grep"};
int n = 0;
for (int i = 0; i < 3; i++) {
if (tool_on(cfg, explore[i]))
cst_buf_printf(b, "%s%s", n++ ? ", " : " (", explore[i]);
}
if (n)
cst_buf_puts(b, ")");
if (tool_on(cfg, "read_file"))
cst_buf_puts(b, "; read big files in slices with read_file offset/limit, "
"and use the documents the user attached");
cst_buf_puts(b, ".\n2) Do the work");
n = 0;
if (tool_on(cfg, "write_file")) {
cst_buf_puts(b, ": write_file for new files");
n++;
}
if (tool_on(cfg, "edit_file"))
cst_buf_printf(b, "%sedit_file for small exact replacements",
n++ ? ", " : ": ");
if (tool_on(cfg, "apply_patch"))
cst_buf_printf(b, "%sapply_patch for multi-hunk diffs to existing files",
n++ ? ", " : ": ");
if (tool_on(cfg, "run_shell"))
cst_buf_printf(b, "%srun_shell for commands, computations, data "
"processing and other CLIs",
n++ ? ", " : ": ");
cst_buf_puts(b, ".\n");
if (tool_on(cfg, "run_shell"))
cst_buf_puts(b, "3) Check the result before saying it works (re-read it, "
"run it, or verify the numbers); fix and re-run until it "
"holds.\n");
if (tool_on(cfg, "todo_write"))
cst_buf_puts(b, "- For work with several steps keep a todo list with "
"todo_write and update it as you go.\n");
if (tool_on(cfg, "ask_user"))
cst_buf_puts(b, "- Use ask_user only when a decision is truly the user's; "
"otherwise choose sensibly and say so.\n");
cst_buf_puts(b, "Finish with a short plain-text summary of the result.\n"
"Never invent other tool names.\n");
}
/* Workflow section for the default tool profile; names only active tools. */
static void put_workflow(cst_buf_t *b, const cst_agent_config_t *cfg) {
if (general_mode(cfg)) {
put_workflow_general(b, cfg);
return;
}
cst_buf_puts(b, "\nWorkflow:\n1) Inspect only what you need");
const char *explore[] = {"list_dir", "glob", "grep"};
int n = 0;
@@ -235,6 +289,25 @@ static const char DEF_INTRO[] =
"could not verify, say so.\n"
"- Keep going until the task is done or truly blocked.\n\n";
/* Same role, framed for /mode general: the workspace may hold documents,
* data or anything else, not just code. */
static const char DEF_INTRO_GENERAL[] =
"You are CST-Agent, a general-purpose assistant working in the user's "
"local workspace. All tool paths are relative to the workspace root and "
"shell commands run there; the material you work on may be code, "
"documents, data or anything else.\n\n"
"Principles:\n"
"- Reply in the user's language. Be concise: lead with the result, no "
"filler.\n"
"- Understand before answering: read the files, documents and sources the "
"task refers to instead of guessing; never invent content, numbers or "
"tool results.\n"
"- Do what was asked, at the scope asked: leave unrelated files, data and "
"material alone.\n"
"- Check your work when you can (re-read it, run it, cross-check the "
"source); if you could not verify something, say so.\n"
"- Keep going until the task is done or truly blocked.\n\n";
static void put_tool_use(cst_buf_t *b, const cst_agent_config_t *cfg) {
cst_buf_puts(b, "\nTool use:\n");
if (tool_on(cfg, "run_shell") &&
@@ -248,15 +321,26 @@ static void put_tool_use(cst_buf_t *b, const cst_agent_config_t *cfg) {
cst_buf_puts(b, "- Read a file before editing it and again after a failed "
"edit. The `N|` prefixes in read_file output are not part "
"of the file.\n");
if (general_mode(cfg) && tool_on(cfg, "web_fetch"))
cst_buf_puts(b, "- Use web_fetch for pages the user points you to; say so "
"when a page could not be fetched instead of guessing its "
"content.\n");
cst_buf_puts(b, "- When a call fails, read the error and change approach "
"instead of repeating the same call.\n");
}
static void put_safety(cst_buf_t *b, const cst_agent_config_t *cfg) {
cst_buf_puts(b, "\nSafety:\n"
"- Do not commit, push or rewrite git history unless asked. "
"Do not delete or overwrite files you did not create unless "
"the task requires it. Never print secrets or API keys.\n");
if (general_mode(cfg))
cst_buf_puts(b, "\nSafety:\n"
"- Do not delete or overwrite files or data you did not "
"create unless the task requires it, and do not send the "
"user's content anywhere the task did not ask for. Never "
"print secrets or API keys.\n");
else
cst_buf_puts(b, "\nSafety:\n"
"- Do not commit, push or rewrite git history unless asked. "
"Do not delete or overwrite files you did not create unless "
"the task requires it. Never print secrets or API keys.\n");
if (tool_on(cfg, "run_shell"))
cst_buf_puts(b, "- run_shell may run in a sandbox (writes only inside the "
"workspace and temp dir; the network works). If a command is "
@@ -365,7 +449,9 @@ char *cst_agent_build_prompt(const cst_agent_config_t *cfg, cst_protocol_t p,
const char *project_notes) {
int minimal = !cfg || cfg->tool_profile == CST_TOOLS_MINIMAL;
cst_buf_t b = {0};
cst_buf_puts(&b, minimal ? PROMPT_BASE : DEF_INTRO);
cst_buf_puts(&b, minimal ? PROMPT_BASE
: general_mode(cfg) ? DEF_INTRO_GENERAL
: DEF_INTRO);
if (cst_protocol_is_native(p))
cst_buf_puts(&b, minimal ? SEC_NATIVE
: "Call tools through the native "
@@ -2241,11 +2327,12 @@ int cst_agent_undo_available(const cst_agent_t *a) {
* later changes reach the model as persisted notes appended to the history,
* which keeps the cached prefix intact. */
#define PROMPT_VERSION 2
#define PROMPT_VERSION 3
typedef struct {
int plan;
char approval[96];
char mode[16];
char branch[128];
char day[16];
char notes[24]; /* hash of AGENTS.md, "" = none */
@@ -2255,6 +2342,7 @@ static void state_now(const cst_agent_t *a, pstate_t *s) {
memset(s, 0, sizeof(*s));
s->plan = a->cfg.plan_mode;
snprintf(s->approval, sizeof(s->approval), "%s", approval_desc(&a->cfg));
snprintf(s->mode, sizeof(s->mode), "%s", cst_mode_name(a->cfg.mode));
git_branch(a->cfg.workspace_root, s->branch, sizeof(s->branch));
today(s->day, sizeof(s->day));
if (a->notes && a->notes[0])
@@ -2267,6 +2355,7 @@ static cJSON *state_json(const pstate_t *s) {
cJSON *o = cJSON_CreateObject();
cJSON_AddNumberToObject(o, "plan", s->plan);
cJSON_AddStringToObject(o, "approval", s->approval);
cJSON_AddStringToObject(o, "mode", s->mode);
cJSON_AddStringToObject(o, "branch", s->branch);
cJSON_AddStringToObject(o, "day", s->day);
cJSON_AddStringToObject(o, "notes", s->notes);
@@ -2282,6 +2371,7 @@ static void state_parse(const cJSON *o, pstate_t *s) {
if (cJSON_IsString(v)) \
snprintf(s->field, sizeof(s->field), "%s", v->valuestring);
STATE_STR("approval", approval)
STATE_STR("mode", mode)
STATE_STR("branch", branch)
STATE_STR("day", day)
STATE_STR("notes", notes)
@@ -2293,6 +2383,7 @@ static char *system_meta(const cst_agent_t *a, const pstate_t *s) {
cJSON_AddStringToObject(o, "protocol", cst_protocol_name(a->cfg.protocol));
cJSON_AddNumberToObject(o, "pv", PROMPT_VERSION);
cJSON_AddNumberToObject(o, "tools", a->cfg.tool_profile);
cJSON_AddStringToObject(o, "mode", cst_mode_name(a->cfg.mode));
cJSON_AddItemToObject(o, "state", state_json(s));
char *out = cJSON_PrintUnformatted(o);
cJSON_Delete(o);
@@ -2312,10 +2403,13 @@ static int system_current(const cst_message_t *m, const cst_agent_config_t *c) {
const cJSON *pv = cJSON_GetObjectItemCaseSensitive(meta, "pv");
const cJSON *pr = cJSON_GetObjectItemCaseSensitive(meta, "protocol");
const cJSON *tp = cJSON_GetObjectItemCaseSensitive(meta, "tools");
const cJSON *md = cJSON_GetObjectItemCaseSensitive(meta, "mode");
int ok = cJSON_IsNumber(pv) && pv->valueint == PROMPT_VERSION &&
cJSON_IsString(pr) &&
strcmp(pr->valuestring, cst_protocol_name(c->protocol)) == 0 &&
cJSON_IsNumber(tp) && tp->valueint == c->tool_profile;
ok = ok && cJSON_IsString(md) &&
strcmp(md->valuestring, cst_mode_name(c->mode)) == 0;
cJSON_Delete(meta);
return ok;
}
@@ -2393,6 +2487,14 @@ static void sync_notes(cst_agent_t *a) {
"is available again.\n");
if (strcmp(now.approval, was.approval) != 0)
cst_buf_printf(&b, "[cst] Approval mode is now %s.\n", now.approval);
if (strcmp(now.mode, was.mode) != 0)
cst_buf_printf(&b,
"[cst] Working mode is now %s%s. Earlier instructions about "
"how to frame the work no longer apply.\n",
now.mode,
strcmp(now.mode, "general") == 0
? " (general: documents, data, research)"
: " (coding: repo, build, tests)");
if (strcmp(now.branch, was.branch) != 0)
cst_buf_printf(&b, "[cst] The git branch is now %s.\n",
now.branch[0] ? now.branch : "(none)");
+129 -24
View File
@@ -4,6 +4,7 @@
#include "cJSON.h"
#include "cst_attach.h"
#include "cst_pdf.h"
#include "cst_util.h"
#include "os_compat.h"
@@ -102,6 +103,9 @@ static int le16(const unsigned char *p) {
}
static const char *mime_of_ext(const char *mime) {
if (strcmp(mime, "application/pdf") == 0 ||
strcmp(mime, "text/plain") == 0)
return "txt"; /* a document is stored as the text it was reduced to */
if (strcmp(mime, "image/png") == 0)
return "png";
if (strcmp(mime, "image/jpeg") == 0)
@@ -352,23 +356,73 @@ static void make_id(const char *name, const char *data, size_t n, char *out,
snprintf(out, out_sz, "img-%08x", (unsigned)(h & 0xFFFFFFFFu));
}
/* n bytes, NUL-terminated: a text payload is handed around as a C string. */
static char *memdup_z(const char *data, size_t n) {
char *copy = malloc(n + 1);
if (!copy)
return NULL;
memcpy(copy, data, n);
copy[n] = 0;
return copy;
}
/* What a picked file is, plus the payload to store for it: an image stays as
* it is, a PDF is reduced to its text layer (the mime still says PDF, the
* stored file holds text), anything else must be UTF-8 text. The caller frees
* the result; *out_len is its length. */
static char *prepare(const char *data, size_t n, char *mime, size_t mime_sz,
int *pages, size_t *out_len, char *err, size_t err_sz) {
*pages = 0;
*out_len = n;
if (cst_attach_sniff(data, n, mime, mime_sz) == 0) {
if (n > CST_ATTACH_MAX_BYTES) {
snprintf(err, err_sz, "image is %.1f MB; the limit is %d MB",
(double)n / (1024 * 1024), (int)(CST_ATTACH_MAX_BYTES >> 20));
return NULL;
}
char *copy = memdup_z(data, n);
if (!copy)
snprintf(err, err_sz, "out of memory");
return copy;
}
if (n >= 4 && memcmp(data, "%PDF", 4) == 0) {
int pg = 0;
char perr[256];
char *text = cst_pdf_text(data, n, &pg, perr, sizeof(perr));
if (!text) {
snprintf(err, err_sz, "cannot read the PDF: %.200s", perr);
return NULL;
}
snprintf(mime, mime_sz, "application/pdf");
*pages = pg;
*out_len = strlen(text);
return text;
}
if (n > CST_ATTACH_TEXT_MAX) {
snprintf(err, err_sz, "text is %.1f MB; the limit is %d MB",
(double)n / (1024 * 1024), (int)(CST_ATTACH_TEXT_MAX >> 20));
return NULL;
}
if (memchr(data, 0, n) || !cst_utf8_valid(data, n)) {
snprintf(err, err_sz,
"not an image (PNG, JPEG, GIF, WebP or BMP), a PDF or UTF-8 "
"text; the content decides, not the extension");
return NULL;
}
snprintf(mime, mime_sz, "text/plain");
char *copy = memdup_z(data, n);
if (!copy)
snprintf(err, err_sz, "out of memory");
return copy;
}
/* Write one payload whose kind is already known. */
static cst_attachment_t *store(const char *session_path, const char *name,
const char *data, size_t n, const char *origin,
char *err, size_t err_sz) {
const char *data, size_t n, const char *mime,
int pages, const char *origin, char *err,
size_t err_sz) {
if (!name || !name[0])
name = "image";
char mime[32];
if (cst_attach_sniff(data, n, mime, sizeof(mime)) != 0) {
snprintf(err, err_sz,
"not a supported image (PNG, JPEG, GIF, WebP or BMP; "
"checked by content, not by extension)");
return NULL;
}
if (n > CST_ATTACH_MAX_BYTES) {
snprintf(err, err_sz, "image is %.1f MB; the limit is %d MB",
(double)n / (1024 * 1024), (int)(CST_ATTACH_MAX_BYTES >> 20));
return NULL;
}
char dir[OS_PATH_MAX];
if (cst_attach_dir(session_path, dir, sizeof(dir)) != 0) {
snprintf(err, err_sz, "cannot create the attachment directory");
@@ -386,7 +440,9 @@ static cst_attachment_t *store(const char *session_path, const char *name,
snprintf(a->origin, sizeof(a->origin), "%s", origin ? origin : "user");
snprintf(a->detail, sizeof(a->detail), "auto");
a->bytes = (long long)n;
cst_attach_dimensions(data, n, &a->width, &a->height);
a->pages = pages;
if (cst_attach_is_image(a))
cst_attach_dimensions(data, n, &a->width, &a->height);
char full[OS_PATH_MAX];
if (cst_attach_full_path(session_path, a, full, sizeof(full)) != 0) {
@@ -419,14 +475,26 @@ cst_attachment_t *cst_attach_import_bytes(const char *session_path,
}
err[0] = 0;
if (!session_path || !session_path[0]) {
snprintf(err, err_sz, "no session to store the image in");
snprintf(err, err_sz, "no session to store the file in");
return NULL;
}
if (!data || !n) {
snprintf(err, err_sz, "image is empty");
snprintf(err, err_sz, "the file is empty");
return NULL;
}
return store(session_path, name, data, n, "user", err, err_sz);
char mime[32];
if (cst_attach_sniff(data, n, mime, sizeof(mime)) != 0) {
snprintf(err, err_sz,
"not a supported image (PNG, JPEG, GIF, WebP or BMP; "
"checked by content, not by extension)");
return NULL;
}
if (n > CST_ATTACH_MAX_BYTES) {
snprintf(err, err_sz, "image is %.1f MB; the limit is %d MB",
(double)n / (1024 * 1024), (int)(CST_ATTACH_MAX_BYTES >> 20));
return NULL;
}
return store(session_path, name, data, n, mime, 0, "user", err, err_sz);
}
cst_attachment_t *cst_attach_import_file(const char *session_path,
@@ -449,11 +517,30 @@ cst_attachment_t *cst_attach_import_file(const char *session_path,
for (const char *p = src_path; *p; p++)
if (*p == '/' || *p == '\\')
leaf = p + 1;
cst_attachment_t *a = store(session_path, leaf, data, n, "user", err, err_sz);
char mime[32];
int pages = 0;
size_t pn = 0;
char *payload =
prepare(data, n, mime, sizeof(mime), &pages, &pn, err, err_sz);
free(data);
if (!payload)
return NULL;
cst_attachment_t *a =
store(session_path, leaf, payload, pn, mime, pages, "user", err, err_sz);
free(payload);
return a;
}
/* Images are opaque and travel as image parts; everything else is text the
* store holds and the request inlines. */
int cst_attach_is_image(const cst_attachment_t *a) {
return a && strncmp(a->mime, "image/", 6) == 0;
}
int cst_attach_is_text(const cst_attachment_t *a) {
return a && !cst_attach_is_image(a);
}
char *cst_attach_read(const char *session_path, const cst_attachment_t *a,
size_t *out_len, char *err, size_t err_sz) {
char dummy[8];
@@ -470,11 +557,12 @@ char *cst_attach_read(const char *session_path, const cst_attachment_t *a,
char *data = read_whole(full, out_len, CST_ATTACH_MAX_BYTES);
if (!data) {
snprintf(err, err_sz,
"%.200s is missing; the image was deleted from the session "
"store",
"%.200s is missing; it was deleted from the session store",
a->name);
return NULL;
}
if (!cst_attach_is_image(a)) /* a document is text, nothing to verify */
return data;
char mime[32];
if (cst_attach_sniff(data, *out_len, mime, sizeof(mime)) != 0) {
snprintf(err, err_sz, "%.200s in the session store is no longer an image",
@@ -486,6 +574,8 @@ char *cst_attach_read(const char *session_path, const cst_attachment_t *a,
}
char *cst_attach_data_url(const char *session_path, const cst_attachment_t *a) {
if (!cst_attach_is_image(a)) /* a document travels as text, not as a URL */
return NULL;
char err[256];
size_t n = 0;
char *data = cst_attach_read(session_path, a, &n, err, sizeof(err));
@@ -509,10 +599,21 @@ void cst_attach_describe(const cst_attachment_t *a, char *out, size_t out_sz) {
snprintf(out, out_sz, "(none)");
return;
}
const char *kind = strncmp(a->mime, "image/", 6) == 0 ? a->mime + 6 : a->mime;
const char *kind = a->mime;
char dim[32] = "";
if (a->width > 0 && a->height > 0)
snprintf(dim, sizeof(dim), "%dx%d ", a->width, a->height);
if (cst_attach_is_image(a)) {
if (strncmp(a->mime, "image/", 6) == 0)
kind = a->mime + 6;
if (a->width > 0 && a->height > 0)
snprintf(dim, sizeof(dim), "%dx%d ", a->width, a->height);
} else if (strcmp(a->mime, "application/pdf") == 0) {
kind = "pdf";
if (a->pages > 0)
snprintf(dim, sizeof(dim), "%d page%s ", a->pages,
a->pages == 1 ? "" : "s");
} else if (strcmp(a->mime, "text/plain") == 0 || !a->mime[0]) {
kind = "text";
}
out[0] = 0;
if (a->bytes >= 1024 * 1024)
snprintf(out, out_sz, "%s%s %.1f MB", dim, kind,
@@ -580,6 +681,8 @@ char *cst_attachments_to_json(const cst_attachment_t *list, int n) {
cJSON_AddNumberToObject(o, "width", a->width);
cJSON_AddNumberToObject(o, "height", a->height);
}
if (a->pages > 0)
cJSON_AddNumberToObject(o, "pages", a->pages);
if (a->detail[0] && strcmp(a->detail, "auto") != 0)
cJSON_AddStringToObject(o, "detail", a->detail);
if (a->origin[0])
@@ -628,6 +731,8 @@ cst_attachment_t *cst_attachments_from_json(const void *array_json, int *n_out)
a->width = cJSON_IsNumber(v) ? v->valueint : 0;
v = cJSON_GetObjectItemCaseSensitive(it, "height");
a->height = cJSON_IsNumber(v) ? v->valueint : 0;
v = cJSON_GetObjectItemCaseSensitive(it, "pages");
a->pages = cJSON_IsNumber(v) ? v->valueint : 0;
v = cJSON_GetObjectItemCaseSensitive(it, "detail");
snprintf(a->detail, sizeof(a->detail), "%s",
cJSON_IsString(v) ? v->valuestring : "auto");
+169
View File
@@ -390,6 +390,175 @@ int cst_clipboard_image(char **data, size_t *n, char *err, size_t err_sz) {
#endif
/* --- text clipboard ------------------------------------------------------ */
#ifdef _WIN32
int cst_clipboard_text(char **data, size_t *n, char *err, size_t err_sz) {
*data = NULL;
*n = 0;
if (!IsClipboardFormatAvailable(CF_UNICODETEXT) || !OpenClipboard(NULL)) {
set_err(err, err_sz, "no text on the clipboard");
return -1;
}
HANDLE h = GetClipboardData(CF_UNICODETEXT);
const wchar_t *w = h ? GlobalLock(h) : NULL;
if (!w) {
if (h)
GlobalUnlock(h);
CloseClipboard();
set_err(err, err_sz, "no text on the clipboard");
return -1;
}
char *utf8 = os_wide_to_utf8(w);
size_t len = utf8 ? strlen(utf8) : 0;
GlobalUnlock(h);
CloseClipboard();
if (!utf8 || !len) {
free(utf8);
set_err(err, err_sz, "no text on the clipboard");
return -1;
}
if (len > CST_CLIPBOARD_TEXT_MAX) {
free(utf8);
set_err(err, err_sz, "clipboard text is too large");
return -1;
}
*data = utf8;
*n = len;
return 0;
}
int cst_clipboard_set_text(const char *text, size_t n, char *err,
size_t err_sz) {
if (!text || os_clipboard_set(text, n) != 0) {
set_err(err, err_sz, "could not put text on the clipboard");
return -1;
}
return 0;
}
#else
/* stdout of a clipboard reader, capped and NUL-terminated. */
static int clip_read(const char *cmd, const char *tool, char **data, size_t *n,
char *err, size_t err_sz) {
os_run_result_t r;
memset(&r, 0, sizeof(r));
if (os_run_shell_c(NULL, cmd, CST_CLIPBOARD_TEXT_MAX + 1, &r) != 0) {
os_run_result_free(&r);
set_err(err, err_sz, "could not read the clipboard");
return -1;
}
if (r.exit_code != 0 || r.out_len == 0) {
int missing = r.exit_code == 127;
os_run_result_free(&r);
if (missing) {
char msg[96];
snprintf(msg, sizeof(msg), "reading the clipboard needs %s", tool);
set_err(err, err_sz, msg);
} else {
set_err(err, err_sz, "no text on the clipboard");
}
return -1;
}
if (r.out_len > CST_CLIPBOARD_TEXT_MAX) {
os_run_result_free(&r);
set_err(err, err_sz, "clipboard text is too large");
return -1;
}
char *copy = malloc(r.out_len + 1);
if (!copy) {
os_run_result_free(&r);
set_err(err, err_sz, "out of memory");
return -1;
}
memcpy(copy, r.out, r.out_len);
copy[r.out_len] = 0;
os_run_result_free(&r);
*data = copy;
*n = r.out_len;
return 0;
}
int cst_clipboard_text(char **data, size_t *n, char *err, size_t err_sz) {
*data = NULL;
*n = 0;
#ifdef __APPLE__
return clip_read("pbpaste 2>/dev/null", "pbpaste", data, n, err, err_sz);
#else
const char *wl = getenv("WAYLAND_DISPLAY");
if (wl && *wl)
return clip_read("wl-paste --type text/plain --no-newline 2>/dev/null",
"wl-clipboard (wl-paste)", data, n, err, err_sz);
const char *x = getenv("DISPLAY");
if (x && *x)
return clip_read("xclip -selection clipboard -o 2>/dev/null", "xclip",
data, n, err, err_sz);
set_err(err, err_sz, "no clipboard here (no Wayland or X11 display)");
return -1;
#endif
}
int cst_clipboard_set_text(const char *text, size_t n, char *err,
size_t err_sz) {
if (!text)
return -1;
if (n > CST_CLIPBOARD_TEXT_MAX) {
set_err(err, err_sz, "text is too large for the clipboard");
return -1;
}
const char *fmt = NULL, *tool = NULL;
#ifdef __APPLE__
fmt = "pbcopy < '%s'";
tool = "pbcopy";
#else
if (getenv("WAYLAND_DISPLAY")) {
fmt = "wl-copy < '%s'";
tool = "wl-clipboard (wl-copy)";
} else if (getenv("DISPLAY")) {
fmt = "xclip -selection clipboard -i < '%s'";
tool = "xclip";
}
#endif
if (!fmt) {
set_err(err, err_sz, "no clipboard here (no Wayland or X11 display)");
return -1;
}
char tmp[OS_PATH_MAX];
int fd = os_mkstemp(tmp, sizeof(tmp), "cst-clip");
if (fd < 0) {
set_err(err, err_sz, "could not create a temporary file");
return -1;
}
FILE *fp = fdopen(fd, "wb");
int ok = fp && fwrite(text, 1, n, fp) == n && fclose(fp) == 0;
if (!ok) {
if (fp)
fclose(fp);
remove(tmp);
set_err(err, err_sz, "could not write the text");
return -1;
}
char cmd[OS_PATH_MAX + 64];
snprintf(cmd, sizeof(cmd), fmt, tmp);
os_run_result_t r;
memset(&r, 0, sizeof(r));
int rc = os_run_shell_c(NULL, cmd, 4096, &r);
int code = r.exit_code;
os_run_result_free(&r);
remove(tmp);
if (rc != 0 || code != 0) {
char msg[96];
snprintf(msg, sizeof(msg), "writing the clipboard needs %s", tool);
set_err(err, err_sz, msg);
return -1;
}
return 0;
}
#endif
static int hexval(int c) {
if (c >= '0' && c <= '9')
return c - '0';
+151 -52
View File
@@ -22,43 +22,75 @@
#define ERRBODY_MAX 4096
#define LLM_MAX_RETRIES 3
/* Point libcurl at a CA bundle on Windows.
static int ca_file_ok(const char *path) {
if (!path || !path[0])
return 0;
FILE *f = fopen(path, "rb");
if (!f)
return 0;
fclose(f);
return 1;
}
/* Point libcurl at a CA bundle.
*
* An OpenSSL-based libcurl keeps the path it was built with -- MSYS2's is
* "/mingw64/etc/ssl/certs/ca-bundle.crt", which resolves to nothing once the
* binary runs outside an MSYS2 shell, and that build ignores CURL_CA_BUNDLE.
* Every HTTPS request then dies with CURLE_SSL_CACERT_BADFILE (77).
* libcurl keeps the bundle path it was built with. On Windows an OpenSSL
* build carries MSYS2's "/mingw64/etc/ssl/certs/ca-bundle.crt"; the static
* Linux release is built on one distro and runs on all of them, whose bundles
* live in different places. A path that does not exist fails every HTTPS
* request with CURLE_SSL_CACERT_BADFILE (77).
*
* Order: $CST_CA_BUNDLE, then ca-bundle.crt beside the executable. If neither
* exists nothing is set, so a libcurl linked against Schannel (the Windows
* certificate store) behaves exactly as before. */
static void llm_apply_ca_bundle(CURL *curl) {
#if defined(_WIN32)
* Order: $CST_CA_BUNDLE; on Windows ca-bundle.crt beside the executable (if
* absent nothing is set, so Schannel uses the certificate store); elsewhere
* $SSL_CERT_FILE, libcurl's own default if that file exists, then the usual
* distro locations. Decided once per process. */
void cst_curl_apply_ca(void *curl) {
static char ca[OS_PATH_MAX];
static int checked;
if (!checked) {
checked = 1;
static atomic_int state; /* 0 unchecked, 1 checking, 2 done */
int expect = 0;
if (atomic_compare_exchange_strong(&state, &expect, 1)) {
const char *env = getenv("CST_CA_BUNDLE");
if (env && env[0]) {
if (ca_file_ok(env)) {
snprintf(ca, sizeof(ca), "%s", env);
} else {
char dir[OS_PATH_MAX];
if (os_exe_dir(dir, sizeof(dir)) == 0)
os_path_join(ca, sizeof(ca), dir, "ca-bundle.crt");
}
if (ca[0]) {
FILE *f = fopen(ca, "rb");
if (f)
fclose(f);
#if defined(_WIN32)
char dir[OS_PATH_MAX], p[OS_PATH_MAX];
if (os_exe_dir(dir, sizeof(dir)) == 0 &&
os_path_join(p, sizeof(p), dir, "ca-bundle.crt") == 0 &&
ca_file_ok(p))
snprintf(ca, sizeof(ca), "%s", p);
#else
static const char *const known[] = {
"/etc/ssl/certs/ca-certificates.crt", /* Debian, Ubuntu, Arch, Alpine */
"/etc/pki/tls/certs/ca-bundle.crt", /* Fedora, RHEL */
"/etc/ssl/cert.pem", /* macOS, BSD, Alpine */
"/etc/ssl/ca-bundle.pem", /* openSUSE */
"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
};
const char *pick = NULL;
const char *sslenv = getenv("SSL_CERT_FILE");
const curl_version_info_data *vi = curl_version_info(CURLVERSION_NOW);
if (ca_file_ok(sslenv))
pick = sslenv;
else if (vi && ca_file_ok(vi->cainfo))
pick = NULL; /* libcurl's built-in default already works */
else
ca[0] = '\0';
for (size_t i = 0; i < sizeof(known) / sizeof(known[0]); i++)
if (ca_file_ok(known[i])) {
pick = known[i];
break;
}
if (pick)
snprintf(ca, sizeof(ca), "%s", pick);
#endif
}
atomic_store(&state, 2);
} else {
while (atomic_load(&state) != 2)
;
}
if (ca[0])
curl_easy_setopt(curl, CURLOPT_CAINFO, ca);
#else
(void)curl;
#endif
curl_easy_setopt((CURL *)curl, CURLOPT_CAINFO, ca);
}
#include "cst_attach.h"
@@ -223,28 +255,78 @@ static cJSON *image_part(const cst_llm_request_t *req,
return p;
}
/* Append every attachment of m as image parts (or a note saying why not). */
static void parts_add_images(const cst_llm_request_t *req, cJSON *parts,
const cst_message_t *m, size_t *budget) {
/* One stored document as a text part: its text, framed so the model knows
* where it came from. Documents are plain text on the wire, so a text-only
* model and CST_NO_IMAGES both still get them. */
static cJSON *document_part(const cst_llm_request_t *req,
const cst_attachment_t *a, size_t *budget,
char *why, size_t why_sz) {
why[0] = 0;
if (!req->session_path || !req->session_path[0]) {
snprintf(why, why_sz, "there is no session store to read it from");
return NULL;
}
char err[256];
size_t n = 0;
char *text = cst_attach_read(req->session_path, a, &n, err, sizeof(err));
if (!text) {
snprintf(why, why_sz, "%s", err);
return NULL;
}
int cut = 0;
if (n > *budget) {
n = *budget;
cut = 1;
}
*budget -= n;
char desc[128];
cst_attach_describe(a, desc, sizeof(desc));
cst_buf_t b = {0};
cst_buf_printf(&b, "[document \"%.120s\" (%s)%s]\n", a->name, desc,
cut ? " -- only the start is included" : "");
cst_buf_append(&b, text, n);
cst_buf_puts(&b, cut ? "\n[-- document truncated --]"
: "\n[-- end of document --]");
free(text);
cJSON *p = cJSON_CreateObject();
cJSON_AddStringToObject(p, "type", "text");
cJSON_AddStringToObject(p, "text", b.buf ? b.buf : "");
cst_buf_free(&b);
return p;
}
/* Append every attachment of m: images as image parts (or a note saying why
* not), documents inline as text. */
static void parts_add_attachments(const cst_llm_request_t *req, cJSON *parts,
const cst_message_t *m, size_t *budget,
size_t *doc_budget, const char *img_off) {
int n = m->nattach;
if (n > CST_ATTACH_MAX_COUNT) {
char note[160];
snprintf(note, sizeof(note), "[%d of %d images sent]", CST_ATTACH_MAX_COUNT,
n);
snprintf(note, sizeof(note),
"[only the first %d of %d attachments are sent]",
CST_ATTACH_MAX_COUNT, n);
parts_add_text(parts, cJSON_CreateString(note));
n = CST_ATTACH_MAX_COUNT;
}
for (int i = 0; i < n; i++) {
const cst_attachment_t *a = &m->attach[i];
int is_img = cst_attach_is_image(a);
char why[256];
cJSON *p = image_part(req, a, budget, why, sizeof(why));
cJSON *p = NULL;
if (is_img && img_off)
snprintf(why, sizeof(why), "%s", img_off);
else if (is_img)
p = image_part(req, a, budget, why, sizeof(why));
else
p = document_part(req, a, doc_budget, why, sizeof(why));
if (p) {
cJSON_AddItemToArray(parts, p);
continue;
}
char note[512];
snprintf(note, sizeof(note), "[image \"%.120s\" not sent: %.200s]",
a->name, why);
snprintf(note, sizeof(note), "[%s \"%.120s\" not sent: %.200s]",
is_img ? "image" : "document", a->name, why);
parts_add_text(parts, cJSON_CreateString(note));
}
}
@@ -252,8 +334,10 @@ static void parts_add_images(const cst_llm_request_t *req, cJSON *parts,
/* Images a tool result produced are deferred: an assistant tool_call must be
* answered by tool messages only, so they ride in one extra user message
* after the run of tool messages ends. *pending collects it. */
static void defer_images(const cst_llm_request_t *req, const cst_message_t *m,
cJSON **pending, size_t *budget) {
static void defer_attachments(const cst_llm_request_t *req,
const cst_message_t *m, cJSON **pending,
size_t *budget, size_t *doc_budget,
const char *img_off) {
cJSON *p = *pending;
if (!p) {
p = cJSON_CreateObject();
@@ -261,15 +345,18 @@ static void defer_images(const cst_llm_request_t *req, const cst_message_t *m,
cJSON_AddArrayToObject(p, "content");
*pending = p;
}
parts_add_images(req, cJSON_GetObjectItemCaseSensitive(p, "content"), m,
budget);
parts_add_attachments(req, cJSON_GetObjectItemCaseSensitive(p, "content"), m,
budget, doc_budget, img_off);
}
/* m's text plus one line per image it would have carried (malloc'd). */
/* m's text plus one line per image it would have carried (malloc'd); a
* document is not affected (it is text and is sent as such). */
static char *image_notes(const cst_message_t *m, const char *why) {
cst_buf_t b = {0};
cst_buf_puts(&b, m->content ? m->content : "");
for (int i = 0; i < m->nattach; i++) {
if (!cst_attach_is_image(&m->attach[i]))
continue;
char d[128];
cst_attach_describe(&m->attach[i], d, sizeof(d));
cst_buf_printf(&b, "%s[image \"%.120s\" (%s) not sent: %s]",
@@ -362,6 +449,7 @@ char *cst_llm_build_body(const cst_llm_request_t *req) {
cJSON *prev_user = NULL; /* merge consecutive user messages */
cJSON *pending = NULL; /* images from tool results, waiting for a break */
size_t img_budget = CST_ATTACH_MAX_TOTAL;
size_t doc_budget = CST_ATTACH_MAX_TOTAL;
const char *noimg = getenv("CST_NO_IMAGES");
const char *img_off =
noimg && noimg[0] && noimg[0] != '0'
@@ -375,15 +463,26 @@ char *cst_llm_build_body(const cst_llm_request_t *req) {
cst_role_t role = m->role;
if (role == CST_ROLE_TOOL && !m->tool_call_id[0])
role = CST_ROLE_USER;
int has_img = m->attach && m->nattach > 0;
int n_att = m->attach ? m->nattach : 0;
int has_img = 0, has_doc = 0;
for (int k = 0; k < n_att; k++) {
if (cst_attach_is_image(&m->attach[k]))
has_img = 1;
else
has_doc = 1;
}
char *noted = NULL;
if (has_img && img_off) {
/* plain text: text-only APIs may refuse content arrays */
noted = image_notes(m, img_off);
if (noted)
mm.content = noted;
has_img = 0;
if (!has_doc) {
/* plain text: text-only APIs may refuse content arrays */
noted = image_notes(m, img_off);
if (noted)
mm.content = noted;
}
}
/* a document needs a content array even when no image can go out */
int att_parts = has_img || has_doc;
/* Every tool_call must be answered by tool messages, so tool-produced
* images only leave the queue when the run of tool results is over. */
@@ -399,7 +498,7 @@ char *cst_llm_build_body(const cst_llm_request_t *req) {
cJSON *pc = prev_user
? cJSON_GetObjectItemCaseSensitive(prev_user, "content")
: NULL;
if (!has_img && !cJSON_IsArray(pc)) {
if (!att_parts && !cJSON_IsArray(pc)) {
cJSON *c = clean_string(m->content, 0);
if (prev_user) {
cst_buf_t b = {0};
@@ -431,8 +530,8 @@ char *cst_llm_build_body(const cst_llm_request_t *req) {
}
cJSON *parts = content_parts(o);
parts_add_text(parts, clean_string(m->content, 0));
if (has_img)
parts_add_images(req, parts, m, &img_budget);
if (att_parts)
parts_add_attachments(req, parts, m, &img_budget, &doc_budget, img_off);
free(noted);
continue;
}
@@ -466,8 +565,8 @@ char *cst_llm_build_body(const cst_llm_request_t *req) {
cJSON_AddTrueToObject(o, "prefix");
}
cJSON_AddItemToArray(msgs, o);
if (role == CST_ROLE_TOOL && has_img)
defer_images(req, m, &pending, &img_budget);
if (role == CST_ROLE_TOOL && n_att)
defer_attachments(req, m, &pending, &img_budget, &doc_budget, img_off);
free(noted);
}
if (pending)
@@ -988,7 +1087,7 @@ int cst_llm_chat_stream(const cst_llm_request_t *req, char *err,
ret = -1;
break;
}
llm_apply_ca_bundle(curl);
cst_curl_apply_ca(curl);
sse_reset(&s);
s.curl = curl;
if (rec_dir && rec_dir[0]) {
@@ -1233,7 +1332,7 @@ int cst_llm_list_models_meta(const char *api_base, const char *api_key,
snprintf(err, err_sz, "curl init failed");
return -1;
}
llm_apply_ca_bundle(curl);
cst_curl_apply_ca(curl);
char url[1024];
size_t bl = strlen(api_base);
while (bl && api_base[bl - 1] == '/')
+25 -8
View File
@@ -26,6 +26,8 @@ static void usage(const char *argv0) {
" (last used)\n"
" -m, --model NAME model (last used for the provider)\n"
" -e, --effort LEVEL low | medium | high | max (last used)\n"
" -M, --mode NAME coding (default, code framed) | general\n"
" (documents, data, research; last used)\n"
" -w, --workspace DIR project directory (default: current)\n"
" -c, --continue reopen the last session (default)\n"
" -N, --new start a new session\n"
@@ -59,13 +61,13 @@ static void usage(const char *argv0) {
"API keys: the TUI asks for a missing key and saves it per provider\n"
" in the config dir (credentials, mode 0600); /key changes it.\n"
" Fallbacks: <provider env> (DEEPSEEK_API_KEY, ...), CST_API_KEY.\n"
"Settings: provider, models and effort are remembered in\n"
"Settings: provider, models, effort and mode are remembered in\n"
" settings.json next to the credentials.\n"
"Env: CST_PROVIDER CST_MODEL CST_EFFORT CST_PROTOCOL CST_TOOLS\n"
" CST_CONFIRM CST_MAX_STEPS CST_TOOL_OUT_CAP CST_CTX_WINDOW\n"
" CST_CTX_TOKENS CST_AUTO_COMPACT=0 CST_SHELL_TIMEOUT\n"
" CST_METRICS=0 CST_RECORD_SSE CST_REPLAY_SSE CST_MODELS\n"
" CST_APPROVAL=ask|auto|yolo CST_AUTO_APPROVE=1 (=yolo)\n"
"Env: CST_PROVIDER CST_MODEL CST_EFFORT CST_MODE CST_PROTOCOL\n"
" CST_TOOLS CST_CONFIRM CST_MAX_STEPS CST_TOOL_OUT_CAP\n"
" CST_CTX_WINDOW CST_CTX_TOKENS CST_AUTO_COMPACT=0\n"
" CST_SHELL_TIMEOUT CST_METRICS=0 CST_RECORD_SSE CST_REPLAY_SSE\n"
" CST_MODELS CST_APPROVAL=ask|auto|yolo CST_AUTO_APPROVE=1 (=yolo)\n"
" CST_SANDBOX=off CST_SHELL CST_NO_PROJECT_NOTES=1 NO_COLOR\n"
"TUI: type /help inside for commands and keys\n",
argv0);
@@ -374,6 +376,7 @@ int main(int argc, char **argv) {
{"approval", required_argument, 0, 'A'},
{"confirm", required_argument, 0, 'C'},
{"effort", required_argument, 0, 'e'},
{"mode", required_argument, 0, 'M'},
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'V'},
{"list-models", optional_argument, 0, 0x100},
@@ -385,8 +388,8 @@ int main(int argc, char **argv) {
{"web-open", no_argument, 0, 0x106},
{0, 0, 0, 0}};
int c;
while ((c = getopt_long(argc, argv, "w:s:b:k:m:P:r:n:T:Hp:dahVNcR:LyA:C:e:", opts, NULL)) !=
-1) {
while ((c = getopt_long(argc, argv, "w:s:b:k:m:P:r:n:T:Hp:dahVNcR:LyA:C:e:M:",
opts, NULL)) != -1) {
switch (c) {
case 'w':
snprintf(cfg.workspace_root, sizeof(cfg.workspace_root), "%s", optarg);
@@ -478,6 +481,14 @@ int main(int argc, char **argv) {
}
snprintf(cfg.effort, sizeof(cfg.effort), "%s", optarg);
break;
case 'M':
if (!cst_mode_valid(optarg)) {
fprintf(stderr, "bad --mode %s (coding | general)\n", optarg);
curl_global_cleanup();
return 1;
}
snprintf(cfg.mode, sizeof(cfg.mode), "%s", optarg);
break;
case 'h':
usage(argv[0]);
curl_global_cleanup();
@@ -557,6 +568,12 @@ int main(int argc, char **argv) {
snprintf(cfg.effort, sizeof(cfg.effort), "%s",
cst_effort_valid(e) ? e : CST_DEFAULT_EFFORT);
}
if (!cfg.mode[0]) {
const char *m = getenv("CST_MODE");
if (!cst_mode_valid(m))
m = saved.mode;
snprintf(cfg.mode, sizeof(cfg.mode), "%s", cst_mode_name(m));
}
if (!cfg.api_base[0]) {
const char *env_base = getenv("CST_API_BASE");
if (!env_base || !env_base[0])
+4 -5
View File
@@ -37,11 +37,6 @@
#define NET_SEND_TIMEOUT_MS 20000
static void set_err(char *err, size_t err_sz, const char *what) {
if (err && err_sz)
snprintf(err, err_sz, "%s", what);
}
#ifdef _WIN32
static void set_err_win(char *err, size_t err_sz, const char *what) {
if (err && err_sz)
@@ -59,6 +54,10 @@ static int net_last_conn_reset(void) {
return e == WSAECONNRESET || e == WSAECONNABORTED || e == WSAENOTSOCK;
}
#else
static void set_err(char *err, size_t err_sz, const char *what) {
if (err && err_sz)
snprintf(err, err_sz, "%s", what);
}
#define SET_ERR(e, n, w) set_err(e, n, w)
#define NET_FD(s) ((int)(s))
static void net_close_raw(os_socket_t s) { close(s); }
+71 -12
View File
@@ -13,6 +13,7 @@
#include "os_internal.h"
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -503,19 +504,74 @@ int os_resolve_shell(char *out, size_t out_sz) {
#endif
}
/* Per thread: parallel tool runs and sub-agents each watch their own flag. */
static _Thread_local volatile int *g_run_cancel;
static _Thread_local int g_run_timeout_s;
/* Per thread: parallel tool runs and sub-agents each watch their own flag.
* Thread keys rather than _Thread_local, which tcc does not implement; each
* value fits in the key's pointer slot, so nothing is allocated. */
#ifdef _WIN32
static INIT_ONCE g_run_once = INIT_ONCE_STATIC_INIT;
static DWORD g_key_cancel = TLS_OUT_OF_INDEXES, g_key_timeout = TLS_OUT_OF_INDEXES;
static BOOL CALLBACK run_keys_init(PINIT_ONCE once, PVOID param, PVOID *ctx) {
(void)once;
(void)param;
(void)ctx;
g_key_cancel = TlsAlloc();
g_key_timeout = TlsAlloc();
return TRUE;
}
static void *run_key_get(DWORD *key) {
InitOnceExecuteOnce(&g_run_once, run_keys_init, NULL, NULL);
if (*key == TLS_OUT_OF_INDEXES)
return NULL;
DWORD err = GetLastError(); /* TlsGetValue clears it */
void *v = TlsGetValue(*key);
SetLastError(err);
return v;
}
static void run_key_set(DWORD *key, void *v) {
InitOnceExecuteOnce(&g_run_once, run_keys_init, NULL, NULL);
if (*key != TLS_OUT_OF_INDEXES)
TlsSetValue(*key, v);
}
#else
static pthread_once_t g_run_once = PTHREAD_ONCE_INIT;
static pthread_key_t g_key_cancel, g_key_timeout;
static int g_run_keys_ok;
static void run_keys_init(void) {
g_run_keys_ok = pthread_key_create(&g_key_cancel, NULL) == 0 &&
pthread_key_create(&g_key_timeout, NULL) == 0;
}
static void *run_key_get(pthread_key_t *key) {
pthread_once(&g_run_once, run_keys_init);
return g_run_keys_ok ? pthread_getspecific(*key) : NULL;
}
static void run_key_set(pthread_key_t *key, void *v) {
pthread_once(&g_run_once, run_keys_init);
if (g_run_keys_ok)
pthread_setspecific(*key, v);
}
#endif
void os_set_cancel_flag(volatile int *flag) { g_run_cancel = flag; }
static volatile int *run_cancel(void) {
return (volatile int *)run_key_get(&g_key_cancel);
}
static int run_timeout(void) {
return (int)(intptr_t)run_key_get(&g_key_timeout);
}
void os_set_run_timeout(int seconds) { g_run_timeout_s = seconds; }
void os_set_cancel_flag(volatile int *flag) {
run_key_set(&g_key_cancel, (void *)(uintptr_t)flag);
}
int os_get_run_timeout(void) { return g_run_timeout_s; }
void os_set_run_timeout(int seconds) {
run_key_set(&g_key_timeout, (void *)(intptr_t)seconds);
}
int os_get_run_timeout(void) { return run_timeout(); }
int os_run_timeout_effective(void) {
if (g_run_timeout_s > 0)
return g_run_timeout_s;
int t = run_timeout();
if (t > 0)
return t;
const char *e = getenv("CST_SHELL_TIMEOUT");
if (e && atoi(e) > 0)
return atoi(e);
@@ -693,8 +749,8 @@ int os_run_capture_ex(const char *cwd, const char *const argv[],
}
/* Checked on every pass, so a chatty command still stops promptly. */
if (!reaped && !killed &&
((g_run_cancel && *g_run_cancel) || (deadline > 0 && now > deadline))) {
killed = (g_run_cancel && *g_run_cancel) ? 2 : 1;
(os_cancel_requested() || (deadline > 0 && now > deadline))) {
killed = os_cancel_requested() ? 2 : 1;
killed_at = now;
kill(-pid, SIGTERM);
}
@@ -900,9 +956,12 @@ void os_run_parallel(os_task_fn fn, void *const args[], int n) {
free(tasks);
}
int os_cancel_requested(void) { return g_run_cancel && *g_run_cancel; }
int os_cancel_requested(void) {
volatile int *c = run_cancel();
return c && *c;
}
volatile int *os_get_cancel_flag(void) { return g_run_cancel; }
volatile int *os_get_cancel_flag(void) { return run_cancel(); }
#ifndef _WIN32
int os_proc_spawn(const char *cwd, const char *const argv[],
+1901
View File
File diff suppressed because it is too large Load Diff
+4 -1
View File
@@ -452,7 +452,10 @@ char *cst_session_export_md(cst_session_t *s, const char *title,
for (int k = 0; k < m->nattach; k++) {
char d[128];
cst_attach_describe(&m->attach[k], d, sizeof(d));
cst_buf_printf(&b, "- image `%s` (%s)\n", m->attach[k].name, d);
cst_buf_printf(&b, "- %s `%s` (%s)\n",
cst_attach_is_image(&m->attach[k]) ? "image"
: "document",
m->attach[k].name, d);
}
if (m->nattach)
cst_buf_puts(&b, "\n");
+36 -2
View File
@@ -28,11 +28,17 @@ int cst_settings_load(cst_settings_t *s) {
FILE *fp = fopen(path, "rb");
if (!fp)
return -1;
static _Thread_local char buf[65536];
size_t n = fread(buf, 1, sizeof(buf) - 1, fp);
enum { SETTINGS_MAX = 65536 };
char *buf = malloc(SETTINGS_MAX);
if (!buf) {
fclose(fp);
return -1;
}
size_t n = fread(buf, 1, SETTINGS_MAX - 1, fp);
fclose(fp);
buf[n] = 0;
cJSON *root = cJSON_Parse(buf + cst_bom_len(buf, n));
free(buf);
if (!cJSON_IsObject(root)) {
cJSON_Delete(root);
return -1;
@@ -41,6 +47,8 @@ int cst_settings_load(cst_settings_t *s) {
cJSON_GetObjectItemCaseSensitive(root, "provider"));
copy_str(s->effort, sizeof(s->effort),
cJSON_GetObjectItemCaseSensitive(root, "effort"));
copy_str(s->mode, sizeof(s->mode),
cJSON_GetObjectItemCaseSensitive(root, "mode"));
copy_str(s->approval, sizeof(s->approval),
cJSON_GetObjectItemCaseSensitive(root, "approval"));
s->show_thinking =
@@ -80,6 +88,8 @@ int cst_settings_save(const cst_settings_t *s) {
cJSON_AddStringToObject(root, "provider", s->provider);
if (s->effort[0])
cJSON_AddStringToObject(root, "effort", s->effort);
if (s->mode[0])
cJSON_AddStringToObject(root, "mode", s->mode);
if (s->approval[0])
cJSON_AddStringToObject(root, "approval", s->approval);
if (s->show_thinking)
@@ -129,6 +139,21 @@ int cst_approval_parse(const char *s, int *out) {
return -1;
}
static const char *const MODE_NAMES[] = {"coding", "general"};
int cst_mode_valid(const char *m) {
for (size_t i = 0; m && m[0] && i < sizeof(MODE_NAMES) / sizeof(*MODE_NAMES);
i++) {
if (strcmp(m, MODE_NAMES[i]) == 0)
return 1;
}
return 0;
}
const char *cst_mode_name(const char *m) {
return cst_mode_valid(m) ? m : CST_DEFAULT_MODE;
}
const char *cst_settings_model(const cst_settings_t *s, const char *provider) {
for (int i = 0; provider && i < s->nmodels; i++) {
if (strcmp(s->models[i].provider, provider) == 0 && s->models[i].model[0])
@@ -142,6 +167,8 @@ int cst_settings_remember(const cst_agent_config_t *cfg) {
cst_settings_load(&s);
snprintf(s.provider, sizeof(s.provider), "%s", cfg->provider);
snprintf(s.effort, sizeof(s.effort), "%s", cfg->effort);
if (cfg->mode[0])
snprintf(s.mode, sizeof(s.mode), "%s", cfg->mode);
int i = 0;
while (i < s.nmodels && strcmp(s.models[i].provider, cfg->provider) != 0)
i++;
@@ -170,6 +197,13 @@ int cst_settings_remember_thinking(int show_thinking) {
return cst_settings_save(&s);
}
int cst_settings_remember_mode(const char *mode) {
cst_settings_t s;
cst_settings_load(&s);
snprintf(s.mode, sizeof(s.mode), "%s", cst_mode_name(mode));
return cst_settings_save(&s);
}
static void real_ws(const char *ws, char *out, size_t n) {
if (!ws || os_realpath(ws, out, n) != 0)
snprintf(out, n, "%s", ws ? ws : "");
+5 -5
View File
@@ -40,7 +40,7 @@ static const struct {
"runs commands as needed.",
"", 0},
{"explore",
"Fast read-only explorer: searches and reads the codebase to answer a "
"Fast read-only explorer: searches and reads the workspace to answer a "
"question (where is X, how does Y work, which files do Z). Several can "
"run at once.",
"You only read. Search broadly first (grep, glob, list_dir), then read "
@@ -49,11 +49,11 @@ static const struct {
"you looked for and did not find.",
1},
{"plan",
"Read-only planner: investigates the code involved and returns a "
"Read-only planner: investigates the material involved and returns a "
"step-by-step implementation plan.",
"You only read. Investigate the code involved, then return a concrete "
"plan: the files to change and what to change in each, risks and edge "
"cases, and how to verify. Sketch code only where it removes ambiguity.",
"You only read. Investigate what is involved, then return a concrete "
"plan: what to produce or change and where, risks and edge cases, and "
"how to check the result. Sketch code only where it removes ambiguity.",
1},
};
#define NBUILTIN ((int)(sizeof(BUILTIN) / sizeof(BUILTIN[0])))
+68
View File
@@ -7,6 +7,7 @@
#include <string.h>
#include "cst_tools.h"
#include "cst_clipboard.h"
#include "cst_util.h"
#include "tools_internal.h"
@@ -106,3 +107,70 @@ int cst_tool_ask_user(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *c,
1);
return tool_set_resultf(r, 0, "user answered: %s", ans);
}
/* The system clipboard: what the user copied elsewhere. Reading needs no
* permission (READ); writing replaces what the user has copied (WRITE, so
* the confirmation frontier applies). */
int cst_tool_clipboard_read(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *c,
cst_tool_result_t *r) {
(void)ctx;
char err[192];
char *text = NULL;
size_t n = 0;
if (cst_clipboard_text(&text, &n, err, sizeof(err)) != 0)
return tool_set_result(r, err, 1);
long cap = tool_arg_long(c, "max_bytes", 65536);
if (cap > 0 && (size_t)cap < n)
n = (size_t)cap;
cst_buf_t b = {0};
cst_buf_printf(&b, "clipboard text (%zu bytes%s):\n", (size_t)n,
(size_t)cap < (size_t)n ? ", truncated" : "");
cst_buf_append(&b, text, n);
if (b.len && b.buf[b.len - 1] != '\n')
cst_buf_puts(&b, "\n");
free(text);
return tool_take_buf(r, &b, 0);
}
int cst_tool_clipboard_write(const cst_tool_ctx_t *ctx,
const ctl_tool_call_t *c, cst_tool_result_t *r) {
(void)ctx;
size_t n = 0;
const char *text = tool_arg_n(c, "text", &n);
if (!text)
return tool_set_result(r, "error: missing text", 1);
char err[192];
if (cst_clipboard_set_text(text, n, err, sizeof(err)) != 0)
return tool_set_result(r, err, 1);
return tool_set_resultf(r, 0, "copied %zu bytes to the clipboard", n);
}
/* Confirmation preview: what the clipboard would hold afterwards. Clipboard
* text has no diff, so this is the text itself, cut to a readable size. */
#define CLIP_PREVIEW_MAX 2000
int cst_preview_clipboard_write(const cst_tool_ctx_t *ctx,
const ctl_tool_call_t *c, char **out) {
(void)ctx;
size_t n = 0;
const char *text = tool_arg_n(c, "text", &n);
if (!text) {
*out = strdup("error: missing text");
return -1;
}
int lines = 0;
for (size_t i = 0; i < n; i++)
lines += text[i] == '\n';
size_t cut = n;
if (cut > CLIP_PREVIEW_MAX)
cut = cst_utf8_floor(text, CLIP_PREVIEW_MAX);
cst_buf_t b = {0};
cst_buf_printf(&b, "clipboard: replace with %zu bytes, %d line%s\n", n,
lines + (n && text[n - 1] != '\n'), lines == 0 ? "" : "s");
cst_buf_append(&b, text, cut);
if (b.len && b.buf[b.len - 1] != '\n')
cst_buf_puts(&b, "\n");
if (cut < n)
cst_buf_printf(&b, "… (%zu more bytes)\n", n - cut);
*out = cst_buf_steal(&b);
return 0;
}
+8
View File
@@ -267,6 +267,14 @@ int cst_tool_view_image(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *c,
cst_attachment_t *a = cst_attach_import_file(session, full, err, sizeof(err));
if (!a)
return tool_set_resultf(r, 1, "error: cannot show %.200s: %s", path, err);
if (!cst_attach_is_image(a)) {
cst_attach_free(a);
return tool_set_resultf(
r, 1,
"error: %.200s is not an image; a text file or PDF reaches the model "
"through /attach <path> (a PDF becomes its text layer)",
path);
}
snprintf(a->origin, sizeof(a->origin), "view_image");
const char *d = tool_arg(c, "detail");
if (d && (strcmp(d, "low") == 0 || strcmp(d, "high") == 0))
+16 -2
View File
@@ -66,8 +66,9 @@ static const cst_tool_def_t TOOLS[] = {
{"detail", S, 0, "low or high (provider hint; default auto)"}},
CST_TP_READ, 0, cst_tool_view_image, NULL, NO_DYN},
{"run_shell",
"Run a non-interactive shell command in the workspace root for builds, "
"tests, git and other CLIs (stdin is empty; long runs are killed). "
"Run a non-interactive shell command in the workspace root: builds, "
"tests, git, scripts, computations, data processing, other CLIs "
"(stdin is empty; long runs are killed). "
"Returns stdout+stderr with colors stripped and long output cut to head "
"+ tail. Prefer read_file/grep/glob/list_dir over cat/grep/find.",
"Run a shell command in the workspace root (non-interactive, stdin is "
@@ -158,6 +159,19 @@ static const cst_tool_def_t TOOLS[] = {
{{"question", S, 1, "the question"},
{"options", S, 0, "suggested answers, one per line"}},
CST_TP_ASK, 0, cst_tool_ask_user, NULL, NO_DYN},
{"clipboard_read",
"Read the text on the system clipboard — what the user copied outside "
"the workspace. Returns UTF-8 text.",
NULL,
{{"max_bytes", I, 0, "cap on the returned text (default 65536)"}},
CST_TP_READ, 0, cst_tool_clipboard_read, NULL, NO_DYN},
{"clipboard_write",
"Replace the system clipboard with text, so the user can paste it into "
"another app. Overwrites what they had copied.",
NULL,
{{"text", S, 1, "text to put on the clipboard"}},
CST_TP_WRITE, 0, cst_tool_clipboard_write, cst_preview_clipboard_write,
NO_DYN},
};
#define NTOOLS ((int)(sizeof(TOOLS) / sizeof(TOOLS[0])))
+3 -2
View File
@@ -659,9 +659,10 @@ static int plan_patch(const char *ws, const char *patch, patch_plan_t *pl,
pl->full[i] = malloc(OS_PATH_MAX);
if (!pl->full[i] ||
cst_sandbox_resolve(ws, target, pl->full[i], OS_PATH_MAX) != 0) {
if (dry && pl->full[i] && !pl->del[i] && is_new) {
if (dry && pl->full[i] && !pl->del[i] && is_new &&
strlen(target) < OS_PATH_MAX) {
/* parent dirs do not exist yet; the write would create them */
snprintf(pl->full[i], OS_PATH_MAX, "%s", target);
memcpy(pl->full[i], target, strlen(target) + 1);
} else {
snprintf(err, err_sz, "error: path outside workspace: %.200s",
target);
+7
View File
@@ -46,6 +46,13 @@ int cst_tool_todo_write(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *c,
cst_tool_result_t *r);
int cst_tool_ask_user(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *c,
cst_tool_result_t *r);
/* Clipboard text (system clipboard, not the workspace). */
int cst_tool_clipboard_read(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *c,
cst_tool_result_t *r);
int cst_tool_clipboard_write(const cst_tool_ctx_t *ctx,
const ctl_tool_call_t *c, cst_tool_result_t *r);
int cst_preview_clipboard_write(const cst_tool_ctx_t *ctx,
const ctl_tool_call_t *c, char **out);
int cst_tool_web_fetch(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *c,
cst_tool_result_t *r);
int cst_tool_view_image(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *c,
+1
View File
@@ -215,6 +215,7 @@ int cst_tool_web_fetch(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *c,
memset(&f, 0, sizeof(f));
char errbuf[CURL_ERROR_SIZE];
errbuf[0] = 0;
cst_curl_apply_ca(curl);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 5L);
+111 -20
View File
@@ -152,6 +152,7 @@ static int cst_clock_gettime_mono(struct timespec *ts) {
#ifdef NCURSES_VERSION
static int g_kitty_on;
#ifndef _WIN32
/* Bind the reports and ask whether the terminal speaks the protocol; the
* flags are pushed once the reply arrives (see tui_wget_wch). */
static void kitty_init(void) {
@@ -182,6 +183,7 @@ static void kitty_restore(void) {
g_kitty_on = 0;
}
}
#endif /* !_WIN32 */
#endif
/* wget_wch() that turns kitty key reports back into legacy input. */
@@ -2352,6 +2354,7 @@ static const char *const TIPS[] = {
"Ctrl+P opens the command palette",
"Type @ to mention a file in your message",
"/effort sets reasoning effort: low, medium, high, max",
"/mode general reframes the agent for non-code work",
"/model lists the models your API key can use",
"/undo reverts the file changes of the last turn",
"/provider switches provider; keys are saved per provider",
@@ -2830,7 +2833,10 @@ static void reload_hist_from_session(tui_t *t) {
for (int k = 0; k < m->nattach; k++) {
char d[128];
cst_attach_describe(&m->attach[k], d, sizeof(d));
cst_buf_printf(&ub, "\n[image %s · %s]", m->attach[k].name, d);
cst_buf_printf(&ub, "\n[%s %s · %s]",
cst_attach_is_image(&m->attach[k]) ? "image"
: "document",
m->attach[k].name, d);
}
block_set_body(b, ub.buf ? ub.buf : "", ub.len);
cst_buf_free(&ub);
@@ -4359,6 +4365,41 @@ static void cmd_effort(tui_t *t, char *arg, int *quit) {
cfg->effort, cfg->provider, cfg->model);
}
static void cmd_mode(tui_t *t, char *arg, int *quit) {
(void)quit;
cst_agent_config_t *cfg = cst_agent_config_mut(t->agent);
static const char *const names[] = {"coding", "general"};
static const char *const desc[] = {
"code framed: repo, build, tests (default)",
"documents, data, research, everyday files"};
const char *want = NULL;
if (arg && arg[0]) {
if (!cst_mode_valid(arg)) {
push_system_line(t, "Unknown mode '%s' (coding | general)", arg);
return;
}
want = arg;
} else {
char items[2][128];
int cur_idx = 0;
for (int i = 0; i < 2; i++) {
snprintf(items[i], 128, "%-8s %s", names[i], desc[i]);
if (strcmp(names[i], cst_mode_name(cfg->mode)) == 0)
cur_idx = i;
}
int pick = picker_run(t, "Working mode", items, 2, cur_idx);
if (pick < 0)
return;
want = names[pick];
}
snprintf(cfg->mode, sizeof(cfg->mode), "%s", want);
cst_settings_remember_mode(cfg->mode);
push_system_line(t, "(mode → %s%s)", cfg->mode,
strcmp(cfg->mode, "general") == 0
? "; the system prompt is rewritten on the next turn"
: "");
}
static void cmd_provider(tui_t *t, char *arg, int *quit) {
(void)quit;
cst_agent_config_t *cfg = cst_agent_config_mut(t->agent);
@@ -4637,14 +4678,15 @@ static void cmd_status(tui_t *t, char *arg, int *quit) {
: !same ? "this run only (--api-key / CST_API_KEY)"
: strcmp(from, "saved") == 0 ? "saved (/key to replace)"
: from);
push_system_line(t, " protocol %s · tools %s · max steps %d",
push_system_line(t, " protocol %s · tools %s · mode %s · max steps %d",
cst_protocol_name(cfg->protocol),
cst_tool_profile_name(cfg->tool_profile), cfg->max_steps);
cst_tool_profile_name(cfg->tool_profile),
cst_mode_name(cfg->mode), cfg->max_steps);
char appr[64];
approval_label(t, appr, sizeof(appr));
push_system_line(t, " approval %s — %s", appr,
approval_help(approval_mode(t)));
push_system_line(t, " mode %s",
push_system_line(t, " plan %s",
cfg->plan_mode ? "Plan (read-only tools)" : "Build");
const char *notes = cst_agent_notes(t->agent);
push_system_line(t, " notes %s",
@@ -4823,19 +4865,39 @@ static void report_attached(tui_t *t, int added) {
cst_agent_config(t->agent)->model);
}
/* /attach: stage images for the next user message. The bytes are copied into
* the session's attachment directory now, so a picture picked from /tmp keeps
* working after the file is gone. */
/* /attach paste: the clipboard image if there is one, else its text goes
* into the composer (CR dropped, control bytes kept out, INPUT_CAP respected). */
static int paste_text_into_input(tui_t *t, const char *text, size_t n) {
char *buf = malloc(n + 1);
if (!buf)
return 0;
size_t k = 0;
for (size_t i = 0; i < n && t->in_len + k + 1 < INPUT_CAP; i++) {
unsigned char c = (unsigned char)text[i];
if (c == '\r' || (c < 0x20 && c != '\n' && c != '\t'))
continue;
buf[k++] = (char)c;
}
if (k)
input_insert(t, buf, k);
free(buf);
return (int)k;
}
/* /attach: stage files for the next user message -- images, PDFs (reduced to
* their text) and text. The payload is copied into the session's attachment
* directory now, so a file picked from /tmp keeps working after it is gone. */
static void cmd_attach(tui_t *t, char *arg, int *quit) {
(void)quit;
int n = cst_agent_pending_count(t->agent);
if (!arg || !arg[0] || strcmp(arg, "list") == 0) {
if (n == 0) {
push_system_line(t, "No images picked. Usage: /attach <path>");
push_system_line(t, "Nothing attached yet. Usage: /attach <path>, "
"/attach paste, /attach list, /attach clear");
return;
}
push_system_line(t, "%d image%s with the next message (sent once):", n,
n > 1 ? "s" : "");
push_system_line(t, "%d attachment%s with the next message (sent once):",
n, n > 1 ? "s" : "");
for (int i = 0; i < n; i++) {
char line[256];
if (cst_agent_pending_describe(t->agent, i, line, sizeof(line)) == 0)
@@ -4846,7 +4908,7 @@ static void cmd_attach(tui_t *t, char *arg, int *quit) {
}
if (strcmp(arg, "clear") == 0 || strcmp(arg, "none") == 0) {
cst_agent_pending_clear(t->agent);
push_system_line(t, "Dropped the picked images.");
push_system_line(t, "Dropped the attachments.");
return;
}
char err[256];
@@ -4854,7 +4916,24 @@ static void cmd_attach(tui_t *t, char *arg, int *quit) {
char *img = NULL;
size_t len = 0;
if (cst_clipboard_image(&img, &len, err, sizeof(err)) != 0) {
push_system_line(t, "Error: %s", err);
/* no image: put the clipboard text in the composer instead */
char *text = NULL;
size_t tn = 0;
char terr[192];
if (cst_clipboard_text(&text, &tn, terr, sizeof(terr)) != 0) {
push_system_line(t, "Error: %s", terr);
return;
}
int added = paste_text_into_input(t, text, tn);
free(text);
if (added <= 0) {
push_system_line(t, "(no room in the composer for the clipboard "
"text)");
return;
}
push_system_line(t, "(pasted %d bytes of clipboard text into the "
"composer)", added);
layout_maybe_grow_input(t);
return;
}
char mime[32], name[32];
@@ -4879,19 +4958,29 @@ static void cmd_attach(tui_t *t, char *arg, int *quit) {
report_attached(t, 1);
}
static int file_is_image(const char *path) {
/* A file worth attaching: an image, a PDF, or something that reads as text.
* Deciding here in the TUI only avoids turning a random dropped binary into
* a pasted path; the store checks the content for real. */
static int file_is_attachable(const char *path) {
FILE *f = fopen(path, "rb");
if (!f)
return 0;
unsigned char head[16];
unsigned char head[64];
size_t got = fread(head, 1, sizeof(head), f);
fclose(f);
char mime[32];
return cst_attach_sniff(head, got, mime, sizeof(mime)) == 0;
if (cst_attach_sniff(head, got, mime, sizeof(mime)) == 0)
return 1;
if (got >= 4 && memcmp(head, "%PDF", 4) == 0)
return 1;
for (size_t i = 0; i < got; i++)
if (head[i] == 0 || head[i] < 0x09)
return 0;
return got > 0;
}
/* A paste that is nothing but image file paths (a file dropped on the
* terminal) attaches those files instead of typing the paths. */
/* A paste that is nothing but file paths (a file dropped on the terminal)
* attaches those files instead of typing the paths. */
static void paste_image_paths(tui_t *t) {
size_t from = t->paste_at, to = t->cur;
if (to <= from || to - from != t->in_len - t->paste_len0 ||
@@ -4903,7 +4992,7 @@ static void paste_image_paths(tui_t *t) {
if (n <= 0)
return;
for (int i = 0; i < n; i++)
if (!file_is_image(paths[i]))
if (!file_is_attachable(paths[i]))
return;
input_erase(t, from, to);
int added = 0;
@@ -5439,6 +5528,8 @@ static const slash_cmd_t SLASH[] = {
cmd_protocol},
{"tools", "", "[on|off NAME|minimal]", "list or toggle tools", 0,
cmd_tools},
{"mode", "", "[coding|general]", "coding or general (non-code) framing", 1,
cmd_mode},
{"permissions", "perms", "[reset]", "show saved always-allow rules", 1,
cmd_permissions},
{"sandbox", "", "[reset-labels]", "shell sandbox and labeled folders", 1,
@@ -5462,8 +5553,8 @@ static const slash_cmd_t SLASH[] = {
{"export", "", "[file]", "write the transcript as Markdown", 1,
cmd_export},
{"copy", "", "", "copy the last reply (OSC 52)", 1, cmd_copy},
{"attach", "image", "[path|paste|clear]",
"send image(s) with the next message",
{"attach", "image|file", "[path|paste|clear]",
"send files (image, PDF, text) or clipboard text with the next message",
1, cmd_attach},
{"init", "", "", "have the agent write AGENTS.md", 0, cmd_init},
{"details", "", "", "expand/collapse all tool output", 1, cmd_details},
+16
View File
@@ -263,6 +263,7 @@ static cJSON *wui_state_new(wui_t *w) {
cJSON_AddStringToObject(o, "provider", cfg->provider);
cJSON_AddStringToObject(o, "model", cfg->model);
cJSON_AddStringToObject(o, "effort", cfg->effort);
cJSON_AddStringToObject(o, "mode", cst_mode_name(cfg->mode));
cJSON_AddStringToObject(o, "approval", cst_approval_name(cfg->approval));
cJSON_AddStringToObject(o, "protocol_tools", cst_protocol_name(cfg->protocol));
cJSON_AddBoolToObject(o, "plan_mode", cfg->plan_mode);
@@ -1670,6 +1671,12 @@ static int h_settings_get(cst_http_conn_t *c, void *ud) {
cJSON *pr = cJSON_AddArrayToObject(o, "profiles");
for (int p = CST_TOOLS_DEFAULT; pr && p <= CST_TOOLS_MINIMAL; p++)
cJSON_AddItemToArray(pr, cJSON_CreateString(cst_tool_profile_name(p)));
cJSON_AddStringToObject(o, "mode", cst_mode_name(cfg->mode));
cJSON *md = cJSON_AddArrayToObject(o, "modes");
if (md) {
cJSON_AddItemToArray(md, cJSON_CreateString("coding"));
cJSON_AddItemToArray(md, cJSON_CreateString("general"));
}
cJSON *cf = cJSON_AddObjectToObject(o, "confirm");
if (cf) {
cJSON_AddBoolToObject(cf, "shell", cfg->confirm_shell);
@@ -1728,6 +1735,7 @@ static int h_settings_x(cst_http_conn_t *c, void *ud) {
const cJSON *proto = cJSON_GetObjectItem(j, "protocol");
const cJSON *steps = cJSON_GetObjectItem(j, "max_steps");
const cJSON *prof = cJSON_GetObjectItem(j, "tool_profile");
const cJSON *mode = cJSON_GetObjectItem(j, "mode");
const cJSON *tools = cJSON_GetObjectItem(j, "tools");
const cJSON *conf = cJSON_GetObjectItem(j, "confirm");
cst_protocol_t p = cfg->protocol;
@@ -1742,6 +1750,9 @@ static int h_settings_x(cst_http_conn_t *c, void *ud) {
else if (prof && (!cJSON_IsString(prof) ||
cst_tool_profile_parse(prof->valuestring, &profile) != 0))
snprintf(bad, sizeof(bad), "未知的工具集(default 或 minimal)");
else if (mode && (!cJSON_IsString(mode) ||
!cst_mode_valid(mode->valuestring)))
snprintf(bad, sizeof(bad), "工作模式只能是 coding / general");
else if (tools && !cJSON_IsObject(tools))
snprintf(bad, sizeof(bad), "tools 要是 {\"名字\": true/false}");
else if (conf && !cJSON_IsObject(conf))
@@ -1760,6 +1771,11 @@ static int h_settings_x(cst_http_conn_t *c, void *ud) {
}
cfg->protocol = p;
cfg->tool_profile = profile;
if (mode) {
snprintf(cfg->mode, sizeof(cfg->mode), "%s",
cst_mode_name(mode->valuestring));
cst_settings_remember_mode(cfg->mode);
}
if (steps)
cfg->max_steps = (int)steps->valuedouble;
for (const cJSON *t = tools ? tools->child : NULL; t; t = t->next)
+100
View File
@@ -325,6 +325,100 @@ static void test_import_file(const char *root) {
"missing file refused");
}
/* Documents: text is stored as text, a PDF as its text layer while the mime
* still says PDF, and neither is an image as far as the wire is concerned. */
static void test_documents(const char *root) {
char session[1024], src[1024];
snprintf(session, sizeof(session), "%.900s/sessions/doc.jsonl", root);
char err[256] = "";
const char *text = "# Notes\n\nFive painters, one canvas.\n";
snprintf(src, sizeof(src), "%.900s/notes.md", root);
FILE *f = fopen(src, "wb");
EXPECT(f != NULL, "write the text file");
if (f) {
fwrite(text, 1, strlen(text), f);
fclose(f);
}
cst_attachment_t *a = cst_attach_import_file(session, src, err, sizeof(err));
EXPECT(a != NULL, "text file imported");
if (a) {
EXPECT(strcmp(a->mime, "text/plain") == 0, "text mime");
EXPECT(!cst_attach_is_image(a) && cst_attach_is_text(a), "not an image");
EXPECT(a->pages == 0, "no pages for text");
EXPECT(strstr(a->rel, ".txt") != NULL, "text stored as .txt");
EXPECT(a->bytes == (long long)strlen(text), "text size");
size_t n = 0;
char *back = cst_attach_read(session, a, &n, err, sizeof(err));
EXPECT(back && n == strlen(text) && memcmp(back, text, n) == 0,
"text reads back exactly");
free(back);
EXPECT(cst_attach_data_url(session, a) == NULL,
"a document has no data url");
char desc[128];
cst_attach_describe(a, desc, sizeof(desc));
EXPECT(strstr(desc, "text") != NULL, "describe says text");
cst_attach_free(a);
}
/* a one-page PDF with a text layer */
static const char PDF[] =
"%PDF-1.4\n"
"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n"
"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n"
"3 0 obj\n<< /Type /Page /Parent 2 0 R /Resources << /Font << /F1 4 0 R "
">> >> /Contents 5 0 R >>\nendobj\n"
"4 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\n"
"endobj\n"
"5 0 obj\n<< >>\nstream\n"
"BT /F1 12 Tf 72 720 Td (Attached paper abstract) Tj ET\n"
"endstream\nendobj\n"
"trailer\n<< /Root 1 0 R >>\n%%EOF\n";
snprintf(src, sizeof(src), "%.900s/paper.pdf", root);
f = fopen(src, "wb");
EXPECT(f != NULL, "write the PDF");
if (f) {
fwrite(PDF, 1, strlen(PDF), f);
fclose(f);
}
err[0] = 0;
a = cst_attach_import_file(session, src, err, sizeof(err));
EXPECT(a != NULL, "PDF imported");
if (a) {
EXPECT(strcmp(a->mime, "application/pdf") == 0, "the PDF keeps its mime");
EXPECT(a->pages == 1, "page count comes from the extractor");
EXPECT(strstr(a->rel, ".txt") != NULL, "the text layer is what is stored");
EXPECT(cst_attach_is_text(a), "documents are text on the wire");
char desc[128];
cst_attach_describe(a, desc, sizeof(desc));
EXPECT(strstr(desc, "pdf") != NULL && strstr(desc, "1 page") != NULL,
"describe names the PDF and its pages");
size_t n = 0;
char *back = cst_attach_read(session, a, &n, err, sizeof(err));
EXPECT(back && strstr(back, "Attached paper abstract") != NULL,
"the extracted text reads back");
free(back);
cst_attach_free(a);
}
err[0] = 0;
EXPECT(cst_attach_import_file(session, "/nonexistent/x.pdf", err,
sizeof(err)) == NULL,
"a missing PDF is refused");
/* neither image, PDF nor text: a binary blob */
static const char binary[] = "\x01\x02\x03\x00\x04\x05";
snprintf(src, sizeof(src), "%.900s/blob.bin", root);
f = fopen(src, "wb");
if (f) {
fwrite(binary, 1, sizeof(binary), f);
fclose(f);
}
err[0] = 0;
EXPECT(cst_attach_import_file(session, src, err, sizeof(err)) == NULL,
"a binary file is refused");
EXPECT(strstr(err, "not an image") != NULL, "err says what was expected");
}
static void test_json_roundtrip(void) {
cst_attachment_t list[3];
memset(list, 0, sizeof(list));
@@ -344,6 +438,8 @@ static void test_json_roundtrip(void) {
list[1].bytes = 4096;
snprintf(list[1].detail, sizeof(list[1].detail), "high");
snprintf(list[1].origin, sizeof(list[1].origin), "view_image");
snprintf(list[1].mime, sizeof(list[1].mime), "application/pdf");
list[1].pages = 12;
snprintf(list[2].id, sizeof(list[2].id), "img-3");
snprintf(list[2].name, sizeof(list[2].name), "c.webp");
@@ -365,6 +461,9 @@ static void test_json_roundtrip(void) {
EXPECT(strcmp(back[1].detail, "high") == 0 &&
strcmp(back[1].origin, "view_image") == 0,
"detail and origin survive");
EXPECT(strcmp(back[1].mime, "application/pdf") == 0 && back[1].pages == 12,
"a document keeps its mime and page count");
EXPECT(back[2].pages == 0, "pages default to 0");
EXPECT(strcmp(back[2].mime, "image/webp") == 0 && back[2].width == 0,
"entry without dimensions");
EXPECT(strcmp(back[0].detail, "auto") == 0, "missing detail defaults");
@@ -530,6 +629,7 @@ int main(void) {
test_dib();
test_store(root);
test_import_file(root);
test_documents(root);
test_json_roundtrip();
test_lists();
test_agent_pending(root);
+21
View File
@@ -106,11 +106,13 @@ static void test_settings(void) {
snprintf(cfg.provider, sizeof(cfg.provider), "openai");
snprintf(cfg.model, sizeof(cfg.model), "gpt-5");
snprintf(cfg.effort, sizeof(cfg.effort), "max");
snprintf(cfg.mode, sizeof(cfg.mode), "general");
CHECK(cst_settings_remember(&cfg) == 0);
CHECK(cst_settings_load(&s) == 0);
CHECK(strcmp(s.provider, "openai") == 0);
CHECK(strcmp(s.effort, "max") == 0);
CHECK(strcmp(s.mode, "general") == 0);
CHECK(strcmp(cst_settings_model(&s, "deepseek"), "deepseek-v4-pro") == 0);
CHECK(strcmp(cst_settings_model(&s, "openai"), "gpt-5") == 0);
CHECK(s.nmodels == 2);
@@ -145,6 +147,24 @@ static void test_effort(void) {
free(body);
}
static void test_mode(void) {
CHECK(cst_mode_valid("coding") && cst_mode_valid("general"));
CHECK(!cst_mode_valid("code") && !cst_mode_valid(NULL));
CHECK(!cst_mode_valid(""));
CHECK(strcmp(cst_mode_name("general"), "general") == 0);
CHECK(strcmp(cst_mode_name(NULL), CST_DEFAULT_MODE) == 0);
CHECK(strcmp(cst_mode_name("nonsense"), "coding") == 0);
CHECK(cst_settings_remember_mode("general") == 0);
cst_settings_t s;
CHECK(cst_settings_load(&s) == 0);
CHECK(strcmp(s.mode, "general") == 0);
/* an unknown value is recorded as the default, not as itself */
CHECK(cst_settings_remember_mode("junk") == 0);
CHECK(cst_settings_load(&s) == 0);
CHECK(strcmp(s.mode, "coding") == 0);
}
int main(void) {
CHECK(test_tmpdir(g_dir, sizeof(g_dir), "cst-config") == 0);
setenv("XDG_CONFIG_HOME", g_dir, 1);
@@ -158,6 +178,7 @@ int main(void) {
test_creds();
test_settings();
test_effort();
test_mode();
CHECK(test_rmrf(g_dir) == 0);
printf("test_config: OK\n");
+109
View File
@@ -406,9 +406,118 @@ static void test_images_on(void) {
cst_attach_free(img);
}
/* Every text part of message i, joined (malloc'd, "" when there is none). */
static char *text_of(const cJSON *root, int i) {
const cJSON *m =
cJSON_GetArrayItem(cJSON_GetObjectItemCaseSensitive(root, "messages"), i);
const cJSON *c = cJSON_GetObjectItemCaseSensitive(m, "content");
if (cJSON_IsString(c)) {
size_t n = strlen(c->valuestring);
char *out = malloc(n + 1);
if (out)
memcpy(out, c->valuestring, n + 1);
return out;
}
size_t len = 1;
const cJSON *p, *t, *s;
cJSON_ArrayForEach(p, c) {
t = cJSON_GetObjectItemCaseSensitive(p, "type");
s = cJSON_GetObjectItemCaseSensitive(p, "text");
if (cJSON_IsString(t) && strcmp(t->valuestring, "text") == 0 &&
cJSON_IsString(s))
len += strlen(s->valuestring) + 1;
}
char *out = calloc(1, len);
if (!out)
return NULL;
cJSON_ArrayForEach(p, c) {
t = cJSON_GetObjectItemCaseSensitive(p, "type");
s = cJSON_GetObjectItemCaseSensitive(p, "text");
if (cJSON_IsString(t) && strcmp(t->valuestring, "text") == 0 &&
cJSON_IsString(s)) {
strcat(out, s->valuestring);
strcat(out, "\n");
}
}
return out;
}
/* A document is inlined as text, so a text-only model and a message that
* also carries an image both keep it; the image is what becomes a note. */
static void test_document_parts(void) {
char dir[1024], sess[1100], err[256], src[1200];
if (test_tmpdir(dir, sizeof(dir), "cst-body-doc") != 0) {
EXPECT(0, "scratch dir");
return;
}
snprintf(sess, sizeof(sess), "%s/s.jsonl", dir);
snprintf(src, sizeof(src), "%s/paper.pdf", dir);
static const char PDF[] =
"%PDF-1.4\n"
"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n"
"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n"
"3 0 obj\n<< /Type /Page /Parent 2 0 R /Resources << /Font << /F1 4 0 R "
">> >> /Contents 5 0 R >>\nendobj\n"
"4 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\n"
"endobj\n"
"5 0 obj\n<< >>\nstream\n"
"BT /F1 12 Tf 72 720 Td (Inlined paper text) Tj ET\n"
"endstream\nendobj\n"
"trailer\n<< /Root 1 0 R >>\n%%EOF\n";
FILE *f = fopen(src, "wb");
EXPECT(f != NULL, "write the PDF");
if (!f)
return;
fwrite(PDF, 1, strlen(PDF), f);
fclose(f);
cst_attachment_t *doc = cst_attach_import_file(sess, src, err, sizeof(err));
EXPECT(doc != NULL, "PDF stored");
if (!doc)
return;
static const unsigned char png[32] = {0x89, 'P', 'N', 'G', '\r', '\n', 0x1A,
'\n', 0, 0, 0, 13, 'I', 'H', 'D', 'R',
0, 0, 0, 2, 0, 0, 0, 2};
cst_attachment_t *img = cst_attach_import_bytes(
sess, "shot.png", (const char *)png, sizeof(png), err, sizeof(err));
EXPECT(img != NULL, "image stored");
if (!img) {
cst_attach_free(doc);
return;
}
cst_attachment_t both[2] = {*doc, *img};
cst_message_t m[2];
m[0] = msg(CST_ROLE_USER, "what does this say?");
m[0].attach = both;
m[0].nattach = 2;
m[1] = msg(CST_ROLE_USER, "thanks");
cst_llm_request_t r;
memset(&r, 0, sizeof(r));
r.model = "deepseek-flash";
r.msgs = m;
r.nmsgs = 2;
r.images_off = 1; /* a text-only model */
r.session_path = sess;
cJSON *j = build_req(&r);
char *txt = text_of(j, 0);
EXPECT(txt && strstr(txt, "[document \"paper.pdf\"") &&
strstr(txt, "Inlined paper text") &&
strstr(txt, "[-- end of document --]"),
"the PDF text is inlined even when images are off");
EXPECT(txt && strstr(txt, "[image \"shot.png\"") && strstr(txt, "not sent"),
"the image beside it is still only a note");
free(txt);
char *s = cJSON_PrintUnformatted(j);
EXPECT(s && !strstr(s, "image_url"), "no image part with images off");
free(s);
cJSON_Delete(j);
cst_attach_free(doc);
cst_attach_free(img);
}
int main(void) {
test_images_off();
test_images_on();
test_document_parts();
test_reasoning_and_prefix();
test_cache_hints();
test_tools_snapshot();
+4 -1
View File
@@ -8,6 +8,7 @@
#include "cst_test_util.h"
#include "os_compat.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -49,7 +50,9 @@ static void test_builtin(void) {
cst_model_info("deepseek", "deepseek-chat", &mi);
EXPECT(mi.vision == 1, "deepseek-chat is deepseek-flash");
cst_model_info(NULL, "gpt-4o-mini-2024", &mi);
EXPECT(mi.price.miss == 0.15 && mi.context == 128000 && mi.vision == 1,
/* x87 (i686) compares the literal at long double precision: no == here */
EXPECT(fabs(mi.price.miss - 0.15) < 1e-12 && mi.context == 128000 &&
mi.vision == 1,
"gpt-4o-mini over gpt-4o");
cst_model_info(NULL, "Qwen/Qwen2.5-VL-72B-Instruct", &mi);
EXPECT(mi.vision == 1 && mi.context == 131072, "glob *-vl* + qwen prefix");
+250
View File
@@ -0,0 +1,250 @@
/* Text extraction from PDFs: hand-made fixtures for the shapes that matter
* (plain content, FlateDecode, CID fonts with ToUnicode CMaps, object
* streams) plus the two error paths (encrypted, not a PDF). */
#include "cst_pdf.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int failures = 0;
#define CHECK(cond, what) \
do { \
if (!(cond)) { \
fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, what); \
failures++; \
} \
} while (0)
static char *extract(const char *pdf, int *pages, char *err, size_t err_sz) {
return cst_pdf_text(pdf, strlen(pdf), pages, err, err_sz);
}
static int has(const char *hay, const char *needle) {
return hay && strstr(hay, needle) != NULL;
}
/* --- 1. plain, uncompressed content, two lines via Td --------------- */
static const char PLAIN[] =
"%PDF-1.4\n"
"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n"
"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n"
"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] "
"/Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>\nendobj\n"
"4 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n"
"5 0 obj\n<< >>\nstream\n"
"BT\n/F1 12 Tf\n72 720 Td\n(Line one) Tj\n0 -14 Td\n"
"(A \\(paren\\) and a \\\\ backslash) Tj\nET\n"
"endstream\nendobj\n"
"trailer\n<< /Root 1 0 R >>\n%%EOF\n";
static void test_plain(void) {
char err[256] = "";
int pages = 0;
char *t = extract(PLAIN, &pages, err, sizeof(err));
CHECK(t != NULL, err);
CHECK(pages == 1, "one page");
CHECK(has(t, "Line one"), "first line");
CHECK(has(t, "A (paren) and a \\ backslash"), "escapes");
CHECK(!has(t, "\r"), "no CR left");
free(t);
}
/* --- 2. FlateDecode content stream ---------------------------------- */
/* raw deflate (zlib, level 9, no header) of
* "BT /F1 12 Tf 72 720 Td (Hello, compressed world) Tj ET\n" */
static const unsigned char FLATE[] = {
0x73, 0x0a, 0x51, 0xd0, 0x77, 0x33, 0x54, 0x30, 0x34, 0x52, 0x08, 0x49,
0x53, 0x30, 0x37, 0x02, 0x22, 0x03, 0x85, 0x90, 0x14, 0x05, 0x0d, 0x8f,
0xd4, 0x9c, 0x9c, 0x7c, 0x1d, 0x85, 0xe4, 0xfc, 0xdc, 0x82, 0xa2, 0xd4,
0xe2, 0xe2, 0xd4, 0x14, 0x85, 0xf2, 0xfc, 0xa2, 0x9c, 0x14, 0x4d, 0x85,
0x90, 0x2c, 0x05, 0xd7, 0x10, 0x2e, 0x00};
static void test_flate(void) {
char pdf[2048];
int n = snprintf(pdf, sizeof(pdf),
"%%PDF-1.4\n"
"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n"
"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n"
"3 0 obj\n<< /Type /Page /Parent 2 0 R /Resources << /Font "
"<< /F1 4 0 R >> >> /Contents 5 0 R >>\nendobj\n"
"4 0 obj\n<< /Type /Font /Subtype /Type1 >>\nendobj\n"
"5 0 obj\n<< /Filter /FlateDecode >>\nstream\n");
memcpy(pdf + n, FLATE, sizeof(FLATE));
n += (int)sizeof(FLATE);
n += snprintf(pdf + n, sizeof(pdf) - (size_t)n,
"\nendstream\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n");
char err[256] = "";
int pages = 0;
char *t = cst_pdf_text(pdf, (size_t)n, &pages, err, sizeof(err));
CHECK(t != NULL, err);
CHECK(has(t, "Hello, compressed world"), "inflated text");
free(t);
}
/* 2b. zlib-framed FlateDecode (RFC 1950), which is what real writers emit:
* zlib.compress(b"BT /F1 12 Tf 72 720 Td (Zlib framed hello) Tj ET\n"). */
static const unsigned char ZLIB[] = {
0x78, 0xda, 0x73, 0x0a, 0x51, 0xd0, 0x77, 0x33, 0x54, 0x30, 0x34, 0x52,
0x08, 0x49, 0x53, 0x30, 0x37, 0x02, 0x22, 0x03, 0x85, 0x90, 0x14, 0x05,
0x8d, 0xa8, 0x9c, 0xcc, 0x24, 0x85, 0xb4, 0xa2, 0xc4, 0xdc, 0xd4, 0x14,
0x85, 0x8c, 0xd4, 0x9c, 0x9c, 0x7c, 0x4d, 0x85, 0x90, 0x2c, 0x05, 0xd7,
0x10, 0x2e, 0x00, 0x33, 0x0f, 0x0d, 0x3a};
static void test_zlib_flate(void) {
char pdf[2048];
int n = snprintf(pdf, sizeof(pdf),
"%%PDF-1.4\n"
"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n"
"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n"
"3 0 obj\n<< /Type /Page /Parent 2 0 R /Resources << /Font "
"<< /F1 4 0 R >> >> /Contents 5 0 R >>\nendobj\n"
"4 0 obj\n<< /Type /Font /Subtype /Type1 >>\nendobj\n"
"5 0 obj\n<< /Filter /FlateDecode >>\nstream\n");
memcpy(pdf + n, ZLIB, sizeof(ZLIB));
n += (int)sizeof(ZLIB);
n += snprintf(pdf + n, sizeof(pdf) - (size_t)n,
"\nendstream\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n");
char err[256] = "";
int pages = 0;
char *t = cst_pdf_text(pdf, (size_t)n, &pages, err, sizeof(err));
CHECK(t != NULL, err);
CHECK(has(t, "Zlib framed hello"), "zlib header skipped, text inflated");
free(t);
}
/* 2c. an inline image: its bytes are not text and must be skipped. */
static const char INLINE_IMG[] =
"%PDF-1.4\n"
"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n"
"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n"
"3 0 obj\n<< /Type /Page /Parent 2 0 R /Resources << /Font << /F1 4 0 R "
">> >> /Contents 5 0 R >>\nendobj\n"
"4 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n"
"5 0 obj\n<< >>\nstream\n"
"BT /F1 12 Tf 72 720 Td (Before the image) Tj ET\n"
"q 20 0 0 20 72 700 cm\n"
"BI /W 8 /H 8 /CS /RGB /BPC 8 /F /AHx ID\n"
"00ff0000ff00ff00ff00ff00 8123<0001> EI Q\n"
"BT /F1 12 Tf 72 680 Td (After the image) Tj ET\n"
"endstream\nendobj\n"
"trailer\n<< /Root 1 0 R >>\n%%EOF\n";
static void test_inline_image(void) {
char err[256] = "";
int pages = 0;
char *t = extract(INLINE_IMG, &pages, err, sizeof(err));
CHECK(t != NULL, err);
CHECK(has(t, "Before the image"), "text before the inline image");
CHECK(has(t, "After the image"), "text after it is still found");
CHECK(!has(t, "00ff0000"), "the image bytes were skipped");
CHECK(!has(t, "8123"), "its hex data was skipped too");
free(t);
}
/* --- 3. CID font with a ToUnicode CMap ------------------------------ */
static const char CID[] =
"%PDF-1.5\n"
"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n"
"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n"
"3 0 obj\n<< /Type /Page /Parent 2 0 R /Resources << /Font << /F1 4 0 R "
">> >> /Contents 5 0 R >>\nendobj\n"
"4 0 obj\n<< /Type /Font /Subtype /Type0 /Encoding /Identity-H "
"/ToUnicode 6 0 R >>\nendobj\n"
"5 0 obj\n<< >>\nstream\n"
"BT /F1 12 Tf 72 720 Td <0001000200030004> Tj ET\n"
"endstream\nendobj\n"
"6 0 obj\n<< >>\nstream\n"
"1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n"
"2 beginbfchar\n<0001> <4F60>\n<0002> <597D>\nendbfchar\n"
"1 beginbfrange\n<0003> <0004> <0041>\nendbfrange\n"
"endcmap\nendstream\nendobj\n"
"trailer\n<< /Root 1 0 R >>\n%%EOF\n";
static void test_cid(void) {
char err[256] = "";
int pages = 0;
char *t = extract(CID, &pages, err, sizeof(err));
CHECK(t != NULL, err);
CHECK(has(t, "\xe4\xbd\xa0\xe5\xa5\xbd"), "bfchar maps to 你好");
CHECK(has(t, "AB"), "bfrange walks the code points");
free(t);
}
/* --- 4. objects inside an object stream ----------------------------- */
static void test_objstm(void) {
char pdf[4096];
const char *page = "<< /Type /Page /Parent 2 0 R /Resources << /Font << /F1 "
"4 0 R >> >> /Contents 5 0 R >>";
const char *font = "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>";
/* the stream is "num1 off1 num2 off2" -- /N and /First are in the dict --
* and offsets count from /First, which is where the bodies start, so
* /First is the length of the pairs list itself */
char hdr[64];
int off4 = (int)strlen(page) + 1; /* object 4 follows the page */
int first = snprintf(hdr, sizeof(hdr), "3 0 4 %d ", off4);
int n = snprintf(pdf, sizeof(pdf),
"%%PDF-1.5\n"
"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n"
"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n"
"5 0 obj\n<< >>\nstream\n"
"BT /F1 12 Tf 72 720 Td (Inside an object stream) Tj ET\n"
"endstream\nendobj\n"
"6 0 obj\n<< /Type /ObjStm /N 2 /First %d >>\nstream\n"
"%s%s\n%s",
first, hdr, page, font);
n += snprintf(pdf + n, sizeof(pdf) - (size_t)n,
"\nendstream\nendobj\n"
"trailer\n<< /Root 1 0 R >>\n%%EOF\n");
char err[256] = "";
int pages = 0;
char *t = cst_pdf_text(pdf, (size_t)n, &pages, err, sizeof(err));
CHECK(t != NULL, err);
CHECK(pages == 1, "one page through the object stream");
CHECK(has(t, "Inside an object stream"), "text of the page in the ObjStm");
free(t);
}
/* --- 5. error paths -------------------------------------------------- */
static void test_errors(void) {
char err[256] = "";
char *t = extract("%PDF-1.7\ntrailer\n<< /Root 1 0 R /Encrypt 9 0 R >>\n",
NULL, err, sizeof(err));
CHECK(t == NULL, "encrypted file is refused");
CHECK(has(err, "encrypted"), "says it is encrypted");
err[0] = 0;
t = extract("hello, not a pdf at all\n", NULL, err, sizeof(err));
CHECK(t == NULL, "non-PDF is refused");
CHECK(has(err, "not a PDF"), "says it is not a PDF");
err[0] = 0;
t = extract("%PDF-1.4\n1 0 obj\n<< >>\nendobj\n", NULL, err, sizeof(err));
CHECK(t == NULL, "a PDF without text is refused");
CHECK(has(err, "no extractable text") || has(err, "no readable pages"),
"explains the missing text");
}
int main(void) {
test_plain();
test_flate();
test_zlib_flate();
test_inline_image();
test_cid();
test_objstm();
test_errors();
if (failures) {
fprintf(stderr, "test_pdf_text: %d failure(s)\n", failures);
return 1;
}
printf("test_pdf_text: OK\n");
return 0;
}
+5 -2
View File
@@ -89,8 +89,11 @@ typedef struct {
const unsigned char *json;
size_t position;
} error;
/* cst-agent: per thread, parses run concurrently (sub-agents, MCP) */
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
/* cst-agent: per thread, parses run concurrently (sub-agents, MCP).
* tcc has no thread-local storage; cst-agent never reads cJSON_GetErrorPtr. */
#if defined(__TINYC__)
static error global_error = { NULL, 0 };
#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
static _Thread_local error global_error = { NULL, 0 };
#elif defined(__GNUC__)
static __thread error global_error = { NULL, 0 };
+299 -96
View File
@@ -165,8 +165,11 @@ const log = $('log');
const scroll = $('scroll');
let state = {};
let live = null; /* streaming assistant block */
let steps = null; /* this turn's tool list */
let proc = null; /* the open process block: thinking + tool calls */
let stepIndex = new Map(); /* tool call id -> step row */
let lastTurn = null; /* { session, ms }: the last turn's time, kept across the rebuild */
let pendingPreviews = []; /* { src, name }: object URLs of the images uploaded from this page */
let shownPreviews = []; /* the ones the newest prompt still shows until the rebuild */
let files = new Map(); /* this turn's file changes: path -> {add, del} */
let permReq = null;
let askReq = null;
@@ -277,58 +280,61 @@ function updateJump() {
function showEmpty(show) {
$('empty').classList.toggle('gone', !show);
}
/* every row of the transcript shares one left edge, the composer's: no avatar
* column, the assistant reads as plain text, only errors carry a mark */
function bubble(role, cls) {
const m = el('div', 'msg ' + (cls || role));
/* no avatar per message: the assistant reads as plain text in the column,
* the way the reference transcript does; only errors get a mark */
const g = el('div', 'gutter', role === 'error' ? '!' : '');
const b = el('div', 'body');
m.appendChild(g);
m.appendChild(b);
log.appendChild(m);
showEmpty(false);
scrollDown(true);
return { root: m, body: b };
}
function copyButton(text) {
const b = el('button', null, '复制');
b.onclick = async () => {
try {
await navigator.clipboard.writeText(text);
b.textContent = '已复制';
setTimeout(() => { b.textContent = '复制'; }, 1200);
} catch { b.textContent = '复制失败'; }
};
function actBtn(name, title, fn) {
const b = el('button', 'act');
b.title = title;
b.setAttribute('aria-label', title);
b.appendChild(icon(name));
b.onclick = fn;
return b;
}
function attachStrip(atts) {
const strip = el('div', 'attach-strip');
for (const a of atts) {
function copyButton(text) {
const b = actBtn('copy', '复制', async () => {
try {
await navigator.clipboard.writeText(text);
setIcon(b, 'check');
b.title = '已复制';
setTimeout(() => { setIcon(b, 'copy'); b.title = '复制'; }, 1200);
} catch { toast('浏览器不允许写剪贴板'); }
});
return b;
}
/* images sit above the prompt, outside the bubble: one keeps its shape, more
* than one become a row of square tiles; a click opens the full picture */
function attachStrip(srcs) {
const strip = el('div', 'attach-strip' + (srcs.length === 1 ? ' one' : ''));
srcs.forEach((s, i) => {
const b = el('button', 'thumb');
b.title = s.name || '查看图片';
const img = el('img');
img.alt = a.name || 'image';
img.alt = s.name || 'image';
img.loading = 'lazy';
img.src = attachURL(a.rel);
strip.appendChild(img);
}
img.decoding = 'async';
img.src = s.src;
b.appendChild(img);
b.onclick = () => openLightbox(srcs, i);
strip.appendChild(b);
});
return strip;
}
/* reasoning belongs inside .body: as a sibling it becomes a second flex item
* and squeezes the answer into a narrow column */
function thinkInto(body, text, open) {
let d = body.querySelector(':scope > details.think');
let t;
if (!d) {
d = el('details', 'think');
d.appendChild(el('summary', null, '思考过程'));
t = el('div');
d.appendChild(t);
body.insertBefore(d, body.firstChild);
} else {
t = d.querySelector('div');
}
if (open) d.open = true;
t.textContent += text;
return d;
function userBubble(text, srcs) {
const b = bubble('user');
b.body.textContent = text;
if (srcs && srcs.length) b.root.insertBefore(attachStrip(srcs), b.body);
b.root.dataset.prompt = '1';
actionsFor(b.root, text);
return b;
}
function actionsFor(root, text) {
const row = el('div', 'msg-actions');
@@ -336,6 +342,119 @@ function actionsFor(root, text) {
root.appendChild(row);
return row;
}
/* --- lightbox ------------------------------------------------------------ */
let lb = null; /* { srcs, i } while a picture is open */
function showLightbox() {
const s = lb.srcs[lb.i];
$('lb-img').src = s.src;
$('lb-img').alt = s.name || '';
const many = lb.srcs.length > 1;
$('lb-count').textContent = many ? (lb.i + 1) + ' / ' + lb.srcs.length : '';
$('lb-prev').hidden = !many;
$('lb-next').hidden = !many;
}
function openLightbox(srcs, i) {
lb = { srcs: srcs.slice(), i };
showLightbox();
$('lightbox').hidden = false;
}
function closeLightbox() {
$('lightbox').hidden = true;
$('lb-img').removeAttribute('src');
lb = null;
}
function stepLightbox(d) {
if (!lb || lb.srcs.length < 2) return;
lb.i = (lb.i + d + lb.srcs.length) % lb.srcs.length;
showLightbox();
}
/* --- process timeline -----------------------------------------------------
* Consecutive thinking and tool calls share one block that folds to a single
* line; visible text (or a note, or the next prompt) closes it. History and
* the live stream follow the same rule, so a reload draws what streamed. */
function procLabel(p) {
const parts = [];
if (p.thinks) parts.push(p.thinks > 1 ? '思考 ' + p.thinks + ' 次' : '已思考');
if (p.tools) parts.push('工具 ' + p.tools + ' 次');
const counts = parts.join(' · ');
if (p.root.classList.contains('run')) {
p.lbl.textContent = p.act || '处理中…';
p.meta.textContent = counts;
} else {
p.lbl.textContent = counts || '过程';
p.meta.textContent = '';
}
}
function ensureProc() {
if (proc) return proc;
if (live && live.html) sealLive();
const d = el('details', 'proc');
d.open = !!state.show_thinking;
const s = el('summary', 'proc-sum');
s.appendChild(icon('chevron', 'proc-chev'));
const lbl = el('span', 'proc-lbl');
const meta = el('span', 'proc-meta');
s.appendChild(lbl);
s.appendChild(meta);
const box = el('div', 'tl');
d.appendChild(s);
d.appendChild(box);
log.appendChild(d);
showEmpty(false);
proc = { root: d, lbl, meta, box, thinks: 0, tools: 0, cur: null, act: '' };
procLabel(proc);
return proc;
}
function sealProc() {
if (!proc) return;
proc.root.classList.remove('run');
procLabel(proc);
proc = null;
}
function procAct(p, text) {
p.root.classList.add('run');
p.act = text;
procLabel(p);
}
function firstLine(s) {
const l = String(s).split('\n').find((x) => x.trim()) || '';
return l.trim().slice(0, 200);
}
function procThink(text, running) {
const p = ensureProc();
let t = p.cur && p.cur.kind === 'think' ? p.cur : null;
if (!t) {
const d = el('details', 'tl-item think');
d.open = !!state.show_thinking;
const s = el('summary');
s.appendChild(el('span', 'tl-dot'));
s.appendChild(el('span', 'tl-name', '思考'));
const prev = el('span', 'tl-prev');
s.appendChild(prev);
const body = el('div', 'think-text');
const node = document.createTextNode('');
body.appendChild(node);
d.appendChild(s);
d.appendChild(body);
p.box.appendChild(d);
t = { kind: 'think', root: d, prev, node, hasLine: false };
p.cur = t;
p.thinks++;
}
t.node.appendData(text);
/* the preview is the first line, so it stops changing once that is whole */
if (!t.hasLine) {
t.prev.textContent = firstLine(t.node.data);
t.hasLine = /\S[^\n]*\n/.test(t.node.data);
}
if (running) procAct(p, '正在思考…');
else procLabel(p);
return t;
}
/* "[cst] Plan mode is now ON: ..." notes the engine adds to the history; the
* model reads the English, the page shows one line per change */
const APPROVAL_ZH = { ask: '每次询问', auto: '自动', yolo: '完全放行' };
@@ -355,6 +474,7 @@ function noteLine(text) {
.map((l) => zhOf(NOTE_ZH, l) || l);
const n = el('div', 'note-line', shown.join(' · '));
n.title = String(text || '');
sealProc();
log.appendChild(n);
}
/* history: the stored calls become the same step lines a live turn draws,
@@ -381,15 +501,23 @@ function renderMessage(m) {
if (m.note) return noteLine(m.content);
if (m.role === 'tool' || m.tool_result) return historyResult(m);
const isUser = m.role === 'user';
if (isUser) steps = null; /* each prompt starts its own step list */
const text = m.text !== undefined ? m.text : (m.content || '');
if (isUser || text.trim() || m.reasoning || (m.attach && m.attach.length)) {
const b = bubble(isUser ? 'user' : 'assistant');
if (!isUser && m.html) b.body.innerHTML = m.html;
if (isUser) {
sealProc();
stepIndex = new Map();
const srcs = (m.attach || []).map((a) => ({ src: attachURL(a.rel), name: a.name }));
userBubble(text, srcs);
return;
}
if (m.reasoning) {
procThink(m.reasoning, false);
proc.cur = null; /* the next round's thinking is its own entry */
}
if (text.trim()) {
sealProc();
const b = bubble('assistant');
if (m.html) b.body.innerHTML = m.html;
else b.body.textContent = text;
if (m.reasoning) thinkInto(b.body, m.reasoning, !!state.show_thinking);
if (m.attach && m.attach.length) b.body.insertBefore(attachStrip(m.attach), b.body.firstChild);
if (isUser) b.root.dataset.prompt = '1';
actionsFor(b.root, text);
}
for (const c of m.calls || []) historyCall(c);
@@ -400,12 +528,12 @@ function lastPromptActions() {
const p = prompts[prompts.length - 1];
if (!p) return;
const row = p.querySelector('.msg-actions');
if (row) row.appendChild(Object.assign(el('button', null, '编辑重发'), { onclick: () => editLast(p) }));
if (row) row.appendChild(actBtn('edit', '编辑重发', () => editLast(p)));
const answers = log.querySelectorAll('.msg.assistant');
const a = answers[answers.length - 1];
if (a && (p.compareDocumentPosition(a) & Node.DOCUMENT_POSITION_FOLLOWING)) {
const r = a.querySelector('.msg-actions');
if (r) r.appendChild(Object.assign(el('button', null, '重新生成'), { onclick: () => retry() }));
if (r) r.appendChild(actBtn('retry', '重新生成', () => retry()));
}
}
@@ -415,17 +543,23 @@ async function loadSession() {
stepIndex = new Map();
files = new Map();
renderFilesPanel();
steps = null;
proc = null;
live = null;
for (const m of data.messages) renderMessage(m);
for (const d of log.querySelectorAll('details.turn-steps')) d.open = detailsAll;
steps = null;
sealProc();
stepIndex = new Map();
lastPromptActions();
if (lastTurn && lastTurn.session === state.session && log.lastChild) turnMeta(lastTurn.ms);
if (turnErr && turnErr.session === state.session) {
if (turnErr.stopped) noteLine('已停止');
else bubble('error').body.textContent = turnErr.text;
}
/* a rebuild is not new content: settle every entrance animation at once */
if (log.getAnimations) {
for (const a of log.getAnimations({ subtree: true })) {
try { a.finish(); } catch { /* an infinite pulse cannot finish; it keeps running */ }
}
}
showEmpty(log.children.length === 0);
const last = [...(data.messages || [])].reverse().find((m) => m.role === 'user' && !m.note && !m.tool_result);
document.title = (last && last.content ? last.content.slice(0, 40) + ' · ' : '') + 'CST-Agent';
@@ -435,28 +569,22 @@ async function loadSession() {
/* --- live blocks --------------------------------------------------------- */
/* text closes the process block above it; thinking or a tool call after the
* text closes the answer, so the next words start a bubble below them */
function ensureLive() {
if (live) return live;
sealProc();
const b = bubble('assistant');
b.body.classList.add('live');
/* the answer gets its own box: rewriting body.innerHTML would drop the
* reasoning <details> that thinkInto keeps at the top of body */
const out = el('div', 'live-html');
b.body.appendChild(out);
live = { root: b.root, body: b.body, out, html: '' };
return live;
}
function ensureSteps() {
if (steps) return steps;
const d = el('details', 'turn-steps');
d.open = true;
const s = el('summary', 'steps-sum', '本轮工具调用');
d.appendChild(s);
const box = el('div', 'steps-box');
d.appendChild(box);
log.appendChild(d);
steps = { root: d, sum: s, box, count: 0 };
return steps;
function sealLive() {
if (!live) return;
live.body.classList.remove('live');
live = null;
}
function phaseText(p) {
return { open: '准备中', ready: '待执行', run: '执行中', progress: '进行中', done: '完成' }[p] || p || '';
@@ -471,24 +599,26 @@ function argsLine(args) {
function stepFor(ev) {
let st = stepIndex.get(ev.id);
if (st) return st;
const c = ensureSteps();
const node = el('details', 'step-line run');
const p = ensureProc();
const node = el('details', 'tl-item step-line run');
node.open = detailsAll;
const sum = el('summary');
const name = el('span', 'name', ev.name || 'tool');
const args = el('span', 'args');
const phase = el('span', 'phase', '准备中');
sum.appendChild(el('span', 'tl-dot'));
sum.appendChild(name);
sum.appendChild(args);
sum.appendChild(phase);
const body = el('div', 'step-body');
node.appendChild(sum);
node.appendChild(body);
c.box.appendChild(node);
st = { root: node, sum, name, args, phase, body, t0: Date.now(), bad: false };
p.box.appendChild(node);
st = { kind: 'tool', root: node, sum, name, args, phase, body, t0: Date.now(), bad: false, proc: p };
stepIndex.set(ev.id, st);
c.count++;
c.sum.textContent = '本轮工具调用 · ' + c.count + ' 次';
p.cur = st;
p.tools++;
procLabel(p);
return st;
}
@@ -630,6 +760,10 @@ function onTool(ev) {
st.root.classList.add('done');
st.phase.textContent = '完成 · ' + ((Date.now() - st.t0) / 1000).toFixed(1) + 's';
}
if (st.proc === proc) {
procAct(proc, ev.phase === 'done' ? '等待模型…'
: (ev.phase === 'progress' && ev.detail ? ev.detail : '执行 ' + (ev.name || '工具') + '…'));
}
scrollDown(false);
}
function onToolResult(ev) {
@@ -642,6 +776,7 @@ function onToolResult(ev) {
if (st.args.textContent) st.body.appendChild(el('pre', 'step-args-full', st.args.textContent));
if (ev.out) st.body.appendChild(el('pre', 'step-out', ev.out + (ev.truncated ? '\n… (截断)' : '')));
if (!st.bad) noteFileChange(ev);
if (st.proc === proc) procAct(proc, '等待模型…');
scrollDown(false);
}
function turnMeta(ms) {
@@ -741,29 +876,62 @@ function applyState(s) {
syncSend();
if (!busy && !permReq) $('status').textContent = '就绪';
renderPending();
renderTodo(s.todo);
if ('show_thinking' in s && s.show_thinking !== shownThinking) {
shownThinking = s.show_thinking;
for (const d of log.querySelectorAll('details.proc, details.tl-item.think')) d.open = !!s.show_thinking;
}
}
const revokeAll = (list) => { for (const s of list) URL.revokeObjectURL(s.src); };
/* images waiting for the next prompt: thumbnails when this page uploaded all
* of them, otherwise (another client, the CLI) the server's one-line notes */
let pendingSeen = 0; /* the server's count last time: an upload's reply can beat its state event */
function renderPending() {
const p = $('pending');
const n = (s.pending_images || []).length;
const list = state.pending_images || [];
const n = list.length;
if (!n && pendingSeen && pendingPreviews.length) {
revokeAll(pendingPreviews);
pendingPreviews = [];
}
pendingSeen = n;
p.hidden = !n;
if (n) {
p.textContent = '';
for (const line of s.pending_images) {
p.textContent = '';
if (!n) return;
const clear = () => post('api/attach', undefined, 'DELETE').catch(toastErr);
const clearTitle = n > 1 ? '清空全部 ' + n + ' 张待发图片' : '移除这张图片';
if (pendingPreviews.length === n) {
pendingPreviews.forEach((s, i) => {
const t = el('div', 'pend-thumb');
const img = el('img');
img.src = s.src;
img.alt = s.name || 'image';
img.title = list[i];
img.onclick = () => openLightbox(pendingPreviews, i);
const x = el('button', 'pend-x');
x.title = clearTitle;
x.setAttribute('aria-label', clearTitle);
x.appendChild(icon('close'));
x.onclick = clear;
t.appendChild(img);
t.appendChild(x);
p.appendChild(t);
});
} else {
for (const line of list) {
const chip = el('span', 'chip');
chip.appendChild(el('span', null, line));
const x = el('button', 'icon tiny');
x.appendChild(icon('close'));
x.title = '清空待发图片';
x.onclick = () => post('api/attach', undefined, 'DELETE').catch(toastErr);
x.onclick = clear;
chip.appendChild(x);
p.appendChild(chip);
}
if (s.sees_images === 0)
p.appendChild(el('span', 'chip warn', (s.model || '当前模型') + ' 不识图:图片不会发给模型,换个识图模型再发'));
}
renderTodo(s.todo);
if ('show_thinking' in s && s.show_thinking !== shownThinking) {
shownThinking = s.show_thinking;
for (const d of log.querySelectorAll('details.think')) d.open = !!s.show_thinking;
}
if (state.sees_images === 0)
p.appendChild(el('span', 'chip warn', (state.model || '当前模型') + ' 不识图:图片不会发给模型,换个识图模型再发'));
}
/* --- SSE ----------------------------------------------------------------- */
@@ -787,7 +955,7 @@ function connect() {
});
on('think_delta', (d) => {
markBusy();
thinkInto(ensureLive().body, d.text || '', true);
procThink(d.text || '', true);
scrollDown(false);
});
on('tool', (ev) => { markBusy(); onTool(ev); });
@@ -795,8 +963,9 @@ function connect() {
on('todo', (d) => renderTodo(d.text));
on('session', (d) => {
closePop();
live = null; steps = null; stepIndex = new Map();
live = null; proc = null; stepIndex = new Map();
turnErr = null;
lastTurn = null;
loadSession().then(loadSessions).catch(toastErr);
closeDrawers();
if (d && d.id) $('status').textContent = '已切换会话';
@@ -805,16 +974,24 @@ function connect() {
on('permission_done', hideGate);
on('ask_user', showAsk);
on('turn_end', (d) => {
if (turnStart) { turnMeta(Date.now() - turnStart); turnStart = 0; }
if (live) live.body.classList.remove('live');
live = null; steps = null; stepIndex = new Map();
lastTurn = turnStart ? { session: state.session, ms: Date.now() - turnStart } : null;
turnStart = 0;
sealLive();
sealProc();
stepIndex = new Map();
/* the reload below rebuilds the log, so the reason is drawn after it */
turnErr = d && d.rc ? {
text: turnError(d),
stopped: /cancelled$/.test(d.error || ''),
session: state.session,
} : null;
loadSession().then(loadSessions).catch(toastErr);
loadSession().then(() => {
/* the rebuilt prompt shows the server's copies now */
if (!lb || !lb.srcs.some((s) => shownPreviews.includes(s))) {
revokeAll(shownPreviews);
shownPreviews = [];
}
}).then(loadSessions).catch(toastErr);
});
/* the browser resumes from Last-Event-ID; a restarted server has none of
* those events, so its state (and maybe session) is fetched afresh */
@@ -887,6 +1064,12 @@ async function answerGate(value) {
}
}
window.addEventListener('keydown', (e) => {
if (lb) {
if (e.key === 'Escape') { e.preventDefault(); closeLightbox(); }
else if (e.key === 'ArrowLeft') { e.preventDefault(); stepLightbox(-1); }
else if (e.key === 'ArrowRight') { e.preventDefault(); stepLightbox(1); }
return;
}
/* typing "3" or "y" into the box must not grant a permission */
const typing = e.isComposing || e.ctrlKey || e.metaKey || e.altKey ||
(e.target && (e.target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(e.target.tagName)));
@@ -1534,6 +1717,7 @@ async function showRunSettings() {
const proto = field('工具协议', select(s.protocols || [], s.protocol));
const steps = field('每轮步数', Object.assign(el('input'), { type: 'number', min: 1, max: 1000, value: s.max_steps }));
const prof = field('工具集', select(s.profiles || [], s.tool_profile));
const mode = field('工作模式', select(s.modes || [], s.mode));
box.appendChild(el('h4', 'sub', '需要确认(审批模式 ' + (s.approval || '-') + ')'));
const conf = {};
@@ -1603,6 +1787,7 @@ async function showRunSettings() {
if (proto.value !== s.protocol) body.protocol = proto.value;
if (+steps.value !== s.max_steps) body.max_steps = +steps.value;
if (prof.value !== s.tool_profile) body.tool_profile = prof.value;
if (mode.value !== s.mode) body.mode = mode.value;
const c = {};
for (const k of Object.keys(conf)) if (conf[k].checked !== !!(s.confirm || {})[k]) c[k] = conf[k].checked;
if (Object.keys(c).length) body.confirm = c;
@@ -1668,15 +1853,16 @@ function editLast(node) {
syncSend();
input.focus();
}
function freshTurn(text) {
const b = bubble('user');
b.body.textContent = text;
b.root.dataset.prompt = '1';
steps = null;
function freshTurn(text, srcs) {
sealProc();
sealLive();
revokeAll(shownPreviews);
shownPreviews = srcs || [];
userBubble(text, shownPreviews);
stepIndex = new Map();
files = new Map();
live = null;
turnErr = null;
lastTurn = null;
renderFilesPanel();
turnStart = Date.now();
}
@@ -1731,11 +1917,23 @@ async function send(text) {
setEditing(false);
return retry(body);
}
freshTurn(body);
/* the images go out with this prompt: draw them now from the local copies */
const pend = (state.pending_images || []).length;
let srcs = [];
if (pend && pendingPreviews.length === pend) {
srcs = pendingPreviews;
pendingPreviews = [];
}
freshTurn(body, srcs);
try {
await post('api/turn', { text: body });
if (busy) $('status').textContent = '已开始…';
} catch (e) {
if (srcs.length && !pendingPreviews.length && shownPreviews === srcs) {
pendingPreviews = srcs; /* still waiting on the server: keep the thumbnails */
shownPreviews = [];
renderPending();
}
bubble('error').body.textContent = errMsg(e);
}
}
@@ -1805,7 +2003,7 @@ function setThinking(a) {
function setDetails(a) {
detailsAll = onOffArg(a, detailsAll);
localStorage.setItem('cst.details', detailsAll ? '1' : '0');
for (const d of log.querySelectorAll('details.turn-steps, details.step-line')) d.open = detailsAll;
for (const d of log.querySelectorAll('details.step-line')) d.open = detailsAll;
toast(detailsAll ? '工具输出全部展开' : '工具输出全部收起', 'ok');
}
async function providerCmd(a) {
@@ -2220,6 +2418,8 @@ async function upload(file) {
body: file,
});
try { await readReply(r); } catch (e) { toast('上传失败:' + errMsg(e)); return; }
pendingPreviews.push({ src: URL.createObjectURL(file), name: file.name || 'pasted.png' });
renderPending();
if (state.sees_images === 0) toast((state.model || '当前模型') + ' 不识图,这张图不会发给模型', 'warn');
}
@@ -2335,10 +2535,13 @@ document.addEventListener('drop', async (e) => {
for (const f of e.dataTransfer.files) await upload(f);
});
$('backdrop').onclick = closeDrawers;
$('lightbox').onclick = (e) => { if (e.target === $('lightbox')) closeLightbox(); };
$('lb-close').onclick = closeLightbox;
$('lb-prev').onclick = () => stepLightbox(-1);
$('lb-next').onclick = () => stepLightbox(1);
/* --- go ------------------------------------------------------------------ */
applyTheme(localStorage.getItem('cst.theme') || 'dark');
/* the rail/panel/theme classes are already on <body> from the inline script in
* index.html, so nothing here has to re-derive them */
autoGrow();
+11
View File
@@ -41,6 +41,10 @@
<symbol id="i-lv4" viewBox="0 0 24 24"><path d="M4 18.5V13h2.6v5.5zM8.7 18.5V10h2.6v8.5zM13.4 18.5V6.8h2.6v11.7zM18.1 18.5V4h2.6v14.5z" class="f"/></symbol>
<symbol id="i-file" viewBox="0 0 24 24"><path d="M13.5 3.5H7A2.5 2.5 0 0 0 4.5 6v12A2.5 2.5 0 0 0 7 20.5h10A2.5 2.5 0 0 0 19.5 18V9.5z"/><path d="M13.5 3.5v6h6"/></symbol>
<symbol id="i-clock" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M12 7.2V12l3.2 2"/></symbol>
<symbol id="i-edit" viewBox="0 0 24 24"><path d="M14.8 5.2l4 4L9 19H5v-4z"/><path d="M12.6 7.4l4 4"/></symbol>
<symbol id="i-retry" viewBox="0 0 24 24"><path d="M4.5 12a7.5 7.5 0 0 1 13-5.1M19.5 12a7.5 7.5 0 0 1-13 5.1"/><path d="M17.8 3.6v3.6h-3.6M6.2 20.4v-3.6h3.6"/></symbol>
<symbol id="i-left" viewBox="0 0 24 24"><path d="M14.5 6l-6 6 6 6"/></symbol>
<symbol id="i-right" viewBox="0 0 24 24"><path d="M9.5 6l6 6-6 6"/></symbol>
<symbol id="i-folder" viewBox="0 0 24 24"><path d="M3.5 6.5A1.5 1.5 0 0 1 5 5h4l2 2.5h8A1.5 1.5 0 0 1 20.5 9v9A1.5 1.5 0 0 1 19 19.5H5A1.5 1.5 0 0 1 3.5 18z"/></symbol>
</svg>
@@ -216,6 +220,13 @@
<div id="backdrop"></div>
<div id="pop" class="pop" hidden></div>
<div id="modal" hidden><div id="modal-box"></div></div>
<div id="lightbox" hidden>
<img id="lb-img" alt="">
<button id="lb-close" class="lb-btn" title="关闭 (Esc)"><svg class="i"><use href="#i-close"/></svg></button>
<button id="lb-prev" class="lb-btn" title="上一张 (←)"><svg class="i"><use href="#i-left"/></svg></button>
<button id="lb-next" class="lb-btn" title="下一张 (→)"><svg class="i"><use href="#i-right"/></svg></button>
<span id="lb-count"></span>
</div>
<div id="toast" class="toast" role="status" aria-live="polite" hidden></div>
<script>
/* Layout is decided here, before app.js runs and before the first paint: the
+158 -62
View File
@@ -35,6 +35,7 @@
--composer-surface-secondary: #202026;
--bg-code: #08080a;
--bubble-user: var(--main-surface-tertiary);
/* every hover/active tint is alpha, so it lands correctly on any surface */
--hover: color-mix(in srgb, var(--text-primary) 7%, transparent);
@@ -68,8 +69,11 @@
--accent: var(--accent-primary);
--danger: var(--text-error);
--rail: 252px;
--panel: 296px;
/* the side columns grow with the screen so a wide window does not turn into
* one wide middle: the text stays near the run panel it is read against */
--rail: clamp(240px, 14vw, 280px);
--panel: clamp(296px, 20vw, 380px);
--content: 720px; /* text column and composer share this edge */
--radius: 12px;
--radius-lg: 22px;
--shadow: 0 16px 40px rgba(0, 0, 0, .45);
@@ -103,6 +107,7 @@
--composer-surface-secondary: #f4f4f6;
--bg-code: #f5f5f7;
--bubble-user: #eef0f4;
--accent-primary: #0f9d70;
--accent-fg: #ffffff;
@@ -306,7 +311,7 @@ body.no-side #side { pointer-events: none; }
border-radius: 99px; padding: 2px; position: relative;
}
.seg button {
height: 25px; padding: 0 12px; border-radius: 99px; color: var(--fg-dim); font-size: 12.5px;
height: 25px; padding: 0 12px; white-space: nowrap; border-radius: 99px; color: var(--fg-dim); font-size: 12.5px;
transition: color var(--t-fast), background var(--t);
}
.seg button.on { background: var(--bg-lift); color: var(--fg); font-weight: 600; }
@@ -316,7 +321,7 @@ body.no-side #side { pointer-events: none; }
flex: 1 1 auto; overflow-y: auto; padding: 22px 0 10px;
scroll-behavior: smooth; scrollbar-gutter: stable;
}
#log { max-width: 760px; margin: 0 auto; padding: 0 20px; }
#log { max-width: calc(var(--content) + 40px); margin: 0 auto; padding: 0 20px; }
#log:empty { display: none; }
/* --- empty state ---------------------------------------------------------- */
@@ -330,16 +335,22 @@ body.no-side #side { pointer-events: none; }
}
/* --- transcript ----------------------------------------------------------- */
.msg { display: flex; gap: 12px; padding: 13px 0 0; animation: fade-up var(--t) var(--ease) both; }
.msg .gutter { flex: 0 0 24px; padding-top: 2px; color: var(--fg-faint); font-size: 11px; text-align: center; user-select: none; }
.msg .body { min-width: 0; flex: 1 1 auto; }
.msg.user { justify-content: flex-end; }
.msg.user .gutter { display: none; }
/* one left edge for everything (answer, process block, notes), the same edge
* as the composer; prompts hang on the right edge with their images above */
.msg { display: flex; flex-direction: column; align-items: stretch; padding: 14px 0 0; animation: fade-up var(--t) var(--ease) both; }
.msg .body { min-width: 0; max-width: 100%; }
.msg.user { align-items: flex-end; padding-top: 24px; }
#log > .msg.user:first-child { padding-top: 6px; }
.msg.user .body {
background: var(--bg-lift); border-radius: 18px 18px 6px 18px;
padding: 9px 15px; max-width: 76%; white-space: pre-wrap; word-break: break-word;
background: var(--bubble-user); border-radius: 24px;
padding: 11px 18px; max-width: min(76%, 560px); white-space: pre-wrap; word-break: break-word;
}
.msg.error .body { color: var(--danger); white-space: pre-wrap; }
.msg.error .body::before {
content: "!"; display: inline-flex; align-items: center; justify-content: center;
width: 18px; height: 18px; margin-right: 8px; border-radius: 50%; vertical-align: 1px;
background: color-mix(in srgb, var(--danger) 18%, transparent); font-size: 12px; font-weight: 800;
}
.body > :first-child, .live-html > :first-child { margin-top: 0; }
.body > :last-child, .live-html > :last-child { margin-bottom: 0; }
.body h1, .body h2, .body h3, .body h4 { line-height: 1.35; margin: 1.1em 0 .5em; }
@@ -370,63 +381,102 @@ body.no-side #side { pointer-events: none; }
background: var(--accent); animation: blink 1.1s steps(2, start) infinite;
}
.attach-strip { display: flex; flex-wrap: wrap; gap: 8px; margin: 2px 0 8px; justify-content: flex-end; }
.attach-strip img {
width: 108px; height: 108px; object-fit: cover; border-radius: 12px;
border: 1px solid var(--line); animation: rise var(--t) var(--ease) both;
/* a prompt's images: above the bubble and outside it, square tiles when there
* are several, the picture's own shape when there is one */
.attach-strip { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 12px; margin: 0 0 10px; max-width: 100%; }
.attach-strip .thumb {
display: block; width: 152px; height: 152px; padding: 0; overflow: hidden; cursor: zoom-in;
border-radius: 20px; border: 1px solid var(--line); background: var(--bg-soft);
animation: rise var(--t) var(--ease) both;
transition: border-color var(--t-fast), transform 90ms var(--ease);
}
.attach-strip .thumb:hover { border-color: var(--line-strong); }
.attach-strip .thumb:active { transform: scale(.985); }
.attach-strip .thumb img { display: block; width: 100%; height: 100%; object-fit: cover; }
.attach-strip.one .thumb { width: auto; height: auto; }
.attach-strip.one .thumb img {
width: auto; height: auto; min-width: 72px; min-height: 72px;
max-width: min(260px, 70vw); max-height: 260px; object-fit: contain;
}
.turn-meta { display: flex; align-items: center; gap: 10px; padding: 10px 0 2px 36px; }
.turn-meta { display: flex; align-items: center; gap: 10px; padding: 8px 0 2px; }
.turn-meta details > summary { cursor: pointer; list-style: none; color: var(--fg-faint); font-size: 12px; transition: color var(--t-fast); }
.turn-meta details > summary::-webkit-details-marker { display: none; }
.turn-meta details > summary:hover { color: var(--fg-dim); }
.msg:has(> .msg-actions) { flex-wrap: wrap; row-gap: 0; }
.msg-actions { display: flex; flex-basis: 100%; gap: 2px; padding: 4px 0 0 36px; opacity: 0; transition: opacity var(--t) var(--ease); }
/* the actions take a row only under messages that have text to act on */
.msg-actions { display: flex; gap: 2px; padding-top: 4px; margin-left: -7px; opacity: 0; transition: opacity var(--t) var(--ease); }
.msg.user .msg-actions { margin: 0 -7px 0 0; }
.msg:hover .msg-actions, .msg-actions:focus-within { opacity: 1; }
.msg-actions button {
height: 26px; padding: 0 9px; border-radius: 8px; color: var(--fg-faint); font-size: 12px;
.act {
width: 30px; height: 28px; border-radius: 8px; color: var(--fg-faint);
display: inline-flex; align-items: center; justify-content: center;
transition: background var(--t-fast), color var(--t-fast), transform 90ms var(--ease);
}
.act svg.i { width: 16px; height: 16px; }
.act:hover { background: var(--bg-hover); color: var(--fg); }
.act:active { transform: scale(.94); }
/* --- process block: a run of thinking and tool calls, folded to one line --- */
.proc { margin: 10px 0 0; }
.proc-sum {
display: inline-flex; align-items: center; gap: 7px; max-width: 100%; height: 28px;
margin-left: -7px; padding: 0 10px 0 6px; border-radius: 8px;
cursor: pointer; list-style: none; color: var(--fg-faint); font-size: 13px; user-select: none;
transition: background var(--t-fast), color var(--t-fast);
}
.msg-actions button:hover { background: var(--bg-hover); color: var(--fg); }
.think { margin: .1em 0 .5em; }
.think summary { cursor: pointer; list-style: none; color: var(--fg-faint); font-size: 12.5px; transition: color var(--t-fast); }
.think summary::-webkit-details-marker { display: none; }
.think summary::before { content: "▸ "; }
.think[open] summary::before { content: "▾ "; }
.think summary:hover { color: var(--fg-dim); }
.think > div {
color: var(--fg-dim); font-size: 13.5px; white-space: pre-wrap;
padding: 6px 0 2px 14px; border-left: 2px solid var(--line);
animation: fade-in var(--t) var(--ease) both;
.proc-sum::-webkit-details-marker { display: none; }
.proc-sum:hover { background: var(--bg-hover); color: var(--fg-dim); }
.proc-chev { width: 14px; height: 14px; transform: rotate(-90deg); transition: transform var(--t) var(--ease); }
.proc[open] > .proc-sum .proc-chev { transform: none; }
.proc-lbl { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.proc-meta { flex: 0 0 auto; color: var(--fg-quat); font-size: 12px; white-space: nowrap; }
.proc-meta:empty { display: none; }
/* the running block's label shimmers instead of spinning */
.proc.run .proc-lbl {
background: linear-gradient(90deg, var(--fg-faint) 0%, var(--fg) 45%, var(--fg-faint) 90%);
background-size: 220% 100%; -webkit-background-clip: text; background-clip: text;
color: transparent; animation: shimmer 1.8s linear infinite;
}
/* tool calls: one line, opens on demand (like "已执行 python · <<PY>") */
.turn-steps { padding: 6px 0 0 36px; }
.turn-steps > summary { cursor: pointer; list-style: none; color: var(--fg-faint); font-size: 12.5px; transition: color var(--t-fast); }
.turn-steps > summary::-webkit-details-marker { display: none; }
.turn-steps > summary::before { content: "⌘ "; }
.turn-steps > summary:hover { color: var(--fg-dim); }
.steps-box { padding: 2px 0 0 12px; margin-top: 4px; border-left: 2px solid var(--line); }
.step-line { animation: fade-up var(--t) var(--ease) both; }
.step-line > summary {
display: flex; align-items: baseline; gap: 8px; cursor: pointer; list-style: none;
padding: 5px 0; font-size: 13px; color: var(--fg-dim);
/* the timeline: one hairline, one dot per entry */
.tl { position: relative; margin: 2px 0 0; padding: 2px 0 2px 20px; animation: fade-in var(--t) var(--ease) both; }
.tl::before {
content: ""; position: absolute; left: 4px; top: 14px; bottom: 14px; width: 1px;
background: var(--line);
}
.tl-item { position: relative; animation: fade-up var(--t) var(--ease) both; }
.tl-item > summary {
display: flex; align-items: center; gap: 8px; min-height: 28px; padding: 2px 0;
cursor: pointer; list-style: none; font-size: 13px; color: var(--fg-dim);
transition: color var(--t-fast);
}
.step-line > summary::-webkit-details-marker { display: none; }
.step-line > summary:hover { color: var(--fg); }
.step-line .name { font-family: var(--mono); font-size: 12.5px; color: var(--fg); }
.step-line .args { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: var(--mono); font-size: 12px; }
.step-line .phase { font-size: 11.5px; color: var(--fg-faint); white-space: nowrap; display: inline-flex; align-items: center; gap: 6px; }
.step-line.run .phase { color: var(--warn); }
.step-line.run .phase::before {
content: ""; width: 6px; height: 6px; border-radius: 50%;
background: var(--warn); animation: pulse 1.1s var(--ease) infinite;
.tl-item > summary::-webkit-details-marker { display: none; }
.tl-item > summary:hover { color: var(--fg); }
.tl-dot {
position: absolute; left: -20px; top: 9px; width: 9px; height: 9px; border-radius: 50%;
background: var(--bg); border: 1.5px solid var(--line-strong);
}
.tl-item.think .tl-dot { border-color: color-mix(in srgb, var(--violet) 75%, transparent); }
.tl-name { flex: 0 0 auto; font-size: 12.5px; color: var(--fg-dim); }
.tl-prev {
flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
color: var(--fg-faint); font-size: 12.5px;
}
.tl-item.think[open] .tl-prev { visibility: hidden; }
.think-text {
color: var(--fg-dim); font-size: 13px; line-height: 1.65; white-space: pre-wrap; word-break: break-word;
padding: 2px 0 8px; animation: fade-in var(--t) var(--ease) both;
}
/* tool calls: one line each, open for arguments and output */
.step-line .name { flex: 0 0 auto; font-family: var(--mono); font-size: 12.5px; color: var(--fg); }
.step-line .args { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: var(--mono); font-size: 12px; color: var(--fg-faint); }
.step-line .phase { flex: 0 0 auto; font-size: 11.5px; color: var(--fg-faint); white-space: nowrap; }
.step-line.run .phase { color: var(--warn); }
.step-line.run .tl-dot { border-color: var(--warn); background: color-mix(in srgb, var(--warn) 30%, var(--bg)); animation: pulse 1.1s var(--ease) infinite; }
.step-line.done .tl-dot { border-color: var(--accent-line); background: var(--accent-weak); }
.step-line.bad .tl-dot { border-color: var(--danger); background: color-mix(in srgb, var(--danger) 20%, var(--bg)); }
.step-line.bad .phase, .step-line.bad .name { color: var(--danger); }
.step-line.done .phase::before { content: "✓"; }
.step-line.bad .phase::before { content: "✕"; }
/* a sub-agent's latest steps, next to its task */
.step-line .step-detail {
flex: 0 1 40%; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
@@ -435,7 +485,7 @@ body.no-side #side { pointer-events: none; }
.step-line.done .step-detail { display: none; }
/* "[cst] plan mode is now ON" and other engine notes in the history */
.note-line {
padding: 6px 0 2px 36px; font-size: 12px; color: var(--fg-faint);
padding: 8px 0 2px; font-size: 12px; color: var(--fg-faint);
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.note-line::before { content: "· "; }
@@ -459,9 +509,24 @@ body.no-side #side { pointer-events: none; }
/* --- composer ------------------------------------------------------------- */
#composer { padding: 8px 20px 12px; }
#composer > * { max-width: 760px; margin: 0 auto; }
.pending { display: flex; flex-wrap: wrap; gap: 8px; padding: 0 0 8px; }
#composer > * { max-width: var(--content); margin: 0 auto; }
.pending { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; padding: 6px 0 10px; }
.pending .chip { background: var(--bg-soft); border-color: var(--line); }
/* images waiting for the next prompt, the way they will look once sent */
.pend-thumb { position: relative; width: 56px; height: 56px; flex: 0 0 auto; animation: rise var(--t) var(--ease) both; }
.pend-thumb img {
display: block; width: 100%; height: 100%; object-fit: cover; cursor: zoom-in;
border-radius: 12px; border: 1px solid var(--line);
}
.pend-x {
position: absolute; top: -7px; right: -7px; width: 20px; height: 20px; border-radius: 50%;
display: flex; align-items: center; justify-content: center;
background: var(--main-surface-tertiary); border: 1px solid var(--line-strong); color: var(--fg-dim);
opacity: 0; transition: opacity var(--t-fast), color var(--t-fast);
}
.pend-x svg.i { width: 12px; height: 12px; stroke-width: 2.2; }
.pend-thumb:hover .pend-x, .pend-x:focus-visible { opacity: 1; }
.pend-x:hover { color: var(--fg); }
.edit-bar {
display: flex; align-items: center; gap: 8px; padding: 6px 10px; margin-bottom: 8px;
border-radius: 10px; border: 1px solid var(--line); background: var(--bg-soft);
@@ -698,9 +763,6 @@ body.no-panel #panel { pointer-events: none; }
.todo-list .boxmark { color: var(--fg-faint); }
.todo-list li.done { color: var(--fg-faint); text-decoration: line-through; }
.todo-list li.doing { color: var(--fg); font-weight: 600; }
#steps-body .step-line > summary { font-size: 12.5px; }
#steps-body .step-line .phase { font-size: 11px; }
/* --- modal sheet (session list) ------------------------------------------- */
#modal {
position: fixed; inset: 0; background: rgba(0, 0, 0, .5); z-index: 40;
@@ -808,11 +870,44 @@ body.drawer-open #backdrop { display: block; }
body.side-open #side, body.panel-open #panel { transform: none; }
.only-narrow { display: inline-flex; }
#to-bottom { bottom: 150px; right: 16px; }
.hero h1 { font-size: 21px; }
.msg.user .body { max-width: 88%; }
.turn-meta, .msg-actions, .turn-steps, .note-line { padding-left: 0; }
.attach-strip .thumb { width: 120px; height: 120px; }
#lightbox { padding: 56px 12px; }
}
@media (max-width: 560px) {
#chip-approval .lbl { display: none; }
.seg button { padding: 0 9px; }
}
@media (min-width: 901px) { #backdrop { display: none !important; } }
/* touch screens have no hover: the actions stay visible */
@media (hover: none) {
.msg-actions, .pend-x { opacity: 1; }
}
/* --- lightbox ------------------------------------------------------------- */
#lightbox {
position: fixed; inset: 0; z-index: 70; padding: 56px 72px;
display: flex; align-items: center; justify-content: center;
background: rgba(0, 0, 0, .84); animation: fade-in var(--t) var(--ease) both;
}
#lb-img {
max-width: 100%; max-height: 100%; object-fit: contain; border-radius: 12px;
box-shadow: 0 20px 60px rgba(0, 0, 0, .5); animation: pop-in 180ms var(--ease) both;
}
.lb-btn {
position: absolute; width: 40px; height: 40px; border-radius: 50%;
display: flex; align-items: center; justify-content: center;
background: rgba(255, 255, 255, .1); color: #fff;
transition: background var(--t-fast), transform 90ms var(--ease);
}
.lb-btn:hover { background: rgba(255, 255, 255, .2); }
#lb-close { top: 14px; right: 14px; }
#lb-prev { left: 14px; top: calc(50% - 20px); }
#lb-next { right: 14px; top: calc(50% - 20px); }
#lb-count {
position: absolute; bottom: 18px; left: 50%; transform: translateX(-50%);
color: rgba(255, 255, 255, .75); font-size: 13px; font-variant-numeric: tabular-nums;
}
/* --- motion --------------------------------------------------------------- */
@keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
@@ -821,6 +916,7 @@ body.drawer-open #backdrop { display: block; }
@keyframes pop-in { from { opacity: 0; transform: translateY(-4px) scale(.97); } to { opacity: 1; transform: none; } }
@keyframes pulse { 0%, 100% { opacity: .3; transform: scale(.85); } 50% { opacity: 1; transform: scale(1); } }
@keyframes blink { 0%, 100% { opacity: 1; } 50% { opacity: 0; } }
@keyframes shimmer { from { background-position: 100% 0; } to { background-position: -120% 0; } }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation-duration: 1ms !important; transition-duration: 1ms !important; }
#scroll { scroll-behavior: auto; }