diff --git a/.claude/skills/scheduled-tasks/SKILL.md b/.claude/skills/scheduled-tasks/SKILL.md index a0acc61fe3..7fd3703289 100644 --- a/.claude/skills/scheduled-tasks/SKILL.md +++ b/.claude/skills/scheduled-tasks/SKILL.md @@ -203,8 +203,8 @@ Run `error` codes (`internal/scheduling/scheduler.go:105`): | `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. 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`) | -| `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__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 | yes (`unpaid` leaves it retryable) | +| `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`) | +| `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__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 | — | A failure is retried after 30 s, 2 min and 10 min (`DeliveryRetries`) only when the failure diff --git a/acceleration/internal/api/scheduled_delivery.go b/acceleration/internal/api/scheduled_delivery.go index 14bcaaa9f3..f2e6c32e53 100644 --- a/acceleration/internal/api/scheduled_delivery.go +++ b/acceleration/internal/api/scheduled_delivery.go @@ -1112,7 +1112,8 @@ func (s *Server) openTaskSession(ctx context.Context, delivery scheduledDelivery // is the one the user texts this agent from; the number rung from is the // agent's own text line. An occurrence rings once: the call's session is // taken on the run before it is placed, so neither a retry nor a worker -// taking the run over rings the user again (callEnded). A call the +// taking the run over rings the user again (callEnded): a placed call is rung +// once, whatever refuses it. A call the // occurrence has no time left to ring and hold is missed, not placed: it // would be hung up mid-sentence when the occurrence runs out. The call is // taken before anything else is checked, so an attempt after the one that @@ -1212,13 +1213,18 @@ func callSpec(config store.AgentConfig, delivery scheduledDelivery, agentID stri // carryOutOnCall opens the session of a call a task placed and holds the // call until it is over. The user has been rung by now, so a failure is -// final: another attempt would ring them again. +// final: another attempt would ring them again, even after a refusal because +// the money could not be checked (callEnded). func (s *Server) carryOutOnCall(ctx context.Context, delivery scheduledDelivery, spec session.Spec) (string, string, error) { created, err := s.sessions.Create(ctx, spec) if _, unanswered := errors.AsType[*session.CallUnansweredError](err); unanswered { return "", "", s.callEnded(ctx, delivery, spec.ID, undeliveredFinally(scheduling.ReasonNotAnswered, err)) } if err != nil { + // A session the organization may not pay for fails under the refusal's code (unpaid). + if _, refused := moneyError(err); refused { + return "", "", s.callEnded(ctx, delivery, spec.ID, unpaid(err)) + } return "", "", s.callEnded(ctx, delivery, spec.ID, undeliveredFinally(scheduling.ReasonFailed, err)) } if err := s.store.ScheduledTasks.SetSession(ctx, delivery.CustomerID, delivery.TaskID, created.ID()); err != nil { @@ -1239,12 +1245,16 @@ func (s *Server) carryOutOnCall(ctx context.Context, delivery scheduledDelivery, // callEnded records on the run the reason the call callID failed under, and // answers that failure: a worker taking the run over after this one stopped -// finds the call placed, and records how it went rather than that it was. +// finds the call placed, and records how it went rather than that it was. The +// user has been rung, so every failure is final, a refusal because the money +// could not be checked (unpaid) included: a retry would ring nobody, and a +// second ring is the most intrusive way to try again (AI-3597). func (s *Server) callEnded(ctx context.Context, delivery scheduledDelivery, callID string, err error) error { var failure *scheduling.Failure if !errors.As(err, &failure) { return err } + failure.Final = true if err := s.store.ScheduledTaskRuns.SetCallReason(context.WithoutCancel(ctx), delivery.CustomerID, delivery.RunID, callID, failure.Reason); err != nil { s.logger.Error("could not record how a scheduled task's call ended", "run", delivery.RunID, "error", err) } @@ -1299,7 +1309,12 @@ func (s *Server) holdCall(ctx context.Context, created *session.Session, deliver // carryOutAnswered sends the task as the first turn of a call somebody // picked up, and stays on it until it ends, or until scheduledCallLimit, -// when the agent hangs up. +// when the agent hangs up. A turn the organization may not pay for, refused +// before the agent answered anything on the call, leaves the agent silent: +// the attempt fails under the money (turnRefusal), final (callEnded), and the +// agent hangs up. A refusal because the money could not be checked is final +// too: a placed call is rung once. A refusal after the agent answered is a +// later turn's: the task was said. func (s *Server) carryOutAnswered(ctx context.Context, created *session.Session, delivery scheduledDelivery, events <-chan session.Event) error { // The call's turn has an id of its own: a channel tried before the call // left its turn in the conversation under the run's, which would be taken @@ -1310,14 +1325,21 @@ func (s *Server) carryOutAnswered(ctx context.Context, created *session.Session, } limit := time.NewTimer(scheduledCallLimit) defer limit.Stop() + answered := false for { select { case <-ctx.Done(): return ctx.Err() - case _, open := <-events: + case event, open := <-events: if !open { return nil } + if refusal := turnRefusal(event); refusal != nil && !answered { + return refusal + } + if _, ok := event.(agent.Responded); ok { + answered = true + } case <-limit.C: return nil } diff --git a/acceleration/internal/api/scheduled_unpaid_test.go b/acceleration/internal/api/scheduled_unpaid_test.go index 7c61b1dd8b..36ea88038b 100644 --- a/acceleration/internal/api/scheduled_unpaid_test.go +++ b/acceleration/internal/api/scheduled_unpaid_test.go @@ -12,6 +12,7 @@ import ( "testing" "time" + "github.com/GetStream/Vision-Agents/acceleration/internal/agent" "github.com/GetStream/Vision-Agents/acceleration/internal/auth" "github.com/GetStream/Vision-Agents/acceleration/internal/channelbridge" "github.com/GetStream/Vision-Agents/acceleration/internal/channels" @@ -1166,3 +1167,364 @@ func (s *TelnyxUnpaidSuite) TestAConversationTurnTheUserStopsIsDelivered() { s.Fail("the delivery never settled once the turn was stopped") } } + +// ringing is a phone task's call as deliverByPhone holds it once the vendor placed it: the +// delivery, taken on a run of its own, and the session the call is held in, open on an edge the +// test picks up, in the conversation of a session the user opened while the organization had +// credit. writer is the number the user is rung on, line the one rung from, agentID the agent the +// conversation is written as, done what carrying the task out came to. +type ringing struct { + task store.ScheduledTask + run store.ScheduledTaskRun + delivery scheduledDelivery + spec session.Spec + edge *ringingEdge + writer string + line string + agentID string + done <-chan callOutcome + // answered is closed once the agent answers on the call. + answered <-chan struct{} +} + +// ringingOn is ringing, on model, with the call's session opened and nobody picked up yet. +func (s *TelnyxUnpaidSuite) ringingOn(model string) ringing { + return s.ring(s.dial(s.callOn(model))) +} + +// callOn is ringing, on model, with the call taken on its run and not placed yet. +func (s *TelnyxUnpaidSuite) callOn(model string) ringing { + window, longest := scheduledPhoneWindow, scheduledCallLimit + // The limit is longer than the test waits for the call to be let go: a call let go is one + // the agent hung up, or the test ended. + scheduledPhoneWindow, scheduledCallLimit = deliveryWait, 2*deliveryWait + s.T().Cleanup(func() { scheduledPhoneWindow, scheduledCallLimit = window, longest }) + number, writer := "+1555"+digits(s.utils.uuid()), "+1347"+digits(s.utils.uuid()) + s.seedSMSLine(number) + s.config.Channels.Lines = store.AgentChannels{SMS: &store.ChannelLine{Number: number}} + s.config.Models.LLM = model + s.Require().NoError(s.store.AgentConfigs.Update(context.Background(), &s.config)) + user := s.data.createUser() + s.Require().NoError(s.store.ContactMapEntries.Upsert(context.Background(), &store.ContactMapEntry{ + CustomerID: s.customerID(), ConfigID: s.config.ID, Kind: string(channels.SMS), Address: writer, UserID: user.userID, + })) + s.usage.Credit(s.T(), s.RouterSuite.app.organization.ID, 10_000_000) + s.Require().Eventually(func() bool { + return s.gate.Allow(context.Background(), s.customerID(), dlc.SMS, writer) == nil + }, 10*time.Second, 50*time.Millisecond, "the credit is read") + opened := user.createSession(CreateSessionRequest{ConfigId: &s.config.ID}) + task := s.userTask(user, opened.Id, "phone") + now := time.Now() + run := store.ScheduledTaskRun{TaskID: task.ID, CustomerID: task.CustomerID, ScheduledFor: now, + Trigger: store.ScheduledTaskTriggerManual, Prompt: task.Instructions, State: store.ScheduledTaskRunRunning, + Attempts: 1, StartedAt: &now} + s.Require().NoError(s.store.ScheduledTaskRuns.Insert(context.Background(), &run)) + found, running := s.router.sessions.Get(opened.Id, session.Owner{CustomerID: s.customerID(), UserID: user.userID, Kind: auth.KindAuthenticated}) + s.Require().True(running) + delivery := scheduledDelivery{CustomerID: s.customerID(), ConfigID: s.config.ID, UserID: user.userID, + CallerKind: "authenticated", TaskID: task.ID, RunID: run.ID, SessionID: opened.Id, + ConversationID: found.Spec().ConversationID, CommandID: "st_" + run.ID, Text: "stretch", Due: now, + APIKey: task.APIKey, Channels: task.Channels} + return s.takeCall(ringing{task: task, run: run, delivery: delivery, writer: writer, line: number, agentID: found.Spec().AgentID}) +} + +// takeCall is call with a call of its own taken on its run, as deliverByPhone takes one before +// it rings: the run must have none taken. +func (s *TelnyxUnpaidSuite) takeCall(call ringing) ringing { + call.spec = callSpec(s.config, call.delivery, call.agentID, phone.Placed{SessionID: s.utils.uuid()}, call.line, call.writer) + took, _, err := s.store.ScheduledTaskRuns.TakeCall(context.Background(), call.task.CustomerID, call.run.ID, call.spec.ID) + s.Require().NoError(err) + s.Require().True(took, "the call is taken on the run before it is placed") + call.edge = newRingingEdge() + call.spec.Edge = call.edge + // The suite's sessions have no telephony to press digits or transfer with, which is all the + // number is for once the call is placed. + call.spec.Phone = nil + return call +} + +// dial has the router carry the task out on call, as deliverByPhone does once the vendor placed it. +func (s *TelnyxUnpaidSuite) dial(call ringing) ringing { + done := make(chan callOutcome, 1) + call.done = done + go func() { + deliveredTo, sessionID, err := s.router.carryOutOnCall(scheduledOwnerContext(context.Background(), call.delivery), call.delivery, call.spec) + done <- callOutcome{deliveredTo: deliveredTo, sessionID: sessionID, err: err} + }() + return call +} + +// ring waits for the session of a dialled call to open, and watches it for the agent answering. +func (s *TelnyxUnpaidSuite) ring(call ringing) ringing { + s.Require().Eventually(func() bool { + _, live := s.router.sessions.Get(call.spec.ID, session.OwnerOf(call.spec)) + return live + }, deliveryWait, 20*time.Millisecond, "the call's session never opened") + held, _ := s.router.sessions.Get(call.spec.ID, session.OwnerOf(call.spec)) + events, detach := held.Watch() + s.T().Cleanup(detach) + answered := make(chan struct{}) + go func() { + said := false + for event := range events { + if _, ok := event.(agent.Responded); ok && !said { + said = true + close(answered) + } + } + }() + call.answered = answered + return call +} + +// letGo is what carrying the task out on call came to, once the call is let go. +func (s *TelnyxUnpaidSuite) letGo(call ringing) callOutcome { + select { + case outcome := <-call.done: + return outcome + case <-time.After(deliveryWait): + s.FailNow("the call was never let go") + return callOutcome{} + } +} + +// callTurn is how the task's turn on call stands, as the call's session holds it. +func (s *TelnyxUnpaidSuite) callTurn(call ringing) string { + return s.callTurnUnder(call, call.delivery.CommandID+"_call") +} + +// callTurnUnder is how the turn under id on call stands, as the call's session holds it. +func (s *TelnyxUnpaidSuite) callTurnUnder(call ringing, id string) string { + held, live := s.router.sessions.Get(call.spec.ID, session.OwnerOf(call.spec)) + if !live { + return "" + } + state, _, _ := held.FollowUpReply(id) + return state +} + +// hangUp has the user hang up on call. +func (s *TelnyxUnpaidSuite) hangUp(call ringing) { + _, err := s.router.sessions.Close(call.spec.ID, session.OwnerOf(call.spec)) + s.Require().NoError(err) +} + +// A phone task whose call was answered, and whose turn on it the model refuses because the credit +// ran out after the call was placed, said nothing to the user: the agent hangs up, the attempt +// fails under the refusal's code and is not tried again, and the run keeps that code for a worker +// that takes it over (AI-3597). +func (s *TelnyxUnpaidSuite) TestACallWhoseTurnIsRefusedForMoneyFailsUnderTheMoney() { + call := s.ringingOn("noted/noted-model") + s.usage.Credit(s.T(), s.RouterSuite.app.organization.ID, -10_000_000) + s.refusedForMoney(call.writer) + + call.edge.pickUp(call.writer) + outcome := s.letGo(call) + + var failure *scheduling.Failure + s.Require().ErrorAs(outcome.err, &failure) + s.Equal(codeInsufficientCredits, failure.Reason) + s.True(failure.Final, "spent credit outlasts every retry of the run") + s.True(refusedTurn(outcome.err), "the walk over the channels ends at the call") + s.Empty(outcome.deliveredTo) + _, live := s.router.sessions.Get(call.spec.ID, session.OwnerOf(call.spec)) + s.False(live, "the agent hung up") + kept, err := s.store.ScheduledTaskRuns.Get(context.Background(), s.customerID(), call.task.ID, call.run.ID) + s.Require().NoError(err) + s.Require().NotNil(kept.Error) + s.Equal(codeInsufficientCredits, *kept.Error, "a worker taking the run over finds how the call went") + s.Equal(call.spec.ID, kept.SessionID, "the user is rung once") +} + +// A phone task whose answered call's turn is refused because the money cannot be checked is +// not tried again: the check would pass again on its own, but a retry would ring the user a second +// time. The attempt fails final under the same code, after one ring, and the call stays taken on +// the run (AI-3597). +func (s *TelnyxUnpaidSuite) TestACallWhoseTurnIsRefusedWhileMoneyCannotBeCheckedFailsFinalAfterOneRing() { + call := s.ringingOn("noted/noted-model") + s.uncheckable(call.writer) + + call.edge.pickUp(call.writer) + outcome := s.letGo(call) + + var failure *scheduling.Failure + s.Require().ErrorAs(outcome.err, &failure) + s.Equal(codeSpendCheckUnavailable, failure.Reason) + s.True(failure.Final, "a second ring is not worth a check that passes again") + s.True(refusedTurn(outcome.err), "the walk over the channels ends at the call") + s.Empty(outcome.deliveredTo) + s.False(s.rungAgain(call), "the user is rung once") + kept, err := s.store.ScheduledTaskRuns.Get(context.Background(), s.customerID(), call.task.ID, call.run.ID) + s.Require().NoError(err) + s.Equal(call.spec.ID, kept.SessionID, "the call is not given back") + s.Require().NotNil(kept.Error) + s.Equal(codeSpendCheckUnavailable, *kept.Error, "a worker taking the run over finds how the call went") +} + +// A phone task whose call's turn is refused for money is rung once whatever reason the attempts +// before it failed under: an attempt that failed before it rang, such as the user being on a call, +// leaves the next attempt's earlier reason something else than money (AI-3597 R2.1). +func (s *TelnyxUnpaidSuite) TestACallWhoseTurnIsRefusedIsRungOnceWhateverTheAttemptsBetweenFailedUnder() { + call := s.callOn("noted/noted-model") + call.delivery.Earlier = "on_a_call" + call = s.ring(s.dial(call)) + s.uncheckable(call.writer) + + call.edge.pickUp(call.writer) + outcome := s.letGo(call) + + var failure *scheduling.Failure + s.Require().ErrorAs(outcome.err, &failure) + s.Equal(codeSpendCheckUnavailable, failure.Reason) + s.True(failure.Final, "a retry would ring the user again") + s.True(refusedTurn(outcome.err)) + s.False(s.rungAgain(call), "the user is rung once") +} + +// A phone task on the channels text, then call, whose text failed first for another reason than +// money, has that reason as the earlier one of every attempt (deliverChain records the first +// channel's). The call refused for money while it cannot be checked is rung once all the same +// (AI-3597 R2.1). +func (s *TelnyxUnpaidSuite) TestACallWhoseSessionCannotOpenIsRungOnceWhateverTheFirstChannelFailedUnder() { + call := s.callOn("noted/noted-model") + s.uncheckable(call.writer) + call.delivery.Earlier = "unreachable" + + outcome := s.letGo(s.dial(call)) + + var failure *scheduling.Failure + s.Require().ErrorAs(outcome.err, &failure) + s.Equal(codeSpendCheckUnavailable, failure.Reason) + s.True(failure.Final) + s.False(s.rungAgain(call), "the user is rung once") +} + +// rungAgain is whether the run lets another attempt take a call after call failed: the store hands +// one out only when the run has none taken. +func (s *TelnyxUnpaidSuite) rungAgain(call ringing) bool { + took, _, err := s.store.ScheduledTaskRuns.TakeCall(context.Background(), call.task.CustomerID, call.run.ID, s.utils.uuid()) + s.Require().NoError(err) + return took +} + +// uncheckable takes down the Redis the router shares its holds through, and waits until the gate +// refuses a text to person because the money cannot be checked. +func (s *TelnyxUnpaidSuite) uncheckable(person string) { + s.sharing.stop() + s.Require().Eventually(func() bool { + s.serverClient.call(http.MethodPost, "/v1/search", SearchRequest{Query: "again"}) + return policy.Transient(s.gate.Allow(context.Background(), s.customerID(), dlc.SMS, person)) + }, 10*time.Second, 20*time.Millisecond, "refused once a hold waited unshared") +} + +// A phone task whose call's session cannot open, the credit being spent after the call was placed, +// fails under the refusal's code, final, and the run keeps that code for a worker that takes it +// over (AI-3597). +func (s *TelnyxUnpaidSuite) TestACallWhoseSessionCannotOpenForMoneyFailsUnderTheMoney() { + call := s.callOn("noted/noted-model") + s.usage.Credit(s.T(), s.RouterSuite.app.organization.ID, -10_000_000) + s.refusedForMoney(call.writer) + + outcome := s.letGo(s.dial(call)) + + var failure *scheduling.Failure + s.Require().ErrorAs(outcome.err, &failure) + s.Equal(codeInsufficientCredits, failure.Reason) + s.True(failure.Final, "spent credit outlasts every retry of the run") + kept, err := s.store.ScheduledTaskRuns.Get(context.Background(), s.customerID(), call.task.ID, call.run.ID) + s.Require().NoError(err) + s.Equal(call.spec.ID, kept.SessionID, "the user is rung once") + s.Require().NotNil(kept.Error) + s.Equal(codeInsufficientCredits, *kept.Error, "a worker taking the run over finds how the call went") +} + +// A phone task whose call's session cannot open because the money cannot be checked fails under +// the same code, final, with the call kept on the run: the user was rung, and is rung once +// (AI-3597). +func (s *TelnyxUnpaidSuite) TestACallWhoseSessionCannotOpenWhileMoneyCannotBeCheckedFailsFinal() { + call := s.callOn("noted/noted-model") + s.uncheckable(call.writer) + + outcome := s.letGo(s.dial(call)) + + var failure *scheduling.Failure + s.Require().ErrorAs(outcome.err, &failure) + s.Equal(codeSpendCheckUnavailable, failure.Reason) + s.True(failure.Final, "a retry would ring the user again") + kept, err := s.store.ScheduledTaskRuns.Get(context.Background(), s.customerID(), call.task.ID, call.run.ID) + s.Require().NoError(err) + s.Equal(call.spec.ID, kept.SessionID, "the call is not given back") + s.Require().NotNil(kept.Error) + s.Equal(codeSpendCheckUnavailable, *kept.Error, "a worker taking the run over finds how the call went") +} + +// A phone task whose call's turn the model answers is delivered by phone once the user hangs up, +// as it always was (control: the same on the base). +func (s *TelnyxUnpaidSuite) TestACallWhoseTurnIsAnsweredIsDelivered() { + call := s.ringingOn("noted/noted-model") + + call.edge.pickUp(call.writer) + s.answeredOn(call) + s.held(call) + s.hangUp(call) + outcome := s.letGo(call) + + s.Require().NoError(outcome.err) + s.Equal(store.ScheduledTaskDeliveredPhone, outcome.deliveredTo) +} + +// A phone task whose call's turn fails for a reason that is not money, such as the model's +// provider being down, holds the call until the user hangs up and is delivered by phone, as it +// always was (control: the same on the base). Only a refusal for money fails the run. +func (s *TelnyxUnpaidSuite) TestACallWhoseTurnFailsNotForMoneyIsDelivered() { + call := s.ringingOn("failing/failing-model") + + call.edge.pickUp(call.writer) + s.Require().Eventually(func() bool { return s.callTurn(call) == "failed" }, + deliveryWait, 20*time.Millisecond, "the task's turn never failed") + s.held(call) + s.hangUp(call) + outcome := s.letGo(call) + + s.Require().NoError(outcome.err) + s.Equal(store.ScheduledTaskDeliveredPhone, outcome.deliveredTo) +} + +// A phone task whose call's turn the model answers, and whose later turn on the call the model +// refuses because the credit ran out meanwhile, said the task: the call is held until the user +// hangs up and is delivered by phone. Only a refusal before the agent answered fails the run. +func (s *TelnyxUnpaidSuite) TestACallWhoseLaterTurnIsRefusedForMoneyIsDelivered() { + call := s.ringingOn("noted/noted-model") + call.edge.pickUp(call.writer) + s.answeredOn(call) + s.usage.Credit(s.T(), s.RouterSuite.app.organization.ID, -10_000_000) + s.refusedForMoney(call.writer) + refusal := s.gate.Allow(context.Background(), s.customerID(), dlc.SMS, call.writer) + s.Require().NotNil(turnRefusal(agent.Error{Context: "llm", Err: refusal}), "the gate's refusal is one for money: %v", refusal) + held, live := s.router.sessions.Get(call.spec.ID, session.OwnerOf(call.spec)) + s.Require().True(live) + + // The task's turn still holds the call's reply, so the later turn's refused model call is + // reported as the agent reports one (agent.Agent.fail), with the refusal the spent credit gives. + held.Report(refusal, "llm") + s.held(call) + s.hangUp(call) + outcome := s.letGo(call) + + s.Require().NoError(outcome.err) + s.Equal(store.ScheduledTaskDeliveredPhone, outcome.deliveredTo) +} + +// answeredOn waits for the agent to answer on call. +func (s *TelnyxUnpaidSuite) answeredOn(call ringing) { + select { + case <-call.answered: + case <-time.After(deliveryWait): + s.FailNow("the agent never answered on the call") + } +} + +// held checks that call is still held, not let go, for settleFor. +func (s *TelnyxUnpaidSuite) held(call ringing) { + s.Never(func() bool { return len(call.done) > 0 }, settleFor, 20*time.Millisecond, "the call was let go before the user hung up") +} diff --git a/acceleration/internal/scheduling/AGENTS.md b/acceleration/internal/scheduling/AGENTS.md index 3b3df3758c..cf98089b16 100644 --- a/acceleration/internal/scheduling/AGENTS.md +++ b/acceleration/internal/scheduling/AGENTS.md @@ -172,7 +172,9 @@ Each rule names the test that fails when it breaks. Suites: `SchedulerSuite` `TestScheduledTasksSuite/TestATaskWithNoOccurrenceLeftIsRefusedBeforeItsLimitOrItsConfigIsAsked`, `TestScheduledTasksSuite/TestTheAgentCannotResumeAFailedOneShotPastItsTime`. - **A call rings once, on an SMS number, never more than 15 min late, and only with ring and - call limit left in the occurrence (S5).** Too late is `missed` without a call; nobody + call limit left in the occurrence (S5).** A placed call is rung once, whatever refuses it: a + refusal while the money could not be checked, of its session or its answered turn, fails the + run final under the money code (`callEnded`, AI-3597). Too late is `missed` without a call; nobody answering is `not_answered`, final, kept on the run for a worker that takes it over and for a retry, whatever would stop that retry's call. A call placed whose end the run does not record (delivered, or cut off with the worker) is `already_called`, and no channel after @@ -195,7 +197,9 @@ Each rule names the test that fails when it breaks. Suites: `SchedulerSuite` `TestStoreSuite/TestARunsCallKeepsTheReasonItEndedUnderForTheWorkerTakingItOver`, `TestScheduledTasksSuite/TestARetryShortOfTimeAfterAnUnansweredCallIsNotAnswered`, `TestScheduledTasksSuite/TestARetryAQuarterHourLateAfterAnUnansweredCallIsNotAnswered`, - `TestScheduledTasksSuite/TestARetryWhileTheUserIsOnACallAfterAnUnansweredCallIsNotAnswered`. + `TestScheduledTasksSuite/TestARetryWhileTheUserIsOnACallAfterAnUnansweredCallIsNotAnswered`, + `TestTelnyxUnpaidSuite/TestACallWhoseSessionCannotOpenWhileMoneyCannotBeCheckedFailsFinal`, + `TestTelnyxUnpaidSuite/TestACallWhoseTurnIsRefusedWhileMoneyCannotBeCheckedFailsFinalAfterOneRing`. - **A reply that was cancelled or interrupted runs again once; a finished one is read back (AI-1558).** `replyCommand` reads the follow-up's state in the conversation (rebuilt from Stream after a restart), not the run's `attempts`, which also count attempts that never diff --git a/acceleration/internal/store/scheduled_task_run.go b/acceleration/internal/store/scheduled_task_run.go index 3b83cc18a0..8bf8566c8d 100644 --- a/acceleration/internal/store/scheduled_task_run.go +++ b/acceleration/internal/store/scheduled_task_run.go @@ -185,7 +185,8 @@ func (r *ScheduledTaskRuns) SetCallReason(ctx context.Context, customerID, runID } // ReleaseCall gives back a call TakeCall -// took and could not place, so a later attempt may ring. +// took and could not place, so a later attempt may ring. A placed call is +// never given back: it is rung once (callEnded in internal/api). func (r *ScheduledTaskRuns) ReleaseCall(ctx context.Context, customerID, runID, sessionID string) error { _, err := r.store.global.NewUpdate().Model((*ScheduledTaskRun)(nil)). Set("session_id = ''").