diff --git a/cmd/archied/model_catalog.go b/cmd/archied/model_catalog.go index f18174111..c87274d3e 100644 --- a/cmd/archied/model_catalog.go +++ b/cmd/archied/model_catalog.go @@ -11,15 +11,19 @@ import ( func applyModelCatalog(cfg *config.Config, snapshot modelcatalog.Snapshot) []string { discovered := make(map[string]config.Provider, len(snapshot.Providers)) + limits := make(map[string]config.ModelLimits) var models []string for _, provider := range snapshot.Providers { discovered[provider.ID] = config.Provider{ Class: provider.Class, APIKeyEnv: provider.APIKeyEnv, BaseURL: provider.BaseURL, } for _, model := range provider.Models { - models = append(models, provider.ID+"/"+model.ID) + ref := provider.ID + "/" + model.ID + models = append(models, ref) + limits[ref] = config.ModelLimits{ContextWindow: model.ContextWindow, MaxOutputTokens: model.MaxOutputTokens} } } + cfg.ModelLimits = limits cfg.Providers = mergeProviders(discovered, cfg.Providers) for i := range cfg.Identities { cfg.Identities[i].Providers = mergeProviders(discovered, cfg.Identities[i].Providers) diff --git a/cmd/archied/model_catalog_test.go b/cmd/archied/model_catalog_test.go index 4c5b43006..3ffabdff7 100644 --- a/cmd/archied/model_catalog_test.go +++ b/cmd/archied/model_catalog_test.go @@ -23,7 +23,7 @@ func TestApplyModelCatalogNormalizesEveryExecutionScope(t *testing.T) { { ID: "openai", Class: "openai", APIKeyEnv: "OPENAI_API_KEY", BaseURL: "https://api.openai.test/v1", - Models: []modelcatalog.Model{{ID: "gpt-tool"}}, + Models: []modelcatalog.Model{{ID: "gpt-tool", ContextWindow: 128_000, MaxOutputTokens: 16_000}}, }, { ID: "anthropic", Class: "anthropic", APIKeyEnv: "ANTHROPIC_API_KEY", @@ -49,4 +49,7 @@ func TestApplyModelCatalogNormalizesEveryExecutionScope(t *testing.T) { if !reflect.DeepEqual(models, wantModels) { t.Fatalf("models = %v, want %v", models, wantModels) } + if got := cfg.ModelLimits["openai/gpt-tool"]; got.ContextWindow != 128_000 || got.MaxOutputTokens != 16_000 { + t.Fatalf("model limits = %+v, want catalog capacity", got) + } } diff --git a/cmd/archied/reload.go b/cmd/archied/reload.go index 31f05aa4f..0479ebc7e 100644 --- a/cmd/archied/reload.go +++ b/cmd/archied/reload.go @@ -145,11 +145,23 @@ var reloadableFields = map[string]bool{ "Budgets": true, "Dispatch": true, "Models": true, + "ModelLimits": true, "Notify": true, - // Per-poll reads off the live config in pollIssuesWithConfig: - // cfg.Label feeds IssuesWithLabel (daemon.go:359,390), cfg.BotUser - // feeds AssignedIssues (:368,381). Not carried by ForTask, so - // pinned by hand in TestReloadableFieldsCoverForTaskSnapshot. + // BotUser/BotEmail used to be poll-path only; ForTask now carries both + // into the task snapshot as well, because the sandboxed worker builds + // its own worktree.Manager and signs its own commits (agentworker + // task_execution.go, config.go ForTask). The commit identity is + // therefore per-dispatch and does reload. The startup-built daemon + // trees (bootstrap.go:654) still capture both, but only to record + // user.name/user.email in the clone's own .git/config + // (worktree.go setIdentity) -- cosmetic, not the signature go-git + // commits with -- so a reload applies where it counts and this stays + // reloadable rather than requires-restart. + "BotEmail": true, + // cfg.Label additionally feeds IssuesWithLabel per poll cycle + // (daemon.go:359,390) and cfg.BotUser feeds AssignedIssues (:364,377). + // Label is not carried by ForTask, so it is pinned by hand in + // TestReloadableFieldsCoverForTaskSnapshot. "Label": true, "BotUser": true, // Worked example of the every-consumer criterion above: the sole diff --git a/cmd/archied/reload_test.go b/cmd/archied/reload_test.go index 6cdadbe73..1bf005f36 100644 --- a/cmd/archied/reload_test.go +++ b/cmd/archied/reload_test.go @@ -287,9 +287,11 @@ func TestReloadableFieldsCoverForTaskSnapshot(t *testing.T) { t.Errorf("ForTask field %s is not allowlisted as reloadable", name) } } - // The poll-path fields (Label, BotUser) are not carried by ForTask; - // pin them explicitly so a refactor that moves their read site does - // not silently drop the allowlist entry. + // Label is not carried by ForTask; BotUser now is, but it is also read + // on the poll path independently of the task snapshot. Pin both by hand + // so a refactor that moves either read site -- including one that drops + // BotUser from ForTask again -- does not silently drop the allowlist + // entry the poll path still depends on. for _, name := range []string{"Label", "BotUser"} { if !reloadableFields[name] { t.Errorf("poll-path field %s is not allowlisted as reloadable", name) diff --git a/docs/data/generated/contracts.json b/docs/data/generated/contracts.json index d672cffe2..626b8f565 100644 --- a/docs/data/generated/contracts.json +++ b/docs/data/generated/contracts.json @@ -17,6 +17,9 @@ }, "type": "array" }, + "context_window": { + "type": "integer" + }, "extra_rules": { "type": "string" }, @@ -127,6 +130,9 @@ "tokens_used": { "type": "integer" }, + "usage": { + "$ref": "#/schemas/Usage" + }, "version": { "type": "integer" } @@ -258,6 +264,10 @@ "description": "MIMEType is the content type (e.g. \"image/png\", \"audio/ogg\").", "type": "string" }, + "path": { + "description": "Path is a local filesystem path on the host that produced the\nattachment. It is the alternative to URL for outbound delivery: a\nURL is fetched by the platform, a Path is uploaded by us. A file the\nagent wrote has no URL and never gets one -- publishing it would\ntrade a delivery problem for a hosting and access-control one -- so\nsenders that support upload must read this.\n\nExactly one of URL and Path is meaningful for an outbound send.", + "type": "string" + }, "type": { "description": "Type is \"image\", \"video\", \"audio\", or \"document\".", "type": "string" @@ -392,6 +402,28 @@ } }, "type": "object" + }, + "Usage": { + "additionalProperties": false, + "description": "Usage preserves provider-reported token economics for evaluation.", + "properties": { + "cache_creation_tokens": { + "type": "integer" + }, + "cached_tokens": { + "type": "integer" + }, + "completion_tokens": { + "type": "integer" + }, + "prompt_tokens": { + "type": "integer" + }, + "total_tokens": { + "type": "integer" + } + }, + "type": "object" } } } diff --git a/go.mod b/go.mod index 8ad268b0a..6463854c1 100644 --- a/go.mod +++ b/go.mod @@ -72,7 +72,7 @@ require ( github.com/moby/moby/client v0.5.1 github.com/nats-io/nats-server/v2 v2.14.4 github.com/nats-io/nats.go v1.52.0 - github.com/samcharles93/ai-sdk v0.1.22 + github.com/samcharles93/ai-sdk v0.1.25 github.com/traefik/yaegi v0.16.1 golang.org/x/net v0.57.0 golang.org/x/term v0.45.0 diff --git a/go.sum b/go.sum index eab955d28..32ef8d7ce 100644 --- a/go.sum +++ b/go.sum @@ -126,12 +126,8 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= -github.com/samcharles93/ai-sdk v0.1.20 h1:Z52dyMN293aV8Cpgjdyyd2zw6oNF5FSXKWfCuxY/3UA= -github.com/samcharles93/ai-sdk v0.1.20/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o= -github.com/samcharles93/ai-sdk v0.1.21 h1:V/OqLnoWuZQ/8qw6MiVZuQU5qVLkULGex6WMQYCbCg4= -github.com/samcharles93/ai-sdk v0.1.21/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o= -github.com/samcharles93/ai-sdk v0.1.22 h1:IIV1HVOzCKMQl5MvZ23WzEzaOyHpnT8QcoN8ihFi9Xc= -github.com/samcharles93/ai-sdk v0.1.22/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o= +github.com/samcharles93/ai-sdk v0.1.25 h1:30cvHZBw01XRif2cOG/PToC7xTQUZ5DHwMOShT8zSnw= +github.com/samcharles93/ai-sdk v0.1.25/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o= github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw= github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= diff --git a/internal/agentexec/loop_runner.go b/internal/agentexec/loop_runner.go index 4a18ccdf6..6632d1df6 100644 --- a/internal/agentexec/loop_runner.go +++ b/internal/agentexec/loop_runner.go @@ -103,6 +103,12 @@ func (r *LoopRunner) Run(ctx context.Context, workspace string, req Request, rep MaxSteps: req.Budget.MaxSteps, WallClock: req.Budget.WallClock, }, + Compact: agentloop.CompactionConfig{ + Enabled: req.ContextWindow > 0, + ContextWindow: req.ContextWindow, + ThresholdRatio: 0.5, + TargetRatio: 0.15, + }, Completion: agentloop.CompletionForceFinish, ReadOnly: req.ReadOnly, ProtectPaths: protectionMatcher(req.Protection, req.ReadOnly), @@ -114,19 +120,34 @@ func (r *LoopRunner) Run(ctx context.Context, workspace string, req Request, rep ), Logger: r.logger(req), }) + result := resultFromRun(req, res, notes.appended, captures) + if cause := context.Cause(ctx); cause != nil { + return result, cause + } + return result, err +} + +func resultFromRun(req Request, res agentloop.Result, appended []string, captures map[string][]json.RawMessage) Result { result := Result{ - Version: ProtocolVersion, - TaskID: req.TaskID, - Attempt: req.Attempt, - Stage: req.Stage, - Status: string(res.Status), - StopReason: res.StopReason, - Changes: res.Changes, - Iterations: res.Iterations, - TokensUsed: res.TokensUsed, + Version: ProtocolVersion, + TaskID: req.TaskID, + Attempt: req.Attempt, + Stage: req.Stage, + Status: string(res.Status), + StopReason: res.StopReason, + Changes: res.Changes, + Iterations: res.Iterations, + TokensUsed: res.TokensUsed, + Usage: Usage{ + PromptTokens: res.Usage.PromptTokens, + CompletionTokens: res.Usage.CompletionTokens, + TotalTokens: res.Usage.TotalTokens, + CachedTokens: res.Usage.CachedTokens, + CacheCreationTokens: res.Usage.CacheCreationTokens, + }, Summary: res.Summary, Detail: res.Detail, - AppendedNotes: notes.appended, + AppendedNotes: appended, Captures: captures, } // agentloop may return a zero-valued status on early exit (model @@ -136,10 +157,7 @@ func (r *LoopRunner) Run(ctx context.Context, workspace string, req Request, rep result.Status = "blocked" result.Detail = "agent returned no status (possible model connectivity issue)" } - if cause := context.Cause(ctx); cause != nil { - return result, cause - } - return result, err + return result } func projectScopedRules(workspace, extra string) string { diff --git a/internal/agentexec/loop_runner_test.go b/internal/agentexec/loop_runner_test.go index 704ac9cb0..0923f8918 100644 --- a/internal/agentexec/loop_runner_test.go +++ b/internal/agentexec/loop_runner_test.go @@ -11,6 +11,7 @@ import ( "time" "github.com/samcharles93/ai-sdk/agentloop" + "github.com/samcharles93/ai-sdk/chat" "github.com/samcharles93/ai-sdk/runtime" "github.com/samcharles93/archie-core/internal/tools" @@ -70,6 +71,9 @@ func TestLoopRunnerMapsRequestAndCapturesOutput(t *testing.T) { if cfg.Completion != agentloop.CompletionForceFinish { t.Fatalf("Completion = %q, want forced finish recovery", cfg.Completion) } + if !cfg.Compact.Enabled || cfg.Compact.ContextWindow <= 0 { + t.Fatalf("Compact = %#v, want adaptive non-blocking history compaction", cfg.Compact) + } if !strings.Contains(cfg.ExtraRules, "Confine discovery to /workspace") || !strings.Contains(cfg.ExtraRules, "unless the mission explicitly requests") { t.Fatalf("project discovery rule missing from ExtraRules: %q", cfg.ExtraRules) @@ -80,11 +84,14 @@ func TestLoopRunnerMapsRequestAndCapturesOutput(t *testing.T) { if _, err := cfg.Extra["decide"].Execute(ctx, `{"fit":true}`); err != nil { t.Fatal(err) } - return agentloop.Result{Status: agentloop.StatusPassed, Summary: "done", TokensUsed: 10}, nil + return agentloop.Result{ + Status: agentloop.StatusPassed, Summary: "done", TokensUsed: 10, + Usage: chat.Usage{PromptTokens: 8, CompletionTokens: 2, TotalTokens: 10, CachedTokens: 6}, + }, nil }, } req := Request{ - Version: ProtocolVersion, TaskID: 1, Attempt: 1, Stage: "assess", Model: "provider/model", Mission: "mission", + Version: ProtocolVersion, TaskID: 1, Attempt: 1, Stage: "assess", Model: "provider/model", ContextWindow: 120_000, Mission: "mission", Protection: Protection{Suffixes: []string{"_templ.go"}, Globs: []string{"*_test.go"}}, CaptureTools: []CaptureTool{{Name: "decide", Parameters: json.RawMessage(`{"type":"object"}`), MaxCalls: 1}}, } @@ -95,6 +102,9 @@ func TestLoopRunnerMapsRequestAndCapturesOutput(t *testing.T) { if got.Status != StatusPassed || got.Summary != "done" || got.TokensUsed != 10 { t.Fatalf("unexpected result: %#v", got) } + if got.Usage.PromptTokens != 8 || got.Usage.CompletionTokens != 2 || got.Usage.CachedTokens != 6 { + t.Fatalf("usage = %#v, want provider breakdown", got.Usage) + } if len(got.AppendedNotes) != 1 || got.AppendedNotes[0] != "verified note" { t.Fatalf("appended notes = %v", got.AppendedNotes) } diff --git a/internal/agentexec/protocol.go b/internal/agentexec/protocol.go index a6775288a..090e6cbd3 100644 --- a/internal/agentexec/protocol.go +++ b/internal/agentexec/protocol.go @@ -60,21 +60,22 @@ type CaptureTool struct { // map a host path to a fixed path without exposing host layout in the wire // protocol. type Request struct { - Version int `json:"version"` - TaskID int64 `json:"task_id"` - Attempt int `json:"attempt"` - Stage string `json:"stage"` - Workflow string `json:"workflow,omitempty"` - Model string `json:"model"` - Mission string `json:"mission"` - ExtraRules string `json:"extra_rules,omitempty"` - ReadOnly bool `json:"read_only,omitempty"` - Budget Budget `json:"budget"` - Gate Gate `json:"gate"` - Preflight []Command `json:"preflight,omitempty"` - Protection Protection `json:"protection"` - Notes string `json:"notes,omitempty"` - CaptureTools []CaptureTool `json:"capture_tools,omitempty"` + Version int `json:"version"` + TaskID int64 `json:"task_id"` + Attempt int `json:"attempt"` + Stage string `json:"stage"` + Workflow string `json:"workflow,omitempty"` + Model string `json:"model"` + ContextWindow int `json:"context_window,omitempty"` + Mission string `json:"mission"` + ExtraRules string `json:"extra_rules,omitempty"` + ReadOnly bool `json:"read_only,omitempty"` + Budget Budget `json:"budget"` + Gate Gate `json:"gate"` + Preflight []Command `json:"preflight,omitempty"` + Protection Protection `json:"protection"` + Notes string `json:"notes,omitempty"` + CaptureTools []CaptureTool `json:"capture_tools,omitempty"` // Plugins are bundled Yaegi plugins from the skill's plugins/ // directory. Each entry carries the name and source so the agent // can register them as tools. PRD section 5 Layer 1. @@ -118,12 +119,23 @@ type Result struct { Changes []string `json:"changes,omitempty"` Iterations int `json:"iterations,omitempty"` TokensUsed int `json:"tokens_used,omitempty"` + Usage Usage `json:"usage"` Summary string `json:"summary,omitempty"` Detail string `json:"detail,omitempty"` AppendedNotes []string `json:"appended_notes,omitempty"` Captures map[string][]json.RawMessage `json:"captures,omitempty"` } +// Usage preserves provider-reported token economics for evaluation. Total is +// retained separately as TokensUsed for compatibility with stored task rows. +type Usage struct { + PromptTokens int `json:"prompt_tokens,omitempty"` + CompletionTokens int `json:"completion_tokens,omitempty"` + TotalTokens int `json:"total_tokens,omitempty"` + CachedTokens int `json:"cached_tokens,omitempty"` + CacheCreationTokens int `json:"cache_creation_tokens,omitempty"` +} + // Provider describes how the worker resolves a model provider. API keys are // referenced by environment variable name and never serialized. type Provider struct { diff --git a/internal/app/agentworker/task_execution.go b/internal/app/agentworker/task_execution.go index 2cb687372..7ccdcc719 100644 --- a/internal/app/agentworker/task_execution.go +++ b/internal/app/agentworker/task_execution.go @@ -147,8 +147,12 @@ func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependen wf := workflow.Route(req.Task, registry) trees := &hybridTrees{ - push: dependencies.trees, - local: &worktree.Manager{WorkDir: workDir}, + push: dependencies.trees, + local: &worktree.Manager{ + WorkDir: workDir, + BotUser: req.Cfg.BotUser, + BotEmail: req.Cfg.BotEmail, + }, localDir: workDir, branch: req.Task.Branch, worktreeUID: worktreeOwnerID(os.Getenv("WORKTREE_UID")), diff --git a/internal/app/agentworker/task_execution_test.go b/internal/app/agentworker/task_execution_test.go index d2d1418af..bd10329e5 100644 --- a/internal/app/agentworker/task_execution_test.go +++ b/internal/app/agentworker/task_execution_test.go @@ -12,6 +12,7 @@ import ( "testing" "time" + "github.com/go-git/go-git/v6" "github.com/nats-io/nats-server/v2/server" natssrv "github.com/nats-io/nats-server/v2/test" natsio "github.com/nats-io/nats.go" @@ -337,7 +338,11 @@ func TestRunTaskExecutesBootstrapWorkflowEndToEnd(t *testing.T) { if err != nil { t.Fatalf("prepare: %v", err) } - req := taskrun.Request{Task: task, Repo: config.Repo{Owner: "acme", Name: "widget", Base: "main"}, Cfg: config.Config{}.ForTask()} + req := taskrun.Request{ + Task: task, + Repo: config.Repo{Owner: "acme", Name: "widget", Base: "main"}, + Cfg: config.Config{BotUser: "archie-bot", BotEmail: "archie-bot@example.com"}.ForTask(), + } fakeRunner := runnerFactory(func(map[string]agentexec.Provider, *slog.Logger) agentexec.Runner { return panicRunner{t} }) response, err := runTask(ctx, req, taskDependencies{forge: fg, store: st, trees: remote}, fakeRunner, hostDir, slog.New(slog.DiscardHandler)) if err != nil { @@ -353,6 +358,23 @@ func TestRunTaskExecutesBootstrapWorkflowEndToEnd(t *testing.T) { if _, err := os.Stat(filepath.Join(hostDir, ".archie", "bootstrap.md")); err != nil { t.Fatalf("expected bootstrap marker file: %v", err) } + repo, err := git.PlainOpen(hostDir) + if err != nil { + t.Fatal(err) + } + head, err := repo.Head() + if err != nil { + t.Fatal(err) + } + commit, err := repo.CommitObject(head.Hash()) + if err != nil { + t.Fatal(err) + } + if commit.Author.Name != "archie-bot" || commit.Author.Email != "archie-bot@example.com" || + commit.Committer.Name != "archie-bot" || commit.Committer.Email != "archie-bot@example.com" { + t.Fatalf("commit identity = author %q <%s>, committer %q <%s>", + commit.Author.Name, commit.Author.Email, commit.Committer.Name, commit.Committer.Email) + } } // TestExecuteTaskRequestUsesInfrastructureRPCDependencies preserves the diff --git a/internal/config/clone_test.go b/internal/config/clone_test.go index cef6b680e..0a8a228d9 100644 --- a/internal/config/clone_test.go +++ b/internal/config/clone_test.go @@ -9,8 +9,9 @@ import "testing" func TestConfigCloneDeepCopiesReferenceFields(t *testing.T) { enabled := true orig := Config{ - Models: map[string]string{"builder": "m"}, - Repos: []Repo{{Gate: [][]string{{"task", "check"}}, Protect: []string{"p"}}}, + Models: map[string]string{"builder": "m"}, + ModelLimits: map[string]ModelLimits{"m": {ContextWindow: 128_000}}, + Repos: []Repo{{Gate: [][]string{{"task", "check"}}, Protect: []string{"p"}}}, Identities: []IdentityConfig{{ Models: map[string]string{"planner": "m2"}, Repos: []Repo{{Gate: [][]string{{"go", "vet"}}}}, @@ -28,6 +29,7 @@ func TestConfigCloneDeepCopiesReferenceFields(t *testing.T) { got := orig.Clone() got.Models["builder"] = "changed" + got.ModelLimits["m"] = ModelLimits{ContextWindow: 1} got.Repos[0].Gate[0][0] = "changed" got.Repos[0].Protect[0] = "changed" got.Identities[0].Models["planner"] = "changed" @@ -44,6 +46,9 @@ func TestConfigCloneDeepCopiesReferenceFields(t *testing.T) { if orig.Models["builder"] != "m" { t.Error("Models map is shared") } + if orig.ModelLimits["m"].ContextWindow != 128_000 { + t.Error("ModelLimits map is shared") + } if orig.Repos[0].Gate[0][0] != "task" || orig.Repos[0].Protect[0] != "p" { t.Error("Repo nested slices are shared") } diff --git a/internal/config/config.go b/internal/config/config.go index c047e41ba..11adcee38 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -439,8 +439,9 @@ type Config struct { // namespace. When empty, the single-identity fields (BotUser, // Forge, Repos, Models, Providers, Dispatch, PollInterval) are used // unchanged for backward compatibility. - Identities []IdentityConfig `toml:"identities" yaml:"identities"` - Repos []Repo `toml:"repos" yaml:"repos"` + Identities []IdentityConfig `toml:"identities" yaml:"identities"` + Repos []Repo `toml:"repos" yaml:"repos"` + ModelLimits map[string]ModelLimits `toml:"-" yaml:"-" json:"-"` // Extra holds additional feature configuration from conf.d/ files that // don't match a known feature name. Keys are the filename stem (e.g. @@ -475,15 +476,25 @@ type IdentityConfig struct { Repos []Repo `toml:"repos" yaml:"repos"` } +type ModelLimits struct { + ContextWindow int `json:"context_window"` + MaxOutputTokens int `json:"max_output_tokens"` +} + // TaskConfig is the non-secret subset of Config needed to run workflow // stages. It is safe to send to an archie-agent container. type TaskConfig struct { - Models map[string]string `json:"models"` - Budgets Budgets `json:"budgets"` - Dispatch Dispatch `json:"dispatch"` - DiffCapLines int `json:"diff_cap_lines"` - Notify Notify `json:"notify"` - Forge TaskForge `json:"forge"` + // BotUser and BotEmail are non-secret commit attribution carried to the + // sandbox because the worker owns local deterministic commits. + BotUser string `json:"bot_user"` + BotEmail string `json:"bot_email"` + Models map[string]string `json:"models"` + ModelLimits map[string]ModelLimits `json:"model_limits,omitempty"` + Budgets Budgets `json:"budgets"` + Dispatch Dispatch `json:"dispatch"` + DiffCapLines int `json:"diff_cap_lines"` + Notify Notify `json:"notify"` + Forge TaskForge `json:"forge"` } // TaskForge is the non-secret forge configuration needed by workflow stages. @@ -495,7 +506,10 @@ type TaskForge struct { // needed to run a workflow. func (c Config) ForTask() TaskConfig { return TaskConfig{ + BotUser: c.BotUser, + BotEmail: c.BotEmail, Models: cloneStringMap(c.Models), + ModelLimits: maps.Clone(c.ModelLimits), Budgets: c.Budgets, Dispatch: Dispatch{Trigger: c.Dispatch.Trigger, AckReaction: c.Dispatch.AckReaction, Labels: cloneStringMap(c.Dispatch.Labels)}, DiffCapLines: c.DiffCapLines, @@ -510,7 +524,10 @@ func (c Config) ForTask() TaskConfig { // workflow stages read via TaskContext.Cfg. func (tc TaskConfig) ToConfig() Config { return Config{ + BotUser: tc.BotUser, + BotEmail: tc.BotEmail, Models: cloneStringMap(tc.Models), + ModelLimits: maps.Clone(tc.ModelLimits), Budgets: tc.Budgets, Dispatch: Dispatch{Trigger: tc.Dispatch.Trigger, AckReaction: tc.Dispatch.AckReaction, Labels: cloneStringMap(tc.Dispatch.Labels)}, DiffCapLines: tc.DiffCapLines, @@ -537,6 +554,7 @@ func cloneStringMap(src map[string]string) map[string]string { // are shared with the published snapshot. func (c Config) Clone() Config { c.Models = cloneStringMap(c.Models) + c.ModelLimits = maps.Clone(c.ModelLimits) c.Providers = maps.Clone(c.Providers) c.Dispatch.Labels = cloneStringMap(c.Dispatch.Labels) c.LegacyAgent.Env = append([]string(nil), c.LegacyAgent.Env...) diff --git a/internal/config/config_test.go b/internal/config/config_test.go index cf91a23c9..0ca4bd1fa 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -14,6 +14,8 @@ import ( func TestTaskConfigToConfigRoundTrip(t *testing.T) { cfg := Config{ + BotUser: "archie-bot", + BotEmail: "archie-bot@users.noreply.github.com", DiffCapLines: 321, Models: map[string]string{"builder": "anthropic/claude"}, Budgets: Budgets{MaxSteps: 12, WallClock: Duration(45 * time.Minute), GateMaxFailures: 3}, @@ -114,6 +116,8 @@ func TestConfigForTaskJSONRoundTrip(t *testing.T) { } want := TaskConfig{ + BotUser: cfg.BotUser, + BotEmail: cfg.BotEmail, Models: cfg.Models, Budgets: cfg.Budgets, Dispatch: cfg.Dispatch, @@ -146,7 +150,7 @@ func TestConfigForTaskJSONRoundTrip(t *testing.T) { if err != nil { t.Fatal(err) } - assertJSONKeys(t, data, "models", "budgets", "dispatch", "diff_cap_lines", "notify", "forge") + assertJSONKeys(t, data, "bot_user", "bot_email", "models", "budgets", "dispatch", "diff_cap_lines", "notify", "forge") var forgePayload map[string]json.RawMessage var payload map[string]json.RawMessage diff --git a/internal/domain/workflow/agent.go b/internal/domain/workflow/agent.go index 7a4b0652b..9e30fcd38 100644 --- a/internal/domain/workflow/agent.go +++ b/internal/domain/workflow/agent.go @@ -9,6 +9,7 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/skill" ) @@ -120,22 +121,23 @@ func (a AgentStage) Stage() Stage { } req := agentexec.Request{ - Version: agentexec.ProtocolVersion, - TaskID: tc.Task.ID, - Attempt: tc.Task.Attempt, - Stage: a.Name, - Workflow: tc.Task.Workflow, - Model: modelRef, - Mission: missionWithSkill(tc, a.Mission(tc)), - ExtraRules: extraRules, - ReadOnly: a.ReadOnly, - Budget: budget, - Gate: gate, - Preflight: preflight, - Protection: protection, - Notes: tc.Task.Notes, - CaptureTools: captureTools, - Plugins: pluginSpecs(tc.SkillPlugins), + Version: agentexec.ProtocolVersion, + TaskID: tc.Task.ID, + Attempt: tc.Task.Attempt, + Stage: a.Name, + Workflow: tc.Task.Workflow, + Model: modelRef, + ContextWindow: modelContextBudget(tc.Cfg, modelRef), + Mission: missionWithSkill(tc, a.Mission(tc)), + ExtraRules: extraRules, + ReadOnly: a.ReadOnly, + Budget: budget, + Gate: gate, + Preflight: preflight, + Protection: protection, + Notes: tc.Task.Notes, + CaptureTools: captureTools, + Plugins: pluginSpecs(tc.SkillPlugins), } res, err := tc.Agent.Run(ctx, tc.Dir, req, tc.toolCallReporter(a.Name)) @@ -163,17 +165,15 @@ func (a AgentStage) Stage() Stage { return fmt.Errorf("persist agent notes: %w", saveErr) } } + tc.Task.TokensUsed += res.TokensUsed + tc.Task.Iterations += res.Iterations + if emitErr := tc.EmitDurable(ctx, events.KindAgentFinish, a.Name, res.Summary, agentFinishData(res, modelRef)); emitErr != nil { + return fmt.Errorf("persist agent finish: %w", emitErr) + } if err != nil { return fmt.Errorf("agent run: %w", err) } - tc.Task.TokensUsed += res.TokensUsed - tc.Task.Iterations += res.Iterations - tc.Emit("agent_finish", a.Name, res.Summary, map[string]any{ - "status": res.Status, "stop_reason": res.StopReason, - "tokens": res.TokensUsed, "iterations": res.Iterations, "model": modelRef, - }) - if res.Status != agentexec.StatusPassed { detail := res.Detail if detail == "" { @@ -194,6 +194,23 @@ func (a AgentStage) Stage() Stage { }} } +func modelContextBudget(cfg config.Config, modelRef string) int { + limits := cfg.ModelLimits[modelRef] + if limits.ContextWindow <= limits.MaxOutputTokens { + return 0 + } + return limits.ContextWindow - limits.MaxOutputTokens +} + +func agentFinishData(res agentexec.Result, modelRef string) map[string]any { + return map[string]any{ + "status": res.Status, "stop_reason": res.StopReason, + "tokens": res.TokensUsed, "iterations": res.Iterations, "model": modelRef, + "prompt_tokens": res.Usage.PromptTokens, "completion_tokens": res.Usage.CompletionTokens, + "cached_tokens": res.Usage.CachedTokens, "cache_creation_tokens": res.Usage.CacheCreationTokens, + } +} + // GateFromRepo converts the repo's configured command lists into an // agent execution gate. func GateFromRepo(repo config.Repo, budgets config.Budgets) agentexec.Gate { diff --git a/internal/domain/workflow/implement.go b/internal/domain/workflow/implement.go index ee3db088e..fddf9d820 100644 --- a/internal/domain/workflow/implement.go +++ b/internal/domain/workflow/implement.go @@ -7,13 +7,15 @@ import ( "strings" "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/events" ) // Bounds on how much of a failing gate command's output rides along at each // point in this stage. They serve different purposes and are sized // independently, not derived from one another: -// - baselineWarnLogBytes is a daemon log line -- kept short so one baseline -// failure doesn't dominate the log around it. +// - baselineWarnLogBytes is the tail shown in daemon/container logs. Test +// runners put the useful failure after their long list of passing packages, +// so keeping the head made the operator log actively misleading. // - baselineMissionBytes is what the builder agent sees -- generous, since // it needs enough context to actually diagnose the failure. // - baselineParkOutputBytes is what a human (or Archie's own chat tools) @@ -23,7 +25,7 @@ import ( // see the actual compiler error. It stays comfortably under the store's // own park-reason cap (see internal/store's Task.ParkReason clip). const ( - baselineWarnLogBytes = 200 + baselineWarnLogBytes = 2048 baselineMissionBytes = 3000 baselineParkOutputBytes = 2048 ) @@ -46,7 +48,7 @@ func StageBaselineGate() Stage { } tc.Log.Warn("baseline red -- auto-fixing pre-existing gate failure", "cmd", strings.Join(argv, " "), - "err", clip(string(out), baselineWarnLogBytes)) + "err", clipTail(string(out), baselineWarnLogBytes)) // Run builder to fix the failure via TDD. mission := fmt.Sprintf( @@ -65,13 +67,14 @@ func StageBaselineGate() Stage { modelRef := tc.Cfg.Models["builder"] req := agentexec.Request{ - Version: agentexec.ProtocolVersion, - TaskID: tc.Task.ID, - Attempt: tc.Task.Attempt, - Stage: "baseline-fix", - Workflow: tc.Task.Workflow, - Model: modelRef, - Mission: mission, + Version: agentexec.ProtocolVersion, + TaskID: tc.Task.ID, + Attempt: tc.Task.Attempt, + Stage: "baseline-fix", + Workflow: tc.Task.Workflow, + Model: modelRef, + ContextWindow: modelContextBudget(tc.Cfg, modelRef), + Mission: mission, Budget: agentexec.Budget{ MaxSteps: tc.Cfg.Budgets.MaxSteps, WallClock: tc.Cfg.Budgets.WallClock.Std(), @@ -81,6 +84,14 @@ func StageBaselineGate() Stage { } res, agentErr := tc.Agent.Run(ctx, tc.Dir, req, tc.toolCallReporter("baseline-fix")) + if agentErr != nil && res.Version == 0 { + return fmt.Errorf("baseline-fix agent run: %w", agentErr) + } + tc.Task.TokensUsed += res.TokensUsed + tc.Task.Iterations += res.Iterations + if emitErr := tc.EmitDurable(ctx, events.KindAgentFinish, "baseline-fix", res.Summary, agentFinishData(res, modelRef)); emitErr != nil { + return fmt.Errorf("persist baseline-fix agent finish: %w", emitErr) + } if agentErr != nil { return fmt.Errorf("baseline-fix agent run: %w", agentErr) } diff --git a/internal/domain/workflow/implement_test.go b/internal/domain/workflow/implement_test.go index aba68383d..08656f06d 100644 --- a/internal/domain/workflow/implement_test.go +++ b/internal/domain/workflow/implement_test.go @@ -1,6 +1,7 @@ package workflow import ( + "bytes" "context" "errors" "log/slog" @@ -12,10 +13,114 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/forge" "github.com/samcharles93/archie-core/internal/store" + "github.com/samcharles93/archie-core/internal/worktree" ) +func TestStageBaselineGateAccountsForRepairAgentUsage(t *testing.T) { + dir := t.TempDir() + runGit(t, dir, "init") + script := filepath.Join(dir, "gate.sh") + if err := os.WriteFile(script, []byte("#!/bin/sh\nexit 1\n"), 0o755); err != nil { + t.Fatal(err) + } + runner := agentRunnerFunc(func(context.Context, string, agentexec.Request, agentexec.ToolCallReporter) (agentexec.Result, error) { + return agentexec.Result{ + Version: agentexec.ProtocolVersion, Status: agentexec.StatusPassed, + TokensUsed: 120, Iterations: 3, + Usage: agentexec.Usage{PromptTokens: 100, CompletionTokens: 20, TotalTokens: 120, CachedTokens: 80}, + }, nil + }) + task := &store.Task{ID: 1, Attempt: 1, Owner: "o", Repo: "r"} + tc := &TaskContext{ + Task: task, Repo: config.Repo{Owner: "o", Name: "r", Gate: [][]string{{"sh", script}}}, + Cfg: config.Config{Models: map[string]string{"builder": "provider/model"}}, + Agent: runner, Trees: &worktree.Manager{BotUser: "archie", BotEmail: "archie@example.com"}, + Dir: dir, Log: slog.New(slog.DiscardHandler), + } + if err := StageBaselineGate().Run(t.Context(), tc); err != nil { + t.Fatal(err) + } + if task.TokensUsed != 120 || task.Iterations != 3 { + t.Fatalf("baseline usage = %d tokens/%d iterations, want 120/3", task.TokensUsed, task.Iterations) + } +} + +func TestStageBaselineGateWarningIncludesFailureTail(t *testing.T) { + dir := t.TempDir() + script := filepath.Join(dir, "gate.sh") + // Pad past baselineWarnLogBytes (2048) so clipTail short-circuit does + // NOT save head-clipping from being detected. The marker near the END + // would otherwise be inside the window either way; a marker past the + // window asserts the direction. + body := "echo headmarker; head -c 5000 /dev/zero | tr '\\0' x; echo; echo tailmarker; exit 1\n" + if err := os.WriteFile(script, []byte("#!/bin/sh\n"+body), 0o755); err != nil { + t.Fatal(err) + } + var logs bytes.Buffer + tc := &TaskContext{ + Task: &store.Task{ID: 1, Owner: "o", Repo: "r"}, + Repo: config.Repo{Gate: [][]string{{"sh", script}}}, + Agent: alwaysFailingRunner, + Dir: dir, + Log: slog.New(slog.NewJSONHandler(&logs, nil)), + } + + _ = StageBaselineGate().Run(t.Context(), tc) + logsStr := logs.String() + if !strings.Contains(logsStr, "tailmarker") { + t.Fatalf("baseline warning omitted the useful failure tail: %s", logsStr) + } + if strings.Contains(logsStr, "headmarker") { + t.Fatalf("baseline warning included the head marker -- clip is retaining the head instead of the tail") + } +} + +// TestStageBaselineGateAgentRunErrorSkipsAgentFinish pins the ordering +// inside StageBaselineGate: when the baseline-fix agent returns an error, +// the stage must surface that error WITHOUT first emitting an +// agent_finish event whose status/stop_reason/tokens are all zero. AgentStage +// (internal/domain/workflow/agent.go) bails on every error path before its +// own agent_finish emit, so the baseline-fix path must match. +func TestStageBaselineGateAgentRunErrorSkipsAgentFinish(t *testing.T) { + dir := t.TempDir() + script := filepath.Join(dir, "gate.sh") + if err := os.WriteFile(script, []byte("#!/bin/sh\nexit 1\n"), 0o755); err != nil { + t.Fatal(err) + } + bus := events.NewBus() + sub := bus.Subscribe(8) + t.Cleanup(sub.Close) + runner := agentRunnerFunc(func(context.Context, string, agentexec.Request, agentexec.ToolCallReporter) (agentexec.Result, error) { + return agentexec.Result{}, errors.New("simulated transport failure") + }) + task := &store.Task{ID: 1, Owner: "o", Repo: "r"} + tc := &TaskContext{ + Task: task, + Repo: config.Repo{Owner: "o", Name: "r", Gate: [][]string{{"sh", script}}}, + Cfg: config.Config{Models: map[string]string{"builder": "provider/model"}}, + Agent: runner, + Bus: bus, + Dir: dir, + Log: slog.New(slog.DiscardHandler), + } + if err := StageBaselineGate().Run(t.Context(), tc); err == nil { + t.Fatal("expected StageBaselineGate to surface the agent error") + } + for { + select { + case ev := <-sub.C: + if ev.Kind == "agent_finish" { + t.Fatalf("baseline-fix errored but agent_finish was still published: %+v", ev) + } + default: + return + } + } +} + // fakeForge implements forge.Forge for TestStageCommitPushCloses. type fakeForge struct { closed int diff --git a/internal/domain/workflow/workflow.go b/internal/domain/workflow/workflow.go index 221a42df3..84f202876 100644 --- a/internal/domain/workflow/workflow.go +++ b/internal/domain/workflow/workflow.go @@ -7,6 +7,7 @@ package workflow import ( "context" + "errors" "fmt" "log/slog" "sort" @@ -119,6 +120,29 @@ func (tc *TaskContext) Emit(kind, stage, detail string, data map[string]any) { }) } +// EmitDurable persists evaluation-critical telemetry before publishing it to +// the lossy live bus. The assigned ID tells the daemon sink to broadcast +// without inserting a duplicate row. +func (tc *TaskContext) EmitDurable(ctx context.Context, kind, stage, detail string, data map[string]any) error { + if tc.Store == nil { + tc.Emit(kind, stage, detail, data) + return nil + } + event := events.Event{ + At: time.Now().UTC(), Kind: kind, TaskID: tc.Task.ID, Repo: tc.Task.Owner + "/" + tc.Task.Repo, + Issue: tc.Task.IssueNumber, Workflow: tc.Task.Workflow, Stage: stage, Detail: detail, Data: data, + } + id, err := tc.Store.InsertEvent(ctx, event) + if err != nil { + return err + } + event.ID = id + if tc.Bus != nil { + tc.Bus.Publish(event) + } + return nil +} + // toolCallReporter builds the agentexec.ToolCallReporter an agent stage // passes to tc.Agent.Run, so every completed tool call during that run // surfaces as a tool_call event on the task timeline (archie-core-467's @@ -248,6 +272,9 @@ func Run(ctx context.Context, wf Workflow, tc *TaskContext) { data := map[string]any{"duration_ms": time.Since(started).Milliseconds()} if err != nil { data["error"] = err.Error() + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + data["interrupted"] = true + } } tc.Emit(events.KindStageFinish, stage.Name, "", data) diff --git a/internal/events/events.go b/internal/events/events.go index 817c6bf94..c735892ab 100644 --- a/internal/events/events.go +++ b/internal/events/events.go @@ -15,7 +15,13 @@ const ( KindTaskQueued = "task_queued" KindStageStart = "stage_start" KindStageFinish = "stage_finish" // data: duration_ms, error - KindAgentFinish = "agent_finish" // data: status, stop_reason, tokens, iterations, model + // KindAgentFinish carries the stage's token economics as well as its + // outcome: tokens is the run total (agentexec.Result.TokensUsed) and the + // prompt/completion/cached/cache_creation breakdown is the provider's own + // accounting, forwarded verbatim for evaluation. The breakdown is absent + // on events persisted before it was carried across the agent boundary, so + // consumers must treat each field as optional rather than zero. + KindAgentFinish = "agent_finish" // data: status, stop_reason, tokens, iterations, model, prompt_tokens, completion_tokens, cached_tokens, cache_creation_tokens // KindToolCall marks one completed tool invocation during an agent // stage run (archie-core-467's task-transcript counterpart -- the // interactive chat gateway surfaces its own tool calls separately via @@ -31,9 +37,12 @@ const ( // intervention is recorded in the tasks table but invisible on the // timeline and the activity stream -- the one kind of event most worth // seeing, because it explains why a task changed course. - KindHumanApproved = "human_approved" - KindHumanRejected = "human_rejected" - KindTaskRetried = "task_retried" + KindHumanApproved = "human_approved" + KindHumanRejected = "human_rejected" + // KindTaskRetried records what the retry was escaping from. RetryTask + // clears stage and park_reason in the same statement that increments the + // count, so this event is the only place that context survives. + KindTaskRetried = "task_retried" // data: retry_count, previous_stage, previous_reason KindTaskCancelled = "task_cancelled" KindTaskStopped = "task_stopped" KindTaskAbandoned = "task_abandoned" diff --git a/internal/gateway/session_store_sqlite.go b/internal/gateway/session_store_sqlite.go index 3975ffa08..c7f0c8025 100644 --- a/internal/gateway/session_store_sqlite.go +++ b/internal/gateway/session_store_sqlite.go @@ -204,8 +204,9 @@ func (s *sqliteSessionStore) Close() error { } func (s *sqliteSessionStore) ClaimTurn(ctx context.Context, initial TurnRecord) (TurnRecord, TurnClaim, error) { - if initial.TurnID == "" { - return TurnRecord{}, "", fmt.Errorf("sessionstore: turn ID is required") + initial, initialToolCalls, err := prepareInitialTurn(initial, time.Now().UTC()) + if err != nil { + return TurnRecord{}, "", err } s.mu.Lock() defer s.mu.Unlock() @@ -216,6 +217,22 @@ func (s *sqliteSessionStore) ClaimTurn(ctx context.Context, initial TurnRecord) } defer func() { _ = tx.Rollback() }() + // Claim by writing first. Under WAL, a transaction that reads and then + // upgrades to a writer can fail immediately with SQLITE_BUSY_SNAPSHOT; + // busy_timeout only waits for ordinary writer contention. INSERT ... ON + // CONFLICT acquires writer intent before any snapshot read, so concurrent + // claimers wait normally and the loser can inspect the committed turn. + inserted, err := insertInitialTurn(ctx, tx, initial, initialToolCalls) + if err != nil { + return TurnRecord{}, "", err + } + if inserted { + if err := tx.Commit(); err != nil { + return TurnRecord{}, "", fmt.Errorf("sessionstore: claim turn: commit: %w", err) + } + return initial, TurnClaimOwned, nil + } + var turn TurnRecord var createdMS, updatedMS int64 var toolCallsRaw string @@ -228,61 +245,6 @@ func (s *sqliteSessionStore) ClaimTurn(ctx context.Context, initial TurnRecord) &turn.InputMessageID, &turn.AssistantMessageID, &turn.PartialText, &turn.ResponseText, &toolCallsRaw, &turn.Error, &createdMS, &updatedMS, ) - if errors.Is(err, sql.ErrNoRows) { - now := time.Now().UTC() - initial.Status = TurnStatusRunning - initial.Attempt = 1 - if initial.CreatedAt.IsZero() { - initial.CreatedAt = now - } - initial.UpdatedAt = now - initialToolCalls, marshalErr := marshalToolCalls(initial.ToolCalls) - if marshalErr != nil { - return TurnRecord{}, "", marshalErr - } - // insertErr is deliberately its own name, not err: this whole block - // is inside `if errors.Is(err, sql.ErrNoRows)`, so reusing err here - // would shadow the outer err for the rest of the block -- including - // the retry read below, whose result must reach the outer `if err - // != nil` after this block closes. A shadowed reassignment there - // would go out of scope silently, leaving the outer err at its - // original sql.ErrNoRows value regardless of how the retry read - // actually went. - result, insertErr := tx.ExecContext(ctx, ` - INSERT INTO turns ( - turn_id, session_id, source_id, status, attempt, owner_id, - input_message_id, assistant_message_id, partial_text, - response_text, tool_calls, error, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(turn_id) DO NOTHING`, turnValues(initial, initialToolCalls)...) - if insertErr != nil { - return TurnRecord{}, "", fmt.Errorf("sessionstore: claim turn: insert: %w", insertErr) - } - affected, insertErr := result.RowsAffected() - if insertErr != nil { - return TurnRecord{}, "", fmt.Errorf("sessionstore: claim turn: rows affected: %w", insertErr) - } - if affected == 1 { - if err := tx.Commit(); err != nil { - return TurnRecord{}, "", fmt.Errorf("sessionstore: claim turn: commit: %w", err) - } - return initial, TurnClaimOwned, nil - } - // Another connection inserted the same turn between our read and - // insert. Read it in this transaction and apply the normal claim - // state machine instead of surfacing a uniqueness error. This - // assigns the OUTER err (see above) -- it is what the `if err != - // nil` check below this block actually sees. - err = tx.QueryRowContext(ctx, ` - SELECT turn_id, session_id, source_id, status, attempt, owner_id, - input_message_id, assistant_message_id, partial_text, - response_text, tool_calls, error, created_at, updated_at - FROM turns WHERE turn_id = ?`, initial.TurnID).Scan( - &turn.TurnID, &turn.SessionID, &turn.SourceID, &turn.Status, &turn.Attempt, &turn.OwnerID, - &turn.InputMessageID, &turn.AssistantMessageID, &turn.PartialText, - &turn.ResponseText, &toolCallsRaw, &turn.Error, &createdMS, &updatedMS, - ) - } if err != nil { return TurnRecord{}, "", fmt.Errorf("sessionstore: read turn: %w", err) } @@ -291,7 +253,10 @@ func (s *sqliteSessionStore) ClaimTurn(ctx context.Context, initial TurnRecord) if turn.ToolCalls, err = unmarshalToolCalls(toolCallsRaw); err != nil { return TurnRecord{}, "", err } + return claimExistingTurn(ctx, tx, turn, initial) +} +func claimExistingTurn(ctx context.Context, tx *sql.Tx, turn, initial TurnRecord) (TurnRecord, TurnClaim, error) { switch turn.Status { case TurnStatusCompleted: return turn, TurnClaimCompleted, nil @@ -341,6 +306,38 @@ func (s *sqliteSessionStore) ClaimTurn(ctx context.Context, initial TurnRecord) } } +func insertInitialTurn(ctx context.Context, tx *sql.Tx, initial TurnRecord, toolCalls string) (bool, error) { + result, err := tx.ExecContext(ctx, ` + INSERT INTO turns ( + turn_id, session_id, source_id, status, attempt, owner_id, + input_message_id, assistant_message_id, partial_text, + response_text, tool_calls, error, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(turn_id) DO NOTHING`, turnValues(initial, toolCalls)...) + if err != nil { + return false, fmt.Errorf("sessionstore: claim turn: insert: %w", err) + } + affected, err := result.RowsAffected() + if err != nil { + return false, fmt.Errorf("sessionstore: claim turn: rows affected: %w", err) + } + return affected == 1, nil +} + +func prepareInitialTurn(initial TurnRecord, now time.Time) (TurnRecord, string, error) { + if initial.TurnID == "" { + return TurnRecord{}, "", fmt.Errorf("sessionstore: turn ID is required") + } + initial.Status = TurnStatusRunning + initial.Attempt = 1 + if initial.CreatedAt.IsZero() { + initial.CreatedAt = now + } + initial.UpdatedAt = now + toolCalls, err := marshalToolCalls(initial.ToolCalls) + return initial, toolCalls, err +} + func (s *sqliteSessionStore) RecoverTurns(ctx context.Context, ownerID string) error { if ownerID == "" { return fmt.Errorf("sessionstore: recovery owner ID is required") diff --git a/internal/gateway/session_store_sqlite_claimturn_race_test.go b/internal/gateway/session_store_sqlite_claimturn_race_test.go index e274213b9..c26cdccd1 100644 --- a/internal/gateway/session_store_sqlite_claimturn_race_test.go +++ b/internal/gateway/session_store_sqlite_claimturn_race_test.go @@ -4,43 +4,23 @@ import ( "context" "fmt" "path/filepath" - "strings" "sync" "testing" "time" ) -// TestClaimTurnConcurrentInsertRaceNeverReturnsAnError guards against a -// variable-shadowing bug in ClaimTurn (session_store_sqlite.go), fixed -// alongside this test: the branch handling "another connection inserted the -// same turn between our read and insert" used to write its retry read's -// result into an `err` shadowed inside the `errors.Is(err, sql.ErrNoRows)` -// block by an earlier `result, err := tx.ExecContext(...)`. That shadowed -// err went out of scope at the block's closing brace, so the outer err -// checked afterward was still sql.ErrNoRows from the original read -- the -// loser of that race would always return an error wrapped -// "sessionstore: read turn: %w", even though the comment's own stated -// intent is "apply the normal claim state machine instead of surfacing a -// uniqueness error." Confirmed via careful reading of Go's block-scoping -// rules, not assumed. +// TestClaimTurnConcurrentInsertRaceResolvesToOneOwner verifies that ordinary +// contention between processes sharing the session database is resolved by +// ClaimTurn itself. Callers must not need to recognize and retry SQLite's +// SQLITE_BUSY or SQLITE_BUSY_SNAPSHOT implementation details. // -// Honest limitation: this test could NOT be made to reproduce that exact -// branch through genuine concurrent access. A one-off diagnostic (real -// two-connection race, sleep-widened to force overlap, reverted before this -// commit -- never present in a shipped file) showed the loser instead fails -// its own INSERT outright with SQLITE_BUSY_SNAPSHOT under WAL mode with this -// driver, before ON CONFLICT DO NOTHING can ever report affected=0. That -// means the specific "0 rows affected" branch this bug lived in may be -// effectively unreachable via a same-driver, same-journal-mode race today. -// The fix stands regardless -- the shadowing was real, wrong on its own -// terms, and free to correct -- but this test cannot claim to exercise the -// exact line that was fixed. What it verifies is the weaker, still real -// property that matters operationally: many genuinely concurrent -// same-turn-ID claims across separate connections never produce the bug's -// specific error signature. Treat this as a guard against a regression -// becoming reachable (a different SQLite version, journal mode, or driver -// with weaker snapshot isolation), not as proof the original bug was ever -// live in production. +// Two invariants must hold under contention: every ClaimTurn call returns +// without error, and EXACTLY ONE of the racers ends up TurnClaimOwned while +// the other observes the committed row and returns a non-owning claim. +// The second invariant matters more than the first: a bug that returns +// TurnClaimOwned to both racers means two archied processes drive the same +// turn to completion, and the assistant reply gets emitted twice to the +// chat. The first invariant alone would not catch that. // // A single sqliteSessionStore instance cannot exhibit any of this: its own // mutex serializes every ClaimTurn call against that instance's connection, @@ -48,20 +28,11 @@ import ( // against the same file-backed database -- the real-world shape of the // scenario (two archied/worker processes or connections sharing one session // DB). -// -// SQLite's own write-lock contention (SQLITE_BUSY / SQLITE_BUSY_SNAPSHOT, -// "database is locked") is infrastructure noise distinct from the bug: it -// comes from BeginTx/ExecContext/Commit failing outright and is wrapped -// with a different prefix ("claim turn: begin/insert/rows affected/commit"). -// Only the "sessionstore: read turn:" wrap was the bug's unique signature, -// so transient busy errors are retried rather than treated as failures. -func TestClaimTurnConcurrentInsertRaceNeverReturnsAnError(t *testing.T) { +func TestClaimTurnConcurrentInsertRaceResolvesToOneOwner(t *testing.T) { path := filepath.Join(t.TempDir(), "sessions.db") const stores = 2 const trials = 100 - const maxRetriesPerAttempt = 20 - const busyRetryDelay = time.Millisecond openers := make([]TurnLedger, stores) for i := range openers { @@ -84,23 +55,9 @@ func TestClaimTurnConcurrentInsertRaceNeverReturnsAnError(t *testing.T) { ctx := context.Background() now := time.UnixMilli(1000).UTC() - claimRetryingBusy := func(ledger TurnLedger, initial TurnRecord) error { - var err error - for range maxRetriesPerAttempt { - _, _, err = ledger.ClaimTurn(ctx, initial) - if err == nil || !strings.Contains(err.Error(), "database is locked") { - return err - } - time.Sleep(busyRetryDelay) - } - return err - } - // Each trial races the two independent stores over one turn ID, then waits - // before starting the next trial. Running every trial at once adds 100-way - // global writer contention that is unrelated to the same-turn insert race - // this regression covers and can exhaust the bounded SQLITE_BUSY retries - // before any competing transaction gets scheduled to finish. + // before starting the next trial. This isolates the same-turn claim race + // from unrelated 100-way global writer contention. for trial := range trials { turnID := fmt.Sprintf("race-turn-%d", trial) initial := TurnRecord{ @@ -112,6 +69,7 @@ func TestClaimTurnConcurrentInsertRaceNeverReturnsAnError(t *testing.T) { UpdatedAt: now, } errs := make([]error, stores) + claims := make([]TurnClaim, stores) var wg sync.WaitGroup var start sync.WaitGroup start.Add(1) @@ -120,20 +78,25 @@ func TestClaimTurnConcurrentInsertRaceNeverReturnsAnError(t *testing.T) { go func(i int) { defer wg.Done() start.Wait() - errs[i] = claimRetryingBusy(openers[i], initial) + _, claims[i], errs[i] = openers[i].ClaimTurn(ctx, initial) }(i) } start.Done() wg.Wait() for i, err := range errs { - if err == nil { - continue + if err != nil { + t.Fatalf("trial %d, store %d: ClaimTurn() unexpected error = %v", trial, i, err) } - if strings.Contains(err.Error(), "sessionstore: read turn:") { - t.Fatalf("trial %d, store %d: ClaimTurn() error = %v -- a losing racer surfaced the winner's insert as a read failure instead of applying the normal claim state machine", trial, i, err) + } + owners := 0 + for _, c := range claims { + if c == TurnClaimOwned { + owners++ } - t.Fatalf("trial %d, store %d: ClaimTurn() unexpected error = %v", trial, i, err) + } + if owners != 1 { + t.Fatalf("trial %d: expected exactly one TurnClaimOwned across %d racers, got %d (claims=%v)", trial, stores, owners, claims) } } } diff --git a/internal/infrastructure/configuration/defaults.go b/internal/infrastructure/configuration/defaults.go index 0d14f5639..e8f80e492 100644 --- a/internal/infrastructure/configuration/defaults.go +++ b/internal/infrastructure/configuration/defaults.go @@ -225,18 +225,28 @@ func applyDispatchDefaults(cfg *config.Config) { } } -// applyIdentityDefaults derives the commit email for a single-identity -// deployment. Multi-identity deployments configure each identity explicitly. +// applyIdentityDefaults derives forge-appropriate commit emails wherever the +// operator omitted one, for both deployment shapes. func applyIdentityDefaults(cfg *config.Config) { - if len(cfg.Identities) > 0 || cfg.BotUser == "" || cfg.BotEmail != "" { - return + if len(cfg.Identities) > 0 { + for i := range cfg.Identities { + cfg.Identities[i].BotEmail = defaultBotEmail(cfg.Identities[i].Forge.Type, cfg.Identities[i].BotUser, cfg.Identities[i].BotEmail) + } } - switch cfg.Forge.Type { + cfg.BotEmail = defaultBotEmail(cfg.Forge.Type, cfg.BotUser, cfg.BotEmail) +} + +func defaultBotEmail(forgeType, user, email string) string { + if user == "" || email != "" { + return email + } + switch forgeType { case forgeTypeGitHub: - cfg.BotEmail = cfg.BotUser + "@users.noreply.github.com" + return user + "@users.noreply.github.com" case forgeTypeGitea: - cfg.BotEmail = cfg.BotUser + "@gitea.local" + return user + "@gitea.local" } + return email } // applyContainerDefaults makes managed task workers usable without an explicit diff --git a/internal/infrastructure/configuration/defaults_test.go b/internal/infrastructure/configuration/defaults_test.go index de3cfcec3..a3dae7858 100644 --- a/internal/infrastructure/configuration/defaults_test.go +++ b/internal/infrastructure/configuration/defaults_test.go @@ -63,6 +63,23 @@ func TestApplyForgeDefaultsIntake(t *testing.T) { } } +func TestApplyIdentityDefaultsDerivesEmailPerIdentity(t *testing.T) { + cfg := &config.Config{Identities: []config.IdentityConfig{ + {BotUser: "github-bot", Forge: config.Forge{Type: forgeTypeGitHub}}, + {BotUser: "gitea-bot", Forge: config.Forge{Type: forgeTypeGitea}}, + {BotUser: "explicit", BotEmail: "bot@example.test", Forge: config.Forge{Type: forgeTypeGitHub}}, + }} + + applyIdentityDefaults(cfg) + + want := []string{"github-bot@users.noreply.github.com", "gitea-bot@gitea.local", "bot@example.test"} + for i := range want { + if cfg.Identities[i].BotEmail != want[i] { + t.Errorf("identity %d BotEmail = %q, want %q", i, cfg.Identities[i].BotEmail, want[i]) + } + } +} + func TestApplyCaptureDefaultsFillsZeroValues(t *testing.T) { cfg := &config.Config{} applyCaptureDefaults(cfg) diff --git a/internal/store/interface.go b/internal/store/interface.go index fc2b346b2..990dd7f6f 100644 --- a/internal/store/interface.go +++ b/internal/store/interface.go @@ -74,6 +74,7 @@ type TaskEvents interface { type WorkflowStore interface { Update(ctx context.Context, t *Task) error Transition(ctx context.Context, taskID int64, from, to, detail string) error + InsertEvent(ctx context.Context, e events.Event) (int64, error) } // CaptureStore persists unbound inbound webhook captures -- events with no diff --git a/internal/storerpc/storerpc.go b/internal/storerpc/storerpc.go index 73ce328a8..34555ea0c 100644 --- a/internal/storerpc/storerpc.go +++ b/internal/storerpc/storerpc.go @@ -12,14 +12,16 @@ import ( "github.com/nats-io/nats.go" + "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/natsrpc" "github.com/samcharles93/archie-core/internal/store" ) // Subjects for the two store.TaskStore methods workflow stages call mid-run. const ( - SubjectUpdate = "archie.store.update" - SubjectTransition = "archie.store.transition" + SubjectUpdate = "archie.store.update" + SubjectTransition = "archie.store.transition" + SubjectInsertEvent = "archie.store.insert_event" ) // UpdateRequest mirrors store.TaskStore.Update's argument. @@ -35,9 +37,14 @@ type TransitionRequest struct { Detail string `json:"detail"` } +type InsertEventRequest struct { + Event events.Event `json:"event"` +} + // Response carries the result of an RPC. Error is empty on success. type Response struct { natsrpc.Envelope + ID int64 `json:"id,omitempty"` } // Server handles storerpc requests against the daemon's TaskStore. @@ -52,9 +59,20 @@ func (s *Server) Register(nc *nats.Conn) (unsubscribe func(), err error) { return natsrpc.RegisterAll(nc, []natsrpc.Registration{ {Subject: SubjectUpdate, Handler: s.handleUpdate}, {Subject: SubjectTransition, Handler: s.handleTransition}, + {Subject: SubjectInsertEvent, Handler: s.handleInsertEvent}, }) } +func (s *Server) handleInsertEvent(msg *nats.Msg) { + var req InsertEventRequest + if err := json.Unmarshal(msg.Data, &req); err != nil { + s.reply(msg, err) + return + } + id, err := s.Store.InsertEvent(context.Background(), req.Event) + natsrpc.Respond(msg, s.Log, "storerpc", Response{Envelope: natsrpc.NewEnvelope(err), ID: id}) +} + func (s *Server) handleUpdate(msg *nats.Msg) { var req UpdateRequest if err := json.Unmarshal(msg.Data, &req); err != nil { @@ -106,5 +124,13 @@ func (c *Client) Transition(ctx context.Context, taskID int64, from, to, detail return resp.Err() } +func (c *Client) InsertEvent(ctx context.Context, event events.Event) (int64, error) { + resp, err := natsrpc.Call[Response](ctx, c.rpc(), SubjectInsertEvent, InsertEventRequest{Event: event}) + if err != nil { + return 0, err + } + return resp.ID, resp.Err() +} + // Compile-time check: Client satisfies WorkflowStore. var _ store.WorkflowStore = (*Client)(nil) diff --git a/internal/storerpc/storerpc_test.go b/internal/storerpc/storerpc_test.go index e1d8711c4..28b4e81da 100644 --- a/internal/storerpc/storerpc_test.go +++ b/internal/storerpc/storerpc_test.go @@ -10,6 +10,7 @@ import ( natssrv "github.com/nats-io/nats-server/v2/test" "github.com/nats-io/nats.go" + "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/store" ) @@ -108,6 +109,21 @@ func TestClientTransitionPersistsViaServer(t *testing.T) { } } +func TestClientInsertEventPersistsViaServer(t *testing.T) { + s, _, client := newTestServer(t) + task := enqueueTask(t, s) + event := events.Event{Kind: events.KindAgentFinish, TaskID: task.ID, Data: map[string]any{"tokens": 42}} + + id, err := client.InsertEvent(context.Background(), event) + if err != nil { + t.Fatalf("InsertEvent: %v", err) + } + got, err := s.TaskEvents(context.Background(), task.ID) + if err != nil || len(got) != 1 || got[0].ID != id || got[0].Kind != events.KindAgentFinish { + t.Fatalf("TaskEvents = (%+v, %v), want persisted agent_finish id %d", got, err, id) + } +} + func TestClientPropagatesServerError(t *testing.T) { s, _, client := newTestServer(t) task := enqueueTask(t, s) diff --git a/internal/webui/api_tasks.go b/internal/webui/api_tasks.go index 58751ba8b..d39cc9aea 100644 --- a/internal/webui/api_tasks.go +++ b/internal/webui/api_tasks.go @@ -12,6 +12,7 @@ import ( "strconv" "strings" + "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/taskstate" @@ -53,14 +54,65 @@ func (s *Server) handleTasks(w http.ResponseWriter, r *http.Request) { } views := make([]taskView, len(tasks)) for i := range tasks { - views[i] = taskView{Task: tasks[i], Actions: taskstate.Actions(tasks[i].Status)} + repoURL, issueURL, prURL := s.taskURLs(tasks[i]) + views[i] = taskView{Task: tasks[i], Actions: taskstate.Actions(tasks[i].Status), RepoURL: repoURL, IssueURL: issueURL, PRURL: prURL} } writeJSON(w, views) } type taskView struct { store.Task - Actions []taskstate.Action `json:"actions"` + Actions []taskstate.Action `json:"actions"` + RepoURL string `json:"repo_url,omitempty"` + IssueURL string `json:"issue_url,omitempty"` + PRURL string `json:"pr_url,omitempty"` +} + +func (s *Server) taskURLs(task store.Task) (repoURL, issueURL, prURL string) { + if s.Cfg == nil { + return "", "", "" + } + forgeCfg := forgeConfigForTask(s.Cfg.Get(), task) + if forgeCfg.Host == "" || task.Owner == "" || task.Repo == "" { + return "", "", "" + } + repoURL = strings.TrimRight(forgeCfg.Host, "/") + "/" + url.PathEscape(task.Owner) + "/" + url.PathEscape(task.Repo) + if task.IsForgeBacked() && task.IssueNumber > 0 { + issueURL = repoURL + "/issues/" + strconv.Itoa(task.IssueNumber) + } + if task.PRNumber > 0 { + segment := "pull" + if forgeCfg.Type == "gitea" { + segment = "pulls" + } + prURL = repoURL + "/" + segment + "/" + strconv.Itoa(task.PRNumber) + } + return repoURL, issueURL, prURL +} + +func forgeConfigForTask(cfg config.Config, task store.Task) config.Forge { + for _, identity := range cfg.Identities { + if task.Identity != "" && identity.Name == task.Identity { + return identity.Forge + } + } + var matched *config.Forge + for i := range cfg.Identities { + identity := &cfg.Identities[i] + for _, repo := range identity.Repos { + if repo.Owner == task.Owner && repo.Name == task.Repo { + if matched != nil { + return cfg.Forge + } + forgeCopy := identity.Forge + matched = &forgeCopy + } + } + } + if matched != nil { + return *matched + } + return cfg.Forge } func (s *Server) handleTask(w http.ResponseWriter, r *http.Request) { @@ -122,7 +174,7 @@ func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) { ID: outcome.eventID, Kind: outcome.kind, TaskID: task.ID, Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber, - Detail: outcome.detail, + Detail: outcome.detail, Data: outcome.data, }) writeJSON(w, map[string]any{"ok": true, "action": action, "task_id": id}) } @@ -268,6 +320,7 @@ func validOrigin(u *url.URL, wantScheme, wantHost string) bool { type actionOutcome struct { kind string detail string + data map[string]any eventID int64 } @@ -380,7 +433,15 @@ func (s *Server) retryTask(ctx context.Context, w http.ResponseWriter, task *sto if s.storeFailed(w, s.Store.RetryTask(ctx, task.ID, store.StatusParked, "")) { return nil } - return &actionOutcome{kind: events.KindTaskRetried, detail: "retried via the dashboard"} + return &actionOutcome{ + kind: events.KindTaskRetried, + detail: "retried via the dashboard", + data: map[string]any{ + "retry_count": task.RetryCount + 1, + "previous_stage": task.Stage, + "previous_reason": task.ParkReason, + }, + } } // retireTask moves a spent task to dead. Failure is logged, not returned: diff --git a/internal/webui/api_tasks_actions_test.go b/internal/webui/api_tasks_actions_test.go index 67aab008e..15216fb63 100644 --- a/internal/webui/api_tasks_actions_test.go +++ b/internal/webui/api_tasks_actions_test.go @@ -276,6 +276,11 @@ func TestActionsEmitEvents(t *testing.T) { if ev.Kind == "" { t.Error("event Kind is empty") } + if tc.action == "retry" { + if ev.Data["retry_count"] != 1 || ev.Data["previous_reason"] != tc.reason { + t.Errorf("retry event Data = %#v, want retry count and previous failure", ev.Data) + } + } default: t.Fatalf("%s emitted no event: the activity stream and timeline "+ "never show that a human intervened", tc.action) diff --git a/internal/webui/api_tasks_test.go b/internal/webui/api_tasks_test.go index f77ebb165..362c96b83 100644 --- a/internal/webui/api_tasks_test.go +++ b/internal/webui/api_tasks_test.go @@ -15,10 +15,34 @@ import ( "strings" "testing" + "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/store" ) +func TestTaskURLsUseOwningForgeRoutes(t *testing.T) { + srv := &Server{Cfg: config.NewHolder(config.Config{ + Forge: config.Forge{Type: "github", Host: "https://github.example"}, + Identities: []config.IdentityConfig{{ + Name: "gitea", Forge: config.Forge{Type: "gitea", Host: "https://gitea.example"}, + Repos: []config.Repo{{Owner: "acme", Name: "widget"}}, + }}, + })} + task := store.Task{Owner: "acme", Repo: "widget", IssueNumber: 12, PRNumber: 34, Identity: "gitea"} + + repoURL, issueURL, prURL := srv.taskURLs(task) + if repoURL != "https://gitea.example/acme/widget" || issueURL != repoURL+"/issues/12" || prURL != repoURL+"/pulls/34" { + t.Fatalf("URLs = %q, %q, %q; want canonical Gitea routes", repoURL, issueURL, prURL) + } + + task.Identity = "" + task.Owner, task.Repo = "other", "repo" + _, _, prURL = srv.taskURLs(task) + if prURL != "https://github.example/other/repo/pull/34" { + t.Fatalf("GitHub PR URL = %q", prURL) + } +} + // Approve requeues from the task's own recorded state rather than anything // the caller supplies, so a stale dashboard cannot approve a task twice. func TestHandleTaskActionApproveUsesRecordedState(t *testing.T) { diff --git a/tools/go.mod b/tools/go.mod index 2a91c2bb8..477a411b8 100644 --- a/tools/go.mod +++ b/tools/go.mod @@ -17,10 +17,11 @@ require ( github.com/pb33f/ordered-map/v2 v2.3.1 // indirect github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect - github.com/samcharles93/ai-sdk v0.1.20 // indirect + github.com/samcharles93/ai-sdk v0.1.25 // indirect github.com/traefik/yaegi v0.16.1 // indirect go.yaml.in/yaml/v4 v4.0.0-rc.2 // indirect golang.org/x/sys v0.47.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect modernc.org/libc v1.74.4 // indirect modernc.org/mathutil v1.7.1 // indirect modernc.org/memory v1.11.0 // indirect diff --git a/tools/go.sum b/tools/go.sum index f39572757..9ff89b19d 100644 --- a/tools/go.sum +++ b/tools/go.sum @@ -1,7 +1,5 @@ github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= -github.com/antithesishq/antithesis-sdk-go v0.7.2 h1:oEEedg1Xgi8drRjqB0f9tfjhLoInE0IYZfZ6zAhQUbY= -github.com/antithesishq/antithesis-sdk-go v0.7.2/go.mod h1:FQyySiasQQM8735Ddel3MRojmy4dA1IqCeyJ5jmPMbI= github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk= github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg= github.com/buger/jsonparser v1.1.2 h1:frqHqw7otoVbk5M8LlE/L7HTnIq2v9RX6EJ48i9AxJk= @@ -10,8 +8,6 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= -github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo= -github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY= github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo= github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= @@ -20,22 +16,8 @@ github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/invopop/jsonschema v0.14.0 h1:MHQqLhvpNUZfw+hM3AZDYK7jxO8FZoQeQM77g8iyZjg= github.com/invopop/jsonschema v0.14.0/go.mod h1:ygm6C2EaVNMBDPpaPlnOA2pFAxBnxGjFlMZABxm9n2I= -github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk= -github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= -github.com/minio/highwayhash v1.0.4 h1:asJizugGgchQod2ja9NJlGOWq4s7KsAWr5XUc9Clgl4= -github.com/minio/highwayhash v1.0.4/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ= -github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc= -github.com/nats-io/jwt/v2 v2.8.2/go.mod h1:Ag/56sq9OblL4JgdYufDd16Egb17Kr/8WwwuO/forVc= -github.com/nats-io/nats-server/v2 v2.14.4 h1:efgjZ8cdExAKRuqSg8UPJFprb+l7NlBtSDPhDlw3rO4= -github.com/nats-io/nats-server/v2 v2.14.4/go.mod h1:BltdpOYestjbtQSnVO2zGHdg5SGBZjt+GYTgB9LZq/I= -github.com/nats-io/nats.go v1.52.0 h1:n3avV4VBsCgsdwh71TppsTwtv+QdPs7ntSKM8qJLGsc= -github.com/nats-io/nats.go v1.52.0/go.mod h1:26HypzazeOkyO3/mqd1zZd53STJN0EjCYF9Uy2ZOBno= -github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg= -github.com/nats-io/nkeys v0.4.16/go.mod h1:llLgWoI0o4z/Q57q2R1kHfmocyhGV6VG/U18Glg1Afs= -github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= -github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= github.com/pb33f/ordered-map/v2 v2.3.1 h1:5319HDO0aw4DA4gzi+zv4FXU9UlSs3xGZ40wcP1nBjY= @@ -46,16 +28,14 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= -github.com/samcharles93/ai-sdk v0.1.20 h1:Z52dyMN293aV8Cpgjdyyd2zw6oNF5FSXKWfCuxY/3UA= -github.com/samcharles93/ai-sdk v0.1.20/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o= +github.com/samcharles93/ai-sdk v0.1.25 h1:30cvHZBw01XRif2cOG/PToC7xTQUZ5DHwMOShT8zSnw= +github.com/samcharles93/ai-sdk v0.1.25/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/traefik/yaegi v0.16.1 h1:f1De3DVJqIDKmnasUF6MwmWv1dSEEat0wcpXhD2On3E= github.com/traefik/yaegi v0.16.1/go.mod h1:4eVhbPb3LnD2VigQjhYbEJ69vDRFdT2HQNrXx8eEwUY= go.yaml.in/yaml/v4 v4.0.0-rc.2 h1:/FrI8D64VSr4HtGIlUtlFMGsm7H7pWTbj6vOLVZcA6s= go.yaml.in/yaml/v4 v4.0.0-rc.2/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0= -golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= -golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= @@ -63,10 +43,10 @@ golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= -golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= -golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= modernc.org/cc/v4 v4.29.1 h1:MKgdCV3WykTSPqpVrnxdEDS0HEd2FHpKZDzxzU5LyeI= diff --git a/ui/dist/assets/index.js b/ui/dist/assets/index.js index 446dcbbef..401093d00 100644 --- a/ui/dist/assets/index.js +++ b/ui/dist/assets/index.js @@ -6,8 +6,8 @@ stroke-width="12" stroke-linecap="round" stroke-dasharray="${c}" stroke-dashoffset="${c*(1-i/100)}" - class="gauge-value"/>`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function x(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}var S=`archie.setup-complete.dismissed.v1`;function C(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(S),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function w(e=globalThis.localStorage){e?.setItem?.(S,`1`)}var T=new Set([`waiting_human`,`parked`]);function E(e=[]){let t=e.filter(e=>T.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function D(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),m=e(`h1.hero-title`,A()),_=r(`connecting`,`idle`),y=[],b=new Map;S(),D();let x=g(e=>{y.unshift(e),y.splice(50),T()},e=>{_.className=`pill pill-${e===`live`?`ok`:`warn`}`,_.textContent=e});t.addEventListener(`archie:teardown`,x);function S(){n(t,e(`div.hero`,e(`div`,m,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),_),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),T()}function T(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>O(e,b)))}async function D(){try{let[e,t,n,r]=await Promise.all([h.summary(),h.setup().catch(()=>null),h.workflows().catch(()=>null),h.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);T(),k(r),m.textContent=t?.operator?`${A()}, ${t.operator}`:A(),P(e),F(t),I(e,n),L(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:D},l(`refresh`,{size:15}),`Retry`))}}function k(t){let r=E(t),i=r.attention.count,a=r.running.count;n(p,i>0&&e(`a.btn.btn-attention`,{href:r.attention.href},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:r.running.href},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:D},l(`refresh`,{size:15}),`Refresh`))}function P(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,v({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),v({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),v({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),v({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:N(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function F(t){let r=C(t),i=r.kind===`omit`||r.kind===`dismissed`;if(d.classList.toggle(`dash-top-standalone`,i),i)return n(c);let a=r.remaining;if(a.length){let r=Math.round((t.steps.length-a.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(R))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`div.setup-complete-actions`,e(`span.setup-pct`,l(`check`,{size:16})),e(`button.icon-btn.setup-dismiss`,{type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onclick:()=>{w(),F(t)}},`×`)))))}function I(e,t){j(u,e,t)}function L(e){M(f,e)}function R(t){return e(`li.setup-step${t.done?`.done`:``}`,e(`span.setup-check`,t.done?l(`check`,{size:12}):``),e(`div`,e(`div.setup-step-title`,t.title),t.detail&&e(`div.setup-step-detail`,t.detail)))}return t}function O(t,n){let r=k(t,n),i=r>0,o=()=>{i&&(location.hash=`#/tasks?task=${encodeURIComponent(r)}`)};return e(`tr${i?`.activity-row`:``}`,i?{role:`link`,tabindex:`0`,title:`Open task details`,onclick:o,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())}}:void 0,e(`td.strong`,e(`span`,t.kind||t.type||`event`)),e(`td.mono`,i?`#${r}`:`—`),e(`td`,t.detail||t.message||``),e(`td`,a(t.at||Date.now())))}function k(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function A(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function j(t,i,a){let o=a?.workflows||[],c=o.reduce((e,t)=>e+(t.runs||0),0),l=o.reduce((e,t)=>e+(t.merged||0)+(t.pr_open||0),0),u=o.reduce((e,t)=>e+(t.parked||0),0);if(!c){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Gate pulse`)),s(`No completed runs yet`,`Once Archie finishes a task, its gate pass rate appears here.`)));return}let d=l/c*100;n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Gate pulse`),e(`p.card-sub`,`Work that passed its quality gates`))),b({value:d,label:`pass rate`}),e(`ul.pulse-list`,...o.slice(0,3).map(t=>e(`li.pulse-item`,e(`span.pulse-name`,t.workflow||`workflow`),r(`${t.merged||0}/${t.runs||0}`,(t.merged||0)===(t.runs||0)?`ok`:(t.parked||0)>0?`warn`:`info`))),u>0&&e(`li.pulse-item`,e(`span.pulse-name`,`Parked, awaiting you`),r(String(u),`warn`)))))}function M(t,r){let i=r?.tokens_by_day||[],a=i.reduce((e,t)=>e+(t.tokens||0),0);if(!i.length){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Token outlook`)),s(`Nothing spent yet`,`Usage appears here once Archie runs its first task.`)));return}let c=a/i.length,l=Math.round(c*30),u=i.slice(-7).reduce((e,t)=>e+(t.tokens||0),0);n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Token outlook`),e(`p.card-sub`,`Next 30 days at the current rate`))),e(`div.forecast-value`,o(l)),e(`div.forecast-note`,`Based on ${o(Math.round(c))} per day over ${i.length} days`),x([{label:`Last 7 days (${o(u)})`,value:u,kind:`info`},{label:`Earlier (${o(a-u)})`,value:Math.max(a-u,0),kind:`idle`}])))}function N(e){if(e.length<4)return null;let t=Math.floor(e.length/2),n=e.slice(0,t).reduce((e,t)=>e+t,0),r=e.slice(t).reduce((e,t)=>e+t,0);return n?(r-n)/n*100:null}function P(e,t){let n=e.title||`untitled task`;return{"aria-expanded":String(t),"aria-controls":`task-timeline-${e.id}`,"aria-label":`${t?`Collapse`:`Expand`} timeline for ${n}`}}var F=new Set([`waiting_human`,`parked`]),I=new Set([`needs_you`,`queued`,`running`,`waiting_human`,`pr_open`,`merged`,`parked`,`dead`,`rejected`,`closed_wont_do`]);function L(e){let t=e?.get?.(`status`)||``;return I.has(t)?t:``}function R(e,t){return t?t===`needs_you`?F.has(e.status):e.status===t:!0}var z={queued:`Queued`,running:`Working`,waiting_human:`Waiting for you`,pr_open:`In review`,merged:`Merged`,parked:`Parked`,dead:`Stopped (too many retries)`,rejected:`Rejected`,closed_wont_do:`Won't do`};function B(e){return z[e]||e||`Unknown`}function V(t=new URLSearchParams){let o=e(`div`),c=e(`div.grid.grid-4.task-summary`),l=e(`tbody`),u=[],d=L(t),f=``,p=Number(t.get(`task`)),m=Number.isFinite(p)&&p>0?p:null,g=m!==null,_=``,y=new Map,b=new Map,x=new Set,S=e(`input.task-search`,{type:`search`,placeholder:`Search by title or repo…`,oninput:e=>{f=e.target.value.trim().toLowerCase(),O()}}),C=e(`select.task-filter`,{onchange:e=>{d=e.target.value,O()}},e(`option`,{value:``},`All statuses`),e(`option`,{value:`needs_you`,selected:d===`needs_you`},`Needs you`),...Object.entries(z).map(([t,n])=>e(`option`,{value:t,selected:d===t},n)));w(),T();function w(){n(o,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Tasks`),e(`p.page-sub`,`Every issue archied has picked up, and where it stands.`)),e(`div.page-actions`,e(`button.btn`,{onclick:T},`Refresh`))),c,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`All tasks`),e(`p.card-sub`,`Click a row for its timeline`)),e(`div.task-filters`,S,C)),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repo`,`Issue`,`Title`,`Status`,`Workflow`,`Stage`,`Last activity`,`Action`].map(t=>e(`th`,t)))),l))))}async function T(){try{[u,_]=await Promise.all([h.tasks(),h.config().then(e=>e?.identity?.forge_host||``).catch(()=>``)]),E(),O(),m&&u.some(e=>String(e.id)===String(m))&&W(m),k()}catch(t){n(c,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(l,e(`tr`,e(`td`,{colspan:8},s(`Cannot reach archied`,String(t.message||t)))))}}function E(){let e=u.length,t={};for(let e of u)t[e.status]=(t[e.status]||0)+1;let r=t.running||0,i=(t.waiting_human||0)+(t.parked||0),a=(t.merged||0)+(t.pr_open||0);n(c,v({label:`Total tasks`,value:e,compare:e?`Everything archied has ever picked up`:`No tasks yet`}),v({label:`Working now`,value:r,compare:e?`${r} of ${e} in progress`:`Nothing running`}),v({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),v({label:`Delivered`,value:a,compare:e?`${Math.round(a/e*100)}% of all tasks`:`No tasks yet`}))}function D(){return u.filter(e=>R(e,d)?!f||`${e.title} ${e.repo}`.toLowerCase().includes(f):!1)}function O(){let t=D();if(!u.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No tasks yet`,`Tasks appear here once archied picks up an issue to work.`))));return}if(!t.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No matching tasks`,`Try a different search or status filter.`))));return}l.replaceChildren();for(let e of t)l.append(A(e)),m===e.id&&l.append(H(e));k()}function k(){!g||!m||(g=!1,requestAnimationFrame(()=>{let e=document.getElementById(`task-row-${m}`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView({block:`center`,behavior:`smooth`}))}))}function A(t){let n=m===t.id,o=`task-timeline-${t.id}`,s=e=>{e?.stopPropagation(),m=m===t.id?null:t.id,O(),m===t.id&&W(t.id)};return e(`tr.task-row`,{...P(t,n),id:`task-row-${t.id}`,tabindex:`0`,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),s(e))},onclick:s},e(`td.mono`,{"data-label":`Repository`},e(`button.task-expand`,{type:`button`,"aria-expanded":String(n),"aria-controls":o,"aria-label":`${n?`Collapse`:`Expand`} timeline for ${t.title||`untitled task`}`,onclick:s},n?`−`:`+`),I(t)??`${t.owner}/${t.repo}`),e(`td.mono`,{"data-label":`Issue`},V(t)??`#${t.issue_number}`),e(`td.strong`,{"data-label":`Title`},t.title||`(untitled)`),e(`td`,{"data-label":`Status`},r(B(t.status),i(t.status))),e(`td`,{"data-label":`Workflow`},t.workflow||`—`),e(`td`,{"data-label":`Stage`},t.stage||`—`),e(`td`,{"data-label":`Last activity`,title:t.created_at?`Created ${a(t.created_at)}`:``},a(t.updated_at)),e(`td`,{"data-label":`Actions`},j(t)))}function j(t){let n=b.get(t.id),r=n?e(`span.task-action-error`,n):null,i=x.has(t.id),a=(n,r,a,o)=>e(n,{type:`button`,disabled:i,onclick:e=>{e.stopPropagation(),!(o&&!window.confirm(o))&&M(t.id,r)}},a),o=(t.actions||[]).map(e=>{switch(e){case`cancel`:return a(`button.btn.btn-small.btn-quiet`,e,`Cancel`,`Cancel "${t.title||`this task`}"? This closes the forge issue.`);case`stop`:return a(`button.btn.btn-small`,e,`Stop`,`Stop "${t.title||`this task`}"? Recoverable work will remain parked.`);case`approve`:return a(`button.btn.btn-small`,e,`Approve`);case`reject`:return a(`button.btn.btn-small.btn-quiet`,e,`Reject`,`Reject "${t.title||`this task`}"? This closes the forge issue.`);case`retry`:return a(`button.btn.btn-small`,e,`Retry`);case`abandon`:return a(`button.btn.btn-small.btn-quiet`,e,`Abandon`,`Abandon "${t.title||`this task`}"? This closes the forge issue.`);case`archive`:return a(`button.btn.btn-small.btn-quiet`,e,`Archive`,`Archive the local record for "${t.title||`this task`}"?`);case`open_pr`:return F(t,`pulls`,t.pr_number,`Open PR`);case`open_issue`:return F(t,`issues`,t.issue_number,`Open issue`);default:return null}});return!o.length&&!r?`—`:e(`div.task-actions`,r,o)}async function M(e,t){b.delete(e),x.add(e),O();try{await h.taskAction(e,t),x.delete(e),t===`archive`&&(m=null),await T()}catch(t){x.delete(e),b.set(e,t.message||`Action failed`),O()}}function N(e){return!_||!e.owner||!e.repo?null:`${_.replace(/\/+$/,``)}/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`}function F(t,n,r,i){let a=N(t);return!a||!r||n===`issues`&&t.source===`chat`?e(`button.btn.btn-small`,{type:`button`,disabled:!0,title:`${i} is unavailable`},i):e(`a.btn.btn-small`,{href:`${a}/${n}/${r}`,target:`_blank`,rel:`noreferrer`,onclick:e=>e.stopPropagation()},i)}function I(t){let n=N(t);return n?e(`a.task-source-link`,{href:n,target:`_blank`,rel:`noreferrer`,title:`Open ${t.owner}/${t.repo} on the forge`,onclick:e=>e.stopPropagation()},`${t.owner}/${t.repo}`):null}function V(t){let n=N(t);return t.source===`chat`||!n||!t.issue_number?null:e(`a.task-source-link`,{href:`${n}/issues/${t.issue_number}`,target:`_blank`,rel:`noreferrer`,title:`Open issue #${t.issue_number} on the forge`,onclick:e=>e.stopPropagation()},`#${t.issue_number}`)}function H(t){let n=y.get(t.id);return e(`tr.task-timeline-row`,{id:`task-timeline-${t.id}`},e(`td`,{colspan:8},e(`div.task-detail-actions`,e(`div.task-decision-title`,`Available actions`),j(t)),t.status===`waiting_human`&&t.plan?e(`div.task-decision`,e(`div.task-decision-title`,`Decision required`),e(`div.task-decision-plan`,t.plan)):t.status===`parked`&&t.park_reason?e(`div.task-decision`,e(`div.task-decision-title`,`Park reason`),e(`div.task-decision-plan`,t.park_reason)):null,n===void 0?e(`div.task-timeline-loading`,`Loading timeline…`):n===null?e(`div.task-timeline-error`,e(`div.task-timeline-title`,`Could not load timeline`),e(`div.task-timeline-detail`,`archied did not answer for this task's events. It may be restarting — retry, or check the daemon.`),e(`button.btn`,{onclick:()=>W(t.id)},`Retry`)):n.length?e(`ul.task-timeline`,...n.map(U)):s(`No events yet`,`This task has not recorded any transitions.`)))}function U(t){return e(`li.task-timeline-entry`,e(`span.task-timeline-dot`),e(`div`,e(`div.task-timeline-kind`,t.kind||t.type||`event`),t.detail&&e(`div.task-timeline-detail`,t.detail),e(`div.task-timeline-when`,a(t.at))))}async function W(e){try{let t=await h.task(e);y.set(e,t||[])}catch{y.set(e,null)}O()}return o}function H(){let t=e(`div`),r=e(`div.grid.grid-2`),i=e(`input.skill-search`,{type:`search`,placeholder:`Search skills…`,oninput:e=>{o=e.target.value.trim().toLowerCase(),d()}}),a=[],o=``,c=null;l(),u();function l(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Skills`),e(`p.page-sub`,`What Archie can do, in plain language.`)),e(`div.page-actions`,e(`button.btn`,{onclick:u},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Catalogue`),e(`p.card-sub`,`Project, shared, and user-global skills`)),i),r)),d()}async function u(){try{a=(await h.skills())?.skills||[],c=null}catch(e){a=[],c=String(e.message||e)}d()}function d(){if(c)return n(r,s(`Cannot reach archied`,c));if(!a.length)return n(r,s(`No skills discovered yet`,`Skills live as SKILL.md files under project, shared, or user-global .agents/skills// directories. Add one and refresh to make it available.`));let e=a.filter(e=>f(e,o));if(!e.length)return n(r,s(`No skills match`,`Nothing found for "${o}".`));n(r,...e.map(p))}function f(e,t){return!t||`${e.name} ${e.description}`.toLowerCase().includes(t)}function p(t){return e(`div.card.skill-card`,e(`div.card-head`,e(`h3.card-title`,t.name||`Untitled skill`),t.workflow&&e(`span.pill.pill-info`,t.workflow)),e(`p.skill-desc`,t.description||`No description provided.`),e(`div.skill-source`,t.source||`Unknown source`))}return t}var U={bootstrap:`Bootstrap`,implement:`Implement`,tdd:`TDD`,feasibility:`Feasibility check`};function W(e){return U[e]?U[e]:e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown`}function G(e,t){return t?Math.round(e/t*100):0}function K(t,n=`ok`){return e(`div.wf-bar`,e(`div.wf-bar-fill.wf-bar-${n}`,{style:`width:${Math.min(100,Math.max(0,t))}%`}))}function ee(e){if(!e)return`—`;if(e<1e3)return`${e} ms`;let t=e/1e3;return t<60?`${t.toFixed(1)} s`:`${(t/60).toFixed(1)} min`}function te(){let t=e(`div`),r=e(`div`),i=e(`div`),a=e(`div`);o(),c();function o(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Workflows`),e(`p.page-sub`,`Run outcomes and spend per workflow, and where stages get stuck.`)),e(`div.page-actions`,e(`button.btn`,{onclick:c},`Refresh`))),a,r,i)}async function c(){try{let e=await h.workflows();l(e?.definitions||[]),u(e?.workflows||[],e?.definitions||[]),d(e?.stages||[])}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(i)}}function l(t){if(!t.length){n(a);return}let r=e(`input`,{placeholder:`Identity`,required:!0}),i=e(`input`,{placeholder:`owner/repository`,required:!0}),o=e(`select`,{required:!0},...t.filter(e=>e.enabled).map(t=>e(`option`,{value:t.id},W(t.name||t.id)))),s=e(`input`,{placeholder:`Short task title`,required:!0}),c=e(`textarea`,{placeholder:`Instructions for the work`,required:!0,rows:3}),l=e(`p.card-sub`),u=e(`button.btn`,{type:`submit`},`Start work`),d=e(`form.wf-form`,{onsubmit:async e=>{e.preventDefault(),u.disabled=!0;try{let e=await h.workRequest({identity:r.value,repository:i.value,workflow:o.value,title:s.value,instructions:c.value});l.textContent=`Queued task #${e.task_id}.`,d.reset()}catch(e){l.textContent=String(e.message||e)}finally{u.disabled=!1}}},r,i,o,s,c,u,l);n(a,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Start work`),e(`p.card-sub`,`This enters Archie’s normal admitted task queue.`))),d))}function u(t,i){let a=new Map(t.map(e=>[e.workflow,e])),o=i.map(e=>({...e,...a.get(e.id)||{workflow:e.id,runs:0,merged:0}}));if(!o.length){n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`))),s(`No workflow runs yet`,`Stats appear here once a task has run through a workflow.`)));return}n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`),e(`p.card-sub`,`Success rate is merged tasks over all runs`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Origin`,`Runs`,`Success rate`,`Avg tokens`,`Avg steps`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>{let n=G(t.merged,t.runs);return e(`tr`,e(`td.strong`,W(t.workflow)),e(`td.mono`,t.origin||`registry`),e(`td`,`${t.runs} run${t.runs===1?``:`s`}`),e(`td`,e(`div.wf-rate`,`${n}%`,e(`span.wf-rate-sub`,`${t.merged} of ${t.runs} merged`)),K(n,n>=50?`ok`:`warn`)),e(`td.mono`,t.avg_tokens?t.avg_tokens.toLocaleString():`—`),e(`td.mono`,t.avg_steps?t.avg_steps.toFixed(1):`—`))}))))))}function d(t){if(!t.length){n(i,e(`div.card.wf-stage-card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per stage`))),s(`No stage data yet`,`Stage timing and failures appear here once workflows have run.`)));return}let r=Math.max(...t.map(e=>e.avg_ms||0),1),a=[...t].sort((e,t)=>(t.avg_ms||0)-(e.avg_ms||0)),o=[...t].filter(e=>e.errors>0).sort((e,t)=>t.errors-e.errors);n(i,e(`div.grid.grid-2.wf-stage-card`,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Slowest stages`),e(`p.card-sub`,`Average duration, this workflow's stages`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Runs`,`Avg duration`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(t=>e(`tr`,e(`td`,W(t.workflow)),e(`td.strong`,t.stage),e(`td`,`${t.runs}`),e(`td`,e(`div.wf-rate`,ee(t.avg_ms)),K(G(t.avg_ms,r),`info`)))))))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Most failures`),e(`p.card-sub`,`Stages that error out, over their runs`))),o.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Failures`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>e(`tr`,e(`td`,W(t.workflow)),e(`td.strong`,t.stage),e(`td`,e(`div.wf-rate`,`${t.errors} of ${t.runs}`),K(G(t.errors,t.runs),`danger`))))))):s(`No failures recorded`,`Every stage has completed cleanly so far.`))))}return t}function ne(){let t=e(`div`),i=e(`div.grid.grid-2`);a(),o();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Channels`),e(`p.page-sub`,`The conversational front-ends Archie can be reached through.`)),e(`div.page-actions`,e(`button.btn`,{onclick:o},`Refresh`))),i)}async function o(){try{c((await h.channels())?.channels||[])}catch(e){n(i,s(`Cannot reach archied`,String(e.message||e)))}}function c(e){if(!e.length){n(i,s(`No channels configured`,`Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.`));return}n(i,...e.map(l))}function l(t){return e(`div.card.channel-card`,e(`div.card-head`,e(`h3.card-title`,t.name),r(t.state||(t.configured?`configured`:`stopped`),re(t.state,t.configured))),e(`p.channel-desc`,t.description),e(`p.channel-detail`,t.detail),t.reload_supported?e(`button.btn`,{onclick:async e=>{e.currentTarget.disabled=!0;try{await h.channelReload(t.id||t.name.toLowerCase()),await o()}catch{e.currentTarget.disabled=!1}}},`Reload`):e(`p.channel-detail`,`Reload requires a daemon restart for this adapter.`))}return t}function re(e,t){return e===`running`?`ok`:e===`failed`||e===`degraded`?`warn`:`idle`}function ie(e){return e==null||e===``?`—`:String(e)}function q(t,n,r){let i=ie(n),a=e(`span.kv-label`,t),o=e(`span.kv-value.mono${i===`—`?`.is-empty`:``}`,{title:i},i);if(!r?.key)return e(`div.kv`,a,o);let s=r.locked?.[r.key];if(s)return e(`div.kv.is-locked`,a,o,e(`span.kv-note`,s));let c=r.overridden?.includes(r.key),l=e(`button.kv-btn`,{type:`button`,title:`Edit ${t}`},`Edit`),u=c?e(`button.kv-btn`,{type:`button`,title:`Discard the dashboard value and fall back to the config file`},`Reset`):null,d=e(`div.kv-actions`,c&&e(`span.kv-flag`,{title:`Set from the dashboard; this shadows the value in the config file`},`overridden`),l,u),f=e(`div.kv`,a,o,d);return l.addEventListener(`click`,()=>se(f,t,r,[a,o,d])),u?.addEventListener(`click`,()=>ae(f,u,r)),f}function ae(e,t,n){let{key:r,onSaved:i}=n;t.disabled=!0,h.configReset(r).then(()=>i?.()).catch(n=>{t.disabled=!1,oe(e,String(n.message||n))})}function oe(t,n){let r=t.querySelector?.(`.kv-note`);r||(r=e(`span.kv-note.is-error`),t.appendChild(r)),r.classList.add(`is-error`),r.textContent=n}function se(t,r,i,a){let{key:o,type:s,raw:c,onSaved:l}=i,u=s===`bool`?e(`select.kv-input`,e(`option`,{value:`true`,selected:c===!0},`true`),e(`option`,{value:`false`,selected:c===!1},`false`)):e(`input.kv-input`,{type:`text`,value:String(c??``)}),d=e(`button.kv-save`,{type:`button`},`Save`),f=e(`button.kv-cancel`,{type:`button`},`Cancel`),p=e(`span.kv-note.is-error`);n(t,e(`span.kv-label`,r),u,e(`div.kv-actions`,d,f),p),u.focus?.(),u.select?.();let m=()=>n(t,...a);f.addEventListener(`click`,m),u.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.preventDefault?.(),d.click()),e.key===`Escape`&&m()}),d.addEventListener(`click`,async()=>{let e=ce(s,u.value);if(e.error){p.textContent=e.error;return}d.disabled=!0;try{await h.configUpdate({[o]:e.value}),l?.()}catch(e){p.textContent=String(e.message||e),d.disabled=!1}})}function ce(e,t){switch(e){case`int`:{let e=parseInt(t,10);return Number.isNaN(e)?{error:`Enter a whole number`}:{value:e}}case`bool`:return{value:t===`true`};default:return{value:t}}}var le={ok:`OK`,update_available:`Update available`,drift:`Drift`,unknown:`Unknown`},ue={ok:`ok`,update_available:`info`,drift:`danger`,unknown:`idle`};function de(t){return t.length?fe(`How each component is deployed, and whether what's running matches what's installed. Hover a row for the exact versions compared.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Component`,`Install type`,`Running`,`Latest available`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,{title:[`Installed claim: ${t.installed_claim||`unknown`}`,`Running: ${t.running_version||`not observed`}`,t.reference?`Reference: ${t.reference}`:null].filter(Boolean).join(` -`)},e(`td.strong`,t.label||t.id),e(`td.mono`,t.install_type||`—`),e(`td.mono`,t.running_version||`—`),e(`td.mono`,t.latest_available||`—`),e(`td`,r(le[t.status]||t.status,ue[t.status]||`idle`)))))))):fe(`How each component is deployed, and whether what's running matches what's installed.`,s(`No components reported`,`The configured update-check command returned nothing.`))}function fe(t,...n){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Update status`),e(`p.card-sub`,t))),...n)}function pe(){let t=e(`div.cfg-page`),r=e(`div`),i=e(`div`);a(),o(),c();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Configuration`),e(`p.page-sub`,`What archied is actually running with right now.`)),e(`div.page-actions`,e(`button.btn`,{onclick:()=>{o(),c()}},`Refresh`))),i,r)}async function o(){try{l(await h.config(),o)}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t))))}}async function c(){try{let e=await h.version();n(i,de(e?.components||[]))}catch(t){if(t?.status===501){n(i);return}n(i,e(`div.card`,s(`Update status unavailable`,String(t.message||t))))}}function l(t,i){if(!t||Object.keys(t).length===0){n(r,e(`div.card`,s(`No configuration loaded`,`archied is running without a config file wired into the dashboard, so there is nothing to show.`)));return}let a={locked:t.locked||{},overridden:t.overridden||[],onSaved:i},o=[t.reload?.overlay_unavailable&&e(`div.card.cfg-notice`,e(`p`,`The runtime config overlay is not in effect: ${t.reload.overlay_unavailable}`)),t.reload?.last_error&&e(`div.card.cfg-notice`,e(`p`,`The last config reload failed; the running config is unchanged: ${t.reload.last_error}`))];n(r,...o,he(t.identity,a),ge(t.repositories),ve(t.models,t.providers),be(t.budgets,a),xe(t.storage,t.containers,a),Ce(t.web,a),me(t.provenance))}return t}function me(t){return t?.length?J(`Configuration sources`,`Applied from top to bottom; later entries take precedence over earlier ones.`,e(`div.kv-list`,...t.map(e=>q(`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,e.path)))):J(`Configuration sources`,`The files that supplied the running configuration.`,s(`Source provenance is unavailable.`))}function J(t,n,...r){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t),e(`p.card-sub`,n))),...r)}function he(t,n){return t?J(`Identity`,`Who Archie is on the forge, and how it addresses commits and comments.`,e(`div.kv-list`,q(`Bot account`,t.bot_user,{key:`bot_user`,type:`string`,raw:t.bot_user,...n}),q(`Commit author email`,t.bot_email,{key:`bot_email`,type:`string`,raw:t.bot_email,...n}),q(`Pickup label`,t.label,{key:`label`,type:`string`,raw:t.label,...n}),q(`Forge type`,t.forge_type,{key:`forge.type`,type:`string`,raw:t.forge_type,...n}),q(`Forge host`,t.forge_host,{key:`forge.host`,type:`string`,raw:t.forge_host,...n}),q(`Max diff size (lines)`,t.diff_cap_lines||`Unlimited`,{key:`diff_cap_lines`,type:`int`,raw:t.diff_cap_lines,...n}))):J(`Identity`,`Who Archie is on the forge.`,s(`Not available`))}function ge(t){return t?.length?J(`Repositories`,`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repository`,`Base branch`,`Ecosystem`,`Quality gate`,`Protected paths`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,e(`td.strong`,`${t.owner}/${t.name}`),e(`td.mono`,t.base),e(`td`,t.ecosystem||`go`),e(`td.mono`,_e(t.gate)),e(`td.mono`,t.protect?.length?t.protect.join(`, `):`—`))))))):J(`Repositories`,`The repositories Archie polls for work.`,s(`No repositories configured`,`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`))}function _e(e){return e?.length?e.map(e=>e.join(` `)).join(` → `):`—`}function ve(t,n){let i=Object.entries(t||{}),a=Object.entries(n||{}),o=i.length?e(`div.kv-list`,...i.map(([e,t])=>q(ye(e),t))):s(`No model roles configured`,`Assign a model to at least one role (e.g. "builder") in [models].`),c=a.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Provider`,`Class`,`Base URL`,`API key env var`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(([t,n])=>e(`tr`,e(`td.strong`,t),e(`td`,n.class),e(`td.mono`,n.base_url||`default`),e(`td.mono`,n.api_key_env||`—`),e(`td`,n.configured?r(`configured`,`ok`):r(`missing credentials`,`warn`))))))):s(`No providers configured`,`Add a [providers.] entry so a model role above has something to run on.`);return J(`Models & providers`,`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,e(`h3.cfg-subhead`,`Model roles`),o,e(`h3.cfg-subhead`,`Providers`),c)}function ye(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function be(t,n){return t?J(`Budgets`,`The limits every autonomous stage runs under, so a stuck task cannot run forever.`,e(`div.kv-list`,q(`Max steps`,t.max_steps||`Unlimited`,{key:`budgets.max_steps`,type:`int`,raw:t.max_steps,...n}),q(`Wall clock`,t.wall_clock,{key:`budgets.wall_clock`,type:`string`,raw:t.wall_clock,...n}),q(`Max gate failures before parking`,t.gate_max_failures||`Unlimited`,{key:`budgets.gate_max_failures`,type:`int`,raw:t.gate_max_failures,...n}))):J(`Budgets`,`Limits on every agent stage.`,s(`Not available`))}function xe(t,n,r){let i=[];return t&&i.push(e(`h3.cfg-subhead`,`Paths`),e(`div.kv-list`,q(`Work directory`,t.work_dir,{key:`work_dir`,type:`string`,...r}),q(`State path prefix`,t.db_path,{key:`db_path`,type:`string`,...r}),q(`Shared skills directory`,t.skills_dir||`None (uses the work directory)`,{key:`skills_dir`,type:`string`,raw:t.skills_dir,...r}),q(`Daemon plugin directory`,t.plugin_dir||`None`,{key:`plugin_dir`,type:`string`,raw:t.plugin_dir,...r}),q(`Secret engine plugin directory`,t.secret_engine_dir||`None (built-in engines only)`,{key:`secret_engine_dir`,type:`string`,raw:t.secret_engine_dir,...r}))),n&&i.push(e(`h3.cfg-subhead`,`Sandboxed containers`),e(`div.kv-list`,q(`Agent image`,n.image||`Not set`,{key:`containers.image`,type:`string`,raw:n.image,...r}),q(`Max concurrent tasks`,n.max_concurrency||`Unlimited`,{key:`containers.max_concurrency`,type:`int`,raw:n.max_concurrency,...r}),q(`Container max lifetime`,n.max_uptime,{key:`containers.max_uptime`,type:`string`,raw:n.max_uptime,...r}),q(`Persistent volume retention`,n.volume_ttl,{key:`containers.volume_ttl`,type:`string`,raw:n.volume_ttl,...r}),q(`How images are refreshed`,Se(n.pull_policy),{key:`containers.pull_policy`,type:`string`,raw:n.pull_policy,...r}),q(`Docker network`,n.network||`Auto-detected`,{key:`containers.network`,type:`string`,raw:n.network,...r}))),i.length||i.push(s(`Not available`)),J(`Storage & sandboxing`,`Where archied keeps its state, and how it isolates task execution.`,...i)}function Se(e){return e===`always`?`Always pull the latest image before running`:`Only pull when the image is missing locally`}function Ce(t,n){return t?J(`Dashboard`,`This dashboard's own listen address.`,e(`div.kv-list`,q(`Listen address`,t.listen===`off`?`Disabled`:t.listen,{key:`web.listen`,type:`string`,raw:t.listen===`off`?``:t.listen,...n}))):J(`Dashboard`,`This dashboard's own listen address.`,s(`Not available`))}var we=[{value:``,label:`All levels`},{value:`ERROR`,label:`Errors`},{value:`WARN,ERROR`,label:`Warnings and errors`},{value:`INFO,WARN,ERROR`,label:`Info and above`},{value:`DEBUG`,label:`Debug only`}];function Te(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function Ee(){let t=e(`div`),i=e(`div.log-list`),a=r(`connecting`,`idle`),o=e(`span.log-meta`),c={level:``,component:``,q:``},l=!1,u=[],d=[],f=new Map,p=!1,m=e(`select.log-select`,{onchange:e=>x({level:e.target.value})},...we.map(t=>e(`option`,{value:t.value},t.label))),g=e(`select.log-select`,{onchange:e=>x({component:e.target.value})}),v=e(`input.log-search`,{type:`search`,placeholder:`Search messages and fields…`,oninput:Me(e=>x({q:e.target.value}),250)}),y=e(`button.btn`,{onclick:S},`Pause`);C();let b=_(e=>E(e),e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,b),w();function x(e){c={...c,...e},w()}function S(){l=!l,y.textContent=l?`Resume`:`Pause`,y.classList.toggle(`btn-primary`,l)}function C(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Logs`),e(`p.page-sub`,`What Archie has been doing, newest last.`)),e(`div.page-actions`,y,e(`button.btn`,{onclick:w},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div.log-filters`,m,g,v),e(`div.log-status`,o,a)),i))}async function w(){o.textContent=`Refreshing…`;try{let e=await h.logs({level:c.level,component:c.component,q:c.q,limit:500});T(e.components||[]),p=!!e.disabled,o.textContent=e.disabled?`Durable history unavailable; live daemon logs continue.`:e.truncated?`showing the most recent matches from ${e.file}`:e.file||``,d=e.entries||[],D()}catch(e){n(i,s(`Cannot read logs`,String(e.message||e)))}}function T(t){if(je(t,u))return;u=t;let r=c.component;n(g,e(`option`,{value:``},`All components`),...t.map(t=>e(`option`,{value:t},t))),g.value=r}function E(e){if(l)return;let t=e;O(t)&&(f.set(De(t),t),t.fields?.component&&T([...u,t.fields.component]),D())}function D(){let e=new Map;for(let t of d)e.set(De(t),t);for(let[t,n]of f)e.set(t,n);let t=[...e.values()].filter(O).slice(-1e3);if(!t.length){n(i,s(p?`Durable history unavailable`:`Nothing matches`,p?`Live daemon logs will appear here while this page is open.`:`Try a wider level or clear the search.`));return}n(i,...t.map(Oe)),i.scrollTop=i.scrollHeight}function O(e){if(c.level&&!c.level.split(`,`).includes((e.level||``).toUpperCase())||c.component&&e.fields?.component!==c.component)return!1;if(c.q){let t=c.q.toLowerCase();if(!`${e.message||e.msg||``} ${JSON.stringify(e.fields||{})}`.toLowerCase().includes(t))return!1}return!0}return t}function De(e){return`${e.time||``}|${e.level||``}|${e.message||e.msg||``}|${JSON.stringify(e.fields||{})}`}function Oe(t){let n=t.fields||{};return e(`div.log-row.log-${Te(t.level)}`,e(`span.log-time.mono`,Ae(t.time)),e(`span.log-level`,(t.level||`info`).toUpperCase()),e(`span.log-body`,e(`span.log-msg`,t.message||t.msg||``),...Object.entries(n).map(([t,n])=>e(`span.log-field`,e(`span.log-field-key`,t),String(ke(n))))))}function ke(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function Ae(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function je(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Me(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}}function Ne(t,{expanded:n,onToggle:i}){let o=e(`tr.capture-row`,{tabindex:`0`,"aria-expanded":String(n),onclick:i,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i(e))}},e(`td.mono`,t.source||`(unknown)`),e(`td`,{title:t.received_at||``},a(t.received_at)),e(`td`,r(`Unbound`,`idle`)),e(`td.mono`,t.content_type||`—`),e(`td`,e(`button.btn.btn-small`,{type:`button`},n?`Hide`:`View`)));return n?[o,Pe(t)]:[o]}function Pe(t){return e(`tr.capture-detail-row`,e(`td`,{colspan:5},e(`div.capture-detail`,e(`div.capture-detail-section`,e(`div.capture-detail-title`,`Payload`),Fe(t.body)),e(`div.capture-detail-section`,e(`div.capture-detail-title`,`Headers`),Fe(t.headers)))))}function Fe(t){return t?e(`pre.capture-payload`,Ie(t)):e(`div.capture-empty`,`(empty)`)}function Ie(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function Le(){let t=e(`div`),i=e(`div.card`),a=r(`connecting`,`idle`),o=[],c=null,l=null,u=!0;p(),f();let d=g(e=>{e.kind===`capture`&&f()},e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,d);async function f(){try{let e=await h.captures(100);u=e.enabled!==!1,o=e.captures||[],l=null}catch(e){l=String(e.message||e)}m()}function p(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Event inspector`),e(`p.page-sub`,`Real inbound payloads archie has captured, most recent first.`)),e(`div.page-actions`,a,e(`button.btn`,{onclick:f},`Refresh`))),i),m()}function m(){if(l){n(i,s(`Cannot reach archied`,l));return}if(!u){n(i,s(`Capture is not configured`,`This deployment has no capture storage wired up.`));return}if(!o.length){n(i,s(`No captures yet`,`Point a webhook at /webhooks/capture/ and it will show up here.`));return}n(i,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Source`,`Received`,`Binding`,`Content type`,``].map(t=>e(`th`,t)))),e(`tbody`,...o.flatMap(e=>Ne(e,{expanded:c===e.id,onToggle:()=>{c=c===e.id?null:e.id,m()}}))))))}return t}var Re=[`string`,`number`,`bool`,`object`,`array`,`any`];function ze(e){if(e==null)return`any`;if(Array.isArray(e))return`array`;switch(typeof e){case`string`:return`string`;case`number`:return`number`;case`boolean`:return`bool`;case`object`:return`object`;default:return`any`}}function Be(e,t){return e?`${e}.${t}`:t}function Ve(e,t){return`${e}[${t}]`}function He(t,{path:n=``,name:r=``,onPick:i}={}){return typeof t==`object`&&t?e(`ul.mapping-tree-list`,...(Array.isArray(t)?t.map((e,t)=>[String(t),e,Ve(n,t)]):Object.entries(t).map(([e,t])=>[e,t,Be(n,e)])).map(([t,n,r])=>e(`li.mapping-tree-item`,e(`span.mapping-tree-key`,{onclick:e=>{e.stopPropagation(),i?.({path:r,type:ze(n),name:t})}},t),He(n,{path:r,name:t,onPick:i})))):e(`span.mapping-tree-value`,{onclick:e=>{e.stopPropagation(),i?.({path:n,type:ze(t),name:r})}},JSON.stringify(t))}function Ue(t,{preview:n,onRemove:r,onNameChange:i,onTypeChange:a,onRequiredChange:o}={}){if(!t.length)return e(`div.mapping-empty-fields`,`Click a value in the payload to bind a field.`);let s=new Map((n?.failures||[]).map(e=>[e.field_name,e]));return e(`table.table.mapping-fields-table`,e(`thead`,e(`tr`,...[`Field name`,`Path`,`Type`,`Required`,`Preview`,``].map(t=>e(`th`,t)))),e(`tbody`,...t.map((t,c)=>e(`tr`,e(`td`,e(`input.mapping-input`,{value:t.name,oninput:e=>i?.(c,e.target.value)})),e(`td.mono`,t.path),e(`td`,e(`select.mapping-select`,{onchange:e=>a?.(c,e.target.value)},...Re.map(n=>e(`option`,{value:n,selected:n===t.type},n)))),e(`td`,e(`input`,{type:`checkbox`,checked:t.required,onchange:e=>o?.(c,e.target.checked)})),e(`td`,We(t,n,s)),e(`td`,e(`button.btn.btn-small`,{type:`button`,onclick:()=>r?.(c)},`Remove`))))))}function We(e,t,n){if(!t)return r(`not previewed`,`idle`);let i=n.get(e.name);return i?r(i.reason,`danger`):Object.prototype.hasOwnProperty.call(t.values||{},e.name)?r(JSON.stringify(t.values[e.name]),`ok`):r(`skipped (optional)`,`idle`)}function Ge(t,{onEdit:n,onDelete:r}){return e(`tr`,e(`td`,t.name),e(`td.mono`,t.source_hint||`—`),e(`td`,String(t.fields?.length??0)),e(`td`,e(`button.btn.btn-small`,{type:`button`,onclick:()=>n?.(t)},`Edit`),e(`button.btn.btn-small`,{type:`button`,onclick:()=>r?.(t)},`Delete`)))}function Ke(){let t=e(`div`),r=[],i=[],a=null,o=null;C(),c();async function c(){try{let[e,t]=await Promise.all([h.mappings(),h.captures(100)]);r=e.mappings||[],i=t.captures||[],a=null}catch(e){a=String(e.message||e)}C()}function l(){o={id:null,name:``,sourceHint:``,fields:[],captureId:null,payload:null,payloadError:null,preview:null,actionError:null},C()}function u(e){o={id:e.id,name:e.name,sourceHint:e.source_hint||``,fields:(e.fields||[]).map(e=>({...e})),captureId:null,payload:null,payloadError:null,preview:null,actionError:null},C()}async function d(e){if(window.confirm(`Delete mapping "${e.name}"?`))try{await h.mappingDelete(e.id),await c()}catch(e){a=String(e.message||e),C()}}function f(e){let t=i.find(t=>String(t.id)===String(e));if(o.captureId=t?t.id:null,o.preview=null,!t)o.payload=null,o.payloadError=null;else try{o.payload=JSON.parse(t.body),o.payloadError=null}catch{o.payload=null,o.payloadError=`This capture's body is not valid JSON, so its fields cannot be mapped by path.`}C()}function p({path:e,type:t,name:n}){let r=new Set(o.fields.map(e=>e.name)),i=n||`field`,a=1;for(;r.has(i);)i=`${n||`field`}_${++a}`;o.fields.push({name:i,path:e,type:t,required:!0}),o.preview=null,C()}function m(e){o.fields.splice(e,1),o.preview=null,C()}function g(e,t){Object.assign(o.fields[e],t),o.preview=null,C()}let _=(e,t)=>g(e,{name:t}),v=(e,t)=>g(e,{type:t}),y=(e,t)=>g(e,{required:t});async function b(){if(!o.captureId){o.actionError=`Pick a captured event to preview against.`,C();return}try{o.preview=await h.mappingPreview(o.captureId,o.fields),o.actionError=null}catch(e){o.actionError=String(e.message||e)}C()}async function x(){let e={name:o.name,source_hint:o.sourceHint,fields:o.fields};try{o.id?await h.mappingUpdate(o.id,e):await h.mappingCreate(e),o=null,await c()}catch(e){o.actionError=String(e.message||e),C()}}function S(){o=null,C()}function C(){n(t,o?T():w())}function w(){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Field mappings`),e(`p.page-sub`,`Bind named fields to JSON paths from a real captured event, ready for a playbook binding.`)),e(`div.page-actions`,e(`button.btn.btn-primary`,{type:`button`,onclick:l},`New mapping`))),a?s(`Cannot reach archied`,a):r.length?e(`div.card`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Name`,`Source hint`,`Fields`,``].map(t=>e(`th`,t)))),e(`tbody`,...r.map(e=>Ge(e,{onEdit:u,onDelete:d})))))):s(`No mappings yet`,`Create one from a captured event to reuse fields in a future playbook binding.`))}function T(){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,o.id?`Edit mapping`:`New mapping`)),e(`div.page-actions`,e(`button.btn`,{type:`button`,onclick:S},`Cancel`),e(`button.btn.btn-primary`,{type:`button`,onclick:x},`Save`))),o.actionError?e(`div.mapping-error`,o.actionError):null,e(`div.card.mapping-form`,e(`label.mapping-form-row`,`Name`,e(`input.mapping-input`,{value:o.name,oninput:e=>{o.name=e.target.value}})),e(`label.mapping-form-row`,`Source hint (organisational only)`,e(`input.mapping-input`,{value:o.sourceHint,oninput:e=>{o.sourceHint=e.target.value}})),e(`label.mapping-form-row`,`Preview against captured event`,e(`select.mapping-select`,{onchange:e=>f(e.target.value)},e(`option`,{value:``},`— pick a captured event —`),...i.map(t=>e(`option`,{value:t.id,selected:String(o.captureId)===String(t.id)},`${t.source||`(unknown)`} — ${t.received_at||``}`))))),e(`div.card.mapping-fields`,e(`div.mapping-section-title`,`Bound fields`),Ue(o.fields,{preview:o.preview,onRemove:m,onNameChange:_,onTypeChange:v,onRequiredChange:y}),e(`button.btn`,{type:`button`,onclick:b},`Preview`)),e(`div.card.mapping-payload`,e(`div.mapping-section-title`,`Payload — click a value to bind it`),o.payloadError?e(`div.mapping-error`,o.payloadError):o.payload===null?e(`div.mapping-empty-fields`,`Pick a captured event above to see its payload.`):He(o.payload,{onPick:p})))}return t}function qe(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Memory`),e(`p.page-sub`,`What Archie can recall between conversations, and the tools it uses to do it.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},l(`refresh`,{size:15}),`Refresh`))),r)}async function a(){n(r,e(`div.card`,e(`div.mem-loading`,`Loading…`)));try{let t=await h.memory();if(!t.enabled||!t.providers?.length){n(r,e(`div.card`,s(`Memory is not configured`,`Without a provider, Archie starts every conversation with no recollection of earlier ones.`)));return}n(r,e(`div.grid.grid-2`,...t.providers.map(Je)))}catch(t){n(r,e(`div.card`,s(`Cannot read memory providers`,String(t.message||t))))}}return t}function Je(t){let n=t.tools||[];return e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t.name||`provider`),e(`p.card-sub`,Ye(t.role))),t.available?r(`ready`,`ok`):r(`unavailable`,`danger`)),!t.available&&e(`p.mem-warning`,`Configured but not usable right now — a required binary or connection may be missing.`),n.length?e(`ul.mem-tools`,...n.map(t=>e(`li.mem-tool`,e(`div.mem-tool-name.mono`,t.name),t.description&&e(`div.mem-tool-desc`,t.description)))):e(`p.mem-warning`,`This provider exposes no tools, so the agent cannot use it.`))}function Ye(e){return e===`external`?`Added by you — an external store Archie was given`:`Built in — always available to Archie`}var Xe=`
+ class="gauge-value"/>`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function x(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}var S=`archie.setup-complete.dismissed.v1`;function C(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(S),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function w(e=globalThis.localStorage){e?.setItem?.(S,`1`)}var T=new Set([`waiting_human`,`parked`]);function E(e=[]){let t=e.filter(e=>T.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function D(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),m=e(`h1.hero-title`,A()),_=r(`connecting`,`idle`),y=[],b=new Map;S(),D();let x=g(e=>{y.unshift(e),y.splice(50),T()},e=>{_.className=`pill pill-${e===`live`?`ok`:`warn`}`,_.textContent=e});t.addEventListener(`archie:teardown`,x);function S(){n(t,e(`div.hero`,e(`div`,m,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),_),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),T()}function T(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>O(e,b)))}async function D(){try{let[e,t,n,r]=await Promise.all([h.summary(),h.setup().catch(()=>null),h.workflows().catch(()=>null),h.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);T(),k(r),m.textContent=t?.operator?`${A()}, ${t.operator}`:A(),P(e),F(t),I(e,n),L(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:D},l(`refresh`,{size:15}),`Retry`))}}function k(t){let r=E(t),i=r.attention.count,a=r.running.count;n(p,i>0&&e(`a.btn.btn-attention`,{href:r.attention.href},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:r.running.href},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:D},l(`refresh`,{size:15}),`Refresh`))}function P(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,v({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),v({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),v({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),v({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:N(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function F(t){let r=C(t),i=r.kind===`omit`||r.kind===`dismissed`;if(d.classList.toggle(`dash-top-standalone`,i),i)return n(c);let a=r.remaining;if(a.length){let r=Math.round((t.steps.length-a.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(R))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`div.setup-complete-actions`,e(`span.setup-pct`,l(`check`,{size:16})),e(`button.icon-btn.setup-dismiss`,{type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onclick:()=>{w(),F(t)}},`×`)))))}function I(e,t){j(u,e,t)}function L(e){M(f,e)}function R(t){return e(`li.setup-step${t.done?`.done`:``}`,e(`span.setup-check`,t.done?l(`check`,{size:12}):``),e(`div`,e(`div.setup-step-title`,t.title),t.detail&&e(`div.setup-step-detail`,t.detail)))}return t}function O(t,n){let r=k(t,n),i=r>0,o=()=>{i&&(location.hash=`#/tasks?task=${encodeURIComponent(r)}`)};return e(`tr${i?`.activity-row`:``}`,i?{role:`link`,tabindex:`0`,title:`Open task details`,onclick:o,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())}}:void 0,e(`td.strong`,e(`span`,t.kind||t.type||`event`)),e(`td.mono`,i?`#${r}`:`—`),e(`td`,t.detail||t.message||``),e(`td`,a(t.at||Date.now())))}function k(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function A(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function j(t,i,a){let o=a?.workflows||[],c=o.reduce((e,t)=>e+(t.runs||0),0),l=o.reduce((e,t)=>e+(t.merged||0)+(t.pr_open||0),0),u=o.reduce((e,t)=>e+(t.parked||0),0);if(!c){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Gate pulse`)),s(`No completed runs yet`,`Once Archie finishes a task, its gate pass rate appears here.`)));return}let d=l/c*100;n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Gate pulse`),e(`p.card-sub`,`Work that passed its quality gates`))),b({value:d,label:`pass rate`}),e(`ul.pulse-list`,...o.slice(0,3).map(t=>e(`li.pulse-item`,e(`span.pulse-name`,t.workflow||`workflow`),r(`${t.merged||0}/${t.runs||0}`,(t.merged||0)===(t.runs||0)?`ok`:(t.parked||0)>0?`warn`:`info`))),u>0&&e(`li.pulse-item`,e(`span.pulse-name`,`Parked, awaiting you`),r(String(u),`warn`)))))}function M(t,r){let i=r?.tokens_by_day||[],a=i.reduce((e,t)=>e+(t.tokens||0),0);if(!i.length){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Token outlook`)),s(`Nothing spent yet`,`Usage appears here once Archie runs its first task.`)));return}let c=a/i.length,l=Math.round(c*30),u=i.slice(-7).reduce((e,t)=>e+(t.tokens||0),0);n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Token outlook`),e(`p.card-sub`,`Next 30 days at the current rate`))),e(`div.forecast-value`,o(l)),e(`div.forecast-note`,`Based on ${o(Math.round(c))} per day over ${i.length} days`),x([{label:`Last 7 days (${o(u)})`,value:u,kind:`info`},{label:`Earlier (${o(a-u)})`,value:Math.max(a-u,0),kind:`idle`}])))}function N(e){if(e.length<4)return null;let t=Math.floor(e.length/2),n=e.slice(0,t).reduce((e,t)=>e+t,0),r=e.slice(t).reduce((e,t)=>e+t,0);return n?(r-n)/n*100:null}function P(e,t){let n=e.title||`untitled task`;return{"aria-expanded":String(t),"aria-controls":`task-timeline-${e.id}`,"aria-label":`${t?`Collapse`:`Expand`} timeline for ${n}`}}var F=new Set([`waiting_human`,`parked`]),I=new Set([`needs_you`,`queued`,`running`,`waiting_human`,`pr_open`,`merged`,`parked`,`dead`,`rejected`,`closed_wont_do`]);function L(e){let t=e?.get?.(`status`)||``;return I.has(t)?t:``}function R(e,t){return t?t===`needs_you`?F.has(e.status):e.status===t:!0}function z(e){return String(e||`event`).replaceAll(`_`,` `).replace(/\b\w/g,e=>e.toUpperCase())}function B(e){let t=Number(e);if(!Number.isFinite(t)||t<0)return``;if(t<1e3)return`${Math.round(t)} ms`;let n=t/1e3;if(n<60)return`${n.toFixed(+(n<10))} s`;let r=Math.round(n),i=Math.floor(r/60),a=r%60;if(i<60)return a===0?`${i} min`:`${i} min ${a} s`;let o=Math.floor(i/60),s=i-o*60;return s===0?`${o} h`:`${o} h ${s} min`}function V(e){let t=Number(e);return!Number.isFinite(t)||t<=0?``:t.toLocaleString(`en-US`)}function H(e={}){let t=e.data||{},n=e.stage||`unknown stage`,r=e.workflow?`${e.workflow} workflow`:``;if(e.kind===`stage_start`)return{title:`Started stage: ${n}`,detail:r};if(e.kind===`stage_finish`){let e=B(t.duration_ms),i=[r,e&&`ran for ${e}`].filter(Boolean).join(` · `);return{title:t.interrupted?`Stage interrupted: ${n}`:t.error?`Stage failed: ${n}`:`Finished stage: ${n}`,detail:[i,t.error].filter(Boolean).join(` — `)}}if(e.kind===`task_retried`){let n=Number(t.retry_count);return{title:Number.isFinite(n)&&n>0?`Retry ${n}`:`Retry requested`,detail:[t.previous_stage&&`after ${t.previous_stage}`,t.previous_reason].filter(Boolean).join(`: `)||e.detail||``}}if(e.kind===`agent_finish`){let r=V(t.iterations),i=V(t.tokens),a=V(t.prompt_tokens),o=V(t.completion_tokens),s=V(t.cached_tokens),c=[r&&`${r} iterations`,i&&`${i} tokens`,a&&`${a} prompt`,o&&`${o} completion`,s&&`${s} cached`,t.model].filter(Boolean);return{title:`Agent ${t.status||`finished`}: ${n}`,detail:c.join(` · `)||e.detail||``}}return{title:z(e.kind||e.type),detail:e.detail||``}}var U={queued:`Queued`,running:`Working`,waiting_human:`Waiting for you`,pr_open:`In review`,merged:`Merged`,parked:`Parked`,dead:`Stopped (too many retries)`,rejected:`Rejected`,closed_wont_do:`Won't do`};function ee(e){return U[e]||e||`Unknown`}function te(t=new URLSearchParams){let o=e(`div`),c=e(`div.grid.grid-4.task-summary`),l=e(`tbody`),u=[],d=L(t),f=``,p=Number(t.get(`task`)),m=Number.isFinite(p)&&p>0?p:null,g=m!==null,_=new Map,y=new Map,b=new Set,x=e(`input.task-search`,{type:`search`,placeholder:`Search by title or repo…`,oninput:e=>{f=e.target.value.trim().toLowerCase(),D()}}),S=e(`select.task-filter`,{onchange:e=>{d=e.target.value,D()}},e(`option`,{value:``},`All statuses`),e(`option`,{value:`needs_you`,selected:d===`needs_you`},`Needs you`),...Object.entries(U).map(([t,n])=>e(`option`,{value:t,selected:d===t},n)));C(),w();function C(){n(o,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Tasks`),e(`p.page-sub`,`Every issue archied has picked up, and where it stands.`)),e(`div.page-actions`,e(`button.btn`,{onclick:w},`Refresh`))),c,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`All tasks`),e(`p.card-sub`,`Click a row for its timeline`)),e(`div.task-filters`,x,S)),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repo`,`Issue`,`Title`,`Status`,`Workflow`,`Stage`,`Last activity`,`Action`].map(t=>e(`th`,t)))),l))))}async function w(){try{u=await h.tasks(),T(),D(),m&&u.some(e=>String(e.id)===String(m))&&B(m),O()}catch(t){n(c,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(l,e(`tr`,e(`td`,{colspan:8},s(`Cannot reach archied`,String(t.message||t)))))}}function T(){let e=u.length,t={};for(let e of u)t[e.status]=(t[e.status]||0)+1;let r=t.running||0,i=(t.waiting_human||0)+(t.parked||0),a=(t.merged||0)+(t.pr_open||0);n(c,v({label:`Total tasks`,value:e,compare:e?`Everything archied has ever picked up`:`No tasks yet`}),v({label:`Working now`,value:r,compare:e?`${r} of ${e} in progress`:`Nothing running`}),v({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),v({label:`Delivered`,value:a,compare:e?`${Math.round(a/e*100)}% of all tasks`:`No tasks yet`}))}function E(){return u.filter(e=>R(e,d)?!f||`${e.title} ${e.repo}`.toLowerCase().includes(f):!1)}function D(){let t=E();if(!u.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No tasks yet`,`Tasks appear here once archied picks up an issue to work.`))));return}if(!t.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No matching tasks`,`Try a different search or status filter.`))));return}l.replaceChildren();for(let e of t)l.append(k(e)),m===e.id&&l.append(I(e));O()}function O(){!g||!m||(g=!1,requestAnimationFrame(()=>{let e=document.getElementById(`task-row-${m}`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView({block:`center`,behavior:`smooth`}))}))}function k(t){let n=m===t.id,o=`task-timeline-${t.id}`,s=e=>{e?.stopPropagation(),m=m===t.id?null:t.id,D(),m===t.id&&B(t.id)};return e(`tr.task-row`,{...P(t,n),id:`task-row-${t.id}`,tabindex:`0`,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),s(e))},onclick:s},e(`td.mono`,{"data-label":`Repository`},e(`button.task-expand`,{type:`button`,"aria-expanded":String(n),"aria-controls":o,"aria-label":`${n?`Collapse`:`Expand`} timeline for ${t.title||`untitled task`}`,onclick:s},n?`−`:`+`),N(t)??`${t.owner}/${t.repo}`),e(`td.mono`,{"data-label":`Issue`},F(t)??`#${t.issue_number}`),e(`td.strong`,{"data-label":`Title`},t.title||`(untitled)`),e(`td`,{"data-label":`Status`},r(ee(t.status),i(t.status))),e(`td`,{"data-label":`Workflow`},t.workflow||`—`),e(`td`,{"data-label":`Stage`},t.stage||`—`),e(`td`,{"data-label":`Last activity`,title:t.created_at?`Created ${a(t.created_at)}`:``},a(t.updated_at)),e(`td`,{"data-label":`Actions`},A(t)))}function A(t){let n=y.get(t.id),r=n?e(`span.task-action-error`,n):null,i=b.has(t.id),a=(n,r,a,o)=>e(n,{type:`button`,disabled:i,onclick:e=>{e.stopPropagation(),!(o&&!window.confirm(o))&&j(t.id,r)}},a),o=(t.actions||[]).map(e=>{switch(e){case`cancel`:return a(`button.btn.btn-small.btn-quiet`,e,`Cancel`,`Cancel "${t.title||`this task`}"? This closes the forge issue.`);case`stop`:return a(`button.btn.btn-small`,e,`Stop`,`Stop "${t.title||`this task`}"? Recoverable work will remain parked.`);case`approve`:return a(`button.btn.btn-small`,e,`Approve`);case`reject`:return a(`button.btn.btn-small.btn-quiet`,e,`Reject`,`Reject "${t.title||`this task`}"? This closes the forge issue.`);case`retry`:return a(`button.btn.btn-small`,e,`Retry`);case`abandon`:return a(`button.btn.btn-small.btn-quiet`,e,`Abandon`,`Abandon "${t.title||`this task`}"? This closes the forge issue.`);case`archive`:return a(`button.btn.btn-small.btn-quiet`,e,`Archive`,`Archive the local record for "${t.title||`this task`}"?`);case`open_pr`:return M(t,`pull_request`,t.pr_number,`Open PR`);case`open_issue`:return M(t,`issue`,t.issue_number,`Open issue`);default:return null}});return!o.length&&!r?`—`:e(`div.task-actions`,r,o)}async function j(e,t){y.delete(e),b.add(e),D();try{await h.taskAction(e,t),b.delete(e),t===`archive`&&(m=null),await w()}catch(t){b.delete(e),y.set(e,t.message||`Action failed`),D()}}function M(t,n,r,i){let a=n===`issue`?t.issue_url:t.pr_url;return!a||!r||n===`issue`&&t.source===`chat`?e(`button.btn.btn-small`,{type:`button`,disabled:!0,title:`${i} is unavailable`},i):e(`a.btn.btn-small`,{href:a,target:`_blank`,rel:`noreferrer`,onclick:e=>e.stopPropagation()},i)}function N(t){let n=t.repo_url;return n?e(`a.task-source-link`,{href:n,target:`_blank`,rel:`noreferrer`,title:`Open ${t.owner}/${t.repo} on the forge`,onclick:e=>e.stopPropagation()},`${t.owner}/${t.repo}`):null}function F(t){let n=t.issue_url;return t.source===`chat`||!n||!t.issue_number?null:e(`a.task-source-link`,{href:n,target:`_blank`,rel:`noreferrer`,title:`Open issue #${t.issue_number} on the forge`,onclick:e=>e.stopPropagation()},`#${t.issue_number}`)}function I(t){let n=_.get(t.id);return e(`tr.task-timeline-row`,{id:`task-timeline-${t.id}`},e(`td`,{colspan:8},e(`div.task-detail-actions`,e(`div.task-decision-title`,`Available actions`),A(t)),t.status===`waiting_human`&&t.plan?e(`div.task-decision`,e(`div.task-decision-title`,`Decision required`),e(`div.task-decision-plan`,t.plan)):t.status===`parked`&&t.park_reason?e(`div.task-decision`,e(`div.task-decision-title`,`Park reason`),e(`div.task-decision-plan`,t.park_reason)):null,n===void 0?e(`div.task-timeline-loading`,`Loading timeline…`):n===null?e(`div.task-timeline-error`,e(`div.task-timeline-title`,`Could not load timeline`),e(`div.task-timeline-detail`,`archied did not answer for this task's events. It may be restarting — retry, or check the daemon.`),e(`button.btn`,{onclick:()=>B(t.id)},`Retry`)):n.length?e(`ul.task-timeline`,...n.map(z)):s(`No events yet`,`This task has not recorded any transitions.`)))}function z(t){let n=H(t);return e(`li.task-timeline-entry`,e(`span.task-timeline-dot`),e(`div`,e(`div.task-timeline-kind`,n.title),n.detail&&e(`div.task-timeline-detail`,n.detail),e(`div.task-timeline-when`,a(t.at))))}async function B(e){try{let t=await h.task(e);_.set(e,t||[])}catch{_.set(e,null)}D()}return o}function ne(){let t=e(`div`),r=e(`div.grid.grid-2`),i=e(`input.skill-search`,{type:`search`,placeholder:`Search skills…`,oninput:e=>{o=e.target.value.trim().toLowerCase(),d()}}),a=[],o=``,c=null;l(),u();function l(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Skills`),e(`p.page-sub`,`What Archie can do, in plain language.`)),e(`div.page-actions`,e(`button.btn`,{onclick:u},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Catalogue`),e(`p.card-sub`,`Project, shared, and user-global skills`)),i),r)),d()}async function u(){try{a=(await h.skills())?.skills||[],c=null}catch(e){a=[],c=String(e.message||e)}d()}function d(){if(c)return n(r,s(`Cannot reach archied`,c));if(!a.length)return n(r,s(`No skills discovered yet`,`Skills live as SKILL.md files under project, shared, or user-global .agents/skills// directories. Add one and refresh to make it available.`));let e=a.filter(e=>f(e,o));if(!e.length)return n(r,s(`No skills match`,`Nothing found for "${o}".`));n(r,...e.map(p))}function f(e,t){return!t||`${e.name} ${e.description}`.toLowerCase().includes(t)}function p(t){return e(`div.card.skill-card`,e(`div.card-head`,e(`h3.card-title`,t.name||`Untitled skill`),t.workflow&&e(`span.pill.pill-info`,t.workflow)),e(`p.skill-desc`,t.description||`No description provided.`),e(`div.skill-source`,t.source||`Unknown source`))}return t}var re={bootstrap:`Bootstrap`,implement:`Implement`,tdd:`TDD`,feasibility:`Feasibility check`};function W(e){return re[e]?re[e]:e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown`}function G(e,t){return t?Math.round(e/t*100):0}function K(t,n=`ok`){return e(`div.wf-bar`,e(`div.wf-bar-fill.wf-bar-${n}`,{style:`width:${Math.min(100,Math.max(0,t))}%`}))}function ie(e){if(!e)return`—`;if(e<1e3)return`${e} ms`;let t=e/1e3;return t<60?`${t.toFixed(1)} s`:`${(t/60).toFixed(1)} min`}function ae(){let t=e(`div`),r=e(`div`),i=e(`div`),a=e(`div`);o(),c();function o(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Workflows`),e(`p.page-sub`,`Run outcomes and spend per workflow, and where stages get stuck.`)),e(`div.page-actions`,e(`button.btn`,{onclick:c},`Refresh`))),a,r,i)}async function c(){try{let e=await h.workflows();l(e?.definitions||[]),u(e?.workflows||[],e?.definitions||[]),d(e?.stages||[])}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(i)}}function l(t){if(!t.length){n(a);return}let r=e(`input`,{placeholder:`Identity`,required:!0}),i=e(`input`,{placeholder:`owner/repository`,required:!0}),o=e(`select`,{required:!0},...t.filter(e=>e.enabled).map(t=>e(`option`,{value:t.id},W(t.name||t.id)))),s=e(`input`,{placeholder:`Short task title`,required:!0}),c=e(`textarea`,{placeholder:`Instructions for the work`,required:!0,rows:3}),l=e(`p.card-sub`),u=e(`button.btn`,{type:`submit`},`Start work`),d=e(`form.wf-form`,{onsubmit:async e=>{e.preventDefault(),u.disabled=!0;try{let e=await h.workRequest({identity:r.value,repository:i.value,workflow:o.value,title:s.value,instructions:c.value});l.textContent=`Queued task #${e.task_id}.`,d.reset()}catch(e){l.textContent=String(e.message||e)}finally{u.disabled=!1}}},r,i,o,s,c,u,l);n(a,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Start work`),e(`p.card-sub`,`This enters Archie’s normal admitted task queue.`))),d))}function u(t,i){let a=new Map(t.map(e=>[e.workflow,e])),o=i.map(e=>({...e,...a.get(e.id)||{workflow:e.id,runs:0,merged:0}}));if(!o.length){n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`))),s(`No workflow runs yet`,`Stats appear here once a task has run through a workflow.`)));return}n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`),e(`p.card-sub`,`Success rate is merged tasks over all runs`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Origin`,`Runs`,`Success rate`,`Avg tokens`,`Avg steps`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>{let n=G(t.merged,t.runs);return e(`tr`,e(`td.strong`,W(t.workflow)),e(`td.mono`,t.origin||`registry`),e(`td`,`${t.runs} run${t.runs===1?``:`s`}`),e(`td`,e(`div.wf-rate`,`${n}%`,e(`span.wf-rate-sub`,`${t.merged} of ${t.runs} merged`)),K(n,n>=50?`ok`:`warn`)),e(`td.mono`,t.avg_tokens?t.avg_tokens.toLocaleString():`—`),e(`td.mono`,t.avg_steps?t.avg_steps.toFixed(1):`—`))}))))))}function d(t){if(!t.length){n(i,e(`div.card.wf-stage-card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per stage`))),s(`No stage data yet`,`Stage timing and failures appear here once workflows have run.`)));return}let r=Math.max(...t.map(e=>e.avg_ms||0),1),a=[...t].sort((e,t)=>(t.avg_ms||0)-(e.avg_ms||0)),o=[...t].filter(e=>e.errors>0).sort((e,t)=>t.errors-e.errors);n(i,e(`div.grid.grid-2.wf-stage-card`,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Slowest stages`),e(`p.card-sub`,`Average duration, this workflow's stages`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Runs`,`Avg duration`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(t=>e(`tr`,e(`td`,W(t.workflow)),e(`td.strong`,t.stage),e(`td`,`${t.runs}`),e(`td`,e(`div.wf-rate`,ie(t.avg_ms)),K(G(t.avg_ms,r),`info`)))))))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Most failures`),e(`p.card-sub`,`Stages that error out, over their runs`))),o.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Failures`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>e(`tr`,e(`td`,W(t.workflow)),e(`td.strong`,t.stage),e(`td`,e(`div.wf-rate`,`${t.errors} of ${t.runs}`),K(G(t.errors,t.runs),`danger`))))))):s(`No failures recorded`,`Every stage has completed cleanly so far.`))))}return t}function oe(){let t=e(`div`),i=e(`div.grid.grid-2`);a(),o();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Channels`),e(`p.page-sub`,`The conversational front-ends Archie can be reached through.`)),e(`div.page-actions`,e(`button.btn`,{onclick:o},`Refresh`))),i)}async function o(){try{c((await h.channels())?.channels||[])}catch(e){n(i,s(`Cannot reach archied`,String(e.message||e)))}}function c(e){if(!e.length){n(i,s(`No channels configured`,`Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.`));return}n(i,...e.map(l))}function l(t){return e(`div.card.channel-card`,e(`div.card-head`,e(`h3.card-title`,t.name),r(t.state||(t.configured?`configured`:`stopped`),se(t.state,t.configured))),e(`p.channel-desc`,t.description),e(`p.channel-detail`,t.detail),t.reload_supported?e(`button.btn`,{onclick:async e=>{e.currentTarget.disabled=!0;try{await h.channelReload(t.id||t.name.toLowerCase()),await o()}catch{e.currentTarget.disabled=!1}}},`Reload`):e(`p.channel-detail`,`Reload requires a daemon restart for this adapter.`))}return t}function se(e,t){return e===`running`?`ok`:e===`failed`||e===`degraded`?`warn`:`idle`}function ce(e){return e==null||e===``?`—`:String(e)}function q(t,n,r){let i=ce(n),a=e(`span.kv-label`,t),o=e(`span.kv-value.mono${i===`—`?`.is-empty`:``}`,{title:i},i);if(!r?.key)return e(`div.kv`,a,o);let s=r.locked?.[r.key];if(s)return e(`div.kv.is-locked`,a,o,e(`span.kv-note`,s));let c=r.overridden?.includes(r.key),l=e(`button.kv-btn`,{type:`button`,title:`Edit ${t}`},`Edit`),u=c?e(`button.kv-btn`,{type:`button`,title:`Discard the dashboard value and fall back to the config file`},`Reset`):null,d=e(`div.kv-actions`,c&&e(`span.kv-flag`,{title:`Set from the dashboard; this shadows the value in the config file`},`overridden`),l,u),f=e(`div.kv`,a,o,d);return l.addEventListener(`click`,()=>de(f,t,r,[a,o,d])),u?.addEventListener(`click`,()=>le(f,u,r)),f}function le(e,t,n){let{key:r,onSaved:i}=n;t.disabled=!0,h.configReset(r).then(()=>i?.()).catch(n=>{t.disabled=!1,ue(e,String(n.message||n))})}function ue(t,n){let r=t.querySelector?.(`.kv-note`);r||(r=e(`span.kv-note.is-error`),t.appendChild(r)),r.classList.add(`is-error`),r.textContent=n}function de(t,r,i,a){let{key:o,type:s,raw:c,onSaved:l}=i,u=s===`bool`?e(`select.kv-input`,e(`option`,{value:`true`,selected:c===!0},`true`),e(`option`,{value:`false`,selected:c===!1},`false`)):e(`input.kv-input`,{type:`text`,value:String(c??``)}),d=e(`button.kv-save`,{type:`button`},`Save`),f=e(`button.kv-cancel`,{type:`button`},`Cancel`),p=e(`span.kv-note.is-error`);n(t,e(`span.kv-label`,r),u,e(`div.kv-actions`,d,f),p),u.focus?.(),u.select?.();let m=()=>n(t,...a);f.addEventListener(`click`,m),u.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.preventDefault?.(),d.click()),e.key===`Escape`&&m()}),d.addEventListener(`click`,async()=>{let e=fe(s,u.value);if(e.error){p.textContent=e.error;return}d.disabled=!0;try{await h.configUpdate({[o]:e.value}),l?.()}catch(e){p.textContent=String(e.message||e),d.disabled=!1}})}function fe(e,t){switch(e){case`int`:{let e=parseInt(t,10);return Number.isNaN(e)?{error:`Enter a whole number`}:{value:e}}case`bool`:return{value:t===`true`};default:return{value:t}}}var pe={ok:`OK`,update_available:`Update available`,drift:`Drift`,unknown:`Unknown`},me={ok:`ok`,update_available:`info`,drift:`danger`,unknown:`idle`};function he(t){return t.length?ge(`How each component is deployed, and whether what's running matches what's installed. Hover a row for the exact versions compared.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Component`,`Install type`,`Running`,`Latest available`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,{title:[`Installed claim: ${t.installed_claim||`unknown`}`,`Running: ${t.running_version||`not observed`}`,t.reference?`Reference: ${t.reference}`:null].filter(Boolean).join(` +`)},e(`td.strong`,t.label||t.id),e(`td.mono`,t.install_type||`—`),e(`td.mono`,t.running_version||`—`),e(`td.mono`,t.latest_available||`—`),e(`td`,r(pe[t.status]||t.status,me[t.status]||`idle`)))))))):ge(`How each component is deployed, and whether what's running matches what's installed.`,s(`No components reported`,`The configured update-check command returned nothing.`))}function ge(t,...n){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Update status`),e(`p.card-sub`,t))),...n)}function _e(){let t=e(`div.cfg-page`),r=e(`div`),i=e(`div`);a(),o(),c();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Configuration`),e(`p.page-sub`,`What archied is actually running with right now.`)),e(`div.page-actions`,e(`button.btn`,{onclick:()=>{o(),c()}},`Refresh`))),i,r)}async function o(){try{l(await h.config(),o)}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t))))}}async function c(){try{let e=await h.version();n(i,he(e?.components||[]))}catch(t){if(t?.status===501){n(i);return}n(i,e(`div.card`,s(`Update status unavailable`,String(t.message||t))))}}function l(t,i){if(!t||Object.keys(t).length===0){n(r,e(`div.card`,s(`No configuration loaded`,`archied is running without a config file wired into the dashboard, so there is nothing to show.`)));return}let a={locked:t.locked||{},overridden:t.overridden||[],onSaved:i},o=[t.reload?.overlay_unavailable&&e(`div.card.cfg-notice`,e(`p`,`The runtime config overlay is not in effect: ${t.reload.overlay_unavailable}`)),t.reload?.last_error&&e(`div.card.cfg-notice`,e(`p`,`The last config reload failed; the running config is unchanged: ${t.reload.last_error}`))];n(r,...o,ye(t.identity,a),be(t.repositories),Se(t.models,t.providers),we(t.budgets,a),Te(t.storage,t.containers,a),De(t.web,a),ve(t.provenance))}return t}function ve(t){return t?.length?J(`Configuration sources`,`Applied from top to bottom; later entries take precedence over earlier ones.`,e(`div.kv-list`,...t.map(e=>q(`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,e.path)))):J(`Configuration sources`,`The files that supplied the running configuration.`,s(`Source provenance is unavailable.`))}function J(t,n,...r){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t),e(`p.card-sub`,n))),...r)}function ye(t,n){return t?J(`Identity`,`Who Archie is on the forge, and how it addresses commits and comments.`,e(`div.kv-list`,q(`Bot account`,t.bot_user,{key:`bot_user`,type:`string`,raw:t.bot_user,...n}),q(`Commit author email`,t.bot_email,{key:`bot_email`,type:`string`,raw:t.bot_email,...n}),q(`Pickup label`,t.label,{key:`label`,type:`string`,raw:t.label,...n}),q(`Forge type`,t.forge_type,{key:`forge.type`,type:`string`,raw:t.forge_type,...n}),q(`Forge host`,t.forge_host,{key:`forge.host`,type:`string`,raw:t.forge_host,...n}),q(`Max diff size (lines)`,t.diff_cap_lines||`Unlimited`,{key:`diff_cap_lines`,type:`int`,raw:t.diff_cap_lines,...n}))):J(`Identity`,`Who Archie is on the forge.`,s(`Not available`))}function be(t){return t?.length?J(`Repositories`,`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repository`,`Base branch`,`Ecosystem`,`Quality gate`,`Protected paths`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,e(`td.strong`,`${t.owner}/${t.name}`),e(`td.mono`,t.base),e(`td`,t.ecosystem||`go`),e(`td.mono`,xe(t.gate)),e(`td.mono`,t.protect?.length?t.protect.join(`, `):`—`))))))):J(`Repositories`,`The repositories Archie polls for work.`,s(`No repositories configured`,`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`))}function xe(e){return e?.length?e.map(e=>e.join(` `)).join(` → `):`—`}function Se(t,n){let i=Object.entries(t||{}),a=Object.entries(n||{}),o=i.length?e(`div.kv-list`,...i.map(([e,t])=>q(Ce(e),t))):s(`No model roles configured`,`Assign a model to at least one role (e.g. "builder") in [models].`),c=a.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Provider`,`Class`,`Base URL`,`API key env var`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(([t,n])=>e(`tr`,e(`td.strong`,t),e(`td`,n.class),e(`td.mono`,n.base_url||`default`),e(`td.mono`,n.api_key_env||`—`),e(`td`,n.configured?r(`configured`,`ok`):r(`missing credentials`,`warn`))))))):s(`No providers configured`,`Add a [providers.] entry so a model role above has something to run on.`);return J(`Models & providers`,`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,e(`h3.cfg-subhead`,`Model roles`),o,e(`h3.cfg-subhead`,`Providers`),c)}function Ce(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function we(t,n){return t?J(`Budgets`,`The limits every autonomous stage runs under, so a stuck task cannot run forever.`,e(`div.kv-list`,q(`Max steps`,t.max_steps||`Unlimited`,{key:`budgets.max_steps`,type:`int`,raw:t.max_steps,...n}),q(`Wall clock`,t.wall_clock,{key:`budgets.wall_clock`,type:`string`,raw:t.wall_clock,...n}),q(`Max gate failures before parking`,t.gate_max_failures||`Unlimited`,{key:`budgets.gate_max_failures`,type:`int`,raw:t.gate_max_failures,...n}))):J(`Budgets`,`Limits on every agent stage.`,s(`Not available`))}function Te(t,n,r){let i=[];return t&&i.push(e(`h3.cfg-subhead`,`Paths`),e(`div.kv-list`,q(`Work directory`,t.work_dir,{key:`work_dir`,type:`string`,...r}),q(`State path prefix`,t.db_path,{key:`db_path`,type:`string`,...r}),q(`Shared skills directory`,t.skills_dir||`None (uses the work directory)`,{key:`skills_dir`,type:`string`,raw:t.skills_dir,...r}),q(`Daemon plugin directory`,t.plugin_dir||`None`,{key:`plugin_dir`,type:`string`,raw:t.plugin_dir,...r}),q(`Secret engine plugin directory`,t.secret_engine_dir||`None (built-in engines only)`,{key:`secret_engine_dir`,type:`string`,raw:t.secret_engine_dir,...r}))),n&&i.push(e(`h3.cfg-subhead`,`Sandboxed containers`),e(`div.kv-list`,q(`Agent image`,n.image||`Not set`,{key:`containers.image`,type:`string`,raw:n.image,...r}),q(`Max concurrent tasks`,n.max_concurrency||`Unlimited`,{key:`containers.max_concurrency`,type:`int`,raw:n.max_concurrency,...r}),q(`Container max lifetime`,n.max_uptime,{key:`containers.max_uptime`,type:`string`,raw:n.max_uptime,...r}),q(`Persistent volume retention`,n.volume_ttl,{key:`containers.volume_ttl`,type:`string`,raw:n.volume_ttl,...r}),q(`How images are refreshed`,Ee(n.pull_policy),{key:`containers.pull_policy`,type:`string`,raw:n.pull_policy,...r}),q(`Docker network`,n.network||`Auto-detected`,{key:`containers.network`,type:`string`,raw:n.network,...r}))),i.length||i.push(s(`Not available`)),J(`Storage & sandboxing`,`Where archied keeps its state, and how it isolates task execution.`,...i)}function Ee(e){return e===`always`?`Always pull the latest image before running`:`Only pull when the image is missing locally`}function De(t,n){return t?J(`Dashboard`,`This dashboard's own listen address.`,e(`div.kv-list`,q(`Listen address`,t.listen===`off`?`Disabled`:t.listen,{key:`web.listen`,type:`string`,raw:t.listen===`off`?``:t.listen,...n}))):J(`Dashboard`,`This dashboard's own listen address.`,s(`Not available`))}var Oe=[{value:``,label:`All levels`},{value:`ERROR`,label:`Errors`},{value:`WARN,ERROR`,label:`Warnings and errors`},{value:`INFO,WARN,ERROR`,label:`Info and above`},{value:`DEBUG`,label:`Debug only`}];function ke(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function Ae(){let t=e(`div`),i=e(`div.log-list`),a=r(`connecting`,`idle`),o=e(`span.log-meta`),c={level:``,component:``,q:``},l=!1,u=[],d=[],f=new Map,p=!1,m=e(`select.log-select`,{onchange:e=>x({level:e.target.value})},...Oe.map(t=>e(`option`,{value:t.value},t.label))),g=e(`select.log-select`,{onchange:e=>x({component:e.target.value})}),v=e(`input.log-search`,{type:`search`,placeholder:`Search messages and fields…`,oninput:Ie(e=>x({q:e.target.value}),250)}),y=e(`button.btn`,{onclick:S},`Pause`);C();let b=_(e=>E(e),e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,b),w();function x(e){c={...c,...e},w()}function S(){l=!l,y.textContent=l?`Resume`:`Pause`,y.classList.toggle(`btn-primary`,l)}function C(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Logs`),e(`p.page-sub`,`What Archie has been doing, newest last.`)),e(`div.page-actions`,y,e(`button.btn`,{onclick:w},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div.log-filters`,m,g,v),e(`div.log-status`,o,a)),i))}async function w(){o.textContent=`Refreshing…`;try{let e=await h.logs({level:c.level,component:c.component,q:c.q,limit:500});T(e.components||[]),p=!!e.disabled,o.textContent=e.disabled?`Durable history unavailable; live daemon logs continue.`:e.truncated?`showing the most recent matches from ${e.file}`:e.file||``,d=e.entries||[],D()}catch(e){n(i,s(`Cannot read logs`,String(e.message||e)))}}function T(t){if(Fe(t,u))return;u=t;let r=c.component;n(g,e(`option`,{value:``},`All components`),...t.map(t=>e(`option`,{value:t},t))),g.value=r}function E(e){if(l)return;let t=e;O(t)&&(f.set(je(t),t),t.fields?.component&&T([...u,t.fields.component]),D())}function D(){let e=new Map;for(let t of d)e.set(je(t),t);for(let[t,n]of f)e.set(t,n);let t=[...e.values()].filter(O).slice(-1e3);if(!t.length){n(i,s(p?`Durable history unavailable`:`Nothing matches`,p?`Live daemon logs will appear here while this page is open.`:`Try a wider level or clear the search.`));return}n(i,...t.map(Me)),i.scrollTop=i.scrollHeight}function O(e){if(c.level&&!c.level.split(`,`).includes((e.level||``).toUpperCase())||c.component&&e.fields?.component!==c.component)return!1;if(c.q){let t=c.q.toLowerCase();if(!`${e.message||e.msg||``} ${JSON.stringify(e.fields||{})}`.toLowerCase().includes(t))return!1}return!0}return t}function je(e){return`${e.time||``}|${e.level||``}|${e.message||e.msg||``}|${JSON.stringify(e.fields||{})}`}function Me(t){let n=t.fields||{};return e(`div.log-row.log-${ke(t.level)}`,e(`span.log-time.mono`,Pe(t.time)),e(`span.log-level`,(t.level||`info`).toUpperCase()),e(`span.log-body`,e(`span.log-msg`,t.message||t.msg||``),...Object.entries(n).map(([t,n])=>e(`span.log-field`,e(`span.log-field-key`,t),String(Ne(n))))))}function Ne(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function Pe(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function Fe(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Ie(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}}function Le(t,{expanded:n,onToggle:i}){let o=e(`tr.capture-row`,{tabindex:`0`,"aria-expanded":String(n),onclick:i,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i(e))}},e(`td.mono`,t.source||`(unknown)`),e(`td`,{title:t.received_at||``},a(t.received_at)),e(`td`,r(`Unbound`,`idle`)),e(`td.mono`,t.content_type||`—`),e(`td`,e(`button.btn.btn-small`,{type:`button`},n?`Hide`:`View`)));return n?[o,Re(t)]:[o]}function Re(t){return e(`tr.capture-detail-row`,e(`td`,{colspan:5},e(`div.capture-detail`,e(`div.capture-detail-section`,e(`div.capture-detail-title`,`Payload`),ze(t.body)),e(`div.capture-detail-section`,e(`div.capture-detail-title`,`Headers`),ze(t.headers)))))}function ze(t){return t?e(`pre.capture-payload`,Be(t)):e(`div.capture-empty`,`(empty)`)}function Be(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function Ve(){let t=e(`div`),i=e(`div.card`),a=r(`connecting`,`idle`),o=[],c=null,l=null,u=!0;p(),f();let d=g(e=>{e.kind===`capture`&&f()},e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,d);async function f(){try{let e=await h.captures(100);u=e.enabled!==!1,o=e.captures||[],l=null}catch(e){l=String(e.message||e)}m()}function p(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Event inspector`),e(`p.page-sub`,`Real inbound payloads archie has captured, most recent first.`)),e(`div.page-actions`,a,e(`button.btn`,{onclick:f},`Refresh`))),i),m()}function m(){if(l){n(i,s(`Cannot reach archied`,l));return}if(!u){n(i,s(`Capture is not configured`,`This deployment has no capture storage wired up.`));return}if(!o.length){n(i,s(`No captures yet`,`Point a webhook at /webhooks/capture/ and it will show up here.`));return}n(i,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Source`,`Received`,`Binding`,`Content type`,``].map(t=>e(`th`,t)))),e(`tbody`,...o.flatMap(e=>Le(e,{expanded:c===e.id,onToggle:()=>{c=c===e.id?null:e.id,m()}}))))))}return t}var He=[`string`,`number`,`bool`,`object`,`array`,`any`];function Ue(e){if(e==null)return`any`;if(Array.isArray(e))return`array`;switch(typeof e){case`string`:return`string`;case`number`:return`number`;case`boolean`:return`bool`;case`object`:return`object`;default:return`any`}}function We(e,t){return e?`${e}.${t}`:t}function Ge(e,t){return`${e}[${t}]`}function Ke(t,{path:n=``,name:r=``,onPick:i}={}){return typeof t==`object`&&t?e(`ul.mapping-tree-list`,...(Array.isArray(t)?t.map((e,t)=>[String(t),e,Ge(n,t)]):Object.entries(t).map(([e,t])=>[e,t,We(n,e)])).map(([t,n,r])=>e(`li.mapping-tree-item`,e(`span.mapping-tree-key`,{onclick:e=>{e.stopPropagation(),i?.({path:r,type:Ue(n),name:t})}},t),Ke(n,{path:r,name:t,onPick:i})))):e(`span.mapping-tree-value`,{onclick:e=>{e.stopPropagation(),i?.({path:n,type:Ue(t),name:r})}},JSON.stringify(t))}function qe(t,{preview:n,onRemove:r,onNameChange:i,onTypeChange:a,onRequiredChange:o}={}){if(!t.length)return e(`div.mapping-empty-fields`,`Click a value in the payload to bind a field.`);let s=new Map((n?.failures||[]).map(e=>[e.field_name,e]));return e(`table.table.mapping-fields-table`,e(`thead`,e(`tr`,...[`Field name`,`Path`,`Type`,`Required`,`Preview`,``].map(t=>e(`th`,t)))),e(`tbody`,...t.map((t,c)=>e(`tr`,e(`td`,e(`input.mapping-input`,{value:t.name,oninput:e=>i?.(c,e.target.value)})),e(`td.mono`,t.path),e(`td`,e(`select.mapping-select`,{onchange:e=>a?.(c,e.target.value)},...He.map(n=>e(`option`,{value:n,selected:n===t.type},n)))),e(`td`,e(`input`,{type:`checkbox`,checked:t.required,onchange:e=>o?.(c,e.target.checked)})),e(`td`,Je(t,n,s)),e(`td`,e(`button.btn.btn-small`,{type:`button`,onclick:()=>r?.(c)},`Remove`))))))}function Je(e,t,n){if(!t)return r(`not previewed`,`idle`);let i=n.get(e.name);return i?r(i.reason,`danger`):Object.prototype.hasOwnProperty.call(t.values||{},e.name)?r(JSON.stringify(t.values[e.name]),`ok`):r(`skipped (optional)`,`idle`)}function Ye(t,{onEdit:n,onDelete:r}){return e(`tr`,e(`td`,t.name),e(`td.mono`,t.source_hint||`—`),e(`td`,String(t.fields?.length??0)),e(`td`,e(`button.btn.btn-small`,{type:`button`,onclick:()=>n?.(t)},`Edit`),e(`button.btn.btn-small`,{type:`button`,onclick:()=>r?.(t)},`Delete`)))}function Xe(){let t=e(`div`),r=[],i=[],a=null,o=null;C(),c();async function c(){try{let[e,t]=await Promise.all([h.mappings(),h.captures(100)]);r=e.mappings||[],i=t.captures||[],a=null}catch(e){a=String(e.message||e)}C()}function l(){o={id:null,name:``,sourceHint:``,fields:[],captureId:null,payload:null,payloadError:null,preview:null,actionError:null},C()}function u(e){o={id:e.id,name:e.name,sourceHint:e.source_hint||``,fields:(e.fields||[]).map(e=>({...e})),captureId:null,payload:null,payloadError:null,preview:null,actionError:null},C()}async function d(e){if(window.confirm(`Delete mapping "${e.name}"?`))try{await h.mappingDelete(e.id),await c()}catch(e){a=String(e.message||e),C()}}function f(e){let t=i.find(t=>String(t.id)===String(e));if(o.captureId=t?t.id:null,o.preview=null,!t)o.payload=null,o.payloadError=null;else try{o.payload=JSON.parse(t.body),o.payloadError=null}catch{o.payload=null,o.payloadError=`This capture's body is not valid JSON, so its fields cannot be mapped by path.`}C()}function p({path:e,type:t,name:n}){let r=new Set(o.fields.map(e=>e.name)),i=n||`field`,a=1;for(;r.has(i);)i=`${n||`field`}_${++a}`;o.fields.push({name:i,path:e,type:t,required:!0}),o.preview=null,C()}function m(e){o.fields.splice(e,1),o.preview=null,C()}function g(e,t){Object.assign(o.fields[e],t),o.preview=null,C()}let _=(e,t)=>g(e,{name:t}),v=(e,t)=>g(e,{type:t}),y=(e,t)=>g(e,{required:t});async function b(){if(!o.captureId){o.actionError=`Pick a captured event to preview against.`,C();return}try{o.preview=await h.mappingPreview(o.captureId,o.fields),o.actionError=null}catch(e){o.actionError=String(e.message||e)}C()}async function x(){let e={name:o.name,source_hint:o.sourceHint,fields:o.fields};try{o.id?await h.mappingUpdate(o.id,e):await h.mappingCreate(e),o=null,await c()}catch(e){o.actionError=String(e.message||e),C()}}function S(){o=null,C()}function C(){n(t,o?T():w())}function w(){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Field mappings`),e(`p.page-sub`,`Bind named fields to JSON paths from a real captured event, ready for a playbook binding.`)),e(`div.page-actions`,e(`button.btn.btn-primary`,{type:`button`,onclick:l},`New mapping`))),a?s(`Cannot reach archied`,a):r.length?e(`div.card`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Name`,`Source hint`,`Fields`,``].map(t=>e(`th`,t)))),e(`tbody`,...r.map(e=>Ye(e,{onEdit:u,onDelete:d})))))):s(`No mappings yet`,`Create one from a captured event to reuse fields in a future playbook binding.`))}function T(){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,o.id?`Edit mapping`:`New mapping`)),e(`div.page-actions`,e(`button.btn`,{type:`button`,onclick:S},`Cancel`),e(`button.btn.btn-primary`,{type:`button`,onclick:x},`Save`))),o.actionError?e(`div.mapping-error`,o.actionError):null,e(`div.card.mapping-form`,e(`label.mapping-form-row`,`Name`,e(`input.mapping-input`,{value:o.name,oninput:e=>{o.name=e.target.value}})),e(`label.mapping-form-row`,`Source hint (organisational only)`,e(`input.mapping-input`,{value:o.sourceHint,oninput:e=>{o.sourceHint=e.target.value}})),e(`label.mapping-form-row`,`Preview against captured event`,e(`select.mapping-select`,{onchange:e=>f(e.target.value)},e(`option`,{value:``},`— pick a captured event —`),...i.map(t=>e(`option`,{value:t.id,selected:String(o.captureId)===String(t.id)},`${t.source||`(unknown)`} — ${t.received_at||``}`))))),e(`div.card.mapping-fields`,e(`div.mapping-section-title`,`Bound fields`),qe(o.fields,{preview:o.preview,onRemove:m,onNameChange:_,onTypeChange:v,onRequiredChange:y}),e(`button.btn`,{type:`button`,onclick:b},`Preview`)),e(`div.card.mapping-payload`,e(`div.mapping-section-title`,`Payload — click a value to bind it`),o.payloadError?e(`div.mapping-error`,o.payloadError):o.payload===null?e(`div.mapping-empty-fields`,`Pick a captured event above to see its payload.`):Ke(o.payload,{onPick:p})))}return t}function Ze(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Memory`),e(`p.page-sub`,`What Archie can recall between conversations, and the tools it uses to do it.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},l(`refresh`,{size:15}),`Refresh`))),r)}async function a(){n(r,e(`div.card`,e(`div.mem-loading`,`Loading…`)));try{let t=await h.memory();if(!t.enabled||!t.providers?.length){n(r,e(`div.card`,s(`Memory is not configured`,`Without a provider, Archie starts every conversation with no recollection of earlier ones.`)));return}n(r,e(`div.grid.grid-2`,...t.providers.map(Qe)))}catch(t){n(r,e(`div.card`,s(`Cannot read memory providers`,String(t.message||t))))}}return t}function Qe(t){let n=t.tools||[];return e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t.name||`provider`),e(`p.card-sub`,$e(t.role))),t.available?r(`ready`,`ok`):r(`unavailable`,`danger`)),!t.available&&e(`p.mem-warning`,`Configured but not usable right now — a required binary or connection may be missing.`),n.length?e(`ul.mem-tools`,...n.map(t=>e(`li.mem-tool`,e(`div.mem-tool-name.mono`,t.name),t.description&&e(`div.mem-tool-desc`,t.description)))):e(`p.mem-warning`,`This provider exposes no tools, so the agent cannot use it.`))}function $e(e){return e===`external`?`Added by you — an external store Archie was given`:`Built in — always available to Archie`}var et=`
ARCHIE WORKSPACE

Chat

@@ -72,10 +72,10 @@
-`;function Ze(){let e=document.createElement(`template`);e.innerHTML=Xe.trim();let t=e.content.firstElementChild,n={};for(let e of t.querySelectorAll(`[data-chat-ref]`))n[e.dataset.chatRef]=e;return{root:t,refs:n}}function Y(t){let n=document.createDocumentFragment(),r=/(~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^\s)]+\)|\*[^*]+\*|_[^_]+_)/g,i=0;for(let a of t.matchAll(r)){a.index>i&&n.append(document.createTextNode(t.slice(i,a.index)));let r=a[0];if(r.startsWith(`~~`))n.append(e(`del`,r.slice(2,-2)));else if(r.startsWith(`**`)||r.startsWith(`__`))n.append(e(`strong`,r.slice(2,-2)));else if(r.startsWith("`"))n.append(e(`code`,r.slice(1,-1)));else if(r.startsWith(`[`)){let t=r.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);n.append(e(`a`,{href:t[2],target:`_blank`,rel:`noreferrer`},t[1]))}else n.append(e(`em`,r.slice(1,-1)));i=a.index+r.length}return ii&&n.append(document.createTextNode(t.slice(i,a.index)));let r=a[0];if(r.startsWith(`~~`))n.append(e(`del`,r.slice(2,-2)));else if(r.startsWith(`**`)||r.startsWith(`__`))n.append(e(`strong`,r.slice(2,-2)));else if(r.startsWith("`"))n.append(e(`code`,r.slice(1,-1)));else if(r.startsWith(`[`)){let t=r.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);n.append(e(`a`,{href:t[2],target:`_blank`,rel:`noreferrer`},t[1]))}else n.append(e(`em`,r.slice(1,-1)));i=a.index+r.length}return i{i.length&&(n.append(e(`p`,Y(i.join(` `)))),i=[])},c=()=>{a&&n.append(a),a=null};for(let t=0;te(`td`,Y(t)))));n.append(e(`table`,e(`thead`,e(`tr`,...u.map(t=>e(`th`,Y(t))))),a));continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),n.append(e(`h${f[1].length}`,Y(f[2])));continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let t=m?`ol`:`ul`;(!a||a.tagName.toLowerCase()!==t)&&(c(),a=e(t)),a.append(e(`li`,Y((p||m)[1])));continue}if(l.startsWith(`>`)){s(),c(),n.append(e(`blockquote`,Y(l.replace(/^>\s?/,``))));continue}i.push(l)}return s(),c(),o&&n.append(e(`pre`,e(`code`,o.join(` -`)))),n}function $e(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function et(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}function tt(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function nt(){return e(`div.chat-bubble-row.assistant`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,`Archie`),e(`div.chat-tools`),e(`div.chat-bubble-text`)))}function rt(t){let n=t.from??t.From??``,r=t.text??t.Text??``,i=n!==`web`;return e(`div.chat-bubble-row.${i?`assistant`:`user`}`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,i?`Archie`:`You`),i?it(t,r):e(`div.chat-bubble-text`,r)))}function it(t,n){let r=t.tool_calls||t.ToolCalls||[],i=[e(`div.chat-tools`)];for(let t of r){let n=!!(t.err||t.Err);i[0].append(e(`div.chat-tool`+(n?`.failed`:``),e(`span.chat-tool-icon`,`🔧`),e(`span.chat-tool-name`,t.name||t.Name||`tool`),e(`span.chat-tool-summary`,t.err||t.Err||t.output||t.Output||`done`)))}return i.push(Qe(n)),i}function X(e,t){let n=Qe(t);return typeof e?.replaceWith==`function`?e.replaceWith(n):e?.parentNode&&e.parentNode.replaceChild(n,e),n}function at(t,n){let r=n?.tool??``;if(!t||!r)return null;let i=n.parameters??``,a=n.text??``,o=e(`div.chat-tool`,e(`span.chat-tool-icon`,`🔧`),e(`span.chat-tool-name`,r),i&&e(`code.chat-tool-parameters`,i),e(`span.chat-tool-summary`,a));return n.failed&&(o.className=`chat-tool failed`),ot(t).append(o),o}function ot(t){let n=t.querySelector(`.chat-tools`);if(n)return n;let r=e(`div.chat-tools`);return t.append(r),r}var st=`archie.web.chat.channel`;function Z(){let e=localStorage.getItem(st);return e||(e=u(),localStorage.setItem(st,e)),e}function ct(e){return{text:e,sourceID:u()}}function lt(e){return{...e}}function ut(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?lt(e.turn):ct(r),isRetry:n}}function dt({sessionList:t,sessionTools:n,sessions:r,currentSession:i,onSelect:a}){if(t.replaceChildren(),n.hidden=!i,!r.length){t.append(e(`div.chat-empty`,`Your conversations will appear here.`));return}for(let n of r)t.append(e(`button.chat-session`,{class:i===n.session_id?`active`:``,onclick:()=>a(n.session_id)},e(`strong`,tt(n)),e(`span`,new Date(n.last_active_at).toLocaleString())))}function ft(t,n,r){t.persona.replaceChildren(e(`option`,{value:``},`Personality`));for(let r of n.personas||[])t.persona.append(e(`option`,{value:r},r));t.persona.value=n.active_persona||``;let i=n.providers||[];t.provider.hidden=i.length===0,t.provider.replaceChildren(e(`option`,{value:``},`Provider`));for(let n of i)t.provider.append(e(`option`,{value:n},n));t.provider.value=n.active_provider||i[0]||``,pt(t,n,t.provider.value),t.restart.hidden=!n.restart_available,t.dangerousPanel.hidden=!n.dangerous_available,n.dangerous_available&&r()}function pt(t,n,r){let i=n.models_by_provider||{},a=r&&i[r]?i[r]:n.models||[];t.model.replaceChildren(e(`option`,{value:``},`Model`));for(let n of a)t.model.append(e(`option`,{value:n},n));t.model.value=n.active_model||``}function mt(t,n){let r=(n||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e),i=e(`div.chat-command-list`);r.length||i.append(e(`span`,`Send a message to begin.`));for(let t of r)i.append(e(`div.chat-command-item`,e(`code`,t.usage||t.command),e(`span`,t.description||``)));return t.replaceChildren(e(`summary`,`Available commands (${r.length})`),i),r}function ht(t,n,{onDefer:r,onInstall:i}){t.replaceChildren();let a=n?.snapshot||null,o=n?.available||[];if(!o.length){t.append(e(`span`,a?.deferred?`Update deferred.`:`Archie is up to date.`));return}t.append(e(`div`,e(`strong`,`Update available`),e(`span`,o.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `))),e(`div.chat-update-actions`,e(`button.btn`,{onclick:r},`Defer`),n.can_install?e(`button.btn.btn-primary`,{onclick:i},`Install update`):null))}function gt(t,n,{onRequest:r,onDecision:i}){t.replaceChildren();let a=n?.checkpoints||[],o=n?.pending||[],s=e(`select.chat-select`,{"aria-label":`Checkpoint`},e(`option`,{value:``},`Select checkpoint`),...a.map(t=>e(`option`,{value:t.Number??t.number},`${t.Number??t.number} — ${t.Label??t.label??`checkpoint`}`))),c=e(`input.chat-dangerous-input`,{placeholder:`Process name or id`,"aria-label":`Process name or id`}),l=(e,t)=>()=>r(e,String(t.value||t).trim()),u=(t,n,r)=>e(`button.btn`,{onclick:()=>i(t,n)},r),d=o.length?o.map(t=>e(`div.chat-dangerous-pending`,e(`span`,t.description),e(`div.chat-update-actions`,u(t.id,`approve`,`Approve`),u(t.id,`permanent`,`Approve for 24h`),u(t.id,`deny`,`Deny`)))):[e(`span.chat-hint`,`No pending dangerous actions.`)];t.append(e(`div.chat-dangerous-head`,e(`strong`,`Dangerous actions`),e(`span.chat-hint`,`Every action requires approval.`)),e(`div.chat-dangerous-controls`,e(`div`,s,e(`button.btn`,{onclick:l(`rollback`,s)},`Request rollback`)),e(`div`,c,e(`button.btn`,{onclick:l(`stop`,c)},`Request stop`))),e(`div.chat-dangerous-pending-list`,...d))}function _t(e){return e?.status===501?null:`Could not check for updates.`}function vt(){let{root:t,refs:n}=Ze(),{sessionList:r,transcript:i,composer:a,send:o,stop:s,status:c,persona:l,provider:u,model:d,restart:f,emptyState:p,updatePanel:m,dangerousPanel:g,commandMenu:_,sessionTools:v,commandHelp:y,checkUpdates:b,newChat:x}=n,S=``,C=[],w=!1,T=null,E=null,D={},O=[],k=[],A=0;f.onclick=()=>{window.confirm(`Reload the Telegram chat adapter?`)&&(a.value=`/restart`,H())},x.onclick=()=>{a.value=`/new`,H()};for(let e of t.querySelectorAll(`[data-chat-prompt]`))e.onclick=()=>{a.value=e.dataset.chatPrompt,a.focus()};function j(e){p.remove(),i.append(rt(e)),i.scrollTop=i.scrollHeight}function M(){let e=a.value.slice(0,a.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);return e?e[1].toLowerCase():null}function N(){_.hidden=!0,k=[],A=0}function P(){let t=M();if(t===null){N();return}if(k=O.filter(e=>`${e.command} ${e.description}`.toLowerCase().includes(t)).slice(0,8),!k.length){N();return}A=Math.min(A,k.length-1),_.replaceChildren(...k.map((t,n)=>e(`button.chat-command-option`,{type:`button`,role:`option`,"aria-selected":String(n===A),onmousedown:e=>e.preventDefault(),onclick:()=>F(n)},e(`code`,t.command),e(`span`,t.description||t.usage||``)))),_.hidden=!1,_.children[A]?.scrollIntoView({block:`nearest`})}function F(e){let t=k[e];if(!t)return;let n=a.value.slice(0,a.selectionStart),r=a.value.slice(a.selectionStart),i=n.search(/(?:^|\s)\/[^\s]*$/),o=i<0?n.length:i+ +(n[i]===` `);a.value=`${n.slice(0,o)}${t.command} ${r}`;let s=o+t.command.length+1;a.setSelectionRange(s,s),N(),a.focus()}async function I(){try{let e=await h.chatUpdate();E=e?.snapshot||null,ht(m,e,{onDefer:async()=>{await h.chatUpdateDefer(E),ht(m,{snapshot:{deferred:!0},available:[]},{onDefer:()=>{},onInstall:()=>{}}),c.textContent=`Update deferred`},onInstall:async()=>{c.textContent=`Installing…`,await h.chatUpdateInstall(E),c.textContent=`Update started`,I()}})}catch(t){let n=_t(t);m.replaceChildren(...n?[e(`span`,n)]:[])}}async function L(){try{gt(g,await h.chatDangerous(),{onRequest:async(e,t)=>{if(t)try{await h.chatDangerousRequest(e,t),c.textContent=`Approval requested`,await L()}catch(e){c.textContent=e.message||`Could not request action`}},onDecision:async(e,t)=>{try{await h.chatDangerousDecision(e,t),c.textContent=t===`deny`?`Action denied`:`Action approved`,await L()}catch(e){c.textContent=e.message||`Approval failed`}}})}catch(t){g.replaceChildren(e(`span.chat-hint`,t.message||`Dangerous actions unavailable`))}}async function R(){let e=await h.chatSessions();C=e.sessions||[],D=e,ft({persona:l,provider:u,model:d,restart:f,dangerousPanel:g},e,L),O=mt(y,e.commands),dt({sessionList:r,sessionTools:v,sessions:C,currentSession:S,onSelect:V}),!S&&C[0]&&await V(C[0].session_id)}async function z(e){if(S)try{c.textContent=`Working…`;let t=await h.chatMessage(Z(),e);t.session_id&&(S=t.session_id),c.textContent=t.reply||`Session updated`,await R(),S&&await V(S),v.open=!1}catch(e){c.textContent=e.message||`Session action failed`}}function B(e,t){let n=window.prompt(t);n?.trim()&&z(`${e} ${n.trim()}`)}async function V(e){S=e,dt({sessionList:r,sessionTools:v,sessions:C,currentSession:S,onSelect:V}),i.replaceChildren(),await h.chatMessage(Z(),`/resume ${e}`),l.value=D.active_personas?.[e]||D.active_persona||``;let[t,n]=await Promise.all([h.chatMessages(e),h.chatTurns(e)]),a=new Map;for(let e of n||[]){let t=e.assistant_message_id||e.AssistantMessageID;t&&a.set(t,e)}for(let e of t){let t=e.message_id||e.MessageID,n=a.get(t);j(n?{...e,tool_calls:n.tool_calls||n.ToolCalls||[]}:e)}i.children.length||i.append(p)}async function H(t=null){let{text:n,turn:r,isRetry:l}=ut(t,a.value);if(!n||w)return;N(),w=!0,o.disabled=!0,s.disabled=!1,a.disabled=!0,c.textContent=l?`Retrying…`:`Thinking…`,l||(j({from:`web`,text:n}),a.value=``);let u=l?t.replyBubble:nt();l||i.append(u),u.querySelector(`.chat-retry`)?.remove(),u.querySelector(`.chat-tools`)?.replaceChildren();let d=u.querySelector(`.chat-bubble-text`),f=``,p=!1,m=!1,h;try{T=new AbortController,h=setTimeout(()=>{m=!0,T.abort()},12e4);let e=await fetch(`/api/chat/stream`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`text/event-stream`},body:JSON.stringify({channel_id:Z(),source_id:r.sourceID,text:r.text}),signal:T.signal});if(!e.ok)throw Error(await e.text()||`${e.status} ${e.statusText}`);let t=e.body.getReader(),n=new TextDecoder,i=``;for(;;){let{value:e,done:r}=await t.read();i+=n.decode(e||new Uint8Array,{stream:!r});let a=i.split(` +`)))),o=null):o=[];continue}if(o){o.push(l);continue}let u=rt(l),d=t+1e(`td`,Y(t)))));n.append(e(`table`,e(`thead`,e(`tr`,...u.map(t=>e(`th`,Y(t))))),a));continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),n.append(e(`h${f[1].length}`,Y(f[2])));continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let t=m?`ol`:`ul`;(!a||a.tagName.toLowerCase()!==t)&&(c(),a=e(t)),a.append(e(`li`,Y((p||m)[1])));continue}if(l.startsWith(`>`)){s(),c(),n.append(e(`blockquote`,Y(l.replace(/^>\s?/,``))));continue}i.push(l)}return s(),c(),o&&n.append(e(`pre`,e(`code`,o.join(` +`)))),n}function rt(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function it(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}function at(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function ot(){return e(`div.chat-bubble-row.assistant`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,`Archie`),e(`div.chat-tools`),e(`div.chat-bubble-text`)))}function st(t){let n=t.from??t.From??``,r=t.text??t.Text??``,i=n!==`web`;return e(`div.chat-bubble-row.${i?`assistant`:`user`}`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,i?`Archie`:`You`),i?ct(t,r):e(`div.chat-bubble-text`,r)))}function ct(t,n){let r=t.tool_calls||t.ToolCalls||[],i=[e(`div.chat-tools`)];for(let t of r){let n=!!(t.err||t.Err);i[0].append(e(`div.chat-tool`+(n?`.failed`:``),e(`span.chat-tool-icon`,`🔧`),e(`span.chat-tool-name`,t.name||t.Name||`tool`),e(`span.chat-tool-summary`,t.summary||t.Summary||t.err||t.Err||`done`)))}return i.push(nt(n)),i}function X(e,t){let n=nt(t);return typeof e?.replaceWith==`function`?e.replaceWith(n):e?.parentNode&&e.parentNode.replaceChild(n,e),n}function lt(t,n){let r=n?.tool??``;if(!t||!r)return null;let i=n.parameters??``,a=n.text??``,o=e(`div.chat-tool`,e(`span.chat-tool-icon`,`🔧`),e(`span.chat-tool-name`,r),i&&e(`code.chat-tool-parameters`,i),e(`span.chat-tool-summary`,a));return n.failed&&(o.className=`chat-tool failed`),ut(t).append(o),o}function ut(t){let n=t.querySelector(`.chat-tools`);if(n)return n;let r=e(`div.chat-tools`);return t.append(r),r}var dt=`archie.web.chat.channel`;function Z(){let e=localStorage.getItem(dt);return e||(e=u(),localStorage.setItem(dt,e)),e}function ft(e){return{text:e,sourceID:u()}}function pt(e){return{...e}}function mt(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?pt(e.turn):ft(r),isRetry:n}}function ht({sessionList:t,sessionTools:n,sessions:r,currentSession:i,onSelect:a}){if(t.replaceChildren(),n.hidden=!i,!r.length){t.append(e(`div.chat-empty`,`Your conversations will appear here.`));return}for(let n of r)t.append(e(`button.chat-session`,{class:i===n.session_id?`active`:``,onclick:()=>a(n.session_id)},e(`strong`,at(n)),e(`span`,new Date(n.last_active_at).toLocaleString())))}function gt(t,n,r){t.persona.replaceChildren(e(`option`,{value:``},`Personality`));for(let r of n.personas||[])t.persona.append(e(`option`,{value:r},r));t.persona.value=n.active_persona||``;let i=n.providers||[];t.provider.hidden=i.length===0,t.provider.replaceChildren(e(`option`,{value:``},`Provider`));for(let n of i)t.provider.append(e(`option`,{value:n},n));t.provider.value=n.active_provider||i[0]||``,_t(t,n,t.provider.value),t.restart.hidden=!n.restart_available,t.dangerousPanel.hidden=!n.dangerous_available,n.dangerous_available&&r()}function _t(t,n,r){let i=n.models_by_provider||{},a=r&&i[r]?i[r]:n.models||[];t.model.replaceChildren(e(`option`,{value:``},`Model`));for(let n of a)t.model.append(e(`option`,{value:n},n));t.model.value=n.active_model||``}function vt(t,n){let r=(n||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e),i=e(`div.chat-command-list`);r.length||i.append(e(`span`,`Send a message to begin.`));for(let t of r)i.append(e(`div.chat-command-item`,e(`code`,t.usage||t.command),e(`span`,t.description||``)));return t.replaceChildren(e(`summary`,`Available commands (${r.length})`),i),r}function yt(t,n,{onDefer:r,onInstall:i}){t.replaceChildren();let a=n?.snapshot||null,o=n?.available||[];if(!o.length){t.append(e(`span`,a?.deferred?`Update deferred.`:`Archie is up to date.`));return}t.append(e(`div`,e(`strong`,`Update available`),e(`span`,o.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `))),e(`div.chat-update-actions`,e(`button.btn`,{onclick:r},`Defer`),n.can_install?e(`button.btn.btn-primary`,{onclick:i},`Install update`):null))}function bt(t,n,{onRequest:r,onDecision:i}){t.replaceChildren();let a=n?.checkpoints||[],o=n?.pending||[],s=e(`select.chat-select`,{"aria-label":`Checkpoint`},e(`option`,{value:``},`Select checkpoint`),...a.map(t=>e(`option`,{value:t.Number??t.number},`${t.Number??t.number} — ${t.Label??t.label??`checkpoint`}`))),c=e(`input.chat-dangerous-input`,{placeholder:`Process name or id`,"aria-label":`Process name or id`}),l=(e,t)=>()=>r(e,String(t.value||t).trim()),u=(t,n,r)=>e(`button.btn`,{onclick:()=>i(t,n)},r),d=o.length?o.map(t=>e(`div.chat-dangerous-pending`,e(`span`,t.description),e(`div.chat-update-actions`,u(t.id,`approve`,`Approve`),u(t.id,`permanent`,`Approve for 24h`),u(t.id,`deny`,`Deny`)))):[e(`span.chat-hint`,`No pending dangerous actions.`)];t.append(e(`div.chat-dangerous-head`,e(`strong`,`Dangerous actions`),e(`span.chat-hint`,`Every action requires approval.`)),e(`div.chat-dangerous-controls`,e(`div`,s,e(`button.btn`,{onclick:l(`rollback`,s)},`Request rollback`)),e(`div`,c,e(`button.btn`,{onclick:l(`stop`,c)},`Request stop`))),e(`div.chat-dangerous-pending-list`,...d))}function xt(e){return e?.status===501?null:`Could not check for updates.`}function St(){let{root:t,refs:n}=tt(),{sessionList:r,transcript:i,composer:a,send:o,stop:s,status:c,persona:l,provider:u,model:d,restart:f,emptyState:p,updatePanel:m,dangerousPanel:g,commandMenu:_,sessionTools:v,commandHelp:y,checkUpdates:b,newChat:x}=n,S=``,C=[],w=!1,T=null,E=null,D={},O=[],k=[],A=0;f.onclick=()=>{window.confirm(`Reload the Telegram chat adapter?`)&&(a.value=`/restart`,H())},x.onclick=()=>{a.value=`/new`,H()};for(let e of t.querySelectorAll(`[data-chat-prompt]`))e.onclick=()=>{a.value=e.dataset.chatPrompt,a.focus()};function j(e){p.remove(),i.append(st(e)),i.scrollTop=i.scrollHeight}function M(){let e=a.value.slice(0,a.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);return e?e[1].toLowerCase():null}function N(){_.hidden=!0,k=[],A=0}function P(){let t=M();if(t===null){N();return}if(k=O.filter(e=>`${e.command} ${e.description}`.toLowerCase().includes(t)).slice(0,8),!k.length){N();return}A=Math.min(A,k.length-1),_.replaceChildren(...k.map((t,n)=>e(`button.chat-command-option`,{type:`button`,role:`option`,"aria-selected":String(n===A),onmousedown:e=>e.preventDefault(),onclick:()=>F(n)},e(`code`,t.command),e(`span`,t.description||t.usage||``)))),_.hidden=!1,_.children[A]?.scrollIntoView({block:`nearest`})}function F(e){let t=k[e];if(!t)return;let n=a.value.slice(0,a.selectionStart),r=a.value.slice(a.selectionStart),i=n.search(/(?:^|\s)\/[^\s]*$/),o=i<0?n.length:i+ +(n[i]===` `);a.value=`${n.slice(0,o)}${t.command} ${r}`;let s=o+t.command.length+1;a.setSelectionRange(s,s),N(),a.focus()}async function I(){try{let e=await h.chatUpdate();E=e?.snapshot||null,yt(m,e,{onDefer:async()=>{await h.chatUpdateDefer(E),yt(m,{snapshot:{deferred:!0},available:[]},{onDefer:()=>{},onInstall:()=>{}}),c.textContent=`Update deferred`},onInstall:async()=>{c.textContent=`Installing…`;let e=await h.chatUpdateInstall(E);E=null,yt(m,{snapshot:{},available:[]},{onDefer:()=>{},onInstall:()=>{}}),c.textContent=e?.result?.restart_requested?`Update installed; restart queued`:`Update complete`}})}catch(t){let n=xt(t);m.replaceChildren(...n?[e(`span`,n)]:[])}}async function L(){try{bt(g,await h.chatDangerous(),{onRequest:async(e,t)=>{if(t)try{await h.chatDangerousRequest(e,t),c.textContent=`Approval requested`,await L()}catch(e){c.textContent=e.message||`Could not request action`}},onDecision:async(e,t)=>{try{await h.chatDangerousDecision(e,t),c.textContent=t===`deny`?`Action denied`:`Action approved`,await L()}catch(e){c.textContent=e.message||`Approval failed`}}})}catch(t){g.replaceChildren(e(`span.chat-hint`,t.message||`Dangerous actions unavailable`))}}async function R(){let e=await h.chatSessions();C=e.sessions||[],D=e,gt({persona:l,provider:u,model:d,restart:f,dangerousPanel:g},e,L),O=vt(y,e.commands),ht({sessionList:r,sessionTools:v,sessions:C,currentSession:S,onSelect:V}),!S&&C[0]&&await V(C[0].session_id)}async function z(e){if(S)try{c.textContent=`Working…`;let t=await h.chatMessage(Z(),e);t.session_id&&(S=t.session_id),c.textContent=t.reply||`Session updated`,await R(),S&&await V(S),v.open=!1}catch(e){c.textContent=e.message||`Session action failed`}}function B(e,t){let n=window.prompt(t);n?.trim()&&z(`${e} ${n.trim()}`)}async function V(e){S=e,ht({sessionList:r,sessionTools:v,sessions:C,currentSession:S,onSelect:V}),i.replaceChildren(),await h.chatMessage(Z(),`/resume ${e}`),l.value=D.active_personas?.[e]||D.active_persona||``;let[t,n]=await Promise.all([h.chatMessages(e),h.chatTurns(e)]),a=new Map;for(let e of n||[]){let t=e.assistant_message_id||e.AssistantMessageID;t&&a.set(t,e)}for(let e of t){let t=e.message_id||e.MessageID,n=a.get(t);j(n?{...e,tool_calls:n.tool_calls||n.ToolCalls||[]}:e)}i.children.length||i.append(p)}async function H(t=null){let{text:n,turn:r,isRetry:l}=mt(t,a.value);if(!n||w)return;N(),w=!0,o.disabled=!0,s.disabled=!1,a.disabled=!0,c.textContent=l?`Retrying…`:`Thinking…`,l||(j({from:`web`,text:n}),a.value=``);let u=l?t.replyBubble:ot();l||i.append(u),u.querySelector(`.chat-retry`)?.remove(),u.querySelector(`.chat-tools`)?.replaceChildren();let d=u.querySelector(`.chat-bubble-text`),f=``,p=!1,m=!1,h;try{T=new AbortController,h=setTimeout(()=>{m=!0,T.abort()},12e4);let e=await fetch(`/api/chat/stream`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`text/event-stream`},body:JSON.stringify({channel_id:Z(),source_id:r.sourceID,text:r.text}),signal:T.signal});if(!e.ok)throw Error(await e.text()||`${e.status} ${e.statusText}`);let t=e.body.getReader(),n=new TextDecoder,i=``;for(;;){let{value:e,done:r}=await t.read();i+=n.decode(e||new Uint8Array,{stream:!r});let a=i.split(` `);i=a.pop()||``;for(let e of a){let t=e.split(` -`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(S=n.session_id),n.type===`delta`&&(f+=n.text,d=X(d,f)),n.type===`tool`&&at(u.querySelector(`.chat-bubble`)??u,n),n.type===`done`&&(p=!0,f||(f=n.text,d=X(d,f))),n.type===`error`)throw Error(n.text)}if(r)break}if(!p)throw Error(`chat stream ended before completion`);d.isConnected&&(d=X(d,f)),c.textContent=`Ready`,await R()}catch(t){if(t.name===`AbortError`&&!m)d=X(d,`Turn stopped.`),c.textContent=`Stopped`;else{d=X(d,`Unable to complete that turn: ${t.message||t}`);let n=lt(r),i=e(`button.btn.chat-retry`,{type:`button`,onclick:()=>H({turn:n,replyBubble:u})},`Retry`);u.append(i),c.textContent=`Error — retry available`}}finally{clearTimeout(h),T=null,w=!1,o.disabled=!1,s.disabled=!0,a.disabled=!1,a.focus()}}o.onclick=()=>H(),s.onclick=()=>{let e=S;c.textContent=`Stopping…`,e&&h.chatCancel(e).catch(()=>{}),T?.abort()},a.oninput=P,a.onkeydown=e=>{if(!_.hidden&&k.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&k.some(e=>e.command===a.value.trim())){e.preventDefault(),N(),H();return}if(e.key===`ArrowDown`){e.preventDefault(),A=(A+1)%k.length,P();return}if(e.key===`ArrowUp`){e.preventDefault(),A=(A+k.length-1)%k.length,P();return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),F(A);return}if(e.key===`Escape`){e.preventDefault(),N();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),H())},l.onchange=async()=>{!S||!l.value||(await h.chatPersona(S,l.value),D.active_personas={...D.active_personas||{},[S]:l.value},c.textContent=`Personality: ${l.value}`)},u.onchange=async()=>{pt({model:d},D,u.value),u.value&&await U(`/model --provider ${u.value}`)},d.onchange=async()=>{d.value&&await U(`/model ${d.value}`)};async function U(e){try{let t=await h.chatMessage(Z(),e);c.textContent=t.reply||`Model updated`,await R()}catch(e){c.textContent=`Model update failed: ${e.message||e}`}}b.onclick=I;let W={retry:()=>z(`/retry`),undo:()=>z(`/undo`),title:()=>B(`/title`,`Session title`),branch:()=>B(`/branch`,`Branch name (optional)`),compress:()=>z(`/compress --preview`)};for(let e of t.querySelectorAll(`[data-chat-action]`))e.onclick=W[e.dataset.chatAction];return R().catch(e=>{c.textContent=e.message||`Chat unavailable`}),I(),t}var Q=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:D},{path:`/chat`,label:`Chat`,icon:`chat`,view:vt},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:V},{path:`/logs`,label:`Logs`,icon:`logs`,view:Ee},{path:`/captures`,label:`Event inspector`,icon:`captures`,view:Le},{path:`/mappings`,label:`Field mappings`,icon:`mappings`,view:Ke},{path:`/skills`,label:`Skills`,icon:`skills`,view:H},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:te},{path:`/memory`,label:`Memory`,icon:`memory`,view:qe},{path:`/channels`,label:`Channels`,icon:`channels`,view:ne},{path:`/settings`,label:`Configuration`,icon:`settings`,view:pe}],yt=`archie.theme`;function bt(e){document.documentElement.dataset.theme=e,localStorage.setItem(yt,e)}function $(){return localStorage.getItem(yt)||`dark`}function xt(t){let r=new Map,i=e(`nav.nav`,...[null].flatMap(()=>[...Q.map(n=>{let i=e(`a.nav-item`,{href:`#${n.path}`,onclick:e=>{n.soon?e.preventDefault():t(n.path)},"aria-disabled":n.soon||void 0,title:n.soon?`Coming soon`:void 0},l(n.icon),e(`span.nav-label`,n.label),n.soon&&e(`span.nav-soon`,`soon`));return r.set(n.path,i),i})])),a=e(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{bt($()===`dark`?`light`:`dark`),n(a,l($()===`dark`?`moon`:`sun`))}});n(a,l($()===`dark`?`moon`:`sun`));let o,s=()=>{o?.classList.remove(`is-open`),c.setAttribute(`aria-expanded`,`false`)},c=e(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{o.classList.add(`is-open`),c.setAttribute(`aria-expanded`,`true`),u.focus()}},l(`search`,{size:15})),u=e(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:e=>{if(e.key===`Escape`){s(),e.target.blur();return}if(e.key!==`Enter`)return;let n=e.target.value.trim().toLowerCase(),r=Q.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(t(r.path),e.target.value=``,e.target.blur(),s())}});return o=e(`div.topbar-search`,e(`span.topbar-search-icon`,{"aria-hidden":`true`},l(`search`,{size:15})),c,u),{node:e(`header.topbar`,e(`div.brand`,e(`span.brand-mark`,`A`),`Archie`),i,e(`div.topbar-end`,o,e(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},l(`help`)),a,e(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,n]of r)t===e?n.setAttribute(`aria-current`,`page`):n.removeAttribute(`aria-current`)}}}function St(){bt($());let t=e(`main.main`),r=xt(i);n(document.getElementById(`app`),e(`div.shell`,r.node,t));function i(e){location.hash===`#${e}`?a(e):location.hash=e}function a(e){t.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[i,a=``]=e.split(`?`,2),o=Q.find(e=>e.path===i)||Q[0];r.highlight(o.path),n(t,o.view?o.view(new URLSearchParams(a)):Ct(o))}window.addEventListener(`hashchange`,()=>a(location.hash.slice(1)||`/`)),a(location.hash.slice(1)||`/`)}function Ct(t){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,t.label))),e(`div.card`,e(`div.empty`,e(`div.empty-title`,`${t.label} is not built yet`),e(`div`,`This section is next up. Nothing is broken.`))))}St(); \ No newline at end of file +`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(S=n.session_id),n.type===`delta`&&(f+=n.text,d=X(d,f)),n.type===`tool`&<(u.querySelector(`.chat-bubble`)??u,n),n.type===`done`&&(p=!0,f||(f=n.text,d=X(d,f))),n.type===`error`)throw Error(n.text)}if(r)break}if(!p)throw Error(`chat stream ended before completion`);d.isConnected&&(d=X(d,f)),c.textContent=`Ready`,await R()}catch(t){if(t.name===`AbortError`&&!m)d=X(d,`Turn stopped.`),c.textContent=`Stopped`;else{d=X(d,`Unable to complete that turn: ${t.message||t}`);let n=pt(r),i=e(`button.btn.chat-retry`,{type:`button`,onclick:()=>H({turn:n,replyBubble:u})},`Retry`);u.append(i),c.textContent=`Error — retry available`}}finally{clearTimeout(h),T=null,w=!1,o.disabled=!1,s.disabled=!0,a.disabled=!1,a.focus()}}o.onclick=()=>H(),s.onclick=()=>{let e=S;c.textContent=`Stopping…`,e&&h.chatCancel(e).catch(()=>{}),T?.abort()},a.oninput=P,a.onkeydown=e=>{if(!_.hidden&&k.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&k.some(e=>e.command===a.value.trim())){e.preventDefault(),N(),H();return}if(e.key===`ArrowDown`){e.preventDefault(),A=(A+1)%k.length,P();return}if(e.key===`ArrowUp`){e.preventDefault(),A=(A+k.length-1)%k.length,P();return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),F(A);return}if(e.key===`Escape`){e.preventDefault(),N();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),H())},l.onchange=async()=>{!S||!l.value||(await h.chatPersona(S,l.value),D.active_personas={...D.active_personas||{},[S]:l.value},c.textContent=`Personality: ${l.value}`)},u.onchange=async()=>{_t({model:d},D,u.value),u.value&&await U(`/model --provider ${u.value}`)},d.onchange=async()=>{d.value&&await U(`/model ${d.value}`)};async function U(e){try{let t=await h.chatMessage(Z(),e);c.textContent=t.reply||`Model updated`,await R()}catch(e){c.textContent=`Model update failed: ${e.message||e}`}}b.onclick=I;let ee={retry:()=>z(`/retry`),undo:()=>z(`/undo`),title:()=>B(`/title`,`Session title`),branch:()=>B(`/branch`,`Branch name (optional)`),compress:()=>z(`/compress --preview`)};for(let e of t.querySelectorAll(`[data-chat-action]`))e.onclick=ee[e.dataset.chatAction];return R().catch(e=>{c.textContent=e.message||`Chat unavailable`}),I(),t}var Q=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:D},{path:`/chat`,label:`Chat`,icon:`chat`,view:St},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:te},{path:`/logs`,label:`Logs`,icon:`logs`,view:Ae},{path:`/captures`,label:`Event inspector`,icon:`captures`,view:Ve},{path:`/mappings`,label:`Field mappings`,icon:`mappings`,view:Xe},{path:`/skills`,label:`Skills`,icon:`skills`,view:ne},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:ae},{path:`/memory`,label:`Memory`,icon:`memory`,view:Ze},{path:`/channels`,label:`Channels`,icon:`channels`,view:oe},{path:`/settings`,label:`Configuration`,icon:`settings`,view:_e}],Ct=`archie.theme`;function wt(e){document.documentElement.dataset.theme=e,localStorage.setItem(Ct,e)}function $(){return localStorage.getItem(Ct)||`dark`}function Tt(t){let r=new Map,i=e(`nav.nav`,...[null].flatMap(()=>[...Q.map(n=>{let i=e(`a.nav-item`,{href:`#${n.path}`,onclick:e=>{n.soon?e.preventDefault():t(n.path)},"aria-disabled":n.soon||void 0,title:n.soon?`Coming soon`:void 0},l(n.icon),e(`span.nav-label`,n.label),n.soon&&e(`span.nav-soon`,`soon`));return r.set(n.path,i),i})])),a=e(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{wt($()===`dark`?`light`:`dark`),n(a,l($()===`dark`?`moon`:`sun`))}});n(a,l($()===`dark`?`moon`:`sun`));let o,s=()=>{o?.classList.remove(`is-open`),c.setAttribute(`aria-expanded`,`false`)},c=e(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{o.classList.add(`is-open`),c.setAttribute(`aria-expanded`,`true`),u.focus()}},l(`search`,{size:15})),u=e(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:e=>{if(e.key===`Escape`){s(),e.target.blur();return}if(e.key!==`Enter`)return;let n=e.target.value.trim().toLowerCase(),r=Q.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(t(r.path),e.target.value=``,e.target.blur(),s())}});return o=e(`div.topbar-search`,e(`span.topbar-search-icon`,{"aria-hidden":`true`},l(`search`,{size:15})),c,u),{node:e(`header.topbar`,e(`div.brand`,e(`span.brand-mark`,`A`),`Archie`),i,e(`div.topbar-end`,o,e(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},l(`help`)),a,e(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,n]of r)t===e?n.setAttribute(`aria-current`,`page`):n.removeAttribute(`aria-current`)}}}function Et(){wt($());let t=e(`main.main`),r=Tt(i);n(document.getElementById(`app`),e(`div.shell`,r.node,t));function i(e){location.hash===`#${e}`?a(e):location.hash=e}function a(e){t.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[i,a=``]=e.split(`?`,2),o=Q.find(e=>e.path===i)||Q[0];r.highlight(o.path),n(t,o.view?o.view(new URLSearchParams(a)):Dt(o))}window.addEventListener(`hashchange`,()=>a(location.hash.slice(1)||`/`)),a(location.hash.slice(1)||`/`)}function Dt(t){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,t.label))),e(`div.card`,e(`div.empty`,e(`div.empty-title`,`${t.label} is not built yet`),e(`div`,`This section is next up. Nothing is broken.`))))}Et(); \ No newline at end of file diff --git a/ui/src/tasks/tasks.js b/ui/src/tasks/tasks.js index 6759909a1..487246291 100644 --- a/ui/src/tasks/tasks.js +++ b/ui/src/tasks/tasks.js @@ -4,6 +4,7 @@ import { ago, el, empty, mount, pill, statusKind } from "../base/dom.js"; import { statTile } from "../base/statTile.js"; import { taskRowA11y } from "./task-row.js"; import { initialTaskFilter, taskMatchesStatus } from "./task-filters.js"; +import { describeTimelineEvent } from "./timeline-event.js"; /** * Plain-language status labels. One place, so "waiting_human" only ever @@ -41,7 +42,6 @@ export function tasksPage(params = new URLSearchParams()) { const requestedTask = Number(params.get("task")); let expandedId = Number.isFinite(requestedTask) && requestedTask > 0 ? requestedTask : null; let focusRequestedTask = expandedId !== null; - let forgeHost = ""; const eventCache = new Map(); // Keyed by task id. A single shared string leaked one row's failure into // every other row's action cell. @@ -114,10 +114,7 @@ export function tasksPage(params = new URLSearchParams()) { async function load() { try { - [tasks, forgeHost] = await Promise.all([ - api.tasks(), - api.config().then((cfg) => cfg?.identity?.forge_host || "").catch(() => ""), - ]); + tasks = await api.tasks(); renderSummary(); renderRows(); if (expandedId && tasks.some((task) => String(task.id) === String(expandedId))) { @@ -333,9 +330,9 @@ export function tasksPage(params = new URLSearchParams()) { `Archive the local record for "${t.title || "this task"}"?`, ); case "open_pr": - return taskLink(t, "pulls", t.pr_number, "Open PR"); + return taskLink(t, "pull_request", t.pr_number, "Open PR"); case "open_issue": - return taskLink(t, "issues", t.issue_number, "Open issue"); + return taskLink(t, "issue", t.issue_number, "Open issue"); default: return null; } @@ -360,16 +357,9 @@ export function tasksPage(params = new URLSearchParams()) { } } - // Both forge links derive from the same host so they can never drift apart: - // one place builds the base, both anchors reuse it. - function forgeBase(t) { - if (!forgeHost || !t.owner || !t.repo) return null; - return `${forgeHost.replace(/\/+$/, "")}/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}`; - } - function taskLink(t, kind, number, label) { - const base = forgeBase(t); - if (!base || !number || (kind === "issues" && t.source === "chat")) { + const href = kind === "issue" ? t.issue_url : t.pr_url; + if (!href || !number || (kind === "issue" && t.source === "chat")) { return el( "button.btn.btn-small", { type: "button", disabled: true, title: `${label} is unavailable` }, @@ -379,7 +369,7 @@ export function tasksPage(params = new URLSearchParams()) { return el( "a.btn.btn-small", { - href: `${base}/${kind}/${number}`, + href, target: "_blank", rel: "noreferrer", onclick: (event) => event.stopPropagation(), @@ -389,7 +379,7 @@ export function tasksPage(params = new URLSearchParams()) { } function repoLink(t) { - const base = forgeBase(t); + const base = t.repo_url; if (!base) return null; return el( "a.task-source-link", @@ -405,14 +395,14 @@ export function tasksPage(params = new URLSearchParams()) { } function issueLink(t) { - const base = forgeBase(t); + const href = t.issue_url; // A chat-sourced task has no issue on the forge, but its repo may still // exist -- the repo link stays, the issue link does not. - if (t.source === "chat" || !base || !t.issue_number) return null; + if (t.source === "chat" || !href || !t.issue_number) return null; return el( "a.task-source-link", { - href: `${base}/issues/${t.issue_number}`, + href, target: "_blank", rel: "noreferrer", title: `Open issue #${t.issue_number} on the forge`, @@ -460,13 +450,14 @@ export function tasksPage(params = new URLSearchParams()) { } function timelineEntry(ev) { + const description = describeTimelineEvent(ev); return el( "li.task-timeline-entry", el("span.task-timeline-dot"), el( "div", - el("div.task-timeline-kind", ev.kind || ev.type || "event"), - ev.detail && el("div.task-timeline-detail", ev.detail), + el("div.task-timeline-kind", description.title), + description.detail && el("div.task-timeline-detail", description.detail), el("div.task-timeline-when", ago(ev.at)), ), ); diff --git a/ui/src/tasks/timeline-event.js b/ui/src/tasks/timeline-event.js new file mode 100644 index 000000000..12dc3b354 --- /dev/null +++ b/ui/src/tasks/timeline-event.js @@ -0,0 +1,78 @@ +function words(value) { + return String(value || "event") + .replaceAll("_", " ") + .replace(/\b\w/g, (letter) => letter.toUpperCase()); +} + +function duration(milliseconds) { + const ms = Number(milliseconds); + if (!Number.isFinite(ms) || ms < 0) return ""; + if (ms < 1000) return `${Math.round(ms)} ms`; + const seconds = ms / 1000; + // Under 60s: 1 dp when seconds < 10, 0 dp otherwise (40.6 s, but 41 s). + if (seconds < 60) return `${seconds.toFixed(seconds < 10 ? 1 : 0)} s`; + const roundedSeconds = Math.round(seconds); + const minutes = Math.floor(roundedSeconds / 60); + const remSec = roundedSeconds % 60; + if (minutes < 60) return remSec === 0 ? `${minutes} min` : `${minutes} min ${remSec} s`; + const hours = Math.floor(minutes / 60); + const remMin = minutes - hours * 60; + return remMin === 0 ? `${hours} h` : `${hours} h ${remMin} min`; +} + +function count(value) { + const n = Number(value); + // Render only for positive counts; zero is treated as "no metric + // reported" so a partially-populated agent_finish (pre-v0.1.24 events, + // or a failed run whose result is the zero Result) does not appear as + // "0 prompt · 0 completion · 0 cached". + if (!Number.isFinite(n) || n <= 0) return ""; + return n.toLocaleString("en-US"); +} + +export function describeTimelineEvent(ev = {}) { + const data = ev.data || {}; + const stage = ev.stage || "unknown stage"; + const workflow = ev.workflow ? `${ev.workflow} workflow` : ""; + + if (ev.kind === "stage_start") { + return { title: `Started stage: ${stage}`, detail: workflow }; + } + if (ev.kind === "stage_finish") { + const elapsed = duration(data.duration_ms); + const context = [workflow, elapsed && `ran for ${elapsed}`].filter(Boolean).join(" · "); + return { + title: data.interrupted ? `Stage interrupted: ${stage}` : data.error ? `Stage failed: ${stage}` : `Finished stage: ${stage}`, + detail: [context, data.error].filter(Boolean).join(" — "), + }; + } + if (ev.kind === "task_retried") { + const count = Number(data.retry_count); + const attempt = Number.isFinite(count) && count > 0 ? `Retry ${count}` : "Retry requested"; + const previous = [data.previous_stage && `after ${data.previous_stage}`, data.previous_reason] + .filter(Boolean) + .join(": "); + return { title: attempt, detail: previous || ev.detail || "" }; + } + if (ev.kind === "agent_finish") { + const iterations = count(data.iterations); + const total = count(data.tokens); + const prompt = count(data.prompt_tokens); + const completion = count(data.completion_tokens); + const cached = count(data.cached_tokens); + const usage = [ + iterations && `${iterations} iterations`, + total && `${total} tokens`, + prompt && `${prompt} prompt`, + completion && `${completion} completion`, + cached && `${cached} cached`, + data.model, + ].filter(Boolean); + return { + title: `Agent ${data.status || "finished"}: ${stage}`, + detail: usage.join(" · ") || ev.detail || "", + }; + } + + return { title: words(ev.kind || ev.type), detail: ev.detail || "" }; +} diff --git a/ui/test/timeline-event.test.js b/ui/test/timeline-event.test.js new file mode 100644 index 000000000..c136c672e --- /dev/null +++ b/ui/test/timeline-event.test.js @@ -0,0 +1,107 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { describeTimelineEvent } from "../src/tasks/timeline-event.js"; + +test("stage events name the stage, workflow, duration, and failure", () => { + assert.deepEqual( + describeTimelineEvent({ + kind: "stage_finish", + workflow: "implement", + stage: "baseline", + data: { duration_ms: 1250, error: "task check failed" }, + }), + { + title: "Stage failed: baseline", + detail: "implement workflow · ran for 1.3 s — task check failed", + }, + ); +}); + +test("retry events explain which failure caused the retry", () => { + assert.deepEqual( + describeTimelineEvent({ + kind: "task_retried", + detail: "retried via the dashboard", + data: { retry_count: 2, previous_stage: "baseline", previous_reason: "task check failed" }, + }), + { title: "Retry 2", detail: "after baseline: task check failed" }, + ); +}); + +test("agent events expose stage efficiency and cache usage", () => { + assert.deepEqual( + describeTimelineEvent({ + kind: "agent_finish", + stage: "analyse", + data: { + status: "passed", + iterations: 7, + tokens: 282066, + prompt_tokens: 280000, + completion_tokens: 2066, + cached_tokens: 240000, + model: "openai/gpt-5.6-luna", + }, + }), + { + title: "Agent passed: analyse", + detail: + "7 iterations · 282,066 tokens · 280,000 prompt · 2,066 completion · 240,000 cached · openai/gpt-5.6-luna", + }, + ); +}); + +test("agent events with zero-valued usage fields omit them entirely", () => { + // Pre-v0.1.24 persisted events lack the breakdown fields, and a + // failed run still publishes agent_finish with the zero Result. Either + // shape must not render "0 prompt · 0 completion · 0 cached". + const result = describeTimelineEvent({ + kind: "agent_finish", + stage: "baseline-fix", + data: { + status: "", + iterations: 0, + tokens: 0, + prompt_tokens: 0, + completion_tokens: 0, + cached_tokens: 0, + model: "openai/gpt-5.6-luna", + }, + }); + assert.equal(result.title, "Agent finished: baseline-fix"); + assert.equal(result.detail.includes("0 "), false, `detail should not mention zero counts: ${result.detail}`); + assert.equal(result.detail, "openai/gpt-5.6-luna"); +}); + +test("stage durations render minutes and hours, not raw seconds", () => { + const r1 = describeTimelineEvent({ kind: "stage_finish", stage: "analyse", data: { duration_ms: 8_500 } }); + assert.equal(r1.detail, "ran for 8.5 s"); + const r2 = describeTimelineEvent({ kind: "stage_finish", stage: "analyse", data: { duration_ms: 40_600 } }); + assert.equal(r2.detail, "ran for 41 s"); + const r3 = describeTimelineEvent({ kind: "stage_finish", stage: "fix", data: { duration_ms: 5 * 60_000 + 12_000 } }); + assert.equal(r3.detail, "ran for 5 min 12 s"); + const r4 = describeTimelineEvent({ kind: "stage_finish", stage: "tdd", data: { duration_ms: 1 * 3_600_000 } }); + assert.equal(r4.detail, "ran for 1 h"); + const r5 = describeTimelineEvent({ kind: "stage_finish", stage: "analyse", data: { duration_ms: 90_000 } }); + assert.equal(r5.detail, "ran for 1 min 30 s"); + const r6 = describeTimelineEvent({ kind: "stage_finish", stage: "analyse", data: { duration_ms: 3_599_600 } }); + assert.equal(r6.detail, "ran for 1 h"); +}); + +test("cancelled stages are described as interrupted rather than failed", () => { + assert.deepEqual( + describeTimelineEvent({ + kind: "stage_finish", + stage: "implement", + data: { error: "context canceled", interrupted: true }, + }), + { title: "Stage interrupted: implement", detail: "context canceled" }, + ); +}); + +test("unknown event kinds become readable labels", () => { + assert.deepEqual(describeTimelineEvent({ kind: "human_approved", detail: "approved via dashboard" }), { + title: "Human Approved", + detail: "approved via dashboard", + }); +});