Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
d54d59c
AI-3594: a scheduled reply wait reads how the turn ended from the con…
kanat Nov 23, 2026
c1572fa
AI-3594: test reply waits whose turn ended unwatched
kanat Nov 23, 2026
30b5725
AI-3594: document that every reply wait reads the turn's end from the…
kanat Nov 23, 2026
1af2ee9
Merge remote-tracking branch 'origin/main' into kanat/ai-3594-reply-w…
kanat Nov 23, 2026
266de5a
Merge remote-tracking branch 'origin/main' into kanat/ai-3594-reply-w…
kanat Nov 23, 2026
82136ab
AI-3594: a conversation retry waits out the turn an earlier attempt b…
kanat Nov 23, 2026
282da2c
AI-3594: a text channel carries only its own follow-up's reply
kanat Nov 23, 2026
f8f5877
AI-3594: test a refused conversation follow-up and an interrupted reply
kanat Nov 23, 2026
4d16fc2
AI-3594: the skill row claims the unwatched end only while the sessio…
kanat Nov 23, 2026
fb7afe0
AI-3594: the unwatched-end tests name an attempt cut short in an open…
kanat Nov 23, 2026
d2f9523
AI-3594: test a text follow-up the session refuses
kanat Nov 23, 2026
7c3505e
AI-3594: a text task texts its reply as the conversation keeps it
kanat Nov 23, 2026
51ca37b
Merge remote-tracking branch 'origin/main' into kanat/ai-3594-reply-w…
kanat Nov 23, 2026
dded582
AI-3594: the skill row's line numbers after the merge of main
kanat Nov 23, 2026
5815da5
AI-3594: the reply_failed row names a text channel's first cut-off too
kanat Nov 23, 2026
70d0b5c
AI-3594: merge origin/main (#2277's call path kept, read from events)
kanat Nov 24, 2026
b64e9b9
AI-3594: the money row cites deliveryReason and unpaid at their lines
kanat Nov 24, 2026
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
4 changes: 2 additions & 2 deletions .claude/skills/scheduled-tasks/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,12 +198,12 @@ Run `error` codes (`internal/scheduling/scheduler.go:105`):
| `thread_gone` | A thread task's thread no longer exists, or is not its user's thread of its customer | no |
| `connection_removed` | A thread task's line (its connection) was removed | no |
| `no_reply` | The agent said nothing and made no file to carry | yes |
| `reply_failed` | The reply failed, or was cancelled or interrupted and, when run once more under `st_<run>_r1`, was cut off again (a thread task's first cut-off also gives it, and the retry runs it again) | yes |
| `reply_failed` | The reply failed, or was cancelled or interrupted and, when run once more under `st_<run>_r1`, was cut off again (a text channel's or a thread task's first cut-off also gives it, and the retry runs it again) | yes |
| `no_phone_number` | The user never texted this agent by SMS; a number used only on WhatsApp is not rung | yes |
| `no_agent_number` | The config has no SMS line to ring from | yes |
| `not_answered` | Nobody picked up within the 90 s ring | no |
| `already_called` | A call was placed for this occurrence already, and its end is not recorded; no channel after `phone` is tried. That call may have carried the task out, so the run leaves the failure streak as it is and the task moves on as after a run that did not fail (a one-shot is `completed`) | no |
| `account_suspended`, `insufficient_credits`, `system_limit_reached`, `spend_limit_reached`, `user_limit_reached` | A step the organization may not pay for was refused for money (suspended, no credit left, or a spent limit): an SMS, WhatsApp or iMessage text or a thread task's reply (`dlc.ErrUnpaid`, or its reservation), the task's session opening or being carried on, a turn the model refuses, on a text channel (an `agent.Error` in `captureReply`, which ends the walk over the channels, `refusedTurn`), in the conversation (`followUpInConversation` waits for the turn to end and reads it from the session's events; a turn that ends any other way is still `delivered`) or on a thread task (`deliverOnThread` reads it from the session's events), or its call, placed or not: a placed call whose session cannot open fails under the refusal's code (`carryOutOnCall`); on an answered call, a turn refused before the agent answered anything hangs up (`carryOutAnswered`), and a refusal after that is a later turn's, still `delivered`. The run records the refusal's own code (`deliveryReason`, `scheduled_delivery.go:334`), never `channel_unreachable` or `delivery_failed`, and the router warns, naming the task | no (`unpaid`, `scheduled_delivery.go:355`) |
| `account_suspended`, `insufficient_credits`, `system_limit_reached`, `spend_limit_reached`, `user_limit_reached` | A step the organization may not pay for was refused for money (suspended, no credit left, or a spent limit): an SMS, WhatsApp or iMessage text or a thread task's reply (`dlc.ErrUnpaid`, or its reservation), the task's session opening or being carried on, a turn the model refuses, on a text channel (`captureReply`, which ends the walk over the channels, `refusedTurn`), in the conversation (`followUpInConversation` waits for the turn to end; a turn that ends any other way is still `delivered`) or on a thread task (`deliverOnThread`), or its call, placed or not: a placed call whose session cannot open fails under the refusal's code (`carryOutOnCall`); on an answered call, a turn refused before the agent answered anything hangs up (`carryOutAnswered`, which reads its events), and a refusal after that is a later turn's, still `delivered`. Each reads how the turn ended from the conversation, which keeps the error that failed the reply (`Session.FollowUpFailure`, `turnRefusal`), never from the session's events alone, which a watcher that falls behind loses; a text channel carries only its own follow-up's reply, read back once its turn ends (`readBackReply`). A turn that ended while no attempt watched it, such as one an attempt cut short left running, fails the same way while the session that ran it is still open. That error is kept in memory only: once the conversation is opened again (a restart, a drain, or the end of the session's unwatched grace), the retry reads a bare `failed` and records `reply_failed` on a text channel or a thread, or `delivered` in the conversation (known gap). The run records the refusal's own code (`deliveryReason`, `scheduled_delivery.go:356`), never `channel_unreachable` or `delivery_failed`, and the router warns, naming the task | no (`unpaid`, `scheduled_delivery.go:400`) |
| `spend_check_unavailable` | The router could not check what the organization has spent, so it refused the step for now (`policy.Transient`). A turn it refused runs once more on the retry, under `st_<run>_r1`: the scheduler hands the next attempt the reason this one failed under (`deliverWithRetries`), a hand-off to the router holding the session carries it (`scheduledHandOff.Earlier`), and `replyCommand` reruns a failed reply after a money code. A conversation rerun refused as well fails the attempt under the same code (`followUpInConversation`), so the run fails once its retries are spent. A reply that failed for any other reason is read back as it was. A placed call is rung once: refused this way, its session or its answered turn fails the run under this code, final, with the call kept on the run (`callEnded`), so the user is not rung again | yes (`unpaid` leaves it retryable) |
| `task_paused` | On a `missed` run: a one-shot whose time came while it was paused, or an occurrence the cut-over of a move skipped whose run the source had started | — |

Expand Down
162 changes: 52 additions & 110 deletions acceleration/internal/api/scheduled_delivery.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,6 @@ const scheduledPeerPath = "/internal/scheduled-tasks/deliver"
// a window spent is an attempt, not a lost occurrence.
const scheduledWindow = 10 * time.Minute

// scheduledReplySettle is how long the agent stays quiet, with nothing left
// running, before what it said is taken as its answer: a channel's own
// reading of a turn (channels.settleGap), over the same words.
var scheduledReplySettle = 2 * time.Second

// scheduledReplyWindow bounds reading an answer for a channel. The lease is
// renewed while a delivery runs, so a slow turn is waited out; one still
// running at the window's end fails the channel, not the conversation.
Expand Down Expand Up @@ -500,112 +495,67 @@ func (s *Server) waitOutCall(ctx context.Context, found *session.Session, window
return nil
}

// captureReply runs the follow-up in found and reads what the agent
// answers, and the files its code made, settled the way a channel's replies
// settle: quiet for the settle gap, with nothing left running. The words are
// the conversation's own; a channel carries them out, holding no second copy
// of the turn. A follow-up the conversation already holds is not run again:
// its words and files are read back.
// captureReply runs the follow-up in found and reads what the agent answers to it, and the files
// its code made, once its turn has ended (readBackReply). The words are the conversation's own,
// of this follow-up alone: another turn the follow-up waited behind (followUpWithin) is not
// carried. A channel carries them out, holding no second copy of the turn. A follow-up the
// conversation already holds is not run again: its words and files are read back the same.
func (s *Server) captureReply(ctx context.Context, found *session.Session, delivery scheduledDelivery) (string, []sandbox.Attachment, error) {
delivery.CommandID = replyCommand(found, delivery.CommandID, delivery.Earlier)
if err := refusedAgain(found, delivery); err != nil {
return "", nil, err
}
if _, _, known := found.FollowUpReply(delivery.CommandID); known {
reply, err := s.readBackReply(ctx, found, delivery.CommandID)
return reply.Text, reply.Files, err
}
events, detach := found.Watch()
defer detach()
if err := s.followUpWithin(ctx, found, delivery); err != nil {
return "", nil, err
}
var said []string
var files []sandbox.Attachment
active := found.Busy()
last := time.Now()
deadline := time.Now().Add(s.replyWindow)
ticker := time.NewTicker(250 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return "", nil, ctx.Err()
case event, open := <-events:
if !open {
return captured(said, files)
}
active, last = true, time.Now()
// A turn the organization may not pay for ends with the model's refusal, which no
// reply follows: the run records the money, not an agent that said nothing.
if refusal := turnRefusal(event); refusal != nil {
return "", nil, refusal
}
if text := spokenOf(event); text != "" && (len(said) == 0 || said[len(said)-1] != text) {
said = append(said, text)
}
// Merged as the conversation keeps them, so a retry reading them back sends the same.
files = conversation.MergeFiles(files, madeBy(event))
case <-ticker.C:
if found.Busy() {
active = true
}
switch {
case time.Now().After(deadline):
return captured(said, files)
case active && !found.Busy() && time.Since(last) >= scheduledReplySettle:
return captured(said, files)
}
if _, _, known := found.FollowUpReply(delivery.CommandID); !known {
if err := s.followUpWithin(ctx, found, delivery); err != nil {
return "", nil, err
}
}
reply, err := s.readBackReply(ctx, found, delivery.CommandID)
return reply.Text, reply.Files, err
}

// followUpInConversation puts the follow-up to found, whose conversation carries the reply, and
// waits for its turn to end. A turn the organization may not pay for ends with the model's
// refusal, which leaves the user nothing: the run records the money (turnRefusal), as a text
// channel's does. Any other end leaves the reply in the conversation as it stands, delivered: a
// turn that finished or failed for another reason, one still running at scheduledReplyWindow, or a
// session that ended. A follow-up the conversation already holds runs nothing, so nothing is
// waited for: it stands as it is, except a rerun after a refusal for money (replyCommand) that
// failed too, which left the user nothing again. That one fails the attempt under the earlier
// reason, tried again until the run's attempts are spent, as a text channel's is.
// session that ended. How the turn ended is read from the conversation (turnRefusal), never from
// the events alone, which a watcher that falls behind loses. A follow-up the conversation already
// holds runs nothing: its turn, which an earlier attempt began, is waited out the same, and one
// already ended settles at once, failing under the money when it was refused for money while no
// attempt watched it. A rerun after a refusal for money (replyCommand) that failed too left the
// user nothing again: it fails the attempt under the earlier reason, tried again until the run's
// attempts are spent, as a text channel's is.
func (s *Server) followUpInConversation(ctx context.Context, found *session.Session, delivery scheduledDelivery) error {
if err := refusedAgain(found, delivery); err != nil {
return err
}
_, _, known := found.FollowUpReply(delivery.CommandID)
events, detach := found.Watch()
defer detach()
if err := s.followUpWithin(ctx, found, delivery); err != nil || known {
if err := s.followUpWithin(ctx, found, delivery); err != nil {
return err
}
deadline := time.Now().Add(s.replyWindow)
ticker := time.NewTicker(s.replyPoll)
defer ticker.Stop()
for {
// An event or a tick is when to look: how the turn ended is read from the conversation,
// which records it before the session sends watchers the event (Session.consume), so a
// watcher that has fallen behind and lost it still settles the same.
select {
case <-ctx.Done():
return ctx.Err()
case event, open := <-events:
case _, open := <-events:
if !open {
return nil
}
if refusal := turnRefusal(event); refusal != nil {
return refusal
}
// The conversation records the agent.Error that fails a turn before the session sends
// it to watchers (Session.consume), so the turn has failed by now if it was this one.
if _, erred := event.(agent.Error); erred {
if state, _, _ := found.FollowUpReply(delivery.CommandID); replyEnded(state) {
return nil
}
}
case <-ticker.C:
// A failed turn is told by its agent.Error, which says whether it was the money.
state, _, _ := found.FollowUpReply(delivery.CommandID)
if state != "failed" && replyEnded(state) || time.Now().After(deadline) {
return nil
}
}
if state, _, _ := found.FollowUpReply(delivery.CommandID); replyEnded(state) {
return turnRefusal(found, delivery.CommandID)
}
if time.Now().After(deadline) {
return nil
}
}
}
Expand All @@ -627,14 +577,19 @@ type turnRefused struct{ error }

func (e turnRefused) Unwrap() error { return e.error }

// turnRefusal is the failure a text turn's event ends it with, when the event is the model's
// refusal for money (unpaid), and nil otherwise: any other agent.Error, such as a tool's, leaves
// the turn running.
func turnRefusal(event session.Event) error {
if failed, erred := event.(agent.Error); erred {
if _, refused := moneyError(failed.Err); refused {
return unpaid(turnRefused{failed.Err})
}
// turnRefusal is the failure the reply to the follow-up under id in found ends with, when the
// conversation records it failed on the model's refusal for money (unpaid), and nil otherwise:
// a reply still running, one that ended any other way, or a failure a watcher alone was told of,
// such as a tool's (Session.Report), which leaves the turn running.
func turnRefusal(found *session.Session, id string) error {
return moneyRefusal(found.FollowUpFailure(id))
}

// moneyRefusal is failure as the refusal for money that ended a text turn (turnRefused), and nil
// when failure is nil or any other error.
func moneyRefusal(failure error) error {
if _, refused := moneyError(failure); refused {
return unpaid(turnRefused{failure})
}
return nil
}
Expand Down Expand Up @@ -694,6 +649,11 @@ func (s *Server) readBackReply(ctx context.Context, found *session.Session, id s
}
return reply, nil
case "cancelled", "interrupted", "failed":
// A turn the organization may not pay for failed on the model's refusal: the run records
// the money, as the attempt that ran the turn would have.
if refusal := turnRefusal(found, id); refusal != nil {
return conversation.FinishedReply{}, refusal
}
return conversation.FinishedReply{}, undelivered(scheduling.ReasonReplyFailed, fmt.Errorf("the reply to this occurrence was %s", state))
}
if time.Now().After(deadline) {
Expand All @@ -716,28 +676,6 @@ func captured(said []string, files []sandbox.Attachment) (string, []sandbox.Atta
return text, files, nil
}

// spokenOf is what an event is worth carrying out, if anything: the agent's
// finished reply. Settled work's own words are not: the agent's next turn
// tells them, and the conversation keeps only the reply, which a retry reads
// back.
func spokenOf(event session.Event) string {
if happened, ok := event.(agent.Responded); ok {
return happened.Text
}
return ""
}

// madeBy is the files an event hands back: what the code a tool or settled work ran made.
func madeBy(event session.Event) []sandbox.Attachment {
switch happened := event.(type) {
case agent.ToolRan:
return happened.Files
case agent.TaskSettled:
return happened.Files
}
return nil
}

// reachableText says whether a channel would carry the task's words to its
// user now, the words aside.
func (s *Server) reachableText(ctx context.Context, delivery scheduledDelivery, channel string) error {
Expand Down Expand Up @@ -1334,8 +1272,12 @@ func (s *Server) carryOutAnswered(ctx context.Context, created *session.Session,
if !open {
return nil
}
if refusal := turnRefusal(event); refusal != nil && !answered {
return refusal
// The call's turn is read from its events: a refusal is the call's end only while
// the agent has answered nothing, and the conversation keeps no such order.
if failed, erred := event.(agent.Error); erred && !answered {
if refusal := moneyRefusal(failed.Err); refusal != nil {
return refusal
}
}
if _, ok := event.(agent.Responded); ok {
answered = true
Expand Down
22 changes: 10 additions & 12 deletions acceleration/internal/api/scheduled_reply_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (

"github.com/stretchr/testify/require"

"github.com/GetStream/Vision-Agents/acceleration/internal/agent"
"github.com/GetStream/Vision-Agents/acceleration/internal/sandbox"
"github.com/GetStream/Vision-Agents/acceleration/internal/scheduling"
)
Expand Down Expand Up @@ -37,15 +36,14 @@ func TestAReplyOfTwoTurnsIsJoinedAsTheConversationJoinsThem(t *testing.T) {
require.Equal(t, "First.\n\nSecond.", text)
}

func TestTheFilesCodeHandedBackAreThoseOfARunAndOfSettledWork(t *testing.T) {
chart := sandbox.Attachment{Name: "chart.png", MIME: "image/png", URL: "https://cdn.example/chart.png"}

require.Equal(t, []sandbox.Attachment{chart}, madeBy(agent.ToolRan{Files: []sandbox.Attachment{chart}}))
require.Equal(t, []sandbox.Attachment{chart}, madeBy(agent.TaskSettled{Files: []sandbox.Attachment{chart}}))
require.Nil(t, madeBy(agent.Responded{Text: "Here is the chart."}))
}

func TestSettledWorksOwnWordsAreNotCarriedButTheAgentsReplyIs(t *testing.T) {
require.Empty(t, spokenOf(agent.TaskSettled{Text: "steps: 9,214"}))
require.Equal(t, "You walked 9,214 steps today.", spokenOf(agent.Responded{Text: "You walked 9,214 steps today."}))
// A reply ends however its turn did, interrupted included: a regenerate or an edit during the
// turn interrupts it (Conversation.switchTo) while the session stays open, and a wait that took
// it for running would hold its worker to the end of the reply window (AI-3594 R1.3).
func TestAReplyEndsHoweverItsTurnEnded(t *testing.T) {
for _, state := range []string{"completed", "cancelled", "interrupted", "failed"} {
require.True(t, replyEnded(state), state)
}
for _, state := range []string{"", "thinking", "writing", "tools", "queued"} {
require.False(t, replyEnded(state), state)
}
}
10 changes: 6 additions & 4 deletions acceleration/internal/api/scheduled_tasks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3432,7 +3432,9 @@ func (s *ScheduledTasksSuite) TestATaskTextedBySMSCarriesTheFileItsCodeMade() {
s.Equal("sms", run.DeliveredTo)
s.Require().Eventually(func() bool { return len(s.sink.mediaTo(writer)) > 0 },
10*time.Second, 50*time.Millisecond, "no file was texted to %s", writer)
s.Equal([]string{"Done."}, s.sink.to(writer))
// The words of both rounds, as the conversation keeps them and a thread task texts them
// (reportReply).
s.Equal([]string{"Done.\n\nDone."}, s.sink.to(writer))
s.Equal([]string{report}, s.sink.mediaTo(writer))
}

Expand Down Expand Up @@ -3465,7 +3467,7 @@ func (s *ScheduledTasksSuite) TestATaskWhoseFileTheLineRefusesTextsItsWordsOnce(
run := s.delivered(s.tasksOf(user)[0])
s.Equal("sms", run.DeliveredTo)
s.Never(func() bool { return len(s.sink.to(writer)) > 1 }, dropped, 20*time.Millisecond, "texted once")
s.Equal([]string{"Done."}, s.sink.to(writer))
s.Equal([]string{"Done.\n\nDone."}, s.sink.to(writer), "the words of both rounds, as the conversation keeps them")
s.Empty(s.sink.mediaTo(writer), "the file was refused")
}

Expand Down Expand Up @@ -4194,7 +4196,7 @@ func (s *ScheduledTasksSuite) TestATurnCancelledBeforeItsReplyRunsAgainOnTheRetr
task, found := s.onWhatsApp(writer, "whatsapp")
run := s.manualRun(task)
_, err := s.cutOff(s.router, task, run, found.Interrupt)
s.Equal(scheduling.ReasonNoReply, scheduling.ReasonOf(err), "%v", err)
s.Equal(scheduling.ReasonReplyFailed, scheduling.ReasonOf(err), "%v", err)

deliveredTo, err := s.deliverRun(task, run)

Expand Down Expand Up @@ -4231,7 +4233,7 @@ func (s *ScheduledTasksSuite) TestATurnWhoseProviderBrokeAsItWasCancelledRunsAga
}
})
_, err := s.cutOff(s.router, task, run, found.Interrupt)
s.Equal(scheduling.ReasonNoReply, scheduling.ReasonOf(err), "%v", err)
s.Equal(scheduling.ReasonReplyFailed, scheduling.ReasonOf(err), "%v", err)
state, _, _ := found.FollowUpReply(command)
s.Equal("cancelled", state)

Expand Down
Loading
Loading