Repository navigation
Expand file tree
/
Copy pathrunner.go
More file actions
459 lines (420 loc) · 18.3 KB
/
Copy pathrunner.go
File metadata and controls
459 lines (420 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
// ABOUTME: Runner maps Slack threads to concurrent tracker runs via the RunManager.
// ABOUTME: OnMention starts a run; OnInteraction routes a reply/click to the run's gate.
package chatops
import (
"context"
"errors"
"fmt"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
tracker "github.com/2389-research/tracker"
"github.com/2389-research/tracker/pipeline"
)
// RunnerDeps are the transport-provided hooks and per-run config a Runner needs.
type RunnerDeps struct {
// NewThreadUI returns a ThreadUI bound to one (channel, thread) — supplied by
// the transport (slack.go) so the runner stays Slack-agnostic.
NewThreadUI func(channel, threadTS string) ThreadUI
// WorkDir is where ResolveSource looks for local .dip files (built-ins
// resolve regardless).
WorkDir string
// RunsBase is the parent directory for per-thread isolated run workdirs
// (base/<sanitized thread_ts>), each holding that run's checkpoint.
RunsBase string
// NewID returns a fresh unique gate id per call.
NewID func() string
// Intent resolves @mention text to a workflow + params. Nil falls back to the
// deterministic grammar ("[run] <workflow> [k=v ...]").
Intent IntentResolver
// Store persists active runs for resume-after-restart. Nil disables it.
Store *Store
// KeepWorkdirs retains a run's workdir after it finishes (for later
// inspection) instead of reclaiming the disk. Default false: reap on
// terminal, bounding disk under sustained multi-run load.
KeepWorkdirs bool
// ConfirmOverUSD requires a human to confirm a run whose expected cost meets
// or exceeds this dollar amount before it starts. 0 disables confirmation.
ConfirmOverUSD float64
// ConfigBase carries provider/budget/backend config; the runner overlays the
// per-run Interviewer, EventHandler, and Params onto a copy of it.
ConfigBase tracker.Config
}
// Runner maps Slack threads to tracker runs. It owns a RunManager and, per
// active thread, the ThreadInterviewer that inbound interactions resolve against.
type Runner struct {
rm *tracker.RunManager
deps RunnerDeps
mu sync.Mutex
byThread map[string]*ThreadInterviewer // thread_ts → interviewer (inbound routing)
lastMu sync.Mutex
last map[string]RunRecord // thread_ts → most recent run, for `retry`
stMu sync.Mutex
trackers map[string]*statusTracker // thread_ts → live status card, for `status`
steerMu sync.Mutex
steerCh map[string]chan map[string]string // thread_ts → run's steering channel, for `steer`
// onStart, when set, sees each run launch starts, before watch can reap
// and Forget it. Test seam: a fast run can finish and leave the
// RunManager before a caller's rm.Get, so tests take the handle here.
onStart func(threadTS string, run *tracker.ManagedRun)
}
// NewRunner builds a Runner over an existing RunManager.
func NewRunner(rm *tracker.RunManager, deps RunnerDeps) *Runner {
return &Runner{
rm: rm,
deps: deps,
byThread: make(map[string]*ThreadInterviewer),
last: make(map[string]RunRecord),
trackers: make(map[string]*statusTracker),
steerCh: make(map[string]chan map[string]string),
}
}
// OnMention starts a run for a fresh @mention. thread_ts is the run's identity:
// the RunManager keys on it, and every message for this run routes by it.
func (r *Runner) OnMention(ctx context.Context, channel, threadTS, text string) {
ui := r.deps.NewThreadUI(channel, threadTS)
// A mention may be a control command (help/status/cancel/runs/retry) rather
// than a request to start a run — including inside an already-active thread.
if r.handleCommand(ctx, ui, threadTS, text) {
return
}
// One run per thread. Reject a fresh request when this thread already has a
// live run BEFORE doing any estimate/confirm/registration — otherwise the
// doomed second mention would clobber the live run's per-thread state
// (interviewer, steering channel, status card) on its way to being rejected
// by rm.Start. Commands (status/cancel/steer/bump) went through handleCommand
// above, so they are unaffected. (rm.Start remains the authoritative guard.)
if _, active := r.rm.Get(threadTS); active {
r.handleAdmission(ui, tracker.ErrRunKeyActive) // same message as the authoritative Start guard
return
}
intent, err := r.resolveIntent(ctx, text)
if err != nil {
_ = ui.Post("I couldn't work out what to run: " + err.Error())
r.suggestWorkflows(ui)
return
}
if !validWorkflowName(intent.Workflow) {
// SECURITY: reject path-shaped names before ResolveSource. ResolveSource
// treats a name with a separator or .dip suffix as a filesystem path
// (and absolute paths as-is), so an unvalidated name like
// "../../../etc/hosts" or "/abs/evil.dip" would load an arbitrary file
// off the host. The LLM resolver validates against the catalog; the
// grammar fallback does not — this guard covers both uniformly.
_ = ui.Post(fmt.Sprintf("`%s` isn't a valid workflow name — try a built-in, or `runs` to see what's available.", intent.Workflow))
return
}
source, info, err := tracker.ResolveSource(intent.Workflow, r.deps.WorkDir)
if err != nil {
_ = ui.Post("Unknown workflow: " + err.Error())
r.suggestWorkflows(ui)
return
}
if !r.estimateAndConfirm(ctx, ui, threadTS, source, info.Ref()) {
return
}
rec := RunRecord{ThreadTS: threadTS, Channel: channel, Workflow: intent.Workflow, Params: intent.Params}
r.launch(ctx, ui, source, info.Ref(), rec,
fmt.Sprintf("🚀 starting `%s` — I'll keep you posted here.", info.DisplayName), 0)
}
// estimateAndConfirm posts a rough cost estimate up front (the "tells you the
// bill before you spend" signal) and, above the configured threshold, blocks on
// a confirm gate. Returns false only when the human declined. A failed estimate
// never blocks a run.
func (r *Runner) estimateAndConfirm(ctx context.Context, ui ThreadUI, threadTS, source string, ref tracker.SourceRef) bool {
est, err := tracker.EstimateRun(ctx, source, tracker.WithSource(ref))
if err != nil || est.AgentNodes == 0 {
return true
}
_ = ui.Post(fmt.Sprintf("🔎 Estimate: ~$%.2f–$%.2f · %d steps · %d agent nodes _(rough — actual depends on turns/loops)_",
est.LowUSD, est.HighUSD, est.Steps, est.AgentNodes))
if r.needsConfirm(est) {
return r.confirmRun(ctx, ui, threadTS, est)
}
return true
}
// needsConfirm reports whether the estimate exceeds the confirm-over threshold.
func (r *Runner) needsConfirm(est *tracker.RunEstimate) bool {
return r.deps.ConfirmOverUSD > 0 && est.ExpectedUSD >= r.deps.ConfirmOverUSD
}
// confirmRun posts a Run/Cancel gate and blocks until the human answers, using a
// temporary interviewer registered for the thread just for this decision (the
// run's own interviewer is created later in launch). Returns true to proceed.
func (r *Runner) confirmRun(ctx context.Context, ui ThreadUI, threadTS string, est *tracker.RunEstimate) bool {
iv := NewThreadInterviewer(ui, r.deps.NewID)
iv.SetPipelineContext(ctx)
r.register(threadTS, iv)
ans, err := iv.Ask(
fmt.Sprintf("This looks like ~$%.2f (up to $%.2f). Run it?", est.ExpectedUSD, est.HighUSD),
[]string{"Run it", "Cancel"}, "Run it")
r.unregister(threadTS)
iv.Cancel()
if err != nil || ans != "Run it" {
_ = ui.Post("👍 cancelled — no run started.")
return false
}
return true
}
// Resume re-launches an interrupted run after a restart. Each thread has a
// deterministic workdir + checkpoint path; because the checkpoint file still
// exists, launching again replays from it (the engine loads a checkpoint at its
// configured path automatically). No run-id bookkeeping required.
func (r *Runner) Resume(ctx context.Context, rec RunRecord) {
ui := r.deps.NewThreadUI(rec.Channel, rec.ThreadTS)
if !validWorkflowName(rec.Workflow) {
// A persisted record with a path-shaped workflow (tampered state file)
// must not reach ResolveSource — same containment as OnMention.
_ = ui.Post("Couldn't resume (invalid workflow name in saved state).")
r.deps.Store.remove(rec.ThreadTS)
return
}
source, info, err := tracker.ResolveSource(rec.Workflow, r.deps.WorkDir)
if err != nil {
_ = ui.Post("Couldn't resume (workflow gone): " + err.Error())
r.deps.Store.remove(rec.ThreadTS)
return
}
r.launch(ctx, ui, source, info.Ref(), rec, "🔄 resuming this run after a restart…", 0)
}
// launch wires a per-run interviewer + notifier onto a copy of the base config,
// pins the deterministic per-thread workdir + checkpoint path (so the run is
// resumable and so a resume replays from it), starts the run, records it, and
// watches it to completion. ref anchors the source's *_file directives (the
// per-thread WorkingDir is not where the workflow lives, so the engine must
// not resolve sidecars relative to cwd).
func (r *Runner) launch(ctx context.Context, ui ThreadUI, source string, ref tracker.SourceRef, rec RunRecord, ack string, budgetOverrideCents int) {
workDir, checkpoint := r.runPaths(rec.ThreadTS)
if err := os.MkdirAll(workDir, 0o755); err != nil {
_ = ui.Post("Couldn't prepare a workspace: " + err.Error())
return
}
iv := NewThreadInterviewer(ui, r.deps.NewID)
cfg := r.deps.ConfigBase
cfg.WorkingDir = workDir
cfg.CheckpointDir = checkpoint
cfg.Source = ref
cfg.Params = rec.Params
cfg.Interviewer = iv
// The steering channel must be on the config before Start (the engine reads
// it at construction), but it is only recorded in the per-thread map AFTER a
// successful Start (see the register note below) — so a rejected duplicate
// mention can't clobber the live run's channel. An unregistered channel is
// just GC'd.
steer := make(chan map[string]string, steerBufSize)
cfg.SteeringChan = steer
if budgetOverrideCents > 0 {
cfg.Budget.MaxCostCents = budgetOverrideCents // `bump` raised the ceiling
}
st, closeEvents := r.attachEventSink(&cfg, ui, rec)
// Register per-thread state AFTER a successful Start: registering earlier
// would let a duplicate mention that Start rejects (ErrRunKeyActive) clobber
// the live run's interviewer, steering channel, or status card. The window
// before register is far shorter than the run reaching its first gate, so no
// inbound answer is lost in practice.
run, err := r.rm.Start(ctx, rec.ThreadTS, source, cfg)
if err != nil {
closeEvents() // no run to feed it — stop the forwarding goroutine
r.handleAdmission(ui, err)
return
}
if r.onStart != nil {
r.onStart(rec.ThreadTS, run)
}
r.register(rec.ThreadTS, iv)
r.registerSteering(rec.ThreadTS, steer)
if st != nil {
r.trackStatus(rec.ThreadTS, st) // so `status` can report live progress
}
r.deps.Store.put(rec)
r.remember(rec.ThreadTS, rec) // enable `retry` in this thread
if cents := cfg.Budget.MaxCostCents; cents > 0 {
ack += fmt.Sprintf("\n_Budget: up to $%.2f._", float64(cents)/100)
}
_ = ui.Post(ack)
go r.watch(rec.ThreadTS, run, ui, closeEvents)
}
// chatEventBufSize bounds the per-run chat event queue. Progress events are far
// smaller than the Slack round-trips that consume them, so a few hundred slots
// absorb a transient stall without unbounded memory.
const chatEventBufSize = 256
// attachEventSink composes this run's chat event rendering, installs it on cfg
// as a bounded buffered handler, and returns the live status card (nil when the
// transport has none) plus a close func that flushes the queue and reports drops.
//
// The notifier posts discrete gate/failure/terminal messages. When the transport
// supports a live status card (StatusRenderer), also drive that card from the
// stream and quiet the notifier's per-stage/cost chatter (the card shows it) —
// the thread gets one updating dashboard instead of spam.
//
// The composed sink does network I/O, and event handlers run synchronously on
// the engine goroutine, so it goes behind pipeline's bounded queue rather than
// straight onto Config.EventHandler: a hung Slack call would otherwise halt
// unrelated pipeline work and hold this thread's RunManager slot open. Buffering
// is not a substitute for an outbound client timeout — a permanently blocked
// HTTP call still wedges the flush at Close.
//
// OverflowDropOldest keeps the freshest progress view; the queue protects
// terminal and gate lifecycle events from dropping under any policy, so a
// lossy policy here cannot strand a watcher or split a gate pair.
func (r *Runner) attachEventSink(cfg *tracker.Config, ui ThreadUI, rec RunRecord) (*statusTracker, func()) {
nf := newNotifier(ui)
handler := nf.HandlePipelineEvent
var st *statusTracker
if sr, ok := ui.(StatusRenderer); ok {
st = newStatusTracker(sr, rec.Workflow, float64(cfg.Budget.MaxCostCents)/100)
nf.quiet = true
handler = func(evt pipeline.PipelineEvent) {
st.HandlePipelineEvent(evt)
nf.HandlePipelineEvent(evt)
}
}
sink := pipeline.PipelineEventHandlerFunc(handler)
buffered, err := pipeline.NewBufferedPipelineHandler(sink, chatEventBufSize, pipeline.OverflowDropOldest)
if err != nil {
// Unreachable: sink is non-nil and the capacity/policy are constants. Fall
// back to synchronous delivery loudly rather than starting a run with no
// event rendering at all.
log.Printf("chatops: buffered event handler unavailable (%v); chat events will render on the engine goroutine", err)
cfg.EventHandler = sink
return st, func() {}
}
cfg.EventHandler = buffered
return st, func() {
_ = buffered.Close()
if n := buffered.Dropped(); n > 0 {
log.Printf("chatops: thread %s dropped %d progress event(s) — the chat transport could not keep up", rec.ThreadTS, n)
}
}
}
// runPaths returns the deterministic workdir and checkpoint path for a thread.
func (r *Runner) runPaths(threadTS string) (workDir, checkpoint string) {
workDir = filepath.Join(r.deps.RunsBase, sanitizeThread(threadTS))
return workDir, filepath.Join(workDir, "checkpoint.json")
}
// SweepOrphans removes workdirs under RunsBase that no live store record
// references — left by a crash between a run's store.remove and its reap. Runs
// referenced by keep (the current store records, which Resume will replay) are
// preserved. Best-effort; the state file (not a dir) is skipped.
func (r *Runner) SweepOrphans(keep []RunRecord) {
live := make(map[string]bool, len(keep))
for _, rec := range keep {
live[sanitizeThread(rec.ThreadTS)] = true
}
entries, err := os.ReadDir(r.deps.RunsBase)
if err != nil {
return
}
for _, e := range entries {
if !e.IsDir() || live[e.Name()] {
continue
}
_ = os.RemoveAll(filepath.Join(r.deps.RunsBase, e.Name()))
}
}
// workflowNamePattern matches a safe bare workflow identifier — no path
// separators, no dots — so it can never be interpreted as a filesystem path by
// ResolveSource. Built-in names and local <name>.dip files resolve by this bare
// name; a user types "quick", not "quick.dip" or a path.
var workflowNamePattern = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
// validWorkflowName reports whether name is a safe bare workflow identifier.
func validWorkflowName(name string) bool {
return workflowNamePattern.MatchString(name)
}
// sanitizeThread turns a thread_ts into a safe single path segment.
func sanitizeThread(threadTS string) string {
out := strings.Map(func(rn rune) rune {
switch {
case rn >= 'a' && rn <= 'z', rn >= 'A' && rn <= 'Z', rn >= '0' && rn <= '9', rn == '-', rn == '_':
return rn
default:
return '_'
}
}, threadTS)
if out == "" {
return "thread"
}
return out
}
// resolveIntent uses the configured IntentResolver, or the grammar by default.
func (r *Runner) resolveIntent(ctx context.Context, text string) (Intent, error) {
if r.deps.Intent != nil {
return r.deps.Intent.Resolve(ctx, text)
}
return parseGrammar(text)
}
// OnInteraction routes an inbound button/modal/reply to the right run's pending
// gate, using thread_ts (which run) and gateID (which gate). Returns false if no
// run/gate matched.
func (r *Runner) OnInteraction(threadTS, gateID string, answer GateAnswer) bool {
r.mu.Lock()
iv := r.byThread[threadTS]
r.mu.Unlock()
if iv == nil {
return false
}
return iv.Resolve(gateID, answer)
}
// handleAdmission applies the already-active / at-capacity policy.
//
// DECISION POINT (D4) — at capacity this starter simply rejects. Alternatives:
// queue the request and start it when a slot frees, or preempt the oldest run.
func (r *Runner) handleAdmission(ui ThreadUI, err error) {
switch {
case errors.Is(err, tracker.ErrRunKeyActive):
_ = ui.Post("A run is already active in this thread — reply here, or open a new thread for a new run.")
case errors.Is(err, tracker.ErrAtCapacity):
_ = ui.Post("I'm at capacity right now — please try again in a bit.")
default:
_ = ui.Post("Couldn't start the run: " + err.Error())
}
}
// watch waits for a run to finish, unregisters it, delivers the outcome, and
// reaps the run's disk. Reaping runs after deliver so delivery can still read
// the run's artifacts.
func (r *Runner) watch(threadTS string, run *tracker.ManagedRun, ui ThreadUI, closeEvents func()) {
<-run.Done()
// Flush the buffered chat events before delivering the outcome, so the
// thread reads in order: progress posts, then the final result.
closeEvents()
r.unregister(threadTS)
r.untrackStatus(threadTS)
r.unregisterSteering(threadTS)
r.deps.Store.remove(threadTS) // finished — no longer resumable
deliver(context.Background(), ui, run)
r.reap(threadTS) // reclaim the workdir BEFORE freeing the key...
// ...then free the thread. Forget must come last: it re-admits the thread,
// and a `bump`/`retry` reacting to the terminal message would otherwise
// rm.Start into this same deterministic workdir while reap is still deleting
// it — the new run's checkpoint/artifacts would vanish mid-flight. Holding
// the key through deliver+reap serializes reap against any re-launch. deliver
// runs before reap because it reads the run dir (diagnosis).
r.rm.Forget(threadTS)
}
// reap reclaims a finished run's workdir (bounding disk), or, when retention is
// on, drops just the checkpoint so a later run in the same thread starts fresh
// instead of replaying this one. os.RemoveAll ignores ErrNotExist, so a
// concurrent cleanup is harmless. (A crash before reap leaves the workdir +
// checkpoint for resume.)
func (r *Runner) reap(threadTS string) {
workDir, checkpoint := r.runPaths(threadTS)
if r.deps.KeepWorkdirs {
if checkpoint != "" {
_ = os.Remove(checkpoint)
}
return
}
_ = os.RemoveAll(workDir)
}
func (r *Runner) register(threadTS string, iv *ThreadInterviewer) {
r.mu.Lock()
r.byThread[threadTS] = iv
r.mu.Unlock()
}
func (r *Runner) unregister(threadTS string) {
r.mu.Lock()
delete(r.byThread, threadTS)
r.mu.Unlock()
}