Feat/operator alerts (#1635)

* feat(state): durable operator alerts owned by the State Store

Alerts dedup on org+kind+subject, resolve themselves when a condition
clears, and are raised, resolved, dismissed and listed through the state
contract. Task transitions raise needs-human and failed alerts in the same
transaction; the store checks service health and prunes closed alerts.
Each raise and resolve queues a webhook delivery whose attempts are kept.

* feat(notify): deliver operator alerts to the webhook; raise config and release alerts

notify.webhook now receives raised and resolved alerts above a severity
threshold with HMAC-signed payloads, bounded retry and every attempt recorded
on the alert. archied raises model alias, provider and credential-binding
alerts from the effective configuration, an update alert from the release
channel, and a credential-rejected alert from the egress resolver. The
dashboard API lists and dismisses the caller's org's alerts.

* feat(ui): alert bell in the top bar and webhook alert settings

The bell lists the org's open alerts by severity with dismiss and a link per
alert, and refreshes from the event stream. The task settings page gains the
webhook severity threshold and signing secret. ui/dist rebuilt.
This commit is contained in:
sam authored and GitHub committed 2026-10-12 03:30:46 +11:00
1 parent f34f60f9c7
commit 8a3ba32c5a
43 files changed
+4671 -465

No files matched your search

+6 -4
View File
@@ -246,12 +246,14 @@ listen = "127.0.0.1:8484"
# [memory]
# engine = "builtin" # "builtin" is the only engine implemented so far
# Notifications for human-in-the-loop moments
# (approval requests, gate failures, parked tasks).
# Archie POSTs a JSON payload to the webhook
# wire it to n8n, email, Slack, or any HTTP endpoint.
# Operator alerts (parked tasks, failed runs, unhealthy services, missing
# credentials) are listed in the dashboard. Archie also POSTs each raised and
# resolved alert as JSON to the webhook: wire it to n8n, email, Slack, or any
# HTTP endpoint. Failed deliveries are retried and recorded on the alert.
[notify]
# webhook = "https://n8n.example.com/webhook/archie"
# min_severity = "warning" # info, warning or action: the lowest severity delivered
# secret = {engine = "env", key = "ARCHIE_NOTIFY_SECRET"} # signs X-Archie-Signature (HMAC-SHA256)
[budgets]
max_steps = 60
+349
View File
@@ -0,0 +1,349 @@
package archied
import (
"context"
"fmt"
"maps"
"net/http"
"slices"
"strings"
"sync"
"time"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/alert"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/infrastructure/alertwebhook"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
"github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog"
"github.com/samcharles93/archie-core/internal/releaseupdate"
)
const (
// deliveryInterval is how often due webhook deliveries are claimed.
deliveryInterval = 15 * time.Second
// releaseCheckInterval is how often GitHub is asked for a newer release.
releaseCheckInterval = 6 * time.Hour
// alertCallTimeout bounds one check's calls to the State Store.
alertCallTimeout = 20 * time.Second
// credentialReportEvery is how long an unchanged credential state goes
// unreported, so the egress path does not call the State Store per request.
credentialReportEvery = 10 * time.Minute
)
// alertChecks raises the alerts that have no transition to hang on: the
// daemon's configuration and the release channel. Each check lists what it
// owns, so alerts from before a restart are still cleared once fixed.
type alertChecks struct {
store alert.Store
log func(msg string, args ...any)
cfg func() config.Config
// catalog is the models the providers currently offer.
catalog func() modelcatalog.Snapshot
// release is the newest release the update channel offers.
release func(context.Context) (releaseupdate.Snapshot, error)
}
func (c alertChecks) reporter() alert.Reporter {
return alert.Reporter{Raiser: c.store, By: "archied"}
}
// sync makes the open alerts of kind in orgID match active: it raises each
// input and resolves the alerts, snoozed or open, whose condition cleared.
func (c alertChecks) sync(ctx context.Context, orgID org.OrgID, kind string, active []alert.Input) {
reporter := c.reporter()
subjects := make([]string, 0, len(active))
for _, in := range active {
reporter.Raise(ctx, in)
subjects = append(subjects, in.Subject)
}
existing, err := c.store.ListAlerts(ctx, orgID, alert.Filter{States: []alert.State{alert.StateOpen, alert.StateDismissed}, Limit: 500})
if err != nil {
c.log("alerts not checked", "kind", kind, "err", err)
return
}
for _, a := range existing {
if a.Kind == kind && a.Condition && !slices.Contains(subjects, a.Subject) {
reporter.Resolve(ctx, a.Key)
}
}
}
// checkConfig raises the alerts the effective configuration implies: a
// missing or dangling model alias, and providers and granted services with no
// usable credential.
func (c alertChecks) checkConfig(ctx context.Context) {
cfg := c.cfg()
c.sync(ctx, org.DefaultOrgID, alert.KindModelAlias, modelAliasAlerts(cfg.Models, c.catalog()))
c.sync(ctx, org.DefaultOrgID, alert.KindProviderNoKey, providerAlerts(cfg.Providers))
unbound := unboundAlerts(cfg)
for _, orgID := range credentialOrgs(cfg) {
c.sync(ctx, orgID, alert.KindToolNoBinding, unbound[orgID])
}
}
func modelAliasAlerts(aliases map[string]string, catalog modelcatalog.Snapshot) []alert.Input {
var out []alert.Input
input := func(alias, title, body string) alert.Input {
return alert.Input{
Org: org.DefaultOrgID, Kind: alert.KindModelAlias, Subject: "alias:" + alias,
Severity: alert.SeverityAction, Condition: true, Title: title, Body: body, Link: "/settings/models",
}
}
if strings.TrimSpace(aliases[config.DefaultModelAlias]) == "" {
out = append(out, input(config.DefaultModelAlias, "No default model alias is set",
"Agent steps and chat use the default alias when none is named. Point it at a model in model settings."))
}
for _, alias := range slices.Sorted(maps.Keys(aliases)) {
providerID, modelID, ok := strings.Cut(aliases[alias], "/")
if !ok {
continue
}
offered := catalogModels(catalog, providerID)
// A provider the catalogue does not list is a credential problem, not
// a retired model.
if len(offered) > 0 && !slices.Contains(offered, modelID) {
out = append(out, input(alias, fmt.Sprintf("Model alias %q points at a model that no longer exists", alias),
fmt.Sprintf("The %s provider no longer offers the model this alias names. Choose another in model settings.", providerID)))
}
}
return out
}
func catalogModels(catalog modelcatalog.Snapshot, providerID string) []string {
for _, provider := range catalog.Providers {
if provider.ID == providerID {
ids := make([]string, len(provider.Models))
for i, model := range provider.Models {
ids[i] = model.ID
}
return ids
}
}
return nil
}
func providerAlerts(providers map[string]config.Provider) []alert.Input {
var out []alert.Input
for _, name := range slices.Sorted(maps.Keys(providers)) {
if !providers[name].Disabled {
continue
}
out = append(out, alert.Input{
Org: org.DefaultOrgID, Kind: alert.KindProviderNoKey, Subject: "provider:" + name,
Severity: alert.SeverityAction, Condition: true,
Title: fmt.Sprintf("Provider %q has no usable credential", name),
Body: "Its API key could not be resolved, so models on this provider cannot run. Check its credential in credential bindings.",
Link: "/settings/credential-bindings",
})
}
return out
}
// credentialOrgs are the orgs whose identities are granted credentials, the
// instance org always among them.
func credentialOrgs(cfg config.Config) []org.OrgID {
orgs := []org.OrgID{org.DefaultOrgID}
for _, name := range append([]string{""}, identityNames(cfg)...) {
orgName, _ := cfg.CredentialAccess(name)
if id := org.OrgID(credentialOrg(orgName)); !slices.Contains(orgs, id) {
orgs = append(orgs, id)
}
}
return orgs
}
func identityNames(cfg config.Config) []string {
names := make([]string, 0, len(cfg.Identities))
for _, id := range cfg.Identities {
names = append(names, id.Name)
}
return names
}
func credentialOrg(name string) string {
if name == "" {
return string(org.DefaultOrgID)
}
return name
}
// unboundAlerts are the granted services with no credential binding in the
// granting identity's org, by org. A model provider needs no binding of its
// own here: its key is the provider's.
func unboundAlerts(cfg config.Config) map[org.OrgID][]alert.Input {
out := map[org.OrgID][]alert.Input{}
seen := map[alert.Key]bool{}
for _, name := range append([]string{""}, identityNames(cfg)...) {
orgName, granted := cfg.CredentialAccess(name)
orgID := org.OrgID(credentialOrg(orgName))
bound := cfg.Containers.BoundCredentials(orgName, granted, granted)
for _, service := range granted {
key := alert.Key{Org: orgID, Kind: alert.KindToolNoBinding, Subject: "service:" + service}
if _, ok := cfg.Providers[service]; ok || bound[service].Service != "" || seen[key] {
continue
}
seen[key] = true
out[orgID] = append(out[orgID], alert.Input{
Key: key, Severity: alert.SeverityAction, Condition: true,
Title: fmt.Sprintf("%q is granted but has no credential binding", service),
Body: "Runs that use this service cannot authenticate. Bind a credential to it.",
Link: "/settings/credential-bindings",
})
}
}
return out
}
// checkRelease raises an info alert while the update channel offers a newer
// release. A failed check changes nothing: the next one decides.
func (c alertChecks) checkRelease(ctx context.Context) {
snapshot, err := c.release(ctx)
if err != nil {
c.log("release check failed", "err", err)
return
}
var active []alert.Input
if available := snapshot.Available(); len(available) > 0 {
parts := make([]string, len(available))
for i, component := range available {
parts[i] = fmt.Sprintf("%s %s", component.Label, component.Available)
}
active = append(active, alert.Input{
Org: org.DefaultOrgID, Kind: alert.KindReleaseAvailable, Subject: "release",
Severity: alert.SeverityInfo, Condition: true,
Title: "A newer release is available", Body: "Available: " + strings.Join(parts, ", ") + ".",
Link: "/settings/status",
})
}
c.sync(ctx, org.DefaultOrgID, alert.KindReleaseAvailable, active)
}
// every runs fn now and then each interval until ctx ends.
func every(ctx context.Context, interval time.Duration, fn func(context.Context)) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
callCtx, cancel := context.WithTimeout(ctx, alertCallTimeout)
fn(callCtx)
cancel()
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}
// startAlerts starts the daemon's alert checks and the webhook delivery loop.
// The State Store being away costs the checks a tick, nothing else.
func (b *boot) startAlerts(ctx context.Context) {
client, ok := b.stateStore.(alert.Store)
if !ok {
return
}
reader := controlplanerpc.NewRPCClient(b.controlPlaneRPC)
catalog := controlplanerpc.UpdateService(reader, "").Catalog
checks := alertChecks{
store: client, log: b.log.Warn, cfg: b.cfgHolder.Get, catalog: b.catalogState,
release: func(ctx context.Context) (releaseupdate.Snapshot, error) { return catalog.Check(ctx) },
}
b.alertChecks = &checks
go every(ctx, releaseCheckInterval, checks.checkRelease)
go every(ctx, deliveryInterval, b.deliverAlerts(client))
checks.checkConfig(ctx)
}
// recheckAlerts re-evaluates the configuration alerts after the configuration
// changed. It never blocks the change that caused it.
func (b *boot) recheckAlerts(ctx context.Context) {
checks := b.alertChecks
if checks == nil {
return
}
go func() {
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), alertCallTimeout)
defer cancel()
checks.checkConfig(ctx)
}()
}
// deliverAlerts sends due webhook deliveries. A delivery the webhook is not
// configured for, or whose alert is below the severity threshold, is closed
// as skipped; one that fails is retried by the store on its schedule.
func (b *boot) deliverAlerts(store alert.Deliverer) func(context.Context) {
client := &http.Client{Timeout: 15 * time.Second}
return func(ctx context.Context) {
due, err := store.ClaimAlertDeliveries(ctx, 20)
if err != nil {
b.log.Warn("alert deliveries not claimed", "err", err)
return
}
notify := b.cfgHolder.Get().Notify
for _, d := range due {
outcome := alert.Outcome{DeliveryID: d.ID}
threshold := alert.Severity(notify.MinSeverity)
if !threshold.Valid() {
threshold = alert.SeverityWarning
}
if notify.Webhook == "" || d.Alert.Severity.Rank() < threshold.Rank() {
outcome.Skipped = true
} else {
secret := ""
if notify.Secret != (config.SecretRef{}) {
secret, err = b.secrets.Resolve(notify.Secret)
}
if err != nil {
outcome.Error = "notify secret could not be resolved"
} else {
outcome = alertwebhook.Send(ctx, client, notify.Webhook, secret, d)
}
}
if err := store.RecordAlertAttempt(ctx, outcome); err != nil {
b.log.Warn("alert delivery not recorded", "delivery", d.ID, "err", err)
}
}
}
}
// credentialWatch raises an alert when a bound credential cannot be resolved
// and clears it once it can. The egress path calls observe per request, so an
// unchanged state is reported at most every credentialReportEvery.
type credentialWatch struct {
reporter alert.Reporter
mu sync.Mutex
last map[alert.Key]credentialState
}
type credentialState struct {
rejected bool
at time.Time
}
func (w *credentialWatch) observe(ctx context.Context, orgName, service string, rejected bool) {
if w == nil {
return
}
key := alert.Key{Org: org.OrgID(credentialOrg(orgName)), Kind: alert.KindCredentialInvalid, Subject: "service:" + service}
w.mu.Lock()
if w.last == nil {
w.last = map[alert.Key]credentialState{}
}
previous, known := w.last[key]
if known && previous.rejected == rejected && time.Since(previous.at) < credentialReportEvery {
w.mu.Unlock()
return
}
w.last[key] = credentialState{rejected: rejected, at: time.Now()}
w.mu.Unlock()
go func() {
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), alertCallTimeout)
defer cancel()
w.reporter.Sync(ctx, rejected, alert.Input{
Key: key, Severity: alert.SeverityAction, Condition: true,
Title: fmt.Sprintf("The credential bound to %q is not working", service),
Body: "Its secret could not be resolved, so runs that use this service cannot authenticate. Check the binding.",
Link: "/settings/credential-bindings",
})
}()
}
+13
View File
@@ -32,6 +32,7 @@ import (
"github.com/samcharles93/archie-core/internal/daemon"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/agent"
"github.com/samcharles93/archie-core/internal/domain/alert"
"github.com/samcharles93/archie-core/internal/domain/applystatus"
"github.com/samcharles93/archie-core/internal/domain/health"
"github.com/samcharles93/archie-core/internal/domain/identity"
@@ -201,6 +202,13 @@ type boot struct {
// signal path rather than inventing a new one.
shutdown context.CancelFunc
// alertChecks re-evaluates the configuration alerts when the configuration
// changes. Nil until the daemon's run loop starts them.
alertChecks *alertChecks
// credentialWatch reports bound credentials that stop resolving. Nil
// when the State Store has no alert surface.
credentialWatch *credentialWatch
cleanups []func()
}
@@ -270,6 +278,9 @@ func (b *boot) openStateStoreAdapter(ctx context.Context) error {
return err
}
b.stateStore = client
if alerts, ok := b.stateStore.(alert.Store); ok {
b.credentialWatch = &credentialWatch{reporter: alert.Reporter{Raiser: alerts, Log: b.log, By: "archied"}}
}
b.taskModels = client
b.controlPlaneRPC = client.ControlPlane()
b.controlPlane = controlplane.NewRPCClient(b.controlPlaneRPC)
@@ -680,6 +691,7 @@ func (b *boot) publishConfig(ctx context.Context, cfg config.Config) {
// The daemon owns the published configuration view.
if b.processName != applystatus.Gateway {
b.publishConfigSnapshot(ctx)
b.recheckAlerts(ctx)
}
}
@@ -785,6 +797,7 @@ func (b *boot) runLoop(ctx context.Context, once bool) error {
b.log.Info("archied running", "repos", len(b.cfg.Repos), "poll", b.cfg.PollInterval.Std().String(), "label", b.cfg.Label)
b.startDrainMonitor(ctx)
b.startWatchdog(ctx)
b.startAlerts(ctx)
if err := b.d.Run(ctx); err != nil && ctx.Err() == nil {
b.log.Error("daemon exited", "err", err)
return err
+1 -1
View File
@@ -58,7 +58,7 @@ func (b *boot) setupKitLauncher(ctx context.Context) {
// container logs in with, against the live grants and bindings; a setup
// session's token resolves through the session grants instead.
b.sessionGrants = &sessionGrants{}
resolver := runCredentialResolver{runs: b.stateStoreGrants.Client, sessions: b.sessionGrants, models: b.taskModels, config: b.cfgHolder, secrets: b.secrets}
resolver := runCredentialResolver{runs: b.stateStoreGrants.Client, sessions: b.sessionGrants, models: b.taskModels, config: b.cfgHolder, secrets: b.secrets, credentials: b.credentialWatch}
// Without a harness secret store, Register refuses a Kit with a
// required OAuth credential.
oauthStore, _ := b.stateStore.(egress.OAuthStore)
@@ -33,12 +33,14 @@ type runCredentialResolver struct {
secrets interface {
Resolve(config.SecretRef) (string, error)
}
// credentials, when set, is told whether each bound secret resolved.
credentials *credentialWatch
}
func (r runCredentialResolver) Resolve(ctx context.Context, credential, service string) (string, error) {
if r.sessions != nil {
if org, services, ok := r.sessions.GrantedFor(credential); ok {
return r.resolveBinding(org, services, service)
return r.resolveBinding(ctx, org, services, service)
}
}
task, err := r.runs.TaskForCredential(ctx, credential)
@@ -53,13 +55,13 @@ func (r runCredentialResolver) Resolve(ctx context.Context, credential, service
if r.isModelProvider(ctx, cfg, task, service) {
granted = append(slices.Clone(granted), service)
}
return r.resolveBinding(org, granted, service)
return r.resolveBinding(ctx, org, granted, service)
}
// resolveBinding resolves service from the org's binding when the run or
// session is granted it. An OAuth binding resolves to the empty string: the
// proxy supplies the org's token set itself.
func (r runCredentialResolver) resolveBinding(org string, granted []string, service string) (string, error) {
func (r runCredentialResolver) resolveBinding(ctx context.Context, org string, granted []string, service string) (string, error) {
cfg := r.config.Get()
binding, ok := cfg.Containers.BoundCredentials(org, granted, []string{service})[service]
if !ok {
@@ -71,7 +73,9 @@ func (r runCredentialResolver) resolveBinding(org string, granted []string, serv
if r.secrets == nil {
return "", egress.ErrUnbound
}
return r.secrets.Resolve(binding.Secret)
value, err := r.secrets.Resolve(binding.Secret)
r.credentials.observe(ctx, org, service, err != nil)
return value, err
}
// isModelProvider reports whether service is a provider the task's models
+9
View File
@@ -94,6 +94,7 @@ func compose(ctx context.Context, d deps) *webui.Server {
srv.Policies = policies
}
wireOrgSurface(srv, d.Store)
wireAlerts(srv, d.Store)
if presence, ok := d.Store.(storecontract.PresenceStore); ok {
srv.Presence = presence
srv.RunningVersions = servicekit.RunningVersions(ctx, presence, 0)
@@ -228,3 +229,11 @@ func refusalStore(store storecontract.TaskStore) storecontract.CaptureRefusalSto
refusals, _ := store.(storecontract.CaptureRefusalStore)
return refusals
}
// wireAlerts gives the dashboard the State Store's alert surface when the
// store has one.
func wireAlerts(srv *webui.Server, store any) {
if alerts, ok := store.(webui.AlertSource); ok {
srv.Alerts = alerts
}
}
+2 -2
View File
@@ -124,12 +124,12 @@ func runtimeConfigFrom(ctx context.Context, reader controlplanerpc.ResourceReade
}
func runtimeToolConfigFrom(ctx context.Context, reader controlplanerpc.ResourceReader, versions map[string]int64, out config.Config) (config.Config, map[string]int64, error) {
policy := taskPolicy{DiffCapLines: out.DiffCap(), NotifyWebhook: out.Notify.Webhook}
policy := taskPolicyOf(out)
if err := layerResourceJSON(ctx, reader, versions, TaskPolicyKind, &policy); err != nil {
return config.Config{}, nil, err
}
out.DiffCapLines = new(policy.DiffCapLines)
out.Notify.Webhook = policy.NotifyWebhook
out.Notify = config.Notify{Webhook: policy.NotifyWebhook, MinSeverity: policy.NotifyMinSeverity, Secret: policy.NotifySecret}
if err := layerResource(ctx, reader, versions, ToolSettingsKind, func(settings toolSettings) error {
headers := make(map[string]map[string]string, len(out.Tools.MCPServers))
+19 -3
View File
@@ -5,18 +5,21 @@ import (
"net/url"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/alert"
)
const TaskPolicyKind = "task-policy"
type taskPolicy struct {
DiffCapLines int `json:"diff_cap_lines"`
NotifyWebhook string `json:"notify_webhook"`
DiffCapLines int `json:"diff_cap_lines"`
NotifyWebhook string `json:"notify_webhook"`
NotifyMinSeverity string `json:"notify_min_severity"`
NotifySecret config.SecretRef `json:"notify_secret"`
}
func taskPolicyDefinition() Definition {
return Definition{Kind: TaskPolicyKind, Title: "Task policy", ApplyMode: "live", Document: taskPolicy{}, Seed: func(cfg config.Config) any {
return taskPolicy{DiffCapLines: cfg.DiffCap(), NotifyWebhook: cfg.Notify.Webhook}
return taskPolicyOf(cfg)
}, Validate: func(input []byte) error {
return validateAs(input, func(doc taskPolicy) error {
if doc.DiffCapLines < 0 {
@@ -28,7 +31,20 @@ func taskPolicyDefinition() Definition {
return fmt.Errorf("notify_webhook must be an HTTP or HTTPS URL")
}
}
if !alert.Severity(doc.NotifyMinSeverity).Valid() && doc.NotifyMinSeverity != "" {
return fmt.Errorf("notify_min_severity must be info, warning or action")
}
if (doc.NotifySecret.Engine == "") != (doc.NotifySecret.Key == "") {
return fmt.Errorf("notify_secret needs both an engine and a key")
}
return nil
})
}}
}
func taskPolicyOf(cfg config.Config) taskPolicy {
return taskPolicy{
DiffCapLines: cfg.DiffCap(), NotifyWebhook: cfg.Notify.Webhook,
NotifyMinSeverity: cfg.Notify.MinSeverity, NotifySecret: cfg.Notify.Secret,
}
}
+127
View File
@@ -0,0 +1,127 @@
package statestore
import (
"context"
"fmt"
"slices"
"time"
"github.com/samcharles93/archie-core/internal/domain/alert"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/presence"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
)
const (
// alertSweepInterval is how often the store checks service health and
// prunes closed alerts.
alertSweepInterval = time.Minute
// alertRetention is how long a resolved or dismissed alert is kept.
alertRetention = 30 * 24 * time.Hour
// serviceGrace is how long a service may be unhealthy before it is worth
// an operator's attention: restarts and updates pass through it.
serviceGrace = 5 * time.Minute
)
// serviceWatch remembers since when each service has been unhealthy.
type serviceWatch struct {
since map[string]time.Time
}
// unhealthy returns the services that have been down or degraded for longer
// than serviceGrace, and forgets those that recovered. A service that never
// reported is absent rather than unhealthy and is left out.
func (w *serviceWatch) unhealthy(mesh []presence.Service, now time.Time) []string {
if w.since == nil {
w.since = map[string]time.Time{}
}
var out []string
for _, service := range mesh {
if !slices.Contains(presence.Services(), service.Service) || service.ReportedAt.IsZero() {
continue
}
if service.State == presence.StateUp {
delete(w.since, service.Service)
continue
}
since, ok := w.since[service.Service]
if !ok {
since = now
w.since[service.Service] = since
}
if now.Sub(since) >= serviceGrace {
out = append(out, service.Service)
}
}
return out
}
func serviceAlert(name string) alert.Input {
return alert.Input{
Org: org.DefaultOrgID, Kind: alert.KindServiceUnhealthy, Subject: "service:" + name,
Severity: alert.SeverityWarning, Condition: true,
Title: name + " is unhealthy",
Body: fmt.Sprintf("%s has not been healthy for over %d minutes.", name, int(serviceGrace.Minutes())),
Link: "/settings/status",
}
}
// startSweeps starts the store's periodic work: auto-updating packages, and
// checking service health and pruning alerts.
func (b *server) startSweeps(ctx context.Context, deps staterpc.Deps) {
go b.autoUpdatePackages(ctx, deps.Packages)
if deps.Alerts != nil {
go b.sweepAlerts(ctx, deps.Alerts)
}
}
// sweepAlerts raises and clears service health alerts and prunes closed
// alerts, until ctx ends. Service health has no transition to hang an alert
// on, so it is checked here, next to the presence records it reads.
func (b *server) sweepAlerts(ctx context.Context, store alert.Store) {
pruner, _ := b.st.(alert.Pruner)
records, _ := b.st.(interface {
ListPresence(context.Context) ([]storecontract.Presence, error)
})
reporter := alert.Reporter{Raiser: store, Log: b.log, By: "state-store"}
var watch serviceWatch
ticker := time.NewTicker(alertSweepInterval)
defer ticker.Stop()
for {
if records != nil {
b.checkServices(ctx, reporter, records, &watch)
}
if pruner != nil {
if _, err := pruner.PruneAlerts(ctx, time.Now().Add(-alertRetention)); err != nil && ctx.Err() == nil {
b.log.Warn("prune alerts", "err", err)
}
}
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}
func (b *server) checkServices(ctx context.Context, reporter alert.Reporter, records interface {
ListPresence(context.Context) ([]storecontract.Presence, error)
}, watch *serviceWatch,
) {
list, err := records.ListPresence(ctx)
if err != nil {
if ctx.Err() == nil {
b.log.Warn("service health not checked", "err", err)
}
return
}
now := time.Now()
mesh := presence.Mesh(list, now)
down := watch.unhealthy(mesh, now)
for _, service := range mesh {
if slices.Contains(presence.Services(), service.Service) {
reporter.Sync(ctx, slices.Contains(down, service.Service), serviceAlert(service.Service))
}
}
}
+5 -1
View File
@@ -20,6 +20,7 @@ import (
"github.com/samcharles93/archie-core/internal/app/servicekit"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/alert"
"github.com/samcharles93/archie-core/internal/domain/health"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
@@ -144,7 +145,7 @@ func Run(ctx context.Context, options Options) error { //nolint:cyclop // the co
deps := b.stateStoreDeps(grants)
controlPlaneDeps(&deps, control)
go b.autoUpdatePackages(ctx, deps.Packages)
b.startSweeps(ctx, deps)
return serveStateStore(ctx, listener, deps, opts)
}
@@ -432,6 +433,9 @@ func (b *server) accessDeps(deps *staterpc.Deps) {
if os, ok := b.st.(org.Repository); ok {
deps.Orgs = os
}
if as, ok := b.st.(alert.Store); ok {
deps.Alerts = as
}
}
// serveStateStore registers the StateStore gRPC service and serves it until
+9 -5
View File
@@ -433,7 +433,6 @@ type TaskConfig struct {
MaxRetries int `json:"max_retries"`
Dispatch Dispatch `json:"dispatch"`
DiffCapLines int `json:"diff_cap_lines"`
Notify Notify `json:"notify"`
Forge TaskForge `json:"forge"`
ToolPolicy ToolPolicy `json:"tool_policy"`
Review Review `json:"review"`
@@ -469,7 +468,6 @@ func (c Config) ForTask() TaskConfig {
MaxRetries: c.MaxRetries,
Dispatch: Dispatch{Trigger: c.Dispatch.Trigger, AckReaction: c.Dispatch.AckReaction},
DiffCapLines: c.DiffCap(),
Notify: c.Notify,
Forge: TaskForge{Host: c.Forge.Host},
ToolPolicy: c.Tools.Policy,
Review: c.Review,
@@ -490,7 +488,6 @@ func (tc TaskConfig) ToConfig() Config {
MaxRetries: tc.MaxRetries,
Dispatch: Dispatch{Trigger: tc.Dispatch.Trigger, AckReaction: tc.Dispatch.AckReaction},
DiffCapLines: &tc.DiffCapLines,
Notify: tc.Notify,
Forge: Forge{Host: tc.Forge.Host},
Tools: ToolsConfig{Policy: tc.ToolPolicy},
Review: tc.Review,
@@ -899,10 +896,17 @@ type TelegramConfig struct {
Token SecretRef `toml:"token" yaml:"token"`
}
// Notify configures outbound notifications (n8n webhook → email etc.).
// Notify configures outbound alert deliveries (n8n webhook → email etc.).
type Notify struct {
// Webhook receives JSON POSTs for events that need a human. Empty disables.
// Webhook receives a JSON POST when an operator alert is raised or
// resolved. Empty disables.
Webhook string `toml:"webhook" json:"webhook" yaml:"webhook"`
// MinSeverity is the lowest alert severity delivered: info, warning or
// action. Empty means warning.
MinSeverity string `toml:"min_severity" json:"min_severity" yaml:"min_severity"`
// Secret signs each payload with HMAC-SHA256 in X-Archie-Signature.
// Empty sends payloads unsigned.
Secret SecretRef `toml:"secret" json:"-" yaml:"secret"`
}
// Web configures the observability dashboard. Health is archied's own liveness
File diff suppressed because it is too large. Load diff
@@ -152,6 +152,12 @@ const (
StateStoreService_SetMembership_FullMethodName = "/state.v1.StateStoreService/SetMembership"
StateStoreService_RemoveMembership_FullMethodName = "/state.v1.StateStoreService/RemoveMembership"
StateStoreService_AssignAgent_FullMethodName = "/state.v1.StateStoreService/AssignAgent"
StateStoreService_RaiseAlert_FullMethodName = "/state.v1.StateStoreService/RaiseAlert"
StateStoreService_ResolveAlert_FullMethodName = "/state.v1.StateStoreService/ResolveAlert"
StateStoreService_DismissAlert_FullMethodName = "/state.v1.StateStoreService/DismissAlert"
StateStoreService_ListAlerts_FullMethodName = "/state.v1.StateStoreService/ListAlerts"
StateStoreService_ClaimAlertDeliveries_FullMethodName = "/state.v1.StateStoreService/ClaimAlertDeliveries"
StateStoreService_RecordAlertAttempt_FullMethodName = "/state.v1.StateStoreService/RecordAlertAttempt"
)
// StateStoreServiceClient is the client API for StateStoreService service.
@@ -413,6 +419,18 @@ type StateStoreServiceClient interface {
SetMembership(ctx context.Context, in *SetMembershipRequest, opts ...grpc.CallOption) (*SetMembershipResponse, error)
RemoveMembership(ctx context.Context, in *RemoveMembershipRequest, opts ...grpc.CallOption) (*RemoveMembershipResponse, error)
AssignAgent(ctx context.Context, in *AssignAgentRequest, opts ...grpc.CallOption) (*AssignAgentResponse, error)
// Operator alerts (internal/domain/alert). A caller acting for a principal
// reads, dismisses and raises only in that principal's org; a request org is
// ignored for it. A service acting for no one names the org itself.
// RaiseAlert and ResolveAlert are idempotent, so a periodic check can call
// them every tick. ClaimAlertDeliveries and RecordAlertAttempt serve the
// outbound webhook and refuse a caller scoped to an org.
RaiseAlert(ctx context.Context, in *RaiseAlertRequest, opts ...grpc.CallOption) (*RaiseAlertResponse, error)
ResolveAlert(ctx context.Context, in *ResolveAlertRequest, opts ...grpc.CallOption) (*ResolveAlertResponse, error)
DismissAlert(ctx context.Context, in *DismissAlertRequest, opts ...grpc.CallOption) (*DismissAlertResponse, error)
ListAlerts(ctx context.Context, in *ListAlertsRequest, opts ...grpc.CallOption) (*ListAlertsResponse, error)
ClaimAlertDeliveries(ctx context.Context, in *ClaimAlertDeliveriesRequest, opts ...grpc.CallOption) (*ClaimAlertDeliveriesResponse, error)
RecordAlertAttempt(ctx context.Context, in *RecordAlertAttemptRequest, opts ...grpc.CallOption) (*RecordAlertAttemptResponse, error)
}
type stateStoreServiceClient struct {
@@ -1780,6 +1798,66 @@ func (c *stateStoreServiceClient) AssignAgent(ctx context.Context, in *AssignAge
return out, nil
}
func (c *stateStoreServiceClient) RaiseAlert(ctx context.Context, in *RaiseAlertRequest, opts ...grpc.CallOption) (*RaiseAlertResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RaiseAlertResponse)
err := c.cc.Invoke(ctx, StateStoreService_RaiseAlert_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) ResolveAlert(ctx context.Context, in *ResolveAlertRequest, opts ...grpc.CallOption) (*ResolveAlertResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ResolveAlertResponse)
err := c.cc.Invoke(ctx, StateStoreService_ResolveAlert_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) DismissAlert(ctx context.Context, in *DismissAlertRequest, opts ...grpc.CallOption) (*DismissAlertResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(DismissAlertResponse)
err := c.cc.Invoke(ctx, StateStoreService_DismissAlert_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) ListAlerts(ctx context.Context, in *ListAlertsRequest, opts ...grpc.CallOption) (*ListAlertsResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ListAlertsResponse)
err := c.cc.Invoke(ctx, StateStoreService_ListAlerts_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) ClaimAlertDeliveries(ctx context.Context, in *ClaimAlertDeliveriesRequest, opts ...grpc.CallOption) (*ClaimAlertDeliveriesResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ClaimAlertDeliveriesResponse)
err := c.cc.Invoke(ctx, StateStoreService_ClaimAlertDeliveries_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) RecordAlertAttempt(ctx context.Context, in *RecordAlertAttemptRequest, opts ...grpc.CallOption) (*RecordAlertAttemptResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RecordAlertAttemptResponse)
err := c.cc.Invoke(ctx, StateStoreService_RecordAlertAttempt_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// StateStoreServiceServer is the server API for StateStoreService service.
// All implementations must embed UnimplementedStateStoreServiceServer
// for forward compatibility.
@@ -2039,6 +2117,18 @@ type StateStoreServiceServer interface {
SetMembership(context.Context, *SetMembershipRequest) (*SetMembershipResponse, error)
RemoveMembership(context.Context, *RemoveMembershipRequest) (*RemoveMembershipResponse, error)
AssignAgent(context.Context, *AssignAgentRequest) (*AssignAgentResponse, error)
// Operator alerts (internal/domain/alert). A caller acting for a principal
// reads, dismisses and raises only in that principal's org; a request org is
// ignored for it. A service acting for no one names the org itself.
// RaiseAlert and ResolveAlert are idempotent, so a periodic check can call
// them every tick. ClaimAlertDeliveries and RecordAlertAttempt serve the
// outbound webhook and refuse a caller scoped to an org.
RaiseAlert(context.Context, *RaiseAlertRequest) (*RaiseAlertResponse, error)
ResolveAlert(context.Context, *ResolveAlertRequest) (*ResolveAlertResponse, error)
DismissAlert(context.Context, *DismissAlertRequest) (*DismissAlertResponse, error)
ListAlerts(context.Context, *ListAlertsRequest) (*ListAlertsResponse, error)
ClaimAlertDeliveries(context.Context, *ClaimAlertDeliveriesRequest) (*ClaimAlertDeliveriesResponse, error)
RecordAlertAttempt(context.Context, *RecordAlertAttemptRequest) (*RecordAlertAttemptResponse, error)
mustEmbedUnimplementedStateStoreServiceServer()
}
@@ -2448,6 +2538,24 @@ func (UnimplementedStateStoreServiceServer) RemoveMembership(context.Context, *R
func (UnimplementedStateStoreServiceServer) AssignAgent(context.Context, *AssignAgentRequest) (*AssignAgentResponse, error) {
return nil, status.Error(codes.Unimplemented, "method AssignAgent not implemented")
}
func (UnimplementedStateStoreServiceServer) RaiseAlert(context.Context, *RaiseAlertRequest) (*RaiseAlertResponse, error) {
return nil, status.Error(codes.Unimplemented, "method RaiseAlert not implemented")
}
func (UnimplementedStateStoreServiceServer) ResolveAlert(context.Context, *ResolveAlertRequest) (*ResolveAlertResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ResolveAlert not implemented")
}
func (UnimplementedStateStoreServiceServer) DismissAlert(context.Context, *DismissAlertRequest) (*DismissAlertResponse, error) {
return nil, status.Error(codes.Unimplemented, "method DismissAlert not implemented")
}
func (UnimplementedStateStoreServiceServer) ListAlerts(context.Context, *ListAlertsRequest) (*ListAlertsResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ListAlerts not implemented")
}
func (UnimplementedStateStoreServiceServer) ClaimAlertDeliveries(context.Context, *ClaimAlertDeliveriesRequest) (*ClaimAlertDeliveriesResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ClaimAlertDeliveries not implemented")
}
func (UnimplementedStateStoreServiceServer) RecordAlertAttempt(context.Context, *RecordAlertAttemptRequest) (*RecordAlertAttemptResponse, error) {
return nil, status.Error(codes.Unimplemented, "method RecordAlertAttempt not implemented")
}
func (UnimplementedStateStoreServiceServer) mustEmbedUnimplementedStateStoreServiceServer() {}
func (UnimplementedStateStoreServiceServer) testEmbeddedByValue() {}
@@ -4842,6 +4950,114 @@ func _StateStoreService_AssignAgent_Handler(srv interface{}, ctx context.Context
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_RaiseAlert_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RaiseAlertRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).RaiseAlert(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_RaiseAlert_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).RaiseAlert(ctx, req.(*RaiseAlertRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_ResolveAlert_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ResolveAlertRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).ResolveAlert(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_ResolveAlert_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).ResolveAlert(ctx, req.(*ResolveAlertRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_DismissAlert_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(DismissAlertRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).DismissAlert(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_DismissAlert_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).DismissAlert(ctx, req.(*DismissAlertRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_ListAlerts_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListAlertsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).ListAlerts(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_ListAlerts_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).ListAlerts(ctx, req.(*ListAlertsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_ClaimAlertDeliveries_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ClaimAlertDeliveriesRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).ClaimAlertDeliveries(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_ClaimAlertDeliveries_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).ClaimAlertDeliveries(ctx, req.(*ClaimAlertDeliveriesRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_RecordAlertAttempt_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RecordAlertAttemptRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).RecordAlertAttempt(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_RecordAlertAttempt_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).RecordAlertAttempt(ctx, req.(*RecordAlertAttemptRequest))
}
return interceptor(ctx, in, info, handler)
}
// StateStoreService_ServiceDesc is the grpc.ServiceDesc for StateStoreService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
@@ -5369,6 +5585,30 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
MethodName: "AssignAgent",
Handler: _StateStoreService_AssignAgent_Handler,
},
{
MethodName: "RaiseAlert",
Handler: _StateStoreService_RaiseAlert_Handler,
},
{
MethodName: "ResolveAlert",
Handler: _StateStoreService_ResolveAlert_Handler,
},
{
MethodName: "DismissAlert",
Handler: _StateStoreService_DismissAlert_Handler,
},
{
MethodName: "ListAlerts",
Handler: _StateStoreService_ListAlerts_Handler,
},
{
MethodName: "ClaimAlertDeliveries",
Handler: _StateStoreService_ClaimAlertDeliveries_Handler,
},
{
MethodName: "RecordAlertAttempt",
Handler: _StateStoreService_RecordAlertAttempt_Handler,
},
},
Streams: []grpc.StreamDesc{
{
+1 -2
View File
@@ -123,10 +123,9 @@ func TestIdentityTasksUseLiveSettings(t *testing.T) {
root.Models = map[string]string{"builder": model}
root.Budgets.MaxSteps++
root.Dispatch.Trigger = "label"
root.Notify.Webhook = "https://example.test/notify"
d.Cfg.Set(root)
got := d.configFor(task)
if !reflect.DeepEqual(got.Models, root.Models) || !reflect.DeepEqual(got.Providers, root.Providers) || got.Budgets != root.Budgets || got.Dispatch != root.Dispatch || got.Notify != root.Notify {
if !reflect.DeepEqual(got.Models, root.Models) || !reflect.DeepEqual(got.Providers, root.Providers) || got.Budgets != root.Budgets || got.Dispatch != root.Dispatch {
t.Fatalf("identity settings replaced the current runtime settings: %+v", got)
}
repo, ok := d.repoFor(task)
+279
View File
@@ -0,0 +1,279 @@
// Package alert is the operator's list of things that need a human. The State
// Store owns the rows; services raise and clear alerts through its contract and
// never read the table.
//
// An alert is one row per (org, kind, subject). A condition alert is backed by
// something that can stop being true, so whoever detects it resolves it when
// it clears. An event alert records something that happened and stays until
// an operator dismisses it.
//
// Titles and bodies are shown to every member of the org and sent to the
// notify webhook. A raiser writes them from fixed text and ids, never from an
// error string, a command line or a credential.
package alert
import (
"context"
"errors"
"fmt"
"log/slog"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// Severity orders how loudly an alert asks for attention.
type Severity string
const (
SeverityInfo Severity = "info"
SeverityWarning Severity = "warning"
SeverityAction Severity = "action"
)
// Rank orders severities, highest first needing the most attention. An unknown
// severity ranks below info.
func (s Severity) Rank() int {
switch s {
case SeverityAction:
return 3
case SeverityWarning:
return 2
case SeverityInfo:
return 1
default:
return 0
}
}
// Valid reports whether s is a known severity.
func (s Severity) Valid() bool { return s.Rank() > 0 }
// State is where an alert is in its life.
type State string
const (
StateOpen State = "open"
StateResolved State = "resolved"
StateDismissed State = "dismissed"
)
// Conditions and events the in-tree raisers use. The kind is part of the
// dedup key, so renaming one orphans its open alerts.
const (
KindTaskNeedsHuman = "task.needs_human"
KindTaskFailed = "task.failed"
KindModelAlias = "model.alias"
KindProviderNoKey = "provider.no_credential"
KindToolNoBinding = "tool.no_credential"
KindCredentialInvalid = "credential.rejected"
KindServiceUnhealthy = "service.unhealthy"
KindReleaseAvailable = "release.available"
)
// Limits on what a raiser may store.
const (
maxKindLen = 64
maxSubjectLen = 200
maxTitleLen = 200
maxBodyLen = 2000
maxLinkLen = 500
)
// ErrInvalid is returned for an alert the store would refuse to hold.
var ErrInvalid = errors.New("alert: invalid")
// Key is what makes two raises the same alert.
type Key struct {
Org org.OrgID
Kind string
Subject string
}
// Input is one raise.
type Input struct {
Key
Severity Severity
Title string
Body string
// Link is the dashboard path that fixes it, such as /tasks/12.
Link string
// Condition is true when the raiser resolves the alert itself once the
// condition clears. An event alert (false) stays until dismissed.
Condition bool
}
// Validate refuses an input the store cannot hold.
func (in Input) Validate() error {
switch {
case in.Org == "":
return fmt.Errorf("%w: org is required", ErrInvalid)
case in.Kind == "" || len(in.Kind) > maxKindLen:
return fmt.Errorf("%w: kind is required and at most %d bytes", ErrInvalid, maxKindLen)
case in.Subject == "" || len(in.Subject) > maxSubjectLen:
return fmt.Errorf("%w: subject is required and at most %d bytes", ErrInvalid, maxSubjectLen)
case !in.Severity.Valid():
return fmt.Errorf("%w: severity %q", ErrInvalid, in.Severity)
case strings.TrimSpace(in.Title) == "" || len(in.Title) > maxTitleLen:
return fmt.Errorf("%w: title is required and at most %d bytes", ErrInvalid, maxTitleLen)
case len(in.Body) > maxBodyLen:
return fmt.Errorf("%w: body is at most %d bytes", ErrInvalid, maxBodyLen)
case len(in.Link) > maxLinkLen || (in.Link != "" && !strings.HasPrefix(in.Link, "/")):
return fmt.Errorf("%w: link must be a dashboard path of at most %d bytes", ErrInvalid, maxLinkLen)
}
return nil
}
// Alert is one row.
type Alert struct {
ID int64
Key
Severity Severity
Title string
Body string
Link string
Condition bool
State State
FirstRaised time.Time
LastSeen time.Time
Count int64
// ClosedBy and ClosedAt say who resolved or dismissed the alert and when.
ClosedBy string
ClosedAt time.Time
// Deliveries are the outbound notices this alert owed, newest first.
Deliveries []Delivery
}
// Apply is the alert after a raise. prev is the existing row, nil when there
// is none. opened reports that the alert became open: it is new, or it was
// resolved, or it was an event alert that had been dismissed. An open alert
// raised again only bumps its count and last seen. A dismissed condition
// alert is snoozed: it stays dismissed until the condition clears and recurs.
func Apply(prev *Alert, in Input, now time.Time) (next Alert, opened bool) {
fresh := Alert{
Key: in.Key, Severity: in.Severity, Title: in.Title, Body: in.Body, Link: in.Link,
Condition: in.Condition, State: StateOpen, FirstRaised: now, LastSeen: now, Count: 1,
}
if prev == nil {
return fresh, true
}
next = *prev
next.Severity, next.Title, next.Body, next.Link, next.Condition = in.Severity, in.Title, in.Body, in.Link, in.Condition
next.LastSeen = now
switch {
case prev.State == StateOpen:
next.Count++
return next, false
case prev.State == StateDismissed && prev.Condition && in.Condition:
return next, false
default:
fresh.ID, fresh.Deliveries = prev.ID, prev.Deliveries
return fresh, true
}
}
// Resolve is the alert after its condition cleared. changed reports that it
// moved to resolved. Only a condition alert has a condition to clear: an
// event alert stays until dismissed, and a resolved alert stays as it is. A
// snoozed (dismissed) condition alert resolves, so it can come back if the
// condition recurs.
func Resolve(prev Alert, by string, now time.Time) (next Alert, changed bool) {
if !prev.Condition || prev.State == StateResolved {
return prev, false
}
prev.State, prev.ClosedBy, prev.ClosedAt = StateResolved, by, now
return prev, true
}
// Dismiss is the alert after an operator dismissed it. changed reports that it
// moved to dismissed; only an open alert can be dismissed.
func Dismiss(prev Alert, by string, now time.Time) (next Alert, changed bool) {
if prev.State != StateOpen {
return prev, false
}
prev.State, prev.ClosedBy, prev.ClosedAt = StateDismissed, by, now
return prev, true
}
// Filter selects what List returns.
type Filter struct {
// States to include; empty means open only.
States []State
Limit int
}
// Store is the State Store's alert surface.
type Store interface {
Raiser
// Dismiss dismisses an open alert in org.
DismissAlert(ctx context.Context, orgID org.OrgID, id int64, by string) error
// List returns an org's alerts, highest severity then newest first.
ListAlerts(ctx context.Context, orgID org.OrgID, filter Filter) ([]Alert, error)
Deliverer
}
// Pruner removes alerts that closed before a retention cutoff, with their
// deliveries. The State Store runs it; it is not part of the contract.
type Pruner interface {
PruneAlerts(ctx context.Context, cutoff time.Time) (int64, error)
}
// Raiser is what a service needs to raise and clear alerts.
type Raiser interface {
// RaiseAlert stores in, idempotently: see Apply.
RaiseAlert(ctx context.Context, in Input) (Alert, error)
// ResolveAlert clears a condition alert; no alert under key is not an
// error.
ResolveAlert(ctx context.Context, key Key, by string) error
}
// Reporter raises and clears alerts for a service. A failure is logged and
// left for the next check: reporting never blocks or fails the caller's work.
// The zero Reporter, and one with no Raiser, does nothing.
type Reporter struct {
Raiser Raiser
Log *slog.Logger
// By names the resolver recorded on alerts this reporter clears.
By string
}
// Raise stores in.
func (r Reporter) Raise(ctx context.Context, in Input) {
if r.Raiser == nil {
return
}
if _, err := r.Raiser.RaiseAlert(ctx, in); err != nil {
r.warn("alert not raised", in.Key, err)
}
}
// Resolve clears the alert under key.
func (r Reporter) Resolve(ctx context.Context, key Key) {
if r.Raiser == nil {
return
}
if err := r.Raiser.ResolveAlert(ctx, key, r.By); err != nil {
r.warn("alert not resolved", key, err)
}
}
// Sync raises in while active holds and resolves it once it does not. It is
// the whole body of a periodic check for one condition.
func (r Reporter) Sync(ctx context.Context, active bool, in Input) {
if active {
r.Raise(ctx, in)
return
}
r.Resolve(ctx, in.Key)
}
func (r Reporter) warn(msg string, key Key, err error) {
if r.Log != nil {
r.Log.Warn(msg, "org", key.Org, "kind", key.Kind, "subject", key.Subject, "err", err)
}
}
// ErrNotFound is returned for an alert or delivery that does not exist, or
// that belongs to another org.
var ErrNotFound = errors.New("alert: not found")
+85
View File
@@ -0,0 +1,85 @@
package alert
import (
"context"
"time"
)
// Delivery states.
const (
DeliveryPending = "pending"
DeliveryDelivered = "delivered"
DeliveryFailed = "failed"
// DeliverySkipped is a notice nothing was configured to send, or whose
// severity was below the threshold.
DeliverySkipped = "skipped"
)
// What a delivery announces.
const (
EventRaised = "raised"
EventResolved = "resolved"
)
// MaxDeliveryAttempts bounds the retries of one notice. After the last the
// delivery is failed and kept on the alert.
const MaxDeliveryAttempts = 5
// RetryDelay is how long to wait after the attempt-th failed attempt.
func RetryDelay(attempt int64) time.Duration {
delays := [...]time.Duration{time.Minute, 5 * time.Minute, 15 * time.Minute, time.Hour}
return delays[min(max(attempt, 1), int64(len(delays)))-1]
}
// Delivery is one notice an alert owes: raised or resolved.
type Delivery struct {
ID int64
AlertID int64
Event string
State string
CreatedAt time.Time
// NextAttemptAt is when a pending delivery is next due.
NextAttemptAt time.Time
Attempts []Attempt
}
// Attempt is one try at a delivery.
type Attempt struct {
N int64
At time.Time
StatusCode int
Error string
}
// Due is a delivery with the alert it announces.
type Due struct {
Delivery
Alert Alert
// Attempt is the number of this try, counting from one.
Attempt int64
}
// Outcome is how one attempt went.
type Outcome struct {
DeliveryID int64
// Skipped closes the delivery without an attempt.
Skipped bool
StatusCode int
// Error is empty on success. It is stored on the alert and shown to the
// operator, so it names the failure and never the request.
Error string
}
// OK reports a successful attempt.
func (o Outcome) OK() bool { return !o.Skipped && o.Error == "" }
// Deliverer is the outbound half of the store: the due notices, and what
// became of each.
type Deliverer interface {
// ClaimDeliveries returns up to limit pending deliveries that are due and
// pushes each one's next attempt out, so a worker that dies mid-attempt
// does not strand it and two workers do not send it twice.
ClaimAlertDeliveries(ctx context.Context, limit int) ([]Due, error)
// RecordAttempt records an attempt and settles or reschedules the delivery.
RecordAlertAttempt(ctx context.Context, outcome Outcome) error
}
+3 -37
View File
@@ -1,16 +1,13 @@
package workflow
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
// notify posts a one-way notice on a forge-backed task's issue and, when
// configured, to the notify webhook.
// notify posts a one-way notice on a forge-backed task's issue. The operator
// alert for the task waiting on a human is raised by the State Store when the
// task parks.
func notify(ctx context.Context, tc *TaskContext, kind string) {
if tc.Task.IsForgeBacked() {
if _, err := tc.Forge.Comment(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, deliveryNotice(tc, kind)); err != nil {
@@ -18,37 +15,6 @@ func notify(ctx context.Context, tc *TaskContext, kind string) {
"kind", kind, "issue", tc.Task.IssueNumber, "err", err)
}
}
url := tc.Cfg.Notify.Webhook
if url == "" {
return
}
fields := map[string]any{
"type": kind, "repo": tc.Repo.FullName(), "task_id": tc.Task.ID,
"source": tc.Task.Source, "identity": tc.Task.Identity,
"title": tc.Task.Title, "prd": tc.Task.Plan,
}
if tc.Task.IsForgeBacked() {
fields["issue"] = tc.Task.IssueNumber
fields["issue_url"] = fmt.Sprintf("%s/%s/issues/%d",
tc.Cfg.Forge.Host, tc.Repo.FullName(), tc.Task.IssueNumber)
}
payload, _ := json.Marshal(fields)
reqCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, url, bytes.NewReader(payload))
if err != nil {
tc.Log.Warn("notify webhook request build failed", "err", err)
return
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
tc.Log.Warn("notify webhook failed", "err", err)
return
}
if err := resp.Body.Close(); err != nil {
tc.Log.Warn("close notify webhook response", "err", err)
}
}
// deliveryNotice is the body of the one-way notice notify posts on a
+4
View File
@@ -72,6 +72,10 @@ const (
KindTaskArchiveRequested = "task_archive_requested"
KindWorkRequestSubmitted = "work_request_submitted"
KindLog = "log" // data: level, msg
// KindAlert marks an operator alert opening, resolving or being
// dismissed, so the dashboard's bell updates over the event stream.
// data: id, kind, state, severity.
KindAlert = "alert"
// KindChangesCaptured records one attempt's change at commit or push time.
// data: schema, owner, repo, base, branch, head_sha, base_sha, pr_number,
@@ -0,0 +1,94 @@
// Package alertwebhook delivers operator alerts to the notify webhook.
package alertwebhook
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"time"
"github.com/samcharles93/archie-core/internal/domain/alert"
"github.com/samcharles93/archie-core/internal/webhookguard"
)
// SignatureHeader carries the payload's HMAC-SHA256 when a secret is set.
const SignatureHeader = "X-Archie-Signature"
const timeout = 10 * time.Second
type payload struct {
Event string `json:"event"`
Attempt int64 `json:"attempt"`
Alert body `json:"alert"`
}
type body struct {
ID int64 `json:"id"`
Org string `json:"org"`
Kind string `json:"kind"`
Subject string `json:"subject"`
Severity string `json:"severity"`
Title string `json:"title"`
Body string `json:"body"`
Link string `json:"link"`
State string `json:"state"`
FirstRaised time.Time `json:"first_raised"`
LastSeen time.Time `json:"last_seen"`
Count int64 `json:"count"`
}
// Payload is the JSON body sent for a due delivery.
func Payload(due alert.Due) ([]byte, error) {
a := due.Alert
return json.Marshal(payload{
Event: due.Event, Attempt: due.Attempt,
Alert: body{
ID: a.ID, Org: string(a.Org), Kind: a.Kind, Subject: a.Subject, Severity: string(a.Severity),
Title: a.Title, Body: a.Body, Link: a.Link, State: string(a.State),
FirstRaised: a.FirstRaised, LastSeen: a.LastSeen, Count: a.Count,
},
})
}
// Send posts due to webhook, signed with secret when it is not empty. The
// outcome's error names what went wrong without the webhook URL, which may
// carry a token.
func Send(ctx context.Context, client *http.Client, webhook, secret string, due alert.Due) alert.Outcome {
out := alert.Outcome{DeliveryID: due.ID}
data, err := Payload(due)
if err != nil {
out.Error = "encode payload"
return out
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, webhook, bytes.NewReader(data))
if err != nil {
out.Error = "invalid webhook URL"
return out
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Archie-Event", due.Event)
req.Header.Set("X-Archie-Delivery", fmt.Sprint(due.ID))
if secret != "" {
req.Header.Set(SignatureHeader, webhookguard.SignHMAC(data, secret))
}
resp, err := client.Do(req)
if err != nil {
if urlErr, ok := errors.AsType[*url.Error](err); ok {
err = urlErr.Err
}
out.Error = err.Error()
return out
}
_ = resp.Body.Close()
out.StatusCode = resp.StatusCode
if resp.StatusCode < 200 || resp.StatusCode > 299 {
out.Error = fmt.Sprintf("webhook answered %d", resp.StatusCode)
}
return out
}
+328
View File
@@ -0,0 +1,328 @@
// Operator alerts: the Postgres implementation of internal/domain/alert.Store.
// Every write runs in a transaction that holds an advisory lock on the alert's
// key, so a raise and a resolve of one alert never interleave, and records the
// event and the delivery the change owes in the same commit.
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/samcharles93/archie-core/internal/domain/alert"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
var (
_ alert.Store = (*Store)(nil)
_ alert.Pruner = (*Store)(nil)
)
// deliveriesPerAlert bounds the delivery history one listed alert carries.
const deliveriesPerAlert = 10
func alertFromRow(r postgresdb.Alert) alert.Alert {
a := alert.Alert{
ID: r.ID,
Org: org.OrgID(r.OrgID), Kind: r.Kind, Subject: r.Subject,
Severity: alert.Severity(r.Severity), Title: r.Title, Body: r.Body, Link: r.Link,
Condition: r.IsCondition, State: alert.State(r.State),
FirstRaised: r.FirstRaised, LastSeen: r.LastSeen, Count: r.Count, ClosedBy: r.ClosedBy,
}
if r.ClosedAt.Valid {
a.ClosedAt = r.ClosedAt.Time
}
return a
}
func alertParams(a alert.Alert) postgresdb.UpsertAlertParams {
return postgresdb.UpsertAlertParams{
OrgID: string(a.Org), Kind: a.Kind, Subject: a.Subject, Severity: string(a.Severity),
Title: a.Title, Body: a.Body, Link: a.Link, IsCondition: a.Condition, State: string(a.State),
FirstRaised: a.FirstRaised, LastSeen: a.LastSeen, Count: a.Count, ClosedBy: a.ClosedBy,
ClosedAt: pgtype.Timestamptz{Time: a.ClosedAt, Valid: !a.ClosedAt.IsZero()},
}
}
func alertLockKey(k alert.Key) string { return string(k.Org) + "\x00" + k.Kind + "\x00" + k.Subject }
// lockedAlert takes the key's lock and returns the stored alert, nil when
// there is none.
func lockedAlert(ctx context.Context, q *postgresdb.Queries, key alert.Key) (*alert.Alert, error) {
if err := q.LockAlertKey(ctx, alertLockKey(key)); err != nil {
return nil, err
}
row, err := q.GetAlertByKey(ctx, postgresdb.GetAlertByKeyParams{OrgID: string(key.Org), Kind: key.Kind, Subject: key.Subject})
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
a := alertFromRow(row)
return &a, nil
}
// alertChanged records an alert's change on the event stream, and the
// delivery it owes when delivery is not empty.
func alertChanged(ctx context.Context, q *postgresdb.Queries, a alert.Alert, delivery string) error {
if delivery != "" {
if err := q.InsertAlertDelivery(ctx, postgresdb.InsertAlertDeliveryParams{AlertID: a.ID, Event: delivery}); err != nil {
return err
}
}
_, err := insertEventQ(org.WithOrg(ctx, a.Org), q, events.Event{
Kind: events.KindAlert, Detail: a.Title,
Data: map[string]any{"id": a.ID, "kind": a.Kind, "state": string(a.State), "severity": string(a.Severity)},
})
return err
}
// raiseAlert stores in under q, which must be a transaction.
func raiseAlert(ctx context.Context, q *postgresdb.Queries, in alert.Input) (alert.Alert, error) {
if err := in.Validate(); err != nil {
return alert.Alert{}, err
}
prev, err := lockedAlert(ctx, q, in.Key)
if err != nil {
return alert.Alert{}, err
}
next, opened := alert.Apply(prev, in, time.Now().UTC())
row, err := q.UpsertAlert(ctx, alertParams(next))
if err != nil {
return alert.Alert{}, err
}
stored := alertFromRow(row)
if opened {
if err := alertChanged(ctx, q, stored, alert.EventRaised); err != nil {
return alert.Alert{}, err
}
}
return stored, nil
}
// resolveAlert clears the alert under key through q, which must be a
// transaction.
func resolveAlert(ctx context.Context, q *postgresdb.Queries, key alert.Key, by string) error {
prev, err := lockedAlert(ctx, q, key)
if err != nil || prev == nil {
return err
}
next, changed := alert.Resolve(*prev, by, time.Now().UTC())
if !changed {
return nil
}
row, err := q.UpsertAlert(ctx, alertParams(next))
if err != nil {
return err
}
return alertChanged(ctx, q, alertFromRow(row), alert.EventResolved)
}
func (s *Store) inTx(ctx context.Context, fn func(*postgresdb.Queries) error) error {
tx, err := s.pool.Begin(ctx)
if err != nil {
return err
}
defer func() { _ = tx.Rollback(ctx) }()
if err := fn(postgresdb.New(tx)); err != nil {
return err
}
return tx.Commit(ctx)
}
// Raise stores in idempotently.
func (s *Store) RaiseAlert(ctx context.Context, in alert.Input) (alert.Alert, error) {
var out alert.Alert
err := s.inTx(ctx, func(q *postgresdb.Queries) (err error) {
out, err = raiseAlert(ctx, q, in)
return err
})
return out, err
}
// Resolve clears the alert under key.
func (s *Store) ResolveAlert(ctx context.Context, key alert.Key, by string) error {
return s.inTx(ctx, func(q *postgresdb.Queries) error { return resolveAlert(ctx, q, key, by) })
}
// Dismiss dismisses an open alert of orgID. An alert of another org is
// indistinguishable from none.
func (s *Store) DismissAlert(ctx context.Context, orgID org.OrgID, id int64, by string) error {
return s.inTx(ctx, func(q *postgresdb.Queries) error {
row, err := q.GetOrgAlert(ctx, postgresdb.GetOrgAlertParams{OrgID: string(orgID), ID: id})
if errors.Is(err, pgx.ErrNoRows) {
return alert.ErrNotFound
}
if err != nil {
return err
}
prev, err := lockedAlert(ctx, q, alertFromRow(row).Key)
if err != nil || prev == nil {
return errors.Join(err, alert.ErrNotFound)
}
next, changed := alert.Dismiss(*prev, by, time.Now().UTC())
if !changed {
return nil
}
stored, err := q.UpsertAlert(ctx, alertParams(next))
if err != nil {
return err
}
return alertChanged(ctx, q, alertFromRow(stored), "")
})
}
// List returns an org's alerts with their deliveries.
func (s *Store) ListAlerts(ctx context.Context, orgID org.OrgID, filter alert.Filter) ([]alert.Alert, error) {
states := []string{string(alert.StateOpen)}
if len(filter.States) > 0 {
states = states[:0]
for _, st := range filter.States {
states = append(states, string(st))
}
}
limit := filter.Limit
if limit <= 0 || limit > 500 {
limit = 200
}
q := s.queries()
rows, err := q.ListAlerts(ctx, postgresdb.ListAlertsParams{OrgID: string(orgID), States: states, PageLimit: int32(limit)})
if err != nil {
return nil, err
}
out := make([]alert.Alert, len(rows))
ids := make([]int64, len(rows))
for i, r := range rows {
out[i], ids[i] = alertFromRow(r), r.ID
}
if len(ids) == 0 {
return nil, nil
}
deliveries, err := alertDeliveries(ctx, q, ids)
if err != nil {
return nil, err
}
for i := range out {
out[i].Deliveries = deliveries[out[i].ID]
}
return out, nil
}
// alertDeliveries returns each alert's newest deliveries with their attempts.
func alertDeliveries(ctx context.Context, q *postgresdb.Queries, alertIDs []int64) (map[int64][]alert.Delivery, error) {
rows, err := q.ListAlertDeliveries(ctx, alertIDs)
if err != nil {
return nil, err
}
byAlert := map[int64][]alert.Delivery{}
var deliveryIDs []int64
for _, r := range rows {
if len(byAlert[r.AlertID]) >= deliveriesPerAlert {
continue
}
byAlert[r.AlertID] = append(byAlert[r.AlertID], deliveryFromRow(r))
deliveryIDs = append(deliveryIDs, r.ID)
}
if len(deliveryIDs) == 0 {
return byAlert, nil
}
attempts, err := q.ListAlertAttempts(ctx, deliveryIDs)
if err != nil {
return nil, err
}
byDelivery := map[int64][]alert.Attempt{}
for _, a := range attempts {
byDelivery[a.DeliveryID] = append(byDelivery[a.DeliveryID], alert.Attempt{
N: a.Attempt, At: a.At, StatusCode: int(a.StatusCode), Error: a.Error,
})
}
for _, list := range byAlert {
for i := range list {
list[i].Attempts = byDelivery[list[i].ID]
}
}
return byAlert, nil
}
func deliveryFromRow(r postgresdb.AlertDelivery) alert.Delivery {
return alert.Delivery{
ID: r.ID, AlertID: r.AlertID, Event: r.Event, State: r.State,
CreatedAt: r.CreatedAt, NextAttemptAt: r.NextAttemptAt,
}
}
// Prune removes alerts closed before cutoff, with their deliveries.
func (s *Store) PruneAlerts(ctx context.Context, cutoff time.Time) (int64, error) {
return s.queries().PruneAlerts(ctx, pgtype.Timestamptz{Time: cutoff, Valid: true})
}
// ClaimDeliveries returns the due deliveries with their alerts.
func (s *Store) ClaimAlertDeliveries(ctx context.Context, limit int) ([]alert.Due, error) {
if limit <= 0 || limit > 100 {
limit = 20
}
var out []alert.Due
err := s.inTx(ctx, func(q *postgresdb.Queries) error {
rows, err := q.ClaimAlertDeliveries(ctx, int32(limit))
if err != nil {
return err
}
for _, r := range rows {
row, err := q.GetAlert(ctx, r.AlertID)
if err != nil {
return err
}
out = append(out, alert.Due{Delivery: deliveryFromRow(r), Alert: alertFromRow(row), Attempt: r.Attempts + 1})
}
return nil
})
return out, err
}
// RecordAttempt records one attempt and settles or reschedules the delivery.
func (s *Store) RecordAlertAttempt(ctx context.Context, o alert.Outcome) error {
return s.inTx(ctx, func(q *postgresdb.Queries) error {
d, err := q.LockAlertDelivery(ctx, o.DeliveryID)
if errors.Is(err, pgx.ErrNoRows) {
return alert.ErrNotFound
}
if err != nil {
return err
}
if d.State != alert.DeliveryPending {
return nil
}
now := time.Now().UTC()
params := postgresdb.SettleAlertDeliveryParams{ID: d.ID, State: alert.DeliveryPending, Attempts: d.Attempts, NextAttemptAt: d.NextAttemptAt}
switch {
case o.Skipped:
params.State = alert.DeliverySkipped
default:
params.Attempts++
if err := q.InsertAlertAttempt(ctx, postgresdb.InsertAlertAttemptParams{
DeliveryID: d.ID, Attempt: params.Attempts, StatusCode: int64(o.StatusCode), Error: o.Error,
}); err != nil {
return err
}
switch {
case o.OK():
params.State = alert.DeliveryDelivered
case params.Attempts >= alert.MaxDeliveryAttempts:
params.State = alert.DeliveryFailed
default:
params.NextAttemptAt = now.Add(alert.RetryDelay(params.Attempts))
}
}
if err := q.SettleAlertDelivery(ctx, params); err != nil {
return fmt.Errorf("settle alert delivery: %w", err)
}
return nil
})
}
@@ -0,0 +1,56 @@
-- Operator alerts: things that need a human, one row per (org, kind, subject).
-- Raising an open alert again bumps the row instead of adding one. A
-- condition-backed alert resolves when its condition clears; an event alert
-- stays until dismissed. Deliveries are the outbound notices (the notify
-- webhook) each raise or resolve owes, with every attempt kept.
-- +goose Up
CREATE TABLE alerts (
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
org_id text NOT NULL,
kind text NOT NULL,
subject text NOT NULL,
severity text NOT NULL CHECK (severity IN ('info', 'warning', 'action')),
title text NOT NULL,
body text NOT NULL DEFAULT '',
link text NOT NULL DEFAULT '',
is_condition boolean NOT NULL,
state text NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'resolved', 'dismissed')),
first_raised timestamptz NOT NULL,
last_seen timestamptz NOT NULL,
count bigint NOT NULL DEFAULT 1,
closed_by text NOT NULL DEFAULT '',
closed_at timestamptz,
UNIQUE (org_id, kind, subject)
);
CREATE INDEX idx_alerts_org_state ON alerts (org_id, state, id);
CREATE INDEX idx_alerts_closed ON alerts (closed_at) WHERE state <> 'open';
CREATE TABLE alert_deliveries (
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
alert_id bigint NOT NULL REFERENCES alerts (id) ON DELETE CASCADE,
event text NOT NULL CHECK (event IN ('raised', 'resolved')),
state text NOT NULL DEFAULT 'pending' CHECK (state IN ('pending', 'delivered', 'failed', 'skipped')),
created_at timestamptz NOT NULL DEFAULT now(),
next_attempt_at timestamptz NOT NULL DEFAULT now(),
attempts bigint NOT NULL DEFAULT 0
);
CREATE INDEX idx_alert_deliveries_due ON alert_deliveries (next_attempt_at) WHERE state = 'pending';
CREATE INDEX idx_alert_deliveries_alert ON alert_deliveries (alert_id, id);
CREATE TABLE alert_delivery_attempts (
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
delivery_id bigint NOT NULL REFERENCES alert_deliveries (id) ON DELETE CASCADE,
attempt bigint NOT NULL,
at timestamptz NOT NULL DEFAULT now(),
status_code bigint NOT NULL DEFAULT 0,
error text NOT NULL DEFAULT ''
);
CREATE INDEX idx_alert_delivery_attempts_delivery ON alert_delivery_attempts (delivery_id, id);
-- +goose Down
DROP TABLE alert_delivery_attempts;
DROP TABLE alert_deliveries;
DROP TABLE alerts;
@@ -0,0 +1,448 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: alerts.sql
package postgresdb
import (
"context"
"time"
"github.com/jackc/pgx/v5/pgtype"
)
const claimAlertDeliveries = `-- name: ClaimAlertDeliveries :many
UPDATE alert_deliveries SET next_attempt_at = now() + interval '2 minutes'
WHERE id IN (
SELECT d.id FROM alert_deliveries d
WHERE d.state = 'pending' AND d.next_attempt_at <= now()
ORDER BY d.id LIMIT $1 FOR UPDATE SKIP LOCKED)
RETURNING id, alert_id, event, state, created_at, next_attempt_at, attempts
`
func (q *Queries) ClaimAlertDeliveries(ctx context.Context, pageLimit int32) ([]AlertDelivery, error) {
rows, err := q.db.Query(ctx, claimAlertDeliveries, pageLimit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []AlertDelivery
for rows.Next() {
var i AlertDelivery
if err := rows.Scan(
&i.ID,
&i.AlertID,
&i.Event,
&i.State,
&i.CreatedAt,
&i.NextAttemptAt,
&i.Attempts,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const getAlert = `-- name: GetAlert :one
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
FROM alerts WHERE id = $1
`
func (q *Queries) GetAlert(ctx context.Context, id int64) (Alert, error) {
row := q.db.QueryRow(ctx, getAlert, id)
var i Alert
err := row.Scan(
&i.ID,
&i.OrgID,
&i.Kind,
&i.Subject,
&i.Severity,
&i.Title,
&i.Body,
&i.Link,
&i.IsCondition,
&i.State,
&i.FirstRaised,
&i.LastSeen,
&i.Count,
&i.ClosedBy,
&i.ClosedAt,
)
return i, err
}
const getAlertByKey = `-- name: GetAlertByKey :one
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
FROM alerts WHERE org_id = $1 AND kind = $2 AND subject = $3
`
type GetAlertByKeyParams struct {
OrgID string
Kind string
Subject string
}
func (q *Queries) GetAlertByKey(ctx context.Context, arg GetAlertByKeyParams) (Alert, error) {
row := q.db.QueryRow(ctx, getAlertByKey, arg.OrgID, arg.Kind, arg.Subject)
var i Alert
err := row.Scan(
&i.ID,
&i.OrgID,
&i.Kind,
&i.Subject,
&i.Severity,
&i.Title,
&i.Body,
&i.Link,
&i.IsCondition,
&i.State,
&i.FirstRaised,
&i.LastSeen,
&i.Count,
&i.ClosedBy,
&i.ClosedAt,
)
return i, err
}
const getOrgAlert = `-- name: GetOrgAlert :one
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
FROM alerts WHERE org_id = $1 AND id = $2
`
type GetOrgAlertParams struct {
OrgID string
ID int64
}
func (q *Queries) GetOrgAlert(ctx context.Context, arg GetOrgAlertParams) (Alert, error) {
row := q.db.QueryRow(ctx, getOrgAlert, arg.OrgID, arg.ID)
var i Alert
err := row.Scan(
&i.ID,
&i.OrgID,
&i.Kind,
&i.Subject,
&i.Severity,
&i.Title,
&i.Body,
&i.Link,
&i.IsCondition,
&i.State,
&i.FirstRaised,
&i.LastSeen,
&i.Count,
&i.ClosedBy,
&i.ClosedAt,
)
return i, err
}
const insertAlertAttempt = `-- name: InsertAlertAttempt :exec
INSERT INTO alert_delivery_attempts (delivery_id, attempt, status_code, error) VALUES ($1, $2, $3, $4)
`
type InsertAlertAttemptParams struct {
DeliveryID int64
Attempt int64
StatusCode int64
Error string
}
func (q *Queries) InsertAlertAttempt(ctx context.Context, arg InsertAlertAttemptParams) error {
_, err := q.db.Exec(ctx, insertAlertAttempt,
arg.DeliveryID,
arg.Attempt,
arg.StatusCode,
arg.Error,
)
return err
}
const insertAlertDelivery = `-- name: InsertAlertDelivery :exec
INSERT INTO alert_deliveries (alert_id, event) VALUES ($1, $2)
`
type InsertAlertDeliveryParams struct {
AlertID int64
Event string
}
func (q *Queries) InsertAlertDelivery(ctx context.Context, arg InsertAlertDeliveryParams) error {
_, err := q.db.Exec(ctx, insertAlertDelivery, arg.AlertID, arg.Event)
return err
}
const listAlertAttempts = `-- name: ListAlertAttempts :many
SELECT id, delivery_id, attempt, at, status_code, error
FROM alert_delivery_attempts WHERE delivery_id = ANY($1::bigint[]) ORDER BY delivery_id, id
`
func (q *Queries) ListAlertAttempts(ctx context.Context, deliveryIds []int64) ([]AlertDeliveryAttempt, error) {
rows, err := q.db.Query(ctx, listAlertAttempts, deliveryIds)
if err != nil {
return nil, err
}
defer rows.Close()
var items []AlertDeliveryAttempt
for rows.Next() {
var i AlertDeliveryAttempt
if err := rows.Scan(
&i.ID,
&i.DeliveryID,
&i.Attempt,
&i.At,
&i.StatusCode,
&i.Error,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listAlertDeliveries = `-- name: ListAlertDeliveries :many
SELECT id, alert_id, event, state, created_at, next_attempt_at, attempts
FROM alert_deliveries WHERE alert_id = ANY($1::bigint[]) ORDER BY alert_id, id DESC
`
func (q *Queries) ListAlertDeliveries(ctx context.Context, alertIds []int64) ([]AlertDelivery, error) {
rows, err := q.db.Query(ctx, listAlertDeliveries, alertIds)
if err != nil {
return nil, err
}
defer rows.Close()
var items []AlertDelivery
for rows.Next() {
var i AlertDelivery
if err := rows.Scan(
&i.ID,
&i.AlertID,
&i.Event,
&i.State,
&i.CreatedAt,
&i.NextAttemptAt,
&i.Attempts,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listAlerts = `-- name: ListAlerts :many
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
FROM alerts
WHERE org_id = $1 AND state = ANY($2::text[])
ORDER BY CASE severity WHEN 'action' THEN 3 WHEN 'warning' THEN 2 ELSE 1 END DESC, last_seen DESC, id DESC
LIMIT $3
`
type ListAlertsParams struct {
OrgID string
States []string
PageLimit int32
}
func (q *Queries) ListAlerts(ctx context.Context, arg ListAlertsParams) ([]Alert, error) {
rows, err := q.db.Query(ctx, listAlerts, arg.OrgID, arg.States, arg.PageLimit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Alert
for rows.Next() {
var i Alert
if err := rows.Scan(
&i.ID,
&i.OrgID,
&i.Kind,
&i.Subject,
&i.Severity,
&i.Title,
&i.Body,
&i.Link,
&i.IsCondition,
&i.State,
&i.FirstRaised,
&i.LastSeen,
&i.Count,
&i.ClosedBy,
&i.ClosedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockAlertDelivery = `-- name: LockAlertDelivery :one
SELECT id, alert_id, event, state, created_at, next_attempt_at, attempts
FROM alert_deliveries WHERE id = $1 FOR UPDATE
`
func (q *Queries) LockAlertDelivery(ctx context.Context, id int64) (AlertDelivery, error) {
row := q.db.QueryRow(ctx, lockAlertDelivery, id)
var i AlertDelivery
err := row.Scan(
&i.ID,
&i.AlertID,
&i.Event,
&i.State,
&i.CreatedAt,
&i.NextAttemptAt,
&i.Attempts,
)
return i, err
}
const lockAlertKey = `-- name: LockAlertKey :exec
SELECT pg_advisory_xact_lock(hashtextextended($1::text, 0))
`
// Operator alerts and their outbound deliveries (internal/domain/alert).
// Serialises raisers of one alert, so two first raises cannot both insert.
func (q *Queries) LockAlertKey(ctx context.Context, lockKey string) error {
_, err := q.db.Exec(ctx, lockAlertKey, lockKey)
return err
}
const pruneAlerts = `-- name: PruneAlerts :execrows
DELETE FROM alerts WHERE state <> 'open' AND closed_at < $1
`
func (q *Queries) PruneAlerts(ctx context.Context, closedAt pgtype.Timestamptz) (int64, error) {
result, err := q.db.Exec(ctx, pruneAlerts, closedAt)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const settleAlertDelivery = `-- name: SettleAlertDelivery :exec
UPDATE alert_deliveries SET state = $2, attempts = $3, next_attempt_at = $4 WHERE id = $1
`
type SettleAlertDeliveryParams struct {
ID int64
State string
Attempts int64
NextAttemptAt time.Time
}
func (q *Queries) SettleAlertDelivery(ctx context.Context, arg SettleAlertDeliveryParams) error {
_, err := q.db.Exec(ctx, settleAlertDelivery,
arg.ID,
arg.State,
arg.Attempts,
arg.NextAttemptAt,
)
return err
}
const taskAlertInfo = `-- name: TaskAlertInfo :one
SELECT org_id, title, workflow, park_class FROM tasks WHERE id = $1
`
type TaskAlertInfoRow struct {
OrgID string
Title string
Workflow string
ParkClass string
}
func (q *Queries) TaskAlertInfo(ctx context.Context, id int64) (TaskAlertInfoRow, error) {
row := q.db.QueryRow(ctx, taskAlertInfo, id)
var i TaskAlertInfoRow
err := row.Scan(
&i.OrgID,
&i.Title,
&i.Workflow,
&i.ParkClass,
)
return i, err
}
const upsertAlert = `-- name: UpsertAlert :one
INSERT INTO alerts (org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
ON CONFLICT (org_id, kind, subject) DO UPDATE SET
severity = excluded.severity, title = excluded.title, body = excluded.body, link = excluded.link,
is_condition = excluded.is_condition, state = excluded.state, first_raised = excluded.first_raised,
last_seen = excluded.last_seen, count = excluded.count, closed_by = excluded.closed_by, closed_at = excluded.closed_at
RETURNING id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
`
type UpsertAlertParams struct {
OrgID string
Kind string
Subject string
Severity string
Title string
Body string
Link string
IsCondition bool
State string
FirstRaised time.Time
LastSeen time.Time
Count int64
ClosedBy string
ClosedAt pgtype.Timestamptz
}
func (q *Queries) UpsertAlert(ctx context.Context, arg UpsertAlertParams) (Alert, error) {
row := q.db.QueryRow(ctx, upsertAlert,
arg.OrgID,
arg.Kind,
arg.Subject,
arg.Severity,
arg.Title,
arg.Body,
arg.Link,
arg.IsCondition,
arg.State,
arg.FirstRaised,
arg.LastSeen,
arg.Count,
arg.ClosedBy,
arg.ClosedAt,
)
var i Alert
err := row.Scan(
&i.ID,
&i.OrgID,
&i.Kind,
&i.Subject,
&i.Severity,
&i.Title,
&i.Body,
&i.Link,
&i.IsCondition,
&i.State,
&i.FirstRaised,
&i.LastSeen,
&i.Count,
&i.ClosedBy,
&i.ClosedAt,
)
return i, err
}
@@ -44,6 +44,43 @@ type AccessPolicyVersion struct {
UpdatedAt time.Time
}
type Alert struct {
ID int64
OrgID string
Kind string
Subject string
Severity string
Title string
Body string
Link string
IsCondition bool
State string
FirstRaised time.Time
LastSeen time.Time
Count int64
ClosedBy string
ClosedAt pgtype.Timestamptz
}
type AlertDelivery struct {
ID int64
AlertID int64
Event string
State string
CreatedAt time.Time
NextAttemptAt time.Time
Attempts int64
}
type AlertDeliveryAttempt struct {
ID int64
DeliveryID int64
Attempt int64
At time.Time
StatusCode int64
Error string
}
type ApplyStatus struct {
Process string
Kind string
@@ -0,0 +1,68 @@
-- Operator alerts and their outbound deliveries (internal/domain/alert).
-- name: LockAlertKey :exec
-- Serialises raisers of one alert, so two first raises cannot both insert.
SELECT pg_advisory_xact_lock(hashtextextended(sqlc.arg(lock_key)::text, 0));
-- name: GetAlertByKey :one
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
FROM alerts WHERE org_id = $1 AND kind = $2 AND subject = $3;
-- name: GetOrgAlert :one
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
FROM alerts WHERE org_id = $1 AND id = $2;
-- name: GetAlert :one
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
FROM alerts WHERE id = $1;
-- name: UpsertAlert :one
INSERT INTO alerts (org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
ON CONFLICT (org_id, kind, subject) DO UPDATE SET
severity = excluded.severity, title = excluded.title, body = excluded.body, link = excluded.link,
is_condition = excluded.is_condition, state = excluded.state, first_raised = excluded.first_raised,
last_seen = excluded.last_seen, count = excluded.count, closed_by = excluded.closed_by, closed_at = excluded.closed_at
RETURNING id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at;
-- name: ListAlerts :many
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
FROM alerts
WHERE org_id = $1 AND state = ANY(sqlc.arg(states)::text[])
ORDER BY CASE severity WHEN 'action' THEN 3 WHEN 'warning' THEN 2 ELSE 1 END DESC, last_seen DESC, id DESC
LIMIT sqlc.arg(page_limit);
-- name: PruneAlerts :execrows
DELETE FROM alerts WHERE state <> 'open' AND closed_at < $1;
-- name: InsertAlertDelivery :exec
INSERT INTO alert_deliveries (alert_id, event) VALUES ($1, $2);
-- name: ClaimAlertDeliveries :many
UPDATE alert_deliveries SET next_attempt_at = now() + interval '2 minutes'
WHERE id IN (
SELECT d.id FROM alert_deliveries d
WHERE d.state = 'pending' AND d.next_attempt_at <= now()
ORDER BY d.id LIMIT sqlc.arg(page_limit) FOR UPDATE SKIP LOCKED)
RETURNING id, alert_id, event, state, created_at, next_attempt_at, attempts;
-- name: LockAlertDelivery :one
SELECT id, alert_id, event, state, created_at, next_attempt_at, attempts
FROM alert_deliveries WHERE id = $1 FOR UPDATE;
-- name: SettleAlertDelivery :exec
UPDATE alert_deliveries SET state = $2, attempts = $3, next_attempt_at = $4 WHERE id = $1;
-- name: InsertAlertAttempt :exec
INSERT INTO alert_delivery_attempts (delivery_id, attempt, status_code, error) VALUES ($1, $2, $3, $4);
-- name: ListAlertDeliveries :many
SELECT id, alert_id, event, state, created_at, next_attempt_at, attempts
FROM alert_deliveries WHERE alert_id = ANY(sqlc.arg(alert_ids)::bigint[]) ORDER BY alert_id, id DESC;
-- name: ListAlertAttempts :many
SELECT id, delivery_id, attempt, at, status_code, error
FROM alert_delivery_attempts WHERE delivery_id = ANY(sqlc.arg(delivery_ids)::bigint[]) ORDER BY delivery_id, id;
-- name: TaskAlertInfo :one
SELECT org_id, title, workflow, park_class FROM tasks WHERE id = $1;
+1 -1
View File
@@ -338,7 +338,7 @@ func (s *Store) CancelExecution(ctx context.Context, taskID int64, reason, to st
if n == 0 {
return nil, storecontract.ErrStaleTransition
}
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
TaskID: taskID, FromStatus: execution.Status, ToStatus: to, Detail: clip(reason, 4000),
}); err != nil {
return nil, err
+7 -7
View File
@@ -276,7 +276,7 @@ func (s *Store) Transition(ctx context.Context, taskID int64, from, to, detail s
if n == 0 {
return storecontract.ErrStaleTransition
}
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
TaskID: taskID, FromStatus: from, ToStatus: to, Detail: clip(detail, 4000),
}); err != nil {
return err
@@ -291,7 +291,7 @@ func (s *Store) Transition(ctx context.Context, taskID int64, from, to, detail s
return err
}
if promoted > 0 {
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
TaskID: taskID, FromStatus: workflow.StatusPROpen, ToStatus: workflow.StatusQueued,
Detail: "queued the next review",
}); err != nil {
@@ -327,7 +327,7 @@ func (s *Store) ParkTask(ctx context.Context, taskID int64, from, detail, class
if n == 0 {
return storecontract.ErrStaleTransition
}
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
TaskID: taskID, FromStatus: from, ToStatus: workflow.StatusParked, Detail: clip(detail, 4000),
}); err != nil {
return err
@@ -409,7 +409,7 @@ func (s *Store) BeginRemediation(ctx context.Context, taskID int64, payload stri
if n == 0 {
return storecontract.ErrStaleTransition
}
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
TaskID: taskID, FromStatus: workflow.StatusPROpen, ToStatus: workflow.StatusQueued,
Detail: "review reaction queued remediation",
}); err != nil {
@@ -589,7 +589,7 @@ func (s *Store) RespondReviewGate(ctx context.Context, taskID int64, fromStatus,
if rereview {
detail = "operator requested a re-review"
}
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
TaskID: taskID, FromStatus: fromStatus, ToStatus: workflow.StatusQueued, Detail: detail,
}); err != nil {
return err
@@ -619,7 +619,7 @@ func (s *Store) requeue(ctx context.Context, taskID int64, fromStatus, wf, detai
if n == 0 {
return storecontract.ErrStaleTransition
}
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
TaskID: taskID, FromStatus: fromStatus, ToStatus: workflow.StatusQueued, Detail: detail,
}); err != nil {
return err
@@ -684,7 +684,7 @@ func (s *Store) RecoverStale(ctx context.Context) (int64, error) {
return 0, err
}
}
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
TaskID: execution.ID, FromStatus: workflow.StatusRunning, ToStatus: workflow.StatusQueued,
Detail: "re-queued after a crashed or replaced daemon",
}); err != nil {
@@ -0,0 +1,91 @@
package postgres
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/samcharles93/archie-core/internal/domain/alert"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
"github.com/samcharles93/archie-core/internal/taskstate"
)
// systemResolver is recorded as the resolver of an alert the store clears
// itself because the task moved on.
const systemResolver = "system"
// recordTransition writes a transition's audit row and the alerts that
// transition raises or clears, in the same transaction. Every task status
// move goes through it, so the alerts follow the state without a poller.
func recordTransition(ctx context.Context, q *postgresdb.Queries, p postgresdb.InsertTransitionParams) error {
if err := q.InsertTransition(ctx, p); err != nil {
return err
}
return syncTaskAlerts(ctx, q, p)
}
// needsHuman reports whether a task in status, parked with class, is waiting
// on an operator's decision.
func needsHuman(status, class string) bool {
return status == workflow.StatusWaitingHuman || (status == workflow.StatusParked && class == taskstate.ParkNeedsHuman)
}
// failed reports whether a task in status, parked with class, will not
// succeed without an operator starting it over.
func failed(status, class string) bool {
return status == workflow.StatusDead || (status == workflow.StatusParked && class == taskstate.ParkTerminal)
}
func syncTaskAlerts(ctx context.Context, q *postgresdb.Queries, p postgresdb.InsertTransitionParams) error {
leaving := p.FromStatus == workflow.StatusWaitingHuman || p.FromStatus == workflow.StatusParked
if !leaving && p.ToStatus != workflow.StatusWaitingHuman && p.ToStatus != workflow.StatusParked && p.ToStatus != workflow.StatusDead {
return nil
}
info, err := q.TaskAlertInfo(ctx, p.TaskID)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return err
}
subject := fmt.Sprintf("task:%d", p.TaskID)
link := fmt.Sprintf("/tasks/%d", p.TaskID)
name := fmt.Sprintf("Task #%d", p.TaskID)
described := name
if info.Title != "" {
described = fmt.Sprintf("%s %q", name, info.Title)
}
key := func(kind string) alert.Key {
return alert.Key{Org: org.OrgID(info.OrgID), Kind: kind, Subject: subject}
}
if needsHuman(p.ToStatus, info.ParkClass) {
body := described + " is waiting for your approval or review."
if p.ToStatus == workflow.StatusParked {
body = described + " is parked and needs a decision."
}
_, err := raiseAlert(ctx, q, alert.Input{
Key: key(alert.KindTaskNeedsHuman), Severity: alert.SeverityAction, Condition: true,
Title: name + " needs you", Body: body, Link: link,
})
if err != nil {
return err
}
} else if leaving {
if err := resolveAlert(ctx, q, key(alert.KindTaskNeedsHuman), systemResolver); err != nil {
return err
}
}
if failed(p.ToStatus, info.ParkClass) {
_, err := raiseAlert(ctx, q, alert.Input{
Key: key(alert.KindTaskFailed), Severity: alert.SeverityWarning,
Title: name + " failed", Body: described + " failed and will not run again until you retry it.", Link: link,
})
return err
}
return nil
}
+190
View File
@@ -0,0 +1,190 @@
// Alerts: the operator alert RPCs. A caller acting for a principal is
// confined to that principal's org; a service acting for no one names the org
// on the request.
package staterpc
import (
"context"
"errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/alert"
"github.com/samcharles93/archie-core/internal/domain/org"
)
var errAlertsUnavailable = status.Error(codes.Unavailable, "alert store unavailable")
// alertOrg is the org a call acts in.
func alertOrg(ctx context.Context, requested string) (org.OrgID, error) {
if id, ok := org.Scope(ctx); ok {
return id, nil
}
if requested == "" {
return "", status.Error(codes.InvalidArgument, "org_id is required")
}
return org.OrgID(requested), nil
}
func alertStatus(err error) error {
switch {
case errors.Is(err, alert.ErrInvalid):
return status.Error(codes.InvalidArgument, err.Error())
case errors.Is(err, alert.ErrNotFound):
return status.Error(codes.NotFound, alert.ErrNotFound.Error())
default:
return mapError(err)
}
}
func alertProto(a alert.Alert) *pb.Alert {
return &pb.Alert{
Id: a.ID, OrgId: string(a.Org), Kind: a.Kind, Subject: a.Subject,
Severity: string(a.Severity), Title: a.Title, Body: a.Body, Link: a.Link,
Condition: a.Condition, State: string(a.State),
FirstRaised: timestamp(a.FirstRaised), LastSeen: timestamp(a.LastSeen), Count: a.Count,
ClosedBy: a.ClosedBy, ClosedAt: timestamp(a.ClosedAt),
Deliveries: mapValues(a.Deliveries, alertDeliveryProto),
}
}
func alertValue(a *pb.Alert) alert.Alert {
return alert.Alert{
ID: a.GetId(),
Org: org.OrgID(a.GetOrgId()), Kind: a.GetKind(), Subject: a.GetSubject(),
Severity: alert.Severity(a.GetSeverity()), Title: a.GetTitle(), Body: a.GetBody(), Link: a.GetLink(),
Condition: a.GetCondition(), State: alert.State(a.GetState()),
FirstRaised: timeValue(a.GetFirstRaised()), LastSeen: timeValue(a.GetLastSeen()), Count: a.GetCount(),
ClosedBy: a.GetClosedBy(), ClosedAt: timeValue(a.GetClosedAt()),
Deliveries: mapValues(a.GetDeliveries(), alertDeliveryValue),
}
}
func alertDeliveryProto(d alert.Delivery) *pb.AlertDelivery {
return &pb.AlertDelivery{
Id: d.ID, Event: d.Event, State: d.State, CreatedAt: timestamp(d.CreatedAt),
Attempts: mapValues(d.Attempts, func(a alert.Attempt) *pb.AlertAttempt {
return &pb.AlertAttempt{N: a.N, At: timestamp(a.At), StatusCode: int64(a.StatusCode), Error: a.Error}
}),
}
}
func alertDeliveryValue(d *pb.AlertDelivery) alert.Delivery {
return alert.Delivery{
ID: d.GetId(), Event: d.GetEvent(), State: d.GetState(), CreatedAt: timeValue(d.GetCreatedAt()),
Attempts: mapValues(d.GetAttempts(), func(a *pb.AlertAttempt) alert.Attempt {
return alert.Attempt{N: a.GetN(), At: timeValue(a.GetAt()), StatusCode: int(a.GetStatusCode()), Error: a.GetError()}
}),
}
}
func (s *server) RaiseAlert(ctx context.Context, r *pb.RaiseAlertRequest) (*pb.RaiseAlertResponse, error) {
if s.deps.Alerts == nil {
return nil, errAlertsUnavailable
}
orgID, err := alertOrg(ctx, r.GetOrgId())
if err != nil {
return nil, err
}
stored, err := s.deps.Alerts.RaiseAlert(ctx, alert.Input{
Org: orgID, Kind: r.GetKind(), Subject: r.GetSubject(),
Severity: alert.Severity(r.GetSeverity()), Title: r.GetTitle(), Body: r.GetBody(), Link: r.GetLink(),
Condition: r.GetCondition(),
})
if err != nil {
return nil, alertStatus(err)
}
return &pb.RaiseAlertResponse{Alert: alertProto(stored)}, nil
}
func (s *server) ResolveAlert(ctx context.Context, r *pb.ResolveAlertRequest) (*pb.ResolveAlertResponse, error) {
if s.deps.Alerts == nil {
return nil, errAlertsUnavailable
}
orgID, err := alertOrg(ctx, r.GetOrgId())
if err != nil {
return nil, err
}
key := alert.Key{Org: orgID, Kind: r.GetKind(), Subject: r.GetSubject()}
if err := s.deps.Alerts.ResolveAlert(ctx, key, access.ActorFromContext(ctx)); err != nil {
return nil, alertStatus(err)
}
return &pb.ResolveAlertResponse{}, nil
}
func (s *server) DismissAlert(ctx context.Context, r *pb.DismissAlertRequest) (*pb.DismissAlertResponse, error) {
if s.deps.Alerts == nil {
return nil, errAlertsUnavailable
}
orgID, err := alertOrg(ctx, r.GetOrgId())
if err != nil {
return nil, err
}
if err := s.deps.Alerts.DismissAlert(ctx, orgID, r.GetId(), access.ActorFromContext(ctx)); err != nil {
return nil, alertStatus(err)
}
return &pb.DismissAlertResponse{}, nil
}
func (s *server) ListAlerts(ctx context.Context, r *pb.ListAlertsRequest) (*pb.ListAlertsResponse, error) {
if s.deps.Alerts == nil {
return nil, errAlertsUnavailable
}
orgID, err := alertOrg(ctx, r.GetOrgId())
if err != nil {
return nil, err
}
filter := alert.Filter{Limit: int(r.GetLimit())}
for _, st := range r.GetStates() {
filter.States = append(filter.States, alert.State(st))
}
alerts, err := s.deps.Alerts.ListAlerts(ctx, orgID, filter)
if err != nil {
return nil, alertStatus(err)
}
return &pb.ListAlertsResponse{Alerts: mapValues(alerts, alertProto)}, nil
}
// requireUnscoped refuses a caller confined to an org: the delivery queue
// spans every org.
func requireUnscoped(ctx context.Context) error {
if _, ok := org.Scope(ctx); ok {
return status.Error(codes.PermissionDenied, "alert deliveries are not available to an org-scoped caller")
}
return nil
}
func (s *server) ClaimAlertDeliveries(ctx context.Context, r *pb.ClaimAlertDeliveriesRequest) (*pb.ClaimAlertDeliveriesResponse, error) {
if s.deps.Alerts == nil {
return nil, errAlertsUnavailable
}
if err := requireUnscoped(ctx); err != nil {
return nil, err
}
due, err := s.deps.Alerts.ClaimAlertDeliveries(ctx, int(r.GetLimit()))
if err != nil {
return nil, alertStatus(err)
}
return &pb.ClaimAlertDeliveriesResponse{Due: mapValues(due, func(d alert.Due) *pb.DueAlertDelivery {
return &pb.DueAlertDelivery{Delivery: alertDeliveryProto(d.Delivery), Alert: alertProto(d.Alert), Attempt: d.Attempt}
})}, nil
}
func (s *server) RecordAlertAttempt(ctx context.Context, r *pb.RecordAlertAttemptRequest) (*pb.RecordAlertAttemptResponse, error) {
if s.deps.Alerts == nil {
return nil, errAlertsUnavailable
}
if err := requireUnscoped(ctx); err != nil {
return nil, err
}
err := s.deps.Alerts.RecordAlertAttempt(ctx, alert.Outcome{
DeliveryID: r.GetDeliveryId(), Skipped: r.GetSkipped(), StatusCode: int(r.GetStatusCode()), Error: r.GetError(),
})
if err != nil {
return nil, alertStatus(err)
}
return &pb.RecordAlertAttemptResponse{}, nil
}
@@ -0,0 +1,65 @@
// Alerts: the client half of the operator alert RPCs.
package staterpc
import (
"context"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/alert"
"github.com/samcharles93/archie-core/internal/domain/org"
)
var _ alert.Store = (*Client)(nil)
func (c *Client) RaiseAlert(ctx context.Context, in alert.Input) (alert.Alert, error) {
r, err := c.client.RaiseAlert(ctx, &pb.RaiseAlertRequest{
OrgId: string(in.Org), Kind: in.Kind, Subject: in.Subject, Severity: string(in.Severity),
Title: in.Title, Body: in.Body, Link: in.Link, Condition: in.Condition,
})
if err != nil {
return alert.Alert{}, unmapError(err)
}
return alertValue(r.GetAlert()), nil
}
func (c *Client) ResolveAlert(ctx context.Context, key alert.Key, _ string) error {
_, err := c.client.ResolveAlert(ctx, &pb.ResolveAlertRequest{OrgId: string(key.Org), Kind: key.Kind, Subject: key.Subject})
return unmapError(err)
}
func (c *Client) DismissAlert(ctx context.Context, orgID org.OrgID, id int64, _ string) error {
_, err := c.client.DismissAlert(ctx, &pb.DismissAlertRequest{OrgId: string(orgID), Id: id})
return unmapError(err)
}
func (c *Client) ListAlerts(ctx context.Context, orgID org.OrgID, filter alert.Filter) ([]alert.Alert, error) {
states := make([]string, len(filter.States))
for i, st := range filter.States {
states[i] = string(st)
}
r, err := c.client.ListAlerts(ctx, &pb.ListAlertsRequest{OrgId: string(orgID), States: states, Limit: int32(filter.Limit)})
if err != nil {
return nil, unmapError(err)
}
return mapValues(r.GetAlerts(), alertValue), nil
}
func (c *Client) ClaimAlertDeliveries(ctx context.Context, limit int) ([]alert.Due, error) {
r, err := c.client.ClaimAlertDeliveries(ctx, &pb.ClaimAlertDeliveriesRequest{Limit: int32(limit)})
if err != nil {
return nil, unmapError(err)
}
return mapValues(r.GetDue(), func(d *pb.DueAlertDelivery) alert.Due {
delivery := alertDeliveryValue(d.GetDelivery())
a := alertValue(d.GetAlert())
delivery.AlertID = a.ID
return alert.Due{Delivery: delivery, Alert: a, Attempt: d.GetAttempt()}
}), nil
}
func (c *Client) RecordAlertAttempt(ctx context.Context, o alert.Outcome) error {
_, err := c.client.RecordAlertAttempt(ctx, &pb.RecordAlertAttemptRequest{
DeliveryId: o.DeliveryID, Skipped: o.Skipped, StatusCode: int64(o.StatusCode), Error: o.Error,
})
return unmapError(err)
}
@@ -0,0 +1,209 @@
package staterpc
import (
"context"
"fmt"
"slices"
"strings"
"testing"
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/alert"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// fakeAlerts holds alerts in memory and applies the same transition rules the
// State Store does, so the test drives the RPC handlers' org handling and the
// domain's dedup, resolve and dismiss rules without a database.
type fakeAlerts struct {
alert.Store
next int64
alerts map[alert.Key]*alert.Alert
}
func (f *fakeAlerts) RaiseAlert(_ context.Context, in alert.Input) (alert.Alert, error) {
if err := in.Validate(); err != nil {
return alert.Alert{}, err
}
prev := f.alerts[in.Key]
next, _ := alert.Apply(prev, in, time.Now())
if prev == nil {
f.next++
next.ID = f.next
}
f.alerts[in.Key] = &next
return next, nil
}
func (f *fakeAlerts) ResolveAlert(_ context.Context, key alert.Key, by string) error {
if prev := f.alerts[key]; prev != nil {
next, _ := alert.Resolve(*prev, by, time.Now())
f.alerts[key] = &next
}
return nil
}
func (f *fakeAlerts) DismissAlert(_ context.Context, orgID org.OrgID, id int64, by string) error {
for key, a := range f.alerts {
if a.ID == id && key.Org == orgID {
next, _ := alert.Dismiss(*a, by, time.Now())
f.alerts[key] = &next
return nil
}
}
return alert.ErrNotFound
}
func (f *fakeAlerts) ListAlerts(_ context.Context, orgID org.OrgID, filter alert.Filter) ([]alert.Alert, error) {
states := filter.States
if len(states) == 0 {
states = []alert.State{alert.StateOpen}
}
var out []alert.Alert
for key, a := range f.alerts {
if key.Org == orgID && slices.Contains(states, a.State) {
out = append(out, *a)
}
}
slices.SortFunc(out, func(a, b alert.Alert) int { return strings.Compare(a.Subject, b.Subject) })
return out, nil
}
type alertStep struct {
as org.OrgID // the caller's scope; empty is a service acting for no one
op string // raise, event, resolve, dismiss or list
org string // the org the request names
subject string
states []string
want []string // list: "org subject state xcount"
code codes.Code
}
func TestAlerts(t *testing.T) {
const a, b = "org-a", "org-b"
cases := []struct {
name string
steps []alertStep
}{
{"raising again bumps one row", []alertStep{
{op: "raise", org: a, subject: "t1"},
{op: "raise", org: a, subject: "t1"},
{op: "raise", org: a, subject: "t1"},
{op: "raise", org: a, subject: "t2"},
{op: "list", org: a, want: []string{"org-a t1 open x3", "org-a t2 open x1"}},
}},
{"a condition alert resolves itself", []alertStep{
{op: "raise", org: a, subject: "t1"},
{op: "resolve", org: a, subject: "t1"},
{op: "resolve", org: a, subject: "t1"},
{op: "list", org: a},
{op: "list", org: a, states: []string{"resolved"}, want: []string{"org-a t1 resolved x1"}},
}},
{"an event alert is not resolved by a check", []alertStep{
{op: "event", org: a, subject: "t1"},
{op: "resolve", org: a, subject: "t1"},
{op: "list", org: a, want: []string{"org-a t1 open x1"}},
}},
{"a dismissed condition stays snoozed until it clears and recurs", []alertStep{
{op: "raise", org: a, subject: "t1"},
{op: "dismiss", as: a, subject: "t1"},
{op: "raise", org: a, subject: "t1"},
{op: "list", org: a},
{op: "resolve", org: a, subject: "t1"},
{op: "raise", org: a, subject: "t1"},
{op: "list", org: a, want: []string{"org-a t1 open x1"}},
}},
{"a dismissed event comes back when it happens again", []alertStep{
{op: "event", org: a, subject: "t1"},
{op: "dismiss", as: a, subject: "t1"},
{op: "list", org: a},
{op: "event", org: a, subject: "t1"},
{op: "list", org: a, want: []string{"org-a t1 open x1"}},
}},
{"orgs never see each other's alerts", []alertStep{
{op: "raise", org: a, subject: "t1"},
{op: "raise", org: b, subject: "t1"},
{op: "raise", org: b, subject: "t2"},
{op: "list", as: a, want: []string{"org-a t1 open x1"}},
{op: "list", as: b, org: a, want: []string{"org-b t1 open x1", "org-b t2 open x1"}},
}},
{"a scoped caller cannot reach another org", []alertStep{
{op: "raise", org: a, subject: "t1"},
{op: "dismiss", as: b, org: a, subject: "t1", code: codes.NotFound},
{op: "raise", as: b, org: a, subject: "t9"},
{op: "list", as: a, want: []string{"org-a t1 open x1"}},
{op: "list", as: b, want: []string{"org-b t9 open x1"}},
}},
{"a service must name the org", []alertStep{
{op: "raise", subject: "t1", code: codes.InvalidArgument},
}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
s := &server{deps: Deps{Alerts: &fakeAlerts{alerts: map[alert.Key]*alert.Alert{}}}}
for i, step := range tc.steps {
ctx := context.Background()
if step.as != "" {
ctx = org.WithScope(ctx, step.as)
}
got, err := runAlertStep(ctx, s, step)
if status.Code(err) != step.code {
t.Fatalf("step %d (%s): code %v, want %v (%v)", i, step.op, status.Code(err), step.code, err)
}
if step.op == "list" && !slices.Equal(got, step.want) {
t.Fatalf("step %d: listed %q, want %q", i, got, step.want)
}
}
})
}
}
func runAlertStep(ctx context.Context, s *server, step alertStep) ([]string, error) {
switch step.op {
case "raise", "event":
_, err := s.RaiseAlert(ctx, &pb.RaiseAlertRequest{
OrgId: step.org, Kind: "k", Subject: step.subject, Severity: "action", Title: "t",
Condition: step.op == "raise",
})
return nil, err
case "resolve":
_, err := s.ResolveAlert(ctx, &pb.ResolveAlertRequest{OrgId: step.org, Kind: "k", Subject: step.subject})
return nil, err
case "dismiss":
// The alert's id is looked up under the org the step names, or the
// caller's own.
owner := cmpOr(step.org, string(step.as))
listed, err := s.deps.Alerts.ListAlerts(ctx, org.OrgID(owner), alert.Filter{})
if err != nil {
return nil, err
}
id := int64(-1)
for _, a := range listed {
if a.Subject == step.subject {
id = a.ID
}
}
_, err = s.DismissAlert(ctx, &pb.DismissAlertRequest{OrgId: step.org, Id: id})
return nil, err
default:
r, err := s.ListAlerts(ctx, &pb.ListAlertsRequest{OrgId: step.org, States: step.states})
var out []string
for _, a := range r.GetAlerts() {
out = append(out, fmt.Sprintf("%s %s %s x%d", a.GetOrgId(), a.GetSubject(), a.GetState(), a.GetCount()))
}
return out, err
}
}
func cmpOr(values ...string) string {
for _, v := range values {
if v != "" {
return v
}
}
return ""
}
@@ -19,6 +19,7 @@ import (
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/alert"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/mapping"
@@ -143,6 +144,9 @@ type Deps struct {
// Denials records and lists denial records. Optional: nil disables the
// pair with codes.Unavailable.
Denials access.DenialStore
// Alerts is the operator alert store. Optional: nil answers the alert
// RPCs with codes.Unavailable.
Alerts alert.Store
// Orgs persists orgs, workspaces, memberships and agent assignments.
// Optional: nil answers the org RPCs with codes.Unavailable.
Orgs org.Repository
+8
View File
@@ -24,3 +24,11 @@ func VerifyHMAC(body []byte, signature, secret string) bool {
mac.Write(body)
return hmac.Equal(supplied, mac.Sum(nil))
}
// SignHMAC is the "sha256=" hex HMAC-SHA256 of body, the form VerifyHMAC
// accepts.
func SignHMAC(body []byte, secret string) string {
mac := hmac.New(sha256.New, []byte(secret))
mac.Write(body)
return "sha256=" + hex.EncodeToString(mac.Sum(nil))
}
+122
View File
@@ -0,0 +1,122 @@
package webui
import (
"context"
"errors"
"net/http"
"strconv"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/alert"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// AlertSource is the alert surface the dashboard reads and dismisses
// through. The caller's org is the only one it can reach.
type AlertSource interface {
ListAlerts(ctx context.Context, orgID org.OrgID, filter alert.Filter) ([]alert.Alert, error)
DismissAlert(ctx context.Context, orgID org.OrgID, id int64, by string) error
}
type alertView struct {
ID int64 `json:"id"`
Kind string `json:"kind"`
Subject string `json:"subject"`
Severity string `json:"severity"`
Title string `json:"title"`
Body string `json:"body"`
Link string `json:"link,omitempty"`
Condition bool `json:"condition"`
State string `json:"state"`
FirstRaised time.Time `json:"first_raised"`
LastSeen time.Time `json:"last_seen"`
Count int64 `json:"count"`
ClosedBy string `json:"closed_by,omitempty"`
ClosedAt *time.Time `json:"closed_at,omitempty"`
Deliveries []deliveryView `json:"deliveries"`
}
type deliveryView struct {
Event string `json:"event"`
State string `json:"state"`
Created time.Time `json:"created_at"`
Attempts []attemptView `json:"attempts"`
}
type attemptView struct {
N int64 `json:"n"`
At time.Time `json:"at"`
StatusCode int `json:"status_code,omitempty"`
Error string `json:"error,omitempty"`
}
func viewOfAlert(a alert.Alert) alertView {
view := alertView{
ID: a.ID, Kind: a.Kind, Subject: a.Subject, Severity: string(a.Severity), Title: a.Title,
Body: a.Body, Link: a.Link, Condition: a.Condition, State: string(a.State),
FirstRaised: a.FirstRaised, LastSeen: a.LastSeen, Count: a.Count, ClosedBy: a.ClosedBy,
Deliveries: make([]deliveryView, 0, len(a.Deliveries)),
}
if !a.ClosedAt.IsZero() {
view.ClosedAt = &a.ClosedAt
}
for _, d := range a.Deliveries {
dv := deliveryView{Event: d.Event, State: d.State, Created: d.CreatedAt, Attempts: make([]attemptView, 0, len(d.Attempts))}
for _, at := range d.Attempts {
dv.Attempts = append(dv.Attempts, attemptView{N: at.N, At: at.At, StatusCode: at.StatusCode, Error: at.Error})
}
view.Deliveries = append(view.Deliveries, dv)
}
return view
}
// handleAlerts lists the caller's org's alerts: open ones unless ?state names
// others (comma separated), most severe first.
func (s *Server) handleAlerts(w http.ResponseWriter, r *http.Request) {
if s.Alerts == nil {
http.Error(w, "alerts unavailable", http.StatusServiceUnavailable)
return
}
filter := alert.Filter{}
if states := r.URL.Query().Get("state"); states != "" {
for state := range strings.SplitSeq(states, ",") {
filter.States = append(filter.States, alert.State(strings.TrimSpace(state)))
}
}
alerts, err := s.Alerts.ListAlerts(r.Context(), policyOrg(r), filter)
if err != nil {
s.Log.Error("list alerts", "err", err)
http.Error(w, "list alerts failed", http.StatusBadGateway)
return
}
views := make([]alertView, len(alerts))
for i, a := range alerts {
views[i] = viewOfAlert(a)
}
writeJSON(w, map[string]any{"alerts": views})
}
// handleAlertDismiss dismisses one open alert of the caller's org.
func (s *Server) handleAlertDismiss(w http.ResponseWriter, r *http.Request) {
if s.Alerts == nil {
http.Error(w, "alerts unavailable", http.StatusServiceUnavailable)
return
}
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.Error(w, "invalid alert id", http.StatusBadRequest)
return
}
err = s.Alerts.DismissAlert(r.Context(), policyOrg(r), id, access.ActorFromContext(r.Context()))
switch {
case errors.Is(err, alert.ErrNotFound):
http.Error(w, "alert not found", http.StatusNotFound)
case err != nil:
s.Log.Error("dismiss alert", "err", err)
http.Error(w, "dismiss alert failed", http.StatusBadGateway)
default:
w.WriteHeader(http.StatusNoContent)
}
}
+6
View File
@@ -94,6 +94,10 @@ type Server struct {
// dashboard.
ApplyStatus storecontract.ApplyStatusStore
// Alerts lists and dismisses the caller's org's operator alerts. Nil
// answers 503.
Alerts AlertSource
// Presence lists every service instance's record, behind the services
// card. Nil answers 503.
Presence storecontract.PresenceStore
@@ -253,6 +257,8 @@ func (s *Server) registerCoreRoutes(mux *http.ServeMux) {
mux.HandleFunc("POST /api/channels/{id}/reload", instanceOnly(s.handleChannelReload))
mux.HandleFunc("GET /api/version", s.handleVersion)
mux.HandleFunc("GET /api/capabilities", s.handleCapabilities)
mux.HandleFunc("GET /api/alerts", s.handleAlerts)
mux.HandleFunc("POST /api/alerts/{id}/dismiss", s.handleAlertDismiss)
}
func (s *Server) registerTaskRoutes(mux *http.ServeMux) {
+96
View File
@@ -279,6 +279,19 @@ service StateStoreService {
rpc SetMembership(SetMembershipRequest) returns (SetMembershipResponse);
rpc RemoveMembership(RemoveMembershipRequest) returns (RemoveMembershipResponse);
rpc AssignAgent(AssignAgentRequest) returns (AssignAgentResponse);
// Operator alerts (internal/domain/alert). A caller acting for a principal
// reads, dismisses and raises only in that principal's org; a request org is
// ignored for it. A service acting for no one names the org itself.
// RaiseAlert and ResolveAlert are idempotent, so a periodic check can call
// them every tick. ClaimAlertDeliveries and RecordAlertAttempt serve the
// outbound webhook and refuse a caller scoped to an org.
rpc RaiseAlert(RaiseAlertRequest) returns (RaiseAlertResponse);
rpc ResolveAlert(ResolveAlertRequest) returns (ResolveAlertResponse);
rpc DismissAlert(DismissAlertRequest) returns (DismissAlertResponse);
rpc ListAlerts(ListAlertsRequest) returns (ListAlertsResponse);
rpc ClaimAlertDeliveries(ClaimAlertDeliveriesRequest) returns (ClaimAlertDeliveriesResponse);
rpc RecordAlertAttempt(RecordAlertAttemptRequest) returns (RecordAlertAttemptResponse);
}
message RegisterTaskGrantRequest {
@@ -1613,3 +1626,86 @@ message CallerModelsResponse {
string org_id = 1;
map<string, string> aliases = 2;
}
// Alert mirrors internal/domain/alert.Alert. Severity is info, warning or
// action; state is open, resolved or dismissed.
message Alert {
int64 id = 1;
string org_id = 2;
string kind = 3;
string subject = 4;
string severity = 5;
string title = 6;
string body = 7;
string link = 8;
bool condition = 9;
string state = 10;
google.protobuf.Timestamp first_raised = 11;
google.protobuf.Timestamp last_seen = 12;
int64 count = 13;
string closed_by = 14;
google.protobuf.Timestamp closed_at = 15;
repeated AlertDelivery deliveries = 16;
}
// AlertDelivery is one outbound notice an alert owed. Event is raised or
// resolved; state is pending, delivered, failed or skipped.
message AlertDelivery {
int64 id = 1;
string event = 2;
string state = 3;
google.protobuf.Timestamp created_at = 4;
repeated AlertAttempt attempts = 5;
}
message AlertAttempt {
int64 n = 1;
google.protobuf.Timestamp at = 2;
int64 status_code = 3;
string error = 4;
}
message RaiseAlertRequest {
string org_id = 1;
string kind = 2;
string subject = 3;
string severity = 4;
string title = 5;
string body = 6;
string link = 7;
// condition is true when the raiser resolves the alert itself once the
// condition clears; an event alert stays until dismissed.
bool condition = 8;
}
message RaiseAlertResponse { Alert alert = 1; }
message ResolveAlertRequest {
string org_id = 1;
string kind = 2;
string subject = 3;
}
message ResolveAlertResponse {}
message DismissAlertRequest {
string org_id = 1;
int64 id = 2;
}
message DismissAlertResponse {}
message ListAlertsRequest {
string org_id = 1;
// states defaults to open.
repeated string states = 2;
int32 limit = 3;
}
message ListAlertsResponse { repeated Alert alerts = 1; }
message ClaimAlertDeliveriesRequest { int32 limit = 1; }
message DueAlertDelivery {
AlertDelivery delivery = 1;
Alert alert = 2;
// attempt is the number of this try, counting from one.
int64 attempt = 3;
}
message ClaimAlertDeliveriesResponse { repeated DueAlertDelivery due = 1; }
message RecordAlertAttemptRequest {
int64 delivery_id = 1;
bool skipped = 2;
int64 status_code = 3;
// error is empty on success.
string error = 4;
}
message RecordAlertAttemptResponse {}
+1 -1
View File
@@ -1,3 +1,3 @@
import{$n as e,A as t,An as n,Bn as r,Bt as i,Dn as a,En as o,Et as s,Fn as c,Gn as l,Hn as u,In as d,Jn as f,Jt as p,Kn as m,Ln as h,Mn as g,Nn as ee,O as te,Pn as _,Qn as v,R as y,Rn as ne,S as re,Sn as b,St as x,U as ie,Un as ae,Ut as S,V as oe,Vn as se,Wn as C,Xn as w,Y as T,Yn as E,Zn as ce,_ as D,_n as le,dn as ue,g as de,ht as fe,i as O,ir as k,jn as pe,kn as A,kt as j,l as me,lt as he,m as ge,mn as _e,mt as ve,n as ye,nt as be,on as xe,ot as Se,pt as Ce,qn as M,r as we,s as Te,tt as Ee,w as De,wn as Oe,xn as ke,y as Ae,yt as je,z as Me,zn as N}from"./PageHeader.js";var Ne=void 0,Pe=typeof window<`u`&&window.trustedTypes;if(Pe)try{Ne=Pe.createPolicy(`vue`,{createHTML:e=>e})}catch{}var Fe=Ne?e=>Ne.createHTML(e):e=>e,Ie=`http://www.w3.org/2000/svg`,Le=`http://www.w3.org/1998/Math/MathML`,P=typeof document<`u`?document:null,Re=P&&P.createElement(`template`),ze={insert:(e,t,n)=>{t.insertBefore(e,n||null)},remove:e=>{let t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,n,r)=>{let i=t===`svg`?P.createElementNS(Ie,e):t===`mathml`?P.createElementNS(Le,e):n?P.createElement(e,{is:n}):P.createElement(e);return e===`select`&&r&&r.multiple!=null&&i.setAttribute(`multiple`,r.multiple),i},createText:e=>P.createTextNode(e),createComment:e=>P.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>P.querySelector(e),setScopeId(e,t){e.setAttribute(t,``)},insertStaticContent(e,t,n,r,i,a){let o=n?n.previousSibling:t.lastChild;if(i&&(i===a||i.nextSibling))for(;t.insertBefore(i.cloneNode(!0),n),i!==a&&(i=i.nextSibling););else{Re.innerHTML=Fe(r===`svg`?`<svg>${e}</svg>`:r===`mathml`?`<math>${e}</math>`:e);let i=Re.content;if(r===`svg`||r===`mathml`){let e=i.firstChild;for(;e.firstChild;)i.appendChild(e.firstChild);i.removeChild(e)}t.insertBefore(i,n)}return[o?o.nextSibling:t.firstChild,n?n.previousSibling:t.lastChild]}},F=`transition`,Be=`animation`,Ve=Symbol(`_vtc`),He={name:String,type:String,css:{type:Boolean,default:!0},duration:[String,Number,Object],enterFromClass:String,enterActiveClass:String,enterToClass:String,appearFromClass:String,appearActiveClass:String,appearToClass:String,leaveFromClass:String,leaveActiveClass:String,leaveToClass:String},Ue=_({},we,He),We=(e=>(e.displayName=`Transition`,e.props=Ue,e))((e,{slots:t})=>oe(ye,Ke(e),t)),I=(e,t=[])=>{N(e)?e.forEach(e=>e(...t)):e&&e(...t)},Ge=e=>e?N(e)?e.some(e=>e.length>1):e.length>1:!1;function Ke(e){let t={};for(let n in e)n in He||(t[n]=e[n]);if(e.css===!1)return t;let{name:n=`v`,type:r,duration:i,enterFromClass:a=`${n}-enter-from`,enterActiveClass:o=`${n}-enter-active`,enterToClass:s=`${n}-enter-to`,appearFromClass:c=a,appearActiveClass:l=o,appearToClass:u=s,leaveFromClass:d=`${n}-leave-from`,leaveActiveClass:f=`${n}-leave-active`,leaveToClass:p=`${n}-leave-to`}=e,m=qe(i),h=m&&m[0],g=m&&m[1],{onBeforeEnter:ee,onEnter:te,onEnterCancelled:v,onLeave:y,onLeaveCancelled:ne,onBeforeAppear:re=ee,onAppear:b=te,onAppearCancelled:x=v}=t,ie=(e,t,n,r)=>{e._enterCancelled=r,R(e,t?u:s),R(e,t?l:o),n&&n()},ae=(e,t)=>{e._isLeaving=!1,R(e,d),R(e,p),R(e,f),t&&t()},S=e=>(t,n)=>{let i=e?b:te,o=()=>ie(t,e,n);I(i,[t,o]),Ye(()=>{R(t,e?c:a),L(t,e?u:s),Ge(i)||Ze(t,r,h,o)})};return _(t,{onBeforeEnter(e){I(ee,[e]),L(e,a),L(e,o)},onBeforeAppear(e){I(re,[e]),L(e,c),L(e,l)},onEnter:S(!1),onAppear:S(!0),onLeave(e,t){e._isLeaving=!0;let n=()=>ae(e,t);L(e,d),e._enterCancelled?(L(e,f),tt(e)):(tt(e),L(e,f)),Ye(()=>{e._isLeaving&&(R(e,d),L(e,p),Ge(y)||Ze(e,r,g,n))}),I(y,[e,n])},onEnterCancelled(e){ie(e,!1,void 0,!0),I(v,[e])},onAppearCancelled(e){ie(e,!0,void 0,!0),I(x,[e])},onLeaveCancelled(e){ae(e),I(ne,[e])}})}function qe(e){if(e==null)return null;if(u(e))return[Je(e.enter),Je(e.leave)];{let t=Je(e);return[t,t]}}function Je(e){return k(e)}function L(e,t){t.split(/\s+/).forEach(t=>t&&e.classList.add(t)),(e[Ve]||(e[Ve]=new Set)).add(t)}function R(e,t){t.split(/\s+/).forEach(t=>t&&e.classList.remove(t));let n=e[Ve];n&&(n.delete(t),n.size||(e[Ve]=void 0))}function Ye(e){requestAnimationFrame(()=>{requestAnimationFrame(e)})}var Xe=0;function Ze(e,t,n,r){let i=e._endId=++Xe,a=()=>{i===e._endId&&r()};if(n!=null)return setTimeout(a,n);let{type:o,timeout:s,propCount:c}=Qe(e,t);if(!o)return r();let l=o+`end`,u=0,d=()=>{e.removeEventListener(l,f),a()},f=t=>{t.target===e&&++u>=c&&d()};setTimeout(()=>{u<c&&d()},s+1),e.addEventListener(l,f)}function Qe(e,t){let n=window.getComputedStyle(e),r=e=>(n[e]||``).split(`, `),i=r(`${F}Delay`),a=r(`${F}Duration`),o=$e(i,a),s=r(`${Be}Delay`),c=r(`${Be}Duration`),l=$e(s,c),u=null,d=0,f=0;t===F?o>0&&(u=F,d=o,f=a.length):t===Be?l>0&&(u=Be,d=l,f=c.length):(d=Math.max(o,l),u=d>0?o>l?F:Be:null,f=u?u===F?a.length:c.length:0);let p=u===F&&/\b(?:transform|all)(?:,|$)/.test(r(`${F}Property`).toString());return{type:u,timeout:d,propCount:f,hasTransform:p}}function $e(e,t){for(;e.length<t.length;)e=e.concat(e);return Math.max(...t.map((t,n)=>et(t)+et(e[n])))}function eLine truncated
`))),e[V]=B(i);let a=r||i.props&&i.props.type===`number`;z(e,t?`change`:`input`,t=>{t.target.composing||e[V](an(e.value,n,a))}),(n||a)&&z(e,`change`,()=>{e.value=an(e.value,n,a)}),t||(z(e,`compositionstart`,tn),z(e,`compositionend`,nn),z(e,`change`,nn))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[rn];delete e[rn],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[V](an(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[V]=B(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?ce(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)}},sn={deep:!0,created(e,t,n){e[V]=B(n),z(e,`change`,()=>{let t=e._modelValue,n=pn(e),r=e.checked,i=e[V];if(N(t)){let e=w(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(l(t)){let e=new Set(t);r?e.add(n):e.delete(n),i(e)}else i(mn(e,r))})},mounted:cn,beforeUpdate(e,t,n){e[V]=B(n),cn(e,t,n)}};function cn(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(N(t))i=w(t,r.props.value)>-1;else if(l(t))i=t.has(r.props.value);else{if(t===n)return;i=E(t,mn(e,!0))}e.checked!==i&&(e.checked=i)}var ln={created(e,{value:t},n){e.checked=E(t,n.props.value),e[V]=B(n),z(e,`change`,()=>{e[V](pn(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[V]=B(r),t!==n&&(e.checked=E(t,r.props.value))}},un={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,z(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?ce(pn(e)):pn(e)),r=e.multiple,i=r?l(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?N(i)?t.slice():t:i];try{e[V](i)}finally{be(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[V]=B(r)},mounted(e,{value:t}){fn(e,t)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[V]=B(n)},updated(e,{value:t}){let n=e._pendingValue;e._pendingValue=void 0,(!n||n[0]!==e.multiple||!dn(t,n[1],n[0]))&&fn(e,t)}};function dn(e,t,n){if(!n||N(e))return E(e,t);if(l(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function fn(e,t){let n=e.multiple,r=N(t);if(!n||r||l(t)){for(let i=0,a=e.options.length;i<a;i++){let a=e.options[i],o=pn(a);if(n){if(r){let e=typeof o;a.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(o)):w(t,o)>-1}else a.selected=t.has(o)}else if(E(pn(a),t)){e.selectedIndex!==i&&(e.selectedIndex=i);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function pn(e){return`_value`in e?e._value:e.value}function mn(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var hn={created(e,t,n){_n(e,t,n,null,`created`)},mounted(e,t,n){_n(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){_n(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){_n(e,t,n,r,`updated`)}};function gn(e,t){switch(e){case`SELECT`:return un;case`TEXTAREA`:return on;default:switch(t){case`checkbox`:return sn;case`radio`:return ln;default:return on}}}function _n(e,t,n,r,i){let a=gn(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function vn(){on.getSSRProps=({value:e})=>({value:e}),ln.getSSRProps=({value:e},t)=>{if(t.props&&E(t.props.value,e))return{checked:!0}},sn.getSSRProps=({value:e},t)=>{if(N(e)){if(t.props&&w(e,t.props.value)>-1)return{checked:!0}}else if(l(e)){if(t.props&&e.has(t.props.value))return{checked:!0}}else if(e)return{checked:!0}},hn.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=gn(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var yn=[`ctrl`,`shift`,`alt`,`meta`],bn={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)=>yn.some(n=>e[`${n}Key`]&&!t.includes(n))},xn=(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=bn[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},Sn={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},Cn=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`);return n[r]||(n[r]=(n=>{if(!(`key`in n))return;let r=d(n.key);if(t.some(e=>e===r||Sn[e]===r))return e(n)}))},wn=_({patchProp:Pt},ze),Tn,En=!1;function Dn(){return Tn||=De(wn)}function On(){return Tn=En?Tn:re(wn),En=!0,Tn}var kn=((...e)=>{Dn().render(...e)}),An=((...e)=>{On().hydrate(...e)}),jn=((...e)=>{let t=Dn().createApp(...e),{mount:n}=t;return t.mount=e=>{let i=Pn(e);if(!i)return;let a=t._component;!r(a)&&!a.render&&!a.template&&(a.template=i.innerHTML),i.nodeType===1&&(i.textContent=``);let o=n(i,!1,Nn(i));return i instanceof Element&&(i.removeAttribute(`v-cloak`),i.setAttribute(`data-v-app`,``)),o},t}),Mn=((...e)=>{let t=On().createApp(...e),{moun Line truncated
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var ui;function di(e){ui=e}var fi=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function pi(e){let t=e instanceof fi?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 mi(e,t){let n=await fetch(e,t);if(ui?.(n.status===401),!n.ok)throw new fi(await li(n),n.status);return n}async function $(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=ci,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 mi(e,s);return a?await c.json():void 0}var hi={health:()=>$(`/health/detailed`),services:()=>$(`/api/services`),policies:()=>$(`/api/access/policies`),putPolicy:e=>$(`/api/access/policies`,{method:`PUT`,body:e}),deletePolicy:e=>$(`/api/access/policies`,{method:`DELETE`,body:e,parse:!1}),orgs:()=>$(`/api/orgs`),orgCreate:e=>$(`/api/orgs`,{method:`POST`,body:e}),org:e=>$(`/api/orgs/${encodeURIComponent(e)}`),orgWorkspaces:e=>$(`/api/orgs/${encodeURIComponent(e)}/workspaces`),createOrgWorkspace:(e,t)=>$(`/api/orgs/${encodeURIComponent(e)}/workspaces`,{method:`POST`,body:t}),orgMembers:e=>$(`/api/orgs/${encodeURIComponent(e)}/members`),addOrgMember:(e,t)=>$(`/api/orgs/${encodeURIComponent(e)}/members`,{method:`POST`,body:t}),setOrgMember:(e,t,n)=>$(`/api/orgs/${encodeURIComponent(e)}/members/${encodeURIComponent(t)}`,{method:`PUT`,body:n}),removeOrgMember:(e,t,n)=>$(`/api/orgs/${encodeURIComponent(e)}/members/${encodeURIComponent(t)}`+Q({workspace:n}),{method:`DELETE`,parse:!1}),assignOrgAgent:(e,t)=>$(`/api/orgs/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}`,{method:`PUT`}),summary:()=>$(`/api/summary`),tasks:()=>$(`/api/tasks`),taskPage:async e=>{let t=await mi(`/api/tasks`+Q(e),{headers:{Accept:`application/json`},signal:AbortSignal.timeout(ci)});return{tasks:await t.json(),next:t.headers.get(`X-Next-Cursor`)}},taskMeta:()=>$(`/api/task-meta`),task:e=>$(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>$(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>$(`/api/tasks/${encodeURIComponent(e)}/changes`+Q(t)),taskDebug:(e,t)=>$(`/api/tasks/${encodeURIComponent(e)}/debug`+Q(t)),taskAction:(e,t,n)=>$(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t,...n}}),setup:()=>$(`/api/setup`),capabilities:()=>$(`/api/capabilities`),workflows:()=>$(`/api/workflows`),workflowEnabled:(e,t)=>$(`/api/workflows/${encodeURIComponent(e)}/enabled`,{method:`PUT`,body:{enabled:t},parse:!1}),workRequest:e=>$(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>$(`/api/skills`),channels:()=>$(`/api/channels`),curators:()=>$(`/api/curators`),channelReload:e=>$(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>$(`/api/config`),logs:e=>$(`/api/logs`+Q(e)),taskLogs:(e,t)=>$(`/api/tasks/${encodeURIComponent(e)}/logs`+Q(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),version:()=>$(`/api/version`),updateSnapshot:()=>$(`/api/chat/update`),updateDefer:e=>$(`/api/chat/update/defer`,{method:`POST`,body:{snapshot:e}}),updateInstall:e=>$(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:9e5}),captures:e=>$(`/api/captures`+Q({limit:e})),eventTypes:e=>$(`/api/event-types`+Q({workspace:e})),eventTypeCreate:e=>$(`/api/event-types`,{method:`POST`,body:e}),eventTypeUpdate:(e,t)=>$(`/api/event-types/${encodeURIComponent(e)}`,{method:`PUT`,body:t}),eventTypeDelete:e=>$(`/api/event-types/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappings:e=>$(`/api/mappings`+Q({workspace:e})),mappingCreate:e=>$(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>$(`/api/mappings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),mappingDelete:e=>$(`/api/mappings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>$(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:e=>$(`/api/bindings`+Q({workspace:e})),dispatches:(e,t)=>$(`/api/${e}/${encodeURIComponent(t)}/dispatches`),bindingCreate:e=>$(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>$(`/api/bindings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),bindingDelete:e=>$(`/api/bindings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>$(`/api/bindings/${encodeURIComponent(e)}/approve`,{method:`POST`}),bindingPause:e=>$(`/api/bindings/${encodeURIComponent(e)}/pause`,{method:`POST`}),bindingResume:e=>$(`/api/bindings/${encodeURIComponent(e)}/resume`,{method:`POST`}),harnessBindings:()=>$(`/api/harness/bindings`),sources:e=>$(`/api/sources`+Q({workspace:e})),sourceCreate:(e,t=``)=>$(`/api/sources`,{method:`POST`,body:{path:e,wo Line truncated
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var ui;function di(e){ui=e}var fi=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function pi(e){let t=e instanceof fi?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 mi(e,t){let n=await fetch(e,t);if(ui?.(n.status===401),!n.ok)throw new fi(await li(n),n.status);return n}async function $(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=ci,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 mi(e,s);return a?await c.json():void 0}var hi={health:()=>$(`/health/detailed`),services:()=>$(`/api/services`),policies:()=>$(`/api/access/policies`),putPolicy:e=>$(`/api/access/policies`,{method:`PUT`,body:e}),deletePolicy:e=>$(`/api/access/policies`,{method:`DELETE`,body:e,parse:!1}),orgs:()=>$(`/api/orgs`),orgCreate:e=>$(`/api/orgs`,{method:`POST`,body:e}),org:e=>$(`/api/orgs/${encodeURIComponent(e)}`),orgWorkspaces:e=>$(`/api/orgs/${encodeURIComponent(e)}/workspaces`),createOrgWorkspace:(e,t)=>$(`/api/orgs/${encodeURIComponent(e)}/workspaces`,{method:`POST`,body:t}),orgMembers:e=>$(`/api/orgs/${encodeURIComponent(e)}/members`),addOrgMember:(e,t)=>$(`/api/orgs/${encodeURIComponent(e)}/members`,{method:`POST`,body:t}),setOrgMember:(e,t,n)=>$(`/api/orgs/${encodeURIComponent(e)}/members/${encodeURIComponent(t)}`,{method:`PUT`,body:n}),removeOrgMember:(e,t,n)=>$(`/api/orgs/${encodeURIComponent(e)}/members/${encodeURIComponent(t)}`+Q({workspace:n}),{method:`DELETE`,parse:!1}),assignOrgAgent:(e,t)=>$(`/api/orgs/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}`,{method:`PUT`}),alerts:()=>$(`/api/alerts`),dismissAlert:e=>$(`/api/alerts/${e}/dismiss`,{method:`POST`,parse:!1}),summary:()=>$(`/api/summary`),tasks:()=>$(`/api/tasks`),taskPage:async e=>{let t=await mi(`/api/tasks`+Q(e),{headers:{Accept:`application/json`},signal:AbortSignal.timeout(ci)});return{tasks:await t.json(),next:t.headers.get(`X-Next-Cursor`)}},taskMeta:()=>$(`/api/task-meta`),task:e=>$(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>$(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>$(`/api/tasks/${encodeURIComponent(e)}/changes`+Q(t)),taskDebug:(e,t)=>$(`/api/tasks/${encodeURIComponent(e)}/debug`+Q(t)),taskAction:(e,t,n)=>$(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t,...n}}),setup:()=>$(`/api/setup`),capabilities:()=>$(`/api/capabilities`),workflows:()=>$(`/api/workflows`),workflowEnabled:(e,t)=>$(`/api/workflows/${encodeURIComponent(e)}/enabled`,{method:`PUT`,body:{enabled:t},parse:!1}),workRequest:e=>$(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>$(`/api/skills`),channels:()=>$(`/api/channels`),curators:()=>$(`/api/curators`),channelReload:e=>$(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>$(`/api/config`),logs:e=>$(`/api/logs`+Q(e)),taskLogs:(e,t)=>$(`/api/tasks/${encodeURIComponent(e)}/logs`+Q(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),version:()=>$(`/api/version`),updateSnapshot:()=>$(`/api/chat/update`),updateDefer:e=>$(`/api/chat/update/defer`,{method:`POST`,body:{snapshot:e}}),updateInstall:e=>$(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:9e5}),captures:e=>$(`/api/captures`+Q({limit:e})),eventTypes:e=>$(`/api/event-types`+Q({workspace:e})),eventTypeCreate:e=>$(`/api/event-types`,{method:`POST`,body:e}),eventTypeUpdate:(e,t)=>$(`/api/event-types/${encodeURIComponent(e)}`,{method:`PUT`,body:t}),eventTypeDelete:e=>$(`/api/event-types/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappings:e=>$(`/api/mappings`+Q({workspace:e})),mappingCreate:e=>$(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>$(`/api/mappings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),mappingDelete:e=>$(`/api/mappings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>$(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:e=>$(`/api/bindings`+Q({workspace:e})),dispatches:(e,t)=>$(`/api/${e}/${encodeURIComponent(t)}/dispatches`),bindingCreate:e=>$(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>$(`/api/bindings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),bindingDelete:e=>$(`/api/bindings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>$(`/api/bindings/${encodeURIComponent(e)}/approve`,{method:`POST`}),bindingPause:e=>$(`/api/bindings/${encodeURIComponent(e)}/pause`,{method:`POST`}),bindingResume:e=>$(`/api/bindings/${encodeURIComponent(e)}/resume`,{method:`POST`}),harnessBindings:()=>$(`/api/harness/bindings`),sources:e=>$(`/apLine truncated
+1 -1
View File
@@ -1 +1 @@
.vue-flow{z-index:0;direction:ltr;width:100%;height:100%;position:relative;overflow:hidden}.vue-flow__container{width:100%;height:100%;position:absolute;top:0;left:0}.vue-flow__pane{z-index:1}.vue-flow__pane.draggable{cursor:grab}.vue-flow__pane.selection{cursor:pointer}.vue-flow__pane.dragging{cursor:grabbing}.vue-flow__transformationpane{transform-origin:0 0;z-index:2;pointer-events:none}.vue-flow__viewport{z-index:4;overflow:clip}.vue-flow__selection{z-index:6}.vue-flow__edge-labels{pointer-events:none;-webkit-user-select:none;user-select:none;width:100%;height:100%;position:absolute}.vue-flow__nodesselection-rect:focus,.vue-flow__nodesselection-rect:focus-visible{outline:none}.vue-flow .vue-flow__edges{pointer-events:none;overflow:visible}.vue-flow__edge-path,.vue-flow__connection-path{stroke:#b1b1b7;stroke-width:1px;fill:none}.vue-flow__edge{pointer-events:visibleStroke;cursor:pointer}.vue-flow__edge.animated path{stroke-dasharray:5;animation:.5s linear infinite dashdraw}.vue-flow__edge.animated path.vue-flow__edge-interaction{stroke-dasharray:none;animation:none}.vue-flow__edge.inactive{pointer-events:none}.vue-flow__edge.selected,.vue-flow__edge:focus,.vue-flow__edge:focus-visible{outline:none}.vue-flow__edge.selected .vue-flow__edge-path,.vue-flow__edge:focus .vue-flow__edge-path,.vue-flow__edge:focus-visible .vue-flow__edge-path{stroke:#555}.vue-flow__edge-textwrapper{pointer-events:all}.vue-flow__edge-textbg{fill:#fff}.vue-flow__edge-text{pointer-events:none;-webkit-user-select:none;user-select:none}.vue-flow__connection{pointer-events:none}.vue-flow__connection .animated{stroke-dasharray:5;animation:.5s linear infinite dashdraw}.vue-flow__connectionline{z-index:1001}.vue-flow__nodes{pointer-events:none;transform-origin:0 0}.vue-flow__node{-webkit-user-select:none;user-select:none;pointer-events:all;transform-origin:0 0;box-sizing:border-box;cursor:default;position:absolute}.vue-flow__node.draggable{cursor:grab;pointer-events:all}.vue-flow__node.draggable.dragging{cursor:grabbing}.vue-flow__nodesselection{z-index:3;transform-origin:0 0;pointer-events:none}.vue-flow__nodesselection-rect{pointer-events:all;cursor:grab;position:absolute}.vue-flow__nodesselection-rect.dragging{cursor:grabbing}.vue-flow__handle{pointer-events:none;min-width:5px;min-height:5px;position:absolute}.vue-flow__handle.connectable{pointer-events:all;cursor:crosshair}.vue-flow__handle-bottom{bottom:0;left:50%;transform:translate(-50%,50%)}.vue-flow__handle-top{top:0;left:50%;transform:translate(-50%,-50%)}.vue-flow__handle-left{top:50%;left:0;transform:translate(-50%,-50%)}.vue-flow__handle-right{top:50%;right:0;transform:translate(50%,-50%)}.vue-flow__edgeupdater{cursor:move;pointer-events:all}.vue-flow__panel{z-index:5;margin:15px;position:absolute}.vue-flow__panel.top{top:0}.vue-flow__panel.bottom{bottom:0}.vue-flow__panel.left{left:0}.vue-flow__panel.right{right:0}.vue-flow__panel.center{left:50%;transform:translate(-50%)}@keyframes dashdraw{0%{stroke-dashoffset:10px}}.vue-flow__controls{box-shadow:0 0 2px 1px #00000014}.vue-flow__controls-button{box-sizing:content-box;cursor:pointer;-webkit-user-select:none;user-select:none;background:#fefefe;border:none;border-bottom:1px solid #eee;justify-content:center;align-items:center;width:16px;height:16px;padding:5px;display:flex}.vue-flow__controls-button svg{width:100%;max-width:12px;max-height:12px}.vue-flow__controls-button:hover{background:#f4f4f4}.vue-flow__controls-button:disabled{pointer-events:none}.vue-flow__controls-button:disabled svg{fill-opacity:.4}.workflow-flow-edge path{stroke:var(--color-muted-foreground);stroke-width:1.5px}.workflow-flow-edge.trace-ok path{stroke:var(--color-ok)}.workflow-flow-edge.trace-failed path{stroke:var(--color-danger)}.workflow-flow-edge.trace-interrupted path{stroke:var(--color-warn)}.workflow-flow-edge.trace-running path{stroke:var(--color-info);stroke-dasharray:6 4;animation:.8s linear infinite edge-trace}@keyframes edge-trace{to{stroke-dashoffset:-10px}}@media (prefers-reduced-motion:reduce){.workflow-flow-edge.trace-running path,.step-running{animation:none}}.workflow-data-edge path{stroke:var(--color-primary);stroke-dasharray:5 4;stroke-width:1.25px}@keyframes step-running{50%{box-shadow:0 0 0 4px color-mix(in oklab, var(--color-info) 30%, transparent)}}.step-running{animation:1.6s ease-in-out infinite step-running}.workflow-canvas .vue-flow__controls{box-shadow:none}.workflow-canvas .vue-flow__controls-button{background:var(--color-card);border-color:var(--color-border);fill:var(--color-foreground)}.workflow-canvas .vue-flow__controls-button:hover{background:var(--color-secondary)}@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reLine truncated
.vue-flow{z-index:0;direction:ltr;width:100%;height:100%;position:relative;overflow:hidden}.vue-flow__container{width:100%;height:100%;position:absolute;top:0;left:0}.vue-flow__pane{z-index:1}.vue-flow__pane.draggable{cursor:grab}.vue-flow__pane.selection{cursor:pointer}.vue-flow__pane.dragging{cursor:grabbing}.vue-flow__transformationpane{transform-origin:0 0;z-index:2;pointer-events:none}.vue-flow__viewport{z-index:4;overflow:clip}.vue-flow__selection{z-index:6}.vue-flow__edge-labels{pointer-events:none;-webkit-user-select:none;user-select:none;width:100%;height:100%;position:absolute}.vue-flow__nodesselection-rect:focus,.vue-flow__nodesselection-rect:focus-visible{outline:none}.vue-flow .vue-flow__edges{pointer-events:none;overflow:visible}.vue-flow__edge-path,.vue-flow__connection-path{stroke:#b1b1b7;stroke-width:1px;fill:none}.vue-flow__edge{pointer-events:visibleStroke;cursor:pointer}.vue-flow__edge.animated path{stroke-dasharray:5;animation:.5s linear infinite dashdraw}.vue-flow__edge.animated path.vue-flow__edge-interaction{stroke-dasharray:none;animation:none}.vue-flow__edge.inactive{pointer-events:none}.vue-flow__edge.selected,.vue-flow__edge:focus,.vue-flow__edge:focus-visible{outline:none}.vue-flow__edge.selected .vue-flow__edge-path,.vue-flow__edge:focus .vue-flow__edge-path,.vue-flow__edge:focus-visible .vue-flow__edge-path{stroke:#555}.vue-flow__edge-textwrapper{pointer-events:all}.vue-flow__edge-textbg{fill:#fff}.vue-flow__edge-text{pointer-events:none;-webkit-user-select:none;user-select:none}.vue-flow__connection{pointer-events:none}.vue-flow__connection .animated{stroke-dasharray:5;animation:.5s linear infinite dashdraw}.vue-flow__connectionline{z-index:1001}.vue-flow__nodes{pointer-events:none;transform-origin:0 0}.vue-flow__node{-webkit-user-select:none;user-select:none;pointer-events:all;transform-origin:0 0;box-sizing:border-box;cursor:default;position:absolute}.vue-flow__node.draggable{cursor:grab;pointer-events:all}.vue-flow__node.draggable.dragging{cursor:grabbing}.vue-flow__nodesselection{z-index:3;transform-origin:0 0;pointer-events:none}.vue-flow__nodesselection-rect{pointer-events:all;cursor:grab;position:absolute}.vue-flow__nodesselection-rect.dragging{cursor:grabbing}.vue-flow__handle{pointer-events:none;min-width:5px;min-height:5px;position:absolute}.vue-flow__handle.connectable{pointer-events:all;cursor:crosshair}.vue-flow__handle-bottom{bottom:0;left:50%;transform:translate(-50%,50%)}.vue-flow__handle-top{top:0;left:50%;transform:translate(-50%,-50%)}.vue-flow__handle-left{top:50%;left:0;transform:translate(-50%,-50%)}.vue-flow__handle-right{top:50%;right:0;transform:translate(50%,-50%)}.vue-flow__edgeupdater{cursor:move;pointer-events:all}.vue-flow__panel{z-index:5;margin:15px;position:absolute}.vue-flow__panel.top{top:0}.vue-flow__panel.bottom{bottom:0}.vue-flow__panel.left{left:0}.vue-flow__panel.right{right:0}.vue-flow__panel.center{left:50%;transform:translate(-50%)}@keyframes dashdraw{0%{stroke-dashoffset:10px}}.vue-flow__controls{box-shadow:0 0 2px 1px #00000014}.vue-flow__controls-button{box-sizing:content-box;cursor:pointer;-webkit-user-select:none;user-select:none;background:#fefefe;border:none;border-bottom:1px solid #eee;justify-content:center;align-items:center;width:16px;height:16px;padding:5px;display:flex}.vue-flow__controls-button svg{width:100%;max-width:12px;max-height:12px}.vue-flow__controls-button:hover{background:#f4f4f4}.vue-flow__controls-button:disabled{pointer-events:none}.vue-flow__controls-button:disabled svg{fill-opacity:.4}.workflow-flow-edge path{stroke:var(--color-muted-foreground);stroke-width:1.5px}.workflow-flow-edge.trace-ok path{stroke:var(--color-ok)}.workflow-flow-edge.trace-failed path{stroke:var(--color-danger)}.workflow-flow-edge.trace-interrupted path{stroke:var(--color-warn)}.workflow-flow-edge.trace-running path{stroke:var(--color-info);stroke-dasharray:6 4;animation:.8s linear infinite edge-trace}@keyframes edge-trace{to{stroke-dashoffset:-10px}}@media (prefers-reduced-motion:reduce){.workflow-flow-edge.trace-running path,.step-running{animation:none}}.workflow-data-edge path{stroke:var(--color-primary);stroke-dasharray:5 4;stroke-width:1.25px}@keyframes step-running{50%{box-shadow:0 0 0 4px color-mix(in oklab, var(--color-info) 30%, transparent)}}.step-running{animation:1.6s ease-in-out infinite step-running}.workflow-canvas .vue-flow__controls{box-shadow:none}.workflow-canvas .vue-flow__controls-button{background:var(--color-card);border-color:var(--color-border);fill:var(--color-foreground)}.workflow-canvas .vue-flow__controls-button:hover{background:var(--color-secondary)}@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reLine truncated
+69 -69
View File
@@ -1,68 +1,68 @@
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentProfilesPage.js","assets/HistoryLink.js","assets/PageHeader.js","assets/badge.js","assets/CredentialBindingsPage.js","assets/PlaybooksPage.js","assets/HarnessPage.js","assets/HarnessPage.css","assets/NotFoundPage.js"])))=>i.map(i=>d[i]);
import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as m,O as h,P as g,Q as _,R as v,S as y,T as b,U as x,V as S,W as C,X as w,Y as T,Z as E,_ as ee,a as D,at as te,b as ne,c as re,ct as ie,d as ae,et as oe,f as se,g as ce,h as le,i as ue,it as de,j as fe,k as pe,l as me,lt as he,m as ge,n as _e,nt as ve,o as ye,ot as be,p as xe,q as Se,r as Ce,rt as we,s as Te,st as Ee,t as De,tt as Oe,u as ke,ut as Ae,v as O,w as je,x as Me,y as Ne,z as Pe}from"./HistoryLink.js";import{$ as Fe,A as k,B as Ie,C as Le,Ct as Re,D as A,Dn as ze,En as Be,Ft as Ve,It as He,Jt as j,Mt as Ue,O as M,Pt as We,Qn as N,R as Ge,Rt as Ke,Sn as qe,St as P,Tn as Je,Tt as Ye,Ut as F,V as Xe,Wt as Ze,X as Qe,Xt as $e,Y as et,_ as I,_n as tt,_t as nt,an as rt,at as it,b as L,bn as at,d as ot,dn as st,er as ct,et as lt,ht as R,it as ut,kn as z,lt as B,mn as dt,nr as V,nt as ft,on as pt,pn as mt,pt as ht,rn as gt,s as H,t as _t,tr as vt,tt as U,v as W,vn as yt,wn as bt,x as G,xt as K,y as q,yn as J,zt as xt}from"./PageHeader.js";import{A as St,D as Ct,E as Y,J as wt,K as Tt,U as Et,X as Dt,Y as Ot,_ as kt,b as X,d as At,g as jt,i as Mt,m as Nt,n as Pt,q as Ft,r as Z,t as It,w as Lt,x as Rt,y as zt}from"./badge.js";(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 Bt=Ee({name:`arrow-down`,size:24,node:[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m19 12-7 7-7-7`,key:`1idqje`}]]}),Vt=Ee({name:`arrow-left`,size:24,node:[[`path`,{d:`m12 19-7-7 7-7`,key:`1l729n`}],[`path`,{d:`M19 12H5`,key:`x3x0zl`}]]}),Ht=Ee({name:`arrow-right`,size:24,node:[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`m12 5 7 7-7 7`,key:`xquz4c`}]]}),Ut=Ee({name:`arrow-up-down`,size:24,node:[[`path`,{d:`m21 16-4 4-4-4`,key:`f6ql7i`}],[`path`,{d:`M17 20V4`,key:`1ejh1v`}],[`path`,{d:`m3 8 4-4 4 4`,key:`11wl7u`}],[`path`,{d:`M7 4v16`,key:`1glfcx`}]]}),Wt=Ee({name:`arrow-up-right`,size:24,node:[[`path`,{d:`M7 7h10v10`,key:`1tivn9`}],[`path`,{d:`M7 17 17 7`,key:`1vkiza`}]]}),Gt=Ee({name:`arrow-up`,size:24,node:[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]}),Kt=Ee({name:`book-open`,size:24,node:[[`path`,{d:`M12 5v16`,key:`1f6ucr`}],[`path`,{d:`M20.001 19A2 2 0 0022 17V5a2 2 0 00-1.999-2L16 3.002A5 5 0 0012 5a5 5 0 00-4-2H4a2 2 0 00-2 2v12a2 2 0 001.999 2H8a5 5 0 014 2 5 5 0 014-2z`,key:`1fyvmf`}]]}),qt=Ee({name:`bot`,size:24,node:[[`path`,{d:`M12 8V4H8`,key:`hb8ula`}],[`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`,key:`enze0r`}],[`path`,{d:`M2 14h2`,key:`vft8re`}],[`path`,{d:`M20 14h2`,key:`4cs60a`}],[`path`,{d:`M15 13v2`,key:`1xurst`}],[`path`,{d:`M9 13v2`,key:`rq6x2g`}]]}),Jt=Ee({name:`braces`,size:24,node:[[`path`,{d:`M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1`,key:`ezmyqa`}],[`path`,{d:`M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1`,key:`e1hn23`}]],aliases:[`curly-braces`]}),Yt=Ee({name:`calendar-clock`,size:24,node:[[`path`,{d:`M16 14v2.2l1.6 1`,key:`fo4ql5`}],[`path`,{d:`M16 2v3`,key:`otl347`}],[`path`,{d:`M21 7.338V5a2 2 0 00-2-2H5a2 2 0 00-2 2v14a2 2 0 002 2h2.338`,key:`7hb8p4`}],[`path`,{d:`M3 9h5.859`,key:`numkqi`}],[`path`,{d:`M8 2v3`,key:`1ioesn`}],[`circle`,{cx:`16`,cy:`16`,r:`6`,key:`qoo3c4`}]]}),Xt=Ee({name:`check`,size:24,node:[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]}),Zt=Ee({name:`chevron-down`,size:24,node:[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]}),Qt=Ee({name:`chevron-right`,size:24,node:[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]}),$t=Ee({name:`chevron-up`,size:24,node:[[`path`,{d:`m18 15-6-6-6 6`,key:`153udz`}]]}),en=Ee({name:`circle-alert`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`line`,{x1:`12`,x2:`12`,y1:`8`,y2:`12`,key:`1pkeuh`}],[`line`,{x1:`12`,x2:`12.01`,y1:`16`,y2:`16`,key:`4dfq90`}]],aliases:[`alert-circle`]}),tn=Ee({name:`circle-check`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m16 9-5.5 5.5L8 12`,key:`xofnsj`}]],aliases:[`check-circle-2`]}),nn=Ee({name:`circle-dot`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]}),rn=Ee({name:`circle-question-mark`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3`,key:`1u773s`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]],aliases:[`help-circle`,`circle-help`]}),an=Ee({name:Line truncated
import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as m,O as h,P as g,Q as _,R as v,S as y,T as b,U as x,V as S,W as C,X as w,Y as T,Z as E,_ as ee,a as D,at as te,b as ne,c as re,ct as ie,d as ae,et as oe,f as se,g as ce,h as le,i as ue,it as de,j as fe,k as pe,l as me,lt as he,m as ge,n as _e,nt as ve,o as ye,ot as be,p as xe,q as Se,r as Ce,rt as we,s as Te,st as Ee,t as De,tt as Oe,u as ke,ut as Ae,v as O,w as je,x as Me,y as Ne,z as Pe}from"./HistoryLink.js";import{$ as Fe,A as k,B as Ie,C as Le,Ct as Re,D as A,Dn as ze,En as Be,Ft as Ve,It as He,Jt as j,Mt as Ue,O as M,Pt as We,Qn as N,R as Ge,Rt as Ke,Sn as qe,St as P,Tn as Je,Tt as Ye,Ut as F,V as Xe,Wt as Ze,X as Qe,Xt as $e,Y as et,_ as I,_n as tt,_t as nt,an as rt,at as it,b as L,bn as at,d as ot,dn as st,er as ct,et as lt,ht as R,it as ut,kn as z,lt as B,mn as dt,nr as V,nt as ft,on as pt,pn as mt,pt as ht,rn as gt,s as H,t as _t,tr as vt,tt as U,v as W,vn as yt,wn as bt,x as G,xt as K,y as q,yn as J,zt as xt}from"./PageHeader.js";import{A as St,D as Ct,E as Y,J as wt,K as Tt,U as Et,X as Dt,Y as Ot,_ as kt,b as X,d as At,g as jt,i as Mt,m as Nt,n as Pt,q as Ft,r as Z,t as It,w as Lt,x as Rt,y as zt}from"./badge.js";(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 Bt=Ee({name:`arrow-down`,size:24,node:[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m19 12-7 7-7-7`,key:`1idqje`}]]}),Vt=Ee({name:`arrow-left`,size:24,node:[[`path`,{d:`m12 19-7-7 7-7`,key:`1l729n`}],[`path`,{d:`M19 12H5`,key:`x3x0zl`}]]}),Ht=Ee({name:`arrow-right`,size:24,node:[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`m12 5 7 7-7 7`,key:`xquz4c`}]]}),Ut=Ee({name:`arrow-up-down`,size:24,node:[[`path`,{d:`m21 16-4 4-4-4`,key:`f6ql7i`}],[`path`,{d:`M17 20V4`,key:`1ejh1v`}],[`path`,{d:`m3 8 4-4 4 4`,key:`11wl7u`}],[`path`,{d:`M7 4v16`,key:`1glfcx`}]]}),Wt=Ee({name:`arrow-up-right`,size:24,node:[[`path`,{d:`M7 7h10v10`,key:`1tivn9`}],[`path`,{d:`M7 17 17 7`,key:`1vkiza`}]]}),Gt=Ee({name:`arrow-up`,size:24,node:[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]}),Kt=Ee({name:`bell`,size:24,node:[[`path`,{d:`M10.268 21a2 2 0 0 0 3.464 0`,key:`vwvbt9`}],[`path`,{d:`M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326`,key:`11g9vi`}]]}),qt=Ee({name:`book-open`,size:24,node:[[`path`,{d:`M12 5v16`,key:`1f6ucr`}],[`path`,{d:`M20.001 19A2 2 0 0022 17V5a2 2 0 00-1.999-2L16 3.002A5 5 0 0012 5a5 5 0 00-4-2H4a2 2 0 00-2 2v12a2 2 0 001.999 2H8a5 5 0 014 2 5 5 0 014-2z`,key:`1fyvmf`}]]}),Jt=Ee({name:`bot`,size:24,node:[[`path`,{d:`M12 8V4H8`,key:`hb8ula`}],[`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`,key:`enze0r`}],[`path`,{d:`M2 14h2`,key:`vft8re`}],[`path`,{d:`M20 14h2`,key:`4cs60a`}],[`path`,{d:`M15 13v2`,key:`1xurst`}],[`path`,{d:`M9 13v2`,key:`rq6x2g`}]]}),Yt=Ee({name:`braces`,size:24,node:[[`path`,{d:`M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1`,key:`ezmyqa`}],[`path`,{d:`M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1`,key:`e1hn23`}]],aliases:[`curly-braces`]}),Xt=Ee({name:`calendar-clock`,size:24,node:[[`path`,{d:`M16 14v2.2l1.6 1`,key:`fo4ql5`}],[`path`,{d:`M16 2v3`,key:`otl347`}],[`path`,{d:`M21 7.338V5a2 2 0 00-2-2H5a2 2 0 00-2 2v14a2 2 0 002 2h2.338`,key:`7hb8p4`}],[`path`,{d:`M3 9h5.859`,key:`numkqi`}],[`path`,{d:`M8 2v3`,key:`1ioesn`}],[`circle`,{cx:`16`,cy:`16`,r:`6`,key:`qoo3c4`}]]}),Zt=Ee({name:`check`,size:24,node:[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]}),Qt=Ee({name:`chevron-down`,size:24,node:[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]}),$t=Ee({name:`chevron-right`,size:24,node:[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]}),en=Ee({name:`chevron-up`,size:24,node:[[`path`,{d:`m18 15-6-6-6 6`,key:`153udz`}]]}),tn=Ee({name:`circle-alert`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`line`,{x1:`12`,x2:`12`,y1:`8`,y2:`12`,key:`1pkeuh`}],[`line`,{x1:`12`,x2:`12.01`,y1:`16`,y2:`16`,key:`4dfq90`}]],aliases:[`alert-circle`]}),nn=Ee({name:`circle-check`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m16 9-5.5 5.5L8 12`,key:`xofnsj`}]],aliases:[`check-circle-2`]}),rn=Ee({name:`circle-dot`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]}),an=Ee({nLine truncated
`);d=n.pop()||``;for(let e of n){let t=e.split(`
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(dr.value=n.session_id),n.type===`delta`&&(o+=n.text,gr.value=gr.value?{...gr.value,text:o}:null),(n.type===`tool`||n.type===`navigate`)&&(a=[...a,n],gr.value=gr.value?{...gr.value,tools:a}:null),n.type===`ask`&&n.ask&&(clearTimeout(l),gr.value=gr.value?{...gr.value,ask:n.ask}: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`);fr.value=[...fr.value,{from:`assistant`,text:o,tool_calls:a}],gr.value=null,mr.value=`Ready`,await jr()}catch(e){let t=e;t.name===`AbortError`&&!c?(gr.value={text:`Turn stopped.`,tools:a,isError:!1,turn:r,isRetry:i},mr.value=`Stopped`):(gr.value={text:`Unable to complete that turn: ${t.message||t}`,tools:a,isError:!0,turn:r?ir(r):void 0,isRetry:i},mr.value=`Error — retry available`)}finally{clearTimeout(l),cr=null,kr=null,hr.value=!1}}function Wr(){mr.value=`Stopping…`,dr.value&&X.chatCancel(dr.value).catch(()=>{}),Ar()}function Gr(){B(()=>{jr().catch(e=>{mr.value=e.message||`Chat unavailable`})}),ht(()=>{Ar()})}async function Kr(e){let t=new Uint8Array(await e.arrayBuffer()),n=``;for(let e=0;e<t.length;e+=32768)n+=String.fromCharCode(...t.subarray(e,e+32768));await Ur({textOverride:`🎤 Voice message`,voice:{data:btoa(n),mime_type:e.type||`audio/webm`}})}var qr=[`aria-label`,`title`,`aria-expanded`,`aria-controls`],Jr=k({__name:`ChatFab`,props:{open:{type:Boolean}},emits:[`toggle`],setup(e,{emit:t}){let n=t;function r(e){return Y(`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)=>(R(),G(`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":z(or),onClick:i[0]||=e=>n(`toggle`)},[W(`span`,{"aria-hidden":`true`,class:N(r(!e.open))},[M(z(_n),{size:22})],2),W(`span`,{"aria-hidden":`true`,class:N(r(e.open))},[M(z(Jn),{size:22})],2)],8,qr))}});function Yr(e){return typeof e==`string`?`'${e}'`:new $r().serialize(e)}var Xr=` _-,;:!?.'"()[]{}@*/\\&#%\`^+<=>|~$0123456789abcdefghijklmnopqrstuvwxyz`,Zr=(function(){let e=new Uint8Array(128);for(let t=0;t<69;t++)e[Xr.charCodeAt(t)]=t+1;for(let t=65;t<=90;t++)e[t]=e[t+32];return e})();function Qr(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&&Zr[n]?Zr[n]:n+128,s=a<128&&Zr[a]?Zr[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 $r=(function(){class e{#e=new Map;compare(e,t){let n=typeof e,r=typeof t;return n===`string`&&r===`string`?Qr(e,t):n===`number`&&r===`number`?e-t:Qr(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(Qr),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.$ArrLine truncated
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(fr.value=n.session_id),n.type===`delta`&&(o+=n.text,_r.value=_r.value?{..._r.value,text:o}:null),(n.type===`tool`||n.type===`navigate`)&&(a=[...a,n],_r.value=_r.value?{..._r.value,tools:a}:null),n.type===`ask`&&n.ask&&(clearTimeout(l),_r.value=_r.value?{..._r.value,ask:n.ask}: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`);pr.value=[...pr.value,{from:`assistant`,text:o,tool_calls:a}],_r.value=null,hr.value=`Ready`,await Mr()}catch(e){let t=e;t.name===`AbortError`&&!c?(_r.value={text:`Turn stopped.`,tools:a,isError:!1,turn:r,isRetry:i},hr.value=`Stopped`):(_r.value={text:`Unable to complete that turn: ${t.message||t}`,tools:a,isError:!0,turn:r?ar(r):void 0,isRetry:i},hr.value=`Error — retry available`)}finally{clearTimeout(l),lr=null,Ar=null,gr.value=!1}}function Gr(){hr.value=`Stopping…`,fr.value&&X.chatCancel(fr.value).catch(()=>{}),jr()}function Kr(){B(()=>{Mr().catch(e=>{hr.value=e.message||`Chat unavailable`})}),ht(()=>{jr()})}async function qr(e){let t=new Uint8Array(await e.arrayBuffer()),n=``;for(let e=0;e<t.length;e+=32768)n+=String.fromCharCode(...t.subarray(e,e+32768));await Wr({textOverride:`🎤 Voice message`,voice:{data:btoa(n),mime_type:e.type||`audio/webm`}})}var Jr=[`aria-label`,`title`,`aria-expanded`,`aria-controls`],Yr=k({__name:`ChatFab`,props:{open:{type:Boolean}},emits:[`toggle`],setup(e,{emit:t}){let n=t;function r(e){return Y(`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)=>(R(),G(`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":z(sr),onClick:i[0]||=e=>n(`toggle`)},[W(`span`,{"aria-hidden":`true`,class:N(r(!e.open))},[M(z(vn),{size:22})],2),W(`span`,{"aria-hidden":`true`,class:N(r(e.open))},[M(z(Yn),{size:22})],2)],8,Jr))}});function Xr(e){return typeof e==`string`?`'${e}'`:new ei().serialize(e)}var Zr=` _-,;:!?.'"()[]{}@*/\\&#%\`^+<=>|~$0123456789abcdefghijklmnopqrstuvwxyz`,Qr=(function(){let e=new Uint8Array(128);for(let t=0;t<69;t++)e[Zr.charCodeAt(t)]=t+1;for(let t=65;t<=90;t++)e[t]=e[t+32];return e})();function $r(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&&Qr[n]?Qr[n]:n+128,s=a<128&&Qr[a]?Qr[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 ei=(function(){class e{#e=new Map;compare(e,t){let n=typeof e,r=typeof t;return n===`string`&&r===`string`?$r(e,t):n===`number`&&r===`number`?e-t:$r(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($r),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.$ArrLine truncated
- a positive number
- less than the value passed to \`max\` (or ${ks} if no \`max\` prop is set)
- less than the value passed to \`max\` (or ${As} if no \`max\` prop is set)
- \`null\` or \`undefined\` if the progress is indeterminate.
Defaulting to \`null\`.`),null)}function Ps(e){return Ms(e)&&!Number.isNaN(e)&&e>0?e:(console.error(`Invalid prop \`max\` of value \`${e}\` supplied to \`ProgressRoot\`. Only numbers greater than 0 are valid max values. Defaulting to \`${ks}\`.`),ks)}var Fs=k({__name:`ProgressRoot`,props:{modelValue:{type:[Number,null],required:!1},max:{type:Number,required:!1,default:ks},getValueLabel:{type:Function,required:!1,default:(e,t)=>Ms(e)?`${Math.round(e/t*ks)}%`:void 0},getValueText:{type:Function,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},emits:[`update:modelValue`,`update:max`],setup(e,{emit:t}){let n=e,r=t;v();let i=T(n,`modelValue`,r,{passive:n.modelValue===void 0}),a=T(n,`max`,r,{passive:n.max===void 0});F(()=>i.value,async e=>{let t=Ns(e,n.max);t!==e&&(await ft(),i.value=t)},{immediate:!0}),F(()=>n.max,e=>{let t=Ps(n.max);t!==e&&(a.value=t)},{immediate:!0});let o=I(()=>ii(i.value)?`indeterminate`:i.value===a.value?`complete`:`loading`);return js({modelValue:i,max:a,progressState:o}),(t,n)=>(R(),q(z(jt),{"as-child":e.asChild,as:e.as,"aria-valuemax":z(a),"aria-valuemin":0,"aria-valuenow":Ms(z(i))?z(i):void 0,"aria-valuetext":e.getValueText?.(z(i),z(a)),"aria-label":e.getValueLabel(z(i),z(a)),role:`progressbar`,"data-state":o.value,"data-value":z(i)??void 0,"data-max":z(a)},{default:j(()=>[P(t.$slots,`default`,{modelValue:z(i)})]),_:3},8,[`as-child`,`as`,`aria-valuemax`,`aria-valuenow`,`aria-valuetext`,`aria-label`,`data-state`,`data-value`,`data-max`]))}}),Is=k({__name:`ProgressIndicator`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(e){let t=e,n=As();return v(),(e,r)=>(R(),q(z(jt),U(t,{"data-state":z(n).progressState.value,"data-value":z(n).modelValue?.value??void 0,"data-max":z(n).max.value}),{default:j(()=>[P(e.$slots,`default`)]),_:3},16,[`data-state`,`data-value`,`data-max`]))}}),Ls=`radio.select`;function Rs(e,t,n){de(Ls,n,{originalEvent:e,value:t})}var zs=k({inheritAttrs:!1,__name:`Radio`,props:{id:{type:String,required:!1},value:{type:null,required:!1},disabled:{type:Boolean,required:!1,default:!1},checked:{type:Boolean,required:!1,default:void 0},asChild:{type:Boolean,required:!1},as:{type:null,required:!1,default:`button`},name:{type:String,required:!1},required:{type:Boolean,required:!1}},emits:[`update:checked`,`select`],setup(e,{emit:t}){let n=e,r=t,i=T(n,`checked`,r,{passive:n.checked===void 0}),{value:a}=Be(n),{forwardRef:o,currentElement:s}=v(),c=pi(s),l=mi(),u=I(()=>n.id&&s.value?document.querySelector(`[for="${n.id}"]`)?.innerText:void 0);function d(e){n.disabled||Rs(e,n.value,e=>{r(`select`,e),!e?.defaultPrevented&&(i.value=!0,c.value&&e.stopPropagation())})}return(t,n)=>(R(),G(H,null,[M(z(jt),U({id:e.id,ref:z(o),role:`radio`,type:e.as===`button`?`button`:void 0,as:e.as,"aria-checked":z(i)??!1,"aria-label":u.value,"as-child":e.asChild,disabled:e.disabled?``:void 0,"data-state":z(i)?`checked`:`unchecked`,"data-disabled":e.disabled?``:void 0,value:z(a),required:e.required,name:e.name},{...z(l),...t.$attrs},{onClick:Dt(d,[`stop`])}),{default:j(()=>[P(t.$slots,`default`,{checked:z(i)})]),_:3},16,[`id`,`type`,`as`,`aria-checked`,`aria-label`,`as-child`,`disabled`,`data-state`,`data-disabled`,`value`,`required`,`name`]),z(c)&&e.name?(R(),q(z(Fa),U({key:0,type:`radio`,tabindex:`-1`,value:z(a),checked:!!z(i),name:e.name,disabled:e.disabled,required:e.required},z(l)),null,16,[`value`,`checked`,`name`,`disabled`,`required`])):L(`v-if`,!0)],64))}}),[Bs,Vs]=be(`RadioGroupRoot`),Hs=k({__name:`RadioGroupRoot`,props:{modelValue:{type:null,required:!1},defaultValue:{type:null,required:!1},disabled:{type:Boolean,required:!1,default:!1},orientation:{type:String,required:!1,default:void 0},dir:{type:String,required:!1},loop:{type:Boolean,required:!1,default:!0},asChild:{type:Boolean,required:!1},as:{type:null,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1,default:!1}},emits:[`update:modelValue`],setup(e,{emit:t}){let n=e,r=t,{forwardRef:i,currentElement:a}=v(),o=T(n,`modelValue`,r,{defaultValue:n.defaultValue,passive:n.modelValue===void 0}),{disabled:s,loop:c,orientation:l,name:u,required:d,dir:f}=Be(n),p=S(f),m=pi(a);return Vs({modelValue:o,changeModelValue:e=>{o.value=e},disabled:s,loop:c,orientation:l,name:u?.value,required:d}),(t,n)=>(R(),q(z(to),{"as-child":``,orientation:z(l),dir:z(p),loop:z(c)},{default:j(()=>[M(z(jt),{ref:z(i),role:`radiogroup`,"data-disabled":z(s)?``:void 0,"as-child":e.asChild,as:e.as,"aria-orientation":z(l),"aria-required":z(d),dir:z(p)},{default:j(()=>[P(t.$slots,`default`,{modelValue:z(o)}),z(m)&&z(u)?(R(),q(z(Fa),{key:0,required:z(d),disabled:z(s),value:z(o),name:z(u)},null,8,[`required`,`disabled`,`value`,`name`])):L(`v-if`,!0)]),_:3},8,[`data-disabled`,`as-child`,`as`,`aria-orientation`,`aria-required`,`dir`])]),_:3},8,[`orientation`,`dir`,`loop`]))}}),[Us,Ws]=be(`RadioGroupItem`),Gs=k({inheritAttrs:!1,__name:`RadioGroupItem`,props:{id:{type:String,required:!1},value:{type:null,reqLine truncated
`),r=[],i=null,a=null,o=()=>{r.length&&(t.push({kind:`p`,inline:pd(r.join(` `))}),r=[])},s=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>pd(e))}),null)};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.push({kind:`pre`,code:a.join(`
`)}),a=null):a=[];continue}if(a){a.push(c);continue}let l=hd(c),u=e+1<n.length?hd(n[e+1]):null;if(l&&u&&gd(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=hd(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>pd(e)),rows:r.map(e=>e.map(e=>pd(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:pd(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])}else c.startsWith(`>`)?(o(),s(),t.push({kind:`blockquote`,inline:pd(c.replace(/^>\s?/,``))})):r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
`)}),t}function hd(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 gd(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var _d={class:`[overflow-wrap:anywhere]`},vd={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},yd={class:`font-mono text-[0.85em]`},bd={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},xd={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},Sd={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},Cd={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},wd={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},Td={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},Ed={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},Dd={key:8,class:`mb-2.5 last:mb-0`},Od=k({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=I(()=>md(t.text));return(e,t)=>(R(),G(`div`,_d,[(R(!0),G(H,null,K(n.value,(e,t)=>(R(),G(H,{key:t},[e.kind===`pre`?(R(),G(`pre`,vd,[W(`code`,yd,V(e.code),1)])):e.kind===`table`?(R(),G(`table`,bd,[W(`thead`,null,[W(`tr`,null,[(R(!0),G(H,null,K(e.head,(e,t)=>(R(),G(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[M(dd,{inline:e},null,8,[`inline`])]))),128))])]),W(`tbody`,null,[(R(!0),G(H,null,K(e.rows,(e,t)=>(R(),G(`tr`,{key:t},[(R(!0),G(H,null,K(e,(e,t)=>(R(),G(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[M(dd,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(R(),G(`blockquote`,xd,[M(dd,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(R(),G(`h1`,Sd,[M(dd,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(R(),G(`h2`,Cd,[M(dd,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(R(),G(`h3`,wd,[M(dd,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(R(),G(`ul`,Td,[(R(!0),G(H,null,K(e.items,(e,t)=>(R(),G(`li`,{key:t},[M(dd,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(R(),G(`ol`,Ed,[(R(!0),G(H,null,K(e.items,(e,t)=>(R(),G(`li`,{key:t},[M(dd,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(R(),G(`p`,Dd,[M(dd,{inline:e.inline},null,8,[`inline`])])):L(``,!0)],64))),128))]))}}),kd={class:`truncate`},Ad=k({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=Re(`RouterLink`);return R(),q(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:j(()=>[M(z(Wt),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),W(`span`,kd,V(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),jd={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},Md={class:`font-semibold text-foreground`},Nd={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},Pd=k({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=I(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=I(()=>t.tool.parameters||t.tool.Parameters||``),i=I(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=I(()=>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?(R(),q(Ad,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(R(),G(`div`,jd,[M(z(qn),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),W(`span`,Md,V(n.value),1),r.value?(R(),G(`code`,Nd,V(r.value),1)):L(``,!0),W(`span`,{class:N(z(Y)(`text-fg-muted`,i.value&&`text-danger`))},V(a.value),3)]))}}),Fd={key:0,class:`mb-2 grid gap-0.5 text-xs`},Id={key:1,class:`mb-2 flex flex-wrap gap-1.5`},Ld={key:3,class:`whitespace-pre-wrap`},Rd=k({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},media:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(R(),G(`div`,{class:N([`flex`,e.assistant?`justify-start`:`justify-end`])},[W(`div`,{class:N(z(Y)(`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?(R(),G(`div`,Fd,[(R(!0),G(H,null,K(e.tools,(t,n)=>(R(),q(Pd,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):L(``,!0),e.media.length?(R(),G(`div`,Id,[(R(!0),G(H,null,K(e.media,(e,t)=>(R(),q(id,{key:t,attachment:e},null,8,[`attachment`]))),128))])):L(``,!0),e.assistant?(R(),q(Od,{key:2,text:e.text},null,8,[`text`])):(R(),G(`div`,Ld,V(e.text),1)),P(t.$slots,`default`)],2)],2))}}),zd={class:`text-sm`},Bd={class:`font-medium`},Vd={key:0,class:`mt-1 text-fg-muted`},Hd={key:1,class:`mt-2 flex flex-wrap gap-2`},Ud=k({__name:`ChatChLine truncated
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>Qg?`${n.slice(0,Qg).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var e_=[`title`],t_=k({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=I(()=>Tg(n.event)),a=I(()=>$g(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=I(()=>n.event.at?Dh(n.event.at):`—`);return(e,t)=>(R(),q(z(Yg),{class:N(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:[Ot(Dt(o,[`prevent`]),[`enter`]),Ot(Dt(o,[`prevent`]),[`space`])]},{default:j(()=>[M(z($),{class:`font-medium`},{default:j(()=>[A(V(n.event.kind||n.event.type||`event`),1)]),_:1}),M(z($),{class:`font-mono`},{default:j(()=>[A(V(i.value>0?`#${i.value}`:`—`),1)]),_:1}),M(z($),{class:`w-[55%] max-w-0`},{default:j(()=>[W(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},V(a.value.text),9,e_)]),_:1}),M(z($),null,{default:j(()=>[A(V(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}}),n_=[{value:`all`,label:`All`},{value:`tasks`,label:`Tasks`},{value:`system`,label:`System`}];function r_(e){return(Number(e?.task_id)||0)>0}function i_(e,t){return t===`tasks`?r_(e):t!==`system`||!r_(e)}function a_(e,t){return e.filter(e=>i_(e,t))}function o_(e,t){return e>0?``:t===`all`?`Waiting for activity`:t===`tasks`?`No task events yet`:`No system events yet`}function s_(e,t){return`${e}:${t??0}`}function c_(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=s_($g(n).text,r),a=t[t.length-1];a&&a.key===i?(a.count+=1,a.events.push(n)):t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var l_={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},u_={class:`max-h-[28rem] overflow-y-auto`},d_=[`aria-expanded`,`aria-label`,`onClick`],f_=[`title`],p_=k({__name:`LiveActivityCard`,setup(e){let t=Af(),{activity:n,streamKind:r,streamState:i}=Ae(ee()),a=J(`all`),o=I(()=>a_(n.value,a.value)),s=I(()=>o_(o.value.length,a.value)),c=tt(new Set),l=I(()=>c_(o.value));function u(e){c.has(e)?c.delete(e):c.add(e)}function d(e){return c.has(e.key)}function f(e){return $g(e.representative)}function p(e){return e.representative.at?Dh(e.representative.at):`—`}function m(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(R(),q(z(bh),null,{default:j(()=>[M(z(Th),null,{default:j(()=>[M(z(Eh),null,{default:j(()=>[...t[1]||=[A(`Live activity`,-1)]]),_:1}),M(z(xh),{class:`flex items-center gap-2`},{default:j(()=>[M(z(Gg),{modelValue:a.value,"onUpdate:modelValue":t[0]||=e=>a.value=e,label:`Filter activity`,options:z(n_)},null,8,[`modelValue`,`options`]),M(z(It),{variant:z(r)},{default:j(()=>[A(V(z(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),M(z(Sh),null,{default:j(()=>[W(`div`,l_,[W(`div`,u_,[M(z(qg),null,{default:j(()=>[M(z(Zg),{class:`sticky top-0 z-10 bg-card`},{default:j(()=>[M(z(Yg),null,{default:j(()=>[M(z(Xg),null,{default:j(()=>[...t[2]||=[A(`Event`,-1)]]),_:1}),M(z(Xg),null,{default:j(()=>[...t[3]||=[A(`Task`,-1)]]),_:1}),M(z(Xg),null,{default:j(()=>[...t[4]||=[A(`Detail`,-1)]]),_:1}),M(z(Xg),null,{default:j(()=>[...t[5]||=[A(`When`,-1)]]),_:1})]),_:1})]),_:1}),M(z(Jg),null,{default:j(()=>[o.value.length?L(``,!0):(R(),q(z(Yg),{key:0},{default:j(()=>[M(z($),{colspan:`4`},{default:j(()=>[M(z(dh),null,{default:j(()=>[M(z(mh),null,{default:j(()=>[M(z(_h),null,{default:j(()=>[A(V(s.value),1)]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})),o.value.length?(R(!0),G(H,{key:1},K(l.value,e=>(R(),G(H,{key:e.key},[e.count===1?(R(),q(t_,{key:0,event:e.representative,onOpen:m},null,8,[`event`])):(R(),G(H,{key:1},[M(z(Yg),{class:N(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&&m(e.taskID),onKeydown:[Ot(Dt(t=>e.taskID>0&&m(e.taskID),[`prevent`]),[`enter`]),Ot(Dt(t=>e.taskID>0&&m(e.taskID),[`prevent`]),[`space`])]},{default:j(()=>[M(z($),{class:`font-medium`},{default:j(()=>[W(`button`,{type:`button`,class:`inline-flex items-center gap-1 rounded hover:opacity-80`,"aria-expanded":d(e),"aria-label":`${d(e)?`Hide`:`Show`} ${e.count} ${e.label} events`,onClick:Dt(t=>u(e.key),[`stop`])},[d(e)?(R(),q(z(Zt),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`})):(R(),q(z(Qt),{key:1,class:`size-3.5 shrink-0 text-fg-subtle`})),A(` `+V(e.label)+` `,1),M(z(It),{variant:`idle`},{default:j(()=>[A(`×`+V(e.count),1)]),_:2},1024)],8,d_)]),_:2},1024),M(z($),{class:`font-mono`},{default:j(()=>[A(V(e.taskID>0?`#${e.taskID}`:`—`),1)]),_:2},1024),M(z($),{class:`w-[55%] max-w-0`},{default:j(()=>[W(`span`,{class:`block truncate`,title:f(e).truncated?f(e).full:void 0},V(f(e).text),9,f_)]),_:2},1024),M(z($),null,{default:j(()=>[A(V(p(e)),1)]),_:2},1024)]),_:2},1032,[`class`,`role`,`tabindex`,`title`,`onClick`,`onKeydown`]),d(e)?(R(!0),G(H,{key:0},K(e.events,(t,n)=>(R(),q(t_,{key:`${e.key}:${n}`,event:t,onOpen:m},null 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 Pv(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 Fv(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 Iv(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 Lv(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 Rv=J([]),zv=J([]),Bv=J(!0),Vv=J(null),Hv=J(null),Uv=J(!1),Wv=J(null);async function Gv(){try{let e=await X.eventTypes(Mv.value);Bv.value=e.enabled!==!1,Rv.value=e.event_types||[],zv.value=e.proposals||[],Vv.value=null}catch(e){Vv.value=e.message||String(e)}}function Kv(e){return{headers:(e.headers||[]).map(e=>({...e})),payload:(e.payload||[]).map(e=>({...e}))}}function qv(e){Wv.value=null,Hv.value=e}function Jv(e){let t=ny.value.find(t=>String(t.id)===e.sample_id);qv({mode:`proposal`,id:null,source:e.source,name:``,rule:Kv(e.rule),headersText:``,body:t?.body||``,exampleHeaders:e.headers||{}})}function Yv(e=``){qv({mode:`paste`,id:null,source:e,name:``,rule:{headers:[],payload:[]},headersText:``,body:``,exampleHeaders:{}})}function Xv(e){qv({mode:`edit`,id:e.id,source:e.source,name:e.name,rule:Kv(e.rule),headersText:``,body:``,exampleHeaders:{}})}function Zv(){Hv.value=null}async function Qv(){let e=Hv.value;if(e){Uv.value=!0;try{if(e.mode===`edit`&&e.id)await X.eventTypeUpdate(e.id,{name:e.name,rule:Lv(e.rule)});else{let t=e.mode===`paste`?Nv(e.headersText):e.exampleHeaders;await X.eventTypeCreate({source:e.source,name:e.name,rule:e.mode===`paste`?void 0:Lv(e.rule),example:{headers:t,body:e.body}})}Hv.value=null,await Gv()}catch(e){Wv.value=e.message||String(e)}finally{Uv.value=!1}}}var $v=J(null);async function ey(){let e=$v.value;if($v.value=null,e)try{await X.eventTypeDelete(e.id),await Gv()}catch(e){Vv.value=e.message||String(e)}}var ty=100,ny=J([]),ry=J(!0),iy=J(null),ay=J(!0),oy=J(null);async function sy(){try{let e=await X.captures(ty);ry.value=e.enabled!==!1,ny.value=e.captures||[],iy.value=null}catch(e){iy.value=e.message||String(e)}finally{ay.value=!1}}function cy(e){let t=ny.value.find(t=>t.id===e);return t&&(oy.value=t),!!t}function ly(){ny.value.length&&(oy.value=ny.value[0])}function uy(){ce(`captures`,()=>{sy(),Gv()})}var dy=[`owner`,`admin`,`developer`,`viewer`],fy=J([]),py=J(!1),my=J(``),hy=J(null),gy=null;function _y(e=!1){return hy.value&&!e?Promise.resolve():gy||(gy=X.orgs().then(e=>{fy.value=e.orgs,py.value=e.instance_admin,my.value=e.current;let t=hy.value?.id??e.current;hy.value=e.orgs.find(e=>e.id===t)??e.orgs[0]??null}).finally(()=>{gy=null}),gy)}function vy(e){hy.value=fy.value.find(t=>t.id===e)??hy.value}var yy=hy,by={key:0,class:`text-xs text-fg-muted`},xy={key:1,class:`flex flex-col gap-1 text-xs`},Sy={key:1},Cy={key:2,class:`text-xs text-fg-muted`},wy=k({__name:`DispatchLinks`,props:{kind:{},id:{}},setup(e){let t=e,n=J([]),r=J(!1);F(()=>[t.kind,t.id],async()=>{r.value=!1;try{n.value=await X.dispatches(t.kind,t.id)}catch{n.value=[],r.value=!0}},{immediate:!0});let i=e=>({path:`/events`,query:{tab:`inspector`,capture:e}});return(e,a)=>{let o=Re(`RouterLink`);return r.value?(R(),G(`p`,by,`Dispatches unavailable.`)):n.value.length?(R(),G(`ul`,xy,[(R(!0),G(H,null,K(n.value,e=>(R(),G(`li`,{key:e.binding_id+e.capture_id,class:`flex flex-wrap items-center gap-x-2 font-mono text-fg-muted`},[t.kind===`bindings`?L(``,!0):(R(),q(o,{key:0,to:{path:`/events`,query:{tab:`bindings`}},class:`hover:text-foreground`},{default:j(()=>[A(`binding `+V(e.binding_id.slice(0,8))+` v`+V(e.binding_version),1)]),_:2},1024)),t.kind===`captures`?L(``,!0):(R(),q(o,{key:1,to:i(e.capture_id),class:`hover:text-foreground`},{default:j(()=>[A(`capture `+V(e.capture_id.slice(0,8)),1)]),_:2},1032,[`to`])),t.kind===`tasks`?L(``,!0):(R(),G(H,{key:2},[e.task_id?(R(),q(o,{key:0,to:`/tasks/${e.task_id}`,class:`text-foreground hover:underline`},{default:j(()=>[A(`task #`+V(e.task_id),1)]),_:2},1032,[`to`])):(R(),G(`span`,Sy,V(e.reason||`claimed, no task recorded`),1))],64)),W(`span`,null,V(z(Dh)(e.dispatched_at)),1)]))),128))])):t.kind===`tasks`?L(``,!0):(R(),G(`p`,Cy,` No dispatches yet. `))}}}),Ty=k({__name:`Spinner`,props:{class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e;return(e,n)=>(R(),q(z(pn),{role:`status`,"aria-label":`Loading`,class:N(z(Y)(`size-4 animate-spin`,t.class))},null,8,[`class`]))}});function Ey(e,t){return t?e.filter(e=>e.event_type_id===t):[]}function Dy(e){return(e?.repository??`required`)!==`none`}function Oy(e, Line truncated
`)}};iR.defaultYaml={explicit:!1,version:`1.2`},iR.defaultTags={"!!":`tag:yaml.org,2002:`};function aR(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function oR(e){let t=new Set;return ZL(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function sR(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function cR(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=oR(e);let a=sR(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&(UL(t.node)||GL(t.node)))t.node.anchor=t.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:r}}function lR(e,t,n,r){if(r&&typeof r==`object`){if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){let n=r[t],i=lR(e,r,String(t),n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(let t of Array.from(r.keys())){let n=r.get(t),i=lR(e,r,t,n);i===void 0?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(let t of Array.from(r)){let n=lR(e,r,t,t);n===void 0?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(let[t,n]of Object.entries(r)){let i=lR(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}function uR(e,t,n){if(Array.isArray(e))return e.map((e,t)=>uR(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!qL(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=e=>{r.res=e,delete n.onCreate};let i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e==`bigint`&&!n?.keep?Number(e):e}var dR=class{constructor(e){Object.defineProperty(this,RL,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!BL(e))throw TypeError(`A document argument is required`);let a={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n==`number`?n:100},o=uR(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?lR(i,{"":o},``,o):o}},fR=class extends dR{constructor(e){super(ML),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],ZL(e,{Node:(e,t)=>{(zL(t)||qL(t))&&n.push(t)}}),t&&(t.aliasResolveCache=n));let r;for(let e of n){if(e===this)break;e.anchor===this.source&&(r=e)}if(r&&t){let{anchors:e,doc:n,maxAliasCount:i}=t,a=e.get(r);if(a||=(uR(r,null,t),e.get(r)),a?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=pR(n,r,e)),a.count*a.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`)}return r}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}return t.anchors.get(n).res}toString(e,t,n){let r=`*${this.source}`;if(e){if(aR(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${r} `}return r}};function pR(e,t,n){if(zL(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(GL(t)){let r=0;for(let i of t.items){let t=pR(e,i,n);t>r&&(r=t)}return r}if(HL(t)){let r=pR(e,t.key,n),i=pR(e,t.value,n);return Math.max(r,i)}return 1}var mR=e=>!e||typeof e!=`function`&&typeof e!=`object`,hR=class extends dR{constructor(e){super(IL),this.value=e}toJSON(e,t){return t?.keep?this.value:uR(this.value,e,t)}toString(){return String(this.value)}};hR.BLOCK_FOLDED=`BLOCK_FOLDED`,hR.BLOCK_LITERAL=`BLOCK_LITERAL`,hR.PLAIN=`PLAIN`,hR.QUOTE_DOUBLE=`QUOTE_DOUBLE`,hR.QUOTE_SINGLE=`QUOTE_SINGLE`;var gR=`tag:yaml.org,2002:`;function _R(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function vR(e,t,n){if(BL(e)&&(e=e.contents),KL(e))return e;if(HL(e)){let t=n.schema[PL].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=n,c;if(r&&e&&typeof e==`object`){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new fR(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=gR+t.slice(2));let l=_R(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new hR(e);return c&&(c.node=t),t Line truncated
`)?CR(n,t):n.includes(`
Defaulting to \`null\`.`),null)}function Fs(e){return Ns(e)&&!Number.isNaN(e)&&e>0?e:(console.error(`Invalid prop \`max\` of value \`${e}\` supplied to \`ProgressRoot\`. Only numbers greater than 0 are valid max values. Defaulting to \`${As}\`.`),As)}var Is=k({__name:`ProgressRoot`,props:{modelValue:{type:[Number,null],required:!1},max:{type:Number,required:!1,default:As},getValueLabel:{type:Function,required:!1,default:(e,t)=>Ns(e)?`${Math.round(e/t*As)}%`:void 0},getValueText:{type:Function,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},emits:[`update:modelValue`,`update:max`],setup(e,{emit:t}){let n=e,r=t;v();let i=T(n,`modelValue`,r,{passive:n.modelValue===void 0}),a=T(n,`max`,r,{passive:n.max===void 0});F(()=>i.value,async e=>{let t=Ps(e,n.max);t!==e&&(await ft(),i.value=t)},{immediate:!0}),F(()=>n.max,e=>{let t=Fs(n.max);t!==e&&(a.value=t)},{immediate:!0});let o=I(()=>ai(i.value)?`indeterminate`:i.value===a.value?`complete`:`loading`);return Ms({modelValue:i,max:a,progressState:o}),(t,n)=>(R(),q(z(jt),{"as-child":e.asChild,as:e.as,"aria-valuemax":z(a),"aria-valuemin":0,"aria-valuenow":Ns(z(i))?z(i):void 0,"aria-valuetext":e.getValueText?.(z(i),z(a)),"aria-label":e.getValueLabel(z(i),z(a)),role:`progressbar`,"data-state":o.value,"data-value":z(i)??void 0,"data-max":z(a)},{default:j(()=>[P(t.$slots,`default`,{modelValue:z(i)})]),_:3},8,[`as-child`,`as`,`aria-valuemax`,`aria-valuenow`,`aria-valuetext`,`aria-label`,`data-state`,`data-value`,`data-max`]))}}),Ls=k({__name:`ProgressIndicator`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(e){let t=e,n=js();return v(),(e,r)=>(R(),q(z(jt),U(t,{"data-state":z(n).progressState.value,"data-value":z(n).modelValue?.value??void 0,"data-max":z(n).max.value}),{default:j(()=>[P(e.$slots,`default`)]),_:3},16,[`data-state`,`data-value`,`data-max`]))}}),Rs=`radio.select`;function zs(e,t,n){de(Rs,n,{originalEvent:e,value:t})}var Bs=k({inheritAttrs:!1,__name:`Radio`,props:{id:{type:String,required:!1},value:{type:null,required:!1},disabled:{type:Boolean,required:!1,default:!1},checked:{type:Boolean,required:!1,default:void 0},asChild:{type:Boolean,required:!1},as:{type:null,required:!1,default:`button`},name:{type:String,required:!1},required:{type:Boolean,required:!1}},emits:[`update:checked`,`select`],setup(e,{emit:t}){let n=e,r=t,i=T(n,`checked`,r,{passive:n.checked===void 0}),{value:a}=Be(n),{forwardRef:o,currentElement:s}=v(),c=mi(s),l=hi(),u=I(()=>n.id&&s.value?document.querySelector(`[for="${n.id}"]`)?.innerText:void 0);function d(e){n.disabled||zs(e,n.value,e=>{r(`select`,e),!e?.defaultPrevented&&(i.value=!0,c.value&&e.stopPropagation())})}return(t,n)=>(R(),G(H,null,[M(z(jt),U({id:e.id,ref:z(o),role:`radio`,type:e.as===`button`?`button`:void 0,as:e.as,"aria-checked":z(i)??!1,"aria-label":u.value,"as-child":e.asChild,disabled:e.disabled?``:void 0,"data-state":z(i)?`checked`:`unchecked`,"data-disabled":e.disabled?``:void 0,value:z(a),required:e.required,name:e.name},{...z(l),...t.$attrs},{onClick:Dt(d,[`stop`])}),{default:j(()=>[P(t.$slots,`default`,{checked:z(i)})]),_:3},16,[`id`,`type`,`as`,`aria-checked`,`aria-label`,`as-child`,`disabled`,`data-state`,`data-disabled`,`value`,`required`,`name`]),z(c)&&e.name?(R(),q(z(Ia),U({key:0,type:`radio`,tabindex:`-1`,value:z(a),checked:!!z(i),name:e.name,disabled:e.disabled,required:e.required},z(l)),null,16,[`value`,`checked`,`name`,`disabled`,`required`])):L(`v-if`,!0)],64))}}),[Vs,Hs]=be(`RadioGroupRoot`),Us=k({__name:`RadioGroupRoot`,props:{modelValue:{type:null,required:!1},defaultValue:{type:null,required:!1},disabled:{type:Boolean,required:!1,default:!1},orientation:{type:String,required:!1,default:void 0},dir:{type:String,required:!1},loop:{type:Boolean,required:!1,default:!0},asChild:{type:Boolean,required:!1},as:{type:null,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1,default:!1}},emits:[`update:modelValue`],setup(e,{emit:t}){let n=e,r=t,{forwardRef:i,currentElement:a}=v(),o=T(n,`modelValue`,r,{defaultValue:n.defaultValue,passive:n.modelValue===void 0}),{disabled:s,loop:c,orientation:l,name:u,required:d,dir:f}=Be(n),p=S(f),m=mi(a);return Hs({modelValue:o,changeModelValue:e=>{o.value=e},disabled:s,loop:c,orientation:l,name:u?.value,required:d}),(t,n)=>(R(),q(z(no),{"as-child":``,orientation:z(l),dir:z(p),loop:z(c)},{default:j(()=>[M(z(jt),{ref:z(i),role:`radiogroup`,"data-disabled":z(s)?``:void 0,"as-child":e.asChild,as:e.as,"aria-orientation":z(l),"aria-required":z(d),dir:z(p)},{default:j(()=>[P(t.$slots,`default`,{modelValue:z(o)}),z(m)&&z(u)?(R(),q(z(Ia),{key:0,required:z(d),disabled:z(s),value:z(o),name:z(u)},null,8,[`required`,`disabled`,`value`,`name`])):L(`v-if`,!0)]),_:3},8,[`data-disabled`,`as-child`,`as`,`aria-orientation`,`aria-required`,`dir`])]),_:3},8,[`orientation`,`dir`,`loop`]))}}),[Ws,Gs]=be(`RadioGroupItem`),Ks=k({inheritAttrs:!1,__name:`RadioGroupItem`,props:{id:{type:String,required:!1},value:{type:null,reqLine truncated
`),r=[],i=null,a=null,o=()=>{r.length&&(t.push({kind:`p`,inline:md(r.join(` `))}),r=[])},s=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>md(e))}),null)};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.push({kind:`pre`,code:a.join(`
`)}),a=null):a=[];continue}if(a){a.push(c);continue}let l=gd(c),u=e+1<n.length?gd(n[e+1]):null;if(l&&u&&_d(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=gd(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>md(e)),rows:r.map(e=>e.map(e=>md(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:md(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])}else c.startsWith(`>`)?(o(),s(),t.push({kind:`blockquote`,inline:md(c.replace(/^>\s?/,``))})):r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
`)}),t}function gd(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 _d(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var vd={class:`[overflow-wrap:anywhere]`},yd={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},bd={class:`font-mono text-[0.85em]`},xd={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},Sd={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},Cd={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},wd={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},Td={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`},Dd={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},Od={key:8,class:`mb-2.5 last:mb-0`},kd=k({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=I(()=>hd(t.text));return(e,t)=>(R(),G(`div`,vd,[(R(!0),G(H,null,K(n.value,(e,t)=>(R(),G(H,{key:t},[e.kind===`pre`?(R(),G(`pre`,yd,[W(`code`,bd,V(e.code),1)])):e.kind===`table`?(R(),G(`table`,xd,[W(`thead`,null,[W(`tr`,null,[(R(!0),G(H,null,K(e.head,(e,t)=>(R(),G(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[M(fd,{inline:e},null,8,[`inline`])]))),128))])]),W(`tbody`,null,[(R(!0),G(H,null,K(e.rows,(e,t)=>(R(),G(`tr`,{key:t},[(R(!0),G(H,null,K(e,(e,t)=>(R(),G(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[M(fd,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(R(),G(`blockquote`,Sd,[M(fd,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(R(),G(`h1`,Cd,[M(fd,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(R(),G(`h2`,wd,[M(fd,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(R(),G(`h3`,Td,[M(fd,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(R(),G(`ul`,Ed,[(R(!0),G(H,null,K(e.items,(e,t)=>(R(),G(`li`,{key:t},[M(fd,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(R(),G(`ol`,Dd,[(R(!0),G(H,null,K(e.items,(e,t)=>(R(),G(`li`,{key:t},[M(fd,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(R(),G(`p`,Od,[M(fd,{inline:e.inline},null,8,[`inline`])])):L(``,!0)],64))),128))]))}}),Ad={class:`truncate`},jd=k({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=Re(`RouterLink`);return R(),q(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:j(()=>[M(z(Wt),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),W(`span`,Ad,V(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),Md={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},Nd={class:`font-semibold text-foreground`},Pd={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},Fd=k({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=I(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=I(()=>t.tool.parameters||t.tool.Parameters||``),i=I(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=I(()=>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?(R(),q(jd,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(R(),G(`div`,Md,[M(z(Jn),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),W(`span`,Nd,V(n.value),1),r.value?(R(),G(`code`,Pd,V(r.value),1)):L(``,!0),W(`span`,{class:N(z(Y)(`text-fg-muted`,i.value&&`text-danger`))},V(a.value),3)]))}}),Id={key:0,class:`mb-2 grid gap-0.5 text-xs`},Ld={key:1,class:`mb-2 flex flex-wrap gap-1.5`},Rd={key:3,class:`whitespace-pre-wrap`},zd=k({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},media:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(R(),G(`div`,{class:N([`flex`,e.assistant?`justify-start`:`justify-end`])},[W(`div`,{class:N(z(Y)(`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?(R(),G(`div`,Id,[(R(!0),G(H,null,K(e.tools,(t,n)=>(R(),q(Fd,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):L(``,!0),e.media.length?(R(),G(`div`,Ld,[(R(!0),G(H,null,K(e.media,(e,t)=>(R(),q(ad,{key:t,attachment:e},null,8,[`attachment`]))),128))])):L(``,!0),e.assistant?(R(),q(kd,{key:2,text:e.text},null,8,[`text`])):(R(),G(`div`,Rd,V(e.text),1)),P(t.$slots,`default`)],2)],2))}}),Bd={class:`text-sm`},Vd={class:`font-medium`},Hd={key:0,class:`mt-1 text-fg-muted`},Ud={key:1,class:`mt-2 flex flex-wrap gap-2`},Wd=k({__name:`ChatChLine truncated
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>$g?`${n.slice(0,$g).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var t_=[`title`],n_=k({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=I(()=>Eg(n.event)),a=I(()=>e_(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=I(()=>n.event.at?Oh(n.event.at):`—`);return(e,t)=>(R(),q(z(Xg),{class:N(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:[Ot(Dt(o,[`prevent`]),[`enter`]),Ot(Dt(o,[`prevent`]),[`space`])]},{default:j(()=>[M(z($),{class:`font-medium`},{default:j(()=>[A(V(n.event.kind||n.event.type||`event`),1)]),_:1}),M(z($),{class:`font-mono`},{default:j(()=>[A(V(i.value>0?`#${i.value}`:`—`),1)]),_:1}),M(z($),{class:`w-[55%] max-w-0`},{default:j(()=>[W(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},V(a.value.text),9,t_)]),_:1}),M(z($),null,{default:j(()=>[A(V(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}}),r_=[{value:`all`,label:`All`},{value:`tasks`,label:`Tasks`},{value:`system`,label:`System`}];function i_(e){return(Number(e?.task_id)||0)>0}function a_(e,t){return t===`tasks`?i_(e):t!==`system`||!i_(e)}function o_(e,t){return e.filter(e=>a_(e,t))}function s_(e,t){return e>0?``:t===`all`?`Waiting for activity`:t===`tasks`?`No task events yet`:`No system events yet`}function c_(e,t){return`${e}:${t??0}`}function l_(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=c_(e_(n).text,r),a=t[t.length-1];a&&a.key===i?(a.count+=1,a.events.push(n)):t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var u_={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},d_={class:`max-h-[28rem] overflow-y-auto`},f_=[`aria-expanded`,`aria-label`,`onClick`],p_=[`title`],m_=k({__name:`LiveActivityCard`,setup(e){let t=jf(),{activity:n,streamKind:r,streamState:i}=Ae(ee()),a=J(`all`),o=I(()=>o_(n.value,a.value)),s=I(()=>s_(o.value.length,a.value)),c=tt(new Set),l=I(()=>l_(o.value));function u(e){c.has(e)?c.delete(e):c.add(e)}function d(e){return c.has(e.key)}function f(e){return e_(e.representative)}function p(e){return e.representative.at?Oh(e.representative.at):`—`}function m(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(R(),q(z(xh),null,{default:j(()=>[M(z(Eh),null,{default:j(()=>[M(z(Dh),null,{default:j(()=>[...t[1]||=[A(`Live activity`,-1)]]),_:1}),M(z(Sh),{class:`flex items-center gap-2`},{default:j(()=>[M(z(Kg),{modelValue:a.value,"onUpdate:modelValue":t[0]||=e=>a.value=e,label:`Filter activity`,options:z(r_)},null,8,[`modelValue`,`options`]),M(z(It),{variant:z(r)},{default:j(()=>[A(V(z(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),M(z(Ch),null,{default:j(()=>[W(`div`,u_,[W(`div`,d_,[M(z(Jg),null,{default:j(()=>[M(z(Qg),{class:`sticky top-0 z-10 bg-card`},{default:j(()=>[M(z(Xg),null,{default:j(()=>[M(z(Zg),null,{default:j(()=>[...t[2]||=[A(`Event`,-1)]]),_:1}),M(z(Zg),null,{default:j(()=>[...t[3]||=[A(`Task`,-1)]]),_:1}),M(z(Zg),null,{default:j(()=>[...t[4]||=[A(`Detail`,-1)]]),_:1}),M(z(Zg),null,{default:j(()=>[...t[5]||=[A(`When`,-1)]]),_:1})]),_:1})]),_:1}),M(z(Yg),null,{default:j(()=>[o.value.length?L(``,!0):(R(),q(z(Xg),{key:0},{default:j(()=>[M(z($),{colspan:`4`},{default:j(()=>[M(z(fh),null,{default:j(()=>[M(z(hh),null,{default:j(()=>[M(z(vh),null,{default:j(()=>[A(V(s.value),1)]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})),o.value.length?(R(!0),G(H,{key:1},K(l.value,e=>(R(),G(H,{key:e.key},[e.count===1?(R(),q(n_,{key:0,event:e.representative,onOpen:m},null,8,[`event`])):(R(),G(H,{key:1},[M(z(Xg),{class:N(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&&m(e.taskID),onKeydown:[Ot(Dt(t=>e.taskID>0&&m(e.taskID),[`prevent`]),[`enter`]),Ot(Dt(t=>e.taskID>0&&m(e.taskID),[`prevent`]),[`space`])]},{default:j(()=>[M(z($),{class:`font-medium`},{default:j(()=>[W(`button`,{type:`button`,class:`inline-flex items-center gap-1 rounded hover:opacity-80`,"aria-expanded":d(e),"aria-label":`${d(e)?`Hide`:`Show`} ${e.count} ${e.label} events`,onClick:Dt(t=>u(e.key),[`stop`])},[d(e)?(R(),q(z(Qt),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`})):(R(),q(z($t),{key:1,class:`size-3.5 shrink-0 text-fg-subtle`})),A(` `+V(e.label)+` `,1),M(z(It),{variant:`idle`},{default:j(()=>[A(`×`+V(e.count),1)]),_:2},1024)],8,f_)]),_:2},1024),M(z($),{class:`font-mono`},{default:j(()=>[A(V(e.taskID>0?`#${e.taskID}`:`—`),1)]),_:2},1024),M(z($),{class:`w-[55%] max-w-0`},{default:j(()=>[W(`span`,{class:`block truncate`,title:f(e).truncated?f(e).full:void 0},V(f(e).text),9,p_)]),_:2},1024),M(z($),null,{default:j(()=>[A(V(p(e)),1)]),_:2},1024)]),_:2},1032,[`class`,`role`,`tabindex`,`title`,`onClick`,`onKeydown`]),d(e)?(R(!0),G(H,{key:0},K(e.events,(t,n)=>(R(),q(n_,{key:`${e.key}:${n}`,event:t,onOpen:m},null 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 Fv(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 Iv(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 Lv(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 Rv(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 zv=J([]),Bv=J([]),Vv=J(!0),Hv=J(null),Uv=J(null),Wv=J(!1),Gv=J(null);async function Kv(){try{let e=await X.eventTypes(Nv.value);Vv.value=e.enabled!==!1,zv.value=e.event_types||[],Bv.value=e.proposals||[],Hv.value=null}catch(e){Hv.value=e.message||String(e)}}function qv(e){return{headers:(e.headers||[]).map(e=>({...e})),payload:(e.payload||[]).map(e=>({...e}))}}function Jv(e){Gv.value=null,Uv.value=e}function Yv(e){let t=ry.value.find(t=>String(t.id)===e.sample_id);Jv({mode:`proposal`,id:null,source:e.source,name:``,rule:qv(e.rule),headersText:``,body:t?.body||``,exampleHeaders:e.headers||{}})}function Xv(e=``){Jv({mode:`paste`,id:null,source:e,name:``,rule:{headers:[],payload:[]},headersText:``,body:``,exampleHeaders:{}})}function Zv(e){Jv({mode:`edit`,id:e.id,source:e.source,name:e.name,rule:qv(e.rule),headersText:``,body:``,exampleHeaders:{}})}function Qv(){Uv.value=null}async function $v(){let e=Uv.value;if(e){Wv.value=!0;try{if(e.mode===`edit`&&e.id)await X.eventTypeUpdate(e.id,{name:e.name,rule:Rv(e.rule)});else{let t=e.mode===`paste`?Pv(e.headersText):e.exampleHeaders;await X.eventTypeCreate({source:e.source,name:e.name,rule:e.mode===`paste`?void 0:Rv(e.rule),example:{headers:t,body:e.body}})}Uv.value=null,await Kv()}catch(e){Gv.value=e.message||String(e)}finally{Wv.value=!1}}}var ey=J(null);async function ty(){let e=ey.value;if(ey.value=null,e)try{await X.eventTypeDelete(e.id),await Kv()}catch(e){Hv.value=e.message||String(e)}}var ny=100,ry=J([]),iy=J(!0),ay=J(null),oy=J(!0),sy=J(null);async function cy(){try{let e=await X.captures(ny);iy.value=e.enabled!==!1,ry.value=e.captures||[],ay.value=null}catch(e){ay.value=e.message||String(e)}finally{oy.value=!1}}function ly(e){let t=ry.value.find(t=>t.id===e);return t&&(sy.value=t),!!t}function uy(){ry.value.length&&(sy.value=ry.value[0])}function dy(){ce(`captures`,()=>{cy(),Kv()})}var fy=[`owner`,`admin`,`developer`,`viewer`],py=J([]),my=J(!1),hy=J(``),gy=J(null),_y=null;function vy(e=!1){return gy.value&&!e?Promise.resolve():_y||(_y=X.orgs().then(e=>{py.value=e.orgs,my.value=e.instance_admin,hy.value=e.current;let t=gy.value?.id??e.current;gy.value=e.orgs.find(e=>e.id===t)??e.orgs[0]??null}).finally(()=>{_y=null}),_y)}function yy(e){gy.value=py.value.find(t=>t.id===e)??gy.value}var by=gy,xy={key:0,class:`text-xs text-fg-muted`},Sy={key:1,class:`flex flex-col gap-1 text-xs`},Cy={key:1},wy={key:2,class:`text-xs text-fg-muted`},Ty=k({__name:`DispatchLinks`,props:{kind:{},id:{}},setup(e){let t=e,n=J([]),r=J(!1);F(()=>[t.kind,t.id],async()=>{r.value=!1;try{n.value=await X.dispatches(t.kind,t.id)}catch{n.value=[],r.value=!0}},{immediate:!0});let i=e=>({path:`/events`,query:{tab:`inspector`,capture:e}});return(e,a)=>{let o=Re(`RouterLink`);return r.value?(R(),G(`p`,xy,`Dispatches unavailable.`)):n.value.length?(R(),G(`ul`,Sy,[(R(!0),G(H,null,K(n.value,e=>(R(),G(`li`,{key:e.binding_id+e.capture_id,class:`flex flex-wrap items-center gap-x-2 font-mono text-fg-muted`},[t.kind===`bindings`?L(``,!0):(R(),q(o,{key:0,to:{path:`/events`,query:{tab:`bindings`}},class:`hover:text-foreground`},{default:j(()=>[A(`binding `+V(e.binding_id.slice(0,8))+` v`+V(e.binding_version),1)]),_:2},1024)),t.kind===`captures`?L(``,!0):(R(),q(o,{key:1,to:i(e.capture_id),class:`hover:text-foreground`},{default:j(()=>[A(`capture `+V(e.capture_id.slice(0,8)),1)]),_:2},1032,[`to`])),t.kind===`tasks`?L(``,!0):(R(),G(H,{key:2},[e.task_id?(R(),q(o,{key:0,to:`/tasks/${e.task_id}`,class:`text-foreground hover:underline`},{default:j(()=>[A(`task #`+V(e.task_id),1)]),_:2},1032,[`to`])):(R(),G(`span`,Cy,V(e.reason||`claimed, no task recorded`),1))],64)),W(`span`,null,V(z(Oh)(e.dispatched_at)),1)]))),128))])):t.kind===`tasks`?L(``,!0):(R(),G(`p`,wy,` No dispatches yet. `))}}}),Ey=k({__name:`Spinner`,props:{class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e;return(e,n)=>(R(),q(z(mn),{role:`status`,"aria-label":`Loading`,class:N(z(Y)(`size-4 animate-spin`,t.class))},null,8,[`class`]))}});function Dy(e,t){return t?e.filter(e=>e.event_type_id===t):[]}function Oy(e){return(e?.repository??`required`)!==`none`}function ky(e, Line truncated
`)}};sR.defaultYaml={explicit:!1,version:`1.2`},sR.defaultTags={"!!":`tag:yaml.org,2002:`};function cR(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function lR(e){let t=new Set;return eR(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function uR(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function dR(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=lR(e);let a=uR(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&(KL(t.node)||JL(t.node)))t.node.anchor=t.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:r}}function fR(e,t,n,r){if(r&&typeof r==`object`){if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){let n=r[t],i=fR(e,r,String(t),n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(let t of Array.from(r.keys())){let n=r.get(t),i=fR(e,r,t,n);i===void 0?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(let t of Array.from(r)){let n=fR(e,r,t,t);n===void 0?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(let[t,n]of Object.entries(r)){let i=fR(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}function pR(e,t,n){if(Array.isArray(e))return e.map((e,t)=>pR(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!XL(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=e=>{r.res=e,delete n.onCreate};let i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e==`bigint`&&!n?.keep?Number(e):e}var mR=class{constructor(e){Object.defineProperty(this,VL,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!UL(e))throw TypeError(`A document argument is required`);let a={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n==`number`?n:100},o=pR(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?fR(i,{"":o},``,o):o}},hR=class extends mR{constructor(e){super(FL),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],eR(e,{Node:(e,t)=>{(HL(t)||XL(t))&&n.push(t)}}),t&&(t.aliasResolveCache=n));let r;for(let e of n){if(e===this)break;e.anchor===this.source&&(r=e)}if(r&&t){let{anchors:e,doc:n,maxAliasCount:i}=t,a=e.get(r);if(a||=(pR(r,null,t),e.get(r)),a?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=gR(n,r,e)),a.count*a.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`)}return r}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}return t.anchors.get(n).res}toString(e,t,n){let r=`*${this.source}`;if(e){if(cR(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${r} `}return r}};function gR(e,t,n){if(HL(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(JL(t)){let r=0;for(let i of t.items){let t=gR(e,i,n);t>r&&(r=t)}return r}if(GL(t)){let r=gR(e,t.key,n),i=gR(e,t.value,n);return Math.max(r,i)}return 1}var _R=e=>!e||typeof e!=`function`&&typeof e!=`object`,vR=class extends mR{constructor(e){super(zL),this.value=e}toJSON(e,t){return t?.keep?this.value:pR(this.value,e,t)}toString(){return String(this.value)}};vR.BLOCK_FOLDED=`BLOCK_FOLDED`,vR.BLOCK_LITERAL=`BLOCK_LITERAL`,vR.PLAIN=`PLAIN`,vR.QUOTE_DOUBLE=`QUOTE_DOUBLE`,vR.QUOTE_SINGLE=`QUOTE_SINGLE`;var yR=`tag:yaml.org,2002:`;function bR(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function xR(e,t,n){if(UL(e)&&(e=e.contents),YL(e))return e;if(GL(e)){let t=n.schema[LL].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=n,c;if(r&&e&&typeof e==`object`){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new hR(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=yR+t.slice(2));let l=bR(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new vR(e);return c&&(c.node=t),t Line truncated
`)?ER(n,t):n.includes(`
`)?`
`+CR(n,t):(e.endsWith(` `)?``:` `)+n,TR=`flow`,ER=`block`,DR=`quoted`;function OR(e,t,n=`flow`,{indentAtStart:r,lineWidth:i=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!i||i<0)return e;i<a&&(a=0);let c=Math.max(1+a,1+i-t.length);if(e.length<=c)return e;let l=[],u={},d=i-t.length;typeof r==`number`&&(r>i-Math.max(2,a)?l.push(0):d=i-r);let f,p,m=!1,h=-1,g=-1,_=-1;n===`block`&&(h=kR(e,h,t.length),h!==-1&&(d=h+c));for(let r;r=e[h+=1];){if(n===`quoted`&&r===`\\`){switch(g=h,e[h+1]){case`x`:h+=3;break;case`u`:h+=5;break;case`U`:h+=9;break;default:h+=1}_=h}if(r===`
`)n===`block`&&(h=kR(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(r===` `&&p&&p!==` `&&p!==`
`+ER(n,t):(e.endsWith(` `)?``:` `)+n,OR=`flow`,kR=`block`,AR=`quoted`;function jR(e,t,n=`flow`,{indentAtStart:r,lineWidth:i=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!i||i<0)return e;i<a&&(a=0);let c=Math.max(1+a,1+i-t.length);if(e.length<=c)return e;let l=[],u={},d=i-t.length;typeof r==`number`&&(r>i-Math.max(2,a)?l.push(0):d=i-r);let f,p,m=!1,h=-1,g=-1,_=-1;n===`block`&&(h=MR(e,h,t.length),h!==-1&&(d=h+c));for(let r;r=e[h+=1];){if(n===`quoted`&&r===`\\`){switch(g=h,e[h+1]){case`x`:h+=3;break;case`u`:h+=5;break;case`U`:h+=9;break;default:h+=1}_=h}if(r===`
`)n===`block`&&(h=MR(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(r===` `&&p&&p!==` `&&p!==`
`&&p!==` `){let t=e[h+1];t&&t!==` `&&t!==`
`&&t!==` `&&(f=h)}if(h>=d){if(f)l.push(f),d=f+c,f=void 0;else if(n===`quoted`){for(;p===` `||p===` `;)p=r,r=e[h+=1],m=!0;let t=h>_+1?h-2:g-1;if(u[t])return e;l.push(t),u[t]=!0,d=t+c,f=void 0}else m=!0}}p=r}if(m&&s&&s(),l.length===0)return e;o&&o();let v=e.slice(0,l[0]);for(let r=0;r<l.length;++r){let i=l[r],a=l[r+1]||e.length;i===0?v=`\n${t}${e.slice(0,a)}`:(n===`quoted`&&u[i]&&(v+=`${e[i]}\\`),v+=`\n${t}${e.slice(i+1,a)}`)}return v}function kR(e,t,n){let r=t,i=t+1,a=e[i];for(;a===` `||a===` `;)if(t<i+n)a=e[++t];else{do a=e[++t];while(a&&a!==`
`);r=t,i=t+1,a=e[i]}return r}var AR=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),jR=e=>/^(%|---|\.\.\.)/m.test(e);function MR(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
`){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function NR(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(jR(e)?` `:``),o=``,s=0;for(let e=0,t=n[e];t;t=n[++e])if(t===` `&&n[e+1]===`\\`&&n[e+2]===`n`&&(o+=n.slice(s,e)+`\\ `,e+=1,s=e,t=`\\`),t===`\\`)switch(n[e+1]){case`u`:{o+=n.slice(s,e);let t=n.substr(e+2,4);switch(t){case`0000`:o+=`\\0`;break;case`0007`:o+=`\\a`;break;case`000b`:o+=`\\v`;break;case`001b`:o+=`\\e`;break;case`0085`:o+=`\\N`;break;case`00a0`:o+=`\\_`;break;case`2028`:o+=`\\L`;break;case`2029`:o+=`\\P`;break;default:t.substr(0,2)===`00`?o+=`\\x`+t.substr(2):o+=n.substr(e,6)}e+=5,s=e+1}break;case`n`:if(r||n[e+2]===`"`||n.length<i)e+=1;else{for(o+=n.slice(s,e)+`
`&&t!==` `&&(f=h)}if(h>=d){if(f)l.push(f),d=f+c,f=void 0;else if(n===`quoted`){for(;p===` `||p===` `;)p=r,r=e[h+=1],m=!0;let t=h>_+1?h-2:g-1;if(u[t])return e;l.push(t),u[t]=!0,d=t+c,f=void 0}else m=!0}}p=r}if(m&&s&&s(),l.length===0)return e;o&&o();let v=e.slice(0,l[0]);for(let r=0;r<l.length;++r){let i=l[r],a=l[r+1]||e.length;i===0?v=`\n${t}${e.slice(0,a)}`:(n===`quoted`&&u[i]&&(v+=`${e[i]}\\`),v+=`\n${t}${e.slice(i+1,a)}`)}return v}function MR(e,t,n){let r=t,i=t+1,a=e[i];for(;a===` `||a===` `;)if(t<i+n)a=e[++t];else{do a=e[++t];while(a&&a!==`
`);r=t,i=t+1,a=e[i]}return r}var NR=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),PR=e=>/^(%|---|\.\.\.)/m.test(e);function FR(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
`){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function IR(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(PR(e)?` `:``),o=``,s=0;for(let e=0,t=n[e];t;t=n[++e])if(t===` `&&n[e+1]===`\\`&&n[e+2]===`n`&&(o+=n.slice(s,e)+`\\ `,e+=1,s=e,t=`\\`),t===`\\`)switch(n[e+1]){case`u`:{o+=n.slice(s,e);let t=n.substr(e+2,4);switch(t){case`0000`:o+=`\\0`;break;case`0007`:o+=`\\a`;break;case`000b`:o+=`\\v`;break;case`001b`:o+=`\\e`;break;case`0085`:o+=`\\N`;break;case`00a0`:o+=`\\_`;break;case`2028`:o+=`\\L`;break;case`2029`:o+=`\\P`;break;default:t.substr(0,2)===`00`?o+=`\\x`+t.substr(2):o+=n.substr(e,6)}e+=5,s=e+1}break;case`n`:if(r||n[e+2]===`"`||n.length<i)e+=1;else{for(o+=n.slice(s,e)+`
`;n[e+2]===`\\`&&n[e+3]===`n`&&n[e+4]!==`"`;)o+=`
`,e+=2;o+=a,n[e+2]===` `&&(o+=`\\`),e+=1,s=e+1}break;default:e+=1}return o=s?o+n.slice(s):n,r?o:OR(o,a,DR,AR(t,!1))}function PR(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
`)||/[ \t]\n|\n[ \t]/.test(e))return NR(e,t);let n=t.indent||(jR(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:OR(r,n,TR,AR(t,!1))}function FR(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=NR;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?PR:i&&!t?NR:n?PR:NR}return r(e,t)}var IR;try{IR=RegExp(`(^|(?<!
`,e+=2;o+=a,n[e+2]===` `&&(o+=`\\`),e+=1,s=e+1}break;default:e+=1}return o=s?o+n.slice(s):n,r?o:jR(o,a,AR,NR(t,!1))}function LR(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
`)||/[ \t]\n|\n[ \t]/.test(e))return IR(e,t);let n=t.indent||(PR(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:jR(r,n,OR,NR(t,!1))}function RR(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=IR;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?LR:i&&!t?IR:n?LR:IR}return r(e,t)}var zR;try{zR=RegExp(`(^|(?<!
))
+(?!
|$)`,`g`)}catch{IR=/\n+(?!\n|$)/g}function LR({comment:e,type:t,value:n},r,i,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n))return FR(n,r);let l=r.indent||(r.forceBlockIndent||jR(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===hR.BLOCK_FOLDED?!1:t===hR.BLOCK_LITERAL||!MR(n,c,l.length);if(!n)return u?`|
|$)`,`g`)}catch{zR=/\n+(?!\n|$)/g}function BR({comment:e,type:t,value:n},r,i,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n))return RR(n,r);let l=r.indent||(r.forceBlockIndent||PR(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===vR.BLOCK_FOLDED?!1:t===vR.BLOCK_LITERAL||!FR(n,c,l.length);if(!n)return u?`|
`:`>
`;let d,f;for(f=n.length;f>0;--f){let e=n[f-1];if(e!==`
`&&e!==` `&&e!==` `)break}let p=n.substring(f),m=p.indexOf(`
`);m===-1?d=`-`:n===p||m!==p.length-1?(d=`+`,a&&a()):d=``,p&&=(n=n.slice(0,-p.length),p[p.length-1]===`
`&&(p=p.slice(0,-1)),p.replace(IR,`$&${l}`));let h=!1,g,_=-1;for(g=0;g<n.length;++g){let e=n[g];if(e===` `)h=!0;else if(e===`
`&&(p=p.slice(0,-1)),p.replace(zR,`$&${l}`));let h=!1,g,_=-1;for(g=0;g<n.length;++g){let e=n[g];if(e===` `)h=!0;else if(e===`
`)_=g;else break}let v=n.substring(0,_<g?_+1:g);v&&=(n=n.substring(v.length),v.replace(/\n+/g,`$&${l}`));let y=(h?l?`2`:`1`:``)+d;if(e&&(y+=` `+s(e.replace(/ ?[\r\n]+/g,` `)),i&&i()),!u){let e=n.replace(/\n+/g,`
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${l}`),i=!1,a=AR(r,!0);o!==`folded`&&t!==hR.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=OR(`${v}${e}${p}`,l,ER,a);if(!i)return`>${y}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${y}\n${l}${v}${n}${p}`}function RR(e,t,n,r){let{type:i,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
`)||u&&/[[\]{},]/.test(a))return FR(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
`)?FR(a,t):LR(e,t,n,r);if(!s&&!u&&i!==hR.PLAIN&&a.includes(`
`))return LR(e,t,n,r);if(jR(a)){if(c===``)return t.forceBlockIndent=!0,LR(e,t,n,r);if(s&&c===l)return FR(a,t)}let d=a.replace(/\n+/g,`$&\n${c}`);if(o){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(d),{compat:n,tags:r}=t.doc.schema;if(r.some(e)||n?.some(e))return FR(a,t)}return s?d:OR(d,c,TR,AR(t,!1))}function zR(e,t,n,r){let{implicitKey:i,inFlow:a}=t,o=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==hR.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=hR.QUOTE_DOUBLE);let c=e=>{switch(e){case hR.BLOCK_FOLDED:case hR.BLOCK_LITERAL:return i||a?FR(o.value,t):LR(o,t,n,r);case hR.QUOTE_DOUBLE:return NR(o.value,t);case hR.QUOTE_SINGLE:return PR(o.value,t);case hR.PLAIN:return RR(o,t,n,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:e,defaultStringType:n}=t.options,r=i&&e||n;if(l=c(r),l===null)throw Error(`Unsupported default string type ${r}`)}return l}function BR(e,t){let n=Object.assign({blockQuote:!0,commentString:SR,defaultKeyType:null,defaultStringType:`PLAIN`,directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:`false`,flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:`null`,simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:`true`,verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case`block`:r=!1;break;case`flow`:r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:r,options:n}}function VR(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let n,r;if(UL(t)){r=t.value;let i=e.filter(e=>e.identify?.(r));if(i.length>1){let e=i.filter(e=>e.test);e.length>0&&(i=e)}n=i.find(e=>e.format===t.format)??i.find(e=>!e.format)}else r=t,n=e.find(e=>e.nodeClass&&r instanceof e.nodeClass);if(!n){let e=r?.constructor?.name??(r===null?`null`:typeof r);throw Error(`Tag not resolved for ${e} value`)}return n}function HR(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=(UL(e)||GL(e))&&e.anchor;a&&aR(a)&&(n.add(a),i.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&i.push(r.directives.tagString(o)),i.join(` `)}function UR(e,t,n,r){if(HL(e))return e.toString(t,n,r);if(zL(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError(`Cannot stringify circular structure without alias nodes`);t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,a=KL(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=VR(t.doc.schema.tags,a);let o=HR(a,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof i.stringify==`function`?i.stringify(a,t,n,r):UL(a)?zR(a,t,n,r):a.toString(t,n,r);return o?UL(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}function WR({key:e,value:t},n,r,i){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n,f=KL(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(GL(e)||!KL(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let p=!d&&(!e||f&&t==null&&!n.inFlow||GL(e)||(UL(e)?e.type===hR.BLOCK_FOLDED||e.type===hR.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=UR(e,n,()=>m=!0,()=>h=!0);if(!p&&!n.inFlow&&g.length>1024){if(d)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);p=!0}if(n.inFlow){if(a||t==null)return m&&r&&r(),g===``?`?`:p?`? ${g}`:g}else if(a&&!d||t==null&&p)return g=`? ${g}`,f&&!m?g+=wR(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=wR(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=wR(g,n.indent,l(f))));let _,v,y;KL(t)?(_=!!t.spaceBefore,v=t.commentBefore,y=t.comment):(_=!1,v=null,y=null,t&&typeof t==`object`&&(t=o.createNode(t))),n.implicitKey=!1,!p&&!f&&UL(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&WL(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let b=!1,x=UR(t,n,()=>b=!0,()=>h=!0),S=` `;if(f||_||v){if(S=_?`
`:``,v){let e=l(v);S+=`\n${CR(e,n.indent)}`}x===``&&!n.inFlow?S===`
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${l}`),i=!1,a=NR(r,!0);o!==`folded`&&t!==vR.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=jR(`${v}${e}${p}`,l,kR,a);if(!i)return`>${y}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${y}\n${l}${v}${n}${p}`}function VR(e,t,n,r){let{type:i,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
`)||u&&/[[\]{},]/.test(a))return RR(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
`)?RR(a,t):BR(e,t,n,r);if(!s&&!u&&i!==vR.PLAIN&&a.includes(`
`))return BR(e,t,n,r);if(PR(a)){if(c===``)return t.forceBlockIndent=!0,BR(e,t,n,r);if(s&&c===l)return RR(a,t)}let d=a.replace(/\n+/g,`$&\n${c}`);if(o){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(d),{compat:n,tags:r}=t.doc.schema;if(r.some(e)||n?.some(e))return RR(a,t)}return s?d:jR(d,c,OR,NR(t,!1))}function HR(e,t,n,r){let{implicitKey:i,inFlow:a}=t,o=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==vR.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=vR.QUOTE_DOUBLE);let c=e=>{switch(e){case vR.BLOCK_FOLDED:case vR.BLOCK_LITERAL:return i||a?RR(o.value,t):BR(o,t,n,r);case vR.QUOTE_DOUBLE:return IR(o.value,t);case vR.QUOTE_SINGLE:return LR(o.value,t);case vR.PLAIN:return VR(o,t,n,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:e,defaultStringType:n}=t.options,r=i&&e||n;if(l=c(r),l===null)throw Error(`Unsupported default string type ${r}`)}return l}function UR(e,t){let n=Object.assign({blockQuote:!0,commentString:TR,defaultKeyType:null,defaultStringType:`PLAIN`,directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:`false`,flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:`null`,simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:`true`,verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case`block`:r=!1;break;case`flow`:r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:r,options:n}}function WR(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let n,r;if(KL(t)){r=t.value;let i=e.filter(e=>e.identify?.(r));if(i.length>1){let e=i.filter(e=>e.test);e.length>0&&(i=e)}n=i.find(e=>e.format===t.format)??i.find(e=>!e.format)}else r=t,n=e.find(e=>e.nodeClass&&r instanceof e.nodeClass);if(!n){let e=r?.constructor?.name??(r===null?`null`:typeof r);throw Error(`Tag not resolved for ${e} value`)}return n}function GR(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=(KL(e)||JL(e))&&e.anchor;a&&cR(a)&&(n.add(a),i.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&i.push(r.directives.tagString(o)),i.join(` `)}function KR(e,t,n,r){if(GL(e))return e.toString(t,n,r);if(HL(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError(`Cannot stringify circular structure without alias nodes`);t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,a=YL(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=WR(t.doc.schema.tags,a);let o=GR(a,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof i.stringify==`function`?i.stringify(a,t,n,r):KL(a)?HR(a,t,n,r):a.toString(t,n,r);return o?KL(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}function qR({key:e,value:t},n,r,i){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n,f=YL(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(JL(e)||!YL(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let p=!d&&(!e||f&&t==null&&!n.inFlow||JL(e)||(KL(e)?e.type===vR.BLOCK_FOLDED||e.type===vR.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=KR(e,n,()=>m=!0,()=>h=!0);if(!p&&!n.inFlow&&g.length>1024){if(d)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);p=!0}if(n.inFlow){if(a||t==null)return m&&r&&r(),g===``?`?`:p?`? ${g}`:g}else if(a&&!d||t==null&&p)return g=`? ${g}`,f&&!m?g+=DR(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=DR(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=DR(g,n.indent,l(f))));let _,v,y;YL(t)?(_=!!t.spaceBefore,v=t.commentBefore,y=t.comment):(_=!1,v=null,y=null,t&&typeof t==`object`&&(t=o.createNode(t))),n.implicitKey=!1,!p&&!f&&KL(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&qL(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let b=!1,x=KR(t,n,()=>b=!0,()=>h=!0),S=` `;if(f||_||v){if(S=_?`
`:``,v){let e=l(v);S+=`\n${ER(e,n.indent)}`}x===``&&!n.inFlow?S===`
`&&y&&(S=`
`):S+=`\n${n.indent}`}else if(!p&&GL(t)){let e=x[0],r=x.indexOf(`
`):S+=`\n${n.indent}`}else if(!p&&JL(t)){let e=x[0],r=x.indexOf(`
`),i=r!==-1,a=n.inFlow??t.flow??t.items.length===0;if(i||!a){let t=!1;if(i&&(e===`&`||e===`!`)){let n=x.indexOf(` `);e===`&`&&n!==-1&&n<r&&x[n+1]===`!`&&(n=x.indexOf(` `,n+1)),(n===-1||r<n)&&(t=!0)}t||(S=`\n${n.indent}`)}}else(x===``||x[0]===`
`)&&(S=``);return g+=S+x,n.inFlow?b&&r&&r():y&&!b?g+=wR(g,n.indent,l(y)):h&&i&&i(),g}function GR(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var KR=`<<`,qR={identify:e=>e===KR||typeof e==`symbol`&&e.description===KR,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new hR(Symbol(KR)),{addToJSMap:YR}),stringify:()=>KR},JR=(e,t)=>(qR.identify(t)||UL(t)&&(!t.type||t.type===hR.PLAIN)&&qR.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===qR.tag&&e.default);function YR(e,t,n){let r=ZR(e,n);if(WL(r))for(let n of r.items)XR(e,t,n);else if(Array.isArray(r))for(let n of r)XR(e,t,n);else XR(e,t,r)}function XR(e,t,n){let r=ZR(e,n);if(!VL(r))throw Error(`Merge sources must be maps or map aliases`);let i=r.toJSON(null,e,Map);for(let[e,n]of i)t instanceof Map?t.has(e)||t.set(e,n):t instanceof Set?t.add(e):Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0});return t}function ZR(e,t){return e&&zL(t)?t.resolve(e.doc,e):t}function QR(e,t,{key:n,value:r}){if(KL(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(JR(e,n))YR(e,t,r);else{let i=uR(n,``,e);if(t instanceof Map)t.set(i,uR(r,i,e));else if(t instanceof Set)t.add(i);else{let a=$R(n,i,e),o=uR(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function $R(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(KL(e)&&n?.doc){let t=BR(n.doc,{});t.anchors=new Set;for(let e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=!0,t.inStringifyKey=!0;let r=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(r);e.length>40&&(e=e.substring(0,36)+`..."`),GR(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}function ez(e,t,n){return new tz(vR(e,void 0,n),vR(t,void 0,n))}var tz=class e{constructor(e,t=null){Object.defineProperty(this,RL,{value:FL}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return KL(n)&&(n=n.clone(t)),KL(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return QR(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?WR(this,e,t,n):JSON.stringify(this)}};function nz(e,t,n){return(t.inFlow??e.flow?iz:rz)(e,t,n)}function rz({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:a,type:null}),d=!1,f=[];for(let e=0;e<t.length;++e){let i=t[e],o=null;if(KL(i))!d&&i.spaceBefore&&f.push(``),az(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if(HL(i)){let e=KL(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),az(n,f,e.commentBefore,d))}d=!1;let s=UR(i,u,()=>o=null,()=>d=!0);o&&(s+=wR(s,a,l(o))),d&&o&&(d=!1),f.push(r+s)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let e=1;e<f.length;++e){let t=f[e];p+=t?`\n${c}${t}`:`
`)&&(S=``);return g+=S+x,n.inFlow?b&&r&&r():y&&!b?g+=DR(g,n.indent,l(y)):h&&i&&i(),g}function JR(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var YR=`<<`,XR={identify:e=>e===YR||typeof e==`symbol`&&e.description===YR,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new vR(Symbol(YR)),{addToJSMap:QR}),stringify:()=>YR},ZR=(e,t)=>(XR.identify(t)||KL(t)&&(!t.type||t.type===vR.PLAIN)&&XR.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===XR.tag&&e.default);function QR(e,t,n){let r=ez(e,n);if(qL(r))for(let n of r.items)$R(e,t,n);else if(Array.isArray(r))for(let n of r)$R(e,t,n);else $R(e,t,r)}function $R(e,t,n){let r=ez(e,n);if(!WL(r))throw Error(`Merge sources must be maps or map aliases`);let i=r.toJSON(null,e,Map);for(let[e,n]of i)t instanceof Map?t.has(e)||t.set(e,n):t instanceof Set?t.add(e):Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0});return t}function ez(e,t){return e&&HL(t)?t.resolve(e.doc,e):t}function tz(e,t,{key:n,value:r}){if(YL(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(ZR(e,n))QR(e,t,r);else{let i=pR(n,``,e);if(t instanceof Map)t.set(i,pR(r,i,e));else if(t instanceof Set)t.add(i);else{let a=nz(n,i,e),o=pR(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function nz(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(YL(e)&&n?.doc){let t=UR(n.doc,{});t.anchors=new Set;for(let e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=!0,t.inStringifyKey=!0;let r=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(r);e.length>40&&(e=e.substring(0,36)+`..."`),JR(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}function rz(e,t,n){return new iz(xR(e,void 0,n),xR(t,void 0,n))}var iz=class e{constructor(e,t=null){Object.defineProperty(this,VL,{value:RL}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return YL(n)&&(n=n.clone(t)),YL(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return tz(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?qR(this,e,t,n):JSON.stringify(this)}};function az(e,t,n){return(t.inFlow??e.flow?sz:oz)(e,t,n)}function oz({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:a,type:null}),d=!1,f=[];for(let e=0;e<t.length;++e){let i=t[e],o=null;if(YL(i))!d&&i.spaceBefore&&f.push(``),cz(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if(GL(i)){let e=YL(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),cz(n,f,e.commentBefore,d))}d=!1;let s=KR(i,u,()=>o=null,()=>d=!0);o&&(s+=DR(s,a,l(o))),d&&o&&(d=!1),f.push(r+s)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let e=1;e<f.length;++e){let t=f[e];p+=t?`\n${c}${t}`:`
`}}return e?(p+=`
`+CR(l(e),c),s&&s()):d&&o&&o(),p}function iz({items:e},t,{flowChars:n,itemIndent:r}){let{indent:i,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let n=0;n<e.length;++n){let i=e[n],a=null;if(KL(i))i.spaceBefore&&d.push(``),az(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(HL(i)){let e=KL(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),az(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=KL(i.value)?i.value:null;n?(n.comment&&(a=n.comment),n.commentBefore&&(l=!0)):i.value==null&&e?.comment&&(a=e.comment)}a&&(l=!0);let o=UR(i,c,()=>a=null);l||=d.length>u||o.includes(`
`),n<e.length-1?o+=`,`:t.options.trailingComma&&(t.options.lineWidth>0&&(l||=d.reduce((e,t)=>e+t.length+2,2)+(o.length+2)>t.options.lineWidth),l&&(o+=`,`)),a&&(o+=wR(o,r,s(a))),d.push(o),u=d.length}let{start:f,end:p}=n;if(d.length===0)return f+p;if(!l){let e=d.reduce((e,t)=>e+t.length+2,2);l=t.options.lineWidth>0&&e>t.options.lineWidth}if(l){let e=f;for(let t of d)e+=t?`\n${a}${i}${t}`:`
`;return`${e}\n${i}${p}`}return`${f}${o}${d.join(` `)}${o}${p}`}function az({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=CR(t(r),e);n.push(i.trimStart())}}function oz(e,t){let n=UL(t)?t.value:t;for(let r of e)if(HL(r)&&(r.key===t||r.key===n||UL(r.key)&&r.key.value===n))return r}var sz=class extends xR{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(PL,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,a=new this(e),o=(e,o)=>{if(typeof i==`function`)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(o!==void 0||r)&&a.items.push(ez(e,o,n))};if(t instanceof Map)for(let[e,n]of t)o(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))o(e,t[e]);return typeof e.sortMapEntries==`function`&&a.items.sort(e.sortMapEntries),a}add(e,t){let n;n=HL(e)?e:!e||typeof e!=`object`||!(`key`in e)?new tz(e,e?.value):new tz(e.key,e.value);let r=oz(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);UL(r.value)&&mR(n.value)?r.value.value=n.value:r.value=n.value}else if(i){let e=this.items.findIndex(e=>i(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=oz(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=oz(this.items,e)?.value;return(!t&&UL(n)?n.value:n)??void 0}has(e){return!!oz(this.items,e)}set(e,t){this.add(new tz(e,t),!0)}toJSON(e,t,n){let r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let e of this.items)QR(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!HL(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),nz(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}},cz={collection:`map`,default:!0,nodeClass:sz,tag:`tag:yaml.org,2002:map`,resolve(e,t){return VL(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>sz.from(e,t,n)},lz=class extends xR{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(LL,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=uz(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=uz(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&UL(r)?r.value:r}has(e){let t=uz(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=uz(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];UL(r)&&mR(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(uR(e,String(r++),t));return n}toString(e,t,n){return e?nz(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let a of t){if(typeof r==`function`){let n=t instanceof Set?a:String(e++);a=r.call(t,n,a)}i.items.push(vR(a,void 0,n))}}return i}};function uz(e){let t=UL(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var dz={collection:`seq`,default:!0,nodeClass:lz,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return WL(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>lz.from(e,t,n)},fz={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),zR(e,t,n,r)}},pz={identify:e=>e==null,createNode:()=>new hR(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new hR(null),stringify:({source:e},t)=>typeof e==`string`&&pz.test.test(e)?e:t.options.nullStr},mz={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new hR(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},n){return e&&mz.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}};function hz({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r==`bigint`)return String(r);let i=typeof r==`number`?r:Number(r);if(!isFinite(i))return isNaN(i)?`.nan`:i<0?`-.inf`:`.inf`;let a=Object.is(r,-0)?`-0`:JSON.stringify(r);if(!e&&t&&(!n||n===`tag:yaml.org,2002:float`)&&/^-?\d/.test(a)&&!a.includes(`e`)){let e=a.indexOf(`.`);e<0&&(e=a.length,a+=`.`);let n=t-(a.length-e-1);for(;n-->0;)a+=`0`}return a}var gz={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:hz},_z={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),string Line truncated
`:` `)}return zR({comment:e,type:t,value:s},r,i,a)}};function jz(e,t){if(WL(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!HL(r)){if(VL(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new tz(new hR(null));if(r.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${r.commentBefore}\n${e.key.commentBefore}`:r.commentBefore),r.comment){let t=e.value??e.key;t.comment=t.comment?`${r.comment}\n${t.comment}`:r.comment}r=e}e.items[n]=HL(r)?r:new tz(r)}}else t(`Expected a sequence for this tag`);return e}function Mz(e,t,n){let{replacer:r}=n,i=new lz(e);i.tag=`tag:yaml.org,2002:pairs`;let a=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof r==`function`&&(e=r.call(t,String(a++),e));let o,s;if(Array.isArray(e)){if(e.length===2)o=e[0],s=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)o=t[0],s=e[o];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else o=e;i.items.push(ez(o,s,n))}return i}var Nz={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:jz,createNode:Mz},Pz=class e extends lz{constructor(){super(),this.add=sz.prototype.add.bind(this),this.delete=sz.prototype.delete.bind(this),this.get=sz.prototype.get.bind(this),this.has=sz.prototype.has.bind(this),this.set=sz.prototype.set.bind(this),this.tag=e.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let e of this.items){let r,i;if(HL(e)?(r=uR(e.key,``,t),i=uR(e.value,r,t)):r=uR(e,``,t),n.has(r))throw Error(`Ordered maps must not include duplicate keys`);n.set(r,i)}return n}static from(e,t,n){let r=Mz(e,t,n),i=new this;return i.items=r.items,i}};Pz.tag=`tag:yaml.org,2002:omap`;var Fz={collection:`seq`,identify:e=>e instanceof Map,nodeClass:Pz,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=jz(e,t),r=[];for(let{key:e}of n.items)UL(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new Pz,n)},createNode:(e,t,n)=>Pz.from(e,t,n)};function Iz({value:e,source:t},n){return t&&(e?Lz:Rz).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var Lz={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new hR(!0),stringify:Iz},Rz={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new hR(!1),stringify:Iz},zz={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:hz},Bz={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():hz(e)}},Vz={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new hR(parseFloat(e.replace(/_/g,``))),n=e.indexOf(`.`);if(n!==-1){let r=e.substring(n+1).replace(/_/g,``);r[r.length-1]===`0`&&(t.minFractionDigits=r.length)}return t},stringify:hz},Hz=e=>typeof e==`bigint`||Number.isInteger(e);function Uz(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function Wz(e,t,n){let{value:r}=e;if(Hz(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return hz(e)}var Gz={identify:Hz,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Uz(e,2,2,n),stringify:e=>Wz(e,2,`0b`)},Kz={identify:Hz,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Uz(e,1,8,n),stringify:e=>Wz(e,8,`0`)},qz={identify:Hz,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Uz(e,0,10,n),stringify:hz},Jz={identify:Hz,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Uz(e,2,16,n),stringify:e=>Wz(e,16,`0x`)},Yz=class e extends sz{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=HL(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new tz(e.key,null):new tz(e,null),oz(this.items,t.key)||this.items.push(t)}get(e,t){let n=oz(this.items,e);return!t&&HL(n)?UL(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=oz(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new tz(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return s Line truncated
`)?(n.push(`...`),n.push(CR(t,``))):n.push(`... ${t}`)}else n.push(`...`)}else{let t=e.comment;t&&o&&(t=t.replace(/^\n+/,``)),t&&((!o||s)&&n[n.length-1]!==``&&n.push(``),n.push(CR(a(t),``)))}return n.join(`
`+ER(l(e),c),s&&s()):d&&o&&o(),p}function sz({items:e},t,{flowChars:n,itemIndent:r}){let{indent:i,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let n=0;n<e.length;++n){let i=e[n],a=null;if(YL(i))i.spaceBefore&&d.push(``),cz(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(GL(i)){let e=YL(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),cz(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=YL(i.value)?i.value:null;n?(n.comment&&(a=n.comment),n.commentBefore&&(l=!0)):i.value==null&&e?.comment&&(a=e.comment)}a&&(l=!0);let o=KR(i,c,()=>a=null);l||=d.length>u||o.includes(`
`),n<e.length-1?o+=`,`:t.options.trailingComma&&(t.options.lineWidth>0&&(l||=d.reduce((e,t)=>e+t.length+2,2)+(o.length+2)>t.options.lineWidth),l&&(o+=`,`)),a&&(o+=DR(o,r,s(a))),d.push(o),u=d.length}let{start:f,end:p}=n;if(d.length===0)return f+p;if(!l){let e=d.reduce((e,t)=>e+t.length+2,2);l=t.options.lineWidth>0&&e>t.options.lineWidth}if(l){let e=f;for(let t of d)e+=t?`\n${a}${i}${t}`:`
`;return`${e}\n${i}${p}`}return`${f}${o}${d.join(` `)}${o}${p}`}function cz({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=ER(t(r),e);n.push(i.trimStart())}}function lz(e,t){let n=KL(t)?t.value:t;for(let r of e)if(GL(r)&&(r.key===t||r.key===n||KL(r.key)&&r.key.value===n))return r}var uz=class extends wR{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(LL,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,a=new this(e),o=(e,o)=>{if(typeof i==`function`)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(o!==void 0||r)&&a.items.push(rz(e,o,n))};if(t instanceof Map)for(let[e,n]of t)o(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))o(e,t[e]);return typeof e.sortMapEntries==`function`&&a.items.sort(e.sortMapEntries),a}add(e,t){let n;n=GL(e)?e:!e||typeof e!=`object`||!(`key`in e)?new iz(e,e?.value):new iz(e.key,e.value);let r=lz(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);KL(r.value)&&_R(n.value)?r.value.value=n.value:r.value=n.value}else if(i){let e=this.items.findIndex(e=>i(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=lz(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=lz(this.items,e)?.value;return(!t&&KL(n)?n.value:n)??void 0}has(e){return!!lz(this.items,e)}set(e,t){this.add(new iz(e,t),!0)}toJSON(e,t,n){let r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let e of this.items)tz(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!GL(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),az(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}},dz={collection:`map`,default:!0,nodeClass:uz,tag:`tag:yaml.org,2002:map`,resolve(e,t){return WL(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>uz.from(e,t,n)},fz=class extends wR{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(BL,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=pz(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=pz(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&KL(r)?r.value:r}has(e){let t=pz(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=pz(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];KL(r)&&_R(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(pR(e,String(r++),t));return n}toString(e,t,n){return e?az(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let a of t){if(typeof r==`function`){let n=t instanceof Set?a:String(e++);a=r.call(t,n,a)}i.items.push(xR(a,void 0,n))}}return i}};function pz(e){let t=KL(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var mz={collection:`seq`,default:!0,nodeClass:fz,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return qL(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>fz.from(e,t,n)},hz={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),HR(e,t,n,r)}},gz={identify:e=>e==null,createNode:()=>new vR(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new vR(null),stringify:({source:e},t)=>typeof e==`string`&&gz.test.test(e)?e:t.options.nullStr},_z={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new vR(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},n){return e&&_z.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}};function vz({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r==`bigint`)return String(r);let i=typeof r==`number`?r:Number(r);if(!isFinite(i))return isNaN(i)?`.nan`:i<0?`-.inf`:`.inf`;let a=Object.is(r,-0)?`-0`:JSON.stringify(r);if(!e&&t&&(!n||n===`tag:yaml.org,2002:float`)&&/^-?\d/.test(a)&&!a.includes(`e`)){let e=a.indexOf(`.`);e<0&&(e=a.length,a+=`.`);let n=t-(a.length-e-1);for(;n-->0;)a+=`0`}return a}var yz={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:vz},bz={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),string Line truncated
`:` `)}return HR({comment:e,type:t,value:s},r,i,a)}};function Pz(e,t){if(qL(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!GL(r)){if(WL(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new iz(new vR(null));if(r.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${r.commentBefore}\n${e.key.commentBefore}`:r.commentBefore),r.comment){let t=e.value??e.key;t.comment=t.comment?`${r.comment}\n${t.comment}`:r.comment}r=e}e.items[n]=GL(r)?r:new iz(r)}}else t(`Expected a sequence for this tag`);return e}function Fz(e,t,n){let{replacer:r}=n,i=new fz(e);i.tag=`tag:yaml.org,2002:pairs`;let a=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof r==`function`&&(e=r.call(t,String(a++),e));let o,s;if(Array.isArray(e)){if(e.length===2)o=e[0],s=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)o=t[0],s=e[o];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else o=e;i.items.push(rz(o,s,n))}return i}var Iz={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:Pz,createNode:Fz},Lz=class e extends fz{constructor(){super(),this.add=uz.prototype.add.bind(this),this.delete=uz.prototype.delete.bind(this),this.get=uz.prototype.get.bind(this),this.has=uz.prototype.has.bind(this),this.set=uz.prototype.set.bind(this),this.tag=e.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let e of this.items){let r,i;if(GL(e)?(r=pR(e.key,``,t),i=pR(e.value,r,t)):r=pR(e,``,t),n.has(r))throw Error(`Ordered maps must not include duplicate keys`);n.set(r,i)}return n}static from(e,t,n){let r=Fz(e,t,n),i=new this;return i.items=r.items,i}};Lz.tag=`tag:yaml.org,2002:omap`;var Rz={collection:`seq`,identify:e=>e instanceof Map,nodeClass:Lz,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=Pz(e,t),r=[];for(let{key:e}of n.items)KL(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new Lz,n)},createNode:(e,t,n)=>Lz.from(e,t,n)};function zz({value:e,source:t},n){return t&&(e?Bz:Vz).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var Bz={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new vR(!0),stringify:zz},Vz={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new vR(!1),stringify:zz},Hz={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:vz},Uz={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():vz(e)}},Wz={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new vR(parseFloat(e.replace(/_/g,``))),n=e.indexOf(`.`);if(n!==-1){let r=e.substring(n+1).replace(/_/g,``);r[r.length-1]===`0`&&(t.minFractionDigits=r.length)}return t},stringify:vz},Gz=e=>typeof e==`bigint`||Number.isInteger(e);function Kz(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function qz(e,t,n){let{value:r}=e;if(Gz(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return vz(e)}var Jz={identify:Gz,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Kz(e,2,2,n),stringify:e=>qz(e,2,`0b`)},Yz={identify:Gz,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Kz(e,1,8,n),stringify:e=>qz(e,8,`0`)},Xz={identify:Gz,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Kz(e,0,10,n),stringify:vz},Zz={identify:Gz,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Kz(e,2,16,n),stringify:e=>qz(e,16,`0x`)},Qz=class e extends uz{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=GL(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new iz(e.key,null):new iz(e,null),lz(this.items,t.key)||this.items.push(t)}get(e,t){let n=lz(this.items,e);return!t&&GL(n)?KL(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=lz(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new iz(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return s Line truncated
`)?(n.push(`...`),n.push(ER(t,``))):n.push(`... ${t}`)}else n.push(`...`)}else{let t=e.comment;t&&o&&(t=t.replace(/^\n+/,``)),t&&((!o||s)&&n[n.length-1]!==``&&n.push(``),n.push(ER(a(t),``)))}return n.join(`
`)+`
`}var uB=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,RL,{value:NL});let r=null;typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=i;let{version:a}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(a=this.directives.yaml.version)):this.directives=new iR({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[RL]:{value:NL}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=KL(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){dB(this.contents)&&this.contents.add(e)}addIn(e,t){dB(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=oR(this);e.anchor=!t||n.has(t)?sR(t||`a`,n):t}return new fR(e.anchor)}createNode(e,t,n){let r;if(typeof t==`function`)e=t.call({"":e},``,e),r=t;else if(Array.isArray(t)){let e=t.filter(e=>typeof e==`number`||e instanceof String||e instanceof Number).map(String);e.length>0&&(t=t.concat(e)),r=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:a,flow:o,keepUndefined:s,onTagObj:c,tag:l}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:f}=cR(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=vR(e,l,p);return o&&GL(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){return new tz(this.createNode(e,null,n),this.createNode(t,null,n))}delete(e){return dB(this.contents)?this.contents.delete(e):!1}deleteIn(e){return bR(e)?this.contents!=null&&(this.contents=null,!0):dB(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return GL(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return bR(e)?!t&&UL(this.contents)?this.contents.value:this.contents:GL(this.contents)?this.contents.getIn(e,t):void 0}has(e){return GL(this.contents)?this.contents.has(e):!1}hasIn(e){return bR(e)?this.contents!==void 0:GL(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=yR(this.schema,[e],t):dB(this.contents)&&this.contents.set(e,t)}setIn(e,t){bR(e)?this.contents=t:this.contents==null?this.contents=yR(this.schema,Array.from(e),t):dB(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==`number`&&(e=String(e));let n;switch(e){case`1.1`:this.directives?this.directives.yaml.version=`1.1`:this.directives=new iR({version:`1.1`}),n={resolveKnownTags:!1,schema:`yaml-1.1`};break;case`1.2`:case`next`:this.directives?this.directives.yaml.version=e:this.directives=new iR({version:e}),n={resolveKnownTags:!0,schema:`core`};break;case null:this.directives&&delete this.directives,n=null;break;default:{let t=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new cB(Object.assign(n,t));else throw Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:a}={}){let o={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},s=uR(this.contents,t??``,o);if(typeof i==`function`)for(let{count:e,res:t}of o.anchors.values())i(t,e);return typeof a==`function`?lR(a,{"":s},``,s):s}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error(`Document with errors cannot be stringified`);if(`indent`in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return lB(this,e)}};function dB(e){if(GL(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var fB=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},pB=class extends fB{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},mB=class extends fB{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},hB=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
`),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}};function gB(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,y=null,b=null,x=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:(!b||n!==`seq-item-ind`)&&(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,x??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,x??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),b&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),b=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){y&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),y=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let S=e[e.length-1],C=S?S.offset+S.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:y,found:b,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:C,start:x??C}}function _B(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
`))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let t of e.items){for(let e of t.start)if(e.type===`newline`)return!0;if(t.sep){for(let e of t.sep)if(e.type===`newline`)return!0}if(_B(t.key)||_B(t.value))return!0}return!1;default:return!0}}function vB(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&_B(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}function yB(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||UL(e)&&UL(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var bB=`All mapping items must start at the same column`;function xB({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??sz)(n.schema);n.atRoot&&=!1;let s=r.offset,c=null;for(let a of r.items){let{start:l,key:u,sep:d,value:f}=a,p=gB(l,{indicator:`explicit-key-ind`,next:u??d?.[0],offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0}),m=!p.found;if(m){if(u&&(u.type===`block-seq`?i(s,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in u&&u.indent!==r.indent&&i(s,`BAD_INDENT`,bB)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
`+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||_B(u))&&i(u??l[l.length-1],`MULTILINE_IMPLICIT_KEY`,`Implicit keys need to be on a single line`)}else p.found?.indent!==r.indent&&i(s,`BAD_INDENT`,bB);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&vB(r.indent,u,i),n.atKey=!1,yB(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=gB(d??[],{indicator:`map-value-ind`,next:f,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!u||u.type===`block-scalar`});if(s=_.end,_.found){m&&(f?.type===`block-map`&&!_.hasNewline&&i(s,`BLOCK_AS_IMPLICIT_KEY`,`Nested mappings are not allowed in compact mappings`),n.options.strict&&p.start<_.found.offset-1024&&i(g.range,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit block mapping key`));let c=f?e(n,f,_,i):t(n,s,d,null,_,i);n.schema.compat&&vB(r.indent,f,i),s=c.range[2];let l=new tz(g,c);n.options.keepSourceTokens&&(l.srcToken=a),o.items.push(l)}else{m&&i(g.range,`MISSING_CHAR`,`Implicit map keys need to be followed by map values`),_.comment&&(g.comment?g.comment+=`
`+_.comment:g.comment=_.comment);let e=new tz(g);n.options.keepSourceTokens&&(e.srcToken=a),o.items.push(e)}}return c&&c<s&&i(c,`IMPOSSIBLE`,`Map comment with trailing content`),o.range=[r.offset,s,c??s],o}function SB({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??lz)(n.schema);n.atRoot&&=!1,n.atKey&&=!1;let s=r.offset,c=null;for(let{start:a,value:l}of r.items){let u=gB(a,{indicator:`seq-item-ind`,next:l,offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!u.found){if(u.anchor||u.tag||l)l?.type===`block-seq`?i(u.end,`BAD_INDENT`,`All sequence items must start at the same column`):i(s,`MISSING_CHAR`,`Sequence item without - indicator`);else{c=u.end,u.comment&&(o.comment=u.comment);continue}}let d=l?e(n,l,u,i):t(n,u.end,a,null,u,i);n.schema.compat&&vB(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}function CB(e,t,n,r){let i=``;if(e){let a=!1,o=``;for(let s of e){let{source:e,type:c}=s;switch(c){case`space`:a=!0;break;case`comment`:{n&&!a&&r(s,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let t=e.substring(1)||` `;i?i+=o+t:i=t,o=``;break}case`newline`:i&&(o+=e),a=!0;break;default:r(s,`UNEXPECTED_TOKEN`,`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}var wB=`Block collections are not allowed within flow collections`,TB=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function EB({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?sz:lz))(n.schema);c.flow=!0;let l=n.atRoot;l&&(n.atRoot=!1),n.atKey&&=!1;let u=r.offset+r.start.source.length;for(let a=0;a<r.items.length;++a){let l=r.items[a],{start:d,key:f,sep:p,value:m}=l,h=gB(d,{flow:s,indicator:`explicit-key-ind`,next:f??p?.[0],offset:u,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!h.found){if(!h.anchor&&!h.tag&&!p&&!m){a===0&&h.comma?i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`):a<r.items.length-1&&i(h.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${s}`),h.comment&&(c.comment?c.comment+=`
`+h.comment:c.comment=h.comment),u=h.end;continue}!o&&n.options.strict&&_B(f)&&i(f,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`)}if(a===0)h.comma&&i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`);else if(h.comma||i(h.start,`MISSING_CHAR`,`Missing , between ${s} items`),h.comment){let e=``;loop:for(let t of d)switch(t.type){case`comma`:case`space`:break;case`comment`:e=t.source.substring(1);break loop;default:break loop}if(e){let t=c.items[c.items.length-1];HL(t)&&(t=t.value??t.key),t.comment?t.comment+=`
`+e:t.comment=e,h.comment=h.comment.substring(e.length+1)}}if(!o&&!p&&!h.found){let r=m?e(n,m,h,i):t(n,h.end,p,null,h,i);c.items.push(r),u=r.range[2],TB(m)&&i(r.range,`BLOCK_IN_FLOW`,wB)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);TB(f)&&i(g.range,`BLOCK_IN_FLOW`,wB),n.atKey=!1;let _=gB(p??[],{flow:s,indicator:`map-value-ind`,next:m,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(_.found){if(!o&&!h.found&&n.options.strict){if(p)for(let e of p){if(e===_.found)break;if(e.type===`newline`){i(e,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`);break}}h.start<_.found.offset-1024&&i(_.found,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit flow sequence key`)}}else m&&(`source`in m&&m.source?.[0]===`:`?i(m,`MISSING_CHAR`,`Missing space after : in ${s}`):i(_.start,`MISSING_CHAR`,`Missing , or : between ${s} items`));let v=m?e(n,m,_,i):_.found?t(n,_.end,p,null,_,i):null;v?TB(m)&&i(v.range,`BLOCK_IN_FLOW`,wB):_.comment&&(g.comment?g.comment+=`
`+_.comment:g.comment=_.comment);let y=new tz(g,v);if(n.options.keepSourceTokens&&(y.srcToken=l),o){let e=c;yB(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(y)}else{let e=new sz(n.schema);e.flow=!0,e.items.push(y);let t=(v??g).range;e.range=[g.range[0],t[1],t[2]],c.items.push(e)}u=v?v.range[2]:_.end}}let d=o?`}`:`]`,[f,...p]=r.end,m=u;if(f?.source===d)m=f.offset+f.source.length;else{let e=s[0].toUpperCase()+s.substring(1),t=l?`${e} must end with a ${d}`:`${e} in block collection must be sufficiently indented and end with a ${d}`;i(u,l?`MISSING_CHAR`:`BAD_INDENT`,t),f&&f.source.length!==1&&p.unshift(f)}if(p.length>0){let e=CB(p,m,n.options.strict,i);e.comment&&(c.comment?c.comment+=`
`+e.comment:c.comment=e.comment),c.range=[r.offset,m,e.offset]}else c.range=[r.offset,m,m];return c}function DB(e,t,n,r,i,a){let o=n.type===`block-map`?xB(e,t,n,r,a):n.type===`block-seq`?SB(e,t,n,r,a):EB(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function OB(e,t,n,r,i){let a=r.tag,o=a?t.directives.tagName(a.source,e=>i(a,`TAG_RESOLVE_FAILED`,e)):null;if(n.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=r,n=e&&a?e.offset>a.offset?e:a:e??a;n&&(!t||t.offset<n.offset)&&i(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let s=n.type===`block-map`?`map`:n.type===`block-seq`?`seq`:n.start.source===`{`?`map`:`seq`;if(!a||!o||o===`!`||o===sz.tagName&&s===`map`||o===lz.tagName&&s===`seq`)return DB(e,t,n,i,o);let c=t.schema.tags.find(e=>e.tag===o&&e.collection===s);if(!c){let r=t.schema.knownTags[o];if(r?.collection===s)t.schema.tags.push(Object.assign({},r,{default:!1})),c=r;else return r?i(a,`BAD_COLLECTION_TYPE`,`${r.tag} used for ${s} collection, but expects ${r.collection??`scalar`}`,!0):i(a,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${o}`,!0),DB(e,t,n,i,o)}let l=DB(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=KL(u)?u:new hR(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function kB(e,t,n){let r=t.offset,i=AB(t,e.options.strict,n);if(!i)return{value:``,type:null,comment:``,range:[r,r,r]};let a=i.mode===`>`?hR.BLOCK_FOLDED:hR.BLOCK_LITERAL,o=t.source?jB(t.source):[],s=o.length;for(let e=o.length-1;e>=0;--e){let t=o[e][1];if(t===``||t===`\r`)s=e;else break}if(s===0){let e=i.chomp===`+`&&o.length>0?`
`}var pB=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,VL,{value:IL});let r=null;typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=i;let{version:a}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(a=this.directives.yaml.version)):this.directives=new sR({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[VL]:{value:IL}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=YL(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){mB(this.contents)&&this.contents.add(e)}addIn(e,t){mB(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=lR(this);e.anchor=!t||n.has(t)?uR(t||`a`,n):t}return new hR(e.anchor)}createNode(e,t,n){let r;if(typeof t==`function`)e=t.call({"":e},``,e),r=t;else if(Array.isArray(t)){let e=t.filter(e=>typeof e==`number`||e instanceof String||e instanceof Number).map(String);e.length>0&&(t=t.concat(e)),r=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:a,flow:o,keepUndefined:s,onTagObj:c,tag:l}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:f}=dR(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=xR(e,l,p);return o&&JL(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){return new iz(this.createNode(e,null,n),this.createNode(t,null,n))}delete(e){return mB(this.contents)?this.contents.delete(e):!1}deleteIn(e){return CR(e)?this.contents!=null&&(this.contents=null,!0):mB(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return JL(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return CR(e)?!t&&KL(this.contents)?this.contents.value:this.contents:JL(this.contents)?this.contents.getIn(e,t):void 0}has(e){return JL(this.contents)?this.contents.has(e):!1}hasIn(e){return CR(e)?this.contents!==void 0:JL(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=SR(this.schema,[e],t):mB(this.contents)&&this.contents.set(e,t)}setIn(e,t){CR(e)?this.contents=t:this.contents==null?this.contents=SR(this.schema,Array.from(e),t):mB(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==`number`&&(e=String(e));let n;switch(e){case`1.1`:this.directives?this.directives.yaml.version=`1.1`:this.directives=new sR({version:`1.1`}),n={resolveKnownTags:!1,schema:`yaml-1.1`};break;case`1.2`:case`next`:this.directives?this.directives.yaml.version=e:this.directives=new sR({version:e}),n={resolveKnownTags:!0,schema:`core`};break;case null:this.directives&&delete this.directives,n=null;break;default:{let t=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new dB(Object.assign(n,t));else throw Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:a}={}){let o={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},s=pR(this.contents,t??``,o);if(typeof i==`function`)for(let{count:e,res:t}of o.anchors.values())i(t,e);return typeof a==`function`?fR(a,{"":s},``,s):s}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error(`Document with errors cannot be stringified`);if(`indent`in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return fB(this,e)}};function mB(e){if(JL(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var hB=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},gB=class extends hB{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},_B=class extends hB{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},vB=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
`),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}};function yB(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,y=null,b=null,x=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:(!b||n!==`seq-item-ind`)&&(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,x??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,x??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),b&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),b=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){y&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),y=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let S=e[e.length-1],C=S?S.offset+S.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:y,found:b,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:C,start:x??C}}function bB(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
`))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let t of e.items){for(let e of t.start)if(e.type===`newline`)return!0;if(t.sep){for(let e of t.sep)if(e.type===`newline`)return!0}if(bB(t.key)||bB(t.value))return!0}return!1;default:return!0}}function xB(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&bB(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}function SB(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||KL(e)&&KL(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var CB=`All mapping items must start at the same column`;function wB({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??uz)(n.schema);n.atRoot&&=!1;let s=r.offset,c=null;for(let a of r.items){let{start:l,key:u,sep:d,value:f}=a,p=yB(l,{indicator:`explicit-key-ind`,next:u??d?.[0],offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0}),m=!p.found;if(m){if(u&&(u.type===`block-seq`?i(s,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in u&&u.indent!==r.indent&&i(s,`BAD_INDENT`,CB)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
`+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||bB(u))&&i(u??l[l.length-1],`MULTILINE_IMPLICIT_KEY`,`Implicit keys need to be on a single line`)}else p.found?.indent!==r.indent&&i(s,`BAD_INDENT`,CB);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&xB(r.indent,u,i),n.atKey=!1,SB(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=yB(d??[],{indicator:`map-value-ind`,next:f,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!u||u.type===`block-scalar`});if(s=_.end,_.found){m&&(f?.type===`block-map`&&!_.hasNewline&&i(s,`BLOCK_AS_IMPLICIT_KEY`,`Nested mappings are not allowed in compact mappings`),n.options.strict&&p.start<_.found.offset-1024&&i(g.range,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit block mapping key`));let c=f?e(n,f,_,i):t(n,s,d,null,_,i);n.schema.compat&&xB(r.indent,f,i),s=c.range[2];let l=new iz(g,c);n.options.keepSourceTokens&&(l.srcToken=a),o.items.push(l)}else{m&&i(g.range,`MISSING_CHAR`,`Implicit map keys need to be followed by map values`),_.comment&&(g.comment?g.comment+=`
`+_.comment:g.comment=_.comment);let e=new iz(g);n.options.keepSourceTokens&&(e.srcToken=a),o.items.push(e)}}return c&&c<s&&i(c,`IMPOSSIBLE`,`Map comment with trailing content`),o.range=[r.offset,s,c??s],o}function TB({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??fz)(n.schema);n.atRoot&&=!1,n.atKey&&=!1;let s=r.offset,c=null;for(let{start:a,value:l}of r.items){let u=yB(a,{indicator:`seq-item-ind`,next:l,offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!u.found){if(u.anchor||u.tag||l)l?.type===`block-seq`?i(u.end,`BAD_INDENT`,`All sequence items must start at the same column`):i(s,`MISSING_CHAR`,`Sequence item without - indicator`);else{c=u.end,u.comment&&(o.comment=u.comment);continue}}let d=l?e(n,l,u,i):t(n,u.end,a,null,u,i);n.schema.compat&&xB(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}function EB(e,t,n,r){let i=``;if(e){let a=!1,o=``;for(let s of e){let{source:e,type:c}=s;switch(c){case`space`:a=!0;break;case`comment`:{n&&!a&&r(s,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let t=e.substring(1)||` `;i?i+=o+t:i=t,o=``;break}case`newline`:i&&(o+=e),a=!0;break;default:r(s,`UNEXPECTED_TOKEN`,`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}var DB=`Block collections are not allowed within flow collections`,OB=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function kB({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?uz:fz))(n.schema);c.flow=!0;let l=n.atRoot;l&&(n.atRoot=!1),n.atKey&&=!1;let u=r.offset+r.start.source.length;for(let a=0;a<r.items.length;++a){let l=r.items[a],{start:d,key:f,sep:p,value:m}=l,h=yB(d,{flow:s,indicator:`explicit-key-ind`,next:f??p?.[0],offset:u,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!h.found){if(!h.anchor&&!h.tag&&!p&&!m){a===0&&h.comma?i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`):a<r.items.length-1&&i(h.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${s}`),h.comment&&(c.comment?c.comment+=`
`+h.comment:c.comment=h.comment),u=h.end;continue}!o&&n.options.strict&&bB(f)&&i(f,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`)}if(a===0)h.comma&&i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`);else if(h.comma||i(h.start,`MISSING_CHAR`,`Missing , between ${s} items`),h.comment){let e=``;loop:for(let t of d)switch(t.type){case`comma`:case`space`:break;case`comment`:e=t.source.substring(1);break loop;default:break loop}if(e){let t=c.items[c.items.length-1];GL(t)&&(t=t.value??t.key),t.comment?t.comment+=`
`+e:t.comment=e,h.comment=h.comment.substring(e.length+1)}}if(!o&&!p&&!h.found){let r=m?e(n,m,h,i):t(n,h.end,p,null,h,i);c.items.push(r),u=r.range[2],OB(m)&&i(r.range,`BLOCK_IN_FLOW`,DB)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);OB(f)&&i(g.range,`BLOCK_IN_FLOW`,DB),n.atKey=!1;let _=yB(p??[],{flow:s,indicator:`map-value-ind`,next:m,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(_.found){if(!o&&!h.found&&n.options.strict){if(p)for(let e of p){if(e===_.found)break;if(e.type===`newline`){i(e,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`);break}}h.start<_.found.offset-1024&&i(_.found,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit flow sequence key`)}}else m&&(`source`in m&&m.source?.[0]===`:`?i(m,`MISSING_CHAR`,`Missing space after : in ${s}`):i(_.start,`MISSING_CHAR`,`Missing , or : between ${s} items`));let v=m?e(n,m,_,i):_.found?t(n,_.end,p,null,_,i):null;v?OB(m)&&i(v.range,`BLOCK_IN_FLOW`,DB):_.comment&&(g.comment?g.comment+=`
`+_.comment:g.comment=_.comment);let y=new iz(g,v);if(n.options.keepSourceTokens&&(y.srcToken=l),o){let e=c;SB(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(y)}else{let e=new uz(n.schema);e.flow=!0,e.items.push(y);let t=(v??g).range;e.range=[g.range[0],t[1],t[2]],c.items.push(e)}u=v?v.range[2]:_.end}}let d=o?`}`:`]`,[f,...p]=r.end,m=u;if(f?.source===d)m=f.offset+f.source.length;else{let e=s[0].toUpperCase()+s.substring(1),t=l?`${e} must end with a ${d}`:`${e} in block collection must be sufficiently indented and end with a ${d}`;i(u,l?`MISSING_CHAR`:`BAD_INDENT`,t),f&&f.source.length!==1&&p.unshift(f)}if(p.length>0){let e=EB(p,m,n.options.strict,i);e.comment&&(c.comment?c.comment+=`
`+e.comment:c.comment=e.comment),c.range=[r.offset,m,e.offset]}else c.range=[r.offset,m,m];return c}function AB(e,t,n,r,i,a){let o=n.type===`block-map`?wB(e,t,n,r,a):n.type===`block-seq`?TB(e,t,n,r,a):kB(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function jB(e,t,n,r,i){let a=r.tag,o=a?t.directives.tagName(a.source,e=>i(a,`TAG_RESOLVE_FAILED`,e)):null;if(n.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=r,n=e&&a?e.offset>a.offset?e:a:e??a;n&&(!t||t.offset<n.offset)&&i(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let s=n.type===`block-map`?`map`:n.type===`block-seq`?`seq`:n.start.source===`{`?`map`:`seq`;if(!a||!o||o===`!`||o===uz.tagName&&s===`map`||o===fz.tagName&&s===`seq`)return AB(e,t,n,i,o);let c=t.schema.tags.find(e=>e.tag===o&&e.collection===s);if(!c){let r=t.schema.knownTags[o];if(r?.collection===s)t.schema.tags.push(Object.assign({},r,{default:!1})),c=r;else return r?i(a,`BAD_COLLECTION_TYPE`,`${r.tag} used for ${s} collection, but expects ${r.collection??`scalar`}`,!0):i(a,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${o}`,!0),AB(e,t,n,i,o)}let l=AB(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=YL(u)?u:new vR(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function MB(e,t,n){let r=t.offset,i=NB(t,e.options.strict,n);if(!i)return{value:``,type:null,comment:``,range:[r,r,r]};let a=i.mode===`>`?vR.BLOCK_FOLDED:vR.BLOCK_LITERAL,o=t.source?PB(t.source):[],s=o.length;for(let e=o.length-1;e>=0;--e){let t=o[e][1];if(t===``||t===`\r`)s=e;else break}if(s===0){let e=i.chomp===`+`&&o.length>0?`
`.repeat(Math.max(1,o.length-1)):``,n=r+i.length;return t.source&&(n+=t.source.length),{value:e,type:a,comment:i.comment,range:[r,n,n]}}let c=t.indent+i.indent,l=t.offset+i.length,u=0;for(let t=0;t<s;++t){let[r,a]=o[t];if(a===``||a===`\r`)i.indent===0&&r.length>c&&(c=r.length);else{r.length<c&&n(l+r.length,`MISSING_CHAR`,`Block scalars with more-indented leading empty lines must use an explicit indentation indicator`),i.indent===0&&(c=r.length),u=t,c===0&&!e.atRoot&&n(l,`BAD_INDENT`,`Block scalar values in collections must be indented`);break}l+=r.length+a.length+1}for(let e=o.length-1;e>=s;--e)o[e][0].length>c&&(s=e+1);let d=``,f=``,p=!1;for(let e=0;e<u;++e)d+=o[e][0].slice(c)+`
`;for(let e=u;e<s;++e){let[t,r]=o[e];l+=t.length+r.length+1;let s=r[r.length-1]===`\r`;if(s&&(r=r.slice(0,-1)),r&&t.length<c){let e=`Block scalar lines must not be less indented than their ${i.indent?`explicit indentation indicator`:`first line`}`;n(l-r.length-(s?2:1),`BAD_INDENT`,e),t=``}a===hR.BLOCK_LITERAL?(d+=f+t.slice(c)+r,f=`
`;for(let e=u;e<s;++e){let[t,r]=o[e];l+=t.length+r.length+1;let s=r[r.length-1]===`\r`;if(s&&(r=r.slice(0,-1)),r&&t.length<c){let e=`Block scalar lines must not be less indented than their ${i.indent?`explicit indentation indicator`:`first line`}`;n(l-r.length-(s?2:1),`BAD_INDENT`,e),t=``}a===vR.BLOCK_LITERAL?(d+=f+t.slice(c)+r,f=`
`):t.length>c||r[0]===` `?(f===` `?f=`
`:!p&&f===`
`&&(f=`
@@ -75,59 +75,59 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
`+o[e][0].slice(c);d[d.length-1]!==`
`&&(d+=`
`);break;default:d+=`
`}let m=r+i.length+t.source.length;return{value:d,type:a,comment:i.comment,range:[r,m,m]}}function AB({offset:e,props:t},n,r){if(t[0].type!==`block-scalar-header`)return r(t[0],`IMPOSSIBLE`,`Block scalar header not found`),null;let{source:i}=t[0],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function jB(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}function MB(e,t,n){let{offset:r,type:i,source:a,end:o}=e,s,c,l=(e,t,i)=>n(r+e,t,i);switch(i){case`scalar`:s=hR.PLAIN,c=NB(a,l);break;case`single-quoted-scalar`:s=hR.QUOTE_SINGLE,c=PB(a,l);break;case`double-quoted-scalar`:s=hR.QUOTE_DOUBLE,c=IB(a,l);break;default:return n(e,`UNEXPECTED_TOKEN`,`Expected a flow scalar value, but found: ${i}`),{value:``,type:null,comment:``,range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=CB(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function NB(e,t){let n=``;switch(e[0]){case` `:n=`a tab character`;break;case`,`:n=`flow indicator character ,`;break;case`%`:n=`directive indicator character %`;break;case`|`:case`>`:n=`block scalar indicator ${e[0]}`;break;case`@`:case"`":n=`reserved character ${e[0]}`}return n&&t(0,`BAD_SCALAR_START`,`Plain value cannot start with ${n}`),FB(e)}function PB(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),FB(e.slice(1,-1)).replace(/''/g,`'`)}function FB(e){let t=/(.*?)\r?\n/sy,n=t.exec(e);if(!n)return e;let r,i;try{r=RegExp(`(?<![ ])[ ]+$`),i=RegExp(`^[ ]+|(?<![ ])[ ]+$`,`g`)}catch{r=/[ \t]+$/,i=/^[ \t]+|[ \t]+$/g}let a=n[1].replace(r,``),o=` `,s=t.lastIndex;for(;n=t.exec(e);){let e=n[1].replace(i,``);e===``?o===`
`}let m=r+i.length+t.source.length;return{value:d,type:a,comment:i.comment,range:[r,m,m]}}function NB({offset:e,props:t},n,r){if(t[0].type!==`block-scalar-header`)return r(t[0],`IMPOSSIBLE`,`Block scalar header not found`),null;let{source:i}=t[0],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function PB(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}function FB(e,t,n){let{offset:r,type:i,source:a,end:o}=e,s,c,l=(e,t,i)=>n(r+e,t,i);switch(i){case`scalar`:s=vR.PLAIN,c=IB(a,l);break;case`single-quoted-scalar`:s=vR.QUOTE_SINGLE,c=LB(a,l);break;case`double-quoted-scalar`:s=vR.QUOTE_DOUBLE,c=zB(a,l);break;default:return n(e,`UNEXPECTED_TOKEN`,`Expected a flow scalar value, but found: ${i}`),{value:``,type:null,comment:``,range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=EB(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function IB(e,t){let n=``;switch(e[0]){case` `:n=`a tab character`;break;case`,`:n=`flow indicator character ,`;break;case`%`:n=`directive indicator character %`;break;case`|`:case`>`:n=`block scalar indicator ${e[0]}`;break;case`@`:case"`":n=`reserved character ${e[0]}`}return n&&t(0,`BAD_SCALAR_START`,`Plain value cannot start with ${n}`),RB(e)}function LB(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),RB(e.slice(1,-1)).replace(/''/g,`'`)}function RB(e){let t=/(.*?)\r?\n/sy,n=t.exec(e);if(!n)return e;let r,i;try{r=RegExp(`(?<![ ])[ ]+$`),i=RegExp(`^[ ]+|(?<![ ])[ ]+$`,`g`)}catch{r=/[ \t]+$/,i=/^[ \t]+|[ \t]+$/g}let a=n[1].replace(r,``),o=` `,s=t.lastIndex;for(;n=t.exec(e);){let e=n[1].replace(i,``);e===``?o===`
`?a+=o:o=`
`:(a+=o+e,o=` `),s=t.lastIndex}let c=/[ \t]*(.*)/sy;return c.lastIndex=s,n=c.exec(e),a+o+(n?.[1]??``)}function IB(e,t){let n=``;for(let r=1;r<e.length-1;++r){let i=e[r];if(i!==`\r`||e[r+1]!==`
`:(a+=o+e,o=` `),s=t.lastIndex}let c=/[ \t]*(.*)/sy;return c.lastIndex=s,n=c.exec(e),a+o+(n?.[1]??``)}function zB(e,t){let n=``;for(let r=1;r<e.length-1;++r){let i=e[r];if(i!==`\r`||e[r+1]!==`
`){if(i===`
`){let{fold:t,offset:i}=LB(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=RB[i];if(a)n+=a;else if(i===`
`){let{fold:t,offset:i}=BB(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=VB[i];if(a)n+=a;else if(i===`
`)for(i=e[r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`\r`&&e[r+1]===`
`)for(i=e[++r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`x`||i===`u`||i===`U`){let a=i===`x`?2:i===`u`?4:8;n+=zB(e,r+1,a,t),r+=a}else{let i=e.substr(r-1,2);t(r-1,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),n+=i}}else if(i===` `||i===` `){let t=r,a=e[r+1];for(;a===` `||a===` `;)a=e[++r+1];a!==`
`)for(i=e[++r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`x`||i===`u`||i===`U`){let a=i===`x`?2:i===`u`?4:8;n+=HB(e,r+1,a,t),r+=a}else{let i=e.substr(r-1,2);t(r-1,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),n+=i}}else if(i===` `||i===` `){let t=r,a=e[r+1];for(;a===` `||a===` `;)a=e[++r+1];a!==`
`&&(a!==`\r`||e[r+2]!==`
`)&&(n+=r>t?e.slice(t,r+1):i)}else n+=i}}return(e[e.length-1]!==`"`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing "quote`),n}function LB(e,t){let n=``,r=e[t+1];for(;(r===` `||r===` `||r===`
`)&&(n+=r>t?e.slice(t,r+1):i)}else n+=i}}return(e[e.length-1]!==`"`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing "quote`),n}function BB(e,t){let n=``,r=e[t+1];for(;(r===` `||r===` `||r===`
`||r===`\r`)&&(r!==`\r`||e[t+2]===`
`);)r===`
`&&(n+=`
`),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}var RB={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
`,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function zB(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}function BB(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?kB(e,t,r):MB(t,e.options.strict,r),c=n?e.directives.tagName(n.source,e=>r(n,`TAG_RESOLVE_FAILED`,e)):null,l;l=e.options.stringKeys&&e.atKey?e.schema[IL]:c?VB(e.schema,i,c,n,r):t.type===`scalar`?HB(e,i,t,r):e.schema[IL];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=UL(a)?a:new hR(a)}catch(e){let a=e instanceof Error?e.message:String(e);r(n??t,`TAG_RESOLVE_FAILED`,a),u=new hR(i)}return u.range=s,u.source=i,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function VB(e,t,n,r,i){if(n===`!`)return e[IL];let a=[];for(let t of e.tags)if(!t.collection&&t.tag===n){if(t.default&&t.test)a.push(t);else return t}for(let e of a)if(e.test?.test(t))return e;let o=e.knownTags[n];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(r,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${n}`,n!==`tag:yaml.org,2002:str`),e[IL])}function HB({atKey:e,directives:t,schema:n},r,i,a){let o=n.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(r))||n[IL];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[IL];o.tag!==e.tag&&a(i,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${t.tagString(o.tag)} or ${t.tagString(e.tag)}`,!0)}return o}function UB(e,t,n){if(t){n??=t.length;for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case`space`:case`comment`:case`newline`:e-=n.source.length;continue}for(n=t[++r];n?.type===`space`;)e+=n.source.length,n=t[++r];break}}return e}var WB={composeNode:GB,composeEmptyNode:KB};function GB(e,t,n,r){let i=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=n,l,u=!0;switch(t.type){case`alias`:l=qB(e,t,r),(s||c)&&r(t,`ALIAS_PROPS`,`An alias node must not specify any properties`);break;case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`block-scalar`:l=BB(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=OB(WB,e,t,n,r),s&&(l.anchor=s.source.substring(1))}catch(e){r(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:r(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),u=!1}return l??=KB(e,t.offset,void 0,null,n,r),s&&l.anchor===``&&r(s,`BAD_ALIAS`,`Anchor cannot be an empty string`),i&&e.options.stringKeys&&(!UL(l)||typeof l.value!=`string`||l.tag&&l.tag!==`tag:yaml.org,2002:str`)&&r(c??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),a&&(l.spaceBefore=!0),o&&(t.type===`scalar`&&t.source===``?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function KB(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=BB(e,{type:`scalar`,offset:UB(t,n,r),indent:-1,source:``},s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===``&&l(o,`BAD_ALIAS`,`Anchor cannot be an empty string`)),i&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function qB({options:e},{offset:t,source:n,end:r},i){let a=new fR(n.substring(1));a.source===``&&i(t,`BAD_ALIAS`,`Alias cannot be an empty string`),a.source.endsWith(`:`)&&i(t+n.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let o=t+n.length,s=CB(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}function JB(e,t,{offset:n,start:r,value:i,end:a},o){let s=new uB(void 0,Object.assign({_directives:t},e)),c={atKey:!1,atRoot:!0,directives:s.directives,options:s.options,schema:s.schema},l=gB(r,{indicator:`doc-start`,next:i??a?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});l.found&&(s.directives.docStart=!0,i&&(i.type===`block-map`||i.type===`block-seq`)&&!l.hasNewline&&o(l.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),s.contents=i?GB(c,i,l,o):KB(c,l.end,r,null,l,o);let u=s.contents.range[2],d=CB(a,u,!1,o);return d.comment&&(s.comment=d.comment),s.range=[n,u,d.offset],s}function YB(e){if(typeof e==`number`)return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n==`string`?n.length:1)]}function XB(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
`),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}var VB={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
`,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function HB(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}function UB(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?MB(e,t,r):FB(t,e.options.strict,r),c=n?e.directives.tagName(n.source,e=>r(n,`TAG_RESOLVE_FAILED`,e)):null,l;l=e.options.stringKeys&&e.atKey?e.schema[zL]:c?WB(e.schema,i,c,n,r):t.type===`scalar`?GB(e,i,t,r):e.schema[zL];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=KL(a)?a:new vR(a)}catch(e){let a=e instanceof Error?e.message:String(e);r(n??t,`TAG_RESOLVE_FAILED`,a),u=new vR(i)}return u.range=s,u.source=i,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function WB(e,t,n,r,i){if(n===`!`)return e[zL];let a=[];for(let t of e.tags)if(!t.collection&&t.tag===n){if(t.default&&t.test)a.push(t);else return t}for(let e of a)if(e.test?.test(t))return e;let o=e.knownTags[n];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(r,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${n}`,n!==`tag:yaml.org,2002:str`),e[zL])}function GB({atKey:e,directives:t,schema:n},r,i,a){let o=n.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(r))||n[zL];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[zL];o.tag!==e.tag&&a(i,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${t.tagString(o.tag)} or ${t.tagString(e.tag)}`,!0)}return o}function KB(e,t,n){if(t){n??=t.length;for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case`space`:case`comment`:case`newline`:e-=n.source.length;continue}for(n=t[++r];n?.type===`space`;)e+=n.source.length,n=t[++r];break}}return e}var qB={composeNode:JB,composeEmptyNode:YB};function JB(e,t,n,r){let i=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=n,l,u=!0;switch(t.type){case`alias`:l=XB(e,t,r),(s||c)&&r(t,`ALIAS_PROPS`,`An alias node must not specify any properties`);break;case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`block-scalar`:l=UB(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=jB(qB,e,t,n,r),s&&(l.anchor=s.source.substring(1))}catch(e){r(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:r(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),u=!1}return l??=YB(e,t.offset,void 0,null,n,r),s&&l.anchor===``&&r(s,`BAD_ALIAS`,`Anchor cannot be an empty string`),i&&e.options.stringKeys&&(!KL(l)||typeof l.value!=`string`||l.tag&&l.tag!==`tag:yaml.org,2002:str`)&&r(c??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),a&&(l.spaceBefore=!0),o&&(t.type===`scalar`&&t.source===``?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function YB(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=UB(e,{type:`scalar`,offset:KB(t,n,r),indent:-1,source:``},s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===``&&l(o,`BAD_ALIAS`,`Anchor cannot be an empty string`)),i&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function XB({options:e},{offset:t,source:n,end:r},i){let a=new hR(n.substring(1));a.source===``&&i(t,`BAD_ALIAS`,`Alias cannot be an empty string`),a.source.endsWith(`:`)&&i(t+n.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let o=t+n.length,s=EB(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}function ZB(e,t,{offset:n,start:r,value:i,end:a},o){let s=new pB(void 0,Object.assign({_directives:t},e)),c={atKey:!1,atRoot:!0,directives:s.directives,options:s.options,schema:s.schema},l=yB(r,{indicator:`doc-start`,next:i??a?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});l.found&&(s.directives.docStart=!0,i&&(i.type===`block-map`||i.type===`block-seq`)&&!l.hasNewline&&o(l.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),s.contents=i?JB(c,i,l,o):YB(c,l.end,r,null,l,o);let u=s.contents.range[2],d=EB(a,u,!1,o);return d.comment&&(s.comment=d.comment),s.range=[n,u,d.offset],s}function QB(e){if(typeof e==`number`)return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n==`string`?n.length:1)]}function $B(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
`:`
`)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var ZB=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=YB(e);r?this.warnings.push(new mB(i,t,n)):this.errors.push(new pB(i,t,n))},this.directives=new iR({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=XB(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(GL(i)&&!i.flow&&i.items.length>0){let e=i.items[0];HL(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:XB(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=YB(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=JB(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new pB(YB(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new pB(YB(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=CB(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new pB(YB(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=new uB(void 0,Object.assign({_directives:this.directives},this.options));this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),e.range=[0,t,t],this.decorate(e,!1),yield e}}},QB=Symbol(`break visit`),$B=Symbol(`skip children`),eV=Symbol(`remove item`);function tV(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),nV(Object.freeze([]),e,t)}tV.BREAK=QB,tV.SKIP=$B,tV.REMOVE=eV,tV.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},tV.parentCollection=(e,t)=>{let n=tV.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&`items`in i)return i;throw Error(`Parent collection not found`)};function nV(e,t,n){let r=n(t,e);if(typeof r==`symbol`)return r;for(let i of[`key`,`value`]){let a=t[i];if(a&&`items`in a){for(let t=0;t<a.items.length;++t){let r=nV(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===QB)return QB;else r===eV&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}function rV(e){switch(e){case``:return`byte-order-mark`;case``:return`doc-mode`;case``:return`flow-error-end`;case``:return`scalar`;case`---`:return`doc-start`;case`...`:return`doc-end`;case``:case`
`)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var eV=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=QB(e);r?this.warnings.push(new _B(i,t,n)):this.errors.push(new gB(i,t,n))},this.directives=new sR({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=$B(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(JL(i)&&!i.flow&&i.items.length>0){let e=i.items[0];GL(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:$B(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=QB(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=ZB(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new gB(QB(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new gB(QB(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=EB(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new gB(QB(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=new pB(void 0,Object.assign({_directives:this.directives},this.options));this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),e.range=[0,t,t],this.decorate(e,!1),yield e}}},tV=Symbol(`break visit`),nV=Symbol(`skip children`),rV=Symbol(`remove item`);function iV(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),aV(Object.freeze([]),e,t)}iV.BREAK=tV,iV.SKIP=nV,iV.REMOVE=rV,iV.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},iV.parentCollection=(e,t)=>{let n=iV.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&`items`in i)return i;throw Error(`Parent collection not found`)};function aV(e,t,n){let r=n(t,e);if(typeof r==`symbol`)return r;for(let i of[`key`,`value`]){let a=t[i];if(a&&`items`in a){for(let t=0;t<a.items.length;++t){let r=aV(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===tV)return tV;else r===rV&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}function oV(e){switch(e){case``:return`byte-order-mark`;case``:return`doc-mode`;case``:return`flow-error-end`;case``:return`scalar`;case`---`:return`doc-start`;case`...`:return`doc-end`;case``:case`
`:case`\r
`:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}function iV(e){switch(e){case void 0:case` `:case`
`:case`\r`:case` `:return!0;default:return!1}}var aV=new Set(`0123456789ABCDEFabcdef`),oV=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),sV=new Set(`,[]{}`),cV=new Set(` ,[]{}
\r `),lV=e=>!e||cV.has(e),uV=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer=``,this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=`string`)throw TypeError(`source is not a string`);this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??`stream`;for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===` `||t===` `;)t=this.buffer[++e];return!t||t===`#`||t===`
`:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}function sV(e){switch(e){case void 0:case` `:case`
`:case`\r`:case` `:return!0;default:return!1}}var cV=new Set(`0123456789ABCDEFabcdef`),lV=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),uV=new Set(`,[]{}`),dV=new Set(` ,[]{}
\r `),fV=e=>!e||dV.has(e),pV=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer=``,this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=`string`)throw TypeError(`source is not a string`);this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??`stream`;for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===` `||t===` `;)t=this.buffer[++e];return!t||t===`#`||t===`
`||t===`\r`&&this.buffer[e+1]===`
`}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===` `;)t=this.buffer[++n+e];if(t===`\r`){let t=this.buffer[n+e+1];if(t===`
`||!t&&!this.atEnd)return e+n+1}return t===`
`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t===`-`||t===`.`){let t=this.buffer.substr(e,3);if((t===`---`||t===`...`)&&iV(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!=`number`||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]===`\r`&&--e,this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case`stream`:return yield*this.parseStream();case`line-start`:return yield*this.parseLineStart();case`block-start`:return yield*this.parseBlockStart();case`doc`:return yield*this.parseDocument();case`flow`:return yield*this.parseFlowCollection();case`quoted-scalar`:return yield*this.parseQuotedScalar();case`block-scalar`:return yield*this.parseBlockScalar();case`plain-scalar`:return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext(`stream`);if(e[0]===``&&(yield*this.pushCount(1),e=e.substring(1)),e[0]===`%`){let t=e.length,n=e.indexOf(`#`);for(;n!==-1;){let r=e[n-1];if(r===` `||r===` `){t=n-1;break}n=e.indexOf(`#`,n+1)}for(;;){let n=e[t-1];if(n===` `||n===` `)--t;else break}let r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),`stream`}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),`stream`}return yield``,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext(`line-start`);if(e===`-`||e===`.`){if(!this.atEnd&&!this.hasChars(4))return this.setNext(`line-start`);let e=this.peek(3);if((e===`---`||e===`...`)&&iV(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,e===`---`?`doc`:`stream`}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!iV(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext(`block-start`);if((e===`-`||e===`?`||e===`:`)&&iV(t)){let e=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=e,`block-start`}return`doc`}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext(`doc`);let t=yield*this.pushIndicators();switch(e[t]){case`#`:yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),`doc`;case`*`:return yield*this.pushUntil(lV),`doc`;case`"`:case`'`:return yield*this.parseQuotedScalar();case`|`:case`>`:return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let r=this.getLine();if(r===null)return this.setNext(`flow`);if((n!==-1&&n<this.indentNext&&r[0]!==`#`||n===0&&(r.startsWith(`---`)||r.startsWith(`...`))&&iV(r[3]))&&(n!==this.indentNext-1||this.flowLevel!==1||r[0]!==`]`&&r[0]!==`}`))return this.flowLevel=0,yield``,yield*this.parseLineStart();let i=0;for(;r[i]===`,`;)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return`flow`;case`#`:return yield*this.pushCount(r.length-i),`flow`;case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),this.flowKey=!0,--this.flowLevel,this.flowLevel?`flow`:`doc`;case`*`:return yield*this.pushUntil(lV),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||iV(e)||e===`,`)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),`flow`}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e===`'`)for(;t!==-1&&this.buffer[t+1]===`'`;)t=this.buffer.indexOf(`'`,t+2);else for(;t!==-1;){let e=0;for(;this.buffer[t-1-e]===`\\`;)e+=1;if(e%2==0)break;t=this.buffer.indexOf(`"`,t+1)}let n=this.buffer.substring(0,t),r=n.indexOf(`
`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t===`-`||t===`.`){let t=this.buffer.substr(e,3);if((t===`---`||t===`...`)&&sV(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!=`number`||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]===`\r`&&--e,this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case`stream`:return yield*this.parseStream();case`line-start`:return yield*this.parseLineStart();case`block-start`:return yield*this.parseBlockStart();case`doc`:return yield*this.parseDocument();case`flow`:return yield*this.parseFlowCollection();case`quoted-scalar`:return yield*this.parseQuotedScalar();case`block-scalar`:return yield*this.parseBlockScalar();case`plain-scalar`:return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext(`stream`);if(e[0]===``&&(yield*this.pushCount(1),e=e.substring(1)),e[0]===`%`){let t=e.length,n=e.indexOf(`#`);for(;n!==-1;){let r=e[n-1];if(r===` `||r===` `){t=n-1;break}n=e.indexOf(`#`,n+1)}for(;;){let n=e[t-1];if(n===` `||n===` `)--t;else break}let r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),`stream`}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),`stream`}return yield``,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext(`line-start`);if(e===`-`||e===`.`){if(!this.atEnd&&!this.hasChars(4))return this.setNext(`line-start`);let e=this.peek(3);if((e===`---`||e===`...`)&&sV(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,e===`---`?`doc`:`stream`}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!sV(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext(`block-start`);if((e===`-`||e===`?`||e===`:`)&&sV(t)){let e=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=e,`block-start`}return`doc`}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext(`doc`);let t=yield*this.pushIndicators();switch(e[t]){case`#`:yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),`doc`;case`*`:return yield*this.pushUntil(fV),`doc`;case`"`:case`'`:return yield*this.parseQuotedScalar();case`|`:case`>`:return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let r=this.getLine();if(r===null)return this.setNext(`flow`);if((n!==-1&&n<this.indentNext&&r[0]!==`#`||n===0&&(r.startsWith(`---`)||r.startsWith(`...`))&&sV(r[3]))&&(n!==this.indentNext-1||this.flowLevel!==1||r[0]!==`]`&&r[0]!==`}`))return this.flowLevel=0,yield``,yield*this.parseLineStart();let i=0;for(;r[i]===`,`;)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return`flow`;case`#`:return yield*this.pushCount(r.length-i),`flow`;case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),this.flowKey=!0,--this.flowLevel,this.flowLevel?`flow`:`doc`;case`*`:return yield*this.pushUntil(fV),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||sV(e)||e===`,`)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),`flow`}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e===`'`)for(;t!==-1&&this.buffer[t+1]===`'`;)t=this.buffer.indexOf(`'`,t+2);else for(;t!==-1;){let e=0;for(;this.buffer[t-1-e]===`\\`;)e+=1;if(e%2==0)break;t=this.buffer.indexOf(`"`,t+1)}let n=this.buffer.substring(0,t),r=n.indexOf(`
`,this.pos);if(r!==-1){for(;r!==-1;){let e=this.continueScalar(r+1);if(e===-1)break;r=n.indexOf(`
`,e)}r!==-1&&(t=r-(n[r-1]===`\r`?2:1))}if(t===-1){if(!this.atEnd)return this.setNext(`quoted-scalar`);t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?`flow`:`doc`}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t===`+`)this.blockScalarKeep=!0;else if(t>`0`&&t<=`9`)this.blockScalarIndent=Number(t)-1;else if(t!==`-`)break}return yield*this.pushUntil(e=>iV(e)||e===`#`)}*parseBlockScalar(){let e=this.pos-1,t=0,n;loop:for(let r=this.pos;n=this.buffer[r];++r)switch(n){case` `:t+=1;break;case`
`,e)}r!==-1&&(t=r-(n[r-1]===`\r`?2:1))}if(t===-1){if(!this.atEnd)return this.setNext(`quoted-scalar`);t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?`flow`:`doc`}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t===`+`)this.blockScalarKeep=!0;else if(t>`0`&&t<=`9`)this.blockScalarIndent=Number(t)-1;else if(t!==`-`)break}return yield*this.pushUntil(e=>sV(e)||e===`#`)}*parseBlockScalar(){let e=this.pos-1,t=0,n;loop:for(let r=this.pos;n=this.buffer[r];++r)switch(n){case` `:t+=1;break;case`
`:e=r,t=0;break;case`\r`:{let e=this.buffer[r+1];if(!e&&!this.atEnd)return this.setNext(`block-scalar`);if(e===`
`)break}default:break loop}if(!n&&!this.atEnd)return this.setNext(`block-scalar`);if(t>=this.indentNext){this.indentNext=this.blockScalarIndent===-1?t:this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let t=this.continueScalar(e+1);if(t===-1)break;e=this.buffer.indexOf(`
`,t)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext(`block-scalar`);e=this.buffer.length}}let r=e+1;for(n=this.buffer[r];n===` `;)n=this.buffer[++r];if(n===` `){for(;n===` `||n===` `||n===`\r`||n===`
`;)n=this.buffer[++r];e=r-1}else if(!this.blockScalarKeep)do{let n=e-1,r=this.buffer[n];r===`\r`&&(r=this.buffer[--n]);let i=n;for(;r===` `;)r=this.buffer[--n];if(r===`
`&&n>=this.pos&&n+1+t>i)e=n;else break}while(1);return yield``,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===`:`){let r=this.buffer[n+1];if(iV(r)||e&&sV.has(r))break;t=n}else if(iV(r)){let i=this.buffer[n+1];if(r===`\r`&&(i===`
`&&n>=this.pos&&n+1+t>i)e=n;else break}while(1);return yield``,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===`:`){let r=this.buffer[n+1];if(sV(r)||e&&uV.has(r))break;t=n}else if(sV(r)){let i=this.buffer[n+1];if(r===`\r`&&(i===`
`?(n+=1,r=`
`,i=this.buffer[n+1]):t=n),i===`#`||e&&sV.has(i))break;if(r===`
`){let e=this.continueScalar(n+1);if(e===-1)break;n=Math.max(n,e-2)}}else{if(e&&sV.has(r))break;t=n}return!r&&!this.atEnd?this.setNext(`plain-scalar`):(yield``,yield*this.pushToIndex(t+1,!0),e?`flow`:`doc`)}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield``),0)}*pushIndicators(){let e=0;loop:for(;;){switch(this.charAt(0)){case`!`:e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue loop;case`&`:e+=yield*this.pushUntil(lV),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(iV(n)||t&&sV.has(n)){t?this.flowKey&&=!1:this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue loop}}}break loop}return e}*pushTag(){if(this.charAt(1)===`<`){let e=this.pos+2,t=this.buffer[e];for(;!iV(t)&&t!==`>`;)t=this.buffer[++e];return yield*this.pushToIndex(t===`>`?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(oV.has(t))t=this.buffer[++e];else if(t===`%`&&aV.has(this.buffer[e+1])&&aV.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
`,i=this.buffer[n+1]):t=n),i===`#`||e&&uV.has(i))break;if(r===`
`){let e=this.continueScalar(n+1);if(e===-1)break;n=Math.max(n,e-2)}}else{if(e&&uV.has(r))break;t=n}return!r&&!this.atEnd?this.setNext(`plain-scalar`):(yield``,yield*this.pushToIndex(t+1,!0),e?`flow`:`doc`)}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield``),0)}*pushIndicators(){let e=0;loop:for(;;){switch(this.charAt(0)){case`!`:e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue loop;case`&`:e+=yield*this.pushUntil(fV),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(sV(n)||t&&uV.has(n)){t?this.flowKey&&=!1:this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue loop}}}break loop}return e}*pushTag(){if(this.charAt(1)===`<`){let e=this.pos+2,t=this.buffer[e];for(;!sV(t)&&t!==`>`;)t=this.buffer[++e];return yield*this.pushToIndex(t===`>`?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(lV.has(t))t=this.buffer[++e];else if(t===`%`&&cV.has(this.buffer[e+1])&&cV.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
`?yield*this.pushCount(1):e===`\r`&&this.charAt(1)===`
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}},dV=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}};function fV(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function pV(e){for(let t=0;t<e.length;++t)switch(e[t].type){case`space`:case`comment`:case`newline`:break;default:return t}return-1}function mV(e){switch(e?.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`flow-collection`:return!0;default:return!1}}function hV(e){switch(e.type){case`document`:return e.start;case`block-map`:{let t=e.items[e.items.length-1];return t.sep??t.start}case`block-seq`:return e.items[e.items.length-1].start;default:return[]}}function gV(e){if(e.length===0)return[];let t=e.length;loop:for(;--t>=0;)switch(e[t].type){case`doc-start`:case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:case`newline`:break loop}for(;e[++t]?.type===`space`;);return e.splice(t,e.length)}function _V(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function vV(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!fV(t.start,`explicit-key-ind`)&&!fV(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,mV(t.value)?t.value.end?_V(t.value.end,t.sep):t.value.end=t.sep:_V(t.start,t.sep),delete t.sep)}var yV=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source=``,this.type=``,this.lexer=new uV,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=rV(e);if(!t){let t=`Not a YAML token: ${e}`;yield*this.pop({type:`error`,offset:this.offset,message:t,source:e}),this.offset+=e.length}else if(t===`scalar`)this.atNewLine=!1,this.atScalar=!0,this.type=`scalar`;else{switch(this.type=t,yield*this.step(),t){case`newline`:this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case`space`:this.atNewLine&&e[0]===` `&&(this.indent+=e.length);break;case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:this.atNewLine&&(this.indent+=e.length);break;case`doc-mode`:case`flow-error-end`:return;default:this.atNewLine=!1}this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type===`doc-end`&&e?.type!==`doc-end`){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:`doc-end`,offset:this.offset,source:this.source})}else{if(!e)return yield*this.stream();switch(e.type){case`document`:return yield*this.document(e);case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return yield*this.scalar(e);case`block-scalar`:return yield*this.blockScalar(e);case`block-map`:return yield*this.blockMap(e);case`block-seq`:return yield*this.blockSequence(e);case`flow-collection`:return yield*this.flowCollection(e);case`doc-end`:return yield*this.documentEnd(e)}yield*this.pop()}}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:`error`,offset:this.offset,source:``,message:`Tried to pop an empty stack`};else if(this.stack.length===0)yield t;else{let e=this.peek(1);switch(t.type===`block-scalar`?t.indent=`indent`in e?e.indent:0:t.type===`flow-collection`&&e.type===`document`&&(t.indent=0),t.type===`flow-collection`&&vV(t),e.type){case`document`:e.value=t;break;case`block-scalar`:e.props.push(t);break;case`block-map`:{let n=e.items[e.items.length-1];if(n.value){e.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case`block-seq`:{let n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case`flow-collection`:{let n=e.items[e.items.length-1];!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((e.type===`document`||e.type===`block-map`||e.type===`block-seq`)&&(t.type===`block-map`||t.type===`block-seq`)){let n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&pV(n.start)===-1&&(t.indent===0||n.start.every(e=>e.type!==`comment`||e.in Line truncated
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}},mV=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}};function hV(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function gV(e){for(let t=0;t<e.length;++t)switch(e[t].type){case`space`:case`comment`:case`newline`:break;default:return t}return-1}function _V(e){switch(e?.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`flow-collection`:return!0;default:return!1}}function vV(e){switch(e.type){case`document`:return e.start;case`block-map`:{let t=e.items[e.items.length-1];return t.sep??t.start}case`block-seq`:return e.items[e.items.length-1].start;default:return[]}}function yV(e){if(e.length===0)return[];let t=e.length;loop:for(;--t>=0;)switch(e[t].type){case`doc-start`:case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:case`newline`:break loop}for(;e[++t]?.type===`space`;);return e.splice(t,e.length)}function bV(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function xV(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!hV(t.start,`explicit-key-ind`)&&!hV(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,_V(t.value)?t.value.end?bV(t.value.end,t.sep):t.value.end=t.sep:bV(t.start,t.sep),delete t.sep)}var SV=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source=``,this.type=``,this.lexer=new pV,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=oV(e);if(!t){let t=`Not a YAML token: ${e}`;yield*this.pop({type:`error`,offset:this.offset,message:t,source:e}),this.offset+=e.length}else if(t===`scalar`)this.atNewLine=!1,this.atScalar=!0,this.type=`scalar`;else{switch(this.type=t,yield*this.step(),t){case`newline`:this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case`space`:this.atNewLine&&e[0]===` `&&(this.indent+=e.length);break;case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:this.atNewLine&&(this.indent+=e.length);break;case`doc-mode`:case`flow-error-end`:return;default:this.atNewLine=!1}this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type===`doc-end`&&e?.type!==`doc-end`){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:`doc-end`,offset:this.offset,source:this.source})}else{if(!e)return yield*this.stream();switch(e.type){case`document`:return yield*this.document(e);case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return yield*this.scalar(e);case`block-scalar`:return yield*this.blockScalar(e);case`block-map`:return yield*this.blockMap(e);case`block-seq`:return yield*this.blockSequence(e);case`flow-collection`:return yield*this.flowCollection(e);case`doc-end`:return yield*this.documentEnd(e)}yield*this.pop()}}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:`error`,offset:this.offset,source:``,message:`Tried to pop an empty stack`};else if(this.stack.length===0)yield t;else{let e=this.peek(1);switch(t.type===`block-scalar`?t.indent=`indent`in e?e.indent:0:t.type===`flow-collection`&&e.type===`document`&&(t.indent=0),t.type===`flow-collection`&&xV(t),e.type){case`document`:e.value=t;break;case`block-scalar`:e.props.push(t);break;case`block-map`:{let n=e.items[e.items.length-1];if(n.value){e.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case`block-seq`:{let n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case`flow-collection`:{let n=e.items[e.items.length-1];!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((e.type===`document`||e.type===`block-map`||e.type===`block-seq`)&&(t.type===`block-map`||t.type===`block-seq`)){let n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&gV(n.start)===-1&&(t.indent===0||n.start.every(e=>e.type!==`comment`||e.in Line truncated
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
`,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){_V(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,i=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey){if(!t.sep){if(fV(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=gV(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(fV(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(mV(t.key)&&!fV(t.sep,`newline`)){let e=gV(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):fV(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!fV(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){_V(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||fV(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.ite Line truncated
`,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){bV(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,i=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey){if(!t.sep){if(hV(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=yV(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(hV(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(_V(t.key)&&!hV(t.sep,`newline`)){let e=yV(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):hV(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!hV(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){bV(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||hV(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.ite Line truncated
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=gV(hV(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=gV(hV(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}};function bV(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new dV||null,prettyErrors:t}}function xV(e,t={}){let{lineCounter:n,prettyErrors:r}=bV(t),i=new yV(n?.addNewLine),a=new ZB(t),o=null;for(let t of a.compose(i.parse(e),!0,e.length))if(!o)o=t;else if(o.options.logLevel!==`silent`){o.errors.push(new pB(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(hB(e,n)),o.warnings.forEach(hB(e,n))),o}function SV(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let i=xV(e,n);if(!i)return null;if(i.warnings.forEach(e=>GR(i.options.logLevel,e)),i.errors.length>0){if(i.options.logLevel!==`silent`)throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},n))}function CV(e,t,n){let r=null;if(typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t),typeof n==`string`&&(n=n.length),typeof n==`number`){let e=Math.round(n);n=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=n??t??{};if(!e)return}return BL(e)&&!r?e.toString(n):new uB(e,r,n).toString(n)}var wV=e=>typeof e==`object`&&!!e&&!Array.isArray(e),TV=e=>wV(e)?Object.entries(e).map(([e,t])=>[e,Array.isArray(t)?t:[]]):[];function EV(e){if(wV(e)){if(wV(e.parallel))return{kind:`parallel`,base:[`parallel`],branches:TV(e.parallel)};if(wV(e.switch))return{kind:`switch`,base:[`switch`,`cases`],on:typeof e.switch.on==`string`?e.switch.on:``,branches:TV(e.switch.cases)}}}function DV(e){return e.slice(2).includes(`parallel`)}function OV(e,t){let n=xV(e).getIn(t,!0);if(VL(n))return n.toJSON()}function kV(e,t,n){let r=xV(e);return r.setIn(t,r.createNode(BV(n))),r.toString()}function AV(e,t,n){let r=xV(e),i=t.slice(0,-1),a=DV(i);if(a&&![`agent.run`,`workflow.call`].includes(n))throw Error(`Branches allow only read-only agents and workflow calls.`);let o=r.getIn(i,!0);if(WL(o)||(r.setIn(i,r.createNode([])),o=r.getIn(i,!0)),!WL(o))return{source:e,path:[]};let s=Math.min(Math.max(Number(t.at(-1))+1,0),o.items.length),c=n===`parallel`?{parallel:{"branch-1":[],"branch-2":[]}}:n===`switch`?{switch:{on:``,cases:{true:[],default:[]}}}:{type:n,...a&&n===`agent.run`?{settings:{read_only:!0}}:{}};return o.items.splice(s,0,r.createNode(c)),{source:r.toString(),path:[...i,s]}}function jV(e,t){if(t===`switch`){if(!e||e.includes(`/`))throw Error(`A case is the value it matches, without a slash.`)}else if(!/^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/.test(e))throw Error(`Use a lowercase branch name with letters, digits, dots or dashes.`)}function MV(e,t){let n=e.getIn(t,!0),r=EV(VL(n)?n.toJSON():void 0),i=r?e.getIn([...t,...r.base],!0):void 0;if(!r||!VL(i))throw Error(`This step has no branches.`);return{kind:r.kind,branches:i}}function NV(e,t,n){let r=xV(e),{kind:i,branches:a}=MV(r,t);if(jV(n,i),a.has(n))throw Error(`Branch ${n} already exists.`);return a.set(n,r.createNode([])),r.toString()}function PV(e,t,n,r){let i=xV(e),{kind:a,branches:o}=MV(i,t);if(jV(r,a),n!==r&&o.has(r))throw Error(`Branch ${r} already exists.`);let s=o.items.find(e=>UL(e.key)&&e.key.value===n);if(!s||!UL(s.key))throw Error(`Branch ${n} does not exist.`);return s.key.value=r,i.toString()}function FV(e,t,n){let r=xV(e),{kind:i,branches:a}=MV(r,t);if(i===`parallel`&&a.items.length<=2)throw Error(`Parallel needs at least two branches.`);if(a.items.length<=1)throw Error(`A switch needs at least one case.`);return Line truncated
`).find(e=>e.trim())?.trim()}}function eH(e,t){let n=JSON.stringify(e??{})+` `+(typeof t==`string`?`{{ ${t.replace(/^!/,``)} }}`:``);return[...new Set([...n.matchAll(XV)].map(e=>e[1]))]}function tH(e){let t=xV(e).toJS(),n=ZV(t)&&Array.isArray(t.steps)?t.steps:[],r=[],i=[],a=new Map,o=[],s=new Set,c=`start`;r.push({id:c,type:`step`,position:{x:0,y:0},data:{kind:`start`,key:`start`,title:`Starts when`,type:``,detail:``}});let l=[c],u=1,d=new Map,f=e=>{let t=d.get(e)??0;return d.set(e,t+1),t},p=(e,t,n,i,s,c,l,u)=>{let d=ZV(e)?e:{},p=EV(d),m=p?.kind??(typeof d.type==`string`?d.type:``),h=ZV(d.settings)?d.settings:{},g=typeof d.id==`string`?d.id:``,_=`step-${t}`,v=s?`${s}/${g||m}`:g||m;r.push({id:_,type:`step`,position:{x:n,y:i},data:{kind:`step`,key:g||t,title:g||YV(m),type:m,role:UV(m),step:l?.length===2?String(Number(l[1])+1).padStart(2,`0`):void 0,detail:p?.on?`on ${p.on.replace(/^steps\./,``)}`:QV(m,h),summary:$V(h),when:typeof d.when==`string`?d.when:void 0,retry:ZV(d.retry)&&typeof d.retry.attempts==`number`?d.retry.attempts:void 0,continues:d.on_failure===`continue`,branch:s,lane:u,path:l,stage:v,occurrence:f(v),...c?{resume:c}:{}}}),g&&a.set(g,_);let y=p?.on?`{{ ${p.on} }}`:``;for(let e of eH([d.settings,y],d.when))o.push({from:e,to:_});return _},m=(e,t,n)=>{e.forEach((r,a)=>i.push({id:`flow-${r}-${t}`,source:r,target:t,kind:`flow`,...s.has(r)?{otherwise:!0}:{},insertAfter:a===e.length-1?n:void 0}))};for(let[e,t]of n.entries()){let n=EV(t);if(n){let{kind:i,base:a,branches:o}=n,c=p(t,String(e+1),0,u*KV,void 0,void 0,[`steps`,e]);m(l,c,[`steps`,e-1]),u++;let d=ZV(t)&&typeof t.id==`string`?t.id:i,f=i===`switch`&&!o.some(([e])=>e==="default"),h=o.length+ +!!f,g=[],_=0;o.forEach(([t,n],o)=>{let s=(o-(h-1)/2)*qV,l=[c],f=[`steps`,e,...a,t];n.forEach((n,r)=>{let a=p(n,`${e+1}-${t}-${r+1}`,s,(u+r)*KV,t,d,[...f,r],i);m(l,a,[...f,r-1]),l=[a]}),_=Math.max(_,n.length);let v=`add-${e}-${t}`;r.push({id:v,type:`add`,position:{x:s+104,y:(u+n.length)*KV},data:{kind:`step`,key:v,title:``,type:``,detail:``,branch:t,lane:i,insertAfter:[...f,n.length-1]}}),m(l,v),g.push(v)});let v=(Math.max(_,1)+1)*KV-24;o.forEach(([t],n)=>{let a=(n-(h-1)/2)*qV;r.push({id:`lane-${e}-${t}`,type:`lane`,position:{x:a-12,y:u*KV-40},style:{width:`264px`,height:`${v}px`},zIndex:-1,data:{kind:`step`,key:t,title:t,type:``,detail:``,lane:i}})}),f&&(g.push(c),s.add(c)),l=g,u+=Math.max(_,1)+1;continue}let i=p(t,String(e+1),0,u*KV,void 0,void 0,[`steps`,e]);m(l,i,[`steps`,e-1]),l=[i],u++}r.push({id:`add-end`,type:`add`,position:{x:104,y:u*KV-24},data:{kind:`step`,key:`add`,title:``,type:``,detail:``,insertAfter:[`steps`,n.length-1]}}),m(l,`add-end`);for(let{from:e,to:t}of o){let n=a.get(e);n&&(i.some(e=>e.kind===`flow`&&e.source===n&&e.target===t)||i.push({id:`data-${n}-${t}`,source:n,target:t,kind:`data`,label:e,offset:24+14*i.filter(e=>e.kind===`data`).length,sourceHandle:`data-out`,targetHandle:`data-in`}))}return{nodes:r,edges:i}}var nH={agent:qt,command:In,repo:un,gate:Mn,forge:vn,human:Un,review:cn,workflow:Kn},rH={agent:`Agents`,command:`Commands`,repo:`Repository`,gate:`Checks`,forge:`Issues and PRs`,human:`People`,review:`Review`,workflow:`Flow`};function iH(e){return e===`parallel`?un:e===`switch`?Pn:nH[e.split(`.`)[0]]??Kn}function aH(e){return Object.keys(rH).map(t=>({title:rH[t],icon:nH[t],types:e.filter(e=>e.split(`.`)[0]===t)})).filter(e=>e.types.length)}function oH(e){return Object.entries(e?.inputs??{}).map(([e,t])=>({name:e,type:t.type,required:t.required===!0})).sort((e,t)=>e.name.localeCompare(t.name))}function sH(e,t){return e.filter(e=>e.required&&!(t[e.name]??``).trim()).map(e=>e.name)}function cH(e,t){switch(t){case`number`:{let t=e.trim();return t!==``&&!Number.isNaN(Number(t))?Number(t):e}case`bool`:return e===`true`||e!==`false`&&e;case`string`:return e;default:try{return JSON.parse(e)}catch{return e}}}function lH(e,t){let n={};for(let r of e){let e=t[r.name];e!==void 0&&e!==``&&(n[r.name]=cH(e,r.type))}return n}var uH=k({__name:`WorkflowPicker`,props:{value:{},workflows:{},label:{}},emits:[`pick`],setup(e,{emit:t}){let n=t;return(t,r)=>(R(),q(z(ml),{"model-value":e.value||void 0,"onUpdate:modelValue":r[0]||=e=>n(`pick`,String(e))},{default:j(()=>[M(z(xl),{"aria-label":e.label},{default:j(()=>[M(z(Sl),{placeholder:`Choose workflow`})]),_:1},8,[`aria-label`]),M(z(hl),null,{default:j(()=>[e.value&&!e.workflows.some(t=>t.id===e.value)?(R(),q(z(vl),{key:0,value:e.value,disabled:``},{default:j(()=>[A(V(e.value)+` (unavailable)`,1)]),_:1},8,[`value`])):L(``,!0),(R(!0),G(H,null,K(e.workflows,e=>(R(),q(z(vl),{key:e.id,value:e.id},{default:j(()=>[A(V(e.id),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1},8,[`model-value`]))}});function dH(e){return e.ok?`Valid`:e.line?`Line ${e.line}: ${e.message}`:e.message}function fH(e,t=[]){let n=xV(e),r=n.errors[0];if(r)return{ok:!1,message:EH(r.message),line:r.linePos?.[0]?.line};let i=n.toJS();if(!DH(i))return{ok:!1,message:`A workflow is a mapping with an id and steps.`};let a=typeof i.id==`stLine truncated
`).map((e,t)=>({number:t+1,text:e,tokens:SH(e)}))}var bH=/^(\s*)(-\s+)?/,xH=/^([^:#\s][^:#]*?)(:)(\s*)(.*)$/;function SH(e){let{code:t,comment:n}=CH(e),r=wH(t);return n&&r.push({text:n,kind:`comment`}),r}function CH(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(t)r===t&&(t=``);else if(r===`"`||r===`'`)t=r;else if(r===`#`&&(n===0||/\s/.test(e[n-1]??``)))return{code:e.slice(0,n),comment:e.slice(n)}}return{code:e,comment:``}}function wH(e){if(!e)return[];let t=[],n=bH.exec(e);n?.[1]&&t.push({text:n[1],kind:`plain`}),n?.[2]&&t.push({text:n[2],kind:`punct`});let r=e.slice(n?.[0].length??0);if(!r)return t;let i=xH.exec(r);return i?(t.push({text:i[1]??``,kind:`key`}),t.push({text:i[2]??`:`,kind:`punct`}),i[3]&&t.push({text:i[3],kind:`plain`}),[...t,...TH(i[4]??``)]):[...t,...TH(r)]}function TH(e){if(!e)return[];let t=/^("[^"]*"?|'[^']*'?)([\s\S]*)$/.exec(e);if(!t)return[{text:e,kind:`plain`}];let n=[{text:t[1]??``,kind:`string`}];return t[2]&&n.push({text:t[2],kind:`plain`}),n}function EH(e){return e.split(`
`)[0]?.trim()||`invalid YAML`}function DH(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function OH(e){return typeof e==`string`&&e.trim()!==``}var kH={class:`flex h-full w-[24rem] flex-col border-l border-border bg-card shadow-xl`},AH={class:`flex items-center gap-2.5 border-b border-border px-4 py-3`},jH={class:`flex size-8 shrink-0 items-center justify-center rounded-md bg-secondary text-primary`},MH={class:`min-w-0 flex-1`},NH=[`value`,`placeholder`],PH={class:`truncate font-mono text-[11px] text-fg-subtle`},FH={class:`flex-1 space-y-5 overflow-y-auto px-4 py-4`},IH={key:0,class:`rounded-md bg-danger/10 px-2.5 py-1.5 text-xs text-danger`,role:`alert`},LH={key:1,class:`space-y-3`},RH={key:0,class:`block space-y-1.5`},zH={id:`switch-on`},BH=[`value`],VH={class:`text-xs font-medium text-muted-foreground`},HH={class:`flex items-center gap-2`},UH={key:1,role:`alert`,class:`text-xs text-danger`},WH={key:2,class:`space-y-1.5`},GH=[`title`],KH=[`value`],qH=[`value`],JH={key:4,class:`flex flex-wrap items-center gap-1 pt-0.5`},YH=[`onClick`],XH=[`onClick`],ZH={key:3,class:`divide-y divide-border rounded-md border border-border`},QH=[`title`],$H=[`value`,`onChange`],eU=[`value`],tU=[`value`,`onInput`],nU=[`value`,`onFocus`,`onInput`],rU={key:0,class:`space-y-3`},iU={class:`text-[13px]`},aU={key:0,class:`text-danger`},oU={class:`ml-2 text-xs text-fg-subtle`},sU=[`aria-label`,`value`,`onChange`],cU={key:0,value:`value`},lU=[`aria-label`,`value`,`onChange`],uU=[`value`],dU=[`aria-label`,`value`,`onChange`],fU={key:1,class:`space-y-3`},pU={class:`text-[13px]`},mU={class:`ml-2 text-xs text-fg-subtle`},hU=[`aria-label`,`disabled`,`value`,`onChange`],gU=[`value`],_U=[`title`],vU={key:0,class:`text-xs text-danger`},yU={class:`space-y-2`},bU={class:`divide-y divide-border rounded-md border border-border`},xU={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},SU=[`value`],CU={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},wU=[`value`],TU={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},EU=[`value`],DU={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},OU={class:`flex items-center border-t border-border px-4 py-2.5`},kU=k({__name:`StepEditor`,props:{yaml:{},path:{},vocabulary:{},workflows:{},modelAliases:{}},emits:[`update:yaml`,`close`,`remove`],setup(e,{emit:t}){let n=e,r=t,i=I(()=>OV(n.yaml,n.path)??{}),a=I(()=>EV(i.value)),o=I(()=>a.value?.kind??(typeof i.value.type==`string`?i.value.type:``)),s=I(()=>a.value?.branches.map(([e])=>e)??[]),c=I(()=>o.value===`parallel`?2:1);function l(e){r(`update:yaml`,kV(n.yaml,n.path,{...i.value,switch:{...i.value.switch,on:e}}))}let u=J(``),d=J(``);function f(e,t,i=``){try{let a=e===`add`?NV(n.yaml,n.path,t):e===`rename`?PV(n.yaml,n.path,t,i):FV(n.yaml,n.path,t);r(`update:yaml`,a),u.value=``,d.value=``}catch(e){d.value=String(e.message)}}let p=I(()=>n.vocabulary.find(e=>e.name===o.value)),m=I(()=>typeof i.value.settings==`object`&&i.value.settings!==null?i.value.settings:{}),h=I(()=>zV(n.yaml,n.path)),g=I(()=>p.value?.settings&&i.value.settings?_H(i.value.settings,p.value.settings,`settings`):``),_=[`mission`,`workflow`,`message`,`body`,`plan`,`then`,`status`,`detail`,`run`,`rules`],v=/mission|body|detail|plan|rules/;function y(e,t){return[`workflow.call`,`workflow.handoff`].includes(o.value)&&e===`workflow`||o.value===`human.approve`&&e===`then`?`workflow`:o.value===`agent.run`&&e===`model`?`select`:t.type===`string`?t.enum?`select`:v.test(e)?`text`:`line`:t.type===`boolean`?`boolean`:t.type===`integer`||t.type===`number`?`number`:t.type===`array`&&t.items?.type===`string`?`lines`:`yaml`}let b=I(()=>{let e=Object.entries(p.value?.settings?.properties??{}).filter(([e])=>o.value!==`workflow.call`||![`inputs`,`outputs`].includes(e)).map(([e,t])=>({key:e,schema:t,kind:y(e,t),options:o.value===`agent.run`&&e===`model`?n.modelAliases:t.enum??[]})),t=e.filter(e=>_.includes(e.key)&&e.kind!==`boolean`).sort((e,t)=>_.indexOf(e.key)-_.indexOf(t.key))[0],r=e.filter(e=>e!==t);return{lead:t,compact:r.filter(e=>[`workflow`,`select`,`line`,`number`,`boolean`].includes(e.kind)),long:r.filter(e=>[`text`,`lines`,`yaml`].includes(e.kind))}});function x(e){let{id:t,type:i,...a}=e;r(`update:yaml`,kV(n.yaml,n.path,{id:t,type:i,...a}))}function S(e,t){x({...i.value,[e]:t})}function C(e){S(`retry`,{...i.value.retry,...e})}function w(e,t){let n={...m.value,[e]:t};o.value===`workflow.call`&&e===`wait`&&t!==!0&&delete n.outputs,x({...i.value,settings:n})}function T(e,t){let n={...m.value,[e]:t};o.value===`workflow.call`&&t!==m.value[e]&&(delete n.inputs,delete n.outputs),x({...i.value,settings:n})}let E=I(()=>n.workflows.find(e=>e.id===m.value.workflow)),ee=I(()=>Object.entries(VV(E.value?.yaml??``,`inputs`)??{})),D=I(()=>Object.entries(VV(E.value?.yaml??``,`outputs`)??{})),te=I(()=>Object.entries(VV(n.yaml,`inputs`)??{})),ne=I(()=>Object.entries(VV(n.yaml,`outputs`)??{})),re=I(()=>m.value.inputs??{}),ie=I(()=>m.value.outputs??{}),ae=e=>typeof e==`string`&&e.startsWith(`inputs.`),oe=e Line truncated
`)[0]}}}let fe=e=>e===void 0?``:CV(e).trimEnd(),pe=(e,t)=>t.title??e.replaceAll(`_`,` `).replace(/^./,e=>e.toUpperCase()),me=e=>typeof m.value[e]==`string`?m.value[e]:``;return(t,n)=>(R(),G(`aside`,kH,[W(`header`,AH,[W(`span`,jH,[(R(),q(Ye(z(iH)(o.value)),{class:`size-4`}))]),W(`div`,MH,[W(`input`,{value:i.value.id??``,class:`w-full truncate bg-transparent text-sm font-medium outline-none placeholder:text-fg-subtle focus:underline`,placeholder:z(YV)(o.value),"aria-label":`Step id`,onInput:n[0]||=e=>S(`id`,e.target.value)},null,40,NH),W(`div`,PH,V(o.value),1)]),M(z(Z),{type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":`Close`,onClick:n[1]||=e=>r(`close`)},{default:j(()=>[M(z(Jn))]),_:1})]),W(`div`,FH,[g.value?(R(),G(`p`,IH,V(g.value),1)):L(``,!0),a.value?(R(),G(`section`,LH,[o.value===`switch`?(R(),G(`label`,RH,[n[18]||=W(`span`,{class:`text-xs font-medium text-muted-foreground`,title:`The value whose case runs; a case named default runs when none matches`},`Switch on`,-1),M(z(O),{"model-value":a.value.on,class:`font-mono`,placeholder:`steps.assess.result.fit`,list:`switch-on`,onChange:n[2]||=e=>l(e.target.value.trim())},null,8,[`model-value`]),W(`datalist`,zH,[(R(!0),G(H,null,K(h.value,e=>(R(),G(`option`,{key:e,value:`steps.${e}.result.`},null,8,BH))),128))])])):L(``,!0),W(`div`,VH,V(o.value===`switch`?`Cases`:`Branches`),1),(R(!0),G(H,null,K(s.value,e=>(R(),G(`div`,{key:e,class:`flex items-center gap-2`},[M(z(O),{"model-value":e,class:N(o.value===`switch`&&`font-mono`),"aria-label":`${o.value===`switch`?`Case`:`Branch`} ${e}`,onChange:t=>f(`rename`,e,t.target.value.trim())},null,8,[`model-value`,`class`,`aria-label`,`onChange`]),M(z(Z),{type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":`Remove ${e}`,disabled:s.value.length<=c.value,onClick:t=>f(`delete`,e)},{default:j(()=>[M(z(Rn))]),_:1},8,[`aria-label`,`disabled`,`onClick`])]))),128)),W(`div`,HH,[M(z(O),{modelValue:u.value,"onUpdate:modelValue":n[3]||=e=>u.value=e,"aria-label":o.value===`switch`?`New case value`:`New branch name`,placeholder:o.value===`switch`?`Value, or default`:`Branch name`,onKeydown:n[4]||=Ot(Dt(e=>f(`add`,u.value.trim()),[`prevent`]),[`enter`])},null,8,[`modelValue`,`aria-label`,`placeholder`]),M(z(Z),{type:`button`,size:`icon-sm`,variant:`outline`,"aria-label":o.value===`switch`?`Add case`:`Add branch`,disabled:!u.value.trim(),onClick:n[5]||=e=>f(`add`,u.value.trim())},{default:j(()=>[M(z(Tn))]),_:1},8,[`aria-label`,`disabled`])]),d.value?(R(),G(`p`,UH,V(d.value),1)):L(``,!0)])):L(``,!0),b.value.lead?(R(),G(`section`,WH,[W(`div`,{class:`flex items-center gap-1 text-xs font-medium text-muted-foreground`,title:b.value.lead.schema.description},[A(V(pe(b.value.lead.key,b.value.lead.schema))+` `,1),b.value.lead.schema.description?(R(),q(z(rn),{key:0,class:`size-3 text-fg-subtle`})):L(``,!0)],8,GH),b.value.lead.kind===`workflow`?(R(),q(uH,{key:0,value:me(b.value.lead.key),workflows:e.workflows,label:pe(b.value.lead.key,b.value.lead.schema),onPick:n[6]||=e=>T(b.value.lead.key,e)},null,8,[`value`,`workflows`,`label`])):b.value.lead.kind===`select`?(R(),G(`select`,{key:1,class:`h-9 w-full rounded-md border border-input bg-background px-2`,value:me(b.value.lead.key),onChange:n[7]||=e=>w(b.value.lead.key,e.target.value||void 0)},[n[19]||=W(`option`,{value:``},`Default`,-1),(R(!0),G(H,null,K(b.value.lead.options,e=>(R(),G(`option`,{key:e,value:e},V(e),9,qH))),128))],40,KH)):b.value.lead.kind===`text`?(R(),q(z(zl),{key:2,"model-value":me(b.value.lead.key),class:`min-h-40 text-[13px] leading-relaxed`,onFocus:n[8]||=e=>ce.value=b.value.lead.key,"onUpdate:modelValue":n[9]||=e=>w(b.value.lead.key,String(e))},null,8,[`model-value`])):(R(),q(z(O),{key:3,"model-value":me(b.value.lead.key),onFocus:n[10]||=e=>ce.value=b.value.lead.key,"onUpdate:modelValue":n[11]||=e=>w(b.value.lead.key,String(e))},null,8,[`model-value`])),h.value.length&&b.value.lead.kind!==`select`?(R(),G(`div`,JH,[n[20]||=W(`span`,{class:`text-[11px] text-fg-subtle`},`Insert`,-1),(R(!0),G(H,null,K(h.value,e=>(R(),G(H,{key:e},[W(`button`,{type:`button`,class:`rounded-full border border-border px-2 py-0.5 font-mono text-[11px] hover:border-primary hover:text-primary`,onClick:t=>le(e,`summary`)},V(e),9,YH),W(`button`,{type:`button`,class:`rounded-full border border-border px-2 py-0.5 font-mono text-[11px] hover:border-primary hover:text-primary`,onClick:t=>le(e,`result`)},V(e)+`.result`,9,XH)],64))),128))])):L(``,!0)])):L(``,!0),b.value.compact.length?(R(),G(`section`,ZH,[(R(!0),G(H,null,K(b.value.compact,t=>(R(),G(`div`,{key:t.key,class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},[W(`span`,{class:`flex flex-1 items-center gap-1 text-[13px]`,title:t.schema.description},[A(V(pe(t.key,t.schema))+` `,1),t.schema.description?(R(),q(z(rn),{key:0,class:`size-3 text-fg-subtle`})):L(``,!0)],8,QH),t.kind===`workflow`?(R(),q(uH,{key:0,class:`max-w-48`,value:me(t.key),workflows:e.workflows,label:pe(t.key,t.schema),onPick:e=>T(t.key,e)},null,8,[`value`,`workflows`,`label`,`onPicLine truncated
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=yV(vV(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=yV(vV(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}};function CV(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new mV||null,prettyErrors:t}}function wV(e,t={}){let{lineCounter:n,prettyErrors:r}=CV(t),i=new SV(n?.addNewLine),a=new eV(t),o=null;for(let t of a.compose(i.parse(e),!0,e.length))if(!o)o=t;else if(o.options.logLevel!==`silent`){o.errors.push(new gB(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(vB(e,n)),o.warnings.forEach(vB(e,n))),o}function TV(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let i=wV(e,n);if(!i)return null;if(i.warnings.forEach(e=>JR(i.options.logLevel,e)),i.errors.length>0){if(i.options.logLevel!==`silent`)throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},n))}function EV(e,t,n){let r=null;if(typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t),typeof n==`string`&&(n=n.length),typeof n==`number`){let e=Math.round(n);n=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=n??t??{};if(!e)return}return UL(e)&&!r?e.toString(n):new pB(e,r,n).toString(n)}var DV=e=>typeof e==`object`&&!!e&&!Array.isArray(e),OV=e=>DV(e)?Object.entries(e).map(([e,t])=>[e,Array.isArray(t)?t:[]]):[];function kV(e){if(DV(e)){if(DV(e.parallel))return{kind:`parallel`,base:[`parallel`],branches:OV(e.parallel)};if(DV(e.switch))return{kind:`switch`,base:[`switch`,`cases`],on:typeof e.switch.on==`string`?e.switch.on:``,branches:OV(e.switch.cases)}}}function AV(e){return e.slice(2).includes(`parallel`)}function jV(e,t){let n=wV(e).getIn(t,!0);if(WL(n))return n.toJSON()}function MV(e,t,n){let r=wV(e);return r.setIn(t,r.createNode(UV(n))),r.toString()}function NV(e,t,n){let r=wV(e),i=t.slice(0,-1),a=AV(i);if(a&&![`agent.run`,`workflow.call`].includes(n))throw Error(`Branches allow only read-only agents and workflow calls.`);let o=r.getIn(i,!0);if(qL(o)||(r.setIn(i,r.createNode([])),o=r.getIn(i,!0)),!qL(o))return{source:e,path:[]};let s=Math.min(Math.max(Number(t.at(-1))+1,0),o.items.length),c=n===`parallel`?{parallel:{"branch-1":[],"branch-2":[]}}:n===`switch`?{switch:{on:``,cases:{true:[],default:[]}}}:{type:n,...a&&n===`agent.run`?{settings:{read_only:!0}}:{}};return o.items.splice(s,0,r.createNode(c)),{source:r.toString(),path:[...i,s]}}function PV(e,t){if(t===`switch`){if(!e||e.includes(`/`))throw Error(`A case is the value it matches, without a slash.`)}else if(!/^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/.test(e))throw Error(`Use a lowercase branch name with letters, digits, dots or dashes.`)}function FV(e,t){let n=e.getIn(t,!0),r=kV(WL(n)?n.toJSON():void 0),i=r?e.getIn([...t,...r.base],!0):void 0;if(!r||!WL(i))throw Error(`This step has no branches.`);return{kind:r.kind,branches:i}}function IV(e,t,n){let r=wV(e),{kind:i,branches:a}=FV(r,t);if(PV(n,i),a.has(n))throw Error(`Branch ${n} already exists.`);return a.set(n,r.createNode([])),r.toString()}function LV(e,t,n,r){let i=wV(e),{kind:a,branches:o}=FV(i,t);if(PV(r,a),n!==r&&o.has(r))throw Error(`Branch ${r} already exists.`);let s=o.items.find(e=>KL(e.key)&&e.key.value===n);if(!s||!KL(s.key))throw Error(`Branch ${n} does not exist.`);return s.key.value=r,i.toString()}function RV(e,t,n){let r=wV(e),{kind:i,branches:a}=FV(r,t);if(i===`parallel`&&a.items.length<=2)throw Error(`Parallel needs at least two branches.`);if(a.items.length<=1)throw Error(`A switch needs at least one case.`);return Line truncated
`).find(e=>e.trim())?.trim()}}function rH(e,t){let n=JSON.stringify(e??{})+` `+(typeof t==`string`?`{{ ${t.replace(/^!/,``)} }}`:``);return[...new Set([...n.matchAll($V)].map(e=>e[1]))]}function iH(e){let t=wV(e).toJS(),n=eH(t)&&Array.isArray(t.steps)?t.steps:[],r=[],i=[],a=new Map,o=[],s=new Set,c=`start`;r.push({id:c,type:`step`,position:{x:0,y:0},data:{kind:`start`,key:`start`,title:`Starts when`,type:``,detail:``}});let l=[c],u=1,d=new Map,f=e=>{let t=d.get(e)??0;return d.set(e,t+1),t},p=(e,t,n,i,s,c,l,u)=>{let d=eH(e)?e:{},p=kV(d),m=p?.kind??(typeof d.type==`string`?d.type:``),h=eH(d.settings)?d.settings:{},g=typeof d.id==`string`?d.id:``,_=`step-${t}`,v=s?`${s}/${g||m}`:g||m;r.push({id:_,type:`step`,position:{x:n,y:i},data:{kind:`step`,key:g||t,title:g||QV(m),type:m,role:KV(m),step:l?.length===2?String(Number(l[1])+1).padStart(2,`0`):void 0,detail:p?.on?`on ${p.on.replace(/^steps\./,``)}`:tH(m,h),summary:nH(h),when:typeof d.when==`string`?d.when:void 0,retry:eH(d.retry)&&typeof d.retry.attempts==`number`?d.retry.attempts:void 0,continues:d.on_failure===`continue`,branch:s,lane:u,path:l,stage:v,occurrence:f(v),...c?{resume:c}:{}}}),g&&a.set(g,_);let y=p?.on?`{{ ${p.on} }}`:``;for(let e of rH([d.settings,y],d.when))o.push({from:e,to:_});return _},m=(e,t,n)=>{e.forEach((r,a)=>i.push({id:`flow-${r}-${t}`,source:r,target:t,kind:`flow`,...s.has(r)?{otherwise:!0}:{},insertAfter:a===e.length-1?n:void 0}))};for(let[e,t]of n.entries()){let n=kV(t);if(n){let{kind:i,base:a,branches:o}=n,c=p(t,String(e+1),0,u*YV,void 0,void 0,[`steps`,e]);m(l,c,[`steps`,e-1]),u++;let d=eH(t)&&typeof t.id==`string`?t.id:i,f=i===`switch`&&!o.some(([e])=>e==="default"),h=o.length+ +!!f,g=[],_=0;o.forEach(([t,n],o)=>{let s=(o-(h-1)/2)*XV,l=[c],f=[`steps`,e,...a,t];n.forEach((n,r)=>{let a=p(n,`${e+1}-${t}-${r+1}`,s,(u+r)*YV,t,d,[...f,r],i);m(l,a,[...f,r-1]),l=[a]}),_=Math.max(_,n.length);let v=`add-${e}-${t}`;r.push({id:v,type:`add`,position:{x:s+104,y:(u+n.length)*YV},data:{kind:`step`,key:v,title:``,type:``,detail:``,branch:t,lane:i,insertAfter:[...f,n.length-1]}}),m(l,v),g.push(v)});let v=(Math.max(_,1)+1)*YV-24;o.forEach(([t],n)=>{let a=(n-(h-1)/2)*XV;r.push({id:`lane-${e}-${t}`,type:`lane`,position:{x:a-12,y:u*YV-40},style:{width:`264px`,height:`${v}px`},zIndex:-1,data:{kind:`step`,key:t,title:t,type:``,detail:``,lane:i}})}),f&&(g.push(c),s.add(c)),l=g,u+=Math.max(_,1)+1;continue}let i=p(t,String(e+1),0,u*YV,void 0,void 0,[`steps`,e]);m(l,i,[`steps`,e-1]),l=[i],u++}r.push({id:`add-end`,type:`add`,position:{x:104,y:u*YV-24},data:{kind:`step`,key:`add`,title:``,type:``,detail:``,insertAfter:[`steps`,n.length-1]}}),m(l,`add-end`);for(let{from:e,to:t}of o){let n=a.get(e);n&&(i.some(e=>e.kind===`flow`&&e.source===n&&e.target===t)||i.push({id:`data-${n}-${t}`,source:n,target:t,kind:`data`,label:e,offset:24+14*i.filter(e=>e.kind===`data`).length,sourceHandle:`data-out`,targetHandle:`data-in`}))}return{nodes:r,edges:i}}var aH={agent:Jt,command:Ln,repo:dn,gate:Nn,forge:yn,human:Wn,review:ln,workflow:qn},oH={agent:`Agents`,command:`Commands`,repo:`Repository`,gate:`Checks`,forge:`Issues and PRs`,human:`People`,review:`Review`,workflow:`Flow`};function sH(e){return e===`parallel`?dn:e===`switch`?Fn:aH[e.split(`.`)[0]]??qn}function cH(e){return Object.keys(oH).map(t=>({title:oH[t],icon:aH[t],types:e.filter(e=>e.split(`.`)[0]===t)})).filter(e=>e.types.length)}function lH(e){return Object.entries(e?.inputs??{}).map(([e,t])=>({name:e,type:t.type,required:t.required===!0})).sort((e,t)=>e.name.localeCompare(t.name))}function uH(e,t){return e.filter(e=>e.required&&!(t[e.name]??``).trim()).map(e=>e.name)}function dH(e,t){switch(t){case`number`:{let t=e.trim();return t!==``&&!Number.isNaN(Number(t))?Number(t):e}case`bool`:return e===`true`||e!==`false`&&e;case`string`:return e;default:try{return JSON.parse(e)}catch{return e}}}function fH(e,t){let n={};for(let r of e){let e=t[r.name];e!==void 0&&e!==``&&(n[r.name]=dH(e,r.type))}return n}var pH=k({__name:`WorkflowPicker`,props:{value:{},workflows:{},label:{}},emits:[`pick`],setup(e,{emit:t}){let n=t;return(t,r)=>(R(),q(z(hl),{"model-value":e.value||void 0,"onUpdate:modelValue":r[0]||=e=>n(`pick`,String(e))},{default:j(()=>[M(z(Sl),{"aria-label":e.label},{default:j(()=>[M(z(Cl),{placeholder:`Choose workflow`})]),_:1},8,[`aria-label`]),M(z(gl),null,{default:j(()=>[e.value&&!e.workflows.some(t=>t.id===e.value)?(R(),q(z(yl),{key:0,value:e.value,disabled:``},{default:j(()=>[A(V(e.value)+` (unavailable)`,1)]),_:1},8,[`value`])):L(``,!0),(R(!0),G(H,null,K(e.workflows,e=>(R(),q(z(yl),{key:e.id,value:e.id},{default:j(()=>[A(V(e.id),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1},8,[`model-value`]))}});function mH(e){return e.ok?`Valid`:e.line?`Line ${e.line}: ${e.message}`:e.message}function hH(e,t=[]){let n=wV(e),r=n.errors[0];if(r)return{ok:!1,message:kH(r.message),line:r.linePos?.[0]?.line};let i=n.toJS();if(!AH(i))return{ok:!1,message:`A workflow is a mapping with an id and steps.`};let a=typeof i.id==`stLine truncated
`).map((e,t)=>({number:t+1,text:e,tokens:TH(e)}))}var CH=/^(\s*)(-\s+)?/,wH=/^([^:#\s][^:#]*?)(:)(\s*)(.*)$/;function TH(e){let{code:t,comment:n}=EH(e),r=DH(t);return n&&r.push({text:n,kind:`comment`}),r}function EH(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(t)r===t&&(t=``);else if(r===`"`||r===`'`)t=r;else if(r===`#`&&(n===0||/\s/.test(e[n-1]??``)))return{code:e.slice(0,n),comment:e.slice(n)}}return{code:e,comment:``}}function DH(e){if(!e)return[];let t=[],n=CH.exec(e);n?.[1]&&t.push({text:n[1],kind:`plain`}),n?.[2]&&t.push({text:n[2],kind:`punct`});let r=e.slice(n?.[0].length??0);if(!r)return t;let i=wH.exec(r);return i?(t.push({text:i[1]??``,kind:`key`}),t.push({text:i[2]??`:`,kind:`punct`}),i[3]&&t.push({text:i[3],kind:`plain`}),[...t,...OH(i[4]??``)]):[...t,...OH(r)]}function OH(e){if(!e)return[];let t=/^("[^"]*"?|'[^']*'?)([\s\S]*)$/.exec(e);if(!t)return[{text:e,kind:`plain`}];let n=[{text:t[1]??``,kind:`string`}];return t[2]&&n.push({text:t[2],kind:`plain`}),n}function kH(e){return e.split(`
`)[0]?.trim()||`invalid YAML`}function AH(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jH(e){return typeof e==`string`&&e.trim()!==``}var MH={class:`flex h-full w-[24rem] flex-col border-l border-border bg-card shadow-xl`},NH={class:`flex items-center gap-2.5 border-b border-border px-4 py-3`},PH={class:`flex size-8 shrink-0 items-center justify-center rounded-md bg-secondary text-primary`},FH={class:`min-w-0 flex-1`},IH=[`value`,`placeholder`],LH={class:`truncate font-mono text-[11px] text-fg-subtle`},RH={class:`flex-1 space-y-5 overflow-y-auto px-4 py-4`},zH={key:0,class:`rounded-md bg-danger/10 px-2.5 py-1.5 text-xs text-danger`,role:`alert`},BH={key:1,class:`space-y-3`},VH={key:0,class:`block space-y-1.5`},HH={id:`switch-on`},UH=[`value`],WH={class:`text-xs font-medium text-muted-foreground`},GH={class:`flex items-center gap-2`},KH={key:1,role:`alert`,class:`text-xs text-danger`},qH={key:2,class:`space-y-1.5`},JH=[`title`],YH=[`value`],XH=[`value`],ZH={key:4,class:`flex flex-wrap items-center gap-1 pt-0.5`},QH=[`onClick`],$H=[`onClick`],eU={key:3,class:`divide-y divide-border rounded-md border border-border`},tU=[`title`],nU=[`value`,`onChange`],rU=[`value`],iU=[`value`,`onInput`],aU=[`value`,`onFocus`,`onInput`],oU={key:0,class:`space-y-3`},sU={class:`text-[13px]`},cU={key:0,class:`text-danger`},lU={class:`ml-2 text-xs text-fg-subtle`},uU=[`aria-label`,`value`,`onChange`],dU={key:0,value:`value`},fU=[`aria-label`,`value`,`onChange`],pU=[`value`],mU=[`aria-label`,`value`,`onChange`],hU={key:1,class:`space-y-3`},gU={class:`text-[13px]`},_U={class:`ml-2 text-xs text-fg-subtle`},vU=[`aria-label`,`disabled`,`value`,`onChange`],yU=[`value`],bU=[`title`],xU={key:0,class:`text-xs text-danger`},SU={class:`space-y-2`},CU={class:`divide-y divide-border rounded-md border border-border`},wU={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},TU=[`value`],EU={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},DU=[`value`],OU={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},kU=[`value`],AU={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},jU={class:`flex items-center border-t border-border px-4 py-2.5`},MU=k({__name:`StepEditor`,props:{yaml:{},path:{},vocabulary:{},workflows:{},modelAliases:{}},emits:[`update:yaml`,`close`,`remove`],setup(e,{emit:t}){let n=e,r=t,i=I(()=>jV(n.yaml,n.path)??{}),a=I(()=>kV(i.value)),o=I(()=>a.value?.kind??(typeof i.value.type==`string`?i.value.type:``)),s=I(()=>a.value?.branches.map(([e])=>e)??[]),c=I(()=>o.value===`parallel`?2:1);function l(e){r(`update:yaml`,MV(n.yaml,n.path,{...i.value,switch:{...i.value.switch,on:e}}))}let u=J(``),d=J(``);function f(e,t,i=``){try{let a=e===`add`?IV(n.yaml,n.path,t):e===`rename`?LV(n.yaml,n.path,t,i):RV(n.yaml,n.path,t);r(`update:yaml`,a),u.value=``,d.value=``}catch(e){d.value=String(e.message)}}let p=I(()=>n.vocabulary.find(e=>e.name===o.value)),m=I(()=>typeof i.value.settings==`object`&&i.value.settings!==null?i.value.settings:{}),h=I(()=>HV(n.yaml,n.path)),g=I(()=>p.value?.settings&&i.value.settings?bH(i.value.settings,p.value.settings,`settings`):``),_=[`mission`,`workflow`,`message`,`body`,`plan`,`then`,`status`,`detail`,`run`,`rules`],v=/mission|body|detail|plan|rules/;function y(e,t){return[`workflow.call`,`workflow.handoff`].includes(o.value)&&e===`workflow`||o.value===`human.approve`&&e===`then`?`workflow`:o.value===`agent.run`&&e===`model`?`select`:t.type===`string`?t.enum?`select`:v.test(e)?`text`:`line`:t.type===`boolean`?`boolean`:t.type===`integer`||t.type===`number`?`number`:t.type===`array`&&t.items?.type===`string`?`lines`:`yaml`}let b=I(()=>{let e=Object.entries(p.value?.settings?.properties??{}).filter(([e])=>o.value!==`workflow.call`||![`inputs`,`outputs`].includes(e)).map(([e,t])=>({key:e,schema:t,kind:y(e,t),options:o.value===`agent.run`&&e===`model`?n.modelAliases:t.enum??[]})),t=e.filter(e=>_.includes(e.key)&&e.kind!==`boolean`).sort((e,t)=>_.indexOf(e.key)-_.indexOf(t.key))[0],r=e.filter(e=>e!==t);return{lead:t,compact:r.filter(e=>[`workflow`,`select`,`line`,`number`,`boolean`].includes(e.kind)),long:r.filter(e=>[`text`,`lines`,`yaml`].includes(e.kind))}});function x(e){let{id:t,type:i,...a}=e;r(`update:yaml`,MV(n.yaml,n.path,{id:t,type:i,...a}))}function S(e,t){x({...i.value,[e]:t})}function C(e){S(`retry`,{...i.value.retry,...e})}function w(e,t){let n={...m.value,[e]:t};o.value===`workflow.call`&&e===`wait`&&t!==!0&&delete n.outputs,x({...i.value,settings:n})}function T(e,t){let n={...m.value,[e]:t};o.value===`workflow.call`&&t!==m.value[e]&&(delete n.inputs,delete n.outputs),x({...i.value,settings:n})}let E=I(()=>n.workflows.find(e=>e.id===m.value.workflow)),ee=I(()=>Object.entries(WV(E.value?.yaml??``,`inputs`)??{})),D=I(()=>Object.entries(WV(E.value?.yaml??``,`outputs`)??{})),te=I(()=>Object.entries(WV(n.yaml,`inputs`)??{})),ne=I(()=>Object.entries(WV(n.yaml,`outputs`)??{})),re=I(()=>m.value.inputs??{}),ie=I(()=>m.value.outputs??{}),ae=e=>typeof e==`string`&&e.startsWith(`inputs.`),oe=e Line truncated
`)[0]}}}let fe=e=>e===void 0?``:EV(e).trimEnd(),pe=(e,t)=>t.title??e.replaceAll(`_`,` `).replace(/^./,e=>e.toUpperCase()),me=e=>typeof m.value[e]==`string`?m.value[e]:``;return(t,n)=>(R(),G(`aside`,MH,[W(`header`,NH,[W(`span`,PH,[(R(),q(Ye(z(sH)(o.value)),{class:`size-4`}))]),W(`div`,FH,[W(`input`,{value:i.value.id??``,class:`w-full truncate bg-transparent text-sm font-medium outline-none placeholder:text-fg-subtle focus:underline`,placeholder:z(QV)(o.value),"aria-label":`Step id`,onInput:n[0]||=e=>S(`id`,e.target.value)},null,40,IH),W(`div`,LH,V(o.value),1)]),M(z(Z),{type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":`Close`,onClick:n[1]||=e=>r(`close`)},{default:j(()=>[M(z(Yn))]),_:1})]),W(`div`,RH,[g.value?(R(),G(`p`,zH,V(g.value),1)):L(``,!0),a.value?(R(),G(`section`,BH,[o.value===`switch`?(R(),G(`label`,VH,[n[18]||=W(`span`,{class:`text-xs font-medium text-muted-foreground`,title:`The value whose case runs; a case named default runs when none matches`},`Switch on`,-1),M(z(O),{"model-value":a.value.on,class:`font-mono`,placeholder:`steps.assess.result.fit`,list:`switch-on`,onChange:n[2]||=e=>l(e.target.value.trim())},null,8,[`model-value`]),W(`datalist`,HH,[(R(!0),G(H,null,K(h.value,e=>(R(),G(`option`,{key:e,value:`steps.${e}.result.`},null,8,UH))),128))])])):L(``,!0),W(`div`,WH,V(o.value===`switch`?`Cases`:`Branches`),1),(R(!0),G(H,null,K(s.value,e=>(R(),G(`div`,{key:e,class:`flex items-center gap-2`},[M(z(O),{"model-value":e,class:N(o.value===`switch`&&`font-mono`),"aria-label":`${o.value===`switch`?`Case`:`Branch`} ${e}`,onChange:t=>f(`rename`,e,t.target.value.trim())},null,8,[`model-value`,`class`,`aria-label`,`onChange`]),M(z(Z),{type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":`Remove ${e}`,disabled:s.value.length<=c.value,onClick:t=>f(`delete`,e)},{default:j(()=>[M(z(zn))]),_:1},8,[`aria-label`,`disabled`,`onClick`])]))),128)),W(`div`,GH,[M(z(O),{modelValue:u.value,"onUpdate:modelValue":n[3]||=e=>u.value=e,"aria-label":o.value===`switch`?`New case value`:`New branch name`,placeholder:o.value===`switch`?`Value, or default`:`Branch name`,onKeydown:n[4]||=Ot(Dt(e=>f(`add`,u.value.trim()),[`prevent`]),[`enter`])},null,8,[`modelValue`,`aria-label`,`placeholder`]),M(z(Z),{type:`button`,size:`icon-sm`,variant:`outline`,"aria-label":o.value===`switch`?`Add case`:`Add branch`,disabled:!u.value.trim(),onClick:n[5]||=e=>f(`add`,u.value.trim())},{default:j(()=>[M(z(En))]),_:1},8,[`aria-label`,`disabled`])]),d.value?(R(),G(`p`,KH,V(d.value),1)):L(``,!0)])):L(``,!0),b.value.lead?(R(),G(`section`,qH,[W(`div`,{class:`flex items-center gap-1 text-xs font-medium text-muted-foreground`,title:b.value.lead.schema.description},[A(V(pe(b.value.lead.key,b.value.lead.schema))+` `,1),b.value.lead.schema.description?(R(),q(z(an),{key:0,class:`size-3 text-fg-subtle`})):L(``,!0)],8,JH),b.value.lead.kind===`workflow`?(R(),q(pH,{key:0,value:me(b.value.lead.key),workflows:e.workflows,label:pe(b.value.lead.key,b.value.lead.schema),onPick:n[6]||=e=>T(b.value.lead.key,e)},null,8,[`value`,`workflows`,`label`])):b.value.lead.kind===`select`?(R(),G(`select`,{key:1,class:`h-9 w-full rounded-md border border-input bg-background px-2`,value:me(b.value.lead.key),onChange:n[7]||=e=>w(b.value.lead.key,e.target.value||void 0)},[n[19]||=W(`option`,{value:``},`Default`,-1),(R(!0),G(H,null,K(b.value.lead.options,e=>(R(),G(`option`,{key:e,value:e},V(e),9,XH))),128))],40,YH)):b.value.lead.kind===`text`?(R(),q(z(Bl),{key:2,"model-value":me(b.value.lead.key),class:`min-h-40 text-[13px] leading-relaxed`,onFocus:n[8]||=e=>ce.value=b.value.lead.key,"onUpdate:modelValue":n[9]||=e=>w(b.value.lead.key,String(e))},null,8,[`model-value`])):(R(),q(z(O),{key:3,"model-value":me(b.value.lead.key),onFocus:n[10]||=e=>ce.value=b.value.lead.key,"onUpdate:modelValue":n[11]||=e=>w(b.value.lead.key,String(e))},null,8,[`model-value`])),h.value.length&&b.value.lead.kind!==`select`?(R(),G(`div`,ZH,[n[20]||=W(`span`,{class:`text-[11px] text-fg-subtle`},`Insert`,-1),(R(!0),G(H,null,K(h.value,e=>(R(),G(H,{key:e},[W(`button`,{type:`button`,class:`rounded-full border border-border px-2 py-0.5 font-mono text-[11px] hover:border-primary hover:text-primary`,onClick:t=>le(e,`summary`)},V(e),9,QH),W(`button`,{type:`button`,class:`rounded-full border border-border px-2 py-0.5 font-mono text-[11px] hover:border-primary hover:text-primary`,onClick:t=>le(e,`result`)},V(e)+`.result`,9,$H)],64))),128))])):L(``,!0)])):L(``,!0),b.value.compact.length?(R(),G(`section`,eU,[(R(!0),G(H,null,K(b.value.compact,t=>(R(),G(`div`,{key:t.key,class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},[W(`span`,{class:`flex flex-1 items-center gap-1 text-[13px]`,title:t.schema.description},[A(V(pe(t.key,t.schema))+` `,1),t.schema.description?(R(),q(z(an),{key:0,class:`size-3 text-fg-subtle`})):L(``,!0)],8,tU),t.kind===`workflow`?(R(),q(pH,{key:0,class:`max-w-48`,value:me(t.key),workflows:e.workflows,label:pe(t.key,t.schema),onPick:e=>T(t.key,e)},null,8,[`value`,`workflows`,`label`,`onPicLine truncated
`):``,class:`min-h-16 font-mono text-xs`,placeholder:`One per line`,"onUpdate:modelValue":t=>w(e.key,String(t).split(`
`).filter(Boolean))},null,8,[`model-value`,`onUpdate:modelValue`])):(R(),G(H,{key:2},[M(z(zl),{"model-value":fe(m.value[e.key]),class:`min-h-24 font-mono text-xs`,placeholder:`YAML`,onChange:t=>de(e.key,t.target.value)},null,8,[`model-value`,`onChange`]),ue.value[e.key]?(R(),G(`span`,vU,V(ue.value[e.key]),1)):L(``,!0)],64))]))),128)),W(`section`,yU,[n[33]||=W(`div`,{class:`text-xs font-medium text-muted-foreground`},`Flow`,-1),W(`div`,bU,[W(`label`,xU,[n[28]||=W(`span`,{class:`flex-1 text-[13px]`},`Run only when`,-1),W(`input`,{class:`h-7 w-48 rounded-md border border-input bg-background px-2 font-mono text-xs`,placeholder:`always`,value:i.value.when??``,onInput:n[12]||=e=>S(`when`,e.target.value)},null,40,SU)]),W(`label`,CU,[n[30]||=W(`span`,{class:`flex-1 text-[13px]`},`If it fails`,-1),W(`select`,{class:`h-7 rounded-md border border-input bg-background px-1.5 text-[13px]`,value:i.value.on_failure??``,onChange:n[13]||=e=>S(`on_failure`,e.target.value||void 0)},[...n[29]||=[W(`option`,{value:``},`Park the task`,-1),W(`option`,{value:`continue`},`Continue`,-1)]],40,wU)]),W(`label`,TU,[n[31]||=W(`span`,{class:`flex-1 text-[13px]`},`Attempts`,-1),W(`input`,{type:`number`,min:`1`,max:`10`,placeholder:`1`,class:`h-7 w-20 rounded-md border border-input bg-background px-2 text-right text-[13px]`,value:i.value.retry?.attempts??``,onInput:n[14]||=e=>C({attempts:e.target.value===``?void 0:Number(e.target.value)})},null,40,EU)]),W(`label`,DU,[n[32]||=W(`span`,{class:`flex-1 text-[13px]`},`Retry backoff`,-1),M(z(wm),{"model-value":i.value.retry?.backoff??``,units:[`s`,`m`,`h`],"onUpdate:modelValue":n[15]||=e=>C({backoff:e||void 0})},null,8,[`model-value`])])])])]),W(`footer`,OU,[M(z(Z),{type:`button`,variant:`ghost`,size:`sm`,class:`text-danger`,onClick:n[16]||=e=>r(`remove`)},{default:j(()=>[M(z(Rn)),n[34]||=A(`Delete step`,-1)]),_:1}),M(z(Z),{type:`button`,size:`sm`,class:`ml-auto`,onClick:n[17]||=e=>r(`close`)},{default:j(()=>[...n[35]||=[A(`Done`,-1)]]),_:1})])]))}}),AU=`repository_path`;function jU(e,t,n){let r=[];for(let[n,i]of e){let e=t[n];e?.from===`path`&&e.path.trim()&&r.push({name:n,path:e.path.trim(),type:i.type??`string`,required:i.required===!0})}return n.trim()&&r.push({name:AU,path:n.trim(),type:`string`,required:!0}),r}function MU(e){return Array.isArray(e)?`array`:e===null?`null`:typeof e==`boolean`?`bool`:typeof e==`object`?`object`:typeof e}function NU(e,t,n){let r=[];for(let[i,a]of e){let e=t[i],o=a.type??`string`;if(!(e&&(e.from===`path`?e.path.trim():e.value!==``))){a.required&&r.push(`${i} is required`);continue}if(e.from===`path`){let e=n?.failures?.find(e=>e.field_name===i);e&&r.push(`${i}: ${e.reason}`);continue}let s=MU(ky(e.value,o));o!==`any`&&s!==o&&r.push(`${i} is ${o}, but ${JSON.stringify(e.value)} is not`)}return n?.failures?.some(e=>e.field_name===`repository_path`)&&r.push(`the repository path does not resolve`),r}function PU(e,t){let n={};for(let[r,i]of e){let e=t[r];e?.from===`path`&&e.path.trim()?n[r]={param:r}:e?.from===`value`&&e.value!==``&&(n[r]={value:ky(e.value,i.type??`string`)})}return n}function FU(e,t){let n=e=>t.find(t=>t.name===e)?.path??``,r={};for(let[t,i]of Object.entries(e.inputs??{}))r[t]=i.param?{from:`path`,path:n(i.param),value:``}:{from:`value`,path:``,value:typeof i.value==`string`?i.value:JSON.stringify(i.value)};return{rows:r,repositoryPath:n(e.repo_param)}}function IU(e,t=``){return Array.isArray(e)?e.slice(0,3).flatMap((e,n)=>{let r=`${t}[${n}]`;return[r,...IU(e,r)]}):e&&typeof e==`object`?Object.entries(e).flatMap(([e,n])=>{let r=t?`${t}.${e}`:e;return[r,...IU(n,r)]}):[]}function LU(e){try{return e?.body?JSON.parse(e.body):null}catch{return null}}function RU(e){try{let t=JSON.parse(e.headers??`{}`);return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Array.isArray(t)?t.join(`, `):String(t)]))}catch{return{}}}function zU(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>80?`${t.slice(0,80)}…`:t}var BU={class:`flex h-full flex-col`},VU={class:`flex items-center gap-2 border-b border-border px-4 py-3`},HU={class:`min-w-0 flex-1 truncate text-sm font-medium`},UU={key:0,class:`flex flex-1 items-center justify-center`},WU={class:`space-y-1.5`},GU=[`disabled`],KU=[`value`],qU={key:1,class:`space-y-1.5`},JU=[`value`],YU=[`title`],XU={class:`space-y-1.5`},ZU={id:`bind-paths`},QU=[`value`],$U={class:`divide-y divide-border rounded-md border border-border`},eW={class:`flex items-center gap-1.5 text-xs`},tW={class:`font-mono`},nW={class:`text-fg-subtle`},rW={key:0,class:`text-danger`,title:`Required`},iW=[`title`,`aria-label`,`onClick`],aW=[`onUpdate:modelValue`,`aria-label`],oW=[`onUpdate:modelValue`,`aria-label`],sW={key:2,class:`text-xs text-danger`},cW=[`title`],lW={key:0,class:`space-y-1 px-3 py-2`},uW={key:0,class:`text-xs text-danger`},dW={key:1,class:`truncate font-mono text-xs text-success`},fW={key:1,class:`px-3 py-2 text-xs text-fg-subtle`},pW={class:`space-y-2`},mW={key:0,role:`alert`,class:`text-xs text-danger`},hW={key:1,clas Line truncated
`).filter(Boolean))},null,8,[`model-value`,`onUpdate:modelValue`])):(R(),G(H,{key:2},[M(z(Bl),{"model-value":fe(m.value[e.key]),class:`min-h-24 font-mono text-xs`,placeholder:`YAML`,onChange:t=>de(e.key,t.target.value)},null,8,[`model-value`,`onChange`]),ue.value[e.key]?(R(),G(`span`,xU,V(ue.value[e.key]),1)):L(``,!0)],64))]))),128)),W(`section`,SU,[n[33]||=W(`div`,{class:`text-xs font-medium text-muted-foreground`},`Flow`,-1),W(`div`,CU,[W(`label`,wU,[n[28]||=W(`span`,{class:`flex-1 text-[13px]`},`Run only when`,-1),W(`input`,{class:`h-7 w-48 rounded-md border border-input bg-background px-2 font-mono text-xs`,placeholder:`always`,value:i.value.when??``,onInput:n[12]||=e=>S(`when`,e.target.value)},null,40,TU)]),W(`label`,EU,[n[30]||=W(`span`,{class:`flex-1 text-[13px]`},`If it fails`,-1),W(`select`,{class:`h-7 rounded-md border border-input bg-background px-1.5 text-[13px]`,value:i.value.on_failure??``,onChange:n[13]||=e=>S(`on_failure`,e.target.value||void 0)},[...n[29]||=[W(`option`,{value:``},`Park the task`,-1),W(`option`,{value:`continue`},`Continue`,-1)]],40,DU)]),W(`label`,OU,[n[31]||=W(`span`,{class:`flex-1 text-[13px]`},`Attempts`,-1),W(`input`,{type:`number`,min:`1`,max:`10`,placeholder:`1`,class:`h-7 w-20 rounded-md border border-input bg-background px-2 text-right text-[13px]`,value:i.value.retry?.attempts??``,onInput:n[14]||=e=>C({attempts:e.target.value===``?void 0:Number(e.target.value)})},null,40,kU)]),W(`label`,AU,[n[32]||=W(`span`,{class:`flex-1 text-[13px]`},`Retry backoff`,-1),M(z(Tm),{"model-value":i.value.retry?.backoff??``,units:[`s`,`m`,`h`],"onUpdate:modelValue":n[15]||=e=>C({backoff:e||void 0})},null,8,[`model-value`])])])])]),W(`footer`,jU,[M(z(Z),{type:`button`,variant:`ghost`,size:`sm`,class:`text-danger`,onClick:n[16]||=e=>r(`remove`)},{default:j(()=>[M(z(zn)),n[34]||=A(`Delete step`,-1)]),_:1}),M(z(Z),{type:`button`,size:`sm`,class:`ml-auto`,onClick:n[17]||=e=>r(`close`)},{default:j(()=>[...n[35]||=[A(`Done`,-1)]]),_:1})])]))}}),NU=`repository_path`;function PU(e,t,n){let r=[];for(let[n,i]of e){let e=t[n];e?.from===`path`&&e.path.trim()&&r.push({name:n,path:e.path.trim(),type:i.type??`string`,required:i.required===!0})}return n.trim()&&r.push({name:NU,path:n.trim(),type:`string`,required:!0}),r}function FU(e){return Array.isArray(e)?`array`:e===null?`null`:typeof e==`boolean`?`bool`:typeof e==`object`?`object`:typeof e}function IU(e,t,n){let r=[];for(let[i,a]of e){let e=t[i],o=a.type??`string`;if(!(e&&(e.from===`path`?e.path.trim():e.value!==``))){a.required&&r.push(`${i} is required`);continue}if(e.from===`path`){let e=n?.failures?.find(e=>e.field_name===i);e&&r.push(`${i}: ${e.reason}`);continue}let s=FU(Ay(e.value,o));o!==`any`&&s!==o&&r.push(`${i} is ${o}, but ${JSON.stringify(e.value)} is not`)}return n?.failures?.some(e=>e.field_name===`repository_path`)&&r.push(`the repository path does not resolve`),r}function LU(e,t){let n={};for(let[r,i]of e){let e=t[r];e?.from===`path`&&e.path.trim()?n[r]={param:r}:e?.from===`value`&&e.value!==``&&(n[r]={value:Ay(e.value,i.type??`string`)})}return n}function RU(e,t){let n=e=>t.find(t=>t.name===e)?.path??``,r={};for(let[t,i]of Object.entries(e.inputs??{}))r[t]=i.param?{from:`path`,path:n(i.param),value:``}:{from:`value`,path:``,value:typeof i.value==`string`?i.value:JSON.stringify(i.value)};return{rows:r,repositoryPath:n(e.repo_param)}}function zU(e,t=``){return Array.isArray(e)?e.slice(0,3).flatMap((e,n)=>{let r=`${t}[${n}]`;return[r,...zU(e,r)]}):e&&typeof e==`object`?Object.entries(e).flatMap(([e,n])=>{let r=t?`${t}.${e}`:e;return[r,...zU(n,r)]}):[]}function BU(e){try{return e?.body?JSON.parse(e.body):null}catch{return null}}function VU(e){try{let t=JSON.parse(e.headers??`{}`);return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Array.isArray(t)?t.join(`, `):String(t)]))}catch{return{}}}function HU(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>80?`${t.slice(0,80)}…`:t}var UU={class:`flex h-full flex-col`},WU={class:`flex items-center gap-2 border-b border-border px-4 py-3`},GU={class:`min-w-0 flex-1 truncate text-sm font-medium`},KU={key:0,class:`flex flex-1 items-center justify-center`},qU={class:`space-y-1.5`},JU=[`disabled`],YU=[`value`],XU={key:1,class:`space-y-1.5`},ZU=[`value`],QU=[`title`],$U={class:`space-y-1.5`},eW={id:`bind-paths`},tW=[`value`],nW={class:`divide-y divide-border rounded-md border border-border`},rW={class:`flex items-center gap-1.5 text-xs`},iW={class:`font-mono`},aW={class:`text-fg-subtle`},oW={key:0,class:`text-danger`,title:`Required`},sW=[`title`,`aria-label`,`onClick`],cW=[`onUpdate:modelValue`,`aria-label`],lW=[`onUpdate:modelValue`,`aria-label`],uW={key:2,class:`text-xs text-danger`},dW=[`title`],fW={key:0,class:`space-y-1 px-3 py-2`},pW={key:0,class:`text-xs text-danger`},mW={key:1,class:`truncate font-mono text-xs text-success`},hW={key:1,class:`px-3 py-2 text-xs text-fg-subtle`},gW={class:`space-y-2`},_W={key:0,role:`alert`,class:`text-xs text-danger`},vW={key:1,clas Line truncated
`).replace(`
`,`
+`).split(`
`).map(e=>e.trim().toLowerCase());if(i.length===1)return e.toLowerCase()===t.toLowerCase();r||n.add(e.toLowerCase());let a=i.every((e,t)=>n.has(e)&&Array.from(n.values())[t]===i[t]);return r&&n.delete(e.toLowerCase()),a}function oQ(e,t){return n=>{if(!n.code&&!n.key)return!1;let r=sQ(n.code,e);return Array.isArray(e)?e.some(e=>aQ(n[r],e,t,n.type===`keyup`)):aQ(n[r],e,t,n.type===`keyup`)}}function sQ(e,t){return t.includes(e)?`code`:`key`}function cQ(e,t){let n=I(()=>ze(t?.target)??nQ),r=qe(ze(e)===!0),i=!1,a=new Set,o=c(ze(e));F(()=>ze(e),(e,t)=>{typeof t==`boolean`&&typeof e!=`boolean`&&s(),o=c(e)},{immediate:!0}),eK([`blur`,`contextmenu`],s),nK((...e)=>o(...e),e=>{let n=ze(t?.actInsideInputWithModifier)??!0,a=ze(t?.preventDefault)??!1;if(i=iQ(e),(!i||i&&!n)&&rQ(e))return;let o=e.composedPath?.call(e)?.[0]||e.target,s=o?.nodeName===`BUTTON`||o?.nodeName===`A`;!a&&(i||!s)&&e.preventDefault(),r.value=!0},{eventName:`keydown`,target:n}),nK((...e)=>o(...e),e=>{let n=ze(t?.actInsideInputWithModifier)??!0;if(r.value){if((!i||i&&!n)&&rQ(e))return;i=!1,r.value=!1}},{eventName:`keyup`,target:n});function s(){i=!1,a.clear(),r.value=ze(e)===!0}function c(e){return e===null?(s(),()=>!1):typeof e==`boolean`?(s(),r.value=e,()=>!1):Array.isArray(e)||typeof e==`string`?oQ(e,a):e}return r}var lQ=`vue-flow__node-desc`,uQ=`vue-flow__edge-desc`,dQ=`vue-flow__aria-live`,fQ=[`Enter`,` `,`Escape`],pQ={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};function mQ(e){return{...e.computedPosition||{x:0,y:0},width:e.dimensions.width||0,height:e.dimensions.height||0}}function hQ(e,t){let n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)}function gQ(e){return{width:e.offsetWidth,height:e.offsetHeight}}function _Q(e,t=0,n=1){return Math.min(Math.max(e,t),n)}function vQ(e,t){return{x:_Q(e.x,t[0][0],t[1][0]),y:_Q(e.y,t[0][1],t[1][1])}}function yQ(e){let t=e.getRootNode();return`elementFromPoint`in t?t:window.document}function bQ(e){return e&&typeof e==`object`&&`id`in e&&`source`in e&&`target`in e}function xQ(e){return e&&typeof e==`object`&&`id`in e&&`position`in e&&!bQ(e)}function SQ(e){return xQ(e)&&`computedPosition`in e}function CQ(e){return!Number.isNaN(e)&&Number.isFinite(e)}function wQ(e){return CQ(e.width)&&CQ(e.height)&&CQ(e.x)&&CQ(e.y)}function TQ(e,t,n){let r={id:e.id.toString(),type:e.type??`default`,dimensions:mt({width:0,height:0}),computedPosition:mt({z:0,...e.position}),handleBounds:{source:[],target:[]},draggable:void 0,selectable:void 0,connectable:void 0,focusable:void 0,selected:!1,dragging:!1,resizing:!1,initialized:!1,isParent:!1,position:{x:0,y:0},data:H$(e.data)?e.data:{},events:mt(H$(e.events)?e.events:{})};return Object.assign(t??r,e,{id:e.id.toString(),parentNode:n})}function EQ(e,t,n){let r={id:e.id.toString(),type:e.type??t?.type??`default`,source:e.source.toString(),target:e.target.toString(),sourceHandle:e.sourceHandle?.toString(),targetHandle:e.targetHandle?.toString(),updatable:e.updatable??n?.updatable,selectable:e.selectable??n?.selectable,focusable:e.focusable??n?.focusable,data:H$(e.data)?e.data:{},events:mt(H$(e.events)?e.events:{}),label:e.label??``,interactionWidth:e.interactionWidth??n?.interactionWidth,...n??{}};return Object.assign(t??r,e,{id:e.id.toString()})}function DQ(e,t,n,r){let i=typeof e==`string`?e:e.id,a=new Set,o=r===`source`?`target`:`source`;for(let e of n)e[o]===i&&a.add(e[r]);return t.filter(e=>a.has(e.id))}function OQ(...e){if(e.length===3){let[t,n,r]=e;return DQ(t,n,r,`target`)}let[t,n]=e,r=typeof t==`string`?t:t.id;return n.filter(e=>bQ(e)&&e.source===r).map(e=>n.find(t=>xQ(t)&&t.id===e.target))}function kQ(...e){if(e.length===3){let[t,n,r]=e;return DQ(t,n,r,`source`)}let[t,n]=e,r=typeof t==`string`?t:t.id;return n.filter(e=>bQ(e)&&e.target===r).map(e=>n.find(t=>xQ(t)&&t.id===e.source))}function AQ({source:e,sourceHandle:t,target:n,targetHandle:r}){return`vueflow__edge-${e}${t??``}-${n}${r??``}`}function jQ(e,t){return t.some(t=>bQ(t)&&t.source===e.source&&t.target===e.target&&(t.sourceHandle===e.sourceHandle||!t.sourceHandle&&!e.sourceHandle)&&(t.targetHandle===e.targetHandle||!t.targetHandle&&!e.targetHandle))}function MQ({x:e,y:t},{x:n,y:r,zoom:i}){return{x:e*i+n,y:t*i+r}}function NQ({x:e,y:t},{x:n,y:r,zoom:i},a=!1,o=[1,1]){let s={x:(e-n)/i,y:(t-r)/i};return a?T$(s,o):s}function PQ(e,t){return{x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}}function FQ({x:e,y:t,width:n,height:r}){return{x:e,y:t,x2:e+n,y2:t+r}}function IQ({x:e,y:t,x2:n,y2:r}){return{x:e,y:t,width:n-e,height:r-t}}function LQ(e){let t={x:1/0,y:1/0,x2:-1/0,y2:-1/0};for(let n=0;n<e.length;n++){let r=e[n];t=PQ(t,FQ({...r.computedPosition,...r.dimensions}))}return IQ(t)}function RQ(e,t,n={x:0,y:0,zoom:1},r=!1,i=!1){let a={...NQ(t,n),width:t.width/n.zoom,height:t.height/n.zoom},o=[];for(let t of e){let{dimensions:e,selectable:n=!0,hidden:s= Line truncated
`).map(e=>e.trim().toLowerCase());if(i.length===1)return e.toLowerCase()===t.toLowerCase();r||n.add(e.toLowerCase());let a=i.every((e,t)=>n.has(e)&&Array.from(n.values())[t]===i[t]);return r&&n.delete(e.toLowerCase()),a}function lQ(e,t){return n=>{if(!n.code&&!n.key)return!1;let r=uQ(n.code,e);return Array.isArray(e)?e.some(e=>cQ(n[r],e,t,n.type===`keyup`)):cQ(n[r],e,t,n.type===`keyup`)}}function uQ(e,t){return t.includes(e)?`code`:`key`}function dQ(e,t){let n=I(()=>ze(t?.target)??aQ),r=qe(ze(e)===!0),i=!1,a=new Set,o=c(ze(e));F(()=>ze(e),(e,t)=>{typeof t==`boolean`&&typeof e!=`boolean`&&s(),o=c(e)},{immediate:!0}),rK([`blur`,`contextmenu`],s),aK((...e)=>o(...e),e=>{let n=ze(t?.actInsideInputWithModifier)??!0,a=ze(t?.preventDefault)??!1;if(i=sQ(e),(!i||i&&!n)&&oQ(e))return;let o=e.composedPath?.call(e)?.[0]||e.target,s=o?.nodeName===`BUTTON`||o?.nodeName===`A`;!a&&(i||!s)&&e.preventDefault(),r.value=!0},{eventName:`keydown`,target:n}),aK((...e)=>o(...e),e=>{let n=ze(t?.actInsideInputWithModifier)??!0;if(r.value){if((!i||i&&!n)&&oQ(e))return;i=!1,r.value=!1}},{eventName:`keyup`,target:n});function s(){i=!1,a.clear(),r.value=ze(e)===!0}function c(e){return e===null?(s(),()=>!1):typeof e==`boolean`?(s(),r.value=e,()=>!1):Array.isArray(e)||typeof e==`string`?lQ(e,a):e}return r}var fQ=`vue-flow__node-desc`,pQ=`vue-flow__edge-desc`,mQ=`vue-flow__aria-live`,hQ=[`Enter`,` `,`Escape`],gQ={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};function _Q(e){return{...e.computedPosition||{x:0,y:0},width:e.dimensions.width||0,height:e.dimensions.height||0}}function vQ(e,t){let n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)}function yQ(e){return{width:e.offsetWidth,height:e.offsetHeight}}function bQ(e,t=0,n=1){return Math.min(Math.max(e,t),n)}function xQ(e,t){return{x:bQ(e.x,t[0][0],t[1][0]),y:bQ(e.y,t[0][1],t[1][1])}}function SQ(e){let t=e.getRootNode();return`elementFromPoint`in t?t:window.document}function CQ(e){return e&&typeof e==`object`&&`id`in e&&`source`in e&&`target`in e}function wQ(e){return e&&typeof e==`object`&&`id`in e&&`position`in e&&!CQ(e)}function TQ(e){return wQ(e)&&`computedPosition`in e}function EQ(e){return!Number.isNaN(e)&&Number.isFinite(e)}function DQ(e){return EQ(e.width)&&EQ(e.height)&&EQ(e.x)&&EQ(e.y)}function OQ(e,t,n){let r={id:e.id.toString(),type:e.type??`default`,dimensions:mt({width:0,height:0}),computedPosition:mt({z:0,...e.position}),handleBounds:{source:[],target:[]},draggable:void 0,selectable:void 0,connectable:void 0,focusable:void 0,selected:!1,dragging:!1,resizing:!1,initialized:!1,isParent:!1,position:{x:0,y:0},data:G$(e.data)?e.data:{},events:mt(G$(e.events)?e.events:{})};return Object.assign(t??r,e,{id:e.id.toString(),parentNode:n})}function kQ(e,t,n){let r={id:e.id.toString(),type:e.type??t?.type??`default`,source:e.source.toString(),target:e.target.toString(),sourceHandle:e.sourceHandle?.toString(),targetHandle:e.targetHandle?.toString(),updatable:e.updatable??n?.updatable,selectable:e.selectable??n?.selectable,focusable:e.focusable??n?.focusable,data:G$(e.data)?e.data:{},events:mt(G$(e.events)?e.events:{}),label:e.label??``,interactionWidth:e.interactionWidth??n?.interactionWidth,...n??{}};return Object.assign(t??r,e,{id:e.id.toString()})}function AQ(e,t,n,r){let i=typeof e==`string`?e:e.id,a=new Set,o=r===`source`?`target`:`source`;for(let e of n)e[o]===i&&a.add(e[r]);return t.filter(e=>a.has(e.id))}function jQ(...e){if(e.length===3){let[t,n,r]=e;return AQ(t,n,r,`target`)}let[t,n]=e,r=typeof t==`string`?t:t.id;return n.filter(e=>CQ(e)&&e.source===r).map(e=>n.find(t=>wQ(t)&&t.id===e.target))}function MQ(...e){if(e.length===3){let[t,n,r]=e;return AQ(t,n,r,`source`)}let[t,n]=e,r=typeof t==`string`?t:t.id;return n.filter(e=>CQ(e)&&e.target===r).map(e=>n.find(t=>wQ(t)&&t.id===e.source))}function NQ({source:e,sourceHandle:t,target:n,targetHandle:r}){return`vueflow__edge-${e}${t??``}-${n}${r??``}`}function PQ(e,t){return t.some(t=>CQ(t)&&t.source===e.source&&t.target===e.target&&(t.sourceHandle===e.sourceHandle||!t.sourceHandle&&!e.sourceHandle)&&(t.targetHandle===e.targetHandle||!t.targetHandle&&!e.targetHandle))}function FQ({x:e,y:t},{x:n,y:r,zoom:i}){return{x:e*i+n,y:t*i+r}}function IQ({x:e,y:t},{x:n,y:r,zoom:i},a=!1,o=[1,1]){let s={x:(e-n)/i,y:(t-r)/i};return a?O$(s,o):s}function LQ(e,t){return{x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}}function RQ({x:e,y:t,width:n,height:r}){return{x:e,y:t,x2:e+n,y2:t+r}}function zQ({x:e,y:t,x2:n,y2:r}){return{x:e,y:t,width:n-e,height:r-t}}function BQ(e){let t={x:1/0,y:1/0,x2:-1/0,y2:-1/0};for(let n=0;n<e.length;n++){let r=e[n];t=LQ(t,RQ({...r.computedPosition,...r.dimensions}))}return zQ(t)}function VQ(e,t,n={x:0,y:0,zoom:1},r=!1,i=!1){let a={...IQ(t,n),width:t.width/n.zoom,height:t.height/n.zoom},o=[];for(let t of e){let{dimensions:e,selectable:n=!0,hidden:s= Line truncated
Node: ${e}`,NODE_NOT_FOUND:e=>`Node not found
Node: ${e}`,NODE_MISSING_PARENT:(e,t)=>`Node is missing a parent
Node: ${e}
@@ -147,4 +147,4 @@ Edge: ${e}
Source: ${t}
Target: ${n}`,EDGE_ORPHANED:e=>`Edge was orphaned (suddenly missing source or target) and has been removed
Edge: ${e}`,EDGE_NOT_FOUND:e=>`Edge not found
Edge: ${e}`,USEVUEFLOW_OPTIONS:()=>`The options parameter is deprecated and will be removed in the next major version. Please use the id parameter instead`},y$=class extends Error{constructor(e,...t){super(v$[e]?.call(v$,...t)),this.name=`VueFlowError`,this.code=e,this.args=t}};function b$(e){return`clientX`in e}function x$(e){return`sourceEvent`in e}function S$(e,t){let n=b$(e),r,i;return n?(r=e.clientX,i=e.clientY):`touches`in e&&e.touches.length>0?(r=e.touches[0].clientX,i=e.touches[0].clientY):`changedTouches`in e&&e.changedTouches.length>0?(r=e.changedTouches[0].clientX,i=e.changedTouches[0].clientY):(r=0,i=0),{x:r-(t?.left??0),y:i-(t?.top??0)}}var C$=()=>typeof navigator<`u`&&(navigator==null?void 0:navigator.userAgent)?.indexOf(`Mac`)>=0;function w$(e){return{width:e.dimensions?.width??e.width??0,height:e.dimensions?.height??e.height??0}}function T$(e,t=[1,1]){return{x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}}var E$=()=>!0;function D$(e){e?.classList.remove(`valid`,`connecting`,`vue-flow__handle-valid`,`vue-flow__handle-connecting`)}function O$(e,t,n){let r=[],i={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(let e of t.values())hQ(i,mQ(e))>0&&r.push(e);return r}var k$=250;function A$(e,t,n,r){let i=[],a=1/0,o=O$(e,n,t+k$);for(let n of o){let o=[...n.handleBounds?.source??[],...n.handleBounds?.target??[]];for(let s of o){if(r.nodeId===s.nodeId&&r.type===s.type&&r.id===s.id)continue;let{x:o,y:c}=p$(n,s,s.position,!0),l=Math.sqrt((o-e.x)**2+(c-e.y)**2);l>t||(l<a?(i=[{...s,x:o,y:c}],a=l):l===a&&i.push({...s,x:o,y:c}))}}if(!i.length)return null;if(i.length>1){let e=r.type===`source`?`target`:`source`;return i.find(t=>t.type===e)??i[0]}return i[0]}function j$(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:i,fromType:a,doc:o,lib:s,flowId:c,isValidConnection:l=E$},u,d,f,p){let m=a===`target`,h=t?o.querySelector(`.${s}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:g,y:_}=S$(e),v=o.elementFromPoint(g,_),y=v?.classList.contains(`${s}-flow__handle`)?v:h,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){let e=M$(void 0,y),t=y.getAttribute(`data-nodeid`),a=y.getAttribute(`data-handleid`),o=y.classList.contains(`connectable`),s=y.classList.contains(`connectableend`);if(!t||!e)return b;let c={source:m?t:r,sourceHandle:m?a:i,target:m?r:t,targetHandle:m?i:a};b.connection=c,b.isValid=o&&s&&(n===ZZ.Strict?m&&e===`source`||!m&&e===`target`:t!==r||a!==i)&&l(c,{nodes:d,edges:u,sourceNode:f(c.source),targetNode:f(c.target)}),b.toHandle=F$(t,e,a,p,n,!0)}return b}function M$(e,t){return e||(t?.classList.contains(`target`)?`target`:t?.classList.contains(`source`)?`source`:null)}function N$(e,t){let n=null;return t?n=`valid`:e&&!t&&(n=`invalid`),n}function P$(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}function F$(e,t,n,r,i,a=!1){let o=r.get(e);if(!o)return null;let s=i===ZZ.Strict?o.handleBounds?.[t]:[...o.handleBounds?.source??[],...o.handleBounds?.target??[]],c=(n?s?.find(e=>e.id===n):s?.[0])??null;return c&&a?{...c,...p$(o,c,c.position,!0)}:c}var I$={[JZ.Left]:JZ.Right,[JZ.Right]:JZ.Left,[JZ.Top]:JZ.Bottom,[JZ.Bottom]:JZ.Top},L$=[`production`,`prod`];function R$(e,...t){z$()&&console.warn(`[Vue Flow]: ${e}`,...t)}function z$(){return!L$.includes(`production`)}function B$(e,t,n,r,i){let a=t.querySelectorAll(`.vue-flow__handle.${e}`);return a?.length?Array.from(a).map(t=>{let a=t.getBoundingClientRect();return{id:t.getAttribute(`data-handleid`),type:e,nodeId:i,position:t.getAttribute(`data-handlepos`),x:(a.left-n.left)/r,y:(a.top-n.top)/r,...gQ(t)}}):null}function V$(e,t,n,r,i,a=!1,o){i.value=!1,e.selected?(a||e.selected&&t)&&(r([e]),ft(()=>{o.blur()})):n([e])}function H$(e){return z(e)!==void 0}function U$(e,t,n,r){if(!e||!e.source||!e.target)return n(new y$(_$.EDGE_INVALID,e?.id??`[ID UNKNOWN]`)),!1;let i;return i=bQ(e)?e:{...e,id:AQ(e)},i=EQ(i,void 0,r),!jQ(i,t)&&i}function W$(e,t,n,r,i){if(!t.source||!t.target)return i(new y$(_$.EDGE_INVALID,e.id)),!1;if(!n)return i(new y$(_$.EDGE_NOT_FOUND,e.id)),!1;let{id:a,...o}=e;return{...o,id:r?AQ(t):a,source:t.source,target:t.target,sourceHandle:t.sourceHandle,targetHandle:t.targetHandle}}function G$(e,t,n){let r={},i=[];for(let a=0;a<e.length;++a){let o=e[a];if(!xQ(o)){n(new y$(_$.NODE_INVALID,o?.id));continue}let s=TQ(o,t(o.id),o.parentNode);o.parentNode&&(r[o.parentNode]=!0),i[a]=s}for(let e of i){let a=t(e.parentNode)||i.find(t=>t.id===e.parentNode);e.parentNode&&!a&&n(new y$(_$.NODE_MISSING_PARENT,e.id,e.parentNode)),(e.parentNode||r[e.id])&&(r[e.id]&&(e.isParent=!0),a&&(a.isParent=!0))}return i}function K$(e,t,n,r,i,a){let o=i,s=r.get(o)||new Map;r.set(o,s.set(n,t)),o=`${i}-${e}`;let c=r.get(o)||new Map;if(r.set(o,c.set(n,t)),a){o=`${i}-${e}-${a}`;let s=r.get(o)||new Map;r.set(o,s.set(n,t))}}function q$(e,t,n){e.clear();for(let t of n){let{source:n,target:r,sourceHandle:i=null,targetHandle:a=null}=t,o={edgeId:t.id,source:n,target:r,sourceHandle:i,targetHandle:a},s=`${n}-${i}--${r}-${a}`;K$(`source`,o,`${r}-${a}--Line truncated
Edge: ${e}`,USEVUEFLOW_OPTIONS:()=>`The options parameter is deprecated and will be removed in the next major version. Please use the id parameter instead`},S$=class extends Error{constructor(e,...t){super(x$[e]?.call(x$,...t)),this.name=`VueFlowError`,this.code=e,this.args=t}};function C$(e){return`clientX`in e}function w$(e){return`sourceEvent`in e}function T$(e,t){let n=C$(e),r,i;return n?(r=e.clientX,i=e.clientY):`touches`in e&&e.touches.length>0?(r=e.touches[0].clientX,i=e.touches[0].clientY):`changedTouches`in e&&e.changedTouches.length>0?(r=e.changedTouches[0].clientX,i=e.changedTouches[0].clientY):(r=0,i=0),{x:r-(t?.left??0),y:i-(t?.top??0)}}var E$=()=>typeof navigator<`u`&&(navigator==null?void 0:navigator.userAgent)?.indexOf(`Mac`)>=0;function D$(e){return{width:e.dimensions?.width??e.width??0,height:e.dimensions?.height??e.height??0}}function O$(e,t=[1,1]){return{x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}}var k$=()=>!0;function A$(e){e?.classList.remove(`valid`,`connecting`,`vue-flow__handle-valid`,`vue-flow__handle-connecting`)}function j$(e,t,n){let r=[],i={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(let e of t.values())vQ(i,_Q(e))>0&&r.push(e);return r}var M$=250;function N$(e,t,n,r){let i=[],a=1/0,o=j$(e,n,t+M$);for(let n of o){let o=[...n.handleBounds?.source??[],...n.handleBounds?.target??[]];for(let s of o){if(r.nodeId===s.nodeId&&r.type===s.type&&r.id===s.id)continue;let{x:o,y:c}=g$(n,s,s.position,!0),l=Math.sqrt((o-e.x)**2+(c-e.y)**2);l>t||(l<a?(i=[{...s,x:o,y:c}],a=l):l===a&&i.push({...s,x:o,y:c}))}}if(!i.length)return null;if(i.length>1){let e=r.type===`source`?`target`:`source`;return i.find(t=>t.type===e)??i[0]}return i[0]}function P$(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:i,fromType:a,doc:o,lib:s,flowId:c,isValidConnection:l=k$},u,d,f,p){let m=a===`target`,h=t?o.querySelector(`.${s}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:g,y:_}=T$(e),v=o.elementFromPoint(g,_),y=v?.classList.contains(`${s}-flow__handle`)?v:h,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){let e=F$(void 0,y),t=y.getAttribute(`data-nodeid`),a=y.getAttribute(`data-handleid`),o=y.classList.contains(`connectable`),s=y.classList.contains(`connectableend`);if(!t||!e)return b;let c={source:m?t:r,sourceHandle:m?a:i,target:m?r:t,targetHandle:m?i:a};b.connection=c,b.isValid=o&&s&&(n===eQ.Strict?m&&e===`source`||!m&&e===`target`:t!==r||a!==i)&&l(c,{nodes:d,edges:u,sourceNode:f(c.source),targetNode:f(c.target)}),b.toHandle=R$(t,e,a,p,n,!0)}return b}function F$(e,t){return e||(t?.classList.contains(`target`)?`target`:t?.classList.contains(`source`)?`source`:null)}function I$(e,t){let n=null;return t?n=`valid`:e&&!t&&(n=`invalid`),n}function L$(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}function R$(e,t,n,r,i,a=!1){let o=r.get(e);if(!o)return null;let s=i===eQ.Strict?o.handleBounds?.[t]:[...o.handleBounds?.source??[],...o.handleBounds?.target??[]],c=(n?s?.find(e=>e.id===n):s?.[0])??null;return c&&a?{...c,...g$(o,c,c.position,!0)}:c}var z$={[ZZ.Left]:ZZ.Right,[ZZ.Right]:ZZ.Left,[ZZ.Top]:ZZ.Bottom,[ZZ.Bottom]:ZZ.Top},B$=[`production`,`prod`];function V$(e,...t){H$()&&console.warn(`[Vue Flow]: ${e}`,...t)}function H$(){return!B$.includes(`production`)}function U$(e,t,n,r,i){let a=t.querySelectorAll(`.vue-flow__handle.${e}`);return a?.length?Array.from(a).map(t=>{let a=t.getBoundingClientRect();return{id:t.getAttribute(`data-handleid`),type:e,nodeId:i,position:t.getAttribute(`data-handlepos`),x:(a.left-n.left)/r,y:(a.top-n.top)/r,...yQ(t)}}):null}function W$(e,t,n,r,i,a=!1,o){i.value=!1,e.selected?(a||e.selected&&t)&&(r([e]),ft(()=>{o.blur()})):n([e])}function G$(e){return z(e)!==void 0}function K$(e,t,n,r){if(!e||!e.source||!e.target)return n(new S$(b$.EDGE_INVALID,e?.id??`[ID UNKNOWN]`)),!1;let i;return i=CQ(e)?e:{...e,id:NQ(e)},i=kQ(i,void 0,r),!PQ(i,t)&&i}function q$(e,t,n,r,i){if(!t.source||!t.target)return i(new S$(b$.EDGE_INVALID,e.id)),!1;if(!n)return i(new S$(b$.EDGE_NOT_FOUND,e.id)),!1;let{id:a,...o}=e;return{...o,id:r?NQ(t):a,source:t.source,target:t.target,sourceHandle:t.sourceHandle,targetHandle:t.targetHandle}}function J$(e,t,n){let r={},i=[];for(let a=0;a<e.length;++a){let o=e[a];if(!wQ(o)){n(new S$(b$.NODE_INVALID,o?.id));continue}let s=OQ(o,t(o.id),o.parentNode);o.parentNode&&(r[o.parentNode]=!0),i[a]=s}for(let e of i){let a=t(e.parentNode)||i.find(t=>t.id===e.parentNode);e.parentNode&&!a&&n(new S$(b$.NODE_MISSING_PARENT,e.id,e.parentNode)),(e.parentNode||r[e.id])&&(r[e.id]&&(e.isParent=!0),a&&(a.isParent=!0))}return i}function Y$(e,t,n,r,i,a){let o=i,s=r.get(o)||new Map;r.set(o,s.set(n,t)),o=`${i}-${e}`;let c=r.get(o)||new Map;if(r.set(o,c.set(n,t)),a){o=`${i}-${e}-${a}`;let s=r.get(o)||new Map;r.set(o,s.set(n,t))}}function X$(e,t,n){e.clear();for(let t of n){let{source:n,target:r,sourceHandle:i=null,targetHandle:a=null}=t,o={edgeId:t.id,source:n,target:r,sourceHandle:i,targetHandle:a},s=`${n}-${i}--${r}-${a}`;Y$(`source`,o,`${r}-${a}--Line truncated
+99
View File
@@ -0,0 +1,99 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { storeToRefs } from "pinia";
import { Bell } from "@lucide/vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { api } from "@/lib/api";
import { useLiveUpdatesStore } from "@/stores/live-updates";
import { groupBySeverity, type AlertSeverity, type OperatorAlert } from "./alerts";
const alerts = ref<OperatorAlert[]>([]);
const failed = ref(false);
const open = ref(false);
async function load() {
try {
alerts.value = (await api.alerts<{ alerts: OperatorAlert[] }>()).alerts;
failed.value = false;
} catch {
failed.value = true;
}
}
async function dismiss(alert: OperatorAlert) {
alerts.value = alerts.value.filter((a) => a.id !== alert.id);
try {
await api.dismissAlert(alert.id);
} catch {
await load();
}
}
// The bell follows the event stream: the store records every alert change as
// an event, so the newest alert event's id moving means the list moved. A
// reconnect re-reads, since events may have been missed while it was down.
const live = useLiveUpdatesStore();
const { activity, connectionRevision } = storeToRefs(live);
watch(() => activity.value.find((event) => event.kind === "alert")?.id, load);
watch(connectionRevision, load);
onMounted(load);
const groups = computed(() => groupBySeverity(alerts.value));
const tone: Record<AlertSeverity, "danger" | "warn" | "info"> = { action: "danger", warning: "warn", info: "info" };
const label = computed(() =>
alerts.value.length === 0 ? "Alerts" : `Alerts, ${alerts.value.length} open`,
);
function failedDeliveries(alert: OperatorAlert): number {
return alert.deliveries.filter((d) => d.state === "failed").length;
}
</script>
<template>
<Popover v-model:open="open">
<PopoverTrigger as-child>
<Button variant="ghost" size="icon" class="relative" :aria-label="label">
<Bell class="size-4" aria-hidden="true" />
<Badge
v-if="alerts.length"
:variant="groups[0] ? tone[groups[0].severity] : 'info'"
class="absolute -top-1 -right-1 h-4 min-w-4 px-1 text-[11px] tabular-nums"
>
{{ alerts.length }}
</Badge>
</Button>
</PopoverTrigger>
<PopoverContent align="end" class="w-96 max-w-[calc(100vw-1.5rem)] p-0">
<p v-if="failed" class="px-3 pt-3 text-xs text-danger" role="alert">Alerts could not be loaded.</p>
<p v-else-if="!groups.length" class="px-3 py-6 text-center text-sm text-fg-subtle">Nothing needs you.</p>
<div v-else class="max-h-96 overflow-y-auto">
<section v-for="group in groups" :key="group.severity" class="border-b p-3 last:border-b-0">
<h3 class="mb-2 text-xs font-medium text-fg-subtle">{{ group.label }}</h3>
<ul class="grid gap-3">
<li v-for="alert in group.alerts" :key="alert.id" class="grid gap-1">
<div class="flex items-start justify-between gap-2">
<RouterLink v-if="alert.link" :to="alert.link" class="text-sm font-medium hover:underline" @click="open = false">
{{ alert.title }}
</RouterLink>
<span v-else class="text-sm font-medium">{{ alert.title }}</span>
<Button variant="ghost" size="sm" class="h-6 shrink-0 px-2 text-xs" @click="dismiss(alert)">
Dismiss
</Button>
</div>
<p v-if="alert.body" class="text-xs text-fg-subtle">{{ alert.body }}</p>
<p class="text-xs text-fg-subtle">
<template v-if="alert.count > 1">Seen {{ alert.count }} times. </template>
<template v-if="alert.condition">Clears when fixed; dismissing snoozes it.</template>
<template v-else>Stays until dismissed.</template>
</p>
<p v-if="failedDeliveries(alert)" class="text-xs text-warn">Webhook delivery failed.</p>
</li>
</ul>
</section>
</div>
</PopoverContent>
</Popover>
</template>
+36
View File
@@ -0,0 +1,36 @@
/** Operator alerts as the dashboard reads them: what needs a human, by severity. */
export type AlertSeverity = "action" | "warning" | "info";
export interface AlertDelivery {
event: string;
state: string;
attempts: { n: number; at: string; status_code?: number; error?: string }[];
}
export interface OperatorAlert {
id: number;
kind: string;
severity: AlertSeverity;
title: string;
body: string;
link?: string;
condition: boolean;
count: number;
last_seen: string;
deliveries: AlertDelivery[];
}
/** Most urgent first, as the list groups them. */
export const SEVERITY_GROUPS: { severity: AlertSeverity; label: string }[] = [
{ severity: "action", label: "Needs you" },
{ severity: "warning", label: "Warnings" },
{ severity: "info", label: "Info" },
];
export function groupBySeverity(alerts: readonly OperatorAlert[]) {
return SEVERITY_GROUPS.map((group) => ({
...group,
alerts: alerts.filter((alert) => alert.severity === group.severity),
})).filter((group) => group.alerts.length > 0);
}
+2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import AlertsBell from "@/alerts/AlertsBell.vue";
import NewTaskButton from "@/tasks/NewTaskButton.vue";
import Brand from "./Brand.vue";
import ConnectionPill from "./ConnectionPill.vue";
@@ -19,6 +20,7 @@ const props = defineProps<{ hidden: string[] }>();
<div class="flex shrink-0 items-center gap-2">
<SearchBar :hidden="props.hidden" />
<NewTaskButton v-if="!props.hidden.includes('/workflows')" />
<AlertsBell />
<ConnectionPill />
<SupportLink />
<ProfileDropdown />
+3
View File
@@ -191,6 +191,9 @@ export const api = {
`/api/orgs/${encodeURIComponent(id)}/agents/${encodeURIComponent(identity)}`,
{ method: "PUT" },
),
alerts: <T = unknown>() => request<T>("/api/alerts"),
dismissAlert: (id: number) =>
request<void>(`/api/alerts/${id}/dismiss`, { method: "POST", parse: false }),
summary: <T = unknown>() => request<T>("/api/summary"),
tasks: <T = unknown>() => request<T>("/api/tasks"),
// taskPage reads one page of the board; next is the cursor for the page
+21 -2
View File
@@ -3,7 +3,9 @@ import ApplyStatusRows from "./ApplyStatusRows.vue";
import { computed, onMounted } from "vue";
import { storeToRefs } from "pinia";
import { Button } from "@/components/ui/button";
import {Input} from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import PageHeader from "@/base/PageHeader.vue";
import { DurationInput, formatGoDuration, parseGoDuration } from "@/components/ui/duration-input";
import {
@@ -17,6 +19,7 @@ import { SettingRow } from "@/components/ui/setting-row";
import { resourcesForPage, useControlPlaneStore } from "@/stores/control-plane";
import DraftHint from "./DraftHint.vue";
import HistoryLink from "./HistoryLink.vue";
import SecretRefField from "./SecretRefField.vue";
const POLICY="task-policy";
const KIND = "workflow-execution-settings";
@@ -33,7 +36,7 @@ const { catalog, catalogError } = storeToRefs(store);
onMounted(store.load);
const resources = computed(() => resourcesForPage(catalog.value, "tasks"));
const policy=computed(()=>store.drafts[POLICY]?.value as {diff_cap_lines:number;notify_webhook:string}|undefined);
const policy=computed(()=>store.drafts[POLICY]?.value as {diff_cap_lines:number;notify_webhook:string;notify_min_severity:string;notify_secret:{engine:string;key:string}}|undefined);
const limits = computed(() => store.drafts[KIND]?.value as ExecutionSettings | undefined);
const error = computed(() => store.pageErrorFor(KIND));
@@ -66,9 +69,25 @@ const taskRuntime = seconds("max_task_runtime_seconds");
<SettingRow label="Maximum changed lines" hint="Applied to new tasks. 0 disables the limit." for="task-diff-cap">
<div class="flex flex-wrap items-center gap-3"><Input id="task-diff-cap" v-model.number="policy.diff_cap_lines" type="number" min="0" class="max-w-40" /><DraftHint :kind="POLICY" path="diff_cap_lines" /></div>
</SettingRow>
<SettingRow label="Notification webhook" hint="Applied to new tasks. Empty disables notifications." for="task-notify">
<SettingRow label="Alert webhook" hint="Receives each raised and resolved alert. Empty disables." for="task-notify">
<div class="flex flex-wrap items-center gap-3"><Input id="task-notify" v-model="policy.notify_webhook" type="url" class="max-w-md" /><DraftHint :kind="POLICY" path="notify_webhook" /></div>
</SettingRow>
<SettingRow label="Webhook severity" hint="The lowest severity delivered.">
<div class="flex flex-wrap items-center gap-3">
<Select :model-value="policy.notify_min_severity || 'warning'" @update:model-value="policy.notify_min_severity = String($event)">
<SelectTrigger class="w-40" aria-label="Webhook severity"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="info">Info</SelectItem>
<SelectItem value="warning">Warning</SelectItem>
<SelectItem value="action">Needs you</SelectItem>
</SelectContent>
</Select>
<DraftHint :kind="POLICY" path="notify_min_severity" />
</div>
</SettingRow>
<SettingRow label="Webhook signing secret" hint="Signs each payload in X-Archie-Signature. Not set sends unsigned.">
<div class="flex flex-wrap items-center gap-3"><SecretRefField v-if="policy.notify_secret" v-model="policy.notify_secret" id-prefix="task-notify-secret" /><Button v-else variant="outline" size="sm" @click="policy.notify_secret = { engine: '', key: '' }">Set reference</Button><DraftHint :kind="POLICY" path="notify_secret" /></div>
</SettingRow>
</template>
<template v-if="limits">
<SettingRow label="Task time limit" for="te-task" hint="Parked after this. 0 disables.">