Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions cmd/codeaf-replay/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
3 changes: 3 additions & 0 deletions cmd/codeaf/appfactory_org.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
63 changes: 56 additions & 7 deletions cmd/codeaf/factory_workstream_agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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,
Expand All @@ -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).
Expand All @@ -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.
Expand All @@ -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):
Expand All @@ -147,14 +171,39 @@ 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()
}
return serve.AgentTurnEnd{USD: usd, Transient: transientModelError(failed)}, failed
}
}

// 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
Expand Down
52 changes: 52 additions & 0 deletions cmd/codeaf/factory_workstream_agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"

"github.com/Agent-Field/codeaf/internal/factory"
Expand Down Expand Up @@ -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)
}
}
1 change: 1 addition & 0 deletions cmd/codeaf/testdata/model_spend_owners.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions docs/changes/unreleased/3013-org-chat-transitions.md
Original file line number Diff line number Diff line change
@@ -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.
18 changes: 17 additions & 1 deletion docs/design/app-v3/PROTOCOL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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}` |
Expand Down Expand Up @@ -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:<chat id>` (`hosted:<chat id>:own` when the call used the person's own key), so
Expand Down Expand Up @@ -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
<old doer> to <new doer>".
`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
Expand Down
19 changes: 13 additions & 6 deletions internal/appwire/factory_org.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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 == "" {
Expand Down Expand Up @@ -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
Expand Down
53 changes: 53 additions & 0 deletions internal/appwire/factory_org_chat_transition.go
Original file line number Diff line number Diff line change
@@ -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
})

}
Loading
Loading