diff --git a/docs/prds/state-store-contract.md b/docs/prds/state-store-contract.md index 31298c0d9..b9ec56e97 100644 --- a/docs/prds/state-store-contract.md +++ b/docs/prds/state-store-contract.md @@ -259,8 +259,9 @@ Methods are named after the store methods so the mapping is unambiguous. `workfl | Dispatch | `ArmedBindingsForSource`, `RecordDispatch`, `ListUndispatchedCaptures` | | BindingTaskCreator | `EnqueueBindingTask` | | Config snapshot | `PutConfigSnapshot`, `GetConfigSnapshot` | +| Task log | `ReadTaskLog`, `StreamTaskLogContent` | -That is **42 unique RPCs** across one service (the `TaskEvents.Close` method is dropped). +That is **44 unique RPCs** across one service (the `TaskEvents.Close` method is dropped). `Close()` is **excluded** from the wire (it is server lifecycle, not a client call) — see §11. The config-snapshot pair was added by `archie-core-ymut` (see @@ -271,6 +272,19 @@ neither. `ConfigSnapshot.document` is opaque to this contract — the store neit validates it, and `schema` names the projection so a reader can refuse a shape it does not understand. +The task-log pair was added by `archie-core-iaqx` (see `docs/prds/ui-service-boundary.md`'s +route inventory). It is the one surface whose payload is not a row: the store service reads +them out of the state directory it owns with `internal/logging`'s own reader, so the wire +carries `logging.Entry`/`logging.Query` values and neither side restates the JSONL format. +`ReadTaskLog` returns a decoded page and `StreamTaskLogContent` returns the raw bytes +server-streamed, because a log file rotates at 20 MB — past gRPC's 4 MiB unary cap — and the +same reasoning that made `StreamCaptures` supersede `ListCaptures` applies. `found=false` with +no error means the attempt has no log; a service with no reader answers `Unavailable` instead, +and the two answers are load-bearing for the dashboard: only the second is a deployment +condition, and the panel that collapsed them told operators task logging was switched off when +it was not. The Go facade is `storecontract.TaskLogStore` (2 methods), carried by +`*staterpc.Client` alongside the rest. + ### Domain types and `values.go` mapping `values.go` maps proto ⇄ these types. The task model for the **agent** path is the domain-owned @@ -638,7 +652,7 @@ an explicit operator decision. (`workflow.Store` + `workflow.Task`/`Status`/`Source`, per dependency rules #2 and #7); daemon/webui store surfaces stay **producer-owned** in `internal/store`. `store.WorkflowStore` is superseded by `workflow.Store`. -- **One `StateStore` gRPC service** (42 RPCs, grouped by contract) + narrow Go consumer facades +- **One `StateStore` gRPC service** (44 RPCs, grouped by contract) + narrow Go consumer facades (≤8) on `staterpc.Client` — mirrors the single-`ChatService` precedent. - **Domain type relocation** (`Task`/`Status`/`Source` → `internal/domain/workflow`) is a Phase 2 prerequisite, pulled forward from migration-decisions §4 (minimal bound, diff --git a/docs/prds/ui-service-boundary.md b/docs/prds/ui-service-boundary.md index 3cda49dcb..a9b68c716 100644 --- a/docs/prds/ui-service-boundary.md +++ b/docs/prds/ui-service-boundary.md @@ -65,7 +65,8 @@ cutover. | `/api/chat/*` | Gateway `ChatContract` and its versioned client | contract seam exists; DTO and stream parity remain | | `/api/tasks/*`, `/api/workflows`, `/api/setup` | State Store read/action contracts plus an explicit execution/admin action contract | State Store adapter exists; UI-facing narrow surface remains | | `/events` | State Store `EventsSince`, polled by one UI-process pump feeding `Server.Broadcast` | RESOLVED (`archie-core-za9f`): see migration-decisions, "Dashboard live event delivery". No new RPC; replay cursor and drop-recovery are the existing `since` watermark in `sse.go` | -| `/api/logs`, `/api/logs/stream` | daemon diagnostic feed, host-local | unresolved: `logging.Feed` is in-process on the daemon host and has no contract | +| `/api/logs`, `/api/logs/stream` | daemon diagnostic feed, host-local | unresolved: `logging.Feed` is in-process on the daemon host and has no contract. The per-task log routes moved off this row: see `/api/tasks/*` above | +| `/api/tasks/{id}/logs`, `/api/tasks/{id}/logs/download` | State Store task-log read contract (`TaskLogStore`: `ReadTaskLog` + `StreamTaskLogContent`), read by the UI process from the service that owns the state directory | RESOLVED (`archie-core-iaqx`): the UI process composes `TaskLogStore` from its own State Store client and serves the attempt log as JSON (`found` distinguishes "no log for this attempt" from "this process cannot read logs") and as a `Content-Disposition` attachment named `task--attempt-.log`. The daemon's in-process registry is wired as the server-side reader in `internal/app/archied/state_store.go` only (`staterpc.Deps.TaskLogs`), so no process opens another process's log files | | `/api/captures`, `/api/mappings`, `/api/bindings` | State Store contracts, with webhook verification owned by Work Intake/Messaging | RESOLVED (cutover, `archie-core-8cda.5.4`): the UI process composes CaptureStore/MappingStore/BindingStore and mounts the `captureintake.Receiver` from its own State Store client; the daemon's binding-dispatch loop keeps consuming captures from the same store | | `/api/config` (read) | daemon-published `ConfigView` snapshot, read over the State Store contract | RESOLVED (`archie-core-ymut`): see migration-decisions, "Dashboard configuration page" | | `/api/config` (write), `/api/config/reset`, `/api/config/repos/*` | a configuration write contract; the daemon stays the policy owner | DESCOPED for Phase 3 (`archie-core-ymut`), NOT abandoned: 503 in the UI process, SPA hides the controls, editing is config.toml plus reload. Dashboard editing is a tracked feature (`archie-core-1786637498420-327`) and its transport is `archie-core-j28m`; the handlers and their func-field seams on `webui.Server` are kept for it | diff --git a/internal/app/archied/state_store.go b/internal/app/archied/state_store.go index fe4b129f1..d2f2eea3f 100644 --- a/internal/app/archied/state_store.go +++ b/internal/app/archied/state_store.go @@ -125,6 +125,22 @@ func (b *boot) openStateStore(ctx context.Context) error { // degrades that group rather than aborting boot. func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps { deps := staterpc.Deps{Tasks: b.st, Log: b.log, Grants: grants} + // Task logs live in the state directory, which this process owns, and the + // dashboard process owns no such directory -- so this is where a task-log + // read is served from (docs/prds/ui-service-boundary.md). The reader is + // the daemon's own registry, built over the same state-directory + // derivation this process uses for its SQLite file; both resolve from the + // same configured DBPath, so they agree on where archie keeps its state. + // + // The nil check is on the registry, not on the interface it is assigned + // to: a nil *logging.TaskRegistry stored in this field produces a non-nil + // interface holding a nil pointer, which the server's own + // `deps.TaskLogs == nil` guard would not catch. Leaving the field unset is + // what makes the RPC answer Unavailable -- the honest "this process cannot + // read logs" -- instead of depending on nil-receiver behaviour to notice. + if b.taskLogs != nil { + deps.TaskLogs = b.taskLogs + } if cs, ok := b.st.(storecontract.CaptureStore); ok { deps.Captures = cs } diff --git a/internal/app/archied/state_store_test.go b/internal/app/archied/state_store_test.go index 2d922ed30..fede02cf5 100644 --- a/internal/app/archied/state_store_test.go +++ b/internal/app/archied/state_store_test.go @@ -11,7 +11,9 @@ import ( "github.com/samcharles93/archie-core/internal/config" pb "github.com/samcharles93/archie-core/internal/contracts/state/v1" + "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" + "github.com/samcharles93/archie-core/internal/logging" "github.com/samcharles93/archie-core/internal/store" ) @@ -98,6 +100,35 @@ func TestServeStateStoreServesContract(t *testing.T) { } } +// TestStateStoreDepsServeTaskLogs proves the standalone State Store process is +// where a task-log read is served from: the daemon process holds no dashboard +// listener any more, so the service the UI process dials is the only place this +// contract can have a server-side reader, and it must be the daemon's own +// registry over the state directory. +// +// Without this wiring the RPC exists and answers Unavailable for every task, +// which the dashboard reports as "this process cannot read logs" -- honest, but +// still not a working download (archie-core-iaqx). +func TestStateStoreDepsServeTaskLogs(t *testing.T) { + b := newBootstrap() + logs := logging.NewTaskRegistry(filepath.Join(t.TempDir(), "logs", "tasks"), logging.NewFeed(10), logging.TaskSinkOptions{}) + b.taskLogs = logs + + deps := b.stateStoreDeps(&staterpc.TaskGrants{}) + if deps.TaskLogs == nil { + t.Fatal("stateStoreDeps leaves TaskLogs nil; the State Store process is the only server-side reader the dashboard can reach") + } + if deps.TaskLogs != storecontract.TaskLogStore(logs) { + t.Fatalf("TaskLogs = %T, want the daemon's own registry over the state directory", deps.TaskLogs) + } + // A boot without a registry must not fabricate one: an empty reader would + // answer found=false for every attempt, which reads as "the attempt has no + // log" rather than "this process cannot read logs". + if plain := (&boot{}).stateStoreDeps(&staterpc.TaskGrants{}); plain.TaskLogs != nil { + t.Errorf("TaskLogs = %T with no registry on the boot, want nil so the RPC reports unavailability", plain.TaskLogs) + } +} + // TestStateStoreDataSurvivesRestart is the .4.7 restart/recovery check: a // task written by one archie-state-store process must still be there for a // fresh process opening the same archie.db path, proving b.openStateStore diff --git a/internal/app/archieui/compose.go b/internal/app/archieui/compose.go index 47de3e8a6..06e16c9ec 100644 --- a/internal/app/archieui/compose.go +++ b/internal/app/archieui/compose.go @@ -38,12 +38,17 @@ type deps struct { // UpdateRepoField: the configuration owner stays the daemon. The read // crosses as the snapshot ConfigSource renders; the write routes answer // 503 and the page hides their controls (archie-core-ymut). -// - LogFeed, TaskLogs, Events, Channels, ReloadChannel, Curators, Memory, +// - LogFeed, Events, Channels, ReloadChannel, Curators, Memory, // Workflows, WorkRequests, RunningVersions, Chat.Updates, // UpdateReportPath: no contract exists for these yet. // Defining one amends the owning service's contract first // (docs/prds/ui-service-boundary.md:205-207); the route migration is // archie-core-8cda.5.3. +// - TaskLogs: wired below from the store client's TaskLogStore contract. +// Task log files live in the state directory the State Store owns, so this +// process reads one attempt's log over that contract rather than opening +// the file itself -- which would only work on a single host and is exactly +// what the boundary forbids (archie-core-iaqx). // - Captures, CaptureIntake, CaptureMaxEvents: wired below. From the // cutover change (archie-core-8cda.5.4) this process is the only // listener serving POST /webhooks/capture/{source}: the receiver is a @@ -77,10 +82,31 @@ func compose(d deps) *webui.Server { if d.Chat != nil { srv.Chat = &webui.ChatService{Contract: d.Chat} } + // The task-log read crosses the State Store contract: the files live in + // the state directory that process owns, so this one asks for the log + // rather than opening a path (docs/prds/ui-service-boundary.md). Withholding + // it would degrade a page that has an owner, and would leave the dashboard + // claiming task logging was not enabled -- see wireTaskLogs. + wireTaskLogs(d, srv) wireCaptureSurfaces(d, srv) return srv } +// wireTaskLogs attaches the task-log read when the store client carries the +// contract, and logs the absence when it does not: a store without it leaves +// the page reporting that this process cannot read logs, which is true, rather +// than that the attempt has none, which it cannot know. +func wireTaskLogs(d deps, srv *webui.Server) { + logs, ok := d.Store.(storecontract.TaskLogStore) + if !ok { + if d.Store != nil { + d.Log.Warn("task logs unavailable: state store does not implement TaskLogStore") + } + return + } + srv.TaskLogs = logs +} + // wireCaptureSurfaces attaches the capture read and the intake receiver. // Both resolve from d.Store's contracts: CaptureStore backs the inspector's // list and the mapping preview's scan window, BindingDispatcher resolves the diff --git a/internal/app/archieui/compose_test.go b/internal/app/archieui/compose_test.go index 4240197f4..39f9e30dc 100644 --- a/internal/app/archieui/compose_test.go +++ b/internal/app/archieui/compose_test.go @@ -88,7 +88,6 @@ func TestComposeUIServerHoldsNoDaemonState(t *testing.T) { "Memory": srv.Memory, "Channels": srv.Channels, "LogFeed": srv.LogFeed, - "TaskLogs": srv.TaskLogs, "WorkRequests": srv.WorkRequests, } for name, handle := range unwired { @@ -105,6 +104,16 @@ func TestComposeUIServerHoldsNoDaemonState(t *testing.T) { if srv.Mappings == nil || srv.Bindings == nil { t.Error("Mappings/Bindings are unwired; both are State Store contracts the composed client implements") } + // TaskLogs is the same shape as Mappings/Bindings -- the store client + // carries TaskLogStore -- and it is the one that used to answer "task + // logging was not enabled for this run" for every attempt in a deployment + // where logging is unconditional (archie-core-iaqx). + if srv.TaskLogs == nil { + t.Error("TaskLogs is unwired; the State Store client implements TaskLogStore, so leaving it nil degrades a page that has an owner") + } + if _, ok := srv.TaskLogs.(*staterpc.Client); !ok { + t.Errorf("TaskLogs = %T, want the remote *staterpc.Client: the UI process owns no state directory to read a log file from", srv.TaskLogs) + } if srv.UpdateReportPath != "" { t.Error("UpdateReportPath is set; host-local update relay stays with the daemon") } diff --git a/internal/app/archieui/degraded_routes_test.go b/internal/app/archieui/degraded_routes_test.go index b1d3370c8..e3879a2d3 100644 --- a/internal/app/archieui/degraded_routes_test.go +++ b/internal/app/archieui/degraded_routes_test.go @@ -14,6 +14,7 @@ import ( "google.golang.org/grpc" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" + "github.com/samcharles93/archie-core/internal/logging" "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/webui" ) @@ -51,11 +52,13 @@ func TestRoutesWithoutAContractDegradeExplicitly(t *testing.T) { want: http.StatusServiceUnavailable, }, { - // The task exists; its logs do not, because the files live on - // the daemon's host. "disabled" is the same answer the daemon - // gives when task logging is off, and the page already reads it. + // Task logs are a State Store read contract now + // (archie-core-iaqx), so the route answers with real data + // rather than the degrade. The task exists and its attempt + // has no log file, which is the found=false answer -- the + // page says the attempt has no log, not that logging is off. name: "per-task logs", method: http.MethodGet, path: "/api/tasks/" + strconv.FormatInt(taskID, 10) + "/logs", - want: http.StatusOK, emptyJSON: `"disabled":true`, + want: http.StatusOK, emptyJSON: `"found":false`, }, { name: "release version and update flow", method: http.MethodGet, path: "/api/version", @@ -159,8 +162,17 @@ func composeUIProcess(t *testing.T) (*webui.Server, int64) { } t.Cleanup(func() { _ = st.Close() }) + // The task-log reader lives on the state-directory side of the boundary: + // the State Store process holds a registry over the directory it owns, and + // the dashboard reads through it (archie-core-iaqx). Nothing is written to + // it here, so every attempt reads as found=false. + logs := logging.NewTaskRegistry(filepath.Join(t.TempDir(), "logs", "tasks"), logging.NewFeed(10), logging.TaskSinkOptions{}) + target, stop := serveGRPC(t, func(r grpc.ServiceRegistrar) { - staterpc.RegisterServer(r, staterpc.Deps{Tasks: st, Captures: st, BindingDispatcher: st, ConfigSnapshots: st, Log: slog.New(slog.DiscardHandler)}) + staterpc.RegisterServer(r, staterpc.Deps{ + Tasks: st, Captures: st, BindingDispatcher: st, ConfigSnapshots: st, + TaskLogs: logs, Log: slog.New(slog.DiscardHandler), + }) }) t.Cleanup(stop) client, closeClient, err := staterpc.Dial(target, "") diff --git a/internal/app/archieui/task_logs_test.go b/internal/app/archieui/task_logs_test.go new file mode 100644 index 000000000..c634420e4 --- /dev/null +++ b/internal/app/archieui/task_logs_test.go @@ -0,0 +1,201 @@ +package archieui + +import ( + "encoding/json" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "path/filepath" + "strconv" + "strings" + "testing" + + "google.golang.org/grpc" + + "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" + "github.com/samcharles93/archie-core/internal/logging" + "github.com/samcharles93/archie-core/internal/store" + "github.com/samcharles93/archie-core/internal/webui" +) + +// TestUIProcessReadsTaskLogsOverTheStateStoreContract is the dashboard bug, +// pinned end to end: the extracted UI process serves GET /api/tasks/{id}/logs +// and has no way to read a task's persisted log at all, because the only reader +// it ever had was a daemon-local file handle. The page therefore answered "Task +// logging is optional and was not enabled for this run" for every attempt of +// every task, on a deployment where task logging is unconditional and the files +// exist. +// +// The fix is a State Store read contract, so this drives the real thing: a log +// file written on the state-directory side, a gRPC server over it, a dashboard +// composed exactly as the UI process composes one, and an HTTP request through +// the composed handler. +func TestUIProcessReadsTaskLogsOverTheStateStoreContract(t *testing.T) { + srv, taskID, wantAttempt := composeUIProcessWithLog(t) + ts := httptest.NewServer(srv.Handler()) + defer ts.Close() + + path := "/api/tasks/" + strconv.FormatInt(taskID, 10) + "/logs" + req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, ts.URL+path, nil) + if err != nil { + t.Fatalf("request: %v", err) + } + resp, err := ts.Client().Do(req) + if err != nil { + t.Fatalf("GET %s: %v", path, err) + } + defer resp.Body.Close() + raw, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("read body: %v", err) + } + var body struct { + Entries []logging.Entry `json:"entries"` + Attempt int `json:"attempt"` + Found bool `json:"found"` + File string `json:"file"` + } + if err := json.Unmarshal(raw, &body); err != nil { + t.Fatalf("decode response: %v (%s)", err, raw) + } + if !body.Found { + t.Errorf("found = false for an attempt whose log exists on the state-directory side (%s)", raw) + } + if body.Attempt != wantAttempt { + t.Errorf("attempt = %d, want %d (the task's current attempt, resolved without a query param)", body.Attempt, wantAttempt) + } + if len(body.Entries) != 1 || body.Entries[0].Message != "gate failed" { + t.Fatalf("entries = %+v, want the one entry the log holds", body.Entries) + } + if got, ok := body.Entries[0].Fields["component"]; !ok || got != "gate" { + t.Errorf("entry fields = %+v, want the structured component field to survive the hop", body.Entries[0].Fields) + } + // The path is reported, not used: the UI process must not be able to open + // it, and the page only names where the log came from. + if !strings.HasSuffix(body.File, "attempt-"+strconv.Itoa(wantAttempt)+".jsonl") { + t.Errorf("file = %q, want the attempt's own log path", body.File) + } +} + +// TestUIProcessServesTaskLogDownload drives the download endpoint through the +// real composition: the bytes arrive over the contract, and the response is an +// attachment named for the attempt rather than an SPA page. +// +// A GET that falls through to the asset handler answers 200 with HTML, which +// is why this asserts the attachment headers and the content, not the status. +func TestUIProcessServesTaskLogDownload(t *testing.T) { + srv, taskID, wantAttempt := composeUIProcessWithLog(t) + ts := httptest.NewServer(srv.Handler()) + defer ts.Close() + + path := "/api/tasks/" + strconv.FormatInt(taskID, 10) + "/logs/download" + req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, ts.URL+path, nil) + if err != nil { + t.Fatalf("request: %v", err) + } + resp, err := ts.Client().Do(req) + if err != nil { + t.Fatalf("GET %s: %v", path, err) + } + defer resp.Body.Close() + raw, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("read body: %v", err) + } + wantName := "task-" + strconv.FormatInt(taskID, 10) + "-attempt-" + strconv.Itoa(wantAttempt) + ".log" + if got := resp.Header.Get("Content-Disposition"); got != `attachment; filename="`+wantName+`"` { + t.Errorf("Content-Disposition = %q, want the attempt's own filename %q (status %d, body %s)", got, wantName, resp.StatusCode, raw) + } + if !strings.Contains(string(raw), "gate failed") { + t.Errorf("download body = %s, want the attempt's own log content", raw) + } +} + +// TestUIProcessReportsMissingTaskLogsHonestly pins the second half of the fix: +// with the reader wired and no log on disk, the page must be able to say that +// the ATTEMPT has no log. It is a different claim from "this process cannot +// read logs", and only the second one is about the operator's configuration. +func TestUIProcessReportsMissingTaskLogsHonestly(t *testing.T) { + srv, taskID := composeUIProcess(t) + ts := httptest.NewServer(srv.Handler()) + defer ts.Close() + + path := "/api/tasks/" + strconv.FormatInt(taskID, 10) + "/logs" + req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, ts.URL+path, nil) + if err != nil { + t.Fatalf("request: %v", err) + } + resp, err := ts.Client().Do(req) + if err != nil { + t.Fatalf("GET %s: %v", path, err) + } + defer resp.Body.Close() + raw, _ := io.ReadAll(resp.Body) + + var body struct { + Disabled bool `json:"disabled"` + Found bool `json:"found"` + } + if err := json.Unmarshal(raw, &body); err != nil { + t.Fatalf("decode response: %v (%s)", err, raw) + } + if body.Disabled { + t.Fatalf("disabled = true for a process that can read task logs (%s); the page turns that into \"logging was not enabled for this run\"", raw) + } + if body.Found { + t.Errorf("found = true for an attempt with no log file (%s)", raw) + } +} + +// composeUIProcessWithLog is composeUIProcess plus one real log on the +// state-directory side: a gRPC server whose task-log reader holds an attempt's +// file, so the dashboard's read has to cross the wire to see anything. +func composeUIProcessWithLog(t *testing.T) (*webui.Server, int64, int) { + t.Helper() + st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "tasks.sqlite")) + if err != nil { + t.Fatalf("open store: %v", err) + } + t.Cleanup(func() { _ = st.Close() }) + + task, err := st.EnqueueChatTask(t.Context(), "acme", "widget", "a task", "body", "implement", "") + if err != nil { + t.Fatalf("seed task: %v", err) + } + + // The state directory the State Store process owns. The dashboard never + // learns this path: it asks the contract for the log. + logs := logging.NewTaskRegistry(filepath.Join(t.TempDir(), "logs", "tasks"), logging.NewFeed(10), logging.TaskSinkOptions{}) + if err := logs.Open(task.ID, task.Attempt); err != nil { + t.Fatalf("open task log: %v", err) + } + logs.Write(task.ID, logging.Entry{ + Level: "ERROR", Message: "gate failed", Fields: map[string]any{"component": "gate"}, + }) + if err := logs.Close(task.ID); err != nil { + t.Fatalf("close task log: %v", err) + } + + target, stop := serveGRPC(t, func(r grpc.ServiceRegistrar) { + staterpc.RegisterServer(r, staterpc.Deps{ + Tasks: st, Captures: st, BindingDispatcher: st, ConfigSnapshots: st, + TaskLogs: logs, Log: slog.New(slog.DiscardHandler), + }) + }) + t.Cleanup(stop) + client, closeClient, err := staterpc.Dial(target, "") + if err != nil { + t.Fatalf("dial state store: %v", err) + } + t.Cleanup(closeClient) + + options := Options{Listen: "127.0.0.1:0", DependencyTimeout: defaultDependencyTimeout} + srv := compose(deps{ + Options: options, + Log: slog.New(slog.DiscardHandler), + Store: client, + Health: newReadinessRegistry(options, client, nil), + }) + return srv, task.ID, task.Attempt +} diff --git a/internal/contracts/state/v1/state.pb.go b/internal/contracts/state/v1/state.pb.go index 5f72d6d25..7b59d9eaa 100644 --- a/internal/contracts/state/v1/state.pb.go +++ b/internal/contracts/state/v1/state.pb.go @@ -3541,6 +3541,399 @@ func (x *GetConfigSnapshotResponse) GetFound() bool { return false } +// TaskLogEntry mirrors internal/logging.Entry: one decoded log line. fields +// carries every remaining key as a JSON object string, the same way Event +// carries its data, so structured context survives the hop without this +// contract having to know what a call site attached. +type TaskLogEntry struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Time *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=time,proto3" json:"time,omitempty"` + Level string `protobuf:"bytes,3,opt,name=level,proto3" json:"level,omitempty"` + Msg string `protobuf:"bytes,4,opt,name=msg,proto3" json:"msg,omitempty"` + FieldsJson string `protobuf:"bytes,5,opt,name=fields_json,json=fieldsJson,proto3" json:"fields_json,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *TaskLogEntry) Reset() { + *x = TaskLogEntry{} + mi := &file_state_v1_state_proto_msgTypes[63] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *TaskLogEntry) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TaskLogEntry) ProtoMessage() {} + +func (x *TaskLogEntry) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[63] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use TaskLogEntry.ProtoReflect.Descriptor instead. +func (*TaskLogEntry) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{63} +} + +func (x *TaskLogEntry) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *TaskLogEntry) GetTime() *timestamppb.Timestamp { + if x != nil { + return x.Time + } + return nil +} + +func (x *TaskLogEntry) GetLevel() string { + if x != nil { + return x.Level + } + return "" +} + +func (x *TaskLogEntry) GetMsg() string { + if x != nil { + return x.Msg + } + return "" +} + +func (x *TaskLogEntry) GetFieldsJson() string { + if x != nil { + return x.FieldsJson + } + return "" +} + +// ReadTaskLog returns a page of one task attempt's decoded log. attempt is the +// attempt the caller resolved (the dashboard sends the task's current attempt +// when the request omitted one). levels, component, contains, since and until +// carry the whole query the logging package's Tail accepts -- the wire mirrors +// that query rather than a subset of it, so a filter cannot silently stop +// working by crossing the boundary. limit is caller-capped +// (docs/prds/state-store-contract.md §8: the log cap is 2000). +type ReadTaskLogRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + TaskId int64 `protobuf:"varint,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"` + Attempt int64 `protobuf:"varint,2,opt,name=attempt,proto3" json:"attempt,omitempty"` + Limit int64 `protobuf:"varint,3,opt,name=limit,proto3" json:"limit,omitempty"` + Levels []string `protobuf:"bytes,4,rep,name=levels,proto3" json:"levels,omitempty"` + Component string `protobuf:"bytes,5,opt,name=component,proto3" json:"component,omitempty"` + Contains string `protobuf:"bytes,6,opt,name=contains,proto3" json:"contains,omitempty"` + Since *timestamppb.Timestamp `protobuf:"bytes,7,opt,name=since,proto3" json:"since,omitempty"` + Until *timestamppb.Timestamp `protobuf:"bytes,8,opt,name=until,proto3" json:"until,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ReadTaskLogRequest) Reset() { + *x = ReadTaskLogRequest{} + mi := &file_state_v1_state_proto_msgTypes[64] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ReadTaskLogRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ReadTaskLogRequest) ProtoMessage() {} + +func (x *ReadTaskLogRequest) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[64] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ReadTaskLogRequest.ProtoReflect.Descriptor instead. +func (*ReadTaskLogRequest) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{64} +} + +func (x *ReadTaskLogRequest) GetTaskId() int64 { + if x != nil { + return x.TaskId + } + return 0 +} + +func (x *ReadTaskLogRequest) GetAttempt() int64 { + if x != nil { + return x.Attempt + } + return 0 +} + +func (x *ReadTaskLogRequest) GetLimit() int64 { + if x != nil { + return x.Limit + } + return 0 +} + +func (x *ReadTaskLogRequest) GetLevels() []string { + if x != nil { + return x.Levels + } + return nil +} + +func (x *ReadTaskLogRequest) GetComponent() string { + if x != nil { + return x.Component + } + return "" +} + +func (x *ReadTaskLogRequest) GetContains() string { + if x != nil { + return x.Contains + } + return "" +} + +func (x *ReadTaskLogRequest) GetSince() *timestamppb.Timestamp { + if x != nil { + return x.Since + } + return nil +} + +func (x *ReadTaskLogRequest) GetUntil() *timestamppb.Timestamp { + if x != nil { + return x.Until + } + return nil +} + +// found=false is not an error: the task has no log file for that attempt. +// That is a different condition from a process that cannot read logs at all +// (codes.Unavailable), and the dashboard reports them differently. +type ReadTaskLogResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Entries []*TaskLogEntry `protobuf:"bytes,1,rep,name=entries,proto3" json:"entries,omitempty"` + Truncated bool `protobuf:"varint,2,opt,name=truncated,proto3" json:"truncated,omitempty"` + Attempt int64 `protobuf:"varint,3,opt,name=attempt,proto3" json:"attempt,omitempty"` + Found bool `protobuf:"varint,4,opt,name=found,proto3" json:"found,omitempty"` + Components []string `protobuf:"bytes,5,rep,name=components,proto3" json:"components,omitempty"` + // file is the path read, so the page can name where the log came from. It + // is the state directory's own layout, reported to an already-authenticated + // operator; no caller is expected to open it. + File string `protobuf:"bytes,6,opt,name=file,proto3" json:"file,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ReadTaskLogResponse) Reset() { + *x = ReadTaskLogResponse{} + mi := &file_state_v1_state_proto_msgTypes[65] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ReadTaskLogResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ReadTaskLogResponse) ProtoMessage() {} + +func (x *ReadTaskLogResponse) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[65] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ReadTaskLogResponse.ProtoReflect.Descriptor instead. +func (*ReadTaskLogResponse) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{65} +} + +func (x *ReadTaskLogResponse) GetEntries() []*TaskLogEntry { + if x != nil { + return x.Entries + } + return nil +} + +func (x *ReadTaskLogResponse) GetTruncated() bool { + if x != nil { + return x.Truncated + } + return false +} + +func (x *ReadTaskLogResponse) GetAttempt() int64 { + if x != nil { + return x.Attempt + } + return 0 +} + +func (x *ReadTaskLogResponse) GetFound() bool { + if x != nil { + return x.Found + } + return false +} + +func (x *ReadTaskLogResponse) GetComponents() []string { + if x != nil { + return x.Components + } + return nil +} + +func (x *ReadTaskLogResponse) GetFile() string { + if x != nil { + return x.File + } + return "" +} + +// StreamTaskLogContent returns one attempt's log verbatim, for a download. The +// bytes are the file's own JSONL, not a re-encoding of it: this contract +// transports the log, it does not restate the format. found=false, with no +// chunks, means the attempt has no log file -- not an error. +type StreamTaskLogContentRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + TaskId int64 `protobuf:"varint,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"` + Attempt int64 `protobuf:"varint,2,opt,name=attempt,proto3" json:"attempt,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *StreamTaskLogContentRequest) Reset() { + *x = StreamTaskLogContentRequest{} + mi := &file_state_v1_state_proto_msgTypes[66] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *StreamTaskLogContentRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*StreamTaskLogContentRequest) ProtoMessage() {} + +func (x *StreamTaskLogContentRequest) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[66] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use StreamTaskLogContentRequest.ProtoReflect.Descriptor instead. +func (*StreamTaskLogContentRequest) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{66} +} + +func (x *StreamTaskLogContentRequest) GetTaskId() int64 { + if x != nil { + return x.TaskId + } + return 0 +} + +func (x *StreamTaskLogContentRequest) GetAttempt() int64 { + if x != nil { + return x.Attempt + } + return 0 +} + +type StreamTaskLogContentResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Chunk []byte `protobuf:"bytes,1,opt,name=chunk,proto3" json:"chunk,omitempty"` + Attempt int64 `protobuf:"varint,2,opt,name=attempt,proto3" json:"attempt,omitempty"` + Found bool `protobuf:"varint,3,opt,name=found,proto3" json:"found,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *StreamTaskLogContentResponse) Reset() { + *x = StreamTaskLogContentResponse{} + mi := &file_state_v1_state_proto_msgTypes[67] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *StreamTaskLogContentResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*StreamTaskLogContentResponse) ProtoMessage() {} + +func (x *StreamTaskLogContentResponse) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[67] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use StreamTaskLogContentResponse.ProtoReflect.Descriptor instead. +func (*StreamTaskLogContentResponse) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{67} +} + +func (x *StreamTaskLogContentResponse) GetChunk() []byte { + if x != nil { + return x.Chunk + } + return nil +} + +func (x *StreamTaskLogContentResponse) GetAttempt() int64 { + if x != nil { + return x.Attempt + } + return 0 +} + +func (x *StreamTaskLogContentResponse) GetFound() bool { + if x != nil { + return x.Found + } + return false +} + type InsertCaptureRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Capture *CapturedEvent `protobuf:"bytes,1,opt,name=capture,proto3" json:"capture,omitempty"` @@ -3552,7 +3945,7 @@ type InsertCaptureRequest struct { func (x *InsertCaptureRequest) Reset() { *x = InsertCaptureRequest{} - mi := &file_state_v1_state_proto_msgTypes[63] + mi := &file_state_v1_state_proto_msgTypes[68] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3564,7 +3957,7 @@ func (x *InsertCaptureRequest) String() string { func (*InsertCaptureRequest) ProtoMessage() {} func (x *InsertCaptureRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[63] + mi := &file_state_v1_state_proto_msgTypes[68] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3577,7 +3970,7 @@ func (x *InsertCaptureRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use InsertCaptureRequest.ProtoReflect.Descriptor instead. func (*InsertCaptureRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{63} + return file_state_v1_state_proto_rawDescGZIP(), []int{68} } func (x *InsertCaptureRequest) GetCapture() *CapturedEvent { @@ -3610,7 +4003,7 @@ type InsertCaptureResponse struct { func (x *InsertCaptureResponse) Reset() { *x = InsertCaptureResponse{} - mi := &file_state_v1_state_proto_msgTypes[64] + mi := &file_state_v1_state_proto_msgTypes[69] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3622,7 +4015,7 @@ func (x *InsertCaptureResponse) String() string { func (*InsertCaptureResponse) ProtoMessage() {} func (x *InsertCaptureResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[64] + mi := &file_state_v1_state_proto_msgTypes[69] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3635,7 +4028,7 @@ func (x *InsertCaptureResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use InsertCaptureResponse.ProtoReflect.Descriptor instead. func (*InsertCaptureResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{64} + return file_state_v1_state_proto_rawDescGZIP(), []int{69} } func (x *InsertCaptureResponse) GetId() int64 { @@ -3654,7 +4047,7 @@ type ListCapturesRequest struct { func (x *ListCapturesRequest) Reset() { *x = ListCapturesRequest{} - mi := &file_state_v1_state_proto_msgTypes[65] + mi := &file_state_v1_state_proto_msgTypes[70] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3666,7 +4059,7 @@ func (x *ListCapturesRequest) String() string { func (*ListCapturesRequest) ProtoMessage() {} func (x *ListCapturesRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[65] + mi := &file_state_v1_state_proto_msgTypes[70] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3679,7 +4072,7 @@ func (x *ListCapturesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListCapturesRequest.ProtoReflect.Descriptor instead. func (*ListCapturesRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{65} + return file_state_v1_state_proto_rawDescGZIP(), []int{70} } func (x *ListCapturesRequest) GetLimit() int64 { @@ -3698,7 +4091,7 @@ type ListCapturesResponse struct { func (x *ListCapturesResponse) Reset() { *x = ListCapturesResponse{} - mi := &file_state_v1_state_proto_msgTypes[66] + mi := &file_state_v1_state_proto_msgTypes[71] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3710,7 +4103,7 @@ func (x *ListCapturesResponse) String() string { func (*ListCapturesResponse) ProtoMessage() {} func (x *ListCapturesResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[66] + mi := &file_state_v1_state_proto_msgTypes[71] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3723,7 +4116,7 @@ func (x *ListCapturesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListCapturesResponse.ProtoReflect.Descriptor instead. func (*ListCapturesResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{66} + return file_state_v1_state_proto_rawDescGZIP(), []int{71} } func (x *ListCapturesResponse) GetCaptures() []*CapturedEvent { @@ -3742,7 +4135,7 @@ type StreamCapturesRequest struct { func (x *StreamCapturesRequest) Reset() { *x = StreamCapturesRequest{} - mi := &file_state_v1_state_proto_msgTypes[67] + mi := &file_state_v1_state_proto_msgTypes[72] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3754,7 +4147,7 @@ func (x *StreamCapturesRequest) String() string { func (*StreamCapturesRequest) ProtoMessage() {} func (x *StreamCapturesRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[67] + mi := &file_state_v1_state_proto_msgTypes[72] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3767,7 +4160,7 @@ func (x *StreamCapturesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use StreamCapturesRequest.ProtoReflect.Descriptor instead. func (*StreamCapturesRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{67} + return file_state_v1_state_proto_rawDescGZIP(), []int{72} } func (x *StreamCapturesRequest) GetLimit() int64 { @@ -3787,7 +4180,7 @@ type StreamCapturesResponse struct { func (x *StreamCapturesResponse) Reset() { *x = StreamCapturesResponse{} - mi := &file_state_v1_state_proto_msgTypes[68] + mi := &file_state_v1_state_proto_msgTypes[73] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3799,7 +4192,7 @@ func (x *StreamCapturesResponse) String() string { func (*StreamCapturesResponse) ProtoMessage() {} func (x *StreamCapturesResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[68] + mi := &file_state_v1_state_proto_msgTypes[73] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3812,7 +4205,7 @@ func (x *StreamCapturesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use StreamCapturesResponse.ProtoReflect.Descriptor instead. func (*StreamCapturesResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{68} + return file_state_v1_state_proto_rawDescGZIP(), []int{73} } func (x *StreamCapturesResponse) GetCapture() *CapturedEvent { @@ -3831,7 +4224,7 @@ type InsertMappingRequest struct { func (x *InsertMappingRequest) Reset() { *x = InsertMappingRequest{} - mi := &file_state_v1_state_proto_msgTypes[69] + mi := &file_state_v1_state_proto_msgTypes[74] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3843,7 +4236,7 @@ func (x *InsertMappingRequest) String() string { func (*InsertMappingRequest) ProtoMessage() {} func (x *InsertMappingRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[69] + mi := &file_state_v1_state_proto_msgTypes[74] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3856,7 +4249,7 @@ func (x *InsertMappingRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use InsertMappingRequest.ProtoReflect.Descriptor instead. func (*InsertMappingRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{69} + return file_state_v1_state_proto_rawDescGZIP(), []int{74} } func (x *InsertMappingRequest) GetMapping() *Mapping { @@ -3875,7 +4268,7 @@ type InsertMappingResponse struct { func (x *InsertMappingResponse) Reset() { *x = InsertMappingResponse{} - mi := &file_state_v1_state_proto_msgTypes[70] + mi := &file_state_v1_state_proto_msgTypes[75] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3887,7 +4280,7 @@ func (x *InsertMappingResponse) String() string { func (*InsertMappingResponse) ProtoMessage() {} func (x *InsertMappingResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[70] + mi := &file_state_v1_state_proto_msgTypes[75] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3900,7 +4293,7 @@ func (x *InsertMappingResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use InsertMappingResponse.ProtoReflect.Descriptor instead. func (*InsertMappingResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{70} + return file_state_v1_state_proto_rawDescGZIP(), []int{75} } func (x *InsertMappingResponse) GetId() int64 { @@ -3919,7 +4312,7 @@ type GetMappingRequest struct { func (x *GetMappingRequest) Reset() { *x = GetMappingRequest{} - mi := &file_state_v1_state_proto_msgTypes[71] + mi := &file_state_v1_state_proto_msgTypes[76] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3931,7 +4324,7 @@ func (x *GetMappingRequest) String() string { func (*GetMappingRequest) ProtoMessage() {} func (x *GetMappingRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[71] + mi := &file_state_v1_state_proto_msgTypes[76] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3944,7 +4337,7 @@ func (x *GetMappingRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetMappingRequest.ProtoReflect.Descriptor instead. func (*GetMappingRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{71} + return file_state_v1_state_proto_rawDescGZIP(), []int{76} } func (x *GetMappingRequest) GetId() int64 { @@ -3964,7 +4357,7 @@ type GetMappingResponse struct { func (x *GetMappingResponse) Reset() { *x = GetMappingResponse{} - mi := &file_state_v1_state_proto_msgTypes[72] + mi := &file_state_v1_state_proto_msgTypes[77] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3976,7 +4369,7 @@ func (x *GetMappingResponse) String() string { func (*GetMappingResponse) ProtoMessage() {} func (x *GetMappingResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[72] + mi := &file_state_v1_state_proto_msgTypes[77] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3989,7 +4382,7 @@ func (x *GetMappingResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetMappingResponse.ProtoReflect.Descriptor instead. func (*GetMappingResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{72} + return file_state_v1_state_proto_rawDescGZIP(), []int{77} } func (x *GetMappingResponse) GetMapping() *Mapping { @@ -4014,7 +4407,7 @@ type ListMappingsRequest struct { func (x *ListMappingsRequest) Reset() { *x = ListMappingsRequest{} - mi := &file_state_v1_state_proto_msgTypes[73] + mi := &file_state_v1_state_proto_msgTypes[78] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4026,7 +4419,7 @@ func (x *ListMappingsRequest) String() string { func (*ListMappingsRequest) ProtoMessage() {} func (x *ListMappingsRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[73] + mi := &file_state_v1_state_proto_msgTypes[78] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4039,7 +4432,7 @@ func (x *ListMappingsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListMappingsRequest.ProtoReflect.Descriptor instead. func (*ListMappingsRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{73} + return file_state_v1_state_proto_rawDescGZIP(), []int{78} } type ListMappingsResponse struct { @@ -4051,7 +4444,7 @@ type ListMappingsResponse struct { func (x *ListMappingsResponse) Reset() { *x = ListMappingsResponse{} - mi := &file_state_v1_state_proto_msgTypes[74] + mi := &file_state_v1_state_proto_msgTypes[79] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4063,7 +4456,7 @@ func (x *ListMappingsResponse) String() string { func (*ListMappingsResponse) ProtoMessage() {} func (x *ListMappingsResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[74] + mi := &file_state_v1_state_proto_msgTypes[79] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4076,7 +4469,7 @@ func (x *ListMappingsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListMappingsResponse.ProtoReflect.Descriptor instead. func (*ListMappingsResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{74} + return file_state_v1_state_proto_rawDescGZIP(), []int{79} } func (x *ListMappingsResponse) GetMappings() []*Mapping { @@ -4095,7 +4488,7 @@ type UpdateMappingRequest struct { func (x *UpdateMappingRequest) Reset() { *x = UpdateMappingRequest{} - mi := &file_state_v1_state_proto_msgTypes[75] + mi := &file_state_v1_state_proto_msgTypes[80] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4107,7 +4500,7 @@ func (x *UpdateMappingRequest) String() string { func (*UpdateMappingRequest) ProtoMessage() {} func (x *UpdateMappingRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[75] + mi := &file_state_v1_state_proto_msgTypes[80] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4120,7 +4513,7 @@ func (x *UpdateMappingRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use UpdateMappingRequest.ProtoReflect.Descriptor instead. func (*UpdateMappingRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{75} + return file_state_v1_state_proto_rawDescGZIP(), []int{80} } func (x *UpdateMappingRequest) GetMapping() *Mapping { @@ -4138,7 +4531,7 @@ type UpdateMappingResponse struct { func (x *UpdateMappingResponse) Reset() { *x = UpdateMappingResponse{} - mi := &file_state_v1_state_proto_msgTypes[76] + mi := &file_state_v1_state_proto_msgTypes[81] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4150,7 +4543,7 @@ func (x *UpdateMappingResponse) String() string { func (*UpdateMappingResponse) ProtoMessage() {} func (x *UpdateMappingResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[76] + mi := &file_state_v1_state_proto_msgTypes[81] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4163,7 +4556,7 @@ func (x *UpdateMappingResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use UpdateMappingResponse.ProtoReflect.Descriptor instead. func (*UpdateMappingResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{76} + return file_state_v1_state_proto_rawDescGZIP(), []int{81} } type DeleteMappingRequest struct { @@ -4175,7 +4568,7 @@ type DeleteMappingRequest struct { func (x *DeleteMappingRequest) Reset() { *x = DeleteMappingRequest{} - mi := &file_state_v1_state_proto_msgTypes[77] + mi := &file_state_v1_state_proto_msgTypes[82] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4187,7 +4580,7 @@ func (x *DeleteMappingRequest) String() string { func (*DeleteMappingRequest) ProtoMessage() {} func (x *DeleteMappingRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[77] + mi := &file_state_v1_state_proto_msgTypes[82] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4200,7 +4593,7 @@ func (x *DeleteMappingRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteMappingRequest.ProtoReflect.Descriptor instead. func (*DeleteMappingRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{77} + return file_state_v1_state_proto_rawDescGZIP(), []int{82} } func (x *DeleteMappingRequest) GetId() int64 { @@ -4218,7 +4611,7 @@ type DeleteMappingResponse struct { func (x *DeleteMappingResponse) Reset() { *x = DeleteMappingResponse{} - mi := &file_state_v1_state_proto_msgTypes[78] + mi := &file_state_v1_state_proto_msgTypes[83] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4230,7 +4623,7 @@ func (x *DeleteMappingResponse) String() string { func (*DeleteMappingResponse) ProtoMessage() {} func (x *DeleteMappingResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[78] + mi := &file_state_v1_state_proto_msgTypes[83] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4243,7 +4636,7 @@ func (x *DeleteMappingResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteMappingResponse.ProtoReflect.Descriptor instead. func (*DeleteMappingResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{78} + return file_state_v1_state_proto_rawDescGZIP(), []int{83} } type InsertBindingRequest struct { @@ -4255,7 +4648,7 @@ type InsertBindingRequest struct { func (x *InsertBindingRequest) Reset() { *x = InsertBindingRequest{} - mi := &file_state_v1_state_proto_msgTypes[79] + mi := &file_state_v1_state_proto_msgTypes[84] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4267,7 +4660,7 @@ func (x *InsertBindingRequest) String() string { func (*InsertBindingRequest) ProtoMessage() {} func (x *InsertBindingRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[79] + mi := &file_state_v1_state_proto_msgTypes[84] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4280,7 +4673,7 @@ func (x *InsertBindingRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use InsertBindingRequest.ProtoReflect.Descriptor instead. func (*InsertBindingRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{79} + return file_state_v1_state_proto_rawDescGZIP(), []int{84} } func (x *InsertBindingRequest) GetBinding() *Binding { @@ -4299,7 +4692,7 @@ type InsertBindingResponse struct { func (x *InsertBindingResponse) Reset() { *x = InsertBindingResponse{} - mi := &file_state_v1_state_proto_msgTypes[80] + mi := &file_state_v1_state_proto_msgTypes[85] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4311,7 +4704,7 @@ func (x *InsertBindingResponse) String() string { func (*InsertBindingResponse) ProtoMessage() {} func (x *InsertBindingResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[80] + mi := &file_state_v1_state_proto_msgTypes[85] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4324,7 +4717,7 @@ func (x *InsertBindingResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use InsertBindingResponse.ProtoReflect.Descriptor instead. func (*InsertBindingResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{80} + return file_state_v1_state_proto_rawDescGZIP(), []int{85} } func (x *InsertBindingResponse) GetId() int64 { @@ -4343,7 +4736,7 @@ type GetBindingRequest struct { func (x *GetBindingRequest) Reset() { *x = GetBindingRequest{} - mi := &file_state_v1_state_proto_msgTypes[81] + mi := &file_state_v1_state_proto_msgTypes[86] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4355,7 +4748,7 @@ func (x *GetBindingRequest) String() string { func (*GetBindingRequest) ProtoMessage() {} func (x *GetBindingRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[81] + mi := &file_state_v1_state_proto_msgTypes[86] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4368,7 +4761,7 @@ func (x *GetBindingRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetBindingRequest.ProtoReflect.Descriptor instead. func (*GetBindingRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{81} + return file_state_v1_state_proto_rawDescGZIP(), []int{86} } func (x *GetBindingRequest) GetId() int64 { @@ -4388,7 +4781,7 @@ type GetBindingResponse struct { func (x *GetBindingResponse) Reset() { *x = GetBindingResponse{} - mi := &file_state_v1_state_proto_msgTypes[82] + mi := &file_state_v1_state_proto_msgTypes[87] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4400,7 +4793,7 @@ func (x *GetBindingResponse) String() string { func (*GetBindingResponse) ProtoMessage() {} func (x *GetBindingResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[82] + mi := &file_state_v1_state_proto_msgTypes[87] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4413,7 +4806,7 @@ func (x *GetBindingResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetBindingResponse.ProtoReflect.Descriptor instead. func (*GetBindingResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{82} + return file_state_v1_state_proto_rawDescGZIP(), []int{87} } func (x *GetBindingResponse) GetBinding() *Binding { @@ -4438,7 +4831,7 @@ type ListBindingsRequest struct { func (x *ListBindingsRequest) Reset() { *x = ListBindingsRequest{} - mi := &file_state_v1_state_proto_msgTypes[83] + mi := &file_state_v1_state_proto_msgTypes[88] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4450,7 +4843,7 @@ func (x *ListBindingsRequest) String() string { func (*ListBindingsRequest) ProtoMessage() {} func (x *ListBindingsRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[83] + mi := &file_state_v1_state_proto_msgTypes[88] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4463,7 +4856,7 @@ func (x *ListBindingsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListBindingsRequest.ProtoReflect.Descriptor instead. func (*ListBindingsRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{83} + return file_state_v1_state_proto_rawDescGZIP(), []int{88} } type ListBindingsResponse struct { @@ -4475,7 +4868,7 @@ type ListBindingsResponse struct { func (x *ListBindingsResponse) Reset() { *x = ListBindingsResponse{} - mi := &file_state_v1_state_proto_msgTypes[84] + mi := &file_state_v1_state_proto_msgTypes[89] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4487,7 +4880,7 @@ func (x *ListBindingsResponse) String() string { func (*ListBindingsResponse) ProtoMessage() {} func (x *ListBindingsResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[84] + mi := &file_state_v1_state_proto_msgTypes[89] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4500,7 +4893,7 @@ func (x *ListBindingsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListBindingsResponse.ProtoReflect.Descriptor instead. func (*ListBindingsResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{84} + return file_state_v1_state_proto_rawDescGZIP(), []int{89} } func (x *ListBindingsResponse) GetBindings() []*Binding { @@ -4519,7 +4912,7 @@ type UpdateBindingRequest struct { func (x *UpdateBindingRequest) Reset() { *x = UpdateBindingRequest{} - mi := &file_state_v1_state_proto_msgTypes[85] + mi := &file_state_v1_state_proto_msgTypes[90] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4531,7 +4924,7 @@ func (x *UpdateBindingRequest) String() string { func (*UpdateBindingRequest) ProtoMessage() {} func (x *UpdateBindingRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[85] + mi := &file_state_v1_state_proto_msgTypes[90] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4544,7 +4937,7 @@ func (x *UpdateBindingRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use UpdateBindingRequest.ProtoReflect.Descriptor instead. func (*UpdateBindingRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{85} + return file_state_v1_state_proto_rawDescGZIP(), []int{90} } func (x *UpdateBindingRequest) GetBinding() *Binding { @@ -4562,7 +4955,7 @@ type UpdateBindingResponse struct { func (x *UpdateBindingResponse) Reset() { *x = UpdateBindingResponse{} - mi := &file_state_v1_state_proto_msgTypes[86] + mi := &file_state_v1_state_proto_msgTypes[91] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4574,7 +4967,7 @@ func (x *UpdateBindingResponse) String() string { func (*UpdateBindingResponse) ProtoMessage() {} func (x *UpdateBindingResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[86] + mi := &file_state_v1_state_proto_msgTypes[91] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4587,7 +4980,7 @@ func (x *UpdateBindingResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use UpdateBindingResponse.ProtoReflect.Descriptor instead. func (*UpdateBindingResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{86} + return file_state_v1_state_proto_rawDescGZIP(), []int{91} } type DeleteBindingRequest struct { @@ -4599,7 +4992,7 @@ type DeleteBindingRequest struct { func (x *DeleteBindingRequest) Reset() { *x = DeleteBindingRequest{} - mi := &file_state_v1_state_proto_msgTypes[87] + mi := &file_state_v1_state_proto_msgTypes[92] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4611,7 +5004,7 @@ func (x *DeleteBindingRequest) String() string { func (*DeleteBindingRequest) ProtoMessage() {} func (x *DeleteBindingRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[87] + mi := &file_state_v1_state_proto_msgTypes[92] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4624,7 +5017,7 @@ func (x *DeleteBindingRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteBindingRequest.ProtoReflect.Descriptor instead. func (*DeleteBindingRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{87} + return file_state_v1_state_proto_rawDescGZIP(), []int{92} } func (x *DeleteBindingRequest) GetId() int64 { @@ -4642,7 +5035,7 @@ type DeleteBindingResponse struct { func (x *DeleteBindingResponse) Reset() { *x = DeleteBindingResponse{} - mi := &file_state_v1_state_proto_msgTypes[88] + mi := &file_state_v1_state_proto_msgTypes[93] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4654,7 +5047,7 @@ func (x *DeleteBindingResponse) String() string { func (*DeleteBindingResponse) ProtoMessage() {} func (x *DeleteBindingResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[88] + mi := &file_state_v1_state_proto_msgTypes[93] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4667,7 +5060,7 @@ func (x *DeleteBindingResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteBindingResponse.ProtoReflect.Descriptor instead. func (*DeleteBindingResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{88} + return file_state_v1_state_proto_rawDescGZIP(), []int{93} } type ApproveBindingRequest struct { @@ -4679,7 +5072,7 @@ type ApproveBindingRequest struct { func (x *ApproveBindingRequest) Reset() { *x = ApproveBindingRequest{} - mi := &file_state_v1_state_proto_msgTypes[89] + mi := &file_state_v1_state_proto_msgTypes[94] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4691,7 +5084,7 @@ func (x *ApproveBindingRequest) String() string { func (*ApproveBindingRequest) ProtoMessage() {} func (x *ApproveBindingRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[89] + mi := &file_state_v1_state_proto_msgTypes[94] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4704,7 +5097,7 @@ func (x *ApproveBindingRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ApproveBindingRequest.ProtoReflect.Descriptor instead. func (*ApproveBindingRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{89} + return file_state_v1_state_proto_rawDescGZIP(), []int{94} } func (x *ApproveBindingRequest) GetId() int64 { @@ -4722,7 +5115,7 @@ type ApproveBindingResponse struct { func (x *ApproveBindingResponse) Reset() { *x = ApproveBindingResponse{} - mi := &file_state_v1_state_proto_msgTypes[90] + mi := &file_state_v1_state_proto_msgTypes[95] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4734,7 +5127,7 @@ func (x *ApproveBindingResponse) String() string { func (*ApproveBindingResponse) ProtoMessage() {} func (x *ApproveBindingResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[90] + mi := &file_state_v1_state_proto_msgTypes[95] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4747,7 +5140,7 @@ func (x *ApproveBindingResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ApproveBindingResponse.ProtoReflect.Descriptor instead. func (*ApproveBindingResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{90} + return file_state_v1_state_proto_rawDescGZIP(), []int{95} } type ArmedBindingsForSourceRequest struct { @@ -4759,7 +5152,7 @@ type ArmedBindingsForSourceRequest struct { func (x *ArmedBindingsForSourceRequest) Reset() { *x = ArmedBindingsForSourceRequest{} - mi := &file_state_v1_state_proto_msgTypes[91] + mi := &file_state_v1_state_proto_msgTypes[96] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4771,7 +5164,7 @@ func (x *ArmedBindingsForSourceRequest) String() string { func (*ArmedBindingsForSourceRequest) ProtoMessage() {} func (x *ArmedBindingsForSourceRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[91] + mi := &file_state_v1_state_proto_msgTypes[96] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4784,7 +5177,7 @@ func (x *ArmedBindingsForSourceRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ArmedBindingsForSourceRequest.ProtoReflect.Descriptor instead. func (*ArmedBindingsForSourceRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{91} + return file_state_v1_state_proto_rawDescGZIP(), []int{96} } func (x *ArmedBindingsForSourceRequest) GetSource() string { @@ -4803,7 +5196,7 @@ type ArmedBindingsForSourceResponse struct { func (x *ArmedBindingsForSourceResponse) Reset() { *x = ArmedBindingsForSourceResponse{} - mi := &file_state_v1_state_proto_msgTypes[92] + mi := &file_state_v1_state_proto_msgTypes[97] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4815,7 +5208,7 @@ func (x *ArmedBindingsForSourceResponse) String() string { func (*ArmedBindingsForSourceResponse) ProtoMessage() {} func (x *ArmedBindingsForSourceResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[92] + mi := &file_state_v1_state_proto_msgTypes[97] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4828,7 +5221,7 @@ func (x *ArmedBindingsForSourceResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ArmedBindingsForSourceResponse.ProtoReflect.Descriptor instead. func (*ArmedBindingsForSourceResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{92} + return file_state_v1_state_proto_rawDescGZIP(), []int{97} } func (x *ArmedBindingsForSourceResponse) GetBindings() []*Binding { @@ -4850,7 +5243,7 @@ type RecordDispatchRequest struct { func (x *RecordDispatchRequest) Reset() { *x = RecordDispatchRequest{} - mi := &file_state_v1_state_proto_msgTypes[93] + mi := &file_state_v1_state_proto_msgTypes[98] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4862,7 +5255,7 @@ func (x *RecordDispatchRequest) String() string { func (*RecordDispatchRequest) ProtoMessage() {} func (x *RecordDispatchRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[93] + mi := &file_state_v1_state_proto_msgTypes[98] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4875,7 +5268,7 @@ func (x *RecordDispatchRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RecordDispatchRequest.ProtoReflect.Descriptor instead. func (*RecordDispatchRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{93} + return file_state_v1_state_proto_rawDescGZIP(), []int{98} } func (x *RecordDispatchRequest) GetBindingId() int64 { @@ -4914,7 +5307,7 @@ type RecordDispatchResponse struct { func (x *RecordDispatchResponse) Reset() { *x = RecordDispatchResponse{} - mi := &file_state_v1_state_proto_msgTypes[94] + mi := &file_state_v1_state_proto_msgTypes[99] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4926,7 +5319,7 @@ func (x *RecordDispatchResponse) String() string { func (*RecordDispatchResponse) ProtoMessage() {} func (x *RecordDispatchResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[94] + mi := &file_state_v1_state_proto_msgTypes[99] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4939,7 +5332,7 @@ func (x *RecordDispatchResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RecordDispatchResponse.ProtoReflect.Descriptor instead. func (*RecordDispatchResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{94} + return file_state_v1_state_proto_rawDescGZIP(), []int{99} } type ListUndispatchedCapturesRequest struct { @@ -4952,7 +5345,7 @@ type ListUndispatchedCapturesRequest struct { func (x *ListUndispatchedCapturesRequest) Reset() { *x = ListUndispatchedCapturesRequest{} - mi := &file_state_v1_state_proto_msgTypes[95] + mi := &file_state_v1_state_proto_msgTypes[100] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4964,7 +5357,7 @@ func (x *ListUndispatchedCapturesRequest) String() string { func (*ListUndispatchedCapturesRequest) ProtoMessage() {} func (x *ListUndispatchedCapturesRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[95] + mi := &file_state_v1_state_proto_msgTypes[100] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4977,7 +5370,7 @@ func (x *ListUndispatchedCapturesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListUndispatchedCapturesRequest.ProtoReflect.Descriptor instead. func (*ListUndispatchedCapturesRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{95} + return file_state_v1_state_proto_rawDescGZIP(), []int{100} } func (x *ListUndispatchedCapturesRequest) GetSources() []string { @@ -5003,7 +5396,7 @@ type ListUndispatchedCapturesResponse struct { func (x *ListUndispatchedCapturesResponse) Reset() { *x = ListUndispatchedCapturesResponse{} - mi := &file_state_v1_state_proto_msgTypes[96] + mi := &file_state_v1_state_proto_msgTypes[101] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5015,7 +5408,7 @@ func (x *ListUndispatchedCapturesResponse) String() string { func (*ListUndispatchedCapturesResponse) ProtoMessage() {} func (x *ListUndispatchedCapturesResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[96] + mi := &file_state_v1_state_proto_msgTypes[101] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5028,7 +5421,7 @@ func (x *ListUndispatchedCapturesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListUndispatchedCapturesResponse.ProtoReflect.Descriptor instead. func (*ListUndispatchedCapturesResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{96} + return file_state_v1_state_proto_rawDescGZIP(), []int{101} } func (x *ListUndispatchedCapturesResponse) GetCaptures() []*CapturedEvent { @@ -5048,7 +5441,7 @@ type StreamUndispatchedCapturesRequest struct { func (x *StreamUndispatchedCapturesRequest) Reset() { *x = StreamUndispatchedCapturesRequest{} - mi := &file_state_v1_state_proto_msgTypes[97] + mi := &file_state_v1_state_proto_msgTypes[102] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5060,7 +5453,7 @@ func (x *StreamUndispatchedCapturesRequest) String() string { func (*StreamUndispatchedCapturesRequest) ProtoMessage() {} func (x *StreamUndispatchedCapturesRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[97] + mi := &file_state_v1_state_proto_msgTypes[102] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5073,7 +5466,7 @@ func (x *StreamUndispatchedCapturesRequest) ProtoReflect() protoreflect.Message // Deprecated: Use StreamUndispatchedCapturesRequest.ProtoReflect.Descriptor instead. func (*StreamUndispatchedCapturesRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{97} + return file_state_v1_state_proto_rawDescGZIP(), []int{102} } func (x *StreamUndispatchedCapturesRequest) GetSources() []string { @@ -5100,7 +5493,7 @@ type StreamUndispatchedCapturesResponse struct { func (x *StreamUndispatchedCapturesResponse) Reset() { *x = StreamUndispatchedCapturesResponse{} - mi := &file_state_v1_state_proto_msgTypes[98] + mi := &file_state_v1_state_proto_msgTypes[103] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5112,7 +5505,7 @@ func (x *StreamUndispatchedCapturesResponse) String() string { func (*StreamUndispatchedCapturesResponse) ProtoMessage() {} func (x *StreamUndispatchedCapturesResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[98] + mi := &file_state_v1_state_proto_msgTypes[103] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5125,7 +5518,7 @@ func (x *StreamUndispatchedCapturesResponse) ProtoReflect() protoreflect.Message // Deprecated: Use StreamUndispatchedCapturesResponse.ProtoReflect.Descriptor instead. func (*StreamUndispatchedCapturesResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{98} + return file_state_v1_state_proto_rawDescGZIP(), []int{103} } func (x *StreamUndispatchedCapturesResponse) GetCapture() *CapturedEvent { @@ -5151,7 +5544,7 @@ type EnqueueBindingTaskRequest struct { func (x *EnqueueBindingTaskRequest) Reset() { *x = EnqueueBindingTaskRequest{} - mi := &file_state_v1_state_proto_msgTypes[99] + mi := &file_state_v1_state_proto_msgTypes[104] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5163,7 +5556,7 @@ func (x *EnqueueBindingTaskRequest) String() string { func (*EnqueueBindingTaskRequest) ProtoMessage() {} func (x *EnqueueBindingTaskRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[99] + mi := &file_state_v1_state_proto_msgTypes[104] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5176,7 +5569,7 @@ func (x *EnqueueBindingTaskRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use EnqueueBindingTaskRequest.ProtoReflect.Descriptor instead. func (*EnqueueBindingTaskRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{99} + return file_state_v1_state_proto_rawDescGZIP(), []int{104} } func (x *EnqueueBindingTaskRequest) GetOwner() string { @@ -5244,7 +5637,7 @@ type EnqueueBindingTaskResponse struct { func (x *EnqueueBindingTaskResponse) Reset() { *x = EnqueueBindingTaskResponse{} - mi := &file_state_v1_state_proto_msgTypes[100] + mi := &file_state_v1_state_proto_msgTypes[105] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5256,7 +5649,7 @@ func (x *EnqueueBindingTaskResponse) String() string { func (*EnqueueBindingTaskResponse) ProtoMessage() {} func (x *EnqueueBindingTaskResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[100] + mi := &file_state_v1_state_proto_msgTypes[105] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5269,7 +5662,7 @@ func (x *EnqueueBindingTaskResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use EnqueueBindingTaskResponse.ProtoReflect.Descriptor instead. func (*EnqueueBindingTaskResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{100} + return file_state_v1_state_proto_rawDescGZIP(), []int{105} } func (x *EnqueueBindingTaskResponse) GetTask() *Task { @@ -5526,7 +5919,39 @@ const file_state_v1_state_proto_rawDesc = "" + "\x18GetConfigSnapshotRequest\"g\n" + "\x19GetConfigSnapshotResponse\x124\n" + "\bsnapshot\x18\x01 \x01(\v2\x18.state.v1.ConfigSnapshotR\bsnapshot\x12\x14\n" + - "\x05found\x18\x02 \x01(\bR\x05found\"\x95\x01\n" + + "\x05found\x18\x02 \x01(\bR\x05found\"\x97\x01\n" + + "\fTaskLogEntry\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12.\n" + + "\x04time\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x04time\x12\x14\n" + + "\x05level\x18\x03 \x01(\tR\x05level\x12\x10\n" + + "\x03msg\x18\x04 \x01(\tR\x03msg\x12\x1f\n" + + "\vfields_json\x18\x05 \x01(\tR\n" + + "fieldsJson\"\x93\x02\n" + + "\x12ReadTaskLogRequest\x12\x17\n" + + "\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x18\n" + + "\aattempt\x18\x02 \x01(\x03R\aattempt\x12\x14\n" + + "\x05limit\x18\x03 \x01(\x03R\x05limit\x12\x16\n" + + "\x06levels\x18\x04 \x03(\tR\x06levels\x12\x1c\n" + + "\tcomponent\x18\x05 \x01(\tR\tcomponent\x12\x1a\n" + + "\bcontains\x18\x06 \x01(\tR\bcontains\x120\n" + + "\x05since\x18\a \x01(\v2\x1a.google.protobuf.TimestampR\x05since\x120\n" + + "\x05until\x18\b \x01(\v2\x1a.google.protobuf.TimestampR\x05until\"\xc9\x01\n" + + "\x13ReadTaskLogResponse\x120\n" + + "\aentries\x18\x01 \x03(\v2\x16.state.v1.TaskLogEntryR\aentries\x12\x1c\n" + + "\ttruncated\x18\x02 \x01(\bR\ttruncated\x12\x18\n" + + "\aattempt\x18\x03 \x01(\x03R\aattempt\x12\x14\n" + + "\x05found\x18\x04 \x01(\bR\x05found\x12\x1e\n" + + "\n" + + "components\x18\x05 \x03(\tR\n" + + "components\x12\x12\n" + + "\x04file\x18\x06 \x01(\tR\x04file\"P\n" + + "\x1bStreamTaskLogContentRequest\x12\x17\n" + + "\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x18\n" + + "\aattempt\x18\x02 \x01(\x03R\aattempt\"d\n" + + "\x1cStreamTaskLogContentResponse\x12\x14\n" + + "\x05chunk\x18\x01 \x01(\fR\x05chunk\x12\x18\n" + + "\aattempt\x18\x02 \x01(\x03R\aattempt\x12\x14\n" + + "\x05found\x18\x03 \x01(\bR\x05found\"\x95\x01\n" + "\x14InsertCaptureRequest\x121\n" + "\acapture\x18\x01 \x01(\v2\x17.state.v1.CapturedEventR\acapture\x12+\n" + "\x11retention_seconds\x18\x02 \x01(\x03R\x10retentionSeconds\x12\x1d\n" + @@ -5614,7 +6039,7 @@ const file_state_v1_state_proto_rawDesc = "" + "binding_id\x18\a \x01(\x03R\tbindingId\x12'\n" + "\x0fbinding_version\x18\b \x01(\x03R\x0ebindingVersion\"@\n" + "\x1aEnqueueBindingTaskResponse\x12\"\n" + - "\x04task\x18\x01 \x01(\v2\x0e.state.v1.TaskR\x04task2\xed\x1c\n" + + "\x04task\x18\x01 \x01(\v2\x0e.state.v1.TaskR\x04task2\xa2\x1e\n" + "\x11StateStoreService\x12\\\n" + "\x11RegisterTaskGrant\x12\".state.v1.RegisterTaskGrantRequest\x1a#.state.v1.RegisterTaskGrantResponse\x12V\n" + "\x0fRevokeTaskGrant\x12 .state.v1.RevokeTaskGrantRequest\x1a!.state.v1.RevokeTaskGrantResponse\x12M\n" + @@ -5644,7 +6069,9 @@ const file_state_v1_state_proto_rawDesc = "" + "StageStats\x12\x1b.state.v1.StageStatsRequest\x1a\x1c.state.v1.StageStatsResponse\x12J\n" + "\vTokensByDay\x12\x1c.state.v1.TokensByDayRequest\x1a\x1d.state.v1.TokensByDayResponse\x12\\\n" + "\x11PutConfigSnapshot\x12\".state.v1.PutConfigSnapshotRequest\x1a#.state.v1.PutConfigSnapshotResponse\x12\\\n" + - "\x11GetConfigSnapshot\x12\".state.v1.GetConfigSnapshotRequest\x1a#.state.v1.GetConfigSnapshotResponse\x12P\n" + + "\x11GetConfigSnapshot\x12\".state.v1.GetConfigSnapshotRequest\x1a#.state.v1.GetConfigSnapshotResponse\x12J\n" + + "\vReadTaskLog\x12\x1c.state.v1.ReadTaskLogRequest\x1a\x1d.state.v1.ReadTaskLogResponse\x12g\n" + + "\x14StreamTaskLogContent\x12%.state.v1.StreamTaskLogContentRequest\x1a&.state.v1.StreamTaskLogContentResponse0\x01\x12P\n" + "\rInsertCapture\x12\x1e.state.v1.InsertCaptureRequest\x1a\x1f.state.v1.InsertCaptureResponse\x12R\n" + "\fListCaptures\x12\x1d.state.v1.ListCapturesRequest\x1a\x1e.state.v1.ListCapturesResponse\"\x03\x88\x02\x01\x12U\n" + "\x0eStreamCaptures\x12\x1f.state.v1.StreamCapturesRequest\x1a .state.v1.StreamCapturesResponse0\x01\x12P\n" + @@ -5681,7 +6108,7 @@ func file_state_v1_state_proto_rawDescGZIP() []byte { return file_state_v1_state_proto_rawDescData } -var file_state_v1_state_proto_msgTypes = make([]protoimpl.MessageInfo, 102) +var file_state_v1_state_proto_msgTypes = make([]protoimpl.MessageInfo, 107) var file_state_v1_state_proto_goTypes = []any{ (*RegisterTaskGrantRequest)(nil), // 0: state.v1.RegisterTaskGrantRequest (*RegisterTaskGrantResponse)(nil), // 1: state.v1.RegisterTaskGrantResponse @@ -5746,58 +6173,63 @@ var file_state_v1_state_proto_goTypes = []any{ (*PutConfigSnapshotResponse)(nil), // 60: state.v1.PutConfigSnapshotResponse (*GetConfigSnapshotRequest)(nil), // 61: state.v1.GetConfigSnapshotRequest (*GetConfigSnapshotResponse)(nil), // 62: state.v1.GetConfigSnapshotResponse - (*InsertCaptureRequest)(nil), // 63: state.v1.InsertCaptureRequest - (*InsertCaptureResponse)(nil), // 64: state.v1.InsertCaptureResponse - (*ListCapturesRequest)(nil), // 65: state.v1.ListCapturesRequest - (*ListCapturesResponse)(nil), // 66: state.v1.ListCapturesResponse - (*StreamCapturesRequest)(nil), // 67: state.v1.StreamCapturesRequest - (*StreamCapturesResponse)(nil), // 68: state.v1.StreamCapturesResponse - (*InsertMappingRequest)(nil), // 69: state.v1.InsertMappingRequest - (*InsertMappingResponse)(nil), // 70: state.v1.InsertMappingResponse - (*GetMappingRequest)(nil), // 71: state.v1.GetMappingRequest - (*GetMappingResponse)(nil), // 72: state.v1.GetMappingResponse - (*ListMappingsRequest)(nil), // 73: state.v1.ListMappingsRequest - (*ListMappingsResponse)(nil), // 74: state.v1.ListMappingsResponse - (*UpdateMappingRequest)(nil), // 75: state.v1.UpdateMappingRequest - (*UpdateMappingResponse)(nil), // 76: state.v1.UpdateMappingResponse - (*DeleteMappingRequest)(nil), // 77: state.v1.DeleteMappingRequest - (*DeleteMappingResponse)(nil), // 78: state.v1.DeleteMappingResponse - (*InsertBindingRequest)(nil), // 79: state.v1.InsertBindingRequest - (*InsertBindingResponse)(nil), // 80: state.v1.InsertBindingResponse - (*GetBindingRequest)(nil), // 81: state.v1.GetBindingRequest - (*GetBindingResponse)(nil), // 82: state.v1.GetBindingResponse - (*ListBindingsRequest)(nil), // 83: state.v1.ListBindingsRequest - (*ListBindingsResponse)(nil), // 84: state.v1.ListBindingsResponse - (*UpdateBindingRequest)(nil), // 85: state.v1.UpdateBindingRequest - (*UpdateBindingResponse)(nil), // 86: state.v1.UpdateBindingResponse - (*DeleteBindingRequest)(nil), // 87: state.v1.DeleteBindingRequest - (*DeleteBindingResponse)(nil), // 88: state.v1.DeleteBindingResponse - (*ApproveBindingRequest)(nil), // 89: state.v1.ApproveBindingRequest - (*ApproveBindingResponse)(nil), // 90: state.v1.ApproveBindingResponse - (*ArmedBindingsForSourceRequest)(nil), // 91: state.v1.ArmedBindingsForSourceRequest - (*ArmedBindingsForSourceResponse)(nil), // 92: state.v1.ArmedBindingsForSourceResponse - (*RecordDispatchRequest)(nil), // 93: state.v1.RecordDispatchRequest - (*RecordDispatchResponse)(nil), // 94: state.v1.RecordDispatchResponse - (*ListUndispatchedCapturesRequest)(nil), // 95: state.v1.ListUndispatchedCapturesRequest - (*ListUndispatchedCapturesResponse)(nil), // 96: state.v1.ListUndispatchedCapturesResponse - (*StreamUndispatchedCapturesRequest)(nil), // 97: state.v1.StreamUndispatchedCapturesRequest - (*StreamUndispatchedCapturesResponse)(nil), // 98: state.v1.StreamUndispatchedCapturesResponse - (*EnqueueBindingTaskRequest)(nil), // 99: state.v1.EnqueueBindingTaskRequest - (*EnqueueBindingTaskResponse)(nil), // 100: state.v1.EnqueueBindingTaskResponse - nil, // 101: state.v1.StatusCountsResponse.CountsEntry - (*timestamppb.Timestamp)(nil), // 102: google.protobuf.Timestamp + (*TaskLogEntry)(nil), // 63: state.v1.TaskLogEntry + (*ReadTaskLogRequest)(nil), // 64: state.v1.ReadTaskLogRequest + (*ReadTaskLogResponse)(nil), // 65: state.v1.ReadTaskLogResponse + (*StreamTaskLogContentRequest)(nil), // 66: state.v1.StreamTaskLogContentRequest + (*StreamTaskLogContentResponse)(nil), // 67: state.v1.StreamTaskLogContentResponse + (*InsertCaptureRequest)(nil), // 68: state.v1.InsertCaptureRequest + (*InsertCaptureResponse)(nil), // 69: state.v1.InsertCaptureResponse + (*ListCapturesRequest)(nil), // 70: state.v1.ListCapturesRequest + (*ListCapturesResponse)(nil), // 71: state.v1.ListCapturesResponse + (*StreamCapturesRequest)(nil), // 72: state.v1.StreamCapturesRequest + (*StreamCapturesResponse)(nil), // 73: state.v1.StreamCapturesResponse + (*InsertMappingRequest)(nil), // 74: state.v1.InsertMappingRequest + (*InsertMappingResponse)(nil), // 75: state.v1.InsertMappingResponse + (*GetMappingRequest)(nil), // 76: state.v1.GetMappingRequest + (*GetMappingResponse)(nil), // 77: state.v1.GetMappingResponse + (*ListMappingsRequest)(nil), // 78: state.v1.ListMappingsRequest + (*ListMappingsResponse)(nil), // 79: state.v1.ListMappingsResponse + (*UpdateMappingRequest)(nil), // 80: state.v1.UpdateMappingRequest + (*UpdateMappingResponse)(nil), // 81: state.v1.UpdateMappingResponse + (*DeleteMappingRequest)(nil), // 82: state.v1.DeleteMappingRequest + (*DeleteMappingResponse)(nil), // 83: state.v1.DeleteMappingResponse + (*InsertBindingRequest)(nil), // 84: state.v1.InsertBindingRequest + (*InsertBindingResponse)(nil), // 85: state.v1.InsertBindingResponse + (*GetBindingRequest)(nil), // 86: state.v1.GetBindingRequest + (*GetBindingResponse)(nil), // 87: state.v1.GetBindingResponse + (*ListBindingsRequest)(nil), // 88: state.v1.ListBindingsRequest + (*ListBindingsResponse)(nil), // 89: state.v1.ListBindingsResponse + (*UpdateBindingRequest)(nil), // 90: state.v1.UpdateBindingRequest + (*UpdateBindingResponse)(nil), // 91: state.v1.UpdateBindingResponse + (*DeleteBindingRequest)(nil), // 92: state.v1.DeleteBindingRequest + (*DeleteBindingResponse)(nil), // 93: state.v1.DeleteBindingResponse + (*ApproveBindingRequest)(nil), // 94: state.v1.ApproveBindingRequest + (*ApproveBindingResponse)(nil), // 95: state.v1.ApproveBindingResponse + (*ArmedBindingsForSourceRequest)(nil), // 96: state.v1.ArmedBindingsForSourceRequest + (*ArmedBindingsForSourceResponse)(nil), // 97: state.v1.ArmedBindingsForSourceResponse + (*RecordDispatchRequest)(nil), // 98: state.v1.RecordDispatchRequest + (*RecordDispatchResponse)(nil), // 99: state.v1.RecordDispatchResponse + (*ListUndispatchedCapturesRequest)(nil), // 100: state.v1.ListUndispatchedCapturesRequest + (*ListUndispatchedCapturesResponse)(nil), // 101: state.v1.ListUndispatchedCapturesResponse + (*StreamUndispatchedCapturesRequest)(nil), // 102: state.v1.StreamUndispatchedCapturesRequest + (*StreamUndispatchedCapturesResponse)(nil), // 103: state.v1.StreamUndispatchedCapturesResponse + (*EnqueueBindingTaskRequest)(nil), // 104: state.v1.EnqueueBindingTaskRequest + (*EnqueueBindingTaskResponse)(nil), // 105: state.v1.EnqueueBindingTaskResponse + nil, // 106: state.v1.StatusCountsResponse.CountsEntry + (*timestamppb.Timestamp)(nil), // 107: google.protobuf.Timestamp } var file_state_v1_state_proto_depIdxs = []int32{ - 102, // 0: state.v1.Task.created_at:type_name -> google.protobuf.Timestamp - 102, // 1: state.v1.Task.updated_at:type_name -> google.protobuf.Timestamp - 102, // 2: state.v1.Event.at:type_name -> google.protobuf.Timestamp - 102, // 3: state.v1.CapturedEvent.received_at:type_name -> google.protobuf.Timestamp + 107, // 0: state.v1.Task.created_at:type_name -> google.protobuf.Timestamp + 107, // 1: state.v1.Task.updated_at:type_name -> google.protobuf.Timestamp + 107, // 2: state.v1.Event.at:type_name -> google.protobuf.Timestamp + 107, // 3: state.v1.CapturedEvent.received_at:type_name -> google.protobuf.Timestamp 7, // 4: state.v1.Mapping.fields:type_name -> state.v1.MappingField - 102, // 5: state.v1.Mapping.created_at:type_name -> google.protobuf.Timestamp - 102, // 6: state.v1.Mapping.updated_at:type_name -> google.protobuf.Timestamp + 107, // 5: state.v1.Mapping.created_at:type_name -> google.protobuf.Timestamp + 107, // 6: state.v1.Mapping.updated_at:type_name -> google.protobuf.Timestamp 9, // 7: state.v1.Binding.matcher:type_name -> state.v1.BindingMatcher - 102, // 8: state.v1.Binding.created_at:type_name -> google.protobuf.Timestamp - 102, // 9: state.v1.Binding.updated_at:type_name -> google.protobuf.Timestamp + 107, // 8: state.v1.Binding.created_at:type_name -> google.protobuf.Timestamp + 107, // 9: state.v1.Binding.updated_at:type_name -> google.protobuf.Timestamp 4, // 10: state.v1.EnqueueChatTaskResponse.task:type_name -> state.v1.Task 4, // 11: state.v1.ClaimNextResponse.task:type_name -> state.v1.Task 4, // 12: state.v1.ClaimByIssueResponse.task:type_name -> state.v1.Task @@ -5807,126 +6239,134 @@ var file_state_v1_state_proto_depIdxs = []int32{ 4, // 16: state.v1.TaskByIDResponse.task:type_name -> state.v1.Task 4, // 17: state.v1.OpenPRsResponse.tasks:type_name -> state.v1.Task 4, // 18: state.v1.TasksResponse.tasks:type_name -> state.v1.Task - 101, // 19: state.v1.StatusCountsResponse.counts:type_name -> state.v1.StatusCountsResponse.CountsEntry + 106, // 19: state.v1.StatusCountsResponse.counts:type_name -> state.v1.StatusCountsResponse.CountsEntry 5, // 20: state.v1.InsertEventRequest.event:type_name -> state.v1.Event 5, // 21: state.v1.EventsSinceResponse.events:type_name -> state.v1.Event 5, // 22: state.v1.TaskEventsResponse.events:type_name -> state.v1.Event 11, // 23: state.v1.WorkflowStatsResponse.stats:type_name -> state.v1.WorkflowStat 12, // 24: state.v1.StageStatsResponse.stats:type_name -> state.v1.StageStat 13, // 25: state.v1.TokensByDayResponse.tokens:type_name -> state.v1.DayTokens - 102, // 26: state.v1.ConfigSnapshot.published_at:type_name -> google.protobuf.Timestamp + 107, // 26: state.v1.ConfigSnapshot.published_at:type_name -> google.protobuf.Timestamp 58, // 27: state.v1.PutConfigSnapshotRequest.snapshot:type_name -> state.v1.ConfigSnapshot 58, // 28: state.v1.GetConfigSnapshotResponse.snapshot:type_name -> state.v1.ConfigSnapshot - 6, // 29: state.v1.InsertCaptureRequest.capture:type_name -> state.v1.CapturedEvent - 6, // 30: state.v1.ListCapturesResponse.captures:type_name -> state.v1.CapturedEvent - 6, // 31: state.v1.StreamCapturesResponse.capture:type_name -> state.v1.CapturedEvent - 8, // 32: state.v1.InsertMappingRequest.mapping:type_name -> state.v1.Mapping - 8, // 33: state.v1.GetMappingResponse.mapping:type_name -> state.v1.Mapping - 8, // 34: state.v1.ListMappingsResponse.mappings:type_name -> state.v1.Mapping - 8, // 35: state.v1.UpdateMappingRequest.mapping:type_name -> state.v1.Mapping - 10, // 36: state.v1.InsertBindingRequest.binding:type_name -> state.v1.Binding - 10, // 37: state.v1.GetBindingResponse.binding:type_name -> state.v1.Binding - 10, // 38: state.v1.ListBindingsResponse.bindings:type_name -> state.v1.Binding - 10, // 39: state.v1.UpdateBindingRequest.binding:type_name -> state.v1.Binding - 10, // 40: state.v1.ArmedBindingsForSourceResponse.bindings:type_name -> state.v1.Binding - 6, // 41: state.v1.ListUndispatchedCapturesResponse.captures:type_name -> state.v1.CapturedEvent - 6, // 42: state.v1.StreamUndispatchedCapturesResponse.capture:type_name -> state.v1.CapturedEvent - 4, // 43: state.v1.EnqueueBindingTaskResponse.task:type_name -> state.v1.Task - 0, // 44: state.v1.StateStoreService.RegisterTaskGrant:input_type -> state.v1.RegisterTaskGrantRequest - 2, // 45: state.v1.StateStoreService.RevokeTaskGrant:input_type -> state.v1.RevokeTaskGrantRequest - 14, // 46: state.v1.StateStoreService.EnqueueIssue:input_type -> state.v1.EnqueueIssueRequest - 16, // 47: state.v1.StateStoreService.EnqueueChatTask:input_type -> state.v1.EnqueueChatTaskRequest - 18, // 48: state.v1.StateStoreService.ClaimNext:input_type -> state.v1.ClaimNextRequest - 20, // 49: state.v1.StateStoreService.ClaimByIssue:input_type -> state.v1.ClaimByIssueRequest - 22, // 50: state.v1.StateStoreService.Transition:input_type -> state.v1.TransitionRequest - 24, // 51: state.v1.StateStoreService.Update:input_type -> state.v1.UpdateRequest - 26, // 52: state.v1.StateStoreService.Requeue:input_type -> state.v1.RequeueRequest - 28, // 53: state.v1.StateStoreService.RecoverStale:input_type -> state.v1.RecoverStaleRequest - 30, // 54: state.v1.StateStoreService.ArchiveTask:input_type -> state.v1.ArchiveTaskRequest - 32, // 55: state.v1.StateStoreService.RetryTask:input_type -> state.v1.RetryTaskRequest - 34, // 56: state.v1.StateStoreService.TaskByIssue:input_type -> state.v1.TaskByIssueRequest - 36, // 57: state.v1.StateStoreService.TaskByID:input_type -> state.v1.TaskByIDRequest - 38, // 58: state.v1.StateStoreService.OpenPRs:input_type -> state.v1.OpenPRsRequest - 40, // 59: state.v1.StateStoreService.ClearTerminalTasks:input_type -> state.v1.ClearTerminalTasksRequest - 42, // 60: state.v1.StateStoreService.Tasks:input_type -> state.v1.TasksRequest - 44, // 61: state.v1.StateStoreService.StatusCounts:input_type -> state.v1.StatusCountsRequest - 46, // 62: state.v1.StateStoreService.InsertEvent:input_type -> state.v1.InsertEventRequest - 48, // 63: state.v1.StateStoreService.EventsSince:input_type -> state.v1.EventsSinceRequest - 50, // 64: state.v1.StateStoreService.TaskEvents:input_type -> state.v1.TaskEventsRequest - 52, // 65: state.v1.StateStoreService.WorkflowStats:input_type -> state.v1.WorkflowStatsRequest - 54, // 66: state.v1.StateStoreService.StageStats:input_type -> state.v1.StageStatsRequest - 56, // 67: state.v1.StateStoreService.TokensByDay:input_type -> state.v1.TokensByDayRequest - 59, // 68: state.v1.StateStoreService.PutConfigSnapshot:input_type -> state.v1.PutConfigSnapshotRequest - 61, // 69: state.v1.StateStoreService.GetConfigSnapshot:input_type -> state.v1.GetConfigSnapshotRequest - 63, // 70: state.v1.StateStoreService.InsertCapture:input_type -> state.v1.InsertCaptureRequest - 65, // 71: state.v1.StateStoreService.ListCaptures:input_type -> state.v1.ListCapturesRequest - 67, // 72: state.v1.StateStoreService.StreamCaptures:input_type -> state.v1.StreamCapturesRequest - 69, // 73: state.v1.StateStoreService.InsertMapping:input_type -> state.v1.InsertMappingRequest - 71, // 74: state.v1.StateStoreService.GetMapping:input_type -> state.v1.GetMappingRequest - 73, // 75: state.v1.StateStoreService.ListMappings:input_type -> state.v1.ListMappingsRequest - 75, // 76: state.v1.StateStoreService.UpdateMapping:input_type -> state.v1.UpdateMappingRequest - 77, // 77: state.v1.StateStoreService.DeleteMapping:input_type -> state.v1.DeleteMappingRequest - 79, // 78: state.v1.StateStoreService.InsertBinding:input_type -> state.v1.InsertBindingRequest - 81, // 79: state.v1.StateStoreService.GetBinding:input_type -> state.v1.GetBindingRequest - 83, // 80: state.v1.StateStoreService.ListBindings:input_type -> state.v1.ListBindingsRequest - 85, // 81: state.v1.StateStoreService.UpdateBinding:input_type -> state.v1.UpdateBindingRequest - 87, // 82: state.v1.StateStoreService.DeleteBinding:input_type -> state.v1.DeleteBindingRequest - 89, // 83: state.v1.StateStoreService.ApproveBinding:input_type -> state.v1.ApproveBindingRequest - 91, // 84: state.v1.StateStoreService.ArmedBindingsForSource:input_type -> state.v1.ArmedBindingsForSourceRequest - 93, // 85: state.v1.StateStoreService.RecordDispatch:input_type -> state.v1.RecordDispatchRequest - 95, // 86: state.v1.StateStoreService.ListUndispatchedCaptures:input_type -> state.v1.ListUndispatchedCapturesRequest - 97, // 87: state.v1.StateStoreService.StreamUndispatchedCaptures:input_type -> state.v1.StreamUndispatchedCapturesRequest - 99, // 88: state.v1.StateStoreService.EnqueueBindingTask:input_type -> state.v1.EnqueueBindingTaskRequest - 1, // 89: state.v1.StateStoreService.RegisterTaskGrant:output_type -> state.v1.RegisterTaskGrantResponse - 3, // 90: state.v1.StateStoreService.RevokeTaskGrant:output_type -> state.v1.RevokeTaskGrantResponse - 15, // 91: state.v1.StateStoreService.EnqueueIssue:output_type -> state.v1.EnqueueIssueResponse - 17, // 92: state.v1.StateStoreService.EnqueueChatTask:output_type -> state.v1.EnqueueChatTaskResponse - 19, // 93: state.v1.StateStoreService.ClaimNext:output_type -> state.v1.ClaimNextResponse - 21, // 94: state.v1.StateStoreService.ClaimByIssue:output_type -> state.v1.ClaimByIssueResponse - 23, // 95: state.v1.StateStoreService.Transition:output_type -> state.v1.TransitionResponse - 25, // 96: state.v1.StateStoreService.Update:output_type -> state.v1.UpdateResponse - 27, // 97: state.v1.StateStoreService.Requeue:output_type -> state.v1.RequeueResponse - 29, // 98: state.v1.StateStoreService.RecoverStale:output_type -> state.v1.RecoverStaleResponse - 31, // 99: state.v1.StateStoreService.ArchiveTask:output_type -> state.v1.ArchiveTaskResponse - 33, // 100: state.v1.StateStoreService.RetryTask:output_type -> state.v1.RetryTaskResponse - 35, // 101: state.v1.StateStoreService.TaskByIssue:output_type -> state.v1.TaskByIssueResponse - 37, // 102: state.v1.StateStoreService.TaskByID:output_type -> state.v1.TaskByIDResponse - 39, // 103: state.v1.StateStoreService.OpenPRs:output_type -> state.v1.OpenPRsResponse - 41, // 104: state.v1.StateStoreService.ClearTerminalTasks:output_type -> state.v1.ClearTerminalTasksResponse - 43, // 105: state.v1.StateStoreService.Tasks:output_type -> state.v1.TasksResponse - 45, // 106: state.v1.StateStoreService.StatusCounts:output_type -> state.v1.StatusCountsResponse - 47, // 107: state.v1.StateStoreService.InsertEvent:output_type -> state.v1.InsertEventResponse - 49, // 108: state.v1.StateStoreService.EventsSince:output_type -> state.v1.EventsSinceResponse - 51, // 109: state.v1.StateStoreService.TaskEvents:output_type -> state.v1.TaskEventsResponse - 53, // 110: state.v1.StateStoreService.WorkflowStats:output_type -> state.v1.WorkflowStatsResponse - 55, // 111: state.v1.StateStoreService.StageStats:output_type -> state.v1.StageStatsResponse - 57, // 112: state.v1.StateStoreService.TokensByDay:output_type -> state.v1.TokensByDayResponse - 60, // 113: state.v1.StateStoreService.PutConfigSnapshot:output_type -> state.v1.PutConfigSnapshotResponse - 62, // 114: state.v1.StateStoreService.GetConfigSnapshot:output_type -> state.v1.GetConfigSnapshotResponse - 64, // 115: state.v1.StateStoreService.InsertCapture:output_type -> state.v1.InsertCaptureResponse - 66, // 116: state.v1.StateStoreService.ListCaptures:output_type -> state.v1.ListCapturesResponse - 68, // 117: state.v1.StateStoreService.StreamCaptures:output_type -> state.v1.StreamCapturesResponse - 70, // 118: state.v1.StateStoreService.InsertMapping:output_type -> state.v1.InsertMappingResponse - 72, // 119: state.v1.StateStoreService.GetMapping:output_type -> state.v1.GetMappingResponse - 74, // 120: state.v1.StateStoreService.ListMappings:output_type -> state.v1.ListMappingsResponse - 76, // 121: state.v1.StateStoreService.UpdateMapping:output_type -> state.v1.UpdateMappingResponse - 78, // 122: state.v1.StateStoreService.DeleteMapping:output_type -> state.v1.DeleteMappingResponse - 80, // 123: state.v1.StateStoreService.InsertBinding:output_type -> state.v1.InsertBindingResponse - 82, // 124: state.v1.StateStoreService.GetBinding:output_type -> state.v1.GetBindingResponse - 84, // 125: state.v1.StateStoreService.ListBindings:output_type -> state.v1.ListBindingsResponse - 86, // 126: state.v1.StateStoreService.UpdateBinding:output_type -> state.v1.UpdateBindingResponse - 88, // 127: state.v1.StateStoreService.DeleteBinding:output_type -> state.v1.DeleteBindingResponse - 90, // 128: state.v1.StateStoreService.ApproveBinding:output_type -> state.v1.ApproveBindingResponse - 92, // 129: state.v1.StateStoreService.ArmedBindingsForSource:output_type -> state.v1.ArmedBindingsForSourceResponse - 94, // 130: state.v1.StateStoreService.RecordDispatch:output_type -> state.v1.RecordDispatchResponse - 96, // 131: state.v1.StateStoreService.ListUndispatchedCaptures:output_type -> state.v1.ListUndispatchedCapturesResponse - 98, // 132: state.v1.StateStoreService.StreamUndispatchedCaptures:output_type -> state.v1.StreamUndispatchedCapturesResponse - 100, // 133: state.v1.StateStoreService.EnqueueBindingTask:output_type -> state.v1.EnqueueBindingTaskResponse - 89, // [89:134] is the sub-list for method output_type - 44, // [44:89] is the sub-list for method input_type - 44, // [44:44] is the sub-list for extension type_name - 44, // [44:44] is the sub-list for extension extendee - 0, // [0:44] is the sub-list for field type_name + 107, // 29: state.v1.TaskLogEntry.time:type_name -> google.protobuf.Timestamp + 107, // 30: state.v1.ReadTaskLogRequest.since:type_name -> google.protobuf.Timestamp + 107, // 31: state.v1.ReadTaskLogRequest.until:type_name -> google.protobuf.Timestamp + 63, // 32: state.v1.ReadTaskLogResponse.entries:type_name -> state.v1.TaskLogEntry + 6, // 33: state.v1.InsertCaptureRequest.capture:type_name -> state.v1.CapturedEvent + 6, // 34: state.v1.ListCapturesResponse.captures:type_name -> state.v1.CapturedEvent + 6, // 35: state.v1.StreamCapturesResponse.capture:type_name -> state.v1.CapturedEvent + 8, // 36: state.v1.InsertMappingRequest.mapping:type_name -> state.v1.Mapping + 8, // 37: state.v1.GetMappingResponse.mapping:type_name -> state.v1.Mapping + 8, // 38: state.v1.ListMappingsResponse.mappings:type_name -> state.v1.Mapping + 8, // 39: state.v1.UpdateMappingRequest.mapping:type_name -> state.v1.Mapping + 10, // 40: state.v1.InsertBindingRequest.binding:type_name -> state.v1.Binding + 10, // 41: state.v1.GetBindingResponse.binding:type_name -> state.v1.Binding + 10, // 42: state.v1.ListBindingsResponse.bindings:type_name -> state.v1.Binding + 10, // 43: state.v1.UpdateBindingRequest.binding:type_name -> state.v1.Binding + 10, // 44: state.v1.ArmedBindingsForSourceResponse.bindings:type_name -> state.v1.Binding + 6, // 45: state.v1.ListUndispatchedCapturesResponse.captures:type_name -> state.v1.CapturedEvent + 6, // 46: state.v1.StreamUndispatchedCapturesResponse.capture:type_name -> state.v1.CapturedEvent + 4, // 47: state.v1.EnqueueBindingTaskResponse.task:type_name -> state.v1.Task + 0, // 48: state.v1.StateStoreService.RegisterTaskGrant:input_type -> state.v1.RegisterTaskGrantRequest + 2, // 49: state.v1.StateStoreService.RevokeTaskGrant:input_type -> state.v1.RevokeTaskGrantRequest + 14, // 50: state.v1.StateStoreService.EnqueueIssue:input_type -> state.v1.EnqueueIssueRequest + 16, // 51: state.v1.StateStoreService.EnqueueChatTask:input_type -> state.v1.EnqueueChatTaskRequest + 18, // 52: state.v1.StateStoreService.ClaimNext:input_type -> state.v1.ClaimNextRequest + 20, // 53: state.v1.StateStoreService.ClaimByIssue:input_type -> state.v1.ClaimByIssueRequest + 22, // 54: state.v1.StateStoreService.Transition:input_type -> state.v1.TransitionRequest + 24, // 55: state.v1.StateStoreService.Update:input_type -> state.v1.UpdateRequest + 26, // 56: state.v1.StateStoreService.Requeue:input_type -> state.v1.RequeueRequest + 28, // 57: state.v1.StateStoreService.RecoverStale:input_type -> state.v1.RecoverStaleRequest + 30, // 58: state.v1.StateStoreService.ArchiveTask:input_type -> state.v1.ArchiveTaskRequest + 32, // 59: state.v1.StateStoreService.RetryTask:input_type -> state.v1.RetryTaskRequest + 34, // 60: state.v1.StateStoreService.TaskByIssue:input_type -> state.v1.TaskByIssueRequest + 36, // 61: state.v1.StateStoreService.TaskByID:input_type -> state.v1.TaskByIDRequest + 38, // 62: state.v1.StateStoreService.OpenPRs:input_type -> state.v1.OpenPRsRequest + 40, // 63: state.v1.StateStoreService.ClearTerminalTasks:input_type -> state.v1.ClearTerminalTasksRequest + 42, // 64: state.v1.StateStoreService.Tasks:input_type -> state.v1.TasksRequest + 44, // 65: state.v1.StateStoreService.StatusCounts:input_type -> state.v1.StatusCountsRequest + 46, // 66: state.v1.StateStoreService.InsertEvent:input_type -> state.v1.InsertEventRequest + 48, // 67: state.v1.StateStoreService.EventsSince:input_type -> state.v1.EventsSinceRequest + 50, // 68: state.v1.StateStoreService.TaskEvents:input_type -> state.v1.TaskEventsRequest + 52, // 69: state.v1.StateStoreService.WorkflowStats:input_type -> state.v1.WorkflowStatsRequest + 54, // 70: state.v1.StateStoreService.StageStats:input_type -> state.v1.StageStatsRequest + 56, // 71: state.v1.StateStoreService.TokensByDay:input_type -> state.v1.TokensByDayRequest + 59, // 72: state.v1.StateStoreService.PutConfigSnapshot:input_type -> state.v1.PutConfigSnapshotRequest + 61, // 73: state.v1.StateStoreService.GetConfigSnapshot:input_type -> state.v1.GetConfigSnapshotRequest + 64, // 74: state.v1.StateStoreService.ReadTaskLog:input_type -> state.v1.ReadTaskLogRequest + 66, // 75: state.v1.StateStoreService.StreamTaskLogContent:input_type -> state.v1.StreamTaskLogContentRequest + 68, // 76: state.v1.StateStoreService.InsertCapture:input_type -> state.v1.InsertCaptureRequest + 70, // 77: state.v1.StateStoreService.ListCaptures:input_type -> state.v1.ListCapturesRequest + 72, // 78: state.v1.StateStoreService.StreamCaptures:input_type -> state.v1.StreamCapturesRequest + 74, // 79: state.v1.StateStoreService.InsertMapping:input_type -> state.v1.InsertMappingRequest + 76, // 80: state.v1.StateStoreService.GetMapping:input_type -> state.v1.GetMappingRequest + 78, // 81: state.v1.StateStoreService.ListMappings:input_type -> state.v1.ListMappingsRequest + 80, // 82: state.v1.StateStoreService.UpdateMapping:input_type -> state.v1.UpdateMappingRequest + 82, // 83: state.v1.StateStoreService.DeleteMapping:input_type -> state.v1.DeleteMappingRequest + 84, // 84: state.v1.StateStoreService.InsertBinding:input_type -> state.v1.InsertBindingRequest + 86, // 85: state.v1.StateStoreService.GetBinding:input_type -> state.v1.GetBindingRequest + 88, // 86: state.v1.StateStoreService.ListBindings:input_type -> state.v1.ListBindingsRequest + 90, // 87: state.v1.StateStoreService.UpdateBinding:input_type -> state.v1.UpdateBindingRequest + 92, // 88: state.v1.StateStoreService.DeleteBinding:input_type -> state.v1.DeleteBindingRequest + 94, // 89: state.v1.StateStoreService.ApproveBinding:input_type -> state.v1.ApproveBindingRequest + 96, // 90: state.v1.StateStoreService.ArmedBindingsForSource:input_type -> state.v1.ArmedBindingsForSourceRequest + 98, // 91: state.v1.StateStoreService.RecordDispatch:input_type -> state.v1.RecordDispatchRequest + 100, // 92: state.v1.StateStoreService.ListUndispatchedCaptures:input_type -> state.v1.ListUndispatchedCapturesRequest + 102, // 93: state.v1.StateStoreService.StreamUndispatchedCaptures:input_type -> state.v1.StreamUndispatchedCapturesRequest + 104, // 94: state.v1.StateStoreService.EnqueueBindingTask:input_type -> state.v1.EnqueueBindingTaskRequest + 1, // 95: state.v1.StateStoreService.RegisterTaskGrant:output_type -> state.v1.RegisterTaskGrantResponse + 3, // 96: state.v1.StateStoreService.RevokeTaskGrant:output_type -> state.v1.RevokeTaskGrantResponse + 15, // 97: state.v1.StateStoreService.EnqueueIssue:output_type -> state.v1.EnqueueIssueResponse + 17, // 98: state.v1.StateStoreService.EnqueueChatTask:output_type -> state.v1.EnqueueChatTaskResponse + 19, // 99: state.v1.StateStoreService.ClaimNext:output_type -> state.v1.ClaimNextResponse + 21, // 100: state.v1.StateStoreService.ClaimByIssue:output_type -> state.v1.ClaimByIssueResponse + 23, // 101: state.v1.StateStoreService.Transition:output_type -> state.v1.TransitionResponse + 25, // 102: state.v1.StateStoreService.Update:output_type -> state.v1.UpdateResponse + 27, // 103: state.v1.StateStoreService.Requeue:output_type -> state.v1.RequeueResponse + 29, // 104: state.v1.StateStoreService.RecoverStale:output_type -> state.v1.RecoverStaleResponse + 31, // 105: state.v1.StateStoreService.ArchiveTask:output_type -> state.v1.ArchiveTaskResponse + 33, // 106: state.v1.StateStoreService.RetryTask:output_type -> state.v1.RetryTaskResponse + 35, // 107: state.v1.StateStoreService.TaskByIssue:output_type -> state.v1.TaskByIssueResponse + 37, // 108: state.v1.StateStoreService.TaskByID:output_type -> state.v1.TaskByIDResponse + 39, // 109: state.v1.StateStoreService.OpenPRs:output_type -> state.v1.OpenPRsResponse + 41, // 110: state.v1.StateStoreService.ClearTerminalTasks:output_type -> state.v1.ClearTerminalTasksResponse + 43, // 111: state.v1.StateStoreService.Tasks:output_type -> state.v1.TasksResponse + 45, // 112: state.v1.StateStoreService.StatusCounts:output_type -> state.v1.StatusCountsResponse + 47, // 113: state.v1.StateStoreService.InsertEvent:output_type -> state.v1.InsertEventResponse + 49, // 114: state.v1.StateStoreService.EventsSince:output_type -> state.v1.EventsSinceResponse + 51, // 115: state.v1.StateStoreService.TaskEvents:output_type -> state.v1.TaskEventsResponse + 53, // 116: state.v1.StateStoreService.WorkflowStats:output_type -> state.v1.WorkflowStatsResponse + 55, // 117: state.v1.StateStoreService.StageStats:output_type -> state.v1.StageStatsResponse + 57, // 118: state.v1.StateStoreService.TokensByDay:output_type -> state.v1.TokensByDayResponse + 60, // 119: state.v1.StateStoreService.PutConfigSnapshot:output_type -> state.v1.PutConfigSnapshotResponse + 62, // 120: state.v1.StateStoreService.GetConfigSnapshot:output_type -> state.v1.GetConfigSnapshotResponse + 65, // 121: state.v1.StateStoreService.ReadTaskLog:output_type -> state.v1.ReadTaskLogResponse + 67, // 122: state.v1.StateStoreService.StreamTaskLogContent:output_type -> state.v1.StreamTaskLogContentResponse + 69, // 123: state.v1.StateStoreService.InsertCapture:output_type -> state.v1.InsertCaptureResponse + 71, // 124: state.v1.StateStoreService.ListCaptures:output_type -> state.v1.ListCapturesResponse + 73, // 125: state.v1.StateStoreService.StreamCaptures:output_type -> state.v1.StreamCapturesResponse + 75, // 126: state.v1.StateStoreService.InsertMapping:output_type -> state.v1.InsertMappingResponse + 77, // 127: state.v1.StateStoreService.GetMapping:output_type -> state.v1.GetMappingResponse + 79, // 128: state.v1.StateStoreService.ListMappings:output_type -> state.v1.ListMappingsResponse + 81, // 129: state.v1.StateStoreService.UpdateMapping:output_type -> state.v1.UpdateMappingResponse + 83, // 130: state.v1.StateStoreService.DeleteMapping:output_type -> state.v1.DeleteMappingResponse + 85, // 131: state.v1.StateStoreService.InsertBinding:output_type -> state.v1.InsertBindingResponse + 87, // 132: state.v1.StateStoreService.GetBinding:output_type -> state.v1.GetBindingResponse + 89, // 133: state.v1.StateStoreService.ListBindings:output_type -> state.v1.ListBindingsResponse + 91, // 134: state.v1.StateStoreService.UpdateBinding:output_type -> state.v1.UpdateBindingResponse + 93, // 135: state.v1.StateStoreService.DeleteBinding:output_type -> state.v1.DeleteBindingResponse + 95, // 136: state.v1.StateStoreService.ApproveBinding:output_type -> state.v1.ApproveBindingResponse + 97, // 137: state.v1.StateStoreService.ArmedBindingsForSource:output_type -> state.v1.ArmedBindingsForSourceResponse + 99, // 138: state.v1.StateStoreService.RecordDispatch:output_type -> state.v1.RecordDispatchResponse + 101, // 139: state.v1.StateStoreService.ListUndispatchedCaptures:output_type -> state.v1.ListUndispatchedCapturesResponse + 103, // 140: state.v1.StateStoreService.StreamUndispatchedCaptures:output_type -> state.v1.StreamUndispatchedCapturesResponse + 105, // 141: state.v1.StateStoreService.EnqueueBindingTask:output_type -> state.v1.EnqueueBindingTaskResponse + 95, // [95:142] is the sub-list for method output_type + 48, // [48:95] is the sub-list for method input_type + 48, // [48:48] is the sub-list for extension type_name + 48, // [48:48] is the sub-list for extension extendee + 0, // [0:48] is the sub-list for field type_name } func init() { file_state_v1_state_proto_init() } @@ -5940,7 +6380,7 @@ func file_state_v1_state_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_state_v1_state_proto_rawDesc), len(file_state_v1_state_proto_rawDesc)), NumEnums: 0, - NumMessages: 102, + NumMessages: 107, NumExtensions: 0, NumServices: 1, }, diff --git a/internal/contracts/state/v1/state_grpc.pb.go b/internal/contracts/state/v1/state_grpc.pb.go index 62d080609..0a9a05449 100644 --- a/internal/contracts/state/v1/state_grpc.pb.go +++ b/internal/contracts/state/v1/state_grpc.pb.go @@ -45,6 +45,8 @@ const ( StateStoreService_TokensByDay_FullMethodName = "/state.v1.StateStoreService/TokensByDay" StateStoreService_PutConfigSnapshot_FullMethodName = "/state.v1.StateStoreService/PutConfigSnapshot" StateStoreService_GetConfigSnapshot_FullMethodName = "/state.v1.StateStoreService/GetConfigSnapshot" + StateStoreService_ReadTaskLog_FullMethodName = "/state.v1.StateStoreService/ReadTaskLog" + StateStoreService_StreamTaskLogContent_FullMethodName = "/state.v1.StateStoreService/StreamTaskLogContent" StateStoreService_InsertCapture_FullMethodName = "/state.v1.StateStoreService/InsertCapture" StateStoreService_ListCaptures_FullMethodName = "/state.v1.StateStoreService/ListCaptures" StateStoreService_StreamCaptures_FullMethodName = "/state.v1.StateStoreService/StreamCaptures" @@ -114,6 +116,17 @@ type StateStoreServiceClient interface { // configuration page"). PutConfigSnapshot(ctx context.Context, in *PutConfigSnapshotRequest, opts ...grpc.CallOption) (*PutConfigSnapshotResponse, error) GetConfigSnapshot(ctx context.Context, in *GetConfigSnapshotRequest, opts ...grpc.CallOption) (*GetConfigSnapshotResponse, error) + // Task log: one task attempt's persisted log. Task log files live in the + // state directory this process owns, so the dashboard reads them over this + // contract rather than opening them itself + // (docs/prds/ui-service-boundary.md). + ReadTaskLog(ctx context.Context, in *ReadTaskLogRequest, opts ...grpc.CallOption) (*ReadTaskLogResponse, error) + // StreamTaskLogContent returns one attempt's log verbatim, one chunk per + // message, for a download. A log file is unbounded input (it rotates at + // DefaultMaxSizeMB), so a unary response would exceed gRPC's 4MiB message + // cap on a real log -- the same reason ListCaptures was superseded by + // StreamCaptures. + StreamTaskLogContent(ctx context.Context, in *StreamTaskLogContentRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[StreamTaskLogContentResponse], error) // Capture InsertCapture(ctx context.Context, in *InsertCaptureRequest, opts ...grpc.CallOption) (*InsertCaptureResponse, error) // Deprecated: Do not use. @@ -419,6 +432,35 @@ func (c *stateStoreServiceClient) GetConfigSnapshot(ctx context.Context, in *Get return out, nil } +func (c *stateStoreServiceClient) ReadTaskLog(ctx context.Context, in *ReadTaskLogRequest, opts ...grpc.CallOption) (*ReadTaskLogResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ReadTaskLogResponse) + err := c.cc.Invoke(ctx, StateStoreService_ReadTaskLog_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *stateStoreServiceClient) StreamTaskLogContent(ctx context.Context, in *StreamTaskLogContentRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[StreamTaskLogContentResponse], error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + stream, err := c.cc.NewStream(ctx, &StateStoreService_ServiceDesc.Streams[0], StateStoreService_StreamTaskLogContent_FullMethodName, cOpts...) + if err != nil { + return nil, err + } + x := &grpc.GenericClientStream[StreamTaskLogContentRequest, StreamTaskLogContentResponse]{ClientStream: stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type StateStoreService_StreamTaskLogContentClient = grpc.ServerStreamingClient[StreamTaskLogContentResponse] + func (c *stateStoreServiceClient) InsertCapture(ctx context.Context, in *InsertCaptureRequest, opts ...grpc.CallOption) (*InsertCaptureResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(InsertCaptureResponse) @@ -442,7 +484,7 @@ func (c *stateStoreServiceClient) ListCaptures(ctx context.Context, in *ListCapt func (c *stateStoreServiceClient) StreamCaptures(ctx context.Context, in *StreamCapturesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[StreamCapturesResponse], error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - stream, err := c.cc.NewStream(ctx, &StateStoreService_ServiceDesc.Streams[0], StateStoreService_StreamCaptures_FullMethodName, cOpts...) + stream, err := c.cc.NewStream(ctx, &StateStoreService_ServiceDesc.Streams[1], StateStoreService_StreamCaptures_FullMethodName, cOpts...) if err != nil { return nil, err } @@ -602,7 +644,7 @@ func (c *stateStoreServiceClient) ListUndispatchedCaptures(ctx context.Context, func (c *stateStoreServiceClient) StreamUndispatchedCaptures(ctx context.Context, in *StreamUndispatchedCapturesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[StreamUndispatchedCapturesResponse], error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - stream, err := c.cc.NewStream(ctx, &StateStoreService_ServiceDesc.Streams[1], StateStoreService_StreamUndispatchedCaptures_FullMethodName, cOpts...) + stream, err := c.cc.NewStream(ctx, &StateStoreService_ServiceDesc.Streams[2], StateStoreService_StreamUndispatchedCaptures_FullMethodName, cOpts...) if err != nil { return nil, err } @@ -677,6 +719,17 @@ type StateStoreServiceServer interface { // configuration page"). PutConfigSnapshot(context.Context, *PutConfigSnapshotRequest) (*PutConfigSnapshotResponse, error) GetConfigSnapshot(context.Context, *GetConfigSnapshotRequest) (*GetConfigSnapshotResponse, error) + // Task log: one task attempt's persisted log. Task log files live in the + // state directory this process owns, so the dashboard reads them over this + // contract rather than opening them itself + // (docs/prds/ui-service-boundary.md). + ReadTaskLog(context.Context, *ReadTaskLogRequest) (*ReadTaskLogResponse, error) + // StreamTaskLogContent returns one attempt's log verbatim, one chunk per + // message, for a download. A log file is unbounded input (it rotates at + // DefaultMaxSizeMB), so a unary response would exceed gRPC's 4MiB message + // cap on a real log -- the same reason ListCaptures was superseded by + // StreamCaptures. + StreamTaskLogContent(*StreamTaskLogContentRequest, grpc.ServerStreamingServer[StreamTaskLogContentResponse]) error // Capture InsertCapture(context.Context, *InsertCaptureRequest) (*InsertCaptureResponse, error) // Deprecated: Do not use. @@ -800,6 +853,12 @@ func (UnimplementedStateStoreServiceServer) PutConfigSnapshot(context.Context, * func (UnimplementedStateStoreServiceServer) GetConfigSnapshot(context.Context, *GetConfigSnapshotRequest) (*GetConfigSnapshotResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetConfigSnapshot not implemented") } +func (UnimplementedStateStoreServiceServer) ReadTaskLog(context.Context, *ReadTaskLogRequest) (*ReadTaskLogResponse, error) { + return nil, status.Error(codes.Unimplemented, "method ReadTaskLog not implemented") +} +func (UnimplementedStateStoreServiceServer) StreamTaskLogContent(*StreamTaskLogContentRequest, grpc.ServerStreamingServer[StreamTaskLogContentResponse]) error { + return status.Error(codes.Unimplemented, "method StreamTaskLogContent not implemented") +} func (UnimplementedStateStoreServiceServer) InsertCapture(context.Context, *InsertCaptureRequest) (*InsertCaptureResponse, error) { return nil, status.Error(codes.Unimplemented, "method InsertCapture not implemented") } @@ -1346,6 +1405,35 @@ func _StateStoreService_GetConfigSnapshot_Handler(srv interface{}, ctx context.C return interceptor(ctx, in, info, handler) } +func _StateStoreService_ReadTaskLog_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ReadTaskLogRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(StateStoreServiceServer).ReadTaskLog(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: StateStoreService_ReadTaskLog_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(StateStoreServiceServer).ReadTaskLog(ctx, req.(*ReadTaskLogRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _StateStoreService_StreamTaskLogContent_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(StreamTaskLogContentRequest) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(StateStoreServiceServer).StreamTaskLogContent(m, &grpc.GenericServerStream[StreamTaskLogContentRequest, StreamTaskLogContentResponse]{ServerStream: stream}) +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type StateStoreService_StreamTaskLogContentServer = grpc.ServerStreamingServer[StreamTaskLogContentResponse] + func _StateStoreService_InsertCapture_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(InsertCaptureRequest) if err := dec(in); err != nil { @@ -1785,6 +1873,10 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{ MethodName: "GetConfigSnapshot", Handler: _StateStoreService_GetConfigSnapshot_Handler, }, + { + MethodName: "ReadTaskLog", + Handler: _StateStoreService_ReadTaskLog_Handler, + }, { MethodName: "InsertCapture", Handler: _StateStoreService_InsertCapture_Handler, @@ -1855,6 +1947,11 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{ }, }, Streams: []grpc.StreamDesc{ + { + StreamName: "StreamTaskLogContent", + Handler: _StateStoreService_StreamTaskLogContent_Handler, + ServerStreams: true, + }, { StreamName: "StreamCaptures", Handler: _StateStoreService_StreamCaptures_Handler, diff --git a/internal/domain/storecontract/storecontract.go b/internal/domain/storecontract/storecontract.go index 6766ddd1a..6f9b280d3 100644 --- a/internal/domain/storecontract/storecontract.go +++ b/internal/domain/storecontract/storecontract.go @@ -18,12 +18,14 @@ package storecontract import ( "context" "errors" + "io" "time" "github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/mapping" "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/events" + "github.com/samcharles93/archie-core/internal/logging" ) // TaskStore is the full store surface the daemon needs. @@ -160,6 +162,27 @@ type BindingTaskCreator interface { EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity string, bindingID int64, bindingVersion int) (*task.Task, error) } +// TaskLogStore reads one task attempt's persisted log. Deliberately separate +// from TaskQueries: the log is not a row, it is a file the logging package +// owns the format of, and a process that can read the task board should not +// have to acquire a log reader to do it. The dashboard's UI process is the +// consumer this exists for -- it holds no daemon-local file handle, so the +// read crosses the State Store contract (docs/prds/ui-service-boundary.md). +// +// Found=false with a nil error is the not-found convention every read here +// uses, and it is load-bearing: "this attempt has no log" is not "this +// process cannot read logs". The second one is an error +// (logging.ErrTaskLogsUnavailable), because a caller that conflates them +// reports a configuration change where none is needed. +type TaskLogStore interface { + // TaskLog returns a page of one attempt's decoded log. attempt 0 selects + // the task's current attempt. + TaskLog(ctx context.Context, taskID int64, attempt int, q logging.Query) (logging.TaskLogPage, error) + // TaskLogContent writes one attempt's log verbatim to w, for a download. + // found is false, with a nil error, when the attempt has no log file. + TaskLogContent(ctx context.Context, taskID int64, attempt int, w io.Writer) (found bool, err error) +} + // CapturedEvent is one unbound inbound webhook capture: no workflow binding, // no forge/task association -- just what arrived, from where, and when. // See docs/prds/event-capture-storage.md. diff --git a/internal/infrastructure/staterpc/client.go b/internal/infrastructure/staterpc/client.go index 817cdee86..958cc4d6d 100644 --- a/internal/infrastructure/staterpc/client.go +++ b/internal/infrastructure/staterpc/client.go @@ -14,6 +14,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/events" + "github.com/samcharles93/archie-core/internal/logging" ) // Client is the single remote adapter wrapping one StateStoreServiceClient, @@ -36,6 +37,7 @@ func (c *Client) Close() error { return nil } var ( _ task.Store = (*Client)(nil) _ storecontract.TaskStore = (*Client)(nil) + _ storecontract.TaskLogStore = (*Client)(nil) _ storecontract.CaptureStore = (*Client)(nil) _ storecontract.MappingStore = (*Client)(nil) _ storecontract.BindingStore = (*Client)(nil) @@ -417,6 +419,58 @@ func (c *Client) EnqueueBindingTask(ctx context.Context, owner, repo, title, bod return taskValue(r.Task), nil } +// Task log + +// TaskLog reads one task attempt's decoded log over the wire. found=false with +// a nil error is the attempt-has-no-log answer; a process with no reader at +// all comes back as an unavailable error, not as an empty page, so a caller +// can tell the two apart. +func (c *Client) TaskLog(ctx context.Context, taskID int64, attempt int, q logging.Query) (logging.TaskLogPage, error) { + r, err := c.client.ReadTaskLog(ctx, taskLogRequestProto(taskID, attempt, q)) + if err != nil { + return logging.TaskLogPage{}, unmapError(err) + } + if !r.Found { + return logging.TaskLogPage{ + Entries: []logging.Entry{}, + Components: []string{}, + }, nil + } + return logging.TaskLogPage{ + Entries: mapValues(r.Entries, taskLogEntryValue), + Truncated: r.Truncated, + File: r.File, + Found: true, + Components: r.Components, + }, nil +} + +// TaskLogContent streams one attempt's log verbatim into w, for a download. +// found is false, with a nil error, when the attempt has no log file. +func (c *Client) TaskLogContent(ctx context.Context, taskID int64, attempt int, w io.Writer) (bool, error) { + stream, err := c.client.StreamTaskLogContent(ctx, &pb.StreamTaskLogContentRequest{TaskId: taskID, Attempt: int64(attempt)}) + if err != nil { + return false, unmapError(err) + } + found := false + for { + r, err := stream.Recv() + if errors.Is(err, io.EOF) { + return found, nil + } + if err != nil { + return found, unmapError(err) + } + found = found || r.Found + if len(r.Chunk) == 0 { + continue + } + if _, err := w.Write(r.Chunk); err != nil { + return found, err + } + } +} + func derefTasks(in []*pb.Task) []task.Task { if in == nil { return nil diff --git a/internal/infrastructure/staterpc/conformance_test.go b/internal/infrastructure/staterpc/conformance_test.go index 9902a5438..90d1a9f92 100644 --- a/internal/infrastructure/staterpc/conformance_test.go +++ b/internal/infrastructure/staterpc/conformance_test.go @@ -31,13 +31,31 @@ type contract interface { store.ConfigSnapshotStore } +// taskLogContract is the task-log read group, driven separately because it is +// not a *store.Store surface: the reader is internal/logging's own registry, +// which owns the log format, so the local side of this contract is a registry +// rather than a store. +type taskLogContract interface { + store.TaskLogStore +} + func remoteContract(t *testing.T, local *store.Store) contract { + t.Helper() + return remoteTaskStore(t, local, nil) +} + +// remoteTaskStore serves local behind a bufconn listener with a task-log +// reader attached, and returns a client for it. The reader is a parameter +// because the log files are internal/logging's, not the store's: this contract +// fronts a reader rather than a table. +func remoteTaskStore(t *testing.T, local *store.Store, logs store.TaskLogStore) *Client { t.Helper() listener := bufconn.Listen(1 << 20) server := grpc.NewServer() RegisterServer(server, Deps{ Tasks: local, Captures: local, Mappings: local, Bindings: local, BindingDispatcher: local, BindingTaskCreator: local, ConfigSnapshots: local, + TaskLogs: logs, }) go func() { _ = server.Serve(listener) }() t.Cleanup(func() { server.Stop(); _ = listener.Close() }) diff --git a/internal/infrastructure/staterpc/server.go b/internal/infrastructure/staterpc/server.go index ab53cba4e..577969246 100644 --- a/internal/infrastructure/staterpc/server.go +++ b/internal/infrastructure/staterpc/server.go @@ -5,7 +5,9 @@ package staterpc import ( + "bytes" "context" + "errors" "log/slog" "time" @@ -17,6 +19,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/mapping" "github.com/samcharles93/archie-core/internal/domain/storecontract" + "github.com/samcharles93/archie-core/internal/logging" ) // Unavailable-capability errors, mirroring gatewayrpc's missing-session-store @@ -30,10 +33,23 @@ var ( errBindingUnavailable = status.Error(codes.Unavailable, "binding store unavailable") errBindingDispatchUnavailable = status.Error(codes.Unavailable, "binding dispatcher unavailable") errBindingTaskCreatorUnavailable = status.Error(codes.Unavailable, "binding task creator unavailable") + // errTaskLogsUnavailable is the "this process cannot read task logs at + // all" answer, and it is deliberately distinct from a found=false read + // result: only the first is a deployment matter. A dashboard that receives + // this reports that the log cannot be read here; it must never turn it + // into "task logging was not enabled for this run", which is what the + // absent-handle path used to do. + errTaskLogsUnavailable = status.Error(codes.Unavailable, msgTaskLogsUnavailable) ) func timeSeconds(s int64) time.Duration { return time.Duration(s) * time.Second } +// taskLogChunkBytes bounds one streamed message. A log file rotates at +// logging.DefaultMaxSizeMB, well past gRPC's 4MiB unary cap, so the download +// is served in pieces (the same reason StreamCaptures superseded ListCaptures) +// and the pieces must be small enough to carry. +const taskLogChunkBytes = 256 << 10 + // Deps groups the store surfaces the StateStore service fronts. TaskStore is // required; the rest are optional (nil disables that group's RPCs, returning // codes.Unavailable) exactly as their daemon-side consumers already treat a @@ -47,7 +63,14 @@ type Deps struct { Bindings storecontract.BindingStore BindingDispatcher storecontract.BindingDispatcher BindingTaskCreator storecontract.BindingTaskCreator - Log *slog.Logger + // TaskLogs reads one task attempt's persisted log out of the state + // directory this process owns. Optional, and nil is the honest default for + // a store service that shares no state directory with the daemon: + // ReadTaskLog then answers codes.Unavailable, which the dashboard reports + // as "this process cannot read logs" rather than as "this attempt has no + // log". Conflating those two is the bug this contract exists to fix. + TaskLogs storecontract.TaskLogStore + Log *slog.Logger } type server struct { @@ -565,6 +588,117 @@ func (s *server) EnqueueBindingTask(ctx context.Context, r *pb.EnqueueBindingTas return &pb.EnqueueBindingTaskResponse{Task: taskProto(t)}, nil } +// Task log + +func (s *server) taskLogs() (storecontract.TaskLogStore, error) { + if s.deps.TaskLogs == nil { + return nil, errTaskLogsUnavailable + } + return s.deps.TaskLogs, nil +} + +func (s *server) ReadTaskLog(ctx context.Context, r *pb.ReadTaskLogRequest) (*pb.ReadTaskLogResponse, error) { + logs, err := s.taskLogs() + if err != nil { + return nil, err + } + page, err := logs.TaskLog(ctx, r.TaskId, int(r.Attempt), taskLogQueryValue(r)) + if err != nil { + // A store that cannot read its own state directory keeps its own + // identity: this is unavailability, not a missing log, and a caller + // has to be able to tell them apart. + if errors.Is(err, logging.ErrTaskLogsUnavailable) { + return nil, errTaskLogsUnavailable + } + return nil, s.logErr("ReadTaskLog", err) + } + if !page.Found { + return &pb.ReadTaskLogResponse{Attempt: r.Attempt}, nil + } + return &pb.ReadTaskLogResponse{ + Entries: mapValues(page.Entries, taskLogEntryProto), + Truncated: page.Truncated, + Attempt: r.Attempt, + Found: true, + Components: page.Components, + File: page.File, + }, nil +} + +// StreamTaskLogContent sends one attempt's log verbatim, one chunk per +// message, for a download. A single reply reports found=false with no chunks: +// the attempt has no log file, which is a normal state rather than a failure. +func (s *server) StreamTaskLogContent(r *pb.StreamTaskLogContentRequest, stream pb.StateStoreService_StreamTaskLogContentServer) error { + logs, err := s.taskLogs() + if err != nil { + return err + } + // The chunking the client sees is owned by the reader that writes into + // this buffer, so the wire never holds a whole log to re-slice it. + buf := &chunkWriter{stream: stream, attempt: r.Attempt} + found, err := logs.TaskLogContent(stream.Context(), r.TaskId, int(r.Attempt), buf) + if err != nil { + if errors.Is(err, logging.ErrTaskLogsUnavailable) { + return errTaskLogsUnavailable + } + return s.logErr("StreamTaskLogContent", err) + } + if err := buf.flush(); err != nil { + return err + } + // A found log with no bytes still reports found: an attempt whose file is + // empty did produce a log, and found is what tells the download it may + // write an empty file rather than answer 404. + if found && buf.sent { + return nil + } + return stream.Send(&pb.StreamTaskLogContentResponse{Attempt: r.Attempt, Found: found}) +} + +// chunkWriter packs everything a log reader writes into stream-sized messages +// on its way through. It exists so the read can be one io.CopyBuffer of the +// file into this writer: the reader keeps its own chunk size, and the bytes +// are never all held at once. +type chunkWriter struct { + stream pb.StateStoreService_StreamTaskLogContentServer + attempt int64 + pending []byte + // sent records whether any chunk reached the client, which is how the + // caller tells "the file was empty" from "the file was read". + sent bool +} + +func (w *chunkWriter) Write(p []byte) (int, error) { + w.pending = append(w.pending, p...) + for len(w.pending) >= taskLogChunkBytes { + if err := w.emit(w.pending[:taskLogChunkBytes]); err != nil { + return 0, err + } + w.pending = w.pending[taskLogChunkBytes:] + } + return len(p), nil +} + +func (w *chunkWriter) emit(chunk []byte) error { + w.sent = true + // The slice is copied into the message: the reader's buffer is reused + // across writes and must not be aliased by a message in flight. + return w.stream.Send(&pb.StreamTaskLogContentResponse{ + Chunk: bytes.Clone(chunk), + Attempt: w.attempt, + Found: true, + }) +} + +func (w *chunkWriter) flush() error { + if len(w.pending) == 0 { + return nil + } + chunk := w.pending + w.pending = nil + return w.emit(chunk) +} + func mappingProtoPtr(m *mapping.Mapping) *pb.Mapping { if m == nil { return nil diff --git a/internal/infrastructure/staterpc/task_log_test.go b/internal/infrastructure/staterpc/task_log_test.go new file mode 100644 index 000000000..c4a01630b --- /dev/null +++ b/internal/infrastructure/staterpc/task_log_test.go @@ -0,0 +1,200 @@ +package staterpc + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/samcharles93/archie-core/internal/logging" + "github.com/samcharles93/archie-core/internal/store" +) + +// TestTaskLogContract drives the task-log read group through both adapters, +// matching the §11 conformance requirement the rest of this package already +// satisfies: the same battery runs against the local reader (a +// *logging.TaskRegistry over this process's own state directory) and against +// the remote *Client. +// +// The two answers this pins as DIFFERENT are the point of the contract. A +// process with no reader reports unavailability; an attempt with no log file +// reports found=false with no error. A caller that cannot tell those apart +// tells an operator task logging is switched off when it is not. +func TestTaskLogContract(t *testing.T) { + for _, mode := range []string{"local", "grpc"} { + t.Run(mode, func(t *testing.T) { + ctx := t.Context() + baseDir := filepath.Join(t.TempDir(), "logs", "tasks") + reader := logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{}) + + const taskID = 7 + if err := reader.Open(taskID, 0); err != nil { + t.Fatalf("open sink: %v", err) + } + reader.Write(taskID, logging.Entry{Level: "INFO", Message: "starting", Fields: map[string]any{"component": "daemon"}}) + reader.Write(taskID, logging.Entry{Level: "ERROR", Message: "gate failed", Fields: map[string]any{"component": "gate"}}) + if err := reader.Close(taskID); err != nil { + t.Fatalf("close sink: %v", err) + } + + var c taskLogContract = reader + if mode == "grpc" { + c = remoteTaskStore(t, store.OpenTest(t), reader) + } + + t.Run("a page carries the decoded entries and their fields", func(t *testing.T) { + page, err := c.TaskLog(ctx, taskID, 0, logging.Query{}) + if err != nil { + t.Fatalf("TaskLog: %v", err) + } + if !page.Found { + t.Fatal("Found = false for an attempt whose log exists") + } + if len(page.Entries) != 2 { + t.Fatalf("entries = %d, want 2", len(page.Entries)) + } + if page.Entries[1].Message != "gate failed" || page.Entries[1].Level != "ERROR" { + t.Errorf("entry = %+v, want the ERROR line the sink wrote", page.Entries[1]) + } + if got, _ := page.Entries[0].Fields["component"].(string); got != "daemon" { + t.Errorf("fields = %+v, want the structured component to survive the hop", page.Entries[0].Fields) + } + if !strings.HasSuffix(page.File, "attempt-0.jsonl") { + t.Errorf("file = %q, want the attempt's own path", page.File) + } + }) + + t.Run("filters and the limit cross the wire", func(t *testing.T) { + page, err := c.TaskLog(ctx, taskID, 0, logging.Query{Levels: []string{"ERROR"}}) + if err != nil { + t.Fatalf("TaskLog: %v", err) + } + if len(page.Entries) != 1 || page.Entries[0].Message != "gate failed" { + t.Fatalf("level filter = %+v, want just the ERROR line", page.Entries) + } + page, err = c.TaskLog(ctx, taskID, 0, logging.Query{Component: "daemon"}) + if err != nil { + t.Fatalf("TaskLog: %v", err) + } + if len(page.Entries) != 1 || page.Entries[0].Message != "starting" { + t.Fatalf("component filter = %+v, want just the daemon line", page.Entries) + } + page, err = c.TaskLog(ctx, taskID, 0, logging.Query{Contains: "gate"}) + if err != nil { + t.Fatalf("TaskLog: %v", err) + } + if len(page.Entries) != 1 || page.Entries[0].Message != "gate failed" { + t.Fatalf("contains filter = %+v, want just the gate line", page.Entries) + } + page, err = c.TaskLog(ctx, taskID, 0, logging.Query{Limit: 1}) + if err != nil { + t.Fatalf("TaskLog: %v", err) + } + if len(page.Entries) != 1 || !page.Truncated { + t.Fatalf("limit = 1 gave %d entries (truncated %v), want one and a truncated marker", len(page.Entries), page.Truncated) + } + }) + + t.Run("components list what the log actually contains", func(t *testing.T) { + page, err := c.TaskLog(ctx, taskID, 0, logging.Query{}) + if err != nil { + t.Fatalf("TaskLog: %v", err) + } + if len(page.Components) != 2 || page.Components[0] != "daemon" || page.Components[1] != "gate" { + t.Fatalf("components = %v, want the sorted distinct set", page.Components) + } + }) + + t.Run("an attempt with no log is found=false, not an error", func(t *testing.T) { + page, err := c.TaskLog(ctx, taskID, 99, logging.Query{}) + if err != nil { + t.Fatalf("TaskLog for a missing attempt = %v, want no error", err) + } + if page.Found { + t.Error("Found = true for an attempt with no log file") + } + if len(page.Entries) != 0 { + t.Errorf("entries = %+v, want none", page.Entries) + } + }) + + t.Run("content is the file verbatim, and found is false when there is none", func(t *testing.T) { + var buf bytes.Buffer + found, err := c.TaskLogContent(ctx, taskID, 0, &buf) + if err != nil { + t.Fatalf("TaskLogContent: %v", err) + } + if !found { + t.Fatal("found = false for an attempt whose log exists") + } + body := buf.String() + if !strings.Contains(body, "gate failed") || !strings.Contains(body, "starting") { + t.Fatalf("content = %q, want the raw log lines", body) + } + // Byte-for-byte: the contract transports the log, it does not + // re-encode it. Every line must still parse as the package's + // own JSONL. + for line := range strings.Lines(strings.TrimSpace(body)) { + if _, ok := loggingTailDecodes(t, line); !ok { + t.Fatalf("line %q does not decode as the logging package's own format", line) + } + } + + buf.Reset() + found, err = c.TaskLogContent(ctx, taskID, 99, &buf) + if err != nil { + t.Fatalf("TaskLogContent for a missing attempt = %v, want no error", err) + } + if found || buf.Len() != 0 { + t.Errorf("found = %v with %d bytes, want false and nothing", found, buf.Len()) + } + }) + }) + } +} + +// TestTaskLogContractWithoutAReaderIsUnavailable pins the other half of the +// distinction, and the one the dashboard's misleading message came from: a +// service with no task-log reader at all must say UNAVAILABLE rather than +// answer an empty page. An empty page is indistinguishable from an attempt +// that has no log, and the dashboard rendered that as "task logging is +// optional and was not enabled for this run". +func TestTaskLogContractWithoutAReaderIsUnavailable(t *testing.T) { + local := store.OpenTest(t) + // remoteContract leaves Deps.TaskLogs nil, which is what a store service + // sharing no state directory with the daemon looks like. + c := remoteContract(t, local) + logs, ok := c.(taskLogContract) + if !ok { + t.Fatalf("remote client does not carry the task-log contract (%T)", c) + } + + if _, err := logs.TaskLog(t.Context(), 1, 0, logging.Query{}); !errors.Is(err, logging.ErrTaskLogsUnavailable) { + t.Errorf("TaskLog without a reader = %v, want ErrTaskLogsUnavailable; an empty page here is what the dashboard read as \"logging was not enabled\"", err) + } + var buf bytes.Buffer + if _, err := logs.TaskLogContent(t.Context(), 1, 0, &buf); !errors.Is(err, logging.ErrTaskLogsUnavailable) { + t.Errorf("TaskLogContent without a reader = %v, want ErrTaskLogsUnavailable", err) + } +} + +// loggingTailDecodes reports whether one line is a record the logging package +// can decode, using that package's own reader rather than a second opinion +// about its format. +func loggingTailDecodes(t *testing.T, line string) (logging.Entry, bool) { + t.Helper() + path := filepath.Join(t.TempDir(), "one.jsonl") + if err := os.WriteFile(path, []byte(line+"\n"), 0o600); err != nil { + t.Fatalf("write temp log: %v", err) + } + res, err := logging.Tail(path, logging.Query{}) + if err != nil { + t.Fatalf("Tail: %v", err) + } + if len(res.Entries) != 1 { + return logging.Entry{}, false + } + return res.Entries[0], true +} diff --git a/internal/infrastructure/staterpc/values.go b/internal/infrastructure/staterpc/values.go index 3573f98fd..54cdb0895 100644 --- a/internal/infrastructure/staterpc/values.go +++ b/internal/infrastructure/staterpc/values.go @@ -17,6 +17,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/events" + "github.com/samcharles93/archie-core/internal/logging" ) func timestamp(t time.Time) *timestamppb.Timestamp { @@ -245,6 +246,12 @@ const ( msgBindingTransition = "binding transition rejected" msgAlreadyDispatched = "already dispatched" msgInternal = "state store: internal error" + // msgTaskLogsUnavailable is the public phrase for "this service has no + // task-log reader". It is a wire contract like the sentinels above: the + // client rehydrates logging.ErrTaskLogsUnavailable from (Unavailable, this + // message), and a caller depends on that to tell "this process cannot read + // logs" from "this attempt has no log". + msgTaskLogsUnavailable = "task log reader unavailable" ) // mapError converts a store sentinel error into a structured gRPC status @@ -301,6 +308,12 @@ func mapError(err error) error { // *status.Error whose code is DeadlineExceeded or Canceled, so we rehydrate // those back to the standard context sentinels -- otherwise the consumer // would (wrongly) park a task that was merely interrupted. +// +// Unavailable carries one message this package owns: the absent task-log +// reader. It is rehydrated for the same reason the error sentinels are -- +// the dashboard's whole bug was rendering "this process cannot read logs" as +// "the attempt has no log", and only the typed error makes that distinction +// available to a caller. func unmapError(err error) error { if err == nil { return nil @@ -314,6 +327,19 @@ func unmapError(err error) error { return context.Canceled case codes.DeadlineExceeded: return context.DeadlineExceeded + } + if sentinel := sentinelForStatus(st); sentinel != nil { + return sentinel + } + return fmt.Errorf("state store: %s: %w", st.Message(), err) +} + +// sentinelForStatus maps a status to the store or logging sentinel it stands +// for, matched on (code, exact canonical message) -- those message constants +// are part of the wire contract (§4). A code whose message is not one this +// package defines returns nil, so the caller falls back to the wrapped form. +func sentinelForStatus(st *status.Status) error { + switch st.Code() { case codes.FailedPrecondition: switch st.Message() { case msgStaleTransition: @@ -334,8 +360,12 @@ func unmapError(err error) error { if st.Message() == msgAlreadyDispatched { return storecontract.ErrAlreadyDispatched } + case codes.Unavailable: + if st.Message() == msgTaskLogsUnavailable { + return logging.ErrTaskLogsUnavailable + } } - return fmt.Errorf("state store: %s: %w", st.Message(), err) + return nil } // configSnapshotProto and configSnapshotValue carry the dashboard's @@ -359,3 +389,46 @@ func configSnapshotValue(snapshot *pb.ConfigSnapshot) storecontract.ConfigSnapsh PublishedAt: timeValue(snapshot.PublishedAt), } } + +// taskLogEntryProto and taskLogEntryValue mirror internal/logging.Entry, whose +// Fields map crosses as a JSON object string exactly as events.Event.Data does +// (see eventDataJSON above). The logging package owns that format end to end; +// this is a transport of it, not a second definition. +func taskLogEntryProto(e logging.Entry) *pb.TaskLogEntry { + return &pb.TaskLogEntry{ + Id: e.ID, Time: timestamp(e.Time), Level: e.Level, Msg: e.Message, + FieldsJson: eventDataJSON(e.Fields), + } +} + +func taskLogEntryValue(e *pb.TaskLogEntry) logging.Entry { + if e == nil { + return logging.Entry{} + } + return logging.Entry{ + ID: e.Id, Time: timeValue(e.Time), Level: e.Level, Message: e.Msg, + Fields: eventDataValue(e.FieldsJson), + } +} + +// taskLogRequestProto is the client half of the ReadTaskLog mapping and +// taskLogQueryValue the server half: the whole logging.Query crosses, not a +// subset of it, so a filter cannot silently stop working at the boundary. +func taskLogRequestProto(taskID int64, attempt int, q logging.Query) *pb.ReadTaskLogRequest { + return &pb.ReadTaskLogRequest{ + TaskId: taskID, Attempt: int64(attempt), Limit: int64(q.Limit), + Levels: q.Levels, Component: q.Component, Contains: q.Contains, + Since: timestamp(q.Since), Until: timestamp(q.Until), + } +} + +func taskLogQueryValue(r *pb.ReadTaskLogRequest) logging.Query { + return logging.Query{ + Levels: r.Levels, + Component: r.Component, + Contains: r.Contains, + Limit: int(r.Limit), + Since: timeValue(r.Since), + Until: timeValue(r.Until), + } +} diff --git a/internal/logging/reader.go b/internal/logging/reader.go index 13a0c6aa9..5d6a6df6e 100644 --- a/internal/logging/reader.go +++ b/internal/logging/reader.go @@ -2,8 +2,11 @@ package logging import ( "bytes" + "context" "encoding/json" + "errors" "fmt" + "io" "os" "slices" "strings" @@ -65,6 +68,88 @@ type Result struct { Truncated bool `json:"truncated"` // File is the path read, for the UI to show where this came from. File string `json:"file"` + // Found reports whether the file existed. False with a nil error is not a + // failure: a caller asking for a log that has no file yet, or one whose + // attempt produced no output, must be told that rather than shown an empty + // page indistinguishable from a log that is genuinely empty. This is also + // what separates "there is no log for this attempt" from "this process + // cannot read logs at all" -- two conditions that a reader has to report + // differently because only the second is a configuration matter. + Found bool `json:"found"` +} + +// TaskLogPage is one task attempt's log as a task-log reader returns it: the +// page Tail selected, whether the attempt has a file at all, and the distinct +// components present in the file's tail so a filter is built from what is +// actually there rather than a hardcoded list that drifts. +type TaskLogPage struct { + Result + Components []string `json:"components"` +} + +// ErrTaskLogsUnavailable reports that this process cannot read task logs at +// all -- no reader is configured here. It is deliberately not the same answer +// as "this attempt has no log" (Result.Found = false): a caller that conflates +// them tells an operator task logging is switched off when it is not, which is +// the bug this error exists to prevent. +var ErrTaskLogsUnavailable = errors.New("logging: task log reader unavailable") + +// taskLogChunkBytes bounds one write a TaskLogContent makes, so a reader that +// pushes into a bounded transport emits chunks that transport can carry. +// io.Copy would otherwise hand it reads of its own choosing. +const taskLogChunkBytes = 256 << 10 + +// TaskLog reads one task attempt's persisted log from this registry. A nil +// registry (task logging not configured for this process) reports +// ErrTaskLogsUnavailable, never an empty page: a process that cannot read logs +// must say so rather than implicate the attempt. Safe to call on a nil +// receiver, like every other method here. +func (r *TaskRegistry) TaskLog(_ context.Context, taskID int64, attempt int, q Query) (TaskLogPage, error) { + if r == nil { + return TaskLogPage{}, ErrTaskLogsUnavailable + } + res, err := Tail(TaskLogPath(r.baseDir, taskID, attempt), q) + if err != nil { + return TaskLogPage{}, err + } + page := TaskLogPage{Result: res, Components: []string{}} + // The filter list is a convenience: failing to build it must not cost the + // caller their entries. Components only reads the tail this page already + // read, so its error is the same "treat as empty" case the daemon-wide + // handler has always applied -- it is dropped deliberately, not missed. + if res.Found { + if components, err := Components(res.File); err == nil { + page.Components = components + } + } + return page, nil +} + +// TaskLogContent writes one task attempt's log to w exactly as it is on disk, +// for a caller that wants the file rather than a decoded page. found is false, +// with a nil error, when the attempt has no log file -- a normal state for an +// attempt that produced no output, and not an error. A nil registry reports +// ErrTaskLogsUnavailable, matching TaskLog. +// +// The content is streamed rather than returned as one slice because a log file +// is unbounded input (it rotates at DefaultMaxSizeMB), and a caller moving it +// across a transport with a message-size limit needs it in pieces. +func (r *TaskRegistry) TaskLogContent(_ context.Context, taskID int64, attempt int, w io.Writer) (bool, error) { + if r == nil { + return false, ErrTaskLogsUnavailable + } + f, err := os.Open(TaskLogPath(r.baseDir, taskID, attempt)) + if err != nil { + if os.IsNotExist(err) { + return false, nil + } + return false, fmt.Errorf("logging: open task log: %w", err) + } + defer func() { _ = f.Close() }() + if _, err := io.CopyBuffer(w, f, make([]byte, taskLogChunkBytes)); err != nil { + return false, fmt.Errorf("logging: read task log: %w", err) + } + return true, nil } // PageResult is what a single forward-paged call returns. @@ -293,6 +378,19 @@ func Tail(path string, q Query) (Result, error) { limit = MaxTailLines } + // found is read before readLines so an absent file is reported as such + // rather than only as an empty entry list -- see Result.Found. It is a + // Stat rather than a second readWindow: readLines reads the whole scan + // window, and doing that twice per Tail call would double the cost of + // every log view for one boolean. + if strings.TrimSpace(path) != "" { + if _, err := os.Stat(path); err == nil { + res.Found = true + } else if !os.IsNotExist(err) { + return Result{}, fmt.Errorf("logging: stat %s: %w", path, err) + } + } + matches := make([]Entry, 0, limit) truncated, _, ok, err := readLines(path, q, 0, func(e Entry, _ int64) bool { if len(matches) == limit { diff --git a/internal/store/interface.go b/internal/store/interface.go index c4a77a86e..bed66d142 100644 --- a/internal/store/interface.go +++ b/internal/store/interface.go @@ -25,6 +25,7 @@ type ( TaskRetryer = storecontract.TaskRetryer TaskQueries = storecontract.TaskQueries TaskEvents = storecontract.TaskEvents + TaskLogStore = storecontract.TaskLogStore CaptureStore = storecontract.CaptureStore ConfigSnapshotStore = storecontract.ConfigSnapshotStore MappingStore = storecontract.MappingStore diff --git a/internal/webui/api_tasks_actions_test.go b/internal/webui/api_tasks_actions_test.go index 7f777e9ba..4ed5dfc94 100644 --- a/internal/webui/api_tasks_actions_test.go +++ b/internal/webui/api_tasks_actions_test.go @@ -56,7 +56,12 @@ type daemonActions struct { // cfg is the daemon's configuration, held by the stand-in daemon // rather than by the dashboard: retry caps are the task owner's // policy and the dashboard does not hold configuration. - cfg *config.Holder + cfg *config.Holder + // logs is the daemon's own task-log registry. Archiving removes a + // task's log files, and that is the daemon's cleanup over the state + // directory it owns -- the dashboard reads logs through a contract and + // has no directory to remove anything from. + logs *logging.TaskRegistry issues *recordingCloser stopper *recordingTaskStopper // scopes records the identity each action arrived with, one per call. @@ -97,10 +102,10 @@ func (d *daemonActions) closeIssue() func(context.Context, string, string, int, } func (d *daemonActions) removeLogs() func(int64) error { - if d.srv.TaskLogs == nil { + if d.logs == nil { return nil } - return d.srv.TaskLogs.Remove + return d.logs.Remove } func (d *daemonActions) publish() func(events.Event) { @@ -701,11 +706,17 @@ func TestArchiveRemovesOnlyOneTerminalTask(t *testing.T) { // logging: without this, an archived task's log files (and every rotated // generation under it) would accumulate on disk forever, since nothing else // in the system ever visits a task again once it leaves the active board. +// +// The removal is the task owner's, not the dashboard's: the log files live in +// the state directory, which the daemon owns, so the stand-in daemon holds the +// registry the way the real one does. The dashboard reads logs through a +// contract and has no directory to remove anything from. func TestArchiveRemovesTheTaskLogDirectory(t *testing.T) { srv := newTestServer(t) ctx := t.Context() baseDir := t.TempDir() - srv.TaskLogs = logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{}) + logs := logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{}) + operatorActions(t, srv).logs = logs if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "done", "", "", ""); err != nil { t.Fatal(err) @@ -715,11 +726,11 @@ func TestArchiveRemovesTheTaskLogDirectory(t *testing.T) { t.Fatal(err) } - if err := srv.TaskLogs.Open(task.ID, task.Attempt); err != nil { + if err := logs.Open(task.ID, task.Attempt); err != nil { t.Fatal(err) } - srv.TaskLogs.Write(task.ID, logging.Entry{Message: "line"}) - if err := srv.TaskLogs.Close(task.ID); err != nil { + logs.Write(task.ID, logging.Entry{Message: "line"}) + if err := logs.Close(task.ID); err != nil { t.Fatal(err) } dir := logging.TaskLogDir(baseDir, task.ID) diff --git a/internal/webui/api_tasks_log_download_test.go b/internal/webui/api_tasks_log_download_test.go new file mode 100644 index 000000000..630bf05d1 --- /dev/null +++ b/internal/webui/api_tasks_log_download_test.go @@ -0,0 +1,161 @@ +package webui + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + + "github.com/samcharles93/archie-core/internal/logging" +) + +// TestHandleTaskLogsDistinguishesNoLogForTheAttempt covers the dashboard's +// misleading report. A process that HAS a task-log reader and an attempt that +// genuinely has no file on disk is a different answer from a process that +// cannot read logs at all, and only the second one is "logging is not enabled +// here". The response has to carry that difference or the page cannot state it. +func TestHandleTaskLogsDistinguishesNoLogForTheAttempt(t *testing.T) { + srv := newTestServer(t) + ctx := t.Context() + srv.TaskLogs = logging.NewTaskRegistry(t.TempDir(), logging.NewFeed(10), logging.TaskSinkOptions{}) + + if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil { + t.Fatal(err) + } + task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 1) + if err != nil { + t.Fatal(err) + } + // No log is ever opened for this task: the reader works, the attempt has + // no file. + + w := getTaskLogs(t, srv, task.ID, nil) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", w.Code, w.Body) + } + var body struct { + Disabled bool `json:"disabled"` + Found bool `json:"found"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatalf("decode response: %v (%s)", err, w.Body) + } + if body.Disabled { + t.Error("disabled = true for a process that has a task-log reader; that is the report the page turns into \"logging was not enabled for this run\"") + } + if body.Found { + t.Error("found = true for an attempt with no log file on disk") + } + if !strings.Contains(w.Body.String(), `"found"`) { + t.Errorf("body = %s, want an explicit found marker so the page can say the attempt has no log rather than that logging is off", w.Body) + } +} + +// TestHandleTaskLogsDownloadServesTheAttemptLog pins the deliverable: the +// endpoint hands back the attempt's log as a file download. The route falling +// through to the SPA asset handler would answer 200 with an HTML page, so this +// asserts on the attachment headers and the body, not merely on the status. +func TestHandleTaskLogsDownloadServesTheAttemptLog(t *testing.T) { + srv := newTestServer(t) + ctx := t.Context() + logs := logging.NewTaskRegistry(t.TempDir(), logging.NewFeed(10), logging.TaskSinkOptions{}) + srv.TaskLogs = logs + + if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil { + t.Fatal(err) + } + task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 1) + if err != nil { + t.Fatal(err) + } + if err := logs.Open(task.ID, task.Attempt); err != nil { + t.Fatal(err) + } + logs.Write(task.ID, logging.Entry{Level: "ERROR", Message: "gate failed"}) + if err := logs.Close(task.ID); err != nil { + t.Fatal(err) + } + + url := "/api/tasks/" + strconv.FormatInt(task.ID, 10) + "/logs/download" + req := httptest.NewRequestWithContext(ctx, http.MethodGet, url, nil) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("GET %s = %d, body %s", url, w.Code, w.Body) + } + wantName := "task-" + strconv.FormatInt(task.ID, 10) + "-attempt-" + strconv.Itoa(task.Attempt) + ".log" + if got := w.Header().Get("Content-Disposition"); got != `attachment; filename="`+wantName+`"` { + t.Errorf("Content-Disposition = %q, want an attachment named %q", got, wantName) + } + if !strings.Contains(w.Body.String(), "gate failed") { + t.Errorf("download body = %s, want the attempt's own log content", w.Body) + } +} + +// TestHandleTaskLogsDownloadWithoutALogAnswersNotFound keeps the download +// honest: there is nothing to attach, so it says so rather than handing back a +// zero-byte file that looks like a successful download of nothing. +func TestHandleTaskLogsDownloadWithoutALogAnswersNotFound(t *testing.T) { + srv := newTestServer(t) + ctx := t.Context() + srv.TaskLogs = logging.NewTaskRegistry(t.TempDir(), logging.NewFeed(10), logging.TaskSinkOptions{}) + + if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil { + t.Fatal(err) + } + task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 1) + if err != nil { + t.Fatal(err) + } + + url := "/api/tasks/" + strconv.FormatInt(task.ID, 10) + "/logs/download" + req := httptest.NewRequestWithContext(ctx, http.MethodGet, url, nil) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + if w.Code != http.StatusNotFound { + t.Fatalf("GET %s with no log = %d, want 404", url, w.Code) + } + // The response is an error, not a file. Attachment headers are written + // before the read (the body streams, so the size is unknown up front), and + // leaving them on a 404 hands the caller a .log attachment containing only + // the error text. + if got := w.Header().Get("Content-Disposition"); got != "" { + t.Errorf("Content-Disposition = %q on a 404, want it cleared so the error is not presented as a download", got) + } + if got := w.Header().Get("Content-Type"); strings.Contains(got, "ndjson") { + t.Errorf("Content-Type = %q on a 404, want the error content type rather than the log's", got) + } +} + +// TestHandleTaskLogsDownloadWithoutAReaderAnswersServiceUnavailable is the +// degradation the boundary permits: a process with no task-log contract answers +// 503 rather than 404, because "I cannot read logs" and "there is no log" are +// not the same claim. +func TestHandleTaskLogsDownloadWithoutAReaderAnswersServiceUnavailable(t *testing.T) { + srv := newTestServer(t) + ctx := t.Context() + if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil { + t.Fatal(err) + } + task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 1) + if err != nil { + t.Fatal(err) + } + + url := "/api/tasks/" + strconv.FormatInt(task.ID, 10) + "/logs/download" + req := httptest.NewRequestWithContext(ctx, http.MethodGet, url, nil) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + if w.Code != http.StatusServiceUnavailable { + body, _ := io.ReadAll(w.Result().Body) + t.Fatalf("GET %s without a reader = %d (%s), want 503", url, w.Code, body) + } + // Same rule as the 404: an unavailable reader is an error, not a file. + if got := w.Header().Get("Content-Disposition"); got != "" { + t.Errorf("Content-Disposition = %q on a 503, want it cleared so the error is not presented as a download", got) + } +} diff --git a/internal/webui/api_tasks_logs.go b/internal/webui/api_tasks_logs.go index 1966a5b17..1e9c9a29d 100644 --- a/internal/webui/api_tasks_logs.go +++ b/internal/webui/api_tasks_logs.go @@ -1,6 +1,9 @@ package webui import ( + "context" + "errors" + "io" "net/http" "strconv" "strings" @@ -16,84 +19,213 @@ import ( // Attempt from the store, since that is what a human or Archie's own chat // tool means by "why did task N park?" almost every time: the most recent // run, not an arbitrary earlier retry. +// +// Two outcomes are kept apart on purpose, because only one of them is about +// the operator's configuration. A process with no task-log reader cannot say +// anything about an attempt, so it reports disabled and the page explains that +// this process cannot read logs. A process WITH a reader and an attempt with +// no log file reports found=false, which the page states as no log recorded +// for the attempt. Collapsing the second into the first is what made the +// dashboard claim "task logging is optional and was not enabled for this run" +// for every attempt of every task in a deployment where logging is +// unconditional. func (s *Server) handleTaskLogs(w http.ResponseWriter, r *http.Request) { - id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) - if err != nil { - http.Error(w, "bad id", http.StatusBadRequest) + id, attempt, ok := s.taskLogTarget(w, r) + if !ok { return } - - task, err := s.Store.TaskByID(r.Context(), id) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - if task == nil { - http.Error(w, "task not found", http.StatusNotFound) + reader := s.taskLogReader() + if reader == nil { + writeDisabledTaskLogs(w, attempt) return } q := r.URL.Query() - attempt := task.Attempt - if raw := strings.TrimSpace(q.Get("attempt")); raw != "" { - attempt, err = strconv.Atoi(raw) - if err != nil { - http.Error(w, "bad attempt", http.StatusBadRequest) - return - } - } - - path := s.TaskLogs.Path(id, attempt) - if path == "" { - // Not an error: task logging is optional, same convention as - // handleLogs for the daemon-wide log. - writeJSON(w, map[string]any{ - "entries": []logging.Entry{}, - "file": "", - "disabled": true, - "attempt": attempt, - }) + limit, ok := taskLogLimit(w, q.Get("limit")) + if !ok { return } - - limit := logging.DefaultTailLines - if raw := strings.TrimSpace(q.Get("limit")); raw != "" { - parsed, err := strconv.Atoi(raw) - if err != nil { - http.Error(w, "bad limit", http.StatusBadRequest) - return - } - switch { - case parsed <= 0: - limit = logging.DefaultTailLines - case parsed > logging.MaxTailLines: - limit = logging.MaxTailLines - default: - limit = parsed - } - } - result, err := logging.Tail(path, logging.Query{ + page, err := reader.TaskLog(r.Context(), id, attempt, logging.Query{ Levels: splitCSV(q.Get("level")), Component: strings.TrimSpace(q.Get("component")), Contains: strings.TrimSpace(q.Get("q")), Limit: limit, }) if err != nil { + // A reader that exists but cannot read here is still a statement about + // this process rather than about the attempt, so it keeps the disabled + // answer instead of claiming the attempt has no log. + if errors.Is(err, logging.ErrTaskLogsUnavailable) { + writeDisabledTaskLogs(w, attempt) + return + } http.Error(w, err.Error(), http.StatusInternalServerError) return } - components, err := logging.Components(path) - if err != nil { - s.Log.Warn("task log components unavailable", "task_id", id, "err", err) - components = []string{} - } - writeJSON(w, map[string]any{ - "entries": result.Entries, - "truncated": result.Truncated, - "file": result.File, - "components": components, + "entries": page.Entries, + "truncated": page.Truncated, + "file": page.File, + "components": page.Components, "attempt": attempt, + // found is the distinction the page needs: a reader answering with no + // entries because the file is absent is not a reader that is absent. + "found": page.Found, }) } + +// handleTaskLogDownload serves one task attempt's log verbatim as a file +// download -- the log itself rather than a decoded view of it, because an +// operator who asks for a download wants to read it in their own tooling or +// hand it to someone else. +// +// The conditions stay apart here too. A process with no reader answers 503, +// not 404: "there is no log for this attempt" is a claim only a process that +// can look is in a position to make. +func (s *Server) handleTaskLogDownload(w http.ResponseWriter, r *http.Request) { + id, attempt, ok := s.taskLogTarget(w, r) + if !ok { + return + } + reader := s.taskLogReader() + if reader == nil { + http.Error(w, logging.ErrTaskLogsUnavailable.Error(), http.StatusServiceUnavailable) + return + } + + // Headers are set before the read because the body streams straight from + // the reader into the response: a log file is unbounded input, so + // buffering it to size the response would defeat the reason the reader + // streams at all. The attempt's own name is known up front. + // + // Everything after this point must therefore CLEAR them before writing an + // error, never add to them: a 404 still carrying `Content-Disposition: + // attachment` is a browser download of the error text under a .log + // filename, and the NDJSON type would misdescribe it too. + w.Header().Set("Content-Type", "application/x-ndjson") + w.Header().Set("Content-Disposition", `attachment; filename="`+taskLogFilename(id, attempt)+`"`) + + clearAttachment := func() { + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + w.Header().Del("Content-Disposition") + } + + found, err := reader.TaskLogContent(r.Context(), id, attempt, w) + if err != nil { + if errors.Is(err, logging.ErrTaskLogsUnavailable) { + clearAttachment() + http.Error(w, err.Error(), http.StatusServiceUnavailable) + return + } + // Once a 200 and a body are on the wire there is no status left to + // send, so a failure partway through is logged where an operator can + // find it rather than silently truncating the file. + s.logf("task log download failed", "task", id, "attempt", attempt, "err", err) + return + } + if !found { + clearAttachment() + http.Error(w, "no log recorded for this attempt", http.StatusNotFound) + } +} + +// taskLogTarget resolves the {id} path value and the task it names, returning +// the attempt to read: the "attempt" query parameter when the request names +// one, otherwise the task's current Attempt. It answers the request itself and +// reports false when either step fails. +func (s *Server) taskLogTarget(w http.ResponseWriter, r *http.Request) (id int64, attempt int, ok bool) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.Error(w, "bad id", http.StatusBadRequest) + return 0, 0, false + } + task, err := s.Store.TaskByID(r.Context(), id) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return 0, 0, false + } + if task == nil { + http.Error(w, "task not found", http.StatusNotFound) + return 0, 0, false + } + + attempt = task.Attempt + if raw := strings.TrimSpace(r.URL.Query().Get("attempt")); raw != "" { + parsed, err := strconv.Atoi(raw) + if err != nil { + http.Error(w, "bad attempt", http.StatusBadRequest) + return 0, 0, false + } + attempt = parsed + } + return id, attempt, true +} + +// taskLogLimit bounds a page the way handleLogs bounds the daemon-wide read: +// the limit is caller-supplied and a log file is unbounded, so a request must +// not be able to pull an arbitrary amount of it into memory. +func taskLogLimit(w http.ResponseWriter, raw string) (int, bool) { + raw = strings.TrimSpace(raw) + if raw == "" { + return logging.DefaultTailLines, true + } + parsed, err := strconv.Atoi(raw) + if err != nil { + http.Error(w, "bad limit", http.StatusBadRequest) + return 0, false + } + switch { + case parsed <= 0: + return logging.DefaultTailLines, true + case parsed > logging.MaxTailLines: + return logging.MaxTailLines, true + default: + return parsed, true + } +} + +// writeDisabledTaskLogs is the "this process cannot read task logs" answer, +// the same convention handleLogs uses for the daemon-wide log: an optional +// capability that is absent here must not turn "why did this task park?" into +// a 500 for every task. +func writeDisabledTaskLogs(w http.ResponseWriter, attempt int) { + writeJSON(w, map[string]any{ + "entries": []logging.Entry{}, + "file": "", + "disabled": true, + "attempt": attempt, + }) +} + +// taskLogFilename names a downloaded attempt's log. It carries the task and +// the attempt because an operator downloading two attempts of the same task +// must not end up with one file overwriting the other, and the attempt is the +// one identifier the log's own path would have given them. +func taskLogFilename(taskID int64, attempt int) string { + return "task-" + strconv.FormatInt(taskID, 10) + "-attempt-" + strconv.Itoa(attempt) + ".log" +} + +// taskLogReader is the task-log read capability this process has, or nil when +// it has none. The seam is a narrow interface rather than a concrete registry +// so the same handlers serve both processes: the daemon holds a registry over +// its own state directory, the dashboard holds the State Store client. A +// consumer-owned seam is the difference between the dashboard degrading +// honestly and the dashboard opening another process's files. +func (s *Server) taskLogReader() TaskLogSource { + if s == nil { + return nil + } + return s.TaskLogs +} + +// TaskLogSource is the read seam the task-log handlers consume. It is the +// logging package's own reader contract, so a registry and a remote client +// satisfy it without either one restating the log format -- the package that +// owns the format also owns the shape of a read of it. +type TaskLogSource interface { + // TaskLog returns a page of one attempt's decoded log. + TaskLog(ctx context.Context, taskID int64, attempt int, q logging.Query) (logging.TaskLogPage, error) + // TaskLogContent writes one attempt's log verbatim to w, for a download. + TaskLogContent(ctx context.Context, taskID int64, attempt int, w io.Writer) (bool, error) +} diff --git a/internal/webui/api_tasks_logs_test.go b/internal/webui/api_tasks_logs_test.go index 6083e7942..8b67119d6 100644 --- a/internal/webui/api_tasks_logs_test.go +++ b/internal/webui/api_tasks_logs_test.go @@ -14,7 +14,8 @@ func TestHandleTaskLogsReturnsEntriesForLatestAttemptByDefault(t *testing.T) { srv := newTestServer(t) ctx := t.Context() baseDir := t.TempDir() - srv.TaskLogs = logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{}) + logs := logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{}) + srv.TaskLogs = logs if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil { t.Fatal(err) @@ -24,13 +25,13 @@ func TestHandleTaskLogsReturnsEntriesForLatestAttemptByDefault(t *testing.T) { t.Fatal(err) } - if err := srv.TaskLogs.Open(task.ID, task.Attempt); err != nil { + if err := logs.Open(task.ID, task.Attempt); err != nil { t.Fatal(err) } - srv.TaskLogs.Write(task.ID, logging.Entry{ + logs.Write(task.ID, logging.Entry{ Level: "ERROR", Message: "gate failed", Fields: map[string]any{"component": "gate"}, }) - if err := srv.TaskLogs.Close(task.ID); err != nil { + if err := logs.Close(task.ID); err != nil { t.Fatal(err) } @@ -58,7 +59,8 @@ func TestHandleTaskLogsHonoursExplicitAttempt(t *testing.T) { srv := newTestServer(t) ctx := t.Context() baseDir := t.TempDir() - srv.TaskLogs = logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{}) + logs := logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{}) + srv.TaskLogs = logs if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil { t.Fatal(err) diff --git a/internal/webui/server.go b/internal/webui/server.go index 01c90bf31..cd5cc2193 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -43,10 +43,16 @@ type Server struct { // LogFeed is the daemon diagnostic stream. It is separate from Events, // which contains persisted task lifecycle activity only. LogFeed *logging.Feed - // TaskLogs holds each task's persisted log output. Archiving a task - // removes its log files here too, via TaskLogs.Remove -- nil (task - // logging not configured) makes that a no-op. - TaskLogs *logging.TaskRegistry + // TaskLogs reads each task's persisted log output. Composition gives this + // process whichever implementation it can use: the daemon (whose state + // directory holds the files) its own *logging.TaskRegistry, and the + // dashboard process, which owns no such directory, the State Store client + // -- the read crosses a contract rather than opening a file + // (docs/prds/ui-service-boundary.md). Nil means this process has no + // task-log capability at all, which the handlers report as disabled rather + // than as "the attempt has no log": those are different claims and only one + // of them is about configuration. + TaskLogs TaskLogSource // UpdateConfig applies a set of dotted-path config updates through // the same validate-persist-publish path as reload (wired by the @@ -238,6 +244,7 @@ func (s *Server) registerTaskRoutes(mux *http.ServeMux) { mux.HandleFunc("POST /api/tasks/{id}/action", s.handleTaskAction) mux.HandleFunc("GET /api/tasks/{id}", s.handleTask) mux.HandleFunc("GET /api/tasks/{id}/logs", s.handleTaskLogs) + mux.HandleFunc("GET /api/tasks/{id}/logs/download", s.handleTaskLogDownload) } func (s *Server) registerMappingAndBindingRoutes(mux *http.ServeMux) { diff --git a/proto/state/v1/state.proto b/proto/state/v1/state.proto index 15c6551b4..67dcdcb77 100644 --- a/proto/state/v1/state.proto +++ b/proto/state/v1/state.proto @@ -53,6 +53,18 @@ service StateStoreService { rpc PutConfigSnapshot(PutConfigSnapshotRequest) returns (PutConfigSnapshotResponse); rpc GetConfigSnapshot(GetConfigSnapshotRequest) returns (GetConfigSnapshotResponse); + // Task log: one task attempt's persisted log. Task log files live in the + // state directory this process owns, so the dashboard reads them over this + // contract rather than opening them itself + // (docs/prds/ui-service-boundary.md). + rpc ReadTaskLog(ReadTaskLogRequest) returns (ReadTaskLogResponse); + // StreamTaskLogContent returns one attempt's log verbatim, one chunk per + // message, for a download. A log file is unbounded input (it rotates at + // DefaultMaxSizeMB), so a unary response would exceed gRPC's 4MiB message + // cap on a real log -- the same reason ListCaptures was superseded by + // StreamCaptures. + rpc StreamTaskLogContent(StreamTaskLogContentRequest) returns (stream StreamTaskLogContentResponse); + // Capture rpc InsertCapture(InsertCaptureRequest) returns (InsertCaptureResponse); // ListCaptures is superseded by StreamCaptures (kept, unmodified, so an @@ -372,6 +384,64 @@ message GetConfigSnapshotResponse { bool found = 2; } +// TaskLogEntry mirrors internal/logging.Entry: one decoded log line. fields +// carries every remaining key as a JSON object string, the same way Event +// carries its data, so structured context survives the hop without this +// contract having to know what a call site attached. +message TaskLogEntry { + int64 id = 1; + google.protobuf.Timestamp time = 2; + string level = 3; + string msg = 4; + string fields_json = 5; +} + +// ReadTaskLog returns a page of one task attempt's decoded log. attempt is the +// attempt the caller resolved (the dashboard sends the task's current attempt +// when the request omitted one). levels, component, contains, since and until +// carry the whole query the logging package's Tail accepts -- the wire mirrors +// that query rather than a subset of it, so a filter cannot silently stop +// working by crossing the boundary. limit is caller-capped +// (docs/prds/state-store-contract.md §8: the log cap is 2000). +message ReadTaskLogRequest { + int64 task_id = 1; + int64 attempt = 2; + int64 limit = 3; + repeated string levels = 4; + string component = 5; + string contains = 6; + google.protobuf.Timestamp since = 7; + google.protobuf.Timestamp until = 8; +} +// found=false is not an error: the task has no log file for that attempt. +// That is a different condition from a process that cannot read logs at all +// (codes.Unavailable), and the dashboard reports them differently. +message ReadTaskLogResponse { + repeated TaskLogEntry entries = 1; + bool truncated = 2; + int64 attempt = 3; + bool found = 4; + repeated string components = 5; + // file is the path read, so the page can name where the log came from. It + // is the state directory's own layout, reported to an already-authenticated + // operator; no caller is expected to open it. + string file = 6; +} + +// StreamTaskLogContent returns one attempt's log verbatim, for a download. The +// bytes are the file's own JSONL, not a re-encoding of it: this contract +// transports the log, it does not restate the format. found=false, with no +// chunks, means the attempt has no log file -- not an error. +message StreamTaskLogContentRequest { + int64 task_id = 1; + int64 attempt = 2; +} +message StreamTaskLogContentResponse { + bytes chunk = 1; + int64 attempt = 2; + bool found = 3; +} + message InsertCaptureRequest { CapturedEvent capture = 1; int64 retention_seconds = 2; diff --git a/ui/dist/assets/index.js b/ui/dist/assets/index.js index 099713840..1db2451f9 100644 --- a/ui/dist/assets/index.js +++ b/ui/dist/assets/index.js @@ -1,16 +1,16 @@ -(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e,t,n,r,i,a,o,s,c,l,u,d,f,p,m={},h=[],g=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,_=Array.isArray;function v(e,t){for(var n in t)e[n]=t[n];return e}function y(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function b(t,n,r){var i,a,o,s={};for(o in n)o==`key`?i=n[o]:o==`ref`?a=n[o]:s[o]=n[o];if(arguments.length>2&&(s.children=arguments.length>3?e.call(arguments,2):r),typeof t==`function`&&t.defaultProps!=null)for(o in t.defaultProps)s[o]===void 0&&(s[o]=t.defaultProps[o]);return x(t,s,i,a,null)}function x(e,r,i,a,o){var s={type:e,props:r,key:i,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++n,__i:-1,__u:0};return o==null&&t.vnode!=null&&t.vnode(s),s}function S(e){return e.children}function C(e,t){this.props=e,this.context=t}function w(e,t){if(t==null)return e.__?w(e.__,e.__i+1):null;for(var n;tt&&r.sort(o),e=r.shift(),t=r.length,T(e)}finally{r.length=O.__r=0}}function k(e,t,n,r,i,a,o,s,c,l,u){var d,f,p,g,_,v,y=r&&r.__k||h,b=t.length;for(c=A(n,t,y,c,b),d=0;d0?o=e.__k[a]=x(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):e.__k[a]=o,c=a+f,o.__=e,o.__b=e.__b+1,s=null,(l=o.__i=ee(o,n,c,d))!=-1&&(d--,(s=n[l])&&(s.__u|=2)),s==null||s.__v==null?(l==-1&&(i>u?f--:ic?f--:f++,o.__u|=4))):e.__k[a]=null;if(d)for(a=0;a+!!u){for(i=n-1,a=n+1;i>=0||a=0?i--:a++])!=null&&!(2&l.__u)&&s==l.key&&c==l.type)return o}return-1}function M(e,t,n){t[0]==`-`?e.setProperty(t,n??``):e[t]=n==null?``:typeof n!=`number`||g.test(t)?n:n+`px`}function N(e,t,n,r,i){var a,o;n:if(t==`style`)if(typeof n==`string`)e.style.cssText=n;else{if(typeof r==`string`&&(e.style.cssText=r=``),r)for(t in r)n&&t in n||M(e.style,t,``);if(n)for(t in n)r&&n[t]==r[t]||M(e.style,t,n[t])}else if(t[0]==`o`&&t[1]==`n`)a=t!=(t=t.replace(u,`$1`)),o=t.toLowerCase(),t=o in e||t==`onFocusOut`||t==`onFocusIn`?o.slice(2):t.slice(2),e.l||={},e.l[t+a]=n,n?r?n[l]=r[l]:(n[l]=d,e.addEventListener(t,a?p:f,a)):e.removeEventListener(t,a?p:f,a);else{if(i==`http://www.w3.org/2000/svg`)t=t.replace(/xlink(H|:h)/,`h`).replace(/sName$/,`s`);else if(t!=`width`&&t!=`height`&&t!=`href`&&t!=`list`&&t!=`form`&&t!=`tabIndex`&&t!=`download`&&t!=`rowSpan`&&t!=`colSpan`&&t!=`role`&&t!=`popover`&&t in e)try{e[t]=n??``;break n}catch{}typeof n==`function`||(n==null||!1===n&&t[4]!=`-`?e.removeAttribute(t):e.setAttribute(t,t==`popover`&&n==1?``:n))}}function P(e){return function(n){if(this.l){var r=this.l[n.type+e];if(n[c]==null)n[c]=d++;else if(n[c]0?e:_(e)?e.map(F):e.constructor===void 0?v({},e):null}function I(n,r,i,a,o,s,c,l,u){var d,f,p,h,g,v,b,x=i.props||m,S=r.props,C=r.type;if(C==`svg`?o=`http://www.w3.org/2000/svg`:C==`math`?o=`http://www.w3.org/1998/Math/MathML`:o||=`http://www.w3.org/1999/xhtml`,s!=null){for(d=0;de.toString(16).padStart(2,`0`));return`${n.slice(0,4).join(``)}-${n.slice(4,6).join(``)}-${n.slice(6,8).join(``)}-${n.slice(8,10).join(``)}-${n.slice(10).join(``)}`}var ce=15e3;function le(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e||{}))r!==``&&r!=null&&t.set(n,r);let n=t.toString();return n?`?${n}`:``}async function ue(e){try{let t=(await e.text()).trim();if(t)return t.split(` -`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var de=class extends Error{constructor(e,t){super(e),this.status=t}};function fe(e){let t=e instanceof de?e.status:void 0,n=e?.message||`Action failed`;return t===401?{kind:`session-expired`,message:n}:t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function pe(e,t){let n=await fetch(e,t);if(!n.ok)throw new de(await ue(n),n.status);return n}async function R(e,{method:t=`GET`,body:n,timeoutMs:r=ce,parse:i=!0}={}){let a={Accept:`application/json`},o={method:t,headers:a,signal:AbortSignal.timeout(r)};t!==`GET`&&(a[`Content-Type`]=`application/json`,a[`X-Archie-CSRF`]=`1`),n!==void 0&&(o.body=JSON.stringify(n));let s=await pe(e,o);return i?s.json():void 0}var z={summary:()=>R(`/api/summary`),tasks:()=>R(`/api/tasks`),taskMeta:()=>R(`/api/task-meta`),task:e=>R(`/api/tasks/${e}`),taskAction:(e,t)=>R(`/api/tasks/${e}/action`,{method:`POST`,body:{action:t}}),setup:()=>R(`/api/setup`),capabilities:()=>R(`/api/capabilities`),workflows:()=>R(`/api/workflows`),workRequest:e=>R(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>R(`/api/skills`),channels:()=>R(`/api/channels`),curators:()=>R(`/api/curators`),channelReload:e=>R(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>R(`/api/config`),version:()=>R(`/api/version`),configUpdate:e=>R(`/api/config`,{method:`PATCH`,body:{updates:e}}),configRepoUpdate:(e,t,n,r)=>R(`/api/config/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`PATCH`,body:{field:n,value:r}}),configReset:e=>R(`/api/config/reset`,{method:`POST`,body:{key:e}}),logs:e=>R(`/api/logs`+le(e)),taskLogs:(e,t)=>R(`/api/tasks/${e}/logs`+le(t)),captures:e=>R(`/api/captures`+le({limit:e})),mappings:()=>R(`/api/mappings`),mappingCreate:e=>R(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>R(`/api/mappings/${e}`,{method:`PATCH`,body:t}),mappingDelete:e=>R(`/api/mappings/${e}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>R(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>R(`/api/bindings`),bindingCreate:e=>R(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>R(`/api/bindings/${e}`,{method:`PATCH`,body:t}),bindingDelete:e=>R(`/api/bindings/${e}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>R(`/api/bindings/${e}/approve`,{method:`POST`}),memory:()=>R(`/api/memory`),chatSessions:()=>R(`/api/chat/sessions`),chatMessages:e=>R(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>R(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>R(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>R(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:se(),text:t,page:location.hash.slice(1)||`/`}}),chatPersona:(e,t)=>R(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatUpdate:()=>R(`/api/chat/update`),chatUpdateDefer:e=>R(`/api/chat/update/defer`,{method:`POST`,body:{snapshot:e}}),chatUpdateInstall:e=>R(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:12e4}),chatDangerous:()=>R(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>R(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>R(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,{signal:t}={})=>pe(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t})};function B(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function me(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function he(e,t){return e?t.filter(t=>t.section&&e[t.section]===!1).map(e=>e.path):[]}var ge=[{id:`queued`,label:`Queued`,kind:`idle`},{id:`running`,label:`Working`,kind:`info`},{id:`waiting_human`,label:`Waiting for you`,kind:`warn`,needs_you:!0},{id:`pr_open`,label:`In review`,kind:`ok`},{id:`merged`,label:`Merged`,kind:`ok`},{id:`parked`,label:`Parked`,kind:`warn`,needs_you:!0},{id:`dead`,label:`Stopped (too many retries)`,kind:`danger`},{id:`rejected`,label:`Rejected`,kind:`danger`},{id:`closed_wont_do`,label:`Won't do`,kind:`idle`}],_e=[{id:`cancel`,label:`Cancel`,kind:`quiet`,confirm:`Cancel "{title}"? This closes the forge issue.`},{id:`stop`,label:`Stop`,kind:`primary`,confirm:`Stop "{title}"? Recoverable work will remain parked.`},{id:`approve`,label:`Approve`,kind:`primary`},{id:`reject`,label:`Reject`,kind:`quiet`,confirm:`Reject "{title}"? This closes the forge issue.`},{id:`retry`,label:`Retry`,kind:`primary`},{id:`abandon`,label:`Abandon`,kind:`quiet`,confirm:`Abandon "{title}"? This closes the forge issue.`},{id:`archive`,label:`Archive`,kind:`quiet`,confirm:`Archive the local record for "{title}"?`},{id:`open_pr`,label:`Open PR`,kind:`link`},{id:`open_issue`,label:`Open issue`,kind:`link`}],ve=[...ge],ye=[..._e],be=new Map(ve.map(e=>[e.id,e])),xe=new Map(ye.map(e=>[e.id,e]));function Se(e){return be.get(e)?.label||e||`Unknown`}function Ce(e){return be.get(e)?.kind||`idle`}function we(){return ve.map(e=>e.id)}function V(){return new Set(ve.filter(e=>e.needs_you).map(e=>e.id))}function Te(e){return xe.get(e)||null}function H(e,t,...n){let[r,...i]=e.split(`.`),a=document.createElement(r||`div`);i.length&&(a.className=i.join(` `)),t!==void 0&&(typeof t!=`object`||t instanceof Node)&&(n.unshift(t),t=null);for(let[e,n]of Object.entries(t||{}))n!=null&&n!==!1&&(e.startsWith(`on`)&&typeof n==`function`?a.addEventListener(e.slice(2).toLowerCase(),n):e===`class`?a.className=[a.className,n].filter(Boolean).join(` `):e===`html`?a.innerHTML=n:a.setAttribute(e,n===!0?``:String(n)));return Ee(a,n),a}function Ee(e,t){for(let n of t.flat(1/0))n!=null&&n!==!1&&e.append(n instanceof Node?n:document.createTextNode(String(n)))}function De(e,...t){return e.replaceChildren(),Ee(e,t),e}function U(e){if(!e)return`—`;let t=e instanceof Date?e:new Date(e),n=Math.floor((Date.now()-t.getTime())/1e3);if(!Number.isFinite(n))return`—`;if(n<45)return`just now`;let r=[[`min`,60],[`hr`,3600],[`day`,86400],[`wk`,604800]],i=`min`,a=60;for(let[e,t]of r)n>=t&&([i,a]=[e,t]);let o=Math.floor(n/a);return`${o} ${i}${o===1?``:`s`} ago`}function Oe(e){return e==null||Number.isNaN(e)?`—`:new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1}).format(e)}var ke={dashboard:``,chat:``,tasks:``,logs:``,skills:``,workflows:``,memory:``,channels:``,curators:``,captures:``,mappings:``,bindings:``,settings:``,search:``,moon:``,sun:``,refresh:``,bell:``,trendUp:``,trendDown:``,check:``,close:``,help:``};function W(e,{size:t=18,className:n=``}={}){let r=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`width`,String(t)),r.setAttribute(`height`,String(t)),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`1.6`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`),r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`class`,`ico ${n}`.trim()),r.innerHTML=ke[e]||ke.dashboard,r}var Ae,G,je,Me,Ne=0,Pe=[],K=t,Fe=K.__b,Ie=K.__r,Le=K.diffed,Re=K.__c,ze=K.unmount,Be=K.__;function Ve(e,t){K.__h&&K.__h(G,e,Ne||t),Ne=0;var n=G.__H||(G.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function q(e){return Ne=1,He(Xe,e)}function He(e,t,n){var r=Ve(Ae++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Xe(void 0,t),function(e){var t=r.__N?r.__N[0]:r.__[0],n=r.t(t,e);t!==n&&(r.__N=[n,r.__[1]],r.__c.setState({}))}],r.__c=G,!G.__f)){var i=function(e,t,n){if(!r.__c.__H)return!0;var i=!1,o=r.__c.props!==e;if(r.__c.__H.__.some(function(e){if(e.__N){i=!0;var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(o=!0)}}),a){var s=a.call(this,e,t,n);return i?s||o:s}return!i||o};G.__f=!0;var a=G.shouldComponentUpdate,o=G.componentWillUpdate;G.componentWillUpdate=function(e,t,n){if(this.__e){var r=a;a=void 0,i(e,t,n),a=r}o&&o.call(this,e,t,n)},G.shouldComponentUpdate=i}return r.__N||r.__}function J(e,t){var n=Ve(Ae++,3);!K.__s&&Ye(n.__H,t)&&(n.__=e,n.u=t,G.__H.__h.push(n))}function Y(e){return Ne=5,Ue(function(){return{current:e}},[])}function Ue(e,t){var n=Ve(Ae++,7);return Ye(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function We(){for(var e;e=Pe.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(qe),t.__h.some(Je),t.__h=[]}catch(n){t.__h=[],K.__e(n,e.__v)}}}K.__b=function(e){G=null,Fe&&Fe(e)},K.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Be&&Be(e,t)},K.__r=function(e){Ie&&Ie(e),Ae=0;var t=(G=e.__c).__H;t&&(je===G?(t.__h=[],G.__h=[],t.__.some(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})):(t.__h.some(qe),t.__h.some(Je),t.__h=[],Ae=0)),je=G},K.diffed=function(e){Le&&Le(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Pe.push(t)!==1&&Me===K.requestAnimationFrame||((Me=K.requestAnimationFrame)||Ke)(We)),t.__H.__.some(function(e){e.u&&=(e.__H=e.u,void 0)})),je=G=null},K.__c=function(e,t){t.some(function(e){try{e.__h.some(qe),e.__h=e.__h.filter(function(e){return!e.__||Je(e)})}catch(n){t.some(function(e){e.__h&&=[]}),t=[],K.__e(n,e.__v)}}),Re&&Re(e,t)},K.unmount=function(e){ze&&ze(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(e){try{qe(e)}catch(e){t=e}}),n.__H=void 0,t&&K.__e(t,n.__v))};var Ge=typeof requestAnimationFrame==`function`;function Ke(e){var t,n=function(){clearTimeout(r),Ge&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);Ge&&(t=requestAnimationFrame(n))}function qe(e){var t=G,n=e.__c;typeof n==`function`&&(e.__c=void 0,n()),G=t}function Je(e){var t=G;e.__c=e.__(),G=t}function Ye(e,t){return!e||e.length!==t.length||t.some(function(t,n){return t!==e[n]})}function Xe(e,t){return typeof t==`function`?t(e):t}function Ze({label:e,value:t,unit:n,trend:r,compare:i,series:a=[],goodDirection:o=`up`}){let s=r==null?null:r>=0?`up`:`down`,c=s==null?null:s===o;return H(`div.card.stat`,H(`div.stat-head`,H(`span.stat-label`,e),s&&H(`span.stat-trend.${c?`up`:`down`}`,W(s===`up`?`trendUp`:`trendDown`,{size:13}),`${Math.abs(r).toFixed(1)}%`)),H(`div.stat-value`,t,n&&H(`span.stat-unit`,n)),i&&H(`div.stat-compare`,i),a.length>1&&Qe(a,c===!1?`var(--danger)`:`var(--ok)`))}function Qe(e,t=`var(--ok)`,{width:n=220,height:r=34}={}){let i=Math.max(...e,1),a=Math.min(...e,0),o=i-a||1,s=e.length>1?n/(e.length-1):n,c=e.map((e,t)=>`${(t*s).toFixed(1)},${(r-(e-a)/o*r).toFixed(1)}`).join(` `),l=H(`svg.spark`,{viewBox:`0 0 ${n} ${r}`,preserveAspectRatio:`none`,"aria-hidden":`true`});return l.innerHTML=``,l}function $e({value:e,label:t,size:n=168}){let r=Math.max(0,Math.min(100,Number(e)||0)),i=r>=90?`var(--ok)`:r>=70?`var(--warn)`:`var(--danger)`,a=n/2,o=n/2,s=2*Math.PI*62*(240/360),c=(e,t)=>{let n=e*Math.PI/180,r=(e+t)*Math.PI/180,i=+(t>180);return[`M ${a+62*Math.cos(n)} ${o+62*Math.sin(n)}`,`A 62 62 0 ${i} 1 ${a+62*Math.cos(r)} ${o+62*Math.sin(r)}`].join(` `)},l=H(`svg.gauge`,{viewBox:`0 0 ${n} ${n*.78}`,role:`img`,"aria-label":`${t}: ${r}%`});return l.innerHTML=` +(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e,t,n,r,i,a,o,s,c,l,u,d,f,p,m={},h=[],g=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,_=Array.isArray;function v(e,t){for(var n in t)e[n]=t[n];return e}function y(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function b(t,n,r){var i,a,o,s={};for(o in n)o==`key`?i=n[o]:o==`ref`?a=n[o]:s[o]=n[o];if(arguments.length>2&&(s.children=arguments.length>3?e.call(arguments,2):r),typeof t==`function`&&t.defaultProps!=null)for(o in t.defaultProps)s[o]===void 0&&(s[o]=t.defaultProps[o]);return x(t,s,i,a,null)}function x(e,r,i,a,o){var s={type:e,props:r,key:i,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++n,__i:-1,__u:0};return o==null&&t.vnode!=null&&t.vnode(s),s}function S(e){return e.children}function C(e,t){this.props=e,this.context=t}function w(e,t){if(t==null)return e.__?w(e.__,e.__i+1):null;for(var n;tt&&r.sort(o),e=r.shift(),t=r.length,T(e)}finally{r.length=O.__r=0}}function k(e,t,n,r,i,a,o,s,c,l,u){var d,f,p,g,_,v,y=r&&r.__k||h,b=t.length;for(c=A(n,t,y,c,b),d=0;d0?o=e.__k[a]=x(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):e.__k[a]=o,c=a+f,o.__=e,o.__b=e.__b+1,s=null,(l=o.__i=ee(o,n,c,d))!=-1&&(d--,(s=n[l])&&(s.__u|=2)),s==null||s.__v==null?(l==-1&&(i>u?f--:ic?f--:f++,o.__u|=4))):e.__k[a]=null;if(d)for(a=0;a+!!u){for(i=n-1,a=n+1;i>=0||a=0?i--:a++])!=null&&!(2&l.__u)&&s==l.key&&c==l.type)return o}return-1}function M(e,t,n){t[0]==`-`?e.setProperty(t,n??``):e[t]=n==null?``:typeof n!=`number`||g.test(t)?n:n+`px`}function N(e,t,n,r,i){var a,o;n:if(t==`style`)if(typeof n==`string`)e.style.cssText=n;else{if(typeof r==`string`&&(e.style.cssText=r=``),r)for(t in r)n&&t in n||M(e.style,t,``);if(n)for(t in n)r&&n[t]==r[t]||M(e.style,t,n[t])}else if(t[0]==`o`&&t[1]==`n`)a=t!=(t=t.replace(u,`$1`)),o=t.toLowerCase(),t=o in e||t==`onFocusOut`||t==`onFocusIn`?o.slice(2):t.slice(2),e.l||={},e.l[t+a]=n,n?r?n[l]=r[l]:(n[l]=d,e.addEventListener(t,a?p:f,a)):e.removeEventListener(t,a?p:f,a);else{if(i==`http://www.w3.org/2000/svg`)t=t.replace(/xlink(H|:h)/,`h`).replace(/sName$/,`s`);else if(t!=`width`&&t!=`height`&&t!=`href`&&t!=`list`&&t!=`form`&&t!=`tabIndex`&&t!=`download`&&t!=`rowSpan`&&t!=`colSpan`&&t!=`role`&&t!=`popover`&&t in e)try{e[t]=n??``;break n}catch{}typeof n==`function`||(n==null||!1===n&&t[4]!=`-`?e.removeAttribute(t):e.setAttribute(t,t==`popover`&&n==1?``:n))}}function P(e){return function(n){if(this.l){var r=this.l[n.type+e];if(n[c]==null)n[c]=d++;else if(n[c]0?e:_(e)?e.map(F):e.constructor===void 0?v({},e):null}function I(n,r,i,a,o,s,c,l,u){var d,f,p,h,g,v,b,x=i.props||m,S=r.props,C=r.type;if(C==`svg`?o=`http://www.w3.org/2000/svg`:C==`math`?o=`http://www.w3.org/1998/Math/MathML`:o||=`http://www.w3.org/1999/xhtml`,s!=null){for(d=0;de.toString(16).padStart(2,`0`));return`${n.slice(0,4).join(``)}-${n.slice(4,6).join(``)}-${n.slice(6,8).join(``)}-${n.slice(8,10).join(``)}-${n.slice(10).join(``)}`}var se=15e3;function ce(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e||{}))r!==``&&r!=null&&t.set(n,r);let n=t.toString();return n?`?${n}`:``}async function le(e){try{let t=(await e.text()).trim();if(t)return t.split(` +`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var ue=class extends Error{constructor(e,t){super(e),this.status=t}};function de(e){let t=e instanceof ue?e.status:void 0,n=e?.message||`Action failed`;return t===401?{kind:`session-expired`,message:n}:t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function fe(e,t){let n=await fetch(e,t);if(!n.ok)throw new ue(await le(n),n.status);return n}async function z(e,{method:t=`GET`,body:n,timeoutMs:r=se,parse:i=!0}={}){let a={Accept:`application/json`},o={method:t,headers:a,signal:AbortSignal.timeout(r)};t!==`GET`&&(a[`Content-Type`]=`application/json`,a[`X-Archie-CSRF`]=`1`),n!==void 0&&(o.body=JSON.stringify(n));let s=await fe(e,o);return i?s.json():void 0}var B={summary:()=>z(`/api/summary`),tasks:()=>z(`/api/tasks`),taskMeta:()=>z(`/api/task-meta`),task:e=>z(`/api/tasks/${e}`),taskAction:(e,t)=>z(`/api/tasks/${e}/action`,{method:`POST`,body:{action:t}}),setup:()=>z(`/api/setup`),capabilities:()=>z(`/api/capabilities`),workflows:()=>z(`/api/workflows`),workRequest:e=>z(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>z(`/api/skills`),channels:()=>z(`/api/channels`),curators:()=>z(`/api/curators`),channelReload:e=>z(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>z(`/api/config`),version:()=>z(`/api/version`),configUpdate:e=>z(`/api/config`,{method:`PATCH`,body:{updates:e}}),configRepoUpdate:(e,t,n,r)=>z(`/api/config/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`PATCH`,body:{field:n,value:r}}),configReset:e=>z(`/api/config/reset`,{method:`POST`,body:{key:e}}),logs:e=>z(`/api/logs`+ce(e)),taskLogs:(e,t)=>z(`/api/tasks/${e}/logs`+ce(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${e}/logs/download`+(t==null?``:`?attempt=${t}`),captures:e=>z(`/api/captures`+ce({limit:e})),mappings:()=>z(`/api/mappings`),mappingCreate:e=>z(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>z(`/api/mappings/${e}`,{method:`PATCH`,body:t}),mappingDelete:e=>z(`/api/mappings/${e}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>z(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>z(`/api/bindings`),bindingCreate:e=>z(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>z(`/api/bindings/${e}`,{method:`PATCH`,body:t}),bindingDelete:e=>z(`/api/bindings/${e}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>z(`/api/bindings/${e}/approve`,{method:`POST`}),memory:()=>z(`/api/memory`),chatSessions:()=>z(`/api/chat/sessions`),chatMessages:e=>z(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>z(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>z(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>z(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:oe(),text:t,page:location.hash.slice(1)||`/`}}),chatPersona:(e,t)=>z(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatUpdate:()=>z(`/api/chat/update`),chatUpdateDefer:e=>z(`/api/chat/update/defer`,{method:`POST`,body:{snapshot:e}}),chatUpdateInstall:e=>z(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:12e4}),chatDangerous:()=>z(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>z(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>z(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,{signal:t}={})=>fe(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t})};function V(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function pe(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function me(e,t){return e?t.filter(t=>t.section&&e[t.section]===!1).map(e=>e.path):[]}var he=[{id:`queued`,label:`Queued`,kind:`idle`},{id:`running`,label:`Working`,kind:`info`},{id:`waiting_human`,label:`Waiting for you`,kind:`warn`,needs_you:!0},{id:`pr_open`,label:`In review`,kind:`ok`},{id:`merged`,label:`Merged`,kind:`ok`},{id:`parked`,label:`Parked`,kind:`warn`,needs_you:!0},{id:`dead`,label:`Stopped (too many retries)`,kind:`danger`},{id:`rejected`,label:`Rejected`,kind:`danger`},{id:`closed_wont_do`,label:`Won't do`,kind:`idle`}],ge=[{id:`cancel`,label:`Cancel`,kind:`quiet`,confirm:`Cancel "{title}"? This closes the forge issue.`},{id:`stop`,label:`Stop`,kind:`primary`,confirm:`Stop "{title}"? Recoverable work will remain parked.`},{id:`approve`,label:`Approve`,kind:`primary`},{id:`reject`,label:`Reject`,kind:`quiet`,confirm:`Reject "{title}"? This closes the forge issue.`},{id:`retry`,label:`Retry`,kind:`primary`},{id:`abandon`,label:`Abandon`,kind:`quiet`,confirm:`Abandon "{title}"? This closes the forge issue.`},{id:`archive`,label:`Archive`,kind:`quiet`,confirm:`Archive the local record for "{title}"?`},{id:`open_pr`,label:`Open PR`,kind:`link`},{id:`open_issue`,label:`Open issue`,kind:`link`}],_e=[...he],ve=[...ge],ye=new Map(_e.map(e=>[e.id,e])),be=new Map(ve.map(e=>[e.id,e]));function xe(e){return ye.get(e)?.label||e||`Unknown`}function Se(e){return ye.get(e)?.kind||`idle`}function Ce(){return _e.map(e=>e.id)}function H(){return new Set(_e.filter(e=>e.needs_you).map(e=>e.id))}function we(e){return be.get(e)||null}function U(e,t,...n){let[r,...i]=e.split(`.`),a=document.createElement(r||`div`);i.length&&(a.className=i.join(` `)),t!==void 0&&(typeof t!=`object`||t instanceof Node)&&(n.unshift(t),t=null);for(let[e,n]of Object.entries(t||{}))n!=null&&n!==!1&&(e.startsWith(`on`)&&typeof n==`function`?a.addEventListener(e.slice(2).toLowerCase(),n):e===`class`?a.className=[a.className,n].filter(Boolean).join(` `):e===`html`?a.innerHTML=n:a.setAttribute(e,n===!0?``:String(n)));return Te(a,n),a}function Te(e,t){for(let n of t.flat(1/0))n!=null&&n!==!1&&e.append(n instanceof Node?n:document.createTextNode(String(n)))}function Ee(e,...t){return e.replaceChildren(),Te(e,t),e}function De(e){if(!e)return`—`;let t=e instanceof Date?e:new Date(e),n=Math.floor((Date.now()-t.getTime())/1e3);if(!Number.isFinite(n))return`—`;if(n<45)return`just now`;let r=[[`min`,60],[`hr`,3600],[`day`,86400],[`wk`,604800]],i=`min`,a=60;for(let[e,t]of r)n>=t&&([i,a]=[e,t]);let o=Math.floor(n/a);return`${o} ${i}${o===1?``:`s`} ago`}function Oe(e){return e==null||Number.isNaN(e)?`—`:new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1}).format(e)}var ke={dashboard:``,chat:``,tasks:``,logs:``,skills:``,workflows:``,memory:``,channels:``,curators:``,captures:``,mappings:``,bindings:``,settings:``,search:``,moon:``,sun:``,refresh:``,bell:``,trendUp:``,trendDown:``,check:``,close:``,help:``};function W(e,{size:t=18,className:n=``}={}){let r=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`width`,String(t)),r.setAttribute(`height`,String(t)),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`1.6`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`),r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`class`,`ico ${n}`.trim()),r.innerHTML=ke[e]||ke.dashboard,r}var Ae,G,je,Me,Ne=0,Pe=[],K=t,Fe=K.__b,Ie=K.__r,Le=K.diffed,Re=K.__c,ze=K.unmount,Be=K.__;function Ve(e,t){K.__h&&K.__h(G,e,Ne||t),Ne=0;var n=G.__H||(G.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function q(e){return Ne=1,He(Xe,e)}function He(e,t,n){var r=Ve(Ae++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Xe(void 0,t),function(e){var t=r.__N?r.__N[0]:r.__[0],n=r.t(t,e);t!==n&&(r.__N=[n,r.__[1]],r.__c.setState({}))}],r.__c=G,!G.__f)){var i=function(e,t,n){if(!r.__c.__H)return!0;var i=!1,o=r.__c.props!==e;if(r.__c.__H.__.some(function(e){if(e.__N){i=!0;var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(o=!0)}}),a){var s=a.call(this,e,t,n);return i?s||o:s}return!i||o};G.__f=!0;var a=G.shouldComponentUpdate,o=G.componentWillUpdate;G.componentWillUpdate=function(e,t,n){if(this.__e){var r=a;a=void 0,i(e,t,n),a=r}o&&o.call(this,e,t,n)},G.shouldComponentUpdate=i}return r.__N||r.__}function J(e,t){var n=Ve(Ae++,3);!K.__s&&Ye(n.__H,t)&&(n.__=e,n.u=t,G.__H.__h.push(n))}function Y(e){return Ne=5,Ue(function(){return{current:e}},[])}function Ue(e,t){var n=Ve(Ae++,7);return Ye(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function We(){for(var e;e=Pe.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(qe),t.__h.some(Je),t.__h=[]}catch(n){t.__h=[],K.__e(n,e.__v)}}}K.__b=function(e){G=null,Fe&&Fe(e)},K.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Be&&Be(e,t)},K.__r=function(e){Ie&&Ie(e),Ae=0;var t=(G=e.__c).__H;t&&(je===G?(t.__h=[],G.__h=[],t.__.some(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})):(t.__h.some(qe),t.__h.some(Je),t.__h=[],Ae=0)),je=G},K.diffed=function(e){Le&&Le(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Pe.push(t)!==1&&Me===K.requestAnimationFrame||((Me=K.requestAnimationFrame)||Ke)(We)),t.__H.__.some(function(e){e.u&&=(e.__H=e.u,void 0)})),je=G=null},K.__c=function(e,t){t.some(function(e){try{e.__h.some(qe),e.__h=e.__h.filter(function(e){return!e.__||Je(e)})}catch(n){t.some(function(e){e.__h&&=[]}),t=[],K.__e(n,e.__v)}}),Re&&Re(e,t)},K.unmount=function(e){ze&&ze(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(e){try{qe(e)}catch(e){t=e}}),n.__H=void 0,t&&K.__e(t,n.__v))};var Ge=typeof requestAnimationFrame==`function`;function Ke(e){var t,n=function(){clearTimeout(r),Ge&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);Ge&&(t=requestAnimationFrame(n))}function qe(e){var t=G,n=e.__c;typeof n==`function`&&(e.__c=void 0,n()),G=t}function Je(e){var t=G;e.__c=e.__(),G=t}function Ye(e,t){return!e||e.length!==t.length||t.some(function(t,n){return t!==e[n]})}function Xe(e,t){return typeof t==`function`?t(e):t}function Ze({label:e,value:t,unit:n,trend:r,compare:i,series:a=[],goodDirection:o=`up`}){let s=r==null?null:r>=0?`up`:`down`,c=s==null?null:s===o;return U(`div.card.stat`,U(`div.stat-head`,U(`span.stat-label`,e),s&&U(`span.stat-trend.${c?`up`:`down`}`,W(s===`up`?`trendUp`:`trendDown`,{size:13}),`${Math.abs(r).toFixed(1)}%`)),U(`div.stat-value`,t,n&&U(`span.stat-unit`,n)),i&&U(`div.stat-compare`,i),a.length>1&&Qe(a,c===!1?`var(--danger)`:`var(--ok)`))}function Qe(e,t=`var(--ok)`,{width:n=220,height:r=34}={}){let i=Math.max(...e,1),a=Math.min(...e,0),o=i-a||1,s=e.length>1?n/(e.length-1):n,c=e.map((e,t)=>`${(t*s).toFixed(1)},${(r-(e-a)/o*r).toFixed(1)}`).join(` `),l=U(`svg.spark`,{viewBox:`0 0 ${n} ${r}`,preserveAspectRatio:`none`,"aria-hidden":`true`});return l.innerHTML=``,l}function $e({value:e,label:t,size:n=168}){let r=Math.max(0,Math.min(100,Number(e)||0)),i=r>=90?`var(--ok)`:r>=70?`var(--warn)`:`var(--danger)`,a=n/2,o=n/2,s=2*Math.PI*62*(240/360),c=(e,t)=>{let n=e*Math.PI/180,r=(e+t)*Math.PI/180,i=+(t>180);return[`M ${a+62*Math.cos(n)} ${o+62*Math.sin(n)}`,`A 62 62 0 ${i} 1 ${a+62*Math.cos(r)} ${o+62*Math.sin(r)}`].join(` `)},l=U(`svg.gauge`,{viewBox:`0 0 ${n} ${n*.78}`,role:`img`,"aria-label":`${t}: ${r}%`});return l.innerHTML=` `,H(`div.gauge-wrap`,l,H(`div.gauge-center`,H(`div.gauge-pct`,`${Math.round(r)}%`),H(`div.gauge-label`,t)))}function et(e){let t=e.reduce((e,t)=>e+(t.value||0),0)||1;return H(`div`,H(`div.segbar`,...e.filter(e=>e.value>0).map(e=>H(`span`,{class:`segbar-part segbar-${e.kind||`idle`}`,style:`width:${(e.value/t*100).toFixed(1)}%`,title:`${e.label}: ${e.value}`}))),H(`div.segbar-legend`,...e.map(e=>H(`span.segbar-key`,H(`span`,{class:`segbar-dot segbar-${e.kind||`idle`}`}),e.label))))}var tt=0;Array.isArray;function X(e,n,r,i,a,o){n||={};var s,c,l=n;if(`ref`in l)for(c in l={},n)c==`ref`?s=n[c]:l[c]=n[c];var u={type:e,props:l,key:r,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--tt,__i:-1,__u:0,__source:a,__self:o};if(typeof e==`function`&&(s=e.defaultProps))for(c in s)l[c]===void 0&&(l[c]=s[c]);return t.vnode&&t.vnode(u),u}function Z({text:e,kind:t=`idle`}){return X(`span`,{className:`pill pill-${t}`,children:e})}var nt=`archie.setup-complete.dismissed.v1`;function rt(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?.(nt),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function it(e=globalThis.localStorage){e?.setItem?.(nt,`1`)}var at=new Set([`waiting_human`,`parked`]);function ot(e=[]){let t=e.filter(e=>at.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 st({node:e}){let t=Y();return J(()=>{t.current&&e&&t.current.replaceChildren(e)},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function ct(e){return X(st,{node:Ze(e)})}function lt(e){return X(st,{node:$e(e)})}function ut({segments:e}){return X(st,{node:et(e)})}function dt({name:e,opts:t}){return X(st,{node:W(e,t)})}function ft({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function pt(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 mt(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function ht(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 gt(){let[e,t]=q([]),[n,r]=q(`connecting`),[i,a]=q(`idle`),[o,s]=q(new Map),[c,l]=q(null),[u,d]=q(null),[f,p]=q(null),[m,h]=q(null),[g,_]=q(null),[,v]=q(!1),y=async()=>{_(null);try{let[e,t,n,r]=await Promise.all([z.summary(),z.setup().catch(()=>null),z.workflows().catch(()=>null),z.tasks().catch(()=>[])]),i=new Map;for(let e of r)e.owner&&e.repo&&e.issue_number&&i.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);s(i),l(e),d(t),p(n),h(r)}catch(e){_(String(e.message||e))}};J(()=>(y(),B(e=>{t(t=>{let n=[e,...t];return n.splice(50),n})},e=>{r(e),a(e===`live`?`ok`:`warn`)})),[]);let b=()=>{it(),v(e=>!e)},x=u?.operator?`${mt()}, ${u.operator}`:mt(),C=null;if(g)C=X(`button`,{className:`btn btn-primary`,onClick:y,children:[X(dt,{name:`refresh`,opts:{size:15}}),` Retry`]});else if(m!==null){let e=ot(m),t=e.attention.count,n=e.running.count;C=X(S,{children:[t>0&&X(`a`,{className:`btn btn-attention`,href:e.attention.href,children:[X(dt,{name:`tasks`,opts:{size:15}}),` `,t,` need`,t===1?`s`:``,` you`]}),n>0&&X(`a`,{className:`btn`,href:e.running.href,children:[X(dt,{name:`workflows`,opts:{size:15}}),` `,n,` running`]}),X(`a`,{className:`btn`,href:`#/logs`,children:[X(dt,{name:`logs`,opts:{size:15}}),` Logs`]}),X(`button`,{className:`btn btn-primary`,onClick:y,children:[X(dt,{name:`refresh`,opts:{size:15}}),` Refresh`]})]})}let w=null;if(g)w=X(`div`,{className:`card`,children:X(ft,{title:`Cannot reach archied`,detail:g})});else if(c){let e=c?.statuses||{},t=(e.merged||0)+(e.pr_open||0),n=(e.parked||0)+(e.waiting_human||0),r=Object.values(e).reduce((e,t)=>e+t,0),i=c?.tokens_by_day||[];w=X(S,{children:[X(ct,{label:`Working now`,value:e.running||0,compare:`${e.queued||0} waiting to start`,series:i.map(e=>e.tokens||0)}),X(ct,{label:`Needs you`,value:n,compare:n?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),X(ct,{label:`Delivered`,value:t,compare:r?`${Math.round(t/r*100)}% of all tasks`:`No tasks yet`}),X(ct,{label:`Tokens used`,value:Oe(i.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${i.length||0} days`,trend:ht(i.map(e=>e.tokens||0)),goodDirection:`down`,series:i.map(e=>e.tokens||0)})]})}let T=null,E=rt(u),D=E.kind===`omit`||E.kind===`dismissed`;if(!D){let e=E.remaining;if(e.length){let t=Math.round((u.steps.length-e.length)/u.steps.length*100);T=X(`div`,{className:`card setup`,children:[X(`div`,{className:`card-head`,children:[X(`div`,{children:[X(`h2`,{className:`card-title`,children:`Finish setting up`}),X(`p`,{className:`card-sub`,children:`Archie needs these before it can work on its own.`})]}),X(`span`,{className:`setup-pct`,children:[t,`%`]})]}),X(`div`,{className:`setup-bar`,children:X(`div`,{className:`setup-bar-fill`,style:{width:`${t}%`}})}),X(`ul`,{className:`setup-list`,children:u.steps.map((e,t)=>X(`li`,{className:`setup-step ${e.done?`done`:``}`,children:[X(`span`,{className:`setup-check`,children:e.done?X(dt,{name:`check`,opts:{size:12}}):``}),X(`div`,{children:[X(`div`,{className:`setup-step-title`,children:e.title}),e.detail&&X(`div`,{className:`setup-step-detail`,children:e.detail})]})]},t))})]})}else T=X(`div`,{className:`card setup setup-done`,children:X(`div`,{className:`card-head`,children:[X(`div`,{children:[X(`h2`,{className:`card-title`,children:`Setup complete`}),X(`p`,{className:`card-sub`,children:`Archie is configured and ready to work.`})]}),X(`div`,{className:`setup-complete-actions`,children:[X(`span`,{className:`setup-pct`,children:X(dt,{name:`check`,opts:{size:16}})}),X(`button`,{className:`icon-btn setup-dismiss`,type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onClick:b,children:`×`})]})]})})}let O=null;if(c){let e=f?.workflows||[],t=e.reduce((e,t)=>e+(t.runs||0),0),n=e.reduce((e,t)=>e+(t.merged||0)+(t.pr_open||0),0),r=e.reduce((e,t)=>e+(t.parked||0),0);if(!t)O=X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:X(`h2`,{className:`card-title`,children:`Gate pulse`})}),X(ft,{title:`No completed runs yet`,detail:`Once Archie finishes a task, its gate pass rate appears here.`})]});else{let i=n/t*100;O=X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:`Gate pulse`}),X(`p`,{className:`card-sub`,children:`Work that passed its quality gates`})]})}),X(lt,{value:i,label:`pass rate`}),X(`ul`,{className:`pulse-list`,children:[e.slice(0,3).map((e,t)=>X(`li`,{className:`pulse-item`,children:[X(`span`,{className:`pulse-name`,children:e.workflow||`workflow`}),X(Z,{text:`${e.merged||0}/${e.runs||0}`,kind:(e.merged||0)===(e.runs||0)?`ok`:(e.parked||0)>0?`warn`:`info`})]},t)),r>0&&X(`li`,{className:`pulse-item`,children:[X(`span`,{className:`pulse-name`,children:`Parked, awaiting you`}),X(Z,{text:String(r),kind:`warn`})]})]})]})}}let k=null;if(c){let e=c?.tokens_by_day||[],t=e.reduce((e,t)=>e+(t.tokens||0),0);if(!e.length)k=X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:X(`h2`,{className:`card-title`,children:`Token outlook`})}),X(ft,{title:`Nothing spent yet`,detail:`Usage appears here once Archie runs its first task.`})]});else{let n=t/e.length,r=Math.round(n*30),i=e.slice(-7).reduce((e,t)=>e+(t.tokens||0),0);k=X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:`Token outlook`}),X(`p`,{className:`card-sub`,children:`Next 30 days at the current rate`})]})}),X(`div`,{className:`forecast-value`,children:Oe(r)}),X(`div`,{className:`forecast-note`,children:[`Based on `,Oe(Math.round(n)),` per day over `,e.length,` days`]}),X(ut,{segments:[{label:`Last 7 days (${Oe(i)})`,value:i,kind:`info`},{label:`Earlier (${Oe(t-i)})`,value:Math.max(t-i,0),kind:`idle`}]})]})}}return X(S,{children:[X(`div`,{className:`hero`,children:[X(`div`,{children:[X(`h1`,{className:`hero-title`,children:x}),X(`p`,{className:`hero-sub`,children:`Your agent's control room — what it is working on, what needs you, and what it is spending.`})]}),X(`div`,{className:`hero-actions`,children:X(`div`,{className:`hero-actions-inner`,children:C})})]}),X(`div`,{className:`dash-section`,children:[X(`div`,{className:`dash-section-head`,children:X(`h2`,{className:`dash-section-title`,children:`Health`})}),X(`div`,{className:`dash-top ${D?`dash-top-standalone`:``}`,children:[X(`div`,{children:T}),X(`div`,{children:O})]})]}),X(`div`,{className:`dash-section`,children:[X(`div`,{className:`dash-section-head`,children:[X(`h2`,{className:`dash-section-title`,children:`Throughput`}),X(`span`,{className:`dash-section-note`,children:`Across all repositories`})]}),X(`div`,{className:`grid grid-4`,children:w})]}),X(`div`,{className:`dash-section`,children:[X(`div`,{className:`dash-section-head`,children:X(`h2`,{className:`dash-section-title`,children:`Right now`})}),X(`div`,{className:`dash-split`,children:[X(`div`,{children:k}),X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:[X(`div`,{children:[X(`h2`,{className:`card-title`,children:`Live activity`}),X(`p`,{className:`card-sub`,children:`Last 50, newest first`})]}),X(Z,{text:n,kind:i})]}),X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Event`}),X(`th`,{children:`Task`}),X(`th`,{children:`Detail`}),X(`th`,{children:`When`})]})}),X(`tbody`,{children:e.length?e.map((e,t)=>{let n=pt(e,o),r=n>0,i=()=>{r&&(location.hash=`#/tasks?task=${encodeURIComponent(n)}`)};return X(`tr`,{className:r?`activity-row`:``,role:r?`link`:void 0,tabIndex:r?`0`:void 0,title:r?`Open task details`:void 0,onClick:r?i:void 0,onKeyDown:r?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i())}:void 0,children:[X(`td`,{className:`strong`,children:X(`span`,{children:e.kind||e.type||`event`})}),X(`td`,{className:`mono`,children:r?`#${n}`:`—`}),X(`td`,{children:e.detail||e.message||``}),X(`td`,{children:U(e.at||Date.now())})]},t)}):X(`tr`,{children:X(`td`,{colSpan:`4`,children:X(ft,{title:`Waiting for activity`,detail:`Events appear here as Archie works.`})})})})]})})]})]})]})]})}function _t(){return X(gt,{})}function vt(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 yt=V(),bt=new Set([`needs_you`,...we()]);function xt(e){let t=e?.get?.(`status`)||``;return bt.has(t)?t:``}function St(e,t){return t?t===`needs_you`?yt.has(e.status):e.status===t:!0}function Ct(e){return String(e||`event`).replaceAll(`_`,` `).replace(/\b\w/g,e=>e.toUpperCase())}function wt(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 Tt(e){let t=Number(e);return!Number.isFinite(t)||t<=0?``:t.toLocaleString(`en-US`)}function Et(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=wt(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=Tt(t.iterations),i=Tt(t.tokens),a=Number(t.cached_tokens)||0,o=Tt((Number(t.prompt_tokens)||0)-a),s=Tt(t.completion_tokens),c=Tt(t.cached_tokens),l=[r&&`${r} iterations`,i&&`${i} tokens`,o&&`${o} fresh prompt`,s&&`${s} completion`,c&&`${c} cached`,t.model].filter(Boolean);return{title:`Agent ${t.status||`finished`}: ${n}`,detail:l.join(` · `)||e.detail||``}}return{title:Ct(e.kind||e.type),detail:e.detail||``}}function Dt(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function Ot(e){let t=e.fields||{};return H(`div.log-row.log-${Dt(e.level)}`,H(`span.log-time.mono`,At(e.time)),H(`span.log-level`,(e.level||`info`).toUpperCase()),H(`span.log-body`,H(`span.log-msg`,e.message||e.msg||``),...Object.entries(t).map(([e,t])=>H(`span.log-field`,H(`span.log-field-key`,e),String(kt(t))))))}function kt(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function At(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function jt({entry:e}){let t=Y(null);return J(()=>{t.current&&t.current.replaceChildren(Ot(e))},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function Mt({state:e,onRetry:t}){if(e===void 0)return X(`div`,{className:`task-log-loading`,children:`Loading attempt log…`});if(e===null)return X(`div`,{className:`task-log-error`,children:[X(`div`,{className:`task-timeline-detail`,children:`Could not load this attempt's log.`}),X(`button`,{className:`btn`,onClick:t,children:`Retry`})]});if(e.disabled)return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:`No persisted log for this attempt`}),X(`div`,{children:`Task logging is optional and was not enabled for this run.`})]});let n=e.entries||[];return n.length?X(`div`,{className:`log-list task-log-list`,children:n.map((e,t)=>X(jt,{entry:e},t))}):X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:`Nothing recorded`}),X(`div`,{children:`This attempt's log file has no entries matching the current filter.`})]})}function Nt(e){let t=Y(null);return J(()=>{t.current&&t.current.replaceChildren(Ze(e))},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function Pt({kind:e,message:t}){return e===`session-expired`?X(`span`,{className:`task-action-error task-action-error-session`,children:[`Your session has expired.`,` `,X(`button`,{className:`button btn btn-small`,type:`button`,onClick:()=>window.location.reload(),children:`Reload to sign in`})]}):e===`refused`?X(`span`,{className:`task-action-error task-action-error-refused`,children:[t,` — you can't do that.`]}):X(`span`,{className:`task-action-error task-action-error-broken`,children:[t,` — try again, or check the daemon.`]})}function Ft({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function It({query:e}){let[t,n]=q(null),[r,i]=q(null),[a,o]=q(()=>xt(e)),[s,c]=q(``),l=Number(e.get(`task`)),u=Number.isFinite(l)&&l>0?l:null,[d,f]=q(u),[p,m]=q(u!==null),[h,g]=q(new Map),[_,v]=q(new Map),[y,b]=q(new Set),[x,C]=q(new Map),[w,T]=q(new Set),E=async()=>{try{i(null);let e=await z.tasks();n(e),d&&e.some(e=>String(e.id)===String(d))&&(h.has(d)||D(d))}catch(e){i(String(e.message||e)),n(null)}};J(()=>{E()},[]);let D=async e=>{try{let t=await z.task(e);g(n=>new Map(n).set(e,t||[]))}catch{g(t=>new Map(t).set(e,null))}},O=async e=>{v(t=>{let n=new Map(t);return n.delete(e),n});try{let t=await z.taskLogs(e,{limit:500});v(n=>new Map(n).set(e,t))}catch{v(t=>new Map(t).set(e,null))}},k=async(e,t)=>{C(t=>{let n=new Map(t);return n.delete(e),n}),T(t=>new Set(t).add(e));try{await z.taskAction(e,t),T(t=>{let n=new Set(t);return n.delete(e),n}),t===`archive`&&f(null),await E()}catch(t){T(t=>{let n=new Set(t);return n.delete(e),n}),C(n=>new Map(n).set(e,fe(t)))}};J(()=>{p&&d&&t&&(m(!1),requestAnimationFrame(()=>{let e=document.getElementById(`task-row-${d}`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView({block:`center`,behavior:`smooth`}))}))},[p,d,t]);let A=(e,t)=>{t&&t.stopPropagation();let n=d!==e;f(n?e:null),n&&D(e)},j=e=>{b(t=>{let n=new Set(t);return n.has(e)?n.delete(e):(n.add(e),_.has(e)||O(e)),n})},ee=()=>{if(!t)return null;let e=t.length,n={};for(let e of t)n[e.status]=(n[e.status]||0)+1;let r=n.running||0,i=(n.waiting_human||0)+(n.parked||0),a=(n.merged||0)+(n.pr_open||0);return X(`div`,{className:`grid grid-4 task-summary`,children:[X(Nt,{label:`Total tasks`,value:e,compare:e?`Everything archied has ever picked up`:`No tasks yet`}),X(Nt,{label:`Working now`,value:r,compare:e?`${r} of ${e} in progress`:`Nothing running`}),X(Nt,{label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),X(Nt,{label:`Delivered`,value:a,compare:e?`${Math.round(a/e*100)}% of all tasks`:`No tasks yet`})]})},M=e=>{let t=x.get(e.id),n=t?Pt(t):null,r=w.has(e.id),i=e=>e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``,a=(e.actions||[]).map(t=>{let n=Te(t);if(!n)return null;let a=e.title||`this task`,o=n.confirm?n.confirm.replaceAll(`{title}`,a):void 0,s=[`button`,`btn`,`btn-small`,i(n.kind)].filter(Boolean).join(` `);if(n.kind===`link`){if(t===`open_pr`)return N(e,`pull_request`,e.pr_number,n.label);if(t===`open_issue`)return N(e,`issue`,e.issue_number,n.label)}return X(`button`,{className:s,type:`button`,disabled:r,onClick:n=>{n.stopPropagation(),!(o&&!window.confirm(o))&&k(e.id,t)},children:n.label},t)}).filter(Boolean);return!a.length&&!n?`—`:X(`div`,{className:`task-actions`,children:[n,a]})},N=(e,t,n,r)=>{let i=t===`issue`?e.issue_url:e.pr_url;return!i||!n||t===`issue`&&e.source===`chat`?X(`button`,{className:`btn btn-small`,type:`button`,disabled:!0,title:`${r} is unavailable`,children:r}):X(`a`,{className:`btn btn-small`,href:i,target:`_blank`,rel:`noreferrer`,onClick:e=>e.stopPropagation(),children:r})},P=e=>{let t=e.repo_url;return t?X(`a`,{className:`task-source-link`,href:t,target:`_blank`,rel:`noreferrer`,title:`Open ${e.owner}/${e.repo} on the forge`,onClick:e=>e.stopPropagation(),children:[e.owner,`/`,e.repo]}):null},te=e=>{let t=e.issue_url;return e.source===`chat`||!t||!e.issue_number?null:X(`a`,{className:`task-source-link`,href:t,target:`_blank`,rel:`noreferrer`,title:`Open issue #${e.issue_number} on the forge`,onClick:e=>e.stopPropagation(),children:[`#`,e.issue_number]})},ne=e=>{let t=h.get(e.id),n=y.has(e.id);return X(`tr`,{className:`task-timeline-row`,id:`task-timeline-${e.id}`,children:X(`td`,{colSpan:8,children:[X(`div`,{className:`task-detail-actions`,children:[X(`div`,{className:`task-decision-title`,children:`Available actions`}),M(e)]}),e.status===`waiting_human`&&e.plan&&X(`div`,{className:`task-decision`,children:[X(`div`,{className:`task-decision-title`,children:`Decision required`}),X(`div`,{className:`task-decision-plan`,children:e.plan})]}),e.status===`parked`&&e.park_reason&&X(`div`,{className:`task-decision`,children:[X(`div`,{className:`task-decision-title`,children:`Park reason`}),X(`div`,{className:`task-decision-plan`,children:e.park_reason})]}),t===void 0?X(`div`,{className:`task-timeline-loading`,children:`Loading timeline…`}):t===null?X(`div`,{className:`task-timeline-error`,children:[X(`div`,{className:`task-timeline-title`,children:`Could not load timeline`}),X(`div`,{className:`task-timeline-detail`,children:`archied did not answer for this task's events. It may be restarting — retry, or check the daemon.`}),X(`button`,{className:`btn`,onClick:()=>D(e.id),children:`Retry`})]}):t.length?X(`ul`,{className:`task-timeline`,children:t.map((e,t)=>{let n=Et(e);return X(`li`,{className:`task-timeline-entry`,children:[X(`span`,{className:`task-timeline-dot`}),X(`div`,{children:[X(`div`,{className:`task-timeline-kind`,children:n.title}),n.detail&&X(`div`,{className:`task-timeline-detail`,children:n.detail}),X(`div`,{className:`task-timeline-when`,children:U(e.at)})]})]},t)})}):X(Ft,{title:`No events yet`,detail:`This task has not recorded any transitions.`}),X(`div`,{className:`task-logs-section`,children:[X(`div`,{className:`task-decision-title`,children:[`Attempt log`,X(`button`,{className:`btn btn-small`,onClick:()=>j(e.id),style:{marginLeft:`10px`},children:n?`Hide`:`Show`})]}),n&&X(Mt,{state:_.get(e.id),onRetry:()=>O(e.id)})]})]})})};return X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Tasks`}),X(`p`,{className:`page-sub`,children:`Every issue archied has picked up, and where it stands.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn`,onClick:E,children:`Refresh`})})]}),r?X(`div`,{className:`grid grid-4 task-summary`,children:X(`div`,{className:`card`,children:X(Ft,{title:`Cannot reach archied`,detail:r})})}):ee(),X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:[X(`div`,{children:[X(`h2`,{className:`card-title`,children:`All tasks`}),X(`p`,{className:`card-sub`,children:`Click a row for its timeline`})]}),X(`div`,{className:`task-filters`,children:[X(`input`,{className:`task-search`,type:`search`,placeholder:`Search by title or repo…`,value:s,onInput:e=>c(e.target.value.trim().toLowerCase())}),X(`select`,{className:`task-filter`,value:a,onChange:e=>o(e.target.value),children:[X(`option`,{value:``,children:`All statuses`}),X(`option`,{value:`needs_you`,children:`Needs you`}),we().map(e=>X(`option`,{value:e,children:Se(e)},e))]})]})]}),X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[`Repo`,`Issue`,`Title`,`Status`,`Workflow`,`Stage`,`Last activity`,`Action`].map(e=>X(`th`,{children:e},e))})}),X(`tbody`,{children:(()=>{if(r)return X(`tr`,{children:X(`td`,{colSpan:8,children:X(Ft,{title:`Cannot reach archied`,detail:r})})});if(!t)return X(`tr`,{children:X(`td`,{colSpan:8,children:X(`div`,{className:`task-timeline-loading`,children:`Loading tasks...`})})});if(!t.length)return X(`tr`,{children:X(`td`,{colSpan:8,children:X(Ft,{title:`No tasks yet`,detail:`Tasks appear here once archied picks up an issue to work.`})})});let e=t.filter(e=>St(e,a)?!s||`${e.title} ${e.repo}`.toLowerCase().includes(s):!1);return e.length?e.map(e=>{let t=d===e.id,n=`task-timeline-${e.id}`;return X(S,{children:[X(`tr`,{className:`task-row`,id:`task-row-${e.id}`,tabIndex:0,onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),A(e.id,t))},onClick:t=>A(e.id,t),...vt(e,t),children:[X(`td`,{className:`mono`,"data-label":`Repository`,children:[X(`button`,{className:`task-expand`,type:`button`,"aria-expanded":String(t),"aria-controls":n,"aria-label":`${t?`Collapse`:`Expand`} timeline for ${e.title||`untitled task`}`,onClick:t=>A(e.id,t),children:t?`−`:`+`}),P(e)??`${e.owner}/${e.repo}`]}),X(`td`,{className:`mono`,"data-label":`Issue`,children:te(e)??`#${e.issue_number}`}),X(`td`,{className:`strong`,"data-label":`Title`,children:e.title||`(untitled)`}),X(`td`,{"data-label":`Status`,children:X(Z,{text:Se(e.status),kind:Ce(e.status)})}),X(`td`,{"data-label":`Workflow`,children:e.workflow||`—`}),X(`td`,{"data-label":`Stage`,children:e.stage||`—`}),X(`td`,{"data-label":`Last activity`,title:e.created_at?`Created ${U(e.created_at)}`:``,children:U(e.updated_at)}),X(`td`,{"data-label":`Actions`,children:M(e)})]}),t&&ne(e)]},e.id)}):X(`tr`,{children:X(`td`,{colSpan:8,children:X(Ft,{title:`No matching tasks`,detail:`Try a different search or status filter.`})})})})()})]})})]})]})}function Lt(e){return X(It,{query:e})}function Rt({title:e,detail:t}){return X(`div`,{class:`empty`,children:[X(`div`,{class:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function zt(e){return X(Bt,{query:e})}function Bt(){let[e,t]=q([]),[n,r]=q(``),[i,a]=q(null),o=async()=>{try{let e=await z.skills();t(e?.skills||[]),a(null)}catch(e){t([]),a(String(e.message||e))}};J(()=>{o()},[]);let s=(e,t)=>!t||`${e.name} ${e.description}`.toLowerCase().includes(t),c=Ue(()=>e.filter(e=>s(e,n)),[e,n]);return X(`div`,{children:[X(`div`,{class:`page-head`,children:[X(`div`,{children:[X(`h1`,{class:`page-title`,children:`Skills`}),X(`p`,{class:`page-sub`,children:`What Archie can do, in plain language.`})]}),X(`div`,{class:`page-actions`,children:X(`button`,{class:`btn`,onClick:o,children:`Refresh`})})]}),X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:[X(`div`,{children:[X(`h2`,{class:`card-title`,children:`Catalogue`}),X(`p`,{class:`card-sub`,children:`Project, shared, and user-global skills`})]}),X(`input`,{class:`skill-search`,type:`search`,placeholder:`Search skills…`,onInput:e=>r(e.target.value.trim().toLowerCase())})]}),X(`div`,{class:`grid grid-2`,children:i?X(Rt,{title:`Cannot reach archied`,detail:i}):e.length?c.length?c.map(e=>X(`div`,{class:`card skill-card`,children:[X(`div`,{class:`card-head`,children:[X(`h3`,{class:`card-title`,children:e.name||`Untitled skill`}),e.workflow&&X(Z,{text:e.workflow,kind:`info`})]}),X(`p`,{class:`skill-desc`,children:e.description||`No description provided.`}),X(`div`,{class:`skill-source`,children:e.source||`Unknown source`})]},e.name)):X(Rt,{title:`No skills match`,detail:`Nothing found for "${n}".`}):X(Rt,{title:`No skills discovered yet`,detail:`Skills live as SKILL.md files under project, shared, or user-global .agents/skills// directories. Add one and refresh to make it available.`})})]})]})}var Vt={bootstrap:`Bootstrap`,implement:`Implement`,tdd:`TDD`,feasibility:`Feasibility check`};function Ht(e){return Vt[e]?Vt[e]:e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown`}function Ut(e,t){return t?Math.round(e/t*100):0}function Wt(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 Gt({title:e,detail:t}){return X(`div`,{class:`empty`,children:[X(`div`,{class:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Kt({fraction:e,kind:t=`ok`}){let n=Math.min(100,Math.max(0,e));return X(`div`,{class:`wf-bar`,children:X(`div`,{class:`wf-bar-fill wf-bar-${t}`,style:{width:`${n}%`}})})}function qt(e){return X(Jt,{query:e})}function Jt(){let[e,t]=q([]),[n,r]=q([]),[i,a]=q([]),[o,s]=q(null),c=async()=>{try{let e=await z.workflows();t(e?.definitions||[]),r(e?.workflows||[]),a(e?.stages||[]),s(null)}catch(e){s(String(e.message||e))}};return J(()=>{c()},[]),X(`div`,{children:[X(`div`,{class:`page-head`,children:[X(`div`,{children:[X(`h1`,{class:`page-title`,children:`Workflows`}),X(`p`,{class:`page-sub`,children:`Run outcomes and spend per workflow, and where stages get stuck.`})]}),X(`div`,{class:`page-actions`,children:X(`button`,{class:`btn`,onClick:c,children:`Refresh`})})]}),X(Yt,{definitions:e}),o?X(`div`,{class:`card`,children:X(Gt,{title:`Cannot reach archied`,detail:o})}):X(S,{children:[X(Xt,{workflows:n,definitions:e}),X(Zt,{stages:i})]})]})}function Yt({definitions:e}){if(!e.length)return null;let t=e.filter(e=>e.enabled)[0]?.id||``,[n,r]=q(``),[i,a]=q(``),[o,s]=q(t),[c,l]=q(``),[u,d]=q(``),[f,p]=q(!1),[m,h]=q(``);return J(()=>{!o&&t&&s(t)},[t,o]),X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:[X(`h2`,{class:`card-title`,children:`Start work`}),X(`p`,{class:`card-sub`,children:`This enters Archie’s normal admitted task queue.`})]})}),X(`form`,{class:`wf-form`,onSubmit:async e=>{e.preventDefault(),p(!0),h(``);try{let e=await z.workRequest({identity:n,repository:i,workflow:o,title:c,instructions:u});h(`Queued task #${e.task_id}.`),r(``),a(``),s(t),l(``),d(``)}catch(e){h(String(e.message||e))}finally{p(!1)}},children:[X(`input`,{placeholder:`Identity`,required:!0,value:n,onInput:e=>r(e.target.value)}),X(`input`,{placeholder:`owner/repository`,required:!0,value:i,onInput:e=>a(e.target.value)}),X(`select`,{required:!0,value:o,onInput:e=>s(e.target.value),children:e.filter(e=>e.enabled).map(e=>X(`option`,{value:e.id,children:Ht(e.name||e.id)},e.id))}),X(`input`,{placeholder:`Short task title`,required:!0,value:c,onInput:e=>l(e.target.value)}),X(`textarea`,{placeholder:`Instructions for the work`,required:!0,rows:3,value:u,onInput:e=>d(e.target.value)}),X(`button`,{class:`btn`,type:`submit`,disabled:f,children:`Start work`}),m&&X(`p`,{class:`card-sub`,children:m})]})]})}function Xt({workflows:e,definitions:t}){let n=new Map(e.map(e=>[e.workflow,e])),r=t.map(e=>({...e,...n.get(e.id)||{workflow:e.id,runs:0,merged:0}}));return r.length?X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:[X(`h2`,{class:`card-title`,children:`Per workflow`}),X(`p`,{class:`card-sub`,children:`Success rate is merged tasks over all runs`})]})}),X(`div`,{class:`table-scroll`,children:X(`table`,{class:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Workflow`}),X(`th`,{children:`Origin`}),X(`th`,{children:`Runs`}),X(`th`,{children:`Success rate`}),X(`th`,{children:`Avg tokens`}),X(`th`,{children:`Avg steps`})]})}),X(`tbody`,{children:r.map(e=>{let t=Ut(e.merged,e.runs);return X(`tr`,{children:[X(`td`,{class:`strong`,children:Ht(e.workflow)}),X(`td`,{class:`mono`,children:e.origin||`registry`}),X(`td`,{children:`${e.runs} run${e.runs===1?``:`s`}`}),X(`td`,{children:[X(`div`,{class:`wf-rate`,children:[t,`%`,X(`span`,{class:`wf-rate-sub`,children:[e.merged,` of `,e.runs,` merged`]})]}),X(Kt,{fraction:t,kind:t>=50?`ok`:`warn`})]}),X(`td`,{class:`mono`,children:e.avg_tokens?e.avg_tokens.toLocaleString():`—`}),X(`td`,{class:`mono`,children:e.avg_steps?e.avg_steps.toFixed(1):`—`})]},e.workflow)})})]})})]}):X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:X(`h2`,{class:`card-title`,children:`Per workflow`})})}),X(Gt,{title:`No workflow runs yet`,detail:`Stats appear here once a task has run through a workflow.`})]})}function Zt({stages:e}){if(!e.length)return X(`div`,{class:`card wf-stage-card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:X(`h2`,{class:`card-title`,children:`Per stage`})})}),X(Gt,{title:`No stage data yet`,detail:`Stage timing and failures appear here once workflows have run.`})]});let t=Math.max(...e.map(e=>e.avg_ms||0),1),n=[...e].sort((e,t)=>(t.avg_ms||0)-(e.avg_ms||0)),r=[...e].filter(e=>e.errors>0).sort((e,t)=>t.errors-e.errors);return X(`div`,{class:`grid grid-2 wf-stage-card`,children:[X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:[X(`h2`,{class:`card-title`,children:`Slowest stages`}),X(`p`,{class:`card-sub`,children:`Average duration, this workflow's stages`})]})}),X(`div`,{class:`table-scroll`,children:X(`table`,{class:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Workflow`}),X(`th`,{children:`Stage`}),X(`th`,{children:`Runs`}),X(`th`,{children:`Avg duration`})]})}),X(`tbody`,{children:n.map((e,n)=>X(`tr`,{children:[X(`td`,{children:Ht(e.workflow)}),X(`td`,{class:`strong`,children:e.stage}),X(`td`,{children:e.runs}),X(`td`,{children:[X(`div`,{class:`wf-rate`,children:Wt(e.avg_ms)}),X(Kt,{fraction:Ut(e.avg_ms,t),kind:`info`})]})]},n))})]})})]}),X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:[X(`h2`,{class:`card-title`,children:`Most failures`}),X(`p`,{class:`card-sub`,children:`Stages that error out, over their runs`})]})}),r.length?X(`div`,{class:`table-scroll`,children:X(`table`,{class:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Workflow`}),X(`th`,{children:`Stage`}),X(`th`,{children:`Failures`})]})}),X(`tbody`,{children:r.map((e,t)=>X(`tr`,{children:[X(`td`,{children:Ht(e.workflow)}),X(`td`,{class:`strong`,children:e.stage}),X(`td`,{children:[X(`div`,{class:`wf-rate`,children:[e.errors,` of `,e.runs]}),X(Kt,{fraction:Ut(e.errors,e.runs),kind:`danger`})]})]},t))})]})}):X(Gt,{title:`No failures recorded`,detail:`Every stage has completed cleanly so far.`})]})]})}function Qt({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function $t(e,t){return e===`running`?`ok`:e===`failed`||e===`degraded`?`warn`:`idle`}function en(){let[e,t]=q([]),[n,r]=q(null),i=async()=>{try{let e=await z.channels();t(e?.channels||[]),r(null)}catch(e){r(String(e.message||e))}};return J(()=>{i()},[]),X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Channels`}),X(`p`,{className:`page-sub`,children:`The conversational front-ends Archie can be reached through.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn`,onClick:i,children:`Refresh`})})]}),X(`div`,{className:`grid grid-2`,children:n?X(Qt,{title:`Cannot reach archied`,detail:n}):e.length===0?X(Qt,{title:`No channels configured`,detail:`Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.`}):e.map(e=>X(`div`,{className:`card channel-card`,children:[X(`div`,{className:`card-head`,children:[X(`h3`,{className:`card-title`,children:e.name}),X(Z,{text:e.state||(e.configured?`configured`:`stopped`),kind:$t(e.state,e.configured)})]}),X(`p`,{className:`channel-desc`,children:e.description}),X(`p`,{className:`channel-detail`,children:e.detail}),e.reload_supported?X(`button`,{className:`btn`,onClick:async t=>{t.currentTarget.disabled=!0;try{await z.channelReload(e.id||e.name.toLowerCase()),await i()}catch{}finally{t.currentTarget&&(t.currentTarget.disabled=!1)}},children:`Reload`}):X(`p`,{className:`channel-detail`,children:`Reload requires a daemon restart for this adapter.`})]},e.id||e.name))})]})}function tn(e){return X(en,{query:e})}function nn({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function rn(e){return X(an,{query:e})}function an({query:e}){let[t,n]=q([]),[r,i]=q(null),a=async()=>{try{let e=await z.curators();n(e?.curators||[]),i(null)}catch(e){i(String(e.message||e))}};return J(()=>{a()},[]),X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Curators`}),X(`p`,{className:`page-sub`,children:`Background agents that maintain memory and skills: what ran, and why.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn`,onClick:a,children:`Refresh`})})]}),X(`div`,{className:`grid grid-2`,children:r?X(nn,{title:`Cannot reach archied`,detail:r}):t.length?t.map(e=>X(sn,{curator:e},e.name)):X(nn,{title:`No curators registered`,detail:`Curators are background agent loops that maintain memory and skills. None are registered on this daemon.`})})]})}function on(e){switch(e){case`healthy`:return`ok`;case`degraded`:return`warn`;case`unhealthy`:return`danger`;default:return`idle`}}function sn({curator:e}){let t=e.recent_actions||[];return X(`div`,{className:`card curator-card`,children:[X(`div`,{className:`card-head`,children:[X(`h3`,{className:`card-title`,children:e.name}),X(Z,{text:e.health?.status||`unknown`,kind:on(e.health?.status)})]}),e.health?.message&&X(`p`,{className:`curator-health-message`,children:e.health.message}),X(`p`,{className:`curator-meta`,children:e.last_run_at?`Last ran ${U(e.last_run_at)} · ${e.last_run_actions} action${e.last_run_actions===1?``:`s`}`:`Has not run yet`}),t.length?X(`ul`,{className:`curator-actions`,children:t.map((e,t)=>X(`li`,{className:`curator-action`,children:[X(`div`,{className:`curator-action-head`,children:[X(`span`,{className:`curator-action-type`,children:e.type||`action`}),X(`span`,{className:`curator-action-time`,children:U(e.at)})]}),e.detail&&X(`p`,{className:`curator-action-detail`,children:e.detail}),e.reason&&X(`p`,{className:`curator-action-reason`,children:[`Why: `,e.reason]})]},t))}):X(`p`,{className:`curator-meta`,children:`No recorded activity yet.`})]})}function cn(e){return e==null||e===``?`—`:String(e)}function ln({label:e,value:t,opts:n}){let r=cn(t),[i,a]=q(!1),[o,s]=q(``),[c,l]=q(null),[u,d]=q(!1),[f,p]=q(!1),m=n?.key;if(!m)return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,title:n?.hint,children:e}),X(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r})]});let h=n.locked?.[m];if(h)return X(`div`,{className:`kv is-locked`,children:[X(`span`,{className:`kv-label`,title:n.hint,children:e}),X(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r}),X(`span`,{className:`kv-note`,children:h})]});if(n.editable===!1)return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,title:n.hint,children:e}),X(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r})]});let g=n.overridden?.includes(m),_=()=>{s(String(n.raw??``)),l(null),a(!0)},v=async()=>{p(!0),l(null);try{await z.configReset(m),n.onSaved?.()}catch(e){l(String(e.message||e))}finally{p(!1)}},y=async()=>{let e=un(n.type,o);if(e.error){l(e.error);return}d(!0),l(null);try{await(n.save||(e=>z.configUpdate({[m]:e})))(e.value),a(!1),n.onSaved?.()}catch(e){l(String(e.message||e))}finally{d(!1)}};if(i){let t=Y(null);J(()=>{t.current&&t.current.focus()},[]);let r=e=>{e.key===`Enter`&&(e.preventDefault(),y()),e.key===`Escape`&&a(!1)},i;return i=n.type===`bool`?X(`select`,{className:`kv-input`,value:o,onChange:e=>s(e.target.value),onKeyDown:r,ref:t,children:[X(`option`,{value:`true`,children:`true`}),X(`option`,{value:`false`,children:`false`})]}):n.type===`enum`?X(`select`,{className:`kv-input`,value:o,onChange:e=>s(e.target.value),onKeyDown:r,ref:t,children:(n.options||[]).map(e=>X(`option`,{value:e,children:e},e))}):X(`input`,{className:`kv-input`,type:`text`,value:o,onInput:e=>s(e.target.value),onKeyDown:r,ref:t}),X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,title:n.hint,children:e}),i,X(`div`,{className:`kv-actions`,children:[X(`button`,{className:`kv-save`,type:`button`,onClick:y,disabled:u,children:`Save`}),X(`button`,{className:`kv-cancel`,type:`button`,onClick:()=>a(!1),disabled:u,children:`Cancel`})]}),c&&X(`span`,{className:`kv-note is-error`,children:c})]})}return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,title:n.hint,children:e}),X(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r}),X(`div`,{className:`kv-actions`,children:[g&&X(`span`,{className:`kv-flag`,title:`Set from the dashboard; this shadows the value in the config file`,children:`overridden`}),X(`button`,{className:`kv-btn`,type:`button`,title:`Edit ${e}`,onClick:_,children:`Edit`}),g&&X(`button`,{className:`kv-btn`,type:`button`,title:`Discard the dashboard value and fall back to the config file`,onClick:v,disabled:f,children:`Reset`})]}),c&&X(`span`,{className:`kv-note is-error`,children:c})]})}function un(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}}}function dn({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function fn({sub:e,title:t,children:n}){return X(`div`,{className:`card cfg-section`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:t||`Update status`}),X(`p`,{className:`card-sub`,children:e})]})}),n]})}var pn={ok:`OK`,update_available:`Update available`,drift:`Drift`,unknown:`Unknown`},mn={ok:`ok`,update_available:`info`,drift:`danger`,unknown:`idle`};function hn({components:e}){return!e||!e.length?X(fn,{sub:`How each component is deployed, and whether what's running matches what's installed.`,children:X(dn,{title:`No components reported`,detail:`The configured update-check command returned nothing.`})}):X(fn,{sub:`How each component is deployed, and whether what's running matches what's installed. Hover a row for the exact versions compared.`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Component`}),X(`th`,{children:`Install type`}),X(`th`,{children:`Running`}),X(`th`,{children:`Latest available`}),X(`th`,{children:`Status`})]})}),X(`tbody`,{children:e.map(e=>X(`tr`,{title:[`Installed claim: ${e.installed_claim||`unknown`}`,`Running: ${e.running_version||`not observed`}`,e.reference?`Reference: ${e.reference}`:null].filter(Boolean).join(` -`),children:[X(`td`,{className:`strong`,children:e.label||e.id}),X(`td`,{className:`mono`,children:e.install_type||`—`}),X(`td`,{className:`mono`,children:e.running_version||`—`}),X(`td`,{className:`mono`,children:e.latest_available||`—`}),X(`td`,{children:X(Z,{text:pn[e.status]||e.status,kind:mn[e.status]||`idle`})})]},e.id||e.label))})]})})})}function Q({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function $({title:e,sub:t,children:n}){return X(`div`,{className:`card cfg-section`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:e}),X(`p`,{className:`card-sub`,children:t})]})}),n]})}function gn({origins:e}){return e?.length?X($,{title:`Configuration sources`,sub:`Applied from top to bottom; later entries take precedence over earlier ones.`,children:X(`div`,{className:`kv-list`,children:e.map((e,t)=>X(ln,{label:`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,value:e.path},t))})}):X($,{title:`Configuration sources`,sub:`The files that supplied the running configuration.`,children:X(Q,{title:`Source provenance is unavailable.`})})}function _n(e){return e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``}function vn({data:e,error:t}){if(t)return X($,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships.`,children:X(Q,{title:`Lifecycle unavailable`,detail:t})});let n=e?.statuses||[],r=e?.actions||[];return X($,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships. Add one on the backend and it appears here without a frontend change.`,children:[X(`h3`,{className:`cfg-subhead`,children:`Statuses`}),n.length?X(`div`,{className:`kv-list`,children:n.map(e=>{let t=e.label??Se(e.id),n=e.kind??Ce(e.id);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(Z,{text:t,kind:n})})]},e.id)})}):X(Q,{title:`No statuses reported`,detail:`The server did not return any lifecycle statuses.`}),X(`h3`,{className:`cfg-subhead`,children:`Actions`}),r.length?X(`div`,{className:`kv-list`,children:r.map(e=>{let t=e.label??e.id,n=_n(e.kind);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(`button`,{className:`btn btn-small ${n}`,type:`button`,disabled:!0,children:t})})]},e.id)})}):X(Q,{title:`No actions reported`,detail:`The server did not return any operator actions.`})]})}function yn({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=q(!1),[o,s]=q(null),[c,l]=q(!!e[t]);return r?X(`td`,{children:[X(`input`,{className:`repo-field-checkbox`,type:`checkbox`,checked:c,onChange:async r=>{let i=r.target.checked;l(i),a(!0),s(null);try{await z.configRepoUpdate(e.owner,e.name,t,i),n?.()}catch(e){l(!i),s(String(e.message||e))}finally{a(!1)}},disabled:i}),o&&X(`span`,{className:`kv-note is-error`,children:o})]}):X(`td`,{children:c?`yes`:`no`})}function bn({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=q(String(e[t]??0)),[o,s]=q(null),[c,l]=q(!1);return r?X(`td`,{children:[X(`input`,{className:`kv-input`,type:`text`,value:i,onChange:e=>a(e.target.value),onBlur:async()=>{let r=parseInt(i,10);if(Number.isNaN(r)){s(`Enter a whole number`);return}l(!0),s(null);try{await z.configRepoUpdate(e.owner,e.name,t,r),n?.()}catch(e){s(String(e.message||e))}finally{l(!1)}},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),e.target.blur())},disabled:c}),o&&X(`span`,{className:`kv-note is-error`,children:o})]}):X(`td`,{className:`mono`,children:i})}function xn({repos:e,onSaved:t,editable:n=!0}){if(!e?.length)return X($,{title:`Repositories`,sub:`The repositories Archie polls for work.`,children:X(Q,{title:`No repositories configured`,detail:`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`})});let r=e=>e?.length?e.map(e=>e.join(` `)).join(` → `):`—`;return X($,{title:`Repositories`,sub:`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request. Concurrent tasks, retries, and self-review are per-repository overrides -- PATCH /api/config/repos/{owner}/{name}, not the file config.toml directly.`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Repository`}),X(`th`,{children:`Base branch`}),X(`th`,{children:`Ecosystem`}),X(`th`,{children:`Quality gate`}),X(`th`,{children:`Protected paths`}),X(`th`,{children:`Concurrent`}),X(`th`,{children:`Max retries`}),X(`th`,{children:`Self-review`})]})}),X(`tbody`,{children:e.map((e,i)=>X(`tr`,{children:[X(`td`,{className:`strong`,children:[e.owner,`/`,e.name]}),X(`td`,{className:`mono`,children:e.base}),X(`td`,{children:e.ecosystem||`go`}),X(`td`,{className:`mono`,children:r(e.gate)}),X(`td`,{className:`mono`,children:e.protect?.length?e.protect.join(`, `):`—`}),X(yn,{r:e,field:`allow_concurrent`,onSaved:t,editable:n}),X(bn,{r:e,field:`max_retries`,onSaved:t,editable:n}),X(yn,{r:e,field:`review_enabled`,onSaved:t,editable:n})]},i))})]})})})}function Sn(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function Cn({models:e,providers:t}){let n=Object.entries(e||{}),r=Object.entries(t||{});return X($,{title:`Models & providers`,sub:`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,children:[X(`h3`,{className:`cfg-subhead`,children:`Model roles`}),n.length?X(`div`,{className:`kv-list`,children:n.map(([e,t])=>X(ln,{label:Sn(e),value:t},e))}):X(Q,{title:`No model roles configured`,detail:`Assign a model to at least one role (e.g. "builder") in [models].`}),X(`h3`,{className:`cfg-subhead`,children:`Providers`}),r.length?X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Provider`}),X(`th`,{children:`Class`}),X(`th`,{children:`Base URL`}),X(`th`,{children:`API key env var`}),X(`th`,{children:`Status`})]})}),X(`tbody`,{children:r.map(([e,t])=>X(`tr`,{children:[X(`td`,{className:`strong`,children:e}),X(`td`,{children:t.class}),X(`td`,{className:`mono`,children:t.base_url||`default`}),X(`td`,{className:`mono`,children:t.api_key_env||`—`}),X(`td`,{children:t.configured?X(Z,{text:`configured`,kind:`ok`}):X(Z,{text:`missing credentials`,kind:`warn`})})]},e))})]})}):X(Q,{title:`No providers configured`,detail:`Add a [providers.] entry so a model role above has something to run on.`})]})}function wn(){let[e,t]=q(null),[n,r]=q(null),[i,a]=q(null),[o,s]=q(null),[c,l]=q(!1),[u,d]=q(null),[f,p]=q(null),m=()=>{h(),g(),_()},h=async()=>{try{let e=await z.config();t(e),r(null)}catch(e){r(String(e.message||e))}},g=async()=>{try{let e=await z.version();a(e?.components||[]),s(null),l(!1)}catch(e){e?.status===501?l(!0):s(String(e.message||e))}},_=async()=>{try{let e=await z.taskMeta();d(e),p(null)}catch(e){p(String(e.message||e))}};return J(()=>{m()},[]),X(`div`,{className:`cfg-page`,children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Configuration`}),X(`p`,{className:`page-sub`,children:`What archied is actually running with right now.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn`,onClick:m,children:`Refresh`})})]}),X(`div`,{children:!c&&(o?X(`div`,{className:`card`,children:X(Q,{title:`Update status unavailable`,detail:o})}):i?X(hn,{components:i}):null)}),X(`div`,{children:X(vn,{data:u,error:f})}),X(`div`,{children:n?X(`div`,{className:`card`,children:X(Q,{title:`Cannot reach archied`,detail:n})}):!e||Object.keys(e).length===0?X(`div`,{className:`card`,children:X(Q,{title:`No configuration loaded`,detail:`archied is running without a config file wired into the dashboard, so there is nothing to show.`})}):X(S,{children:[e.reload?.overlay_unavailable&&X(`div`,{className:`card cfg-notice`,children:X(`p`,{children:[`The runtime config overlay is not in effect: `,e.reload.overlay_unavailable]})}),e.reload?.last_error&&X(`div`,{className:`card cfg-notice`,children:X(`p`,{children:[`The last config reload failed; the running config is unchanged: `,e.reload.last_error]})}),(e.schema||[]).map((t,n)=>{let r=t.fields.filter(e=>e.type!==`structured`);return r.length?X($,{title:t.label,sub:t.description,children:X(`div`,{className:`kv-list`,children:r.map(t=>X(ln,{label:t.label,value:t.value,opts:{key:t.key,type:t.type,options:t.options,raw:t.value,hint:t.description,editable:t.editable&&e.editable!==!1,locked:e.locked||{},overridden:e.overridden||[],onSaved:h}},t.key))})},n):null}),X(xn,{repos:e.repositories,onSaved:h,editable:e.editable!==!1}),X(Cn,{models:e.models,providers:e.providers}),X(gn,{origins:e.provenance})]})})]})}function Tn(e){return X(wn,{query:e})}function En({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Dn(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function On(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function kn(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function An({entry:e}){let t=e.fields||{};return X(`div`,{className:`log-row log-${Dn(e.level)}`,children:[X(`span`,{className:`log-time mono`,children:kn(e.time)}),X(`span`,{className:`log-level`,children:(e.level||`info`).toUpperCase()}),X(`span`,{className:`log-body`,children:[X(`span`,{className:`log-msg`,children:e.message||e.msg||``}),Object.entries(t).map(([e,t])=>X(`span`,{className:`log-field`,children:[X(`span`,{className:`log-field-key`,children:e}),String(On(t))]},e))]})]})}var jn=[{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 Mn(e){return`${e.time||``}|${e.level||``}|${e.message||e.msg||``}|${JSON.stringify(e.fields||{})}`}function Nn(){let[e,t]=q({level:``,component:``,q:``}),[n,r]=q(!1),[i,a]=q([]),[o,s]=q([]),c=Y(new Map),[l,u]=q(0),[d,f]=q(!1),[p,m]=q(`connecting`),[h,g]=q(`Refreshing…`),_=Y(null),v=Y(null),y=async()=>{g(`Refreshing…`);try{let t=await z.logs({level:e.level,component:e.component,q:e.q,limit:500});a(e=>{let n=t.components||[];return e.length===n.length&&e.every((e,t)=>e===n[t])?e:n}),f(!!t.disabled);let n=t.disabled?`Durable history unavailable; live daemon logs continue.`:t.truncated?`showing the most recent matches from ${t.file}`:t.file||``;g(n),s(t.entries||[])}catch{g(`Cannot read logs`)}};J(()=>{y()},[e]),J(()=>{let e=me(e=>{if(b.current)return;let t=e;S.current(t)&&(c.current.set(Mn(t),t),t.fields?.component&&a(e=>e.includes(t.fields.component)?e:[...e,t.fields.component]),u(e=>e+1))},e=>{m(e)});return()=>e()},[]);let b=Y(n);b.current=n;let x=t=>{if(e.level&&!e.level.split(`,`).includes((t.level||``).toUpperCase())||e.component&&t.fields?.component!==e.component)return!1;if(e.q){let n=e.q.toLowerCase();if(!`${t.message||t.msg||``} ${JSON.stringify(t.fields||{})}`.toLowerCase().includes(n))return!1}return!0},S=Y(x);S.current=x;let C=Ue(()=>{let e=new Map;for(let t of o)e.set(Mn(t),t);for(let[t,n]of c.current)e.set(t,n);return[...e.values()].filter(x).slice(-1e3)},[o,l,e]);return J(()=>{_.current&&(_.current.scrollTop=_.current.scrollHeight)},[C]),X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Logs`}),X(`p`,{className:`page-sub`,children:`What Archie has been doing, newest last.`})]}),X(`div`,{className:`page-actions`,children:[X(`button`,{className:`btn ${n?`btn-primary`:``}`,onClick:()=>r(!n),children:n?`Resume`:`Pause`}),X(`button`,{className:`btn`,onClick:y,children:`Refresh`})]})]}),X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:[X(`div`,{className:`log-filters`,children:[X(`select`,{className:`log-select`,value:e.level,onChange:e=>t(t=>({...t,level:e.target.value})),children:jn.map(e=>X(`option`,{value:e.value,children:e.label},e.value))}),X(`select`,{className:`log-select`,value:e.component,onChange:e=>t(t=>({...t,component:e.target.value})),children:[X(`option`,{value:``,children:`All components`}),i.map(e=>X(`option`,{value:e,children:e},e))]}),X(`input`,{className:`log-search`,type:`search`,placeholder:`Search messages and fields…`,onInput:e=>{let n=e.target.value;v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{t(e=>({...e,q:n}))},250)}})]}),X(`div`,{className:`log-status`,children:[X(`span`,{className:`log-meta`,children:h}),X(Z,{text:p,kind:p===`live`?`ok`:`warn`})]})]}),X(`div`,{className:`log-list`,ref:_,children:h===`Cannot read logs`?X(En,{title:`Cannot read logs`}):C.length?C.map(e=>X(An,{entry:e},Mn(e))):X(En,{title:d?`Durable history unavailable`:`Nothing matches`,detail:d?`Live daemon logs will appear here while this page is open.`:`Try a wider level or clear the search.`})})]})]})}function Pn(e){return X(Nn,{query:e})}function Fn({capture:e,expanded:t,onToggle:n}){return X(S,{children:[X(`tr`,{className:`capture-row`,tabIndex:`0`,"aria-expanded":String(t),onClick:n,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),n(e))},children:[X(`td`,{className:`mono`,children:e.source||`(unknown)`}),X(`td`,{title:e.received_at||``,children:U(e.received_at)}),X(`td`,{children:X(Z,{text:`Unbound`,kind:`idle`})}),X(`td`,{className:`mono`,children:e.content_type||`—`}),X(`td`,{children:X(`button`,{className:`btn btn-small`,type:`button`,children:t?`Hide`:`View`})})]}),t&&X(In,{capture:e})]})}function In({capture:e}){return X(`tr`,{className:`capture-detail-row`,children:X(`td`,{colSpan:`5`,children:X(`div`,{className:`capture-detail`,children:[X(`div`,{className:`capture-detail-section`,children:[X(`div`,{className:`capture-detail-title`,children:`Payload`}),X(Ln,{raw:e.body})]}),X(`div`,{className:`capture-detail-section`,children:[X(`div`,{className:`capture-detail-title`,children:`Headers`}),X(Ln,{raw:e.headers})]})]})})})}function Ln({raw:e}){return e?X(`pre`,{className:`capture-payload`,children:Rn(e)}):X(`div`,{className:`capture-empty`,children:`(empty)`})}function Rn(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function zn({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Bn(e){return X(Vn,{query:e})}function Vn({query:e}){let[t,n]=q([]),[r,i]=q(null),[a,o]=q(null),[s,c]=q(!0),[l,u]=q({text:`connecting`,kind:`idle`}),d=async()=>{try{let e=await z.captures(100);c(e.enabled!==!1),n(e.captures||[]),o(null)}catch(e){o(String(e.message||e))}};return J(()=>{d();let e=B(e=>{e.kind===`capture`&&d()},e=>{u({text:e,kind:e===`live`?`ok`:`warn`})});return()=>e()},[]),X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Event inspector`}),X(`p`,{className:`page-sub`,children:`Real inbound payloads archie has captured, most recent first.`})]}),X(`div`,{className:`page-actions`,children:[X(Z,{text:l.text,kind:l.kind}),X(`button`,{className:`btn`,onClick:d,children:`Refresh`})]})]}),X(`div`,{className:`card`,children:a?X(zn,{title:`Cannot reach archied`,detail:a}):s?t.length?X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[`Source`,`Received`,`Binding`,`Content type`,``].map((e,t)=>X(`th`,{children:e},t))})}),X(`tbody`,{children:t.map(e=>X(Fn,{capture:e,expanded:r===e.id,onToggle:()=>i(r===e.id?null:e.id)},e.id))})]})}):X(zn,{title:`No captures yet`,detail:`Point a webhook at /webhooks/capture/ and it will show up here.`}):X(zn,{title:`Capture is not configured`,detail:`This deployment has no capture storage wired up.`})})]})}var Hn=[`string`,`number`,`bool`,`object`,`array`,`any`];function Un(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 Wn(e,t){return e?`${e}.${t}`:t}function Gn(e,t){return`${e}[${t}]`}function Kn({value:e,path:t=``,name:n=``,onPick:r}){return typeof e==`object`&&e?X(`ul`,{className:`mapping-tree-list`,children:(Array.isArray(e)?e.map((e,n)=>[String(n),e,Gn(t,n)]):Object.entries(e).map(([e,n])=>[e,n,Wn(t,e)])).map(([e,t,n])=>X(`li`,{className:`mapping-tree-item`,children:[X(`span`,{className:`mapping-tree-key`,onClick:i=>{i.stopPropagation(),r&&r({path:n,type:Un(t),name:e})},children:e}),X(Kn,{value:t,path:n,name:e,onPick:r})]},n))}):X(`span`,{className:`mapping-tree-value`,onClick:i=>{i.stopPropagation(),r&&r({path:t,type:Un(e),name:n})},children:JSON.stringify(e)})}function qn({fields:e,preview:t,onRemove:n,onNameChange:r,onTypeChange:i,onRequiredChange:a}){if(!e.length)return X(`div`,{className:`mapping-empty-fields`,children:`Click a value in the payload to bind a field.`});let o=new Map((t?.failures||[]).map(e=>[e.field_name,e]));return X(`table`,{className:`table mapping-fields-table`,children:[X(`thead`,{children:X(`tr`,{children:[`Field name`,`Path`,`Type`,`Required`,`Preview`,``].map((e,t)=>X(`th`,{children:e},t))})}),X(`tbody`,{children:e.map((e,s)=>X(`tr`,{children:[X(`td`,{children:X(`input`,{className:`mapping-input`,value:e.name,onInput:e=>r?.(s,e.target.value)})}),X(`td`,{className:`mono`,children:e.path}),X(`td`,{children:X(`select`,{className:`mapping-select`,value:e.type,onChange:e=>i?.(s,e.target.value),children:Hn.map(e=>X(`option`,{value:e,children:e},e))})}),X(`td`,{children:X(`input`,{type:`checkbox`,checked:e.required,onChange:e=>a?.(s,e.target.checked)})}),X(`td`,{children:X(Jn,{field:e,preview:t,failureByField:o})}),X(`td`,{children:X(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>n?.(s),children:`Remove`})})]},s))})]})}function Jn({field:e,preview:t,failureByField:n}){if(!t)return X(Z,{text:`not previewed`,kind:`idle`});let r=n.get(e.name);return r?X(Z,{text:r.reason,kind:`danger`}):Object.prototype.hasOwnProperty.call(t.values||{},e.name)?X(Z,{text:JSON.stringify(t.values[e.name]),kind:`ok`}):X(Z,{text:`skipped (optional)`,kind:`idle`})}function Yn({mapping:e,onEdit:t,onDelete:n}){return X(`tr`,{children:[X(`td`,{children:e.name}),X(`td`,{className:`mono`,children:e.source_hint||`—`}),X(`td`,{children:String(e.fields?.length??0)}),X(`td`,{children:[X(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>t?.(e),children:`Edit`}),X(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>n?.(e),children:`Delete`})]})]})}function Xn({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Zn(e){return X(Qn,{query:e})}function Qn({query:e}){let[t,n]=q([]),[r,i]=q([]),[a,o]=q(null),[s,c]=q(null),l=async()=>{try{let[e,t]=await Promise.all([z.mappings(),z.captures(100)]);n(e.mappings||[]),i(t.captures||[]),o(null)}catch(e){o(String(e.message||e))}};J(()=>{l()},[]);let u=()=>{c({id:null,name:``,sourceHint:``,fields:[],captureId:null,payload:null,payloadError:null,preview:null,actionError:null})},d=e=>{c({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})},f=async e=>{if(window.confirm(`Delete mapping "${e.name}"?`))try{await z.mappingDelete(e.id),await l()}catch(e){o(String(e.message||e))}},p=e=>{let t=r.find(t=>String(t.id)===String(e));c(e=>{let n={...e,captureId:t?t.id:null,preview:null};if(!t)n.payload=null,n.payloadError=null;else try{n.payload=JSON.parse(t.body),n.payloadError=null}catch{n.payload=null,n.payloadError=`This capture's body is not valid JSON, so its fields cannot be mapped by path.`}return n})},m=({path:e,type:t,name:n})=>{c(r=>{let i=new Set(r.fields.map(e=>e.name)),a=n||`field`,o=1;for(;i.has(a);)a=`${n||`field`}_${++o}`;let s=[...r.fields,{name:a,path:e,type:t,required:!0}];return{...r,fields:s,preview:null}})},h=e=>{c(t=>{let n=t.fields.slice();return n.splice(e,1),{...t,fields:n,preview:null}})},g=(e,t)=>{c(n=>{let r=n.fields.slice();return r[e]={...r[e],...t},{...n,fields:r,preview:null}})};return s?X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:X(`h1`,{className:`page-title`,children:s.id?`Edit mapping`:`New mapping`})}),X(`div`,{className:`page-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:()=>{c(null)},children:`Cancel`}),X(`button`,{className:`btn btn-primary`,type:`button`,onClick:async()=>{let e={name:s.name,source_hint:s.sourceHint,fields:s.fields};try{s.id?await z.mappingUpdate(s.id,e):await z.mappingCreate(e),c(null),await l()}catch(e){c(t=>({...t,actionError:String(e.message||e)}))}},children:`Save`})]})]}),s.actionError&&X(`div`,{className:`mapping-error`,children:s.actionError}),X(`div`,{className:`card mapping-form`,children:[X(`label`,{className:`mapping-form-row`,children:[`Name`,X(`input`,{className:`mapping-input`,value:s.name,onInput:e=>c(t=>({...t,name:e.target.value}))})]}),X(`label`,{className:`mapping-form-row`,children:[`Source hint (organisational only)`,X(`input`,{className:`mapping-input`,value:s.sourceHint,onInput:e=>c(t=>({...t,sourceHint:e.target.value}))})]}),X(`label`,{className:`mapping-form-row`,children:[`Preview against captured event`,X(`select`,{className:`mapping-select`,value:s.captureId||``,onChange:e=>p(e.target.value),children:[X(`option`,{value:``,children:`— pick a captured event —`}),r.map(e=>X(`option`,{value:e.id,children:[e.source||`(unknown)`,` — `,e.received_at||``]},e.id))]})]})]}),X(`div`,{className:`card mapping-fields`,children:[X(`div`,{className:`mapping-section-title`,children:`Bound fields`}),X(qn,{fields:s.fields,preview:s.preview,onRemove:h,onNameChange:(e,t)=>g(e,{name:t}),onTypeChange:(e,t)=>g(e,{type:t}),onRequiredChange:(e,t)=>g(e,{required:t})}),X(`button`,{className:`btn`,type:`button`,onClick:async()=>{if(!s.captureId){c(e=>({...e,actionError:`Pick a captured event to preview against.`}));return}try{let e=await z.mappingPreview(s.captureId,s.fields);c(t=>({...t,preview:e,actionError:null}))}catch(e){c(t=>({...t,actionError:String(e.message||e)}))}},children:`Preview`})]}),X(`div`,{className:`card mapping-payload`,children:[X(`div`,{className:`mapping-section-title`,children:`Payload — click a value to bind it`}),s.payloadError?X(`div`,{className:`mapping-error`,children:s.payloadError}):s.payload===null?X(`div`,{className:`mapping-empty-fields`,children:`Pick a captured event above to see its payload.`}):X(Kn,{value:s.payload,onPick:m})]})]}):X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Field mappings`}),X(`p`,{className:`page-sub`,children:`Bind named fields to JSON paths from a real captured event, ready for a playbook binding.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn btn-primary`,type:`button`,onClick:u,children:`New mapping`})})]}),a?X(Xn,{title:`Cannot reach archied`,detail:a}):t.length?X(`div`,{className:`card`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[`Name`,`Source hint`,`Fields`,``].map((e,t)=>X(`th`,{children:e},t))})}),X(`tbody`,{children:t.map(e=>X(Yn,{mapping:e,onEdit:()=>d(e),onDelete:()=>f(e)},e.id))})]})})}):X(Xn,{title:`No mappings yet`,detail:`Create one from a captured event to reuse fields in a future playbook binding.`})]})}var $n={draft:`draft`,pending_approval:`pending approval`,armed:`armed`},er={draft:`idle`,pending_approval:`warn`,armed:`ok`};function tr({status:e}){return X(Z,{text:$n[e]||e,kind:er[e]||`idle`})}function nr({binding:e,onEdit:t,onApprove:n,onDelete:r}){let i=e.owner&&e.repo?`${e.owner}/${e.repo}`:`—`;return X(`tr`,{children:[X(`td`,{children:e.name}),X(`td`,{className:`mono`,children:e.matcher?.source||`—`}),X(`td`,{children:e.workflow}),X(`td`,{className:`mono`,children:i}),X(`td`,{children:X(tr,{status:e.status})}),X(`td`,{children:[X(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>t?.(e),children:`Edit`}),e.status===`pending_approval`&&X(`button`,{className:`btn btn-small btn-primary`,type:`button`,onClick:()=>n?.(e),children:`Approve`}),X(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>r?.(e),children:`Delete`})]})]})}function rr({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function ir(e){return X(or,{query:e})}function ar(){return{id:null,name:``,source:``,mappingId:``,workflow:``,owner:``,repo:``,secret:``,actionError:null}}function or({query:e}){let[t,n]=q([]),[r,i]=q([]),[a,o]=q([]),[s,c]=q(null),[l,u]=q(null),d=async()=>{try{let[e,t,r]=await Promise.all([z.bindings(),z.mappings(),z.workflows()]);n(e.bindings||[]),i(t.mappings||[]),o((r.definitions||[]).filter(e=>e.enabled)),c(null)}catch(e){c(String(e.message||e))}};J(()=>{d()},[]);let f=()=>{u(ar())},p=e=>{u({id:e.id,name:e.name,source:e.matcher?.source||``,mappingId:e.mapping_id?String(e.mapping_id):``,workflow:e.workflow||``,owner:e.owner||``,repo:e.repo||``,secret:``,actionError:null})},m=()=>u(null),h=async()=>{let e={name:l.name,matcher:{source:l.source},mapping_id:Number(l.mappingId)||0,workflow:l.workflow,owner:l.owner,repo:l.repo,secret:l.secret};try{l.id?await z.bindingUpdate(l.id,e):await z.bindingCreate(e),u(null),await d()}catch(e){u(t=>({...t,actionError:String(e.message||e)}))}},g=async e=>{try{await z.bindingApprove(e.id),await d()}catch(e){c(String(e.message||e))}},_=async e=>{if(window.confirm(`Delete binding "${e.name}"?`))try{await z.bindingDelete(e.id),await d()}catch(e){c(String(e.message||e))}};return l?X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:X(`h1`,{className:`page-title`,children:l.id?`Edit binding`:`New binding`})}),X(`div`,{className:`page-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:m,children:`Cancel`}),X(`button`,{className:`btn btn-primary`,type:`button`,onClick:h,children:`Save`})]})]}),l.actionError&&X(`div`,{className:`binding-error`,children:l.actionError}),X(`div`,{className:`card binding-form`,children:[X(`label`,{className:`binding-form-row`,children:[`Name`,X(`input`,{className:`binding-input`,value:l.name,onInput:e=>u(t=>({...t,name:e.target.value}))})]}),X(`label`,{className:`binding-form-row`,children:[`Source (the path segment senders POST to, e.g. "sentry")`,X(`input`,{className:`binding-input`,value:l.source,onInput:e=>u(t=>({...t,source:e.target.value}))})]}),X(`label`,{className:`binding-form-row`,children:[`Field mapping`,X(`select`,{className:`binding-select`,value:l.mappingId,onChange:e=>u(t=>({...t,mappingId:e.target.value})),children:[X(`option`,{value:``,children:`— pick a saved mapping —`}),r.map(e=>X(`option`,{value:e.id,children:e.name},e.id))]})]}),X(`label`,{className:`binding-form-row`,children:[`Workflow`,X(`select`,{className:`binding-select`,value:l.workflow,onChange:e=>u(t=>({...t,workflow:e.target.value})),children:[X(`option`,{value:``,children:`— pick a workflow —`}),a.map(e=>X(`option`,{value:e.id,children:e.name},e.id))]})]}),X(`label`,{className:`binding-form-row`,children:[`Repo pin -- owner (optional; leave both blank for the single-configured-repo default)`,X(`input`,{className:`binding-input`,value:l.owner,onInput:e=>u(t=>({...t,owner:e.target.value}))})]}),X(`label`,{className:`binding-form-row`,children:[`Repo pin -- repo`,X(`input`,{className:`binding-input`,value:l.repo,onInput:e=>u(t=>({...t,repo:e.target.value}))})]}),X(`label`,{className:`binding-form-row`,children:[`Shared secret (`,l.id?`leave blank to keep the current secret`:`senders sign with this via HMAC-SHA256`,`)`,X(`input`,{className:`binding-input`,type:`password`,value:l.secret,onInput:e=>u(t=>({...t,secret:e.target.value}))})]})]})]}):X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Playbook bindings`}),X(`p`,{className:`page-sub`,children:`Tie a matcher, a field mapping, and a workflow together. New and edited bindings need explicit approval before they can fire.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn btn-primary`,type:`button`,onClick:f,children:`New binding`})})]}),s?X(rr,{title:`Cannot reach archied`,detail:s}):t.length?X(`div`,{className:`card`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[`Name`,`Source`,`Workflow`,`Repo pin`,`Status`,``].map((e,t)=>X(`th`,{children:e},t))})}),X(`tbody`,{children:t.map(e=>X(nr,{binding:e,onEdit:()=>p(e),onApprove:()=>g(e),onDelete:()=>_(e)},e.id))})]})})}):X(rr,{title:`No bindings yet`,detail:`Create one from a saved field mapping to turn a captured webhook into a workflow.`})]})}function sr({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function cr(e){return e===`external`?`Added by you — an external store Archie was given`:`Built in — always available to Archie`}function lr({provider:e}){let t=e.tools||[];return X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:[X(`div`,{children:[X(`h2`,{className:`card-title`,children:e.name||`provider`}),X(`p`,{className:`card-sub`,children:cr(e.role)})]}),e.available?X(Z,{text:`ready`,kind:`ok`}):X(Z,{text:`unavailable`,kind:`danger`})]}),!e.available&&X(`p`,{className:`mem-warning`,children:`Configured but not usable right now — a required binary or connection may be missing.`}),t.length?X(`ul`,{className:`mem-tools`,children:t.map((e,t)=>X(`li`,{className:`mem-tool`,children:[X(`div`,{className:`mem-tool-name mono`,children:e.name}),e.description&&X(`div`,{className:`mem-tool-desc`,children:e.description})]},t))}):X(`p`,{className:`mem-warning`,children:`This provider exposes no tools, so the agent cannot use it.`})]})}function ur(){let[e,t]=q(null),[n,r]=q(!0),[i,a]=q(null),[o,s]=q(!0),c=async()=>{s(!0),a(null);try{let e=await z.memory();r(!!e.enabled),t(e.providers||[])}catch(e){a(String(e.message||e))}finally{s(!1)}};return J(()=>{c()},[]),X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Memory`}),X(`p`,{className:`page-sub`,children:`What Archie can recall between conversations, and the tools it uses to do it.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn`,onClick:c,children:`Refresh`})})]}),X(`div`,{children:o?X(`div`,{className:`card`,children:X(`div`,{className:`mem-loading`,children:`Loading…`})}):i?X(`div`,{className:`card`,children:X(sr,{title:`Cannot read memory providers`,detail:i})}):!n||!e.length?X(`div`,{className:`card`,children:X(sr,{title:`Memory is not configured`,detail:`Without a provider, Archie starts every conversation with no recollection of earlier ones.`})}):X(`div`,{className:`grid grid-2`,children:e.map((e,t)=>X(lr,{provider:e},t))})})]})}function dr(e){return X(ur,{query:e})}function fr(e){let t=document.createDocumentFragment(),n=/(!\[[^\]]*\]\((?:https?:\/\/[^\s)]+|data:image\/[^\s)]+|\/[^\s)]+)\)|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\((?:https?:\/\/[^\s)]+|\/[^\s)]+)\)|\*[^*]+\*|_[^_]+_)/g,r=0;for(let i of e.matchAll(n)){i.index>r&&t.append(document.createTextNode(e.slice(r,i.index)));let n=i[0];if(n.startsWith(`![`)){let e=n.match(/^!\[([^\]]*)\]\((.+)\)$/);e&&t.append(H(`img.chat-media-img`,{src:e[2],alt:e[1]||`Image`,loading:`lazy`}))}else if(n.startsWith(`~~`))t.append(H(`del`,n.slice(2,-2)));else if(n.startsWith(`**`)||n.startsWith(`__`))t.append(H(`strong`,n.slice(2,-2)));else if(n.startsWith("`"))t.append(H(`code`,n.slice(1,-1)));else if(n.startsWith(`[`)){let e=n.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+|\/[^\s)]+)\)$/);t.append(H(`a`,{href:e[2],target:`_blank`,rel:`noreferrer`},e[1]))}else t.append(H(`em`,n.slice(1,-1)));r=i.index+n.length}return r{r.length&&(t.append(H(`p`,fr(r.join(` `)))),r=[])},s=()=>{i&&t.append(i),i=null};for(let e=0;eH(`td`,fr(e)))));t.append(H(`table`,H(`thead`,H(`tr`,...l.map(e=>H(`th`,fr(e))))),i));continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.append(H(`h${d[1].length}`,fr(d[2])));continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tagName.toLowerCase()!==e)&&(s(),i=H(e)),i.append(H(`li`,fr((f||p)[1])));continue}if(c.startsWith(`>`)){o(),s(),t.append(H(`blockquote`,fr(c.replace(/^>\s?/,``))));continue}r.push(c)}return o(),s(),a&&t.append(H(`pre`,H(`code`,a.join(` -`)))),t}function mr(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 hr(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var gr=`archie.web.chat.channel`;function _r(){let e=localStorage.getItem(gr);return e||(e=se(),localStorage.setItem(gr,e)),e}function vr(e){return{text:e,sourceID:se()}}function yr(e){return{...e}}function br(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?yr(e.turn):vr(r),isRetry:n}}function xr(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function Sr(e){return e?.status===501?null:`Could not check for updates.`}function Cr(){return location.hash.slice(1)||`/`}function wr({text:e}){let t=Y(null);return J(()=>{t.current&&t.current.replaceChildren(pr(e||``))},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function Tr(){let[e,t]=q([]),[n,r]=q(``),[i,a]=q([]),[o,s]=q(``),[c,l]=q(`Ready`),[u,d]=q(!1),[f,p]=q({}),[m,h]=q(``),[g,_]=q(``),[v,y]=q(``),[b,x]=q([]),[C,w]=q([]),[T,E]=q(0),[D,O]=q(!1),[k,A]=q(null),[j,ee]=q(null),[M,N]=q(null),[P,te]=q(``),[ne,re]=q(``),[F,I]=q(null),ie=Y(null),L=Y(null),ae=Y(null),oe=Y(null),se=Y(null),ce=Y(u);ce.current=u,J(()=>{ie.current&&(ie.current.scrollTop=ie.current.scrollHeight)},[i,F]),J(()=>{B().catch(e=>{l(e.message||`Chat unavailable`)}),le();let e=()=>{ae.current?.abort()};return window.addEventListener(`archie:teardown`,e),()=>{window.removeEventListener(`archie:teardown`,e),ae.current?.abort()}},[]);async function le(){try{let e=await z.chatUpdate();ee(e?.snapshot||null),A(e)}catch(e){let t=Sr(e);A(t?{error:t}:null)}}async function ue(){if(j)try{await z.chatUpdateDefer(j),A({snapshot:{deferred:!0},available:[]}),l(`Update deferred`)}catch(e){l(e.message||`Could not defer update`)}}async function de(){if(j)try{l(`Installing…`);let e=await z.chatUpdateInstall(j);ee(null),A({snapshot:{},available:[]}),l(e?.result?.restart_requested?`Update installed; restart queued`:`Update complete`)}catch(e){l(e.message||`Update install failed`)}}async function fe(){try{let e=await z.chatDangerous();N(e)}catch(e){N({error:e.message||`Dangerous actions unavailable`})}}async function pe(e,t){if(t)try{await z.chatDangerousRequest(e,t),l(`Approval requested`),await fe()}catch(e){l(e.message||`Could not request action`)}}async function R(e,t){try{await z.chatDangerousDecision(e,t),l(t===`deny`?`Action denied`:`Action approved`),await fe()}catch(e){l(e.message||`Approval failed`)}}async function B(){let e=await z.chatSessions(),r=e.sessions||[];t(r),p(e),h(e.active_persona||``);let i=e.providers||[],a=e.active_provider||i[0]||``;_(a),y(e.active_model||``);let o=(e.commands||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e);x(o),e.dangerous_available&&await fe(),!n&&r[0]&&await me(r[0].session_id,e,r)}async function me(e,t,n){let i=t||f;r(e),a([]),I(null);let o=i.active_personas?.[e]||i.active_persona||``;h(o);try{await z.chatMessage(_r(),`/resume ${e}`);let[t,n]=await Promise.all([z.chatMessages(e),z.chatTurns(e)]),r=new Map;for(let e of n||[]){let t=e.assistant_message_id||e.AssistantMessageID;t&&r.set(t,e)}let i=(t||[]).map(e=>{let t=e.message_id||e.MessageID,n=r.get(t);return n?{...e,tool_calls:n.tool_calls||n.ToolCalls||[]}:e});a(i)}catch(e){l(e.message||`Could not load session messages`)}}async function he(e){if(n)try{l(`Working…`);let t=await z.chatMessage(_r(),e);t.session_id&&r(t.session_id),l(t.reply||`Session updated`),await B(),(t.session_id||n)&&await me(t.session_id||n),oe.current&&(oe.current.open=!1)}catch(e){l(e.message||`Session action failed`)}}function ge(e,t){let n=window.prompt(t);n?.trim()&&he(`${e} ${n.trim()}`)}function _e(e){let t=e.target.value;h(t),!(!n||!t)&&z.chatPersona(n,t).then(()=>{p(e=>({...e,active_personas:{...e.active_personas||{},[n]:t}})),l(`Personality: ${t}`)}).catch(e=>{l(e.message||`Failed to set personality`)})}async function ve(e){let t=e.target.value;if(_(t),t)try{let e=await z.chatMessage(_r(),`/model --provider ${t}`);l(e.reply||`Provider updated`),await B()}catch(e){l(`Provider update failed: ${e.message||e}`)}}async function ye(e){let t=e.target.value;if(y(t),t)try{let e=await z.chatMessage(_r(),`/model ${t}`);l(e.reply||`Model updated`),await B()}catch(e){l(`Model update failed: ${e.message||e}`)}}function be(){window.confirm(`Reload the Telegram chat adapter?`)&&(s(`/restart`),V({textOverride:`/restart`}))}function xe(){s(`/new`),V({textOverride:`/new`})}function Se(e){let t=e.target.value;s(t);let n=t.slice(0,e.target.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);if(n){let e=n[1].toLowerCase(),t=b.filter(t=>`${t.command} ${t.description}`.toLowerCase().includes(e)).slice(0,8);if(t.length){w(t),E(0),O(!0);return}}O(!1),w([])}function Ce(e){let t=C[e];if(!t||!L.current)return;let n=L.current,r=n.value.slice(0,n.selectionStart),i=n.value.slice(n.selectionStart),a=r.search(/(?:^|\s)\/[^\s]*$/),o=a<0?r.length:a+ +(r[a]===` `),c=`${r.slice(0,o)}${t.command} ${i}`;s(c),O(!1);let l=o+t.command.length+1;setTimeout(()=>{n.focus(),n.setSelectionRange(l,l)},0)}function we(e){if(D&&C.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&C.some(e=>e.command===o.trim())){e.preventDefault(),O(!1),V();return}if(e.key===`ArrowDown`){e.preventDefault(),E(e=>(e+1)%C.length);return}if(e.key===`ArrowUp`){e.preventDefault(),E(e=>(e+C.length-1)%C.length);return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Ce(T);return}if(e.key===`Escape`){e.preventDefault(),O(!1);return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),V())}async function V(e=null){let t=e?.textOverride,{text:n,turn:i,isRetry:c}=br(e,t===void 0?o:t);if(!n||ce.current)return;O(!1),d(!0),l(c?`Retrying…`:`Thinking…`),c||(a(e=>[...e,{from:`web`,text:n}]),s(``));let u=[];I({text:``,tools:[],isError:!1,turn:i,isRetry:c});let f=``,p=!1,m=!1,h=null;try{let e=new AbortController;ae.current=e,h=setTimeout(()=>{m=!0,e.abort()},12e4);let t=(await z.chatStream({channel_id:_r(),source_id:i.sourceID,text:i.text,page:Cr()},{signal:e.signal})).body.getReader(),n=new TextDecoder,o=``;for(;;){let{value:e,done:i}=await t.read();o+=n.decode(e||new Uint8Array,{stream:!i});let a=o.split(` + class="gauge-value"/>`,U(`div.gauge-wrap`,l,U(`div.gauge-center`,U(`div.gauge-pct`,`${Math.round(r)}%`),U(`div.gauge-label`,t)))}function et(e){let t=e.reduce((e,t)=>e+(t.value||0),0)||1;return U(`div`,U(`div.segbar`,...e.filter(e=>e.value>0).map(e=>U(`span`,{class:`segbar-part segbar-${e.kind||`idle`}`,style:`width:${(e.value/t*100).toFixed(1)}%`,title:`${e.label}: ${e.value}`}))),U(`div.segbar-legend`,...e.map(e=>U(`span.segbar-key`,U(`span`,{class:`segbar-dot segbar-${e.kind||`idle`}`}),e.label))))}var tt=0;Array.isArray;function X(e,n,r,i,a,o){n||={};var s,c,l=n;if(`ref`in l)for(c in l={},n)c==`ref`?s=n[c]:l[c]=n[c];var u={type:e,props:l,key:r,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--tt,__i:-1,__u:0,__source:a,__self:o};if(typeof e==`function`&&(s=e.defaultProps))for(c in s)l[c]===void 0&&(l[c]=s[c]);return t.vnode&&t.vnode(u),u}function Z({text:e,kind:t=`idle`}){return X(`span`,{className:`pill pill-${t}`,children:e})}var nt=`archie.setup-complete.dismissed.v1`;function rt(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?.(nt),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function it(e=globalThis.localStorage){e?.setItem?.(nt,`1`)}var at=new Set([`waiting_human`,`parked`]);function ot(e=[]){let t=e.filter(e=>at.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 st({node:e}){let t=Y();return J(()=>{t.current&&e&&t.current.replaceChildren(e)},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function ct(e){return X(st,{node:Ze(e)})}function lt(e){return X(st,{node:$e(e)})}function ut({segments:e}){return X(st,{node:et(e)})}function dt({name:e,opts:t}){return X(st,{node:W(e,t)})}function ft({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function pt(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 mt(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function ht(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 gt(){let[e,t]=q([]),[n,r]=q(`connecting`),[i,a]=q(`idle`),[o,s]=q(new Map),[c,l]=q(null),[u,d]=q(null),[f,p]=q(null),[m,h]=q(null),[g,_]=q(null),[,v]=q(!1),y=async()=>{_(null);try{let[e,t,n,r]=await Promise.all([B.summary(),B.setup().catch(()=>null),B.workflows().catch(()=>null),B.tasks().catch(()=>[])]),i=new Map;for(let e of r)e.owner&&e.repo&&e.issue_number&&i.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);s(i),l(e),d(t),p(n),h(r)}catch(e){_(String(e.message||e))}};J(()=>(y(),V(e=>{t(t=>{let n=[e,...t];return n.splice(50),n})},e=>{r(e),a(e===`live`?`ok`:`warn`)})),[]);let b=()=>{it(),v(e=>!e)},x=u?.operator?`${mt()}, ${u.operator}`:mt(),C=null;if(g)C=X(`button`,{className:`btn btn-primary`,onClick:y,children:[X(dt,{name:`refresh`,opts:{size:15}}),` Retry`]});else if(m!==null){let e=ot(m),t=e.attention.count,n=e.running.count;C=X(S,{children:[t>0&&X(`a`,{className:`btn btn-attention`,href:e.attention.href,children:[X(dt,{name:`tasks`,opts:{size:15}}),` `,t,` need`,t===1?`s`:``,` you`]}),n>0&&X(`a`,{className:`btn`,href:e.running.href,children:[X(dt,{name:`workflows`,opts:{size:15}}),` `,n,` running`]}),X(`a`,{className:`btn`,href:`#/logs`,children:[X(dt,{name:`logs`,opts:{size:15}}),` Logs`]}),X(`button`,{className:`btn btn-primary`,onClick:y,children:[X(dt,{name:`refresh`,opts:{size:15}}),` Refresh`]})]})}let w=null;if(g)w=X(`div`,{className:`card`,children:X(ft,{title:`Cannot reach archied`,detail:g})});else if(c){let e=c?.statuses||{},t=(e.merged||0)+(e.pr_open||0),n=(e.parked||0)+(e.waiting_human||0),r=Object.values(e).reduce((e,t)=>e+t,0),i=c?.tokens_by_day||[];w=X(S,{children:[X(ct,{label:`Working now`,value:e.running||0,compare:`${e.queued||0} waiting to start`,series:i.map(e=>e.tokens||0)}),X(ct,{label:`Needs you`,value:n,compare:n?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),X(ct,{label:`Delivered`,value:t,compare:r?`${Math.round(t/r*100)}% of all tasks`:`No tasks yet`}),X(ct,{label:`Tokens used`,value:Oe(i.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${i.length||0} days`,trend:ht(i.map(e=>e.tokens||0)),goodDirection:`down`,series:i.map(e=>e.tokens||0)})]})}let T=null,E=rt(u),D=E.kind===`omit`||E.kind===`dismissed`;if(!D){let e=E.remaining;if(e.length){let t=Math.round((u.steps.length-e.length)/u.steps.length*100);T=X(`div`,{className:`card setup`,children:[X(`div`,{className:`card-head`,children:[X(`div`,{children:[X(`h2`,{className:`card-title`,children:`Finish setting up`}),X(`p`,{className:`card-sub`,children:`Archie needs these before it can work on its own.`})]}),X(`span`,{className:`setup-pct`,children:[t,`%`]})]}),X(`div`,{className:`setup-bar`,children:X(`div`,{className:`setup-bar-fill`,style:{width:`${t}%`}})}),X(`ul`,{className:`setup-list`,children:u.steps.map((e,t)=>X(`li`,{className:`setup-step ${e.done?`done`:``}`,children:[X(`span`,{className:`setup-check`,children:e.done?X(dt,{name:`check`,opts:{size:12}}):``}),X(`div`,{children:[X(`div`,{className:`setup-step-title`,children:e.title}),e.detail&&X(`div`,{className:`setup-step-detail`,children:e.detail})]})]},t))})]})}else T=X(`div`,{className:`card setup setup-done`,children:X(`div`,{className:`card-head`,children:[X(`div`,{children:[X(`h2`,{className:`card-title`,children:`Setup complete`}),X(`p`,{className:`card-sub`,children:`Archie is configured and ready to work.`})]}),X(`div`,{className:`setup-complete-actions`,children:[X(`span`,{className:`setup-pct`,children:X(dt,{name:`check`,opts:{size:16}})}),X(`button`,{className:`icon-btn setup-dismiss`,type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onClick:b,children:`×`})]})]})})}let O=null;if(c){let e=f?.workflows||[],t=e.reduce((e,t)=>e+(t.runs||0),0),n=e.reduce((e,t)=>e+(t.merged||0)+(t.pr_open||0),0),r=e.reduce((e,t)=>e+(t.parked||0),0);if(!t)O=X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:X(`h2`,{className:`card-title`,children:`Gate pulse`})}),X(ft,{title:`No completed runs yet`,detail:`Once Archie finishes a task, its gate pass rate appears here.`})]});else{let i=n/t*100;O=X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:`Gate pulse`}),X(`p`,{className:`card-sub`,children:`Work that passed its quality gates`})]})}),X(lt,{value:i,label:`pass rate`}),X(`ul`,{className:`pulse-list`,children:[e.slice(0,3).map((e,t)=>X(`li`,{className:`pulse-item`,children:[X(`span`,{className:`pulse-name`,children:e.workflow||`workflow`}),X(Z,{text:`${e.merged||0}/${e.runs||0}`,kind:(e.merged||0)===(e.runs||0)?`ok`:(e.parked||0)>0?`warn`:`info`})]},t)),r>0&&X(`li`,{className:`pulse-item`,children:[X(`span`,{className:`pulse-name`,children:`Parked, awaiting you`}),X(Z,{text:String(r),kind:`warn`})]})]})]})}}let k=null;if(c){let e=c?.tokens_by_day||[],t=e.reduce((e,t)=>e+(t.tokens||0),0);if(!e.length)k=X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:X(`h2`,{className:`card-title`,children:`Token outlook`})}),X(ft,{title:`Nothing spent yet`,detail:`Usage appears here once Archie runs its first task.`})]});else{let n=t/e.length,r=Math.round(n*30),i=e.slice(-7).reduce((e,t)=>e+(t.tokens||0),0);k=X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:`Token outlook`}),X(`p`,{className:`card-sub`,children:`Next 30 days at the current rate`})]})}),X(`div`,{className:`forecast-value`,children:Oe(r)}),X(`div`,{className:`forecast-note`,children:[`Based on `,Oe(Math.round(n)),` per day over `,e.length,` days`]}),X(ut,{segments:[{label:`Last 7 days (${Oe(i)})`,value:i,kind:`info`},{label:`Earlier (${Oe(t-i)})`,value:Math.max(t-i,0),kind:`idle`}]})]})}}return X(S,{children:[X(`div`,{className:`hero`,children:[X(`div`,{children:[X(`h1`,{className:`hero-title`,children:x}),X(`p`,{className:`hero-sub`,children:`Your agent's control room — what it is working on, what needs you, and what it is spending.`})]}),X(`div`,{className:`hero-actions`,children:X(`div`,{className:`hero-actions-inner`,children:C})})]}),X(`div`,{className:`dash-section`,children:[X(`div`,{className:`dash-section-head`,children:X(`h2`,{className:`dash-section-title`,children:`Health`})}),X(`div`,{className:`dash-top ${D?`dash-top-standalone`:``}`,children:[X(`div`,{children:T}),X(`div`,{children:O})]})]}),X(`div`,{className:`dash-section`,children:[X(`div`,{className:`dash-section-head`,children:[X(`h2`,{className:`dash-section-title`,children:`Throughput`}),X(`span`,{className:`dash-section-note`,children:`Across all repositories`})]}),X(`div`,{className:`grid grid-4`,children:w})]}),X(`div`,{className:`dash-section`,children:[X(`div`,{className:`dash-section-head`,children:X(`h2`,{className:`dash-section-title`,children:`Right now`})}),X(`div`,{className:`dash-split`,children:[X(`div`,{children:k}),X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:[X(`div`,{children:[X(`h2`,{className:`card-title`,children:`Live activity`}),X(`p`,{className:`card-sub`,children:`Last 50, newest first`})]}),X(Z,{text:n,kind:i})]}),X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Event`}),X(`th`,{children:`Task`}),X(`th`,{children:`Detail`}),X(`th`,{children:`When`})]})}),X(`tbody`,{children:e.length?e.map((e,t)=>{let n=pt(e,o),r=n>0,i=()=>{r&&(location.hash=`#/tasks?task=${encodeURIComponent(n)}`)};return X(`tr`,{className:r?`activity-row`:``,role:r?`link`:void 0,tabIndex:r?`0`:void 0,title:r?`Open task details`:void 0,onClick:r?i:void 0,onKeyDown:r?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i())}:void 0,children:[X(`td`,{className:`strong`,children:X(`span`,{children:e.kind||e.type||`event`})}),X(`td`,{className:`mono`,children:r?`#${n}`:`—`}),X(`td`,{children:e.detail||e.message||``}),X(`td`,{children:De(e.at||Date.now())})]},t)}):X(`tr`,{children:X(`td`,{colSpan:`4`,children:X(ft,{title:`Waiting for activity`,detail:`Events appear here as Archie works.`})})})})]})})]})]})]})]})}function _t(){return X(gt,{})}function vt(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 yt=H(),bt=new Set([`needs_you`,...Ce()]);function xt(e){let t=e?.get?.(`status`)||``;return bt.has(t)?t:``}function St(e,t){return t?t===`needs_you`?yt.has(e.status):e.status===t:!0}function Ct(e){return String(e||`event`).replaceAll(`_`,` `).replace(/\b\w/g,e=>e.toUpperCase())}function wt(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 Tt(e){let t=Number(e);return!Number.isFinite(t)||t<=0?``:t.toLocaleString(`en-US`)}function Et(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=wt(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=Tt(t.iterations),i=Tt(t.tokens),a=Number(t.cached_tokens)||0,o=Tt((Number(t.prompt_tokens)||0)-a),s=Tt(t.completion_tokens),c=Tt(t.cached_tokens),l=[r&&`${r} iterations`,i&&`${i} tokens`,o&&`${o} fresh prompt`,s&&`${s} completion`,c&&`${c} cached`,t.model].filter(Boolean);return{title:`Agent ${t.status||`finished`}: ${n}`,detail:l.join(` · `)||e.detail||``}}return{title:Ct(e.kind||e.type),detail:e.detail||``}}function Dt(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function Ot(e){let t=e.fields||{};return U(`div.log-row.log-${Dt(e.level)}`,U(`span.log-time.mono`,At(e.time)),U(`span.log-level`,(e.level||`info`).toUpperCase()),U(`span.log-body`,U(`span.log-msg`,e.message||e.msg||``),...Object.entries(t).map(([e,t])=>U(`span.log-field`,U(`span.log-field-key`,e),String(kt(t))))))}function kt(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function At(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function jt({entry:e}){let t=Y(null);return J(()=>{t.current&&t.current.replaceChildren(Ot(e))},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function Mt(e,t){return`/api/tasks/${e}/logs/download`+(t==null?``:`?attempt=${t}`)}function Nt({state:e,onRetry:t,taskId:n}){if(e===void 0)return X(`div`,{className:`task-log-loading`,children:`Loading attempt log…`});if(e===null)return X(`div`,{className:`task-log-error`,children:[X(`div`,{className:`task-timeline-detail`,children:`Could not load this attempt's log.`}),X(`button`,{className:`btn`,onClick:t,children:`Retry`})]});if(e.found===!1&&!e.disabled)return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:`No log recorded for this attempt`}),X(`div`,{children:`This attempt produced no output, or it has not started writing yet.`})]});if(e.disabled)return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:`No persisted log for this attempt`}),X(`div`,{children:`This dashboard cannot read task logs. The service that owns the log files is not reporting a log reader.`})]});let r=e.entries||[],i=n==null?null:Mt(n,e.attempt),a=i?X(`a`,{className:`btn btn-small task-log-download`,href:i,download:!0,children:`Download log`}):null;return r.length?X(S,{children:[X(`div`,{className:`log-list task-log-list`,children:r.map((e,t)=>X(jt,{entry:e},t))}),a]}):X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:`Nothing recorded`}),X(`div`,{children:`This attempt's log file has no entries matching the current filter.`}),a]})}function Pt(e){let t=Y(null);return J(()=>{t.current&&t.current.replaceChildren(Ze(e))},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function Ft({kind:e,message:t}){return e===`session-expired`?X(`span`,{className:`task-action-error task-action-error-session`,children:[`Your session has expired.`,` `,X(`button`,{className:`button btn btn-small`,type:`button`,onClick:()=>window.location.reload(),children:`Reload to sign in`})]}):e===`refused`?X(`span`,{className:`task-action-error task-action-error-refused`,children:[t,` — you can't do that.`]}):X(`span`,{className:`task-action-error task-action-error-broken`,children:[t,` — try again, or check the daemon.`]})}function It({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Lt({query:e}){let[t,n]=q(null),[r,i]=q(null),[a,o]=q(()=>xt(e)),[s,c]=q(``),l=Number(e.get(`task`)),u=Number.isFinite(l)&&l>0?l:null,[d,f]=q(u),[p,m]=q(u!==null),[h,g]=q(new Map),[_,v]=q(new Map),[y,b]=q(new Set),[x,C]=q(new Map),[w,T]=q(new Set),E=async()=>{try{i(null);let e=await B.tasks();n(e),d&&e.some(e=>String(e.id)===String(d))&&(h.has(d)||D(d))}catch(e){i(String(e.message||e)),n(null)}};J(()=>{E()},[]);let D=async e=>{try{let t=await B.task(e);g(n=>new Map(n).set(e,t||[]))}catch{g(t=>new Map(t).set(e,null))}},O=async e=>{v(t=>{let n=new Map(t);return n.delete(e),n});try{let t=await B.taskLogs(e,{limit:500});v(n=>new Map(n).set(e,t))}catch{v(t=>new Map(t).set(e,null))}},k=async(e,t)=>{C(t=>{let n=new Map(t);return n.delete(e),n}),T(t=>new Set(t).add(e));try{await B.taskAction(e,t),T(t=>{let n=new Set(t);return n.delete(e),n}),t===`archive`&&f(null),await E()}catch(t){T(t=>{let n=new Set(t);return n.delete(e),n}),C(n=>new Map(n).set(e,de(t)))}};J(()=>{p&&d&&t&&(m(!1),requestAnimationFrame(()=>{let e=document.getElementById(`task-row-${d}`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView({block:`center`,behavior:`smooth`}))}))},[p,d,t]);let A=(e,t)=>{t&&t.stopPropagation();let n=d!==e;f(n?e:null),n&&D(e)},j=e=>{b(t=>{let n=new Set(t);return n.has(e)?n.delete(e):(n.add(e),_.has(e)||O(e)),n})},ee=()=>{if(!t)return null;let e=t.length,n={};for(let e of t)n[e.status]=(n[e.status]||0)+1;let r=n.running||0,i=(n.waiting_human||0)+(n.parked||0),a=(n.merged||0)+(n.pr_open||0);return X(`div`,{className:`grid grid-4 task-summary`,children:[X(Pt,{label:`Total tasks`,value:e,compare:e?`Everything archied has ever picked up`:`No tasks yet`}),X(Pt,{label:`Working now`,value:r,compare:e?`${r} of ${e} in progress`:`Nothing running`}),X(Pt,{label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),X(Pt,{label:`Delivered`,value:a,compare:e?`${Math.round(a/e*100)}% of all tasks`:`No tasks yet`})]})},M=e=>{let t=x.get(e.id),n=t?Ft(t):null,r=w.has(e.id),i=e=>e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``,a=(e.actions||[]).map(t=>{let n=we(t);if(!n)return null;let a=e.title||`this task`,o=n.confirm?n.confirm.replaceAll(`{title}`,a):void 0,s=[`button`,`btn`,`btn-small`,i(n.kind)].filter(Boolean).join(` `);if(n.kind===`link`){if(t===`open_pr`)return N(e,`pull_request`,e.pr_number,n.label);if(t===`open_issue`)return N(e,`issue`,e.issue_number,n.label)}return X(`button`,{className:s,type:`button`,disabled:r,onClick:n=>{n.stopPropagation(),!(o&&!window.confirm(o))&&k(e.id,t)},children:n.label},t)}).filter(Boolean);return!a.length&&!n?`—`:X(`div`,{className:`task-actions`,children:[n,a]})},N=(e,t,n,r)=>{let i=t===`issue`?e.issue_url:e.pr_url;return!i||!n||t===`issue`&&e.source===`chat`?X(`button`,{className:`btn btn-small`,type:`button`,disabled:!0,title:`${r} is unavailable`,children:r}):X(`a`,{className:`btn btn-small`,href:i,target:`_blank`,rel:`noreferrer`,onClick:e=>e.stopPropagation(),children:r})},P=e=>{let t=e.repo_url;return t?X(`a`,{className:`task-source-link`,href:t,target:`_blank`,rel:`noreferrer`,title:`Open ${e.owner}/${e.repo} on the forge`,onClick:e=>e.stopPropagation(),children:[e.owner,`/`,e.repo]}):null},te=e=>{let t=e.issue_url;return e.source===`chat`||!t||!e.issue_number?null:X(`a`,{className:`task-source-link`,href:t,target:`_blank`,rel:`noreferrer`,title:`Open issue #${e.issue_number} on the forge`,onClick:e=>e.stopPropagation(),children:[`#`,e.issue_number]})},ne=e=>{let t=h.get(e.id),n=y.has(e.id);return X(`tr`,{className:`task-timeline-row`,id:`task-timeline-${e.id}`,children:X(`td`,{colSpan:8,children:[X(`div`,{className:`task-detail-actions`,children:[X(`div`,{className:`task-decision-title`,children:`Available actions`}),M(e)]}),e.status===`waiting_human`&&e.plan&&X(`div`,{className:`task-decision`,children:[X(`div`,{className:`task-decision-title`,children:`Decision required`}),X(`div`,{className:`task-decision-plan`,children:e.plan})]}),e.status===`parked`&&e.park_reason&&X(`div`,{className:`task-decision`,children:[X(`div`,{className:`task-decision-title`,children:`Park reason`}),X(`div`,{className:`task-decision-plan`,children:e.park_reason})]}),t===void 0?X(`div`,{className:`task-timeline-loading`,children:`Loading timeline…`}):t===null?X(`div`,{className:`task-timeline-error`,children:[X(`div`,{className:`task-timeline-title`,children:`Could not load timeline`}),X(`div`,{className:`task-timeline-detail`,children:`archied did not answer for this task's events. It may be restarting — retry, or check the daemon.`}),X(`button`,{className:`btn`,onClick:()=>D(e.id),children:`Retry`})]}):t.length?X(`ul`,{className:`task-timeline`,children:t.map((e,t)=>{let n=Et(e);return X(`li`,{className:`task-timeline-entry`,children:[X(`span`,{className:`task-timeline-dot`}),X(`div`,{children:[X(`div`,{className:`task-timeline-kind`,children:n.title}),n.detail&&X(`div`,{className:`task-timeline-detail`,children:n.detail}),X(`div`,{className:`task-timeline-when`,children:De(e.at)})]})]},t)})}):X(It,{title:`No events yet`,detail:`This task has not recorded any transitions.`}),X(`div`,{className:`task-logs-section`,children:[X(`div`,{className:`task-decision-title`,children:[`Attempt log`,X(`button`,{className:`btn btn-small`,onClick:()=>j(e.id),style:{marginLeft:`10px`},children:n?`Hide`:`Show`})]}),n&&X(Nt,{state:_.get(e.id),taskId:e.id,onRetry:()=>O(e.id)})]})]})})};return X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Tasks`}),X(`p`,{className:`page-sub`,children:`Every issue archied has picked up, and where it stands.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn`,onClick:E,children:`Refresh`})})]}),r?X(`div`,{className:`grid grid-4 task-summary`,children:X(`div`,{className:`card`,children:X(It,{title:`Cannot reach archied`,detail:r})})}):ee(),X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:[X(`div`,{children:[X(`h2`,{className:`card-title`,children:`All tasks`}),X(`p`,{className:`card-sub`,children:`Click a row for its timeline`})]}),X(`div`,{className:`task-filters`,children:[X(`input`,{className:`task-search`,type:`search`,placeholder:`Search by title or repo…`,value:s,onInput:e=>c(e.target.value.trim().toLowerCase())}),X(`select`,{className:`task-filter`,value:a,onChange:e=>o(e.target.value),children:[X(`option`,{value:``,children:`All statuses`}),X(`option`,{value:`needs_you`,children:`Needs you`}),Ce().map(e=>X(`option`,{value:e,children:xe(e)},e))]})]})]}),X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[`Repo`,`Issue`,`Title`,`Status`,`Workflow`,`Stage`,`Last activity`,`Action`].map(e=>X(`th`,{children:e},e))})}),X(`tbody`,{children:(()=>{if(r)return X(`tr`,{children:X(`td`,{colSpan:8,children:X(It,{title:`Cannot reach archied`,detail:r})})});if(!t)return X(`tr`,{children:X(`td`,{colSpan:8,children:X(`div`,{className:`task-timeline-loading`,children:`Loading tasks...`})})});if(!t.length)return X(`tr`,{children:X(`td`,{colSpan:8,children:X(It,{title:`No tasks yet`,detail:`Tasks appear here once archied picks up an issue to work.`})})});let e=t.filter(e=>St(e,a)?!s||`${e.title} ${e.repo}`.toLowerCase().includes(s):!1);return e.length?e.map(e=>{let t=d===e.id,n=`task-timeline-${e.id}`;return X(S,{children:[X(`tr`,{className:`task-row`,id:`task-row-${e.id}`,tabIndex:0,onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),A(e.id,t))},onClick:t=>A(e.id,t),...vt(e,t),children:[X(`td`,{className:`mono`,"data-label":`Repository`,children:[X(`button`,{className:`task-expand`,type:`button`,"aria-expanded":String(t),"aria-controls":n,"aria-label":`${t?`Collapse`:`Expand`} timeline for ${e.title||`untitled task`}`,onClick:t=>A(e.id,t),children:t?`−`:`+`}),P(e)??`${e.owner}/${e.repo}`]}),X(`td`,{className:`mono`,"data-label":`Issue`,children:te(e)??`#${e.issue_number}`}),X(`td`,{className:`strong`,"data-label":`Title`,children:e.title||`(untitled)`}),X(`td`,{"data-label":`Status`,children:X(Z,{text:xe(e.status),kind:Se(e.status)})}),X(`td`,{"data-label":`Workflow`,children:e.workflow||`—`}),X(`td`,{"data-label":`Stage`,children:e.stage||`—`}),X(`td`,{"data-label":`Last activity`,title:e.created_at?`Created ${De(e.created_at)}`:``,children:De(e.updated_at)}),X(`td`,{"data-label":`Actions`,children:M(e)})]}),t&&ne(e)]},e.id)}):X(`tr`,{children:X(`td`,{colSpan:8,children:X(It,{title:`No matching tasks`,detail:`Try a different search or status filter.`})})})})()})]})})]})]})}function Rt(e){return X(Lt,{query:e})}function zt({title:e,detail:t}){return X(`div`,{class:`empty`,children:[X(`div`,{class:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Bt(e){return X(Vt,{query:e})}function Vt(){let[e,t]=q([]),[n,r]=q(``),[i,a]=q(null),o=async()=>{try{let e=await B.skills();t(e?.skills||[]),a(null)}catch(e){t([]),a(String(e.message||e))}};J(()=>{o()},[]);let s=(e,t)=>!t||`${e.name} ${e.description}`.toLowerCase().includes(t),c=Ue(()=>e.filter(e=>s(e,n)),[e,n]);return X(`div`,{children:[X(`div`,{class:`page-head`,children:[X(`div`,{children:[X(`h1`,{class:`page-title`,children:`Skills`}),X(`p`,{class:`page-sub`,children:`What Archie can do, in plain language.`})]}),X(`div`,{class:`page-actions`,children:X(`button`,{class:`btn`,onClick:o,children:`Refresh`})})]}),X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:[X(`div`,{children:[X(`h2`,{class:`card-title`,children:`Catalogue`}),X(`p`,{class:`card-sub`,children:`Project, shared, and user-global skills`})]}),X(`input`,{class:`skill-search`,type:`search`,placeholder:`Search skills…`,onInput:e=>r(e.target.value.trim().toLowerCase())})]}),X(`div`,{class:`grid grid-2`,children:i?X(zt,{title:`Cannot reach archied`,detail:i}):e.length?c.length?c.map(e=>X(`div`,{class:`card skill-card`,children:[X(`div`,{class:`card-head`,children:[X(`h3`,{class:`card-title`,children:e.name||`Untitled skill`}),e.workflow&&X(Z,{text:e.workflow,kind:`info`})]}),X(`p`,{class:`skill-desc`,children:e.description||`No description provided.`}),X(`div`,{class:`skill-source`,children:e.source||`Unknown source`})]},e.name)):X(zt,{title:`No skills match`,detail:`Nothing found for "${n}".`}):X(zt,{title:`No skills discovered yet`,detail:`Skills live as SKILL.md files under project, shared, or user-global .agents/skills// directories. Add one and refresh to make it available.`})})]})]})}var Ht={bootstrap:`Bootstrap`,implement:`Implement`,tdd:`TDD`,feasibility:`Feasibility check`};function Ut(e){return Ht[e]?Ht[e]:e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown`}function Wt(e,t){return t?Math.round(e/t*100):0}function Gt(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 Kt({title:e,detail:t}){return X(`div`,{class:`empty`,children:[X(`div`,{class:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function qt({fraction:e,kind:t=`ok`}){let n=Math.min(100,Math.max(0,e));return X(`div`,{class:`wf-bar`,children:X(`div`,{class:`wf-bar-fill wf-bar-${t}`,style:{width:`${n}%`}})})}function Jt(e){return X(Yt,{query:e})}function Yt(){let[e,t]=q([]),[n,r]=q([]),[i,a]=q([]),[o,s]=q(null),c=async()=>{try{let e=await B.workflows();t(e?.definitions||[]),r(e?.workflows||[]),a(e?.stages||[]),s(null)}catch(e){s(String(e.message||e))}};return J(()=>{c()},[]),X(`div`,{children:[X(`div`,{class:`page-head`,children:[X(`div`,{children:[X(`h1`,{class:`page-title`,children:`Workflows`}),X(`p`,{class:`page-sub`,children:`Run outcomes and spend per workflow, and where stages get stuck.`})]}),X(`div`,{class:`page-actions`,children:X(`button`,{class:`btn`,onClick:c,children:`Refresh`})})]}),X(Xt,{definitions:e}),o?X(`div`,{class:`card`,children:X(Kt,{title:`Cannot reach archied`,detail:o})}):X(S,{children:[X(Zt,{workflows:n,definitions:e}),X(Qt,{stages:i})]})]})}function Xt({definitions:e}){if(!e.length)return null;let t=e.filter(e=>e.enabled)[0]?.id||``,[n,r]=q(``),[i,a]=q(``),[o,s]=q(t),[c,l]=q(``),[u,d]=q(``),[f,p]=q(!1),[m,h]=q(``);return J(()=>{!o&&t&&s(t)},[t,o]),X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:[X(`h2`,{class:`card-title`,children:`Start work`}),X(`p`,{class:`card-sub`,children:`This enters Archie’s normal admitted task queue.`})]})}),X(`form`,{class:`wf-form`,onSubmit:async e=>{e.preventDefault(),p(!0),h(``);try{let e=await B.workRequest({identity:n,repository:i,workflow:o,title:c,instructions:u});h(`Queued task #${e.task_id}.`),r(``),a(``),s(t),l(``),d(``)}catch(e){h(String(e.message||e))}finally{p(!1)}},children:[X(`input`,{placeholder:`Identity`,required:!0,value:n,onInput:e=>r(e.target.value)}),X(`input`,{placeholder:`owner/repository`,required:!0,value:i,onInput:e=>a(e.target.value)}),X(`select`,{required:!0,value:o,onInput:e=>s(e.target.value),children:e.filter(e=>e.enabled).map(e=>X(`option`,{value:e.id,children:Ut(e.name||e.id)},e.id))}),X(`input`,{placeholder:`Short task title`,required:!0,value:c,onInput:e=>l(e.target.value)}),X(`textarea`,{placeholder:`Instructions for the work`,required:!0,rows:3,value:u,onInput:e=>d(e.target.value)}),X(`button`,{class:`btn`,type:`submit`,disabled:f,children:`Start work`}),m&&X(`p`,{class:`card-sub`,children:m})]})]})}function Zt({workflows:e,definitions:t}){let n=new Map(e.map(e=>[e.workflow,e])),r=t.map(e=>({...e,...n.get(e.id)||{workflow:e.id,runs:0,merged:0}}));return r.length?X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:[X(`h2`,{class:`card-title`,children:`Per workflow`}),X(`p`,{class:`card-sub`,children:`Success rate is merged tasks over all runs`})]})}),X(`div`,{class:`table-scroll`,children:X(`table`,{class:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Workflow`}),X(`th`,{children:`Origin`}),X(`th`,{children:`Runs`}),X(`th`,{children:`Success rate`}),X(`th`,{children:`Avg tokens`}),X(`th`,{children:`Avg steps`})]})}),X(`tbody`,{children:r.map(e=>{let t=Wt(e.merged,e.runs);return X(`tr`,{children:[X(`td`,{class:`strong`,children:Ut(e.workflow)}),X(`td`,{class:`mono`,children:e.origin||`registry`}),X(`td`,{children:`${e.runs} run${e.runs===1?``:`s`}`}),X(`td`,{children:[X(`div`,{class:`wf-rate`,children:[t,`%`,X(`span`,{class:`wf-rate-sub`,children:[e.merged,` of `,e.runs,` merged`]})]}),X(qt,{fraction:t,kind:t>=50?`ok`:`warn`})]}),X(`td`,{class:`mono`,children:e.avg_tokens?e.avg_tokens.toLocaleString():`—`}),X(`td`,{class:`mono`,children:e.avg_steps?e.avg_steps.toFixed(1):`—`})]},e.workflow)})})]})})]}):X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:X(`h2`,{class:`card-title`,children:`Per workflow`})})}),X(Kt,{title:`No workflow runs yet`,detail:`Stats appear here once a task has run through a workflow.`})]})}function Qt({stages:e}){if(!e.length)return X(`div`,{class:`card wf-stage-card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:X(`h2`,{class:`card-title`,children:`Per stage`})})}),X(Kt,{title:`No stage data yet`,detail:`Stage timing and failures appear here once workflows have run.`})]});let t=Math.max(...e.map(e=>e.avg_ms||0),1),n=[...e].sort((e,t)=>(t.avg_ms||0)-(e.avg_ms||0)),r=[...e].filter(e=>e.errors>0).sort((e,t)=>t.errors-e.errors);return X(`div`,{class:`grid grid-2 wf-stage-card`,children:[X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:[X(`h2`,{class:`card-title`,children:`Slowest stages`}),X(`p`,{class:`card-sub`,children:`Average duration, this workflow's stages`})]})}),X(`div`,{class:`table-scroll`,children:X(`table`,{class:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Workflow`}),X(`th`,{children:`Stage`}),X(`th`,{children:`Runs`}),X(`th`,{children:`Avg duration`})]})}),X(`tbody`,{children:n.map((e,n)=>X(`tr`,{children:[X(`td`,{children:Ut(e.workflow)}),X(`td`,{class:`strong`,children:e.stage}),X(`td`,{children:e.runs}),X(`td`,{children:[X(`div`,{class:`wf-rate`,children:Gt(e.avg_ms)}),X(qt,{fraction:Wt(e.avg_ms,t),kind:`info`})]})]},n))})]})})]}),X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:[X(`h2`,{class:`card-title`,children:`Most failures`}),X(`p`,{class:`card-sub`,children:`Stages that error out, over their runs`})]})}),r.length?X(`div`,{class:`table-scroll`,children:X(`table`,{class:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Workflow`}),X(`th`,{children:`Stage`}),X(`th`,{children:`Failures`})]})}),X(`tbody`,{children:r.map((e,t)=>X(`tr`,{children:[X(`td`,{children:Ut(e.workflow)}),X(`td`,{class:`strong`,children:e.stage}),X(`td`,{children:[X(`div`,{class:`wf-rate`,children:[e.errors,` of `,e.runs]}),X(qt,{fraction:Wt(e.errors,e.runs),kind:`danger`})]})]},t))})]})}):X(Kt,{title:`No failures recorded`,detail:`Every stage has completed cleanly so far.`})]})]})}function $t({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function en(e,t){return e===`running`?`ok`:e===`failed`||e===`degraded`?`warn`:`idle`}function tn(){let[e,t]=q([]),[n,r]=q(null),i=async()=>{try{let e=await B.channels();t(e?.channels||[]),r(null)}catch(e){r(String(e.message||e))}};return J(()=>{i()},[]),X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Channels`}),X(`p`,{className:`page-sub`,children:`The conversational front-ends Archie can be reached through.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn`,onClick:i,children:`Refresh`})})]}),X(`div`,{className:`grid grid-2`,children:n?X($t,{title:`Cannot reach archied`,detail:n}):e.length===0?X($t,{title:`No channels configured`,detail:`Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.`}):e.map(e=>X(`div`,{className:`card channel-card`,children:[X(`div`,{className:`card-head`,children:[X(`h3`,{className:`card-title`,children:e.name}),X(Z,{text:e.state||(e.configured?`configured`:`stopped`),kind:en(e.state,e.configured)})]}),X(`p`,{className:`channel-desc`,children:e.description}),X(`p`,{className:`channel-detail`,children:e.detail}),e.reload_supported?X(`button`,{className:`btn`,onClick:async t=>{t.currentTarget.disabled=!0;try{await B.channelReload(e.id||e.name.toLowerCase()),await i()}catch{}finally{t.currentTarget&&(t.currentTarget.disabled=!1)}},children:`Reload`}):X(`p`,{className:`channel-detail`,children:`Reload requires a daemon restart for this adapter.`})]},e.id||e.name))})]})}function nn(e){return X(tn,{query:e})}function rn({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function an(e){return X(on,{query:e})}function on({query:e}){let[t,n]=q([]),[r,i]=q(null),a=async()=>{try{let e=await B.curators();n(e?.curators||[]),i(null)}catch(e){i(String(e.message||e))}};return J(()=>{a()},[]),X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Curators`}),X(`p`,{className:`page-sub`,children:`Background agents that maintain memory and skills: what ran, and why.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn`,onClick:a,children:`Refresh`})})]}),X(`div`,{className:`grid grid-2`,children:r?X(rn,{title:`Cannot reach archied`,detail:r}):t.length?t.map(e=>X(cn,{curator:e},e.name)):X(rn,{title:`No curators registered`,detail:`Curators are background agent loops that maintain memory and skills. None are registered on this daemon.`})})]})}function sn(e){switch(e){case`healthy`:return`ok`;case`degraded`:return`warn`;case`unhealthy`:return`danger`;default:return`idle`}}function cn({curator:e}){let t=e.recent_actions||[];return X(`div`,{className:`card curator-card`,children:[X(`div`,{className:`card-head`,children:[X(`h3`,{className:`card-title`,children:e.name}),X(Z,{text:e.health?.status||`unknown`,kind:sn(e.health?.status)})]}),e.health?.message&&X(`p`,{className:`curator-health-message`,children:e.health.message}),X(`p`,{className:`curator-meta`,children:e.last_run_at?`Last ran ${De(e.last_run_at)} · ${e.last_run_actions} action${e.last_run_actions===1?``:`s`}`:`Has not run yet`}),t.length?X(`ul`,{className:`curator-actions`,children:t.map((e,t)=>X(`li`,{className:`curator-action`,children:[X(`div`,{className:`curator-action-head`,children:[X(`span`,{className:`curator-action-type`,children:e.type||`action`}),X(`span`,{className:`curator-action-time`,children:De(e.at)})]}),e.detail&&X(`p`,{className:`curator-action-detail`,children:e.detail}),e.reason&&X(`p`,{className:`curator-action-reason`,children:[`Why: `,e.reason]})]},t))}):X(`p`,{className:`curator-meta`,children:`No recorded activity yet.`})]})}function ln(e){return e==null||e===``?`—`:String(e)}function un({label:e,value:t,opts:n}){let r=ln(t),[i,a]=q(!1),[o,s]=q(``),[c,l]=q(null),[u,d]=q(!1),[f,p]=q(!1),m=n?.key;if(!m)return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,title:n?.hint,children:e}),X(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r})]});let h=n.locked?.[m];if(h)return X(`div`,{className:`kv is-locked`,children:[X(`span`,{className:`kv-label`,title:n.hint,children:e}),X(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r}),X(`span`,{className:`kv-note`,children:h})]});if(n.editable===!1)return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,title:n.hint,children:e}),X(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r})]});let g=n.overridden?.includes(m),_=()=>{s(String(n.raw??``)),l(null),a(!0)},v=async()=>{p(!0),l(null);try{await B.configReset(m),n.onSaved?.()}catch(e){l(String(e.message||e))}finally{p(!1)}},y=async()=>{let e=dn(n.type,o);if(e.error){l(e.error);return}d(!0),l(null);try{await(n.save||(e=>B.configUpdate({[m]:e})))(e.value),a(!1),n.onSaved?.()}catch(e){l(String(e.message||e))}finally{d(!1)}};if(i){let t=Y(null);J(()=>{t.current&&t.current.focus()},[]);let r=e=>{e.key===`Enter`&&(e.preventDefault(),y()),e.key===`Escape`&&a(!1)},i;return i=n.type===`bool`?X(`select`,{className:`kv-input`,value:o,onChange:e=>s(e.target.value),onKeyDown:r,ref:t,children:[X(`option`,{value:`true`,children:`true`}),X(`option`,{value:`false`,children:`false`})]}):n.type===`enum`?X(`select`,{className:`kv-input`,value:o,onChange:e=>s(e.target.value),onKeyDown:r,ref:t,children:(n.options||[]).map(e=>X(`option`,{value:e,children:e},e))}):X(`input`,{className:`kv-input`,type:`text`,value:o,onInput:e=>s(e.target.value),onKeyDown:r,ref:t}),X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,title:n.hint,children:e}),i,X(`div`,{className:`kv-actions`,children:[X(`button`,{className:`kv-save`,type:`button`,onClick:y,disabled:u,children:`Save`}),X(`button`,{className:`kv-cancel`,type:`button`,onClick:()=>a(!1),disabled:u,children:`Cancel`})]}),c&&X(`span`,{className:`kv-note is-error`,children:c})]})}return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,title:n.hint,children:e}),X(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r}),X(`div`,{className:`kv-actions`,children:[g&&X(`span`,{className:`kv-flag`,title:`Set from the dashboard; this shadows the value in the config file`,children:`overridden`}),X(`button`,{className:`kv-btn`,type:`button`,title:`Edit ${e}`,onClick:_,children:`Edit`}),g&&X(`button`,{className:`kv-btn`,type:`button`,title:`Discard the dashboard value and fall back to the config file`,onClick:v,disabled:f,children:`Reset`})]}),c&&X(`span`,{className:`kv-note is-error`,children:c})]})}function dn(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}}}function fn({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function pn({sub:e,title:t,children:n}){return X(`div`,{className:`card cfg-section`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:t||`Update status`}),X(`p`,{className:`card-sub`,children:e})]})}),n]})}var mn={ok:`OK`,update_available:`Update available`,drift:`Drift`,unknown:`Unknown`},hn={ok:`ok`,update_available:`info`,drift:`danger`,unknown:`idle`};function gn({components:e}){return!e||!e.length?X(pn,{sub:`How each component is deployed, and whether what's running matches what's installed.`,children:X(fn,{title:`No components reported`,detail:`The configured update-check command returned nothing.`})}):X(pn,{sub:`How each component is deployed, and whether what's running matches what's installed. Hover a row for the exact versions compared.`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Component`}),X(`th`,{children:`Install type`}),X(`th`,{children:`Running`}),X(`th`,{children:`Latest available`}),X(`th`,{children:`Status`})]})}),X(`tbody`,{children:e.map(e=>X(`tr`,{title:[`Installed claim: ${e.installed_claim||`unknown`}`,`Running: ${e.running_version||`not observed`}`,e.reference?`Reference: ${e.reference}`:null].filter(Boolean).join(` +`),children:[X(`td`,{className:`strong`,children:e.label||e.id}),X(`td`,{className:`mono`,children:e.install_type||`—`}),X(`td`,{className:`mono`,children:e.running_version||`—`}),X(`td`,{className:`mono`,children:e.latest_available||`—`}),X(`td`,{children:X(Z,{text:mn[e.status]||e.status,kind:hn[e.status]||`idle`})})]},e.id||e.label))})]})})})}function Q({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function $({title:e,sub:t,children:n}){return X(`div`,{className:`card cfg-section`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:e}),X(`p`,{className:`card-sub`,children:t})]})}),n]})}function _n({origins:e}){return e?.length?X($,{title:`Configuration sources`,sub:`Applied from top to bottom; later entries take precedence over earlier ones.`,children:X(`div`,{className:`kv-list`,children:e.map((e,t)=>X(un,{label:`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,value:e.path},t))})}):X($,{title:`Configuration sources`,sub:`The files that supplied the running configuration.`,children:X(Q,{title:`Source provenance is unavailable.`})})}function vn(e){return e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``}function yn({data:e,error:t}){if(t)return X($,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships.`,children:X(Q,{title:`Lifecycle unavailable`,detail:t})});let n=e?.statuses||[],r=e?.actions||[];return X($,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships. Add one on the backend and it appears here without a frontend change.`,children:[X(`h3`,{className:`cfg-subhead`,children:`Statuses`}),n.length?X(`div`,{className:`kv-list`,children:n.map(e=>{let t=e.label??xe(e.id),n=e.kind??Se(e.id);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(Z,{text:t,kind:n})})]},e.id)})}):X(Q,{title:`No statuses reported`,detail:`The server did not return any lifecycle statuses.`}),X(`h3`,{className:`cfg-subhead`,children:`Actions`}),r.length?X(`div`,{className:`kv-list`,children:r.map(e=>{let t=e.label??e.id,n=vn(e.kind);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(`button`,{className:`btn btn-small ${n}`,type:`button`,disabled:!0,children:t})})]},e.id)})}):X(Q,{title:`No actions reported`,detail:`The server did not return any operator actions.`})]})}function bn({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=q(!1),[o,s]=q(null),[c,l]=q(!!e[t]);return r?X(`td`,{children:[X(`input`,{className:`repo-field-checkbox`,type:`checkbox`,checked:c,onChange:async r=>{let i=r.target.checked;l(i),a(!0),s(null);try{await B.configRepoUpdate(e.owner,e.name,t,i),n?.()}catch(e){l(!i),s(String(e.message||e))}finally{a(!1)}},disabled:i}),o&&X(`span`,{className:`kv-note is-error`,children:o})]}):X(`td`,{children:c?`yes`:`no`})}function xn({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=q(String(e[t]??0)),[o,s]=q(null),[c,l]=q(!1);return r?X(`td`,{children:[X(`input`,{className:`kv-input`,type:`text`,value:i,onChange:e=>a(e.target.value),onBlur:async()=>{let r=parseInt(i,10);if(Number.isNaN(r)){s(`Enter a whole number`);return}l(!0),s(null);try{await B.configRepoUpdate(e.owner,e.name,t,r),n?.()}catch(e){s(String(e.message||e))}finally{l(!1)}},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),e.target.blur())},disabled:c}),o&&X(`span`,{className:`kv-note is-error`,children:o})]}):X(`td`,{className:`mono`,children:i})}function Sn({repos:e,onSaved:t,editable:n=!0}){if(!e?.length)return X($,{title:`Repositories`,sub:`The repositories Archie polls for work.`,children:X(Q,{title:`No repositories configured`,detail:`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`})});let r=e=>e?.length?e.map(e=>e.join(` `)).join(` → `):`—`;return X($,{title:`Repositories`,sub:`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request. Concurrent tasks, retries, and self-review are per-repository overrides -- PATCH /api/config/repos/{owner}/{name}, not the file config.toml directly.`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Repository`}),X(`th`,{children:`Base branch`}),X(`th`,{children:`Ecosystem`}),X(`th`,{children:`Quality gate`}),X(`th`,{children:`Protected paths`}),X(`th`,{children:`Concurrent`}),X(`th`,{children:`Max retries`}),X(`th`,{children:`Self-review`})]})}),X(`tbody`,{children:e.map((e,i)=>X(`tr`,{children:[X(`td`,{className:`strong`,children:[e.owner,`/`,e.name]}),X(`td`,{className:`mono`,children:e.base}),X(`td`,{children:e.ecosystem||`go`}),X(`td`,{className:`mono`,children:r(e.gate)}),X(`td`,{className:`mono`,children:e.protect?.length?e.protect.join(`, `):`—`}),X(bn,{r:e,field:`allow_concurrent`,onSaved:t,editable:n}),X(xn,{r:e,field:`max_retries`,onSaved:t,editable:n}),X(bn,{r:e,field:`review_enabled`,onSaved:t,editable:n})]},i))})]})})})}function Cn(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function wn({models:e,providers:t}){let n=Object.entries(e||{}),r=Object.entries(t||{});return X($,{title:`Models & providers`,sub:`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,children:[X(`h3`,{className:`cfg-subhead`,children:`Model roles`}),n.length?X(`div`,{className:`kv-list`,children:n.map(([e,t])=>X(un,{label:Cn(e),value:t},e))}):X(Q,{title:`No model roles configured`,detail:`Assign a model to at least one role (e.g. "builder") in [models].`}),X(`h3`,{className:`cfg-subhead`,children:`Providers`}),r.length?X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Provider`}),X(`th`,{children:`Class`}),X(`th`,{children:`Base URL`}),X(`th`,{children:`API key env var`}),X(`th`,{children:`Status`})]})}),X(`tbody`,{children:r.map(([e,t])=>X(`tr`,{children:[X(`td`,{className:`strong`,children:e}),X(`td`,{children:t.class}),X(`td`,{className:`mono`,children:t.base_url||`default`}),X(`td`,{className:`mono`,children:t.api_key_env||`—`}),X(`td`,{children:t.configured?X(Z,{text:`configured`,kind:`ok`}):X(Z,{text:`missing credentials`,kind:`warn`})})]},e))})]})}):X(Q,{title:`No providers configured`,detail:`Add a [providers.] entry so a model role above has something to run on.`})]})}function Tn(){let[e,t]=q(null),[n,r]=q(null),[i,a]=q(null),[o,s]=q(null),[c,l]=q(!1),[u,d]=q(null),[f,p]=q(null),m=()=>{h(),g(),_()},h=async()=>{try{let e=await B.config();t(e),r(null)}catch(e){r(String(e.message||e))}},g=async()=>{try{let e=await B.version();a(e?.components||[]),s(null),l(!1)}catch(e){e?.status===501?l(!0):s(String(e.message||e))}},_=async()=>{try{let e=await B.taskMeta();d(e),p(null)}catch(e){p(String(e.message||e))}};return J(()=>{m()},[]),X(`div`,{className:`cfg-page`,children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Configuration`}),X(`p`,{className:`page-sub`,children:`What archied is actually running with right now.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn`,onClick:m,children:`Refresh`})})]}),X(`div`,{children:!c&&(o?X(`div`,{className:`card`,children:X(Q,{title:`Update status unavailable`,detail:o})}):i?X(gn,{components:i}):null)}),X(`div`,{children:X(yn,{data:u,error:f})}),X(`div`,{children:n?X(`div`,{className:`card`,children:X(Q,{title:`Cannot reach archied`,detail:n})}):!e||Object.keys(e).length===0?X(`div`,{className:`card`,children:X(Q,{title:`No configuration loaded`,detail:`archied is running without a config file wired into the dashboard, so there is nothing to show.`})}):X(S,{children:[e.reload?.overlay_unavailable&&X(`div`,{className:`card cfg-notice`,children:X(`p`,{children:[`The runtime config overlay is not in effect: `,e.reload.overlay_unavailable]})}),e.reload?.last_error&&X(`div`,{className:`card cfg-notice`,children:X(`p`,{children:[`The last config reload failed; the running config is unchanged: `,e.reload.last_error]})}),(e.schema||[]).map((t,n)=>{let r=t.fields.filter(e=>e.type!==`structured`);return r.length?X($,{title:t.label,sub:t.description,children:X(`div`,{className:`kv-list`,children:r.map(t=>X(un,{label:t.label,value:t.value,opts:{key:t.key,type:t.type,options:t.options,raw:t.value,hint:t.description,editable:t.editable&&e.editable!==!1,locked:e.locked||{},overridden:e.overridden||[],onSaved:h}},t.key))})},n):null}),X(Sn,{repos:e.repositories,onSaved:h,editable:e.editable!==!1}),X(wn,{models:e.models,providers:e.providers}),X(_n,{origins:e.provenance})]})})]})}function En(e){return X(Tn,{query:e})}function Dn({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function On(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function kn(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function An(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function jn({entry:e}){let t=e.fields||{};return X(`div`,{className:`log-row log-${On(e.level)}`,children:[X(`span`,{className:`log-time mono`,children:An(e.time)}),X(`span`,{className:`log-level`,children:(e.level||`info`).toUpperCase()}),X(`span`,{className:`log-body`,children:[X(`span`,{className:`log-msg`,children:e.message||e.msg||``}),Object.entries(t).map(([e,t])=>X(`span`,{className:`log-field`,children:[X(`span`,{className:`log-field-key`,children:e}),String(kn(t))]},e))]})]})}var Mn=[{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 Nn(e){return`${e.time||``}|${e.level||``}|${e.message||e.msg||``}|${JSON.stringify(e.fields||{})}`}function Pn(){let[e,t]=q({level:``,component:``,q:``}),[n,r]=q(!1),[i,a]=q([]),[o,s]=q([]),c=Y(new Map),[l,u]=q(0),[d,f]=q(!1),[p,m]=q(`connecting`),[h,g]=q(`Refreshing…`),_=Y(null),v=Y(null),y=async()=>{g(`Refreshing…`);try{let t=await B.logs({level:e.level,component:e.component,q:e.q,limit:500});a(e=>{let n=t.components||[];return e.length===n.length&&e.every((e,t)=>e===n[t])?e:n}),f(!!t.disabled);let n=t.disabled?`Durable history unavailable; live daemon logs continue.`:t.truncated?`showing the most recent matches from ${t.file}`:t.file||``;g(n),s(t.entries||[])}catch{g(`Cannot read logs`)}};J(()=>{y()},[e]),J(()=>{let e=pe(e=>{if(b.current)return;let t=e;S.current(t)&&(c.current.set(Nn(t),t),t.fields?.component&&a(e=>e.includes(t.fields.component)?e:[...e,t.fields.component]),u(e=>e+1))},e=>{m(e)});return()=>e()},[]);let b=Y(n);b.current=n;let x=t=>{if(e.level&&!e.level.split(`,`).includes((t.level||``).toUpperCase())||e.component&&t.fields?.component!==e.component)return!1;if(e.q){let n=e.q.toLowerCase();if(!`${t.message||t.msg||``} ${JSON.stringify(t.fields||{})}`.toLowerCase().includes(n))return!1}return!0},S=Y(x);S.current=x;let C=Ue(()=>{let e=new Map;for(let t of o)e.set(Nn(t),t);for(let[t,n]of c.current)e.set(t,n);return[...e.values()].filter(x).slice(-1e3)},[o,l,e]);return J(()=>{_.current&&(_.current.scrollTop=_.current.scrollHeight)},[C]),X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Logs`}),X(`p`,{className:`page-sub`,children:`What Archie has been doing, newest last.`})]}),X(`div`,{className:`page-actions`,children:[X(`button`,{className:`btn ${n?`btn-primary`:``}`,onClick:()=>r(!n),children:n?`Resume`:`Pause`}),X(`button`,{className:`btn`,onClick:y,children:`Refresh`})]})]}),X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:[X(`div`,{className:`log-filters`,children:[X(`select`,{className:`log-select`,value:e.level,onChange:e=>t(t=>({...t,level:e.target.value})),children:Mn.map(e=>X(`option`,{value:e.value,children:e.label},e.value))}),X(`select`,{className:`log-select`,value:e.component,onChange:e=>t(t=>({...t,component:e.target.value})),children:[X(`option`,{value:``,children:`All components`}),i.map(e=>X(`option`,{value:e,children:e},e))]}),X(`input`,{className:`log-search`,type:`search`,placeholder:`Search messages and fields…`,onInput:e=>{let n=e.target.value;v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{t(e=>({...e,q:n}))},250)}})]}),X(`div`,{className:`log-status`,children:[X(`span`,{className:`log-meta`,children:h}),X(Z,{text:p,kind:p===`live`?`ok`:`warn`})]})]}),X(`div`,{className:`log-list`,ref:_,children:h===`Cannot read logs`?X(Dn,{title:`Cannot read logs`}):C.length?C.map(e=>X(jn,{entry:e},Nn(e))):X(Dn,{title:d?`Durable history unavailable`:`Nothing matches`,detail:d?`Live daemon logs will appear here while this page is open.`:`Try a wider level or clear the search.`})})]})]})}function Fn(e){return X(Pn,{query:e})}function In({capture:e,expanded:t,onToggle:n}){return X(S,{children:[X(`tr`,{className:`capture-row`,tabIndex:`0`,"aria-expanded":String(t),onClick:n,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),n(e))},children:[X(`td`,{className:`mono`,children:e.source||`(unknown)`}),X(`td`,{title:e.received_at||``,children:De(e.received_at)}),X(`td`,{children:X(Z,{text:`Unbound`,kind:`idle`})}),X(`td`,{className:`mono`,children:e.content_type||`—`}),X(`td`,{children:X(`button`,{className:`btn btn-small`,type:`button`,children:t?`Hide`:`View`})})]}),t&&X(Ln,{capture:e})]})}function Ln({capture:e}){return X(`tr`,{className:`capture-detail-row`,children:X(`td`,{colSpan:`5`,children:X(`div`,{className:`capture-detail`,children:[X(`div`,{className:`capture-detail-section`,children:[X(`div`,{className:`capture-detail-title`,children:`Payload`}),X(Rn,{raw:e.body})]}),X(`div`,{className:`capture-detail-section`,children:[X(`div`,{className:`capture-detail-title`,children:`Headers`}),X(Rn,{raw:e.headers})]})]})})})}function Rn({raw:e}){return e?X(`pre`,{className:`capture-payload`,children:zn(e)}):X(`div`,{className:`capture-empty`,children:`(empty)`})}function zn(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function Bn({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Vn(e){return X(Hn,{query:e})}function Hn({query:e}){let[t,n]=q([]),[r,i]=q(null),[a,o]=q(null),[s,c]=q(!0),[l,u]=q({text:`connecting`,kind:`idle`}),d=async()=>{try{let e=await B.captures(100);c(e.enabled!==!1),n(e.captures||[]),o(null)}catch(e){o(String(e.message||e))}};return J(()=>{d();let e=V(e=>{e.kind===`capture`&&d()},e=>{u({text:e,kind:e===`live`?`ok`:`warn`})});return()=>e()},[]),X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Event inspector`}),X(`p`,{className:`page-sub`,children:`Real inbound payloads archie has captured, most recent first.`})]}),X(`div`,{className:`page-actions`,children:[X(Z,{text:l.text,kind:l.kind}),X(`button`,{className:`btn`,onClick:d,children:`Refresh`})]})]}),X(`div`,{className:`card`,children:a?X(Bn,{title:`Cannot reach archied`,detail:a}):s?t.length?X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[`Source`,`Received`,`Binding`,`Content type`,``].map((e,t)=>X(`th`,{children:e},t))})}),X(`tbody`,{children:t.map(e=>X(In,{capture:e,expanded:r===e.id,onToggle:()=>i(r===e.id?null:e.id)},e.id))})]})}):X(Bn,{title:`No captures yet`,detail:`Point a webhook at /webhooks/capture/ and it will show up here.`}):X(Bn,{title:`Capture is not configured`,detail:`This deployment has no capture storage wired up.`})})]})}var Un=[`string`,`number`,`bool`,`object`,`array`,`any`];function Wn(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 Gn(e,t){return e?`${e}.${t}`:t}function Kn(e,t){return`${e}[${t}]`}function qn({value:e,path:t=``,name:n=``,onPick:r}){return typeof e==`object`&&e?X(`ul`,{className:`mapping-tree-list`,children:(Array.isArray(e)?e.map((e,n)=>[String(n),e,Kn(t,n)]):Object.entries(e).map(([e,n])=>[e,n,Gn(t,e)])).map(([e,t,n])=>X(`li`,{className:`mapping-tree-item`,children:[X(`span`,{className:`mapping-tree-key`,onClick:i=>{i.stopPropagation(),r&&r({path:n,type:Wn(t),name:e})},children:e}),X(qn,{value:t,path:n,name:e,onPick:r})]},n))}):X(`span`,{className:`mapping-tree-value`,onClick:i=>{i.stopPropagation(),r&&r({path:t,type:Wn(e),name:n})},children:JSON.stringify(e)})}function Jn({fields:e,preview:t,onRemove:n,onNameChange:r,onTypeChange:i,onRequiredChange:a}){if(!e.length)return X(`div`,{className:`mapping-empty-fields`,children:`Click a value in the payload to bind a field.`});let o=new Map((t?.failures||[]).map(e=>[e.field_name,e]));return X(`table`,{className:`table mapping-fields-table`,children:[X(`thead`,{children:X(`tr`,{children:[`Field name`,`Path`,`Type`,`Required`,`Preview`,``].map((e,t)=>X(`th`,{children:e},t))})}),X(`tbody`,{children:e.map((e,s)=>X(`tr`,{children:[X(`td`,{children:X(`input`,{className:`mapping-input`,value:e.name,onInput:e=>r?.(s,e.target.value)})}),X(`td`,{className:`mono`,children:e.path}),X(`td`,{children:X(`select`,{className:`mapping-select`,value:e.type,onChange:e=>i?.(s,e.target.value),children:Un.map(e=>X(`option`,{value:e,children:e},e))})}),X(`td`,{children:X(`input`,{type:`checkbox`,checked:e.required,onChange:e=>a?.(s,e.target.checked)})}),X(`td`,{children:X(Yn,{field:e,preview:t,failureByField:o})}),X(`td`,{children:X(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>n?.(s),children:`Remove`})})]},s))})]})}function Yn({field:e,preview:t,failureByField:n}){if(!t)return X(Z,{text:`not previewed`,kind:`idle`});let r=n.get(e.name);return r?X(Z,{text:r.reason,kind:`danger`}):Object.prototype.hasOwnProperty.call(t.values||{},e.name)?X(Z,{text:JSON.stringify(t.values[e.name]),kind:`ok`}):X(Z,{text:`skipped (optional)`,kind:`idle`})}function Xn({mapping:e,onEdit:t,onDelete:n}){return X(`tr`,{children:[X(`td`,{children:e.name}),X(`td`,{className:`mono`,children:e.source_hint||`—`}),X(`td`,{children:String(e.fields?.length??0)}),X(`td`,{children:[X(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>t?.(e),children:`Edit`}),X(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>n?.(e),children:`Delete`})]})]})}function Zn({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Qn(e){return X($n,{query:e})}function $n({query:e}){let[t,n]=q([]),[r,i]=q([]),[a,o]=q(null),[s,c]=q(null),l=async()=>{try{let[e,t]=await Promise.all([B.mappings(),B.captures(100)]);n(e.mappings||[]),i(t.captures||[]),o(null)}catch(e){o(String(e.message||e))}};J(()=>{l()},[]);let u=()=>{c({id:null,name:``,sourceHint:``,fields:[],captureId:null,payload:null,payloadError:null,preview:null,actionError:null})},d=e=>{c({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})},f=async e=>{if(window.confirm(`Delete mapping "${e.name}"?`))try{await B.mappingDelete(e.id),await l()}catch(e){o(String(e.message||e))}},p=e=>{let t=r.find(t=>String(t.id)===String(e));c(e=>{let n={...e,captureId:t?t.id:null,preview:null};if(!t)n.payload=null,n.payloadError=null;else try{n.payload=JSON.parse(t.body),n.payloadError=null}catch{n.payload=null,n.payloadError=`This capture's body is not valid JSON, so its fields cannot be mapped by path.`}return n})},m=({path:e,type:t,name:n})=>{c(r=>{let i=new Set(r.fields.map(e=>e.name)),a=n||`field`,o=1;for(;i.has(a);)a=`${n||`field`}_${++o}`;let s=[...r.fields,{name:a,path:e,type:t,required:!0}];return{...r,fields:s,preview:null}})},h=e=>{c(t=>{let n=t.fields.slice();return n.splice(e,1),{...t,fields:n,preview:null}})},g=(e,t)=>{c(n=>{let r=n.fields.slice();return r[e]={...r[e],...t},{...n,fields:r,preview:null}})};return s?X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:X(`h1`,{className:`page-title`,children:s.id?`Edit mapping`:`New mapping`})}),X(`div`,{className:`page-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:()=>{c(null)},children:`Cancel`}),X(`button`,{className:`btn btn-primary`,type:`button`,onClick:async()=>{let e={name:s.name,source_hint:s.sourceHint,fields:s.fields};try{s.id?await B.mappingUpdate(s.id,e):await B.mappingCreate(e),c(null),await l()}catch(e){c(t=>({...t,actionError:String(e.message||e)}))}},children:`Save`})]})]}),s.actionError&&X(`div`,{className:`mapping-error`,children:s.actionError}),X(`div`,{className:`card mapping-form`,children:[X(`label`,{className:`mapping-form-row`,children:[`Name`,X(`input`,{className:`mapping-input`,value:s.name,onInput:e=>c(t=>({...t,name:e.target.value}))})]}),X(`label`,{className:`mapping-form-row`,children:[`Source hint (organisational only)`,X(`input`,{className:`mapping-input`,value:s.sourceHint,onInput:e=>c(t=>({...t,sourceHint:e.target.value}))})]}),X(`label`,{className:`mapping-form-row`,children:[`Preview against captured event`,X(`select`,{className:`mapping-select`,value:s.captureId||``,onChange:e=>p(e.target.value),children:[X(`option`,{value:``,children:`— pick a captured event —`}),r.map(e=>X(`option`,{value:e.id,children:[e.source||`(unknown)`,` — `,e.received_at||``]},e.id))]})]})]}),X(`div`,{className:`card mapping-fields`,children:[X(`div`,{className:`mapping-section-title`,children:`Bound fields`}),X(Jn,{fields:s.fields,preview:s.preview,onRemove:h,onNameChange:(e,t)=>g(e,{name:t}),onTypeChange:(e,t)=>g(e,{type:t}),onRequiredChange:(e,t)=>g(e,{required:t})}),X(`button`,{className:`btn`,type:`button`,onClick:async()=>{if(!s.captureId){c(e=>({...e,actionError:`Pick a captured event to preview against.`}));return}try{let e=await B.mappingPreview(s.captureId,s.fields);c(t=>({...t,preview:e,actionError:null}))}catch(e){c(t=>({...t,actionError:String(e.message||e)}))}},children:`Preview`})]}),X(`div`,{className:`card mapping-payload`,children:[X(`div`,{className:`mapping-section-title`,children:`Payload — click a value to bind it`}),s.payloadError?X(`div`,{className:`mapping-error`,children:s.payloadError}):s.payload===null?X(`div`,{className:`mapping-empty-fields`,children:`Pick a captured event above to see its payload.`}):X(qn,{value:s.payload,onPick:m})]})]}):X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Field mappings`}),X(`p`,{className:`page-sub`,children:`Bind named fields to JSON paths from a real captured event, ready for a playbook binding.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn btn-primary`,type:`button`,onClick:u,children:`New mapping`})})]}),a?X(Zn,{title:`Cannot reach archied`,detail:a}):t.length?X(`div`,{className:`card`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[`Name`,`Source hint`,`Fields`,``].map((e,t)=>X(`th`,{children:e},t))})}),X(`tbody`,{children:t.map(e=>X(Xn,{mapping:e,onEdit:()=>d(e),onDelete:()=>f(e)},e.id))})]})})}):X(Zn,{title:`No mappings yet`,detail:`Create one from a captured event to reuse fields in a future playbook binding.`})]})}var er={draft:`draft`,pending_approval:`pending approval`,armed:`armed`},tr={draft:`idle`,pending_approval:`warn`,armed:`ok`};function nr({status:e}){return X(Z,{text:er[e]||e,kind:tr[e]||`idle`})}function rr({binding:e,onEdit:t,onApprove:n,onDelete:r}){let i=e.owner&&e.repo?`${e.owner}/${e.repo}`:`—`;return X(`tr`,{children:[X(`td`,{children:e.name}),X(`td`,{className:`mono`,children:e.matcher?.source||`—`}),X(`td`,{children:e.workflow}),X(`td`,{className:`mono`,children:i}),X(`td`,{children:X(nr,{status:e.status})}),X(`td`,{children:[X(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>t?.(e),children:`Edit`}),e.status===`pending_approval`&&X(`button`,{className:`btn btn-small btn-primary`,type:`button`,onClick:()=>n?.(e),children:`Approve`}),X(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>r?.(e),children:`Delete`})]})]})}function ir({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function ar(e){return X(sr,{query:e})}function or(){return{id:null,name:``,source:``,mappingId:``,workflow:``,owner:``,repo:``,secret:``,actionError:null}}function sr({query:e}){let[t,n]=q([]),[r,i]=q([]),[a,o]=q([]),[s,c]=q(null),[l,u]=q(null),d=async()=>{try{let[e,t,r]=await Promise.all([B.bindings(),B.mappings(),B.workflows()]);n(e.bindings||[]),i(t.mappings||[]),o((r.definitions||[]).filter(e=>e.enabled)),c(null)}catch(e){c(String(e.message||e))}};J(()=>{d()},[]);let f=()=>{u(or())},p=e=>{u({id:e.id,name:e.name,source:e.matcher?.source||``,mappingId:e.mapping_id?String(e.mapping_id):``,workflow:e.workflow||``,owner:e.owner||``,repo:e.repo||``,secret:``,actionError:null})},m=()=>u(null),h=async()=>{let e={name:l.name,matcher:{source:l.source},mapping_id:Number(l.mappingId)||0,workflow:l.workflow,owner:l.owner,repo:l.repo,secret:l.secret};try{l.id?await B.bindingUpdate(l.id,e):await B.bindingCreate(e),u(null),await d()}catch(e){u(t=>({...t,actionError:String(e.message||e)}))}},g=async e=>{try{await B.bindingApprove(e.id),await d()}catch(e){c(String(e.message||e))}},_=async e=>{if(window.confirm(`Delete binding "${e.name}"?`))try{await B.bindingDelete(e.id),await d()}catch(e){c(String(e.message||e))}};return l?X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:X(`h1`,{className:`page-title`,children:l.id?`Edit binding`:`New binding`})}),X(`div`,{className:`page-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:m,children:`Cancel`}),X(`button`,{className:`btn btn-primary`,type:`button`,onClick:h,children:`Save`})]})]}),l.actionError&&X(`div`,{className:`binding-error`,children:l.actionError}),X(`div`,{className:`card binding-form`,children:[X(`label`,{className:`binding-form-row`,children:[`Name`,X(`input`,{className:`binding-input`,value:l.name,onInput:e=>u(t=>({...t,name:e.target.value}))})]}),X(`label`,{className:`binding-form-row`,children:[`Source (the path segment senders POST to, e.g. "sentry")`,X(`input`,{className:`binding-input`,value:l.source,onInput:e=>u(t=>({...t,source:e.target.value}))})]}),X(`label`,{className:`binding-form-row`,children:[`Field mapping`,X(`select`,{className:`binding-select`,value:l.mappingId,onChange:e=>u(t=>({...t,mappingId:e.target.value})),children:[X(`option`,{value:``,children:`— pick a saved mapping —`}),r.map(e=>X(`option`,{value:e.id,children:e.name},e.id))]})]}),X(`label`,{className:`binding-form-row`,children:[`Workflow`,X(`select`,{className:`binding-select`,value:l.workflow,onChange:e=>u(t=>({...t,workflow:e.target.value})),children:[X(`option`,{value:``,children:`— pick a workflow —`}),a.map(e=>X(`option`,{value:e.id,children:e.name},e.id))]})]}),X(`label`,{className:`binding-form-row`,children:[`Repo pin -- owner (optional; leave both blank for the single-configured-repo default)`,X(`input`,{className:`binding-input`,value:l.owner,onInput:e=>u(t=>({...t,owner:e.target.value}))})]}),X(`label`,{className:`binding-form-row`,children:[`Repo pin -- repo`,X(`input`,{className:`binding-input`,value:l.repo,onInput:e=>u(t=>({...t,repo:e.target.value}))})]}),X(`label`,{className:`binding-form-row`,children:[`Shared secret (`,l.id?`leave blank to keep the current secret`:`senders sign with this via HMAC-SHA256`,`)`,X(`input`,{className:`binding-input`,type:`password`,value:l.secret,onInput:e=>u(t=>({...t,secret:e.target.value}))})]})]})]}):X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Playbook bindings`}),X(`p`,{className:`page-sub`,children:`Tie a matcher, a field mapping, and a workflow together. New and edited bindings need explicit approval before they can fire.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn btn-primary`,type:`button`,onClick:f,children:`New binding`})})]}),s?X(ir,{title:`Cannot reach archied`,detail:s}):t.length?X(`div`,{className:`card`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[`Name`,`Source`,`Workflow`,`Repo pin`,`Status`,``].map((e,t)=>X(`th`,{children:e},t))})}),X(`tbody`,{children:t.map(e=>X(rr,{binding:e,onEdit:()=>p(e),onApprove:()=>g(e),onDelete:()=>_(e)},e.id))})]})})}):X(ir,{title:`No bindings yet`,detail:`Create one from a saved field mapping to turn a captured webhook into a workflow.`})]})}function cr({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function lr(e){return e===`external`?`Added by you — an external store Archie was given`:`Built in — always available to Archie`}function ur({provider:e}){let t=e.tools||[];return X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:[X(`div`,{children:[X(`h2`,{className:`card-title`,children:e.name||`provider`}),X(`p`,{className:`card-sub`,children:lr(e.role)})]}),e.available?X(Z,{text:`ready`,kind:`ok`}):X(Z,{text:`unavailable`,kind:`danger`})]}),!e.available&&X(`p`,{className:`mem-warning`,children:`Configured but not usable right now — a required binary or connection may be missing.`}),t.length?X(`ul`,{className:`mem-tools`,children:t.map((e,t)=>X(`li`,{className:`mem-tool`,children:[X(`div`,{className:`mem-tool-name mono`,children:e.name}),e.description&&X(`div`,{className:`mem-tool-desc`,children:e.description})]},t))}):X(`p`,{className:`mem-warning`,children:`This provider exposes no tools, so the agent cannot use it.`})]})}function dr(){let[e,t]=q(null),[n,r]=q(!0),[i,a]=q(null),[o,s]=q(!0),c=async()=>{s(!0),a(null);try{let e=await B.memory();r(!!e.enabled),t(e.providers||[])}catch(e){a(String(e.message||e))}finally{s(!1)}};return J(()=>{c()},[]),X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Memory`}),X(`p`,{className:`page-sub`,children:`What Archie can recall between conversations, and the tools it uses to do it.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn`,onClick:c,children:`Refresh`})})]}),X(`div`,{children:o?X(`div`,{className:`card`,children:X(`div`,{className:`mem-loading`,children:`Loading…`})}):i?X(`div`,{className:`card`,children:X(cr,{title:`Cannot read memory providers`,detail:i})}):!n||!e.length?X(`div`,{className:`card`,children:X(cr,{title:`Memory is not configured`,detail:`Without a provider, Archie starts every conversation with no recollection of earlier ones.`})}):X(`div`,{className:`grid grid-2`,children:e.map((e,t)=>X(ur,{provider:e},t))})})]})}function fr(e){return X(dr,{query:e})}function pr(e){let t=document.createDocumentFragment(),n=/(!\[[^\]]*\]\((?:https?:\/\/[^\s)]+|data:image\/[^\s)]+|\/[^\s)]+)\)|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\((?:https?:\/\/[^\s)]+|\/[^\s)]+)\)|\*[^*]+\*|_[^_]+_)/g,r=0;for(let i of e.matchAll(n)){i.index>r&&t.append(document.createTextNode(e.slice(r,i.index)));let n=i[0];if(n.startsWith(`![`)){let e=n.match(/^!\[([^\]]*)\]\((.+)\)$/);e&&t.append(U(`img.chat-media-img`,{src:e[2],alt:e[1]||`Image`,loading:`lazy`}))}else if(n.startsWith(`~~`))t.append(U(`del`,n.slice(2,-2)));else if(n.startsWith(`**`)||n.startsWith(`__`))t.append(U(`strong`,n.slice(2,-2)));else if(n.startsWith("`"))t.append(U(`code`,n.slice(1,-1)));else if(n.startsWith(`[`)){let e=n.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+|\/[^\s)]+)\)$/);t.append(U(`a`,{href:e[2],target:`_blank`,rel:`noreferrer`},e[1]))}else t.append(U(`em`,n.slice(1,-1)));r=i.index+n.length}return r{r.length&&(t.append(U(`p`,pr(r.join(` `)))),r=[])},s=()=>{i&&t.append(i),i=null};for(let e=0;eU(`td`,pr(e)))));t.append(U(`table`,U(`thead`,U(`tr`,...l.map(e=>U(`th`,pr(e))))),i));continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.append(U(`h${d[1].length}`,pr(d[2])));continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tagName.toLowerCase()!==e)&&(s(),i=U(e)),i.append(U(`li`,pr((f||p)[1])));continue}if(c.startsWith(`>`)){o(),s(),t.append(U(`blockquote`,pr(c.replace(/^>\s?/,``))));continue}r.push(c)}return o(),s(),a&&t.append(U(`pre`,U(`code`,a.join(` +`)))),t}function hr(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 gr(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var _r=`archie.web.chat.channel`;function vr(){let e=localStorage.getItem(_r);return e||(e=oe(),localStorage.setItem(_r,e)),e}function yr(e){return{text:e,sourceID:oe()}}function br(e){return{...e}}function xr(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?br(e.turn):yr(r),isRetry:n}}function Sr(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function Cr(e){return e?.status===501?null:`Could not check for updates.`}function wr(){return location.hash.slice(1)||`/`}function Tr({text:e}){let t=Y(null);return J(()=>{t.current&&t.current.replaceChildren(mr(e||``))},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function Er(){let[e,t]=q([]),[n,r]=q(``),[i,a]=q([]),[o,s]=q(``),[c,l]=q(`Ready`),[u,d]=q(!1),[f,p]=q({}),[m,h]=q(``),[g,_]=q(``),[v,y]=q(``),[b,x]=q([]),[C,w]=q([]),[T,E]=q(0),[D,O]=q(!1),[k,A]=q(null),[j,ee]=q(null),[M,N]=q(null),[P,te]=q(``),[ne,re]=q(``),[F,I]=q(null),L=Y(null),R=Y(null),ie=Y(null),ae=Y(null),oe=Y(null),se=Y(u);se.current=u,J(()=>{L.current&&(L.current.scrollTop=L.current.scrollHeight)},[i,F]),J(()=>{V().catch(e=>{l(e.message||`Chat unavailable`)}),ce();let e=()=>{ie.current?.abort()};return window.addEventListener(`archie:teardown`,e),()=>{window.removeEventListener(`archie:teardown`,e),ie.current?.abort()}},[]);async function ce(){try{let e=await B.chatUpdate();ee(e?.snapshot||null),A(e)}catch(e){let t=Cr(e);A(t?{error:t}:null)}}async function le(){if(j)try{await B.chatUpdateDefer(j),A({snapshot:{deferred:!0},available:[]}),l(`Update deferred`)}catch(e){l(e.message||`Could not defer update`)}}async function ue(){if(j)try{l(`Installing…`);let e=await B.chatUpdateInstall(j);ee(null),A({snapshot:{},available:[]}),l(e?.result?.restart_requested?`Update installed; restart queued`:`Update complete`)}catch(e){l(e.message||`Update install failed`)}}async function de(){try{let e=await B.chatDangerous();N(e)}catch(e){N({error:e.message||`Dangerous actions unavailable`})}}async function fe(e,t){if(t)try{await B.chatDangerousRequest(e,t),l(`Approval requested`),await de()}catch(e){l(e.message||`Could not request action`)}}async function z(e,t){try{await B.chatDangerousDecision(e,t),l(t===`deny`?`Action denied`:`Action approved`),await de()}catch(e){l(e.message||`Approval failed`)}}async function V(){let e=await B.chatSessions(),r=e.sessions||[];t(r),p(e),h(e.active_persona||``);let i=e.providers||[],a=e.active_provider||i[0]||``;_(a),y(e.active_model||``);let o=(e.commands||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e);x(o),e.dangerous_available&&await de(),!n&&r[0]&&await pe(r[0].session_id,e,r)}async function pe(e,t,n){let i=t||f;r(e),a([]),I(null);let o=i.active_personas?.[e]||i.active_persona||``;h(o);try{await B.chatMessage(vr(),`/resume ${e}`);let[t,n]=await Promise.all([B.chatMessages(e),B.chatTurns(e)]),r=new Map;for(let e of n||[]){let t=e.assistant_message_id||e.AssistantMessageID;t&&r.set(t,e)}let i=(t||[]).map(e=>{let t=e.message_id||e.MessageID,n=r.get(t);return n?{...e,tool_calls:n.tool_calls||n.ToolCalls||[]}:e});a(i)}catch(e){l(e.message||`Could not load session messages`)}}async function me(e){if(n)try{l(`Working…`);let t=await B.chatMessage(vr(),e);t.session_id&&r(t.session_id),l(t.reply||`Session updated`),await V(),(t.session_id||n)&&await pe(t.session_id||n),ae.current&&(ae.current.open=!1)}catch(e){l(e.message||`Session action failed`)}}function he(e,t){let n=window.prompt(t);n?.trim()&&me(`${e} ${n.trim()}`)}function ge(e){let t=e.target.value;h(t),!(!n||!t)&&B.chatPersona(n,t).then(()=>{p(e=>({...e,active_personas:{...e.active_personas||{},[n]:t}})),l(`Personality: ${t}`)}).catch(e=>{l(e.message||`Failed to set personality`)})}async function _e(e){let t=e.target.value;if(_(t),t)try{let e=await B.chatMessage(vr(),`/model --provider ${t}`);l(e.reply||`Provider updated`),await V()}catch(e){l(`Provider update failed: ${e.message||e}`)}}async function ve(e){let t=e.target.value;if(y(t),t)try{let e=await B.chatMessage(vr(),`/model ${t}`);l(e.reply||`Model updated`),await V()}catch(e){l(`Model update failed: ${e.message||e}`)}}function ye(){window.confirm(`Reload the Telegram chat adapter?`)&&(s(`/restart`),H({textOverride:`/restart`}))}function be(){s(`/new`),H({textOverride:`/new`})}function xe(e){let t=e.target.value;s(t);let n=t.slice(0,e.target.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);if(n){let e=n[1].toLowerCase(),t=b.filter(t=>`${t.command} ${t.description}`.toLowerCase().includes(e)).slice(0,8);if(t.length){w(t),E(0),O(!0);return}}O(!1),w([])}function Se(e){let t=C[e];if(!t||!R.current)return;let n=R.current,r=n.value.slice(0,n.selectionStart),i=n.value.slice(n.selectionStart),a=r.search(/(?:^|\s)\/[^\s]*$/),o=a<0?r.length:a+ +(r[a]===` `),c=`${r.slice(0,o)}${t.command} ${i}`;s(c),O(!1);let l=o+t.command.length+1;setTimeout(()=>{n.focus(),n.setSelectionRange(l,l)},0)}function Ce(e){if(D&&C.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&C.some(e=>e.command===o.trim())){e.preventDefault(),O(!1),H();return}if(e.key===`ArrowDown`){e.preventDefault(),E(e=>(e+1)%C.length);return}if(e.key===`ArrowUp`){e.preventDefault(),E(e=>(e+C.length-1)%C.length);return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Se(T);return}if(e.key===`Escape`){e.preventDefault(),O(!1);return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),H())}async function H(e=null){let t=e?.textOverride,{text:n,turn:i,isRetry:c}=xr(e,t===void 0?o:t);if(!n||se.current)return;O(!1),d(!0),l(c?`Retrying…`:`Thinking…`),c||(a(e=>[...e,{from:`web`,text:n}]),s(``));let u=[];I({text:``,tools:[],isError:!1,turn:i,isRetry:c});let f=``,p=!1,m=!1,h=null;try{let e=new AbortController;ie.current=e,h=setTimeout(()=>{m=!0,e.abort()},12e4);let t=(await B.chatStream({channel_id:vr(),source_id:i.sourceID,text:i.text,page:wr()},{signal:e.signal})).body.getReader(),n=new TextDecoder,o=``;for(;;){let{value:e,done:i}=await t.read();o+=n.decode(e||new Uint8Array,{stream:!i});let a=o.split(` `);o=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&&r(n.session_id),n.type===`delta`&&(f+=n.text,I(e=>e?{...e,text:f}:null)),n.type===`tool`&&(u=[...u,n],I(e=>e?{...e,tools:u}:null)),n.type===`navigate`&&(u=[...u,n],I(e=>e?{...e,tools:u}:null)),n.type===`done`&&(p=!0,f||=n.text),n.type===`error`)throw Error(n.text)}if(i)break}if(!p)throw Error(`chat stream ended before completion`);a(e=>[...e,{from:`assistant`,text:f,tool_calls:u}]),I(null),l(`Ready`),await B()}catch(e){if(e.name===`AbortError`&&!m)I({text:`Turn stopped.`,tools:u,isError:!1,turn:i,isRetry:c}),l(`Stopped`);else{let t=`Unable to complete that turn: ${e.message||e}`;I({text:t,tools:u,isError:!0,turn:yr(i),isRetry:c}),l(`Error — retry available`)}}finally{clearTimeout(h),ae.current=null,d(!1),L.current&&L.current.focus()}}function Te(){l(`Stopping…`),n&&z.chatCancel(n).catch(()=>{}),ae.current?.abort()}let H=f.models_by_provider||{},Ee=g&&H[g]?H[g]:f.models||[];return X(`div`,{className:`chat-page-content`,children:[X(`header`,{className:`chat-topbar`,children:[X(`div`,{children:[X(`span`,{className:`chat-kicker`,children:`ARCHIE WORKSPACE`}),X(`h1`,{className:`page-title`,children:`Chat`})]}),X(`div`,{className:`chat-topbar-actions`,children:[X(`span`,{className:`chat-status`,children:c}),f.restart_available&&X(`button`,{className:`btn`,type:`button`,onClick:be,children:`Reload Telegram`}),X(`button`,{className:`btn`,type:`button`,onClick:le,children:`Check updates`}),X(`select`,{className:`chat-select`,"aria-label":`Personality`,value:m,onChange:_e,children:[X(`option`,{value:``,children:`Personality`}),(f.personas||[]).map(e=>X(`option`,{value:e,children:e},e))]}),(f.providers||[]).length>0&&X(`select`,{className:`chat-select`,"aria-label":`Provider`,value:g,onChange:ve,children:[X(`option`,{value:``,children:`Provider`}),(f.providers||[]).map(e=>X(`option`,{value:e,children:e},e))]}),X(`select`,{className:`chat-select`,"aria-label":`Model`,value:v,onChange:ye,children:[X(`option`,{value:``,children:`Model`}),Ee.map(e=>X(`option`,{value:e,children:e},e))]})]})]}),k&&X(`div`,{className:`chat-update-panel`,children:k.error?X(`span`,{children:k.error}):k.available?.length?X(S,{children:[X(`div`,{children:[X(`strong`,{children:`Update available`}),X(`span`,{children:k.available.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `)})]}),X(`div`,{className:`chat-update-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:ue,children:`Defer`}),k.can_install&&X(`button`,{className:`btn btn-primary`,type:`button`,onClick:de,children:`Install update`})]})]}):X(`span`,{children:k.snapshot?.deferred?`Update deferred.`:`Archie is up to date.`})}),f.dangerous_available&&M&&X(`div`,{className:`chat-dangerous-panel`,children:[X(`div`,{className:`chat-dangerous-head`,children:[X(`strong`,{children:`Dangerous actions`}),X(`span`,{className:`chat-hint`,children:`Every action requires approval.`})]}),X(`div`,{className:`chat-dangerous-controls`,children:[X(`div`,{children:[X(`select`,{className:`chat-select`,"aria-label":`Checkpoint`,value:P,onChange:e=>te(e.target.value),children:[X(`option`,{value:``,children:`Select checkpoint`}),(M.checkpoints||[]).map(e=>X(`option`,{value:e.Number??e.number,children:[e.Number??e.number,` — `,e.Label??e.label??`checkpoint`]},e.Number??e.number))]}),X(`button`,{className:`btn`,type:`button`,onClick:()=>pe(`rollback`,P),children:`Request rollback`})]}),X(`div`,{children:[X(`input`,{className:`chat-dangerous-input`,placeholder:`Process name or id`,"aria-label":`Process name or id`,value:ne,onInput:e=>re(e.target.value)}),X(`button`,{className:`btn`,type:`button`,onClick:()=>pe(`stop`,ne),children:`Request stop`})]})]}),X(`div`,{className:`chat-dangerous-pending-list`,children:(M.pending||[]).length?M.pending.map(e=>X(`div`,{className:`chat-dangerous-pending`,children:[X(`span`,{children:e.description}),X(`div`,{className:`chat-update-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:()=>R(e.id,`approve`),children:`Approve`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>R(e.id,`permanent`),children:`Approve for 24h`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>R(e.id,`deny`),children:`Deny`})]})]},e.id)):X(`span`,{className:`chat-hint`,children:`No pending dangerous actions.`})})]}),X(`div`,{className:`chat-layout`,children:[X(`aside`,{className:`chat-sidebar`,children:[X(`div`,{className:`chat-sidebar-head`,children:[X(`strong`,{children:`Conversations`}),X(`button`,{className:`btn btn-primary`,type:`button`,onClick:xe,children:`+ New chat`})]}),X(`div`,{className:`chat-session-list`,children:e.length?e.map(e=>X(`button`,{className:`chat-session ${n===e.session_id?`active`:``}`,type:`button`,onClick:()=>me(e.session_id),children:[X(`strong`,{children:xr(e)}),X(`span`,{children:new Date(e.last_active_at).toLocaleString()})]},e.session_id)):X(`div`,{className:`chat-empty`,children:`Your conversations will appear here.`})})]}),X(`section`,{className:`chat-workspace`,children:[X(`div`,{className:`chat-workspace-head`,children:[X(`span`,{className:`chat-workspace-label`,children:`PERSONAL ASSISTANT`}),X(`details`,{className:`chat-command-help`,children:[X(`summary`,{children:[`Available commands (`,b.length,`)`]}),X(`div`,{className:`chat-command-list`,children:b.length?b.map(e=>X(`div`,{className:`chat-command-item`,children:[X(`code`,{children:e.usage||e.command}),X(`span`,{children:e.description||``})]},e.command)):X(`span`,{children:`Send a message to begin.`})})]}),X(`details`,{className:`chat-session-tools`,ref:oe,hidden:!n,children:[X(`summary`,{children:`Session actions`}),X(`div`,{className:`chat-session-tool-list`,children:[X(`button`,{className:`btn`,type:`button`,onClick:()=>he(`/retry`),children:`Retry`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>he(`/undo`),children:`Undo`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>ge(`/title`,`Session title`),children:`Rename`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>ge(`/branch`,`Branch name (optional)`),children:`Branch`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>he(`/compress --preview`),children:`Preview compression`})]})]})]}),X(`div`,{className:`chat-transcript`,ref:ie,children:!i.length&&!F?X(`div`,{className:`chat-empty-state`,children:[X(`span`,{className:`chat-empty-mark`,children:`A`}),X(`h2`,{children:`What are we working on?`}),X(`p`,{children:`Ask Archie anything, or start with one of these prompts.`}),X(`div`,{className:`chat-prompt-grid`,children:[X(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{s(`Summarise active tasks`),L.current?.focus()},children:`Summarise active tasks`}),X(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{s(`Show running agents`),L.current?.focus()},children:`Show running agents`}),X(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{s(`Check system status`),L.current?.focus()},children:`Check system status`})]})]}):X(S,{children:[i.map((e,t)=>{let n=e.from??e.From??``,r=e.text??e.Text??``,i=n!==`web`,a=e.tool_calls||e.ToolCalls||[];return X(`div`,{className:`chat-bubble-row ${i?`assistant`:`user`}`,children:X(`div`,{className:`chat-bubble`,children:[X(`div`,{className:`chat-bubble-meta`,children:i?`Archie`:`You`}),i?X(S,{children:[a.length>0&&X(`div`,{className:`chat-tools`,children:a.map((e,t)=>{if(e.path)return X(`a`,{className:`chat-nav-chip`,href:`#${e.path}`,title:`Go to ${e.label||e.path}`,children:[X(`span`,{className:`chat-nav-chip-icon`,"aria-hidden":`true`,children:`↗`}),X(`span`,{className:`chat-nav-chip-label`,children:e.label||e.path})]},t);let n=e.name||e.Name||e.tool||`tool`,r=e.parameters||e.Parameters||``,i=e.summary||e.Summary||e.text||e.err||e.Err||`done`;return X(`div`,{className:`chat-tool ${e.err||e.Err||e.failed?`failed`:``}`,children:[X(`span`,{className:`chat-tool-icon`,children:`🔧`}),X(`span`,{className:`chat-tool-name`,children:n}),r&&X(`code`,{className:`chat-tool-parameters`,children:r}),X(`span`,{className:`chat-tool-summary`,children:i})]},t)})}),X(wr,{text:r})]}):X(`div`,{className:`chat-bubble-text`,children:r})]})},t)}),F&&X(`div`,{className:`chat-bubble-row assistant`,children:X(`div`,{className:`chat-bubble`,children:[X(`div`,{className:`chat-bubble-meta`,children:`Archie`}),F.tools?.length>0&&X(`div`,{className:`chat-tools`,children:F.tools.map((e,t)=>{if(e.path)return X(`a`,{className:`chat-nav-chip`,href:`#${e.path}`,title:`Go to ${e.label||e.path}`,children:[X(`span`,{className:`chat-nav-chip-icon`,"aria-hidden":`true`,children:`↗`}),X(`span`,{className:`chat-nav-chip-label`,children:e.label||e.path})]},t);let n=e.name||e.tool||`tool`,r=e.parameters||``,i=e.summary||e.text||(e.failed?`failed`:`running…`);return X(`div`,{className:`chat-tool ${e.failed?`failed`:``}`,children:[X(`span`,{className:`chat-tool-icon`,children:`🔧`}),X(`span`,{className:`chat-tool-name`,children:n}),r&&X(`code`,{className:`chat-tool-parameters`,children:r}),X(`span`,{className:`chat-tool-summary`,children:i})]},t)})}),X(wr,{text:F.text||`…`}),F.isError&&X(`button`,{className:`btn chat-retry`,type:`button`,onClick:()=>V({turn:F.turn}),children:`Retry`})]})})]})}),X(`div`,{className:`chat-compose`,children:X(`div`,{className:`chat-composer-shell`,children:[X(`textarea`,{ref:L,className:`chat-composer`,rows:3,placeholder:`Message Archie… (commands like /status and /new work here)`,"aria-label":`Message Archie`,disabled:u,value:o,onInput:Se,onKeyDown:we}),D&&C.length>0&&X(`div`,{className:`chat-command-menu`,ref:se,role:`listbox`,"aria-label":`Commands`,children:C.map((e,t)=>X(`button`,{type:`button`,role:`option`,"aria-selected":String(t===T),className:`chat-command-option`,onMouseDown:e=>e.preventDefault(),onClick:()=>Ce(t),children:[X(`code`,{children:e.command}),X(`span`,{children:e.description||e.usage||``})]},e.command))}),X(`div`,{className:`chat-compose-actions`,children:[X(`span`,{className:`chat-hint`,children:`Enter to send · Shift+Enter for a new line`}),X(`button`,{className:`btn`,type:`button`,disabled:!u,onClick:Te,children:`Stop`}),X(`button`,{className:`btn btn-primary`,type:`button`,disabled:u||!o.trim(),onClick:()=>V(),children:`Send`})]})]})})]})]})]})}function Er(){let e=document.createElement(`div`);return e.className=`chat-page`,oe(X(Tr,{}),e),e}var Dr=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:_t},{path:`/chat`,label:`Chat`,icon:`chat`,view:Er,section:`chat`},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:Lt},{path:`/logs`,label:`Logs`,icon:`logs`,view:Pn,section:`logs`},{path:`/captures`,label:`Event inspector`,icon:`captures`,view:Bn,section:`captures`},{path:`/mappings`,label:`Field mappings`,icon:`mappings`,view:Zn,section:`mappings`},{path:`/bindings`,label:`Playbook bindings`,icon:`bindings`,view:ir,section:`bindings`},{path:`/skills`,label:`Skills`,icon:`skills`,view:zt,section:`skills`},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:qt,section:`workflows`},{path:`/memory`,label:`Memory`,icon:`memory`,view:dr,section:`memory`},{path:`/curators`,label:`Curators`,icon:`curators`,view:rn,section:`curators`},{path:`/channels`,label:`Channels`,icon:`channels`,view:tn,section:`channels`},{path:`/settings`,label:`Configuration`,icon:`settings`,view:Tn,section:`settings`}],Or=`archie.theme`;function kr(e){document.documentElement.dataset.theme=e,localStorage.setItem(Or,e)}function Ar(){return localStorage.getItem(Or)||`dark`}function jr(e,t){let n=new Map,r=H(`nav.nav`,...[null].flatMap(()=>[...Dr.map(t=>{let r=H(`a.nav-item`,{href:`#${t.path}`,onclick:n=>{t.soon?n.preventDefault():e(t.path)},"aria-disabled":t.soon||void 0,title:t.soon?`Coming soon`:void 0},W(t.icon),H(`span.nav-label`,t.label),t.soon&&H(`span.nav-soon`,`soon`));return n.set(t.path,r),r})])),i=H(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{kr(Ar()===`dark`?`light`:`dark`),De(i,W(Ar()===`dark`?`moon`:`sun`))}});De(i,W(Ar()===`dark`?`moon`:`sun`));let a,o=()=>{a?.classList.remove(`is-open`),s.setAttribute(`aria-expanded`,`false`)},s=H(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{a.classList.add(`is-open`),s.setAttribute(`aria-expanded`,`true`),c.focus()}},W(`search`,{size:15})),c=H(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:t=>{if(t.key===`Escape`){t.preventDefault(),o(),t.target.blur();return}if(t.key!==`Enter`)return;let n=t.target.value.trim().toLowerCase(),r=Dr.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(e(r.path),t.target.value=``,t.target.blur(),o())}});return a=H(`div.topbar-search`,H(`span.topbar-search-icon`,{"aria-hidden":`true`},W(`search`,{size:15})),s,c),{node:H(`header.topbar`,H(`div.brand`,H(`span.brand-mark`,`A`),`Archie`),r,H(`div.topbar-end`,a,H(`button.icon-btn.icon-btn-chat`,{"aria-label":`Open chat`,title:`Chat with Archie`,"aria-expanded":`false`,onclick:()=>t?.()},W(`chat`)),H(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},W(`help`)),i,H(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,r]of n)t===e?r.setAttribute(`aria-current`,`page`):r.removeAttribute(`aria-current`)},hide(e){for(let t of e)n.get(t)?.remove()}}}function Mr(){kr(Ar());let e=H(`main.main`),t=H(`aside.chat-drawer`,{"aria-label":`Chat with Archie`}),n=H(`button.icon-btn.chat-drawer-close`,{"aria-label":`Close chat`,title:`Close chat`,onclick:()=>o(!1)},W(`close`)),r=H(`div.chat-drawer-head`,H(`strong`,`Archie`),n);t.append(H(`div.chat-drawer-panel`,r,Er()),H(`div.chat-scrim`,{onclick:()=>o(!1)}));let i=jr(s,()=>o());z.capabilities().then(e=>i.hide(he(e?.sections,Dr))).catch(()=>{});let a=H(`div.shell`,i.node,e,t);De(document.getElementById(`app`),a);function o(e){let n=e===void 0?!t.classList.contains(`is-open`):e;t.classList.toggle(`is-open`,n),document.body.classList.toggle(`chat-open`,n);let r=a.querySelector(`.icon-btn-chat`);r&&r.setAttribute(`aria-expanded`,String(n))}window.__archieToggleChat=o;function s(e){location.hash===`#`+e?c(e):location.hash=e}function c(t){e.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[n,r=``]=t.split(`?`,2),a=Dr.find(e=>e.path===n)||Dr[0];if(i.highlight(a.path),a.path===`/chat`){De(e),o(!0);return}let s=a.view?a.view(new URLSearchParams(r)):Nr(a);s instanceof Node?De(e,s):oe(s,e),o(!1)}window.addEventListener(`hashchange`,()=>c(location.hash.slice(1)||`/`)),window.addEventListener(`keydown`,e=>{e.defaultPrevented||e.key===`Escape`&&t.classList.contains(`is-open`)&&o(!1)}),c(location.hash.slice(1)||`/`)}function Nr(e){return H(`div`,H(`div.page-head`,H(`div`,H(`h1.page-title`,e.label))),H(`div.card`,H(`div.empty`,H(`div.empty-title`,`${e.label} is not built yet`),H(`div`,`This section is next up. Nothing is broken.`))))}Mr(); \ 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&&r(n.session_id),n.type===`delta`&&(f+=n.text,I(e=>e?{...e,text:f}:null)),n.type===`tool`&&(u=[...u,n],I(e=>e?{...e,tools:u}:null)),n.type===`navigate`&&(u=[...u,n],I(e=>e?{...e,tools:u}:null)),n.type===`done`&&(p=!0,f||=n.text),n.type===`error`)throw Error(n.text)}if(i)break}if(!p)throw Error(`chat stream ended before completion`);a(e=>[...e,{from:`assistant`,text:f,tool_calls:u}]),I(null),l(`Ready`),await V()}catch(e){if(e.name===`AbortError`&&!m)I({text:`Turn stopped.`,tools:u,isError:!1,turn:i,isRetry:c}),l(`Stopped`);else{let t=`Unable to complete that turn: ${e.message||e}`;I({text:t,tools:u,isError:!0,turn:br(i),isRetry:c}),l(`Error — retry available`)}}finally{clearTimeout(h),ie.current=null,d(!1),R.current&&R.current.focus()}}function we(){l(`Stopping…`),n&&B.chatCancel(n).catch(()=>{}),ie.current?.abort()}let U=f.models_by_provider||{},Te=g&&U[g]?U[g]:f.models||[];return X(`div`,{className:`chat-page-content`,children:[X(`header`,{className:`chat-topbar`,children:[X(`div`,{children:[X(`span`,{className:`chat-kicker`,children:`ARCHIE WORKSPACE`}),X(`h1`,{className:`page-title`,children:`Chat`})]}),X(`div`,{className:`chat-topbar-actions`,children:[X(`span`,{className:`chat-status`,children:c}),f.restart_available&&X(`button`,{className:`btn`,type:`button`,onClick:ye,children:`Reload Telegram`}),X(`button`,{className:`btn`,type:`button`,onClick:ce,children:`Check updates`}),X(`select`,{className:`chat-select`,"aria-label":`Personality`,value:m,onChange:ge,children:[X(`option`,{value:``,children:`Personality`}),(f.personas||[]).map(e=>X(`option`,{value:e,children:e},e))]}),(f.providers||[]).length>0&&X(`select`,{className:`chat-select`,"aria-label":`Provider`,value:g,onChange:_e,children:[X(`option`,{value:``,children:`Provider`}),(f.providers||[]).map(e=>X(`option`,{value:e,children:e},e))]}),X(`select`,{className:`chat-select`,"aria-label":`Model`,value:v,onChange:ve,children:[X(`option`,{value:``,children:`Model`}),Te.map(e=>X(`option`,{value:e,children:e},e))]})]})]}),k&&X(`div`,{className:`chat-update-panel`,children:k.error?X(`span`,{children:k.error}):k.available?.length?X(S,{children:[X(`div`,{children:[X(`strong`,{children:`Update available`}),X(`span`,{children:k.available.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `)})]}),X(`div`,{className:`chat-update-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:le,children:`Defer`}),k.can_install&&X(`button`,{className:`btn btn-primary`,type:`button`,onClick:ue,children:`Install update`})]})]}):X(`span`,{children:k.snapshot?.deferred?`Update deferred.`:`Archie is up to date.`})}),f.dangerous_available&&M&&X(`div`,{className:`chat-dangerous-panel`,children:[X(`div`,{className:`chat-dangerous-head`,children:[X(`strong`,{children:`Dangerous actions`}),X(`span`,{className:`chat-hint`,children:`Every action requires approval.`})]}),X(`div`,{className:`chat-dangerous-controls`,children:[X(`div`,{children:[X(`select`,{className:`chat-select`,"aria-label":`Checkpoint`,value:P,onChange:e=>te(e.target.value),children:[X(`option`,{value:``,children:`Select checkpoint`}),(M.checkpoints||[]).map(e=>X(`option`,{value:e.Number??e.number,children:[e.Number??e.number,` — `,e.Label??e.label??`checkpoint`]},e.Number??e.number))]}),X(`button`,{className:`btn`,type:`button`,onClick:()=>fe(`rollback`,P),children:`Request rollback`})]}),X(`div`,{children:[X(`input`,{className:`chat-dangerous-input`,placeholder:`Process name or id`,"aria-label":`Process name or id`,value:ne,onInput:e=>re(e.target.value)}),X(`button`,{className:`btn`,type:`button`,onClick:()=>fe(`stop`,ne),children:`Request stop`})]})]}),X(`div`,{className:`chat-dangerous-pending-list`,children:(M.pending||[]).length?M.pending.map(e=>X(`div`,{className:`chat-dangerous-pending`,children:[X(`span`,{children:e.description}),X(`div`,{className:`chat-update-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:()=>z(e.id,`approve`),children:`Approve`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>z(e.id,`permanent`),children:`Approve for 24h`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>z(e.id,`deny`),children:`Deny`})]})]},e.id)):X(`span`,{className:`chat-hint`,children:`No pending dangerous actions.`})})]}),X(`div`,{className:`chat-layout`,children:[X(`aside`,{className:`chat-sidebar`,children:[X(`div`,{className:`chat-sidebar-head`,children:[X(`strong`,{children:`Conversations`}),X(`button`,{className:`btn btn-primary`,type:`button`,onClick:be,children:`+ New chat`})]}),X(`div`,{className:`chat-session-list`,children:e.length?e.map(e=>X(`button`,{className:`chat-session ${n===e.session_id?`active`:``}`,type:`button`,onClick:()=>pe(e.session_id),children:[X(`strong`,{children:Sr(e)}),X(`span`,{children:new Date(e.last_active_at).toLocaleString()})]},e.session_id)):X(`div`,{className:`chat-empty`,children:`Your conversations will appear here.`})})]}),X(`section`,{className:`chat-workspace`,children:[X(`div`,{className:`chat-workspace-head`,children:[X(`span`,{className:`chat-workspace-label`,children:`PERSONAL ASSISTANT`}),X(`details`,{className:`chat-command-help`,children:[X(`summary`,{children:[`Available commands (`,b.length,`)`]}),X(`div`,{className:`chat-command-list`,children:b.length?b.map(e=>X(`div`,{className:`chat-command-item`,children:[X(`code`,{children:e.usage||e.command}),X(`span`,{children:e.description||``})]},e.command)):X(`span`,{children:`Send a message to begin.`})})]}),X(`details`,{className:`chat-session-tools`,ref:ae,hidden:!n,children:[X(`summary`,{children:`Session actions`}),X(`div`,{className:`chat-session-tool-list`,children:[X(`button`,{className:`btn`,type:`button`,onClick:()=>me(`/retry`),children:`Retry`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>me(`/undo`),children:`Undo`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>he(`/title`,`Session title`),children:`Rename`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>he(`/branch`,`Branch name (optional)`),children:`Branch`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>me(`/compress --preview`),children:`Preview compression`})]})]})]}),X(`div`,{className:`chat-transcript`,ref:L,children:!i.length&&!F?X(`div`,{className:`chat-empty-state`,children:[X(`span`,{className:`chat-empty-mark`,children:`A`}),X(`h2`,{children:`What are we working on?`}),X(`p`,{children:`Ask Archie anything, or start with one of these prompts.`}),X(`div`,{className:`chat-prompt-grid`,children:[X(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{s(`Summarise active tasks`),R.current?.focus()},children:`Summarise active tasks`}),X(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{s(`Show running agents`),R.current?.focus()},children:`Show running agents`}),X(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{s(`Check system status`),R.current?.focus()},children:`Check system status`})]})]}):X(S,{children:[i.map((e,t)=>{let n=e.from??e.From??``,r=e.text??e.Text??``,i=n!==`web`,a=e.tool_calls||e.ToolCalls||[];return X(`div`,{className:`chat-bubble-row ${i?`assistant`:`user`}`,children:X(`div`,{className:`chat-bubble`,children:[X(`div`,{className:`chat-bubble-meta`,children:i?`Archie`:`You`}),i?X(S,{children:[a.length>0&&X(`div`,{className:`chat-tools`,children:a.map((e,t)=>{if(e.path)return X(`a`,{className:`chat-nav-chip`,href:`#${e.path}`,title:`Go to ${e.label||e.path}`,children:[X(`span`,{className:`chat-nav-chip-icon`,"aria-hidden":`true`,children:`↗`}),X(`span`,{className:`chat-nav-chip-label`,children:e.label||e.path})]},t);let n=e.name||e.Name||e.tool||`tool`,r=e.parameters||e.Parameters||``,i=e.summary||e.Summary||e.text||e.err||e.Err||`done`;return X(`div`,{className:`chat-tool ${e.err||e.Err||e.failed?`failed`:``}`,children:[X(`span`,{className:`chat-tool-icon`,children:`🔧`}),X(`span`,{className:`chat-tool-name`,children:n}),r&&X(`code`,{className:`chat-tool-parameters`,children:r}),X(`span`,{className:`chat-tool-summary`,children:i})]},t)})}),X(Tr,{text:r})]}):X(`div`,{className:`chat-bubble-text`,children:r})]})},t)}),F&&X(`div`,{className:`chat-bubble-row assistant`,children:X(`div`,{className:`chat-bubble`,children:[X(`div`,{className:`chat-bubble-meta`,children:`Archie`}),F.tools?.length>0&&X(`div`,{className:`chat-tools`,children:F.tools.map((e,t)=>{if(e.path)return X(`a`,{className:`chat-nav-chip`,href:`#${e.path}`,title:`Go to ${e.label||e.path}`,children:[X(`span`,{className:`chat-nav-chip-icon`,"aria-hidden":`true`,children:`↗`}),X(`span`,{className:`chat-nav-chip-label`,children:e.label||e.path})]},t);let n=e.name||e.tool||`tool`,r=e.parameters||``,i=e.summary||e.text||(e.failed?`failed`:`running…`);return X(`div`,{className:`chat-tool ${e.failed?`failed`:``}`,children:[X(`span`,{className:`chat-tool-icon`,children:`🔧`}),X(`span`,{className:`chat-tool-name`,children:n}),r&&X(`code`,{className:`chat-tool-parameters`,children:r}),X(`span`,{className:`chat-tool-summary`,children:i})]},t)})}),X(Tr,{text:F.text||`…`}),F.isError&&X(`button`,{className:`btn chat-retry`,type:`button`,onClick:()=>H({turn:F.turn}),children:`Retry`})]})})]})}),X(`div`,{className:`chat-compose`,children:X(`div`,{className:`chat-composer-shell`,children:[X(`textarea`,{ref:R,className:`chat-composer`,rows:3,placeholder:`Message Archie… (commands like /status and /new work here)`,"aria-label":`Message Archie`,disabled:u,value:o,onInput:xe,onKeyDown:Ce}),D&&C.length>0&&X(`div`,{className:`chat-command-menu`,ref:oe,role:`listbox`,"aria-label":`Commands`,children:C.map((e,t)=>X(`button`,{type:`button`,role:`option`,"aria-selected":String(t===T),className:`chat-command-option`,onMouseDown:e=>e.preventDefault(),onClick:()=>Se(t),children:[X(`code`,{children:e.command}),X(`span`,{children:e.description||e.usage||``})]},e.command))}),X(`div`,{className:`chat-compose-actions`,children:[X(`span`,{className:`chat-hint`,children:`Enter to send · Shift+Enter for a new line`}),X(`button`,{className:`btn`,type:`button`,disabled:!u,onClick:we,children:`Stop`}),X(`button`,{className:`btn btn-primary`,type:`button`,disabled:u||!o.trim(),onClick:()=>H(),children:`Send`})]})]})})]})]})]})}function Dr(){let e=document.createElement(`div`);return e.className=`chat-page`,ae(X(Er,{}),e),e}var Or=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:_t},{path:`/chat`,label:`Chat`,icon:`chat`,view:Dr,section:`chat`},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:Rt},{path:`/logs`,label:`Logs`,icon:`logs`,view:Fn,section:`logs`},{path:`/captures`,label:`Event inspector`,icon:`captures`,view:Vn,section:`captures`},{path:`/mappings`,label:`Field mappings`,icon:`mappings`,view:Qn,section:`mappings`},{path:`/bindings`,label:`Playbook bindings`,icon:`bindings`,view:ar,section:`bindings`},{path:`/skills`,label:`Skills`,icon:`skills`,view:Bt,section:`skills`},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:Jt,section:`workflows`},{path:`/memory`,label:`Memory`,icon:`memory`,view:fr,section:`memory`},{path:`/curators`,label:`Curators`,icon:`curators`,view:an,section:`curators`},{path:`/channels`,label:`Channels`,icon:`channels`,view:nn,section:`channels`},{path:`/settings`,label:`Configuration`,icon:`settings`,view:En,section:`settings`}],kr=`archie.theme`;function Ar(e){document.documentElement.dataset.theme=e,localStorage.setItem(kr,e)}function jr(){return localStorage.getItem(kr)||`dark`}function Mr(e,t){let n=new Map,r=U(`nav.nav`,...[null].flatMap(()=>[...Or.map(t=>{let r=U(`a.nav-item`,{href:`#${t.path}`,onclick:n=>{t.soon?n.preventDefault():e(t.path)},"aria-disabled":t.soon||void 0,title:t.soon?`Coming soon`:void 0},W(t.icon),U(`span.nav-label`,t.label),t.soon&&U(`span.nav-soon`,`soon`));return n.set(t.path,r),r})])),i=U(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{Ar(jr()===`dark`?`light`:`dark`),Ee(i,W(jr()===`dark`?`moon`:`sun`))}});Ee(i,W(jr()===`dark`?`moon`:`sun`));let a,o=()=>{a?.classList.remove(`is-open`),s.setAttribute(`aria-expanded`,`false`)},s=U(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{a.classList.add(`is-open`),s.setAttribute(`aria-expanded`,`true`),c.focus()}},W(`search`,{size:15})),c=U(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:t=>{if(t.key===`Escape`){t.preventDefault(),o(),t.target.blur();return}if(t.key!==`Enter`)return;let n=t.target.value.trim().toLowerCase(),r=Or.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(e(r.path),t.target.value=``,t.target.blur(),o())}});return a=U(`div.topbar-search`,U(`span.topbar-search-icon`,{"aria-hidden":`true`},W(`search`,{size:15})),s,c),{node:U(`header.topbar`,U(`div.brand`,U(`span.brand-mark`,`A`),`Archie`),r,U(`div.topbar-end`,a,U(`button.icon-btn.icon-btn-chat`,{"aria-label":`Open chat`,title:`Chat with Archie`,"aria-expanded":`false`,onclick:()=>t?.()},W(`chat`)),U(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},W(`help`)),i,U(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,r]of n)t===e?r.setAttribute(`aria-current`,`page`):r.removeAttribute(`aria-current`)},hide(e){for(let t of e)n.get(t)?.remove()}}}function Nr(){Ar(jr());let e=U(`main.main`),t=U(`aside.chat-drawer`,{"aria-label":`Chat with Archie`}),n=U(`button.icon-btn.chat-drawer-close`,{"aria-label":`Close chat`,title:`Close chat`,onclick:()=>o(!1)},W(`close`)),r=U(`div.chat-drawer-head`,U(`strong`,`Archie`),n);t.append(U(`div.chat-drawer-panel`,r,Dr()),U(`div.chat-scrim`,{onclick:()=>o(!1)}));let i=Mr(s,()=>o());B.capabilities().then(e=>i.hide(me(e?.sections,Or))).catch(()=>{});let a=U(`div.shell`,i.node,e,t);Ee(document.getElementById(`app`),a);function o(e){let n=e===void 0?!t.classList.contains(`is-open`):e;t.classList.toggle(`is-open`,n),document.body.classList.toggle(`chat-open`,n);let r=a.querySelector(`.icon-btn-chat`);r&&r.setAttribute(`aria-expanded`,String(n))}window.__archieToggleChat=o;function s(e){location.hash===`#`+e?c(e):location.hash=e}function c(t){e.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[n,r=``]=t.split(`?`,2),a=Or.find(e=>e.path===n)||Or[0];if(i.highlight(a.path),a.path===`/chat`){Ee(e),o(!0);return}let s=a.view?a.view(new URLSearchParams(r)):Pr(a);s instanceof Node?Ee(e,s):ae(s,e),o(!1)}window.addEventListener(`hashchange`,()=>c(location.hash.slice(1)||`/`)),window.addEventListener(`keydown`,e=>{e.defaultPrevented||e.key===`Escape`&&t.classList.contains(`is-open`)&&o(!1)}),c(location.hash.slice(1)||`/`)}function Pr(e){return U(`div`,U(`div.page-head`,U(`div`,U(`h1.page-title`,e.label))),U(`div.card`,U(`div.empty`,U(`div.empty-title`,`${e.label} is not built yet`),U(`div`,`This section is next up. Nothing is broken.`))))}Nr(); \ No newline at end of file diff --git a/ui/src/base/api.jsx b/ui/src/base/api.jsx index 553cc3853..e98fd9065 100644 --- a/ui/src/base/api.jsx +++ b/ui/src/base/api.jsx @@ -112,6 +112,11 @@ export const api = { configReset: (key) => request("/api/config/reset", { method: "POST", body: { key } }), logs: (params) => request("/api/logs" + qs(params)), taskLogs: (id, params) => request(`/api/tasks/${id}/logs` + qs(params)), + // A download is a navigation, not a fetch: the browser must own the + // Content-Disposition filename and stream the body to disk rather than hold + // a whole log in memory. The URL builder is the client-side contract, and + // base/log-row's sibling module keeps it beside the panel that uses it. + taskLogDownloadURL: (id, attempt) => `/api/tasks/${id}/logs/download` + (attempt == null ? "" : `?attempt=${attempt}`), captures: (limit) => request("/api/captures" + qs({ limit })), mappings: () => request("/api/mappings"), mappingCreate: (mapping) => request("/api/mappings", { method: "POST", body: mapping }), diff --git a/ui/src/tasks/task-logs.jsx b/ui/src/tasks/task-logs.jsx index 51b3b8d4f..806dba2cd 100644 --- a/ui/src/tasks/task-logs.jsx +++ b/ui/src/tasks/task-logs.jsx @@ -10,7 +10,14 @@ function LogRowNode({ entry }) { return
; } -export function TaskLogPanel({ state, onRetry }) { +// Task-log download URL. The attempt is named explicitly so a download matches +// the attempt the panel is showing rather than whatever is current by the time +// the operator clicks. +export function taskLogDownloadURL(id, attempt) { + return `/api/tasks/${id}/logs/download` + (attempt == null ? "" : `?attempt=${attempt}`); +} + +export function TaskLogPanel({ state, onRetry, taskId }) { if (state === undefined) { return
Loading attempt log…
; } @@ -22,28 +29,54 @@ export function TaskLogPanel({ state, onRetry }) {
); } + + // A reader exists in this process but the attempt has no log file. That is a + // fact about the attempt, and saying "logging was not enabled" here (which + // this panel used to do) told the operator to go and change a setting that + // was already correct. + if (state.found === false && !state.disabled) { + return ( +
+
No log recorded for this attempt
+
This attempt produced no output, or it has not started writing yet.
+
+ ); + } + + // This process cannot read task logs at all. That IS about the deployment, + // and it is the only case where the panel may say so. if (state.disabled) { return (
No persisted log for this attempt
-
Task logging is optional and was not enabled for this run.
+
This dashboard cannot read task logs. The service that owns the log files is not reporting a log reader.
); } + const entries = state.entries || []; + const download = taskId != null ? taskLogDownloadURL(taskId, state.attempt) : null; + const footer = download ? ( + Download log + ) : null; + if (!entries.length) { return (
Nothing recorded
This attempt's log file has no entries matching the current filter.
+ {footer}
); } return ( -
- {entries.map((entry, i) => ( - - ))} -
+ <> +
+ {entries.map((entry, i) => ( + + ))} +
+ {footer} + ); } diff --git a/ui/src/tasks/tasks.jsx b/ui/src/tasks/tasks.jsx index 35d6f285a..dcc172fec 100644 --- a/ui/src/tasks/tasks.jsx +++ b/ui/src/tasks/tasks.jsx @@ -359,7 +359,7 @@ function TasksApp({ query }) { {logsExpandedForTask && ( - loadTaskLogs(t.id)} /> + loadTaskLogs(t.id)} /> )} diff --git a/ui/test/api-client.test.js b/ui/test/api-client.test.js index 50112326f..63adfed89 100644 --- a/ui/test/api-client.test.js +++ b/ui/test/api-client.test.js @@ -69,6 +69,14 @@ const READS = [ // separately rather than folded into either inventory above. const STREAMS = ["chatStream"]; +// URL builders make no request at all: they hand a browser navigation to a +// route the server serves as a file download, so the browser owns the +// Content-Disposition filename and streams the body to disk. They are listed +// separately because asserting a fetch contract on them would be wrong, and +// leaving them out of this suite entirely is how an unclassified method +// slipped through before. +const URLS = ["taskLogDownloadURL"]; + let calls = []; function stubFetch(respond) { @@ -135,6 +143,19 @@ test("the chat stream posts its payload and asks for an event stream", async () assert.equal(init.body, JSON.stringify({ text: "hi" })); }); +// A URL builder must not fetch: the browser has to own the navigation for the +// server's Content-Disposition filename to apply. A fetch here would consume +// the attachment and lose its name. +test("the task-log download URL is built, not fetched", async () => { + stubFetch(() => { + throw new Error("a download URL must not be fetched by the client"); + }); + + assert.equal(api.taskLogDownloadURL(7, 2), "/api/tasks/7/logs/download?attempt=2"); + assert.equal(api.taskLogDownloadURL(7, null), "/api/tasks/7/logs/download"); + assert.equal(calls.length, 0, "building a download URL must not make a request"); +}); + test("a bodyless DELETE resolves on 204 without parsing a body", async () => { stubFetch(() => ({ ok: true, @@ -175,6 +196,7 @@ test("every api method is classified by this suite", () => { ...MUTATIONS.map(([name]) => name), ...READS.map(([name]) => name), ...STREAMS, + ...URLS, ]); const actual = Object.keys(api).filter((key) => typeof api[key] === "function"); const unclassified = actual.filter((name) => !classified.has(name)).sort(); diff --git a/ui/test/task-logs.test.js b/ui/test/task-logs.test.js index b3685ca1b..a97410851 100644 --- a/ui/test/task-logs.test.js +++ b/ui/test/task-logs.test.js @@ -1,10 +1,10 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { render, cleanup } from "@testing-library/preact"; -import { TaskLogPanel } from "../src/tasks/task-logs.jsx"; +import { TaskLogPanel, taskLogDownloadURL } from "../src/tasks/task-logs.jsx"; function renderPanel(state, opts = {}) { - const { container, unmount } = render(); + const { container, unmount } = render(); return { root: container, unmount }; } @@ -24,20 +24,37 @@ test("fetch failure renders a retry control", () => { unmount(); }); -test("disabled response (task logging not enabled) renders a placeholder, not a crash", () => { +// The panel used to answer every failed read with "Task logging is optional +// and was not enabled for this run", which was false in a deployment where +// logging is unconditional: the dashboard simply could not read the log. The +// two conditions are now stated differently, and this pins that they stay so. +test("a reader that is absent says the dashboard cannot read logs, not that logging is off", () => { const { root, unmount } = renderPanel({ disabled: true, entries: [] }); assert.match(root.textContent, /No persisted log/); + assert.doesNotMatch( + root.textContent, + /not enabled for this run/, + "this text blames a configuration setting for a process that simply cannot read logs", + ); + unmount(); +}); + +test("an attempt with a reader but no log file is not reported as disabled", () => { + const { root, unmount } = renderPanel({ found: false, entries: [], attempt: 0 }); + assert.match(root.textContent, /No log recorded for this attempt/); + assert.doesNotMatch(root.textContent, /was not enabled for this run/); unmount(); }); test("empty entries render a placeholder distinct from the disabled state", () => { - const { root, unmount } = renderPanel({ disabled: false, entries: [] }); + const { root, unmount } = renderPanel({ disabled: false, found: true, entries: [], attempt: 0 }); assert.match(root.textContent, /Nothing recorded/); unmount(); }); test("entries render one row per entry with fields visible, surfacing stage/token detail", () => { const { root, unmount } = renderPanel({ + found: true, entries: [ { time: "2026-01-01T00:00:00Z", @@ -64,3 +81,25 @@ test("entries render one row per entry with fields visible, surfacing stage/toke assert.match(root.textContent, /iteration/); unmount(); }); + +// The download is the feature the panel was missing: an operator who wants the +// log in their own tooling had no way to get it. +test("the download link points at the attempt being shown", () => { + assert.equal(taskLogDownloadURL(42, 3), "/api/tasks/42/logs/download?attempt=3"); + // No attempt yet resolved: let the server pick the task's current one. + assert.equal(taskLogDownloadURL(42, null), "/api/tasks/42/logs/download"); +}); + +test("a panel with entries offers the download for that attempt", () => { + const { root, unmount } = renderPanel({ found: true, attempt: 3, entries: [{ level: "info", msg: "hi" }] }, { taskId: 42 }); + const link = root.querySelector(".task-log-download"); + assert.ok(link, "a download control should render when the attempt has a log"); + assert.equal(link.getAttribute("href"), "/api/tasks/42/logs/download?attempt=3"); + unmount(); +}); + +test("a panel for an attempt with no log offers no download", () => { + const { root, unmount } = renderPanel({ found: false, attempt: 0, entries: [] }, { taskId: 42 }); + assert.equal(root.querySelector(".task-log-download"), null, "there is nothing to download"); + unmount(); +});