Relates to CODAGT-1330 `create_workspace`, `start_workspace` and `stop_workspace` read a fair bit from the database whilst they wait on a build: the chat workspace TTL setting, the workspace's agents, the agent's lifecycle state, and the chat row once the build is done. When one of those reads failed, we'd log it (or just ignore it) and carry on as if it hadn't, e.g. falling back to the template's TTL or leaving out the agent status, and the tool still reported success. A failed write of the new build ID to the chat binding was handled the same way. To fix, we'll return a tool error for those database errors, so the model knows the call failed and can retry. `start_workspace` and `stop_workspace` now also re-bind the chat when its build is stale, so a retried call repairs a binding write that failed. An invalid TTL setting, a workspace with no build yet, and agent selection errors all behave like they do today. A tool error doesn't stop the build. The tools only watch the build and the agent, so the build, the startup scripts and the turn all carry on. If the model calls the tool again, `create_workspace` finds the workspace through the chat binding, which #30663 commits with the workspace, and waits on it again rather than creating a second one. It only creates a replacement if the agent has since disconnected or timed out, like it does today. `start_workspace` just waits on the latest build again, and the other workspace tools find and dial the agent themselves. This follows on from #30663.
194 lines
5.9 KiB
Go
194 lines
5.9 KiB
Go
package chattool
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"unicode/utf8"
|
|
|
|
"charm.land/fantasy"
|
|
"github.com/google/uuid"
|
|
"golang.org/x/xerrors"
|
|
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
)
|
|
|
|
const templateNotAvailableMessage = "template not available for chat workspaces; use list_templates to find allowed templates"
|
|
|
|
// WorkspaceUnavailableHint follows errors that keep a tool from loading the
|
|
// chat's workspace so the model recovers instead of concluding it is blocked.
|
|
const WorkspaceUnavailableHint = "The workspace is probably gone; use the create_workspace tool to make a new one"
|
|
|
|
func workspaceLoadErrorResponse(err error) fantasy.ToolResponse {
|
|
return fantasy.NewTextErrorResponse(
|
|
xerrors.Errorf("load workspace: %w. %s", err, WorkspaceUnavailableHint).Error(),
|
|
)
|
|
}
|
|
|
|
// externalAuthRequiredMessage tells the model how to unblock a request that
|
|
// failed because the workspace owner has not authenticated with a required
|
|
// external auth provider. The login links are in the response detail.
|
|
const externalAuthRequiredMessage = "the workspace owner must authenticate with the listed external auth providers before this template can be used. " +
|
|
"Show the user the authentication link(s) from detail so they can open them, then retry create_workspace once they confirm they have authenticated"
|
|
|
|
// hasExternalAuthValidation reports whether any validation error identifies a
|
|
// missing external auth provider.
|
|
func hasExternalAuthValidation(validations []codersdk.ValidationError) bool {
|
|
for _, validation := range validations {
|
|
if validation.Field == "external_auth" {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func marshalToolResponse(result any) fantasy.ToolResponse {
|
|
data, err := json.Marshal(result)
|
|
if err != nil {
|
|
return fantasy.NewTextResponse("{}")
|
|
}
|
|
return fantasy.NewTextResponse(string(data))
|
|
}
|
|
|
|
// toolResponse builds a fantasy.ToolResponse from a JSON-serializable
|
|
// result map. The map constraint ensures all tool results serialize
|
|
// to JSON objects so the frontend can safely parse them.
|
|
func toolResponse(result map[string]any) fantasy.ToolResponse {
|
|
return marshalToolResponse(result)
|
|
}
|
|
|
|
// buildToolResponse marshals a buildErrorResult into a tool response.
|
|
// Separate from toolResponse to keep the map[string]any constraint
|
|
// on the general helper while allowing typed error structs.
|
|
func buildToolResponse(r buildErrorResult) fantasy.ToolResponse {
|
|
return marshalToolResponse(r)
|
|
}
|
|
|
|
// responseErrorResult converts a codersdk.Response into a structured
|
|
// tool result. We return these via toolResponse rather than
|
|
// NewTextErrorResponse because the fantasy/chatprompt pipeline flattens
|
|
// IsError content into a single string and drops validation details.
|
|
func responseErrorResult(resp codersdk.Response) map[string]any {
|
|
message := resp.Message
|
|
if message == "" {
|
|
message = "request failed"
|
|
}
|
|
|
|
result := map[string]any{
|
|
"error": message,
|
|
}
|
|
if resp.Detail != "" {
|
|
result["detail"] = resp.Detail
|
|
}
|
|
if len(resp.Validations) > 0 {
|
|
result["validations"] = resp.Validations
|
|
}
|
|
if hasExternalAuthValidation(resp.Validations) {
|
|
result["action_required"] = externalAuthRequiredMessage
|
|
}
|
|
return result
|
|
}
|
|
|
|
func latestWorkspaceBuildAndJob(
|
|
ctx context.Context,
|
|
db database.Store,
|
|
workspaceID uuid.UUID,
|
|
) (database.WorkspaceBuild, database.ProvisionerJob, error) {
|
|
build, err := db.GetLatestWorkspaceBuildByWorkspaceID(ctx, workspaceID)
|
|
if err != nil {
|
|
return database.WorkspaceBuild{}, database.ProvisionerJob{}, xerrors.Errorf("get latest build: %w", err)
|
|
}
|
|
|
|
job, err := db.GetProvisionerJobByID(ctx, build.JobID)
|
|
if err != nil {
|
|
return database.WorkspaceBuild{}, database.ProvisionerJob{}, xerrors.Errorf("get provisioner job: %w", err)
|
|
}
|
|
return build, job, nil
|
|
}
|
|
|
|
func publishBuildBinding(
|
|
ctx context.Context,
|
|
db database.Store,
|
|
chatID uuid.UUID,
|
|
workspaceID uuid.UUID,
|
|
buildID uuid.UUID,
|
|
onChatUpdated func(database.Chat),
|
|
) error {
|
|
updatedChat, err := db.UpdateChatWorkspaceBinding(ctx, database.UpdateChatWorkspaceBindingParams{
|
|
ID: chatID,
|
|
WorkspaceID: uuid.NullUUID{UUID: workspaceID, Valid: true},
|
|
BuildID: uuid.NullUUID{
|
|
UUID: buildID,
|
|
Valid: buildID != uuid.Nil,
|
|
},
|
|
AgentID: uuid.NullUUID{},
|
|
})
|
|
if err != nil {
|
|
return xerrors.Errorf("bind chat to build: %w", err)
|
|
}
|
|
if onChatUpdated != nil {
|
|
onChatUpdated(updatedChat)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func provisionerJobTerminal(status database.ProvisionerJobStatus) bool {
|
|
switch status {
|
|
case database.ProvisionerJobStatusSucceeded,
|
|
database.ProvisionerJobStatusFailed,
|
|
database.ProvisionerJobStatusCanceled:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func truncateRunes(value string, maxLen int) string {
|
|
if maxLen <= 0 || value == "" {
|
|
return ""
|
|
}
|
|
if utf8.RuneCountInString(value) <= maxLen {
|
|
return value
|
|
}
|
|
|
|
runes := []rune(value)
|
|
if maxLen > len(runes) {
|
|
maxLen = len(runes)
|
|
}
|
|
return string(runes[:maxLen])
|
|
}
|
|
|
|
// buildErrorResult is a structured error response that preserves
|
|
// the build ID alongside the error message. This lets the frontend
|
|
// keep showing build logs when a build fails instead of losing
|
|
// them on the error transition.
|
|
type buildErrorResult struct {
|
|
Error string `json:"error"`
|
|
BuildID string `json:"build_id,omitempty"`
|
|
}
|
|
|
|
func newBuildError(msg string, buildID uuid.UUID) buildErrorResult {
|
|
r := buildErrorResult{Error: msg}
|
|
if buildID != uuid.Nil {
|
|
r.BuildID = buildID.String()
|
|
}
|
|
return r
|
|
}
|
|
|
|
// setBuildID adds the build_id field to a tool response map when
|
|
// the build ID is known (non-zero).
|
|
func setBuildID(result map[string]any, buildID uuid.UUID) {
|
|
if buildID != uuid.Nil {
|
|
result["build_id"] = buildID.String()
|
|
}
|
|
}
|
|
|
|
// setNoBuild marks the response with no_build: true when no build
|
|
// was triggered. The frontend uses this flag to suppress the
|
|
// build-log section for already-running workspaces.
|
|
func setNoBuild(result map[string]any, buildID uuid.UUID) {
|
|
if buildID == uuid.Nil {
|
|
result["no_build"] = true
|
|
}
|
|
}
|