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
3 changes: 2 additions & 1 deletion .claude/skills/scheduled-tasks/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ Read the task, then its runs, then the logs, in that order.

| Check | How | What it means |
| --- | --- | --- |
| Task `state` | `GET /v1/agents/scheduled-tasks/{id}` | `paused`: a pause, or its config was deleted (`internal/api/configs.go:308`). `failed`: five failed occurrences in a row (`maxConsecutiveFailures`), or a last occurrence that failed; resume clears it. A failed task with no occurrence left, or a paused one that did not sleep through its time, answers resume with 400 `schedule_in_past`: PATCH a new schedule first. A paused one-shot whose time passed while paused is completed with a `missed` run (`task_paused`). `completed`: a one-shot ran, or the repeat has nothing left |
| Task `state` | `GET /v1/agents/scheduled-tasks/{id}` | `paused`: a pause, or its config was deleted (`internal/api/configs.go:308`). `failed`: five failed occurrences in a row (`maxConsecutiveFailures`), or a last occurrence that failed; resume clears it. A failed task with no occurrence left, or a paused one that did not sleep through its time, answers resume with 400 `schedule_in_past`: PATCH a new schedule first, 15 min out at the soonest. A paused one-shot whose time passed while paused is completed with a `missed` run (`task_paused`). `completed`: a one-shot ran, or the repeat has nothing left |
| `next_run_at`, `upcoming` | same | In the task's zone. Wrong hour: the zone (below) |
| `schedule.timezone` | same | Resolved at create from the call, the session, `users.timezone`, then `default_timezone`. A session opened with a zone moves `users.timezone` (`internal/api/session_create.go:76`) |
| `quiet_hours` | same | An occurrence due inside them is held to their end: its run stays `running` with nothing sent. A run by hand is never held |
Expand All @@ -182,6 +182,7 @@ Read the task, then its runs, then the logs, in that order.
| Limit | create or resume answers 409 `too_many_tasks` | The user holds `max_tasks_per_user` active tasks on this config |
| Edit refused | update, pause or resume answers 409 `task_changed` | The task changed between the request's read and its save (another edit or pause, or a worker's claim, hold, finish or session write; a lease renewal is not a change): nothing was saved, so read it again and retry. The agent's `update_scheduled_task` is refused the same way |
| The tools | the model never calls `schedule_task` | `scheduling.enabled` off, incognito, a guest or anonymous caller, or a `noauth` router |
| Tool refused | `schedule_task` answers `interval_too_short` or `scheduled_turn` | The agent's first run is 15 min from now at the soonest (`scheduling.MinMove`). A turn a task fired cannot schedule a task, nor reschedule, snooze or resume one; it may list, pause, skip and cancel |
| Old history gone | a completed or failed task 404, or old runs missing | A daily job deletes runs finished over 90 days ago, and completed or failed tasks over 90 days old (`ScheduledTasksKept`); active and paused tasks stay |
| Session deleted | task 404 | Deleting a session deletes the tasks made in it or following up in it, with their runs, and redacts the changes recorded of them (`DeleteForSession`) |
| User forgotten | task 404, its runs gone | `router usage forget-user` deleted every task of that user in the app, with its runs, and redacted the changes recorded of them (`ForgetUserTasks`) |
Expand Down
14 changes: 11 additions & 3 deletions .factory/features/scheduled-tasks.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,14 @@ Create does not need `scheduling.enabled`: that flag only offers the tools
(`internal/api/scheduled_tasks.go:752`). A device may not change `instructions` (403).

A move is refused with `interval_too_short` when it lands under 15 minutes from now
(`scheduling.MinMove`, `scheduling.go:52`). One move is allowed: to or past the current run,
(`scheduling.MinMove`, `scheduling.go:56`). One move is allowed: to or past the current run,
when that run is still ahead. With no run pending, or with the current run already due,
every move must be 15 minutes out (`scheduling.CheckMove`, `scheduling.go:59`).
every move must be 15 minutes out (`scheduling.CheckMove`, `scheduling.go:63`). A schedule
written to a failed task is held to the same check, since its resume takes the next run from
that schedule. The agent's `schedule_task` sets a first run 15 minutes out at the soonest
(`scheduling.CheckFirst`); a backend's create over REST has no floor. The agent's
`reschedule` counts a new zone, repeat or until as a move, as a PATCH counts every schedule
it writes; a new title or instructions alone is not one.

A task's `last_run_at` is when a run last finished, in UTC (`max(finished_at)`,
`internal/store/scheduled_tasks.go:845`). A run's `scheduled_for` is when the occurrence was
Expand All @@ -115,7 +120,10 @@ and `last_run_at` Tue 10:00.

Scheduled turns are customer spend: they never consume the end user's daily caps. That is
the follow-up turn and the replies that finish it. What the user types after it is theirs
again.
again. So a scheduled turn cannot set a run going: `schedule_task`, and the `reschedule`,
`snooze` and `resume` of `update_scheduled_task`, answer it `scheduled_turn`. Otherwise a
task could make the next one, and they would run on, uncounted, with nobody asking again.
It may still list, pause, skip and cancel.

Delivery goes where the task says, in order (`deliver_to`, default the conversation alone).
The agent's reply is written once in its conversation, under the run's command id. A text
Expand Down
65 changes: 65 additions & 0 deletions acceleration/internal/agent/native_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -631,6 +631,71 @@ func (s *AgentSuite) TestWorkANativeModelHandsOverInAReplyWithNoIDIsAskedAsSched
s.Equal([]bool{true}, s.subagent.askedScheduled())
}

// joinNativeReportingScheduledCalls joins a native model offered remind_later, whose runs
// say on the channel returned whether each was asked for in a turn a scheduled task fired.
func (s *AgentSuite) joinNativeReportingScheduledCalls() (*nativePeer, <-chan bool) {
ran := make(chan bool, 1)
peer := s.joinNativeWith(func(options *Options) {
options.Tools = harness.Tools{Tools: []harness.Tool{{Name: "remind_later", Description: "remind the caller later"}}}
options.ToolRunner = &stubToolRunner{run: func(ctx context.Context, _ llm.ToolCall) ([]llm.ContentPart, error) {
ran <- ScheduledCall(ctx)
return llm.TextParts("{}"), nil
}}
})
return peer, ran
}

// ranScheduled is whether the one run on ran was a scheduled task's call.
func (s *AgentSuite) ranScheduled(ran <-chan bool) bool {
select {
case scheduled := <-ran:
return scheduled
case <-time.After(settleFor):
s.FailNow("the tool never ran")
return false
}
}

func (s *AgentSuite) TestAToolAskedInAScheduledNativeTurnRunsAsTheTasksCall() {
peer, ran := s.joinNativeReportingScheduledCalls()
_, err := s.agent.RespondTo(routing.WithScheduledTurn(s.ctx), "Remind me of my booking", nil, options.LLM{})
s.Require().NoError(err)
s.nativeFrame(peer, "response.create")
s.nativeSend(peer, `{"type":"response.created","response":{"id":"r1"}}`)
s.nativeSend(peer, `{"type":"response.function_call_arguments.done","response_id":"r1","call_id":"call1","name":"remind_later","arguments":"{}"}`)

s.True(s.ranScheduled(ran), "the scheduled task's reply asked for it")
}

// The caller cutting in does not make a call the task's reply already asked for theirs.
func (s *AgentSuite) TestAToolTheTasksNativeReplyAsksForAfterTheCallerCutsInIsStillTheTasksCall() {
peer, ran := s.joinNativeReportingScheduledCalls()
_, err := s.agent.RespondTo(routing.WithScheduledTurn(s.ctx), "Remind me of my booking", nil, options.LLM{})
s.Require().NoError(err)
s.nativeFrame(peer, "response.create")
s.nativeSend(peer, `{"type":"response.created","response":{"id":"r1"}}`)
s.nativeSend(peer, `{"type":"input_audio_buffer.speech_started"}`)
s.heardSpeechStart()
s.nativeSend(peer, `{"type":"response.function_call_arguments.done","response_id":"r1","call_id":"call1","name":"remind_later","arguments":"{}"}`)

s.True(s.ranScheduled(ran), "the scheduled task's reply asked for it")
}

func (s *AgentSuite) TestAToolAskedInTheCallersOwnNativeReplyIsNotTheTasksCall() {
peer, ran := s.joinNativeReportingScheduledCalls()
_, err := s.agent.RespondTo(routing.WithScheduledTurn(s.ctx), "Remind me of my booking", nil, options.LLM{})
s.Require().NoError(err)
s.nativeFrame(peer, "response.create")
s.nativeSend(peer, `{"type":"response.created","response":{"id":"r1"}}`)
s.nativeSend(peer, `{"type":"response.done","response":{"id":"r1","status":"completed"}}`)
s.nativeSend(peer, `{"type":"input_audio_buffer.speech_started"}`)
s.heardSpeechStart()
s.nativeSend(peer, `{"type":"response.created","response":{"id":"r2"}}`)
s.nativeSend(peer, `{"type":"response.function_call_arguments.done","response_id":"r2","call_id":"call2","name":"remind_later","arguments":"{}"}`)

s.False(s.ranScheduled(ran), "the caller asked for it")
}

func (s *AgentSuite) TestAToolsPictureInAScheduledNativeTurnIsLookedAtAsScheduledWhenTheCallerCutsInWhileItRuns() {
running := make(chan struct{}, 1)
release := make(chan struct{})
Expand Down
16 changes: 16 additions & 0 deletions acceleration/internal/agent/requester.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,22 @@ func RequesterFrom(ctx context.Context) (Requester, bool) {
return requester, ok
}

type scheduledCallKey struct{}

// WithScheduledCall marks ctx as a tool call asked for in a turn a scheduled task fired, which
// nobody asked for just now. It is not routing.WithScheduledTurn: that one makes spend the
// customer's, and what the tool does after is still charged as it was.
func WithScheduledCall(ctx context.Context) context.Context {
return context.WithValue(ctx, scheduledCallKey{}, true)
}

// ScheduledCall reports whether the tool call ctx runs was asked for in a turn a scheduled task
// fired.
func ScheduledCall(ctx context.Context) bool {
scheduled, _ := ctx.Value(scheduledCallKey{}).(bool)
return scheduled
}

// requesterLocked is who the turn being answered came from. A participant heard on a call
// names their user; a message written in a channel of a type an agent config answers in names
// its writer (WithWriter); a typed command names its sender. The caller holds a.mu.
Expand Down
16 changes: 10 additions & 6 deletions acceleration/internal/agent/telephony.go
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,15 @@ func (a *Agent) prepareTool(requested harness.ToolRequested) (context.Context, c
if requester := a.requesterLocked(); requester != (Requester{}) {
parent = WithRequester(parent, requester)
}
// A call is the scheduled task's when its reply is known to be (scheduledReply), or when
// the last thing is a scheduled turn and the call's reply is not known to be the one that
// answered the caller (answerReply).
known := requested.TurnID != ""
scheduled := a.scheduled && !(known && requested.TurnID == a.answerReply) ||
known && requested.TurnID == a.scheduledReply
if scheduled {
parent = WithScheduledCall(parent)
}
ctx, cancel := context.WithCancel(parent)
if a.toolCancels == nil {
a.toolCancels = map[string]context.CancelFunc{}
Expand All @@ -609,12 +618,7 @@ func (a *Agent) prepareTool(requested harness.ToolRequested) (context.Context, c
if a.toolScheduled == nil {
a.toolScheduled = map[string]bool{}
}
// A call is the scheduled task's when its reply is known to be (scheduledReply), or when
// the last thing is a scheduled turn and the call's reply is not known to be the one that
// answered the caller (answerReply).
known := requested.TurnID != ""
a.toolScheduled[requested.Call.ID] = a.scheduled && !(known && requested.TurnID == a.answerReply) ||
known && requested.TurnID == a.scheduledReply
a.toolScheduled[requested.Call.ID] = scheduled
if a.toolsRunning == nil {
a.toolsRunning = map[string]string{}
}
Expand Down
10 changes: 10 additions & 0 deletions acceleration/internal/api/scheduled_tasks.go
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,16 @@ func (s *Server) rescheduleTask(task *store.ScheduledTask, written ScheduledTask
}
task.NextRunAt = &next
}
// A failed task's resume, and the agent's reschedule of a completed one that names no new
// time, arm the next occurrence of this schedule as written and check nothing, so that
// occurrence is held to the floor here.
if task.State == store.ScheduledTaskFailed || task.State == store.ScheduledTaskCompleted {
if next, ok := parsed.Next(now); ok {
if err := scheduling.CheckMove(next, current, now); err != nil {
return scheduleFailure(err)
}
}
}
task.StartLocal, task.Timezone, task.RRule = parsed.StartLocal, parsed.Timezone, parsed.Repeat
task.UntilDate = nil
if !parsed.Until.IsZero() {
Expand Down
Loading
Loading