aboutsummaryrefslogtreecommitdiff
path: root/97-whatcmd.zsh
blob: aa41097ed7ab5c00d0ee28bc928d74fd5f4c42f3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
# opencode-command.plugin.zsh

_whatcmd_project_root() {
    emulate -L zsh

    local dir=$PWD
    local marker

    local -a markers=(
        .git
        .hg
        Cargo.toml
        go.mod
        pyproject.toml
        package.json
        dune-project
        CMakeLists.txt
        meson.build
        Makefile
        build.zig
        pom.xml
        build.gradle
        build.gradle.kts
        WORKSPACE
        WORKSPACE.bazel
        MODULE.bazel
        flake.nix
        mix.exs
        rebar.config
        cabal.project
        stack.yaml
        Gemfile
        composer.json
        AGENTS.md
    )

    while true; do
        for marker in $markers; do
            if [[ -e "$dir/$marker" ]]; then
                REPLY=$dir
                return 0
            fi
        done

        [[ $dir == / ]] && break
        dir=${dir:h}
    done

    REPLY=''
    return 1
}


#
# Describe the local environment to the command-generating agent.
#
_whatcmd_environment() {
    emulate -L zsh

    local os='unknown'
    local userland='unknown'
    local package_manager='unknown'
    local privilege='none'

    #
    # Distribution / OS.
    #
    if [[ -r /etc/os-release ]]; then
        local NAME='' PRETTY_NAME='' ID='' VERSION_ID=''

        . /etc/os-release

        os="${PRETTY_NAME:-${NAME:-${ID:-unknown}}}"
    elif [[ $OSTYPE == darwin* ]]; then
        os="macOS $(command sw_vers -productVersion 2>/dev/null)"
    else
        os="$(command uname -s 2>/dev/null)"
    fi

    #
    # Roughly identify the command-line userland.
    #
    if command ls --version >/dev/null 2>&1; then
        userland="$(command ls --version 2>/dev/null | head -n1)"
    elif (( $+commands[busybox] )); then
        userland="$(command busybox 2>&1 | head -n1)"
    elif [[ $OSTYPE == darwin* || $OSTYPE == *bsd* ]]; then
        userland='BSD-style userland'
    fi

    #
    # Prefer the native package manager.
    #
    local pm
    for pm in emerge dnf apt apt-get pacman zypper apk brew; do
        if (( $+commands[$pm] )); then
            package_manager=$pm
            break
        fi
    done

    #
    # This actually matters quite a bit for generated administrative
    # commands.
    #
    if (( $+commands[doas] )); then
        privilege=doas
    elif (( $+commands[sudo] )); then
        privilege=sudo
    fi

    print -r -- "OS: $os"
    print -r -- "Kernel: $(command uname -sr 2>/dev/null)"
    print -r -- "Architecture: $(command uname -m 2>/dev/null)"
    print -r -- "Shell: zsh $ZSH_VERSION"
    print -r -- "Userland: $userland"
    print -r -- "Package manager: $package_manager"
    print -r -- "Privilege command: $privilege"
    print -r -- "Current Id: $(id)"
    print -r -- "Working directory: $PWD"
}


#
# Public interface.
#
# Examples:
#
#   whatcmd find all files larger than 1GB
#   $(whatcmd get url of git origin)
#   whatcmd install imagemagick | wl-copy
#
whatcmd() {
    emulate -L zsh

    if (( $# == 0 )); then
        print -u2 -r -- 'usage: whatcmd <request>'
        return 2
    fi

    local request="$*"
    local environment="$(_whatcmd_environment)"

    local prompt
    prompt=$'The command will be run in this environment:\n'
    prompt+="$environment"
    prompt+=$'\n\n'
    prompt+="Request: $request"

    local project_root=''
    local permissions

    if _whatcmd_project_root; then
        project_root=$REPLY

        permissions='
            "*": "deny",
            "read": {
              "*": "allow",
              "*.env": "deny",
              "*.env.*": "deny",
              "*.env.example": "allow"
            },
            "glob": "allow",
            "grep": "allow",
            "external_directory": "deny"
    '
    else
        permissions='
            "*": "deny"
    '
    fi

    local opencode_config='
{
  "agent": {
    "whatcmd": {
      "description": "Generate exactly one shell command for a requested operation",
      "mode": "primary",

      "permission": {
        '"$permissions"'
      },

      "prompt": "You are a shell-command generator, not a conversational assistant.\n\nThe user describes an operation they want to perform. Your job is to output the zsh command they should run to perform that operation.\n\nNEVER perform the requested operation yourself.\nNEVER return the result of the requested operation.\nNEVER answer the request directly.\nALWAYS return a command that the user can run to obtain the requested result or perform the requested action.\n\nFor example:\n- Request: get the URL of the git origin\n  Output: git remote get-url origin\n\n- Request: find all executable files under the current directory\n  Output: find . -type f -executable\n\n- Request: show processes listening on TCP ports\n  Output: ss -ltnp\n\nYou may use read, glob, and grep ONLY when local project-specific information is necessary to determine which command should be run. Examples include:\n- compile this project\n- run this project tests\n- start this application\n- build the current package\n\nFor generic shell questions, do not inspect the filesystem.\n\nWhen you inspect a project, inspection is only evidence for choosing the command. Do not return information discovered during inspection as the answer.\n\nYou must never execute shell commands, modify files, access the network, invoke other agents, or perform the requested operation.\n\nYour final response must contain EXACTLY the shell command and nothing else.\nNo markdown.\nNo explanation.\nNo commentary.\nNo prefix or suffix."
    }
  }
}
'

    OPENCODE_CONFIG_CONTENT="$opencode_config" \
        command opencode run \
            --agent whatcmd \
            --format json \
            --thinking \
            "$prompt" |
        _whatcmd_demux

    local -a pipeline_status=("${pipestatus[@]}")

    # Preserve an OpenCode failure rather than just returning the
    # demuxer's status.
    (( pipeline_status[1] != 0 )) && return $pipeline_status[1]
    return $pipeline_status[2]
}

_whatcmd_demux() {
    emulate -L zsh

    local line type text tool target
    local final=''

    while IFS= read -r line; do
        type=$(jq -r '.type // empty' <<< "$line") || continue

        case "$type" in
            text)
                # Don't emit yet. The last completed text part is the
                # command we care about.
                final=$(jq -r '.part.text // empty' <<< "$line")
                ;;

            reasoning)
                text=$(
                    jq -r '
                        (.part.text // "")
                        | gsub("[\r\n\t]+"; " ")
                        | gsub("  +"; " ")
                    ' <<< "$line"
                )

                [[ -n $text ]] && print -u2 -r -- "⬤ $text"
                ;;

            tool_use)
                tool=$(jq -r '.part.tool // "tool"' <<< "$line")

                case "$tool" in
                    read)
                        target=$(
                            jq -r '
                                .part.state.input.filePath //
                                .part.state.input.path //
                                ""
                            ' <<< "$line"
                        )
                        print -u2 -r -- "󰈙 Reading ${target:t}"
                        ;;

                    glob)
                        print -u2 -r -- "󰱼 Looking through project files"
                        ;;

                    grep)
                        print -u2 -r -- "󰱼 Searching project"
                        ;;

                    *)
                        print -u2 -r -- "⚙ Using $tool"
                        ;;
                esac
                ;;

            error)
                text=$(
                    jq -r '
                        .error.data.message //
                        .error.message //
                        .error.name //
                        "OpenCode error"
                    ' <<< "$line"
                )
                print -u2 -r -- "✗ $text"
                ;;
        esac
    done

    [[ -n $final ]] && print -r -- "$final"
}

#
# Minibuffer highlighting
#
# This replaces all region_highlight entries immediately before every
# minibuffer redraw.  That prevents zsh-syntax-highlighting and
# fast-syntax-highlighting from leaking stale ranges into the recursive
# editor.
#
_opencode_minibuffer_pre_redraw() {
    emulate -L zsh

    region_highlight=(
        "P${_opencode_prompt_start} $((_opencode_prompt_start + 2)) fg=yellow,bold"
        "P$((_opencode_prompt_start + 2)) ${_opencode_prompt_end} fg=magenta,bold"
    )
}


#
# Customized read-from-minibuffer.
#
# - colored OpenCode prompt
# - plain editable text
# - no shell syntax highlighting
# - preserves/restores original editing buffer
#
_opencode_minibuffer() {
    emulate -L zsh

    local readprompt="$1"

    integer stat=1
    integer savelim=$UNDO_LIMIT_NO
    integer changeno=$UNDO_CHANGE_NO

    {
        () {
            local pretext="$PREDISPLAY$LBUFFER$RBUFFER$POSTDISPLAY
"

            local +h LBUFFER=
            local +h RBUFFER=
            local +h PREDISPLAY="$pretext$readprompt"
            local +h POSTDISPLAY=

            #
            # These are special ZLE parameters, so localize them for the
            # recursive editor.
            #
            local +h -a region_highlight
            local +h -a zle_highlight

            #
            # Don't apply any of ZLE's normal visual highlighting to the
            # natural-language text.
            #
            zle_highlight=(
                'default:none'
                'region:none'
                'special:none'
                'suffix:none'
                'isearch:none'
                'paste:none'
            )

            #
            # These are dynamically scoped, so
            # _opencode_minibuffer_pre_redraw can see them.
            #
            integer _opencode_prompt_start=${#pretext}
            integer _opencode_prompt_end=${#PREDISPLAY}

            #
            # Temporarily replace zle-line-pre-redraw.
            #
            # This is stronger than trying to configure individual syntax
            # highlighters: regardless of what they put in region_highlight,
            # our hook runs immediately before display and replaces it with
            # exactly the one range we want.
            #
            integer had_pre_redraw=0

            if zle -l zle-line-pre-redraw >/dev/null 2>&1; then
                zle -A zle-line-pre-redraw _opencode_saved_pre_redraw
                had_pre_redraw=1
            fi

            {
                zle -N \
                    zle-line-pre-redraw \
                    _opencode_minibuffer_pre_redraw

                #
                # Clear any stale syntax-highlighting ranges before the
                # recursive editor even starts.
                #
                region_highlight=(
                    "P${_opencode_prompt_start} ${_opencode_prompt_end} fg=magenta,bold"
                )

                local NUMERIC
                unset NUMERIC

                zle split-undo
                UNDO_LIMIT_NO=$UNDO_CHANGE_NO

                zle recursive-edit -K main
                stat=$?

                (( stat )) || REPLY=$BUFFER

            } always {
                #
                # Restore the user's normal redraw widget, which in turn
                # restores zsh-syntax-highlighting/F-Sy-H behavior at the
                # normal shell prompt.
                #
                if (( had_pre_redraw )); then
                    zle -A \
                        _opencode_saved_pre_redraw \
                        zle-line-pre-redraw

                    zle -D _opencode_saved_pre_redraw
                else
                    zle -D zle-line-pre-redraw
                fi
            }
        }

    } always {
        #
        # Remove the recursive editor's changes from the original command
        # line's undo history.
        #
        zle undo $changeno
        UNDO_LIMIT_NO=$savelim
    }

    return $stat
}


_whatcmd_autosuggest_pause() {
    emulate -L zsh

    #
    # Remember whether autosuggestions were already disabled before us.
    #
    _whatcmd_autosuggest_was_disabled=${+_ZSH_AUTOSUGGEST_DISABLED}

    if (( ${+widgets[autosuggest-disable]} )); then
        zle autosuggest-disable
    fi


    POSTDISPLAY=
}


_whatcmd_autosuggest_resume() {
    emulate -L zsh

    POSTDISPLAY=

    #
    # Don't enable it if the user already had it disabled before invoking
    # whatcmd.
    #
    if (( !_whatcmd_autosuggest_was_disabled )) &&
       (( ${+widgets[autosuggest-enable]} )); then
        zle autosuggest-enable
    fi

    unset _whatcmd_autosuggest_was_disabled
}

#
# Ctrl-? widget
#
_opencode_command() {
    emulate -L zsh

    local request

    #
    # Save the outer ZLE state.  History navigation inside recursive-edit
    # changes HISTNO, and that can otherwise leak back into the real prompt.
    #
    local saved_buffer=$BUFFER
    integer saved_cursor=$CURSOR
    integer saved_histno=$HISTNO

    _whatcmd_autosuggest_pause

    {
      #
      # Give the natural-language minibuffer its own history.
      #
      () {
          local history_file="${XDG_STATE_HOME:-$HOME/.local/state}/opencode-command/history"

          mkdir -p -- "${history_file:h}" || return 1

          #
          # Push normal shell history and load our OpenCode history.
          #
          # -a restores the previous history automatically when this
          # anonymous function returns.
          #
          fc -p -a "$history_file" 1000 1000

          _opencode_minibuffer " ⬤ What command " || return

          request=$REPLY

          [[ -z "${request//[[:space:]]/}" ]] && return 1

          #
          # Store the natural-language request in OpenCode history.
          #
          print -s -- "$request"
      }

      local minibuffer_ec=$?

      #
      # The anonymous function has exited, so fc -p -a has restored the
      # normal shell history. Restore the outer editor's history position
      # and command line.
      #
      # Assigning HISTNO can itself load a history entry into BUFFER, so
      # restore HISTNO first and BUFFER afterward.
      #
      HISTNO=$saved_histno
      BUFFER=$saved_buffer
      CURSOR=$saved_cursor

      (( minibuffer_ec != 0 )) && return $minibuffer_ec

      unsetopt MONITOR

      local tmpdir
      tmpdir=$(mktemp -d "${TMPDIR:-/tmp}/whatcmd.XXXXXX") || return 1

      local result_file="$tmpdir/result"
      local status_file="$tmpdir/status"
      local stderr_fifo="$tmpdir/stderr"

      mkfifo "$stderr_fifo" || {
          rm -rf -- "$tmpdir"
          return 1
      }

      #
      # Open the FIFO read/write in the parent so opening either end
      # never blocks waiting for the other side.
      #
      local fifo_fd
      exec {fifo_fd}<>"$stderr_fifo"

      (
          whatcmd "$request" >| "$result_file" 2>"$stderr_fifo"
          print -r -- "$?" >| "$status_file"
      ) &

      local -a spinner=(
          '⠋' '⠙' '⠹' '⠸' '⠼'
          '⠴' '⠦' '⠧' '⠇' '⠏'