diff --git a/README.md b/README.md index 58f9d31..5195f5c 100644 --- a/README.md +++ b/README.md @@ -98,13 +98,20 @@ keys act as their user with the Viewer role. External-subject keys act as an active registered agent whose immutable handle equals the subject. The rules are in [`design/API.md`](design/API.md#access-keys-v0111). -### Agent protocol (0.1.13) - -An Admin registers agents through `POST /api/tracker/v1/agents`, with a handle, -display name, description and accountable person owner. Keys are issued and -revoked by the platform, never by Tracker. Disabling an agent rejects all its -keys, cancels its non-terminal runs and withdraws its open requests. Names and -owners may change; handles cannot. Existing issue attribution is not rewritten. +### Agent protocol (0.1.14) + +An agent registers itself: the first call of a new external-subject key is +`POST /api/tracker/v1/agents/register` with a display name, description and +its accountable person owner; the handle is the key's subject. Minting that +key needs a Project admin, which is the admission decision. The owner is +claimed by the agent, so the Agents page marks self-registered agents with the +key that registered them. An Admin can also register an agent directly through +`POST /api/tracker/v1/agents`. Keys are issued and revoked by the platform, +never by Tracker. Disabling an agent rejects all its keys (it cannot register +again), cancels its non-terminal runs and withdraws its open requests. Names +and owners may change; handles cannot. Existing issue attribution is not +rewritten. The rules are in +[`design/API.md`](design/API.md#self-registration-v0114). Agents poll `/inbox` and `/events`. Initialize the event cursor without `after`, then poll with `after=next`; sequence allocation and the represented write @@ -169,14 +176,14 @@ a required BuildKit secret, never through build arguments or committed files. ## Catalog and release -The next app release is **0.1.13**, also recorded in `web/package.json`. +The next app release is **0.1.14**, also recorded in `web/package.json`. `catalog/entry.yaml` carries no committed version: the first tag (`v0.1.0`) created `versions[]` with `ghcr.io/appthrust/tracker@sha256:`, stream `0.1`; later tags append at publication time. Do not add a version with an unbuilt or placeholder image digest. OpenAPI's `info.version` describes the API schema, not the app release. This repository has no hand-maintained changelog. -After the release prerequisites are available, push the SemVer tag `v0.1.13`. +After the release prerequisites are available, push the SemVer tag `v0.1.14`. The tag workflow: 1. Performs one multi-platform build on `ubuntu-24.04` for Linux amd64 and arm64, @@ -196,8 +203,8 @@ The tag workflow: Publication commands used by the workflow: ```sh -bun hack/publish-entry.ts submit --version 0.1.13 --digest sha256: -bun hack/publish-entry.ts await --version 0.1.13 --digest sha256: +bun hack/publish-entry.ts submit --version 0.1.14 --digest sha256: +bun hack/publish-entry.ts await --version 0.1.14 --digest sha256: ``` Writers are serialized by `tracker-catalog-publish`; the workflow is guarded to @@ -218,7 +225,7 @@ After publication, each estate's `AppCatalogSource` syncs the signed catalog. Install Issues from the Project Marketplace (Directory is an automatic dependency). Existing `follow` installations on stream `0.1` roll to the new version; `pinned` installations show `UpdateAvailable` and require an explicit -version update. Confirm the installation is Ready, `/releasez` reports `0.1.13`, +version update. Confirm the installation is Ready, `/releasez` reports `0.1.14`, the Project lists the `tracker` Access Key space as Ready, and an exchanged key reads `/api/tracker/v1/me`. These are release steps, not actions performed by a source-only version bump. diff --git a/cmd/server/internal/api/agents.go b/cmd/server/internal/api/agents.go index 558132f..9abaf29 100644 --- a/cmd/server/internal/api/agents.go +++ b/cmd/server/internal/api/agents.go @@ -1,6 +1,7 @@ package api import ( + "github.com/appthrust/appserver-go/appserver/httpx" "github.com/appthrust/tracker/cmd/server/internal/domain" "github.com/appthrust/tracker/cmd/server/internal/store" "strconv" @@ -40,6 +41,22 @@ func (a *API) agentCreate(s *request) (any, int, error) { return &item, 201, err } +func (a *API) agentRegister(s *request) (any, int, error) { + if !s.actor.Key || s.actor.Kind != "agent" { + return nil, 0, httpx.Forbidden() + } + var input store.AgentRegister + if err := decode(s, &input); err != nil { + return nil, 0, err + } + item, created, err := s.tx.RegisterAgent(input, s.actor, s.keyName) + status := 200 + if created { + status = 201 + } + return &item, status, err +} + func (a *API) inbox(s *request) (any, int, error) { list, err := s.tx.Inbox(s.actor) return items[domain.InboxItem]{Items: list}, 200, err diff --git a/cmd/server/internal/api/agents_test.go b/cmd/server/internal/api/agents_test.go index 01a9b32..8b14acd 100644 --- a/cmd/server/internal/api/agents_test.go +++ b/cmd/server/internal/api/agents_test.go @@ -1,10 +1,19 @@ package api import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" "testing" "time" "github.com/appthrust/appserver-go/accesskey" + "github.com/appthrust/appserver-go/appserver/identity" "github.com/appthrust/tracker/cmd/server/internal/domain" "github.com/appthrust/tracker/cmd/server/internal/store" "github.com/stretchr/testify/require" @@ -153,3 +162,212 @@ func TestAgentLeaseWaitingAndDisabledBoundaries(t *testing.T) { require.Equal(t, "assigneeSub", issues[0].(map[string]any)["path"]) } } + +func TestAgentSelfRegistration(t *testing.T) { + private, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + signer := accesskey.NewES256Signer("registration-test", private) + jwks := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/access/jwks.json" { + http.NotFound(w, r) + return + } + _ = json.NewEncoder(w).Encode(signer.JWKS()) + })) + t.Cleanup(jwks.Close) + issuer := accesskey.IssuerURL(jwks.URL) + h := newHarnessTrusting(t, identity.Trust{AccessIssuer: issuer, AccessAudience: "tracker"}) + assertion := func(subject accesskey.Subject, keyName string, scopes ...string) string { + value, err := signer.Sign(accesskey.Claims{ + Issuer: issuer, Audience: "tracker", Project: "pj-test", KeyName: keyName, Subject: subject, + Scopes: scopes, JTI: "test", IssuedAt: time.Now(), ExpiresAt: time.Now().Add(time.Minute), + }) + require.NoError(t, err) + return "Bearer " + value + } + external := func(handle string, scopes ...string) string { + return assertion(accesskey.Subject{Kind: accesskey.SubjectExternal, ID: handle}, "ak-register", scopes...) + } + bearer := external("self-agent", scopeRead, scopeWrite) + body := []byte(`{"name":"Self Agent","description":"Registers itself","ownerSub":"owner"}`) + checkBlockedRoutes := func(t *testing.T) { + t.Helper() + for _, route := range (&API{}).routes() { + if route.pattern == "POST /agents/register" || route.pattern == "GET /agent-guide" { + continue + } + method, path, _ := strings.Cut(route.pattern, " ") + path = strings.ReplaceAll(path, "{id}", "01JABCDEFGHJKMNPQRSTVWXYZ0") + data := rawCall(t, h, bearer, method, path, "", []byte(`{}`), 403) + require.Contains(t, string(data), `"error":"key_subject"`, route.pattern) + } + data := rawCall(t, h, bearer, "GET", "/people/person-1/avatar", "", nil, 403) + require.Contains(t, string(data), `"error":"key_subject"`) + guide := rawCall(t, h, bearer, "GET", "/agent-guide", "", nil, 200) + require.Contains(t, string(guide), "POST /agents/register") + } + t.Run("unregistered routes", checkBlockedRoutes) + data := rawCall(t, h, bearer, "GET", "/me", "", nil, 403) + require.Contains(t, string(data), "POST /api/tracker/v1/agents/register") + + // Reads and user-key writes cannot supply the owner's signed-in name. + rawCall(t, h, "Bearer "+token("read-owner"), "GET", "/me", "", nil, 200) + userKey := assertion(accesskey.Subject{Kind: accesskey.SubjectUser, ID: "key-owner"}, "ak-user", scopeRead, scopeWrite) + rawCall(t, h, userKey, "POST", "/issues", "", []byte(`{"title":"Only a key wrote","type":"task"}`), 201) + for _, owner := range []string{"unknown-owner", "read-owner", "key-owner", "agent:01JABCDEFGHJKMNPQRSTVWXYZ0", ""} { + t.Run("invalid owner "+owner, func(t *testing.T) { + input, err := json.Marshal(map[string]string{"name": "Self Agent", "ownerSub": owner}) + require.NoError(t, err) + data := rawCall(t, h, bearer, "POST", "/agents/register", "", input, 400) + var failure struct { + Code string `json:"error"` + Issues []domain.FieldError `json:"issues"` + } + require.NoError(t, json.Unmarshal(data, &failure)) + require.Equal(t, "invalid", failure.Code) + require.Len(t, failure.Issues, 1) + require.Equal(t, "ownerSub", failure.Issues[0].Path) + }) + } + for _, tc := range []struct { + name, bearer, code string + status int + }{ + {"user key", userKey, "forbidden", 403}, + {"signed-in admin", "Bearer " + token("admin"), "forbidden", 403}, + {"signed-in person", "Bearer " + token("owner"), "forbidden", 403}, + {"read-only external key", external("self-agent", scopeRead), "insufficient_scope", 403}, + {"invalid handle", external("Invalid_handle", scopeWrite), "invalid", 400}, + } { + t.Run(tc.name, func(t *testing.T) { + data := rawCall(t, h, tc.bearer, "POST", "/agents/register", "", body, tc.status) + require.Contains(t, string(data), `"error":"`+tc.code+`"`) + }) + } + claims, err := json.Marshal(map[string]string{"sub": "owner", "name": "Olivia Owner", "email": "owner@example.test"}) + require.NoError(t, err) + session := "Bearer " + base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"none"}`)) + "." + base64.RawURLEncoding.EncodeToString(claims) + "." + rawCall(t, h, session, "POST", "/issues", "", []byte(`{"title":"Signed-in owner","type":"task"}`), 201) + for _, tc := range []struct { + name, body string + }{ + {"empty name", `{"name":"","ownerSub":"owner"}`}, + {"blank name", `{"name":" ","ownerSub":"owner"}`}, + {"long name", `{"name":"` + strings.Repeat("あ", 201) + `","ownerSub":"owner"}`}, + {"long description", `{"name":"Agent","description":"` + strings.Repeat("é", 2049) + `","ownerSub":"owner"}`}, + {"body handle", `{"name":"Agent","ownerSub":"owner","handle":"other-agent"}`}, + {"body provenance", `{"name":"Agent","ownerSub":"owner","registeredByKey":"ak-forged"}`}, + } { + t.Run(tc.name, func(t *testing.T) { + data := rawCall(t, h, bearer, "POST", "/agents/register", "", []byte(tc.body), 400) + require.Contains(t, string(data), `"error":"invalid"`) + }) + } + + eventsBefore := call[map[string]any](h, "admin", "GET", "/events", nil, 200) + data = rawCall(t, h, bearer, "POST", "/agents/register", "register-start", body, 201) + var agent domain.Agent + require.NoError(t, json.Unmarshal(data, &agent)) + require.Equal(t, "self-agent", agent.Handle) + require.Equal(t, "Self Agent", agent.Name) + require.Equal(t, "Registers itself", agent.Description) + require.Equal(t, domain.Person{Sub: "owner", Name: "Olivia Owner"}, agent.Owner) + require.NotNil(t, agent.RegisteredByKey) + require.Equal(t, "ak-register", *agent.RegisteredByKey) + require.False(t, agent.Disabled) + require.NoError(t, h.database.InWorkspace(t.Context(), "pj-test", false, func(tx *store.Tx) error { + stored, err := tx.Agent(agent.ID) + require.NoError(t, err) + require.Equal(t, agent.Owner, stored.Owner) + require.Equal(t, agent.RegisteredByKey, stored.RegisteredByKey) + return nil + })) + for _, input := range [][]byte{body, []byte(`{"name":"","description":"Ignored","ownerSub":"agent:ignored"}`)} { + data = rawCall(t, h, bearer, "POST", "/agents/register", "register-start", input, 200) + var existing domain.Agent + require.NoError(t, json.Unmarshal(data, &existing)) + require.Equal(t, agent.ID, existing.ID) + require.Equal(t, agent.Name, existing.Name) + require.Equal(t, agent.Description, existing.Description) + require.Equal(t, agent.Owner, existing.Owner) + require.Equal(t, agent.RegisteredByKey, existing.RegisteredByKey) + require.Equal(t, agent.CreatedAt, existing.CreatedAt) + require.Equal(t, agent.UpdatedAt, existing.UpdatedAt) + } + data = rawCall(t, h, bearer, "POST", "/agents/register", strings.Repeat("k", 129), body, 200) + require.Contains(t, string(data), `"id":"`+agent.ID+`"`, "the idempotency header is ignored, not validated") + eventsAfter := call[map[string]any](h, "admin", "GET", "/events", nil, 200) + require.Equal(t, eventsBefore, eventsAfter, "registration must not emit an issue event") + data = rawCall(t, h, bearer, "POST", "/agents/register", "", []byte(`{"name":123,"ownerSub":"owner"}`), 400) + require.Contains(t, string(data), `"error":"invalid"`, "an existing agent must still decode the body shape") + data = rawCall(t, h, bearer, "GET", "/me", "", nil, 200) + require.Contains(t, string(data), `"kind":"agent"`) + require.Contains(t, string(data), `"sub":"agent:`+agent.ID+`"`) + + rotated := assertion(accesskey.Subject{Kind: accesskey.SubjectExternal, ID: "self-agent"}, "ak-rotated", scopeWrite) + data = rawCall(t, h, rotated, "POST", "/agents/register", "", body, 200) + var existing domain.Agent + require.NoError(t, json.Unmarshal(data, &existing)) + require.Equal(t, agent.RegisteredByKey, existing.RegisteredByKey) + patched := call[domain.Agent](h, "admin", "PATCH", "/agents/"+agent.ID, map[string]string{"name": "Renamed", "description": "Updated", "ownerSub": "admin"}, 200) + require.Equal(t, agent.RegisteredByKey, patched.RegisteredByKey) + call[any](h, "admin", "PATCH", "/agents/"+agent.ID, map[string]string{"registeredByKey": "ak-forged"}, 400) + disabled := call[domain.Agent](h, "admin", "PATCH", "/agents/"+agent.ID, map[string]bool{"disabled": true}, 200) + require.Equal(t, agent.RegisteredByKey, disabled.RegisteredByKey) + data = rawCall(t, h, bearer, "POST", "/agents/register", "register-start", body, 403) + require.Contains(t, string(data), `"error":"key_subject"`) + require.Contains(t, string(data), "The access key subject is not an active registered agent") + t.Run("disabled routes", checkBlockedRoutes) + agents := call[items[domain.Agent]](h, "admin", "GET", "/agents?includeDisabled=true", nil, 200) + require.Len(t, agents.Items, 1) + require.True(t, agents.Items[0].Disabled) + require.Equal(t, patched.Name, agents.Items[0].Name) + require.Equal(t, patched.Owner, agents.Items[0].Owner) + require.Equal(t, agent.RegisteredByKey, agents.Items[0].RegisteredByKey) + + // Registration is allowed with write alone, and uses character/byte limits. + limits := []byte(`{"name":"` + strings.Repeat("あ", 200) + `","description":"` + strings.Repeat("é", 2048) + `","ownerSub":"owner"}`) + rawCall(t, h, external("limit-agent", scopeWrite), "POST", "/agents/register", "", limits, 201) + adminAgent := rawCall(t, h, "Bearer "+token("admin"), "POST", "/agents", "", []byte(`{"handle":"admin-agent","name":"Admin Agent","ownerSub":"admin"}`), 201) + require.Contains(t, string(adminAgent), `"registeredByKey":null`) + data = rawCall(t, h, external("admin-agent", scopeWrite), "POST", "/agents/register", "", body, 200) + require.Contains(t, string(data), `"registeredByKey":null`, "self-registration cannot take credit for an Admin-created agent") +} + +func TestAgentSelfRegistrationContract(t *testing.T) { + allowed := []string{} + for _, route := range (&API{}).routes() { + if route.unregistered { + allowed = append(allowed, route.pattern) + } + } + require.ElementsMatch(t, []string{"POST /agents/register", "GET /agent-guide"}, allowed) + var document struct { + Components struct { + Schemas map[string]struct { + Properties map[string]json.RawMessage `json:"properties"` + Required []string `json:"required"` + AdditionalProperties bool `json:"additionalProperties"` + } `json:"schemas"` + } `json:"components"` + Paths map[string]map[string]struct { + Responses map[string]json.RawMessage `json:"responses"` + } `json:"paths"` + } + require.NoError(t, json.Unmarshal(openapiDocument, &document)) + agent := document.Components.Schemas["Agent"] + require.Contains(t, agent.Required, "registeredByKey") + var provenance struct { + AnyOf []map[string]string `json:"anyOf"` + } + require.NoError(t, json.Unmarshal(agent.Properties["registeredByKey"], &provenance)) + require.ElementsMatch(t, []map[string]string{{"type": "string"}, {"type": "null"}}, provenance.AnyOf) + input := document.Components.Schemas["AgentRegister"] + require.ElementsMatch(t, []string{"name", "ownerSub"}, input.Required) + require.NotContains(t, input.Properties, "handle") + require.NotContains(t, input.Properties, "registeredByKey") + require.False(t, input.AdditionalProperties) + for _, status := range []string{"200", "201", "400", "401", "403", "503"} { + require.Contains(t, document.Paths["/agents/register"]["post"].Responses, status) + } +} diff --git a/cmd/server/internal/api/api.go b/cmd/server/internal/api/api.go index 46f9fcb..c980e83 100644 --- a/cmd/server/internal/api/api.go +++ b/cmd/server/internal/api/api.go @@ -29,11 +29,12 @@ type API struct { mux *http.ServeMux } type request struct { - r *http.Request - w http.ResponseWriter - tx *store.Tx - actor domain.Actor - bearer string + r *http.Request + w http.ResponseWriter + tx *store.Tx + actor domain.Actor + bearer string + keyName string } type endpoint func(*request) (any, int, error) @@ -41,7 +42,7 @@ func New(database *store.Store, auth *identity.Authenticator, upstream *platform a := &API{store: database, identity: auth, platform: upstream, directory: people, workspace: workspace, mux: http.NewServeMux()} a.mux.HandleFunc("GET /api/tracker/v1/openapi.json", a.openapi) for _, route := range a.routes() { - a.route(route.pattern, route.mutation, route.roles, route.handler) + a.route(route.pattern, route.mutation, route.roles, route.unregistered, route.handler) } a.mux.HandleFunc("GET /api/tracker/v1/people/{id}/avatar", a.avatar) a.mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) { httpx.WriteError(w, httpx.NotFound(), "tracker") }) @@ -60,7 +61,7 @@ func (a *API) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-store") a.mux.ServeHTTP(w, r) } -func (a *API) route(pattern string, mutation, roles bool, fn endpoint) { +func (a *API) route(pattern string, mutation, roles, unregistered bool, fn endpoint) { method, path, _ := bytes.Cut([]byte(pattern), []byte(" ")) a.mux.HandleFunc(string(method)+" /api/tracker/v1"+string(path), func(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) @@ -81,6 +82,7 @@ func (a *API) route(pattern string, mutation, roles bool, fn endpoint) { // The assertion is addressed to Tracker only: it is never forwarded // to Directory. The person's name comes from Tracker's own record. s.actor = actor + s.keyName = claims.Principal.KeyName if mutation { log.Printf("tracker access key mutation: %s %s key=%q subject=%q request_id=%q", r.Method, r.URL.Path, claims.Principal.KeyName, actor.Sub, r.Header.Get("X-Request-Id")) } @@ -124,10 +126,14 @@ func (a *API) route(pattern string, mutation, roles bool, fn endpoint) { if key && s.actor.Kind == "agent" { actor, err := tx.AgentBySubject(s.actor.Sub) if err != nil { - return err + var response *httpx.Error + if !unregistered || !errors.As(err, &response) || response.Code != "key_subject" { + return err + } + } else { + actor.Scopes = s.actor.Scopes + s.actor = actor } - actor.Scopes = s.actor.Scopes - s.actor = actor } else if key { name, err := tx.KnownName(s.actor.Sub) if err != nil { diff --git a/cmd/server/internal/api/collaboration_test.go b/cmd/server/internal/api/collaboration_test.go index ade7f1a..c4f76bc 100644 --- a/cmd/server/internal/api/collaboration_test.go +++ b/cmd/server/internal/api/collaboration_test.go @@ -191,7 +191,7 @@ func TestAgentGuideAndOpenAPIShapes(t *testing.T) { require.Contains(t, document.Components.Schemas, name) } for path, methods := range document.Paths { - if operation, ok := methods["post"]; ok && !strings.HasSuffix(path, "/attachments") { + if operation, ok := methods["post"]; ok && path != "/agents/register" && !strings.HasSuffix(path, "/attachments") { parameters, err := json.Marshal(operation["parameters"]) require.NoError(t, err) require.Contains(t, string(parameters), "Idempotency-Key", path) diff --git a/cmd/server/internal/api/idempotency.go b/cmd/server/internal/api/idempotency.go index 62f9e17..6ddd5e2 100644 --- a/cmd/server/internal/api/idempotency.go +++ b/cmd/server/internal/api/idempotency.go @@ -26,7 +26,7 @@ func (a *API) execute(s *request, fn endpoint) (any, int, error) { return body, status, nil } key := s.r.Header.Get("Idempotency-Key") - if s.r.Method != http.MethodPost || key == "" || strings.HasSuffix(s.r.URL.Path, "/attachments") { + if s.r.Method != http.MethodPost || key == "" || s.r.URL.Path == "/api/tracker/v1/agents/register" || strings.HasSuffix(s.r.URL.Path, "/attachments") { return invoke() } if !domain.Text(key, 1, 128) { diff --git a/cmd/server/internal/api/keys.go b/cmd/server/internal/api/keys.go index e5fa3a1..e9012ce 100644 --- a/cmd/server/internal/api/keys.go +++ b/cmd/server/internal/api/keys.go @@ -18,7 +18,8 @@ const ( // // The Project claim is the tenant boundary. All keys remain Viewers and never // reach Platform role lookup or Directory. External subjects are resolved to -// active registered agents inside the request transaction. +// active registered agents inside the request transaction, except on routes +// explicitly admitting keys before registration. func keyActor(principal accesskey.Principal, project string, mutation bool) (domain.Actor, error) { if principal.Project != project { return domain.Actor{}, httpx.Fail(401, "unauthenticated", "A valid bearer token is required") diff --git a/cmd/server/internal/api/openapi.json b/cmd/server/internal/api/openapi.json index 1161d1c..eb2f444 100644 --- a/cmd/server/internal/api/openapi.json +++ b/cmd/server/internal/api/openapi.json @@ -2,7 +2,7 @@ "openapi": "3.1.0", "info": { "title": "Tracker API", - "version": "0.1.13", + "version": "0.1.14", "description": "Contract: design/API.md. One workspace per PLATFORM_PROJECT_ID. The bearer is the signed-in user's token or an Access Key assertion (audience tracker; scope tracker:read for GET, tracker:write otherwise). External-subject assertions resolve by immutable registered agent handle. GET scopes tracker:read; other methods tracker:write; missing scope is 403 insufficient_scope. Every key is refused on Admin routes. See /agent-guide for the collaboration protocol." }, "servers": [ @@ -4729,6 +4729,105 @@ ] } }, + "/agents/register": { + "post": { + "operationId": "registerAgent", + "summary": "registerAgent", + "description": "External-subject key with tracker:write only. The immutable handle comes from the assertion. ownerSub must be a person with a signed-in write in this workspace; their recorded name is stored. Creates an agent with registeredByKey set to the assertion's Access Key name. An active registration returns 200 without applying the body; a disabled agent returns 403 key_subject. Idempotency-Key is ignored: every call checks the current registration and disabled state. Normal lastSeenAt observation still applies.", + "responses": { + "201": { + "description": "Agent registered", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Agent" + } + } + } + }, + "200": { + "description": "Existing active agent; request body not applied", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Agent" + } + } + } + }, + "400": { + "description": "Invalid request; unknown or non-person owner has issue path ownerSub", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden caller, insufficient_scope, or disabled key_subject", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AgentRegister" + } + } + } + } + } + }, "/agents/{id}": { "patch": { "operationId": "patchAgent", @@ -6267,7 +6366,7 @@ "get": { "operationId": "getAgentGuide", "summary": "getAgentGuide", - "description": "Agent protocol generated from the handler route table.", + "description": "Agent protocol generated from the handler route table. External keys with tracker:read may read it even before registration or when their agent is disabled.", "responses": { "200": { "description": "Success", @@ -8588,6 +8687,17 @@ "disabled": { "type": "boolean" }, + "registeredByKey": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Immutable Access Key name that self-registered this agent; null when registered by an Admin." + }, "activeRuns": { "type": "integer", "minimum": 0, @@ -8625,6 +8735,7 @@ "description", "owner", "disabled", + "registeredByKey", "activeRuns", "openRequests", "lastSeenAt", @@ -8663,6 +8774,31 @@ ], "additionalProperties": false }, + "AgentRegister": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "description": { + "type": "string", + "description": "At most 4096 UTF-8 bytes" + }, + "ownerSub": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "description": "Person subject with a signed-in write in this workspace." + } + }, + "required": [ + "name", + "ownerSub" + ], + "additionalProperties": false + }, "AgentPatch": { "type": "object", "properties": { diff --git a/cmd/server/internal/api/routes.go b/cmd/server/internal/api/routes.go index 036de42..f7f42ab 100644 --- a/cmd/server/internal/api/routes.go +++ b/cmd/server/internal/api/routes.go @@ -6,78 +6,80 @@ import ( ) type routeDefinition struct { - pattern string - mutation bool - roles bool - handler endpoint - guide string + pattern string + mutation bool + roles bool + handler endpoint + guide string + unregistered bool // External keys need not resolve to an active agent. } // This is the registration and agent-guide authority. Special binary/public // handlers (Directory avatar and OpenAPI) are mounted separately. func (a *API) routes() []routeDefinition { return []routeDefinition{ - {"GET /me", false, true, a.me, "Confirm your kind, agent handle, owner and scopes."}, - {"GET /workspace", false, false, a.workspaceGet, "Read the agentCompletion policy."}, - {"PATCH /workspace", true, true, a.workspacePatch, ""}, - {"GET /statuses", false, false, a.statusList, "Read workflow status IDs and categories."}, - {"POST /statuses", true, true, a.statusCreate, ""}, - {"PATCH /statuses/{id}", true, true, a.statusPatch, ""}, - {"DELETE /statuses/{id}", true, true, a.statusDelete, ""}, - {"PUT /statuses/order", true, true, a.statusOrder, ""}, - {"GET /labels", false, false, a.labelList, ""}, - {"POST /labels", true, true, a.labelCreate, ""}, - {"PATCH /labels/{id}", true, true, a.labelPatch, ""}, - {"DELETE /labels/{id}", true, true, a.labelDelete, ""}, - {"GET /projects", false, false, a.projectList, ""}, - {"POST /projects", true, false, a.projectCreate, ""}, - {"GET /projects/{id}", false, false, a.projectGet, ""}, - {"PATCH /projects/{id}", true, true, a.projectPatch, ""}, - {"DELETE /projects/{id}", true, true, a.projectDelete, ""}, - {"GET /sprints", false, false, a.sprintList, ""}, - {"POST /sprints", true, false, a.sprintCreate, ""}, - {"GET /sprints/{id}", false, false, a.sprintGet, ""}, - {"PATCH /sprints/{id}", true, false, a.sprintPatch, ""}, - {"POST /sprints/{id}/start", true, false, a.sprintStart, ""}, - {"POST /sprints/{id}/close", true, false, a.sprintClose, ""}, - {"DELETE /sprints/{id}", true, true, a.sprintDelete, ""}, - {"GET /sprints/{id}/burndown", false, false, a.sprintBurndown, ""}, - {"GET /velocity", false, false, a.velocity, ""}, - {"GET /issues", false, false, a.issueList, "Filter issues; list rows include delegator, activeRun and openRequestCount."}, - {"POST /issues", true, false, a.issueCreate, "Create an issue; you are its reporter. You may assign it to yourself."}, - {"GET /issues/{id}", false, false, a.issueGet, "Read current fields, updatedAt and blocking issues before editing."}, - {"PATCH /issues/{id}", true, false, a.issuePatch, "Edit only if assignee or reporter; send expectedUpdatedAt to avoid overwriting changes."}, - {"DELETE /issues/{id}", true, true, a.issueDelete, ""}, - {"GET /issues/{id}/timeline", false, false, a.timeline, "Read comments, activities, runs and requests."}, - {"POST /issues/{id}/comments", true, false, a.commentCreate, "Discuss any issue; @handle mentions a registered agent."}, - {"PATCH /comments/{id}", true, false, a.commentPatch, "Edit your own comment; mentions are reparsed."}, - {"DELETE /comments/{id}", true, true, a.commentDelete, ""}, - {"POST /issues/{id}/attachments", true, false, a.attachmentCreate, "Attach evidence (multipart; excluded from idempotent replay)."}, - {"GET /attachments/{id}", false, false, a.attachmentGet, ""}, - {"DELETE /attachments/{id}", true, true, a.attachmentDelete, ""}, - {"GET /views", false, false, a.viewList, ""}, - {"POST /views", true, true, a.viewCreate, ""}, - {"PATCH /views/{id}", true, true, a.viewPatch, ""}, - {"DELETE /views/{id}", true, true, a.viewDelete, ""}, - {"GET /people", false, false, a.people, "Keys cannot access Directory; returns an empty unavailable result."}, - {"GET /agents", false, false, a.agentList, "Discover agents; includeDisabled=true also returns retired identities."}, - {"POST /agents", true, true, a.agentCreate, ""}, - {"PATCH /agents/{id}", true, true, a.agentPatch, ""}, - {"GET /inbox", false, false, a.inbox, "Requests first, then answers, mentions and actionable assignments."}, - {"POST /inbox/ack", true, false, a.inboxAck, "Acknowledge {answers:[requestId], mentions:[commentId]} after handling them."}, - {"GET /events", false, false, a.events, "Initialize without after (empty items and current next); poll with after=next and limit 1–500."}, - {"POST /issues/{id}/runs", true, false, a.runStart, "Start only on your assigned issue with {session?,note?}; retain the returned run ID."}, - {"GET /issues/{id}/runs", false, false, a.runList, "Inspect newest runs first, including stalled and terminal history."}, - {"GET /runs/{id}", false, false, a.runGet, "Re-read your lease and state before resuming."}, - {"POST /runs/{id}/heartbeat", true, false, a.runHeartbeat, "Send {note?} well before the 10-minute lease expires, including while waiting."}, - {"POST /runs/{id}/finish", true, false, a.runFinish, "Send {outcome:'succeeded'|'failed',summary,links?}; links are HTTPS pr/commit/url entries."}, - {"POST /runs/{id}/cancel", true, false, a.runCancel, "Cancel your own run; any person may cancel it too. Open requests are withdrawn."}, - {"POST /issues/{id}/requests", true, false, a.requestCreate, "Raise {kind:'question'|'approval',title,body?,options?,to?,runId?}; omitted to defaults to delegator/owner, null means any person."}, - {"GET /requests", false, false, a.requestList, "Filter by state, to (subject, me, or none), and issue (ID or identifier)."}, - {"GET /requests/{id}", false, false, a.requestGet, "Read a handoff and its answer."}, - {"POST /requests/{id}/answer", true, true, a.requestAnswer, "Answer a question addressed to you using {option?,body?}; choose one offered option if present."}, - {"POST /requests/{id}/withdraw", true, false, a.requestWithdraw, "Withdraw your open request when it is no longer needed."}, - {"GET /agent-guide", false, false, a.agentGuide, "Read this protocol."}, + {"GET /me", false, true, a.me, "Confirm your kind, agent handle, owner and scopes.", false}, + {"GET /workspace", false, false, a.workspaceGet, "Read the agentCompletion policy.", false}, + {"PATCH /workspace", true, true, a.workspacePatch, "", false}, + {"GET /statuses", false, false, a.statusList, "Read workflow status IDs and categories.", false}, + {"POST /statuses", true, true, a.statusCreate, "", false}, + {"PATCH /statuses/{id}", true, true, a.statusPatch, "", false}, + {"DELETE /statuses/{id}", true, true, a.statusDelete, "", false}, + {"PUT /statuses/order", true, true, a.statusOrder, "", false}, + {"GET /labels", false, false, a.labelList, "", false}, + {"POST /labels", true, true, a.labelCreate, "", false}, + {"PATCH /labels/{id}", true, true, a.labelPatch, "", false}, + {"DELETE /labels/{id}", true, true, a.labelDelete, "", false}, + {"GET /projects", false, false, a.projectList, "", false}, + {"POST /projects", true, false, a.projectCreate, "", false}, + {"GET /projects/{id}", false, false, a.projectGet, "", false}, + {"PATCH /projects/{id}", true, true, a.projectPatch, "", false}, + {"DELETE /projects/{id}", true, true, a.projectDelete, "", false}, + {"GET /sprints", false, false, a.sprintList, "", false}, + {"POST /sprints", true, false, a.sprintCreate, "", false}, + {"GET /sprints/{id}", false, false, a.sprintGet, "", false}, + {"PATCH /sprints/{id}", true, false, a.sprintPatch, "", false}, + {"POST /sprints/{id}/start", true, false, a.sprintStart, "", false}, + {"POST /sprints/{id}/close", true, false, a.sprintClose, "", false}, + {"DELETE /sprints/{id}", true, true, a.sprintDelete, "", false}, + {"GET /sprints/{id}/burndown", false, false, a.sprintBurndown, "", false}, + {"GET /velocity", false, false, a.velocity, "", false}, + {"GET /issues", false, false, a.issueList, "Filter issues; list rows include delegator, activeRun and openRequestCount.", false}, + {"POST /issues", true, false, a.issueCreate, "Create an issue; you are its reporter. You may assign it to yourself.", false}, + {"GET /issues/{id}", false, false, a.issueGet, "Read current fields, updatedAt and blocking issues before editing.", false}, + {"PATCH /issues/{id}", true, false, a.issuePatch, "Edit only if assignee or reporter; send expectedUpdatedAt to avoid overwriting changes.", false}, + {"DELETE /issues/{id}", true, true, a.issueDelete, "", false}, + {"GET /issues/{id}/timeline", false, false, a.timeline, "Read comments, activities, runs and requests.", false}, + {"POST /issues/{id}/comments", true, false, a.commentCreate, "Discuss any issue; @handle mentions a registered agent.", false}, + {"PATCH /comments/{id}", true, false, a.commentPatch, "Edit your own comment; mentions are reparsed.", false}, + {"DELETE /comments/{id}", true, true, a.commentDelete, "", false}, + {"POST /issues/{id}/attachments", true, false, a.attachmentCreate, "Attach evidence (multipart; excluded from idempotent replay).", false}, + {"GET /attachments/{id}", false, false, a.attachmentGet, "", false}, + {"DELETE /attachments/{id}", true, true, a.attachmentDelete, "", false}, + {"GET /views", false, false, a.viewList, "", false}, + {"POST /views", true, true, a.viewCreate, "", false}, + {"PATCH /views/{id}", true, true, a.viewPatch, "", false}, + {"DELETE /views/{id}", true, true, a.viewDelete, "", false}, + {"GET /people", false, false, a.people, "Keys cannot access Directory; returns an empty unavailable result.", false}, + {"GET /agents", false, false, a.agentList, "Discover agents; includeDisabled=true also returns retired identities.", false}, + {"POST /agents", true, true, a.agentCreate, "", false}, + {"POST /agents/register", true, false, a.agentRegister, "Register your own external handle with {name, description?, ownerSub}; 201 when new, 200 when already active.", true}, + {"PATCH /agents/{id}", true, true, a.agentPatch, "", false}, + {"GET /inbox", false, false, a.inbox, "Requests first, then answers, mentions and actionable assignments.", false}, + {"POST /inbox/ack", true, false, a.inboxAck, "Acknowledge {answers:[requestId], mentions:[commentId]} after handling them.", false}, + {"GET /events", false, false, a.events, "Initialize without after (empty items and current next); poll with after=next and limit 1–500.", false}, + {"POST /issues/{id}/runs", true, false, a.runStart, "Start only on your assigned issue with {session?,note?}; retain the returned run ID.", false}, + {"GET /issues/{id}/runs", false, false, a.runList, "Inspect newest runs first, including stalled and terminal history.", false}, + {"GET /runs/{id}", false, false, a.runGet, "Re-read your lease and state before resuming.", false}, + {"POST /runs/{id}/heartbeat", true, false, a.runHeartbeat, "Send {note?} well before the 10-minute lease expires, including while waiting.", false}, + {"POST /runs/{id}/finish", true, false, a.runFinish, "Send {outcome:'succeeded'|'failed',summary,links?}; links are HTTPS pr/commit/url entries.", false}, + {"POST /runs/{id}/cancel", true, false, a.runCancel, "Cancel your own run; any person may cancel it too. Open requests are withdrawn.", false}, + {"POST /issues/{id}/requests", true, false, a.requestCreate, "Raise {kind:'question'|'approval',title,body?,options?,to?,runId?}; omitted to defaults to delegator/owner, null means any person.", false}, + {"GET /requests", false, false, a.requestList, "Filter by state, to (subject, me, or none), and issue (ID or identifier).", false}, + {"GET /requests/{id}", false, false, a.requestGet, "Read a handoff and its answer.", false}, + {"POST /requests/{id}/answer", true, true, a.requestAnswer, "Answer a question addressed to you using {option?,body?}; choose one offered option if present.", false}, + {"POST /requests/{id}/withdraw", true, false, a.requestWithdraw, "Withdraw your open request when it is no longer needed.", false}, + {"GET /agent-guide", false, false, a.agentGuide, "Read this protocol.", true}, } } @@ -89,15 +91,24 @@ func (a *API) agentGuide(_ *request) (any, int, error) { ## Identity -Ask an Admin to register your immutable handle and mint an external-subject -Access Key with that same handle. No Tracker-issued secret is involved. -Exchange the key for a short-lived assertion, never send the raw key here: +Ask an Admin to mint an external-subject Access Key for your immutable handle. +No Tracker-issued secret is involved. Exchange the key for a short-lived +assertion, never send the raw key here: ` + "```sh\napth access-keys create --project --space tracker --external --scope tracker:read --scope tracker:write\nprintf %s \"$KEY\" | apth access-keys exchange --project \n```\n" + ` Send Authorization: Bearer and Content-Type: application/json. GET needs tracker:read; other methods need tracker:write; neither implies the other. Refresh assertions before expiry. Admin operations refuse every key. +Your first call is POST /agents/register with {name, description?, ownerSub}. +The handle comes from your assertion, not the body. The owner must be a person +who has written in this workspace while signed in; use that person's subject. +The owner is claimed, not consented: an Admin may correct it or disable you. +Registration returns 201 when new. It is safe to call on every start: an active +agent receives 200 with its existing record, without applying the body. +Disabled agents cannot register again. GET /agent-guide is available before +registration; all other authenticated routes require an active agent. + ## Inbox and event loop Initialize the event cursor first, then read the inbox. Poll the feed using its @@ -132,12 +143,15 @@ Use a fresh Idempotency-Key (1–128 characters) for every new POST operation; retry an uncertain response with exactly the same path and body and same key. The first response is replayed for 24 hours per actor, across all of its keys. Use a new key for each heartbeat. Multipart attachment uploads are excluded. +POST /agents/register is intrinsically idempotent and ignores Idempotency-Key; +it always checks the current registration and disabled state. For field edits, send expectedUpdatedAt from your latest issue read. 401: exchange again; raw_key_not_accepted means you sent a raw key. -403 insufficient_scope: ask for the missing scope. 403 key_subject: ask the -Admin whether your handle is registered and active. 403 forbidden: do not -retry as another actor; ask the delegator to perform the prohibited action. +403 insufficient_scope: ask for the missing scope. 403 key_subject: register an +unknown handle with POST /agents/register; ask an Admin about a disabled agent. +403 forbidden: do not retry as another actor; ask the delegator to perform the +prohibited action. 409 conflict: re-read the issue/run/request. Stop after lease expiry or reassignment; do not overwrite an updated issue. Resolve open approvals before success. Never reuse an idempotency key for a different operation. diff --git a/cmd/server/internal/domain/agents.go b/cmd/server/internal/domain/agents.go index f18e0da..1fe2a19 100644 --- a/cmd/server/internal/domain/agents.go +++ b/cmd/server/internal/domain/agents.go @@ -30,17 +30,18 @@ type AgentIdentity struct { } type Agent struct { - ID string `json:"id"` - Handle string `json:"handle"` - Name string `json:"name"` - Description string `json:"description"` - Owner Person `json:"owner"` - Disabled bool `json:"disabled"` - ActiveRuns int `json:"activeRuns"` - OpenRequests int `json:"openRequests"` - LastSeenAt *time.Time `json:"lastSeenAt"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` + ID string `json:"id"` + Handle string `json:"handle"` + Name string `json:"name"` + Description string `json:"description"` + Owner Person `json:"owner"` + Disabled bool `json:"disabled"` + RegisteredByKey *string `json:"registeredByKey"` + ActiveRuns int `json:"activeRuns"` + OpenRequests int `json:"openRequests"` + LastSeenAt *time.Time `json:"lastSeenAt"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` } func (a Agent) Person() Person { diff --git a/cmd/server/internal/store/agents.go b/cmd/server/internal/store/agents.go index bbded0c..4d0feec 100644 --- a/cmd/server/internal/store/agents.go +++ b/cmd/server/internal/store/agents.go @@ -14,11 +14,11 @@ import ( const agentColumns = `a.id,a.handle,a.name,a.description,a.owner_sub,a.owner_name,a.disabled,a.created_at,a.updated_at, (SELECT count(*) FROM tracker_run r JOIN tracker_issue i ON i.id=r.issue_id WHERE r.agent_id=a.id AND i.deleted_at IS NULL AND r.state IN ('running','waiting') AND r.lease_expires_at >= $2), (SELECT count(*) FROM tracker_request q JOIN tracker_issue i ON i.id=q.issue_id WHERE i.workspace_id=a.workspace_id AND i.deleted_at IS NULL AND q.from_sub='agent:'||a.id AND q.state='open'), - a.last_seen_at` + a.last_seen_at,a.registered_key` func scanAgent(row scanner) (domain.Agent, error) { var a domain.Agent - err := row.Scan(&a.ID, &a.Handle, &a.Name, &a.Description, &a.Owner.Sub, &a.Owner.Name, &a.Disabled, &a.CreatedAt, &a.UpdatedAt, &a.ActiveRuns, &a.OpenRequests, &a.LastSeenAt) + err := row.Scan(&a.ID, &a.Handle, &a.Name, &a.Description, &a.Owner.Sub, &a.Owner.Name, &a.Disabled, &a.CreatedAt, &a.UpdatedAt, &a.ActiveRuns, &a.OpenRequests, &a.LastSeenAt, &a.RegisteredByKey) return a, err } @@ -27,13 +27,16 @@ func (t *Tx) Agent(id string) (domain.Agent, error) { } func (t *Tx) AgentBySubject(subject string) (domain.Actor, error) { - a, err := scanAgent(t.SQL.QueryRowContext(t.Context, `SELECT `+agentColumns+` FROM tracker_agent a WHERE a.workspace_id=$1 AND a.handle=$3 AND NOT a.disabled`, t.WorkspaceID, t.now(), subject)) + a, err := scanAgent(t.SQL.QueryRowContext(t.Context, `SELECT `+agentColumns+` FROM tracker_agent a WHERE a.workspace_id=$1 AND a.handle=$3`, t.WorkspaceID, t.now(), subject)) if errors.Is(err, sql.ErrNoRows) { - return domain.Actor{}, httpx.Fail(403, "key_subject", "The access key subject is not an active registered agent") + return domain.Actor{}, httpx.Fail(403, "key_subject", "The access key subject is not registered; call POST /api/tracker/v1/agents/register") } if err != nil { return domain.Actor{}, err } + if a.Disabled { + return domain.Actor{}, httpx.Fail(403, "key_subject", "The access key subject is not an active registered agent") + } return domain.Actor{Person: a.Person(), Kind: "agent", AgentID: a.ID, Role: "Viewer", Key: true}, nil } @@ -80,6 +83,55 @@ func (t *Tx) CreateAgent(input AgentCreate, owner domain.Person, actor domain.Ac return t.Agent(id) } +type AgentRegister struct { + Name string `json:"name"` + Description string `json:"description"` + OwnerSub string `json:"ownerSub"` +} + +func (t *Tx) RegisterAgent(input AgentRegister, actor domain.Actor, keyName string) (domain.Agent, bool, error) { + if !actor.Key || actor.Kind != "agent" { + return domain.Agent{}, false, httpx.Forbidden() + } + handle := actor.Sub + if actor.Agent != nil { + handle = actor.Agent.Handle + } + if !agentHandle.MatchString(handle) { + return domain.Agent{}, false, invalid("Invalid agent handle, name or description") + } + existing, err := scanAgent(t.SQL.QueryRowContext(t.Context, `SELECT `+agentColumns+` FROM tracker_agent a WHERE a.workspace_id=$1 AND a.handle=$3`, t.WorkspaceID, t.now(), handle)) + if err == nil { + if existing.Disabled { + return domain.Agent{}, false, httpx.Fail(403, "key_subject", "The access key subject is not an active registered agent") + } + return existing, false, nil + } + if !errors.Is(err, sql.ErrNoRows) { + return domain.Agent{}, false, err + } + if !domain.Text(input.Name, 1, 200) || len(input.Description) > 4096 { + return domain.Agent{}, false, invalid("Invalid agent handle, name or description") + } + if !domain.Text(input.OwnerSub, 1, 4096) || domain.ActorKind(input.OwnerSub) != "person" { + return domain.Agent{}, false, &domain.FieldError{Path: "ownerSub", Message: "Owner must be a person with a signed-in write in this workspace"} + } + name, err := t.KnownName(input.OwnerSub) + if err != nil { + return domain.Agent{}, false, err + } + if name == "" { + return domain.Agent{}, false, &domain.FieldError{Path: "ownerSub", Message: "Owner must be a person with a signed-in write in this workspace"} + } + id := ulid.Make().String() + if err := t.Exec(`INSERT INTO tracker_agent(id,workspace_id,handle,name,description,owner_sub,owner_name,registered_key) VALUES($1,$2,$3,$4,$5,$6,$7,$8)`, + id, t.WorkspaceID, handle, strings.TrimSpace(input.Name), input.Description, input.OwnerSub, name, keyName); err != nil { + return domain.Agent{}, false, err + } + item, err := t.Agent(id) + return item, true, err +} + func (t *Tx) AgentAssignee(sub string) (*domain.Person, error) { a, err := t.Agent(strings.TrimPrefix(sub, "agent:")) if errors.Is(err, sql.ErrNoRows) || (err == nil && a.Disabled) { diff --git a/cmd/server/internal/store/agents_test.go b/cmd/server/internal/store/agents_test.go index ee7229c..706b40e 100644 --- a/cmd/server/internal/store/agents_test.go +++ b/cmd/server/internal/store/agents_test.go @@ -267,3 +267,100 @@ func TestAgentFixtureAndReadFilters(t *testing.T) { return nil })) } + +func TestRegisterAgentOwnershipAndProvenance(t *testing.T) { + db, _ := testutil.Database(t, Open) + require.NoError(t, db.EnsureWorkspace(t.Context(), "registration")) + require.NoError(t, db.EnsureWorkspace(t.Context(), "other")) + person := domain.Actor{Person: domain.Person{Sub: "owner", Name: "Olivia Owner"}, Kind: "person", Role: "Admin"} + external := domain.Actor{Person: domain.Person{Sub: "self-agent", Name: "self-agent"}, Kind: "agent", Key: true} + input := AgentRegister{Name: " Self Agent ", Description: "Self-registered", OwnerSub: person.Sub} + var registered domain.Agent + var resolved domain.Actor + require.NoError(t, db.InWorkspace(t.Context(), "registration", true, func(tx *Tx) error { + _, err := tx.CreateIssue(IssueCreate{Title: "Owner wrote while signed in", Type: "task"}, person.Person, nil) + require.NoError(t, err) + for _, actor := range []domain.Actor{ + person, + {Person: person.Person, Kind: "person", Key: true}, + {Person: external.Person, Kind: "agent"}, + } { + _, created, err := tx.RegisterAgent(input, actor, "ak-registration") + var failure *httpx.Error + require.ErrorAs(t, err, &failure) + require.Equal(t, "forbidden", failure.Code) + require.False(t, created) + } + _, err = tx.CreateAgent(AgentCreate{Handle: "admin-only", Name: "Admin Only"}, person.Person, external) + var failure *httpx.Error + require.ErrorAs(t, err, &failure) + require.Equal(t, "forbidden", failure.Code, "self-registration must not weaken Admin creation") + var created bool + registered, created, err = tx.RegisterAgent(input, external, "ak-registration") + require.NoError(t, err) + require.True(t, created) + require.Equal(t, "self-agent", registered.Handle) + require.Equal(t, "Self Agent", registered.Name) + require.Equal(t, person.Person, registered.Owner) + require.NotNil(t, registered.RegisteredByKey) + require.Equal(t, "ak-registration", *registered.RegisteredByKey) + resolved, err = tx.AgentBySubject(external.Sub) + require.NoError(t, err) + require.Equal(t, registered.ID, resolved.AgentID) + require.Equal(t, "agent:"+registered.ID, resolved.Sub) + adminAgent, err := tx.CreateAgent(AgentCreate{Handle: "admin-agent", Name: "Admin Agent"}, person.Person, person) + require.NoError(t, err) + require.Nil(t, adminAgent.RegisteredByKey) + return nil + })) + // A repeat succeeds even in a read-only transaction: the body is not applied. + require.NoError(t, db.InWorkspace(t.Context(), "registration", false, func(tx *Tx) error { + for _, actor := range []domain.Actor{external, resolved} { + existing, created, err := tx.RegisterAgent(AgentRegister{OwnerSub: "agent:ignored"}, actor, "ak-other") + require.NoError(t, err) + require.False(t, created) + require.Equal(t, registered, existing) + } + return nil + })) + require.NoError(t, db.InWorkspace(t.Context(), "other", true, func(tx *Tx) error { + _, created, err := tx.RegisterAgent(input, external, "ak-other") + var field *domain.FieldError + require.ErrorAs(t, err, &field) + require.Equal(t, "ownerSub", field.Path, "another workspace's signed-in write cannot qualify the owner") + require.False(t, created) + list, err := tx.Agents(true) + require.NoError(t, err) + require.Empty(t, list) + return nil + })) + require.NoError(t, db.InWorkspace(t.Context(), "registration", true, func(tx *Tx) error { + name := "Admin renamed" + description := "Admin edited" + owner := domain.Person{Sub: "corrected-owner", Name: "Corrected Owner"} + disabled := true + patched, err := tx.PatchAgent(registered.ID, AgentPatch{Name: &name, Description: &description, Disabled: &disabled}, &owner, person) + require.NoError(t, err) + require.Equal(t, registered.RegisteredByKey, patched.RegisteredByKey) + for _, actor := range []domain.Actor{external, resolved} { + _, created, err := tx.RegisterAgent(input, actor, "ak-other") + var failure *httpx.Error + require.ErrorAs(t, err, &failure) + require.Equal(t, "key_subject", failure.Code) + require.Equal(t, 403, failure.Status) + require.False(t, created) + } + stored, err := tx.Agent(registered.ID) + require.NoError(t, err) + require.Equal(t, patched, stored) + _, err = tx.AgentBySubject("self-agent") + require.ErrorContains(t, err, "The access key subject is not an active registered agent") + _, err = tx.AgentBySubject("unknown-agent") + var failure *httpx.Error + require.ErrorAs(t, err, &failure) + require.Equal(t, "key_subject", failure.Code) + require.Equal(t, 403, failure.Status) + require.ErrorContains(t, err, "POST /api/tracker/v1/agents/register") + return nil + })) +} diff --git a/cmd/server/internal/store/migrations/014_agent_self_registration.sql b/cmd/server/internal/store/migrations/014_agent_self_registration.sql new file mode 100644 index 0000000..5b5dbdb --- /dev/null +++ b/cmd/server/internal/store/migrations/014_agent_self_registration.sql @@ -0,0 +1,2 @@ +-- Access Key name that self-registered the agent; NULL = registered by an Admin. +ALTER TABLE tracker_agent ADD COLUMN registered_key text CHECK (char_length(registered_key) BETWEEN 1 AND 253); diff --git a/cmd/server/internal/store/projects_test.go b/cmd/server/internal/store/projects_test.go index 23d3d0b..0f4907a 100644 --- a/cmd/server/internal/store/projects_test.go +++ b/cmd/server/internal/store/projects_test.go @@ -250,7 +250,7 @@ func TestProjectsMigrationFromV010(t *testing.T) { } var versions int require.NoError(t, tx.SQL.QueryRowContext(t.Context(), `SELECT count(*) FROM tracker_schema_migrations`).Scan(&versions)) - require.Equal(t, 13, versions) + require.Equal(t, 14, versions) var reporterIndex string require.NoError(t, tx.SQL.QueryRowContext(t.Context(), `SELECT indexdef FROM pg_indexes WHERE schemaname=current_schema() AND indexname='tracker_issue_reporter'`).Scan(&reporterIndex)) require.Contains(t, reporterIndex, "USING btree (workspace_id, reporter_sub) WHERE (deleted_at IS NULL)") diff --git a/design/API.md b/design/API.md index 896635e..92dcc33 100644 --- a/design/API.md +++ b/design/API.md @@ -485,7 +485,7 @@ An **Actor** is a person or an agent. Everything a person can be on an issue | Entity | Owner (sole writer) | Lifecycle | Invariants | | --- | --- | --- | --- | -| **Agent** | Admin | `active ⇄ disabled`; never deleted (history refers to it) | has an immutable `id` and an immutable, unique `handle` (see "Identifiers"); `name` and `description` are editable; exactly one `owner` Person, who is accountable for what it does; an Assertion whose `external` subject equals no active agent's handle is refused (403 `key_subject`). | +| **Agent** | Admin; the agent itself, once, to come into existence ("Self-registration") | `active ⇄ disabled`; never deleted (history refers to it) | has an immutable `id` and an immutable, unique `handle` (see "Identifiers"); `name` and `description` are editable; exactly one `owner` Person, who is accountable for what it does; an Assertion whose `external` subject equals no active agent's handle is refused (403 `key_subject`) on every route except self-registration and `GET /agent-guide`. | | **Delegation** (fields on Issue) | whoever assigns | set when the assignee becomes an agent, cleared when it becomes a person or nobody | `delegator` is a Person: the person who assigned, or the agent's owner when an agent assigned (itself or another agent). The delegator is who the agent answers to on this issue. | | **Run** | the agent that started it; a person may cancel | `running ⇄ waiting → succeeded \| failed \| canceled` | only the issue's assignee starts a run; at most one non-terminal run per issue; holds a lease (`leaseExpiresAt`, 10 minutes, renewed by heartbeat, compared at microsecond precision); a run whose lease has passed is `stalled` (derived at read time). A stalled run blocks nothing and is never revived: heartbeat and finish are refused, and the next start on the issue closes it as `failed/lease_expired`. Changing the assignee away from the agent cancels its non-terminal run (`reassigned`) in the same transaction. Whatever ends a run without success (cancel, reassignment, expiry closure) withdraws its open requests. | | **Request** | requester creates and withdraws; addressee answers | `open → answered \| withdrawn` | `kind ∈ {question, approval, review}`; directed from one actor to one actor, or to "any person"; `approval` and `review` are answered only by people; a `review` exists only as the result of a finished run; only a run's own agent attaches a request to that run, and the run must belong to the same issue (otherwise anyone could force a run into `waiting`). | @@ -521,6 +521,7 @@ identifier of its own: it is the free-text `session` of a Run. | Answer `approval` / `review` | addressee, or any person when unaddressed; Admin | never | | Cancel a run | any | its own | | Assign to an agent | any | itself, on issues it reported | +| Register itself | n/a | `tracker:write`, with an external key whose handle is not registered | | Delete, settings, statuses, labels, shared views, sprint start/close/delete, manage agents | as today | never | | `GET /people` (Directory) | any | empty, `source: unavailable` (Directory accepts only user bearers) | @@ -538,6 +539,7 @@ type Actor = Person & { kind: ActorKind; agent?: { id: string; handle: string; o type Agent = { id: string; handle: string /* immutable; also the external subject of its Access Keys */ name: string; description: string /* ≤ 4096 bytes: what to delegate to it */ owner: Person; disabled: boolean + registeredByKey: string | null /* Access Key name that self-registered it; null = registered by an Admin */ activeRuns: number; openRequests: number; lastSeenAt: string | null; createdAt: string; updatedAt: string } type RunState = 'running' | 'waiting' | 'stalled' | 'succeeded' | 'failed' | 'canceled' @@ -578,7 +580,8 @@ Changes to existing shapes: - `POST`/`PATCH /issues`: `assigneeSub` accepts `agent:`; a disabled agent → 400 (path `assigneeSub`). `PATCH` accepts `expectedUpdatedAt?`; a mismatch → 409 `conflict`. An agent setting a `completed` status under `review` → 403. -- All `POST` routes except the multipart attachment upload honour +- All `POST` routes except the multipart attachment upload and + `POST /agents/register` honour `Idempotency-Key` (≤ 128 chars): the first handler status and body are kept 24 h per (actor, key) and replayed for the identical request (method, URI, content type, body bytes); a different request under the same key → 409. @@ -598,6 +601,7 @@ Changes to existing shapes: | `GET /agents?includeDisabled=` | → `{ items: Agent[] }` | any | | `POST /agents` | `{ handle, name, description?, ownerSub }` → `Agent` 201; duplicate handle → 409 | Admin | | `PATCH /agents/{id}` | `{ name?, description?, ownerSub?, disabled? }` → `Agent`; disabling cancels its non-terminal runs | Admin | +| `POST /agents/register` | `{ name, description?, ownerSub }` → `Agent` 201; already registered and active → that `Agent` 200, body not applied; see "Self-registration" | external key | | `GET /inbox` | → `{ items: InboxItem[] }` for the caller, requests first | any | | `POST /inbox/ack` | `{ answers?: string[] /* request ids */; mentions?: string[] /* comment ids */ }` → 204 | any | | `GET /events?after=&limit=` | → `{ items: Event[]; next: number }`, ascending, limit default 100 max 500; `after` omitted = from now | any | @@ -624,6 +628,43 @@ Agent actors are stored in the existing `*_sub` columns as `agent:`, so no existing column changes type. Expired idempotency rows are deleted opportunistically by the write that inserts a new one. + +### Self-registration (v0.1.14) + +An agent brings itself into existence: the first call of a new external key +is `POST /agents/register`. No Admin registers the handle beforehand. + +Why this is safe to allow: only a Project admin can mint an external-subject +key (`apth access-keys create --external `). Holding such a key for +this Project and the `tracker` audience is therefore the admission decision; +requiring a Tracker Admin to type the same handle again added a second +approval by the same class of person and nothing else. + +| Rule | Result when violated | +| --- | --- | +| The caller is an external-subject key with `tracker:write`. People (signed-in or user key) register agents with `POST /agents` | 403 `forbidden` | +| The handle is the assertion's external subject, never a body field: an agent registers only itself. It must match the handle pattern | 400 `invalid` | +| `ownerSub` is a person with a signed-in write in this workspace (`store.KnownName` is non-empty); the stored `owner.name` is that name. A key cannot ask Directory, so this is the only source of a real name, and it keeps the owner someone who uses this workspace | 400 `invalid`, path `ownerSub` | +| `name` 1–200 chars, `description` ≤ 4096 bytes, as for `POST /agents` | 400 `invalid` | +| The handle belongs to a disabled agent: an Admin's decision is not undone by the agent | 403 `key_subject` | +| The handle is already registered and active | 200 with the existing `Agent`; the body is not applied and the agent is not changed (the call still counts as the agent being seen), so an agent may call this on every start | + +The owner is **claimed, not verified**: the agent names its owner and the +owner did not consent in Tracker. `registeredByKey` records the Access Key name +from the assertion, the Agents page marks such agents, and an Admin corrects +the owner or disables the agent with `PATCH /agents/{id}`. `registeredByKey` +never changes afterwards, including when an Admin edits the agent. + +An unregistered external key is refused everywhere else with 403 +`key_subject`, whose message names `POST /agents/register`. `GET /agent-guide` +is the one read it may make, because the guide is where an agent learns to +register. Registration is not an Event (the feed describes issues). The route +is idempotent by its own rule and ignores `Idempotency-Key`: a stored 201 +replayed after an Admin disabled the agent would contradict the row above. + +Storage (migration `014_agent_self_registration.sql`): +`tracker_agent.registered_key`, null for Admin-registered agents. + ### UI - **Actor rendering**: an agent shows its own glyph and a tooltip "owned by @@ -646,5 +687,10 @@ opportunistically by the write that inserts a new one. last seen, active runs, open requests and the median time a request waited for a person. (Runs by outcome needs a cross-issue run listing and a Dashboard link needs the Dashboard URL; neither exists, so neither is shown.) + Self-registered agents carry a mark naming the key that registered them, so + an Admin can check the claimed owner. "Let an agent register itself" shows + the key command and the `POST /agents/register` body with the viewer's own + subject as `ownerSub`, because a person has no other place to read their + subject. - **Settings**: completion policy. - Copy in Japanese and English (`web/src/copy/agents.ts`). diff --git a/web/package.json b/web/package.json index d455053..85227bb 100644 --- a/web/package.json +++ b/web/package.json @@ -1,6 +1,6 @@ { "name": "@appthrust/tracker", - "version": "0.1.13", + "version": "0.1.14", "private": true, "type": "module", "scripts": { diff --git a/web/src/api/tracker.ts b/web/src/api/tracker.ts index d45d720..a20cd79 100644 --- a/web/src/api/tracker.ts +++ b/web/src/api/tracker.ts @@ -29,6 +29,8 @@ export type Agent = { description: string owner: Person disabled: boolean + /** The Access Key name (`ak-…`) the agent registered itself with; null when an Admin registered it. Never changes. */ + registeredByKey: string | null /** Live (running or waiting, not stalled) runs. */ activeRuns: number /** Open requests the agent raised. */ diff --git a/web/src/copy/agents.ts b/web/src/copy/agents.ts index 475955e..21ac00e 100644 --- a/web/src/copy/agents.ts +++ b/web/src/copy/agents.ts @@ -190,6 +190,37 @@ export const agentMessages = defineDashboardMessages({ 'tracker.agents.copy': { defaultMessage: 'Copy command', translations: { ja: 'コマンドをコピー' } }, 'tracker.agents.copied': { defaultMessage: 'Command copied', translations: { ja: 'コマンドをコピーしました' } }, 'tracker.agents.showKey': { defaultMessage: 'Key command for {name}', translations: { ja: '{name} のキー発行コマンド' } }, + 'tracker.agents.selfRegistered': { defaultMessage: 'Self-registered · {key}', translations: { ja: '自己登録 · {key}' } }, + 'tracker.agents.selfRegisteredHint': { + defaultMessage: 'This agent registered itself with the Access Key {key} and named its responsible person, who has not confirmed it. Check the owner, and edit or disable the agent if it is wrong.', + translations: { ja: 'アクセスキー {key} で自分で登録したエージェントです。責任者はエージェントが名乗ったもので、本人は確認していません。違っていれば編集するか無効にしてください。' }, + }, + 'tracker.agents.ownerClaimed': { defaultMessage: 'Owned by {name} (claimed by the agent, not confirmed)', translations: { ja: '責任者: {name}(エージェントの申告・未確認)' } }, + 'tracker.agents.selfRegister.toggle': { defaultMessage: 'Let an agent register itself', translations: { ja: 'エージェントに自分で登録させる' } }, + 'tracker.agents.selfRegister.lead': { + defaultMessage: 'Give an agent a key and it registers itself; no one registers it here first. You become its responsible person, and admins see that it registered itself.', + translations: { ja: 'キーを渡せば、エージェントが自分で登録します。ここで先に登録する必要はありません。責任者はあなたになり、管理者には自己登録と表示されます。' }, + }, + 'tracker.agents.selfRegister.handle': { defaultMessage: 'Agent handle', translations: { ja: 'エージェントのハンドル' } }, + 'tracker.agents.selfRegister.handleHint': { + defaultMessage: 'Lowercase letters, digits and hyphens, starting with a letter. It becomes the agent’s @handle and cannot be changed later.', + translations: { ja: '英小文字・数字・ハイフン(先頭は英字)。エージェントの @ハンドル になり、あとから変更できません。' }, + }, + 'tracker.agents.selfRegister.keyStep': { defaultMessage: 'A Project admin issues the key', translations: { ja: 'プロジェクト管理者がキーを発行する' } }, + 'tracker.agents.selfRegister.keyStepBody': { defaultMessage: 'Run this with the apth CLI and hand the key it shows to the agent.', translations: { ja: 'apth CLI で実行し、表示されたキーをエージェントに渡します。' } }, + 'tracker.agents.selfRegister.keyStepEmpty': { defaultMessage: 'Enter a handle to see the command.', translations: { ja: 'ハンドルを入力するとコマンドが表示されます。' } }, + 'tracker.agents.selfRegister.registerStep': { defaultMessage: 'The agent registers itself', translations: { ja: 'エージェントが自分で登録する' } }, + 'tracker.agents.selfRegister.registerStepBody': { + defaultMessage: 'With that key, the agent sends this as its first call. It may change the name.', + translations: { ja: 'エージェントはそのキーで、最初にこのリクエストを送ります。name は変えてかまいません。' }, + }, + 'tracker.agents.selfRegister.ownerNote': { + defaultMessage: 'ownerSub is your own ID ({sub}). It is accepted only if you have already written in this workspace while signed in, such as an issue or a comment.', + translations: { ja: 'ownerSub はあなた自身の ID({sub})です。サインインしてこのワークスペースで課題やコメントを書いたことがないと受け付けられません。' }, + }, + 'tracker.agents.selfRegister.nameExample': { defaultMessage: 'Agent name', translations: { ja: 'エージェント名' } }, + 'tracker.agents.selfRegister.copy': { defaultMessage: 'Copy request', translations: { ja: 'リクエストをコピー' } }, + 'tracker.agents.selfRegister.copied': { defaultMessage: 'Request copied', translations: { ja: 'リクエストをコピーしました' } }, // Settings: completion policy 'tracker.completion.title': { defaultMessage: 'Finishing agent work', translations: { ja: 'エージェントの作業の完了' } }, diff --git a/web/src/dev/mock-tracker.test.ts b/web/src/dev/mock-tracker.test.ts index f39f811..df01af8 100644 --- a/web/src/dev/mock-tracker.test.ts +++ b/web/src/dev/mock-tracker.test.ts @@ -878,11 +878,11 @@ describe('tracker mock: agents fixture', () => { const active = (await call('GET', '/agents')).body.items as Agent[] expect(active.map((agent) => agent.handle)).toEqual(['astra', 'claude', 'opus-ui']) const all = await agentsByHandle() - expect([...all.values()].map((agent) => [agent.handle, agent.name, agent.owner.sub, agent.disabled, agent.activeRuns, agent.openRequests])).toEqual([ - ['astra', 'Astra', 'dev-sam', false, 1, 1], - ['claude', 'Claude', 'dev-jordan', false, 0, 1], - ['legacy-bot', 'Legacy bot', 'dev-alex', true, 0, 0], - ['opus-ui', 'Opus UI', 'dev-alex', false, 1, 1], + expect([...all.values()].map((agent) => [agent.handle, agent.name, agent.owner.sub, agent.disabled, agent.registeredByKey, agent.activeRuns, agent.openRequests])).toEqual([ + ['astra', 'Astra', 'dev-sam', false, null, 1, 1], + ['claude', 'Claude', 'dev-jordan', false, null, 0, 1], + ['legacy-bot', 'Legacy bot', 'dev-alex', true, null, 0, 0], + ['opus-ui', 'Opus UI', 'dev-alex', false, 'ak-md8mw', 1, 1], ]) expect(all.get('astra')!.lastSeenAt).toEqual(expect.any(String)) }) @@ -1147,7 +1147,7 @@ describe('tracker mock: delegation, runs and requests', () => { expect((await call('POST', '/agents', { handle: 'astra', name: 'X', ownerSub: 'dev-alex' })).status).toBe(409) expect((await call('POST', '/agents', { handle: 'scout', name: 'Scout', ownerSub: 'agent:x' })).body.issues[0].path).toBe('ownerSub') const created = await call('POST', '/agents', { handle: 'scout', name: 'Scout', description: 'Finds flaky tests.', ownerSub: 'dev-jordan' }) - expect(created).toMatchObject({ status: 201, body: { handle: 'scout', owner: { sub: 'dev-jordan', name: 'Jordan Lee' }, activeRuns: 0, openRequests: 0, lastSeenAt: null } }) + expect(created).toMatchObject({ status: 201, body: { handle: 'scout', owner: { sub: 'dev-jordan', name: 'Jordan Lee' }, registeredByKey: null, activeRuns: 0, openRequests: 0, lastSeenAt: null } }) expect((await call('PATCH', `/agents/${created.body.id}`, { name: 'Scout 2', ownerSub: 'dev-sam' })).body).toMatchObject({ name: 'Scout 2', owner: { sub: 'dev-sam' } }) const guide = await call('GET', '/agent-guide') expect(guide.headers.get('Content-Type')).toContain('text/markdown') diff --git a/web/src/dev/mock-tracker.ts b/web/src/dev/mock-tracker.ts index 4ceaf17..18ba0c6 100644 --- a/web/src/dev/mock-tracker.ts +++ b/web/src/dev/mock-tracker.ts @@ -14,7 +14,8 @@ // one; 17 work items carry a size. The exact fixture (shared authority with // the server seed) is `SPRINT_FIXTURE` below. // Agents (API.md "Agents"): four registered agents (astra, opus-ui, claude, -// legacy-bot disabled), delegations, runs (running, waiting, stalled, +// legacy-bot disabled; opus-ui registered itself with the key `ak-md8mw`, +// the others were registered by an Admin), delegations, runs (running, waiting, stalled, // succeeded), requests, a mention and two agent-reported issues (APT-41/42), // all relative to the moment of seeding — the shared fixture is // `.tmp/agents-ui/fixture.md`, mirrored by `seedAgents` below. Leases are @@ -253,7 +254,7 @@ type StoredIssue = { sprintId: string | null } type StoredComment = Omit & { deleted: boolean } -type StoredAgent = { id: string; handle: string; name: string; description: string; owner: Person; disabled: boolean; createdAt: string; updatedAt: string; lastSeenAt: string | null } +type StoredAgent = { id: string; handle: string; name: string; description: string; owner: Person; disabled: boolean; registeredByKey: string | null; createdAt: string; updatedAt: string; lastSeenAt: string | null } /** `state` never holds `stalled`: it is derived from `leaseExpiresAt` on read, as on the server. */ type StoredRun = Omit & { issueId: string; agentId: string; state: StoredRunState } type StoredRequest = { @@ -572,14 +573,14 @@ function seedTracker({ withProjects = process.env.MOCK_PROJECTS !== 'none' }: { type MockState = ReturnType -/** One agent of the fixture (`.tmp/agents-ui/fixture.md`, "Agents"); times are offsets from the moment of seeding. */ -type AgentFixture = { handle: string; name: string; owner: Person; disabled: boolean; description: string; created: number; updated: number; seen: number } +/** One agent of the fixture (`.tmp/agents-ui/fixture.md`, "Agents"); times are offsets from the moment of seeding. `registeredByKey`: the key it registered itself with (absent: an Admin registered it). */ +type AgentFixture = { handle: string; name: string; owner: Person; disabled: boolean; description: string; created: number; updated: number; seen: number; registeredByKey?: string } const MINUTE = 60_000 const DAY = 24 * HOUR export const AGENT_FIXTURE = { agents: [ { handle: 'astra', name: 'Astra', owner: MOCK_PEOPLE.sam, disabled: false, description: 'Backend implementer. Go handlers, store queries, migrations and their tests. Delegate issues with a clear acceptance check.', created: -14 * DAY, updated: -14 * DAY, seen: -2 * MINUTE }, - { handle: 'opus-ui', name: 'Opus UI', owner: MOCK_PEOPLE.alex, disabled: false, description: 'UI implementer. React screens, copy and accessibility in the SPA. Delegate issues that include the expected screen or a screenshot.', created: -7 * DAY, updated: -7 * DAY, seen: -1 * MINUTE }, + { handle: 'opus-ui', name: 'Opus UI', owner: MOCK_PEOPLE.alex, disabled: false, description: 'UI implementer. React screens, copy and accessibility in the SPA. Delegate issues that include the expected screen or a screenshot.', created: -7 * DAY, updated: -7 * DAY, seen: -1 * MINUTE, registeredByKey: 'ak-md8mw' }, { handle: 'claude', name: 'Claude', owner: MOCK_PEOPLE.jordan, disabled: false, description: 'Planner and triage. Reads new reports, finds duplicates, proposes priority and sprint. Does not change code.', created: -14 * DAY, updated: -14 * DAY, seen: -2 * HOUR }, { handle: 'legacy-bot', name: 'Legacy bot', owner: MOCK_PEOPLE.alex, disabled: true, description: 'Old nightly triage script. Replaced by claude.', created: -60 * DAY, updated: -30 * DAY, seen: -32 * DAY }, ] as AgentFixture[], @@ -622,6 +623,7 @@ function seedAgents(seeded: MockState) { description: fixture.description, owner: fixture.owner, disabled: fixture.disabled, + registeredByKey: fixture.registeredByKey ?? null, createdAt: at(fixture.created), updatedAt: at(fixture.updated), lastSeenAt: at(fixture.seen), @@ -1896,7 +1898,7 @@ async function agentRoutes(request: Request, url: URL, route: string): Promise agent.handle === input.handle)) return conflict('an agent with this handle exists') const time = now() - const agent: StoredAgent = { id: nextId(), handle: input.handle as string, name: (input.name as string).trim(), description: (input.description as string | undefined) ?? '', owner: personFor(input.ownerSub as string), disabled: false, createdAt: time, updatedAt: time, lastSeenAt: null } + const agent: StoredAgent = { id: nextId(), handle: input.handle as string, name: (input.name as string).trim(), description: (input.description as string | undefined) ?? '', owner: personFor(input.ownerSub as string), disabled: false, registeredByKey: null, createdAt: time, updatedAt: time, lastSeenAt: null } state.agents.push(agent) return json(agentView(agent), 201) } diff --git a/web/src/features/agents/agents-settings.tsx b/web/src/features/agents/agents-settings.tsx index a72fd2f..94f4971 100644 --- a/web/src/features/agents/agents-settings.tsx +++ b/web/src/features/agents/agents-settings.tsx @@ -6,14 +6,19 @@ // says the agent's work in progress is stopped — and copy the exact `apth` // command that mints a key. The key is shown once by the platform, never by // Tracker. Runs by outcome are not shown: no route lists runs across issues. +// An agent that registered itself (API.md "Self-registration") carries a mark +// naming its key and says its owner is claimed, not confirmed, so an Admin +// checks it. "Let an agent register itself", open to everyone, shows the key +// command for a typed handle and the request the agent sends with the +// viewer's own subject as `ownerSub`: a person has no other place to read it. import { useQuery } from '@tanstack/react-query' -import { Bot, Check, Copy, KeyRound, Pencil, Plus, Power, PowerOff } from 'lucide-react' +import { Bot, Check, CircleHelp, Copy, KeyRound, Pencil, Plus, Power, PowerOff } from 'lucide-react' import { useId, useMemo, useState, type FormEvent } from 'react' import { peopleQuery, requestsQuery, useAgentMutations, useUpdateWorkspace } from '../../api/queries' import { isTrackerError, type Agent, type AgentCompletion, type Person } from '../../api/tracker' import { useText } from '../../i18n' -import { accessKeyCommand, AGENT_COMPLETIONS, AGENT_DESCRIPTION_MAX_BYTES, AGENT_HANDLE_PATTERN, AGENT_NAME_MAX, medianWaitMs } from '../../model/agents' -import { ActionError, Avatar, Button, cn, ConfirmDialog, Dialog, Field, formatDateTime, formatDuration, formatRelative, Notice, Section, SelectInput, showToast, TextArea, TextInput } from '../../ui' +import { accessKeyCommand, accessKeyCommandFor, AGENT_COMPLETIONS, AGENT_DESCRIPTION_MAX_BYTES, AGENT_HANDLE_PATTERN, AGENT_NAME_MAX, medianWaitMs, selfRegisterRequest } from '../../model/agents' +import { ActionError, Avatar, Badge, Button, cn, ConfirmDialog, Dialog, Field, formatDateTime, formatDuration, formatRelative, Notice, Section, SelectInput, showToast, TextArea, TextInput } from '../../ui' import { useReference } from '../issues/use-reference' import { AgentTag } from './actor' @@ -25,6 +30,8 @@ export function AgentSettings() { const [editing, setEditing] = useState(null) const [disabling, setDisabling] = useState(null) const [keyFor, setKeyFor] = useState(null) + const [helpOpen, setHelpOpen] = useState(false) + const helpId = useId() const waits = useMemo(() => { const byAgent = new Map() for (const agent of agents) byAgent.set(agent.id, medianWaitMs((answered.data ?? []).filter((request) => request.from.sub === `agent:${agent.id}`))) @@ -53,13 +60,19 @@ export function AgentSettings() { title={t('tracker.settings.agents')} className="mt-6" actions={ - me.isAdmin ? ( - - ) : undefined + {me.isAdmin ? ( + + ) : null} + } > + {helpOpen ? : null} {active.length === 0 ? (

{t('tracker.agents.empty')}

) : ( @@ -100,8 +113,13 @@ function AgentRow({ agent, wait, showKey, onToggleKey, onEdit, onDisable, onEnab {agent.name} @{agent.handle} + {agent.registeredByKey !== null ? ( + + {t('tracker.agents.selfRegistered', { key: agent.registeredByKey })} + + ) : null}

-

{t('tracker.agent.ownedBy', { name: agent.owner.name })}

+

{agent.registeredByKey !== null ? t('tracker.agents.ownerClaimed', { name: agent.owner.name }) : t('tracker.agent.ownedBy', { name: agent.owner.name })}

{agent.description ?

{agent.description}

: null}

{agent.lastSeenAt ? ( @@ -146,29 +164,76 @@ function AgentRow({ agent, wait, showKey, onToggleKey, onEdit, onDisable, onEnab /** The exact `apth` command and a copy button; the key itself never passes through Tracker. */ function KeyCommand({ id, agent }: { id: string; agent: Agent }) { const { t } = useText() - const [copied, setCopied] = useState(false) - const command = accessKeyCommand(agent.handle) return (

{t('tracker.agents.keyBody')}

-
- {command} - -
+ +
+ ) +} + +/** + * "Let an agent register itself": step 1 is the key command for the handle the + * viewer types (a Project admin runs it), step 2 the request the agent sends + * first, with the viewer's own subject as `ownerSub`. Tracker never sends it. + */ +function SelfRegisterHelp({ id }: { id: string }) { + const { t } = useText() + const { me } = useReference() + const [handle, setHandle] = useState('') + const command = accessKeyCommandFor(handle) + const request = selfRegisterRequest(command ? handle : t('tracker.agents.selfRegister.nameExample'), me.sub) + const handleId = `${id}-handle` + return ( +
+

{t('tracker.agents.selfRegister.lead')}

+ +
+ + @ + + setHandle(event.target.value.toLowerCase())} maxLength={31} autoComplete="off" spellCheck={false} className="pl-7 font-mono" /> +
+
+
    +
  1. +

    {t('tracker.agents.selfRegister.keyStep')}

    +

    {command ? t('tracker.agents.selfRegister.keyStepBody') : t('tracker.agents.selfRegister.keyStepEmpty')}

    + {command ? : null} +
  2. +
  3. +

    {t('tracker.agents.selfRegister.registerStep')}

    +

    {t('tracker.agents.selfRegister.registerStepBody')}

    + +

    {t('tracker.agents.selfRegister.ownerNote', { sub: me.sub })}

    +
  4. +
+
+ ) +} + +/** Text to paste as is (a command, a request) beside its copy button; the check shows until the text changes. */ +function CopySnippet({ text, copyLabel, copiedLabel }: { text: string; copyLabel: string; copiedLabel: string }) { + const { t } = useText() + const [copied, setCopied] = useState(null) + return ( +
+ {text} +
) } diff --git a/web/src/model/agents.test.ts b/web/src/model/agents.test.ts index 0b89792..48f25fe 100644 --- a/web/src/model/agents.test.ts +++ b/web/src/model/agents.test.ts @@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test' import type { Actor, IssueSummary, Run, Status, TrackerRequest } from '../api/tracker' import { accessKeyCommand, + accessKeyCommandFor, agentIdOf, canAnswer, canCancelRun, @@ -15,6 +16,9 @@ import { medianWaitMs, mentionAt, parseMentions, + selfRegisterBody, + selfRegisterRequest, + SELF_REGISTER_PATH, type ActionableStanding, } from './agents' import { matchesFilter } from './issues' @@ -65,6 +69,18 @@ describe('agent rules', () => { expect(accessKeyCommand('astra')).toBe('apth access-keys create --space tracker --external astra --scope tracker:read --scope tracker:write') }) + test('self-registration help: a key command only for a valid handle; a JSON body with exactly the given name and subject', () => { + expect(accessKeyCommandFor('astra')).toBe(accessKeyCommand('astra')) + for (const handle of ['', 'a', 'Astra', '9lives', 'astra bot', 'a'.repeat(32)]) expect(accessKeyCommandFor(handle), handle).toBeNull() + const sub = 'auth0|"quoted"\\sub' + expect(JSON.parse(selfRegisterBody('Astra “β”', sub))).toEqual({ name: 'Astra “β”', ownerSub: sub }) + const request = selfRegisterRequest('Astra', 'dev-alex') + const [head, body] = request.split('\n\n') + expect(head!.split('\n')[0]).toBe(`POST ${SELF_REGISTER_PATH}`) + expect(SELF_REGISTER_PATH).toBe('/api/tracker/v1/agents/register') + expect(JSON.parse(body!)).toEqual({ name: 'Astra', ownerSub: 'dev-alex' }) + }) + test('a non-terminal run whose lease has passed reads as stalled; terminal runs never do', () => { const lease = '2026-11-11T00:10:00.000Z' expect(deriveRunState('running', lease, Date.parse(lease) - 1)).toBe('running') diff --git a/web/src/model/agents.ts b/web/src/model/agents.ts index 97a1b70..08f0df1 100644 --- a/web/src/model/agents.ts +++ b/web/src/model/agents.ts @@ -2,8 +2,8 @@ // and AI agents on the same board"): actor kinds and agent subjects, the run // lease (`stalled` is derived from `leaseExpiresAt`), who may answer, // withdraw or cancel, the completion policy, "Actionable" and its order, -// `@handle` mentions, and the request wait statistics the agents settings -// page shows. +// `@handle` mentions, the request wait statistics the agents settings page +// shows, and the snippets of its "Let an agent register itself" help. import type { Actor, AgentCompletion, AgentInfo, Priority, RequestKind, Run, RunState, StatusCategory, TrackerRequest } from '../api/tracker' /** `^[a-z][a-z0-9-]{1,30}$`: what people type (`@astra`) and the `external` subject of the agent's Access Keys. */ @@ -44,6 +44,24 @@ export function accessKeyCommand(handle: string): string { return `apth access-keys create --space tracker --external ${handle} ${ACCESS_KEY_SCOPES.map((scope) => `--scope ${scope}`).join(' ')}` } +/** The key command for a handle someone is typing; null until it is a valid handle. */ +export function accessKeyCommandFor(handle: string): string | null { + return AGENT_HANDLE_PATTERN.test(handle) ? accessKeyCommand(handle) : null +} + +/** Where an agent registers itself (API.md "Self-registration"): its first call with a new key. */ +export const SELF_REGISTER_PATH = '/api/tracker/v1/agents/register' + +/** The JSON body of `POST /agents/register`: the agent's name and the owner it claims. The handle is never in it; the key carries it. */ +export function selfRegisterBody(name: string, ownerSub: string): string { + return JSON.stringify({ name, ownerSub }, null, 2) +} + +/** The request an agent sends to register itself, as shown for copying: request line, content type, body. */ +export function selfRegisterRequest(name: string, ownerSub: string): string { + return `POST ${SELF_REGISTER_PATH}\nContent-Type: application/json\n\n${selfRegisterBody(name, ownerSub)}` +} + // --- runs ------------------------------------------------------------------------ export type StoredRunState = Exclude