@k-leumas/queque-cli 0.9.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,594 @@
1
+ # shellcheck shell=bash
2
+ # QueQue bash adapter: the literal `??` trigger for bash 5.0 or newer (readline `bind -x`).
3
+ #
4
+ # `qq init bash` adds a line to ~/.bashrc that sources this file. It binds `?` in the emacs and
5
+ # vi-insert keymaps. The first `?` inserts a literal `?` at the cursor at once; a second `?`
6
+ # right after it consumes the trigger, writes the line state to request.json in a private
7
+ # session dir and runs the unchanged `qq client`, which opens /dev/tty itself:
8
+ #
9
+ # reads READLINE_LINE / READLINE_POINT (split at the cursor into lbuffer / rbuffer)
10
+ # writes <session>/request.json {version, ttyPath, cwd, shellPid, lbuffer, rbuffer,
11
+ # shell:"bash", shellVersion}
12
+ # reads <session>/result.json cancel | replace-buffer | error
13
+ # writes READLINE_LINE / READLINE_POINT only; nothing runs until the user presses Enter.
14
+ #
15
+ # This file mirrors shell/zsh/queque.zsh (the reference adapter): the instant frame (plan
16
+ # 11-06), then the installed-tool handoff, the daemon prewarm and the Zellij floating pane
17
+ # (plan 11-07). Where bash differs (a detached tool scan with a `tools.pending` marker), the
18
+ # section comment says why.
19
+
20
+ # Non-interactive shells (scp, rsync, `bash -c`) read ~/.bashrc too: print nothing, change nothing.
21
+ [[ $- == *i* ]] || return 0 2>/dev/null || exit 0
22
+
23
+ # Only bash 3.2-parseable syntax above this point: macOS /bin/bash must reach the refusal.
24
+ if (( BASH_VERSINFO[0] < 5 )); then
25
+ printf 'queque: the ?? trigger needs bash 5.0+ (found %s)\n' "$BASH_VERSION" >&2
26
+ # shellcheck disable=SC2317 # reached when the file is run instead of sourced
27
+ return 0 2>/dev/null || exit 0
28
+ fi
29
+
30
+ # The accepted line is `cmd # explanation`: without this the `#` part becomes arguments
31
+ # (mirrors zsh `setopt interactivecomments`). The only option this file changes at source time.
32
+ shopt -s interactive_comments
33
+
34
+ # ---------------------------------------------------------------------------
35
+ # Helpers
36
+ # ---------------------------------------------------------------------------
37
+ # Every external tool is called through `command`: bash expands aliases when a function is
38
+ # defined, and the source line sits after the user's aliases (`alias rm='rm -i'`).
39
+
40
+ _qq_log() {
41
+ [[ -n ${QQ_DEBUG_LOG_FILE:-} ]] || return 0
42
+ printf '%s [bash] %s\n' "$(command date '+%Y-%m-%dT%H:%M:%S%z')" "$1" \
43
+ >>"$QQ_DEBUG_LOG_FILE" 2>/dev/null
44
+ return 0
45
+ }
46
+
47
+ # _qq_cleanup dir the adapter's half of the two-flag cleanup (D-05). The detached tool writer
48
+ # may still be scanning, so the adapter writes `closed` and removes the dir only once the
49
+ # writer's `tools.pending` marker is gone; otherwise the writer removes it when it sees
50
+ # `closed`. Each side sets its own flag before it checks the other's, so whichever finishes
51
+ # last removes the dir, and a second `rm -rf` is harmless. Every exit of `_qq_question` after
52
+ # the session dir exists goes through here.
53
+ _qq_cleanup() {
54
+ local dir=${1:-}
55
+ [[ -n $dir && -d $dir ]] || return 0
56
+ { : >"$dir/closed"; } 2>/dev/null
57
+ if [[ ! -e $dir/tools.pending ]]; then
58
+ command rm -rf -- "$dir" 2>/dev/null
59
+ fi
60
+ return 0
61
+ }
62
+
63
+ # Readline repaints only the last line of a multi-line prompt after a `bind -x` function
64
+ # printed something, so the leading lines would vanish under the summary. Print them here.
65
+ _qq_reprint_prompt_head() {
66
+ local p=${PS1@P}
67
+ # Drop the \[ \] markers (\001 \002) that only readline understands.
68
+ p=${p//$'\001'/}
69
+ p=${p//$'\002'/}
70
+ if [[ $p == *$'\n'* ]]; then
71
+ printf '%s\n' "${p%$'\n'*}"
72
+ fi
73
+ return 0
74
+ }
75
+
76
+ # Restore the line exactly as it was before the trigger, cursor included. zsh gets the cursor
77
+ # back by restoring LBUFFER and RBUFFER separately; bash needs the explicit point.
78
+ _qq_restore_line() {
79
+ READLINE_LINE="${QQ_ORIG_LBUFFER:-}${QQ_ORIG_RBUFFER:-}"
80
+ READLINE_POINT=${QQ_ORIG_POINT:-0}
81
+ }
82
+
83
+ # ---------------------------------------------------------------------------
84
+ # Instant first frame (D-04; quick 261011-jbh, LD-1)
85
+ # ---------------------------------------------------------------------------
86
+ # The moment `??` fires, the adapter paints the `queque › <lbuffer>` header and a `thinking…`
87
+ # row into the modal surface, before Node starts:
88
+ # inline `_qq_paint_inline_instant_frame` prints the scroll reserve, a fresh cursor save, an
89
+ # erase, the frame and a restore, so the cursor ends on the reserve top. The reserve is
90
+ # byte-identical to the client's inlineScrollReserve, so the client's own reserve
91
+ # moves nothing; the client clears the frame in its first visible write.
92
+ # Zellij `_qq_write_pane_instant_frame` writes the frame to `instant-frame.txt` in the 0700
93
+ # session dir, and the pane wrapper (`QQ_PANE_PAINT_SCRIPT`) cats it before it execs
94
+ # the unchanged client argv. The lbuffer never reaches the zellij or sh argv.
95
+ # The rows mirror Ink's loading frame: the header (only for a non-empty lbuffer), the FILTER
96
+ # row and the content margin (blank here), then the loading text. Control characters are
97
+ # stripped from the lbuffer before it reaches the terminal.
98
+ #
99
+ # The reference is src/shared/instant-frame-spec.ts. tests/instant-frame-parity.test.ts runs
100
+ # these functions and shell/zsh/queque.zsh against it byte for byte over a fixture table, so a
101
+ # change here needs the same change there. Builtins and parameter expansion only (no fork),
102
+ # every function returns 0, and QQ_INSTANT_FRAME=0 paints nothing.
103
+ # Plain globals, not readonly: the file is re-sourced in dev.
104
+ QQ_MODAL_VIEWPORT_LINES=18 # mirrors INSTANT_FRAME_VIEWPORT_LINES (spec)
105
+ QQ_MODAL_MAX_COLUMNS=80 # mirrors MODAL_MAX_COLUMNS (spec, CandidateSelect)
106
+ QQ_MODAL_PADDING_COLUMNS=1 # mirrors the Modal paddingX on each side
107
+ QQ_ZELLIJ_FRAME_COLUMNS=2 # mirrors the floating pane border columns
108
+ QQ_INSTANT_FRAME_ROWS_ABOVE_LOADING=2 # mirrors the FILTER row + the content marginTop
109
+ QQ_INSTANT_FRAME_LOADING_TEXT='thinking…' # mirrors INSTANT_FRAME_LOADING_TEXT (spec)
110
+ QQ_INSTANT_FRAME_FILE='instant-frame.txt' # mirrors INSTANT_FRAME_SPEC.frameFile
111
+ # shellcheck disable=SC2016 # the Zellij pane wrapper; /bin/sh expands it there
112
+ QQ_PANE_PAINT_SCRIPT='cat "$1" 2>/dev/null; shift; exec "$@"'
113
+ QQ_INSTANT_FRAME_PAINTED=${QQ_INSTANT_FRAME_PAINTED:-0}
114
+
115
+ # _qq_instant_frame lbuffer columns sets REPLY to the frame rows joined by CR LF (empty with
116
+ # QQ_INSTANT_FRAME=0). Columns that are not all digits, 0 or above the max mean the max.
117
+ _qq_instant_frame() {
118
+ REPLY=''
119
+ if [[ ${QQ_INSTANT_FRAME:-} == 0 ]]; then
120
+ return 0
121
+ fi
122
+ # Outside a UTF-8 locale (glibc images default to C) bash counts and slices bytes: the header
123
+ # would come out short (› and … are 3 bytes) and a typed multibyte character could be cut in
124
+ # half. Count characters in a UTF-8 locale for this function only (`local` restores it on
125
+ # return). If none exists the assignment changes nothing; its warning goes to /dev/null.
126
+ # `local` is a builtin, so its redirect covers it. A bare assignment ignores its own
127
+ # redirect, so the second one sits in a `{ }` group (WR-01).
128
+ local probe='›'
129
+ if (( ${#probe} != 1 )); then
130
+ local LC_ALL=C.UTF-8 2>/dev/null
131
+ if (( ${#probe} != 1 )); then
132
+ { LC_ALL=en_US.UTF-8; } 2>/dev/null
133
+ fi
134
+ fi
135
+ local lbuffer=${1//[[:cntrl:]]/}
136
+ local columns=${2:-}
137
+ if [[ $columns =~ ^0*([1-9][0-9]{0,2})$ ]] && (( BASH_REMATCH[1] <= QQ_MODAL_MAX_COLUMNS )); then
138
+ columns=${BASH_REMATCH[1]}
139
+ else
140
+ columns=$QQ_MODAL_MAX_COLUMNS
141
+ fi
142
+ local width=$(( columns - 2 * QQ_MODAL_PADDING_COLUMNS ))
143
+ if (( width < 1 )); then
144
+ width=1
145
+ fi
146
+ local pad dim=$'\e[2m' undim=$'\e[22m' crlf=$'\r\n' frame='' text i
147
+ printf -v pad '%*s' "$QQ_MODAL_PADDING_COLUMNS" ''
148
+ if [[ -n ${1:-} ]]; then
149
+ text="queque › ${lbuffer}"
150
+ if (( ${#text} > width )); then
151
+ text="${text:0:width-1}…"
152
+ fi
153
+ frame="${pad}${dim}${text}${undim}${crlf}"
154
+ fi
155
+ for (( i = 0; i < QQ_INSTANT_FRAME_ROWS_ABOVE_LOADING; i++ )); do
156
+ frame+=$crlf
157
+ done
158
+ REPLY="${frame}${pad}${dim}${QQ_INSTANT_FRAME_LOADING_TEXT}${undim}"
159
+ return 0
160
+ }
161
+
162
+ # _qq_inline_instant_frame_bytes lbuffer columns sets REPLY to the inline paint: the reserve
163
+ # (newlines, CSI <n> A, CR, ESC 7) + CSI J + the frame + ESC 8. Empty when the frame is empty.
164
+ _qq_inline_instant_frame_bytes() {
165
+ _qq_instant_frame "${1:-}" "${2:-}"
166
+ if [[ -z $REPLY ]]; then
167
+ return 0
168
+ fi
169
+ local frame=$REPLY newlines
170
+ printf -v newlines '%*s' "$QQ_MODAL_VIEWPORT_LINES" ''
171
+ # bash 5.2 turns `patsub_replacement` on by default: an unquoted `&` in the replacement part
172
+ # of ${var//pattern/replacement} stands for the matched text. Keep this replacement free of
173
+ # `&`, or the reserve stops being QQ_MODAL_VIEWPORT_LINES newlines.
174
+ newlines=${newlines// /$'\n'}
175
+ REPLY="${newlines}"$'\e['"${QQ_MODAL_VIEWPORT_LINES}A"$'\r\e7\e[J'"${frame}"$'\e8'
176
+ return 0
177
+ }
178
+
179
+ # _qq_paint_inline_instant_frame lbuffer prints the inline paint in one write when stdout is a
180
+ # terminal. QQ_INSTANT_FRAME_PAINTED=1 only when that write succeeded.
181
+ _qq_paint_inline_instant_frame() {
182
+ QQ_INSTANT_FRAME_PAINTED=0
183
+ if [[ ! -t 1 ]]; then
184
+ return 0
185
+ fi
186
+ _qq_inline_instant_frame_bytes "${1:-}" "${COLUMNS:-}"
187
+ if [[ -z $REPLY ]]; then
188
+ return 0
189
+ fi
190
+ if printf '%s' "$REPLY" 2>/dev/null; then
191
+ QQ_INSTANT_FRAME_PAINTED=1
192
+ fi
193
+ return 0
194
+ }
195
+
196
+ # _qq_clear_instant_frame erases a frame this adapter painted when the client will not (it
197
+ # was never started, or it exited non-zero): back to the paint's own save, erase below.
198
+ _qq_clear_instant_frame() {
199
+ if [[ $QQ_INSTANT_FRAME_PAINTED == 1 ]]; then
200
+ printf '\e8\e[J' 2>/dev/null
201
+ _qq_log "instant frame cleared"
202
+ fi
203
+ QQ_INSTANT_FRAME_PAINTED=0
204
+ return 0
205
+ }
206
+
207
+ # _qq_write_pane_instant_frame dir lbuffer pane_columns writes the frame + CSI H to
208
+ # dir/instant-frame.txt for the Zellij pane wrapper. A failed write removes the file, so a
209
+ # failure means "no file" and the pane launches as before.
210
+ _qq_write_pane_instant_frame() {
211
+ local dir=${1:-}
212
+ if [[ -z $dir || ! -d $dir ]]; then
213
+ return 0
214
+ fi
215
+ _qq_instant_frame "${2:-}" "${3:-}"
216
+ if [[ -z $REPLY ]]; then
217
+ return 0
218
+ fi
219
+ if ! { printf '%s' "${REPLY}"$'\e[H' >"$dir/$QQ_INSTANT_FRAME_FILE"; } 2>/dev/null; then
220
+ command rm -f -- "$dir/$QQ_INSTANT_FRAME_FILE" 2>/dev/null
221
+ fi
222
+ return 0
223
+ }
224
+
225
+ # ---------------------------------------------------------------------------
226
+ # Installed-tool handoff (D-05; zsh `_qq_write_tool_handoff`, spike 005)
227
+ # ---------------------------------------------------------------------------
228
+ # Writes the names bash can resolve into the session dir, next to request.json, so the client
229
+ # can flag candidates that use missing tools and steer the prompt to installed ones:
230
+ # commands.txt `compgen -c` (every command name bash resolves, PATH included)
231
+ # builtins.txt `compgen -b` (never flagged)
232
+ # functions.txt functions without a leading `_`, plus alias names (one file, 09 D-01)
233
+ # The scan costs about 85 ms in bash (8.8 ms in zsh), so it runs in a detached writer
234
+ # alongside client startup. `tools.pending` is the contract with src/client/tool-handoff.ts:
235
+ # the adapter creates it before the writer starts, the writer removes it last, and the client
236
+ # waits up to 500 ms while it exists. The names stay unordered: the client puts them in a Set.
237
+ # Never chain on compgen's exit status: `compgen -a` with no aliases and the public-function
238
+ # filter with only `_` functions both exit 1. Only an empty commands.txt removes the three files
239
+ # (failure means "no files", so the client shows no flags). Kill switch: QQ_TOOL_AWARENESS=0.
240
+
241
+ # _qq_write_tool_handoff dir the scan itself (synchronous; tests call it directly).
242
+ _qq_write_tool_handoff() {
243
+ local dir=${1:-}
244
+ if [[ ${QQ_TOOL_AWARENESS:-} == 0 || -z $dir || ! -d $dir ]]; then
245
+ return 0
246
+ fi
247
+ # Kept per D-05. It runs in the detached writer, where it only resets that subshell's
248
+ # table; compgen scans PATH itself, which is what lists a tool installed after the shell
249
+ # started (bash-widget b12 proves that, not this line).
250
+ hash -r 2>/dev/null
251
+ { compgen -c >"$dir/commands.txt"; } 2>/dev/null
252
+ { compgen -b >"$dir/builtins.txt"; } 2>/dev/null
253
+ { compgen -A function | command grep -v '^_'; compgen -a; } >"$dir/functions.txt" 2>/dev/null
254
+ if [[ ! -s $dir/commands.txt ]]; then
255
+ command rm -f -- "$dir/commands.txt" "$dir/builtins.txt" "$dir/functions.txt" 2>/dev/null
256
+ fi
257
+ return 0
258
+ }
259
+
260
+ # _qq_start_tool_handoff dir creates tools.pending, then starts the writer detached and
261
+ # returns at once. Only the `( … & )` subshell form is silent inside a `bind -x` function: a
262
+ # bare `&`, `& disown`, `set +m` or `wait` print `[1] PID` / `Done` into the user's terminal.
263
+ # The writer's own half of the two-flag cleanup: remove the marker, then remove the dir if the
264
+ # adapter already wrote `closed`.
265
+ _qq_start_tool_handoff() {
266
+ local dir=${1:-}
267
+ if [[ ${QQ_TOOL_AWARENESS:-} == 0 || -z $dir || ! -d $dir ]]; then
268
+ return 0
269
+ fi
270
+ if ! { : >"$dir/tools.pending"; } 2>/dev/null; then
271
+ return 0
272
+ fi
273
+ ( {
274
+ _qq_write_tool_handoff "$dir"
275
+ command rm -f -- "$dir/tools.pending"
276
+ if [[ -e $dir/closed ]]; then
277
+ command rm -rf -- "$dir"
278
+ fi
279
+ } </dev/null >/dev/null 2>&1 & )
280
+ return 0
281
+ }
282
+
283
+ # ---------------------------------------------------------------------------
284
+ # Daemon prewarm (zsh `_qq_prewarm_daemon`)
285
+ # ---------------------------------------------------------------------------
286
+ # Sourcing the adapter starts `qq daemon --ensure` once per shell in the background, so the
287
+ # first `??` pays less startup cost. QQ_DAEMON_PREWARMED=1 (set here, or by a harness before
288
+ # sourcing) skips it; a second source in the same shell keeps the 1.
289
+ QQ_DAEMON_PREWARMED=${QQ_DAEMON_PREWARMED:-0}
290
+
291
+ _qq_prewarm_daemon() {
292
+ if [[ $QQ_DAEMON_PREWARMED == 1 ]]; then
293
+ return 0
294
+ fi
295
+ QQ_DAEMON_PREWARMED=1
296
+ ( {
297
+ local qq_bin
298
+ if [[ -n ${QQ_DEV_ROOT:-} && -f ${QQ_DEV_ROOT}/dist/cli/main.js ]] \
299
+ && type -P node >/dev/null 2>&1; then
300
+ command node "${QQ_DEV_ROOT}/dist/cli/main.js" daemon --ensure
301
+ elif qq_bin=$(type -P qq 2>/dev/null) && [[ -n $qq_bin ]]; then
302
+ command "$qq_bin" daemon --ensure
303
+ fi
304
+ } </dev/null >/dev/null 2>&1 & )
305
+ return 0
306
+ }
307
+
308
+ # ---------------------------------------------------------------------------
309
+ # Zellij floating pane (D-07)
310
+ # ---------------------------------------------------------------------------
311
+ # With $ZELLIJ set, `_qq_question` runs the unchanged client in a floating pane and reads its
312
+ # one newline-terminated result line from a FIFO in the session dir. The FIFO read gives up
313
+ # after QQ_RESULT_READ_TIMEOUT_S (zsh reads for 30 s too; the client's IPC wait is 26 s), so a
314
+ # dead pane can never hang the shell. A launcher that exits non-zero writes the sentinel line
315
+ # into the FIFO, which wakes the read at once. `zellij` is called without `command` (as in zsh)
316
+ # so tests can fake it with a shell function.
317
+ QQ_RESULT_READ_TIMEOUT_S=30
318
+ QQ_ZELLIJ_LAUNCH_SENTINEL='QQ_LAUNCH_FAILED'
319
+
320
+ # ---------------------------------------------------------------------------
321
+ # Result application
322
+ # ---------------------------------------------------------------------------
323
+ # _qq_apply_result_str JSON applies a result to READLINE_LINE / READLINE_POINT.
324
+ # _qq_apply_result FILE reads a result file and delegates to the above.
325
+ #
326
+ # {"kind":"cancel"} restore, return 0
327
+ # {"kind":"replace-buffer","lbuffer":…,"rbuffer":…} summary, history, new line, return 0
328
+ # {"kind":"error","message":…} print message, restore, return 0
329
+ # anything else, unparsable JSON, empty lbuffer restore, return 1
330
+
331
+ _qq_apply_result_str() {
332
+ local json=${1:-} kind new_l new_r message
333
+ kind=$(printf '%s' "$json" | command jq -r '.kind // empty' 2>/dev/null) || kind=''
334
+
335
+ case $kind in
336
+ cancel)
337
+ _qq_restore_line
338
+ return 0
339
+ ;;
340
+ replace-buffer)
341
+ if ! new_l=$(printf '%s' "$json" | command jq -r '.lbuffer // empty' 2>/dev/null) \
342
+ || ! new_r=$(printf '%s' "$json" | command jq -r '.rbuffer // ""' 2>/dev/null) \
343
+ || [[ -z $new_l ]]; then
344
+ _qq_restore_line
345
+ return 1
346
+ fi
347
+ # Two summary lines above the prompt: the query (dim) and the command. Both go through
348
+ # %s, never into the format string.
349
+ if [[ -n ${QQ_ORIG_LBUFFER:-} ]]; then
350
+ printf '\e[38;5;240mqueque › %s\e[39m\n' "$QQ_ORIG_LBUFFER"
351
+ fi
352
+ printf '%s\n' "${new_l}${new_r}"
353
+ # D-13: the natural-language query goes into history; the command only once it is run.
354
+ if [[ -n ${QQ_ORIG_LBUFFER:-} ]]; then
355
+ history -s -- "$QQ_ORIG_LBUFFER"
356
+ fi
357
+ _qq_reprint_prompt_head
358
+ # Insertion only: the command is placed in the line, the user decides to press Enter.
359
+ READLINE_LINE="${new_l}${new_r}"
360
+ READLINE_POINT=${#new_l}
361
+ return 0
362
+ ;;
363
+ error)
364
+ message=$(printf '%s' "$json" | command jq -r '.message // empty' 2>/dev/null) || message=''
365
+ if [[ -n $message ]]; then
366
+ printf '%s\n' "$message"
367
+ fi
368
+ _qq_restore_line
369
+ return 0
370
+ ;;
371
+ *)
372
+ _qq_restore_line
373
+ return 1
374
+ ;;
375
+ esac
376
+ }
377
+
378
+ _qq_apply_result() {
379
+ local file=${1:-} json
380
+ if [[ -z $file || ! -r $file ]]; then
381
+ _qq_restore_line
382
+ return 1
383
+ fi
384
+ json=$(<"$file") || json=''
385
+ _qq_apply_result_str "$json"
386
+ }
387
+
388
+ # ---------------------------------------------------------------------------
389
+ # The `?` binding
390
+ # ---------------------------------------------------------------------------
391
+
392
+ _qq_question() {
393
+ # A user's `set -e` (or -u, -E, pipefail) must not kill the shell or leak out of here:
394
+ # `local -` restores the options when the function returns.
395
+ local -
396
+ set +euE +o pipefail
397
+
398
+ local lbuf=${READLINE_LINE:0:READLINE_POINT} rbuf=${READLINE_LINE:READLINE_POINT}
399
+
400
+ # First `?`: insert it at the cursor, no delay. READLINE_POINT counts characters (5.0+).
401
+ if [[ $lbuf != *\? ]]; then
402
+ READLINE_LINE="${lbuf}?${rbuf}"
403
+ READLINE_POINT=$(( READLINE_POINT + 1 ))
404
+ return 0
405
+ fi
406
+
407
+ # Second `?`: consume the trigger and remember the line and the cursor before the first `?`.
408
+ QQ_ORIG_LBUFFER=${lbuf%\?}
409
+ QQ_ORIG_RBUFFER=$rbuf
410
+ QQ_ORIG_POINT=$(( READLINE_POINT - 1 ))
411
+ READLINE_LINE="${QQ_ORIG_LBUFFER}${QQ_ORIG_RBUFFER}"
412
+ READLINE_POINT=$QQ_ORIG_POINT
413
+ QQ_INSTANT_FRAME_PAINTED=0
414
+ _qq_log "trigger fired lbuffer=${QQ_ORIG_LBUFFER} rbuffer=${QQ_ORIG_RBUFFER}"
415
+
416
+ # The client: the dev bundle when QQ_DEV_ROOT points at a built checkout, else qq on PATH
417
+ # (type -P searches PATH only, so a dev `qq` function cannot shadow the installed binary).
418
+ local -a qq_cmd
419
+ if [[ -n ${QQ_DEV_ROOT:-} && -f ${QQ_DEV_ROOT}/dist/cli/main.js ]]; then
420
+ qq_cmd=(node "${QQ_DEV_ROOT}/dist/cli/main.js")
421
+ else
422
+ local qq_bin
423
+ qq_bin=$(type -P qq 2>/dev/null) || qq_bin=''
424
+ if [[ -z $qq_bin ]]; then
425
+ _qq_log "qq not found"
426
+ printf '%s\n' 'queque: qq not found — run: qq init bash && source ~/.bashrc' >&2
427
+ return 0
428
+ fi
429
+ qq_cmd=("$qq_bin")
430
+ fi
431
+ _qq_log "qq_cmd=${qq_cmd[*]}"
432
+
433
+ # jq writes request.json and reads the result. Without it the request write fails after the
434
+ # paint, so check first and say why (WR-02). type -P, like `command jq`, ignores functions.
435
+ if ! type -P jq >/dev/null 2>&1; then
436
+ _qq_log "jq not found"
437
+ printf '%s\n' 'queque: jq not found — install jq (see: qq doctor)' >&2
438
+ return 0
439
+ fi
440
+
441
+ # Instant first frame (D-04): paint the header and the loading row now, before mktemp, jq
442
+ # and Node, so the modal shows something at once (zsh paints at the same point). The Zellij
443
+ # pane gets its frame through a file instead. QQ_ORIG_LBUFFER is this adapter's name for the
444
+ # value zsh paints as QQ_LBUFFER.
445
+ if [[ -z ${ZELLIJ:-} ]]; then
446
+ _qq_paint_inline_instant_frame "$QQ_ORIG_LBUFFER"
447
+ _qq_log "instant frame painted=${QQ_INSTANT_FRAME_PAINTED}"
448
+ fi
449
+
450
+ # A private session dir. Phase 10 Defect 3: an empty mktemp result (full or unwritable /tmp)
451
+ # must stop before any write, or every path below would land at the filesystem root.
452
+ local tmpdir
453
+ tmpdir=$(command mktemp -d /tmp/qq-sess.XXXXXX 2>/dev/null) || tmpdir=''
454
+ if [[ -z $tmpdir || ! -d $tmpdir ]]; then
455
+ _qq_clear_instant_frame
456
+ _qq_log "mktemp -d failed; session dir not created"
457
+ printf '%s\n' 'queque: cannot create a temp dir in /tmp' >&2
458
+ return 0
459
+ fi
460
+ command chmod 700 "$tmpdir"
461
+ _qq_log "tmpdir=${tmpdir}"
462
+
463
+ # request.json through jq --arg only, never string-built JSON. ttyPath is /dev/tty (no
464
+ # `tty` fork): the client opens the controlling terminal itself.
465
+ local req_file=$tmpdir/request.json
466
+ if ! command jq -n \
467
+ --arg tty /dev/tty --arg cwd "$PWD" --argjson pid "$$" \
468
+ --arg l "$QQ_ORIG_LBUFFER" --arg r "$QQ_ORIG_RBUFFER" --arg v "$BASH_VERSION" \
469
+ '{version:1, ttyPath:$tty, cwd:$cwd, shellPid:$pid, lbuffer:$l, rbuffer:$r, shell:"bash", shellVersion:$v}' \
470
+ >"$req_file" 2>/dev/null; then
471
+ _qq_clear_instant_frame
472
+ _qq_log "request.json could not be written"
473
+ _qq_cleanup "$tmpdir"
474
+ return 0
475
+ fi
476
+
477
+ # The tool scan runs alongside client startup (D-05); the client waits on tools.pending.
478
+ _qq_start_tool_handoff "$tmpdir"
479
+ _qq_log "tool handoff started"
480
+
481
+ # The client's stderr: QQ_DEBUG_LOG_FILE when a developer sets it, else a file in the 0700
482
+ # session dir that goes with it. Never a fixed /tmp name: `2>>` follows a symlink or blocks
483
+ # on a FIFO another local user could create there first (WR-04).
484
+ local qq_log_file=${QQ_DEBUG_LOG_FILE:-$tmpdir/client.err}
485
+
486
+ if [[ -n ${ZELLIJ:-} ]]; then
487
+ # ---- Zellij path (D-07): the client in a floating pane, the result through a FIFO ----
488
+ # No inline frame was painted on this path, so the setup failures below have nothing to
489
+ # clear; the pane frame file goes with the session dir.
490
+ local fifo=$tmpdir/result.fifo
491
+ if ! command mkfifo "$fifo" 2>/dev/null; then
492
+ _qq_log 'mkfifo failed'
493
+ _qq_restore_line
494
+ _qq_cleanup "$tmpdir"
495
+ return 0
496
+ fi
497
+ _qq_log "fifo=${fifo}"
498
+
499
+ # Read-write, opened before the pane starts: a plain `<"$fifo"` blocks in open() until a
500
+ # writer appears, so a pane that never starts would never let the read timeout begin.
501
+ # Holding the read end before the launch also keeps the sentinel from a launcher that
502
+ # fails at once (FIFO data is dropped when no end is open). The client writes one
503
+ # newline-terminated line, so `read` returns as soon as it lands.
504
+ local qq_fifo_fd
505
+ if ! { exec {qq_fifo_fd}<>"$fifo"; } 2>/dev/null; then
506
+ _qq_log 'fifo open failed'
507
+ _qq_restore_line
508
+ _qq_cleanup "$tmpdir"
509
+ return 0
510
+ fi
511
+
512
+ # The uncaughtException/unhandledRejection handlers in main.ts write a cancel result to
513
+ # QQ_RESULT_FILE even when an error escapes the client. `local -x`: the launcher and the
514
+ # pane inherit it, the user's shell does not keep a path into a deleted dir (WR-03).
515
+ local -x QQ_RESULT_FILE=$fifo
516
+
517
+ # Pane size: QQ_PANE_WIDTH / QQ_PANE_HEIGHT, default 80x24 (exported for the client, for
518
+ # this call only; a value the user exported is back as it was afterwards).
519
+ local qq_pane_width=${QQ_PANE_WIDTH:-80} qq_pane_height=${QQ_PANE_HEIGHT:-24}
520
+ local -x QQ_PANE_WIDTH=$qq_pane_width QQ_PANE_HEIGHT=$qq_pane_height
521
+
522
+ # Instant first frame (D-04): written to a file in the 0700 session dir; the pane wrapper
523
+ # cats it, then execs the unchanged client argv. A width that is not all digits (e.g. a
524
+ # percentage) falls back to the modal width.
525
+ local qq_frame_columns=0
526
+ if [[ $qq_pane_width =~ ^[0-9]+$ ]]; then
527
+ qq_frame_columns=$(( 10#$qq_pane_width - QQ_ZELLIJ_FRAME_COLUMNS ))
528
+ fi
529
+ _qq_write_pane_instant_frame "$tmpdir" "$QQ_ORIG_LBUFFER" "$qq_frame_columns"
530
+ local -a pane_cmd
531
+ if [[ -s $tmpdir/$QQ_INSTANT_FRAME_FILE ]]; then
532
+ pane_cmd=(/bin/sh -c "$QQ_PANE_PAINT_SCRIPT" queque-instant-frame
533
+ "$tmpdir/$QQ_INSTANT_FRAME_FILE" "${qq_cmd[@]}")
534
+ else
535
+ pane_cmd=("${qq_cmd[@]}")
536
+ fi
537
+ _qq_log "pane instant frame=${#pane_cmd[@]}"
538
+
539
+ # Launch detached and silent (the `( … & )` form). The launcher's copy of the read end is
540
+ # closed; `1<>` opens the FIFO without blocking, so the sentinel write never hangs.
541
+ ( {
542
+ exec {qq_fifo_fd}<&-
543
+ if ! zellij run --floating --close-on-exit --width "$qq_pane_width" --height "$qq_pane_height" \
544
+ --name qq -- "${pane_cmd[@]}" client --request-file "$req_file" --result-file "$fifo" \
545
+ 2>>"$qq_log_file"; then
546
+ { printf '%s\n' "$QQ_ZELLIJ_LAUNCH_SENTINEL" 1<>"$fifo"; } 2>/dev/null
547
+ fi
548
+ } </dev/null >/dev/null 2>&1 & )
549
+
550
+ local result=''
551
+ if ! IFS= read -r -t "$QQ_RESULT_READ_TIMEOUT_S" -u "$qq_fifo_fd" result; then
552
+ _qq_log "fifo read timed out"
553
+ result='{"kind":"cancel"}'
554
+ fi
555
+ exec {qq_fifo_fd}<&-
556
+ _qq_log "fifo read complete"
557
+
558
+ if [[ $result == "$QQ_ZELLIJ_LAUNCH_SENTINEL" ]]; then
559
+ _qq_log 'zellij run failed'
560
+ _qq_restore_line
561
+ _qq_cleanup "$tmpdir"
562
+ return 0
563
+ fi
564
+ _qq_apply_result_str "$result" || _qq_log "result not applied; line restored"
565
+ else
566
+ # ---- Inline path: the client runs as a foreground child and writes a result file ----
567
+ local result_file=$tmpdir/result.json
568
+ local -x QQ_RESULT_FILE=$result_file
569
+ local qq_client_status=0
570
+ command "${qq_cmd[@]}" client --request-file "$req_file" --result-file "$result_file" \
571
+ 2>>"$qq_log_file" || qq_client_status=$?
572
+ _qq_log "client status=${qq_client_status}"
573
+
574
+ # A client that crashed (before or after Ink) cannot clear the instant frame. One that
575
+ # exited 0 already cleared it in its first visible write.
576
+ if (( qq_client_status != 0 )); then
577
+ _qq_clear_instant_frame
578
+ fi
579
+
580
+ # A missing or malformed result keeps the original line and cursor.
581
+ _qq_apply_result "$result_file" || _qq_log "result not applied; line restored"
582
+ fi
583
+
584
+ _qq_cleanup "$tmpdir"
585
+ return 0
586
+ }
587
+
588
+ # Never `vi-command` (`?` searches history there) and never the two-key `??` sequence (a lone
589
+ # `?` would then wait for keyseq-timeout before it appears).
590
+ bind -m emacs -x '"?": _qq_question'
591
+ bind -m vi-insert -x '"?": _qq_question'
592
+
593
+ # Warm the daemon once per interactive shell (non-interactive shells returned at the top).
594
+ _qq_prewarm_daemon
@@ -412,6 +412,8 @@ qq-question-widget() {
412
412
  "ttyPath": $tty_json,
413
413
  "cwd": $cwd_json,
414
414
  "shellPid": $$,
415
+ "shell": "zsh",
416
+ "shellVersion": $(printf '%s' "$ZSH_VERSION" | jq -Rs .),
415
417
  "lbuffer": $(printf '%s' "$QQ_LBUFFER" | jq -Rs .),
416
418
  "rbuffer": $(printf '%s' "$QQ_RBUFFER" | jq -Rs .)
417
419
  }
@@ -432,13 +434,16 @@ JSON
432
434
 
433
435
  # Export FIFO path so uncaughtException/unhandledRejection handlers in main.ts
434
436
  # can write a cancel result even if the error escapes the Promise block.
435
- export QQ_RESULT_FILE="$fifo_path"
437
+ # `local -x`: the pane inherits it, the user's shell does not keep a path into a
438
+ # deleted session dir after the widget returns (WR-03).
439
+ local -x QQ_RESULT_FILE="$fifo_path"
436
440
 
437
441
  # Pane dimensions — override with QQ_PANE_WIDTH / QQ_PANE_HEIGHT (defaults 80×24).
442
+ # Exported for this call only; a value the user exported is back afterwards.
438
443
  local qq_pane_width="${QQ_PANE_WIDTH:-80}"
439
444
  local qq_pane_height="${QQ_PANE_HEIGHT:-24}"
440
- export QQ_PANE_WIDTH="$qq_pane_width"
441
- export QQ_PANE_HEIGHT="$qq_pane_height"
445
+ local -x QQ_PANE_WIDTH="$qq_pane_width"
446
+ local -x QQ_PANE_HEIGHT="$qq_pane_height"
442
447
 
443
448
  # Instant first frame (LD-1): the frame goes to a file in the 0700 session
444
449
  # dir; the pane wrapper cats it, then execs the unchanged client argv. A
@@ -456,11 +461,14 @@ JSON
456
461
  fi
457
462
  _qq_log "pane instant frame=${#pane_cmd[@]}"
458
463
 
459
- # Launch the floating pane backgrounded+disowned (D-06).
464
+ # Launch the floating pane backgrounded+disowned (D-06). Its stderr, like the
465
+ # inline client's, goes to QQ_DEBUG_LOG_FILE or else client.err in the 0700 session
466
+ # dir: never a fixed /tmp name another local user could pre-create as a symlink or a
467
+ # FIFO (WR-04).
460
468
  # Launch at config height; qq client shrinks the pane once content is rendered.
461
469
  zellij run --floating --close-on-exit --width "$qq_pane_width" --height "$qq_pane_height" --name "qq" -- \
462
470
  "${pane_cmd[@]}" client --request-file "$req_file" --result-file "$fifo_path" \
463
- 2>>"${QQ_DEBUG_LOG_FILE:-/tmp/qq-${UID}-debug.log}" &!
471
+ 2>>"${QQ_DEBUG_LOG_FILE:-$tmpdir/client.err}" &!
464
472
 
465
473
  # Block on FIFO read with a 30 s timeout (D-05).
466
474
  local result='{"kind":"cancel"}'
@@ -472,14 +480,14 @@ JSON
472
480
  else
473
481
  # ---- Inline path: foreground child writes to a regular temp file ----
474
482
  local result_file="$tmpdir/result.json"
475
- export QQ_RESULT_FILE="$result_file"
483
+ local -x QQ_RESULT_FILE="$result_file"
476
484
  _qq_log "inline mode result_file=${result_file}"
477
485
 
478
486
  # Run the client as a foreground child. ZLE yields the terminal so Ink
479
487
  # can open /dev/tty and render the selection UI inline.
480
488
  local qq_client_status=0
481
489
  "${qq_cmd[@]}" client --request-file "$req_file" --result-file "$result_file" \
482
- 2>>"${QQ_DEBUG_LOG_FILE:-/tmp/qq-${UID}-debug.log}" || qq_client_status=$?
490
+ 2>>"${QQ_DEBUG_LOG_FILE:-$tmpdir/client.err}" || qq_client_status=$?
483
491
 
484
492
  # A client that crashed (before or after Ink) cannot clear the instant
485
493
  # frame: restore the widget's own fresh save (the reserve top) and erase.