Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion charts/tria-spot/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ agent:
toolResultMaxBytes: 12288 # a longer tool result is cut, and says how much was dropped
dailyTokenCeiling: 2000000 # tokens per UTC day (input, output, cache creation); 0 = no ceiling
hourlyTokenCeiling: 600000 # tokens in any rolling hour (input, output, cache creation); 0 = no ceiling
skipQuietWakes: true # a startup or timer wake with no facts and no open issue ends without a model call
skipQuietWakes: true # a startup or timer wake with no facts and no open issue ends without a model call; so does one that follows a timer wake whose turn did nothing
logLevel: info # debug | info | warn | error
# Logs carry what happened, never what was said: no message, issue or model
# text at any level. true lets debug logs include it (tool input and the
Expand Down
6 changes: 6 additions & 0 deletions cmd/tria-spot/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,12 @@ func supervise(cfg config.Config, errOut io.Writer) int {
return sup.ReplyCheck(replyTo)
},
Core: coreServer(cfg), Others: otherServers(cfg),
Reauth: func(ctx context.Context) error {
if link == nil {
return errors.New("the spot holds no link to the core")
}
return link.Refresh(ctx)
},
CallTimeout: cfg.ToolTimeout, ResultMax: cfg.ToolResultMax, SpotName: cfg.Name, RecallFirst: cfg.RecallFirst, NotesOnly: cfg.NotesOnly, PostGate: cfg.PostGate, FenceResults: cfg.FenceResults, Tasks: cfg.MaxTasks > 0 && !cfg.TaskActor(), TasksViaCore: cfg.Substrate(), TasksOffered: func() bool { return link != nil && link.TasksOffered() }, Tenant: cfg.Tenant, Logger: log,
})
}
Expand Down
10 changes: 10 additions & 0 deletions docs/releases/v0.9.10.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
A timer wake that has nothing to do costs no model call, and a refused token on connect is retried.

- **A timer wake after a turn that did nothing makes no model call.** A model that found nothing still planned its next wake, and the supervisor counted every such wake as asked for by the agent, so it ran a turn each time: the whole prompt and tool list, twice, to read an empty room. On an actor it was worse: the core sends the words of the plan with its order and not who made it, so every timer wake looked asked for, the supervisor's own quiet plan included, and the quiet rule never applied. The supervisor now keeps in its state directory who made the plan and whether the last timer wake's turn only read the room and planned the next wake. A wake that follows such a turn, or a plan the supervisor made itself, is not counted as asked for; with nothing to show it ends without a model call, with an issue open too, until something changes or 12 hours have passed. A turn that does any other work, a message and an event are as before.
- **A wake whose facts are no longer true makes no model call.** A wake carried by changes to an issue that closed before the wake ran had its facts dropped and its edges kept, and ran a turn with nothing to show. It is now quiet.
- **A core that refuses the token on connect gets one fresh hello and one more try.** An actor's first connect of a wake could meet "authorization required" (the core revokes a token issued before it marked the actor suspended). The turn failed, the wake was lost, and the retry replaced a long plan with a wake two minutes later.
- The hourly token ceiling is its own pause reason, with the time the spot expects to wake; a connector with `auth: injected` sends a placeholder bearer for an actor's egress to replace.

Upgrade: chart `oci://ghcr.io/triageagent-dev/charts/tria-spot` 0.9.10, image `ghcr.io/triageagent-dev/spot:0.9.10`.

**Full Changelog**: https://github.com/triageagent-dev/spot/compare/v0.9.9...v0.9.10
2 changes: 1 addition & 1 deletion docs/spec.html
Original file line number Diff line number Diff line change
Expand Up @@ -652,7 +652,7 @@ <h3>Turns and supervisor</h3>
<tr><td class="k"><code>--min-wake / --max-wake</code></td><td><code>2m</code> / <code>2h</code></td><td>clamp for the agent&rsquo;s schedule</td></tr>
<tr><td class="k"><code>--daily-token-ceiling</code></td><td><code>2000000</code></td><td>tokens per UTC day; <code>0</code> = none</td></tr>
<tr><td class="k"><code>--hourly-token-ceiling</code></td><td><code>600000</code></td><td>tokens in any rolling hour; <code>0</code> = none. At the ceiling no wake starts until the oldest turns of the hour have aged out; the samples are in memory (a restart starts the hour empty, the daily ceiling still holds)</td></tr>
<tr><td class="k"><code>--skip-quiet-wakes</code></td><td><code>true</code></td><td>a startup or timer wake with no facts, no held edge and no open issue in the core ends without a model call, unless a person or the agent itself asked for that wake; the next wake is the longest the spot allows, or an event</td></tr>
<tr><td class="k"><code>--skip-quiet-wakes</code></td><td><code>true</code></td><td>a startup or timer wake with no facts, no held edge and no open issue in the core ends without a model call, unless a person or the agent itself asked for that wake; the next wake is the longest the spot allows, or an event. Two more wakes end the same way: one whose facts are all about issues that have closed since, and a timer wake that follows a timer wake whose turn only read the room and planned the next one (the plan of such a turn is kept in time but is not counted as asked for; this holds with an issue open, until something changes or 12 hours have passed)</td></tr>
<tr><td class="k"><code>--poll-interval</code></td><td><code>30s</code></td><td>poll interval, while the stream is down</td></tr>
<tr><td class="k"><code>--edge-cooldown</code></td><td><code>1m</code></td><td>gap between a turn and an edge wake</td></tr>
<tr><td class="k"><code>--chat-batch</code></td><td><code>10m</code></td><td>wait of a message that does not name the spot; <code>0</code> = at once</td></tr>
Expand Down
2 changes: 1 addition & 1 deletion docs/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ The core keeps the spot’s schedule (the core’s ADR-106): the spot decides wh
| Part | Rule |
|---|---|
| The process | One binary, one image. It serves HTTP on `--listen` (`:80`): `GET /readyz`, which answers 200 as soon as the server listens (the actor’s wake-up probe; the join and the hello are done inside the core’s first request, which waits for them), and `POST /frame`. The snapshot keeps only the volumes, so every wake starts a new process. There is no startup wake and no timer of its own: the core’s schedule (ADR-106) is the only clock, and an order from the core is taken as it is, because a new process holds neither the plan nor the promise. |
| Link to the core | Requests, no websocket (the egress gateway refuses every upgrade). `POST /v2/messenger/spot/link` carries `challenge`, `join`, `renew` and `hello` (the certificate join of section 9, with `runtime: substrate` in the hello; the core’s answer may carry `tasks: true`, which says it makes task actors); `POST /v2/messenger/spot/link/report` carries the reports, with the bearer token hello returned. The core does not renew that token (30 minutes): the spot says hello again when under 3 minutes are left, and after any 401 on a report. |
| Link to the core | Requests, no websocket (the egress gateway refuses every upgrade). `POST /v2/messenger/spot/link` carries `challenge`, `join`, `renew` and `hello` (the certificate join of section 9, with `runtime: substrate` in the hello; the core’s answer may carry `tasks: true`, which says it makes task actors); `POST /v2/messenger/spot/link/report` carries the reports, with the bearer token hello returned. The core does not renew that token (30 minutes): the spot says hello again when under 3 minutes are left, and after any 401 on a report. A turn that finds the core's MCP server refusing the token on connect (401, "authorization required") says hello once more, which writes a new token to the token file, and connects again; if that fails too the core is down for the turn. |
| The core’s requests | `POST /frame`, one frame per request, the shapes of the stream. `wake` (`tick` or `promise`), `rooms`, `name` and `budget` are answered 202 at once; `control` is answered 200 with `{"controlResult"}` within 8 s, and the `wake` control asks for a manual wake. The core sends an actor no `issues` frame, so a change of the issues waits for the next tick. Anyone who can reach the port can send a request, so a frame counts only with a token of the core's in `Authorization: Bearer`: one the core CA signed for this actor (the hello says `tokenCheck: signed`, and the core mints one per frame), taken once (the same token on a second frame is a replay, 401), ending no further ahead than the hour, and verified for this spot, workspace and key; or the access token of the last hello, which a core from before signed tokens puts on every request it sends (compared in constant time). The hello token is also kept on `/state`, so a process started for a wake knows it; a saved token that reads as a signed one is taken only while it verifies. Before the link is up a request without it is a bare poke: nothing in it is read, it starts the join and the hello, and the first poke of a process asks for one plain tick wake (no words of its own). With the link up a request without the token is refused, 401. One request is answered at a time (429 for another), the body is 64 KiB at most, and the server has read, write and idle timeouts. A budget with a negative or absurd figure, and a name with a control character, are dropped; the words of a wake order are cut to 200 characters and shown to the model as quoted text, not an instruction; a refused control answers with no task list. |
| Reports | Kept until the supervisor is idle (no turn, no task, nothing waiting), then sent in this order: turns, stats, the wake reports last. The core may suspend the actor once it has the wake report, so nothing follows it. A frame that made no wake (the rooms had nothing new) is answered with `{"wake":{"reason":"rooms","lane":"long","outcome":"idle"}}`, which ends the outstanding wake and leaves the stored plan. The `schedule` frame follows hello only when the process holds a plan, because one without would replace the core’s. |
| What survives | `/state`, the actor’s durable directory: the usage ledger, the room cursors and read marks, the digest, the promises, the identity, and `window.json`: the tokens of the last hour (the hourly ceiling), the early wakes of the last hour (their cap), the issue state edges are told against and the plan the last wake left (the core holds it; an actor that reports a promise without having run a wake says it back). Held edges do not survive a suspension, so `--edge-cooldown` and `--chat-batch` are 0 in this runtime and the next tick reads whatever a cap left. |
Expand Down
2 changes: 1 addition & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ func Parse(args []string, out io.Writer) (Config, error) {
fs.DurationVar(&c.ToolTimeout, "tool-timeout", 60*time.Second, "cap on one tool call; past it the model gets an error result")
fs.IntVar(&c.ToolResultMax, "tool-result-max-bytes", 12288, "cap on the bytes of one tool result the model sees; a longer one is cut and says so")
fs.Int64Var(&c.HourlyTokenCeil, "hourly-token-ceiling", 600_000, "tokens in any rolling hour after which no wake starts until the hour has room again; 0 disables the ceiling")
fs.BoolVar(&c.SkipQuietWakes, "skip-quiet-wakes", true, "end a startup or timer wake without a model call when it has no facts and the core shows no open issue (a wake a person or the agent asked for still runs)")
fs.BoolVar(&c.SkipQuietWakes, "skip-quiet-wakes", true, "end a startup or timer wake without a model call when it has no facts and the core shows no open issue (a wake a person or the agent asked for still runs), and a timer wake that follows one whose turn only read the room")
fs.Int64Var(&c.DailyTokenCeil, "daily-token-ceiling", 2_000_000, "tokens per UTC day after which no wake starts; 0 disables the ceiling")
fs.DurationVar(&c.PollInterval, "poll-interval", 30*time.Second, "how often the core is polled for edges between turns; with --core-api-url only while the trigger stream is down")
fs.DurationVar(&c.EdgeCooldown, "edge-cooldown", time.Minute, "minimum gap between the end of a turn and an edge wake")
Expand Down
9 changes: 9 additions & 0 deletions internal/ledger/ledger.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,15 @@ func (l *Ledger) Path(name string) string { return filepath.Join(l.sup, name) }
// every wake starts an empty one.
type Session struct {
Running bool `json:"running,omitempty"` // a turn was in flight when this was written
// PlanSource is who made the plan the next timer wake belongs to: "agent"
// when the model asked for it, else the supervisor's own label (quiet,
// backoff, a default). Empty in a state written before this was kept.
PlanSource string `json:"planSource,omitempty"`
// Idle counts the timer wakes in a row whose turn did nothing but read the
// room and plan the next one.
Idle int `json:"idle,omitempty"`
// LastTurn is when the last model turn that did not fail ended, Unix ms.
LastTurn int64 `json:"lastTurn,omitempty"`
}

// LoadSession returns the saved session; a missing or unreadable file is an
Expand Down
11 changes: 11 additions & 0 deletions internal/mcptools/mcptools.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,17 @@ func Connect(ctx context.Context, url, tokenFile string, httpTimeout time.Durati
return c, nil
}

// Unauthorized reports whether err says the server refused the access token
// (HTTP 401, which the client reads as "authorization required").
func Unauthorized(err error) bool {
if err == nil {
return false
}
return client.IsOAuthAuthorizationRequiredError(err) ||
strings.Contains(err.Error(), "authorization required") ||
strings.Contains(err.Error(), "401")
}

func readToken(path string) string {
if tok, ok := injected.Read(path); ok {
return tok
Expand Down
110 changes: 108 additions & 2 deletions internal/supervisor/supervisor.go
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,7 @@ func (s *Supervisor) Run(ctx context.Context) error {
orderedWake = pend != nil && s.cfg.Substrate()
}
if pend == nil && s.selfWakeDue() {
pend = &pending{reason: prompt.Tick, scheduledBy: s.scheduledWhy}
pend = &pending{reason: prompt.Tick, scheduledBy: s.askedBy(s.scheduledWhy)}
}
if pend != nil {
if s.paused() {
Expand Down Expand Up @@ -484,6 +484,9 @@ func (s *Supervisor) ordered() *pending {
return nil
}
s.log.Info("the core asks for a wake", "reason", o.Reason)
if o.Reason == "tick" {
why = s.askedBy(why)
}
return &pending{reason: prompt.Tick, scheduledBy: why}
}
switch o.Reason {
Expand All @@ -503,6 +506,7 @@ func (s *Supervisor) ordered() *pending {
if why == "" {
why = s.scheduledWhy
}
why = s.askedBy(why)
default:
s.log.Debug("a wake of a reason the spot does not know is dropped", "reason", o.Reason)
return nil
Expand Down Expand Up @@ -820,6 +824,7 @@ func (s *Supervisor) idleWake(reason, why, source string) {
s.nextTick, s.scheduledWhy = e.At, e.Why
}
s.status.NextWake = &Next{At: s.nextTick.UTC().Format(time.RFC3339), Why: s.scheduledWhy, Source: source}
s.notePlan(source, nil)
s.reportWake(reason, LaneLong, source, agent.Result{}, s.nextTick, source)
s.setState("idle")
}
Expand Down Expand Up @@ -942,16 +947,103 @@ func turnOutcome(failed bool) string {
// model call: every step of a turn sends the whole prompt again, and a spot that
// is woken for nothing would read its notes and go looking. An event, a message
// or the wake the agent asked for still runs a turn.
//
// Two more wakes are quiet. One carried only facts that are no longer true (an
// issue that closed before the wake ran): its edges are still there, its facts
// are not, and there is nothing to show the model. The other follows a timer
// wake whose turn did nothing (idleTurn): the model looked and found nothing,
// so until something changes it is not asked again, open issue or not, for
// idleReview.
func (s *Supervisor) quiet(ctx context.Context, reason prompt.Reason, p *pending, asked bool) bool {
if !s.cfg.SkipQuietWakes || asked || (reason != prompt.Startup && reason != prompt.Tick) || len(p.facts) > 0 || len(p.edges) > 0 {
if !s.cfg.SkipQuietWakes || asked || (reason != prompt.Startup && reason != prompt.Tick) || len(p.facts) > 0 || hasMessage(p.edges) {
return false
}
if s.idleNow() {
return true
}
qctx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
issues, err := s.core.ListOpenIssues(qctx)
return err == nil && len(issues) == 0
}

// idleReview is how long after a turn that did nothing the timer wakes stay
// without a model call. After it the model looks again, once.
const idleReview = 12 * time.Hour

// idleNow reports whether the last timer wake's turn did nothing and that was
// less than idleReview ago. It is read from the state directory: a process
// started for one wake (an actor) holds nothing else of the wake before.
func (s *Supervisor) idleNow() bool {
sess := s.led.LoadSession()
return sess.Idle > 0 && sess.LastTurn > 0 && s.now().Sub(time.UnixMilli(sess.LastTurn)) < idleReview
}

// askedBy is the reason a timer wake is the agent's own: why, when the plan it
// belongs to was the model's and its last turn did something. A plan the
// supervisor made (quiet, backoff, a default) was asked for by nobody, and
// neither is the wake a model planned at the end of a turn that did nothing:
// such a wake only repeats the look. The core sends the words of the plan with
// its order and not who made it, so this is read from the state directory.
func (s *Supervisor) askedBy(why string) string {
sess := s.led.LoadSession()
switch schedule.Source(sess.PlanSource) {
case "", schedule.SourceAgent, schedule.SourceClamped:
default:
return ""
}
if s.idleNow() {
return ""
}
return why
}

// notePlan keeps who made the plan the next timer wake belongs to.
func (s *Supervisor) notePlan(source string, change func(*ledger.Session)) {
sess := s.led.LoadSession()
sess.PlanSource = source
if change != nil {
change(&sess)
}
if err := s.led.SaveSession(sess); err != nil {
s.log.Error("saving session", "err", err)
}
}

// hasMessage reports whether a wake carries something a person or Tria wrote.
func hasMessage(es []heldEdge) bool {
for _, e := range es {
if e.Kind == edges.Message {
return true
}
}
return false
}

// lightTools are the calls of a turn that did nothing: it read its room and
// planned its next wake.
var lightTools = map[string]bool{"read_workspace_room": true, "schedule_next": true, "finish": true}

// idleTurn reports whether a turn's tool calls were all of lightTools.
func idleTurn(res agent.Result) bool {
for _, st := range res.Trace {
if st.Kind == "cut" {
return false
}
if st.Kind != "tool" {
continue
}
name := st.Name
if i := strings.LastIndex(name, "__"); i >= 0 {
name = name[i+2:]
}
if !lightTools[name] {
return false
}
}
return res.Steps > 0
}

// currentFacts drops what the wake need not show: the same fact twice, and a
// fact about an issue that is no longer open.
func (s *Supervisor) currentFacts(ctx context.Context, p *pending) []string {
Expand Down Expand Up @@ -1990,6 +2082,20 @@ func (s *Supervisor) turn(ctx context.Context, p *pending) {
s.kept = plan.Kept
s.setPromises(plan.Promises)
s.status.NextWake = &Next{At: s.nextTick.UTC().Format(time.RFC3339), Why: w.Why, Source: string(w.Source), Note: w.Note}
s.notePlan(string(w.Source), func(sess *ledger.Session) {
if failed {
return
}
sess.LastTurn = s.now().UnixMilli()
// A timer wake nobody wrote to, with nothing to show, whose turn only
// read the room: the next timer wake is not the agent's to ask for.
if p.reason == prompt.Tick && !asked && len(p.facts) == 0 && idleTurn(res) {
sess.Idle++
s.log.Info("the turn did nothing: timer wakes make no model call until something changes", "idle", sess.Idle)
} else {
sess.Idle = 0
}
})
s.reportWake(string(p.reason), LaneLong, turnOutcome(failed), res, s.nextTick, string(w.Source))
if !failed {
s.addDigest(p.reason, res)
Expand Down
Loading