Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

feat(voice): let Live post Task files from the Computer's playground

LeoXinge6b18e845bf0
diff --git a/apps/computer/local-daemon/internal/daemon/computer_tools.go b/apps/computer/local-daemon/internal/daemon/computer_tools.go
index 40e783c5..5ceb085c 100644
--- a/apps/computer/local-daemon/internal/daemon/computer_tools.go
+++ b/apps/computer/local-daemon/internal/daemon/computer_tools.go
@@ -6,7 +6,6 @@ import (
"errors"
"time"
- lingercontext "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/context"
"github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/localtools"
"github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/transport"
"github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/protocol"
@@ -19,12 +18,11 @@ type liveBrowserTools interface {
func (d *Daemon) handleComputerTool(ctx context.Context, stream transport.Stream, command protocol.Command) error {
var request struct {
- ToolSessionID string `json:"tool_session_id"`
- Server string `json:"server"`
- Name string `json:"tool_name"`
- Arguments json.RawMessage `json:"arguments"`
- Scope *lingercontext.SharedTaskScope `json:"task_scope"`
- DeadlineMS int64 `json:"deadline_ms"`
+ ToolSessionID string `json:"tool_session_id"`
+ Server string `json:"server"`
+ Name string `json:"tool_name"`
+ Arguments json.RawMessage `json:"arguments"`
+ DeadlineMS int64 `json:"deadline_ms"`
}
if json.Unmarshal(command.Payload, &request) != nil || request.DeadlineMS < 1000 || request.DeadlineMS > 120000 {
return errors.New("invalid Computer tool command")
@@ -69,10 +67,8 @@ func (d *Daemon) handleComputerTool(ctx context.Context, stream transport.Stream
result, err = liveBrowserResult(data)
}
}
- case "task_files":
- if request.Scope != nil && d.contextViews != nil && request.Scope.TenantID == command.TenantID && request.Scope.AgentID == command.AgentID {
- result, err = d.contextViews.ReadLiveTaskFiles(callCtx, *request.Scope, request.Name, request.Arguments)
- }
+ case "playground":
+ result, err = d.callPlayground(callCtx, command.TenantID, command.AgentID, request.Name, request.Arguments)
}
if failure := localtools.BrowserCallNotRun(err); failure != "" {
// Nothing ran: the owner's Chrome is not connected or is busy.
diff --git a/apps/computer/local-daemon/internal/daemon/playground_tools.go b/apps/computer/local-daemon/internal/daemon/playground_tools.go
new file mode 100644
index 00000000..dec9d9f4
--- /dev/null
+++ b/apps/computer/local-daemon/internal/daemon/playground_tools.go
@@ -0,0 +1,295 @@
+package daemon
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "mime/multipart"
+ "net/http"
+ "os"
+ "path"
+ "strconv"
+ "strings"
+
+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/clicredential"
+ lingercontext "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/context"
+)
+
+const (
+ // The Agent message commit route's limits: per file and per message.
+ maxCardFileBytes = 50 << 20
+ maxCardTotalBytes = 512 << 20
+ maxCardFiles = 5
+)
+
+// playgroundCardClient posts cards to TeamHub; the Computer tool's deadline
+// bounds each request, and a redirect is never followed with the credential.
+var playgroundCardClient = &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error {
+ return http.ErrUseLastResponse
+}}
+
+// playgroundFailure is a result TeamHub tells the live model as an error code.
+type playgroundFailure struct{ code, detail string }
+
+func (f *playgroundFailure) Error() string { return f.code + ": " + f.detail }
+
+type playgroundRequest struct {
+ Folder lingercontext.PlaygroundFolder `json:"folder"`
+ Path string `json:"path"`
+ Offset int64 `json:"offset"`
+ Limit int64 `json:"limit"`
+}
+
+type playgroundCardFile struct {
+ Folder lingercontext.PlaygroundFolder `json:"folder"`
+ Path string `json:"path"`
+ RepresentationFormat string `json:"representation_format"`
+ MediaType string `json:"media_type"`
+}
+
+type playgroundCard struct {
+ OperationID string `json:"operation_id"`
+ InboxID string `json:"inbox_id"`
+ Title string `json:"title"`
+ Content string `json:"content"`
+ Files []playgroundCardFile `json:"files"`
+}
+
+// callPlayground runs one live voice file action for the command's Agent.
+func (d *Daemon) callPlayground(ctx context.Context, tenantID, agentID, name string, arguments json.RawMessage) (map[string]any, error) {
+ if d.contextViews == nil {
+ return map[string]any{"status": "unavailable"}, nil
+ }
+ var (
+ result map[string]any
+ err error
+ )
+ switch name {
+ case "list", "read":
+ var request playgroundRequest
+ if !decodes(arguments, &request) {
+ return map[string]any{"status": "invalid_file_path"}, nil
+ }
+ if name == "list" {
+ result, err = d.contextViews.ListPlayground(ctx, tenantID, agentID, request.Folder, request.Path)
+ } else {
+ result, err = d.contextViews.ReadPlayground(ctx, tenantID, agentID, request.Folder, request.Path, request.Offset, request.Limit)
+ }
+ case "send_card":
+ var card playgroundCard
+ if !decodes(arguments, &card) {
+ return map[string]any{"status": "invalid_card"}, nil
+ }
+ result, err = d.sendPlaygroundCard(ctx, tenantID, agentID, card)
+ default:
+ return map[string]any{"status": "unavailable"}, nil
+ }
+ var failure *playgroundFailure
+ switch {
+ case err == nil:
+ return result, nil
+ case errors.As(err, &failure):
+ return map[string]any{"status": failure.code, "detail": failure.detail}, nil
+ case errors.Is(err, lingercontext.ErrPlaygroundFolder), errors.Is(err, lingercontext.ErrSharedTaskPathConflict):
+ return map[string]any{"status": "not_allowed"}, nil
+ case errors.Is(err, lingercontext.ErrPlaygroundPath):
+ return map[string]any{"status": "invalid_file_path"}, nil
+ case errors.Is(err, fs.ErrNotExist):
+ return map[string]any{"status": "file_not_found"}, nil
+ case errors.Is(err, lingercontext.ErrPlaygroundNotFolder):
+ return map[string]any{"status": "not_a_folder"}, nil
+ case errors.Is(err, lingercontext.ErrPlaygroundNotFile):
+ return map[string]any{"status": "not_a_file"}, nil
+ }
+ return nil, err
+}
+
+// decodes reports whether arguments decode into target; a malformed call is
+// told to the live model as a status, not failed.
+func decodes(arguments json.RawMessage, target any) bool {
+ return json.Unmarshal(arguments, target) == nil
+}
+
+type openedCardFile struct {
+ file *os.File
+ upload map[string]any
+ size int64
+ uploadID string
+}
+
+// sendPlaygroundCard reads the card's files where the Agent wrote them and
+// commits the card through the Agent API, the request `teamhub message card
+// --attach` sends. The operation ID makes a repeated call the same message.
+func (d *Daemon) sendPlaygroundCard(ctx context.Context, tenantID, agentID string, card playgroundCard) (map[string]any, error) {
+ title := strings.TrimSpace(card.Title)
+ if card.OperationID == "" || !strings.HasPrefix(card.InboxID, "room:") || title == "" || title != card.Title ||
+ len([]rune(title)) > 120 || strings.ContainsAny(title, "\r\n") || strings.TrimSpace(card.Content) == "" || len(card.Files) > maxCardFiles {
+ return nil, &playgroundFailure{"invalid_card", "A card needs a one-line title, content and at most 5 files."}
+ }
+ files := make([]openedCardFile, 0, len(card.Files))
+ defer func() {
+ for _, opened := range files {
+ _ = opened.file.Close()
+ }
+ }()
+ var total int64
+ for index, requested := range card.Files {
+ file, info, err := d.contextViews.OpenPlaygroundFile(ctx, tenantID, agentID, requested.Folder, requested.Path)
+ if err != nil {
+ return nil, err
+ }
+ opened, err := prepareCardFile(file, info.Size(), index, requested)
+ files = append(files, opened)
+ if err != nil {
+ return nil, err
+ }
+ if total += info.Size(); total > maxCardTotalBytes {
+ return nil, &playgroundFailure{"files_too_large", "The files are over 512 MiB together."}
+ }
+ }
+ profile, token, err := d.agentCLICredential(tenantID, agentID)
+ if err != nil {
+ return nil, err
+ }
+ return commitCard(ctx, profile, token, card, files)
+}
+
+// prepareCardFile hashes one opened file for its upload entry.
+func prepareCardFile(file *os.File, size int64, index int, requested playgroundCardFile) (openedCardFile, error) {
+ opened := openedCardFile{file: file, size: size, uploadID: "upload_" + strconv.Itoa(index)}
+ if size > maxCardFileBytes {
+ return opened, &playgroundFailure{"file_too_large", path.Base(requested.Path) + " is over 50 MiB."}
+ }
+ hash := sha256.New()
+ if _, err := io.Copy(hash, file); err != nil {
+ return opened, err
+ }
+ if _, err := file.Seek(0, io.SeekStart); err != nil {
+ return opened, err
+ }
+ opened.upload = map[string]any{
+ "upload_id": opened.uploadID, "filename": path.Base(requested.Path),
+ "representation_format": requested.RepresentationFormat, "media_type": requested.MediaType,
+ "size_bytes": size, "sha256": hex.EncodeToString(hash.Sum(nil)),
+ }
+ return opened, nil
+}
+
+// commitCard posts the card and its prepared files as the Agent.
+func commitCard(ctx context.Context, profile clicredential.Profile, token string, card playgroundCard, files []openedCardFile) (map[string]any, error) {
+ segments := []map[string]any{{"type": "text", "content": card.Content}}
+ uploads := make([]map[string]any, 0, len(files))
+ for _, opened := range files {
+ segments = append(segments, map[string]any{"type": "document", "upload_id": opened.uploadID})
+ uploads = append(uploads, opened.upload)
+ }
+ invocation := sha256.Sum256([]byte(card.OperationID))
+ metadata, err := json.Marshal(map[string]any{
+ "invocation_id": "agent-invocation-sha256:" + hex.EncodeToString(invocation[:]),
+ "inbox_id": card.InboxID, "card_title": card.Title, "segments": segments, "uploads": uploads,
+ })
+ if err != nil {
+ return nil, err
+ }
+ body, writer := io.Pipe()
+ form := multipart.NewWriter(writer)
+ go func() {
+ _ = writer.CloseWithError(writeCardForm(form, metadata, files))
+ }()
+ defer body.Close()
+ request, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimSuffix(profile.URL, "/")+"/api/agent/v1/messages/commit", body)
+ if err != nil {
+ return nil, err
+ }
+ request.Header.Set("Authorization", "Bearer "+token)
+ request.Header.Set("Content-Type", form.FormDataContentType())
+ request.Header.Set("X-TeamHub-Expected-Tenant-Id", profile.TenantID)
+ request.Header.Set("X-TeamHub-Expected-Agent-Id", profile.AgentID)
+ request.Header.Set("X-TeamHub-Operation-Id", card.OperationID)
+ response, err := playgroundCardClient.Do(request)
+ if err != nil {
+ // The request may have reached TeamHub; only the same operation may retry.
+ return nil, &playgroundFailure{"outcome_unknown", "The card may have been posted; check the chat before trying again."}
+ }
+ defer response.Body.Close()
+ return cardCommitResult(response)
+}
+
+func writeCardForm(form *multipart.Writer, metadata []byte, files []openedCardFile) error {
+ if err := form.WriteField("metadata", string(metadata)); err != nil {
+ return err
+ }
+ for _, opened := range files {
+ part, err := form.CreateFormFile("file", opened.uploadID)
+ if err != nil {
+ return err
+ }
+ // A file that grew since it was hashed fails TeamHub's size check.
+ if _, err := io.Copy(part, io.LimitReader(opened.file, opened.size+1)); err != nil {
+ return err
+ }
+ }
+ return form.Close()
+}
+
+// cardCommitResult is the posted card's message and the Documents its files
+// became, in file order.
+func cardCommitResult(response *http.Response) (map[string]any, error) {
+ data, err := io.ReadAll(io.LimitReader(response.Body, 8<<20))
+ if err != nil {
+ return nil, &playgroundFailure{"outcome_unknown", "The card may have been posted; check the chat before trying again."}
+ }
+ if response.StatusCode != http.StatusOK {
+ var envelope struct {
+ Error struct {
+ Code string `json:"code"`
+ } `json:"error"`
+ }
+ _ = json.Unmarshal(data, &envelope)
+ return nil, &playgroundFailure{"upload_failed", strings.TrimSpace(fmt.Sprintf("TeamHub answered HTTP %d %s", response.StatusCode, envelope.Error.Code))}
+ }
+ var committed struct {
+ MessageID string `json:"message_id"`
+ Resources []struct {
+ Kind string `json:"kind"`
+ SegmentIndex int `json:"segment_index"`
+ DocumentID string `json:"document_id"`
+ Name string `json:"name"`
+ } `json:"resources"`
+ }
+ if err := json.Unmarshal(data, &committed); err != nil || committed.MessageID == "" {
+ return nil, &playgroundFailure{"outcome_unknown", "TeamHub's answer could not be read; check the chat before trying again."}
+ }
+ documents := make([]map[string]any, 0, len(committed.Resources))
+ for _, resource := range committed.Resources {
+ if resource.Kind == "document" {
+ documents = append(documents, map[string]any{"document_id": resource.DocumentID, "filename": resource.Name})
+ }
+ }
+ return map[string]any{"message_id": committed.MessageID, "documents": documents}, nil
+}
+
+// agentCLICredential is the TeamHub CLI profile and token the Agent Service
+// pushed to this Computer for the Agent.
+func (d *Daemon) agentCLICredential(tenantID, agentID string) (clicredential.Profile, string, error) {
+ if d.cliCredentials == nil {
+ return clicredential.Profile{}, "", &playgroundFailure{"agent_unavailable", "This Computer holds no TeamHub credential for the Agent."}
+ }
+ installation, err := d.cliCredentials.Lookup(tenantID, agentID)
+ if errors.Is(err, clicredential.ErrNotInstalled) {
+ return clicredential.Profile{}, "", &playgroundFailure{"agent_unavailable", "This Computer holds no TeamHub credential for the Agent."}
+ }
+ if err != nil {
+ return clicredential.Profile{}, "", err
+ }
+ token, err := os.ReadFile(installation.CredentialPath)
+ if err != nil {
+ return clicredential.Profile{}, "", err
+ }
+ return installation.Profile, strings.TrimSpace(string(token)), nil
+}
diff --git a/apps/computer/local-daemon/internal/daemon/playground_tools_test.go b/apps/computer/local-daemon/internal/daemon/playground_tools_test.go
new file mode 100644
index 00000000..796cb108
--- /dev/null
+++ b/apps/computer/local-daemon/internal/daemon/playground_tools_test.go
@@ -0,0 +1,133 @@
+package daemon
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/clicredential"
+)
+
+func openTestCardFile(t *testing.T, name string, content []byte, index int) openedCardFile {
+ t.Helper()
+ filename := filepath.Join(t.TempDir(), name)
+ if err := os.WriteFile(filename, content, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ file, err := os.Open(filename)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = file.Close() })
+ opened, err := prepareCardFile(file, int64(len(content)), index, playgroundCardFile{Path: "out/" + name, RepresentationFormat: "png", MediaType: "image/png"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return opened
+}
+
+func TestPlaygroundCardCommitsTheFilesAsTheAgent(t *testing.T) {
+ image := bytes.Repeat([]byte{0x89, 'P', 'N', 'G'}, 300_000)
+ var metadata map[string]any
+ parts := map[string][]byte{}
+ server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
+ if request.URL.Path != "/api/agent/v1/messages/commit" || request.Header.Get("Authorization") != "Bearer token-1" ||
+ request.Header.Get("X-TeamHub-Expected-Agent-Id") != "agent-1" || request.Header.Get("X-TeamHub-Operation-Id") != "voice-call-1" {
+ http.Error(writer, `{"error":{"code":"FORBIDDEN"}}`, http.StatusForbidden)
+ return
+ }
+ reader, err := request.MultipartReader()
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ for {
+ part, err := reader.NextPart()
+ if errors.Is(err, io.EOF) {
+ break
+ }
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ data, _ := io.ReadAll(part)
+ if part.FormName() == "metadata" {
+ _ = json.Unmarshal(data, &metadata)
+ continue
+ }
+ parts[part.FileName()] = data
+ }
+ _, _ = writer.Write([]byte(`{"accepted":true,"target":{"type":"room","id":"room-1"},"inbox_id":"room:room-1","message_id":"message-1","duplicate_request":false,"resources":[{"kind":"document","segment_index":1,"status":"published","document_id":"document-1","name":"cartoon.png"}]}`))
+ }))
+ defer server.Close()
+ card := playgroundCard{OperationID: "voice-call-1", InboxID: "room:room-1", Title: "Cartoon", Content: "The drawing is done."}
+ result, err := commitCard(t.Context(), clicredential.Profile{URL: server.URL, TenantID: "tenant-1", AgentID: "agent-1"}, "token-1", card,
+ []openedCardFile{openTestCardFile(t, "cartoon.png", image, 0)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ documents := result["documents"].([]map[string]any)
+ if result["message_id"] != "message-1" || len(documents) != 1 || documents[0]["document_id"] != "document-1" || documents[0]["filename"] != "cartoon.png" {
+ t.Fatalf("result=%v", result)
+ }
+ if !bytes.Equal(parts["upload_0"], image) {
+ t.Fatalf("uploaded %d bytes, want the whole %d byte file", len(parts["upload_0"]), len(image))
+ }
+ sum := sha256.Sum256(image)
+ invocation := sha256.Sum256([]byte("voice-call-1"))
+ uploads := metadata["uploads"].([]any)
+ upload := uploads[0].(map[string]any)
+ if metadata["invocation_id"] != "agent-invocation-sha256:"+hex.EncodeToString(invocation[:]) || metadata["inbox_id"] != "room:room-1" ||
+ metadata["card_title"] != "Cartoon" || upload["filename"] != "cartoon.png" || upload["sha256"] != hex.EncodeToString(sum[:]) ||
+ upload["size_bytes"] != float64(len(image)) || upload["media_type"] != "image/png" || upload["representation_format"] != "png" {
+ t.Fatalf("metadata=%v", metadata)
+ }
+ segments := metadata["segments"].([]any)
+ if len(segments) != 2 || segments[0].(map[string]any)["content"] != "The drawing is done." || segments[1].(map[string]any)["upload_id"] != "upload_0" {
+ t.Fatalf("segments=%v", segments)
+ }
+}
+
+func TestPlaygroundCardReportsARefusedCommit(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
+ _, _ = io.Copy(io.Discard, request.Body)
+ writer.WriteHeader(http.StatusForbidden)
+ _, _ = writer.Write([]byte(`{"error":{"code":"OPERATION_NOT_PERMITTED","message":"no","request_id":"r"}}`))
+ }))
+ defer server.Close()
+ card := playgroundCard{OperationID: "voice-call-2", InboxID: "room:room-1", Title: "Cartoon", Content: "Done."}
+ _, err := commitCard(t.Context(), clicredential.Profile{URL: server.URL, TenantID: "tenant-1", AgentID: "agent-1"}, "token-1", card,
+ []openedCardFile{openTestCardFile(t, "cartoon.png", []byte("png"), 0)})
+ var failure *playgroundFailure
+ if !errors.As(err, &failure) || failure.code != "upload_failed" || !strings.Contains(failure.detail, "403 OPERATION_NOT_PERMITTED") {
+ t.Fatalf("err=%v", err)
+ }
+}
+
+func TestPlaygroundCardRefusesAnInvalidCardOrMissingCredential(t *testing.T) {
+ daemon := &Daemon{}
+ for _, card := range []playgroundCard{
+ {OperationID: "op", InboxID: "room:room-1", Title: "Two\nlines", Content: "x"},
+ {OperationID: "op", InboxID: "task:task-1", Title: "Title", Content: "x"},
+ {OperationID: "op", InboxID: "room:room-1", Title: "Title", Content: " "},
+ {OperationID: "op", InboxID: "room:room-1", Title: "Title", Content: "x", Files: make([]playgroundCardFile, 6)},
+ } {
+ var failure *playgroundFailure
+ if _, err := daemon.sendPlaygroundCard(t.Context(), "tenant-1", "agent-1", card); !errors.As(err, &failure) || failure.code != "invalid_card" {
+ t.Fatalf("card %+v = %v", card, err)
+ }
+ }
+ var failure *playgroundFailure
+ if _, _, err := daemon.agentCLICredential("tenant-1", "agent-1"); !errors.As(err, &failure) || failure.code != "agent_unavailable" {
+ t.Fatalf("credential = %v", err)
+ }
+}
diff --git a/apps/computer/local-daemon/internal/linger/context/filesystem_unix.go b/apps/computer/local-daemon/internal/linger/context/filesystem_unix.go
index ee98dfb5..0bc03a06 100644
--- a/apps/computer/local-daemon/internal/linger/context/filesystem_unix.go
+++ b/apps/computer/local-daemon/internal/linger/context/filesystem_unix.go
@@ -23,3 +23,10 @@ func syncDirectory(root *os.Root, relative string) error {
defer file.Close()
return file.Sync()
}
+
+// singleLink reports whether a file has no other hard link that could name
+// content from outside its folder.
+func singleLink(info os.FileInfo) bool {
+ stat, ok := info.Sys().(*syscall.Stat_t)
+ return ok && stat.Nlink == 1
+}
diff --git a/apps/computer/local-daemon/internal/linger/context/filesystem_windows.go b/apps/computer/local-daemon/internal/linger/context/filesystem_windows.go
index 83dbf69a..197a356c 100644
--- a/apps/computer/local-daemon/internal/linger/context/filesystem_windows.go
+++ b/apps/computer/local-daemon/internal/linger/context/filesystem_windows.go
@@ -78,3 +78,7 @@ func replaceProjectionFile(root *os.Root, source, target string) error {
// Contents are flushed before publication; the SQLite projection journal
// replays interrupted replacements on the next activation.
func syncDirectory(_ *os.Root, _ string) error { return nil }
+
+// singleLink is true on Windows: os.FileInfo carries no link count there, and
+// creating a hard link needs the same access as reading the file directly.
+func singleLink(os.FileInfo) bool { return true }
diff --git a/apps/computer/local-daemon/internal/linger/context/live_playground.go b/apps/computer/local-daemon/internal/linger/context/live_playground.go
new file mode 100644
index 00000000..d7268911
--- /dev/null
+++ b/apps/computer/local-daemon/internal/linger/context/live_playground.go
@@ -0,0 +1,233 @@
+package lingercontext
+
+import (
+ "context"
+ "database/sql"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+)
+
+// PlaygroundFolder names one folder the live voice may read: a delegated
+// Task's output folder, or a Meta Room's own folder. TeamHub authorizes the
+// names; this endpoint only resolves folders it retained for the Agent.
+type PlaygroundFolder struct {
+ TaskID string `json:"task_id,omitempty"`
+ OriginRoomID string `json:"origin_room_id,omitempty"`
+ RoomID string `json:"room_id,omitempty"`
+}
+
+var (
+ // ErrPlaygroundFolder means the endpoint holds no such folder for the Agent.
+ ErrPlaygroundFolder = errors.New("playground folder is not available to this Agent")
+ // ErrPlaygroundPath means a path is malformed, leaves its folder or passes a link.
+ ErrPlaygroundPath = errors.New("playground path is invalid")
+ // ErrPlaygroundNotFolder means a list named a file.
+ ErrPlaygroundNotFolder = errors.New("playground path is not a folder")
+ // ErrPlaygroundNotFile means a read named a folder or a special file.
+ ErrPlaygroundNotFile = errors.New("playground path is not a single regular file")
+)
+
+const (
+ // maxPlaygroundEntries bounds one listing.
+ maxPlaygroundEntries = 100
+ // MaxPlaygroundReadBytes keeps one read's base64 inside the Runner
+ // Gateway's 256 KiB string limit.
+ MaxPlaygroundReadBytes = 192 * 1024
+)
+
+// PlaygroundDirectory resolves folder to its directory on this endpoint.
+func (s *ViewStore) PlaygroundDirectory(ctx context.Context, tenantID, agentID string, folder PlaygroundFolder) (string, error) {
+ if tenantID == "" || agentID == "" {
+ return "", ErrPlaygroundFolder
+ }
+ switch {
+ case folder.TaskID != "" && folder.OriginRoomID != "" && folder.RoomID == "":
+ return s.taskPlaygroundDirectory(ctx, SharedTaskScope{Version: 1, TenantID: tenantID, AgentID: agentID,
+ OriginRoomID: folder.OriginRoomID, Role: sharedTaskRoleAlterEgo, TaskID: folder.TaskID})
+ case folder.RoomID != "" && folder.TaskID == "" && folder.OriginRoomID == "":
+ return s.roomPlaygroundDirectory(ctx, tenantID, agentID, folder.RoomID)
+ default:
+ return "", ErrPlaygroundFolder
+ }
+}
+
+func (s *ViewStore) taskPlaygroundDirectory(ctx context.Context, scope SharedTaskScope) (string, error) {
+ if !sharedTaskIDPattern.MatchString(scope.TaskID) {
+ return "", ErrPlaygroundFolder
+ }
+ storage := s.sharedTaskStorage()
+ if storage == nil {
+ return "", ErrSharedTaskStorageUnavailable
+ }
+ var found bool
+ err := s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM shared_task_scopes WHERE json_extract(scope_json,'$.tenant_id')=? AND json_extract(scope_json,'$.agent_id')=? AND json_extract(scope_json,'$.origin_room_id')=? AND json_extract(scope_json,'$.task_id')=? AND json_extract(scope_json,'$.role')='alter_ego')`, scope.TenantID, scope.AgentID, scope.OriginRoomID, scope.TaskID).Scan(&found)
+ if err != nil {
+ return "", err
+ }
+ if !found {
+ return "", ErrPlaygroundFolder
+ }
+ directory := storage.taskDirectory(scope, scope.TaskID)
+ relative, err := filepath.Rel(storage.root, directory)
+ if err != nil {
+ return "", err
+ }
+ return directory, realDirectories(storage.root, relative)
+}
+
+// roomPlaygroundDirectory is ./playground/<roomID> of the Agent's Meta
+// Context for that Room, the folder its Meta Runs write.
+func (s *ViewStore) roomPlaygroundDirectory(ctx context.Context, tenantID, agentID, roomID string) (string, error) {
+ if !sharedTaskIDPattern.MatchString(roomID) {
+ return "", ErrPlaygroundFolder
+ }
+ key, err := json.Marshal([]string{"meta", agentID, "room", roomID})
+ if err != nil {
+ return "", err
+ }
+ record, err := s.readOnce(ctx, string(key))
+ if errors.Is(err, sql.ErrNoRows) {
+ return "", ErrPlaygroundFolder
+ }
+ if err != nil {
+ return "", err
+ }
+ if record.View.TenantID != tenantID || record.View.AgentID != agentID {
+ return "", ErrPlaygroundFolder
+ }
+ return filepath.Join(record.WorkspacePath, sharedTaskPlayground, roomID),
+ realDirectories(record.WorkspacePath, filepath.Join(sharedTaskPlayground, roomID))
+}
+
+// realDirectories requires every component of relative under root to be a
+// real directory, so no link leads out of the folder.
+func realDirectories(root, relative string) error {
+ current := root
+ for _, part := range append([]string{""}, strings.Split(relative, string(filepath.Separator))...) {
+ current = filepath.Join(current, part)
+ info, err := os.Lstat(current)
+ if errors.Is(err, fs.ErrNotExist) {
+ return ErrPlaygroundFolder
+ }
+ if err != nil {
+ return err
+ }
+ if !realDirectory(info) {
+ return fmt.Errorf("%w: %s", ErrSharedTaskPathConflict, current)
+ }
+ }
+ return nil
+}
+
+// OpenPlaygroundFile opens one regular file of a folder. A link anywhere on
+// its path, or a file with another hard link, is refused.
+func (s *ViewStore) OpenPlaygroundFile(ctx context.Context, tenantID, agentID string, folder PlaygroundFolder, relative string) (*os.File, os.FileInfo, error) {
+ directory, err := s.PlaygroundDirectory(ctx, tenantID, agentID, folder)
+ if err != nil {
+ return nil, nil, err
+ }
+ file, err := openPlaygroundPath(directory, relative)
+ if err != nil {
+ return nil, nil, err
+ }
+ info, err := file.Stat()
+ if err == nil && (!info.Mode().IsRegular() || !singleLink(info)) {
+ err = ErrPlaygroundNotFile
+ }
+ if err != nil {
+ _ = file.Close()
+ return nil, nil, err
+ }
+ return file, info, nil
+}
+
+func openPlaygroundPath(directory, relative string) (*os.File, error) {
+ relative = filepath.FromSlash(strings.Trim(relative, "/"))
+ if relative == "" || relative == "." {
+ return os.Open(directory)
+ }
+ if _, err := safeJoin(directory, relative); err != nil {
+ return nil, ErrPlaygroundPath
+ }
+ file, err := openContextFile(directory, relative)
+ if err != nil && !errors.Is(err, fs.ErrNotExist) {
+ return nil, ErrPlaygroundPath
+ }
+ return file, err
+}
+
+// ListPlayground lists one folder: name, whether it is a folder, size and
+// modification time of up to 100 entries. Links are left out.
+func (s *ViewStore) ListPlayground(ctx context.Context, tenantID, agentID string, folder PlaygroundFolder, relative string) (map[string]any, error) {
+ directory, err := s.PlaygroundDirectory(ctx, tenantID, agentID, folder)
+ if err != nil {
+ return nil, err
+ }
+ file, err := openPlaygroundPath(directory, relative)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+ if info, err := file.Stat(); err != nil {
+ return nil, err
+ } else if !info.IsDir() {
+ return nil, ErrPlaygroundNotFolder
+ }
+ entries, err := file.ReadDir(-1)
+ if err != nil {
+ return nil, err
+ }
+ items := make([]map[string]any, 0, min(len(entries), maxPlaygroundEntries))
+ total := 0
+ for _, entry := range entries {
+ if entry.Type()&(os.ModeSymlink|os.ModeIrregular) != 0 {
+ continue
+ }
+ total++
+ if len(items) == maxPlaygroundEntries {
+ continue
+ }
+ info, err := entry.Info()
+ if err != nil {
+ continue
+ }
+ item := map[string]any{"name": entry.Name(), "directory": entry.IsDir(), "modified_ns": strconv.FormatInt(info.ModTime().UnixNano(), 10)}
+ if !entry.IsDir() {
+ item["size"] = info.Size()
+ }
+ items = append(items, item)
+ }
+ return map[string]any{"files": items, "total": total}, nil
+}
+
+// ReadPlayground reads up to limit bytes of one file from offset. TeamHub
+// joins reads into a whole file and checks it did not change in between.
+func (s *ViewStore) ReadPlayground(ctx context.Context, tenantID, agentID string, folder PlaygroundFolder, relative string, offset, limit int64) (map[string]any, error) {
+ if offset < 0 || limit <= 0 || limit > MaxPlaygroundReadBytes {
+ return nil, ErrPlaygroundPath
+ }
+ file, info, err := s.OpenPlaygroundFile(ctx, tenantID, agentID, folder, relative)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+ if _, err = file.Seek(offset, io.SeekStart); err != nil {
+ return nil, err
+ }
+ data, err := io.ReadAll(io.LimitReader(file, limit))
+ if err != nil {
+ return nil, err
+ }
+ next := offset + int64(len(data))
+ return map[string]any{"data_base64": base64.StdEncoding.EncodeToString(data), "size": info.Size(),
+ "modified_ns": strconv.FormatInt(info.ModTime().UnixNano(), 10), "offset": offset, "next_offset": next,
+ "eof": next >= info.Size()}, nil
+}
diff --git a/apps/computer/local-daemon/internal/linger/context/live_playground_test.go b/apps/computer/local-daemon/internal/linger/context/live_playground_test.go
new file mode 100644
index 00000000..0dde2e39
--- /dev/null
+++ b/apps/computer/local-daemon/internal/linger/context/live_playground_test.go
@@ -0,0 +1,130 @@
+package lingercontext
+
+import (
+ "bytes"
+ "encoding/base64"
+ "errors"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func readWholePlaygroundFile(t *testing.T, store *ViewStore, folder PlaygroundFolder, relative string) []byte {
+ t.Helper()
+ var recovered []byte
+ var offset int64
+ for {
+ result, err := store.ReadPlayground(t.Context(), "tenant-1", "agent-1", folder, relative, offset, MaxPlaygroundReadBytes)
+ if err != nil {
+ t.Fatal(err)
+ }
+ encoded := result["data_base64"].(string)
+ if len(encoded) > 256*1024 {
+ t.Fatalf("one read is %d base64 characters, over the Runner Gateway string limit", len(encoded))
+ }
+ chunk, err := base64.StdEncoding.DecodeString(encoded)
+ if err != nil {
+ t.Fatal(err)
+ }
+ recovered = append(recovered, chunk...)
+ offset = result["next_offset"].(int64)
+ if result["eof"] == true {
+ return recovered
+ }
+ }
+}
+
+func TestLivePlaygroundReadsTaskOutputWithoutMetaMountAndRejectsOtherScopes(t *testing.T) {
+ fixture := openSharedTaskFixture(t)
+ alter := applyScoped(t, fixture.store, scopedView("alter-1", testAlterKey, alterScope("task-1", "room-1")))
+ content := bytes.Repeat([]byte("output"), 100000)
+ taskDir := filepath.Join(alter.WorkspacePath, "playground", "task-1")
+ if err := os.WriteFile(filepath.Join(taskDir, "report.txt"), content, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := fixture.store.Close(); err != nil {
+ t.Fatal(err)
+ }
+ fixture.reopen(t)
+ folder := PlaygroundFolder{TaskID: "task-1", OriginRoomID: "room-1"}
+ if !bytes.Equal(readWholePlaygroundFile(t, fixture.store, folder, "report.txt"), content) {
+ t.Fatal("Live did not read the actual Task output")
+ }
+ listed, err := fixture.store.ListPlayground(t.Context(), "tenant-1", "agent-1", folder, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ files := listed["files"].([]map[string]any)
+ if len(files) != 1 || files[0]["name"] != "report.txt" || files[0]["size"] != int64(len(content)) || files[0]["directory"] != false {
+ t.Fatalf("list=%v", listed)
+ }
+ for _, wrong := range []struct {
+ tenant, agent string
+ folder PlaygroundFolder
+ }{
+ {"other", "agent-1", folder},
+ {"tenant-1", "other", folder},
+ {"tenant-1", "agent-1", PlaygroundFolder{TaskID: "task-1", OriginRoomID: "other"}},
+ {"tenant-1", "agent-1", PlaygroundFolder{TaskID: "task-2", OriginRoomID: "room-1"}},
+ {"tenant-1", "agent-1", PlaygroundFolder{TaskID: "task-1", OriginRoomID: "room-1", RoomID: "room-1"}},
+ } {
+ if _, err := fixture.store.ReadPlayground(t.Context(), wrong.tenant, wrong.agent, wrong.folder, "report.txt", 0, 10); !errors.Is(err, ErrPlaygroundFolder) {
+ t.Fatalf("cross-scope read %+v = %v", wrong, err)
+ }
+ }
+ outside := filepath.Join(t.TempDir(), "secret")
+ if err := os.WriteFile(outside, []byte("secret"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := createTestFileLink(t, outside, filepath.Join(taskDir, "link")); err != nil {
+ t.Fatal(err)
+ }
+ for _, filename := range []string{"../secret", outside, "link"} {
+ if _, err := fixture.store.ReadPlayground(t.Context(), "tenant-1", "agent-1", folder, filename, 0, 10); err == nil {
+ t.Fatalf("unsafe path accepted: %s", filename)
+ }
+ }
+ if _, err := fixture.store.ReadPlayground(t.Context(), "tenant-1", "agent-1", folder, "report.txt", 0, MaxPlaygroundReadBytes+1); !errors.Is(err, ErrPlaygroundPath) {
+ t.Fatalf("an over-limit read = %v", err)
+ }
+ if _, err := fixture.store.ReadPlayground(t.Context(), "tenant-1", "agent-1", folder, "missing.txt", 0, 10); !errors.Is(err, fs.ErrNotExist) {
+ t.Fatalf("a missing file = %v", err)
+ }
+}
+
+func TestLivePlaygroundReadsTheMetaRoomFolder(t *testing.T) {
+ fixture := openSharedTaskFixture(t)
+ meta := applyScoped(t, fixture.store, scopedView("meta-1", testMetaKey, metaScope()))
+ roomDir := filepath.Join(meta.WorkspacePath, "playground", "room-1")
+ if err := os.MkdirAll(filepath.Join(roomDir, "drafts"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(roomDir, "drafts", "note.md"), []byte("# Note"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ folder := PlaygroundFolder{RoomID: "room-1"}
+ listed, err := fixture.store.ListPlayground(t.Context(), "tenant-1", "agent-1", folder, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if files := listed["files"].([]map[string]any); len(files) != 1 || files[0]["name"] != "drafts" || files[0]["directory"] != true {
+ t.Fatalf("list=%v", listed)
+ }
+ if got := readWholePlaygroundFile(t, fixture.store, folder, "drafts/note.md"); string(got) != "# Note" {
+ t.Fatalf("read=%q", got)
+ }
+ if _, err := fixture.store.ListPlayground(t.Context(), "tenant-1", "agent-1", folder, "drafts/note.md"); !errors.Is(err, ErrPlaygroundNotFolder) {
+ t.Fatalf("listing a file = %v", err)
+ }
+ if _, err := fixture.store.ReadPlayground(t.Context(), "tenant-1", "agent-1", folder, "drafts", 0, 10); !errors.Is(err, ErrPlaygroundNotFile) {
+ t.Fatalf("reading a folder = %v", err)
+ }
+ for _, wrong := range []struct {
+ tenant, agent, room string
+ }{{"other", "agent-1", "room-1"}, {"tenant-1", "agent-2", "room-1"}, {"tenant-1", "agent-1", "room-2"}} {
+ if _, err := fixture.store.ListPlayground(t.Context(), wrong.tenant, wrong.agent, PlaygroundFolder{RoomID: wrong.room}, ""); !errors.Is(err, ErrPlaygroundFolder) {
+ t.Fatalf("another Room folder %+v = %v", wrong, err)
+ }
+ }
+}
diff --git a/apps/computer/local-daemon/internal/linger/context/live_task_files.go b/apps/computer/local-daemon/internal/linger/context/live_task_files.go
deleted file mode 100644
index fe6c6017..00000000
--- a/apps/computer/local-daemon/internal/linger/context/live_task_files.go
+++ /dev/null
@@ -1,113 +0,0 @@
-package lingercontext
-
-import (
- "context"
- "encoding/base64"
- "encoding/json"
- "errors"
- "io"
- "os"
- "path/filepath"
- "strconv"
- "strings"
-)
-
-// ReadLiveTaskFiles resolves a TeamHub-authorized task identity against the
-// locally retained scope. It needs no Meta view or playground mount.
-func (s *ViewStore) ReadLiveTaskFiles(ctx context.Context, scope SharedTaskScope, name string, args json.RawMessage) (map[string]any, error) {
- if scope.Version != 1 || scope.Role != sharedTaskRoleAlterEgo || !sharedTaskIDPattern.MatchString(scope.TaskID) || scope.TenantID == "" || scope.AgentID == "" || scope.OriginRoomID == "" {
- return nil, ErrSharedTaskScope
- }
- storage := s.sharedTaskStorage()
- if storage == nil {
- return nil, ErrSharedTaskStorageUnavailable
- }
- var found bool
- err := s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM shared_task_scopes WHERE json_extract(scope_json,'$.tenant_id')=? AND json_extract(scope_json,'$.agent_id')=? AND json_extract(scope_json,'$.origin_room_id')=? AND json_extract(scope_json,'$.task_id')=? AND json_extract(scope_json,'$.role')='alter_ego')`, scope.TenantID, scope.AgentID, scope.OriginRoomID, scope.TaskID).Scan(&found)
- if err != nil {
- return nil, err
- }
- if !found {
- return nil, ErrSharedTaskScope
- }
- var input struct {
- Path string `json:"path"`
- Offset int64 `json:"offset"`
- }
- if json.Unmarshal(args, &input) != nil || input.Offset < 0 || filepath.IsAbs(input.Path) || strings.ContainsRune(input.Path, 0) {
- return nil, errors.New("invalid Task file request")
- }
- directory := storage.taskDirectory(scope, scope.TaskID)
- // Reject every symbolic directory in the locally owned prefix as well as
- // escapes through user-created links inside the Task.
- relative, err := filepath.Rel(storage.root, directory)
- if err != nil {
- return nil, err
- }
- current := storage.root
- for _, part := range append([]string{""}, strings.Split(relative, string(filepath.Separator))...) {
- current = filepath.Join(current, part)
- info, err := os.Lstat(current)
- if err != nil {
- return nil, err
- }
- if !realDirectory(info) {
- return nil, ErrSharedTaskPathConflict
- }
- }
- if name == "list_files" {
- root, err := os.OpenRoot(directory)
- if err != nil {
- return nil, err
- }
- defer root.Close()
- path := input.Path
- if path == "" {
- path = "."
- }
- file, err := root.Open(path)
- if err != nil {
- return nil, err
- }
- defer file.Close()
- entries, err := file.ReadDir(101)
- if err != nil && !errors.Is(err, io.EOF) {
- return nil, err
- }
- truncated := len(entries) > 100
- if truncated {
- entries = entries[:100]
- }
- items := make([]map[string]any, 0, len(entries))
- for _, entry := range entries {
- if entry.Type()&os.ModeSymlink != 0 {
- continue
- }
- items = append(items, map[string]any{"name": entry.Name(), "directory": entry.IsDir()})
- }
- return map[string]any{"files": items, "truncated": truncated}, nil
- }
- if name != "read_file" {
- return nil, errors.New("unknown Task file tool")
- }
- file, err := openContextFile(directory, input.Path)
- if err != nil {
- return nil, err
- }
- defer file.Close()
- info, err := file.Stat()
- if err != nil {
- return nil, err
- }
- if !info.Mode().IsRegular() {
- return nil, errors.New("Task file is not regular")
- }
- if _, err = file.Seek(input.Offset, io.SeekStart); err != nil {
- return nil, err
- }
- data, err := io.ReadAll(io.LimitReader(file, 512*1024))
- if err != nil {
- return nil, err
- }
- return map[string]any{"data_base64": base64.StdEncoding.EncodeToString(data), "size": info.Size(), "modified_ns": strconv.FormatInt(info.ModTime().UnixNano(), 10), "offset": input.Offset, "next_offset": input.Offset + int64(len(data)), "eof": input.Offset+int64(len(data)) >= info.Size()}, nil
-}
diff --git a/apps/computer/local-daemon/internal/linger/context/live_task_files_test.go b/apps/computer/local-daemon/internal/linger/context/live_task_files_test.go
deleted file mode 100644
index ea5f904f..00000000
--- a/apps/computer/local-daemon/internal/linger/context/live_task_files_test.go
+++ /dev/null
@@ -1,69 +0,0 @@
-package lingercontext
-
-import (
- "bytes"
- "encoding/base64"
- "encoding/json"
- "errors"
- "os"
- "path/filepath"
- "testing"
-)
-
-func TestLiveTaskFilesWithoutMetaMountSurviveRestartAndRejectOtherScopes(t *testing.T) {
- fixture := openSharedTaskFixture(t)
- scope := alterScope("task-1", "room-1")
- alter := applyScoped(t, fixture.store, scopedView("alter-1", testAlterKey, scope))
- content := bytes.Repeat([]byte("output"), 100000)
- taskDir := filepath.Join(alter.WorkspacePath, "playground", "task-1")
- if err := os.WriteFile(filepath.Join(taskDir, "report.txt"), content, 0o600); err != nil {
- t.Fatal(err)
- }
- if err := fixture.store.Close(); err != nil {
- t.Fatal(err)
- }
- fixture.reopen(t)
- var recovered []byte
- var offset int64
- for {
- args, _ := json.Marshal(map[string]any{"path": "report.txt", "offset": offset})
- result, err := fixture.store.ReadLiveTaskFiles(t.Context(), *scope, "read_file", args)
- if err != nil {
- t.Fatal(err)
- }
- chunk, err := base64.StdEncoding.DecodeString(result["data_base64"].(string))
- if err != nil {
- t.Fatal(err)
- }
- recovered = append(recovered, chunk...)
- offset = result["next_offset"].(int64)
- if result["eof"] == true {
- break
- }
- }
- if !bytes.Equal(recovered, content) {
- t.Fatal("Live did not read the actual Task output")
- }
- listed, err := fixture.store.ReadLiveTaskFiles(t.Context(), *scope, "list_files", json.RawMessage(`{}`))
- if err != nil || len(listed["files"].([]map[string]any)) != 1 {
- t.Fatalf("list=%v %v", listed, err)
- }
- for _, wrong := range []SharedTaskScope{{Version: 1, TenantID: "other", AgentID: scope.AgentID, OriginRoomID: scope.OriginRoomID, TaskID: scope.TaskID, Role: scope.Role}, {Version: 1, TenantID: scope.TenantID, AgentID: scope.AgentID, OriginRoomID: "other", TaskID: scope.TaskID, Role: scope.Role}, {Version: 1, TenantID: scope.TenantID, AgentID: "other", OriginRoomID: scope.OriginRoomID, TaskID: scope.TaskID, Role: scope.Role}} {
- if _, err := fixture.store.ReadLiveTaskFiles(t.Context(), wrong, "read_file", json.RawMessage(`{"path":"report.txt"}`)); !errors.Is(err, ErrSharedTaskScope) {
- t.Fatalf("cross-scope read=%v", err)
- }
- }
- outside := filepath.Join(t.TempDir(), "secret")
- if err := os.WriteFile(outside, []byte("secret"), 0o600); err != nil {
- t.Fatal(err)
- }
- if err := createTestFileLink(t, outside, filepath.Join(taskDir, "link")); err != nil {
- t.Fatal(err)
- }
- for _, filename := range []string{"../secret", outside, "link"} {
- args, _ := json.Marshal(map[string]string{"path": filename})
- if _, err := fixture.store.ReadLiveTaskFiles(t.Context(), *scope, "read_file", args); err == nil {
- t.Fatalf("unsafe path accepted: %s", filename)
- }
- }
-}
diff --git a/apps/computer/tests/runner-wire-contract.test.ts b/apps/computer/tests/runner-wire-contract.test.ts
index 3c784d9a..3f1fb873 100644
--- a/apps/computer/tests/runner-wire-contract.test.ts
+++ b/apps/computer/tests/runner-wire-contract.test.ts
@@ -70,18 +70,10 @@ const agentFrames = [
owner_actor_id: "owner-1",
agent_id: "agent-1",
tool_session_id: "voice-1",
- server: "task_files",
- tool_name: "list_files",
- arguments: {},
+ server: "playground",
+ tool_name: "list",
+ arguments: { folder: { room_id: "room-1" }, path: "" },
deadline_ms: 60_000,
- task_scope: {
- version: 1,
- tenant_id: "tenant-1",
- agent_id: "agent-1",
- origin_room_id: "room-1",
- role: "alter_ego",
- task_id: "task-1",
- },
},
{
type: "runner.welcome",
diff --git a/apps/node-services/src/agent/executor/http/agent-manager-http-server.ts b/apps/node-services/src/agent/executor/http/agent-manager-http-server.ts
index 9b5c134a..8af7a491 100644
--- a/apps/node-services/src/agent/executor/http/agent-manager-http-server.ts
+++ b/apps/node-services/src/agent/executor/http/agent-manager-http-server.ts
@@ -420,7 +420,11 @@ const createAgentManagerHttpApp = <TRuntimeSettings>(
if (
!isRecord(body) ||
!isRecord(body.arguments) ||
- !["browser", "task_files"].includes(String(body.server)) ||
+ !["browser", "playground"].includes(String(body.server)) ||
+ (body.deadline_ms !== undefined &&
+ (!Number.isInteger(body.deadline_ms) ||
+ Number(body.deadline_ms) < 1_000 ||
+ Number(body.deadline_ms) > 120_000)) ||
[
"tenant_id",
"owner_actor_id",
@@ -451,7 +455,6 @@ const createAgentManagerHttpApp = <TRuntimeSettings>(
);
const request =
body as unknown as AgentManagementSchemas["schemas"]["LocalComputerToolCall"];
- const scope = request.task_scope;
const result = await computerTools.callComputerTool({
tenantId: request.tenant_id,
ownerActorId: request.owner_actor_id,
@@ -461,15 +464,7 @@ const createAgentManagerHttpApp = <TRuntimeSettings>(
server: request.server,
toolName: request.tool_name,
arguments: request.arguments,
- ...(scope
- ? {
- taskScope: {
- ...scope,
- version: 1 as const,
- role: "alter_ego" as const,
- },
- }
- : {}),
+ ...(request.deadline_ms ? { deadlineMs: request.deadline_ms } : {}),
signal: context.req.raw.signal,
});
return context.json({ result });
diff --git a/apps/node-services/src/agent/runner-gateway/context-view-content.ts b/apps/node-services/src/agent/runner-gateway/context-view-content.ts
index 4189e7c9..88055eb5 100644
--- a/apps/node-services/src/agent/runner-gateway/context-view-content.ts
+++ b/apps/node-services/src/agent/runner-gateway/context-view-content.ts
@@ -3,12 +3,14 @@ import { constants, type BigIntStats } from "node:fs";
import { lstat, open, readdir, realpath } from "node:fs/promises";
import path from "node:path";
-import type { SharedTaskScope } from "@linger/wire-contracts/runner-gateway/types";
import { mediaTypeForExtension } from "@linger/document-files/media-type";
import { sha256Hex } from "@linger/service-kit/node";
import type { RuntimeViewPlan } from "../executor/workspace.js";
-import { sharedTaskScopeWire } from "./shared-task-scope.js";
+import {
+ sharedTaskScopeWire,
+ type SharedTaskScopeWire,
+} from "./shared-task-scope.js";
const RUNTIME_WORKSPACE = "/workspace";
const MAX_FILE_COUNT = 10_000;
@@ -50,7 +52,7 @@ export interface ContextViewManifest {
readonly version: 1;
readonly execution_context_key: string;
readonly runtime_instance_id: string;
- readonly shared_task_scope?: SharedTaskScope;
+ readonly shared_task_scope?: SharedTaskScopeWire;
readonly mappings: readonly ContextViewMapping[];
readonly skills: readonly ContextViewSkill[];
}
diff --git a/apps/node-services/src/agent/runner-gateway/runner-computer-tools.ts b/apps/node-services/src/agent/runner-gateway/runner-computer-tools.ts
index e823a9d9..21526059 100644
--- a/apps/node-services/src/agent/runner-gateway/runner-computer-tools.ts
+++ b/apps/node-services/src/agent/runner-gateway/runner-computer-tools.ts
@@ -1,7 +1,4 @@
-import type {
- ComputerToolResult,
- SharedTaskScope,
-} from "@linger/wire-contracts/runner-gateway/types";
+import type { ComputerToolResult } from "@linger/wire-contracts/runner-gateway/types";
import {
RUNNER_GATEWAY_PROTOCOL_VERSION,
parseAgentToDaemonEnvelope,
@@ -23,10 +20,11 @@ export interface ComputerToolRequest {
computerId: string;
agentId: string;
toolSessionId: string;
- server: "browser" | "task_files";
+ server: "browser" | "playground";
toolName: string;
arguments: Record<string, unknown>;
- taskScope?: SharedTaskScope;
+ /** How long the Computer may take; defaults to one minute. */
+ deadlineMs?: number;
signal: AbortSignal;
}
const unknown = () => ({
@@ -68,15 +66,8 @@ export class RunnerComputerTools {
.places(request.computerId, request.tenantId, request.agentId)
)
throw new LocalComputerNotFoundError();
- if (
- request.taskScope &&
- (request.server !== "task_files" ||
- request.taskScope.tenant_id !== request.tenantId ||
- request.taskScope.agent_id !== request.agentId ||
- request.taskScope.role !== "alter_ego")
- )
- throw new LocalComputerNotFoundError();
if (this.pending.size >= 16) return { status: "busy" };
+ const deadlineMs = request.deadlineMs ?? 60_000;
const commandId = this.context.createId();
const command = parseAgentToDaemonEnvelope({
type: "execute",
@@ -92,8 +83,7 @@ export class RunnerComputerTools {
server: request.server,
tool_name: request.toolName,
arguments: request.arguments,
- ...(request.taskScope ? { task_scope: request.taskScope } : {}),
- deadline_ms: 60_000,
+ deadline_ms: deadlineMs,
});
let timer: NodeJS.Timeout | undefined;
let abort: (() => void) | undefined;
@@ -108,7 +98,7 @@ export class RunnerComputerTools {
});
abort = () => resolve(unknown());
request.signal.addEventListener("abort", abort, { once: true });
- timer = setTimeout(() => resolve(unknown()), 62_000);
+ timer = setTimeout(() => resolve(unknown()), deadlineMs + 2_000);
timer.unref();
});
request.signal.throwIfAborted();
diff --git a/apps/node-services/src/agent/runner-gateway/shared-task-scope.ts b/apps/node-services/src/agent/runner-gateway/shared-task-scope.ts
index bde64931..7f687a59 100644
--- a/apps/node-services/src/agent/runner-gateway/shared-task-scope.ts
+++ b/apps/node-services/src/agent/runner-gateway/shared-task-scope.ts
@@ -1,6 +1,15 @@
-import type { SharedTaskScope as SharedTaskScopeWire } from "@linger/wire-contracts/runner-gateway/types";
import type { SharedTaskScope } from "../executor/context-ref.js";
+/** The envelope schema's SharedTaskScope, carried inside a Context View manifest. */
+export interface SharedTaskScopeWire {
+ readonly version: 1;
+ readonly tenant_id: string;
+ readonly agent_id: string;
+ readonly origin_room_id: string;
+ readonly role: "meta" | "alter_ego";
+ readonly task_id?: string;
+}
+
/** The receiver resolves the scope under its own shared root. */
export const sharedTaskScopeWire = (
scope: SharedTaskScope | undefined,
diff --git a/apps/node-services/tests/agent/runner-gateway/runner-computer-tools.test.ts b/apps/node-services/tests/agent/runner-gateway/runner-computer-tools.test.ts
index 79d59c2b..5219e51a 100644
--- a/apps/node-services/tests/agent/runner-gateway/runner-computer-tools.test.ts
+++ b/apps/node-services/tests/agent/runner-gateway/runner-computer-tools.test.ts
@@ -112,26 +112,19 @@ const target = {
ownerActorId: "actor-1",
agentId: "agent-1",
toolSessionId: "voice-session-1",
- server: "task_files" as const,
- toolName: "list_files",
- arguments: {},
- taskScope: {
- version: 1 as const,
- tenant_id: "tenant-1",
- agent_id: "agent-1",
- role: "alter_ego" as const,
- origin_room_id: "room-1",
- task_id: "task-1",
- },
+ server: "playground" as const,
+ toolName: "list",
+ arguments: { location: { room_id: "room-1" }, path: "" },
signal: new AbortController().signal,
};
describe("Live native Computer tools", () => {
- it("reads a retained task workspace without starting a model", async () => {
+ it("reads a playground folder without starting a model", async () => {
const { gateway, connection, command, sent } = await connect();
const pending = gateway.callComputerTool(target);
const request = await command();
- expect(request.task_scope).toEqual(target.taskScope);
+ expect(request.arguments).toEqual(target.arguments);
+ expect(request.deadline_ms).toBe(60_000);
await connection.receive({
type: "executed",
kind: "computer_tool",
@@ -151,7 +144,12 @@ describe("Live native Computer tools", () => {
),
).toBe(false);
});
- it("rejects another owner, Agent or task scope before dispatch", async () => {
+ it("gives the Computer the deadline the caller asks for", async () => {
+ const { gateway, command } = await connect();
+ void gateway.callComputerTool({ ...target, deadlineMs: 120_000 });
+ expect((await command()).deadline_ms).toBe(120_000);
+ });
+ it("rejects another owner or Agent before dispatch", async () => {
const { gateway, sent } = await connect();
await expect(
gateway.callComputerTool({ ...target, ownerActorId: "actor-other" }),
@@ -159,12 +157,6 @@ describe("Live native Computer tools", () => {
await expect(
gateway.callComputerTool({ ...target, agentId: "agent-other" }),
).rejects.toBeInstanceOf(LocalComputerNotFoundError);
- await expect(
- gateway.callComputerTool({
- ...target,
- taskScope: { ...target.taskScope, tenant_id: "tenant-other" },
- }),
- ).rejects.toBeInstanceOf(LocalComputerNotFoundError);
expect(
sent.some(
(item) => item.type === "execute" && item.kind === "computer_tool",
@@ -184,7 +176,6 @@ describe("Live native Computer tools", () => {
...target,
server: "browser",
toolName: "browser_click",
- taskScope: undefined,
});
await command();
connection.disconnect();
diff --git a/apps/teamhub/internal/app/contract_server_agent_file_tools.go b/apps/teamhub/internal/app/contract_server_agent_file_tools.go
index b8913687..24ab9e22 100644
--- a/apps/teamhub/internal/app/contract_server_agent_file_tools.go
+++ b/apps/teamhub/internal/app/contract_server_agent_file_tools.go
@@ -15,6 +15,10 @@ func agentFileToolMultipartReader(c *gin.Context, maxBytes int64) (*multipart.Re
if err != nil || mediaType != "multipart/form-data" || parameters["boundary"] == "" {
return nil, errors.New("request must be multipart/form-data with one boundary")
}
+ // Files of up to hundreds of MiB outlast the server's whole-request read timeout.
+ if err := extendUploadReadDeadline(c); err != nil {
+ return nil, err
+ }
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes)
return multipart.NewReader(c.Request.Body, parameters["boundary"]), nil
}
diff --git a/apps/teamhub/internal/roomagent/http_gateway.go b/apps/teamhub/internal/roomagent/http_gateway.go
index 49931a03..fab9adb1 100644
--- a/apps/teamhub/internal/roomagent/http_gateway.go
+++ b/apps/teamhub/internal/roomagent/http_gateway.go
@@ -20,6 +20,7 @@ var opaqueIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$`)
type HTTPGateway struct {
client *agentapi.ClientWithResponses
browserClient *agentapi.ClientWithResponses
+ toolClient *agentapi.ClientWithResponses
}
const agentManagementRequestTimeout = 15 * time.Second
@@ -28,6 +29,10 @@ const agentManagementRequestTimeout = 15 * time.Second
// browser verification at the Gateway.
const localBrowserConnectionRequestTimeout = 65 * time.Second
+// localComputerToolRequestTimeout covers the longest deadline a Computer tool
+// call may name, two minutes, at the Gateway.
+const localComputerToolRequestTimeout = 125 * time.Second
+
// NewHTTPGateway validates the service endpoint and creates an AgentManagement client.
func NewHTTPGateway(baseURL, token string, client *http.Client) (*HTTPGateway, error) {
if client == nil {
@@ -44,7 +49,13 @@ func NewHTTPGateway(baseURL, token string, client *http.Client) (*HTTPGateway, e
if err != nil {
return nil, fmt.Errorf("create browser connection contract client: %w", err)
}
- return &HTTPGateway{client: generatedClient, browserClient: browserClient}, nil
+ toolHTTPClient := *client
+ toolHTTPClient.Timeout = localComputerToolRequestTimeout
+ toolClient, err := NewAgentManagementClient(baseURL, token, &toolHTTPClient)
+ if err != nil {
+ return nil, fmt.Errorf("create Computer tool contract client: %w", err)
+ }
+ return &HTTPGateway{client: generatedClient, browserClient: browserClient, toolClient: toolClient}, nil
}
// NewAgentManagementClient validates the Agent Service origin and creates a
diff --git a/apps/teamhub/internal/roomagent/local_computer_tools.go b/apps/teamhub/internal/roomagent/local_computer_tools.go
index 89d9fb70..beeb90b1 100644
--- a/apps/teamhub/internal/roomagent/local_computer_tools.go
+++ b/apps/teamhub/internal/roomagent/local_computer_tools.go
@@ -37,7 +37,7 @@ func (e *LocalComputerToolError) Error() string { return e.Code + ": " + e.Messa
// CallLocalComputerTool dispatches directly to the Computer without creating a model Run.
func (g *HTTPGateway) CallLocalComputerTool(ctx context.Context, call api.LocalComputerToolCall) (map[string]any, error) {
- response, err := g.browserClient.CallLocalComputerToolWithResponse(ctx, call)
+ response, err := g.toolClient.CallLocalComputerToolWithResponse(ctx, call)
if err != nil {
return nil, &LocalComputerToolError{Code: "outcome_unknown", Message: "The Computer may have performed the operation. Check its effect before retrying."}
}
@@ -45,7 +45,11 @@ func (g *HTTPGateway) CallLocalComputerTool(ctx context.Context, call api.LocalC
return nil, &LocalComputerToolError{Code: "computer_unavailable", Message: "The Computer could not accept this tool call."}
}
if status, ok := response.JSON200.Result["status"].(string); ok && status != "ok" {
- return nil, &LocalComputerToolError{Code: status, Message: "Check the Computer and current operation state before continuing."}
+ message, _ := response.JSON200.Result["detail"].(string)
+ if message == "" {
+ message = "Check the Computer and current operation state before continuing."
+ }
+ return nil, &LocalComputerToolError{Code: status, Message: message}
}
return response.JSON200.Result, nil
}
diff --git a/apps/teamhub/internal/store/queries/voice_live.sql b/apps/teamhub/internal/store/queries/voice_live.sql
index fed68603..17ab0093 100644
--- a/apps/teamhub/internal/store/queries/voice_live.sql
+++ b/apps/teamhub/internal/store/queries/voice_live.sql
@@ -385,21 +385,20 @@ SELECT EXISTS(
AND callback.coordinator_actor_id=sqlc.arg(coordinator_actor_id)::text AND item.archived_at IS NULL
)::boolean;
--- name: GetVoiceLiveReportTask :one
-SELECT message.task_id FROM task_meta_callback_messages message
+-- name: GetVoiceLiveTaskLatestReport :one
+-- The report the Task's coordinator got when its latest turn ended.
+SELECT message.id FROM task_meta_callback_messages message
+JOIN work_items item ON item.id=message.task_id AND item.task_execution_generation=message.generation
JOIN task_meta_callbacks callback ON callback.task_id=message.task_id AND callback.generation=message.generation
-WHERE message.id=sqlc.arg(report_id)::text AND message.task_id=sqlc.arg(task_id)::text
- AND callback.coordinator_actor_id=sqlc.arg(coordinator_actor_id)::text AND callback.tenant_id=sqlc.arg(tenant_id)::text;
-
--- name: GetVoiceLiveReportDelivery :one
-SELECT message_id FROM voice_live_report_deliveries WHERE report_id=sqlc.arg(report_id)::text;
-
--- name: LockVoiceLiveReport :exec
-SELECT id FROM task_meta_callback_messages WHERE id=sqlc.arg(report_id)::text FOR UPDATE;
+WHERE message.task_id=sqlc.arg(task_id)::text
+ AND callback.coordinator_actor_id=sqlc.arg(coordinator_actor_id)::text AND callback.tenant_id=sqlc.arg(tenant_id)::text
+ORDER BY message.meta_seq DESC LIMIT 1;
-- name: CreateVoiceLiveReportDelivery :exec
+-- A report is delivered once; a later card with the same files keeps the first.
INSERT INTO voice_live_report_deliveries(report_id,voice_session_id,message_id)
-VALUES(sqlc.arg(report_id)::text,sqlc.arg(voice_session_id)::text,sqlc.arg(message_id)::text);
+VALUES(sqlc.arg(report_id)::text,sqlc.arg(voice_session_id)::text,sqlc.arg(message_id)::text)
+ON CONFLICT (report_id) DO NOTHING;
-- name: MarkVoiceLiveReportNonActionable :exec
UPDATE task_meta_callback_messages SET non_actionable=true WHERE id=sqlc.arg(report_id)::text;
diff --git a/apps/teamhub/internal/store/queries/voice_live_tasks.sql b/apps/teamhub/internal/store/queries/voice_live_tasks.sql
index d3e04321..093ad294 100644
--- a/apps/teamhub/internal/store/queries/voice_live_tasks.sql
+++ b/apps/teamhub/internal/store/queries/voice_live_tasks.sql
@@ -20,6 +20,12 @@ ORDER BY task.created_at DESC LIMIT 1;
SELECT * FROM voice_live_tasks
WHERE room_id=sqlc.arg(room_id)::text AND owner_actor_id=sqlc.arg(owner_actor_id)::text AND ordinal=sqlc.arg(ordinal)::int;
+-- name: GetVoiceLiveTaskByWorkItem :one
+-- A call names a Task's output folder by its Work Item ID.
+SELECT * FROM voice_live_tasks
+WHERE room_id=sqlc.arg(room_id)::text AND owner_actor_id=sqlc.arg(owner_actor_id)::text
+ AND work_item_id=sqlc.arg(work_item_id)::text;
+
-- name: CancelVoiceLiveTask :execrows
UPDATE voice_live_tasks SET canceled_at=clock_timestamp()
WHERE work_item_id=sqlc.arg(work_item_id)::text AND canceled_at IS NULL;
diff --git a/apps/teamhub/internal/store/voice_live.sql.go b/apps/teamhub/internal/store/voice_live.sql.go
index da439a3f..30911081 100644
--- a/apps/teamhub/internal/store/voice_live.sql.go
+++ b/apps/teamhub/internal/store/voice_live.sql.go
@@ -154,6 +154,7 @@ func (q *Queries) CreateVoiceLiveReply(ctx context.Context, arg CreateVoiceLiveR
const createVoiceLiveReportDelivery = `-- name: CreateVoiceLiveReportDelivery :exec
INSERT INTO voice_live_report_deliveries(report_id,voice_session_id,message_id)
VALUES($1::text,$2::text,$3::text)
+ON CONFLICT (report_id) DO NOTHING
`
type CreateVoiceLiveReportDeliveryParams struct {
@@ -162,6 +163,7 @@ type CreateVoiceLiveReportDeliveryParams struct {
MessageID string `json:"message_id"`
}
+// A report is delivered once; a later card with the same files keeps the first.
func (q *Queries) CreateVoiceLiveReportDelivery(ctx context.Context, arg CreateVoiceLiveReportDeliveryParams) error {
_, err := q.db.Exec(ctx, createVoiceLiveReportDelivery, arg.ReportID, arg.VoiceSessionID, arg.MessageID)
return err
@@ -501,43 +503,6 @@ func (q *Queries) GetVoiceLiveReplySessionContext(ctx context.Context, voiceSess
return i, err
}
-const getVoiceLiveReportDelivery = `-- name: GetVoiceLiveReportDelivery :one
-SELECT message_id FROM voice_live_report_deliveries WHERE report_id=$1::text
-`
-
-func (q *Queries) GetVoiceLiveReportDelivery(ctx context.Context, reportID string) (string, error) {
- row := q.db.QueryRow(ctx, getVoiceLiveReportDelivery, reportID)
- var message_id string
- err := row.Scan(&message_id)
- return message_id, err
-}
-
-const getVoiceLiveReportTask = `-- name: GetVoiceLiveReportTask :one
-SELECT message.task_id FROM task_meta_callback_messages message
-JOIN task_meta_callbacks callback ON callback.task_id=message.task_id AND callback.generation=message.generation
-WHERE message.id=$1::text AND message.task_id=$2::text
- AND callback.coordinator_actor_id=$3::text AND callback.tenant_id=$4::text
-`
-
-type GetVoiceLiveReportTaskParams struct {
- ReportID string `json:"report_id"`
- TaskID string `json:"task_id"`
- CoordinatorActorID string `json:"coordinator_actor_id"`
- TenantID string `json:"tenant_id"`
-}
-
-func (q *Queries) GetVoiceLiveReportTask(ctx context.Context, arg GetVoiceLiveReportTaskParams) (string, error) {
- row := q.db.QueryRow(ctx, getVoiceLiveReportTask,
- arg.ReportID,
- arg.TaskID,
- arg.CoordinatorActorID,
- arg.TenantID,
- )
- var task_id string
- err := row.Scan(&task_id)
- return task_id, err
-}
-
const getVoiceLiveRoomLabel = `-- name: GetVoiceLiveRoomLabel :one
SELECT coalesce(agent_peer.display_name,room.name)::text AS label
FROM rooms room
@@ -591,6 +556,29 @@ func (q *Queries) GetVoiceLiveSlackUser(ctx context.Context, connectionID string
return column_1, err
}
+const getVoiceLiveTaskLatestReport = `-- name: GetVoiceLiveTaskLatestReport :one
+SELECT message.id FROM task_meta_callback_messages message
+JOIN work_items item ON item.id=message.task_id AND item.task_execution_generation=message.generation
+JOIN task_meta_callbacks callback ON callback.task_id=message.task_id AND callback.generation=message.generation
+WHERE message.task_id=$1::text
+ AND callback.coordinator_actor_id=$2::text AND callback.tenant_id=$3::text
+ORDER BY message.meta_seq DESC LIMIT 1
+`
+
+type GetVoiceLiveTaskLatestReportParams struct {
+ TaskID string `json:"task_id"`
+ CoordinatorActorID string `json:"coordinator_actor_id"`
+ TenantID string `json:"tenant_id"`
+}
+
+// The report the Task's coordinator got when its latest turn ended.
+func (q *Queries) GetVoiceLiveTaskLatestReport(ctx context.Context, arg GetVoiceLiveTaskLatestReportParams) (string, error) {
+ row := q.db.QueryRow(ctx, getVoiceLiveTaskLatestReport, arg.TaskID, arg.CoordinatorActorID, arg.TenantID)
+ var id string
+ err := row.Scan(&id)
+ return id, err
+}
+
const getVoiceLiveToolCall = `-- name: GetVoiceLiveToolCall :one
SELECT output,request_hash,state,name FROM voice_live_tool_calls
WHERE voice_session_id=$1::text AND call_id=$2::text
@@ -1098,15 +1086,6 @@ func (q *Queries) ListVoiceLiveUncertainOperations(ctx context.Context, voiceSes
return items, nil
}
-const lockVoiceLiveReport = `-- name: LockVoiceLiveReport :exec
-SELECT id FROM task_meta_callback_messages WHERE id=$1::text FOR UPDATE
-`
-
-func (q *Queries) LockVoiceLiveReport(ctx context.Context, reportID string) error {
- _, err := q.db.Exec(ctx, lockVoiceLiveReport, reportID)
- return err
-}
-
const lockVoiceLiveSessionCurrent = `-- name: LockVoiceLiveSessionCurrent :one
SELECT (status IN ('provisioning','connected','reconnecting') AND live_lease_until>clock_timestamp())::boolean
FROM voice_sessions WHERE id=$1::text FOR UPDATE
diff --git a/apps/teamhub/internal/store/voice_live_tasks.sql.go b/apps/teamhub/internal/store/voice_live_tasks.sql.go
index ac26fd00..48ec67f9 100644
--- a/apps/teamhub/internal/store/voice_live_tasks.sql.go
+++ b/apps/teamhub/internal/store/voice_live_tasks.sql.go
@@ -238,6 +238,37 @@ func (q *Queries) GetVoiceLiveTask(ctx context.Context, arg GetVoiceLiveTaskPara
return i, err
}
+const getVoiceLiveTaskByWorkItem = `-- name: GetVoiceLiveTaskByWorkItem :one
+SELECT work_item_id, room_id, owner_actor_id, home_room_id, ordinal, voice_session_id, goal, surface, canceled_at, created_at FROM voice_live_tasks
+WHERE room_id=$1::text AND owner_actor_id=$2::text
+ AND work_item_id=$3::text
+`
+
+type GetVoiceLiveTaskByWorkItemParams struct {
+ RoomID string `json:"room_id"`
+ OwnerActorID string `json:"owner_actor_id"`
+ WorkItemID string `json:"work_item_id"`
+}
+
+// A call names a Task's output folder by its Work Item ID.
+func (q *Queries) GetVoiceLiveTaskByWorkItem(ctx context.Context, arg GetVoiceLiveTaskByWorkItemParams) (VoiceLiveTask, error) {
+ row := q.db.QueryRow(ctx, getVoiceLiveTaskByWorkItem, arg.RoomID, arg.OwnerActorID, arg.WorkItemID)
+ var i VoiceLiveTask
+ err := row.Scan(
+ &i.WorkItemID,
+ &i.RoomID,
+ &i.OwnerActorID,
+ &i.HomeRoomID,
+ &i.Ordinal,
+ &i.VoiceSessionID,
+ &i.Goal,
+ &i.Surface,
+ &i.CanceledAt,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
const listVoiceLivePendingApprovals = `-- name: ListVoiceLivePendingApprovals :many
SELECT decision.id,coalesce(decision.alter_ego_task_id,'')::text AS task_id,decision.kind,decision.view,
card.version AS card_version
diff --git a/apps/teamhub/internal/voice/voice_live.go b/apps/teamhub/internal/voice/voice_live.go
index 70007dd5..2f120203 100644
--- a/apps/teamhub/internal/voice/voice_live.go
+++ b/apps/teamhub/internal/voice/voice_live.go
@@ -213,10 +213,12 @@ func (s *Service) executeVoiceLiveTool(ctx context.Context, session voicelive.Se
return s.replyToVoiceLiveTask(ctx, session, request)
case voicelive.ToolCancelTask:
return s.cancelVoiceLiveTask(ctx, session, request)
- case voicelive.ToolTaskFiles:
- return s.voiceLiveTaskFiles(ctx, session, request)
- case voicelive.ToolPublishTaskResult:
- return s.publishVoiceLiveTaskResult(ctx, session, request)
+ case voicelive.ToolListFiles:
+ return s.listVoiceLiveFiles(ctx, session, request)
+ case voicelive.ToolReadFile:
+ return s.readVoiceLiveFile(ctx, session, request)
+ case voicelive.ToolSendCard:
+ return s.sendVoiceLiveCard(ctx, session, request)
case voicelive.ToolListTasks:
return s.listVoiceLiveTasks(ctx, session, request)
case voicelive.ToolDecideApproval:
diff --git a/apps/teamhub/internal/voice/voice_live_canvas.go b/apps/teamhub/internal/voice/voice_live_canvas.go
index 3f4fcc6f..cf63a0b5 100644
--- a/apps/teamhub/internal/voice/voice_live_canvas.go
+++ b/apps/teamhub/internal/voice/voice_live_canvas.go
@@ -324,8 +324,8 @@ func (s *Service) attachVoiceLiveEmailFile(ctx context.Context, session voiceliv
return "", voicelive.ErrInvalid
}
canvasID, fileID := strings.TrimSpace(args.DocumentID), strings.TrimSpace(args.FileDocumentID)
- taskID, file := strings.TrimSpace(args.TaskID), strings.TrimSpace(args.File)
- if canvasID == "" || (fileID == "") == (taskID == "") || file != "" && taskID == "" {
+ file := strings.TrimSpace(args.File)
+ if canvasID == "" || (fileID == "") == (file == "") {
return "", voicelive.ErrInvalid
}
principal, err := s.voiceLiveAgentPrincipal(ctx, session)
@@ -342,7 +342,7 @@ func (s *Service) attachVoiceLiveEmailFile(ctx context.Context, session voiceliv
if err != nil {
return "", err
}
- attachment, output, err := s.voiceLiveFileAttachment(ctx, session, principal, fileID, taskID, file)
+ attachment, output, err := s.voiceLiveFileAttachment(ctx, session, principal, fileID, file)
if output != "" || err != nil {
return output, err
}
diff --git a/apps/teamhub/internal/voice/voice_live_files.go b/apps/teamhub/internal/voice/voice_live_files.go
index 0328bdef..e3e26fb1 100644
--- a/apps/teamhub/internal/voice/voice_live_files.go
+++ b/apps/teamhub/internal/voice/voice_live_files.go
@@ -3,21 +3,18 @@ package voice
import (
"context"
"encoding/base64"
- "encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
- "mime"
"path"
+ "slices"
+ "strconv"
"strings"
"time"
"unicode/utf8"
"github.com/jackc/pgx/v5"
- artifactstore "github.com/simplexai-labs/linger/apps/teamhub/internal/artifact"
- "github.com/simplexai-labs/linger/apps/teamhub/internal/document"
- "github.com/simplexai-labs/linger/apps/teamhub/internal/messagecreation"
"github.com/simplexai-labs/linger/apps/teamhub/internal/roomagent"
"github.com/simplexai-labs/linger/apps/teamhub/internal/store"
"github.com/simplexai-labs/linger/apps/teamhub/internal/voicelive"
@@ -25,151 +22,334 @@ import (
voiceapi "github.com/simplexai-labs/linger/contracts-go/teamhubinternal"
)
-// The scope is resolved from a persisted delegation, never from model-supplied
-// tenant/agent/room IDs or a host filesystem path.
-func (s *Service) voiceTaskComputer(ctx context.Context, session voicelive.Session, handle string) (store.VoiceLiveTask, roomagent.LocalComputerTools, api.LocalComputerToolCall, error) {
- ordinal, ok := voicelive.TaskOrdinal(handle)
- if !ok {
- return store.VoiceLiveTask{}, nil, api.LocalComputerToolCall{}, voicelive.ErrInvalid
+const (
+ // maxVoiceLiveFileBytes bounds one file the live voice reads whole, to
+ // attach it to an email or a Slack message.
+ maxVoiceLiveFileBytes = 32 << 20
+ // voiceLiveReadChunk is one read of a file; its base64 fits the Runner
+ // Gateway's 256 KiB string limit.
+ voiceLiveReadChunk = 192 << 10
+ // voiceLiveCatBytes is what cat reads to print its first characters.
+ voiceLiveCatBytes = 12 << 10
+ voiceLiveCatRunes = 3000
+ // voiceLiveCardDeadline lets a card's files upload from the Computer.
+ voiceLiveCardDeadline = 120_000
+)
+
+// voiceLiveFolder is one folder of ./playground the call may open.
+type voiceLiveFolder struct {
+ display string
+ // folder names it to the Computer: a Task's output or the Room's own.
+ folder map[string]any
+ // roomID is where a card with its files goes; taskID is set for a Task.
+ roomID, taskID string
+}
+
+// voiceLiveFolder resolves ./playground/<name>/ from what the call may open:
+// this Room's own folder, or the output of a task the call's user gave it and
+// its Agent coordinates. It never trusts a model-supplied host path.
+func (s *Service) voiceLiveFolder(ctx context.Context, session voicelive.Session, name string) (voiceLiveFolder, error) {
+ display := voicelive.PlaygroundRoot + name + "/"
+ if name == session.RoomID {
+ return voiceLiveFolder{display: display, folder: map[string]any{"room_id": name}, roomID: name}, nil
+ }
+ task, err := s.queries.GetVoiceLiveTaskByWorkItem(ctx, store.GetVoiceLiveTaskByWorkItemParams{RoomID: session.RoomID, OwnerActorID: session.HumanActorID, WorkItemID: name})
+ if errors.Is(err, pgx.ErrNoRows) {
+ return voiceLiveFolder{}, voicelive.ErrNotFound
}
- task, err := s.queries.GetVoiceLiveTask(ctx, store.GetVoiceLiveTaskParams{RoomID: session.RoomID, OwnerActorID: session.HumanActorID, Ordinal: ordinal})
if err != nil {
- return task, nil, api.LocalComputerToolCall{}, err
+ return voiceLiveFolder{}, err
}
authorized, err := s.queries.VoiceLiveTaskCoordinatedBy(ctx, store.VoiceLiveTaskCoordinatedByParams{TaskID: task.WorkItemID, TenantID: session.TenantID, CoordinatorActorID: session.Agent.ID})
if err != nil {
- return task, nil, api.LocalComputerToolCall{}, err
+ return voiceLiveFolder{}, err
}
if !authorized {
- return task, nil, api.LocalComputerToolCall{}, voicelive.ErrNotFound
+ return voiceLiveFolder{}, voicelive.ErrNotFound
}
+ return voiceLiveFolder{display: display, folder: map[string]any{"task_id": task.WorkItemID, "origin_room_id": task.HomeRoomID},
+ roomID: task.HomeRoomID, taskID: task.WorkItemID}, nil
+}
+
+// callVoiceLivePlayground runs one file action on the Computer of the
+// call's Agent.
+func (s *Service) callVoiceLivePlayground(ctx context.Context, session voicelive.Session, name string, arguments map[string]any, deadlineMS int) (map[string]any, error) {
target, _, ok, err := s.voiceLiveBrowserTarget(ctx, session)
if err != nil {
- return task, nil, api.LocalComputerToolCall{}, err
+ return nil, err
}
tools, supported := s.localComputers.(roomagent.LocalComputerTools)
if !ok || !supported {
- return task, nil, api.LocalComputerToolCall{}, &roomagent.LocalComputerToolError{Code: "computer_unavailable", Message: "Connect the task's Local Computer"}
- }
- call := api.LocalComputerToolCall{TenantId: session.TenantID, OwnerActorId: session.HumanActorID, ComputerId: target.ComputerID, AgentId: target.AgentManagementID, ToolSessionId: session.ID, Server: api.TaskFiles}
- call.TaskScope = &struct {
- AgentId string `json:"agent_id"`
- OriginRoomId string `json:"origin_room_id"`
- TaskId string `json:"task_id"`
- TenantId string `json:"tenant_id"`
- }{AgentId: target.AgentManagementID, OriginRoomId: task.HomeRoomID, TaskId: task.WorkItemID, TenantId: session.TenantID}
- return task, tools, call, nil
+ return nil, &roomagent.LocalComputerToolError{Code: "computer_offline", Message: "The user's computer is not connected."}
+ }
+ call := api.LocalComputerToolCall{TenantId: session.TenantID, OwnerActorId: session.HumanActorID, ComputerId: target.ComputerID,
+ AgentId: target.AgentManagementID, ToolSessionId: session.ID, Server: api.Playground, ToolName: name, Arguments: arguments}
+ if deadlineMS > 0 {
+ call.DeadlineMs = &deadlineMS
+ }
+ return tools.CallLocalComputerTool(ctx, call)
}
-func (s *Service) voiceLiveTaskFiles(ctx context.Context, session voicelive.Session, request voiceapi.VoiceLiveToolCall) (string, error) {
- var args voicelive.TaskFilesArguments
- if voicelive.DecodeArguments(request.Arguments, &args) != nil || (args.Action != "list" && args.Action != "read") {
- return "", voicelive.ErrInvalid
+// voiceLiveFileError is what the live model is told when a file action fails.
+func voiceLiveFileError(err error) (string, error) {
+ var local *roomagent.LocalComputerToolError
+ if errors.As(err, &local) {
+ return voicelive.Output(map[string]string{"error": local.Code, "detail": local.Message}), nil
+ }
+ if errors.Is(err, voicelive.ErrNotFound) {
+ return voicelive.Output(map[string]string{"error": "folder_not_found", "next": "ls ./playground/ lists the folders you can open."}), nil
+ }
+ return "", err
+}
+
+// voiceLiveFilePath resolves a file path the model gave.
+func (s *Service) voiceLiveFilePath(ctx context.Context, session voicelive.Session, raw string) (voiceLiveFolder, string, string, error) {
+ parsed, ok := voicelive.ParsePlaygroundPath(raw)
+ if !ok {
+ return voiceLiveFolder{}, "", voicelive.ErrorOutput("invalid_file_path"), nil
+ }
+ if parsed.Folder == "" || parsed.Inside == "" {
+ return voiceLiveFolder{}, "", voicelive.ErrorOutput("not_a_file"), nil
}
- task, tools, call, err := s.voiceTaskComputer(ctx, session, args.TaskID)
+ folder, err := s.voiceLiveFolder(ctx, session, parsed.Folder)
if err != nil {
- return voiceFileError(err)
+ output, err := voiceLiveFileError(err)
+ return voiceLiveFolder{}, "", output, err
}
- call.ToolName = "list_files"
- if args.Action == "read" {
- call.ToolName = "read_file"
+ return folder, parsed.Inside, "", nil
+}
+
+// listVoiceLiveFiles prints a folder like ls -lh.
+func (s *Service) listVoiceLiveFiles(ctx context.Context, session voicelive.Session, request voiceapi.VoiceLiveToolCall) (string, error) {
+ var args voicelive.PathArguments
+ if voicelive.DecodeArguments(request.Arguments, &args) != nil {
+ return "", voicelive.ErrInvalid
+ }
+ parsed, ok := voicelive.ParsePlaygroundPath(args.Path)
+ if !ok {
+ return voicelive.ErrorOutput("invalid_file_path"), nil
}
- call.Arguments = map[string]any{"path": voicelive.TaskFilePath(args.Path, task.WorkItemID), "offset": 0}
- result, err := tools.CallLocalComputerTool(ctx, call)
+ if parsed.Folder == "" {
+ return s.listVoiceLiveFolders(ctx, session)
+ }
+ folder, err := s.voiceLiveFolder(ctx, session, parsed.Folder)
+ if err != nil {
+ return voiceLiveFileError(err)
+ }
+ result, err := s.callVoiceLivePlayground(ctx, session, "list", map[string]any{"folder": folder.folder, "path": parsed.Inside}, 0)
if err != nil {
- return voiceFileError(err)
+ return voiceLiveFileError(err)
+ }
+ var listed struct {
+ Files []struct {
+ Name string `json:"name"`
+ Directory bool `json:"directory"`
+ Size int64 `json:"size"`
+ Modified string `json:"modified_ns"`
+ } `json:"files"`
+ Total int `json:"total"`
+ }
+ if err := remarshal(result, &listed); err != nil {
+ return "", err
+ }
+ entries := make([]voicelive.ListEntry, 0, len(listed.Files))
+ for _, file := range listed.Files {
+ entry := voicelive.ListEntry{Name: file.Name, Directory: file.Directory, Size: file.Size}
+ if nanos, err := strconv.ParseInt(file.Modified, 10, 64); err == nil {
+ entry.Modified = time.Unix(0, nanos)
+ }
+ entries = append(entries, entry)
}
- if args.Action == "list" {
- return voicelive.Output(result), nil
+ display := folder.display
+ if parsed.Inside != "" {
+ display += strings.TrimSuffix(parsed.Inside, "/") + "/"
}
- chunk, err := decodeVoiceFileChunk(result)
+ return voicelive.FormatListing(display, entries, listed.Total), nil
+}
+
+// listVoiceLiveFolders prints ./playground/: the Room's own folder and the
+// output folder of each task this call can talk about.
+func (s *Service) listVoiceLiveFolders(ctx context.Context, session voicelive.Session) (string, error) {
+ views, err := s.voiceLiveTaskViews(ctx, session)
if err != nil {
- return voiceFileError(err)
+ return "", err
}
- if !utf8.Valid(chunk.data) {
- return voicelive.ErrorOutput("not_text_use_publish_task_result"), nil
+ var listing strings.Builder
+ listing.WriteString(voicelive.PlaygroundRoot + "\n")
+ fmt.Fprintf(&listing, "%s/ this room's own files\n", session.RoomID)
+ for _, view := range views {
+ if view.WorkItemID != "" {
+ fmt.Fprintf(&listing, "%s/ %s output: %s\n", view.WorkItemID, voicelive.TaskID(view.Ordinal), voicelive.Snippet(view.Goal))
+ }
}
- text, truncated := voicelive.Truncate(string(chunk.data), 3000)
- return voicelive.Output(map[string]any{"text": text, "truncated": truncated || !chunk.EOF, "size": chunk.Size}), nil
+ return listing.String(), nil
}
-func voiceFileError(err error) (string, error) {
- var local *roomagent.LocalComputerToolError
- if errors.As(err, &local) {
- return voicelive.Output(map[string]string{"error": local.Code, "detail": local.Message}), nil
+// readVoiceLiveFile prints the first characters of a text file like cat.
+func (s *Service) readVoiceLiveFile(ctx context.Context, session voicelive.Session, request voiceapi.VoiceLiveToolCall) (string, error) {
+ var args voicelive.PathArguments
+ if voicelive.DecodeArguments(request.Arguments, &args) != nil {
+ return "", voicelive.ErrInvalid
+ }
+ folder, inside, output, err := s.voiceLiveFilePath(ctx, session, args.Path)
+ if output != "" || err != nil {
+ return output, err
}
- if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, voicelive.ErrNotFound) {
- return voicelive.ErrorOutput("task_not_found"), nil
+ result, err := s.callVoiceLivePlayground(ctx, session, "read", map[string]any{"folder": folder.folder, "path": inside, "offset": 0, "limit": voiceLiveCatBytes}, 0)
+ if err != nil {
+ return voiceLiveFileError(err)
+ }
+ chunk, err := decodeVoiceLiveChunk(result)
+ if err != nil {
+ return "", err
+ }
+ data := chunk.data
+ if !chunk.EOF {
+ // The read may end inside a character.
+ for cut := 0; cut < utf8.UTFMax && len(data) > 0 && !utf8.Valid(data); cut++ {
+ data = data[:len(data)-1]
+ }
+ }
+ if !utf8.Valid(data) {
+ return voicelive.ErrorOutput("not_text"), nil
+ }
+ text, truncated := voicelive.Truncate(string(data), voiceLiveCatRunes)
+ if truncated || !chunk.EOF {
+ text += fmt.Sprintf("\n… truncated (%s total)", voicelive.HumanSize(chunk.Size))
+ }
+ return text, nil
+}
+
+// sendVoiceLiveCard posts a card with files as the call's Agent. The Computer
+// reads the files and commits the card through the Agent API, as `teamhub
+// message card --attach` does; a Task whose files it carries counts as told.
+func (s *Service) sendVoiceLiveCard(ctx context.Context, session voicelive.Session, request voiceapi.VoiceLiveToolCall) (string, error) {
+ var args voicelive.SendCardArguments
+ if voicelive.DecodeArguments(request.Arguments, &args) != nil {
+ return "", voicelive.ErrInvalid
}
- if errors.Is(err, voicelive.ErrInvalid) {
+ title, content := strings.TrimSpace(args.Title), strings.TrimSpace(args.Content)
+ if title == "" || utf8.RuneCountInString(title) > 120 || strings.ContainsAny(title, "\r\n") || content == "" ||
+ utf8.RuneCountInString(content) > 20000 || len(args.Attach) > voicelive.MaxCardFiles {
return "", voicelive.ErrInvalid
}
- return "", err
+ // A Task's result goes to the Room that coordinates the Task, which is
+ // this Room unless the Task came from a group Room.
+ roomID, files, tasks := "", make([]map[string]any, 0, len(args.Attach)), []string{}
+ for _, raw := range args.Attach {
+ folder, inside, output, err := s.voiceLiveFilePath(ctx, session, raw)
+ if output != "" || err != nil {
+ return output, err
+ }
+ if roomID != "" && folder.roomID != roomID {
+ return voicelive.ErrorOutput("files_from_different_rooms"), nil
+ }
+ roomID = folder.roomID
+ if folder.taskID != "" && !slices.Contains(tasks, folder.taskID) {
+ tasks = append(tasks, folder.taskID)
+ }
+ format, mediaType := voicelive.FileType(path.Base(inside))
+ files = append(files, map[string]any{"folder": folder.folder, "path": inside, "representation_format": format, "media_type": mediaType})
+ }
+ if roomID == "" {
+ roomID = session.RoomID
+ }
+ current, err := s.voiceLiveCurrent(ctx, session)
+ if err != nil {
+ return "", err
+ }
+ if !current {
+ // A call that handed over may not post its result as well.
+ return "", voicelive.ErrNotFound
+ }
+ result, err := s.callVoiceLivePlayground(ctx, session, "send_card", map[string]any{
+ "operation_id": "voice-live:" + session.ID + ":" + request.CallId, "inbox_id": "room:" + roomID,
+ "title": title, "content": content, "files": files,
+ }, voiceLiveCardDeadline)
+ if err != nil {
+ return voiceLiveFileError(err)
+ }
+ messageID, _ := result["message_id"].(string)
+ if messageID == "" {
+ return voicelive.Output(map[string]string{"error": "outcome_unknown", "detail": "The card may have been posted; check the chat before trying again."}), nil
+ }
+ if err := s.markVoiceLiveTasksTold(ctx, session, tasks, messageID); err != nil {
+ return "", err
+ }
+ return voicelive.Output(map[string]any{"status": "delivered", "message_id": messageID, "documents": result["documents"]}), nil
}
-type voiceFileChunk struct {
- Data string `json:"data_base64"`
- Size int64 `json:"size"`
- Modified string `json:"modified_ns"`
- Offset int64 `json:"offset"`
- Next int64 `json:"next_offset"`
- EOF bool `json:"eof"`
- data []byte
+// voiceLiveCurrent reports whether the call still holds the live lease.
+func (s *Service) voiceLiveCurrent(ctx context.Context, session voicelive.Session) (bool, error) {
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return false, err
+ }
+ defer tx.Rollback(ctx)
+ return s.queries.WithTx(tx).LockVoiceLiveSessionCurrent(ctx, session.ID)
}
-func decodeVoiceFileChunk(result map[string]any) (voiceFileChunk, error) {
- var chunk voiceFileChunk
- raw, err := json.Marshal(result)
- if err == nil {
- err = json.Unmarshal(raw, &chunk)
+// markVoiceLiveTasksTold records each Task's latest report as delivered by
+// the card, so a switch does not ask the Meta to deliver it again.
+func (s *Service) markVoiceLiveTasksTold(ctx context.Context, session voicelive.Session, tasks []string, messageID string) error {
+ if len(tasks) == 0 {
+ return nil
}
+ tx, err := s.pool.Begin(ctx)
if err != nil {
- return chunk, err
+ return err
}
- chunk.data, err = base64.StdEncoding.DecodeString(chunk.Data)
- if err != nil || chunk.Modified == "" || chunk.Size < 0 || chunk.Offset < 0 || chunk.Next != chunk.Offset+int64(len(chunk.data)) || chunk.Next > chunk.Size || chunk.EOF != (chunk.Next == chunk.Size) || len(chunk.data) > 512*1024 {
- return chunk, voicelive.ErrInvalid
+ defer tx.Rollback(ctx)
+ queries := s.queries.WithTx(tx)
+ for _, task := range tasks {
+ report, err := queries.GetVoiceLiveTaskLatestReport(ctx, store.GetVoiceLiveTaskLatestReportParams{TaskID: task, CoordinatorActorID: session.Agent.ID, TenantID: session.TenantID})
+ if errors.Is(err, pgx.ErrNoRows) {
+ continue
+ }
+ if err != nil {
+ return err
+ }
+ if err = queries.CreateVoiceLiveReportDelivery(ctx, store.CreateVoiceLiveReportDeliveryParams{ReportID: report, VoiceSessionID: session.ID, MessageID: messageID}); err != nil {
+ return err
+ }
+ if err = queries.MarkVoiceLiveReportNonActionable(ctx, report); err != nil {
+ return err
+ }
}
- return chunk, nil
+ return tx.Commit(ctx)
}
-// Each read is bounded. Size/mtime must stay constant across chunks; changing
-// outputs never become an apparently successful mixed-version attachment.
-func (s *Service) stageVoiceTaskFile(ctx context.Context, tools roomagent.LocalComputerTools, call api.LocalComputerToolCall, filename string) (artifactstore.Object, error) {
- reader, writer := io.Pipe()
- go func() {
- _ = writer.CloseWithError(copyVoiceTaskFile(ctx, tools, call, filename, writer))
- }()
- defer reader.Close()
- return s.artifacts.Put(ctx, reader)
+// readVoiceLiveFileWhole reads a whole file into memory, chunk by chunk, to
+// attach it to an email or a Slack message. It fails when the file changes
+// while it is read.
+func (s *Service) readVoiceLiveFileWhole(ctx context.Context, session voicelive.Session, folder voiceLiveFolder, inside string, w io.Writer) error {
+ return copyVoiceLiveFile(func(offset int64) (map[string]any, error) {
+ return s.callVoiceLivePlayground(ctx, session, "read", map[string]any{"folder": folder.folder, "path": inside, "offset": offset, "limit": voiceLiveReadChunk}, 0)
+ }, w)
}
-// maxVoiceTaskFileBytes bounds one task output the live voice reads whole.
-const maxVoiceTaskFileBytes = 32 << 20
-
-// copyVoiceTaskFile writes one task output file to w, chunk by chunk, and
-// fails when the file changes while it is read.
-func copyVoiceTaskFile(ctx context.Context, tools roomagent.LocalComputerTools, call api.LocalComputerToolCall, filename string, w io.Writer) error {
+// copyVoiceLiveFile joins the reads read returns from each offset.
+func copyVoiceLiveFile(read func(offset int64) (map[string]any, error), w io.Writer) error {
var size int64 = -1
var modified string
var offset int64
for {
- call.ToolName = "read_file"
- call.Arguments = map[string]any{"path": filename, "offset": offset}
- result, err := tools.CallLocalComputerTool(ctx, call)
+ result, err := read(offset)
if err != nil {
return err
}
- chunk, err := decodeVoiceFileChunk(result)
+ chunk, err := decodeVoiceLiveChunk(result)
if err != nil {
return err
}
if size < 0 {
- size = chunk.Size
- modified = chunk.Modified
+ size, modified = chunk.Size, chunk.Modified
+ }
+ if size > maxVoiceLiveFileBytes {
+ return &roomagent.LocalComputerToolError{Code: "file_too_large", Message: "The file is over 32 MiB."}
}
- if size > maxVoiceTaskFileBytes || chunk.Size != size || chunk.Modified != modified || chunk.Offset != offset || (!chunk.EOF && chunk.Next <= offset) {
- return errors.New("task output changed or exceeds 32 MiB")
+ if chunk.Size != size || chunk.Modified != modified || chunk.Offset != offset || (!chunk.EOF && chunk.Next <= offset) {
+ return &roomagent.LocalComputerToolError{Code: "file_changed", Message: "The file changed while it was read; try again."}
}
if _, err = w.Write(chunk.data); err != nil {
return err
@@ -181,128 +361,34 @@ func copyVoiceTaskFile(ctx context.Context, tools roomagent.LocalComputerTools,
}
}
-func (s *Service) publishVoiceLiveTaskResult(ctx context.Context, session voicelive.Session, request voiceapi.VoiceLiveToolCall) (string, error) {
- var args voicelive.PublishTaskResultArguments
- if voicelive.DecodeArguments(request.Arguments, &args) != nil || args.ReportID == "" || strings.TrimSpace(args.Text) == "" || utf8.RuneCountInString(args.Text) > 20000 || strings.TrimSpace(args.Title) == "" || utf8.RuneCountInString(args.Title) > 120 || len(args.Files) > 5 {
- return "", voicelive.ErrInvalid
- }
- // A question/text-only report does not require an online Computer.
- ordinal, ok := voicelive.TaskOrdinal(args.TaskID)
- if !ok {
- return "", voicelive.ErrInvalid
- }
- task, err := s.queries.GetVoiceLiveTask(ctx, store.GetVoiceLiveTaskParams{RoomID: session.RoomID, OwnerActorID: session.HumanActorID, Ordinal: ordinal})
- if err != nil {
- return voiceFileError(err)
- }
- if _, err = s.queries.GetVoiceLiveReportTask(ctx, store.GetVoiceLiveReportTaskParams{ReportID: args.ReportID, TaskID: task.WorkItemID, CoordinatorActorID: session.Agent.ID, TenantID: session.TenantID}); err != nil {
- return voiceFileError(err)
- }
- prior, err := s.queries.GetVoiceLiveReportDelivery(ctx, args.ReportID)
- if err == nil {
- return voicelive.Output(map[string]string{"status": "delivered", "message_id": prior, "room_id": task.HomeRoomID}), nil
- }
- if !errors.Is(err, pgx.ErrNoRows) {
- return "", err
- }
- objects := []artifactstore.Object{}
- commitAttempted := false
- defer func() {
- if !commitAttempted {
- cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
- defer cancel()
- for _, object := range objects {
- _ = artifactstore.DeleteDetached(cleanup, s.artifacts, object.Key)
- }
- }
- }()
- if len(args.Files) > 0 {
- task, tools, call, err := s.voiceTaskComputer(ctx, session, args.TaskID)
- if err != nil {
- return voiceFileError(err)
- }
- seen := map[string]bool{}
- for _, filename := range args.Files {
- filename = voicelive.TaskFilePath(filename, task.WorkItemID)
- if filename == "" || path.IsAbs(filename) || path.Clean(filename) != filename || filename == ".." || strings.HasPrefix(filename, "../") || seen[filename] {
- return voicelive.ErrorOutput("invalid_file_path"), nil
- }
- seen[filename] = true
- object, err := s.stageVoiceTaskFile(ctx, tools, call, filename)
- if err != nil {
- return voiceFileError(err)
- }
- objects = append(objects, object)
- }
- }
- tx, err := s.pool.Begin(ctx)
- if err != nil {
- return "", err
- }
- defer tx.Rollback(ctx)
- // Serialize close/lease loss against publication. A stale foreground can
- // finish reading bytes, but cannot publish a new result after handing over.
- queries := s.queries.WithTx(tx)
- current, err := queries.LockVoiceLiveSessionCurrent(ctx, session.ID)
- if err != nil {
- return "", err
- }
- if !current {
- return "", voicelive.ErrNotFound
- }
- if err = queries.LockVoiceLiveReport(ctx, args.ReportID); err != nil {
- return "", err
- }
- prior, err = queries.GetVoiceLiveReportDelivery(ctx, args.ReportID)
- if err == nil {
- return voicelive.Output(map[string]string{"status": "delivered", "message_id": prior, "room_id": task.HomeRoomID}), nil
- }
- if !errors.Is(err, pgx.ErrNoRows) {
- return "", err
- }
- segments := []messagecreation.Segment{{Type: "text", Content: args.Text}}
- versions := []string{}
- for index, object := range objects {
- name := path.Base(args.Files[index])
- extension := strings.ToLower(path.Ext(name))
- format := strings.TrimPrefix(extension, ".")
- if format == "" {
- format = "binary"
- }
- if format == "md" {
- format = "markdown"
- }
- mediaType := mime.TypeByExtension(extension)
- if mediaType == "" {
- mediaType = "application/octet-stream"
- }
- attachment, err := s.documents.CreateAgentMessageAttachmentTx(ctx, tx, document.CreateAgentMessageAttachmentInput{TenantID: session.TenantID, RoomID: task.HomeRoomID, AgentActorID: session.Agent.ID, AttachmentKey: fmt.Sprintf("live:%s:%d", args.ReportID, index), SourceInvocationID: request.CallId, Filename: name, RepresentationFormat: format, MediaType: mediaType, ObjectKey: object.Key, SizeBytes: object.Size, SHA256: hex.EncodeToString(object.SHA256[:])})
- if err != nil {
- return "", err
- }
- segments = append(segments, messagecreation.Segment{Type: "file", Content: name, DocumentID: attachment.DocumentID, DocumentVersionID: attachment.DocumentVersionID, Filename: name, MediaType: mediaType})
- versions = append(versions, attachment.DocumentVersionID)
+type voiceLiveChunk struct {
+ Data string `json:"data_base64"`
+ Size int64 `json:"size"`
+ Modified string `json:"modified_ns"`
+ Offset int64 `json:"offset"`
+ Next int64 `json:"next_offset"`
+ EOF bool `json:"eof"`
+ data []byte
+}
+
+func decodeVoiceLiveChunk(result map[string]any) (voiceLiveChunk, error) {
+ var chunk voiceLiveChunk
+ if err := remarshal(result, &chunk); err != nil {
+ return chunk, err
}
- content, err := messagecreation.Normalize(segments)
- if err != nil {
- return "", err
+ var err error
+ chunk.data, err = base64.StdEncoding.DecodeString(chunk.Data)
+ if err != nil || chunk.Modified == "" || chunk.Size < 0 || chunk.Offset < 0 || chunk.Next != chunk.Offset+int64(len(chunk.data)) ||
+ chunk.Next > chunk.Size || chunk.EOF != (chunk.Next == chunk.Size) || len(chunk.data) > voiceLiveReadChunk {
+ return chunk, voicelive.ErrInvalid
}
- created, err := messagecreation.Create(ctx, queries, messagecreation.Draft{TenantID: session.TenantID, RoomID: task.HomeRoomID, Author: session.Agent, Content: content, CardTitle: args.Title, AttachmentVersionIDs: versions, SuppressMentionSignals: true})
+ return chunk, nil
+}
+
+func remarshal(value any, target any) error {
+ raw, err := json.Marshal(value)
if err != nil {
- return "", err
- }
- if err = queries.CreateVoiceLiveReportDelivery(ctx, store.CreateVoiceLiveReportDeliveryParams{ReportID: args.ReportID, VoiceSessionID: session.ID, MessageID: created.Message.ID}); err != nil {
- return "", err
- }
- // It remains in history, but a switch must not ask Meta to deliver it again.
- if err = queries.MarkVoiceLiveReportNonActionable(ctx, args.ReportID); err != nil {
- return "", err
- }
- // A lost commit response does not prove rollback. Keep staged objects once
- // commit starts; otherwise an acknowledged publication could lose its files.
- commitAttempted = true
- if err = tx.Commit(ctx); err != nil {
- return "", err
+ return err
}
- return voicelive.Output(map[string]string{"status": "delivered", "message_id": created.Message.ID, "room_id": task.HomeRoomID}), nil
+ return json.Unmarshal(raw, target)
}
diff --git a/apps/teamhub/internal/voice/voice_live_files_test.go b/apps/teamhub/internal/voice/voice_live_files_test.go
index 5a3edfa4..73ac678c 100644
--- a/apps/teamhub/internal/voice/voice_live_files_test.go
+++ b/apps/teamhub/internal/voice/voice_live_files_test.go
@@ -2,17 +2,14 @@ package voice
import (
"bytes"
- "context"
"encoding/base64"
"io"
"testing"
-
- api "github.com/simplexai-labs/linger/contracts-go/nodeservicesinternal"
)
-func TestVoiceTaskFileChunksRejectMissingOrInconsistentBoundaries(t *testing.T) {
+func TestVoiceLiveChunksRejectMissingOrInconsistentBoundaries(t *testing.T) {
good := map[string]any{"data_base64": base64.StdEncoding.EncodeToString([]byte("hello")), "size": 5, "modified_ns": "1234567890123456789", "offset": 0, "next_offset": 5, "eof": true}
- chunk, err := decodeVoiceFileChunk(good)
+ chunk, err := decodeVoiceLiveChunk(good)
if err != nil || string(chunk.data) != "hello" {
t.Fatalf("valid chunk=%v %v", chunk, err)
}
@@ -22,44 +19,38 @@ func TestVoiceTaskFileChunksRejectMissingOrInconsistentBoundaries(t *testing.T)
bad[k] = v
}
bad[key] = value
- if _, err := decodeVoiceFileChunk(bad); err == nil {
+ if _, err := decodeVoiceLiveChunk(bad); err == nil {
t.Fatalf("accepted inconsistent %s", key)
}
}
}
-// fakeTaskFiles serves one task output file in chunks, optionally changing it
-// after the first read.
-type fakeTaskFiles struct {
- content []byte
- chunk int
- modified []string
- calls int
-}
-
-func (f *fakeTaskFiles) CallLocalComputerTool(_ context.Context, call api.LocalComputerToolCall) (map[string]any, error) {
- offset := int(call.Arguments["offset"].(int64))
- end := min(offset+f.chunk, len(f.content))
- modified := f.modified[min(f.calls, len(f.modified)-1)]
- f.calls++
- return map[string]any{
- "data_base64": base64.StdEncoding.EncodeToString(f.content[offset:end]), "size": len(f.content),
- "modified_ns": modified, "offset": offset, "next_offset": end, "eof": end == len(f.content),
- }, nil
+// chunkedFile serves one file in chunks, optionally changing it after the
+// first read.
+func chunkedFile(content []byte, size int, modified []string, calls *int) func(int64) (map[string]any, error) {
+ return func(offset int64) (map[string]any, error) {
+ end := min(int(offset)+size, len(content))
+ stamp := modified[min(*calls, len(modified)-1)]
+ *calls++
+ return map[string]any{
+ "data_base64": base64.StdEncoding.EncodeToString(content[offset:end]), "size": len(content),
+ "modified_ns": stamp, "offset": offset, "next_offset": end, "eof": end == len(content),
+ }, nil
+ }
}
-func TestCopyVoiceTaskFileReadsEveryChunkAndRefusesAChangingFile(t *testing.T) {
- files := &fakeTaskFiles{content: []byte("# ウォリアーズ brief\n116:113"), chunk: 7, modified: []string{"1"}}
+func TestCopyVoiceLiveFileReadsEveryChunkAndRefusesAChangingFile(t *testing.T) {
+ content := []byte("# ウォリアーズ brief\n116:113")
+ var calls int
var out bytes.Buffer
- if err := copyVoiceTaskFile(t.Context(), files, api.LocalComputerToolCall{}, "report.md", &out); err != nil || out.String() != string(files.content) || files.calls < 2 {
- t.Fatalf("copy=%q calls=%d err=%v", out.String(), files.calls, err)
+ if err := copyVoiceLiveFile(chunkedFile(content, 7, []string{"1"}, &calls), &out); err != nil || !bytes.Equal(out.Bytes(), content) || calls < 2 {
+ t.Fatalf("copy=%q calls=%d err=%v", out.String(), calls, err)
}
- changing := &fakeTaskFiles{content: []byte("0123456789"), chunk: 4, modified: []string{"1", "2"}}
- if err := copyVoiceTaskFile(t.Context(), changing, api.LocalComputerToolCall{}, "report.md", io.Discard); err == nil {
+ calls = 0
+ if err := copyVoiceLiveFile(chunkedFile([]byte("0123456789"), 4, []string{"1", "2"}, &calls), io.Discard); err == nil {
t.Fatal("a file that changed while read was accepted")
}
}
-
func TestVoiceLiveMediaTypeIsABareType(t *testing.T) {
for name, want := range map[string]string{"report.md": "text/markdown", "data.json": "application/json", "slides.pdf": "application/pdf", "blob": "application/octet-stream"} {
if got := voiceLiveMediaType(name, ""); got != want {
diff --git a/apps/teamhub/internal/voice/voice_live_slack.go b/apps/teamhub/internal/voice/voice_live_slack.go
index ba926d8a..2f94a968 100644
--- a/apps/teamhub/internal/voice/voice_live_slack.go
+++ b/apps/teamhub/internal/voice/voice_live_slack.go
@@ -35,8 +35,8 @@ type voiceLiveSlackCall func(slug string, arguments map[string]any) (map[string]
func (s *Service) sendVoiceLiveSlack(ctx context.Context, session voicelive.Session, request teamhubinternal.VoiceLiveToolCall, args voicelive.AppArguments) (string, error) {
text := strings.TrimSpace(args.Text)
channel, person, userID, thread := strings.TrimSpace(args.Channel), strings.TrimSpace(args.Person), strings.TrimSpace(args.UserID), strings.TrimSpace(args.ThreadTS)
- documentID, taskID, file := strings.TrimSpace(args.DocumentID), strings.TrimSpace(args.TaskID), strings.TrimSpace(args.File)
- attaching := documentID != "" || taskID != ""
+ documentID, file := strings.TrimSpace(args.DocumentID), strings.TrimSpace(args.File)
+ attaching := documentID != "" || file != ""
targets := 0
for _, target := range []bool{channel != "", person != "", userID != "", bool(args.ToSelf)} {
if target {
@@ -44,7 +44,7 @@ func (s *Service) sendVoiceLiveSlack(ctx context.Context, session voicelive.Sess
}
}
if text == "" && !attaching || utf8.RuneCountInString(text) > voicelive.MaxSlackTextRunes || targets != 1 || thread != "" && channel == "" ||
- documentID != "" && taskID != "" || file != "" && taskID == "" {
+ documentID != "" && file != "" {
return "", voicelive.ErrInvalid
}
app, output, err := s.voiceLiveApp(ctx, session, []string{"slack"}, args.Account)
@@ -83,7 +83,7 @@ func (s *Service) sendVoiceLiveSlack(ctx context.Context, session voicelive.Sess
}
var status, outcome string
if attaching {
- attachment, output, err := s.voiceLiveFileAttachment(ctx, session, app.principal, documentID, taskID, file)
+ attachment, output, err := s.voiceLiveFileAttachment(ctx, session, app.principal, documentID, file)
if output != "" || err != nil {
return output, err
}
@@ -155,33 +155,21 @@ type voiceLiveAttachment struct {
}
// voiceLiveFileAttachment reads the file a Slack send or an email canvas
-// attaches: a Document
-// the call's Agent reads, as its Agent download gives it, or a task's output
-// file on the user's Local Computer. output is what the live model is told
+// attaches: a Document the call's Agent reads, as its Agent download gives
+// it, or a file under ./playground on the user's Local Computer. output is what the live model is told
// instead when it cannot be read.
-func (s *Service) voiceLiveFileAttachment(ctx context.Context, session voicelive.Session, principal agentcredential.Principal, documentID, taskID, file string) (voiceLiveAttachment, string, error) {
- if taskID != "" && file == "" {
- // A task's output is a folder: the model must name one file in it.
- return voiceLiveAttachment{}, voicelive.Output(map[string]string{
- "error": "file_required", "next": "List this task's output files with task_files, then call again with the path of the one to attach.",
- }), nil
- }
- if taskID != "" {
- task, tools, call, err := s.voiceTaskComputer(ctx, session, taskID)
- if err != nil {
- output, err := voiceFileError(err)
+func (s *Service) voiceLiveFileAttachment(ctx context.Context, session voicelive.Session, principal agentcredential.Principal, documentID, file string) (voiceLiveAttachment, string, error) {
+ if file != "" {
+ folder, inside, output, err := s.voiceLiveFilePath(ctx, session, file)
+ if output != "" || err != nil {
return voiceLiveAttachment{}, output, err
}
- filename := voicelive.TaskFilePath(file, task.WorkItemID)
- if filename == "" || path.IsAbs(filename) || path.Clean(filename) != filename || filename == ".." || strings.HasPrefix(filename, "../") {
- return voiceLiveAttachment{}, voicelive.ErrorOutput("invalid_file_path"), nil
- }
var content bytes.Buffer
- if err := copyVoiceTaskFile(ctx, tools, call, filename, &content); err != nil {
- output, err := voiceFileError(err)
+ if err := s.readVoiceLiveFileWhole(ctx, session, folder, inside, &content); err != nil {
+ output, err := voiceLiveFileError(err)
return voiceLiveAttachment{}, output, err
}
- name := path.Base(filename)
+ name := path.Base(inside)
return voiceLiveAttachment{name: name, mediaType: voiceLiveMediaType(name, ""), content: content.Bytes()}, "", nil
}
download, err := s.documents.DownloadAgentFileConditional(ctx, principal.TenantID, principal.AgentID, documentID, "markdown", "")
@@ -193,7 +181,7 @@ func (s *Service) voiceLiveFileAttachment(ctx context.Context, session voicelive
}
content := download.InlineBytes
if content == nil {
- if download.SizeBytes > maxVoiceTaskFileBytes {
+ if download.SizeBytes > maxVoiceLiveFileBytes {
return voiceLiveAttachment{}, voicelive.ErrorOutput("file_too_large"), nil
}
object, err := s.artifacts.Open(ctx, download.ObjectKey)
@@ -201,11 +189,11 @@ func (s *Service) voiceLiveFileAttachment(ctx context.Context, session voicelive
return voiceLiveAttachment{}, "", err
}
defer object.Close()
- if content, err = io.ReadAll(io.LimitReader(object, maxVoiceTaskFileBytes+1)); err != nil {
+ if content, err = io.ReadAll(io.LimitReader(object, maxVoiceLiveFileBytes+1)); err != nil {
return voiceLiveAttachment{}, "", err
}
}
- if len(content) > maxVoiceTaskFileBytes {
+ if len(content) > maxVoiceLiveFileBytes {
return voiceLiveAttachment{}, voicelive.ErrorOutput("file_too_large"), nil
}
// The download names the stored file, which may be a rendering's own
diff --git a/apps/teamhub/internal/voice/voice_live_tasks.go b/apps/teamhub/internal/voice/voice_live_tasks.go
index dad32300..62052393 100644
--- a/apps/teamhub/internal/voice/voice_live_tasks.go
+++ b/apps/teamhub/internal/voice/voice_live_tasks.go
@@ -47,7 +47,7 @@ func (s *Service) voiceLiveTaskViews(ctx context.Context, session voicelive.Sess
runStarted := map[string]time.Time{}
for index, row := range rows {
records[index] = voicelive.TaskRecord{
- Ordinal: row.Ordinal, StartedHere: row.StartedHere, Goal: row.Goal, Surface: row.Surface,
+ Ordinal: row.Ordinal, WorkItemID: row.WorkItemID, StartedHere: row.StartedHere, Goal: row.Goal, Surface: row.Surface,
Canceled: row.CanceledAt.Valid, Execution: row.ExecutionStatus,
}
if row.ReportID != "" {
diff --git a/apps/teamhub/internal/voicelive/apps.go b/apps/teamhub/internal/voicelive/apps.go
index f1aeb4c0..3e33e4e6 100644
--- a/apps/teamhub/internal/voicelive/apps.go
+++ b/apps/teamhub/internal/voicelive/apps.go
@@ -105,7 +105,7 @@ var AppTools = []Tool{
{
Name: ToolSendSlack,
Description: "Send a Slack message from the user's connected Slack: to a channel (a channel_id from a Slack result, or a name such as #sales), into one of its threads with thread_ts, as a direct message to person (a colleague's name or email) or user_id (a result's author_id, to answer whoever wrote), or to_self for the user's own Slack DM with themself. Give exactly one of channel, person, user_id and to_self. " +
- "text is only what the user wants to say, in their words. To send a file, attach one: document_id for a document in this app (sent as Markdown, or as its original file), or task_id with file for a task's output (a path as task_files lists it); text is then the note with the file and may be empty. " +
+ "text is only what the user wants to say, in their words. To send a file, attach one: document_id for a document in this app (sent as Markdown, or as its original file), or file for a file on the user's computer (a path under ./playground as ls lists it, such as a task's output); text is then the note with the file and may be empty. " +
"It cannot be undone: first call without confirmed; it returns needs_confirmation with where it goes, the file and the text: say that and ask. Only after the user says yes in their next turn, call again with the same arguments and confirmed=true. " +
"Say it was sent only when the result is sent; outcome_unknown means it may have gone out: never send again. " + slackPerson + "channel_not_found or channel_ambiguous: ask which channel. " + accountChoice,
Parameters: objectSchema([]string{"confirmed"}, map[string]any{
@@ -116,8 +116,7 @@ var AppTools = []Tool{
"user_id": stringProperty("A Slack result's author_id, for a direct message"),
"to_self": map[string]any{"type": "boolean", "description": "Send to the user's own Slack DM with themself"},
"document_id": stringProperty("Optional document in this app to attach as a file"),
- "task_id": stringProperty("Optional task whose output file to attach, such as t1; needs file"),
- "file": stringProperty("With task_id: the output file's path, such as report.md"),
+ "file": stringProperty("Optional file to attach, such as ./playground/workitem_1d09.../report.md"),
"account": stringProperty("Optional Slack workspace account"),
"confirmed": map[string]any{"type": "boolean", "description": "Whether the user said yes to sending it, in their own next turn"},
}),
@@ -175,7 +174,6 @@ type AppArguments struct {
UserID string `json:"user_id"`
Since string `json:"since"`
ToSelf LooseBool `json:"to_self"`
- TaskID string `json:"task_id"`
File string `json:"file"`
}
diff --git a/apps/teamhub/internal/voicelive/canvas.go b/apps/teamhub/internal/voicelive/canvas.go
index 9a37b3ec..c82f18e5 100644
--- a/apps/teamhub/internal/voicelive/canvas.go
+++ b/apps/teamhub/internal/voicelive/canvas.go
@@ -70,14 +70,13 @@ var EditEmailCanvasTool = Tool{
// AttachEmailFileTool describes the tool that attaches a file to a canvas.
var AttachEmailFileTool = Tool{
Name: ToolAttachEmailFile,
- Description: "Attach a file to a Gmail canvas in this room, so the email goes out with it: a document or file in this app (one shared in a room or in the Library, such as a deck a task delivered; find its document_id with search_documents) or a task's output file (task_id with file, a path as task_files lists it). It is added at the end of the canvas at once; never call start_task for this. " +
- "Give exactly one of file_document_id and task_id. It returns the canvas's attachments and revision_id: tell the user in one short sentence what is attached. " +
+ Description: "Attach a file to a Gmail canvas in this room, so the email goes out with it: a document or file in this app (one shared in a room or in the Library, such as a deck a task delivered; find its document_id with search_documents) or a file on the user's computer (file, a path under ./playground as ls lists it, such as a task's output). It is added at the end of the canvas at once; never call start_task for this. " +
+ "Give exactly one of file_document_id and file. It returns the canvas's attachments and revision_id: tell the user in one short sentence what is attached. " +
"file_not_supported means the email cannot carry that kind of file (it takes PDF, Office, image, text and ZIP files); file_too_large means it is over 15 MB.",
Parameters: objectSchema([]string{"document_id"}, map[string]any{
"document_id": stringProperty("The canvas, from open_email_canvas"),
"file_document_id": stringProperty("The document or file in this app to attach, from search_documents"),
- "task_id": stringProperty("Or the task whose output file to attach, such as t1; needs file"),
- "file": stringProperty("With task_id: the output file's path, such as report.pptx"),
+ "file": stringProperty("Or a file such as ./playground/workitem_1d09.../report.pptx"),
}),
}
@@ -85,7 +84,6 @@ var AttachEmailFileTool = Tool{
type AttachEmailFileArguments struct {
DocumentID string `json:"document_id"`
FileDocumentID string `json:"file_document_id"`
- TaskID string `json:"task_id"`
File string `json:"file"`
}
diff --git a/apps/teamhub/internal/voicelive/playground.go b/apps/teamhub/internal/voicelive/playground.go
new file mode 100644
index 00000000..c5108dfd
--- /dev/null
+++ b/apps/teamhub/internal/voicelive/playground.go
@@ -0,0 +1,158 @@
+package voicelive
+
+import (
+ "fmt"
+ "mime"
+ "path"
+ "strings"
+ "time"
+)
+
+// The live voice reads and posts files in the folders a Meta Agent sees under
+// ./playground: <task id> holds a delegated Task's output, <room id> the
+// Room's own files. Paths are written the way the Meta and its Tasks write
+// them, so a path from a Task's report works as it is.
+const (
+ ToolListFiles = "ls"
+ ToolReadFile = "cat"
+ ToolSendCard = "send_card"
+)
+
+// PlaygroundRoot starts every path.
+const PlaygroundRoot = "./playground/"
+
+// MaxCardFiles is how many files one card carries.
+const MaxCardFiles = 5
+
+// PathArguments names one path.
+type PathArguments struct {
+ Path string `json:"path"`
+}
+
+// SendCardArguments is one card: a title, a one-line result and files.
+type SendCardArguments struct {
+ Title string `json:"title"`
+ Content string `json:"content"`
+ Attach []string `json:"attach"`
+}
+
+func init() {
+ Tools = append(Tools,
+ Tool{Name: ToolListFiles, Description: "List a folder on the user's computer, like ls -lh: size, modified time (UTC) and name; folders end with /. " +
+ "./playground/ lists the folders you can open: one per task of this call (./playground/<task folder>/, the folder its report names) and this room's own folder. " +
+ "Never guess a file exists: list first.",
+ Parameters: objectSchema(nil, map[string]any{"path": stringProperty("A folder such as ./playground/workitem_1d09.../; empty for ./playground/")})},
+ Tool{Name: ToolReadFile, Description: "Print a text file on the user's computer, like cat: its first 3000 characters, and how much more there is. " +
+ "not_text means it is an image, video or other binary file: send it with send_card instead of reading it.",
+ Parameters: objectSchema([]string{"path"}, map[string]any{"path": stringProperty("A file such as ./playground/workitem_1d09.../report.md")})},
+ Tool{Name: ToolSendCard, Description: "Post a card in the chat as yourself, like teamhub message card --attach: a one-line title, a one-line result and up to 5 files from ./playground. " +
+ "Use it to deliver a finished task's result with its files; each file becomes a document in the chat. It never sends as the user. " +
+ "Say it is in the chat only after it returns delivered; its documents can then be opened with page_action open_document. " +
+ "A task that failed is not a card: say what happened. upload_failed or outcome_unknown means it did not go out or may have: never send it twice before checking the chat.",
+ Parameters: objectSchema([]string{"title", "content"}, map[string]any{
+ "title": map[string]any{"type": "string", "maxLength": 120, "description": "The card's title, one line"},
+ "content": stringProperty("The one-line result, in the user's language"),
+ "attach": map[string]any{"type": "array", "maxItems": MaxCardFiles, "items": map[string]any{"type": "string"},
+ "description": "Files such as ./playground/workitem_1d09.../cartoon.png; no folders"},
+ })},
+ )
+}
+
+// PlaygroundPath is a path split into the folder it names and the path
+// inside that folder. Folder is empty for ./playground/ itself.
+type PlaygroundPath struct {
+ Folder, Inside string
+}
+
+// ParsePlaygroundPath reads ./playground/<folder>/<inside>. It is false for a
+// path outside ./playground or one that climbs out of its folder.
+func ParsePlaygroundPath(raw string) (PlaygroundPath, bool) {
+ cleaned := strings.TrimSpace(raw)
+ if strings.ContainsAny(cleaned, "\\\x00") || strings.HasPrefix(cleaned, "/") {
+ return PlaygroundPath{}, false
+ }
+ for _, segment := range strings.Split(cleaned, "/") {
+ if segment == ".." {
+ return PlaygroundPath{}, false
+ }
+ }
+ cleaned = path.Clean(cleaned)
+ if cleaned == "." || cleaned == "playground" {
+ return PlaygroundPath{}, true
+ }
+ rest, ok := strings.CutPrefix(cleaned, "playground/")
+ if !ok {
+ return PlaygroundPath{}, false
+ }
+ folder, inside, _ := strings.Cut(rest, "/")
+ return PlaygroundPath{Folder: folder, Inside: inside}, true
+}
+
+// FileType is the Document representation format and media type a file is
+// stored with, from its extension.
+func FileType(filename string) (format, mediaType string) {
+ extension := strings.ToLower(path.Ext(filename))
+ format = strings.TrimPrefix(extension, ".")
+ switch format {
+ case "":
+ format = "binary"
+ case "md":
+ format = "markdown"
+ }
+ mediaType = mime.TypeByExtension(extension)
+ if mediaType == "" {
+ mediaType = "application/octet-stream"
+ }
+ return format, mediaType
+}
+
+// ListEntry is one row of a folder listing.
+type ListEntry struct {
+ Name string
+ Directory bool
+ Size int64
+ Modified time.Time
+}
+
+// FormatListing prints a folder like ls -lh. total counts every entry the
+// folder holds, so a cut listing says how many are left out.
+func FormatListing(folder string, entries []ListEntry, total int) string {
+ var listing strings.Builder
+ listing.WriteString(folder + "\n")
+ if total == 0 {
+ listing.WriteString("(empty)\n")
+ }
+ for _, entry := range entries {
+ size, name := HumanSize(entry.Size), entry.Name
+ if entry.Directory {
+ size, name = "-", name+"/"
+ }
+ modified := "-"
+ if !entry.Modified.IsZero() {
+ modified = entry.Modified.UTC().Format("2006-01-02 15:04Z")
+ }
+ fmt.Fprintf(&listing, "%5s %s %s\n", size, modified, name)
+ }
+ if more := total - len(entries); more > 0 {
+ fmt.Fprintf(&listing, "… %d more\n", more)
+ }
+ return listing.String()
+}
+
+// HumanSize prints a byte count the way ls -lh does: 512, 3.7K, 197K, 12M.
+func HumanSize(size int64) string {
+ value, unit := float64(size), ""
+ for _, next := range []string{"K", "M", "G", "T"} {
+ if value < 1024 {
+ break
+ }
+ value, unit = value/1024, next
+ }
+ if unit == "" {
+ return fmt.Sprintf("%d", size)
+ }
+ if value < 10 {
+ return fmt.Sprintf("%.1f%s", value, unit)
+ }
+ return fmt.Sprintf("%.0f%s", value, unit)
+}
diff --git a/apps/teamhub/internal/voicelive/playground_test.go b/apps/teamhub/internal/voicelive/playground_test.go
new file mode 100644
index 00000000..3602197f
--- /dev/null
+++ b/apps/teamhub/internal/voicelive/playground_test.go
@@ -0,0 +1,58 @@
+package voicelive
+
+import (
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestParsePlaygroundPathKeepsInsideItsFolder(t *testing.T) {
+ for raw, want := range map[string]PlaygroundPath{
+ "": {},
+ "./playground/": {},
+ "playground": {},
+ "./playground/workitem_1/": {Folder: "workitem_1"},
+ "./playground/workitem_1/out/a.png": {Folder: "workitem_1", Inside: "out/a.png"},
+ "playground/room_1/notes.md": {Folder: "room_1", Inside: "notes.md"},
+ "./playground/workitem_1/./out//a.png": {Folder: "workitem_1", Inside: "out/a.png"},
+ } {
+ if got, ok := ParsePlaygroundPath(raw); !ok || got != want {
+ t.Errorf("ParsePlaygroundPath(%q)=%+v %v, want %+v", raw, got, ok, want)
+ }
+ }
+ for _, raw := range []string{"/etc/passwd", "./playground/workitem_1/../room_1/a", "../playground/x", "./other/a", "./playground/w\\a", "./playground/w/a\x00"} {
+ if got, ok := ParsePlaygroundPath(raw); ok {
+ t.Errorf("ParsePlaygroundPath(%q) accepted as %+v", raw, got)
+ }
+ }
+}
+
+func TestFormatListingReadsLikeLs(t *testing.T) {
+ modified := time.Date(2026, 11, 11, 10, 10, 2, 0, time.FixedZone("CST", 8*3600))
+ listing := FormatListing("./playground/workitem_1/", []ListEntry{
+ {Name: "out", Directory: true, Modified: modified},
+ {Name: "cartoon.png", Size: 201_728, Modified: modified},
+ }, 3)
+ for _, want := range []string{"./playground/workitem_1/\n", " - 2026-11-11 02:10Z out/\n", " 197K 2026-11-11 02:10Z cartoon.png\n", "… 1 more\n"} {
+ if !strings.Contains(listing, want) {
+ t.Fatalf("listing %q lacks %q", listing, want)
+ }
+ }
+ if got := FormatListing("./playground/", nil, 0); got != "./playground/\n(empty)\n" {
+ t.Fatalf("empty listing=%q", got)
+ }
+}
+
+func TestHumanSizeAndFileType(t *testing.T) {
+ for size, want := range map[int64]string{0: "0", 512: "512", 3800: "3.7K", 201_728: "197K", 12 << 20: "12M"} {
+ if got := HumanSize(size); got != want {
+ t.Errorf("HumanSize(%d)=%s, want %s", size, got, want)
+ }
+ }
+ for name, want := range map[string][2]string{"a.PNG": {"png", "image/png"}, "r.md": {"markdown", ""}, "blob": {"binary", "application/octet-stream"}} {
+ format, media := FileType(name)
+ if format != want[0] || (want[1] != "" && media != want[1]) {
+ t.Errorf("FileType(%s)=%s %s", name, format, media)
+ }
+ }
+}
diff --git a/apps/teamhub/internal/voicelive/task_files.go b/apps/teamhub/internal/voicelive/task_files.go
deleted file mode 100644
index 071d1d19..00000000
--- a/apps/teamhub/internal/voicelive/task_files.go
+++ /dev/null
@@ -1,52 +0,0 @@
-package voicelive
-
-import (
- "path"
- "strings"
-)
-
-// ToolTaskFiles names the existing-task output reader.
-const ToolTaskFiles = "task_files"
-
-// ToolPublishTaskResult names durable report publication.
-const ToolPublishTaskResult = "publish_task_result"
-
-// TaskFilesArguments selects a relative path inside an authorized task output root.
-type TaskFilesArguments struct {
- TaskID string `json:"task_id"`
- Action string `json:"action"`
- Path string `json:"path"`
-}
-
-// PublishTaskResultArguments selects a report and verified files for publication.
-type PublishTaskResultArguments struct {
- TaskID string `json:"task_id"`
- ReportID string `json:"report_id"`
- Title string `json:"title"`
- Text string `json:"text"`
- Files []string `json:"files"`
-}
-
-func init() {
- Tools = append(Tools, Tool{Name: ToolTaskFiles, Description: "Read an existing task's actual output directory directly on the user's Local Computer, without starting a Meta model or mounting a Meta workspace. action list lists paths; action read reads at most 3000 characters of a UTF-8 text file. Paths are relative to this task's own output root, such as report.md; the root is the folder the task calls ./playground/<its id>. Never guess a file exists: list first.", Parameters: objectSchema([]string{"task_id", "action"}, map[string]any{"task_id": stringProperty("Task handle such as t1"), "action": map[string]any{"type": "string", "enum": []string{"list", "read"}}, "path": stringProperty("Relative path, empty for the root")})},
- Tool{Name: ToolPublishTaskResult, Description: "Deliver a task report or question as an Agent message with its actual files. Call this before telling the user the result is delivered. Use report_id from list_tasks; publication is durable and happens only once per report. files are up to 5 relative task output paths verified with task_files; use an empty list for a question or a report without files. This never sends as the user. It uses the private coordinator room for tasks from group rooms. A completed task may be read after switching modes. Do not run the original task again.", Parameters: objectSchema([]string{"task_id", "report_id", "title", "text", "files"}, map[string]any{"task_id": stringProperty("Task handle"), "report_id": stringProperty("Exact latest report_id"), "title": stringProperty("Short result title"), "text": stringProperty("Result or question in the user's language"), "files": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "maxItems": 5}})})
-}
-
-// TaskFilePath is a path relative to the task's output root. A task names
-// its files from its own workspace, as ./playground/<task id>/report.md, and
-// the live model repeats that; the root is the playground's task folder.
-func TaskFilePath(raw, workItemID string) string {
- cleaned := path.Clean(strings.TrimSpace(raw))
- for _, prefix := range []string{"playground/" + workItemID, workItemID} {
- if cleaned == prefix {
- return ""
- }
- if rest, ok := strings.CutPrefix(cleaned, prefix+"/"); ok {
- return rest
- }
- }
- if cleaned == "." {
- return ""
- }
- return cleaned
-}
diff --git a/apps/teamhub/internal/voicelive/task_files_test.go b/apps/teamhub/internal/voicelive/task_files_test.go
deleted file mode 100644
index 23ac12f2..00000000
--- a/apps/teamhub/internal/voicelive/task_files_test.go
+++ /dev/null
@@ -1,23 +0,0 @@
-package voicelive
-
-import "testing"
-
-func TestTaskFilePathIsRelativeToTheTaskFolder(t *testing.T) {
- const task = "workitem_1d098ce43808c5d388b81b791cf335e8"
- for raw, want := range map[string]string{
- "./playground/" + task + "/report.md": "report.md",
- "playground/" + task + "/out/a.md": "out/a.md",
- "./playground/" + task: "",
- task + "/report.md": "report.md",
- "report.md": "report.md",
- " ./report.md ": "report.md",
- "": "",
- ".": "",
- "playground/workitem_other/report.md": "playground/workitem_other/report.md",
- "../" + task + "/report.md": "../" + task + "/report.md",
- } {
- if got := TaskFilePath(raw, task); got != want {
- t.Fatalf("%q: %q, want %q", raw, got, want)
- }
- }
-}
diff --git a/apps/teamhub/internal/voicelive/tasks.go b/apps/teamhub/internal/voicelive/tasks.go
index 3678e5e8..8590a652 100644
--- a/apps/teamhub/internal/voicelive/tasks.go
+++ b/apps/teamhub/internal/voicelive/tasks.go
@@ -119,7 +119,7 @@ var taskTools = []Tool{
{
Name: ToolListTasks,
Description: "See the user's tasks in this room: those of this call, and earlier ones still working or reported within the last day. Each task's goal, state (pending, working, waiting_for_approval, reported with its latest report, which may be a result or something it needs from the user, failed, canceled) and the latest steps. When asked how things are going, give the state of every task, canceled and finished ones included. Only pending and working mean something is being done right now; never say a task is still doing something in any other state. " +
- "Call it when the user asks how far along something is, whether it is done or what is being worked on, and to find a task_id; never answer progress from impression. " +
+ "Call it when the user asks how far along something is, whether it is done or what is being worked on, and to find a task_id or the folder its files are in; never answer progress from impression. " +
"scope=room instead reports every Agent still working in this room, the last ones that finished and background Tasks; for another room, get its room_id with find_rooms and pass it. " +
"The work is yours to the user: speak of it in the first person, picking the one or two lines that matter.",
Parameters: objectSchema([]string{}, map[string]any{
@@ -145,6 +145,8 @@ const ConfirmationValidFor = 10 * time.Minute
// TaskRecord is one voice task with the state of its delegated Task.
type TaskRecord struct {
Ordinal int32
+ // WorkItemID names the Task, and its output folder ./playground/<WorkItemID>/.
+ WorkItemID string
// StartedHere is set for tasks this call started.
StartedHere bool
Goal string
@@ -172,6 +174,7 @@ type TaskReport struct {
// TaskView is what Voice Runtime and the live model learn about one task.
type TaskView struct {
Ordinal int32
+ WorkItemID string
StartedHere bool
Goal string
Surface string
@@ -185,7 +188,7 @@ type TaskView struct {
// View reports one task in the terms of its delegated Task.
func View(record TaskRecord) TaskView {
view := TaskView{
- Ordinal: record.Ordinal, StartedHere: record.StartedHere, Goal: record.Goal, Surface: record.Surface,
+ Ordinal: record.Ordinal, WorkItemID: record.WorkItemID, StartedHere: record.StartedHere, Goal: record.Goal, Surface: record.Surface,
Report: record.Report, Steps: record.Steps, RunningFor: record.RunningFor, Approvals: record.Approvals,
}
switch {
@@ -210,6 +213,9 @@ func TaskListOutput(views []TaskView) map[string]any {
tasks := make([]map[string]any, 0, len(views))
for _, view := range views {
task := map[string]any{"task_id": TaskID(view.Ordinal), "goal": truncateRunes(view.Goal, 200), "state": view.State}
+ if view.WorkItemID != "" {
+ task["folder"] = PlaygroundRoot + view.WorkItemID + "/"
+ }
if len(view.Steps) > 0 {
task["recent_steps"] = view.Steps
}
@@ -218,7 +224,6 @@ func TaskListOutput(views []TaskView) map[string]any {
}
if view.Report != nil {
task["latest_report"] = Snippet(view.Report.Body)
- task["report_id"] = view.Report.ID
task["delivered"] = view.Report.Delivered
}
if len(view.Approvals) > 0 {
diff --git a/apps/teamhub/tests/integration/voice_live_canvas_test.go b/apps/teamhub/tests/integration/voice_live_canvas_test.go
index 0d0918d7..9653acce 100644
--- a/apps/teamhub/tests/integration/voice_live_canvas_test.go
+++ b/apps/teamhub/tests/integration/voice_live_canvas_test.go
@@ -459,8 +459,11 @@ func TestVoiceLiveWritesAndChangesAnEmailCanvasAsTheAgent(t *testing.T) {
if strings.Count(stateOf(), "](document-asset:") != 3 {
t.Fatalf("attachments at once=%v state=%q", results, stateOf())
}
- // A task's output is a folder: without a file the model is told to list it.
- if folder := call("attach-task", "attach_email_file", map[string]string{"document_id": documentID, "task_id": "t1"}); folder["error"] != "file_required" {
- t.Fatalf("attach of a task without a file=%v", folder)
+ // A file is named by its ./playground path: a folder is not a file, and a
+ // folder of no task of the call is not found.
+ for file, want := range map[string]string{"./playground/workitem_unknown/": "not_a_file", "./playground/workitem_unknown/a.png": "folder_not_found", "/etc/hosts": "invalid_file_path"} {
+ if attached := call("attach-"+want, "attach_email_file", map[string]string{"document_id": documentID, "file": file}); attached["error"] != want {
+ t.Fatalf("attach of %s=%v", file, attached)
+ }
}
}
diff --git a/apps/teamhub/tests/integration/voice_live_test.go b/apps/teamhub/tests/integration/voice_live_test.go
index 131c3719..a85761e3 100644
--- a/apps/teamhub/tests/integration/voice_live_test.go
+++ b/apps/teamhub/tests/integration/voice_live_test.go
@@ -711,28 +711,36 @@ func TestVoiceLiveTasksReportResultsAndWhatTheyWaitFor(t *testing.T) {
if _, err := env.pool.Exec(t.Context(), `DELETE FROM voice_sessions WHERE id='voice_session_told'`); err != nil {
t.Fatal(err)
}
- // Publication is a durable receipt, independent of the worker's tool call ID.
- var reportID string
- if err := env.pool.QueryRow(t.Context(), `SELECT id FROM task_meta_callback_messages WHERE task_id=$1 ORDER BY meta_seq DESC LIMIT 1`, workItem(first["task_id"])).Scan(&reportID); err != nil {
- t.Fatal(err)
- }
- publish := func(callID string) string {
+ // A Task's result is posted from its folder on the user's Computer; the
+ // folder is named by the Task, and the card waits for the Computer.
+ sendCard := func(callID string, attach ...string) map[string]any {
t.Helper()
- args, _ := json.Marshal(map[string]any{"task_id": first["task_id"], "report_id": reportID, "title": "Comparison ready", "text": "Sony at 1899 is the best fit, added to the cart.", "files": []string{}})
+ args, _ := json.Marshal(map[string]any{"title": "Comparison ready", "content": "Sony at 1899 is the best fit, added to the cart.", "attach": attach})
var result teamhubinternal.VoiceLiveToolResult
- decode(t, voiceRuntimeCall(t, env, http.MethodPost, "/internal/v1/voice/live-tool-calls", map[string]any{"voice_session_id": sessionID, "turn_id": "lt_publish", "call_id": callID, "name": "publish_task_result", "arguments": string(args)}, http.StatusOK), &result)
- return result.Output
+ decode(t, voiceRuntimeCall(t, env, http.MethodPost, "/internal/v1/voice/live-tool-calls", map[string]any{"voice_session_id": sessionID, "turn_id": "lt_card", "call_id": callID, "name": "send_card", "arguments": string(args)}, http.StatusOK), &result)
+ var output map[string]any
+ if err := json.Unmarshal([]byte(result.Output), &output); err != nil {
+ t.Fatalf("send_card output=%s", result.Output)
+ }
+ return output
}
- published := publish("publish-first")
- if !strings.Contains(published, `"status":"delivered"`) || publish("publish-again") != published {
- t.Fatalf("publication did not deduplicate: %s", published)
+ folder := "./playground/" + workItem(first["task_id"]) + "/"
+ for attach, want := range map[string]string{
+ folder + "compare.md": "computer_offline",
+ "./playground/workitem_unknown/a.png": "folder_not_found",
+ folder + "../" + workItem(second["task_id"]): "invalid_file_path",
+ folder: "not_a_file",
+ } {
+ if output := sendCard("card-"+want, attach); output["error"] != want {
+ t.Fatalf("send_card %s=%v, want %s", attach, output, want)
+ }
}
- if countRows(t, env, `SELECT count(*) FROM voice_live_report_deliveries WHERE report_id=$1`, reportID) != 1 || countRows(t, env, `SELECT count(*) FROM task_meta_callback_messages WHERE id=$1 AND non_actionable`, reportID) != 1 {
- t.Fatal("publication receipt or callback acknowledgement missing")
+ if countRows(t, env, `SELECT count(*) FROM voice_live_report_deliveries WHERE voice_session_id=$1`, sessionID) != 0 {
+ t.Fatal("a card that was not posted marked its report delivered")
}
decode(t, voiceRuntimeCall(t, env, http.MethodGet, "/internal/v1/voice/sessions/"+sessionID+"/live-tasks", nil, http.StatusOK), &tasks)
- if len(tasks.Tasks) != 1 || tasks.Tasks[0].TaskId != second["task_id"] {
- t.Fatalf("delivered old report still pending: %+v", tasks.Tasks)
+ if len(tasks.Tasks) != 2 || tasks.Tasks[0].TaskId != first["task_id"] || *tasks.Tasks[0].Replies[0].Delivered {
+ t.Fatalf("live tasks after an unposted card: %+v", tasks.Tasks)
}
}
diff --git a/apps/voice-runtime/acceptance/live-scenarios/scenarios.ts b/apps/voice-runtime/acceptance/live-scenarios/scenarios.ts
index 43d0e22a..1f243735 100644
--- a/apps/voice-runtime/acceptance/live-scenarios/scenarios.ts
+++ b/apps/voice-runtime/acceptance/live-scenarios/scenarios.ts
@@ -334,11 +334,11 @@ export function scenarioJobs(
};
case "end_voice_mode":
return { status: "done" };
- case "publish_task_result":
+ case "send_card":
return {
status: "delivered",
message_id: "m_published",
- room_id: "r_123",
+ documents: [],
};
default:
return { status: "ok", results: [] };
@@ -377,7 +377,7 @@ export function scenarioJobs(
goal: update.goal,
state: "reported",
latest_report: update.replies.at(-1),
- report_id: `report_${update.taskId}`,
+ folder: `./playground/workitem_${update.taskId}/`,
delivered: false,
},
],
diff --git a/apps/voice-runtime/src/live-prompts.ts b/apps/voice-runtime/src/live-prompts.ts
index 979a2781..36969277 100644
--- a/apps/voice-runtime/src/live-prompts.ts
+++ b/apps/voice-runtime/src/live-prompts.ts
@@ -19,7 +19,7 @@ function describe(update: UpdateCue) {
const task = `${update.taskId} (${JSON.stringify(update.goal.slice(0, 300))})`;
switch (update.kind) {
case "report":
- return `Task ${task} ended its turn with a report to you; it is in the latest context notes, written to you, not to the user. Decide what the user needs, as a coordinator would. If the work is done, say in two or three short sentences, about fifteen seconds, what it came to: the conclusion and at most two or three key facts, and offer more detail; first use list_tasks to obtain report_id, inspect any output paths with task_files, then call publish_task_result with the full result and files. Only say it is in chat after that succeeds. A question is also published with an empty files list. Never wake a Meta model to publish it. If it is blocked or asks for something only the user can give (log in, scan a code, connect Chrome, pick one, a missing detail, a yes before sending or paying), ask them that plainly in one or two sentences; pass their answer back with reply_to_task and the task goes on from where it stopped. Say only what the report states.`;
+ return `Task ${task} ended its turn with a report to you; it is in the latest context notes, written to you, not to the user. Decide what the user needs, as a coordinator would. If the work is done, say in two or three short sentences, about fifteen seconds, what it came to: the conclusion and at most two or three key facts, and offer more detail. When it made files, ls the folder its report names (list_tasks gives each task's folder) and send_card its title, one-line result and files; only say they are in the chat after send_card returns delivered. A result without files is only said. Never wake a Meta model to deliver it. If it is blocked or asks for something only the user can give (log in, scan a code, connect Chrome, pick one, a missing detail, a yes before sending or paying), ask them that plainly in one or two sentences; pass their answer back with reply_to_task and the task goes on from where it stopped. Say only what the report states.`;
case "browser":
return update.replies?.length
? "The local browser step you were waiting for did not finish. In one short sentence say so and offer to try again or to do it in the background."
diff --git a/apps/voice-runtime/src/live-worker.test.ts b/apps/voice-runtime/src/live-worker.test.ts
index 98093874..c545fd88 100644
--- a/apps/voice-runtime/src/live-worker.test.ts
+++ b/apps/voice-runtime/src/live-worker.test.ts
@@ -1266,9 +1266,7 @@ describe("LiveVoiceWorker background work", () => {
{
type: "function_calls",
update: true,
- calls: [
- { callId: "publish", name: "publish_task_result", arguments: "{}" },
- ],
+ calls: [{ callId: "publish", name: "send_card", arguments: "{}" }],
},
{ type: "response_finished", canceled: false },
);
diff --git a/apps/voice-runtime/src/live-worker.ts b/apps/voice-runtime/src/live-worker.ts
index 9cd007c7..64674267 100644
--- a/apps/voice-runtime/src/live-worker.ts
+++ b/apps/voice-runtime/src/live-worker.ts
@@ -70,6 +70,8 @@ const retryMs = 300;
* hears its real result instead of a timeout.
*/
const confirmedWriteTimeoutMs = 60_000;
+/** A card's files upload from the Computer for up to two minutes. */
+const sendCardTimeoutMs = 130_000;
/** A local browser step may wake a sleeping Computer before it runs. */
const browserTimeoutMs = 70_000;
/** A local browser step longer than this no longer holds the conversation. */
@@ -1573,8 +1575,8 @@ export class LiveVoiceWorker {
const result = await this.client.executeLiveToolCall(
request,
AbortSignal.timeout(
- call.name === "publish_task_result"
- ? 120_000
+ call.name === "send_card"
+ ? sendCardTimeoutMs
: parseArguments(call)?.confirmed === true
? confirmedWriteTimeoutMs
: (this.options.toolTimeoutMs ?? 15_000),
diff --git a/contracts/generated/go/nodeservicesinternal/openapi.gen.go b/contracts/generated/go/nodeservicesinternal/openapi.gen.go
index 7f1e3897..1c6af716 100644
--- a/contracts/generated/go/nodeservicesinternal/openapi.gen.go
+++ b/contracts/generated/go/nodeservicesinternal/openapi.gen.go
@@ -712,8 +712,8 @@ func (e InternalErrorCode) Valid() bool {
// Defines values for LocalComputerToolCallServer.
const (
- Browser LocalComputerToolCallServer = "browser"
- TaskFiles LocalComputerToolCallServer = "task_files"
+ Browser LocalComputerToolCallServer = "browser"
+ Playground LocalComputerToolCallServer = "playground"
)
// Valid indicates whether the value is a known member of the LocalComputerToolCallServer enum.
@@ -721,7 +721,7 @@ func (e LocalComputerToolCallServer) Valid() bool {
switch e {
case Browser:
return true
- case TaskFiles:
+ case Playground:
return true
default:
return false
@@ -1555,20 +1555,17 @@ type InternalErrorCode string
// LocalComputerToolCall defines model for LocalComputerToolCall.
type LocalComputerToolCall struct {
- AgentId string `json:"agent_id"`
- Arguments map[string]interface{} `json:"arguments"`
- ComputerId string `json:"computer_id"`
- OwnerActorId string `json:"owner_actor_id"`
- Server LocalComputerToolCallServer `json:"server"`
- TaskScope *struct {
- AgentId string `json:"agent_id"`
- OriginRoomId string `json:"origin_room_id"`
- TaskId string `json:"task_id"`
- TenantId string `json:"tenant_id"`
- } `json:"task_scope,omitempty"`
- TenantId string `json:"tenant_id"`
- ToolName string `json:"tool_name"`
- ToolSessionId string `json:"tool_session_id"`
+ AgentId string `json:"agent_id"`
+ Arguments map[string]interface{} `json:"arguments"`
+ ComputerId string `json:"computer_id"`
+
+ // DeadlineMs How long the Computer may take; 60000 when omitted.
+ DeadlineMs *int `json:"deadline_ms,omitempty"`
+ OwnerActorId string `json:"owner_actor_id"`
+ Server LocalComputerToolCallServer `json:"server"`
+ TenantId string `json:"tenant_id"`
+ ToolName string `json:"tool_name"`
+ ToolSessionId string `json:"tool_session_id"`
}
// LocalComputerToolCallServer defines model for LocalComputerToolCall.Server.
diff --git a/contracts/generated/go/runnergateway/wire.gen.go b/contracts/generated/go/runnergateway/wire.gen.go
index 172c24f9..5ce59174 100644
--- a/contracts/generated/go/runnergateway/wire.gen.go
+++ b/contracts/generated/go/runnergateway/wire.gen.go
@@ -2455,21 +2455,20 @@ func (OperationCancelled) RequiredFields() []string {
// ComputerToolCall mirrors the ComputerToolCall schema shape.
type ComputerToolCall struct {
- Type string `json:"type"`
- ProtocolVersion string `json:"protocol_version"`
- CommandID string `json:"command_id"`
- RunnerID string `json:"runner_id"`
- ConnectionEpoch uint64 `json:"connection_epoch"`
- TenantID string `json:"tenant_id"`
- OwnerActorID string `json:"owner_actor_id"`
- AgentID string `json:"agent_id"`
- ToolSessionID string `json:"tool_session_id"`
- Server string `json:"server"`
- ToolName string `json:"tool_name"`
- Arguments json.RawMessage `json:"arguments"`
- TaskScope *SharedTaskScope `json:"task_scope,omitempty"`
- DeadlineMs uint64 `json:"deadline_ms"`
- Kind string `json:"kind"`
+ Type string `json:"type"`
+ ProtocolVersion string `json:"protocol_version"`
+ CommandID string `json:"command_id"`
+ RunnerID string `json:"runner_id"`
+ ConnectionEpoch uint64 `json:"connection_epoch"`
+ TenantID string `json:"tenant_id"`
+ OwnerActorID string `json:"owner_actor_id"`
+ AgentID string `json:"agent_id"`
+ ToolSessionID string `json:"tool_session_id"`
+ Server string `json:"server"`
+ ToolName string `json:"tool_name"`
+ Arguments json.RawMessage `json:"arguments"`
+ DeadlineMs uint64 `json:"deadline_ms"`
+ Kind string `json:"kind"`
}
// FixedFields lists the keys whose value the schema fixes for a ComputerToolCall.
diff --git a/contracts/generated/typescript/src/generated/node-services-internal/types.ts b/contracts/generated/typescript/src/generated/node-services-internal/types.ts
index 28c48c81..1f04d691 100644
--- a/contracts/generated/typescript/src/generated/node-services-internal/types.ts
+++ b/contracts/generated/typescript/src/generated/node-services-internal/types.ts
@@ -1168,17 +1168,13 @@ export interface components {
agent_id: string;
tool_session_id: string;
/** @enum {string} */
- server: "browser" | "task_files";
+ server: "browser" | "playground";
tool_name: string;
arguments: {
[key: string]: unknown;
};
- task_scope?: {
- tenant_id: string;
- agent_id: string;
- origin_room_id: string;
- task_id: string;
- };
+ /** @description How long the Computer may take; 60000 when omitted. */
+ deadline_ms?: number;
};
LocalComputerToolResult: {
result: {
diff --git a/contracts/generated/typescript/src/generated/runner-gateway/schema.ts b/contracts/generated/typescript/src/generated/runner-gateway/schema.ts
index 08a5cac3..a243204c 100644
--- a/contracts/generated/typescript/src/generated/runner-gateway/schema.ts
+++ b/contracts/generated/typescript/src/generated/runner-gateway/schema.ts
@@ -4624,7 +4624,7 @@ export const runnerGatewayEnvelopeSchema = {
$ref: "#/$defs/Id",
},
server: {
- enum: ["browser", "task_files"],
+ enum: ["browser", "playground"],
},
tool_name: {
type: "string",
@@ -4634,9 +4634,6 @@ export const runnerGatewayEnvelopeSchema = {
arguments: {
$ref: "#/$defs/OpaqueObject",
},
- task_scope: {
- $ref: "#/$defs/SharedTaskScope",
- },
deadline_ms: {
type: "integer",
minimum: 1000,
diff --git a/contracts/generated/typescript/src/generated/runner-gateway/types.ts b/contracts/generated/typescript/src/generated/runner-gateway/types.ts
index b714dca8..61e66296 100644
--- a/contracts/generated/typescript/src/generated/runner-gateway/types.ts
+++ b/contracts/generated/typescript/src/generated/runner-gateway/types.ts
@@ -162,10 +162,6 @@ export type OperationAck = OperationIdentity & {
command_id: Id;
through_seq: PositiveInteger;
};
-/**
- * TeamHub identifier used as a single directory segment on every platform.
- */
-export type SharedTaskScopeId = string;
export type DaemonToAgentEnvelope =
| RunnerHello
| RunnerHeartbeat
@@ -934,24 +930,12 @@ export interface ComputerToolCall {
owner_actor_id: Id;
agent_id: Id;
tool_session_id: Id;
- server: "browser" | "task_files";
+ server: "browser" | "playground";
tool_name: string;
arguments: OpaqueObject;
- task_scope?: SharedTaskScope;
deadline_ms: number;
kind: "computer_tool";
}
-/**
- * TeamHub-trusted shared Task directory identity. The receiver resolves it under its own configured shared root; no host path crosses the protocol. A meta scope has no task_id; an alter_ego scope requires one.
- */
-export interface SharedTaskScope {
- version: 1;
- tenant_id: SharedTaskScopeId;
- agent_id: SharedTaskScopeId;
- origin_room_id: SharedTaskScopeId;
- role: "meta" | "alter_ego";
- task_id?: SharedTaskScopeId;
-}
export interface RunnerHello {
type: "runner.hello";
protocol_version: ProtocolVersion;
diff --git a/contracts/openapi/node-services-internal/openapi.yaml b/contracts/openapi/node-services-internal/openapi.yaml
index 60f97890..9996a621 100644
--- a/contracts/openapi/node-services-internal/openapi.yaml
+++ b/contracts/openapi/node-services-internal/openapi.yaml
@@ -2763,7 +2763,7 @@ components:
type: string
enum:
- browser
- - task_files
+ - playground
tool_name:
type: string
minLength: 1
@@ -2771,23 +2771,11 @@ components:
arguments:
type: object
additionalProperties: true
- task_scope:
- type: object
- additionalProperties: false
- required:
- - tenant_id
- - agent_id
- - origin_room_id
- - task_id
- properties:
- tenant_id:
- type: string
- agent_id:
- type: string
- origin_room_id:
- type: string
- task_id:
- type: string
+ deadline_ms:
+ type: integer
+ minimum: 1000
+ maximum: 120000
+ description: How long the Computer may take; 60000 when omitted.
LocalComputerToolResult:
type: object
additionalProperties: false
diff --git a/contracts/runner-gateway/envelope.schema.json b/contracts/runner-gateway/envelope.schema.json
index d96d9354..14ce8fe8 100644
--- a/contracts/runner-gateway/envelope.schema.json
+++ b/contracts/runner-gateway/envelope.schema.json
@@ -4600,7 +4600,7 @@
"$ref": "#/$defs/Id"
},
"server": {
- "enum": ["browser", "task_files"]
+ "enum": ["browser", "playground"]
},
"tool_name": {
"type": "string",
@@ -4610,9 +4610,6 @@
"arguments": {
"$ref": "#/$defs/OpaqueObject"
},
- "task_scope": {
- "$ref": "#/$defs/SharedTaskScope"
- },
"deadline_ms": {
"type": "integer",
"minimum": 1000,