Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
175 lines (155 loc) · 5.92 KB
/
Copy pathmain.go
File metadata and controls
175 lines (155 loc) · 5.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
// ABOUTME: Entry point for trackerbot — a Slack front-end that drives Tracker pipelines.
// ABOUTME: Wires the Socket Mode transport, RunManager, and Runner together.
package main
import (
"cmp"
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"log"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
tracker "github.com/2389-research/tracker"
"github.com/2389-research/tracker/internal/chatgptauth"
"github.com/2389-research/tracker/pipeline"
chatops "github.com/2389-research/tracker/transport/chatops"
)
func main() {
if err := checkOpenAIAuth(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
botToken := os.Getenv("SLACK_BOT_TOKEN")
appToken := os.Getenv("SLACK_APP_TOKEN")
if botToken == "" || appToken == "" {
fmt.Fprintln(os.Stderr, "trackerbot: set SLACK_BOT_TOKEN (xoxb-…) and SLACK_APP_TOKEN (xapp-…)")
os.Exit(1)
}
workDir := envOr("TRACKERBOT_WORKDIR", ".")
runsBase := envOr("TRACKERBOT_RUNS", filepath.Join(os.TempDir(), "trackerbot-runs"))
maxConcurrent := envInt("TRACKERBOT_MAX_CONCURRENT", 8)
bot, err := NewSlackBot(botToken, appToken)
if err != nil {
log.Fatalf("trackerbot: %v", err)
}
configureAllowlist(bot)
// Fail-closed per-run budget so chat-triggered runs never spend unbounded.
// Default $5; TRACKERBOT_MAX_COST_CENTS=0 disables (operator's explicit choice).
maxCostCents := envInt("TRACKERBOT_MAX_COST_CENTS", 500)
// The runner pins a deterministic workdir + checkpoint per thread, so the
// RunManager only provides concurrency/lifecycle here.
rm := tracker.NewRunManager(tracker.WithMaxConcurrent(maxConcurrent))
configBase := tracker.Config{
Backend: os.Getenv("TRACKERBOT_BACKEND"),
Budget: pipeline.BudgetLimits{MaxCostCents: maxCostCents},
// Per-thread workdirs are created fresh and empty, so `requires: git`
// workflows (ask_and_execute, build_product) would dead-stop at preflight
// with "not a git repository". Auto-init git in the fresh dir — safe
// because it's always empty (see runner.launch's MkdirAll).
Git: &tracker.GitConfig{Preflight: tracker.GitPreflightInit, AllowInit: true},
}
st := chatops.OpenStore(filepath.Join(runsBase, "trackerbot-state.json"))
runner := chatops.NewRunner(rm, RunnerDeps{
NewThreadUI: bot.NewThreadUI,
WorkDir: workDir,
RunsBase: runsBase,
NewID: newGateID,
ConfigBase: configBase,
Intent: buildIntentResolver(configBase),
Store: st,
KeepWorkdirs: os.Getenv("TRACKERBOT_KEEP_WORKDIRS") == "1",
ConfirmOverUSD: float64(envInt("TRACKERBOT_CONFIRM_OVER_CENTS", 200)) / 100,
})
bot.SetRunner(runner)
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
resumeOrphans(ctx, runner, st.List())
log.Printf("trackerbot: connecting via Socket Mode (max %d concurrent runs; runs under %s)…", maxConcurrent, runsBase)
if err := bot.Run(ctx); err != nil && ctx.Err() == nil {
log.Fatalf("trackerbot: %v", err)
}
log.Println("trackerbot: shut down")
}
// errChatGPTLogin is why trackerbot won't start in ChatGPT mode.
var errChatGPTLogin = errors.New("trackerbot won't run with TRACKER_OPENAI_AUTH=chatgpt: a ChatGPT subscription login is for one person's own use, not a shared Slack bot; use an OpenAI API key instead")
// checkOpenAIAuth refuses TRACKER_OPENAI_AUTH=chatgpt. trackerbot serves
// everyone in a Slack channel, and a ChatGPT subscription login belongs to
// one person on their own machine, not to a service for others (design D3).
// An invalid value fails here, as it would at every run's client build.
func checkOpenAIAuth() error {
mode, err := chatgptauth.ModeFromEnv()
if err != nil {
return fmt.Errorf("trackerbot: %w", err)
}
if mode == chatgptauth.ModeChatGPT {
return errChatGPTLogin
}
return nil
}
// configureAllowlist restricts who may drive the bot from TRACKERBOT_ALLOWED_USERS,
// warning loudly when unset (open to everyone in the bot's channels).
func configureAllowlist(bot *SlackBot) {
allowed := splitCSV(os.Getenv("TRACKERBOT_ALLOWED_USERS"))
if len(allowed) == 0 {
log.Printf("trackerbot: WARNING — no TRACKERBOT_ALLOWED_USERS set; anyone in the bot's channels can start paid runs")
return
}
bot.SetAllowlist(allowed)
log.Printf("trackerbot: restricted to %d allowlisted user(s)", len(allowed))
}
// resumeOrphans sweeps workdirs no store record references, then re-launches the
// runs that were active when a previous process exited.
func resumeOrphans(ctx context.Context, runner *Runner, orphans []RunRecord) {
runner.SweepOrphans(orphans)
if len(orphans) == 0 {
return
}
log.Printf("trackerbot: resuming %d interrupted run(s) from a previous session", len(orphans))
for _, rec := range orphans {
go runner.Resume(ctx, rec)
}
}
// buildIntentResolver enables natural-language routing when an LLM is available,
// falling back to the deterministic "run <workflow>" grammar otherwise.
func buildIntentResolver(cfg tracker.Config) IntentResolver {
client, err := tracker.NewLLMClient(cfg)
if err != nil {
log.Printf("trackerbot: LLM intent unavailable (%v) — using the 'run <workflow>' grammar", err)
return chatops.GrammarResolver{}
}
model := envOr("TRACKERBOT_MODEL", "claude-haiku-4-5")
log.Printf("trackerbot: natural-language intent enabled (model %s)", model)
return chatops.NewLLMIntentResolver(client, model)
}
func envOr(key, def string) string {
return cmp.Or(os.Getenv(key), def)
}
// splitCSV parses a comma-separated env value into trimmed, non-empty items.
func splitCSV(v string) []string {
var out []string
for _, p := range strings.Split(v, ",") {
if p = strings.TrimSpace(p); p != "" {
out = append(out, p)
}
}
return out
}
func envInt(key string, def int) int {
if v := os.Getenv(key); v != "" {
if n, err := strconv.Atoi(v); err == nil {
return n
}
}
return def
}
// newGateID returns a short random id used to correlate a gate with its answer.
func newGateID() string {
var b [8]byte
_, _ = rand.Read(b[:])
return hex.EncodeToString(b[:])
}