├── useragents ├── src │ ├── __init__.py │ ├── custom_agents │ │ ├── __init__.py │ │ └── web_search_tool.py │ ├── models.py │ ├── registry.py │ └── current_time.py ├── README.md ├── docker-compose.yaml ├── pyproject.toml ├── makefile ├── Dockerfile └── main.py ├── milla.png ├── shell.nix ├── plugins ├── hello.lua ├── proxy_test.lua ├── rss.yaml ├── test.lua ├── repology.lua ├── ip.lua ├── robtex.lua ├── urban.lua ├── euvd.lua └── rss.lua ├── Dockerfile_distroless ├── Dockerfile_distroless_vendored ├── .github └── workflows │ ├── go_build.yaml │ └── docker.yaml ├── Dockerfile_scratch_vendored ├── Dockerfile ├── Dockerfile_debug ├── scripts └── entry_limit_trigger.sql ├── .gitignore ├── docker-compose.yaml ├── makefile ├── .golangci.yml ├── utils.go ├── iana_whois.go ├── useragents.go ├── docker-compose-postgres.yaml ├── go.mod ├── defaults.go ├── config-example.toml ├── openai.go ├── openrouter.go ├── rss.go ├── gemini.go ├── ollama.go ├── ghost.go ├── types.go ├── go.sum ├── plugins.go ├── main.go └── LICENSE /useragents/src/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /useragents/src/custom_agents/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /useragents/README.md: -------------------------------------------------------------------------------- 1 | # milla user agents 2 | -------------------------------------------------------------------------------- /milla.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/terminaldweller/milla/HEAD/milla.png -------------------------------------------------------------------------------- /shell.nix: -------------------------------------------------------------------------------- 1 | { pkgs ? import {} }: 2 | pkgs.mkShell { 3 | nativeBuildInputs = with pkgs.buildPackages; [ pgformatter ]; 4 | } 5 | -------------------------------------------------------------------------------- /plugins/hello.lua: -------------------------------------------------------------------------------- 1 | local milla = require("milla") 2 | 3 | function hello() milla.reply_to("hello") end 4 | 5 | milla.register_cmd("/plugins/hello.lua", "hello", "hello") 6 | -------------------------------------------------------------------------------- /useragents/src/models.py: -------------------------------------------------------------------------------- 1 | import pydantic 2 | 3 | 4 | class AgentRequest(pydantic.BaseModel): 5 | agent_name: str 6 | instructions: str 7 | query: str 8 | 9 | 10 | class AgentResponse(pydantic.BaseModel): 11 | agent_name: str 12 | response: str 13 | -------------------------------------------------------------------------------- /Dockerfile_distroless: -------------------------------------------------------------------------------- 1 | FROM golang:1.24-alpine3.21 AS builder 2 | WORKDIR /milla 3 | COPY go.sum go.mod /milla/ 4 | RUN go mod download 5 | COPY *.go /milla/ 6 | RUN CGO_ENABLED=0 go build 7 | 8 | FROM gcr.io/distroless/static-debian12 9 | COPY --from=builder /milla/milla "/usr/bin/milla" 10 | ENTRYPOINT ["milla"] 11 | -------------------------------------------------------------------------------- /plugins/proxy_test.lua: -------------------------------------------------------------------------------- 1 | local milla = require("milla") 2 | local os = require("os") 3 | local json = require("json") 4 | 5 | os.setenv("ALL_PROXY", "socks5://172.17.0.1:9057") 6 | 7 | local http = require("http") 8 | 9 | local response, err = http.request("GET", "https://icanhazip.com") 10 | print(response.body) 11 | -------------------------------------------------------------------------------- /useragents/src/registry.py: -------------------------------------------------------------------------------- 1 | class AgentRegistry: 2 | def __init__(self): 3 | self.registry = {} 4 | 5 | def __call__(self, func): 6 | self.registry[func.__name__] = func 7 | print(f"Registered agent: {func.__name__}") 8 | return func 9 | 10 | 11 | agentRegistry = AgentRegistry() 12 | -------------------------------------------------------------------------------- /Dockerfile_distroless_vendored: -------------------------------------------------------------------------------- 1 | FROM golang:1.24-alpine3.21 AS builder 2 | WORKDIR /milla 3 | COPY go.sum go.mod /milla/ 4 | COPY vendor /milla/vendor 5 | COPY *.go /milla/ 6 | RUN CGO_ENABLED=0 go build 7 | 8 | FROM gcr.io/distroless/static-debian12 9 | COPY --from=builder /milla/milla "/usr/bin/milla" 10 | ENTRYPOINT ["milla"] 11 | -------------------------------------------------------------------------------- /useragents/docker-compose.yaml: -------------------------------------------------------------------------------- 1 | services: 2 | useragents: 3 | image: useragents 4 | build: 5 | context: . 6 | ports: 7 | - 127.0.0.1:9910:443/tcp 8 | networks: 9 | - uanet 10 | environment: 11 | - OPENAI_API_KEY= 12 | cap_drop: 13 | - ALL 14 | entrypoint: ["/docker-entrypoint.sh"] 15 | networks: 16 | uanet: 17 | -------------------------------------------------------------------------------- /plugins/rss.yaml: -------------------------------------------------------------------------------- 1 | period: 3600 2 | channel: "#rssfeed" 3 | rssfeeds: 4 | - name: "one" 5 | url: "https://www.youtube.com/feeds/videos.xml?channel_id=UCaiL2GDNpLYH6Wokkk1VNcg" 6 | - name: "two" 7 | url: "https://www.youtube.com/feeds/videos.xml?channel_id=UCd26IHBHcbtxD7pUdnIgiCw" 8 | - name: "three" 9 | url: "https://www.youtube.com/feeds/videos.xml?channel_id=UCS4FAVeYW_IaZqAbqhlvxlA" 10 | -------------------------------------------------------------------------------- /.github/workflows/go_build.yaml: -------------------------------------------------------------------------------- 1 | name: Go 2 | on: 3 | push: 4 | branches: [ "main" ] 5 | pull_request: 6 | branches: [ "main" ] 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v4 12 | - name: Set up Go 13 | uses: actions/setup-go@v4 14 | with: 15 | go-version: '1.21' 16 | - name: Build 17 | run: go build -v ./... 18 | -------------------------------------------------------------------------------- /useragents/src/current_time.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | from agents import function_tool 3 | 4 | 5 | @function_tool 6 | def fetch_time(): 7 | """ 8 | Fetches the current time. 9 | """ 10 | 11 | return datetime.now().strftime("%H:%M:%S") 12 | 13 | 14 | @function_tool 15 | def fetch_date(): 16 | """ 17 | Fetches the current date. 18 | """ 19 | 20 | return datetime.now().strftime("%Y-%m-%d") 21 | -------------------------------------------------------------------------------- /Dockerfile_scratch_vendored: -------------------------------------------------------------------------------- 1 | FROM golang:1.24-alpine3.21 AS builder 2 | WORKDIR /milla 3 | COPY go.sum go.mod /milla/ 4 | COPY vendor /milla/vendor 5 | COPY *.go /milla/ 6 | RUN CGO_ENABLED=0 go build 7 | 8 | FROM alpine:3.21 AS cert 9 | RUN apk add --no-cache ca-certificates 10 | 11 | FROM scratch 12 | COPY --from=cert /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ 13 | COPY --from=builder /milla/milla "/milla" 14 | ENTRYPOINT ["/milla"] 15 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.24-alpine3.21 AS builder 2 | WORKDIR /milla 3 | COPY go.sum go.mod /milla/ 4 | RUN go mod download 5 | COPY *.go /milla/ 6 | RUN go build 7 | 8 | FROM alpine:3.21 9 | ENV HOME=/home/user 10 | RUN set -eux; \ 11 | adduser -u 1001 -D -h "$HOME" user; \ 12 | mkdir "$HOME/.irssi"; \ 13 | chown -R user:user "$HOME" 14 | COPY --from=builder /milla/milla "$HOME/milla" 15 | RUN chown user:user "$HOME/milla" 16 | USER user 17 | ENTRYPOINT ["/home/user/milla"] 18 | -------------------------------------------------------------------------------- /Dockerfile_debug: -------------------------------------------------------------------------------- 1 | FROM golang:1.24-alpine3.21 AS builder 2 | WORKDIR /milla 3 | COPY go.sum go.mod /milla/ 4 | COPY vendor /milla/vendor 5 | COPY *.go /milla/ 6 | RUN CGO_ENABLED=0 go build 7 | 8 | FROM golang:1.24-alpine3.21 AS debug 9 | RUN CGO_ENABLED=0 go install -ldflags "-s -w -extldflags '-static'" github.com/go-delve/delve/cmd/dlv@latest 10 | 11 | FROM alpine:3.21 12 | COPY --from=debug /go/bin/dlv /usr/bin/dlv 13 | COPY --from=builder /milla/milla "/usr/bin/milla" 14 | ENTRYPOINT ["/usr/bin/dlv"] 15 | -------------------------------------------------------------------------------- /useragents/src/custom_agents/web_search_tool.py: -------------------------------------------------------------------------------- 1 | from agents import Agent, WebSearchTool 2 | from src.current_time import fetch_date 3 | from src.models import AgentRequest 4 | from src.registry import agentRegistry 5 | 6 | 7 | @agentRegistry 8 | def web_search_tool(agent_request: AgentRequest) -> Agent: 9 | tools = [WebSearchTool(), fetch_date] 10 | 11 | agent = Agent( 12 | name=agent_request.agent_name, 13 | instructions=agent_request.instructions, 14 | tools=tools, 15 | ) 16 | 17 | return agent 18 | -------------------------------------------------------------------------------- /scripts/entry_limit_trigger.sql: -------------------------------------------------------------------------------- 1 | create function remove_old_entries() 2 | returns trigger 3 | as $$ 4 | begin 5 | if( 6 | select 7 | COUNT(*) 8 | from 9 | table_name) > 10000 then 10 | delete from table_name 11 | where id in( 12 | select 13 | id 14 | from 15 | table_name 16 | order by 17 | id asc 18 | limit 1000); 19 | end if; 20 | return null; 21 | end; 22 | $$ 23 | language plpgsql; 24 | 25 | create trigger remove_old_entries_trigger 26 | after insert on table_name for each row 27 | execute procedure remove_old_entries(); 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # If you prefer the allow list template instead of the deny list, see community template: 2 | # https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore 3 | # 4 | # Binaries for programs and plugins 5 | *.exe 6 | *.exe~ 7 | *.dll 8 | *.so 9 | *.dylib 10 | 11 | # Test binary, built with `go test -c` 12 | *.test 13 | 14 | # Output of the go coverage tool, specifically when used with LiteIDE 15 | *.out 16 | 17 | # Dependency directories (remove the comment below to include it) 18 | # vendor/ 19 | 20 | # Go workspace file 21 | go.work 22 | 23 | ,* 24 | 25 | manga.json 26 | ipo.json 27 | anime.json 28 | crypto.json 29 | youtube.json 30 | security.json 31 | term_com_certs.json 32 | Session.vim 33 | dive.log 34 | -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | services: 2 | terra: 3 | image: milla_distroless_vendored 4 | build: 5 | context: . 6 | dockerfile: ./Dockerfile_distroless_vendored 7 | deploy: 8 | resources: 9 | limits: 10 | memory: 128M 11 | logging: 12 | driver: "json-file" 13 | options: 14 | max-size: "100m" 15 | networks: 16 | - terranet 17 | user: 1000:1000 18 | restart: unless-stopped 19 | entrypoint: ["/usr/bin/milla"] 20 | command: ["--config", "/config.toml"] 21 | volumes: 22 | - ./config-omni.toml:/config.toml 23 | - /etc/localtime:/etc/localtime:ro 24 | - ./plugins/:/plugins/:ro 25 | cap_drop: 26 | - ALL 27 | networks: 28 | terranet: 29 | -------------------------------------------------------------------------------- /makefile: -------------------------------------------------------------------------------- 1 | .PHONY: d_test d_deploy d_down d_build help 2 | 3 | IMAGE_NAME=milla 4 | 5 | d_test: 6 | nq docker compose -f ./docker-compose-devi.yaml up --build 7 | 8 | d_deploy: 9 | nq docker compose -f ./docker-compose.yaml up --build 10 | 11 | d_down: 12 | docker compose -f ./docker-compose.yaml down 13 | docker compose -f ./docker-compose-devi.yaml down 14 | 15 | d_build: d_build_distroless_vendored 16 | 17 | d_build_regular: 18 | docker build -t $(IMAGE_NAME)-f ./Dockerfile . 19 | 20 | d_build_distroless: 21 | docker build -t $(IMAGE_NAME) -f ./Dockerfile_distroless . 22 | 23 | d_build_distroless_vendored: 24 | docker build -t $(IMAGE_NAME) -f ./Dockerfile_distroless_vendored . 25 | 26 | help: 27 | @echo "d_test" 28 | @echo "d_deploy" 29 | @echo "d_down" 30 | @echo "d_build" 31 | -------------------------------------------------------------------------------- /plugins/test.lua: -------------------------------------------------------------------------------- 1 | local milla = require("milla") 2 | 3 | local function sleep(n) 4 | local t0 = os.clock() 5 | while os.clock() - t0 <= n do end 6 | end 7 | 8 | local function test_printer() 9 | local config = milla.toml_config.new() 10 | print(config:IrcServer()) 11 | config:IrcServer("irc.libera.chat") 12 | print(config:IrcServer()) 13 | 14 | while true do 15 | milla.send_message(config:IrcServer(), "#warroom") 16 | sleep(5) 17 | end 18 | end 19 | 20 | local function test_query() 21 | local query = 22 | "select log from liberanet_milla_us_market_news order by log desc;" 23 | local result = milla.query_db(query) 24 | 25 | print(result) 26 | 27 | for _, v in ipairs(result) do print(v) end 28 | end 29 | 30 | -- test_printer() 31 | test_query() 32 | -------------------------------------------------------------------------------- /useragents/pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "milla" 3 | version = "0.1.0" 4 | description = "" 5 | authors = [ 6 | {name = "terminaldweller",email = "devi+github@terminaldweller.com"} 7 | ] 8 | license = {text = "GPL-3.0"} 9 | readme = "README.md" 10 | requires-python = ">=3.13" 11 | dependencies = [ 12 | "openai-agents (>=0.0.4,<0.0.5)", 13 | "fastapi (>=0.115.11,<0.116.0)", 14 | "uvicorn (>=0.34.0,<0.35.0)", 15 | "pydantic (>=2.11.3,<3.0.0)", 16 | "playwright (>=1.52.0,<2.0.0)" 17 | ] 18 | 19 | [tool.poetry] 20 | package-mode = false 21 | 22 | [tool.poetry.group.dev.dependencies] 23 | ruff = "^0.11.0" 24 | black = "^25.1.0" 25 | mypy = "^1.15.0" 26 | pylint = "^3.3.5" 27 | bandit = "^1.8.3" 28 | 29 | [build-system] 30 | requires = ["poetry-core>=2.0.0,<3.0.0"] 31 | build-backend = "poetry.core.masonry.api" 32 | -------------------------------------------------------------------------------- /useragents/makefile: -------------------------------------------------------------------------------- 1 | .PHONY: d_test d_down d_build help up down test log 2 | 3 | IMAGE_NAME=useragents 4 | 5 | up: d_test 6 | 7 | down: d_down 8 | 9 | log: 10 | nqtail 11 | 12 | test: 13 | @curl -k -X POST -H 'Content-Type: application/json' --data '{"agent_name": "web_search_tool", "instructions":"you are a web search bot", "query": "make me a cryptocurrency news digest from the news for today please. give me the references for the news you mention."}' https://127.0.0.1:9910/api/v1/agent 14 | 15 | d_test: 16 | nq docker compose -f ./docker-compose-uas.yaml up --build 17 | 18 | d_down: 19 | docker compose -f ./docker-compose-uas.yaml down 20 | 21 | d_build: d_build_regular 22 | 23 | d_build_regular: 24 | docker build -t $(IMAGE_NAME)-f ./Dockerfile . 25 | 26 | help: 27 | @echo "up" 28 | @echo "down" 29 | @echo "test" 30 | @echo "d_test" 31 | @echo "d_down" 32 | @echo "d_build" 33 | -------------------------------------------------------------------------------- /plugins/repology.lua: -------------------------------------------------------------------------------- 1 | local milla = require("milla") 2 | local os = require("os") 3 | local json = require("json") 4 | 5 | -- https://repology.org/api 6 | -- /repology void_x86_64 7 | function repology(arg) 8 | -- os.setenv("http_proxy", "http://172.17.0.1:8120") 9 | 10 | local http = require("http") 11 | 12 | local url = "https://repology.org/api/v1/repository/" .. arg .. "/problems" 13 | 14 | local response = http.request("GET", url) 15 | 16 | io.write(response.body) 17 | 18 | local json_response, err = json.decode(response.body) 19 | io.write(json_response) 20 | if err ~= nil then print(err) end 21 | 22 | for _, item in pairs(json_response) do 23 | for k, v in ipairs(item) do print(k, v) end 24 | end 25 | 26 | local result = "" 27 | for key, value in pairs(json_response) do 28 | result = result .. key .. ": " .. value .. " -- " 29 | end 30 | 31 | return result 32 | end 33 | 34 | milla.register_cmd("/plugins/repology.lua", "repology", "repology") 35 | -------------------------------------------------------------------------------- /plugins/ip.lua: -------------------------------------------------------------------------------- 1 | local milla = require("milla") 2 | local os = require("os") 3 | local json = require("json") 4 | 5 | -- this function should be global 6 | -- one string arg that holds all args 7 | -- should only return one string value 8 | function milla_get_ip(arg) 9 | -- setting the proxy value before loading the http module 10 | -- this way, only this script will be using this proxy 11 | os.setenv("http_proxy", "http://172.17.0.1:8120") 12 | 13 | local http = require("http") 14 | 15 | local url = "http://ip-api.com/json/" .. arg 16 | 17 | print("Requesting: " .. url) 18 | 19 | local response, err = http.request("GET", url) 20 | if err ~= nil then print(err) end 21 | 22 | local json_response, err = json.decode(response.body) 23 | if err ~= nil then print(err) end 24 | for k, v in pairs(json_response) do print(k, v) end 25 | 26 | local result = "" 27 | for key, value in pairs(json_response) do 28 | result = result .. key .. ": " .. value .. " -- " 29 | end 30 | 31 | return result 32 | end 33 | 34 | -- script_path, command_name, function_name 35 | milla.register_cmd("/plugins/ip.lua", "ip", "milla_get_ip") 36 | -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | run: 2 | concurrency: 16 3 | timeout: 5m 4 | modules-download-mode: readonly 5 | allow-parallel-runners: true 6 | allow-serial-runners: true 7 | go: '1.22.3' 8 | linters-settings: 9 | depguard: 10 | rules: 11 | srcs: 12 | listMode: "Strict" 13 | allow: 14 | - $gostd 15 | - github.com/alecthomas/chroma/v2/quick 16 | - github.com/google/generative-ai-go 17 | - github.com/lrstanley/girc 18 | - github.com/sashabaranov/go-openai 19 | - github.com/BurntSushi/toml 20 | - github.com/jackc/pgx/v5 21 | - github.com/jackc/pgx/v5/pgxpool 22 | - github.com/jackc/pgx/v5/pgtype 23 | - github.com/yuin/gopher-lua 24 | - github.com/ailncode/gluaxmlpath 25 | - github.com/cjoudrey/gluahttp 26 | - github.com/kohkimakimoto/gluayaml 27 | - github.com/yuin/gluare 28 | - gitlab.com/megalithic-llc/gluasocket 29 | - github.com/layeh/gopher-json 30 | - github.com/mmcdole/gofeed 31 | - github.com/cenkalti/backoff/v5 32 | - golang.org/x/net/proxy 33 | - google.golang.org/genai 34 | - golang.org/x/net/html 35 | - github.com/ergochat/irc-go/ircmsg 36 | -------------------------------------------------------------------------------- /plugins/robtex.lua: -------------------------------------------------------------------------------- 1 | local milla = require("milla") 2 | local os = require("os") 3 | 4 | -- https://www.robtex.com/api/ 5 | function robtex(cli_args) 6 | local args = {} 7 | for i in string.gmatch(cli_args, "%S+") do table.insert(args, i) end 8 | 9 | os.setenv("http_proxy", "http://172.17.0.1:8120") 10 | 11 | local http = require("http") 12 | 13 | local url_ipquery = "https://freeapi.robtex.com/ipquery/" 14 | local url_asquery = "https://freeapi.robtex.com/asquery/" 15 | local url_pdns_forward = "https://freeapi.robtex.com/pdns/forward/" 16 | local url_rpns_reverse = "https://freeapi.robtex.com/pdns/reverse" 17 | 18 | local url 19 | 20 | if args[1] == "ipquery" then 21 | url = url_ipquery .. args[2] 22 | elseif args[1] == "asquery" then 23 | url = url_asquery .. args[2] 24 | elseif args[1] == "pdns_forward" then 25 | url = url_pdns_forward .. args[2] 26 | elseif args[1] == "pdns_reverse" then 27 | url = url_rpns_reverse .. args[2] 28 | else 29 | return "Invalid command" 30 | end 31 | 32 | local response = http.request("GET", url) 33 | 34 | io.write(response.body) 35 | 36 | return response.body 37 | end 38 | 39 | milla.register_cmd("/plugins/robtex.lua", "robtex", "robtex") 40 | -------------------------------------------------------------------------------- /useragents/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.13-slim AS python-base 2 | ENV PYTHONUNBUFFERED=1 \ 3 | PYTHONDONTWRITEBYTECODE=1 \ 4 | PIP_NO_CACHE_DIR=off \ 5 | PIP_DISABLE_PIP_VERSION_CHECK=on \ 6 | PIP_DEFAULT_TIMEOUT=100 \ 7 | POETRY_HOME="/poetry" \ 8 | POETRY_VIRTUALENVS_IN_PROJECT=true \ 9 | POETRY_NO_INTERACTION=1 \ 10 | PYSETUP_PATH="/useragent" \ 11 | VENV_PATH="/useragent/.venv" 12 | ENV PATH="$POETRY_HOME/bin:$VENV_PATH/bin:$PATH" 13 | 14 | FROM python-base AS builder-base 15 | ENV POETRY_VERSION=2.1.1 16 | RUN apt-get update && apt-get install -y --no-install-recommends curl build-essential 17 | RUN curl -sSL https://install.python-poetry.org | python - 18 | WORKDIR $PYSETUP_PATH 19 | COPY ./pyproject.toml ./ 20 | RUN poetry install --without dev 21 | 22 | FROM alpine:3.21 AS certbuilder 23 | RUN apk add openssl 24 | WORKDIR /certs 25 | RUN openssl req -nodes -new -x509 -subj="/C=/ST=/L=/O=/CN=useragents" -keyout server.key -out server.cert 26 | 27 | FROM python-base AS production 28 | RUN apt-get update && apt-get install --no-install-recommends -y poppler-utils python3-magic 29 | COPY --from=certbuilder /certs/ $PYSETUP_PATH/ 30 | ENV FASTAPI_ENV=production 31 | COPY --from=builder-base $VENV_PATH $VENV_PATH 32 | COPY ./src $PYSETUP_PATH/src 33 | COPY ./main.py $PYSETUP_PATH/main.py 34 | WORKDIR $PYSETUP_PATH 35 | -------------------------------------------------------------------------------- /utils.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | 7 | "github.com/lrstanley/girc" 8 | ) 9 | 10 | func Min(x, y int) int { 11 | if x < y { 12 | return x 13 | } 14 | return y 15 | } 16 | 17 | func IrcJoin(irc *girc.Client, channel []string) { 18 | if len(channel) > 1 && channel[1] != "" { 19 | irc.Cmd.JoinKey(channel[0], channel[1]) 20 | } else { 21 | irc.Cmd.Join(channel[0]) 22 | } 23 | } 24 | 25 | func chunker(inputString string, chromaFormatter string) []string { 26 | chunks := strings.Split(inputString, "\n") 27 | 28 | switch chromaFormatter { 29 | case "terminal": 30 | fallthrough 31 | case "terminal8": 32 | fallthrough 33 | case "terminal16": 34 | fallthrough 35 | case "terminal256": 36 | for count, chunk := range chunks { 37 | lastColorCode, err := extractLast256ColorEscapeCode(chunk) 38 | if err != nil { 39 | continue 40 | } 41 | 42 | if count <= len(chunks)-2 { 43 | chunks[count+1] = fmt.Sprintf("\033[38;5;%sm", lastColorCode) + chunks[count+1] 44 | } 45 | } 46 | case "terminal16m": 47 | fallthrough 48 | default: 49 | } 50 | 51 | return chunks 52 | } 53 | 54 | func SendToIRC( 55 | client *girc.Client, 56 | event girc.Event, 57 | message string, 58 | chromaFormatter string, 59 | ) { 60 | chunks := chunker(message, chromaFormatter) 61 | 62 | for _, chunk := range chunks { 63 | if len(strings.TrimSpace(chunk)) == 0 { 64 | continue 65 | } 66 | 67 | client.Cmd.Reply(event, chunk) 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /iana_whois.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "net" 6 | "net/http" 7 | "net/url" 8 | "time" 9 | 10 | "golang.org/x/net/html" 11 | "golang.org/x/net/proxy" 12 | ) 13 | 14 | func IANAWhoisGet(query string, appConfig *TomlConfig) string { 15 | var httpClient http.Client 16 | 17 | var dialer proxy.Dialer 18 | 19 | if appConfig.GeneralProxy != "" { 20 | proxyURL, err := url.Parse(appConfig.GeneralProxy) 21 | if err != nil { 22 | log.Fatal(err.Error()) 23 | 24 | return "" 25 | } 26 | 27 | dialer, err = proxy.FromURL(proxyURL, &net.Dialer{Timeout: time.Duration(appConfig.RequestTimeout) * time.Second}) 28 | if err != nil { 29 | log.Fatal(err.Error()) 30 | 31 | return "" 32 | } 33 | 34 | httpClient = http.Client{ 35 | Transport: &http.Transport{ 36 | Dial: dialer.Dial, 37 | }, 38 | } 39 | } 40 | 41 | resp, err := httpClient.Get("https://www.iana.org/whois?q=" + query) 42 | if err != nil { 43 | log.Println(err) 44 | 45 | return "" 46 | } 47 | 48 | defer resp.Body.Close() 49 | 50 | doc, err := html.Parse(resp.Body) 51 | if err != nil { 52 | log.Println(err) 53 | 54 | return "" 55 | } 56 | 57 | var getContent func(*html.Node) string 58 | 59 | getContent = func(n *html.Node) string { 60 | if n.Type == html.ElementNode && n.Data == "pre" { 61 | var content string 62 | for c := n.FirstChild; c != nil; c = c.NextSibling { 63 | if c.Type == html.TextNode { 64 | content += c.Data 65 | } 66 | } 67 | return content 68 | } 69 | for c := n.FirstChild; c != nil; c = c.NextSibling { 70 | result := getContent(c) 71 | if result != "" { 72 | return result 73 | } 74 | } 75 | return "" 76 | } 77 | 78 | preContent := getContent(doc) 79 | log.Println(preContent) 80 | 81 | return preContent 82 | } 83 | -------------------------------------------------------------------------------- /.github/workflows/docker.yaml: -------------------------------------------------------------------------------- 1 | name: Publish Docker image 2 | on: 3 | release: 4 | types: [published] 5 | push: 6 | branches: [ "main" ] 7 | jobs: 8 | push_to_registry: 9 | name: Push Docker image to Docker Hub 10 | runs-on: ubuntu-latest 11 | permissions: 12 | packages: write 13 | contents: read 14 | attestations: write 15 | id-token: write 16 | steps: 17 | - name: Check out the repo 18 | uses: actions/checkout@v4 19 | - name: Set up Docker Buildx 20 | uses: docker/setup-buildx-action@v3 21 | - name: Log in to Docker Hub 22 | uses: docker/login-action@f4ef78c080cd8ba55a85445d5b36e214a81df20a 23 | with: 24 | username: ${{ secrets.DOCKER_USERNAME }} 25 | password: ${{ secrets.DOCKER_PASSWORD }} 26 | - name: Extract metadata (tags, labels) for Docker 27 | id: meta 28 | uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7 29 | with: 30 | images: terminaldweller/milla 31 | - name: Build and push Docker image 32 | id: push 33 | uses: docker/build-push-action@3b5e8027fcad23fda98b2e3ac259d8d67585f671 34 | with: 35 | context: . 36 | file: ./Dockerfile 37 | push: true 38 | sbom: true 39 | tags: ${{ steps.meta.outputs.tags }} 40 | labels: ${{ steps.meta.outputs.labels }} 41 | provenance: mode=max 42 | # - name: Docker Scout 43 | # id: docker-scout 44 | # if: ${{ github.event_name == 'pull_request' }} 45 | # uses: docker/scout-action@v1 46 | # with: 47 | # command: cves 48 | # image: ${{ github.event.repository.name }} 49 | # ignore-unchanged: true 50 | # only-severities: critical,high,medium,low 51 | # write-comment: true 52 | # github-token: ${{ secrets.GITHUB_TOKEN }} 53 | -------------------------------------------------------------------------------- /plugins/urban.lua: -------------------------------------------------------------------------------- 1 | local milla = require("milla") 2 | local os = require("os") 3 | local json = require("json") 4 | 5 | os.setenv("ALL_PROXY", "socks5://172.17.0.1:9004") 6 | 7 | local http = require("http") 8 | 9 | function milla_urban(cli_args) 10 | local args = {} 11 | for i in string.gmatch(cli_args, "%S+") do table.insert(args, i) end 12 | 13 | for k, v in ipairs(args) do print(k, v) end 14 | 15 | local count = 1 16 | local term = "" 17 | 18 | local skip = false 19 | 20 | for i = 1, #args do 21 | if skip then 22 | skip = false 23 | goto continue 24 | end 25 | if args[i] == "-n" then 26 | count = tonumber(args[i + 1]) 27 | skip = true 28 | else 29 | term = term .. args[i] .. " " 30 | end 31 | ::continue:: 32 | end 33 | print("Term: " .. term) 34 | print("Count: " .. count) 35 | 36 | local user_agent = 37 | "Mozilla/5.0 (X11; U; Linux x86_64; pl-PL; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10" 38 | 39 | local escaped_term = milla.url_encode(term) 40 | local url = "http://api.urbandictionary.com/v0/define?term=" .. escaped_term 41 | local response, err = http.request("GET", url, { 42 | timeout = "10s", 43 | headers = { 44 | ["User-Agent"] = user_agent, 45 | ["Accept"] = "application/json", 46 | ["Host"] = "api.urbandictionary.com", 47 | ["Connection"] = "keep-alive", 48 | ["Cache-Control"] = "no-cache", 49 | ["DNT"] = 1, 50 | ["sec-ch-ua-platform"] = "Windows", 51 | ["Pragma"] = "no-cache" 52 | } 53 | }) 54 | if err ~= nil then print(err) end 55 | print(response.body) 56 | 57 | local json_response, err = json.decode(response.body) 58 | if err ~= nil then print(err) end 59 | 60 | if response.status_code ~= 200 then 61 | return "Error: " .. response.status_code 62 | end 63 | 64 | local result = "" 65 | for _, v in ipairs(json_response["list"]) do 66 | for kk, vv in pairs(v) do print(kk, vv) end 67 | if count > 0 then 68 | result = result .. tostring(count) .. " - " .. v["definition"] .. 69 | " ---- " 70 | end 71 | count = count - 1 72 | end 73 | 74 | return result 75 | end 76 | 77 | milla.register_cmd("/plugins/urban.lua", "urban", "milla_urban") 78 | -------------------------------------------------------------------------------- /plugins/euvd.lua: -------------------------------------------------------------------------------- 1 | local milla = require("milla") 2 | local os = require("os") 3 | local json = require("json") 4 | 5 | -- https://euvd.enisa.europa.eu/apidoc 6 | function euvd(cli_args) 7 | local args = {} 8 | for i in string.gmatch(cli_args, "%S+") do table.insert(args, i) end 9 | 10 | os.setenv("http_proxy", "http://172.17.0.1:8120") 11 | 12 | local http = require("http") 13 | local url 14 | 15 | local url_latest = 16 | "https://euvdservices.enisa.europa.eu/api/lastvulnerabilities" 17 | local url_exploited = 18 | "https://euvdservices.enisa.europa.eu/api/exploitedvulnerabilities" 19 | local url_critical = 20 | "https://euvdservices.enisa.europa.eu/api/criticalvulnerabilities" 21 | 22 | if args[1] == "latest" then 23 | url = url_latest 24 | elseif args[1] == "exploited" then 25 | url = url_exploited 26 | elseif args[1] == "critical" then 27 | url = url_critical 28 | else 29 | return "Invalid command" 30 | end 31 | 32 | local response, err = http.request("GET", url, {timeout = "10s"}) 33 | if err ~= nil then 34 | print(err) 35 | return err 36 | end 37 | print(response.body) 38 | 39 | local json_response, err = json.decode(response.body) 40 | if err ~= nil then 41 | print(err) 42 | return err 43 | end 44 | 45 | if response.status_code ~= 200 then 46 | return "Error: " .. response.status_code 47 | end 48 | 49 | local result = "" 50 | for k, v in ipairs(json_response) do 51 | result = result .. "id: " .. v["id"] .. "\n" 52 | result = result .. "description: " .. v["description"] .. "\n" 53 | result = result .. "datePublished: " .. v["datePublished"] .. "\n" 54 | result = result .. "dateUpdated: " .. v["dateUpdated"] .. "\n" 55 | result = result .. "baseScore: " .. v["baseScore"] .. "\n" 56 | result = result .. "baseScoreVersion: " .. v["baseScoreVersion"] .. "\n" 57 | result = result .. "baseScoreVector: " .. v["baseScoreVector"] .. "\n" 58 | result = result .. "references: " .. v["references"] .. "\n" 59 | result = result .. "aliases: " .. v["aliases"] .. "\n" 60 | result = result .. "assigner: " .. v["assigner"] .. "\n" 61 | result = result .. "epss: " .. v["epss"] .. "\n" 62 | result = result .. 63 | "----------------------------------------------------------------" .. 64 | "\n" 65 | end 66 | 67 | print(result) 68 | 69 | return result 70 | end 71 | 72 | milla.register_cmd("/plugins/euvd.lua", "euvd", "euvd") 73 | -------------------------------------------------------------------------------- /useragents.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "crypto/tls" 7 | "encoding/json" 8 | "fmt" 9 | "log" 10 | "net/http" 11 | "time" 12 | ) 13 | 14 | const ( 15 | UserAgentsURL = "https://useragents:443/api/v1/agent" 16 | ) 17 | 18 | func UserAgentsGet(uaActionName, query string, appConfig *TomlConfig) string { 19 | var userAgentRequest UserAgentRequest 20 | 21 | var userAgentResponse UserAgentResponse 22 | 23 | _, ok := appConfig.UserAgentActions[uaActionName] 24 | if !ok { 25 | log.Println("UserAgentAction not found:", uaActionName) 26 | 27 | return fmt.Sprintf("useragents: %s: action not found", uaActionName) 28 | } 29 | 30 | userAgentRequest.Agent_Name = appConfig.UserAgentActions[uaActionName].Agent_Name 31 | userAgentRequest.Instructions = appConfig.UserAgentActions[uaActionName].Instructions 32 | 33 | if query != "" { 34 | userAgentRequest.Query = query 35 | } else { 36 | userAgentRequest.Query = appConfig.UserAgentActions[uaActionName].Query 37 | } 38 | 39 | log.Println("UserAgentRequest:", appConfig.UserAgentActions[uaActionName]) 40 | log.Println(userAgentRequest) 41 | 42 | jsonData, err := json.Marshal(userAgentRequest) 43 | if err != nil { 44 | log.Println(err) 45 | 46 | return fmt.Sprintf("useragents: %s: could not marshall json request", userAgentRequest.Agent_Name) 47 | } 48 | 49 | ctx, cancel := context.WithTimeout(context.Background(), time.Duration(appConfig.RequestTimeout)*time.Second) 50 | defer cancel() 51 | 52 | req, err := http.NewRequest( 53 | http.MethodPost, 54 | UserAgentsURL, 55 | bytes.NewBuffer(jsonData), 56 | ) 57 | if err != nil { 58 | log.Println(err) 59 | 60 | return fmt.Sprintf("useragents: %s: could not create request", userAgentRequest.Agent_Name) 61 | } 62 | 63 | req = req.WithContext(ctx) 64 | 65 | req.Header.Set("Content-Type", "application/json") 66 | 67 | client := &http.Client{ 68 | Transport: &http.Transport{ 69 | TLSClientConfig: &tls.Config{ 70 | InsecureSkipVerify: true, 71 | }, 72 | }, 73 | } 74 | 75 | response, err := client.Do(req) 76 | if err != nil { 77 | log.Println(err) 78 | 79 | return fmt.Sprintf("useragents: %s: could not send request", userAgentRequest.Agent_Name) 80 | } 81 | 82 | defer response.Body.Close() 83 | 84 | if err != nil { 85 | log.Println(err) 86 | 87 | return fmt.Sprintf("useragents: %s: could not read response", userAgentRequest.Agent_Name) 88 | } 89 | 90 | err = json.NewDecoder(response.Body).Decode(&userAgentResponse) 91 | if err != nil { 92 | log.Println(err) 93 | 94 | return fmt.Sprintf("useragents: %s: could not unmarshall json response", userAgentRequest.Agent_Name) 95 | } 96 | 97 | return userAgentResponse.Response 98 | } 99 | -------------------------------------------------------------------------------- /plugins/rss.lua: -------------------------------------------------------------------------------- 1 | local milla = require("milla") 2 | local yaml = require("yaml") 3 | local http = require("http") 4 | local xmlpath = require("xmlpath") 5 | 6 | local function read_file(file) 7 | local f = assert(io.open(file, "rb")) 8 | local content = f:read("*all") 9 | f:close() 10 | return content 11 | end 12 | 13 | local function sleep(n) os.execute("sleep " .. tonumber(n)) end 14 | 15 | local function get_config() 16 | local yaml_config = read_file("./plugins/rss.yaml") 17 | local config = yaml.parse(yaml_config) 18 | return config 19 | end 20 | 21 | local function get_rss_feed(config) 22 | local titles = {} 23 | local author_names = {} 24 | local uris = {} 25 | local rss_feed_list = {} 26 | 27 | for _, v in pairs(config.rssfeeds) do 28 | local response, err = http.request("GET", v.url) 29 | if err ~= nil then 30 | milla.send_message(err, "") 31 | goto continue 32 | end 33 | local node, err = xmlpath.loadxml(response.body) 34 | if err ~= nil then 35 | milla.send_message(err, "") 36 | goto continue 37 | end 38 | 39 | local path, err = xmlpath.compile("//entry/title") 40 | if err ~= nil then 41 | milla.send_message(err, "") 42 | goto continue 43 | end 44 | local iterator = path:iter(node) 45 | for _, match in ipairs(iterator) do 46 | table.insert(titles, match:string()) 47 | end 48 | 49 | path, err = xmlpath.compile("//entry/author/name") 50 | if err ~= nil then 51 | milla.send_message(err, "") 52 | goto continue 53 | end 54 | iterator = path:iter(node) 55 | for _, match in ipairs(iterator) do 56 | table.insert(author_names, match:string()) 57 | end 58 | 59 | path, err = xmlpath.compile("//entry/author/uri") 60 | if err ~= nil then 61 | milla.send_message(err, "") 62 | goto continue 63 | end 64 | iterator = path:iter(node) 65 | for _, match in ipairs(iterator) do 66 | table.insert(uris, match:string()) 67 | end 68 | ::continue:: 69 | end 70 | 71 | for i = 1, #titles do 72 | table.insert(rss_feed_list, 73 | author_names[i] .. ": " .. titles[i] .. " -- " .. uris[i]) 74 | end 75 | 76 | return rss_feed_list 77 | end 78 | 79 | local function rss_feed() 80 | local config = get_config() 81 | while true do 82 | for _, v in pairs(get_rss_feed(config)) do 83 | milla.send_message(v, config.channel) 84 | sleep(config.period) 85 | end 86 | end 87 | end 88 | 89 | rss_feed() 90 | -------------------------------------------------------------------------------- /docker-compose-postgres.yaml: -------------------------------------------------------------------------------- 1 | services: 2 | terra: 3 | image: milla_distroless_vendored 4 | build: 5 | context: . 6 | dockerfile: ./Dockerfile_distroless_vendored 7 | deploy: 8 | resources: 9 | limits: 10 | memory: 128M 11 | logging: 12 | driver: "json-file" 13 | options: 14 | max-size: "100m" 15 | networks: 16 | - terranet 17 | user: 1000:1000 18 | restart: unless-stopped 19 | entrypoint: ["/usr/bin/milla"] 20 | command: ["--config", "/config.toml"] 21 | volumes: 22 | - ./config-omni.toml:/config.toml 23 | - /etc/localtime:/etc/localtime:ro 24 | - ./plugins/:/plugins/:ro 25 | cap_drop: 26 | - ALL 27 | postgres: 28 | image: postgres:16-alpine3.19 29 | deploy: 30 | resources: 31 | limits: 32 | memory: 4096M 33 | logging: 34 | driver: "json-file" 35 | options: 36 | max-size: "200m" 37 | restart: unless-stopped 38 | ports: 39 | - "127.0.0.1:5455:5432/tcp" 40 | volumes: 41 | - terra_postgres_vault:/var/lib/postgresql/data 42 | - ./scripts/:/docker-entrypoint-initdb.d/:ro 43 | environment: 44 | - POSTGRES_PASSWORD_FILE=/run/secrets/pg_pass_secret 45 | - POSTGRES_USER_FILE=/run/secrets/pg_user_secret 46 | - POSTGRES_INITDB_ARGS_FILE=/run/secrets/pg_initdb_args_secret 47 | - POSTGRES_DB_FILE=/run/secrets/pg_db_secret 48 | networks: 49 | - terranet 50 | - dbnet 51 | secrets: 52 | - pg_pass_secret 53 | - pg_user_secret 54 | - pg_initdb_args_secret 55 | - pg_db_secret 56 | pgadmin: 57 | image: dpage/pgadmin4:8.6 58 | deploy: 59 | resources: 60 | limits: 61 | memory: 1024M 62 | logging: 63 | driver: "json-file" 64 | options: 65 | max-size: "100m" 66 | environment: 67 | - PGADMIN_LISTEN_PORT=${PGADMIN_LISTEN_PORT:-5050} 68 | - PGADMIN_DEFAULT_EMAIL= 69 | - PGADMIN_DEFAULT_PASSWORD_FILE=/run/secrets/pgadmin_pass 70 | - PGADMIN_DISABLE_POSTFIX=${PGADMIN_DISABLE_POSTFIX:-YES} 71 | ports: 72 | - "127.0.0.1:5050:5050/tcp" 73 | restart: unless-stopped 74 | volumes: 75 | - terra_pgadmin_vault:/var/lib/pgadmin 76 | networks: 77 | - dbnet 78 | secrets: 79 | - pgadmin_pass 80 | networks: 81 | terranet: 82 | driver: bridge 83 | dbnet: 84 | volumes: 85 | terra_postgres_vault: 86 | terra_pgadmin_vault: 87 | secrets: 88 | pg_pass_secret: 89 | file: ./pg/pg_pass_secret 90 | pg_user_secret: 91 | file: ./pg/pg_user_secret 92 | pg_initdb_args_secret: 93 | file: ./pg/pg_initdb_args_secret 94 | pg_db_secret: 95 | file: ./pg/pg_db_secret 96 | pgadmin_pass: 97 | file: ./pgadmin/pgadmin_pass 98 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module milla 2 | 3 | go 1.24.0 4 | 5 | toolchain go1.24.2 6 | 7 | require ( 8 | github.com/BurntSushi/toml v1.5.0 9 | github.com/ailncode/gluaxmlpath v0.0.0-20161126153117-6ce478ecb4a6 10 | github.com/alecthomas/chroma/v2 v2.16.0 11 | github.com/cenkalti/backoff/v5 v5.0.2 12 | github.com/cjoudrey/gluahttp v0.0.0-20201111170219-25003d9adfa9 13 | github.com/coyim/otr3 v0.0.0-20230314203300-86897a28af47 14 | github.com/ergochat/irc-go v0.4.0 15 | github.com/jackc/pgx/v5 v5.7.4 16 | github.com/kohkimakimoto/gluayaml v0.0.0-20160815032708-6fe413d49d73 17 | github.com/layeh/gopher-json v0.0.0-20201124131017-552bb3c4c3bf 18 | github.com/lrstanley/girc v0.0.0-20250219025855-423afa8a8828 19 | github.com/mmcdole/gofeed v1.3.0 20 | github.com/sashabaranov/go-openai v1.38.1 21 | github.com/yuin/gluare v0.0.0-20170607022532-d7c94f1a80ed 22 | github.com/yuin/gopher-lua v1.1.1 23 | gitlab.com/megalithic-llc/gluasocket v0.3.1 24 | golang.org/x/net v0.39.0 25 | google.golang.org/genai v1.0.0 26 | ) 27 | 28 | require ( 29 | cloud.google.com/go v0.120.0 // indirect 30 | cloud.google.com/go/auth v0.15.0 // indirect 31 | cloud.google.com/go/compute/metadata v0.6.0 // indirect 32 | github.com/PuerkitoBio/goquery v1.10.3 // indirect 33 | github.com/andybalholm/cascadia v1.3.3 // indirect 34 | github.com/awnumar/memcall v0.1.2 // indirect 35 | github.com/coyim/constbn v0.0.0-20230207191538-27f0129d98cd // indirect 36 | github.com/dlclark/regexp2 v1.11.5 // indirect 37 | github.com/felixge/httpsnoop v1.0.4 // indirect 38 | github.com/go-logr/logr v1.4.2 // indirect 39 | github.com/go-logr/stdr v1.2.2 // indirect 40 | github.com/google/go-cmp v0.7.0 // indirect 41 | github.com/google/s2a-go v0.1.9 // indirect 42 | github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect 43 | github.com/googleapis/gax-go/v2 v2.14.1 // indirect 44 | github.com/gorilla/websocket v1.5.3 // indirect 45 | github.com/jackc/pgpassfile v1.0.0 // indirect 46 | github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect 47 | github.com/jackc/puddle/v2 v2.2.2 // indirect 48 | github.com/json-iterator/go v1.1.12 // indirect 49 | github.com/mmcdole/goxpp v1.1.1 // indirect 50 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect 51 | github.com/modern-go/reflect2 v1.0.2 // indirect 52 | go.opentelemetry.io/auto/sdk v1.1.0 // indirect 53 | go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0 // indirect 54 | go.opentelemetry.io/otel v1.35.0 // indirect 55 | go.opentelemetry.io/otel/metric v1.35.0 // indirect 56 | go.opentelemetry.io/otel/trace v1.35.0 // indirect 57 | golang.org/x/crypto v0.37.0 // indirect 58 | golang.org/x/sync v0.13.0 // indirect 59 | golang.org/x/sys v0.32.0 // indirect 60 | golang.org/x/text v0.24.0 // indirect 61 | google.golang.org/genproto/googleapis/rpc v0.0.0-20250414145226-207652e42e2e // indirect 62 | google.golang.org/grpc v1.71.1 // indirect 63 | google.golang.org/protobuf v1.36.6 // indirect 64 | gopkg.in/xmlpath.v2 v2.0.0-20150820204837-860cbeca3ebc // indirect 65 | gopkg.in/yaml.v2 v2.4.0 // indirect 66 | ) 67 | -------------------------------------------------------------------------------- /defaults.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func AddSaneDefaults(config *TomlConfig) { 4 | if config.IrcNick == "" { 5 | config.IrcNick = "milla" 6 | } 7 | 8 | if config.ChromaStyle == "" { 9 | config.ChromaStyle = "rose-pine-moon" 10 | } 11 | 12 | if config.ChromaFormatter == "" { 13 | config.ChromaFormatter = "noop" 14 | } 15 | 16 | if config.DatabaseAddress == "" { 17 | config.DatabaseAddress = "postgres" 18 | } 19 | 20 | if config.DatabaseUser == "" { 21 | config.DatabaseUser = "milla" 22 | } 23 | 24 | if config.DatabaseName == "" { 25 | config.DatabaseName = "milladb" 26 | } 27 | 28 | if config.Temperature == 0 { 29 | config.Temperature = 0.5 30 | } 31 | 32 | if config.RequestTimeout == 0 { 33 | config.RequestTimeout = 10 34 | } 35 | 36 | if config.MillaReconnectDelay == 0 { 37 | config.MillaReconnectDelay = 30 38 | } 39 | 40 | if config.IrcPort == 0 { 41 | config.IrcPort = 6697 42 | } 43 | 44 | if config.KeepAlive == 0 { 45 | config.KeepAlive = 600 46 | } 47 | 48 | if config.MemoryLimit == 0 { 49 | config.MemoryLimit = 20 50 | } 51 | 52 | if config.PingDelay == 0 { 53 | config.PingDelay = 20 54 | } 55 | 56 | if config.PingTimeout == 0 { 57 | config.PingTimeout = 20 58 | } 59 | 60 | if config.OllamaMirostatEta == 0 { 61 | config.OllamaMirostatEta = 0.1 62 | } 63 | 64 | if config.OllamaMirostatTau == 0 { 65 | config.OllamaMirostatTau = 5.0 66 | } 67 | 68 | if config.OllamaNumCtx == 0 { 69 | config.OllamaNumCtx = 4096 70 | } 71 | 72 | if config.OllamaRepeatLastN == 0 { 73 | config.OllamaRepeatLastN = 64 74 | } 75 | 76 | if config.OllamaRepeatPenalty == 0 { 77 | config.OllamaRepeatPenalty = 1.1 78 | } 79 | 80 | if config.OllamaSeed == 0 { 81 | config.OllamaSeed = 42 82 | } 83 | 84 | if config.OllamaNumPredict == 0 { 85 | config.OllamaNumPredict = -1 86 | } 87 | 88 | if config.TopK == 0 { 89 | config.TopK = 40 90 | } 91 | 92 | if config.TopP == 0.0 { 93 | config.TopP = 0.9 94 | } 95 | 96 | if config.OllamaMinP == 0 { 97 | config.OllamaMinP = 0.05 98 | } 99 | 100 | if config.Temperature == 0 { 101 | config.Temperature = 0.7 102 | } 103 | 104 | if config.IrcBackOffMaxInterval == 0 { 105 | config.IrcBackOffMaxInterval = 500 106 | } 107 | 108 | if config.IrcBackOffRandomizationFactor == 0 { 109 | config.IrcBackOffRandomizationFactor = 0.5 110 | } 111 | 112 | if config.IrcBackOffMultiplier == 0 { 113 | config.IrcBackOffMultiplier = 1.5 114 | } 115 | 116 | if config.IrcBackOffMaxInterval == 0 { 117 | config.IrcBackOffMaxInterval = 60 118 | } 119 | 120 | if config.DbBackOffMaxInterval == 0 { 121 | config.DbBackOffMaxInterval = 500 122 | } 123 | 124 | if config.DbBackOffRandomizationFactor == 0 { 125 | config.DbBackOffRandomizationFactor = 0.5 126 | } 127 | 128 | if config.DbBackOffMultiplier == 0 { 129 | config.DbBackOffMultiplier = 1.5 130 | } 131 | 132 | if config.DbBackOffMaxInterval == 0 { 133 | config.DbBackOffMaxInterval = 60 134 | } 135 | 136 | if config.OllamaThink == "" { 137 | config.OllamaThink = "false" 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /config-example.toml: -------------------------------------------------------------------------------- 1 | [ircd.devinet] 2 | ircServer = "irc.myawesomeircnet.com" 3 | ircPort = 6697 4 | ircNick = "milla" 5 | enableSasl = true 6 | ircSaslUser = "milla" 7 | ircSaslPass = "xxxxx" 8 | ircChannels = [["##chan1"], ["##chan2"]] 9 | temp = 0.2 10 | requestTimeout = 10 11 | millaReconnectDelay = 60 12 | model = "gpt-3.5-turbo" 13 | chromaStyle = "rose-pine-moon" 14 | chromaFormatter = "terminal256" 15 | provider = "chatgpt" 16 | apikey = "xxxx" 17 | memoryLimit = 20 18 | admins = ["noone_has_this_nick"] 19 | debug = true 20 | out = true 21 | databaseAddress = "postgres:5432" 22 | databasePassword = "changeme" 23 | databaseUser = "devi" 24 | databaseName = "milla" 25 | scrapeChannels = [["#soulhack"], ["#warroom"], ["#securityfeeds"]] 26 | ircProxy = "socks5://127.0.0.1:9050" 27 | llmProxy = "http://127.0.0.1:8180" 28 | skipTLSVerify = false 29 | useTLS = true 30 | adminOnly = false 31 | context = ["please respond in french even if i use another language unless you are specifically asked to use any language other than french", "your name is terra"] 32 | plugins = ["/plugins/ip.lua", "/plugins/urban.lua"] 33 | [ircd.devinet.watchlist.security] 34 | watchList = [["#securityfeeds"]] 35 | watchFiles = ["/watchfiles/voidbox.list"] 36 | alertChannel = ["#milla_alerts"] 37 | eventTypes = ["PRIVMSG"] 38 | fgColor = 0 39 | bgColor = 28 40 | [ircd.devinet.rss.manga] 41 | rssFile = "/rssfeeds/manga.json" 42 | channel = ["#manga"] 43 | [ircd.devinet.rss.anime] 44 | rssFile = "/rssfeeds/anime.json" 45 | channel = ["#anime"] 46 | [ircd.devinet.triggeredScripts.hello] 47 | path = "/plugins/hello.lua" 48 | funcName = "hello" 49 | triggerTypes = ["PRIVMSG"] 50 | [ircd.devinet.userAgentActions.cryptoDailyDigest] 51 | agent_name = "crypto_daily_digest" 52 | instructions = "you are a news digest bot" 53 | query = "give me a news digest of the news related to to cryptocurrencries for today. please do mention your sources for each one." 54 | tools = ["WebSearchTool"] 55 | [ircd.devinet.aliases.cryptoDailyDigest] 56 | alias = "/ua cryptoDailyDigest" 57 | 58 | [ircd.liberanet] 59 | ircServer = "irc.libera.chat" 60 | ircNick = "milla" 61 | model = "gpt-3.5-turbo" 62 | ircPort = 6697 63 | chromaStyle = "rose-pine-moon" 64 | chromaFormatter = "terminal16m" 65 | provider = "gemini" 66 | apikey = "xxxx" 67 | temp = 0.5 68 | requestTimeout = 10 69 | millaReconnectDelay = 60 70 | keepAlive = 20 71 | memoryLimit = 20 72 | pingDelay = 20 73 | pingTimeout = 600 74 | skipTLSVerify = false 75 | useTLS = true 76 | disableSTSFallback = true 77 | allowFlood = false 78 | admins = ["noone_has_this_nick"] 79 | ircChannels = [["##milla1"], ["##milla2"]] 80 | debug = true 81 | out = true 82 | ircProxy = "socks5://127.0.0.1:9051" 83 | llmProxy = "http://127.0.0.1:8181" 84 | adminOnly = true 85 | [ircd.liberanet.customCommands.digest] 86 | sql = "select log from liberanet_milla_us_market_news order by log desc;" 87 | limit = 300 88 | context = ["you are a sentiment-analysis bot"] 89 | prompt= "i have provided to you news headlines in the form of previous conversations between you and me using the user role. please provide the digest of the news for me." 90 | [ircd.liberanet.customCommands.summarize] 91 | sql= "select log from liberanet_milla_us_market_news order by log desc;" 92 | limit= 300 93 | context = ["you are a sentiment-analysis bot"] 94 | prompt= "i have provided to you news headlines in the form of previous conversations between you and me using the user role. please summarize the provided news for me. provide some details." 95 | -------------------------------------------------------------------------------- /openai.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "log" 7 | "net" 8 | "net/http" 9 | "net/url" 10 | "strings" 11 | "time" 12 | 13 | "github.com/alecthomas/chroma/v2/quick" 14 | "github.com/lrstanley/girc" 15 | openai "github.com/sashabaranov/go-openai" 16 | "golang.org/x/net/proxy" 17 | ) 18 | 19 | func DoChatGPTRequest( 20 | appConfig *TomlConfig, 21 | gptMemory *[]openai.ChatCompletionMessage, 22 | prompt, systemPrompt string, 23 | ) (string, error) { 24 | ctx, cancel := context.WithTimeout(context.Background(), time.Duration(appConfig.RequestTimeout)*time.Second) 25 | defer cancel() 26 | 27 | var httpClient http.Client 28 | 29 | if appConfig.LLMProxy != "" { 30 | proxyURL, err := url.Parse(appConfig.IRCProxy) 31 | if err != nil { 32 | cancel() 33 | 34 | return "", err 35 | } 36 | 37 | dialer, err := proxy.FromURL(proxyURL, &net.Dialer{Timeout: time.Duration(appConfig.RequestTimeout) * time.Second}) 38 | if err != nil { 39 | cancel() 40 | 41 | return "", err 42 | } 43 | 44 | httpClient = http.Client{ 45 | Transport: &http.Transport{ 46 | Dial: dialer.Dial, 47 | }, 48 | } 49 | } 50 | 51 | config := openai.DefaultConfig(appConfig.Apikey) 52 | config.HTTPClient = &httpClient 53 | 54 | if appConfig.Endpoint != "" { 55 | config.BaseURL = appConfig.Endpoint 56 | log.Print(config.BaseURL) 57 | } 58 | 59 | gptClient := openai.NewClientWithConfig(config) 60 | 61 | *gptMemory = append(*gptMemory, openai.ChatCompletionMessage{ 62 | Role: openai.ChatMessageRoleSystem, 63 | Content: systemPrompt, 64 | }) 65 | 66 | *gptMemory = append(*gptMemory, openai.ChatCompletionMessage{ 67 | Role: openai.ChatMessageRoleUser, 68 | Content: prompt, 69 | }) 70 | 71 | resp, err := gptClient.CreateChatCompletion(ctx, openai.ChatCompletionRequest{ 72 | Model: appConfig.Model, 73 | Messages: *gptMemory, 74 | }) 75 | if err != nil { 76 | return "", err 77 | } 78 | 79 | return resp.Choices[0].Message.Content, nil 80 | } 81 | 82 | func ChatGPTRequestProcessor( 83 | appConfig *TomlConfig, 84 | client *girc.Client, 85 | event girc.Event, 86 | gptMemory *[]openai.ChatCompletionMessage, 87 | prompt, systemPrompt string, 88 | ) string { 89 | resp, err := DoChatGPTRequest(appConfig, gptMemory, prompt, systemPrompt) 90 | if err != nil { 91 | client.Cmd.ReplyTo(event, "error: "+err.Error()) 92 | 93 | return "" 94 | } 95 | 96 | *gptMemory = append(*gptMemory, openai.ChatCompletionMessage{ 97 | Role: openai.ChatMessageRoleAssistant, 98 | Content: resp, 99 | }) 100 | 101 | if len(*gptMemory) > appConfig.MemoryLimit { 102 | *gptMemory = []openai.ChatCompletionMessage{} 103 | 104 | for _, context := range appConfig.Context { 105 | *gptMemory = append(*gptMemory, openai.ChatCompletionMessage{ 106 | Role: openai.ChatMessageRoleAssistant, 107 | Content: context, 108 | }) 109 | } 110 | } 111 | 112 | var writer bytes.Buffer 113 | 114 | err = quick.Highlight( 115 | &writer, 116 | resp, 117 | "markdown", 118 | appConfig.ChromaFormatter, 119 | appConfig.ChromaStyle) 120 | if err != nil { 121 | client.Cmd.ReplyTo(event, "error: "+err.Error()) 122 | 123 | return "" 124 | } 125 | 126 | return writer.String() 127 | } 128 | 129 | func ChatGPTHandler( 130 | irc *girc.Client, 131 | appConfig *TomlConfig, 132 | gptMemory *[]openai.ChatCompletionMessage, 133 | ) { 134 | irc.Handlers.AddBg(girc.PRIVMSG, func(client *girc.Client, event girc.Event) { 135 | if !strings.HasPrefix(event.Last(), appConfig.IrcNick+": ") { 136 | return 137 | } 138 | 139 | if appConfig.AdminOnly { 140 | byAdmin := false 141 | 142 | for _, admin := range appConfig.Admins { 143 | if event.Source.Name == admin { 144 | byAdmin = true 145 | } 146 | } 147 | 148 | if !byAdmin { 149 | return 150 | } 151 | } 152 | 153 | prompt := strings.TrimPrefix(event.Last(), appConfig.IrcNick+": ") 154 | log.Println(prompt) 155 | 156 | if string(prompt[0]) == "/" { 157 | runCommand(client, event, appConfig) 158 | 159 | return 160 | } 161 | 162 | result := ChatGPTRequestProcessor(appConfig, client, event, gptMemory, prompt, appConfig.SystemPrompt) 163 | if result != "" { 164 | SendToIRC(client, event, result, appConfig.ChromaFormatter) 165 | } 166 | }) 167 | } 168 | -------------------------------------------------------------------------------- /openrouter.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "encoding/json" 7 | "log" 8 | "net" 9 | "net/http" 10 | "net/url" 11 | "strings" 12 | "time" 13 | 14 | "github.com/alecthomas/chroma/v2/quick" 15 | "github.com/lrstanley/girc" 16 | "golang.org/x/net/proxy" 17 | ) 18 | 19 | func DoORRequest( 20 | appConfig *TomlConfig, 21 | memory *[]MemoryElement, 22 | prompt string, 23 | ) (string, error) { 24 | var jsonPayload []byte 25 | 26 | var err error 27 | 28 | memoryElement := MemoryElement{ 29 | Role: "user", 30 | Content: prompt, 31 | } 32 | 33 | if len(*memory) > appConfig.MemoryLimit { 34 | *memory = []MemoryElement{} 35 | 36 | for _, context := range appConfig.Context { 37 | *memory = append(*memory, MemoryElement{ 38 | Role: "assistant", 39 | Content: context, 40 | }) 41 | } 42 | } 43 | 44 | *memory = append(*memory, memoryElement) 45 | 46 | ollamaRequest := OllamaChatRequest{ 47 | Model: appConfig.Model, 48 | System: appConfig.SystemPrompt, 49 | Messages: *memory, 50 | } 51 | 52 | jsonPayload, err = json.Marshal(ollamaRequest) 53 | if err != nil { 54 | 55 | return "", err 56 | } 57 | 58 | log.Printf("json payload: %s", string(jsonPayload)) 59 | 60 | ctx, cancel := context.WithTimeout(context.Background(), time.Duration(appConfig.RequestTimeout)*time.Second) 61 | defer cancel() 62 | 63 | request, err := http.NewRequest(http.MethodPost, appConfig.Endpoint, bytes.NewBuffer(jsonPayload)) 64 | if err != nil { 65 | 66 | return "", err 67 | } 68 | 69 | request = request.WithContext(ctx) 70 | request.Header.Set("content-type", "application/json") 71 | request.Header.Set("Authorization", "Bearer "+appConfig.Apikey) 72 | 73 | var httpClient http.Client 74 | 75 | var dialer proxy.Dialer 76 | 77 | if appConfig.LLMProxy != "" { 78 | proxyURL, err := url.Parse(appConfig.IRCProxy) 79 | if err != nil { 80 | cancel() 81 | 82 | log.Fatal(err.Error()) 83 | } 84 | 85 | dialer, err = proxy.FromURL(proxyURL, &net.Dialer{Timeout: time.Duration(appConfig.RequestTimeout) * time.Second}) 86 | if err != nil { 87 | cancel() 88 | 89 | log.Fatal(err.Error()) 90 | } 91 | 92 | httpClient = http.Client{ 93 | Transport: &http.Transport{ 94 | Dial: dialer.Dial, 95 | }, 96 | } 97 | } 98 | response, err := httpClient.Do(request) 99 | 100 | if err != nil { 101 | return "", err 102 | } 103 | 104 | defer response.Body.Close() 105 | 106 | log.Println("response body:", response.Body) 107 | 108 | var orresponse ORResponse 109 | 110 | err = json.NewDecoder(response.Body).Decode(&orresponse) 111 | if err != nil { 112 | return "", err 113 | } 114 | 115 | var result string 116 | 117 | for _, choice := range orresponse.Choices { 118 | result += choice.Message.Content + "\n" 119 | } 120 | 121 | return result, nil 122 | } 123 | 124 | func ORRequestProcessor( 125 | appConfig *TomlConfig, 126 | client *girc.Client, 127 | event girc.Event, 128 | memory *[]MemoryElement, 129 | prompt string, 130 | ) string { 131 | response, err := DoORRequest(appConfig, memory, prompt) 132 | if err != nil { 133 | client.Cmd.ReplyTo(event, "error: "+err.Error()) 134 | 135 | return "" 136 | } 137 | 138 | assistantElement := MemoryElement{ 139 | Role: "assistant", 140 | Content: response, 141 | } 142 | 143 | *memory = append(*memory, assistantElement) 144 | 145 | log.Println(response) 146 | 147 | var writer bytes.Buffer 148 | 149 | err = quick.Highlight(&writer, 150 | response, 151 | "markdown", 152 | appConfig.ChromaFormatter, 153 | appConfig.ChromaStyle) 154 | if err != nil { 155 | client.Cmd.ReplyTo(event, "error: "+err.Error()) 156 | 157 | return "" 158 | } 159 | 160 | return writer.String() 161 | } 162 | 163 | func ORHandler( 164 | irc *girc.Client, 165 | appConfig *TomlConfig, 166 | memory *[]MemoryElement) { 167 | irc.Handlers.AddBg(girc.PRIVMSG, func(client *girc.Client, event girc.Event) { 168 | if !strings.HasPrefix(event.Last(), appConfig.IrcNick+": ") { 169 | return 170 | } 171 | 172 | if appConfig.AdminOnly { 173 | byAdmin := false 174 | 175 | for _, admin := range appConfig.Admins { 176 | if event.Source.Name == admin { 177 | byAdmin = true 178 | } 179 | } 180 | 181 | if !byAdmin { 182 | return 183 | } 184 | } 185 | 186 | prompt := strings.TrimPrefix(event.Last(), appConfig.IrcNick+": ") 187 | log.Println(prompt) 188 | 189 | if string(prompt[0]) == "/" { 190 | runCommand(client, event, appConfig) 191 | 192 | return 193 | } 194 | 195 | result := ORRequestProcessor(appConfig, client, event, memory, prompt) 196 | if result != "" { 197 | SendToIRC(client, event, result, appConfig.ChromaFormatter) 198 | } 199 | }) 200 | 201 | } 202 | -------------------------------------------------------------------------------- /useragents/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | API Server for custom user agents 5 | """ 6 | 7 | import argparse 8 | import importlib.util 9 | import os 10 | import sys 11 | 12 | from src.models import AgentRequest, AgentResponse 13 | from src.registry import agentRegistry 14 | 15 | from agents import Runner, Agent 16 | import fastapi 17 | from fastapi.encoders import jsonable_encoder 18 | from fastapi.responses import JSONResponse 19 | import uvicorn 20 | 21 | 22 | class ArgParser: 23 | """ 24 | Argument parser for command line arguments. 25 | """ 26 | 27 | def __init__(self): 28 | parser = argparse.ArgumentParser() 29 | parser.add_argument( 30 | "--plugin-dir", 31 | type=str, 32 | help="Directory containing plugins", 33 | default="/useragent/src/custom_agents", 34 | ) 35 | parser.add_argument( 36 | "--port", type=int, help="Port to run the server on", default=443 37 | ) 38 | parser.add_argument( 39 | "--address", type=str, help="which address to bind to", default="0.0.0.0" 40 | ) 41 | self.args = parser.parse_args() 42 | 43 | 44 | def load_plugins(plugin_dir: str): 45 | """ 46 | Load all Python files in the specified directory as modules. 47 | Args: 48 | plugin_dir (str): Directory containing the plugin files. 49 | """ 50 | for filename in os.listdir(plugin_dir): 51 | if filename.endswith(".py") and filename != "__init__.py": 52 | filepath = os.path.join(plugin_dir, filename) 53 | print(filepath) 54 | module_name = filename[:-3] 55 | spec = importlib.util.spec_from_file_location(module_name, filepath) 56 | if spec and spec.loader: 57 | module = importlib.util.module_from_spec(spec) 58 | sys.modules[module_name] = module 59 | spec.loader.exec_module(module) 60 | print(f"Loaded module: {module_name} from {filepath}") 61 | else: 62 | print(f"Warning: Could not load module {module_name} from {filepath}") 63 | 64 | 65 | def get_agent_generator(agent_name: str) -> Agent: 66 | """ 67 | Find and return the agent generator function from the custom agent registry 68 | """ 69 | for k, v in agentRegistry.registry.items(): 70 | print(k, v) 71 | try: 72 | agent = agentRegistry.registry[agent_name] 73 | except KeyError: 74 | raise ValueError(f"Agent {agent_name} not found in registry.") 75 | 76 | return agent 77 | 78 | 79 | class AgentRunner: 80 | """ 81 | Class to run the agent with the provided request. 82 | """ 83 | 84 | def __init__(self, agent_request): 85 | self.agent_request = agent_request 86 | 87 | async def run(self) -> str: 88 | print( 89 | f"Running agent {self.agent_request.agent_name} with instructions: {self.agent_request.instructions} with query: {self.agent_request.query}" 90 | ) 91 | 92 | try: 93 | agent = get_agent_generator(self.agent_request.agent_name)( 94 | self.agent_request 95 | ) 96 | except ValueError as e: 97 | print(f"Error: {e}") 98 | return str(e) 99 | 100 | result = await Runner.run(agent, self.agent_request.query) 101 | print(result.final_output_as(str)) 102 | 103 | return result.final_output_as(str) 104 | 105 | 106 | class APIServer: 107 | """ 108 | The API server 109 | """ 110 | 111 | def __init__(self): 112 | self.app = fastapi.FastAPI() 113 | self.router = fastapi.APIRouter() 114 | self.router.add_api_route( 115 | "/api/v1/agent", self.agent_handler, methods=["POST"], tags=[] 116 | ) 117 | self.agent_registry = {} 118 | 119 | self.app.include_router(self.router) 120 | 121 | async def agent_handler(self, agent_request: AgentRequest) -> fastapi.Response: 122 | print(f"Received request: {agent_request}") 123 | response = await AgentRunner(agent_request).run() 124 | 125 | result = AgentResponse(agent_name=agent_request.agent_name, response=response) 126 | 127 | print(f"Response: {result}") 128 | 129 | return JSONResponse( 130 | content=jsonable_encoder(result), 131 | status_code=200, 132 | ) 133 | 134 | 135 | def main(): 136 | argparser = ArgParser() 137 | load_plugins(argparser.args.plugin_dir) 138 | app = APIServer().app 139 | uvicorn.run( 140 | app, 141 | host=argparser.args.address, 142 | port=argparser.args.port, 143 | ssl_keyfile="./server.key", 144 | ssl_certfile="./server.cert", 145 | ) 146 | 147 | 148 | if __name__ == "__main__": 149 | main() 150 | -------------------------------------------------------------------------------- /rss.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "fmt" 7 | "log" 8 | "net" 9 | "net/http" 10 | "net/url" 11 | "os" 12 | "slices" 13 | "time" 14 | 15 | "github.com/jackc/pgx/v5/pgxpool" 16 | "github.com/lrstanley/girc" 17 | "github.com/mmcdole/gofeed" 18 | "golang.org/x/net/proxy" 19 | ) 20 | 21 | func GetFeed(feed FeedConfig, 22 | client *girc.Client, 23 | pool *pgxpool.Pool, 24 | channel []string, 25 | groupName string, 26 | ) { 27 | rowName := groupName + "__" + feed.Name + "__" 28 | 29 | ctx, cancel := context.WithTimeout(context.Background(), time.Duration(feed.Timeout)*time.Second) 30 | defer cancel() 31 | 32 | parsedFeed, err := feed.FeedParser.ParseURLWithContext(feed.URL, ctx) 33 | if err != nil { 34 | LogError(err) 35 | } else { 36 | if len(parsedFeed.Items) > 0 { 37 | query := fmt.Sprintf("select newest_unix_time from rss where name = '%s'", rowName) 38 | 39 | ctx, cancel := context.WithTimeout(context.Background(), time.Duration(10)*time.Second) 40 | defer cancel() 41 | 42 | newestFromDB := int64(0) 43 | 44 | err := pool.QueryRow(ctx, query).Scan(&newestFromDB) 45 | if err != nil { 46 | _, err = pool.Exec(ctx, fmt.Sprintf("insert into rss (name, newest_unix_time) values ('%s',0)", rowName)) 47 | if err != nil { 48 | LogError(err) 49 | 50 | return 51 | } 52 | } 53 | 54 | sortFunc := func(a, b *gofeed.Item) int { 55 | if a.PublishedParsed.Before(*b.PublishedParsed) { 56 | return -1 57 | } else if a.PublishedParsed.After(*b.PublishedParsed) { 58 | return 1 59 | } 60 | 61 | return 0 62 | } 63 | 64 | slices.SortFunc(parsedFeed.Items, sortFunc) 65 | 66 | for _, item := range parsedFeed.Items { 67 | if item.PublishedParsed.Unix() > newestFromDB { 68 | client.Cmd.Message(channel[0], feed.Name[0:Min(20, len(feed.Name))]+": "+parsedFeed.Title+": "+item.Title+" >>> "+item.Link) 69 | } 70 | } 71 | 72 | query = fmt.Sprintf("update rss set newest_unix_time = %d where name = '%s'", parsedFeed.Items[len(parsedFeed.Items)-1].PublishedParsed.Unix(), rowName) 73 | 74 | ctx2, cancel := context.WithTimeout(context.Background(), time.Duration(10)*time.Second) 75 | defer cancel() 76 | 77 | _, err = pool.Exec(ctx2, query) 78 | if err != nil { 79 | LogError(err) 80 | } 81 | } 82 | } 83 | } 84 | 85 | func feedDispatcher( 86 | config RSSConfig, 87 | client *girc.Client, 88 | pool *pgxpool.Pool, 89 | channel []string, 90 | groupName string, 91 | period int, 92 | ) { 93 | for { 94 | if client.IsConnected() { 95 | for i := range len(config.Feeds) { 96 | config.Feeds[i].FeedParser = gofeed.NewParser() 97 | 98 | config.Feeds[i].FeedParser.UserAgent = config.Feeds[i].UserAgent 99 | 100 | if config.Feeds[i].Proxy != "" { 101 | proxyURL, err := url.Parse(config.Feeds[i].Proxy) 102 | if err != nil { 103 | LogError(err) 104 | 105 | continue 106 | } 107 | 108 | dialer, err := proxy.FromURL(proxyURL, &net.Dialer{Timeout: time.Duration(config.Feeds[i].Timeout) * time.Second}) 109 | if err != nil { 110 | LogError(err) 111 | 112 | continue 113 | } 114 | 115 | httpClient := http.Client{ 116 | Transport: &http.Transport{ 117 | Dial: dialer.Dial, 118 | }, 119 | } 120 | 121 | config.Feeds[i].FeedParser.Client = &httpClient 122 | } 123 | } 124 | 125 | for _, feed := range config.Feeds { 126 | go GetFeed(feed, client, pool, channel, groupName) 127 | } 128 | 129 | time.Sleep(time.Duration(period) * time.Second) 130 | } else { 131 | time.Sleep(time.Duration(10) * time.Second) 132 | } 133 | } 134 | } 135 | 136 | func ParseRSSConfig(rssConfFilePath string) *RSSConfig { 137 | file, err := os.Open(rssConfFilePath) 138 | if err != nil { 139 | LogError(err) 140 | 141 | return nil 142 | } 143 | 144 | var config *RSSConfig 145 | 146 | decoder := json.NewDecoder(file) 147 | 148 | err = decoder.Decode(&config) 149 | if err != nil { 150 | LogError(err) 151 | 152 | return nil 153 | } 154 | 155 | return config 156 | } 157 | 158 | func runRSS(appConfig *TomlConfig, client *girc.Client) { 159 | query := fmt.Sprintf( 160 | `create table if not exists rss ( 161 | id serial primary key, 162 | name text not null unique, 163 | newest_unix_time bigint not null 164 | )`) 165 | 166 | for { 167 | if appConfig.pool != nil { 168 | ctx, cancel := context.WithTimeout(context.Background(), time.Duration(10)*time.Second) 169 | defer cancel() 170 | 171 | _, err := appConfig.pool.Exec(ctx, query) 172 | if err != nil { 173 | LogError(err) 174 | } else { 175 | break 176 | } 177 | } 178 | 179 | time.Sleep(time.Duration(10) * time.Second) 180 | } 181 | 182 | log.Print("spawning the RSS feed dispatcher") 183 | 184 | for groupName, rss := range appConfig.Rss { 185 | rssConfig := ParseRSSConfig(rss.RssFile) 186 | if rssConfig == nil { 187 | log.Print("Could not parse RSS config file " + rss.RssFile + ". Exiting.") 188 | } else { 189 | go feedDispatcher(*rssConfig, client, appConfig.pool, rss.Channel, groupName, rssConfig.Period) 190 | } 191 | } 192 | } 193 | -------------------------------------------------------------------------------- /gemini.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "fmt" 7 | "log" 8 | "net/http" 9 | "net/url" 10 | "strings" 11 | "time" 12 | 13 | "github.com/alecthomas/chroma/v2/quick" 14 | "github.com/lrstanley/girc" 15 | "google.golang.org/genai" 16 | ) 17 | 18 | func (t *ProxyRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { 19 | transport := http.DefaultTransport.(*http.Transport).Clone() 20 | 21 | if t.ProxyURL != "" { 22 | proxyURL, err := url.Parse(t.ProxyURL) 23 | if err != nil { 24 | return nil, err 25 | } 26 | 27 | transport.Proxy = http.ProxyURL(proxyURL) 28 | } 29 | 30 | newReq := req.Clone(req.Context()) 31 | vals := newReq.URL.Query() 32 | vals.Set("key", t.APIKey) 33 | newReq.URL.RawQuery = vals.Encode() 34 | 35 | resp, err := transport.RoundTrip(newReq) 36 | if err != nil { 37 | return nil, err 38 | } 39 | 40 | return resp, nil 41 | } 42 | 43 | func DoGeminiRequest( 44 | appConfig *TomlConfig, 45 | geminiMemory *[]*genai.Content, 46 | prompt, systemPrompt string, 47 | ) (string, error) { 48 | httpProxyClient := &http.Client{Transport: &ProxyRoundTripper{ 49 | APIKey: appConfig.Apikey, 50 | ProxyURL: appConfig.LLMProxy, 51 | }} 52 | 53 | ctx, cancel := context.WithTimeout(context.Background(), time.Duration(appConfig.RequestTimeout)*time.Second) 54 | defer cancel() 55 | 56 | clientGemini, err := genai.NewClient(ctx, &genai.ClientConfig{ 57 | APIKey: appConfig.Apikey, 58 | HTTPClient: httpProxyClient, 59 | }) 60 | if err != nil { 61 | return "", fmt.Errorf("Could not create a genai client.", err) 62 | } 63 | 64 | *geminiMemory = append(*geminiMemory, genai.NewContentFromText(prompt, "user")) 65 | 66 | temperature := float32(appConfig.Temperature) 67 | topk := float32(appConfig.TopK) 68 | 69 | result, err := clientGemini.Models.GenerateContent(ctx, appConfig.Model, *geminiMemory, &genai.GenerateContentConfig{ 70 | Temperature: &temperature, 71 | SystemInstruction: genai.NewContentFromText(systemPrompt, "system"), 72 | TopK: &topk, 73 | TopP: &appConfig.TopP, 74 | // SafetySettings: []*genai.SafetySetting{ 75 | // { 76 | // Category: genai.HarmCategoryDangerousContent, 77 | // Threshold: genai.HarmBlockThresholdBlockNone, 78 | // }, 79 | // { 80 | // Category: genai.HarmCategoryHarassment, 81 | // Threshold: genai.HarmBlockThresholdBlockNone, 82 | // }, 83 | // { 84 | // Category: genai.HarmCategoryHateSpeech, 85 | // Threshold: genai.HarmBlockThresholdBlockNone, 86 | // }, 87 | // { 88 | // Category: genai.HarmCategorySexuallyExplicit, 89 | // Threshold: genai.HarmBlockThresholdBlockNone, 90 | // }, 91 | // { 92 | // Category: genai.HarmCategoryCivicIntegrity, 93 | // Threshold: genai.HarmBlockThresholdBlockNone, 94 | // }, 95 | // { 96 | // Category: genai.HarmCategoryUnspecified, 97 | // Threshold: genai.HarmBlockThresholdBlockNone, 98 | // }, 99 | // }, 100 | }) 101 | if err != nil { 102 | return "", fmt.Errorf("Gemini: Could not generate content", err) 103 | } 104 | 105 | return result.Text(), nil 106 | } 107 | 108 | func GeminiRequestProcessor( 109 | appConfig *TomlConfig, 110 | client *girc.Client, 111 | event girc.Event, 112 | geminiMemory *[]*genai.Content, 113 | prompt, systemPrompt string, 114 | ) string { 115 | geminiResponse, err := DoGeminiRequest(appConfig, geminiMemory, prompt, systemPrompt) 116 | if err != nil { 117 | client.Cmd.ReplyTo(event, "error: "+err.Error()) 118 | 119 | return "" 120 | } 121 | 122 | log.Println(geminiResponse) 123 | 124 | if len(*geminiMemory) > appConfig.MemoryLimit { 125 | *geminiMemory = []*genai.Content{} 126 | 127 | for _, context := range appConfig.Context { 128 | *geminiMemory = append(*geminiMemory, genai.NewContentFromText(context, "model")) 129 | } 130 | } 131 | 132 | *geminiMemory = append(*geminiMemory, genai.NewContentFromText(prompt, "user")) 133 | *geminiMemory = append(*geminiMemory, genai.NewContentFromText(geminiResponse, "model")) 134 | 135 | var writer bytes.Buffer 136 | 137 | err = quick.Highlight( 138 | &writer, 139 | geminiResponse, 140 | "markdown", 141 | appConfig.ChromaFormatter, 142 | appConfig.ChromaStyle) 143 | if err != nil { 144 | client.Cmd.ReplyTo(event, "error: "+err.Error()) 145 | 146 | return "" 147 | } 148 | 149 | return writer.String() 150 | } 151 | 152 | func GeminiHandler( 153 | irc *girc.Client, 154 | appConfig *TomlConfig, 155 | geminiMemory *[]*genai.Content, 156 | ) { 157 | irc.Handlers.AddBg(girc.PRIVMSG, func(client *girc.Client, event girc.Event) { 158 | if !strings.HasPrefix(event.Last(), appConfig.IrcNick+": ") { 159 | return 160 | } 161 | 162 | if appConfig.AdminOnly { 163 | byAdmin := false 164 | 165 | for _, admin := range appConfig.Admins { 166 | if event.Source.Name == admin { 167 | byAdmin = true 168 | } 169 | } 170 | 171 | if !byAdmin { 172 | return 173 | } 174 | } 175 | 176 | prompt := strings.TrimPrefix(event.Last(), appConfig.IrcNick+": ") 177 | log.Println(prompt) 178 | 179 | if string(prompt[0]) == "/" { 180 | runCommand(client, event, appConfig) 181 | 182 | return 183 | } 184 | 185 | result := GeminiRequestProcessor(appConfig, client, event, geminiMemory, prompt, appConfig.SystemPrompt) 186 | 187 | if result != "" { 188 | SendToIRC(client, event, result, appConfig.ChromaFormatter) 189 | } 190 | }) 191 | } 192 | -------------------------------------------------------------------------------- /ollama.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "encoding/json" 7 | "log" 8 | "net" 9 | "net/http" 10 | "net/url" 11 | "strings" 12 | "time" 13 | 14 | "github.com/alecthomas/chroma/v2/quick" 15 | "github.com/lrstanley/girc" 16 | "golang.org/x/net/proxy" 17 | ) 18 | 19 | func DoOllamaRequest( 20 | appConfig *TomlConfig, 21 | ollamaMemory *[]MemoryElement, 22 | prompt, systemPrompt string, 23 | ) (string, error) { 24 | var jsonPayload []byte 25 | 26 | var err error 27 | 28 | memoryElement := MemoryElement{ 29 | Role: "user", 30 | Content: prompt, 31 | } 32 | 33 | if len(*ollamaMemory) > appConfig.MemoryLimit { 34 | *ollamaMemory = []MemoryElement{} 35 | 36 | for _, context := range appConfig.Context { 37 | *ollamaMemory = append(*ollamaMemory, MemoryElement{ 38 | Role: "assistant", 39 | Content: context, 40 | }) 41 | } 42 | } 43 | 44 | *ollamaMemory = append(*ollamaMemory, memoryElement) 45 | 46 | ollamaRequest := OllamaChatRequest{ 47 | Model: appConfig.Model, 48 | KeepAlive: time.Duration(appConfig.KeepAlive), 49 | Stream: false, 50 | Think: appConfig.OllamaThink, 51 | Messages: *ollamaMemory, 52 | System: systemPrompt, 53 | Options: OllamaRequestOptions{ 54 | Mirostat: appConfig.OllamaMirostat, 55 | MirostatEta: appConfig.OllamaMirostatEta, 56 | MirostatTau: appConfig.OllamaMirostatTau, 57 | NumCtx: appConfig.OllamaNumCtx, 58 | RepeatLastN: appConfig.OllamaRepeatLastN, 59 | RepeatPenalty: appConfig.OllamaRepeatPenalty, 60 | Temperature: appConfig.Temperature, 61 | Seed: appConfig.OllamaSeed, 62 | NumPredict: appConfig.OllamaNumPredict, 63 | TopK: appConfig.TopK, 64 | TopP: appConfig.TopP, 65 | MinP: appConfig.OllamaMinP, 66 | }, 67 | } 68 | 69 | jsonPayload, err = json.Marshal(ollamaRequest) 70 | if err != nil { 71 | return "", err 72 | } 73 | 74 | log.Printf("json payload: %s", string(jsonPayload)) 75 | 76 | ctx, cancel := context.WithTimeout(context.Background(), time.Duration(appConfig.RequestTimeout)*time.Second) 77 | defer cancel() 78 | 79 | request, err := http.NewRequest(http.MethodPost, appConfig.Endpoint, bytes.NewBuffer(jsonPayload)) 80 | if err != nil { 81 | return "", err 82 | } 83 | 84 | request = request.WithContext(ctx) 85 | request.Header.Set("Content-Type", "application/json") 86 | 87 | var httpClient http.Client 88 | 89 | var dialer proxy.Dialer 90 | 91 | if appConfig.LLMProxy != "" { 92 | proxyURL, err := url.Parse(appConfig.IRCProxy) 93 | if err != nil { 94 | cancel() 95 | 96 | log.Fatal(err.Error()) 97 | } 98 | 99 | dialer, err = proxy.FromURL(proxyURL, &net.Dialer{Timeout: time.Duration(appConfig.RequestTimeout) * time.Second}) 100 | if err != nil { 101 | cancel() 102 | 103 | log.Fatal(err.Error()) 104 | } 105 | 106 | httpClient = http.Client{ 107 | Transport: &http.Transport{ 108 | Dial: dialer.Dial, 109 | }, 110 | } 111 | } 112 | 113 | response, err := httpClient.Do(request) 114 | if err != nil { 115 | return "", err 116 | } 117 | 118 | defer response.Body.Close() 119 | 120 | var ollamaChatResponse OllamaChatMessagesResponse 121 | 122 | err = json.NewDecoder(response.Body).Decode(&ollamaChatResponse) 123 | if err != nil { 124 | return "", err 125 | } 126 | 127 | log.Println("ollama chat response: ", ollamaChatResponse) 128 | 129 | return ollamaChatResponse.Messages.Content, nil 130 | } 131 | 132 | func OllamaRequestProcessor( 133 | appConfig *TomlConfig, 134 | client *girc.Client, 135 | event girc.Event, 136 | ollamaMemory *[]MemoryElement, 137 | prompt, systemPrompt string, 138 | ) string { 139 | response, err := DoOllamaRequest(appConfig, ollamaMemory, prompt, systemPrompt) 140 | if err != nil { 141 | client.Cmd.ReplyTo(event, "error: "+err.Error()) 142 | 143 | return "" 144 | } 145 | 146 | assistantElement := MemoryElement{ 147 | Role: "assistant", 148 | Content: response, 149 | } 150 | 151 | *ollamaMemory = append(*ollamaMemory, assistantElement) 152 | 153 | log.Println(response) 154 | 155 | var writer bytes.Buffer 156 | 157 | err = quick.Highlight(&writer, 158 | response, 159 | "markdown", 160 | appConfig.ChromaFormatter, 161 | appConfig.ChromaStyle) 162 | if err != nil { 163 | client.Cmd.ReplyTo(event, "error: "+err.Error()) 164 | 165 | return "" 166 | } 167 | 168 | return writer.String() 169 | } 170 | 171 | func OllamaHandler( 172 | irc *girc.Client, 173 | appConfig *TomlConfig, 174 | ollamaMemory *[]MemoryElement, 175 | ) { 176 | irc.Handlers.AddBg(girc.PRIVMSG, func(client *girc.Client, event girc.Event) { 177 | if !strings.HasPrefix(event.Last(), appConfig.IrcNick+": ") { 178 | return 179 | } 180 | 181 | if appConfig.AdminOnly { 182 | byAdmin := false 183 | 184 | for _, admin := range appConfig.Admins { 185 | if event.Source.Name == admin { 186 | byAdmin = true 187 | } 188 | } 189 | 190 | if !byAdmin { 191 | return 192 | } 193 | } 194 | 195 | prompt := strings.TrimPrefix(event.Last(), appConfig.IrcNick+": ") 196 | log.Println(prompt) 197 | 198 | if string(prompt[0]) == "/" { 199 | runCommand(client, event, appConfig) 200 | 201 | return 202 | } 203 | 204 | result := OllamaRequestProcessor(appConfig, client, event, ollamaMemory, prompt, appConfig.SystemPrompt) 205 | if result != "" { 206 | SendToIRC(client, event, result, appConfig.ChromaFormatter) 207 | } 208 | }) 209 | } 210 | -------------------------------------------------------------------------------- /ghost.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "crypto/tls" 6 | "errors" 7 | "io" 8 | "log" 9 | "net" 10 | "os" 11 | "sync" 12 | 13 | ircgomsg "github.com/ergochat/irc-go/ircmsg" 14 | "golang.org/x/net/proxy" 15 | ) 16 | 17 | func RunGhost(ghostNetwork GhostNetwork, name string) { 18 | var listener net.Listener 19 | 20 | var err error 21 | 22 | if ghostNetwork.ServerKey == "" || ghostNetwork.ServerCert == "" { 23 | log.Printf("Ghost %s: either one or both of ServerKey and ServerCert were not provided. ghosty will not be listening on TLS.", name) 24 | 25 | listener, err = net.Listen("tcp", ghostNetwork.ListenAddress) 26 | if err != nil { 27 | log.Fatalf("Ghost %s: Failed to listen on %s: %v", name, ghostNetwork.ListenAddress, err) 28 | } 29 | } else { 30 | tlsCert, err := os.ReadFile(ghostNetwork.ServerCert) 31 | if err != nil { 32 | log.Fatalf("Ghost %s: Failed to read TLS certificate file: %v", name, err) 33 | } 34 | 35 | tlsKey, err := os.ReadFile(ghostNetwork.ServerKey) 36 | if err != nil { 37 | log.Fatalf("Ghost %s: Failed to read TLS key file: %v", name, err) 38 | } 39 | 40 | cert, err := tls.X509KeyPair(tlsCert, tlsKey) 41 | if err != nil { 42 | log.Fatalf("Ghost %s: Failed to load TLS key pair: %v", name, err) 43 | } 44 | 45 | listener, err = tls.Listen("tcp", ghostNetwork.ListenAddress, &tls.Config{ 46 | MinVersion: tls.VersionTLS13, 47 | Certificates: []tls.Certificate{cert}, 48 | }) 49 | if err != nil { 50 | log.Fatalf("Ghost %s: Failed to listen on %s: %v", name, ghostNetwork.ListenAddress, err) 51 | } 52 | } 53 | 54 | defer listener.Close() 55 | 56 | log.Printf("Ghost %s: IRC Bouncer listening on %s", name, ghostNetwork.ListenAddress) 57 | log.Printf("Ghost %s: Connecting clients to IRC server: %s", name, ghostNetwork.ServerAddress) 58 | 59 | for { 60 | clientConn, err := listener.Accept() 61 | if err != nil { 62 | log.Printf("Ghost %s: Failed to accept client connection: %v", name, err) 63 | 64 | continue 65 | } 66 | 67 | go handleClientConnection(clientConn, ghostNetwork, name) 68 | } 69 | } 70 | 71 | func proxyConnectinoTLS(clientConn net.Conn, ghostNetwork GhostNetwork, name string) *tls.Conn { 72 | dialer, err := proxy.SOCKS5("tcp", ghostNetwork.UpstreamProxy, nil, proxy.Direct) 73 | if err != nil { 74 | log.Fatalf("Ghost %s: Failed to create SOCKS5 dialer: %v", name, err) 75 | } 76 | 77 | proxyCon, err := dialer.Dial("tcp", ghostNetwork.ServerAddress) 78 | if err != nil { 79 | log.Printf("Ghost %s: Failed to connect to IRC server %s via proxy %s: %v", name, ghostNetwork.ServerAddress, ghostNetwork.UpstreamProxy, err) 80 | clientConn.Close() 81 | 82 | return nil 83 | } 84 | 85 | var tlsConfig *tls.Config 86 | 87 | if ghostNetwork.CertPath != "" && ghostNetwork.KeyPath != "" { 88 | clientCert, err := tls.LoadX509KeyPair(ghostNetwork.CertPath, ghostNetwork.KeyPath) 89 | if err != nil { 90 | log.Fatalf("Ghost %s: Failed to load client TLS key pair: %v", name, err) 91 | } 92 | 93 | tlsConfig = &tls.Config{ 94 | ServerName: ghostNetwork.ServerName, 95 | Certificates: []tls.Certificate{clientCert}, 96 | InsecureSkipVerify: ghostNetwork.SkipTLSVerify, 97 | MinVersion: tls.VersionTLS13, 98 | } 99 | } else { 100 | tlsConfig = &tls.Config{ 101 | ServerName: ghostNetwork.ServerName, 102 | InsecureSkipVerify: ghostNetwork.SkipTLSVerify, 103 | MinVersion: tls.VersionTLS13, 104 | } 105 | } 106 | 107 | conn := tls.Client(proxyCon, tlsConfig) 108 | 109 | err = conn.Handshake() 110 | if err != nil { 111 | log.Printf("Ghost %s: TLS handshake with IRC server %s failed: %v", name, ghostNetwork.ServerAddress, err) 112 | clientConn.Close() 113 | 114 | return nil 115 | } 116 | 117 | return conn 118 | } 119 | 120 | func connectionTLS(clientConn net.Conn, ghostNetwork GhostNetwork, name string) *tls.Conn { 121 | clientCert, err := tls.LoadX509KeyPair(ghostNetwork.CertPath, ghostNetwork.KeyPath) 122 | if err != nil { 123 | log.Fatalf("Ghost %s: Failed to load client TLS key pair: %v", name, err) 124 | } 125 | 126 | tlsConfig := &tls.Config{ 127 | ServerName: ghostNetwork.ServerName, 128 | Certificates: []tls.Certificate{clientCert}, 129 | InsecureSkipVerify: ghostNetwork.SkipTLSVerify, 130 | MinVersion: tls.VersionTLS13, 131 | } 132 | 133 | conn, err := tls.Dial("tcp", ghostNetwork.ServerAddress, tlsConfig) 134 | if err != nil { 135 | log.Printf("Ghost %s: Failed to connect to IRC server %s with TLS: %v", name, ghostNetwork.ServerAddress, err) 136 | clientConn.Close() 137 | 138 | return nil 139 | } 140 | 141 | return conn 142 | } 143 | 144 | func proxyConnection(clientConn net.Conn, ghostNetwork GhostNetwork, name string) net.Conn { 145 | dialer, err := proxy.SOCKS5("tcp", ghostNetwork.UpstreamProxy, nil, proxy.Direct) 146 | if err != nil { 147 | log.Fatalf("Ghost %s: Failed to create SOCKS5 dialer: %v", name, err) 148 | } 149 | 150 | proxyCon, err := dialer.Dial("tcp", ghostNetwork.ServerAddress) 151 | if err != nil { 152 | log.Printf("Ghost %s: Failed to connect to IRC server %s via proxy %s: %v", name, ghostNetwork.ServerAddress, ghostNetwork.UpstreamProxy, err) 153 | clientConn.Close() 154 | 155 | return nil 156 | } 157 | 158 | return proxyCon 159 | } 160 | 161 | func handleClientConnection(clientConn net.Conn, ghostNetwork GhostNetwork, name string) { 162 | log.Printf("Ghost %s: Client connected from: %s", name, clientConn.RemoteAddr()) 163 | 164 | var ircServerConn net.Conn 165 | 166 | var err error 167 | 168 | if ghostNetwork.UpstreamProxy == "" { 169 | if ghostNetwork.UseTLS { 170 | ircServerConn = connectionTLS(clientConn, ghostNetwork, name) 171 | } else { 172 | ircServerConn, err = net.Dial("tcp", ghostNetwork.ServerAddress) 173 | if err != nil { 174 | log.Printf("Ghost %s: Failed to connect to IRC server %s: %v", name, ghostNetwork.ServerAddress, err) 175 | clientConn.Close() 176 | 177 | return 178 | } 179 | } 180 | } else { 181 | if ghostNetwork.UseTLS { 182 | ircServerConn = proxyConnectinoTLS(clientConn, ghostNetwork, name) 183 | } else { 184 | ircServerConn = proxyConnection(clientConn, ghostNetwork, name) 185 | } 186 | } 187 | 188 | if ircServerConn == nil { 189 | return 190 | } 191 | 192 | log.Printf("Ghost %s: Successfully connected to IRC server: %s", name, ghostNetwork.ServerAddress) 193 | 194 | done := make(chan struct{}) 195 | 196 | var once sync.Once 197 | 198 | closeConnections := func() { 199 | once.Do(func() { 200 | clientConn.Close() 201 | ircServerConn.Close() 202 | close(done) 203 | }) 204 | } 205 | 206 | go relay(ghostNetwork.LogRaw, clientConn, ircServerConn, closeConnections, name) 207 | 208 | go relay(ghostNetwork.LogRaw, ircServerConn, clientConn, closeConnections, name) 209 | 210 | <-done 211 | } 212 | 213 | func relay(logRaw bool, src, dest net.Conn, closer func(), name string) { 214 | reader := bufio.NewReader(src) 215 | 216 | for { 217 | line, err := reader.ReadString('\n') 218 | if err != nil { 219 | if !errors.Is(err, io.EOF) { 220 | log.Printf("Ghost %s: Relay read error on: %v", name, err) 221 | } 222 | 223 | closer() 224 | 225 | return 226 | } 227 | 228 | msg, err := ircgomsg.ParseLine(line) 229 | if err != nil { 230 | log.Printf("Ghost %s: Failed to parse IRC message: %v", name, err) 231 | } 232 | 233 | if msg.Command == "PRIVMSG" { 234 | } 235 | 236 | if msg.Command == "MSG" { 237 | } 238 | 239 | if logRaw { 240 | log.Printf("Ghost %s: %v", name, msg) 241 | } 242 | 243 | _, err = io.WriteString(dest, line) 244 | if err != nil { 245 | closer() 246 | 247 | return 248 | } 249 | } 250 | } 251 | -------------------------------------------------------------------------------- /types.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | "runtime" 7 | "time" 8 | 9 | "github.com/jackc/pgx/v5/pgxpool" 10 | "github.com/mmcdole/gofeed" 11 | lua "github.com/yuin/gopher-lua" 12 | ) 13 | 14 | type LogModel struct { 15 | // Id int64 `db:"id"` 16 | // Channel string `db:"channel"` 17 | Log string `db:"log"` 18 | // Nick string `db:"nick"` 19 | // DateAdded pgtype.Date `db:"dateadded"` 20 | } 21 | 22 | type PluginType struct { 23 | Name string `toml:"name"` 24 | Path string `toml:"path"` 25 | EnvVars [][]string `toml:"envVars"` 26 | } 27 | 28 | type CustomCommand struct { 29 | SQL string `toml:"sql"` 30 | Limit int `toml:"limit"` 31 | Context []string `toml:"context"` 32 | Prompt string `toml:"prompt"` 33 | SystemPrompt string `toml:"systemPrompt"` 34 | } 35 | 36 | type LuaLstates struct { 37 | LuaState *lua.LState 38 | Cancel context.CancelFunc 39 | } 40 | 41 | type WatchList struct { 42 | AlertChannel []string `toml:"alertChannel"` 43 | WatchList [][]string `toml:"watchList"` 44 | WatchFiles []string `toml:"watchFiles"` 45 | Words []string `toml:"watchWords"` 46 | EventTypes []string `toml:"eventTypes"` 47 | FGColor int `toml:"fgColor"` 48 | BGColor int `toml:"bgColor"` 49 | } 50 | 51 | type LuaCommand struct { 52 | Path string 53 | FuncName string 54 | } 55 | 56 | type TriggeredScripts struct { 57 | Path string 58 | FuncName string 59 | Channels [][]string 60 | TriggerTypes []string 61 | } 62 | 63 | type RssFile struct { 64 | RssFile string `toml:"rssFile"` 65 | Channel []string `toml:"channel"` 66 | } 67 | 68 | type TomlConfig struct { 69 | IrcServer string `toml:"ircServer"` 70 | IrcNick string `toml:"ircNick"` 71 | IrcSaslUser string `toml:"ircSaslUser"` 72 | IrcSaslPass string `toml:"ircSaslPass"` 73 | Endpoint string `toml:"endpoint"` 74 | Model string `toml:"model"` 75 | ChromaStyle string `toml:"chromaStyle"` 76 | ChromaFormatter string `toml:"chromaFormatter"` 77 | Provider string `toml:"provider"` 78 | Apikey string `toml:"apikey"` 79 | ClientCertPath string `toml:"clientCertPath"` 80 | ServerPass string `toml:"serverPass"` 81 | Bind string `toml:"bind"` 82 | Name string `toml:"name"` 83 | DatabaseAddress string `toml:"databaseAddress"` 84 | DatabasePassword string `toml:"databasePassword"` 85 | DatabaseUser string `toml:"databaseUser"` 86 | DatabaseName string `toml:"databaseName"` 87 | LLMProxy string `toml:"llmProxy"` 88 | IRCProxy string `toml:"ircProxy"` 89 | GeneralProxy string `toml:"generalProxy"` 90 | IRCDName string `toml:"ircdName"` 91 | WebIRCPassword string `toml:"webIRCPassword"` 92 | WebIRCGateway string `toml:"webIRCGateway"` 93 | WebIRCHostname string `toml:"webIRCHostname"` 94 | WebIRCAddress string `toml:"webIRCAddress"` 95 | RSSFile string `toml:"rssFile"` 96 | AnthropicVersion string `toml:"anthropicVersion"` 97 | Plugins []string `toml:"plugins"` 98 | Context []string `toml:"context"` 99 | SystemPrompt string `toml:"systemPrompt"` 100 | CustomCommands map[string]CustomCommand `toml:"customCommands"` 101 | WatchLists map[string]WatchList `toml:"watchList"` 102 | LuaStates map[string]LuaLstates 103 | LuaCommands map[string]LuaCommand 104 | TriggeredScripts map[string]TriggeredScripts 105 | Rss map[string]RssFile `toml:"rss"` 106 | UserAgentActions map[string]UserAgentRequest `toml:"userAgentActions"` 107 | Aliases map[string]Alias `toml:"aliases"` 108 | RequestTimeout int `toml:"requestTimeout"` 109 | MillaReconnectDelay int `toml:"millaReconnectDelay"` 110 | IrcPort int `toml:"ircPort"` 111 | KeepAlive int `toml:"keepAlive"` 112 | MemoryLimit int `toml:"memoryLimit"` 113 | PingDelay int `toml:"pingDelay"` 114 | PingTimeout int `toml:"pingTimeout"` 115 | OllamaMirostat int `toml:"ollamaMirostat"` 116 | OllamaMirostatEta float64 `toml:"ollamaMirostatEta"` 117 | OllamaMirostatTau float64 `toml:"ollamaMirostatTau"` 118 | OllamaNumCtx int `toml:"ollamaNumCtx"` 119 | OllamaRepeatLastN int `toml:"ollamaRepeatLastN"` 120 | OllamaRepeatPenalty float64 `toml:"ollamaRepeatPenalty"` 121 | Temperature float64 `toml:"temperature"` 122 | OllamaSeed int `toml:"ollamaSeed"` 123 | OllamaNumPredict int `toml:"ollamaNumPredict"` 124 | OllamaMinP float64 `toml:"ollamaMinP"` 125 | OllamaThink string `toml:"ollamaThink"` 126 | TopP float32 `toml:"topP"` 127 | TopK int32 `toml:"topK"` 128 | IrcBackOffInitialInterval int `toml:"ircBackOffInitialInterval"` 129 | IrcBackOffRandomizationFactor float64 `toml:"ircbackOffRandomizationFactor"` 130 | IrcBackOffMultiplier float64 `toml:"ircBackOffMultiplier"` 131 | IrcBackOffMaxInterval int `toml:"ircBackOffMaxInterval"` 132 | DbBackOffInitialInterval int `toml:"dbBackOffInitialInterval"` 133 | DbBackOffRandomizationFactor float64 `toml:"dbBackOffRandomizationFactor"` 134 | DbBackOffMultiplier float64 `toml:"dbBackOffMultiplier"` 135 | DbBackOffMaxInterval int `toml:"dbBackOffMaxInterval"` 136 | EnableSasl bool `toml:"enableSasl"` 137 | SkipTLSVerify bool `toml:"skipTLSVerify"` 138 | UseTLS bool `toml:"useTLS"` 139 | DisableSTSFallback bool `toml:"disableSTSFallback"` 140 | AllowFlood bool `toml:"allowFlood"` 141 | Debug bool `toml:"debug"` 142 | Out bool `toml:"out"` 143 | AdminOnly bool `toml:"adminOnly"` 144 | pool *pgxpool.Pool 145 | Admins []string `toml:"admins"` 146 | IrcChannels [][]string `toml:"ircChannels"` 147 | ScrapeChannels [][]string `toml:"scrapeChannels"` 148 | } 149 | 150 | func (config *TomlConfig) insertLState( 151 | name string, 152 | luaState *lua.LState, 153 | cancel context.CancelFunc, 154 | ) { 155 | if config.LuaStates == nil { 156 | config.LuaStates = make(map[string]LuaLstates) 157 | } 158 | config.LuaStates[name] = LuaLstates{ 159 | LuaState: luaState, 160 | Cancel: cancel, 161 | } 162 | } 163 | 164 | func (config *TomlConfig) deleteLstate(name string) { 165 | if config.LuaStates == nil { 166 | return 167 | } 168 | 169 | if config.LuaStates[name].Cancel != nil { 170 | config.LuaStates[name].Cancel() 171 | } 172 | delete(config.LuaStates, name) 173 | } 174 | 175 | func (config *TomlConfig) insertLuaCommand( 176 | cmd, path, name string, 177 | ) { 178 | if config.LuaCommands == nil { 179 | config.LuaCommands = make(map[string]LuaCommand) 180 | } 181 | config.LuaCommands[cmd] = LuaCommand{Path: path, FuncName: name} 182 | } 183 | 184 | func (config *TomlConfig) deleteLuaCommand(name string) { 185 | if config.LuaCommands == nil { 186 | return 187 | } 188 | delete(config.LuaCommands, name) 189 | } 190 | 191 | func (config *TomlConfig) insertTriggeredScript(path, cmd string, triggerType []string) { 192 | if config.TriggeredScripts == nil { 193 | config.TriggeredScripts = make(map[string]TriggeredScripts) 194 | } 195 | config.TriggeredScripts[path] = TriggeredScripts{ 196 | Path: path, 197 | FuncName: cmd, 198 | TriggerTypes: triggerType, 199 | } 200 | } 201 | 202 | func (config *TomlConfig) deleteTriggeredScript(name string) { 203 | if config.TriggeredScripts == nil { 204 | return 205 | } 206 | 207 | delete(config.TriggeredScripts, name) 208 | } 209 | 210 | type AppConfig struct { 211 | Ircd map[string]TomlConfig `toml:"ircd"` 212 | Ghost map[string]GhostNetwork `toml:"ghost"` 213 | } 214 | 215 | type OllamaRequestOptions struct { 216 | Mirostat int `json:"mirostat"` 217 | MirostatEta float64 `json:"mirostat_eta"` 218 | MirostatTau float64 `json:"mirostat_tau"` 219 | NumCtx int `json:"num_ctx"` 220 | RepeatLastN int `json:"repeat_last_n"` 221 | RepeatPenalty float64 `json:"repeat_penalty"` 222 | Temperature float64 `json:"temperature"` 223 | Seed int `json:"seed"` 224 | NumPredict int `json:"num_predict"` 225 | TopK int32 `json:"top_k"` 226 | TopP float32 `json:"top_p"` 227 | MinP float64 `json:"min_p"` 228 | } 229 | 230 | type OllamaChatResponse struct { 231 | Role string `json:"role"` 232 | Content string `json:"content"` 233 | } 234 | 235 | type OllamaChatMessagesResponse struct { 236 | Messages OllamaChatResponse `json:"message"` 237 | } 238 | 239 | type OllamaChatRequest struct { 240 | Model string `json:"model"` 241 | Stream bool `json:"stream"` 242 | Think string `json:"think"` 243 | KeepAlive time.Duration `json:"keep_alive"` 244 | Options OllamaRequestOptions `json:"options"` 245 | System string `json:"system"` 246 | Messages []MemoryElement `json:"messages"` 247 | } 248 | 249 | type ORMessage struct { 250 | Role string `json:"role"` 251 | Content string `json:"content"` 252 | Refusal string `json:"refusal"` 253 | } 254 | 255 | type ORChoice struct { 256 | FinishReason string `json:"finish_reason"` 257 | Index int `json:"index"` 258 | Message ORMessage `json:"message"` 259 | } 260 | 261 | type ORUsage struct { 262 | PromptTokens int `json:"prompt_tokens"` 263 | CompletionTokens int `json:"completion_tokens"` 264 | TotalTokens int `json:"total_tokens"` 265 | } 266 | type ORResponse struct { 267 | Id string `json:"id"` 268 | Provider string `json:"provider"` 269 | Model string `json:"model"` 270 | Object string `json:"object"` 271 | Created int64 `json:"created"` 272 | Choices []ORChoice `json:"choices"` 273 | SystemFingerprint string `json:"system_fingerprint"` 274 | Usage ORUsage `json:"usage"` 275 | } 276 | 277 | type MemoryElement struct { 278 | Role string `json:"role"` 279 | Content string `json:"content"` 280 | } 281 | 282 | type FeedConfig struct { 283 | Name string `json:"name"` 284 | URL string `json:"url"` 285 | UserAgent string `json:"userAgent"` 286 | Proxy string `json:"proxy"` 287 | Timeout int `json:"timeout"` 288 | FeedParser *gofeed.Parser 289 | } 290 | 291 | type RSSConfig struct { 292 | Feeds []FeedConfig `json:"feeds"` 293 | Period int `json:"period"` 294 | } 295 | 296 | func LogError(err error) { 297 | fn, file, line, ok := runtime.Caller(1) 298 | if ok { 299 | log.Printf("%s: %s-%d >>> %v", runtime.FuncForPC(fn).Name(), file, line, err) 300 | } else { 301 | log.Print(err) 302 | } 303 | } 304 | 305 | func LogErrorFatal(err error) { 306 | fn, file, line, ok := runtime.Caller(1) 307 | if ok { 308 | log.Fatalf("%s: %s-%d >>> %v", runtime.FuncForPC(fn).Name(), file, line, err) 309 | } else { 310 | log.Fatal(err) 311 | } 312 | } 313 | 314 | type ProxyRoundTripper struct { 315 | APIKey string 316 | 317 | ProxyURL string 318 | } 319 | 320 | type UserAgentRequest struct { 321 | Agent_Name string `json:"agent_name" toml:"agent_name"` 322 | Instructions string `json:"instructions" toml:"instructions"` 323 | Query string `json:"query" toml:"query"` 324 | } 325 | 326 | type UserAgentResponse struct { 327 | Agent_Name string `json:"agent_name"` 328 | Response string `json:"response"` 329 | } 330 | 331 | type Alias struct { 332 | Alias string `toml:"alias"` 333 | } 334 | 335 | type GhostRuleSet struct { 336 | Types []string `toml:"types"` 337 | OllamaEndpoint string `toml:"ollamaEndpoint"` 338 | Instructions []string `toml:"instructions"` 339 | Prompt string `toml:"prompt"` 340 | DisableAll bool `toml:"disableAll"` 341 | WhiteList []string `toml:"whiteList"` 342 | EnableAll bool `toml:"enableAll"` 343 | BlackList []string `toml:"blackList"` 344 | Incoming bool `toml:"incoming"` 345 | Rephrase bool `toml:"rephrase"` 346 | } 347 | 348 | type GhostNetwork struct { 349 | ServerCert string `toml:"serverCert"` 350 | ServerKey string `toml:"serverKey"` 351 | ServerAddress string `toml:"ServerAddress"` 352 | ServerName string `toml:"serverName"` 353 | UpstreamProxy string `toml:"upstreamProxy"` 354 | UseTLS bool `toml:"useTLS"` 355 | SkipTLSVerify bool `toml:"skipTLSVerify"` 356 | SaslUser string `toml:"saslUser"` 357 | SaslPass string `toml:"saslPass"` 358 | CertPath string `toml:"certPath"` 359 | KeyPath string `toml:"keyPath"` 360 | ListenAddress string `toml:"listenAddress"` 361 | LogRaw bool `toml:"logRaw"` 362 | GhostRuleSets map[string]GhostRuleSet `toml:"ghostRuleSet"` 363 | } 364 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | cloud.google.com/go v0.120.0 h1:wc6bgG9DHyKqF5/vQvX1CiZrtHnxJjBlKUyF9nP6meA= 2 | cloud.google.com/go v0.120.0/go.mod h1:/beW32s8/pGRuj4IILWQNd4uuebeT4dkOhKmkfit64Q= 3 | cloud.google.com/go/auth v0.15.0 h1:Ly0u4aA5vG/fsSsxu98qCQBemXtAtJf+95z9HK+cxps= 4 | cloud.google.com/go/auth v0.15.0/go.mod h1:WJDGqZ1o9E9wKIL+IwStfyn/+s59zl4Bi+1KQNVXLZ8= 5 | cloud.google.com/go/compute/metadata v0.6.0 h1:A6hENjEsCDtC1k8byVsgwvVcioamEHvZ4j01OwKxG9I= 6 | cloud.google.com/go/compute/metadata v0.6.0/go.mod h1:FjyFAW1MW0C203CEOMDTu3Dk1FlqW3Rga40jzHL4hfg= 7 | github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg= 8 | github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= 9 | github.com/PuerkitoBio/goquery v1.10.3 h1:pFYcNSqHxBD06Fpj/KsbStFRsgRATgnf3LeXiUkhzPo= 10 | github.com/PuerkitoBio/goquery v1.10.3/go.mod h1:tMUX0zDMHXYlAQk6p35XxQMqMweEKB7iK7iLNd4RH4Y= 11 | github.com/ailncode/gluaxmlpath v0.0.0-20161126153117-6ce478ecb4a6 h1:FM0WudTZ+xeiXPJcs+X1Zg8JXe4vlb9P2GZYqCYjZkk= 12 | github.com/ailncode/gluaxmlpath v0.0.0-20161126153117-6ce478ecb4a6/go.mod h1:Ti1AvV2KUYtHEBX7eYbdAGEfFyKz9+lHrJPcr79Vkng= 13 | github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0= 14 | github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= 15 | github.com/alecthomas/chroma/v2 v2.16.0 h1:QC5ZMizk67+HzxFDjQ4ASjni5kWBTGiigRG1u23IGvA= 16 | github.com/alecthomas/chroma/v2 v2.16.0/go.mod h1:RVX6AvYm4VfYe/zsk7mjHueLDZor3aWCNE14TFlepBk= 17 | github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc= 18 | github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= 19 | github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM= 20 | github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA= 21 | github.com/awnumar/memcall v0.1.2 h1:7gOfDTL+BJ6nnbtAp9+HQzUFjtP1hEseRQq8eP055QY= 22 | github.com/awnumar/memcall v0.1.2/go.mod h1:S911igBPR9CThzd/hYQQmTc9SWNu3ZHIlCGaWsWsoJo= 23 | github.com/cenkalti/backoff/v5 v5.0.2 h1:rIfFVxEf1QsI7E1ZHfp/B4DF/6QBAUhmgkxc0H7Zss8= 24 | github.com/cenkalti/backoff/v5 v5.0.2/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= 25 | github.com/cjoudrey/gluahttp v0.0.0-20201111170219-25003d9adfa9 h1:rdWOzitWlNYeUsXmz+IQfa9NkGEq3gA/qQ3mOEqBU6o= 26 | github.com/cjoudrey/gluahttp v0.0.0-20201111170219-25003d9adfa9/go.mod h1:X97UjDTXp+7bayQSFZk2hPvCTmTZIicUjZQRtkwgAKY= 27 | github.com/coyim/constbn v0.0.0-20230207191538-27f0129d98cd h1:tWNy3iPXxx5wmWH8qm7TuDM9vDLWWj18Pp7uxUQILpo= 28 | github.com/coyim/constbn v0.0.0-20230207191538-27f0129d98cd/go.mod h1:3IbgUXKHr9lHYW0qRClJ+UiGNwcvWm5Ce1iOY2Pe/oA= 29 | github.com/coyim/otr3 v0.0.0-20230314203300-86897a28af47 h1:mL+cP7RQUnuAhGW4+wPouDQEU1YuslV/4vjkcI4Ec2w= 30 | github.com/coyim/otr3 v0.0.0-20230314203300-86897a28af47/go.mod h1:7iUG2JMfJTDx4XgHkrSsCtS3iLGCnuEjuZXoXO3lBrc= 31 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 32 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 33 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 34 | github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ= 35 | github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= 36 | github.com/ergochat/irc-go v0.4.0 h1:0YibCKfAAtwxQdNjLQd9xpIEPisLcJ45f8FNsMHAuZc= 37 | github.com/ergochat/irc-go v0.4.0/go.mod h1:2vi7KNpIPWnReB5hmLpl92eMywQvuIeIIGdt/FQCph0= 38 | github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= 39 | github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= 40 | github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= 41 | github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= 42 | github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= 43 | github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= 44 | github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= 45 | github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= 46 | github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= 47 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 48 | github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= 49 | github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= 50 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 51 | github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= 52 | github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= 53 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= 54 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 55 | github.com/googleapis/enterprise-certificate-proxy v0.3.6 h1:GW/XbdyBFQ8Qe+YAmFU9uHLo7OnF5tL52HFAgMmyrf4= 56 | github.com/googleapis/enterprise-certificate-proxy v0.3.6/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= 57 | github.com/googleapis/gax-go/v2 v2.14.1 h1:hb0FFeiPaQskmvakKu5EbCbpntQn48jyHuvrkurSS/Q= 58 | github.com/googleapis/gax-go/v2 v2.14.1/go.mod h1:Hb/NubMaVM88SrNkvl8X/o8XWwDJEPqouaLeN2IUxoA= 59 | github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= 60 | github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= 61 | github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= 62 | github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= 63 | github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= 64 | github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= 65 | github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= 66 | github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= 67 | github.com/jackc/pgx/v5 v5.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg= 68 | github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ= 69 | github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= 70 | github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= 71 | github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= 72 | github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= 73 | github.com/kohkimakimoto/gluayaml v0.0.0-20160815032708-6fe413d49d73 h1:e2UU76WBjv6W0QUuPHe2QfSAXLR1kouek1fcSUtnSrk= 74 | github.com/kohkimakimoto/gluayaml v0.0.0-20160815032708-6fe413d49d73/go.mod h1:I+YgUp/uc0hF+H4RuQjR+uzDJNjUz7Sm21e63UCLWWQ= 75 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= 76 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= 77 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 78 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 79 | github.com/layeh/gopher-json v0.0.0-20201124131017-552bb3c4c3bf h1:bg6J/5S/AeTz7K9i/luJRj31BJ8f+LgYwKQBSOZxSEM= 80 | github.com/layeh/gopher-json v0.0.0-20201124131017-552bb3c4c3bf/go.mod h1:E/q28EyUVBgBQnONAVPIdwvEsv4Ve0vaCA9JWim4+3I= 81 | github.com/lrstanley/girc v0.0.0-20250219025855-423afa8a8828 h1:tJcJDAvGGM1xy1gt6A/7jzTLOnjJsDTxOkykzEgoh9w= 82 | github.com/lrstanley/girc v0.0.0-20250219025855-423afa8a8828/go.mod h1:lgrnhcF8bg/Bd5HA5DOb4Z+uGqUqGnp4skr+J2GwVgI= 83 | github.com/mmcdole/gofeed v1.3.0 h1:5yn+HeqlcvjMeAI4gu6T+crm7d0anY85+M+v6fIFNG4= 84 | github.com/mmcdole/gofeed v1.3.0/go.mod h1:9TGv2LcJhdXePDzxiuMnukhV2/zb6VtnZt1mS+SjkLE= 85 | github.com/mmcdole/goxpp v1.1.1 h1:RGIX+D6iQRIunGHrKqnA2+700XMCnNv0bAOOv5MUhx8= 86 | github.com/mmcdole/goxpp v1.1.1/go.mod h1:v+25+lT2ViuQ7mVxcncQ8ch1URund48oH+jhjiwEgS8= 87 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 88 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= 89 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 90 | github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= 91 | github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= 92 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 93 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 94 | github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= 95 | github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= 96 | github.com/sashabaranov/go-openai v1.38.1 h1:TtZabbFQZa1nEni/IhVtDF/WQjVqDgd+cWR5OeddzF8= 97 | github.com/sashabaranov/go-openai v1.38.1/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg= 98 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 99 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 100 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 101 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= 102 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 103 | github.com/yuin/gluare v0.0.0-20170607022532-d7c94f1a80ed h1:I1vcLHWU9m30rA90rMrKPu0eD3NDA4FBlkB8WMaDyUw= 104 | github.com/yuin/gluare v0.0.0-20170607022532-d7c94f1a80ed/go.mod h1:9w6KSdZh23UWqOywWsRLUcJUrUNjRh4Ql3z9uVgnSP4= 105 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= 106 | github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M= 107 | github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw= 108 | gitlab.com/megalithic-llc/gluasocket v0.3.1 h1:CtsSTZa3G5WnMbhZ3TgvpLwpVlQv6KjO2mqxNOGrhY4= 109 | gitlab.com/megalithic-llc/gluasocket v0.3.1/go.mod h1:/FBarfbXYDsAPzx16ZUmql2rq7GLU5HeuhaJOC9DeBw= 110 | go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= 111 | go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= 112 | go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0 h1:sbiXRNDSWJOTobXh5HyQKjq6wUC5tNybqjIqDpAY4CU= 113 | go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0/go.mod h1:69uWxva0WgAA/4bu2Yy70SLDBwZXuQ6PbBpbsa5iZrQ= 114 | go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ= 115 | go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y= 116 | go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M= 117 | go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE= 118 | go.opentelemetry.io/otel/sdk v1.35.0 h1:iPctf8iprVySXSKJffSS79eOjl9pvxV9ZqOWT0QejKY= 119 | go.opentelemetry.io/otel/sdk v1.35.0/go.mod h1:+ga1bZliga3DxJ3CQGg3updiaAJoNECOgJREo9KHGQg= 120 | go.opentelemetry.io/otel/sdk/metric v1.35.0 h1:1RriWBmCKgkeHEhM7a2uMjMUfP7MsOF5JpUCaEqEI9o= 121 | go.opentelemetry.io/otel/sdk/metric v1.35.0/go.mod h1:is6XYCUMpcKi+ZsOvfluY5YstFnhW0BidkR+gL+qN+w= 122 | go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs= 123 | go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc= 124 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 125 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= 126 | golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= 127 | golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= 128 | golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= 129 | golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= 130 | golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE= 131 | golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc= 132 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= 133 | golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= 134 | golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= 135 | golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= 136 | golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= 137 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 138 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= 139 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= 140 | golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= 141 | golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= 142 | golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= 143 | golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= 144 | golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= 145 | golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= 146 | golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY= 147 | golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E= 148 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 149 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 150 | golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 151 | golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= 152 | golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 153 | golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 154 | golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 155 | golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610= 156 | golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= 157 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 158 | golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 159 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 160 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 161 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 162 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 163 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 164 | golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 165 | golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 166 | golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 167 | golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 168 | golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 169 | golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20= 170 | golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= 171 | golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= 172 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 173 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 174 | golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= 175 | golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= 176 | golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= 177 | golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= 178 | golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= 179 | golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= 180 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 181 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 182 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 183 | golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 184 | golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= 185 | golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= 186 | golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= 187 | golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= 188 | golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= 189 | golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0= 190 | golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU= 191 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 192 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 193 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= 194 | golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= 195 | golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= 196 | golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= 197 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 198 | google.golang.org/genai v1.0.0 h1:9IIZimT9bJm0wiF55VAoGCL8MfOAZcwqRRlxZZ/KSoc= 199 | google.golang.org/genai v1.0.0/go.mod h1:TyfOKRz/QyCaj6f/ZDt505x+YreXnY40l2I6k8TvgqY= 200 | google.golang.org/genproto/googleapis/rpc v0.0.0-20250414145226-207652e42e2e h1:ztQaXfzEXTmCBvbtWYRhJxW+0iJcz2qXfd38/e9l7bA= 201 | google.golang.org/genproto/googleapis/rpc v0.0.0-20250414145226-207652e42e2e/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= 202 | google.golang.org/grpc v1.71.1 h1:ffsFWr7ygTUscGPI0KKK6TLrGz0476KUvvsbqWK0rPI= 203 | google.golang.org/grpc v1.71.1/go.mod h1:H0GRtasmQOh9LkFoCPDu3ZrwUtD1YGE+b2vYBYd/8Ec= 204 | google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= 205 | google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= 206 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 207 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= 208 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= 209 | gopkg.in/xmlpath.v2 v2.0.0-20150820204837-860cbeca3ebc h1:LMEBgNcZUqXaP7evD1PZcL6EcDVa2QOFuI+cqM3+AJM= 210 | gopkg.in/xmlpath.v2 v2.0.0-20150820204837-860cbeca3ebc/go.mod h1:N8UOSI6/c2yOpa/XDz3KVUiegocTziPiqNkeNTMiG1k= 211 | gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= 212 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 213 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 214 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 215 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 216 | -------------------------------------------------------------------------------- /plugins.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | "net/http" 7 | "net/url" 8 | "os" 9 | "reflect" 10 | "strings" 11 | 12 | "github.com/ailncode/gluaxmlpath" 13 | "github.com/cjoudrey/gluahttp" 14 | "github.com/jackc/pgx/v5" 15 | "github.com/kohkimakimoto/gluayaml" 16 | gopherjson "github.com/layeh/gopher-json" 17 | "github.com/lrstanley/girc" 18 | openai "github.com/sashabaranov/go-openai" 19 | "github.com/yuin/gluare" 20 | lua "github.com/yuin/gopher-lua" 21 | "gitlab.com/megalithic-llc/gluasocket" 22 | "google.golang.org/genai" 23 | ) 24 | 25 | func registerStructAsLuaMetaTable[T any]( 26 | luaState *lua.LState, 27 | luaLTable *lua.LTable, 28 | checkStruct func(luaState *lua.LState) *T, 29 | structType T, 30 | metaTableName string, 31 | ) { 32 | metaTable := luaState.NewTypeMetatable(metaTableName) 33 | 34 | luaState.SetField(luaLTable, metaTableName, metaTable) 35 | 36 | luaState.SetField( 37 | metaTable, 38 | "new", 39 | luaState.NewFunction( 40 | newStructFunctionFactory(structType, metaTableName), 41 | ), 42 | ) 43 | 44 | var dummyType T 45 | tableMethods := luaTableGenFactory(reflect.TypeOf(dummyType), checkStruct) 46 | 47 | luaState.SetField( 48 | metaTable, 49 | "__index", 50 | luaState.SetFuncs( 51 | luaState.NewTable(), 52 | tableMethods, 53 | ), 54 | ) 55 | } 56 | 57 | func newStructFunctionFactory[T any](structType T, metaTableName string) func(*lua.LState) int { 58 | return func(luaState *lua.LState) int { 59 | structInstance := &structType 60 | ud := luaState.NewUserData() 61 | ud.Value = structInstance 62 | luaState.SetMetatable(ud, luaState.GetTypeMetatable(metaTableName)) 63 | luaState.Push(ud) 64 | 65 | return 1 66 | } 67 | } 68 | 69 | func checkStruct[T any](luaState *lua.LState) *T { 70 | userData := luaState.CheckUserData(1) 71 | 72 | if v, ok := userData.Value.(*T); ok { 73 | return v 74 | } 75 | 76 | luaState.ArgError(1, "got wrong struct") 77 | 78 | return nil 79 | } 80 | 81 | func getterSetterFactory[T any]( 82 | fieldName string, 83 | fieldType reflect.Type, 84 | checkStruct func(luaState *lua.LState) *T, 85 | ) func(*lua.LState) int { 86 | return func(luaState *lua.LState) int { 87 | genericStruct := checkStruct(luaState) 88 | 89 | structValue := reflect.ValueOf(genericStruct).Elem() 90 | 91 | fieldValue := structValue.FieldByName(fieldName) 92 | 93 | if luaState.GetTop() == 2 { //nolint: mnd,gomnd 94 | switch fieldType.Kind() { 95 | case reflect.String: 96 | fieldValue.SetString(luaState.CheckString(2)) //nolint: mnd,gomnd 97 | case reflect.Float64: 98 | fieldValue.SetFloat(float64(luaState.CheckNumber(2))) //nolint: mnd,gomnd 99 | case reflect.Float32: 100 | fieldValue.SetFloat(float64(luaState.CheckNumber(2))) //nolint: mnd,gomnd 101 | case reflect.Int8: 102 | fieldValue.SetInt(int64(luaState.CheckInt(2))) //nolint: mnd,gomnd 103 | case reflect.Int16: 104 | fieldValue.SetInt(int64(luaState.CheckInt(2))) //nolint: mnd,gomnd 105 | case reflect.Int: 106 | fieldValue.SetInt(int64(luaState.CheckInt(2))) //nolint: mnd,gomnd 107 | case reflect.Int32: 108 | fieldValue.SetInt(int64(luaState.CheckInt(2))) //nolint: mnd,gomnd 109 | case reflect.Int64: 110 | fieldValue.SetInt(int64(luaState.CheckInt(2))) //nolint: mnd,gomnd 111 | case reflect.Bool: 112 | fieldValue.SetBool(luaState.CheckBool(2)) //nolint: mnd,gomnd 113 | case reflect.Uint: 114 | fieldValue.SetUint(uint64(luaState.CheckInt(2))) //nolint: mnd,gomnd 115 | case reflect.Uint8: 116 | fieldValue.SetUint(uint64(luaState.CheckInt(2))) //nolint: mnd,gomnd 117 | case reflect.Uint16: 118 | fieldValue.SetUint(uint64(luaState.CheckInt(2))) //nolint: mnd,gomnd 119 | case reflect.Uint32: 120 | fieldValue.SetUint(uint64(luaState.CheckInt(2))) //nolint: mnd,gomnd 121 | case reflect.Uint64: 122 | fieldValue.SetUint(uint64(luaState.CheckInt(2))) //nolint: mnd,gomnd 123 | case reflect.Func: 124 | case reflect.Ptr: 125 | case reflect.Struct: 126 | case reflect.Slice: 127 | case reflect.Array: 128 | case reflect.Map: 129 | default: 130 | log.Print("unsupported type") 131 | } 132 | 133 | return 0 134 | } 135 | 136 | switch fieldType.Kind() { 137 | case reflect.String: 138 | luaState.Push(lua.LString(fieldValue.Interface().(string))) 139 | case reflect.Float64: 140 | luaState.Push(lua.LNumber(fieldValue.Interface().(float64))) 141 | case reflect.Float32: 142 | luaState.Push(lua.LNumber(fieldValue.Float())) 143 | case reflect.Int8: 144 | luaState.Push(lua.LNumber(fieldValue.Int())) 145 | case reflect.Int16: 146 | luaState.Push(lua.LNumber(fieldValue.Int())) 147 | case reflect.Int: 148 | luaState.Push(lua.LNumber(fieldValue.Int())) 149 | case reflect.Int32: 150 | luaState.Push(lua.LNumber(fieldValue.Int())) 151 | case reflect.Int64: 152 | luaState.Push(lua.LNumber(fieldValue.Int())) 153 | case reflect.Bool: 154 | luaState.Push(lua.LBool(fieldValue.Bool())) 155 | case reflect.Uint: 156 | luaState.Push(lua.LNumber(fieldValue.Uint())) 157 | case reflect.Uint8: 158 | luaState.Push(lua.LNumber(fieldValue.Uint())) 159 | case reflect.Uint16: 160 | luaState.Push(lua.LNumber(fieldValue.Uint())) 161 | case reflect.Uint32: 162 | luaState.Push(lua.LNumber(fieldValue.Uint())) 163 | case reflect.Uint64: 164 | luaState.Push(lua.LNumber(fieldValue.Uint())) 165 | case reflect.Func: 166 | case reflect.Ptr: 167 | case reflect.Struct: 168 | case reflect.Slice: 169 | case reflect.Array: 170 | case reflect.Map: 171 | default: 172 | log.Print("unsupported type") 173 | } 174 | 175 | return 1 176 | } 177 | } 178 | 179 | func luaTableGenFactory[T any]( 180 | structType reflect.Type, 181 | checkStructType func(luaState *lua.LState) *T) map[string]lua.LGFunction { 182 | tableMethods := make(map[string]lua.LGFunction) 183 | 184 | for _, field := range reflect.VisibleFields(structType) { 185 | tableMethods[field.Name] = getterSetterFactory(field.Name, field.Type, checkStructType) 186 | } 187 | 188 | return tableMethods 189 | } 190 | 191 | func sendMessageClosure(luaState *lua.LState, client *girc.Client) func(*lua.LState) int { 192 | return func(luaState *lua.LState) int { 193 | message := luaState.CheckString(1) 194 | target := luaState.CheckString(2) //nolint: mnd,gomnd 195 | 196 | client.Cmd.Message(target, message) 197 | 198 | return 0 199 | } 200 | } 201 | 202 | func replyToMessageClosure(luaStete *lua.LState, client *girc.Client, event girc.Event) func(*lua.LState) int { 203 | return func(luaState *lua.LState) int { 204 | message := luaState.CheckString(1) 205 | 206 | client.Cmd.Message(event.Source.Name, message) 207 | 208 | return 0 209 | } 210 | } 211 | 212 | func registerLuaCommand(luaState *lua.LState, appConfig *TomlConfig) func(*lua.LState) int { 213 | return func(luaState *lua.LState) int { 214 | path := luaState.CheckString(1) 215 | commandName := luaState.CheckString(2) //nolint: mnd,gomnd 216 | funcName := luaState.CheckString(3) //nolint: mnd,gomnd 217 | 218 | _, ok := appConfig.LuaCommands[commandName] 219 | if ok { 220 | log.Print("command already registered: ", commandName) 221 | 222 | return 0 223 | } 224 | 225 | appConfig.insertLuaCommand(commandName, path, funcName) 226 | 227 | log.Print("registered command: ", commandName, path, funcName) 228 | 229 | return 0 230 | } 231 | } 232 | 233 | func registerTriggeredScript(luaState *lua.LState, appConfig *TomlConfig) func(*lua.LState) int { 234 | return func(luaState *lua.LState) int { 235 | path := luaState.CheckString(1) 236 | funcName := luaState.CheckString(3) //nolint: mnd,gomnd 237 | eventTypesTable := luaState.CheckTable(2) //nolint: mnd,gomnd 238 | 239 | _, ok := appConfig.TriggeredScripts[path] 240 | if ok { 241 | log.Print("triggered script already registered: ", path) 242 | 243 | return 0 244 | } 245 | 246 | var eventTypes []string 247 | 248 | eventTypesTable.ForEach(func(_, value lua.LValue) { 249 | if value.Type() != lua.LTString { 250 | log.Print("event type for TriggeredScripts must be a string") 251 | } else { 252 | eventTypes = append(eventTypes, value.String()) 253 | } 254 | }) 255 | 256 | appConfig.insertTriggeredScript(path, funcName, eventTypes) 257 | 258 | return 0 259 | } 260 | } 261 | 262 | func ircJoinChannelClosure(luaState *lua.LState, client *girc.Client) func(*lua.LState) int { 263 | return func(luaState *lua.LState) int { 264 | channel := luaState.CheckString(1) 265 | password := luaState.CheckString(2) //nolint: mnd,gomnd 266 | 267 | if password != "" { 268 | client.Cmd.JoinKey(channel, password) 269 | } else { 270 | client.Cmd.Join(channel) 271 | } 272 | 273 | return 0 274 | } 275 | } 276 | 277 | func ircPartChannelClosure(luaState *lua.LState, client *girc.Client) func(*lua.LState) int { 278 | return func(luaState *lua.LState) int { 279 | channel := luaState.CheckString(1) 280 | 281 | client.Cmd.Part(channel) 282 | 283 | return 0 284 | } 285 | } 286 | 287 | func orRequestClosure(luaState *lua.LState, appConfig *TomlConfig) func(*lua.LState) int { 288 | return func(luaState *lua.LState) int { 289 | prompt := luaState.CheckString(1) 290 | 291 | result, err := DoORRequest(appConfig, &[]MemoryElement{}, prompt) 292 | if err != nil { 293 | LogError(err) 294 | } 295 | 296 | luaState.Push(lua.LString(result)) 297 | 298 | return 1 299 | } 300 | } 301 | 302 | func ollamaRequestClosure(luaState *lua.LState, appConfig *TomlConfig) func(*lua.LState) int { 303 | return func(luaState *lua.LState) int { 304 | prompt := luaState.CheckString(1) 305 | systemPrompt := luaState.CheckString(2) //nolint: mnd,gomnd 306 | 307 | result, err := DoOllamaRequest(appConfig, &[]MemoryElement{}, prompt, systemPrompt) 308 | if err != nil { 309 | LogError(err) 310 | } 311 | 312 | luaState.Push(lua.LString(result)) 313 | 314 | return 1 315 | } 316 | } 317 | 318 | func geminiRequestClosure(luaState *lua.LState, appConfig *TomlConfig) func(*lua.LState) int { 319 | return func(luaState *lua.LState) int { 320 | prompt := luaState.CheckString(1) 321 | systemPrompt := luaState.CheckString(2) //nolint: mnd,gomnd 322 | 323 | result, err := DoGeminiRequest(appConfig, &[]*genai.Content{}, prompt, systemPrompt) 324 | if err != nil { 325 | LogError(err) 326 | } 327 | 328 | luaState.Push(lua.LString(result)) 329 | 330 | return 1 331 | } 332 | } 333 | 334 | func chatGPTRequestClosure(luaState *lua.LState, appConfig *TomlConfig) func(*lua.LState) int { 335 | return func(luaState *lua.LState) int { 336 | prompt := luaState.CheckString(1) 337 | systemPrompt := luaState.CheckString(2) //nolint: mnd,gomnd 338 | 339 | result, err := DoChatGPTRequest(appConfig, &[]openai.ChatCompletionMessage{}, prompt, systemPrompt) 340 | if err != nil { 341 | LogError(err) 342 | } 343 | 344 | luaState.Push(lua.LString(result)) 345 | 346 | return 1 347 | } 348 | } 349 | 350 | func dbQueryClosure(luaState *lua.LState, appConfig *TomlConfig) func(*lua.LState) int { 351 | return func(luaState *lua.LState) int { 352 | if appConfig.pool == nil { 353 | log.Println("Database connection is not available") 354 | 355 | return 0 356 | } 357 | 358 | query := luaState.CheckString(1) 359 | 360 | rows, err := appConfig.pool.Query(context.Background(), query) 361 | if err != nil { 362 | LogError(err) 363 | } 364 | defer rows.Close() 365 | 366 | logs, err := pgx.CollectRows(rows, pgx.RowToStructByName[LogModel]) 367 | if err != nil { 368 | LogError(err) 369 | } 370 | 371 | table := luaState.CreateTable(0, len(logs)) 372 | 373 | for index, log := range logs { 374 | luaState.SetTable(table, lua.LNumber(index), lua.LString(log.Log)) 375 | } 376 | 377 | luaState.Push(table) 378 | 379 | return 1 380 | } 381 | } 382 | 383 | func urlEncode(luaState *lua.LState) func(*lua.LState) int { 384 | return func(luaState *lua.LState) int { 385 | URL := luaState.CheckString(1) 386 | escapedURL := url.QueryEscape(URL) 387 | luaState.Push(lua.LString(escapedURL)) 388 | 389 | return 1 390 | } 391 | } 392 | 393 | func millaModuleLoaderClosure(luaState *lua.LState, client *girc.Client, appConfig *TomlConfig) func(*lua.LState) int { 394 | return func(luaState *lua.LState) int { 395 | exports := map[string]lua.LGFunction{ 396 | "send_message": lua.LGFunction(sendMessageClosure(luaState, client)), 397 | "join_channel": lua.LGFunction(ircJoinChannelClosure(luaState, client)), 398 | "part_channel": lua.LGFunction(ircPartChannelClosure(luaState, client)), 399 | "send_ollama_request": lua.LGFunction(ollamaRequestClosure(luaState, appConfig)), 400 | "send_gemini_request": lua.LGFunction(geminiRequestClosure(luaState, appConfig)), 401 | "send_chatgpt_request": lua.LGFunction(chatGPTRequestClosure(luaState, appConfig)), 402 | "send_or_request": lua.LGFunction(orRequestClosure(luaState, appConfig)), 403 | "query_db": lua.LGFunction(dbQueryClosure(luaState, appConfig)), 404 | "register_cmd": lua.LGFunction(registerLuaCommand(luaState, appConfig)), 405 | "url_encode": lua.LGFunction(urlEncode(luaState)), 406 | } 407 | millaModule := luaState.SetFuncs(luaState.NewTable(), exports) 408 | 409 | registerStructAsLuaMetaTable[TomlConfig](luaState, millaModule, checkStruct, TomlConfig{}, "toml_config") 410 | registerStructAsLuaMetaTable[CustomCommand](luaState, millaModule, checkStruct, CustomCommand{}, "custom_command") 411 | registerStructAsLuaMetaTable[LogModel](luaState, millaModule, checkStruct, LogModel{}, "log_model") 412 | registerStructAsLuaMetaTable[girc.Source](luaState, millaModule, checkStruct, girc.Source{}, "girc_source") 413 | // FIXME: throws error 414 | // registerStructAsLuaMetaTable[girc.Tags](luaState, millaModule, checkStruct, girc.Tags{}, "girc_tags") 415 | registerStructAsLuaMetaTable[girc.Event](luaState, millaModule, checkStruct, girc.Event{}, "girc_event") 416 | 417 | luaState.SetGlobal("milla", millaModule) 418 | 419 | luaState.Push(millaModule) 420 | 421 | return 1 422 | } 423 | } 424 | 425 | func millaModuleLoaderEventClosure(luaState *lua.LState, client *girc.Client, appConfig *TomlConfig, event girc.Event) func(*lua.LState) int { 426 | return func(luaState *lua.LState) int { 427 | exports := map[string]lua.LGFunction{ 428 | "send_message": lua.LGFunction(sendMessageClosure(luaState, client)), 429 | "reply_to": lua.LGFunction(replyToMessageClosure(luaState, client, event)), 430 | "join_channel": lua.LGFunction(ircJoinChannelClosure(luaState, client)), 431 | "part_channel": lua.LGFunction(ircPartChannelClosure(luaState, client)), 432 | "send_ollama_request": lua.LGFunction(ollamaRequestClosure(luaState, appConfig)), 433 | "send_gemini_request": lua.LGFunction(geminiRequestClosure(luaState, appConfig)), 434 | "send_chatgpt_request": lua.LGFunction(chatGPTRequestClosure(luaState, appConfig)), 435 | "send_or_request": lua.LGFunction(orRequestClosure(luaState, appConfig)), 436 | "query_db": lua.LGFunction(dbQueryClosure(luaState, appConfig)), 437 | "register_cmd": lua.LGFunction(registerLuaCommand(luaState, appConfig)), 438 | "url_encode": lua.LGFunction(urlEncode(luaState)), 439 | } 440 | millaModule := luaState.SetFuncs(luaState.NewTable(), exports) 441 | 442 | registerStructAsLuaMetaTable[TomlConfig](luaState, millaModule, checkStruct, TomlConfig{}, "toml_config") 443 | registerStructAsLuaMetaTable[CustomCommand](luaState, millaModule, checkStruct, CustomCommand{}, "custom_command") 444 | registerStructAsLuaMetaTable[LogModel](luaState, millaModule, checkStruct, LogModel{}, "log_model") 445 | registerStructAsLuaMetaTable[girc.Source](luaState, millaModule, checkStruct, girc.Source{}, "girc_source") 446 | registerStructAsLuaMetaTable[girc.Event](luaState, millaModule, checkStruct, girc.Event{}, "girc_event") 447 | 448 | luaState.SetGlobal("milla", millaModule) 449 | 450 | luaState.Push(millaModule) 451 | 452 | return 1 453 | } 454 | } 455 | 456 | func RunScript(scriptPath string, client *girc.Client, appConfig *TomlConfig) { 457 | luaState := lua.NewState() 458 | defer luaState.Close() 459 | 460 | ctx, cancel := context.WithCancel(context.Background()) 461 | 462 | luaState.SetContext(ctx) 463 | 464 | appConfig.insertLState(scriptPath, luaState, cancel) 465 | 466 | luaState.PreloadModule("milla", millaModuleLoaderClosure(luaState, client, appConfig)) 467 | gluasocket.Preload(luaState) 468 | gluaxmlpath.Preload(luaState) 469 | luaState.PreloadModule("yaml", gluayaml.Loader) 470 | luaState.PreloadModule("re", gluare.Loader) 471 | luaState.PreloadModule("json", gopherjson.Loader) 472 | 473 | var proxyString string 474 | if os.Getenv("ALL_PROXY") != "" { 475 | proxyString = os.Getenv("ALL_PROXY") 476 | } else if os.Getenv("HTTPS_PROXY") != "" { 477 | proxyString = os.Getenv("HTTPS_PROXY") 478 | } else if os.Getenv("HTTP_PROXY") != "" { 479 | proxyString = os.Getenv("HTTP_PROXY") 480 | } else if os.Getenv("https_proxy") != "" { 481 | proxyString = os.Getenv("https_proxy") 482 | } else if os.Getenv("http_proxy") != "" { 483 | proxyString = os.Getenv("http_proxy") 484 | } 485 | 486 | proxyTransport := &http.Transport{} 487 | 488 | if proxyString != "" { 489 | proxyURL, err := url.Parse(proxyString) 490 | if err != nil { 491 | LogError(err) 492 | } 493 | 494 | proxyTransport.Proxy = http.ProxyURL(proxyURL) 495 | } 496 | 497 | luaState.PreloadModule("http", gluahttp.NewHttpModule(&http.Client{Transport: proxyTransport}).Loader) 498 | 499 | log.Print("Running script: ", scriptPath) 500 | 501 | err := luaState.DoFile(scriptPath) 502 | if err != nil { 503 | LogError(err) 504 | } 505 | } 506 | 507 | func LoadAllPlugins(appConfig *TomlConfig, client *girc.Client) { 508 | for _, scriptPath := range appConfig.Plugins { 509 | log.Print("Loading plugin: ", scriptPath) 510 | 511 | go RunScript(scriptPath, client, appConfig) 512 | } 513 | } 514 | 515 | func LoadAllEventPlugins(appConfig *TomlConfig, client *girc.Client) { 516 | for _, triggeredScript := range appConfig.TriggeredScripts { 517 | log.Print("Loading event plugin: ", triggeredScript.Path) 518 | 519 | go RunScript(triggeredScript.Path, client, appConfig) 520 | registerTriggeredScripts(client, *appConfig) 521 | } 522 | } 523 | 524 | func RunLuaFunc( 525 | cmd, args string, 526 | client *girc.Client, 527 | appConfig *TomlConfig, 528 | ) string { 529 | luaState := lua.NewState() 530 | defer luaState.Close() 531 | 532 | ctx, cancel := context.WithCancel(context.Background()) 533 | 534 | luaState.SetContext(ctx) 535 | 536 | scriptPath := appConfig.LuaCommands[cmd].Path 537 | 538 | appConfig.insertLState(scriptPath, luaState, cancel) 539 | 540 | luaState.PreloadModule("milla", millaModuleLoaderClosure(luaState, client, appConfig)) 541 | gluasocket.Preload(luaState) 542 | gluaxmlpath.Preload(luaState) 543 | luaState.PreloadModule("yaml", gluayaml.Loader) 544 | luaState.PreloadModule("re", gluare.Loader) 545 | luaState.PreloadModule("json", gopherjson.Loader) 546 | 547 | var proxyString string 548 | if os.Getenv("ALL_PROXY") != "" { 549 | proxyString = os.Getenv("ALL_PROXY") 550 | } else if os.Getenv("HTTPS_PROXY") != "" { 551 | proxyString = os.Getenv("HTTPS_PROXY") 552 | } else if os.Getenv("HTTP_PROXY") != "" { 553 | proxyString = os.Getenv("HTTP_PROXY") 554 | } else if os.Getenv("https_proxy") != "" { 555 | proxyString = os.Getenv("https_proxy") 556 | } else if os.Getenv("http_proxy") != "" { 557 | proxyString = os.Getenv("http_proxy") 558 | } 559 | 560 | log.Print("set proxy env to:", proxyString) 561 | 562 | proxyTransport := &http.Transport{} 563 | 564 | if proxyString != "" { 565 | proxyURL, err := url.Parse(proxyString) 566 | if err != nil { 567 | LogError(err) 568 | } 569 | 570 | proxyTransport.Proxy = http.ProxyURL(proxyURL) 571 | } 572 | 573 | luaState.PreloadModule("http", gluahttp.NewHttpModule(&http.Client{Transport: proxyTransport}).Loader) 574 | 575 | log.Print("Running lua command script: ", scriptPath) 576 | 577 | if err := luaState.DoFile(scriptPath); err != nil { 578 | LogError(err) 579 | 580 | return "" 581 | } 582 | 583 | funcLValue := lua.P{ 584 | Fn: luaState.GetGlobal(appConfig.LuaCommands[cmd].FuncName), 585 | NRet: 1, 586 | Protect: true, 587 | } 588 | 589 | log.Print(cmd) 590 | log.Print(args) 591 | 592 | if err := luaState.CallByParam(funcLValue, lua.LString(args)); err != nil { 593 | log.Print("failed running lua command ...") 594 | LogError(err) 595 | 596 | return "" 597 | } 598 | 599 | result := luaState.Get(-1) 600 | luaState.Pop(1) 601 | 602 | return result.String() 603 | } 604 | 605 | func RunTriggeredLuaFunc( 606 | funcName, scriptPath string, 607 | client *girc.Client, 608 | event girc.Event, 609 | appConfig *TomlConfig, 610 | ) string { 611 | luaState := lua.NewState() 612 | defer luaState.Close() 613 | 614 | ctx, cancel := context.WithCancel(context.Background()) 615 | 616 | luaState.SetContext(ctx) 617 | 618 | appConfig.insertLState(scriptPath, luaState, cancel) 619 | 620 | luaState.PreloadModule("milla", millaModuleLoaderEventClosure(luaState, client, appConfig, event)) 621 | gluasocket.Preload(luaState) 622 | gluaxmlpath.Preload(luaState) 623 | luaState.PreloadModule("yaml", gluayaml.Loader) 624 | luaState.PreloadModule("re", gluare.Loader) 625 | luaState.PreloadModule("json", gopherjson.Loader) 626 | 627 | var proxyString string 628 | if os.Getenv("ALL_PROXY") != "" { 629 | proxyString = os.Getenv("ALL_PROXY") 630 | } else if os.Getenv("HTTPS_PROXY") != "" { 631 | proxyString = os.Getenv("HTTPS_PROXY") 632 | } else if os.Getenv("HTTP_PROXY") != "" { 633 | proxyString = os.Getenv("HTTP_PROXY") 634 | } else if os.Getenv("https_proxy") != "" { 635 | proxyString = os.Getenv("https_proxy") 636 | } else if os.Getenv("http_proxy") != "" { 637 | proxyString = os.Getenv("http_proxy") 638 | } 639 | 640 | log.Print("set proxy env to:", proxyString) 641 | 642 | proxyTransport := &http.Transport{} 643 | 644 | if proxyString != "" { 645 | proxyURL, err := url.Parse(proxyString) 646 | if err != nil { 647 | LogError(err) 648 | } 649 | 650 | proxyTransport.Proxy = http.ProxyURL(proxyURL) 651 | } 652 | 653 | luaState.PreloadModule("http", gluahttp.NewHttpModule(&http.Client{Transport: proxyTransport}).Loader) 654 | 655 | log.Print("Running lua command script: ", scriptPath) 656 | 657 | if err := luaState.DoFile(scriptPath); err != nil { 658 | LogError(err) 659 | 660 | return "" 661 | } 662 | 663 | funcLValue := lua.P{ 664 | Fn: luaState.GetGlobal(funcName), 665 | NRet: 1, 666 | Protect: true, 667 | } 668 | 669 | if err := luaState.CallByParam(funcLValue); err != nil { 670 | log.Print("failed running lua command ...") 671 | LogError(err) 672 | 673 | return "" 674 | } 675 | 676 | result := luaState.Get(-1) 677 | luaState.Pop(1) 678 | 679 | return result.String() 680 | } 681 | 682 | func registerTriggeredScripts(irc *girc.Client, appConfig TomlConfig) { 683 | for _, triggeredScript := range appConfig.TriggeredScripts { 684 | for _, triggerType := range triggeredScript.TriggerTypes { 685 | switch triggerType { 686 | case girc.PRIVMSG: 687 | irc.Handlers.AddBg(girc.PRIVMSG, func(_ *girc.Client, event girc.Event) { 688 | if !strings.HasPrefix(event.Last(), appConfig.IrcNick+": ") { 689 | return 690 | } 691 | 692 | if appConfig.AdminOnly && !isFromAdmin(appConfig.Admins, event) { 693 | return 694 | } 695 | 696 | RunTriggeredLuaFunc(triggeredScript.FuncName, triggeredScript.Path, irc, event, &appConfig) 697 | }) 698 | default: 699 | } 700 | } 701 | } 702 | } 703 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "crypto/tls" 6 | "errors" 7 | "expvar" 8 | "flag" 9 | "fmt" 10 | "index/suffixarray" 11 | "log" 12 | "math/rand" 13 | "net" 14 | "net/http" 15 | _ "net/http/pprof" 16 | "net/url" 17 | "os" 18 | "os/signal" 19 | "reflect" 20 | "regexp" 21 | "runtime" 22 | "strconv" 23 | "strings" 24 | "syscall" 25 | "time" 26 | 27 | "github.com/BurntSushi/toml" 28 | "github.com/cenkalti/backoff/v5" 29 | "github.com/jackc/pgx/v5" 30 | "github.com/jackc/pgx/v5/pgxpool" 31 | "github.com/lrstanley/girc" 32 | openai "github.com/sashabaranov/go-openai" 33 | "golang.org/x/net/proxy" 34 | "google.golang.org/genai" 35 | ) 36 | 37 | var ( 38 | errNotEnoughArgs = errors.New("not enough arguments") 39 | errUnknCmd = errors.New("unknown command") 40 | errUnknConfig = errors.New("unknown config name") 41 | errCantSet = errors.New("can't set field") 42 | errWrongDataForField = errors.New("wrong data type for field") 43 | errUnsupportedType = errors.New("unsupported type") 44 | ) 45 | 46 | func getTableFromChanName(channel, ircdName string) string { 47 | tableName := ircdName + "_" + channel 48 | tableName = strings.ReplaceAll(tableName, "#", "") 49 | tableName = strings.ReplaceAll(tableName, "-", "_") 50 | tableName = strings.TrimSpace(tableName) 51 | 52 | return tableName 53 | } 54 | 55 | func stripColorCodes(input string) string { 56 | re := regexp.MustCompile(`\x1b\[[0-9;]*m`) 57 | input = re.ReplaceAllString(input, "") 58 | re = regexp.MustCompile(`\x03(?:\d{1,2}(?:,\d{1,2})?)?`) 59 | input = re.ReplaceAllString(input, "") 60 | 61 | return input 62 | } 63 | 64 | func sanitizeLog(log string) string { 65 | sanitizeLog := strings.ReplaceAll(log, "'", " ") 66 | 67 | return sanitizeLog 68 | } 69 | 70 | func returnGeminiResponse(resp *genai.GenerateContentResponse) string { 71 | result := "" 72 | 73 | for _, cand := range resp.Candidates { 74 | if cand.Content != nil { 75 | for _, part := range cand.Content.Parts { 76 | result += fmt.Sprintln(part) 77 | } 78 | } 79 | } 80 | 81 | return result 82 | } 83 | 84 | func extractLast256ColorEscapeCode(str string) (string, error) { 85 | pattern256F := `\033\[38;5;(\d+)m` 86 | // pattern256B := `\033\[48;5;(\d+)m` 87 | // pattern16mF := `\033\[38;2;(\d+);(\d+);(\d+)m` 88 | // pattern16mB := `\033\[48;2;(\d+);(\d+);(\d+)m` 89 | 90 | r, err := regexp.Compile(pattern256F) 91 | if err != nil { 92 | return "", fmt.Errorf("failed to compile regular expression: %w", err) 93 | } 94 | 95 | matches := r.FindAllStringSubmatch(str, -1) 96 | if len(matches) == 0 { 97 | return "", nil 98 | } 99 | 100 | lastMatch := matches[len(matches)-1] 101 | 102 | return lastMatch[1], nil 103 | } 104 | 105 | func getHelpString() string { 106 | helpString := "Commands:\n" 107 | helpString += "help - show this help message\n" 108 | helpString += "set - set a configuration value\n" 109 | helpString += "get - get a configuration value\n" 110 | helpString += "join - joins a given channel\n" 111 | helpString += "leave - leaves a given channel\n" 112 | helpString += "cmd - run a custom command defined in the customcommands file\n" 113 | helpString += "getall - returns all config options with their value\n" 114 | helpString += "memstats - returns the memory status currently being used\n" 115 | helpString += "load - loads a lua script\n" 116 | helpString += "unload - unloads a lua script\n" 117 | helpString += "remind - reminds you in a given amount of seconds\n" 118 | helpString += "roll - rolls a dice. the number is between 1 and 6. One arg sets the upper limit. Two args sets the lower and upper limit in that order\n" 119 | 120 | return helpString 121 | } 122 | 123 | func setFieldByName(v reflect.Value, field string, value string) error { 124 | fieldValue := v.FieldByName(field) 125 | if !fieldValue.IsValid() { 126 | return errUnknConfig 127 | } 128 | 129 | if !fieldValue.CanSet() { 130 | return errCantSet 131 | } 132 | 133 | switch fieldValue.Kind() { 134 | case reflect.String: 135 | fieldValue.SetString(value) 136 | case reflect.Int32: 137 | intValue, err := strconv.ParseInt(value, 10, 32) 138 | if err != nil { 139 | return errWrongDataForField 140 | } 141 | 142 | fieldValue.SetInt(int64(intValue)) 143 | case reflect.Int: 144 | intValue, err := strconv.Atoi(value) 145 | if err != nil { 146 | return errWrongDataForField 147 | } 148 | 149 | fieldValue.SetInt(int64(intValue)) 150 | case reflect.Float64: 151 | floatValue, err := strconv.ParseFloat(value, 64) 152 | if err != nil { 153 | return errWrongDataForField 154 | } 155 | 156 | fieldValue.SetFloat(floatValue) 157 | case reflect.Bool: 158 | boolValue, err := strconv.ParseBool(value) 159 | if err != nil { 160 | return errWrongDataForField 161 | } 162 | 163 | fieldValue.SetBool(boolValue) 164 | default: 165 | return errUnsupportedType 166 | } 167 | 168 | return nil 169 | } 170 | 171 | func byteToMByte(bytes uint64, 172 | ) uint64 { 173 | return bytes / 1024 / 1024 //nolint: mnd,gomnd 174 | } 175 | 176 | func handleCustomCommand( 177 | args []string, 178 | client *girc.Client, 179 | event girc.Event, 180 | appConfig *TomlConfig, 181 | ) { 182 | log.Println(args) 183 | 184 | if len(args) < 2 { //nolint: mnd,gomnd 185 | client.Cmd.Reply(event, errNotEnoughArgs.Error()) 186 | 187 | return 188 | } 189 | 190 | customCommand := appConfig.CustomCommands[args[1]] 191 | 192 | if customCommand.SQL == "" { 193 | client.Cmd.Reply(event, "empty sql commands in the custom command") 194 | 195 | return 196 | } 197 | 198 | if appConfig.pool == nil { 199 | client.Cmd.Reply(event, "no database connection") 200 | 201 | return 202 | } 203 | 204 | log.Println(customCommand.SQL) 205 | 206 | rows, err := appConfig.pool.Query(context.Background(), customCommand.SQL) 207 | if err != nil { 208 | client.Cmd.Reply(event, "error: "+err.Error()) 209 | 210 | return 211 | } 212 | defer rows.Close() 213 | 214 | logs, err := pgx.CollectRows(rows, pgx.RowToStructByName[LogModel]) 215 | if err != nil { 216 | LogError(err) 217 | 218 | return 219 | } 220 | 221 | if customCommand.Limit != 0 { 222 | logs = logs[:customCommand.Limit] 223 | } 224 | 225 | log.Println(logs) 226 | 227 | if err != nil { 228 | LogError(err) 229 | 230 | return 231 | } 232 | 233 | switch appConfig.Provider { 234 | case "chatgpt": 235 | var gptMemory []openai.ChatCompletionMessage 236 | 237 | for _, log := range logs { 238 | gptMemory = append(gptMemory, openai.ChatCompletionMessage{ 239 | Role: openai.ChatMessageRoleUser, 240 | Content: log.Log, 241 | }) 242 | } 243 | 244 | for _, customContext := range customCommand.Context { 245 | gptMemory = append(gptMemory, openai.ChatCompletionMessage{ 246 | Role: openai.ChatMessageRoleAssistant, 247 | Content: customContext, 248 | }) 249 | } 250 | 251 | var bigPrompt string 252 | for _, log := range logs { 253 | bigPrompt += log.Log + "\n" 254 | } 255 | 256 | result := ChatGPTRequestProcessor(appConfig, client, event, &gptMemory, customCommand.Prompt, customCommand.SystemPrompt) 257 | if result != "" { 258 | SendToIRC(client, event, result, appConfig.ChromaFormatter) 259 | } 260 | case "gemini": 261 | var geminiMemory []*genai.Content 262 | 263 | for _, log := range logs { 264 | geminiMemory = append(geminiMemory, genai.NewContentFromText(log.Log, "user")) 265 | } 266 | 267 | for _, customContext := range customCommand.Context { 268 | geminiMemory = append(geminiMemory, genai.NewContentFromText(customContext, "model")) 269 | } 270 | 271 | result := GeminiRequestProcessor(appConfig, client, event, &geminiMemory, customCommand.Prompt, customCommand.SystemPrompt) 272 | if result != "" { 273 | SendToIRC(client, event, result, appConfig.ChromaFormatter) 274 | } 275 | case "ollama": 276 | var ollamaMemory []MemoryElement 277 | 278 | for _, log := range logs { 279 | ollamaMemory = append(ollamaMemory, MemoryElement{ 280 | Role: "user", 281 | Content: log.Log, 282 | }) 283 | } 284 | 285 | for _, customContext := range customCommand.Context { 286 | ollamaMemory = append(ollamaMemory, MemoryElement{ 287 | Role: "assistant", 288 | Content: customContext, 289 | }) 290 | } 291 | 292 | result := OllamaRequestProcessor(appConfig, client, event, &ollamaMemory, customCommand.Prompt, customCommand.SystemPrompt) 293 | if result != "" { 294 | SendToIRC(client, event, result, appConfig.ChromaFormatter) 295 | } 296 | case "openrouter": 297 | var memory []MemoryElement 298 | 299 | for _, log := range logs { 300 | memory = append(memory, MemoryElement{ 301 | Role: "user", 302 | Content: log.Log, 303 | }) 304 | } 305 | 306 | for _, customContext := range customCommand.Context { 307 | memory = append(memory, MemoryElement{ 308 | Role: "user", 309 | Content: customContext, 310 | }) 311 | } 312 | 313 | result := ORRequestProcessor(appConfig, client, event, &memory, customCommand.Prompt) 314 | if result != "" { 315 | SendToIRC(client, event, result, appConfig.ChromaFormatter) 316 | } 317 | default: 318 | } 319 | } 320 | 321 | func isFromAdmin(admins []string, event girc.Event) bool { 322 | messageFromAdmin := false 323 | 324 | for _, admin := range admins { 325 | if event.Source.Name == admin { 326 | messageFromAdmin = true 327 | 328 | break 329 | } 330 | } 331 | 332 | return messageFromAdmin 333 | } 334 | 335 | func runCommand( 336 | client *girc.Client, 337 | event girc.Event, 338 | appConfig *TomlConfig, 339 | ) { 340 | cmd := strings.TrimPrefix(event.Last(), appConfig.IrcNick+": ") 341 | cmd = strings.TrimSpace(cmd) 342 | cmd = strings.TrimPrefix(cmd, "/") 343 | args := strings.Split(cmd, " ") 344 | 345 | if appConfig.AdminOnly && !isFromAdmin(appConfig.Admins, event) { 346 | return 347 | } 348 | 349 | switch args[0] { 350 | case "help": 351 | SendToIRC(client, event, getHelpString(), "noop") 352 | case "set": 353 | if len(args) < 3 { //nolint: mnd,gomnd 354 | client.Cmd.Reply(event, errNotEnoughArgs.Error()) 355 | 356 | break 357 | } 358 | 359 | err := setFieldByName(reflect.ValueOf(appConfig).Elem(), args[1], args[2]) 360 | if err != nil { 361 | client.Cmd.Reply(event, err.Error()) 362 | } 363 | case "get": 364 | if len(args) < 2 { //nolint: mnd,gomnd 365 | client.Cmd.Reply(event, errNotEnoughArgs.Error()) 366 | 367 | break 368 | } 369 | 370 | log.Println(args[1]) 371 | 372 | v := reflect.ValueOf(*appConfig) 373 | field := v.FieldByName(args[1]) 374 | 375 | if !field.IsValid() { 376 | client.Cmd.Reply(event, errUnknConfig.Error()) 377 | 378 | break 379 | } 380 | 381 | client.Cmd.Reply(event, fmt.Sprintf("%v", field.Interface())) 382 | case "getall": 383 | value := reflect.ValueOf(*appConfig) 384 | t := value.Type() 385 | 386 | for i := range value.NumField() { 387 | field := t.Field(i) 388 | fieldValue := value.Field(i).Interface() 389 | 390 | fieldValueString, ok := fieldValue.(string) 391 | if !ok { 392 | continue 393 | } 394 | 395 | client.Cmd.Reply(event, fmt.Sprintf("%s: %v", field.Name, fieldValueString)) 396 | } 397 | case "memstats": 398 | var memStats runtime.MemStats 399 | 400 | runtime.ReadMemStats(&memStats) 401 | 402 | client.Cmd.Reply(event, fmt.Sprintf("Alloc: %d MiB", byteToMByte(memStats.Alloc))) 403 | client.Cmd.Reply(event, fmt.Sprintf("TotalAlloc: %d MiB", byteToMByte(memStats.TotalAlloc))) 404 | client.Cmd.Reply(event, fmt.Sprintf("Sys: %d MiB", byteToMByte(memStats.Sys))) 405 | case "join": 406 | if !isFromAdmin(appConfig.Admins, event) { 407 | break 408 | } 409 | 410 | if len(args) < 2 { //nolint: mnd,gomnd 411 | client.Cmd.Reply(event, errNotEnoughArgs.Error()) 412 | 413 | break 414 | } 415 | if len(args) == 3 { 416 | IrcJoin(client, []string{args[1], args[2]}) 417 | } else { 418 | client.Cmd.Join(args[1]) 419 | } 420 | case "leave": 421 | if !isFromAdmin(appConfig.Admins, event) { 422 | break 423 | } 424 | 425 | if len(args) < 2 { //nolint: mnd,gomnd 426 | client.Cmd.Reply(event, errNotEnoughArgs.Error()) 427 | 428 | break 429 | } 430 | 431 | client.Cmd.Part(args[1]) 432 | case "cmd": 433 | if !isFromAdmin(appConfig.Admins, event) { 434 | break 435 | } 436 | 437 | handleCustomCommand(args, client, event, appConfig) 438 | case "load": 439 | if !isFromAdmin(appConfig.Admins, event) { 440 | break 441 | } 442 | 443 | if len(args) < 2 { //nolint: mnd,gomnd 444 | client.Cmd.Reply(event, errNotEnoughArgs.Error()) 445 | 446 | break 447 | } 448 | 449 | RunScript(args[1], client, appConfig) 450 | case "unload": 451 | if !isFromAdmin(appConfig.Admins, event) { 452 | break 453 | } 454 | 455 | if len(args) < 2 { //nolint: mnd,gomnd 456 | client.Cmd.Reply(event, errNotEnoughArgs.Error()) 457 | 458 | break 459 | } 460 | 461 | for key, value := range appConfig.LuaCommands { 462 | if value.Path == args[1] { 463 | appConfig.deleteLuaCommand(key) 464 | 465 | break 466 | } 467 | } 468 | 469 | appConfig.deleteLstate(args[1]) 470 | case "list": 471 | if !isFromAdmin(appConfig.Admins, event) { 472 | break 473 | } 474 | 475 | for key, value := range appConfig.LuaCommands { 476 | client.Cmd.Reply(event, fmt.Sprintf("%s: %s", key, value.Path)) 477 | } 478 | case "remind": 479 | if len(args) < 2 { //nolint: mnd,gomnd 480 | client.Cmd.Message(event.Source.Name, errNotEnoughArgs.Error()) 481 | 482 | break 483 | } 484 | 485 | seconds, err := strconv.Atoi(args[1]) 486 | if err != nil { 487 | client.Cmd.Reply(event, errNotEnoughArgs.Error()) 488 | client.Cmd.Message(event.Source.Name, errNotEnoughArgs.Error()) 489 | 490 | break 491 | } 492 | 493 | client.Cmd.Message(event.Source.Name, "Ok, I'll remind you in "+args[1]+" seconds.") 494 | time.Sleep(time.Duration(seconds) * time.Second) 495 | 496 | client.Cmd.Message(event.Source.Name, "Ping!") 497 | case "forget": 498 | client.Cmd.Reply(event, "I no longer even know whether you're supposed to wear or drink a camel.'") 499 | case "whois": 500 | if len(args) < 2 { //nolint: mnd,gomnd 501 | client.Cmd.Reply(event, errNotEnoughArgs.Error()) 502 | 503 | break 504 | } 505 | 506 | ianaResponse := IANAWhoisGet(args[1], appConfig) 507 | client.Cmd.Reply(event, ianaResponse) 508 | case "roll": 509 | lowerLimit := 1 510 | upperLimit := 6 511 | 512 | if len(args) == 1 { 513 | } else if len(args) == 2 { //nolint: mnd,gomnd 514 | argOne, err := strconv.Atoi(args[1]) 515 | if err != nil { 516 | client.Cmd.Reply(event, errNotEnoughArgs.Error()) 517 | 518 | break 519 | } 520 | 521 | upperLimit = argOne 522 | } else if len(args) == 3 { //nolint: mnd,gomnd 523 | argOne, err := strconv.Atoi(args[1]) 524 | if err != nil { 525 | client.Cmd.Reply(event, errNotEnoughArgs.Error()) 526 | 527 | break 528 | } 529 | 530 | lowerLimit = argOne 531 | 532 | argTwo, err := strconv.Atoi(args[2]) 533 | if err != nil { 534 | client.Cmd.Reply(event, errNotEnoughArgs.Error()) 535 | 536 | break 537 | } 538 | 539 | upperLimit = argTwo 540 | } else { 541 | client.Cmd.Reply(event, errors.New("too many args").Error()) 542 | 543 | break 544 | } 545 | 546 | randomNumber := lowerLimit + rand.Intn(upperLimit-lowerLimit+1) 547 | 548 | client.Cmd.ReplyTo(event, fmt.Sprint(randomNumber)) 549 | case "ua": 550 | if !isFromAdmin(appConfig.Admins, event) { 551 | break 552 | } 553 | 554 | if len(args) < 2 { //nolint: mnd,gomnd 555 | client.Cmd.Reply(event, errNotEnoughArgs.Error()) 556 | 557 | break 558 | } 559 | 560 | var query string 561 | 562 | if len(args) >= 3 { 563 | query = strings.TrimPrefix(cmd, args[0]) 564 | } 565 | 566 | log.Println("query:", query) 567 | response := UserAgentsGet(args[1], query, appConfig) 568 | 569 | // client.Cmd.Reply(event, response) 570 | SendToIRC(client, event, response, appConfig.ChromaFormatter) 571 | 572 | default: 573 | _, ok := appConfig.LuaCommands[args[0]] 574 | if ok { 575 | luaArgs := strings.TrimPrefix(event.Last(), appConfig.IrcNick+": ") 576 | luaArgs = strings.TrimSpace(luaArgs) 577 | luaArgs = strings.TrimPrefix(luaArgs, "/") 578 | luaArgs = strings.TrimPrefix(luaArgs, args[0]) 579 | luaArgs = strings.TrimSpace(luaArgs) 580 | 581 | result := RunLuaFunc(args[0], luaArgs, client, appConfig) 582 | client.Cmd.Reply(event, result) 583 | 584 | break 585 | } 586 | 587 | _, ok = appConfig.Aliases[args[0]] 588 | if ok { 589 | dummyEvent := event 590 | dummyEvent.Params[len(dummyEvent.Params)-1] = appConfig.Aliases[args[0]].Alias 591 | 592 | runCommand(client, dummyEvent, appConfig) 593 | 594 | break 595 | } 596 | 597 | client.Cmd.Reply(event, errUnknCmd.Error()) 598 | } 599 | } 600 | 601 | func connectToDB(appConfig *TomlConfig, ctx *context.Context, irc *girc.Client) { 602 | var pool *pgxpool.Pool 603 | 604 | dbURL := fmt.Sprintf( 605 | "postgres://%s:%s@%s/%s", 606 | appConfig.DatabaseUser, 607 | appConfig.DatabasePassword, 608 | appConfig.DatabaseAddress, 609 | appConfig.DatabaseName) 610 | 611 | log.Println("dbURL:", dbURL) 612 | 613 | poolConfig, err := pgxpool.ParseConfig(dbURL) 614 | if err != nil { 615 | LogError(err) 616 | 617 | return 618 | } 619 | 620 | dbConnect := func() (*pgxpool.Pool, error) { 621 | return pgxpool.NewWithConfig(*ctx, poolConfig) 622 | } 623 | 624 | expBackoff := backoff.WithBackOff(&backoff.ExponentialBackOff{ 625 | InitialInterval: time.Millisecond * time.Duration(appConfig.DbBackOffInitialInterval), 626 | RandomizationFactor: appConfig.DbBackOffRandomizationFactor, 627 | Multiplier: appConfig.DbBackOffMultiplier, 628 | MaxInterval: time.Second * time.Duration(appConfig.DbBackOffMaxInterval), 629 | }) 630 | 631 | pool, err = backoff.Retry(*ctx, dbConnect, expBackoff) 632 | if err != nil { 633 | LogError(err) 634 | } 635 | 636 | log.Printf("%s connected to database", appConfig.IRCDName) 637 | 638 | for _, channel := range appConfig.ScrapeChannels { 639 | tableName := getTableFromChanName(channel[0], appConfig.IRCDName) 640 | query := fmt.Sprintf( 641 | `create table if not exists %s ( 642 | id serial primary key, 643 | channel text not null, 644 | log text not null, 645 | nick text not null, 646 | dateadded timestamp default current_timestamp 647 | )`, tableName) 648 | 649 | _, err := pool.Exec(*ctx, query) 650 | if err != nil { 651 | LogError(err) 652 | 653 | continue 654 | } 655 | } 656 | 657 | appConfig.pool = pool 658 | } 659 | 660 | func scrapeChannel(irc *girc.Client, appConfig *TomlConfig) { 661 | log.Print("spawning scraper") 662 | 663 | irc.Handlers.AddBg(girc.PRIVMSG, func(_ *girc.Client, event girc.Event) { 664 | if appConfig.pool == nil { 665 | log.Println("no db connection. cant write scrapes to db.") 666 | 667 | return 668 | } 669 | 670 | tableName := getTableFromChanName(event.Params[0], appConfig.IRCDName) 671 | query := fmt.Sprintf( 672 | "insert into %s (channel,log,nick) values ('%s','%s','%s')", 673 | tableName, 674 | sanitizeLog(event.Params[0]), 675 | sanitizeLog(stripColorCodes(event.Last())), 676 | event.Source.Name, 677 | ) 678 | 679 | log.Println(query) 680 | 681 | ctx, cancel := context.WithTimeout(context.Background(), time.Duration(appConfig.RequestTimeout)*time.Second) 682 | defer cancel() 683 | 684 | _, err := appConfig.pool.Exec(ctx, query) 685 | if err != nil { 686 | LogError(err) 687 | } 688 | }) 689 | } 690 | 691 | func populateWatchListWords(appConfig *TomlConfig) { 692 | for watchlistName, watchlist := range appConfig.WatchLists { 693 | for _, filepath := range watchlist.WatchFiles { 694 | filebytes, err := os.ReadFile(filepath) 695 | if err != nil { 696 | LogError(err) 697 | 698 | continue 699 | } 700 | 701 | filestring := string(filebytes) 702 | 703 | words := strings.Split(filestring, "\n") 704 | 705 | watchlist.Words = append(watchlist.Words, words...) 706 | appConfig.WatchLists[watchlistName] = watchlist 707 | } 708 | } 709 | } 710 | 711 | func WatchListHandler(irc *girc.Client, appConfig TomlConfig) { 712 | irc.Handlers.AddBg(girc.ALL_EVENTS, func(_ *girc.Client, event girc.Event) { 713 | var isRightEventType bool 714 | 715 | sarray := suffixarray.New([]byte(event.Last())) 716 | 717 | if len(event.Params) == 0 { 718 | return 719 | } 720 | 721 | for watchname, watchlist := range appConfig.WatchLists { 722 | for _, channel := range watchlist.WatchList { 723 | isRightEventType = false 724 | 725 | if channel[0] == event.Params[0] { 726 | 727 | for _, eventType := range watchlist.EventTypes { 728 | if eventType == event.Command { 729 | isRightEventType = true 730 | 731 | break 732 | } 733 | } 734 | 735 | if !isRightEventType { 736 | continue 737 | } 738 | 739 | for _, word := range watchlist.Words { 740 | indexes := sarray.Lookup([]byte(" "+word+" "), 1) 741 | if len(indexes) > 0 { 742 | nextWhitespaceIndex := strings.Index(event.Last()[indexes[0]+1:], " ") 743 | 744 | rewrittenMessage := 745 | event.Last()[:indexes[0]+1] + 746 | fmt.Sprintf("\x1b[48;5;%dm", watchlist.BGColor) + 747 | fmt.Sprintf("\x1b[38;5;%dm", watchlist.FGColor) + 748 | event.Last()[indexes[0]+1:indexes[0]+1+nextWhitespaceIndex] + 749 | "\x1b[0m" + event.Last()[indexes[0]+1+nextWhitespaceIndex:] 750 | 751 | irc.Cmd.Message( 752 | watchlist.AlertChannel[0], 753 | fmt.Sprintf("%s: %s", watchname, rewrittenMessage)) 754 | 755 | log.Printf("matched from watchlist -- %s: %s", watchname, event.Last()) 756 | 757 | break 758 | } 759 | } 760 | } 761 | } 762 | } 763 | }) 764 | } 765 | 766 | func runIRC(appConfig TomlConfig) { 767 | var OllamaMemory []MemoryElement 768 | 769 | var GeminiMemory []*genai.Content 770 | 771 | var GPTMemory []openai.ChatCompletionMessage 772 | 773 | var ORMemory []MemoryElement 774 | 775 | irc := girc.New(girc.Config{ 776 | Server: appConfig.IrcServer, 777 | Port: appConfig.IrcPort, 778 | Nick: appConfig.IrcNick, 779 | User: appConfig.IrcNick, 780 | Name: appConfig.IrcNick, 781 | SSL: appConfig.UseTLS, 782 | PingDelay: time.Duration(appConfig.PingDelay), 783 | PingTimeout: time.Duration(appConfig.PingTimeout), 784 | AllowFlood: appConfig.AllowFlood, 785 | DisableSTSFallback: appConfig.DisableSTSFallback, 786 | GlobalFormat: true, 787 | TLSConfig: &tls.Config{ 788 | InsecureSkipVerify: appConfig.SkipTLSVerify, 789 | ServerName: appConfig.IrcServer, 790 | }, 791 | }) 792 | 793 | if appConfig.WebIRCGateway != "" { 794 | irc.Config.WebIRC.Address = appConfig.WebIRCAddress 795 | irc.Config.WebIRC.Gateway = appConfig.WebIRCGateway 796 | irc.Config.WebIRC.Hostname = appConfig.WebIRCHostname 797 | irc.Config.WebIRC.Password = appConfig.WebIRCPassword 798 | } 799 | 800 | if appConfig.Debug { 801 | irc.Config.Debug = os.Stdout 802 | } 803 | 804 | if appConfig.Out { 805 | irc.Config.Out = os.Stdout 806 | } 807 | 808 | irc.Config.ServerPass = appConfig.ServerPass 809 | 810 | if appConfig.Bind != "" { 811 | irc.Config.Bind = appConfig.Bind 812 | } 813 | 814 | if appConfig.Name != "" { 815 | irc.Config.Name = appConfig.Name 816 | } 817 | 818 | if appConfig.EnableSasl && appConfig.IrcSaslPass != "" && appConfig.IrcSaslUser != "" { 819 | irc.Config.SASL = &girc.SASLPlain{ 820 | User: appConfig.IrcSaslUser, 821 | Pass: appConfig.IrcSaslPass, 822 | } 823 | } 824 | 825 | if appConfig.EnableSasl && appConfig.ClientCertPath != "" { 826 | cert, err := tls.LoadX509KeyPair(appConfig.ClientCertPath, appConfig.ClientCertPath) 827 | if err != nil { 828 | log.Println("invalid client certificate.") 829 | 830 | return 831 | } 832 | 833 | irc.Config.TLSConfig.Certificates = []tls.Certificate{cert} 834 | } 835 | 836 | irc.Handlers.AddBg(girc.CONNECTED, func(_ *girc.Client, _ girc.Event) { 837 | for _, channel := range appConfig.IrcChannels { 838 | IrcJoin(irc, channel) 839 | } 840 | }) 841 | 842 | switch appConfig.Provider { 843 | case "ollama": 844 | for _, context := range appConfig.Context { 845 | OllamaMemory = append(OllamaMemory, MemoryElement{ 846 | Role: "assistant", 847 | Content: context, 848 | }) 849 | } 850 | 851 | OllamaHandler(irc, &appConfig, &OllamaMemory) 852 | case "gemini": 853 | for _, context := range appConfig.Context { 854 | GeminiMemory = append(GeminiMemory, genai.NewContentFromText(context, "model")) 855 | } 856 | 857 | GeminiHandler(irc, &appConfig, &GeminiMemory) 858 | case "chatgpt": 859 | for _, context := range appConfig.Context { 860 | GPTMemory = append(GPTMemory, openai.ChatCompletionMessage{ 861 | Role: openai.ChatMessageRoleAssistant, 862 | Content: context, 863 | }) 864 | } 865 | 866 | ChatGPTHandler(irc, &appConfig, &GPTMemory) 867 | case "openrouter": 868 | for _, context := range appConfig.Context { 869 | ORMemory = append(ORMemory, MemoryElement{ 870 | Role: "user", 871 | Content: context, 872 | }) 873 | } 874 | 875 | ORHandler(irc, &appConfig, &ORMemory) 876 | } 877 | 878 | go LoadAllPlugins(&appConfig, irc) 879 | 880 | go LoadAllEventPlugins(&appConfig, irc) 881 | 882 | if appConfig.DatabaseAddress != "" { 883 | context, cancel := context.WithTimeout(context.Background(), time.Duration(appConfig.RequestTimeout)*time.Second) 884 | defer cancel() 885 | 886 | go connectToDB(&appConfig, &context, irc) 887 | } 888 | 889 | if len(appConfig.ScrapeChannels) > 0 { 890 | irc.Handlers.AddBg(girc.CONNECTED, func(_ *girc.Client, _ girc.Event) { 891 | for _, channel := range appConfig.ScrapeChannels { 892 | IrcJoin(irc, channel) 893 | } 894 | }) 895 | 896 | go scrapeChannel(irc, &appConfig) 897 | } 898 | 899 | if len(appConfig.WatchLists) > 0 { 900 | irc.Handlers.AddBg(girc.CONNECTED, func(_ *girc.Client, _ girc.Event) { 901 | for _, watchlist := range appConfig.WatchLists { 902 | log.Print("joining ", watchlist.AlertChannel) 903 | IrcJoin(irc, watchlist.AlertChannel) 904 | 905 | for _, channel := range watchlist.WatchList { 906 | IrcJoin(irc, channel) 907 | } 908 | } 909 | }) 910 | 911 | populateWatchListWords(&appConfig) 912 | 913 | go WatchListHandler(irc, appConfig) 914 | } 915 | 916 | if len(appConfig.Rss) > 0 { 917 | irc.Handlers.AddBg(girc.CONNECTED, func(client *girc.Client, _ girc.Event) { 918 | for _, rss := range appConfig.Rss { 919 | log.Print("RSS: joining ", rss.Channel) 920 | IrcJoin(irc, rss.Channel) 921 | } 922 | }) 923 | 924 | go runRSS(&appConfig, irc) 925 | } 926 | 927 | var dialer proxy.Dialer 928 | 929 | if appConfig.IRCProxy != "" { 930 | proxyURL, err := url.Parse(appConfig.IRCProxy) 931 | if err != nil { 932 | LogErrorFatal(err) 933 | } 934 | 935 | dialer, err = proxy.FromURL(proxyURL, &net.Dialer{Timeout: time.Duration(appConfig.RequestTimeout) * time.Second}) 936 | if err != nil { 937 | LogErrorFatal(err) 938 | } 939 | } 940 | 941 | connectToIRC := func() (string, error) { 942 | return "", irc.DialerConnect(dialer) 943 | } 944 | 945 | ctx, cancel := context.WithTimeout(context.Background(), time.Duration(appConfig.MillaReconnectDelay)*time.Second) 946 | defer cancel() 947 | 948 | for { 949 | expBackoff := backoff.WithBackOff(&backoff.ExponentialBackOff{ 950 | InitialInterval: time.Millisecond * time.Duration(appConfig.IrcBackOffInitialInterval), 951 | RandomizationFactor: appConfig.IrcBackOffRandomizationFactor, 952 | Multiplier: appConfig.IrcBackOffMultiplier, 953 | MaxInterval: time.Second * time.Duration(appConfig.IrcBackOffMaxInterval), 954 | }) 955 | 956 | _, err := backoff.Retry(ctx, connectToIRC, expBackoff) 957 | if err != nil { 958 | log.Println(appConfig.Name) 959 | LogError(err) 960 | } else { 961 | return 962 | } 963 | } 964 | } 965 | 966 | func goroutines() interface{} { 967 | return runtime.NumGoroutine() 968 | } 969 | 970 | func main() { 971 | expvar.Publish("Goroutines", expvar.Func(goroutines)) 972 | 973 | quitChannel := make(chan os.Signal, 1) 974 | signal.Notify(quitChannel, syscall.SIGINT, syscall.SIGTERM) 975 | 976 | configPath := flag.String("config", "./config.toml", "path to the config file") 977 | prof := flag.Bool("prof", false, "enable prof server") 978 | 979 | flag.Parse() 980 | 981 | data, err := os.ReadFile(*configPath) 982 | if err != nil { 983 | LogErrorFatal(err) 984 | } 985 | 986 | var config AppConfig 987 | 988 | _, err = toml.Decode(string(data), &config) 989 | if err != nil { 990 | LogErrorFatal(err) 991 | } 992 | 993 | for key, value := range config.Ircd { 994 | AddSaneDefaults(&value) 995 | value.IRCDName = key 996 | config.Ircd[key] = value 997 | } 998 | 999 | for k, v := range config.Ircd { 1000 | log.Println(k, v) 1001 | } 1002 | 1003 | for _, v := range config.Ircd { 1004 | if v.IrcServer != "" { 1005 | go runIRC(v) 1006 | } else { 1007 | log.Println("Could not find server for irc connection in the config file. skipping. check your config for spelling errors maybe.") 1008 | } 1009 | } 1010 | 1011 | for k, v := range config.Ghost { 1012 | go RunGhost(v, k) 1013 | } 1014 | 1015 | if *prof { 1016 | go func() { 1017 | err := http.ListenAndServe(":6060", nil) 1018 | log.Println(err) 1019 | }() 1020 | } 1021 | 1022 | <-quitChannel 1023 | } 1024 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------