Repository navigation
Expand file tree
/
Copy path_claude
More file actions
1582 lines (1517 loc) · 84.4 KB
/
Copy path_claude
File metadata and controls
1582 lines (1517 loc) · 84.4 KB
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#compdef claude
# Zsh completion script for Claude Code CLI
# https://github.com/anthropics/claude-code
# Auto-generated for Claude v2.1.296
_claude_session_ids() {
# Claude stores each project under ~/.claude/projects/ with a mangled
# folder name, Claude Code's `path.replace(/[^a-zA-Z0-9]/g, "-")`. That
# regex runs per UTF-16 code unit, so a character beyond U+FFFF such as
# `💩` becomes `--` while `ü`, ` `, `_`, `/` and `.` each become `-`. Zsh
# substitutes per character, hence the separate first pass for the astral
# range. Under a non-UTF-8 locale both passes yield extra hyphens, no
# folder matches, and the originalPath fallback below applies.
local mangled="${PWD//[$'\U00010000'-$'\U0010FFFF']/--}"
mangled="${mangled//[^a-zA-Z0-9]/-}"
local project_dir="$HOME/.claude/projects/$mangled"
# Fallback: if the mangled folder isn't found (e.g. unknown future naming
# scheme, or the session was created from a different canonical path such
# as a resolved symlink), locate the project by matching the authoritative
# `originalPath` recorded in each sessions-index.json.
if [[ ! -d "$project_dir" ]]; then
project_dir=""
local f
for f in "$HOME/.claude/projects"/*/sessions-index.json(N); do
if [[ "$(jq -r '.originalPath // ""' "$f" 2>/dev/null)" == "$PWD" ]]; then
project_dir="${f:h}"
break
fi
done
[[ -z "$project_dir" ]] && return 1
fi
local index_file="$project_dir/sessions-index.json"
local -a ids labels
# Cap the number of sessions offered by completion. Projects with a long
# history can accumulate hundreds of session files — enumerating them all
# triggers zsh's "show all N possibilities?" pager prompt and (worse)
# forces the expensive JSONL parse below to run once per file on every
# TAB press. Default to the 20 most recent; override via
# CLAUDE_COMPLETION_SESSION_LIMIT, where 0 (or any non-positive int)
# disables the cap for users who want the old behavior.
local max_sessions=${CLAUDE_COMPLETION_SESSION_LIMIT:-20}
# Pull branch + summary from sessions-index.json, keyed by sessionId.
# `.summary` here is the same human-readable title `/resume` displays
# (e.g. "refactor-auth-flow"); we prefer it over the first
# user prompt for indexed sessions, falling back to the JSONL when the
# session isn't indexed yet.
local -A index_summary index_branch
if [[ -f "$index_file" ]]; then
local _iid _ibranch _isummary
while IFS=$'\t' read -r _iid _ibranch _isummary; do
[[ -z "$_iid" ]] && continue
index_summary[$_iid]="$_isummary"
index_branch[$_iid]="$_ibranch"
done < <(jq -rs '[.[].entries[]] | .[] | [.sessionId, (.gitBranch // "?"), (.summary // "")] | @tsv' "$index_file" 2>/dev/null)
fi
# Single batched `zstat` for both mtime (epoch seconds) and size (bytes)
# on every jsonl file. Using one stat source for all sessions keeps the
# sort key uniform and gives us the size that `/resume` shows alongside
# the relative-time label. `zstat` is preferred over external `stat`
# because GNU/BSD `stat` flags disagree (GNU `stat -f` means
# filesystem-status, not "format"), so the BSD invocation produced
# garbage paths on Linux.
#
# Note: all locals used below are declared once here, up-front. zsh
# prints the current value of a variable when `local`/`typeset` is
# applied to it a second time in the same scope (treats it like
# `typeset -p`), so the second pass must *not* redeclare these.
local -a jsonl_files mtimes sizes candidates top
local line filepath uuid mtime size title branch info reltime sizestr
local _jb _jcustom _jai _jsum _jprompt _jcmd
local count=0 headroom idx d h m days weeks months years kb mb gb now
jsonl_files=( "$project_dir"/*.jsonl(N) )
(( ${#jsonl_files} == 0 )) && return 1
zmodload -F zsh/stat b:zstat 2>/dev/null
zstat -A mtimes +mtime "${jsonl_files[@]}" 2>/dev/null
zstat -A sizes +size "${jsonl_files[@]}" 2>/dev/null
idx=1
for filepath in "${jsonl_files[@]}"; do
mtime="${mtimes[$idx]}"
size="${sizes[$idx]:-0}"
(( idx++ ))
uuid="${filepath:t:r}"
[[ -z "$mtime" ]] && continue
candidates+=("${mtime}"$'\t'"${uuid}"$'\t'"${size}"$'\t'"${filepath}")
done
# Sort newest first (numeric epoch), then cap. Headroom covers JSONL
# files filtered out in pass 2 (only meta / <command-*> entries) so the
# list doesn't come up short.
if (( ${#candidates} > 0 )); then
if (( max_sessions > 0 )); then
headroom=$(( max_sessions * 2 + 5 ))
while IFS= read -r line; do top+=("$line"); done \
< <(printf '%s\n' "${candidates[@]}" | sort -nr | head -n $headroom)
else
while IFS= read -r line; do top+=("$line"); done \
< <(printf '%s\n' "${candidates[@]}" | sort -nr)
fi
fi
zmodload -F zsh/datetime p:EPOCHSECONDS 2>/dev/null
now=${EPOCHSECONDS:-$(date +%s)}
# Pass 2: resolve title/branch (from index when possible, else parse the
# JSONL), compute the same "1 day ago · main · 2.5MB" trio `/resume`
# displays, and build the label. Newest-first order is preserved by
# `sort -nr` above and by `-o nosort` on the compadd call below.
for line in "${top[@]}"; do
(( max_sessions > 0 && count >= max_sessions )) && break
IFS=$'\t' read -r mtime uuid size filepath <<< "$line"
branch="${index_branch[$uuid]:-?}"
# Parse the JSONL for live title signals — `/rename`-set custom titles
# (type: custom-title) and auto-generated `ai-title` records both live
# there and outrank any frozen `summary` recorded in sessions-index.json.
# We always check, so renaming a session immediately reflects in the
# completer. Both record types get appended throughout the session, so
# reading `head -100; tail -50` catches them without parsing multi-MB
# files. Fields are emitted one per line (with newlines stripped) so
# zsh's `read` doesn't collide with tab-collapsing IFS rules when
# intermediate values are empty.
_jb=""; _jcustom=""; _jai=""; _jsum=""; _jprompt=""; _jcmd=""
{
IFS= read -r _jb
IFS= read -r _jcustom
IFS= read -r _jai
IFS= read -r _jsum
IFS= read -r _jprompt
IFS= read -r _jcmd
} < <( { head -100 "$filepath"; tail -50 "$filepath"; } 2>/dev/null | jq -rs '
[.[] | select(.type=="user")] as $users |
([.[] | select(.type=="custom-title") | .customTitle] | last // "") as $custom |
([.[] | select(.type=="ai-title") | .aiTitle] | last // "") as $ai |
([.[] | select(.type=="summary") | .summary] | first // "") as $sum |
([
$users[]
| select((.isMeta // false) != true and .message.content != null)
| .message.content
| if type=="array" then .[0].text else . end
| select(. != null)
| select(test("^\\s*<(command|local-command)") | not)
] | first // "") as $prompt |
# Command-only sessions (e.g. a quick `/exit`) still show in `/resume`
# labelled by the slash command itself; extract that from the
# <command-name>...</command-name> tag so they surface here too.
([
$users[]
| (.message.content | if type=="array" then .[0].text else . end)
| select(. != null and test("<command-name>"))
| capture("<command-name>(?<c>[^<]+)</command-name>") | .c
] | first // "") as $cmd |
($users[0].gitBranch // "") as $br |
[$br, $custom, $ai, $sum, $prompt, $cmd][]
| gsub("\n"; " ")
' 2>/dev/null )
[[ -n "$_jb" ]] && branch="$_jb"
# Priority: /rename customTitle → aiTitle → index summary →
# inline summary record → first user prompt → first slash command.
if [[ -n "$_jcustom" ]]; then title="$_jcustom"
elif [[ -n "$_jai" ]]; then title="$_jai"
elif [[ -n "${index_summary[$uuid]}" ]]; then title="${index_summary[$uuid]}"
elif [[ -n "$_jsum" ]]; then title="$_jsum"
elif [[ -n "$_jprompt" ]]; then title="$_jprompt"
elif [[ -n "$_jcmd" ]]; then title="$_jcmd"
else title=""
fi
[[ -z "$title" ]] && continue
# Trim/normalize for one-line display.
title="${title//$'\n'/ }"
(( ${#title} > 80 )) && title="${title:0:80}"
# Relative time — same buckets `/resume` uses.
d=$(( now - mtime ))
(( d < 0 )) && d=0
if (( d < 60 )); then
(( d == 1 )) && reltime="1 second ago" || reltime="${d} seconds ago"
elif (( d < 3600 )); then
m=$(( d / 60 ))
(( m == 1 )) && reltime="1 minute ago" || reltime="${m} minutes ago"
elif (( d < 86400 )); then
h=$(( d / 3600 ))
(( h == 1 )) && reltime="1 hour ago" || reltime="${h} hours ago"
elif (( d < 604800 )); then
days=$(( d / 86400 ))
(( days == 1 )) && reltime="1 day ago" || reltime="${days} days ago"
elif (( d < 2592000 )); then
weeks=$(( d / 604800 ))
(( weeks == 1 )) && reltime="1 week ago" || reltime="${weeks} weeks ago"
elif (( d < 31536000 )); then
months=$(( d / 2592000 ))
(( months == 1 )) && reltime="1 month ago" || reltime="${months} months ago"
else
years=$(( d / 31536000 ))
(( years == 1 )) && reltime="1 year ago" || reltime="${years} years ago"
fi
# Human-readable size, one decimal place. Avoids forking awk/bc; zsh
# integer arithmetic keeps the pass-2 loop hot for projects with
# hundreds of sessions.
if (( size < 1024 )); then
sizestr="${size}B"
elif (( size < 1048576 )); then
kb=$(( size * 10 / 1024 ))
(( kb % 10 == 0 )) && sizestr="$((kb/10))KB" || sizestr="$((kb/10)).$((kb%10))KB"
elif (( size < 1073741824 )); then
mb=$(( size * 10 / 1048576 ))
(( mb % 10 == 0 )) && sizestr="$((mb/10))MB" || sizestr="$((mb/10)).$((mb%10))MB"
else
gb=$(( size * 10 / 1073741824 ))
(( gb % 10 == 0 )) && sizestr="$((gb/10))GB" || sizestr="$((gb/10)).$((gb%10))GB"
fi
ids+=("$uuid")
labels+=("${reltime} · ${branch} · ${sizestr} - ${uuid:0:8}: ${title}")
(( count++ ))
done
[[ ${#ids} -eq 0 ]] && return 1
local expl
# `-V sessions` names the group (for zstyle targeting). `-o nosort` is
# what actually disables alphabetical re-sorting — `-V` alone is
# sometimes overridden by the display layer. `-o nosort` is the canonical
# zsh API (used throughout core completion functions) and is stable in
# zsh 5.0.1+, so this is safe for any modern zsh.
_wanted session-ids expl 'session' compadd -V sessions -o nosort -d labels -a ids
}
# Background-session ID completer for `claude attach|logs|stop|kill|respawn|rm`.
# Mirrors how the `claude agents` view itself enumerates sessions: walk
# ~/.claude/jobs/<id>/state.json. A state.json file is the only authoritative
# marker — entries that appear only in daemon/roster.json without a state.json
# are pre-spawn placeholders (no real session) and sessions imported via /bg
# from an interactive terminal land in jobs/ without ever touching roster.json,
# so the roster is neither necessary nor sufficient. Honors CLAUDE_CONFIG_DIR
# per the docs (background sessions are stored there instead of ~/.claude when
# set).
_claude_background_session_ids() {
local config_dir="${CLAUDE_CONFIG_DIR:-$HOME/.claude}"
local jobs_dir="$config_dir/jobs"
[[ -d "$jobs_dir" ]] || return 1
# Gather every job dir that has a state.json. The state.json mtime is the
# session's last-activity timestamp (the supervisor rewrites it on every
# turn), so it's the right key for matching `claude agents`'s newest-first
# ordering. zstat (zsh/stat module) gets all mtimes in a single syscall —
# avoids forking `stat` per file when the user has many sessions.
local -a job_dirs state_files mtimes
local d
for d in "$jobs_dir"/*(N/); do
[[ -r "$d/state.json" ]] || continue
job_dirs+=("$d")
state_files+=("$d/state.json")
done
(( ${#job_dirs} == 0 )) && return 1
zmodload -F zsh/stat b:zstat 2>/dev/null
zstat -A mtimes +mtime "${state_files[@]}" 2>/dev/null
# Build "<mtime>\t<id>\t<label>" rows so a single `sort -nr` orders the
# whole list newest-first regardless of how many sessions there are.
local -a rows
local idx=1 id state_file info name state label mtime
for d in "${job_dirs[@]}"; do
state_file="${state_files[$idx]}"
mtime="${mtimes[$idx]:-0}"
(( idx++ ))
id="${d:t}"
# Observed state.json fields (Claude v2.1.139): `name` (auto-generated or
# user-set), `intent` (the original prompt seed), `state` ("done", "idle",
# etc.). Fall back through other plausible names so a future rename
# doesn't blank the menu entirely.
info=$(jq -r '
[
(.name // .displayName // .title // .sessionName // .intent // .summary // .prompt // ""),
(.state // .status // .lifecycle // "")
] | @tsv
' "$state_file" 2>/dev/null)
name="${info%%$'\t'*}"
state="${info#*$'\t'}"
if [[ -n "$name" && -n "$state" ]]; then
label="${id} [${state}] ${name}"
elif [[ -n "$name" ]]; then
label="${id} ${name}"
elif [[ -n "$state" ]]; then
label="${id} [${state}]"
else
label="${id}"
fi
rows+=("${mtime}"$'\t'"${id}"$'\t'"${label}")
done
local -a ids labels
local line
while IFS=$'\t' read -r mtime id label; do
ids+=("$id")
labels+=("$label")
done < <(printf '%s\n' "${rows[@]}" | sort -nr)
local expl
_wanted bg-session-ids expl 'background session' compadd -o nosort -d labels -a ids
}
# Offer the model aliases Claude accepts in place of a full model name.
# The list mirrors the alias table at
# https://code.claude.com/docs/en/model-config#model-aliases. Full model
# ids are left out on purpose: they change with every model release.
#
# "$@" carries the options the caller adds (`_arguments`' description
# options, or `_sequence`'s separator and already-chosen values for the
# comma-separated --fallback-model), so it has to reach `_describe`.
_claude_models() {
local -a models
models=(
'default:Clear any model override and use the default for your account'
'best:Fable where it is available to you, otherwise the same model as opus'
'fable:Fable, for your hardest and longest-running tasks'
'sonnet:Latest Sonnet, for daily coding tasks'
'opus:Latest Opus, for complex reasoning tasks'
'haiku:Fast and efficient Haiku, for simple tasks'
'sonnet[1m]:Sonnet with a 1 million token context window'
'opus[1m]:Opus with a 1 million token context window'
'opusplan:opus during plan mode, then sonnet for execution'
)
_describe -t models 'model' models "$@"
}
# Set $reply to the directories Claude treats as the current project: the
# working directory and each parent up to the repository root, closest
# first. Outside a repository that is the working directory alone. Symlinks
# are resolved, because Claude keys project state by the resolved path.
_claude_project_dirs() {
local d=${PWD:A} root=""
reply=($d)
while true; do
if [[ -e $d/.git ]]; then root=$d; break; fi
[[ $d == / ]] && break
d=${d:h}
done
d=$reply[1]
while [[ -n $root && $d != "$root" ]]; do
d=${d:h}
reply+=($d)
done
}
# Set $reply to the `name` and the `description` in the frontmatter of the
# agent file $1, each empty when it is missing. Only the frontmatter is
# read, in zsh itself, so no process is started per file.
_claude_agent_frontmatter() {
setopt localoptions extendedglob
local line key val name="" desc=""
local -i n=0 block=0
while IFS= read -r line || [[ -n $line ]]; do
(( n++ ))
line=${line%$'\r'}
if (( n == 1 )); then
# A byte-order mark may precede the opening `---`.
line=${line#$'\xef\xbb\xbf'}
[[ ${line%%[[:space:]]#} == '---' ]] || break
continue
fi
[[ ${line%%[[:space:]]#} == '---' ]] && break
(( n > 200 )) && break
if (( block )); then
# First line of a `description: |` or `>` block.
block=0
if [[ $line == [[:space:]]##[^[:space:]]* ]]; then
desc=${${line##[[:space:]]#}%%[[:space:]]#}
continue
fi
fi
[[ $line == (name|description):* ]] || continue
key=${line%%:*}
val=${${line#*:}##[[:space:]]#}
if [[ $val == \"* ]]; then
val=${${val#\"}%%\"*}
elif [[ $val == \'* ]]; then
val=${${val#\'}%%\'*}
else
# Unquoted: drop a trailing ` # comment`, then trailing blanks.
[[ $val == \#* ]] && val=""
val=${${val%%[[:space:]]##\#*}%%[[:space:]]#}
fi
if [[ $key == name ]]; then
name=$val
elif [[ $val == [\|\>]([+-]|)([0-9]|) ]]; then
block=1
else
desc=$val
fi
done < $1 2>/dev/null
# Descriptions often carry escaped examples; keep the first line short.
desc=${desc%%\\n*}
(( ${#desc} > 80 )) && desc="${desc[1,77]}..."
reply=("$name" "$desc")
}
# Set $reply to the agents of the installed plugins, as `_describe` items.
# The arguments are the project directories (`_claude_project_dirs`).
# - installed_plugins.json names each plugin's `installPath`. The cache
# directory also keeps older versions, so it is not searched. An
# install with project or local scope counts only inside its project.
# - a plugin is skipped when `enabledPlugins` turns it off, or when
# nothing sets it and its manifest says `defaultEnabled: false`. The
# files are the ones Claude reads (checked with `claude plugin list`
# in 2.1.296), the later one winning: the user's settings.json, the
# working directory's .claude/settings.json and settings.local.json,
# and the main repository's .claude/settings.local.json. No other
# parent directory counts, and neither does the repository's
# settings.json below its root.
# - the agent is `<plugin>:<subfolders of agents/>:<name>`, the name
# being the frontmatter `name`, or the file name without it. `<plugin>`
# is the manifest's `name`, the part before `@` without a manifest.
# - `agents` in the manifest replaces the `agents/` scan with the listed
# `.md` files, which get no subfolder in their name.
# See https://code.claude.com/docs/en/plugins/components#agents. Two jq
# processes read every JSON file: one for installed_plugins.json and the
# settings, one for the manifests. Each file is handed over as text and
# parsed inside jq, so a broken one is skipped instead of ending the run.
_claude_plugin_agents() {
setopt localoptions extendedglob
local config=${CLAUDE_CONFIG_DIR:-$HOME/.claude}
local installed=${CLAUDE_CODE_PLUGIN_CACHE_DIR:-$config/plugins}/installed_plugins.json
local -a jqargs rows fields ids roots preset manifests files out
local -A seen
local f row root plugin name desc text main="" gitdir common
local -i i=0 listed
reply=()
[[ -f $installed && -r $installed ]] || return 1
# The main repository is the last project directory when that is a
# checkout. A linked worktree names its git directory in a `.git` file,
# and `commondir` there leads to the repository it belongs to.
(( $# )) && main=${@[-1]}
if [[ -n $main && -f $main/.git ]]; then
gitdir=$(<$main/.git) 2>/dev/null
gitdir=${${gitdir%%$'\n'*}#gitdir: }
[[ $gitdir == /* ]] || gitdir=$main/$gitdir
common=""
[[ -f $gitdir/commondir && -r $gitdir/commondir ]] && common=$(<$gitdir/commondir) 2>/dev/null
common=${common%%$'\n'*}
if [[ -n $common ]]; then
[[ $common == /* ]] || common=$gitdir/$common
main=${common:A:h}
fi
elif [[ ! -d $main/.git ]]; then
main=""
fi
jqargs=(--rawfile installed $installed)
for f in $config/settings.json $1/.claude/settings.json $1/.claude/settings.local.json \
${main:+$main/.claude/settings.local.json}; do
(( i++ ))
if [[ -f $f && -r $f ]]; then
jqargs+=(--rawfile settings$i $f)
else
jqargs+=(--arg settings$i '')
fi
done
(( i < 4 )) && jqargs+=(--arg settings4 '')
# One row per usable plugin: id, install path, and whether a settings
# file sets `enabledPlugins` for it.
rows=("${(@f)$(command jq -n -r "${jqargs[@]}" '
def parse: first((try fromjson catch null), null);
(reduce ($settings1, $settings2, $settings3, $settings4 | parse | objects | .enabledPlugins | objects) as $e
({}; . + $e)) as $enabled
| $installed | parse | objects | .plugins | objects | to_entries[]
| .key as $id
| select($enabled[$id] != false)
| [.value | if type == "array" then .[] else . end | objects
| select(.installPath | type == "string")] as $installs
| ([$installs[] | select(.projectPath as $p | $p != null and any($ARGS.positional[]; . == $p))][0]
// [$installs[] | select(.scope != "project" and .scope != "local")][0])
| objects
| select($id + .installPath | test("[[:cntrl:]]") | not)
| [$id, .installPath, ($enabled | has($id) | tostring)] | join("\u001f")
' --args "$@" 2>/dev/null)}")
for row in $rows; do
fields=("${(@ps:\x1f:)row}")
root=${fields[2]%/}
(( $#fields == 3 )) && [[ -d $root ]] || continue
text=""
f=$root/.claude-plugin/plugin.json
[[ -f $f && -r $f ]] && text=$(<$f) 2>/dev/null
ids+=("$fields[1]") roots+=("$root") preset+=("$fields[3]") manifests+=("$text")
done
(( $#ids )) || return 1
# One row per manifest, in order: name, defaultEnabled, whether it has
# an `agents` key, and the paths under that key.
rows=()
if [[ -n ${(j::)manifests} ]]; then
rows=("${(@f)$(command jq -n -r '
$ARGS.positional[] | first((try fromjson catch null), null) as $m
| if ($m | type) == "object" then
[ ($m.name | if type == "string" then . else "" end),
($m.defaultEnabled != false | tostring),
($m | has("agents") | tostring),
($m.agents | if type == "string" then [.] elif type == "array" then map(strings) else [] end
| join("\u001e")) ]
else ["", "true", "false", ""] end
| join("\u001f") | gsub("[\\n\\r]"; "")
' --args "${manifests[@]}" 2>/dev/null)}")
fi
for (( i = 1; i <= $#ids; i++ )); do
root=$roots[i] plugin=${ids[i]%%@*} listed=0
files=($root/agents/**/*.md(N-.))
if (( $#rows == $#ids )); then
fields=("${(@ps:\x1f:)rows[i]}")
[[ -n $fields[1] ]] && plugin=$fields[1]
[[ $preset[i] == false && $fields[2] == false ]] && continue
if [[ $fields[3] == true ]]; then
listed=1 files=()
for f in "${(@ps:\x1e:)fields[4]}"; do
# Paths start with `./` and stay inside the plugin.
[[ $f == ./*.md && $f != *..* && -f $root/$f ]] && files+=($root/$f)
done
fi
fi
for f in $files; do
_claude_agent_frontmatter $f
# Claude's own fallbacks for a file without usable frontmatter.
name=${reply[1]:-${f:t:r}} desc=${reply[2]:-Agent from $plugin plugin}
if (( listed )); then
name=$plugin:$name
else
name=$plugin${${${f:h}#$root/agents}//\//:}:$name
fi
(( ${+seen[$name]} )) && continue
seen[$name]=1
out+=("${name//:/\\:}:$desc")
done
done
reply=("${out[@]}")
}
# Offer the agents `--agent` accepts, the way Claude finds them
# (https://code.claude.com/docs/en/sub-agents):
# - project: every `.claude/agents/` from the working directory up to the
# repository root, closest first, so `claude --agent` works from a
# subdirectory. Outside a repository only the working directory counts.
# - user: `$CLAUDE_CONFIG_DIR/agents`, `~/.claude/agents` by default.
# - both are searched recursively, and the agent is identified by the
# `name` in its frontmatter, never by its path or file name. A file
# without usable frontmatter is skipped.
# - plugin: see `_claude_plugin_agents`. Only the scoped name is offered.
# Claude also takes the last part alone, but then a user or project
# agent of that name wins, and so does the first of two plugins.
# - built-in: the agents Claude registers itself. A user or project
# agent of the same name replaces one, so it is listed once.
_claude_agents() {
local -a reply dirs agents
local -A seen
local d f name desc
_claude_project_dirs
dirs=("${reply[@]}")
for d in ${^dirs}/.claude/agents "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/agents"; do
for f in $d/**/*.md(N-.); do
_claude_agent_frontmatter $f
name=$reply[1] desc=$reply[2]
# `:` is reserved for plugin-scoped agents; Claude skips such a file.
[[ -n $name && $name != *:* ]] || continue
(( ${+seen[$name]} )) && continue
seen[$name]=1
agents+=("${name}${desc:+:$desc}")
done
done
_claude_plugin_agents "${dirs[@]}"
agents+=("${reply[@]}")
# The descriptions are from the sub-agents page.
for name desc in \
general-purpose 'Complex, multi-step tasks that need both exploration and action' \
statusline-setup 'Configures your status line' \
claude 'Catch-all with every tool available to subagents' \
Explore 'Fast, read-only agent for searching and analyzing codebases' \
Plan 'Research agent that gathers context before presenting a plan' \
claude-code-guide 'Answers questions about Claude Code features'; do
(( ${+seen[$name]} )) || agents+=("$name:$desc")
done
_describe -t agents 'agent' agents "$@"
}
# Offer the MCP servers configured for the current directory, read from
# Claude's own files (https://code.claude.com/docs/en/mcp):
# - user scope: `mcpServers` in ~/.claude.json
# - local scope: `projects.<project path>.mcpServers` in ~/.claude.json
# - project scope: `mcpServers` in the project's `.mcp.json`
# With CLAUDE_CONFIG_DIR set, .claude.json is read from that directory.
# The project is looked up from the working directory up to the repository
# root (see _claude_project_dirs), so servers are also found from a
# subdirectory or through a symlinked path. Needs `jq` 1.6 or newer (for
# `$ARGS`); without it, or with a missing or malformed file, nothing is
# offered.
_claude_mcp_servers() {
local -a reply servers
local d cfg="${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json"
# One `name:scope - type target` row per server. A `:` in the name is
# escaped for _describe. The query string of a URL is dropped, since it
# can hold a token. Control characters are taken out of the description:
# `.mcp.json` comes with the repository, and a newline in it would
# otherwise turn into an extra row.
local rows='def rows($scope):
objects | to_entries[]
| select((.value | type) == "object")
| select(.key | test("[[:cntrl:]]") | not)
| (.value.url // .value.command // "" | tostring | split("?")[0] // "") as $target
| (.value.type // (if .value.url then "http" else "stdio" end) | tostring) as $type
| "\(.key | gsub(":"; "\\:")):\("\($scope) - \($type) \($target)" | gsub("[[:cntrl:]]"; " ") | .[0:100])";'
_claude_project_dirs
if [[ -r $cfg ]]; then
servers+=("${(@f)$(command jq -r "$rows"'
(.mcpServers | rows("user")),
(.projects as $p | $ARGS.positional[] | $p[.]?.mcpServers? | rows("local"))
' "$cfg" --args $reply 2>/dev/null)}")
fi
for d in $reply; do
[[ -r $d/.mcp.json ]] || continue
servers+=("${(@f)$(command jq -r "$rows"' .mcpServers | rows("project")' \
"$d/.mcp.json" 2>/dev/null)}")
done
servers=(${servers:#})
_describe -t mcp-servers 'MCP server' servers "$@"
}
# The three helpers below complete plugin and marketplace values from the
# files Claude keeps under `$CLAUDE_CONFIG_DIR/plugins` (`~/.claude/plugins`
# by default), or under `$CLAUDE_CODE_PLUGIN_CACHE_DIR` when that is set,
# as Claude does. They need `jq` 1.6 or newer, never run `claude` and never use the
# network. A missing or malformed file, or a malformed entry in one,
# leaves the remaining values in place.
# Installed plugins, as `name@marketplace`, from installed_plugins.json.
# The value of an entry is a list of installs, or a single install in the
# older format. An install made for one project (project or local scope,
# with a `projectPath`) only counts inside that project, as found by
# _claude_project_dirs; the first install that counts supplies the
# description.
_claude_installed_plugins() {
local -a reply plugins
local file="${CLAUDE_CODE_PLUGIN_CACHE_DIR:-${CLAUDE_CONFIG_DIR:-$HOME/.claude}/plugins}/installed_plugins.json"
[[ -r $file ]] || return 1
_claude_project_dirs
plugins=("${(@f)$(command jq -r '
$ARGS.positional as $dirs
| .plugins | objects | to_entries[]
| select(.key | test("[[:cntrl:]]") | not)
| ([.value | if type == "array" then .[] else . end | objects
| select((.projectPath | type) != "string" or (.projectPath as $p | $dirs | index($p) != null))
] | first) as $install
| select($install != null)
| "\(.key | gsub(":"; "\\:")):\("\($install.version // "unknown" | tostring) (\($install.scope // "user" | tostring) scope)" | gsub("[[:cntrl:]]"; " ") | .[0:80])"
' "$file" --args $reply 2>/dev/null)}")
plugins=(${plugins:#})
_describe -t plugins 'installed plugin' plugins "$@"
}
# Marketplace names, from known_marketplaces.json.
_claude_marketplaces() {
local -a marketplaces
local file="${CLAUDE_CODE_PLUGIN_CACHE_DIR:-${CLAUDE_CONFIG_DIR:-$HOME/.claude}/plugins}/known_marketplaces.json"
[[ -r $file ]] || return 1
marketplaces=("${(@f)$(command jq -r '
objects | to_entries[]
| select((.value | type) == "object")
| select(.key | test("[[:cntrl:]]") | not)
| ((.value.source | objects | (.repo // .url // .path // .source) | strings | split("?")[0]) // "") as $source
| "\(.key | gsub(":"; "\\:")):\($source)"
' "$file" 2>/dev/null)}")
marketplaces=(${marketplaces:#})
_describe -t marketplaces 'marketplace' marketplaces "$@"
}
# Plugins that can be installed, as `name@marketplace`, from the manifest
# each known marketplace caches under marketplaces/<name>/.
# All manifests go through one jq process. Each is handed over as text
# (`--rawfile <marketplace> <file>`) and parsed inside jq, so a manifest
# that is not valid JSON is skipped. Passed as input files instead, jq
# would give up at the first broken one.
_claude_marketplace_plugins() {
local -a manifests rawfiles plugins
local manifest
manifests=("${CLAUDE_CODE_PLUGIN_CACHE_DIR:-${CLAUDE_CONFIG_DIR:-$HOME/.claude}/plugins}"/marketplaces/*/.claude-plugin/marketplace.json(N-.))
(( $#manifests )) || return 1
for manifest in $manifests; do
rawfiles+=(--rawfile ${manifest:h:h:t} $manifest)
done
plugins=("${(@f)$(command jq -n -r $rawfiles '
$ARGS.named | to_entries[]
| .key as $marketplace
| .value | fromjson? | objects | .plugins | arrays | .[] | objects
| select((.name | type) == "string")
| select(.name | test("[[:cntrl:]]") | not)
| ((.description | strings | gsub("[[:cntrl:]]"; " ") | .[0:80]) // "") as $description
| "\("\(.name)@\($marketplace)" | gsub(":"; "\\:")):\($description)"
' 2>/dev/null)}")
plugins=(${plugins:#})
_describe -t plugins 'plugin' plugins "$@"
}
# Offer a freshly-generated UUID for --session-id, which expects a NEW,
# user-assigned session identifier (not an existing session to resume).
local curcontext="$curcontext" state line
typeset -A opt_args
# Top-level commands. This is the one list to maintain: known_commands and the
# '1:command:(...)' spec below are derived from it. It must not be named
# `commands`: that is zsh's special hash of executables, and a local of that
# name hides it from every completer called from here.
local -a claude_commands
claude_commands=(
'agents:Open agent view (manage background sessions)'
'attach:Open a background session in this terminal'
'auth:Manage authentication'
'auto-mode:Inspect auto mode classifier configuration'
'daemon:Manage the background session supervisor'
'doctor:Check the health of your Claude Code installation'
'gateway:Run the enterprise auth/telemetry gateway'
'import:Import config from another AI coding agent into Claude Code'
'install:Install Claude Code native build. Use [target] to specify version (stable, latest, or specific version)'
'kill:Stop a background session (alias for stop)'
'logs:Print a background session'\''s recent terminal output'
'mcp:Configure and manage MCP servers'
'plugin:Manage Claude Code plugins'
'plugins:Manage Claude Code plugins'
'project:Deprecated - `claude project purge` is now `claude purge`'
'purge:Delete all Claude Code state for a project (transcripts, tasks, file history, config entry)'
'respawn:Restart a background session (or all of them) so it picks up the current Claude binary'
'rm:Delete a background session and its worktree (works on already-exited sessions)'
'self-hosted-runner:Start a runner process that hosts Claude Code cloud sessions on your infrastructure'
'setup-token:Set up a long-lived authentication token (requires Claude subscription)'
'remote-control:Connect your local environment to claude.ai/code'
'stop:Stop a background session'
'ultrareview:Run a cloud-hosted multi-agent code review of the current branch (or a PR number / base branch) and print the findings'
'update:Check for updates and install if available'
'upgrade:Check for updates and install if available'
)
local -a auth_commands
auth_commands=(
'help:Display help for command'
'login:Sign in to your Anthropic account'
'logout:Log out from your Anthropic account'
'status:Show authentication status'
)
local -a mcp_commands
mcp_commands=(
'add:Add an MCP server to Claude Code'
'add-from-claude-desktop:Import MCP servers from Claude Desktop (Mac and WSL only)'
'add-json:Add an MCP server (stdio, SSE, HTTP, or WebSocket) with a JSON string'
'get:Get details about an MCP server'
'help:Display help for command'
'list:List configured MCP servers'
'login:Authenticate with an MCP server (HTTP, SSE, or claude.ai connector)'
'logout:Clear stored OAuth credentials for an MCP server'
'remove:Remove an MCP server'
'reset-project-choices:Reset all approved and rejected project-scoped (.mcp.json) servers within this project'
'serve:Start the Claude Code MCP server'
)
local -a plugin_commands
plugin_commands=(
'configure:Show a plugin'\''s options and which are unset, or save values from stdin with --values-stdin'
'details:Show a plugin'\''s component inventory and projected token cost'
'disable:Disable an enabled plugin'
'enable:Enable a disabled plugin'
'eval:Run eval cases against a plugin and report scored results'
'help:Display help for command'
'init:Scaffold a new plugin at ~/.claude/skills/<name>/'
'new:Scaffold a new plugin at ~/.claude/skills/<name>/'
'install:Install a plugin from available marketplaces (use plugin@marketplace for specific marketplace)'
'i:Install a plugin from available marketplaces (use plugin@marketplace for specific marketplace)'
'list:List installed plugins'
'marketplace:Manage Claude Code marketplaces'
'prune:Remove auto-installed dependencies that are no longer needed'
'autoremove:Remove auto-installed dependencies that are no longer needed'
'uninstall:Uninstall an installed plugin'
'remove:Uninstall an installed plugin'
'tag:Create a {name}--v{version} git tag for a plugin release, validating that plugin.json and any enclosing marketplace entry agree'
'test:Run a mod'\''s tests'
'update:Update a plugin to the latest version (restart required to apply)'
'validate:Validate a plugin or marketplace manifest, or the skills, agents, and commands in a directory'
)
local -a marketplace_commands
marketplace_commands=(
'add:Add a marketplace from a URL, path, or GitHub repo'
'help:Display help for command'
'list:List all configured marketplaces'
'remove:Remove a configured marketplace'
'rm:Remove a configured marketplace'
'update:Update marketplace(s) from their source - updates all if no name specified'
)
# Find the subcommand position by scanning for the first non-flag argument after the command name.
# This handles cases where flags appear before the subcommand (e.g., alias claude='claude --flag').
# Only words before the cursor count: the word being completed is not a
# subcommand yet, and words after it must not change what is offered here.
local subcmd_pos=0
local subcmd="" subcmd2="" subcmd3=""
# Every name in claude_commands must have a branch in the case statement below.
local -a known_commands=(${claude_commands%%:*})
local i
for (( i=2; i < CURRENT; i++ )); do
# Skip flags and their values
[[ "$words[$i]" == -* ]] && continue
# Check if this word is a known subcommand
if (( ${known_commands[(Ie)$words[$i]]} )); then
subcmd_pos=$i
subcmd="$words[$i]"
break
fi
done
# If no subcommand found yet, fall through to main _arguments
if [[ -n "$subcmd" ]]; then
# Drop everything before the subcommand so that $words[1] is the subcommand
# itself. `_arguments` counts positionals from $words[2], so each block
# below can list its own arguments without accounting for `claude` or for
# flags an alias put in front. Nested levels shift once more for the same
# reason, right before their own `case`.
shift $(( subcmd_pos - 1 )) words
(( CURRENT -= subcmd_pos - 1 ))
case $subcmd in
agents)
_arguments -s \
'*--add-dir[Additional directory to allow tool access to in dispatched sessions (repeatable)]:directory:_files -/' \
'--agent[Default agent for sessions dispatched from agent view. Overrides the agent setting]:agent:_claude_agents' \
'--all[With --json: also include completed background sessions]' \
'--allow-dangerously-skip-permissions[Make bypass-permissions mode available to dispatched sessions without defaulting to it]' \
'--cwd[Show only background sessions started under path]:path:_files -/' \
'--dangerously-skip-permissions[Alias for --permission-mode bypassPermissions]' \
'--effort[Default effort level for sessions dispatched from agent view]:level:(low medium high xhigh max ultracode)' \
'(-h --help)'{-h,--help}'[Display help for command]' \
'--json[Print active sessions (interactive and background) as a JSON array and exit (for scripting; does not require a TTY)]' \
'*--mcp-config[MCP server configuration to apply to dispatched sessions (repeatable)]:config:_files' \
'--model[Default model for sessions dispatched from agent view]:model:_claude_models' \
'--permission-mode[Default permission mode for sessions dispatched from agent view]:mode:(acceptEdits auto bypassPermissions manual dontAsk plan)' \
'*--plugin-dir[Load plugins from specified directory for the agent view and dispatched sessions (repeatable)]:path:_files -/' \
'--restricted[Start dispatched sessions in restricted mode]' \
'--setting-sources[Comma-separated list of setting sources to load (user, project, local)]:sources:_values -s , source user project local' \
'--settings[Settings file or JSON string to apply to the agent view and dispatched sessions]:file-or-json:_files' \
'--strict-mcp-config[Only use MCP servers from --mcp-config in dispatched sessions]'
return
;;
attach|logs|stop|kill)
_arguments \
'(-h --help)'{-h,--help}'[Display help for command]' \
':session:_claude_background_session_ids'
return
;;
rm)
_arguments \
'--discard-unpushed[Also discard the worktree'\''s unpushed commits (and any uncommitted changes) while it is still the same worktree at that commit - pass the value a previous claude rm <id> reported]:commit@worktree-id:' \
'--force-remove-worktree[Delete the worktree directory even though the WorktreeRemove hook or git couldn'\''t remove it - pass the value a previous claude rm <id> reported]:worktree-id:' \
'(-h --help)'{-h,--help}'[Display help for command]' \
':session:_claude_background_session_ids'
return
;;
respawn)
_arguments \
'(--all)--all[Restart every stopped session]' \
'(-h --help)'{-h,--help}'[Display help for command]' \
'(--all):session:_claude_background_session_ids'
return
;;
auth)
if (( CURRENT == 2 )); then
_describe 'auth command' auth_commands
else
subcmd2=$words[2]
shift words; (( CURRENT-- ))
case $subcmd2 in
login)
_arguments \
'--claudeai[Use Claude subscription (default)]' \
'--console[Use Anthropic Console (API usage billing) instead of Claude subscription]' \
'--email[Pre-populate email address on the login page]:email:' \
'(-h --help)'{-h,--help}'[Display help]' \
'--sso[Force SSO login flow]'
;;
logout)
_arguments \
'(-h --help)'{-h,--help}'[Display help]'
;;
status)
_arguments \
'(-h --help)'{-h,--help}'[Display help]' \
'--json[Output as JSON (default)]' \
'--text[Output as human-readable text]'
;;
*)
_message 'no more arguments'
;;
esac
fi
return
;;
mcp)
if (( CURRENT == 2 )); then
_describe 'mcp command' mcp_commands
else
subcmd2=$words[2]
shift words; (( CURRENT-- ))
case $subcmd2 in
serve)
_arguments \
'(-d --debug)'{-d,--debug}'[Enable debug mode]' \
'(-h --help)'{-h,--help}'[Display help]' \
'--verbose[Override verbose mode setting from config]'
;;
add)
_arguments \
'--callback-port[Fixed port for OAuth callback (for servers requiring pre-registered redirect URIs)]:port:' \
'--client-id[OAuth client ID for HTTP/SSE servers]:clientId:' \
'--client-secret[Prompt for OAuth client secret (or set MCP_CLIENT_SECRET env var)]' \
'(-e --env)*'{-e,--env}'[Set environment variables (e.g. -e KEY=value)]:env:' \
'(-H --header)*'{-H,--header}'[Set headers for HTTP/SSE servers (e.g. -H "X-Api-Key: abc123" -H "X-Custom: value")]:header:' \
'(-h --help)'{-h,--help}'[Display help]' \
'(-s --scope)'{-s,--scope}'[Configuration scope (local, user, or project) (default: local)]:scope:(local user project)' \
'(-t --transport)'{-t,--transport}'[Transport type (stdio, sse, http). Defaults to stdio if not specified]:transport:(stdio sse http)' \
':name:' \
':commandOrUrl:_files' \
'*:args:_files'
;;
remove)
_arguments \
'(-h --help)'{-h,--help}'[Display help]' \
'(-s --scope)'{-s,--scope}'[Configuration scope (local, user, or project) - if not specified, removes from whichever scope it exists in]:scope:(local user project)' \
':name:_claude_mcp_servers'
;;
add-json)
_arguments \
'--client-secret[Prompt for OAuth client secret (or set MCP_CLIENT_SECRET env var)]' \
'(-h --help)'{-h,--help}'[Display help]' \
'(-s --scope)'{-s,--scope}'[Configuration scope (local, user, or project) (default: local)]:scope:(local user project)' \
':name:' \
':json:'
;;
add-from-claude-desktop)
_arguments \
'(-h --help)'{-h,--help}'[Display help]' \
'(-s --scope)'{-s,--scope}'[Configuration scope (local, user, or project) (default: local)]:scope:(local user project)'
;;
get)
_arguments \
'(-h --help)'{-h,--help}'[Display help]' \
':name:_claude_mcp_servers'
;;
list|reset-project-choices)
_arguments \
'(-h --help)'{-h,--help}'[Display help]'
;;
login)
_arguments \
'(-h --help)'{-h,--help}'[Display help]' \
'--no-browser[Print the authorization URL instead of opening a browser (for SSH/headless sessions - paste the redirect URL back when prompted)]' \
':name:_claude_mcp_servers'
;;
logout)
_arguments \
'(-h --help)'{-h,--help}'[Display help]' \
':name:_claude_mcp_servers'
;;
*)
_message 'no more arguments'
;;
esac
fi
return
;;
plugin|plugins)
if (( CURRENT == 2 )); then