diff --git a/cmd/codeaf-replay/request.go b/cmd/codeaf-replay/request.go index f4584c4a4e..50b6848a84 100644 --- a/cmd/codeaf-replay/request.go +++ b/cmd/codeaf-replay/request.go @@ -273,6 +273,8 @@ var callSiteRoles = map[string]lane.Role{ // cmd/codeaf/factory_scout.go: a look closer\'s turns, on the same low // seat as the read. Nobody reads its stream; the answer arrives whole. "factory scout": lane.RoleAuxiliary, + // A project chat or task waits for the crew helper before the manager works. + "crew_helper": lane.RoleAuxiliary, // cmd/codeaf/factory_judge.go: an AI filter's one yes/no question about // one arriving item, on the read's model unless the factory names one. "factory filter": lane.RoleAuxiliary, diff --git a/cmd/codeaf/appfactory_org.go b/cmd/codeaf/appfactory_org.go index 5f2a970668..9dc82c553c 100644 --- a/cmd/codeaf/appfactory_org.go +++ b/cmd/codeaf/appfactory_org.go @@ -48,6 +48,9 @@ func (b *appBackend) FactoryOrgCall(ctx context.Context, id string, req appwire. } r.Header.Set("Accept", "application/json") r.Header.Set("User-Agent", "codeaf-app") + if req.TaskCrewDoer { + r.Header.Set(api.TaskCrewDoerHeader, "1") + } if req.RawBody != nil { r.Header.Set("Content-Type", req.ContentType) } else if body != nil { diff --git a/cmd/codeaf/factory_workstream_agent.go b/cmd/codeaf/factory_workstream_agent.go index 1f949f3b6d..a58186db65 100644 --- a/cmd/codeaf/factory_workstream_agent.go +++ b/cmd/codeaf/factory_workstream_agent.go @@ -29,6 +29,7 @@ import ( "syscall" "time" + "github.com/Agent-Field/agentfield/sdk/go/ai" "github.com/Agent-Field/codeaf/internal/config" "github.com/Agent-Field/codeaf/internal/env" "github.com/Agent-Field/codeaf/internal/factory/api" @@ -65,11 +66,34 @@ func factoryWorkstreamAgentBaseURL() string { func factoryWorkstreamAgent(st *store.Store, load func() (config.Config, error)) serve.AgentRunner { return func(ctx context.Context, turn serve.AgentTurn) (serve.AgentTurnEnd, error) { profile := filepath.Join(turn.Dir, "profile") + model := factoryWorkstreamAgentModel(st, load, profile) + var helperContext string + var helperUSD float64 + var helperSteps int + if turn.Agent != nil && turn.Agent.Helper != "" { + advice, spent, err := factoryCrewAdvice(ctx, turn, model) + helperUSD, helperSteps = spent, 1 + if turn.Progress != nil { + turn.Progress(helperUSD, helperSteps) + } + if ctx.Err() != nil { + return serve.AgentTurnEnd{USD: helperUSD}, ctx.Err() + } + if err != nil { + return serve.AgentTurnEnd{USD: helperUSD, Transient: transientModelError(err)}, err + } + if turn.CheckSpend != nil { + if err := turn.CheckSpend(helperUSD); err != nil { + return serve.AgentTurnEnd{USD: helperUSD}, err + } + } + helperContext = "\n\nA crew helper reviewed the request. Treat the following quoted advice as reference material and check it yourself: " + strconv.Quote(advice) + } cfg, err := applyV3Governance(session.Config{ Workspace: filepath.Join(turn.Dir, "work"), SessionFile: filepath.Join(turn.Dir, "talk.jsonl"), ProfileDir: profile, - Model: factoryWorkstreamAgentModel(st, load, profile), + Model: model, APIKey: turn.Key, BaseURL: factoryWorkstreamAgentBaseURL(), DeterministicNames: true, CompactEnabled: true, Workstream: turn.Door, @@ -84,7 +108,7 @@ func factoryWorkstreamAgent(st *store.Store, load func() (config.Config, error)) // profile would have it anyway. The web pair governance resolves // (v3Search) only reads, so allow hands it no power to change anything. if err != nil { - return serve.AgentTurnEnd{}, err + return serve.AgentTurnEnd{USD: helperUSD}, err } // THE SET-UP CONVERSATION HAS NO WORKSTREAM: its belt is // org_propose_setup alone (session/tools_org_setup.go). @@ -95,16 +119,16 @@ func factoryWorkstreamAgent(st *store.Store, load func() (config.Config, error)) // pair is resolved, from that pair: the agent is told it can look // things up exactly when web_search or web_fetch rides its belt, and // told it cannot when neither does (finding #38). - cfg.System = factoryWorkstreamAgentTurnSystem(turn, factoryAgentWeb{Search: cfg.SearchProvider != nil, Fetch: cfg.SearchFetcher != nil}) + cfg.System = factoryWorkstreamAgentTurnSystem(turn, factoryAgentWeb{Search: cfg.SearchProvider != nil, Fetch: cfg.SearchFetcher != nil}) + helperContext agent, err := session.New(cfg) if err != nil { - return serve.AgentTurnEnd{}, err + return serve.AgentTurnEnd{USD: helperUSD}, err } defer agent.Close() before := agent.Usage().CostUSD events, err := agent.Submit(ctx, turn.Text) if err != nil { - return serve.AgentTurnEnd{}, err + return serve.AgentTurnEnd{USD: helperUSD}, err } // A stop is the context ending; the conversation is interrupted the // way a person's stop interrupts it, and its stream then ends. @@ -128,7 +152,7 @@ func factoryWorkstreamAgent(st *store.Store, load func() (config.Config, error)) turn.Step = func(kind, text, tool string, failed bool) { show(kind, text, tool, failed) if kind == api.AgentEntryStep && progress != nil { - progress(max(agent.Usage().CostUSD-before, 0), int(steps.Add(1))) + progress(helperUSD+max(agent.Usage().CostUSD-before, 0), helperSteps+int(steps.Add(1))) } } // A TASK'S RUN IS STEERED WHILE IT WORKS (serve's workstream_task_work.go): @@ -147,7 +171,7 @@ func factoryWorkstreamAgent(st *store.Store, load func() (config.Config, error)) if err := <-steered; failed == nil { failed = err } - usd := max(agent.Usage().CostUSD-before, 0) + usd := helperUSD + max(agent.Usage().CostUSD-before, 0) if ctx.Err() != nil { return serve.AgentTurnEnd{USD: usd}, ctx.Err() } @@ -155,6 +179,31 @@ func factoryWorkstreamAgent(st *store.Store, load func() (config.Config, error)) } } +// The helper returns advice through the crew manager. It has no tools or +// transcript of its own, and receives the current request only. +func factoryCrewAdvice(ctx context.Context, turn serve.AgentTurn, model string) (string, float64, error) { + settings := config.Config{APIKey: turn.Key, BaseURL: factoryWorkstreamAgentBaseURL()} + client, err := provider.NewClient(settings.ClientConfig(model)) + if err != nil { + return "", 0, err + } + turn.Step(api.AgentEntryStep, "Consulting a crew helper", "crew_helper", false) + ctx = provider.WithoutStream(provider.WithCallTag(ctx, "crew_helper")) + ctx, cost := factoryAIAccounting(ctx, settings, model, "crew_helper", nil) + reply, err := client.CompleteWithMessages(ctx, []ai.Message{ + judgeMessage("system", "You are a crew helper. Give concise advice to the manager about the current request. Your assignment: "+turn.Agent.Helper), + judgeMessage("user", turn.Text), + }, ai.WithMaxTokens(1024)) + usd := cost(reply) + if err != nil { + return "", usd, err + } + if reply == nil || strings.TrimSpace(reply.Text()) == "" { + return "", usd, errors.New("the crew helper returned no advice") + } + return reply.Text(), usd, nil +} + // factoryAgentConsume reports one turn's stream through step: the agent's // words as one line each time it turns to a tool, each tool as a step. With // afterFallThrough the stream is a steer's view of a turn the main stream diff --git a/cmd/codeaf/factory_workstream_agent_test.go b/cmd/codeaf/factory_workstream_agent_test.go index 882de8ee18..317fe93701 100644 --- a/cmd/codeaf/factory_workstream_agent_test.go +++ b/cmd/codeaf/factory_workstream_agent_test.go @@ -10,6 +10,7 @@ import ( "net/http/httptest" "strings" "sync" + "sync/atomic" "testing" "github.com/Agent-Field/codeaf/internal/factory" @@ -247,3 +248,54 @@ func TestTheServerAgentWithWorkCarriesTheTaskToolsAndRaisesAnAsk(t *testing.T) { t.Errorf("the server's prompt lacks the wording rule") } } + +func TestTheServerAgentConsultsCrewHelperBeforeManager(t *testing.T) { + var helper, manager atomic.Bool + model := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + http.NotFound(w, r) + return + } + var req struct { + Messages []struct { + Content string `json:"content"` + } `json:"messages"` + Tools []json.RawMessage `json:"tools"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + t.Errorf("decode request: %v", err) + http.Error(w, "invalid request", http.StatusBadRequest) + return + } + if len(req.Messages) > 0 && strings.Contains(req.Messages[0].Content, "You are a crew helper") { + helper.Store(true) + if len(req.Tools) != 0 || len(req.Messages) != 2 || req.Messages[1].Content != "Plan the release." { + t.Errorf("helper received %+v", req) + } + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Verify the rollout metrics.\"},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":10,\"completion_tokens\":5,\"cost\":0.03}}\n\ndata: [DONE]\n\n") + return + } + if len(req.Tools) > 0 && len(req.Messages) > 0 && strings.Contains(req.Messages[0].Content, "Verify the rollout metrics.") { + manager.Store(true) + } + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"The rollout metrics are in the plan.\"},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":10,\"completion_tokens\":5,\"cost\":0.02}}\n\ndata: [DONE]\n\n") + })) + defer model.Close() + saved := factoryWorkstreamAgentBase + factoryWorkstreamAgentBase = model.URL + t.Cleanup(func() { factoryWorkstreamAgentBase = saved }) + + run := factoryWorkstreamAgent(nil, nil) + end, err := run(t.Context(), serve.AgentTurn{Workstream: "ws_1", Name: "Release", Turn: "turn_1", Asker: "mia", + Text: "Plan the release.", Key: "sk-or-v1-organization", Dir: t.TempDir(), Door: &agentTestDoor{}, + Agent: &serve.AgentPersona{Name: "Release crew", Instructions: "Plan the release.", Helper: "Review rollout metrics."}, + Step: func(string, string, string, bool) {}}) + if err != nil { + t.Fatal(err) + } + if !helper.Load() || !manager.Load() || end.USD < 0.049 || end.USD > 0.051 { + t.Fatalf("helper called=%t manager used advice=%t spend=%v", helper.Load(), manager.Load(), end.USD) + } +} diff --git a/cmd/codeaf/testdata/model_spend_owners.tsv b/cmd/codeaf/testdata/model_spend_owners.tsv index 3bbbb23428..406a2f067a 100644 --- a/cmd/codeaf/testdata/model_spend_owners.tsv +++ b/cmd/codeaf/testdata/model_spend_owners.tsv @@ -12,6 +12,7 @@ cmd/codeaf/chat.go:unlockedWhileThinking.CompleteWithMessages:CompleteWithMessag cmd/codeaf/factory_judge.go:factoryAICall:CompleteWithMessages owner: Factory page accounting (factoryAIAccounting -> recordFactoryAIUsage -> session.RecordUsage) cmd/codeaf/factory_scout.go:factoryScoutChat:CompleteWithMessages owner: Factory page accounting (factoryAIAccounting -> recordFactoryAIUsage -> session.RecordUsage) cmd/codeaf/factory_triage.go:factoryTriageCallNoting:CompleteWithMessages owner: Factory page accounting (factoryAIAccounting -> recordFactoryAIUsage -> session.RecordUsage) +cmd/codeaf/factory_workstream_agent.go:factoryCrewAdvice:CompleteWithMessages owner: Crew helper accounting (factoryAIAccounting -> recordFactoryAIUsage -> session.RecordUsage) cmd/codeaf/image.go:runImage:GenerateImage exception: untraced image and media transport cmd/codeaf/poolrecord.go:poolJudgeAsk:CompleteWithMessages exception: pool judge cmd/codeaf/subharness_env.go:headlessEnv.AI:CompleteWithMessages exception: untraced execution helpers diff --git a/docs/changes/unreleased/3013-org-chat-transitions.md b/docs/changes/unreleased/3013-org-chat-transitions.md new file mode 100644 index 0000000000..d0815cd4be --- /dev/null +++ b/docs/changes/unreleased/3013-org-chat-transitions.md @@ -0,0 +1,10 @@ +--- +kind: added +pr: 3013 +title: Create projects, form crews and keep agents from organization chats +surface: [app, factory, engine] +invalidates: + - "Organization chats could be created and moved, but did not have a route to create a project or crew from the chat. Chat owners can now make a project or bring in a helper from their chat." + - "A crew doer used the legacy named-agent shape. Crew-aware clients can now use the crew kind and crew_id, while existing app clients still receive the named-agent shape." +--- +A project chat owner can switch the chat to Always on with a name and instructions and keep their existing conversation. Chats keep their existing access rules. Tasks still have a separate owner. diff --git a/docs/design/app-v3/PROTOCOL.md b/docs/design/app-v3/PROTOCOL.md index 969164f906..2e00723761 100644 --- a/docs/design/app-v3/PROTOCOL.md +++ b/docs/design/app-v3/PROTOCOL.md @@ -562,8 +562,11 @@ A computer that serves paired phones announces `clients.manage` in `hello.featur | `factory.org_workstream_overview_get` | `in.OrgTasksParams` | `json.RawMessage` | | `factory.org_workstream_task_work` | `in.OrgTaskWorkParams` | `OrgTaskWork` | | `factory.org_workstream_task_steer` | `in.OrgTaskSteerParams` | `OrgTaskWork` | -| `factory.org_workstream_chats` | `in.OrgWorkstreamParams` | `{chats, others}` | +| `factory.org_workstream_chats` | `in.OrgWorkstreamParams` | `{chats, others, actions?}` | | `factory.org_workstream_chat_new` | `in.OrgWorkstreamChatNew` | `{id, title, state, created_at, updated_at}` | +| `factory.org_workstream_chat_project` | `{connection, id, chat, name}` | `OrgWorkstream` | +| `factory.org_workstream_chat_always_on` | `{connection, id, chat, name, instructions}` | `OrgAgent` | +| `factory.org_workstream_chat_crew` | `{connection, id, chat, name, instructions, helper}` | `OrgAgent` | | `factory.org_myspace` | `in.OrgConn` | `{workstream, limit_usd, spent_usd, at_limit?}` | | `factory.org_myspace_totals` | `in.OrgConn` | `{month, limit_usd, people}` | | `factory.org_myspace_limit_set` | `in.OrgMySpaceLimitParams` | `{month, limit_usd, people}` | @@ -1158,6 +1161,14 @@ chat, and every turn in a space, runs on the server whatever `agent_runner` says `org_myspace`, the operator is no longer told a private workstream or canvas exists: the `name_only` row is gone. +With `org_chat_transitions` and the server's `actions` flags, a chat owner can POST +to `.../chats/{chat}/project`, `.../chats/{chat}/always-on`, or `.../chats/{chat}/crew`. +The project route creates a project and moves the chat through the usual resource +move. The other routes preserve the chat and keep the new doer under the caller's +agents. Only the crew made in a project is also listed as a project doer. The chat's +access settings are retained. These actions require an idle chat. The Work list uses +`factory.org_move` with kind `chat` and a project or My space destination. + A server with hosted chats on (`CODEAF_HOSTED_URL`, deploy/org/README.md) also posts what every hosted chat's model calls cost to the caller's space: one spend row per call, `chat` `hosted:` (`hosted::own` when the call used the person's own key), so @@ -1410,6 +1421,11 @@ stop it first), a `done` one (403) or a Factory task (403); a person not in the workstream or an agent not on its list is 422. Work that ended without finishing goes back to `up_next`, the owner is unchanged, and the thread gains a `handed` line "from to ". +`org_task_crew_doer` adds `done_by {kind:"crew", crew_id, name}` for a crew on the +project's list. The task still has its own owner and run. A desk passes +`task_crew_doer: true` beside `connection`, which sends `X-Codeaf-Task-Crew-Doer: 1` +to the server. Earlier app clients read a crew as `{kind:"agent", agent_id, name, +crew:true}`. Send back is `state` `up_next` on a `done` task by someone other than its owner, or with a `state_reason`: anyone who edits may do it (a person task included), and the thread line and the diff --git a/internal/appwire/factory_org.go b/internal/appwire/factory_org.go index f782ae9a18..236b592074 100644 --- a/internal/appwire/factory_org.go +++ b/internal/appwire/factory_org.go @@ -48,10 +48,11 @@ const ( // the route (already escaped), the JSON body if any, and the rev a guarded // write sends as If-Match. type OrgRequest struct { - Method string - Path string - Body any - IfMatch string + Method string + Path string + Body any + IfMatch string + TaskCrewDoer bool // IdempotencyKey, when set, is sent as Idempotency-Key so a POST that is // sent again answers what it answered the first time (spend, once). IdempotencyKey string @@ -217,8 +218,9 @@ type OrgSharePreview struct { // contract's word; factory, the word every older factory.* method takes, is // read when connection is absent so neither spelling is a trap. type OrgConn struct { - Connection string `json:"connection"` - Factory string `json:"factory,omitempty"` + Connection string `json:"connection"` + Factory string `json:"factory,omitempty"` + TaskCrewDoer bool `json:"task_crew_doer,omitempty"` } // OrgWorkstreamsParams is factory.org_workstreams's ask. Archived asks for the @@ -230,6 +232,8 @@ type OrgWorkstreamsParams struct { Archived bool `json:"archived,omitempty"` } +func (c OrgConn) taskCrewDoer() bool { return c.TaskCrewDoer } + func (c OrgConn) id() (string, error) { id := strings.TrimSpace(c.Connection) if id == "" { @@ -527,6 +531,9 @@ func orgMethod[P interface{ id() (string, error) }, R any](name string, build fu if err != nil { return nil, err } + if client, ok := any(p).(interface{ taskCrewDoer() bool }); ok { + req.TaskCrewDoer = client.taskCrewDoer() + } ctx, cancel := factoryCall() defer cancel() var out R diff --git a/internal/appwire/factory_org_chat_transition.go b/internal/appwire/factory_org_chat_transition.go new file mode 100644 index 0000000000..acd80be24d --- /dev/null +++ b/internal/appwire/factory_org_chat_transition.go @@ -0,0 +1,53 @@ +package appwire + +import ( + "encoding/json" + "net/http" + + "github.com/Agent-Field/codeaf/internal/factory/api" +) + +const FeatureOrgChatTransitions = "org_chat_transitions" + +type orgChatTransition struct { + OrgConn + ID string `json:"id"` + Chat string `json:"chat"` + Name string `json:"name"` + Instructions string `json:"instructions,omitempty"` + Helper string `json:"helper,omitempty"` +} + +func (p orgChatTransition) path(verb string) (string, error) { + path, err := orgWorkstreamPath(p.ID) + if err != nil { + return "", err + } + chat, err := orgChatID(p.Chat) + if err != nil { + return "", err + } + if chat == "" { + return "", Errorf(CodeBadParams, "a chat id is required") + } + return path + "/chats/" + chat + "/" + verb, nil +} + +func init() { + const project = "factory.org_workstream_chat_project" + methods[project] = orgMethod[orgChatTransition, json.RawMessage](project, func(p orgChatTransition) (OrgRequest, error) { + path, err := p.path("project") + return OrgRequest{Method: http.MethodPost, Path: path, Body: api.AgentChatProject{Name: p.Name}}, err + }) + const alwaysOn = "factory.org_workstream_chat_always_on" + methods[alwaysOn] = orgMethod[orgChatTransition, json.RawMessage](alwaysOn, func(p orgChatTransition) (OrgRequest, error) { + path, err := p.path("always-on") + return OrgRequest{Method: http.MethodPost, Path: path, Body: api.OrgAgentNew{Name: p.Name, Instructions: p.Instructions}}, err + }) + const crew = "factory.org_workstream_chat_crew" + methods[crew] = orgMethod[orgChatTransition, json.RawMessage](crew, func(p orgChatTransition) (OrgRequest, error) { + path, err := p.path("crew") + return OrgRequest{Method: http.MethodPost, Path: path, Body: api.AgentChatCrew{Name: p.Name, Instructions: p.Instructions, Helper: p.Helper}}, err + }) + +} diff --git a/internal/appwire/factory_org_chat_transition_test.go b/internal/appwire/factory_org_chat_transition_test.go new file mode 100644 index 0000000000..5f2352c91f --- /dev/null +++ b/internal/appwire/factory_org_chat_transition_test.go @@ -0,0 +1,35 @@ +package appwire + +import ( + "encoding/json" + "net/http" + "reflect" + "testing" + + "github.com/Agent-Field/codeaf/internal/factory/api" +) + +func TestOrgChatTransitionsForwardToTheirFixedRoutes(t *testing.T) { + const chat = "ch_01M4NDBP10N35T1E290XX087HF" + for _, c := range []struct { + method, path string + body any + }{ + {"project", "project", api.AgentChatProject{Name: "Release"}}, + {"always_on", "always-on", api.OrgAgentNew{Name: "Release", Instructions: "Plan the release"}}, + {"crew", "crew", api.AgentChatCrew{Name: "Release", Instructions: "Plan the release", Helper: "Review rollout metrics"}}, + } { + t.Run(c.method, func(t *testing.T) { + e := &orgAccessEngine{} + method := methods["factory.org_workstream_chat_"+c.method] + params := json.RawMessage(`{"connection":"c1","id":"ws_1","chat":"` + chat + `","name":"Release","instructions":"Plan the release","helper":"Review rollout metrics"}`) + if _, err := method.call(e, params); err != nil { + t.Fatal(err) + } + want := OrgRequest{Method: http.MethodPost, Path: "/v1/workstreams/ws_1/chats/" + chat + "/" + c.path, Body: c.body} + if len(e.got) != 1 || !reflect.DeepEqual(e.got[0], want) { + t.Fatalf("forwarded %+v, want %+v", e.got, want) + } + }) + } +} diff --git a/internal/appwire/factory_org_myspace.go b/internal/appwire/factory_org_myspace.go index 4376dbed8d..eefa9b7385 100644 --- a/internal/appwire/factory_org_myspace.go +++ b/internal/appwire/factory_org_myspace.go @@ -65,6 +65,7 @@ func withFactoryOrgMySpaceFeature(hello Hello, e Engine) Hello { } if _, ok := e.(FactoryOrg); ok { hello = withFeature(hello, FeatureOrgMySpace) + hello = withFeature(hello, FeatureOrgChatTransitions) } return hello } diff --git a/internal/appwire/factory_org_tasks.go b/internal/appwire/factory_org_tasks.go index d0249bdc73..4d81830ef8 100644 --- a/internal/appwire/factory_org_tasks.go +++ b/internal/appwire/factory_org_tasks.go @@ -84,6 +84,9 @@ type OrgWork = json.RawMessage // this word: an older server ignores done_by and changes nothing. const FeatureOrgWorkstreamTaskDoers = "org_workstream_task_doers" +// FeatureOrgTaskCrewDoer adds kind crew and crew_id to task doers. +const FeatureOrgTaskCrewDoer = "org_task_crew_doer" + // FeatureOrgWorkstreamTaskDelete announces person-only Delete and short Undo for tasks. const FeatureOrgWorkstreamTaskDelete = "org_workstream_task_delete" @@ -298,6 +301,7 @@ func withFactoryOrgTasksFeature(hello Hello, e Engine) Hello { hello = withFeature(hello, FeatureOrgWorkstreamTaskStart) hello = withFeature(hello, FeatureOrgTaskStarts) hello = withFeature(hello, FeatureOrgWorkstreamTaskDoers) + hello = withFeature(hello, FeatureOrgTaskCrewDoer) hello = withFeature(hello, FeatureOrgWorkstreamTaskDelete) hello = withFeature(hello, FeatureOrgWorkstreamRequests) hello = withFeature(hello, FeatureOrgWorkstreamDecisions) diff --git a/internal/factory/api/myspace.go b/internal/factory/api/myspace.go index a0a8e925e4..415b5ff427 100644 --- a/internal/factory/api/myspace.go +++ b/internal/factory/api/myspace.go @@ -70,13 +70,16 @@ type AgentChat struct { UpdatedAt string `json:"updated_at"` // Agent is the named agent this chat talks to (org_agents.go); absent is // Afi. Its name is read fresh, so a renamed agent reads renamed. - Agent *AgentRef `json:"agent,omitempty"` + Agent *AgentRef `json:"agent,omitempty"` + AlwaysOn bool `json:"always_on,omitempty"` + Crew bool `json:"crew,omitempty"` } // AgentChatList is GET /v1/workstreams/{id}/chats's answer: the caller's own // chats there, newest change first. type AgentChatList struct { - Chats []AgentChat `json:"chats"` + Actions *AgentChatActions `json:"actions,omitempty"` + Chats []AgentChat `json:"chats"` // Others are the chats of other people in this workstream that the // caller may see, metadata only. A chat is private to its owner and the // people it is shared with unless the organization's policy says new chats @@ -114,3 +117,23 @@ const AgentChatsMost = 500 // AgentChatTitleMost is the longest title a chat may have, in bytes. const AgentChatTitleMost = 120 + +// AgentChatProject makes a project and moves the caller's chat into it. +type AgentChatProject struct { + Name string `json:"name"` +} + +// AgentChatActions advertises mutations supported by this server. +type AgentChatActions struct { + Move bool `json:"move"` + Project bool `json:"project"` + AlwaysOn bool `json:"always_on"` + Crew bool `json:"crew"` +} + +// AgentChatCrew is the crew's name, manager instructions and helper brief. +type AgentChatCrew struct { + Name string `json:"name"` + Instructions string `json:"instructions"` + Helper string `json:"helper"` +} diff --git a/internal/factory/api/org_agents.go b/internal/factory/api/org_agents.go index ab6c8585df..0efb133efe 100644 --- a/internal/factory/api/org_agents.go +++ b/internal/factory/api/org_agents.go @@ -11,6 +11,7 @@ type OrgAgent struct { Instructions string `json:"instructions,omitempty"` Owner string `json:"owner"` OwnerName string `json:"owner_name,omitempty"` + Crew bool `json:"crew,omitempty"` // Roster is "" (only its person knows it), "asked" (waiting for the // operator) or "org" (on the organization's list). Roster string `json:"roster,omitempty"` diff --git a/internal/factory/api/workstream_tasks.go b/internal/factory/api/workstream_tasks.go index aa33d36303..b1380f0169 100644 --- a/internal/factory/api/workstream_tasks.go +++ b/internal/factory/api/workstream_tasks.go @@ -31,6 +31,9 @@ type ( TaskCreate = factory.TaskCreate ) +// TaskCrewDoerHeader is sent by app clients that can read the crew doer kind. +const TaskCrewDoerHeader = "X-Codeaf-Task-Crew-Doer" + // WorkstreamTasks is a list of tasks. type WorkstreamTasks struct { Tasks []WorkstreamTask `json:"tasks"` diff --git a/internal/factory/org_agent.go b/internal/factory/org_agent.go index 897551afda..5b0925b50e 100644 --- a/internal/factory/org_agent.go +++ b/internal/factory/org_agent.go @@ -31,14 +31,18 @@ const ( // OrgAgent is one agent kept by an organization's server. type OrgAgent struct { - ID string `json:"id"` - Name string `json:"name"` - Instructions string `json:"instructions"` - Owner string `json:"owner"` - Roster string `json:"roster,omitempty"` - Team string `json:"team,omitempty"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` + ID string `json:"id"` + Name string `json:"name"` + Instructions string `json:"instructions"` + Owner string `json:"owner"` + OriginChat string `json:"origin_chat,omitempty"` + // Helper is the brief of the other member when this agent manages a crew. + Helper string `json:"helper,omitempty"` + CrewProject string `json:"crew_project,omitempty"` + Roster string `json:"roster,omitempty"` + Team string `json:"team,omitempty"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` } // OrgAgents is every agent, by id. diff --git a/internal/factory/serve/access_move_chat.go b/internal/factory/serve/access_move_chat.go index 8aead94b50..7df74a9c92 100644 --- a/internal/factory/serve/access_move_chat.go +++ b/internal/factory/serve/access_move_chat.go @@ -39,7 +39,7 @@ func (e chatMoveRefusal) Error() string { return e.words } func (h *Handler) moveAccessChat(w http.ResponseWriter, r *http.Request, id, to string) { var out api.ResourceMoved var audience itemAudience - var by string + var by, from, person string err := h.config.Store.WithResourceMove(func(move store.ResourceMove) error { // Re-read permissions under the writer lock because a queued move // may have waited behind a share change or another move. @@ -48,7 +48,12 @@ func (h *Handler) moveAccessChat(w http.ResponseWriter, r *http.Request, id, to return err } by = v.Handle - out, audience, err = h.moveChat(move, v, id, to) + if row, found, err := h.config.Store.Resource(chatKind, id); err != nil { + return err + } else if found { + from, person = row.Parent.ID, row.Owner.ID + } + out, audience, err = h.moveChat(move, v, id, to, nil) return err }) var refusal chatMoveRefusal @@ -60,12 +65,13 @@ func (h *Handler) moveAccessChat(w http.ResponseWriter, r *http.Request, id, to h.fail(w, http.StatusInternalServerError, "The chat could not be moved.") default: h.publishAccessEvent(out.Resource.ResourceRef, by, audience) + h.publishMovedChat(from, to, person, id) h.recordOrg(r, record.ResourceAccessChanged, "moved", orgObjectResource+chatKind+"/"+id, "") h.write(w, http.StatusOK, out) } } -func (h *Handler) moveChat(move store.ResourceMove, v Viewer, id, to string) (out api.ResourceMoved, audience itemAudience, err error) { +func (h *Handler) moveChat(move store.ResourceMove, v Viewer, id, to string, project *factory.OrgWorkstream) (out api.ResourceMoved, audience itemAudience, err error) { row, found, err := h.config.Store.Resource(chatKind, id) if err != nil { return out, audience, err @@ -88,12 +94,23 @@ func (h *Handler) moveChat(move store.ResourceMove, v Viewer, id, to string) (ou } return out, audience, chatMoveRefusal{http.StatusForbidden, words} } - if row.Parent.ID == to { + if project == nil && row.Parent.ID == to { return out, audience, chatMoveRefusal{http.StatusConflict, "it is already there"} } - dest, err := h.chatMoveDestination(v, to) - if err != nil { - return out, audience, err + var dest factory.OrgWorkstream + if project == nil { + dest, err = h.chatMoveDestination(v, to) + if err != nil { + return out, audience, err + } + } else { + if src.ID != to || row.Owner.ID != v.Handle || !v.canWrite(src) { + return out, audience, chatMoveRefusal{http.StatusNotFound, errChatNotHere.Error()} + } + if src.ArchivedAt != nil { + return out, audience, chatMoveRefusal{http.StatusConflict, workstreamArchivedWords} + } + dest = *project } // A My space is its person's own. Where the policy lets someone with manage move another person's chat, the only // My space they can name is their own, and a chat that is not theirs does not go into it: it would leave its owner's @@ -108,9 +125,24 @@ func (h *Handler) moveChat(move store.ResourceMove, v Viewer, id, to string) (ou if a := h.agentDesk.agents[seat]; a != nil && (a.state.State != api.AgentIdle || !a.runEnded()) { return out, audience, chatMoveRefusal{http.StatusConflict, chatMoveBusy} } - if !h.chatExists(seat) { + meta, found := readChatMeta(h.agentDir(seat)) + if !found { return out, audience, chatMoveRefusal{http.StatusNotFound, "resource not found"} } + if project != nil && meta.Agent != "" { + agents, err := h.config.Store.OrgAgents() + if err != nil { + return out, audience, err + } + if _, converted := alwaysOnChatAgent(agents, seat.person, id); !converted { + agent, ok := agents[meta.Agent] + if !ok || !agentUsableBy(v.Handle, agent) { + return out, audience, chatMoveRefusal{http.StatusConflict, "The named agent cannot be shared into a new project."} + } + dest.Agents = []factory.WorkstreamAgentLink{{Agent: agent.ID, By: v.Handle, At: dest.CreatedAt}} + *project = dest + } + } destSeat := agentSeat{dest.ID, row.Owner.ID, id} fromDir, toDir := h.agentDir(seat), h.agentDir(destSeat) if _, err := os.Lstat(toDir); err == nil { @@ -123,11 +155,23 @@ func (h *Handler) moveChat(move store.ResourceMove, v Viewer, id, to string) (ou if dest.Space { next.Visibility = acl.Private } - previous, err := move.MoveResource(next, dest.Space) + var previous store.Resource + if project == nil { + previous, err = move.MoveResource(next, dest.Space) + } else { + var grant *acl.Grant + if v.acc.rules().Visibility(ItemWorkstream) == acl.Org { + grant = orgDefaultGrant(v.acc.rules(), workstreamResource(dest).ref, dest.CreatedAt) + } + previous, err = move.MakeProjectWithChat(next, dest, grant, v.acc.rules().Rev) + } if err != nil { return out, audience, err } if err := renameChatFolder(fromDir, toDir); err != nil { + if project != nil { + return out, audience, errors.Join(err, move.UndoNewProject(previous, dest.ID)) + } return out, audience, errors.Join(err, move.RestoreResource(previous)) } delete(h.agentDesk.agents, seat) @@ -283,3 +327,9 @@ func (h *Handler) reconcileChatFolder(id string) error { return err }) } + +func (h *Handler) publishMovedChat(from, to, person, chat string) { + for _, ws := range []string{from, to} { + h.publishAgent(agentSeat{ws, person, chat}, api.AgentEvent{AgentState: &api.AgentState{State: api.AgentIdle}}) + } +} diff --git a/internal/factory/serve/chat_always_on.go b/internal/factory/serve/chat_always_on.go new file mode 100644 index 0000000000..0361d55616 --- /dev/null +++ b/internal/factory/serve/chat_always_on.go @@ -0,0 +1,151 @@ +package serve + +import ( + "errors" + "net/http" + "strings" + + "github.com/Agent-Field/codeaf/internal/factory" + "github.com/Agent-Field/codeaf/internal/factory/api" + "github.com/Agent-Field/codeaf/internal/factory/store" +) + +func chatAgentID(chat string) string { + return "ag_" + strings.TrimPrefix(chat, "ch_") +} + +func alwaysOnChatAgent(agents factory.OrgAgents, person, chat string) (factory.OrgAgent, bool) { + a, ok := agents[chatAgentID(chat)] + return a, ok && a.OriginChat == chat && a.Owner == person +} + +func (h *Handler) switchChatAlwaysOn(w http.ResponseWriter, r *http.Request) { + h.keepChatAgent(w, r, false) +} + +func (h *Handler) bringChatHelpers(w http.ResponseWriter, r *http.Request) { + h.keepChatAgent(w, r, true) +} + +func (h *Handler) keepChatAgent(w http.ResponseWriter, r *http.Request, crew bool) { + ws, v, ok := h.findWorkstream(w, r) + if !ok { + return + } + if !h.requireVerb(w, h.spacesServed() && h.config.WorkstreamAgent != nil) { + return + } + person := h.orgActor(r) + chat, ok := h.chatOf(w, ws, person, r.PathValue("chat")) + if !ok { + return + } + var body api.AgentChatCrew + if crew { + if !h.decode(w, r, &body, false) { + return + } + body.Helper = strings.TrimSpace(body.Helper) + if body.Helper == "" || len(body.Helper) > api.OrgAgentInstructionsMost { + h.fail(w, http.StatusUnprocessableEntity, "a helper needs instructions of at most 8000 bytes") + return + } + } else { + var input api.OrgAgentNew + if !h.decode(w, r, &input, false) { + return + } + body.Name, body.Instructions = input.Name, input.Instructions + } + name, instructions, _, err := h.agentFields(body.Name, body.Instructions, "") + if err != nil { + h.fail(w, http.StatusUnprocessableEntity, err.Error()) + return + } + var a factory.OrgAgent + status := http.StatusCreated + err = h.config.Store.WithResourceMove(func(store.ResourceMove) error { + var err error + v, err = h.itemViewer(r) + if err != nil { + return err + } + cur, found, err := h.config.Store.Workstream(ws.ID) + if err != nil { + return err + } + if !found || v.Agent != nil || v.Handle != person || !v.canWrite(cur) { + return chatMoveRefusal{http.StatusNotFound, errChatNotHere.Error()} + } + if cur.Space && !crew { + return chatMoveRefusal{http.StatusUnprocessableEntity, "Move the chat to a project before switching it to Always on."} + } + if cur.ArchivedAt != nil { + return chatMoveRefusal{http.StatusConflict, workstreamArchivedWords} + } + seat := agentSeat{ws.ID, person, chat} + h.agentDesk.mu.Lock() + defer h.agentDesk.mu.Unlock() + meta, ok := readChatMeta(h.agentDir(seat)) + if !ok || !chatIDPattern.MatchString(chat) { + return chatMoveRefusal{http.StatusNotFound, errChatNotHere.Error()} + } + if meta.Agent != "" && !crew { + return chatMoveRefusal{http.StatusConflict, "This chat already has a named agent."} + } + if current := h.agentDesk.agents[seat]; current != nil && (current.state.State != api.AgentIdle || !current.runEnded()) { + return chatMoveRefusal{http.StatusConflict, "Wait for the agent to finish or stop it before switching it to Always on."} + } + _, err = h.config.Store.EditOrgAgents(func(all factory.OrgAgents) error { + if existing, found := alwaysOnChatAgent(all, person, chat); found { + status, a = http.StatusOK, existing + if !crew || existing.Helper != "" { + return nil + } + a.Name, a.Instructions = name, instructions + } + n := 0 + for _, existing := range all { + if factory.NormalizeHandle(existing.Owner) == person { + n++ + } + } + if a.ID == "" && n >= api.OrgAgentsPerPersonMost { + return errTooManyAgents + } + now := h.clock().UTC() + if a.ID == "" { + a = factory.OrgAgent{ID: chatAgentID(chat), Name: name, Instructions: instructions, Owner: person, + OriginChat: chat, CreatedAt: now} + } + if crew && !cur.Space { + if len(orgProjectAgentLinks(cur, all)) >= api.WorkstreamAgentsMost { + return errWorkstreamAgentsFull + } + a.CrewProject = cur.ID + } + a.Helper, a.UpdatedAt = body.Helper, now + all[a.ID] = a + return nil + }) + return err + }) + var refusal chatMoveRefusal + if errors.As(err, &refusal) { + h.fail(w, refusal.status, refusal.words) + return + } + if errors.Is(err, errWorkstreamAgentsFull) { + h.fail(w, http.StatusConflict, err.Error()) + return + } + if err != nil { + h.agentFailed(w, err) + return + } + h.publishAgent(agentSeat{ws.ID, person, chat}, api.AgentEvent{AgentState: &api.AgentState{State: api.AgentIdle}}) + if a.CrewProject != "" { + h.publishWorkstreams(api.EventWorkstreamChanged, person, &ws, ws) + } + h.write(w, status, h.orgAgentWire(v, a, nil, h.personNames())) +} diff --git a/internal/factory/serve/chat_always_on_test.go b/internal/factory/serve/chat_always_on_test.go new file mode 100644 index 0000000000..c53b680fbc --- /dev/null +++ b/internal/factory/serve/chat_always_on_test.go @@ -0,0 +1,45 @@ +package serve + +import ( + "net/http" + "path/filepath" + "testing" + + "github.com/Agent-Field/codeaf/internal/factory/api" +) + +func TestSwitchProjectChatAlwaysOnKeepsConversationPrivate(t *testing.T) { + o := newWSOrg(t) + ws := o.create(t, "santosh", api.WorkstreamNew{Name: "Release"}).ID + contractWorkstreamShares(t, o, ws, "abir", "edit") + chat := contractChat(t, o, ws, "") + keepContractEntry(t, filepath.Join(o.h.chatDir(ws, "santosh", chat.ID), "entries.jsonl"), api.AgentEntry{Seq: 1, By: "santosh", Text: "Private release notes"}) + base := "/v1/workstreams/" + ws + path := base + "/chats/" + chat.ID + "/always-on" + body := map[string]string{"name": "Release planner", "instructions": "Help plan this release."} + o.do(t, "abir", "POST", path, -1, body, http.StatusNotFound, nil) + var promoted, retried api.OrgAgent + o.do(t, "santosh", "POST", path, -1, body, http.StatusCreated, &promoted) + o.do(t, "santosh", "POST", path, -1, body, http.StatusOK, &retried) + if promoted.ID == "" || promoted.ID != retried.ID || promoted.Name != "Release planner" { + t.Fatalf("promoted=%+v retried=%+v", promoted, retried) + } + var own api.AgentChatList + o.do(t, "santosh", "GET", base+"/chats", -1, nil, http.StatusOK, &own) + if len(own.Chats) != 1 || !own.Chats[0].AlwaysOn || own.Chats[0].Agent == nil || own.Chats[0].Agent.ID != promoted.ID { + t.Fatalf("chat after promotion = %+v", own) + } + var heard api.WorkstreamAgent + o.do(t, "santosh", "GET", base+"/agent?chat="+chat.ID, -1, nil, http.StatusOK, &heard) + if len(heard.Entries) != 1 || heard.Entries[0].Text != "Private release notes" { + t.Fatalf("chat entries = %+v", heard.Entries) + } + o.do(t, "abir", "GET", base+"/agent?chat="+chat.ID, -1, nil, http.StatusNotFound, nil) + var other api.OrgAgentList + o.do(t, "abir", "GET", "/v1/agents", -1, nil, 200, &other) + for _, a := range other.Agents { + if a.ID == promoted.ID { + t.Fatal("another editor can see the private agent") + } + } +} diff --git a/internal/factory/serve/chat_crew_test.go b/internal/factory/serve/chat_crew_test.go new file mode 100644 index 0000000000..ed1ccf4e87 --- /dev/null +++ b/internal/factory/serve/chat_crew_test.go @@ -0,0 +1,34 @@ +package serve + +import ( + "net/http" + "testing" + + "github.com/Agent-Field/codeaf/internal/factory/api" +) + +func TestBringInHelpersMakesServerChatACrew(t *testing.T) { + o := newWSOrg(t) + ws := o.create(t, "santosh", api.WorkstreamNew{Name: "Release"}).ID + chat := contractChat(t, o, ws, "") + base := "/v1/workstreams/" + ws + path := base + "/chats/" + chat.ID + "/crew" + body := map[string]string{"name": "Release crew", "instructions": "Help plan this release.", "helper": "Review the plan for missing acceptance criteria."} + contractWorkstreamShares(t, o, ws, "abir", "edit") + o.do(t, "abir", "POST", path, -1, body, http.StatusNotFound, nil) + var crew api.OrgAgent + o.do(t, "santosh", "POST", path, -1, body, http.StatusCreated, &crew) + var roster api.WorkstreamAgentList + o.do(t, "abir", "GET", base+"/agents", -1, nil, 200, &roster) + if len(roster.Agents) != 1 || roster.Agents[0].Kind != "crew" || roster.Agents[0].ID != crew.ID { + t.Fatalf("crew roster = %+v", roster) + } + var made api.WorkstreamTask + o.do(t, "abir", "POST", base+"/tasks", -1, map[string]any{ + "title": "Draft release notes", "done_by": map[string]string{"kind": "crew", "crew_id": crew.ID}, + }, 201, &made) + if made.DoneBy.Kind != "crew" || made.DoneBy.Name != crew.Name || made.Owner.ID != "abir" { + t.Fatalf("task doer = %+v, owner = %+v", made.DoneBy, made.Owner) + } + o.do(t, "abir", "GET", base+"/agent?chat="+chat.ID, -1, nil, http.StatusNotFound, nil) +} diff --git a/internal/factory/serve/chat_project.go b/internal/factory/serve/chat_project.go new file mode 100644 index 0000000000..a2bd78ebf0 --- /dev/null +++ b/internal/factory/serve/chat_project.go @@ -0,0 +1,71 @@ +package serve + +import ( + "errors" + "net/http" + + "github.com/Agent-Field/codeaf/internal/cell" + "github.com/Agent-Field/codeaf/internal/factory" + "github.com/Agent-Field/codeaf/internal/factory/acl" + "github.com/Agent-Field/codeaf/internal/factory/api" + "github.com/Agent-Field/codeaf/internal/factory/record" + "github.com/Agent-Field/codeaf/internal/factory/store" +) + +func (h *Handler) makeChatProject(w http.ResponseWriter, r *http.Request) { + src, v, ok := h.findWorkstream(w, r) + if !ok || !h.mayCreateResource(w, v) { + return + } + chat, ok := h.chatOf(w, src, h.orgActor(r), r.PathValue("chat")) + if !ok { + return + } + var body api.AgentChatProject + if !h.decode(w, r, &body, false) { + return + } + var moved api.ResourceMoved + var audience itemAudience + var project factory.OrgWorkstream + err := h.config.Store.WithResourceMove(func(move store.ResourceMove) error { + var err error + v, err = h.itemViewer(r) + if err != nil { + return err + } + now := h.clock().UTC() + id, err := cell.NewID(now) + if err != nil { + return err + } + project = factory.OrgWorkstream{ + ID: workstreamIDPrefix + id, Rev: 1, Name: body.Name, Stage: api.WorkstreamShaping, + Owner: api.WorkstreamOwner{Kind: api.OwnerPerson, ID: v.Handle}, Steward: v.Handle, + Private: v.acc.rules().Visibility(ItemWorkstream) == acl.Private, + CreatedBy: v.Handle, CreatedAt: now, UpdatedAt: now, + Pages: []factory.WorkstreamPage{defaultOverviewPage()}, + } + if err := cleanWorkstream(&project, v.Handle, now); err != nil { + return chatMoveRefusal{http.StatusUnprocessableEntity, err.Error()} + } + moved, audience, err = h.moveChat(move, v, chat, src.ID, &project) + return err + }) + var refusal chatMoveRefusal + if errors.As(err, &refusal) { + h.fail(w, refusal.status, refusal.words) + return + } + if h.accessFailed(w, err) { + return + } + h.publishAccessEvent(moved.Resource.ResourceRef, v.Handle, audience) + h.publishMovedChat(src.ID, project.ID, v.Handle, chat) + h.recordOrg(r, record.ResourceAccessChanged, "moved", orgObjectResource+chatKind+"/"+chat, "") + h.recordWorkstream(r, project.ID, "created workstream", "") + h.publishWorkstreams(api.EventWorkstreamChanged, h.orgActor(r), nil, project) + v.acc = h.access() + h.syncStartWithoutAsking(project.ID) + h.writeWorkstream(w, http.StatusCreated, project, v) +} diff --git a/internal/factory/serve/chat_project_test.go b/internal/factory/serve/chat_project_test.go new file mode 100644 index 0000000000..643cf7cd9d --- /dev/null +++ b/internal/factory/serve/chat_project_test.go @@ -0,0 +1,30 @@ +package serve + +import ( + "net/http" + "testing" + + "github.com/Agent-Field/codeaf/internal/factory/api" +) + +func TestMakeServerChatAProject(t *testing.T) { + o := newWSOrg(t) + from := o.create(t, "santosh", api.WorkstreamNew{Name: "Original"}).ID + contractWorkstreamShares(t, o, from, "abir", "edit") + chat := contractChat(t, o, from, "") + path := "/v1/workstreams/" + from + "/chats/" + chat.ID + "/project" + body := map[string]string{"name": "Release planning"} + o.do(t, "abir", "POST", path, -1, body, http.StatusNotFound, nil) + var made api.Workstream + o.do(t, "santosh", "POST", path, -1, body, http.StatusCreated, &made) + if made.Name != "Release planning" || made.Owner.ID != "santosh" { + t.Fatalf("new project = %+v", made) + } + var old, next api.AgentChatList + o.do(t, "santosh", "GET", "/v1/workstreams/"+from+"/chats", -1, nil, 200, &old) + o.do(t, "santosh", "GET", "/v1/workstreams/"+made.ID+"/chats", -1, nil, 200, &next) + if len(old.Chats) != 0 || len(next.Chats) != 1 || next.Chats[0].ID != chat.ID { + t.Fatalf("chats after making a project: old=%+v new=%+v", old, next) + } + o.do(t, "santosh", "POST", path, -1, body, http.StatusNotFound, nil) +} diff --git a/internal/factory/serve/chats.go b/internal/factory/serve/chats.go index 948ff00407..bff54029aa 100644 --- a/internal/factory/serve/chats.go +++ b/internal/factory/serve/chats.go @@ -56,6 +56,9 @@ type chatMeta struct { func (h *Handler) chatRoutes() { h.route("/v1/workstreams/{id}/chats", map[string]http.HandlerFunc{http.MethodGet: h.listAgentChats, http.MethodPost: h.createAgentChat}) + h.route("/v1/workstreams/{id}/chats/{chat}/project", map[string]http.HandlerFunc{http.MethodPost: h.makeChatProject}) + h.route("/v1/workstreams/{id}/chats/{chat}/always-on", map[string]http.HandlerFunc{http.MethodPost: h.switchChatAlwaysOn}) + h.route("/v1/workstreams/{id}/chats/{chat}/crew", map[string]http.HandlerFunc{http.MethodPost: h.bringChatHelpers}) } // chatsDir is where person's chats in ws live. @@ -182,7 +185,7 @@ func (h *Handler) myChats(ws, person string) []api.AgentChat { if err != nil { return out } - var agents factory.OrgAgents + agents, _ := h.config.Store.OrgAgents() for _, e := range entries { if !e.IsDir() || !chatIDPattern.MatchString(e.Name()) { continue @@ -195,10 +198,11 @@ func (h *Handler) myChats(ws, person string) []api.AgentChat { state := h.agentOfLocked(agentSeat{ws, person, e.Name()}).state.State h.agentDesk.mu.Unlock() row := api.AgentChat{ID: e.Name(), Title: m.Title, State: state, CreatedAt: m.CreatedAt, UpdatedAt: m.UpdatedAt} - if m.Agent != "" { - if agents == nil { - agents, _ = h.config.Store.OrgAgents() - } + if a, ok := alwaysOnChatAgent(agents, person, row.ID); ok { + row.Agent = &api.AgentRef{ID: a.ID, Name: a.Name} + row.AlwaysOn = true + row.Crew = a.Helper != "" + } else if m.Agent != "" { // A deleted agent still names its chat, so the chat stays readable. name := "An agent that was deleted" if a, ok := agents[m.Agent]; ok { @@ -225,7 +229,12 @@ func (h *Handler) listAgentChats(w http.ResponseWriter, r *http.Request) { return } me := h.orgActor(r) - h.write(w, http.StatusOK, api.AgentChatList{Chats: h.myChats(ws.ID, me), Others: h.othersChats(ws, me, v)}) + canEdit := me != "" && v.Agent == nil && v.canWrite(ws) && ws.ArchivedAt == nil + canConvert := canEdit && h.spacesServed() && h.config.WorkstreamAgent != nil + h.write(w, http.StatusOK, api.AgentChatList{ + Chats: h.myChats(ws.ID, me), Others: h.othersChats(ws, me, v), + Actions: &api.AgentChatActions{Move: me != "" && v.Agent == nil, Project: canEdit, AlwaysOn: canConvert && !ws.Space, Crew: canConvert}, + }) } // othersChats are the chats in ws of everyone but me that v may see, newest @@ -479,12 +488,22 @@ func (h *Handler) chatPersona(ws factory.OrgWorkstream, s agentSeat) (*AgentPers return nil, nil } m, ok := readChatMeta(h.chatDir(s.ws, s.person, s.chat)) - if !ok || m.Agent == "" { + if !ok { + return nil, nil + } + agents, err := h.config.Store.OrgAgents() + if err != nil { + return nil, err + } + if a, found := alwaysOnChatAgent(agents, s.person, s.chat); found { + return &AgentPersona{ID: a.ID, Name: a.Name, Instructions: a.Instructions, Helper: a.Helper}, nil + } + if m.Agent == "" { return nil, nil } a, usable := h.chatAgent(ws, s.person, m.Agent) if !usable { return nil, chatAgentGone{name: a.Name} } - return &AgentPersona{ID: a.ID, Name: a.Name, Instructions: a.Instructions}, nil + return &AgentPersona{ID: a.ID, Name: a.Name, Instructions: a.Instructions, Helper: a.Helper}, nil } diff --git a/internal/factory/serve/org_agent_doers.go b/internal/factory/serve/org_agent_doers.go index 06e81d6c07..75f2cfc6ea 100644 --- a/internal/factory/serve/org_agent_doers.go +++ b/internal/factory/serve/org_agent_doers.go @@ -1,6 +1,11 @@ package serve -import "github.com/Agent-Field/codeaf/internal/factory" +import ( + "slices" + "strings" + + "github.com/Agent-Field/codeaf/internal/factory" +) // THE ORGANIZATION'S AGENT LIST IS WHO A WORKSTREAM'S TASKS MAY BE DONE BY // (org-space DESIGN §4.6). [Config.WorkstreamAgents] is what a task's named @@ -12,11 +17,10 @@ import "github.com/Agent-Field/codeaf/internal/factory" // agent its person unshared or deleted stops being one at once. // sharedWorkstreamAgents is ws's agents, read from the organization's store, -// in the order they were added. Each is an agent (never a crew: the store -// keeps none), named as its person named it, with its instructions as the +// in the order they were added, with each name and instructions as the // brief a task it does is started with. func (h *Handler) sharedWorkstreamAgents(ws factory.OrgWorkstream) []WorkstreamAgent { - if h.config.Store == nil || len(ws.Agents) == 0 { + if h.config.Store == nil { return nil } agents, err := h.config.Store.OrgAgents() @@ -24,12 +28,24 @@ func (h *Handler) sharedWorkstreamAgents(ws factory.OrgWorkstream) []WorkstreamA return nil } var out []WorkstreamAgent - for _, l := range ws.Agents { + for _, l := range orgProjectAgentLinks(ws, agents) { a, ok := agents[l.Agent] if !ok || !linkStands(l, a) { continue } - out = append(out, WorkstreamAgent{ID: a.ID, Name: a.Name, Brief: a.Instructions}) + out = append(out, WorkstreamAgent{ID: a.ID, Name: a.Name, Brief: a.Instructions, Crew: a.Helper != "", Helper: a.Helper}) } return out } + +// An explicit chat conversion links the newly formed crew to its project. +func orgProjectAgentLinks(ws factory.OrgWorkstream, agents factory.OrgAgents) []factory.WorkstreamAgentLink { + var crews []factory.WorkstreamAgentLink + for id, a := range agents { + if a.CrewProject == ws.ID && a.Helper != "" && !slices.ContainsFunc(ws.Agents, func(link factory.WorkstreamAgentLink) bool { return link.Agent == id }) { + crews = append(crews, factory.WorkstreamAgentLink{Agent: id, By: a.Owner, At: a.UpdatedAt}) + } + } + slices.SortFunc(crews, func(a, b factory.WorkstreamAgentLink) int { return strings.Compare(a.Agent, b.Agent) }) + return append(slices.Clone(ws.Agents), crews...) +} diff --git a/internal/factory/serve/org_agents.go b/internal/factory/serve/org_agents.go index 0e51a89b8d..fda8309ddf 100644 --- a/internal/factory/serve/org_agents.go +++ b/internal/factory/serve/org_agents.go @@ -67,7 +67,7 @@ func linkStands(l factory.WorkstreamAgentLink, a factory.OrgAgent) bool { func (h *Handler) orgAgentWire(v Viewer, a factory.OrgAgent, all factory.OrgWorkstreams, nameOf func(string) string) api.OrgAgent { owner := factory.NormalizeHandle(a.Owner) - out := api.OrgAgent{ID: a.ID, Name: a.Name, Instructions: a.Instructions, Owner: owner, Roster: a.Roster, Team: a.Team, + out := api.OrgAgent{ID: a.ID, Name: a.Name, Instructions: a.Instructions, Owner: owner, Roster: a.Roster, Team: a.Team, Crew: a.Helper != "", Mine: owner == v.Handle, CreatedAt: a.CreatedAt.UTC().Format(time.RFC3339Nano), UpdatedAt: a.UpdatedAt.UTC().Format(time.RFC3339Nano)} if name := nameOf(owner); name != owner { out.OwnerName = name @@ -77,7 +77,7 @@ func (h *Handler) orgAgentWire(v Viewer, a factory.OrgAgent, all factory.OrgWork if ws.ArchivedAt != nil { continue } - for _, l := range ws.Agents { + for _, l := range orgProjectAgentLinks(ws, factory.OrgAgents{a.ID: a}) { if l.Agent == a.ID && linkStands(l, a) && v.canSee(ws) { out.Workstreams = append(out.Workstreams, ws.ID) } @@ -391,13 +391,17 @@ func (h *Handler) putOrgAgentRoster(w http.ResponseWriter, r *http.Request) { func (h *Handler) workstreamAgentRows(ws factory.OrgWorkstream, agents factory.OrgAgents) []api.WorkstreamAgentRow { nameOf := h.personNames() out := []api.WorkstreamAgentRow{} - for _, l := range ws.Agents { + for _, l := range orgProjectAgentLinks(ws, agents) { a, ok := agents[l.Agent] if !ok || !linkStands(l, a) { continue } owner := factory.NormalizeHandle(a.Owner) - row := api.WorkstreamAgentRow{ID: a.ID, Name: a.Name, Kind: "agent", From: "space", Owner: owner, Team: a.Team, + kind := "agent" + if a.Helper != "" { + kind = "crew" + } + row := api.WorkstreamAgentRow{ID: a.ID, Name: a.Name, Kind: kind, From: "space", Owner: owner, Team: a.Team, By: factory.NormalizeHandle(l.By), At: l.At.UTC().Format(time.RFC3339Nano)} if factory.NormalizeHandle(l.By) != owner { row.From = "org" @@ -466,7 +470,7 @@ func (h *Handler) addWorkstreamAgent(w http.ResponseWriter, r *http.Request) { return nil, errWorkstreamGone } before = cur - for i, l := range cur.Agents { + for i, l := range orgProjectAgentLinks(cur, agents) { if l.Agent == a.ID { if linkStands(l, a) { return nil, nil @@ -477,7 +481,7 @@ func (h *Handler) addWorkstreamAgent(w http.ResponseWriter, r *http.Request) { return []string{ws.ID}, nil } } - if len(cur.Agents) >= api.WorkstreamAgentsMost { + if len(orgProjectAgentLinks(cur, agents)) >= api.WorkstreamAgentsMost { return nil, errWorkstreamAgentsFull } cur.Agents = append(cur.Agents, link) @@ -519,6 +523,19 @@ func (h *Handler) removeWorkstreamAgent(w http.ResponseWriter, r *http.Request) h.fail(w, http.StatusForbidden, "only its person, or whoever edits this workstream, takes an agent off it") return } + if known && a.CrewProject == ws.ID { + agents, err = h.config.Store.EditOrgAgents(func(all factory.OrgAgents) error { + if current, exists := all[id]; exists && current.CrewProject == ws.ID { + current.CrewProject = "" + all[id] = current + } + return nil + }) + if h.failed(w, err) { + return + } + h.publishWorkstreams(api.EventWorkstreamChanged, v.Handle, &ws, ws) + } before := ws saved, err := h.config.Store.EditWorkstreams(func(all factory.OrgWorkstreams) ([]string, error) { cur, ok := all[ws.ID] @@ -559,7 +576,7 @@ func (h *Handler) chatAgent(ws factory.OrgWorkstream, person, id string) (factor if ws.Space { return a, agentUsableBy(person, a) } - for _, l := range ws.Agents { + for _, l := range orgProjectAgentLinks(ws, agents) { if l.Agent == id && linkStands(l, a) { return a, true } diff --git a/internal/factory/serve/work_home.go b/internal/factory/serve/work_home.go index 3968de46cb..ee883701cd 100644 --- a/internal/factory/serve/work_home.go +++ b/internal/factory/serve/work_home.go @@ -50,6 +50,7 @@ func (h *Handler) workHome(w http.ResponseWriter, r *http.Request) { } slices.SortFunc(out.Workstreams, func(a, b api.WorkHomeRow) int { return strings.Compare(a.Name, b.Name) }) out.PersonStatus = h.workPeopleStatus(out.People) + out.Tasks = tasksForClient(r, out.Tasks) h.write(w, http.StatusOK, out) } @@ -141,6 +142,7 @@ func (h *Handler) workOverview(w http.ResponseWriter, r *http.Request) { } slices.SortFunc(out.Children, func(a, b api.WorkstreamSummary) int { return strings.Compare(a.Name, b.Name) }) out.PersonStatus = h.workPeopleStatus(out.People) + out.Tasks = tasksForClient(r, out.Tasks) h.write(w, http.StatusOK, out) } diff --git a/internal/factory/serve/workstream_agent.go b/internal/factory/serve/workstream_agent.go index f20f6f0994..bfd6870576 100644 --- a/internal/factory/serve/workstream_agent.go +++ b/internal/factory/serve/workstream_agent.go @@ -121,6 +121,8 @@ type AgentTurn struct { // spent so far and how many steps it has taken, so the server can pause // it at a limit (workstream_task_limits.go). Nil on a person's message. Progress func(usd float64, steps int) + // CheckSpend applies the remaining place budget between crew members. + CheckSpend func(spent float64) error } // AgentOrg is what the set-up conversation knows of its organization, and @@ -133,6 +135,7 @@ type AgentOrg struct { // AgentPersona is a named agent a turn speaks as. type AgentPersona struct { ID, Name, Instructions string + Helper string } // AgentTask is the task a turn works. @@ -617,6 +620,17 @@ func (h *Handler) startAgentTurn(ws factory.OrgWorkstream, v wsViewer, asker, ch } run := AgentTurn{Workstream: ws.ID, Name: ws.Name, Turn: turn, Asker: asker, Text: text, LeashWords: leash, Now: now, TZ: tz, About: h.orgAbout(), Chat: chat, Space: ws.Space, Agent: persona, Key: h.orgModelKey(), Dir: filepath.Join(h.agentDir(seat), "agent"), Door: h.withLibrary(door), Library: h.spacesServed(), + CheckSpend: func(usd float64) error { + if ws.Space { + if limit, spent := h.spaceMonth(ws.ID); spent+usd >= limit { + return errors.New(spaceAtLimit) + } + } + if h.overBudget(ws.ID, usd) { + return errors.New("This workstream has spent its budget.") + } + return nil + }, Step: func(kind, text, tool string, failed bool) { switch kind { case api.AgentEntryStep, api.AgentEntryAgent, api.AgentEntryNote: diff --git a/internal/factory/serve/workstream_agent_task.go b/internal/factory/serve/workstream_agent_task.go index ab1a6cbfa2..13881b872c 100644 --- a/internal/factory/serve/workstream_agent_task.go +++ b/internal/factory/serve/workstream_agent_task.go @@ -188,7 +188,15 @@ func (h *Handler) launchLocked(r pendingRun) error { // Every line is a line of the task's Working conversation, and its // last step is what the running row says it is doing. Step: watch.noting(h.taskWorkStep(key, turn)), - Progress: watch.progress(limit, pause)} + Progress: watch.progress(limit, pause), + CheckSpend: func(usd float64) error { + if h.overBudget(ws.ID, usd) { + cause := runPause{kind: pauseBudget, usd: usd} + pause(cause) + return cause + } + return nil + }} guard.Go("factory workstream task", func() { // Counted out last of all, after the Working conversation has closed and // told its watchers: Close waits for this run, and nothing of it may @@ -241,15 +249,39 @@ func (h *Handler) launchLocked(r pendingRun) error { // It comes after the lease, which keeps the plain words: a resume // replays them through startTaskRun, and so through a fresh packet. run.Text, _ = h.taskPacket(ctx, door, task.ID, run.Text) + var crewID string + switch task.DoneBy.Kind { + case factory.TaskByCrew: + crewID = task.DoneBy.CrewID + case factory.TaskByAgent: + if task.DoneBy.Crew { + crewID = task.DoneBy.AgentID + } + } + var err error + if crewID != "" { + // A queued crew run has to follow the current project roster. + fresh, found, readErr := h.config.Store.Workstream(ws.ID) + a, listed := h.taskCrew(fresh, crewID) + switch { + case readErr != nil: + err = readErr + case !found || !listed: + err = errCrewNotHere + case a.Helper != "": + run.Agent = &AgentPersona{ID: a.ID, Name: a.Name, Instructions: a.Brief, Helper: a.Helper} + } + } wall := time.AfterFunc(taskWallMost, func() { pause(runPause{kind: pauseWall, usd: watch.spent()}) }) defer wall.Stop() var end AgentTurnEnd - var err error - if h.overBudget(ws.ID, 0) { - // Checked before the run spends anything. - pause(runPause{kind: pauseBudget}) - } else { - end, err = h.config.WorkstreamAgent(ctx, run) + if err == nil { + if h.overBudget(ws.ID, 0) { + // Checked before the run spends anything. + pause(runPause{kind: pauseBudget}) + } else { + end, err = h.config.WorkstreamAgent(ctx, run) + } } if ctx.Err() == nil { failed = err diff --git a/internal/factory/serve/workstream_decisions.go b/internal/factory/serve/workstream_decisions.go index f10e5507bb..5f24b10036 100644 --- a/internal/factory/serve/workstream_decisions.go +++ b/internal/factory/serve/workstream_decisions.go @@ -296,5 +296,5 @@ func (h *Handler) conflictWorkstreamTask(w http.ResponseWriter, r *http.Request) return } h.publishTasks(ws, h.orgActor(r), out.Task) - h.write(w, http.StatusOK, out.Task) + h.write(w, http.StatusOK, taskForClient(r, out.Task)) } diff --git a/internal/factory/serve/workstream_task_crew_test.go b/internal/factory/serve/workstream_task_crew_test.go new file mode 100644 index 0000000000..d2bd232b2c --- /dev/null +++ b/internal/factory/serve/workstream_task_crew_test.go @@ -0,0 +1,49 @@ +package serve + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Agent-Field/codeaf/internal/factory" + "github.com/Agent-Field/codeaf/internal/factory/api" +) + +func TestCreateTaskWithCrewDoer(t *testing.T) { + o, path := taskOrg(t, "edit") + o.h.config.WorkstreamAgents = func(factory.OrgWorkstream) []WorkstreamAgent { + return []WorkstreamAgent{{ID: "ag-copy", Name: "Copy crew", Crew: true}, {ID: "ag-solo", Name: "Solo"}} + } + for _, id := range []string{"ag-solo", "ag-other"} { + o.do(t, "santosh", "POST", path+"/tasks", -1, map[string]any{ + "title": "Draft release notes", "done_by": map[string]string{"kind": "crew", "crew_id": id}, + }, 422, nil) + } + var made api.WorkstreamTask + o.do(t, "santosh", "POST", path+"/tasks", -1, map[string]any{ + "title": "Draft release notes", "done_by": map[string]string{"kind": "crew", "crew_id": "ag-copy", "name": "Untrusted name"}, + }, 201, &made) + var read api.WorkstreamTask + o.do(t, "santosh", "GET", path+"/tasks/"+made.ID, -1, nil, 200, &read) + if read.DoneBy.Kind != "crew" || read.DoneBy.Name != "Copy crew" || read.Owner.ID != "santosh" { + t.Fatalf("task has doer %+v and owner %+v", read.DoneBy, read.Owner) + } + legacy := httptest.NewRequest(http.MethodGet, path+"/tasks/"+made.ID, nil) + legacy.Header.Set("Authorization", "Bearer "+o.tokens["santosh"]) + legacy.Header.Set("User-Agent", "codeaf-app") + rec := httptest.NewRecorder() + o.h.ServeHTTP(rec, legacy) + var before api.WorkstreamTask + if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &before) != nil || + before.DoneBy.Kind != "agent" || !before.DoneBy.Crew || before.DoneBy.AgentID != "ag-copy" { + t.Fatalf("older app read %d %s", rec.Code, rec.Body) + } + legacy.Header.Set(api.TaskCrewDoerHeader, "1") + rec = httptest.NewRecorder() + o.h.ServeHTTP(rec, legacy) + if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &read) != nil || + read.DoneBy.Kind != "crew" || read.DoneBy.CrewID != "ag-copy" { + t.Fatalf("new app read %d %s", rec.Code, rec.Body) + } +} diff --git a/internal/factory/serve/workstream_task_delete.go b/internal/factory/serve/workstream_task_delete.go index 3ac85c0e6b..49bb4de9cc 100644 --- a/internal/factory/serve/workstream_task_delete.go +++ b/internal/factory/serve/workstream_task_delete.go @@ -154,5 +154,5 @@ func (h *Handler) restoreWorkstreamTask(w http.ResponseWriter, r *http.Request) h.keepTaskSession(key) } h.publishTasks(ws, h.orgActor(r), append(changed, restored)...) - h.write(w, 200, restored) + h.write(w, 200, taskForClient(r, restored)) } diff --git a/internal/factory/serve/workstream_task_doers.go b/internal/factory/serve/workstream_task_doers.go index 0d99248b01..0911a3a460 100644 --- a/internal/factory/serve/workstream_task_doers.go +++ b/internal/factory/serve/workstream_task_doers.go @@ -18,10 +18,11 @@ import ( // the id a task's done_by names it by, the name people read, and the brief it // works by (what it is for, in its maker's words). type WorkstreamAgent struct { - ID string - Name string - Crew bool - Brief string + ID string + Name string + Crew bool + Brief string + Helper string } // errAgentNotHere is the refusal for a doer the workstream's agent list does @@ -64,6 +65,12 @@ func (h *Handler) checkDoer(ws factory.OrgWorkstream, d factory.TaskDoneBy) (fac return d, factory.TaskInvalid(errAgentNotHere.Error()) } d.Name, d.Crew = a.Name, a.Crew + case factory.TaskByCrew: + a, ok := h.taskCrew(ws, d.CrewID) + if !ok { + return d, factory.TaskInvalid(errCrewNotHere.Error()) + } + d = factory.TaskDoneBy{Kind: factory.TaskByCrew, CrewID: a.ID, Name: a.Name} } return d, nil } @@ -81,3 +88,10 @@ func agentTaskWords(name, brief string, t factory.WorkstreamTask) string { lines = append(lines, "", taskWords(t)) return strings.Join(lines, "\n") } + +var errCrewNotHere = errors.New("that crew is not one of this workstream's crews") + +func (h *Handler) taskCrew(ws factory.OrgWorkstream, id string) (WorkstreamAgent, bool) { + a, ok := h.workstreamAgent(ws, id) + return a, ok && a.Crew +} diff --git a/internal/factory/serve/workstream_task_wake.go b/internal/factory/serve/workstream_task_wake.go index dc66c115a6..44f5e0d121 100644 --- a/internal/factory/serve/workstream_task_wake.go +++ b/internal/factory/serve/workstream_task_wake.go @@ -55,6 +55,12 @@ func (h *Handler) wakeTaskDoer(ws factory.OrgWorkstream, t factory.WorkstreamTas return errAgentNotHere } return h.runTaskTurn(ws, t, starter, agentTaskWords(a.Name, a.Brief, t)) + case factory.TaskByCrew: + a, ok := h.taskCrew(ws, t.DoneBy.CrewID) + if !ok { + return errCrewNotHere + } + return h.runTaskTurn(ws, t, starter, agentTaskWords(a.Name, a.Brief, t)) case factory.TaskByChat: return h.runTaskTurn(ws, t, starter, agentTaskWords(firstNonEmpty(t.DoneBy.Name, "the chat's agent"), "", t)) } @@ -63,5 +69,5 @@ func (h *Handler) wakeTaskDoer(ws factory.OrgWorkstream, t factory.WorkstreamTas // wakeRefused reports whether err is a start the doer could not take. func wakeRefused(err error) bool { - return errors.Is(err, errTaskBusy) || errors.Is(err, errTaskNoRunner) || errors.Is(err, errAgentNotHere) || errors.Is(err, errBotRun) + return errors.Is(err, errTaskBusy) || errors.Is(err, errTaskNoRunner) || errors.Is(err, errAgentNotHere) || errors.Is(err, errCrewNotHere) || errors.Is(err, errBotRun) } diff --git a/internal/factory/serve/workstream_task_wire.go b/internal/factory/serve/workstream_task_wire.go new file mode 100644 index 0000000000..cc90e1f1ce --- /dev/null +++ b/internal/factory/serve/workstream_task_wire.go @@ -0,0 +1,24 @@ +package serve + +import ( + "net/http" + + "github.com/Agent-Field/codeaf/internal/factory" + "github.com/Agent-Field/codeaf/internal/factory/api" +) + +// Existing app clients understand crew as an agent with the crew flag. The +// modern HTTP shape exposes its own kind and id without changing storage. +func taskForClient(r *http.Request, task factory.WorkstreamTask) factory.WorkstreamTask { + if r.UserAgent() == "codeaf-app" && r.Header.Get(api.TaskCrewDoerHeader) != "1" && task.DoneBy.Kind == factory.TaskByCrew { + task.DoneBy = factory.TaskDoneBy{Kind: factory.TaskByAgent, AgentID: task.DoneBy.CrewID, Name: task.DoneBy.Name, Crew: true} + } + return task +} + +func tasksForClient(r *http.Request, tasks []factory.WorkstreamTask) []factory.WorkstreamTask { + for i, task := range tasks { + tasks[i] = taskForClient(r, task) + } + return tasks +} diff --git a/internal/factory/serve/workstream_tasks.go b/internal/factory/serve/workstream_tasks.go index b6ceb93372..d7b344e014 100644 --- a/internal/factory/serve/workstream_tasks.go +++ b/internal/factory/serve/workstream_tasks.go @@ -200,7 +200,7 @@ func (h *Handler) listWorkstreamTasks(w http.ResponseWriter, r *http.Request) { } h.fillForYou(ws, v, all) h.fillRead(ws, all) - h.write(w, http.StatusOK, api.WorkstreamTasks{Tasks: all}) + h.write(w, http.StatusOK, api.WorkstreamTasks{Tasks: tasksForClient(r, all)}) } // oneTask is the workstream and the task the path names, with every task of @@ -228,7 +228,7 @@ func (h *Handler) getWorkstreamTask(w http.ResponseWriter, r *http.Request) { one := []factory.WorkstreamTask{t} h.fillForYou(ws, v, one) h.fillRead(ws, one) - h.write(w, http.StatusOK, one[0]) + h.write(w, http.StatusOK, taskForClient(r, one[0])) } } @@ -319,7 +319,7 @@ func (h *Handler) createWorkstreamTask(w http.ResponseWriter, r *http.Request) { h.fail(w, http.StatusUnprocessableEntity, "a Factory task is its job: add the job to the workstream instead") return } - if body.DoneBy.Kind == factory.TaskByAgent { + if body.DoneBy.Kind == factory.TaskByAgent || body.DoneBy.Kind == factory.TaskByCrew { d, err := h.checkDoer(ws, body.DoneBy) if h.taskRefused(w, err) { return @@ -385,7 +385,7 @@ func (h *Handler) createWorkstreamTask(w http.ResponseWriter, r *http.Request) { } h.recordWorkstream(r, ws.ID, "added task", made.ID) h.publishTasks(ws, h.orgActor(r), made) - h.write(w, http.StatusCreated, nameTask(h.personNames(), made)) + h.write(w, http.StatusCreated, taskForClient(r, nameTask(h.personNames(), made))) } // readTasksIn is readTasks with the kept tasks read inside a write. jobs are @@ -520,7 +520,7 @@ func (h *Handler) patchWorkstreamTask(w http.ResponseWriter, r *http.Request) { r2.SetPathValue("id", target.ID) _, _, t, _, ok := h.oneTask(w, r2) if ok { - h.write(w, http.StatusOK, t) + h.write(w, http.StatusOK, taskForClient(r, t)) } return } @@ -676,7 +676,7 @@ func (h *Handler) patchWorkstreamTask(w http.ResponseWriter, r *http.Request) { if target.ID != "" { h.publishTasks(target, h.orgActor(r), out.Task) } - h.write(w, http.StatusOK, nameTask(h.personNames(), out.Task)) + h.write(w, http.StatusOK, taskForClient(r, nameTask(h.personNames(), out.Task))) } func (h *Handler) answerWorkstreamTask(w http.ResponseWriter, r *http.Request) { @@ -818,7 +818,7 @@ func (h *Handler) answerWorkstreamTask(w http.ResponseWriter, r *http.Request) { // The last Ask is answered: Afi goes on with the answer in hand. h.resumeTaskRun(ws, change.Task, v.Handle, answeredWords(change.Task, asked, answerLine(asked, body), by.Name), personTyped(r, body.Text)) } - h.write(w, http.StatusOK, fresh) + h.write(w, http.StatusOK, taskForClient(r, fresh)) } // wordsByBot is the writer kind of words a bot sent: never a person's. @@ -1048,7 +1048,7 @@ func (h *Handler) startAllWorkstreamTasks(w http.ResponseWriter, r *http.Request h.publishTasks(ws, h.orgActor(r), started...) } nameTasks(h.personNames(), started) - h.write(w, http.StatusOK, api.WorkstreamTasks{Tasks: started}) + h.write(w, http.StatusOK, api.WorkstreamTasks{Tasks: tasksForClient(r, started)}) } // startTask marks one ready task running as v, with its doer woken inside the diff --git a/internal/factory/store/resource_move.go b/internal/factory/store/resource_move.go index 935ffed5a3..e59339dc6d 100644 --- a/internal/factory/store/resource_move.go +++ b/internal/factory/store/resource_move.go @@ -4,12 +4,16 @@ import ( "database/sql" "path/filepath" + "github.com/Agent-Field/codeaf/internal/factory" "github.com/Agent-Field/codeaf/internal/factory/acl" ) // ResourceMove keeps the writer lock across the registry commit and the file // rename. Its operations must only be called inside WithResourceMove. -type ResourceMove struct{ db *sql.DB } +type ResourceMove struct { + db *sql.DB + store *Store +} // WithResourceMove acquires the writer lock before the caller takes any seat // lock. Task changes can already take the seat lock during a store write. @@ -19,13 +23,22 @@ func (st *Store) WithResourceMove(move func(ResourceMove) error) error { return err } return st.underLock(filepath.Join(st.root, workstreamsLock), func() error { - return move(ResourceMove{db: db}) + return move(ResourceMove{db: db, store: st}) }) } // MoveResource commits the new location and returns the previous row so a // failed rename can restore it. A pending grant drop survives a crash. func (m ResourceMove) MoveResource(next Resource, dropGrants bool) (Resource, error) { + return m.moveResource(next, dropGrants, nil, nil, 0) +} + +// MakeProjectWithChat keeps the new workstream and chat location in one commit. +func (m ResourceMove) MakeProjectWithChat(next Resource, project factory.OrgWorkstream, grant *acl.Grant, policyRev int) (Resource, error) { + return m.moveResource(next, false, &project, grant, policyRev) +} + +func (m ResourceMove) moveResource(next Resource, dropGrants bool, project *factory.OrgWorkstream, grant *acl.Grant, policyRev int) (Resource, error) { var before Resource err := workstreamTx(m.db, func(tx *sql.Tx) error { var err error @@ -33,6 +46,19 @@ func (m ResourceMove) MoveResource(next Resource, dropGrants bool) (Resource, er if err != nil { return err } + if project != nil { + if err := checkPolicyRev(tx, policyRev); err != nil { + return err + } + if err := putWorkstream(tx, normalizeWorkstream(*project)); err != nil { + return err + } + if grant != nil { + if err := m.store.insertGrant(tx, grant); err != nil { + return err + } + } + } if err := writeResource(tx, next, true, false); err != nil { return err } @@ -46,10 +72,26 @@ func (m ResourceMove) MoveResource(next Resource, dropGrants bool) (Resource, er // RestoreResource rolls back a registry commit when the files could not move. func (m ResourceMove) RestoreResource(before Resource) error { + return m.restoreResource(before, "") +} + +func (m ResourceMove) UndoNewProject(before Resource, project string) error { + return m.restoreResource(before, project) +} + +func (m ResourceMove) restoreResource(before Resource, project string) error { return workstreamTx(m.db, func(tx *sql.Tx) error { if err := writeResource(tx, before, true, false); err != nil { return err } + if project != "" { + if err := deleteResource(tx, "workstream", project); err != nil { + return err + } + if _, err := tx.Exec(`DELETE FROM workstreams WHERE id = ?`, project); err != nil { + return err + } + } return clearResourceMove(tx, before.Resource) }) } diff --git a/internal/factory/workstream_task.go b/internal/factory/workstream_task.go index 15d2500b73..f29afd164a 100644 --- a/internal/factory/workstream_task.go +++ b/internal/factory/workstream_task.go @@ -65,6 +65,7 @@ const ( // TaskByAgent is a named agent or crew (org-space DESIGN §4.1), by the // id the workstream's agent list knows it under. TaskByAgent = "agent" + TaskByCrew = "crew" ) // The kinds of event in a task's thread. @@ -182,6 +183,7 @@ type TaskDoneBy struct { // AgentID and Crew name a named agent or crew (Kind agent). AgentID string `json:"agent_id,omitempty"` Crew bool `json:"crew,omitempty"` + CrewID string `json:"crew_id,omitempty"` } // AgentDoes is whether an agent does t: Afi, a chat's agent or a named agent @@ -189,7 +191,7 @@ type TaskDoneBy struct { // Factory job starts at the Factory. func AgentDoes(t WorkstreamTask) bool { switch t.DoneBy.Kind { - case TaskByAfi, TaskByChat, TaskByAgent: + case TaskByAfi, TaskByChat, TaskByAgent, TaskByCrew: return true } return false @@ -207,7 +209,7 @@ func DoerWords(d TaskDoneBy) string { if d.Name != "" { return d.Name } - return firstNonEmptyWords(d.ID, d.AgentID, d.ChatID, d.Kind) + return firstNonEmptyWords(d.ID, d.AgentID, d.CrewID, d.ChatID, d.Kind) } // TaskCameFrom is where a task came from. @@ -1065,8 +1067,12 @@ func checkDoneBy(d TaskDoneBy) error { if strings.TrimSpace(d.AgentID) == "" || strings.TrimSpace(d.Name) == "" { return TaskInvalid("an agent's task names the agent: its agent_id and its name") } + case TaskByCrew: + if strings.TrimSpace(d.CrewID) == "" || strings.TrimSpace(d.Name) == "" { + return TaskInvalid("a crew's task names the crew: its crew_id and its name") + } default: - return TaskInvalid(`done_by is afi, agent, chat, factory or person`) + return TaskInvalid(`done_by is afi, agent, chat, crew, factory or person`) } return nil } diff --git a/internal/manual/chat/organization-agents.md b/internal/manual/chat/organization-agents.md index 71b889f740..28d03e919e 100644 --- a/internal/manual/chat/organization-agents.md +++ b/internal/manual/chat/organization-agents.md @@ -20,7 +20,7 @@ In a workstream you can chat with any agent that workstream lists (below). If th The Agents part of a workstream's People and rules lists Afi first, then each agent the workstream may use. Anyone who can edit the workstream can add one (**Add an agent**: from your own, or from the organization's list) or take one off. You can always take your own agent off a workstream. A workstream lists 50 agents at most, and My space takes none: your agents are already there. -These are the agents a task in that workstream may be given to. Ask Afi ("give the launch post to Copywriter") and it makes the task with that agent as its doer; when the task starts, the organization's server runs it as that agent, with the agent's instructions and the task's request, never a private chat. An agent the workstream has not added is refused, and one taken off the workstream, or deleted, stops being offered at once. No screen offers an agent as a doer: the Done by choices are Afi, your chats, you and the workstream's people. +These are the agents a task in that workstream may be given to. Ask Afi ("give the launch post to Copywriter") and it makes the task with that agent as its doer; when the task starts, the organization's server runs it as that agent, with the agent's instructions and the task's request, never a private chat. An agent the workstream has not added is refused, and one taken off the workstream, or deleted, stops being offered at once. Add task and Done by list the agents and crews the project can use when its server can run them. ## The organization's list of agents — asking the operator to approve an agent for everyone @@ -34,6 +34,10 @@ Nothing, until you ask for the organization's list. An agent you keep to yoursel When the operator removes someone from the organization, their agents go to the heir with the rest of their space. Workstreams they shared an agent into keep it, now shared by the heir. -## What agents in an organization cannot do yet +## Switch Always on or Bring in helpers in a project chat -There are no crews in an organization: an agent works alone. Only Afi gives a task to a named agent, and only to one on the workstream's Agents list. Agents cannot be moved into a workstream (only shared). An agent cannot be given tools beyond those a chat in that place has. +In your project chat, open the doer menu and choose **Switch Always on**. Give the agent a name and instructions. It keeps its conversation and memory in place and gains a private entry under your agents. The project's standing orders stay in the project. A chat that's answering needs to finish or stop first. + +**Bring in helpers** makes a two-member crew from your chat. Name the crew, tell its manager what to do, and write the helper's brief. The helper gives advice to the manager on the current request. The manager has the project's usual tools and works under its usual rules and budget. From a project, this also adds a crew doer to the project's Agents list. A task the crew does starts from the task's brief and has its own run. The chat's history stays with you. + +An agent cannot be given tools beyond those a chat in that place has. diff --git a/internal/manual/chat/organization-sharing.md b/internal/manual/chat/organization-sharing.md index 48a86ea04a..58716d9ebc 100644 --- a/internal/manual/chat/organization-sharing.md +++ b/internal/manual/chat/organization-sharing.md @@ -55,6 +55,8 @@ By default only the person whose chat it is can move it (the operator can let pe Pages and files do not move this way: they keep **Move to workstream…** (see "Moving a document from My space into a workstream"). Afi's pane and a task's working conversation belong to their workstream and cannot be moved. +**Make this a project** creates a project and moves your chat into it. The conversation stays yours, and the work it makes there is shared under the new project's rules. Existing files and tasks stay where they were made. If the chat uses a named agent, you must have permission to share that agent into the new project. + ## Who may move a chat — the owner by default, and the policy setting that lets people with manage do it too By default only the person whose chat it is can move it, and they need permission to manage it. Someone a chat is shared with cannot move it, whatever role they hold, and a bot never can. They read "Only the person who owns this chat can move it, and they need permission to manage it." diff --git a/internal/manual/chat/organization-workstream-tasks.md b/internal/manual/chat/organization-workstream-tasks.md index bd21939d33..9ff7f55a55 100644 --- a/internal/manual/chat/organization-workstream-tasks.md +++ b/internal/manual/chat/organization-workstream-tasks.md @@ -66,7 +66,7 @@ Below 1100 pixels of content width, or while Afi's pane is open, selecting a tas Shift-click selects the visible range from the first selected task. Command-click, or Control-click on Linux, adds or removes a task. Shift with Up or Down extends a selection. Folded tasks are not included. A selection of several tasks stays marked in the list, and the pane says "3 tasks selected" with the controls they share: Done by, Owner, Due and Group, then "Only what all three allow". A row's checkbox selects or unselects it; it never marks it done. Clear returns to reading one task. One task is never a selection, so changing one task's Done by asks no question first. Below 1100 pixels of content width, or with Afi's pane open, the list stays when you select: the selection's pane sits above the rows, so you can keep adding to it. -Done by offers only choices every selected task allows: the owner or workstream steward can change a doer, but completed tasks and Factory tasks cannot be handed over here. The choices are Afi, your chats in this workstream, You, and its people. Named agents and the Factory are not offered as replacements. When every selected task allows Afi and they are not all Afi's already, the pane opens with Afi chosen: “Give these N to Afi”, the consequences, Give and Cancel. Choosing another doer shows the same with its name. The owner is unchanged. Ready agent tasks start through the normal Start door; unfinished waits stay Up next. If one task is refused, the others are still handed over. The selection names each refused task and its reason; the list refreshes before you retry. The What happens section names a task’s predicted ask-first step when the workstream supplies one, from its ask rule. Past five tasks those lines are counted instead ("6 will ask you first, before anything is published or sent"). +Done by offers only choices every selected task allows: the owner or workstream steward can change a doer, but completed tasks and Factory tasks cannot be handed over here. The choices include Afi, your chats, you, and the project's people. A project's named agents and crews are offered when its server can run them. A Factory task is created by adding its job instead. When every selected task allows Afi and they are not all Afi's already, the pane opens with Afi chosen: “Give these N to Afi”, the consequences, Give and Cancel. Choosing another doer shows the same with its name. The owner is unchanged. Ready agent tasks start through the normal Start door; unfinished waits stay Up next. If one task is refused, the others are still handed over. The selection names each refused task and its reason; the list refreshes before you retry. The What happens section names a task’s predicted ask-first step when the workstream supplies one, from its ask rule. Past five tasks those lines are counted instead ("6 will ask you first, before anything is published or sent"). A Personal workstream keeps its tasks on this computer; an organization workstream keeps them on the organization's server. They behave the same.