feat(eda): per-org workflow enable/disable gating bindings

A workflow-enablement control-plane resource lists, per org, the workflows
that org has disabled. A binding targeting a disabled workflow is skipped at
dispatch like an unarmed one, is refused on save, and is flagged on the
binding list; the workflows page toggles it. Bindings now carry the org_id
column they already had in storage, over the State Store wire too.

Org-owned workflow definitions are deferred to a follow-up bead: they need
the caller's org, which the access chain resolves.
This commit is contained in:
sam committed 2026-09-30 02:59:23 +10:00
1 parent 1da815f88a
commit 15e64d3de2
29 files changed
+543 -34

No files matched your search

+1 -1
View File
@@ -154,7 +154,7 @@
"url": "/dev/development/workflows/",
"title": "Workflows",
"section": "Development",
"body": "# Workflows\n\nAuthority: `docs/architecture/agent-system.md` for the lifecycle,\n`docs/prds/event-automation.md` for inputs, repository modes and profiles.\n\nWorkflow definitions are YAML stored as a control-plane resource. The State\nStore validates them and the agent compiles them, each against the step\nvocabulary it registers, so both must see the same step types.\n\n## Adding a step type\n\n1. Write the factory in `internal/domain/workflow` as a `StepType`. It decodes\n and validates its settings and returns an error for anything it cannot\n honour. The factory runs when a definition is saved and again when it is\n compiled, so a bad definition is refused on save.\n2. Register it through a provider in\n `internal/infrastructure/workflowsteps/workflowsteps.go`. That one list is\n what every process registers, which is how the validating and executing\n sides agree.\n3. An agent-driven step builds on `AgentStage`; do not start a second path to\n the agent runner.\n4. A step that needs no repository goes in `repoFreeStepTypes` in\n `definition.go`, or workflows declaring `repository: none` or `optional`\n cannot use it. A step that needs one may assume `tc.Dir` holds a worktree\n only when the workflow's repository is `required`.\n5. A step that ends the workflow sets `tc.Outcome`. A workflow that runs out of\n steps without an outcome is parked as a definition bug.\n6. Add a parse test (settings accepted and refused) and a run test with fake\n `Trees` and agent runner.\n\n## Changing the definition format\n\n- The fields a caller needs without the engine (inputs, repository, profile)\n live in `task.WorkflowInterface`, because the dashboard process must not\n import the workflow engine (`cmd/archie-ui/architecture_test.go`). Anything a\n binding or the dashboard checks goes there.\n- The YAML decoder rejects unknown keys. Existing stored definitions must keep\n parsing, so a new key is optional with a default that preserves today's\n behaviour.\n- Examples in `examples/workflows/` are parsed against the registered\n vocabulary by `TestExampleWorkflowsParse`. Add one for a new capability.\n\n## Starting a workflow from chat\n\n`task_spawn` accepts `workflow` and an `inputs` object. The gateway forwards\ninputs through the task creation contract; it does not interpret individual\nworkflows. The daemon checks inputs against the pinned `WorkflowInterface`\nbefore acquiring a container and parks invalid requests with the reason.\n"
"body": "# Workflows\n\nAuthority: `docs/architecture/agent-system.md` for the lifecycle,\n`docs/prds/event-automation.md` for inputs, repository modes and profiles.\n\nWorkflow definitions are YAML stored as a control-plane resource. The State\nStore validates them and the agent compiles them, each against the step\nvocabulary it registers, so both must see the same step types.\n\n## Adding a step type\n\n1. Write the factory in `internal/domain/workflow` as a `StepType`. It decodes\n and validates its settings and returns an error for anything it cannot\n honour. The factory runs when a definition is saved and again when it is\n compiled, so a bad definition is refused on save.\n2. Register it through a provider in\n `internal/infrastructure/workflowsteps/workflowsteps.go`. That one list is\n what every process registers, which is how the validating and executing\n sides agree.\n3. An agent-driven step builds on `AgentStage`; do not start a second path to\n the agent runner.\n4. A step that needs no repository goes in `repoFreeStepTypes` in\n `definition.go`, or workflows declaring `repository: none` or `optional`\n cannot use it. A step that needs one may assume `tc.Dir` holds a worktree\n only when the workflow's repository is `required`.\n5. A step that ends the workflow sets `tc.Outcome`. A workflow that runs out of\n steps without an outcome is parked as a definition bug.\n6. Add a parse test (settings accepted and refused) and a run test with fake\n `Trees` and agent runner.\n\n## Changing the definition format\n\n- The fields a caller needs without the engine (inputs, repository, profile)\n live in `task.WorkflowInterface`, because the dashboard process must not\n import the workflow engine (`cmd/archie-ui/architecture_test.go`). Anything a\n binding or the dashboard checks goes there.\n- The YAML decoder rejects unknown keys. Existing stored definitions must keep\n parsing, so a new key is optional with a default that preserves today's\n behaviour.\n- Examples in `examples/workflows/` are parsed against the registered\n vocabulary by `TestExampleWorkflowsParse`. Add one for a new capability.\n\n## Enabling and disabling\n\nThe `workflow-enablement` control-plane resource lists, per org, the workflows\nthat org has disabled; anything unlisted is enabled. Its readers are the\ndaemon's binding dispatch (a disabled workflow's binding is skipped like an\nunarmed one), the dashboard's binding save (refused) and binding list\n(`workflow_disabled`), and work requests. A new reader of \"may this org run\nthis workflow\" goes through `task.WorkflowEnablement.Enabled`, never a second\nlist. The dashboard acts in the default org until access resolves a caller's\nown.\n\n## Starting a workflow from chat\n\n`task_spawn` accepts `workflow` and an `inputs` object. The gateway forwards\ninputs through the task creation contract; it does not interpret individual\nworkflows. The daemon checks inputs against the pinned `WorkflowInterface`\nbefore acquiring a container and parks invalid requests with the reason.\n"
},
{
"url": "/dev/prds/01-project-management/",
+11
View File
@@ -40,6 +40,17 @@ vocabulary it registers, so both must see the same step types.
- Examples in `examples/workflows/` are parsed against the registered
vocabulary by `TestExampleWorkflowsParse`. Add one for a new capability.
## Enabling and disabling
The `workflow-enablement` control-plane resource lists, per org, the workflows
that org has disabled; anything unlisted is enabled. Its readers are the
daemon's binding dispatch (a disabled workflow's binding is skipped like an
unarmed one), the dashboard's binding save (refused) and binding list
(`workflow_disabled`), and work requests. A new reader of "may this org run
this workflow" goes through `task.WorkflowEnablement.Enabled`, never a second
list. The dashboard acts in the default org until access resolves a caller's
own.
## Starting a workflow from chat
`task_spawn` accepts `workflow` and an `inputs` object. The gateway forwards
+1
View File
@@ -1408,6 +1408,7 @@ func (b *boot) buildDaemon() {
KindWorkflows: b.kindWorkflows,
LabelWorkflows: b.labelWorkflows,
WorkflowDefinitions: b.workflowDefinitions,
WorkflowEnablement: b.controlPlane,
Playbooks: b.playbooks,
}
if identities, ok := b.stateStore.(identity.Repository); ok {
@@ -87,6 +87,11 @@ func TestRoutesWithoutAContractDegradeExplicitly(t *testing.T) {
name: "workflow registry", method: http.MethodGet, path: "/api/workflows",
want: http.StatusOK, emptyJSON: `"definitions":null`,
},
{
name: "workflow enabled toggle", method: http.MethodPut, path: "/api/workflows/implement/enabled",
body: `{"enabled":false}`,
want: http.StatusServiceUnavailable,
},
{
name: "dashboard work request", method: http.MethodPost, path: "/api/work-requests",
body: `{"repository":"acme/widget","workflow":"implement","title":"do it"}`,
+1 -1
View File
@@ -8,7 +8,7 @@ import (
// Schemas are not declared here: each Definition names its document type, and
// Definition.Descriptor derives the JSON Schema from it (internal/app/controlplane/schema.go).
func builtinDefinitions(steps workflow.StepRegistry) []Definition {
definitions := []Definition{workflowDefinition(), workflowDefinitionsDefinition(steps), personaDefinition(), scheduleDefinition(), agentProfileDefinition(), credentialBindingsDefinition()}
definitions := []Definition{workflowDefinition(), workflowDefinitionsDefinition(steps), workflowEnablementDefinition(), personaDefinition(), scheduleDefinition(), agentProfileDefinition(), credentialBindingsDefinition()}
definitions = append(definitions, modelDefinitions()...)
definitions = append(definitions, operationalDefinitions()...)
return definitions
@@ -0,0 +1,38 @@
package controlplane
import (
"context"
"encoding/json"
"github.com/samcharles93/archie-core/internal/config"
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
)
const WorkflowEnablementKind = "workflow-enablement"
func workflowEnablementDefinition() Definition {
return Definition{
Kind: WorkflowEnablementKind,
Title: "Workflow enablement",
Document: task.WorkflowEnablement{},
ApplyMode: "live",
Seed: func(config.Config) any { return task.WorkflowEnablement{Orgs: map[org.OrgID]task.OrgWorkflows{}} },
Validate: func(input []byte) error {
return validateAs(input, func(enablement task.WorkflowEnablement) error { return enablement.Validate() })
},
}
}
// WorkflowEnablement returns which workflows each org has disabled.
func (c *Client) WorkflowEnablement(ctx context.Context) (task.WorkflowEnablement, error) {
response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: WorkflowEnablementKind})
if err != nil {
return task.WorkflowEnablement{}, controlplanerpc.ClientError(err)
}
var enablement task.WorkflowEnablement
err = json.Unmarshal(response.Resource.ValueJson, &enablement)
return enablement, err
}
+13 -3
View File
@@ -2371,7 +2371,9 @@ type Binding struct {
// {"param": name} or {"value": constant} per input.
InputsJson string `protobuf:"bytes,14,opt,name=inputs_json,json=inputsJson,proto3" json:"inputs_json,omitempty"`
// repo_param names the mapped parameter holding "owner/name".
RepoParam string `protobuf:"bytes,15,opt,name=repo_param,json=repoParam,proto3" json:"repo_param,omitempty"`
RepoParam string `protobuf:"bytes,15,opt,name=repo_param,json=repoParam,proto3" json:"repo_param,omitempty"`
// org_id is the org that owns the binding; it is read-only here.
OrgId string `protobuf:"bytes,16,opt,name=org_id,json=orgId,proto3" json:"org_id,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -2504,6 +2506,13 @@ func (x *Binding) GetRepoParam() string {
return ""
}
func (x *Binding) GetOrgId() string {
if x != nil {
return x.OrgId
}
return ""
}
// Source mirrors internal/domain/source.Source.
type Source struct {
state protoimpl.MessageState `protogen:"open.v1"`
@@ -11854,7 +11863,7 @@ const file_state_v1_state_proto_rawDesc = "" +
"matchCount\x12B\n" +
"\x0flast_matched_at\x18\t \x01(\v2\x1a.google.protobuf.TimestampR\rlastMatchedAt\"(\n" +
"\x0eBindingMatcher\x12\x16\n" +
"\x06source\x18\x01 \x01(\tR\x06source\"\xd4\x03\n" +
"\x06source\x18\x01 \x01(\tR\x06source\"\xeb\x03\n" +
"\aBinding\x12\x0e\n" +
"\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" +
"\x04name\x18\x02 \x01(\tR\x04name\x122\n" +
@@ -11874,7 +11883,8 @@ const file_state_v1_state_proto_rawDesc = "" +
"\vinputs_json\x18\x0e \x01(\tR\n" +
"inputsJson\x12\x1d\n" +
"\n" +
"repo_param\x18\x0f \x01(\tR\trepoParamJ\x04\b\n" +
"repo_param\x18\x0f \x01(\tR\trepoParam\x12\x15\n" +
"\x06org_id\x18\x10 \x01(\tR\x05orgIdJ\x04\b\n" +
"\x10\vR\x06secret\"\xc4\x01\n" +
"\x06Source\x12\x12\n" +
"\x04path\x18\x01 \x01(\tR\x04path\x12\x18\n" +
+9
View File
@@ -29,6 +29,15 @@ func (d *Daemon) activeWorkflows(ctx context.Context) (workflow.WorkflowDefiniti
return collection, err
}
// workflowEnablement returns which workflows each org has disabled; with no
// source wired every workflow is enabled.
func (d *Daemon) workflowEnablement(ctx context.Context) (workflowtask.WorkflowEnablement, error) {
if d.WorkflowEnablement == nil {
return workflowtask.WorkflowEnablement{}, nil
}
return d.WorkflowEnablement.WorkflowEnablement(ctx)
}
// resolveBindingTarget checks a matched binding against the workflow it
// targets and resolves the task's repository and inputs. A non-empty reason
// means the binding does not dispatch and the reason is recorded on it; ok
+26 -9
View File
@@ -250,6 +250,12 @@ type Daemon struct {
WorkflowDefinitions interface {
WorkflowDefinitions(context.Context) (workflow.WorkflowDefinitionCollection, int64, error)
}
// WorkflowEnablement supplies which workflows each org has disabled. A
// binding targeting a workflow its org disabled does not dispatch. Nil
// means every workflow is enabled.
WorkflowEnablement interface {
WorkflowEnablement(context.Context) (workflowtask.WorkflowEnablement, error)
}
// ToolRegistry is the central tool registry, wired by the composition
// root. MCP-discovered tools and built-in tools are registered here
@@ -667,16 +673,27 @@ func (d *Daemon) dispatchBindings(ctx context.Context) {
d.Log.Warn("binding dispatch: workflow definitions unavailable", "error", err)
return
}
enablement, err := d.workflowEnablement(ctx)
if err != nil {
d.Log.Warn("binding dispatch: workflow enablement unavailable", "error", err)
return
}
for _, c := range captures {
armed, err := d.BindingDispatcher.ArmedBindingsForSource(ctx, c.Source)
if err != nil {
d.Log.Warn("armed bindings lookup", "source", c.Source, "error", err)
continue
}
for _, b := range armed {
if !b.Matcher.Matches(c.Source, c.Dispatchable()) {
continue
}
d.dispatchCapture(ctx, c, workflows, enablement)
}
}
// dispatchCapture offers one capture to every armed binding on its source. A
// disabled workflow's binding is skipped like an unarmed one, so the capture
// waits rather than recording a failure every cycle.
func (d *Daemon) dispatchCapture(ctx context.Context, c storecontract.CapturedEvent, workflows workflow.WorkflowDefinitionCollection, enablement workflowtask.WorkflowEnablement) {
armed, err := d.BindingDispatcher.ArmedBindingsForSource(ctx, c.Source)
if err != nil {
d.Log.Warn("armed bindings lookup", "source", c.Source, "error", err)
return
}
for _, b := range armed {
if b.Matcher.Matches(c.Source, c.Dispatchable()) && enablement.Enabled(b.OrgID, b.Workflow) {
d.dispatchOneBinding(ctx, b, c, workflows)
}
}
+34
View File
@@ -15,6 +15,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow"
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
@@ -422,3 +423,36 @@ func assertDispatchRecorded(t *testing.T, s *dispatchStores, bindingID string) {
t.Fatalf("binding_dispatches row missing: %v", err)
}
}
type staticEnablement struct {
value workflowtask.WorkflowEnablement
}
func (e staticEnablement) WorkflowEnablement(context.Context) (workflowtask.WorkflowEnablement, error) {
return e.value, nil
}
// A binding whose org disabled its workflow does not dispatch, and the capture
// waits: re-enabling the workflow dispatches it on the next cycle.
func TestDispatchBindingsSkipsWorkflowItsOrgDisabled(t *testing.T) {
s := openDispatchTestStore(t)
mappingID := seedMapping(t, s, "sentry", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString, Required: true})
bindingID, _ := seedArmedBinding(t, s, "sentry", mappingID)
seedCapture(t, s, "sentry", true, `{"title":"hello"}`)
stored, err := s.EdaStore.GetBinding(t.Context(), bindingID)
if err != nil {
t.Fatalf("GetBinding: %v", err)
}
d := newDispatchDaemon(t, s)
var enablement workflowtask.WorkflowEnablement
d.WorkflowEnablement = staticEnablement{enablement.SetEnabled(stored.OrgID, stored.Workflow, false)}
d.dispatchBindings(t.Context())
if tasks, _ := s.Tasks(t.Context(), 10); len(tasks) != 0 {
t.Fatalf("Tasks len = %d, want 0 while the workflow is disabled", len(tasks))
}
d.WorkflowEnablement = staticEnablement{enablement.SetEnabled(stored.OrgID, stored.Workflow, true)}
d.dispatchBindings(t.Context())
assertDispatchRecorded(t, s, bindingID)
}
+10 -5
View File
@@ -8,6 +8,8 @@ import (
"fmt"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// Status is the binding lifecycle state. Mirrors telegram's
@@ -65,11 +67,14 @@ type Binding struct {
// Inputs assigns the workflow's declared inputs, each from a mapped
// parameter or a constant; CheckWorkflow checks them when the binding is
// saved.
Inputs map[string]InputSource `json:"inputs,omitempty"`
Version int `json:"version"`
Status Status `json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Inputs map[string]InputSource `json:"inputs,omitempty"`
// OrgID is the org that owns the binding; the store sets it and a
// binding may target only a workflow that org has enabled.
OrgID org.OrgID `json:"org_id"`
Version int `json:"version"`
Status Status `json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// Validate checks a binding is well-formed before it is persisted: a
@@ -0,0 +1,60 @@
package task
import (
"fmt"
"maps"
"slices"
"strings"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// WorkflowEnablement is the workflow-enablement resource value: which
// workflows each org has turned off. A workflow is enabled for an org unless
// that org lists it, so a newly shipped or added workflow is enabled
// everywhere until an org disables it.
type WorkflowEnablement struct {
Orgs map[org.OrgID]OrgWorkflows `json:"orgs"`
}
// OrgWorkflows is one org's workflow state.
type OrgWorkflows struct {
Disabled []string `json:"disabled"`
}
// Enabled reports whether owner may run workflow.
func (e WorkflowEnablement) Enabled(owner org.OrgID, workflow string) bool {
return !slices.Contains(e.Orgs[owner].Disabled, workflow)
}
// SetEnabled returns e with workflow enabled or disabled for owner.
func (e WorkflowEnablement) SetEnabled(owner org.OrgID, workflow string, enabled bool) WorkflowEnablement {
orgs := make(map[org.OrgID]OrgWorkflows, len(e.Orgs)+1)
maps.Copy(orgs, e.Orgs)
disabled := slices.DeleteFunc(slices.Clone(orgs[owner].Disabled), func(id string) bool { return id == workflow })
if !enabled {
disabled = append(disabled, workflow)
}
orgs[owner] = OrgWorkflows{Disabled: disabled}
return WorkflowEnablement{Orgs: orgs}
}
// Validate rejects blank org or workflow IDs and a workflow listed twice.
func (e WorkflowEnablement) Validate() error {
for owner, state := range e.Orgs {
if strings.TrimSpace(string(owner)) == "" {
return fmt.Errorf("workflow enablement: org ID is required")
}
seen := make(map[string]bool, len(state.Disabled))
for _, workflow := range state.Disabled {
if strings.TrimSpace(workflow) == "" {
return fmt.Errorf("workflow enablement: org %q: workflow ID is required", owner)
}
if seen[workflow] {
return fmt.Errorf("workflow enablement: org %q lists %q twice", owner, workflow)
}
seen[workflow] = true
}
}
return nil
}
@@ -0,0 +1,58 @@
package task
import (
"testing"
"github.com/samcharles93/archie-core/internal/domain/org"
)
func TestWorkflowEnablementEnabled(t *testing.T) {
enablement := WorkflowEnablement{Orgs: map[org.OrgID]OrgWorkflows{
"acme": {Disabled: []string{"triage"}},
}}
cases := []struct {
org org.OrgID
workflow string
want bool
}{
{"acme", "triage", false},
{"acme", "implement", true},
{"other", "triage", true},
}
for _, c := range cases {
if got := enablement.Enabled(c.org, c.workflow); got != c.want {
t.Errorf("Enabled(%q, %q) = %v, want %v", c.org, c.workflow, got, c.want)
}
}
}
func TestWorkflowEnablementSetEnabledRoundTrips(t *testing.T) {
var enablement WorkflowEnablement
enablement = enablement.SetEnabled("acme", "triage", false)
enablement = enablement.SetEnabled("acme", "triage", false)
if enablement.Enabled("acme", "triage") || len(enablement.Orgs["acme"].Disabled) != 1 {
t.Fatalf("disable twice: %+v", enablement)
}
enablement = enablement.SetEnabled("acme", "triage", true)
if !enablement.Enabled("acme", "triage") {
t.Fatalf("re-enable: %+v", enablement)
}
}
func TestWorkflowEnablementValidate(t *testing.T) {
cases := map[string]struct {
enablement WorkflowEnablement
ok bool
}{
"empty": {WorkflowEnablement{}, true},
"valid": {WorkflowEnablement{Orgs: map[org.OrgID]OrgWorkflows{"acme": {Disabled: []string{"triage"}}}}, true},
"blank org": {WorkflowEnablement{Orgs: map[org.OrgID]OrgWorkflows{" ": {Disabled: []string{"triage"}}}}, false},
"blank workflow": {WorkflowEnablement{Orgs: map[org.OrgID]OrgWorkflows{"acme": {Disabled: []string{""}}}}, false},
"duplicate entry": {WorkflowEnablement{Orgs: map[org.OrgID]OrgWorkflows{"acme": {Disabled: []string{"triage", "triage"}}}}, false},
}
for name, c := range cases {
if err := c.enablement.Validate(); (err == nil) != c.ok {
t.Errorf("%s: Validate() = %v, want ok=%v", name, err, c.ok)
}
}
}
@@ -17,6 +17,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/org"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/infrastructure/bindingcipher"
@@ -317,6 +318,7 @@ func bindingValue(r postgresdb.GetBindingRow) (binding.Binding, error) {
Repo: r.Repo,
RepoParam: r.RepoParam,
Inputs: inputs,
OrgID: org.OrgID(r.OrgID),
Version: int(r.Version),
Status: binding.Status(r.Status),
CreatedAt: r.CreatedAt,
@@ -11,7 +11,7 @@ import (
)
const armedBindingsForSource = `-- name: ArmedBindingsForSource :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id
FROM bindings WHERE source = $1 AND status = 'armed' ORDER BY created_at DESC
`
@@ -30,6 +30,7 @@ type ArmedBindingsForSourceRow struct {
Filter string
Inputs string
RepoParam string
OrgID string
}
func (q *Queries) ArmedBindingsForSource(ctx context.Context, source string) ([]ArmedBindingsForSourceRow, error) {
@@ -56,6 +57,7 @@ func (q *Queries) ArmedBindingsForSource(ctx context.Context, source string) ([]
&i.Filter,
&i.Inputs,
&i.RepoParam,
&i.OrgID,
); err != nil {
return nil, err
}
@@ -177,7 +179,7 @@ func (q *Queries) EventTypesForSource(ctx context.Context, source string) ([]Eve
}
const getBinding = `-- name: GetBinding :one
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id
FROM bindings WHERE id = $1
`
@@ -196,6 +198,7 @@ type GetBindingRow struct {
Filter string
Inputs string
RepoParam string
OrgID string
}
func (q *Queries) GetBinding(ctx context.Context, id string) (GetBindingRow, error) {
@@ -216,6 +219,7 @@ func (q *Queries) GetBinding(ctx context.Context, id string) (GetBindingRow, err
&i.Filter,
&i.Inputs,
&i.RepoParam,
&i.OrgID,
)
return i, err
}
@@ -524,7 +528,7 @@ func (q *Queries) InsertToolCall(ctx context.Context, arg InsertToolCallParams)
}
const listBindings = `-- name: ListBindings :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id
FROM bindings ORDER BY created_at DESC
`
@@ -543,6 +547,7 @@ type ListBindingsRow struct {
Filter string
Inputs string
RepoParam string
OrgID string
}
func (q *Queries) ListBindings(ctx context.Context) ([]ListBindingsRow, error) {
@@ -569,6 +574,7 @@ func (q *Queries) ListBindings(ctx context.Context) ([]ListBindingsRow, error) {
&i.Filter,
&i.Inputs,
&i.RepoParam,
&i.OrgID,
); err != nil {
return nil, err
}
@@ -67,15 +67,15 @@ INSERT INTO bindings (id, name, source, mapping, filter, workflow, owner, repo,
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1, $9, $10, $11);
-- name: GetBinding :one
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id
FROM bindings WHERE id = $1;
-- name: ListBindings :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id
FROM bindings ORDER BY created_at DESC;
-- name: ArmedBindingsForSource :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id
FROM bindings WHERE source = $1 AND status = 'armed' ORDER BY created_at DESC;
-- name: UpdateBinding :execrows
+2 -2
View File
@@ -246,7 +246,7 @@ func bindingProto(b binding.Binding) *pb.Binding {
return &pb.Binding{
Id: b.ID, Name: b.Name, Matcher: &pb.BindingMatcher{Source: b.Matcher.Source},
MappingId: b.MappingID, Filter: b.Filter, Workflow: b.Workflow, Owner: b.Owner, Repo: b.Repo,
RepoParam: b.RepoParam, InputsJson: bindingInputsJSON(b.Inputs),
RepoParam: b.RepoParam, InputsJson: bindingInputsJSON(b.Inputs), OrgId: string(b.OrgID),
Version: int64(b.Version), Status: string(b.Status),
CreatedAt: timestamp(b.CreatedAt), UpdatedAt: timestamp(b.UpdatedAt),
}
@@ -263,7 +263,7 @@ func bindingValue(b *pb.Binding) binding.Binding {
return binding.Binding{
ID: b.Id, Name: b.Name, Matcher: binding.Matcher{Source: source},
MappingID: b.MappingId, Filter: b.Filter, Workflow: b.Workflow, Owner: b.Owner, Repo: b.Repo,
RepoParam: b.RepoParam, Inputs: bindingInputsValue(b.InputsJson),
RepoParam: b.RepoParam, Inputs: bindingInputsValue(b.InputsJson), OrgID: org.OrgID(b.OrgId),
Version: int(b.Version), Status: binding.Status(b.Status),
CreatedAt: timeValue(b.CreatedAt), UpdatedAt: timeValue(b.UpdatedAt),
}
+38 -1
View File
@@ -1,11 +1,13 @@
package webui
import (
"context"
"encoding/json"
"errors"
"net/http"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
)
@@ -35,6 +37,9 @@ type bindingRequest struct {
type bindingView struct {
binding.Binding
Unsigned bool `json:"unsigned"`
// WorkflowDisabled marks a binding whose org has disabled the workflow it
// targets; it does not dispatch until the workflow is enabled again.
WorkflowDisabled bool `json:"workflow_disabled"`
}
func (s *Server) handleBindingsList(w http.ResponseWriter, r *http.Request) {
@@ -54,9 +59,15 @@ func (s *Server) handleBindingsList(w http.ResponseWriter, r *http.Request) {
http.Error(w, "list bindings failed", http.StatusInternalServerError)
return
}
enablement, _, err := s.workflowEnablement(r.Context())
if err != nil {
s.Log.Error("workflow enablement", "err", err)
http.Error(w, "list bindings failed", http.StatusInternalServerError)
return
}
views := make([]bindingView, 0, len(bindings))
for _, b := range bindings {
views = append(views, bindingView{Binding: b, Unsigned: unsigned[b.Matcher.Source]})
views = append(views, bindingView{Binding: b, Unsigned: unsigned[b.Matcher.Source], WorkflowDisabled: !enablement.Enabled(b.OrgID, b.Workflow)})
}
writeJSON(w, map[string]any{"bindings": views})
}
@@ -248,6 +259,15 @@ func (s *Server) checkedBinding(w http.ResponseWriter, r *http.Request, id strin
http.Error(w, "binding: workflow not found: "+req.Workflow, http.StatusBadRequest)
return binding.Binding{}, false
}
enabled, err := s.bindingWorkflowEnabled(r.Context(), id, req.Workflow)
if err != nil {
http.Error(w, "workflow enablement unavailable", http.StatusServiceUnavailable)
return binding.Binding{}, false
}
if !enabled {
http.Error(w, "binding: workflow is disabled: "+req.Workflow, http.StatusConflict)
return binding.Binding{}, false
}
iface, err := task.ParseWorkflowInterface(entry.YAML)
if err != nil {
http.Error(w, "binding: workflow "+req.Workflow+": "+err.Error(), http.StatusBadRequest)
@@ -277,3 +297,20 @@ func (s *Server) checkedBinding(w http.ResponseWriter, r *http.Request, id strin
}
return b, true
}
// bindingWorkflowEnabled reports whether the org owning binding id (the
// default org for a binding not yet created) has workflow enabled.
func (s *Server) bindingWorkflowEnabled(ctx context.Context, id, workflow string) (bool, error) {
owner := org.DefaultOrgID
if id != "" {
existing, err := s.Bindings.GetBinding(ctx, id)
if err != nil {
return false, err
}
if existing != nil {
owner = existing.OrgID
}
}
enablement, _, err := s.workflowEnablement(ctx)
return enablement.Enabled(owner, workflow), err
}
+12 -2
View File
@@ -28,13 +28,19 @@ type controlPlaneClientStub struct {
entries []*controlpb.AuditEntry
watch grpc.ServerStreamingClient[controlpb.WatchResponse]
err error
// resources, when set, answers Query per kind and keeps what Command
// writes, falling back to query for a kind it does not hold.
resources map[string]*controlpb.Resource
}
func (f *controlPlaneClientStub) Catalog(context.Context, *controlpb.CatalogRequest, ...grpc.CallOption) (*controlpb.CatalogResponse, error) {
return &controlpb.CatalogResponse{}, f.err
}
func (f *controlPlaneClientStub) Query(context.Context, *controlpb.QueryRequest, ...grpc.CallOption) (*controlpb.QueryResponse, error) {
func (f *controlPlaneClientStub) Query(_ context.Context, request *controlpb.QueryRequest, _ ...grpc.CallOption) (*controlpb.QueryResponse, error) {
if resource, ok := f.resources[request.Kind]; ok {
return &controlpb.QueryResponse{Resource: resource}, f.err
}
return &controlpb.QueryResponse{Resource: f.query}, f.err
}
@@ -53,7 +59,11 @@ func (f *controlPlaneClientStub) Command(_ context.Context, request *controlpb.C
if f.err != nil {
return nil, f.err
}
return &controlpb.CommandResponse{Resource: &controlpb.Resource{Kind: request.Kind, Version: 2, ValueJson: request.ValueJson}}, nil
resource := &controlpb.Resource{Kind: request.Kind, Version: request.ExpectedVersion + 1, ValueJson: request.ValueJson}
if f.resources != nil {
f.resources[request.Kind] = resource
}
return &controlpb.CommandResponse{Resource: resource}, nil
}
func (f *controlPlaneClientStub) Watch(context.Context, *controlpb.WatchRequest, ...grpc.CallOption) (grpc.ServerStreamingClient[controlpb.WatchResponse], error) {
+90
View File
@@ -0,0 +1,90 @@
package webui
import (
"context"
"encoding/json"
"errors"
"net/http"
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
)
const workflowEnablementKind = "workflow-enablement"
// workflowEnablement returns which workflows each org has disabled, and the
// resource version a replacement must name.
func (s *Server) workflowEnablement(ctx context.Context) (task.WorkflowEnablement, int64, error) {
if s.ControlPlane == nil {
return task.WorkflowEnablement{}, 0, nil
}
response, err := s.ControlPlane.Query(ctx, &controlpb.QueryRequest{Kind: workflowEnablementKind})
if err != nil {
return task.WorkflowEnablement{}, 0, err
}
if response.Resource == nil {
return task.WorkflowEnablement{}, 0, errors.New("workflow enablement missing")
}
var enablement task.WorkflowEnablement
if err := json.Unmarshal(response.Resource.ValueJson, &enablement); err != nil {
return task.WorkflowEnablement{}, 0, err
}
return enablement, response.Resource.Version, nil
}
type workflowEnabledRequest struct {
Enabled bool `json:"enabled"`
}
// handleWorkflowEnabled enables or disables a workflow for the dashboard's
// org. Every dashboard caller acts in the default org until access resolves a
// caller's own.
func (s *Server) handleWorkflowEnabled(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
if s.ControlPlane == nil {
http.Error(w, "control plane unavailable", http.StatusServiceUnavailable)
return
}
var request workflowEnabledRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
id := r.PathValue("id")
found, err := s.hasWorkflowDefinition(r.Context(), id)
if err != nil {
http.Error(w, "workflow definitions unavailable", http.StatusServiceUnavailable)
return
}
if !found {
http.Error(w, "workflow not found", http.StatusNotFound)
return
}
enablement, version, err := s.workflowEnablement(r.Context())
if err != nil {
http.Error(w, "workflow enablement unavailable", http.StatusServiceUnavailable)
return
}
value, err := json.Marshal(enablement.SetEnabled(org.DefaultOrgID, id, request.Enabled))
if err != nil {
http.Error(w, "encode workflow enablement", http.StatusInternalServerError)
return
}
audit, err := webAudit()
if err != nil {
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
return
}
if _, err := s.ControlPlane.Command(r.Context(), &controlpb.CommandRequest{
Kind: workflowEnablementKind, Command: "replace", ValueJson: value,
ExpectedVersion: version, Actor: string(audit.ActorID),
Source: audit.Source, RequestId: audit.RequestID,
}); err != nil {
writeControlPlaneError(w, err)
return
}
writeJSON(w, map[string]any{"id": id, "enabled": request.Enabled})
}
@@ -0,0 +1,67 @@
package webui
import (
"encoding/json"
"net/http"
"testing"
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
)
// Disabling a workflow flags the bindings that target it and refuses new
// ones; enabling it again lifts both.
func TestWorkflowDisableFlagsAndRefusesBindings(t *testing.T) {
srv := bindingTestServer(t)
stub, ok := srv.ControlPlane.(*controlPlaneClientStub)
if !ok {
t.Fatal("binding test server has no control-plane stub")
}
stub.resources = map[string]*controlpb.Resource{
workflowEnablementKind: {Kind: workflowEnablementKind, Version: 1, ValueJson: []byte(`{"orgs":{}}`)},
}
mappingID := seedMapping(t, srv, "m")
if w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("a", "sentry", mappingID)); w.Code != http.StatusCreated {
t.Fatalf("create status = %d; body = %s", w.Code, w.Body)
}
setEnabled := func(enabled bool) {
t.Helper()
if w := doJSON(t, srv, http.MethodPut, "/api/workflows/implement/enabled", map[string]any{"enabled": enabled}); w.Code != http.StatusOK {
t.Fatalf("set enabled=%v status = %d; body = %s", enabled, w.Code, w.Body)
}
}
flagged := func() bool {
t.Helper()
w := doJSON(t, srv, http.MethodGet, "/api/bindings", nil)
var body struct {
Bindings []bindingView `json:"bindings"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || len(body.Bindings) != 1 {
t.Fatalf("list bindings: %v; body = %s", err, w.Body)
}
return body.Bindings[0].WorkflowDisabled
}
setEnabled(false)
if !flagged() {
t.Fatal("binding targeting a disabled workflow is not flagged")
}
if w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("b", "sentry", mappingID)); w.Code != http.StatusConflict {
t.Fatalf("create against disabled workflow status = %d, want %d", w.Code, http.StatusConflict)
}
setEnabled(true)
if flagged() {
t.Fatal("binding still flagged after the workflow was enabled")
}
if w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("b", "sentry", mappingID)); w.Code != http.StatusCreated {
t.Fatalf("create after enabling status = %d; body = %s", w.Code, w.Body)
}
}
func TestWorkflowEnabledRefusesUnknownWorkflow(t *testing.T) {
srv := bindingTestServer(t)
if w := doJSON(t, srv, http.MethodPut, "/api/workflows/missing/enabled", map[string]any{"enabled": false}); w.Code != http.StatusNotFound {
t.Fatalf("status = %d, want %d", w.Code, http.StatusNotFound)
}
}
+18 -1
View File
@@ -10,6 +10,7 @@ import (
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
)
@@ -106,7 +107,19 @@ func (s *Server) handleWorkRequest(w http.ResponseWriter, r *http.Request) {
writeJSON(w, map[string]any{"ok": true, "task_id": taskID})
}
// hasWorkflow reports whether workflow id is defined and enabled for the
// default org, the org every dashboard caller acts in until access resolves
// a caller's own.
func (s *Server) hasWorkflow(ctx context.Context, id string) (bool, error) {
found, err := s.hasWorkflowDefinition(ctx, id)
if err != nil || !found {
return false, err
}
enablement, _, err := s.workflowEnablement(ctx)
return enablement.Enabled(org.DefaultOrgID, id), err
}
func (s *Server) hasWorkflowDefinition(ctx context.Context, id string) (bool, error) {
_, found, err := s.workflowEntry(ctx, id)
return found, err
}
@@ -147,9 +160,13 @@ func (s *Server) workflowDefinitions(ctx context.Context) ([]task.Definition, er
if err != nil {
return nil, err
}
enablement, _, err := s.workflowEnablement(ctx)
if err != nil {
return nil, err
}
definitions := make([]task.Definition, 0, len(collection.Definitions))
for _, entry := range collection.Definitions {
definition := task.Definition{ID: entry.ID, Name: entry.ID, Origin: "database", Enabled: true, Repository: task.RepositoryRequired}
definition := task.Definition{ID: entry.ID, Name: entry.ID, Origin: "database", Enabled: enablement.Enabled(org.DefaultOrgID, entry.ID), Repository: task.RepositoryRequired}
if iface, err := task.ParseWorkflowInterface(entry.YAML); err == nil {
definition.Inputs, definition.Repository = iface.Inputs, iface.RepositoryMode()
}
+1
View File
@@ -247,6 +247,7 @@ func (s *Server) registerCoreRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/summary", s.handleSummary)
mux.HandleFunc("GET /api/setup", s.handleSetup)
mux.HandleFunc("GET /api/workflows", s.handleWorkflows)
mux.HandleFunc("PUT /api/workflows/{id}/enabled", s.handleWorkflowEnabled)
mux.HandleFunc("POST /api/work-requests", s.handleWorkRequest)
mux.HandleFunc("GET /api/skills", s.handleSkills)
mux.HandleFunc("GET /api/curators", s.handleCurators)
+2
View File
@@ -455,6 +455,8 @@ message Binding {
string inputs_json = 14;
// repo_param names the mapped parameter holding "owner/name".
string repo_param = 15;
// org_id is the org that owns the binding; it is read-only here.
string org_id = 16;
}
// Source mirrors internal/domain/source.Source.
+2 -2
View File
@@ -2,7 +2,7 @@ var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],en
`&&(e.tagName===`PRE`||e.tagName===`TEXTAREA`)&&(n=n.slice(1));let{textContent:r}=e;r!==n&&r!==n.replace(/\r\n|\r/g,`
`)&&(Ai(e,0)||bi(),e.textContent=t.children)}if(d){if(_||b||!o||f&48){let t=e.tagName.includes(`-`),i=e.namespaceURI.includes(`svg`)?`svg`:e.namespaceURI.includes(`MathML`)?`mathml`:void 0;for(let a in d)if(_&&(a.endsWith(`value`)||a===`indeterminate`)||s(a)&&!ie(a)||a[0]===`.`||t&&!ie(a)||u&&u.includes(a)){if(Di(e,a,d[a]))continue;r(e,a,null,d[a],i,n)}}else if(d.onClick)r(e,`onClick`,null,d.onClick,void 0,n);else if(f&4&&ln(d.style))for(let e in d.style)d.style[e]}let x;(x=d&&d.onVnodeBeforeMount)&&Ps(x,n,t),h&&Tr(t,null,n,`beforeMount`),((x=d&&d.onVnodeMounted)||h||l)&&us(()=>{x&&Ps(x,n,t),l&&g.enter(e),h&&Tr(t,null,n,`mounted`)},i)}return e.nextSibling},m=(e,t,r,o,s,c,u)=>{u||=!!t.dynamicChildren;let d=t.children,p=d.length,m=!1;for(let t=0;t<p;t++){let h=u?d[t]:d[t]=js(d[t]),g=h.type===ps;e?(g&&!u&&t+1<p&&js(d[t+1]).type===ps&&(l(i(e.data.slice(h.children.length)),r,a(e)),e.data=h.children),e=f(e,h,o,s,c,u)):g&&!h.children?l(h.el=i(``),r):(m||(m=!0,Ai(r,1)||bi()),n(null,h,r,null,o,s,Ci(r),c))}return e},h=(e,t,n,r,i,s)=>{let{slotScopeIds:c}=t;c&&(i=i?i.concat(c):c);let d=o(e),f=m(a(e),t,d,n,r,i,s);return f&&wi(f)&&f.data===`]`?a(t.anchor=f):(bi(),l(t.anchor=u(`]`),d,f),f)},g=(e,t,r,i,s,l)=>{if(Mi(e,t)||bi(),t.el=null,l){let t=_(e);for(;;){let n=a(e);if(n&&n!==t)c(n);else break}}let u=a(e),d=o(e);return c(e),n(null,t,d,u,r,i,Ci(d),s),r&&(r.vnode.el=t.el,Co(r,t.el)),u},_=(e,t=`[`,n=`]`)=>{let r=0;for(;e;)if(e=a(e),e&&wi(e)&&(e.data===t&&r++,e.data===n)){if(r===0)return a(e);r--}return e},v=(e,t,n)=>{let r=t.parentNode;r&&r.replaceChild(e,t);let i=n;for(;i;)i.vnode.el===t&&(i.vnode.el=i.subTree.el=e),i=i.parent},y=e=>e.nodeType===1&&e.tagName===`TEMPLATE`;return[d,f]}var Ei=new Set([`src`,`srcset`,`href`,`poster`]);function Di(e,t,n){return Ei.has(t)?e.getAttribute(t)===(n==null?null:`${n}`):!1}var Oi=`data-allow-mismatch`,ki={0:`text`,1:`children`,2:`class`,3:`style`,4:`attribute`};function Ai(e,t){if(t===0||t===1)for(;e&&!e.hasAttribute(Oi);)e=e.parentElement;return ji(e&&e.getAttribute(Oi),t)}function ji(e,t){if(e==null)return!1;if(e===``)return!0;{let n=e.split(`,`);return t===0&&n.includes(`children`)?!0:n.includes(ki[t])}}function Mi(e,t){return Ai(e.parentElement,1)||Ni(e)||Pi(t)}function Ni(e){return e.nodeType===1&&ji(e.getAttribute(Oi),1)}function Pi({props:e}){let t=e&&e[Oi];return typeof t==`string`&&ji(t,1)}var Fi=_e().requestIdleCallback||(e=>setTimeout(e,1)),Ii=_e().cancelIdleCallback||(e=>clearTimeout(e)),Li=(e=1e4)=>t=>{let n=Fi(t,{timeout:e});return()=>Ii(n)};function Ri(e){let{top:t,left:n,bottom:r,right:i}=e.getBoundingClientRect(),{innerHeight:a,innerWidth:o}=window;return(t>0&&t<a||r>0&&r<a)&&(n>0&&n<o||i>0&&i<o)}var zi=e=>(t,n)=>{let r=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){r.disconnect(),t();break}},e);return n(e=>{if(e instanceof Element){if(Ri(e))return t(),r.disconnect(),!1;r.observe(e)}}),()=>r.disconnect()},Bi=e=>t=>{if(e){let n=matchMedia(e);if(n.matches)t();else return n.addEventListener(`change`,t,{once:!0}),()=>n.removeEventListener(`change`,t)}},Vi=(e=[])=>(t,n)=>{y(e)&&(e=[e]);let r=!1,i=e=>{r||(r=!0,a(),t(),e.target.dispatchEvent(new e.constructor(e.type,e)))},a=()=>{n(t=>{for(let n of e)t.removeEventListener(n,i)})};return n(t=>{for(let n of e)t.addEventListener(n,i,{once:!0})}),a};function Hi(e,t){if(wi(e)&&e.data===`[`){let n=1,r=e.nextSibling;for(;r;){if(r.nodeType===1){if(t(r)===!1)break}else if(wi(r)){if(r.data===`]`){if(--n===0)break}else r.data===`[`&&n++}r=r.nextSibling}}else t(e)}var Ui=e=>!!e.type.__asyncLoader;function Wi(e){v(e)&&(e={loader:e});let{loader:t,loadingComponent:n,errorComponent:r,delay:i=200,hydrate:a,timeout:o,suspensible:s=!0,onError:c}=e,l=null,u,d=0,f=()=>(d++,l=null,p()),p=()=>{let e;return l||(e=l=t().catch(e=>{if(e=e instanceof Error?e:Error(String(e)),c)return new Promise((t,n)=>{c(e,()=>t(f()),()=>n(e),d+1)});throw e}).then(t=>e!==l&&l?l:(t&&(t.__esModule||t[Symbol.toStringTag]===`Module`)&&(t=t.default),u=t,t)))};return j({name:`AsyncComponentWrapper`,__asyncLoader:p,__asyncHydrate(e,t,n){let r=e.isConnected,i=!1;(t.bu||=[]).push(()=>i=!0);let o=()=>{i||!e.parentNode||r&&!e.isConnected||n()},s=a?()=>{let n=a(o,t=>Hi(e,t));n&&(t.bum||=[]).push(n)}:o;u?s():p().then(()=>!t.isUnmounted&&s())},get __asyncResolved(){return u},setup(){let e=Rs;if(pi(e),u)return()=>Gi(u,e);let t=t=>{l=null,Zn(t,e,13,!r)};if(s&&e.suspense||Gs)return p().then(t=>()=>Gi(t,e)).catch(e=>(t(e),()=>r?z(r,{error:e}):null));let a=D(!1),c=D(),d=D(!!i),f,m;return ca(()=>{f!=null&&clearTimeout(f),m!=null&&clearTimeout(m)}),i&&(m=setTimeout(()=>{e.isUnmounted||(d.value=!1)},i)),o!=null&&(f=setTimeout(()=>{if(!e.isUnmounted&&!a.value&&!c.value){let e=Error(`Async component timed out after ${o}ms.`);t(e),c.value=e}},o)),p().then(()=>{e.isUnmounted||(a.value=!0,e.parent&&Ki(e.parent.vnode)&&e.parent.update())}).catch(n=>{if(e.isUnmounted){l=null;return}t(n),c.value=n}),()=>{if(a.value&&u)return Gi(u,e);if(c.value&&r)return z(r,{error:c.value});if(n&& Line truncated
`))),e[Kl]=Ul(i);let a=r||i.props&&i.props.type===`number`;ul(e,t?`change`:`input`,t=>{t.target.composing||e[Kl](Jl(e.value,n,a))}),(n||a)&&ul(e,`change`,()=>{e.value=Jl(e.value,n,a)}),t||(ul(e,`compositionstart`,Wl),ul(e,`compositionend`,Gl),ul(e,`change`,Gl))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[ql];delete e[ql],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[Kl](Jl(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[Kl]=Ul(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?me(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},Xl={deep:!0,created(e,t,n){e[Kl]=Ul(n),ul(e,`change`,()=>{let t=e._modelValue,n=nu(e),r=e.checked,i=e[Kl];if(p(t)){let e=Ne(t,n),a=e!==-1;if(r&&!a)i(t.concat(n));else if(!r&&a){let n=[...t];n.splice(e,1),i(n)}}else if(h(t)){let e=new Set(t);r?e.add(n):e.delete(n),i(e)}else i(ru(e,r))})},mounted:Zl,beforeUpdate(e,t,n){e[Kl]=Ul(n),Zl(e,t,n)}};function Zl(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(p(t))i=Ne(t,r.props.value)>-1;else if(h(t))i=t.has(r.props.value);else{if(t===n)return;i=Me(t,ru(e,!0))}e.checked!==i&&(e.checked=i)}var Ql={created(e,{value:t},n){e.checked=Me(t,n.props.value),e[Kl]=Ul(n),ul(e,`change`,()=>{e[Kl](nu(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[Kl]=Ul(r),t!==n&&(e.checked=Me(t,r.props.value))}},$l={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,ul(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?me(nu(e)):nu(e)),r=e.multiple,i=r?h(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?p(i)?t.slice():t:i];try{e[Kl](i)}finally{or(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[Kl]=Ul(r)},mounted(e,{value:t}){tu(e,t)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[Kl]=Ul(n)},updated(e,{value:t}){let n=e._pendingValue;e._pendingValue=void 0,(!n||n[0]!==e.multiple||!eu(t,n[1],n[0]))&&tu(e,t)}};function eu(e,t,n){if(!n||p(e))return Me(e,t);if(h(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function tu(e,t){let n=e.multiple,r=p(t);if(!n||r||h(t)){for(let i=0,a=e.options.length;i<a;i++){let a=e.options[i],o=nu(a);if(n){if(r){let e=typeof o;a.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(o)):Ne(t,o)>-1}else a.selected=t.has(o)}else if(Me(nu(a),t)){e.selectedIndex!==i&&(e.selectedIndex=i);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function nu(e){return`_value`in e?e._value:e.value}function ru(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var iu={created(e,t,n){ou(e,t,n,null,`created`)},mounted(e,t,n){ou(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){ou(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){ou(e,t,n,r,`updated`)}};function au(e,t){switch(e){case`SELECT`:return $l;case`TEXTAREA`:return Yl;default:switch(t){case`checkbox`:return Xl;case`radio`:return Ql;default:return Yl}}}function ou(e,t,n,r,i){let a=au(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function su(){Yl.getSSRProps=({value:e})=>({value:e}),Ql.getSSRProps=({value:e},t)=>{if(t.props&&Me(t.props.value,e))return{checked:!0}},Xl.getSSRProps=({value:e},t)=>{if(p(e)){if(t.props&&Ne(e,t.props.value)>-1)return{checked:!0}}else if(h(e)){if(t.props&&e.has(t.props.value))return{checked:!0}}else if(e)return{checked:!0}},iu.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=au(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var cu=[`ctrl`,`shift`,`alt`,`meta`],lu={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>cu.some(n=>e[`${n}Key`]&&!t.includes(n))},uu=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=lu[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},du={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},fu=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`);return n[r]||(n[r]=(n=>{if(!(`key`in n))return;let r=le(n.key);if(t.some(e=>e===r||du[e]===r))return e(n)}))},pu=l({patchProp:Sl},Sc),mu,hu=!1;function gu(){return mu||=Uo(pu)}function _u(){return mu=hu?mu:Wo(pu),hu=!0,mu}var vu=((...e)=>{gu().render(...e)}),yu=((...e)=>{_u().hydrate(...e)}),bu=((...e)=>{let t=gu().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=Cu(e);if(!r)return;let i=t._component;!v(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent=``);let a=n(r,!1,Su(r));return r instanceof Element&&(r.removeAttribute(`v-cloak`),r.setAttribute(`data-v-app`,``)),a},t}),xu=(( Line truncated
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var Kp;function qp(e){Kp=e}var Jp=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function Yp(e){let t=e instanceof Jp?e.status:void 0,n=e instanceof Error&&e.message?e.message:`Action failed`;return t===401?{kind:`session-expired`,message:n}:t!==void 0&&t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function Xp(e,t){let n=await fetch(e,t);if(Kp?.(n.status===401),!n.ok)throw new Jp(await Gp(n),n.status);return n}async function Zp(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=Up,parse:a=!0}=t,o={Accept:`application/json`},s={method:n,headers:o,signal:AbortSignal.timeout(i)};n!==`GET`&&(o[`Content-Type`]=`application/json`,o[`X-Archie-CSRF`]=`1`),r!==void 0&&(s.body=JSON.stringify(r));let c=await Xp(e,s);return a?await c.json():void 0}var q={health:()=>Zp(`/health/detailed`),summary:()=>Zp(`/api/summary`),tasks:()=>Zp(`/api/tasks`),taskMeta:()=>Zp(`/api/task-meta`),task:e=>Zp(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>Zp(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>Zp(`/api/tasks/${encodeURIComponent(e)}/changes`+Wp(t)),taskDebug:(e,t)=>Zp(`/api/tasks/${encodeURIComponent(e)}/debug`+Wp(t)),taskAction:(e,t)=>Zp(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t}}),setup:()=>Zp(`/api/setup`),capabilities:()=>Zp(`/api/capabilities`),workflows:()=>Zp(`/api/workflows`),workRequest:e=>Zp(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>Zp(`/api/skills`),channels:()=>Zp(`/api/channels`),curators:()=>Zp(`/api/curators`),channelReload:e=>Zp(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>Zp(`/api/config`),logs:e=>Zp(`/api/logs`+Wp(e)),taskLogs:(e,t)=>Zp(`/api/tasks/${encodeURIComponent(e)}/logs`+Wp(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),version:()=>Zp(`/api/version`),updateSnapshot:()=>Zp(`/api/chat/update`),updateInstall:e=>Zp(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:9e5}),captures:e=>Zp(`/api/captures`+Wp({limit:e})),eventTypes:()=>Zp(`/api/event-types`),eventTypeCreate:e=>Zp(`/api/event-types`,{method:`POST`,body:e}),eventTypeUpdate:(e,t)=>Zp(`/api/event-types/${encodeURIComponent(e)}`,{method:`PUT`,body:t}),eventTypeDelete:e=>Zp(`/api/event-types/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappings:()=>Zp(`/api/mappings`),mappingCreate:e=>Zp(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>Zp(`/api/mappings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),mappingDelete:e=>Zp(`/api/mappings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>Zp(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>Zp(`/api/bindings`),bindingCreate:e=>Zp(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>Zp(`/api/bindings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),bindingDelete:e=>Zp(`/api/bindings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>Zp(`/api/bindings/${encodeURIComponent(e)}/approve`,{method:`POST`}),sources:()=>Zp(`/api/sources`),sourceCreate:e=>Zp(`/api/sources`,{method:`POST`,body:{path:e}}),sourceSigning:(e,t)=>Zp(`/api/sources/${encodeURIComponent(e)}/signing`,{method:`POST`,body:{signed:t}}),sourceApproveUnsigned:e=>Zp(`/api/sources/${encodeURIComponent(e)}/approve-unsigned`,{method:`POST`}),sourceSecret:e=>Zp(`/api/sources/${encodeURIComponent(e)}/secret`,{method:`POST`}),chatSessions:()=>Zp(`/api/chat/sessions`),chatMessages:e=>Zp(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>Zp(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>Zp(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>Zp(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:Hp(),text:t,page:location.pathname+location.search||`/`}}),chatPersona:(e,t)=>Zp(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatDangerous:()=>Zp(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>Zp(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>Zp(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,t={})=>Xp(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t.signal})};function Qp(e,t,n=``,r=!1){let i=new EventSource(Vp(n,r));return i.onopen=()=>t(`live`),i.onerror=()=>t(zp(i.readyState)),i.onmessage=t=>{try{e(JSON.parse(t.data),t.lastEventId)}catch{}},()=>i.close()}var $p=`archie.web.chat.channel`;function em(){let e=localStorage.getItem($p);return e||(e=Hp(),localStorage.setItem($p,e)),e}var tm=/(?:^|\s)\/([^\s]*)$/,nm=/(?:^|\s)\/[^\s]*$/,rm=8;function im(e,t,n){let r=t.slice(0,n).match(tm);if(!r)return[];let i=r[1].toLowerCas Line truncated
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var Kp;function qp(e){Kp=e}var Jp=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function Yp(e){let t=e instanceof Jp?e.status:void 0,n=e instanceof Error&&e.message?e.message:`Action failed`;return t===401?{kind:`session-expired`,message:n}:t!==void 0&&t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function Xp(e,t){let n=await fetch(e,t);if(Kp?.(n.status===401),!n.ok)throw new Jp(await Gp(n),n.status);return n}async function Zp(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=Up,parse:a=!0}=t,o={Accept:`application/json`},s={method:n,headers:o,signal:AbortSignal.timeout(i)};n!==`GET`&&(o[`Content-Type`]=`application/json`,o[`X-Archie-CSRF`]=`1`),r!==void 0&&(s.body=JSON.stringify(r));let c=await Xp(e,s);return a?await c.json():void 0}var q={health:()=>Zp(`/health/detailed`),summary:()=>Zp(`/api/summary`),tasks:()=>Zp(`/api/tasks`),taskMeta:()=>Zp(`/api/task-meta`),task:e=>Zp(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>Zp(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>Zp(`/api/tasks/${encodeURIComponent(e)}/changes`+Wp(t)),taskDebug:(e,t)=>Zp(`/api/tasks/${encodeURIComponent(e)}/debug`+Wp(t)),taskAction:(e,t)=>Zp(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t}}),setup:()=>Zp(`/api/setup`),capabilities:()=>Zp(`/api/capabilities`),workflows:()=>Zp(`/api/workflows`),workflowEnabled:(e,t)=>Zp(`/api/workflows/${encodeURIComponent(e)}/enabled`,{method:`PUT`,body:{enabled:t},parse:!1}),workRequest:e=>Zp(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>Zp(`/api/skills`),channels:()=>Zp(`/api/channels`),curators:()=>Zp(`/api/curators`),channelReload:e=>Zp(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>Zp(`/api/config`),logs:e=>Zp(`/api/logs`+Wp(e)),taskLogs:(e,t)=>Zp(`/api/tasks/${encodeURIComponent(e)}/logs`+Wp(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),version:()=>Zp(`/api/version`),updateSnapshot:()=>Zp(`/api/chat/update`),updateInstall:e=>Zp(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:9e5}),captures:e=>Zp(`/api/captures`+Wp({limit:e})),eventTypes:()=>Zp(`/api/event-types`),eventTypeCreate:e=>Zp(`/api/event-types`,{method:`POST`,body:e}),eventTypeUpdate:(e,t)=>Zp(`/api/event-types/${encodeURIComponent(e)}`,{method:`PUT`,body:t}),eventTypeDelete:e=>Zp(`/api/event-types/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappings:()=>Zp(`/api/mappings`),mappingCreate:e=>Zp(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>Zp(`/api/mappings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),mappingDelete:e=>Zp(`/api/mappings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>Zp(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>Zp(`/api/bindings`),bindingCreate:e=>Zp(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>Zp(`/api/bindings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),bindingDelete:e=>Zp(`/api/bindings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>Zp(`/api/bindings/${encodeURIComponent(e)}/approve`,{method:`POST`}),sources:()=>Zp(`/api/sources`),sourceCreate:e=>Zp(`/api/sources`,{method:`POST`,body:{path:e}}),sourceSigning:(e,t)=>Zp(`/api/sources/${encodeURIComponent(e)}/signing`,{method:`POST`,body:{signed:t}}),sourceApproveUnsigned:e=>Zp(`/api/sources/${encodeURIComponent(e)}/approve-unsigned`,{method:`POST`}),sourceSecret:e=>Zp(`/api/sources/${encodeURIComponent(e)}/secret`,{method:`POST`}),chatSessions:()=>Zp(`/api/chat/sessions`),chatMessages:e=>Zp(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>Zp(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>Zp(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>Zp(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:Hp(),text:t,page:location.pathname+location.search||`/`}}),chatPersona:(e,t)=>Zp(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatDangerous:()=>Zp(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>Zp(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>Zp(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,t={})=>Xp(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t.signal})};function Qp(e,t,n=``,r=!1){let i=new EventSource(Vp(n,r));return i.onopen=()=>t(`live`),i.onerror=()=>t(zp(i.readyState)),i.onmessage=t=>{try{e(JSON.parse(t.data),t.lastEventId)}catch{}},()=>i.close()}var $p=`archie.web.chat.channel`;function em(){let e=localStorage.getItem($p);return e||(e=Hp(),localStorage.setItem($p,e)),e}var tm=/(?:^|\s)\/([^\sLine truncated
`);u=r.pop()||``;for(let e of r){let t=e.split(`
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(pm.value=n.session_id),n.type===`delta`&&(o+=n.text,vm.value=vm.value?{...vm.value,text:o}:null),(n.type===`tool`||n.type===`navigate`)&&(a=[...a,n],vm.value=vm.value?{...vm.value,tools:a}:null),n.type===`done`&&(s=!0,o||=n.text||``),n.type===`error`)throw Error(n.text)}if(t)break}if(!s)throw Error(`chat stream ended before completion`);mm.value=[...mm.value,{from:`assistant`,text:o,tool_calls:a}],vm.value=null,gm.value=`Ready`,await Nm()}catch(e){let t=e;t.name===`AbortError`&&!c?(vm.value={text:`Turn stopped.`,tools:a,isError:!1,turn:r,isRetry:i},gm.value=`Stopped`):(vm.value={text:`Unable to complete that turn: ${t.message||t}`,tools:a,isError:!0,turn:r?cm(r):void 0,isRetry:i},gm.value=`Error — retry available`)}finally{clearTimeout(l),jm=null,_m.value=!1}}function Km(){gm.value=`Stopping…`,pm.value&&q.chatCancel(pm.value).catch(()=>{}),Mm()}function qm(){ia(()=>{Nm().catch(e=>{gm.value=e.message||`Chat unavailable`})}),ca(()=>{Mm()})}var Jm=[`aria-label`,`title`,`aria-expanded`,`aria-controls`],Ym=j({__name:`ChatFab`,props:{open:{type:Boolean}},emits:[`toggle`],setup(e,{emit:t}){let n=t;function r(e){return K(`col-start-1 row-start-1 grid place-items-center transition-[opacity,transform] duration-[140ms]`,e?`opacity-100`:`-rotate-45 scale-[0.7] opacity-0`)}return(t,i)=>(F(),I(`button`,{type:`button`,class:`relative z-10 grid size-14 cursor-pointer place-items-center rounded-full border border-border-strong bg-secondary text-primary shadow-[var(--shadow-md)] transition-transform duration-[140ms] hover:-translate-y-px focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:translate-y-0`,"aria-label":e.open?`Close chat`:`Chat with Archie`,title:e.open?`Close chat`:`Chat with Archie`,"aria-expanded":e.open,"aria-controls":O(um),onClick:i[0]||=e=>n(`toggle`)},[R(`span`,{"aria-hidden":`true`,class:T(r(!e.open))},[z(O(Hd),{size:22})],2),R(`span`,{"aria-hidden":`true`,class:T(r(e.open))},[z(O(uf),{size:22})],2)],8,Jm))}});function Xm(e){return typeof e==`string`?`'${e}'`:new eh().serialize(e)}var Zm=` _-,;:!?.'"()[]{}@*/\\&#%\`^+<=>|~$0123456789abcdefghijklmnopqrstuvwxyz`,Qm=(function(){let e=new Uint8Array(128);for(let t=0;t<69;t++)e[Zm.charCodeAt(t)]=t+1;for(let t=65;t<=90;t++)e[t]=e[t+32];return e})();function $m(e,t){if(e===t)return 0;let n=Math.min(e.length,t.length),r=0;for(let i=0;i<n;i++){let n=e.charCodeAt(i),a=t.charCodeAt(i);if(n===a)continue;let o=n<128&&Qm[n]?Qm[n]:n+128,s=a<128&&Qm[a]?Qm[a]:a+128;if(o!==s)return o<s?-1:1;r===0&&(r=n>a?-1:1)}return e.length===t.length?r:e.length<t.length?-1:1}var eh=(function(){class e{#e=new Map;compare(e,t){let n=typeof e,r=typeof t;return n===`string`&&r===`string`?$m(e,t):n===`number`&&r===`number`?e-t:$m(this.serialize(e,!0),this.serialize(t,!0))}serialize(e,t){if(e===null)return`null`;switch(typeof e){case`string`:return t?e:`'${e}'`;case`bigint`:return`${e}n`;case`object`:return this.$object(e);case`function`:return this.$function(e)}return String(e)}serializeObject(e){let t=Object.prototype.toString.call(e);if(t!==`[object Object]`)return this.serializeBuiltInType(t.length<10?`unknown:${t}`:t.slice(8,-1),e);let n=e.constructor,r=n===Object||n===void 0?``:n.name;if(r!==``&&globalThis[r]===n)return this.serializeBuiltInType(r,e);if(`toJSON`in e&&typeof e.toJSON==`function`){let t=e.toJSON();return r+(typeof t==`object`&&t?this.$object(t):`(${this.serialize(t)})`)}let i=Object.keys(e).sort($m),a=`${r}{`;for(let t=0;t<i.length;t++){let n=i[t];a+=`${n}:${this.serialize(e[n])}`,t<i.length-1&&(a+=`,`)}return a+`}`}serializeBuiltInType(e,t){let n=this[`$`+e];if(n)return n.call(this,t);if(typeof t.entries==`function`)return this.serializeObjectEntries(e,t.entries());throw Error(`Cannot serialize ${e}`)}serializeObjectEntries(e,t){let n=Array.from(t).sort((e,t)=>this.compare(e[0],t[0])),r=`${e}{`;for(let e=0;e<n.length;e++){let[t,i]=n[e];r+=`${this.serialize(t,!0)}:${this.serialize(i)}`,e<n.length-1&&(r+=`,`)}return r+`}`}$object(e){let t=this.#e.get(e);return t===void 0&&(this.#e.set(e,`#${this.#e.size}`),t=this.serializeObject(e),this.#e.set(e,t)),t}$function(e){let t=Function.prototype.toString.call(e);return t.slice(-15)===`[native code] }`?`${e.name||``}()[native]`:`${e.name}(${e.length})${t.replace(/\s*\n\s*/g,``)}`}$Array(e){let t=`[`;for(let n=0;n<e.length;n++)t+=this.serialize(e[n]),n<e.length-1&&(t+=`,`);return t+`]`}$Date(e){try{return`Date(${e.toISOString()})`}catch{return`Date(null)`}}$ArrayBuffer(e){return`ArrayBuffer[${new Uint8Array(e).join(`,`)}]`}$Set(e){return`Set${this.$Array(Array.from(e).sort((e,t)=>this.compare(e,t)))}`}$Map(e){return this.serializeObjectEntries(`Map`,e.entries())}}for(let t of[`Error`,`RegExp`,`URL`])e.prototype[`$`+t]=function(e){return`${t}(${e})`};for(let t of[`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`Int16Array`,`Uint16Array`,`Int32Array`,`Uint32Array`,`Float32Array`,`Float64Array`] Line truncated
@@ -17,4 +17,4 @@ Defaulting to \`null\`.`),null)}function BS(e){return RS(e)&&!Number.isNaN(e)&&e
`)}),a=null):a=[];continue}if(a){a.push(c);continue}let l=WE(c),u=e+1<n.length?WE(n[e+1]):null;if(l&&u&&GE(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=WE(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>HE(e)),rows:r.map(e=>e.map(e=>HE(e)))});continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.push({kind:`h${d[1].length}`,inline:HE(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.tag!==e)&&(s(),i={tag:e,items:[]}),i.items.push((f||p)[1]);continue}if(c.startsWith(`>`)){o(),s(),t.push({kind:`blockquote`,inline:HE(c.replace(/^>\s?/,``))});continue}r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
`)}),t}function WE(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 GE(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var KE={class:`[overflow-wrap:anywhere]`},qE={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},JE={class:`font-mono text-[0.85em]`},YE={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},XE={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},ZE={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},QE={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},$E={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},eD={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},tD={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},nD={key:8,class:`mb-2.5 last:mb-0`},rD=j({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=U(()=>UE(t.text));return(e,t)=>(F(),I(`div`,KE,[(F(!0),I(P,null,M(n.value,(e,t)=>(F(),I(P,{key:t},[e.kind===`pre`?(F(),I(`pre`,qE,[R(`code`,JE,E(e.code),1)])):e.kind===`table`?(F(),I(`table`,YE,[R(`thead`,null,[R(`tr`,null,[(F(!0),I(P,null,M(e.head,(e,t)=>(F(),I(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[z(BE,{inline:e},null,8,[`inline`])]))),128))])]),R(`tbody`,null,[(F(!0),I(P,null,M(e.rows,(e,t)=>(F(),I(`tr`,{key:t},[(F(!0),I(P,null,M(e,(e,t)=>(F(),I(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[z(BE,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(F(),I(`blockquote`,XE,[z(BE,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(F(),I(`h1`,ZE,[z(BE,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(F(),I(`h2`,QE,[z(BE,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(F(),I(`h3`,$E,[z(BE,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(F(),I(`ul`,eD,[(F(!0),I(P,null,M(e.items,(e,t)=>(F(),I(`li`,{key:t},[z(BE,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(F(),I(`ol`,tD,[(F(!0),I(P,null,M(e.items,(e,t)=>(F(),I(`li`,{key:t},[z(BE,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(F(),I(`p`,nD,[z(BE,{inline:e.inline},null,8,[`inline`])])):V(``,!0)],64))),128))]))}}),iD={class:`truncate`},aD=j({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=ha(`RouterLink`);return F(),L(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:k(()=>[z(O(xd),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),R(`span`,iD,E(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),oD={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},sD={class:`font-semibold text-foreground`},cD={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},lD=j({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=U(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=U(()=>t.tool.parameters||t.tool.Parameters||``),i=U(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=U(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||(t.streaming?i.value?`failed`:`running…`:`done`));return(t,o)=>e.tool.path?(F(),L(aD,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(F(),I(`div`,oD,[z(O(lf),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),R(`span`,sD,E(n.value),1),r.value?(F(),I(`code`,cD,E(r.value),1)):V(``,!0),R(`span`,{class:T(O(K)(`text-fg-muted`,i.value&&`text-danger`))},E(a.value),3)]))}}),uD={key:0,class:`mb-2 grid gap-0.5 text-xs`},dD={key:2,class:`whitespace-pre-wrap`},fD=j({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(F(),I(`div`,{class:T([`flex`,e.assistant?`justify-start`:`justify-end`])},[R(`div`,{class:T(O(K)(`max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]`,e.assistant?`bg-muted`:`bg-primary/15`))},[e.assistant&&e.tools.length?(F(),I(`div`,uD,[(F(!0),I(P,null,M(e.tools,(t,n)=>(F(),L(lD,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):V(``,!0),e.assistant?(F(),L(rD,{key:1,text:e.text},null,8,[`text`])):(F(),I(`div`,dD,E(e.text),1)),N(t.$slots,`default`)],2)],2))}}),pD={class:`w-full self-center justify-self-center py-6 text-center`},mD={class:`grid gap-2`},hD=[`onClick`],gD=j({__name:`ChatEmptyState`,emits:[`prompt`],setup(e,{emit:t}){let n=t,r=[`Summarise active tasks`,`Show running agents`,`Check system status`];return(e,t)=>(F(),I(`div`,pD,[t[0]||=R(`span`,{"aria-hidden":`true`,class:`mx-auto mb-3 grid size-9 placLine truncated
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>DM?`${n.slice(0,DM).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var kM=[`title`],AM=j({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=U(()=>aM(n.event)),a=U(()=>OM(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=U(()=>n.event.at?hj(n.event.at):`—`);return(e,t)=>(F(),L(O(wM),{class:T(i.value>0?`cursor-pointer`:``),role:i.value>0?`link`:void 0,tabindex:i.value>0?0:void 0,title:i.value>0?`Open task details`:void 0,onClick:o,onKeydown:[fu(uu(o,[`prevent`]),[`enter`]),fu(uu(o,[`prevent`]),[`space`])]},{default:k(()=>[z(O($),{class:`font-medium`},{default:k(()=>[B(E(n.event.kind||n.event.type||`event`),1)]),_:1}),z(O($),{class:`font-mono`},{default:k(()=>[B(E(i.value>0?`#${i.value}`:`—`),1)]),_:1}),z(O($),{class:`w-[55%] max-w-0`},{default:k(()=>[R(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},E(a.value.text),9,kM)]),_:1}),z(O($),null,{default:k(()=>[B(E(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}});function jM(e,t){return`${e}:${t??0}`}function MM(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=jM(OM(n).text,r),a=t[t.length-1];if(a&&a.key===i){a.count+=1,a.events.push(n);continue}t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var NM={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},PM={class:`max-h-[28rem] overflow-y-auto`},FM=[`aria-expanded`,`aria-label`,`onClick`],IM=[`title`],LM=j({__name:`LiveActivityCard`,setup(e){let t=zD(),{activity:n,streamKind:r,streamState:i}=od(CA()),a=rn(new Set),o=U(()=>MM(n.value));function s(e){a.has(e)?a.delete(e):a.add(e)}function c(e){return a.has(e.key)}function l(e){return OM(e.representative)}function u(e){return e.representative.at?hj(e.representative.at):`—`}function d(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(F(),L(O(cj),null,{default:k(()=>[z(O(pj),null,{default:k(()=>[z(O(mj),null,{default:k(()=>[...t[0]||=[B(`Live activity`,-1)]]),_:1}),z(O(lj),null,{default:k(()=>[z(O(aj),{variant:O(r)},{default:k(()=>[B(E(O(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),z(O(uj),null,{default:k(()=>[R(`div`,NM,[R(`div`,PM,[z(O(SM),null,{default:k(()=>[z(O(EM),{class:`sticky top-0 z-10 bg-card`},{default:k(()=>[z(O(wM),null,{default:k(()=>[z(O(TM),null,{default:k(()=>[...t[1]||=[B(`Event`,-1)]]),_:1}),z(O(TM),null,{default:k(()=>[...t[2]||=[B(`Task`,-1)]]),_:1}),z(O(TM),null,{default:k(()=>[...t[3]||=[B(`Detail`,-1)]]),_:1}),z(O(TM),null,{default:k(()=>[...t[4]||=[B(`When`,-1)]]),_:1})]),_:1})]),_:1}),z(O(CM),null,{default:k(()=>[O(n).length?V(``,!0):(F(),L(O(wM),{key:0},{default:k(()=>[z(O($),{colspan:`4`},{default:k(()=>[z(O(ZA),null,{default:k(()=>[z(O(ej),null,{default:k(()=>[z(O(rj),null,{default:k(()=>[...t[5]||=[B(`Waiting for activity`,-1)]]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})),O(n).length?(F(!0),I(P,{key:1},M(o.value,e=>(F(),I(P,{key:e.key},[e.count===1?(F(),L(AM,{key:0,event:e.representative,onOpen:d},null,8,[`event`])):(F(),I(P,{key:1},[z(O(wM),{class:T(e.taskID>0?`cursor-pointer`:``),role:e.taskID>0?`link`:void 0,tabindex:e.taskID>0?0:void 0,title:e.taskID>0?`Open task details`:void 0,onClick:t=>e.taskID>0&&d(e.taskID),onKeydown:[fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`enter`]),fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`space`])]},{default:k(()=>[z(O($),{class:`font-medium`},{default:k(()=>[R(`button`,{type:`button`,class:`inline-flex items-center gap-1 rounded hover:opacity-80`,"aria-expanded":c(e),"aria-label":`${c(e)?`Hide`:`Show`} ${e.count} ${e.label} events`,onClick:uu(t=>s(e.key),[`stop`])},[c(e)?(F(),L(O(Td),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`})):(F(),L(O(Ed),{key:1,class:`size-3.5 shrink-0 text-fg-subtle`})),B(` `+E(e.label)+` `,1),z(O(aj),{variant:`idle`},{default:k(()=>[B(`×`+E(e.count),1)]),_:2},1024)],8,FM)]),_:2},1024),z(O($),{class:`font-mono`},{default:k(()=>[B(E(e.taskID>0?`#${e.taskID}`:`—`),1)]),_:2},1024),z(O($),{class:`w-[55%] max-w-0`},{default:k(()=>[R(`span`,{class:`block truncate`,title:l(e).truncated?l(e).full:void 0},E(l(e).text),9,IM)]),_:2},1024),z(O($),null,{default:k(()=>[B(E(u(e)),1)]),_:2},1024)]),_:2},1032,[`class`,`role`,`tabindex`,`title`,`onClick`,`onKeydown`]),c(e)?(F(!0),I(P,{key:0},M(e.events,(t,n)=>(F(),L(AM,{key:`${e.key}:${n}`,event:t,onOpen:d},null,8,[`event`]))),128)):V(``,!0)],64))],64))),128)):V(``,!0)]),_:1})]),_:1})])])]),_:1})]),_:1}))}}),RM=j({__name:`Alert`,props:{class:{type:[Boolean,null,String,Object,Array]},variant:{}},setup(e){let t=e;return(n,r)=>(F(),I(`div`,{"data-slot":`alert`,class:T(O(K)(O(HM)({variant:e.variant}),t.class)),role:`alert`},[N(n.$slots,`default`)],2))}}),zM=j({__name:`AlertAction`,props:{class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e;return(e,n)=>(F(),I(`div`,{"data-slot":`alert-action`,class:T(O(K)(`absolute top-2 right-2`,t.class))},[N(e.$slots,`default`)],2))}}),BM=j( Line truncated
`)){let e=n.indexOf(`:`);if(e<=0)continue;let r=n.slice(0,e).trim();r&&(t[r]=n.slice(e+1).trim())}return t}function zN(e,t){if(!e.event_type)return{label:`Unidentified`,identified:!1};let n=t.find(t=>t.id===e.event_type);return{label:n?n.name:`Deleted type`,identified:!0}}function BN(e,t){if(!e)return`No event type`;let n=t.find(t=>t.id===e);return n?`${n.source} / ${n.name}`:`Deleted type`}function VN(e){let t=[...(e.headers||[]).map(e=>`${e.name} = ${e.value}`),...(e.payload||[]).map(e=>e.op===`present`?`${e.path} present`:`${e.path} = ${e.value??``}`)];return t.length?t.join(` · `):`any event`}function HN(e){return{headers:(e.headers||[]).filter(e=>e.name.trim()!==``).map(e=>({name:e.name.trim(),value:e.value})),payload:(e.payload||[]).filter(e=>e.path.trim()!==``).map(e=>e.op===`present`?{path:e.path.trim(),op:e.op}:{path:e.path.trim(),op:e.op,value:e.value??``})}}var UN=D([]),WN=D([]),GN=D(!0),KN=D(null),qN=D(null),JN=D(!1),YN=D(null);async function XN(){try{let e=await q.eventTypes();GN.value=e.enabled!==!1,UN.value=e.event_types||[],WN.value=e.proposals||[],KN.value=null}catch(e){KN.value=e.message||String(e)}}function ZN(e){return{headers:(e.headers||[]).map(e=>({...e})),payload:(e.payload||[]).map(e=>({...e}))}}function QN(e){YN.value=null,qN.value=e}function $N(e){let t=sP.value.find(t=>String(t.id)===e.sample_id);QN({mode:`proposal`,id:null,source:e.source,name:``,rule:ZN(e.rule),headersText:``,body:t?.body||``,exampleHeaders:e.headers||{}})}function eP(e=``){QN({mode:`paste`,id:null,source:e,name:``,rule:{headers:[],payload:[]},headersText:``,body:``,exampleHeaders:{}})}function tP(e){QN({mode:`edit`,id:e.id,source:e.source,name:e.name,rule:ZN(e.rule),headersText:``,body:``,exampleHeaders:{}})}function nP(){qN.value=null}async function rP(){let e=qN.value;if(e){JN.value=!0;try{if(e.mode===`edit`&&e.id)await q.eventTypeUpdate(e.id,{name:e.name,rule:HN(e.rule)});else{let t=e.mode===`paste`?RN(e.headersText):e.exampleHeaders;await q.eventTypeCreate({source:e.source,name:e.name,rule:e.mode===`paste`?void 0:HN(e.rule),example:{headers:t,body:e.body}})}qN.value=null,await XN()}catch(e){YN.value=e.message||String(e)}finally{JN.value=!1}}}var iP=D(null);async function aP(){let e=iP.value;if(iP.value=null,e)try{await q.eventTypeDelete(e.id),await XN()}catch(e){KN.value=e.message||String(e)}}var oP=100,sP=D([]),cP=D(!0),lP=D(null),uP=D(!0),dP=D(null);async function fP(){try{let e=await q.captures(oP);cP.value=e.enabled!==!1,sP.value=e.captures||[],lP.value=null}catch(e){lP.value=e.message||String(e)}finally{uP.value=!1}}function pP(e){let t=sP.value.find(t=>t.id===e);return t&&(dP.value=t),!!t}function mP(){sP.value.length&&(dP.value=sP.value[0])}function hP(){wA(`captures`,()=>{fP(),XN()})}var gP=j({__name:`Tabs`,props:{defaultValue:{},orientation:{},dir:{},activationMode:{},modelValue:{},unmountOnHide:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},emits:[`update:modelValue`],setup(e,{emit:t}){let n=e,r=t,i=bg(Pw(n,`class`),r);return(e,t)=>(F(),L(O(VC),H({"data-slot":`tabs`,"data-orientation":O(i).orientation||`horizontal`},O(i),{class:O(K)(`gap-2 group/tabs flex data-horizontal:flex-col`,n.class)}),{default:k(t=>[N(e.$slots,`default`,we(Os(t)))]),_:3},16,[`data-orientation`,`class`]))}}),_P=j({__name:`TabsContent`,props:{value:{},forceMount:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=Pw(t,`class`);return(e,r)=>(F(),L(O(WC),H({"data-slot":`tabs-content`,class:O(K)(`text-sm flex-1 outline-none`,t.class)},O(n)),{default:k(()=>[N(e.$slots,`default`)]),_:3},16,[`class`]))}}),vP=j({__name:`TabsList`,props:{loop:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]},variant:{default:`default`}},setup(e){let t=e,n=Pw(t,`class`,`variant`);return(r,i)=>(F(),L(O(GC),H({"data-slot":`tabs-list`,"data-variant":e.variant},O(n),{class:O(K)(O(bP)({variant:e.variant}),t.class)}),{default:k(()=>[N(r.$slots,`default`)]),_:3},16,[`data-variant`,`class`]))}}),yP=j({__name:`TabsTrigger`,props:{value:{},disabled:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=yg(Pw(t,`class`));return(e,r)=>(F(),L(O(KC),H({"data-slot":`tabs-trigger`,class:O(K)(`gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg:not([class*=size-])]:size-4 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabledLine truncated
`)){let e=n.indexOf(`:`);if(e<=0)continue;let r=n.slice(0,e).trim();r&&(t[r]=n.slice(e+1).trim())}return t}function zN(e,t){if(!e.event_type)return{label:`Unidentified`,identified:!1};let n=t.find(t=>t.id===e.event_type);return{label:n?n.name:`Deleted type`,identified:!0}}function BN(e,t){if(!e)return`No event type`;let n=t.find(t=>t.id===e);return n?`${n.source} / ${n.name}`:`Deleted type`}function VN(e){let t=[...(e.headers||[]).map(e=>`${e.name} = ${e.value}`),...(e.payload||[]).map(e=>e.op===`present`?`${e.path} present`:`${e.path} = ${e.value??``}`)];return t.length?t.join(` · `):`any event`}function HN(e){return{headers:(e.headers||[]).filter(e=>e.name.trim()!==``).map(e=>({name:e.name.trim(),value:e.value})),payload:(e.payload||[]).filter(e=>e.path.trim()!==``).map(e=>e.op===`present`?{path:e.path.trim(),op:e.op}:{path:e.path.trim(),op:e.op,value:e.value??``})}}var UN=D([]),WN=D([]),GN=D(!0),KN=D(null),qN=D(null),JN=D(!1),YN=D(null);async function XN(){try{let e=await q.eventTypes();GN.value=e.enabled!==!1,UN.value=e.event_types||[],WN.value=e.proposals||[],KN.value=null}catch(e){KN.value=e.message||String(e)}}function ZN(e){return{headers:(e.headers||[]).map(e=>({...e})),payload:(e.payload||[]).map(e=>({...e}))}}function QN(e){YN.value=null,qN.value=e}function $N(e){let t=sP.value.find(t=>String(t.id)===e.sample_id);QN({mode:`proposal`,id:null,source:e.source,name:``,rule:ZN(e.rule),headersText:``,body:t?.body||``,exampleHeaders:e.headers||{}})}function eP(e=``){QN({mode:`paste`,id:null,source:e,name:``,rule:{headers:[],payload:[]},headersText:``,body:``,exampleHeaders:{}})}function tP(e){QN({mode:`edit`,id:e.id,source:e.source,name:e.name,rule:ZN(e.rule),headersText:``,body:``,exampleHeaders:{}})}function nP(){qN.value=null}async function rP(){let e=qN.value;if(e){JN.value=!0;try{if(e.mode===`edit`&&e.id)await q.eventTypeUpdate(e.id,{name:e.name,rule:HN(e.rule)});else{let t=e.mode===`paste`?RN(e.headersText):e.exampleHeaders;await q.eventTypeCreate({source:e.source,name:e.name,rule:e.mode===`paste`?void 0:HN(e.rule),example:{headers:t,body:e.body}})}qN.value=null,await XN()}catch(e){YN.value=e.message||String(e)}finally{JN.value=!1}}}var iP=D(null);async function aP(){let e=iP.value;if(iP.value=null,e)try{await q.eventTypeDelete(e.id),await XN()}catch(e){KN.value=e.message||String(e)}}var oP=100,sP=D([]),cP=D(!0),lP=D(null),uP=D(!0),dP=D(null);async function fP(){try{let e=await q.captures(oP);cP.value=e.enabled!==!1,sP.value=e.captures||[],lP.value=null}catch(e){lP.value=e.message||String(e)}finally{uP.value=!1}}function pP(e){let t=sP.value.find(t=>t.id===e);return t&&(dP.value=t),!!t}function mP(){sP.value.length&&(dP.value=sP.value[0])}function hP(){wA(`captures`,()=>{fP(),XN()})}var gP=j({__name:`Tabs`,props:{defaultValue:{},orientation:{},dir:{},activationMode:{},modelValue:{},unmountOnHide:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},emits:[`update:modelValue`],setup(e,{emit:t}){let n=e,r=t,i=bg(Pw(n,`class`),r);return(e,t)=>(F(),L(O(VC),H({"data-slot":`tabs`,"data-orientation":O(i).orientation||`horizontal`},O(i),{class:O(K)(`gap-2 group/tabs flex data-horizontal:flex-col`,n.class)}),{default:k(t=>[N(e.$slots,`default`,we(Os(t)))]),_:3},16,[`data-orientation`,`class`]))}}),_P=j({__name:`TabsContent`,props:{value:{},forceMount:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=Pw(t,`class`);return(e,r)=>(F(),L(O(WC),H({"data-slot":`tabs-content`,class:O(K)(`text-sm flex-1 outline-none`,t.class)},O(n)),{default:k(()=>[N(e.$slots,`default`)]),_:3},16,[`class`]))}}),vP=j({__name:`TabsList`,props:{loop:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]},variant:{default:`default`}},setup(e){let t=e,n=Pw(t,`class`,`variant`);return(r,i)=>(F(),L(O(GC),H({"data-slot":`tabs-list`,"data-variant":e.variant},O(n),{class:O(K)(O(bP)({variant:e.variant}),t.class)}),{default:k(()=>[N(r.$slots,`default`)]),_:3},16,[`data-variant`,`class`]))}}),yP=j({__name:`TabsTrigger`,props:{value:{},disabled:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=yg(Pw(t,`class`));return(e,r)=>(F(),L(O(KC),H({"data-slot":`tabs-trigger`,class:O(K)(`gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg:not([class*=size-])]:size-4 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabledLine truncated
+6 -1
View File
@@ -46,7 +46,12 @@ const emit = defineEmits<{
>
{{ props.binding.filter || "—" }}
</TableCell>
<TableCell>{{ props.binding.workflow || "—" }}</TableCell>
<TableCell>
<div class="flex items-center gap-2">
{{ props.binding.workflow || "—" }}
<Badge v-if="props.binding.workflow_disabled" variant="warn">Disabled</Badge>
</div>
</TableCell>
<TableCell class="font-mono text-fg-muted">{{
repoPin(props.binding)
}}</TableCell>
+2
View File
@@ -29,6 +29,8 @@ export interface Binding {
status?: string;
version?: number;
unsigned?: boolean;
/** Set when the binding's org has disabled the workflow it targets. */
workflow_disabled?: boolean;
}
/** One workflow input's assignment on the wire. */
+6
View File
@@ -158,6 +158,12 @@ export const api = {
setup: <T = unknown>() => request<T>("/api/setup"),
capabilities: <T = unknown>() => request<T>("/api/capabilities"),
workflows: <T = unknown>() => request<T>("/api/workflows"),
workflowEnabled: (id: string, enabled: boolean) =>
request<void>(`/api/workflows/${encodeURIComponent(id)}/enabled`, {
method: "PUT",
body: { enabled },
parse: false,
}),
workRequest: <T = unknown>(workRequest: Payload) =>
request<T>("/api/work-requests", { method: "POST", body: workRequest }),
skills: <T = unknown>() => request<T>("/api/skills"),
+16
View File
@@ -5,6 +5,7 @@ import { Plus, RotateCcw } from "@lucide/vue";
import PageHeader from "@/base/PageHeader.vue";
import { Button } from "@/components/ui/button";
import { StatusPill } from "@/components/ui/status-pill";
import { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { api } from "@/lib/api";
import { delivered } from "@/lib/delivered";
@@ -72,6 +73,17 @@ watchEffect(() => {
if (!selected.value && rows.value.length) selected.value = rows.value[0]!.id;
});
const current = computed(() => rows.value.find((r) => r.id === selected.value));
// A workflow the server does not list yet (a new, unsaved one) has no
// enabled state to show.
const enabled = computed(() => data.value.definitions?.find((d) => d.id === selected.value)?.enabled);
async function setEnabled(value: boolean) {
try {
await api.workflowEnabled(selected.value, value);
await load();
} catch (err) {
error.value = String((err as Error).message || err);
}
}
const stages = computed(() => (data.value.stages ?? []).filter((s) => s.workflow === selected.value));
const workflowRuns = computed(() => runs.value.filter((t) => t.workflow === selected.value));
const tab = ref("definition");
@@ -135,6 +147,10 @@ const rate = (deliveredRuns = 0, total = 0) => (total ? deliveredRuns / total :
<h2 class="font-mono text-[15px] font-medium">{{ selected }}</h2>
<StatusPill v-if="current?.origin">{{ current.origin }}</StatusPill>
<span v-if="current" class="ml-auto text-xs text-fg-subtle">{{ current.runs || 0 }} runs</span>
<label v-if="enabled !== undefined" class="flex items-center gap-2 text-xs text-fg-muted">
Enabled
<Switch :model-value="enabled" aria-label="Workflow enabled" @update:model-value="setEnabled" />
</label>
</header>
<Tabs v-model="tab">
<TabsList>