From a65b4e718e51ee5a71c57768d4cb664d634ceb77 Mon Sep 17 00:00:00 2001 From: Mukesh Kumar Chaudhary Date: Mon, 16 Nov 2026 10:10:51 +0545 Subject: [PATCH 1/7] feat: add typed capability sources with validation, approval and typed answers Capabilities now come from any source that produces a codemode.Source: typed Go functions (capability/gosource), protobuf (registry) or MCP tools (capability/mcpsource), combined with codemode.Combine. - Validate every capability call against its input shape before ExecuteFunc runs; errors name the path and go back to the repair loop. - gosource.Func derives the schema from Go structs, decodes and encodes, and takes access as a required argument. - agent.RunAs[T] checks and decodes the program's answer into T. - NeedsApproval holds a write and every later one; agent.PlanStore and ApplyPlan apply a plan once, by ID, for its owner. - TypeSchema gains Required and an integer kind. --- agent/agent.go | 32 ++- agent/plan.go | 105 +++++++ agent/typed.go | 118 ++++++++ agent/typed_test.go | 136 +++++++++ capability/goschema.go | 256 +++++++++++++++++ capability/goschema_test.go | 122 ++++++++ capability/gosource/gosource.go | 272 ++++++++++++++++++ capability/gosource/gosource_test.go | 169 +++++++++++ capability/jsonschema/jsonschema.go | 150 ++++++++++ capability/jsonschema/jsonschema_test.go | 56 ++++ capability/mcpsource/mcpsource.go | 151 +--------- capability/mcpsource/mcpsource_test.go | 11 +- capability/schema.go | 14 +- capability/validate.go | 247 ++++++++++++++++ capability/validate_test.go | 88 ++++++ codemode/codemode.go | 11 +- codemode/record.go | 34 ++- codemode/source.go | 65 +++++ codemode/source_test.go | 149 ++++++++++ codemode/sourcetest/sourcetest.go | 73 +++++ gen/codemode/codemode.pb.go | 31 +- mcpserver/mcpserver.go | 17 +- mcpserver/mcpserver_test.go | 12 +- proto/codemode.proto | 4 + .../fixturepb/gen/fixture/v1/orders.pb.go | 6 +- .../internal/fixturepb/proto/orders.proto | 1 + registry/reflect_test.go | 3 + registry/registry.go | 85 +++++- registry/registry_test.go | 45 +++ sandbox/starlark/starlark.go | 5 +- scripts/check-consumer.sh | 2 +- 31 files changed, 2292 insertions(+), 178 deletions(-) create mode 100644 agent/plan.go create mode 100644 agent/typed.go create mode 100644 agent/typed_test.go create mode 100644 capability/goschema.go create mode 100644 capability/goschema_test.go create mode 100644 capability/gosource/gosource.go create mode 100644 capability/gosource/gosource_test.go create mode 100644 capability/jsonschema/jsonschema.go create mode 100644 capability/jsonschema/jsonschema_test.go create mode 100644 capability/validate.go create mode 100644 capability/validate_test.go create mode 100644 codemode/source.go create mode 100644 codemode/source_test.go create mode 100644 codemode/sourcetest/sourcetest.go diff --git a/agent/agent.go b/agent/agent.go index 5f7b548..6db0155 100644 --- a/agent/agent.go +++ b/agent/agent.go @@ -35,6 +35,13 @@ type Options struct { OnCall func(codemode.Call) // Stops repair attempts once spent; zero disables. Only providers that report usage count. MaxTokens int64 + // Plans keeps writes held for approval so they can be applied by ID; nil returns them in Pending only. + Plans PlanStore + // PlanOwner scopes a saved plan to one caller, such as a user ID; ApplyPlan must pass the same. + PlanOwner string + + // Set by RunAs: checks the returned value, so a mismatch is repaired like a failure. + check func(any) error } const ( @@ -171,7 +178,7 @@ func generate(ctx context.Context, mode codemode.CodeMode, model llm.Client, req if err == nil { result.Answer = answer result.Planned = planned(recorder) - return result, nil + return result, pending(ctx, recorder, result.Planned, options) } if stop := unretryable(recorder, err); stop != nil { return result, stop @@ -246,9 +253,27 @@ func run(ctx context.Context, mode codemode.CodeMode, source string, options Opt running := time.Now() answer, err := options.Runner.Run(codemode.WithRecorder(ctx, recorder), mode, source) timing.Run += time.Since(running) + if err == nil && options.check != nil { + err = options.check(answer) + } return answer, recorder, err } +func pending(ctx context.Context, recorder *codemode.Recorder, held []codemode.Call, options Options) error { + if !recorder.Pending() { + return nil + } + plan := &Pending{Calls: held} + if options.Plans != nil { + id, err := options.Plans.Save(ctx, options.PlanOwner, held) + if err != nil { + return fmt.Errorf("save plan: %w", err) + } + plan.ID = id + } + return plan +} + func unretryable(recorder *codemode.Recorder, err error) error { if permanent := recorder.Permanent(); permanent != nil { return fmt.Errorf("%w: %w", ErrNotRetried, permanent) @@ -269,9 +294,10 @@ func planned(recorder *codemode.Recorder) []codemode.Call { return writes } -// Stops at the first failure; each write still passes the registry and the transport. +// Apply runs approved calls, including writes that need approval. It stops at the +// first failure; each call still passes validation, the registry and the transport. func Apply(ctx context.Context, mode codemode.CodeMode, planned []codemode.Call) ([]codemode.Call, error) { - recorder := &codemode.Recorder{} + recorder := &codemode.Recorder{Approved: true} ctx = codemode.WithRecorder(ctx, recorder) for _, call := range planned { if _, err := mode.Execute(ctx, call.Name, call.Input); err != nil { diff --git a/agent/plan.go b/agent/plan.go new file mode 100644 index 0000000..ef9c45a --- /dev/null +++ b/agent/plan.go @@ -0,0 +1,105 @@ +package agent + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "sync" + "time" + + "github.com/mukezhz/codemode/codemode" +) + +// Pending is the error a run returns when a write is held for approval. Show +// Calls to the person; on approval, apply them with ApplyPlan(ID), or with +// Apply(Calls) when no PlanStore is configured. +type Pending struct { + // Empty when Options.Plans is nil. + ID string + Calls []codemode.Call +} + +func (pending *Pending) Error() string { + return fmt.Sprintf("%d write(s) wait for approval", len(pending.Calls)) +} + +// ErrNoPlan is returned for a plan that does not exist, has expired, was +// already applied, or belongs to another owner. +var ErrNoPlan = errors.New("no such plan") + +// PlanStore keeps held writes on the server, so the client sends back only an +// ID and cannot change what was approved. Take removes the plan: it applies once. +type PlanStore interface { + Save(ctx context.Context, owner string, calls []codemode.Call) (id string, err error) + Take(ctx context.Context, owner, id string) ([]codemode.Call, error) +} + +// DefaultPlanTTL is how long a memory plan waits for approval. +const DefaultPlanTTL = 15 * time.Minute + +type memoryPlans struct { + ttl time.Duration + mutex sync.Mutex + plans map[string]memoryPlan +} + +type memoryPlan struct { + owner string + calls []codemode.Call + expires time.Time +} + +var _ PlanStore = (*memoryPlans)(nil) + +// NewMemoryPlans keeps plans in this process for ttl (DefaultPlanTTL when zero). +// ponytail: one process only; back PlanStore with your database when there are replicas. +func NewMemoryPlans(ttl time.Duration) PlanStore { + if ttl <= 0 { + ttl = DefaultPlanTTL + } + return &memoryPlans{ttl: ttl, plans: map[string]memoryPlan{}} +} + +func (store *memoryPlans) Save(_ context.Context, owner string, calls []codemode.Call) (string, error) { + random := make([]byte, 16) + if _, err := rand.Read(random); err != nil { + return "", err + } + id := hex.EncodeToString(random) + now := time.Now() + store.mutex.Lock() + defer store.mutex.Unlock() + for key, plan := range store.plans { + if now.After(plan.expires) { + delete(store.plans, key) + } + } + store.plans[id] = memoryPlan{owner: owner, calls: append([]codemode.Call(nil), calls...), expires: now.Add(store.ttl)} + return id, nil +} + +func (store *memoryPlans) Take(_ context.Context, owner, id string) ([]codemode.Call, error) { + store.mutex.Lock() + defer store.mutex.Unlock() + plan, found := store.plans[id] + if !found || plan.owner != owner { + return nil, ErrNoPlan + } + delete(store.plans, id) + if time.Now().After(plan.expires) { + return nil, ErrNoPlan + } + return plan.calls, nil +} + +// ApplyPlan runs an approved plan once. Pass the caller's current runtime: every +// call passes validation, the registry and your transport again. +func ApplyPlan(ctx context.Context, mode codemode.CodeMode, store PlanStore, owner, id string) ([]codemode.Call, error) { + calls, err := store.Take(ctx, owner, id) + if err != nil { + return nil, err + } + return Apply(ctx, mode, calls) +} diff --git a/agent/typed.go b/agent/typed.go new file mode 100644 index 0000000..7c17029 --- /dev/null +++ b/agent/typed.go @@ -0,0 +1,118 @@ +package agent + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "reflect" + "slices" + "sort" + "strings" + + "github.com/mukezhz/codemode/capability" + "github.com/mukezhz/codemode/codemode" + "github.com/mukezhz/codemode/llm" +) + +// RunAs is Run with a typed answer. The model is told the shape of T, the +// program's return value is checked against it, and a mismatch goes back to the +// model to repair like any failure. T is a struct, following encoding/json as +// gosource does, or a string. +func RunAs[T any](ctx context.Context, mode codemode.CodeMode, model llm.Client, request string, options Options) (T, Result, error) { + var answer T + shape, check, err := expect[T]() + if err != nil { + return answer, Result{}, err + } + if shape != "" { + options.Instructions = strings.TrimSpace(options.Instructions + "\n" + shape) + } + options.check = check + result, err := Run(ctx, mode, model, request, options) + if err != nil { + return answer, result, err + } + err = decodeAnswer(result.Answer, &answer) + return answer, result, err +} + +func expect[T any]() (string, func(any) error, error) { + t := reflect.TypeFor[T]() + if t.Kind() == reflect.String { + return "", func(answer any) error { + if _, ok := answer.(string); !ok { + return fmt.Errorf("the program must return a string, got %T", answer) + } + return nil + }, nil + } + schema, types, err := capability.SchemaOf(t, "Answer") + if err != nil { + return "", nil, fmt.Errorf("RunAs needs a struct or string type: %w", err) + } + check := func(answer any) error { + encoded, err := json.Marshal(answer) + if err != nil { + return fmt.Errorf("the returned value cannot be encoded: %w", err) + } + if err := capability.ValidateValue(schema, types, encoded); err != nil { + return fmt.Errorf("the returned value does not match %s: %w", schema.Type, err) + } + var decoded T + return decodeAnswer(answer, &decoded) + } + return describeShape(schema, types), check, nil +} + +func decodeAnswer(answer any, target any) error { + encoded, err := json.Marshal(answer) + if err != nil { + return err + } + decoder := json.NewDecoder(bytes.NewReader(encoded)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(target); err != nil { + return fmt.Errorf("the returned value does not decode: %w", err) + } + return nil +} + +// describeShape is dialect-neutral: every engine's model reads it the same way. +func describeShape(schema capability.TypeSchema, types map[string]capability.TypeSchema) string { + var builder strings.Builder + builder.WriteString("Instead of a string, return an object of type " + schema.Type + ". Fields marked ? may be left out; every other field is required.\n") + writeShape(&builder, schema) + names := make([]string, 0, len(types)) + for name := range types { + if name != schema.Type { + names = append(names, name) + } + } + sort.Strings(names) + for _, name := range names { + writeShape(&builder, types[name]) + } + return builder.String() +} + +func writeShape(builder *strings.Builder, schema capability.TypeSchema) { + if len(schema.Values) > 0 { + fmt.Fprintf(builder, "%s is one of %s\n", schema.Type, strings.Join(schema.Values, ", ")) + return + } + fields := make([]string, 0, len(schema.Fields)) + for name, neutral := range schema.Fields { + marker := "" + if slices.Contains(schema.Optional, name) { + marker = "?" + } + field := name + marker + ": " + neutral + if description := schema.Descriptions[name]; description != "" { + field += " (" + description + ")" + } + fields = append(fields, field) + } + sort.Strings(fields) + fmt.Fprintf(builder, "%s { %s }\n", schema.Type, strings.Join(fields, ", ")) +} diff --git a/agent/typed_test.go b/agent/typed_test.go new file mode 100644 index 0000000..48fcdde --- /dev/null +++ b/agent/typed_test.go @@ -0,0 +1,136 @@ +package agent + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + "time" + + "github.com/mukezhz/codemode/capability" + "github.com/mukezhz/codemode/codemode" +) + +type summary struct { + Open int `json:"open" desc:"todos not done"` + Names []string `json:"names"` + Note string `json:"note,omitempty"` +} + +func TestRunAsRepairsAnAnswerOfTheWrongShape(t *testing.T) { + mode, _ := effects(t) + author := &model{responses: []string{ + `return "two open";`, + `return { open: 1.5, names: [] };`, + `const { todos } = codemode.execute("todos.list", {}); return { open: todos.length, names: ["a"] };`, + }} + + answer, result, err := RunAs[summary](context.Background(), mode, author, "summarize", Options{Runner: newRunner(t)}) + if err != nil { + t.Fatal(err) + } + if answer.Open != 1 || strings.Join(answer.Names, ",") != "a" || result.Attempts != 3 { + t.Fatalf("answer = %+v, attempts = %d", answer, result.Attempts) + } + if !strings.Contains(author.systems[0], "summary { names: repeated string, note?: string, open: integer (todos not done) }") { + t.Fatalf("system prompt does not describe the shape:\n%s", author.systems[0]) + } + if !strings.Contains(author.prompts[1], "want object summary") || !strings.Contains(author.prompts[2], "open: want integer, got 1.5") { + t.Fatalf("repair prompts = %q", author.prompts[1:]) + } +} + +func TestRunAsGivesUpWithTheLastShapeError(t *testing.T) { + mode, _ := effects(t) + author := &model{responses: []string{`return {};`, `return {};`}} + _, _, err := RunAs[summary](context.Background(), mode, author, "summarize", Options{Runner: newRunner(t), Attempts: 2}) + if err == nil || !strings.Contains(err.Error(), "names: required") { + t.Fatalf("err = %v", err) + } +} + +func TestRunAsString(t *testing.T) { + mode, _ := effects(t) + author := &model{responses: []string{`return 3;`, `return "three";`}} + answer, _, err := RunAs[string](context.Background(), mode, author, "count", Options{Runner: newRunner(t)}) + if err != nil || answer != "three" { + t.Fatalf("answer = %q, err = %v", answer, err) + } +} + +func approvals(t *testing.T) (codemode.CodeMode, *[]string) { + t.Helper() + var executed []string + registry := capability.Registry{Capabilities: []capability.Capability{ + {Name: "todos.list", RPC: "list", ReadOnly: true}, + {Name: "todos.rename", RPC: "rename"}, + {Name: "todos.delete", RPC: "delete", NeedsApproval: true}, + }} + source := codemode.Source{Registry: registry, Execute: func(_ context.Context, rpc string, _ json.RawMessage) (json.RawMessage, error) { + executed = append(executed, rpc) + return json.RawMessage(`{"todos":[{"id":1}]}`), nil + }} + mode, err := codemode.FromSource(source, capability.Caller{}) + if err != nil { + t.Fatal(err) + } + return mode, &executed +} + +func TestRunHoldsAWriteThatNeedsApprovalUntilThePlanIsApplied(t *testing.T) { + mode, executed := approvals(t) + author := &model{responses: []string{` + const { todos } = codemode.execute("todos.list", {}); + codemode.execute("todos.rename", { id: 1 }); + codemode.execute("todos.delete", { id: todos[0].id }); + codemode.execute("todos.rename", { id: 2 }); + return "cleaned up";`}} + plans := NewMemoryPlans(0) + + _, err := Run(context.Background(), mode, author, "clean up", Options{Runner: newRunner(t), Plans: plans, PlanOwner: "ada"}) + var held *Pending + if !errors.As(err, &held) { + t.Fatalf("err = %v, want *Pending", err) + } + if strings.Join(*executed, ",") != "list,rename" || len(held.Calls) != 2 || held.ID == "" { + t.Fatalf("executed = %v, held = %+v", *executed, held) + } + + if _, err := ApplyPlan(context.Background(), mode, plans, "grace", held.ID); !errors.Is(err, ErrNoPlan) { + t.Fatalf("another owner applied the plan: %v", err) + } + calls, err := ApplyPlan(context.Background(), mode, plans, "ada", held.ID) + if err != nil || len(calls) != 2 || strings.Join(*executed, ",") != "list,rename,delete,rename" { + t.Fatalf("calls = %+v, executed = %v, err = %v", calls, *executed, err) + } + if _, err := ApplyPlan(context.Background(), mode, plans, "ada", held.ID); !errors.Is(err, ErrNoPlan) { + t.Fatalf("a plan applied twice: %v", err) + } +} + +func TestAnExpiredPlanDoesNotApply(t *testing.T) { + plans := NewMemoryPlans(time.Nanosecond) + id, err := plans.Save(context.Background(), "ada", []codemode.Call{{Name: "todos.delete"}}) + if err != nil { + t.Fatal(err) + } + if _, err := plans.Take(context.Background(), "ada", id); !errors.Is(err, ErrNoPlan) { + t.Fatalf("err = %v", err) + } +} + +func TestApplyFailsForACallerWhoLostAccess(t *testing.T) { + plans := NewMemoryPlans(0) + id, _ := plans.Save(context.Background(), "ada", []codemode.Call{{Name: "todos.delete", Input: json.RawMessage(`{}`)}}) + lost, err := codemode.FromSource(codemode.Source{ + Registry: capability.Registry{Capabilities: []capability.Capability{{Name: "todos.delete", RPC: "delete", Roles: []string{"admin"}, NeedsApproval: true}}}, + Execute: func(context.Context, string, json.RawMessage) (json.RawMessage, error) { return nil, nil }, + }, capability.Caller{Roles: []string{"member"}}) + if err != nil { + t.Fatal(err) + } + if _, err := ApplyPlan(context.Background(), lost, plans, "ada", id); err == nil { + t.Fatal("applied a plan for a caller who may no longer call it") + } +} diff --git a/capability/goschema.go b/capability/goschema.go new file mode 100644 index 0000000..e501c0a --- /dev/null +++ b/capability/goschema.go @@ -0,0 +1,256 @@ +package capability + +import ( + "encoding" + "encoding/json" + "fmt" + "reflect" + "regexp" + "slices" + "sort" + "strings" + "time" +) + +// Enum is implemented by a string type that accepts only certain values: +// +// type Priority string +// func (Priority) Enum() []string { return []string{"low", "high"} } +type Enum interface { + Enum() []string +} + +// SchemaOf describes the Go struct type t in the neutral form, following +// encoding/json: the json tag names a field and `json:"-"` hides it; a pointer, +// omitempty or omitzero makes it optional and every other field is required; +// embedded structs are flattened. A desc tag describes a field to the model. +// fallback names t when it is anonymous. Types with a shape reflection cannot +// know, such as a custom json.Marshaler, are an error. +func SchemaOf(t reflect.Type, fallback string) (TypeSchema, map[string]TypeSchema, error) { + for t.Kind() == reflect.Pointer { + t = t.Elem() + } + if t.Kind() != reflect.Struct || t == timeType { + return TypeSchema{}, nil, fmt.Errorf("%s is not a struct", t) + } + walker := &goWalker{types: map[string]TypeSchema{}, owners: map[string]reflect.Type{}} + name, err := walker.typeName(t, fallback) + if err != nil { + return TypeSchema{}, nil, err + } + walker.owners[name] = t + walker.root = name + schema, err := walker.object(t, name) + if err != nil { + return TypeSchema{}, nil, err + } + if walker.rootReferenced { + walker.types[name] = schema + } + return schema, walker.types, nil +} + +var ( + timeType = reflect.TypeFor[time.Time]() + rawType = reflect.TypeFor[json.RawMessage]() + marshalerType = reflect.TypeFor[json.Marshaler]() + textMarshalerType = reflect.TypeFor[encoding.TextMarshaler]() + enumType = reflect.TypeFor[Enum]() + qualifier = regexp.MustCompile(`[\w./-]*\.`) +) + +type goWalker struct { + types map[string]TypeSchema + owners map[string]reflect.Type + root string + rootReferenced bool +} + +func (walker *goWalker) object(t reflect.Type, name string) (TypeSchema, error) { + schema := TypeSchema{Type: name, Fields: map[string]string{}} + descriptions := map[string]string{} + if err := walker.fields(t, name, &schema, descriptions); err != nil { + return TypeSchema{}, err + } + sort.Strings(schema.Optional) + sort.Strings(schema.Required) + if len(descriptions) > 0 { + schema.Descriptions = descriptions + } + return schema, nil +} + +func (walker *goWalker) fields(t reflect.Type, owner string, schema *TypeSchema, descriptions map[string]string) error { + for index := range t.NumField() { + field := t.Field(index) + tag := field.Tag.Get("json") + if tag == "-" { + continue + } + name, options, _ := strings.Cut(tag, ",") + if field.Anonymous && name == "" { + embedded := field.Type + if embedded.Kind() == reflect.Pointer { + embedded = embedded.Elem() + } + if embedded.Kind() == reflect.Struct { + if err := walker.fields(embedded, owner, schema, descriptions); err != nil { + return err + } + continue + } + } + if !field.IsExported() { + continue + } + if name == "" { + name = field.Name + } + if _, exists := schema.Fields[name]; exists { + return fmt.Errorf("%s.%s: two fields encode as %q", owner, field.Name, name) + } + + kind, err := walker.neutral(field.Type, owner+field.Name) + if err != nil { + return fmt.Errorf("%s.%s: %w", owner, field.Name, err) + } + if slices.Contains(strings.Split(options, ","), "string") { + kind = "string" + } + schema.Fields[name] = kind + + description := strings.TrimSpace(field.Tag.Get("desc")) + if description == "" && deref(field.Type) == timeType { + description = "RFC 3339 timestamp, such as 2026-01-02T15:04:05Z" + } + if description != "" { + descriptions[name] = description + } + + optional := field.Type.Kind() == reflect.Pointer || + slices.Contains(strings.Split(options, ","), "omitempty") || + slices.Contains(strings.Split(options, ","), "omitzero") + if optional { + schema.Optional = append(schema.Optional, name) + } else { + schema.Required = append(schema.Required, name) + } + } + return nil +} + +func (walker *goWalker) neutral(t reflect.Type, fallback string) (string, error) { + t = deref(t) + switch { + case t == timeType: + return "string", nil + case t == rawType || t.Kind() == reflect.Interface: + return "any", nil + case t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8: + return "bytes", nil + case t.Kind() == reflect.String && t.Implements(enumType): + return walker.enum(t, fallback) + case t.Implements(marshalerType) || reflect.PointerTo(t).Implements(marshalerType): + return "", fmt.Errorf("%s implements json.Marshaler, so its JSON shape is unknown", t) + case t.Implements(textMarshalerType) || reflect.PointerTo(t).Implements(textMarshalerType): + return "string", nil + } + + switch t.Kind() { + case reflect.String: + return "string", nil + case reflect.Bool: + return "bool", nil + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return "integer", nil + case reflect.Float32, reflect.Float64: + return "number", nil + case reflect.Slice, reflect.Array: + element, err := walker.neutral(t.Elem(), fallback+"Item") + if err != nil { + return "", err + } + return "repeated " + element, nil + case reflect.Map: + key, err := walker.mapKey(t.Key()) + if err != nil { + return "", err + } + value, err := walker.neutral(t.Elem(), fallback+"Value") + if err != nil { + return "", err + } + return "map<" + key + ", " + value + ">", nil + case reflect.Struct: + return walker.named(t, fallback) + } + return "", fmt.Errorf("%s cannot be sent as JSON", t) +} + +func (walker *goWalker) mapKey(t reflect.Type) (string, error) { + switch t.Kind() { + case reflect.String: + return "string", nil + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return "integer", nil + } + return "", fmt.Errorf("map key %s must be a string or an integer", t) +} + +func (walker *goWalker) named(t reflect.Type, fallback string) (string, error) { + name, err := walker.typeName(t, fallback) + if err != nil { + return "", err + } + if walker.owners[name] == t { + walker.rootReferenced = walker.rootReferenced || name == walker.root + return name, nil + } + walker.owners[name] = t + schema, err := walker.object(t, name) + if err != nil { + return "", err + } + walker.types[name] = schema + return name, nil +} + +func (walker *goWalker) enum(t reflect.Type, fallback string) (string, error) { + name, err := walker.typeName(t, fallback) + if err != nil { + return "", err + } + if walker.owners[name] == t { + return name, nil + } + values := reflect.Zero(t).Interface().(Enum).Enum() + if len(values) == 0 { + return "", fmt.Errorf("%s.Enum() returned no values", t) + } + walker.owners[name] = t + walker.types[name] = TypeSchema{Type: name, Values: values} + return name, nil +} + +// typeName is the Go name without package paths; generic arguments keep their short names. +func (walker *goWalker) typeName(t reflect.Type, fallback string) (string, error) { + name := t.Name() + if name == "" { + name = fallback + } + name = qualifier.ReplaceAllString(name, "") + name = strings.NewReplacer("[", "", "]", "", ",", "", " ", "", "*", "").Replace(name) + if owner, taken := walker.owners[name]; taken && owner != t { + return "", fmt.Errorf("two different types are both named %s (%s and %s)", name, owner, t) + } + return name, nil +} + +func deref(t reflect.Type) reflect.Type { + for t.Kind() == reflect.Pointer { + t = t.Elem() + } + return t +} diff --git a/capability/goschema_test.go b/capability/goschema_test.go new file mode 100644 index 0000000..fa06c1f --- /dev/null +++ b/capability/goschema_test.go @@ -0,0 +1,122 @@ +package capability + +import ( + "encoding/json" + "reflect" + "strings" + "testing" + "time" +) + +type priority string + +func (priority) Enum() []string { return []string{"low", "high"} } + +type audit struct { + CreatedAt time.Time `json:"created_at"` +} + +type tag struct { + Name string `json:"name"` +} + +type createTask struct { + audit + Title string `json:"title" desc:"short summary"` + Priority priority `json:"priority,omitempty"` + Due *time.Time `json:"due"` + Points int `json:"points"` + Weight float64 `json:"weight,omitzero"` + ID int64 `json:"id,string,omitempty"` + Tags []tag `json:"tags"` + Counts map[string]int `json:"counts"` + Extra json.RawMessage `json:"extra,omitempty"` + Blob []byte `json:"blob,omitempty"` + Hidden string `json:"-"` + Untagged bool + internal string +} + +func TestSchemaOfFollowsEncodingJSON(t *testing.T) { + schema, types, err := SchemaOf(reflect.TypeFor[createTask](), "Fallback") + if err != nil { + t.Fatal(err) + } + want := map[string]string{ + "created_at": "string", "title": "string", "priority": "priority", "due": "string", + "points": "integer", "weight": "number", "id": "string", "tags": "repeated tag", + "counts": "map", "extra": "any", "blob": "bytes", "Untagged": "bool", + } + if !reflect.DeepEqual(schema.Fields, want) { + t.Errorf("fields = %v", schema.Fields) + } + if schema.Type != "createTask" { + t.Errorf("type = %q", schema.Type) + } + if got := strings.Join(schema.Required, ","); got != "Untagged,counts,created_at,points,tags,title" { + t.Errorf("required = %s", got) + } + if got := strings.Join(schema.Optional, ","); got != "blob,due,extra,id,priority,weight" { + t.Errorf("optional = %s", got) + } + if schema.Descriptions["title"] != "short summary" || !strings.Contains(schema.Descriptions["due"], "RFC 3339") { + t.Errorf("descriptions = %v", schema.Descriptions) + } + if strings.Join(types["priority"].Values, ",") != "low,high" || types["tag"].Fields["name"] != "string" { + t.Errorf("types = %v", types) + } +} + +type node struct { + Value string `json:"value"` + Children []node `json:"children"` +} + +func TestSchemaOfDeclaresARecursiveRoot(t *testing.T) { + _, types, err := SchemaOf(reflect.TypeFor[node](), "") + if err != nil { + t.Fatal(err) + } + if types["node"].Fields["children"] != "repeated node" { + t.Fatalf("types = %v", types) + } +} + +type shadowed struct { + A string `json:"a"` +} + +// encoding/json would silently drop one of the two "a" fields. +type clash struct { + shadowed + B string `json:"a"` +} + +type opaque struct{} + +func (opaque) MarshalJSON() ([]byte, error) { return []byte(`1`), nil } + +func TestSchemaOfRefusesShapesItCannotKnow(t *testing.T) { + for name, value := range map[string]reflect.Type{ + "not a struct": reflect.TypeFor[string](), + "marshaler": reflect.TypeFor[struct{ X opaque }](), + "channel": reflect.TypeFor[struct{ C chan int }](), + "bool key": reflect.TypeFor[struct{ M map[bool]int }](), + "clash": reflect.TypeFor[clash](), + } { + if _, _, err := SchemaOf(value, "T"); err == nil { + t.Errorf("%s: described", name) + } + } +} + +func TestSchemaOfAgreesWithValidate(t *testing.T) { + schema, types, err := SchemaOf(reflect.TypeFor[createTask](), "") + if err != nil { + t.Fatal(err) + } + encoded, _ := json.Marshal(createTask{Title: "a", Tags: []tag{{Name: "x"}}, Counts: map[string]int{"a": 1}, Priority: "low"}) + if err := ValidateValue(schema, types, encoded); err != nil { + t.Fatalf("a value of the type fails its own schema: %v\n%s", err, encoded) + } +} diff --git a/capability/gosource/gosource.go b/capability/gosource/gosource.go new file mode 100644 index 0000000..6bb6c17 --- /dev/null +++ b/capability/gosource/gosource.go @@ -0,0 +1,272 @@ +// Package gosource turns typed Go functions into capabilities: the schema the +// model sees comes from the request and response structs, input is validated +// and decoded before the function runs, and there is no switch to write. +// +// source, err := gosource.New( +// gosource.Func("todos.list", "Lists todos", gosource.Public(), app.List, gosource.ReadOnly()), +// gosource.Func("todos.delete", "Deletes a todo", gosource.Roles("member"), app.Delete, gosource.NeedsApproval()), +// ) +package gosource + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "reflect" + "regexp" + "slices" + "strings" + + "github.com/mukezhz/codemode/capability" + "github.com/mukezhz/codemode/codemode" +) + +// Access says who may call a capability. There is no zero value: every Func +// names one of Public, Roles or Permissions, so none is exposed by omission. +type Access interface { + grant() (roles, permissions []string, public bool) +} + +type access struct { + roles, permissions []string + public bool +} + +func (access access) grant() ([]string, []string, bool) { + return access.roles, access.permissions, access.public +} + +// Public lets every caller call the capability. +func Public() Access { return access{public: true} } + +// Roles lets callers holding any of roles call the capability. +func Roles(roles ...string) Access { return access{roles: roles} } + +// Permissions lets callers holding any of permissions, such as "deals.write", call the capability. +func Permissions(permissions ...string) Access { return access{permissions: permissions} } + +type Option func(*capability.Capability) + +// ReadOnly marks a capability that changes nothing. Anything else is treated as a +// write: never cached, never retried after it ran, held in plan mode. +func ReadOnly() Option { return func(item *capability.Capability) { item.ReadOnly = true } } + +// NeedsApproval holds the write, and every write after it in the same program, +// until a person approves the plan. +func NeedsApproval() Option { return func(item *capability.Capability) { item.NeedsApproval = true } } + +type Definition struct { + item capability.Capability + call func(context.Context, json.RawMessage) (json.RawMessage, error) + err error +} + +var namePattern = regexp.MustCompile(`^[a-z][A-Za-z0-9_]*\.[a-z][A-Za-z0-9_]*$`) + +// Func defines the capability name, such as "todos.list", served by handler. +// In and Out must be structs; their fields follow encoding/json, and a desc tag +// describes a field to the model. Errors surface from New. +func Func[In, Out any](name, description string, access Access, handler func(context.Context, In) (Out, error), options ...Option) Definition { + fail := func(err error) Definition { return Definition{err: fmt.Errorf("gosource: %s: %w", name, err)} } + if !namePattern.MatchString(name) { + return fail(fmt.Errorf("name must be namespace.method, matching %s", namePattern)) + } + if strings.TrimSpace(description) == "" { + return fail(errors.New("a description is required; it is what search matches and the model reads")) + } + if access == nil { + return fail(errors.New("access is required: gosource.Public(), gosource.Roles(...) or gosource.Permissions(...)")) + } + if handler == nil { + return fail(errors.New("handler is nil")) + } + roles, permissions, public := access.grant() + roles, permissions = trimmed(roles), trimmed(permissions) + if !public && len(roles) == 0 && len(permissions) == 0 { + return fail(errors.New("Roles() and Permissions() need at least one name; use Public() to allow everyone")) + } + for _, permission := range permissions { + if err := capability.ValidatePermission(permission); err != nil { + return fail(err) + } + } + + base := typeBase(name) + input, inputTypes, err := capability.SchemaOf(reflect.TypeFor[In](), base+"Input") + if err != nil { + return fail(fmt.Errorf("input: %w", err)) + } + output, outputTypes, err := capability.SchemaOf(reflect.TypeFor[Out](), base+"Output") + if err != nil { + return fail(fmt.Errorf("output: %w", err)) + } + types := inputTypes + for typeName, schema := range outputTypes { + if existing, taken := types[typeName]; taken && !reflect.DeepEqual(existing, schema) { + return fail(fmt.Errorf("input and output both use the name %s for different types", typeName)) + } + types[typeName] = schema + } + if len(types) == 0 { + types = nil + } + + item := capability.Capability{ + Name: name, RPC: name, Description: strings.TrimSpace(description), + Input: input, Output: output, Types: types, + Roles: roles, Permissions: permissions, + } + for _, option := range options { + option(&item) + } + if item.ReadOnly && item.NeedsApproval { + return fail(errors.New("a read-only capability cannot need approval")) + } + + return Definition{item: item, call: func(ctx context.Context, raw json.RawMessage) (output json.RawMessage, err error) { + var request In + if err := decode(raw, &request); err != nil { + return nil, fmt.Errorf("decode input: %w", err) + } + defer func() { + if recovered := recover(); recovered != nil { + output, err = nil, fmt.Errorf("%s panicked: %v", name, recovered) + } + }() + response, err := handler(ctx, request) + if err != nil { + return nil, err + } + return encode(response, item.Output, item.Types) + }} +} + +// New collects definitions into a source. Its RPCs are the capability names. +func New(definitions ...Definition) (codemode.Source, error) { + var errs []error + calls := map[string]func(context.Context, json.RawMessage) (json.RawMessage, error){} + shapes := map[string]capability.TypeSchema{} + registry := capability.Registry{Capabilities: []capability.Capability{}} + for _, definition := range definitions { + if definition.err != nil { + errs = append(errs, definition.err) + continue + } + if _, exists := calls[definition.item.Name]; exists { + errs = append(errs, fmt.Errorf("gosource: %s is defined twice", definition.item.Name)) + continue + } + // The prompt declares each shape once by name, so one name must mean one shape. + for typeName, schema := range definition.item.Types { + if existing, taken := shapes[typeName]; taken && !reflect.DeepEqual(existing, schema) { + errs = append(errs, fmt.Errorf("gosource: %s: another capability already uses the name %s for a different type", definition.item.Name, typeName)) + } + shapes[typeName] = schema + } + calls[definition.item.Name] = definition.call + registry.Capabilities = append(registry.Capabilities, definition.item) + } + if len(definitions) == 0 { + errs = append(errs, errors.New("gosource: no definitions given")) + } + if err := errors.Join(errs...); err != nil { + return codemode.Source{}, err + } + return codemode.Source{ + Registry: registry, + Execute: func(ctx context.Context, rpc string, input json.RawMessage) (json.RawMessage, error) { + call, ok := calls[rpc] + if !ok { + return nil, fmt.Errorf("gosource: %s is not defined", rpc) + } + return call(ctx, input) + }, + }, nil +} + +func decode(raw json.RawMessage, target any) error { + if trimmed := bytes.TrimSpace(raw); len(trimmed) == 0 || string(trimmed) == "null" { + return nil + } + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(target); err != nil { + return err + } + if err := decoder.Decode(&struct{}{}); err != io.EOF { + return errors.New("expected one JSON value") + } + return nil +} + +// encode sends nil slices and maps as [] and {}: the prompt promised the model a list. +func encode(response any, schema capability.TypeSchema, types map[string]capability.TypeSchema) (json.RawMessage, error) { + encoded, err := json.Marshal(response) + if err != nil { + return nil, fmt.Errorf("encode output: %w", err) + } + var value any + if err := json.Unmarshal(encoded, &value); err != nil { + return nil, err + } + return json.Marshal(fill(value, schema, types)) +} + +func fill(value any, schema capability.TypeSchema, types map[string]capability.TypeSchema) any { + object, ok := value.(map[string]any) + if !ok { + return value + } + for name, fieldType := range schema.Fields { + object[name] = fillValue(object[name], fieldType, types, schema.Optional, name) + } + return object +} + +func fillValue(value any, neutral string, types map[string]capability.TypeSchema, optional []string, name string) any { + if element, found := strings.CutPrefix(neutral, "repeated "); found { + items, _ := value.([]any) + if value == nil { + if slices.Contains(optional, name) { + return nil + } + return []any{} + } + for index, item := range items { + items[index] = fillValue(item, element, types, nil, "") + } + return items + } + if strings.HasPrefix(neutral, "map<") { + if value == nil && !slices.Contains(optional, name) { + return map[string]any{} + } + return value + } + if nested, known := types[neutral]; known && value != nil { + return fill(value, nested, types) + } + return value +} + +func trimmed(values []string) []string { + var kept []string + for _, value := range values { + if value = strings.TrimSpace(value); value != "" { + kept = append(kept, value) + } + } + return kept +} + +// typeBase names anonymous structs: "todos.list" becomes "TodosList". +func typeBase(name string) string { + var builder strings.Builder + for _, part := range strings.FieldsFunc(name, func(r rune) bool { return r == '.' || r == '_' }) { + builder.WriteString(strings.ToUpper(part[:1]) + part[1:]) + } + return builder.String() +} diff --git a/capability/gosource/gosource_test.go b/capability/gosource/gosource_test.go new file mode 100644 index 0000000..d7d490e --- /dev/null +++ b/capability/gosource/gosource_test.go @@ -0,0 +1,169 @@ +package gosource_test + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + + "github.com/mukezhz/codemode/capability" + "github.com/mukezhz/codemode/capability/gosource" + "github.com/mukezhz/codemode/codemode" + "github.com/mukezhz/codemode/codemode/sourcetest" + "github.com/mukezhz/codemode/sandbox" + _ "github.com/mukezhz/codemode/sandbox/goja" +) + +type Todo struct { + ID int `json:"id"` + Title string `json:"title"` + Done bool `json:"done"` +} + +type ListRequest struct { + Done *bool `json:"done" desc:"only todos in this state; leave out for all"` +} + +type ListResponse struct { + Todos []Todo `json:"todos"` +} + +type DeleteRequest struct { + ID int `json:"id"` +} + +type app struct { + todos []Todo + deleted []int +} + +func (app *app) list(_ context.Context, request ListRequest) (ListResponse, error) { + var todos []Todo + for _, todo := range app.todos { + if request.Done == nil || todo.Done == *request.Done { + todos = append(todos, todo) + } + } + return ListResponse{Todos: todos}, nil +} + +func (app *app) remove(_ context.Context, request DeleteRequest) (struct{}, error) { + app.deleted = append(app.deleted, request.ID) + return struct{}{}, nil +} + +func todos(t *testing.T) (codemode.Source, *app) { + t.Helper() + state := &app{todos: []Todo{{ID: 1, Title: "write docs", Done: true}, {ID: 2, Title: "ship"}}} + source, err := gosource.New( + gosource.Func("todos.list", "Lists todos", gosource.Public(), state.list, gosource.ReadOnly()), + gosource.Func("todos.delete", "Deletes a todo", gosource.Roles("member"), state.remove, gosource.NeedsApproval()), + ) + if err != nil { + t.Fatal(err) + } + return source, state +} + +func TestSourcePassesTheContract(t *testing.T) { + source, _ := todos(t) + sourcetest.Run(t, source) +} + +func TestSchemaComesFromTheStructs(t *testing.T) { + source, _ := todos(t) + list := source.Registry.Capabilities[0] + if list.Input.Fields["done"] != "bool" || list.Output.Fields["todos"] != "repeated Todo" || list.Types["Todo"].Fields["id"] != "integer" { + t.Fatalf("list = %+v", list) + } + if list.Input.Descriptions["done"] == "" || !list.ReadOnly || !list.Unrestricted() { + t.Fatalf("list = %+v", list) + } + remove := source.Registry.Capabilities[1] + if strings.Join(remove.Roles, ",") != "member" || !remove.NeedsApproval || remove.ReadOnly || remove.RPC != "todos.delete" { + t.Fatalf("delete = %+v", remove) + } +} + +func TestAProgramCallsTypedFunctions(t *testing.T) { + source, state := todos(t) + mode, err := codemode.FromSource(source, capability.Caller{Roles: []string{"member"}}) + if err != nil { + t.Fatal(err) + } + runner, err := sandbox.New(sandbox.Options{}) + if err != nil { + t.Fatal(err) + } + defer runner.Close() + + value, err := runner.Run(context.Background(), mode, ` + const { todos } = codemode.execute("todos.list", { done: false }); + return todos.map(todo => todo.title).join(",");`) + if err != nil || value != "ship" { + t.Fatalf("value = %v, err = %v", value, err) + } + + _, err = runner.Run(context.Background(), mode, `return codemode.execute("todos.list", { done: "no" });`) + if err == nil || !strings.Contains(err.Error(), `done: want bool, got "no"`) { + t.Fatalf("err = %v", err) + } + + _, err = runner.Run(context.Background(), mode, `codemode.execute("todos.delete", { id: 1 }); return "ok";`) + if !errors.Is(err, codemode.ErrPermanent) || len(state.deleted) != 0 { + t.Fatalf("a delete that needs approval ran without one: err = %v, deleted = %v", err, state.deleted) + } +} + +func TestAnEmptyResultIsAListNotNull(t *testing.T) { + source, _ := todos(t) + output, err := source.Execute(context.Background(), "todos.list", json.RawMessage(`{"done":false,"x":1}`)) + if err == nil { + t.Fatalf("an unknown field reached the handler: %s", output) + } + empty, err := gosource.New(gosource.Func("todos.none", "Lists nothing", gosource.Public(), + func(context.Context, struct{}) (ListResponse, error) { return ListResponse{}, nil })) + if err != nil { + t.Fatal(err) + } + output, err = empty.Execute(context.Background(), "todos.none", nil) + if err != nil || string(output) != `{"todos":[]}` { + t.Fatalf("output = %s, err = %v", output, err) + } +} + +func TestAHandlerPanicIsAnError(t *testing.T) { + source, err := gosource.New(gosource.Func("todos.boom", "Panics", gosource.Public(), + func(context.Context, struct{}) (struct{}, error) { panic("boom") })) + if err != nil { + t.Fatal(err) + } + if _, err := source.Execute(context.Background(), "todos.boom", nil); err == nil || !strings.Contains(err.Error(), "panicked: boom") { + t.Fatalf("err = %v", err) + } +} + +func TestNewRefusesUnsafeOrBrokenDefinitions(t *testing.T) { + noop := func(context.Context, struct{}) (struct{}, error) { return struct{}{}, nil } + type other struct { + Todo string `json:"todo"` + } + for name, definition := range map[string]gosource.Definition{ + "no access": gosource.Func("todos.a", "A", nil, noop), + "empty roles": gosource.Func("todos.a", "A", gosource.Roles(" "), noop), + "bad permission": gosource.Func("todos.a", "A", gosource.Permissions("todos"), noop), + "bad name": gosource.Func("Todos", "A", gosource.Public(), noop), + "no description": gosource.Func("todos.a", " ", gosource.Public(), noop), + "read-only approval": gosource.Func("todos.a", "A", gosource.Public(), noop, gosource.ReadOnly(), gosource.NeedsApproval()), + "not a struct": gosource.Func("todos.a", "A", gosource.Public(), + func(context.Context, string) (struct{}, error) { return struct{}{}, nil }), + } { + if _, err := gosource.New(definition); err == nil { + t.Errorf("%s: accepted", name) + } + } + if _, err := gosource.New(gosource.Func("todos.a", "A", gosource.Public(), noop), gosource.Func("todos.a", "A", gosource.Public(), noop)); err == nil { + t.Error("a name defined twice was accepted") + } +} diff --git a/capability/jsonschema/jsonschema.go b/capability/jsonschema/jsonschema.go new file mode 100644 index 0000000..8a7d506 --- /dev/null +++ b/capability/jsonschema/jsonschema.go @@ -0,0 +1,150 @@ +// Package jsonschema converts JSON Schema objects into capability.TypeSchema. +// Constructs the neutral form cannot express are errors, never "any", which would mislead the model. +package jsonschema + +import ( + "encoding/json" + "errors" + "fmt" + "slices" + "sort" + "strings" + "unicode" + + "github.com/mukezhz/codemode/capability" +) + +type schema struct { + Type any `json:"type"` + Description string `json:"description"` + Properties map[string]*schema `json:"properties"` + Required []string `json:"required"` + Items *schema `json:"items"` + Enum []any `json:"enum"` +} + +// Object converts raw, a top-level object schema, into a shape named name. +// Nested objects and enums are added to types, named after their path. +func Object(raw any, name string, types map[string]capability.TypeSchema) (capability.TypeSchema, error) { + encoded, err := json.Marshal(raw) + if err != nil { + return capability.TypeSchema{}, err + } + var parsed schema + if err := json.Unmarshal(encoded, &parsed); err != nil { + return capability.TypeSchema{}, err + } + if kind, _ := single(parsed.Type); kind != "object" { + return capability.TypeSchema{}, fmt.Errorf("top-level schema is %v, not an object", parsed.Type) + } + return fields(&parsed, name, types) +} + +func fields(parsed *schema, name string, types map[string]capability.TypeSchema) (capability.TypeSchema, error) { + result := capability.TypeSchema{Type: name, Fields: map[string]string{}} + descriptions := map[string]string{} + for field, property := range parsed.Properties { + kind, err := typeOf(property, name+Pascal(field), types) + if err != nil { + return capability.TypeSchema{}, fmt.Errorf("%s: %w", field, err) + } + result.Fields[field] = kind + if description := strings.TrimSpace(property.Description); description != "" { + descriptions[field] = description + } + if slices.Contains(parsed.Required, field) { + result.Required = append(result.Required, field) + } else { + result.Optional = append(result.Optional, field) + } + } + sort.Strings(result.Optional) + sort.Strings(result.Required) + if len(descriptions) > 0 { + result.Descriptions = descriptions + } + return result, nil +} + +func typeOf(property *schema, name string, types map[string]capability.TypeSchema) (string, error) { + if property == nil { + return "", errors.New("no schema") + } + kind, err := single(property.Type) + if err != nil { + return "", err + } + switch kind { + case "string": + if len(property.Enum) == 0 { + return "string", nil + } + values := make([]string, len(property.Enum)) + for i, value := range property.Enum { + text, ok := value.(string) + if !ok { + return "", fmt.Errorf("enum value %v is not a string", value) + } + values[i] = text + } + types[name] = capability.TypeSchema{Type: name, Values: values} + return name, nil + case "integer": + return "integer", nil + case "number": + return "number", nil + case "boolean": + return "bool", nil + case "array": + element, err := typeOf(property.Items, name+"Item", types) + if err != nil { + return "", fmt.Errorf("items: %w", err) + } + return "repeated " + element, nil + case "object": + nested, err := fields(property, name, types) + if err != nil { + return "", err + } + types[name] = nested + return name, nil + } + return "", fmt.Errorf("unsupported type %v", property.Type) +} + +// single accepts "string" or ["string", "null"]: nullable is still one type. +func single(kind any) (string, error) { + switch kind := kind.(type) { + case string: + return kind, nil + case []any: + var found []string + for _, item := range kind { + if name, ok := item.(string); ok && name != "null" { + found = append(found, name) + } + } + if len(found) == 1 { + return found[0], nil + } + } + return "", fmt.Errorf("type %v is not a single JSON type", kind) +} + +// Pascal turns "list_issues" or "list-issues" into "ListIssues", for type names. +func Pascal(name string) string { + var builder strings.Builder + upper := true + for _, r := range name { + if !unicode.IsLetter(r) && !unicode.IsDigit(r) { + upper = true + continue + } + if upper { + r = unicode.ToUpper(r) + upper = false + } + builder.WriteRune(r) + } + return builder.String() +} diff --git a/capability/jsonschema/jsonschema_test.go b/capability/jsonschema/jsonschema_test.go new file mode 100644 index 0000000..35315e8 --- /dev/null +++ b/capability/jsonschema/jsonschema_test.go @@ -0,0 +1,56 @@ +package jsonschema + +import ( + "strings" + "testing" + + "github.com/mukezhz/codemode/capability" +) + +func TestObjectConvertsEveryKind(t *testing.T) { + types := map[string]capability.TypeSchema{} + got, err := Object(map[string]any{ + "type": "object", + "required": []any{"id", "state"}, + "properties": map[string]any{ + "id": map[string]any{"type": "integer", "description": "issue number"}, + "score": map[string]any{"type": []any{"number", "null"}}, + "open": map[string]any{"type": "boolean"}, + "state": map[string]any{"type": "string", "enum": []any{"open", "closed"}}, + "labels": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}, + "author": map[string]any{"type": "object", "properties": map[string]any{"login": map[string]any{"type": "string"}}}, + }, + }, "Issue", types) + if err != nil { + t.Fatal(err) + } + want := map[string]string{"id": "integer", "score": "number", "open": "bool", "state": "IssueState", + "labels": "repeated string", "author": "IssueAuthor"} + for field, kind := range want { + if got.Fields[field] != kind { + t.Errorf("%s = %q, want %q", field, got.Fields[field], kind) + } + } + if strings.Join(got.Required, ",") != "id,state" || strings.Join(got.Optional, ",") != "author,labels,open,score" { + t.Errorf("required = %v, optional = %v", got.Required, got.Optional) + } + if got.Descriptions["id"] != "issue number" { + t.Errorf("descriptions = %v", got.Descriptions) + } + if strings.Join(types["IssueState"].Values, ",") != "open,closed" || types["IssueAuthor"].Fields["login"] != "string" { + t.Errorf("types = %+v", types) + } +} + +func TestObjectRefusesWhatItCannotExpress(t *testing.T) { + for name, raw := range map[string]any{ + "not an object": map[string]any{"type": "string"}, + "oneOf": map[string]any{"type": "object", "properties": map[string]any{"x": map[string]any{"oneOf": []any{}}}}, + "two types": map[string]any{"type": "object", "properties": map[string]any{"x": map[string]any{"type": []any{"string", "number"}}}}, + "number enum": map[string]any{"type": "object", "properties": map[string]any{"x": map[string]any{"type": "string", "enum": []any{1}}}}, + } { + if _, err := Object(raw, "T", map[string]capability.TypeSchema{}); err == nil { + t.Errorf("%s: converted", name) + } + } +} diff --git a/capability/mcpsource/mcpsource.go b/capability/mcpsource/mcpsource.go index b76a090..ad657e1 100644 --- a/capability/mcpsource/mcpsource.go +++ b/capability/mcpsource/mcpsource.go @@ -6,24 +6,17 @@ import ( "encoding/json" "errors" "fmt" - "slices" - "sort" "strings" - "unicode" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/mukezhz/codemode/capability" + "github.com/mukezhz/codemode/capability/jsonschema" "github.com/mukezhz/codemode/codemode" ) -type Source struct { - Registry capability.Registry - // Execute serves only RPCs from this source; route the rest to your own ExecuteFunc. - Execute codemode.ExecuteFunc - // Skipped holds tools whose schemas could not be expressed, with the reason. - Skipped map[string]error -} +// Source.Execute serves only RPCs from this source; combine it with others through codemode.Combine. +type Source = codemode.Source // RPCPrefix starts the RPC of every capability imported under prefix. func RPCPrefix(prefix string) string { return "mcp/" + prefix + "/" } @@ -60,15 +53,15 @@ func convert(prefix string, tool *mcp.Tool) (capability.Capability, error) { return capability.Capability{}, fmt.Errorf("tool name %q cannot be a capability name", tool.Name) } types := map[string]capability.TypeSchema{} - base := pascal(prefix) + pascal(tool.Name) + base := jsonschema.Pascal(prefix) + jsonschema.Pascal(tool.Name) - input, err := object(tool.InputSchema, base+"Input", types) + input, err := jsonschema.Object(tool.InputSchema, base+"Input", types) if err != nil { return capability.Capability{}, fmt.Errorf("input: %w", err) } output := capability.TypeSchema{Fields: map[string]string{"text": "string"}} if tool.OutputSchema != nil { - if output, err = object(tool.OutputSchema, base+"Output", types); err != nil { + if output, err = jsonschema.Object(tool.OutputSchema, base+"Output", types); err != nil { return capability.Capability{}, fmt.Errorf("output: %w", err) } } @@ -78,139 +71,21 @@ func convert(prefix string, tool *mcp.Tool) (capability.Capability, error) { return capability.Capability{ Name: prefix + "." + tool.Name, RPC: RPCPrefix(prefix) + tool.Name, - Description: tool.Description, + Description: description(tool), Input: input, Output: output, Types: types, }, nil } -type schema struct { - Type any `json:"type"` - Description string `json:"description"` - Properties map[string]*schema `json:"properties"` - Required []string `json:"required"` - Items *schema `json:"items"` - Enum []any `json:"enum"` -} - -// Errors rather than loosening to "any", which would mislead the model. -func object(raw any, name string, types map[string]capability.TypeSchema) (capability.TypeSchema, error) { - encoded, err := json.Marshal(raw) - if err != nil { - return capability.TypeSchema{}, err - } - var parsed schema - if err := json.Unmarshal(encoded, &parsed); err != nil { - return capability.TypeSchema{}, err - } - if kind, _ := single(parsed.Type); kind != "object" { - return capability.TypeSchema{}, fmt.Errorf("top-level schema is %v, not an object", parsed.Type) - } - return fields(&parsed, name, types) -} - -func fields(parsed *schema, name string, types map[string]capability.TypeSchema) (capability.TypeSchema, error) { - result := capability.TypeSchema{Type: name, Fields: map[string]string{}} - descriptions := map[string]string{} - for field, property := range parsed.Properties { - kind, err := typeOf(property, name+pascal(field), types) - if err != nil { - return capability.TypeSchema{}, fmt.Errorf("%s: %w", field, err) - } - result.Fields[field] = kind - if description := strings.TrimSpace(property.Description); description != "" { - descriptions[field] = description - } - if !slices.Contains(parsed.Required, field) { - result.Optional = append(result.Optional, field) - } - } - sort.Strings(result.Optional) - if len(descriptions) > 0 { - result.Descriptions = descriptions - } - return result, nil -} - -func typeOf(property *schema, name string, types map[string]capability.TypeSchema) (string, error) { - if property == nil { - return "", errors.New("no schema") - } - kind, err := single(property.Type) - if err != nil { - return "", err - } - switch kind { - case "string": - if len(property.Enum) == 0 { - return "string", nil - } - values := make([]string, len(property.Enum)) - for i, value := range property.Enum { - text, ok := value.(string) - if !ok { - return "", fmt.Errorf("enum value %v is not a string", value) - } - values[i] = text - } - types[name] = capability.TypeSchema{Type: name, Values: values} - return name, nil - case "integer", "number": - return "number", nil - case "boolean": - return "bool", nil - case "array": - element, err := typeOf(property.Items, name+"Item", types) - if err != nil { - return "", fmt.Errorf("items: %w", err) - } - return "repeated " + element, nil - case "object": - nested, err := fields(property, name, types) - if err != nil { - return "", err - } - types[name] = nested - return name, nil - } - return "", fmt.Errorf("unsupported type %v", property.Type) -} - -// single accepts "string" or ["string", "null"]: nullable is still one type. -func single(kind any) (string, error) { - switch kind := kind.(type) { - case string: - return kind, nil - case []any: - var found []string - for _, item := range kind { - if name, ok := item.(string); ok && name != "null" { - found = append(found, name) - } - } - if len(found) == 1 { - return found[0], nil - } - } - return "", fmt.Errorf("type %v is not a single JSON type", kind) -} - -func pascal(name string) string { - var builder strings.Builder - upper := true - for _, r := range name { - if !unicode.IsLetter(r) && !unicode.IsDigit(r) { - upper = true - continue - } - if upper { - r = unicode.ToUpper(r) - upper = false +// Search and the model need prose; a tool without a description falls back to its title or name. +func description(tool *mcp.Tool) string { + for _, text := range []string{tool.Description, tool.Title} { + if text = strings.TrimSpace(text); text != "" { + return text } - builder.WriteRune(r) } - return builder.String() + return "MCP tool " + tool.Name } func execute(session *mcp.ClientSession, rpcPrefix string) codemode.ExecuteFunc { diff --git a/capability/mcpsource/mcpsource_test.go b/capability/mcpsource/mcpsource_test.go index 68dd9ec..ccb2401 100644 --- a/capability/mcpsource/mcpsource_test.go +++ b/capability/mcpsource/mcpsource_test.go @@ -10,6 +10,7 @@ import ( "github.com/mukezhz/codemode/capability" "github.com/mukezhz/codemode/codemode" + "github.com/mukezhz/codemode/codemode/sourcetest" "github.com/mukezhz/codemode/sandbox" _ "github.com/mukezhz/codemode/sandbox/goja" ) @@ -92,7 +93,7 @@ func TestImportConvertsToolsAndRestrictsThem(t *testing.T) { if !ok { t.Fatalf("capabilities = %v", byName) } - if list.Input.Fields["state"] != "string" || list.Input.Fields["limit"] != "number" { + if list.Input.Fields["state"] != "string" || list.Input.Fields["limit"] != "integer" { t.Errorf("input = %+v", list.Input) } item := list.Output.Fields["issues"] @@ -210,3 +211,11 @@ func TestOneProgramCallsHostAndImportedCapabilities(t *testing.T) { t.Fatalf("value = %v", value) } } + +func TestSourcePassesTheContract(t *testing.T) { + source, err := Import(context.Background(), session(t), "github", "engineer") + if err != nil { + t.Fatal(err) + } + sourcetest.Run(t, source) +} diff --git a/capability/schema.go b/capability/schema.go index 629456b..305f662 100644 --- a/capability/schema.go +++ b/capability/schema.go @@ -25,6 +25,8 @@ type Capability struct { // Anything but (idempotency_level) = NO_SIDE_EFFECTS is treated as a write. ReadOnly bool `json:"read_only,omitempty"` + // A write that is held for a person to approve instead of running. + NeedsApproval bool `json:"needs_approval,omitempty"` } func (capability Capability) Unrestricted() bool { @@ -75,11 +77,13 @@ func (capability *Capability) EmbeddingText() string { } type TypeSchema struct { - Type string `json:"type"` - Fields map[string]string `json:"fields"` - Descriptions map[string]string `json:"descriptions,omitempty"` - Optional []string `json:"optional,omitempty"` - Oneofs map[string][]string `json:"oneofs,omitempty"` + Type string `json:"type"` + Fields map[string]string `json:"fields"` + Descriptions map[string]string `json:"descriptions,omitempty"` + Optional []string `json:"optional,omitempty"` + // Validate rejects input that leaves these out or sets them to null. + Required []string `json:"required,omitempty"` + Oneofs map[string][]string `json:"oneofs,omitempty"` // Set only on an enum: the names it accepts and returns. Values []string `json:"values,omitempty"` } diff --git a/capability/validate.go b/capability/validate.go new file mode 100644 index 0000000..a63623a --- /dev/null +++ b/capability/validate.go @@ -0,0 +1,247 @@ +package capability + +import ( + "bytes" + "encoding/json" + "fmt" + "math" + "slices" + "sort" + "strconv" + "strings" +) + +// Validate checks a program's input against the capability's declared shape +// before any host code sees it. Empty input and null count as {}. +func Validate(item Capability, input json.RawMessage) error { + // ponytail: a hand-built capability with no input shape (nil Fields) is not checked; every adapter sets Fields. + if item.Input.Fields == nil { + return nil + } + return ValidateValue(item.Input, item.Types, input) +} + +// ValidateValue checks data against schema, resolving named types in types. +// Errors name the path, such as items[2].id, so a model can repair the program. +func ValidateValue(schema TypeSchema, types map[string]TypeSchema, data json.RawMessage) error { + if trimmed := bytes.TrimSpace(data); len(trimmed) == 0 || string(trimmed) == "null" { + data = json.RawMessage("{}") + } + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var value any + if err := decoder.Decode(&value); err != nil { + return fmt.Errorf("input is not JSON: %w", err) + } + return validator{types: types}.object("", schema, value) +} + +type validator struct { + types map[string]TypeSchema +} + +func (check validator) object(path string, schema TypeSchema, value any) error { + fields, ok := value.(map[string]any) + if !ok { + return mismatch(path, "object "+schema.Type, value) + } + for _, name := range sortedFields(fields) { + fieldType, known := schema.Fields[name] + if !known { + return fmt.Errorf("%s: unknown field; %s has %s", join(path, name), describe(schema.Type), fieldList(schema)) + } + if fields[name] == nil { + continue + } + if err := check.value(join(path, name), fieldType, fields[name]); err != nil { + return err + } + } + for _, name := range schema.Required { + if fields[name] == nil { + return fmt.Errorf("%s: required", join(path, name)) + } + } + for _, group := range sortedFields(schema.Oneofs) { + var set []string + for _, name := range schema.Oneofs[group] { + if fields[name] != nil { + set = append(set, name) + } + } + if len(set) > 1 { + return fmt.Errorf("%s: set at most one of %s, got %s", orInput(path), strings.Join(schema.Oneofs[group], ", "), strings.Join(set, ", ")) + } + } + return nil +} + +func (check validator) value(path, neutral string, value any) error { + if element, found := strings.CutPrefix(neutral, "repeated "); found { + items, ok := value.([]any) + if !ok { + return mismatch(path, "list", value) + } + for index, item := range items { + if err := check.value(fmt.Sprintf("%s[%d]", path, index), element, item); err != nil { + return err + } + } + return nil + } + if key, element, found := mapType(neutral); found { + entries, ok := value.(map[string]any) + if !ok { + return mismatch(path, "object", value) + } + for _, name := range sortedFields(entries) { + entryPath := fmt.Sprintf("%s[%q]", path, name) + if err := mapKey(entryPath, key, name); err != nil { + return err + } + if err := check.value(entryPath, element, entries[name]); err != nil { + return err + } + } + return nil + } + + switch neutral { + case "any": + return nil + case "string", "bytes": + if _, ok := value.(string); !ok { + return mismatch(path, "string", value) + } + return nil + case "bool": + if _, ok := value.(bool); !ok { + return mismatch(path, "bool", value) + } + return nil + case "number": + if _, ok := value.(json.Number); !ok { + return mismatch(path, "number", value) + } + return nil + case "integer": + if !integer(value) { + return mismatch(path, "integer", value) + } + return nil + } + + named, known := check.types[neutral] + if !known { + return fmt.Errorf("%s: type %s is not declared", orInput(path), neutral) + } + if len(named.Values) > 0 { + text, ok := value.(string) + if !ok || !slices.Contains(named.Values, text) { + return fmt.Errorf("%s: want one of %s, got %s", orInput(path), strings.Join(named.Values, ", "), show(value)) + } + return nil + } + return check.object(path, named, value) +} + +// mapType splits "map"; a key is always a scalar, so the first separator splits it. +func mapType(neutral string) (key, value string, found bool) { + inner, found := strings.CutPrefix(neutral, "map<") + if !found { + return "", "", false + } + if inner, found = strings.CutSuffix(inner, ">"); !found { + return "", "", false + } + return strings.Cut(inner, ", ") +} + +func mapKey(path, key, name string) error { + switch key { + case "integer": + if _, err := strconv.ParseInt(name, 10, 64); err != nil { + return fmt.Errorf("%s: key must be an integer", path) + } + case "number": + if _, err := strconv.ParseFloat(name, 64); err != nil { + return fmt.Errorf("%s: key must be a number", path) + } + case "bool": + if name != "true" && name != "false" { + return fmt.Errorf("%s: key must be true or false", path) + } + } + return nil +} + +func integer(value any) bool { + number, ok := value.(json.Number) + if !ok { + return false + } + if _, err := number.Int64(); err == nil { + return true + } + float, err := number.Float64() + return err == nil && float == math.Trunc(float) && !math.IsInf(float, 0) +} + +func mismatch(path, want string, value any) error { + return fmt.Errorf("%s: want %s, got %s", orInput(path), want, show(value)) +} + +func show(value any) string { + switch value := value.(type) { + case nil: + return "null" + case string: + return strconv.Quote(value) + case json.Number: + return value.String() + case bool: + return strconv.FormatBool(value) + case []any: + return "a list" + case map[string]any: + return "an object" + } + return fmt.Sprintf("%v", value) +} + +func join(path, field string) string { + if path == "" { + return field + } + return path + "." + field +} + +func orInput(path string) string { + if path == "" { + return "input" + } + return path +} + +func describe(name string) string { + if name == "" { + return "the input" + } + return name +} + +func fieldList(schema TypeSchema) string { + if len(schema.Fields) == 0 { + return "no fields" + } + return "fields " + strings.Join(sortedFields(schema.Fields), ", ") +} + +func sortedFields[V any](values map[string]V) []string { + keys := make([]string, 0, len(values)) + for key := range values { + keys = append(keys, key) + } + sort.Strings(keys) + return keys +} diff --git a/capability/validate_test.go b/capability/validate_test.go new file mode 100644 index 0000000..6b82126 --- /dev/null +++ b/capability/validate_test.go @@ -0,0 +1,88 @@ +package capability + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestValidateRejectsWhatTheSchemaDoesNotDescribe(t *testing.T) { + item := Capability{ + Input: TypeSchema{Type: "CreateRequest", Fields: map[string]string{ + "title": "string", + "priority": "Priority", + "count": "integer", + "ratio": "number", + "done": "bool", + "tags": "repeated string", + "items": "repeated Item", + "labels": "map", + "meta": "any", + "email": "string", + "phone": "string", + }, Required: []string{"title"}, Oneofs: map[string][]string{"contact": {"email", "phone"}}}, + Types: map[string]TypeSchema{ + "Priority": {Type: "Priority", Values: []string{"low", "high"}}, + "Item": {Type: "Item", Fields: map[string]string{"id": "integer"}, Required: []string{"id"}}, + }, + } + + for _, test := range []struct{ input, want string }{ + {`{"title":"a","priority":"low","count":2,"ratio":0.5,"done":true,"tags":["x"],"items":[{"id":1}],"labels":{"k":1},"meta":[1,"x"]}`, ""}, + {`{"title":"a","count":1e2,"email":"a@b","phone":null}`, ""}, + {`{}`, "title: required"}, + {`null`, "title: required"}, + {`{"title":null}`, "title: required"}, + {`{"title":"a","nope":1}`, "nope: unknown field; CreateRequest has fields"}, + {`{"title":7}`, "title: want string, got 7"}, + {`{"title":"a","count":1.5}`, "count: want integer, got 1.5"}, + {`{"title":"a","ratio":"1"}`, `ratio: want number, got "1"`}, + {`{"title":"a","done":"yes"}`, `done: want bool, got "yes"`}, + {`{"title":"a","tags":"x"}`, `tags: want list, got "x"`}, + {`{"title":"a","items":[{"id":1},{"id":"2"}]}`, `items[1].id: want integer, got "2"`}, + {`{"title":"a","items":[{}]}`, "items[0].id: required"}, + {`{"title":"a","priority":"urgent"}`, `priority: want one of low, high, got "urgent"`}, + {`{"title":"a","labels":{"k":"v"}}`, `labels["k"]: want integer, got "v"`}, + {`{"title":"a","email":"x","phone":"y"}`, "set at most one of email, phone, got email, phone"}, + {`[]`, "input: want object CreateRequest, got a list"}, + {`{"title":`, "input is not JSON"}, + } { + err := Validate(item, json.RawMessage(test.input)) + switch { + case test.want == "" && err != nil: + t.Errorf("%s: unexpected error %v", test.input, err) + case test.want != "" && (err == nil || !strings.Contains(err.Error(), test.want)): + t.Errorf("%s: error = %v, want it to contain %q", test.input, err, test.want) + } + } +} + +func TestValidateSkipsAnInputShapeThatWasNeverDeclared(t *testing.T) { + if err := Validate(Capability{}, json.RawMessage(`{"anything":1}`)); err != nil { + t.Fatal(err) + } + empty := Capability{Input: TypeSchema{Fields: map[string]string{}}} + if err := Validate(empty, json.RawMessage(`{"anything":1}`)); err == nil { + t.Fatal("an empty declared shape accepted a field") + } +} + +func TestValidateRejectsAnUndeclaredType(t *testing.T) { + item := Capability{Input: TypeSchema{Fields: map[string]string{"x": "Missing"}}} + if err := Validate(item, json.RawMessage(`{"x":{}}`)); err == nil || !strings.Contains(err.Error(), "Missing is not declared") { + t.Fatalf("error = %v", err) + } +} + +func FuzzValidateNeverPanics(f *testing.F) { + item := Capability{ + Input: TypeSchema{Fields: map[string]string{"a": "repeated Node", "m": "map", "n": "integer"}}, + Types: map[string]TypeSchema{"Node": {Fields: map[string]string{"next": "Node", "v": "string"}}}, + } + for _, seed := range []string{`{}`, `{"a":[{"next":{"v":"x"}}]}`, `{"m":{"1":true,"x":false}}`, `{"n":1e400}`, `[`} { + f.Add(seed) + } + f.Fuzz(func(t *testing.T, input string) { + _ = Validate(item, json.RawMessage(input)) + }) +} diff --git a/codemode/codemode.go b/codemode/codemode.go index 98cfeae..e57a8d2 100644 --- a/codemode/codemode.go +++ b/codemode/codemode.go @@ -100,12 +100,19 @@ func (runtime *runtime) Execute(ctx context.Context, name string, input json.Raw if !ok { return nil, fmt.Errorf("capability %q is not registered", name) } + // Not recorded: nothing ran, so a rejected write must not stop the repair loop. + if err := capability.Validate(item, input); err != nil { + return nil, fmt.Errorf("invalid input for %s: %w", name, err) + } recorder := recorderFrom(ctx) if recorder == nil { + if item.NeedsApproval && !item.ReadOnly { + return nil, Permanent(fmt.Errorf("%s needs approval: run it through agent.Run and apply the plan", name)) + } return runtime.call(ctx, item, input) } - call := Call{Name: name, Input: input, ReadOnly: item.ReadOnly} - if recorder.Plan && !item.ReadOnly { + call := Call{Name: name, Input: input, ReadOnly: item.ReadOnly, NeedsApproval: item.NeedsApproval} + if recorder.hold(item) { call.Planned = true call.Output = json.RawMessage("{}") recorder.add(call) diff --git a/codemode/record.go b/codemode/record.go index c642fb6..b49bd7a 100644 --- a/codemode/record.go +++ b/codemode/record.go @@ -7,6 +7,8 @@ import ( "fmt" "sync" "time" + + "github.com/mukezhz/codemode/capability" ) // ErrPermanent marks an error a rewritten program cannot fix, such as a permission denial. @@ -23,7 +25,9 @@ type Call struct { Error string `json:"error,omitempty"` ReadOnly bool `json:"read_only,omitempty"` Planned bool `json:"planned,omitempty"` - Duration time.Duration `json:"duration"` + // The capability is held for approval; Planned says whether this call was. + NeedsApproval bool `json:"needs_approval,omitempty"` + Duration time.Duration `json:"duration"` err error } @@ -34,11 +38,35 @@ func (call Call) Err() error { return call.err } type Recorder struct { // Each planned write returns {} to the program. Plan bool + // Approved runs writes that need approval; set only when applying an approved plan. + Approved bool // It must not block. OnCall func(Call) - mutex sync.Mutex - calls []Call + mutex sync.Mutex + calls []Call + holding bool +} + +// hold reports whether a write is recorded instead of run. Once one write is held +// for approval, every later write is too, so the plan keeps the program's order. +func (recorder *Recorder) hold(item capability.Capability) bool { + if item.ReadOnly { + return false + } + recorder.mutex.Lock() + defer recorder.mutex.Unlock() + if item.NeedsApproval && !recorder.Approved { + recorder.holding = true + } + return recorder.Plan || recorder.holding +} + +// Pending reports whether a write is waiting for approval. +func (recorder *Recorder) Pending() bool { + recorder.mutex.Lock() + defer recorder.mutex.Unlock() + return recorder.holding } func (recorder *Recorder) add(call Call) { diff --git a/codemode/source.go b/codemode/source.go new file mode 100644 index 0000000..44d616d --- /dev/null +++ b/codemode/source.go @@ -0,0 +1,65 @@ +package codemode + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "maps" + + "github.com/mukezhz/codemode/capability" +) + +// Source is what every capability adapter produces: the capabilities, and the +// function that serves their RPCs. +type Source struct { + Registry capability.Registry + Execute ExecuteFunc + // Skipped holds definitions the adapter could not express, with the reason. + Skipped map[string]error +} + +// Combine serves several sources as one. A capability name or RPC defined twice is an error. +func Combine(sources ...Source) (Source, error) { + registries := make([]capability.Registry, len(sources)) + owner := map[string]ExecuteFunc{} + skipped := map[string]error{} + for index, source := range sources { + if source.Execute == nil { + return Source{}, fmt.Errorf("source %d has no Execute", index) + } + registries[index] = source.Registry + for _, item := range source.Registry.Capabilities { + if _, exists := owner[item.RPC]; exists { + return Source{}, fmt.Errorf("RPC %q is served by more than one source", item.RPC) + } + owner[item.RPC] = source.Execute + } + maps.Copy(skipped, source.Skipped) + } + merged, err := capability.Merge(registries...) + if err != nil { + return Source{}, err + } + return Source{ + Registry: merged, + Skipped: skipped, + Execute: func(ctx context.Context, rpc string, input json.RawMessage) (json.RawMessage, error) { + execute, ok := owner[rpc] + if !ok { + return nil, fmt.Errorf("no source serves RPC %q", rpc) + } + return execute(ctx, rpc, input) + }, + }, nil +} + +// FromSource builds the runtime for one caller: only what caller may call, +// searched by keyword. Use New for a different search. +func FromSource(source Source, caller capability.Caller) (CodeMode, error) { + if source.Execute == nil { + return nil, errors.New("source has no Execute") + } + allowed := source.Registry.For(caller) + return New(allowed, capability.Keyword(allowed), source.Execute) +} diff --git a/codemode/source_test.go b/codemode/source_test.go new file mode 100644 index 0000000..a2d2552 --- /dev/null +++ b/codemode/source_test.go @@ -0,0 +1,149 @@ +package codemode + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + + "github.com/mukezhz/codemode/capability" +) + +func source(names ...string) (Source, *[]string) { + var called []string + registry := capability.Registry{} + for _, name := range names { + registry.Capabilities = append(registry.Capabilities, capability.Capability{ + Name: name, RPC: "rpc/" + name, + Input: capability.TypeSchema{Fields: map[string]string{"id": "integer"}, Required: []string{"id"}}, + }) + } + return Source{Registry: registry, Execute: func(_ context.Context, rpc string, _ json.RawMessage) (json.RawMessage, error) { + called = append(called, rpc) + return json.RawMessage(`{}`), nil + }}, &called +} + +func TestCombineRoutesEachRPCToItsSource(t *testing.T) { + tasks, tasksCalled := source("tasks.close") + users, usersCalled := source("users.ban") + combined, err := Combine(tasks, users) + if err != nil { + t.Fatal(err) + } + for _, rpc := range []string{"rpc/tasks.close", "rpc/users.ban"} { + if _, err := combined.Execute(context.Background(), rpc, nil); err != nil { + t.Fatal(err) + } + } + if strings.Join(*tasksCalled, ",") != "rpc/tasks.close" || strings.Join(*usersCalled, ",") != "rpc/users.ban" { + t.Fatalf("tasks = %v, users = %v", *tasksCalled, *usersCalled) + } + if _, err := combined.Execute(context.Background(), "rpc/other", nil); err == nil { + t.Fatal("an RPC no source serves ran") + } + if _, err := Combine(tasks, tasks); err == nil { + t.Fatal("combined two sources serving the same RPC") + } +} + +func TestInvalidInputNeverReachesTheHost(t *testing.T) { + tasks, called := source("tasks.close") + mode, err := FromSource(tasks, capability.Caller{}) + if err != nil { + t.Fatal(err) + } + recorder := &Recorder{} + _, err = mode.Execute(WithRecorder(context.Background(), recorder), "tasks.close", json.RawMessage(`{"id":"7"}`)) + if err == nil || !strings.Contains(err.Error(), `id: want integer, got "7"`) { + t.Fatalf("err = %v", err) + } + if len(*called) != 0 || len(recorder.Calls()) != 0 || recorder.Wrote() { + t.Fatalf("called = %v, calls = %v", *called, recorder.Calls()) + } +} + +func approvalSource() (Source, *[]string) { + var called []string + return Source{ + Registry: capability.Registry{Capabilities: []capability.Capability{ + {Name: "tasks.list", RPC: "list", ReadOnly: true}, + {Name: "tasks.rename", RPC: "rename"}, + {Name: "tasks.delete", RPC: "delete", NeedsApproval: true}, + }}, + Execute: func(_ context.Context, rpc string, _ json.RawMessage) (json.RawMessage, error) { + called = append(called, rpc) + return json.RawMessage(`{"ok":true}`), nil + }, + }, &called +} + +func TestAWriteThatNeedsApprovalHoldsItAndEveryLaterWrite(t *testing.T) { + tasks, called := approvalSource() + mode, err := FromSource(tasks, capability.Caller{}) + if err != nil { + t.Fatal(err) + } + recorder := &Recorder{} + ctx := WithRecorder(context.Background(), recorder) + for _, name := range []string{"tasks.rename", "tasks.delete", "tasks.list", "tasks.rename"} { + if _, err := mode.Execute(ctx, name, nil); err != nil { + t.Fatal(err) + } + } + if strings.Join(*called, ",") != "rename,list" { + t.Fatalf("ran %v; want the first rename and the read only", *called) + } + if !recorder.Pending() { + t.Fatal("recorder does not report a pending write") + } + var held []string + for _, call := range recorder.Calls() { + if call.Planned { + held = append(held, call.Name) + } + } + if strings.Join(held, ",") != "tasks.delete,tasks.rename" { + t.Fatalf("held = %v", held) + } + + *called = nil + approved := WithRecorder(context.Background(), &Recorder{Approved: true}) + if _, err := mode.Execute(approved, "tasks.delete", nil); err != nil || strings.Join(*called, ",") != "delete" { + t.Fatalf("approved delete: err = %v, ran %v", err, *called) + } +} + +func TestAWriteThatNeedsApprovalNeverRunsWithoutARecorder(t *testing.T) { + tasks, called := approvalSource() + mode, err := FromSource(tasks, capability.Caller{}) + if err != nil { + t.Fatal(err) + } + _, err = mode.Execute(context.Background(), "tasks.delete", nil) + if !errors.Is(err, ErrPermanent) || len(*called) != 0 { + t.Fatalf("err = %v, ran %v", err, *called) + } +} + +func TestFromSourceKeepsOnlyWhatTheCallerMayCall(t *testing.T) { + open, _ := source("tasks.list") + admin, _ := source("users.ban") + admin.Registry = admin.Registry.Require("admin", func(capability.Capability) bool { return true }) + combined, err := Combine(open, admin) + if err != nil { + t.Fatal(err) + } + mode, err := FromSource(combined, capability.Caller{Roles: []string{"member"}}) + if err != nil { + t.Fatal(err) + } + if _, err := mode.Execute(context.Background(), "users.ban", json.RawMessage(`{"id":1}`)); err == nil { + t.Fatal("a member called an admin capability") + } + matches, err := mode.Search(context.Background(), "users ban tasks list", 5) + if err != nil || len(matches) != 1 || matches[0].Capability.Name != "tasks.list" { + t.Fatalf("matches = %v, err = %v", matches, err) + } +} diff --git a/codemode/sourcetest/sourcetest.go b/codemode/sourcetest/sourcetest.go new file mode 100644 index 0000000..4643026 --- /dev/null +++ b/codemode/sourcetest/sourcetest.go @@ -0,0 +1,73 @@ +// Package sourcetest is the contract every capability source passes: +// call Run from the adapter's own tests. +package sourcetest + +import ( + "context" + "strings" + "testing" + + "github.com/mukezhz/codemode/capability" + "github.com/mukezhz/codemode/codemode" +) + +var scalars = map[string]bool{"string": true, "bytes": true, "bool": true, "number": true, "integer": true, "any": true} + +func Run(t *testing.T, source codemode.Source) { + t.Helper() + if source.Execute == nil { + t.Fatal("source has no Execute") + } + if len(source.Registry.Capabilities) == 0 { + t.Fatal("source has no capabilities") + } + names, rpcs := map[string]bool{}, map[string]bool{} + for _, item := range source.Registry.Capabilities { + if names[item.Name] || rpcs[item.RPC] { + t.Errorf("%s: name or RPC %q appears twice", item.Name, item.RPC) + } + names[item.Name], rpcs[item.RPC] = true, true + if strings.TrimSpace(item.Description) == "" { + t.Errorf("%s: no description; search and the model have nothing to go on", item.Name) + } + if item.Input.Fields == nil { + t.Errorf("%s: input shape is not declared, so its input is never validated", item.Name) + } + if item.ReadOnly && item.NeedsApproval { + t.Errorf("%s: read-only and needs approval", item.Name) + } + for owner, fields := range map[string]map[string]string{"input": item.Input.Fields, "output": item.Output.Fields} { + for field, neutral := range fields { + resolve(t, item.Name+" "+owner+"."+field, neutral, item.Types) + } + } + for typeName, schema := range item.Types { + for field, neutral := range schema.Fields { + resolve(t, item.Name+" "+typeName+"."+field, neutral, item.Types) + } + } + } + if _, err := source.Execute(context.Background(), "sourcetest/no-such-rpc", nil); err == nil { + t.Error("an unknown RPC did not fail") + } +} + +func resolve(t *testing.T, path, neutral string, types map[string]capability.TypeSchema) { + t.Helper() + if element, found := strings.CutPrefix(neutral, "repeated "); found { + resolve(t, path, element, types) + return + } + if inner, found := strings.CutPrefix(neutral, "map<"); found { + if _, value, found := strings.Cut(strings.TrimSuffix(inner, ">"), ", "); found { + resolve(t, path, value, types) + return + } + } + if scalars[neutral] { + return + } + if _, declared := types[neutral]; !declared { + t.Errorf("%s: type %s is not declared", path, neutral) + } +} diff --git a/gen/codemode/codemode.pb.go b/gen/codemode/codemode.pb.go index 168f260..69e3872 100644 --- a/gen/codemode/codemode.pb.go +++ b/gen/codemode/codemode.pb.go @@ -70,6 +70,14 @@ var file_codemode_proto_extTypes = []protoimpl.ExtensionInfo{ Tag: "bytes,50002,opt,name=permissions", Filename: "codemode.proto", }, + { + ExtendedType: (*descriptorpb.MethodOptions)(nil), + ExtensionType: (*bool)(nil), + Field: 50003, + Name: "codemode.needs_approval", + Tag: "varint,50003,opt,name=needs_approval", + Filename: "codemode.proto", + }, { ExtendedType: (*descriptorpb.FieldOptions)(nil), ExtensionType: (*string)(nil), @@ -112,6 +120,11 @@ var ( // // optional string permissions = 50002; E_Permissions = &file_codemode_proto_extTypes[5] + // Holds this write, and every write after it in the same program, until a person + // approves the plan. An error on a method with idempotency_level = NO_SIDE_EFFECTS. + // + // optional bool needs_approval = 50003; + E_NeedsApproval = &file_codemode_proto_extTypes[6] ) // Extension fields to descriptorpb.FieldOptions. @@ -119,7 +132,7 @@ var ( // Unit, format, or valid values; generated Go drops proto comments, so this reaches the model. // // optional string field_description = 50000; - E_FieldDescription = &file_codemode_proto_extTypes[6] + E_FieldDescription = &file_codemode_proto_extTypes[7] ) var File_codemode_proto protoreflect.FileDescriptor @@ -132,7 +145,8 @@ const file_codemode_proto_rawDesc = "" + "\x13default_permissions\x12\x1f.google.protobuf.ServiceOptions\x18҆\x03 \x01(\tR\x12defaultPermissions:B\n" + "\vdescription\x12\x1e.google.protobuf.MethodOptions\x18І\x03 \x01(\tR\vdescription:6\n" + "\x05roles\x12\x1e.google.protobuf.MethodOptions\x18ц\x03 \x01(\tR\x05roles:B\n" + - "\vpermissions\x12\x1e.google.protobuf.MethodOptions\x18҆\x03 \x01(\tR\vpermissions:L\n" + + "\vpermissions\x12\x1e.google.protobuf.MethodOptions\x18҆\x03 \x01(\tR\vpermissions:G\n" + + "\x0eneeds_approval\x12\x1e.google.protobuf.MethodOptions\x18ӆ\x03 \x01(\bR\rneedsApproval:L\n" + "\x11field_description\x12\x1d.google.protobuf.FieldOptions\x18І\x03 \x01(\tR\x10fieldDescriptionB3Z1github.com/mukezhz/codemode/gen/codemode;codemodeb\x06proto3" var file_codemode_proto_goTypes = []any{ @@ -147,11 +161,12 @@ var file_codemode_proto_depIdxs = []int32{ 1, // 3: codemode.description:extendee -> google.protobuf.MethodOptions 1, // 4: codemode.roles:extendee -> google.protobuf.MethodOptions 1, // 5: codemode.permissions:extendee -> google.protobuf.MethodOptions - 2, // 6: codemode.field_description:extendee -> google.protobuf.FieldOptions - 7, // [7:7] is the sub-list for method output_type - 7, // [7:7] is the sub-list for method input_type - 7, // [7:7] is the sub-list for extension type_name - 0, // [0:7] is the sub-list for extension extendee + 1, // 6: codemode.needs_approval:extendee -> google.protobuf.MethodOptions + 2, // 7: codemode.field_description:extendee -> google.protobuf.FieldOptions + 8, // [8:8] is the sub-list for method output_type + 8, // [8:8] is the sub-list for method input_type + 8, // [8:8] is the sub-list for extension type_name + 0, // [0:8] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } @@ -167,7 +182,7 @@ func file_codemode_proto_init() { RawDescriptor: unsafe.Slice(unsafe.StringData(file_codemode_proto_rawDesc), len(file_codemode_proto_rawDesc)), NumEnums: 0, NumMessages: 0, - NumExtensions: 7, + NumExtensions: 8, NumServices: 0, }, GoTypes: file_codemode_proto_goTypes, diff --git a/mcpserver/mcpserver.go b/mcpserver/mcpserver.go index 37d8f21..62ac945 100644 --- a/mcpserver/mcpserver.go +++ b/mcpserver/mcpserver.go @@ -6,6 +6,7 @@ import ( "context" "errors" "fmt" + "strings" "github.com/modelcontextprotocol/go-sdk/mcp" @@ -41,6 +42,8 @@ type Call struct { Name string `json:"name"` Error string `json:"error,omitempty"` DurationMS int64 `json:"duration_ms"` + // Held for approval; it did not run. + Held bool `json:"held,omitempty"` } type RunOutput struct { @@ -122,7 +125,19 @@ func New(modeFor ModeFunc, runner sandbox.Runner, options Options) (*mcp.Server, value, err := runner.Run(codemode.WithRecorder(ctx, recorder), mode, input.Source) output := RunOutput{Value: value, Calls: []Call{}} for _, call := range recorder.Calls() { - output.Calls = append(output.Calls, Call{Name: call.Name, Error: call.Error, DurationMS: call.Duration.Milliseconds()}) + output.Calls = append(output.Calls, Call{Name: call.Name, Error: call.Error, DurationMS: call.Duration.Milliseconds(), Held: call.Planned}) + } + // ponytail: no apply_plan tool yet, so a held write is refused rather than approved here. + if err == nil && recorder.Pending() { + var held []string + for _, call := range recorder.Calls() { + if call.Planned { + held = append(held, call.Name) + } + } + message := "These writes need a person's approval and did not run: " + strings.Join(held, ", ") + + ". This server cannot approve writes; ask the user to make this change in the application." + return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: message}}}, output, nil } if err == nil { return nil, output, nil diff --git a/mcpserver/mcpserver_test.go b/mcpserver/mcpserver_test.go index c67557d..23b3fbb 100644 --- a/mcpserver/mcpserver_test.go +++ b/mcpserver/mcpserver_test.go @@ -26,7 +26,8 @@ func connect(t *testing.T, options Options) *mcp.ClientSession { Output: capability.TypeSchema{Fields: map[string]string{"todos": "repeated string"}}, } complete := capability.Capability{Name: "todos.complete", RPC: "todo.v1.TodoService/Complete", Description: "Completes a todo"} - registry := capability.Registry{Capabilities: []capability.Capability{list, complete}} + purge := capability.Capability{Name: "todos.delete", RPC: "todo.v1.TodoService/Delete", Description: "Deletes a todo", NeedsApproval: true} + registry := capability.Registry{Capabilities: []capability.Capability{list, complete, purge}} mode, err := codemode.New(registry, func(context.Context, string, int) ([]capability.Match, error) { return []capability.Match{{Capability: list}}, nil @@ -129,6 +130,15 @@ func TestRunReportsAWriteThatRanBeforeTheFailure(t *testing.T) { } } +func TestRunRefusesAWriteThatNeedsApproval(t *testing.T) { + result, text := call(t, connect(t, Options{}), "run_program", RunInput{ + Source: `codemode.execute("todos.delete", {}); codemode.execute("todos.complete", {}); return "done";`, + }) + if !result.IsError || !strings.Contains(text, "did not run: todos.delete, todos.complete") { + t.Fatalf("text = %q; a held write must not look like success", text) + } +} + func TestRunRejectsOversizedSource(t *testing.T) { result, text := call(t, connect(t, Options{MaxSourceBytes: 10}), "run_program", RunInput{Source: `return "this is too long";`}) diff --git a/proto/codemode.proto b/proto/codemode.proto index 7e8d293..2df60be 100644 --- a/proto/codemode.proto +++ b/proto/codemode.proto @@ -28,6 +28,10 @@ extend google.protobuf.MethodOptions { // Space-separated resource.action grants (read, write, delete, manage), such as "deals.write". // write implies read; deals.manage grants everything under deals. string permissions = 50002; + + // Holds this write, and every write after it in the same program, until a person + // approves the plan. An error on a method with idempotency_level = NO_SIDE_EFFECTS. + bool needs_approval = 50003; } extend google.protobuf.FieldOptions { diff --git a/registry/internal/fixturepb/gen/fixture/v1/orders.pb.go b/registry/internal/fixturepb/gen/fixture/v1/orders.pb.go index f469bff..5bd49ca 100644 --- a/registry/internal/fixturepb/gen/fixture/v1/orders.pb.go +++ b/registry/internal/fixturepb/gen/fixture/v1/orders.pb.go @@ -438,11 +438,11 @@ const file_orders_proto_rawDesc = "" + "\x06Status\x12\x16\n" + "\x12STATUS_UNSPECIFIED\x10\x00\x12\x0f\n" + "\vSTATUS_OPEN\x10\x01\x12\x12\n" + - "\x0eSTATUS_SHIPPED\x10\x022\xf8\x02\n" + + "\x0eSTATUS_SHIPPED\x10\x022\xfc\x02\n" + "\fOrderService\x12f\n" + "\x04List\x12\x1d.fixture.v1.ListOrdersRequest\x1a\x1e.fixture.v1.ListOrdersResponse\"\x1f\x82\xb5\x18\x1bLists orders, newest first.\x12[\n" + - "\x03Get\x12\x1b.fixture.v1.GetOrderRequest\x1a\x19.fixture.v1.OrderResponse\"\x1c\x82\xb5\x18\x18Returns one order by ID.\x12\x87\x01\n" + - "\x06Cancel\x12\x1b.fixture.v1.GetOrderRequest\x1a\x19.fixture.v1.OrderResponse\"E\x82\xb5\x18&Cancels an order that has not shipped.\x8a\xb5\x18\asupport\x92\xb5\x18\forders.write\x1a\x19\x82\xb5\x18\x06orders\x92\xb5\x18\vorders.readBRZPgithub.com/mukezhz/codemode/registry/internal/fixturepb/gen/fixture/v1;fixturev1b\x06proto3" + "\x03Get\x12\x1b.fixture.v1.GetOrderRequest\x1a\x19.fixture.v1.OrderResponse\"\x1c\x82\xb5\x18\x18Returns one order by ID.\x12\x8b\x01\n" + + "\x06Cancel\x12\x1b.fixture.v1.GetOrderRequest\x1a\x19.fixture.v1.OrderResponse\"I\x82\xb5\x18&Cancels an order that has not shipped.\x8a\xb5\x18\asupport\x92\xb5\x18\forders.write\x98\xb5\x18\x01\x1a\x19\x82\xb5\x18\x06orders\x92\xb5\x18\vorders.readBRZPgithub.com/mukezhz/codemode/registry/internal/fixturepb/gen/fixture/v1;fixturev1b\x06proto3" var ( file_orders_proto_rawDescOnce sync.Once diff --git a/registry/internal/fixturepb/proto/orders.proto b/registry/internal/fixturepb/proto/orders.proto index ac781b0..f7e81b0 100644 --- a/registry/internal/fixturepb/proto/orders.proto +++ b/registry/internal/fixturepb/proto/orders.proto @@ -25,6 +25,7 @@ service OrderService { option (codemode.description) = "Cancels an order that has not shipped."; option (codemode.roles) = "support"; option (codemode.permissions) = "orders.write"; + option (codemode.needs_approval) = true; } } diff --git a/registry/reflect_test.go b/registry/reflect_test.go index 56a184f..f698b51 100644 --- a/registry/reflect_test.go +++ b/registry/reflect_test.go @@ -200,4 +200,7 @@ func TestRolesAndPermissionsComeFromTheContract(t *testing.T) { if strings.Join(cancel.Roles, ",") != "support" || strings.Join(cancel.Permissions, ",") != "orders.write" { t.Errorf("orders.cancel roles=%v permissions=%v, want its own, replacing the default", cancel.Roles, cancel.Permissions) } + if !cancel.NeedsApproval || byName["orders.list"].NeedsApproval { + t.Errorf("needs approval: cancel = %v, list = %v; want only cancel", cancel.NeedsApproval, byName["orders.list"].NeedsApproval) + } } diff --git a/registry/registry.go b/registry/registry.go index f8d59fd..5dce4e2 100644 --- a/registry/registry.go +++ b/registry/registry.go @@ -48,6 +48,8 @@ func generateRegistry(files *descriptorpb.FileDescriptorSet) (Registry, error) { servicePermissionsOption, _ := customOptionNumber(files, ".codemode.default_permissions", ".google.protobuf.ServiceOptions") methodPermissionsOption, _ := customOptionNumber(files, ".codemode.permissions", ".google.protobuf.MethodOptions") + approvalOption, _ := customBoolOptionNumber(files, ".codemode.needs_approval", ".google.protobuf.MethodOptions") + fieldDescriptionOption, _ := customOptionNumber(files, ".codemode.field_description", ".google.protobuf.FieldOptions") shapes := newShapeIndex(files, fieldDescriptionOption) registry := Registry{Capabilities: []Capability{}} @@ -101,6 +103,15 @@ func generateRegistry(files *descriptorpb.FileDescriptorSet) (Registry, error) { } } + needsApproval, err := boolOption(method.GetOptions(), approvalOption) + if err != nil { + return Registry{}, fmt.Errorf("%s.%s: %w", service.GetName(), method.GetName(), err) + } + readOnly := method.GetOptions().GetIdempotencyLevel() == descriptorpb.MethodOptions_NO_SIDE_EFFECTS + if needsApproval && readOnly { + return Registry{}, fmt.Errorf("%s.%s: (codemode.needs_approval) on a NO_SIDE_EFFECTS method; only writes are held", service.GetName(), method.GetName()) + } + description = strings.TrimSpace(description) if description == "" { return Registry{}, fmt.Errorf("%s.%s: method option (codemode.description) is required", service.GetName(), method.GetName()) @@ -139,15 +150,16 @@ func generateRegistry(files *descriptorpb.FileDescriptorSet) (Registry, error) { } registry.Capabilities = append(registry.Capabilities, Capability{ - Name: name, - RPC: serviceName + "/" + method.GetName(), - Description: description, - Input: input, - Output: output, - Types: types, - Roles: roles, - Permissions: permissions, - ReadOnly: method.GetOptions().GetIdempotencyLevel() == descriptorpb.MethodOptions_NO_SIDE_EFFECTS, + Name: name, + RPC: serviceName + "/" + method.GetName(), + Description: description, + Input: input, + Output: output, + Types: types, + Roles: roles, + Permissions: permissions, + ReadOnly: readOnly, + NeedsApproval: needsApproval, }) } } @@ -177,13 +189,21 @@ func optionalRoles(options proto.Message, number protowire.Number) ([]string, er } func customOptionNumber(files *descriptorpb.FileDescriptorSet, name, extendee string) (protowire.Number, error) { + return typedOptionNumber(files, name, extendee, descriptorpb.FieldDescriptorProto_TYPE_STRING) +} + +func customBoolOptionNumber(files *descriptorpb.FileDescriptorSet, name, extendee string) (protowire.Number, error) { + return typedOptionNumber(files, name, extendee, descriptorpb.FieldDescriptorProto_TYPE_BOOL) +} + +func typedOptionNumber(files *descriptorpb.FileDescriptorSet, name, extendee string, kind descriptorpb.FieldDescriptorProto_Type) (protowire.Number, error) { for _, file := range files.File { for _, extension := range file.Extension { fullName := "." + strings.Trim(file.GetPackage()+"."+extension.GetName(), ".") if fullName != name { continue } - if extension.GetExtendee() != extendee || extension.GetType() != descriptorpb.FieldDescriptorProto_TYPE_STRING || extension.GetNumber() < 1 { + if extension.GetExtendee() != extendee || extension.GetType() != kind || extension.GetNumber() < 1 { return 0, fmt.Errorf("custom option %s has an invalid definition", name) } return protowire.Number(extension.GetNumber()), nil @@ -229,6 +249,51 @@ func stringOption(options proto.Message, number protowire.Number) (string, error return value, nil } +// Like stringOption, for a bool; an option that is not defined reads as false. +func boolOption(options proto.Message, number protowire.Number) (bool, error) { + if options == nil || number == 0 { + return false, nil + } + resolved := false + proto.RangeExtensions(options, func(extension protoreflect.ExtensionType, current any) bool { + if extension.TypeDescriptor().Number() == protoreflect.FieldNumber(number) { + resolved, _ = current.(bool) + return false + } + return true + }) + if resolved { + return true, nil + } + data := options.ProtoReflect().GetUnknown() + value := false + for len(data) > 0 { + fieldNumber, wireType, tagLength := protowire.ConsumeTag(data) + if tagLength < 0 { + return false, protowire.ParseError(tagLength) + } + data = data[tagLength:] + if fieldNumber == number { + if wireType != protowire.VarintType { + return false, fmt.Errorf("custom option %d is not a bool", number) + } + option, length := protowire.ConsumeVarint(data) + if length < 0 { + return false, protowire.ParseError(length) + } + value = option != 0 + data = data[length:] + continue + } + length := protowire.ConsumeFieldValue(fieldNumber, wireType, data) + if length < 0 { + return false, protowire.ParseError(length) + } + data = data[length:] + } + return value, nil +} + func resolvedOption(options proto.Message, number protowire.Number) string { value := "" proto.RangeExtensions(options, func(extension protoreflect.ExtensionType, current any) bool { diff --git a/registry/registry_test.go b/registry/registry_test.go index 3cccce5..997a62b 100644 --- a/registry/registry_test.go +++ b/registry/registry_test.go @@ -219,3 +219,48 @@ func TestMethodAnnotationsReplaceBothServiceDefaults(t *testing.T) { } } } + +func approvalFiles(readOnly bool) *descriptorpb.FileDescriptorSet { + serviceOptions := &descriptorpb.ServiceOptions{} + setStringOption(serviceOptions, 50000, "students") + method := &descriptorpb.MethodOptions{} + if readOnly { + method.IdempotencyLevel = descriptorpb.MethodOptions_NO_SIDE_EFFECTS.Enum() + } + unknown := protowire.AppendString(protowire.AppendTag(nil, 50000, protowire.BytesType), "Expels a student.") + unknown = protowire.AppendVarint(protowire.AppendTag(unknown, 50003, protowire.VarintType), 1) + method.ProtoReflect().SetUnknown(unknown) + + return &descriptorpb.FileDescriptorSet{File: []*descriptorpb.FileDescriptorProto{{ + Name: proto.String("codemode.proto"), + Package: proto.String("codemode"), + Extension: []*descriptorpb.FieldDescriptorProto{ + {Name: proto.String("namespace"), Number: proto.Int32(50000), Extendee: proto.String(".google.protobuf.ServiceOptions"), Type: descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum()}, + {Name: proto.String("description"), Number: proto.Int32(50000), Extendee: proto.String(".google.protobuf.MethodOptions"), Type: descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum()}, + {Name: proto.String("needs_approval"), Number: proto.Int32(50003), Extendee: proto.String(".google.protobuf.MethodOptions"), Type: descriptorpb.FieldDescriptorProto_TYPE_BOOL.Enum()}, + }, + }, { + Package: proto.String("student.v1"), + MessageType: []*descriptorpb.DescriptorProto{{Name: proto.String("Empty")}}, + Service: []*descriptorpb.ServiceDescriptorProto{{ + Name: proto.String("StudentService"), + Options: serviceOptions, + Method: []*descriptorpb.MethodDescriptorProto{ + {Name: proto.String("Expel"), InputType: proto.String(".student.v1.Empty"), OutputType: proto.String(".student.v1.Empty"), Options: method}, + }, + }}, + }}} +} + +func TestNeedsApprovalIsReadFromADescriptorSet(t *testing.T) { + registry, err := generateRegistry(approvalFiles(false)) + if err != nil { + t.Fatal(err) + } + if !registry.Capabilities[0].NeedsApproval { + t.Fatal("needs_approval was not read from unknown fields") + } + if _, err := generateRegistry(approvalFiles(true)); err == nil || !strings.Contains(err.Error(), "NO_SIDE_EFFECTS") { + t.Fatalf("a read-only method that needs approval loaded: %v", err) + } +} diff --git a/sandbox/starlark/starlark.go b/sandbox/starlark/starlark.go index 6790854..eabce51 100644 --- a/sandbox/starlark/starlark.go +++ b/sandbox/starlark/starlark.go @@ -43,8 +43,9 @@ func New(options sandbox.Options) (sandbox.Runner, error) { // starlarkTypes renders registry types as Starlark; numbers stay int-or-float because the registry merges numeric scalars. var starlarkTypes = prompt.Types{ Scalar: map[string]string{ - "number": "int|float", - "bytes": "string (base64)", + "number": "int|float", + "integer": "int", + "bytes": "string (base64)", }, List: func(element string) string { return "[" + element + "]" }, Dict: func(key, value string) string { return "{" + key + ": " + value + "}" }, diff --git a/scripts/check-consumer.sh b/scripts/check-consumer.sh index 9a467bf..176a32c 100755 --- a/scripts/check-consumer.sh +++ b/scripts/check-consumer.sh @@ -13,7 +13,7 @@ trap 'rm -rf "$work"' EXIT echo "==> core packages build with CGO_ENABLED=0" CGO_ENABLED=0 go build \ - "$root/capability" "$root/capability/pgstore" "$root/codemode" \ + "$root/capability" "$root/capability/pgstore" "$root/capability/gosource" "$root/capability/jsonschema" "$root/codemode" \ "$root/agent" "$root/llm" "$root/llm/claude" "$root/llm/openai" \ "$root/sandbox" "$root/sandbox/goja" "$root/sandbox/starlark" "$root/sandbox/lua" \ "$root/sandbox/subprocess" "$root/cmd/codemode-worker" From 3b1a4141ef945519ddffe768096f66bb22dccc60 Mon Sep 17 00:00:00 2001 From: Mukesh Kumar Chaudhary Date: Mon, 16 Nov 2026 10:11:17 +0545 Subject: [PATCH 2/7] feat: serve the todo example from typed Go functions app.Source builds the three todo capabilities with gosource; the proto path stays behind -source proto, and a test asserts both give the same answer. todo-mcp uses the Go source. --- examples/todo/README.md | 16 ++-- examples/todo/app/app.go | 132 ++++++++++++++++------------- examples/todo/app/app_test.go | 59 ++++++++++++- examples/todo/cmd/todo-mcp/main.go | 6 +- examples/todo/main.go | 24 ++++-- 5 files changed, 164 insertions(+), 73 deletions(-) diff --git a/examples/todo/README.md b/examples/todo/README.md index cd11fcd..895a1cd 100644 --- a/examples/todo/README.md +++ b/examples/todo/README.md @@ -1,9 +1,12 @@ # todo The smallest complete code-mode application: three capabilities (`todos.create`, -`todos.list`, `todos.complete`) generated from one proto file, an in-memory -store, and a model that answers a request by writing **one program** that calls -them. +`todos.list`, `todos.complete`), an in-memory store, and a model that answers a +request by writing **one program** that calls them. + +The capabilities come from typed Go functions by default (`app.Source`, built +with `gosource`). `-source proto` serves the same three from `proto/todo.proto` +instead; a test asserts both give the same answer. It runs with no API key, no database and no Docker. Start here; move to [`taskreport`](../taskreport) for a web UI, roles and a real database. @@ -11,7 +14,7 @@ It runs with no API key, no database and no Docker. Start here; move to ``` proto/todo.proto the contract: three RPCs and their descriptions gen/ generated Go, committed so `go run` needs no buf -app/ ExecuteFunc: RPC path → in-memory todo list +app/ the todo list: typed methods, Source() for Go, Execute for proto main.go the command-line demo cmd/todo-mcp/ the same app as an MCP server for Claude Code, Cursor, ... ``` @@ -154,7 +157,10 @@ index is rebuilt on every start because the registry is tiny. See ## Changing the contract -Edit `proto/todo.proto`, then from the repository root: +With the default Go source, add a method to `app.App` and a `gosource.Func` line +to `Source()`; the schema comes from its request and response structs. + +For `-source proto`, edit `proto/todo.proto`, then from the repository root: ```sh make generate diff --git a/examples/todo/app/app.go b/examples/todo/app/app.go index ff58090..490cb1e 100644 --- a/examples/todo/app/app.go +++ b/examples/todo/app/app.go @@ -8,12 +8,10 @@ import ( "fmt" "io" "strings" -) + "sync" -const ( - createRPC = "todo.v1.TodoService/Create" - listRPC = "todo.v1.TodoService/List" - completeRPC = "todo.v1.TodoService/Complete" + "github.com/mukezhz/codemode/capability/gosource" + "github.com/mukezhz/codemode/codemode" ) type Todo struct { @@ -22,27 +20,26 @@ type Todo struct { Completed bool `json:"completed"` } -type createRequest struct { - Title string `json:"title"` +type CreateRequest struct { + Title string `json:"title" desc:"what needs doing"` } -type createResponse struct { +type TodoResponse struct { Todo Todo `json:"todo"` } -type listResponse struct { +type ListRequest struct{} + +type ListResponse struct { Todos []Todo `json:"todos"` } -type completeRequest struct { - ID int64 `json:"id"` -} - -type completeResponse struct { - Todo Todo `json:"todo"` +type CompleteRequest struct { + ID int64 `json:"id" desc:"the id from todos.list"` } type App struct { + mutex sync.Mutex nextID int64 todos []Todo } @@ -51,63 +48,82 @@ func New() *App { return &App{} } +// Source serves the app from its Go types: no proto, no switch. +func (app *App) Source() (codemode.Source, error) { + return gosource.New( + gosource.Func("todos.create", "Creates a todo item with the given title.", gosource.Public(), app.Create), + gosource.Func("todos.list", "Lists all todo items and their completion state.", gosource.Public(), app.List, gosource.ReadOnly()), + gosource.Func("todos.complete", "Marks a todo item as completed by ID.", gosource.Public(), app.Complete), + ) +} + +func (app *App) Create(_ context.Context, request CreateRequest) (TodoResponse, error) { + title := strings.TrimSpace(request.Title) + if title == "" { + return TodoResponse{}, errors.New("title is required") + } + app.mutex.Lock() + defer app.mutex.Unlock() + app.nextID++ + item := Todo{ID: app.nextID, Title: title} + app.todos = append(app.todos, item) + return TodoResponse{Todo: item}, nil +} + +func (app *App) List(context.Context, ListRequest) (ListResponse, error) { + app.mutex.Lock() + defer app.mutex.Unlock() + return ListResponse{Todos: append([]Todo{}, app.todos...)}, nil +} + +func (app *App) Complete(_ context.Context, request CompleteRequest) (TodoResponse, error) { + app.mutex.Lock() + defer app.mutex.Unlock() + for index := range app.todos { + if app.todos[index].ID == request.ID { + app.todos[index].Completed = true + return TodoResponse{Todo: app.todos[index]}, nil + } + } + return TodoResponse{}, fmt.Errorf("todo %d not found", request.ID) +} + +const ( + createRPC = "todo.v1.TodoService/Create" + listRPC = "todo.v1.TodoService/List" + completeRPC = "todo.v1.TodoService/Complete" +) + +// Execute serves the proto registry's RPC paths with the same methods. +// ponytail: hand-written routing until registry.Source dispatches generated services. func (app *App) Execute(ctx context.Context, rpc string, input json.RawMessage) (json.RawMessage, error) { if err := ctx.Err(); err != nil { return nil, err } - var output any switch rpc { case createRPC: - var request createRequest - if err := decode(input, &request); err != nil { - return nil, err - } - request.Title = strings.TrimSpace(request.Title) - if request.Title == "" { - return nil, errors.New("title is required") - } - app.nextID++ - item := Todo{ID: app.nextID, Title: request.Title} - app.todos = append(app.todos, item) - output = createResponse{Todo: item} - + return serve(ctx, input, app.Create) case listRPC: - var request struct{} - if err := decode(input, &request); err != nil { - return nil, err - } - output = listResponse{Todos: append([]Todo{}, app.todos...)} - + return serve(ctx, input, app.List) case completeRPC: - var request completeRequest - if err := decode(input, &request); err != nil { - return nil, err - } - for index := range app.todos { - if app.todos[index].ID == request.ID { - app.todos[index].Completed = true - output = completeResponse{Todo: app.todos[index]} - break - } - } - if output == nil { - return nil, fmt.Errorf("todo %d not found", request.ID) - } - - default: - return nil, fmt.Errorf("RPC %q is not implemented", rpc) + return serve(ctx, input, app.Complete) } - return json.Marshal(output) + return nil, fmt.Errorf("RPC %q is not implemented", rpc) } -func decode(input []byte, target any) error { +func serve[In, Out any](ctx context.Context, input json.RawMessage, handler func(context.Context, In) (Out, error)) (json.RawMessage, error) { + var request In decoder := json.NewDecoder(bytes.NewReader(input)) decoder.DisallowUnknownFields() - if err := decoder.Decode(target); err != nil { - return fmt.Errorf("decode input: %w", err) + if err := decoder.Decode(&request); err != nil { + return nil, fmt.Errorf("decode input: %w", err) } if err := decoder.Decode(&struct{}{}); err != io.EOF { - return errors.New("decode input: expected one JSON value") + return nil, errors.New("decode input: expected one JSON value") + } + response, err := handler(ctx, request) + if err != nil { + return nil, err } - return nil + return json.Marshal(response) } diff --git a/examples/todo/app/app_test.go b/examples/todo/app/app_test.go index e42bd1f..c57b10d 100644 --- a/examples/todo/app/app_test.go +++ b/examples/todo/app/app_test.go @@ -4,6 +4,15 @@ import ( "context" "encoding/json" "testing" + + "github.com/mukezhz/codemode/capability" + "github.com/mukezhz/codemode/codemode" + "github.com/mukezhz/codemode/codemode/sourcetest" + coderegistry "github.com/mukezhz/codemode/registry" + "github.com/mukezhz/codemode/sandbox" + _ "github.com/mukezhz/codemode/sandbox/goja" + + todov1 "github.com/mukezhz/codemode/examples/todo/gen/todo/v1" ) func TestWorkflow(t *testing.T) { @@ -18,7 +27,7 @@ func TestWorkflow(t *testing.T) { if err != nil { t.Fatal(err) } - var response listResponse + var response ListResponse if err := json.Unmarshal(output, &response); err != nil { t.Fatal(err) } @@ -36,3 +45,51 @@ func TestEmptyListIsAnArray(t *testing.T) { t.Fatalf("output = %s, want an empty array so .length works", output) } } + +func TestGoSourcePassesTheContract(t *testing.T) { + source, err := New().Source() + if err != nil { + t.Fatal(err) + } + sourcetest.Run(t, source) +} + +const program = ` +codemode.execute("todos.create", { title: "Document code mode" }); +codemode.execute("todos.create", { title: "Run the Todo demo" }); +const { todos } = codemode.execute("todos.list", {}); +const pending = todos.filter(todo => !todo.completed); +const done = codemode.execute("todos.complete", { id: pending[0].id }); +return "completed " + done.todo.title + ", " + (pending.length - 1) + " left";` + +func TestGoAndProtoSourcesAnswerAlike(t *testing.T) { + runner, err := sandbox.New(sandbox.Options{}) + if err != nil { + t.Fatal(err) + } + defer runner.Close() + + fromGo, err := New().Source() + if err != nil { + t.Fatal(err) + } + registry, err := coderegistry.FromFiles(todov1.File_todo_proto) + if err != nil { + t.Fatal(err) + } + fromProto := codemode.Source{Registry: registry, Execute: New().Execute} + + for name, source := range map[string]codemode.Source{"go": fromGo, "proto": fromProto} { + mode, err := codemode.FromSource(source, capability.Caller{}) + if err != nil { + t.Fatal(err) + } + value, err := runner.Run(context.Background(), mode, program) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + if value != "completed Document code mode, 1 left" { + t.Fatalf("%s: value = %v", name, value) + } + } +} diff --git a/examples/todo/cmd/todo-mcp/main.go b/examples/todo/cmd/todo-mcp/main.go index ee2e8d1..2560bcb 100644 --- a/examples/todo/cmd/todo-mcp/main.go +++ b/examples/todo/cmd/todo-mcp/main.go @@ -12,9 +12,7 @@ import ( "github.com/mukezhz/codemode/capability" "github.com/mukezhz/codemode/codemode" "github.com/mukezhz/codemode/examples/todo/app" - todov1 "github.com/mukezhz/codemode/examples/todo/gen/todo/v1" "github.com/mukezhz/codemode/mcpserver" - coderegistry "github.com/mukezhz/codemode/registry" "github.com/mukezhz/codemode/sandbox" _ "github.com/mukezhz/codemode/sandbox/goja" @@ -31,11 +29,11 @@ func main() { } func run(ctx context.Context) error { - registry, err := coderegistry.FromFiles(todov1.File_todo_proto) + source, err := app.New().Source() if err != nil { return err } - mode, err := codemode.New(registry, capability.Keyword(registry), app.New().Execute) + mode, err := codemode.FromSource(source, capability.Caller{}) if err != nil { return err } diff --git a/examples/todo/main.go b/examples/todo/main.go index d4d18ab..7d4df25 100644 --- a/examples/todo/main.go +++ b/examples/todo/main.go @@ -34,6 +34,7 @@ func main() { model := flag.String("model", "", "model name, overriding ANTHROPIC_MODEL / OPENAI_MODEL") temperature := flag.Float64("temperature", -1, "sampling temperature; negative leaves the provider default") instructions := flag.String("instructions", "", "extra guidance appended to the system prompt") + from := flag.String("source", "go", "where capabilities come from: go (typed Go functions) or proto (todo.proto)") flag.Parse() options, err := llm.OptionsFromEnv() @@ -50,24 +51,24 @@ func main() { options.Temperature = llm.Float(*temperature) } - if err := run(context.Background(), *request, options, *instructions); err != nil { + if err := run(context.Background(), *from, *request, options, *instructions); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } -func run(ctx context.Context, request string, options llm.Options, instructions string) error { - registry, err := coderegistry.FromFiles(todov1.File_todo_proto) +func run(ctx context.Context, from, request string, options llm.Options, instructions string) error { + source, err := newSource(from) if err != nil { return err } - search, closeSearch, err := newSearch(ctx, registry) + search, closeSearch, err := newSearch(ctx, source.Registry) if err != nil { return err } defer closeSearch() - mode, err := codemode.New(registry, search, app.New().Execute) + mode, err := codemode.New(source.Registry, search, source.Execute) if err != nil { return err } @@ -101,6 +102,19 @@ func run(ctx context.Context, request string, options llm.Options, instructions return nil } +// Both sources describe the same three capabilities and give the same answers. +func newSource(from string) (codemode.Source, error) { + todos := app.New() + switch from { + case "go": + return todos.Source() + case "proto": + registry, err := coderegistry.FromFiles(todov1.File_todo_proto) + return codemode.Source{Registry: registry, Execute: todos.Execute}, err + } + return codemode.Source{}, fmt.Errorf("-source must be go or proto, not %q", from) +} + func newSearch(ctx context.Context, registry capability.Registry) (codemode.SearchFunc, func(), error) { store, err := capability.OpenStoreFromEnv(ctx) if errors.Is(err, capability.ErrNoStore) { From 768e417353299114b41c832e727cd5d3b5fa5b0d Mon Sep 17 00:00:00 2001 From: Mukesh Kumar Chaudhary Date: Mon, 16 Nov 2026 10:11:17 +0545 Subject: [PATCH 3/7] docs: lead with typed Go sources; add sources, types and approval pages The quickstart builds capabilities from Go structs, returns a typed answer and approves a write. The protobuf quickstart moves to docs/content/protobuf.md. Adds ADR 0008 and the pluggable-sources milestone. --- CHANGELOG.md | 39 ++ CLAUDE.md | 5 +- README.md | 74 ++-- docs/.vitepress/config.ts | 6 +- docs/content/approval.md | 88 +++++ docs/content/capabilities.md | 8 +- docs/content/existing-app.md | 2 +- docs/content/index.md | 80 ++-- docs/content/overview.md | 2 +- docs/content/protobuf.md | 367 ++++++++++++++++++ docs/content/quickstart.md | 362 ++++++++--------- docs/content/sources.md | 82 ++++ docs/content/types.md | 75 ++++ docs/content/writes.md | 4 + notes/decisions/0008-capability-sources.md | 61 +++ notes/milestones/2026-11-pluggable-sources.md | 247 ++++++++++++ 16 files changed, 1205 insertions(+), 297 deletions(-) create mode 100644 docs/content/approval.md create mode 100644 docs/content/protobuf.md create mode 100644 docs/content/sources.md create mode 100644 docs/content/types.md create mode 100644 notes/decisions/0008-capability-sources.md create mode 100644 notes/milestones/2026-11-pluggable-sources.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 18ff09c..9b6dd1a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,36 @@ version is 0, a minor bump may break the API. ## [Unreleased] ### Added +- `capability/gosource`: capabilities from typed Go functions. + `gosource.Func(name, description, access, func(ctx, In) (Out, error), options...)` + takes its schema from the request and response structs, decodes and encodes + for you, and needs no `switch` over RPC names. Access (`Public`, `Roles`, + `Permissions`) is a required argument; `ReadOnly` and `NeedsApproval` are options. +- `codemode.Source`, `codemode.Combine` (several sources as one, routed by RPC; + duplicates are an error) and `codemode.FromSource(source, caller)`, which + narrows to the caller and defaults to keyword search. +- Every capability call is validated against its input shape before + `ExecuteFunc` runs: unknown fields, kinds, enums, required fields and oneofs, + with errors that name the path so the model can repair the program. + `capability.Validate`, `capability.ValidateValue`. +- `capability.SchemaOf`: the neutral shape of a Go struct, following + `encoding/json`, with `desc` tags and `capability.Enum` string types. +- `TypeSchema.Required` and an `integer` kind, filled by `gosource` and + `mcpsource`. +- `agent.RunAs[T]`: the model is told `T`'s shape, the program's return value + is checked and decoded into `T`, and a mismatch is repaired like a failure. +- Approval: `Capability.NeedsApproval`, the `(codemode.needs_approval)` method + option and `gosource.NeedsApproval()`. A run holds that write and every later + one and returns `*agent.Pending`; `agent.PlanStore`, `agent.NewMemoryPlans` and + `agent.ApplyPlan(ctx, mode, store, owner, id)` apply a plan once, by ID, for its + owner. A write needing approval fails rather than runs outside `agent.Run`. +- `capability/jsonschema`: the JSON Schema converter `mcpsource` used, exported. +- `codemode/sourcetest.Run`: the contract every capability source passes. +- `examples/todo` serves its capabilities from Go functions by default; + `-source proto` keeps the proto path. +- Docs: a Go-structs quickstart, and pages for capability sources, types and + validation, and approving writes. The protobuf quickstart moved to + `docs/content/protobuf.md`. - `capability.TypeSchema` carries `descriptions`, `optional`, `oneofs`, and, on an enum, its `values`, and every dialect's prompt renders them. Protos fill them from `(codemode.field_description)`, a new field option, proto3 @@ -80,6 +110,15 @@ version is 0, a minor bump may break the API. longer tells the model about capabilities it cannot call. ### Changed +- A capability call whose input does not match the declared shape now fails + before `ExecuteFunc`. Hand-built capabilities with no input `Fields` are not + checked. +- `mcpsource` maps JSON Schema `integer` to `integer` rather than `number`, + records `required` fields, and falls back to a tool's title or name when it has + no description. `mcpsource.Source` is now an alias of `codemode.Source`. +- `agent.Apply` runs writes that need approval: applying is the approval. +- `mcpserver`'s `run_program` returns an error naming the writes held for + approval instead of reporting success. - Docs lead with integrating codemode: a five-step summary on the landing page and README, the sidebar ordered Get started → Ship it → How it works, and one pre-production checklist. Fixed stale snippets, including a Dockerfile that diff --git a/CLAUDE.md b/CLAUDE.md index e3c7a2e..033414f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,9 +6,9 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## What this is -Code mode: protobuf RPCs become capabilities a model composes inside a sandbox. The model writes one program (JS/Starlark/Lua) instead of N tool calls; the sandbox exposes only `codemode.execute(name, args)`, which calls back into Go, where the generated registry and role annotations are checked before anything runs. +Code mode: typed Go functions, protobuf RPCs or MCP tools become capabilities a model composes inside a sandbox. The model writes one program (JS/Starlark/Lua) instead of N tool calls; the sandbox exposes only `codemode.execute(name, args)`, which calls back into Go, where the generated registry and role annotations are checked before anything runs. -Flow: protos → `buf generate` (Go carries its own descriptors, so `registry.FromFiles` works at runtime) → registry → capability store/vector search picks relevant capabilities → LLM provider writes program → sandbox engine runs it → `agent/` orchestrates (with program caching and streaming). End-to-end walkthrough: `docs/content/flow.md`. +Flow: a source (typed Go functions via `capability/gosource`, protos via `buf generate` + `registry.FromFiles`, or MCP tools via `capability/mcpsource`) → `codemode.Source` → capability store/vector search picks relevant capabilities → LLM provider writes program → sandbox engine runs it, every call validated against its shape → `agent/` orchestrates (program caching, streaming, typed answers via `RunAs`, approval plans). End-to-end walkthrough: `docs/content/flow.md`. ## Ports and adapters @@ -17,6 +17,7 @@ Flow: protos → `buf generate` (Go carries its own descriptors, so `registry.Fr | `capability.Store` | `capability/sqlitestore`, `capability/pgstore` | | `program.Cache` | `program.New` (semantic), `program.NewExactCache` | | `program.Store` | `program.NewMemoryStore`, `capability/sqlitestore`, `capability/pgstore` | +| `agent.PlanStore` | `agent.NewMemoryPlans` | | `llm.Client`, `llm.Streamer` | `llm/claude`, `llm/openai` | | `sandbox.Runner` | `sandbox/goja`, `sandbox/starlark`, `sandbox/lua`, `sandbox/subprocess` | | `sandbox.Isolation` (registered) | `sandbox/subprocess` (`process`); in-process is built in | diff --git a/README.md b/README.md index 0990ffb..e466ece 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # Code Mode -Turn protobuf RPCs into capabilities a model can compose inside a sandbox. +Turn typed Go functions, protobuf RPCs or MCP tools into capabilities a model +composes inside a sandbox. Ordinary tool use makes a model work one call at a time: fifty tasks, fifty round trips, every intermediate result back through the model. Code mode has the model @@ -24,36 +25,47 @@ before anything runs. go get github.com/mukezhz/codemode ``` -Annotate a protobuf service with `(codemode.namespace)` and a -`(codemode.description)` per method, then: +The Go functions you already have are the capabilities; their structs are the +schema: ```go -full, err := registry.FromFiles(ordersv1.File_orders_v1_orders_proto) // 1. registry from generated Go - -// 2. your code: the only place that touches data -execute := func(ctx context.Context, rpc string, input json.RawMessage) (json.RawMessage, error) { - switch rpc { - case "orders.v1.OrderService/List": - return listOrders(ctx, input) - } - return nil, fmt.Errorf("RPC %q is not implemented", rpc) +type ListOrders struct { + Status string `json:"status,omitempty" desc:"only orders in this status"` } -// 3. per request: only what this caller may call -allowed := full.For(capability.Caller{Roles: user.Roles, Permissions: user.Permissions}) -mode, err := codemode.New(allowed, capability.Keyword(allowed), execute) - -// 4. model writes a program, sandbox runs it -model, err := llm.NewFromEnv() // ANTHROPIC_API_KEY or OPENAI_API_KEY -runner, err := sandbox.NewFromEnv(sandbox.Options{}) // in-process JS by default -result, err := agent.Run(ctx, mode, model, "how much have paid orders brought in?", - agent.Options{Runner: runner}) -fmt.Println(agent.Answer(result.Answer)) +// 1. your code: typed functions, the only place that touches data +source, err := gosource.New( + gosource.Func("orders.list", "Lists orders", gosource.Public(), shop.List, gosource.ReadOnly()), + gosource.Func("orders.refund", "Refunds a paid order", gosource.Roles("support"), shop.Refund, gosource.NeedsApproval()), +) + +// 2. per request: only what this caller may call +mode, err := codemode.FromSource(source, capability.Caller{Roles: user.Roles}) + +// 3. model writes a program, sandbox runs it, the answer comes back as your struct +model, err := llm.NewFromEnv() // ANTHROPIC_API_KEY or OPENAI_API_KEY +runner, err := sandbox.NewFromEnv(sandbox.Options{}) // in-process JS by default +revenue, result, err := agent.RunAs[Revenue](ctx, mode, model, "how much have paid orders brought in?", + agent.Options{Runner: runner, Plans: plans, PlanOwner: user.ID}) + +// 4. a refund waits for a person +var pending *agent.Pending +if errors.As(err, &pending) { + // show pending.Calls; on approval: + calls, err := agent.ApplyPlan(ctx, mode, plans, user.ID, pending.ID) +} ``` -Blank-import the backends you want (`llm/claude`, `sandbox/goja`, …); nothing -else is linked. [**Quickstart**](docs/content/quickstart.md) builds this as -complete files in fifteen minutes. +No codegen and no `switch` over RPC names. Every call the program makes is +validated against your structs before your function runs; a bad call goes back +to the model to fix. Access is required on every capability, so nothing is +exposed by omission. + +Already describe your API in protobuf, or have MCP servers? They are +[sources too](docs/content/sources.md), and `codemode.Combine` serves several at +once. Blank-import the backends you want (`llm/claude`, `sandbox/goja`, …); +nothing else is linked. [**Quickstart**](docs/content/quickstart.md) builds this +as complete files in ten minutes. ## Quick start @@ -95,7 +107,8 @@ limits, audit log). Both run programs in-process by default; add Full docs are a VitePress site under [`docs/`](docs/content). **Get started** -- [**Quickstart**](docs/content/quickstart.md) — an empty directory to a model answering, in eight steps +- [**Quickstart**](docs/content/quickstart.md) — an empty directory to a typed answer and an approved write, in six steps +- [Capability sources](docs/content/sources.md) — Go structs, protobuf, MCP, or several at once · [Capabilities from protobuf](docs/content/protobuf.md) - [**Integration guide**](docs/content/using-it.md) — every integration choice, explained - [Adding it to an existing app](docs/content/existing-app.md) — a CRM walked through: contract, adapter, roles, tenants, confirmed writes, and a non-Go CRM via a sidecar @@ -103,6 +116,7 @@ Full docs are a VitePress site under [`docs/`](docs/content). - [Development and production](docs/content/environments.md) · [Running the worker](docs/content/worker.md) — same binary, different isolation - [What your binary links](docs/content/dependencies.md) — the blank imports, and why - [Permissions](docs/content/permissions.md) · [Roles and tenants](docs/content/tenants.md) — roles in the contract, rows in your code +- [Types and validation](docs/content/types.md) · [Approving writes](docs/content/approval.md) - [Writes and retries](docs/content/writes.md) · [Caching programs](docs/content/caching.md) **Grow it** @@ -127,11 +141,13 @@ make docs-build # build the static site | `proto/` | `codemode.proto`: the service and method annotations (namespace, description, roles, permissions), embedded for consumers | | `registry/` | Builds a registry from linked descriptors or a Buf descriptor set; CLI in `cmd/codemode-registry/` | | `gen/` | Generated Go for `codemode.proto`. Each example generates into its own tree | -| `capability/` | Registry types and the vector index; backends in `sqlitestore/` and `pgstore/` | -| `codemode/` | The two-method public interface: `Search` and `Execute` | +| `capability/` | Registry types, validation and the vector index; backends in `sqlitestore/` and `pgstore/` | +| `capability/gosource/` | Capabilities from typed Go functions | +| `capability/mcpsource/` | Capabilities from an MCP server's tools | +| `codemode/` | The two-method public interface, `Search` and `Execute`, and `Source` / `Combine` | | `llm/` | The `Client` interface; providers in `claude/` and `openai/` | | `sandbox/` | The `Runner` interface; engines in `goja/`, `starlark/`, `lua/` | -| `agent/` | Search → prompt → model → sandbox, with a repair loop | +| `agent/` | Search → prompt → model → sandbox, with a repair loop, typed answers and approval plans | | `examples/todo/` | The smallest end-to-end example, also served over MCP | | `examples/taskreport/` | A complete app: SQLite tasks, 23 capabilities, roles, reporting | | `docs/` | The published documentation site | diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 3d71831..8093178 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -6,7 +6,7 @@ export default withMermaid( defineConfig({ title: "Code Mode", description: - "Turn protobuf RPCs into capabilities a model can compose in a sandbox.", + "Turn typed Go functions, protobuf RPCs or MCP tools into capabilities a model composes in a sandbox.", lang: "en-US", // Pages live in content/ so this directory holds only the site: the @@ -39,6 +39,8 @@ export default withMermaid( text: "Get started", items: [ { text: "Quickstart", link: "/quickstart" }, + { text: "Capability sources", link: "/sources" }, + { text: "Capabilities from protobuf", link: "/protobuf" }, { text: "Integration guide", link: "/using-it" }, { text: "Adding it to an existing app", link: "/existing-app" }, ], @@ -51,6 +53,8 @@ export default withMermaid( { text: "What your binary links", link: "/dependencies" }, { text: "Permissions", link: "/permissions" }, { text: "Roles and tenants", link: "/tenants" }, + { text: "Types and validation", link: "/types" }, + { text: "Approving writes", link: "/approval" }, { text: "Writes and retries", link: "/writes" }, { text: "Caching programs", link: "/caching" }, ], diff --git a/docs/content/approval.md b/docs/content/approval.md new file mode 100644 index 0000000..53b09aa --- /dev/null +++ b/docs/content/approval.md @@ -0,0 +1,88 @@ +# Approving writes + +Some writes should not happen until a person says yes: a refund, a delete, an +email to a customer. Mark them, and the program that calls one runs its reads, +records the write instead of making it, and returns the plan for approval. + +```go +gosource.Func("orders.refund", "Refunds a paid order by ID.", + gosource.Roles("support"), shop.Refund, gosource.NeedsApproval()) +``` + +In protobuf: + +```protobuf +rpc Refund(RefundOrderRequest) returns (RefundOrderResponse) { + option (codemode.description) = "Refunds a paid order by ID."; + option (codemode.needs_approval) = true; +} +``` + +A read cannot need approval; declaring both is an error when the source is built. + +## The flow + +```go +plans := agent.NewMemoryPlans(0) // once, at startup + +_, err := agent.Run(ctx, mode, model, request, agent.Options{ + Runner: runner, Plans: plans, PlanOwner: user.ID, +}) +var pending *agent.Pending +if errors.As(err, &pending) { + // show pending.Calls; send pending.ID to the client +} + +// later, when the same user approves: +calls, err := agent.ApplyPlan(ctx, mode, plans, user.ID, id) +``` + +```mermaid +sequenceDiagram + participant User + participant App + participant Agent + participant Sandbox + App->>Agent: Run + Agent->>Sandbox: program + Sandbox-->>Agent: reads ran, refund recorded + Agent-->>App: *Pending{ID, Calls} + App->>User: "refund order 1?" + User->>App: approve ID + App->>Agent: ApplyPlan(ID) + Agent-->>App: calls made +``` + +## What is guaranteed + +- A write that needs approval never runs without `Apply` or `ApplyPlan`. Called + outside `agent.Run`, with no recorder, it fails with a permanent error rather + than running. +- Once a write is held, **every later write in the same program is held too**, + so the plan keeps the program's order. Writes before it have already run. +- The plan stays on the server. The client sends back only the ID, so it cannot + change what was approved. +- A plan applies once, only for its `PlanOwner`, and expires (`DefaultPlanTTL`, + 15 minutes, for the memory store). +- `ApplyPlan` takes the caller's *current* runtime: every call passes + validation, the registry and your handler's checks again, so a user who lost a + role cannot apply a plan made before. + +Without a `PlanStore`, `Pending.ID` is empty and you apply `Pending.Calls` with +`agent.Apply` yourself. + +`agent.NewMemoryPlans` keeps plans in one process. With more than one replica, +implement `agent.PlanStore` (`Save`, `Take`) on your database; `Take` must +delete the plan it returns. + +## Limits + +A held write returns `{}` to the program, so a program that uses a held write's +output — the ID of an order it just created, say — cannot plan the steps after +it accurately. Approve, then ask again. + +MCP clients cannot approve yet: `run_program` refuses a program that reaches a +write needing approval and says which writes did not run. Ask the user to make +that change in your application. + +`agent.Options.Plan` still holds *every* write, approval or not, for a dry run. diff --git a/docs/content/capabilities.md b/docs/content/capabilities.md index 407a0f9..4615cf3 100644 --- a/docs/content/capabilities.md +++ b/docs/content/capabilities.md @@ -293,10 +293,10 @@ flowchart LR path --> gotypes["generated Go
protobuf types"] ``` -The Todo application already decodes strictly into concrete Go structs and -rejects unknown fields. Once Go types are generated from the contracts, a generic -helper can give trusted Go callers typed calls while still delegating to the raw -interface. +Every call is validated against the capability's input shape before +`ExecuteFunc` runs, whatever the source, and `capability/gosource` decodes it +into your own structs, so a handler never sees a malformed request. See +[Types and validation](/types). ## Capabilities from an MCP server diff --git a/docs/content/existing-app.md b/docs/content/existing-app.md index c121239..6fa79c8 100644 --- a/docs/content/existing-app.md +++ b/docs/content/existing-app.md @@ -212,7 +212,7 @@ message PipelineReport { } ``` -Generate it the way the [Quickstart](/quickstart#_4-generate-go) does, with +Generate it the way the [Quickstart](/protobuf#_4-generate-go) does, with `codemode.proto` excluded from generation and from lint: ```yaml diff --git a/docs/content/index.md b/docs/content/index.md index 41e6034..ebff146 100644 --- a/docs/content/index.md +++ b/docs/content/index.md @@ -5,8 +5,9 @@ hero: name: Code Mode text: The model writes a program, not a call tagline: > - Turn protobuf RPCs into capabilities a model can compose inside a sandbox. - Fifty tasks become one model turn, and a registry decides what may actually run. + Turn your typed Go functions, protobuf RPCs or MCP tools into capabilities a + model composes inside a sandbox. Fifty tasks become one model turn, and a + registry decides what may actually run. actions: - theme: brand text: Quickstart @@ -34,11 +35,16 @@ features: An RPC declares which roles or permissions may call it. Each request, pass what the caller holds, fixed roles or ones an admin created at runtime, and the capability is withheld from what runs and from the prompt at once. - - title: Generated from your contracts + - title: Typed at both ends details: > - Annotate a protobuf service with a namespace and a description per method. - The registry, the schemas, and the model-facing declarations all fall out of - make generate. + The schema comes from your Go structs, protos or JSON Schema. Every call is + validated before your handler runs, and agent.RunAs returns the answer as + your struct. A mismatch goes back to the model to fix. + - title: A person approves the risky writes + details: > + Mark a write NeedsApproval and the program records it instead of running it. + Show the plan, apply it by ID once, and the client never touches what was + approved. - title: In-process to container, one setting details: > JavaScript, Starlark, or Lua, run in your process while you develop and in a @@ -64,69 +70,45 @@ features: ## Use it in your app -Five steps take an application from protobuf contracts to a model answering -questions against them. Only step 3 is code nobody can write for you. +Three steps take the Go functions you already have to a model answering +questions with them. ```mermaid flowchart LR - a["1 annotate
.proto"] --> b["2 registry
FromFiles"] - b --> c["3 execute
your code"] - c --> d["4 per caller
For(Caller)"] - d --> e["5 run
agent.Run"] -``` - -**1. Annotate the contract.** A namespace on the service, a description on each -method. That is all a model will ever read about it. - -```proto -service OrderService { - option (codemode.namespace) = "orders"; - rpc List(ListRequest) returns (ListResponse) { - option (codemode.description) = "Lists orders, optionally filtered by status."; - } -} -``` - -**2. Derive the registry** from the generated Go. No file to keep in sync. - -```go -full, err := registry.FromFiles(ordersv1.File_orders_v1_orders_proto) + a["1 define
gosource.Func"] --> b["2 per caller
FromSource"] + b --> c["3 run
agent.RunAs"] ``` -**3. Write `ExecuteFunc`.** It receives an RPC path and JSON input, and calls -your service layer the way your HTTP handlers already do. +**1. Define capabilities from typed functions.** The structs are the schema; +access is required, and writes can wait for a person. ```go -func execute(ctx context.Context, rpc string, input json.RawMessage) (json.RawMessage, error) { - switch rpc { - case "orders.v1.OrderService/List": - return listOrders(ctx, input) // identity comes from ctx, never from input - } - return nil, fmt.Errorf("RPC %q is not implemented", rpc) -} +source, err := gosource.New( + gosource.Func("orders.list", "Lists orders, optionally only those in one status.", + gosource.Public(), shop.List, gosource.ReadOnly()), + gosource.Func("orders.refund", "Refunds a paid order by ID.", + gosource.Roles("support"), shop.Refund, gosource.NeedsApproval()), +) ``` -**4. Narrow to the caller, per request.** What they may not call is withheld +**2. Narrow to the caller, per request.** What they may not call is withheld from the prompt and refused at run time. ```go -allowed := full.For(capability.Caller{Roles: user.Roles, Permissions: user.Permissions}) -mode, err := codemode.New(allowed, capability.Keyword(allowed), execute) +mode, err := codemode.FromSource(source, capability.Caller{Roles: user.Roles}) ``` -**5. Run a request.** +**3. Run a request, and get a struct back.** ```go -result, err := agent.Run(ctx, mode, model, "how much have paid orders brought in?", - agent.Options{Runner: runner}) -fmt.Println(agent.Answer(result.Answer)) +revenue, result, err := agent.RunAs[Revenue](ctx, mode, model, + "how much have paid orders brought in?", agent.Options{Runner: runner}) ``` `model` comes from `llm.NewFromEnv()` and `runner` from `sandbox.NewFromEnv(sandbox.Options{})`. The [Quickstart](/quickstart) builds all -of this as complete files in fifteen minutes; the [Integration guide](/using-it) -explains every choice; [Adding it to an existing app](/existing-app) walks a real -CRM through it. +of this as complete files in ten minutes. Already have protos or MCP servers? +See [Capability sources](/sources). ## In one screen diff --git a/docs/content/overview.md b/docs/content/overview.md index a73fc47..3e173d5 100644 --- a/docs/content/overview.md +++ b/docs/content/overview.md @@ -102,7 +102,7 @@ go run ./examples/taskreport -serve :8080 ## Where to go next -- [Quickstart](/quickstart) — an empty directory to a model answering, in eight steps. +- [Quickstart](/quickstart) — an empty directory to a model answering, in six steps. - [Integration guide](/using-it) — every integration choice, explained. - [Adding it to an existing app](/existing-app) — a real CRM, start to finish. - [Architecture](/architecture) — packages, ports, the request lifecycle, trust boundaries. diff --git a/docs/content/protobuf.md b/docs/content/protobuf.md new file mode 100644 index 0000000..5cb284d --- /dev/null +++ b/docs/content/protobuf.md @@ -0,0 +1,367 @@ +# Capabilities from protobuf + +The [quickstart](/quickstart) builds capabilities from Go structs. If your API +is already described in protobuf, the protos can be the source instead: the +registry is read out of the generated Go, and roles, permissions, reads and +approval are declared in the contract. Every file below is complete; copy them +as they are. + +You will build a tiny shop with two capabilities, `orders.list` and +`orders.refund`, and ask: *"how much have paid orders brought in, and who is the +biggest customer?"* + +``` +shop/ +├── buf.yaml +├── buf.gen.yaml +├── proto/ +│ ├── codemode.proto ← copied from the library, step 2 +│ └── orders/v1/orders.proto ← your contract, step 3 +├── gen/ ← generated, step 4 +└── main.go ← your application, step 5 +``` + +You need Go and [buf](https://buf.build/docs/installation). No database, no +Docker, and an API key only for the last step. + +## 1. Create the module + +```sh +mkdir shop && cd shop +go mod init example.com/shop +go get github.com/mukezhz/codemode@latest +``` + +## 2. Copy the annotations + +Two protobuf options mark a service as something a model may call. The library +prints the file that matches its version: + +```sh +mkdir -p proto/orders/v1 +go run github.com/mukezhz/codemode/cmd/codemode-registry -print-proto > proto/codemode.proto +``` + +## 3. Write the contract + +`proto/orders/v1/orders.proto`: + +```protobuf +syntax = "proto3"; + +package orders.v1; + +import "codemode.proto"; + +option go_package = "example.com/shop/gen/orders/v1;ordersv1"; + +service OrderService { + option (codemode.namespace) = "orders"; + + rpc List(ListOrdersRequest) returns (ListOrdersResponse) { + option idempotency_level = NO_SIDE_EFFECTS; + option (codemode.description) = "Lists orders, optionally only those with the given status: pending, paid or refunded."; + } + + rpc Refund(RefundOrderRequest) returns (RefundOrderResponse) { + option (codemode.description) = "Refunds a paid order by ID."; + option (codemode.roles) = "support admin"; + } +} + +message Order { + int64 id = 1; + string customer = 2; + string status = 3; + double total = 4; +} + +message ListOrdersRequest { + string status = 1; +} + +message ListOrdersResponse { + repeated Order orders = 1; +} + +message RefundOrderRequest { + int64 id = 1; +} + +message RefundOrderResponse { + Order order = 1; +} +``` + +What each line is for: + +- `(codemode.namespace) = "orders"` + the method name gives the capability name + the model calls: `orders.list`, `orders.refund`. +- `(codemode.description)` is the **only** prose the model reads about the call, + and what search matches on. Write it for someone who has never seen your code. +- `(codemode.roles) = "support admin"`: only callers with one of those roles get + `orders.refund` at all. See [Permissions](/permissions#several-roles-on-one-rpc-or-service). +- `idempotency_level = NO_SIDE_EFFECTS` marks a read. Everything else is treated + as a write, which matters for [retries and plans](/writes). +- `option (codemode.needs_approval) = true` on a write holds it for a person to + approve before it runs. See [Approving writes](/approval). + +## 4. Generate Go + +`buf.yaml`: + +```yaml +version: v2 +modules: + - path: proto +lint: + use: + - STANDARD + except: + - RPC_REQUEST_STANDARD_NAME + - RPC_RESPONSE_STANDARD_NAME + - RPC_REQUEST_RESPONSE_UNIQUE + ignore: + - proto/codemode.proto +``` + +`ignore` keeps `buf lint` off the library's file. The three exceptions are +optional: they let request and response types be named for what they hold +(`ListOrdersRequest`, a shared `Order`), which reads better in the prompt. + +`buf.gen.yaml`: + +```yaml +version: v2 +inputs: + - directory: proto + exclude_paths: + - proto/codemode.proto +plugins: + - remote: buf.build/protocolbuffers/go:v1.36.11 + out: gen + opt: paths=source_relative +``` + +```sh +buf generate +``` + +This writes `gen/orders/v1/orders.pb.go`. `codemode.proto` is excluded on +purpose: its Go code already ships inside the library, and your generated file +imports it from there. + +## 5. Write the application + +`main.go`: + +```go +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log" + "os" + + "github.com/mukezhz/codemode/agent" + "github.com/mukezhz/codemode/capability" + "github.com/mukezhz/codemode/codemode" + "github.com/mukezhz/codemode/llm" + "github.com/mukezhz/codemode/registry" + "github.com/mukezhz/codemode/sandbox" + + _ "github.com/mukezhz/codemode/llm/claude" + _ "github.com/mukezhz/codemode/llm/openai" + _ "github.com/mukezhz/codemode/sandbox/goja" + _ "github.com/mukezhz/codemode/sandbox/subprocess" + + ordersv1 "example.com/shop/gen/orders/v1" +) + +// execute is your application: the only code that touches real data. +// ponytail: hand-written routing; the Go-structs source in the quickstart needs none. +func execute(ctx context.Context, rpc string, input json.RawMessage) (json.RawMessage, error) { + switch rpc { + case "orders.v1.OrderService/List": + var request struct { + Status string `json:"status"` + } + if err := json.Unmarshal(input, &request); err != nil { + return nil, err + } + orders := []map[string]any{} + for _, order := range []map[string]any{ + {"id": 1, "customer": "ada", "status": "paid", "total": 42.5}, + {"id": 2, "customer": "linus", "status": "pending", "total": 10}, + {"id": 3, "customer": "grace", "status": "paid", "total": 99}, + } { + if request.Status == "" || order["status"] == request.Status { + orders = append(orders, order) + } + } + return json.Marshal(map[string]any{"orders": orders}) + } + return nil, fmt.Errorf("RPC %q is not implemented", rpc) +} + +func main() { + ctx := context.Background() + + full, err := registry.FromFiles(ordersv1.File_orders_v1_orders_proto) + if err != nil { + log.Fatal(err) + } + allowed := full.ForRole("customer") // in your app: full.For(capability.Caller{...}) per request + mode, err := codemode.New(allowed, capability.Keyword(allowed), execute) + if err != nil { + log.Fatal(err) + } + runner, err := sandbox.NewFromEnv(sandbox.Options{}) + if err != nil { + log.Fatal(err) + } + defer runner.Close() + + model, err := llm.NewFromEnv() + if err != nil && !errors.Is(err, llm.ErrNoProvider) { + log.Fatal(err) + } + if model == nil { + // No API key: run a hand-written program so you can see the sandbox work. + value, err := runner.Run(ctx, mode, ` + const { orders } = codemode.execute("orders.list", { status: "paid" }); + const total = orders.reduce((sum, order) => sum + order.total, 0); + return orders.length + " paid orders, " + total + " in total";`) + if err != nil { + log.Fatal(err) + } + fmt.Println(value) + return + } + + request := "how much have paid orders brought in, and who is the biggest customer?" + if len(os.Args) > 1 { + request = os.Args[1] + } + result, err := agent.Run(ctx, mode, model, request, agent.Options{Runner: runner}) + if err != nil { + log.Fatal(err) + } + fmt.Printf("program:\n%s\n\nanswer: %s\n", result.Source, agent.Answer(result.Answer)) +} +``` + +The five things it does, in order: + +| Line | What it is | +| --- | --- | +| `registry.FromFiles(...)` | reads the capabilities out of the generated code. Nothing to keep in sync. | +| `full.ForRole("customer")` | this caller's allowlist. `orders.refund` needs `support` or `admin`, so it is not in it. In a real app, pass what you fetch for the signed-in user: `full.For(capability.Caller{Roles: ..., Permissions: ...})`. See [Roles and permissions](/permissions#roles-and-permissions). | +| `capability.Keyword(allowed)` | search with no database. Switch to a [vector index](/search) later. | +| `execute` | **your code**: the only place that touches data. The program never sees it. | +| `agent.Run` | search → prompt → model writes a program → sandbox runs it → answer. | + +## 6. Run it without a key + +```sh +go mod tidy +go run . +``` + +``` +2 paid orders, 141.5 in total +``` + +No model was involved: `main.go` ran a hand-written program so you can see the +sandbox, the registry and `execute` work before spending a token. + +## 7. Let a model write the program + +```sh +export ANTHROPIC_API_KEY=sk-ant-... +go run . +``` + +Or any OpenAI-compatible endpoint: + +```sh +export OPENAI_API_KEY=sk-... +export OPENAI_BASE_URL=https://api.deepseek.com/v1 # omit for OpenAI +export OPENAI_MODEL=deepseek-chat +go run . +``` + +``` +program: +const { orders } = codemode.execute("orders.list", { status: "paid" }); +if (orders.length === 0) { + return "no paid orders yet"; +} +const revenue = orders.reduce((sum, order) => sum + order.total, 0); +const byCustomer = {}; +for (const order of orders) { + byCustomer[order.customer] = (byCustomer[order.customer] || 0) + order.total; +} +let topCustomer = null; +let topTotal = -Infinity; +for (const name of Object.keys(byCustomer)) { + if (byCustomer[name] > topTotal) { + topTotal = byCustomer[name]; + topCustomer = name; + } +} +return "Paid orders brought in " + revenue + "; biggest customer is " + topCustomer + " (" + topTotal + ")"; + +answer: Paid orders brought in 141.5; biggest customer is grace (99) +``` + +The program differs a little from run to run; the answer should not. + +One model call. The model wrote a program that fetched, filtered, summed and +ranked; only the final sentence came back. Ask something else: + +```sh +go run . "list pending orders and their customers" +go run . "refund order 1" +``` + +The second one is worth running. The caller is a `customer`, so `orders.refund` +is not in their registry: not in the prompt, and not callable. The model works +with what it has: + +``` +answer: order 1: ada, 42.5, status paid (no refund capability is available, so nothing was changed) +``` + +Change `ForRole("customer")` to `ForRole("support")` and the same request +refunds, once you add a `Refund` case to `execute`. + +## 8. Run programs out of process + +So far every program ran inside your process, which is what you want while +developing. For production, run them in `codemode-worker`: + +```sh +go get -tool github.com/mukezhz/codemode/cmd/codemode-worker # pins it to your codemode version +go install github.com/mukezhz/codemode/cmd/codemode-worker # puts it on PATH ($GOBIN) +SANDBOX_ISOLATION=process go run . +``` + +Nothing in `main.go` changes. `sandbox.NewFromEnv` reads the setting, starts a +worker once to check it works, and runs every program in a fresh child process +with a memory cap and no access to your environment. See +[Running the worker](/worker). + +## Where next + +| You want to | Read | +| --- | --- | +| add it to an app you already have (a CRM, say) | [Adding it to an existing app](/existing-app) | +| understand how the pieces fit | [Architecture](/architecture) | +| connect a real backend, gRPC or your services | [Add it to your application](/using-it#_3-write-executefunc) | +| scope data per user, roles, tenants | [Roles and tenants](/tenants) | +| configure the same binary for dev and prod | [Development and production](/environments) | +| expose it to Claude Code or Cursor | [Serving MCP clients](/mcp) | diff --git a/docs/content/quickstart.md b/docs/content/quickstart.md index 504c0d4..d1006f0 100644 --- a/docs/content/quickstart.md +++ b/docs/content/quickstart.md @@ -1,26 +1,16 @@ # Quickstart -Fifteen minutes from an empty directory to a model answering a question by -writing a program against your own API. Every file below is complete; copy them -as they are. +Ten minutes from an empty directory to a model answering a question by writing a +program against your own Go functions. No protobuf, no code generation, no +`switch` over RPC names: the functions you already have, typed, are the +capabilities. You will build a tiny shop with two capabilities, `orders.list` and `orders.refund`, and ask: *"how much have paid orders brought in, and who is the -biggest customer?"* +biggest customer?"* You will get the answer back as a Go struct, and the refund +will wait for you to approve it. -``` -shop/ -├── buf.yaml -├── buf.gen.yaml -├── proto/ -│ ├── codemode.proto ← copied from the library, step 2 -│ └── orders/v1/orders.proto ← your contract, step 3 -├── gen/ ← generated, step 4 -└── main.go ← your application, step 5 -``` - -You need Go and [buf](https://buf.build/docs/installation). No database, no -Docker, and an API key only for the last step. +You need Go. No database, no Docker, and an API key only for step 4. ## 1. Create the module @@ -30,124 +20,7 @@ go mod init example.com/shop go get github.com/mukezhz/codemode@latest ``` -## 2. Copy the annotations - -Two protobuf options mark a service as something a model may call. The library -prints the file that matches its version: - -```sh -mkdir -p proto/orders/v1 -go run github.com/mukezhz/codemode/cmd/codemode-registry -print-proto > proto/codemode.proto -``` - -## 3. Write the contract - -`proto/orders/v1/orders.proto`: - -```protobuf -syntax = "proto3"; - -package orders.v1; - -import "codemode.proto"; - -option go_package = "example.com/shop/gen/orders/v1;ordersv1"; - -service OrderService { - option (codemode.namespace) = "orders"; - - rpc List(ListOrdersRequest) returns (ListOrdersResponse) { - option idempotency_level = NO_SIDE_EFFECTS; - option (codemode.description) = "Lists orders, optionally only those with the given status: pending, paid or refunded."; - } - - rpc Refund(RefundOrderRequest) returns (RefundOrderResponse) { - option (codemode.description) = "Refunds a paid order by ID."; - option (codemode.roles) = "support admin"; - } -} - -message Order { - int64 id = 1; - string customer = 2; - string status = 3; - double total = 4; -} - -message ListOrdersRequest { - string status = 1; -} - -message ListOrdersResponse { - repeated Order orders = 1; -} - -message RefundOrderRequest { - int64 id = 1; -} - -message RefundOrderResponse { - Order order = 1; -} -``` - -What each line is for: - -- `(codemode.namespace) = "orders"` + the method name gives the capability name - the model calls: `orders.list`, `orders.refund`. -- `(codemode.description)` is the **only** prose the model reads about the call, - and what search matches on. Write it for someone who has never seen your code. -- `(codemode.roles) = "support admin"`: only callers with one of those roles get - `orders.refund` at all. See [Permissions](/permissions#several-roles-on-one-rpc-or-service). -- `idempotency_level = NO_SIDE_EFFECTS` marks a read. Everything else is treated - as a write, which matters for [retries and plans](/writes). - -## 4. Generate Go - -`buf.yaml`: - -```yaml -version: v2 -modules: - - path: proto -lint: - use: - - STANDARD - except: - - RPC_REQUEST_STANDARD_NAME - - RPC_RESPONSE_STANDARD_NAME - - RPC_REQUEST_RESPONSE_UNIQUE - ignore: - - proto/codemode.proto -``` - -`ignore` keeps `buf lint` off the library's file. The three exceptions are -optional: they let request and response types be named for what they hold -(`ListOrdersRequest`, a shared `Order`), which reads better in the prompt. - -`buf.gen.yaml`: - -```yaml -version: v2 -inputs: - - directory: proto - exclude_paths: - - proto/codemode.proto -plugins: - - remote: buf.build/protocolbuffers/go:v1.36.11 - out: gen - opt: paths=source_relative -``` - -```sh -buf generate -``` - -This writes `gen/orders/v1/orders.pb.go`. `codemode.proto` is excluded on -purpose: its Go code already ships inside the library, and your generated file -imports it from there. - -## 5. Write the application +## 2. Write the application `main.go`: @@ -156,7 +29,6 @@ package main import ( "context" - "encoding/json" "errors" "fmt" "log" @@ -164,53 +36,93 @@ import ( "github.com/mukezhz/codemode/agent" "github.com/mukezhz/codemode/capability" + "github.com/mukezhz/codemode/capability/gosource" "github.com/mukezhz/codemode/codemode" "github.com/mukezhz/codemode/llm" - "github.com/mukezhz/codemode/registry" "github.com/mukezhz/codemode/sandbox" _ "github.com/mukezhz/codemode/llm/claude" _ "github.com/mukezhz/codemode/llm/openai" _ "github.com/mukezhz/codemode/sandbox/goja" _ "github.com/mukezhz/codemode/sandbox/subprocess" - - ordersv1 "example.com/shop/gen/orders/v1" ) -// execute is your application: the only code that touches real data. -func execute(ctx context.Context, rpc string, input json.RawMessage) (json.RawMessage, error) { - switch rpc { - case "orders.v1.OrderService/List": - var request struct { - Status string `json:"status"` - } - if err := json.Unmarshal(input, &request); err != nil { - return nil, err +type Status string + +func (Status) Enum() []string { return []string{"pending", "paid", "refunded"} } + +type Order struct { + ID int64 `json:"id"` + Customer string `json:"customer"` + Status Status `json:"status"` + Total float64 `json:"total"` +} + +type ListOrders struct { + Status Status `json:"status,omitempty" desc:"only orders in this status; leave out for all"` +} + +type Orders struct { + Orders []Order `json:"orders"` +} + +type RefundOrder struct { + ID int64 `json:"id" desc:"the id from orders.list"` +} + +type OrderResult struct { + Order Order `json:"order"` +} + +// Shop is your application: the only code that touches real data. +type Shop struct { + orders []Order +} + +func (shop *Shop) List(_ context.Context, request ListOrders) (Orders, error) { + var found []Order + for _, order := range shop.orders { + if request.Status == "" || order.Status == request.Status { + found = append(found, order) } - orders := []map[string]any{} - for _, order := range []map[string]any{ - {"id": 1, "customer": "ada", "status": "paid", "total": 42.5}, - {"id": 2, "customer": "linus", "status": "pending", "total": 10}, - {"id": 3, "customer": "grace", "status": "paid", "total": 99}, - } { - if request.Status == "" || order["status"] == request.Status { - orders = append(orders, order) - } + } + return Orders{Orders: found}, nil +} + +func (shop *Shop) Refund(_ context.Context, request RefundOrder) (OrderResult, error) { + for index := range shop.orders { + if shop.orders[index].ID == request.ID && shop.orders[index].Status == "paid" { + shop.orders[index].Status = "refunded" + return OrderResult{Order: shop.orders[index]}, nil } - return json.Marshal(map[string]any{"orders": orders}) } - return nil, fmt.Errorf("RPC %q is not implemented", rpc) + return OrderResult{}, fmt.Errorf("no paid order %d", request.ID) +} + +type Revenue struct { + Total float64 `json:"total"` + TopCustomer string `json:"top_customer"` } func main() { ctx := context.Background() - - full, err := registry.FromFiles(ordersv1.File_orders_v1_orders_proto) + shop := &Shop{orders: []Order{ + {ID: 1, Customer: "ada", Status: "paid", Total: 42.5}, + {ID: 2, Customer: "linus", Status: "pending", Total: 10}, + {ID: 3, Customer: "grace", Status: "paid", Total: 99}, + }} + + source, err := gosource.New( + gosource.Func("orders.list", "Lists orders, optionally only those in one status.", + gosource.Public(), shop.List, gosource.ReadOnly()), + gosource.Func("orders.refund", "Refunds a paid order by ID.", + gosource.Roles("support"), shop.Refund, gosource.NeedsApproval()), + ) if err != nil { log.Fatal(err) } - allowed := full.ForRole("customer") // in your app: full.For(capability.Caller{...}) per request - mode, err := codemode.New(allowed, capability.Keyword(allowed), execute) + caller := capability.Caller{Roles: []string{"support"}} // in your app: the signed-in user's roles + mode, err := codemode.FromSource(source, caller) if err != nil { log.Fatal(err) } @@ -221,10 +133,7 @@ func main() { defer runner.Close() model, err := llm.NewFromEnv() - if err != nil && !errors.Is(err, llm.ErrNoProvider) { - log.Fatal(err) - } - if model == nil { + if errors.Is(err, llm.ErrNoProvider) { // No API key: run a hand-written program so you can see the sandbox work. value, err := runner.Run(ctx, mode, ` const { orders } = codemode.execute("orders.list", { status: "paid" }); @@ -236,30 +145,67 @@ func main() { fmt.Println(value) return } + if err != nil { + log.Fatal(err) + } - request := "how much have paid orders brought in, and who is the biggest customer?" if len(os.Args) > 1 { - request = os.Args[1] + refund(ctx, mode, model, runner, os.Args[1]) + return + } + revenue, result, err := agent.RunAs[Revenue](ctx, mode, model, + "how much have paid orders brought in, and who is the biggest customer?", agent.Options{Runner: runner}) + if err != nil { + log.Fatal(err) + } + fmt.Printf("program:\n%s\n\n%.2f in total, biggest customer %s\n", result.Source, revenue.Total, revenue.TopCustomer) +} + +func refund(ctx context.Context, mode codemode.CodeMode, model llm.Client, runner sandbox.Runner, request string) { + plans := agent.NewMemoryPlans(0) + _, err := agent.Run(ctx, mode, model, request, agent.Options{Runner: runner, Plans: plans, PlanOwner: "you"}) + var pending *agent.Pending + if !errors.As(err, &pending) { + fmt.Println("nothing needed approval:", err) + return } - result, err := agent.Run(ctx, mode, model, request, agent.Options{Runner: runner}) + for _, call := range pending.Calls { + fmt.Printf("wants to run %s %s\n", call.Name, call.Input) + } + fmt.Print("approve? [y/N] ") + var answer string + fmt.Scanln(&answer) + if answer != "y" { + fmt.Println("nothing changed") + return + } + calls, err := agent.ApplyPlan(ctx, mode, plans, "you", pending.ID) if err != nil { log.Fatal(err) } - fmt.Printf("program:\n%s\n\nanswer: %s\n", result.Source, agent.Answer(result.Answer)) + fmt.Printf("ran %d call(s)\n", len(calls)) } ``` -The five things it does, in order: +What it does, in order: -| Line | What it is | +| Code | What it is | | --- | --- | -| `registry.FromFiles(...)` | reads the capabilities out of the generated code. Nothing to keep in sync. | -| `full.ForRole("customer")` | this caller's allowlist. `orders.refund` needs `support` or `admin`, so it is not in it. In a real app, pass what you fetch for the signed-in user: `full.For(capability.Caller{Roles: ..., Permissions: ...})`. See [Roles and permissions](/permissions#roles-and-permissions). | -| `capability.Keyword(allowed)` | search with no database. Switch to a [vector index](/search) later. | -| `execute` | **your code**: the only place that touches data. The program never sees it. | -| `agent.Run` | search → prompt → model writes a program → sandbox runs it → answer. | - -## 6. Run it without a key +| `type ListOrders struct`, `type Orders struct` | the contract. The model sees these shapes; `desc` tags are the prose it reads about a field. Fields follow `encoding/json`: `omitempty` or a pointer makes one optional, every other field is required. | +| `func (Status) Enum()` | a string type that accepts only these values, in the prompt and at the boundary. | +| `gosource.Func(name, description, access, handler)` | one capability. The description is what search matches and the model reads. | +| `gosource.Public()`, `gosource.Roles("support")` | who may call it. There is no default: a capability with no access does not compile into a source. | +| `gosource.ReadOnly()` | a read. Everything else is a write: never cached, never retried after it ran. | +| `gosource.NeedsApproval()` | the write waits for a person. See [Approving writes](/approval). | +| `codemode.FromSource(source, caller)` | this caller's runtime: only what they may call, searched by keyword. | +| `agent.RunAs[Revenue]` | search → prompt → model writes a program → sandbox runs it → the value is checked against `Revenue` and decoded. | + +Before your function runs, every call the program makes is checked against the +shape: a wrong type, an unknown field or a missing required field goes back to +the model as an error naming the field, and the model fixes the program. Your +handler only ever sees a valid `ListOrders`. See [Types and validation](/types). + +## 3. Run it without a key ```sh go mod tidy @@ -271,9 +217,9 @@ go run . ``` No model was involved: `main.go` ran a hand-written program so you can see the -sandbox, the registry and `execute` work before spending a token. +sandbox, the capabilities and your functions work before spending a token. -## 7. Let a model write the program +## 4. Let a model write the program ```sh export ANTHROPIC_API_KEY=sk-ant-... @@ -292,49 +238,45 @@ go run . ``` program: const { orders } = codemode.execute("orders.list", { status: "paid" }); -if (orders.length === 0) { - return "no paid orders yet"; -} -const revenue = orders.reduce((sum, order) => sum + order.total, 0); const byCustomer = {}; +let total = 0; for (const order of orders) { + total += order.total; byCustomer[order.customer] = (byCustomer[order.customer] || 0) + order.total; } -let topCustomer = null; -let topTotal = -Infinity; -for (const name of Object.keys(byCustomer)) { - if (byCustomer[name] > topTotal) { - topTotal = byCustomer[name]; - topCustomer = name; - } -} -return "Paid orders brought in " + revenue + "; biggest customer is " + topCustomer + " (" + topTotal + ")"; +const top = Object.keys(byCustomer).sort((a, b) => byCustomer[b] - byCustomer[a])[0]; +return { total: total, top_customer: top }; -answer: Paid orders brought in 141.5; biggest customer is grace (99) +141.50 in total, biggest customer grace ``` The program differs a little from run to run; the answer should not. -One model call. The model wrote a program that fetched, filtered, summed and -ranked; only the final sentence came back. Ask something else: +One model call. The model was told the shape of `Revenue`, so it returned an +object instead of a sentence; had it returned the wrong shape, it would have +been asked to fix it. + +## 5. Approve a write ```sh -go run . "list pending orders and their customers" go run . "refund order 1" ``` -The second one is worth running. The caller is a `customer`, so `orders.refund` -is not in their registry: not in the prompt, and not callable. The model works -with what it has: - ``` -answer: order 1: ada, 42.5, status paid (no refund capability is available, so nothing was changed) +wants to run orders.refund {"id":1} +approve? [y/N] y +ran 1 call(s) ``` -Change `ForRole("customer")` to `ForRole("support")` and the same request -refunds, once you add a `Refund` case to `execute`. +`orders.refund` needs approval, so the program ran its reads and *recorded* the +refund instead of making it. `agent.Run` returned `*agent.Pending`; the plan was +kept on the server under an ID, and `agent.ApplyPlan` ran it once you said yes. +Answer anything but `y` and nothing changes. + +Change the caller to `capability.Caller{Roles: []string{"customer"}}` and +`orders.refund` disappears: not in the prompt, and not callable. -## 8. Run programs out of process +## 6. Run programs out of process So far every program ran inside your process, which is what you want while developing. For production, run them in `codemode-worker`: @@ -354,9 +296,9 @@ with a memory cap and no access to your environment. See | You want to | Read | | --- | --- | +| use protos, MCP servers or several sources at once | [Capability sources](/sources) | +| hold writes for a person | [Approving writes](/approval) | +| know exactly what is checked | [Types and validation](/types) | | add it to an app you already have (a CRM, say) | [Adding it to an existing app](/existing-app) | -| understand how the pieces fit | [Architecture](/architecture) | -| connect a real backend, gRPC or your services | [Add it to your application](/using-it#_3-write-executefunc) | | scope data per user, roles, tenants | [Roles and tenants](/tenants) | -| configure the same binary for dev and prod | [Development and production](/environments) | | expose it to Claude Code or Cursor | [Serving MCP clients](/mcp) | diff --git a/docs/content/sources.md b/docs/content/sources.md new file mode 100644 index 0000000..c03b21b --- /dev/null +++ b/docs/content/sources.md @@ -0,0 +1,82 @@ +# Capability sources + +A capability is a function the model's program may call. Where its definition +comes from is a choice; what codemode guarantees about it is not. Every source +produces the same `codemode.Source`: + +```go +type Source struct { + Registry capability.Registry // what may be called, with its shapes and access + Execute codemode.ExecuteFunc // what serves each call + Skipped map[string]error // definitions the adapter could not express +} +``` + +and from there validation, approval, search, typed answers and the sandbox +behave the same. + +```mermaid +flowchart LR + G["Go structs
capability/gosource"] --> S + P["protobuf
registry"] --> S + M["MCP servers
capability/mcpsource"] --> S + S["codemode.Source"] --> C["codemode.Combine"] + C --> F["codemode.FromSource(source, caller)"] + F --> A["agent.Run / agent.RunAs"] +``` + +## Choosing one + +| You have | Use | Why | +| --- | --- | --- | +| Go functions | [`gosource`](/quickstart) | No codegen, no switch; the structs are the schema. Start here. | +| An API described in protobuf | [`registry`](/protobuf) | The contract already exists; roles and approval live in it. | +| A service in another language, or a SaaS | [`mcpsource`](/capabilities#capabilities-from-an-mcp-server) | Run or reuse an MCP server; import its tools. | + +## What every capability carries + +| Field | Decided by | +| --- | --- | +| Name, description | the provider | +| Input and output shape | the provider | +| Handler | the provider | +| Read or write | the provider proposes, your application decides | +| Access: roles, permissions | your application only | +| Needs approval | your application only | + +A provider describes a capability; only your application grants it. That is why +`mcpsource` makes every imported tool require a role you name and treats each as +a write, whatever the server claims, and why `gosource.Func` has no default +access. + +## Combining sources + +```go +own, err := gosource.New(...) +github, err := mcpsource.Import(ctx, session, "github", "engineer") +proto := codemode.Source{Registry: registry, Execute: app.Execute} + +all, err := codemode.Combine(own, github, proto) +mode, err := codemode.FromSource(all, caller) +``` + +`Combine` routes each call to the source that owns its RPC. A capability name or +RPC defined twice is an error, not a silent override. + +`FromSource` is `New` with the defaults: `Registry.For(caller)` and keyword +search. Use `codemode.New` directly for a [vector index](/search). + +## Writing an adapter + +A new source is a package that returns a `codemode.Source`. In its tests, run the +shared contract: + +```go +func TestSourcePassesTheContract(t *testing.T) { + sourcetest.Run(t, source) +} +``` + +It checks names and RPCs are unique, every capability has a description and a +declared input shape, every referenced type is declared, and an unknown RPC +fails. diff --git a/docs/content/types.md b/docs/content/types.md new file mode 100644 index 0000000..4217cd4 --- /dev/null +++ b/docs/content/types.md @@ -0,0 +1,75 @@ +# Types and validation + +Codemode checks values at the two places the model's program meets your code. + +| Where | What is checked | On a mismatch | +| --- | --- | --- | +| Each `codemode.execute(name, input)` | `input` against the capability's input shape | the call fails before your handler runs; the error names the field, and the model repairs the program | +| The program's return value, with `agent.RunAs[T]` | the value against `T` | the model is told what was wrong and repairs the program | + +A program that already ran a write is never repaired, so a write cannot happen +twice. See [Writes and retries](/writes). + +## Input + +Every source declares an input shape, and every call is validated against it: + +- an unknown field is rejected, naming the fields that exist; +- each value must have its declared kind: `string`, `bool`, `number`, + `integer` (no fraction), lists, maps, nested shapes and enums; +- a field the shape marks required must be present and not `null`; +- at most one field of a `oneof` group may be set. + +Errors carry the path, for example `items[2].id: want integer, got "2"`. +Nothing that fails validation is recorded as a call, so it never counts as a +write. + +What counts as required depends on the source: + +| Source | Required | Optional | +| --- | --- | --- | +| `gosource` | every field without `omitempty`, `omitzero` or a pointer | the rest | +| `mcpsource` | the JSON Schema's `required` | the rest | +| protobuf | nothing: proto3 fields default to zero | `optional` fields are shown as optional | + +## Go structs + +`gosource` and `RunAs` read Go types the way `encoding/json` writes them: + +| Go | Shape | +| --- | --- | +| `string`, `bool` | `string`, `bool` | +| `int`, `int64`, `uint32`, ... | `integer` | +| `float64`, `float32` | `number` | +| `[]T`, `[N]T` | list of `T` | +| `map[string]T`, `map[int]T` | map | +| `[]byte` | base64 string | +| `time.Time` | RFC 3339 string | +| `json.RawMessage`, `any` | anything | +| a struct | a named shape, declared once | +| a string type with `Enum() []string` | one of those values | +| `,string` tag option | string | + +Embedded structs are flattened. A `desc:"..."` tag describes a field to the +model. A type whose JSON shape reflection cannot know — a custom +`json.Marshaler`, a channel, a function — is an error when the source is built, +never a silent `any`. + +A nil slice or map in a response is sent as `[]` or `{}`, because the prompt +promised the model a list. + +## Typed answers + +```go +type Revenue struct { + Total float64 `json:"total"` + TopCustomer string `json:"top_customer"` +} + +revenue, result, err := agent.RunAs[Revenue](ctx, mode, model, request, options) +``` + +The model is told the shape in a sentence every engine reads alike, the return +value is checked and decoded into `T`, and a mismatch is repaired like any other +failure, within `Options.Attempts`. `RunAs[string]` asks for a string. The shape +is part of the cache key, so a cached program is reused only for the same `T`. diff --git a/docs/content/writes.md b/docs/content/writes.md index 0834f3e..4bb84bd 100644 --- a/docs/content/writes.md +++ b/docs/content/writes.md @@ -43,6 +43,10 @@ user what changed. ## Approving writes first +To hold only the writes that matter, such as a refund, mark them +`NeedsApproval` and apply the plan by ID: see [Approving writes](/approval). +To dry-run every write, use `Options.Plan`. + With `Options.Plan`, reads run but writes are recorded instead of executed and returned in `Result.Planned`. Show them, then apply exactly those: diff --git a/notes/decisions/0008-capability-sources.md b/notes/decisions/0008-capability-sources.md new file mode 100644 index 0000000..0cb87ae --- /dev/null +++ b/notes/decisions/0008-capability-sources.md @@ -0,0 +1,61 @@ +# 0008 — Capabilities come from sources; guarantees live in the core + +**Status:** accepted +**Date:** 2026-11-16 + +## Context + +Protobuf read as the core of codemode. It never was: `capability`, `codemode`, +`agent`, `llm`, `sandbox` and `program` import neither protobuf nor `registry/`, +and `capability/mcpsource` was already a second source. But every integration +looked like protobuf — buf config, a vendored `codemode.proto` — followed by a +hand-written `switch rpc` with request structs duplicating the schema and its +own JSON decoding. Nothing validated a program's arguments before the handler, +approval was all-or-nothing (`Options.Plan`), and the answer was `any`. + +BAML was proposed as a replacement because of Schema-Aligned Parsing: an LLM +result is your type or an error. Its half that matters here is the guarantee. +Its other half, repairing malformed JSON, does not apply: a program's values +leave the interpreter as exact JSON. BAML also has no notion of a service, no +place for roles or approval, no runtime descriptors to read a registry from, and +a Rust runtime that would break `CGO_ENABLED=0`. + +## Decision + +A source is an adapter that produces `codemode.Source{Registry, Execute}`. +`gosource` (typed Go functions), `registry` (protobuf) and `mcpsource` (MCP +tools) are sources; `codemode.Combine` serves several as one. The developer +default is `gosource`: the structs are the schema and there is no switch. + +The guarantees belong to the core, so every source gets them: + +- **Input validation.** `codemode` validates each call against the capability's + input shape before `ExecuteFunc`. Errors name the path and go back to the + model to repair. A rejected call is not recorded, so it never counts as a write. +- **Typed answers.** `agent.RunAs[T]` tells the model `T`'s shape, checks the + return value and decodes it. A mismatch is a repairable failure. +- **Approval.** `Capability.NeedsApproval`, declared by the source. A held write + holds every later write, so the plan keeps the program's order. Plans live + server-side in an `agent.PlanStore` and apply once, by ID, for their owner. +- **Fail-closed access.** `gosource.Func` takes access as a required argument + with no zero value; `mcpsource` still requires a role; protobuf keeps its + annotations. + +`TypeSchema` gains `Required`, honoured only by sources that mean it (Go +structs, JSON Schema; not proto3), and an `integer` kind. + +BAML is not the core. If it is added, it is a source: BAML-generated Go types +may already work with `gosource`, which a spike must confirm (cgo, and whether +`@description` survives) before any `bamlsource` package exists. + +## Consequences + +- A call that used to reach a handler with an unknown field or the wrong type + now fails first. Hand-built capabilities with no input `Fields` are not + checked, so existing test doubles keep working. +- Proto registries still send every integer as `number`; protobuf typed + dispatch, where `protojson` would enforce it, is v0.2. +- A held write returns `{}` to the program, so the steps after it may plan + wrongly. Documented, not solved. +- MCP clients cannot approve: `run_program` refuses and names the held writes + until an `apply_plan` tool exists. diff --git a/notes/milestones/2026-11-pluggable-sources.md b/notes/milestones/2026-11-pluggable-sources.md new file mode 100644 index 0000000..66a1d06 --- /dev/null +++ b/notes/milestones/2026-11-pluggable-sources.md @@ -0,0 +1,247 @@ +# Pluggable capability sources + +Depends on: nothing · Trigger: hosts that do not want protobuf, and every host +that writes a `switch rpc` · Decision: [0008](../decisions/0008-capability-sources.md) + +**Status (2026-11-16):** v0.1 implemented, untagged. Differences from the plan +below: `Source`, `Combine` and `FromSource` live in `codemode` (an `ExecuteFunc` +in `capability` would import `codemode`), `sourcetest` is `codemode/sourcetest`, +the Go schema is `capability.SchemaOf` (stdlib reflection, so Go type names reach +the prompt, rather than `jsonschema-go`), and descriptions use a `desc` tag. +Not done: T3.5 (taskreport approval UI) and tagging `v0.1.0`. Open questions +1–3 resolved as: add `Required`, add `integer`, RPC is the capability name; +4 kept as written. + +## Problem + +From an application developer's side, a first integration asks four things, in +this order: + +1. Can I use the Go functions I already have, in ten minutes? +2. Can the model do damage? +3. Can it ask before it deletes something? +4. Can I get a struct back instead of a string? + +Today the answer to 1 is no. Protobuf reads as the core, so a first integration +means buf config, a vendored `codemode.proto`, then a `switch rpc` with +hand-typed RPC strings, request structs duplicating the schema, and hand-written +decoding (`examples/todo/app/app.go:54`). Nothing validates a program's +arguments before the handler, approval is all-or-nothing (`Options.Plan`), and +the final answer is `any`. + +Protobuf is not the core. `capability`, `codemode`, `agent`, `llm`, `sandbox` +and `program` import neither protobuf nor `registry/`; they work in +`capability.Registry`, `TypeSchema` and `ExecuteFunc`, and `capability/mcpsource` +is already a second source. What is missing is the developer-facing layer. + +BAML's appeal is Schema-Aligned Parsing: an LLM result is your type or an error. +The guarantee half applies here. The JSON-repair half does not: program values +leave the interpreter as exact JSON. + +## Goal + +What a developer writes: + +```go +src, err := gosource.New( + gosource.Func("todos.list", "List todos", gosource.Public(), app.List, gosource.ReadOnly()), + gosource.Func("todos.delete", "Delete a todo", gosource.Roles("member"), app.Delete, gosource.NeedsApproval()), +) +mode, err := codemode.FromSource(src, caller) + +summary, err := agent.RunAs[Summary](ctx, mode, model, "clean up done todos", options) +var pending *agent.Pending +if errors.As(err, &pending) { + // show pending.Calls; on approval: + calls, err := agent.ApplyPlan(ctx, mode, plans, pending.ID) +} +``` + +No buf, no vendored proto, no `switch`, no duplicated struct. Protobuf, MCP and +BAML become other ways to produce the same `capability.Source`. + +```mermaid +flowchart LR + G[capability/gosource] --> S + P[registry] --> S + M[capability/mcpsource] --> S + B[capability/bamlsource] --> S + S["capability.Source{Registry, Execute}"] --> C[capability.Combine] + C --> F[codemode.FromSource] + F --> A["agent.RunAs[T]"] +``` + +## The provider contract + +Every capability, from any source, carries six things: + +| Field | Decided by | +| --- | --- | +| Name, description | provider | +| Input and output schema | provider | +| Handler | provider | +| Effect (read or write) | provider proposes, host decides | +| Access (roles, permissions) | host only | +| Needs approval | host only | + +A provider describes; only the host grants. A remote provider can never make its +own tool public, read-only or approval-free. + +| Provider | How it provides | Status | +| --- | --- | --- | +| The host's own Go code | `gosource.Func`, or proto `registry.Source(impl)` | v0.1, v0.2 | +| Another team or language | An MCP server in any SDK, imported with `mcpsource` | works; per-caller identity in v0.2 | +| A third-party SaaS | Its MCP server, same path | works | + +MCP is the out-of-process path. No new wire protocol. + +## Principles + +- Every source is its own package. `capability` never imports a vendor SDK; + `check-consumer.sh` stays green after every task. +- No source may produce an unrestricted capability by omission. Access is a + required argument wherever the host binds a capability. +- Effect defaults to write. Only an explicit marker makes a capability + read-only. +- Existing proto users do not break: `registry/` keeps its import path. + +## v0.1 — your Go functions, typed, safe, with approval + +Four PRs, in order. Tag `v0.1.0` after the last. + +### PR 1 — Core contracts + +- **T1.1** ADR `0008-capability-sources.md`: the core is source-agnostic, + sources are adapters, validation and typed results live in the core. Records + why BAML is a source and not the core, and why SAP's repair half is skipped. +- **T1.2** Move `Source{Registry, Execute, Skipped}` from `mcpsource` to + `capability`; `mcpsource.Import` returns it. mcpsource tests pass unchanged + apart from the type name. +- **T1.3** `capability.Combine(sources...) (Source, error)`: merges with the + existing `Merge` (duplicate names fail) and routes `Execute` by RPC to the + owning source. Tests: routing, duplicate name, unknown RPC. +- **T1.4** Extract `object`/`fields`/`typeOf` from `mcpsource` into exported + `capability/jsonschema`. Unsupported constructs stay an error, never `any`. + Converter tests move with it. +- **T1.5** `capability.Validate(item, input) error` against `item.Input` and + `item.Types`: unknown fields, JSON kinds, enum values, `repeated`, + `map`, nested types, oneof exclusivity. Errors name the path + (`items[2].id: want number`). Table tests per rule; a fuzz test that it never + panics. +- **T1.6** `codemode` runs `Validate` before `execute`. Tests: an invalid call + never reaches `ExecuteFunc`; the agent's repair prompt carries the path. +- **T1.7** `capability/sourcetest.Run(t, source)`: shared contract every adapter + calls — unique names, referenced types resolvable, RPC routable, unknown RPC + errors. + +### PR 2 — `capability/gosource` + +- **T2.1** `Func[In, Out any](name, description string, access Access, + handler func(context.Context, In) (Out, error), options ...Option)`. + `Access` has an unexported method; only `Public()`, `Roles(...)` and + `Permissions(...)` build one, so there is no zero value to forget. + Options: `ReadOnly()`, `NeedsApproval()`. +- **T2.2** Schema from `In`/`Out` through `github.com/google/jsonschema-go` + `For[T]` (already an indirect dependency) and the T1.4 converter. + Descriptions from its `jsonschema:"..."` tag; no tag of our own. +- **T2.3** `New(funcs...) (capability.Source, error)`: name pattern, duplicates, + `Execute` decodes into `In` with `DisallowUnknownFields` and encodes `Out`; a + handler panic becomes an error. Tests: round trip, unknown field rejected, + `sourcetest.Run`. +- **T2.4** `codemode.FromSource(source, caller) (CodeMode, error)`: applies + `Registry.For(caller)` and defaults search to `capability.Keyword`. +- **T2.5** `examples/todo` gains a gosource variant beside the proto one. Both + run the same fixed program and must give the same answer. + +### PR 3 — Approval + +- **T3.1** `Capability.NeedsApproval bool`. Sources set it: `gosource` through + `NeedsApproval()`, proto through a new `(codemode.needs_approval)` method + option, `mcpsource` through an import option (host policy). + A read-only capability that needs approval is a build error. +- **T3.2** A run holds a write that needs approval, and every write after it, + instead of executing them. Writes before it execute as today. `agent.Run` + returns `*agent.Pending{ID, Calls}`. `Options.Plan` stays and still holds + every write. +- **T3.3** `agent.PlanStore` port (`Save`, `Take` — take deletes, so a plan + applies once) with an in-memory adapter and a TTL. `agent.ApplyPlan(ctx, + mode, store, id)` applies by ID, so the client never sends the calls back. + Calls pass through `Validate`, the registry and access checks again. +- **T3.4** Tests: approval-free writes execute and later ones are held; apply by + ID once; second apply fails; expired plan fails; a caller who lost access + fails at apply. +- **T3.5** Taskreport: delete RPCs need approval; the UI shows pending calls + with approve and reject. + +### PR 4 — Typed result + +- **T4.1** `agent.RunAs[T any](ctx, mode, model, request, options) (T, Result, + error)`, a wrapper over `Run`, not a second loop. Schema of `T` through the + T2.2 path. +- **T4.2** Each dialect's `Runner.Prompt` renders the expected return shape when + given one (JS, Starlark, Lua). Prompt snapshot test per engine. +- **T4.3** The program's return value is validated against `T`'s schema; a + mismatch goes through `repairPrompt` with the path error and counts against + `Attempts`. Tests: wrong shape repairs then succeeds; exhausted attempts + return the last validation error. + +### v0.1 docs + +- README leads with the Goal snippet. Protobuf, MCP and BAML move under "Other + sources". +- `docs/content/sources.md` (choosing a source, the provider contract), + `docs/content/approval.md`; `writes.md` links to approval; sidebar in + `docs/.vitepress/config.ts`. +- Quickstart rewritten around `gosource`; the proto quickstart becomes + `docs/content/protobuf.md`. +- `CHANGELOG.md` `[Unreleased]` per PR. + +## v0.2 — other sources, remote safety + +- **Proto typed dispatch.** `registry.Source(impl any, files...)`: finds + `impl.(context.Context, *Req) (*Resp, error)` by reflection (the gRPC + server shape), decodes with `protojson`, encodes with `registry.MarshalJSON`. + A method with no Go implementation fails at build. Removes the switch for + existing proto users. +- **Per-caller identity in `mcpsource`.** Today one session is bound at import, + so a remote provider sees one identity for every user and cannot do row-level + checks. Build the session per call from the caller, like `mcpserver`'s + `ModeFunc`. Required before multi-user remote providers. +- **Approval over MCP.** `run_program` returns held writes and a plan ID; a new + `apply_plan` tool applies it. Today an MCP client's user approves program + text, not the writes it makes. +- **BAML spike**, written up as ADR 0009: does the generated Go types package + pull cgo or the Rust runtime (`go list -deps`), and does `@description` + reach the Go output? If the types are plain Go, BAML support is a docs page + showing them with `gosource`. Only if not, `capability/bamlsource` parses the + `.baml` subset needed (`class`, `enum`, `@description`, `@alias`, optional, + lists, maps). Access is a bind-time argument, never a BAML comment. + +## Out of scope + +SAP JSON repair; JSON Schema files as a source (until a non-Go host asks); OpenAPI +import; Connect handler shape; mocked outputs for planned writes — a program +that uses a held write's output stays unplannable, documented in `approval.md`; +asking the user a question mid-program; moving `registry/`; a `codemode init` +scaffold. + +## Open questions + +1. `TypeSchema` has `Optional` but no required. Proto3 fields are implicitly + optional; Go structs and JSON Schema can mean required. Add + `Required []string`, honoured only by sources that set it? +2. All numerics are `"number"`, so `Validate` cannot reject `1.5` for an `int`. + Add an `integer` kind? +3. `gosource` RPC string: the capability name, or a separate value? +4. Holding every write after the first approval-required one keeps the order + intact but can hold harmless writes. Is that the right default? + +## Done when + +- The todo example runs from Go structs with no `switch rpc`, and the proto + variant gives the same answer. +- An invalid argument never reaches a handler, from any source. +- A write marked `NeedsApproval` never runs without an `ApplyPlan`, and a plan + applies at most once. +- `agent.RunAs[T]` returns a validated `T` or an error after repair attempts. +- `make test` and `check-consumer.sh` green; `v0.1.0` tagged. From 300d87adf319a79411d6f54cf02793743307bfaa Mon Sep 17 00:00:00 2001 From: Mukesh Kumar Chaudhary Date: Mon, 16 Nov 2026 10:22:11 +0545 Subject: [PATCH 4/7] feat: add a todo delete that needs approval todos.delete is NeedsApproval in both the Go source and todo.proto. todo-mcp builds its server in newServer, and a test shows run_program refusing a program that reaches the delete and naming what did not run. --- examples/todo/README.md | 7 +- examples/todo/app/app.go | 25 ++++++ examples/todo/cmd/todo-mcp/main.go | 24 +++-- examples/todo/cmd/todo-mcp/main_test.go | 54 +++++++++++ examples/todo/gen/todo/v1/todo.pb.go | 115 ++++++++++++++++++++++-- examples/todo/proto/todo.proto | 13 +++ 6 files changed, 218 insertions(+), 20 deletions(-) create mode 100644 examples/todo/cmd/todo-mcp/main_test.go diff --git a/examples/todo/README.md b/examples/todo/README.md index 895a1cd..8ab6180 100644 --- a/examples/todo/README.md +++ b/examples/todo/README.md @@ -1,7 +1,8 @@ # todo -The smallest complete code-mode application: three capabilities (`todos.create`, -`todos.list`, `todos.complete`), an in-memory store, and a model that answers a +The smallest complete code-mode application: four capabilities (`todos.create`, +`todos.list`, `todos.complete`, and `todos.delete`, which needs approval), an +in-memory store, and a model that answers a request by writing **one program** that calls them. The capabilities come from typed Go functions by default (`app.Source`, built @@ -17,6 +18,8 @@ gen/ generated Go, committed so `go run` needs no buf app/ the todo list: typed methods, Source() for Go, Execute for proto main.go the command-line demo cmd/todo-mcp/ the same app as an MCP server for Claude Code, Cursor, ... + An MCP client cannot approve, so run_program refuses a + program that reaches todos.delete and names what did not run. ``` All commands below run from the **repository root**. diff --git a/examples/todo/app/app.go b/examples/todo/app/app.go index 490cb1e..17c0cce 100644 --- a/examples/todo/app/app.go +++ b/examples/todo/app/app.go @@ -38,6 +38,14 @@ type CompleteRequest struct { ID int64 `json:"id" desc:"the id from todos.list"` } +type DeleteRequest struct { + ID int64 `json:"id" desc:"the id from todos.list"` +} + +type DeleteResponse struct { + Deleted bool `json:"deleted"` +} + type App struct { mutex sync.Mutex nextID int64 @@ -54,6 +62,8 @@ func (app *App) Source() (codemode.Source, error) { gosource.Func("todos.create", "Creates a todo item with the given title.", gosource.Public(), app.Create), gosource.Func("todos.list", "Lists all todo items and their completion state.", gosource.Public(), app.List, gosource.ReadOnly()), gosource.Func("todos.complete", "Marks a todo item as completed by ID.", gosource.Public(), app.Complete), + gosource.Func("todos.delete", "Deletes a todo item by ID. The user approves each deletion before it happens.", + gosource.Public(), app.Delete, gosource.NeedsApproval()), ) } @@ -88,7 +98,20 @@ func (app *App) Complete(_ context.Context, request CompleteRequest) (TodoRespon return TodoResponse{}, fmt.Errorf("todo %d not found", request.ID) } +func (app *App) Delete(_ context.Context, request DeleteRequest) (DeleteResponse, error) { + app.mutex.Lock() + defer app.mutex.Unlock() + for index := range app.todos { + if app.todos[index].ID == request.ID { + app.todos = append(app.todos[:index], app.todos[index+1:]...) + return DeleteResponse{Deleted: true}, nil + } + } + return DeleteResponse{}, fmt.Errorf("todo %d not found", request.ID) +} + const ( + deleteRPC = "todo.v1.TodoService/Delete" createRPC = "todo.v1.TodoService/Create" listRPC = "todo.v1.TodoService/List" completeRPC = "todo.v1.TodoService/Complete" @@ -107,6 +130,8 @@ func (app *App) Execute(ctx context.Context, rpc string, input json.RawMessage) return serve(ctx, input, app.List) case completeRPC: return serve(ctx, input, app.Complete) + case deleteRPC: + return serve(ctx, input, app.Delete) } return nil, fmt.Errorf("RPC %q is not implemented", rpc) } diff --git a/examples/todo/cmd/todo-mcp/main.go b/examples/todo/cmd/todo-mcp/main.go index 2560bcb..ae683a6 100644 --- a/examples/todo/cmd/todo-mcp/main.go +++ b/examples/todo/cmd/todo-mcp/main.go @@ -29,14 +29,6 @@ func main() { } func run(ctx context.Context) error { - source, err := app.New().Source() - if err != nil { - return err - } - mode, err := codemode.FromSource(source, capability.Caller{}) - if err != nil { - return err - } // An MCP client is a program author you do not control: prefer SANDBOX_ISOLATION=process. runner, err := sandbox.NewFromEnv(sandbox.Options{}) if err != nil { @@ -45,9 +37,23 @@ func run(ctx context.Context) error { defer runner.Close() fmt.Fprintf(os.Stderr, "todo-mcp: %s\n", runner.Name()) - server, err := mcpserver.New(mcpserver.Static(mode), runner, mcpserver.Options{Name: "todo"}) + server, err := newServer(runner) if err != nil { return err } return server.Run(ctx, &mcp.StdioTransport{}) } + +// todos.delete needs approval, which an MCP client cannot give: run_program +// refuses a program that reaches it and names the writes that did not run. +func newServer(runner sandbox.Runner) (*mcp.Server, error) { + source, err := app.New().Source() + if err != nil { + return nil, err + } + mode, err := codemode.FromSource(source, capability.Caller{}) + if err != nil { + return nil, err + } + return mcpserver.New(mcpserver.Static(mode), runner, mcpserver.Options{Name: "todo"}) +} diff --git a/examples/todo/cmd/todo-mcp/main_test.go b/examples/todo/cmd/todo-mcp/main_test.go new file mode 100644 index 0000000..712d0a5 --- /dev/null +++ b/examples/todo/cmd/todo-mcp/main_test.go @@ -0,0 +1,54 @@ +package main + +import ( + "context" + "strings" + "testing" + + "github.com/modelcontextprotocol/go-sdk/mcp" + + "github.com/mukezhz/codemode/mcpserver" + "github.com/mukezhz/codemode/sandbox" +) + +func TestAnMCPClientCannotDeleteWithoutApproval(t *testing.T) { + ctx := context.Background() + runner, err := sandbox.New(sandbox.Options{}) + if err != nil { + t.Fatal(err) + } + defer runner.Close() + server, err := newServer(runner) + if err != nil { + t.Fatal(err) + } + serverTransport, clientTransport := mcp.NewInMemoryTransports() + if _, err := server.Connect(ctx, serverTransport, nil); err != nil { + t.Fatal(err) + } + session, err := mcp.NewClient(&mcp.Implementation{Name: "test"}, nil).Connect(ctx, clientTransport, nil) + if err != nil { + t.Fatal(err) + } + defer session.Close() + + result, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "run_program", Arguments: mcpserver.RunInput{Source: ` + const { todo } = codemode.execute("todos.create", { title: "temporary" }); + codemode.execute("todos.delete", { id: todo.id }); + return "deleted";`}}) + if err != nil { + t.Fatal(err) + } + text := result.Content[0].(*mcp.TextContent).Text + if !result.IsError || !strings.Contains(text, "did not run: todos.delete") { + t.Fatalf("result = %q; a delete needing approval must not report success", text) + } + + listed, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "run_program", Arguments: mcpserver.RunInput{Source: `return codemode.execute("todos.list", {}).todos.length;`}}) + if err != nil || listed.IsError { + t.Fatalf("list: %v %+v", err, listed) + } + if structured, _ := listed.StructuredContent.(map[string]any); structured["value"] != float64(1) { + t.Fatalf("value = %v; the todo created before the held delete must still exist", listed.StructuredContent) + } +} diff --git a/examples/todo/gen/todo/v1/todo.pb.go b/examples/todo/gen/todo/v1/todo.pb.go index 2e3b905..bca5d75 100644 --- a/examples/todo/gen/todo/v1/todo.pb.go +++ b/examples/todo/gen/todo/v1/todo.pb.go @@ -338,6 +338,94 @@ func (x *Todo) GetCompleted() bool { return false } +type DeleteTodoRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DeleteTodoRequest) Reset() { + *x = DeleteTodoRequest{} + mi := &file_todo_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DeleteTodoRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DeleteTodoRequest) ProtoMessage() {} + +func (x *DeleteTodoRequest) ProtoReflect() protoreflect.Message { + mi := &file_todo_proto_msgTypes[7] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DeleteTodoRequest.ProtoReflect.Descriptor instead. +func (*DeleteTodoRequest) Descriptor() ([]byte, []int) { + return file_todo_proto_rawDescGZIP(), []int{7} +} + +func (x *DeleteTodoRequest) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type DeleteTodoResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Deleted bool `protobuf:"varint,1,opt,name=deleted,proto3" json:"deleted,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DeleteTodoResponse) Reset() { + *x = DeleteTodoResponse{} + mi := &file_todo_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DeleteTodoResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DeleteTodoResponse) ProtoMessage() {} + +func (x *DeleteTodoResponse) ProtoReflect() protoreflect.Message { + mi := &file_todo_proto_msgTypes[8] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DeleteTodoResponse.ProtoReflect.Descriptor instead. +func (*DeleteTodoResponse) Descriptor() ([]byte, []int) { + return file_todo_proto_rawDescGZIP(), []int{8} +} + +func (x *DeleteTodoResponse) GetDeleted() bool { + if x != nil { + return x.Deleted + } + return false +} + var File_todo_proto protoreflect.FileDescriptor const file_todo_proto_rawDesc = "" + @@ -358,11 +446,16 @@ const file_todo_proto_rawDesc = "" + "\x04Todo\x12\x0e\n" + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x14\n" + "\x05title\x18\x02 \x01(\tR\x05title\x12\x1c\n" + - "\tcompleted\x18\x03 \x01(\bR\tcompleted2\xf6\x02\n" + + "\tcompleted\x18\x03 \x01(\bR\tcompleted\"#\n" + + "\x11DeleteTodoRequest\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\".\n" + + "\x12DeleteTodoResponse\x12\x18\n" + + "\adeleted\x18\x01 \x01(\bR\adeleted2\x91\x04\n" + "\vTodoService\x12p\n" + "\x06Create\x12\x1a.todo.v1.CreateTodoRequest\x1a\x1b.todo.v1.CreateTodoResponse\"-\x82\xb5\x18)Creates a todo item with the given title.\x12v\n" + "\x04List\x12\x19.todo.v1.ListTodosRequest\x1a\x1a.todo.v1.ListTodosResponse\"7\x82\xb5\x180Lists all todo items and their completion state.\x90\x02\x01\x12r\n" + - "\bComplete\x12\x1c.todo.v1.CompleteTodoRequest\x1a\x1d.todo.v1.CompleteTodoResponse\")\x82\xb5\x18%Marks a todo item as completed by ID.\x1a\t\x82\xb5\x18\x05todosB>ZZ todo.v1.Todo @@ -393,11 +488,13 @@ var file_todo_proto_depIdxs = []int32{ 0, // 3: todo.v1.TodoService.Create:input_type -> todo.v1.CreateTodoRequest 2, // 4: todo.v1.TodoService.List:input_type -> todo.v1.ListTodosRequest 4, // 5: todo.v1.TodoService.Complete:input_type -> todo.v1.CompleteTodoRequest - 1, // 6: todo.v1.TodoService.Create:output_type -> todo.v1.CreateTodoResponse - 3, // 7: todo.v1.TodoService.List:output_type -> todo.v1.ListTodosResponse - 5, // 8: todo.v1.TodoService.Complete:output_type -> todo.v1.CompleteTodoResponse - 6, // [6:9] is the sub-list for method output_type - 3, // [3:6] is the sub-list for method input_type + 7, // 6: todo.v1.TodoService.Delete:input_type -> todo.v1.DeleteTodoRequest + 1, // 7: todo.v1.TodoService.Create:output_type -> todo.v1.CreateTodoResponse + 3, // 8: todo.v1.TodoService.List:output_type -> todo.v1.ListTodosResponse + 5, // 9: todo.v1.TodoService.Complete:output_type -> todo.v1.CompleteTodoResponse + 8, // 10: todo.v1.TodoService.Delete:output_type -> todo.v1.DeleteTodoResponse + 7, // [7:11] is the sub-list for method output_type + 3, // [3:7] is the sub-list for method input_type 3, // [3:3] is the sub-list for extension type_name 3, // [3:3] is the sub-list for extension extendee 0, // [0:3] is the sub-list for field type_name @@ -414,7 +511,7 @@ func file_todo_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_todo_proto_rawDesc), len(file_todo_proto_rawDesc)), NumEnums: 0, - NumMessages: 7, + NumMessages: 9, NumExtensions: 0, NumServices: 1, }, diff --git a/examples/todo/proto/todo.proto b/examples/todo/proto/todo.proto index adbc4c7..5b9c520 100644 --- a/examples/todo/proto/todo.proto +++ b/examples/todo/proto/todo.proto @@ -21,6 +21,11 @@ service TodoService { rpc Complete(CompleteTodoRequest) returns (CompleteTodoResponse) { option (codemode.description) = "Marks a todo item as completed by ID."; } + + rpc Delete(DeleteTodoRequest) returns (DeleteTodoResponse) { + option (codemode.description) = "Deletes a todo item by ID. The user approves each deletion before it happens."; + option (codemode.needs_approval) = true; + } } message CreateTodoRequest { @@ -50,3 +55,11 @@ message Todo { string title = 2; bool completed = 3; } + +message DeleteTodoRequest { + int64 id = 1; +} + +message DeleteTodoResponse { + bool deleted = 1; +} From a1fb19f5634edd7c6d82381c1f4ecf9187ccf429 Mon Sep 17 00:00:00 2001 From: Mukesh Kumar Chaudhary Date: Mon, 16 Nov 2026 10:22:11 +0545 Subject: [PATCH 5/7] feat: serve taskreport from typed Go functions and approve deletes in chat The 23 capabilities are typed methods on app.App, served by gosource by default; -source proto keeps the protos, routed to the same methods, and a test holds both to the same names, descriptions, roles, reads and approvals. tasks.delete needs approval. A chat that reaches it returns the held plan, the page shows Approve and Reject, and POST /api/plans/{id}/approve or /reject applies or discards it once, for its owner. A delete from the board is its own approval. --- examples/taskreport/README.md | 56 +- examples/taskreport/app/app.go | 712 ++++++++++-------- examples/taskreport/app/app_test.go | 79 ++ examples/taskreport/gen/task/v1/task.pb.go | 6 +- examples/taskreport/main.go | 44 +- examples/taskreport/proto/task.proto | 4 +- examples/taskreport/serve.go | 7 +- examples/taskreport/server/approval_test.go | 104 +++ examples/taskreport/server/server.go | 113 ++- .../web/dist/assets/chat-CmZZLyt2.js | 1 - .../web/dist/assets/chat-fahH1l62.js | 1 + .../{index-Dm_jx5Ya.js => index-B8YGsnYU.js} | 2 +- .../{index-D4Un-2Pf.js => index-D-DTohO0.js} | 12 +- ...{index-CZUp2bvV.css => index-D44oUAo0.css} | 2 +- examples/taskreport/web/dist/index.html | 4 +- examples/taskreport/web/src/api.ts | 12 + examples/taskreport/web/src/routes/chat.tsx | 54 +- examples/taskreport/web/src/styles.css | 6 + 18 files changed, 865 insertions(+), 354 deletions(-) create mode 100644 examples/taskreport/server/approval_test.go delete mode 100644 examples/taskreport/web/dist/assets/chat-CmZZLyt2.js create mode 100644 examples/taskreport/web/dist/assets/chat-fahH1l62.js rename examples/taskreport/web/dist/assets/{index-Dm_jx5Ya.js => index-B8YGsnYU.js} (97%) rename examples/taskreport/web/dist/assets/{index-D4Un-2Pf.js => index-D-DTohO0.js} (90%) rename examples/taskreport/web/dist/assets/{index-CZUp2bvV.css => index-D44oUAo0.css} (95%) diff --git a/examples/taskreport/README.md b/examples/taskreport/README.md index 49eaae5..954df81 100644 --- a/examples/taskreport/README.md +++ b/examples/taskreport/README.md @@ -1,13 +1,14 @@ # taskreport A task tracker with a web UI, driven in code mode. Tasks live in SQLite, -twenty-three capabilities are generated from two protobuf files, and a model -answers questions by writing **one JavaScript program** that composes them — -returning a document the browser renders as charts and tables. +twenty-three capabilities are typed Go functions in [`app/app.go`](app/app.go), +and a model answers questions by writing **one JavaScript program** that +composes them — returning a document the browser renders as charts and tables. +A program that deletes a task waits for you to approve it in the chat. -Everything the application needs is in this directory. The only thing it takes -from the repository root is `proto/codemode.proto`, which declares the -annotations that mark a service as a capability surface. +The same twenty-three are also described in two protobuf files; +`-source proto` serves them from there instead, and a test asserts both sources +declare the same names, descriptions, roles, reads and approvals. --- @@ -205,8 +206,12 @@ Then use . ## Changing the contracts -After editing `proto/task.proto` or `proto/user.proto`, from the repository -root: +With the default Go source, add a method to `app.App` and a `gosource.Func` line +to `Source()`. Its request and response structs are the schema the model sees, +and every call is validated against them before the method runs. + +For `-source proto`, after editing `proto/task.proto` or `proto/user.proto`, from +the repository root: ```sh make generate @@ -390,9 +395,9 @@ Here the model is asked **once**. Only the finished document comes back. ## Capabilities -Generated from [`proto/task.proto`](proto/task.proto) and -[`proto/user.proto`](proto/user.proto) — this application's own contracts, -living beside it — and merged at startup. The split is +Defined in [`app/app.go`](app/app.go), and mirrored in +[`proto/task.proto`](proto/task.proto) and [`proto/user.proto`](proto/user.proto) +for `-source proto`. The split is deliberate: `tasks` and `projects` are primitives, and `reports` holds only the aggregates a database genuinely does better than a program would. @@ -403,12 +408,20 @@ aggregates a database genuinely does better than a program would. | `reports` | `statusCounts` `byProject` `byPriority` `overdue` `completedBetween` `throughput` · admin: `byOwner` | | `users` | `me` · admin: `list` | -The admin ones are marked `option (codemode.roles) = "admin";` in the protos, so -the policy lives beside the RPC rather than in a list in `main.go` that could -drift. They are **withheld from a member's registry entirely** — absent from the +The admin ones are declared `gosource.Roles("admin")` beside each function, and +`option (codemode.roles) = "admin";` in the protos, so the policy lives beside the +capability rather than in a list in `main.go` that could drift. They are **withheld from a member's registry entirely** — absent from the map `Execute` resolves against, not merely hidden from the model, and therefore absent from the prompt too. +`tasks.delete` needs approval (`gosource.NeedsApproval()`, and +`option (codemode.needs_approval) = true;` in the proto). When a program in the +chat reaches it, that delete and every write after it are held: the chat shows +them with **Approve** and **Reject**, and only the plan's ID goes back to the +server (`POST /api/plans/{id}/approve` or `/reject`), which applies it once, for +the user who was shown it. Deleting from the board is a button you pressed, so +it runs at once. + Anything needing judgement — what counts as behind, how to phrase a summary, what to do first — stays in the program the model writes. There is no `reports.whatShouldIDoNext` RPC, and there should not be. @@ -418,6 +431,7 @@ what to do first — stays in the program the model writes. There is no | Flag | Default | | | --- | --- | --- | | `-request` | a status report | what to ask | +| `-source` | `go` | where capabilities come from: `go` (typed functions in `app/`) or `proto` | | `-base-url` | `$OPENAI_BASE_URL` | OpenAI-compatible endpoint | | `-api-key` | `$OPENAI_API_KEY` | key for that endpoint | | `-model` | `deepseek-chat` | model name | @@ -453,18 +467,18 @@ capability signatures search selected — explains more than this README does. ## How the pieces fit ``` -proto/ this application's contracts: task.proto, user.proto +proto/ the same contracts in protobuf, for -source proto gen/ their generated Go, committed so `go get` needs no buf main.go flags and wiring. Reads $OPENAI_* itself; SANDBOX_* through sandbox.NewFromEnv. env.go loads .env into the environment, before the flags are parsed. serve.go the -serve flag: HTTP, graceful shutdown. store/ the application's own SQLite database. Knows nothing about models. -app/ ExecuteFunc: RPC path -> store call. The trust boundary. +app/ typed functions -> store calls, and Source(). The trust boundary. auth/ who is asking. Identity on the context, never in a request. search/ ranks capabilities; decides what the model is told about. trace/ logs every step. Wraps the interfaces from outside. view/ the document schema the programs return and the browser renders. -server/ REST for the board, /api/chat for the prompt. +server/ REST for the board, /api/chat for the prompt, /api/plans for approval. web/ Vite + React + TanStack Router. Built output is embedded. .env your key. Copy .env.example. ``` @@ -481,8 +495,9 @@ builds `llm.Options` explicitly from flags and `$OPENAI_*`, and calls `sandbox.NewFromEnv` so `SANDBOX_*` chooses the sandbox. Swap either for your config file and nothing in the library changes. -**The registry is derived, not generated.** `registry.FromFiles(taskv1.File_task_proto)` -reads the descriptors already compiled into the binary. No `registry.json`, no +**Nothing to generate.** The default source reads the Go structs; with +`-source proto`, `registry.FromFiles(taskv1.File_task_proto)` reads the +descriptors already compiled into the binary. No `registry.json`, no `go:embed`, no build step, and it cannot drift from the contracts. **Search and the allowlist are separate lists.** Search decides what the model @@ -490,7 +505,8 @@ reads the descriptors already compiled into the binary. No `registry.json`, no it: a program calling `tasks.dropDatabase` fails a map lookup before any application code executes. -**Strict decoding.** `app` rejects unknown request fields, so a model that +**Strict input.** Every call is validated against its shape before `app` runs — +unknown fields, wrong types, a priority that is not low, medium or high — so a model that invents `assignee` is told on the first call — while the error can still be fed back for repair — rather than having the value dropped and the answer come out quietly wrong. diff --git a/examples/taskreport/app/app.go b/examples/taskreport/app/app.go index 8d9a6d7..364c206 100644 --- a/examples/taskreport/app/app.go +++ b/examples/taskreport/app/app.go @@ -4,10 +4,14 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "strings" + "github.com/mukezhz/codemode/capability/gosource" + "github.com/mukezhz/codemode/codemode" + "github.com/mukezhz/codemode/examples/taskreport/auth" "github.com/mukezhz/codemode/examples/taskreport/store" ) @@ -25,363 +29,473 @@ func New(store *store.Store, admins ...string) *App { return &App{store: store, admins: set} } -// RPC paths this application serves, as constants so proto renames surface at compile time. -const ( - taskCreate = "task.v1.TaskService/Create" - taskGet = "task.v1.TaskService/Get" - taskList = "task.v1.TaskService/List" - taskUpdate = "task.v1.TaskService/Update" - taskComplete = "task.v1.TaskService/Complete" - taskReopen = "task.v1.TaskService/Reopen" - taskDelete = "task.v1.TaskService/Delete" - taskAddTag = "task.v1.TaskService/AddTag" - taskRemoveTag = "task.v1.TaskService/RemoveTag" - taskSearch = "task.v1.TaskService/Search" - taskListFor = "task.v1.TaskService/ListFor" - taskAssign = "task.v1.TaskService/Assign" - - projectList = "task.v1.ProjectService/List" - projectRename = "task.v1.ProjectService/Rename" - - reportStatus = "task.v1.ReportService/StatusCounts" - reportByProject = "task.v1.ReportService/ByProject" - reportByPrio = "task.v1.ReportService/ByPriority" - reportOverdue = "task.v1.ReportService/Overdue" - reportCompleted = "task.v1.ReportService/CompletedBetween" - reportThrough = "task.v1.ReportService/Throughput" - reportByOwner = "task.v1.ReportService/ByOwner" - - userMe = "user.v1.UserService/Me" - userList = "user.v1.UserService/List" -) +// Source serves every capability from the typed methods below: the request and +// response structs are the schema, and access is declared beside each one. +// Every method is scoped to the signed-in user, and none takes a user ID to say +// who that is; the four that reach across owners are administrators only. +func (app *App) Source() (codemode.Source, error) { + public, admin, read := gosource.Public(), gosource.Roles(string(auth.RoleAdmin)), gosource.ReadOnly() + return gosource.New( + gosource.Func("tasks.create", "Creates a task. Title is required. Priority is low, medium, or high and defaults to medium. Due date is YYYY-MM-DD.", public, app.Create), + gosource.Func("tasks.get", "Returns one task by its numeric ID.", public, app.Get, read), + gosource.Func("tasks.list", "Lists tasks, newest first. Every filter is optional and they combine: status is open or completed, and tag matches a single tag.", public, app.List, read), + gosource.Func("tasks.update", "Changes a task's title, project, priority, or due date. Only the fields you set are written; the rest keep their current values.", public, app.Update), + gosource.Func("tasks.complete", "Marks a task completed, recording the completion date. Completing an already completed task is an error.", public, app.Complete), + gosource.Func("tasks.reopen", "Marks a completed task open again and clears its completion date.", public, app.Reopen), + gosource.Func("tasks.delete", "Deletes a task permanently by ID. The user approves each deletion before it happens.", public, app.Delete, gosource.NeedsApproval()), + gosource.Func("tasks.addTag", "Adds a tag to a task. Adding a tag it already has changes nothing.", public, app.AddTag), + gosource.Func("tasks.removeTag", "Removes a tag from a task.", public, app.RemoveTag), + gosource.Func("tasks.search", "Finds tasks whose title contains the given text, case-insensitively.", public, app.Search, read), + gosource.Func("tasks.listFor", "Lists another user's tasks. Administrators only; everyone else uses tasks.list, which returns their own.", admin, app.ListFor, read), + gosource.Func("tasks.assign", "Moves a task to a different owner. Administrators only.", admin, app.Assign), + + gosource.Func("projects.list", "Lists every project name that has at least one task, with how many tasks each holds.", public, app.Projects, read), + gosource.Func("projects.rename", "Moves every task in one project to another project name.", public, app.RenameProject), + + gosource.Func("reports.statusCounts", "Totals every task by state: open, completed, overdue, and due today.", public, app.StatusCounts, read), + gosource.Func("reports.byProject", "Counts open and completed tasks per project, so one call answers where the work sits.", public, app.ByProject, read), + gosource.Func("reports.byPriority", "Counts open and completed tasks per priority level.", public, app.ByPriority, read), + gosource.Func("reports.overdue", "Lists open tasks whose due date is before as_of, oldest first. Leave as_of empty for today.", public, app.Overdue, read), + gosource.Func("reports.completedBetween", "Lists tasks completed between two YYYY-MM-DD dates, inclusive.", public, app.CompletedBetween, read), + gosource.Func("reports.throughput", "Counts tasks completed on each of the last N days, most recent first, including days with none.", public, app.Throughput, read), + gosource.Func("reports.byOwner", "Counts open and completed tasks per person across the whole workspace. Administrators only.", admin, app.ByOwner, read), + + gosource.Func("users.me", "Returns the signed-in user: their name and role. Takes no arguments — the caller is already known.", public, app.Me, read), + gosource.Func("users.list", "Lists everyone in the workspace with their role. Administrators only.", admin, app.Users, read), + ) +} -func (app *App) Execute(ctx context.Context, rpc string, input json.RawMessage) (json.RawMessage, error) { +type Priority string + +func (Priority) Enum() []string { return []string{"low", "medium", "high"} } + +type Status string + +func (Status) Enum() []string { return []string{"open", "completed"} } + +type CreateTask struct { + Title string `json:"title"` + Project string `json:"project,omitempty"` + Priority Priority `json:"priority,omitempty" desc:"defaults to medium"` + DueDate string `json:"due_date,omitempty" desc:"YYYY-MM-DD"` + Tags []string `json:"tags,omitempty"` +} + +type TaskID struct { + ID int64 `json:"id"` +} + +type ListTasks struct { + Project string `json:"project,omitempty"` + Status Status `json:"status,omitempty" desc:"leave out for both"` + Priority Priority `json:"priority,omitempty"` + Tag string `json:"tag,omitempty"` + Limit int `json:"limit,omitempty" desc:"leave out for every match"` +} + +type UpdateTask struct { + ID int64 `json:"id"` + Title string `json:"title,omitempty"` + Project string `json:"project,omitempty"` + Priority Priority `json:"priority,omitempty"` + DueDate string `json:"due_date,omitempty" desc:"YYYY-MM-DD"` +} + +type TagTask struct { + ID int64 `json:"id"` + Tag string `json:"tag"` +} + +type SearchTasks struct { + Text string `json:"text"` + Limit int `json:"limit,omitempty"` +} + +type ListFor struct { + Owner string `json:"owner"` + Status Status `json:"status,omitempty" desc:"leave out for both"` + Limit int `json:"limit,omitempty"` +} + +type AssignTask struct { + ID int64 `json:"id"` + Owner string `json:"owner"` +} + +type RenameProject struct { + From string `json:"from"` + To string `json:"to"` +} + +type AsOf struct { + AsOf string `json:"as_of,omitempty" desc:"YYYY-MM-DD; leave out for today"` +} + +type DateRange struct { + Start string `json:"start" desc:"YYYY-MM-DD"` + End string `json:"end" desc:"YYYY-MM-DD"` +} + +type Days struct { + Days int `json:"days"` +} + +type None struct{} + +type TaskResult struct { + Task store.Task `json:"task"` +} + +type TaskList struct { + Tasks []store.Task `json:"tasks"` + Count int `json:"count"` +} + +type Deleted struct { + Deleted bool `json:"deleted"` +} + +type ProjectList struct { + Projects []store.Project `json:"projects"` +} + +type Moved struct { + Moved int `json:"moved"` +} + +type Groups struct { + Groups []store.GroupCount `json:"groups"` +} + +type Throughput struct { + Days []store.DayCount `json:"days"` +} + +type User struct { + Name string `json:"name"` + Role string `json:"role" desc:"member or admin"` +} + +type UserResult struct { + User User `json:"user"` +} + +type UserList struct { + Users []User `json:"users"` +} + +// No identity is a wiring failure: stop rather than pick a default. +func scope(ctx context.Context) (auth.Identity, store.Scope, error) { if err := ctx.Err(); err != nil { - return nil, err + return auth.Identity{}, store.Scope{}, err } - - // No identity is a wiring failure: stop rather than pick a default. identity, err := auth.From(ctx) if err != nil { - return nil, err + return auth.Identity{}, store.Scope{}, err } - scope := store.Only(identity.User) if identity.Admin() { - scope = store.Everyone() + return identity, store.Everyone(), nil } + return identity, store.Only(identity.User), nil +} - switch rpc { - case taskCreate: - var request struct { - Title string `json:"title"` - Project string `json:"project"` - Priority string `json:"priority"` - DueDate string `json:"due_date"` - Tags []string `json:"tags"` - } - if err := decode(input, &request); err != nil { - return nil, err - } - // Owner comes from the identity, never from the request. - return task(app.store.Create(identity.User, request.Title, request.Project, request.Priority, request.DueDate, request.Tags)) +func (app *App) Create(ctx context.Context, request CreateTask) (TaskResult, error) { + identity, _, err := scope(ctx) + if err != nil { + return TaskResult{}, err + } + // Owner comes from the identity, never from the request. + return task(app.store.Create(identity.User, request.Title, request.Project, string(request.Priority), request.DueDate, request.Tags)) +} - case taskGet: - id, err := decodeID(input) - if err != nil { - return nil, err - } - return task(app.store.Get(scope, id)) - - case taskList: - var request struct { - Project string `json:"project"` - Status string `json:"status"` - Priority string `json:"priority"` - Tag string `json:"tag"` - Limit int `json:"limit"` - } - if err := decode(input, &request); err != nil { - return nil, err - } - return tasks(app.store.List(scope, store.Filter{ - Project: request.Project, - Status: request.Status, - Priority: request.Priority, - Tag: request.Tag, - Limit: request.Limit, - })) - - case taskUpdate: - var request struct { - ID int64 `json:"id"` - Title string `json:"title"` - Project string `json:"project"` - Priority string `json:"priority"` - DueDate string `json:"due_date"` - } - if err := decode(input, &request); err != nil { - return nil, err - } - return task(app.store.Update(scope, request.ID, request.Title, request.Project, request.Priority, request.DueDate)) +func (app *App) Get(ctx context.Context, request TaskID) (TaskResult, error) { + _, scope, err := withID(ctx, request.ID) + if err != nil { + return TaskResult{}, err + } + return task(app.store.Get(scope, request.ID)) +} - case taskComplete: - id, err := decodeID(input) - if err != nil { - return nil, err - } - return task(app.store.Complete(scope, id)) +func (app *App) List(ctx context.Context, request ListTasks) (TaskList, error) { + _, scope, err := scope(ctx) + if err != nil { + return TaskList{}, err + } + return tasks(app.store.List(scope, store.Filter{ + Project: request.Project, Status: string(request.Status), Priority: string(request.Priority), + Tag: request.Tag, Limit: request.Limit, + })) +} - case taskReopen: - id, err := decodeID(input) - if err != nil { - return nil, err - } - return task(app.store.Reopen(scope, id)) +func (app *App) Update(ctx context.Context, request UpdateTask) (TaskResult, error) { + _, scope, err := scope(ctx) + if err != nil { + return TaskResult{}, err + } + return task(app.store.Update(scope, request.ID, request.Title, request.Project, string(request.Priority), request.DueDate)) +} - case taskDelete: - id, err := decodeID(input) - if err != nil { - return nil, err - } - if err := app.store.Delete(scope, id); err != nil { - return nil, err - } - return encode(map[string]any{"deleted": true}) +func (app *App) Complete(ctx context.Context, request TaskID) (TaskResult, error) { + _, scope, err := withID(ctx, request.ID) + if err != nil { + return TaskResult{}, err + } + return task(app.store.Complete(scope, request.ID)) +} - case taskAddTag, taskRemoveTag: - var request struct { - ID int64 `json:"id"` - Tag string `json:"tag"` - } - if err := decode(input, &request); err != nil { - return nil, err - } - if rpc == taskAddTag { - return task(app.store.AddTag(scope, request.ID, request.Tag)) - } - return task(app.store.RemoveTag(scope, request.ID, request.Tag)) +func (app *App) Reopen(ctx context.Context, request TaskID) (TaskResult, error) { + _, scope, err := withID(ctx, request.ID) + if err != nil { + return TaskResult{}, err + } + return task(app.store.Reopen(scope, request.ID)) +} - case taskSearch: - var request struct { - Text string `json:"text"` - Limit int `json:"limit"` - } - if err := decode(input, &request); err != nil { - return nil, err - } - return tasks(app.store.Search(scope, request.Text, request.Limit)) +func (app *App) Delete(ctx context.Context, request TaskID) (Deleted, error) { + _, scope, err := withID(ctx, request.ID) + if err != nil { + return Deleted{}, err + } + if err := app.store.Delete(scope, request.ID); err != nil { + return Deleted{}, err + } + return Deleted{Deleted: true}, nil +} - case projectList: - if err := decode(input, &struct{}{}); err != nil { - return nil, err - } - projects, err := app.store.Projects(scope) - if err != nil { - return nil, err - } - return encode(map[string]any{"projects": projects}) +func (app *App) AddTag(ctx context.Context, request TagTask) (TaskResult, error) { + _, scope, err := scope(ctx) + if err != nil { + return TaskResult{}, err + } + return task(app.store.AddTag(scope, request.ID, request.Tag)) +} - case projectRename: - var request struct { - From string `json:"from"` - To string `json:"to"` - } - if err := decode(input, &request); err != nil { - return nil, err - } - moved, err := app.store.RenameProject(scope, request.From, request.To) - if err != nil { - return nil, err - } - return encode(map[string]any{"moved": moved}) +func (app *App) RemoveTag(ctx context.Context, request TagTask) (TaskResult, error) { + _, scope, err := scope(ctx) + if err != nil { + return TaskResult{}, err + } + return task(app.store.RemoveTag(scope, request.ID, request.Tag)) +} - case reportStatus: - if err := decode(input, &struct{}{}); err != nil { - return nil, err - } - counts, err := app.store.StatusCounts(scope) - if err != nil { - return nil, err - } - return encode(counts) +func (app *App) Search(ctx context.Context, request SearchTasks) (TaskList, error) { + _, scope, err := scope(ctx) + if err != nil { + return TaskList{}, err + } + return tasks(app.store.Search(scope, request.Text, request.Limit)) +} - case reportByProject, reportByPrio: - if err := decode(input, &struct{}{}); err != nil { - return nil, err - } - groups, err := app.store.ByProject(scope) - if rpc == reportByPrio { - groups, err = app.store.ByPriority(scope) - } - if err != nil { - return nil, err - } - return encode(map[string]any{"groups": groups}) +func (app *App) Projects(ctx context.Context, _ None) (ProjectList, error) { + _, scope, err := scope(ctx) + if err != nil { + return ProjectList{}, err + } + projects, err := app.store.Projects(scope) + return ProjectList{Projects: orEmpty(projects)}, err +} - case reportOverdue: - var request struct { - AsOf string `json:"as_of"` - } - if err := decode(input, &request); err != nil { - return nil, err - } - return tasks(app.store.Overdue(scope, request.AsOf)) +func (app *App) RenameProject(ctx context.Context, request RenameProject) (Moved, error) { + _, scope, err := scope(ctx) + if err != nil { + return Moved{}, err + } + moved, err := app.store.RenameProject(scope, request.From, request.To) + return Moved{Moved: moved}, err +} - case reportCompleted: - var request struct { - Start string `json:"start"` - End string `json:"end"` - } - if err := decode(input, &request); err != nil { - return nil, err - } - return tasks(app.store.CompletedBetween(scope, request.Start, request.End)) +func (app *App) StatusCounts(ctx context.Context, _ None) (store.StatusCounts, error) { + _, scope, err := scope(ctx) + if err != nil { + return store.StatusCounts{}, err + } + return app.store.StatusCounts(scope) +} - case reportThrough: - var request struct { - Days int `json:"days"` - } - if err := decode(input, &request); err != nil { - return nil, err - } - days, err := app.store.Throughput(scope, request.Days) - if err != nil { - return nil, err - } - return encode(map[string]any{"days": days}) +func (app *App) ByProject(ctx context.Context, _ None) (Groups, error) { + _, scope, err := scope(ctx) + if err != nil { + return Groups{}, err + } + return groups(app.store.ByProject(scope)) +} - case userMe: - if err := decode(input, &struct{}{}); err != nil { - return nil, err - } - return encode(map[string]any{"user": user{Name: identity.User, Role: string(identity.Role)}}) +func (app *App) ByPriority(ctx context.Context, _ None) (Groups, error) { + _, scope, err := scope(ctx) + if err != nil { + return Groups{}, err + } + return groups(app.store.ByPriority(scope)) +} - // Administrators only: members' registries omit these; the checks fail closed on a wiring bug. +func (app *App) Overdue(ctx context.Context, request AsOf) (TaskList, error) { + _, scope, err := scope(ctx) + if err != nil { + return TaskList{}, err + } + return tasks(app.store.Overdue(scope, request.AsOf)) +} - case userList: - if _, err := auth.RequireAdmin(ctx, "users.list"); err != nil { - return nil, err - } - if err := decode(input, &struct{}{}); err != nil { - return nil, err - } - return encode(map[string]any{"users": app.members()}) +func (app *App) CompletedBetween(ctx context.Context, request DateRange) (TaskList, error) { + _, scope, err := scope(ctx) + if err != nil { + return TaskList{}, err + } + return tasks(app.store.CompletedBetween(scope, request.Start, request.End)) +} - case taskListFor: - if _, err := auth.RequireAdmin(ctx, "tasks.listFor"); err != nil { - return nil, err - } - var request struct { - Owner string `json:"owner"` - Status string `json:"status"` - Limit int `json:"limit"` - } - if err := decode(input, &request); err != nil { - return nil, err - } - if strings.TrimSpace(request.Owner) == "" { - return nil, fmt.Errorf("owner is required") - } - return tasks(app.store.List(store.Only(request.Owner), store.Filter{ - Status: request.Status, - Limit: request.Limit, - })) +func (app *App) Throughput(ctx context.Context, request Days) (Throughput, error) { + _, scope, err := scope(ctx) + if err != nil { + return Throughput{}, err + } + days, err := app.store.Throughput(scope, request.Days) + return Throughput{Days: orEmpty(days)}, err +} - case taskAssign: - if _, err := auth.RequireAdmin(ctx, "tasks.assign"); err != nil { - return nil, err - } - var request struct { - ID int64 `json:"id"` - Owner string `json:"owner"` - } - if err := decode(input, &request); err != nil { - return nil, err - } - return task(app.store.Assign(request.ID, request.Owner)) +func (app *App) Me(ctx context.Context, _ None) (UserResult, error) { + identity, _, err := scope(ctx) + if err != nil { + return UserResult{}, err + } + return UserResult{User: User{Name: identity.User, Role: string(identity.Role)}}, nil +} - case reportByOwner: - if _, err := auth.RequireAdmin(ctx, "reports.byOwner"); err != nil { - return nil, err - } - if err := decode(input, &struct{}{}); err != nil { - return nil, err - } - groups, err := app.store.ByOwner(store.Everyone()) - if err != nil { - return nil, err - } - return encode(map[string]any{"groups": groups}) +// Administrators only: members' registries omit these, and the checks fail closed on a wiring bug. - default: - return nil, fmt.Errorf("RPC %q is not implemented", rpc) +func (app *App) Users(ctx context.Context, _ None) (UserList, error) { + if _, err := auth.RequireAdmin(ctx, "users.list"); err != nil { + return UserList{}, err } + return UserList{Users: app.members()}, nil } -type user struct { - Name string `json:"name"` - Role string `json:"role"` +func (app *App) ListFor(ctx context.Context, request ListFor) (TaskList, error) { + if _, err := auth.RequireAdmin(ctx, "tasks.listFor"); err != nil { + return TaskList{}, err + } + if strings.TrimSpace(request.Owner) == "" { + return TaskList{}, errors.New("owner is required") + } + return tasks(app.store.List(store.Only(request.Owner), store.Filter{Status: string(request.Status), Limit: request.Limit})) +} + +func (app *App) Assign(ctx context.Context, request AssignTask) (TaskResult, error) { + if _, err := auth.RequireAdmin(ctx, "tasks.assign"); err != nil { + return TaskResult{}, err + } + return task(app.store.Assign(request.ID, request.Owner)) +} + +func (app *App) ByOwner(ctx context.Context, _ None) (Groups, error) { + if _, err := auth.RequireAdmin(ctx, "reports.byOwner"); err != nil { + return Groups{}, err + } + return groups(app.store.ByOwner(store.Everyone())) } -func (app *App) members() []user { +func (app *App) members() []User { owners, err := app.store.Owners() if err != nil { - return nil + return []User{} } - members := make([]user, 0, len(owners)) + members := make([]User, 0, len(owners)) for _, owner := range owners { role := string(auth.RoleMember) if app.admins[owner] { role = string(auth.RoleAdmin) } - members = append(members, user{Name: owner, Role: role}) + members = append(members, User{Name: owner, Role: role}) } return members } -func task(item store.Task, err error) (json.RawMessage, error) { - if err != nil { - return nil, err +func withID(ctx context.Context, id int64) (auth.Identity, store.Scope, error) { + if id == 0 { + return auth.Identity{}, store.Scope{}, errors.New("id is required") } - return encode(map[string]any{"task": item}) + return scope(ctx) } -func tasks(items []store.Task, err error) (json.RawMessage, error) { - if err != nil { - return nil, err - } - return encode(map[string]any{"tasks": items, "count": len(items)}) +func task(item store.Task, err error) (TaskResult, error) { + return TaskResult{Task: item}, err +} + +func tasks(items []store.Task, err error) (TaskList, error) { + return TaskList{Tasks: orEmpty(items), Count: len(items)}, err } -func encode(value any) (json.RawMessage, error) { - return json.Marshal(value) +func groups(items []store.GroupCount, err error) (Groups, error) { + return Groups{Groups: orEmpty(items)}, err } -func decodeID(input []byte) (int64, error) { - var request struct { - ID int64 `json:"id"` +// The proto path encodes with encoding/json, so a nil list would reach the program as null. +func orEmpty[T any](items []T) []T { + if items == nil { + return []T{} } - if err := decode(input, &request); err != nil { - return 0, err + return items +} + +// Execute serves the proto registry's RPC paths with the same typed methods. +// ponytail: hand-written routing until registry.Source dispatches generated services. +func (app *App) Execute(ctx context.Context, rpc string, input json.RawMessage) (json.RawMessage, error) { + handler, ok := app.protoRoutes()[rpc] + if !ok { + return nil, fmt.Errorf("RPC %q is not implemented", rpc) } - if request.ID == 0 { - return 0, fmt.Errorf("id is required") + return handler(ctx, input) +} + +type route func(context.Context, json.RawMessage) (json.RawMessage, error) + +func (app *App) protoRoutes() map[string]route { + return map[string]route{ + "task.v1.TaskService/Create": serve(app.Create), + "task.v1.TaskService/Get": serve(app.Get), + "task.v1.TaskService/List": serve(app.List), + "task.v1.TaskService/Update": serve(app.Update), + "task.v1.TaskService/Complete": serve(app.Complete), + "task.v1.TaskService/Reopen": serve(app.Reopen), + "task.v1.TaskService/Delete": serve(app.Delete), + "task.v1.TaskService/AddTag": serve(app.AddTag), + "task.v1.TaskService/RemoveTag": serve(app.RemoveTag), + "task.v1.TaskService/Search": serve(app.Search), + "task.v1.TaskService/ListFor": serve(app.ListFor), + "task.v1.TaskService/Assign": serve(app.Assign), + "task.v1.ProjectService/List": serve(app.Projects), + "task.v1.ProjectService/Rename": serve(app.RenameProject), + "task.v1.ReportService/StatusCounts": serve(app.StatusCounts), + "task.v1.ReportService/ByProject": serve(app.ByProject), + "task.v1.ReportService/ByPriority": serve(app.ByPriority), + "task.v1.ReportService/Overdue": serve(app.Overdue), + "task.v1.ReportService/CompletedBetween": serve(app.CompletedBetween), + "task.v1.ReportService/Throughput": serve(app.Throughput), + "task.v1.ReportService/ByOwner": serve(app.ByOwner), + "user.v1.UserService/Me": serve(app.Me), + "user.v1.UserService/List": serve(app.Users), } - return request.ID, nil } // decode rejects unknown fields so a model learns of invented fields on the first call. -func decode(input []byte, target any) error { - if len(bytes.TrimSpace(input)) == 0 { - input = []byte("{}") - } - decoder := json.NewDecoder(bytes.NewReader(input)) - decoder.DisallowUnknownFields() - if err := decoder.Decode(target); err != nil { - return fmt.Errorf("decode input: %w", err) - } - if err := decoder.Decode(&struct{}{}); err != io.EOF { - return fmt.Errorf("decode input: unexpected trailing data") +func serve[In, Out any](handler func(context.Context, In) (Out, error)) route { + return func(ctx context.Context, input json.RawMessage) (json.RawMessage, error) { + if len(bytes.TrimSpace(input)) == 0 { + input = []byte("{}") + } + var request In + decoder := json.NewDecoder(bytes.NewReader(input)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&request); err != nil { + return nil, fmt.Errorf("decode input: %w", err) + } + if err := decoder.Decode(&struct{}{}); err != io.EOF { + return nil, errors.New("decode input: unexpected trailing data") + } + response, err := handler(ctx, request) + if err != nil { + return nil, err + } + return json.Marshal(response) } - return nil } diff --git a/examples/taskreport/app/app_test.go b/examples/taskreport/app/app_test.go index a9e60f8..90d75ec 100644 --- a/examples/taskreport/app/app_test.go +++ b/examples/taskreport/app/app_test.go @@ -9,6 +9,7 @@ import ( "time" "github.com/mukezhz/codemode/codemode" + "github.com/mukezhz/codemode/codemode/sourcetest" "github.com/mukezhz/codemode/sandbox" "github.com/mukezhz/codemode/sandbox/goja" @@ -407,3 +408,81 @@ func TestEmptyResultsAreArrays(t *testing.T) { t.Fatalf("value = %#v, want 0", value) } } + +func goSource(t *testing.T, tasks *store.Store) codemode.Source { + t.Helper() + source, err := app.New(tasks, "grace").Source() + if err != nil { + t.Fatal(err) + } + return source +} + +func TestGoSourcePassesTheContract(t *testing.T) { + sourcetest.Run(t, goSource(t, nil)) +} + +// The Go functions and the protos are two descriptions of one surface; neither may drift. +func TestGoAndProtoSourcesDeclareTheSameSurface(t *testing.T) { + fromProto := map[string]capability.Capability{} + for _, item := range full(t).Capabilities { + fromProto[item.Name] = item + } + fromGo := goSource(t, nil).Registry.Capabilities + if len(fromGo) != len(fromProto) { + t.Fatalf("go declares %d capabilities, proto %d", len(fromGo), len(fromProto)) + } + for _, item := range fromGo { + proto, ok := fromProto[item.Name] + if !ok { + t.Errorf("%s is not in the protos", item.Name) + continue + } + if item.Description != proto.Description || item.ReadOnly != proto.ReadOnly || item.NeedsApproval != proto.NeedsApproval || + strings.Join(item.Roles, ",") != strings.Join(proto.Roles, ",") { + t.Errorf("%s differs:\n go %q read=%v approval=%v roles=%v\n proto %q read=%v approval=%v roles=%v", item.Name, + item.Description, item.ReadOnly, item.NeedsApproval, item.Roles, + proto.Description, proto.ReadOnly, proto.NeedsApproval, proto.Roles) + } + for field := range proto.Input.Fields { + if _, ok := item.Input.Fields[field]; !ok { + t.Errorf("%s: input field %s is missing from the Go struct", item.Name, field) + } + } + } +} + +func TestGoSourceRunsTheWholeWorkflow(t *testing.T) { + tasks, err := store.Open(":memory:") + if err != nil { + t.Fatal(err) + } + tasks.SetClock(func() time.Time { return time.Date(2026, 8, 15, 12, 0, 0, 0, time.UTC) }) + t.Cleanup(func() { tasks.Close() }) + mode, err := codemode.FromSource(goSource(t, tasks), capability.Caller{Roles: []string{string(auth.RoleMember)}}) + if err != nil { + t.Fatal(err) + } + ctx := auth.NewContext(context.Background(), auth.Identity{User: "ada", Role: auth.RoleMember}) + + value := run(t, ctx, mode, ` + codemode.execute("tasks.create", { title: "Write docs", project: "docs", priority: "high", due_date: "2026-08-10" }); + const second = codemode.execute("tasks.create", { title: "Ship it", priority: "low" }).task; + codemode.execute("tasks.complete", { id: second.id }); + const counts = codemode.execute("reports.statusCounts", {}); + return counts.open + " open, " + counts.completed + " done, " + codemode.execute("reports.overdue", {}).tasks.length + " overdue"; + `) + if value != "1 open, 1 done, 1 overdue" { + t.Fatalf("answer = %#v", value) + } + + runner, err := goja.New(sandbox.Options{Timeout: 5 * time.Second}) + if err != nil { + t.Fatal(err) + } + defer runner.Close() + if _, err := runner.Run(ctx, mode, `return codemode.execute("tasks.create", { title: "x", priority: "urgent" });`); err == nil || + !strings.Contains(err.Error(), "want one of low, medium, high") { + t.Fatalf("an invalid priority reached the store: %v", err) + } +} diff --git a/examples/taskreport/gen/task/v1/task.pb.go b/examples/taskreport/gen/task/v1/task.pb.go index 0122d4a..1bdafd9 100644 --- a/examples/taskreport/gen/task/v1/task.pb.go +++ b/examples/taskreport/gen/task/v1/task.pb.go @@ -1623,15 +1623,15 @@ const file_task_proto_rawDesc = "" + "\x04date\x18\x01 \x01(\tR\x04date\x12\x1c\n" + "\tcompleted\x18\x02 \x01(\x05R\tcompleted\";\n" + "\x12ThroughputResponse\x12%\n" + - "\x04days\x18\x01 \x03(\v2\x11.task.v1.DayCountR\x04days2\xf7\r\n" + + "\x04days\x18\x01 \x03(\v2\x11.task.v1.DayCountR\x04days2\xaf\x0e\n" + "\vTaskService\x12\xb4\x01\n" + "\x06Create\x12\x1a.task.v1.CreateTaskRequest\x1a\x15.task.v1.TaskResponse\"w\x82\xb5\x18sCreates a task. Title is required. Priority is low, medium, or high and defaults to medium. Due date is YYYY-MM-DD.\x12a\n" + "\x03Get\x12\x17.task.v1.GetTaskRequest\x1a\x15.task.v1.TaskResponse\"*\x82\xb5\x18#Returns one task by its numeric ID.\x90\x02\x01\x12\xc7\x01\n" + "\x04List\x12\x19.task.v1.ListTasksRequest\x1a\x19.task.v1.TaskListResponse\"\x88\x01\x82\xb5\x18\x80\x01Lists tasks, newest first. Every filter is optional and they combine: status is open or completed, and tag matches a single tag.\x90\x02\x01\x12\xc3\x01\n" + "\x06Update\x12\x1a.task.v1.UpdateTaskRequest\x1a\x15.task.v1.TaskResponse\"\x85\x01\x82\xb5\x18\x80\x01Changes a task's title, project, priority, or due date. Only the fields you set are written; the rest keep their current values.\x12\xa7\x01\n" + "\bComplete\x12\x16.task.v1.TaskIDRequest\x1a\x15.task.v1.TaskResponse\"l\x82\xb5\x18hMarks a task completed, recording the completion date. Completing an already completed task is an error.\x12~\n" + - "\x06Reopen\x12\x16.task.v1.TaskIDRequest\x1a\x15.task.v1.TaskResponse\"E\x82\xb5\x18AMarks a completed task open again and clears its completion date.\x12d\n" + - "\x06Delete\x12\x16.task.v1.TaskIDRequest\x1a\x1b.task.v1.DeleteTaskResponse\"%\x82\xb5\x18!Deletes a task permanently by ID.\x12|\n" + + "\x06Reopen\x12\x16.task.v1.TaskIDRequest\x1a\x15.task.v1.TaskResponse\"E\x82\xb5\x18AMarks a completed task open again and clears its completion date.\x12\x9b\x01\n" + + "\x06Delete\x12\x16.task.v1.TaskIDRequest\x1a\x1b.task.v1.DeleteTaskResponse\"\\\x82\xb5\x18TDeletes a task permanently by ID. The user approves each deletion before it happens.\x98\xb5\x18\x01\x12|\n" + "\x06AddTag\x12\x13.task.v1.TagRequest\x1a\x15.task.v1.TaskResponse\"F\x82\xb5\x18BAdds a tag to a task. Adding a tag it already has changes nothing.\x12W\n" + "\tRemoveTag\x12\x13.task.v1.TagRequest\x1a\x15.task.v1.TaskResponse\"\x1e\x82\xb5\x18\x1aRemoves a tag from a task.\x12\x8d\x01\n" + "\x06Search\x12\x1b.task.v1.SearchTasksRequest\x1a\x19.task.v1.TaskListResponse\"K\x82\xb5\x18DFinds tasks whose title contains the given text, case-insensitively.\x90\x02\x01\x12\xb7\x01\n" + diff --git a/examples/taskreport/main.go b/examples/taskreport/main.go index 03e800b..0bb19fd 100644 --- a/examples/taskreport/main.go +++ b/examples/taskreport/main.go @@ -2,6 +2,7 @@ package main import ( "context" + "errors" "flag" "fmt" "os" @@ -52,6 +53,7 @@ func main() { "comma-separated capability names to make admin-only at runtime, for testing denial without editing the protos") flag.StringVar(&config.logLevel, "log", "info", "debug, info, warn, or error; debug shows the prompt, the program, and every capability call") flag.StringVar(&config.audit, "audit", "", "append one JSON line per capability call to this file when serving") + flag.StringVar(&config.source, "source", "go", "where capabilities come from: go (typed functions in app/) or proto (proto/*.proto)") flag.Parse() if err := run(context.Background(), config); err != nil { @@ -78,6 +80,7 @@ type config struct { logLevel string audit string restrict string + source string } func run(ctx context.Context, config config) error { @@ -105,20 +108,21 @@ func run(ctx context.Context, config config) error { identity := auth.Identity{User: config.user, Role: role} ctx = auth.NewContext(ctx, identity) - full, err := capabilities() + source, err := capabilities(config, tasks) if err != nil { return err } - full, err = restrict(full, config.restrict) + full, err := restrict(source.Registry, config.restrict) if err != nil { return err } + source.Registry = full // A member's runtime lacks admin capabilities entirely, not just hidden from the model. allowed := forRole(full, identity) // Search shapes what the model sees; only the registry is a security boundary. - mode, err := codemode.New(allowed, search.New(allowed), app.New(tasks, adminsOf(config)...).Execute) + mode, err := codemode.New(allowed, search.New(allowed), source.Execute) if err != nil { return err } @@ -143,7 +147,7 @@ func run(ctx context.Context, config config) error { if config.apiKey == "" && config.baseURL == "" { if config.serve != "" { - return serve(ctx, config, tasks, full, nil) + return serve(ctx, config, tasks, source, nil) } return offline(ctx, mode, runner, config) } @@ -160,7 +164,7 @@ func run(ctx context.Context, config config) error { fmt.Printf("model\n %s at %s\n\n", model.Name(), endpointLabel(config.baseURL)) if config.serve != "" { - return serve(ctx, config, tasks, full, model) + return serve(ctx, config, tasks, source, model) } result, err := agent.Run(ctx, mode, model, config.request, agent.Options{ @@ -170,6 +174,15 @@ func run(ctx context.Context, config config) error { Instructions: strings.TrimSpace(identity.Instructions() + "\n" + config.instructions), }) report(result, config.verbose, runner) + var pending *agent.Pending + if errors.As(err, &pending) { + fmt.Println("held for approval, nothing below has run") + for _, call := range pending.Calls { + fmt.Printf(" %s %s\n", call.Name, call.Input) + } + fmt.Println("\napprove changes like these in the web app: -serve :8080") + return nil + } if err != nil { return err } @@ -184,16 +197,29 @@ func envFile() string { return "examples/taskreport/.env" } -func capabilities() (capability.Registry, error) { - tasks, err := coderegistry.FromFiles(taskv1.File_task_proto) +// Both sources describe the same 23 capabilities with the same access; a test holds them together. +func capabilities(config config, tasks *store.Store) (codemode.Source, error) { + application := app.New(tasks, adminsOf(config)...) + switch config.source { + case "go": + return application.Source() + case "proto": + registry, err := protoRegistry() + return codemode.Source{Registry: registry, Execute: application.Execute}, err + } + return codemode.Source{}, fmt.Errorf("-source must be go or proto, not %q", config.source) +} + +func protoRegistry() (capability.Registry, error) { + taskFiles, err := coderegistry.FromFiles(taskv1.File_task_proto) if err != nil { return capability.Registry{}, err } - users, err := coderegistry.FromFiles(userv1.File_user_proto) + userFiles, err := coderegistry.FromFiles(userv1.File_user_proto) if err != nil { return capability.Registry{}, err } - return capability.Merge(tasks, users) + return capability.Merge(taskFiles, userFiles) } func restrict(full capability.Registry, names string) (capability.Registry, error) { diff --git a/examples/taskreport/proto/task.proto b/examples/taskreport/proto/task.proto index 444a2d6..df21374 100644 --- a/examples/taskreport/proto/task.proto +++ b/examples/taskreport/proto/task.proto @@ -45,7 +45,9 @@ service TaskService { } rpc Delete(TaskIDRequest) returns (DeleteTaskResponse) { - option (codemode.description) = "Deletes a task permanently by ID."; + option (codemode.description) = "Deletes a task permanently by ID. The user approves each deletion before it happens."; + // The program records the deletion; it runs only once the user approves the plan. + option (codemode.needs_approval) = true; } rpc AddTag(TagRequest) returns (TaskResponse) { diff --git a/examples/taskreport/serve.go b/examples/taskreport/serve.go index 41b8dc7..7fa5a38 100644 --- a/examples/taskreport/serve.go +++ b/examples/taskreport/serve.go @@ -13,7 +13,7 @@ import ( "strings" "time" - "github.com/mukezhz/codemode/capability" + "github.com/mukezhz/codemode/codemode" "github.com/mukezhz/codemode/llm" "github.com/mukezhz/codemode/sandbox" @@ -42,7 +42,7 @@ func serve( ctx context.Context, config config, tasks *store.Store, - full capability.Registry, + source codemode.Source, model llm.Client, ) error { assets, err := web.Assets() @@ -69,7 +69,8 @@ func serve( handler, err := server.New(server.Options{ Store: tasks, - Full: full, + Full: source.Registry, + Execute: source.Execute, Admins: []string{"grace"}, Model: model, Runner: chatRunner, diff --git a/examples/taskreport/server/approval_test.go b/examples/taskreport/server/approval_test.go new file mode 100644 index 0000000..3aa4452 --- /dev/null +++ b/examples/taskreport/server/approval_test.go @@ -0,0 +1,104 @@ +package server_test + +import ( + "net/http" + "strconv" + "testing" + + "github.com/mukezhz/codemode/examples/taskreport/app" + "github.com/mukezhz/codemode/examples/taskreport/server" + "github.com/mukezhz/codemode/examples/taskreport/store" +) + +func fromGo(t *testing.T) func(*server.Options) { + return func(options *server.Options) { + source, err := app.New(options.Store, options.Admins...).Source() + if err != nil { + t.Fatal(err) + } + options.Full, options.Execute = source.Registry, source.Execute + } +} + +func adasTasks(t *testing.T, handler http.Handler) []store.Task { + t.Helper() + return decode[struct { + Tasks []store.Task `json:"tasks"` + }](t, do(t, handler, "GET", "/api/tasks", "", "ada", "member")).Tasks +} + +type chatPending struct { + Pending *struct { + ID string `json:"id"` + Calls []struct { + Name string `json:"name"` + } `json:"calls"` + } `json:"pending"` +} + +func TestChatHoldsADeleteUntilTheUserApprovesIt(t *testing.T) { + for name, configure := range map[string][]func(*server.Options){"proto": nil, "go": {fromGo(t)}} { + t.Run(name, func(t *testing.T) { + author := &model{program: ` + const { tasks } = codemode.execute("tasks.list", { status: "open" }); + for (const task of tasks) codemode.execute("tasks.delete", { id: task.id }); + return "deleted " + tasks.length;`} + handler := newServer(t, author, configure...) + before := len(adasTasks(t, handler)) + + response := do(t, handler, "POST", "/api/chat", `{"request":"delete my open tasks"}`, "ada", "member") + if response.Code != http.StatusOK { + t.Fatalf("chat returned %d: %s", response.Code, response.Body) + } + held := decode[chatPending](t, response).Pending + if held == nil || held.ID == "" || len(held.Calls) != 2 || held.Calls[0].Name != "tasks.delete" { + t.Fatalf("pending = %+v; want both deletes held", held) + } + if len(adasTasks(t, handler)) != before { + t.Fatal("a delete ran before it was approved") + } + + if response := do(t, handler, "POST", "/api/plans/"+held.ID+"/approve", "", "linus", "member"); response.Code != http.StatusNotFound { + t.Fatalf("another user approved ada's plan: %d", response.Code) + } + if response := do(t, handler, "POST", "/api/plans/"+held.ID+"/approve", "", "ada", "member"); response.Code != http.StatusOK { + t.Fatalf("approve returned %d: %s", response.Code, response.Body) + } + if left := len(adasTasks(t, handler)); left != before-2 { + t.Fatalf("%d tasks left, want %d", left, before-2) + } + if response := do(t, handler, "POST", "/api/plans/"+held.ID+"/approve", "", "ada", "member"); response.Code != http.StatusNotFound { + t.Fatalf("a plan applied twice: %d", response.Code) + } + }) + } +} + +func TestARejectedPlanNeverRuns(t *testing.T) { + author := &model{program: `codemode.execute("tasks.delete", { id: codemode.execute("tasks.list", {}).tasks[0].id }); return "ok";`} + handler := newServer(t, author, fromGo(t)) + before := len(adasTasks(t, handler)) + + held := decode[chatPending](t, do(t, handler, "POST", "/api/chat", `{"request":"delete one"}`, "ada", "member")).Pending + if held == nil { + t.Fatal("nothing was held") + } + if response := do(t, handler, "POST", "/api/plans/"+held.ID+"/reject", "", "ada", "member"); response.Code != http.StatusOK { + t.Fatalf("reject returned %d: %s", response.Code, response.Body) + } + if response := do(t, handler, "POST", "/api/plans/"+held.ID+"/approve", "", "ada", "member"); response.Code != http.StatusNotFound { + t.Fatalf("a rejected plan was approved: %d", response.Code) + } + if len(adasTasks(t, handler)) != before { + t.Fatal("a rejected delete ran") + } +} + +func TestTheBoardDeleteButtonIsItsOwnApproval(t *testing.T) { + handler := newServer(t, nil, fromGo(t)) + tasks := adasTasks(t, handler) + response := do(t, handler, "DELETE", "/api/tasks/"+strconv.FormatInt(tasks[0].ID, 10), "", "ada", "member") + if response.Code != http.StatusOK || len(adasTasks(t, handler)) != len(tasks)-1 { + t.Fatalf("board delete returned %d: %s", response.Code, response.Body) + } +} diff --git a/examples/taskreport/server/server.go b/examples/taskreport/server/server.go index 9d29b62..d6ff468 100644 --- a/examples/taskreport/server/server.go +++ b/examples/taskreport/server/server.go @@ -29,8 +29,12 @@ import ( ) type Options struct { - Store *store.Store - Full capability.Registry + Store *store.Store + Full capability.Registry + // Serves Full's RPCs; nil uses the app's proto routes, so Full must be the proto registry. + Execute codemode.ExecuteFunc + // Keeps chat writes that need approval; nil keeps them in memory. + Plans agent.PlanStore Admins []string Model llm.Client Runner sandbox.Runner @@ -50,7 +54,6 @@ type Options struct { type Server struct { options Options - app *app.App log *slog.Logger fairness *fairness audit *auditor @@ -85,9 +88,16 @@ func New(options Options) (*Server, error) { } options.Runner = trace.Runner(options.Runner, logger, options.Programs) + application := app.New(options.Store, options.Admins...) + if options.Execute == nil { + options.Execute = application.Execute + } + if options.Plans == nil { + options.Plans = agent.NewMemoryPlans(0) + } + return &Server{ options: options, - app: app.New(options.Store, options.Admins...), log: logger, fairness: &fairness{perMinute: options.ChatsPerMinute, concurrent: options.ChatsAtOnce}, audit: audit, @@ -106,6 +116,8 @@ func (server *Server) Handler() http.Handler { mux.HandleFunc("GET /api/summary", server.summary) mux.HandleFunc("POST /api/chat", server.fairness.guard(server.chat)) mux.HandleFunc("POST /api/chat/stream", server.fairness.guard(server.chatStream)) + mux.HandleFunc("POST /api/plans/{id}/approve", server.approvePlan) + mux.HandleFunc("POST /api/plans/{id}/reject", server.rejectPlan) mux.Handle("/", server.assets()) @@ -136,7 +148,7 @@ func (server *Server) scoped(ctx context.Context) (codemode.CodeMode, capability } // Policy comes from (codemode.roles) in the protos, not a list here. allowed := server.options.Full.ForRole(string(identity.Role)) - mode, err := codemode.New(allowed, search.New(allowed), server.app.Execute) + mode, err := codemode.New(allowed, search.New(allowed), server.options.Execute) if err != nil { return nil, capability.Registry{}, err } @@ -226,7 +238,9 @@ func (server *Server) execute(writer http.ResponseWriter, request *http.Request, fail(writer, http.StatusBadRequest, err) return } - output, err := mode.Execute(request.Context(), name, encoded) + // A button the user pressed is their approval, so a delete from the board runs at once. + approved := codemode.WithRecorder(request.Context(), &codemode.Recorder{Approved: true}) + output, err := mode.Execute(approved, name, encoded) if err != nil { fail(writer, http.StatusBadRequest, err) return @@ -240,7 +254,9 @@ type chatRequest struct { } type chatResponse struct { - Document view.Document `json:"document"` + Document view.Document `json:"document"` + // Set when the program reached a write that needs approval; nothing it holds has run. + Pending *pendingPlan `json:"pending,omitempty"` Program string `json:"program"` Attempts int `json:"attempts"` Used []capability.Match `json:"used"` @@ -355,7 +371,23 @@ func (server *Server) answer( CacheCaller: string(identity.Role), OnChunk: onChunk, OnCall: server.audit.hook(identity), + Plans: server.options.Plans, + PlanOwner: identity.User, }) + var held *agent.Pending + if errors.As(err, &held) { + log.Info("step=answer", "held", len(held.Calls), "attempts", result.Attempts) + return chatResponse{ + Document: view.Document{Blocks: []view.Block{{Type: view.KindText, + Text: "This needs your approval before it changes anything."}}}, + Pending: newPendingPlan(held), + Program: result.Source, + Attempts: result.Attempts, + Used: result.Matches, + Took: time.Since(started).Round(time.Millisecond).String(), + Timing: result.Timing, + }, http.StatusOK, nil + } if err != nil { server.log.Error("chat failed", "request", body.Request, "error", err, "program", result.Source) return chatResponse{}, http.StatusBadGateway, err @@ -391,6 +423,73 @@ func (server *Server) answer( }, http.StatusOK, nil } +type pendingPlan struct { + ID string `json:"id"` + Calls []plannedCall `json:"calls"` +} + +type plannedCall struct { + Name string `json:"name"` + Input json.RawMessage `json:"input"` +} + +func newPendingPlan(held *agent.Pending) *pendingPlan { + plan := &pendingPlan{ID: held.ID, Calls: []plannedCall{}} + for _, call := range held.Calls { + plan.Calls = append(plan.Calls, plannedCall{Name: call.Name, Input: call.Input}) + } + return plan +} + +// approvePlan runs a held plan once, for the user who was shown it, against +// their current capabilities: a role lost since then is a role lost now. +func (server *Server) approvePlan(writer http.ResponseWriter, request *http.Request) { + identity, err := auth.From(request.Context()) + if err != nil { + fail(writer, http.StatusUnauthorized, err) + return + } + mode, _, err := server.scoped(request.Context()) + if err != nil { + fail(writer, http.StatusUnauthorized, err) + return + } + calls, err := agent.ApplyPlan(request.Context(), mode, server.options.Plans, identity.User, request.PathValue("id")) + if hook := server.audit.hook(identity); hook != nil { + for _, call := range calls { + hook(call) + } + } + if errors.Is(err, agent.ErrNoPlan) { + fail(writer, http.StatusNotFound, err) + return + } + ran := make([]map[string]string, 0, len(calls)) + for _, call := range calls { + ran = append(ran, map[string]string{"name": call.Name, "error": call.Error}) + } + if err != nil { + writer.Header().Set("Content-Type", "application/json") + writer.WriteHeader(http.StatusBadRequest) + json.NewEncoder(writer).Encode(map[string]any{"error": err.Error(), "calls": ran}) + return + } + send(writer, map[string]any{"calls": ran}) +} + +func (server *Server) rejectPlan(writer http.ResponseWriter, request *http.Request) { + identity, err := auth.From(request.Context()) + if err != nil { + fail(writer, http.StatusUnauthorized, err) + return + } + if _, err := server.options.Plans.Take(request.Context(), identity.User, request.PathValue("id")); err != nil { + fail(writer, http.StatusNotFound, err) + return + } + send(writer, map[string]bool{"rejected": true}) +} + func (server *Server) assets() http.Handler { if server.options.Assets == nil { return http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { diff --git a/examples/taskreport/web/dist/assets/chat-CmZZLyt2.js b/examples/taskreport/web/dist/assets/chat-CmZZLyt2.js deleted file mode 100644 index 58ae782..0000000 --- a/examples/taskreport/web/dist/assets/chat-CmZZLyt2.js +++ /dev/null @@ -1 +0,0 @@ -import{j as e,r as g,a as w}from"./index-D4Un-2Pf.js";function y({document:s}){return s.unavailable?e.jsx("article",{className:"doc refusal",children:e.jsx("p",{className:"refusal-text",children:s.unavailable})}):e.jsxs("article",{className:"doc",children:[s.title&&e.jsx("h2",{className:"doc-title",children:s.title}),(s.blocks??[]).map((a,t)=>e.jsx($,{block:a},t))]})}function $({block:s}){switch(s.type){case"stats":return e.jsxs("section",{className:"block",children:[e.jsx(x,{text:s.heading}),e.jsx("div",{className:"stats",children:s.items.map((a,t)=>e.jsxs("div",{className:`stat tone-${a.tone??"none"}`,children:[e.jsx("span",{className:"stat-value",children:v(a.value)}),e.jsx("span",{className:"stat-label",children:a.label})]},t))})]});case"bar":return e.jsxs("section",{className:"block",children:[e.jsx(x,{text:s.heading}),e.jsx(k,{series:s.series})]});case"line":return e.jsxs("section",{className:"block",children:[e.jsx(x,{text:s.heading}),e.jsx(S,{series:s.series})]});case"table":return e.jsxs("section",{className:"block",children:[e.jsx(x,{text:s.heading}),e.jsx("div",{className:"table-scroll",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsx("tr",{children:s.columns.map(a=>e.jsx("th",{children:a},a))})}),e.jsx("tbody",{children:s.rows.map((a,t)=>e.jsx("tr",{children:a.map((l,i)=>e.jsx("td",{children:l},i))},t))})]})})]});case"text":return e.jsxs("section",{className:"block",children:[e.jsx(x,{text:s.heading}),e.jsx("p",{className:"prose",children:s.text})]})}}function x({text:s}){return s?e.jsx("h3",{className:"block-heading",children:s}):null}function k({series:s}){const a=Math.max(...s.map(t=>t.value),1);return e.jsx("div",{className:"bars",children:s.map((t,l)=>e.jsxs("div",{className:"bar-row",children:[e.jsx("span",{className:"bar-label",title:t.label,children:t.label}),e.jsx("div",{className:"bar-track",children:e.jsx("div",{className:"bar-fill",style:{width:`${t.value/a*100}%`}})}),e.jsx("span",{className:"bar-value",children:v(t.value)})]},l))})}function S({series:s}){const i=Math.max(...s.map(c=>c.value),1),u=s.length>1?584/(s.length-1):0,p=(c,m)=>{const N=8+c*u,f=152-m/i*144;return[N,f]},r=s.map((c,m)=>p(m,c.value)),n=r.map(([c,m],N)=>`${N===0?"M":"L"}${c},${m}`).join(" "),h=`${n} L${r[r.length-1][0]},152 L${r[0][0]},152 Z`,[d,o]=r[r.length-1];return e.jsxs("div",{className:"line",children:[e.jsxs("svg",{viewBox:"0 0 600 160",role:"img","aria-label":"trend over time",children:[e.jsx("path",{d:h,className:"line-area"}),e.jsx("path",{d:n,className:"line-stroke"}),e.jsx("circle",{cx:d,cy:o,r:"4",className:"line-dot"})]}),e.jsxs("div",{className:"line-labels",children:[e.jsx("span",{children:s[0]?.label}),e.jsx("span",{children:s[s.length-1]?.label})]})]})}function v(s){return Number.isInteger(s)?String(s):s.toFixed(1)}const q=["give me a status report across every project","what is overdue, and which of it is high priority?","how much did we finish this week compared to what is still open?","chart my completions over the last two weeks","what should I work on next?"];function C(){const[s,a]=g.useState(""),[t,l]=g.useState([]),[i,u]=g.useState(!1);async function p(r){const n=r.trim();if(!(!n||i)){a(""),u(!0),l(h=>[...h,{request:n}]);try{let h="";const d=await w.chatStream(n,o=>{h+=o,l(c=>b(c,{request:n,writing:h}))});l(o=>b(o,{request:n,result:d}))}catch(h){l(d=>b(d,{request:n,error:h.message}))}finally{u(!1)}}}return e.jsxs("div",{className:"ask",children:[t.length===0&&e.jsxs("div",{className:"suggestions",children:[e.jsx("p",{className:"hint",children:"One question becomes one program. It calls several capabilities, does the filtering and totalling in the sandbox, and returns a document to render — not a sentence."}),q.map(r=>e.jsx("button",{className:"suggestion",onClick:()=>p(r),children:r},r))]}),e.jsx("div",{className:"turns",children:t.map((r,n)=>e.jsx(F,{turn:r,pending:i&&n===t.length-1},n))}),e.jsxs("form",{className:"composer",onSubmit:r=>{r.preventDefault(),p(s)},children:[e.jsx("input",{value:s,onChange:r=>a(r.target.value),placeholder:"Ask about your work…","aria-label":"Your question",disabled:i}),e.jsx("button",{type:"submit",disabled:i||!s.trim(),children:i?"Thinking…":"Ask"})]})]})}function j(s){return s<1e6?`${Math.round(s/1e3)}µs`:`${(s/1e6).toFixed(0)}ms`}function F({turn:s,pending:a}){const[t,l]=g.useState(!1);return e.jsxs("section",{className:"turn",children:[e.jsx("p",{className:"question",children:s.request}),a&&!s.result&&!s.error&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"thinking",children:"Writing a program…"}),s.writing&&e.jsx("pre",{className:"program writing",children:s.writing})]}),s.error&&e.jsx("p",{className:"error",children:s.error}),s.result&&e.jsxs(e.Fragment,{children:[e.jsx(y,{document:s.result.document}),e.jsxs("div",{className:"provenance",children:[e.jsxs("button",{className:"link",onClick:()=>l(i=>!i),children:[t?"Hide":"Show"," the program"]}),e.jsxs("span",{className:"muted",children:[s.result.cached?"reused a cached program":`${s.result.attempts} attempt${s.result.attempts===1?"":"s"}`," ","· ",s.result.took," · ",s.result.used.length," capabilities offered"]})]}),t&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"muted",children:["writing ",j(s.result.timing.Generate)," · searching"," ",j(s.result.timing.Search)," · cache ",j(s.result.timing.Cache)," · running"," ",j(s.result.timing.Run)]}),e.jsx("pre",{className:"program",children:s.result.program}),e.jsx("ul",{className:"offered",children:s.result.used.map(i=>e.jsxs("li",{children:[e.jsx("code",{children:i.capability.name})," ",i.capability.description]},i.capability.name))})]})]})]})}function b(s,a){return[...s.slice(0,-1),a]}export{C as component}; diff --git a/examples/taskreport/web/dist/assets/chat-fahH1l62.js b/examples/taskreport/web/dist/assets/chat-fahH1l62.js new file mode 100644 index 0000000..6e197e7 --- /dev/null +++ b/examples/taskreport/web/dist/assets/chat-fahH1l62.js @@ -0,0 +1 @@ +import{j as e,r as m,a as v}from"./index-D-DTohO0.js";function y({document:s}){return s.unavailable?e.jsx("article",{className:"doc refusal",children:e.jsx("p",{className:"refusal-text",children:s.unavailable})}):e.jsxs("article",{className:"doc",children:[s.title&&e.jsx("h2",{className:"doc-title",children:s.title}),(s.blocks??[]).map((a,t)=>e.jsx(k,{block:a},t))]})}function k({block:s}){switch(s.type){case"stats":return e.jsxs("section",{className:"block",children:[e.jsx(j,{text:s.heading}),e.jsx("div",{className:"stats",children:s.items.map((a,t)=>e.jsxs("div",{className:`stat tone-${a.tone??"none"}`,children:[e.jsx("span",{className:"stat-value",children:b(a.value)}),e.jsx("span",{className:"stat-label",children:a.label})]},t))})]});case"bar":return e.jsxs("section",{className:"block",children:[e.jsx(j,{text:s.heading}),e.jsx($,{series:s.series})]});case"line":return e.jsxs("section",{className:"block",children:[e.jsx(j,{text:s.heading}),e.jsx(S,{series:s.series})]});case"table":return e.jsxs("section",{className:"block",children:[e.jsx(j,{text:s.heading}),e.jsx("div",{className:"table-scroll",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsx("tr",{children:s.columns.map(a=>e.jsx("th",{children:a},a))})}),e.jsx("tbody",{children:s.rows.map((a,t)=>e.jsx("tr",{children:a.map((r,i)=>e.jsx("td",{children:r},i))},t))})]})})]});case"text":return e.jsxs("section",{className:"block",children:[e.jsx(j,{text:s.heading}),e.jsx("p",{className:"prose",children:s.text})]})}}function j({text:s}){return s?e.jsx("h3",{className:"block-heading",children:s}):null}function $({series:s}){const a=Math.max(...s.map(t=>t.value),1);return e.jsx("div",{className:"bars",children:s.map((t,r)=>e.jsxs("div",{className:"bar-row",children:[e.jsx("span",{className:"bar-label",title:t.label,children:t.label}),e.jsx("div",{className:"bar-track",children:e.jsx("div",{className:"bar-fill",style:{width:`${t.value/a*100}%`}})}),e.jsx("span",{className:"bar-value",children:b(t.value)})]},r))})}function S({series:s}){const i=Math.max(...s.map(d=>d.value),1),h=s.length>1?584/(s.length-1):0,c=(d,p)=>{const N=8+d*h,f=152-p/i*144;return[N,f]},n=s.map((d,p)=>c(p,d.value)),l=n.map(([d,p],N)=>`${N===0?"M":"L"}${d},${p}`).join(" "),o=`${l} L${n[n.length-1][0]},152 L${n[0][0]},152 Z`,[x,u]=n[n.length-1];return e.jsxs("div",{className:"line",children:[e.jsxs("svg",{viewBox:"0 0 600 160",role:"img","aria-label":"trend over time",children:[e.jsx("path",{d:o,className:"line-area"}),e.jsx("path",{d:l,className:"line-stroke"}),e.jsx("circle",{cx:x,cy:u,r:"4",className:"line-dot"})]}),e.jsxs("div",{className:"line-labels",children:[e.jsx("span",{children:s[0]?.label}),e.jsx("span",{children:s[s.length-1]?.label})]})]})}function b(s){return Number.isInteger(s)?String(s):s.toFixed(1)}const q=["give me a status report across every project","what is overdue, and which of it is high priority?","how much did we finish this week compared to what is still open?","chart my completions over the last two weeks","what should I work on next?"];function A(){const[s,a]=m.useState(""),[t,r]=m.useState([]),[i,h]=m.useState(!1);async function c(n){const l=n.trim();if(!(!l||i)){a(""),h(!0),r(o=>[...o,{request:l}]);try{let o="";const x=await v.chatStream(l,u=>{o+=u,r(d=>w(d,{request:l,writing:o}))});r(u=>w(u,{request:l,result:x}))}catch(o){r(x=>w(x,{request:l,error:o.message}))}finally{h(!1)}}}return e.jsxs("div",{className:"ask",children:[t.length===0&&e.jsxs("div",{className:"suggestions",children:[e.jsx("p",{className:"hint",children:"One question becomes one program. It calls several capabilities, does the filtering and totalling in the sandbox, and returns a document to render — not a sentence."}),q.map(n=>e.jsx("button",{className:"suggestion",onClick:()=>c(n),children:n},n))]}),e.jsx("div",{className:"turns",children:t.map((n,l)=>e.jsx(C,{turn:n,pending:i&&l===t.length-1},l))}),e.jsxs("form",{className:"composer",onSubmit:n=>{n.preventDefault(),c(s)},children:[e.jsx("input",{value:s,onChange:n=>a(n.target.value),placeholder:"Ask about your work…","aria-label":"Your question",disabled:i}),e.jsx("button",{type:"submit",disabled:i||!s.trim(),children:i?"Thinking…":"Ask"})]})]})}function g(s){return s<1e6?`${Math.round(s/1e3)}µs`:`${(s/1e6).toFixed(0)}ms`}function C({turn:s,pending:a}){const[t,r]=m.useState(!1);return e.jsxs("section",{className:"turn",children:[e.jsx("p",{className:"question",children:s.request}),a&&!s.result&&!s.error&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"thinking",children:"Writing a program…"}),s.writing&&e.jsx("pre",{className:"program writing",children:s.writing})]}),s.error&&e.jsx("p",{className:"error",children:s.error}),s.result&&e.jsxs(e.Fragment,{children:[e.jsx(y,{document:s.result.document}),s.result.pending&&e.jsx(F,{plan:s.result.pending}),e.jsxs("div",{className:"provenance",children:[e.jsxs("button",{className:"link",onClick:()=>r(i=>!i),children:[t?"Hide":"Show"," the program"]}),e.jsxs("span",{className:"muted",children:[s.result.cached?"reused a cached program":`${s.result.attempts} attempt${s.result.attempts===1?"":"s"}`," ","· ",s.result.took," · ",s.result.used.length," capabilities offered"]})]}),t&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"muted",children:["writing ",g(s.result.timing.Generate)," · searching"," ",g(s.result.timing.Search)," · cache ",g(s.result.timing.Cache)," · running"," ",g(s.result.timing.Run)]}),e.jsx("pre",{className:"program",children:s.result.program}),e.jsx("ul",{className:"offered",children:s.result.used.map(i=>e.jsxs("li",{children:[e.jsx("code",{children:i.capability.name})," ",i.capability.description]},i.capability.name))})]})]})]})}function F({plan:s}){const[a,t]=m.useState("waiting"),[r,i]=m.useState("");async function h(c){t("working");try{if(c){const{calls:n}=await v.approve(s.id);i(`${n.length} change${n.length===1?"":"s"} made`),t("approved")}else await v.reject(s.id),i("nothing was changed"),t("rejected")}catch(n){i(n.message),t("rejected")}}return e.jsxs("div",{className:"pending",children:[e.jsx("p",{className:"pending-title",children:"Waiting for your approval"}),e.jsx("ul",{children:s.calls.map((c,n)=>e.jsxs("li",{children:[e.jsx("code",{children:c.name})," ",e.jsx("span",{className:"muted",children:JSON.stringify(c.input)})]},n))}),a==="waiting"||a==="working"?e.jsxs("div",{className:"pending-actions",children:[e.jsx("button",{onClick:()=>h(!0),disabled:a==="working",children:"Approve"}),e.jsx("button",{className:"secondary",onClick:()=>h(!1),disabled:a==="working",children:"Reject"})]}):e.jsx("p",{className:a==="approved"?"muted":"error",children:r})]})}function w(s,a){return[...s.slice(0,-1),a]}export{A as component}; diff --git a/examples/taskreport/web/dist/assets/index-Dm_jx5Ya.js b/examples/taskreport/web/dist/assets/index-B8YGsnYU.js similarity index 97% rename from examples/taskreport/web/dist/assets/index-Dm_jx5Ya.js rename to examples/taskreport/web/dist/assets/index-B8YGsnYU.js index 46a3d32..7ab9a81 100644 --- a/examples/taskreport/web/dist/assets/index-Dm_jx5Ya.js +++ b/examples/taskreport/web/dist/assets/index-B8YGsnYU.js @@ -1 +1 @@ -import{r as s,a as n,j as a}from"./index-D4Un-2Pf.js";function w(){const[r,c]=s.useState([]),[t,g]=s.useState(null),[i,y]=s.useState("open"),[d,j]=s.useState(""),[x,S]=s.useState(""),[v,f]=s.useState("medium"),[N,b]=s.useState(""),[u,m]=s.useState(null),p=s.useCallback(async()=>{try{const[e,l]=await Promise.all([n.tasks({status:i}),n.summary()]);c(e.tasks??[]),g(l),m(null)}catch(e){m(e.message)}},[i]);s.useEffect(()=>{p()},[p]);async function h(e){try{await e,await p()}catch(l){m(l.message)}}return a.jsxs("div",{className:"board",children:[t&&a.jsxs("div",{className:"stats",children:[a.jsx(o,{label:"Open",value:t.open}),a.jsx(o,{label:"Overdue",value:t.overdue,tone:t.overdue>0?"bad":"none"}),a.jsx(o,{label:"Due today",value:t.due_today,tone:"warn"}),a.jsx(o,{label:"Done",value:t.completed,tone:"good"})]}),a.jsxs("form",{className:"new-task",onSubmit:e=>{e.preventDefault(),d.trim()&&h(n.create({title:d,project:x,priority:v,due_date:N}).then(()=>{j(""),b("")}))},children:[a.jsx("input",{value:d,onChange:e=>j(e.target.value),placeholder:"What needs doing?","aria-label":"Task title"}),a.jsx("input",{value:x,onChange:e=>S(e.target.value),placeholder:"Project","aria-label":"Project"}),a.jsxs("select",{value:v,onChange:e=>f(e.target.value),"aria-label":"Priority",children:[a.jsx("option",{value:"low",children:"low"}),a.jsx("option",{value:"medium",children:"medium"}),a.jsx("option",{value:"high",children:"high"})]}),a.jsx("input",{type:"date",value:N,onChange:e=>b(e.target.value),"aria-label":"Due date"}),a.jsx("button",{type:"submit",children:"Add"})]}),a.jsx("div",{className:"filters",children:["open","completed",""].map(e=>a.jsx("button",{className:i===e?"chip on":"chip",onClick:()=>y(e),children:e||"all"},e||"all"))}),u&&a.jsx("p",{className:"error",children:u}),a.jsxs("ul",{className:"tasks",children:[r.map(e=>a.jsxs("li",{className:e.completed?"task done":"task",children:[a.jsx("button",{className:"tick","aria-label":e.completed?"Reopen":"Complete",onClick:()=>h(e.completed?n.reopen(e.id):n.complete(e.id)),children:e.completed?"✓":""}),a.jsxs("div",{className:"task-body",children:[a.jsx("span",{className:"task-title",children:e.title}),a.jsxs("span",{className:"task-meta",children:[e.project&&a.jsx("span",{className:"tag",children:e.project}),a.jsx("span",{className:`prio prio-${e.priority}`,children:e.priority}),e.due_date&&a.jsxs("span",{className:"due",children:["due ",e.due_date]}),e.tags.map(l=>a.jsxs("span",{className:"tag muted",children:["#",l]},l))]})]}),a.jsx("button",{className:"remove","aria-label":"Delete",onClick:()=>h(n.remove(e.id)),children:"×"})]},e.id)),r.length===0&&!u&&a.jsx("li",{className:"empty",children:"Nothing here."})]})]})}function o({label:r,value:c,tone:t="none"}){return a.jsxs("div",{className:`stat tone-${t}`,children:[a.jsx("span",{className:"stat-value",children:c}),a.jsx("span",{className:"stat-label",children:r})]})}export{w as component}; +import{r as s,a as n,j as a}from"./index-D-DTohO0.js";function w(){const[r,c]=s.useState([]),[t,g]=s.useState(null),[i,y]=s.useState("open"),[d,j]=s.useState(""),[x,S]=s.useState(""),[v,f]=s.useState("medium"),[N,b]=s.useState(""),[u,m]=s.useState(null),p=s.useCallback(async()=>{try{const[e,l]=await Promise.all([n.tasks({status:i}),n.summary()]);c(e.tasks??[]),g(l),m(null)}catch(e){m(e.message)}},[i]);s.useEffect(()=>{p()},[p]);async function h(e){try{await e,await p()}catch(l){m(l.message)}}return a.jsxs("div",{className:"board",children:[t&&a.jsxs("div",{className:"stats",children:[a.jsx(o,{label:"Open",value:t.open}),a.jsx(o,{label:"Overdue",value:t.overdue,tone:t.overdue>0?"bad":"none"}),a.jsx(o,{label:"Due today",value:t.due_today,tone:"warn"}),a.jsx(o,{label:"Done",value:t.completed,tone:"good"})]}),a.jsxs("form",{className:"new-task",onSubmit:e=>{e.preventDefault(),d.trim()&&h(n.create({title:d,project:x,priority:v,due_date:N}).then(()=>{j(""),b("")}))},children:[a.jsx("input",{value:d,onChange:e=>j(e.target.value),placeholder:"What needs doing?","aria-label":"Task title"}),a.jsx("input",{value:x,onChange:e=>S(e.target.value),placeholder:"Project","aria-label":"Project"}),a.jsxs("select",{value:v,onChange:e=>f(e.target.value),"aria-label":"Priority",children:[a.jsx("option",{value:"low",children:"low"}),a.jsx("option",{value:"medium",children:"medium"}),a.jsx("option",{value:"high",children:"high"})]}),a.jsx("input",{type:"date",value:N,onChange:e=>b(e.target.value),"aria-label":"Due date"}),a.jsx("button",{type:"submit",children:"Add"})]}),a.jsx("div",{className:"filters",children:["open","completed",""].map(e=>a.jsx("button",{className:i===e?"chip on":"chip",onClick:()=>y(e),children:e||"all"},e||"all"))}),u&&a.jsx("p",{className:"error",children:u}),a.jsxs("ul",{className:"tasks",children:[r.map(e=>a.jsxs("li",{className:e.completed?"task done":"task",children:[a.jsx("button",{className:"tick","aria-label":e.completed?"Reopen":"Complete",onClick:()=>h(e.completed?n.reopen(e.id):n.complete(e.id)),children:e.completed?"✓":""}),a.jsxs("div",{className:"task-body",children:[a.jsx("span",{className:"task-title",children:e.title}),a.jsxs("span",{className:"task-meta",children:[e.project&&a.jsx("span",{className:"tag",children:e.project}),a.jsx("span",{className:`prio prio-${e.priority}`,children:e.priority}),e.due_date&&a.jsxs("span",{className:"due",children:["due ",e.due_date]}),e.tags.map(l=>a.jsxs("span",{className:"tag muted",children:["#",l]},l))]})]}),a.jsx("button",{className:"remove","aria-label":"Delete",onClick:()=>h(n.remove(e.id)),children:"×"})]},e.id)),r.length===0&&!u&&a.jsx("li",{className:"empty",children:"Nothing here."})]})]})}function o({label:r,value:c,tone:t="none"}){return a.jsxs("div",{className:`stat tone-${t}`,children:[a.jsx("span",{className:"stat-value",children:c}),a.jsx("span",{className:"stat-label",children:r})]})}export{w as component}; diff --git a/examples/taskreport/web/dist/assets/index-D4Un-2Pf.js b/examples/taskreport/web/dist/assets/index-D-DTohO0.js similarity index 90% rename from examples/taskreport/web/dist/assets/index-D4Un-2Pf.js rename to examples/taskreport/web/dist/assets/index-D-DTohO0.js index ceaf0eb..e061516 100644 --- a/examples/taskreport/web/dist/assets/index-D4Un-2Pf.js +++ b/examples/taskreport/web/dist/assets/index-D-DTohO0.js @@ -1,15 +1,15 @@ -(function(){const c=document.createElement("link").relList;if(c&&c.supports&&c.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))f(r);new MutationObserver(r=>{for(const h of r)if(h.type==="childList")for(const g of h.addedNodes)g.tagName==="LINK"&&g.rel==="modulepreload"&&f(g)}).observe(document,{childList:!0,subtree:!0});function s(r){const h={};return r.integrity&&(h.integrity=r.integrity),r.referrerPolicy&&(h.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?h.credentials="include":r.crossOrigin==="anonymous"?h.credentials="omit":h.credentials="same-origin",h}function f(r){if(r.ep)return;r.ep=!0;const h=s(r);fetch(r.href,h)}})();function kv(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var Sf={exports:{}},fu={};var $h;function Wv(){if($h)return fu;$h=1;var a=Symbol.for("react.transitional.element"),c=Symbol.for("react.fragment");function s(f,r,h){var g=null;if(h!==void 0&&(g=""+h),r.key!==void 0&&(g=""+r.key),"key"in r){h={};for(var m in r)m!=="key"&&(h[m]=r[m])}else h=r;return r=h.ref,{$$typeof:a,type:f,key:g,ref:r!==void 0?r:null,props:h}}return fu.Fragment=c,fu.jsx=s,fu.jsxs=s,fu}var Ph;function Fv(){return Ph||(Ph=1,Sf.exports=Wv()),Sf.exports}var k=Fv(),bf={exports:{}},ut={};var Ih;function $v(){if(Ih)return ut;Ih=1;var a=Symbol.for("react.transitional.element"),c=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),f=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),h=Symbol.for("react.consumer"),g=Symbol.for("react.context"),m=Symbol.for("react.forward_ref"),y=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),S=Symbol.for("react.lazy"),p=Symbol.for("react.activity"),b=Symbol.iterator;function T(A){return A===null||typeof A!="object"?null:(A=b&&A[b]||A["@@iterator"],typeof A=="function"?A:null)}var R={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},E=Object.assign,D={};function w(A,q,Z){this.props=A,this.context=q,this.refs=D,this.updater=Z||R}w.prototype.isReactComponent={},w.prototype.setState=function(A,q){if(typeof A!="object"&&typeof A!="function"&&A!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,A,q,"setState")},w.prototype.forceUpdate=function(A){this.updater.enqueueForceUpdate(this,A,"forceUpdate")};function Y(){}Y.prototype=w.prototype;function K(A,q,Z){this.props=A,this.context=q,this.refs=D,this.updater=Z||R}var X=K.prototype=new Y;X.constructor=K,E(X,w.prototype),X.isPureReactComponent=!0;var et=Array.isArray;function G(){}var L={H:null,A:null,T:null,S:null},Q=Object.prototype.hasOwnProperty;function J(A,q,Z){var F=Z.ref;return{$$typeof:a,type:A,key:q,ref:F!==void 0?F:null,props:Z}}function ct(A,q){return J(A.type,q,A.props)}function P(A){return typeof A=="object"&&A!==null&&A.$$typeof===a}function ft(A){var q={"=":"=0",":":"=2"};return"$"+A.replace(/[=:]/g,function(Z){return q[Z]})}var bt=/\/+/g;function ee(A,q){return typeof A=="object"&&A!==null&&A.key!=null?ft(""+A.key):q.toString(36)}function Bt(A){switch(A.status){case"fulfilled":return A.value;case"rejected":throw A.reason;default:switch(typeof A.status=="string"?A.then(G,G):(A.status="pending",A.then(function(q){A.status==="pending"&&(A.status="fulfilled",A.value=q)},function(q){A.status==="pending"&&(A.status="rejected",A.reason=q)})),A.status){case"fulfilled":return A.value;case"rejected":throw A.reason}}throw A}function N(A,q,Z,F,nt){var it=typeof A;(it==="undefined"||it==="boolean")&&(A=null);var vt=!1;if(A===null)vt=!0;else switch(it){case"bigint":case"string":case"number":vt=!0;break;case"object":switch(A.$$typeof){case a:case c:vt=!0;break;case S:return vt=A._init,N(vt(A._payload),q,Z,F,nt)}}if(vt)return nt=nt(A),vt=F===""?"."+ee(A,0):F,et(nt)?(Z="",vt!=null&&(Z=vt.replace(bt,"$&/")+"/"),N(nt,q,Z,"",function(Qe){return Qe})):nt!=null&&(P(nt)&&(nt=ct(nt,Z+(nt.key==null||A&&A.key===nt.key?"":(""+nt.key).replace(bt,"$&/")+"/")+vt)),q.push(nt)),1;vt=0;var Jt=F===""?".":F+":";if(et(A))for(var Ct=0;Ct>>1,zt=N[_t];if(0>>1;_tr(Z,lt))Fr(nt,Z)?(N[_t]=nt,N[F]=lt,_t=F):(N[_t]=Z,N[q]=lt,_t=q);else if(Fr(nt,lt))N[_t]=nt,N[F]=lt,_t=F;else break t}}return V}function r(N,V){var lt=N.sortIndex-V.sortIndex;return lt!==0?lt:N.id-V.id}if(a.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var h=performance;a.unstable_now=function(){return h.now()}}else{var g=Date,m=g.now();a.unstable_now=function(){return g.now()-m}}var y=[],d=[],S=1,p=null,b=3,T=!1,R=!1,E=!1,D=!1,w=typeof setTimeout=="function"?setTimeout:null,Y=typeof clearTimeout=="function"?clearTimeout:null,K=typeof setImmediate<"u"?setImmediate:null;function X(N){for(var V=s(d);V!==null;){if(V.callback===null)f(d);else if(V.startTime<=N)f(d),V.sortIndex=V.expirationTime,c(y,V);else break;V=s(d)}}function et(N){if(E=!1,X(N),!R)if(s(y)!==null)R=!0,G||(G=!0,ft());else{var V=s(d);V!==null&&Bt(et,V.startTime-N)}}var G=!1,L=-1,Q=5,J=-1;function ct(){return D?!0:!(a.unstable_now()-JN&&ct());){var _t=p.callback;if(typeof _t=="function"){p.callback=null,b=p.priorityLevel;var zt=_t(p.expirationTime<=N);if(N=a.unstable_now(),typeof zt=="function"){p.callback=zt,X(N),V=!0;break e}p===s(y)&&f(y),X(N)}else f(y);p=s(y)}if(p!==null)V=!0;else{var A=s(d);A!==null&&Bt(et,A.startTime-N),V=!1}}break t}finally{p=null,b=lt,T=!1}V=void 0}}finally{V?ft():G=!1}}}var ft;if(typeof K=="function")ft=function(){K(P)};else if(typeof MessageChannel<"u"){var bt=new MessageChannel,ee=bt.port2;bt.port1.onmessage=P,ft=function(){ee.postMessage(null)}}else ft=function(){w(P,0)};function Bt(N,V){L=w(function(){N(a.unstable_now())},V)}a.unstable_IdlePriority=5,a.unstable_ImmediatePriority=1,a.unstable_LowPriority=4,a.unstable_NormalPriority=3,a.unstable_Profiling=null,a.unstable_UserBlockingPriority=2,a.unstable_cancelCallback=function(N){N.callback=null},a.unstable_forceFrameRate=function(N){0>N||125_t?(N.sortIndex=lt,c(d,N),s(y)===null&&N===s(d)&&(E?(Y(L),L=-1):E=!0,Bt(et,lt-_t))):(N.sortIndex=zt,c(y,N),R||T||(R=!0,G||(G=!0,ft()))),N},a.unstable_shouldYield=ct,a.unstable_wrapCallback=function(N){var V=b;return function(){var lt=b;b=V;try{return N.apply(this,arguments)}finally{b=lt}}}})(Tf)),Tf}var lm;function Iv(){return lm||(lm=1,Ef.exports=Pv()),Ef.exports}var zf={exports:{}},te={};var nm;function tg(){if(nm)return te;nm=1;var a=pu();function c(y){var d="https://react.dev/errors/"+y;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(a)}catch(c){console.error(c)}}return a(),zf.exports=tg(),zf.exports}var um;function lg(){if(um)return ou;um=1;var a=Iv(),c=pu(),s=eg();function f(t){var e="https://react.dev/errors/"+t;if(1zt||(t.current=_t[zt],_t[zt]=null,zt--)}function Z(t,e){zt++,_t[zt]=t.current,t.current=e}var F=A(null),nt=A(null),it=A(null),vt=A(null);function Jt(t,e){switch(Z(it,e),Z(nt,t),Z(F,null),e.nodeType){case 9:case 11:t=(t=e.documentElement)&&(t=t.namespaceURI)?bh(t):0;break;default:if(t=e.tagName,e=e.namespaceURI)e=bh(e),t=_h(e,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}q(F),Z(F,t)}function Ct(){q(F),q(nt),q(it)}function Qe(t){t.memoizedState!==null&&Z(vt,t);var e=F.current,l=_h(e,t.type);e!==l&&(Z(nt,t),Z(F,l))}function Ve(t){nt.current===t&&(q(F),q(nt)),vt.current===t&&(q(vt),uu._currentValue=lt)}var dl,da;function He(t){if(dl===void 0)try{throw Error()}catch(l){var e=l.stack.trim().match(/\n( *(at )?)/);dl=e&&e[1]||"",da=-1{for(const h of r)if(h.type==="childList")for(const g of h.addedNodes)g.tagName==="LINK"&&g.rel==="modulepreload"&&f(g)}).observe(document,{childList:!0,subtree:!0});function s(r){const h={};return r.integrity&&(h.integrity=r.integrity),r.referrerPolicy&&(h.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?h.credentials="include":r.crossOrigin==="anonymous"?h.credentials="omit":h.credentials="same-origin",h}function f(r){if(r.ep)return;r.ep=!0;const h=s(r);fetch(r.href,h)}})();function kv(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var Sf={exports:{}},fu={};var $h;function Wv(){if($h)return fu;$h=1;var a=Symbol.for("react.transitional.element"),c=Symbol.for("react.fragment");function s(f,r,h){var g=null;if(h!==void 0&&(g=""+h),r.key!==void 0&&(g=""+r.key),"key"in r){h={};for(var m in r)m!=="key"&&(h[m]=r[m])}else h=r;return r=h.ref,{$$typeof:a,type:f,key:g,ref:r!==void 0?r:null,props:h}}return fu.Fragment=c,fu.jsx=s,fu.jsxs=s,fu}var Ph;function Fv(){return Ph||(Ph=1,Sf.exports=Wv()),Sf.exports}var k=Fv(),bf={exports:{}},ut={};var Ih;function $v(){if(Ih)return ut;Ih=1;var a=Symbol.for("react.transitional.element"),c=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),f=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),h=Symbol.for("react.consumer"),g=Symbol.for("react.context"),m=Symbol.for("react.forward_ref"),y=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),S=Symbol.for("react.lazy"),p=Symbol.for("react.activity"),b=Symbol.iterator;function T(A){return A===null||typeof A!="object"?null:(A=b&&A[b]||A["@@iterator"],typeof A=="function"?A:null)}var R={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},E=Object.assign,D={};function w(A,q,Z){this.props=A,this.context=q,this.refs=D,this.updater=Z||R}w.prototype.isReactComponent={},w.prototype.setState=function(A,q){if(typeof A!="object"&&typeof A!="function"&&A!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,A,q,"setState")},w.prototype.forceUpdate=function(A){this.updater.enqueueForceUpdate(this,A,"forceUpdate")};function Y(){}Y.prototype=w.prototype;function K(A,q,Z){this.props=A,this.context=q,this.refs=D,this.updater=Z||R}var X=K.prototype=new Y;X.constructor=K,E(X,w.prototype),X.isPureReactComponent=!0;var et=Array.isArray;function G(){}var L={H:null,A:null,T:null,S:null},Q=Object.prototype.hasOwnProperty;function J(A,q,Z){var F=Z.ref;return{$$typeof:a,type:A,key:q,ref:F!==void 0?F:null,props:Z}}function ct(A,q){return J(A.type,q,A.props)}function P(A){return typeof A=="object"&&A!==null&&A.$$typeof===a}function ft(A){var q={"=":"=0",":":"=2"};return"$"+A.replace(/[=:]/g,function(Z){return q[Z]})}var bt=/\/+/g;function ee(A,q){return typeof A=="object"&&A!==null&&A.key!=null?ft(""+A.key):q.toString(36)}function Bt(A){switch(A.status){case"fulfilled":return A.value;case"rejected":throw A.reason;default:switch(typeof A.status=="string"?A.then(G,G):(A.status="pending",A.then(function(q){A.status==="pending"&&(A.status="fulfilled",A.value=q)},function(q){A.status==="pending"&&(A.status="rejected",A.reason=q)})),A.status){case"fulfilled":return A.value;case"rejected":throw A.reason}}throw A}function N(A,q,Z,F,nt){var it=typeof A;(it==="undefined"||it==="boolean")&&(A=null);var vt=!1;if(A===null)vt=!0;else switch(it){case"bigint":case"string":case"number":vt=!0;break;case"object":switch(A.$$typeof){case a:case c:vt=!0;break;case S:return vt=A._init,N(vt(A._payload),q,Z,F,nt)}}if(vt)return nt=nt(A),vt=F===""?"."+ee(A,0):F,et(nt)?(Z="",vt!=null&&(Z=vt.replace(bt,"$&/")+"/"),N(nt,q,Z,"",function(Ve){return Ve})):nt!=null&&(P(nt)&&(nt=ct(nt,Z+(nt.key==null||A&&A.key===nt.key?"":(""+nt.key).replace(bt,"$&/")+"/")+vt)),q.push(nt)),1;vt=0;var Jt=F===""?".":F+":";if(et(A))for(var Ct=0;Ct>>1,zt=N[_t];if(0>>1;_tr(Z,lt))Fr(nt,Z)?(N[_t]=nt,N[F]=lt,_t=F):(N[_t]=Z,N[q]=lt,_t=q);else if(Fr(nt,lt))N[_t]=nt,N[F]=lt,_t=F;else break t}}return V}function r(N,V){var lt=N.sortIndex-V.sortIndex;return lt!==0?lt:N.id-V.id}if(a.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var h=performance;a.unstable_now=function(){return h.now()}}else{var g=Date,m=g.now();a.unstable_now=function(){return g.now()-m}}var y=[],d=[],S=1,p=null,b=3,T=!1,R=!1,E=!1,D=!1,w=typeof setTimeout=="function"?setTimeout:null,Y=typeof clearTimeout=="function"?clearTimeout:null,K=typeof setImmediate<"u"?setImmediate:null;function X(N){for(var V=s(d);V!==null;){if(V.callback===null)f(d);else if(V.startTime<=N)f(d),V.sortIndex=V.expirationTime,c(y,V);else break;V=s(d)}}function et(N){if(E=!1,X(N),!R)if(s(y)!==null)R=!0,G||(G=!0,ft());else{var V=s(d);V!==null&&Bt(et,V.startTime-N)}}var G=!1,L=-1,Q=5,J=-1;function ct(){return D?!0:!(a.unstable_now()-JN&&ct());){var _t=p.callback;if(typeof _t=="function"){p.callback=null,b=p.priorityLevel;var zt=_t(p.expirationTime<=N);if(N=a.unstable_now(),typeof zt=="function"){p.callback=zt,X(N),V=!0;break e}p===s(y)&&f(y),X(N)}else f(y);p=s(y)}if(p!==null)V=!0;else{var A=s(d);A!==null&&Bt(et,A.startTime-N),V=!1}}break t}finally{p=null,b=lt,T=!1}V=void 0}}finally{V?ft():G=!1}}}var ft;if(typeof K=="function")ft=function(){K(P)};else if(typeof MessageChannel<"u"){var bt=new MessageChannel,ee=bt.port2;bt.port1.onmessage=P,ft=function(){ee.postMessage(null)}}else ft=function(){w(P,0)};function Bt(N,V){L=w(function(){N(a.unstable_now())},V)}a.unstable_IdlePriority=5,a.unstable_ImmediatePriority=1,a.unstable_LowPriority=4,a.unstable_NormalPriority=3,a.unstable_Profiling=null,a.unstable_UserBlockingPriority=2,a.unstable_cancelCallback=function(N){N.callback=null},a.unstable_forceFrameRate=function(N){0>N||125_t?(N.sortIndex=lt,c(d,N),s(y)===null&&N===s(d)&&(E?(Y(L),L=-1):E=!0,Bt(et,lt-_t))):(N.sortIndex=zt,c(y,N),R||T||(R=!0,G||(G=!0,ft()))),N},a.unstable_shouldYield=ct,a.unstable_wrapCallback=function(N){var V=b;return function(){var lt=b;b=V;try{return N.apply(this,arguments)}finally{b=lt}}}})(Tf)),Tf}var lm;function Iv(){return lm||(lm=1,Ef.exports=Pv()),Ef.exports}var zf={exports:{}},te={};var nm;function tg(){if(nm)return te;nm=1;var a=pu();function c(y){var d="https://react.dev/errors/"+y;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(a)}catch(c){console.error(c)}}return a(),zf.exports=tg(),zf.exports}var um;function lg(){if(um)return ou;um=1;var a=Iv(),c=pu(),s=eg();function f(t){var e="https://react.dev/errors/"+t;if(1zt||(t.current=_t[zt],_t[zt]=null,zt--)}function Z(t,e){zt++,_t[zt]=t.current,t.current=e}var F=A(null),nt=A(null),it=A(null),vt=A(null);function Jt(t,e){switch(Z(it,e),Z(nt,t),Z(F,null),e.nodeType){case 9:case 11:t=(t=e.documentElement)&&(t=t.namespaceURI)?bh(t):0;break;default:if(t=e.tagName,e=e.namespaceURI)e=bh(e),t=_h(e,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}q(F),Z(F,t)}function Ct(){q(F),q(nt),q(it)}function Ve(t){t.memoizedState!==null&&Z(vt,t);var e=F.current,l=_h(e,t.type);e!==l&&(Z(nt,t),Z(F,l))}function Ze(t){nt.current===t&&(q(F),q(nt)),vt.current===t&&(q(vt),uu._currentValue=lt)}var hl,da;function He(t){if(hl===void 0)try{throw Error()}catch(l){var e=l.stack.trim().match(/\n( *(at )?)/);hl=e&&e[1]||"",da=-1)":-1u||_[n]!==C[u]){var B=` -`+_[n].replace(" at new "," at ");return t.displayName&&B.includes("")&&(B=B.replace("",t.displayName)),B}while(1<=n&&0<=u);break}}}finally{Sn=!1,Error.prepareStackTrace=l}return(l=t?t.displayName||t.name:"")?He(l):""}function ha(t,e){switch(t.tag){case 26:case 27:case 5:return He(t.type);case 16:return He("Lazy");case 13:return t.child!==e&&e!==null?He("Suspense Fallback"):He("Suspense");case 19:return He("SuspenseList");case 0:case 15:return De(t.type,!1);case 11:return De(t.type.render,!1);case 1:return De(t.type,!0);case 31:return He("Activity");default:return""}}function Ze(t){try{var e="",l=null;do e+=ha(t,l),l=t,t=t.return;while(t);return e}catch(n){return` +`+_[n].replace(" at new "," at ");return t.displayName&&B.includes("")&&(B=B.replace("",t.displayName)),B}while(1<=n&&0<=u);break}}}finally{Sn=!1,Error.prepareStackTrace=l}return(l=t?t.displayName||t.name:"")?He(l):""}function ha(t,e){switch(t.tag){case 26:case 27:case 5:return He(t.type);case 16:return He("Lazy");case 13:return t.child!==e&&e!==null?He("Suspense Fallback"):He("Suspense");case 19:return He("SuspenseList");case 0:case 15:return De(t.type,!1);case 11:return De(t.type.render,!1);case 1:return De(t.type,!0);case 31:return He("Activity");default:return""}}function Ke(t){try{var e="",l=null;do e+=ha(t,l),l=t,t=t.return;while(t);return e}catch(n){return` Error generating stack: `+n.message+` -`+n.stack}}var Zl=Object.prototype.hasOwnProperty,ma=a.unstable_scheduleCallback,ya=a.unstable_cancelCallback,Su=a.unstable_shouldYield,It=a.unstable_requestPaint,Nt=a.unstable_now,Kl=a.unstable_getCurrentPriorityLevel,va=a.unstable_ImmediatePriority,Pf=a.unstable_UserBlockingPriority,bu=a.unstable_NormalPriority,C0=a.unstable_LowPriority,If=a.unstable_IdlePriority,x0=a.log,D0=a.unstable_setDisableYieldValue,ga=null,re=null;function hl(t){if(typeof x0=="function"&&D0(t),re&&typeof re.setStrictMode=="function")try{re.setStrictMode(ga,t)}catch{}}var de=Math.clz32?Math.clz32:N0,U0=Math.log,L0=Math.LN2;function N0(t){return t>>>=0,t===0?32:31-(U0(t)/L0|0)|0}var _u=256,Eu=262144,Tu=4194304;function Jl(t){var e=t&42;if(e!==0)return e;switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return t&261888;case 262144:case 524288:case 1048576:case 2097152:return t&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function zu(t,e,l){var n=t.pendingLanes;if(n===0)return 0;var u=0,i=t.suspendedLanes,o=t.pingedLanes;t=t.warmLanes;var v=n&134217727;return v!==0?(n=v&~i,n!==0?u=Jl(n):(o&=v,o!==0?u=Jl(o):l||(l=v&~t,l!==0&&(u=Jl(l))))):(v=n&~i,v!==0?u=Jl(v):o!==0?u=Jl(o):l||(l=n&~t,l!==0&&(u=Jl(l)))),u===0?0:e!==0&&e!==u&&(e&i)===0&&(i=u&-u,l=e&-e,i>=l||i===32&&(l&4194048)!==0)?e:u}function pa(t,e){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&e)===0}function B0(t,e){switch(t){case 1:case 2:case 4:case 8:case 64:return e+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function to(){var t=Tu;return Tu<<=1,(Tu&62914560)===0&&(Tu=4194304),t}function ic(t){for(var e=[],l=0;31>l;l++)e.push(t);return e}function Sa(t,e){t.pendingLanes|=e,e!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function H0(t,e,l,n,u,i){var o=t.pendingLanes;t.pendingLanes=l,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=l,t.entangledLanes&=l,t.errorRecoveryDisabledLanes&=l,t.shellSuspendCounter=0;var v=t.entanglements,_=t.expirationTimes,C=t.hiddenUpdates;for(l=o&~l;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var X0=/[\n"\\]/g;function _e(t){return t.replace(X0,function(e){return"\\"+e.charCodeAt(0).toString(16)+" "})}function dc(t,e,l,n,u,i,o,v){t.name="",o!=null&&typeof o!="function"&&typeof o!="symbol"&&typeof o!="boolean"?t.type=o:t.removeAttribute("type"),e!=null?o==="number"?(e===0&&t.value===""||t.value!=e)&&(t.value=""+be(e)):t.value!==""+be(e)&&(t.value=""+be(e)):o!=="submit"&&o!=="reset"||t.removeAttribute("value"),e!=null?hc(t,o,be(e)):l!=null?hc(t,o,be(l)):n!=null&&t.removeAttribute("value"),u==null&&i!=null&&(t.defaultChecked=!!i),u!=null&&(t.checked=u&&typeof u!="function"&&typeof u!="symbol"),v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"?t.name=""+be(v):t.removeAttribute("name")}function mo(t,e,l,n,u,i,o,v){if(i!=null&&typeof i!="function"&&typeof i!="symbol"&&typeof i!="boolean"&&(t.type=i),e!=null||l!=null){if(!(i!=="submit"&&i!=="reset"||e!=null)){rc(t);return}l=l!=null?""+be(l):"",e=e!=null?""+be(e):l,v||e===t.value||(t.value=e),t.defaultValue=e}n=n??u,n=typeof n!="function"&&typeof n!="symbol"&&!!n,t.checked=v?t.checked:!!n,t.defaultChecked=!!n,o!=null&&typeof o!="function"&&typeof o!="symbol"&&typeof o!="boolean"&&(t.name=o),rc(t)}function hc(t,e,l){e==="number"&&Ou(t.ownerDocument)===t||t.defaultValue===""+l||(t.defaultValue=""+l)}function An(t,e,l,n){if(t=t.options,e){e={};for(var u=0;u"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),pc=!1;if(ke)try{var Ta={};Object.defineProperty(Ta,"passive",{get:function(){pc=!0}}),window.addEventListener("test",Ta,Ta),window.removeEventListener("test",Ta,Ta)}catch{pc=!1}var yl=null,Sc=null,Cu=null;function _o(){if(Cu)return Cu;var t,e=Sc,l=e.length,n,u="value"in yl?yl.value:yl.textContent,i=u.length;for(t=0;t=Ra),Oo=" ",Mo=!1;function Co(t,e){switch(t){case"keyup":return vy.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function xo(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Cn=!1;function py(t,e){switch(t){case"compositionend":return xo(e);case"keypress":return e.which!==32?null:(Mo=!0,Oo);case"textInput":return t=e.data,t===Oo&&Mo?null:t;default:return null}}function Sy(t,e){if(Cn)return t==="compositionend"||!zc&&Co(t,e)?(t=_o(),Cu=Sc=yl=null,Cn=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1=e)return{node:l,offset:e-t};t=n}t:{for(;l;){if(l.nextSibling){l=l.nextSibling;break t}l=l.parentNode}l=void 0}l=qo(l)}}function Yo(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?Yo(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function Go(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var e=Ou(t.document);e instanceof t.HTMLIFrameElement;){try{var l=typeof e.contentWindow.location.href=="string"}catch{l=!1}if(l)t=e.contentWindow;else break;e=Ou(t.document)}return e}function Oc(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e&&(e==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||e==="textarea"||t.contentEditable==="true")}var Oy=ke&&"documentMode"in document&&11>=document.documentMode,xn=null,Mc=null,xa=null,Cc=!1;function Xo(t,e,l){var n=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;Cc||xn==null||xn!==Ou(n)||(n=xn,"selectionStart"in n&&Oc(n)?n={start:n.selectionStart,end:n.selectionEnd}:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection(),n={anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}),xa&&Ca(xa,n)||(xa=n,n=Ei(Mc,"onSelect"),0>=o,u-=o,je=1<<32-de(e)+u|l<ot?(mt=$,$=null):mt=$.sibling;var pt=x(O,$,M[ot],H);if(pt===null){$===null&&($=mt);break}t&&$&&pt.alternate===null&&e(O,$),z=i(pt,z,ot),gt===null?I=pt:gt.sibling=pt,gt=pt,$=mt}if(ot===M.length)return l(O,$),yt&&Fe(O,ot),I;if($===null){for(;otot?(mt=$,$=null):mt=$.sibling;var jl=x(O,$,pt.value,H);if(jl===null){$===null&&($=mt);break}t&&$&&jl.alternate===null&&e(O,$),z=i(jl,z,ot),gt===null?I=jl:gt.sibling=jl,gt=jl,$=mt}if(pt.done)return l(O,$),yt&&Fe(O,ot),I;if($===null){for(;!pt.done;ot++,pt=M.next())pt=j(O,pt.value,H),pt!==null&&(z=i(pt,z,ot),gt===null?I=pt:gt.sibling=pt,gt=pt);return yt&&Fe(O,ot),I}for($=n($);!pt.done;ot++,pt=M.next())pt=U($,O,ot,pt.value,H),pt!==null&&(t&&pt.alternate!==null&&$.delete(pt.key===null?ot:pt.key),z=i(pt,z,ot),gt===null?I=pt:gt.sibling=pt,gt=pt);return t&&$.forEach(function(Jv){return e(O,Jv)}),yt&&Fe(O,ot),I}function Ot(O,z,M,H){if(typeof M=="object"&&M!==null&&M.type===E&&M.key===null&&(M=M.props.children),typeof M=="object"&&M!==null){switch(M.$$typeof){case T:t:{for(var I=M.key;z!==null;){if(z.key===I){if(I=M.type,I===E){if(z.tag===7){l(O,z.sibling),H=u(z,M.props.children),H.return=O,O=H;break t}}else if(z.elementType===I||typeof I=="object"&&I!==null&&I.$$typeof===Q&&an(I)===z.type){l(O,z.sibling),H=u(z,M.props),Ha(H,M),H.return=O,O=H;break t}l(O,z);break}else e(O,z);z=z.sibling}M.type===E?(H=Il(M.props.children,O.mode,H,M.key),H.return=O,O=H):(H=wu(M.type,M.key,M.props,null,O.mode,H),Ha(H,M),H.return=O,O=H)}return o(O);case R:t:{for(I=M.key;z!==null;){if(z.key===I)if(z.tag===4&&z.stateNode.containerInfo===M.containerInfo&&z.stateNode.implementation===M.implementation){l(O,z.sibling),H=u(z,M.children||[]),H.return=O,O=H;break t}else{l(O,z);break}else e(O,z);z=z.sibling}H=Hc(M,O.mode,H),H.return=O,O=H}return o(O);case Q:return M=an(M),Ot(O,z,M,H)}if(Bt(M))return W(O,z,M,H);if(ft(M)){if(I=ft(M),typeof I!="function")throw Error(f(150));return M=I.call(M),tt(O,z,M,H)}if(typeof M.then=="function")return Ot(O,z,Ku(M),H);if(M.$$typeof===K)return Ot(O,z,Xu(O,M),H);Ju(O,M)}return typeof M=="string"&&M!==""||typeof M=="number"||typeof M=="bigint"?(M=""+M,z!==null&&z.tag===6?(l(O,z.sibling),H=u(z,M),H.return=O,O=H):(l(O,z),H=Bc(M,O.mode,H),H.return=O,O=H),o(O)):l(O,z)}return function(O,z,M,H){try{Ba=0;var I=Ot(O,z,M,H);return Gn=null,I}catch($){if($===Yn||$===Vu)throw $;var gt=me(29,$,null,O.mode);return gt.lanes=H,gt.return=O,gt}}}var cn=rr(!0),dr=rr(!1),bl=!1;function kc(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Wc(t,e){t=t.updateQueue,e.updateQueue===t&&(e.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function _l(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function El(t,e,l){var n=t.updateQueue;if(n===null)return null;if(n=n.shared,(St&2)!==0){var u=n.pending;return u===null?e.next=e:(e.next=u.next,u.next=e),n.pending=e,e=qu(t),Wo(t,null,l),e}return ju(t,n,e,l),qu(t)}function ja(t,e,l){if(e=e.updateQueue,e!==null&&(e=e.shared,(l&4194048)!==0)){var n=e.lanes;n&=t.pendingLanes,l|=n,e.lanes=l,lo(t,l)}}function Fc(t,e){var l=t.updateQueue,n=t.alternate;if(n!==null&&(n=n.updateQueue,l===n)){var u=null,i=null;if(l=l.firstBaseUpdate,l!==null){do{var o={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};i===null?u=i=o:i=i.next=o,l=l.next}while(l!==null);i===null?u=i=e:i=i.next=e}else u=i=e;l={baseState:n.baseState,firstBaseUpdate:u,lastBaseUpdate:i,shared:n.shared,callbacks:n.callbacks},t.updateQueue=l;return}t=l.lastBaseUpdate,t===null?l.firstBaseUpdate=e:t.next=e,l.lastBaseUpdate=e}var $c=!1;function qa(){if($c){var t=wn;if(t!==null)throw t}}function wa(t,e,l,n){$c=!1;var u=t.updateQueue;bl=!1;var i=u.firstBaseUpdate,o=u.lastBaseUpdate,v=u.shared.pending;if(v!==null){u.shared.pending=null;var _=v,C=_.next;_.next=null,o===null?i=C:o.next=C,o=_;var B=t.alternate;B!==null&&(B=B.updateQueue,v=B.lastBaseUpdate,v!==o&&(v===null?B.firstBaseUpdate=C:v.next=C,B.lastBaseUpdate=_))}if(i!==null){var j=u.baseState;o=0,B=C=_=null,v=i;do{var x=v.lane&-536870913,U=x!==v.lane;if(U?(ht&x)===x:(n&x)===x){x!==0&&x===qn&&($c=!0),B!==null&&(B=B.next={lane:0,tag:v.tag,payload:v.payload,callback:null,next:null});t:{var W=t,tt=v;x=e;var Ot=l;switch(tt.tag){case 1:if(W=tt.payload,typeof W=="function"){j=W.call(Ot,j,x);break t}j=W;break t;case 3:W.flags=W.flags&-65537|128;case 0:if(W=tt.payload,x=typeof W=="function"?W.call(Ot,j,x):W,x==null)break t;j=p({},j,x);break t;case 2:bl=!0}}x=v.callback,x!==null&&(t.flags|=64,U&&(t.flags|=8192),U=u.callbacks,U===null?u.callbacks=[x]:U.push(x))}else U={lane:x,tag:v.tag,payload:v.payload,callback:v.callback,next:null},B===null?(C=B=U,_=j):B=B.next=U,o|=x;if(v=v.next,v===null){if(v=u.shared.pending,v===null)break;U=v,v=U.next,U.next=null,u.lastBaseUpdate=U,u.shared.pending=null}}while(!0);B===null&&(_=j),u.baseState=_,u.firstBaseUpdate=C,u.lastBaseUpdate=B,i===null&&(u.shared.lanes=0),Ol|=o,t.lanes=o,t.memoizedState=j}}function hr(t,e){if(typeof t!="function")throw Error(f(191,t));t.call(e)}function mr(t,e){var l=t.callbacks;if(l!==null)for(t.callbacks=null,t=0;ti?i:8;var o=N.T,v={};N.T=v,vs(t,!1,e,l);try{var _=u(),C=N.S;if(C!==null&&C(v,_),_!==null&&typeof _=="object"&&typeof _.then=="function"){var B=Hy(_,n);Xa(t,e,B,Se(t))}else Xa(t,e,n,Se(t))}catch(j){Xa(t,e,{then:function(){},status:"rejected",reason:j},Se())}finally{V.p=i,o!==null&&v.types!==null&&(o.types=v.types),N.T=o}}function Xy(){}function ms(t,e,l,n){if(t.tag!==5)throw Error(f(476));var u=Kr(t).queue;Zr(t,u,e,lt,l===null?Xy:function(){return Jr(t),l(n)})}function Kr(t){var e=t.memoizedState;if(e!==null)return e;e={memoizedState:lt,baseState:lt,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:tl,lastRenderedState:lt},next:null};var l={};return e.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:tl,lastRenderedState:l},next:null},t.memoizedState=e,t=t.alternate,t!==null&&(t.memoizedState=e),e}function Jr(t){var e=Kr(t);e.next===null&&(e=t.alternate.memoizedState),Xa(t,e.next.queue,{},Se())}function ys(){return Ft(uu)}function kr(){return wt().memoizedState}function Wr(){return wt().memoizedState}function Qy(t){for(var e=t.return;e!==null;){switch(e.tag){case 24:case 3:var l=Se();t=_l(l);var n=El(e,t,l);n!==null&&(fe(n,e,l),ja(n,e,l)),e={cache:Vc()},t.payload=e;return}e=e.return}}function Vy(t,e,l){var n=Se();l={lane:n,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},ni(t)?$r(e,l):(l=Lc(t,e,l,n),l!==null&&(fe(l,t,n),Pr(l,e,n)))}function Fr(t,e,l){var n=Se();Xa(t,e,l,n)}function Xa(t,e,l,n){var u={lane:n,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(ni(t))$r(e,u);else{var i=t.alternate;if(t.lanes===0&&(i===null||i.lanes===0)&&(i=e.lastRenderedReducer,i!==null))try{var o=e.lastRenderedState,v=i(o,l);if(u.hasEagerState=!0,u.eagerState=v,he(v,o))return ju(t,e,u,0),Mt===null&&Hu(),!1}catch{}if(l=Lc(t,e,u,n),l!==null)return fe(l,t,n),Pr(l,e,n),!0}return!1}function vs(t,e,l,n){if(n={lane:2,revertLane:ks(),gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},ni(t)){if(e)throw Error(f(479))}else e=Lc(t,l,n,2),e!==null&&fe(e,t,2)}function ni(t){var e=t.alternate;return t===st||e!==null&&e===st}function $r(t,e){Qn=Fu=!0;var l=t.pending;l===null?e.next=e:(e.next=l.next,l.next=e),t.pending=e}function Pr(t,e,l){if((l&4194048)!==0){var n=e.lanes;n&=t.pendingLanes,l|=n,e.lanes=l,lo(t,l)}}var Qa={readContext:Ft,use:Iu,useCallback:Ht,useContext:Ht,useEffect:Ht,useImperativeHandle:Ht,useLayoutEffect:Ht,useInsertionEffect:Ht,useMemo:Ht,useReducer:Ht,useRef:Ht,useState:Ht,useDebugValue:Ht,useDeferredValue:Ht,useTransition:Ht,useSyncExternalStore:Ht,useId:Ht,useHostTransitionStatus:Ht,useFormState:Ht,useActionState:Ht,useOptimistic:Ht,useMemoCache:Ht,useCacheRefresh:Ht};Qa.useEffectEvent=Ht;var Ir={readContext:Ft,use:Iu,useCallback:function(t,e){return le().memoizedState=[t,e===void 0?null:e],t},useContext:Ft,useEffect:Hr,useImperativeHandle:function(t,e,l){l=l!=null?l.concat([t]):null,ei(4194308,4,Yr.bind(null,e,t),l)},useLayoutEffect:function(t,e){return ei(4194308,4,t,e)},useInsertionEffect:function(t,e){ei(4,2,t,e)},useMemo:function(t,e){var l=le();e=e===void 0?null:e;var n=t();if(sn){hl(!0);try{t()}finally{hl(!1)}}return l.memoizedState=[n,e],n},useReducer:function(t,e,l){var n=le();if(l!==void 0){var u=l(e);if(sn){hl(!0);try{l(e)}finally{hl(!1)}}}else u=e;return n.memoizedState=n.baseState=u,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:u},n.queue=t,t=t.dispatch=Vy.bind(null,st,t),[n.memoizedState,t]},useRef:function(t){var e=le();return t={current:t},e.memoizedState=t},useState:function(t){t=fs(t);var e=t.queue,l=Fr.bind(null,st,e);return e.dispatch=l,[t.memoizedState,l]},useDebugValue:ds,useDeferredValue:function(t,e){var l=le();return hs(l,t,e)},useTransition:function(){var t=fs(!1);return t=Zr.bind(null,st,t.queue,!0,!1),le().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,e,l){var n=st,u=le();if(yt){if(l===void 0)throw Error(f(407));l=l()}else{if(l=e(),Mt===null)throw Error(f(349));(ht&127)!==0||br(n,e,l)}u.memoizedState=l;var i={value:l,getSnapshot:e};return u.queue=i,Hr(Er.bind(null,n,i,t),[t]),n.flags|=2048,Zn(9,{destroy:void 0},_r.bind(null,n,i,l,e),null),l},useId:function(){var t=le(),e=Mt.identifierPrefix;if(yt){var l=qe,n=je;l=(n&~(1<<32-de(n)-1)).toString(32)+l,e="_"+e+"R_"+l,l=$u++,0<\/script>",i=i.removeChild(i.firstChild);break;case"select":i=typeof n.is=="string"?o.createElement("select",{is:n.is}):o.createElement("select"),n.multiple?i.multiple=!0:n.size&&(i.size=n.size);break;default:i=typeof n.is=="string"?o.createElement(u,{is:n.is}):o.createElement(u)}}i[kt]=e,i[ne]=n;t:for(o=e.child;o!==null;){if(o.tag===5||o.tag===6)i.appendChild(o.stateNode);else if(o.tag!==4&&o.tag!==27&&o.child!==null){o.child.return=o,o=o.child;continue}if(o===e)break t;for(;o.sibling===null;){if(o.return===null||o.return===e)break t;o=o.return}o.sibling.return=o.return,o=o.sibling}e.stateNode=i;t:switch(Pt(i,u,n),u){case"button":case"input":case"select":case"textarea":n=!!n.autoFocus;break t;case"img":n=!0;break t;default:n=!1}n&&ll(e)}}return Dt(e),xs(e,e.type,t===null?null:t.memoizedProps,e.pendingProps,l),null;case 6:if(t&&e.stateNode!=null)t.memoizedProps!==n&&ll(e);else{if(typeof n!="string"&&e.stateNode===null)throw Error(f(166));if(t=it.current,Hn(e)){if(t=e.stateNode,l=e.memoizedProps,n=null,u=Wt,u!==null)switch(u.tag){case 27:case 5:n=u.memoizedProps}t[kt]=e,t=!!(t.nodeValue===l||n!==null&&n.suppressHydrationWarning===!0||ph(t.nodeValue,l)),t||pl(e,!0)}else t=Ti(t).createTextNode(n),t[kt]=e,e.stateNode=t}return Dt(e),null;case 31:if(l=e.memoizedState,t===null||t.memoizedState!==null){if(n=Hn(e),l!==null){if(t===null){if(!n)throw Error(f(318));if(t=e.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(f(557));t[kt]=e}else tn(),(e.flags&128)===0&&(e.memoizedState=null),e.flags|=4;Dt(e),t=!1}else l=Yc(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=l),t=!0;if(!t)return e.flags&256?(ve(e),e):(ve(e),null);if((e.flags&128)!==0)throw Error(f(558))}return Dt(e),null;case 13:if(n=e.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(u=Hn(e),n!==null&&n.dehydrated!==null){if(t===null){if(!u)throw Error(f(318));if(u=e.memoizedState,u=u!==null?u.dehydrated:null,!u)throw Error(f(317));u[kt]=e}else tn(),(e.flags&128)===0&&(e.memoizedState=null),e.flags|=4;Dt(e),u=!1}else u=Yc(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=u),u=!0;if(!u)return e.flags&256?(ve(e),e):(ve(e),null)}return ve(e),(e.flags&128)!==0?(e.lanes=l,e):(l=n!==null,t=t!==null&&t.memoizedState!==null,l&&(n=e.child,u=null,n.alternate!==null&&n.alternate.memoizedState!==null&&n.alternate.memoizedState.cachePool!==null&&(u=n.alternate.memoizedState.cachePool.pool),i=null,n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(i=n.memoizedState.cachePool.pool),i!==u&&(n.flags|=2048)),l!==t&&l&&(e.child.flags|=8192),si(e,e.updateQueue),Dt(e),null);case 4:return Ct(),t===null&&Ps(e.stateNode.containerInfo),Dt(e),null;case 10:return Pe(e.type),Dt(e),null;case 19:if(q(qt),n=e.memoizedState,n===null)return Dt(e),null;if(u=(e.flags&128)!==0,i=n.rendering,i===null)if(u)Za(n,!1);else{if(jt!==0||t!==null&&(t.flags&128)!==0)for(t=e.child;t!==null;){if(i=Wu(t),i!==null){for(e.flags|=128,Za(n,!1),t=i.updateQueue,e.updateQueue=t,si(e,t),e.subtreeFlags=0,t=l,l=e.child;l!==null;)Fo(l,t),l=l.sibling;return Z(qt,qt.current&1|2),yt&&Fe(e,n.treeForkCount),e.child}t=t.sibling}n.tail!==null&&Nt()>hi&&(e.flags|=128,u=!0,Za(n,!1),e.lanes=4194304)}else{if(!u)if(t=Wu(i),t!==null){if(e.flags|=128,u=!0,t=t.updateQueue,e.updateQueue=t,si(e,t),Za(n,!0),n.tail===null&&n.tailMode==="hidden"&&!i.alternate&&!yt)return Dt(e),null}else 2*Nt()-n.renderingStartTime>hi&&l!==536870912&&(e.flags|=128,u=!0,Za(n,!1),e.lanes=4194304);n.isBackwards?(i.sibling=e.child,e.child=i):(t=n.last,t!==null?t.sibling=i:e.child=i,n.last=i)}return n.tail!==null?(t=n.tail,n.rendering=t,n.tail=t.sibling,n.renderingStartTime=Nt(),t.sibling=null,l=qt.current,Z(qt,u?l&1|2:l&1),yt&&Fe(e,n.treeForkCount),t):(Dt(e),null);case 22:case 23:return ve(e),Ic(),n=e.memoizedState!==null,t!==null?t.memoizedState!==null!==n&&(e.flags|=8192):n&&(e.flags|=8192),n?(l&536870912)!==0&&(e.flags&128)===0&&(Dt(e),e.subtreeFlags&6&&(e.flags|=8192)):Dt(e),l=e.updateQueue,l!==null&&si(e,l.retryQueue),l=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(l=t.memoizedState.cachePool.pool),n=null,e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),n!==l&&(e.flags|=2048),t!==null&&q(nn),null;case 24:return l=null,t!==null&&(l=t.memoizedState.cache),e.memoizedState.cache!==l&&(e.flags|=2048),Pe(Yt),Dt(e),null;case 25:return null;case 30:return null}throw Error(f(156,e.tag))}function Wy(t,e){switch(qc(e),e.tag){case 1:return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return Pe(Yt),Ct(),t=e.flags,(t&65536)!==0&&(t&128)===0?(e.flags=t&-65537|128,e):null;case 26:case 27:case 5:return Ve(e),null;case 31:if(e.memoizedState!==null){if(ve(e),e.alternate===null)throw Error(f(340));tn()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 13:if(ve(e),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(f(340));tn()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return q(qt),null;case 4:return Ct(),null;case 10:return Pe(e.type),null;case 22:case 23:return ve(e),Ic(),t!==null&&q(nn),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 24:return Pe(Yt),null;case 25:return null;default:return null}}function Td(t,e){switch(qc(e),e.tag){case 3:Pe(Yt),Ct();break;case 26:case 27:case 5:Ve(e);break;case 4:Ct();break;case 31:e.memoizedState!==null&&ve(e);break;case 13:ve(e);break;case 19:q(qt);break;case 10:Pe(e.type);break;case 22:case 23:ve(e),Ic(),t!==null&&q(nn);break;case 24:Pe(Yt)}}function Ka(t,e){try{var l=e.updateQueue,n=l!==null?l.lastEffect:null;if(n!==null){var u=n.next;l=u;do{if((l.tag&t)===t){n=void 0;var i=l.create,o=l.inst;n=i(),o.destroy=n}l=l.next}while(l!==u)}}catch(v){Tt(e,e.return,v)}}function Al(t,e,l){try{var n=e.updateQueue,u=n!==null?n.lastEffect:null;if(u!==null){var i=u.next;n=i;do{if((n.tag&t)===t){var o=n.inst,v=o.destroy;if(v!==void 0){o.destroy=void 0,u=e;var _=l,C=v;try{C()}catch(B){Tt(u,_,B)}}}n=n.next}while(n!==i)}}catch(B){Tt(e,e.return,B)}}function zd(t){var e=t.updateQueue;if(e!==null){var l=t.stateNode;try{mr(e,l)}catch(n){Tt(t,t.return,n)}}}function Ad(t,e,l){l.props=fn(t.type,t.memoizedProps),l.state=t.memoizedState;try{l.componentWillUnmount()}catch(n){Tt(t,e,n)}}function Ja(t,e){try{var l=t.ref;if(l!==null){switch(t.tag){case 26:case 27:case 5:var n=t.stateNode;break;case 30:n=t.stateNode;break;default:n=t.stateNode}typeof l=="function"?t.refCleanup=l(n):l.current=n}}catch(u){Tt(t,e,u)}}function we(t,e){var l=t.ref,n=t.refCleanup;if(l!==null)if(typeof n=="function")try{n()}catch(u){Tt(t,e,u)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof l=="function")try{l(null)}catch(u){Tt(t,e,u)}else l.current=null}function Rd(t){var e=t.type,l=t.memoizedProps,n=t.stateNode;try{t:switch(e){case"button":case"input":case"select":case"textarea":l.autoFocus&&n.focus();break t;case"img":l.src?n.src=l.src:l.srcSet&&(n.srcset=l.srcSet)}}catch(u){Tt(t,t.return,u)}}function Ds(t,e,l){try{var n=t.stateNode;gv(n,t.type,l,e),n[ne]=e}catch(u){Tt(t,t.return,u)}}function Od(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&Ul(t.type)||t.tag===4}function Us(t){t:for(;;){for(;t.sibling===null;){if(t.return===null||Od(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.tag===27&&Ul(t.type)||t.flags&2||t.child===null||t.tag===4)continue t;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function Ls(t,e,l){var n=t.tag;if(n===5||n===6)t=t.stateNode,e?(l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l).insertBefore(t,e):(e=l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l,e.appendChild(t),l=l._reactRootContainer,l!=null||e.onclick!==null||(e.onclick=Je));else if(n!==4&&(n===27&&Ul(t.type)&&(l=t.stateNode,e=null),t=t.child,t!==null))for(Ls(t,e,l),t=t.sibling;t!==null;)Ls(t,e,l),t=t.sibling}function fi(t,e,l){var n=t.tag;if(n===5||n===6)t=t.stateNode,e?l.insertBefore(t,e):l.appendChild(t);else if(n!==4&&(n===27&&Ul(t.type)&&(l=t.stateNode),t=t.child,t!==null))for(fi(t,e,l),t=t.sibling;t!==null;)fi(t,e,l),t=t.sibling}function Md(t){var e=t.stateNode,l=t.memoizedProps;try{for(var n=t.type,u=e.attributes;u.length;)e.removeAttributeNode(u[0]);Pt(e,n,l),e[kt]=t,e[ne]=l}catch(i){Tt(t,t.return,i)}}var nl=!1,Qt=!1,Ns=!1,Cd=typeof WeakSet=="function"?WeakSet:Set,Kt=null;function Fy(t,e){if(t=t.containerInfo,ef=xi,t=Go(t),Oc(t)){if("selectionStart"in t)var l={start:t.selectionStart,end:t.selectionEnd};else t:{l=(l=t.ownerDocument)&&l.defaultView||window;var n=l.getSelection&&l.getSelection();if(n&&n.rangeCount!==0){l=n.anchorNode;var u=n.anchorOffset,i=n.focusNode;n=n.focusOffset;try{l.nodeType,i.nodeType}catch{l=null;break t}var o=0,v=-1,_=-1,C=0,B=0,j=t,x=null;e:for(;;){for(var U;j!==l||u!==0&&j.nodeType!==3||(v=o+u),j!==i||n!==0&&j.nodeType!==3||(_=o+n),j.nodeType===3&&(o+=j.nodeValue.length),(U=j.firstChild)!==null;)x=j,j=U;for(;;){if(j===t)break e;if(x===l&&++C===u&&(v=o),x===i&&++B===n&&(_=o),(U=j.nextSibling)!==null)break;j=x,x=j.parentNode}j=U}l=v===-1||_===-1?null:{start:v,end:_}}else l=null}l=l||{start:0,end:0}}else l=null;for(lf={focusedElem:t,selectionRange:l},xi=!1,Kt=e;Kt!==null;)if(e=Kt,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,Kt=t;else for(;Kt!==null;){switch(e=Kt,i=e.alternate,t=e.flags,e.tag){case 0:if((t&4)!==0&&(t=e.updateQueue,t=t!==null?t.events:null,t!==null))for(l=0;l title"))),Pt(i,n,l),i[kt]=t,Zt(i),n=i;break t;case"link":var o=Bh("link","href",u).get(n+(l.href||""));if(o){for(var v=0;vOt&&(o=Ot,Ot=tt,tt=o);var O=wo(v,tt),z=wo(v,Ot);if(O&&z&&(U.rangeCount!==1||U.anchorNode!==O.node||U.anchorOffset!==O.offset||U.focusNode!==z.node||U.focusOffset!==z.offset)){var M=j.createRange();M.setStart(O.node,O.offset),U.removeAllRanges(),tt>Ot?(U.addRange(M),U.extend(z.node,z.offset)):(M.setEnd(z.node,z.offset),U.addRange(M))}}}}for(j=[],U=v;U=U.parentNode;)U.nodeType===1&&j.push({element:U,left:U.scrollLeft,top:U.scrollTop});for(typeof v.focus=="function"&&v.focus(),v=0;vl?32:l,N.T=null,l=Gs,Gs=null;var i=Cl,o=sl;if(Vt=0,Fn=Cl=null,sl=0,(St&6)!==0)throw Error(f(331));var v=St;if(St|=4,Yd(i.current),jd(i,i.current,o,l),St=v,Ia(0,!1),re&&typeof re.onPostCommitFiberRoot=="function")try{re.onPostCommitFiberRoot(ga,i)}catch{}return!0}finally{V.p=u,N.T=n,ah(t,e)}}function ih(t,e,l){e=Te(l,e),e=bs(t.stateNode,e,2),t=El(t,e,2),t!==null&&(Sa(t,2),Ye(t))}function Tt(t,e,l){if(t.tag===3)ih(t,t,l);else for(;e!==null;){if(e.tag===3){ih(e,t,l);break}else if(e.tag===1){var n=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof n.componentDidCatch=="function"&&(Ml===null||!Ml.has(n))){t=Te(l,t),l=cd(2),n=El(e,l,2),n!==null&&(sd(l,n,e,t),Sa(n,2),Ye(n));break}}e=e.return}}function Zs(t,e,l){var n=t.pingCache;if(n===null){n=t.pingCache=new Iy;var u=new Set;n.set(e,u)}else u=n.get(e),u===void 0&&(u=new Set,n.set(e,u));u.has(l)||(js=!0,u.add(l),t=av.bind(null,t,e,l),e.then(t,t))}function av(t,e,l){var n=t.pingCache;n!==null&&n.delete(e),t.pingedLanes|=t.suspendedLanes&l,t.warmLanes&=~l,Mt===t&&(ht&l)===l&&(jt===4||jt===3&&(ht&62914560)===ht&&300>Nt()-di?(St&2)===0&&$n(t,0):qs|=l,Wn===ht&&(Wn=0)),Ye(t)}function ch(t,e){e===0&&(e=to()),t=Pl(t,e),t!==null&&(Sa(t,e),Ye(t))}function uv(t){var e=t.memoizedState,l=0;e!==null&&(l=e.retryLane),ch(t,l)}function iv(t,e){var l=0;switch(t.tag){case 31:case 13:var n=t.stateNode,u=t.memoizedState;u!==null&&(l=u.retryLane);break;case 19:n=t.stateNode;break;case 22:n=t.stateNode._retryCache;break;default:throw Error(f(314))}n!==null&&n.delete(e),ch(t,l)}function cv(t,e){return ma(t,e)}var Si=null,In=null,Ks=!1,bi=!1,Js=!1,Dl=0;function Ye(t){t!==In&&t.next===null&&(In===null?Si=In=t:In=In.next=t),bi=!0,Ks||(Ks=!0,fv())}function Ia(t,e){if(!Js&&bi){Js=!0;do for(var l=!1,n=Si;n!==null;){if(t!==0){var u=n.pendingLanes;if(u===0)var i=0;else{var o=n.suspendedLanes,v=n.pingedLanes;i=(1<<31-de(42|t)+1)-1,i&=u&~(o&~v),i=i&201326741?i&201326741|1:i?i|2:0}i!==0&&(l=!0,rh(n,i))}else i=ht,i=zu(n,n===Mt?i:0,n.cancelPendingCommit!==null||n.timeoutHandle!==-1),(i&3)===0||pa(n,i)||(l=!0,rh(n,i));n=n.next}while(l);Js=!1}}function sv(){sh()}function sh(){bi=Ks=!1;var t=0;Dl!==0&&Sv()&&(t=Dl);for(var e=Nt(),l=null,n=Si;n!==null;){var u=n.next,i=fh(n,e);i===0?(n.next=null,l===null?Si=u:l.next=u,u===null&&(In=l)):(l=n,(t!==0||(i&3)!==0)&&(bi=!0)),n=u}Vt!==0&&Vt!==5||Ia(t),Dl!==0&&(Dl=0)}function fh(t,e){for(var l=t.suspendedLanes,n=t.pingedLanes,u=t.expirationTimes,i=t.pendingLanes&-62914561;0v)break;var B=_.transferSize,j=_.initiatorType;B&&Sh(j)&&(_=_.responseEnd,o+=B*(_"u"?null:document;function Dh(t,e,l){var n=ta;if(n&&typeof e=="string"&&e){var u=_e(e);u='link[rel="'+t+'"][href="'+u+'"]',typeof l=="string"&&(u+='[crossorigin="'+l+'"]'),xh.has(u)||(xh.add(u),t={rel:t,crossOrigin:l,href:e},n.querySelector(u)===null&&(e=n.createElement("link"),Pt(e,"link",t),Zt(e),n.head.appendChild(e)))}}function Mv(t){fl.D(t),Dh("dns-prefetch",t,null)}function Cv(t,e){fl.C(t,e),Dh("preconnect",t,e)}function xv(t,e,l){fl.L(t,e,l);var n=ta;if(n&&t&&e){var u='link[rel="preload"][as="'+_e(e)+'"]';e==="image"&&l&&l.imageSrcSet?(u+='[imagesrcset="'+_e(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(u+='[imagesizes="'+_e(l.imageSizes)+'"]')):u+='[href="'+_e(t)+'"]';var i=u;switch(e){case"style":i=ea(t);break;case"script":i=la(t)}Ce.has(i)||(t=p({rel:"preload",href:e==="image"&&l&&l.imageSrcSet?void 0:t,as:e},l),Ce.set(i,t),n.querySelector(u)!==null||e==="style"&&n.querySelector(nu(i))||e==="script"&&n.querySelector(au(i))||(e=n.createElement("link"),Pt(e,"link",t),Zt(e),n.head.appendChild(e)))}}function Dv(t,e){fl.m(t,e);var l=ta;if(l&&t){var n=e&&typeof e.as=="string"?e.as:"script",u='link[rel="modulepreload"][as="'+_e(n)+'"][href="'+_e(t)+'"]',i=u;switch(n){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":i=la(t)}if(!Ce.has(i)&&(t=p({rel:"modulepreload",href:t},e),Ce.set(i,t),l.querySelector(u)===null)){switch(n){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(au(i)))return}n=l.createElement("link"),Pt(n,"link",t),Zt(n),l.head.appendChild(n)}}}function Uv(t,e,l){fl.S(t,e,l);var n=ta;if(n&&t){var u=Tn(n).hoistableStyles,i=ea(t);e=e||"default";var o=u.get(i);if(!o){var v={loading:0,preload:null};if(o=n.querySelector(nu(i)))v.loading=5;else{t=p({rel:"stylesheet",href:t,"data-precedence":e},l),(l=Ce.get(i))&&of(t,l);var _=o=n.createElement("link");Zt(_),Pt(_,"link",t),_._p=new Promise(function(C,B){_.onload=C,_.onerror=B}),_.addEventListener("load",function(){v.loading|=1}),_.addEventListener("error",function(){v.loading|=2}),v.loading|=4,Ai(o,e,n)}o={type:"stylesheet",instance:o,count:1,state:v},u.set(i,o)}}}function Lv(t,e){fl.X(t,e);var l=ta;if(l&&t){var n=Tn(l).hoistableScripts,u=la(t),i=n.get(u);i||(i=l.querySelector(au(u)),i||(t=p({src:t,async:!0},e),(e=Ce.get(u))&&rf(t,e),i=l.createElement("script"),Zt(i),Pt(i,"link",t),l.head.appendChild(i)),i={type:"script",instance:i,count:1,state:null},n.set(u,i))}}function Nv(t,e){fl.M(t,e);var l=ta;if(l&&t){var n=Tn(l).hoistableScripts,u=la(t),i=n.get(u);i||(i=l.querySelector(au(u)),i||(t=p({src:t,async:!0,type:"module"},e),(e=Ce.get(u))&&rf(t,e),i=l.createElement("script"),Zt(i),Pt(i,"link",t),l.head.appendChild(i)),i={type:"script",instance:i,count:1,state:null},n.set(u,i))}}function Uh(t,e,l,n){var u=(u=it.current)?zi(u):null;if(!u)throw Error(f(446));switch(t){case"meta":case"title":return null;case"style":return typeof l.precedence=="string"&&typeof l.href=="string"?(e=ea(l.href),l=Tn(u).hoistableStyles,n=l.get(e),n||(n={type:"style",instance:null,count:0,state:null},l.set(e,n)),n):{type:"void",instance:null,count:0,state:null};case"link":if(l.rel==="stylesheet"&&typeof l.href=="string"&&typeof l.precedence=="string"){t=ea(l.href);var i=Tn(u).hoistableStyles,o=i.get(t);if(o||(u=u.ownerDocument||u,o={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},i.set(t,o),(i=u.querySelector(nu(t)))&&!i._p&&(o.instance=i,o.state.loading=5),Ce.has(t)||(l={rel:"preload",as:"style",href:l.href,crossOrigin:l.crossOrigin,integrity:l.integrity,media:l.media,hrefLang:l.hrefLang,referrerPolicy:l.referrerPolicy},Ce.set(t,l),i||Bv(u,t,l,o.state))),e&&n===null)throw Error(f(528,""));return o}if(e&&n!==null)throw Error(f(529,""));return null;case"script":return e=l.async,l=l.src,typeof l=="string"&&e&&typeof e!="function"&&typeof e!="symbol"?(e=la(l),l=Tn(u).hoistableScripts,n=l.get(e),n||(n={type:"script",instance:null,count:0,state:null},l.set(e,n)),n):{type:"void",instance:null,count:0,state:null};default:throw Error(f(444,t))}}function ea(t){return'href="'+_e(t)+'"'}function nu(t){return'link[rel="stylesheet"]['+t+"]"}function Lh(t){return p({},t,{"data-precedence":t.precedence,precedence:null})}function Bv(t,e,l,n){t.querySelector('link[rel="preload"][as="style"]['+e+"]")?n.loading=1:(e=t.createElement("link"),n.preload=e,e.addEventListener("load",function(){return n.loading|=1}),e.addEventListener("error",function(){return n.loading|=2}),Pt(e,"link",l),Zt(e),t.head.appendChild(e))}function la(t){return'[src="'+_e(t)+'"]'}function au(t){return"script[async]"+t}function Nh(t,e,l){if(e.count++,e.instance===null)switch(e.type){case"style":var n=t.querySelector('style[data-href~="'+_e(l.href)+'"]');if(n)return e.instance=n,Zt(n),n;var u=p({},l,{"data-href":l.href,"data-precedence":l.precedence,href:null,precedence:null});return n=(t.ownerDocument||t).createElement("style"),Zt(n),Pt(n,"style",u),Ai(n,l.precedence,t),e.instance=n;case"stylesheet":u=ea(l.href);var i=t.querySelector(nu(u));if(i)return e.state.loading|=4,e.instance=i,Zt(i),i;n=Lh(l),(u=Ce.get(u))&&of(n,u),i=(t.ownerDocument||t).createElement("link"),Zt(i);var o=i;return o._p=new Promise(function(v,_){o.onload=v,o.onerror=_}),Pt(i,"link",n),e.state.loading|=4,Ai(i,l.precedence,t),e.instance=i;case"script":return i=la(l.src),(u=t.querySelector(au(i)))?(e.instance=u,Zt(u),u):(n=l,(u=Ce.get(i))&&(n=p({},l),rf(n,u)),t=t.ownerDocument||t,u=t.createElement("script"),Zt(u),Pt(u,"link",n),t.head.appendChild(u),e.instance=u);case"void":return null;default:throw Error(f(443,e.type))}else e.type==="stylesheet"&&(e.state.loading&4)===0&&(n=e.instance,e.state.loading|=4,Ai(n,l.precedence,t));return e.instance}function Ai(t,e,l){for(var n=l.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),u=n.length?n[n.length-1]:null,i=u,o=0;o title"):null)}function Hv(t,e,l){if(l===1||e.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof e.precedence!="string"||typeof e.href!="string"||e.href==="")break;return!0;case"link":if(typeof e.rel!="string"||typeof e.href!="string"||e.href===""||e.onLoad||e.onError)break;return e.rel==="stylesheet"?(t=e.disabled,typeof e.precedence=="string"&&t==null):!0;case"script":if(e.async&&typeof e.async!="function"&&typeof e.async!="symbol"&&!e.onLoad&&!e.onError&&e.src&&typeof e.src=="string")return!0}return!1}function jh(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function jv(t,e,l,n){if(l.type==="stylesheet"&&(typeof n.media!="string"||matchMedia(n.media).matches!==!1)&&(l.state.loading&4)===0){if(l.instance===null){var u=ea(n.href),i=e.querySelector(nu(u));if(i){e=i._p,e!==null&&typeof e=="object"&&typeof e.then=="function"&&(t.count++,t=Oi.bind(t),e.then(t,t)),l.state.loading|=4,l.instance=i,Zt(i);return}i=e.ownerDocument||e,n=Lh(n),(u=Ce.get(u))&&of(n,u),i=i.createElement("link"),Zt(i);var o=i;o._p=new Promise(function(v,_){o.onload=v,o.onerror=_}),Pt(i,"link",n),l.instance=i}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(l,e),(e=l.state.preload)&&(l.state.loading&3)===0&&(t.count++,l=Oi.bind(t),e.addEventListener("load",l),e.addEventListener("error",l))}}var df=0;function qv(t,e){return t.stylesheets&&t.count===0&&Ci(t,t.stylesheets),0df?50:800)+e);return t.unsuspend=l,function(){t.unsuspend=null,clearTimeout(n),clearTimeout(u)}}:null}function Oi(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Ci(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var Mi=null;function Ci(t,e){t.stylesheets=null,t.unsuspend!==null&&(t.count++,Mi=new Map,e.forEach(wv,t),Mi=null,Oi.call(t))}function wv(t,e){if(!(e.state.loading&4)){var l=Mi.get(t);if(l)var n=l.get(null);else{l=new Map,Mi.set(t,l);for(var u=t.querySelectorAll("link[data-precedence],style[data-precedence]"),i=0;i"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(a)}catch(c){console.error(c)}}return a(),_f.exports=lg(),_f.exports}var ag=ng();const ug=!1;var cm=at.use,Ym=at.useLayoutEffect;function ig(a,c,s){at.useEffect(()=>{if(!a.current||s||typeof IntersectionObserver!="function")return()=>c();const f=new IntersectionObserver(r=>{c(r.pop())},{rootMargin:"100px"});return f.observe(a.current),()=>{f.disconnect(),c()}},[c,s,a])}function cg(a){const c=at.useRef(null);return at.useImperativeHandle(a,()=>c.current,[]),c}function mu(a){return a[a.length-1]}function sg(a){return typeof a=="function"}function ra(a,c){return sg(a)?a(c):a}const Gm=Object.prototype.hasOwnProperty,fg=Object.prototype.propertyIsEnumerable;function Xm(a){for(const c in a)if(Gm.call(a,c))return!0;return!1}const og=()=>Object.create(null),dn=(a,c)=>mn(a,c,og);function mn(a,c,s=()=>({}),f=0){if(a===c)return a;if(f>500)return c;const r=c,h=om(a)&&om(r);if(!h&&!(Ki(a)&&Ki(r)))return r;const g=h?a:sm(a);if(!g)return r;const m=h?r:sm(r);if(!m)return r;const y=g.length,d=m.length,S=h?new Array(d):s();let p=0;for(let b=0;b"u")return!0;const s=c.prototype;return!(!fm(s)||!s.hasOwnProperty("isPrototypeOf"))}function fm(a){return Object.prototype.toString.call(a)==="[object Object]"}function om(a){return Array.isArray(a)&&a.length===Object.keys(a).length}function Yl(a,c,s){if(a===c)return!0;if(typeof a!=typeof c)return!1;if(Array.isArray(a)&&Array.isArray(c)){if(a.length!==c.length)return!1;for(let f=0,r=a.length;fr||!Yl(a[g],c[g],s)))return!1;return r===h}return!1}function rg(a){return typeof a?.message!="string"?!1:a.message.startsWith("Failed to fetch dynamically imported module")||a.message.startsWith("error loading dynamically imported module")||a.message.startsWith("Importing a module script failed")}const dg=/[\x00-\x1f\x7f"<>`{}]/g;function hg(a){return a.replace(dg,c=>"%"+c.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0"))}function rm(a){let c;try{c=decodeURI(a)}catch{c=a.replaceAll(/%[0-9A-F]{2}/gi,s=>{try{return decodeURI(s)}catch{return s}})}return hg(c)}const mg=["http:","https:","mailto:","tel:"];function Ji(a,c){if(!a)return!1;try{const s=new URL(a);return!c.has(s.protocol)}catch{return!1}}function ru(a){if(!a)return{path:a,handledProtocolRelativeURL:!1};if(!/[%\\\x00-\x1f\x7f]/.test(a)&&!a.startsWith("//"))return{path:a,handledProtocolRelativeURL:!1};const c=/%25|%5C/gi;let s=0,f="",r;for(;(r=c.exec(a))!==null;)f+=rm(a.slice(s,r.index))+r[0],s=c.lastIndex;f=f+rm(s?a.slice(s):a);let h=!1;return f.startsWith("//")&&(h=!0,f="/"+f.replace(/^\/+/,"")),{path:f,handledProtocolRelativeURL:h}}function yg(a){return/\s|[^\u0000-\u007F]/.test(a)?a.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):a}function vg(a,c){if(a===c)return!0;if(a.length!==c.length)return!1;for(let s=0;s{h.next&&(h.prev?(h.prev.next=h.next,h.next.prev=h.prev,h.next=void 0,f&&(f.next=h,h.prev=f)):(h.next.prev=void 0,s=h.next,h.next=void 0,f&&(h.prev=f,f.next=h)),f=h)};return{get(h){const g=c.get(h);if(g)return r(g),g.value},set(h,g){if(c.size>=a&&s){const y=s;c.delete(y.key),y.next&&(s=y.next,y.next.prev=void 0),y===f&&(f=void 0)}const m=c.get(h);if(m)m.value=g,r(m);else{const y={key:h,value:g,prev:f};f&&(f.next=y),f=y,s||(s=y),c.set(h,y)}},clear(){c.clear(),s=void 0,f=void 0}}}const wl=4,Qm=5;function gg(a){const c=a.indexOf("{");if(c===-1)return null;const s=a.indexOf("}",c);return s===-1||c+1>=a.length?null:[c,s]}function Vm(a,c,s=new Uint16Array(6)){const f=a.indexOf("/",c),r=f===-1?a.length:f,h=a.substring(c,r);if(!h||!h.includes("$"))return s[0]=0,s[1]=c,s[2]=c,s[3]=r,s[4]=r,s[5]=r,s;if(h==="$"){const m=a.length;return s[0]=2,s[1]=c,s[2]=c,s[3]=m,s[4]=m,s[5]=m,s}if(h.charCodeAt(0)===36)return s[0]=1,s[1]=c,s[2]=c+1,s[3]=r,s[4]=r,s[5]=r,s;const g=gg(h);if(g){const[m,y]=g,d=h.charCodeAt(m+1);if(d===45){if(m+2!P.parse&&P.caseSensitive===G&&P.prefix===L&&P.suffix===Q);if(ct)D=ct;else{const P=pg(K,d,G,L,Q);D=P,P.parent=r,P.depth=h;let ft;K===1?ft=r.dynamic??=[]:K===3?ft=r.optional??=[]:ft=r.wildcard??=[],ft.push(P),ft.length===2&&g?.push(ft)}break}}r=D}if(T&&s.children&&!s.isRoot&&s.id&&s.id.charCodeAt(s.id.lastIndexOf("/")+1)===95){const E=ca(d);E.kind=Qm,E.parent=r,h++,E.depth=h,r.pathless??=[],r.pathless.push(E),r=E}const R=(s.path||!s.children)&&!s.isRoot;if(R&&d.endsWith("/")){const E=ca(d);E.kind=wl,E.parent=r,h++,E.depth=h,r.index=E,r=E}r.parse=T??null,r.priority=S?.params?.priority??0,R&&!r.route&&(r.route=s,r.fullPath=d)}if(s.children)for(const d of s.children)ec(a,c,d,y,r,h,g,m)}function Zm(a,c){if(a.parse&&!c.parse)return-1;if(!a.parse&&c.parse)return 1;if(a.parse&&c.parse&&(a.priority||c.priority))return c.priority-a.priority;if(a.prefix&&c.prefix&&a.prefix!==c.prefix){if(a.prefix.startsWith(c.prefix))return-1;if(c.prefix.startsWith(a.prefix))return 1}if(a.suffix&&c.suffix&&a.suffix!==c.suffix){if(a.suffix.endsWith(c.suffix))return-1;if(c.suffix.endsWith(a.suffix))return 1}return a.prefix&&!c.prefix?-1:!a.prefix&&c.prefix?1:a.suffix&&!c.suffix?-1:!a.suffix&&c.suffix?1:a.caseSensitive&&!c.caseSensitive?-1:!a.caseSensitive&&c.caseSensitive?1:0}function ca(a){return{kind:0,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:a,parent:null,parse:null,priority:0}}function pg(a,c,s,f,r){return{kind:a,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:c,parent:null,parse:null,priority:0,caseSensitive:s,prefix:f,suffix:r}}function Sg(a,c){const s=ca("/"),f=new Uint16Array(6),r=[];for(const h of a)ec(!1,f,h,1,s,0,r);for(const h of r)h.sort(Zm);c.masksTree=s,c.flatCache=ki(1e3)}function bg(a,c){a||="/";const s=c.flatCache.get(a);if(s)return s;const f=Qf(a,c.masksTree);return c.flatCache.set(a,f),f}function _g(a,c,s,f,r){a||="/",f||="/";const h=c?`case\0${a}`:a;let g=r.singleCache.get(h);return g||(g=ca("/"),ec(c,new Uint16Array(6),{from:a},1,g,0),r.singleCache.set(h,g)),Qf(f,g,s)}function Eg(a,c,s=!1){const f=s?a:`nofuzz\0${a}`,r=c.matchCache.get(f);if(r!==void 0)return r;a||="/";let h;try{h=Qf(a,c.segmentTree,s)}catch(g){if(g instanceof URIError)h=null;else throw g}return h&&(h.branch=Jm(h.route)),c.matchCache.set(f,h),h}function Tg(a){return a==="/"?a:a.replace(/\/{1,}$/,"")}function zg(a,c=!1,s){const f=ca(a.fullPath),r=new Uint16Array(6),h=[],g={},m={};let y=0;ec(c,r,a,1,f,0,h,d=>{if(s?.(d,y),d.id in g&&Xf(),g[d.id]=d,y!==0&&d.path){const S=Tg(d.fullPath);(!m[S]||d.fullPath.endsWith("/"))&&(m[S]=d)}y++});for(const d of h)d.sort(Zm);return{processedTree:{segmentTree:f,singleCache:ki(1e3),matchCache:ki(1e3),flatCache:null,masksTree:null},routesById:g,routesByPath:m}}function Qf(a,c,s=!1){const f=a.split("/"),r=Rg(a,f,c,s);if(!r)return null;const[h]=Km(a,f,r);return{route:r.node.route,rawParams:h}}function Km(a,c,s){const f=Ag(s.node);let r=null;const h=Object.create(null);let g=s.extract?.part??0,m=s.extract?.node??0,y=s.extract?.path??0,d=s.extract?.segment??0;for(;m=0;G--){const L=p.wildcard[G],{prefix:Q,suffix:J}=L;if(!(Q&&(K||!(L.caseSensitive?X:et??=X.toLowerCase()).startsWith(Q)))){if(J){if(K)continue;const ct=c.slice(b).join("/").slice(-J.length);if((L.caseSensitive?ct:ct.toLowerCase())!==J)continue}m.push({node:L,index:g,skipped:T,statics:R,dynamics:E,optionals:D,extract:w,rawParams:Y})}}if(p.optional){const G=T|1<=0;L--){const Q=p.optional[L];m.push({node:Q,index:b,skipped:G,statics:R,dynamics:E,optionals:D,extract:w,rawParams:Y})}if(!K)for(let L=p.optional.length-1;L>=0;L--){const Q=p.optional[L],{prefix:J,suffix:ct}=Q;if(J||ct){const P=Q.caseSensitive?X:et??=X.toLowerCase();if(J&&!P.startsWith(J)||ct&&!P.endsWith(ct))continue}m.push({node:Q,index:b+1,skipped:T,statics:R,dynamics:E,optionals:D+ji(g,b),extract:w,rawParams:Y})}}if(!K&&p.dynamic&&X)for(let G=p.dynamic.length-1;G>=0;G--){const L=p.dynamic[G],{prefix:Q,suffix:J}=L;if(Q||J){const ct=L.caseSensitive?X:et??=X.toLowerCase();if(Q&&!ct.startsWith(Q)||J&&!ct.endsWith(J))continue}m.push({node:L,index:b+1,skipped:T,statics:R,dynamics:E+ji(g,b),optionals:D,extract:w,rawParams:Y})}if(!K&&p.staticInsensitive){const G=p.staticInsensitive.get(et??=X.toLowerCase());G&&m.push({node:G,index:b+1,skipped:T,statics:R+ji(g,b),dynamics:E,optionals:D,extract:w,rawParams:Y})}if(!K&&p.static){const G=p.static.get(X);G&&m.push({node:G,index:b+1,skipped:T,statics:R+ji(g,b),dynamics:E,optionals:D,extract:w,rawParams:Y})}if(p.pathless)for(let G=p.pathless.length-1;G>=0;G--){const L=p.pathless[G];m.push({node:L,index:b,skipped:T,statics:R,dynamics:E,optionals:D,extract:w,rawParams:Y})}}if(d)return d;if(f&&y){let S=y.index;for(let b=0;ba.statics||c.statics===a.statics&&(c.dynamics>a.dynamics||c.dynamics===a.dynamics&&(c.optionals>a.optionals||c.optionals===a.optionals&&((c.node.kind===wl)>(a.node.kind===wl)||c.node.kind===wl==(a.node.kind===wl)&&c.node.depth>a.node.depth))):!0}function Gi(a){return Vf(a.filter(c=>c!==void 0).join("/"))}function Vf(a){return a.replace(/\/{2,}/g,"/")}function km(a){return a==="/"?a:a.replace(/^\/{1,}/,"")}function ol(a){const c=a.length;return c>1&&a[c-1]==="/"?a.replace(/\/{1,}$/,""):a}function Wm(a){return ol(km(a))}function Wi(a,c){return a?.endsWith("/")&&a!=="/"&&a!==`${c}/`?a.slice(0,-1):a}function Mg(a,c,s){return Wi(a,s)===Wi(c,s)}function Cg({base:a,to:c,trailingSlash:s="never",cache:f}){const r=c===".",h=c.startsWith("/");let g;if(f){g=h?c:r?a:a+"\0"+c;const d=f.get(g);if(d)return d}let m;if(r)m=a.split("/");else if(h)m=c.split("/");else{for(m=a.split("/");m.length>1&&mu(m)==="";)m.pop();const d=c.split("/");for(let S=0,p=d.length;S1?m.pop():m=[""]:b==="."||m.push(b)}}m.length>1&&(mu(m)===""?s==="never"&&m.pop():s==="always"&&m.push(""));const y=Vf(m.join("/"))||"/";return g&&f&&f.set(g,y),y}function xg(a){const c=new Map(a.map(r=>[encodeURIComponent(r),r])),s=Array.from(c.keys()).map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),f=new RegExp(s,"g");return r=>r.replace(f,h=>c.get(h)??h)}function Af(a,c,s){const f=c[a];return typeof f!="string"?f:a==="_splat"?/^[a-zA-Z0-9\-._~!/]*$/.test(f)?f:f.split("/").map(r=>mm(r,s)).join("/"):mm(f,s)}function hm({path:a,params:c,decoder:s,...f}){let r=!1;const h=Object.create(null);if(!a||a==="/")return{interpolatedPath:"/",usedParams:h,isMissingParams:r};if(!a.includes("$"))return{interpolatedPath:a,usedParams:h,isMissingParams:r};const g=a.length;let m=0,y,d="";for(;ma.state.__TSR_key||a.href;function Hg(a){const c=a.getAttribute(ym);if(c)return`[${ym}="${c}"]`;let s="",f=a,r;for(;r=f.parentNode;){let h=1,g=f;for(;g=g.previousElementSibling;)h++;const m=`${f.localName}:nth-child(${h})`;s=s?`${m} > ${s}`:m,f=r}return s}let wi=!1;const Xi="window";function Nf(a){try{return typeof a=="function"?a():document.querySelector(a)}catch{}}function vm(a){const c=new Set;for(const s of a){if(s===Xi)continue;const f=Nf(s);f&&c.add(f)}return c}function jg(a,c){const s=a.options.scrollRestoration,f=a._scroll;s&&(f.restoring=!0);const r=a.options.getScrollRestorationKey||Bg,h=new Set,g=m=>{const y=ua[m]||={};for(const d of h)d===document?y[Xi]={scrollX,scrollY}:d.isConnected&&(y[Hg(d)]={scrollX:d.scrollLeft,scrollY:d.scrollTop})};s&&!f.restoration&&(f.restoration=!0,wi=!1,history.scrollRestoration="manual",document.addEventListener("scroll",m=>{wi||h.add(m.target)},!0),a.subscribe("onBeforeLoad",m=>{m.fromLocation&&g(r(m.fromLocation)),h.clear()}),addEventListener("pagehide",()=>{g(r(a.stores.resolvedLocation.get()??a.stores.location.get())),Ng()})),!f.reset&&(f.reset=!0,a.subscribe("onRendered",m=>{const y=a.options.scrollRestorationBehavior,d=a.options.scrollToTopSelectors,S=f.next,p=f.hash;let b;if(h.clear(),f.next=!0,f.hash=!1,typeof a.options.scrollRestoration=="function"&&!a.options.scrollRestoration({location:a.latestLocation}))return;const T=r(m.toLocation),R=m.fromLocation&&r(m.fromLocation);if(f.restoring&&R&&R!==T){const E=ua[R];if(E){let D=ua[T];for(const w in E){if(w===Xi){if(S)continue}else{const Y=Nf(w);if(!Y||S&&d&&(b??=vm(d),b.has(Y)))continue}D||(D=ua[T]={}),D[w]??=E[w]}}}wi=!0;try{const E=m.toLocation.hash,D=m.toLocation.state.__hashScrollIntoViewOptions??!0;let w=!1;if(S){!E&&d&&(b??=vm(d));const Y=E&&D&&p,K=f.restoring?ua[T]:void 0;if(K)for(const X in K){const{scrollX:et,scrollY:G}=K[X];if(X===Xi){if(Y)continue;scrollTo({top:G,left:et,behavior:y}),w=!0}else{const L=Nf(X);L&&(L.scrollLeft=et,L.scrollTop=G,b?.delete(L))}}if(!E){const X={top:0,left:0,behavior:y};if(w||scrollTo(X),b)for(const et of b)et.scrollTo(X)}}!w&&E&&D&&document.getElementById(E)?.scrollIntoView(D)}finally{wi=!1}}))}function qg(a,c=String){const s=new URLSearchParams;for(const f in a){const r=a[f];r!==void 0&&s.set(f,c(r))}return s.toString()}function Rf(a){return a?a==="false"?!1:a==="true"?!0:+a*0===0&&+a+""===a?+a:a:""}function wg(a){const c=new URLSearchParams(a),s=Object.create(null);for(const[f,r]of c.entries()){const h=s[f];h==null?s[f]=Rf(r):Array.isArray(h)?h.push(Rf(r)):s[f]=[h,Rf(r)]}return s}const Yg=/^(?:\s|["[{\d-]|fa|nu|tr)/,Gg=Qg(JSON.parse),Xg=Vg(JSON.stringify,JSON.parse);function Qg(a){return c=>{c[0]==="?"&&(c=c.substring(1));const s=wg(c);for(const f in s){const r=s[f];if(typeof r=="string")try{s[f]=a(r)}catch{}}return s}}function Vg(a,c){const s=c===JSON.parse;function f(r){if(r&&typeof r=="object")try{return a(r)}catch{}else if(c&&typeof r=="string"){if(s&&!Yg.test(r))return r;try{return c(r),a(r)}catch{}}return r}return r=>{const h=qg(r,f);return h?`?${h}`:""}}const sa="__root__";function Zg(a){if(a.statusCode=a.statusCode||a.code||307,!a._builtLocation&&!a.reloadDocument&&typeof a.href=="string")try{new URL(a.href),a.reloadDocument=!0}catch{}const c=new Headers(a.headers);a.href&&c.get("Location")===null&&c.set("Location",a.href);const s=new Response(null,{status:a.statusCode,headers:c});if(s.options=a,a.throw)throw s;return s}function Zf(a){return a instanceof Response&&!!a.options}function Kg(a){return{input:({url:c})=>{for(const s of a)c=Bf(s,c);return c},output:({url:c})=>{for(let s=a.length-1;s>=0;s--)c=$m(a[s],c);return c}}}function Jg(a){const c=Wm(a.basepath),s=`/${c}`,f=a.caseSensitive?s:s.toLowerCase(),r=`${f}/`;return{input:({url:h})=>{const g=a.caseSensitive?h.pathname:h.pathname.toLowerCase();return g===f?h.pathname="/":g.startsWith(r)&&(h.pathname=h.pathname.slice(s.length)),h},output:({url:h})=>(h.pathname=Gi(["/",c,h.pathname]),h)}}function Bf(a,c){const s=a?.input?.({url:c});if(s){if(typeof s=="string")return new URL(s);if(s instanceof URL)return s}return c}function $m(a,c){const s=a?.output?.({url:c});if(s){if(typeof s=="string")return new URL(s);if(s instanceof URL)return s}return c}function kg(a,c){const{createMutableStore:s,createReadonlyStore:f,batch:r}=c,h=new Map,g=s("idle"),m=s(a),y=s(void 0),d=s([]),S=f(()=>d.get().map(E=>h.get(E).get())),p=f(()=>({status:g.get(),isLoading:g.get()==="pending",matches:S.get(),location:m.get(),resolvedLocation:y.get()}));function b(E){let D=h.get(E);return D||(D=s(void 0),h.set(E,D)),D}const T={status:g,location:m,resolvedLocation:y,ids:d,matches:S,byRoute:h,__store:p,getMatchStore:b,setMatches:R};function R(E){const D=d.get(),w=E.map(Y=>Y.routeId);r(()=>{vg(D,w)||d.set(w);for(const Y of D)w.includes(Y)||h.get(Y).set(()=>{});for(const Y of E){const K=b(Y.routeId);K.get()!==Y&&K.set(Y)}})}return T}var Gl="__TSR_index",gm="popstate",pm="beforeunload";function Wg(a){let c=a.getLocation();const s=new Set,f=g=>{c=a.getLocation(),s.forEach(m=>m({location:c,action:g}))},r=g=>{a.notifyOnIndexChange??!0?f(g):c=a.getLocation()},h=async({task:g,navigateOpts:m,...y})=>{if(m?.ignoreBlocker??!1){g();return}const d=a.getBlockers?.()??[],S=y.type==="PUSH"||y.type==="REPLACE";if(typeof document<"u"&&d.length&&S)for(const p of d){const b=Fi(y.path,y.state);if(await p.blockerFn({currentLocation:c,nextLocation:b,action:y.type})){a.onBlocked?.();return}}g()};return{get location(){return c},get length(){return a.getLength()},subscribers:s,subscribe:g=>(s.add(g),()=>{s.delete(g)}),push:(g,m,y)=>{const d=c.state[Gl];m=Sm(d+1,m),h({task:()=>{a.pushState(g,m),f({type:"PUSH"})},navigateOpts:y,type:"PUSH",path:g,state:m})},replace:(g,m,y)=>{const d=c.state[Gl];m=Sm(d,m),h({task:()=>{a.replaceState(g,m),f({type:"REPLACE"})},navigateOpts:y,type:"REPLACE",path:g,state:m})},go:(g,m)=>{h({task:()=>{a.go(g),r({type:"GO",index:g})},navigateOpts:m,type:"GO"})},back:g=>{h({task:()=>{a.back(g?.ignoreBlocker??!1),r({type:"BACK"})},navigateOpts:g,type:"BACK"})},forward:g=>{h({task:()=>{a.forward(g?.ignoreBlocker??!1),r({type:"FORWARD"})},navigateOpts:g,type:"FORWARD"})},canGoBack:()=>c.state[Gl]!==0,createHref:g=>a.createHref(g),block:g=>{if(!a.setBlockers)return()=>{};const m=a.getBlockers?.()??[];return a.setBlockers([...m,g]),()=>{const y=a.getBlockers?.()??[];a.setBlockers?.(y.filter(d=>d!==g))}},flush:()=>a.flush?.(),destroy:()=>a.destroy?.(),notify:f}}function Sm(a,c){c||(c={});const s=Kf();return{...c,key:s,__TSR_key:s,[Gl]:a}}function Fg(a){const c=typeof document<"u"?window:void 0,s=c.history.pushState,f=c.history.replaceState;let r=[];const h=()=>r,g=L=>r=L,m=(L=>L),y=(()=>Fi(`${c.location.pathname}${c.location.search}${c.location.hash}`,c.history.state));if(!c.history.state?.__TSR_key&&!c.history.state?.key){const L=Kf();c.history.replaceState({[Gl]:0,key:L,__TSR_key:L},"")}let d=y(),S,p=!1,b=!1,T=!1,R=!1;const E=()=>d;let D;const w=()=>{D&&(G._ignoreSubscribers=!0,(D[2]?c.history.pushState:c.history.replaceState)(D[1],"",D[0]),G._ignoreSubscribers=!1,D=void 0,S=void 0)},Y=(L,Q,J)=>{const ct=m(Q),P=!!D;P||(S=d),d=Fi(Q,J),D=[ct,J,D?.[2]||L],P||queueMicrotask(()=>w())},K=L=>{d=y(),G.notify({type:L})},X=async()=>{if(b){b=!1;return}const L=y(),Q=L.state[Gl]-d.state[Gl],J=Q===1,ct=Q===-1,P=!J&&!ct||p;p=!1;const ft=P?"GO":ct?"BACK":"FORWARD",bt=P?{type:"GO",index:Q}:{type:ct?"BACK":"FORWARD"};if(T)T=!1;else{const ee=h();if(typeof document<"u"&&ee.length){for(const Bt of ee)if(await Bt.blockerFn({currentLocation:d,nextLocation:L,action:ft})){b=!0,c.history.go(1),G.notify(bt);return}}}d=y(),G.notify(bt)},et=L=>{if(R){R=!1;return}let Q=!1;const J=h();if(typeof document<"u"&&J.length)for(const ct of J){const P=ct.enableBeforeUnload??!0;if(P===!0){Q=!0;break}if(typeof P=="function"&&P()===!0){Q=!0;break}}if(Q)return L.preventDefault(),L.returnValue=""},G=Wg({getLocation:E,getLength:()=>c.history.length,pushState:(L,Q)=>Y(!0,L,Q),replaceState:(L,Q)=>Y(!1,L,Q),back:L=>(L&&(T=!0),R=!0,c.history.back()),forward:L=>{L&&(T=!0),R=!0,c.history.forward()},go:L=>{p=!0,c.history.go(L)},createHref:L=>m(L),flush:w,destroy:()=>{c.history.pushState=s,c.history.replaceState=f,c.removeEventListener(pm,et,{capture:!0}),c.removeEventListener(gm,X)},onBlocked:()=>{S&&d!==S&&(d=S)},getBlockers:h,setBlockers:g,notifyOnIndexChange:!1});return c.addEventListener(pm,et,{capture:!0}),c.addEventListener(gm,X),c.history.pushState=function(...L){const Q=s.apply(c.history,L);return G._ignoreSubscribers||K("PUSH"),Q},c.history.replaceState=function(...L){const Q=f.apply(c.history,L);return G._ignoreSubscribers||K("REPLACE"),Q},G}function $g(a){let c=a.replace(/[\x00-\x1f\x7f]/g,"");return c.startsWith("//")&&(c="/"+c.replace(/^\/+/,"")),c}function Fi(a,c){const s=$g(a),f=s.indexOf("#"),r=s.indexOf("?"),h=Kf();return{href:s,pathname:s.substring(0,f>0?r>0?Math.min(f,r):f:r>0?r:s.length),hash:f>-1?s.substring(f):"",search:r>-1?s.slice(r,f===-1?void 0:f):"",state:c||{[Gl]:0,key:h,__TSR_key:h}}}function Kf(){return(Math.random()+1).toString(36).substring(7)}function bm(a){return a.options.loader||a.options.beforeLoad||a.lazyFn||a.options.component?.preload||a.options.pendingComponent?.preload}function lc(a,c){return{fromLocation:c,toLocation:a,pathChanged:c?.pathname!==a.pathname,hrefChanged:c?.href!==a.href,hashChanged:c?.hash!==a.hash}}function _m({key:a,__TSR_key:c,__TSR_index:s,__hashScrollIntoViewOptions:f,...r}){return r}function Pg(a,c,s,f){for(const r of c){if(f?.()===!1)return;s.some(h=>h.routeId===r.routeId)||a.routesById[r.routeId].options.onLeave?.(r)}for(const r of s){if(f?.()===!1)return;a.routesById[r.routeId].options[c.some(h=>h.routeId===r.routeId)?"onStay":"onEnter"]?.(r)}}var Ig=class{constructor(a,c){this.tempLocationKey=`${Math.round(Math.random()*1e7)}`,this._scroll={next:!0},this.subscribers=new Set,this._cache=new Map,this._committed=[],this.routeBranchCache=new WeakMap,this.lightweightCache=new WeakMap,this.startTransition=async s=>(s(),!1),this.update=s=>{const f=this.options,r=this.basepath??f?.basepath??"/",h=this.basepath===void 0,g=f?.rewrite;if(this.options={...f,...s},this.isServer=this.options.isServer??ug??typeof document>"u",this.protocolAllowlist=new Set(this.options.protocolAllowlist),this.options.pathParamsAllowedCharacters&&(this.pathParamsDecoder=xg(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.options.history?this.history=this.options.history:this.history=Fg()),this.origin=this.options.origin,this.origin||(window?.origin&&window.origin!=="null"?this.origin=window.origin:this.origin="http://localhost"),this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree){this.routeTree=this.options.routeTree;let d;this.resolvePathCache=ki(1e3),d=this.buildRouteTree(),this.setRoutes(d)}if(!this.stores&&this.latestLocation){const d=this.getStoreConfig(this);this.batch=d.batch,this.stores=kg(this.latestLocation,d),jg(this)}const m=this.options.basepath??"/",y=this.options.rewrite;if(h||r!==m||g!==y){this.basepath=m;const d=[],S=Wm(m);S&&S!=="/"&&d.push(Jg({basepath:m})),y&&d.push(y),this.rewrite=d.length===0?void 0:d.length===1?d[0]:Kg(d),this.history&&this.updateLatestLocation(),this.stores&&this.stores.location.set(this.latestLocation)}},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{const s=zg(this.routeTree,this.options.caseSensitive,(f,r)=>{f.init({originalIndex:r})});return this.options.routeMasks&&Sg(this.options.routeMasks,s.processedTree),s},this.subscribe=(s,f)=>{const r={eventType:s,fn:f};return this.subscribers.add(r),()=>{this.subscribers.delete(r)}},this.emit=s=>{for(const f of this.subscribers)if(f.eventType===s.type)try{f.fn(s)}catch(r){console.error(r)}},this.parseLocation=(s,f)=>{const r=({pathname:y,search:d,hash:S,href:p,state:b})=>{if(!this.rewrite&&!/[ \x00-\x1f\x7f\u0080-\uffff]/.test(y)){const w=this.options.parseSearch(d),Y=this.options.stringifySearch(w);return{href:y+Y+S,publicHref:y+Y+S,pathname:ru(y).path,external:!1,searchStr:Y,search:dn(f?.search,w),hash:ru(S.slice(1)).path,state:mn(f?.state,b)}}const T=new URL(p,this.origin),R=Bf(this.rewrite,T),E=this.options.parseSearch(R.search),D=this.options.stringifySearch(E);return R.search=D,{href:R.href.replace(R.origin,""),publicHref:p,pathname:ru(R.pathname).path,external:!!this.rewrite&&R.origin!==this.origin,searchStr:D,search:dn(f?.search,E),hash:ru(R.hash.slice(1)).path,state:mn(f?.state,b)}},h=r(s),{__tempLocation:g,__tempKey:m}=h.state;if(g&&(!m||m===this.tempLocationKey)){const y=r(g);return y.state.key=h.state.key,y.state.__TSR_key=h.state.__TSR_key,delete y.state.__tempLocation,{...y,maskedLocation:h}}return h},this.resolvePathWithBase=(s,f)=>Cg({base:s,to:f.includes("//")?Vf(f):f,trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(s,f,r)=>typeof s=="string"?this.matchRoutesInternal({pathname:s,search:f},r):this.matchRoutesInternal(s,f),this.getMatchedRoutes=s=>{const f=Object.create(null),r=Eg(ol(s),this.processedTree,!0);return r&&Object.assign(f,r.rawParams),[r?.branch||[this.routesById.__root__],f,r?.route]},this.buildLocation=s=>{const f=(h={})=>{const g=h._fromLocation||this._pendingLocation||this.latestLocation,m=this.matchRoutesLightweight(g);h.from;const y=h.unsafeRelative==="path"?g.pathname:h.from??m[1],d=h.to?`${h.to}`:void 0,S=m[2],p=Object.assign(Object.create(null),m[3]),b=d?.charCodeAt(0)===47?"/":this.resolvePathWithBase(y,"."),T=d?this.resolvePathWithBase(b,d):b,R=Em(h.params,p),E=this.routesByPath[ol(T)];let D;if(E)D=this.getRouteBranch(E);else if(T.includes("$"))D=[];else{const[P,ft,bt]=this.getMatchedRoutes(T);D=P,this.options.notFoundRoute&&(!bt||bt.path!=="/"&&ft["**"])&&(D=[...D,this.options.notFoundRoute])}if(D.length&&Xm(R))for(const P of D){const ft=P.options.params?.stringify??P.options.stringifyParams;if(ft)try{Object.assign(R,ft(R))}catch{}}const w=s.leaveParams?T:ru(hm({path:T,params:R,decoder:this.pathParamsDecoder,server:this.isServer}).interpolatedPath).path;let Y=S;if(s._includeValidateSearch&&this.options.search?.strict){const P={};D.forEach(ft=>{if(ft.options.validateSearch)try{Object.assign(P,Qi(ft.options.validateSearch,{...P,...Y}))}catch{}}),Y=P}Y=ep(Y,h,D,s._includeValidateSearch),Y=dn(S,Y);const K=this.options.stringifySearch(Y),X=h.hash===!0?g.hash:h.hash?ra(h.hash,g.hash):void 0,et=X?`#${X}`:"";let G=h.state===!0?g.state:h.state?ra(h.state,g.state):{};G=mn(g.state,G);const L=`${w}${K}${et}`;let Q,J,ct=!1;if(this.rewrite){const P=new URL(L,this.origin),ft=$m(this.rewrite,P);Q=P.href.replace(P.origin,""),ft.origin!==this.origin?(J=ft.href,ct=!0):J=ft.pathname+ft.search+ft.hash}else Q=yg(L),J=Q;return{publicHref:J,href:Q,pathname:w,search:Y,searchStr:K,state:G,hash:X??"",external:ct,unmaskOnReload:h.unmaskOnReload}},r=(h={},g)=>{const m=f(h);let y=g?f(g):void 0;if(!y){const d=Object.create(null);if(this.options.routeMasks){const S=bg(m.pathname,this.processedTree);if(S){Object.assign(d,S.rawParams);const{from:p,params:b,...T}=S.route,R=Em(b,d);g={from:s.from,...T,params:R},y=f(g)}}}return y&&(m.maskedLocation=y),m};return s.mask?r(s,{from:s.from,...s.mask}):r(s)},this.commitLocation=async({viewTransition:s,ignoreBlocker:f,...r})=>{let h;const g=ol(this.latestLocation.href)===ol(r.href)&&Yl(_m(r.state),_m(this.latestLocation.state)),m=this._commitPromise;let y;const d=new Promise(S=>{y=S});if(d.resolve=()=>{y(),m?.resolve()},this._commitPromise=d,g)this.load();else{let{maskedLocation:S,hashScrollIntoView:p,...b}=r;S&&(b={...S,state:{...S.state,__tempKey:void 0,__tempLocation:{...b,search:b.searchStr,state:{...b.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(b.unmaskOnReload??this.options.unmaskOnReload??!1)&&(b.state.__tempKey=this.tempLocationKey)),b.state.__hashScrollIntoViewOptions=p??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=s,h=r.replace?"REPLACE":"PUSH",this.history[h==="REPLACE"?"replace":"push"](b.publicHref,b.state,{ignoreBlocker:f}),this.history.subscribers.size||this.load({action:{type:h}})}return this._scroll.next=r.resetScroll??!0,this._commitPromise},this.buildAndCommitLocation=({replace:s,resetScroll:f,hashScrollIntoView:r,viewTransition:h,ignoreBlocker:g,_redirects:m,href:y,...d}={})=>{if(y){const b=this.history.location.state.__TSR_index,T=Fi(y,{__TSR_index:s?b:b+1}),R=new URL(T.pathname,this.origin);d.to=Bf(this.rewrite,R).pathname,d.search=this.options.parseSearch(T.search),d.hash=T.hash.slice(1)}const S=this.buildLocation({...d,_includeValidateSearch:!0});m&&(S._redirects=m),this._pendingLocation=S;const p=this.commitLocation({...S,viewTransition:h,replace:s,resetScroll:f,hashScrollIntoView:r,ignoreBlocker:g});return queueMicrotask(()=>{this._pendingLocation===S&&(this._pendingLocation=void 0)}),p},this.navigate=async({to:s,reloadDocument:f,href:r,publicHref:h,...g})=>{let m=!1;if(r)try{new URL(`${r}`),m=!0}catch{}if(m&&!f&&(f=!0),f){if(s!==void 0||!r){const d=this.buildLocation({to:s,...g});r=r??d.publicHref,h=h??d.publicHref}const y=!m&&h?h:r;if(Ji(y,this.protocolAllowlist))return;if(!g.ignoreBlocker){const d=this.history.getBlockers?.()??[];for(const S of d)if(S?.blockerFn&&await S.blockerFn({currentLocation:this.latestLocation,nextLocation:this.latestLocation,action:"PUSH"}))return}g.replace?window.location.replace(y):window.location.href=y;return}return this.buildAndCommitLocation({...g,href:r,to:s,_isNavigate:!0})},this.load=async s=>{this.updateLatestLocation(),s?.action&&(this._scroll.hash=s.action.type==="PUSH"||s.action.type==="REPLACE"),await op(this,s)},this.startViewTransition=s=>{const f=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,f&&typeof document.startViewTransition=="function"){let r;if(typeof f=="object"&&window.CSS?.supports?.("selector(:active-view-transition-type(a))")){const h=this.latestLocation,g=this.stores.resolvedLocation.get(),m=typeof f.types=="function"?f.types(lc(h,g)):f.types;if(m===!1)return s();r={update:s,types:m}}else r=s;return document.startViewTransition(r).updateCallbackDone}return s()},this.invalidate=s=>{const f=this._committed,r=s?.filter,h=this._preloads,g=new Set([...f,...this._cache.values(),...[...h?.values()??[]].flat(),...this._tx?.[3]??[]].filter(d=>!r||r(d)).map(d=>d.id)),m=[];for(const[d,S]of h??[])S.some(p=>g.has(p.id))&&(h.delete(d),m.push(d));const y=d=>{if(g.has(d.id)){const S=this.routesById[d.routeId],p={...d,invalid:!0,...(s?.forcePending||d.status==="error"||d.status==="notFound")&&bm(S)?{status:"pending",error:void 0}:void 0};return d._flight=void 0,p}return d};this._committed=f.map(y);for(const[d,S]of this._cache)g.has(d)&&(S.invalid=!0,s?.forcePending&&(S.status="pending"));for(const d of g)this._flights?.delete(d);for(const d of m)d.abort();return this.shouldViewTransition=!1,this.load({sync:s?.sync})},this.resolveRedirect=s=>{const f=s.headers.get("Location");if(!s.options.href||s.options._builtLocation){const r=(s.options._builtLocation??this.buildLocation(s.options)).publicHref||"/";s.options.href=r,s.headers.set("Location",r)}else if(f)try{const r=new URL(f);if(this.origin&&r.origin===this.origin){const h=r.pathname+r.search+r.hash;s.options.href=h,s.headers.set("Location",h)}}catch{}if(s.options.href&&!s.options._builtLocation&&Ji(s.options.href,this.protocolAllowlist))throw new Error("Redirect blocked: unsafe protocol");return s.headers.get("Location")||s.headers.set("Location",s.options.href),s},this.clearCache=s=>{const f=this._cache,r=this._preloads,h=s?.filter,g=[],m=[];for(const[d,S]of f)(!h||h(S))&&(m.push(d),g.push(S));const y=[];for(const[d,S]of r??[])(!h||S.some(h))&&(y.push(d),g.push(...S));for(const d of m)f.delete(d);for(const d of y)r.delete(d);for(const d of g){const S=d._flight;d._flight=void 0,S&&!--S[2]&&(this._flights?.get(d.id)===S&&this._flights.delete(d.id),y.push(S[1]))}for(const d of y)d.abort()},this.loadRouteChunk=fa,this.preloadRoute=s=>s0(this,s),this.matchRoute=(s,f)=>{const r={...s,to:s.to?this.resolvePathWithBase(s.from||"",s.to):void 0,params:s.params||{},leaveParams:!0},h=this.buildLocation(r),g=this.stores.status.get()==="pending";if(f?.pending&&!g)return!1;const m=f?.pending??!g?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),y=_g(h.pathname,f?.caseSensitive??!1,f?.fuzzy??!1,m.pathname,this.processedTree);return!y||s.params&&!Yl(y.rawParams,s.params,{partial:!0})?!1:f?.includeSearch??!0?Yl(m.search,h.search,{partial:!0})?y.rawParams:!1:y.rawParams},this.getStoreConfig=c,this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...a,caseSensitive:a.caseSensitive??!1,notFoundMode:a.notFoundMode??"fuzzy",stringifySearch:a.stringifySearch??Xg,parseSearch:a.parseSearch??Gg,protocolAllowlist:a.protocolAllowlist??mg}),self.__TSR_ROUTER__=this}isShell(){return!!this.options.isShell}get state(){return this.stores.__store.get()}setRoutes({routesById:a,routesByPath:c,processedTree:s}){this.routesById=a,this.routesByPath=c,this.processedTree=s;const f=this.options.notFoundRoute;f&&(f.init({originalIndex:99999999999}),this.routesById[f.id]=f)}getRouteBranch(a){let c=this.routeBranchCache.get(a);return c||(c=Jm(a),this.routeBranchCache.set(a,c)),c}matchRoutesInternal(a,c){const[s,f,r]=this.getMatchedRoutes(a.pathname);let h=s,g=!1;(r?r.path!=="/"&&f["**"]:ol(a.pathname))&&(this.options.notFoundRoute?h=[...h,this.options.notFoundRoute]:g=!0);const m=g?lp(this.options.notFoundMode,h):void 0,y=new Array(h.length),d=this._committed,S=(b,T)=>{const R=d[T];return R?.routeId===b.id?R:b===this.options.notFoundRoute?d.find(E=>E.routeId===b.id):void 0};let p;for(let b=0;b{const b=p(m.preSearchFilters?m.preSearchFilters.reduce((T,R)=>R(T),S):S);return m.postSearchFilters?m.postSearchFilters.reduce((T,R)=>R(T),b):b};r.push(d)}const y=m.validateSearch;if(y){const d=({search:S,next:p,meta:b})=>{const T=p(S);if(f)try{const R=Qi(y,T);if(b&&R)for(const E in R)E in T||(b.defaulted||=new Map).set(E,R[E]);return{...T,...R}}catch{}return T};r.push(d)}}const h=(g,m,y)=>{if(g>=r.length){if(!c.search)return{};if(c.search===!0)return m;const S=ra(c.search,m);return y&&(y.explicit=S),S}const d=(S,p)=>{if(p){const b=y||{};return{search:h(g+1,S,b),meta:b}}return h(g+1,S,y)};return r[g]({search:m,next:d,meta:y})};return h(0,a)}function lp(a,c){if(a!=="root"){let s;for(let f=c.length-1;f>=0;f--){const r=c[f];if(r.options.notFoundComponent)return r.id;s||=r.children&&r.id}if(s)return s}return sa}function Em(a,c){return a===!1||a===null?Object.create(null):(a??!0)===!0?c:Object.assign(c,ra(a,c))}function Tm(a,c){const s=a.options.params?.parse??a.options.parseParams;s&&Object.assign(c,s(c))}function Hf(a,c){return a.options[c]?.preload?.()}function np(a,c){const s=Hf(a,"component"),f=Hf(a,"pendingComponent"),r=c&&f?f.then(c):f;return c&&!f&&c(),s&&r?Promise.all([s,r]).then(()=>{}):s??r}function fa(a,c,s){const f=()=>c===!1?void 0:c?Hf(a,c):np(a,s),r=a._lazy;if(r)return r===!0?f():r.then(f);if(!a.lazyFn)return f();const h=a.lazyFn().then(g=>{{const{id:m,...y}=g.options;Object.assign(a.options,y),a._lazy=!0}},g=>{throw a._lazy=void 0,g});return a._lazy=h,h.then(f)}function Pm(a){const c=a.findIndex(s=>s.status!=="success"||s._notFound)+1;return c&&c{const r=()=>f(c);c.addEventListener("abort",r,{once:!0}),Promise.resolve(a).then(s,f).finally(()=>c.removeEventListener("abort",r))})}function gn(a,c){return a.routesById[c.routeId]}function vu(a,c,s){return Zf(a)?[xe,a]:yn(a)?(a.routeId||=s,[nc,a]):(c&&typeof a?.then=="function"&&(a=new Error("A Promise was thrown",{cause:a})),c?[Xl,a]:[Xe,a])}function Im(a,c){let s=vu(c,!0,a.id);if(s[0]!==Xl)return s;try{a.options.onError?.(s[1])}catch(f){s=vu(f,!0,a.id)}return s}function du(a,c,s){return s[0].signal.aborted||!s[2]()?(s[0].abort(),[vn]):Im(a,c)}function t0(a,c){return s=>a.navigate({...s,_fromLocation:c})}async function ap(a,c,s,f,r,h){const[g,m]=c,y=s[0].signal,d=!!s[4];for(let S=s[7]??0;S=h&&(p.status="pending"),s[8]?.();try{gu(a,p,"beforeLoad",s[0]);const X=await Ql(w(Y),y);if(!s[2]())return s[0].abort(),[S,[vn]];const et=vu(X,!1,b.id);if(et[0]!==Xe)return rl(a,p),[S,et];p.context={...E,...X}}catch(X){return rl(a,p),[S,du(b,X,s)]}finally{K==="success"&&p.status==="pending"&&(p.status="success"),gu(a,p,!1,s[0])}}r()}function Jf(a,c,s){if(!(!s||--s[2])){if(a._flights?.get(c.id)===s){const f=a._tx;if(f&&!f[0].signal.aborted&&!f[3].includes(c)&&f[3].some(r=>r.id===c.id)&&f[3].some(r=>r.isFetching==="beforeLoad"))return;a._flights.delete(c.id)}return s[1]}}function rl(a,c){const s=c._flight;c._flight=void 0,Jf(a,c,s)?.abort()}function oe(a,c,s,f){const r=[];for(const h of c)if(!s?.includes(h)){const g=h._flight;if(h._flight=void 0,f&&g?.[2]===1&&a._flights?.get(h.id)===g&&s?.some(m=>m.id===h.id))g[2]=0;else{const m=Jf(a,h,g);m&&r.push(m)}}for(const h of r)h.abort()}function kf(a){for(const c of a){const s=c._flight;s&&s[2]++}}function gu(a,c,s,f){if(c.isFetching=s,f&&a._tx?.[0]!==f)return;const r=a.stores.byRoute.get(c.routeId),h=r?.get();h?.id===c.id&&r.set({...h,isFetching:s})}function e0(a,c,s,f,r,h,g){const m=c[0];return{params:s.params,location:m,navigate:t0(a,m),cause:g?"preload":s.cause,abortController:r,preload:g,deps:s.loaderDeps,parentMatchPromise:h,context:s.context,route:f,...a.options.additionalContext}}async function zm(a,c,s,f,r,h,g,m){const y=m.signal;if(y.aborted)return[vn];if(!r)return[Xe,void 0];let d=s._flight;gu(a,s,"loader",m);try{if(!d){const S=new AbortController;d=[Promise.resolve().then(()=>r(e0(a,c,s,f,S,h,g))).then(p=>vu(p,!1,f.id),p=>vu(p,!0,f.id)).then(p=>(p[0]!==Xe&&a._flights?.get(s.id)===d&&(a._flights.delete(s.id),d[2]||S.abort()),p[0]===Xl&&d[2]?Im(f,p[1]):p)),S,1],(a._flights??=new Map).set(s.id,d)}return s._flight=d,s.abortController=d[1],await Ql(d[0],y)}catch(S){if(S!==y)throw S;return rl(a,s),[vn]}finally{gu(a,s,!1,m)}}function Am(a,c,s){c[0]===Xe?(a.loaderData=c[1],a.error=void 0,a.status="success",a.invalid=!1,a.updatedAt=Date.now(),a.preload=s):c[0]!==xe&&(a.status="success",a.error=void 0,a.invalid=!0)}function up(a,c,s){const f=a._cache.get(c.id);if(f!==s||a._committed.some(h=>h.id===c.id&&h._flight===c._flight))return;const r={...c,_notFound:void 0,context:{}};r._flight&&r._flight[2]++,a._cache.set(c.id,r),f&&rl(a,f)}function Rm(a,c){return c[0]===Xl||c[0]===nc?{...a,status:c[0]===Xl?"error":"notFound",error:c[1],_flight:void 0}:a}function ip(a,c,s,f,r,h,g){const m=c[1][s],y=gn(a,m),d=!!h[4],S=a._cache.get(m.id);let p,b=!1,T;try{if(m.status==="success"&&(p=y.options.shouldReload,typeof p=="function"&&(p=p(e0(a,c,m,y,h[0],r,d))),h[2]()||(h[0].abort(),T=[vn])),!T)if(m.status!=="success")b=!0;else{const J=h[4]||m.preload?y.options.preloadStaleTime??a.options.defaultPreloadStaleTime??3e4:y.options.staleTime??a.options.defaultStaleTime??0;b=!!(m.invalid||p||p===void 0&&Date.now()-m.updatedAt>=J&&(h[6]||m.cause==="enter"||h[3].some(ct=>ct.routeId===m.routeId&&ct.id!==m.id)))}}catch(J){m.invalid=!0,rl(a,m),T=du(y,J,h)}const R=y.options.loader,E=typeof R=="function"?R:R?.handler;let D=(!d||y.options.preload!==!1)&&R?a._flights?.get(m.id):void 0;D===m._flight||T?D=void 0:D&&!b&&!d&&p===void 0?b=!0:b||(D=void 0);const w=!!(R&&b&&m.status==="success"&&!d&&!h[5]&&((typeof R=="function"?void 0:R?.staleReloadMode)??a.options.defaultStaleReloadMode)!=="blocking"),Y=b&&(!d||y.options.preload!==!1),K=Y&&!w&&(m.status!=="success"||!!R),X=y.lazyFn&&y._lazy!==!0?h[8]:void 0;if(Y&&!R&&(m.invalid=!1,m.updatedAt=Date.now()),D&&D[2]++,K){const J=m._flight;m._flight=D,Jf(a,m,J)?.abort(),m.status==="success"&&s>=g&&(m.status="pending"),h[8]?.()}Y||(m.isFetching=!1);const et=(T?Promise.resolve(T):K?zm(a,c,m,y,E,r,d,h[0]):Promise.resolve([Xe,m.loaderData])).then(J=>(K&&(Am(m,J,d),J[0]===Xe&&(R&&!h[0].signal.aborted&&up(a,m,S),m.status="pending")),J)),G=Ql(Promise.resolve().then(()=>fa(y,void 0,X)),h[0].signal).then(()=>{},J=>[s,du(y,J,h)]).then(J=>et.then(ct=>(K&&!J&&ct[0]===Xe&&m.status==="pending"&&h[2]()&&(m.status="success",h[8]?.()),J)));if(f.push([s,et,G]),!w)return et.then(J=>Rm(m,J));const L={...m,status:"pending",preload:!1,_flight:D};m.invalid=!1,m.isFetching="loader";const Q=zm(a,c,L,y,E,r,!1,h[0]).then(J=>(m.isFetching=!1,Am(L,J,!1),J));return(c[2]??=[]).push([s,Q,G,L]),Q.then(J=>Rm(L,J))}async function jf(a,c,s,f,r=0){const h=s?.[1][1];let g=h?.routeId?c.findIndex(m=>m.routeId===h.routeId):s?.[0]??c.length-1;g<0&&(g=0);for(let m=g;m>=0;m--){const y=gn(a,c[m]),d=fa(y,!1);if(d)try{await Ql(d,f)}catch(S){if(S===f)throw S}if(y.options.notFoundComponent)return m}return h?.routeId?g:r}function oa(a,c){c[2]&&(oe(a,c[2].map(s=>s[3])),c[2]=void 0)}async function Om(a,c,s,f){let r;try{await Promise.all(a.map(h=>h[1].then(async g=>{const m=h[0];if(!(f&&m>=await f)){if(g[0]>=xe)throw[m,g];!r&&g[0]!==Xe&&(r=[m,g],await Promise.all((s??[]).map(y=>{if(!(y[0]<=m))return y[1].then(d=>{if(d[0]===xe)throw[y[0],d]})})))}})))}catch(h){return h}return c??r}async function l0(a,c,s,f,r,h,g){const m=c[1];let y=await h,d=!1;const S=m.findIndex(R=>R._notFound),p=R=>R[1][0]===nc?jf(a,m,R,f.signal):R[0];let b=S<0?m.length:S;if((y?.[1][0]??0)>=xe)b=0;else if(y){b=y[2]??=await p(y);for(const R of s){if(R[0]>=b)break;const E=await R[1];if(E[0]!==Xe&&E[0]=b)break;const E=await R[2];if(E){y=E;break}}if((y?.[1][0]??0)>=xe){const R=y[1];if(R[0]!==xe||R[1].options.reloadDocument||r<20)return oa(a,c),R;d=!0,y=[0,[Xl,new Error("Too many redirects")]]}const T=y?y[2]??await p(y):S;if(T>=0){const R=y?.[1],E=R?.[0],D=m[T],w=R?.[1],Y=()=>{R&&(D._notFound=void 0,E===Xl?D.status="error":(w.routeId=D.routeId,D.routeId===a.routeTree.id?(D.status="success",D._notFound=!0):D.status="notFound"),D.error=w,D.isFetching=!1)};Y();const K=gn(a,D);try{await Ql(R?Promise.resolve().then(()=>fa(K,E===Xl?"errorComponent":"notFoundComponent")):Promise.all([fa(K),fa(K,"notFoundComponent")]),f.signal)}catch(X){if(X===f.signal)return oa(a,c),[vn]}R?d&&(f.abort(),await Promise.all([...s.map(X=>X[1]),...s.map(X=>X[2]),...(c[2]??[]).map(X=>X[1])]),oa(a,c),oe(a,m),Y()):(D.status="success",g?.())}return c}async function n0(a,c,s,f=0,r=c[1].length){const h=c[1];for(let g=f;gE._notFound);if(a.options.notFoundMode!=="root"&&g>=0){const E=await jf(a,r[1],void 0,f[0].signal,g);E!==g&&(s[g]._notFound=void 0,s[E]._notFound=!0),g=E}let m=g<0?s.length:g+1,y=0;for(;y{for(let E=S;E=xe&&(m=0),b()),f[2]()&&!f[4]){const E=[];for(const[D,w]of a._flights??[])w[2]||(a._flights.delete(D),E.push(w[1]));for(const D of E)D.abort()}let R;try{const E=l0(a,r,d,f[0],f[1],Om(d,T,r[2]),f[8]);r[2]?.length&&(r[3]=Om(r[2],void 0,void 0,E.then(D=>yu(D)?0:Pm(D[1]).length,()=>0))),R=await E}catch(E){throw oa(a,r),E}return yu(R)?R:n0(a,R,f[0].signal,f[7]===R[1].length?f[7]:0)}function qf(a,c){if(a._tx!==c)return;let s=a._pending,f=!1;const r=s?.[0][3][s[1]]?.id;s?.[0]!==c&&(s&&c[3][s[1]]?.id===r?(s[0]=c,f=!0):(clearTimeout(s?.[3]),a._pending=s=void 0));const h=c[3],g=a.stores.matches.get();let m=-1,y,d,S,p=!1;for(let E=0;E0){s[3]=setTimeout(()=>qf(a,c),E);return}s[2]=0}const T=h.map(E=>({...E,_flight:void 0}));T[m].status="pending";const R=a.startTransition(()=>a.stores.setMatches(T),T).then(E=>(E&&a._pending===s&&s[4]===R&&!s[2]&&(s[2]=Date.now()+d),E));s[4]=R}function Vi(a,c){const s=a._pending;s?.[0]===c&&(clearTimeout(s[3]),a._pending=void 0)}function u0(a,c){a._committed=c,a.stores.setMatches(c)}function Mm(a,c){oe(a,c[1]),oa(a,c)}function cp(a,c,s,f){const r=a._committed,h=a._cache;for(const d of s)d.preload=!1,f&&(d._assetEnd=void 0);const g=Pm(s).length,m=new Map,y=Date.now();for(const d of[...r,...h.values()]){if(d.status!=="success"||s.some((p,b)=>p.id===d.id&&(b=(d.preload?S.options.preloadGcTime??a.options.defaultPreloadGcTime??3e5:S.options.gcTime??a.options.defaultGcTime??3e5)||m.set(d.id,h.get(d.id)===d?d:{...d,_flight:void 0,isFetching:!1,context:{}})}c[3]=[],a._cache=m,u0(a,s),oe(a,[...h.values(),...r],[...s,...m.values()]),Pg(a,r,s,()=>a._tx===c)}async function hn(a,c){let s=a._tx;for(;s&&s!==c;){if(await s[5],a._tx===s)return;s=a._tx}}async function i0(a,c,s){await a.navigate({...s.options,replace:!0,ignoreBlocker:!0,_redirects:c[1]+1})}function c0(a,c){Vi(a,c),c[0].abort(),oe(a,c[3]),c[3]=[],a._tx===c&&(a.batch(()=>{a.stores.status.set("idle"),a.stores.setMatches(a._committed)}),a._tx===c&&(a._commitPromise?.resolve(),a._commitPromise=void 0))}async function sp(a,c,s,f,r){const h=s.map(d=>({...d}));kf(h);for(const d of f)rl(a,h[d[0]]),h[d[0]]=d[3];const g=[c[2],h];let m;try{m=await l0(a,g,f,c[0],c[1],r)}catch(d){throw oe(a,h),d}if(yu(m)){oe(a,h),m[0]===xe&&a._tx===c&&a._committed===s&&await i0(a,c,m[1]);return}const y=await n0(a,m,c[0].signal);if(a._tx!==c||a._committed!==s){oe(a,y[1]);return}for(const d of y[1]){const S=a._cache.get(d.id);S?._flight&&S._flight===d._flight&&(a._cache.delete(d.id),rl(a,S))}u0(a,y[1]),oe(a,s,y[1])}async function fp(a,c,s,f,r,h){const g=[c[0],c[1],()=>a._tx===c&&!!c[3].length,a._committed,void 0,r,s,h,f],m=await a0(a,c[2],c[3],g);if(yu(m)){m[0]===xe&&a._tx===c?(Vi(a,c),oe(a,c[3]),c[3]=[],a._tx===c&&await i0(a,c,m[1])):c0(a,c);return}const y=a._pending;if(y?.[0]===c&&(clearTimeout(y[3]),y[4])){const b=c[0].signal;let T=!1;try{T=await Ql(y[4],b)}catch(R){if(R!==b)throw R}if(T&&a._pending===y&&y[0]===c){const R=y[2]-Date.now();if(R>0){try{await Ql(new Promise(E=>{y[3]=setTimeout(E,R)}),b)}catch{}clearTimeout(y[3])}}}if(a._tx!==c){Vi(a,c),Mm(a,m);return}const d=c[2],S=lc(d,a.stores.resolvedLocation.get()),p=m[2];await a.startViewTransition(async()=>{if(a._tx!==c){Mm(a,m);return}const b=()=>{Vi(a,c),cp(a,c,m[1],h),a._tx===c&&(a.emit({type:"onLoad",...S}),a._tx===c&&a.emit({type:"onBeforeRouteMount",...S}))},T=await a.startTransition(b,m[1]);if(a._tx!==c){oa(a,m);return}p?.length&&sp(a,c,m[1],p,m[3]).catch(console.error),a.batch(()=>{a.stores.resolvedLocation.set(d),a.stores.status.set("idle"),a._tx===c&&a.emit({type:"onResolved",...S}),T&&a._tx===c&&a.emit({type:"onRendered",...S})}),a._tx===c&&(a._commitPromise?.resolve(),a._commitPromise=void 0)})}async function op(a,c){const s=a._tx,f=a.stores.resolvedLocation.get(),r=f??a.stores.location.get(),h=a.latestLocation,g=a._pendingLocation,m=g?.href===h.href?g._redirects??0:0,y=a._handoff,d=y?.[0](),S=new AbortController,p=a._preflight;if(a._preflight=S,d||y?.[1](),p?.abort(),S.signal.aborted){await hn(a,s);return}const b=lc(h,f);if(a.emit({type:"onBeforeNavigate",...b}),S.signal.aborted||a.emit({type:"onBeforeLoad",...b}),S.signal.aborted){await hn(a,s);return}const T=r.href===h.href;let R,E=S;try{R=a.matchRoutes(h,{_controller:S}),kf(R)}catch(Y){if(S.abort(),!Zf(Y)){await hn(a),a._commitPromise?.resolve(),a._commitPromise=void 0;return}await a.navigate({...Y.options,replace:!0,ignoreBlocker:!0}),await hn(a,s);return}const D=d?y[1](R):void 0;if(D?E=d:d?.abort(),S.signal.aborted){oe(a,R),await hn(a,s);return}a._preflight=void 0;const w=[E,m,h,R,Date.now(),Promise.resolve().then(()=>fp(a,w,T,()=>qf(a,w),c?.sync,D)).catch(()=>{a._tx===w&&c0(a,w)})];if(a._tx=w,s){for(const Y of a.stores.matches.get()){if(a._tx!==w)break;Y.isFetching&&gu(a,Y,!1)}s[0].abort(),oe(a,s[3],w[3],!0)}if(a._tx!==w){oe(a,w[3]),w[3]=[],await hn(a,w);return}a.batch(()=>{a.stores.status.set("pending"),a.stores.location.set(h)}),!f&&!R.some(Y=>Y._notFound)&&qf(a,w);try{await w[5]}finally{await hn(a,w)}}async function s0(a,c,s=0){if(s>20)return;const f=c._builtLocation??a.buildLocation(c),r=a._committed,h=new AbortController;let g;try{g=a.matchRoutes(f,{_controller:h}),kf(g)}catch(y){h.abort(),yn(y)||console.error(y);return}(a._preloads??=new Map).set(h,g);let m;try{let y;try{y=await a0(a,f,g,[h,s,()=>!0,r,!0])}finally{m=a._preloads.delete(h),oe(a,g),h.abort()}if(!yu(y))return y[1];if(m&&y[0]===xe&&!y[1].options.reloadDocument)return s0(a,{...y[1].options,_fromLocation:f},s+1)}catch(y){yn(y)||console.error(y)}}const rp="Error preloading route! ☝️";var f0=class{get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}constructor(a){if(this.init=c=>{this.originalIndex=c.originalIndex;const s=this.options,f=!s?.path&&!s?.id;this.parentRoute=this.options.getParentRoute?.(),f?this._path=sa:this.parentRoute||Xf();let r=f?sa:s?.path;r&&r!=="/"&&(r=km(r));const h=s?.id||r;let g=f?sa:Gi([this.parentRoute.id==="__root__"?"":this.parentRoute.id,h]);r==="__root__"&&(r="/"),g!=="__root__"&&(g=Gi(["/",g]));const m=g==="__root__"?"/":Gi([this.parentRoute.fullPath,r]);this._path=r,this._id=g,this._fullPath=m,this._to=ol(m)},this.addChildren=c=>this._addFileChildren(c),this._addFileChildren=c=>(Array.isArray(c)&&(this.children=c),typeof c=="object"&&c!==null&&(this.children=Object.values(c)),this),this._addFileTypes=()=>this,this.updateLoader=c=>(Object.assign(this.options,c),this),this.update=c=>(Object.assign(this.options,c),this),this.lazy=c=>(this.lazyFn=c,this),this.redirect=c=>Zg({from:this.fullPath,...c}),this.options=a||{},this.isRoot=!a?.getParentRoute,a?.id&&a?.path)throw new Error("Route cannot have both an 'id' and a 'path' option.")}},dp=class extends f0{constructor(a){super(a)}};function Wf(a){return k.jsx(hp,{...a})}var hp=class extends at.Component{constructor(...a){super(...a),this.state={error:null},this.reset=()=>{this.setState({error:null})}}static getDerivedStateFromProps(a,c){const s=a.getResetKey();return c.error&&c.resetKey!==s?{resetKey:s,error:null}:{resetKey:s}}static getDerivedStateFromError(a){return{error:a}}componentDidCatch(a,c){this.props.onCatch?.(a,c)}render(){const a=this.state.error;return a?at.createElement(this.props.errorComponent??mp,{error:a,reset:this.reset}):this.props.children}};function mp({error:a}){const[c,s]=at.useState(!1);return k.jsxs("div",{style:{padding:".5rem",maxWidth:"100%"},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:".5rem"},children:[k.jsx("strong",{style:{fontSize:"1rem"},children:"Something went wrong!"}),k.jsx("button",{style:{appearance:"none",fontSize:".6em",border:"1px solid currentColor",padding:".1rem .2rem",fontWeight:"bold",borderRadius:".25rem"},onClick:()=>s(f=>!f),children:c?"Hide Error":"Show Error"})]}),k.jsx("div",{style:{height:".25rem"}}),c?k.jsx("div",{children:k.jsx("pre",{style:{fontSize:".7em",border:"1px solid red",borderRadius:".25rem",padding:".3rem",color:"red",overflow:"auto"},children:a.message?k.jsx("code",{children:a.message}):null})}):null]})}function yp({children:a,fallback:c=null}){return k.jsx(tc.Fragment,{children:o0()?a:c})}function o0(){return tc.useSyncExternalStore(vp,()=>!0,()=>!1)}function vp(){return()=>{}}var r0=at.createContext(null);function Be(a){return at.useContext(r0)}var ac=at.createContext(void 0),gp=at.createContext(void 0),Lt=(a=>(a[a.None=0]="None",a[a.Mutable=1]="Mutable",a[a.Watching=2]="Watching",a[a.RecursedCheck=4]="RecursedCheck",a[a.Recursed=8]="Recursed",a[a.Dirty=16]="Dirty",a[a.Pending=32]="Pending",a))(Lt||{});function pp({update:a,notify:c,unwatched:s}){return{link:f,unlink:r,propagate:h,checkDirty:g,shallowPropagate:m};function f(d,S,p){const b=S.depsTail;if(b!==void 0&&b.dep===d)return;const T=b!==void 0?b.nextDep:S.deps;if(T!==void 0&&T.dep===d){T.version=p,S.depsTail=T;return}const R=d.subsTail;if(R!==void 0&&R.version===p&&R.sub===S)return;const E=S.depsTail=d.subsTail={version:p,dep:d,sub:S,prevDep:b,nextDep:T,prevSub:R,nextSub:void 0};T!==void 0&&(T.prevDep=E),b!==void 0?b.nextDep=E:S.deps=E,R!==void 0?R.nextSub=E:d.subs=E}function r(d,S=d.sub){const p=d.dep,b=d.prevDep,T=d.nextDep,R=d.nextSub,E=d.prevSub;return T!==void 0?T.prevDep=b:S.depsTail=b,b!==void 0?b.nextDep=T:S.deps=T,R!==void 0?R.prevSub=E:p.subsTail=E,E!==void 0?E.nextSub=R:(p.subs=R)===void 0&&s(p),T}function h(d){let S=d.nextSub,p;t:do{const b=d.sub;let T=b.flags;if(T&60?T&12?T&4?!(T&48)&&y(d,b)?(b.flags=T|40,T&=1):T=0:b.flags=T&-9|32:T=0:b.flags=T|32,T&2&&c(b),T&1){const R=b.subs;if(R!==void 0){const E=(d=R).nextSub;E!==void 0&&(p={value:S,prev:p},S=E);continue}}if((d=S)!==void 0){S=d.nextSub;continue}for(;p!==void 0;)if(d=p.value,p=p.prev,d!==void 0){S=d.nextSub;continue t}break}while(!0)}function g(d,S){let p,b=0,T=!1;t:do{const R=d.dep,E=R.flags;if(S.flags&16)T=!0;else if((E&17)===17){if(a(R)){const D=R.subs;D.nextSub!==void 0&&m(D),T=!0}}else if((E&33)===33){(d.nextSub!==void 0||d.prevSub!==void 0)&&(p={value:d,prev:p}),d=R.deps,S=R,++b;continue}if(!T){const D=d.nextDep;if(D!==void 0){d=D;continue}}for(;b--;){const D=S.subs,w=D.nextSub!==void 0;if(w?(d=p.value,p=p.prev):d=D,T){if(a(S)){w&&m(D),S=d.sub;continue}T=!1}else S.flags&=-33;S=d.sub;const Y=d.nextDep;if(Y!==void 0){d=Y;continue t}}return T}while(!0)}function m(d){do{const S=d.sub,p=S.flags;(p&48)===32&&(S.flags=p|16,(p&6)===2&&c(S))}while((d=d.nextSub)!==void 0)}function y(d,S){let p=S.depsTail;for(;p!==void 0;){if(p===d)return!0;p=p.prevDep}return!1}}function Sp(a,c,s){const f=typeof a=="object",r=f?a:void 0;return{next:(f?a.next:a)?.bind(r),error:(f?a.error:c)?.bind(r),complete:(f?a.complete:s)?.bind(r)}}const wf=[];let Zi=0;const{link:Cm,unlink:bp,propagate:_p,checkDirty:d0,shallowPropagate:xm}=pp({update(a){return a._update()},notify(a){wf[Yf++]=a,a.flags&=~Lt.Watching},unwatched(a){a.depsTail!==void 0&&(a.depsTail=void 0,a.flags=Lt.Mutable|Lt.Dirty,Pi(a))}});let Yi=0,Yf=0,Ge,Gf=0;function Ep(a){try{++Gf,a()}finally{--Gf||h0()}}function Pi(a){const c=a.depsTail;let s=c!==void 0?c.nextDep:a.deps;for(;s!==void 0;)s=bp(s,a)}function h0(){if(!(Gf>0)){for(;Yi{r.get(),m.current?g.next?.(r._snapshot):m.current=!0});return{unsubscribe:()=>{y.stop()}}},_update(h){const g=Ge,m=c?.compare??Object.is;if(s)Ge=r,++Zi,r.depsTail=void 0;else if(h===void 0)return!1;s&&(r.flags=Lt.Mutable|Lt.RecursedCheck);try{const y=r._snapshot,d=typeof h=="function"?h(y):h===void 0&&s?f(y):h;return y===void 0||!m(y,d)?(r._snapshot=d,!0):!1}finally{Ge=g,s&&(r.flags&=~Lt.RecursedCheck),Pi(r)}}};return s?(r.flags=Lt.Mutable|Lt.Dirty,r.get=function(){const h=r.flags;if(h&Lt.Dirty||h&Lt.Pending&&d0(r.deps,r)){if(r._update()){const g=r.subs;g!==void 0&&xm(g)}}else h&Lt.Pending&&(r.flags=h&~Lt.Pending);return Ge!==void 0&&Cm(r,Ge,Zi),r._snapshot}):r.set=function(h){if(r._update(h)){const g=r.subs;g!==void 0&&(_p(g),xm(g),h0())}},r}function Tp(a){const c=()=>{const f=Ge;Ge=s,++Zi,s.depsTail=void 0,s.flags=Lt.Watching|Lt.RecursedCheck;try{return a()}finally{Ge=f,s.flags&=~Lt.RecursedCheck,Pi(s)}},s={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:Lt.Watching|Lt.RecursedCheck,notify(){const f=this.flags;f&Lt.Dirty||f&Lt.Pending&&d0(this.deps,this)?c():this.flags=Lt.Watching},stop(){this.flags=Lt.None,this.depsTail=void 0,Pi(this)}};return c(),s}var Of={exports:{}},Mf={},Cf={exports:{}},xf={};var Um;function zp(){if(Um)return xf;Um=1;var a=pu();function c(p,b){return p===b&&(p!==0||1/p===1/b)||p!==p&&b!==b}var s=typeof Object.is=="function"?Object.is:c,f=a.useState,r=a.useEffect,h=a.useLayoutEffect,g=a.useDebugValue;function m(p,b){var T=b(),R=f({inst:{value:T,getSnapshot:b}}),E=R[0].inst,D=R[1];return h(function(){E.value=T,E.getSnapshot=b,y(E)&&D({inst:E})},[p,T,b]),r(function(){return y(E)&&D({inst:E}),p(function(){y(E)&&D({inst:E})})},[p]),g(T),T}function y(p){var b=p.getSnapshot;p=p.value;try{var T=b();return!s(p,T)}catch{return!0}}function d(p,b){return b()}var S=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:m;return xf.useSyncExternalStore=a.useSyncExternalStore!==void 0?a.useSyncExternalStore:S,xf}var Lm;function Ap(){return Lm||(Lm=1,Cf.exports=zp()),Cf.exports}var Nm;function Rp(){if(Nm)return Mf;Nm=1;var a=pu(),c=Ap();function s(d,S){return d===S&&(d!==0||1/d===1/S)||d!==d&&S!==S}var f=typeof Object.is=="function"?Object.is:s,r=c.useSyncExternalStore,h=a.useRef,g=a.useEffect,m=a.useMemo,y=a.useDebugValue;return Mf.useSyncExternalStoreWithSelector=function(d,S,p,b,T){var R=h(null);if(R.current===null){var E={hasValue:!1,value:null};R.current=E}else E=R.current;R=m(function(){function w(G){if(!Y){if(Y=!0,K=G,G=b(G),T!==void 0&&E.hasValue){var L=E.value;if(T(L,G))return X=L}return X=G}if(L=X,f(K,G))return L;var Q=b(G);return T!==void 0&&T(L,Q)?(K=G,L):(K=G,X=Q)}var Y=!1,K,X,et=p===void 0?null:p;return[function(){return w(S())},et===null?void 0:function(){return w(et())}]},[S,p,b,T]);var D=r(d,R[0],R[1]);return g(function(){E.hasValue=!0,E.value=D},[D]),y(D),D},Mf}var Bm;function Op(){return Bm||(Bm=1,Of.exports=Rp()),Of.exports}var Mp=Op();function Cp(a,c){return a===c}function Vl(a,c,s=Cp){const f=at.useCallback(g=>{if(!a)return()=>{};const{unsubscribe:m}=a.subscribe(g);return m},[a]),r=at.useCallback(()=>a?.get(),[a]);return Mp.useSyncExternalStoreWithSelector(f,r,r,c,s)}var Hm={};function xp(a,c){const s=at.useRef();return f=>{const r=a?.select?a.select(f):f;return a?.structuralSharing??c.options.defaultStructuralSharing?s.current=mn(s.current,r):r}}function pn(a){const c=Be(),s=at.useContext(a.from?gp:ac),f=a.from??s,r=c.stores.getMatchStore(f),h=xp(a,c),g=Vl(r,m=>m?h(m):Hm);if(g!==Hm)return g;(a.shouldThrow??!0)&&Xf()}function m0(a){return pn({from:a.from,strict:a.strict,structuralSharing:a.structuralSharing,select:c=>a.select?a.select(c.loaderData):c.loaderData})}function y0(a){const{select:c,...s}=a;return pn({...s,select:f=>c?c(f.loaderDeps):f.loaderDeps})}function v0(a){return pn({from:a.from,shouldThrow:a.shouldThrow,structuralSharing:a.structuralSharing,strict:a.strict,select:c=>{const s=a.strict===!1?c.params:c._strictParams;return a.select?a.select(s):s}})}function g0(a){return pn({from:a.from,strict:a.strict,shouldThrow:a.shouldThrow,structuralSharing:a.structuralSharing,select:c=>a.select?a.select(c.search):c.search})}function p0(a){const c=Be();return at.useCallback(s=>c.navigate({...s,from:s.from??a?.from}),[a?.from,c])}function S0(a){return pn({...a,select:c=>a.select?a.select(c.context):c.context})}function Df(a){const c=at.useRef(a);return Yl(c.current,a,{ignoreUndefined:!1})||(c.current=a),c.current}function Dp(a,c){return a[0]===c[0]&&a[1]===c[1]&&a[2]===c[2]}function Up(a,c,s){if(a?.external)return Ji(a.href,s)?void 0:a.href;if(!wp(c)&&!(typeof c!="string"||c.indexOf(":")===-1))try{return new URL(c),Ji(c,s)?void 0:c}catch{}}function Lp(a,c,s,f,r,h){if(h)return!1;if(s?.exact){if(!Mg(a.pathname,c.pathname,f))return!1}else{const g=Wi(a.pathname,f),m=Wi(c.pathname,f);if(!(g.startsWith(m)&&(g.length===m.length||g[m.length]==="/")))return!1}return(s?.includeSearch??!0)&&!Yl(a.search,c.search,{partial:!s?.exact,ignoreUndefined:!s?.explicitUndefined})?!1:s?.includeHash?r&&a.hash===c.hash:!0}function Np(a,c){const s=Be(),f=cg(c),{activeProps:r,inactiveProps:h,activeOptions:g,to:m,preload:y,preloadDelay:d,preloadIntentProximity:S,hashScrollIntoView:p,replace:b,startTransition:T,resetScroll:R,viewTransition:E,children:D,target:w,disabled:Y,style:K,className:X,onClick:et,onBlur:G,onFocus:L,onMouseEnter:Q,onMouseLeave:J,onTouchStart:ct,ignoreBlocker:P,params:ft,search:bt,hash:ee,state:Bt,mask:N,reloadDocument:V,unsafeRelative:lt,from:_t,_fromLocation:zt,...A}=a,q=o0(),Z=Df(a.search),F=Df(a.params),nt=Df(g),it=at.useMemo(()=>a,[s,a.from,a._fromLocation,a.hash,a.to,Z,F,a.state,a.mask,a.unsafeRelative]),vt=at.useCallback(It=>{const Nt=s.buildLocation({_fromLocation:It,...it}),Kl=qp(Nt.maskedLocation?Nt.maskedLocation.publicHref:Nt.publicHref,Nt.maskedLocation?Nt.maskedLocation.external:Nt.external,s.history,Y),va=Up(Kl,m,s.protocolAllowlist);return[Kl?.href,va,Lp(It,Nt,nt,s.basepath,q,va!==void 0)]},[nt,Y,q,it,s,m]),[Jt,Ct,Qe]=Vl(s.stores.location,vt,Dp),Ve=Qe?ra(r,{})??Bp:Uf,dl=Qe?Uf:ra(h,{})??Uf,da=[X,Ve.className,dl.className].filter(Boolean).join(" "),He=(K||Ve.style||dl.style)&&{...K,...Ve.style,...dl.style},Sn=at.useRef(!1),De=a.reloadDocument||Ct||Y?!1:y??s.options.defaultPreload,ha=d??s.options.defaultPreloadDelay??0,Ze=at.useCallback(()=>{s.preloadRoute(it).catch(It=>{console.warn(It),console.warn(rp)})},[s,it]),Zl=at.useCallback(It=>{if(!It){Lf(f);return}if(!(It.isIntersecting??De==="intent")){It.isIntersecting===!1&&Lf(f);return}if(!ha){Ze();return}hu.has(f)||hu.set(f,setTimeout(()=>{hu.delete(f),Ze()},ha))},[Ze,f,De,ha]);ig(f,Zl,De!=="viewport"),at.useEffect(()=>{Sn.current||De==="render"&&(Ze(),Sn.current=!0)},[Ze,De]);const ma=It=>{const Nt=It.currentTarget.getAttribute("target"),Kl=w!==void 0?w:Nt;!Y&&!Yp(It)&&!It.defaultPrevented&&(!Kl||Kl==="_self")&&It.button===0&&(It.preventDefault(),s.navigate({...it,replace:b,resetScroll:R,hashScrollIntoView:p,startTransition:T,viewTransition:E,ignoreBlocker:P}))};if(Ct)return{...A,ref:f,href:Ct,...D&&{children:D},...w&&{target:w},...Y&&{disabled:Y},...K&&{style:K},...X&&{className:X},...et&&{onClick:et},...G&&{onBlur:G},...L&&{onFocus:L},...Q&&{onMouseEnter:Q},...J&&{onMouseLeave:J},...ct&&{onTouchStart:ct}};const ya=()=>{De==="intent"&&Ze()},Su=()=>{De==="intent"&&Lf(f)};return{...A,...Ve,...dl,href:Jt,ref:f,onClick:aa([et,ma]),onBlur:aa([G,Su]),onFocus:aa([L,Zl]),onMouseEnter:aa([Q,Zl]),onMouseLeave:aa([J,Su]),onTouchStart:aa([ct,ya]),disabled:!!Y,target:w,...He&&{style:He},...da&&{className:da},...Y&&Hp,...Qe&&jp}}var Uf={},Bp={className:"active"},Hp={role:"link","aria-disabled":!0},jp={"data-status":"active","aria-current":"page"},hu=new WeakMap,Lf=a=>{clearTimeout(hu.get(a)),hu.delete(a)},aa=a=>c=>{for(const s of a)if(s){if(c.defaultPrevented)return;s(c)}};function qp(a,c,s,f){if(!f)return c?{href:a,external:!0}:{href:s.createHref(a)||"/",external:!1}}function wp(a){if(typeof a!="string")return!1;const c=a.charCodeAt(0);return c===47?a.charCodeAt(1)!==47:c===46}var Ii=at.forwardRef((a,c)=>{const{_asChild:s,...f}=a,{type:r,...h}=Np(f,c),g=typeof f.children=="function"?f.children({isActive:h["data-status"]==="active"}):f.children;if(!s){const{disabled:m,...y}=h;return at.createElement("a",y,g)}return at.createElement(s,h,g)});function Yp(a){return!!(a.metaKey||a.altKey||a.ctrlKey||a.shiftKey)}var Gp=class extends f0{constructor(c){super(c),this.useMatch=s=>pn({select:s?.select,from:this.id,structuralSharing:s?.structuralSharing}),this.useRouteContext=s=>S0({...s,from:this.id}),this.useSearch=s=>g0({select:s?.select,structuralSharing:s?.structuralSharing,from:this.id}),this.useParams=s=>v0({select:s?.select,structuralSharing:s?.structuralSharing,from:this.id}),this.useLoaderDeps=s=>y0({...s,from:this.id}),this.useLoaderData=s=>m0({...s,from:this.id}),this.useNavigate=()=>p0({from:this.fullPath}),this.Link=tc.forwardRef((s,f)=>k.jsx(Ii,{ref:f,from:this.fullPath,...s}))}};function Xp(a){return new Gp(a)}var Qp=class extends dp{constructor(a){super(a),this.useMatch=c=>pn({select:c?.select,from:this.id,structuralSharing:c?.structuralSharing}),this.useRouteContext=c=>S0({...c,from:this.id}),this.useSearch=c=>g0({select:c?.select,structuralSharing:c?.structuralSharing,from:this.id}),this.useParams=c=>v0({select:c?.select,structuralSharing:c?.structuralSharing,from:this.id}),this.useLoaderDeps=c=>y0({...c,from:this.id}),this.useLoaderData=c=>m0({...c,from:this.id}),this.useNavigate=()=>p0({from:this.fullPath}),this.Link=tc.forwardRef((c,s)=>k.jsx(Ii,{ref:s,from:this.fullPath,...c}))}};function Vp(a){return new Qp(a)}function b0(a){return c=>{const s=Xp(c);return s.isRoot=!1,s}}function _0(a,c){let s,f,r;const h=()=>(s||(r=void 0,s=a().then(m=>{s=void 0,f=m[c]}).catch(m=>{s=void 0,r=m})),s),g=function(y){if(r){if(rg(r)&&typeof sessionStorage<"u"){const d=`tanstack_router_reload:${r.message}`;if(!sessionStorage.getItem(d))throw sessionStorage.setItem(d,"1"),window.location.reload(),new Promise(()=>{})}throw r}if(!f)if(cm)cm(h());else throw h();return at.createElement(f,y)};return g.preload=h,g}function Zp(a){const c=Be(),s=`not-found-${Vl(c.stores.location,f=>f.pathname)}-${Vl(c.stores.status,f=>f)}`;return k.jsx(Wf,{getResetKey:()=>s,onCatch:(f,r)=>{if(yn(f))a.onCatch?.(f,r);else throw f},errorComponent:({error:f})=>{if(yn(f))return a.fallback?.(f);throw f},children:a.children})}function Kp(){return k.jsx("p",{children:"Not Found"})}function ia(a){return k.jsx(k.Fragment,{children:a.children})}function E0(a,c,s){return c.options.notFoundComponent?k.jsx(c.options.notFoundComponent,{...s}):a.options.defaultNotFoundComponent?k.jsx(a.options.defaultNotFoundComponent,{...s}):k.jsx(Kp,{})}function uc(a,c){const s=c?.options.pendingComponent??a.options.defaultPendingComponent;return s?k.jsx(s,{}):null}var Jp=(a,c)=>a[0]===c[0]&&a[1]===c[1],T0=at.memo(function({routeId:c}){const s=Be();return k.jsx(kp,{router:s,match:Vl(s.stores.getMatchStore(c),f=>f)})});function kp({router:a,match:c}){const s=a.routesById[c.routeId],f=uc(a,s),r=s.options.errorComponent??a.options.defaultErrorComponent,h=s.options.onCatch??a.options.defaultOnCatch,g=s.isRoot?s.options.notFoundComponent??a.options.notFoundRoute?.options.component:s.options.notFoundComponent,m=c.ssr===!1||c.ssr==="data-only",y=s.options.wrapInSuspense??f??(s.options.errorComponent?.preload||m)?at.Suspense:ia,d=r?Wf:ia,S=g?Zp:ia;return k.jsxs(s.isRoot?s.options.shellComponent??ia:ia,{children:[k.jsx(ac.Provider,{value:c.routeId,children:k.jsx(y,{fallback:f,children:k.jsx(d,{getResetKey:()=>c,errorComponent:r,onCatch:(p,b)=>{if(yn(p))throw p.routeId??=c.routeId,p;h?.(p,b)},children:k.jsx(S,{fallback:p=>{if(p.routeId??=c.routeId,p.routeId!==c.routeId)throw p;return at.createElement(g,p)},children:m?k.jsx(yp,{fallback:f,children:k.jsx(jm,{match:c})}):k.jsx(jm,{match:c})})})})}),null]})}var jm=at.memo(function({match:c}){const s=Be(),f=c.routeId,r=s.routesById[f],h=at.useMemo(()=>{const m=(r.options.remountDeps??s.options.defaultRemountDeps)?.({routeId:f,loaderDeps:c.loaderDeps,params:c._strictParams,search:c._strictSearch});return m?JSON.stringify(m):void 0},[f,c.loaderDeps,c._strictParams,c._strictSearch,r.options.remountDeps,s.options.defaultRemountDeps]),g=at.useMemo(()=>{const m=r.options.component??s.options.defaultComponent;return m?k.jsx(m,{},h):k.jsx(z0,{})},[h,r.options.component,s.options.defaultComponent]);if(c.status==="pending"){if(s._tx)throw s._tx[5];return uc(s,r)}if(c.status==="notFound")return E0(s,r,c.error);if(c.status==="error")throw c.error;return g}),z0=at.memo(function(){const c=Be(),s=at.useContext(ac);let f,r,h;{const m=c.stores.getMatchStore(s);[f,r]=Vl(m,y=>[!!y._notFound,y.error],Jp),h=Vl(c.stores.ids,y=>y[y.indexOf(s)+1])}if(f)return E0(c,c.routesById[s],r);if(!h)return null;const g=k.jsx(T0,{routeId:h});return s===sa?k.jsx(at.Suspense,{fallback:uc(c),children:g}):g});function A0(a,c){const s=a[1];a.length=0,s?.(c)}function Wp({t:a}){const c=Be(),s=c._rendered??=[];return c.startTransition=(f,r)=>new Promise((h,g)=>{A0(s,!1),s.push(r,h),a(c),at.startTransition(()=>{try{f()}catch(m){s[1]===h&&(s.length=0),g(m)}})}),Ym(()=>{const f=c.history.subscribe(c.load);c.updateLatestLocation();const r=c.latestLocation,h=c.buildLocation({to:r.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});if(ol(r.publicHref)!==ol(h.publicHref))return c.commitLocation({...h,replace:!0,ignoreBlocker:!0}),f;const g=c.stores.resolvedLocation.get();return g?.href===r.href&&g.state.__TSR_key===r.state.__TSR_key?s.push(c.stores.matches.get(),m=>{m&&c.emit({type:"onRendered",...lc(g,g)})}):c._tx||c.load().catch(console.error),f},[c,c.history]),null}function Fp(){const a=Be(),c=a.routesById[sa],s=uc(a,c),f=a.ssr?ia:at.Suspense,r=k.jsxs(k.Fragment,{children:[k.jsx(Wp,{t:at.useState()[1]}),k.jsx(f,{fallback:s,children:k.jsx($p,{})})]});return a.options.InnerWrap?k.jsx(a.options.InnerWrap,{children:r}):r}function $p(){const a=Be(),c=a._rendered,s=Vl(a.stores.matches,g=>c[0]??g),f=s[0],r=f?.routeId;Ym(()=>{c[0]===s&&A0(c,!0)},[c,s]);const h=r?k.jsx(T0,{routeId:r}):null;return k.jsx(ac.Provider,{value:r,children:a.options.disableGlobalCatchBoundary?h:k.jsx(Wf,{getResetKey:()=>f,onCatch:void 0,children:h})})}var Pp=a=>({createMutableStore:Dm,createReadonlyStore:Dm,batch:Ep}),Ip=a=>new t1(a),t1=class extends Ig{constructor(a){super(a,Pp)}};function e1({router:a,children:c,...s}){Xm(s)&&a.update({...a.options,...s,context:{...a.options.context,...s.context}});const f=k.jsx(r0.Provider,{value:a,children:c});return a.options.Wrap?k.jsx(a.options.Wrap,{children:f}):f}function l1({router:a,...c}){return k.jsx(e1,{router:a,...c,children:k.jsx(Fp,{})})}const R0="taskreport.user",O0="taskreport.role";function Ff(){return{user:localStorage.getItem(R0)??"ada",role:localStorage.getItem(O0)??"member"}}function n1(a,c){localStorage.setItem(R0,a),localStorage.setItem(O0,c)}async function ql(a,c){const{user:s,role:f}=Ff(),r=await fetch(`/api${a}`,{...c,headers:{"Content-Type":"application/json","X-Demo-User":s,"X-Demo-Role":f,...c?.headers}}),h=await r.text(),g=h?JSON.parse(h):null;if(!r.ok)throw new Error(g?.error??`${r.status} ${r.statusText}`);return g}const a1={session:()=>ql("/session"),summary:()=>ql("/summary"),tasks:(a={})=>{const c=new URLSearchParams(Object.entries(a).filter(([,s])=>s!=="")).toString();return ql(`/tasks${c?`?${c}`:""}`)},create:a=>ql("/tasks",{method:"POST",body:JSON.stringify(a)}),complete:a=>ql(`/tasks/${a}/complete`,{method:"POST"}),reopen:a=>ql(`/tasks/${a}/reopen`,{method:"POST"}),remove:a=>ql(`/tasks/${a}`,{method:"DELETE"}),chat:a=>ql("/chat",{method:"POST",body:JSON.stringify({request:a})}),chatStream:u1};async function u1(a,c,s){const{user:f,role:r}=Ff(),h=await fetch("/api/chat/stream",{method:"POST",signal:s,headers:{"Content-Type":"application/json","X-Demo-User":f,"X-Demo-Role":r},body:JSON.stringify({request:a})});if(!h.ok||!h.body){const S=await h.text();throw new Error(i1(S)??`${h.status} ${h.statusText}`)}const g=h.body.getReader(),m=new TextDecoder;let y="",d=null;for(;;){const{done:S,value:p}=await g.read();if(S)break;y+=m.decode(p,{stream:!0});let b=y.indexOf(` +`+n.stack}}var Zl=Object.prototype.hasOwnProperty,ma=a.unstable_scheduleCallback,ya=a.unstable_cancelCallback,Su=a.unstable_shouldYield,It=a.unstable_requestPaint,Nt=a.unstable_now,Kl=a.unstable_getCurrentPriorityLevel,va=a.unstable_ImmediatePriority,Pf=a.unstable_UserBlockingPriority,bu=a.unstable_NormalPriority,C0=a.unstable_LowPriority,If=a.unstable_IdlePriority,x0=a.log,D0=a.unstable_setDisableYieldValue,ga=null,re=null;function ml(t){if(typeof x0=="function"&&D0(t),re&&typeof re.setStrictMode=="function")try{re.setStrictMode(ga,t)}catch{}}var de=Math.clz32?Math.clz32:N0,U0=Math.log,L0=Math.LN2;function N0(t){return t>>>=0,t===0?32:31-(U0(t)/L0|0)|0}var _u=256,Eu=262144,Tu=4194304;function Jl(t){var e=t&42;if(e!==0)return e;switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return t&261888;case 262144:case 524288:case 1048576:case 2097152:return t&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function zu(t,e,l){var n=t.pendingLanes;if(n===0)return 0;var u=0,i=t.suspendedLanes,o=t.pingedLanes;t=t.warmLanes;var v=n&134217727;return v!==0?(n=v&~i,n!==0?u=Jl(n):(o&=v,o!==0?u=Jl(o):l||(l=v&~t,l!==0&&(u=Jl(l))))):(v=n&~i,v!==0?u=Jl(v):o!==0?u=Jl(o):l||(l=n&~t,l!==0&&(u=Jl(l)))),u===0?0:e!==0&&e!==u&&(e&i)===0&&(i=u&-u,l=e&-e,i>=l||i===32&&(l&4194048)!==0)?e:u}function pa(t,e){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&e)===0}function B0(t,e){switch(t){case 1:case 2:case 4:case 8:case 64:return e+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function to(){var t=Tu;return Tu<<=1,(Tu&62914560)===0&&(Tu=4194304),t}function ic(t){for(var e=[],l=0;31>l;l++)e.push(t);return e}function Sa(t,e){t.pendingLanes|=e,e!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function H0(t,e,l,n,u,i){var o=t.pendingLanes;t.pendingLanes=l,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=l,t.entangledLanes&=l,t.errorRecoveryDisabledLanes&=l,t.shellSuspendCounter=0;var v=t.entanglements,_=t.expirationTimes,C=t.hiddenUpdates;for(l=o&~l;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var X0=/[\n"\\]/g;function _e(t){return t.replace(X0,function(e){return"\\"+e.charCodeAt(0).toString(16)+" "})}function dc(t,e,l,n,u,i,o,v){t.name="",o!=null&&typeof o!="function"&&typeof o!="symbol"&&typeof o!="boolean"?t.type=o:t.removeAttribute("type"),e!=null?o==="number"?(e===0&&t.value===""||t.value!=e)&&(t.value=""+be(e)):t.value!==""+be(e)&&(t.value=""+be(e)):o!=="submit"&&o!=="reset"||t.removeAttribute("value"),e!=null?hc(t,o,be(e)):l!=null?hc(t,o,be(l)):n!=null&&t.removeAttribute("value"),u==null&&i!=null&&(t.defaultChecked=!!i),u!=null&&(t.checked=u&&typeof u!="function"&&typeof u!="symbol"),v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"?t.name=""+be(v):t.removeAttribute("name")}function mo(t,e,l,n,u,i,o,v){if(i!=null&&typeof i!="function"&&typeof i!="symbol"&&typeof i!="boolean"&&(t.type=i),e!=null||l!=null){if(!(i!=="submit"&&i!=="reset"||e!=null)){rc(t);return}l=l!=null?""+be(l):"",e=e!=null?""+be(e):l,v||e===t.value||(t.value=e),t.defaultValue=e}n=n??u,n=typeof n!="function"&&typeof n!="symbol"&&!!n,t.checked=v?t.checked:!!n,t.defaultChecked=!!n,o!=null&&typeof o!="function"&&typeof o!="symbol"&&typeof o!="boolean"&&(t.name=o),rc(t)}function hc(t,e,l){e==="number"&&Ou(t.ownerDocument)===t||t.defaultValue===""+l||(t.defaultValue=""+l)}function An(t,e,l,n){if(t=t.options,e){e={};for(var u=0;u"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),pc=!1;if(We)try{var Ta={};Object.defineProperty(Ta,"passive",{get:function(){pc=!0}}),window.addEventListener("test",Ta,Ta),window.removeEventListener("test",Ta,Ta)}catch{pc=!1}var vl=null,Sc=null,Cu=null;function _o(){if(Cu)return Cu;var t,e=Sc,l=e.length,n,u="value"in vl?vl.value:vl.textContent,i=u.length;for(t=0;t=Ra),Oo=" ",Mo=!1;function Co(t,e){switch(t){case"keyup":return vy.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function xo(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Cn=!1;function py(t,e){switch(t){case"compositionend":return xo(e);case"keypress":return e.which!==32?null:(Mo=!0,Oo);case"textInput":return t=e.data,t===Oo&&Mo?null:t;default:return null}}function Sy(t,e){if(Cn)return t==="compositionend"||!zc&&Co(t,e)?(t=_o(),Cu=Sc=vl=null,Cn=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1=e)return{node:l,offset:e-t};t=n}t:{for(;l;){if(l.nextSibling){l=l.nextSibling;break t}l=l.parentNode}l=void 0}l=qo(l)}}function Yo(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?Yo(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function Go(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var e=Ou(t.document);e instanceof t.HTMLIFrameElement;){try{var l=typeof e.contentWindow.location.href=="string"}catch{l=!1}if(l)t=e.contentWindow;else break;e=Ou(t.document)}return e}function Oc(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e&&(e==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||e==="textarea"||t.contentEditable==="true")}var Oy=We&&"documentMode"in document&&11>=document.documentMode,xn=null,Mc=null,xa=null,Cc=!1;function Xo(t,e,l){var n=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;Cc||xn==null||xn!==Ou(n)||(n=xn,"selectionStart"in n&&Oc(n)?n={start:n.selectionStart,end:n.selectionEnd}:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection(),n={anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}),xa&&Ca(xa,n)||(xa=n,n=Ei(Mc,"onSelect"),0>=o,u-=o,je=1<<32-de(e)+u|l<ot?(mt=$,$=null):mt=$.sibling;var pt=x(O,$,M[ot],H);if(pt===null){$===null&&($=mt);break}t&&$&&pt.alternate===null&&e(O,$),z=i(pt,z,ot),gt===null?I=pt:gt.sibling=pt,gt=pt,$=mt}if(ot===M.length)return l(O,$),yt&&$e(O,ot),I;if($===null){for(;otot?(mt=$,$=null):mt=$.sibling;var ql=x(O,$,pt.value,H);if(ql===null){$===null&&($=mt);break}t&&$&&ql.alternate===null&&e(O,$),z=i(ql,z,ot),gt===null?I=ql:gt.sibling=ql,gt=ql,$=mt}if(pt.done)return l(O,$),yt&&$e(O,ot),I;if($===null){for(;!pt.done;ot++,pt=M.next())pt=j(O,pt.value,H),pt!==null&&(z=i(pt,z,ot),gt===null?I=pt:gt.sibling=pt,gt=pt);return yt&&$e(O,ot),I}for($=n($);!pt.done;ot++,pt=M.next())pt=U($,O,ot,pt.value,H),pt!==null&&(t&&pt.alternate!==null&&$.delete(pt.key===null?ot:pt.key),z=i(pt,z,ot),gt===null?I=pt:gt.sibling=pt,gt=pt);return t&&$.forEach(function(Jv){return e(O,Jv)}),yt&&$e(O,ot),I}function Ot(O,z,M,H){if(typeof M=="object"&&M!==null&&M.type===E&&M.key===null&&(M=M.props.children),typeof M=="object"&&M!==null){switch(M.$$typeof){case T:t:{for(var I=M.key;z!==null;){if(z.key===I){if(I=M.type,I===E){if(z.tag===7){l(O,z.sibling),H=u(z,M.props.children),H.return=O,O=H;break t}}else if(z.elementType===I||typeof I=="object"&&I!==null&&I.$$typeof===Q&&an(I)===z.type){l(O,z.sibling),H=u(z,M.props),Ha(H,M),H.return=O,O=H;break t}l(O,z);break}else e(O,z);z=z.sibling}M.type===E?(H=Il(M.props.children,O.mode,H,M.key),H.return=O,O=H):(H=wu(M.type,M.key,M.props,null,O.mode,H),Ha(H,M),H.return=O,O=H)}return o(O);case R:t:{for(I=M.key;z!==null;){if(z.key===I)if(z.tag===4&&z.stateNode.containerInfo===M.containerInfo&&z.stateNode.implementation===M.implementation){l(O,z.sibling),H=u(z,M.children||[]),H.return=O,O=H;break t}else{l(O,z);break}else e(O,z);z=z.sibling}H=Hc(M,O.mode,H),H.return=O,O=H}return o(O);case Q:return M=an(M),Ot(O,z,M,H)}if(Bt(M))return W(O,z,M,H);if(ft(M)){if(I=ft(M),typeof I!="function")throw Error(f(150));return M=I.call(M),tt(O,z,M,H)}if(typeof M.then=="function")return Ot(O,z,Ku(M),H);if(M.$$typeof===K)return Ot(O,z,Xu(O,M),H);Ju(O,M)}return typeof M=="string"&&M!==""||typeof M=="number"||typeof M=="bigint"?(M=""+M,z!==null&&z.tag===6?(l(O,z.sibling),H=u(z,M),H.return=O,O=H):(l(O,z),H=Bc(M,O.mode,H),H.return=O,O=H),o(O)):l(O,z)}return function(O,z,M,H){try{Ba=0;var I=Ot(O,z,M,H);return Gn=null,I}catch($){if($===Yn||$===Vu)throw $;var gt=me(29,$,null,O.mode);return gt.lanes=H,gt.return=O,gt}}}var cn=rr(!0),dr=rr(!1),_l=!1;function kc(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Wc(t,e){t=t.updateQueue,e.updateQueue===t&&(e.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function El(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function Tl(t,e,l){var n=t.updateQueue;if(n===null)return null;if(n=n.shared,(St&2)!==0){var u=n.pending;return u===null?e.next=e:(e.next=u.next,u.next=e),n.pending=e,e=qu(t),Wo(t,null,l),e}return ju(t,n,e,l),qu(t)}function ja(t,e,l){if(e=e.updateQueue,e!==null&&(e=e.shared,(l&4194048)!==0)){var n=e.lanes;n&=t.pendingLanes,l|=n,e.lanes=l,lo(t,l)}}function Fc(t,e){var l=t.updateQueue,n=t.alternate;if(n!==null&&(n=n.updateQueue,l===n)){var u=null,i=null;if(l=l.firstBaseUpdate,l!==null){do{var o={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};i===null?u=i=o:i=i.next=o,l=l.next}while(l!==null);i===null?u=i=e:i=i.next=e}else u=i=e;l={baseState:n.baseState,firstBaseUpdate:u,lastBaseUpdate:i,shared:n.shared,callbacks:n.callbacks},t.updateQueue=l;return}t=l.lastBaseUpdate,t===null?l.firstBaseUpdate=e:t.next=e,l.lastBaseUpdate=e}var $c=!1;function qa(){if($c){var t=wn;if(t!==null)throw t}}function wa(t,e,l,n){$c=!1;var u=t.updateQueue;_l=!1;var i=u.firstBaseUpdate,o=u.lastBaseUpdate,v=u.shared.pending;if(v!==null){u.shared.pending=null;var _=v,C=_.next;_.next=null,o===null?i=C:o.next=C,o=_;var B=t.alternate;B!==null&&(B=B.updateQueue,v=B.lastBaseUpdate,v!==o&&(v===null?B.firstBaseUpdate=C:v.next=C,B.lastBaseUpdate=_))}if(i!==null){var j=u.baseState;o=0,B=C=_=null,v=i;do{var x=v.lane&-536870913,U=x!==v.lane;if(U?(ht&x)===x:(n&x)===x){x!==0&&x===qn&&($c=!0),B!==null&&(B=B.next={lane:0,tag:v.tag,payload:v.payload,callback:null,next:null});t:{var W=t,tt=v;x=e;var Ot=l;switch(tt.tag){case 1:if(W=tt.payload,typeof W=="function"){j=W.call(Ot,j,x);break t}j=W;break t;case 3:W.flags=W.flags&-65537|128;case 0:if(W=tt.payload,x=typeof W=="function"?W.call(Ot,j,x):W,x==null)break t;j=p({},j,x);break t;case 2:_l=!0}}x=v.callback,x!==null&&(t.flags|=64,U&&(t.flags|=8192),U=u.callbacks,U===null?u.callbacks=[x]:U.push(x))}else U={lane:x,tag:v.tag,payload:v.payload,callback:v.callback,next:null},B===null?(C=B=U,_=j):B=B.next=U,o|=x;if(v=v.next,v===null){if(v=u.shared.pending,v===null)break;U=v,v=U.next,U.next=null,u.lastBaseUpdate=U,u.shared.pending=null}}while(!0);B===null&&(_=j),u.baseState=_,u.firstBaseUpdate=C,u.lastBaseUpdate=B,i===null&&(u.shared.lanes=0),Ml|=o,t.lanes=o,t.memoizedState=j}}function hr(t,e){if(typeof t!="function")throw Error(f(191,t));t.call(e)}function mr(t,e){var l=t.callbacks;if(l!==null)for(t.callbacks=null,t=0;ti?i:8;var o=N.T,v={};N.T=v,vs(t,!1,e,l);try{var _=u(),C=N.S;if(C!==null&&C(v,_),_!==null&&typeof _=="object"&&typeof _.then=="function"){var B=Hy(_,n);Xa(t,e,B,Se(t))}else Xa(t,e,n,Se(t))}catch(j){Xa(t,e,{then:function(){},status:"rejected",reason:j},Se())}finally{V.p=i,o!==null&&v.types!==null&&(o.types=v.types),N.T=o}}function Xy(){}function ms(t,e,l,n){if(t.tag!==5)throw Error(f(476));var u=Kr(t).queue;Zr(t,u,e,lt,l===null?Xy:function(){return Jr(t),l(n)})}function Kr(t){var e=t.memoizedState;if(e!==null)return e;e={memoizedState:lt,baseState:lt,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:el,lastRenderedState:lt},next:null};var l={};return e.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:el,lastRenderedState:l},next:null},t.memoizedState=e,t=t.alternate,t!==null&&(t.memoizedState=e),e}function Jr(t){var e=Kr(t);e.next===null&&(e=t.alternate.memoizedState),Xa(t,e.next.queue,{},Se())}function ys(){return Ft(uu)}function kr(){return wt().memoizedState}function Wr(){return wt().memoizedState}function Qy(t){for(var e=t.return;e!==null;){switch(e.tag){case 24:case 3:var l=Se();t=El(l);var n=Tl(e,t,l);n!==null&&(fe(n,e,l),ja(n,e,l)),e={cache:Vc()},t.payload=e;return}e=e.return}}function Vy(t,e,l){var n=Se();l={lane:n,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},ni(t)?$r(e,l):(l=Lc(t,e,l,n),l!==null&&(fe(l,t,n),Pr(l,e,n)))}function Fr(t,e,l){var n=Se();Xa(t,e,l,n)}function Xa(t,e,l,n){var u={lane:n,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(ni(t))$r(e,u);else{var i=t.alternate;if(t.lanes===0&&(i===null||i.lanes===0)&&(i=e.lastRenderedReducer,i!==null))try{var o=e.lastRenderedState,v=i(o,l);if(u.hasEagerState=!0,u.eagerState=v,he(v,o))return ju(t,e,u,0),Mt===null&&Hu(),!1}catch{}if(l=Lc(t,e,u,n),l!==null)return fe(l,t,n),Pr(l,e,n),!0}return!1}function vs(t,e,l,n){if(n={lane:2,revertLane:ks(),gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},ni(t)){if(e)throw Error(f(479))}else e=Lc(t,l,n,2),e!==null&&fe(e,t,2)}function ni(t){var e=t.alternate;return t===st||e!==null&&e===st}function $r(t,e){Qn=Fu=!0;var l=t.pending;l===null?e.next=e:(e.next=l.next,l.next=e),t.pending=e}function Pr(t,e,l){if((l&4194048)!==0){var n=e.lanes;n&=t.pendingLanes,l|=n,e.lanes=l,lo(t,l)}}var Qa={readContext:Ft,use:Iu,useCallback:Ht,useContext:Ht,useEffect:Ht,useImperativeHandle:Ht,useLayoutEffect:Ht,useInsertionEffect:Ht,useMemo:Ht,useReducer:Ht,useRef:Ht,useState:Ht,useDebugValue:Ht,useDeferredValue:Ht,useTransition:Ht,useSyncExternalStore:Ht,useId:Ht,useHostTransitionStatus:Ht,useFormState:Ht,useActionState:Ht,useOptimistic:Ht,useMemoCache:Ht,useCacheRefresh:Ht};Qa.useEffectEvent=Ht;var Ir={readContext:Ft,use:Iu,useCallback:function(t,e){return le().memoizedState=[t,e===void 0?null:e],t},useContext:Ft,useEffect:Hr,useImperativeHandle:function(t,e,l){l=l!=null?l.concat([t]):null,ei(4194308,4,Yr.bind(null,e,t),l)},useLayoutEffect:function(t,e){return ei(4194308,4,t,e)},useInsertionEffect:function(t,e){ei(4,2,t,e)},useMemo:function(t,e){var l=le();e=e===void 0?null:e;var n=t();if(sn){ml(!0);try{t()}finally{ml(!1)}}return l.memoizedState=[n,e],n},useReducer:function(t,e,l){var n=le();if(l!==void 0){var u=l(e);if(sn){ml(!0);try{l(e)}finally{ml(!1)}}}else u=e;return n.memoizedState=n.baseState=u,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:u},n.queue=t,t=t.dispatch=Vy.bind(null,st,t),[n.memoizedState,t]},useRef:function(t){var e=le();return t={current:t},e.memoizedState=t},useState:function(t){t=fs(t);var e=t.queue,l=Fr.bind(null,st,e);return e.dispatch=l,[t.memoizedState,l]},useDebugValue:ds,useDeferredValue:function(t,e){var l=le();return hs(l,t,e)},useTransition:function(){var t=fs(!1);return t=Zr.bind(null,st,t.queue,!0,!1),le().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,e,l){var n=st,u=le();if(yt){if(l===void 0)throw Error(f(407));l=l()}else{if(l=e(),Mt===null)throw Error(f(349));(ht&127)!==0||br(n,e,l)}u.memoizedState=l;var i={value:l,getSnapshot:e};return u.queue=i,Hr(Er.bind(null,n,i,t),[t]),n.flags|=2048,Zn(9,{destroy:void 0},_r.bind(null,n,i,l,e),null),l},useId:function(){var t=le(),e=Mt.identifierPrefix;if(yt){var l=qe,n=je;l=(n&~(1<<32-de(n)-1)).toString(32)+l,e="_"+e+"R_"+l,l=$u++,0<\/script>",i=i.removeChild(i.firstChild);break;case"select":i=typeof n.is=="string"?o.createElement("select",{is:n.is}):o.createElement("select"),n.multiple?i.multiple=!0:n.size&&(i.size=n.size);break;default:i=typeof n.is=="string"?o.createElement(u,{is:n.is}):o.createElement(u)}}i[kt]=e,i[ne]=n;t:for(o=e.child;o!==null;){if(o.tag===5||o.tag===6)i.appendChild(o.stateNode);else if(o.tag!==4&&o.tag!==27&&o.child!==null){o.child.return=o,o=o.child;continue}if(o===e)break t;for(;o.sibling===null;){if(o.return===null||o.return===e)break t;o=o.return}o.sibling.return=o.return,o=o.sibling}e.stateNode=i;t:switch(Pt(i,u,n),u){case"button":case"input":case"select":case"textarea":n=!!n.autoFocus;break t;case"img":n=!0;break t;default:n=!1}n&&nl(e)}}return Dt(e),xs(e,e.type,t===null?null:t.memoizedProps,e.pendingProps,l),null;case 6:if(t&&e.stateNode!=null)t.memoizedProps!==n&&nl(e);else{if(typeof n!="string"&&e.stateNode===null)throw Error(f(166));if(t=it.current,Hn(e)){if(t=e.stateNode,l=e.memoizedProps,n=null,u=Wt,u!==null)switch(u.tag){case 27:case 5:n=u.memoizedProps}t[kt]=e,t=!!(t.nodeValue===l||n!==null&&n.suppressHydrationWarning===!0||ph(t.nodeValue,l)),t||Sl(e,!0)}else t=Ti(t).createTextNode(n),t[kt]=e,e.stateNode=t}return Dt(e),null;case 31:if(l=e.memoizedState,t===null||t.memoizedState!==null){if(n=Hn(e),l!==null){if(t===null){if(!n)throw Error(f(318));if(t=e.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(f(557));t[kt]=e}else tn(),(e.flags&128)===0&&(e.memoizedState=null),e.flags|=4;Dt(e),t=!1}else l=Yc(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=l),t=!0;if(!t)return e.flags&256?(ve(e),e):(ve(e),null);if((e.flags&128)!==0)throw Error(f(558))}return Dt(e),null;case 13:if(n=e.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(u=Hn(e),n!==null&&n.dehydrated!==null){if(t===null){if(!u)throw Error(f(318));if(u=e.memoizedState,u=u!==null?u.dehydrated:null,!u)throw Error(f(317));u[kt]=e}else tn(),(e.flags&128)===0&&(e.memoizedState=null),e.flags|=4;Dt(e),u=!1}else u=Yc(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=u),u=!0;if(!u)return e.flags&256?(ve(e),e):(ve(e),null)}return ve(e),(e.flags&128)!==0?(e.lanes=l,e):(l=n!==null,t=t!==null&&t.memoizedState!==null,l&&(n=e.child,u=null,n.alternate!==null&&n.alternate.memoizedState!==null&&n.alternate.memoizedState.cachePool!==null&&(u=n.alternate.memoizedState.cachePool.pool),i=null,n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(i=n.memoizedState.cachePool.pool),i!==u&&(n.flags|=2048)),l!==t&&l&&(e.child.flags|=8192),si(e,e.updateQueue),Dt(e),null);case 4:return Ct(),t===null&&Ps(e.stateNode.containerInfo),Dt(e),null;case 10:return Ie(e.type),Dt(e),null;case 19:if(q(qt),n=e.memoizedState,n===null)return Dt(e),null;if(u=(e.flags&128)!==0,i=n.rendering,i===null)if(u)Za(n,!1);else{if(jt!==0||t!==null&&(t.flags&128)!==0)for(t=e.child;t!==null;){if(i=Wu(t),i!==null){for(e.flags|=128,Za(n,!1),t=i.updateQueue,e.updateQueue=t,si(e,t),e.subtreeFlags=0,t=l,l=e.child;l!==null;)Fo(l,t),l=l.sibling;return Z(qt,qt.current&1|2),yt&&$e(e,n.treeForkCount),e.child}t=t.sibling}n.tail!==null&&Nt()>hi&&(e.flags|=128,u=!0,Za(n,!1),e.lanes=4194304)}else{if(!u)if(t=Wu(i),t!==null){if(e.flags|=128,u=!0,t=t.updateQueue,e.updateQueue=t,si(e,t),Za(n,!0),n.tail===null&&n.tailMode==="hidden"&&!i.alternate&&!yt)return Dt(e),null}else 2*Nt()-n.renderingStartTime>hi&&l!==536870912&&(e.flags|=128,u=!0,Za(n,!1),e.lanes=4194304);n.isBackwards?(i.sibling=e.child,e.child=i):(t=n.last,t!==null?t.sibling=i:e.child=i,n.last=i)}return n.tail!==null?(t=n.tail,n.rendering=t,n.tail=t.sibling,n.renderingStartTime=Nt(),t.sibling=null,l=qt.current,Z(qt,u?l&1|2:l&1),yt&&$e(e,n.treeForkCount),t):(Dt(e),null);case 22:case 23:return ve(e),Ic(),n=e.memoizedState!==null,t!==null?t.memoizedState!==null!==n&&(e.flags|=8192):n&&(e.flags|=8192),n?(l&536870912)!==0&&(e.flags&128)===0&&(Dt(e),e.subtreeFlags&6&&(e.flags|=8192)):Dt(e),l=e.updateQueue,l!==null&&si(e,l.retryQueue),l=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(l=t.memoizedState.cachePool.pool),n=null,e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),n!==l&&(e.flags|=2048),t!==null&&q(nn),null;case 24:return l=null,t!==null&&(l=t.memoizedState.cache),e.memoizedState.cache!==l&&(e.flags|=2048),Ie(Yt),Dt(e),null;case 25:return null;case 30:return null}throw Error(f(156,e.tag))}function Wy(t,e){switch(qc(e),e.tag){case 1:return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return Ie(Yt),Ct(),t=e.flags,(t&65536)!==0&&(t&128)===0?(e.flags=t&-65537|128,e):null;case 26:case 27:case 5:return Ze(e),null;case 31:if(e.memoizedState!==null){if(ve(e),e.alternate===null)throw Error(f(340));tn()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 13:if(ve(e),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(f(340));tn()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return q(qt),null;case 4:return Ct(),null;case 10:return Ie(e.type),null;case 22:case 23:return ve(e),Ic(),t!==null&&q(nn),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 24:return Ie(Yt),null;case 25:return null;default:return null}}function Td(t,e){switch(qc(e),e.tag){case 3:Ie(Yt),Ct();break;case 26:case 27:case 5:Ze(e);break;case 4:Ct();break;case 31:e.memoizedState!==null&&ve(e);break;case 13:ve(e);break;case 19:q(qt);break;case 10:Ie(e.type);break;case 22:case 23:ve(e),Ic(),t!==null&&q(nn);break;case 24:Ie(Yt)}}function Ka(t,e){try{var l=e.updateQueue,n=l!==null?l.lastEffect:null;if(n!==null){var u=n.next;l=u;do{if((l.tag&t)===t){n=void 0;var i=l.create,o=l.inst;n=i(),o.destroy=n}l=l.next}while(l!==u)}}catch(v){Tt(e,e.return,v)}}function Rl(t,e,l){try{var n=e.updateQueue,u=n!==null?n.lastEffect:null;if(u!==null){var i=u.next;n=i;do{if((n.tag&t)===t){var o=n.inst,v=o.destroy;if(v!==void 0){o.destroy=void 0,u=e;var _=l,C=v;try{C()}catch(B){Tt(u,_,B)}}}n=n.next}while(n!==i)}}catch(B){Tt(e,e.return,B)}}function zd(t){var e=t.updateQueue;if(e!==null){var l=t.stateNode;try{mr(e,l)}catch(n){Tt(t,t.return,n)}}}function Ad(t,e,l){l.props=fn(t.type,t.memoizedProps),l.state=t.memoizedState;try{l.componentWillUnmount()}catch(n){Tt(t,e,n)}}function Ja(t,e){try{var l=t.ref;if(l!==null){switch(t.tag){case 26:case 27:case 5:var n=t.stateNode;break;case 30:n=t.stateNode;break;default:n=t.stateNode}typeof l=="function"?t.refCleanup=l(n):l.current=n}}catch(u){Tt(t,e,u)}}function we(t,e){var l=t.ref,n=t.refCleanup;if(l!==null)if(typeof n=="function")try{n()}catch(u){Tt(t,e,u)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof l=="function")try{l(null)}catch(u){Tt(t,e,u)}else l.current=null}function Rd(t){var e=t.type,l=t.memoizedProps,n=t.stateNode;try{t:switch(e){case"button":case"input":case"select":case"textarea":l.autoFocus&&n.focus();break t;case"img":l.src?n.src=l.src:l.srcSet&&(n.srcset=l.srcSet)}}catch(u){Tt(t,t.return,u)}}function Ds(t,e,l){try{var n=t.stateNode;gv(n,t.type,l,e),n[ne]=e}catch(u){Tt(t,t.return,u)}}function Od(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&Ll(t.type)||t.tag===4}function Us(t){t:for(;;){for(;t.sibling===null;){if(t.return===null||Od(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.tag===27&&Ll(t.type)||t.flags&2||t.child===null||t.tag===4)continue t;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function Ls(t,e,l){var n=t.tag;if(n===5||n===6)t=t.stateNode,e?(l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l).insertBefore(t,e):(e=l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l,e.appendChild(t),l=l._reactRootContainer,l!=null||e.onclick!==null||(e.onclick=ke));else if(n!==4&&(n===27&&Ll(t.type)&&(l=t.stateNode,e=null),t=t.child,t!==null))for(Ls(t,e,l),t=t.sibling;t!==null;)Ls(t,e,l),t=t.sibling}function fi(t,e,l){var n=t.tag;if(n===5||n===6)t=t.stateNode,e?l.insertBefore(t,e):l.appendChild(t);else if(n!==4&&(n===27&&Ll(t.type)&&(l=t.stateNode),t=t.child,t!==null))for(fi(t,e,l),t=t.sibling;t!==null;)fi(t,e,l),t=t.sibling}function Md(t){var e=t.stateNode,l=t.memoizedProps;try{for(var n=t.type,u=e.attributes;u.length;)e.removeAttributeNode(u[0]);Pt(e,n,l),e[kt]=t,e[ne]=l}catch(i){Tt(t,t.return,i)}}var al=!1,Qt=!1,Ns=!1,Cd=typeof WeakSet=="function"?WeakSet:Set,Kt=null;function Fy(t,e){if(t=t.containerInfo,ef=xi,t=Go(t),Oc(t)){if("selectionStart"in t)var l={start:t.selectionStart,end:t.selectionEnd};else t:{l=(l=t.ownerDocument)&&l.defaultView||window;var n=l.getSelection&&l.getSelection();if(n&&n.rangeCount!==0){l=n.anchorNode;var u=n.anchorOffset,i=n.focusNode;n=n.focusOffset;try{l.nodeType,i.nodeType}catch{l=null;break t}var o=0,v=-1,_=-1,C=0,B=0,j=t,x=null;e:for(;;){for(var U;j!==l||u!==0&&j.nodeType!==3||(v=o+u),j!==i||n!==0&&j.nodeType!==3||(_=o+n),j.nodeType===3&&(o+=j.nodeValue.length),(U=j.firstChild)!==null;)x=j,j=U;for(;;){if(j===t)break e;if(x===l&&++C===u&&(v=o),x===i&&++B===n&&(_=o),(U=j.nextSibling)!==null)break;j=x,x=j.parentNode}j=U}l=v===-1||_===-1?null:{start:v,end:_}}else l=null}l=l||{start:0,end:0}}else l=null;for(lf={focusedElem:t,selectionRange:l},xi=!1,Kt=e;Kt!==null;)if(e=Kt,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,Kt=t;else for(;Kt!==null;){switch(e=Kt,i=e.alternate,t=e.flags,e.tag){case 0:if((t&4)!==0&&(t=e.updateQueue,t=t!==null?t.events:null,t!==null))for(l=0;l title"))),Pt(i,n,l),i[kt]=t,Zt(i),n=i;break t;case"link":var o=Bh("link","href",u).get(n+(l.href||""));if(o){for(var v=0;vOt&&(o=Ot,Ot=tt,tt=o);var O=wo(v,tt),z=wo(v,Ot);if(O&&z&&(U.rangeCount!==1||U.anchorNode!==O.node||U.anchorOffset!==O.offset||U.focusNode!==z.node||U.focusOffset!==z.offset)){var M=j.createRange();M.setStart(O.node,O.offset),U.removeAllRanges(),tt>Ot?(U.addRange(M),U.extend(z.node,z.offset)):(M.setEnd(z.node,z.offset),U.addRange(M))}}}}for(j=[],U=v;U=U.parentNode;)U.nodeType===1&&j.push({element:U,left:U.scrollLeft,top:U.scrollTop});for(typeof v.focus=="function"&&v.focus(),v=0;vl?32:l,N.T=null,l=Gs,Gs=null;var i=xl,o=fl;if(Vt=0,Fn=xl=null,fl=0,(St&6)!==0)throw Error(f(331));var v=St;if(St|=4,Yd(i.current),jd(i,i.current,o,l),St=v,Ia(0,!1),re&&typeof re.onPostCommitFiberRoot=="function")try{re.onPostCommitFiberRoot(ga,i)}catch{}return!0}finally{V.p=u,N.T=n,ah(t,e)}}function ih(t,e,l){e=Te(l,e),e=bs(t.stateNode,e,2),t=Tl(t,e,2),t!==null&&(Sa(t,2),Ye(t))}function Tt(t,e,l){if(t.tag===3)ih(t,t,l);else for(;e!==null;){if(e.tag===3){ih(e,t,l);break}else if(e.tag===1){var n=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof n.componentDidCatch=="function"&&(Cl===null||!Cl.has(n))){t=Te(l,t),l=cd(2),n=Tl(e,l,2),n!==null&&(sd(l,n,e,t),Sa(n,2),Ye(n));break}}e=e.return}}function Zs(t,e,l){var n=t.pingCache;if(n===null){n=t.pingCache=new Iy;var u=new Set;n.set(e,u)}else u=n.get(e),u===void 0&&(u=new Set,n.set(e,u));u.has(l)||(js=!0,u.add(l),t=av.bind(null,t,e,l),e.then(t,t))}function av(t,e,l){var n=t.pingCache;n!==null&&n.delete(e),t.pingedLanes|=t.suspendedLanes&l,t.warmLanes&=~l,Mt===t&&(ht&l)===l&&(jt===4||jt===3&&(ht&62914560)===ht&&300>Nt()-di?(St&2)===0&&$n(t,0):qs|=l,Wn===ht&&(Wn=0)),Ye(t)}function ch(t,e){e===0&&(e=to()),t=Pl(t,e),t!==null&&(Sa(t,e),Ye(t))}function uv(t){var e=t.memoizedState,l=0;e!==null&&(l=e.retryLane),ch(t,l)}function iv(t,e){var l=0;switch(t.tag){case 31:case 13:var n=t.stateNode,u=t.memoizedState;u!==null&&(l=u.retryLane);break;case 19:n=t.stateNode;break;case 22:n=t.stateNode._retryCache;break;default:throw Error(f(314))}n!==null&&n.delete(e),ch(t,l)}function cv(t,e){return ma(t,e)}var Si=null,In=null,Ks=!1,bi=!1,Js=!1,Ul=0;function Ye(t){t!==In&&t.next===null&&(In===null?Si=In=t:In=In.next=t),bi=!0,Ks||(Ks=!0,fv())}function Ia(t,e){if(!Js&&bi){Js=!0;do for(var l=!1,n=Si;n!==null;){if(t!==0){var u=n.pendingLanes;if(u===0)var i=0;else{var o=n.suspendedLanes,v=n.pingedLanes;i=(1<<31-de(42|t)+1)-1,i&=u&~(o&~v),i=i&201326741?i&201326741|1:i?i|2:0}i!==0&&(l=!0,rh(n,i))}else i=ht,i=zu(n,n===Mt?i:0,n.cancelPendingCommit!==null||n.timeoutHandle!==-1),(i&3)===0||pa(n,i)||(l=!0,rh(n,i));n=n.next}while(l);Js=!1}}function sv(){sh()}function sh(){bi=Ks=!1;var t=0;Ul!==0&&Sv()&&(t=Ul);for(var e=Nt(),l=null,n=Si;n!==null;){var u=n.next,i=fh(n,e);i===0?(n.next=null,l===null?Si=u:l.next=u,u===null&&(In=l)):(l=n,(t!==0||(i&3)!==0)&&(bi=!0)),n=u}Vt!==0&&Vt!==5||Ia(t),Ul!==0&&(Ul=0)}function fh(t,e){for(var l=t.suspendedLanes,n=t.pingedLanes,u=t.expirationTimes,i=t.pendingLanes&-62914561;0v)break;var B=_.transferSize,j=_.initiatorType;B&&Sh(j)&&(_=_.responseEnd,o+=B*(_"u"?null:document;function Dh(t,e,l){var n=ta;if(n&&typeof e=="string"&&e){var u=_e(e);u='link[rel="'+t+'"][href="'+u+'"]',typeof l=="string"&&(u+='[crossorigin="'+l+'"]'),xh.has(u)||(xh.add(u),t={rel:t,crossOrigin:l,href:e},n.querySelector(u)===null&&(e=n.createElement("link"),Pt(e,"link",t),Zt(e),n.head.appendChild(e)))}}function Mv(t){ol.D(t),Dh("dns-prefetch",t,null)}function Cv(t,e){ol.C(t,e),Dh("preconnect",t,e)}function xv(t,e,l){ol.L(t,e,l);var n=ta;if(n&&t&&e){var u='link[rel="preload"][as="'+_e(e)+'"]';e==="image"&&l&&l.imageSrcSet?(u+='[imagesrcset="'+_e(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(u+='[imagesizes="'+_e(l.imageSizes)+'"]')):u+='[href="'+_e(t)+'"]';var i=u;switch(e){case"style":i=ea(t);break;case"script":i=la(t)}Ce.has(i)||(t=p({rel:"preload",href:e==="image"&&l&&l.imageSrcSet?void 0:t,as:e},l),Ce.set(i,t),n.querySelector(u)!==null||e==="style"&&n.querySelector(nu(i))||e==="script"&&n.querySelector(au(i))||(e=n.createElement("link"),Pt(e,"link",t),Zt(e),n.head.appendChild(e)))}}function Dv(t,e){ol.m(t,e);var l=ta;if(l&&t){var n=e&&typeof e.as=="string"?e.as:"script",u='link[rel="modulepreload"][as="'+_e(n)+'"][href="'+_e(t)+'"]',i=u;switch(n){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":i=la(t)}if(!Ce.has(i)&&(t=p({rel:"modulepreload",href:t},e),Ce.set(i,t),l.querySelector(u)===null)){switch(n){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(au(i)))return}n=l.createElement("link"),Pt(n,"link",t),Zt(n),l.head.appendChild(n)}}}function Uv(t,e,l){ol.S(t,e,l);var n=ta;if(n&&t){var u=Tn(n).hoistableStyles,i=ea(t);e=e||"default";var o=u.get(i);if(!o){var v={loading:0,preload:null};if(o=n.querySelector(nu(i)))v.loading=5;else{t=p({rel:"stylesheet",href:t,"data-precedence":e},l),(l=Ce.get(i))&&of(t,l);var _=o=n.createElement("link");Zt(_),Pt(_,"link",t),_._p=new Promise(function(C,B){_.onload=C,_.onerror=B}),_.addEventListener("load",function(){v.loading|=1}),_.addEventListener("error",function(){v.loading|=2}),v.loading|=4,Ai(o,e,n)}o={type:"stylesheet",instance:o,count:1,state:v},u.set(i,o)}}}function Lv(t,e){ol.X(t,e);var l=ta;if(l&&t){var n=Tn(l).hoistableScripts,u=la(t),i=n.get(u);i||(i=l.querySelector(au(u)),i||(t=p({src:t,async:!0},e),(e=Ce.get(u))&&rf(t,e),i=l.createElement("script"),Zt(i),Pt(i,"link",t),l.head.appendChild(i)),i={type:"script",instance:i,count:1,state:null},n.set(u,i))}}function Nv(t,e){ol.M(t,e);var l=ta;if(l&&t){var n=Tn(l).hoistableScripts,u=la(t),i=n.get(u);i||(i=l.querySelector(au(u)),i||(t=p({src:t,async:!0,type:"module"},e),(e=Ce.get(u))&&rf(t,e),i=l.createElement("script"),Zt(i),Pt(i,"link",t),l.head.appendChild(i)),i={type:"script",instance:i,count:1,state:null},n.set(u,i))}}function Uh(t,e,l,n){var u=(u=it.current)?zi(u):null;if(!u)throw Error(f(446));switch(t){case"meta":case"title":return null;case"style":return typeof l.precedence=="string"&&typeof l.href=="string"?(e=ea(l.href),l=Tn(u).hoistableStyles,n=l.get(e),n||(n={type:"style",instance:null,count:0,state:null},l.set(e,n)),n):{type:"void",instance:null,count:0,state:null};case"link":if(l.rel==="stylesheet"&&typeof l.href=="string"&&typeof l.precedence=="string"){t=ea(l.href);var i=Tn(u).hoistableStyles,o=i.get(t);if(o||(u=u.ownerDocument||u,o={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},i.set(t,o),(i=u.querySelector(nu(t)))&&!i._p&&(o.instance=i,o.state.loading=5),Ce.has(t)||(l={rel:"preload",as:"style",href:l.href,crossOrigin:l.crossOrigin,integrity:l.integrity,media:l.media,hrefLang:l.hrefLang,referrerPolicy:l.referrerPolicy},Ce.set(t,l),i||Bv(u,t,l,o.state))),e&&n===null)throw Error(f(528,""));return o}if(e&&n!==null)throw Error(f(529,""));return null;case"script":return e=l.async,l=l.src,typeof l=="string"&&e&&typeof e!="function"&&typeof e!="symbol"?(e=la(l),l=Tn(u).hoistableScripts,n=l.get(e),n||(n={type:"script",instance:null,count:0,state:null},l.set(e,n)),n):{type:"void",instance:null,count:0,state:null};default:throw Error(f(444,t))}}function ea(t){return'href="'+_e(t)+'"'}function nu(t){return'link[rel="stylesheet"]['+t+"]"}function Lh(t){return p({},t,{"data-precedence":t.precedence,precedence:null})}function Bv(t,e,l,n){t.querySelector('link[rel="preload"][as="style"]['+e+"]")?n.loading=1:(e=t.createElement("link"),n.preload=e,e.addEventListener("load",function(){return n.loading|=1}),e.addEventListener("error",function(){return n.loading|=2}),Pt(e,"link",l),Zt(e),t.head.appendChild(e))}function la(t){return'[src="'+_e(t)+'"]'}function au(t){return"script[async]"+t}function Nh(t,e,l){if(e.count++,e.instance===null)switch(e.type){case"style":var n=t.querySelector('style[data-href~="'+_e(l.href)+'"]');if(n)return e.instance=n,Zt(n),n;var u=p({},l,{"data-href":l.href,"data-precedence":l.precedence,href:null,precedence:null});return n=(t.ownerDocument||t).createElement("style"),Zt(n),Pt(n,"style",u),Ai(n,l.precedence,t),e.instance=n;case"stylesheet":u=ea(l.href);var i=t.querySelector(nu(u));if(i)return e.state.loading|=4,e.instance=i,Zt(i),i;n=Lh(l),(u=Ce.get(u))&&of(n,u),i=(t.ownerDocument||t).createElement("link"),Zt(i);var o=i;return o._p=new Promise(function(v,_){o.onload=v,o.onerror=_}),Pt(i,"link",n),e.state.loading|=4,Ai(i,l.precedence,t),e.instance=i;case"script":return i=la(l.src),(u=t.querySelector(au(i)))?(e.instance=u,Zt(u),u):(n=l,(u=Ce.get(i))&&(n=p({},l),rf(n,u)),t=t.ownerDocument||t,u=t.createElement("script"),Zt(u),Pt(u,"link",n),t.head.appendChild(u),e.instance=u);case"void":return null;default:throw Error(f(443,e.type))}else e.type==="stylesheet"&&(e.state.loading&4)===0&&(n=e.instance,e.state.loading|=4,Ai(n,l.precedence,t));return e.instance}function Ai(t,e,l){for(var n=l.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),u=n.length?n[n.length-1]:null,i=u,o=0;o title"):null)}function Hv(t,e,l){if(l===1||e.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof e.precedence!="string"||typeof e.href!="string"||e.href==="")break;return!0;case"link":if(typeof e.rel!="string"||typeof e.href!="string"||e.href===""||e.onLoad||e.onError)break;return e.rel==="stylesheet"?(t=e.disabled,typeof e.precedence=="string"&&t==null):!0;case"script":if(e.async&&typeof e.async!="function"&&typeof e.async!="symbol"&&!e.onLoad&&!e.onError&&e.src&&typeof e.src=="string")return!0}return!1}function jh(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function jv(t,e,l,n){if(l.type==="stylesheet"&&(typeof n.media!="string"||matchMedia(n.media).matches!==!1)&&(l.state.loading&4)===0){if(l.instance===null){var u=ea(n.href),i=e.querySelector(nu(u));if(i){e=i._p,e!==null&&typeof e=="object"&&typeof e.then=="function"&&(t.count++,t=Oi.bind(t),e.then(t,t)),l.state.loading|=4,l.instance=i,Zt(i);return}i=e.ownerDocument||e,n=Lh(n),(u=Ce.get(u))&&of(n,u),i=i.createElement("link"),Zt(i);var o=i;o._p=new Promise(function(v,_){o.onload=v,o.onerror=_}),Pt(i,"link",n),l.instance=i}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(l,e),(e=l.state.preload)&&(l.state.loading&3)===0&&(t.count++,l=Oi.bind(t),e.addEventListener("load",l),e.addEventListener("error",l))}}var df=0;function qv(t,e){return t.stylesheets&&t.count===0&&Ci(t,t.stylesheets),0df?50:800)+e);return t.unsuspend=l,function(){t.unsuspend=null,clearTimeout(n),clearTimeout(u)}}:null}function Oi(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Ci(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var Mi=null;function Ci(t,e){t.stylesheets=null,t.unsuspend!==null&&(t.count++,Mi=new Map,e.forEach(wv,t),Mi=null,Oi.call(t))}function wv(t,e){if(!(e.state.loading&4)){var l=Mi.get(t);if(l)var n=l.get(null);else{l=new Map,Mi.set(t,l);for(var u=t.querySelectorAll("link[data-precedence],style[data-precedence]"),i=0;i"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(a)}catch(c){console.error(c)}}return a(),_f.exports=lg(),_f.exports}var ag=ng();const ug=!1;var cm=at.use,Ym=at.useLayoutEffect;function ig(a,c,s){at.useEffect(()=>{if(!a.current||s||typeof IntersectionObserver!="function")return()=>c();const f=new IntersectionObserver(r=>{c(r.pop())},{rootMargin:"100px"});return f.observe(a.current),()=>{f.disconnect(),c()}},[c,s,a])}function cg(a){const c=at.useRef(null);return at.useImperativeHandle(a,()=>c.current,[]),c}function mu(a){return a[a.length-1]}function sg(a){return typeof a=="function"}function ra(a,c){return sg(a)?a(c):a}const Gm=Object.prototype.hasOwnProperty,fg=Object.prototype.propertyIsEnumerable;function Xm(a){for(const c in a)if(Gm.call(a,c))return!0;return!1}const og=()=>Object.create(null),dn=(a,c)=>mn(a,c,og);function mn(a,c,s=()=>({}),f=0){if(a===c)return a;if(f>500)return c;const r=c,h=om(a)&&om(r);if(!h&&!(Ki(a)&&Ki(r)))return r;const g=h?a:sm(a);if(!g)return r;const m=h?r:sm(r);if(!m)return r;const y=g.length,d=m.length,S=h?new Array(d):s();let p=0;for(let b=0;b"u")return!0;const s=c.prototype;return!(!fm(s)||!s.hasOwnProperty("isPrototypeOf"))}function fm(a){return Object.prototype.toString.call(a)==="[object Object]"}function om(a){return Array.isArray(a)&&a.length===Object.keys(a).length}function Yl(a,c,s){if(a===c)return!0;if(typeof a!=typeof c)return!1;if(Array.isArray(a)&&Array.isArray(c)){if(a.length!==c.length)return!1;for(let f=0,r=a.length;fr||!Yl(a[g],c[g],s)))return!1;return r===h}return!1}function rg(a){return typeof a?.message!="string"?!1:a.message.startsWith("Failed to fetch dynamically imported module")||a.message.startsWith("error loading dynamically imported module")||a.message.startsWith("Importing a module script failed")}const dg=/[\x00-\x1f\x7f"<>`{}]/g;function hg(a){return a.replace(dg,c=>"%"+c.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0"))}function rm(a){let c;try{c=decodeURI(a)}catch{c=a.replaceAll(/%[0-9A-F]{2}/gi,s=>{try{return decodeURI(s)}catch{return s}})}return hg(c)}const mg=["http:","https:","mailto:","tel:"];function Ji(a,c){if(!a)return!1;try{const s=new URL(a);return!c.has(s.protocol)}catch{return!1}}function ru(a){if(!a)return{path:a,handledProtocolRelativeURL:!1};if(!/[%\\\x00-\x1f\x7f]/.test(a)&&!a.startsWith("//"))return{path:a,handledProtocolRelativeURL:!1};const c=/%25|%5C/gi;let s=0,f="",r;for(;(r=c.exec(a))!==null;)f+=rm(a.slice(s,r.index))+r[0],s=c.lastIndex;f=f+rm(s?a.slice(s):a);let h=!1;return f.startsWith("//")&&(h=!0,f="/"+f.replace(/^\/+/,"")),{path:f,handledProtocolRelativeURL:h}}function yg(a){return/\s|[^\u0000-\u007F]/.test(a)?a.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):a}function vg(a,c){if(a===c)return!0;if(a.length!==c.length)return!1;for(let s=0;s{h.next&&(h.prev?(h.prev.next=h.next,h.next.prev=h.prev,h.next=void 0,f&&(f.next=h,h.prev=f)):(h.next.prev=void 0,s=h.next,h.next=void 0,f&&(h.prev=f,f.next=h)),f=h)};return{get(h){const g=c.get(h);if(g)return r(g),g.value},set(h,g){if(c.size>=a&&s){const y=s;c.delete(y.key),y.next&&(s=y.next,y.next.prev=void 0),y===f&&(f=void 0)}const m=c.get(h);if(m)m.value=g,r(m);else{const y={key:h,value:g,prev:f};f&&(f.next=y),f=y,s||(s=y),c.set(h,y)}},clear(){c.clear(),s=void 0,f=void 0}}}const wl=4,Qm=5;function gg(a){const c=a.indexOf("{");if(c===-1)return null;const s=a.indexOf("}",c);return s===-1||c+1>=a.length?null:[c,s]}function Vm(a,c,s=new Uint16Array(6)){const f=a.indexOf("/",c),r=f===-1?a.length:f,h=a.substring(c,r);if(!h||!h.includes("$"))return s[0]=0,s[1]=c,s[2]=c,s[3]=r,s[4]=r,s[5]=r,s;if(h==="$"){const m=a.length;return s[0]=2,s[1]=c,s[2]=c,s[3]=m,s[4]=m,s[5]=m,s}if(h.charCodeAt(0)===36)return s[0]=1,s[1]=c,s[2]=c+1,s[3]=r,s[4]=r,s[5]=r,s;const g=gg(h);if(g){const[m,y]=g,d=h.charCodeAt(m+1);if(d===45){if(m+2!P.parse&&P.caseSensitive===G&&P.prefix===L&&P.suffix===Q);if(ct)D=ct;else{const P=pg(K,d,G,L,Q);D=P,P.parent=r,P.depth=h;let ft;K===1?ft=r.dynamic??=[]:K===3?ft=r.optional??=[]:ft=r.wildcard??=[],ft.push(P),ft.length===2&&g?.push(ft)}break}}r=D}if(T&&s.children&&!s.isRoot&&s.id&&s.id.charCodeAt(s.id.lastIndexOf("/")+1)===95){const E=ca(d);E.kind=Qm,E.parent=r,h++,E.depth=h,r.pathless??=[],r.pathless.push(E),r=E}const R=(s.path||!s.children)&&!s.isRoot;if(R&&d.endsWith("/")){const E=ca(d);E.kind=wl,E.parent=r,h++,E.depth=h,r.index=E,r=E}r.parse=T??null,r.priority=S?.params?.priority??0,R&&!r.route&&(r.route=s,r.fullPath=d)}if(s.children)for(const d of s.children)ec(a,c,d,y,r,h,g,m)}function Zm(a,c){if(a.parse&&!c.parse)return-1;if(!a.parse&&c.parse)return 1;if(a.parse&&c.parse&&(a.priority||c.priority))return c.priority-a.priority;if(a.prefix&&c.prefix&&a.prefix!==c.prefix){if(a.prefix.startsWith(c.prefix))return-1;if(c.prefix.startsWith(a.prefix))return 1}if(a.suffix&&c.suffix&&a.suffix!==c.suffix){if(a.suffix.endsWith(c.suffix))return-1;if(c.suffix.endsWith(a.suffix))return 1}return a.prefix&&!c.prefix?-1:!a.prefix&&c.prefix?1:a.suffix&&!c.suffix?-1:!a.suffix&&c.suffix?1:a.caseSensitive&&!c.caseSensitive?-1:!a.caseSensitive&&c.caseSensitive?1:0}function ca(a){return{kind:0,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:a,parent:null,parse:null,priority:0}}function pg(a,c,s,f,r){return{kind:a,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:c,parent:null,parse:null,priority:0,caseSensitive:s,prefix:f,suffix:r}}function Sg(a,c){const s=ca("/"),f=new Uint16Array(6),r=[];for(const h of a)ec(!1,f,h,1,s,0,r);for(const h of r)h.sort(Zm);c.masksTree=s,c.flatCache=ki(1e3)}function bg(a,c){a||="/";const s=c.flatCache.get(a);if(s)return s;const f=Qf(a,c.masksTree);return c.flatCache.set(a,f),f}function _g(a,c,s,f,r){a||="/",f||="/";const h=c?`case\0${a}`:a;let g=r.singleCache.get(h);return g||(g=ca("/"),ec(c,new Uint16Array(6),{from:a},1,g,0),r.singleCache.set(h,g)),Qf(f,g,s)}function Eg(a,c,s=!1){const f=s?a:`nofuzz\0${a}`,r=c.matchCache.get(f);if(r!==void 0)return r;a||="/";let h;try{h=Qf(a,c.segmentTree,s)}catch(g){if(g instanceof URIError)h=null;else throw g}return h&&(h.branch=Jm(h.route)),c.matchCache.set(f,h),h}function Tg(a){return a==="/"?a:a.replace(/\/{1,}$/,"")}function zg(a,c=!1,s){const f=ca(a.fullPath),r=new Uint16Array(6),h=[],g={},m={};let y=0;ec(c,r,a,1,f,0,h,d=>{if(s?.(d,y),d.id in g&&Xf(),g[d.id]=d,y!==0&&d.path){const S=Tg(d.fullPath);(!m[S]||d.fullPath.endsWith("/"))&&(m[S]=d)}y++});for(const d of h)d.sort(Zm);return{processedTree:{segmentTree:f,singleCache:ki(1e3),matchCache:ki(1e3),flatCache:null,masksTree:null},routesById:g,routesByPath:m}}function Qf(a,c,s=!1){const f=a.split("/"),r=Rg(a,f,c,s);if(!r)return null;const[h]=Km(a,f,r);return{route:r.node.route,rawParams:h}}function Km(a,c,s){const f=Ag(s.node);let r=null;const h=Object.create(null);let g=s.extract?.part??0,m=s.extract?.node??0,y=s.extract?.path??0,d=s.extract?.segment??0;for(;m=0;G--){const L=p.wildcard[G],{prefix:Q,suffix:J}=L;if(!(Q&&(K||!(L.caseSensitive?X:et??=X.toLowerCase()).startsWith(Q)))){if(J){if(K)continue;const ct=c.slice(b).join("/").slice(-J.length);if((L.caseSensitive?ct:ct.toLowerCase())!==J)continue}m.push({node:L,index:g,skipped:T,statics:R,dynamics:E,optionals:D,extract:w,rawParams:Y})}}if(p.optional){const G=T|1<=0;L--){const Q=p.optional[L];m.push({node:Q,index:b,skipped:G,statics:R,dynamics:E,optionals:D,extract:w,rawParams:Y})}if(!K)for(let L=p.optional.length-1;L>=0;L--){const Q=p.optional[L],{prefix:J,suffix:ct}=Q;if(J||ct){const P=Q.caseSensitive?X:et??=X.toLowerCase();if(J&&!P.startsWith(J)||ct&&!P.endsWith(ct))continue}m.push({node:Q,index:b+1,skipped:T,statics:R,dynamics:E,optionals:D+ji(g,b),extract:w,rawParams:Y})}}if(!K&&p.dynamic&&X)for(let G=p.dynamic.length-1;G>=0;G--){const L=p.dynamic[G],{prefix:Q,suffix:J}=L;if(Q||J){const ct=L.caseSensitive?X:et??=X.toLowerCase();if(Q&&!ct.startsWith(Q)||J&&!ct.endsWith(J))continue}m.push({node:L,index:b+1,skipped:T,statics:R,dynamics:E+ji(g,b),optionals:D,extract:w,rawParams:Y})}if(!K&&p.staticInsensitive){const G=p.staticInsensitive.get(et??=X.toLowerCase());G&&m.push({node:G,index:b+1,skipped:T,statics:R+ji(g,b),dynamics:E,optionals:D,extract:w,rawParams:Y})}if(!K&&p.static){const G=p.static.get(X);G&&m.push({node:G,index:b+1,skipped:T,statics:R+ji(g,b),dynamics:E,optionals:D,extract:w,rawParams:Y})}if(p.pathless)for(let G=p.pathless.length-1;G>=0;G--){const L=p.pathless[G];m.push({node:L,index:b,skipped:T,statics:R,dynamics:E,optionals:D,extract:w,rawParams:Y})}}if(d)return d;if(f&&y){let S=y.index;for(let b=0;ba.statics||c.statics===a.statics&&(c.dynamics>a.dynamics||c.dynamics===a.dynamics&&(c.optionals>a.optionals||c.optionals===a.optionals&&((c.node.kind===wl)>(a.node.kind===wl)||c.node.kind===wl==(a.node.kind===wl)&&c.node.depth>a.node.depth))):!0}function Gi(a){return Vf(a.filter(c=>c!==void 0).join("/"))}function Vf(a){return a.replace(/\/{2,}/g,"/")}function km(a){return a==="/"?a:a.replace(/^\/{1,}/,"")}function rl(a){const c=a.length;return c>1&&a[c-1]==="/"?a.replace(/\/{1,}$/,""):a}function Wm(a){return rl(km(a))}function Wi(a,c){return a?.endsWith("/")&&a!=="/"&&a!==`${c}/`?a.slice(0,-1):a}function Mg(a,c,s){return Wi(a,s)===Wi(c,s)}function Cg({base:a,to:c,trailingSlash:s="never",cache:f}){const r=c===".",h=c.startsWith("/");let g;if(f){g=h?c:r?a:a+"\0"+c;const d=f.get(g);if(d)return d}let m;if(r)m=a.split("/");else if(h)m=c.split("/");else{for(m=a.split("/");m.length>1&&mu(m)==="";)m.pop();const d=c.split("/");for(let S=0,p=d.length;S1?m.pop():m=[""]:b==="."||m.push(b)}}m.length>1&&(mu(m)===""?s==="never"&&m.pop():s==="always"&&m.push(""));const y=Vf(m.join("/"))||"/";return g&&f&&f.set(g,y),y}function xg(a){const c=new Map(a.map(r=>[encodeURIComponent(r),r])),s=Array.from(c.keys()).map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),f=new RegExp(s,"g");return r=>r.replace(f,h=>c.get(h)??h)}function Af(a,c,s){const f=c[a];return typeof f!="string"?f:a==="_splat"?/^[a-zA-Z0-9\-._~!/]*$/.test(f)?f:f.split("/").map(r=>mm(r,s)).join("/"):mm(f,s)}function hm({path:a,params:c,decoder:s,...f}){let r=!1;const h=Object.create(null);if(!a||a==="/")return{interpolatedPath:"/",usedParams:h,isMissingParams:r};if(!a.includes("$"))return{interpolatedPath:a,usedParams:h,isMissingParams:r};const g=a.length;let m=0,y,d="";for(;ma.state.__TSR_key||a.href;function Hg(a){const c=a.getAttribute(ym);if(c)return`[${ym}="${c}"]`;let s="",f=a,r;for(;r=f.parentNode;){let h=1,g=f;for(;g=g.previousElementSibling;)h++;const m=`${f.localName}:nth-child(${h})`;s=s?`${m} > ${s}`:m,f=r}return s}let wi=!1;const Xi="window";function Nf(a){try{return typeof a=="function"?a():document.querySelector(a)}catch{}}function vm(a){const c=new Set;for(const s of a){if(s===Xi)continue;const f=Nf(s);f&&c.add(f)}return c}function jg(a,c){const s=a.options.scrollRestoration,f=a._scroll;s&&(f.restoring=!0);const r=a.options.getScrollRestorationKey||Bg,h=new Set,g=m=>{const y=ua[m]||={};for(const d of h)d===document?y[Xi]={scrollX,scrollY}:d.isConnected&&(y[Hg(d)]={scrollX:d.scrollLeft,scrollY:d.scrollTop})};s&&!f.restoration&&(f.restoration=!0,wi=!1,history.scrollRestoration="manual",document.addEventListener("scroll",m=>{wi||h.add(m.target)},!0),a.subscribe("onBeforeLoad",m=>{m.fromLocation&&g(r(m.fromLocation)),h.clear()}),addEventListener("pagehide",()=>{g(r(a.stores.resolvedLocation.get()??a.stores.location.get())),Ng()})),!f.reset&&(f.reset=!0,a.subscribe("onRendered",m=>{const y=a.options.scrollRestorationBehavior,d=a.options.scrollToTopSelectors,S=f.next,p=f.hash;let b;if(h.clear(),f.next=!0,f.hash=!1,typeof a.options.scrollRestoration=="function"&&!a.options.scrollRestoration({location:a.latestLocation}))return;const T=r(m.toLocation),R=m.fromLocation&&r(m.fromLocation);if(f.restoring&&R&&R!==T){const E=ua[R];if(E){let D=ua[T];for(const w in E){if(w===Xi){if(S)continue}else{const Y=Nf(w);if(!Y||S&&d&&(b??=vm(d),b.has(Y)))continue}D||(D=ua[T]={}),D[w]??=E[w]}}}wi=!0;try{const E=m.toLocation.hash,D=m.toLocation.state.__hashScrollIntoViewOptions??!0;let w=!1;if(S){!E&&d&&(b??=vm(d));const Y=E&&D&&p,K=f.restoring?ua[T]:void 0;if(K)for(const X in K){const{scrollX:et,scrollY:G}=K[X];if(X===Xi){if(Y)continue;scrollTo({top:G,left:et,behavior:y}),w=!0}else{const L=Nf(X);L&&(L.scrollLeft=et,L.scrollTop=G,b?.delete(L))}}if(!E){const X={top:0,left:0,behavior:y};if(w||scrollTo(X),b)for(const et of b)et.scrollTo(X)}}!w&&E&&D&&document.getElementById(E)?.scrollIntoView(D)}finally{wi=!1}}))}function qg(a,c=String){const s=new URLSearchParams;for(const f in a){const r=a[f];r!==void 0&&s.set(f,c(r))}return s.toString()}function Rf(a){return a?a==="false"?!1:a==="true"?!0:+a*0===0&&+a+""===a?+a:a:""}function wg(a){const c=new URLSearchParams(a),s=Object.create(null);for(const[f,r]of c.entries()){const h=s[f];h==null?s[f]=Rf(r):Array.isArray(h)?h.push(Rf(r)):s[f]=[h,Rf(r)]}return s}const Yg=/^(?:\s|["[{\d-]|fa|nu|tr)/,Gg=Qg(JSON.parse),Xg=Vg(JSON.stringify,JSON.parse);function Qg(a){return c=>{c[0]==="?"&&(c=c.substring(1));const s=wg(c);for(const f in s){const r=s[f];if(typeof r=="string")try{s[f]=a(r)}catch{}}return s}}function Vg(a,c){const s=c===JSON.parse;function f(r){if(r&&typeof r=="object")try{return a(r)}catch{}else if(c&&typeof r=="string"){if(s&&!Yg.test(r))return r;try{return c(r),a(r)}catch{}}return r}return r=>{const h=qg(r,f);return h?`?${h}`:""}}const sa="__root__";function Zg(a){if(a.statusCode=a.statusCode||a.code||307,!a._builtLocation&&!a.reloadDocument&&typeof a.href=="string")try{new URL(a.href),a.reloadDocument=!0}catch{}const c=new Headers(a.headers);a.href&&c.get("Location")===null&&c.set("Location",a.href);const s=new Response(null,{status:a.statusCode,headers:c});if(s.options=a,a.throw)throw s;return s}function Zf(a){return a instanceof Response&&!!a.options}function Kg(a){return{input:({url:c})=>{for(const s of a)c=Bf(s,c);return c},output:({url:c})=>{for(let s=a.length-1;s>=0;s--)c=$m(a[s],c);return c}}}function Jg(a){const c=Wm(a.basepath),s=`/${c}`,f=a.caseSensitive?s:s.toLowerCase(),r=`${f}/`;return{input:({url:h})=>{const g=a.caseSensitive?h.pathname:h.pathname.toLowerCase();return g===f?h.pathname="/":g.startsWith(r)&&(h.pathname=h.pathname.slice(s.length)),h},output:({url:h})=>(h.pathname=Gi(["/",c,h.pathname]),h)}}function Bf(a,c){const s=a?.input?.({url:c});if(s){if(typeof s=="string")return new URL(s);if(s instanceof URL)return s}return c}function $m(a,c){const s=a?.output?.({url:c});if(s){if(typeof s=="string")return new URL(s);if(s instanceof URL)return s}return c}function kg(a,c){const{createMutableStore:s,createReadonlyStore:f,batch:r}=c,h=new Map,g=s("idle"),m=s(a),y=s(void 0),d=s([]),S=f(()=>d.get().map(E=>h.get(E).get())),p=f(()=>({status:g.get(),isLoading:g.get()==="pending",matches:S.get(),location:m.get(),resolvedLocation:y.get()}));function b(E){let D=h.get(E);return D||(D=s(void 0),h.set(E,D)),D}const T={status:g,location:m,resolvedLocation:y,ids:d,matches:S,byRoute:h,__store:p,getMatchStore:b,setMatches:R};function R(E){const D=d.get(),w=E.map(Y=>Y.routeId);r(()=>{vg(D,w)||d.set(w);for(const Y of D)w.includes(Y)||h.get(Y).set(()=>{});for(const Y of E){const K=b(Y.routeId);K.get()!==Y&&K.set(Y)}})}return T}var Gl="__TSR_index",gm="popstate",pm="beforeunload";function Wg(a){let c=a.getLocation();const s=new Set,f=g=>{c=a.getLocation(),s.forEach(m=>m({location:c,action:g}))},r=g=>{a.notifyOnIndexChange??!0?f(g):c=a.getLocation()},h=async({task:g,navigateOpts:m,...y})=>{if(m?.ignoreBlocker??!1){g();return}const d=a.getBlockers?.()??[],S=y.type==="PUSH"||y.type==="REPLACE";if(typeof document<"u"&&d.length&&S)for(const p of d){const b=Fi(y.path,y.state);if(await p.blockerFn({currentLocation:c,nextLocation:b,action:y.type})){a.onBlocked?.();return}}g()};return{get location(){return c},get length(){return a.getLength()},subscribers:s,subscribe:g=>(s.add(g),()=>{s.delete(g)}),push:(g,m,y)=>{const d=c.state[Gl];m=Sm(d+1,m),h({task:()=>{a.pushState(g,m),f({type:"PUSH"})},navigateOpts:y,type:"PUSH",path:g,state:m})},replace:(g,m,y)=>{const d=c.state[Gl];m=Sm(d,m),h({task:()=>{a.replaceState(g,m),f({type:"REPLACE"})},navigateOpts:y,type:"REPLACE",path:g,state:m})},go:(g,m)=>{h({task:()=>{a.go(g),r({type:"GO",index:g})},navigateOpts:m,type:"GO"})},back:g=>{h({task:()=>{a.back(g?.ignoreBlocker??!1),r({type:"BACK"})},navigateOpts:g,type:"BACK"})},forward:g=>{h({task:()=>{a.forward(g?.ignoreBlocker??!1),r({type:"FORWARD"})},navigateOpts:g,type:"FORWARD"})},canGoBack:()=>c.state[Gl]!==0,createHref:g=>a.createHref(g),block:g=>{if(!a.setBlockers)return()=>{};const m=a.getBlockers?.()??[];return a.setBlockers([...m,g]),()=>{const y=a.getBlockers?.()??[];a.setBlockers?.(y.filter(d=>d!==g))}},flush:()=>a.flush?.(),destroy:()=>a.destroy?.(),notify:f}}function Sm(a,c){c||(c={});const s=Kf();return{...c,key:s,__TSR_key:s,[Gl]:a}}function Fg(a){const c=typeof document<"u"?window:void 0,s=c.history.pushState,f=c.history.replaceState;let r=[];const h=()=>r,g=L=>r=L,m=(L=>L),y=(()=>Fi(`${c.location.pathname}${c.location.search}${c.location.hash}`,c.history.state));if(!c.history.state?.__TSR_key&&!c.history.state?.key){const L=Kf();c.history.replaceState({[Gl]:0,key:L,__TSR_key:L},"")}let d=y(),S,p=!1,b=!1,T=!1,R=!1;const E=()=>d;let D;const w=()=>{D&&(G._ignoreSubscribers=!0,(D[2]?c.history.pushState:c.history.replaceState)(D[1],"",D[0]),G._ignoreSubscribers=!1,D=void 0,S=void 0)},Y=(L,Q,J)=>{const ct=m(Q),P=!!D;P||(S=d),d=Fi(Q,J),D=[ct,J,D?.[2]||L],P||queueMicrotask(()=>w())},K=L=>{d=y(),G.notify({type:L})},X=async()=>{if(b){b=!1;return}const L=y(),Q=L.state[Gl]-d.state[Gl],J=Q===1,ct=Q===-1,P=!J&&!ct||p;p=!1;const ft=P?"GO":ct?"BACK":"FORWARD",bt=P?{type:"GO",index:Q}:{type:ct?"BACK":"FORWARD"};if(T)T=!1;else{const ee=h();if(typeof document<"u"&&ee.length){for(const Bt of ee)if(await Bt.blockerFn({currentLocation:d,nextLocation:L,action:ft})){b=!0,c.history.go(1),G.notify(bt);return}}}d=y(),G.notify(bt)},et=L=>{if(R){R=!1;return}let Q=!1;const J=h();if(typeof document<"u"&&J.length)for(const ct of J){const P=ct.enableBeforeUnload??!0;if(P===!0){Q=!0;break}if(typeof P=="function"&&P()===!0){Q=!0;break}}if(Q)return L.preventDefault(),L.returnValue=""},G=Wg({getLocation:E,getLength:()=>c.history.length,pushState:(L,Q)=>Y(!0,L,Q),replaceState:(L,Q)=>Y(!1,L,Q),back:L=>(L&&(T=!0),R=!0,c.history.back()),forward:L=>{L&&(T=!0),R=!0,c.history.forward()},go:L=>{p=!0,c.history.go(L)},createHref:L=>m(L),flush:w,destroy:()=>{c.history.pushState=s,c.history.replaceState=f,c.removeEventListener(pm,et,{capture:!0}),c.removeEventListener(gm,X)},onBlocked:()=>{S&&d!==S&&(d=S)},getBlockers:h,setBlockers:g,notifyOnIndexChange:!1});return c.addEventListener(pm,et,{capture:!0}),c.addEventListener(gm,X),c.history.pushState=function(...L){const Q=s.apply(c.history,L);return G._ignoreSubscribers||K("PUSH"),Q},c.history.replaceState=function(...L){const Q=f.apply(c.history,L);return G._ignoreSubscribers||K("REPLACE"),Q},G}function $g(a){let c=a.replace(/[\x00-\x1f\x7f]/g,"");return c.startsWith("//")&&(c="/"+c.replace(/^\/+/,"")),c}function Fi(a,c){const s=$g(a),f=s.indexOf("#"),r=s.indexOf("?"),h=Kf();return{href:s,pathname:s.substring(0,f>0?r>0?Math.min(f,r):f:r>0?r:s.length),hash:f>-1?s.substring(f):"",search:r>-1?s.slice(r,f===-1?void 0:f):"",state:c||{[Gl]:0,key:h,__TSR_key:h}}}function Kf(){return(Math.random()+1).toString(36).substring(7)}function bm(a){return a.options.loader||a.options.beforeLoad||a.lazyFn||a.options.component?.preload||a.options.pendingComponent?.preload}function lc(a,c){return{fromLocation:c,toLocation:a,pathChanged:c?.pathname!==a.pathname,hrefChanged:c?.href!==a.href,hashChanged:c?.hash!==a.hash}}function _m({key:a,__TSR_key:c,__TSR_index:s,__hashScrollIntoViewOptions:f,...r}){return r}function Pg(a,c,s,f){for(const r of c){if(f?.()===!1)return;s.some(h=>h.routeId===r.routeId)||a.routesById[r.routeId].options.onLeave?.(r)}for(const r of s){if(f?.()===!1)return;a.routesById[r.routeId].options[c.some(h=>h.routeId===r.routeId)?"onStay":"onEnter"]?.(r)}}var Ig=class{constructor(a,c){this.tempLocationKey=`${Math.round(Math.random()*1e7)}`,this._scroll={next:!0},this.subscribers=new Set,this._cache=new Map,this._committed=[],this.routeBranchCache=new WeakMap,this.lightweightCache=new WeakMap,this.startTransition=async s=>(s(),!1),this.update=s=>{const f=this.options,r=this.basepath??f?.basepath??"/",h=this.basepath===void 0,g=f?.rewrite;if(this.options={...f,...s},this.isServer=this.options.isServer??ug??typeof document>"u",this.protocolAllowlist=new Set(this.options.protocolAllowlist),this.options.pathParamsAllowedCharacters&&(this.pathParamsDecoder=xg(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.options.history?this.history=this.options.history:this.history=Fg()),this.origin=this.options.origin,this.origin||(window?.origin&&window.origin!=="null"?this.origin=window.origin:this.origin="http://localhost"),this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree){this.routeTree=this.options.routeTree;let d;this.resolvePathCache=ki(1e3),d=this.buildRouteTree(),this.setRoutes(d)}if(!this.stores&&this.latestLocation){const d=this.getStoreConfig(this);this.batch=d.batch,this.stores=kg(this.latestLocation,d),jg(this)}const m=this.options.basepath??"/",y=this.options.rewrite;if(h||r!==m||g!==y){this.basepath=m;const d=[],S=Wm(m);S&&S!=="/"&&d.push(Jg({basepath:m})),y&&d.push(y),this.rewrite=d.length===0?void 0:d.length===1?d[0]:Kg(d),this.history&&this.updateLatestLocation(),this.stores&&this.stores.location.set(this.latestLocation)}},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{const s=zg(this.routeTree,this.options.caseSensitive,(f,r)=>{f.init({originalIndex:r})});return this.options.routeMasks&&Sg(this.options.routeMasks,s.processedTree),s},this.subscribe=(s,f)=>{const r={eventType:s,fn:f};return this.subscribers.add(r),()=>{this.subscribers.delete(r)}},this.emit=s=>{for(const f of this.subscribers)if(f.eventType===s.type)try{f.fn(s)}catch(r){console.error(r)}},this.parseLocation=(s,f)=>{const r=({pathname:y,search:d,hash:S,href:p,state:b})=>{if(!this.rewrite&&!/[ \x00-\x1f\x7f\u0080-\uffff]/.test(y)){const w=this.options.parseSearch(d),Y=this.options.stringifySearch(w);return{href:y+Y+S,publicHref:y+Y+S,pathname:ru(y).path,external:!1,searchStr:Y,search:dn(f?.search,w),hash:ru(S.slice(1)).path,state:mn(f?.state,b)}}const T=new URL(p,this.origin),R=Bf(this.rewrite,T),E=this.options.parseSearch(R.search),D=this.options.stringifySearch(E);return R.search=D,{href:R.href.replace(R.origin,""),publicHref:p,pathname:ru(R.pathname).path,external:!!this.rewrite&&R.origin!==this.origin,searchStr:D,search:dn(f?.search,E),hash:ru(R.hash.slice(1)).path,state:mn(f?.state,b)}},h=r(s),{__tempLocation:g,__tempKey:m}=h.state;if(g&&(!m||m===this.tempLocationKey)){const y=r(g);return y.state.key=h.state.key,y.state.__TSR_key=h.state.__TSR_key,delete y.state.__tempLocation,{...y,maskedLocation:h}}return h},this.resolvePathWithBase=(s,f)=>Cg({base:s,to:f.includes("//")?Vf(f):f,trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(s,f,r)=>typeof s=="string"?this.matchRoutesInternal({pathname:s,search:f},r):this.matchRoutesInternal(s,f),this.getMatchedRoutes=s=>{const f=Object.create(null),r=Eg(rl(s),this.processedTree,!0);return r&&Object.assign(f,r.rawParams),[r?.branch||[this.routesById.__root__],f,r?.route]},this.buildLocation=s=>{const f=(h={})=>{const g=h._fromLocation||this._pendingLocation||this.latestLocation,m=this.matchRoutesLightweight(g);h.from;const y=h.unsafeRelative==="path"?g.pathname:h.from??m[1],d=h.to?`${h.to}`:void 0,S=m[2],p=Object.assign(Object.create(null),m[3]),b=d?.charCodeAt(0)===47?"/":this.resolvePathWithBase(y,"."),T=d?this.resolvePathWithBase(b,d):b,R=Em(h.params,p),E=this.routesByPath[rl(T)];let D;if(E)D=this.getRouteBranch(E);else if(T.includes("$"))D=[];else{const[P,ft,bt]=this.getMatchedRoutes(T);D=P,this.options.notFoundRoute&&(!bt||bt.path!=="/"&&ft["**"])&&(D=[...D,this.options.notFoundRoute])}if(D.length&&Xm(R))for(const P of D){const ft=P.options.params?.stringify??P.options.stringifyParams;if(ft)try{Object.assign(R,ft(R))}catch{}}const w=s.leaveParams?T:ru(hm({path:T,params:R,decoder:this.pathParamsDecoder,server:this.isServer}).interpolatedPath).path;let Y=S;if(s._includeValidateSearch&&this.options.search?.strict){const P={};D.forEach(ft=>{if(ft.options.validateSearch)try{Object.assign(P,Qi(ft.options.validateSearch,{...P,...Y}))}catch{}}),Y=P}Y=ep(Y,h,D,s._includeValidateSearch),Y=dn(S,Y);const K=this.options.stringifySearch(Y),X=h.hash===!0?g.hash:h.hash?ra(h.hash,g.hash):void 0,et=X?`#${X}`:"";let G=h.state===!0?g.state:h.state?ra(h.state,g.state):{};G=mn(g.state,G);const L=`${w}${K}${et}`;let Q,J,ct=!1;if(this.rewrite){const P=new URL(L,this.origin),ft=$m(this.rewrite,P);Q=P.href.replace(P.origin,""),ft.origin!==this.origin?(J=ft.href,ct=!0):J=ft.pathname+ft.search+ft.hash}else Q=yg(L),J=Q;return{publicHref:J,href:Q,pathname:w,search:Y,searchStr:K,state:G,hash:X??"",external:ct,unmaskOnReload:h.unmaskOnReload}},r=(h={},g)=>{const m=f(h);let y=g?f(g):void 0;if(!y){const d=Object.create(null);if(this.options.routeMasks){const S=bg(m.pathname,this.processedTree);if(S){Object.assign(d,S.rawParams);const{from:p,params:b,...T}=S.route,R=Em(b,d);g={from:s.from,...T,params:R},y=f(g)}}}return y&&(m.maskedLocation=y),m};return s.mask?r(s,{from:s.from,...s.mask}):r(s)},this.commitLocation=async({viewTransition:s,ignoreBlocker:f,...r})=>{let h;const g=rl(this.latestLocation.href)===rl(r.href)&&Yl(_m(r.state),_m(this.latestLocation.state)),m=this._commitPromise;let y;const d=new Promise(S=>{y=S});if(d.resolve=()=>{y(),m?.resolve()},this._commitPromise=d,g)this.load();else{let{maskedLocation:S,hashScrollIntoView:p,...b}=r;S&&(b={...S,state:{...S.state,__tempKey:void 0,__tempLocation:{...b,search:b.searchStr,state:{...b.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(b.unmaskOnReload??this.options.unmaskOnReload??!1)&&(b.state.__tempKey=this.tempLocationKey)),b.state.__hashScrollIntoViewOptions=p??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=s,h=r.replace?"REPLACE":"PUSH",this.history[h==="REPLACE"?"replace":"push"](b.publicHref,b.state,{ignoreBlocker:f}),this.history.subscribers.size||this.load({action:{type:h}})}return this._scroll.next=r.resetScroll??!0,this._commitPromise},this.buildAndCommitLocation=({replace:s,resetScroll:f,hashScrollIntoView:r,viewTransition:h,ignoreBlocker:g,_redirects:m,href:y,...d}={})=>{if(y){const b=this.history.location.state.__TSR_index,T=Fi(y,{__TSR_index:s?b:b+1}),R=new URL(T.pathname,this.origin);d.to=Bf(this.rewrite,R).pathname,d.search=this.options.parseSearch(T.search),d.hash=T.hash.slice(1)}const S=this.buildLocation({...d,_includeValidateSearch:!0});m&&(S._redirects=m),this._pendingLocation=S;const p=this.commitLocation({...S,viewTransition:h,replace:s,resetScroll:f,hashScrollIntoView:r,ignoreBlocker:g});return queueMicrotask(()=>{this._pendingLocation===S&&(this._pendingLocation=void 0)}),p},this.navigate=async({to:s,reloadDocument:f,href:r,publicHref:h,...g})=>{let m=!1;if(r)try{new URL(`${r}`),m=!0}catch{}if(m&&!f&&(f=!0),f){if(s!==void 0||!r){const d=this.buildLocation({to:s,...g});r=r??d.publicHref,h=h??d.publicHref}const y=!m&&h?h:r;if(Ji(y,this.protocolAllowlist))return;if(!g.ignoreBlocker){const d=this.history.getBlockers?.()??[];for(const S of d)if(S?.blockerFn&&await S.blockerFn({currentLocation:this.latestLocation,nextLocation:this.latestLocation,action:"PUSH"}))return}g.replace?window.location.replace(y):window.location.href=y;return}return this.buildAndCommitLocation({...g,href:r,to:s,_isNavigate:!0})},this.load=async s=>{this.updateLatestLocation(),s?.action&&(this._scroll.hash=s.action.type==="PUSH"||s.action.type==="REPLACE"),await op(this,s)},this.startViewTransition=s=>{const f=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,f&&typeof document.startViewTransition=="function"){let r;if(typeof f=="object"&&window.CSS?.supports?.("selector(:active-view-transition-type(a))")){const h=this.latestLocation,g=this.stores.resolvedLocation.get(),m=typeof f.types=="function"?f.types(lc(h,g)):f.types;if(m===!1)return s();r={update:s,types:m}}else r=s;return document.startViewTransition(r).updateCallbackDone}return s()},this.invalidate=s=>{const f=this._committed,r=s?.filter,h=this._preloads,g=new Set([...f,...this._cache.values(),...[...h?.values()??[]].flat(),...this._tx?.[3]??[]].filter(d=>!r||r(d)).map(d=>d.id)),m=[];for(const[d,S]of h??[])S.some(p=>g.has(p.id))&&(h.delete(d),m.push(d));const y=d=>{if(g.has(d.id)){const S=this.routesById[d.routeId],p={...d,invalid:!0,...(s?.forcePending||d.status==="error"||d.status==="notFound")&&bm(S)?{status:"pending",error:void 0}:void 0};return d._flight=void 0,p}return d};this._committed=f.map(y);for(const[d,S]of this._cache)g.has(d)&&(S.invalid=!0,s?.forcePending&&(S.status="pending"));for(const d of g)this._flights?.delete(d);for(const d of m)d.abort();return this.shouldViewTransition=!1,this.load({sync:s?.sync})},this.resolveRedirect=s=>{const f=s.headers.get("Location");if(!s.options.href||s.options._builtLocation){const r=(s.options._builtLocation??this.buildLocation(s.options)).publicHref||"/";s.options.href=r,s.headers.set("Location",r)}else if(f)try{const r=new URL(f);if(this.origin&&r.origin===this.origin){const h=r.pathname+r.search+r.hash;s.options.href=h,s.headers.set("Location",h)}}catch{}if(s.options.href&&!s.options._builtLocation&&Ji(s.options.href,this.protocolAllowlist))throw new Error("Redirect blocked: unsafe protocol");return s.headers.get("Location")||s.headers.set("Location",s.options.href),s},this.clearCache=s=>{const f=this._cache,r=this._preloads,h=s?.filter,g=[],m=[];for(const[d,S]of f)(!h||h(S))&&(m.push(d),g.push(S));const y=[];for(const[d,S]of r??[])(!h||S.some(h))&&(y.push(d),g.push(...S));for(const d of m)f.delete(d);for(const d of y)r.delete(d);for(const d of g){const S=d._flight;d._flight=void 0,S&&!--S[2]&&(this._flights?.get(d.id)===S&&this._flights.delete(d.id),y.push(S[1]))}for(const d of y)d.abort()},this.loadRouteChunk=fa,this.preloadRoute=s=>s0(this,s),this.matchRoute=(s,f)=>{const r={...s,to:s.to?this.resolvePathWithBase(s.from||"",s.to):void 0,params:s.params||{},leaveParams:!0},h=this.buildLocation(r),g=this.stores.status.get()==="pending";if(f?.pending&&!g)return!1;const m=f?.pending??!g?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),y=_g(h.pathname,f?.caseSensitive??!1,f?.fuzzy??!1,m.pathname,this.processedTree);return!y||s.params&&!Yl(y.rawParams,s.params,{partial:!0})?!1:f?.includeSearch??!0?Yl(m.search,h.search,{partial:!0})?y.rawParams:!1:y.rawParams},this.getStoreConfig=c,this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...a,caseSensitive:a.caseSensitive??!1,notFoundMode:a.notFoundMode??"fuzzy",stringifySearch:a.stringifySearch??Xg,parseSearch:a.parseSearch??Gg,protocolAllowlist:a.protocolAllowlist??mg}),self.__TSR_ROUTER__=this}isShell(){return!!this.options.isShell}get state(){return this.stores.__store.get()}setRoutes({routesById:a,routesByPath:c,processedTree:s}){this.routesById=a,this.routesByPath=c,this.processedTree=s;const f=this.options.notFoundRoute;f&&(f.init({originalIndex:99999999999}),this.routesById[f.id]=f)}getRouteBranch(a){let c=this.routeBranchCache.get(a);return c||(c=Jm(a),this.routeBranchCache.set(a,c)),c}matchRoutesInternal(a,c){const[s,f,r]=this.getMatchedRoutes(a.pathname);let h=s,g=!1;(r?r.path!=="/"&&f["**"]:rl(a.pathname))&&(this.options.notFoundRoute?h=[...h,this.options.notFoundRoute]:g=!0);const m=g?lp(this.options.notFoundMode,h):void 0,y=new Array(h.length),d=this._committed,S=(b,T)=>{const R=d[T];return R?.routeId===b.id?R:b===this.options.notFoundRoute?d.find(E=>E.routeId===b.id):void 0};let p;for(let b=0;b{const b=p(m.preSearchFilters?m.preSearchFilters.reduce((T,R)=>R(T),S):S);return m.postSearchFilters?m.postSearchFilters.reduce((T,R)=>R(T),b):b};r.push(d)}const y=m.validateSearch;if(y){const d=({search:S,next:p,meta:b})=>{const T=p(S);if(f)try{const R=Qi(y,T);if(b&&R)for(const E in R)E in T||(b.defaulted||=new Map).set(E,R[E]);return{...T,...R}}catch{}return T};r.push(d)}}const h=(g,m,y)=>{if(g>=r.length){if(!c.search)return{};if(c.search===!0)return m;const S=ra(c.search,m);return y&&(y.explicit=S),S}const d=(S,p)=>{if(p){const b=y||{};return{search:h(g+1,S,b),meta:b}}return h(g+1,S,y)};return r[g]({search:m,next:d,meta:y})};return h(0,a)}function lp(a,c){if(a!=="root"){let s;for(let f=c.length-1;f>=0;f--){const r=c[f];if(r.options.notFoundComponent)return r.id;s||=r.children&&r.id}if(s)return s}return sa}function Em(a,c){return a===!1||a===null?Object.create(null):(a??!0)===!0?c:Object.assign(c,ra(a,c))}function Tm(a,c){const s=a.options.params?.parse??a.options.parseParams;s&&Object.assign(c,s(c))}function Hf(a,c){return a.options[c]?.preload?.()}function np(a,c){const s=Hf(a,"component"),f=Hf(a,"pendingComponent"),r=c&&f?f.then(c):f;return c&&!f&&c(),s&&r?Promise.all([s,r]).then(()=>{}):s??r}function fa(a,c,s){const f=()=>c===!1?void 0:c?Hf(a,c):np(a,s),r=a._lazy;if(r)return r===!0?f():r.then(f);if(!a.lazyFn)return f();const h=a.lazyFn().then(g=>{{const{id:m,...y}=g.options;Object.assign(a.options,y),a._lazy=!0}},g=>{throw a._lazy=void 0,g});return a._lazy=h,h.then(f)}function Pm(a){const c=a.findIndex(s=>s.status!=="success"||s._notFound)+1;return c&&c{const r=()=>f(c);c.addEventListener("abort",r,{once:!0}),Promise.resolve(a).then(s,f).finally(()=>c.removeEventListener("abort",r))})}function gn(a,c){return a.routesById[c.routeId]}function vu(a,c,s){return Zf(a)?[xe,a]:yn(a)?(a.routeId||=s,[nc,a]):(c&&typeof a?.then=="function"&&(a=new Error("A Promise was thrown",{cause:a})),c?[Xl,a]:[Qe,a])}function Im(a,c){let s=vu(c,!0,a.id);if(s[0]!==Xl)return s;try{a.options.onError?.(s[1])}catch(f){s=vu(f,!0,a.id)}return s}function du(a,c,s){return s[0].signal.aborted||!s[2]()?(s[0].abort(),[vn]):Im(a,c)}function t0(a,c){return s=>a.navigate({...s,_fromLocation:c})}async function ap(a,c,s,f,r,h){const[g,m]=c,y=s[0].signal,d=!!s[4];for(let S=s[7]??0;S=h&&(p.status="pending"),s[8]?.();try{gu(a,p,"beforeLoad",s[0]);const X=await Ql(w(Y),y);if(!s[2]())return s[0].abort(),[S,[vn]];const et=vu(X,!1,b.id);if(et[0]!==Qe)return dl(a,p),[S,et];p.context={...E,...X}}catch(X){return dl(a,p),[S,du(b,X,s)]}finally{K==="success"&&p.status==="pending"&&(p.status="success"),gu(a,p,!1,s[0])}}r()}function Jf(a,c,s){if(!(!s||--s[2])){if(a._flights?.get(c.id)===s){const f=a._tx;if(f&&!f[0].signal.aborted&&!f[3].includes(c)&&f[3].some(r=>r.id===c.id)&&f[3].some(r=>r.isFetching==="beforeLoad"))return;a._flights.delete(c.id)}return s[1]}}function dl(a,c){const s=c._flight;c._flight=void 0,Jf(a,c,s)?.abort()}function oe(a,c,s,f){const r=[];for(const h of c)if(!s?.includes(h)){const g=h._flight;if(h._flight=void 0,f&&g?.[2]===1&&a._flights?.get(h.id)===g&&s?.some(m=>m.id===h.id))g[2]=0;else{const m=Jf(a,h,g);m&&r.push(m)}}for(const h of r)h.abort()}function kf(a){for(const c of a){const s=c._flight;s&&s[2]++}}function gu(a,c,s,f){if(c.isFetching=s,f&&a._tx?.[0]!==f)return;const r=a.stores.byRoute.get(c.routeId),h=r?.get();h?.id===c.id&&r.set({...h,isFetching:s})}function e0(a,c,s,f,r,h,g){const m=c[0];return{params:s.params,location:m,navigate:t0(a,m),cause:g?"preload":s.cause,abortController:r,preload:g,deps:s.loaderDeps,parentMatchPromise:h,context:s.context,route:f,...a.options.additionalContext}}async function zm(a,c,s,f,r,h,g,m){const y=m.signal;if(y.aborted)return[vn];if(!r)return[Qe,void 0];let d=s._flight;gu(a,s,"loader",m);try{if(!d){const S=new AbortController;d=[Promise.resolve().then(()=>r(e0(a,c,s,f,S,h,g))).then(p=>vu(p,!1,f.id),p=>vu(p,!0,f.id)).then(p=>(p[0]!==Qe&&a._flights?.get(s.id)===d&&(a._flights.delete(s.id),d[2]||S.abort()),p[0]===Xl&&d[2]?Im(f,p[1]):p)),S,1],(a._flights??=new Map).set(s.id,d)}return s._flight=d,s.abortController=d[1],await Ql(d[0],y)}catch(S){if(S!==y)throw S;return dl(a,s),[vn]}finally{gu(a,s,!1,m)}}function Am(a,c,s){c[0]===Qe?(a.loaderData=c[1],a.error=void 0,a.status="success",a.invalid=!1,a.updatedAt=Date.now(),a.preload=s):c[0]!==xe&&(a.status="success",a.error=void 0,a.invalid=!0)}function up(a,c,s){const f=a._cache.get(c.id);if(f!==s||a._committed.some(h=>h.id===c.id&&h._flight===c._flight))return;const r={...c,_notFound:void 0,context:{}};r._flight&&r._flight[2]++,a._cache.set(c.id,r),f&&dl(a,f)}function Rm(a,c){return c[0]===Xl||c[0]===nc?{...a,status:c[0]===Xl?"error":"notFound",error:c[1],_flight:void 0}:a}function ip(a,c,s,f,r,h,g){const m=c[1][s],y=gn(a,m),d=!!h[4],S=a._cache.get(m.id);let p,b=!1,T;try{if(m.status==="success"&&(p=y.options.shouldReload,typeof p=="function"&&(p=p(e0(a,c,m,y,h[0],r,d))),h[2]()||(h[0].abort(),T=[vn])),!T)if(m.status!=="success")b=!0;else{const J=h[4]||m.preload?y.options.preloadStaleTime??a.options.defaultPreloadStaleTime??3e4:y.options.staleTime??a.options.defaultStaleTime??0;b=!!(m.invalid||p||p===void 0&&Date.now()-m.updatedAt>=J&&(h[6]||m.cause==="enter"||h[3].some(ct=>ct.routeId===m.routeId&&ct.id!==m.id)))}}catch(J){m.invalid=!0,dl(a,m),T=du(y,J,h)}const R=y.options.loader,E=typeof R=="function"?R:R?.handler;let D=(!d||y.options.preload!==!1)&&R?a._flights?.get(m.id):void 0;D===m._flight||T?D=void 0:D&&!b&&!d&&p===void 0?b=!0:b||(D=void 0);const w=!!(R&&b&&m.status==="success"&&!d&&!h[5]&&((typeof R=="function"?void 0:R?.staleReloadMode)??a.options.defaultStaleReloadMode)!=="blocking"),Y=b&&(!d||y.options.preload!==!1),K=Y&&!w&&(m.status!=="success"||!!R),X=y.lazyFn&&y._lazy!==!0?h[8]:void 0;if(Y&&!R&&(m.invalid=!1,m.updatedAt=Date.now()),D&&D[2]++,K){const J=m._flight;m._flight=D,Jf(a,m,J)?.abort(),m.status==="success"&&s>=g&&(m.status="pending"),h[8]?.()}Y||(m.isFetching=!1);const et=(T?Promise.resolve(T):K?zm(a,c,m,y,E,r,d,h[0]):Promise.resolve([Qe,m.loaderData])).then(J=>(K&&(Am(m,J,d),J[0]===Qe&&(R&&!h[0].signal.aborted&&up(a,m,S),m.status="pending")),J)),G=Ql(Promise.resolve().then(()=>fa(y,void 0,X)),h[0].signal).then(()=>{},J=>[s,du(y,J,h)]).then(J=>et.then(ct=>(K&&!J&&ct[0]===Qe&&m.status==="pending"&&h[2]()&&(m.status="success",h[8]?.()),J)));if(f.push([s,et,G]),!w)return et.then(J=>Rm(m,J));const L={...m,status:"pending",preload:!1,_flight:D};m.invalid=!1,m.isFetching="loader";const Q=zm(a,c,L,y,E,r,!1,h[0]).then(J=>(m.isFetching=!1,Am(L,J,!1),J));return(c[2]??=[]).push([s,Q,G,L]),Q.then(J=>Rm(L,J))}async function jf(a,c,s,f,r=0){const h=s?.[1][1];let g=h?.routeId?c.findIndex(m=>m.routeId===h.routeId):s?.[0]??c.length-1;g<0&&(g=0);for(let m=g;m>=0;m--){const y=gn(a,c[m]),d=fa(y,!1);if(d)try{await Ql(d,f)}catch(S){if(S===f)throw S}if(y.options.notFoundComponent)return m}return h?.routeId?g:r}function oa(a,c){c[2]&&(oe(a,c[2].map(s=>s[3])),c[2]=void 0)}async function Om(a,c,s,f){let r;try{await Promise.all(a.map(h=>h[1].then(async g=>{const m=h[0];if(!(f&&m>=await f)){if(g[0]>=xe)throw[m,g];!r&&g[0]!==Qe&&(r=[m,g],await Promise.all((s??[]).map(y=>{if(!(y[0]<=m))return y[1].then(d=>{if(d[0]===xe)throw[y[0],d]})})))}})))}catch(h){return h}return c??r}async function l0(a,c,s,f,r,h,g){const m=c[1];let y=await h,d=!1;const S=m.findIndex(R=>R._notFound),p=R=>R[1][0]===nc?jf(a,m,R,f.signal):R[0];let b=S<0?m.length:S;if((y?.[1][0]??0)>=xe)b=0;else if(y){b=y[2]??=await p(y);for(const R of s){if(R[0]>=b)break;const E=await R[1];if(E[0]!==Qe&&E[0]=b)break;const E=await R[2];if(E){y=E;break}}if((y?.[1][0]??0)>=xe){const R=y[1];if(R[0]!==xe||R[1].options.reloadDocument||r<20)return oa(a,c),R;d=!0,y=[0,[Xl,new Error("Too many redirects")]]}const T=y?y[2]??await p(y):S;if(T>=0){const R=y?.[1],E=R?.[0],D=m[T],w=R?.[1],Y=()=>{R&&(D._notFound=void 0,E===Xl?D.status="error":(w.routeId=D.routeId,D.routeId===a.routeTree.id?(D.status="success",D._notFound=!0):D.status="notFound"),D.error=w,D.isFetching=!1)};Y();const K=gn(a,D);try{await Ql(R?Promise.resolve().then(()=>fa(K,E===Xl?"errorComponent":"notFoundComponent")):Promise.all([fa(K),fa(K,"notFoundComponent")]),f.signal)}catch(X){if(X===f.signal)return oa(a,c),[vn]}R?d&&(f.abort(),await Promise.all([...s.map(X=>X[1]),...s.map(X=>X[2]),...(c[2]??[]).map(X=>X[1])]),oa(a,c),oe(a,m),Y()):(D.status="success",g?.())}return c}async function n0(a,c,s,f=0,r=c[1].length){const h=c[1];for(let g=f;gE._notFound);if(a.options.notFoundMode!=="root"&&g>=0){const E=await jf(a,r[1],void 0,f[0].signal,g);E!==g&&(s[g]._notFound=void 0,s[E]._notFound=!0),g=E}let m=g<0?s.length:g+1,y=0;for(;y{for(let E=S;E=xe&&(m=0),b()),f[2]()&&!f[4]){const E=[];for(const[D,w]of a._flights??[])w[2]||(a._flights.delete(D),E.push(w[1]));for(const D of E)D.abort()}let R;try{const E=l0(a,r,d,f[0],f[1],Om(d,T,r[2]),f[8]);r[2]?.length&&(r[3]=Om(r[2],void 0,void 0,E.then(D=>yu(D)?0:Pm(D[1]).length,()=>0))),R=await E}catch(E){throw oa(a,r),E}return yu(R)?R:n0(a,R,f[0].signal,f[7]===R[1].length?f[7]:0)}function qf(a,c){if(a._tx!==c)return;let s=a._pending,f=!1;const r=s?.[0][3][s[1]]?.id;s?.[0]!==c&&(s&&c[3][s[1]]?.id===r?(s[0]=c,f=!0):(clearTimeout(s?.[3]),a._pending=s=void 0));const h=c[3],g=a.stores.matches.get();let m=-1,y,d,S,p=!1;for(let E=0;E0){s[3]=setTimeout(()=>qf(a,c),E);return}s[2]=0}const T=h.map(E=>({...E,_flight:void 0}));T[m].status="pending";const R=a.startTransition(()=>a.stores.setMatches(T),T).then(E=>(E&&a._pending===s&&s[4]===R&&!s[2]&&(s[2]=Date.now()+d),E));s[4]=R}function Vi(a,c){const s=a._pending;s?.[0]===c&&(clearTimeout(s[3]),a._pending=void 0)}function u0(a,c){a._committed=c,a.stores.setMatches(c)}function Mm(a,c){oe(a,c[1]),oa(a,c)}function cp(a,c,s,f){const r=a._committed,h=a._cache;for(const d of s)d.preload=!1,f&&(d._assetEnd=void 0);const g=Pm(s).length,m=new Map,y=Date.now();for(const d of[...r,...h.values()]){if(d.status!=="success"||s.some((p,b)=>p.id===d.id&&(b=(d.preload?S.options.preloadGcTime??a.options.defaultPreloadGcTime??3e5:S.options.gcTime??a.options.defaultGcTime??3e5)||m.set(d.id,h.get(d.id)===d?d:{...d,_flight:void 0,isFetching:!1,context:{}})}c[3]=[],a._cache=m,u0(a,s),oe(a,[...h.values(),...r],[...s,...m.values()]),Pg(a,r,s,()=>a._tx===c)}async function hn(a,c){let s=a._tx;for(;s&&s!==c;){if(await s[5],a._tx===s)return;s=a._tx}}async function i0(a,c,s){await a.navigate({...s.options,replace:!0,ignoreBlocker:!0,_redirects:c[1]+1})}function c0(a,c){Vi(a,c),c[0].abort(),oe(a,c[3]),c[3]=[],a._tx===c&&(a.batch(()=>{a.stores.status.set("idle"),a.stores.setMatches(a._committed)}),a._tx===c&&(a._commitPromise?.resolve(),a._commitPromise=void 0))}async function sp(a,c,s,f,r){const h=s.map(d=>({...d}));kf(h);for(const d of f)dl(a,h[d[0]]),h[d[0]]=d[3];const g=[c[2],h];let m;try{m=await l0(a,g,f,c[0],c[1],r)}catch(d){throw oe(a,h),d}if(yu(m)){oe(a,h),m[0]===xe&&a._tx===c&&a._committed===s&&await i0(a,c,m[1]);return}const y=await n0(a,m,c[0].signal);if(a._tx!==c||a._committed!==s){oe(a,y[1]);return}for(const d of y[1]){const S=a._cache.get(d.id);S?._flight&&S._flight===d._flight&&(a._cache.delete(d.id),dl(a,S))}u0(a,y[1]),oe(a,s,y[1])}async function fp(a,c,s,f,r,h){const g=[c[0],c[1],()=>a._tx===c&&!!c[3].length,a._committed,void 0,r,s,h,f],m=await a0(a,c[2],c[3],g);if(yu(m)){m[0]===xe&&a._tx===c?(Vi(a,c),oe(a,c[3]),c[3]=[],a._tx===c&&await i0(a,c,m[1])):c0(a,c);return}const y=a._pending;if(y?.[0]===c&&(clearTimeout(y[3]),y[4])){const b=c[0].signal;let T=!1;try{T=await Ql(y[4],b)}catch(R){if(R!==b)throw R}if(T&&a._pending===y&&y[0]===c){const R=y[2]-Date.now();if(R>0){try{await Ql(new Promise(E=>{y[3]=setTimeout(E,R)}),b)}catch{}clearTimeout(y[3])}}}if(a._tx!==c){Vi(a,c),Mm(a,m);return}const d=c[2],S=lc(d,a.stores.resolvedLocation.get()),p=m[2];await a.startViewTransition(async()=>{if(a._tx!==c){Mm(a,m);return}const b=()=>{Vi(a,c),cp(a,c,m[1],h),a._tx===c&&(a.emit({type:"onLoad",...S}),a._tx===c&&a.emit({type:"onBeforeRouteMount",...S}))},T=await a.startTransition(b,m[1]);if(a._tx!==c){oa(a,m);return}p?.length&&sp(a,c,m[1],p,m[3]).catch(console.error),a.batch(()=>{a.stores.resolvedLocation.set(d),a.stores.status.set("idle"),a._tx===c&&a.emit({type:"onResolved",...S}),T&&a._tx===c&&a.emit({type:"onRendered",...S})}),a._tx===c&&(a._commitPromise?.resolve(),a._commitPromise=void 0)})}async function op(a,c){const s=a._tx,f=a.stores.resolvedLocation.get(),r=f??a.stores.location.get(),h=a.latestLocation,g=a._pendingLocation,m=g?.href===h.href?g._redirects??0:0,y=a._handoff,d=y?.[0](),S=new AbortController,p=a._preflight;if(a._preflight=S,d||y?.[1](),p?.abort(),S.signal.aborted){await hn(a,s);return}const b=lc(h,f);if(a.emit({type:"onBeforeNavigate",...b}),S.signal.aborted||a.emit({type:"onBeforeLoad",...b}),S.signal.aborted){await hn(a,s);return}const T=r.href===h.href;let R,E=S;try{R=a.matchRoutes(h,{_controller:S}),kf(R)}catch(Y){if(S.abort(),!Zf(Y)){await hn(a),a._commitPromise?.resolve(),a._commitPromise=void 0;return}await a.navigate({...Y.options,replace:!0,ignoreBlocker:!0}),await hn(a,s);return}const D=d?y[1](R):void 0;if(D?E=d:d?.abort(),S.signal.aborted){oe(a,R),await hn(a,s);return}a._preflight=void 0;const w=[E,m,h,R,Date.now(),Promise.resolve().then(()=>fp(a,w,T,()=>qf(a,w),c?.sync,D)).catch(()=>{a._tx===w&&c0(a,w)})];if(a._tx=w,s){for(const Y of a.stores.matches.get()){if(a._tx!==w)break;Y.isFetching&&gu(a,Y,!1)}s[0].abort(),oe(a,s[3],w[3],!0)}if(a._tx!==w){oe(a,w[3]),w[3]=[],await hn(a,w);return}a.batch(()=>{a.stores.status.set("pending"),a.stores.location.set(h)}),!f&&!R.some(Y=>Y._notFound)&&qf(a,w);try{await w[5]}finally{await hn(a,w)}}async function s0(a,c,s=0){if(s>20)return;const f=c._builtLocation??a.buildLocation(c),r=a._committed,h=new AbortController;let g;try{g=a.matchRoutes(f,{_controller:h}),kf(g)}catch(y){h.abort(),yn(y)||console.error(y);return}(a._preloads??=new Map).set(h,g);let m;try{let y;try{y=await a0(a,f,g,[h,s,()=>!0,r,!0])}finally{m=a._preloads.delete(h),oe(a,g),h.abort()}if(!yu(y))return y[1];if(m&&y[0]===xe&&!y[1].options.reloadDocument)return s0(a,{...y[1].options,_fromLocation:f},s+1)}catch(y){yn(y)||console.error(y)}}const rp="Error preloading route! ☝️";var f0=class{get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}constructor(a){if(this.init=c=>{this.originalIndex=c.originalIndex;const s=this.options,f=!s?.path&&!s?.id;this.parentRoute=this.options.getParentRoute?.(),f?this._path=sa:this.parentRoute||Xf();let r=f?sa:s?.path;r&&r!=="/"&&(r=km(r));const h=s?.id||r;let g=f?sa:Gi([this.parentRoute.id==="__root__"?"":this.parentRoute.id,h]);r==="__root__"&&(r="/"),g!=="__root__"&&(g=Gi(["/",g]));const m=g==="__root__"?"/":Gi([this.parentRoute.fullPath,r]);this._path=r,this._id=g,this._fullPath=m,this._to=rl(m)},this.addChildren=c=>this._addFileChildren(c),this._addFileChildren=c=>(Array.isArray(c)&&(this.children=c),typeof c=="object"&&c!==null&&(this.children=Object.values(c)),this),this._addFileTypes=()=>this,this.updateLoader=c=>(Object.assign(this.options,c),this),this.update=c=>(Object.assign(this.options,c),this),this.lazy=c=>(this.lazyFn=c,this),this.redirect=c=>Zg({from:this.fullPath,...c}),this.options=a||{},this.isRoot=!a?.getParentRoute,a?.id&&a?.path)throw new Error("Route cannot have both an 'id' and a 'path' option.")}},dp=class extends f0{constructor(a){super(a)}};function Wf(a){return k.jsx(hp,{...a})}var hp=class extends at.Component{constructor(...a){super(...a),this.state={error:null},this.reset=()=>{this.setState({error:null})}}static getDerivedStateFromProps(a,c){const s=a.getResetKey();return c.error&&c.resetKey!==s?{resetKey:s,error:null}:{resetKey:s}}static getDerivedStateFromError(a){return{error:a}}componentDidCatch(a,c){this.props.onCatch?.(a,c)}render(){const a=this.state.error;return a?at.createElement(this.props.errorComponent??mp,{error:a,reset:this.reset}):this.props.children}};function mp({error:a}){const[c,s]=at.useState(!1);return k.jsxs("div",{style:{padding:".5rem",maxWidth:"100%"},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:".5rem"},children:[k.jsx("strong",{style:{fontSize:"1rem"},children:"Something went wrong!"}),k.jsx("button",{style:{appearance:"none",fontSize:".6em",border:"1px solid currentColor",padding:".1rem .2rem",fontWeight:"bold",borderRadius:".25rem"},onClick:()=>s(f=>!f),children:c?"Hide Error":"Show Error"})]}),k.jsx("div",{style:{height:".25rem"}}),c?k.jsx("div",{children:k.jsx("pre",{style:{fontSize:".7em",border:"1px solid red",borderRadius:".25rem",padding:".3rem",color:"red",overflow:"auto"},children:a.message?k.jsx("code",{children:a.message}):null})}):null]})}function yp({children:a,fallback:c=null}){return k.jsx(tc.Fragment,{children:o0()?a:c})}function o0(){return tc.useSyncExternalStore(vp,()=>!0,()=>!1)}function vp(){return()=>{}}var r0=at.createContext(null);function Be(a){return at.useContext(r0)}var ac=at.createContext(void 0),gp=at.createContext(void 0),Lt=(a=>(a[a.None=0]="None",a[a.Mutable=1]="Mutable",a[a.Watching=2]="Watching",a[a.RecursedCheck=4]="RecursedCheck",a[a.Recursed=8]="Recursed",a[a.Dirty=16]="Dirty",a[a.Pending=32]="Pending",a))(Lt||{});function pp({update:a,notify:c,unwatched:s}){return{link:f,unlink:r,propagate:h,checkDirty:g,shallowPropagate:m};function f(d,S,p){const b=S.depsTail;if(b!==void 0&&b.dep===d)return;const T=b!==void 0?b.nextDep:S.deps;if(T!==void 0&&T.dep===d){T.version=p,S.depsTail=T;return}const R=d.subsTail;if(R!==void 0&&R.version===p&&R.sub===S)return;const E=S.depsTail=d.subsTail={version:p,dep:d,sub:S,prevDep:b,nextDep:T,prevSub:R,nextSub:void 0};T!==void 0&&(T.prevDep=E),b!==void 0?b.nextDep=E:S.deps=E,R!==void 0?R.nextSub=E:d.subs=E}function r(d,S=d.sub){const p=d.dep,b=d.prevDep,T=d.nextDep,R=d.nextSub,E=d.prevSub;return T!==void 0?T.prevDep=b:S.depsTail=b,b!==void 0?b.nextDep=T:S.deps=T,R!==void 0?R.prevSub=E:p.subsTail=E,E!==void 0?E.nextSub=R:(p.subs=R)===void 0&&s(p),T}function h(d){let S=d.nextSub,p;t:do{const b=d.sub;let T=b.flags;if(T&60?T&12?T&4?!(T&48)&&y(d,b)?(b.flags=T|40,T&=1):T=0:b.flags=T&-9|32:T=0:b.flags=T|32,T&2&&c(b),T&1){const R=b.subs;if(R!==void 0){const E=(d=R).nextSub;E!==void 0&&(p={value:S,prev:p},S=E);continue}}if((d=S)!==void 0){S=d.nextSub;continue}for(;p!==void 0;)if(d=p.value,p=p.prev,d!==void 0){S=d.nextSub;continue t}break}while(!0)}function g(d,S){let p,b=0,T=!1;t:do{const R=d.dep,E=R.flags;if(S.flags&16)T=!0;else if((E&17)===17){if(a(R)){const D=R.subs;D.nextSub!==void 0&&m(D),T=!0}}else if((E&33)===33){(d.nextSub!==void 0||d.prevSub!==void 0)&&(p={value:d,prev:p}),d=R.deps,S=R,++b;continue}if(!T){const D=d.nextDep;if(D!==void 0){d=D;continue}}for(;b--;){const D=S.subs,w=D.nextSub!==void 0;if(w?(d=p.value,p=p.prev):d=D,T){if(a(S)){w&&m(D),S=d.sub;continue}T=!1}else S.flags&=-33;S=d.sub;const Y=d.nextDep;if(Y!==void 0){d=Y;continue t}}return T}while(!0)}function m(d){do{const S=d.sub,p=S.flags;(p&48)===32&&(S.flags=p|16,(p&6)===2&&c(S))}while((d=d.nextSub)!==void 0)}function y(d,S){let p=S.depsTail;for(;p!==void 0;){if(p===d)return!0;p=p.prevDep}return!1}}function Sp(a,c,s){const f=typeof a=="object",r=f?a:void 0;return{next:(f?a.next:a)?.bind(r),error:(f?a.error:c)?.bind(r),complete:(f?a.complete:s)?.bind(r)}}const wf=[];let Zi=0;const{link:Cm,unlink:bp,propagate:_p,checkDirty:d0,shallowPropagate:xm}=pp({update(a){return a._update()},notify(a){wf[Yf++]=a,a.flags&=~Lt.Watching},unwatched(a){a.depsTail!==void 0&&(a.depsTail=void 0,a.flags=Lt.Mutable|Lt.Dirty,Pi(a))}});let Yi=0,Yf=0,Xe,Gf=0;function Ep(a){try{++Gf,a()}finally{--Gf||h0()}}function Pi(a){const c=a.depsTail;let s=c!==void 0?c.nextDep:a.deps;for(;s!==void 0;)s=bp(s,a)}function h0(){if(!(Gf>0)){for(;Yi{r.get(),m.current?g.next?.(r._snapshot):m.current=!0});return{unsubscribe:()=>{y.stop()}}},_update(h){const g=Xe,m=c?.compare??Object.is;if(s)Xe=r,++Zi,r.depsTail=void 0;else if(h===void 0)return!1;s&&(r.flags=Lt.Mutable|Lt.RecursedCheck);try{const y=r._snapshot,d=typeof h=="function"?h(y):h===void 0&&s?f(y):h;return y===void 0||!m(y,d)?(r._snapshot=d,!0):!1}finally{Xe=g,s&&(r.flags&=~Lt.RecursedCheck),Pi(r)}}};return s?(r.flags=Lt.Mutable|Lt.Dirty,r.get=function(){const h=r.flags;if(h&Lt.Dirty||h&Lt.Pending&&d0(r.deps,r)){if(r._update()){const g=r.subs;g!==void 0&&xm(g)}}else h&Lt.Pending&&(r.flags=h&~Lt.Pending);return Xe!==void 0&&Cm(r,Xe,Zi),r._snapshot}):r.set=function(h){if(r._update(h)){const g=r.subs;g!==void 0&&(_p(g),xm(g),h0())}},r}function Tp(a){const c=()=>{const f=Xe;Xe=s,++Zi,s.depsTail=void 0,s.flags=Lt.Watching|Lt.RecursedCheck;try{return a()}finally{Xe=f,s.flags&=~Lt.RecursedCheck,Pi(s)}},s={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:Lt.Watching|Lt.RecursedCheck,notify(){const f=this.flags;f&Lt.Dirty||f&Lt.Pending&&d0(this.deps,this)?c():this.flags=Lt.Watching},stop(){this.flags=Lt.None,this.depsTail=void 0,Pi(this)}};return c(),s}var Of={exports:{}},Mf={},Cf={exports:{}},xf={};var Um;function zp(){if(Um)return xf;Um=1;var a=pu();function c(p,b){return p===b&&(p!==0||1/p===1/b)||p!==p&&b!==b}var s=typeof Object.is=="function"?Object.is:c,f=a.useState,r=a.useEffect,h=a.useLayoutEffect,g=a.useDebugValue;function m(p,b){var T=b(),R=f({inst:{value:T,getSnapshot:b}}),E=R[0].inst,D=R[1];return h(function(){E.value=T,E.getSnapshot=b,y(E)&&D({inst:E})},[p,T,b]),r(function(){return y(E)&&D({inst:E}),p(function(){y(E)&&D({inst:E})})},[p]),g(T),T}function y(p){var b=p.getSnapshot;p=p.value;try{var T=b();return!s(p,T)}catch{return!0}}function d(p,b){return b()}var S=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:m;return xf.useSyncExternalStore=a.useSyncExternalStore!==void 0?a.useSyncExternalStore:S,xf}var Lm;function Ap(){return Lm||(Lm=1,Cf.exports=zp()),Cf.exports}var Nm;function Rp(){if(Nm)return Mf;Nm=1;var a=pu(),c=Ap();function s(d,S){return d===S&&(d!==0||1/d===1/S)||d!==d&&S!==S}var f=typeof Object.is=="function"?Object.is:s,r=c.useSyncExternalStore,h=a.useRef,g=a.useEffect,m=a.useMemo,y=a.useDebugValue;return Mf.useSyncExternalStoreWithSelector=function(d,S,p,b,T){var R=h(null);if(R.current===null){var E={hasValue:!1,value:null};R.current=E}else E=R.current;R=m(function(){function w(G){if(!Y){if(Y=!0,K=G,G=b(G),T!==void 0&&E.hasValue){var L=E.value;if(T(L,G))return X=L}return X=G}if(L=X,f(K,G))return L;var Q=b(G);return T!==void 0&&T(L,Q)?(K=G,L):(K=G,X=Q)}var Y=!1,K,X,et=p===void 0?null:p;return[function(){return w(S())},et===null?void 0:function(){return w(et())}]},[S,p,b,T]);var D=r(d,R[0],R[1]);return g(function(){E.hasValue=!0,E.value=D},[D]),y(D),D},Mf}var Bm;function Op(){return Bm||(Bm=1,Of.exports=Rp()),Of.exports}var Mp=Op();function Cp(a,c){return a===c}function Vl(a,c,s=Cp){const f=at.useCallback(g=>{if(!a)return()=>{};const{unsubscribe:m}=a.subscribe(g);return m},[a]),r=at.useCallback(()=>a?.get(),[a]);return Mp.useSyncExternalStoreWithSelector(f,r,r,c,s)}var Hm={};function xp(a,c){const s=at.useRef();return f=>{const r=a?.select?a.select(f):f;return a?.structuralSharing??c.options.defaultStructuralSharing?s.current=mn(s.current,r):r}}function pn(a){const c=Be(),s=at.useContext(a.from?gp:ac),f=a.from??s,r=c.stores.getMatchStore(f),h=xp(a,c),g=Vl(r,m=>m?h(m):Hm);if(g!==Hm)return g;(a.shouldThrow??!0)&&Xf()}function m0(a){return pn({from:a.from,strict:a.strict,structuralSharing:a.structuralSharing,select:c=>a.select?a.select(c.loaderData):c.loaderData})}function y0(a){const{select:c,...s}=a;return pn({...s,select:f=>c?c(f.loaderDeps):f.loaderDeps})}function v0(a){return pn({from:a.from,shouldThrow:a.shouldThrow,structuralSharing:a.structuralSharing,strict:a.strict,select:c=>{const s=a.strict===!1?c.params:c._strictParams;return a.select?a.select(s):s}})}function g0(a){return pn({from:a.from,strict:a.strict,shouldThrow:a.shouldThrow,structuralSharing:a.structuralSharing,select:c=>a.select?a.select(c.search):c.search})}function p0(a){const c=Be();return at.useCallback(s=>c.navigate({...s,from:s.from??a?.from}),[a?.from,c])}function S0(a){return pn({...a,select:c=>a.select?a.select(c.context):c.context})}function Df(a){const c=at.useRef(a);return Yl(c.current,a,{ignoreUndefined:!1})||(c.current=a),c.current}function Dp(a,c){return a[0]===c[0]&&a[1]===c[1]&&a[2]===c[2]}function Up(a,c,s){if(a?.external)return Ji(a.href,s)?void 0:a.href;if(!wp(c)&&!(typeof c!="string"||c.indexOf(":")===-1))try{return new URL(c),Ji(c,s)?void 0:c}catch{}}function Lp(a,c,s,f,r,h){if(h)return!1;if(s?.exact){if(!Mg(a.pathname,c.pathname,f))return!1}else{const g=Wi(a.pathname,f),m=Wi(c.pathname,f);if(!(g.startsWith(m)&&(g.length===m.length||g[m.length]==="/")))return!1}return(s?.includeSearch??!0)&&!Yl(a.search,c.search,{partial:!s?.exact,ignoreUndefined:!s?.explicitUndefined})?!1:s?.includeHash?r&&a.hash===c.hash:!0}function Np(a,c){const s=Be(),f=cg(c),{activeProps:r,inactiveProps:h,activeOptions:g,to:m,preload:y,preloadDelay:d,preloadIntentProximity:S,hashScrollIntoView:p,replace:b,startTransition:T,resetScroll:R,viewTransition:E,children:D,target:w,disabled:Y,style:K,className:X,onClick:et,onBlur:G,onFocus:L,onMouseEnter:Q,onMouseLeave:J,onTouchStart:ct,ignoreBlocker:P,params:ft,search:bt,hash:ee,state:Bt,mask:N,reloadDocument:V,unsafeRelative:lt,from:_t,_fromLocation:zt,...A}=a,q=o0(),Z=Df(a.search),F=Df(a.params),nt=Df(g),it=at.useMemo(()=>a,[s,a.from,a._fromLocation,a.hash,a.to,Z,F,a.state,a.mask,a.unsafeRelative]),vt=at.useCallback(It=>{const Nt=s.buildLocation({_fromLocation:It,...it}),Kl=qp(Nt.maskedLocation?Nt.maskedLocation.publicHref:Nt.publicHref,Nt.maskedLocation?Nt.maskedLocation.external:Nt.external,s.history,Y),va=Up(Kl,m,s.protocolAllowlist);return[Kl?.href,va,Lp(It,Nt,nt,s.basepath,q,va!==void 0)]},[nt,Y,q,it,s,m]),[Jt,Ct,Ve]=Vl(s.stores.location,vt,Dp),Ze=Ve?ra(r,{})??Bp:Uf,hl=Ve?Uf:ra(h,{})??Uf,da=[X,Ze.className,hl.className].filter(Boolean).join(" "),He=(K||Ze.style||hl.style)&&{...K,...Ze.style,...hl.style},Sn=at.useRef(!1),De=a.reloadDocument||Ct||Y?!1:y??s.options.defaultPreload,ha=d??s.options.defaultPreloadDelay??0,Ke=at.useCallback(()=>{s.preloadRoute(it).catch(It=>{console.warn(It),console.warn(rp)})},[s,it]),Zl=at.useCallback(It=>{if(!It){Lf(f);return}if(!(It.isIntersecting??De==="intent")){It.isIntersecting===!1&&Lf(f);return}if(!ha){Ke();return}hu.has(f)||hu.set(f,setTimeout(()=>{hu.delete(f),Ke()},ha))},[Ke,f,De,ha]);ig(f,Zl,De!=="viewport"),at.useEffect(()=>{Sn.current||De==="render"&&(Ke(),Sn.current=!0)},[Ke,De]);const ma=It=>{const Nt=It.currentTarget.getAttribute("target"),Kl=w!==void 0?w:Nt;!Y&&!Yp(It)&&!It.defaultPrevented&&(!Kl||Kl==="_self")&&It.button===0&&(It.preventDefault(),s.navigate({...it,replace:b,resetScroll:R,hashScrollIntoView:p,startTransition:T,viewTransition:E,ignoreBlocker:P}))};if(Ct)return{...A,ref:f,href:Ct,...D&&{children:D},...w&&{target:w},...Y&&{disabled:Y},...K&&{style:K},...X&&{className:X},...et&&{onClick:et},...G&&{onBlur:G},...L&&{onFocus:L},...Q&&{onMouseEnter:Q},...J&&{onMouseLeave:J},...ct&&{onTouchStart:ct}};const ya=()=>{De==="intent"&&Ke()},Su=()=>{De==="intent"&&Lf(f)};return{...A,...Ze,...hl,href:Jt,ref:f,onClick:aa([et,ma]),onBlur:aa([G,Su]),onFocus:aa([L,Zl]),onMouseEnter:aa([Q,Zl]),onMouseLeave:aa([J,Su]),onTouchStart:aa([ct,ya]),disabled:!!Y,target:w,...He&&{style:He},...da&&{className:da},...Y&&Hp,...Ve&&jp}}var Uf={},Bp={className:"active"},Hp={role:"link","aria-disabled":!0},jp={"data-status":"active","aria-current":"page"},hu=new WeakMap,Lf=a=>{clearTimeout(hu.get(a)),hu.delete(a)},aa=a=>c=>{for(const s of a)if(s){if(c.defaultPrevented)return;s(c)}};function qp(a,c,s,f){if(!f)return c?{href:a,external:!0}:{href:s.createHref(a)||"/",external:!1}}function wp(a){if(typeof a!="string")return!1;const c=a.charCodeAt(0);return c===47?a.charCodeAt(1)!==47:c===46}var Ii=at.forwardRef((a,c)=>{const{_asChild:s,...f}=a,{type:r,...h}=Np(f,c),g=typeof f.children=="function"?f.children({isActive:h["data-status"]==="active"}):f.children;if(!s){const{disabled:m,...y}=h;return at.createElement("a",y,g)}return at.createElement(s,h,g)});function Yp(a){return!!(a.metaKey||a.altKey||a.ctrlKey||a.shiftKey)}var Gp=class extends f0{constructor(c){super(c),this.useMatch=s=>pn({select:s?.select,from:this.id,structuralSharing:s?.structuralSharing}),this.useRouteContext=s=>S0({...s,from:this.id}),this.useSearch=s=>g0({select:s?.select,structuralSharing:s?.structuralSharing,from:this.id}),this.useParams=s=>v0({select:s?.select,structuralSharing:s?.structuralSharing,from:this.id}),this.useLoaderDeps=s=>y0({...s,from:this.id}),this.useLoaderData=s=>m0({...s,from:this.id}),this.useNavigate=()=>p0({from:this.fullPath}),this.Link=tc.forwardRef((s,f)=>k.jsx(Ii,{ref:f,from:this.fullPath,...s}))}};function Xp(a){return new Gp(a)}var Qp=class extends dp{constructor(a){super(a),this.useMatch=c=>pn({select:c?.select,from:this.id,structuralSharing:c?.structuralSharing}),this.useRouteContext=c=>S0({...c,from:this.id}),this.useSearch=c=>g0({select:c?.select,structuralSharing:c?.structuralSharing,from:this.id}),this.useParams=c=>v0({select:c?.select,structuralSharing:c?.structuralSharing,from:this.id}),this.useLoaderDeps=c=>y0({...c,from:this.id}),this.useLoaderData=c=>m0({...c,from:this.id}),this.useNavigate=()=>p0({from:this.fullPath}),this.Link=tc.forwardRef((c,s)=>k.jsx(Ii,{ref:s,from:this.fullPath,...c}))}};function Vp(a){return new Qp(a)}function b0(a){return c=>{const s=Xp(c);return s.isRoot=!1,s}}function _0(a,c){let s,f,r;const h=()=>(s||(r=void 0,s=a().then(m=>{s=void 0,f=m[c]}).catch(m=>{s=void 0,r=m})),s),g=function(y){if(r){if(rg(r)&&typeof sessionStorage<"u"){const d=`tanstack_router_reload:${r.message}`;if(!sessionStorage.getItem(d))throw sessionStorage.setItem(d,"1"),window.location.reload(),new Promise(()=>{})}throw r}if(!f)if(cm)cm(h());else throw h();return at.createElement(f,y)};return g.preload=h,g}function Zp(a){const c=Be(),s=`not-found-${Vl(c.stores.location,f=>f.pathname)}-${Vl(c.stores.status,f=>f)}`;return k.jsx(Wf,{getResetKey:()=>s,onCatch:(f,r)=>{if(yn(f))a.onCatch?.(f,r);else throw f},errorComponent:({error:f})=>{if(yn(f))return a.fallback?.(f);throw f},children:a.children})}function Kp(){return k.jsx("p",{children:"Not Found"})}function ia(a){return k.jsx(k.Fragment,{children:a.children})}function E0(a,c,s){return c.options.notFoundComponent?k.jsx(c.options.notFoundComponent,{...s}):a.options.defaultNotFoundComponent?k.jsx(a.options.defaultNotFoundComponent,{...s}):k.jsx(Kp,{})}function uc(a,c){const s=c?.options.pendingComponent??a.options.defaultPendingComponent;return s?k.jsx(s,{}):null}var Jp=(a,c)=>a[0]===c[0]&&a[1]===c[1],T0=at.memo(function({routeId:c}){const s=Be();return k.jsx(kp,{router:s,match:Vl(s.stores.getMatchStore(c),f=>f)})});function kp({router:a,match:c}){const s=a.routesById[c.routeId],f=uc(a,s),r=s.options.errorComponent??a.options.defaultErrorComponent,h=s.options.onCatch??a.options.defaultOnCatch,g=s.isRoot?s.options.notFoundComponent??a.options.notFoundRoute?.options.component:s.options.notFoundComponent,m=c.ssr===!1||c.ssr==="data-only",y=s.options.wrapInSuspense??f??(s.options.errorComponent?.preload||m)?at.Suspense:ia,d=r?Wf:ia,S=g?Zp:ia;return k.jsxs(s.isRoot?s.options.shellComponent??ia:ia,{children:[k.jsx(ac.Provider,{value:c.routeId,children:k.jsx(y,{fallback:f,children:k.jsx(d,{getResetKey:()=>c,errorComponent:r,onCatch:(p,b)=>{if(yn(p))throw p.routeId??=c.routeId,p;h?.(p,b)},children:k.jsx(S,{fallback:p=>{if(p.routeId??=c.routeId,p.routeId!==c.routeId)throw p;return at.createElement(g,p)},children:m?k.jsx(yp,{fallback:f,children:k.jsx(jm,{match:c})}):k.jsx(jm,{match:c})})})})}),null]})}var jm=at.memo(function({match:c}){const s=Be(),f=c.routeId,r=s.routesById[f],h=at.useMemo(()=>{const m=(r.options.remountDeps??s.options.defaultRemountDeps)?.({routeId:f,loaderDeps:c.loaderDeps,params:c._strictParams,search:c._strictSearch});return m?JSON.stringify(m):void 0},[f,c.loaderDeps,c._strictParams,c._strictSearch,r.options.remountDeps,s.options.defaultRemountDeps]),g=at.useMemo(()=>{const m=r.options.component??s.options.defaultComponent;return m?k.jsx(m,{},h):k.jsx(z0,{})},[h,r.options.component,s.options.defaultComponent]);if(c.status==="pending"){if(s._tx)throw s._tx[5];return uc(s,r)}if(c.status==="notFound")return E0(s,r,c.error);if(c.status==="error")throw c.error;return g}),z0=at.memo(function(){const c=Be(),s=at.useContext(ac);let f,r,h;{const m=c.stores.getMatchStore(s);[f,r]=Vl(m,y=>[!!y._notFound,y.error],Jp),h=Vl(c.stores.ids,y=>y[y.indexOf(s)+1])}if(f)return E0(c,c.routesById[s],r);if(!h)return null;const g=k.jsx(T0,{routeId:h});return s===sa?k.jsx(at.Suspense,{fallback:uc(c),children:g}):g});function A0(a,c){const s=a[1];a.length=0,s?.(c)}function Wp({t:a}){const c=Be(),s=c._rendered??=[];return c.startTransition=(f,r)=>new Promise((h,g)=>{A0(s,!1),s.push(r,h),a(c),at.startTransition(()=>{try{f()}catch(m){s[1]===h&&(s.length=0),g(m)}})}),Ym(()=>{const f=c.history.subscribe(c.load);c.updateLatestLocation();const r=c.latestLocation,h=c.buildLocation({to:r.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});if(rl(r.publicHref)!==rl(h.publicHref))return c.commitLocation({...h,replace:!0,ignoreBlocker:!0}),f;const g=c.stores.resolvedLocation.get();return g?.href===r.href&&g.state.__TSR_key===r.state.__TSR_key?s.push(c.stores.matches.get(),m=>{m&&c.emit({type:"onRendered",...lc(g,g)})}):c._tx||c.load().catch(console.error),f},[c,c.history]),null}function Fp(){const a=Be(),c=a.routesById[sa],s=uc(a,c),f=a.ssr?ia:at.Suspense,r=k.jsxs(k.Fragment,{children:[k.jsx(Wp,{t:at.useState()[1]}),k.jsx(f,{fallback:s,children:k.jsx($p,{})})]});return a.options.InnerWrap?k.jsx(a.options.InnerWrap,{children:r}):r}function $p(){const a=Be(),c=a._rendered,s=Vl(a.stores.matches,g=>c[0]??g),f=s[0],r=f?.routeId;Ym(()=>{c[0]===s&&A0(c,!0)},[c,s]);const h=r?k.jsx(T0,{routeId:r}):null;return k.jsx(ac.Provider,{value:r,children:a.options.disableGlobalCatchBoundary?h:k.jsx(Wf,{getResetKey:()=>f,onCatch:void 0,children:h})})}var Pp=a=>({createMutableStore:Dm,createReadonlyStore:Dm,batch:Ep}),Ip=a=>new t1(a),t1=class extends Ig{constructor(a){super(a,Pp)}};function e1({router:a,children:c,...s}){Xm(s)&&a.update({...a.options,...s,context:{...a.options.context,...s.context}});const f=k.jsx(r0.Provider,{value:a,children:c});return a.options.Wrap?k.jsx(a.options.Wrap,{children:f}):f}function l1({router:a,...c}){return k.jsx(e1,{router:a,...c,children:k.jsx(Fp,{})})}const R0="taskreport.user",O0="taskreport.role";function Ff(){return{user:localStorage.getItem(R0)??"ada",role:localStorage.getItem(O0)??"member"}}function n1(a,c){localStorage.setItem(R0,a),localStorage.setItem(O0,c)}async function Ge(a,c){const{user:s,role:f}=Ff(),r=await fetch(`/api${a}`,{...c,headers:{"Content-Type":"application/json","X-Demo-User":s,"X-Demo-Role":f,...c?.headers}}),h=await r.text(),g=h?JSON.parse(h):null;if(!r.ok)throw new Error(g?.error??`${r.status} ${r.statusText}`);return g}const a1={session:()=>Ge("/session"),summary:()=>Ge("/summary"),tasks:(a={})=>{const c=new URLSearchParams(Object.entries(a).filter(([,s])=>s!=="")).toString();return Ge(`/tasks${c?`?${c}`:""}`)},create:a=>Ge("/tasks",{method:"POST",body:JSON.stringify(a)}),complete:a=>Ge(`/tasks/${a}/complete`,{method:"POST"}),reopen:a=>Ge(`/tasks/${a}/reopen`,{method:"POST"}),remove:a=>Ge(`/tasks/${a}`,{method:"DELETE"}),approve:a=>Ge(`/plans/${a}/approve`,{method:"POST"}),reject:a=>Ge(`/plans/${a}/reject`,{method:"POST"}),chat:a=>Ge("/chat",{method:"POST",body:JSON.stringify({request:a})}),chatStream:u1};async function u1(a,c,s){const{user:f,role:r}=Ff(),h=await fetch("/api/chat/stream",{method:"POST",signal:s,headers:{"Content-Type":"application/json","X-Demo-User":f,"X-Demo-Role":r},body:JSON.stringify({request:a})});if(!h.ok||!h.body){const S=await h.text();throw new Error(i1(S)??`${h.status} ${h.statusText}`)}const g=h.body.getReader(),m=new TextDecoder;let y="",d=null;for(;;){const{done:S,value:p}=await g.read();if(S)break;y+=m.decode(p,{stream:!0});let b=y.indexOf(` `);for(;b!==-1;){const T=y.slice(0,b);y=y.slice(b+2),b=y.indexOf(` `);const[R,...E]=T.split(` `),D=R.replace(/^event:\s*/,""),w=E.join(` -`).replace(/^data:\s*/,"");if(w){if(D==="chunk")c(JSON.parse(w).text);else if(D==="result")d=JSON.parse(w);else if(D==="error")throw new Error(JSON.parse(w).error)}}}if(!d)throw new Error("the answer stream ended without a result");return d}function i1(a){try{return JSON.parse(a).error??null}catch{return null}}const $f=Vp({component:c1}),qm=[{user:"ada",role:"member"},{user:"linus",role:"member"},{user:"grace",role:"admin"}];function c1(){const[a,c]=at.useState(null),[s,f]=at.useState(null),r=Be(),h=Ff();at.useEffect(()=>{a1.session().then(c).catch(m=>f(m.message))},[]);function g(m){const y=qm.find(d=>d.user===m);y&&(n1(y.user,y.role),r.invalidate(),window.location.reload())}return k.jsxs("div",{className:"app",children:[k.jsxs("header",{className:"topbar",children:[k.jsxs("div",{className:"brand",children:[k.jsx("span",{className:"mark","aria-hidden":"true"}),k.jsx("span",{children:"Taskreport"})]}),k.jsxs("nav",{children:[k.jsx(Ii,{to:"/",activeOptions:{exact:!0},children:"Board"}),k.jsx(Ii,{to:"/chat",children:"Ask"})]}),k.jsxs("div",{className:"who",children:[a&&k.jsxs("span",{className:`pill role-${a.role}`,children:[a.role,a.withheld>0&&` · ${a.withheld} withheld`]}),k.jsx("select",{value:h.user,onChange:m=>g(m.target.value),children:qm.map(m=>k.jsx("option",{value:m.user,children:m.user},m.user))})]})]}),s&&k.jsx("p",{className:"error banner",children:s}),k.jsx("main",{children:k.jsx(z0,{})}),k.jsx("footer",{children:a?.model?k.jsxs("span",{children:[a.capabilities.length," capabilities across ",a.namespaces.join(", ")," ·"," ",a.model]}):k.jsxs("span",{children:[a?.capabilities.length??0," capabilities · no model configured, so Ask is disabled"]})})]})}const s1="modulepreload",f1=function(a){return"/"+a},wm={},M0=function(c,s,f){let r=Promise.resolve();if(s&&s.length>0){let y=function(d){return Promise.all(d.map(S=>Promise.resolve(S).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const g=document.querySelector("meta[property=csp-nonce]"),m=g?.nonce||g?.getAttribute("nonce");r=y(s.map(d=>{if(d=f1(d),d in wm)return;wm[d]=!0;const S=d.endsWith(".css"),p=S?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${p}`))return;const b=document.createElement("link");if(b.rel=S?"stylesheet":s1,S||(b.as="script"),b.crossOrigin="",b.href=d,m&&b.setAttribute("nonce",m),document.head.appendChild(b),S)return new Promise((T,R)=>{b.addEventListener("load",T),b.addEventListener("error",()=>R(new Error(`Unable to preload CSS for ${d}`)))})}))}function h(g){const m=new Event("vite:preloadError",{cancelable:!0});if(m.payload=g,window.dispatchEvent(m),!m.defaultPrevented)throw g}return r.then(g=>{for(const m of g||[])m.status==="rejected"&&h(m.reason);return c().catch(h)})},o1=()=>M0(()=>import("./index-Dm_jx5Ya.js"),[]),r1=b0()({component:_0(o1,"component")}),d1=()=>M0(()=>import("./chat-CmZZLyt2.js"),[]),h1=b0()({component:_0(d1,"component")}),m1=r1.update({id:"/",path:"/",getParentRoute:()=>$f}),y1=h1.update({id:"/chat",path:"/chat",getParentRoute:()=>$f}),v1={IndexRoute:m1,ChatRoute:y1},g1=$f._addFileChildren(v1)._addFileTypes(),p1=Ip({routeTree:g1});ag.createRoot(document.getElementById("root")).render(k.jsx(at.StrictMode,{children:k.jsx(l1,{router:p1})}));export{a1 as a,k as j,at as r}; +`).replace(/^data:\s*/,"");if(w){if(D==="chunk")c(JSON.parse(w).text);else if(D==="result")d=JSON.parse(w);else if(D==="error")throw new Error(JSON.parse(w).error)}}}if(!d)throw new Error("the answer stream ended without a result");return d}function i1(a){try{return JSON.parse(a).error??null}catch{return null}}const $f=Vp({component:c1}),qm=[{user:"ada",role:"member"},{user:"linus",role:"member"},{user:"grace",role:"admin"}];function c1(){const[a,c]=at.useState(null),[s,f]=at.useState(null),r=Be(),h=Ff();at.useEffect(()=>{a1.session().then(c).catch(m=>f(m.message))},[]);function g(m){const y=qm.find(d=>d.user===m);y&&(n1(y.user,y.role),r.invalidate(),window.location.reload())}return k.jsxs("div",{className:"app",children:[k.jsxs("header",{className:"topbar",children:[k.jsxs("div",{className:"brand",children:[k.jsx("span",{className:"mark","aria-hidden":"true"}),k.jsx("span",{children:"Taskreport"})]}),k.jsxs("nav",{children:[k.jsx(Ii,{to:"/",activeOptions:{exact:!0},children:"Board"}),k.jsx(Ii,{to:"/chat",children:"Ask"})]}),k.jsxs("div",{className:"who",children:[a&&k.jsxs("span",{className:`pill role-${a.role}`,children:[a.role,a.withheld>0&&` · ${a.withheld} withheld`]}),k.jsx("select",{value:h.user,onChange:m=>g(m.target.value),children:qm.map(m=>k.jsx("option",{value:m.user,children:m.user},m.user))})]})]}),s&&k.jsx("p",{className:"error banner",children:s}),k.jsx("main",{children:k.jsx(z0,{})}),k.jsx("footer",{children:a?.model?k.jsxs("span",{children:[a.capabilities.length," capabilities across ",a.namespaces.join(", ")," ·"," ",a.model]}):k.jsxs("span",{children:[a?.capabilities.length??0," capabilities · no model configured, so Ask is disabled"]})})]})}const s1="modulepreload",f1=function(a){return"/"+a},wm={},M0=function(c,s,f){let r=Promise.resolve();if(s&&s.length>0){let y=function(d){return Promise.all(d.map(S=>Promise.resolve(S).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const g=document.querySelector("meta[property=csp-nonce]"),m=g?.nonce||g?.getAttribute("nonce");r=y(s.map(d=>{if(d=f1(d),d in wm)return;wm[d]=!0;const S=d.endsWith(".css"),p=S?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${p}`))return;const b=document.createElement("link");if(b.rel=S?"stylesheet":s1,S||(b.as="script"),b.crossOrigin="",b.href=d,m&&b.setAttribute("nonce",m),document.head.appendChild(b),S)return new Promise((T,R)=>{b.addEventListener("load",T),b.addEventListener("error",()=>R(new Error(`Unable to preload CSS for ${d}`)))})}))}function h(g){const m=new Event("vite:preloadError",{cancelable:!0});if(m.payload=g,window.dispatchEvent(m),!m.defaultPrevented)throw g}return r.then(g=>{for(const m of g||[])m.status==="rejected"&&h(m.reason);return c().catch(h)})},o1=()=>M0(()=>import("./index-B8YGsnYU.js"),[]),r1=b0()({component:_0(o1,"component")}),d1=()=>M0(()=>import("./chat-fahH1l62.js"),[]),h1=b0()({component:_0(d1,"component")}),m1=r1.update({id:"/",path:"/",getParentRoute:()=>$f}),y1=h1.update({id:"/chat",path:"/chat",getParentRoute:()=>$f}),v1={IndexRoute:m1,ChatRoute:y1},g1=$f._addFileChildren(v1)._addFileTypes(),p1=Ip({routeTree:g1});ag.createRoot(document.getElementById("root")).render(k.jsx(at.StrictMode,{children:k.jsx(l1,{router:p1})}));export{a1 as a,k as j,at as r}; diff --git a/examples/taskreport/web/dist/assets/index-CZUp2bvV.css b/examples/taskreport/web/dist/assets/index-D44oUAo0.css similarity index 95% rename from examples/taskreport/web/dist/assets/index-CZUp2bvV.css rename to examples/taskreport/web/dist/assets/index-D44oUAo0.css index 04c4eeb..3d95e78 100644 --- a/examples/taskreport/web/dist/assets/index-CZUp2bvV.css +++ b/examples/taskreport/web/dist/assets/index-D44oUAo0.css @@ -1 +1 @@ -:root{--bg: #f7f7f5;--panel: #ffffff;--line: #e3e2dd;--ink: #1c1b19;--muted: #6f6d67;--accent: #2f6f4e;--accent-soft: #dfeee6;--good: #2f6f4e;--warn: #9a6a12;--bad: #a33a2a;--radius: 10px;--shadow: 0 1px 2px rgb(28 27 25 / 6%), 0 8px 24px rgb(28 27 25 / 4%)}@media(prefers-color-scheme:dark){:root{--bg: #16171a;--panel: #1e2024;--line: #2e3238;--ink: #ecebe8;--muted: #9a9891;--accent: #6cc298;--accent-soft: #1d3830;--good: #6cc298;--warn: #d9a441;--bad: #e0705c;--shadow: 0 1px 2px rgb(0 0 0 / 30%), 0 8px 24px rgb(0 0 0 / 20%)}}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.55 ui-sans-serif,system-ui,-apple-system,Segoe UI,sans-serif;font-variant-numeric:tabular-nums}.app{max-width:900px;margin:0 auto;padding:0 20px 64px}.topbar{display:flex;align-items:center;gap:20px;padding:18px 0;border-bottom:1px solid var(--line);position:sticky;top:0;background:var(--bg);z-index:5}.brand{display:flex;align-items:center;gap:9px;font-weight:620;letter-spacing:-.01em}.mark{width:13px;height:13px;border-radius:4px;background:var(--accent)}.topbar nav{display:flex;gap:4px;margin-left:auto}.topbar nav a{color:var(--muted);text-decoration:none;padding:6px 12px;border-radius:999px;font-weight:500}.topbar nav a:hover{color:var(--ink)}.topbar nav a.active{background:var(--accent-soft);color:var(--accent)}.who{display:flex;align-items:center;gap:10px}.pill{font-size:12px;padding:3px 9px;border-radius:999px;background:var(--panel);border:1px solid var(--line);color:var(--muted)}.pill.role-admin{color:var(--accent);border-color:var(--accent)}footer{margin-top:40px;color:var(--muted);font-size:13px;text-align:center}main{padding-top:28px}input,select,button,textarea{font:inherit;color:inherit}input,select{background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:8px 10px}input:focus-visible,select:focus-visible,button:focus-visible{outline:2px solid var(--accent);outline-offset:1px}button{cursor:pointer;border:1px solid transparent;border-radius:8px;padding:8px 14px;background:var(--accent);color:#fff;font-weight:550}button:disabled{opacity:.5;cursor:default}.error{color:var(--bad)}.error.banner{padding:10px 14px;border:1px solid var(--bad);border-radius:var(--radius)}.muted{color:var(--muted)}.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px}.stat{background:var(--panel);border:1px solid var(--line);border-left:3px solid var(--line);border-radius:var(--radius);padding:14px 16px;display:flex;flex-direction:column;gap:2px}.stat-value{font-size:26px;font-weight:640;letter-spacing:-.02em}.stat-label{font-size:13px;color:var(--muted)}.tone-good{border-left-color:var(--good)}.tone-warn{border-left-color:var(--warn)}.tone-bad{border-left-color:var(--bad)}.new-task{display:flex;gap:8px;margin:22px 0 14px;flex-wrap:wrap}.new-task input:first-child{flex:1 1 220px}.filters{display:flex;gap:6px;margin-bottom:14px}.chip{background:var(--panel);border:1px solid var(--line);color:var(--muted);padding:5px 12px;border-radius:999px;font-weight:500}.chip.on{background:var(--accent-soft);color:var(--accent);border-color:var(--accent)}.tasks{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:8px}.task{display:flex;align-items:center;gap:12px;padding:12px 14px;background:var(--panel);border:1px solid var(--line);border-radius:var(--radius)}.task.done .task-title{text-decoration:line-through;color:var(--muted)}.tick{width:22px;height:22px;flex:none;padding:0;border-radius:6px;background:transparent;border:1.5px solid var(--line);color:var(--accent);font-size:13px}.task.done .tick{background:var(--accent-soft);border-color:var(--accent)}.task-body{display:flex;flex-direction:column;gap:3px;min-width:0;flex:1}.task-title{font-weight:500}.task-meta{display:flex;gap:8px;flex-wrap:wrap;font-size:12px;color:var(--muted)}.tag{background:var(--accent-soft);color:var(--accent);padding:1px 7px;border-radius:999px}.tag.muted{background:transparent;color:var(--muted);border:1px solid var(--line)}.prio-high{color:var(--bad);font-weight:600}.prio-medium{color:var(--warn)}.remove{background:transparent;color:var(--muted);padding:2px 8px;font-size:18px;line-height:1}.remove:hover{color:var(--bad)}.empty{color:var(--muted);padding:24px;text-align:center}.ask{display:flex;flex-direction:column;gap:18px}.hint{color:var(--muted);margin:0 0 6px}.suggestions{display:flex;flex-direction:column;gap:8px;align-items:flex-start}.suggestion{background:var(--panel);border:1px solid var(--line);color:var(--ink);font-weight:450;text-align:left}.suggestion:hover{border-color:var(--accent);color:var(--accent)}.turns{display:flex;flex-direction:column;gap:26px}.turn{display:flex;flex-direction:column;gap:12px}.question{margin:0;font-weight:600;font-size:17px;letter-spacing:-.01em}.thinking{color:var(--muted);margin:0}.composer{display:flex;gap:8px;position:sticky;bottom:0;padding:14px 0;background:var(--bg)}.composer input{flex:1}.doc{background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);padding:18px 20px;box-shadow:var(--shadow);display:flex;flex-direction:column;gap:20px}.doc-title{margin:0;font-size:18px;letter-spacing:-.01em}.doc.refusal{border-left:3px solid var(--warn);background:var(--bg);box-shadow:none}.refusal-text{margin:0;color:var(--muted)}.refusal-text:before{content:"⚠ ";color:var(--warn)}.block{display:flex;flex-direction:column;gap:10px}.block-heading{margin:0;font-size:13px;text-transform:uppercase;letter-spacing:.07em;color:var(--muted);font-weight:600}.prose{margin:0}.bars{display:flex;flex-direction:column;gap:7px}.bar-row{display:grid;grid-template-columns:minmax(80px,150px) 1fr 42px;gap:10px;align-items:center}.bar-label{font-size:13px;color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.bar-track{background:var(--bg);border-radius:5px;height:20px;overflow:hidden}.bar-fill{background:var(--accent);height:100%;border-radius:5px;min-width:2px}.bar-value{text-align:right;font-size:13px;font-weight:600}.line svg{width:100%;height:auto;display:block}.line-area{fill:var(--accent-soft)}.line-stroke{fill:none;stroke:var(--accent);stroke-width:2;stroke-linejoin:round}.line-dot{fill:var(--accent)}.line-labels{display:flex;justify-content:space-between;font-size:12px;color:var(--muted)}.table-scroll{overflow-x:auto}table{border-collapse:collapse;width:100%;font-size:14px}th,td{text-align:left;padding:7px 10px;border-bottom:1px solid var(--line)}th{font-size:12px;text-transform:uppercase;letter-spacing:.06em;color:var(--muted)}tbody tr:last-child td{border-bottom:none}.provenance{display:flex;gap:12px;align-items:center;flex-wrap:wrap;font-size:13px}.link{background:transparent;color:var(--accent);padding:0;font-weight:550;text-decoration:underline}.program{margin:0;padding:14px 16px;overflow-x:auto;background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);font:13px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}.offered{margin:0;padding-left:18px;font-size:13px;color:var(--muted)}.offered code{color:var(--ink)}@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}.program.writing{opacity:.65;max-height:16rem;overflow-y:auto} +:root{--bg: #f7f7f5;--panel: #ffffff;--line: #e3e2dd;--ink: #1c1b19;--muted: #6f6d67;--accent: #2f6f4e;--accent-soft: #dfeee6;--good: #2f6f4e;--warn: #9a6a12;--bad: #a33a2a;--radius: 10px;--shadow: 0 1px 2px rgb(28 27 25 / 6%), 0 8px 24px rgb(28 27 25 / 4%)}@media(prefers-color-scheme:dark){:root{--bg: #16171a;--panel: #1e2024;--line: #2e3238;--ink: #ecebe8;--muted: #9a9891;--accent: #6cc298;--accent-soft: #1d3830;--good: #6cc298;--warn: #d9a441;--bad: #e0705c;--shadow: 0 1px 2px rgb(0 0 0 / 30%), 0 8px 24px rgb(0 0 0 / 20%)}}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.55 ui-sans-serif,system-ui,-apple-system,Segoe UI,sans-serif;font-variant-numeric:tabular-nums}.app{max-width:900px;margin:0 auto;padding:0 20px 64px}.topbar{display:flex;align-items:center;gap:20px;padding:18px 0;border-bottom:1px solid var(--line);position:sticky;top:0;background:var(--bg);z-index:5}.brand{display:flex;align-items:center;gap:9px;font-weight:620;letter-spacing:-.01em}.mark{width:13px;height:13px;border-radius:4px;background:var(--accent)}.topbar nav{display:flex;gap:4px;margin-left:auto}.topbar nav a{color:var(--muted);text-decoration:none;padding:6px 12px;border-radius:999px;font-weight:500}.topbar nav a:hover{color:var(--ink)}.topbar nav a.active{background:var(--accent-soft);color:var(--accent)}.who{display:flex;align-items:center;gap:10px}.pill{font-size:12px;padding:3px 9px;border-radius:999px;background:var(--panel);border:1px solid var(--line);color:var(--muted)}.pill.role-admin{color:var(--accent);border-color:var(--accent)}footer{margin-top:40px;color:var(--muted);font-size:13px;text-align:center}main{padding-top:28px}input,select,button,textarea{font:inherit;color:inherit}input,select{background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:8px 10px}input:focus-visible,select:focus-visible,button:focus-visible{outline:2px solid var(--accent);outline-offset:1px}button{cursor:pointer;border:1px solid transparent;border-radius:8px;padding:8px 14px;background:var(--accent);color:#fff;font-weight:550}button:disabled{opacity:.5;cursor:default}.error{color:var(--bad)}.error.banner{padding:10px 14px;border:1px solid var(--bad);border-radius:var(--radius)}.muted{color:var(--muted)}.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px}.stat{background:var(--panel);border:1px solid var(--line);border-left:3px solid var(--line);border-radius:var(--radius);padding:14px 16px;display:flex;flex-direction:column;gap:2px}.stat-value{font-size:26px;font-weight:640;letter-spacing:-.02em}.stat-label{font-size:13px;color:var(--muted)}.tone-good{border-left-color:var(--good)}.tone-warn{border-left-color:var(--warn)}.tone-bad{border-left-color:var(--bad)}.new-task{display:flex;gap:8px;margin:22px 0 14px;flex-wrap:wrap}.new-task input:first-child{flex:1 1 220px}.filters{display:flex;gap:6px;margin-bottom:14px}.chip{background:var(--panel);border:1px solid var(--line);color:var(--muted);padding:5px 12px;border-radius:999px;font-weight:500}.chip.on{background:var(--accent-soft);color:var(--accent);border-color:var(--accent)}.tasks{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:8px}.task{display:flex;align-items:center;gap:12px;padding:12px 14px;background:var(--panel);border:1px solid var(--line);border-radius:var(--radius)}.task.done .task-title{text-decoration:line-through;color:var(--muted)}.tick{width:22px;height:22px;flex:none;padding:0;border-radius:6px;background:transparent;border:1.5px solid var(--line);color:var(--accent);font-size:13px}.task.done .tick{background:var(--accent-soft);border-color:var(--accent)}.task-body{display:flex;flex-direction:column;gap:3px;min-width:0;flex:1}.task-title{font-weight:500}.task-meta{display:flex;gap:8px;flex-wrap:wrap;font-size:12px;color:var(--muted)}.tag{background:var(--accent-soft);color:var(--accent);padding:1px 7px;border-radius:999px}.tag.muted{background:transparent;color:var(--muted);border:1px solid var(--line)}.prio-high{color:var(--bad);font-weight:600}.prio-medium{color:var(--warn)}.remove{background:transparent;color:var(--muted);padding:2px 8px;font-size:18px;line-height:1}.remove:hover{color:var(--bad)}.empty{color:var(--muted);padding:24px;text-align:center}.ask{display:flex;flex-direction:column;gap:18px}.hint{color:var(--muted);margin:0 0 6px}.suggestions{display:flex;flex-direction:column;gap:8px;align-items:flex-start}.suggestion{background:var(--panel);border:1px solid var(--line);color:var(--ink);font-weight:450;text-align:left}.suggestion:hover{border-color:var(--accent);color:var(--accent)}.turns{display:flex;flex-direction:column;gap:26px}.turn{display:flex;flex-direction:column;gap:12px}.question{margin:0;font-weight:600;font-size:17px;letter-spacing:-.01em}.thinking{color:var(--muted);margin:0}.composer{display:flex;gap:8px;position:sticky;bottom:0;padding:14px 0;background:var(--bg)}.composer input{flex:1}.doc{background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);padding:18px 20px;box-shadow:var(--shadow);display:flex;flex-direction:column;gap:20px}.doc-title{margin:0;font-size:18px;letter-spacing:-.01em}.doc.refusal{border-left:3px solid var(--warn);background:var(--bg);box-shadow:none}.refusal-text{margin:0;color:var(--muted)}.refusal-text:before{content:"⚠ ";color:var(--warn)}.block{display:flex;flex-direction:column;gap:10px}.block-heading{margin:0;font-size:13px;text-transform:uppercase;letter-spacing:.07em;color:var(--muted);font-weight:600}.prose{margin:0}.bars{display:flex;flex-direction:column;gap:7px}.bar-row{display:grid;grid-template-columns:minmax(80px,150px) 1fr 42px;gap:10px;align-items:center}.bar-label{font-size:13px;color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.bar-track{background:var(--bg);border-radius:5px;height:20px;overflow:hidden}.bar-fill{background:var(--accent);height:100%;border-radius:5px;min-width:2px}.bar-value{text-align:right;font-size:13px;font-weight:600}.line svg{width:100%;height:auto;display:block}.line-area{fill:var(--accent-soft)}.line-stroke{fill:none;stroke:var(--accent);stroke-width:2;stroke-linejoin:round}.line-dot{fill:var(--accent)}.line-labels{display:flex;justify-content:space-between;font-size:12px;color:var(--muted)}.table-scroll{overflow-x:auto}table{border-collapse:collapse;width:100%;font-size:14px}th,td{text-align:left;padding:7px 10px;border-bottom:1px solid var(--line)}th{font-size:12px;text-transform:uppercase;letter-spacing:.06em;color:var(--muted)}tbody tr:last-child td{border-bottom:none}.provenance{display:flex;gap:12px;align-items:center;flex-wrap:wrap;font-size:13px}.link{background:transparent;color:var(--accent);padding:0;font-weight:550;text-decoration:underline}.program{margin:0;padding:14px 16px;overflow-x:auto;background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);font:13px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}.offered{margin:0;padding-left:18px;font-size:13px;color:var(--muted)}.offered code{color:var(--ink)}@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}.program.writing{opacity:.65;max-height:16rem;overflow-y:auto}.pending{border:1px solid var(--warn, #c98a00);border-radius:var(--radius);padding:12px 14px;margin:12px 0}.pending-title{font-weight:600;margin:0 0 8px}.pending ul{margin:0 0 12px;padding-left:18px}.pending-actions{display:flex;gap:8px}button.secondary{background:transparent;color:inherit;border-color:currentColor} diff --git a/examples/taskreport/web/dist/index.html b/examples/taskreport/web/dist/index.html index 992857c..bdaa657 100644 --- a/examples/taskreport/web/dist/index.html +++ b/examples/taskreport/web/dist/index.html @@ -4,8 +4,8 @@ Taskreport - - + +
diff --git a/examples/taskreport/web/src/api.ts b/examples/taskreport/web/src/api.ts index 51d37fd..683910e 100644 --- a/examples/taskreport/web/src/api.ts +++ b/examples/taskreport/web/src/api.ts @@ -51,8 +51,16 @@ export type StatusCounts = { due_today: number; }; +// Writes the program reached that need the user's approval. None of them has +// run; the server keeps the plan and applies exactly these on approve. +export type PendingPlan = { + id: string; + calls: { name: string; input: Record }[]; +}; + export type ChatResult = { document: ViewDocument; + pending?: PendingPlan; program: string; attempts: number; used: { capability: { name: string; description: string }; distance: number }[]; @@ -117,6 +125,10 @@ export const api = { reopen: (id: number) => call<{ task: Task }>(`/tasks/${id}/reopen`, { method: "POST" }), remove: (id: number) => call<{ deleted: boolean }>(`/tasks/${id}`, { method: "DELETE" }), + approve: (id: string) => + call<{ calls: { name: string; error?: string }[] }>(`/plans/${id}/approve`, { method: "POST" }), + reject: (id: string) => call<{ rejected: boolean }>(`/plans/${id}/reject`, { method: "POST" }), + chat: (request: string) => call("/chat", { method: "POST", body: JSON.stringify({ request }) }), diff --git a/examples/taskreport/web/src/routes/chat.tsx b/examples/taskreport/web/src/routes/chat.tsx index 1470d7c..13c72de 100644 --- a/examples/taskreport/web/src/routes/chat.tsx +++ b/examples/taskreport/web/src/routes/chat.tsx @@ -1,6 +1,6 @@ import { createFileRoute } from "@tanstack/react-router"; import { useState } from "react"; -import { api, type ChatResult } from "../api"; +import { api, type ChatResult, type PendingPlan } from "../api"; import { DocumentView } from "../components/Blocks"; export const Route = createFileRoute("/chat")({ component: Ask }); @@ -122,6 +122,7 @@ function TurnView({ turn, pending }: { turn: Turn; pending: boolean }) { {turn.result && ( <> + {turn.result.pending && } {/* The program is the evidence. When an answer looks wrong, this is what tells you whether the model or the data was at fault. */} @@ -164,6 +165,57 @@ function TurnView({ turn, pending }: { turn: Turn; pending: boolean }) { ); } +// PendingView asks before anything the program wanted to change actually +// changes. Approve sends only the plan's ID: the server applies exactly what is +// listed here, once, and checks the caller's access again as it does. +function PendingView({ plan }: { plan: PendingPlan }) { + const [state, setState] = useState<"waiting" | "working" | "approved" | "rejected">("waiting"); + const [outcome, setOutcome] = useState(""); + + async function decide(approve: boolean) { + setState("working"); + try { + if (approve) { + const { calls } = await api.approve(plan.id); + setOutcome(`${calls.length} change${calls.length === 1 ? "" : "s"} made`); + setState("approved"); + } else { + await api.reject(plan.id); + setOutcome("nothing was changed"); + setState("rejected"); + } + } catch (err) { + setOutcome((err as Error).message); + setState("rejected"); + } + } + + return ( +
+

Waiting for your approval

+
    + {plan.calls.map((call, index) => ( +
  • + {call.name} {JSON.stringify(call.input)} +
  • + ))} +
+ {state === "waiting" || state === "working" ? ( +
+ + +
+ ) : ( +

{outcome}

+ )} +
+ ); +} + function replaceLast(turns: Turn[], turn: Turn): Turn[] { return [...turns.slice(0, -1), turn]; } diff --git a/examples/taskreport/web/src/styles.css b/examples/taskreport/web/src/styles.css index b571169..6eaee93 100644 --- a/examples/taskreport/web/src/styles.css +++ b/examples/taskreport/web/src/styles.css @@ -198,3 +198,9 @@ tbody tr:last-child td { border-bottom: none; } max-height: 16rem; overflow-y: auto; } + +.pending { border: 1px solid var(--warn, #c98a00); border-radius: var(--radius); padding: 12px 14px; margin: 12px 0; } +.pending-title { font-weight: 600; margin: 0 0 8px; } +.pending ul { margin: 0 0 12px; padding-left: 18px; } +.pending-actions { display: flex; gap: 8px; } +button.secondary { background: transparent; color: inherit; border-color: currentColor; } From 4432f5a74f3e334819f1809f268174beac2afa23 Mon Sep 17 00:00:00 2001 From: Mukesh Kumar Chaudhary Date: Mon, 16 Nov 2026 10:22:11 +0545 Subject: [PATCH 6/7] feat: add shop and combined examples examples/shop is the quickstart as a runnable, tested example: Go-struct capabilities, a typed answer with RunAs, and a refund approved at the terminal. examples/combined runs one program over a Go function, the todo proto service and an in-process MCP server via codemode.Combine. Both run with no API key (make demo-shop, make demo-combined). --- Makefile | 8 +- examples/combined/README.md | 34 +++++++ examples/combined/main.go | 177 +++++++++++++++++++++++++++++++++ examples/combined/main_test.go | 52 ++++++++++ examples/shop/README.md | 37 +++++++ examples/shop/main.go | 168 +++++++++++++++++++++++++++++++ examples/shop/main_test.go | 98 ++++++++++++++++++ 7 files changed, 573 insertions(+), 1 deletion(-) create mode 100644 examples/combined/README.md create mode 100644 examples/combined/main.go create mode 100644 examples/combined/main_test.go create mode 100644 examples/shop/README.md create mode 100644 examples/shop/main.go create mode 100644 examples/shop/main_test.go diff --git a/Makefile b/Makefile index e68f1ef..f858527 100644 --- a/Makefile +++ b/Makefile @@ -1,9 +1,15 @@ -.PHONY: demo-todo mcp-todo worker worker-image test-container demo-report demo-web generate generate-go generate-registry test test-vector \ +.PHONY: demo-todo demo-shop demo-combined mcp-todo worker worker-image test-container demo-report demo-web generate generate-go generate-registry test test-vector \ test-postgres test-consumer test-env docs docs-build docs-preview demo-todo: generate go run ./examples/todo +demo-shop: + go run ./examples/shop + +demo-combined: + go run ./examples/combined + worker: go build -o bin/codemode-worker ./cmd/codemode-worker diff --git a/examples/combined/README.md b/examples/combined/README.md new file mode 100644 index 0000000..524dbb4 --- /dev/null +++ b/examples/combined/README.md @@ -0,0 +1,34 @@ +# combined + +One program, three capability sources: this application's own Go functions, a +protobuf service, and an MCP server's tools, joined with `codemode.Combine`. + +| Capability | Source | +| --- | --- | +| `notes.add` | Go: `gosource.Func` in `main.go` | +| `todos.create`, `todos.list`, `todos.complete`, `todos.delete` | protobuf: [`examples/todo/proto/todo.proto`](../todo/proto/todo.proto) | +| `calendar.events` | MCP: an in-process server standing in for another team's service | + +From the repository root: + +```sh +make demo-combined # or: go run ./examples/combined — no key, a fixed program +``` + +``` +answer + Scheduled today: Write the docs at 14:00 +``` + +The program lists todos from the proto service, today's events from the MCP +server, and saves a note through the Go function, all in one run. Set +`ANTHROPIC_API_KEY` or `OPENAI_API_KEY` to have a model write it instead. + +What to look at: + +- `Combine` routes each call to the source that owns its RPC. A name or RPC + defined twice is an error. +- `mcpsource.Import(..., "member")`: imported tools require the role the host + names and count as writes, whatever the server claims. A caller with no role + never sees `calendar.events`. +- Every call is validated against its shape, whichever source it came from. diff --git a/examples/combined/main.go b/examples/combined/main.go new file mode 100644 index 0000000..1cec9ee --- /dev/null +++ b/examples/combined/main.go @@ -0,0 +1,177 @@ +// combined serves one program from three sources at once: typed Go functions, +// a protobuf service and an MCP server's tools, joined with codemode.Combine. +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "log" + "strings" + "sync" + + "github.com/modelcontextprotocol/go-sdk/mcp" + + "github.com/mukezhz/codemode/agent" + "github.com/mukezhz/codemode/capability" + "github.com/mukezhz/codemode/capability/gosource" + "github.com/mukezhz/codemode/capability/mcpsource" + "github.com/mukezhz/codemode/codemode" + "github.com/mukezhz/codemode/llm" + coderegistry "github.com/mukezhz/codemode/registry" + "github.com/mukezhz/codemode/sandbox" + + todo "github.com/mukezhz/codemode/examples/todo/app" + todov1 "github.com/mukezhz/codemode/examples/todo/gen/todo/v1" + + _ "github.com/mukezhz/codemode/llm/claude" + _ "github.com/mukezhz/codemode/llm/openai" + _ "github.com/mukezhz/codemode/sandbox/goja" +) + +// Notes are this application's own capabilities, from Go. +type Note struct { + Text string `json:"text"` +} + +type Notes struct { + mutex sync.Mutex + notes []Note +} + +type AddNote struct { + Text string `json:"text" desc:"the note, one or two sentences"` +} + +type NoteList struct { + Notes []Note `json:"notes"` +} + +func (notes *Notes) Add(_ context.Context, request AddNote) (NoteList, error) { + if strings.TrimSpace(request.Text) == "" { + return NoteList{}, errors.New("text is required") + } + notes.mutex.Lock() + defer notes.mutex.Unlock() + notes.notes = append(notes.notes, Note(request)) + return NoteList{Notes: append([]Note{}, notes.notes...)}, nil +} + +func (notes *Notes) Source() (codemode.Source, error) { + return gosource.New(gosource.Func("notes.add", "Saves a note and returns every note so far.", gosource.Public(), notes.Add)) +} + +// The calendar stands in for a service another team runs, in any language: it +// speaks MCP, and codemode imports its tools. +type EventsInput struct { + Day string `json:"day" jsonschema:"YYYY-MM-DD"` +} + +type Event struct { + Title string `json:"title"` + Time string `json:"time"` +} + +type EventsOutput struct { + Events []Event `json:"events"` +} + +func calendar(ctx context.Context) (*mcp.ClientSession, error) { + server := mcp.NewServer(&mcp.Implementation{Name: "calendar"}, nil) + mcp.AddTool(server, &mcp.Tool{Name: "events", Description: "Lists the events on one day."}, + func(_ context.Context, _ *mcp.CallToolRequest, input EventsInput) (*mcp.CallToolResult, EventsOutput, error) { + return nil, EventsOutput{Events: []Event{{Title: "Launch review", Time: "10:00"}, {Title: "Write the docs", Time: "14:00"}}}, nil + }) + serverTransport, clientTransport := mcp.NewInMemoryTransports() + if _, err := server.Connect(ctx, serverTransport, nil); err != nil { + return nil, err + } + return mcp.NewClient(&mcp.Implementation{Name: "combined"}, nil).Connect(ctx, clientTransport, nil) +} + +func sources(ctx context.Context) (codemode.Source, func(), error) { + notes, err := (&Notes{}).Source() + if err != nil { + return codemode.Source{}, nil, err + } + + registry, err := coderegistry.FromFiles(todov1.File_todo_proto) + if err != nil { + return codemode.Source{}, nil, err + } + todos := todo.New() + todos.Create(ctx, todo.CreateRequest{Title: "Write the docs"}) + todos.Create(ctx, todo.CreateRequest{Title: "Book the venue"}) + fromProto := codemode.Source{Registry: registry, Execute: todos.Execute} + + session, err := calendar(ctx) + if err != nil { + return codemode.Source{}, nil, err + } + // Imported tools arrive restricted to a role the host names, and count as writes. + events, err := mcpsource.Import(ctx, session, "calendar", "member") + if err != nil { + session.Close() + return codemode.Source{}, nil, err + } + + all, err := codemode.Combine(notes, fromProto, events) + if err != nil { + session.Close() + return codemode.Source{}, nil, err + } + return all, func() { session.Close() }, nil +} + +const program = ` +const { todos } = codemode.execute("todos.list", {}); +const { events } = codemode.execute("calendar.events", { day: "2026-11-16" }); +const open = todos.filter(todo => !todo.completed).map(todo => todo.title); +const busy = events.filter(event => open.includes(event.title)).map(event => event.title + " at " + event.time); +const { notes } = codemode.execute("notes.add", { text: "Scheduled today: " + (busy.join(", ") || "nothing on the list") }); +return notes[notes.length - 1].text;` + +func main() { + request := flag.String("request", "which of my open todos are on today's calendar? note it down", "what to ask") + flag.Parse() + ctx := context.Background() + + all, closeSources, err := sources(ctx) + if err != nil { + log.Fatal(err) + } + defer closeSources() + mode, err := codemode.FromSource(all, capability.Caller{Roles: []string{"member"}}) + if err != nil { + log.Fatal(err) + } + runner, err := sandbox.NewFromEnv(sandbox.Options{}) + if err != nil { + log.Fatal(err) + } + defer runner.Close() + + fmt.Println("capabilities") + for _, item := range all.Registry.Capabilities { + fmt.Printf(" %-16s %s\n", item.Name, item.RPC) + } + + model, err := llm.NewFromEnv() + if errors.Is(err, llm.ErrNoProvider) { + value, err := runner.Run(ctx, mode, program) + if err != nil { + log.Fatal(err) + } + fmt.Printf("\nprogram (fixed; set ANTHROPIC_API_KEY or OPENAI_API_KEY to have one written)\n%s\n\nanswer\n %v\n", program, value) + return + } + if err != nil { + log.Fatal(err) + } + result, err := agent.Run(ctx, mode, model, *request, agent.Options{Runner: runner}) + if err != nil { + log.Fatal(err) + } + fmt.Printf("\nprogram\n%s\n\nanswer\n %s\n", result.Source, agent.Answer(result.Answer)) +} diff --git a/examples/combined/main_test.go b/examples/combined/main_test.go new file mode 100644 index 0000000..fc3815a --- /dev/null +++ b/examples/combined/main_test.go @@ -0,0 +1,52 @@ +package main + +import ( + "context" + "testing" + + "github.com/mukezhz/codemode/capability" + "github.com/mukezhz/codemode/codemode" + "github.com/mukezhz/codemode/codemode/sourcetest" + "github.com/mukezhz/codemode/sandbox" +) + +func TestOneProgramCallsAllThreeSources(t *testing.T) { + ctx := context.Background() + all, closeSources, err := sources(ctx) + if err != nil { + t.Fatal(err) + } + defer closeSources() + sourcetest.Run(t, all) + + mode, err := codemode.FromSource(all, capability.Caller{Roles: []string{"member"}}) + if err != nil { + t.Fatal(err) + } + runner, err := sandbox.New(sandbox.Options{}) + if err != nil { + t.Fatal(err) + } + defer runner.Close() + + value, err := runner.Run(ctx, mode, program) + if err != nil { + t.Fatal(err) + } + if value != "Scheduled today: Write the docs at 14:00" { + t.Fatalf("value = %v", value) + } +} + +func TestImportedToolsNeedTheRoleTheHostNamed(t *testing.T) { + all, closeSources, err := sources(context.Background()) + if err != nil { + t.Fatal(err) + } + defer closeSources() + for _, name := range all.Registry.For(capability.Caller{}).Names() { + if name == "calendar.events" { + t.Fatal("a caller with no role can reach an imported tool") + } + } +} diff --git a/examples/shop/README.md b/examples/shop/README.md new file mode 100644 index 0000000..9f09102 --- /dev/null +++ b/examples/shop/README.md @@ -0,0 +1,37 @@ +# shop + +The [quickstart](../../docs/content/quickstart.md) as a runnable example: two +capabilities from typed Go functions, an answer that comes back as a Go struct, +and a refund that waits for you to approve it. + +``` +main.go the shop: structs, two functions, gosource, RunAs, ApplyPlan +main_test.go typed answer, approval, access and validation, with no model +``` + +From the repository root: + +```sh +make demo-shop # or: go run ./examples/shop — no key, a fixed program +``` + +``` +2 paid orders, 141.5 in total +``` + +With a model: + +```sh +export ANTHROPIC_API_KEY=sk-ant-... # or OPENAI_API_KEY (+ OPENAI_BASE_URL, OPENAI_MODEL) +go run ./examples/shop # revenue and top customer, as a Revenue struct +go run ./examples/shop "refund order 1" # held; answer y to apply it +``` + +What to look at: + +- `ListOrders`, `Orders`, `Status` are the schema. `Status` has `Enum()`, so + `{status: "lost"}` is rejected before `Shop.List` runs. +- `orders.refund` is `Roles("support")` and `NeedsApproval()`: a customer + cannot see it, and support must approve each one. +- `agent.RunAs[Revenue]` returns a validated `Revenue`; a program that returns a + sentence is asked to return the object instead. diff --git a/examples/shop/main.go b/examples/shop/main.go new file mode 100644 index 0000000..660bc07 --- /dev/null +++ b/examples/shop/main.go @@ -0,0 +1,168 @@ +// shop is the quickstart as a runnable example: capabilities from typed Go +// functions, a typed answer, and a refund that waits for approval. +package main + +import ( + "context" + "errors" + "fmt" + "log" + "os" + + "github.com/mukezhz/codemode/agent" + "github.com/mukezhz/codemode/capability" + "github.com/mukezhz/codemode/capability/gosource" + "github.com/mukezhz/codemode/codemode" + "github.com/mukezhz/codemode/llm" + "github.com/mukezhz/codemode/sandbox" + + _ "github.com/mukezhz/codemode/llm/claude" + _ "github.com/mukezhz/codemode/llm/openai" + _ "github.com/mukezhz/codemode/sandbox/goja" + _ "github.com/mukezhz/codemode/sandbox/subprocess" +) + +type Status string + +func (Status) Enum() []string { return []string{"pending", "paid", "refunded"} } + +type Order struct { + ID int64 `json:"id"` + Customer string `json:"customer"` + Status Status `json:"status"` + Total float64 `json:"total"` +} + +type ListOrders struct { + Status Status `json:"status,omitempty" desc:"only orders in this status; leave out for all"` +} + +type Orders struct { + Orders []Order `json:"orders"` +} + +type RefundOrder struct { + ID int64 `json:"id" desc:"the id from orders.list"` +} + +type OrderResult struct { + Order Order `json:"order"` +} + +// Shop is your application: the only code that touches real data. +type Shop struct { + orders []Order +} + +func (shop *Shop) List(_ context.Context, request ListOrders) (Orders, error) { + var found []Order + for _, order := range shop.orders { + if request.Status == "" || order.Status == request.Status { + found = append(found, order) + } + } + return Orders{Orders: found}, nil +} + +func (shop *Shop) Refund(_ context.Context, request RefundOrder) (OrderResult, error) { + for index := range shop.orders { + if shop.orders[index].ID == request.ID && shop.orders[index].Status == "paid" { + shop.orders[index].Status = "refunded" + return OrderResult{Order: shop.orders[index]}, nil + } + } + return OrderResult{}, fmt.Errorf("no paid order %d", request.ID) +} + +type Revenue struct { + Total float64 `json:"total"` + TopCustomer string `json:"top_customer"` +} + +func newShop() *Shop { + return &Shop{orders: []Order{ + {ID: 1, Customer: "ada", Status: "paid", Total: 42.5}, + {ID: 2, Customer: "linus", Status: "pending", Total: 10}, + {ID: 3, Customer: "grace", Status: "paid", Total: 99}, + }} +} + +func (shop *Shop) Source() (codemode.Source, error) { + return gosource.New( + gosource.Func("orders.list", "Lists orders, optionally only those in one status.", + gosource.Public(), shop.List, gosource.ReadOnly()), + gosource.Func("orders.refund", "Refunds a paid order by ID.", + gosource.Roles("support"), shop.Refund, gosource.NeedsApproval()), + ) +} + +func main() { + ctx := context.Background() + source, err := newShop().Source() + if err != nil { + log.Fatal(err) + } + caller := capability.Caller{Roles: []string{"support"}} // in your app: the signed-in user's roles + mode, err := codemode.FromSource(source, caller) + if err != nil { + log.Fatal(err) + } + runner, err := sandbox.NewFromEnv(sandbox.Options{}) + if err != nil { + log.Fatal(err) + } + defer runner.Close() + + model, err := llm.NewFromEnv() + if errors.Is(err, llm.ErrNoProvider) { + // No API key: run a hand-written program so you can see the sandbox work. + value, err := runner.Run(ctx, mode, ` + const { orders } = codemode.execute("orders.list", { status: "paid" }); + const total = orders.reduce((sum, order) => sum + order.total, 0); + return orders.length + " paid orders, " + total + " in total";`) + if err != nil { + log.Fatal(err) + } + fmt.Println(value) + return + } + if err != nil { + log.Fatal(err) + } + + if len(os.Args) > 1 { + refund(ctx, mode, model, runner, os.Args[1]) + return + } + revenue, result, err := agent.RunAs[Revenue](ctx, mode, model, + "how much have paid orders brought in, and who is the biggest customer?", agent.Options{Runner: runner}) + if err != nil { + log.Fatal(err) + } + fmt.Printf("program:\n%s\n\n%.2f in total, biggest customer %s\n", result.Source, revenue.Total, revenue.TopCustomer) +} + +func refund(ctx context.Context, mode codemode.CodeMode, model llm.Client, runner sandbox.Runner, request string) { + plans := agent.NewMemoryPlans(0) + _, err := agent.Run(ctx, mode, model, request, agent.Options{Runner: runner, Plans: plans, PlanOwner: "you"}) + var pending *agent.Pending + if !errors.As(err, &pending) { + fmt.Println("nothing needed approval:", err) + return + } + for _, call := range pending.Calls { + fmt.Printf("wants to run %s %s\n", call.Name, call.Input) + } + fmt.Print("approve? [y/N] ") + var answer string + fmt.Scanln(&answer) + if answer != "y" { + fmt.Println("nothing changed") + return + } + calls, err := agent.ApplyPlan(ctx, mode, plans, "you", pending.ID) + if err != nil { + log.Fatal(err) + } + fmt.Printf("ran %d call(s)\n", len(calls)) +} diff --git a/examples/shop/main_test.go b/examples/shop/main_test.go new file mode 100644 index 0000000..236c641 --- /dev/null +++ b/examples/shop/main_test.go @@ -0,0 +1,98 @@ +package main + +import ( + "context" + "errors" + "strings" + "testing" + + "github.com/mukezhz/codemode/agent" + "github.com/mukezhz/codemode/capability" + "github.com/mukezhz/codemode/codemode" + "github.com/mukezhz/codemode/codemode/sourcetest" + "github.com/mukezhz/codemode/sandbox" +) + +type script struct{ programs []string } + +func (script *script) Name() string { return "test/script" } + +func (script *script) Complete(context.Context, string, string) (string, error) { + if len(script.programs) == 0 { + return "", errors.New("no programs left") + } + program := script.programs[0] + script.programs = script.programs[1:] + return program, nil +} + +func setup(t *testing.T, roles ...string) (*Shop, codemode.CodeMode, sandbox.Runner) { + t.Helper() + shop := newShop() + source, err := shop.Source() + if err != nil { + t.Fatal(err) + } + sourcetest.Run(t, source) + mode, err := codemode.FromSource(source, capability.Caller{Roles: roles}) + if err != nil { + t.Fatal(err) + } + runner, err := sandbox.New(sandbox.Options{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { runner.Close() }) + return shop, mode, runner +} + +func TestRevenueComesBackTyped(t *testing.T) { + _, mode, runner := setup(t, "support") + model := &script{programs: []string{ + `return "141.5, grace";`, + `const { orders } = codemode.execute("orders.list", { status: "paid" }); + const top = orders.reduce((a, b) => (b.total > a.total ? b : a)); + return { total: orders.reduce((sum, o) => sum + o.total, 0), top_customer: top.customer };`, + }} + revenue, result, err := agent.RunAs[Revenue](context.Background(), mode, model, "revenue?", agent.Options{Runner: runner}) + if err != nil { + t.Fatal(err) + } + if revenue.Total != 141.5 || revenue.TopCustomer != "grace" || result.Attempts != 2 { + t.Fatalf("revenue = %+v after %d attempts", revenue, result.Attempts) + } +} + +func TestARefundWaitsForApproval(t *testing.T) { + shop, mode, runner := setup(t, "support") + plans := agent.NewMemoryPlans(0) + model := &script{programs: []string{`codemode.execute("orders.refund", { id: 1 }); return "refunded";`}} + + _, err := agent.Run(context.Background(), mode, model, "refund order 1", agent.Options{Runner: runner, Plans: plans, PlanOwner: "you"}) + var pending *agent.Pending + if !errors.As(err, &pending) || shop.orders[0].Status != "paid" { + t.Fatalf("err = %v, status = %s; the refund must wait", err, shop.orders[0].Status) + } + if _, err := agent.ApplyPlan(context.Background(), mode, plans, "you", pending.ID); err != nil { + t.Fatal(err) + } + if shop.orders[0].Status != "refunded" { + t.Fatalf("status = %s after approval", shop.orders[0].Status) + } +} + +func TestACustomerCannotRefund(t *testing.T) { + _, mode, runner := setup(t, "customer") + _, err := runner.Run(context.Background(), mode, `return codemode.execute("orders.refund", { id: 1 });`) + if err == nil || !strings.Contains(err.Error(), "not registered") { + t.Fatalf("err = %v", err) + } +} + +func TestAnInvalidStatusNeverReachesTheShop(t *testing.T) { + _, mode, runner := setup(t) + _, err := runner.Run(context.Background(), mode, `return codemode.execute("orders.list", { status: "lost" });`) + if err == nil || !strings.Contains(err.Error(), "want one of pending, paid, refunded") { + t.Fatalf("err = %v", err) + } +} From ae66758d1dca8df0b7b4ddd7e6ef36502966105a Mon Sep 17 00:00:00 2001 From: Mukesh Kumar Chaudhary Date: Mon, 16 Nov 2026 10:22:11 +0545 Subject: [PATCH 7/7] docs: point to the new examples and the taskreport approval flow --- CHANGELOG.md | 9 ++++++++- CLAUDE.md | 1 + README.md | 9 +++++++-- docs/content/approval.md | 13 +++++++++++++ docs/content/quickstart.md | 5 ++++- notes/milestones/2026-11-pluggable-sources.md | 3 ++- 6 files changed, 35 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b6dd1a..54d504f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,7 +32,14 @@ version is 0, a minor bump may break the API. - `capability/jsonschema`: the JSON Schema converter `mcpsource` used, exported. - `codemode/sourcetest.Run`: the contract every capability source passes. - `examples/todo` serves its capabilities from Go functions by default; - `-source proto` keeps the proto path. + `-source proto` keeps the proto path. `todos.delete` needs approval, and + `todo-mcp` shows `run_program` refusing it. +- `examples/taskreport` serves its 23 capabilities from typed Go functions by + default (`-source proto` keeps the protos, and a test holds both to the same + surface). `tasks.delete` needs approval: the chat shows held writes with + Approve and Reject, backed by `POST /api/plans/{id}/approve` and `/reject`. +- `examples/shop`, the quickstart as a runnable example, and + `examples/combined`, one program over Go, protobuf and MCP sources. - Docs: a Go-structs quickstart, and pages for capability sources, types and validation, and approving writes. The protobuf quickstart moved to `docs/content/protobuf.md`. diff --git a/CLAUDE.md b/CLAUDE.md index 033414f..194efd2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -32,4 +32,5 @@ Flow: a source (typed Go functions via `capability/gosource`, protos via `buf ge - Single test: `go test ./agent -run TestName -count=1` - `make test-env` — library packages may read env only in their `env.go` - `make demo-todo` — runs without API keys or DB (keyword search fallback, fixed program) +- `make demo-shop` / `make demo-combined` — the quickstart, and one program over Go, proto and MCP sources; both run without keys - `make demo-web BASE_URL=... API_KEY=... MODEL=...` — taskreport web app on :8080 diff --git a/README.md b/README.md index e466ece..f97cf0d 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,10 @@ Ask it *"what is overdue, and which of it is high priority?"* and one model turn produces one program, which returns a document the browser renders as stat cards, a chart, and a table. Works against any OpenAI-compatible endpoint. -Each example has a step-by-step README: [`examples/todo`](examples/todo/README.md) +Two more show the new pieces in isolation: [`examples/shop`](examples/shop/README.md) +(the quickstart: typed answer, approved refund) and +[`examples/combined`](examples/combined/README.md) (Go functions, a proto service +and an MCP server in one program). Each example has a step-by-step README: [`examples/todo`](examples/todo/README.md) (no key, no database, also an MCP server for Claude Code) and [`examples/taskreport`](examples/taskreport/README.md) (web UI, roles, rate limits, audit log). Both run programs in-process by default; add @@ -149,7 +152,9 @@ make docs-build # build the static site | `sandbox/` | The `Runner` interface; engines in `goja/`, `starlark/`, `lua/` | | `agent/` | Search → prompt → model → sandbox, with a repair loop, typed answers and approval plans | | `examples/todo/` | The smallest end-to-end example, also served over MCP | -| `examples/taskreport/` | A complete app: SQLite tasks, 23 capabilities, roles, reporting | +| `examples/shop/` | The quickstart: Go-struct capabilities, a typed answer, an approved refund | +| `examples/combined/` | Go functions, a proto service and an MCP server in one program | +| `examples/taskreport/` | A complete app: SQLite tasks, 23 typed capabilities, roles, reporting, approval in the chat | | `docs/` | The published documentation site | | `notes/` | Internal writing: PRDs, milestones, decisions. Never published. | diff --git a/docs/content/approval.md b/docs/content/approval.md index 53b09aa..8bffb1f 100644 --- a/docs/content/approval.md +++ b/docs/content/approval.md @@ -75,6 +75,19 @@ Without a `PlanStore`, `Pending.ID` is empty and you apply `Pending.Calls` with implement `agent.PlanStore` (`Save`, `Take`) on your database; `Take` must delete the plan it returns. +## In a web app + +[`examples/taskreport`](https://github.com/mukezhz/codemode/tree/main/examples/taskreport) +holds `tasks.delete` for approval. The chat response carries the plan's ID and +its calls; the page shows them with Approve and Reject, which post to +`/api/plans/{id}/approve` or `/reject`. A delete from the task board is a +button the user pressed, so the server runs it with an approved recorder: + +```go +approved := codemode.WithRecorder(ctx, &codemode.Recorder{Approved: true}) +output, err := mode.Execute(approved, "tasks.delete", input) +``` + ## Limits A held write returns `{}` to the program, so a program that uses a held write's diff --git a/docs/content/quickstart.md b/docs/content/quickstart.md index d1006f0..550df2c 100644 --- a/docs/content/quickstart.md +++ b/docs/content/quickstart.md @@ -10,7 +10,10 @@ You will build a tiny shop with two capabilities, `orders.list` and biggest customer?"* You will get the answer back as a Go struct, and the refund will wait for you to approve it. -You need Go. No database, no Docker, and an API key only for step 4. +You need Go. No database, no Docker, and an API key only for step 4. The +finished code is +[`examples/shop`](https://github.com/mukezhz/codemode/tree/main/examples/shop) +in the repository, with tests. ## 1. Create the module diff --git a/notes/milestones/2026-11-pluggable-sources.md b/notes/milestones/2026-11-pluggable-sources.md index 66a1d06..1730285 100644 --- a/notes/milestones/2026-11-pluggable-sources.md +++ b/notes/milestones/2026-11-pluggable-sources.md @@ -8,7 +8,8 @@ below: `Source`, `Combine` and `FromSource` live in `codemode` (an `ExecuteFunc` in `capability` would import `codemode`), `sourcetest` is `codemode/sourcetest`, the Go schema is `capability.SchemaOf` (stdlib reflection, so Go type names reach the prompt, rather than `jsonschema-go`), and descriptions use a `desc` tag. -Not done: T3.5 (taskreport approval UI) and tagging `v0.1.0`. Open questions +T3.5 is done: taskreport serves typed Go functions by default and approves +deletes in the chat. Not done: tagging `v0.1.0`. Open questions 1–3 resolved as: add `Required`, add `integer`, RPC is the capability name; 4 kept as written.