qs-ask: answer via Claude Code on the subscription, not an API key

No API key and no separate billing: qs-ask now shells out to `claude -p`,
which draws on the existing subscription already authenticated on this
host. The trade is latency — Claude Code boots a Node process per
question, ~6s measured against the raw API's ~1s — so the launcher now
races Wikipedia and Claude instead of chaining them. Wikipedia fills the
card in under a second and Claude supersedes it on arrival; chaining
would have left the card blank for six seconds on every question.

Isolation, verified: --safe-mode drops CLAUDE.md, skills, hooks, plugins
and MCP while leaving auth working, which matters for correctness and not
just speed — the global CLAUDE.md here asks for caveman-mode replies and
that would have leaked into answers. --no-session-persistence writes no
transcript, and a dedicated empty cwd keeps launcher questions out of any
project's history or auto-memory. Confirmed no project namespace, no
transcript and no memory write after a run.

Not --bare, which looks right and is a trap: its auth is strictly
ANTHROPIC_API_KEY, so it cannot use the subscription at all.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
rope 2026-08-01 17:34:50 +01:00
parent dbed82bab4
commit 309c54d31b
2 changed files with 72 additions and 64 deletions

View file

@ -61,76 +61,74 @@
done done
'') '')
# Instant-answer backend for the quickshell launcher on the desktops: # Instant-answer backend for the quickshell launcher on the desktops:
# `printf '%s' "question" | ssh mediaserver qs-ask`. The Anthropic key # `printf '%s' "question" | ssh mediaserver qs-ask`.
# lives here and nowhere else, so the desktops hold no credential and #
# there's a single place to rotate it. # Runs through Claude Code so it draws on fred's existing subscription —
# no API key, no separate billing. The trade is latency: Claude Code boots
# a Node process per question, so this takes ~6s against the raw API's
# ~1s. The launcher therefore shows its Wikipedia answer first and lets
# this one supersede it when it lands.
# #
# Reads the question from stdin — passing it as an ssh argv element would # Reads the question from stdin — passing it as an ssh argv element would
# send it through the remote shell for a second round of word splitting. # send it through the remote shell for a second round of word splitting.
# #
# Haiku 4.5 is the cheapest model and ample for a one-line factual # Every flag here is either isolation or trimming the invocation:
# answer: ~$0.0005 a query at $1/$5 per million input/output tokens. No # --safe-mode no CLAUDE.md, skills, hooks, plugins, MCP or
# `thinking` and no `effort` — `effort` errors on Haiku 4.5, and a # custom agents. Critical for correctness, not
# one-sentence fact needs no reasoning tokens. # just speed: fred's ~/.claude/CLAUDE.md tells
# Claude to answer in caveman mode, which would
# otherwise leak into launcher answers. Auth
# keeps working normally, which is what makes
# the subscription usable here.
# --no-session-persistence writes no transcript, so launcher questions
# never appear in /resume or any project history
# --tools "" no tools at all: nothing to load, and it
# cannot touch the filesystem or network
# --disable-slash-commands no skill resolution
# --strict-mcp-config ignore every MCP config (none supplied)
# --system-prompt replaces the full Claude Code system prompt
# with one line, rather than appending to it
# --permission-mode dontAsk never block waiting on a prompt nobody sees
# --model claude-haiku-4-5 smallest model — a one-line fact needs no more
# #
# Set the key up once (fred's own file, no sudo needed): # NOT --bare, which looks like the right flag and is a trap: it skips even
# mkdir -p ~/.config/anthropic # more, but its auth is "strictly ANTHROPIC_API_KEY or apiKeyHelper (OAuth
# printf '%s' sk-ant-... > ~/.config/anthropic/api-key # and keychain are never read)" — i.e. it cannot use the subscription.
# chmod 600 ~/.config/anthropic/api-key
# #
# STDOUT is the launcher's channel: the answer, or nothing at all on a # STDOUT is the launcher's channel: the answer, or nothing at all if the
# missing key, a failed call, or an UNKNOWN reply — silence is what the # call fails or the model doesn't know — silence is what the launcher
# launcher reads as "fall back to Wikipedia", so it must stay clean. # reads as "keep the Wikipedia answer". Every reason for that silence goes
# Every reason for that silence is reported on STDERR instead, which the # to STDERR instead, which the launcher discards and a human running
# launcher discards but a human running `qs-ask` by hand can read. # `qs-ask` by hand can read.
(pkgs.writeShellScriptBin "qs-ask" '' (pkgs.writeShellScriptBin "qs-ask" ''
q=$(${pkgs.coreutils}/bin/cat) q=$(${pkgs.coreutils}/bin/cat)
[ -z "$q" ] && { echo "qs-ask: no question on stdin" >&2; exit 0; } [ -z "$q" ] && { echo "qs-ask: no question on stdin" >&2; exit 0; }
key_file="$HOME/.config/anthropic/api-key"
[ -r "$key_file" ] || { echo "qs-ask: no readable key at $key_file" >&2; exit 0; }
key=$(${pkgs.coreutils}/bin/tr -d '\n' < "$key_file")
[ -z "$key" ] && { echo "qs-ask: key file is empty" >&2; exit 0; }
# Catches the classic paste-the-placeholder-literally mistake, which
# otherwise only shows up as an opaque 401.
case "$key" in
sk-ant-...|*...) echo "qs-ask: key file holds a placeholder, not a real key" >&2; exit 0 ;;
esac
# jq builds the body, so a question containing quotes or backslashes # Claude Code derives its project state (transcripts, auto-memory) from
# can't break out of the JSON string. # the working directory, so run from a dedicated empty one. Combined with
body=$(${pkgs.jq}/bin/jq -n --arg q "$q" '{ # --no-session-persistence and --safe-mode, a launcher question leaves no
model: "claude-haiku-4-5", # trace in the real projects' history or memory.
max_tokens: 300, work="$HOME/.cache/qs-ask"
system: "Answer the question in one or two short sentences, under 240 characters. Lead with the specific fact asked for, including units. No preamble, no caveats, no markdown, no follow-up offers. If you do not know, or the answer depends on live data you do not have, reply with exactly: UNKNOWN", ${pkgs.coreutils}/bin/mkdir -p "$work" || { echo "qs-ask: cannot create $work" >&2; exit 0; }
messages: [ { role: "user", content: $q } ] cd "$work" || { echo "qs-ask: cannot enter $work" >&2; exit 0; }
}')
# No -f here: a 4xx body carries the API's own error message, which is ans=$(printf '%s' "$q" | ${pkgs.claude-code}/bin/claude -p \
# far more useful on stderr than curl's exit code. Status is appended on --safe-mode \
# its own line so it can be split off the JSON. --no-session-persistence \
resp=$(${pkgs.curl}/bin/curl -s -w '\n%{http_code}' --max-time 10 \ --tools "" \
https://api.anthropic.com/v1/messages \ --disable-slash-commands \
-H 'content-type: application/json' \ --strict-mcp-config \
-H "x-api-key: $key" \ --permission-mode dontAsk \
-H 'anthropic-version: 2023-06-01' \ --output-format text \
--data-raw "$body") \ --model claude-haiku-4-5 \
|| { echo "qs-ask: request failed (network or timeout)" >&2; exit 0; } --system-prompt 'Answer the question in one or two short sentences, under 240 characters. Lead with the specific fact asked for, including units. No preamble, no caveats, no markdown, no follow-up offers. If you do not know, or the answer depends on live data you do not have, reply with exactly: UNKNOWN' \
2>/dev/null) \
|| { echo "qs-ask: claude exited non-zero (auth expired? run 'claude' once to log in)" >&2; exit 0; }
code=''${resp##*$'\n'} ans=$(printf '%s' "$ans" | ${pkgs.coreutils}/bin/tr -d '\r' | ${pkgs.gnused}/bin/sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
json=''${resp%$'\n'*}
if [ "$code" != 200 ]; then
printf 'qs-ask: HTTP %s %s\n' "$code" \
"$(printf '%s' "$json" | ${pkgs.jq}/bin/jq -r '.error.message // "no error message"')" >&2
exit 0
fi
ans=$(printf '%s' "$json" | ${pkgs.jq}/bin/jq -r '[.content[]? | select(.type == "text") | .text] | join(" ")')
# UNKNOWN or a refusal (empty content): stay quiet on stdout so the
# launcher's Wikipedia path answers instead.
case "$ans" in case "$ans" in
"" |null) echo "qs-ask: empty answer (refusal or no text block)" >&2; exit 0 ;; "") echo "qs-ask: empty answer" >&2; exit 0 ;;
UNKNOWN*) echo "qs-ask: model replied UNKNOWN" >&2; exit 0 ;; UNKNOWN*) echo "qs-ask: model replied UNKNOWN" >&2; exit 0 ;;
esac esac
printf '%s' "$ans" printf '%s' "$ans"

View file

@ -1709,6 +1709,9 @@ in
property string answerSource: "" property string answerSource: ""
property bool answerDropNext: false property bool answerDropNext: false
property bool askDropNext: false property bool askDropNext: false
// Claude answered the current query, so the slower-arriving
// Wikipedia result must not overwrite it.
property bool askWon: false
property var answerCache: ({}) property var answerCache: ({})
readonly property var answerStop: [ readonly property var answerStop: [
@ -1798,6 +1801,7 @@ in
answerTimer.stop(); answerTimer.stop();
killAnswer(); killAnswer();
killAsk(); killAsk();
askWon = false;
answerFact = ""; answerFact = "";
answerLead = ""; answerLead = "";
answerTitle = ""; answerTitle = "";
@ -1817,12 +1821,16 @@ in
showAnswer(hit); showAnswer(hit);
return; return;
} }
// Claude first it answers the questions Wikipedia // Both at once. Wikipedia fills the card in well under a
// can't. Silence from it means "no key, unreachable, or // second; Claude takes ~6s through Claude Code and
// doesn't know", and Wikipedia takes over. // supersedes it on arrival. Racing them beats chaining:
// Claude-then-fallback would leave the card blank for
// six seconds on every question.
askWon = false;
killAsk(); killAsk();
askProc.command = [Commands.askFetch, q]; askProc.command = [Commands.askFetch, q];
askProc.running = true; askProc.running = true;
startWiki();
} }
function startWiki() { function startWiki() {
@ -1834,10 +1842,8 @@ in
function takeAsk(raw) { function takeAsk(raw) {
if (askDropNext) { askDropNext = false; return; } if (askDropNext) { askDropNext = false; return; }
const text = raw.trim(); const text = raw.trim();
if (text === "") { // Nothing to add whatever Wikipedia found stands.
startWiki(); if (text === "") return;
return;
}
const res = { const res = {
title: "", // no article behind it title: "", // no article behind it
fact: text.slice(0, 400), fact: text.slice(0, 400),
@ -1848,6 +1854,7 @@ in
cacheAnswer(res); cacheAnswer(res);
// Typing may have moved on while the call was out. // Typing may have moved on while the call was out.
if (answerQuery !== answerKey(searchInput.text)) return; if (answerQuery !== answerKey(searchInput.text)) return;
askWon = true;
showAnswer(res); showAnswer(res);
} }
@ -1972,6 +1979,9 @@ in
: "https://en.wikipedia.org/wiki/" + encodeURIComponent(title.replace(/ /g, "_")), : "https://en.wikipedia.org/wiki/" + encodeURIComponent(title.replace(/ /g, "_")),
source: "Wikipedia" source: "Wikipedia"
}; };
// Claude already answered this query don't overwrite
// the better answer in the cache or on screen.
if (askWon) return;
cacheAnswer(res); cacheAnswer(res);
// Typing may have moved on while curl was out. // Typing may have moved on while curl was out.
if (answerQuery !== answerKey(searchInput.text)) return; if (answerQuery !== answerKey(searchInput.text)) return;