Compare commits

...
22 Commits
Author SHA1 Message Date
ZacharyZhang-NYandClaude Fable 5 39cb1ca1bc chore(release): bump workspace version to 0.1.13
Release / prepare draft release (push) Successful in 6s
Release / build (aarch64-apple-darwin) (push) Failing after 1s
Release / build (x86_64-apple-darwin) (push) Failing after 1s
Release / build (x86_64-pc-windows-msvc) (push) Canceled after 0s
Release / publish release (push) Canceled after 0s
Release / build (x86_64-unknown-linux-gnu) (push) Successful in 16m32s
Release / build (aarch64-unknown-linux-gnu) (push) Successful in 16m13s
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KSy9S31pZNWXtRZNVJ1sDf
2026-08-27 12:43:58 -04:00
ZacharyZhang-NYandClaude Fable 5 e83610db6a chore(legal): regenerate THIRD-PARTY-NOTICES for the 0.1.13 dependency set
cargo-about over the updated lockfile (h2 0.4.19, webbrowser 1.2.4).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KSy9S31pZNWXtRZNVJ1sDf
2026-08-27 12:09:34 -04:00
ZacharyZhang-NYandClaude Fable 5 fd5cff2de6 chore(gates): finish the Windows sweep — zero clippy findings workspace-wide
Second layer of platform gaps the mac/linux-only gate history left:
unix-only test imports/helpers now cfg-gated (mermaid, fast-worktree,
hunk-tracker, pager-render link test, three pty_e2e module decls),
clippy-suggested cleanups in Windows-cfg code (file-utils classifier,
tui console-mode restore, shared clipboard arboard-error flow, tools
terminal closure, workspace capability tail), and `cargo update` of h2
(RUSTSEC-2026-0258) and webbrowser (RUSTSEC-2026-0257) so `cargo deny
check advisories` passes again.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KSy9S31pZNWXtRZNVJ1sDf
2026-08-27 12:04:32 -04:00
ZacharyZhang-NYandClaude Fable 5 427e8b6fea docs(agents): record the upstream sync baseline and the subagent spawn bound
The 0.1.13 sync had to reconstruct the fork point by content
fingerprinting; the sync record (baseline snapshot, last-evaluated
upstream commit, and where upstream hides its per-change lists) now
lives in AGENTS.md so the next sync starts from facts.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KSy9S31pZNWXtRZNVJ1sDf
2026-08-27 11:55:19 -04:00
ZacharyZhang-NYandClaude Fable 5 50669bf302 chore(gates): zero clippy warnings and a buildable sandbox example on Windows
The full-workspace gates had never run on this platform: collapsible
ifs in the Windows shell probe, a same-type cast in the crash handler,
an unused AsRawHandle import, and the sandbox smoke-test example
building its unix-only body (libc, kernel enforcement) unconditionally.
The example now stubs main off-unix; formatting reflow from cargo fmt.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KSy9S31pZNWXtRZNVJ1sDf
2026-08-27 11:55:19 -04:00
ZacharyZhang-NYandClaude Fable 5 25d1a4f980 fix(sampler): retry Cloudflare 52x and other 5xx during outages
Port of upstream grok-build 1.0.0/1.0.1-window retry policy.

- is_retryable_api_status: 429 plus any 5xx except Cloudflare 525/526
  (origin TLS handshake / invalid certificate — never clears on its
  own), replacing the 500|502|503|504|520 allowlist so the 521-524,
  529, and 530 edge pages an outage serves actually retry.
- The generic retry path clamps a server Retry-After to
  MAX_RETRY_BACKOFF (30s) and jitters it: Cloudflare 52x pages ask for
  60-120s, which across the budget stalled a turn ~28 minutes. The 429
  path keeps the full (parse-capped) Retry-After under its low attempt
  cap, and jitter is shared via jittered().

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KSy9S31pZNWXtRZNVJ1sDf
2026-08-27 11:51:36 -04:00
ZacharyZhang-NYandClaude Fable 5 a441b23a6d fix(mcp): kigi mcp add <name> <url> infers an HTTP server
Port of upstream grok-build 1.0.9. A bare positional http(s):// URL
with no transport flag was silently added as a stdio command whose
"command" was the URL. It now infers the HTTP transport with a notice;
extra args, --env, legacy --command/--url, and every explicit flag keep
their prior meaning, and scheme-less URL-looking commands still stay
stdio with the existing warning.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KSy9S31pZNWXtRZNVJ1sDf
2026-08-27 11:42:47 -04:00
ZacharyZhang-NYandClaude Fable 5 574122884a fix(windows): resolve the home directory via the standard lookup
Port of upstream grok-build 1.0.4/1.0.5. Two paths read $HOME only,
which is usually unset on Windows outside Git Bash:

- the global-gitignore fallback (prompt/ignore.rs) now uses
  std::env::home_dir(), the crate-wide idiom;
- fast-worktree's resolve_kigi_home falls back to std::env::home_dir()
  with the same dunce canonicalization, eliminating the documented
  divergence from kigi_config::default_kigi_home. On Unix home_dir()
  reads $HOME first, so behavior is unchanged where HOME is set.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KSy9S31pZNWXtRZNVJ1sDf
2026-08-27 11:34:45 -04:00
ZacharyZhang-NYandClaude Fable 5 97de661554 fix(startup): thread-exhaustion resilience — cap workers, never panic
Port of upstream grok-build 0.2.113/0.2.114 fixes, extended to Kigi's
startup order.

- kigi-tty-utils runtime module: worker-cap policy (8 max) — tokio's
  per-core default pins 100+ thread slots on many-core shared hosts
  against RLIMIT_NPROC / pids.max, and later spawns die with EAGAIN.
- kigi-bin builds the main runtime with capped workers and reports an
  out-of-threads host with a diagnostic + exit(1) instead of a panic.
- The pre-runtime optimization threads (HTTP warmup, early model
  prefetch) spawn recoverably and degrade — their panic would have
  preempted the runtime's own diagnostic.
- The per-session actor thread and its runtime report spawn/build
  failure through the existing acp::Error / AgentBuildError boundaries
  (new RuntimeBuild variant) instead of panicking the agent host.
- fsnotify's watcher thread spawn maps into FsNotifyError::WatcherStart
  so callers degrade instead of crashing.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KSy9S31pZNWXtRZNVJ1sDf
2026-08-27 11:28:17 -04:00
ZacharyZhang-NYandClaude Fable 5 bf93091416 fix(agents): bound how many subagents one session runs at once
Port of upstream grok-build 1.0.1 (landed upstream 2026-08-06). The
coordinator fire-and-forgot every spawn, so a wide fan-out (graph
waves, swarm bursts, model-driven Task storms) could exhaust file
descriptors.

- kigi-tools task/admission: SubagentLimits — 32 concurrent per session
  by default (KIGI_MAX_CONCURRENT_SUBAGENTS), queue|fail behavior
  (KIGI_SUBAGENT_LIMIT_BEHAVIOR), zero clamped to 1, read once at the
  composition root; parse_positive_env helper.
- Each parent session gets one spawn semaphore (map entries live for
  the process so a resumed session shares its predecessor's limit);
  handle_subagent_request holds an owned permit for the whole child
  run — queue awaits FIFO with a unified-log notice at saturation,
  fail routes through send_pre_spawn_failure. After a queued wait, a
  closed parent command channel (teardown) fails the spawn instead of
  running against a dead parent.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KSy9S31pZNWXtRZNVJ1sDf
2026-08-27 11:09:24 -04:00
ZacharyZhang-NYandClaude Fable 5 26d26e15c9 fix(exec): bounded post-kill reaps — D-state children can't wedge a turn
Port of upstream grok-build 1.0.1 (landed upstream 2026-08-06).

A child wedged in an uninterruptible kernel syscall (D-state) never
observes SIGKILL, and a background descendant can hold the output pipes
open past the kill; both previously stalled tool futures without bound.

- kigi-tty-utils: KILL_REAP_TIMEOUT (5s) + reap_killed_bounded — wait
  for an already-killed child at most the bound, then abandon the corpse
  to tokio's orphan reaper.
- local_terminal: pipe readers share their buffer with the spawner and
  join under the reap bound on both exit arms (aborted readers are
  awaited so no tail bytes race the take); the whole tree is enrolled in
  a ProcessGroup and group-killed on timeout; the timeout arm returns
  the synthetic result instead of waiting on the corpse. Grandchild
  kill + prompt-return pinned by a ported unix regression test.
- kigi-tools: reap_killed_search_child wrapper; grep's four kill sites
  reap bounded; glob's stderr goes to null (an unread pipe blocks rg on
  warning backpressure) and its truncation kill reaps bounded.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KSy9S31pZNWXtRZNVJ1sDf
2026-08-27 10:45:17 -04:00
ZacharyZhang-NYandClaude Fable 5 1ae803519e fix(compaction): configurable summarizer tool_choice; wider overflow detection
Port of upstream grok-build 0.2.105 + 0.2.118.

- CompactionToolChoice (auto default | none), resolved env
  KIGI_COMPACTION_TOOL_CHOICE > [features].compaction_tool_choice >
  remote settings. Some OpenAI-compatible servers reject
  tool_choice:"none" with tools attached, failing every long-session
  compaction; auto keeps them working (the summarization prompt already
  forbids tool use). Threaded from agent + subagent spawn through
  CompactionConfig into generate_session_compact; the Responses gate
  counts hosted tools too, so a hosted-only request still carries the
  configured choice.
- is_context_length_error recognizes the "current message ... exceeds
  budget" phrasing, so that overflow is Fatal instead of burning the
  retry budget on a deterministic failure.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KSy9S31pZNWXtRZNVJ1sDf
2026-08-27 10:22:18 -04:00
ZacharyZhang-NYandClaude Fable 5 6a4bff0d45 fix(agent): a racing cancel can no longer wedge the session's turn slot
Port of upstream grok-build 0.2.103. session/prompt runs an async intake
preamble before enqueueing SessionCommand::Prompt on the actor mailbox; a
concurrent cancel could enqueue Cancel first, land on an idle actor as a
no-op, and the prompt then started a turn nothing would ever cancel.

The per-session prompt-intake lock becomes the dispatch lock: prompt()
holds it across intake as before, and cancel() now holds it around its
Cancel send, so a cancel orders behind the prompt it targets. Regression
test ported verbatim (unix-only harness, like its siblings).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KSy9S31pZNWXtRZNVJ1sDf
2026-08-27 09:53:09 -04:00
ZacharyZhang-NYandClaude Fable 5 6e0464fa74 fix(auth): unique tmp per auth.json write; tighten loose credential perms
Port of upstream grok-build 0.2.113-window fixes:
- write_auth_json_atomic tmp path gains a monotonic sequence next to the
  pid, so two concurrent in-process writers (background mint + proactive
  refresher) cannot share one tmp path and tear each other's bytes; a tmp
  write that fails partway is reclaimed instead of orphaned.
- New secure_file::ensure_owner_only_permissions (0o600 / Windows ACL)
  tightens pre-existing world-readable credential files on read, backup,
  write, replace, and restore. Best-effort with warns after durable
  content — a chmod-only failure must not masquerade as a failed write —
  and propagating in restore_prior_bytes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KSy9S31pZNWXtRZNVJ1sDf
2026-08-27 09:31:21 -04:00
ZacharyZhang-NYandClaude Fable 5 257caed650 Add kigicli.dev frontend worker with built site assets
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012pFJn6ycA4hPRwM9sqasi6
2026-08-25 23:04:06 -04:00
ZacharyZhang-NYandClaude Opus 5 3e1652ca98 ci: drop the inert GitHub workflows
Gitea ignores `.github/workflows/` entirely once `.gitea/workflows/` is
non-empty, so these two files have had no effect since the release workflow
landed — and the GitHub repo they targeted is gone (404, suspended account),
so they cannot run there either.

They were not merely dead: warm-cache.yml's Monday cron kept firing on the
Gitea side before `.gitea/` existed, queueing jobs against GitHub-hosted
labels (`macos-14`, `windows-2022`, `ubuntu-24.04-arm`) that no self-hosted
runner advertises. Those sat queued forever, and its one dispatchable leg
failed on `rustup: command not found` — the same bare-image gap the Gitea
workflow now provisions around.

`.gitea/workflows/release.yml` is the only pipeline; docs/RELEASE.md already
documents it as such.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-10 22:11:28 -04:00
ZacharyZhang-NYandClaude Opus 5 479fb8cbbd chore(release): bump workspace version to 0.1.12
Release / prepare draft release (push) Successful in 5s
Release / build (aarch64-apple-darwin) (push) Failing after 1s
Release / build (x86_64-apple-darwin) (push) Failing after 2s
Release / build (x86_64-pc-windows-msvc) (push) Canceled after 0s
Release / publish release (push) Canceled after 0s
Release / build (aarch64-unknown-linux-gnu) (push) Successful in 18m14s
Release / build (x86_64-unknown-linux-gnu) (push) Successful in 17m20s
Every crate inherits `workspace.package.version`, so the single edit plus
the refreshed lockfile carries the release. The `v0.1.12` tag is what
triggers the build; release.yml gates the tag against this value, and
`cargo metadata --locked` passes so the build's `--locked` will too.

This is the first release cut on Gitea Actions. v0.1.6 through v0.1.9 were
all cancelled for want of a runner whose label matched anything, so nothing
has ever published from the new forge — `releases/latest` still 404s, which
is exactly why `kigi update` finds nothing today. Ships the link migration
in the previous commit, so the installers and self-updater published here
point at Gitea instead of a GitHub repo that no longer serves them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-10 21:13:19 -04:00
ZacharyZhang-NYandClaude Opus 5 9fb82291b2 chore(migration): repoint every published link off GitHub
The canonical repo is git.zacharyzhang.com now, so every URL a user can
actually reach had to move with it.

Self-updater: `PRODUCTION_ENDPOINTS.update_base_url` targets Gitea's
`/api/v1/repos/.../releases`, which serves the same wire format GitHub's
releases API did — `Release`/asset deserialisation is unchanged. The alpha
channel requests `?per_page=30&limit=30` because GitHub reads the page size
from `per_page` and Gitea from `limit`, and each ignores the other's, so one
URL stays correct on either.

Installers: same API base, and the documented one-liners become
`https://kigicli.dev/install.{sh,ps1}`. That domain's Worker proxies both
files from Gitea raw `main`, so the published install command survives any
future forge move without being reprinted everywhere. install.ps1 also drops
the GitHub-specific `Accept: application/vnd.github+json`.

Everything else user-facing: `/feedback` and the shell's feedback fallback
point at the Gitea issue tracker, `/docs` at the Gitea-rendered README, and
web_fetch's User-Agent at kigicli.dev. SECURITY.md now routes reports to the
issue tracker with a warning to withhold exploitable detail, because Gitea
has no equivalent of GitHub's private vulnerability reporting. Comments
naming `.github/workflows/release.yml` name `.gitea/` now.

Tests assert against these constants rather than literal URLs, so they
follow automatically; the one URL-shape assertion (production endpoints are
https) still holds.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-10 21:13:19 -04:00
ZacharyZhang-NYandClaude Opus 5 8bdfb551b6 chore(git): ignore prompt.txt and the kigicli.dev worker artifacts
`/prompt.txt` is the one-shot Mac Mini runner-setup prompt. It carries a
Gitea runner registration token once filled in, and a leaked registration
token lets anyone attach a runner to the account and receive our jobs —
including release jobs. Anchored with a leading slash so a legitimately
tracked prompt.txt deeper in the tree would still be versioned.

The .wrangler/ and node_modules/ lines were already sitting uncommitted in
the working tree for the untracked frontend/ worker; they belong in this
same file, so they ride along rather than being split out.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-10 20:24:30 -04:00
ZacharyZhang-NYandClaude Opus 5 8864b9ecc5 ci(gitea): add the release workflow and point it at our real runners
Gitea has no hosted runners, so every `runs-on` has to name a machine we
registered ourselves — and the labels in the first draft of this file did
not match what our machines advertise. The only online Linux runner
(`dokploy-runner-01`) offers `ubuntu-latest`/`ubuntu-24.04`/`ubuntu-22.04`,
never `linux-x86_64`, and Gitea's API cannot relabel a runner remotely, so
a `v*` tag would have queued forever against a label nothing served.

The three Linux jobs therefore run on `ubuntu-latest`. That runner is in
container mode against a bare runner-image, so those legs now provision
what they need per run: build-essential, pkg-config, unzip (protoc), tar
and jq, plus rustup when absent — installed with `--default-toolchain none`
so `rust-toolchain.toml` still decides the channel and `rustup show`
materialises it. `prepare` installs jq/curl the same way. macOS stays on
`macos-arm64` and Windows on `windows-x86_64`, both host mode with their
toolchains preinstalled, so the new provisioning step is gated on a
`linux:` matrix key rather than on `ext == 'tar.gz'`, which covers Darwin
too.

docs/RELEASE.md picks up the corrected label table, the fact that
`register --labels` is ignored once config.yaml supplies them, the
registration-token call being a POST (a GET parses as runner id 0 and
404s), and how each host-mode runner is supervised so it survives reboots
and crashes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-10 20:21:22 -04:00
ZacharyZhang-NY 553ec1c620 chore(release): bump workspace version to 0.1.11
Release / build (x86_64-unknown-linux-gnu) (push) Failing after 5s
Release / build (aarch64-apple-darwin) (push) Canceled after 0s
Release / build (aarch64-unknown-linux-gnu) (push) Canceled after 0s
Release / build (x86_64-apple-darwin) (push) Canceled after 0s
Release / build (x86_64-pc-windows-msvc) (push) Canceled after 0s
Release / publish GitHub Release (push) Canceled after 0s
All 62 crates inherit `workspace.package.version`, so the single edit
plus the refreshed lockfile carries the release. The `v0.1.11` tag is
what triggers the build; release.yml gates the tag against this value.

Ships the sessionless-model-switch fix (f656627): `/model` from a
non-project launch directory now starts the session its deferred switch
drains into instead of dangling silently.
2026-07-27 16:04:51 -04:00
ZacharyZhang-NY f656627c10 fix(tui): start the session a sessionless model switch defers into
Launching kigi in a non-project directory (~/Downloads, ~, /tmp — anywhere
`is_project_dir` rejects) leaves the agent view session-less behind the
project-picker question, which only a PLAIN prompt can open. Slash
commands still execute there, so `/model <name> <effort>` stashed its
switch in `deferred_model_switch` — a stash that assumes a create is in
flight — and with none pending it dangled forever with zero feedback:
the picker rendered, the user chose model and effort, and nothing
changed. Not a 0.1.10 regression: 0.1.9 pty-reproduces identically; the
report correlated with the upgrade only because every earlier launch
happened to be from a project directory.

Apply the QueueCommand precedent ("queued slash work bypasses the
picker, so create the deferred session or it never drains") to both
deferral sites — Action::SwitchModel in the router and
set_default_model's no-session branch — via
skip_picker_and_create_session, whose in-flight guard already makes it a
no-op while a create is pending, so the racing-create case is unchanged.
SessionCreated then applies the stash through the existing
apply_deferred_model_switch path; pty-verified end-to-end from
~/Downloads (session created, model changed, effort applied).
2026-07-27 15:55:57 -04:00
138 changed files with 12593 additions and 5102 deletions

No files matched your search

+375
View File
@@ -0,0 +1,375 @@
name: Release
# PRD F8, Gitea edition. On a v* tag push, build the single-file kigi binary
# for the five supported targets, package kigi-<version>-<target-triple>.
# {tar.gz|zip} (binary + LICENSE + NOTICE + THIRD-PARTY-NOTICES), and publish
# them as a Gitea Release alongside SHA256SUMS. install.sh, install.ps1 and
# auto_update::release_asset_name() all resolve these exact names — keep the
# naming in lockstep with them.
#
# RUNNERS. Gitea has no hosted runners; every label below must be a runner you
# registered yourself (docs/RELEASE.md has the register commands):
#
# ubuntu-latest Linux x86_64, container mode — the label the Dokploy box's
# runner already advertises. Builds both Linux targets;
# aarch64 is a cross-compile, so this leg installs the
# aarch64 GNU toolchain. Because the image is a bare
# runner-image, the Linux legs provision their own apt
# packages and rustup (see the provision steps below).
# Registering a dedicated `linux-x86_64:docker://...` runner
# instead is fine — swap the three labels back if you do.
# macos-arm64 Apple Silicon Mac, host mode. Builds both Darwin targets;
# x86_64 is a cross-compile against the same SDK. macOS
# CANNOT be built anywhere else — Apple's SDK licence
# restricts it to Apple hardware.
# windows-x86_64 Windows x86_64, host mode, with VS 2022 Build Tools
# (C++ workload). Needed because the tree links ring,
# mimalloc, zstd-sys and libz-sys against a static MSVC CRT
# (-C target-feature=+crt-static).
#
# SHELLS. Every step names its shell explicitly and the Windows leg never uses
# bash. On a normal Windows box `bash` resolves to WSL (not Git Bash), and
# `pwsh` (PowerShell 7) is usually absent — so Windows steps use `powershell`,
# which is the built-in 5.1. Keep those steps 5.1-compatible: no `&&`, no
# ternary, no null-coalescing.
#
# Note: because this file exists, Gitea ignores .github/workflows entirely.
#
# PUBLISH ORDER. The release is created as a draft and only made public once
# SHA256SUMS is attached, so `releases/latest` never hands the installer a
# release whose checksum manifest is still missing.
on:
push:
tags: ["v*"]
permissions:
contents: write
env:
CARGO_TERM_COLOR: always
# Matches the version pinned by the dotslash launcher in bin/protoc. That
# launcher is not used here: it has no Windows entry and needs a `cargo
# install dotslash` first, so every platform fetches protoc directly.
PROTOC_VERSION: "29.3"
jobs:
prepare:
name: prepare draft release
runs-on: ubuntu-latest
outputs:
release_id: ${{ steps.draft.outputs.release_id }}
steps:
- uses: actions/checkout@v4
- name: Check tag matches workspace version
shell: bash
run: |
tag_version="${GITHUB_REF_NAME#v}"
cargo_version="$(sed -n 's/^version = "\(.*\)"$/\1/p' Cargo.toml | head -n 1)"
if [ "$tag_version" != "$cargo_version" ]; then
echo "Tag $GITHUB_REF_NAME does not match workspace version $cargo_version" >&2
exit 1
fi
- name: Create or reuse draft release
id: draft
shell: bash
env:
TOKEN: ${{ secrets.GITEA_TOKEN }}
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
run: |
set -eu
# The runner-image is bare; jq and curl are both used below.
if ! command -v jq >/dev/null || ! command -v curl >/dev/null; then
SUDO=""; command -v sudo >/dev/null && SUDO=sudo
export DEBIAN_FRONTEND=noninteractive
$SUDO apt-get update -qq
$SUDO apt-get install -y -qq --no-install-recommends jq curl ca-certificates
fi
# Idempotent so a re-run of a failed tag build reuses the same draft
# instead of erroring on a duplicate tag_name.
existing="$(curl -sS -H "Authorization: token $TOKEN" \
"$API/releases/tags/$GITHUB_REF_NAME")"
release_id="$(printf '%s' "$existing" | jq -r '.id // empty')"
if [ -z "$release_id" ]; then
prerelease=false
case "$GITHUB_REF_NAME" in *-*) prerelease=true ;; esac
created="$(curl -fsS -X POST \
-H "Authorization: token $TOKEN" \
-H "Content-Type: application/json" \
-d "{\"tag_name\":\"$GITHUB_REF_NAME\",\"name\":\"$GITHUB_REF_NAME\",\"draft\":true,\"prerelease\":$prerelease}" \
"$API/releases")"
release_id="$(printf '%s' "$created" | jq -r '.id')"
echo "Created draft release $release_id (prerelease=$prerelease)"
else
echo "Reusing release $release_id for $GITHUB_REF_NAME"
fi
echo "release_id=$release_id" >> "$GITHUB_OUTPUT"
build:
name: build (${{ matrix.target }})
needs: prepare
strategy:
fail-fast: false
matrix:
include:
- target: x86_64-unknown-linux-gnu
runner: ubuntu-latest
protoc: linux-x86_64
ext: tar.gz
linux: true
- target: aarch64-unknown-linux-gnu
runner: ubuntu-latest
protoc: linux-x86_64
ext: tar.gz
linux: true
cross_gnu: true
- target: aarch64-apple-darwin
runner: macos-arm64
protoc: osx-aarch_64
ext: tar.gz
- target: x86_64-apple-darwin
runner: macos-arm64
protoc: osx-aarch_64
ext: tar.gz
- target: x86_64-pc-windows-msvc
runner: windows-x86_64
protoc: win64
ext: zip
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@v4
# ── linux container provisioning ──────────────────────────────────────
# The Linux legs run in a bare gitea runner-image, which ships git and
# node for the JavaScript actions but no compiler, no unzip (protoc) and
# no rustup. Host-mode macOS and Windows already have their toolchains
# installed, so this step is Linux-only.
- name: Provision Linux build deps
if: matrix.linux
shell: bash
run: |
set -eu
SUDO=""; command -v sudo >/dev/null && SUDO=sudo
export DEBIAN_FRONTEND=noninteractive
$SUDO apt-get update -qq
$SUDO apt-get install -y -qq --no-install-recommends \
build-essential pkg-config ca-certificates curl unzip tar jq
# ── protoc ────────────────────────────────────────────────────────────
- name: Install protoc (unix)
if: matrix.ext == 'tar.gz'
shell: bash
run: |
set -eu
url="https://github.com/protocolbuffers/protobuf/releases/download/v${PROTOC_VERSION}/protoc-${PROTOC_VERSION}-${{ matrix.protoc }}.zip"
curl -fsSL -o protoc.zip "$url"
rm -rf "$HOME/protoc"
unzip -q -o protoc.zip -d "$HOME/protoc"
chmod +x "$HOME/protoc/bin/protoc"
echo "$HOME/protoc/bin" >> "$GITHUB_PATH"
- name: Install protoc (windows)
if: matrix.ext == 'zip'
shell: powershell
run: |
$ErrorActionPreference = "Stop"
$url = "https://github.com/protocolbuffers/protobuf/releases/download/v$env:PROTOC_VERSION/protoc-$env:PROTOC_VERSION-${{ matrix.protoc }}.zip"
Invoke-WebRequest -Uri $url -OutFile protoc.zip
$dest = Join-Path $env:USERPROFILE "protoc"
if (Test-Path $dest) { Remove-Item $dest -Recurse -Force }
Expand-Archive protoc.zip -DestinationPath $dest -Force
Add-Content -Path $env:GITHUB_PATH -Value (Join-Path $dest "bin")
# ── toolchain ─────────────────────────────────────────────────────────
# rust-toolchain.toml pins the channel (1.97.0) and preinstalls both
# Linux targets; `rustup show` materialises exactly that.
- name: Install toolchain (unix)
if: matrix.ext == 'tar.gz'
shell: bash
run: |
set -eu
# No-op on the macOS host runner, which has rustup installed already.
# `--default-toolchain none` leaves the channel choice to
# rust-toolchain.toml, which `rustup show` then materialises.
if ! command -v rustup >/dev/null; then
curl --proto '=https' --tlsv1.2 -fsSL https://sh.rustup.rs \
| sh -s -- -y --no-modify-path --profile minimal --default-toolchain none
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
export PATH="$HOME/.cargo/bin:$PATH"
fi
rustup show
rustup target add ${{ matrix.target }}
- name: Install toolchain (windows)
if: matrix.ext == 'zip'
shell: powershell
run: |
$ErrorActionPreference = "Stop"
rustup show
rustup target add ${{ matrix.target }}
# ring, mimalloc, zstd-sys and libz-sys are all cc-rs builds, so the
# cross target needs its own C toolchain — cc-rs picks these up from the
# target-suffixed vars.
- name: Install aarch64 cross toolchain
if: matrix.cross_gnu
shell: bash
run: |
set -eu
SUDO=""; command -v sudo >/dev/null && SUDO=sudo
$SUDO apt-get update -qq
$SUDO apt-get install -y -qq gcc-aarch64-linux-gnu g++-aarch64-linux-gnu
{
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc"
echo "CC_aarch64_unknown_linux_gnu=aarch64-linux-gnu-gcc"
echo "CXX_aarch64_unknown_linux_gnu=aarch64-linux-gnu-g++"
echo "AR_aarch64_unknown_linux_gnu=aarch64-linux-gnu-ar"
} >> "$GITHUB_ENV"
# ── build ─────────────────────────────────────────────────────────────
- name: Build kigi (unix)
if: matrix.ext == 'tar.gz'
shell: bash
run: cargo build --profile release-dist -p kigi-bin --locked --target ${{ matrix.target }}
- name: Build kigi (windows)
if: matrix.ext == 'zip'
shell: powershell
run: |
$ErrorActionPreference = "Stop"
cargo build --profile release-dist -p kigi-bin --locked --target ${{ matrix.target }}
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
# ── package, upload, checksum ─────────────────────────────────────────
# Archives go straight to the release rather than through the artifact
# store: they are large, and the release is the only place install.sh
# can read them from anyway. Only the checksum line travels as an
# artifact, for the publish job to concatenate.
- name: Package and upload (unix)
if: matrix.ext == 'tar.gz'
shell: bash
env:
TOKEN: ${{ secrets.GITEA_TOKEN }}
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
RELEASE_ID: ${{ needs.prepare.outputs.release_id }}
run: |
set -eu
version="${GITHUB_REF_NAME#v}"
archive="kigi-${version}-${{ matrix.target }}.tar.gz"
staging="$(mktemp -d)"
cp "target/${{ matrix.target }}/release-dist/kigi" "$staging/kigi"
cp LICENSE "$staging/"
[ -f NOTICE ] && cp NOTICE "$staging/"
for f in THIRD-PARTY-NOTICES THIRD-PARTY-NOTICES.md; do
[ -f "$f" ] && cp "$f" "$staging/"
done
tar -C "$staging" -czf "$archive" .
curl -fsS -X POST \
-H "Authorization: token $TOKEN" \
-F "attachment=@${archive}" \
"$API/releases/$RELEASE_ID/assets?name=${archive}" > /dev/null
echo "Uploaded $archive"
if command -v sha256sum >/dev/null; then
sha256sum "$archive" > "checksum-${{ matrix.target }}.txt"
else
shasum -a 256 "$archive" > "checksum-${{ matrix.target }}.txt"
fi
cat "checksum-${{ matrix.target }}.txt"
- name: Package and upload (windows)
if: matrix.ext == 'zip'
shell: powershell
env:
TOKEN: ${{ secrets.GITEA_TOKEN }}
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
RELEASE_ID: ${{ needs.prepare.outputs.release_id }}
run: |
$ErrorActionPreference = "Stop"
$version = $env:GITHUB_REF_NAME.TrimStart("v")
$archive = "kigi-$version-${{ matrix.target }}.zip"
$staging = Join-Path $env:RUNNER_TEMP "staging"
if (Test-Path $staging) { Remove-Item $staging -Recurse -Force }
New-Item -ItemType Directory -Force -Path $staging | Out-Null
Copy-Item "target/${{ matrix.target }}/release-dist/kigi.exe" (Join-Path $staging "kigi.exe")
Copy-Item LICENSE $staging
if (Test-Path NOTICE) { Copy-Item NOTICE $staging }
foreach ($f in @("THIRD-PARTY-NOTICES", "THIRD-PARTY-NOTICES.md")) {
if (Test-Path $f) { Copy-Item $f $staging }
}
Compress-Archive -Path (Join-Path $staging "*") -DestinationPath $archive -Force
# System32\curl.exe, not PowerShell's `curl` alias for
# Invoke-WebRequest, which cannot do multipart uploads.
$api = "$env:API/releases/$env:RELEASE_ID/assets?name=$archive"
& "$env:SystemRoot\System32\curl.exe" -fsS -X POST `
-H "Authorization: token $env:TOKEN" `
-F "attachment=@$archive" $api
if ($LASTEXITCODE -ne 0) { throw "asset upload failed ($LASTEXITCODE)" }
Write-Host "Uploaded $archive"
# sha256sum's exact format, so the publish job can just concatenate.
# ASCII keeps the BOM out — a BOM would corrupt the first hash.
$hash = (Get-FileHash -Algorithm SHA256 -Path $archive).Hash.ToLowerInvariant()
"$hash $archive" | Out-File -FilePath "checksum-${{ matrix.target }}.txt" -Encoding ascii
Get-Content "checksum-${{ matrix.target }}.txt"
- uses: actions/upload-artifact@v3
with:
name: checksum-${{ matrix.target }}
path: checksum-${{ matrix.target }}.txt
if-no-files-found: error
publish:
name: publish release
needs: [prepare, build]
runs-on: ubuntu-latest
steps:
- uses: actions/download-artifact@v3
with:
path: checksums
- name: Assemble SHA256SUMS
shell: bash
run: |
set -eu
# download-artifact v3 nests each artifact in its own directory. The
# Windows line arrives CRLF-terminated; strip CR so every line is LF
# for install.sh's `read -r hash name`.
find checksums -name 'checksum-*.txt' -exec cat {} + \
| tr -d '\r' | grep -v '^$' | sort -k2 > SHA256SUMS
lines="$(wc -l < SHA256SUMS)"
if [ "$lines" -ne 5 ]; then
echo "expected 5 checksum lines, got $lines" >&2
cat SHA256SUMS >&2
exit 1
fi
cat SHA256SUMS
- name: Attach SHA256SUMS and publish
shell: bash
env:
TOKEN: ${{ secrets.GITEA_TOKEN }}
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
RELEASE_ID: ${{ needs.prepare.outputs.release_id }}
run: |
set -eu
curl -fsS -X POST \
-H "Authorization: token $TOKEN" \
-F "attachment=@SHA256SUMS" \
"$API/releases/$RELEASE_ID/assets?name=SHA256SUMS" > /dev/null
# Flip the draft public only now that every asset install.sh looks
# for is attached.
curl -fsS -X PATCH \
-H "Authorization: token $TOKEN" \
-H "Content-Type: application/json" \
-d '{"draft":false}' \
"$API/releases/$RELEASE_ID" > /dev/null
echo "Published $GITHUB_REF_NAME"
-147
View File
@@ -1,147 +0,0 @@
name: Release
# PRD F8: on tag push v*, build the single-file kigi binary for the five
# supported targets, package per-target archives named
# kigi-<version>-<target-triple>.{tar.gz|zip} (binary + LICENSE + NOTICE +
# THIRD-PARTY-NOTICES), generate SHA256SUMS, and publish everything as a
# GitHub Release. install.sh / install.ps1 and the in-app self-updater
# (kigi-update) both resolve these exact asset names — keep the naming in
# lockstep with auto_update::release_asset_name().
on:
push:
tags: ["v*"]
permissions:
contents: write
env:
CARGO_TERM_COLOR: always
jobs:
build:
name: build (${{ matrix.target }})
strategy:
fail-fast: false
matrix:
include:
- target: aarch64-apple-darwin
os: macos-14
# macos-14 runners are arm64; the x86_64 slice is a cross-compile
# against the same SDK (macos-13 Intel runners are deprecated).
- target: x86_64-apple-darwin
os: macos-14
- target: x86_64-unknown-linux-gnu
os: ubuntu-24.04
- target: aarch64-unknown-linux-gnu
os: ubuntu-24.04-arm
- target: x86_64-pc-windows-msvc
os: windows-2022
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Check tag matches workspace version
shell: bash
run: |
tag_version="${GITHUB_REF_NAME#v}"
cargo_version="$(sed -n 's/^version = "\(.*\)"$/\1/p' Cargo.toml | head -n 1)"
if [ "$tag_version" != "$cargo_version" ]; then
echo "Tag $GITHUB_REF_NAME does not match workspace version $cargo_version" >&2
exit 1
fi
- name: Install toolchain (rust-toolchain.toml)
run: rustup show
- name: Add build target
run: rustup target add ${{ matrix.target }}
- name: Install dotslash (protoc launcher)
run: cargo install dotslash --locked
# Windows cannot exec the dotslash launcher directly (no shebang
# support → os error 193), and the build script's documented fallback
# is a protoc on PATH — install the same version the dotslash file
# pins (v29.3).
- name: Install protoc (Windows PATH fallback)
if: runner.os == 'Windows'
shell: pwsh
run: |
$url = "https://github.com/protocolbuffers/protobuf/releases/download/v29.3/protoc-29.3-win64.zip"
Invoke-WebRequest -Uri $url -OutFile protoc.zip
Expand-Archive protoc.zip -DestinationPath "$env:USERPROFILE\protoc"
Add-Content $env:GITHUB_PATH "$env:USERPROFILE\protoc\bin"
- uses: Swatinem/rust-cache@v2
with:
key: ${{ matrix.target }}
- name: Build kigi (release-dist)
run: cargo build --profile release-dist -p kigi-bin --locked --target ${{ matrix.target }}
- name: Package archive (tar.gz)
if: runner.os != 'Windows'
shell: bash
run: |
version="${GITHUB_REF_NAME#v}"
archive="kigi-${version}-${{ matrix.target }}.tar.gz"
staging="$(mktemp -d)"
cp "target/${{ matrix.target }}/release-dist/kigi" "$staging/kigi"
cp LICENSE "$staging/"
[ -f NOTICE ] && cp NOTICE "$staging/"
for f in THIRD-PARTY-NOTICES THIRD-PARTY-NOTICES.md; do
[ -f "$f" ] && cp "$f" "$staging/"
done
tar -C "$staging" -czf "$archive" .
shasum -a 256 "$archive" || sha256sum "$archive"
echo "ARCHIVE=$archive" >> "$GITHUB_ENV"
- name: Package archive (zip)
if: runner.os == 'Windows'
shell: pwsh
run: |
$version = $env:GITHUB_REF_NAME.TrimStart("v")
$archive = "kigi-$version-${{ matrix.target }}.zip"
$staging = New-Item -ItemType Directory -Path (Join-Path $env:RUNNER_TEMP "staging")
Copy-Item "target/${{ matrix.target }}/release-dist/kigi.exe" (Join-Path $staging "kigi.exe")
Copy-Item LICENSE $staging
if (Test-Path NOTICE) { Copy-Item NOTICE $staging }
foreach ($f in @("THIRD-PARTY-NOTICES", "THIRD-PARTY-NOTICES.md")) {
if (Test-Path $f) { Copy-Item $f $staging }
}
Compress-Archive -Path (Join-Path $staging "*") -DestinationPath $archive
Get-FileHash -Algorithm SHA256 $archive
Add-Content -Path $env:GITHUB_ENV -Value "ARCHIVE=$archive"
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: ${{ env.ARCHIVE }}
path: ${{ env.ARCHIVE }}
if-no-files-found: error
release:
name: publish GitHub Release
needs: build
runs-on: ubuntu-24.04
steps:
- uses: actions/download-artifact@v4
with:
path: dist
merge-multiple: true
- name: Generate SHA256SUMS
working-directory: dist
run: |
ls -l
sha256sum kigi-* > SHA256SUMS
cat SHA256SUMS
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
files: dist/*
prerelease: ${{ contains(github.ref_name, '-') }}
generate_release_notes: true
fail_on_unmatched_files: true
-85
View File
@@ -1,85 +0,0 @@
name: Warm build cache
# Release builds run on TAG refs, and GitHub Actions cache isolation only
# lets a run restore caches created on its OWN ref or the DEFAULT branch.
# No workflow ran on `main`, so every release compiled the whole workspace
# cold on all five targets (~50 min wall clock, gated by Windows). This
# workflow builds the same `release-dist` profile on `main` so tag builds
# restore a warm default-branch cache.
#
# Triggers: dependency-affecting pushes to main (each release's version-bump
# commit warms the cache for the NEXT release), a weekly refresh so the
# cache never hits GitHub's 7-day unused-eviction, and manual dispatch.
#
# The setup steps mirror release.yml's build job (toolchain, target,
# dotslash/protoc, rust-cache key) — keep them in lockstep, or the cache
# key won't match and releases go back to cold builds.
on:
push:
branches: ["main"]
paths:
- "Cargo.lock"
- "Cargo.toml"
- "rust-toolchain.toml"
- ".github/workflows/warm-cache.yml"
schedule:
- cron: "17 5 * * 1"
workflow_dispatch:
permissions:
contents: read
env:
CARGO_TERM_COLOR: always
concurrency:
group: warm-cache
cancel-in-progress: true
jobs:
warm:
name: warm (${{ matrix.target }})
strategy:
fail-fast: false
matrix:
include:
- target: aarch64-apple-darwin
os: macos-14
- target: x86_64-apple-darwin
os: macos-14
- target: x86_64-unknown-linux-gnu
os: ubuntu-24.04
- target: aarch64-unknown-linux-gnu
os: ubuntu-24.04-arm
- target: x86_64-pc-windows-msvc
os: windows-2022
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Install toolchain (rust-toolchain.toml)
run: rustup show
- name: Add build target
run: rustup target add ${{ matrix.target }}
- name: Install dotslash (protoc launcher)
run: cargo install dotslash --locked
- name: Install protoc (Windows PATH fallback)
if: runner.os == 'Windows'
shell: pwsh
run: |
$url = "https://github.com/protocolbuffers/protobuf/releases/download/v29.3/protoc-29.3-win64.zip"
Invoke-WebRequest -Uri $url -OutFile protoc.zip
Expand-Archive protoc.zip -DestinationPath "$env:USERPROFILE\protoc"
Add-Content $env:GITHUB_PATH "$env:USERPROFILE\protoc\bin"
# Same key as release.yml so tag builds restore this cache verbatim.
- uses: Swatinem/rust-cache@v2
with:
key: ${{ matrix.target }}
- name: Build kigi (release-dist)
run: cargo build --profile release-dist -p kigi-bin --locked --target ${{ matrix.target }}
+7
View File
@@ -1,3 +1,10 @@
/target
**/*.rs.bk
.DS_Store
# frontend/ (kigicli.dev worker)
.wrangler/
node_modules/
# Runner-setup prompt; holds a Gitea registration token once filled in.
/prompt.txt
+15
View File
@@ -14,6 +14,14 @@ official `kimi` CLI: binary `kigi`, config dir `~/.kigi`
Never read or write `~/.kimi` (except the explicit one-time read-only
import) or any `KIMI_*` env var.
Upstream sync record (update on every sync): fork baseline is upstream
snapshot `8adf901` (2026-07-16, ≈v0.2.102); bug fixes evaluated and
selectively ported through upstream `77cd7eb` (2026-08-25, ≈v1.0.10) in
the 0.1.13 cycle. Upstream is daily "Synced from monorepo" snapshots —
the commit BODIES carry per-change bullet lists, and
`crates/codegen/xai-grok-shell/changelogs/` maps releases to dates;
start any future sync from those two, not from raw diffs.
## Hard constraints
- **Zero egress**: only `auth.kimi.com`, `api.kimi.com`, `api.moonshot.cn`,
@@ -195,6 +203,13 @@ client-side, no backend surface.
(`MAX_SWARM_RUNTIME`) are bounded: the swarm blocks the caller's turn,
so every wait needs a ceiling. Stragglers at the deadline are reported
as still-running WITH their ids.
- Underneath every fan-out (swarm, graph, raw Task) sits the
session-scoped spawn bound: `handle_subagent_request` holds one permit
from the parent session's semaphore for the whole child run
(kigi-tools `task/admission`: 32 default via
`KIGI_MAX_CONCURRENT_SUBAGENTS`, queue|fail via
`KIGI_SUBAGENT_LIMIT_BEHAVIOR`), so wide fan-outs queue instead of
exhausting file descriptors.
- `ToolKind::AgentSwarm` is its own variant because `TemplateRenderer`'s
`by_kind` map holds ONE tool name per kind — sharing `Task` would
silently redirect `${{ tools.by_kind.task }}` in other tools' prompts.
Generated
+83 -83
View File
@@ -228,7 +228,7 @@ version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -251,7 +251,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -1810,7 +1810,7 @@ version = "3.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.48.0",
]
[[package]]
@@ -2654,7 +2654,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users 0.5.2",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -2980,7 +2980,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -3958,7 +3958,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b305d85504de270ad3525d726a6b69cc59ee7b2269b014387651107ab9f0755b"
dependencies = [
"bstr",
"hashbrown 0.17.1",
"hashbrown 0.15.5",
]
[[package]]
@@ -4497,9 +4497,9 @@ dependencies = [
[[package]]
name = "h2"
version = "0.4.15"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155"
checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16"
dependencies = [
"atomic-waker",
"bytes",
@@ -5442,7 +5442,7 @@ dependencies = [
[[package]]
name = "kigi-acp-lib"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"agent-client-protocol",
"async-trait",
@@ -5456,7 +5456,7 @@ dependencies = [
[[package]]
name = "kigi-agent"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"chrono",
"dirs 6.0.0",
@@ -5486,7 +5486,7 @@ dependencies = [
[[package]]
name = "kigi-agent-lifecycle"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"async-trait",
"tokio",
@@ -5495,7 +5495,7 @@ dependencies = [
[[package]]
name = "kigi-auth"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"async-trait",
"http 1.4.2",
@@ -5508,7 +5508,7 @@ dependencies = [
[[package]]
name = "kigi-bin"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"anyhow",
"clap",
@@ -5543,7 +5543,7 @@ dependencies = [
[[package]]
name = "kigi-chat-state"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"indexmap",
"kigi-compaction",
@@ -5560,7 +5560,7 @@ dependencies = [
[[package]]
name = "kigi-codebase-graph"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"ahash",
"clap",
@@ -5596,7 +5596,7 @@ dependencies = [
[[package]]
name = "kigi-compaction"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"anyhow",
"async-trait",
@@ -5609,7 +5609,7 @@ dependencies = [
[[package]]
name = "kigi-config"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"base64",
"blake3",
@@ -5632,7 +5632,7 @@ dependencies = [
[[package]]
name = "kigi-config-types"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"agent-client-protocol",
"indexmap",
@@ -5646,7 +5646,7 @@ dependencies = [
[[package]]
name = "kigi-crash-handler"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"backtrace",
"libc",
@@ -5657,7 +5657,7 @@ dependencies = [
[[package]]
name = "kigi-env"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"tracing",
"url",
@@ -5665,7 +5665,7 @@ dependencies = [
[[package]]
name = "kigi-fast-worktree"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"anyhow",
"bytes",
@@ -5697,7 +5697,7 @@ dependencies = [
[[package]]
name = "kigi-file-utils"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"anyhow",
"aws-config",
@@ -5721,7 +5721,7 @@ dependencies = [
[[package]]
name = "kigi-fsnotify"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"criterion",
"dunce",
@@ -5742,7 +5742,7 @@ dependencies = [
[[package]]
name = "kigi-gix-status"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"gix",
"kigi-test-utils",
@@ -5752,7 +5752,7 @@ dependencies = [
[[package]]
name = "kigi-hooks"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"fastrand",
"kigi-config",
@@ -5771,7 +5771,7 @@ dependencies = [
[[package]]
name = "kigi-hooks-plugins-types"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"serde",
"serde_json",
@@ -5779,7 +5779,7 @@ dependencies = [
[[package]]
name = "kigi-http"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"kigi-auth",
"kigi-log",
@@ -5794,7 +5794,7 @@ dependencies = [
[[package]]
name = "kigi-hunk-tracker"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"chrono",
"dunce",
@@ -5815,14 +5815,14 @@ dependencies = [
[[package]]
name = "kigi-interjection-core"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"serde",
]
[[package]]
name = "kigi-log"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"anyhow",
"chrono",
@@ -5840,7 +5840,7 @@ dependencies = [
[[package]]
name = "kigi-markdown"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"anstyle",
"anstyle-lossy",
@@ -5864,14 +5864,14 @@ dependencies = [
[[package]]
name = "kigi-markdown-core"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"pulldown-cmark",
]
[[package]]
name = "kigi-mcp"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"agent-client-protocol",
"async-trait",
@@ -5908,7 +5908,7 @@ dependencies = [
[[package]]
name = "kigi-memory"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"anyhow",
"arc-swap",
@@ -5942,7 +5942,7 @@ dependencies = [
[[package]]
name = "kigi-mermaid"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"fontdb",
"image",
@@ -5960,7 +5960,7 @@ dependencies = [
[[package]]
name = "kigi-models"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"kigi-env",
"serde",
@@ -5970,7 +5970,7 @@ dependencies = [
[[package]]
name = "kigi-pager-minimal"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"chrono",
"crossterm",
@@ -5987,7 +5987,7 @@ dependencies = [
[[package]]
name = "kigi-pager-pty-harness"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"alacritty_terminal",
"anyhow",
@@ -6012,7 +6012,7 @@ dependencies = [
[[package]]
name = "kigi-pager-render"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"agent-client-protocol",
"anstyle",
@@ -6064,7 +6064,7 @@ dependencies = [
[[package]]
name = "kigi-paths"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"camino",
"serde",
@@ -6074,7 +6074,7 @@ dependencies = [
[[package]]
name = "kigi-prompt-queue"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"serde",
"serde_json",
@@ -6082,7 +6082,7 @@ dependencies = [
[[package]]
name = "kigi-proto-build"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"anyhow",
"pbjson-build",
@@ -6093,7 +6093,7 @@ dependencies = [
[[package]]
name = "kigi-ratatui-inline"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"ansi-width",
"anstyle-parse 0.2.7",
@@ -6110,7 +6110,7 @@ dependencies = [
[[package]]
name = "kigi-ratatui-textarea"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"arboard",
"chrono",
@@ -6131,7 +6131,7 @@ dependencies = [
[[package]]
name = "kigi-sampler"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"async-openai",
"async-stream",
@@ -6154,7 +6154,7 @@ dependencies = [
[[package]]
name = "kigi-sampling-types"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"assert_matches",
"async-openai",
@@ -6171,7 +6171,7 @@ dependencies = [
[[package]]
name = "kigi-sandbox"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"anyhow",
"chrono",
@@ -6192,7 +6192,7 @@ dependencies = [
[[package]]
name = "kigi-secrets"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"regex",
"serde_json",
@@ -6230,7 +6230,7 @@ dependencies = [
[[package]]
name = "kigi-shell"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"agent-client-protocol",
"anyhow",
@@ -6367,7 +6367,7 @@ dependencies = [
[[package]]
name = "kigi-shell-base"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"anyhow",
"chrono",
@@ -6392,7 +6392,7 @@ dependencies = [
[[package]]
name = "kigi-sqlite-journal"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"libc",
"rusqlite",
@@ -6403,7 +6403,7 @@ dependencies = [
[[package]]
name = "kigi-subagent-resolution"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"kigi-sampling-types",
"kigi-tool-types",
@@ -6418,7 +6418,7 @@ dependencies = [
[[package]]
name = "kigi-system-power"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"windows-sys 0.59.0",
"zbus",
@@ -6426,7 +6426,7 @@ dependencies = [
[[package]]
name = "kigi-test-support"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"agent-client-protocol",
"anyhow",
@@ -6448,7 +6448,7 @@ dependencies = [
[[package]]
name = "kigi-test-utils"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"runfiles",
"tracing",
@@ -6457,11 +6457,11 @@ dependencies = [
[[package]]
name = "kigi-token-estimation"
version = "0.1.10"
version = "0.1.13"
[[package]]
name = "kigi-tool-protocol"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"kigi-tool-types",
"serde",
@@ -6472,7 +6472,7 @@ dependencies = [
[[package]]
name = "kigi-tool-runtime"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"anyhow",
"async-trait",
@@ -6490,7 +6490,7 @@ dependencies = [
[[package]]
name = "kigi-tool-types"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"minijinja",
"schemars 1.2.1",
@@ -6500,7 +6500,7 @@ dependencies = [
[[package]]
name = "kigi-tools"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"anyhow",
"arc-swap",
@@ -6577,7 +6577,7 @@ dependencies = [
[[package]]
name = "kigi-tools-api"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"kigi-proto-build",
"kigi-tool-protocol",
@@ -6590,11 +6590,11 @@ dependencies = [
[[package]]
name = "kigi-tracing-macros"
version = "0.1.10"
version = "0.1.13"
[[package]]
name = "kigi-tty-utils"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"libc",
"nix 0.30.1",
@@ -6604,7 +6604,7 @@ dependencies = [
[[package]]
name = "kigi-tui"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"agent-client-protocol",
"ansi-to-tui",
@@ -6691,7 +6691,7 @@ dependencies = [
[[package]]
name = "kigi-update"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"anyhow",
"dunce",
@@ -6720,14 +6720,14 @@ dependencies = [
[[package]]
name = "kigi-version"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"semver",
]
[[package]]
name = "kigi-workspace"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"agent-client-protocol",
"anyhow",
@@ -6806,7 +6806,7 @@ dependencies = [
[[package]]
name = "kigi-workspace-types"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"base64",
"chrono",
@@ -7305,7 +7305,7 @@ version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "536bfad37a309d62069485248eeaba1e8d9853aaf951caaeaed0585a95346f08"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -7576,7 +7576,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -7997,7 +7997,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.48.0",
]
[[package]]
@@ -8840,7 +8840,7 @@ dependencies = [
[[package]]
name = "ptyctl"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"alacritty_terminal",
"anyhow",
@@ -8858,7 +8858,7 @@ dependencies = [
[[package]]
name = "ptyctl-cli"
version = "0.1.10"
version = "0.1.13"
dependencies = [
"anyhow",
"axum",
@@ -8992,7 +8992,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -9617,7 +9617,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -9687,7 +9687,7 @@ dependencies = [
"security-framework 3.7.0",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -10536,7 +10536,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -10937,7 +10937,7 @@ dependencies = [
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.4",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -11882,7 +11882,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
dependencies = [
"memoffset",
"tempfile",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -12414,15 +12414,15 @@ dependencies = [
[[package]]
name = "webbrowser"
version = "1.2.1"
version = "1.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fc95580916af1e68ff6a7be07446fc5db73ebf71cf092de939bbf5f7e189f72"
checksum = "62c35be770821a214dbc362fc26908c853e776c0004294d0b10b8a6bad582f94"
dependencies = [
"core-foundation 0.10.1",
"jni",
"log",
"ndk-context",
"objc2 0.6.4",
"objc2-app-kit",
"objc2-foundation 0.3.2",
"url",
"web-sys",
@@ -12561,7 +12561,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.48.0",
]
[[package]]
+1 -1
View File
@@ -76,7 +76,7 @@ members = [
]
[workspace.package]
version = "0.1.10"
version = "0.1.13"
edition = "2024"
license = "Apache-2.0"
+4 -4
View File
@@ -36,12 +36,12 @@ key? OpenAI, Anthropic, Google, DeepSeek, Groq, Moonshot and
```sh
# macOS / Linux
curl -fsSL https://raw.githubusercontent.com/ZacharyZhang-NY/Kigi-CLI/main/install.sh | bash
curl -fsSL https://kigicli.dev/install.sh | bash
```
```powershell
# Windows PowerShell
irm https://raw.githubusercontent.com/ZacharyZhang-NY/Kigi-CLI/main/install.ps1 | iex
irm https://kigicli.dev/install.ps1 | iex
```
```sh
@@ -176,8 +176,8 @@ keyring entry, and its own `KIGI_*` env vars, and never touches what the
official `kimi` CLI installed. `kigi import-kimi` copies your old config over
once, read-only.
**Zero telemetry.** It talks to the APIs you configured, GitHub Releases, and
your own MCP servers. Nothing else.
**Zero telemetry.** It talks to the APIs you configured, the Kigi release
server, and your own MCP servers. Nothing else.
## License
+5 -3
View File
@@ -1,8 +1,10 @@
# Security Policy
Kigi is a community build; report vulnerabilities via
[GitHub private vulnerability reporting](https://github.com/ZacharyZhang-NY/Kigi-CLI/security/advisories/new)
on this repository. Please do not open public issues for security reports.
Kigi is a community build; report vulnerabilities on the
[Kigi issue tracker](https://git.zacharyzhang.com/ZacharyZhang-NY/Kigi-CLI/issues).
Issues there are public, so please leave out any detail that would make a
report directly exploitable — open with the affected area and impact, and a
maintainer will follow up for the rest.
Dependency advisories are gated in CI with `cargo deny check advisories`;
documented exceptions live in `deny.toml`.
+5936 -4507
View File
File diff suppressed because it is too large. Load diff
+5
View File
@@ -17,6 +17,11 @@ pub enum AgentBuildError {
#[error("IO error during agent construction: {0}")]
IoError(#[from] std::io::Error),
/// The per-session runtime could not be built — fd or thread
/// exhaustion (EMFILE/EAGAIN), not a definition problem.
#[error("failed to build the session runtime: {0}")]
RuntimeBuild(std::io::Error),
/// Carries template line numbers and surrounding context.
#[error("template rendering error: {0}")]
MiniJinjaError(#[from] minijinja::Error),
@@ -32,5 +32,5 @@ fn get_global_gitignore_path() -> Option<PathBuf> {
git2::Config::open_default()
.ok()
.and_then(|cfg| cfg.get_path("core.excludesFile").ok())
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".gitignore")))
.or_else(|| std::env::home_dir().map(|h| h.join(".gitignore")))
}
+18 -2
View File
@@ -1221,10 +1221,26 @@ fn main() {
"Found crashed sessions from a previous run"
);
}
let runtime = tokio::runtime::Builder::new_multi_thread()
// Capped workers: tokio's per-core default pins 100+ thread slots on
// many-core shared hosts and later spawns die with EAGAIN.
let runtime = match tokio::runtime::Builder::new_multi_thread()
.worker_threads(kigi_tty_utils::runtime::capped_worker_threads().get())
.enable_all()
.build()
.unwrap_or_else(|e| panic!("failed to start tokio runtime: {e}"));
{
Ok(runtime) => runtime,
Err(e) => {
// A host out of threads (RLIMIT_NPROC / pids.max) is an
// environment problem, not a bug — report it, don't panic.
kigi_tty_utils::restore_native_stderr();
eprintln!("Error: failed to start the async runtime: {e}");
eprintln!(
"The host may be out of threads (RLIMIT_NPROC or the cgroup pids ceiling); \
close other processes or raise the limit, then retry."
);
std::process::exit(1);
}
};
let result = run_and_shutdown(runtime, async_main(), RUNTIME_SHUTDOWN_GRACE);
kigi_log::debug_log::flush();
if let Err(e) = result {
@@ -668,6 +668,11 @@ pub struct RemoteSettings {
/// remote settings verbatim-input flag; env (`KIGI_COMPACTION_VERBATIM_INPUT`) and config override it. `None` = default (true).
#[serde(default)]
pub compaction_verbatim_input: Option<bool>,
/// Compaction summarizer `tool_choice` (`auto` | `none`) from remote
/// settings. Env (`KIGI_COMPACTION_TOOL_CHOICE`) and config override it.
/// Some backends reject `tool_choice: "none"` with tools attached.
#[serde(default)]
pub compaction_tool_choice: Option<String>,
/// Master switch for jemalloc heap sampling + threshold dumps.
/// `Some(true)` enables, `Some(false)` kill-switch, `None` = client default off.
#[serde(default)]
+11 -13
View File
@@ -78,11 +78,10 @@ pub fn detect_windows_shell() -> &'static WindowsShell {
kigi_tty_utils::detach_std_command(&mut cmd);
cmd.arg("pwsh.exe").stdin(std::process::Stdio::null());
cmd.output()
} {
if output.status.success() {
tracing::info!("Windows shell: pwsh");
return WindowsShell::Pwsh;
}
} && output.status.success()
{
tracing::info!("Windows shell: pwsh");
return WindowsShell::Pwsh;
}
// powershell.exe (Windows PowerShell 5.1).
@@ -131,14 +130,13 @@ fn find_git_bash() -> Option<String> {
kigi_tty_utils::detach_std_command(&mut cmd);
cmd.arg("bash.exe").stdin(std::process::Stdio::null());
cmd.output()
} {
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
for line in stdout.lines() {
let line = line.trim();
if line.to_ascii_lowercase().contains("git") {
return Some(line.to_string());
}
} && output.status.success()
{
let stdout = String::from_utf8_lossy(&output.stdout);
for line in stdout.lines() {
let line = line.trim();
if line.to_ascii_lowercase().contains("git") {
return Some(line.to_string());
}
}
}
@@ -616,7 +616,7 @@ mod win {
}
let signal = exception_to_signal(exception_code);
let si_code = exception_code as i32;
let si_code = exception_code;
// ExceptionInformation[1] holds the faulting address for ACCESS_VIOLATION.
let si_addr = if exception_code == EXCEPTION_ACCESS_VIOLATION
+4 -3
View File
@@ -11,7 +11,8 @@ pub struct KigiEndpoints {
pub coding_api_base_url: &'static str,
/// OAuth device-flow host for Kimi Code subscription login.
pub oauth_host: &'static str,
/// GitHub Releases API endpoint the self-updater polls.
/// Releases API endpoint the self-updater polls (GitHub-Releases-shaped;
/// Gitea's `/api/v1` serves the same wire format).
pub update_base_url: &'static str,
/// Human-facing page for subscription upgrade guidance.
pub upgrade_page_url: &'static str,
@@ -20,7 +21,7 @@ pub struct KigiEndpoints {
pub const PRODUCTION_ENDPOINTS: KigiEndpoints = KigiEndpoints {
coding_api_base_url: "https://api.kimi.com/coding/v1",
oauth_host: "https://auth.kimi.com",
update_base_url: "https://api.github.com/repos/ZacharyZhang-NY/Kigi-CLI/releases",
update_base_url: "https://git.zacharyzhang.com/api/v1/repos/ZacharyZhang-NY/Kigi-CLI/releases",
upgrade_page_url: "https://www.kimi.com/code/",
};
@@ -29,7 +30,7 @@ pub const CODE_BASE_URL_ENV: &str = "KIGI_CODE_BASE_URL";
/// Env var overriding [`oauth_host`] (PRD F1).
pub const OAUTH_HOST_ENV: &str = "KIGI_OAUTH_HOST";
/// Env var overriding [`update_base_url`] (PRD F8). Points the self-updater
/// at an alternate GitHub-Releases-shaped API (mirrors, tests).
/// at an alternate GitHub/Gitea-Releases-shaped API (mirrors, tests).
pub const UPDATE_BASE_URL_ENV: &str = "KIGI_UPDATE_BASE_URL";
fn resolve(var: &str, compiled: &'static str) -> String {
@@ -76,6 +76,7 @@ mod tests {
assert_eq!(std::fs::read(&dest).unwrap(), data);
}
#[cfg(unix)]
#[test]
fn test_clone_preserves_permissions() {
use std::os::unix::fs::PermissionsExt;
@@ -341,12 +341,14 @@ pub fn resolve_kigi_home() -> Result<PathBuf> {
if let Ok(v) = std::env::var("KIGI_SHARE_DIR") {
return Ok(PathBuf::from(v));
}
let home =
PathBuf::from(std::env::var("HOME").context("neither $KIGI_SHARE_DIR nor $HOME is set")?);
// Canonicalize the home dir so worktree paths share the same physical .kigi
// tree as trust/hooks even when it is symlinked. The dunce canonicalization
// must stay in sync with kigi_config::default_kigi_home();
// home resolution deliberately differs ($HOME here vs std::env::home_dir()).
// Standard home-dir lookup (`USERPROFILE`/Known Folders on Windows, where
// `HOME` is usually unset outside Git Bash) — the same resolution as
// kigi_config::default_kigi_home(), so worktree paths land in the same
// physical .kigi tree as trust/hooks.
let home = std::env::home_dir()
.context("neither $KIGI_SHARE_DIR nor a home directory could be resolved")?;
// Canonicalize so a symlinked home still maps to one physical tree; the
// dunce canonicalization must stay in sync with default_kigi_home().
Ok(dunce::canonicalize(&home).unwrap_or(home).join(".kigi"))
}
@@ -37,6 +37,7 @@ pub(crate) fn execute_plan(plan: WorktreePlan) -> Result<CreateWorktreeResult> {
#[cfg(test)]
mod tests {
#[cfg(unix)]
use super::*;
use crate::{IgnoredFilesMode, WorkingTreeMode, WorktreeBuilder};
use kigi_test_utils::git::{git_commit_all, init_git_repo};
@@ -89,10 +89,10 @@ fn is_platform_system_dir(cwd: &Path) -> bool {
#[cfg(target_os = "windows")]
fn is_platform_system_dir(cwd: &Path) -> bool {
if let Ok(temp) = std::env::var("TEMP").or_else(|_| std::env::var("TMP")) {
if cwd.starts_with(&temp) {
return true;
}
if let Ok(temp) = std::env::var("TEMP").or_else(|_| std::env::var("TMP"))
&& cwd.starts_with(&temp)
{
return true;
}
let path_lower = cwd.to_string_lossy().to_lowercase();
@@ -103,7 +103,7 @@ fn is_platform_system_dir(cwd: &Path) -> bool {
return true;
}
if cwd.parent().map_or(false, |p| p.parent().is_none()) && cwd.to_string_lossy().len() <= 3 {
if cwd.parent().is_some_and(|p| p.parent().is_none()) && cwd.to_string_lossy().len() <= 3 {
return true;
}
+8 -2
View File
@@ -971,7 +971,7 @@ pub(crate) fn start_with_timeout(
let progress_for_thread = progress.clone();
let thread = std::thread::spawn(move || {
let watcher_loop = move || {
let update_stage = |stage: &'static str| {
if let Ok(mut p) = progress_for_thread.lock() {
p.set_stage(stage);
@@ -1351,7 +1351,13 @@ pub(crate) fn start_with_timeout(
let _ = ready_tx.send(Err(Box::new(e)));
}
}
});
};
// Recoverable spawn: a host out of threads must surface as an error the
// caller can degrade on, not a `std::thread::spawn` panic.
let thread = std::thread::Builder::new()
.name("fsnotify-watcher".into())
.spawn(watcher_loop)
.map_err(|e| crate::FsNotifyError::WatcherStart(Box::new(e)))?;
// Wait for watcher to be ready (with timeout)
if let Ok(mut p) = progress.lock() {
@@ -318,6 +318,7 @@ mod tests {
assert!(matches!(state, FileContentState::TooLarge { .. }));
}
#[cfg(unix)]
#[tokio::test]
async fn test_read_file_bounded_symlink() {
let dir = tempfile::tempdir().unwrap();
+1
View File
@@ -150,6 +150,7 @@ fn write_private(path: &Path, contents: &str) -> std::io::Result<()> {
#[cfg(test)]
mod tests {
use super::*;
#[cfg(unix)]
use std::time::Instant;
/// Write an executable `#!/bin/sh` fake `mmdc` and return (dir-guard, path).
@@ -179,9 +179,12 @@ fn reap_process_group(_child: &Child) {
#[cfg(test)]
mod tests {
use super::*;
#[cfg(unix)]
use std::process::Stdio;
#[cfg(unix)]
use std::time::Instant;
#[cfg(unix)]
fn detached(mut cmd: Command) -> Command {
cmd.stdin(Stdio::null())
.stdout(Stdio::null())
@@ -214,6 +214,7 @@ pub fn open_url_if_safe(url: &str, filter: SchemeFilter) -> bool {
mod tests {
use super::*;
#[cfg(not(target_os = "windows"))]
#[test]
fn open_path_command_passes_path_as_a_single_arg() {
// Path with spaces must be one argument, never shell-interpolated.
@@ -10,6 +10,7 @@
//! portable re-injection exists (TIOCSTI is blocked); accepted loss.
use std::io::Write;
#[cfg(unix)]
use std::time::Duration;
/// Bounds the reply buffer against terminals that stream without a terminator.
+47 -7
View File
@@ -5,8 +5,11 @@
//!
//! # Retry behavior summary
//!
//! **Retried** (up to [`DEFAULT_MAX_RETRIES`] = 15, ~6 min with 30s backoff cap):
//! - 500, 502, 503, 504, 520 (server errors)
//! **Retried** (up to [`DEFAULT_MAX_RETRIES`] = 15, ~6 min with the
//! [`MAX_RETRY_BACKOFF`] cap — a server `Retry-After` is clamped to it too):
//! - Any 5xx except Cloudflare 525/526 — covers the Cloudflare edge pages
//! (520-524 origin unreachable/timed out, 530 edge 1xxx) and upstream
//! overload (529); see `is_retryable_api_status`
//! - Connection errors (timeout, refused, reset)
//! - `EventStreamError` / `StreamError` (mid-stream failures)
//! - `EmptyResponse` (model returned no content/tool calls)
@@ -77,16 +80,35 @@ pub fn doom_loop_backoff(retry_count: u32) -> Duration {
Duration::from_millis(hasher.finish() % 251)
}
/// Exponential backoff (2s, 4s, 8s, ..., capped 30s) with +/-20% jitter
/// to prevent thundering-herd retry storms.
/// Longest single wait on the generic retry path — the exponential-backoff
/// ceiling, and the clamp for a server `Retry-After`. Cloudflare answers 52x
/// with `Retry-After: 60`-`120`; honoring that verbatim across the retry
/// budget would stall a turn ~28 min instead of the ~6 min budget. The 429
/// path deliberately waits the full `Retry-After` instead, bounded by
/// [`RATE_LIMIT_RETRY_THRESHOLD`] attempts (and by the parse-level 120s cap
/// on the header).
pub const MAX_RETRY_BACKOFF: Duration = Duration::from_secs(30);
/// Exponential backoff (2s, 4s, 8s, ..., capped at [`MAX_RETRY_BACKOFF`])
/// with +/-20% jitter to prevent thundering-herd retry storms.
pub fn retry_backoff_with_jitter(retry_count: u32) -> Duration {
let shift = retry_count.saturating_sub(1);
let base_ms = 2000u64
.checked_shl(shift)
.unwrap_or(u64::MAX)
.min(MAX_RETRY_BACKOFF.as_millis() as u64);
jittered(Duration::from_millis(base_ms))
}
/// +/-20% jitter around `base`, de-syncing clients that failed at the
/// same instant (e.g. a mass Cloudflare 52x event during an origin outage).
fn jittered(base: Duration) -> Duration {
use std::hash::{Hash, Hasher};
use std::sync::atomic::{AtomicU64, Ordering};
static JITTER_SEQ: AtomicU64 = AtomicU64::new(0);
let shift = retry_count.saturating_sub(1);
let base_ms = 2000u64.checked_shl(shift).unwrap_or(u64::MAX).min(30_000);
let base_ms = base.as_millis() as u64;
let jitter_range = base_ms / 5;
let mut hasher = std::hash::DefaultHasher::new();
JITTER_SEQ.fetch_add(1, Ordering::Relaxed).hash(&mut hasher);
@@ -210,9 +232,11 @@ pub fn classify_error(
if next_attempt >= max_retries {
return RetryDecision::Fatal(clone_error(err));
}
// A server `Retry-After` is clamped: Cloudflare 52x pages ask for
// 60-120s, which across the budget would stall a turn ~28 min.
let backoff = err
.retry_after()
.map(Duration::from_secs)
.map(|secs| jittered(Duration::from_secs(secs).min(MAX_RETRY_BACKOFF)))
.unwrap_or_else(|| retry_backoff_with_jitter(next_attempt));
if next_attempt == 1 {
return RetryDecision::RetryWithClientRebuild { backoff };
@@ -595,6 +619,22 @@ mod tests {
}
}
#[test]
fn classify_5xx_retry_after_is_clamped_to_backoff_cap() {
// Cloudflare answers 52x with Retry-After: 60-120; honoring it
// verbatim across the retry budget would stall a turn ~28 min.
let err = api_err_with_retry_after(StatusCode::from_u16(522).unwrap(), 120);
match classify_error(&err, 1, 15, RATE_LIMIT_RETRY_THRESHOLD) {
RetryDecision::Retry { backoff } => {
assert!(
backoff <= MAX_RETRY_BACKOFF.mul_f64(1.2),
"52x Retry-After must clamp to ~MAX_RETRY_BACKOFF, got {backoff:?}"
);
}
other => panic!("expected Retry, got {other:?}"),
}
}
#[test]
fn classify_5xx_first_retry_rebuilds_client() {
let err = api_err(StatusCode::INTERNAL_SERVER_ERROR, "boom");
@@ -239,9 +239,7 @@ impl SamplingError {
SamplingError::InvalidConfiguration(_) => false,
SamplingError::Http(err) => is_retryable_reqwest(err),
SamplingError::Serialization(_) => false,
SamplingError::Api { status, .. } => {
matches!(status.as_u16(), 429 | 500 | 502 | 503 | 504 | 520)
}
SamplingError::Api { status, .. } => is_retryable_api_status(status.as_u16()),
SamplingError::EventStreamError(_) => true,
SamplingError::StreamError { .. } => true,
SamplingError::IdleTimeout { .. } => false,
@@ -342,6 +340,15 @@ pub fn try_parse_stream_error(data: &str) -> Option<SamplingError> {
})
}
/// 429 and any 5xx except Cloudflare 525/526 (origin TLS handshake /
/// invalid certificate — a broken origin certificate never clears on its
/// own). The 5xx sweep covers the Cloudflare edge pages (520-524 origin
/// unreachable/timed out, 530 edge 1xxx) and upstream overload (529),
/// which an outage serves in place of the API's own statuses.
pub fn is_retryable_api_status(status: u16) -> bool {
status == 429 || ((500..=599).contains(&status) && !matches!(status, 525 | 526))
}
/// True when an error message indicates a context-window overflow. Backends report
/// this inconsistently with no stable error code, so we match the message text; it's
/// deterministic (re-sending the same payload always fails), so callers must not retry.
@@ -352,6 +359,7 @@ pub fn is_context_length_error(message: &str) -> bool {
|| m.contains("maximum prompt length")
|| m.contains("maximum context length")
|| m.contains("context_length_exceeded")
|| (m.contains("current message") && m.contains("exceeds budget"))
}
/// Decide whether a [`reqwest::Error`] is worth retrying.
@@ -378,6 +386,27 @@ pub fn is_retryable_reqwest(err: &reqwest::Error) -> bool {
mod tests {
use super::*;
#[test]
fn retryable_api_status_covers_edge_5xx_and_excludes_broken_tls() {
for status in [
429u16, 500, 502, 503, 504, 520, 521, 522, 523, 524, 529, 530, 599,
] {
assert!(is_retryable_api_status(status), "should retry {status}");
}
// Cloudflare 525/526: origin TLS handshake / invalid certificate —
// a broken origin certificate never clears on its own.
for status in [525u16, 526, 400, 401, 403, 404, 408, 422, 200] {
assert!(!is_retryable_api_status(status), "must not retry {status}");
}
let api = SamplingError::Api {
status: StatusCode::from_u16(522).unwrap(),
message: "cloudflare: connection timed out".into(),
model_metadata: None,
retry_after_secs: None,
};
assert!(api.is_retryable(), "522 edge page must be retryable");
}
#[test]
fn context_length_error_matches_backend_variants() {
for msg in [
@@ -387,6 +416,7 @@ mod tests {
"This model's maximum context length is 200000 tokens",
"invalid_request_error: prompt is too long: 300000 tokens > 200000 maximum",
"error type: context_length_exceeded",
"the current message exceeds budget: 120000 < 250000",
] {
assert!(is_context_length_error(msg), "should match: {msg}");
}
@@ -14,9 +14,19 @@
//! cargo run -p kigi-sandbox --example sandbox_smoke_test -- read-only
//! ```
// Kernel enforcement is unix-only (Seatbelt / Landlock); Windows builds a
// stub so `--all-targets` stays green everywhere.
#[cfg(unix)]
use kigi_sandbox::{ProfileName, SandboxManager};
#[cfg(unix)]
use std::path::Path;
#[cfg(not(unix))]
fn main() {
eprintln!("sandbox_smoke_test exercises kernel enforcement and only runs on Unix.");
}
#[cfg(unix)]
fn main() {
let profile_name = std::env::args()
.nth(1)
@@ -121,6 +131,7 @@ fn main() {
println!("\n✅ Smoke test complete");
}
#[cfg(unix)]
fn test_read(label: &str, path: &Path) {
if path.is_file() {
match std::fs::read(path) {
@@ -150,6 +161,7 @@ fn test_read(label: &str, path: &Path) {
}
}
#[cfg(unix)]
fn test_write(label: &str, path: &Path) {
match std::fs::write(path, b"sandbox-test") {
Ok(()) => {
+9 -10
View File
@@ -1164,6 +1164,7 @@ mod platform {
#[cfg(not(target_os = "macos"))]
mod platform {
use super::ImageData;
#[cfg(target_os = "linux")]
use std::process::{Command, Stdio};
/// No subprocess-free pasteboard probe exists off-macOS.
@@ -1926,19 +1927,18 @@ mod platform {
// Public API
pub fn get_text() -> anyhow::Result<Option<String>> {
let mut arboard_error = None;
match arboard_get_text() {
let arboard_error = match arboard_get_text() {
Ok(Some(text)) => return Ok(Some(text)),
// Wayland-only: arboard's empty answer is not authoritative,
// fall through to wl-paste (see `wayland_tool_selected`).
#[cfg(target_os = "linux")]
Ok(None) if wayland_tool_selected(linux_tool_spec()) => {}
Ok(None) if wayland_tool_selected(linux_tool_spec()) => None,
Ok(None) => return Ok(None),
Err(e) => {
tracing::debug!("arboard get_text failed: {e}");
arboard_error = Some(e);
Some(e)
}
}
};
#[cfg(target_os = "linux")]
if let Some(spec) = linux_tool_spec() {
let bytes = run_capture_out_checked(spec.read_text, CLI_READ_WAIT)?;
@@ -2039,19 +2039,18 @@ mod platform {
}
pub fn get_image() -> anyhow::Result<Option<ImageData>> {
let mut arboard_error = None;
match arboard_get_image() {
let arboard_error = match arboard_get_image() {
Ok(Some(image)) => return Ok(Some(image)),
// Wayland-only: arboard's empty answer is not authoritative,
// fall through to wl-paste (see `wayland_tool_selected`).
#[cfg(target_os = "linux")]
Ok(None) if wayland_tool_selected(linux_tool_spec()) => {}
Ok(None) if wayland_tool_selected(linux_tool_spec()) => None,
Ok(None) => return Ok(None),
Err(e) => {
tracing::debug!("arboard get_image failed: {e}");
arboard_error = Some(e);
Some(e)
}
}
};
#[cfg(target_os = "linux")]
if let Some(spec) = linux_tool_spec()
&& let Some(argv) = spec.read_png
@@ -26,7 +26,7 @@ use std::io::{self, Write};
use std::path::Path;
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
/// Creates or opens a file with secure permissions (owner read/write only).
///
@@ -58,17 +58,20 @@ pub fn write_secure_file(path: &Path, contents: &[u8]) -> io::Result<()> {
file.write_all(contents)?;
file.flush()?;
// On Windows, we need to set permissions after file creation
#[cfg(windows)]
{
set_windows_secure_permissions(path)?;
}
// Re-assert owner-only bits: `OpenOptions::mode` only applies on create,
// so an existing world-readable file would otherwise keep open perms.
ensure_owner_only_permissions(path)?;
Ok(())
}
/// Opens a file for writing with secure permissions set during creation (Unix)
/// or prepares it for permission setting after creation (Windows).
///
/// Callers that write secret material should also call
/// [`ensure_owner_only_permissions`] after the write (or use
/// [`write_secure_file`]), because `mode(0o600)` only applies when the file
/// is newly created — not when truncating an existing path.
pub fn open_secure_file(path: &Path) -> io::Result<File> {
let mut options = OpenOptions::new();
options.truncate(true).write(true).create(true);
@@ -82,6 +85,44 @@ pub fn open_secure_file(path: &Path) -> io::Result<File> {
options.open(path)
}
/// Ensure `path` is owner-read/write only (Unix `0o600` / Windows user ACL).
///
/// Best-effort on missing files (`NotFound` is ignored). Other errors
/// propagate so callers can fail closed when tightening a secret store.
///
/// Use on **load** of credential files so a hand-copied or restored
/// world-readable `auth.json` is tightened before the process continues.
pub fn ensure_owner_only_permissions(path: &Path) -> io::Result<()> {
match ensure_owner_only_permissions_inner(path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e),
}
}
fn ensure_owner_only_permissions_inner(path: &Path) -> io::Result<()> {
#[cfg(unix)]
{
let metadata = std::fs::metadata(path)?;
let mode = metadata.permissions().mode();
if mode & 0o777 != 0o600 {
let mut perms = metadata.permissions();
perms.set_mode(0o600);
std::fs::set_permissions(path, perms)?;
}
Ok(())
}
#[cfg(windows)]
{
set_windows_secure_permissions(path)
}
#[cfg(not(any(unix, windows)))]
{
let _ = path;
Ok(())
}
}
/// Sets Windows-specific secure permissions on a file.
///
/// This function modifies the file's ACL to:
@@ -219,8 +260,6 @@ mod tests {
#[cfg(unix)]
#[test]
fn test_unix_permissions() {
use std::os::unix::fs::PermissionsExt;
let temp_dir = tempfile::tempdir().unwrap();
let file_path = temp_dir.path().join("test_perms.txt");
@@ -231,4 +270,43 @@ mod tests {
// Check that only owner has read/write (0o600), ignoring file type bits
assert_eq!(mode & 0o777, 0o600);
}
#[cfg(unix)]
#[test]
fn ensure_owner_only_tightens_world_readable_file() {
let temp_dir = tempfile::tempdir().unwrap();
let file_path = temp_dir.path().join("loose.txt");
fs::write(&file_path, b"secret").unwrap();
let mut loose = fs::metadata(&file_path).unwrap().permissions();
loose.set_mode(0o644);
fs::set_permissions(&file_path, loose).unwrap();
assert_eq!(
fs::metadata(&file_path).unwrap().permissions().mode() & 0o777,
0o644
);
ensure_owner_only_permissions(&file_path).unwrap();
assert_eq!(
fs::metadata(&file_path).unwrap().permissions().mode() & 0o777,
0o600
);
}
#[cfg(unix)]
#[test]
fn write_secure_file_tightens_existing_world_readable_file() {
let temp_dir = tempfile::tempdir().unwrap();
let file_path = temp_dir.path().join("existing.txt");
fs::write(&file_path, b"old").unwrap();
let mut loose = fs::metadata(&file_path).unwrap().permissions();
loose.set_mode(0o666);
fs::set_permissions(&file_path, loose).unwrap();
write_secure_file(&file_path, b"new secret").unwrap();
assert_eq!(
fs::metadata(&file_path).unwrap().permissions().mode() & 0o777,
0o600
);
assert_eq!(fs::read_to_string(&file_path).unwrap(), "new secret");
}
}
@@ -2171,6 +2171,19 @@ impl Config {
)
.with_segment_detail(self.resolve_compaction_detail())
}
/// Resolve summarizer `tool_choice`: env `KIGI_COMPACTION_TOOL_CHOICE` >
/// config > remote settings > default (`auto`).
pub(crate) fn resolve_compaction_tool_choice(
&self,
) -> crate::util::config::CompactionToolChoice {
crate::util::config::resolve_compaction_tool_choice_from(
env_string(crate::util::config::ENV_COMPACTION_TOOL_CHOICE).as_deref(),
self.features.compaction_tool_choice.as_deref(),
self.remote_settings
.as_ref()
.and_then(|r| r.compaction_tool_choice.as_deref()),
)
}
/// Resolve verbatim-input flag: env `KIGI_COMPACTION_VERBATIM_INPUT` > config > remote settings > default `true`.
pub(crate) fn resolve_compaction_verbatim_input(&self) -> bool {
BoolFlag::env("KIGI_COMPACTION_VERBATIM_INPUT")
@@ -3696,6 +3709,9 @@ pub struct Features {
/// Feed the summarizer the verbatim conversation instead of the lossy rewrite; `None` = defer to env/remote settings/default (true).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub compaction_verbatim_input: Option<bool>,
/// Summarizer `tool_choice` (`auto` | `none`); `None` = defer to env/remote settings/default (`auto`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub compaction_tool_choice: Option<String>,
/// Snapshot a completed subagent's isolated worktree into a durable git ref
/// and delete its directory (resume rehydrates from the ref). This is the
/// per-deployment rollout lever (set in managed_config.toml `[features]`).
@@ -3,7 +3,7 @@
//! Port of kimi-cli's `/feedback` slash command (kimi-cli
//! `src/kimi_cli/ui/shell/slash.py`, `feedback()`): subscription (OAuth)
//! sessions POST the user's feedback text to `{coding_api_base_url}/feedback`
//! with a Bearer token; everyone else is pointed at the GitHub issue tracker.
//! with a Bearer token; everyone else is pointed at the project issue tracker.
//! The request body carries exactly the fields kimi-cli sends:
//! `session_id`, `content`, `version`, `os`, `model`.
@@ -12,7 +12,8 @@ use std::sync::Arc;
use serde::Serialize;
/// Where non-subscription users (no OAuth session) submit feedback instead.
pub const FEEDBACK_ISSUES_URL: &str = "https://github.com/ZacharyZhang-NY/Kigi-CLI/issues";
pub const FEEDBACK_ISSUES_URL: &str =
"https://git.zacharyzhang.com/ZacharyZhang-NY/Kigi-CLI/issues";
/// HTTP error from the feedback endpoint with a preserved status code, so
/// callers can distinguish auth failures (401) without string matching.
+54 -41
View File
@@ -1938,7 +1938,7 @@ fn resolve_prefetch_env(kimi_code_config: Option<KimiCodeConfig>) -> Option<Pref
/// credentials from disk.
pub fn start_early_prefetch_with_auth(auth: Option<KimiAuth>) -> Option<EarlyPrefetchHandle> {
let env = resolve_prefetch_env_with_auth(auth)?;
Some(spawn_prefetch_thread(env))
spawn_prefetch_thread(env)
}
/// Start the model-catalog prefetch on a background thread.
@@ -1949,51 +1949,64 @@ pub fn start_early_prefetch(
kimi_code_config: Option<KimiCodeConfig>,
) -> Option<EarlyPrefetchHandle> {
let env = resolve_prefetch_env(kimi_code_config)?;
Some(spawn_prefetch_thread(env))
spawn_prefetch_thread(env)
}
fn spawn_prefetch_thread(env: PrefetchEnv) -> EarlyPrefetchHandle {
std::thread::spawn(move || {
let mut timer = crate::instrumentation_timer!("startup.early_prefetch");
let proxy_endpoint = env.endpoints.proxy_url();
timer.with_field("endpoint", proxy_endpoint.as_str());
// Resolve each stored subscription-OAuth session's bearer (refreshed
// on expiry) so those platforms are part of the STARTUP fetch plan —
// otherwise a claude-pro-max-only user boots onto the bundled Kimi
// table until some later async refresh happens to run, and the cache
// origin (which encodes enabled platforms) never matches the
// async-path's claude-inclusive origin.
let oauth_tokens = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map(|rt| {
rt.block_on(crate::agent::models_fetch::resolve_generic_oauth_tokens(
&crate::auth::oauth_registry::pool_home(),
))
})
.unwrap_or_default();
let models = prefetch_models_blocking(
&env.endpoints,
env.auth.as_ref(),
&oauth_tokens,
env.model_fetch_auth,
&env.platform_keys,
);
if (env.endpoints.deployment_key.is_some() || crate::managed_config::has_active_team_auth())
&& crate::config::is_managed_config_stale_for(
&crate::managed_config::current_serving_identity(),
)
&& crate::managed_config::is_fetch_enabled()
&& let Ok(rt) = tokio::runtime::Builder::new_current_thread()
/// `None` when the OS refuses a thread: the prefetch is an optimization and
/// runs before the runtime builds, so a spawn panic here would preempt the
/// runtime's own out-of-threads diagnostic.
fn spawn_prefetch_thread(env: PrefetchEnv) -> Option<EarlyPrefetchHandle> {
let spawned = std::thread::Builder::new()
.name("early-prefetch".into())
.spawn(move || {
let mut timer = crate::instrumentation_timer!("startup.early_prefetch");
let proxy_endpoint = env.endpoints.proxy_url();
timer.with_field("endpoint", proxy_endpoint.as_str());
// Resolve each stored subscription-OAuth session's bearer (refreshed
// on expiry) so those platforms are part of the STARTUP fetch plan —
// otherwise a claude-pro-max-only user boots onto the bundled Kimi
// table until some later async refresh happens to run, and the cache
// origin (which encodes enabled platforms) never matches the
// async-path's claude-inclusive origin.
let oauth_tokens = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
{
crate::managed_config::clear_orphan();
let _ = rt.block_on(crate::managed_config::sync());
}
.map(|rt| {
rt.block_on(crate::agent::models_fetch::resolve_generic_oauth_tokens(
&crate::auth::oauth_registry::pool_home(),
))
})
.unwrap_or_default();
let models = prefetch_models_blocking(
&env.endpoints,
env.auth.as_ref(),
&oauth_tokens,
env.model_fetch_auth,
&env.platform_keys,
);
if (env.endpoints.deployment_key.is_some()
|| crate::managed_config::has_active_team_auth())
&& crate::config::is_managed_config_stale_for(
&crate::managed_config::current_serving_identity(),
)
&& crate::managed_config::is_fetch_enabled()
&& let Ok(rt) = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
{
crate::managed_config::clear_orphan();
let _ = rt.block_on(crate::managed_config::sync());
}
EarlyPrefetchResult { models }
})
EarlyPrefetchResult { models }
});
match spawned {
Ok(handle) => Some(handle),
Err(e) => {
tracing::error!(error = %e, "early prefetch thread spawn failed; skipping prefetch");
None
}
}
}
/// Map a model id (catalog key or routing slug) to its catalog key.
@@ -1725,8 +1725,8 @@ impl acp::Agent for MvpAgent {
return Ok(acp::PromptResponse::new(acp::StopReason::EndTurn));
}
}
let intake_lock = self.prompt_intake_lock(&arguments.session_id);
let intake_guard = intake_lock.lock().await;
let dispatch_lock = self.dispatch_lock(&arguments.session_id);
let dispatch_guard = dispatch_lock.lock().await;
let meta_prompt_mode = arguments
.meta
.as_ref()
@@ -1830,7 +1830,7 @@ impl acp::Agent for MvpAgent {
acp::Error::internal_error()
.data(format!("failed to dispatch prompt to session: {e}"))
})?;
drop(intake_guard);
drop(dispatch_guard);
self.push_roster_activity_delta(
&arguments.session_id,
crate::agent::roster::RosterActivity::Working,
@@ -2025,6 +2025,11 @@ impl acp::Agent for MvpAgent {
.and_then(|m| m.get("rewindIfPristine"))
.and_then(|v| v.as_bool())
.unwrap_or(false);
// Ordered behind any in-flight prompt intake: a cancel that
// overtakes the prompt it targets lands on an idle actor, and the
// prompt then starts a turn nothing will ever cancel.
let dispatch_lock = self.dispatch_lock(&args.session_id);
let _dispatch_guard = dispatch_lock.lock().await;
let _ = handle
.cmd_tx
.send(SessionCommand::Cancel {
@@ -978,7 +978,10 @@ impl MvpAgent {
sessions: RefCell::new(HashMap::new()),
activity,
loading_sessions: RefCell::new(HashMap::new()),
prompt_intake_locks: RefCell::new(HashMap::new()),
dispatch_locks: RefCell::new(HashMap::new()),
subagent_limits:
kigi_tools::implementations::kigi::task::admission::SubagentLimits::from_env(),
subagent_spawn_permits: RefCell::new(HashMap::new()),
session_threads: RefCell::new(HashMap::new()),
resident_roster_titles: RefCell::new(HashMap::new()),
initialize_request: OnceLock::new(),
@@ -2183,6 +2186,7 @@ impl MvpAgent {
.cfg
.borrow()
.resolve_compaction_verbatim_input();
let compaction_tool_choice = self.cfg.borrow().resolve_compaction_tool_choice();
let two_pass_enabled = self.cfg.borrow().is_two_pass_compaction_enabled();
let auto_update = self.cfg.borrow().cli.auto_update;
let client_type = *self.client_type.borrow();
@@ -2568,6 +2572,7 @@ impl MvpAgent {
system_prompt_label,
compaction_mode,
compaction_verbatim_input,
compaction_tool_choice,
two_pass_enabled,
buffering_settings,
origin_client.clone(),
@@ -462,21 +462,30 @@ pub struct MvpAgent {
loading_sessions: RefCell<
HashMap<acp::SessionId, tokio::sync::watch::Receiver<bool>>,
>,
/// Per-session prompt-intake serialization lock. LEADER-SAFE(per-session):
/// keyed by SessionId, mirrors `sessions` lifecycle.
///
/// Each incoming `session/prompt` RPC is dispatched as its own task by the
/// ACP message loop, and [`Self::prompt`] runs an async preamble (prompt-mode
/// query, trace context, model lookup) BEFORE it enqueues
/// `SessionCommand::Prompt` onto the actor's FIFO mailbox. Without
/// serialization those preambles interleave across tasks, so the mailbox —
/// and therefore the authoritative prompt queue — receives prompts out of
/// submission order. `prompt()` holds this lock across the preamble and
/// releases it immediately after the enqueue (the turn itself runs unlocked),
/// which makes intake order match arrival order.
prompt_intake_locks: RefCell<
/// Per-session lock ordering dispatch onto the actor's mailbox:
/// [`Self::prompt`] holds it across its intake preamble (prompt-mode
/// query, trace context, model lookup) and releases it right after the
/// enqueue, so prompts land in submission order; `cancel` holds it
/// around its `Cancel` send, so a cancel cannot overtake the prompt it
/// targets and wedge the turn slot (see
/// `cancel_never_overtakes_in_flight_prompt_intake`). Cancels wait out
/// preambles held ahead of them — keep preambles lean.
/// LEADER-SAFE(per-session): mirrors `sessions` lifecycle.
dispatch_locks: RefCell<
HashMap<acp::SessionId, std::rc::Rc<tokio::sync::Mutex<()>>>,
>,
/// Session-scoped subagent spawn limits, read once from env at
/// construction (composition root).
subagent_limits: kigi_tools::implementations::kigi::task::admission::SubagentLimits,
/// Per-parent-session spawn semaphores sized to `subagent_limits`; a
/// wide fan-out queues on the semaphore instead of exhausting file
/// descriptors. Keyed by session id string (the coordinator's
/// `parent_session_id`). Entries deliberately live for the whole
/// process: a removed-then-resumed session keeps its id, so sharing one
/// semaphore across generations keeps the limit correct while old
/// children still run. Growth is bounded by distinct sessions per
/// process and each entry is tiny. LEADER-SAFE(per-session).
subagent_spawn_permits: RefCell<HashMap<String, std::sync::Arc<tokio::sync::Semaphore>>>,
/// LEADER-SAFE(per-session): keyed by SessionId. Mirrors `sessions` lifecycle.
session_threads: RefCell<HashMap<acp::SessionId, SessionThread>>,
/// Title per resident session id, refreshed each `build_roster`. Lets the
@@ -717,10 +726,18 @@ pub struct MvpAgent {
/// sampling client is discarded, but the TLS root certificates it loads
/// are cached at the process level by `rustls-native-certs`.
pub fn warm_async_http_client() {
std::thread::spawn(|| {
let _timer = crate::instrumentation_timer!("startup.async_http_warmup");
let _ = crate::http::shared_client();
});
// Recoverable spawn: the warmup is an optimization that runs before the
// runtime builds — an out-of-threads host must reach the runtime's own
// diagnostic, not panic here.
let spawned = std::thread::Builder::new()
.name("http-warmup".into())
.spawn(|| {
let _timer = crate::instrumentation_timer!("startup.async_http_warmup");
let _ = crate::http::shared_client();
});
if let Err(e) = spawned {
tracing::warn!(error = %e, "async HTTP warmup thread spawn failed; first request warms instead");
}
}
pub(crate) fn resolve_required_agent_type(
model_agent_type: Option<&str>,
@@ -38,19 +38,16 @@ impl MvpAgent {
/// drops the `session_live_state` entry so that map stays bounded.
pub(crate) fn remove_session(&self, id: &acp::SessionId) {
self.sessions.borrow_mut().remove(id);
self.prompt_intake_locks.borrow_mut().remove(id);
self.dispatch_locks.borrow_mut().remove(id);
self.session_threads.borrow_mut().remove(id);
self.session_index_claims.borrow_mut().remove(id);
self.require_gateway_sessions.borrow_mut().remove(id);
self.session_live_state.borrow_mut().remove(id);
}
/// Get-or-create the per-session prompt-intake lock (see
/// [`Self::prompt_intake_locks`]).
pub(super) fn prompt_intake_lock(
&self,
id: &acp::SessionId,
) -> std::rc::Rc<tokio::sync::Mutex<()>> {
self.prompt_intake_locks
/// Get-or-create the per-session dispatch lock (see
/// [`Self::dispatch_locks`]). Cheap clone of the shared `Rc`.
pub(super) fn dispatch_lock(&self, id: &acp::SessionId) -> std::rc::Rc<tokio::sync::Mutex<()>> {
self.dispatch_locks
.borrow_mut()
.entry(id.clone())
.or_default()
@@ -272,6 +272,19 @@ impl MvpAgent {
self.try_build_subagent_spawn_context(parent_session_id)
.expect("parent session must exist when spawning subagents")
}
/// Get-or-create the parent session's spawn semaphore (see
/// [`Self::subagent_spawn_permits`]). Cheap clone of the shared `Arc`.
fn subagent_spawn_permit(&self, parent_session_id: &str) -> std::sync::Arc<tokio::sync::Semaphore> {
self.subagent_spawn_permits
.borrow_mut()
.entry(parent_session_id.to_string())
.or_insert_with(|| {
std::sync::Arc::new(tokio::sync::Semaphore::new(
self.subagent_limits.effective_max_concurrent(),
))
})
.clone()
}
/// Fallible variant of [`Self::build_subagent_spawn_context`]: returns
/// `None` when the parent `SessionHandle` is absent (evicted / torn down)
/// instead of panicking, so read-only paths that can race a teardown can
@@ -387,6 +400,8 @@ impl MvpAgent {
};
Some(crate::agent::subagent::SubagentSpawnContext {
lsp: parent_lsp,
spawn_limits: self.subagent_limits,
spawn_permits: self.subagent_spawn_permit(parent_session_id),
gateway: self.gateway.clone(),
client_hooks: Default::default(),
sampling_config: self.sampling_config.borrow().clone(),
@@ -2152,6 +2152,59 @@ fn cancel_does_not_forward_to_bridge_in_local_mode() {
);
});
}
/// Regression (post-cancel slot hang): a cancel racing the prompt it targets
/// must land on the actor mailbox AFTER that prompt, or it hits an idle
/// actor as a no-op and the prompt then starts a turn nothing cancels.
/// The dispatch lock (`dispatch_locks`) provides that ordering.
#[test]
fn cancel_never_overtakes_in_flight_prompt_intake() {
use crate::session::SessionCommand;
use acp::Agent as _;
run_local_for_bridge_test(|| async {
let agent = build_minimal_agent_for_tests();
let sid = acp::SessionId::new("sess-cancel-intake-race");
let (handle, _tx, mut cmd_rx) = make_live_session_handle(&sid, None);
agent.sessions.borrow_mut().insert(sid.clone(), handle);
let order: std::rc::Rc<std::cell::RefCell<Vec<&'static str>>> =
std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
let (intake_parked_tx, intake_parked_rx) = tokio::sync::oneshot::channel::<()>();
let driver_order = order.clone();
tokio::task::spawn_local(async move {
let mut intake_parked_tx = Some(intake_parked_tx);
while let Some(cmd) = cmd_rx.recv().await {
match cmd {
SessionCommand::GetCurrentPromptMode { .. } => {
if let Some(tx) = intake_parked_tx.take() {
let _ = tx.send(());
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
}
SessionCommand::Prompt { .. } => driver_order.borrow_mut().push("prompt"),
SessionCommand::Cancel { .. } => driver_order.borrow_mut().push("cancel"),
_ => {}
}
}
});
let prompt_fut = agent.prompt(acp::PromptRequest::new(
sid.clone(),
vec![acp::ContentBlock::from("hi")],
));
let cancel_fut = async {
intake_parked_rx
.await
.expect("prompt intake reaches the fake actor");
let _ = agent
.cancel(acp::CancelNotification::new(sid.clone()))
.await;
};
let _ = futures::join!(prompt_fut, cancel_fut);
assert_eq!(
order.borrow().as_slice(),
["prompt", "cancel"],
"cancel must land on the actor mailbox after the prompt it targets"
);
});
}
use crate::session::SessionCommand as TestSessionCommand;
/// Build a session handle wired to a *live* command channel. Returns the
/// handle (move into `sessions`) plus a probe `cmd_tx`/`cmd_rx` so a test
@@ -81,6 +81,64 @@ pub(crate) async fn handle_subagent_request(
}
_ => {}
}
// Session-scoped concurrency admission: hold one permit for the whole
// child run so a wide fan-out queues (default) or fails (configured)
// instead of exhausting file descriptors. Queued spawns are not yet
// visible in the coordinator; they admit in FIFO order.
use kigi_tools::implementations::kigi::task::admission::LimitBehavior;
let _spawn_permit = match ctx.spawn_limits.behavior {
LimitBehavior::Fail => match ctx.spawn_permits.clone().try_acquire_owned() {
Ok(permit) => permit,
Err(_) => {
let limit = ctx.spawn_limits.effective_max_concurrent();
kigi_log::unified_log::warn(
"subagent.spawn.rejected_at_concurrent_limit",
Some(&ctx.parent_session_id),
Some(serde_json::json!({ "limit": limit })),
);
let msg = format!(
"Session subagent limit reached ({limit} running); \
retry after one finishes, or raise KIGI_MAX_CONCURRENT_SUBAGENTS"
);
send_pre_spawn_failure(request, &msg, coordinator, &ctx, gateway);
return;
}
},
LimitBehavior::Queue => {
if ctx.spawn_permits.available_permits() == 0 {
kigi_log::unified_log::warn(
"subagent.spawn.queued_at_concurrent_limit",
Some(&ctx.parent_session_id),
Some(serde_json::json!({
"limit": ctx.spawn_limits.effective_max_concurrent(),
"subagent_id": request.id,
})),
);
}
ctx.spawn_permits
.clone()
.acquire_owned()
.await
.expect("subagent spawn semaphore is never closed")
}
};
// The parent can end while a spawn is queued on the semaphore (a queued
// request is not yet in the coordinator, so the teardown cancel sweep
// cannot see it). A closed parent command channel is the teardown
// signal. The channel closes when the actor finishes shutting down, so a
// permit granted during that brief drain can still slip through — the
// same in-flight window an ordinary spawn racing teardown already has;
// closing it fully would require queueing inside the coordinator.
if ctx.parent_cmd_tx.as_ref().is_some_and(|tx| tx.is_closed()) {
send_pre_spawn_failure(
request,
"Parent session ended while the spawn was queued at the subagent limit.",
coordinator,
&ctx,
gateway,
);
return;
}
let run_in_background = request.run_in_background
|| definition.background.unwrap_or(false);
let cancel_token = CancellationToken::new();
@@ -1006,6 +1064,7 @@ pub(crate) async fn handle_subagent_request(
kigi_agent::DEFAULT_SYSTEM_PROMPT_LABEL.to_string(),
kigi_chat_state::CompactionMode::Summary,
ctx.resolve_compaction_verbatim_input(),
ctx.resolve_compaction_tool_choice(),
false,
None,
None,
@@ -133,6 +133,13 @@ impl AutoCompactThresholdTiers {
pub(crate) struct SubagentSpawnContext {
/// Parent's LSP runtime — inherited via ToolContext, same as fs/terminal.
pub lsp: Option<std::sync::Arc<dyn kigi_tools::implementations::lsp::LspBackend>>,
/// Session-scoped spawn limits (env-resolved once at the composition root).
pub spawn_limits: kigi_tools::implementations::kigi::task::admission::SubagentLimits,
/// Parent session's spawn semaphore, sized to
/// `spawn_limits.effective_max_concurrent()`. A permit is held for the
/// whole child run, so a wide fan-out queues (or fails, per behavior)
/// instead of exhausting file descriptors.
pub spawn_permits: std::sync::Arc<tokio::sync::Semaphore>,
#[expect(
dead_code,
reason = "unused in production; remove expect when wired or delete the item"
@@ -397,6 +404,21 @@ impl SubagentSpawnContext {
.resolve()
.value
}
/// Subagent summarizer `tool_choice`, mirroring
/// `Config::resolve_compaction_tool_choice` (env > config > remote
/// settings > default `auto`).
pub fn resolve_compaction_tool_choice(&self) -> crate::util::config::CompactionToolChoice {
crate::util::config::resolve_compaction_tool_choice_from(
crate::agent::config::env_string(crate::util::config::ENV_COMPACTION_TOOL_CHOICE)
.as_deref(),
self.agent_config
.as_ref()
.and_then(|c| c.features.compaction_tool_choice.as_deref()),
self.remote_settings
.as_ref()
.and_then(|r| r.compaction_tool_choice.as_deref()),
)
}
/// Whether a completed subagent's worktree is snapshotted into a durable ref
/// and its directory deleted. Resolution mirrors the other subagent gates
/// (env > config > remote settings > default). Default `false` so it ships dark;
+154 -12
View File
@@ -224,6 +224,18 @@ impl AuthFileLock {
pub fn read_auth_json(auth_file: &Path) -> std::io::Result<AuthStore> {
let mut file = File::open(auth_file)?;
// Tighten world-readable copies (hand-restored, umask edge cases, etc.)
// right after open, so even an unreadable/invalid file gets fixed.
// Best-effort: a chmod failure must not block login/read paths.
if let Err(e) = crate::util::secure_file::ensure_owner_only_permissions(auth_file) {
tracing::warn!(
path = %auth_file.display(),
error = %e,
"auth: failed to enforce owner-only permissions on auth.json"
);
}
let mut contents = String::new();
file.read_to_string(&mut contents)?;
@@ -289,6 +301,14 @@ pub(crate) fn backup_corrupt_auth_file(path: &Path) -> Option<PathBuf> {
match std::fs::rename(path, &backup) {
Ok(()) => {
// Corrupt backups still hold token material — keep them owner-only.
if let Err(e) = crate::util::secure_file::ensure_owner_only_permissions(&backup) {
tracing::warn!(
path = %backup.display(),
error = %e,
"auth: failed to tighten permissions on corrupt-auth backup"
);
}
tracing::warn!(
original = %path.display(),
backup = %backup.display(),
@@ -421,18 +441,59 @@ fn write_store_to(path: &Path, auth_store: &AuthStore) -> std::io::Result<()> {
.into_inner()
.map_err(|e| e.into_error())?
.sync_all()?;
#[cfg(windows)]
{
crate::util::secure_file::set_windows_secure_permissions(path)?;
// `open_secure_file` mode bits apply only on create; tighten existing
// paths. Best-effort after durable content: a chmod-only failure must not
// look like a failed write — the in-place fallback restores the prior
// snapshot on any `write_store_to` Err, which would discard freshly
// written tokens. The load path re-tightens on the next read.
if let Err(e) = crate::util::secure_file::ensure_owner_only_permissions(path) {
tracing::warn!(
error = %e,
path = %path.display(),
"auth: failed to ensure owner-only permissions after write"
);
}
Ok(())
}
/// Atomic write: tmp + Windows-safe replace (see `util::fs::replace_file`).
fn write_auth_json_atomic(auth_file: &Path, auth_store: &AuthStore) -> std::io::Result<()> {
let tmp = auth_file.with_extension(format!("json.{}.tmp", std::process::id()));
write_store_to(&tmp, auth_store)?;
crate::util::fs::replace_file(&tmp, auth_file)
write_auth_json_atomic_with(auth_file, auth_store, write_store_to)
}
/// Inner of [`write_auth_json_atomic`] with the tmp-file writer injectable so
/// the torn-tmp-write path is unit-testable without real I/O faults.
fn write_auth_json_atomic_with(
auth_file: &Path,
auth_store: &AuthStore,
write: fn(&Path, &AuthStore) -> std::io::Result<()>,
) -> std::io::Result<()> {
// Unique per write (pid + monotonic seq): two concurrent in-process
// writers (e.g. background mint + proactive refresher) must not share
// one tmp path, or each can tear the other's half-written bytes.
static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let tmp = auth_file.with_extension(format!(
"json.{}.{}.tmp",
std::process::id(),
TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
));
if let Err(e) = write(&tmp, auth_store) {
// Reclaim the partial tmp; the unique name otherwise accumulates
// one orphan per failed write. `replace_file` cleans its own leg.
let _ = std::fs::remove_file(&tmp);
return Err(e);
}
crate::util::fs::replace_file(&tmp, auth_file)?;
// Re-assert on the final path (covers rename edge cases / FS quirks).
// Best-effort: the replace already published the new tokens.
if let Err(e) = crate::util::secure_file::ensure_owner_only_permissions(auth_file) {
tracing::warn!(
error = %e,
path = %auth_file.display(),
"auth: failed to ensure owner-only permissions after replace"
);
}
Ok(())
}
/// Non-atomic fallback: truncate and rewrite `auth.json` in place.
@@ -486,10 +547,7 @@ fn restore_prior_bytes(auth_file: &Path, bytes: &[u8]) -> std::io::Result<()> {
let mut file = open_secure_file(auth_file)?;
file.write_all(bytes)?;
file.sync_all()?;
#[cfg(windows)]
{
crate::util::secure_file::set_windows_secure_permissions(auth_file)?;
}
crate::util::secure_file::ensure_owner_only_permissions(auth_file)?;
Ok(())
}
@@ -804,7 +862,87 @@ mod write_fallback_tests {
);
}
/// Rollback after a failed write must keep the file owner-only (0o600).
/// An in-place rewrite over a pre-existing world-readable auth.json must
/// tighten it to 0o600 — `open_secure_file` mode bits apply only on
/// create, so truncating an existing loose file keeps its old mode. The
/// in-place path is the one that reuses the inode (the atomic path
/// replaces it with a fresh 0o600 temp file).
#[cfg(unix)]
#[test]
fn in_place_write_tightens_preexisting_world_readable_auth_json() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("auth.json");
std::fs::write(&path, b"{}").unwrap();
let mut loose = std::fs::metadata(&path).unwrap().permissions();
loose.set_mode(0o644);
std::fs::set_permissions(&path, loose).unwrap();
write_auth_json_in_place(&path, &sample_store()).unwrap();
let mode = std::fs::metadata(&path).unwrap().permissions().mode();
assert_eq!(
mode & 0o777,
0o600,
"in-place rewrite must tighten preexisting open perms"
);
}
/// Simulates a torn tmp write: partial bytes land at the target path,
/// then the write fails — the temp file must not be left behind.
fn fake_partial_write_then_fail(path: &Path, _: &AuthStore) -> std::io::Result<()> {
std::fs::write(path, b"{ torn")?;
Err(std::io::Error::from(std::io::ErrorKind::StorageFull))
}
/// A tmp write that fails partway must reclaim the temp file; the unique
/// tmp name otherwise accumulates one orphan per failed write.
#[test]
fn atomic_write_reclaims_tmp_when_store_write_fails() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("auth.json");
let err = write_auth_json_atomic_with(&path, &sample_store(), fake_partial_write_then_fail)
.unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::StorageFull);
let orphans: Vec<_> = std::fs::read_dir(dir.path())
.unwrap()
.filter_map(Result::ok)
.filter(|e| e.file_name().to_string_lossy().contains(".tmp"))
.collect();
assert!(
orphans.is_empty(),
"failed tmp write must not leave temp files behind: {orphans:?}"
);
}
/// The replace step failing (target path occupied by a directory) must
/// also leave no temp file — `replace_file` reclaims its tmp on failure.
#[test]
fn atomic_write_reclaims_tmp_when_replace_fails() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("auth.json");
std::fs::create_dir(&path).unwrap();
assert!(
write_auth_json_atomic(&path, &sample_store()).is_err(),
"replacing a directory must fail"
);
let orphans: Vec<_> = std::fs::read_dir(dir.path())
.unwrap()
.filter_map(Result::ok)
.filter(|e| e.file_name().to_string_lossy().contains(".tmp"))
.collect();
assert!(
orphans.is_empty(),
"failed replace must not leave temp files behind: {orphans:?}"
);
}
/// Rollback after a failed write must leave the file owner-only (0o600)
/// even when the file had loose permissions going in — the restore path
/// truncates the existing inode, which keeps its old mode unless
/// explicitly tightened.
#[cfg(unix)]
#[test]
fn in_place_restore_is_owner_only() {
@@ -812,9 +950,13 @@ mod write_fallback_tests {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("auth.json");
write_auth_json_in_place(&path, &sample_store()).unwrap();
let mut loose = std::fs::metadata(&path).unwrap().permissions();
loose.set_mode(0o644);
std::fs::set_permissions(&path, loose).unwrap();
let _ = write_auth_json_in_place_with(&path, &sample_store(), fake_truncate_then_fail);
let mode = std::fs::metadata(&path).unwrap().permissions().mode();
assert_eq!(mode & 0o777, 0o600, "restored file must stay 0o600");
assert_eq!(mode & 0o777, 0o600, "restored file must be 0o600");
}
}
@@ -112,6 +112,7 @@ pub(crate) async fn spawn_session_actor(
system_prompt_label: String,
compaction_mode: kigi_chat_state::CompactionMode,
compaction_verbatim_input: bool,
compaction_tool_choice: crate::util::config::CompactionToolChoice,
two_pass_enabled: bool,
buffering_settings: Option<BufferingSettings>,
origin_client: Option<crate::http::OriginClientInfo>,
@@ -1032,6 +1033,7 @@ pub(crate) async fn spawn_session_actor(
previous_model: std::cell::Cell::new(None),
compaction_mode,
verbatim_input: compaction_verbatim_input,
tool_choice: compaction_tool_choice,
prefire: crate::session::compaction_config::PrefireState::default(),
prefix_released: std::sync::atomic::AtomicBool::new(false),
},
@@ -1535,6 +1537,7 @@ pub(crate) async fn spawn_session_on_thread(
system_prompt_label: String,
compaction_mode: kigi_chat_state::CompactionMode,
compaction_verbatim_input: bool,
compaction_tool_choice: crate::util::config::CompactionToolChoice,
two_pass_enabled: bool,
buffering_settings: Option<BufferingSettings>,
origin_client: Option<crate::http::OriginClientInfo>,
@@ -1636,10 +1639,23 @@ pub(crate) async fn spawn_session_on_thread(
};
(initial_last_compaction, initial_prompt_texts)
};
let rt = tokio::runtime::Builder::new_current_thread()
// Runtime construction acquires fds (epoll/kqueue, waker) and
// fails with EMFILE/EAGAIN under resource pressure — report
// through the init channel instead of panicking the thread.
let rt = match tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("session runtime");
{
Ok(rt) => rt,
Err(e) => {
tracing::error!(
error = %e,
"failed to build session runtime (resource exhaustion?)"
);
let _ = init_tx.send(Err(kigi_agent::AgentBuildError::RuntimeBuild(e)));
return;
}
};
let local = tokio::task::LocalSet::new();
local.block_on(&rt, async move {
let _trace_span = parent_traceparent.as_ref().map(|tp| {
@@ -1679,6 +1695,7 @@ pub(crate) async fn spawn_session_on_thread(
system_prompt_label,
compaction_mode,
compaction_verbatim_input,
compaction_tool_choice,
two_pass_enabled,
buffering_settings,
origin_client,
@@ -1759,8 +1776,19 @@ pub(crate) async fn spawn_session_on_thread(
}));
let _ = session_done_rx.await;
});
})
.expect("spawn session thread");
});
let join_handle = match join_handle {
Ok(handle) => handle,
Err(e) => {
tracing::error!(
error = %e,
"failed to spawn session thread (thread/PID limit or memory pressure?)"
);
return Err(
acp::Error::internal_error().data(format!("failed to spawn session thread: {e}"))
);
}
};
let init = init_rx
.await
.map_err(|_| {
@@ -157,6 +157,7 @@ async fn persist_ack_waits_for_disk_flush_before_success() {
previous_model: std::cell::Cell::new(None),
compaction_mode: kigi_chat_state::CompactionMode::Transcript,
verbatim_input: true,
tool_choice: Default::default(),
prefire: crate::session::compaction_config::PrefireState::default(),
prefix_released: std::sync::atomic::AtomicBool::new(false),
},
@@ -611,6 +612,7 @@ async fn first_turn_memory_injection_disabled_does_not_persist_to_chat_history()
previous_model: std::cell::Cell::new(None),
compaction_mode: kigi_chat_state::CompactionMode::Transcript,
verbatim_input: true,
tool_choice: Default::default(),
prefire: crate::session::compaction_config::PrefireState::default(),
prefix_released: std::sync::atomic::AtomicBool::new(false),
},
@@ -871,6 +873,7 @@ async fn cancel_running_task_teardown_clears_running_and_pending_work() {
previous_model: std::cell::Cell::new(None),
compaction_mode: kigi_chat_state::CompactionMode::Transcript,
verbatim_input: true,
tool_choice: Default::default(),
prefire: crate::session::compaction_config::PrefireState::default(),
prefix_released: std::sync::atomic::AtomicBool::new(false),
},
@@ -1865,6 +1868,7 @@ async fn cancel_propagates_to_sampler_handle_so_no_further_emission() {
previous_model: std::cell::Cell::new(None),
compaction_mode: kigi_chat_state::CompactionMode::Transcript,
verbatim_input: true,
tool_choice: Default::default(),
prefire: crate::session::compaction_config::PrefireState::default(),
prefix_released: std::sync::atomic::AtomicBool::new(false),
},
@@ -176,6 +176,7 @@ async fn test_e2e_idle_resume_refreshes_model_metadata() {
previous_model: std::cell::Cell::new(None),
compaction_mode: kigi_chat_state::CompactionMode::Transcript,
verbatim_input: true,
tool_choice: Default::default(),
prefire: crate::session::compaction_config::PrefireState::default(),
prefix_released: std::sync::atomic::AtomicBool::new(false),
},
@@ -112,6 +112,7 @@ async fn create_test_actor(
previous_model: std::cell::Cell::new(None),
compaction_mode: kigi_chat_state::CompactionMode::Transcript,
verbatim_input: true,
tool_choice: Default::default(),
prefire: crate::session::compaction_config::PrefireState::default(),
prefix_released: std::sync::atomic::AtomicBool::new(false),
},
@@ -539,6 +540,7 @@ async fn create_test_actor_with_memory(
previous_model: std::cell::Cell::new(None),
compaction_mode: kigi_chat_state::CompactionMode::Transcript,
verbatim_input: true,
tool_choice: Default::default(),
prefire: crate::session::compaction_config::PrefireState::default(),
prefix_released: std::sync::atomic::AtomicBool::new(false),
},
@@ -1298,6 +1300,7 @@ async fn test_e2e_idle_resume_refreshes_model_metadata() {
previous_model: std::cell::Cell::new(None),
compaction_mode: kigi_chat_state::CompactionMode::Transcript,
verbatim_input: true,
tool_choice: Default::default(),
prefire: crate::session::compaction_config::PrefireState::default(),
prefix_released: std::sync::atomic::AtomicBool::new(false),
},
@@ -163,6 +163,7 @@ async fn create_test_actor_with_memory(
previous_model: std::cell::Cell::new(None),
compaction_mode: kigi_chat_state::CompactionMode::Transcript,
verbatim_input: true,
tool_choice: Default::default(),
prefire: crate::session::compaction_config::PrefireState::default(),
prefix_released: std::sync::atomic::AtomicBool::new(false),
},
@@ -116,6 +116,7 @@ pub(super) async fn make_replay_send_update_fixture() -> ReplaySendUpdateFixture
previous_model: std::cell::Cell::new(None),
compaction_mode: kigi_chat_state::CompactionMode::Transcript,
verbatim_input: true,
tool_choice: Default::default(),
prefire: crate::session::compaction_config::PrefireState::default(),
prefix_released: std::sync::atomic::AtomicBool::new(false),
},
@@ -226,6 +226,7 @@ pub(crate) async fn create_test_actor_ex(
previous_model: std::cell::Cell::new(None),
compaction_mode: kigi_chat_state::CompactionMode::Transcript,
verbatim_input: true,
tool_choice: Default::default(),
prefire: crate::session::compaction_config::PrefireState::default(),
prefix_released: std::sync::atomic::AtomicBool::new(false),
},
@@ -212,6 +212,7 @@ impl SessionActor {
&sampling_config,
self.inference_idle_timeout,
wall_clock_budget_secs,
self.compaction.tool_choice,
)
.await
{
@@ -983,6 +984,7 @@ impl SessionActor {
sampling_config.clone(),
self.inference_idle_timeout,
wall_clock_budget_secs,
self.compaction.tool_choice,
);
let observer =
crate::session::helpers::full_replace_compaction::ShellFullReplaceObserver::new(
@@ -2198,6 +2200,7 @@ mod inline_auto_compact_flow_tests {
previous_model: std::cell::Cell::new(None),
compaction_mode: kigi_chat_state::CompactionMode::Transcript,
verbatim_input: true,
tool_choice: Default::default(),
prefire: crate::session::compaction_config::PrefireState::default(),
prefix_released: std::sync::atomic::AtomicBool::new(false),
},
@@ -146,6 +146,9 @@ pub struct CompactionConfig {
pub compaction_mode: kigi_chat_state::CompactionMode,
/// When `true`, feed the summarizer the verbatim conversation instead of the lossy rewrite (the retry loop may still fall back).
pub verbatim_input: bool,
/// `tool_choice` for summarizer requests with tools attached (`auto` |
/// `none`); some backends reject `"none"`.
pub tool_choice: crate::util::config::CompactionToolChoice,
/// Prefire two-pass state (background NOTE₁ cache + in-flight guard).
/// `Default` (empty cache, not in-flight).
pub prefire: PrefireState,
@@ -70,6 +70,8 @@ pub(crate) struct ShellCompactionSampler {
/// Wall-clock budget (secs) forwarded to `generate_session_compact` as the
/// reasoning-runaway backstop; `0` disables it.
wall_clock_budget_secs: u64,
/// Summarizer `tool_choice` forwarded to `generate_session_compact`.
tool_choice: crate::util::config::CompactionToolChoice,
/// Full output of the most recent successful sample (for L5 telemetry).
last_success: Mutex<Option<CompactOutput>>,
}
@@ -86,6 +88,7 @@ impl ShellCompactionSampler {
sampling_config: SamplingConfig,
idle_timeout: Duration,
wall_clock_budget_secs: u64,
tool_choice: crate::util::config::CompactionToolChoice,
) -> Self {
Self {
use_short_prompt,
@@ -97,6 +100,7 @@ impl ShellCompactionSampler {
sampling_config,
idle_timeout,
wall_clock_budget_secs,
tool_choice,
last_success: Mutex::new(None),
}
}
@@ -135,6 +139,7 @@ impl CompactionSampler for ShellCompactionSampler {
&self.sampling_config,
self.idle_timeout,
self.wall_clock_budget_secs,
self.tool_choice,
)
.await
{
@@ -339,9 +339,10 @@ where
/// prefix and force a full prefill on the summarizer call — attaching them
/// keeps the request prefix byte-identical to the turn requests so the
/// engine reuses the session's KV cache (the whole point of the verbatim
/// input path). Tool *use* is forbidden via `tool_choice: none` where the
/// backend can express it (ChatCompletions, Responses); the Messages wire
/// enum has no `none`, so that path relies on the prompt instruction alone.
/// input path). Tool *use* is forbidden by the prompt instruction;
/// `tool_choice` says what goes on the wire next to the attached tools
/// (ChatCompletions, Responses — some servers reject `"none"`, hence the
/// `auto` default). The Messages wire enum has no `none` either way.
///
/// Errors carry a [`CompactFailure`] classification so the caller can
/// short-circuit retries on deterministic failures (4xx schema violations,
@@ -356,8 +357,17 @@ pub(crate) async fn generate_session_compact(
sampling_config: &SamplingConfig,
idle_timeout: std::time::Duration,
wall_clock_budget_secs: u64,
tool_choice: crate::util::config::CompactionToolChoice,
) -> Result<CompactOutput, CompactFailure> {
let num_messages = chat_history.len();
let wire_tool_choice = match tool_choice {
crate::util::config::CompactionToolChoice::Auto => ToolChoice::auto(),
crate::util::config::CompactionToolChoice::None => ToolChoice::none(),
};
let conversation_tool_choice = match tool_choice {
crate::util::config::CompactionToolChoice::Auto => ConversationToolChoice::Auto,
crate::util::config::CompactionToolChoice::None => ConversationToolChoice::None,
};
let output = match sampling_config.api_backend {
ApiBackend::ChatCompletions => {
let chat_messages: Vec<ChatRequestMessage> =
@@ -373,7 +383,7 @@ pub(crate) async fn generate_session_compact(
.map(|t| ToolDefinition::function(t.name, t.description, t.parameters))
.collect(),
)
.with_tool_choice(ToolChoice::none());
.with_tool_choice(wire_tool_choice);
}
let sid = session_id.to_string();
message.x_kigi_conv_id = Some(sid.clone());
@@ -466,7 +476,10 @@ pub(crate) async fn generate_session_compact(
ApiBackend::Responses => {
let request = ConversationRequest {
items: chat_history,
tool_choice: (!tools.is_empty()).then_some(ConversationToolChoice::None),
// Hosted tools count: a hosted-only request with the choice
// omitted would leave the hosted tool callable mid-compact.
tool_choice: (!tools.is_empty() || !hosted_tools.is_empty())
.then_some(conversation_tool_choice),
tools,
hosted_tools,
model: Some(sampling_config.model.to_owned()),
@@ -1573,6 +1586,7 @@ mod reasoning_compaction_regression_tests {
&config,
std::time::Duration::from_secs(30),
0,
crate::util::config::CompactionToolChoice::Auto,
)
.await
.unwrap_or_else(|_| panic!("compaction must succeed"));
@@ -1661,6 +1675,7 @@ mod reasoning_compaction_regression_tests {
&config,
std::time::Duration::from_secs(30),
0,
crate::util::config::CompactionToolChoice::Auto,
)
.await;
let output = result
@@ -1669,11 +1684,11 @@ mod reasoning_compaction_regression_tests {
let _ = shutdown_tx.send(());
}
/// The compaction request must carry the turn loop's tool definitions
/// (prompt-prefix/KV-cache alignment) with `tool_choice: "none"`, and
/// must omit both keys when no tools are passed (Chat Completions rejects a bare
/// `tool_choice`).
/// (prompt-prefix/KV-cache alignment) with the configured `tool_choice`
/// (`auto` default; `none` when configured), and must omit both keys when
/// no tools are passed (Chat Completions rejects a bare `tool_choice`).
#[tokio::test]
async fn chat_completions_compaction_attaches_tools_with_tool_choice_none() {
async fn chat_completions_compaction_attaches_tools_with_configured_tool_choice() {
use std::sync::{Arc, Mutex};
let captured: Arc<Mutex<Vec<serde_json::Value>>> = Arc::new(Mutex::new(Vec::new()));
let cap = captured.clone();
@@ -1726,12 +1741,13 @@ mod reasoning_compaction_regression_tests {
&config,
std::time::Duration::from_secs(30),
0,
crate::util::config::CompactionToolChoice::Auto,
)
.await
.unwrap_or_else(|_| panic!("compaction with tools must succeed"));
let client = Client::new(config.clone()).unwrap();
generate_session_compact(
chat_history,
chat_history.clone(),
vec![],
vec![],
client,
@@ -1739,16 +1755,36 @@ mod reasoning_compaction_regression_tests {
&config,
std::time::Duration::from_secs(30),
0,
crate::util::config::CompactionToolChoice::Auto,
)
.await
.unwrap_or_else(|_| panic!("compaction without tools must succeed"));
let tools = vec![ToolSpec {
name: "read_file".to_string(),
description: Some("Reads a file".to_string()),
parameters: json!({ "type" : "object", "properties" : {} }),
}];
let client = Client::new(config.clone()).unwrap();
generate_session_compact(
chat_history,
tools,
vec![],
client,
acp::SessionId::new("test-session"),
&config,
std::time::Duration::from_secs(30),
0,
crate::util::config::CompactionToolChoice::None,
)
.await
.unwrap_or_else(|_| panic!("compaction with tool_choice none must succeed"));
let bodies = captured.lock().unwrap();
assert_eq!(bodies.len(), 2, "mock must have served both requests");
assert_eq!(bodies.len(), 3, "mock must have served all three requests");
let with_tools = &bodies[0];
assert_eq!(
with_tools["tool_choice"],
json!("none"),
"tool use must be disabled at decode time"
json!("auto"),
"default tool_choice is auto — some backends reject none; the prompt forbids tool use"
);
let sent_tools = with_tools["tools"]
.as_array()
@@ -1764,6 +1800,12 @@ mod reasoning_compaction_regression_tests {
without_tools.get("tool_choice").is_none(),
"tool_choice without tools is rejected by OpenAI-compat backends"
);
let none_configured = &bodies[2];
assert_eq!(
none_configured["tool_choice"],
json!("none"),
"configured none must reach the wire"
);
let _ = shutdown_tx.send(());
}
#[tokio::test]
@@ -1802,6 +1844,7 @@ mod reasoning_compaction_regression_tests {
&config,
std::time::Duration::from_millis(150),
0,
crate::util::config::CompactionToolChoice::Auto,
)
.await;
match result {
@@ -1869,6 +1912,7 @@ mod reasoning_compaction_regression_tests {
&config,
std::time::Duration::from_millis(150),
0,
crate::util::config::CompactionToolChoice::Auto,
)
.await;
match result {
@@ -1940,6 +1984,7 @@ mod reasoning_compaction_regression_tests {
&config,
std::time::Duration::from_millis(150),
0,
crate::util::config::CompactionToolChoice::Auto,
)
.await;
match result {
@@ -2008,6 +2053,7 @@ mod reasoning_compaction_regression_tests {
&config,
std::time::Duration::from_millis(150),
0,
crate::util::config::CompactionToolChoice::Auto,
)
.await;
match result {
@@ -8,13 +8,66 @@ use tokio::time;
use crate::terminal::runner::{
AsyncTerminalRunner, TerminalError, TerminalRunRequest, TerminalRunResult,
};
use kigi_tty_utils::KILL_REAP_TIMEOUT;
pub struct LocalTerminalRunner;
async fn read_stream(mut stream: impl AsyncReadExt + Unpin) -> Vec<u8> {
let mut buffer = Vec::new();
let _ = stream.read_to_end(&mut buffer).await;
buffer
/// A pipe reader whose buffer is shared with the spawner, so bytes read
/// before an abort are not lost with the task.
struct PipeReader {
task: tokio::task::JoinHandle<()>,
buffer: std::sync::Arc<std::sync::Mutex<Vec<u8>>>,
}
impl PipeReader {
fn spawn(mut stream: impl AsyncReadExt + Unpin + Send + 'static) -> Self {
let buffer = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let task_buffer = std::sync::Arc::clone(&buffer);
let task = tokio::spawn(async move {
let mut chunk = [0u8; 8192];
loop {
match stream.read(&mut chunk).await {
Ok(0) | Err(_) => break,
Ok(n) => Self::lock_buffer(&task_buffer).extend_from_slice(&chunk[..n]),
}
}
});
Self { task, buffer }
}
/// Never panics: a poisoned lock just means a holder panicked mid-append —
/// the buffer is plain bytes and stays consistent, so recover it.
fn lock_buffer(buffer: &std::sync::Mutex<Vec<u8>>) -> std::sync::MutexGuard<'_, Vec<u8>> {
buffer
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn take_buffer(self) -> Vec<u8> {
std::mem::take(&mut Self::lock_buffer(&self.buffer))
}
/// Wait for EOF (pipe closed by all writers) at most [`KILL_REAP_TIMEOUT`],
/// then return everything read so far.
///
/// Callers only join after the child was reaped or killed, so EOF is
/// normally immediate; the bound is a backstop for writers that outlive
/// the command and keep the pipe open — a background descendant
/// (`printf hi; sleep 30 &`) or a process wedged in uninterruptible
/// kernel I/O (D-state), which not even SIGKILL moves.
async fn join_bounded(mut self) -> Vec<u8> {
if time::timeout(KILL_REAP_TIMEOUT, &mut self.task)
.await
.is_err()
{
self.task.abort();
// Await the cancellation: abort() is asynchronous, and a reader
// past its await point could otherwise append between the take
// below and its own completion, losing those bytes.
let _ = (&mut self.task).await;
}
self.take_buffer()
}
}
/// Truncate buffer to keep only the last `limit` bytes (drops oldest bytes).
@@ -66,12 +119,35 @@ impl AsyncTerminalRunner for LocalTerminalRunner {
// Detach from the controlling terminal so child processes
// (e.g. GPG pinentry) cannot open /dev/tty and corrupt the TUI.
// (This also makes the child its own session/group leader, which the
// ProcessGroup attach below relies on.)
kigi_tools::util::detach_command(&mut cmd);
// process-group-killed on the request timeout; an unreapable (D-state)
// child is abandoned to the runtime's orphan reaper
let mut child = cmd
.spawn()
.map_err(|e| TerminalError::Other(format!("Failed to start shell: {e}")))?;
// Own the whole tree, not just the direct shell: on timeout the group
// is killed so grandchildren can't keep running (and can't hold the
// output pipes open past the kill). Group teardown is an enhancement
// over the direct-kill floor, so both enrollment failures degrade
// softly instead of dropping an already-running shell.
let process_group = match kigi_tty_utils::ProcessGroup::new() {
Ok(mut group) => {
if let Err(e) = group.attach(&child) {
// e.g. the child already exited.
tracing::debug!("ProcessGroup::attach failed: {e}");
}
Some(group)
}
Err(e) => {
tracing::warn!("Failed to create process group: {e}");
None
}
};
let stdout = child
.stdout
.take()
@@ -81,28 +157,46 @@ impl AsyncTerminalRunner for LocalTerminalRunner {
.take()
.ok_or_else(|| TerminalError::Other("Failed to capture stderr".into()))?;
let stdout_task = tokio::spawn(read_stream(stdout));
let stderr_task = tokio::spawn(read_stream(stderr));
let stdout_reader = PipeReader::spawn(stdout);
let stderr_reader = PipeReader::spawn(stderr);
let mut timed_out = false;
let wait_result = time::timeout(request.timeout, child.wait()).await;
let exit_status = match wait_result {
let exit_code = match wait_result {
Ok(status_res) => status_res
.map_err(|e| TerminalError::Other(format!("Failed to wait for process: {e}")))?,
.map_err(|e| TerminalError::Other(format!("Failed to wait for process: {e}")))?
.code(),
Err(_) => {
timed_out = true;
// Kill the direct child AND the whole group (grandchildren),
// then return the synthetic timeout result without waiting
// for the corpse: `timed_out: true` already tells the caller
// everything, and a D-state child would never become reapable
// anyway. Both kills are unconditional — `kill()` on a group
// whose attach failed is a silent no-op, so the direct
// `start_kill` is the guaranteed floor (same as
// `util/subprocess.rs`). The kills close the pipes, so the
// bounded joins below return immediately in the normal case;
// the abandoned child goes to tokio's orphan reaper.
if let Err(e) = child.start_kill() {
tracing::warn!("Failed to kill timed-out process: {e}");
}
child.wait().await.map_err(|e| {
TerminalError::Other(format!("Failed to wait for killed process: {e}"))
})?
if let Some(group) = &process_group
&& let Err(e) = group.kill()
{
tracing::warn!("Failed to kill timed-out process group: {e}");
}
None
}
};
let stdout_result = stdout_task.await.unwrap_or_else(|_| Vec::new());
let stderr_result = stderr_task.await.unwrap_or_else(|_| Vec::new());
// Join concurrently (worst case one reap bound, not one per pipe).
// Bounded on the natural-exit arm too: a background descendant that
// outlives the shell (`printf hi; sleep 30 &`) holds the pipes open
// past the child's exit, and an unbounded join stalls on it.
let (stdout_result, stderr_result) =
tokio::join!(stdout_reader.join_bounded(), stderr_reader.join_bounded());
let mut combined = stdout_result;
combined.extend(stderr_result);
@@ -112,7 +206,7 @@ impl AsyncTerminalRunner for LocalTerminalRunner {
Ok(TerminalRunResult {
combined_output,
exit_code: exit_status.code(),
exit_code,
truncated,
signal: None,
timed_out,
@@ -181,4 +275,56 @@ mod tests {
assert_eq!(result.combined_output.trim(), "hello");
assert_eq!(result.exit_code, Some(0));
}
/// Timing out a command whose grandchild inherited the output pipes must
/// (a) return promptly — before the group kill, the joins waited for the
/// grandchild's EOF (the full sleep here; forever for a writer wedged in
/// uninterruptible kernel I/O, the production incident this guards
/// against) — and (b) actually kill the grandchild via the group kill,
/// not merely stop waiting for it.
#[tokio::test]
#[cfg(unix)]
async fn test_timeout_kills_grandchildren_and_returns_promptly() {
let mut request = make_request("sleep 5 & echo bgpid=$!; sleep 5");
request.timeout = std::time::Duration::from_millis(300);
let started = std::time::Instant::now();
let result = LocalTerminalRunner.run(request).await.unwrap();
assert!(result.timed_out, "run should report the timeout");
// Prompt return: request timeout (0.3s) + pipe EOF from the group
// kill (normally instant; KILL_REAP_TIMEOUT-bounded worst case) —
// anything near the 5s sleeps means we waited for the grandchild.
assert!(
started.elapsed() < std::time::Duration::from_secs(4),
"timeout path must not wait for the killed tree (took {:?})",
started.elapsed()
);
// Outcome: the background grandchild must actually be dead, proving
// the group kill reached it. Poll briefly — the SIGKILL is delivered
// synchronously but init may reap the orphan a beat later.
let bg_pid = result
.combined_output
.lines()
.find_map(|l| l.trim().strip_prefix("bgpid="))
.and_then(|p| p.trim().parse::<u32>().ok())
.expect("background pid should have been echoed before the kill");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
loop {
let alive = std::process::Command::new("kill")
.args(["-0", &bg_pid.to_string()])
.status()
.map(|s| s.success())
.unwrap_or(false);
if !alive {
break;
}
assert!(
std::time::Instant::now() < deadline,
"background grandchild {bg_pid} survived the group kill"
);
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
}
}
@@ -33,6 +33,11 @@ pub(crate) fn ctx_with_toggle(toggle: HashMap<String, bool>) -> SubagentSpawnCon
let (tx, _rx) = mpsc::unbounded_channel();
SubagentSpawnContext {
lsp: None,
spawn_limits: kigi_tools::implementations::kigi::task::admission::SubagentLimits::default(),
spawn_permits: std::sync::Arc::new(tokio::sync::Semaphore::new(
kigi_tools::implementations::kigi::task::admission::SubagentLimits::default()
.effective_max_concurrent(),
)),
parent_max_turns: None,
gateway: test_gateway(),
client_hooks: Default::default(),
@@ -1,6 +1,42 @@
/// Default auto-compact threshold (% of context window) when no source sets it.
pub const DEFAULT_AUTO_COMPACT_THRESHOLD_PERCENT: u8 = 85;
/// `tool_choice` sent on compaction summarizer requests when tools are
/// attached (prefix-cache alignment keeps the tool definitions in the
/// request). Default `Auto` because some OpenAI-compatible servers reject
/// `tool_choice: "none"`; the summarization prompt itself forbids tool use.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CompactionToolChoice {
#[default]
Auto,
None,
}
impl std::str::FromStr for CompactionToolChoice {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim().to_ascii_lowercase().as_str() {
"auto" => Ok(Self::Auto),
"none" => Ok(Self::None),
_ => Err(()),
}
}
}
pub(crate) const ENV_COMPACTION_TOOL_CHOICE: &str = "KIGI_COMPACTION_TOOL_CHOICE";
pub(crate) fn resolve_compaction_tool_choice_from(
env: Option<&str>,
config: Option<&str>,
remote: Option<&str>,
) -> CompactionToolChoice {
env.and_then(|s| s.parse().ok())
.or_else(|| config.and_then(|s| s.parse().ok()))
.or_else(|| remote.and_then(|s| s.parse().ok()))
.unwrap_or_default()
}
/// Env-var override for `auto_compact_threshold_percent`. Parsed as `u8`;
/// out-of-range or unparseable values are ignored.
pub(crate) const ENV_AUTO_COMPACT_THRESHOLD_PERCENT: &str = "KIGI_AUTO_COMPACT_THRESHOLD_PERCENT";
@@ -127,6 +163,37 @@ pub fn resolve_compaction_wall_clock_budget_secs(gb_global: Option<u64>) -> u64
resolved
}
#[cfg(test)]
mod compaction_tool_choice_tests {
use super::{CompactionToolChoice, resolve_compaction_tool_choice_from as resolve};
#[test]
fn precedence_env_config_remote_default() {
assert_eq!(resolve(None, None, None), CompactionToolChoice::Auto);
assert_eq!(
resolve(None, None, Some("none")),
CompactionToolChoice::None
);
assert_eq!(
resolve(None, Some("auto"), Some("none")),
CompactionToolChoice::Auto
);
assert_eq!(
resolve(Some("none"), Some("auto"), Some("auto")),
CompactionToolChoice::None
);
// Unparseable tiers fall through instead of masking lower tiers.
assert_eq!(
resolve(Some("bogus"), None, Some("none")),
CompactionToolChoice::None
);
assert_eq!(
resolve(Some("NONE "), None, None),
CompactionToolChoice::None
);
}
}
#[cfg(test)]
mod compaction_wall_clock_budget_tests {
use super::resolve_compaction_wall_clock_budget_secs as resolve;
@@ -2653,7 +2653,7 @@ fn spawn_shell_command(
};
#[cfg(not(unix))]
let mut build_cmd = |with_breakaway: bool| {
let build_cmd = |with_breakaway: bool| {
use windows::Win32::System::Threading::{
CREATE_BREAKAWAY_FROM_JOB, CREATE_NEW_PROCESS_GROUP, CREATE_NO_WINDOW,
};
@@ -358,18 +358,20 @@ impl kigi_tool_runtime::Tool for GrepTool {
tracing::Span::current().record("wall_ms", started.elapsed().as_millis() as u64);
tracing::warn!(timeout_secs = timeout.as_secs(), "grep timed out");
let _ = child.start_kill();
let _ = child.wait().await;
crate::util::reap_killed_search_child(&mut child).await;
return Ok(grep_timeout_output(timeout.as_secs()));
}
};
// When `stdout_truncated`, `rg` is already killed (inside the timeout
// block, before the stderr drain); this only reaps it.
let status = child.wait().await.ok();
// Truncated output means `rg` was already killed (inside the timeout
// block, before the stderr drain) — bounded reap, and the exit code is
// defined as 0. A natural EOF means rg is exiting, so the plain wait
// is prompt.
let exit_code = if stdout_truncated {
crate::util::reap_killed_search_child(&mut child).await;
0
} else {
status.and_then(|s| s.code()).unwrap_or(-1)
child.wait().await.ok().and_then(|s| s.code()).unwrap_or(-1)
};
tracing::Span::current().record("early_kill", stdout_truncated);
@@ -529,7 +531,7 @@ fn grep_progress_stream(
tracing::warn!(timeout_secs = secs, "grep timed out");
});
let _ = child.start_kill();
let _ = child.wait().await;
crate::util::reap_killed_search_child(&mut child).await;
// Finalize what was read (marked truncated) plus an explicit
// notice, so the terminal card does not contradict what was already
// streamed; with nothing streamed, the timeout-only card suffices.
@@ -578,11 +580,14 @@ fn grep_progress_stream(
.await;
}
let status = child.wait().await.ok();
// Truncated output means `rg` was already killed above — bounded reap,
// and the exit code is defined as 0. A natural EOF means rg is
// exiting, so the plain wait is prompt.
let exit_code = if stdout_truncated {
crate::util::reap_killed_search_child(&mut child).await;
0
} else {
status.and_then(|s| s.code()).unwrap_or(-1)
child.wait().await.ok().and_then(|s| s.code()).unwrap_or(-1)
};
let wall_ms = stream_started.elapsed().as_millis() as u64;
@@ -0,0 +1,117 @@
//! Session-scoped subagent spawn limits, enforced by the shell's spawn path.
use crate::util::env::parse_positive_env;
pub const DEFAULT_MAX_CONCURRENT: usize = 32;
/// What happens to a spawn that arrives at the concurrent limit.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum LimitBehavior {
#[default]
Queue,
Fail,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SubagentLimits {
/// Subagents one session may run at once. Zero does not disable the
/// limit: [`Self::effective_max_concurrent`] clamps it to 1.
pub max_concurrent: usize,
pub behavior: LimitBehavior,
}
impl Default for SubagentLimits {
fn default() -> Self {
Self {
max_concurrent: DEFAULT_MAX_CONCURRENT,
behavior: LimitBehavior::Queue,
}
}
}
impl SubagentLimits {
/// Read once at the composition root; inject everywhere else.
pub fn from_env() -> Self {
Self::from_lookup(|var| std::env::var(var).ok())
}
/// A limit can be adjusted but never disabled.
fn from_lookup(lookup: impl Fn(&str) -> Option<String>) -> Self {
let default = Self::default();
let max_concurrent = parse_positive_env(
"KIGI_MAX_CONCURRENT_SUBAGENTS",
lookup("KIGI_MAX_CONCURRENT_SUBAGENTS"),
)
.unwrap_or(default.max_concurrent);
let behavior = match lookup("KIGI_SUBAGENT_LIMIT_BEHAVIOR") {
None => LimitBehavior::Queue,
Some(value) if value.eq_ignore_ascii_case("fail") => LimitBehavior::Fail,
Some(value) if value.eq_ignore_ascii_case("queue") => LimitBehavior::Queue,
Some(value) => {
tracing::warn!(
%value,
"KIGI_SUBAGENT_LIMIT_BEHAVIOR is neither `queue` nor `fail`; keeping `queue`"
);
LimitBehavior::Queue
}
};
Self {
max_concurrent,
behavior,
}
}
/// The semaphore size: a zero limit must still admit one child, or
/// queued spawns starve.
pub fn effective_max_concurrent(&self) -> usize {
self.max_concurrent.max(1)
}
}
#[cfg(test)]
mod tests {
use super::{LimitBehavior, SubagentLimits};
#[test]
fn limits_accept_plain_positive_digits_and_ignore_everything_else() {
let from = |concurrent: Option<&str>, behavior: Option<&str>| {
SubagentLimits::from_lookup(|var| {
match var {
"KIGI_MAX_CONCURRENT_SUBAGENTS" => concurrent,
"KIGI_SUBAGENT_LIMIT_BEHAVIOR" => behavior,
other => panic!("unexpected lookup: {other}"),
}
.map(str::to_owned)
})
};
assert_eq!(from(None, None), SubagentLimits::default());
assert_eq!(
from(Some("5"), Some("FAIL")),
SubagentLimits {
max_concurrent: 5,
behavior: LimitBehavior::Fail,
}
);
// Adjustable but never disabled: zero, negatives, non-digits,
// scientific notation, digit separators, and out-of-range values all
// keep defaults.
for ignored in ["0", "-1", "abc", "1e3", "20_000", "18446744073709551616"] {
assert_eq!(
from(Some(ignored), Some("nonsense")),
SubagentLimits::default(),
"value {ignored:?} should fall back to the defaults"
);
}
}
#[test]
fn a_zero_limit_is_clamped_to_one_not_disabled() {
let limits = SubagentLimits {
max_concurrent: 0,
behavior: LimitBehavior::Queue,
};
assert_eq!(limits.effective_max_concurrent(), 1);
assert_eq!(SubagentLimits::default().effective_max_concurrent(), 32);
}
}
@@ -12,6 +12,7 @@
//! - `SessionIdResource` — current session ID for parent scoping (optional)
//! - `TaskModelValidator` — validates explicit model slugs before spawn
pub mod admission;
pub mod backend;
pub mod types;
@@ -10,7 +10,7 @@ use crate::register_resource;
pub const MAX_URL_LENGTH: usize = 2_000;
pub const MAX_REDIRECTS: usize = 10;
pub const USER_AGENT_STRING: &str =
"Mozilla/5.0 (compatible; kigi-agent/1.0; +https://github.com/ZacharyZhang-NY/Kigi-CLI)";
"Mozilla/5.0 (compatible; kigi-agent/1.0; +https://kigicli.dev)";
/// Runtime-configurable parameters for the `web_fetch` tool.
///
@@ -161,7 +161,8 @@ impl kigi_tool_runtime::Tool for GlobTool {
.arg(&input.pattern)
.arg(&search_dir)
.stdout(Stdio::piped())
.stderr(Stdio::piped());
// stderr is never read; a pipe would block rg once warnings fill it.
.stderr(Stdio::null());
crate::util::detach_command(&mut cmd);
cmd.stdin(Stdio::null());
@@ -206,16 +207,13 @@ impl kigi_tool_runtime::Tool for GlobTool {
}
}
// Consume stderr to avoid deadlocks.
if let Some(stderr_pipe) = child.stderr.take() {
let _ = stderr_pipe
.take(1_000_000)
.read_to_end(&mut Vec::new())
.await;
if truncated_by_bytes {
// Bounded reap: a D-state rg must not stall this future forever.
crate::util::reap_killed_search_child(&mut child).await;
} else {
let _ = child.wait().await;
}
let _ = child.wait().await;
let stdout = String::from_utf8_lossy(&stdout_buf);
let mut truncated = truncated_by_bytes;
+21
View File
@@ -6,6 +6,27 @@
pub use kigi_tty_utils::{detach_from_tty, pager_env};
/// Parse a positive whole number in plain digits (no sign, no separators,
/// no scientific notation). `None` for zero or anything non-canonical.
pub fn parse_positive(value: &str) -> Option<u64> {
value.parse::<u64>().ok().filter(|&parsed| parsed > 0)
}
/// Parse a positive whole-number env value into a count. A set-but-invalid
/// value warns and reads as unset, so the caller's default applies.
pub fn parse_positive_env(var: &str, value: Option<String>) -> Option<usize> {
let value = value?;
let parsed = parse_positive(&value).and_then(|parsed| usize::try_from(parsed).ok());
if parsed.is_none() {
tracing::warn!(
var,
%value,
"env value is not a positive whole number in plain digits; using the default"
);
}
parsed
}
/// Env var set on agent-spawned terminal processes so host tools (e.g. `x ban`)
/// can distinguish agent invocations from human interactive shells.
/// Note: the CLI also uses `KIGI_AGENT` as an
@@ -29,6 +29,7 @@ pub use path_suggestions::format_not_found_error;
pub use remap::{remap_json_keys, remap_schema_properties, reverse_map};
pub use spawn::{
ProcessGroup, ProcessScope, detach_command, global_process_scope, new_process_group,
reap_killed_search_child,
};
pub use truncate::{
DEFAULT_SOFT_WRAP_WIDTH, ceil_char_boundary, estimate_tokens, floor_char_boundary,
@@ -8,3 +8,20 @@
pub use kigi_tty_utils::{
ProcessGroup, ProcessScope, detach_command, global_process_scope, new_process_group,
};
/// Reap an already-killed search child, bounded by
/// [`kigi_tty_utils::KILL_REAP_TIMEOUT`]; on `None` warn and leave the corpse
/// to tokio's orphan reaper.
pub async fn reap_killed_search_child(
child: &mut tokio::process::Child,
) -> Option<std::process::ExitStatus> {
let status =
kigi_tty_utils::reap_killed_bounded(child, kigi_tty_utils::KILL_REAP_TIMEOUT).await;
if status.is_none() {
tracing::warn!(
reap_timeout_secs = kigi_tty_utils::KILL_REAP_TIMEOUT.as_secs(),
"killed search child not reaped (bound expired — likely uninterruptible kernel I/O — or wait failed); abandoning to the orphan reaper"
);
}
status
}
+1 -1
View File
@@ -6,7 +6,7 @@ license = "Apache-2.0"
description = "Lightweight process-spawning utilities for TTY safety — detach from controlling terminal, suppress interactive pagers, process-group lifecycle"
[dependencies]
tokio = { workspace = true, features = ["process"] }
tokio = { workspace = true, features = ["process", "time"] }
[target.'cfg(unix)'.dependencies]
nix = { workspace = true, features = ["signal", "process"] }
+32 -1
View File
@@ -40,6 +40,7 @@ use std::collections::HashMap;
use std::io;
mod process_scope;
pub mod runtime;
pub use process_scope::{ProcessScope, global_process_scope};
// TTY detach — pre_exec building block
@@ -134,6 +135,36 @@ pub fn detach_std_command(cmd: &mut std::process::Command) {
// Process group lifecycle
/// Bound on waiting for an already-killed child (or its pipe readers) before
/// abandoning it.
///
/// A kill normally makes `child.wait()` resolve in milliseconds, but a child
/// wedged in an uninterruptible kernel syscall (D-state — e.g. a read on a
/// hard NFS mount whose server stopped responding) only observes the signal
/// when that syscall returns, which can be effectively never. Callers that
/// must not block (tool futures, turn loops) wait at most this long, then
/// abandon the corpse to the runtime's orphan reaper.
pub const KILL_REAP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
/// Reap an already-killed child, waiting at most `bound` (usually
/// [`KILL_REAP_TIMEOUT`]).
///
/// Returns the exit status when the child was reaped in time. `None` covers
/// both failure shapes — the bound expired (see [`KILL_REAP_TIMEOUT`]) and
/// `wait()` itself erred (e.g. the child was already reaped elsewhere) — the
/// caller's obligation is identical in either case: the kill signal is
/// already delivered, there is no status to report, and the corpse is left
/// to tokio's orphan reaper. Callers should log the `None` case.
pub async fn reap_killed_bounded(
child: &mut tokio::process::Child,
bound: std::time::Duration,
) -> Option<std::process::ExitStatus> {
match tokio::time::timeout(bound, child.wait()).await {
Ok(res) => res.ok(),
Err(_elapsed) => None,
}
}
/// Configure a command so the spawned child becomes the leader of a new
/// process group.
pub fn new_process_group(cmd: &mut tokio::process::Command) {
@@ -536,7 +567,7 @@ pub fn dup_tui_stderr() -> io::Result<std::fs::File> {
// `DuplicateHandle` — avoiding the `from_raw_handle` footgun
// where `File` would take ownership of the process stderr handle
// and close it on drop.
use std::os::windows::io::{AsRawHandle, FromRawHandle};
use std::os::windows::io::FromRawHandle;
let stderr_handle = unsafe {
windows::Win32::System::Console::GetStdHandle(
windows::Win32::System::Console::STD_ERROR_HANDLE,
@@ -0,0 +1,55 @@
//! Worker-thread policy for multi-thread tokio runtimes.
//!
//! Tokio defaults to one worker per core. On many-core shared hosts (100+-core
//! HPC login nodes) that pins 100+ thread slots per kigi process against
//! per-user ceilings — systemd user-slice `pids.max` (commonly 1000) or
//! `RLIMIT_NPROC` — and later thread spawns die with EAGAIN. Kigi's runtimes
//! are I/O-bound, so throughput does not scale with workers past a small
//! count.
//!
//! This is the single home for the cap policy; every multi-thread runtime in
//! the workspace derives its worker count from here so the policy cannot
//! drift across crates.
use std::num::NonZeroUsize;
/// Maximum runtime worker threads for any kigi process.
pub const MAX_WORKER_THREADS: NonZeroUsize = NonZeroUsize::new(8).unwrap();
/// Pure, testable: `min(cores, MAX_WORKER_THREADS)`.
pub fn cap_worker_threads(cores: NonZeroUsize) -> NonZeroUsize {
cores.min(MAX_WORKER_THREADS)
}
/// Reads the host: `min(available_parallelism, MAX_WORKER_THREADS)`.
pub fn capped_worker_threads() -> NonZeroUsize {
cap_worker_threads(std::thread::available_parallelism().unwrap_or(NonZeroUsize::MIN))
}
#[cfg(test)]
mod tests {
use super::*;
fn nz(n: usize) -> NonZeroUsize {
NonZeroUsize::new(n).unwrap()
}
#[test]
fn cap_is_identity_at_or_below_max() {
assert_eq!(cap_worker_threads(nz(1)), nz(1));
assert_eq!(cap_worker_threads(nz(4)), nz(4));
assert_eq!(cap_worker_threads(nz(8)), nz(8));
}
#[test]
fn cap_clamps_many_core_hosts() {
assert_eq!(cap_worker_threads(nz(9)), nz(8));
assert_eq!(cap_worker_threads(nz(360)), nz(8));
}
#[test]
fn capped_worker_threads_stays_in_bounds() {
let n = capped_worker_threads();
assert!(n <= MAX_WORKER_THREADS, "got {n}");
}
}
@@ -62,6 +62,7 @@ use super::session::lifecycle::{
clear_startup_actions, dispatch_agent_type_mismatch_answered, dispatch_exit_session,
dispatch_new_session, dispatch_new_session_inner, dispatch_new_session_with_id,
dispatch_new_worktree_session, dispatch_trust_folder, open_new_session_question,
skip_picker_and_create_session,
};
use super::session::load::{
dispatch_cycle_session_source_filter, dispatch_load_session, dispatch_pick_content_session,
@@ -749,7 +750,12 @@ pub(crate) fn dispatch(action: Action, app: &mut AppView) -> Vec<Effect> {
};
let Some(session_id) = agent.session.session_id.clone() else {
agent.session.deferred_model_switch = Some((model_id, effort));
return vec![];
// No session bound: with a create in flight this is a no-op
// and `SessionCreated` applies the stash; with none in flight
// (project question pending — only a plain prompt opens it) a
// switch would dangle forever, so start the session like the
// QueueCommand arm does for queued slash work.
return skip_picker_and_create_session(app, id);
};
agent.session.model_switch_pending = true;
vec![Effect::SwitchModel {
@@ -1519,12 +1519,20 @@ pub(in crate::app::dispatch) fn set_default_model(
effort: None,
prev_model_id: prev_id.clone(),
});
} else if let Some(agent) = app.agents.get_mut(&aid) {
// No session id yet — stash for
// `EventLoop::on_session_created` to apply once the session
// id materialises. Mirrors the deferred-switch handling in
// `Action::SwitchModel`.
agent.session.deferred_model_switch = Some((new_id, None));
} else {
if let Some(agent) = app.agents.get_mut(&aid) {
// No session id yet — stash for
// `EventLoop::on_session_created` to apply once the session
// id materialises. Mirrors the deferred-switch handling in
// `Action::SwitchModel`.
agent.session.deferred_model_switch = Some((new_id, None));
}
// With no create in flight (project question pending), the stash
// would dangle forever — start the session it drains into. No-op
// when a create is already pending.
effects.extend(
crate::app::dispatch::session::lifecycle::skip_picker_and_create_session(app, aid),
);
}
effects
}
@@ -481,7 +481,7 @@ fn session_failed_clears_flag_no_fetches() {
assert!(!app.agents[&id].pending_extensions_fetch);
}
#[test]
fn switch_model_without_session_does_nothing() {
fn switch_model_without_session_starts_the_session() {
let mut app = test_app_with_agent();
let id = AgentId(0);
app.agents.get_mut(&id).unwrap().session.session_id = None;
@@ -493,7 +493,14 @@ fn switch_model_without_session_does_nothing() {
},
&mut app,
);
assert!(effects.is_empty());
// No create was in flight, so the switch starts the session its stash
// drains into (the stash alone dangled forever — the /model-in-Downloads
// silent no-op). `model_switch_pending` flips on SessionCreated.
assert!(
effects
.iter()
.any(|e| matches!(e, Effect::CreateSession { .. }))
);
assert!(!app.agents[&id].session.model_switch_pending);
}
#[test]
@@ -668,11 +675,17 @@ fn switch_model_deferred_when_no_session_id() {
},
&mut app,
);
assert!(effects.is_empty());
// Stashed for SessionCreated — and the session it drains into is started
// (no create was in flight; a bare stash never drained).
assert_eq!(
app.agents[&id].session.deferred_model_switch,
Some((model_id, None))
);
assert!(
effects
.iter()
.any(|e| matches!(e, Effect::CreateSession { .. }))
);
assert!(!app.agents[&id].session.model_switch_pending);
}
#[test]
@@ -977,6 +977,77 @@ fn switch_model_pending_lifecycle() {
assert!(!app.agents[&id].session.model_switch_pending);
}
/// A model switch with no session AND no create in flight (the project-picker
/// question is pending; only a plain prompt can open it) must start the
/// deferred session itself, or the stashed switch dangles forever with zero
/// feedback — `/model X eff` in `~/Downloads` looked like "the model never
/// changes". Mirrors the `QueueCommand` arm: queued slash work bypasses the
/// picker and creates the session so the stash drains.
#[test]
fn switch_model_without_session_creates_the_deferred_session() {
let mut app = test_app_with_agent();
let id = AgentId(0);
app.agents.get_mut(&id).unwrap().session.session_id = None;
// Harness cwd is `/tmp` (a non-project dir); arm the picker gate the way
// startup leaves it (the harness pre-marks it shown for other tests).
app.project_picker_shown = false;
assert!(app.needs_project_picker());
let model_id = acp::ModelId::new(std::sync::Arc::from("kigi-4.5"));
let effects = dispatch(
Action::SwitchModel {
model_id: model_id.clone(),
effort: None,
},
&mut app,
);
assert_eq!(
app.agents[&id].session.deferred_model_switch,
Some((model_id, None)),
"switch must stay stashed for SessionCreated to apply"
);
assert!(
effects
.iter()
.any(|e| matches!(e, Effect::CreateSession { .. })),
"sessionless switch must start the session the stash drains into"
);
}
/// Same stash path while a create IS in flight (`mcp_init_progress` set):
/// no duplicate `CreateSession` — the pending create applies the stash.
#[test]
fn switch_model_with_create_in_flight_does_not_duplicate_create() {
let mut app = test_app_with_agent();
let id = AgentId(0);
{
let agent = app.agents.get_mut(&id).unwrap();
agent.session.session_id = None;
agent.mcp_init_progress = Some(crate::app::agent_view::McpInitProgress {
total: 0,
connected: 0,
started_at: std::time::Instant::now(),
});
}
let effects = dispatch(
Action::SwitchModel {
model_id: acp::ModelId::new(std::sync::Arc::from("kigi-4.5")),
effort: None,
},
&mut app,
);
assert!(app.agents[&id].session.deferred_model_switch.is_some());
assert!(
!effects
.iter()
.any(|e| matches!(e, Effect::CreateSession { .. })),
"an in-flight create must not be duplicated"
);
}
#[test]
fn no_deferred_switch_means_no_extra_effect() {
// When there is no deferred model switch, SessionCreated should
+5 -5
View File
@@ -813,11 +813,11 @@ pub(crate) mod win_native_selection {
let Ok(saved) = u32::try_from(saved) else {
return;
};
if let Some((handle, current)) = stdin_console_mode() {
if current != saved {
unsafe {
let _ = SetConsoleMode(handle, saved);
}
if let Some((handle, current)) = stdin_console_mode()
&& current != saved
{
unsafe {
let _ = SetConsoleMode(handle, saved);
}
}
}
+99 -12
View File
@@ -112,7 +112,8 @@ pub struct AddArgs {
#[arg(value_name = "ARGS")]
args: Vec<String>,
/// Transport type. Defaults to stdio.
/// Transport type. Defaults to stdio, or to http when the positional
/// argument is an http(s):// URL.
#[arg(short = 't', long, value_enum)]
transport: Option<McpTransport>,
@@ -273,11 +274,24 @@ async fn run_add(args: AddArgs) -> Result<()> {
/// Validate an `mcp add` request and build the transport config.
///
/// The transport flag fully determines how `command_or_url` is interpreted;
/// URL-looking commands only produce a warning, never a behavior change.
/// An explicit transport flag fully determines how `command_or_url` is
/// interpreted. Without one, a bare positional http(s):// URL is inferred to
/// be an HTTP server; other URL-looking commands stay stdio with a warning.
fn resolve_add(args: &AddArgs) -> Result<ResolvedAdd> {
validate_server_name(&args.name)?;
// Extra args or --env mean the user is describing a command, and the
// legacy --command/--url flags keep their own semantics, so only a bare
// positional http(s):// URL triggers inference.
let inferred_http = args.transport.is_none()
&& args.url.is_none()
&& args.args.is_empty()
&& args.env.is_empty()
&& args
.command_or_url
.as_deref()
.is_some_and(|s| s.starts_with("http://") || s.starts_with("https://"));
let transport = match args.transport {
Some(t) => t,
// The legacy --url form defaults to HTTP and honors the legacy --type flag.
@@ -285,6 +299,7 @@ fn resolve_add(args: &AddArgs) -> Result<ResolvedAdd> {
Some(t) if t.eq_ignore_ascii_case("sse") => McpTransport::Sse,
_ => McpTransport::Http,
},
None if inferred_http => McpTransport::Http,
None => McpTransport::Stdio,
};
let explicit_transport = args.transport.is_some();
@@ -391,6 +406,13 @@ fn resolve_add(args: &AddArgs) -> Result<ResolvedAdd> {
}
let headers = parse_headers(&args.header)?;
let mut warnings = Vec::new();
if inferred_http {
warnings.push(format!(
"No --transport given; '{url}' starts with http(s)://, adding as an HTTP server. Use --transport sse for an SSE server, or --transport stdio to force a stdio command."
));
}
Ok(ResolvedAdd {
kind: transport,
transport: McpServerTransportConfig::StreamableHttp {
@@ -402,7 +424,7 @@ fn resolve_add(args: &AddArgs) -> Result<ResolvedAdd> {
oauth_client_secret_env_var: None,
oauth_scopes: None,
},
warnings: Vec::new(),
warnings,
})
}
}
@@ -808,24 +830,89 @@ mod tests {
#[test]
fn add_default_transport_warns_on_url_looking_command() {
let add = parse_add(&["kigi", "mcp", "add", "api", "https://mcp.example.com/mcp"]);
let resolved = resolve_add(&add).expect("defaults to stdio with a warning");
// Scheme-less URL-looking commands stay stdio (no inference) and the
// warning suggests a command that passes URL validation verbatim.
let add = parse_add(&["kigi", "mcp", "add", "local", "localhost:3000"]);
let resolved = resolve_add(&add).expect("localhost command warns");
assert!(matches!(
resolved.transport,
McpServerTransportConfig::Stdio { .. }
));
assert_eq!(resolved.warnings.len(), 1);
assert!(resolved.warnings[0].contains("--transport http"));
// Scheme-less commands get http:// prepended so the suggested
// command passes URL validation verbatim.
let add = parse_add(&["kigi", "mcp", "add", "local", "localhost:3000"]);
let resolved = resolve_add(&add).expect("localhost command warns");
assert!(
resolved.warnings[0].contains("--transport http local http://localhost:3000"),
"got: {}",
resolved.warnings[0]
);
// Extra args mean a command is being described — no inference even
// with an http(s) scheme.
let add = parse_add(&[
"kigi",
"mcp",
"add",
"api",
"--",
"https://mcp.example.com/mcp",
"--flag",
]);
let resolved = resolve_add(&add).expect("URL with args stays stdio");
assert!(matches!(
resolved.transport,
McpServerTransportConfig::Stdio { .. }
));
}
#[test]
fn add_infers_http_for_bare_positional_url() {
for url in ["https://mcp.example.com/mcp", "http://mcp.example.com/mcp"] {
let add = parse_add(&["kigi", "mcp", "add", "api", url]);
let resolved = resolve_add(&add).expect("bare http(s) URL infers http");
assert_eq!(resolved.kind, McpTransport::Http);
match resolved.transport {
McpServerTransportConfig::StreamableHttp {
url: stored,
transport_type,
..
} => {
assert_eq!(stored, url);
assert_eq!(transport_type, None);
}
other => panic!("expected http transport, got {other:?}"),
}
assert_eq!(resolved.warnings.len(), 1);
assert!(
resolved.warnings[0].contains("No --transport given"),
"got: {}",
resolved.warnings[0]
);
}
}
#[test]
fn add_infers_http_with_headers() {
// Previously this bailed: stdio was assumed and --header is remote-only.
let add = parse_add(&[
"kigi",
"mcp",
"add",
"api",
"https://mcp.example.com/mcp",
"--header",
"Authorization: Bearer tok",
]);
let resolved = resolve_add(&add).expect("URL with headers infers http");
assert_eq!(resolved.kind, McpTransport::Http);
match resolved.transport {
McpServerTransportConfig::StreamableHttp { headers, .. } => {
let headers = headers.expect("headers should be set");
assert_eq!(
headers.get("Authorization").map(String::as_str),
Some("Bearer tok")
);
}
other => panic!("expected http transport, got {other:?}"),
}
}
#[test]
@@ -9,8 +9,9 @@ use crate::docs::{all_titles, find_doc};
use crate::slash::command::{AppCtx, ArgItem, CommandExecCtx, CommandResult, SlashCommand};
/// Online docs landing page (hardcoded like other TUI deep-links; the
/// project README is the docs entry point for the GitHub-hosted docs).
pub const BUILD_DOCS_URL: &str = "https://github.com/ZacharyZhang-NY/Kigi-CLI#readme";
/// project README is the docs entry point for the repo-hosted docs).
pub const BUILD_DOCS_URL: &str =
"https://git.zacharyzhang.com/ZacharyZhang-NY/Kigi-CLI/src/branch/main/README.md";
/// Open How-to Guides or online Build docs.
pub struct DocsCommand;
@@ -1,12 +1,13 @@
//! `/feedback` -- open the Kigi GitHub issues page.
//! `/feedback` -- open the Kigi issues page.
use crate::app::actions::Action;
use crate::slash::command::{CommandExecCtx, CommandResult, SlashCommand};
/// Where feedback goes: the project's own issue tracker. Kigi is a community
/// build, so its feedback belongs on its GitHub repo — mirroring the official
/// build, so its feedback belongs on its own repo — mirroring the official
/// kimi-cli, whose `/feedback` opens its repo's issues page.
pub const FEEDBACK_ISSUES_URL: &str = "https://github.com/ZacharyZhang-NY/Kigi-CLI/issues";
pub const FEEDBACK_ISSUES_URL: &str =
"https://git.zacharyzhang.com/ZacharyZhang-NY/Kigi-CLI/issues";
/// Open the Kigi issue tracker in the browser.
pub struct FeedbackCommand;
@@ -17,7 +18,7 @@ impl SlashCommand for FeedbackCommand {
}
fn description(&self) -> &str {
"Report feedback on the Kigi GitHub issues page"
"Report feedback on the Kigi issues page"
}
fn usage(&self) -> &str {
@@ -66,5 +66,6 @@ mod wheel_flood_paints_no_ghost_frames;
mod wheel_overscroll_at_bottom_reengages_follow_mid_stream;
#[path = "pty_e2e/wheel_scrolls_viewport_during_streaming_turn.rs"]
mod wheel_scrolls_viewport_during_streaming_turn;
#[cfg(unix)]
#[path = "pty_e2e/word_select_tip_on_double_click_pty.rs"]
mod word_select_tip_on_double_click_pty;
@@ -11,10 +11,12 @@ mod common;
#[path = "pty_e2e/scroll.rs"]
mod scroll;
#[cfg(unix)]
#[path = "pty_e2e/bash_mode_file_completion_shell_like.rs"]
mod bash_mode_file_completion_shell_like;
#[path = "pty_e2e/bash_mode_strips_redundant_session_cd_from_chrome.rs"]
mod bash_mode_strips_redundant_session_cd_from_chrome;
#[cfg(unix)]
#[path = "pty_e2e/bash_mode_tab_completion_dropdown.rs"]
mod bash_mode_tab_completion_dropdown;
#[path = "pty_e2e/edit_collapsed_oneliner_pty.rs"]
+12 -11
View File
@@ -29,17 +29,18 @@ const MSG_AUTO_UPDATE_BACKGROUND: &str = "Auto-update running in background.";
const MSG_RUN_UPDATE_MANUAL: &str = "Run `kigi update` to get the latest version.";
/// Manual-install one-liner for this platform's bootstrap installer
/// (install.sh / install.ps1 hosted at the repo root, PRD F8).
/// (install.sh / install.ps1, PRD F8). Served from kigicli.dev rather than the
/// repo host directly, so the published command survives a forge migration.
fn manual_install_cmd() -> &'static str {
if cfg!(windows) {
"irm https://raw.githubusercontent.com/ZacharyZhang-NY/Kigi-CLI/main/install.ps1 | iex"
"irm https://kigicli.dev/install.ps1 | iex"
} else {
"curl -fsSL https://raw.githubusercontent.com/ZacharyZhang-NY/Kigi-CLI/main/install.sh | sh"
"curl -fsSL https://kigicli.dev/install.sh | sh"
}
}
/// Build a reinstall hint for a known installer type. Every installer is
/// "internal" (GitHub Releases) today; the parameter survives so the hint
/// "internal" (the repo's Releases) today; the parameter survives so the hint
/// stays correct if another backend ever returns.
fn reinstall_hint(_installer: &str) -> String {
format!("Please reinstall via:\n {}", manual_install_cmd())
@@ -694,7 +695,7 @@ pub(crate) fn detect_platform() -> Result<(&'static str, &'static str)> {
/// Rust target triple for this build — the key that maps a platform to its
/// release-asset name. Must stay in lockstep with the five targets built by
/// `.github/workflows/release.yml` and the tables in install.sh/install.ps1.
/// `.gitea/workflows/release.yml` and the tables in install.sh/install.ps1.
pub(crate) fn target_triple() -> Result<&'static str> {
let triple = if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
"aarch64-apple-darwin"
@@ -2604,19 +2605,19 @@ mod tests {
// reinstall_hint / manual_install_cmd
#[test]
fn test_reinstall_hint_points_at_repo_install_script() {
fn test_reinstall_hint_points_at_published_install_script() {
let hint = reinstall_hint("internal");
if cfg!(windows) {
assert!(hint.contains("irm"), "should suggest irm install: {hint}");
assert!(
hint.contains("ZacharyZhang-NY/Kigi-CLI/main/install.ps1"),
"should reference the repo's install.ps1: {hint}"
hint.contains("kigicli.dev/install.ps1"),
"should reference the published install.ps1: {hint}"
);
} else {
assert!(hint.contains("curl"), "should suggest curl install: {hint}");
assert!(
hint.contains("ZacharyZhang-NY/Kigi-CLI/main/install.sh"),
"should reference the repo's install.sh: {hint}"
hint.contains("kigicli.dev/install.sh"),
"should reference the published install.sh: {hint}"
);
}
// Unknown installers fall back to the same hint.
@@ -2652,7 +2653,7 @@ mod tests {
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
#[test]
fn test_release_asset_name_matches_release_workflow_naming() {
// Must stay in lockstep with .github/workflows/release.yml, which
// Must stay in lockstep with .gitea/workflows/release.yml, which
// publishes kigi-<version>-<target-triple>.{tar.gz|zip}.
let triple = target_triple().unwrap();
assert!(
+13 -10
View File
@@ -8,9 +8,9 @@ use kigi_shell::util::kigi_home::kigi_home;
const TTL_SECONDS_BEFORE_AUTO_UPDATE: Duration = Duration::from_secs(60 * 30);
/// Release channel: this repo's GitHub Releases (PRD F8). The API base is
/// resolved through [`kigi_env::update_base_url`] — production default
/// `https://api.github.com/repos/ZacharyZhang-NY/Kigi-CLI/releases`,
/// Release channel: this repo's Releases (PRD F8). The API base is resolved
/// through [`kigi_env::update_base_url`] — production default
/// `https://git.zacharyzhang.com/api/v1/repos/ZacharyZhang-NY/Kigi-CLI/releases`,
/// overridable via `KIGI_UPDATE_BASE_URL` for mirrors and tests.
pub(crate) fn update_base_url() -> String {
kigi_env::update_base_url()
@@ -167,16 +167,19 @@ async fn fetch_github_json<T: serde::de::DeserializeOwned>(url: &str) -> Result<
/// Latest release for `channel` from a GitHub-Releases-shaped API at `base`.
///
/// - `stable` / `enterprise`: `GET {base}/latest` — GitHub's "latest" already
/// excludes drafts and pre-releases.
/// - `alpha`: `GET {base}?per_page=30` (newest first) and take the semver-max
/// non-draft entry. The list includes both pre-releases and stable
/// releases, so this preserves the max(alpha, stable) channel semantics —
/// alpha users are never stuck behind a newer stable.
/// - `stable` / `enterprise`: `GET {base}/latest` — "latest" already excludes
/// drafts and pre-releases on both GitHub and Gitea.
/// - `alpha`: `GET {base}?per_page=30&limit=30` (newest first) and take the
/// semver-max non-draft entry. The list includes both pre-releases and
/// stable releases, so this preserves the max(alpha, stable) channel
/// semantics — alpha users are never stuck behind a newer stable. GitHub
/// reads the page size from `per_page` and Gitea from `limit`; each ignores
/// the other's parameter, so sending both keeps one URL valid on either.
pub async fn fetch_latest_release_from_base(channel: &str, base: &str) -> Result<Release> {
let base = base.trim_end_matches('/');
if channel == "alpha" {
let releases: Vec<Release> = fetch_github_json(&format!("{base}?per_page=30")).await?;
let releases: Vec<Release> =
fetch_github_json(&format!("{base}?per_page=30&limit=30")).await?;
return releases
.into_iter()
.filter(|r| !r.draft)
@@ -114,7 +114,7 @@ pub fn host_platform() -> String {
}
/// Host Rust target triple, matching `auto_update::target_triple()` and the
/// release-asset naming in `.github/workflows/release.yml`.
/// release-asset naming in `.gitea/workflows/release.yml`.
pub fn host_triple() -> &'static str {
if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
"aarch64-apple-darwin"
@@ -224,11 +224,11 @@ impl ApprovedRoot {
{
return None;
}
return Some(OpenedRegularFile {
Some(OpenedRegularFile {
file,
path: canonical_path,
metadata,
});
})
}
#[cfg(not(any(unix, windows)))]
{
+137 -3
View File
@@ -1,10 +1,14 @@
# Release checklist (PRD F8)
Kigi ships as a single-file binary for five targets, published on this
repo's GitHub Releases by `.github/workflows/release.yml`. Users install via
repo's Gitea Releases by `.gitea/workflows/release.yml`. Users install via
`install.sh` / `install.ps1` and stay current through the in-app
self-updater (`kigi-update`), which resolves the same Releases API.
`.github/workflows/release.yml` is the retired GitHub pipeline. Gitea ignores
`.github/workflows` entirely whenever `.gitea/workflows` is non-empty, so it
does not run — it is kept only as a reference for the GitHub-hosted layout.
## Cutting a release
1. Bump `[workspace.package] version` in `Cargo.toml`; land the change on
@@ -30,16 +34,146 @@ self-updater (`kigi-update`), which resolves the same Releases API.
`release-dist` profile, packages
`kigi-<version>-<target-triple>.{tar.gz|zip}` archives (binary +
LICENSE + NOTICE + THIRD-PARTY-NOTICES), generates `SHA256SUMS`, and
publishes the GitHub Release. Tags containing `-` (e.g.
publishes the Gitea Release. Tags containing `-` (e.g.
`v0.2.0-alpha.1`) publish as pre-releases, which only the `alpha`
update channel picks up.
The release is created as a **draft** and only flipped public once
`SHA256SUMS` is attached, so `releases/latest` never hands the installer
a release whose checksum manifest is still missing. A failed run leaves
the draft in place; re-pushing the tag reuses it rather than erroring on
a duplicate `tag_name`.
5. Smoke-test an installed artifact:
```sh
curl -fsSL https://raw.githubusercontent.com/ZacharyZhang-NY/Kigi-CLI/main/install.sh | sh
curl -fsSL https://kigicli.dev/install.sh | sh
~/.kigi/bin/kigi --version
```
## Build runners
Gitea has no hosted runners, so all three `runs-on` labels below are machines
we register ourselves with `gitea-runner` (the binary formerly called
`act_runner`). Labels are declared in the runner's `config.yaml` as
`<label>:host` (run directly on the machine) or `<label>:docker://<image>` (run
in a container) — with `gitea-runner` v2, `register --labels` is ignored
whenever a config file supplies them.
| Label | Machine | Mode | Builds |
| ---------------- | ------------------------------ | ------ | -------------------------------------------------- |
| `ubuntu-latest` | the Dokploy box | docker | `x86_64-unknown-linux-gnu`, `aarch64-unknown-linux-gnu` |
| `macos-arm64` | Mac Mini (M4) | host | `aarch64-apple-darwin`, `x86_64-apple-darwin` |
| `windows-x86_64` | ZACHARYZHANG-PC | host | `x86_64-pc-windows-msvc` |
The Linux legs use `ubuntu-latest` because that is what the Dokploy box's
runner already advertises. That image is a bare runner-image, so those legs
provision their own apt packages and rustup per run (`rustup show` then picks
up the `rust-toolchain.toml` pin). If you register a dedicated
`linux-x86_64:docker://…` runner later, change the three Linux `runs-on`
values back to match it.
**The Mac is not optional.** Apple's SDK licence limits macOS builds to
Apple-branded hardware, and the Darwin targets need the real Apple linker
anyway (`.cargo/config.toml` passes `-ObjC` and `-undefined dynamic_lookup`).
There is no supported way to produce our macOS artifacts on the Linux server.
One Apple Silicon Mac covers both Darwin targets — `x86_64-apple-darwin` is a
cross-compile against the same SDK, exactly as the old GitHub `macos-14`
runner did it.
Windows is a softer requirement but still wants a real machine: the tree links
`ring`, `mimalloc`, `zstd-sys` and `libz-sys` against a static MSVC CRT
(`-C target-feature=+crt-static`). Cross-compiling that from Linux with
`cargo-xwin` is possible but means debugging four C builds under `clang-cl`;
a Windows runner with the VS 2022 C++ Build Tools reproduces today's binary
exactly.
Linux arm64 *is* cross-compiled on the x86_64 box — the workflow installs
`gcc-aarch64-linux-gnu` and points `cc-rs` at it. The one thing this loses is
the ability to smoke-test the arm64 binary before publishing (the old GitHub
pipeline did not test it either). Register a native arm64 runner and change
that matrix leg's `runner:` if you want it built natively.
### Registering a runner
Get a registration token from **Settings → Actions → Runners** (repo scope),
your user settings (all your repos) or the site admin panel (instance-wide).
Over the API it is a **POST**, not a GET — a GET is parsed as runner id `0` and
404s:
```sh
curl -fsS -X POST -H "Authorization: token $GITEA_API_TOKEN" \
https://git.zacharyzhang.com/api/v1/user/actions/runners/registration-token
```
Write the labels into `config.yaml` first (see `runner.labels` in
`gitea-runner generate-config`), then register on each machine:
```sh
# Linux (the Dokploy box) — container mode
gitea-runner --config config.yaml register --no-interactive \
--instance https://git.zacharyzhang.com \
--token <REGISTRATION_TOKEN> \
--name kigi-linux-x86_64
# macOS (Apple Silicon) — host mode, needs Xcode CLT + rustup + Node on PATH
gitea-runner --config config.yaml register --no-interactive \
--instance https://git.zacharyzhang.com \
--token <REGISTRATION_TOKEN> \
--name kigi-macos-arm64
# Windows — host mode, needs VS 2022 Build Tools + rustup + Node on PATH
gitea-runner --config config.yaml register --no-interactive `
--instance https://git.zacharyzhang.com `
--token <REGISTRATION_TOKEN> `
--name kigi-windows-x86_64
```
Host-mode runners execute steps with the daemon's own environment, so each
needs its build prerequisites installed up front — and the supervisor that
launches the daemon must put them on `PATH`:
- **macOS**: `xcode-select --install`, `rustup`, and Node (for
`actions/checkout`, which is a JavaScript action).
- **Windows**: VS 2022 Build Tools with the "Desktop development with C++"
workload, `rustup`, Git for Windows, and Node. Every Windows step in the
workflow uses `shell: powershell` (5.1) — never `bash`, which on a normal
Windows box resolves to WSL.
- **Linux (docker mode)**: nothing on the host — the workflow installs
`build-essential`, `jq`, `unzip`, protoc, rustup and the cross toolchain
inside the container per run.
### Keeping the runners alive
Each host-mode runner is supervised so it survives reboots and crashes. Both
supervisors export `CARGO_HOME`/`RUSTUP_HOME` and prepend the toolchain, git
and node directories to `PATH`, because host-mode jobs inherit exactly the
daemon's environment.
| Machine | Supervisor | Manage with |
| -------- | --------------------------------------------- | ------------------------------------------------------ |
| Windows | Task Scheduler task `Gitea Runner (Kigi)` running `C:\Users\zhang\gitea-runner\run-runner.ps1` | `Get-ScheduledTask`, `Start-ScheduledTask`, `Stop-ScheduledTask` |
| macOS | LaunchAgent `com.kigi.gitea-runner` (`KeepAlive`) | `launchctl kickstart -k gui/$(id -u)/com.kigi.gitea-runner` |
`prompt.txt` at the repo root is a one-shot setup prompt for the Mac Mini leg.
Both runners also expose a liveness probe on `http://127.0.0.1:9101/healthz`.
### Gitea-specific things that differ from GitHub
- Workflows live in `.gitea/workflows/`. Once that directory is non-empty,
`.github/workflows/` is ignored completely — you cannot run both.
- The automatic token is `secrets.GITEA_TOKEN`, and the release steps call the
Gitea API directly (`POST /releases`, `POST /releases/{id}/assets`,
`PATCH /releases/{id}`) rather than `softprops/action-gh-release`, which
targets GitHub's API and does not work here.
- `uses:` actions are fetched from `github.com` by default
(`DEFAULT_ACTIONS_URL`), so the runners need outbound access to it — our
GitHub *account* being suspended does not affect downloading public actions.
Absolute URLs (`uses: https://gitea.com/actions/checkout@v4`) work too.
- Artifacts carry only the five checksum lines; the archives themselves go
straight to the release. If `actions/upload-artifact@v3` misbehaves on the
instance, the fallback is to drop the artifact steps and have `publish`
download the archives from the release and hash them there.
## Invariants to keep in lockstep
- Asset naming `kigi-<version>-<target-triple>.{tar.gz|zip}` and the
+48
View File
@@ -0,0 +1,48 @@
# kigicli.dev
The Kigi landing site and the Worker that fronts it, deployed to Cloudflare as
the `kigi-frontend` Worker on `kigicli.dev` and `www.kigicli.dev`.
## Layout
| Path | What it is |
| --------------- | ----------------------------------------------------------------- |
| `worker/index.ts` | Worker entry point: installer proxy, `/health`, asset fallthrough |
| `wrangler.jsonc` | Deployment config (custom domains, assets binding, SPA fallback) |
| `dist/` | The built site served by the assets binding |
> **`dist/` is build output, not source.** It was recovered by mirroring the
> live `kigicli.dev` deployment — the original Vite/React project that produced
> these bundles is not in this repo. Content and copy changes therefore have to
> be made against the hashed `dist/assets/index-*.js` and `index-*.css` files
> directly. If the upstream source ever turns up, drop it in beside `dist/` and
> switch `wrangler.jsonc` to point at its build directory.
## Routes
Assets are matched first and served directly. Requests with no matching file
fall through to the Worker, which owns:
- `GET /install.sh` — proxies `install.sh` from the Kigi repo on Gitea
- `GET /install.ps1` — proxies `install.ps1` from the Kigi repo on Gitea
- `GET /health` — plain-text liveness check
- everything else — `env.ASSETS.fetch()`, which serves `index.html` for unknown
paths (single-page-application fallback)
The installer routes are proxied rather than linked so the published install
command (`curl -fsSL https://kigicli.dev/install.sh | bash`) stays stable no
matter where the repo is hosted. Responses are cached for 10 minutes at the
edge, so a push to `main` takes up to that long to show up.
Because assets win over the Worker, never add `install.sh` or `install.ps1` to
`dist/` — they would shadow the proxy routes.
## Deploy
```sh
npm install
npx wrangler deploy
```
Cloudflare Web Analytics injects its beacon `<script>` at the edge; that is why
`dist/index.html` does not contain one and must not have one added.
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
.hero-scene{transform-origin:50%;animation:hero-scene-in 1.2s var(--ease-out) both;position:absolute;inset:0;overflow:hidden;transform:scale(1.06)}.hero-scene canvas{width:100%;height:100%}@keyframes hero-scene-in{0%{opacity:0}to{opacity:1}}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loaded 100 of 138 files, more files were not shown because too many files have changed in this diff. Show more