From 76a7474547b365940c8dd03a80bdd44d1d7d0536 Mon Sep 17 00:00:00 2001 From: Mukesh Kumar Chaudhary Date: Mon, 16 Nov 2026 11:41:08 +0545 Subject: [PATCH 1/3] feat: keep approval plans durable, with events and traceable run errors agent.Plans is the approval API: List (the inbox), Get, Approve, Reject and Resume. A plan carries its status, expiry, request, run ID, each applied call's result and a history of every change. Decisions are a compare-and-set on the stored version, so a plan applies once across replicas; expiry is checked on read; applying records each result before the next call, so a crash resumes instead of losing the plan. Errors name the plan and its state. agent/sqlplans stores plans in SQLite or Postgres through database/sql, and agent/plantest is the contract every store passes. Options.OnEvent reports every step of a run with its run ID, LogEvents sends events to slog, and every error Run returns except *Pending is an *agent.Error with the run ID and the failing stage. Replaces NewMemoryPlans and ApplyPlan, which were never released. --- Makefile | 2 +- agent/agent.go | 96 +++-- agent/event.go | 96 +++++ agent/plan.go | 449 +++++++++++++++++--- agent/plan_test.go | 293 +++++++++++++ agent/plantest/plantest.go | 120 ++++++ agent/sqlplans/sqlplans.go | 158 +++++++ agent/sqlplans/sqlplans_test.go | 81 ++++ agent/typed_test.go | 82 ---- examples/shop/main.go | 9 +- examples/shop/main_test.go | 4 +- examples/taskreport/serve.go | 10 + examples/taskreport/server/approval_test.go | 39 +- examples/taskreport/server/server.go | 86 ++-- examples/taskreport/store/store.go | 3 + scripts/check-consumer.sh | 2 +- 16 files changed, 1308 insertions(+), 222 deletions(-) create mode 100644 agent/event.go create mode 100644 agent/plan_test.go create mode 100644 agent/plantest/plantest.go create mode 100644 agent/sqlplans/sqlplans.go create mode 100644 agent/sqlplans/sqlplans_test.go diff --git a/Makefile b/Makefile index f858527..029a324 100644 --- a/Makefile +++ b/Makefile @@ -85,7 +85,7 @@ test-postgres: -e POSTGRES_DB=codemode -p 55432:5432 pgvector/pgvector:pg17 sleep 4 CAPABILITY_TEST_POSTGRES_DSN=postgres://postgres:test@localhost:55432/codemode?sslmode=disable \ - go test ./capability/pgstore -run TestPostgresSearch -count=1; \ + go test ./capability/pgstore ./agent/sqlplans -run 'TestPostgres' -count=1; \ status=$$?; docker stop codemode-pg >/dev/null; exit $$status # Documentation site. Self-contained under docs/: its own package.json and diff --git a/agent/agent.go b/agent/agent.go index 6db0155..de565bc 100644 --- a/agent/agent.go +++ b/agent/agent.go @@ -35,13 +35,24 @@ 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. + // Plans keeps writes held for approval until someone decides; nil returns them in Pending only. + Plans *Plans + // PlanOwner is who may decide a held plan, such as a user ID. PlanOwner string + // OnEvent receives every step of the run, each carrying Result.RunID. It must not block. + OnEvent func(Event) // Set by RunAs: checks the returned value, so a mismatch is repaired like a failure. check func(any) error + runID string +} + +func (options Options) emit(event Event) { + if options.OnEvent != nil { + event.Time = time.Now() + event.RunID = options.runID + options.OnEvent(event) + } } const ( @@ -66,6 +77,8 @@ func (options Options) checked() (Options, error) { } type Result struct { + // RunID is on every event and error of this run, and on the plan it held. + RunID string Answer any Source string // Empty on a cache hit. @@ -112,36 +125,53 @@ func Run(ctx context.Context, mode codemode.CodeMode, model llm.Client, request if err != nil { return Result{}, err } + options.runID = newID(8) + options.emit(Event{Kind: EventRunStarted}) runner := options.Runner var timing Timing meter := &llm.Meter{} ctx = llm.WithMeter(ctx, meter) + stage := StageCache finish := func(result Result, err error) (Result, error) { timing.Total = time.Since(started) + result.RunID = options.runID result.Timing = timing result.Usage = meter.Usage() - return result, err + var pending *Pending + switch { + case errors.As(err, &pending): + options.emit(Event{Kind: EventRunFinished, PlanID: pending.ID, Count: len(pending.Calls), Duration: timing.Total}) + return result, err + case err != nil: + options.emit(Event{Kind: EventRunFailed, Stage: stage, Duration: timing.Total, Err: err.Error()}) + return result, &Error{RunID: options.runID, Stage: stage, Err: err} + } + options.emit(Event{Kind: EventRunFinished, Duration: timing.Total}) + return result, nil } key, caching := cacheKey(mode, runner, request, options) if caching { if result, hit, err := fromCache(ctx, mode, key, options, &timing); hit || err != nil { + stage = StageRun return finish(result, err) } } + stage = StageSearch search := time.Now() matches, err := mode.Search(ctx, request, options.Limit) timing.Search = time.Since(search) if err != nil { - return finish(Result{}, fmt.Errorf("search: %w", err)) + return finish(Result{}, err) } + options.emit(Event{Kind: EventSearchDone, Count: len(matches), Duration: timing.Search}) if len(matches) == 0 { - return finish(Result{}, errors.New("search matched no capabilities")) + return finish(Result{}, errors.New("search matched no capabilities; check the capability descriptions, or the caller's roles")) } - result, err := generate(ctx, mode, model, request, matches, options, &timing) + result, err := generate(ctx, mode, model, request, matches, options, &timing, &stage) if err != nil { return finish(result, err) } @@ -153,7 +183,7 @@ func Run(ctx context.Context, mode codemode.CodeMode, model llm.Client, request } // Sandbox errors are the model's to fix; transport errors are not. -func generate(ctx context.Context, mode codemode.CodeMode, model llm.Client, request string, matches []capability.Match, options Options, timing *Timing) (Result, error) { +func generate(ctx context.Context, mode codemode.CodeMode, model llm.Client, request string, matches []capability.Match, options Options, timing *Timing, stage *string) (Result, error) { system := options.Runner.Prompt(matches) if instructions := strings.TrimSpace(options.Instructions); instructions != "" { system += "\nAdditional instructions:\n" + instructions + "\n" @@ -165,24 +195,29 @@ func generate(ctx context.Context, mode codemode.CodeMode, model llm.Client, req for attempt := 1; attempt <= options.Attempts; attempt++ { result.Attempts = attempt + *stage = StageGenerate generating := time.Now() response, err := complete(ctx, model, system, prompt, options.OnChunk) - timing.Generate += time.Since(generating) + took := time.Since(generating) + timing.Generate += took if err != nil { return result, err } result.Source = Program(response) + options.emit(Event{Kind: EventProgramWritten, Attempt: attempt, Duration: took}) + *stage = StageRun answer, recorder, err := run(ctx, mode, result.Source, options, timing) result.Calls = append(result.Calls, recorder.Calls()...) if err == nil { result.Answer = answer result.Planned = planned(recorder) - return result, pending(ctx, recorder, result.Planned, options) + return result, pending(ctx, recorder, result.Planned, request, options) } if stop := unretryable(recorder, err); stop != nil { return result, stop } + options.emit(Event{Kind: EventProgramFailed, Attempt: attempt, Err: err.Error()}) if used := llm.UsageFrom(ctx).Total(); options.MaxTokens > 0 && used >= options.MaxTokens { return result, fmt.Errorf("%w: %d of %d tokens used: %w", ErrTokenBudget, used, options.MaxTokens, err) } @@ -249,7 +284,16 @@ func fromCache(ctx context.Context, mode codemode.CodeMode, key program.Key, opt } func run(ctx context.Context, mode codemode.CodeMode, source string, options Options, timing *Timing) (any, *codemode.Recorder, error) { - recorder := &codemode.Recorder{Plan: options.Plan, OnCall: options.OnCall} + recorder := &codemode.Recorder{Plan: options.Plan, OnCall: func(call codemode.Call) { + kind := EventCallDone + if call.Planned { + kind = EventCallHeld + } + options.emit(Event{Kind: kind, Name: call.Name, Duration: call.Duration, Err: call.Error}) + if options.OnCall != nil { + options.OnCall(call) + } + }} running := time.Now() answer, err := options.Runner.Run(codemode.WithRecorder(ctx, recorder), mode, source) timing.Run += time.Since(running) @@ -259,19 +303,18 @@ func run(ctx context.Context, mode codemode.CodeMode, source string, options Opt return answer, recorder, err } -func pending(ctx context.Context, recorder *codemode.Recorder, held []codemode.Call, options Options) error { +func pending(ctx context.Context, recorder *codemode.Recorder, held []codemode.Call, request string, 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 + if options.Plans == nil { + return &Pending{Plan: Plan{RunID: options.runID, Request: request, Calls: held, Status: PlanPending}} + } + plan, err := options.Plans.hold(ctx, options.PlanOwner, options.runID, request, held) + if err != nil { + return err } - return plan + return &Pending{Plan: plan} } func unretryable(recorder *codemode.Recorder, err error) error { @@ -294,19 +337,6 @@ func planned(recorder *codemode.Recorder) []codemode.Call { return writes } -// 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{Approved: true} - ctx = codemode.WithRecorder(ctx, recorder) - for _, call := range planned { - if _, err := mode.Execute(ctx, call.Name, call.Input); err != nil { - return recorder.Calls(), err - } - } - return recorder.Calls(), nil -} - func complete(ctx context.Context, model llm.Client, system, prompt string, chunk func(string)) (string, error) { if chunk != nil { if streamer, ok := model.(llm.Streamer); ok { diff --git a/agent/event.go b/agent/event.go new file mode 100644 index 0000000..91c0ef0 --- /dev/null +++ b/agent/event.go @@ -0,0 +1,96 @@ +package agent + +import ( + "context" + "fmt" + "log/slog" + "time" +) + +// Event is one step of a run or a plan. Every event of one run carries its +// RunID; plan events carry the PlanID too, so a log line, a plan and an error +// can be joined on one key. +type Event struct { + Time time.Time + Kind string + RunID string + PlanID string + // Stage is where a run failed: cache, search, generate, or run. + Stage string + // Name is the capability, on call events. + Name string + Attempt int + Count int + Duration time.Duration + Err string +} + +const ( + EventRunStarted = "run.started" + EventSearchDone = "search.done" + EventProgramWritten = "program.written" + // A program that failed and goes back to the model for repair. + EventProgramFailed = "program.failed" + EventCallDone = "call.done" + EventCallHeld = "call.held" + EventRunFinished = "run.finished" + EventRunFailed = "run.failed" + + EventPlanHeld = "plan.held" + EventPlanApplying = "plan.applying" + EventPlanApplied = "plan.applied" + EventPlanFailed = "plan.failed" + EventPlanRejected = "plan.rejected" + EventPlanExpired = "plan.expired" +) + +// LogEvents writes each event to logger: failures at error level, the rest at info. +func LogEvents(logger *slog.Logger) func(Event) { + return func(event Event) { + attributes := []slog.Attr{slog.String("run", event.RunID)} + add := func(key, value string) { + if value != "" { + attributes = append(attributes, slog.String(key, value)) + } + } + add("plan", event.PlanID) + add("stage", event.Stage) + add("capability", event.Name) + if event.Attempt > 0 { + attributes = append(attributes, slog.Int("attempt", event.Attempt)) + } + if event.Count > 0 { + attributes = append(attributes, slog.Int("count", event.Count)) + } + if event.Duration > 0 { + attributes = append(attributes, slog.Duration("took", event.Duration)) + } + level := slog.LevelInfo + if event.Err != "" { + level = slog.LevelError + attributes = append(attributes, slog.String("error", event.Err)) + } + logger.LogAttrs(context.Background(), level, event.Kind, attributes...) + } +} + +// Error is every failure agent.Run returns, except *Pending: which run, and +// at which stage. errors.Is and errors.As see through it to the cause. +type Error struct { + RunID string + Stage string + Err error +} + +func (failure *Error) Error() string { + return fmt.Sprintf("run %s: %s: %v", failure.RunID, failure.Stage, failure.Err) +} + +func (failure *Error) Unwrap() error { return failure.Err } + +const ( + StageCache = "cache" + StageSearch = "search" + StageGenerate = "generate" + StageRun = "run" +) diff --git a/agent/plan.go b/agent/plan.go index ef9c45a..3488d2c 100644 --- a/agent/plan.go +++ b/agent/plan.go @@ -4,102 +4,437 @@ import ( "context" "crypto/rand" "encoding/hex" + "encoding/json" "errors" "fmt" + "slices" + "sort" "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 PlanStatus string + +const ( + PlanPending PlanStatus = "pending" + PlanApplying PlanStatus = "applying" + PlanApplied PlanStatus = "applied" + PlanFailed PlanStatus = "failed" + PlanRejected PlanStatus = "rejected" + PlanExpired PlanStatus = "expired" +) + +// moves is the whole state machine; anything else is refused. +var moves = map[PlanStatus][]PlanStatus{ + PlanPending: {PlanApplying, PlanRejected, PlanExpired}, + PlanApplying: {PlanApplying, PlanApplied, PlanFailed}, +} + +// Plan is a set of writes held for a person, stored until they decide. +type Plan struct { + ID string `json:"id"` + Owner string `json:"owner"` + // RunID is the run that held these writes; its events and errors carry the same ID. + RunID string `json:"run_id"` + Request string `json:"request"` + Calls []codemode.Call `json:"calls"` + // Applied holds one result per call that has run, in order. + Applied []codemode.Call `json:"applied,omitempty"` + Status PlanStatus `json:"status"` + CreatedAt time.Time `json:"created_at"` + ExpiresAt time.Time `json:"expires_at"` + History []PlanChange `json:"history"` + // Version is the store's compare-and-set counter; leave it alone. + Version int `json:"version"` +} + +type PlanChange struct { + Status PlanStatus `json:"status"` + At time.Time `json:"at"` + By string `json:"by,omitempty"` + Note string `json:"note,omitempty"` +} + +// Decided is the change that ended the plan's wait, if any. +func (plan Plan) Decided() (PlanChange, bool) { + for _, change := range plan.History { + if change.Status != PlanPending { + return change, true + } + } + return PlanChange{}, false +} + +func (plan *Plan) move(to PlanStatus, at time.Time, by, note string) error { + if !slices.Contains(moves[plan.Status], to) { + return plan.decidedError() + } + plan.Status = to + plan.History = append(plan.History, PlanChange{Status: to, At: at, By: by, Note: note}) + return nil +} + +func (plan Plan) decidedError() error { + change, _ := plan.Decided() + detail := fmt.Sprintf("at %s", change.At.UTC().Format(time.RFC3339)) + if change.By != "" { + detail = "by " + change.By + " " + detail + } + if plan.Status == PlanExpired { + return fmt.Errorf("plan %s expired at %s: %w", plan.ID, plan.ExpiresAt.UTC().Format(time.RFC3339), ErrPlanExpired) + } + return fmt.Errorf("plan %s is already %s (%s): %w", plan.ID, plan.Status, detail, ErrPlanDecided) +} + +// Pending is the error a run returns when a write is held for approval. It is +// the stored plan, so ID and ExpiresAt are what the client needs; without +// Options.Plans, ID is empty and Calls go to Apply. type Pending struct { - // Empty when Options.Plans is nil. - ID string - Calls []codemode.Call + Plan } func (pending *Pending) Error() string { - return fmt.Sprintf("%d write(s) wait for approval", len(pending.Calls)) + if pending.ID == "" { + return fmt.Sprintf("%d write(s) wait for approval", len(pending.Calls)) + } + return fmt.Sprintf("plan %s: %d write(s) wait for approval until %s", + pending.ID, len(pending.Calls), pending.ExpiresAt.UTC().Format(time.RFC3339)) } -// 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") +var ( + ErrNoPlan = errors.New("no such plan") + ErrPlanExpired = errors.New("plan expired") + ErrPlanDecided = errors.New("plan already decided") + // ErrPlanChanged is what a PlanStore returns when the stored version moved on. + ErrPlanChanged = errors.New("plan changed since it was read") +) -// 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. +// PlanStore keeps plans. Update writes plan only if the stored version equals +// plan.Version, then increments both; otherwise it returns ErrPlanChanged. Get +// and List return ErrNoPlan, never another owner's plan. List is newest first; +// an empty status lists every status. 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) + Create(ctx context.Context, plan Plan) error + Get(ctx context.Context, owner, id string) (Plan, error) + List(ctx context.Context, owner string, status PlanStatus) ([]Plan, error) + Update(ctx context.Context, plan *Plan) error } -// DefaultPlanTTL is how long a memory plan waits for approval. -const DefaultPlanTTL = 15 * time.Minute +const DefaultPlanTTL = 24 * time.Hour -type memoryPlans struct { - ttl time.Duration - mutex sync.Mutex - plans map[string]memoryPlan +type PlanOptions struct { + // How long a plan waits for a decision; zero takes DefaultPlanTTL. + TTL time.Duration + // Receives plan.held, plan.applying, plan.applied, plan.failed, plan.rejected and plan.expired. It must not block. + OnEvent func(Event) + // Now is for tests; nil uses time.Now. + Now func() time.Time } -type memoryPlan struct { - owner string - calls []codemode.Call - expires time.Time +// Plans is the approval API: runs hold writes in it, and people decide on them +// through it. Safe for concurrent use; the store serialises decisions. +type Plans struct { + store PlanStore + options PlanOptions } -var _ PlanStore = (*memoryPlans)(nil) +func NewPlans(store PlanStore, options PlanOptions) *Plans { + if options.TTL <= 0 { + options.TTL = DefaultPlanTTL + } + if options.Now == nil { + options.Now = time.Now + } + return &Plans{store: store, options: options} +} -// 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 +func (plans *Plans) hold(ctx context.Context, owner, runID, request string, calls []codemode.Call) (Plan, error) { + now := plans.options.Now() + plan := Plan{ + ID: newID(16), Owner: owner, RunID: runID, Request: request, Calls: calls, + Status: PlanPending, CreatedAt: now, ExpiresAt: now.Add(plans.options.TTL), + History: []PlanChange{{Status: PlanPending, At: now, By: owner}}, } - return &memoryPlans{ttl: ttl, plans: map[string]memoryPlan{}} + if err := plans.store.Create(ctx, plan); err != nil { + return Plan{}, fmt.Errorf("save plan: %w", err) + } + plans.emit(Event{Kind: EventPlanHeld, RunID: runID, PlanID: plan.ID, Count: len(calls)}) + return plan, nil } -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 +// Get returns a plan, moving it to expired first if its time has passed. +func (plans *Plans) Get(ctx context.Context, owner, id string) (Plan, error) { + plan, err := plans.store.Get(ctx, owner, id) + if err != nil { + return Plan{}, planError(id, err) } - id := hex.EncodeToString(random) - now := time.Now() + return plans.expire(ctx, plan) +} + +// List returns owner's plans in status, newest first; an empty status lists all. +func (plans *Plans) List(ctx context.Context, owner string, status PlanStatus) ([]Plan, error) { + listed, err := plans.store.List(ctx, owner, "") + if err != nil { + return nil, fmt.Errorf("list plans: %w", err) + } + kept := make([]Plan, 0, len(listed)) + for _, plan := range listed { + if plan, err = plans.expire(ctx, plan); err != nil { + return nil, err + } + if status == "" || plan.Status == status { + kept = append(kept, plan) + } + } + sort.SliceStable(kept, func(i, j int) bool { return kept[i].CreatedAt.After(kept[j].CreatedAt) }) + return kept, nil +} + +// ponytail: expiry happens when a plan is read, so an unread plan stays pending in storage past its time. +func (plans *Plans) expire(ctx context.Context, plan Plan) (Plan, error) { + now := plans.options.Now() + if plan.Status != PlanPending || now.Before(plan.ExpiresAt) { + return plan, nil + } + if err := plan.move(PlanExpired, now, "", "not decided in time"); err != nil { + return plan, err + } + if err := plans.store.Update(ctx, &plan); err != nil { + if errors.Is(err, ErrPlanChanged) { + return plans.store.Get(ctx, plan.Owner, plan.ID) + } + return plan, fmt.Errorf("plan %s: expire: %w", plan.ID, err) + } + plans.emit(Event{Kind: EventPlanExpired, RunID: plan.RunID, PlanID: plan.ID}) + return plan, nil +} + +// Reject discards a pending plan; none of its calls run. +func (plans *Plans) Reject(ctx context.Context, owner, id, note string) (Plan, error) { + plan, err := plans.decide(ctx, owner, id, PlanRejected, note) + if err != nil { + return plan, err + } + plans.emit(Event{Kind: EventPlanRejected, RunID: plan.RunID, PlanID: plan.ID}) + return plan, nil +} + +// Approve runs a pending plan once. Pass the caller's current runtime: each call +// passes validation, the registry and your handler again. On a failed call the +// plan is failed and the error names the call; calls after it do not run. +func (plans *Plans) Approve(ctx context.Context, mode codemode.CodeMode, owner, id string) (Plan, error) { + plan, err := plans.decide(ctx, owner, id, PlanApplying, "approved") + if err != nil { + return plan, err + } + return plans.apply(ctx, mode, plan) +} + +// Resume continues a plan left applying by a crash, from the first call with no +// recorded result. That call may have committed before the crash, so its +// handler should be idempotent, or check before resuming. +func (plans *Plans) Resume(ctx context.Context, mode codemode.CodeMode, owner, id string) (Plan, error) { + plan, err := plans.Get(ctx, owner, id) + if err != nil { + return plan, err + } + if plan.Status != PlanApplying { + return plan, fmt.Errorf("plan %s is %s, not applying; only an interrupted plan resumes: %w", plan.ID, plan.Status, ErrPlanDecided) + } + if err := plan.move(PlanApplying, plans.options.Now(), owner, fmt.Sprintf("resumed at call %d of %d", len(plan.Applied)+1, len(plan.Calls))); err != nil { + return plan, err + } + if err := plans.save(ctx, &plan); err != nil { + return plan, err + } + return plans.apply(ctx, mode, plan) +} + +func (plans *Plans) decide(ctx context.Context, owner, id string, to PlanStatus, note string) (Plan, error) { + plan, err := plans.Get(ctx, owner, id) + if err != nil { + return plan, err + } + // Only a waiting plan is decided; an applying one goes through Resume, never a second Approve. + if plan.Status != PlanPending { + return plan, plan.decidedError() + } + if err := plan.move(to, plans.options.Now(), owner, note); err != nil { + return plan, err + } + return plan, plans.save(ctx, &plan) +} + +// save turns a lost compare-and-set into the error that explains it. +func (plans *Plans) save(ctx context.Context, plan *Plan) error { + err := plans.store.Update(ctx, plan) + if errors.Is(err, ErrPlanChanged) { + if current, getErr := plans.store.Get(ctx, plan.Owner, plan.ID); getErr == nil { + return current.decidedError() + } + } + if err != nil { + return fmt.Errorf("plan %s: save: %w", plan.ID, err) + } + return nil +} + +func (plans *Plans) apply(ctx context.Context, mode codemode.CodeMode, plan Plan) (Plan, error) { + plans.emit(Event{Kind: EventPlanApplying, RunID: plan.RunID, PlanID: plan.ID, Count: len(plan.Calls) - len(plan.Applied)}) + recorder := &codemode.Recorder{Approved: true} + approved := codemode.WithRecorder(ctx, recorder) + for index := len(plan.Applied); index < len(plan.Calls); index++ { + call := plan.Calls[index] + started := time.Now() + output, err := mode.Execute(approved, call.Name, call.Input) + result := codemode.Call{Name: call.Name, Input: call.Input, Output: output, Duration: time.Since(started)} + if err != nil { + result.Error = err.Error() + } + plan.Applied = append(plan.Applied, result) + plans.emit(Event{Kind: EventCallDone, RunID: plan.RunID, PlanID: plan.ID, Name: call.Name, Duration: result.Duration, Err: result.Error}) + if err != nil { + failure := fmt.Errorf("plan %s: call %d of %d (%s): %w", plan.ID, index+1, len(plan.Calls), call.Name, err) + _ = plan.move(PlanFailed, plans.options.Now(), "", failure.Error()) + if saveErr := plans.save(ctx, &plan); saveErr != nil { + return plan, errors.Join(failure, saveErr) + } + plans.emit(Event{Kind: EventPlanFailed, RunID: plan.RunID, PlanID: plan.ID, Name: call.Name, Err: err.Error()}) + return plan, failure + } + // Recorded before the next call, so a crash resumes after this one. + if err := plans.save(ctx, &plan); err != nil { + return plan, err + } + } + if err := plan.move(PlanApplied, plans.options.Now(), "", ""); err != nil { + return plan, err + } + if err := plans.save(ctx, &plan); err != nil { + return plan, err + } + plans.emit(Event{Kind: EventPlanApplied, RunID: plan.RunID, PlanID: plan.ID, Count: len(plan.Applied)}) + return plan, nil +} + +func (plans *Plans) emit(event Event) { + if plans.options.OnEvent != nil { + event.Time = plans.options.Now() + plans.options.OnEvent(event) + } +} + +func planError(id string, err error) error { + if errors.Is(err, ErrNoPlan) { + return fmt.Errorf("plan %s: %w", id, ErrNoPlan) + } + return fmt.Errorf("plan %s: %w", id, err) +} + +// Apply runs calls with approval granted, for a plan kept by the host itself. It +// stops at the first failure; each call still passes validation, the registry +// and the transport. +func Apply(ctx context.Context, mode codemode.CodeMode, calls []codemode.Call) ([]codemode.Call, error) { + recorder := &codemode.Recorder{Approved: true} + ctx = codemode.WithRecorder(ctx, recorder) + for _, call := range calls { + if _, err := mode.Execute(ctx, call.Name, call.Input); err != nil { + return recorder.Calls(), err + } + } + return recorder.Calls(), nil +} + +type memoryPlanStore struct { + mutex sync.Mutex + plans map[string][]byte +} + +var _ PlanStore = (*memoryPlanStore)(nil) + +// NewMemoryPlanStore keeps plans in this process. +// ponytail: lost on restart and invisible to other replicas; use agent/sqlplans for either. +func NewMemoryPlanStore() PlanStore { + return &memoryPlanStore{plans: map[string][]byte{}} +} + +// Plans are stored encoded, so a caller holding a Plan cannot change the stored one. +func (store *memoryPlanStore) Create(_ context.Context, plan Plan) error { store.mutex.Lock() defer store.mutex.Unlock() - for key, plan := range store.plans { - if now.After(plan.expires) { - delete(store.plans, key) - } + if _, exists := store.plans[plan.ID]; exists { + return fmt.Errorf("plan %s already exists", plan.ID) } - store.plans[id] = memoryPlan{owner: owner, calls: append([]codemode.Call(nil), calls...), expires: now.Add(store.ttl)} - return id, nil + encoded, err := json.Marshal(plan) + store.plans[plan.ID] = encoded + return err } -func (store *memoryPlans) Take(_ context.Context, owner, id string) ([]codemode.Call, error) { +func (store *memoryPlanStore) Get(_ context.Context, owner, id string) (Plan, error) { store.mutex.Lock() defer store.mutex.Unlock() - plan, found := store.plans[id] - if !found || plan.owner != owner { - return nil, ErrNoPlan + return store.get(owner, id) +} + +func (store *memoryPlanStore) get(owner, id string) (Plan, error) { + var plan Plan + encoded, found := store.plans[id] + if !found { + return Plan{}, ErrNoPlan + } + if err := json.Unmarshal(encoded, &plan); err != nil { + return Plan{}, err + } + if plan.Owner != owner { + return Plan{}, ErrNoPlan } - delete(store.plans, id) - if time.Now().After(plan.expires) { - return nil, ErrNoPlan + return plan, nil +} + +func (store *memoryPlanStore) List(_ context.Context, owner string, status PlanStatus) ([]Plan, error) { + store.mutex.Lock() + defer store.mutex.Unlock() + var listed []Plan + for id := range store.plans { + plan, err := store.get(owner, id) + if errors.Is(err, ErrNoPlan) { + continue + } + if err != nil { + return nil, err + } + if status == "" || plan.Status == status { + listed = append(listed, plan) + } } - return plan.calls, nil + sort.Slice(listed, func(i, j int) bool { return listed[i].CreatedAt.After(listed[j].CreatedAt) }) + return listed, 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) +func (store *memoryPlanStore) Update(_ context.Context, plan *Plan) error { + store.mutex.Lock() + defer store.mutex.Unlock() + stored, err := store.get(plan.Owner, plan.ID) if err != nil { - return nil, err + return err } - return Apply(ctx, mode, calls) + if stored.Version != plan.Version { + return ErrPlanChanged + } + plan.Version++ + encoded, err := json.Marshal(plan) + if err != nil { + plan.Version-- + return err + } + store.plans[plan.ID] = encoded + return nil +} + +func newID(bytes int) string { + random := make([]byte, bytes) + _, _ = rand.Read(random) + return hex.EncodeToString(random) } diff --git a/agent/plan_test.go b/agent/plan_test.go new file mode 100644 index 0000000..e3c2261 --- /dev/null +++ b/agent/plan_test.go @@ -0,0 +1,293 @@ +package agent_test + +import ( + "context" + "encoding/json" + "errors" + "strings" + "sync" + "testing" + "time" + + "github.com/mukezhz/codemode/agent" + "github.com/mukezhz/codemode/agent/plantest" + "github.com/mukezhz/codemode/capability" + "github.com/mukezhz/codemode/codemode" + "github.com/mukezhz/codemode/sandbox" + "github.com/mukezhz/codemode/sandbox/goja" +) + +func TestMemoryPlanStorePassesTheContract(t *testing.T) { + plantest.Run(t, func(*testing.T) agent.PlanStore { return agent.NewMemoryPlanStore() }) +} + +type script []string + +func (script *script) Name() string { return "test/script" } + +func (script *script) Complete(context.Context, string, string) (string, error) { + if len(*script) == 0 { + return "", errors.New("no programs left") + } + program := (*script)[0] + *script = (*script)[1:] + return program, nil +} + +type world struct { + mode codemode.CodeMode + runner sandbox.Runner + executed *[]string + failOn map[string]bool +} + +func newWorld(t *testing.T) *world { + t.Helper() + executed := &[]string{} + world := &world{executed: executed, failOn: map[string]bool{}} + source := codemode.Source{ + Registry: capability.Registry{Capabilities: []capability.Capability{ + {Name: "tasks.list", RPC: "list", Description: "Lists tasks", ReadOnly: true}, + {Name: "tasks.rename", RPC: "rename", Description: "Renames a task"}, + {Name: "tasks.delete", RPC: "delete", Description: "Deletes a task", NeedsApproval: true}, + }}, + Execute: func(_ context.Context, rpc string, input json.RawMessage) (json.RawMessage, error) { + *executed = append(*executed, rpc+string(input)) + if world.failOn[string(input)] { + return nil, errors.New("task is locked") + } + return json.RawMessage(`{"tasks":[{"id":1},{"id":2}]}`), nil + }, + } + mode, err := codemode.FromSource(source, capability.Caller{}) + if err != nil { + t.Fatal(err) + } + runner, err := goja.New(sandbox.Options{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { runner.Close() }) + world.mode, world.runner = mode, runner + return world +} + +const deleteBoth = ` + const { tasks } = codemode.execute("tasks.list", {}); + for (const task of tasks) codemode.execute("tasks.delete", { id: task.id }); + return "done";` + +type clock struct{ now time.Time } + +func (clock *clock) Now() time.Time { return clock.now } + +func hold(t *testing.T, world *world, plans *agent.Plans, owner string) *agent.Pending { + t.Helper() + model := &script{deleteBoth} + _, err := agent.Run(context.Background(), world.mode, model, "delete both", agent.Options{Runner: world.runner, Plans: plans, PlanOwner: owner}) + var pending *agent.Pending + if !errors.As(err, &pending) { + t.Fatalf("err = %v, want *agent.Pending", err) + } + return pending +} + +func TestAPlanWaitsInTheInboxUntilApproved(t *testing.T) { + world := newWorld(t) + var events []agent.Event + time0 := &clock{now: time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC)} + plans := agent.NewPlans(agent.NewMemoryPlanStore(), agent.PlanOptions{TTL: time.Hour, Now: time0.Now, + OnEvent: func(event agent.Event) { events = append(events, event) }}) + + pending := hold(t, world, plans, "ada") + if pending.ID == "" || pending.RunID == "" || !pending.ExpiresAt.Equal(time0.now.Add(time.Hour)) || len(pending.Calls) != 2 { + t.Fatalf("pending = %+v", pending.Plan) + } + if strings.Join(*world.executed, ",") != "list{}" { + t.Fatalf("executed %v before approval", *world.executed) + } + + inbox, err := plans.List(context.Background(), "ada", agent.PlanPending) + if err != nil || len(inbox) != 1 || inbox[0].ID != pending.ID || inbox[0].Request != "delete both" { + t.Fatalf("inbox = %+v, err = %v", inbox, err) + } + + time0.now = time0.now.Add(10 * time.Minute) + plan, err := plans.Approve(context.Background(), world.mode, "ada", pending.ID) + if err != nil { + t.Fatal(err) + } + if plan.Status != agent.PlanApplied || len(plan.Applied) != 2 || strings.Join(*world.executed, ",") != `list{},delete{"id":1},delete{"id":2}` { + t.Fatalf("plan = %+v, executed = %v", plan, *world.executed) + } + var path []string + for _, change := range plan.History { + path = append(path, string(change.Status)) + } + if strings.Join(path, ">") != "pending>applying>applied" || plan.History[1].By != "ada" { + t.Fatalf("history = %+v", plan.History) + } + + _, err = plans.Approve(context.Background(), world.mode, "ada", pending.ID) + if !errors.Is(err, agent.ErrPlanDecided) || !strings.Contains(err.Error(), "is already applied (by ada at 2026-11-16T12:10:00Z)") { + t.Fatalf("second approve: %v", err) + } + if _, err := plans.Approve(context.Background(), world.mode, "grace", pending.ID); !errors.Is(err, agent.ErrNoPlan) { + t.Fatalf("another owner: %v", err) + } + + var kinds []string + for _, event := range events { + kinds = append(kinds, event.Kind) + if event.PlanID != pending.ID || event.RunID != pending.RunID { + t.Fatalf("event %+v does not carry the plan and run", event) + } + } + if strings.Join(kinds, ",") != "plan.held,plan.applying,call.done,call.done,plan.applied" { + t.Fatalf("events = %v", kinds) + } +} + +func TestARejectedPlanNeverRuns(t *testing.T) { + world := newWorld(t) + plans := agent.NewPlans(agent.NewMemoryPlanStore(), agent.PlanOptions{}) + pending := hold(t, world, plans, "ada") + + plan, err := plans.Reject(context.Background(), "ada", pending.ID, "not today") + if err != nil || plan.Status != agent.PlanRejected || plan.History[1].Note != "not today" { + t.Fatalf("plan = %+v, err = %v", plan, err) + } + if _, err := plans.Approve(context.Background(), world.mode, "ada", pending.ID); !errors.Is(err, agent.ErrPlanDecided) { + t.Fatalf("approved a rejected plan: %v", err) + } + if len(*world.executed) != 1 { + t.Fatalf("executed = %v", *world.executed) + } +} + +func TestAPlanExpiresWhenNobodyDecides(t *testing.T) { + world := newWorld(t) + time0 := &clock{now: time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC)} + var expired int + plans := agent.NewPlans(agent.NewMemoryPlanStore(), agent.PlanOptions{TTL: time.Hour, Now: time0.Now, + OnEvent: func(event agent.Event) { + if event.Kind == agent.EventPlanExpired { + expired++ + } + }}) + pending := hold(t, world, plans, "ada") + + time0.now = time0.now.Add(2 * time.Hour) + listed, err := plans.List(context.Background(), "ada", "") + if err != nil || len(listed) != 1 || listed[0].Status != agent.PlanExpired { + t.Fatalf("listed = %+v, err = %v", listed, err) + } + _, err = plans.Approve(context.Background(), world.mode, "ada", pending.ID) + if !errors.Is(err, agent.ErrPlanExpired) || !strings.Contains(err.Error(), "expired at 2026-11-16T13:00:00Z") { + t.Fatalf("approve after expiry: %v", err) + } + if expired != 1 || len(*world.executed) != 1 { + t.Fatalf("expired events = %d, executed = %v", expired, *world.executed) + } +} + +func TestAFailedCallStopsThePlanAndSaysWhich(t *testing.T) { + world := newWorld(t) + world.failOn[`{"id":1}`] = true + plans := agent.NewPlans(agent.NewMemoryPlanStore(), agent.PlanOptions{}) + pending := hold(t, world, plans, "ada") + + plan, err := plans.Approve(context.Background(), world.mode, "ada", pending.ID) + if err == nil || !strings.Contains(err.Error(), "plan "+pending.ID+": call 1 of 2 (tasks.delete):") || !strings.Contains(err.Error(), "task is locked") { + t.Fatalf("err = %v", err) + } + if plan.Status != agent.PlanFailed || len(plan.Applied) != 1 || plan.Applied[0].Error == "" { + t.Fatalf("plan = %+v", plan) + } + if stored, _ := plans.Get(context.Background(), "ada", pending.ID); stored.Status != agent.PlanFailed { + t.Fatalf("stored status = %s", stored.Status) + } +} + +func TestAPlanResumesAfterACrash(t *testing.T) { + world := newWorld(t) + store := agent.NewMemoryPlanStore() + plans := agent.NewPlans(store, agent.PlanOptions{}) + pending := hold(t, world, plans, "ada") + + // Simulate a crash after the first delete: applying, one result recorded. + crashed, _ := store.Get(context.Background(), "ada", pending.ID) + crashed.Status = agent.PlanApplying + crashed.Applied = []codemode.Call{{Name: "tasks.delete", Input: crashed.Calls[0].Input}} + if err := store.Update(context.Background(), &crashed); err != nil { + t.Fatal(err) + } + + if _, err := plans.Approve(context.Background(), world.mode, "ada", pending.ID); !errors.Is(err, agent.ErrPlanDecided) { + t.Fatalf("approve on an applying plan: %v", err) + } + plan, err := plans.Resume(context.Background(), world.mode, "ada", pending.ID) + if err != nil || plan.Status != agent.PlanApplied { + t.Fatalf("plan = %+v, err = %v", plan, err) + } + if strings.Join(*world.executed, ",") != `list{},delete{"id":2}` { + t.Fatalf("executed = %v; resume must skip the recorded call", *world.executed) + } +} + +func TestTwoApprovalsAtOnceApplyOnce(t *testing.T) { + world := newWorld(t) + plans := agent.NewPlans(agent.NewMemoryPlanStore(), agent.PlanOptions{}) + pending := hold(t, world, plans, "ada") + + var wait sync.WaitGroup + var mutex sync.Mutex + won := 0 + for range 8 { + wait.Add(1) + go func() { + defer wait.Done() + if _, err := plans.Approve(context.Background(), world.mode, "ada", pending.ID); err == nil { + mutex.Lock() + won++ + mutex.Unlock() + } + }() + } + wait.Wait() + if won != 1 { + t.Fatalf("%d approvals succeeded", won) + } +} + +func TestEveryRunErrorNamesTheRunAndTheStage(t *testing.T) { + world := newWorld(t) + var events []agent.Event + model := &script{`throw new Error("typo")`, `throw new Error("typo")`} + result, err := agent.Run(context.Background(), world.mode, model, "list tasks", agent.Options{ + Runner: world.runner, Attempts: 2, OnEvent: func(event agent.Event) { events = append(events, event) }, + }) + var failure *agent.Error + if !errors.As(err, &failure) || failure.RunID != result.RunID || failure.Stage != agent.StageRun { + t.Fatalf("err = %#v", err) + } + if !strings.HasPrefix(err.Error(), "run "+result.RunID+": run: gave up after 2 attempts") { + t.Fatalf("message = %q", err.Error()) + } + var kinds []string + for _, event := range events { + if event.RunID != result.RunID { + t.Fatalf("event %+v has another run ID", event) + } + kinds = append(kinds, event.Kind) + } + want := "run.started,search.done,program.written,program.failed,program.written,program.failed,run.failed" + if strings.Join(kinds, ",") != want { + t.Fatalf("events = %v", kinds) + } + + _, err = agent.Run(context.Background(), world.mode, &script{}, "list tasks", agent.Options{Runner: world.runner}) + if !errors.As(err, &failure) || failure.Stage != agent.StageGenerate { + t.Fatalf("a model failure: %v", err) + } +} diff --git a/agent/plantest/plantest.go b/agent/plantest/plantest.go new file mode 100644 index 0000000..f9f010b --- /dev/null +++ b/agent/plantest/plantest.go @@ -0,0 +1,120 @@ +// Package plantest is the contract every agent.PlanStore passes: call Run from +// the adapter's own tests with a function that returns an empty store. +package plantest + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/mukezhz/codemode/agent" + "github.com/mukezhz/codemode/codemode" +) + +func Run(t *testing.T, empty func(t *testing.T) agent.PlanStore) { + t.Helper() + ctx := context.Background() + at := time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC) + plan := func(id, owner string, status agent.PlanStatus, created time.Time) agent.Plan { + return agent.Plan{ + ID: id, Owner: owner, RunID: "run-" + id, Request: "clean up", Status: status, + Calls: []codemode.Call{{Name: "tasks.delete", Input: []byte(`{"id":1}`)}}, + CreatedAt: created, ExpiresAt: created.Add(time.Hour), + History: []agent.PlanChange{{Status: status, At: created, By: owner}}, + } + } + + t.Run("round trip", func(t *testing.T) { + store := empty(t) + want := plan("p1", "ada", agent.PlanPending, at) + if err := store.Create(ctx, want); err != nil { + t.Fatal(err) + } + got, err := store.Get(ctx, "ada", "p1") + if err != nil { + t.Fatal(err) + } + if got.RunID != "run-p1" || got.Request != "clean up" || len(got.Calls) != 1 || string(got.Calls[0].Input) != `{"id":1}` || + !got.ExpiresAt.Equal(want.ExpiresAt) || len(got.History) != 1 || got.Status != agent.PlanPending { + t.Fatalf("got %+v", got) + } + }) + + t.Run("owner scoped", func(t *testing.T) { + store := empty(t) + if err := store.Create(ctx, plan("p1", "ada", agent.PlanPending, at)); err != nil { + t.Fatal(err) + } + if _, err := store.Get(ctx, "grace", "p1"); !errors.Is(err, agent.ErrNoPlan) { + t.Fatalf("another owner read the plan: %v", err) + } + if _, err := store.Get(ctx, "ada", "nope"); !errors.Is(err, agent.ErrNoPlan) { + t.Fatalf("missing plan: %v", err) + } + listed, err := store.List(ctx, "grace", "") + if err != nil || len(listed) != 0 { + t.Fatalf("another owner listed %d plans, err %v", len(listed), err) + } + }) + + t.Run("list newest first, by status", func(t *testing.T) { + store := empty(t) + for _, item := range []agent.Plan{ + plan("old", "ada", agent.PlanPending, at), + plan("new", "ada", agent.PlanPending, at.Add(time.Minute)), + plan("done", "ada", agent.PlanApplied, at.Add(2*time.Minute)), + } { + if err := store.Create(ctx, item); err != nil { + t.Fatal(err) + } + } + pending, err := store.List(ctx, "ada", agent.PlanPending) + if err != nil || len(pending) != 2 || pending[0].ID != "new" || pending[1].ID != "old" { + t.Fatalf("pending = %+v, err %v", pending, err) + } + all, err := store.List(ctx, "ada", "") + if err != nil || len(all) != 3 || all[0].ID != "done" { + t.Fatalf("all = %+v, err %v", all, err) + } + }) + + t.Run("update is compare and set", func(t *testing.T) { + store := empty(t) + if err := store.Create(ctx, plan("p1", "ada", agent.PlanPending, at)); err != nil { + t.Fatal(err) + } + first, _ := store.Get(ctx, "ada", "p1") + second, _ := store.Get(ctx, "ada", "p1") + first.Status = agent.PlanApplying + if err := store.Update(ctx, &first); err != nil { + t.Fatal(err) + } + if first.Version != second.Version+1 { + t.Fatalf("version = %d, want %d", first.Version, second.Version+1) + } + second.Status = agent.PlanRejected + if err := store.Update(ctx, &second); !errors.Is(err, agent.ErrPlanChanged) { + t.Fatalf("a stale update won: %v", err) + } + got, _ := store.Get(ctx, "ada", "p1") + if got.Status != agent.PlanApplying { + t.Fatalf("status = %s", got.Status) + } + stranger := got + stranger.Owner = "grace" + if err := store.Update(ctx, &stranger); err == nil { + t.Fatal("another owner updated the plan") + } + }) + + t.Run("duplicate id", func(t *testing.T) { + store := empty(t) + if err := store.Create(ctx, plan("p1", "ada", agent.PlanPending, at)); err != nil { + t.Fatal(err) + } + if err := store.Create(ctx, plan("p1", "ada", agent.PlanPending, at)); err == nil { + t.Fatal("created a plan twice") + } + }) +} diff --git a/agent/sqlplans/sqlplans.go b/agent/sqlplans/sqlplans.go new file mode 100644 index 0000000..c45a58f --- /dev/null +++ b/agent/sqlplans/sqlplans.go @@ -0,0 +1,158 @@ +// Package sqlplans keeps agent plans in SQLite or Postgres through database/sql. +// It imports no driver: open the database with your own and pass it in. +package sqlplans + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "strconv" + "strings" + + "github.com/mukezhz/codemode/agent" +) + +type Dialect int + +const ( + SQLite Dialect = iota + Postgres +) + +const table = "codemode_plans" + +type store struct { + db *sql.DB + dialect Dialect +} + +var _ agent.PlanStore = (*store)(nil) + +// Open creates the codemode_plans table if it is missing. The table can share a +// database with your application's own. +func Open(ctx context.Context, db *sql.DB, dialect Dialect) (agent.PlanStore, error) { + if db == nil { + return nil, errors.New("sqlplans: db is nil") + } + plans := &store{db: db, dialect: dialect} + for _, statement := range []string{ + `CREATE TABLE IF NOT EXISTS ` + table + ` ( + id TEXT PRIMARY KEY, + owner TEXT NOT NULL, + status TEXT NOT NULL, + created_at BIGINT NOT NULL, + version INTEGER NOT NULL, + body TEXT NOT NULL + )`, + `CREATE INDEX IF NOT EXISTS ` + table + `_owner ON ` + table + ` (owner, status, created_at)`, + } { + if _, err := db.ExecContext(ctx, statement); err != nil { + return nil, fmt.Errorf("sqlplans: create table: %w", err) + } + } + return plans, nil +} + +// bind rewrites ? placeholders as $1, $2, ... for Postgres. +func (plans *store) bind(query string) string { + if plans.dialect != Postgres { + return query + } + var builder strings.Builder + number := 0 + for _, r := range query { + if r == '?' { + number++ + builder.WriteString("$" + strconv.Itoa(number)) + continue + } + builder.WriteRune(r) + } + return builder.String() +} + +func (plans *store) Create(ctx context.Context, plan agent.Plan) error { + body, err := json.Marshal(plan) + if err != nil { + return err + } + _, err = plans.db.ExecContext(ctx, plans.bind( + `INSERT INTO `+table+` (id, owner, status, created_at, version, body) VALUES (?, ?, ?, ?, ?, ?)`), + plan.ID, plan.Owner, string(plan.Status), plan.CreatedAt.UnixNano(), plan.Version, string(body)) + if err != nil { + return fmt.Errorf("sqlplans: create plan %s: %w", plan.ID, err) + } + return nil +} + +func (plans *store) Get(ctx context.Context, owner, id string) (agent.Plan, error) { + var body string + err := plans.db.QueryRowContext(ctx, plans.bind(`SELECT body FROM `+table+` WHERE id = ? AND owner = ?`), id, owner).Scan(&body) + if errors.Is(err, sql.ErrNoRows) { + return agent.Plan{}, agent.ErrNoPlan + } + if err != nil { + return agent.Plan{}, fmt.Errorf("sqlplans: get plan %s: %w", id, err) + } + return decode(body) +} + +func (plans *store) List(ctx context.Context, owner string, status agent.PlanStatus) ([]agent.Plan, error) { + query, args := `SELECT body FROM `+table+` WHERE owner = ?`, []any{owner} + if status != "" { + query, args = query+` AND status = ?`, append(args, string(status)) + } + rows, err := plans.db.QueryContext(ctx, plans.bind(query+` ORDER BY created_at DESC`), args...) + if err != nil { + return nil, fmt.Errorf("sqlplans: list plans: %w", err) + } + defer rows.Close() + listed := []agent.Plan{} + for rows.Next() { + var body string + if err := rows.Scan(&body); err != nil { + return nil, err + } + plan, err := decode(body) + if err != nil { + return nil, err + } + listed = append(listed, plan) + } + return listed, rows.Err() +} + +func (plans *store) Update(ctx context.Context, plan *agent.Plan) error { + read := plan.Version + plan.Version++ + body, err := json.Marshal(plan) + if err != nil { + plan.Version = read + return err + } + result, err := plans.db.ExecContext(ctx, plans.bind( + `UPDATE `+table+` SET status = ?, version = ?, body = ? WHERE id = ? AND owner = ? AND version = ?`), + string(plan.Status), plan.Version, string(body), plan.ID, plan.Owner, read) + if err != nil { + plan.Version = read + return fmt.Errorf("sqlplans: update plan %s: %w", plan.ID, err) + } + if changed, err := result.RowsAffected(); err != nil || changed == 1 { + return err + } + plan.Version = read + if _, err := plans.Get(ctx, plan.Owner, plan.ID); err != nil { + return err + } + return agent.ErrPlanChanged +} + +func decode(body string) (agent.Plan, error) { + var plan agent.Plan + if err := json.Unmarshal([]byte(body), &plan); err != nil { + return agent.Plan{}, fmt.Errorf("sqlplans: decode plan: %w", err) + } + return plan, nil +} diff --git a/agent/sqlplans/sqlplans_test.go b/agent/sqlplans/sqlplans_test.go new file mode 100644 index 0000000..87ecbf0 --- /dev/null +++ b/agent/sqlplans/sqlplans_test.go @@ -0,0 +1,81 @@ +package sqlplans_test + +import ( + "context" + "database/sql" + "os" + "testing" + + _ "github.com/jackc/pgx/v5/stdlib" + _ "github.com/mattn/go-sqlite3" + + "github.com/mukezhz/codemode/agent" + "github.com/mukezhz/codemode/agent/plantest" + "github.com/mukezhz/codemode/agent/sqlplans" +) + +func TestSQLitePassesTheContract(t *testing.T) { + plantest.Run(t, func(t *testing.T) agent.PlanStore { + db, err := sql.Open("sqlite3", ":memory:") + if err != nil { + t.Fatal(err) + } + db.SetMaxOpenConns(1) // every connection to :memory: is its own database + t.Cleanup(func() { db.Close() }) + store, err := sqlplans.Open(context.Background(), db, sqlplans.SQLite) + if err != nil { + t.Fatal(err) + } + return store + }) +} + +func TestAPlanSurvivesReopening(t *testing.T) { + path := t.TempDir() + "/plans.db" + ctx := context.Background() + open := func() (*sql.DB, agent.PlanStore) { + db, err := sql.Open("sqlite3", path) + if err != nil { + t.Fatal(err) + } + store, err := sqlplans.Open(ctx, db, sqlplans.SQLite) + if err != nil { + t.Fatal(err) + } + return db, store + } + db, store := open() + if err := store.Create(ctx, agent.Plan{ID: "p1", Owner: "ada", Status: agent.PlanPending}); err != nil { + t.Fatal(err) + } + db.Close() + + db, store = open() + defer db.Close() + if plan, err := store.Get(ctx, "ada", "p1"); err != nil || plan.Status != agent.PlanPending { + t.Fatalf("plan = %+v, err = %v", plan, err) + } +} + +// make test-postgres sets the DSN; without it the test is skipped. +func TestPostgresPassesTheContract(t *testing.T) { + dsn := os.Getenv("CAPABILITY_TEST_POSTGRES_DSN") + if dsn == "" { + t.Skip("CAPABILITY_TEST_POSTGRES_DSN is not set") + } + plantest.Run(t, func(t *testing.T) agent.PlanStore { + db, err := sql.Open("pgx", dsn) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { db.Close() }) + if _, err := db.Exec(`DROP TABLE IF EXISTS codemode_plans`); err != nil { + t.Fatal(err) + } + store, err := sqlplans.Open(context.Background(), db, sqlplans.Postgres) + if err != nil { + t.Fatal(err) + } + return store + }) +} diff --git a/agent/typed_test.go b/agent/typed_test.go index 48fcdde..2ff853d 100644 --- a/agent/typed_test.go +++ b/agent/typed_test.go @@ -2,14 +2,8 @@ package agent import ( "context" - "encoding/json" - "errors" "strings" "testing" - "time" - - "github.com/mukezhz/codemode/capability" - "github.com/mukezhz/codemode/codemode" ) type summary struct { @@ -58,79 +52,3 @@ func TestRunAsString(t *testing.T) { 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/examples/shop/main.go b/examples/shop/main.go index 660bc07..6f1e8c7 100644 --- a/examples/shop/main.go +++ b/examples/shop/main.go @@ -143,7 +143,7 @@ func main() { } func refund(ctx context.Context, mode codemode.CodeMode, model llm.Client, runner sandbox.Runner, request string) { - plans := agent.NewMemoryPlans(0) + plans := agent.NewPlans(agent.NewMemoryPlanStore(), agent.PlanOptions{}) _, err := agent.Run(ctx, mode, model, request, agent.Options{Runner: runner, Plans: plans, PlanOwner: "you"}) var pending *agent.Pending if !errors.As(err, &pending) { @@ -157,12 +157,13 @@ func refund(ctx context.Context, mode codemode.CodeMode, model llm.Client, runne var answer string fmt.Scanln(&answer) if answer != "y" { + plans.Reject(ctx, "you", pending.ID, "declined at the prompt") fmt.Println("nothing changed") return } - calls, err := agent.ApplyPlan(ctx, mode, plans, "you", pending.ID) + plan, err := plans.Approve(ctx, mode, "you", pending.ID) if err != nil { - log.Fatal(err) + log.Fatal(err) // names the plan and the call that failed } - fmt.Printf("ran %d call(s)\n", len(calls)) + fmt.Printf("ran %d call(s)\n", len(plan.Applied)) } diff --git a/examples/shop/main_test.go b/examples/shop/main_test.go index 236c641..18cbad5 100644 --- a/examples/shop/main_test.go +++ b/examples/shop/main_test.go @@ -65,7 +65,7 @@ func TestRevenueComesBackTyped(t *testing.T) { func TestARefundWaitsForApproval(t *testing.T) { shop, mode, runner := setup(t, "support") - plans := agent.NewMemoryPlans(0) + plans := agent.NewPlans(agent.NewMemoryPlanStore(), agent.PlanOptions{}) 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"}) @@ -73,7 +73,7 @@ func TestARefundWaitsForApproval(t *testing.T) { 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 { + if _, err := plans.Approve(context.Background(), mode, "you", pending.ID); err != nil { t.Fatal(err) } if shop.orders[0].Status != "refunded" { diff --git a/examples/taskreport/serve.go b/examples/taskreport/serve.go index 7fa5a38..2a75f0e 100644 --- a/examples/taskreport/serve.go +++ b/examples/taskreport/serve.go @@ -13,6 +13,8 @@ import ( "strings" "time" + "github.com/mukezhz/codemode/agent" + "github.com/mukezhz/codemode/agent/sqlplans" "github.com/mukezhz/codemode/codemode" "github.com/mukezhz/codemode/llm" "github.com/mukezhz/codemode/sandbox" @@ -67,7 +69,15 @@ func serve( audit = file } + // Held plans live beside the tasks, so a decision can come after a restart. + planStore, err := sqlplans.Open(ctx, tasks.DB(), sqlplans.SQLite) + if err != nil { + return err + } + plans := agent.NewPlans(planStore, agent.PlanOptions{OnEvent: agent.LogEvents(logger(config))}) + handler, err := server.New(server.Options{ + Plans: plans, Store: tasks, Full: source.Registry, Execute: source.Execute, diff --git a/examples/taskreport/server/approval_test.go b/examples/taskreport/server/approval_test.go index 3aa4452..d56ce0f 100644 --- a/examples/taskreport/server/approval_test.go +++ b/examples/taskreport/server/approval_test.go @@ -3,6 +3,7 @@ package server_test import ( "net/http" "strconv" + "strings" "testing" "github.com/mukezhz/codemode/examples/taskreport/app" @@ -67,8 +68,9 @@ func TestChatHoldsADeleteUntilTheUserApprovesIt(t *testing.T) { 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) + if response := do(t, handler, "POST", "/api/plans/"+held.ID+"/approve", "", "ada", "member"); response.Code != http.StatusConflict || + !strings.Contains(response.Body.String(), "is already applied") { + t.Fatalf("a plan applied twice: %d %s", response.Code, response.Body) } }) } @@ -86,7 +88,7 @@ func TestARejectedPlanNeverRuns(t *testing.T) { 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 { + if response := do(t, handler, "POST", "/api/plans/"+held.ID+"/approve", "", "ada", "member"); response.Code != http.StatusConflict { t.Fatalf("a rejected plan was approved: %d", response.Code) } if len(adasTasks(t, handler)) != before { @@ -94,6 +96,37 @@ func TestARejectedPlanNeverRuns(t *testing.T) { } } +func TestTheInboxListsWhatWaitsAndWhatHappened(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)) + first := decode[chatPending](t, do(t, handler, "POST", "/api/chat", `{"request":"delete one"}`, "ada", "member")).Pending + second := decode[chatPending](t, do(t, handler, "POST", "/api/chat", `{"request":"delete another"}`, "ada", "member")).Pending + do(t, handler, "POST", "/api/plans/"+first.ID+"/reject", "", "ada", "member") + + type inbox struct { + Plans []struct { + ID string `json:"id"` + Status string `json:"status"` + Request string `json:"request"` + ExpiresAt string `json:"expires_at"` + History []struct { + Status string `json:"status"` + } `json:"history"` + } `json:"plans"` + } + waiting := decode[inbox](t, do(t, handler, "GET", "/api/plans?status=pending", "", "ada", "member")).Plans + if len(waiting) != 1 || waiting[0].ID != second.ID || waiting[0].Request != "delete another" || waiting[0].ExpiresAt == "" { + t.Fatalf("pending = %+v", waiting) + } + all := decode[inbox](t, do(t, handler, "GET", "/api/plans", "", "ada", "member")).Plans + if len(all) != 2 || all[1].Status != "rejected" || len(all[1].History) != 2 { + t.Fatalf("all = %+v", all) + } + if others := decode[inbox](t, do(t, handler, "GET", "/api/plans", "", "linus", "member")).Plans; len(others) != 0 { + t.Fatalf("linus sees ada's plans: %+v", others) + } +} + func TestTheBoardDeleteButtonIsItsOwnApproval(t *testing.T) { handler := newServer(t, nil, fromGo(t)) tasks := adasTasks(t, handler) diff --git a/examples/taskreport/server/server.go b/examples/taskreport/server/server.go index d6ff468..0acc214 100644 --- a/examples/taskreport/server/server.go +++ b/examples/taskreport/server/server.go @@ -34,7 +34,7 @@ type Options struct { // 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 + Plans *agent.Plans Admins []string Model llm.Client Runner sandbox.Runner @@ -93,7 +93,7 @@ func New(options Options) (*Server, error) { options.Execute = application.Execute } if options.Plans == nil { - options.Plans = agent.NewMemoryPlans(0) + options.Plans = agent.NewPlans(agent.NewMemoryPlanStore(), agent.PlanOptions{OnEvent: agent.LogEvents(logger)}) } return &Server{ @@ -116,6 +116,7 @@ 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("GET /api/plans", server.listPlans) mux.HandleFunc("POST /api/plans/{id}/approve", server.approvePlan) mux.HandleFunc("POST /api/plans/{id}/reject", server.rejectPlan) @@ -256,7 +257,8 @@ type chatRequest struct { type chatResponse struct { 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"` + Pending *agent.Plan `json:"pending,omitempty"` + RunID string `json:"run_id"` Program string `json:"program"` Attempts int `json:"attempts"` Used []capability.Match `json:"used"` @@ -372,6 +374,7 @@ func (server *Server) answer( OnChunk: onChunk, OnCall: server.audit.hook(identity), Plans: server.options.Plans, + OnEvent: agent.LogEvents(log.With("user", identity.User)), PlanOwner: identity.User, }) var held *agent.Pending @@ -380,7 +383,8 @@ func (server *Server) answer( return chatResponse{ Document: view.Document{Blocks: []view.Block{{Type: view.KindText, Text: "This needs your approval before it changes anything."}}}, - Pending: newPendingPlan(held), + Pending: &held.Plan, + RunID: result.RunID, Program: result.Source, Attempts: result.Attempts, Used: result.Matches, @@ -389,7 +393,7 @@ func (server *Server) answer( }, http.StatusOK, nil } if err != nil { - server.log.Error("chat failed", "request", body.Request, "error", err, "program", result.Source) + server.log.Error("chat failed", "run", result.RunID, "request", body.Request, "error", err, "program", result.Source) return chatResponse{}, http.StatusBadGateway, err } @@ -423,22 +427,18 @@ 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}) +func (server *Server) listPlans(writer http.ResponseWriter, request *http.Request) { + identity, err := auth.From(request.Context()) + if err != nil { + fail(writer, http.StatusUnauthorized, err) + return + } + listed, err := server.options.Plans.List(request.Context(), identity.User, agent.PlanStatus(request.URL.Query().Get("status"))) + if err != nil { + fail(writer, http.StatusInternalServerError, err) + return } - return plan + send(writer, map[string]any{"plans": listed}) } // approvePlan runs a held plan once, for the user who was shown it, against @@ -454,27 +454,13 @@ func (server *Server) approvePlan(writer http.ResponseWriter, request *http.Requ fail(writer, http.StatusUnauthorized, err) return } - calls, err := agent.ApplyPlan(request.Context(), mode, server.options.Plans, identity.User, request.PathValue("id")) + plan, err := server.options.Plans.Approve(request.Context(), mode, identity.User, request.PathValue("id")) if hook := server.audit.hook(identity); hook != nil { - for _, call := range calls { + for _, call := range plan.Applied { 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}) + server.decided(writer, plan, err) } func (server *Server) rejectPlan(writer http.ResponseWriter, request *http.Request) { @@ -483,11 +469,33 @@ func (server *Server) rejectPlan(writer http.ResponseWriter, request *http.Reque fail(writer, http.StatusUnauthorized, err) return } - if _, err := server.options.Plans.Take(request.Context(), identity.User, request.PathValue("id")); err != nil { + plan, err := server.options.Plans.Reject(request.Context(), identity.User, request.PathValue("id"), "rejected in the chat") + server.decided(writer, plan, err) +} + +// decided answers with the plan as it now stands, and a status that says why it did not move. +func (server *Server) decided(writer http.ResponseWriter, plan agent.Plan, err error) { + status := http.StatusOK + switch { + case err == nil: + case errors.Is(err, agent.ErrNoPlan): fail(writer, http.StatusNotFound, err) return + case errors.Is(err, agent.ErrPlanExpired): + status = http.StatusGone + case errors.Is(err, agent.ErrPlanDecided): + status = http.StatusConflict + default: + status = http.StatusBadRequest + } + body := map[string]any{"plan": plan} + if err != nil { + server.log.Warn("plan not applied", "plan", plan.ID, "run", plan.RunID, "error", err) + body["error"] = err.Error() } - send(writer, map[string]bool{"rejected": true}) + writer.Header().Set("Content-Type", "application/json") + writer.WriteHeader(status) + json.NewEncoder(writer).Encode(body) } func (server *Server) assets() http.Handler { diff --git a/examples/taskreport/store/store.go b/examples/taskreport/store/store.go index c86b6ce..58eede1 100644 --- a/examples/taskreport/store/store.go +++ b/examples/taskreport/store/store.go @@ -88,6 +88,9 @@ func Open(path string) (*Store, error) { return store, nil } +// DB is the application's database, for tables it shares, such as held plans. +func (store *Store) DB() *sql.DB { return store.db } + func (store *Store) SetClock(now func() time.Time) { store.now = now } func (store *Store) Close() error { return store.db.Close() } diff --git a/scripts/check-consumer.sh b/scripts/check-consumer.sh index 176a32c..38c5357 100755 --- a/scripts/check-consumer.sh +++ b/scripts/check-consumer.sh @@ -14,7 +14,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/capability/gosource" "$root/capability/jsonschema" "$root/codemode" \ - "$root/agent" "$root/llm" "$root/llm/claude" "$root/llm/openai" \ + "$root/agent" "$root/agent/sqlplans" "$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 c8da7ce7061178d4746e71d881f1feba04cde91b Mon Sep 17 00:00:00 2001 From: Mukesh Kumar Chaudhary Date: Mon, 16 Nov 2026 11:41:08 +0545 Subject: [PATCH 2/3] feat: add an approvals inbox to taskreport Plans live in the app's SQLite file. The Approvals page lists every plan from GET /api/plans with its expiry and history, and the chat shows the same view for a plan it just held. Approve and reject answer 409 for a decided plan and 410 for an expired one, with the plan as it stands. --- .../web/dist/assets/PlanView-Cf5UBqEG.js | 1 + .../web/dist/assets/chat-Doj4bXib.js | 1 + .../web/dist/assets/chat-fahH1l62.js | 1 - .../web/dist/assets/index-C8s4-fGn.js | 16 +++++ .../web/dist/assets/index-D-DTohO0.js | 15 ---- ...{index-D44oUAo0.css => index-DCxQMvnE.css} | 2 +- .../{index-B8YGsnYU.js => index-DxZkSe_0.js} | 2 +- .../web/dist/assets/plans-CeX1mx6r.js | 1 + examples/taskreport/web/dist/index.html | 4 +- examples/taskreport/web/src/api.ts | 42 ++++++++--- .../web/src/components/PlanView.tsx | 69 +++++++++++++++++++ examples/taskreport/web/src/routeTree.gen.ts | 24 ++++++- examples/taskreport/web/src/routes/__root.tsx | 1 + examples/taskreport/web/src/routes/chat.tsx | 56 +-------------- examples/taskreport/web/src/routes/plans.tsx | 33 +++++++++ examples/taskreport/web/src/styles.css | 16 +++-- 16 files changed, 196 insertions(+), 88 deletions(-) create mode 100644 examples/taskreport/web/dist/assets/PlanView-Cf5UBqEG.js create mode 100644 examples/taskreport/web/dist/assets/chat-Doj4bXib.js delete mode 100644 examples/taskreport/web/dist/assets/chat-fahH1l62.js create mode 100644 examples/taskreport/web/dist/assets/index-C8s4-fGn.js delete mode 100644 examples/taskreport/web/dist/assets/index-D-DTohO0.js rename examples/taskreport/web/dist/assets/{index-D44oUAo0.css => index-DCxQMvnE.css} (88%) rename examples/taskreport/web/dist/assets/{index-B8YGsnYU.js => index-DxZkSe_0.js} (97%) create mode 100644 examples/taskreport/web/dist/assets/plans-CeX1mx6r.js create mode 100644 examples/taskreport/web/src/components/PlanView.tsx create mode 100644 examples/taskreport/web/src/routes/plans.tsx diff --git a/examples/taskreport/web/dist/assets/PlanView-Cf5UBqEG.js b/examples/taskreport/web/dist/assets/PlanView-Cf5UBqEG.js new file mode 100644 index 0000000..9c1f2f3 --- /dev/null +++ b/examples/taskreport/web/dist/assets/PlanView-Cf5UBqEG.js @@ -0,0 +1 @@ +import{r as l,j as s,a as p}from"./index-C8s4-fGn.js";function x({plan:r}){const[e,m]=l.useState(r),[n,i]=l.useState(""),[c,o]=l.useState(!1);async function d(a){o(!0);try{const t=a?await p.approve(e.id):await p.reject(e.id);m(t.plan),i(t.error??"")}catch(t){i(t.message)}finally{o(!1)}}return s.jsxs("div",{className:`plan plan-${e.status}`,children:[s.jsxs("p",{className:"plan-title",children:[s.jsx("span",{className:`pill status-${e.status}`,children:e.status})," ",e.request]}),s.jsx("ul",{children:e.calls.map((a,t)=>s.jsxs("li",{children:[s.jsx("code",{children:a.name})," ",s.jsx("span",{className:"muted",children:JSON.stringify(a.input)}),e.applied?.[t]?.error&&s.jsxs("span",{className:"error",children:[" — ",e.applied[t].error]})]},t))}),e.status==="pending"&&s.jsxs("div",{className:"plan-actions",children:[s.jsx("button",{onClick:()=>d(!0),disabled:c,children:"Approve"}),s.jsx("button",{className:"secondary",onClick:()=>d(!1),disabled:c,children:"Reject"}),s.jsxs("span",{className:"muted",children:["expires ",u(e.expires_at)]})]}),n&&s.jsx("p",{className:"error",children:n}),s.jsx("ol",{className:"timeline",children:e.history.map((a,t)=>s.jsxs("li",{children:[s.jsx("span",{className:`dot status-${a.status}`}),a.status," · ",u(a.at),a.by&&` · ${a.by}`,a.note&&s.jsxs("span",{className:"muted",children:[" · ",a.note]})]},t))}),s.jsxs("p",{className:"muted small",children:["plan ",e.id," · run ",e.run_id]})]})}function u(r){return new Date(r).toLocaleString()}export{x as P}; diff --git a/examples/taskreport/web/dist/assets/chat-Doj4bXib.js b/examples/taskreport/web/dist/assets/chat-Doj4bXib.js new file mode 100644 index 0000000..26e3aeb --- /dev/null +++ b/examples/taskreport/web/dist/assets/chat-Doj4bXib.js @@ -0,0 +1 @@ +import{j as e,r as g,a as w}from"./index-C8s4-fGn.js";import{P as y}from"./PlanView-Cf5UBqEG.js";function $({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(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:f(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(S,{series:s.series})]});case"line":return e.jsxs("section",{className:"block",children:[e.jsx(x,{text:s.heading}),e.jsx(q,{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 S({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:f(t.value)})]},l))})}function q({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,v=152-m/i*144;return[N,v]},r=s.map((c,m)=>p(m,c.value)),n=r.map(([c,m],N)=>`${N===0?"M":"L"}${c},${m}`).join(" "),d=`${n} L${r[r.length-1][0]},152 L${r[0][0]},152 Z`,[h,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,className:"line-area"}),e.jsx("path",{d:n,className:"line-stroke"}),e.jsx("circle",{cx:h,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 f(s){return Number.isInteger(s)?String(s):s.toFixed(1)}const F=["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 I(){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(d=>[...d,{request:n}]);try{let d="";const h=await w.chatStream(n,o=>{d+=o,l(c=>b(c,{request:n,writing:d}))});l(o=>b(o,{request:n,result:h}))}catch(d){l(h=>b(h,{request:n,error:d.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."}),F.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(L,{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 L({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($,{document:s.result.document}),s.result.pending&&e.jsx(y,{plan:s.result.pending}),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{I as component}; diff --git a/examples/taskreport/web/dist/assets/chat-fahH1l62.js b/examples/taskreport/web/dist/assets/chat-fahH1l62.js deleted file mode 100644 index 6e197e7..0000000 --- a/examples/taskreport/web/dist/assets/chat-fahH1l62.js +++ /dev/null @@ -1 +0,0 @@ -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-C8s4-fGn.js b/examples/taskreport/web/dist/assets/index-C8s4-fGn.js new file mode 100644 index 0000000..b8aff62 --- /dev/null +++ b/examples/taskreport/web/dist/assets/index-C8s4-fGn.js @@ -0,0 +1,16 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/chat-Doj4bXib.js","assets/PlanView-Cf5UBqEG.js","assets/plans-CeX1mx6r.js"])))=>i.map(i=>d[i]); +(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 Wv(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var _f={exports:{}},fu={};var tm;function Fv(){if(tm)return fu;tm=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 em;function $v(){return em||(em=1,_f.exports=Fv()),_f.exports}var k=$v(),Ef={exports:{}},ut={};var nm;function Pv(){if(nm)return ut;nm=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,lt){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,lt)}}if(vt)return lt=lt(A),vt=F===""?"."+ee(A,0):F,et(lt)?(Z="",vt!=null&&(Z=vt.replace(bt,"$&/")+"/"),N(lt,q,Z,"",function(Qe){return Qe})):lt!=null&&(P(lt)&&(lt=ct(lt,Z+(lt.key==null||A&&A.key===lt.key?"":(""+lt.key).replace(bt,"$&/")+"/")+vt)),q.push(lt)),1;vt=0;var Jt=F===""?".":F+":";if(et(A))for(var Ct=0;Ct>>1,zt=N[_t];if(0>>1;_tr(Z,nt))Fr(lt,Z)?(N[_t]=lt,N[F]=nt,_t=F):(N[_t]=Z,N[q]=nt,_t=q);else if(Fr(lt,nt))N[_t]=lt,N[F]=nt,_t=F;else break t}}return V}function r(N,V){var nt=N.sortIndex-V.sortIndex;return nt!==0?nt: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=nt,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=nt,c(d,N),s(y)===null&&N===s(d)&&(E?(Y(L),L=-1):E=!0,Bt(et,nt-_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 nt=b;b=V;try{return N.apply(this,arguments)}finally{b=nt}}}})(Af)),Af}var um;function tg(){return um||(um=1,zf.exports=Iv()),zf.exports}var Rf={exports:{}},te={};var im;function eg(){if(im)return te;im=1;var a=Su();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(),Rf.exports=eg(),Rf.exports}var sm;function lg(){if(sm)return ou;sm=1;var a=tg(),c=Su(),s=ng();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),lt=A(null),it=A(null),vt=A(null);function Jt(t,e){switch(Z(it,e),Z(lt,t),Z(F,null),e.nodeType){case 9:case 11:t=(t=e.documentElement)&&(t=t.namespaceURI)?Th(t):0;break;default:if(t=e.tagName,e=e.namespaceURI)e=Th(e),t=zh(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(lt),q(it)}function Qe(t){t.memoizedState!==null&&Z(vt,t);var e=F.current,n=zh(e,t.type);e!==n&&(Z(lt,t),Z(F,n))}function Ve(t){lt.current===t&&(q(F),q(lt)),vt.current===t&&(q(vt),uu._currentValue=nt)}var mn,da;function He(t){if(mn===void 0)try{throw Error()}catch(n){var e=n.stack.trim().match(/\n( *(at )?)/);mn=e&&e[1]||"",da=-1)":-1u||_[l]!==C[u]){var B=` +`+_[l].replace(" at new "," at ");return t.displayName&&B.includes("")&&(B=B.replace("",t.displayName)),B}while(1<=l&&0<=u);break}}}finally{Sl=!1,Error.prepareStackTrace=n}return(n=t?t.displayName||t.name:"")?He(n):""}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="",n=null;do e+=ha(t,n),n=t,t=t.return;while(t);return e}catch(l){return` +Error generating stack: `+l.message+` +`+l.stack}}var Kn=Object.prototype.hasOwnProperty,ma=a.unstable_scheduleCallback,ya=a.unstable_cancelCallback,bu=a.unstable_shouldYield,It=a.unstable_requestPaint,Nt=a.unstable_now,Jn=a.unstable_getCurrentPriorityLevel,va=a.unstable_ImmediatePriority,eo=a.unstable_UserBlockingPriority,_u=a.unstable_NormalPriority,x0=a.unstable_LowPriority,no=a.unstable_IdlePriority,D0=a.log,U0=a.unstable_setDisableYieldValue,ga=null,re=null;function yn(t){if(typeof D0=="function"&&U0(t),re&&typeof re.setStrictMode=="function")try{re.setStrictMode(ga,t)}catch{}}var de=Math.clz32?Math.clz32:B0,L0=Math.log,N0=Math.LN2;function B0(t){return t>>>=0,t===0?32:31-(L0(t)/N0|0)|0}var Eu=256,Tu=262144,zu=4194304;function kn(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 Au(t,e,n){var l=t.pendingLanes;if(l===0)return 0;var u=0,i=t.suspendedLanes,o=t.pingedLanes;t=t.warmLanes;var v=l&134217727;return v!==0?(l=v&~i,l!==0?u=kn(l):(o&=v,o!==0?u=kn(o):n||(n=v&~t,n!==0&&(u=kn(n))))):(v=l&~i,v!==0?u=kn(v):o!==0?u=kn(o):n||(n=l&~t,n!==0&&(u=kn(n)))),u===0?0:e!==0&&e!==u&&(e&i)===0&&(i=u&-u,n=e&-e,i>=n||i===32&&(n&4194048)!==0)?e:u}function pa(t,e){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&e)===0}function H0(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 lo(){var t=zu;return zu<<=1,(zu&62914560)===0&&(zu=4194304),t}function sc(t){for(var e=[],n=0;31>n;n++)e.push(t);return e}function Sa(t,e){t.pendingLanes|=e,e!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function j0(t,e,n,l,u,i){var o=t.pendingLanes;t.pendingLanes=n,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=n,t.entangledLanes&=n,t.errorRecoveryDisabledLanes&=n,t.shellSuspendCounter=0;var v=t.entanglements,_=t.expirationTimes,C=t.hiddenUpdates;for(n=o&~n;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var Q0=/[\n"\\]/g;function _e(t){return t.replace(Q0,function(e){return"\\"+e.charCodeAt(0).toString(16)+" "})}function mc(t,e,n,l,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?yc(t,o,be(e)):n!=null?yc(t,o,be(n)):l!=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 go(t,e,n,l,u,i,o,v){if(i!=null&&typeof i!="function"&&typeof i!="symbol"&&typeof i!="boolean"&&(t.type=i),e!=null||n!=null){if(!(i!=="submit"&&i!=="reset"||e!=null)){hc(t);return}n=n!=null?""+be(n):"",e=e!=null?""+be(e):n,v||e===t.value||(t.value=e),t.defaultValue=e}l=l??u,l=typeof l!="function"&&typeof l!="symbol"&&!!l,t.checked=v?t.checked:!!l,t.defaultChecked=!!l,o!=null&&typeof o!="function"&&typeof o!="symbol"&&typeof o!="boolean"&&(t.name=o),hc(t)}function yc(t,e,n){e==="number"&&Mu(t.ownerDocument)===t||t.defaultValue===""+n||(t.defaultValue=""+n)}function Al(t,e,n,l){if(t=t.options,e){e={};for(var u=0;u"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),bc=!1;if(ke)try{var Ta={};Object.defineProperty(Ta,"passive",{get:function(){bc=!0}}),window.addEventListener("test",Ta,Ta),window.removeEventListener("test",Ta,Ta)}catch{bc=!1}var gn=null,_c=null,xu=null;function zo(){if(xu)return xu;var t,e=_c,n=e.length,l,u="value"in gn?gn.value:gn.textContent,i=u.length;for(t=0;t=Ra),xo=" ",Do=!1;function Uo(t,e){switch(t){case"keyup":return gy.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Lo(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Cl=!1;function Sy(t,e){switch(t){case"compositionend":return Lo(e);case"keypress":return e.which!==32?null:(Do=!0,xo);case"textInput":return t=e.data,t===xo&&Do?null:t;default:return null}}function by(t,e){if(Cl)return t==="compositionend"||!Rc&&Uo(t,e)?(t=zo(),xu=_c=gn=null,Cl=!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:n,offset:e-t};t=l}t:{for(;n;){if(n.nextSibling){n=n.nextSibling;break t}n=n.parentNode}n=void 0}n=Go(n)}}function Qo(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?Qo(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function Vo(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var e=Mu(t.document);e instanceof t.HTMLIFrameElement;){try{var n=typeof e.contentWindow.location.href=="string"}catch{n=!1}if(n)t=e.contentWindow;else break;e=Mu(t.document)}return e}function Cc(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 My=ke&&"documentMode"in document&&11>=document.documentMode,xl=null,xc=null,xa=null,Dc=!1;function Zo(t,e,n){var l=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Dc||xl==null||xl!==Mu(l)||(l=xl,"selectionStart"in l&&Cc(l)?l={start:l.selectionStart,end:l.selectionEnd}:(l=(l.ownerDocument&&l.ownerDocument.defaultView||window).getSelection(),l={anchorNode:l.anchorNode,anchorOffset:l.anchorOffset,focusNode:l.focusNode,focusOffset:l.focusOffset}),xa&&Ca(xa,l)||(xa=l,l=Ti(xc,"onSelect"),0>=o,u-=o,je=1<<32-de(e)+u|n<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 n(O,$),yt&&Fe(O,ot),I;if($===null){for(;otot?(mt=$,$=null):mt=$.sibling;var wn=x(O,$,pt.value,H);if(wn===null){$===null&&($=mt);break}t&&$&&wn.alternate===null&&e(O,$),z=i(wn,z,ot),gt===null?I=wn:gt.sibling=wn,gt=wn,$=mt}if(pt.done)return n(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($=l($);!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(kv){return e(O,kv)}),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){n(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&&ul(I)===z.type){n(O,z.sibling),H=u(z,M.props),Ha(H,M),H.return=O,O=H;break t}n(O,z);break}else e(O,z);z=z.sibling}M.type===E?(H=tl(M.props.children,O.mode,H,M.key),H.return=O,O=H):(H=Yu(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){n(O,z.sibling),H=u(z,M.children||[]),H.return=O,O=H;break t}else{n(O,z);break}else e(O,z);z=z.sibling}H=qc(M,O.mode,H),H.return=O,O=H}return o(O);case Q:return M=ul(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,Ju(M),H);if(M.$$typeof===K)return Ot(O,z,Qu(O,M),H);ku(O,M)}return typeof M=="string"&&M!==""||typeof M=="number"||typeof M=="bigint"?(M=""+M,z!==null&&z.tag===6?(n(O,z.sibling),H=u(z,M),H.return=O,O=H):(n(O,z),H=jc(M,O.mode,H),H.return=O,O=H),o(O)):n(O,z)}return function(O,z,M,H){try{Ba=0;var I=Ot(O,z,M,H);return Gl=null,I}catch($){if($===Yl||$===Zu)throw $;var gt=me(29,$,null,O.mode);return gt.lanes=H,gt.return=O,gt}}}var cl=mr(!0),yr=mr(!1),En=!1;function Fc(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function $c(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 Tn(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function zn(t,e,n){var l=t.updateQueue;if(l===null)return null;if(l=l.shared,(St&2)!==0){var u=l.pending;return u===null?e.next=e:(e.next=u.next,u.next=e),l.pending=e,e=wu(t),Po(t,null,n),e}return qu(t,l,e,n),wu(t)}function ja(t,e,n){if(e=e.updateQueue,e!==null&&(e=e.shared,(n&4194048)!==0)){var l=e.lanes;l&=t.pendingLanes,n|=l,e.lanes=n,uo(t,n)}}function Pc(t,e){var n=t.updateQueue,l=t.alternate;if(l!==null&&(l=l.updateQueue,n===l)){var u=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};i===null?u=i=o:i=i.next=o,n=n.next}while(n!==null);i===null?u=i=e:i=i.next=e}else u=i=e;n={baseState:l.baseState,firstBaseUpdate:u,lastBaseUpdate:i,shared:l.shared,callbacks:l.callbacks},t.updateQueue=n;return}t=n.lastBaseUpdate,t===null?n.firstBaseUpdate=e:t.next=e,n.lastBaseUpdate=e}var Ic=!1;function qa(){if(Ic){var t=wl;if(t!==null)throw t}}function wa(t,e,n,l){Ic=!1;var u=t.updateQueue;En=!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:(l&x)===x){x!==0&&x===ql&&(Ic=!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=n;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:En=!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),Cn|=o,t.lanes=o,t.memoizedState=j}}function vr(t,e){if(typeof t!="function")throw Error(f(191,t));t.call(e)}function gr(t,e){var n=t.callbacks;if(n!==null)for(t.callbacks=null,t=0;ti?i:8;var o=N.T,v={};N.T=v,ps(t,!1,e,n);try{var _=u(),C=N.S;if(C!==null&&C(v,_),_!==null&&typeof _=="object"&&typeof _.then=="function"){var B=jy(_,l);Xa(t,e,B,Se(t))}else Xa(t,e,l,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 Qy(){}function vs(t,e,n,l){if(t.tag!==5)throw Error(f(476));var u=Wr(t).queue;kr(t,u,e,nt,n===null?Qy:function(){return Fr(t),n(l)})}function Wr(t){var e=t.memoizedState;if(e!==null)return e;e={memoizedState:nt,baseState:nt,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:tn,lastRenderedState:nt},next:null};var n={};return e.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:tn,lastRenderedState:n},next:null},t.memoizedState=e,t=t.alternate,t!==null&&(t.memoizedState=e),e}function Fr(t){var e=Wr(t);e.next===null&&(e=t.alternate.memoizedState),Xa(t,e.next.queue,{},Se())}function gs(){return Ft(uu)}function $r(){return wt().memoizedState}function Pr(){return wt().memoizedState}function Vy(t){for(var e=t.return;e!==null;){switch(e.tag){case 24:case 3:var n=Se();t=Tn(n);var l=zn(e,t,n);l!==null&&(fe(l,e,n),ja(l,e,n)),e={cache:Kc()},t.payload=e;return}e=e.return}}function Zy(t,e,n){var l=Se();n={lane:l,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},ai(t)?td(e,n):(n=Bc(t,e,n,l),n!==null&&(fe(n,t,l),ed(n,e,l)))}function Ir(t,e,n){var l=Se();Xa(t,e,n,l)}function Xa(t,e,n,l){var u={lane:l,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(ai(t))td(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,n);if(u.hasEagerState=!0,u.eagerState=v,he(v,o))return qu(t,e,u,0),Mt===null&&ju(),!1}catch{}if(n=Bc(t,e,u,l),n!==null)return fe(n,t,l),ed(n,e,l),!0}return!1}function ps(t,e,n,l){if(l={lane:2,revertLane:Fs(),gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},ai(t)){if(e)throw Error(f(479))}else e=Bc(t,n,l,2),e!==null&&fe(e,t,2)}function ai(t){var e=t.alternate;return t===st||e!==null&&e===st}function td(t,e){Ql=$u=!0;var n=t.pending;n===null?e.next=e:(e.next=n.next,n.next=e),t.pending=e}function ed(t,e,n){if((n&4194048)!==0){var l=e.lanes;l&=t.pendingLanes,n|=l,e.lanes=n,uo(t,n)}}var Qa={readContext:Ft,use:ti,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 nd={readContext:Ft,use:ti,useCallback:function(t,e){return ne().memoizedState=[t,e===void 0?null:e],t},useContext:Ft,useEffect:wr,useImperativeHandle:function(t,e,n){n=n!=null?n.concat([t]):null,ni(4194308,4,Qr.bind(null,e,t),n)},useLayoutEffect:function(t,e){return ni(4194308,4,t,e)},useInsertionEffect:function(t,e){ni(4,2,t,e)},useMemo:function(t,e){var n=ne();e=e===void 0?null:e;var l=t();if(sl){yn(!0);try{t()}finally{yn(!1)}}return n.memoizedState=[l,e],l},useReducer:function(t,e,n){var l=ne();if(n!==void 0){var u=n(e);if(sl){yn(!0);try{n(e)}finally{yn(!1)}}}else u=e;return l.memoizedState=l.baseState=u,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:u},l.queue=t,t=t.dispatch=Zy.bind(null,st,t),[l.memoizedState,t]},useRef:function(t){var e=ne();return t={current:t},e.memoizedState=t},useState:function(t){t=rs(t);var e=t.queue,n=Ir.bind(null,st,e);return e.dispatch=n,[t.memoizedState,n]},useDebugValue:ms,useDeferredValue:function(t,e){var n=ne();return ys(n,t,e)},useTransition:function(){var t=rs(!1);return t=kr.bind(null,st,t.queue,!0,!1),ne().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,e,n){var l=st,u=ne();if(yt){if(n===void 0)throw Error(f(407));n=n()}else{if(n=e(),Mt===null)throw Error(f(349));(ht&127)!==0||Tr(l,e,n)}u.memoizedState=n;var i={value:n,getSnapshot:e};return u.queue=i,wr(Ar.bind(null,l,i,t),[t]),l.flags|=2048,Zl(9,{destroy:void 0},zr.bind(null,l,i,n,e),null),n},useId:function(){var t=ne(),e=Mt.identifierPrefix;if(yt){var n=qe,l=je;n=(l&~(1<<32-de(l)-1)).toString(32)+n,e="_"+e+"R_"+n,n=Pu++,0<\/script>",i=i.removeChild(i.firstChild);break;case"select":i=typeof l.is=="string"?o.createElement("select",{is:l.is}):o.createElement("select"),l.multiple?i.multiple=!0:l.size&&(i.size=l.size);break;default:i=typeof l.is=="string"?o.createElement(u,{is:l.is}):o.createElement(u)}}i[kt]=e,i[le]=l;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,l),u){case"button":case"input":case"select":case"textarea":l=!!l.autoFocus;break t;case"img":l=!0;break t;default:l=!1}l&&nn(e)}}return Dt(e),Us(e,e.type,t===null?null:t.memoizedProps,e.pendingProps,n),null;case 6:if(t&&e.stateNode!=null)t.memoizedProps!==l&&nn(e);else{if(typeof l!="string"&&e.stateNode===null)throw Error(f(166));if(t=it.current,Hl(e)){if(t=e.stateNode,n=e.memoizedProps,l=null,u=Wt,u!==null)switch(u.tag){case 27:case 5:l=u.memoizedProps}t[kt]=e,t=!!(t.nodeValue===n||l!==null&&l.suppressHydrationWarning===!0||_h(t.nodeValue,n)),t||bn(e,!0)}else t=zi(t).createTextNode(l),t[kt]=e,e.stateNode=t}return Dt(e),null;case 31:if(n=e.memoizedState,t===null||t.memoizedState!==null){if(l=Hl(e),n!==null){if(t===null){if(!l)throw Error(f(318));if(t=e.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(f(557));t[kt]=e}else el(),(e.flags&128)===0&&(e.memoizedState=null),e.flags|=4;Dt(e),t=!1}else n=Xc(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=n),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(l=e.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(u=Hl(e),l!==null&&l.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 el(),(e.flags&128)===0&&(e.memoizedState=null),e.flags|=4;Dt(e),u=!1}else u=Xc(),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=n,e):(n=l!==null,t=t!==null&&t.memoizedState!==null,n&&(l=e.child,u=null,l.alternate!==null&&l.alternate.memoizedState!==null&&l.alternate.memoizedState.cachePool!==null&&(u=l.alternate.memoizedState.cachePool.pool),i=null,l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(i=l.memoizedState.cachePool.pool),i!==u&&(l.flags|=2048)),n!==t&&n&&(e.child.flags|=8192),fi(e,e.updateQueue),Dt(e),null);case 4:return Ct(),t===null&&tf(e.stateNode.containerInfo),Dt(e),null;case 10:return Pe(e.type),Dt(e),null;case 19:if(q(qt),l=e.memoizedState,l===null)return Dt(e),null;if(u=(e.flags&128)!==0,i=l.rendering,i===null)if(u)Za(l,!1);else{if(jt!==0||t!==null&&(t.flags&128)!==0)for(t=e.child;t!==null;){if(i=Fu(t),i!==null){for(e.flags|=128,Za(l,!1),t=i.updateQueue,e.updateQueue=t,fi(e,t),e.subtreeFlags=0,t=n,n=e.child;n!==null;)Io(n,t),n=n.sibling;return Z(qt,qt.current&1|2),yt&&Fe(e,l.treeForkCount),e.child}t=t.sibling}l.tail!==null&&Nt()>mi&&(e.flags|=128,u=!0,Za(l,!1),e.lanes=4194304)}else{if(!u)if(t=Fu(i),t!==null){if(e.flags|=128,u=!0,t=t.updateQueue,e.updateQueue=t,fi(e,t),Za(l,!0),l.tail===null&&l.tailMode==="hidden"&&!i.alternate&&!yt)return Dt(e),null}else 2*Nt()-l.renderingStartTime>mi&&n!==536870912&&(e.flags|=128,u=!0,Za(l,!1),e.lanes=4194304);l.isBackwards?(i.sibling=e.child,e.child=i):(t=l.last,t!==null?t.sibling=i:e.child=i,l.last=i)}return l.tail!==null?(t=l.tail,l.rendering=t,l.tail=t.sibling,l.renderingStartTime=Nt(),t.sibling=null,n=qt.current,Z(qt,u?n&1|2:n&1),yt&&Fe(e,l.treeForkCount),t):(Dt(e),null);case 22:case 23:return ve(e),es(),l=e.memoizedState!==null,t!==null?t.memoizedState!==null!==l&&(e.flags|=8192):l&&(e.flags|=8192),l?(n&536870912)!==0&&(e.flags&128)===0&&(Dt(e),e.subtreeFlags&6&&(e.flags|=8192)):Dt(e),n=e.updateQueue,n!==null&&fi(e,n.retryQueue),n=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(n=t.memoizedState.cachePool.pool),l=null,e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(l=e.memoizedState.cachePool.pool),l!==n&&(e.flags|=2048),t!==null&&q(al),null;case 24:return n=null,t!==null&&(n=t.memoizedState.cache),e.memoizedState.cache!==n&&(e.flags|=2048),Pe(Yt),Dt(e),null;case 25:return null;case 30:return null}throw Error(f(156,e.tag))}function Fy(t,e){switch(Yc(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));el()}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));el()}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),es(),t!==null&&q(al),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 Rd(t,e){switch(Yc(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),es(),t!==null&&q(al);break;case 24:Pe(Yt)}}function Ka(t,e){try{var n=e.updateQueue,l=n!==null?n.lastEffect:null;if(l!==null){var u=l.next;n=u;do{if((n.tag&t)===t){l=void 0;var i=n.create,o=n.inst;l=i(),o.destroy=l}n=n.next}while(n!==u)}}catch(v){Tt(e,e.return,v)}}function On(t,e,n){try{var l=e.updateQueue,u=l!==null?l.lastEffect:null;if(u!==null){var i=u.next;l=i;do{if((l.tag&t)===t){var o=l.inst,v=o.destroy;if(v!==void 0){o.destroy=void 0,u=e;var _=n,C=v;try{C()}catch(B){Tt(u,_,B)}}}l=l.next}while(l!==i)}}catch(B){Tt(e,e.return,B)}}function Od(t){var e=t.updateQueue;if(e!==null){var n=t.stateNode;try{gr(e,n)}catch(l){Tt(t,t.return,l)}}}function Md(t,e,n){n.props=fl(t.type,t.memoizedProps),n.state=t.memoizedState;try{n.componentWillUnmount()}catch(l){Tt(t,e,l)}}function Ja(t,e){try{var n=t.ref;if(n!==null){switch(t.tag){case 26:case 27:case 5:var l=t.stateNode;break;case 30:l=t.stateNode;break;default:l=t.stateNode}typeof n=="function"?t.refCleanup=n(l):n.current=l}}catch(u){Tt(t,e,u)}}function we(t,e){var n=t.ref,l=t.refCleanup;if(n!==null)if(typeof l=="function")try{l()}catch(u){Tt(t,e,u)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof n=="function")try{n(null)}catch(u){Tt(t,e,u)}else n.current=null}function Cd(t){var e=t.type,n=t.memoizedProps,l=t.stateNode;try{t:switch(e){case"button":case"input":case"select":case"textarea":n.autoFocus&&l.focus();break t;case"img":n.src?l.src=n.src:n.srcSet&&(l.srcset=n.srcSet)}}catch(u){Tt(t,t.return,u)}}function Ls(t,e,n){try{var l=t.stateNode;pv(l,t.type,n,e),l[le]=e}catch(u){Tt(t,t.return,u)}}function xd(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&Nn(t.type)||t.tag===4}function Ns(t){t:for(;;){for(;t.sibling===null;){if(t.return===null||xd(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&&Nn(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 Bs(t,e,n){var l=t.tag;if(l===5||l===6)t=t.stateNode,e?(n.nodeType===9?n.body:n.nodeName==="HTML"?n.ownerDocument.body:n).insertBefore(t,e):(e=n.nodeType===9?n.body:n.nodeName==="HTML"?n.ownerDocument.body:n,e.appendChild(t),n=n._reactRootContainer,n!=null||e.onclick!==null||(e.onclick=Je));else if(l!==4&&(l===27&&Nn(t.type)&&(n=t.stateNode,e=null),t=t.child,t!==null))for(Bs(t,e,n),t=t.sibling;t!==null;)Bs(t,e,n),t=t.sibling}function oi(t,e,n){var l=t.tag;if(l===5||l===6)t=t.stateNode,e?n.insertBefore(t,e):n.appendChild(t);else if(l!==4&&(l===27&&Nn(t.type)&&(n=t.stateNode),t=t.child,t!==null))for(oi(t,e,n),t=t.sibling;t!==null;)oi(t,e,n),t=t.sibling}function Dd(t){var e=t.stateNode,n=t.memoizedProps;try{for(var l=t.type,u=e.attributes;u.length;)e.removeAttributeNode(u[0]);Pt(e,l,n),e[kt]=t,e[le]=n}catch(i){Tt(t,t.return,i)}}var ln=!1,Qt=!1,Hs=!1,Ud=typeof WeakSet=="function"?WeakSet:Set,Kt=null;function $y(t,e){if(t=t.containerInfo,lf=Di,t=Vo(t),Cc(t)){if("selectionStart"in t)var n={start:t.selectionStart,end:t.selectionEnd};else t:{n=(n=t.ownerDocument)&&n.defaultView||window;var l=n.getSelection&&n.getSelection();if(l&&l.rangeCount!==0){n=l.anchorNode;var u=l.anchorOffset,i=l.focusNode;l=l.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break t}var o=0,v=-1,_=-1,C=0,B=0,j=t,x=null;e:for(;;){for(var U;j!==n||u!==0&&j.nodeType!==3||(v=o+u),j!==i||l!==0&&j.nodeType!==3||(_=o+l),j.nodeType===3&&(o+=j.nodeValue.length),(U=j.firstChild)!==null;)x=j,j=U;for(;;){if(j===t)break e;if(x===n&&++C===u&&(v=o),x===i&&++B===l&&(_=o),(U=j.nextSibling)!==null)break;j=x,x=j.parentNode}j=U}n=v===-1||_===-1?null:{start:v,end:_}}else n=null}n=n||{start:0,end:0}}else n=null;for(af={focusedElem:t,selectionRange:n},Di=!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(n=0;n title"))),Pt(i,l,n),i[kt]=t,Zt(i),l=i;break t;case"link":var o=qh("link","href",u).get(l+(n.href||""));if(o){for(var v=0;vOt&&(o=Ot,Ot=tt,tt=o);var O=Xo(v,tt),z=Xo(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;vn?32:n,N.T=null,n=Qs,Qs=null;var i=Dn,o=fn;if(Vt=0,Fl=Dn=null,fn=0,(St&6)!==0)throw Error(f(331));var v=St;if(St|=4,Qd(i.current),Yd(i,i.current,o,n),St=v,Ia(0,!1),re&&typeof re.onPostCommitFiberRoot=="function")try{re.onPostCommitFiberRoot(ga,i)}catch{}return!0}finally{V.p=u,N.T=l,ch(t,e)}}function fh(t,e,n){e=Te(n,e),e=Es(t.stateNode,e,2),t=zn(t,e,2),t!==null&&(Sa(t,2),Ye(t))}function Tt(t,e,n){if(t.tag===3)fh(t,t,n);else for(;e!==null;){if(e.tag===3){fh(e,t,n);break}else if(e.tag===1){var l=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof l.componentDidCatch=="function"&&(xn===null||!xn.has(l))){t=Te(n,t),n=od(2),l=zn(e,n,2),l!==null&&(rd(n,l,e,t),Sa(l,2),Ye(l));break}}e=e.return}}function Js(t,e,n){var l=t.pingCache;if(l===null){l=t.pingCache=new tv;var u=new Set;l.set(e,u)}else u=l.get(e),u===void 0&&(u=new Set,l.set(e,u));u.has(n)||(ws=!0,u.add(n),t=uv.bind(null,t,e,n),e.then(t,t))}function uv(t,e,n){var l=t.pingCache;l!==null&&l.delete(e),t.pingedLanes|=t.suspendedLanes&n,t.warmLanes&=~n,Mt===t&&(ht&n)===n&&(jt===4||jt===3&&(ht&62914560)===ht&&300>Nt()-hi?(St&2)===0&&$l(t,0):Ys|=n,Wl===ht&&(Wl=0)),Ye(t)}function oh(t,e){e===0&&(e=lo()),t=In(t,e),t!==null&&(Sa(t,e),Ye(t))}function iv(t){var e=t.memoizedState,n=0;e!==null&&(n=e.retryLane),oh(t,n)}function cv(t,e){var n=0;switch(t.tag){case 31:case 13:var l=t.stateNode,u=t.memoizedState;u!==null&&(n=u.retryLane);break;case 19:l=t.stateNode;break;case 22:l=t.stateNode._retryCache;break;default:throw Error(f(314))}l!==null&&l.delete(e),oh(t,n)}function sv(t,e){return ma(t,e)}var bi=null,Il=null,ks=!1,_i=!1,Ws=!1,Ln=0;function Ye(t){t!==Il&&t.next===null&&(Il===null?bi=Il=t:Il=Il.next=t),_i=!0,ks||(ks=!0,ov())}function Ia(t,e){if(!Ws&&_i){Ws=!0;do for(var n=!1,l=bi;l!==null;){if(t!==0){var u=l.pendingLanes;if(u===0)var i=0;else{var o=l.suspendedLanes,v=l.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&&(n=!0,mh(l,i))}else i=ht,i=Au(l,l===Mt?i:0,l.cancelPendingCommit!==null||l.timeoutHandle!==-1),(i&3)===0||pa(l,i)||(n=!0,mh(l,i));l=l.next}while(n);Ws=!1}}function fv(){rh()}function rh(){_i=ks=!1;var t=0;Ln!==0&&bv()&&(t=Ln);for(var e=Nt(),n=null,l=bi;l!==null;){var u=l.next,i=dh(l,e);i===0?(l.next=null,n===null?bi=u:n.next=u,u===null&&(Il=n)):(n=l,(t!==0||(i&3)!==0)&&(_i=!0)),l=u}Vt!==0&&Vt!==5||Ia(t),Ln!==0&&(Ln=0)}function dh(t,e){for(var n=t.suspendedLanes,l=t.pingedLanes,u=t.expirationTimes,i=t.pendingLanes&-62914561;0v)break;var B=_.transferSize,j=_.initiatorType;B&&Eh(j)&&(_=_.responseEnd,o+=B*(_"u"?null:document;function Nh(t,e,n){var l=ta;if(l&&typeof e=="string"&&e){var u=_e(e);u='link[rel="'+t+'"][href="'+u+'"]',typeof n=="string"&&(u+='[crossorigin="'+n+'"]'),Lh.has(u)||(Lh.add(u),t={rel:t,crossOrigin:n,href:e},l.querySelector(u)===null&&(e=l.createElement("link"),Pt(e,"link",t),Zt(e),l.head.appendChild(e)))}}function Cv(t){on.D(t),Nh("dns-prefetch",t,null)}function xv(t,e){on.C(t,e),Nh("preconnect",t,e)}function Dv(t,e,n){on.L(t,e,n);var l=ta;if(l&&t&&e){var u='link[rel="preload"][as="'+_e(e)+'"]';e==="image"&&n&&n.imageSrcSet?(u+='[imagesrcset="'+_e(n.imageSrcSet)+'"]',typeof n.imageSizes=="string"&&(u+='[imagesizes="'+_e(n.imageSizes)+'"]')):u+='[href="'+_e(t)+'"]';var i=u;switch(e){case"style":i=ea(t);break;case"script":i=na(t)}Ce.has(i)||(t=p({rel:"preload",href:e==="image"&&n&&n.imageSrcSet?void 0:t,as:e},n),Ce.set(i,t),l.querySelector(u)!==null||e==="style"&&l.querySelector(lu(i))||e==="script"&&l.querySelector(au(i))||(e=l.createElement("link"),Pt(e,"link",t),Zt(e),l.head.appendChild(e)))}}function Uv(t,e){on.m(t,e);var n=ta;if(n&&t){var l=e&&typeof e.as=="string"?e.as:"script",u='link[rel="modulepreload"][as="'+_e(l)+'"][href="'+_e(t)+'"]',i=u;switch(l){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":i=na(t)}if(!Ce.has(i)&&(t=p({rel:"modulepreload",href:t},e),Ce.set(i,t),n.querySelector(u)===null)){switch(l){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(n.querySelector(au(i)))return}l=n.createElement("link"),Pt(l,"link",t),Zt(l),n.head.appendChild(l)}}}function Lv(t,e,n){on.S(t,e,n);var l=ta;if(l&&t){var u=Tl(l).hoistableStyles,i=ea(t);e=e||"default";var o=u.get(i);if(!o){var v={loading:0,preload:null};if(o=l.querySelector(lu(i)))v.loading=5;else{t=p({rel:"stylesheet",href:t,"data-precedence":e},n),(n=Ce.get(i))&&df(t,n);var _=o=l.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,Ri(o,e,l)}o={type:"stylesheet",instance:o,count:1,state:v},u.set(i,o)}}}function Nv(t,e){on.X(t,e);var n=ta;if(n&&t){var l=Tl(n).hoistableScripts,u=na(t),i=l.get(u);i||(i=n.querySelector(au(u)),i||(t=p({src:t,async:!0},e),(e=Ce.get(u))&&hf(t,e),i=n.createElement("script"),Zt(i),Pt(i,"link",t),n.head.appendChild(i)),i={type:"script",instance:i,count:1,state:null},l.set(u,i))}}function Bv(t,e){on.M(t,e);var n=ta;if(n&&t){var l=Tl(n).hoistableScripts,u=na(t),i=l.get(u);i||(i=n.querySelector(au(u)),i||(t=p({src:t,async:!0,type:"module"},e),(e=Ce.get(u))&&hf(t,e),i=n.createElement("script"),Zt(i),Pt(i,"link",t),n.head.appendChild(i)),i={type:"script",instance:i,count:1,state:null},l.set(u,i))}}function Bh(t,e,n,l){var u=(u=it.current)?Ai(u):null;if(!u)throw Error(f(446));switch(t){case"meta":case"title":return null;case"style":return typeof n.precedence=="string"&&typeof n.href=="string"?(e=ea(n.href),n=Tl(u).hoistableStyles,l=n.get(e),l||(l={type:"style",instance:null,count:0,state:null},n.set(e,l)),l):{type:"void",instance:null,count:0,state:null};case"link":if(n.rel==="stylesheet"&&typeof n.href=="string"&&typeof n.precedence=="string"){t=ea(n.href);var i=Tl(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(lu(t)))&&!i._p&&(o.instance=i,o.state.loading=5),Ce.has(t)||(n={rel:"preload",as:"style",href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},Ce.set(t,n),i||Hv(u,t,n,o.state))),e&&l===null)throw Error(f(528,""));return o}if(e&&l!==null)throw Error(f(529,""));return null;case"script":return e=n.async,n=n.src,typeof n=="string"&&e&&typeof e!="function"&&typeof e!="symbol"?(e=na(n),n=Tl(u).hoistableScripts,l=n.get(e),l||(l={type:"script",instance:null,count:0,state:null},n.set(e,l)),l):{type:"void",instance:null,count:0,state:null};default:throw Error(f(444,t))}}function ea(t){return'href="'+_e(t)+'"'}function lu(t){return'link[rel="stylesheet"]['+t+"]"}function Hh(t){return p({},t,{"data-precedence":t.precedence,precedence:null})}function Hv(t,e,n,l){t.querySelector('link[rel="preload"][as="style"]['+e+"]")?l.loading=1:(e=t.createElement("link"),l.preload=e,e.addEventListener("load",function(){return l.loading|=1}),e.addEventListener("error",function(){return l.loading|=2}),Pt(e,"link",n),Zt(e),t.head.appendChild(e))}function na(t){return'[src="'+_e(t)+'"]'}function au(t){return"script[async]"+t}function jh(t,e,n){if(e.count++,e.instance===null)switch(e.type){case"style":var l=t.querySelector('style[data-href~="'+_e(n.href)+'"]');if(l)return e.instance=l,Zt(l),l;var u=p({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return l=(t.ownerDocument||t).createElement("style"),Zt(l),Pt(l,"style",u),Ri(l,n.precedence,t),e.instance=l;case"stylesheet":u=ea(n.href);var i=t.querySelector(lu(u));if(i)return e.state.loading|=4,e.instance=i,Zt(i),i;l=Hh(n),(u=Ce.get(u))&&df(l,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",l),e.state.loading|=4,Ri(i,n.precedence,t),e.instance=i;case"script":return i=na(n.src),(u=t.querySelector(au(i)))?(e.instance=u,Zt(u),u):(l=n,(u=Ce.get(i))&&(l=p({},n),hf(l,u)),t=t.ownerDocument||t,u=t.createElement("script"),Zt(u),Pt(u,"link",l),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&&(l=e.instance,e.state.loading|=4,Ri(l,n.precedence,t));return e.instance}function Ri(t,e,n){for(var l=n.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),u=l.length?l[l.length-1]:null,i=u,o=0;o title"):null)}function jv(t,e,n){if(n===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 Yh(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function qv(t,e,n,l){if(n.type==="stylesheet"&&(typeof l.media!="string"||matchMedia(l.media).matches!==!1)&&(n.state.loading&4)===0){if(n.instance===null){var u=ea(l.href),i=e.querySelector(lu(u));if(i){e=i._p,e!==null&&typeof e=="object"&&typeof e.then=="function"&&(t.count++,t=Mi.bind(t),e.then(t,t)),n.state.loading|=4,n.instance=i,Zt(i);return}i=e.ownerDocument||e,l=Hh(l),(u=Ce.get(u))&&df(l,u),i=i.createElement("link"),Zt(i);var o=i;o._p=new Promise(function(v,_){o.onload=v,o.onerror=_}),Pt(i,"link",l),n.instance=i}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(n,e),(e=n.state.preload)&&(n.state.loading&3)===0&&(t.count++,n=Mi.bind(t),e.addEventListener("load",n),e.addEventListener("error",n))}}var mf=0;function wv(t,e){return t.stylesheets&&t.count===0&&xi(t,t.stylesheets),0mf?50:800)+e);return t.unsuspend=n,function(){t.unsuspend=null,clearTimeout(l),clearTimeout(u)}}:null}function Mi(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)xi(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var Ci=null;function xi(t,e){t.stylesheets=null,t.unsuspend!==null&&(t.count++,Ci=new Map,e.forEach(Yv,t),Ci=null,Mi.call(t))}function Yv(t,e){if(!(e.state.loading&4)){var n=Ci.get(t);if(n)var l=n.get(null);else{n=new Map,Ci.set(t,n);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(),Tf.exports=lg(),Tf.exports}var ug=ag();const ig=!1;var om=at.use,Vm=at.useLayoutEffect;function cg(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 sg(a){const c=at.useRef(null);return at.useImperativeHandle(a,()=>c.current,[]),c}function yu(a){return a[a.length-1]}function fg(a){return typeof a=="function"}function ra(a,c){return fg(a)?a(c):a}const Zm=Object.prototype.hasOwnProperty,og=Object.prototype.propertyIsEnumerable;function Km(a){for(const c in a)if(Zm.call(a,c))return!0;return!1}const rg=()=>Object.create(null),dl=(a,c)=>ml(a,c,rg);function ml(a,c,s=()=>({}),f=0){if(a===c)return a;if(f>500)return c;const r=c,h=hm(a)&&hm(r);if(!h&&!(Ji(a)&&Ji(r)))return r;const g=h?a:rm(a);if(!g)return r;const m=h?r:rm(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!(!dm(s)||!s.hasOwnProperty("isPrototypeOf"))}function dm(a){return Object.prototype.toString.call(a)==="[object Object]"}function hm(a){return Array.isArray(a)&&a.length===Object.keys(a).length}function Gn(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||!Gn(a[g],c[g],s)))return!1;return r===h}return!1}function dg(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 hg=/[\x00-\x1f\x7f"<>`{}]/g;function mg(a){return a.replace(hg,c=>"%"+c.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0"))}function mm(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 mg(c)}const yg=["http:","https:","mailto:","tel:"];function ki(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+=mm(a.slice(s,r.index))+r[0],s=c.lastIndex;f=f+mm(s?a.slice(s):a);let h=!1;return f.startsWith("//")&&(h=!0,f="/"+f.replace(/^\/+/,"")),{path:f,handledProtocolRelativeURL:h}}function vg(a){return/\s|[^\u0000-\u007F]/.test(a)?a.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):a}function gg(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 Yn=4,Jm=5;function pg(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 km(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=pg(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=Sg(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=Jm,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=Yn,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 Wm(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 Sg(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 bg(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(Wm);c.masksTree=s,c.flatCache=Wi(1e3)}function _g(a,c){a||="/";const s=c.flatCache.get(a);if(s)return s;const f=Zf(a,c.masksTree);return c.flatCache.set(a,f),f}function Eg(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)),Zf(f,g,s)}function Tg(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=Zf(a,c.segmentTree,s)}catch(g){if(g instanceof URIError)h=null;else throw g}return h&&(h.branch=$m(h.route)),c.matchCache.set(f,h),h}function zg(a){return a==="/"?a:a.replace(/\/{1,}$/,"")}function Ag(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&&Vf(),g[d.id]=d,y!==0&&d.path){const S=zg(d.fullPath);(!m[S]||d.fullPath.endsWith("/"))&&(m[S]=d)}y++});for(const d of h)d.sort(Wm);return{processedTree:{segmentTree:f,singleCache:Wi(1e3),matchCache:Wi(1e3),flatCache:null,masksTree:null},routesById:g,routesByPath:m}}function Zf(a,c,s=!1){const f=a.split("/"),r=Og(a,f,c,s);if(!r)return null;const[h]=Fm(a,f,r);return{route:r.node.route,rawParams:h}}function Fm(a,c,s){const f=Rg(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+qi(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+qi(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+qi(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+qi(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===Yn)>(a.node.kind===Yn)||c.node.kind===Yn==(a.node.kind===Yn)&&c.node.depth>a.node.depth))):!0}function Xi(a){return Kf(a.filter(c=>c!==void 0).join("/"))}function Kf(a){return a.replace(/\/{2,}/g,"/")}function Pm(a){return a==="/"?a:a.replace(/^\/{1,}/,"")}function dn(a){const c=a.length;return c>1&&a[c-1]==="/"?a.replace(/\/{1,}$/,""):a}function Im(a){return dn(Pm(a))}function Fi(a,c){return a?.endsWith("/")&&a!=="/"&&a!==`${c}/`?a.slice(0,-1):a}function Cg(a,c,s){return Fi(a,s)===Fi(c,s)}function xg({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&&yu(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&&(yu(m)===""?s==="never"&&m.pop():s==="always"&&m.push(""));const y=Kf(m.join("/"))||"/";return g&&f&&f.set(g,y),y}function Dg(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 Of(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=>gm(r,s)).join("/"):gm(f,s)}function vm({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 jg(a){const c=a.getAttribute(pm);if(c)return`[${pm}="${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 Yi=!1;const Qi="window";function Hf(a){try{return typeof a=="function"?a():document.querySelector(a)}catch{}}function Sm(a){const c=new Set;for(const s of a){if(s===Qi)continue;const f=Hf(s);f&&c.add(f)}return c}function qg(a,c){const s=a.options.scrollRestoration,f=a._scroll;s&&(f.restoring=!0);const r=a.options.getScrollRestorationKey||Hg,h=new Set,g=m=>{const y=ua[m]||={};for(const d of h)d===document?y[Qi]={scrollX,scrollY}:d.isConnected&&(y[jg(d)]={scrollX:d.scrollLeft,scrollY:d.scrollTop})};s&&!f.restoration&&(f.restoration=!0,Yi=!1,history.scrollRestoration="manual",document.addEventListener("scroll",m=>{Yi||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())),Bg()})),!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===Qi){if(S)continue}else{const Y=Hf(w);if(!Y||S&&d&&(b??=Sm(d),b.has(Y)))continue}D||(D=ua[T]={}),D[w]??=E[w]}}}Yi=!0;try{const E=m.toLocation.hash,D=m.toLocation.state.__hashScrollIntoViewOptions??!0;let w=!1;if(S){!E&&d&&(b??=Sm(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===Qi){if(Y)continue;scrollTo({top:G,left:et,behavior:y}),w=!0}else{const L=Hf(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{Yi=!1}}))}function wg(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 Mf(a){return a?a==="false"?!1:a==="true"?!0:+a*0===0&&+a+""===a?+a:a:""}function Yg(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]=Mf(r):Array.isArray(h)?h.push(Mf(r)):s[f]=[h,Mf(r)]}return s}const Gg=/^(?:\s|["[{\d-]|fa|nu|tr)/,Xg=Vg(JSON.parse),Qg=Zg(JSON.stringify,JSON.parse);function Vg(a){return c=>{c[0]==="?"&&(c=c.substring(1));const s=Yg(c);for(const f in s){const r=s[f];if(typeof r=="string")try{s[f]=a(r)}catch{}}return s}}function Zg(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&&!Gg.test(r))return r;try{return c(r),a(r)}catch{}}return r}return r=>{const h=wg(r,f);return h?`?${h}`:""}}const sa="__root__";function Kg(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 Jf(a){return a instanceof Response&&!!a.options}function Jg(a){return{input:({url:c})=>{for(const s of a)c=jf(s,c);return c},output:({url:c})=>{for(let s=a.length-1;s>=0;s--)c=e0(a[s],c);return c}}}function kg(a){const c=Im(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=Xi(["/",c,h.pathname]),h)}}function jf(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 e0(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 Wg(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(()=>{gg(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 Xn="__TSR_index",bm="popstate",_m="beforeunload";function Fg(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=$i(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[Xn];m=Em(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[Xn];m=Em(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[Xn]!==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 Em(a,c){c||(c={});const s=kf();return{...c,key:s,__TSR_key:s,[Xn]:a}}function $g(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=(()=>$i(`${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({[Xn]: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=$i(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[Xn]-d.state[Xn],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=Fg({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(_m,et,{capture:!0}),c.removeEventListener(bm,X)},onBlocked:()=>{S&&d!==S&&(d=S)},getBlockers:h,setBlockers:g,notifyOnIndexChange:!1});return c.addEventListener(_m,et,{capture:!0}),c.addEventListener(bm,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 Pg(a){let c=a.replace(/[\x00-\x1f\x7f]/g,"");return c.startsWith("//")&&(c="/"+c.replace(/^\/+/,"")),c}function $i(a,c){const s=Pg(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||{[Xn]:0,key:h,__TSR_key:h}}}function kf(){return(Math.random()+1).toString(36).substring(7)}function Tm(a){return a.options.loader||a.options.beforeLoad||a.lazyFn||a.options.component?.preload||a.options.pendingComponent?.preload}function nc(a,c){return{fromLocation:c,toLocation:a,pathChanged:c?.pathname!==a.pathname,hrefChanged:c?.href!==a.href,hashChanged:c?.hash!==a.hash}}function zm({key:a,__TSR_key:c,__TSR_index:s,__hashScrollIntoViewOptions:f,...r}){return r}function Ig(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 tp=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??ig??typeof document>"u",this.protocolAllowlist=new Set(this.options.protocolAllowlist),this.options.pathParamsAllowedCharacters&&(this.pathParamsDecoder=Dg(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.options.history?this.history=this.options.history:this.history=$g()),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=Wi(1e3),d=this.buildRouteTree(),this.setRoutes(d)}if(!this.stores&&this.latestLocation){const d=this.getStoreConfig(this);this.batch=d.batch,this.stores=Wg(this.latestLocation,d),qg(this)}const m=this.options.basepath??"/",y=this.options.rewrite;if(h||r!==m||g!==y){this.basepath=m;const d=[],S=Im(m);S&&S!=="/"&&d.push(kg({basepath:m})),y&&d.push(y),this.rewrite=d.length===0?void 0:d.length===1?d[0]:Jg(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=Ag(this.routeTree,this.options.caseSensitive,(f,r)=>{f.init({originalIndex:r})});return this.options.routeMasks&&bg(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:dl(f?.search,w),hash:ru(S.slice(1)).path,state:ml(f?.state,b)}}const T=new URL(p,this.origin),R=jf(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:dl(f?.search,E),hash:ru(R.hash.slice(1)).path,state:ml(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)=>xg({base:s,to:f.includes("//")?Kf(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=Tg(dn(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=Am(h.params,p),E=this.routesByPath[dn(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&&Km(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(vm({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,Vi(ft.options.validateSearch,{...P,...Y}))}catch{}}),Y=P}Y=np(Y,h,D,s._includeValidateSearch),Y=dl(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=ml(g.state,G);const L=`${w}${K}${et}`;let Q,J,ct=!1;if(this.rewrite){const P=new URL(L,this.origin),ft=e0(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=vg(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=_g(m.pathname,this.processedTree);if(S){Object.assign(d,S.rawParams);const{from:p,params:b,...T}=S.route,R=Am(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=dn(this.latestLocation.href)===dn(r.href)&&Gn(zm(r.state),zm(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=$i(y,{__TSR_index:s?b:b+1}),R=new URL(T.pathname,this.origin);d.to=jf(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(ki(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 rp(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(nc(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")&&Tm(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&&ki(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=>d0(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=Eg(h.pathname,f?.caseSensitive??!1,f?.fuzzy??!1,m.pathname,this.processedTree);return!y||s.params&&!Gn(y.rawParams,s.params,{partial:!0})?!1:f?.includeSearch??!0?Gn(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??Qg,parseSearch:a.parseSearch??Xg,protocolAllowlist:a.protocolAllowlist??yg}),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=$m(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["**"]:dn(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=Vi(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 Am(a,c){return a===!1||a===null?Object.create(null):(a??!0)===!0?c:Object.assign(c,ra(a,c))}function Rm(a,c){const s=a.options.params?.parse??a.options.parseParams;s&&Object.assign(c,s(c))}function qf(a,c){return a.options[c]?.preload?.()}function ap(a,c){const s=qf(a,"component"),f=qf(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?qf(a,c):ap(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 n0(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 gl(a,c){return a.routesById[c.routeId]}function gu(a,c,s){return Jf(a)?[xe,a]:yl(a)?(a.routeId||=s,[lc,a]):(c&&typeof a?.then=="function"&&(a=new Error("A Promise was thrown",{cause:a})),c?[Qn,a]:[Xe,a])}function l0(a,c){let s=gu(c,!0,a.id);if(s[0]!==Qn)return s;try{a.options.onError?.(s[1])}catch(f){s=gu(f,!0,a.id)}return s}function du(a,c,s){return s[0].signal.aborted||!s[2]()?(s[0].abort(),[vl]):l0(a,c)}function a0(a,c){return s=>a.navigate({...s,_fromLocation:c})}async function up(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{pu(a,p,"beforeLoad",s[0]);const X=await Vn(w(Y),y);if(!s[2]())return s[0].abort(),[S,[vl]];const et=gu(X,!1,b.id);if(et[0]!==Xe)return hn(a,p),[S,et];p.context={...E,...X}}catch(X){return hn(a,p),[S,du(b,X,s)]}finally{K==="success"&&p.status==="pending"&&(p.status="success"),pu(a,p,!1,s[0])}}r()}function Wf(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 hn(a,c){const s=c._flight;c._flight=void 0,Wf(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=Wf(a,h,g);m&&r.push(m)}}for(const h of r)h.abort()}function Ff(a){for(const c of a){const s=c._flight;s&&s[2]++}}function pu(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 u0(a,c,s,f,r,h,g){const m=c[0];return{params:s.params,location:m,navigate:a0(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 Om(a,c,s,f,r,h,g,m){const y=m.signal;if(y.aborted)return[vl];if(!r)return[Xe,void 0];let d=s._flight;pu(a,s,"loader",m);try{if(!d){const S=new AbortController;d=[Promise.resolve().then(()=>r(u0(a,c,s,f,S,h,g))).then(p=>gu(p,!1,f.id),p=>gu(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]===Qn&&d[2]?l0(f,p[1]):p)),S,1],(a._flights??=new Map).set(s.id,d)}return s._flight=d,s.abortController=d[1],await Vn(d[0],y)}catch(S){if(S!==y)throw S;return hn(a,s),[vl]}finally{pu(a,s,!1,m)}}function Mm(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 ip(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&&hn(a,f)}function Cm(a,c){return c[0]===Qn||c[0]===lc?{...a,status:c[0]===Qn?"error":"notFound",error:c[1],_flight:void 0}:a}function cp(a,c,s,f,r,h,g){const m=c[1][s],y=gl(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(u0(a,c,m,y,h[0],r,d))),h[2]()||(h[0].abort(),T=[vl])),!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,hn(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,Wf(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?Om(a,c,m,y,E,r,d,h[0]):Promise.resolve([Xe,m.loaderData])).then(J=>(K&&(Mm(m,J,d),J[0]===Xe&&(R&&!h[0].signal.aborted&&ip(a,m,S),m.status="pending")),J)),G=Vn(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=>Cm(m,J));const L={...m,status:"pending",preload:!1,_flight:D};m.invalid=!1,m.isFetching="loader";const Q=Om(a,c,L,y,E,r,!1,h[0]).then(J=>(m.isFetching=!1,Mm(L,J,!1),J));return(c[2]??=[]).push([s,Q,G,L]),Q.then(J=>Cm(L,J))}async function wf(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=gl(a,c[m]),d=fa(y,!1);if(d)try{await Vn(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 xm(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 i0(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]===lc?wf(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,[Qn,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===Qn?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=gl(a,D);try{await Vn(R?Promise.resolve().then(()=>fa(K,E===Qn?"errorComponent":"notFoundComponent")):Promise.all([fa(K),fa(K,"notFoundComponent")]),f.signal)}catch(X){if(X===f.signal)return oa(a,c),[vl]}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 c0(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 wf(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=i0(a,r,d,f[0],f[1],xm(d,T,r[2]),f[8]);r[2]?.length&&(r[3]=xm(r[2],void 0,void 0,E.then(D=>vu(D)?0:n0(D[1]).length,()=>0))),R=await E}catch(E){throw oa(a,r),E}return vu(R)?R:c0(a,R,f[0].signal,f[7]===R[1].length?f[7]:0)}function Yf(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(()=>Yf(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 Zi(a,c){const s=a._pending;s?.[0]===c&&(clearTimeout(s[3]),a._pending=void 0)}function f0(a,c){a._committed=c,a.stores.setMatches(c)}function Dm(a,c){oe(a,c[1]),oa(a,c)}function sp(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=n0(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,f0(a,s),oe(a,[...h.values(),...r],[...s,...m.values()]),Ig(a,r,s,()=>a._tx===c)}async function hl(a,c){let s=a._tx;for(;s&&s!==c;){if(await s[5],a._tx===s)return;s=a._tx}}async function o0(a,c,s){await a.navigate({...s.options,replace:!0,ignoreBlocker:!0,_redirects:c[1]+1})}function r0(a,c){Zi(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 fp(a,c,s,f,r){const h=s.map(d=>({...d}));Ff(h);for(const d of f)hn(a,h[d[0]]),h[d[0]]=d[3];const g=[c[2],h];let m;try{m=await i0(a,g,f,c[0],c[1],r)}catch(d){throw oe(a,h),d}if(vu(m)){oe(a,h),m[0]===xe&&a._tx===c&&a._committed===s&&await o0(a,c,m[1]);return}const y=await c0(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),hn(a,S))}f0(a,y[1]),oe(a,s,y[1])}async function op(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 s0(a,c[2],c[3],g);if(vu(m)){m[0]===xe&&a._tx===c?(Zi(a,c),oe(a,c[3]),c[3]=[],a._tx===c&&await o0(a,c,m[1])):r0(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 Vn(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 Vn(new Promise(E=>{y[3]=setTimeout(E,R)}),b)}catch{}clearTimeout(y[3])}}}if(a._tx!==c){Zi(a,c),Dm(a,m);return}const d=c[2],S=nc(d,a.stores.resolvedLocation.get()),p=m[2];await a.startViewTransition(async()=>{if(a._tx!==c){Dm(a,m);return}const b=()=>{Zi(a,c),sp(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&&fp(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 rp(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 hl(a,s);return}const b=nc(h,f);if(a.emit({type:"onBeforeNavigate",...b}),S.signal.aborted||a.emit({type:"onBeforeLoad",...b}),S.signal.aborted){await hl(a,s);return}const T=r.href===h.href;let R,E=S;try{R=a.matchRoutes(h,{_controller:S}),Ff(R)}catch(Y){if(S.abort(),!Jf(Y)){await hl(a),a._commitPromise?.resolve(),a._commitPromise=void 0;return}await a.navigate({...Y.options,replace:!0,ignoreBlocker:!0}),await hl(a,s);return}const D=d?y[1](R):void 0;if(D?E=d:d?.abort(),S.signal.aborted){oe(a,R),await hl(a,s);return}a._preflight=void 0;const w=[E,m,h,R,Date.now(),Promise.resolve().then(()=>op(a,w,T,()=>Yf(a,w),c?.sync,D)).catch(()=>{a._tx===w&&r0(a,w)})];if(a._tx=w,s){for(const Y of a.stores.matches.get()){if(a._tx!==w)break;Y.isFetching&&pu(a,Y,!1)}s[0].abort(),oe(a,s[3],w[3],!0)}if(a._tx!==w){oe(a,w[3]),w[3]=[],await hl(a,w);return}a.batch(()=>{a.stores.status.set("pending"),a.stores.location.set(h)}),!f&&!R.some(Y=>Y._notFound)&&Yf(a,w);try{await w[5]}finally{await hl(a,w)}}async function d0(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}),Ff(g)}catch(y){h.abort(),yl(y)||console.error(y);return}(a._preloads??=new Map).set(h,g);let m;try{let y;try{y=await s0(a,f,g,[h,s,()=>!0,r,!0])}finally{m=a._preloads.delete(h),oe(a,g),h.abort()}if(!vu(y))return y[1];if(m&&y[0]===xe&&!y[1].options.reloadDocument)return d0(a,{...y[1].options,_fromLocation:f},s+1)}catch(y){yl(y)||console.error(y)}}const dp="Error preloading route! ☝️";var h0=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||Vf();let r=f?sa:s?.path;r&&r!=="/"&&(r=Pm(r));const h=s?.id||r;let g=f?sa:Xi([this.parentRoute.id==="__root__"?"":this.parentRoute.id,h]);r==="__root__"&&(r="/"),g!=="__root__"&&(g=Xi(["/",g]));const m=g==="__root__"?"/":Xi([this.parentRoute.fullPath,r]);this._path=r,this._id=g,this._fullPath=m,this._to=dn(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=>Kg({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.")}},hp=class extends h0{constructor(a){super(a)}};function $f(a){return k.jsx(mp,{...a})}var mp=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??yp,{error:a,reset:this.reset}):this.props.children}};function yp({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 vp({children:a,fallback:c=null}){return k.jsx(tc.Fragment,{children:m0()?a:c})}function m0(){return tc.useSyncExternalStore(gp,()=>!0,()=>!1)}function gp(){return()=>{}}var y0=at.createContext(null);function Be(a){return at.useContext(y0)}var ac=at.createContext(void 0),pp=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 Sp({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 bp(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 Gf=[];let Ki=0;const{link:Um,unlink:_p,propagate:Ep,checkDirty:v0,shallowPropagate:Lm}=Sp({update(a){return a._update()},notify(a){Gf[Xf++]=a,a.flags&=~Lt.Watching},unwatched(a){a.depsTail!==void 0&&(a.depsTail=void 0,a.flags=Lt.Mutable|Lt.Dirty,Ii(a))}});let Gi=0,Xf=0,Ge,Qf=0;function Tp(a){try{++Qf,a()}finally{--Qf||g0()}}function Ii(a){const c=a.depsTail;let s=c!==void 0?c.nextDep:a.deps;for(;s!==void 0;)s=_p(s,a)}function g0(){if(!(Qf>0)){for(;Gi{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,++Ki,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),Ii(r)}}};return s?(r.flags=Lt.Mutable|Lt.Dirty,r.get=function(){const h=r.flags;if(h&Lt.Dirty||h&Lt.Pending&&v0(r.deps,r)){if(r._update()){const g=r.subs;g!==void 0&&Lm(g)}}else h&Lt.Pending&&(r.flags=h&~Lt.Pending);return Ge!==void 0&&Um(r,Ge,Ki),r._snapshot}):r.set=function(h){if(r._update(h)){const g=r.subs;g!==void 0&&(Ep(g),Lm(g),g0())}},r}function zp(a){const c=()=>{const f=Ge;Ge=s,++Ki,s.depsTail=void 0,s.flags=Lt.Watching|Lt.RecursedCheck;try{return a()}finally{Ge=f,s.flags&=~Lt.RecursedCheck,Ii(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&&v0(this.deps,this)?c():this.flags=Lt.Watching},stop(){this.flags=Lt.None,this.depsTail=void 0,Ii(this)}};return c(),s}var Cf={exports:{}},xf={},Df={exports:{}},Uf={};var Bm;function Ap(){if(Bm)return Uf;Bm=1;var a=Su();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 Uf.useSyncExternalStore=a.useSyncExternalStore!==void 0?a.useSyncExternalStore:S,Uf}var Hm;function Rp(){return Hm||(Hm=1,Df.exports=Ap()),Df.exports}var jm;function Op(){if(jm)return xf;jm=1;var a=Su(),c=Rp();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 xf.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},xf}var qm;function Mp(){return qm||(qm=1,Cf.exports=Op()),Cf.exports}var Cp=Mp();function xp(a,c){return a===c}function Zn(a,c,s=xp){const f=at.useCallback(g=>{if(!a)return()=>{};const{unsubscribe:m}=a.subscribe(g);return m},[a]),r=at.useCallback(()=>a?.get(),[a]);return Cp.useSyncExternalStoreWithSelector(f,r,r,c,s)}var wm={};function Dp(a,c){const s=at.useRef();return f=>{const r=a?.select?a.select(f):f;return a?.structuralSharing??c.options.defaultStructuralSharing?s.current=ml(s.current,r):r}}function pl(a){const c=Be(),s=at.useContext(a.from?pp:ac),f=a.from??s,r=c.stores.getMatchStore(f),h=Dp(a,c),g=Zn(r,m=>m?h(m):wm);if(g!==wm)return g;(a.shouldThrow??!0)&&Vf()}function p0(a){return pl({from:a.from,strict:a.strict,structuralSharing:a.structuralSharing,select:c=>a.select?a.select(c.loaderData):c.loaderData})}function S0(a){const{select:c,...s}=a;return pl({...s,select:f=>c?c(f.loaderDeps):f.loaderDeps})}function b0(a){return pl({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 _0(a){return pl({from:a.from,strict:a.strict,shouldThrow:a.shouldThrow,structuralSharing:a.structuralSharing,select:c=>a.select?a.select(c.search):c.search})}function E0(a){const c=Be();return at.useCallback(s=>c.navigate({...s,from:s.from??a?.from}),[a?.from,c])}function T0(a){return pl({...a,select:c=>a.select?a.select(c.context):c.context})}function Lf(a){const c=at.useRef(a);return Gn(c.current,a,{ignoreUndefined:!1})||(c.current=a),c.current}function Up(a,c){return a[0]===c[0]&&a[1]===c[1]&&a[2]===c[2]}function Lp(a,c,s){if(a?.external)return ki(a.href,s)?void 0:a.href;if(!Yp(c)&&!(typeof c!="string"||c.indexOf(":")===-1))try{return new URL(c),ki(c,s)?void 0:c}catch{}}function Np(a,c,s,f,r,h){if(h)return!1;if(s?.exact){if(!Cg(a.pathname,c.pathname,f))return!1}else{const g=Fi(a.pathname,f),m=Fi(c.pathname,f);if(!(g.startsWith(m)&&(g.length===m.length||g[m.length]==="/")))return!1}return(s?.includeSearch??!0)&&!Gn(a.search,c.search,{partial:!s?.exact,ignoreUndefined:!s?.explicitUndefined})?!1:s?.includeHash?r&&a.hash===c.hash:!0}function Bp(a,c){const s=Be(),f=sg(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:nt,from:_t,_fromLocation:zt,...A}=a,q=m0(),Z=Lf(a.search),F=Lf(a.params),lt=Lf(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}),Jn=wp(Nt.maskedLocation?Nt.maskedLocation.publicHref:Nt.publicHref,Nt.maskedLocation?Nt.maskedLocation.external:Nt.external,s.history,Y),va=Lp(Jn,m,s.protocolAllowlist);return[Jn?.href,va,Np(It,Nt,lt,s.basepath,q,va!==void 0)]},[lt,Y,q,it,s,m]),[Jt,Ct,Qe]=Zn(s.stores.location,vt,Up),Ve=Qe?ra(r,{})??Hp:Nf,mn=Qe?Nf:ra(h,{})??Nf,da=[X,Ve.className,mn.className].filter(Boolean).join(" "),He=(K||Ve.style||mn.style)&&{...K,...Ve.style,...mn.style},Sl=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(dp)})},[s,it]),Kn=at.useCallback(It=>{if(!It){Bf(f);return}if(!(It.isIntersecting??De==="intent")){It.isIntersecting===!1&&Bf(f);return}if(!ha){Ze();return}hu.has(f)||hu.set(f,setTimeout(()=>{hu.delete(f),Ze()},ha))},[Ze,f,De,ha]);cg(f,Kn,De!=="viewport"),at.useEffect(()=>{Sl.current||De==="render"&&(Ze(),Sl.current=!0)},[Ze,De]);const ma=It=>{const Nt=It.currentTarget.getAttribute("target"),Jn=w!==void 0?w:Nt;!Y&&!Gp(It)&&!It.defaultPrevented&&(!Jn||Jn==="_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()},bu=()=>{De==="intent"&&Bf(f)};return{...A,...Ve,...mn,href:Jt,ref:f,onClick:aa([et,ma]),onBlur:aa([G,bu]),onFocus:aa([L,Kn]),onMouseEnter:aa([Q,Kn]),onMouseLeave:aa([J,bu]),onTouchStart:aa([ct,ya]),disabled:!!Y,target:w,...He&&{style:He},...da&&{className:da},...Y&&jp,...Qe&&qp}}var Nf={},Hp={className:"active"},jp={role:"link","aria-disabled":!0},qp={"data-status":"active","aria-current":"page"},hu=new WeakMap,Bf=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 wp(a,c,s,f){if(!f)return c?{href:a,external:!0}:{href:s.createHref(a)||"/",external:!1}}function Yp(a){if(typeof a!="string")return!1;const c=a.charCodeAt(0);return c===47?a.charCodeAt(1)!==47:c===46}var mu=at.forwardRef((a,c)=>{const{_asChild:s,...f}=a,{type:r,...h}=Bp(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 Gp(a){return!!(a.metaKey||a.altKey||a.ctrlKey||a.shiftKey)}var Xp=class extends h0{constructor(c){super(c),this.useMatch=s=>pl({select:s?.select,from:this.id,structuralSharing:s?.structuralSharing}),this.useRouteContext=s=>T0({...s,from:this.id}),this.useSearch=s=>_0({select:s?.select,structuralSharing:s?.structuralSharing,from:this.id}),this.useParams=s=>b0({select:s?.select,structuralSharing:s?.structuralSharing,from:this.id}),this.useLoaderDeps=s=>S0({...s,from:this.id}),this.useLoaderData=s=>p0({...s,from:this.id}),this.useNavigate=()=>E0({from:this.fullPath}),this.Link=tc.forwardRef((s,f)=>k.jsx(mu,{ref:f,from:this.fullPath,...s}))}};function Qp(a){return new Xp(a)}var Vp=class extends hp{constructor(a){super(a),this.useMatch=c=>pl({select:c?.select,from:this.id,structuralSharing:c?.structuralSharing}),this.useRouteContext=c=>T0({...c,from:this.id}),this.useSearch=c=>_0({select:c?.select,structuralSharing:c?.structuralSharing,from:this.id}),this.useParams=c=>b0({select:c?.select,structuralSharing:c?.structuralSharing,from:this.id}),this.useLoaderDeps=c=>S0({...c,from:this.id}),this.useLoaderData=c=>p0({...c,from:this.id}),this.useNavigate=()=>E0({from:this.fullPath}),this.Link=tc.forwardRef((c,s)=>k.jsx(mu,{ref:s,from:this.fullPath,...c}))}};function Zp(a){return new Vp(a)}function Pf(a){return c=>{const s=Qp(c);return s.isRoot=!1,s}}function If(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(dg(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(om)om(h());else throw h();return at.createElement(f,y)};return g.preload=h,g}function Kp(a){const c=Be(),s=`not-found-${Zn(c.stores.location,f=>f.pathname)}-${Zn(c.stores.status,f=>f)}`;return k.jsx($f,{getResetKey:()=>s,onCatch:(f,r)=>{if(yl(f))a.onCatch?.(f,r);else throw f},errorComponent:({error:f})=>{if(yl(f))return a.fallback?.(f);throw f},children:a.children})}function Jp(){return k.jsx("p",{children:"Not Found"})}function ia(a){return k.jsx(k.Fragment,{children:a.children})}function z0(a,c,s){return c.options.notFoundComponent?k.jsx(c.options.notFoundComponent,{...s}):a.options.defaultNotFoundComponent?k.jsx(a.options.defaultNotFoundComponent,{...s}):k.jsx(Jp,{})}function uc(a,c){const s=c?.options.pendingComponent??a.options.defaultPendingComponent;return s?k.jsx(s,{}):null}var kp=(a,c)=>a[0]===c[0]&&a[1]===c[1],A0=at.memo(function({routeId:c}){const s=Be();return k.jsx(Wp,{router:s,match:Zn(s.stores.getMatchStore(c),f=>f)})});function Wp({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?$f:ia,S=g?Kp: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(yl(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(vp,{fallback:f,children:k.jsx(Ym,{match:c})}):k.jsx(Ym,{match:c})})})})}),null]})}var Ym=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(R0,{})},[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 z0(s,r,c.error);if(c.status==="error")throw c.error;return g}),R0=at.memo(function(){const c=Be(),s=at.useContext(ac);let f,r,h;{const m=c.stores.getMatchStore(s);[f,r]=Zn(m,y=>[!!y._notFound,y.error],kp),h=Zn(c.stores.ids,y=>y[y.indexOf(s)+1])}if(f)return z0(c,c.routesById[s],r);if(!h)return null;const g=k.jsx(A0,{routeId:h});return s===sa?k.jsx(at.Suspense,{fallback:uc(c),children:g}):g});function O0(a,c){const s=a[1];a.length=0,s?.(c)}function Fp({t:a}){const c=Be(),s=c._rendered??=[];return c.startTransition=(f,r)=>new Promise((h,g)=>{O0(s,!1),s.push(r,h),a(c),at.startTransition(()=>{try{f()}catch(m){s[1]===h&&(s.length=0),g(m)}})}),Vm(()=>{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(dn(r.publicHref)!==dn(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",...nc(g,g)})}):c._tx||c.load().catch(console.error),f},[c,c.history]),null}function $p(){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(Fp,{t:at.useState()[1]}),k.jsx(f,{fallback:s,children:k.jsx(Pp,{})})]});return a.options.InnerWrap?k.jsx(a.options.InnerWrap,{children:r}):r}function Pp(){const a=Be(),c=a._rendered,s=Zn(a.stores.matches,g=>c[0]??g),f=s[0],r=f?.routeId;Vm(()=>{c[0]===s&&O0(c,!0)},[c,s]);const h=r?k.jsx(A0,{routeId:r}):null;return k.jsx(ac.Provider,{value:r,children:a.options.disableGlobalCatchBoundary?h:k.jsx($f,{getResetKey:()=>f,onCatch:void 0,children:h})})}var Ip=a=>({createMutableStore:Nm,createReadonlyStore:Nm,batch:Tp}),t1=a=>new e1(a),e1=class extends tp{constructor(a){super(a,Ip)}};function n1({router:a,children:c,...s}){Km(s)&&a.update({...a.options,...s,context:{...a.options.context,...s.context}});const f=k.jsx(y0.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(n1,{router:a,...c,children:k.jsx($p,{})})}const M0="taskreport.user",C0="taskreport.role";function ic(){return{user:localStorage.getItem(M0)??"ada",role:localStorage.getItem(C0)??"member"}}function a1(a,c){localStorage.setItem(M0,a),localStorage.setItem(C0,c)}async function rn(a,c){const{user:s,role:f}=ic(),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 u1={session:()=>rn("/session"),summary:()=>rn("/summary"),tasks:(a={})=>{const c=new URLSearchParams(Object.entries(a).filter(([,s])=>s!=="")).toString();return rn(`/tasks${c?`?${c}`:""}`)},create:a=>rn("/tasks",{method:"POST",body:JSON.stringify(a)}),complete:a=>rn(`/tasks/${a}/complete`,{method:"POST"}),reopen:a=>rn(`/tasks/${a}/reopen`,{method:"POST"}),remove:a=>rn(`/tasks/${a}`,{method:"DELETE"}),plans:(a="")=>rn(`/plans${a?`?status=${a}`:""}`),approve:a=>Gm(a,"approve"),reject:a=>Gm(a,"reject"),chat:a=>rn("/chat",{method:"POST",body:JSON.stringify({request:a})}),chatStream:i1};async function Gm(a,c){const{user:s,role:f}=ic(),r=await fetch(`/api/plans/${a}/${c}`,{method:"POST",headers:{"X-Demo-User":s,"X-Demo-Role":f}}),h=await r.json();if(!h.plan)throw new Error(h.error??`${r.status} ${r.statusText}`);return h}async function i1(a,c,s){const{user:f,role:r}=ic(),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(c1(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 c1(a){try{return JSON.parse(a).error??null}catch{return null}}const cc=Zp({component:s1}),Xm=[{user:"ada",role:"member"},{user:"linus",role:"member"},{user:"grace",role:"admin"}];function s1(){const[a,c]=at.useState(null),[s,f]=at.useState(null),r=Be(),h=ic();at.useEffect(()=>{u1.session().then(c).catch(m=>f(m.message))},[]);function g(m){const y=Xm.find(d=>d.user===m);y&&(a1(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(mu,{to:"/",activeOptions:{exact:!0},children:"Board"}),k.jsx(mu,{to:"/chat",children:"Ask"}),k.jsx(mu,{to:"/plans",children:"Approvals"})]}),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:Xm.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(R0,{})}),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 f1="modulepreload",o1=function(a){return"/"+a},Qm={},to=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=o1(d),d in Qm)return;Qm[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":f1,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)})},r1=()=>to(()=>import("./index-DxZkSe_0.js"),[]),d1=Pf()({component:If(r1,"component")}),h1=()=>to(()=>import("./chat-Doj4bXib.js"),__vite__mapDeps([0,1])),m1=Pf()({component:If(h1,"component")}),y1=()=>to(()=>import("./plans-CeX1mx6r.js"),__vite__mapDeps([2,1])),v1=Pf()({component:If(y1,"component")}),g1=d1.update({id:"/",path:"/",getParentRoute:()=>cc}),p1=m1.update({id:"/chat",path:"/chat",getParentRoute:()=>cc}),S1=v1.update({id:"/plans",path:"/plans",getParentRoute:()=>cc}),b1={IndexRoute:g1,ChatRoute:p1,PlansRoute:S1},_1=cc._addFileChildren(b1)._addFileTypes(),E1=t1({routeTree:_1});ug.createRoot(document.getElementById("root")).render(k.jsx(at.StrictMode,{children:k.jsx(l1,{router:E1})}));export{u1 as a,k as j,at as r}; diff --git a/examples/taskreport/web/dist/assets/index-D-DTohO0.js b/examples/taskreport/web/dist/assets/index-D-DTohO0.js deleted file mode 100644 index e061516..0000000 --- a/examples/taskreport/web/dist/assets/index-D-DTohO0.js +++ /dev/null @@ -1,15 +0,0 @@ -(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(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 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 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-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-D44oUAo0.css b/examples/taskreport/web/dist/assets/index-DCxQMvnE.css similarity index 88% rename from examples/taskreport/web/dist/assets/index-D44oUAo0.css rename to examples/taskreport/web/dist/assets/index-DCxQMvnE.css index 3d95e78..d2e6cf7 100644 --- a/examples/taskreport/web/dist/assets/index-D44oUAo0.css +++ b/examples/taskreport/web/dist/assets/index-DCxQMvnE.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}.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} +: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}.plan{border:1px solid var(--border, #d0d0d0);border-radius:var(--radius);padding:12px 14px;margin:12px 0}.plan-pending{border-color:var(--warn)}.plan-title{font-weight:600;margin:0 0 8px}.plan ul{margin:0 0 12px;padding-left:18px}.plan-actions{display:flex;gap:8px;align-items:center;margin-bottom:10px}button.secondary{background:transparent;color:inherit;border-color:currentColor}.timeline{list-style:none;padding:0;margin:0 0 6px;font-size:.9em}.timeline li{display:flex;align-items:center;gap:6px}.dot{width:8px;height:8px;border-radius:50%;background:var(--muted, #888);display:inline-block}.status-pending{background:var(--warn);color:#fff}.status-applied,.dot.status-applying{background:var(--good, #2f8f4e);color:#fff}.status-failed,.status-expired,.status-rejected{background:var(--bad);color:#fff}.small{font-size:.8em} diff --git a/examples/taskreport/web/dist/assets/index-B8YGsnYU.js b/examples/taskreport/web/dist/assets/index-DxZkSe_0.js similarity index 97% rename from examples/taskreport/web/dist/assets/index-B8YGsnYU.js rename to examples/taskreport/web/dist/assets/index-DxZkSe_0.js index 7ab9a81..0197a81 100644 --- a/examples/taskreport/web/dist/assets/index-B8YGsnYU.js +++ b/examples/taskreport/web/dist/assets/index-DxZkSe_0.js @@ -1 +1 @@ -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}; +import{r as s,a as n,j as a}from"./index-C8s4-fGn.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/plans-CeX1mx6r.js b/examples/taskreport/web/dist/assets/plans-CeX1mx6r.js new file mode 100644 index 0000000..fc6f6c2 --- /dev/null +++ b/examples/taskreport/web/dist/assets/plans-CeX1mx6r.js @@ -0,0 +1 @@ +import{r as a,a as o,j as s}from"./index-C8s4-fGn.js";import{P as c}from"./PlanView-Cf5UBqEG.js";function d(){const[t,i]=a.useState(null),[r,l]=a.useState("");if(a.useEffect(()=>{o.plans().then(e=>i(e.plans)).catch(e=>l(e.message))},[]),r)return s.jsx("p",{className:"error",children:r});if(!t)return s.jsx("p",{className:"muted",children:"Loading…"});if(t.length===0)return s.jsx("p",{className:"hint",children:"Nothing has waited for approval yet. Ask the chat to delete a task."});const n=t.filter(e=>e.status==="pending");return s.jsxs("div",{className:"ask",children:[s.jsxs("p",{className:"hint",children:[n.length," waiting for you · ",t.length-n.length," decided"]}),t.map(e=>s.jsx(c,{plan:e},e.id))]})}export{d as component}; diff --git a/examples/taskreport/web/dist/index.html b/examples/taskreport/web/dist/index.html index bdaa657..4a4ef65 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 683910e..bd463fd 100644 --- a/examples/taskreport/web/src/api.ts +++ b/examples/taskreport/web/src/api.ts @@ -51,16 +51,29 @@ 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 = { +// A plan is writes the program reached that need the user's approval. It is +// kept on the server until someone decides or it expires; only its ID comes +// back on approve or reject, so the client cannot change what was approved. +export type PlanStatus = "pending" | "applying" | "applied" | "failed" | "rejected" | "expired"; + +export type PlannedCall = { name: string; input: Record; error?: string }; + +export type Plan = { id: string; - calls: { name: string; input: Record }[]; + run_id: string; + request: string; + status: PlanStatus; + calls: PlannedCall[]; + applied?: PlannedCall[]; + created_at: string; + expires_at: string; + history: { status: PlanStatus; at: string; by?: string; note?: string }[]; }; export type ChatResult = { document: ViewDocument; - pending?: PendingPlan; + pending?: Plan; + run_id: string; program: string; attempts: number; used: { capability: { name: string; description: string }; distance: number }[]; @@ -125,9 +138,9 @@ 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" }), + plans: (status = "") => call<{ plans: Plan[] }>(`/plans${status ? `?status=${status}` : ""}`), + approve: (id: string) => decide(id, "approve"), + reject: (id: string) => decide(id, "reject"), chat: (request: string) => call("/chat", { method: "POST", body: JSON.stringify({ request }) }), @@ -135,6 +148,19 @@ export const api = { chatStream: streamChat, }; +// decide resolves with the plan as it now stands, even when it did not move: +// an expired or already-decided plan is an answer to show, not a crash. +async function decide(id: string, verb: "approve" | "reject"): Promise<{ plan: Plan; error?: string }> { + const { user, role } = identity(); + const response = await fetch(`/api/plans/${id}/${verb}`, { + method: "POST", + headers: { "X-Demo-User": user, "X-Demo-Role": role }, + }); + const body = await response.json(); + if (!body.plan) throw new Error(body.error ?? `${response.status} ${response.statusText}`); + return body; +} + // streamChat asks over server-sent events, calling onChunk with the program as // the model writes it and resolving with the finished answer. // diff --git a/examples/taskreport/web/src/components/PlanView.tsx b/examples/taskreport/web/src/components/PlanView.tsx new file mode 100644 index 0000000..1f47a22 --- /dev/null +++ b/examples/taskreport/web/src/components/PlanView.tsx @@ -0,0 +1,69 @@ +import { useState } from "react"; +import { api, type Plan } from "../api"; + +// PlanView shows one plan: what it would change, when it expires, and every +// step it has taken. Approve and Reject send only the ID; the server applies +// exactly what is listed here, once, checking the caller's access again. +export function PlanView({ plan: initial }: { plan: Plan }) { + const [plan, setPlan] = useState(initial); + const [error, setError] = useState(""); + const [working, setWorking] = useState(false); + + async function decide(approve: boolean) { + setWorking(true); + try { + const outcome = approve ? await api.approve(plan.id) : await api.reject(plan.id); + setPlan(outcome.plan); + setError(outcome.error ?? ""); + } catch (err) { + setError((err as Error).message); + } finally { + setWorking(false); + } + } + + return ( +
+

+ {plan.status} {plan.request} +

+
    + {plan.calls.map((call, index) => ( +
  • + {call.name} {JSON.stringify(call.input)} + {plan.applied?.[index]?.error && — {plan.applied[index].error}} +
  • + ))} +
+ {plan.status === "pending" && ( +
+ + + expires {when(plan.expires_at)} +
+ )} + {error &&

{error}

} +
    + {plan.history.map((change, index) => ( +
  1. + + {change.status} · {when(change.at)} + {change.by && ` · ${change.by}`} + {change.note && · {change.note}} +
  2. + ))} +
+

+ plan {plan.id} · run {plan.run_id} +

+
+ ); +} + +function when(iso: string): string { + return new Date(iso).toLocaleString(); +} diff --git a/examples/taskreport/web/src/routeTree.gen.ts b/examples/taskreport/web/src/routeTree.gen.ts index 81a6d77..b7784fd 100644 --- a/examples/taskreport/web/src/routeTree.gen.ts +++ b/examples/taskreport/web/src/routeTree.gen.ts @@ -11,6 +11,7 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' import { Route as ChatRouteImport } from './routes/chat' +import { Route as PlansRouteImport } from './routes/plans' const IndexRoute = IndexRouteImport.update({ id: '/', @@ -22,31 +23,40 @@ const ChatRoute = ChatRouteImport.update({ path: '/chat', getParentRoute: () => rootRouteImport, } as any) +const PlansRoute = PlansRouteImport.update({ + id: '/plans', + path: '/plans', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute '/chat': typeof ChatRoute + '/plans': typeof PlansRoute } export interface FileRoutesByTo { '/': typeof IndexRoute '/chat': typeof ChatRoute + '/plans': typeof PlansRoute } export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute '/chat': typeof ChatRoute + '/plans': typeof PlansRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/chat' + fullPaths: '/' | '/chat' | '/plans' fileRoutesByTo: FileRoutesByTo - to: '/' | '/chat' - id: '__root__' | '/' | '/chat' + to: '/' | '/chat' | '/plans' + id: '__root__' | '/' | '/chat' | '/plans' fileRoutesById: FileRoutesById } export interface RootRouteChildren { IndexRoute: typeof IndexRoute ChatRoute: typeof ChatRoute + PlansRoute: typeof PlansRoute } declare module '@tanstack/react-router' { @@ -65,12 +75,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ChatRouteImport parentRoute: typeof rootRouteImport } + '/plans': { + id: '/plans' + path: '/plans' + fullPath: '/plans' + preLoaderRoute: typeof PlansRouteImport + parentRoute: typeof rootRouteImport + } } } const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, ChatRoute: ChatRoute, + PlansRoute: PlansRoute, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/examples/taskreport/web/src/routes/__root.tsx b/examples/taskreport/web/src/routes/__root.tsx index 2ce08b8..9ae296d 100644 --- a/examples/taskreport/web/src/routes/__root.tsx +++ b/examples/taskreport/web/src/routes/__root.tsx @@ -45,6 +45,7 @@ function Shell() { Board Ask + Approvals
diff --git a/examples/taskreport/web/src/routes/chat.tsx b/examples/taskreport/web/src/routes/chat.tsx index 13c72de..cc3b121 100644 --- a/examples/taskreport/web/src/routes/chat.tsx +++ b/examples/taskreport/web/src/routes/chat.tsx @@ -1,7 +1,8 @@ import { createFileRoute } from "@tanstack/react-router"; import { useState } from "react"; -import { api, type ChatResult, type PendingPlan } from "../api"; +import { api, type ChatResult } from "../api"; import { DocumentView } from "../components/Blocks"; +import { PlanView } from "../components/PlanView"; export const Route = createFileRoute("/chat")({ component: Ask }); @@ -122,7 +123,7 @@ function TurnView({ turn, pending }: { turn: Turn; pending: boolean }) { {turn.result && ( <> - {turn.result.pending && } + {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. */} @@ -165,57 +166,6 @@ 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/routes/plans.tsx b/examples/taskreport/web/src/routes/plans.tsx new file mode 100644 index 0000000..479a4da --- /dev/null +++ b/examples/taskreport/web/src/routes/plans.tsx @@ -0,0 +1,33 @@ +import { createFileRoute } from "@tanstack/react-router"; +import { useEffect, useState } from "react"; +import { api, type Plan } from "../api"; +import { PlanView } from "../components/PlanView"; + +export const Route = createFileRoute("/plans")({ component: Approvals }); + +// The inbox: plans survive a reload and a restart, so a decision can come later. +function Approvals() { + const [plans, setPlans] = useState(null); + const [error, setError] = useState(""); + + useEffect(() => { + api.plans().then((body) => setPlans(body.plans)).catch((err) => setError(err.message)); + }, []); + + if (error) return

{error}

; + if (!plans) return

Loading…

; + if (plans.length === 0) { + return

Nothing has waited for approval yet. Ask the chat to delete a task.

; + } + const waiting = plans.filter((plan) => plan.status === "pending"); + return ( +
+

+ {waiting.length} waiting for you · {plans.length - waiting.length} decided +

+ {plans.map((plan) => ( + + ))} +
+ ); +} diff --git a/examples/taskreport/web/src/styles.css b/examples/taskreport/web/src/styles.css index 6eaee93..f6bf74e 100644 --- a/examples/taskreport/web/src/styles.css +++ b/examples/taskreport/web/src/styles.css @@ -199,8 +199,16 @@ tbody tr:last-child td { border-bottom: none; } 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; } +.plan { border: 1px solid var(--border, #d0d0d0); border-radius: var(--radius); padding: 12px 14px; margin: 12px 0; } +.plan-pending { border-color: var(--warn); } +.plan-title { font-weight: 600; margin: 0 0 8px; } +.plan ul { margin: 0 0 12px; padding-left: 18px; } +.plan-actions { display: flex; gap: 8px; align-items: center; margin-bottom: 10px; } button.secondary { background: transparent; color: inherit; border-color: currentColor; } +.timeline { list-style: none; padding: 0; margin: 0 0 6px; font-size: 0.9em; } +.timeline li { display: flex; align-items: center; gap: 6px; } +.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--muted, #888); display: inline-block; } +.status-pending { background: var(--warn); color: #fff; } +.status-applied, .dot.status-applying { background: var(--good, #2f8f4e); color: #fff; } +.status-failed, .status-expired, .status-rejected { background: var(--bad); color: #fff; } +.small { font-size: 0.8em; } From 03f52e692f0ac31e5f1b7a6be6f410df9812655b Mon Sep 17 00:00:00 2001 From: Mukesh Kumar Chaudhary Date: Mon, 16 Nov 2026 11:41:08 +0545 Subject: [PATCH 3/3] docs: durable approvals and observability Approving writes is rewritten around agent.Plans: setup, states, what is guaranteed and the errors each situation returns. A new observability page covers events, LogEvents, agent.Error and adapting events to tracing. Adds ADR 0009 and the durable-plans milestone. --- CHANGELOG.md | 20 ++- CLAUDE.md | 2 +- README.md | 11 +- docs/.vitepress/config.ts | 1 + docs/content/approval.md | 141 +++++++++++++--------- docs/content/observability.md | 94 +++++++++++++++ docs/content/quickstart.md | 15 ++- docs/content/types.md | 3 +- notes/decisions/0009-durable-plans.md | 44 +++++++ notes/milestones/2026-11-durable-plans.md | 117 ++++++++++++++++++ 10 files changed, 378 insertions(+), 70 deletions(-) create mode 100644 docs/content/observability.md create mode 100644 notes/decisions/0009-durable-plans.md create mode 100644 notes/milestones/2026-11-durable-plans.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 54d504f..8b0d6c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,9 +26,23 @@ version is 0, a minor bump may break the API. 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`. + one and returns `*agent.Pending`, applied through `agent.Plans` below. A write + needing approval fails rather than runs outside `agent.Run`. +- Durable plans: `agent.NewPlans(store, PlanOptions{TTL, OnEvent})` is the + approval API — `List` (the inbox), `Get`, `Approve`, `Reject` and `Resume`. A + plan has a status (`pending`, `applying`, `applied`, `failed`, `rejected`, + `expired`), an expiry, the request and run that made it, each applied call's + result, and a history of every change. Decisions are a compare-and-set, so a + plan applies once across replicas; expiry is checked on read; a crash while + applying resumes from the first call without a result. Errors name the plan + and its state, wrapping `ErrNoPlan`, `ErrPlanExpired` or `ErrPlanDecided`. +- `agent.PlanStore` (`Create`, `Get`, `List`, `Update`), `agent.NewMemoryPlanStore`, + `agent/sqlplans` for SQLite and Postgres on `database/sql`, and + `agent/plantest.Run`, the contract every plan store passes. +- `Options.OnEvent` and `agent.Event`: one event per step of a run or plan, each + with the run ID. `agent.LogEvents(logger)` sends them to `log/slog`. +- `Result.RunID`, and `*agent.Error{RunID, Stage}` wrapping every error + `agent.Run` returns except `*Pending`. - `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; diff --git a/CLAUDE.md b/CLAUDE.md index 194efd2..aaf46ab 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -17,7 +17,7 @@ Flow: a source (typed Go functions via `capability/gosource`, protos via `buf ge | `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` | +| `agent.PlanStore` | `agent.NewMemoryPlanStore`, `agent/sqlplans` (SQLite and Postgres on `database/sql`) | | `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 f97cf0d..66e326c 100644 --- a/README.md +++ b/README.md @@ -46,14 +46,15 @@ mode, err := codemode.FromSource(source, capability.Caller{Roles: user.Roles}) 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}) + agent.Options{Runner: runner, Plans: plans, PlanOwner: user.ID, OnEvent: agent.LogEvents(logger)}) -// 4. a refund waits for a person +// 4. a refund waits for a person, in your database, until they decide 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) + // send pending.ID and pending.ExpiresAt to the client; later, on approval: + plan, err := plans.Approve(ctx, mode, user.ID, pending.ID) } +// every other error is an *agent.Error carrying result.RunID and the stage that failed ``` No codegen and no `switch` over RPC names. Every call the program makes is @@ -119,7 +120,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) +- [Types and validation](docs/content/types.md) · [Approving writes](docs/content/approval.md) · [Observability](docs/content/observability.md) - [Writes and retries](docs/content/writes.md) · [Caching programs](docs/content/caching.md) **Grow it** diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 8093178..3447f20 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -55,6 +55,7 @@ export default withMermaid( { text: "Roles and tenants", link: "/tenants" }, { text: "Types and validation", link: "/types" }, { text: "Approving writes", link: "/approval" }, + { text: "Observability", link: "/observability" }, { text: "Writes and retries", link: "/writes" }, { text: "Caching programs", link: "/caching" }, ], diff --git a/docs/content/approval.md b/docs/content/approval.md index 8bffb1f..75d8019 100644 --- a/docs/content/approval.md +++ b/docs/content/approval.md @@ -2,86 +2,119 @@ 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. +records the write instead of making it, and leaves a **plan** that waits for a +decision — for minutes or for days. ```go gosource.Func("orders.refund", "Refunds a paid order by ID.", gosource.Roles("support"), shop.Refund, gosource.NeedsApproval()) ``` -In protobuf: +In protobuf: `option (codemode.needs_approval) = true;`. A read cannot need +approval; declaring both is an error when the source is built. -```protobuf -rpc Refund(RefundOrderRequest) returns (RefundOrderResponse) { - option (codemode.description) = "Refunds a paid order by ID."; - option (codemode.needs_approval) = true; -} +## Set up once + +```go +db, _ := sql.Open("sqlite3", "app.db") // or "pgx" for Postgres; your driver +store, _ := sqlplans.Open(ctx, db, sqlplans.SQLite) // creates the codemode_plans table +plans := agent.NewPlans(store, agent.PlanOptions{ + TTL: 24 * time.Hour, // how long a plan waits + OnEvent: agent.LogEvents(logger), // see Observability +}) ``` -A read cannot need approval; declaring both is an error when the source is built. +`agent.NewMemoryPlanStore()` works the same for tests and single-process demos; +it forgets everything on restart. ## 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 + // pending.ID, pending.ExpiresAt, pending.Calls: send them to the client } -// later, when the same user approves: -calls, err := agent.ApplyPlan(ctx, mode, plans, user.ID, id) +inbox, _ := plans.List(ctx, user.ID, agent.PlanPending) // after a reload, tomorrow, anywhere + +plan, err := plans.Approve(ctx, mode, user.ID, id) // runs the calls, once +plan, err := plans.Reject(ctx, user.ID, id, "not now") // runs nothing ``` +`Approve` 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 since +the plan was made cannot apply it. + ```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?" + participant Plans + App->>Plans: agent.Run holds the refund + Plans-->>App: *Pending{ID, ExpiresAt, Calls} + App->>User: "refund order 1? expires tomorrow" + Note over User: later, another device + User->>App: GET inbox + App->>Plans: List(owner, pending) User->>App: approve ID - App->>Agent: ApplyPlan(ID) - Agent-->>App: calls made + App->>Plans: Approve(mode, owner, ID) + Plans-->>App: plan: applied, with each call's result ``` -## What is guaranteed +## States -- 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. +```mermaid +stateDiagram-v2 + [*] --> pending: a run holds a write + pending --> applying: Approve + pending --> rejected: Reject + pending --> expired: read after ExpiresAt + applying --> applied: every call ran + applying --> failed: a call failed + applying --> applying: Resume after a crash +``` -`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. +Every move is recorded in `plan.History` with its time, who made it and a note, +so the plan is its own audit trail. Nothing else is allowed: + +- **Only a pending plan is decided.** Two clicks, two tabs or two replicas + approving at once: the store's compare-and-set lets exactly one through, and + the rest get `ErrPlanDecided`. +- **Expiry** is checked whenever a plan is read — by `Get`, `List`, `Approve` or + `Reject` — and the plan moves to `expired` with an event. No background job. +- **Applying records each call's result before the next one runs.** If the + process dies halfway, the plan stays `applying`; `plans.Resume` continues from + the first call with no result. The call that was in flight may have committed, + so make those handlers idempotent or check before resuming. +- **A failed call stops the plan.** Its status becomes `failed`, later calls do + not run, and `plan.Applied` shows which ran and why the last one failed. + +## Errors say what happened + +| Situation | Error | Message | +| --- | --- | --- | +| Unknown ID, or another owner's | `ErrNoPlan` | `plan 3f2a…: no such plan` | +| Past its time | `ErrPlanExpired` | `plan 3f2a… expired at 2026-11-17T12:00:00Z` | +| Already decided | `ErrPlanDecided` | `plan 3f2a… is already applied (by ada at 2026-11-16T14:02:00Z)` | +| A call failed | wraps the handler's error | `plan 3f2a…: call 2 of 3 (tasks.delete): task is locked` | + +`Approve` and `Reject` return the plan as it stands even with an error, so the +client can show the real state instead of a bare failure. Every plan carries +`RunID`, the run that held it, which ties it to that run's events and errors. ## 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: +keeps plans in its own SQLite file. The chat response carries the plan; the +**Approvals** page lists every plan with its expiry and history from +`GET /api/plans`; Approve and Reject post to `/api/plans/{id}/approve` and +`/reject`, which answer 409 for a decided plan and 410 for an expired one. + +A delete from the task board is a button the user pressed, so the server runs it +with approval granted: ```go approved := codemode.WithRecorder(ctx, &codemode.Recorder{Approved: true}) @@ -90,12 +123,12 @@ 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 -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. +- A held write returns `{}` to the program, so steps that use its output — the + ID of an order it just created — cannot be planned accurately. Approve, then + ask again. +- A plan is decided by its owner. Approval by another role is not built yet. +- MCP clients cannot approve: `run_program` refuses a program that reaches such + a write and names what did not run. +- Without `Options.Plans`, `Pending.ID` is empty; keep `Pending.Calls` yourself + and run them with `agent.Apply`. +- `Options.Plan` still holds *every* write for a dry run, approval or not. diff --git a/docs/content/observability.md b/docs/content/observability.md new file mode 100644 index 0000000..907f2dd --- /dev/null +++ b/docs/content/observability.md @@ -0,0 +1,94 @@ +# Observability + +Every run gets an ID. Its events, its error and any plan it held carry that ID, +so one value finds everything that happened. + +```go +result, err := agent.Run(ctx, mode, model, request, agent.Options{ + Runner: runner, + OnEvent: agent.LogEvents(logger), // log/slog +}) +result.RunID // "7c1e40a2b9d3f051" +``` + +## Events + +`Options.OnEvent` receives one `agent.Event` per step of a run, and +`PlanOptions.OnEvent` one per step of a plan: + +| Kind | When | Useful fields | +| --- | --- | --- | +| `run.started` | the run begins | | +| `search.done` | capabilities matched | `Count`, `Duration` | +| `program.written` | the model wrote a program | `Attempt`, `Duration` | +| `program.failed` | it failed and goes back for repair | `Attempt`, `Err` | +| `call.done` | a capability ran | `Name`, `Duration`, `Err` | +| `call.held` | a write was held for approval | `Name` | +| `run.finished` | an answer, or a plan waiting | `PlanID`, `Duration` | +| `run.failed` | the run gave up | `Stage`, `Err` | +| `plan.held` | a plan was stored | `PlanID`, `Count` | +| `plan.applying` | approved; calls start | `PlanID` | +| `plan.applied` / `plan.failed` | every call ran / one failed | `Name`, `Err` | +| `plan.rejected` / `plan.expired` | decided against / never decided | `PlanID` | + +A failing run reads like this with `LogEvents`: + +``` +level=INFO msg=run.started run=7c1e40a2b9d3f051 +level=INFO msg=search.done run=7c1e40a2b9d3f051 count=5 took=1.2ms +level=INFO msg=program.written run=7c1e40a2b9d3f051 attempt=1 took=2.1s +level=ERROR msg=program.failed run=7c1e40a2b9d3f051 attempt=1 error="invalid input for tasks.list: status: want one of open, completed, got \"done\"" +level=INFO msg=program.written run=7c1e40a2b9d3f051 attempt=2 took=1.8s +level=INFO msg=call.done run=7c1e40a2b9d3f051 capability=tasks.list took=0.4ms +level=INFO msg=run.finished run=7c1e40a2b9d3f051 took=4.0s +``` + +`OnEvent` must not block. Send events to a channel or a buffered logger if the +sink is slow. + +## Errors + +Every error `agent.Run` returns — except `*agent.Pending`, which is not a +failure — is an `*agent.Error`: + +```go +var failure *agent.Error +if errors.As(err, &failure) { + failure.RunID // the same ID as the events + failure.Stage // agent.StageCache, StageSearch, StageGenerate or StageRun +} +// run 7c1e40a2b9d3f051: run: gave up after 3 attempts: invalid input for tasks.list: status: ... +``` + +`errors.Is` sees through it: `ErrNotRetried`, `ErrTokenBudget`, +`codemode.ErrPermanent` and your own handler errors still match. + +| Stage | Means | Look at | +| --- | --- | --- | +| `cache` | a cached program failed after writing | the program cache | +| `search` | search failed or matched nothing | capability descriptions, the caller's roles | +| `generate` | the model call failed | the provider, key, timeout | +| `run` | the program kept failing | the `program.failed` events: each says why | + +## Tracing and metrics + +The core links no telemetry SDK. Adapt `OnEvent` in your application: + +```go +OnEvent: func(event agent.Event) { + span := trace.SpanFromContext(ctx) // your OpenTelemetry span for the request + span.AddEvent(event.Kind, trace.WithAttributes( + attribute.String("codemode.run", event.RunID), + attribute.String("codemode.plan", event.PlanID), + attribute.String("codemode.capability", event.Name), + )) + if event.Err != "" { + span.RecordError(errors.New(event.Err)) + } + runs.Add(ctx, 1, metric.WithAttributes(attribute.String("kind", event.Kind))) +}, +``` + +Worth a dashboard: `plan.held` minus decided (plans waiting), the time from +`plan.held` to `plan.applying` (how long people take), `program.failed` per run +(how often the model needs repair), and `call.done` with `Err` by capability. diff --git a/docs/content/quickstart.md b/docs/content/quickstart.md index 550df2c..b925187 100644 --- a/docs/content/quickstart.md +++ b/docs/content/quickstart.md @@ -165,7 +165,7 @@ func main() { } func refund(ctx context.Context, mode codemode.CodeMode, model llm.Client, runner sandbox.Runner, request string) { - plans := agent.NewMemoryPlans(0) + plans := agent.NewPlans(agent.NewMemoryPlanStore(), agent.PlanOptions{}) _, err := agent.Run(ctx, mode, model, request, agent.Options{Runner: runner, Plans: plans, PlanOwner: "you"}) var pending *agent.Pending if !errors.As(err, &pending) { @@ -179,14 +179,15 @@ func refund(ctx context.Context, mode codemode.CodeMode, model llm.Client, runne var answer string fmt.Scanln(&answer) if answer != "y" { + plans.Reject(ctx, "you", pending.ID, "declined at the prompt") fmt.Println("nothing changed") return } - calls, err := agent.ApplyPlan(ctx, mode, plans, "you", pending.ID) + plan, err := plans.Approve(ctx, mode, "you", pending.ID) if err != nil { - log.Fatal(err) + log.Fatal(err) // names the plan and the call that failed } - fmt.Printf("ran %d call(s)\n", len(calls)) + fmt.Printf("ran %d call(s)\n", len(plan.Applied)) } ``` @@ -273,8 +274,10 @@ ran 1 call(s) `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. +kept under an ID with an expiry, and `plans.Approve` ran it once you said yes. +Answer anything but `y` and `plans.Reject` discards it. Plans here live in +memory; [Approving writes](/approval) keeps them in your database so the answer +can come tomorrow. Change the caller to `capability.Caller{Roles: []string{"customer"}}` and `orders.refund` disappears: not in the prompt, and not callable. diff --git a/docs/content/types.md b/docs/content/types.md index 4217cd4..ce09666 100644 --- a/docs/content/types.md +++ b/docs/content/types.md @@ -7,7 +7,8 @@ Codemode checks values at the two places the model's program meets your code. | 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 +Every check that fails is also a `program.failed` event, carrying the run ID; see +[Observability](/observability). A program that already ran a write is never repaired, so a write cannot happen twice. See [Writes and retries](/writes). ## Input diff --git a/notes/decisions/0009-durable-plans.md b/notes/decisions/0009-durable-plans.md new file mode 100644 index 0000000..830aa0e --- /dev/null +++ b/notes/decisions/0009-durable-plans.md @@ -0,0 +1,44 @@ +# 0009 — Plans are rows, not processes + +**Status:** accepted +**Date:** 2026-11-16 + +## Context + +A held write waits for a person, and a person may answer tomorrow. Three shapes +can hold that wait: an actor per plan, a durable workflow engine that suspends +the program, or a row in a database. + +An in-process actor dies with the process and lives on one replica, so it needs +a database and routing anyway. A workflow engine gives true continuations — the +program resumes with the real result of the approved write — but it needs its +own infrastructure and a sandbox that replays deterministically. Neither is +needed for the cases in front of us: the program has already finished, and what +waits is a list of calls. + +## Decision + +A plan is a row with a status, a version and a history. `agent.Plans` moves it +through `pending → applying → applied | failed`, or to `rejected` or `expired`, +and every move is a compare-and-set on the version, so the database serialises +decisions across replicas. Expiry is checked on read. Applying records each +call's result before the next, so a crash can be resumed rather than lost. + +The storage port is four methods. `agent/sqlplans` implements it once on +`database/sql` for SQLite and Postgres; a host on Cloudflare can implement it on +a Durable Object without touching `agent`. + +Every run gets an ID that its error, its events and its plan all carry. +Observability is one callback, `OnEvent`; `LogEvents` adapts it to `slog`, and +telemetry SDKs stay in the host. + +## Consequences + +- `NewMemoryPlans` and `ApplyPlan` are replaced by `NewPlans` and + `Plans.Approve` before either was released. +- A held write still returns `{}` to the program. Continuations would need the + workflow-engine shape; revisit when a host needs chained approvals. +- `Resume` re-runs the call that was in flight at the crash. Handlers of writes + that need approval should be idempotent, or the host checks before resuming. +- A plan is approved by its owner. Approval by another role is a later change to + `Plans`, not to the store. diff --git a/notes/milestones/2026-11-durable-plans.md b/notes/milestones/2026-11-durable-plans.md new file mode 100644 index 0000000..6f72501 --- /dev/null +++ b/notes/milestones/2026-11-durable-plans.md @@ -0,0 +1,117 @@ +# Durable plans, events and traceable errors + +Depends on: [pluggable sources](2026-11-pluggable-sources.md) · Decision: +[0009](../decisions/0009-durable-plans.md) + +## Problem + +A write that needs approval is held in a plan, but the plan only lives as long +as the response that carried its ID: + +- the memory store loses it on restart, and a second replica never sees it; +- the client cannot list what is waiting, so a refresh loses it; +- expiry is fifteen minutes and the client is never told; it learns from a 404; +- there is no status or history: a plan is either there or silently gone; +- a crash halfway through applying loses the plan after some writes ran. + +And when a run fails, nothing ties the error, the logs and the plan together. + +## Goal + +A person can decide tomorrow, on another device, against another replica, and +the developer can see every step a run and its plan took. + +```go +plans := agent.NewPlans(store, agent.PlanOptions{TTL: 24 * time.Hour, OnEvent: events}) + +_, err := agent.Run(ctx, mode, model, request, agent.Options{ + Runner: runner, Plans: plans, PlanOwner: user.ID, OnEvent: events, +}) +var pending *agent.Pending // pending.ID, pending.Calls, pending.ExpiresAt +var failed *agent.Error // failed.RunID, failed.Stage + +inbox, _ := plans.List(ctx, user.ID, agent.PlanPending) +plan, err := plans.Approve(ctx, mode, user.ID, id) +plan, err := plans.Reject(ctx, user.ID, id, "not now") +``` + +## Design + +One object, `agent.Plans`, is the whole approval API. The storage behind it is a +four-method port, so a database adapter stays small: + +```go +type PlanStore interface { + Create(ctx, Plan) error + Get(ctx, owner, id string) (Plan, error) + List(ctx, owner string, status PlanStatus) ([]Plan, error) + Update(ctx, *Plan) error // only if the stored version is plan.Version; then bumps it +} +``` + +A plan is a row, not a process. No actor and no workflow engine: the database +serialises decisions with a compare-and-set on `version`, so two clicks or two +replicas cannot both apply a plan. + +```mermaid +stateDiagram-v2 + [*] --> pending: run holds a write + pending --> applying: Approve + pending --> rejected: Reject + pending --> expired: read after ExpiresAt + applying --> applied: every call ran + applying --> failed: a call failed + applying --> applying: Resume after a crash +``` + +- **Expiry** is checked when a plan is read (`Get`, `List`, `Approve`), and the + plan is moved to `expired` with an event. No sweeper goroutine. +- **History** records every move with its time, who made it and a note. +- **Apply** records each call's result before the next one runs, so `Resume` + continues from the first call without a result after a crash. +- **Errors** name the plan and its state: + `plan 3f2a9c1e is already applied (by ada at 2026-11-16T14:02:00Z)`, wrapping + `ErrPlanDecided`; a failed call is `plan 3f2a9c1e: call 2 of 3 (tasks.delete): …`. + +`agent/sqlplans` implements the port on `database/sql` for SQLite and Postgres, +with the standard library only; the host opens the database with its own driver. + +### Events and errors + +`Options.OnEvent` and `PlanOptions.OnEvent` receive one `agent.Event` per step: +`run.started`, `search.done`, `program.written`, `program.failed`, `call.done`, +`call.held`, `run.finished`, `run.failed`, and `plan.held`, `plan.applying`, +`plan.applied`, `plan.failed`, `plan.rejected`, `plan.expired`. Each carries the +run ID and, where there is one, the plan ID. `agent.LogEvents(logger)` sends them +to `log/slog`. Tracing and metrics are the host's adapter over the same callback, +so the core links no telemetry SDK. + +Every error `agent.Run` returns, except `*Pending`, is an `*agent.Error` with the +run ID and the stage it failed in (`cache`, `search`, `generate`, `run`): +`run 7c1e40a2b9d3f051: generate: …`. The plan records the run ID too, so a +plan, its run, its events and its error share one key. + +## Tasks + +1. `agent`: `Plan`, `PlanStatus`, transitions, `Plans` (`Get`, `List`, `Approve`, + `Reject`, `Resume`), `NewMemoryPlanStore`, `Pending` embedding `Plan`. + Replaces `NewMemoryPlans` and `ApplyPlan` (unreleased). +2. `agent`: `Event`, `Options.OnEvent`, `LogEvents`, `Error`, `Result.RunID`. +3. `agent/plantest.Run`: the contract every `PlanStore` passes. +4. `agent/sqlplans`: SQLite and Postgres on `database/sql`. +5. Examples: shop and taskreport on `Plans`; taskreport keeps plans in its own + SQLite file, lists them at `GET /api/plans`, and shows an inbox with expiry + and each plan's history. +6. Docs: approval rewritten around `Plans`, a new observability page, changelog. + +## Out of scope + +Approvers other than the owner (a manager approving a refund); an OpenTelemetry +adapter package; notifications beyond the `plan.held` event; mocked outputs for +held writes. + +## Done when + +A plan survives a restart, lists in an inbox with its expiry, applies once +across replicas, resumes after a crash, and every run's error and events carry +the same run ID.