copilot-relay 0.5.3 → 0.6.1

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.
package/README.md CHANGED
@@ -62,8 +62,8 @@ copilot-relay cache --hourly # or --daily; narrow with --since 6h or --m
62
62
  copilot-relay cache --json
63
63
  ```
64
64
 
65
- Check your Copilot plan and quota with `copilot-relay usage`; add `--json` for
66
- scripts. It asks GitHub with the stored token, so no relay needs to run.
65
+ Check your Copilot plan and quota with `copilot-relay usage`; add `--json` for scripts. It asks GitHub
66
+ with the stored token, so no relay needs to run. Tab completion: `eval "$(copilot-relay completion zsh)"` in `~/.zshrc`.
67
67
 
68
68
  ## Go further
69
69
 
@@ -71,7 +71,9 @@ scripts. It asks GitHub with the stored token, so no relay needs to run.
71
71
 
72
72
  - [Configure models and deep checks](wiki/EN-Configuration.md) · [中文](wiki/ZH-Configuration.md)
73
73
  - Run at login: [macOS](wiki/EN-macOS-LaunchAgent.md) · [Windows](wiki/EN-Windows-Service.md) · [Linux](wiki/EN-Linux-systemd.md)
74
- - [Commands](wiki/EN-Commands.md) · [Prompt caching](wiki/EN-Prompt-Caching.md) · [Troubleshoot](wiki/EN-Logging-Troubleshooting.md) · [Understand the architecture](wiki/EN-Architecture.md) · [Contribute](wiki/EN-Development.md)
74
+ - [Commands](wiki/EN-Commands.md) · [GitHub Copilot app](wiki/EN-Copilot-App.md) · [Prompt caching](wiki/EN-Prompt-Caching.md) · [Troubleshoot](wiki/EN-Logging-Troubleshooting.md) · [Understand the architecture](wiki/EN-Architecture.md) · [Contribute](wiki/EN-Development.md)
75
75
 
76
+ **Personal use only.** All forwarded usage runs on your own Copilot seat and limits; never let another person use your relay
77
+ ([why](wiki/EN-Configuration.md#personal-use-only) · [中文](wiki/ZH-Configuration.md#仅限个人使用)).
76
78
  Unofficial research project; not affiliated with GitHub, Anthropic or OpenAI. Upstream services and
77
79
  compatibility can change; model and tool support are not guaranteed (see the Wiki). [MIT licensed](LICENSE).
package/dist/main.js CHANGED
@@ -5554,7 +5554,7 @@ async function* translateResponsesStreamToChatCompletionStream(responseStream) {
5554
5554
  }
5555
5555
  if (event.type === "response.completed" || event.type === "response.incomplete") {
5556
5556
  if (!event.response) throw new Error("Upstream terminal event is missing its response.");
5557
- const completion = translateResponsesToChatCompletion({
5557
+ const completion$1 = translateResponsesToChatCompletion({
5558
5558
  ...event.response,
5559
5559
  status: event.type === "response.incomplete" ? "incomplete" : event.response.status ?? "completed",
5560
5560
  output: event.response.output ?? []
@@ -5583,7 +5583,7 @@ async function* translateResponsesStreamToChatCompletionStream(responseStream) {
5583
5583
  model: event.response.model
5584
5584
  }, {
5585
5585
  delta: {},
5586
- finishReason: completion.choices[0]?.finish_reason,
5586
+ finishReason: completion$1.choices[0]?.finish_reason,
5587
5587
  usage: translateUsage(event.response.usage)
5588
5588
  });
5589
5589
  completed = true;
@@ -10020,7 +10020,15 @@ const effortDescriptions = {
10020
10020
  xhigh: "Extra high reasoning depth for complex problems",
10021
10021
  max: "Maximum reasoning depth for the hardest problems"
10022
10022
  };
10023
- const codexContextWindow = 272e3;
10023
+ const contextWindows = (model) => {
10024
+ const limits = model.capabilities?.limits;
10025
+ if (limits === void 0) return {};
10026
+ const roomBesideReply = limits.max_context_window_tokens - limits.max_output_tokens;
10027
+ return {
10028
+ context_window: roomBesideReply > 0 ? Math.min(limits.max_prompt_tokens, roomBesideReply) : limits.max_prompt_tokens,
10029
+ max_context_window: limits.max_prompt_tokens
10030
+ };
10031
+ };
10024
10032
  const isRecord$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10025
10033
  const readVendorFile = async (name) => {
10026
10034
  let currentDir = dirname(fileURLToPath(import.meta.url));
@@ -10056,7 +10064,6 @@ const generatedEntry = (model, priority, prompt) => {
10056
10064
  description: effortDescriptions[effort]
10057
10065
  }));
10058
10066
  const defaultLevel = levels.find((level) => level.effort === "medium") ?? levels[0];
10059
- const maxPrompt = model.capabilities?.limits?.max_prompt_tokens;
10060
10067
  return {
10061
10068
  slug: model.id,
10062
10069
  display_name: displayName(model),
@@ -10076,10 +10083,7 @@ const generatedEntry = (model, priority, prompt) => {
10076
10083
  apply_patch_tool_type: "freeform",
10077
10084
  supports_parallel_tool_calls: true,
10078
10085
  input_modalities: ["text", "image"],
10079
- ...maxPrompt !== void 0 && {
10080
- context_window: Math.min(codexContextWindow, maxPrompt),
10081
- max_context_window: maxPrompt
10082
- },
10086
+ ...contextWindows(model),
10083
10087
  model_messages: { instructions_template: prompt }
10084
10088
  };
10085
10089
  };
@@ -10087,8 +10091,8 @@ const generatedEntry = (model, priority, prompt) => {
10087
10091
  * The catalog for these models, in order: the first is Codex's default.
10088
10092
  *
10089
10093
  * A model Codex ships keeps Codex's own entry, so its tuned instructions and settings are unchanged;
10090
- * only its position and visibility change. Any other model, such as a Claude model, gets a generated
10091
- * entry.
10094
+ * only its position, visibility and context window change, the window to the one Copilot allows. Any
10095
+ * other model, such as a Claude model, gets a generated entry.
10092
10096
  */
10093
10097
  const buildCodexCatalog = (models$1, vendor) => {
10094
10098
  const seen = /* @__PURE__ */ new Set();
@@ -10101,7 +10105,8 @@ const buildCodexCatalog = (models$1, vendor) => {
10101
10105
  entries.push(bundled ? {
10102
10106
  ...bundled,
10103
10107
  visibility: "list",
10104
- priority
10108
+ priority,
10109
+ ...contextWindows(model)
10105
10110
  } : generatedEntry(model, priority, vendor.prompt));
10106
10111
  }
10107
10112
  return { models: entries };
@@ -10675,7 +10680,7 @@ const routesToTier = (name, tier) => name.toLowerCase().includes("opus") === (ti
10675
10680
  * claude-sonnet-relay. Each tier therefore has its own name. The relay sends every model name without "opus"
10676
10681
  * to gptModel and every one with it to opusModel, so the route reaches the same upstream model. The
10677
10682
  * route names no real Claude model, so the app and its Claude Code take none of that model's
10678
- * built-in context window or tuning; supports1m on the entry says what the window is.
10683
+ * built-in context window or tuning; supports1m and prefer1m on the entry say what the window is.
10679
10684
  */
10680
10685
  const appModelName = (model) => looksAnthropic(model.id) && routesToTier(model.id, model.tier) ? model.id : `claude-${model.tier}-relay`;
10681
10686
  const inferenceModel = (model) => {
@@ -10685,7 +10690,10 @@ const inferenceModel = (model) => {
10685
10690
  return {
10686
10691
  name,
10687
10692
  ...label ? { labelOverride: label } : {},
10688
- ...promptTokens >= 1e6 ? { supports1m: true } : {},
10693
+ ...promptTokens >= 1e6 ? {
10694
+ supports1m: true,
10695
+ prefer1m: true
10696
+ } : {},
10689
10697
  anthropicFamilyTier: model.tier
10690
10698
  };
10691
10699
  };
@@ -11553,6 +11561,533 @@ const usage = defineCommand({
11553
11561
  }
11554
11562
  });
11555
11563
 
11564
+ //#endregion
11565
+ //#region src/lib/completion.ts
11566
+ const completionShells = [
11567
+ "zsh",
11568
+ "bash",
11569
+ "fish",
11570
+ "powershell"
11571
+ ];
11572
+ const isCompletionShell = (value) => completionShells.includes(value);
11573
+ const buildCompletionSpec = (commands, hints) => ({ commands: Object.entries(commands).map(([name, command]) => {
11574
+ const args = Object.entries(command.args ?? {});
11575
+ const options = args.filter(([, definition]) => definition.type !== "positional").map(([optionName, definition]) => {
11576
+ const values = hints[`${name} --${optionName}`];
11577
+ const option = {
11578
+ name: optionName,
11579
+ description: definition.description ?? "",
11580
+ takesValue: definition.type === "string"
11581
+ };
11582
+ if (values !== void 0) option.values = values;
11583
+ return option;
11584
+ });
11585
+ const hasPositional = args.some(([, definition]) => definition.type === "positional");
11586
+ return {
11587
+ name,
11588
+ description: command.meta?.description ?? "",
11589
+ options,
11590
+ positional: hasPositional ? hints[`${name} <>`] : void 0
11591
+ };
11592
+ }) });
11593
+ /**
11594
+ * gptModel and opusModel from config.yaml, for completing a model option. Reads the file without
11595
+ * creating or rewriting it, and gives no models rather than an error when it is missing or cannot
11596
+ * be read: a completion must never print a failure into the command line being typed.
11597
+ */
11598
+ const completionModels = async () => {
11599
+ try {
11600
+ const config = await readExistingAppConfig();
11601
+ if (config === void 0) return [];
11602
+ return [...new Set([config.gptModel, config.opusModel].filter((model) => model !== ""))];
11603
+ } catch {
11604
+ return [];
11605
+ }
11606
+ };
11607
+ const plainDescription = (text$1) => text$1.replace(/[$`\\]/g, "").replace(/\s+/g, " ").trim();
11608
+ const singleQuotePosix = (text$1) => `'${text$1.replaceAll("'", "'\\''")}'`;
11609
+ const singleQuoteFish = (text$1) => `'${text$1.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
11610
+ const singleQuotePowerShell = (text$1) => `'${text$1.replaceAll("'", "''")}'`;
11611
+ const valueOptions = (spec) => [...new Set(spec.commands.flatMap((command) => command.options.filter((option) => option.takesValue).map((option) => `--${option.name}`)))];
11612
+ const modelsCommand = "copilot-relay completion --models";
11613
+ const renderZsh = (spec) => {
11614
+ const zshDescription = (text$1) => plainDescription(text$1).replaceAll("[", "(").replaceAll("]", ")");
11615
+ const zshValues = (label, values) => {
11616
+ if (values === void 0) return `:${label}: `;
11617
+ if (values.kind === "words") return `:${label}:(${values.words.join(" ")})`;
11618
+ if (values.kind === "models") return `:${label}:_copilot_relay_models`;
11619
+ return `:${label}:_files -/`;
11620
+ };
11621
+ return `#compdef copilot-relay
11622
+ # zsh completion for copilot-relay. Generated by \`copilot-relay completion zsh\`.
11623
+
11624
+ _copilot_relay_models() {
11625
+ local -a models
11626
+ models=(\${(f)"$(${modelsCommand} 2>/dev/null)"})
11627
+ _describe -t models 'model' models
11628
+ }
11629
+
11630
+ _copilot_relay() {
11631
+ local -a commands
11632
+ commands=(
11633
+ ${spec.commands.map((command) => ` ${singleQuotePosix(`${command.name}:${plainDescription(command.description)}`)}`).join("\n")}
11634
+ )
11635
+
11636
+ if (( CURRENT == 2 )); then
11637
+ _describe -t commands 'copilot-relay command' commands
11638
+ _arguments '--help[Show help]' '--version[Show the version]'
11639
+ return
11640
+ fi
11641
+
11642
+ local command=\${words[2]}
11643
+ shift 1 words
11644
+ (( CURRENT-- ))
11645
+
11646
+ case $command in
11647
+ ${spec.commands.map((command) => {
11648
+ const specs = command.options.map((option) => {
11649
+ if (option.takesValue) return singleQuotePosix(`--${option.name}=[${zshDescription(option.description)}]${zshValues(option.name, option.values)}`);
11650
+ return singleQuotePosix(`--${option.name}[${zshDescription(option.description)}]`);
11651
+ });
11652
+ specs.push(singleQuotePosix("--help[Show help for this command]"));
11653
+ if (command.positional !== void 0) specs.push(singleQuotePosix(`*${zshValues("argument", command.positional)}`));
11654
+ return [
11655
+ ` (${command.name})`,
11656
+ ` _arguments -s ${specs.join(" \\\n ")}`,
11657
+ " ;;"
11658
+ ].join("\n");
11659
+ }).join("\n")}
11660
+ esac
11661
+ }
11662
+
11663
+ # Autoloaded from fpath, this file is the body of _copilot_relay; sourced or evaluated, it registers
11664
+ # the function with compinit's compdef.
11665
+ if [[ \${funcstack[1]} == _copilot_relay ]]; then
11666
+ _copilot_relay "$@"
11667
+ elif (( \${+functions[compdef]} )); then
11668
+ compdef _copilot_relay copilot-relay
11669
+ else
11670
+ print -u2 "copilot-relay completion: run compinit before loading this script"
11671
+ fi
11672
+ `;
11673
+ };
11674
+ const renderBash = (spec) => {
11675
+ const reply = (values, indent) => {
11676
+ if (values === void 0) return [`${indent}return 0`];
11677
+ if (values.kind === "words") return [`${indent}_copilot_relay_offer ${values.words.map(singleQuotePosix).join(" ")}`, `${indent}return 0`];
11678
+ if (values.kind === "models") return [`${indent}_copilot_relay_offer_quoted < <(_copilot_relay_models)`, `${indent}return 0`];
11679
+ return [`${indent}_copilot_relay_offer_directories`, `${indent}return 0`];
11680
+ };
11681
+ const commandCases = spec.commands.map((command) => {
11682
+ const lines = [` ${command.name})`];
11683
+ const valueOptionsOfCommand = command.options.filter((option) => option.takesValue);
11684
+ if (valueOptionsOfCommand.length > 0) {
11685
+ lines.push(" case $option in");
11686
+ for (const option of valueOptionsOfCommand) lines.push(` --${option.name})`, ...reply(option.values, " "), " ;;");
11687
+ lines.push(" esac");
11688
+ }
11689
+ if (command.positional !== void 0) lines.push(" if [[ $cur != -* ]]; then", ...reply(command.positional, " "), " fi");
11690
+ const options = [...command.options.map((option) => `--${option.name}`), "--help"];
11691
+ lines.push(` _copilot_relay_offer ${options.map(singleQuotePosix).join(" ")}`, " ;;");
11692
+ return lines.join("\n");
11693
+ });
11694
+ const topLevel = [
11695
+ ...spec.commands.map((command) => command.name),
11696
+ "--help",
11697
+ "--version"
11698
+ ];
11699
+ return `# bash completion for copilot-relay. Generated by \`copilot-relay completion bash\`.
11700
+
11701
+ _copilot_relay_models() {
11702
+ ${modelsCommand} 2>/dev/null
11703
+ }
11704
+
11705
+ # Offers each argument that starts with the word being completed. A case pattern compares the
11706
+ # quoted word as text, so neither the candidate nor the typed word is expanded.
11707
+ _copilot_relay_offer() {
11708
+ local candidate
11709
+ for candidate in "$@"; do
11710
+ case $candidate in
11711
+ "$cur"*)
11712
+ COMPREPLY+=("$candidate")
11713
+ ;;
11714
+ esac
11715
+ done
11716
+ }
11717
+
11718
+ # Offers each line of standard input that starts with the word being completed, escaped with
11719
+ # printf %q: bash inserts a completion as typed text, so an unescaped $(...) in a model name would
11720
+ # run when the line is entered.
11721
+ _copilot_relay_offer_quoted() {
11722
+ local candidate
11723
+ while IFS= read -r candidate; do
11724
+ case $candidate in
11725
+ "$cur"*)
11726
+ if [[ -n $candidate ]]; then
11727
+ COMPREPLY+=("$(printf '%q' "$candidate")")
11728
+ fi
11729
+ ;;
11730
+ esac
11731
+ done
11732
+ }
11733
+
11734
+ # Offers directories, escaped for the command line and ending in /, so a name with a space stays
11735
+ # one argument and the next Tab goes inside it.
11736
+ _copilot_relay_offer_directories() {
11737
+ local directory
11738
+ while IFS= read -r directory; do
11739
+ COMPREPLY+=("$(printf '%q' "$directory")/")
11740
+ done < <(compgen -d -- "$cur")
11741
+
11742
+ if type compopt >/dev/null 2>&1; then
11743
+ compopt -o nospace
11744
+ fi
11745
+ }
11746
+
11747
+ _copilot_relay() {
11748
+ local cur option command index word
11749
+ cur=\${COMP_WORDS[COMP_CWORD]}
11750
+ COMPREPLY=()
11751
+
11752
+ # The option whose value is being completed. bash 3.2 keeps "--since=6" as one word, and
11753
+ # readline replaces only the text after the =, so the value alone is completed. Later bash
11754
+ # splits it into "--since", "=" and "6", so the option is the word before the "=".
11755
+ option=\${COMP_WORDS[COMP_CWORD-1]}
11756
+ if [[ $cur == --*=* ]]; then
11757
+ option=\${cur%%=*}
11758
+ cur=\${cur#*=}
11759
+ elif [[ $option == = && COMP_CWORD -ge 2 ]]; then
11760
+ option=\${COMP_WORDS[COMP_CWORD-2]}
11761
+ fi
11762
+
11763
+ if [[ $cur == = ]]; then
11764
+ cur=
11765
+ fi
11766
+
11767
+ # The command is the first word that is neither an option nor an option's value.
11768
+ command=
11769
+ index=1
11770
+ while (( index < COMP_CWORD )); do
11771
+ word=\${COMP_WORDS[index]}
11772
+ case $word in
11773
+ ${valueOptions(spec).length === 0 ? "" : ` ${valueOptions(spec).join("|")})
11774
+ if [[ \${COMP_WORDS[index+1]} == = ]]; then
11775
+ index=$(( index + 3 ))
11776
+ else
11777
+ index=$(( index + 2 ))
11778
+ fi
11779
+
11780
+ continue
11781
+ ;;
11782
+ `} -*)
11783
+ ;;
11784
+ *)
11785
+ command=$word
11786
+ break
11787
+ ;;
11788
+ esac
11789
+
11790
+ index=$(( index + 1 ))
11791
+ done
11792
+
11793
+ if [[ -z $command ]]; then
11794
+ _copilot_relay_offer ${topLevel.map(singleQuotePosix).join(" ")}
11795
+ return 0
11796
+ fi
11797
+
11798
+ case $command in
11799
+ ${commandCases.join("\n")}
11800
+ esac
11801
+ }
11802
+
11803
+ complete -F _copilot_relay copilot-relay
11804
+ `;
11805
+ };
11806
+ const renderFish = (spec) => {
11807
+ const fishValues = (values) => {
11808
+ if (values === void 0) return "";
11809
+ if (values.kind === "words") return ` -a ${singleQuoteFish(values.words.join(" "))}`;
11810
+ if (values.kind === "models") return ` -a '(${modelsCommand} 2>/dev/null)'`;
11811
+ return " -a '(__fish_complete_directories)'";
11812
+ };
11813
+ const commandLines = spec.commands.map((command) => {
11814
+ const condition = `__copilot_relay_using ${command.name}`;
11815
+ const lines = [`complete -c copilot-relay -n '__copilot_relay_using' -a ${command.name} -d ${singleQuoteFish(plainDescription(command.description))}`];
11816
+ for (const option of command.options) {
11817
+ const value = option.takesValue ? ` -r${fishValues(option.values)}` : "";
11818
+ lines.push(`complete -c copilot-relay -n '${condition}' -l ${option.name}${value} -d ${singleQuoteFish(plainDescription(option.description))}`);
11819
+ }
11820
+ lines.push(`complete -c copilot-relay -n '${condition}' -l help -d 'Show help for this command'`);
11821
+ if (command.positional !== void 0) lines.push(`complete -c copilot-relay -n '${condition}'${fishValues(command.positional)}`);
11822
+ return lines.join("\n");
11823
+ });
11824
+ return `# fish completion for copilot-relay. Generated by \`copilot-relay completion fish\`.
11825
+
11826
+ # Prints the command word: the first word after copilot-relay that is neither an option nor the
11827
+ # value of an option that takes one.
11828
+ function __copilot_relay_command
11829
+ set -l words (commandline -opc)
11830
+ set -e words[1]
11831
+ set -l skip_next 0
11832
+ for word in $words
11833
+ if test $skip_next = 1
11834
+ set skip_next 0
11835
+ continue
11836
+ end
11837
+
11838
+ if string match -q -- '--*=*' $word
11839
+ continue
11840
+ end
11841
+
11842
+ if string match -q -- '--*' $word
11843
+ if contains -- (string sub -s 3 -- $word) ${valueOptions(spec).map((option) => option.slice(2)).join(" ")}
11844
+ set skip_next 1
11845
+ end
11846
+
11847
+ continue
11848
+ end
11849
+
11850
+ echo $word
11851
+ return 0
11852
+ end
11853
+
11854
+ return 1
11855
+ end
11856
+
11857
+ # True when the command word is the given one, or, with no argument, when there is none yet.
11858
+ function __copilot_relay_using
11859
+ set -l command (__copilot_relay_command)
11860
+ if test (count $argv) -eq 0
11861
+ test -z "$command"
11862
+ return
11863
+ end
11864
+
11865
+ test "$command" = $argv[1]
11866
+ end
11867
+
11868
+ complete -c copilot-relay -f
11869
+ complete -c copilot-relay -n '__copilot_relay_using' -l help -d 'Show help'
11870
+ complete -c copilot-relay -n '__copilot_relay_using' -l version -d 'Show the version'
11871
+
11872
+ ${commandLines.join("\n\n")}
11873
+ `;
11874
+ };
11875
+ const renderPowerShell = (spec) => {
11876
+ const valuesLiteral = (values) => {
11877
+ if (values === void 0) return "$null";
11878
+ if (values.kind === "words") return `@(${values.words.map(singleQuotePowerShell).join(", ")})`;
11879
+ return singleQuotePowerShell(values.kind);
11880
+ };
11881
+ return `# PowerShell completion for copilot-relay. Generated by \`copilot-relay completion powershell\`.
11882
+
11883
+ $script:CopilotRelayCommands = [ordered]@{
11884
+ ${spec.commands.map((command) => {
11885
+ const options = command.options.map((option) => ` ${singleQuotePowerShell(`--${option.name}`)} = @{ TakesValue = $${option.takesValue}; Values = ${valuesLiteral(option.values)}; Description = ${singleQuotePowerShell(plainDescription(option.description) || option.name)} }`);
11886
+ return [
11887
+ ` ${singleQuotePowerShell(command.name)} = @{`,
11888
+ ` Description = ${singleQuotePowerShell(plainDescription(command.description) || command.name)}`,
11889
+ ` Positional = ${valuesLiteral(command.positional)}`,
11890
+ " Options = [ordered]@{",
11891
+ ...options,
11892
+ " }",
11893
+ " }"
11894
+ ].join("\n");
11895
+ }).join("\n")}
11896
+ }
11897
+
11898
+ Register-ArgumentCompleter -Native -CommandName copilot-relay -ScriptBlock {
11899
+ param($wordToComplete, $commandAst, $cursorPosition)
11900
+
11901
+ # Text PowerShell would read differently is inserted in single quotes, so a model name or a path
11902
+ # with a space or a $( stays one literal argument.
11903
+ $quote = {
11904
+ param($text)
11905
+ if ($text -match "^[A-Za-z0-9._/\\\\:+-]+$") {
11906
+ return $text
11907
+ }
11908
+
11909
+ return "'" + ($text -replace "'", "''") + "'"
11910
+ }
11911
+
11912
+ # The words before the one being completed. An element that holds the cursor is the word being
11913
+ # completed, and an element after the cursor is not part of the question.
11914
+ $prior = @()
11915
+ $elements = @($commandAst.CommandElements | Select-Object -Skip 1)
11916
+ foreach ($element in $elements) {
11917
+ if ($element.Extent.EndOffset -ge $cursorPosition) {
11918
+ break
11919
+ }
11920
+
11921
+ $prior += $element.Extent.Text
11922
+ }
11923
+
11924
+ # The command is the first word that is neither an option nor an option's value.
11925
+ $command = $null
11926
+ $index = 0
11927
+ while ($index -lt $prior.Count) {
11928
+ $word = $prior[$index]
11929
+ if ($word.StartsWith('-')) {
11930
+ if ($null -ne $command -and -not $word.Contains('=')) {
11931
+ $known = $script:CopilotRelayCommands[$command].Options[$word]
11932
+ if ($null -ne $known -and $known.TakesValue) {
11933
+ $index += 1
11934
+ }
11935
+ }
11936
+ } elseif ($null -eq $command) {
11937
+ $command = $word
11938
+ }
11939
+
11940
+ $index += 1
11941
+ }
11942
+
11943
+ # "--since=2" completes the value after the =, and the inserted text keeps the option.
11944
+ $current = $wordToComplete
11945
+ $joined = ''
11946
+ $option = $null
11947
+ if ($null -ne $command -and $current -match '^(--[^=]+)=(.*)$') {
11948
+ $joined = $Matches[1] + '='
11949
+ $option = $script:CopilotRelayCommands[$command].Options[$Matches[1]]
11950
+ $current = $Matches[2]
11951
+ } elseif ($null -ne $command -and $prior.Count -gt 0) {
11952
+ $option = $script:CopilotRelayCommands[$command].Options[$prior[$prior.Count - 1]]
11953
+ }
11954
+
11955
+ $resolve = {
11956
+ param($values)
11957
+ if ($values -is [array]) {
11958
+ return $values | ForEach-Object { @{ Text = $_; Insert = $_; Tip = $_ } }
11959
+ }
11960
+
11961
+ if ($values -eq 'models') {
11962
+ return @(${modelsCommand} 2>$null) | Where-Object { $_ -ne '' } | ForEach-Object { @{ Text = $_; Insert = (& $quote $_); Tip = $_ } }
11963
+ }
11964
+
11965
+ if ($values -eq 'directories') {
11966
+ # The typed path up to its last separator stays as typed; directories are listed inside it.
11967
+ $cut = [Math]::Max($current.LastIndexOf('/'), $current.LastIndexOf('\\'))
11968
+ $prefix = ''
11969
+ $parent = '.'
11970
+ if ($cut -ge 0) {
11971
+ $prefix = $current.Substring(0, $cut + 1)
11972
+ $parent = $prefix
11973
+ }
11974
+
11975
+ return Get-ChildItem -LiteralPath $parent -Directory -ErrorAction SilentlyContinue | ForEach-Object {
11976
+ $path = $prefix + $_.Name + '/'
11977
+ @{ Text = $path; Insert = (& $quote $path); Tip = $_.FullName }
11978
+ }
11979
+ }
11980
+
11981
+ return @()
11982
+ }
11983
+
11984
+ $candidates = @()
11985
+ if ($null -eq $command -or -not $script:CopilotRelayCommands.Contains($command)) {
11986
+ foreach ($name in $script:CopilotRelayCommands.Keys) {
11987
+ $candidates += @{ Text = $name; Insert = $name; Tip = $script:CopilotRelayCommands[$name].Description }
11988
+ }
11989
+
11990
+ $candidates += @{ Text = '--help'; Insert = '--help'; Tip = 'Show help' }
11991
+ $candidates += @{ Text = '--version'; Insert = '--version'; Tip = 'Show the version' }
11992
+ } else {
11993
+ $entry = $script:CopilotRelayCommands[$command]
11994
+ if ($null -ne $option -and $option.TakesValue) {
11995
+ $candidates = @(& $resolve $option.Values)
11996
+ } elseif (-not $current.StartsWith('-') -and $null -ne $entry.Positional) {
11997
+ $candidates = @(& $resolve $entry.Positional)
11998
+ } else {
11999
+ foreach ($name in $entry.Options.Keys) {
12000
+ $candidates += @{ Text = $name; Insert = $name; Tip = $entry.Options[$name].Description }
12001
+ }
12002
+
12003
+ $candidates += @{ Text = '--help'; Insert = '--help'; Tip = 'Show help for this command' }
12004
+ }
12005
+ }
12006
+
12007
+ # A prefix comparison, not -like: a typed [ or * is text, not a wildcard.
12008
+ $candidates | Where-Object { $_.Text.StartsWith($current, [System.StringComparison]::OrdinalIgnoreCase) } | ForEach-Object {
12009
+ $insert = $joined + $_.Insert
12010
+ [System.Management.Automation.CompletionResult]::new($insert, $_.Text, 'ParameterValue', $_.Tip)
12011
+ }
12012
+ }
12013
+ `;
12014
+ };
12015
+ const renderCompletion = (shell, spec) => {
12016
+ if (shell === "zsh") return renderZsh(spec);
12017
+ if (shell === "bash") return renderBash(spec);
12018
+ if (shell === "fish") return renderFish(spec);
12019
+ return renderPowerShell(spec);
12020
+ };
12021
+
12022
+ //#endregion
12023
+ //#region src/completion.ts
12024
+ const completionHints = {
12025
+ "setup <>": {
12026
+ kind: "words",
12027
+ words: [...setupTargets]
12028
+ },
12029
+ "completion <>": {
12030
+ kind: "words",
12031
+ words: [...completionShells]
12032
+ },
12033
+ "replay <>": { kind: "directories" },
12034
+ "models --model": { kind: "models" },
12035
+ "cache --model": { kind: "models" },
12036
+ "cache --since": {
12037
+ kind: "words",
12038
+ words: [
12039
+ "6h",
12040
+ "24h",
12041
+ "2d",
12042
+ "7d"
12043
+ ]
12044
+ }
12045
+ };
12046
+ const completion = defineCommand({
12047
+ meta: {
12048
+ name: "completion",
12049
+ description: `Print a shell completion script for ${completionShells.join(", ")}.`
12050
+ },
12051
+ args: {
12052
+ shell: {
12053
+ type: "positional",
12054
+ required: false,
12055
+ description: `Shell to complete: ${completionShells.join(", ")}.`
12056
+ },
12057
+ models: {
12058
+ type: "boolean",
12059
+ description: "Print gptModel and opusModel from config.yaml, one per line, for a completion script."
12060
+ }
12061
+ },
12062
+ async run({ args }) {
12063
+ if (args.models) {
12064
+ for (const model of await completionModels()) console.log(model);
12065
+ return;
12066
+ }
12067
+ const shell = typeof args.shell === "string" ? args.shell : "";
12068
+ if (!isCompletionShell(shell)) {
12069
+ console.error(`Name a shell: copilot-relay completion <${completionShells.join("|")}>.`);
12070
+ process.exitCode = 1;
12071
+ return;
12072
+ }
12073
+ process.stdout.write(renderCompletion(shell, await buildCompletionSpec$1()));
12074
+ }
12075
+ });
12076
+ const completionCommands = () => ({
12077
+ auth,
12078
+ cache,
12079
+ models,
12080
+ replay,
12081
+ restart,
12082
+ setup,
12083
+ start,
12084
+ status,
12085
+ stop,
12086
+ usage,
12087
+ completion
12088
+ });
12089
+ const buildCompletionSpec$1 = async () => buildCompletionSpec(completionCommands(), completionHints);
12090
+
11556
12091
  //#endregion
11557
12092
  //#region src/main.ts
11558
12093
  await runMain(defineCommand({
@@ -11570,7 +12105,8 @@ await runMain(defineCommand({
11570
12105
  start,
11571
12106
  status,
11572
12107
  stop,
11573
- usage
12108
+ usage,
12109
+ completion
11574
12110
  }
11575
12111
  }));
11576
12112