feat(scheduling): schedules and runs in the State Store with grid timing and run history

Schedules leave the schedules control-plane resource for State Store tables
behind a ScheduleService contract. A run is claimed per schedule slot, missed
slots fire once, the next run stays on the schedule's grid, cron is read in the
schedule-settings time zone, and failed runs are recorded and advance. Three
failures in a row raise a schedule.failing alert. A fired run records a
schedule-fired capture. Run history is pruned by age and count.

Removes the chat and spawn-task runners, the dangerous-payload guard and the
old schedules settings page.
This commit is contained in:
sam committed 2026-10-26 00:49:24 +11:00
1 parent d1d6301fc2
commit cc5789eb5f
50 files changed
+4403 -1348

No files matched your search

+29 -2
View File
@@ -29,11 +29,38 @@ func (o orgAgents) act(ctx context.Context) context.Context {
return org.WithOrg(access.WithPrincipal(ctx, o.principals[0]), o.owner)
}
// orgDirectory finds every organisation and an agent principal to act as in
// each, because the control plane serves a caller only its own org.
type orgDirectory interface {
access.PrincipalSource
ListOrgs(ctx context.Context) ([]org.Org, error)
ListOrgAgents(ctx context.Context, id org.OrgID) ([]org.AgentAssignment, error)
}
// owners lists every org, system org first. Without the directory the system
// org still runs.
func (b *boot) owners(ctx context.Context, directory orgDirectory) []org.OrgID {
owners := []org.OrgID{org.DefaultOrgID}
if directory == nil {
return owners
}
list, err := directory.ListOrgs(ctx)
if err != nil {
b.log.WarnContext(ctx, "organisations unavailable; acting in the system organisation only", "err", err)
return owners
}
for _, o := range list {
if o.ID != org.DefaultOrgID {
owners = append(owners, o.ID)
}
}
return owners
}
func (b *boot) organisations(ctx context.Context) []orgAgents {
directory, _ := b.stateStore.(orgDirectory)
store := scheduleResourceStore{orgs: directory, log: b.log}
var out []orgAgents
for _, owner := range store.owners(ctx) {
for _, owner := range b.owners(ctx, directory) {
entry := orgAgents{owner: owner}
if owner == org.DefaultOrgID && directory != nil {
root := identity.StableID(servicekit.IdentityNames(b.cfgHolder.Get())[0])
-1
View File
@@ -208,7 +208,6 @@ func Run() int { //nolint:cyclop,funlen // the composition root's setup sequence
b.setupDaemonRPC(ctx)
b.playbooks.Keep(ctx, playbookRefreshInterval)
b.workflowDefinitions.Keep(ctx, playbookRefreshInterval)
b.controlPlane.KeepSchedules(ctx, playbookRefreshInterval)
b.wireConfigSurfaces(ctx, args.cfgPath, args.overlayPath)
if err := b.startServices(ctx); err != nil {
+103 -222
View File
@@ -5,20 +5,22 @@ import (
"errors"
"fmt"
"log/slog"
"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"
"github.com/samcharles93/archie-core/internal/domain/scheduling"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanestore"
"github.com/samcharles93/archie-core/internal/infrastructure/crondelivery"
"github.com/samcharles93/archie-core/internal/infrastructure/cronevents"
"github.com/samcharles93/archie-core/internal/infrastructure/schedulecapture"
)
// scheduleFailureAlertStreak is how many failed runs in a row raise an alert.
const scheduleFailureAlertStreak = 3
// schedulingConfig translates external input into the domain-owned engine
// configuration and connects the selected event infrastructure.
func schedulingConfig(input configuration.SchedulingInput, bus *events.Bus) (scheduling.EngineConfig, error) {
@@ -47,239 +49,132 @@ func schedulingConfig(input configuration.SchedulingInput, bus *events.Bus) (sch
return cfg, nil
}
// setupScheduling builds the cron/scheduling composition site: a job store,
// a delivery router over the kind runners this composition root can back
// with a real production dependency, and the ticker engine itself. It does
// not start the engine -- startServices does that alongside every other
// subsystem, and the corresponding Stop is registered here via addCleanup so
// shutdown ordering matches every other daemon-lifecycle subsystem.
//
// The "chat" kind delivers through the Messaging Service. The "workflow" kind
// rides gateway.TaskCreator, the path chat's /spawn uses, so it is wired only
// when [chat] identity profiles configure one.
// scheduleRuns is the State Store's schedule-run surface, as
// *staterpc.Client serves it.
type scheduleRuns interface {
ClaimDueRuns(ctx context.Context, now time.Time, stale time.Duration) ([]scheduling.Claim, error)
FinishScheduleRun(ctx context.Context, runID int64, result scheduling.RunResult, errText string) (int, error)
SetScheduleRunCapture(ctx context.Context, runID int64, captureID string) error
}
// setupScheduling builds the scheduler: claimed runs of a built-in schedule
// go to its in-process job, every other run records a schedule-fired capture
// that bindings start workflows from. The engine is started by startServices.
func (b *boot) setupScheduling() error {
runs, ok := b.stateStore.(scheduleRuns)
if !ok {
return nil
}
cfg, err := schedulingConfig(b.doc.Scheduling, b.bus)
if err != nil {
return fmt.Errorf("scheduling: %w", err)
}
store := scheduleResourceStore{client: b.controlPlane, log: b.log}
if orgs, ok := b.stateStore.(orgDirectory); ok {
store.orgs = orgs
src := scheduleSource{runs: runs, stale: 2 * cfg.JobTimeout, log: b.log}
if alerts, ok := b.stateStore.(alert.Store); ok {
src.alerts = alert.Reporter{Raiser: alerts, Log: b.log, By: "archied"}
}
chatRunner, err := crondelivery.NewChatCourier(store, func(ctx context.Context, target scheduling.Target, text string) error {
return b.messaging.Deliver(ctx, target.Channel, target.ChatID, text)
})
if err != nil {
return fmt.Errorf("scheduling: build chat runner: %w", err)
var fire scheduling.Runner
if captures, ok := b.stateStore.(storecontract.CaptureStore); ok {
fire = scheduleFirer{runs: runs, firer: schedulecapture.Firer{
Captures: captures, Retention: b.cfg.Capture.Retention.Std(), MaxEvents: b.cfg.Capture.MaxEvents,
}}
}
// Channels are instance-owned, so only the system org may message them.
runners := map[string]scheduling.Runner{scheduling.KindChat: systemOrgOnly{
next: chatRunner, store: store,
refusal: errors.New("chat schedules need an organisation channel; use a workflow schedule"),
}}
if b.chatTasks != nil {
workflowRunner, err := crondelivery.NewWorkflowTask(store, spawnTaskSubmitter{creator: b.chatTasks, identity: b.defaultChatIdentity})
if err != nil {
return fmt.Errorf("scheduling: build workflow runner: %w", err)
}
// The chat identity profiles that submit scheduled work belong to the
// system org; another org's schedule must name the agent it runs as.
runners[scheduling.KindWorkflow] = systemOrgOnly{
next: workflowRunner, store: store,
refusal: errors.New("workflow schedules run only in the system organisation until a schedule names its agent"),
}
}
router, err := crondelivery.NewRouter(store, runners)
if err != nil {
return fmt.Errorf("scheduling: build router: %w", err)
}
engine, err := scheduling.NewEngine(store, router, cfg)
engine, err := scheduling.NewEngine(src, scheduleRunner{Fire: fire}, cfg)
if err != nil {
return fmt.Errorf("scheduling: build engine: %w", err)
}
b.schedulingEngine = engine
b.addCleanup(shutdownSchedulingEngine(engine, b.log))
return nil
}
// orgDirectory finds every organisation and an agent principal to act as in
// each, because the control plane serves a caller only its own org.
type orgDirectory interface {
access.PrincipalSource
ListOrgs(ctx context.Context) ([]org.Org, error)
ListOrgAgents(ctx context.Context, id org.OrgID) ([]org.AgentAssignment, error)
}
// scheduleResourceStore is every organisation's schedules document. Engine job
// ids are "<org>/<job id>" so one engine ticks all orgs, and each lookup or
// run record acts under the owning org's principal.
type scheduleResourceStore struct {
client *controlplanestore.Client
orgs orgDirectory
// scheduleSource claims runs from the State Store and records their results,
// raising an alert while a schedule keeps failing.
type scheduleSource struct {
runs scheduleRuns
stale time.Duration
alerts alert.Reporter
log *slog.Logger
}
var (
_ crondelivery.SpecLookup = scheduleResourceStore{}
_ crondelivery.RunRecorder = scheduleResourceStore{}
_ crondelivery.RouterStore = scheduleResourceStore{}
)
func jobKey(owner org.OrgID, id string) string { return string(owner) + "/" + id }
func splitJobKey(key string) (org.OrgID, string) {
owner, id, ok := strings.Cut(key, "/")
if !ok {
return org.DefaultOrgID, key
}
return org.OrgID(owner), id
}
// orgContext returns ctx acting as owner. The system org is the daemon's own,
// so it needs no agent principal.
func (s scheduleResourceStore) orgContext(ctx context.Context, owner org.OrgID) (context.Context, error) {
if owner == org.DefaultOrgID {
return ctx, nil
}
if s.orgs == nil {
return nil, fmt.Errorf("organisation %q: no organisation directory", owner)
}
agents, err := s.orgs.ListOrgAgents(ctx, owner)
func (s scheduleSource) Due(ctx context.Context, now time.Time) ([]scheduling.Job, error) {
claims, err := s.runs.ClaimDueRuns(ctx, now, s.stale)
if err != nil {
return nil, fmt.Errorf("organisation %q: list agents: %w", owner, err)
return nil, err
}
for _, agent := range agents {
principal, err := s.orgs.PrincipalFor(ctx, agent.IdentityID)
if err == nil && principal.Org == owner {
return org.WithOrg(access.WithPrincipal(ctx, principal), owner), nil
jobs := make([]scheduling.Job, 0, len(claims))
for _, c := range claims {
// Built-in jobs share the daemon's state, so they run one at a time.
pool := scheduling.PoolParallel
if c.BuiltIn {
pool = scheduling.PoolSequential
}
jobs = append(jobs, scheduling.Job{
ID: c.ScheduleID, RunID: c.ID, Pool: pool, Detail: c.Name,
ScheduledFor: c.ScheduledFor, BuiltIn: c.BuiltIn,
})
}
return nil, fmt.Errorf("organisation %q has no agent to run its schedules as", owner)
return jobs, nil
}
func (s scheduleResourceStore) orgSchedules(ctx context.Context, key string) (context.Context, string, []scheduling.JobSpec, int64, error) {
owner, id := splitJobKey(key)
octx, err := s.orgContext(ctx, owner)
func (s scheduleSource) Finish(ctx context.Context, job scheduling.Job, result scheduling.RunResult, runErr error) error {
errText := ""
if runErr != nil {
errText = runErr.Error()
}
streak, err := s.runs.FinishScheduleRun(ctx, job.RunID, result, errText)
if err != nil {
return nil, "", nil, 0, err
return err
}
jobs, version, err := s.client.Schedules(octx)
return octx, id, jobs, version, err
if result == scheduling.RunSkipped || s.alerts.Raiser == nil {
return nil
}
s.alerts.Sync(ctx, streak >= scheduleFailureAlertStreak, alert.Input{
Org: org.DefaultOrgID, Kind: alert.KindScheduleFailing, Subject: job.ID,
Severity: alert.SeverityWarning,
Title: fmt.Sprintf("Schedule %q failed %d times in a row", job.Detail, streak),
Body: errText,
Link: "/org/schedules",
Condition: true,
})
return nil
}
func (s scheduleResourceStore) Get(ctx context.Context, key string) (scheduling.JobSpec, bool, error) {
_, id, jobs, _, err := s.orgSchedules(ctx, key)
// scheduleRunner sends a built-in schedule's run to its job and any other
// run to Fire.
type scheduleRunner struct {
Builtins map[string]scheduling.Runner
Fire scheduling.Runner
}
func (r scheduleRunner) Run(ctx context.Context, job scheduling.Job) error {
if job.BuiltIn {
if run := r.Builtins[job.ID]; run != nil {
return run.Run(ctx, job)
}
return fmt.Errorf("built-in schedule %q has no job in this archied", job.ID)
}
if r.Fire == nil {
return errors.New("schedules cannot fire: the State Store offers no capture store")
}
return r.Fire.Run(ctx, job)
}
// scheduleFirer records a schedule-fired capture for the run and links the
// run to it.
type scheduleFirer struct {
runs scheduleRuns
firer schedulecapture.Firer
}
func (f scheduleFirer) Run(ctx context.Context, job scheduling.Job) error {
captureID, err := f.firer.Fire(ctx, source.ScheduleFired{
ScheduleID: job.ID, Name: job.Detail, ScheduledFor: job.ScheduledFor, FiredAt: time.Now(),
})
if err != nil {
return scheduling.JobSpec{}, false, err
return err
}
for _, job := range jobs {
if job.ID == id {
return job, true, nil
}
}
return scheduling.JobSpec{}, false, nil
}
// owners lists every org, system org first. Without the directory the system
// org still runs.
func (s scheduleResourceStore) owners(ctx context.Context) []org.OrgID {
owners := []org.OrgID{org.DefaultOrgID}
if s.orgs == nil {
return owners
}
list, err := s.orgs.ListOrgs(ctx)
if err != nil {
s.log.WarnContext(ctx, "scheduling: organisations unavailable; running system schedules only", "err", err)
return owners
}
for _, o := range list {
if o.ID != org.DefaultOrgID {
owners = append(owners, o.ID)
}
}
return owners
}
func (s scheduleResourceStore) Due(ctx context.Context, now time.Time) ([]scheduling.Job, error) {
var due []scheduling.Job
for _, owner := range s.owners(ctx) {
octx, err := s.orgContext(ctx, owner)
if err != nil {
s.log.WarnContext(ctx, "scheduling: skipping organisation", "org", owner, "err", err)
continue
}
jobs, _, err := s.client.Schedules(octx)
if err != nil {
if owner == org.DefaultOrgID {
return nil, err
}
s.log.WarnContext(ctx, "scheduling: organisation schedules unavailable", "org", owner, "err", err)
continue
}
for _, job := range jobs {
if !job.NextRun.After(now) {
due = append(due, scheduling.Job{ID: jobKey(owner, job.ID), Pool: scheduling.Pool(job.Pool), Detail: job.Detail})
}
}
}
return due, nil
}
// systemOrgOnly runs a kind for the system org and refuses it for any other,
// recording the run so the refused job is not retried every tick.
type systemOrgOnly struct {
next scheduling.Runner
store scheduleResourceStore
refusal error
}
func (r systemOrgOnly) Run(ctx context.Context, job scheduling.Job) error {
if owner, _ := splitJobKey(job.ID); owner == org.DefaultOrgID {
return r.next.Run(ctx, job)
}
return errors.Join(fmt.Errorf("schedule %q: %w", job.ID, r.refusal), r.store.MarkRun(ctx, job.ID, time.Now()))
}
func (s scheduleResourceStore) MarkRun(ctx context.Context, key string, runAt time.Time) error {
for range 4 {
octx, id, jobs, version, err := s.orgSchedules(ctx, key)
if err != nil {
return err
}
found := false
for index := range jobs {
if jobs[index].ID != id {
continue
}
found = true
if jobs[index].Schedule.Resolved().Kind == scheduling.ScheduleOnce {
jobs = append(jobs[:index], jobs[index+1:]...)
break
}
next, nextErr := jobs[index].Schedule.NextRun(runAt)
if nextErr != nil {
return nextErr
}
at := runAt.UTC()
jobs[index].LastRun = &at
jobs[index].NextRun = next.UTC()
break
}
if !found {
return fmt.Errorf("%w: id %q", scheduling.ErrJobNotFound, key)
}
_, err = s.client.ReplaceSchedules(octx, jobs, version, "system:scheduler", "scheduler", fmt.Sprintf("schedule-run:%s:%d", key, runAt.UnixNano()))
if err == nil {
return nil
}
if !errors.Is(err, controlplanestore.ErrVersionConflict) {
return err
}
}
return controlplanestore.ErrVersionConflict
return f.runs.SetScheduleRunCapture(ctx, job.RunID, captureID)
}
// shutdownSchedulingEngine returns a cleanup that stops the ticker engine.
@@ -295,17 +190,3 @@ func shutdownSchedulingEngine(e *scheduling.Engine, log *slog.Logger) func() {
}
}
}
// spawnTaskSubmitter adapts gateway.TaskCreator to crondelivery.TaskSubmitter.
// The job's own id is only a dispatch key to the ticker engine, not an archie
// identity, so it is dropped rather than threaded into the spawn request;
// identity is fixed at construction to the daemon's default chat identity.
type spawnTaskSubmitter struct {
creator gateway.TaskCreator
identity string
}
func (s spawnTaskSubmitter) Submit(ctx context.Context, _, title, body string) error {
_, err := s.creator.CreateTask(ctx, gateway.SpawnRequest{Title: title, Body: body, Identity: s.identity})
return err
}
+1
View File
@@ -78,6 +78,7 @@ func serviceAlert(name string) alert.Input {
func (b *server) startSweeps(ctx context.Context, deps staterpc.Deps) {
go b.autoUpdatePackages(ctx, deps.Packages)
go b.sweepAuditRetention(ctx)
go b.sweepScheduleRuns(ctx, deps)
if deps.Alerts != nil {
go b.sweepAlerts(ctx, deps.Alerts)
}
+62
View File
@@ -0,0 +1,62 @@
package statestore
import (
"context"
"time"
"github.com/samcharles93/archie-core/internal/domain/scheduling"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanestore"
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
)
// scheduleRunSweepInterval is how often run history retention is applied.
const scheduleRunSweepInterval = time.Hour
// scheduleDeps serves schedules from the task store, with the instance's
// schedule settings read afresh on every call.
func (b *server) scheduleDeps(deps *staterpc.Deps) {
if schedules, ok := b.st.(scheduling.Store); ok {
deps.Schedules = schedules
}
if runs, ok := b.st.(scheduling.RunStore); ok {
deps.ScheduleRuns = runs
}
if resources, ok := b.st.(auditRetentionResources); ok {
deps.ScheduleSettings = func(ctx context.Context) (scheduling.Settings, error) {
resource, err := resources.Resource(ctx, storecontract.DefaultOrgID, controlplanestore.ScheduleSettingsKind)
if err != nil {
return scheduling.Settings{}, err
}
return controlplanestore.ScheduleSettings(resource.Value)
}
}
}
// sweepScheduleRuns applies run history retention until ctx ends. An
// unreadable setting skips the tick rather than pruning by a default.
func (b *server) sweepScheduleRuns(ctx context.Context, deps staterpc.Deps) {
if deps.ScheduleRuns == nil || deps.ScheduleSettings == nil {
return
}
ticker := time.NewTicker(scheduleRunSweepInterval)
defer ticker.Stop()
for {
if settings, err := deps.ScheduleSettings(ctx); err != nil {
if ctx.Err() == nil {
b.log.WarnContext(ctx, "schedule run retention not applied: setting unreadable", "err", err)
}
} else if n, err := deps.ScheduleRuns.PruneRuns(ctx, time.Now().Add(-settings.RunRetention), settings.RunRetentionCount); err != nil {
if ctx.Err() == nil {
b.log.WarnContext(ctx, "prune schedule runs", "err", err)
}
} else if n > 0 {
b.log.InfoContext(ctx, "pruned schedule runs", "rows", n)
}
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}
+1
View File
@@ -341,6 +341,7 @@ func (b *server) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps {
}
b.executionDeps(&deps)
b.accessDeps(&deps)
b.scheduleDeps(&deps)
if css, ok := b.st.(storecontract.ConfigSnapshotStore); ok {
deps.ConfigSnapshots = css
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,473 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.2
// - protoc (unknown)
// source: state/v1/schedule.proto
package statev1
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
ScheduleService_ListSchedules_FullMethodName = "/state.v1.ScheduleService/ListSchedules"
ScheduleService_GetSchedule_FullMethodName = "/state.v1.ScheduleService/GetSchedule"
ScheduleService_PutSchedule_FullMethodName = "/state.v1.ScheduleService/PutSchedule"
ScheduleService_DeleteSchedule_FullMethodName = "/state.v1.ScheduleService/DeleteSchedule"
ScheduleService_EnsureBuiltinSchedules_FullMethodName = "/state.v1.ScheduleService/EnsureBuiltinSchedules"
ScheduleService_ClaimDueRuns_FullMethodName = "/state.v1.ScheduleService/ClaimDueRuns"
ScheduleService_RequestScheduleRun_FullMethodName = "/state.v1.ScheduleService/RequestScheduleRun"
ScheduleService_FinishScheduleRun_FullMethodName = "/state.v1.ScheduleService/FinishScheduleRun"
ScheduleService_SetScheduleRunCapture_FullMethodName = "/state.v1.ScheduleService/SetScheduleRunCapture"
ScheduleService_ListScheduleRuns_FullMethodName = "/state.v1.ScheduleService/ListScheduleRuns"
)
// ScheduleServiceClient is the client API for ScheduleService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
//
// Schedules and their runs (internal/domain/scheduling). The scheduler in
// archied claims due runs and records their results; the dashboard edits
// schedules and reads runs. Cron is read in the instance zone from the
// schedule-settings resource.
type ScheduleServiceClient interface {
ListSchedules(ctx context.Context, in *ListSchedulesRequest, opts ...grpc.CallOption) (*ListSchedulesResponse, error)
GetSchedule(ctx context.Context, in *GetScheduleRequest, opts ...grpc.CallOption) (*GetScheduleResponse, error)
PutSchedule(ctx context.Context, in *PutScheduleRequest, opts ...grpc.CallOption) (*PutScheduleResponse, error)
DeleteSchedule(ctx context.Context, in *DeleteScheduleRequest, opts ...grpc.CallOption) (*DeleteScheduleResponse, error)
EnsureBuiltinSchedules(ctx context.Context, in *EnsureBuiltinSchedulesRequest, opts ...grpc.CallOption) (*EnsureBuiltinSchedulesResponse, error)
ClaimDueRuns(ctx context.Context, in *ClaimDueRunsRequest, opts ...grpc.CallOption) (*ClaimDueRunsResponse, error)
RequestScheduleRun(ctx context.Context, in *RequestScheduleRunRequest, opts ...grpc.CallOption) (*RequestScheduleRunResponse, error)
FinishScheduleRun(ctx context.Context, in *FinishScheduleRunRequest, opts ...grpc.CallOption) (*FinishScheduleRunResponse, error)
SetScheduleRunCapture(ctx context.Context, in *SetScheduleRunCaptureRequest, opts ...grpc.CallOption) (*SetScheduleRunCaptureResponse, error)
ListScheduleRuns(ctx context.Context, in *ListScheduleRunsRequest, opts ...grpc.CallOption) (*ListScheduleRunsResponse, error)
}
type scheduleServiceClient struct {
cc grpc.ClientConnInterface
}
func NewScheduleServiceClient(cc grpc.ClientConnInterface) ScheduleServiceClient {
return &scheduleServiceClient{cc}
}
func (c *scheduleServiceClient) ListSchedules(ctx context.Context, in *ListSchedulesRequest, opts ...grpc.CallOption) (*ListSchedulesResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ListSchedulesResponse)
err := c.cc.Invoke(ctx, ScheduleService_ListSchedules_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *scheduleServiceClient) GetSchedule(ctx context.Context, in *GetScheduleRequest, opts ...grpc.CallOption) (*GetScheduleResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetScheduleResponse)
err := c.cc.Invoke(ctx, ScheduleService_GetSchedule_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *scheduleServiceClient) PutSchedule(ctx context.Context, in *PutScheduleRequest, opts ...grpc.CallOption) (*PutScheduleResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(PutScheduleResponse)
err := c.cc.Invoke(ctx, ScheduleService_PutSchedule_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *scheduleServiceClient) DeleteSchedule(ctx context.Context, in *DeleteScheduleRequest, opts ...grpc.CallOption) (*DeleteScheduleResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(DeleteScheduleResponse)
err := c.cc.Invoke(ctx, ScheduleService_DeleteSchedule_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *scheduleServiceClient) EnsureBuiltinSchedules(ctx context.Context, in *EnsureBuiltinSchedulesRequest, opts ...grpc.CallOption) (*EnsureBuiltinSchedulesResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(EnsureBuiltinSchedulesResponse)
err := c.cc.Invoke(ctx, ScheduleService_EnsureBuiltinSchedules_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *scheduleServiceClient) ClaimDueRuns(ctx context.Context, in *ClaimDueRunsRequest, opts ...grpc.CallOption) (*ClaimDueRunsResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ClaimDueRunsResponse)
err := c.cc.Invoke(ctx, ScheduleService_ClaimDueRuns_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *scheduleServiceClient) RequestScheduleRun(ctx context.Context, in *RequestScheduleRunRequest, opts ...grpc.CallOption) (*RequestScheduleRunResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RequestScheduleRunResponse)
err := c.cc.Invoke(ctx, ScheduleService_RequestScheduleRun_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *scheduleServiceClient) FinishScheduleRun(ctx context.Context, in *FinishScheduleRunRequest, opts ...grpc.CallOption) (*FinishScheduleRunResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(FinishScheduleRunResponse)
err := c.cc.Invoke(ctx, ScheduleService_FinishScheduleRun_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *scheduleServiceClient) SetScheduleRunCapture(ctx context.Context, in *SetScheduleRunCaptureRequest, opts ...grpc.CallOption) (*SetScheduleRunCaptureResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SetScheduleRunCaptureResponse)
err := c.cc.Invoke(ctx, ScheduleService_SetScheduleRunCapture_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *scheduleServiceClient) ListScheduleRuns(ctx context.Context, in *ListScheduleRunsRequest, opts ...grpc.CallOption) (*ListScheduleRunsResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ListScheduleRunsResponse)
err := c.cc.Invoke(ctx, ScheduleService_ListScheduleRuns_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// ScheduleServiceServer is the server API for ScheduleService service.
// All implementations must embed UnimplementedScheduleServiceServer
// for forward compatibility.
//
// Schedules and their runs (internal/domain/scheduling). The scheduler in
// archied claims due runs and records their results; the dashboard edits
// schedules and reads runs. Cron is read in the instance zone from the
// schedule-settings resource.
type ScheduleServiceServer interface {
ListSchedules(context.Context, *ListSchedulesRequest) (*ListSchedulesResponse, error)
GetSchedule(context.Context, *GetScheduleRequest) (*GetScheduleResponse, error)
PutSchedule(context.Context, *PutScheduleRequest) (*PutScheduleResponse, error)
DeleteSchedule(context.Context, *DeleteScheduleRequest) (*DeleteScheduleResponse, error)
EnsureBuiltinSchedules(context.Context, *EnsureBuiltinSchedulesRequest) (*EnsureBuiltinSchedulesResponse, error)
ClaimDueRuns(context.Context, *ClaimDueRunsRequest) (*ClaimDueRunsResponse, error)
RequestScheduleRun(context.Context, *RequestScheduleRunRequest) (*RequestScheduleRunResponse, error)
FinishScheduleRun(context.Context, *FinishScheduleRunRequest) (*FinishScheduleRunResponse, error)
SetScheduleRunCapture(context.Context, *SetScheduleRunCaptureRequest) (*SetScheduleRunCaptureResponse, error)
ListScheduleRuns(context.Context, *ListScheduleRunsRequest) (*ListScheduleRunsResponse, error)
mustEmbedUnimplementedScheduleServiceServer()
}
// UnimplementedScheduleServiceServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedScheduleServiceServer struct{}
func (UnimplementedScheduleServiceServer) ListSchedules(context.Context, *ListSchedulesRequest) (*ListSchedulesResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ListSchedules not implemented")
}
func (UnimplementedScheduleServiceServer) GetSchedule(context.Context, *GetScheduleRequest) (*GetScheduleResponse, error) {
return nil, status.Error(codes.Unimplemented, "method GetSchedule not implemented")
}
func (UnimplementedScheduleServiceServer) PutSchedule(context.Context, *PutScheduleRequest) (*PutScheduleResponse, error) {
return nil, status.Error(codes.Unimplemented, "method PutSchedule not implemented")
}
func (UnimplementedScheduleServiceServer) DeleteSchedule(context.Context, *DeleteScheduleRequest) (*DeleteScheduleResponse, error) {
return nil, status.Error(codes.Unimplemented, "method DeleteSchedule not implemented")
}
func (UnimplementedScheduleServiceServer) EnsureBuiltinSchedules(context.Context, *EnsureBuiltinSchedulesRequest) (*EnsureBuiltinSchedulesResponse, error) {
return nil, status.Error(codes.Unimplemented, "method EnsureBuiltinSchedules not implemented")
}
func (UnimplementedScheduleServiceServer) ClaimDueRuns(context.Context, *ClaimDueRunsRequest) (*ClaimDueRunsResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ClaimDueRuns not implemented")
}
func (UnimplementedScheduleServiceServer) RequestScheduleRun(context.Context, *RequestScheduleRunRequest) (*RequestScheduleRunResponse, error) {
return nil, status.Error(codes.Unimplemented, "method RequestScheduleRun not implemented")
}
func (UnimplementedScheduleServiceServer) FinishScheduleRun(context.Context, *FinishScheduleRunRequest) (*FinishScheduleRunResponse, error) {
return nil, status.Error(codes.Unimplemented, "method FinishScheduleRun not implemented")
}
func (UnimplementedScheduleServiceServer) SetScheduleRunCapture(context.Context, *SetScheduleRunCaptureRequest) (*SetScheduleRunCaptureResponse, error) {
return nil, status.Error(codes.Unimplemented, "method SetScheduleRunCapture not implemented")
}
func (UnimplementedScheduleServiceServer) ListScheduleRuns(context.Context, *ListScheduleRunsRequest) (*ListScheduleRunsResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ListScheduleRuns not implemented")
}
func (UnimplementedScheduleServiceServer) mustEmbedUnimplementedScheduleServiceServer() {}
func (UnimplementedScheduleServiceServer) testEmbeddedByValue() {}
// UnsafeScheduleServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to ScheduleServiceServer will
// result in compilation errors.
type UnsafeScheduleServiceServer interface {
mustEmbedUnimplementedScheduleServiceServer()
}
func RegisterScheduleServiceServer(s grpc.ServiceRegistrar, srv ScheduleServiceServer) {
// If the following call panics, it indicates UnimplementedScheduleServiceServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&ScheduleService_ServiceDesc, srv)
}
func _ScheduleService_ListSchedules_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListSchedulesRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ScheduleServiceServer).ListSchedules(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ScheduleService_ListSchedules_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ScheduleServiceServer).ListSchedules(ctx, req.(*ListSchedulesRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ScheduleService_GetSchedule_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetScheduleRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ScheduleServiceServer).GetSchedule(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ScheduleService_GetSchedule_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ScheduleServiceServer).GetSchedule(ctx, req.(*GetScheduleRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ScheduleService_PutSchedule_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(PutScheduleRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ScheduleServiceServer).PutSchedule(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ScheduleService_PutSchedule_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ScheduleServiceServer).PutSchedule(ctx, req.(*PutScheduleRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ScheduleService_DeleteSchedule_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(DeleteScheduleRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ScheduleServiceServer).DeleteSchedule(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ScheduleService_DeleteSchedule_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ScheduleServiceServer).DeleteSchedule(ctx, req.(*DeleteScheduleRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ScheduleService_EnsureBuiltinSchedules_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(EnsureBuiltinSchedulesRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ScheduleServiceServer).EnsureBuiltinSchedules(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ScheduleService_EnsureBuiltinSchedules_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ScheduleServiceServer).EnsureBuiltinSchedules(ctx, req.(*EnsureBuiltinSchedulesRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ScheduleService_ClaimDueRuns_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ClaimDueRunsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ScheduleServiceServer).ClaimDueRuns(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ScheduleService_ClaimDueRuns_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ScheduleServiceServer).ClaimDueRuns(ctx, req.(*ClaimDueRunsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ScheduleService_RequestScheduleRun_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RequestScheduleRunRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ScheduleServiceServer).RequestScheduleRun(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ScheduleService_RequestScheduleRun_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ScheduleServiceServer).RequestScheduleRun(ctx, req.(*RequestScheduleRunRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ScheduleService_FinishScheduleRun_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(FinishScheduleRunRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ScheduleServiceServer).FinishScheduleRun(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ScheduleService_FinishScheduleRun_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ScheduleServiceServer).FinishScheduleRun(ctx, req.(*FinishScheduleRunRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ScheduleService_SetScheduleRunCapture_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SetScheduleRunCaptureRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ScheduleServiceServer).SetScheduleRunCapture(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ScheduleService_SetScheduleRunCapture_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ScheduleServiceServer).SetScheduleRunCapture(ctx, req.(*SetScheduleRunCaptureRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ScheduleService_ListScheduleRuns_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListScheduleRunsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ScheduleServiceServer).ListScheduleRuns(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ScheduleService_ListScheduleRuns_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ScheduleServiceServer).ListScheduleRuns(ctx, req.(*ListScheduleRunsRequest))
}
return interceptor(ctx, in, info, handler)
}
// ScheduleService_ServiceDesc is the grpc.ServiceDesc for ScheduleService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var ScheduleService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "state.v1.ScheduleService",
HandlerType: (*ScheduleServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "ListSchedules",
Handler: _ScheduleService_ListSchedules_Handler,
},
{
MethodName: "GetSchedule",
Handler: _ScheduleService_GetSchedule_Handler,
},
{
MethodName: "PutSchedule",
Handler: _ScheduleService_PutSchedule_Handler,
},
{
MethodName: "DeleteSchedule",
Handler: _ScheduleService_DeleteSchedule_Handler,
},
{
MethodName: "EnsureBuiltinSchedules",
Handler: _ScheduleService_EnsureBuiltinSchedules_Handler,
},
{
MethodName: "ClaimDueRuns",
Handler: _ScheduleService_ClaimDueRuns_Handler,
},
{
MethodName: "RequestScheduleRun",
Handler: _ScheduleService_RequestScheduleRun_Handler,
},
{
MethodName: "FinishScheduleRun",
Handler: _ScheduleService_FinishScheduleRun_Handler,
},
{
MethodName: "SetScheduleRunCapture",
Handler: _ScheduleService_SetScheduleRunCapture_Handler,
},
{
MethodName: "ListScheduleRuns",
Handler: _ScheduleService_ListScheduleRuns_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "state/v1/schedule.proto",
}
+1
View File
@@ -71,6 +71,7 @@ const (
KindServiceUnhealthy = "service.unhealthy"
KindReleaseAvailable = "release.available"
KindPolicyInvalid = "policy.invalid"
KindScheduleFailing = "schedule.failing"
)
// Limits on what a raiser may store.
+1 -1
View File
@@ -30,7 +30,7 @@ func Processes() []string { return []string{Daemon, Gateway, Messaging} }
// Applicability names the consumers of each resource, including boot-only settings.
func Applicability() map[string][]string {
kinds := map[string][]string{}
for _, kind := range []string{"task-policy", "provider-settings", "model-aliases", "repository-policies", "scheduling-policy", "tool-settings", "plugin-settings", "channel-settings", "container-runtime-policies", "credential-bindings", "identity-grants", "agent-profiles", "workflow-execution-settings", "extension-settings", "workflow-definitions", "workflow-enablement", "schedules", "eda-playbooks", "forge-connections"} {
for _, kind := range []string{"task-policy", "provider-settings", "model-aliases", "repository-policies", "scheduling-policy", "tool-settings", "plugin-settings", "channel-settings", "container-runtime-policies", "credential-bindings", "identity-grants", "agent-profiles", "workflow-execution-settings", "extension-settings", "workflow-definitions", "workflow-enablement", "eda-playbooks", "forge-connections"} {
kinds[kind] = []string{Daemon}
}
for _, kind := range []string{"provider-settings", "model-aliases", "tool-settings", "extension-settings", "soul", "skills", "curators"} {
+13 -11
View File
@@ -44,20 +44,19 @@ func (p Pool) resolve() Pool {
return p
}
// Job is one due unit of scheduled work as handed to the engine. It carries
// identity and dispatch policy only: the schedule itself (cron expression,
// next-run time, catch-up policy) belongs to the job store behind JobSource,
// which is why the engine never sees one.
// Job is one claimed run as handed to the engine.
type Job struct {
// ID identifies the job across ticks. It is the overlap key: while a
// run with this ID is queued or in flight, later ticks that report the
// same ID are skipped rather than stacked.
// ID is the schedule id. It is the overlap key: while a run of the
// schedule is queued or in flight, another claimed run of it is skipped.
ID string
// RunID is the claimed run the outcome is recorded against.
RunID int64
// Pool selects the dispatch pool. Empty means PoolSequential.
Pool Pool
// Detail is a human-readable label recorded on emitted events so a run
// stays attributable without the engine knowing what the job does.
Detail string
// Detail is the schedule name, recorded on emitted events.
Detail string
ScheduledFor time.Time
BuiltIn bool
}
// Validate checks the fields the engine relies on.
@@ -68,9 +67,12 @@ func (j Job) Validate() error {
return j.Pool.Validate()
}
// JobSource returns the jobs due at an instant.
// JobSource claims the runs due at an instant and records how each ended.
type JobSource interface {
Due(ctx context.Context, now time.Time) ([]Job, error)
// Finish records a run's result: RunSucceeded, RunFailed with err, or
// RunSkipped when the schedule's previous run was still going.
Finish(ctx context.Context, job Job, result RunResult, err error) error
}
// Runner executes one due job. Implementations must respect ctx: the engine
-30
View File
@@ -1,30 +0,0 @@
package scheduling
import (
"errors"
"fmt"
"regexp"
)
// ErrDangerousCommand is returned when a job's payload names a command nobody
// should schedule. The list is deliberately over-broad: refusing a job an
// operator wanted costs a retry, accepting one costs the host.
var ErrDangerousCommand = errors.New("scheduling: payload names a dangerous command")
// dangerousPayload matches the daemon's own restart, a service or launch
// manager, a process killer, a filesystem format, a raw block write and a
// machine power command. Matching is whole-word and case-insensitive, so "dd"
// is caught while "added" is not.
var dangerousPayload = regexp.MustCompile(`(?i)\b(?:archied restart|systemctl|launchctl|pkill|mkfs|dd|shutdown|reboot)\b`)
// RefuseDangerousJob refuses a job whose payload names a dangerous command.
// The refusal is at creation time because a scheduled job runs unattended:
// there is nobody at tick time to stop it. Every creation path reaches a job
// spec through this one function, so a new token is added here and nowhere
// else.
func RefuseDangerousJob(job JobSpec) error {
if named := dangerousPayload.FindString(job.Payload.Text); named != "" {
return fmt.Errorf("%w: job %q payload names %q", ErrDangerousCommand, job.ID, named)
}
return nil
}
-47
View File
@@ -1,47 +0,0 @@
package scheduling
import (
"errors"
"strings"
"testing"
)
func TestRefuseDangerousJob(t *testing.T) {
cases := []struct {
name string
payload string
want string
}{
{name: "an ordinary body", payload: "Summarise yesterday's commits and open a PR."},
{name: "letters inside a word", payload: "Add a note about the middleware address."},
{name: "a gerund", payload: "Report on the rebooting schedule."},
{name: "the daemon's own restart", payload: "archied restart", want: "archied restart"},
{name: "a service manager", payload: "sudo systemctl restart archied", want: "systemctl"},
{name: "a launch manager", payload: "launchctl unload ~/Library/LaunchAgents/x.plist", want: "launchctl"},
{name: "a process killer", payload: "pkill -f archied", want: "pkill"},
{name: "a filesystem format", payload: "mkfs.ext4 /dev/sda1", want: "mkfs"},
{name: "a raw block write", payload: "sudo dd if=/dev/zero of=/dev/sda", want: "dd"},
{name: "a machine power command", payload: "shutdown -h now", want: "shutdown"},
{name: "a restart in capitals", payload: "Please REBOOT the box", want: "REBOOT"},
}
for _, testCase := range cases {
t.Run(testCase.name, func(t *testing.T) {
job := JobSpec{ID: "nightly", Payload: Payload{Text: testCase.payload}}
err := RefuseDangerousJob(job)
if testCase.want == "" {
if err != nil {
t.Fatalf("RefuseDangerousJob(%q) = %v, want nil", testCase.payload, err)
}
return
}
if !errors.Is(err, ErrDangerousCommand) {
t.Fatalf("RefuseDangerousJob(%q) = %v, want ErrDangerousCommand", testCase.payload, err)
}
for _, want := range []string{testCase.want, `"nightly"`} {
if !strings.Contains(err.Error(), want) {
t.Errorf("RefuseDangerousJob(%q) = %q, want it to name %s", testCase.payload, err, want)
}
}
})
}
}
-99
View File
@@ -1,99 +0,0 @@
package scheduling
import (
"errors"
"time"
)
// Job kinds, selecting the delivery runner. Unknown kinds are stored as-is
// and refused by the router.
const (
// KindChat delivers the job's Payload.Text as a chat message through the
// deployment's channel. It is the default: an empty Kind means KindChat,
// so every job written before this field existed keeps delivering the
// way it did when it was created.
KindChat = "chat"
// KindWorkflow submits the job as a unit of work through the work-intake
// path, so the existing task lifecycle owns scheduling, retries, gates
// and PR opening.
KindWorkflow = "workflow"
)
// JobSpec is one scheduled job as the schedules document persists it, plus
// the bookkeeping fields the scheduler computes (NextRun, LastRun, Created,
// Updated). The wire shape is the public API; the scheduling.Job returned
// to the engine is a stripped subset.
type JobSpec struct {
// ID is the unique identifier. Required, non-empty, and the merge
// key for run recording.
ID string `json:"id"`
// Pool is "parallel" or "sequential". Empty means sequential — the
// safer default, matching Pool.resolve().
Pool string `json:"pool,omitempty"`
// Detail is a human-readable label rendered on events.
Detail string `json:"detail,omitempty" title:"Schedule name"`
// Kind selects the delivery runner. Empty means KindChat.
Kind string `json:"kind,omitempty"`
// Schedule decides when this job is due. See schedule.go for the
// supported kinds and their arithmetic.
Schedule Schedule `json:"schedule"`
// Target and Payload describe where the job's output goes and what it
// carries. They live on the wire so jobs created ahead of the delivery
// runners that read them do not need a shape migration.
Target Target `json:"target"`
Payload Payload `json:"payload"`
// NextRun is the absolute moment the job will next fire. Computed
// at write time so the engine's hot path is a single comparison.
NextRun time.Time `json:"next_run"`
// LastRun is the last run time reported by the run-recording step,
// nil if the job has never run. The schedule does not know whether
// the run succeeded — that judgement belongs to the runner.
LastRun *time.Time `json:"last_run,omitempty"`
// Created and Updated are audit metadata written by the document's
// owner; the engine does not read them.
Created time.Time `json:"created"`
Updated time.Time `json:"updated"`
}
// Target identifies where the job's output goes. Empty Target is valid —
// the delivery runner chooses a default.
type Target struct {
// Channel names the Messaging Service channel, such as "telegram".
Channel string `json:"channel,omitempty"`
// ChatID is the channel-native chat id.
ChatID string `json:"chat_id,omitempty"`
}
// Payload is the content sent at run time.
type Payload struct {
// Text is the literal message body. Templating is a future concern
// and is deliberately absent here.
Text string `json:"text,omitempty"`
}
// Sentinels the schedule vocabulary and its callers match with errors.Is.
var (
// ErrJobNotFound is returned by a job source when the requested id
// is absent from its document.
ErrJobNotFound = errors.New("scheduling: job not found")
// ErrInvalidSpec is returned when a JobSpec or Schedule fails
// structural validation (empty id, unknown schedule kind,
// non-positive interval).
ErrInvalidSpec = errors.New("scheduling: invalid job spec")
// ErrScheduleUnsupported is returned when a job's schedule kind
// cannot compute its next run time. Interval arithmetic is fully
// implemented; cron and once return this so callers can surface a
// clear error rather than silently advancing.
ErrScheduleUnsupported = errors.New("scheduling: schedule kind not implemented")
)
+165
View File
@@ -0,0 +1,165 @@
package scheduling
import (
"context"
"fmt"
"strings"
"time"
)
// OwnerKind names what a schedule belongs to.
type OwnerKind string
const (
// OwnerInstance is the instance itself; its runs act as the system
// identity.
OwnerInstance OwnerKind = "instance"
// OwnerOrg is one organisation, named by Owner.ID.
OwnerOrg OwnerKind = "org"
)
// Owner references what a schedule belongs to. The dashboard renders the
// referenced thing's name; nothing stores a display string.
type Owner struct {
Kind OwnerKind
// ID is the organisation id for OwnerOrg and empty for OwnerInstance.
ID string
}
// Validate rejects an unknown kind and an ID that does not fit it.
func (o Owner) Validate() error {
switch o.Kind {
case OwnerInstance:
if o.ID != "" {
return fmt.Errorf("%w: an instance owner has no id", ErrInvalidSpec)
}
case OwnerOrg:
if o.ID == "" {
return fmt.Errorf("%w: an organisation owner needs an id", ErrInvalidSpec)
}
default:
return fmt.Errorf("%w: unknown owner kind %q", ErrInvalidSpec, o.Kind)
}
return nil
}
// Schedule is one stored schedule.
type Schedule struct {
ID string
Name string
Owner Owner
Enabled bool
// BuiltIn schedules are defined in code: only Enabled and Timing change.
BuiltIn bool
Timing Timing
// NextRun is when the schedule next fires; zero when it never will.
NextRun time.Time
Created time.Time
Updated time.Time
// LastRun is the most recent run, nil before the first.
LastRun *Run
}
// Validate checks the fields a write needs.
func (s Schedule) Validate() error {
if strings.TrimSpace(s.ID) == "" {
return fmt.Errorf("%w: id is required", ErrInvalidSpec)
}
if strings.TrimSpace(s.Name) == "" {
return fmt.Errorf("%w: name is required", ErrInvalidSpec)
}
if err := s.Owner.Validate(); err != nil {
return err
}
return s.Timing.Validate()
}
// RunResult is a run's state.
type RunResult string
const (
// RunPending is a requested run no scheduler has picked up yet.
RunPending RunResult = "pending"
RunRunning RunResult = "running"
RunSucceeded RunResult = "succeeded"
RunFailed RunResult = "failed"
// RunSkipped is a firing dropped because the schedule's previous run was
// still going.
RunSkipped RunResult = "skipped"
)
// Run is one firing of a schedule.
type Run struct {
ID int64
ScheduleID string
// ScheduledFor is the grid time the run belongs to, or the request time
// of a run started by hand. It is unique per schedule, which is what
// stops two schedulers firing the same slot.
ScheduledFor time.Time
Started time.Time
Finished time.Time
Result RunResult
Error string
// CaptureID is the schedule-fired capture the run recorded, empty when
// none. The tasks it started are binding dispatches against it.
CaptureID string
}
// Claim is a run handed to the scheduler to execute.
type Claim struct {
Run
Name string
BuiltIn bool
}
// Builtin is a schedule defined in code, seeded once and then owned by the
// operator's enabled flag and timing.
type Builtin struct {
ID string
Name string
Interval time.Duration
}
// Settings are the instance's schedule settings.
type Settings struct {
// Location is the zone cron expressions are read in.
Location *time.Location
// RunRetention and RunRetentionCount bound run history: a finished run
// goes when it is older than RunRetention or beyond the newest
// RunRetentionCount of its schedule, whichever comes first.
RunRetention time.Duration
RunRetentionCount int
}
// Store persists schedules. Methods that compute a next run take the zone
// cron is read in.
type Store interface {
ListSchedules(ctx context.Context) ([]Schedule, error)
GetSchedule(ctx context.Context, id string) (Schedule, error)
// PutSchedule creates or replaces a schedule and returns it as stored.
// A built-in schedule keeps everything but Enabled and Timing.
PutSchedule(ctx context.Context, s Schedule, loc *time.Location) (Schedule, error)
// DeleteSchedule refuses a built-in schedule with ErrBuiltIn.
DeleteSchedule(ctx context.Context, id string) error
// EnsureBuiltins inserts each missing built-in and leaves existing ones.
EnsureBuiltins(ctx context.Context, builtins []Builtin, loc *time.Location) error
ListRuns(ctx context.Context, scheduleID string, limit int) ([]Run, error)
}
// RunStore persists schedule runs.
type RunStore interface {
// ClaimDue starts every requested run and claims one run for each enabled
// schedule due at now, moving its next run past now. A run left running
// longer than stale is failed first, and a cron schedule whose next run
// was computed in another zone is recomputed in loc.
ClaimDue(ctx context.Context, now time.Time, stale time.Duration, loc *time.Location) ([]Claim, error)
// PruneRuns deletes finished runs older than before or beyond the newest
// keep of their schedule.
PruneRuns(ctx context.Context, before time.Time, keep int) (int64, error)
// RequestRun queues a run of id at now without moving its next run.
RequestRun(ctx context.Context, id string, now time.Time) (Run, error)
// FinishRun records a claimed run's result and returns how many of the
// schedule's latest finished runs failed in a row.
FinishRun(ctx context.Context, runID int64, result RunResult, errText string, at time.Time) (int, error)
SetRunCapture(ctx context.Context, runID int64, captureID string) error
}
+82 -121
View File
@@ -2,6 +2,7 @@ package scheduling
import (
"encoding/json"
"errors"
"fmt"
"time"
)
@@ -35,167 +36,127 @@ func (d *Duration) UnmarshalJSON(data []byte) error {
// Std is the standard-library duration, for arithmetic and comparison.
func (d Duration) Std() time.Duration { return time.Duration(d) }
// String renders the interval the way the document writes it, so an error
// message or a log line reads "30m0s" rather than 1800000000000.
// String renders the interval the way the document writes it.
func (d Duration) String() string { return time.Duration(d).String() }
// Schedule decides when a job is due. The Kind field selects which of
// Interval, Cron, At the store uses to compute nextRun. Empty Kind
// resolves to "interval" so the simplest recurring job needs no
// explicit kind in its JSON.
type Schedule struct {
// Kind is one of ScheduleInterval, ScheduleCron, ScheduleOnce.
// Empty resolves to ScheduleInterval.
Kind string `json:"kind,omitempty"`
// Timing kinds.
const (
// TimingInterval fires on a grid of Interval steps anchored at Start.
TimingInterval = "interval"
// TimingCron fires at each cron match in the instance time zone.
// Day-of-month and day-of-week are ANDed.
TimingCron = "cron"
// TimingOnce fires once at At.
TimingOnce = "once"
)
// Interval is the period for ScheduleInterval. Required when Kind
// is ScheduleInterval; ignored otherwise. It is a Duration rather
// than a time.Duration so the document carries "30m0s" and not the
// nanosecond count that asked an operator to type 1800000000000.
Interval Duration `json:"interval,omitempty"`
var (
// ErrInvalidSpec is returned when a schedule fails validation.
ErrInvalidSpec = errors.New("scheduling: invalid schedule")
// ErrNotFound is returned for an unknown schedule or run.
ErrNotFound = errors.New("scheduling: schedule not found")
// ErrBuiltIn is returned when a change only a user schedule allows is
// asked of a built-in one.
ErrBuiltIn = errors.New("scheduling: built-in schedules cannot be deleted or have their action changed")
)
// Cron is the 5-field cron expression for ScheduleCron. Required
// when Kind is ScheduleCron; ignored otherwise.
Cron string `json:"cron,omitempty"`
// At is the one-shot firing time for ScheduleOnce. Required when
// Kind is ScheduleOnce; ignored otherwise.
At *time.Time `json:"at,omitempty"`
// Start anchors the first run for ScheduleInterval / ScheduleCron.
// Empty means "use creation time" — a freshly-created job with no
// Start still has a finite next_run. Omitted from the wire when
// unset so operator-readable files are not noisy.
// Timing decides when a schedule is due. Times are UTC instants; only a cron
// expression is read in a zone.
type Timing struct {
Kind string `json:"kind"`
Interval Duration `json:"interval,omitempty"`
Cron string `json:"cron,omitempty"`
At *time.Time `json:"at,omitempty"`
// Start anchors the interval grid. Zero means the moment the schedule is
// stored, which the store fills in.
Start time.Time `json:"start"`
}
// Schedule kinds. MarkRun on an unsupported kind returns
// ErrScheduleUnsupported.
const (
// ScheduleInterval fires every Interval after the last successful run
// (or after Start, if never run). The simplest recurring schedule.
ScheduleInterval = "interval"
// ScheduleCron fires at the next cron match after the last run, in that
// run's zone. Day-of-month and day-of-week are ANDed.
ScheduleCron = "cron"
// ScheduleOnce fires once at the configured At time. Subsequent
// MarkRun calls return ErrScheduleUnsupported because there is no
// recurring next-run to compute.
ScheduleOnce = "once"
)
// Validate rejects empty or unknown schedule kinds up front so Create does
// not have to defer the check until MarkRun. Interval additionally requires
// a strictly positive duration; the others defer their full validation.
func (s Schedule) Validate() error {
switch s.Kind {
case "", ScheduleInterval:
if s.Interval <= 0 {
return fmt.Errorf("%w: interval must be positive, got %v", ErrInvalidSpec, s.Interval)
// Validate rejects an unknown kind or a kind missing its field.
func (t Timing) Validate() error {
switch t.Kind {
case TimingInterval:
if t.Interval < Duration(time.Minute) {
return fmt.Errorf("%w: interval must be at least a minute, got %v", ErrInvalidSpec, t.Interval)
}
case ScheduleCron:
if _, err := parseCronSpec(s.Cron); err != nil {
case TimingCron:
if _, err := parseCronSpec(t.Cron); err != nil {
return err
}
case ScheduleOnce:
if s.At == nil {
return fmt.Errorf("%w: once schedule requires an `at` time", ErrInvalidSpec)
case TimingOnce:
if t.At == nil {
return fmt.Errorf("%w: a once schedule needs an at time", ErrInvalidSpec)
}
default:
return fmt.Errorf("%w: unknown schedule kind %q", ErrInvalidSpec, s.Kind)
return fmt.Errorf("%w: unknown timing kind %q", ErrInvalidSpec, t.Kind)
}
return nil
}
// resolve maps the empty kind onto its documented default — "interval" is
// what an operator gets when they leave the field unset on the simplest
// recurring job.
func (s Schedule) resolve() Schedule {
if s.Kind == "" {
s.Kind = ScheduleInterval
}
return s
}
// firstRun returns a never-run job's first fire time: Start (or now) plus
// Interval, At for Once, or the first cron match after Start (or now).
func (s Schedule) firstRun(now time.Time) (time.Time, error) {
switch s.resolve().Kind {
case ScheduleInterval:
if !s.Start.IsZero() {
return s.Start.Add(s.Interval.Std()), nil
// Next returns the first fire time strictly after after, or false when the
// timing never fires again. Interval steps are counted from Start, so a late
// or missed run never shifts the grid; cron is matched in loc.
func (t Timing) Next(after time.Time, loc *time.Location) (time.Time, bool, error) {
switch t.Kind {
case TimingInterval:
step := t.Interval.Std()
if after.Before(t.Start) {
return t.Start.UTC(), true, nil
}
return now.Add(s.Interval.Std()), nil
case ScheduleOnce:
if s.At == nil {
return time.Time{}, fmt.Errorf("%w: once schedule has no at time", ErrScheduleUnsupported)
steps := int64(after.Sub(t.Start)/step) + 1
return t.Start.Add(time.Duration(steps * int64(step))).UTC(), true, nil
case TimingOnce:
if t.At != nil && t.At.After(after) {
return t.At.UTC(), true, nil
}
return *s.At, nil
case ScheduleCron:
sched, err := parseCronSpec(s.Cron)
return time.Time{}, false, nil
case TimingCron:
spec, err := parseCronSpec(t.Cron)
if err != nil {
return time.Time{}, err
return time.Time{}, false, err
}
anchor := now
if !s.Start.IsZero() {
anchor = s.Start
next, err := nextCronRun(spec, after.In(loc))
if err != nil {
return time.Time{}, false, err
}
return nextCronRun(sched, anchor)
return next.UTC(), true, nil
default:
return time.Time{}, fmt.Errorf("%w: unknown kind %q", ErrScheduleUnsupported, s.Kind)
return time.Time{}, false, fmt.Errorf("%w: unknown timing kind %q", ErrInvalidSpec, t.Kind)
}
}
// cronHorizon bounds the next-run scan. A satisfiable expression always
// fires well within it (the sparsest realistic case, Feb 29, recurs every
// four years); only a spec that can never fire — e.g. "0 0 30 2 *", which
// the parser's field ranges cannot reject — exhausts the scan.
// fires well within it; only one that can never fire, such as "0 0 30 2 *",
// exhausts it.
const cronHorizon = 5 * 365 * 24 * time.Hour
// nextCronRun returns the first minute after from's minute, in from's
// location, at which sched is due.
// nextCronRun returns the first minute after from at which sched is due,
// reading wall-clock fields in from's location. A wall-clock minute repeated
// when clocks go back fires only its first time.
func nextCronRun(sched *cronSpec, from time.Time) (time.Time, error) {
loc := from.Location()
t := from.Truncate(time.Minute).Add(time.Minute)
for limit := from.Add(cronHorizon); t.Before(limit); {
if sched.due(t) {
return t, nil
}
if !sched.months.has(int(t.Month())) {
t = time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location()).AddDate(0, 1, 0)
t = time.Date(t.Year(), t.Month()+1, 1, 0, 0, 0, 0, loc)
continue
}
if !sched.hours.has(t.Hour()) {
t = t.Add(time.Hour).Truncate(time.Hour)
t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour()+1, 0, 0, 0, loc)
continue
}
if sched.due(t) && !repeatedWallClock(t) {
return t, nil
}
t = t.Add(time.Minute)
}
return time.Time{}, fmt.Errorf("%w: cron expression does not match any minute within the next five years", ErrInvalidSpec)
}
func (s Schedule) FirstRun(now time.Time) (time.Time, error) { return s.firstRun(now) }
func (s Schedule) NextRun(lastRun time.Time) (time.Time, error) { return s.nextRun(lastRun) }
func (s Schedule) Resolved() Schedule { return s.resolve() }
// nextRun returns the next fire time after a successful run at lastRun. Once
// returns an error.
func (s Schedule) nextRun(lastRun time.Time) (time.Time, error) {
switch s.resolve().Kind {
case ScheduleInterval:
return lastRun.Add(s.Interval.Std()), nil
case ScheduleOnce:
return time.Time{}, fmt.Errorf("%w: once schedule has no next run", ErrScheduleUnsupported)
case ScheduleCron:
sched, err := parseCronSpec(s.Cron)
if err != nil {
return time.Time{}, err
}
return nextCronRun(sched, lastRun)
default:
return time.Time{}, fmt.Errorf("%w: unknown kind %q", ErrScheduleUnsupported, s.Kind)
}
// repeatedWallClock reports whether t's wall-clock hour already happened an
// hour earlier, which is the second pass through an hour the clocks went
// back over.
func repeatedWallClock(t time.Time) bool {
earlier := t.Add(-time.Hour)
return earlier.Hour() == t.Hour() && earlier.Day() == t.Day()
}
+113
View File
@@ -0,0 +1,113 @@
package scheduling
import (
"testing"
"time"
)
func TestTimingNext(t *testing.T) {
sydney, err := time.LoadLocation("Australia/Sydney")
if err != nil {
t.Fatal(err)
}
utc := func(s string) time.Time {
v, err := time.Parse(time.RFC3339, s)
if err != nil {
t.Fatal(err)
}
return v
}
at := utc("2026-11-01T09:00:00Z")
tests := []struct {
name string
timing Timing
loc *time.Location
after time.Time
want time.Time
none bool
}{
{
name: "interval before its start fires at the start",
timing: Timing{Kind: TimingInterval, Interval: Duration(time.Hour), Start: utc("2026-10-01T00:30:00Z")},
after: utc("2026-10-01T00:00:00Z"),
want: utc("2026-10-01T00:30:00Z"),
},
{
name: "interval after three days down stays on its grid",
timing: Timing{Kind: TimingInterval, Interval: Duration(time.Hour), Start: utc("2026-10-01T00:30:00Z")},
after: utc("2026-10-04T07:12:00Z"),
want: utc("2026-10-04T07:30:00Z"),
},
{
name: "interval exactly on a slot moves to the next one",
timing: Timing{Kind: TimingInterval, Interval: Duration(time.Hour), Start: utc("2026-10-01T00:30:00Z")},
after: utc("2026-10-01T02:30:00Z"),
want: utc("2026-10-01T03:30:00Z"),
},
{
name: "cron reads the hour in the instance zone",
timing: Timing{Kind: TimingCron, Cron: "0 9 * * *"},
loc: sydney,
after: utc("2026-07-01T00:00:00Z"),
want: utc("2026-07-01T23:00:00Z"), // 09:00 AEST
},
{
name: "cron keeps local time across the spring-forward change",
timing: Timing{Kind: TimingCron, Cron: "0 9 * * *"},
loc: sydney,
after: utc("2026-10-04T00:00:00Z"), // 11:00 AEDT on the change day
want: utc("2026-10-04T22:00:00Z"), // 09:00 AEDT
},
{
name: "cron in an hour that clocks skip fires the next day",
timing: Timing{Kind: TimingCron, Cron: "30 2 * * *"},
loc: sydney,
after: utc("2026-10-03T15:00:00Z"), // 01:00 AEST, clocks jump 02:00 to 03:00
want: utc("2026-10-04T15:30:00Z"), // 02:30 AEDT next day
},
{
name: "cron in an hour repeated when clocks go back fires once",
timing: Timing{Kind: TimingCron, Cron: "30 2 * * *"},
loc: sydney,
after: utc("2026-04-04T15:31:00Z"), // just after the first 02:30 AEDT
want: utc("2026-04-05T16:30:00Z"), // 02:30 AEST next day, not the repeat
},
{
name: "cron in a half-hour zone",
timing: Timing{Kind: TimingCron, Cron: "0 10 * * *"},
loc: time.FixedZone("ACST", 9*3600+1800),
after: utc("2026-07-01T00:10:00Z"),
want: utc("2026-07-01T00:30:00Z"),
},
{
name: "once before its time",
timing: Timing{Kind: TimingOnce, At: &at},
after: utc("2026-10-01T00:00:00Z"),
want: at,
},
{
name: "once after its time never fires again",
timing: Timing{Kind: TimingOnce, At: &at},
after: at,
none: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
loc := tt.loc
if loc == nil {
loc = time.UTC
}
got, ok, err := tt.timing.Next(tt.after, loc)
if err != nil {
t.Fatal(err)
}
if ok == tt.none {
t.Fatalf("Next ok = %v, want %v", ok, !tt.none)
}
if !got.Equal(tt.want) {
t.Fatalf("Next = %v, want %v", got, tt.want)
}
})
}
}
+16 -3
View File
@@ -11,7 +11,7 @@ import (
)
const (
defaultInterval = time.Minute
defaultInterval = 10 * time.Second
defaultMaxParallel = 4
defaultJobTimeout = time.Hour
)
@@ -28,6 +28,7 @@ const (
phaseSource = "source" // JobSource.Due returned an error
phaseDispatch = "dispatch" // the job was rejected before it ever ran
phaseRun = "run" // Runner.Run failed, panicked or timed out
phaseRecord = "record" // JobSource.Finish failed
)
// sequentialQueueDepth bounds the sequential pool's backlog. Overlap
@@ -229,7 +230,8 @@ func (e *Engine) dispatch(loopCtx, runCtx context.Context, job Job) {
return
}
if !e.claim(job.ID) {
return // an earlier run of this job has not finished; skip this tick
e.finish(loopCtx, job, RunSkipped, nil)
return
}
if job.Pool.resolve() == PoolParallel {
@@ -250,7 +252,9 @@ func (e *Engine) dispatch(loopCtx, runCtx context.Context, job Job) {
case e.queue <- job:
default:
e.release(job.ID)
e.emitError(job, phaseDispatch, errors.New("scheduling: sequential queue full"))
err := errors.New("scheduling: sequential queue full")
e.emitError(job, phaseDispatch, err)
e.finish(loopCtx, job, RunFailed, err)
}
}
@@ -281,8 +285,10 @@ func (e *Engine) runJob(ctx context.Context, job Job) {
elapsed := e.cfg.Clock.Now().Sub(start)
if err != nil {
e.emitError(job, phaseRun, err)
e.finish(ctx, job, RunFailed, err)
return
}
e.finish(ctx, job, RunSucceeded, nil)
e.emit(KindJobRun, job, map[string]any{
"job": job.ID,
"pool": string(job.Pool.resolve()),
@@ -299,6 +305,13 @@ func (e *Engine) safeRun(ctx context.Context, job Job) (err error) {
return e.runner.Run(ctx, job)
}
// finish records a run's result, reporting a failure to record it.
func (e *Engine) finish(ctx context.Context, job Job, result RunResult, runErr error) {
if err := e.source.Finish(ctx, job, result, runErr); err != nil {
e.emitError(job, phaseRecord, err)
}
}
// claim marks a job as queued-or-running, reporting false if it already was.
func (e *Engine) claim(id string) bool {
e.mu.Lock()
-1
View File
@@ -36,7 +36,6 @@ var dashboardPages = []DashboardPage{
{Path: "/org/credential-bindings", Label: "Credential bindings", Description: "Service credentials granted to agent identities."},
{Path: "/org/models", Label: "Models", Description: "Organisation providers and model aliases."},
{Path: "/org/instructions", Label: "Instructions", Description: "Archie's identity, tone and standing instructions for the organisation."},
{Path: "/org/schedules", Label: "Schedules", Description: "Timetabled work."},
{Path: "/org/playbooks", Label: "Playbooks", Description: "Edit event-driven automation rules."},
{Path: "/settings/authentication", Label: "Authentication", Description: "Instance URL and OIDC sign-in."},
{Path: "/workflows", Label: "Workflows", Description: "Workflows and run history."},
+1 -1
View File
@@ -28,7 +28,7 @@ type IntegrationSource interface {
// and settings whose secrets are references, never values.
var readableKinds = []string{
"workflow-execution-settings", "workflow-enablement", "agent-profiles", "skills",
"schedules", "eda-playbooks", "credential-bindings", "identity-grants",
"eda-playbooks", "credential-bindings", "identity-grants",
"soul", "task-policy", "org-model-policy",
}
@@ -2,7 +2,6 @@ package controlplanestore
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
@@ -13,7 +12,6 @@ import (
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/agent"
"github.com/samcharles93/archie-core/internal/domain/applystatus"
"github.com/samcharles93/archie-core/internal/domain/scheduling"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
)
@@ -213,36 +211,3 @@ func sendUpdate[T any](ctx context.Context, out chan<- T, update T) bool {
return false
}
}
// KeepSchedules reads the schedules now and every interval after, so the apply
// status is reported before the scheduler first polls.
func (c *Client) KeepSchedules(ctx context.Context, interval time.Duration) {
keepLoading(ctx, interval, func() { _, _, _ = c.Schedules(ctx) })
}
func (c *Client) Schedules(ctx context.Context) ([]scheduling.JobSpec, int64, error) {
response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: SchedulesKind})
if err != nil {
c.ApplyStatus.Report(ctx, SchedulesKind, 0, err)
return nil, 0, controlplanerpc.ClientError(err)
}
var jobs []scheduling.JobSpec
if err := json.Unmarshal(response.Resource.ValueJson, &jobs); err != nil {
c.ApplyStatus.Report(ctx, SchedulesKind, response.Resource.Version, err)
return nil, 0, err
}
c.ApplyStatus.Report(ctx, SchedulesKind, response.Resource.Version, nil)
return jobs, response.Resource.Version, nil
}
func (c *Client) ReplaceSchedules(ctx context.Context, jobs []scheduling.JobSpec, expectedVersion int64, actor, source, requestID string) (int64, error) {
value, err := json.Marshal(jobs)
if err != nil {
return 0, err
}
response, err := c.rpc.Command(ctx, &pb.CommandRequest{Kind: SchedulesKind, Command: "replace", ValueJson: value, ExpectedVersion: expectedVersion, Actor: actor, Source: source, RequestId: requestID})
if err != nil {
return 0, controlplanerpc.ClientError(err)
}
return response.Resource.Version, nil
}
@@ -8,7 +8,7 @@ import (
// Schemas are not declared here: each Definition names its document type, and
// Definition.Descriptor derives the JSON Schema from it (internal/infrastructure/controlplanestore/schema.go).
func builtinDefinitions(steps workflow.StepRegistry, settings map[string]any) []Definition {
definitions := []Definition{taskPolicyDefinition(), workflowDefinition(), workflowDefinitionsDefinition(steps, settings), workflowDraftsDefinition(), workflowEnablementDefinition(), curatorDefinition(), soulDefinition(), scheduleDefinition(), agentProfileDefinition(), playbooksDefinition(), skillsDefinition(), credentialBindingsDefinition(), identityGrantsDefinition(), orgModelPolicyDefinition(), forgeConnectionsDefinition()}
definitions := []Definition{taskPolicyDefinition(), workflowDefinition(), workflowDefinitionsDefinition(steps, settings), workflowDraftsDefinition(), workflowEnablementDefinition(), curatorDefinition(), soulDefinition(), agentProfileDefinition(), playbooksDefinition(), skillsDefinition(), credentialBindingsDefinition(), identityGrantsDefinition(), orgModelPolicyDefinition(), forgeConnectionsDefinition()}
definitions = append(definitions, modelDefinitions()...)
definitions = append(definitions, operationalDefinitions()...)
return definitions
@@ -67,6 +67,9 @@ func operationalDefinitions() []Definition {
// Live: the retention sweep reads the document on every tick, so a
// change applies to the next sweep without a restart.
auditRetentionDefinition(),
// Live: the scheduler reads the zone on every claim and the State Store
// reads the retention on every sweep.
scheduleSettingsDefinition(),
}
}
@@ -182,7 +182,7 @@ var instanceOnlyKinds = map[string]bool{
TaskPolicyKind: true, ToolSettingsKind: true,
PluginSettingsKind: true, ContainerRuntimePoliciesKind: true, AgentProfileKind: true,
ExtensionSettingsKind: true, UpdateSettingsKind: true, WorkflowExecutionSettingsKind: true,
AuditRetentionKind: true,
AuditRetentionKind: true, ScheduleSettingsKind: true,
}
// checkOrgWrite applies the rules a resource's static validation cannot: the
@@ -0,0 +1,60 @@
package controlplanestore
import (
"bytes"
"encoding/json"
"fmt"
"time"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/scheduling"
)
// ScheduleSettingsKind is the instance's schedule settings: the zone cron
// expressions are read in, and how much run history is kept.
const ScheduleSettingsKind = "schedule-settings"
type scheduleSettings struct {
TimeZone string `json:"time_zone" title:"Time zone"`
RunRetention string `json:"run_retention" title:"Keep runs for"`
RunRetentionCount int `json:"run_retention_count" title:"Runs kept per schedule"`
}
// defaultScheduleSettings keeps a week of runs, at most 100 per schedule.
var defaultScheduleSettings = scheduleSettings{TimeZone: "UTC", RunRetention: "168h", RunRetentionCount: 100}
func scheduleSettingsDefinition() Definition {
return Definition{
Kind: ScheduleSettingsKind, Title: "Schedule settings", ApplyMode: "live",
Document: scheduleSettings{},
Seed: func(config.Config) any { return defaultScheduleSettings },
Validate: func(input []byte) error {
_, err := ScheduleSettings(input)
return err
},
}
}
// ScheduleSettings decodes and checks a stored schedule-settings document.
// The State Store reads it with this same parser, so a value the control
// plane accepted is one the scheduler can use.
func ScheduleSettings(document []byte) (scheduling.Settings, error) {
var doc scheduleSettings
decoder := json.NewDecoder(bytes.NewReader(document))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&doc); err != nil {
return scheduling.Settings{}, fmt.Errorf("decode %s: %w", ScheduleSettingsKind, err)
}
loc, err := time.LoadLocation(doc.TimeZone)
if err != nil || doc.TimeZone == "" || doc.TimeZone == "Local" {
return scheduling.Settings{}, fmt.Errorf("time_zone must be an IANA zone such as Australia/Sydney or UTC")
}
retention, err := time.ParseDuration(doc.RunRetention)
if err != nil || retention < time.Hour {
return scheduling.Settings{}, fmt.Errorf("run_retention must be a duration of at least 1h, such as 168h")
}
if doc.RunRetentionCount < 1 {
return scheduling.Settings{}, fmt.Errorf("run_retention_count must be at least 1")
}
return scheduling.Settings{Location: loc, RunRetention: retention, RunRetentionCount: doc.RunRetentionCount}, nil
}
@@ -1,82 +0,0 @@
package controlplanestore
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/scheduling"
)
const SchedulesKind = "schedules"
func scheduleDefinition() Definition {
return Definition{
Kind: SchedulesKind,
Title: "Schedules",
Document: []scheduling.JobSpec{},
ApplyMode: "live",
Seed: func(config.Config) any { return []scheduling.JobSpec{} },
Validate: func(input []byte) error {
return validateAs(input, validateSchedules)
},
Normalize: normalizeSchedules,
}
}
func validateSchedules(jobs []scheduling.JobSpec) error {
seen := make(map[string]struct{}, len(jobs))
for _, job := range jobs {
if err := scheduling.RefuseDangerousJob(job); err != nil {
return err
}
if strings.TrimSpace(job.ID) == "" {
return fmt.Errorf("schedule ID is required")
}
if _, exists := seen[job.ID]; exists {
return fmt.Errorf("duplicate schedule %q", job.ID)
}
seen[job.ID] = struct{}{}
switch job.Kind {
case scheduling.KindWorkflow:
case scheduling.KindChat:
if job.Target.Channel == "" || job.Target.ChatID == "" || strings.TrimSpace(job.Payload.Text) == "" {
return fmt.Errorf("chat schedule %q needs a channel, chat ID and message", job.ID)
}
default:
return fmt.Errorf("schedule %q has unsupported kind %q", job.ID, job.Kind)
}
if err := job.Schedule.Validate(); err != nil {
return err
}
if err := scheduling.Pool(job.Pool).Validate(); err != nil {
return err
}
}
return nil
}
func normalizeSchedules(input []byte) ([]byte, error) {
var jobs []scheduling.JobSpec
if err := json.Unmarshal(input, &jobs); err != nil {
return nil, err
}
now := time.Now().UTC()
for i := range jobs {
jobs[i].Schedule = jobs[i].Schedule.Resolved()
if jobs[i].NextRun.IsZero() {
next, err := jobs[i].Schedule.FirstRun(now)
if err != nil {
return nil, err
}
jobs[i].NextRun = next.UTC()
}
if jobs[i].Created.IsZero() {
jobs[i].Created = now
}
jobs[i].Updated = now
}
return json.Marshal(jobs)
}
@@ -156,73 +156,6 @@
},
"valid": false
}
],
"schedules": [
{
"why": "a single valid workflow job",
"value": [
{
"id": "daily",
"kind": "workflow",
"schedule": {
"kind": "interval",
"interval": "24h0m0s"
}
}
],
"valid": true
},
{
"why": "a cron job with a pool the server recognises",
"value": [
{
"id": "nightly",
"kind": "workflow",
"pool": "parallel",
"schedule": {
"kind": "cron",
"cron": "0 3 * * *"
}
}
],
"valid": true
},
{
"why": "a job with no id",
"value": [
{
"id": "",
"kind": "workflow",
"schedule": {
"kind": "interval",
"interval": "24h0m0s"
}
}
],
"valid": false
},
{
"why": "two jobs sharing an id",
"value": [
{
"id": "daily",
"kind": "workflow",
"schedule": {
"kind": "interval",
"interval": "24h0m0s"
}
},
{
"id": "daily",
"kind": "workflow",
"schedule": {
"kind": "interval",
"interval": "1h0m0s"
}
}
],
"valid": false
}
]
}
}
@@ -1,66 +0,0 @@
// Package crondelivery delivers due scheduled jobs: ChatCourier sends a chat
// message, WorkflowTask submits work, and Router picks one per job kind.
package crondelivery
import (
"context"
"errors"
"fmt"
"time"
"github.com/samcharles93/archie-core/internal/domain/scheduling"
)
// SpecLookup resolves a job id to its stored spec.
type SpecLookup interface {
// Get returns the job and whether it was found; the error is reserved
// for I/O failures, matching scheduleResourceStore.Get.
Get(ctx context.Context, id string) (scheduling.JobSpec, bool, error)
}
// RunRecorder advances a job's schedule after a successful run.
type RunRecorder interface {
// MarkRun records that id ran at runAt and advances NextRun to the
// schedule's next firing.
MarkRun(ctx context.Context, id string, runAt time.Time) error
}
// RouterStore is what the Router needs from persistence: resolve a job id to
// its spec, and record the run once it succeeds. The per-kind runners still
// take the narrower SpecLookup -- they dispatch one already-hydrated job and
// have no business moving its schedule.
type RouterStore interface {
SpecLookup
RunRecorder
}
// Courier sends one chat message to target. It must honour ctx.
type Courier func(ctx context.Context, target scheduling.Target, text string) error
// TaskSubmitter submits one unit of work.
type TaskSubmitter interface {
Submit(ctx context.Context, identity, title, body string) error
}
// errSpecMissing reports a job the store does not know about. It is a run
// failure rather than a dispatch refusal: the source reported this job due, so
// failing to hydrate it is a real inconsistency, not a misconfiguration.
var errSpecMissing = errors.New("crondelivery: job spec not found")
// hydrate loads the job's persisted spec, wrapping both a store error and the
// not-found case so a caller can match on one sentinel.
func hydrate(ctx context.Context, specs SpecLookup, job scheduling.Job) (scheduling.JobSpec, error) {
spec, ok, err := specs.Get(ctx, job.ID)
if err != nil {
return scheduling.JobSpec{}, fmt.Errorf("crondelivery: load job %q: %w", job.ID, err)
}
if !ok {
return scheduling.JobSpec{}, fmt.Errorf("%w: id %q", errSpecMissing, job.ID)
}
return spec, nil
}
// Compile-time check that the production store satisfies the contract. It
// lives in internal/app/archied, which imports this package, so the assertion
// is made there (scheduling.go) rather than here, where it would be an import
// cycle.
@@ -1,67 +0,0 @@
package crondelivery
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/domain/scheduling"
)
// Router runs a due job with the runner for its kind and advances its
// schedule. A job whose kind has no runner fails its run and still advances,
// so it is reported once per firing rather than on every tick.
type Router struct {
specs RouterStore
runners map[string]scheduling.Runner
}
// NewRouter builds a router over specs and runners. An empty kind is
// KindChat.
func NewRouter(specs RouterStore, runners map[string]scheduling.Runner) (*Router, error) {
if specs == nil {
return nil, errors.New("crondelivery: spec lookup must not be nil")
}
if len(runners) == 0 {
return nil, errors.New("crondelivery: at least one runner is required")
}
return &Router{specs: specs, runners: runners}, nil
}
// Run implements scheduling.Runner: hydrate, resolve the kind, dispatch.
func (r *Router) Run(ctx context.Context, job scheduling.Job) error {
if err := ctx.Err(); err != nil {
return err
}
spec, err := hydrate(ctx, r.specs, job)
if err != nil {
return err
}
kind := spec.Kind
if kind == "" {
kind = scheduling.KindChat
}
runner, ok := r.runners[kind]
if !ok {
// The kind is in the message: the operator's next step is to add a
// runner for it.
refused := fmt.Errorf("crondelivery: no runner registered for job kind %q", strings.TrimSpace(kind))
return errors.Join(refused, r.recordRun(ctx, job))
}
if err := runner.Run(ctx, job); err != nil {
return err
}
return r.recordRun(ctx, job)
}
// recordRun advances the job's schedule.
// ErrScheduleUnsupported (a one-shot) is ignored.
func (r *Router) recordRun(ctx context.Context, job scheduling.Job) error {
if err := r.specs.MarkRun(ctx, job.ID, time.Now()); err != nil && !errors.Is(err, scheduling.ErrScheduleUnsupported) {
return fmt.Errorf("crondelivery: record run of job %q: %w", job.ID, err)
}
return nil
}
@@ -1,55 +0,0 @@
package crondelivery
import (
"context"
"testing"
"time"
"github.com/samcharles93/archie-core/internal/domain/scheduling"
)
type fakeRouterStore struct {
spec scheduling.JobSpec
marked int
}
func (f *fakeRouterStore) Get(context.Context, string) (scheduling.JobSpec, bool, error) {
return f.spec, true, nil
}
func (f *fakeRouterStore) MarkRun(context.Context, string, time.Time) error {
f.marked++
return nil
}
type okRunner struct{}
func (okRunner) Run(context.Context, scheduling.Job) error { return nil }
// A job no runner can deliver must fail its run, so the engine does not
// report it as run, and still advance, so it does not fire on every tick.
func TestRouterAdvancesEveryJob(t *testing.T) {
tests := []struct {
kind string
wantErr bool
}{
{kind: scheduling.KindChat},
{kind: scheduling.KindWorkflow, wantErr: true},
}
for _, tt := range tests {
t.Run(tt.kind, func(t *testing.T) {
store := &fakeRouterStore{spec: scheduling.JobSpec{ID: "j", Kind: tt.kind}}
router, err := NewRouter(store, map[string]scheduling.Runner{scheduling.KindChat: okRunner{}})
if err != nil {
t.Fatal(err)
}
err = router.Run(t.Context(), scheduling.Job{ID: "j"})
if (err != nil) != tt.wantErr {
t.Fatalf("err = %v, want error %v", err, tt.wantErr)
}
if store.marked != 1 {
t.Fatalf("schedule advanced %d times, want 1", store.marked)
}
})
}
}
@@ -1,90 +0,0 @@
package crondelivery
import (
"context"
"errors"
"fmt"
"strings"
"github.com/samcharles93/archie-core/internal/domain/scheduling"
)
// ChatCourier delivers a job's payload text to a chat. It is the runner behind
// the "chat" kind and the epic's headline case: a daily status summary, which
// the blueprints slice will parameterise.
type ChatCourier struct {
specs SpecLookup
courier Courier
}
// NewChatCourier builds the chat runner over a spec lookup and the courier the
// deployment supplies.
func NewChatCourier(specs SpecLookup, courier Courier) (*ChatCourier, error) {
if specs == nil {
return nil, errors.New("crondelivery: spec lookup must not be nil")
}
if courier == nil {
return nil, errors.New("crondelivery: courier must not be nil")
}
return &ChatCourier{specs: specs, courier: courier}, nil
}
// Run sends the job's payload to its chat. A cancelled ctx sends nothing.
func (c *ChatCourier) Run(ctx context.Context, job scheduling.Job) error {
if err := ctx.Err(); err != nil {
return err
}
spec, err := hydrate(ctx, c.specs, job)
if err != nil {
return err
}
if err := c.courier(ctx, spec.Target, spec.Payload.Text); err != nil {
return fmt.Errorf("crondelivery: deliver job %q to %s:%s: %w", job.ID, spec.Target.Channel, spec.Target.ChatID, err)
}
return nil
}
// WorkflowTask submits a job as a unit of work. It is the runner behind the
// "workflow" kind, so a scheduled job reaches the same task lifecycle —
// scheduling, retries, gates, PR opening — that every other intake path feeds.
type WorkflowTask struct {
specs SpecLookup
submitter TaskSubmitter
}
// NewWorkflowTask builds the workflow runner over a spec lookup and the
// submitter the deployment supplies.
func NewWorkflowTask(specs SpecLookup, submitter TaskSubmitter) (*WorkflowTask, error) {
if specs == nil {
return nil, errors.New("crondelivery: spec lookup must not be nil")
}
if submitter == nil {
return nil, errors.New("crondelivery: task submitter must not be nil")
}
return &WorkflowTask{specs: specs, submitter: submitter}, nil
}
// Run submits the job as work, titled by Detail or the job id.
func (w *WorkflowTask) Run(ctx context.Context, job scheduling.Job) error {
if err := ctx.Err(); err != nil {
return err
}
spec, err := hydrate(ctx, w.specs, job)
if err != nil {
return err
}
title := strings.TrimSpace(spec.Detail)
if title == "" {
title = job.ID
}
if err := w.submitter.Submit(ctx, job.ID, title, spec.Payload.Text); err != nil {
return fmt.Errorf("crondelivery: submit job %q: %w", job.ID, err)
}
return nil
}
// compile-time checks: the two deliveries are the engine's contract.
var (
_ scheduling.Runner = (*ChatCourier)(nil)
_ scheduling.Runner = (*WorkflowTask)(nil)
)
+7
View File
@@ -30,3 +30,10 @@ func isUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23505"
}
// isForeignKeyViolation reports whether err is a PostgreSQL foreign-key
// violation (SQLSTATE 23503).
func isForeignKeyViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23503"
}
@@ -0,0 +1,49 @@
-- Schedules leave the schedules control-plane resource for their own tables:
-- running a schedule records a run row and never rewrites the definition, so
-- an operator's edit and a firing cannot conflict. A run is unique by schedule
-- and slot, which is what stops two schedulers firing the same slot twice.
-- +goose Up
CREATE TABLE schedules (
id text PRIMARY KEY CHECK (id <> ''),
owner_kind text NOT NULL CHECK (owner_kind IN ('instance', 'org')),
owner_id text NOT NULL DEFAULT '',
name text NOT NULL CHECK (name <> ''),
enabled boolean NOT NULL DEFAULT true,
built_in boolean NOT NULL DEFAULT false,
timing_kind text NOT NULL CHECK (timing_kind IN ('interval', 'cron', 'once')),
interval_seconds bigint NOT NULL DEFAULT 0,
cron text NOT NULL DEFAULT '',
run_at timestamptz,
anchor timestamptz NOT NULL,
next_run timestamptz,
-- The zone next_run was computed in, so a cron schedule is recomputed
-- when the instance zone changes.
zone text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CHECK ((owner_kind = 'instance') = (owner_id = ''))
);
CREATE INDEX idx_schedules_due ON schedules (next_run) WHERE enabled AND next_run IS NOT NULL;
CREATE TABLE schedule_runs (
id bigserial PRIMARY KEY,
schedule_id text NOT NULL REFERENCES schedules (id) ON DELETE CASCADE,
scheduled_for timestamptz NOT NULL,
started_at timestamptz,
finished_at timestamptz,
result text NOT NULL CHECK (result IN ('pending', 'running', 'succeeded', 'failed', 'skipped')),
error text NOT NULL DEFAULT '',
-- capture_id is the schedule-fired capture the run recorded; the tasks it
-- started are the binding dispatches against that capture.
capture_id text NOT NULL DEFAULT '',
UNIQUE (schedule_id, scheduled_for)
);
CREATE INDEX idx_schedule_runs_latest ON schedule_runs (schedule_id, scheduled_for DESC);
CREATE INDEX idx_schedule_runs_open ON schedule_runs (result) WHERE result IN ('pending', 'running');
DELETE FROM resources WHERE kind = 'schedules';
-- +goose Down
DROP TABLE schedule_runs;
DROP TABLE schedules;
@@ -439,6 +439,35 @@ type RunCredential struct {
ExpiresAt time.Time
}
type Schedule struct {
ID string
OwnerKind string
OwnerID string
Name string
Enabled bool
BuiltIn bool
TimingKind string
IntervalSeconds int64
Cron string
RunAt pgtype.Timestamptz
Anchor time.Time
NextRun pgtype.Timestamptz
Zone string
CreatedAt time.Time
UpdatedAt time.Time
}
type ScheduleRun struct {
ID int64
ScheduleID string
ScheduledFor time.Time
StartedAt pgtype.Timestamptz
FinishedAt pgtype.Timestamptz
Result string
Error string
CaptureID string
}
type Session struct {
SessionID string
Platform string
@@ -0,0 +1,571 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: schedules.sql
package postgresdb
import (
"context"
"time"
"github.com/jackc/pgx/v5/pgtype"
)
const deleteSchedule = `-- name: DeleteSchedule :execrows
DELETE FROM schedules WHERE id = $1
`
func (q *Queries) DeleteSchedule(ctx context.Context, id string) (int64, error) {
result, err := q.db.Exec(ctx, deleteSchedule, id)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const failStaleRuns = `-- name: FailStaleRuns :exec
UPDATE schedule_runs SET result = 'failed', error = 'no result was recorded', finished_at = $1
WHERE result = 'running' AND started_at < $2
`
type FailStaleRunsParams struct {
FinishedAt pgtype.Timestamptz
StartedAt pgtype.Timestamptz
}
func (q *Queries) FailStaleRuns(ctx context.Context, arg FailStaleRunsParams) error {
_, err := q.db.Exec(ctx, failStaleRuns, arg.FinishedAt, arg.StartedAt)
return err
}
const finishScheduleRun = `-- name: FinishScheduleRun :one
UPDATE schedule_runs SET result = $2, error = $3, finished_at = $4
WHERE id = $1 AND result = 'running'
RETURNING schedule_id
`
type FinishScheduleRunParams struct {
ID int64
Result string
Error string
FinishedAt pgtype.Timestamptz
}
func (q *Queries) FinishScheduleRun(ctx context.Context, arg FinishScheduleRunParams) (string, error) {
row := q.db.QueryRow(ctx, finishScheduleRun,
arg.ID,
arg.Result,
arg.Error,
arg.FinishedAt,
)
var schedule_id string
err := row.Scan(&schedule_id)
return schedule_id, err
}
const getSchedule = `-- name: GetSchedule :one
SELECT id, owner_kind, owner_id, name, enabled, built_in, timing_kind, interval_seconds, cron, run_at, anchor, next_run, zone, created_at, updated_at FROM schedules WHERE id = $1
`
func (q *Queries) GetSchedule(ctx context.Context, id string) (Schedule, error) {
row := q.db.QueryRow(ctx, getSchedule, id)
var i Schedule
err := row.Scan(
&i.ID,
&i.OwnerKind,
&i.OwnerID,
&i.Name,
&i.Enabled,
&i.BuiltIn,
&i.TimingKind,
&i.IntervalSeconds,
&i.Cron,
&i.RunAt,
&i.Anchor,
&i.NextRun,
&i.Zone,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const insertBuiltinSchedule = `-- name: InsertBuiltinSchedule :exec
INSERT INTO schedules (id, owner_kind, owner_id, name, enabled, built_in, timing_kind, interval_seconds, anchor, next_run, zone)
VALUES ($1, 'instance', '', $2, true, true, 'interval', $3, $4, $5, $6)
ON CONFLICT (id) DO NOTHING
`
type InsertBuiltinScheduleParams struct {
ID string
Name string
IntervalSeconds int64
Anchor time.Time
NextRun pgtype.Timestamptz
Zone string
}
func (q *Queries) InsertBuiltinSchedule(ctx context.Context, arg InsertBuiltinScheduleParams) error {
_, err := q.db.Exec(ctx, insertBuiltinSchedule,
arg.ID,
arg.Name,
arg.IntervalSeconds,
arg.Anchor,
arg.NextRun,
arg.Zone,
)
return err
}
const insertScheduleRun = `-- name: InsertScheduleRun :one
INSERT INTO schedule_runs (schedule_id, scheduled_for, started_at, result)
VALUES ($1, $2, $3, $4)
ON CONFLICT (schedule_id, scheduled_for) DO NOTHING
RETURNING id, schedule_id, scheduled_for, started_at, finished_at, result, error, capture_id
`
type InsertScheduleRunParams struct {
ScheduleID string
ScheduledFor time.Time
StartedAt pgtype.Timestamptz
Result string
}
func (q *Queries) InsertScheduleRun(ctx context.Context, arg InsertScheduleRunParams) (ScheduleRun, error) {
row := q.db.QueryRow(ctx, insertScheduleRun,
arg.ScheduleID,
arg.ScheduledFor,
arg.StartedAt,
arg.Result,
)
var i ScheduleRun
err := row.Scan(
&i.ID,
&i.ScheduleID,
&i.ScheduledFor,
&i.StartedAt,
&i.FinishedAt,
&i.Result,
&i.Error,
&i.CaptureID,
)
return i, err
}
const latestScheduleRuns = `-- name: LatestScheduleRuns :many
SELECT DISTINCT ON (schedule_id) id, schedule_id, scheduled_for, started_at, finished_at, result, error, capture_id FROM schedule_runs ORDER BY schedule_id, scheduled_for DESC
`
func (q *Queries) LatestScheduleRuns(ctx context.Context) ([]ScheduleRun, error) {
rows, err := q.db.Query(ctx, latestScheduleRuns)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ScheduleRun
for rows.Next() {
var i ScheduleRun
if err := rows.Scan(
&i.ID,
&i.ScheduleID,
&i.ScheduledFor,
&i.StartedAt,
&i.FinishedAt,
&i.Result,
&i.Error,
&i.CaptureID,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listScheduleRuns = `-- name: ListScheduleRuns :many
SELECT id, schedule_id, scheduled_for, started_at, finished_at, result, error, capture_id FROM schedule_runs WHERE schedule_id = $1 ORDER BY scheduled_for DESC LIMIT $2
`
type ListScheduleRunsParams struct {
ScheduleID string
Limit int32
}
func (q *Queries) ListScheduleRuns(ctx context.Context, arg ListScheduleRunsParams) ([]ScheduleRun, error) {
rows, err := q.db.Query(ctx, listScheduleRuns, arg.ScheduleID, arg.Limit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ScheduleRun
for rows.Next() {
var i ScheduleRun
if err := rows.Scan(
&i.ID,
&i.ScheduleID,
&i.ScheduledFor,
&i.StartedAt,
&i.FinishedAt,
&i.Result,
&i.Error,
&i.CaptureID,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listSchedules = `-- name: ListSchedules :many
SELECT id, owner_kind, owner_id, name, enabled, built_in, timing_kind, interval_seconds, cron, run_at, anchor, next_run, zone, created_at, updated_at FROM schedules ORDER BY built_in, name, id
`
// Schedules and their runs (internal/domain/scheduling).
func (q *Queries) ListSchedules(ctx context.Context) ([]Schedule, error) {
rows, err := q.db.Query(ctx, listSchedules)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Schedule
for rows.Next() {
var i Schedule
if err := rows.Scan(
&i.ID,
&i.OwnerKind,
&i.OwnerID,
&i.Name,
&i.Enabled,
&i.BuiltIn,
&i.TimingKind,
&i.IntervalSeconds,
&i.Cron,
&i.RunAt,
&i.Anchor,
&i.NextRun,
&i.Zone,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockDueSchedules = `-- name: LockDueSchedules :many
SELECT id, owner_kind, owner_id, name, enabled, built_in, timing_kind, interval_seconds, cron, run_at, anchor, next_run, zone, created_at, updated_at FROM schedules
WHERE enabled AND next_run IS NOT NULL AND next_run <= $1
ORDER BY next_run
FOR UPDATE SKIP LOCKED
`
func (q *Queries) LockDueSchedules(ctx context.Context, nextRun pgtype.Timestamptz) ([]Schedule, error) {
rows, err := q.db.Query(ctx, lockDueSchedules, nextRun)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Schedule
for rows.Next() {
var i Schedule
if err := rows.Scan(
&i.ID,
&i.OwnerKind,
&i.OwnerID,
&i.Name,
&i.Enabled,
&i.BuiltIn,
&i.TimingKind,
&i.IntervalSeconds,
&i.Cron,
&i.RunAt,
&i.Anchor,
&i.NextRun,
&i.Zone,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockSchedule = `-- name: LockSchedule :one
SELECT id, owner_kind, owner_id, name, enabled, built_in, timing_kind, interval_seconds, cron, run_at, anchor, next_run, zone, created_at, updated_at FROM schedules WHERE id = $1 FOR UPDATE
`
func (q *Queries) LockSchedule(ctx context.Context, id string) (Schedule, error) {
row := q.db.QueryRow(ctx, lockSchedule, id)
var i Schedule
err := row.Scan(
&i.ID,
&i.OwnerKind,
&i.OwnerID,
&i.Name,
&i.Enabled,
&i.BuiltIn,
&i.TimingKind,
&i.IntervalSeconds,
&i.Cron,
&i.RunAt,
&i.Anchor,
&i.NextRun,
&i.Zone,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const lockStaleZoneCronSchedules = `-- name: LockStaleZoneCronSchedules :many
SELECT id, owner_kind, owner_id, name, enabled, built_in, timing_kind, interval_seconds, cron, run_at, anchor, next_run, zone, created_at, updated_at FROM schedules
WHERE enabled AND timing_kind = 'cron' AND zone <> $1
FOR UPDATE SKIP LOCKED
`
func (q *Queries) LockStaleZoneCronSchedules(ctx context.Context, zone string) ([]Schedule, error) {
rows, err := q.db.Query(ctx, lockStaleZoneCronSchedules, zone)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Schedule
for rows.Next() {
var i Schedule
if err := rows.Scan(
&i.ID,
&i.OwnerKind,
&i.OwnerID,
&i.Name,
&i.Enabled,
&i.BuiltIn,
&i.TimingKind,
&i.IntervalSeconds,
&i.Cron,
&i.RunAt,
&i.Anchor,
&i.NextRun,
&i.Zone,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const pruneScheduleRuns = `-- name: PruneScheduleRuns :execrows
WITH ranked AS (
SELECT id AS run_id, finished_at AS ended, row_number() OVER (PARTITION BY schedule_id ORDER BY scheduled_for DESC) AS position
FROM schedule_runs WHERE result NOT IN ('pending', 'running')
)
DELETE FROM schedule_runs WHERE id IN (
SELECT run_id FROM ranked WHERE ended < $1::timestamptz OR position > $2::bigint
)
`
type PruneScheduleRunsParams struct {
Before time.Time
Keep int64
}
func (q *Queries) PruneScheduleRuns(ctx context.Context, arg PruneScheduleRunsParams) (int64, error) {
result, err := q.db.Exec(ctx, pruneScheduleRuns, arg.Before, arg.Keep)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const recentFinishedResults = `-- name: RecentFinishedResults :many
SELECT result FROM schedule_runs
WHERE schedule_id = $1 AND result IN ('succeeded', 'failed')
ORDER BY scheduled_for DESC
LIMIT $2
`
type RecentFinishedResultsParams struct {
ScheduleID string
Limit int32
}
func (q *Queries) RecentFinishedResults(ctx context.Context, arg RecentFinishedResultsParams) ([]string, error) {
rows, err := q.db.Query(ctx, recentFinishedResults, arg.ScheduleID, arg.Limit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []string
for rows.Next() {
var result string
if err := rows.Scan(&result); err != nil {
return nil, err
}
items = append(items, result)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const setScheduleNextRun = `-- name: SetScheduleNextRun :exec
UPDATE schedules SET next_run = $2, zone = $3 WHERE id = $1
`
type SetScheduleNextRunParams struct {
ID string
NextRun pgtype.Timestamptz
Zone string
}
func (q *Queries) SetScheduleNextRun(ctx context.Context, arg SetScheduleNextRunParams) error {
_, err := q.db.Exec(ctx, setScheduleNextRun, arg.ID, arg.NextRun, arg.Zone)
return err
}
const setScheduleRunCapture = `-- name: SetScheduleRunCapture :execrows
UPDATE schedule_runs SET capture_id = $2 WHERE id = $1
`
type SetScheduleRunCaptureParams struct {
ID int64
CaptureID string
}
func (q *Queries) SetScheduleRunCapture(ctx context.Context, arg SetScheduleRunCaptureParams) (int64, error) {
result, err := q.db.Exec(ctx, setScheduleRunCapture, arg.ID, arg.CaptureID)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const startRequestedRuns = `-- name: StartRequestedRuns :many
UPDATE schedule_runs r SET result = 'running', started_at = $1
FROM schedules s
WHERE r.result = 'pending' AND s.id = r.schedule_id
RETURNING r.id, r.schedule_id, r.scheduled_for, s.name, s.built_in
`
type StartRequestedRunsRow struct {
ID int64
ScheduleID string
ScheduledFor time.Time
Name string
BuiltIn bool
}
func (q *Queries) StartRequestedRuns(ctx context.Context, startedAt pgtype.Timestamptz) ([]StartRequestedRunsRow, error) {
rows, err := q.db.Query(ctx, startRequestedRuns, startedAt)
if err != nil {
return nil, err
}
defer rows.Close()
var items []StartRequestedRunsRow
for rows.Next() {
var i StartRequestedRunsRow
if err := rows.Scan(
&i.ID,
&i.ScheduleID,
&i.ScheduledFor,
&i.Name,
&i.BuiltIn,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const upsertSchedule = `-- name: UpsertSchedule :one
INSERT INTO schedules (id, owner_kind, owner_id, name, enabled, built_in, timing_kind, interval_seconds, cron, run_at, anchor, next_run, zone)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
ON CONFLICT (id) DO UPDATE SET
owner_kind = excluded.owner_kind, owner_id = excluded.owner_id, name = excluded.name,
enabled = excluded.enabled, timing_kind = excluded.timing_kind, interval_seconds = excluded.interval_seconds,
cron = excluded.cron, run_at = excluded.run_at, anchor = excluded.anchor, next_run = excluded.next_run,
zone = excluded.zone, updated_at = now()
RETURNING id, owner_kind, owner_id, name, enabled, built_in, timing_kind, interval_seconds, cron, run_at, anchor, next_run, zone, created_at, updated_at
`
type UpsertScheduleParams struct {
ID string
OwnerKind string
OwnerID string
Name string
Enabled bool
BuiltIn bool
TimingKind string
IntervalSeconds int64
Cron string
RunAt pgtype.Timestamptz
Anchor time.Time
NextRun pgtype.Timestamptz
Zone string
}
func (q *Queries) UpsertSchedule(ctx context.Context, arg UpsertScheduleParams) (Schedule, error) {
row := q.db.QueryRow(ctx, upsertSchedule,
arg.ID,
arg.OwnerKind,
arg.OwnerID,
arg.Name,
arg.Enabled,
arg.BuiltIn,
arg.TimingKind,
arg.IntervalSeconds,
arg.Cron,
arg.RunAt,
arg.Anchor,
arg.NextRun,
arg.Zone,
)
var i Schedule
err := row.Scan(
&i.ID,
&i.OwnerKind,
&i.OwnerID,
&i.Name,
&i.Enabled,
&i.BuiltIn,
&i.TimingKind,
&i.IntervalSeconds,
&i.Cron,
&i.RunAt,
&i.Anchor,
&i.NextRun,
&i.Zone,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
@@ -0,0 +1,87 @@
-- Schedules and their runs (internal/domain/scheduling).
-- name: ListSchedules :many
SELECT * FROM schedules ORDER BY built_in, name, id;
-- name: LatestScheduleRuns :many
SELECT DISTINCT ON (schedule_id) * FROM schedule_runs ORDER BY schedule_id, scheduled_for DESC;
-- name: GetSchedule :one
SELECT * FROM schedules WHERE id = $1;
-- name: LockSchedule :one
SELECT * FROM schedules WHERE id = $1 FOR UPDATE;
-- name: UpsertSchedule :one
INSERT INTO schedules (id, owner_kind, owner_id, name, enabled, built_in, timing_kind, interval_seconds, cron, run_at, anchor, next_run, zone)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
ON CONFLICT (id) DO UPDATE SET
owner_kind = excluded.owner_kind, owner_id = excluded.owner_id, name = excluded.name,
enabled = excluded.enabled, timing_kind = excluded.timing_kind, interval_seconds = excluded.interval_seconds,
cron = excluded.cron, run_at = excluded.run_at, anchor = excluded.anchor, next_run = excluded.next_run,
zone = excluded.zone, updated_at = now()
RETURNING *;
-- name: InsertBuiltinSchedule :exec
INSERT INTO schedules (id, owner_kind, owner_id, name, enabled, built_in, timing_kind, interval_seconds, anchor, next_run, zone)
VALUES ($1, 'instance', '', $2, true, true, 'interval', $3, $4, $5, $6)
ON CONFLICT (id) DO NOTHING;
-- name: DeleteSchedule :execrows
DELETE FROM schedules WHERE id = $1;
-- name: FailStaleRuns :exec
UPDATE schedule_runs SET result = 'failed', error = 'no result was recorded', finished_at = $1
WHERE result = 'running' AND started_at < $2;
-- name: StartRequestedRuns :many
UPDATE schedule_runs r SET result = 'running', started_at = $1
FROM schedules s
WHERE r.result = 'pending' AND s.id = r.schedule_id
RETURNING r.id, r.schedule_id, r.scheduled_for, s.name, s.built_in;
-- name: LockDueSchedules :many
SELECT * FROM schedules
WHERE enabled AND next_run IS NOT NULL AND next_run <= $1
ORDER BY next_run
FOR UPDATE SKIP LOCKED;
-- name: LockStaleZoneCronSchedules :many
SELECT * FROM schedules
WHERE enabled AND timing_kind = 'cron' AND zone <> $1
FOR UPDATE SKIP LOCKED;
-- name: SetScheduleNextRun :exec
UPDATE schedules SET next_run = $2, zone = $3 WHERE id = $1;
-- name: InsertScheduleRun :one
INSERT INTO schedule_runs (schedule_id, scheduled_for, started_at, result)
VALUES ($1, $2, $3, $4)
ON CONFLICT (schedule_id, scheduled_for) DO NOTHING
RETURNING *;
-- name: FinishScheduleRun :one
UPDATE schedule_runs SET result = $2, error = $3, finished_at = $4
WHERE id = $1 AND result = 'running'
RETURNING schedule_id;
-- name: RecentFinishedResults :many
SELECT result FROM schedule_runs
WHERE schedule_id = $1 AND result IN ('succeeded', 'failed')
ORDER BY scheduled_for DESC
LIMIT $2;
-- name: SetScheduleRunCapture :execrows
UPDATE schedule_runs SET capture_id = $2 WHERE id = $1;
-- name: ListScheduleRuns :many
SELECT * FROM schedule_runs WHERE schedule_id = $1 ORDER BY scheduled_for DESC LIMIT $2;
-- name: PruneScheduleRuns :execrows
WITH ranked AS (
SELECT id AS run_id, finished_at AS ended, row_number() OVER (PARTITION BY schedule_id ORDER BY scheduled_for DESC) AS position
FROM schedule_runs WHERE result NOT IN ('pending', 'running')
)
DELETE FROM schedule_runs WHERE id IN (
SELECT run_id FROM ranked WHERE ended < sqlc.arg(before)::timestamptz OR position > sqlc.arg(keep)::bigint
);
@@ -0,0 +1,348 @@
// Schedules: the Postgres implementation of internal/domain/scheduling.Store.
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/scheduling"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
var (
_ scheduling.Store = (*Store)(nil)
_ scheduling.RunStore = (*Store)(nil)
)
// failureStreakWindow bounds how many finished runs FinishRun reads to count
// a failure streak.
const failureStreakWindow = 20
func optionalTime(t time.Time) pgtype.Timestamptz {
return pgtype.Timestamptz{Time: t, Valid: !t.IsZero()}
}
func scheduleFromRow(r postgresdb.Schedule) scheduling.Schedule {
s := scheduling.Schedule{
ID: r.ID, Name: r.Name,
Owner: scheduling.Owner{Kind: scheduling.OwnerKind(r.OwnerKind), ID: r.OwnerID},
Enabled: r.Enabled, BuiltIn: r.BuiltIn,
Timing: scheduling.Timing{
Kind: r.TimingKind,
Interval: scheduling.Duration(time.Duration(r.IntervalSeconds) * time.Second),
Cron: r.Cron,
Start: r.Anchor.UTC(),
},
Created: r.CreatedAt, Updated: r.UpdatedAt,
}
if r.RunAt.Valid {
at := r.RunAt.Time.UTC()
s.Timing.At = &at
}
if r.NextRun.Valid {
s.NextRun = r.NextRun.Time.UTC()
}
return s
}
func runFromRow(r postgresdb.ScheduleRun) scheduling.Run {
return scheduling.Run{
ID: r.ID, ScheduleID: r.ScheduleID, ScheduledFor: r.ScheduledFor.UTC(),
Started: r.StartedAt.Time, Finished: r.FinishedAt.Time,
Result: scheduling.RunResult(r.Result), Error: r.Error, CaptureID: r.CaptureID,
}
}
// nextRun is the first fire time strictly after now, unset when the timing
// never fires again.
func nextRun(t scheduling.Timing, now time.Time, loc *time.Location) (pgtype.Timestamptz, error) {
next, ok, err := t.Next(now, loc)
if err != nil || !ok {
return pgtype.Timestamptz{}, err
}
return optionalTime(next), nil
}
func (s *Store) ListSchedules(ctx context.Context) ([]scheduling.Schedule, error) {
q := s.queries()
rows, err := q.ListSchedules(ctx)
if err != nil {
return nil, fmt.Errorf("postgres: list schedules: %w", err)
}
latest, err := q.LatestScheduleRuns(ctx)
if err != nil {
return nil, fmt.Errorf("postgres: latest schedule runs: %w", err)
}
last := make(map[string]scheduling.Run, len(latest))
for _, r := range latest {
last[r.ScheduleID] = runFromRow(r)
}
out := make([]scheduling.Schedule, 0, len(rows))
for _, r := range rows {
schedule := scheduleFromRow(r)
if run, ok := last[r.ID]; ok {
schedule.LastRun = &run
}
out = append(out, schedule)
}
return out, nil
}
func (s *Store) GetSchedule(ctx context.Context, id string) (scheduling.Schedule, error) {
row, err := s.queries().GetSchedule(ctx, id)
if errors.Is(err, pgx.ErrNoRows) {
return scheduling.Schedule{}, scheduling.ErrNotFound
}
if err != nil {
return scheduling.Schedule{}, fmt.Errorf("postgres: get schedule: %w", err)
}
return scheduleFromRow(row), nil
}
// PutSchedule stores in. A built-in schedule takes only Enabled and Timing
// from in. A timing with no start is anchored at the time it is stored.
func (s *Store) PutSchedule(ctx context.Context, in scheduling.Schedule, loc *time.Location) (scheduling.Schedule, error) {
var stored scheduling.Schedule
err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
q := postgresdb.New(tx)
existing, err := q.LockSchedule(ctx, in.ID)
switch {
case errors.Is(err, pgx.ErrNoRows):
if in.BuiltIn {
return fmt.Errorf("%w: built-in schedules are defined in code", scheduling.ErrInvalidSpec)
}
case err != nil:
return err
case existing.BuiltIn:
current := scheduleFromRow(existing)
current.Enabled, current.Timing = in.Enabled, in.Timing
in = current
default:
in.BuiltIn = false
}
if err := in.Validate(); err != nil {
return err
}
now := time.Now().UTC()
if in.Timing.Start.IsZero() {
in.Timing.Start = now
}
next, err := nextRun(in.Timing, now, loc)
if err != nil {
return err
}
row, err := q.UpsertSchedule(ctx, postgresdb.UpsertScheduleParams{
ID: in.ID, OwnerKind: string(in.Owner.Kind), OwnerID: in.Owner.ID, Name: in.Name,
Enabled: in.Enabled, BuiltIn: in.BuiltIn, TimingKind: in.Timing.Kind,
IntervalSeconds: int64(in.Timing.Interval.Std() / time.Second), Cron: in.Timing.Cron,
RunAt: timingAt(in.Timing), Anchor: in.Timing.Start, NextRun: next, Zone: loc.String(),
})
if err != nil {
return err
}
stored = scheduleFromRow(row)
return nil
})
if err != nil {
return scheduling.Schedule{}, fmt.Errorf("postgres: put schedule: %w", err)
}
return stored, nil
}
func timingAt(t scheduling.Timing) pgtype.Timestamptz {
if t.At == nil {
return pgtype.Timestamptz{}
}
return optionalTime(*t.At)
}
func (s *Store) DeleteSchedule(ctx context.Context, id string) error {
return pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
q := postgresdb.New(tx)
existing, err := q.LockSchedule(ctx, id)
if errors.Is(err, pgx.ErrNoRows) {
return scheduling.ErrNotFound
}
if err != nil {
return fmt.Errorf("postgres: delete schedule: %w", err)
}
if existing.BuiltIn {
return scheduling.ErrBuiltIn
}
_, err = q.DeleteSchedule(ctx, id)
return err
})
}
func (s *Store) EnsureBuiltins(ctx context.Context, builtins []scheduling.Builtin, loc *time.Location) error {
now := time.Now().UTC()
return pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
q := postgresdb.New(tx)
for _, b := range builtins {
timing := scheduling.Timing{Kind: scheduling.TimingInterval, Interval: scheduling.Duration(b.Interval), Start: now}
if err := (scheduling.Schedule{ID: b.ID, Name: b.Name, Owner: scheduling.Owner{Kind: scheduling.OwnerInstance}, Timing: timing}).Validate(); err != nil {
return err
}
next, err := nextRun(timing, now, loc)
if err != nil {
return err
}
if err := q.InsertBuiltinSchedule(ctx, postgresdb.InsertBuiltinScheduleParams{
ID: b.ID, Name: b.Name, IntervalSeconds: int64(b.Interval / time.Second),
Anchor: now, NextRun: next, Zone: loc.String(),
}); err != nil {
return fmt.Errorf("postgres: seed built-in schedule %q: %w", b.ID, err)
}
}
return nil
})
}
// ClaimDue runs in one transaction: stale runs fail, requested runs start, a
// cron schedule computed in another zone is recomputed, and each due schedule
// gets one run for its slot and a next run past now. However many slots were
// missed, the schedule fires once. Due rows are locked SKIP LOCKED and the run
// is unique per slot, so a second scheduler claims nothing twice.
func (s *Store) ClaimDue(ctx context.Context, now time.Time, stale time.Duration, loc *time.Location) ([]scheduling.Claim, error) {
var claims []scheduling.Claim
err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
q := postgresdb.New(tx)
at := optionalTime(now)
if err := q.FailStaleRuns(ctx, postgresdb.FailStaleRunsParams{FinishedAt: at, StartedAt: optionalTime(now.Add(-stale))}); err != nil {
return err
}
requested, err := q.StartRequestedRuns(ctx, at)
if err != nil {
return err
}
for _, r := range requested {
claims = append(claims, scheduling.Claim{
ID: r.ID, ScheduleID: r.ScheduleID, ScheduledFor: r.ScheduledFor, Started: now, Result: scheduling.RunRunning,
Name: r.Name, BuiltIn: r.BuiltIn,
})
}
rezoned, err := q.LockStaleZoneCronSchedules(ctx, loc.String())
if err != nil {
return err
}
for _, row := range rezoned {
if err := advance(ctx, q, scheduleFromRow(row), now, loc); err != nil {
return err
}
}
due, err := q.LockDueSchedules(ctx, at)
if err != nil {
return err
}
for _, row := range due {
schedule := scheduleFromRow(row)
run, err := q.InsertScheduleRun(ctx, postgresdb.InsertScheduleRunParams{
ScheduleID: schedule.ID, ScheduledFor: schedule.NextRun, StartedAt: at, Result: string(scheduling.RunRunning),
})
switch {
case errors.Is(err, pgx.ErrNoRows):
// The slot already has a run; only the next run moves.
case err != nil:
return err
default:
claims = append(claims, scheduling.Claim{Run: runFromRow(run), Name: schedule.Name, BuiltIn: schedule.BuiltIn})
}
if err := advance(ctx, q, schedule, now, loc); err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, fmt.Errorf("postgres: claim due schedules: %w", err)
}
return claims, nil
}
// advance moves a schedule's next run to its first slot after now.
func advance(ctx context.Context, q *postgresdb.Queries, schedule scheduling.Schedule, now time.Time, loc *time.Location) error {
next, err := nextRun(schedule.Timing, now, loc)
if err != nil {
return fmt.Errorf("schedule %q: %w", schedule.ID, err)
}
return q.SetScheduleNextRun(ctx, postgresdb.SetScheduleNextRunParams{ID: schedule.ID, NextRun: next, Zone: loc.String()})
}
func (s *Store) RequestRun(ctx context.Context, id string, now time.Time) (scheduling.Run, error) {
run, err := s.queries().InsertScheduleRun(ctx, postgresdb.InsertScheduleRunParams{
ScheduleID: id, ScheduledFor: now.UTC(), Result: string(scheduling.RunPending),
})
if errors.Is(err, pgx.ErrNoRows) {
return scheduling.Run{}, fmt.Errorf("%w: a run of %q was already requested at %s", scheduling.ErrInvalidSpec, id, now.UTC().Format(time.RFC3339Nano))
}
if isForeignKeyViolation(err) {
return scheduling.Run{}, scheduling.ErrNotFound
}
if err != nil {
return scheduling.Run{}, fmt.Errorf("postgres: request schedule run: %w", err)
}
return runFromRow(run), nil
}
// FinishRun records a running run's result and counts the schedule's latest
// consecutive failures. A run that is no longer running is ErrNotFound.
func (s *Store) FinishRun(ctx context.Context, runID int64, result scheduling.RunResult, errText string, at time.Time) (int, error) {
q := s.queries()
scheduleID, err := q.FinishScheduleRun(ctx, postgresdb.FinishScheduleRunParams{
ID: runID, Result: string(result), Error: errText, FinishedAt: optionalTime(at),
})
if errors.Is(err, pgx.ErrNoRows) {
return 0, scheduling.ErrNotFound
}
if err != nil {
return 0, fmt.Errorf("postgres: finish schedule run: %w", err)
}
results, err := q.RecentFinishedResults(ctx, postgresdb.RecentFinishedResultsParams{ScheduleID: scheduleID, Limit: failureStreakWindow})
if err != nil {
return 0, fmt.Errorf("postgres: schedule failure streak: %w", err)
}
streak := 0
for _, r := range results {
if r != string(scheduling.RunFailed) {
break
}
streak++
}
return streak, nil
}
func (s *Store) SetRunCapture(ctx context.Context, runID int64, captureID string) error {
n, err := s.queries().SetScheduleRunCapture(ctx, postgresdb.SetScheduleRunCaptureParams{ID: runID, CaptureID: captureID})
if err != nil {
return fmt.Errorf("postgres: set schedule run capture: %w", err)
}
if n == 0 {
return scheduling.ErrNotFound
}
return nil
}
func (s *Store) ListRuns(ctx context.Context, scheduleID string, limit int) ([]scheduling.Run, error) {
rows, err := s.queries().ListScheduleRuns(ctx, postgresdb.ListScheduleRunsParams{ScheduleID: scheduleID, Limit: int32(min(max(limit, 1), 500))})
if err != nil {
return nil, fmt.Errorf("postgres: list schedule runs: %w", err)
}
out := make([]scheduling.Run, 0, len(rows))
for _, r := range rows {
out = append(out, runFromRow(r))
}
return out, nil
}
func (s *Store) PruneRuns(ctx context.Context, before time.Time, keep int) (int64, error) {
n, err := s.queries().PruneScheduleRuns(ctx, postgresdb.PruneScheduleRunsParams{Before: before, Keep: int64(keep)})
if err != nil {
return 0, fmt.Errorf("postgres: prune schedule runs: %w", err)
}
return n, nil
}
@@ -40,6 +40,7 @@ type Client struct {
org pb.OrgServiceClient
alert pb.AlertServiceClient
audit pb.AuditServiceClient
schedule pb.ScheduleServiceClient
controlPlane controlpb.ControlPlaneServiceClient
}
@@ -69,6 +70,7 @@ func NewClient(conn grpc.ClientConnInterface) *Client {
org: pb.NewOrgServiceClient(conn),
alert: pb.NewAlertServiceClient(conn),
audit: pb.NewAuditServiceClient(conn),
schedule: pb.NewScheduleServiceClient(conn),
controlPlane: controlpb.NewControlPlaneServiceClient(conn),
}
}
@@ -0,0 +1,338 @@
// Schedules: the schedule and schedule-run RPCs. Task grants never reach
// them; the dashboard gates each call before it is made.
package staterpc
import (
"context"
"errors"
"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/scheduling"
)
var errSchedulesUnavailable = status.Error(codes.Unavailable, "schedule store unavailable")
type scheduleServer struct {
pb.UnimplementedScheduleServiceServer
*server
}
func scheduleStatus(err error) error {
switch {
case errors.Is(err, scheduling.ErrInvalidSpec):
return status.Error(codes.InvalidArgument, err.Error())
case errors.Is(err, scheduling.ErrNotFound):
return status.Error(codes.NotFound, scheduling.ErrNotFound.Error())
case errors.Is(err, scheduling.ErrBuiltIn):
return status.Error(codes.FailedPrecondition, scheduling.ErrBuiltIn.Error())
default:
return mapError(err)
}
}
func scheduleError(err error) error {
st, ok := status.FromError(err)
if !ok {
return err
}
switch st.Code() {
case codes.InvalidArgument:
return errors.Join(scheduling.ErrInvalidSpec, errors.New(st.Message()))
case codes.NotFound:
return scheduling.ErrNotFound
case codes.FailedPrecondition:
return scheduling.ErrBuiltIn
default:
return unmapError(err)
}
}
// location is the zone cron is read in, from the instance's settings.
func (s *scheduleServer) location(ctx context.Context) (*time.Location, error) {
if s.deps.ScheduleSettings == nil {
return time.UTC, nil
}
settings, err := s.deps.ScheduleSettings(ctx)
if err != nil {
s.deps.Log.WarnContext(ctx, "schedule settings unreadable", "err", err)
return nil, status.Error(codes.Unavailable, "schedule settings unreadable")
}
return settings.Location, nil
}
func (s *scheduleServer) ListSchedules(ctx context.Context, _ *pb.ListSchedulesRequest) (*pb.ListSchedulesResponse, error) {
if s.deps.Schedules == nil {
return nil, errSchedulesUnavailable
}
list, err := s.deps.Schedules.ListSchedules(ctx)
if err != nil {
return nil, s.logErr("ListSchedules", err)
}
return &pb.ListSchedulesResponse{Schedules: mapValues(list, scheduleProto)}, nil
}
func (s *scheduleServer) GetSchedule(ctx context.Context, r *pb.GetScheduleRequest) (*pb.GetScheduleResponse, error) {
if s.deps.Schedules == nil {
return nil, errSchedulesUnavailable
}
got, err := s.deps.Schedules.GetSchedule(ctx, r.GetId())
if err != nil {
return nil, scheduleStatus(err)
}
return &pb.GetScheduleResponse{Schedule: scheduleProto(got)}, nil
}
func (s *scheduleServer) PutSchedule(ctx context.Context, r *pb.PutScheduleRequest) (*pb.PutScheduleResponse, error) {
if s.deps.Schedules == nil {
return nil, errSchedulesUnavailable
}
loc, err := s.location(ctx)
if err != nil {
return nil, err
}
stored, err := s.deps.Schedules.PutSchedule(ctx, scheduleValue(r.GetSchedule()), loc)
if err != nil {
return nil, scheduleStatus(err)
}
return &pb.PutScheduleResponse{Schedule: scheduleProto(stored)}, nil
}
func (s *scheduleServer) DeleteSchedule(ctx context.Context, r *pb.DeleteScheduleRequest) (*pb.DeleteScheduleResponse, error) {
if s.deps.Schedules == nil {
return nil, errSchedulesUnavailable
}
if err := s.deps.Schedules.DeleteSchedule(ctx, r.GetId()); err != nil {
return nil, scheduleStatus(err)
}
return &pb.DeleteScheduleResponse{}, nil
}
func (s *scheduleServer) EnsureBuiltinSchedules(ctx context.Context, r *pb.EnsureBuiltinSchedulesRequest) (*pb.EnsureBuiltinSchedulesResponse, error) {
if s.deps.Schedules == nil {
return nil, errSchedulesUnavailable
}
loc, err := s.location(ctx)
if err != nil {
return nil, err
}
builtins := mapValues(r.GetBuiltins(), func(b *pb.BuiltinSchedule) scheduling.Builtin {
return scheduling.Builtin{ID: b.GetId(), Name: b.GetName(), Interval: time.Duration(b.GetIntervalSeconds()) * time.Second}
})
if err := s.deps.Schedules.EnsureBuiltins(ctx, builtins, loc); err != nil {
return nil, s.logErr("EnsureBuiltinSchedules", err)
}
return &pb.EnsureBuiltinSchedulesResponse{}, nil
}
func (s *scheduleServer) ClaimDueRuns(ctx context.Context, r *pb.ClaimDueRunsRequest) (*pb.ClaimDueRunsResponse, error) {
if s.deps.ScheduleRuns == nil {
return nil, errSchedulesUnavailable
}
loc, err := s.location(ctx)
if err != nil {
return nil, err
}
claims, err := s.deps.ScheduleRuns.ClaimDue(ctx, timeValue(r.GetNow()), time.Duration(r.GetStaleSeconds())*time.Second, loc)
if err != nil {
return nil, s.logErr("ClaimDueRuns", err)
}
return &pb.ClaimDueRunsResponse{Claims: mapValues(claims, func(c scheduling.Claim) *pb.ScheduleClaim {
return &pb.ScheduleClaim{Run: scheduleRunProto(c.Run), Name: c.Name, BuiltIn: c.BuiltIn}
})}, nil
}
func (s *scheduleServer) RequestScheduleRun(ctx context.Context, r *pb.RequestScheduleRunRequest) (*pb.RequestScheduleRunResponse, error) {
if s.deps.ScheduleRuns == nil {
return nil, errSchedulesUnavailable
}
run, err := s.deps.ScheduleRuns.RequestRun(ctx, r.GetId(), time.Now())
if err != nil {
return nil, scheduleStatus(err)
}
return &pb.RequestScheduleRunResponse{Run: scheduleRunProto(run)}, nil
}
func (s *scheduleServer) FinishScheduleRun(ctx context.Context, r *pb.FinishScheduleRunRequest) (*pb.FinishScheduleRunResponse, error) {
if s.deps.ScheduleRuns == nil {
return nil, errSchedulesUnavailable
}
switch scheduling.RunResult(r.GetResult()) {
case scheduling.RunSucceeded, scheduling.RunFailed, scheduling.RunSkipped:
default:
return nil, status.Errorf(codes.InvalidArgument, "result %q is not a finished result", r.GetResult())
}
streak, err := s.deps.ScheduleRuns.FinishRun(ctx, r.GetRunId(), scheduling.RunResult(r.GetResult()), r.GetError(), time.Now())
if err != nil {
return nil, scheduleStatus(err)
}
return &pb.FinishScheduleRunResponse{FailureStreak: int64(streak)}, nil
}
func (s *scheduleServer) SetScheduleRunCapture(ctx context.Context, r *pb.SetScheduleRunCaptureRequest) (*pb.SetScheduleRunCaptureResponse, error) {
if s.deps.ScheduleRuns == nil {
return nil, errSchedulesUnavailable
}
if err := s.deps.ScheduleRuns.SetRunCapture(ctx, r.GetRunId(), r.GetCaptureId()); err != nil {
return nil, scheduleStatus(err)
}
return &pb.SetScheduleRunCaptureResponse{}, nil
}
func (s *scheduleServer) ListScheduleRuns(ctx context.Context, r *pb.ListScheduleRunsRequest) (*pb.ListScheduleRunsResponse, error) {
if s.deps.Schedules == nil {
return nil, errSchedulesUnavailable
}
runs, err := s.deps.Schedules.ListRuns(ctx, r.GetScheduleId(), int(r.GetLimit()))
if err != nil {
return nil, s.logErr("ListScheduleRuns", err)
}
return &pb.ListScheduleRunsResponse{Runs: mapValues(runs, scheduleRunProto)}, nil
}
func scheduleProto(s scheduling.Schedule) *pb.Schedule {
out := &pb.Schedule{
Id: s.ID, Name: s.Name,
Owner: &pb.ScheduleOwner{Kind: string(s.Owner.Kind), Id: s.Owner.ID},
Enabled: s.Enabled, BuiltIn: s.BuiltIn,
Timing: &pb.ScheduleTiming{
Kind: s.Timing.Kind, IntervalSeconds: int64(s.Timing.Interval.Std() / time.Second),
Cron: s.Timing.Cron, Start: timestamp(s.Timing.Start),
},
NextRun: timestamp(s.NextRun), Created: timestamp(s.Created), Updated: timestamp(s.Updated),
}
if s.Timing.At != nil {
out.Timing.At = timestamp(*s.Timing.At)
}
if s.LastRun != nil {
out.LastRun = scheduleRunProto(*s.LastRun)
}
return out
}
func scheduleValue(p *pb.Schedule) scheduling.Schedule {
t := p.GetTiming()
s := scheduling.Schedule{
ID: p.GetId(), Name: p.GetName(),
Owner: scheduling.Owner{Kind: scheduling.OwnerKind(p.GetOwner().GetKind()), ID: p.GetOwner().GetId()},
Enabled: p.GetEnabled(), BuiltIn: p.GetBuiltIn(),
Timing: scheduling.Timing{
Kind: t.GetKind(), Interval: scheduling.Duration(time.Duration(t.GetIntervalSeconds()) * time.Second),
Cron: t.GetCron(), Start: timeValue(t.GetStart()),
},
NextRun: timeValue(p.GetNextRun()), Created: timeValue(p.GetCreated()), Updated: timeValue(p.GetUpdated()),
}
if t.GetAt() != nil {
at := timeValue(t.GetAt())
s.Timing.At = &at
}
if p.GetLastRun() != nil {
run := scheduleRunValue(p.GetLastRun())
s.LastRun = &run
}
return s
}
func scheduleRunProto(r scheduling.Run) *pb.ScheduleRun {
return &pb.ScheduleRun{
Id: r.ID, ScheduleId: r.ScheduleID, ScheduledFor: timestamp(r.ScheduledFor),
Started: timestamp(r.Started), Finished: timestamp(r.Finished),
Result: string(r.Result), Error: r.Error, CaptureId: r.CaptureID,
}
}
func scheduleRunValue(p *pb.ScheduleRun) scheduling.Run {
return scheduling.Run{
ID: p.GetId(), ScheduleID: p.GetScheduleId(), ScheduledFor: timeValue(p.GetScheduledFor()),
Started: timeValue(p.GetStarted()), Finished: timeValue(p.GetFinished()),
Result: scheduling.RunResult(p.GetResult()), Error: p.GetError(), CaptureID: p.GetCaptureId(),
}
}
// ListSchedules lists every schedule with its latest run.
func (c *Client) ListSchedules(ctx context.Context) ([]scheduling.Schedule, error) {
r, err := c.schedule.ListSchedules(ctx, &pb.ListSchedulesRequest{})
if err != nil {
return nil, scheduleError(err)
}
return mapValues(r.GetSchedules(), scheduleValue), nil
}
func (c *Client) GetSchedule(ctx context.Context, id string) (scheduling.Schedule, error) {
r, err := c.schedule.GetSchedule(ctx, &pb.GetScheduleRequest{Id: id})
if err != nil {
return scheduling.Schedule{}, scheduleError(err)
}
return scheduleValue(r.GetSchedule()), nil
}
func (c *Client) PutSchedule(ctx context.Context, s scheduling.Schedule) (scheduling.Schedule, error) {
r, err := c.schedule.PutSchedule(ctx, &pb.PutScheduleRequest{Schedule: scheduleProto(s)})
if err != nil {
return scheduling.Schedule{}, scheduleError(err)
}
return scheduleValue(r.GetSchedule()), nil
}
func (c *Client) DeleteSchedule(ctx context.Context, id string) error {
_, err := c.schedule.DeleteSchedule(ctx, &pb.DeleteScheduleRequest{Id: id})
return scheduleError(err)
}
// EnsureBuiltinSchedules inserts each missing built-in schedule and leaves
// existing ones as the operator set them.
func (c *Client) EnsureBuiltinSchedules(ctx context.Context, builtins []scheduling.Builtin) error {
_, err := c.schedule.EnsureBuiltinSchedules(ctx, &pb.EnsureBuiltinSchedulesRequest{
Builtins: mapValues(builtins, func(b scheduling.Builtin) *pb.BuiltinSchedule {
return &pb.BuiltinSchedule{Id: b.ID, Name: b.Name, IntervalSeconds: int64(b.Interval / time.Second)}
}),
})
return scheduleError(err)
}
// ClaimDueRuns claims the runs due at now; see scheduling.Store.ClaimDue.
func (c *Client) ClaimDueRuns(ctx context.Context, now time.Time, stale time.Duration) ([]scheduling.Claim, error) {
r, err := c.schedule.ClaimDueRuns(ctx, &pb.ClaimDueRunsRequest{Now: timestamp(now), StaleSeconds: int64(stale / time.Second)})
if err != nil {
return nil, scheduleError(err)
}
return mapValues(r.GetClaims(), func(p *pb.ScheduleClaim) scheduling.Claim {
return scheduling.Claim{Run: scheduleRunValue(p.GetRun()), Name: p.GetName(), BuiltIn: p.GetBuiltIn()}
}), nil
}
// RequestScheduleRun queues a run of id now.
func (c *Client) RequestScheduleRun(ctx context.Context, id string) (scheduling.Run, error) {
r, err := c.schedule.RequestScheduleRun(ctx, &pb.RequestScheduleRunRequest{Id: id})
if err != nil {
return scheduling.Run{}, scheduleError(err)
}
return scheduleRunValue(r.GetRun()), nil
}
// FinishScheduleRun records a run's result and returns the schedule's
// failure streak.
func (c *Client) FinishScheduleRun(ctx context.Context, runID int64, result scheduling.RunResult, errText string) (int, error) {
r, err := c.schedule.FinishScheduleRun(ctx, &pb.FinishScheduleRunRequest{RunId: runID, Result: string(result), Error: errText})
if err != nil {
return 0, scheduleError(err)
}
return int(r.GetFailureStreak()), nil
}
// SetScheduleRunCapture records the schedule-fired capture a run recorded.
func (c *Client) SetScheduleRunCapture(ctx context.Context, runID int64, captureID string) error {
_, err := c.schedule.SetScheduleRunCapture(ctx, &pb.SetScheduleRunCaptureRequest{RunId: runID, CaptureId: captureID})
return scheduleError(err)
}
func (c *Client) ListScheduleRuns(ctx context.Context, scheduleID string, limit int) ([]scheduling.Run, error) {
r, err := c.schedule.ListScheduleRuns(ctx, &pb.ListScheduleRunsRequest{ScheduleId: scheduleID, Limit: int32(limit)})
if err != nil {
return nil, scheduleError(err)
}
return mapValues(r.GetRuns(), scheduleRunValue), nil
}
@@ -21,6 +21,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/audit"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/scheduling"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/storepkg"
"github.com/samcharles93/archie-core/internal/domain/usage"
@@ -148,6 +149,13 @@ type Deps struct {
// with codes.Unavailable. It is deliberately not task-scoped: a task
// grant must never reach it.
Audit audit.Store
// Schedules stores schedules and their runs. Optional: nil answers the
// schedule RPCs with codes.Unavailable.
Schedules scheduling.Store
ScheduleRuns scheduling.RunStore
// ScheduleSettings reads the instance schedule settings. Nil reads cron
// in UTC.
ScheduleSettings func(ctx context.Context) (scheduling.Settings, error)
// Orgs persists orgs, workspaces, memberships and agent assignments.
// Optional: nil answers the org RPCs with codes.Unavailable.
Orgs org.Repository
@@ -195,6 +203,7 @@ func RegisterServer(registrar grpc.ServiceRegistrar, deps Deps) {
pb.RegisterOrgServiceServer(registrar, &orgServer{server: s})
pb.RegisterAlertServiceServer(registrar, &alertServer{server: s})
pb.RegisterAuditServiceServer(registrar, &auditServer{server: s})
pb.RegisterScheduleServiceServer(registrar, &scheduleServer{server: s})
if deps.ControlPlane != nil {
controlpb.RegisterControlPlaneServiceServer(registrar, deps.ControlPlane)
}
+137
View File
@@ -0,0 +1,137 @@
syntax = "proto3";
package state.v1;
import "google/protobuf/timestamp.proto";
// Schedules and their runs (internal/domain/scheduling). The scheduler in
// archied claims due runs and records their results; the dashboard edits
// schedules and reads runs. Cron is read in the instance zone from the
// schedule-settings resource.
service ScheduleService {
rpc ListSchedules(ListSchedulesRequest) returns (ListSchedulesResponse);
rpc GetSchedule(GetScheduleRequest) returns (GetScheduleResponse);
rpc PutSchedule(PutScheduleRequest) returns (PutScheduleResponse);
rpc DeleteSchedule(DeleteScheduleRequest) returns (DeleteScheduleResponse);
rpc EnsureBuiltinSchedules(EnsureBuiltinSchedulesRequest) returns (EnsureBuiltinSchedulesResponse);
rpc ClaimDueRuns(ClaimDueRunsRequest) returns (ClaimDueRunsResponse);
rpc RequestScheduleRun(RequestScheduleRunRequest) returns (RequestScheduleRunResponse);
rpc FinishScheduleRun(FinishScheduleRunRequest) returns (FinishScheduleRunResponse);
rpc SetScheduleRunCapture(SetScheduleRunCaptureRequest) returns (SetScheduleRunCaptureResponse);
rpc ListScheduleRuns(ListScheduleRunsRequest) returns (ListScheduleRunsResponse);
}
message ScheduleOwner {
// kind is "instance" or "org".
string kind = 1;
// id is the organisation id for an org owner, empty for the instance.
string id = 2;
}
message ScheduleTiming {
// kind is "interval", "cron" or "once".
string kind = 1;
int64 interval_seconds = 2;
string cron = 3;
google.protobuf.Timestamp at = 4;
google.protobuf.Timestamp start = 5;
}
message Schedule {
string id = 1;
string name = 2;
ScheduleOwner owner = 3;
bool enabled = 4;
bool built_in = 5;
ScheduleTiming timing = 6;
google.protobuf.Timestamp next_run = 7;
google.protobuf.Timestamp created = 8;
google.protobuf.Timestamp updated = 9;
ScheduleRun last_run = 10;
}
message ScheduleRun {
int64 id = 1;
string schedule_id = 2;
google.protobuf.Timestamp scheduled_for = 3;
google.protobuf.Timestamp started = 4;
google.protobuf.Timestamp finished = 5;
// result is pending, running, succeeded, failed or skipped.
string result = 6;
string error = 7;
string capture_id = 8;
}
message ScheduleClaim {
ScheduleRun run = 1;
string name = 2;
bool built_in = 3;
}
message ListSchedulesRequest {}
message ListSchedulesResponse {
repeated Schedule schedules = 1;
}
message GetScheduleRequest {
string id = 1;
}
message GetScheduleResponse {
Schedule schedule = 1;
}
message PutScheduleRequest {
Schedule schedule = 1;
}
message PutScheduleResponse {
Schedule schedule = 1;
}
message DeleteScheduleRequest {
string id = 1;
}
message DeleteScheduleResponse {}
message BuiltinSchedule {
string id = 1;
string name = 2;
int64 interval_seconds = 3;
}
message EnsureBuiltinSchedulesRequest {
repeated BuiltinSchedule builtins = 1;
}
message EnsureBuiltinSchedulesResponse {}
message ClaimDueRunsRequest {
google.protobuf.Timestamp now = 1;
// stale_seconds fails a run still running after this long.
int64 stale_seconds = 2;
}
message ClaimDueRunsResponse {
repeated ScheduleClaim claims = 1;
}
message RequestScheduleRunRequest {
string id = 1;
}
message RequestScheduleRunResponse {
ScheduleRun run = 1;
}
message FinishScheduleRunRequest {
int64 run_id = 1;
string result = 2;
string error = 3;
}
message FinishScheduleRunResponse {
// failure_streak is how many of the schedule's latest finished runs failed
// in a row.
int64 failure_streak = 1;
}
message SetScheduleRunCaptureRequest {
int64 run_id = 1;
string capture_id = 2;
}
message SetScheduleRunCaptureResponse {}
message ListScheduleRunsRequest {
string schedule_id = 1;
int32 limit = 2;
}
message ListScheduleRunsResponse {
repeated ScheduleRun runs = 1;
}
+100 -100
View File
@@ -1,12 +1,12 @@
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/css2.js","assets/css.js","assets/html.js","assets/javascript.js","assets/javascript2.js","assets/AccountPage.js","assets/PageHeader.js","assets/createLucideIcon.js","assets/input.js","assets/AuthenticationPage.js","assets/CredentialBindingsPage.js","assets/PlaybooksPage.js","assets/AgentProfilesPage.js","assets/HarnessPage.js","assets/badge.js","assets/NotFoundPage.js"])))=>i.map(i=>d[i]);
import{A as e,B as t,C as n,D as r,E as i,F as a,H as o,I as s,L as c,M as l,N as u,O as d,P as f,R as p,S as m,T as h,V as g,_,a as v,b as y,c as b,d as x,f as S,g as C,h as w,i as T,j as ee,k as te,l as E,m as ne,n as D,o as re,p as ie,r as O,s as ae,t as k,u as oe,v as se,w as ce,x as le,y as ue,z as de}from"./badge.js";import{$t as fe,A,B as pe,Bt as me,C as j,Ct as M,D as he,Dn as ge,Dt as _e,En as ve,G as ye,Gt as N,H as be,It as xe,Jt as Se,Kt as Ce,Lt as we,M as P,On as Te,Pt as Ee,Q as De,Qt as Oe,Rt as ke,S as F,Sn as Ae,T as je,Tt as Me,U as Ne,Vt as Pe,Xt as I,Z as Fe,_t as L,an as Ie,b as R,bn as Le,cn as Re,dn as ze,dt as Be,er as z,gn as Ve,hn as He,ht as Ue,ir as B,it as We,jn as V,k as H,kn as Ge,l as U,m as Ke,n as qe,nr as Je,nt as Ye,o as Xe,ot as Ze,p as Qe,pn as $e,r as W,rr as et,rt as G,sn as tt,st as nt,t as rt,tt as it,wn as at,wt as K,x as q,xn as J,y as Y,yn as ot,yt as st}from"./PageHeader.js";import{C as ct,D as lt,I as ut,M as X,N as dt,P as ft,a as eee,at as pt,c as mt,i as ht,it as gt,j as _t,n as vt,nt as tee,o as nee,r as Z,rt as yt,s as bt,t as xt,tt as ree,z as iee}from"./createLucideIcon.js";import{a as St,c as aee,d as oee,f as see,i as cee,l as lee,n as Ct,o as wt,p as Tt,r as Et,s as Dt,t as Q,u as Ot}from"./input.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 uee=typeof window<`u`,kt,At=e=>kt=e,jt=Symbol();function Mt(e){return e&&typeof e==`object`&&Object.prototype.toString.call(e)===`[object Object]`&&typeof e.toJSON!=`function`}var Nt=typeof window==`object`&&window.window===window?window:typeof self==`object`&&self.self===self?self:typeof global==`object`&&global.global===global?global:typeof globalThis==`object`?globalThis:{HTMLElement:null};function dee(e,{autoBom:t=!1}={}){return t&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob([``,e],{type:e.type}):e}function Pt(e,t,n){let r=new XMLHttpRequest;r.open(`GET`,e),r.responseType=`blob`,r.onload=function(){zt(r.response,t,n)},r.onerror=function(){console.error(`could not download file`)},r.send()}function Ft(e){let t=new XMLHttpRequest;t.open(`HEAD`,e,!1);try{t.send()}catch{}return t.status>=200&&t.status<=299}function It(e){try{e.dispatchEvent(new MouseEvent(`click`))}catch{let t=new MouseEvent(`click`,{bubbles:!0,cancelable:!0,view:window,detail:0,screenX:80,screenY:20,clientX:80,clientY:20,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,button:0,relatedTarget:null});e.dispatchEvent(t)}}var Lt=typeof navigator==`object`?navigator:{userAgent:``},Rt=/Macintosh/.test(Lt.userAgent)&&/AppleWebKit/.test(Lt.userAgent)&&!/Safari/.test(Lt.userAgent),zt=uee?typeof HTMLAnchorElement<`u`&&`download`in HTMLAnchorElement.prototype&&!Rt?Bt:`msSaveOrOpenBlob`in Lt?Vt:Ht:()=>{};function Bt(e,t=`download`,n){let r=document.createElement(`a`);r.download=t,r.rel=`noopener`,typeof e==`string`?(r.href=e,r.origin===location.origin?It(r):Ft(r.href)?Pt(e,t,n):(r.target=`_blank`,It(r))):(r.href=URL.createObjectURL(e),setTimeout(function(){URL.revokeObjectURL(r.href)},4e4),setTimeout(function(){It(r)},0))}function Vt(e,t=`download`,n){if(typeof e==`string`){if(Ft(e))Pt(e,t,n);else{let t=document.createElement(`a`);t.href=e,t.target=`_blank`,setTimeout(function(){It(t)})}}else navigator.msSaveOrOpenBlob(dee(e,n),t)}function Ht(e,t,n,r){if(r||=open(``,`_blank`),r&&(r.document.title=r.document.body.innerText=`downloading...`),typeof e==`string`)return Pt(e,t,n);let i=e.type===`application/octet-stream`,a=/constructor/i.test(String(Nt.HTMLElement))||`safari`in Nt,o=/CriOS\/[\d]+/.test(navigator.userAgent);if((o||i&&a||Rt)&&typeof FileReader<`u`){let t=new FileReader;t.onloadend=function(){let e=t.result;if(typeof e!=`string`)throw r=null,Error(`Wrong reader.result type`);e=o?e:e.replace(/^data:[^;]*;/,`data:attachment/file;`),r?r.location.href=e:location.assign(e),r=null},t.readAsDataURL(e)}else{let t=URL.createObjectURL(e);r?r.location.assign(t):location.href=t,r=null,setTimeout(function(){URL.revokeObjectURL(t)},4e4)}}var{assign:fee}=Object;function Ut(){let e=tt(!0),t=e.run(()=>J({})),n=[],r=[],i=He({install(e){At(i),i._a=e,e.provide(jt,i),e.config.globalProperties.$pinia=i,r.forEach(e=>n.push(e)),r=[]},use(e){return this._a?n.push(e):r.push(e),this},_p:n,_a:null,_e:e,_s:new Map,state:t});return i}var Wt=()=>{};function Gt(e,t,n,r=Wt){e.add(t);let i=()=>{e.delete(t)&&Line truncated
import{A as e,B as t,C as n,D as r,E as i,F as a,H as o,I as s,L as c,M as l,N as u,O as d,P as f,R as p,S as m,T as h,V as g,_,a as v,b as y,c as b,d as x,f as S,g as C,h as w,i as T,j as ee,k as te,l as E,m as ne,n as D,o as re,p as ie,r as O,s as ae,t as k,u as oe,v as se,w as ce,x as le,y as ue,z as de}from"./badge.js";import{$t as fe,A,B as pe,Bt as me,C as j,Ct as M,D as he,Dn as ge,Dt as _e,En as ve,G as ye,Gt as N,H as be,It as xe,Jt as Se,Kt as Ce,Lt as we,M as P,On as Te,Pt as Ee,Q as De,Qt as Oe,Rt as ke,S as F,Sn as Ae,T as je,Tt as Me,U as Ne,Vt as Pe,Xt as I,Z as Fe,_t as L,an as Ie,b as R,bn as Le,cn as Re,dn as ze,dt as Be,er as z,gn as Ve,hn as He,ht as Ue,ir as B,it as We,jn as V,k as H,kn as Ge,l as U,m as Ke,n as qe,nr as Je,nt as Ye,o as Xe,ot as Ze,p as Qe,pn as $e,r as W,rr as et,rt as G,sn as tt,st as nt,t as rt,tt as it,wn as at,wt as K,x as q,xn as J,y as Y,yn as ot,yt as st}from"./PageHeader.js";import{C as ct,D as lt,I as ut,M as X,N as dt,P as ft,a as eee,at as pt,c as mt,i as ht,it as gt,j as _t,n as vt,nt as tee,o as nee,r as Z,rt as yt,s as bt,t as xt,tt as ree,z as iee}from"./createLucideIcon.js";import{a as St,c as aee,d as oee,f as see,i as cee,l as lee,n as Ct,o as wt,p as Tt,r as Et,s as Dt,t as Q,u as Ot}from"./input.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 uee=typeof window<`u`,kt,At=e=>kt=e,jt=Symbol();function Mt(e){return e&&typeof e==`object`&&Object.prototype.toString.call(e)===`[object Object]`&&typeof e.toJSON!=`function`}var Nt=typeof window==`object`&&window.window===window?window:typeof self==`object`&&self.self===self?self:typeof global==`object`&&global.global===global?global:typeof globalThis==`object`?globalThis:{HTMLElement:null};function dee(e,{autoBom:t=!1}={}){return t&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob([``,e],{type:e.type}):e}function Pt(e,t,n){let r=new XMLHttpRequest;r.open(`GET`,e),r.responseType=`blob`,r.onload=function(){zt(r.response,t,n)},r.onerror=function(){console.error(`could not download file`)},r.send()}function Ft(e){let t=new XMLHttpRequest;t.open(`HEAD`,e,!1);try{t.send()}catch{}return t.status>=200&&t.status<=299}function It(e){try{e.dispatchEvent(new MouseEvent(`click`))}catch{let t=new MouseEvent(`click`,{bubbles:!0,cancelable:!0,view:window,detail:0,screenX:80,screenY:20,clientX:80,clientY:20,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,button:0,relatedTarget:null});e.dispatchEvent(t)}}var Lt=typeof navigator==`object`?navigator:{userAgent:``},Rt=/Macintosh/.test(Lt.userAgent)&&/AppleWebKit/.test(Lt.userAgent)&&!/Safari/.test(Lt.userAgent),zt=uee?typeof HTMLAnchorElement<`u`&&`download`in HTMLAnchorElement.prototype&&!Rt?Bt:`msSaveOrOpenBlob`in Lt?Vt:Ht:()=>{};function Bt(e,t=`download`,n){let r=document.createElement(`a`);r.download=t,r.rel=`noopener`,typeof e==`string`?(r.href=e,r.origin===location.origin?It(r):Ft(r.href)?Pt(e,t,n):(r.target=`_blank`,It(r))):(r.href=URL.createObjectURL(e),setTimeout(function(){URL.revokeObjectURL(r.href)},4e4),setTimeout(function(){It(r)},0))}function Vt(e,t=`download`,n){if(typeof e==`string`){if(Ft(e))Pt(e,t,n);else{let t=document.createElement(`a`);t.href=e,t.target=`_blank`,setTimeout(function(){It(t)})}}else navigator.msSaveOrOpenBlob(dee(e,n),t)}function Ht(e,t,n,r){if(r||=open(``,`_blank`),r&&(r.document.title=r.document.body.innerText=`downloading...`),typeof e==`string`)return Pt(e,t,n);let i=e.type===`application/octet-stream`,a=/constructor/i.test(String(Nt.HTMLElement))||`safari`in Nt,o=/CriOS\/[\d]+/.test(navigator.userAgent);if((o||i&&a||Rt)&&typeof FileReader<`u`){let t=new FileReader;t.onloadend=function(){let e=t.result;if(typeof e!=`string`)throw r=null,Error(`Wrong reader.result type`);e=o?e:e.replace(/^data:[^;]*;/,`data:attachment/file;`),r?r.location.href=e:location.assign(e),r=null},t.readAsDataURL(e)}else{let t=URL.createObjectURL(e);r?r.location.assign(t):location.href=t,r=null,setTimeout(function(){URL.revokeObjectURL(t)},4e4)}}var{assign:fee}=Object;function Ut(){let e=tt(!0),t=e.run(()=>J({})),n=[],r=[],i=He({install(e){At(i),i._a=e,e.provide(jt,i),e.config.globalProperties.$pinia=i,r.forEach(e=>n.push(e)),r=[]},use(e){return this._a?n.push(e):r.push(e),this},_p:n,_a:null,_e:e,_s:new Map,state:t});return i}var Wt=()=>{};function Gt(e,t,n,r=Wt){e.add(t);let i=()=>{e.delete(t)&&Line truncated
`);p=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&&(Qu.value=n.session_id),n.type===`delta`&&(o+=n.text,id.value=id.value?{...id.value,text:o}:null),(n.type===`tool`||n.type===`navigate`)&&(a=[...a,n],id.value=id.value?{...id.value,tools:a}:null),n.type===`ask`&&n.ask&&(clearTimeout(l),id.value=id.value?{...id.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`);$u.value=!i&&n.trim()===`/new`?[]:[...$u.value,{from:`assistant`,text:o,tool_calls:a}],id.value=null,td.value=`Ready`,await md()}catch(e){let t=e;o&&($u.value=[...$u.value,{from:`assistant`,text:o,tool_calls:a}],a=[]),t.name===`AbortError`&&!c?(id.value={text:`Turn stopped.`,tools:a,isError:!1,turn:r,isRetry:i},td.value=`Stopped`):(id.value={text:`Unable to complete that turn: ${t.message||t}`,tools:a,isError:!0,turn:r?Ju(r):void 0,isRetry:i},td.value=`Error. Retry available.`)}finally{clearTimeout(l),Yu=null,fd=null,nd.value=!1,bd.after?.()}}function Ad(){td.value=`Stopping…`,Qu.value&&Z.chatCancel(Qu.value).catch(()=>{}),pd()}function jd(){Be(()=>{md().catch(e=>{td.value=e.message||`Chat unavailable`})}),Ue(()=>{pd()})}async function Md(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 kd({textOverride:`🎤 Voice message`,voice:{data:btoa(n),mime_type:e.type||`audio/webm`}})}var Nd={class:`grid gap-1 p-1`},Pd={key:0,class:`text-xs text-fg-subtle`},Fd=`__default__`,Id=P({__name:`ChatSettings`,setup(e){let t=Y(()=>od.value||Fd),n=Y(()=>{let e=ad.value.models_by_provider||{},t=Object.entries(e).filter(([,e])=>e.length);return t.length?t:[[``,ad.value.models||[]]]});return(e,r)=>(L(),j(`div`,Nd,[V(td)===`Ready`?F(``,!0):(L(),j(`span`,Pd,B(V(td)),1)),A(V(Bu),{"model-value":t.value,"onUpdate:modelValue":r[0]||=e=>V(yd)(e===Fd?``:String(e??``))},{default:I(()=>[A(V(Wu),{size:`sm`,class:`w-full`,"aria-label":`Model`},{default:I(()=>[A(V(Gu))]),_:1}),A(V(Vu),null,{default:I(()=>[A(V(Uu),{value:Fd},{default:I(()=>[...r[1]||=[H(`Default`,-1)]]),_:1}),(L(!0),j(U,null,M(n.value,([e,t])=>(L(),q(V(Hu),{key:e},{default:I(()=>[e?(L(),q(V(Ate),{key:0},{default:I(()=>[H(B(e),1)]),_:2},1024)):F(``,!0),(L(!0),j(U,null,M(t,e=>(L(),q(V(Uu),{key:e,value:e},{default:I(()=>[H(B(e),1)]),_:2},1032,[`value`]))),128))]),_:2},1024))),128))]),_:1})]),_:1},8,[`model-value`])]))}}),Ld=P({__name:`ChatSessionActions`,setup(e){let t=J(!1);Hte(t);function n(e){t.value=!1,vd(e)}function r(e,n){t.value=!1,Gte(e,n)}return(e,i)=>(L(),q(V(Lu),{open:t.value,"onUpdate:open":i[5]||=e=>t.value=e},{default:I(()=>[A(V(zu),{"as-child":``},{default:I(()=>[A(V(X),{variant:`ghost`,size:`icon-sm`,class:`flex-none`,"aria-label":`More`,title:`More`},{default:I(()=>[A(V(tu))]),_:1})]),_:1}),A(V(Ru),{align:`end`,class:`grid w-64 gap-0.5 p-1`},{default:I(()=>[V(Qu)?(L(),j(U,{key:0},[A(V(X),{variant:`ghost`,size:`sm`,class:`justify-start`,onClick:i[0]||=e=>n(`/retry`)},{default:I(()=>[A(V(_te),{"data-icon":`inline-start`}),i[6]||=H(`Retry`,-1)]),_:1}),A(V(X),{variant:`ghost`,size:`sm`,class:`justify-start`,onClick:i[1]||=e=>n(`/undo`)},{default:I(()=>[A(V(Nu),{"data-icon":`inline-start`}),i[7]||=H(`Undo`,-1)]),_:1}),A(V(X),{variant:`ghost`,size:`sm`,class:`justify-start`,onClick:i[2]||=e=>r(`/title`,`Session title`)},{default:I(()=>[A(V(Cu),{"data-icon":`inline-start`}),i[8]||=H(`Rename`,-1)]),_:1}),A(V(X),{variant:`ghost`,size:`sm`,class:`justify-start`,onClick:i[3]||=e=>r(`/branch`,`Branch name (optional)`)},{default:I(()=>[A(V(lu),{"data-icon":`inline-start`}),i[9]||=H(`Branch`,-1)]),_:1}),A(V(X),{variant:`ghost`,size:`sm`,class:`justify-start`,onClick:i[4]||=e=>n(`/compress --preview`)},{default:I(()=>[A(V(xte),{"data-icon":`inline-start`}),i[10]||=H(`Preview compression`,-1)]),_:1}),A(V(Ote),{class:`my-1`})],64)):F(``,!0),A(Id)]),_:1})]),_:1},8,[`open`]))}}),Rd=new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`});function zd(e){return e.title||e.branch_name||(e.created_at?Rd.format(new Date(e.created_at)):`New chat`)}var Bd={class:`min-w-0 flex-1`},Vd=P({__name:`ChatSessionList`,setup(e){return(e,t)=>(L(),j(`div`,Bd,[A(V(Bu),{"model-value":V(Qu),disabled:!V(Zu).length,"onUpdate:modelValue":t[0]||=e=>V(hd)(String(e))},{default:I(()=>[A(V(Wu),{size:`sm`,class:`w-full`,"aria-label":`Conversation`},{default:I(()=>[A(V(Gu),{placeholder:`No conversations yet`})]),_:1}),A(V(Vu),null,{default:I(()=>[A(V(Hu),null,{default:I(()=>[(L(!0),j(U,null,M(V(Zu),e=>(L(),q(V(Uu),{key:e.session_id,value:e.session_id},{default:I(()=>[H(B(V(zd)(e)),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1})]),_:1},8,[`model-value`,`disabled`])]))}}),Hd={class:`flex items-center gap-1 border-b px-3 py-2`},Ud=P({__name:`ChatBar`,setup(e){return(e,t)=>(L(),j(`div`,Hd,[A(Vd),A(V(X),{variant:`ghost`,size:`icon-sm`,class:`flex-none`,title:`New chat`,"a Line truncated
`))],64)):K(n.$slots,`default`,{},void 0,void 0,1)])],10,vm))}}),xm=P({__name:`CodeBlockContent`,props:{wrap:{type:Boolean,default:!1},lineNumbers:{type:Boolean,default:!1},startLine:{default:1},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=me();function r(e){let t=``;for(let n of e)if(n.type!==Xe){if(n.type===Ke)t+=n.children;else if(n.type===U&&Array.isArray(n.children)){let e=r(n.children);if(e===null)return null;t+=e}else return null}return t}function i(){if(!t.lineNumbers)return null;let e=r(n.default?.()??[]);return e===null?null:e.replace(/\n$/,``).split(`
`)}return(n,r)=>(L(),q(V(dt),{as:`pre`,"data-slot":`code-block-content`,"data-wrap":e.wrap||void 0,"data-numbered":e.lineNumbers||void 0,dir:`ltr`,tabindex:`0`,style:et({counterReset:`line ${e.startLine-1}`}),class:z(V(W)(`px-3 py-3 leading-relaxed group-has-data-[slot=code-block-header]/code-block:pt-2 group-has-data-[slot=code-block-footer]/code-block:pb-2 group-data-[size=sm]/code-block:px-2.5 group-data-[size=sm]/code-block:py-2.5 group-data-[size=sm]/code-block:group-has-data-[slot=code-block-header]/code-block:pt-1.5 min-h-0 min-w-0 scroll-fade-x scrollbar-thin overflow-auto text-start font-mono outline-none data-wrap:scroll-fade-y data-wrap:wrap-break-word data-wrap:whitespace-pre-wrap`,t.class))},{default:I(()=>[A(V(dt),{as:`code`,"data-slot":`code-block-code`,class:`grid min-h-lh min-w-max content-start in-data-numbered:grid-cols-[auto_1fr] in-data-wrap:min-w-0`},{default:I(()=>[(L(!0),j(U,null,M([i()],(e,t)=>(L(),j(U,{key:t},[e?(L(!0),j(U,{key:0},M(e,(e,t)=>(L(),q(bm,{key:t},{default:I(()=>[H(B(e),1)]),_:2},1024))),128)):K(n.$slots,`default`,{},void 0,void 0,1)],64))),128))]),_:3})]),_:3},8,[`data-wrap`,`data-numbered`,`style`,`class`]))}}),Sm={"aria-live":`polite`,class:`sr-only`},Cm=P({inheritAttrs:!1,__name:`CodeBlockCopyButton`,props:{asChild:{type:Boolean},as:{default:`button`},value:{},variant:{default:`ghost`},size:{default:`icon-xs`},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,{copy:n,copied:r}=wt({copiedDuring:2e3,legacy:!0});return(i,a)=>(L(),j(U,null,[A(V(X),G(i.$attrs,{"data-slot":`code-block-copy-button`,"data-copied":V(r)||void 0,as:e.as,"as-child":e.asChild,variant:e.variant,size:e.size,"aria-label":V(r)?`Copied`:`Copy`,class:V(W)(``,t.class),onClick:a[0]||=e=>V(n)(t.value)}),{default:I(()=>[V(r)?(L(),q(V(Vl),{key:0})):(L(),q(V(Ql),{key:1}))]),_:1},16,[`data-copied`,`as`,`as-child`,`variant`,`size`,`aria-label`,`class`]),R(`span`,Sm,B(V(r)?`Copied`:``),1)],64))}}),wm=P({__name:`CodeBlockToken`,props:{token:{}},setup(e){return(t,n)=>(L(),j(`span`,{style:et(e.token.htmlStyle),class:`text-(--shiki-light) dark:text-(--shiki-dark)`},B(e.token.content),5))}}),Tm=class extends Error{constructor(e){super(e),this.name=`ShikiError`}};function Em(e){return Dm(e)}function Dm(e){return Array.isArray(e)?Om(e):e instanceof RegExp?e:typeof e==`object`?km(e):e}function Om(e){let t=[];for(let n=0,r=e.length;n<r;n++)t[n]=Dm(e[n]);return t}function km(e){let t={};for(let n in e)t[n]=Dm(e[n]);return t}function Am(e,...t){return t.forEach(t=>{for(let n in t)e[n]=t[n]}),e}function jm(e){let t=~e.lastIndexOf(`/`)||~e.lastIndexOf(`\\`);return t===0?e:~t===e.length-1?jm(e.substring(0,e.length-1)):e.substr(~t+1)}var Mm=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,Nm=class{static hasCaptures(e){return e!==null&&(Mm.lastIndex=0,Mm.test(e))}static replaceCaptures(e,t,n){return e.replace(Mm,(e,r,i,a)=>{let o=n[parseInt(r||i,10)];if(o){let e=t.substring(o.start,o.end);for(;e[0]===`.`;)e=e.substring(1);switch(a){case`downcase`:return e.toLowerCase();case`upcase`:return e.toUpperCase();default:return e}}else return e})}};function Pm(e,t){return e<t?-1:+(e>t)}function Fm(e,t){if(e===null&&t===null)return 0;if(!e)return-1;if(!t)return 1;let n=e.length,r=t.length;if(n===r){for(let r=0;r<n;r++){let n=Pm(e[r],t[r]);if(n!==0)return n}return 0}return n-r}function Im(e){return!!(/^#[0-9a-f]{6}$/i.test(e)||/^#[0-9a-f]{8}$/i.test(e)||/^#[0-9a-f]{3}$/i.test(e)||/^#[0-9a-f]{4}$/i.test(e))}function Lm(e){return e.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,`\\$&`)}var Rm=class{constructor(e){this.fn=e}cache=new Map;get(e){if(this.cache.has(e))return this.cache.get(e);let t=this.fn(e);return this.cache.set(e,t),t}},zm=class{constructor(e,t,n){this._colorMap=e,this._defaults=t,this._root=n}static createFromRawTheme(e,t){return this.createFromParsedTheme(Wm(e),t)}static createFromParsedTheme(e,t){return qm(e,t)}_cachedMatchRoot=new Rm(e=>this._root.match(e));getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(e){if(e===null)return this._defaults;let t=e.scopeName,n=this._cachedMatchRoot.get(t).find(t=>Vm(e.parent,t.parentScopes));return n?new Um(n.fontStyle,n.foreground,n.background):null}},Bm=class e{constructor(e,t){this.parent=e,this.scopeName=t}static push(t,n){for(let r of n)t=new e(t,r);return t}static from(...t){let n=null;for(let r=0;r<t.length;r++)n=new e(n,t[r]);return n}push(t){return new e(this,t)}getSegments(){let e=this,t=[];for(;e;)t.push(e.scopeName),e=e.parent;return t.reverse(),t}toString(){return this.getSegments().join(` `)}extends(e){return this===e||this.parent!==null&&this.parent.extends(e)}getExtensionIfDefined(e){let t=[],n=this;for(;n&&n!==e;)t.push(n.scopeName),n=n.parent;return n===e?t.reverse():void 0}};function Vm(e,t){if(t.length===0)return!0;for(let n=0;n<t.length;n++){let r=t[n],i=!1;if(r===`>`){if(n===t.length-1)return!1;r=t[++n],i=!0}for(;e&&!Hm(e.scopeName,r);){if(i)return!1;e=e.parent}if(!e)return!1;e=e.parent}return!0}function Hm( Line truncated
`)}findNextMatchSync(e,t,n){let r=this.scanner.findNextMatchSync(e,t,n);return r?{ruleId:this.rules[r.index],captureIndices:r.captureIndices}:null}},Fh=class{constructor(e,t){this.languageId=e,this.tokenType=t}},Ih=class e{_defaultAttributes;_embeddedLanguagesMatcher;constructor(e,t){this._defaultAttributes=new Fh(e,8),this._embeddedLanguagesMatcher=new Lh(Object.entries(t||{}))}getDefaultAttributes(){return this._defaultAttributes}getBasicScopeAttributes(t){return t===null?e._NULL_SCOPE_METADATA:this._getBasicScopeAttributes.get(t)}static _NULL_SCOPE_METADATA=new Fh(0,0);_getBasicScopeAttributes=new Rm(e=>new Fh(this._scopeToLanguage(e),this._toStandardTokenType(e)));_scopeToLanguage(e){return this._embeddedLanguagesMatcher.match(e)||0}_toStandardTokenType(t){let n=t.match(e.STANDARD_TOKEN_TYPE_REGEXP);if(!n)return 8;switch(n[1]){case`comment`:return 1;case`string`:return 2;case`regex`:return 3;case`meta.embedded`:return 0}throw Error(`Unexpected match for standard token type!`)}static STANDARD_TOKEN_TYPE_REGEXP=/\b(comment|string|regex|meta\.embedded)\b/},Lh=class{values;scopesRegExp;constructor(e){if(e.length===0)this.values=null,this.scopesRegExp=null;else{this.values=new Map(e);let t=e.map(([e,t])=>Lm(e));t.sort(),t.reverse(),this.scopesRegExp=RegExp(`^((${t.join(`)|(`)}))($|\\.)`,``)}}match(e){if(!this.scopesRegExp)return;let t=e.match(this.scopesRegExp);if(t)return this.values.get(t[1])}};typeof process<`u`&&{}.VSCODE_TEXTMATE_DEBUG;var Rh=class{constructor(e,t){this.stack=e,this.stoppedEarly=t}};function zh(e,t,n,r,i,a,o,s){let c=t.content.length,l=!1,u=-1;if(o){let o=Bh(e,t,n,r,i,a);i=o.stack,r=o.linePos,n=o.isFirstLine,u=o.anchorPosition}let d=Date.now();for(;!l;){if(s!==0&&Date.now()-d>s)return new Rh(i,!0);f()}return new Rh(i,!1);function f(){let o=Vh(e,t,n,r,i,u);if(!o){a.produce(i,c),l=!0;return}let s=o.captureIndices,d=o.matchedRuleId,f=s&&s.length>0?s[0].end>r:!1;if(d===xh){let o=i.getRule(e);a.produce(i,s[0].start),i=i.withContentNameScopesList(i.nameScopesList),Kh(e,t,n,i,a,o.endCaptures,s),a.produce(i,s[0].end);let d=i;if(i=i.parent,u=d.getAnchorPos(),!f&&d.getEnterPos()===r){i=d,a.produce(i,c),l=!0;return}}else{let o=e.getRule(d);a.produce(i,s[0].start);let p=i,m=o.getName(t.content,s),h=i.contentNameScopesList.pushAttributed(m,e);if(i=i.push(d,r,u,s[0].end===c,null,h,h),o instanceof kh){let r=o;Kh(e,t,n,i,a,r.beginCaptures,s),a.produce(i,s[0].end),u=s[0].end;let d=r.getContentName(t.content,s),m=h.pushAttributed(d,e);if(i=i.withContentNameScopesList(m),r.endHasBackReferences&&(i=i.withEndRule(r.getEndWithResolvedBackReferences(t.content,s))),!f&&p.hasSameRuleAs(i)){i=i.pop(),a.produce(i,c),l=!0;return}}else if(o instanceof Ah){let r=o;Kh(e,t,n,i,a,r.beginCaptures,s),a.produce(i,s[0].end),u=s[0].end;let d=r.getContentName(t.content,s),m=h.pushAttributed(d,e);if(i=i.withContentNameScopesList(m),r.whileHasBackReferences&&(i=i.withEndRule(r.getWhileWithResolvedBackReferences(t.content,s))),!f&&p.hasSameRuleAs(i)){i=i.pop(),a.produce(i,c),l=!0;return}}else if(Kh(e,t,n,i,a,o.captures,s),a.produce(i,s[0].end),i=i.pop(),!f){i=i.safePop(),a.produce(i,c),l=!0;return}}s[0].end>r&&(r=s[0].end,n=!1)}}function Bh(e,t,n,r,i,a){let o=i.beginRuleCapturedEOL?0:-1,s=[];for(let t=i;t;t=t.pop()){let n=t.getRule(e);n instanceof Ah&&s.push({rule:n,stack:t})}for(let c=s.pop();c;c=s.pop()){let{ruleScanner:s,findOptions:l}=Gh(c.rule,e,c.stack.endRule,n,r===o),u=s.findNextMatchSync(t,r,l);if(u){if(u.ruleId!==Sh){i=c.stack.pop();break}u.captureIndices&&u.captureIndices.length&&(a.produce(c.stack,u.captureIndices[0].start),Kh(e,t,n,c.stack,a,c.rule.whileCaptures,u.captureIndices),a.produce(c.stack,u.captureIndices[0].end),o=u.captureIndices[0].end,u.captureIndices[0].end>r&&(r=u.captureIndices[0].end,n=!1))}else{i=c.stack.pop();break}}return{stack:i,linePos:r,anchorPosition:o,isFirstLine:n}}function Vh(e,t,n,r,i,a){let o=Hh(e,t,n,r,i,a),s=e.getInjections();if(s.length===0)return o;let c=Uh(s,e,t,n,r,i,a);if(!c)return o;if(!o)return c;let l=o.captureIndices[0].start,u=c.captureIndices[0].start;return u<l||c.priorityMatch&&u===l?c:o}function Hh(e,t,n,r,i,a){let{ruleScanner:o,findOptions:s}=Wh(i.getRule(e),e,i.endRule,n,r===a),c=o.findNextMatchSync(t,r,s);return c?{captureIndices:c.captureIndices,matchedRuleId:c.ruleId}:null}function Uh(e,t,n,r,i,a,o){let s=Number.MAX_VALUE,c=null,l,u=0,d=a.contentNameScopesList.getScopeNames();for(let a=0,f=e.length;a<f;a++){let f=e[a];if(!f.matcher(d))continue;let{ruleScanner:p,findOptions:m}=Wh(t.getRule(f.ruleId),t,null,r,i===o),h=p.findNextMatchSync(n,i,m);if(!h)continue;let g=h.captureIndices[0].start;if(!(g>=s)&&(s=g,c=h.captureIndices,l=h.ruleId,u=f.priority,s===i))break}return c?{priorityMatch:u===-1,captureIndices:c,matchedRuleId:l}:null}function Wh(e,t,n,r,i){return{ruleScanner:e.compileAG(t,n,r,i),findOptions:0}}function Gh(e,t,n,r,i){return{ruleScanner:e.compileWhileAG(t,n,r,i),findOptions:0}}function Kh(e,t,n,r,i,a,o){if(a.length===0)return;let s=t.content,c=Math.min(a. Line truncated
`;let a=this.createOnigString(e),o=a.content.length,s=new rg(n,e,this._tokenTypeMatchers,this.balancedBracketSelectors),c=zh(this,a,i,0,t,s,!0,r);return ih(a),{lineLength:o,lineTokens:s,ruleStack:c.stack,stoppedEarly:c.stoppedEarly}}};function $h(e,t){return e=Em(e),e.repository=e.repository||{},e.repository.$self={$vscodeTextmateLocation:e.$vscodeTextmateLocation,patterns:e.patterns,name:e.scopeName},e.repository.$base=t||e.repository.$self,e}var eg=class e{constructor(e,t,n){this.parent=e,this.scopePath=t,this.tokenAttributes=n}static fromExtension(t,n){let r=t,i=t?.scopePath??null;for(let t of n)i=Bm.push(i,t.scopeNames),r=new e(r,i,t.encodedTokenAttributes);return r}static createRoot(t,n){return new e(null,new Bm(null,t),n)}static createRootAndLookUpScopeName(t,n,r){let i=r.getMetadataForScope(t),a=new Bm(null,t),o=r.themeProvider.themeMatch(a),s=e.mergeAttributes(n,i,o);return new e(null,a,s)}get scopeName(){return this.scopePath.scopeName}toString(){return this.getScopeNames().join(` `)}equals(t){return e.equals(this,t)}static equals(e,t){do{if(e===t||!e&&!t)return!0;if(!e||!t||e.scopeName!==t.scopeName||e.tokenAttributes!==t.tokenAttributes)return!1;e=e.parent,t=t.parent}while(1)}static mergeAttributes(e,t,n){let r=-1,i=0,a=0;return n!==null&&(r=n.fontStyle,i=n.foregroundId,a=n.backgroundId),Qm.set(e,t.languageId,t.tokenType,null,r,i,a)}pushAttributed(t,n){if(t===null)return this;if(t.indexOf(` `)===-1)return e._pushAttributed(this,t,n);let r=t.split(/ /g),i=this;for(let t of r)i=e._pushAttributed(i,t,n);return i}static _pushAttributed(t,n,r){let i=r.getMetadataForScope(n),a=t.scopePath.push(n),o=r.themeProvider.themeMatch(a),s=e.mergeAttributes(t.tokenAttributes,i,o);return new e(t,a,s)}getScopeNames(){return this.scopePath.getSegments()}getExtensionIfDefined(e){let t=[],n=this;for(;n&&n!==e;)t.push({encodedTokenAttributes:n.tokenAttributes,scopeNames:n.scopePath.getExtensionIfDefined(n.parent?.scopePath??null)}),n=n.parent;return n===e?t.reverse():void 0}},tg=class e{constructor(e,t,n,r,i,a,o,s){this.parent=e,this.ruleId=t,this.beginRuleCapturedEOL=i,this.endRule=a,this.nameScopesList=o,this.contentNameScopesList=s,this.depth=this.parent?this.parent.depth+1:1,this._enterPos=n,this._anchorPos=r}_stackElementBrand=void 0;static NULL=new e(null,0,0,0,!1,null,null,null);_enterPos;_anchorPos;depth;equals(t){return t!==null&&e._equals(this,t)}static _equals(e,t){return e===t?!0:this._structuralEquals(e,t)?eg.equals(e.contentNameScopesList,t.contentNameScopesList):!1}static _structuralEquals(e,t){do{if(e===t||!e&&!t)return!0;if(!e||!t||e.depth!==t.depth||e.ruleId!==t.ruleId||e.endRule!==t.endRule)return!1;e=e.parent,t=t.parent}while(1)}clone(){return this}static _reset(e){for(;e;)e._enterPos=-1,e._anchorPos=-1,e=e.parent}reset(){e._reset(this)}pop(){return this.parent}safePop(){return this.parent?this.parent:this}push(t,n,r,i,a,o,s){return new e(this,t,n,r,i,a,o,s)}getEnterPos(){return this._enterPos}getAnchorPos(){return this._anchorPos}getRule(e){return e.getRule(this.ruleId)}toString(){let e=[];return this._writeString(e,0),`[`+e.join(`,`)+`]`}_writeString(e,t){return this.parent&&(t=this.parent._writeString(e,t)),e[t++]=`(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`,t}withContentNameScopesList(e){return this.contentNameScopesList===e?this:this.parent.push(this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,this.endRule,this.nameScopesList,e)}withEndRule(t){return this.endRule===t?this:new e(this.parent,this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,t,this.nameScopesList,this.contentNameScopesList)}hasSameRuleAs(e){let t=this;for(;t&&t._enterPos===e._enterPos;){if(t.ruleId===e.ruleId)return!0;t=t.parent}return!1}toStateStackFrame(){return{ruleId:wh(this.ruleId),beginRuleCapturedEOL:this.beginRuleCapturedEOL,endRule:this.endRule,nameScopesList:this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList??null)??[],contentNameScopesList:this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList)??[]}}static pushFrame(t,n){let r=eg.fromExtension(t?.nameScopesList??null,n.nameScopesList);return new e(t,Ch(n.ruleId),n.enterPos??-1,n.anchorPos??-1,n.beginRuleCapturedEOL,n.endRule,r,eg.fromExtension(r,n.contentNameScopesList))}},ng=class{balancedBracketScopes;unbalancedBracketScopes;allowAny=!1;constructor(e,t){this.balancedBracketScopes=e.flatMap(e=>e===`*`?(this.allowAny=!0,[]):th(e,Xh).map(e=>e.matcher)),this.unbalancedBracketScopes=t.flatMap(e=>th(e,Xh).map(e=>e.matcher))}get matchesAlways(){return this.allowAny&&this.unbalancedBracketScopes.length===0}get matchesNever(){return this.balancedBracketScopes.length===0&&!this.allowAny}match(e){for(let t of this.unbalancedBracketScopes)if(t(e))return!1;for(let t of this.balancedBracketScopes)if(t(e))return!0;return this.allowAny}},rg=class{constructor(e,t,n,r){this.balancedBracketSelectors=r,this._emitBinaryTokens=e,this._tokenTypeOverrides=n,this._l Line truncated
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(Zu.value=n.session_id),n.type===`delta`&&(o+=n.text,rd.value=rd.value?{...rd.value,text:o}:null),(n.type===`tool`||n.type===`navigate`)&&(a=[...a,n],rd.value=rd.value?{...rd.value,tools:a}:null),n.type===`ask`&&n.ask&&(clearTimeout(l),rd.value=rd.value?{...rd.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`);Qu.value=!i&&n.trim()===`/new`?[]:[...Qu.value,{from:`assistant`,text:o,tool_calls:a}],rd.value=null,ed.value=`Ready`,await pd()}catch(e){let t=e;o&&(Qu.value=[...Qu.value,{from:`assistant`,text:o,tool_calls:a}],a=[]),t.name===`AbortError`&&!c?(rd.value={text:`Turn stopped.`,tools:a,isError:!1,turn:r,isRetry:i},ed.value=`Stopped`):(rd.value={text:`Unable to complete that turn: ${t.message||t}`,tools:a,isError:!0,turn:r?qu(r):void 0,isRetry:i},ed.value=`Error. Retry available.`)}finally{clearTimeout(l),Ju=null,dd=null,td.value=!1,yd.after?.()}}function Od(){ed.value=`Stopping…`,Zu.value&&Z.chatCancel(Zu.value).catch(()=>{}),fd()}function kd(){Be(()=>{pd().catch(e=>{ed.value=e.message||`Chat unavailable`})}),Ue(()=>{fd()})}async function Ad(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 Dd({textOverride:`🎤 Voice message`,voice:{data:btoa(n),mime_type:e.type||`audio/webm`}})}var jd={class:`grid gap-1 p-1`},Md={key:0,class:`text-xs text-fg-subtle`},Nd=`__default__`,Pd=P({__name:`ChatSettings`,setup(e){let t=Y(()=>ad.value||Nd),n=Y(()=>{let e=id.value.models_by_provider||{},t=Object.entries(e).filter(([,e])=>e.length);return t.length?t:[[``,id.value.models||[]]]});return(e,r)=>(L(),j(`div`,jd,[V(ed)===`Ready`?F(``,!0):(L(),j(`span`,Md,B(V(ed)),1)),A(V(zu),{"model-value":t.value,"onUpdate:modelValue":r[0]||=e=>V(vd)(e===Nd?``:String(e??``))},{default:I(()=>[A(V(Uu),{size:`sm`,class:`w-full`,"aria-label":`Model`},{default:I(()=>[A(V(Wu))]),_:1}),A(V(Bu),null,{default:I(()=>[A(V(Hu),{value:Nd},{default:I(()=>[...r[1]||=[H(`Default`,-1)]]),_:1}),(L(!0),j(U,null,M(n.value,([e,t])=>(L(),q(V(Vu),{key:e},{default:I(()=>[e?(L(),q(V(Ate),{key:0},{default:I(()=>[H(B(e),1)]),_:2},1024)):F(``,!0),(L(!0),j(U,null,M(t,e=>(L(),q(V(Hu),{key:e,value:e},{default:I(()=>[H(B(e),1)]),_:2},1032,[`value`]))),128))]),_:2},1024))),128))]),_:1})]),_:1},8,[`model-value`])]))}}),Fd=P({__name:`ChatSessionActions`,setup(e){let t=J(!1);Hte(t);function n(e){t.value=!1,_d(e)}function r(e,n){t.value=!1,Gte(e,n)}return(e,i)=>(L(),q(V(Iu),{open:t.value,"onUpdate:open":i[5]||=e=>t.value=e},{default:I(()=>[A(V(Ru),{"as-child":``},{default:I(()=>[A(V(X),{variant:`ghost`,size:`icon-sm`,class:`flex-none`,"aria-label":`More`,title:`More`},{default:I(()=>[A(V($l))]),_:1})]),_:1}),A(V(Lu),{align:`end`,class:`grid w-64 gap-0.5 p-1`},{default:I(()=>[V(Zu)?(L(),j(U,{key:0},[A(V(X),{variant:`ghost`,size:`sm`,class:`justify-start`,onClick:i[0]||=e=>n(`/retry`)},{default:I(()=>[A(V(_te),{"data-icon":`inline-start`}),i[6]||=H(`Retry`,-1)]),_:1}),A(V(X),{variant:`ghost`,size:`sm`,class:`justify-start`,onClick:i[1]||=e=>n(`/undo`)},{default:I(()=>[A(V(Mu),{"data-icon":`inline-start`}),i[7]||=H(`Undo`,-1)]),_:1}),A(V(X),{variant:`ghost`,size:`sm`,class:`justify-start`,onClick:i[2]||=e=>r(`/title`,`Session title`)},{default:I(()=>[A(V(Su),{"data-icon":`inline-start`}),i[8]||=H(`Rename`,-1)]),_:1}),A(V(X),{variant:`ghost`,size:`sm`,class:`justify-start`,onClick:i[3]||=e=>r(`/branch`,`Branch name (optional)`)},{default:I(()=>[A(V(su),{"data-icon":`inline-start`}),i[9]||=H(`Branch`,-1)]),_:1}),A(V(X),{variant:`ghost`,size:`sm`,class:`justify-start`,onClick:i[4]||=e=>n(`/compress --preview`)},{default:I(()=>[A(V(xte),{"data-icon":`inline-start`}),i[10]||=H(`Preview compression`,-1)]),_:1}),A(V(Ote),{class:`my-1`})],64)):F(``,!0),A(Pd)]),_:1})]),_:1},8,[`open`]))}}),Id=new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`});function Ld(e){return e.title||e.branch_name||(e.created_at?Id.format(new Date(e.created_at)):`New chat`)}var Rd={class:`min-w-0 flex-1`},zd=P({__name:`ChatSessionList`,setup(e){return(e,t)=>(L(),j(`div`,Rd,[A(V(zu),{"model-value":V(Zu),disabled:!V(Xu).length,"onUpdate:modelValue":t[0]||=e=>V(md)(String(e))},{default:I(()=>[A(V(Uu),{size:`sm`,class:`w-full`,"aria-label":`Conversation`},{default:I(()=>[A(V(Wu),{placeholder:`No conversations yet`})]),_:1}),A(V(Bu),null,{default:I(()=>[A(V(Vu),null,{default:I(()=>[(L(!0),j(U,null,M(V(Xu),e=>(L(),q(V(Hu),{key:e.session_id,value:e.session_id},{default:I(()=>[H(B(V(Ld)(e)),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1})]),_:1},8,[`model-value`,`disabled`])]))}}),Bd={class:`flex items-center gap-1 border-b px-3 py-2`},Vd=P({__name:`ChatBar`,setup(e){return(e,t)=>(L(),j(`div`,Bd,[A(zd),A(V(X),{variant:`ghost`,size:`icon-sm`,class:`flex-none`,title:`New chat`,"a Line truncated
`))],64)):K(n.$slots,`default`,{},void 0,void 0,1)])],10,gm))}}),ym=P({__name:`CodeBlockContent`,props:{wrap:{type:Boolean,default:!1},lineNumbers:{type:Boolean,default:!1},startLine:{default:1},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=me();function r(e){let t=``;for(let n of e)if(n.type!==Xe){if(n.type===Ke)t+=n.children;else if(n.type===U&&Array.isArray(n.children)){let e=r(n.children);if(e===null)return null;t+=e}else return null}return t}function i(){if(!t.lineNumbers)return null;let e=r(n.default?.()??[]);return e===null?null:e.replace(/\n$/,``).split(`
`)}return(n,r)=>(L(),q(V(dt),{as:`pre`,"data-slot":`code-block-content`,"data-wrap":e.wrap||void 0,"data-numbered":e.lineNumbers||void 0,dir:`ltr`,tabindex:`0`,style:et({counterReset:`line ${e.startLine-1}`}),class:z(V(W)(`px-3 py-3 leading-relaxed group-has-data-[slot=code-block-header]/code-block:pt-2 group-has-data-[slot=code-block-footer]/code-block:pb-2 group-data-[size=sm]/code-block:px-2.5 group-data-[size=sm]/code-block:py-2.5 group-data-[size=sm]/code-block:group-has-data-[slot=code-block-header]/code-block:pt-1.5 min-h-0 min-w-0 scroll-fade-x scrollbar-thin overflow-auto text-start font-mono outline-none data-wrap:scroll-fade-y data-wrap:wrap-break-word data-wrap:whitespace-pre-wrap`,t.class))},{default:I(()=>[A(V(dt),{as:`code`,"data-slot":`code-block-code`,class:`grid min-h-lh min-w-max content-start in-data-numbered:grid-cols-[auto_1fr] in-data-wrap:min-w-0`},{default:I(()=>[(L(!0),j(U,null,M([i()],(e,t)=>(L(),j(U,{key:t},[e?(L(!0),j(U,{key:0},M(e,(e,t)=>(L(),q(vm,{key:t},{default:I(()=>[H(B(e),1)]),_:2},1024))),128)):K(n.$slots,`default`,{},void 0,void 0,1)],64))),128))]),_:3})]),_:3},8,[`data-wrap`,`data-numbered`,`style`,`class`]))}}),bm={"aria-live":`polite`,class:`sr-only`},xm=P({inheritAttrs:!1,__name:`CodeBlockCopyButton`,props:{asChild:{type:Boolean},as:{default:`button`},value:{},variant:{default:`ghost`},size:{default:`icon-xs`},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,{copy:n,copied:r}=wt({copiedDuring:2e3,legacy:!0});return(i,a)=>(L(),j(U,null,[A(V(X),G(i.$attrs,{"data-slot":`code-block-copy-button`,"data-copied":V(r)||void 0,as:e.as,"as-child":e.asChild,variant:e.variant,size:e.size,"aria-label":V(r)?`Copied`:`Copy`,class:V(W)(``,t.class),onClick:a[0]||=e=>V(n)(t.value)}),{default:I(()=>[V(r)?(L(),q(V(zl),{key:0})):(L(),q(V(Xl),{key:1}))]),_:1},16,[`data-copied`,`as`,`as-child`,`variant`,`size`,`aria-label`,`class`]),R(`span`,bm,B(V(r)?`Copied`:``),1)],64))}}),Sm=P({__name:`CodeBlockToken`,props:{token:{}},setup(e){return(t,n)=>(L(),j(`span`,{style:et(e.token.htmlStyle),class:`text-(--shiki-light) dark:text-(--shiki-dark)`},B(e.token.content),5))}}),Cm=class extends Error{constructor(e){super(e),this.name=`ShikiError`}};function wm(e){return Tm(e)}function Tm(e){return Array.isArray(e)?Em(e):e instanceof RegExp?e:typeof e==`object`?Dm(e):e}function Em(e){let t=[];for(let n=0,r=e.length;n<r;n++)t[n]=Tm(e[n]);return t}function Dm(e){let t={};for(let n in e)t[n]=Tm(e[n]);return t}function Om(e,...t){return t.forEach(t=>{for(let n in t)e[n]=t[n]}),e}function km(e){let t=~e.lastIndexOf(`/`)||~e.lastIndexOf(`\\`);return t===0?e:~t===e.length-1?km(e.substring(0,e.length-1)):e.substr(~t+1)}var Am=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,jm=class{static hasCaptures(e){return e!==null&&(Am.lastIndex=0,Am.test(e))}static replaceCaptures(e,t,n){return e.replace(Am,(e,r,i,a)=>{let o=n[parseInt(r||i,10)];if(o){let e=t.substring(o.start,o.end);for(;e[0]===`.`;)e=e.substring(1);switch(a){case`downcase`:return e.toLowerCase();case`upcase`:return e.toUpperCase();default:return e}}else return e})}};function Mm(e,t){return e<t?-1:+(e>t)}function Nm(e,t){if(e===null&&t===null)return 0;if(!e)return-1;if(!t)return 1;let n=e.length,r=t.length;if(n===r){for(let r=0;r<n;r++){let n=Mm(e[r],t[r]);if(n!==0)return n}return 0}return n-r}function Pm(e){return!!(/^#[0-9a-f]{6}$/i.test(e)||/^#[0-9a-f]{8}$/i.test(e)||/^#[0-9a-f]{3}$/i.test(e)||/^#[0-9a-f]{4}$/i.test(e))}function Fm(e){return e.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,`\\$&`)}var Im=class{constructor(e){this.fn=e}cache=new Map;get(e){if(this.cache.has(e))return this.cache.get(e);let t=this.fn(e);return this.cache.set(e,t),t}},Lm=class{constructor(e,t,n){this._colorMap=e,this._defaults=t,this._root=n}static createFromRawTheme(e,t){return this.createFromParsedTheme(Hm(e),t)}static createFromParsedTheme(e,t){return Gm(e,t)}_cachedMatchRoot=new Im(e=>this._root.match(e));getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(e){if(e===null)return this._defaults;let t=e.scopeName,n=this._cachedMatchRoot.get(t).find(t=>zm(e.parent,t.parentScopes));return n?new Vm(n.fontStyle,n.foreground,n.background):null}},Rm=class e{constructor(e,t){this.parent=e,this.scopeName=t}static push(t,n){for(let r of n)t=new e(t,r);return t}static from(...t){let n=null;for(let r=0;r<t.length;r++)n=new e(n,t[r]);return n}push(t){return new e(this,t)}getSegments(){let e=this,t=[];for(;e;)t.push(e.scopeName),e=e.parent;return t.reverse(),t}toString(){return this.getSegments().join(` `)}extends(e){return this===e||this.parent!==null&&this.parent.extends(e)}getExtensionIfDefined(e){let t=[],n=this;for(;n&&n!==e;)t.push(n.scopeName),n=n.parent;return n===e?t.reverse():void 0}};function zm(e,t){if(t.length===0)return!0;for(let n=0;n<t.length;n++){let r=t[n],i=!1;if(r===`>`){if(n===t.length-1)return!1;r=t[++n],i=!0}for(;e&&!Bm(e.scopeName,r);){if(i)return!1;e=e.parent}if(!e)return!1;e=e.parent}return!0}function Bm( Line truncated
`)}findNextMatchSync(e,t,n){let r=this.scanner.findNextMatchSync(e,t,n);return r?{ruleId:this.rules[r.index],captureIndices:r.captureIndices}:null}},Nh=class{constructor(e,t){this.languageId=e,this.tokenType=t}},Ph=class e{_defaultAttributes;_embeddedLanguagesMatcher;constructor(e,t){this._defaultAttributes=new Nh(e,8),this._embeddedLanguagesMatcher=new Fh(Object.entries(t||{}))}getDefaultAttributes(){return this._defaultAttributes}getBasicScopeAttributes(t){return t===null?e._NULL_SCOPE_METADATA:this._getBasicScopeAttributes.get(t)}static _NULL_SCOPE_METADATA=new Nh(0,0);_getBasicScopeAttributes=new Im(e=>new Nh(this._scopeToLanguage(e),this._toStandardTokenType(e)));_scopeToLanguage(e){return this._embeddedLanguagesMatcher.match(e)||0}_toStandardTokenType(t){let n=t.match(e.STANDARD_TOKEN_TYPE_REGEXP);if(!n)return 8;switch(n[1]){case`comment`:return 1;case`string`:return 2;case`regex`:return 3;case`meta.embedded`:return 0}throw Error(`Unexpected match for standard token type!`)}static STANDARD_TOKEN_TYPE_REGEXP=/\b(comment|string|regex|meta\.embedded)\b/},Fh=class{values;scopesRegExp;constructor(e){if(e.length===0)this.values=null,this.scopesRegExp=null;else{this.values=new Map(e);let t=e.map(([e,t])=>Fm(e));t.sort(),t.reverse(),this.scopesRegExp=RegExp(`^((${t.join(`)|(`)}))($|\\.)`,``)}}match(e){if(!this.scopesRegExp)return;let t=e.match(this.scopesRegExp);if(t)return this.values.get(t[1])}};typeof process<`u`&&{}.VSCODE_TEXTMATE_DEBUG;var Ih=class{constructor(e,t){this.stack=e,this.stoppedEarly=t}};function Lh(e,t,n,r,i,a,o,s){let c=t.content.length,l=!1,u=-1;if(o){let o=Rh(e,t,n,r,i,a);i=o.stack,r=o.linePos,n=o.isFirstLine,u=o.anchorPosition}let d=Date.now();for(;!l;){if(s!==0&&Date.now()-d>s)return new Ih(i,!0);f()}return new Ih(i,!1);function f(){let o=zh(e,t,n,r,i,u);if(!o){a.produce(i,c),l=!0;return}let s=o.captureIndices,d=o.matchedRuleId,f=s&&s.length>0?s[0].end>r:!1;if(d===yh){let o=i.getRule(e);a.produce(i,s[0].start),i=i.withContentNameScopesList(i.nameScopesList),Wh(e,t,n,i,a,o.endCaptures,s),a.produce(i,s[0].end);let d=i;if(i=i.parent,u=d.getAnchorPos(),!f&&d.getEnterPos()===r){i=d,a.produce(i,c),l=!0;return}}else{let o=e.getRule(d);a.produce(i,s[0].start);let p=i,m=o.getName(t.content,s),h=i.contentNameScopesList.pushAttributed(m,e);if(i=i.push(d,r,u,s[0].end===c,null,h,h),o instanceof Dh){let r=o;Wh(e,t,n,i,a,r.beginCaptures,s),a.produce(i,s[0].end),u=s[0].end;let d=r.getContentName(t.content,s),m=h.pushAttributed(d,e);if(i=i.withContentNameScopesList(m),r.endHasBackReferences&&(i=i.withEndRule(r.getEndWithResolvedBackReferences(t.content,s))),!f&&p.hasSameRuleAs(i)){i=i.pop(),a.produce(i,c),l=!0;return}}else if(o instanceof Oh){let r=o;Wh(e,t,n,i,a,r.beginCaptures,s),a.produce(i,s[0].end),u=s[0].end;let d=r.getContentName(t.content,s),m=h.pushAttributed(d,e);if(i=i.withContentNameScopesList(m),r.whileHasBackReferences&&(i=i.withEndRule(r.getWhileWithResolvedBackReferences(t.content,s))),!f&&p.hasSameRuleAs(i)){i=i.pop(),a.produce(i,c),l=!0;return}}else if(Wh(e,t,n,i,a,o.captures,s),a.produce(i,s[0].end),i=i.pop(),!f){i=i.safePop(),a.produce(i,c),l=!0;return}}s[0].end>r&&(r=s[0].end,n=!1)}}function Rh(e,t,n,r,i,a){let o=i.beginRuleCapturedEOL?0:-1,s=[];for(let t=i;t;t=t.pop()){let n=t.getRule(e);n instanceof Oh&&s.push({rule:n,stack:t})}for(let c=s.pop();c;c=s.pop()){let{ruleScanner:s,findOptions:l}=Uh(c.rule,e,c.stack.endRule,n,r===o),u=s.findNextMatchSync(t,r,l);if(u){if(u.ruleId!==bh){i=c.stack.pop();break}u.captureIndices&&u.captureIndices.length&&(a.produce(c.stack,u.captureIndices[0].start),Wh(e,t,n,c.stack,a,c.rule.whileCaptures,u.captureIndices),a.produce(c.stack,u.captureIndices[0].end),o=u.captureIndices[0].end,u.captureIndices[0].end>r&&(r=u.captureIndices[0].end,n=!1))}else{i=c.stack.pop();break}}return{stack:i,linePos:r,anchorPosition:o,isFirstLine:n}}function zh(e,t,n,r,i,a){let o=Bh(e,t,n,r,i,a),s=e.getInjections();if(s.length===0)return o;let c=Vh(s,e,t,n,r,i,a);if(!c)return o;if(!o)return c;let l=o.captureIndices[0].start,u=c.captureIndices[0].start;return u<l||c.priorityMatch&&u===l?c:o}function Bh(e,t,n,r,i,a){let{ruleScanner:o,findOptions:s}=Hh(i.getRule(e),e,i.endRule,n,r===a),c=o.findNextMatchSync(t,r,s);return c?{captureIndices:c.captureIndices,matchedRuleId:c.ruleId}:null}function Vh(e,t,n,r,i,a,o){let s=Number.MAX_VALUE,c=null,l,u=0,d=a.contentNameScopesList.getScopeNames();for(let a=0,f=e.length;a<f;a++){let f=e[a];if(!f.matcher(d))continue;let{ruleScanner:p,findOptions:m}=Hh(t.getRule(f.ruleId),t,null,r,i===o),h=p.findNextMatchSync(n,i,m);if(!h)continue;let g=h.captureIndices[0].start;if(!(g>=s)&&(s=g,c=h.captureIndices,l=h.ruleId,u=f.priority,s===i))break}return c?{priorityMatch:u===-1,captureIndices:c,matchedRuleId:l}:null}function Hh(e,t,n,r,i){return{ruleScanner:e.compileAG(t,n,r,i),findOptions:0}}function Uh(e,t,n,r,i){return{ruleScanner:e.compileWhileAG(t,n,r,i),findOptions:0}}function Wh(e,t,n,r,i,a,o){if(a.length===0)return;let s=t.content,c=Math.min(a. Line truncated
`;let a=this.createOnigString(e),o=a.content.length,s=new tg(n,e,this._tokenTypeMatchers,this.balancedBracketSelectors),c=Lh(this,a,i,0,t,s,!0,r);return nh(a),{lineLength:o,lineTokens:s,ruleStack:c.stack,stoppedEarly:c.stoppedEarly}}};function Zh(e,t){return e=wm(e),e.repository=e.repository||{},e.repository.$self={$vscodeTextmateLocation:e.$vscodeTextmateLocation,patterns:e.patterns,name:e.scopeName},e.repository.$base=t||e.repository.$self,e}var Qh=class e{constructor(e,t,n){this.parent=e,this.scopePath=t,this.tokenAttributes=n}static fromExtension(t,n){let r=t,i=t?.scopePath??null;for(let t of n)i=Rm.push(i,t.scopeNames),r=new e(r,i,t.encodedTokenAttributes);return r}static createRoot(t,n){return new e(null,new Rm(null,t),n)}static createRootAndLookUpScopeName(t,n,r){let i=r.getMetadataForScope(t),a=new Rm(null,t),o=r.themeProvider.themeMatch(a),s=e.mergeAttributes(n,i,o);return new e(null,a,s)}get scopeName(){return this.scopePath.scopeName}toString(){return this.getScopeNames().join(` `)}equals(t){return e.equals(this,t)}static equals(e,t){do{if(e===t||!e&&!t)return!0;if(!e||!t||e.scopeName!==t.scopeName||e.tokenAttributes!==t.tokenAttributes)return!1;e=e.parent,t=t.parent}while(1)}static mergeAttributes(e,t,n){let r=-1,i=0,a=0;return n!==null&&(r=n.fontStyle,i=n.foregroundId,a=n.backgroundId),Xm.set(e,t.languageId,t.tokenType,null,r,i,a)}pushAttributed(t,n){if(t===null)return this;if(t.indexOf(` `)===-1)return e._pushAttributed(this,t,n);let r=t.split(/ /g),i=this;for(let t of r)i=e._pushAttributed(i,t,n);return i}static _pushAttributed(t,n,r){let i=r.getMetadataForScope(n),a=t.scopePath.push(n),o=r.themeProvider.themeMatch(a),s=e.mergeAttributes(t.tokenAttributes,i,o);return new e(t,a,s)}getScopeNames(){return this.scopePath.getSegments()}getExtensionIfDefined(e){let t=[],n=this;for(;n&&n!==e;)t.push({encodedTokenAttributes:n.tokenAttributes,scopeNames:n.scopePath.getExtensionIfDefined(n.parent?.scopePath??null)}),n=n.parent;return n===e?t.reverse():void 0}},$h=class e{constructor(e,t,n,r,i,a,o,s){this.parent=e,this.ruleId=t,this.beginRuleCapturedEOL=i,this.endRule=a,this.nameScopesList=o,this.contentNameScopesList=s,this.depth=this.parent?this.parent.depth+1:1,this._enterPos=n,this._anchorPos=r}_stackElementBrand=void 0;static NULL=new e(null,0,0,0,!1,null,null,null);_enterPos;_anchorPos;depth;equals(t){return t!==null&&e._equals(this,t)}static _equals(e,t){return e===t?!0:this._structuralEquals(e,t)?Qh.equals(e.contentNameScopesList,t.contentNameScopesList):!1}static _structuralEquals(e,t){do{if(e===t||!e&&!t)return!0;if(!e||!t||e.depth!==t.depth||e.ruleId!==t.ruleId||e.endRule!==t.endRule)return!1;e=e.parent,t=t.parent}while(1)}clone(){return this}static _reset(e){for(;e;)e._enterPos=-1,e._anchorPos=-1,e=e.parent}reset(){e._reset(this)}pop(){return this.parent}safePop(){return this.parent?this.parent:this}push(t,n,r,i,a,o,s){return new e(this,t,n,r,i,a,o,s)}getEnterPos(){return this._enterPos}getAnchorPos(){return this._anchorPos}getRule(e){return e.getRule(this.ruleId)}toString(){let e=[];return this._writeString(e,0),`[`+e.join(`,`)+`]`}_writeString(e,t){return this.parent&&(t=this.parent._writeString(e,t)),e[t++]=`(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`,t}withContentNameScopesList(e){return this.contentNameScopesList===e?this:this.parent.push(this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,this.endRule,this.nameScopesList,e)}withEndRule(t){return this.endRule===t?this:new e(this.parent,this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,t,this.nameScopesList,this.contentNameScopesList)}hasSameRuleAs(e){let t=this;for(;t&&t._enterPos===e._enterPos;){if(t.ruleId===e.ruleId)return!0;t=t.parent}return!1}toStateStackFrame(){return{ruleId:Sh(this.ruleId),beginRuleCapturedEOL:this.beginRuleCapturedEOL,endRule:this.endRule,nameScopesList:this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList??null)??[],contentNameScopesList:this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList)??[]}}static pushFrame(t,n){let r=Qh.fromExtension(t?.nameScopesList??null,n.nameScopesList);return new e(t,xh(n.ruleId),n.enterPos??-1,n.anchorPos??-1,n.beginRuleCapturedEOL,n.endRule,r,Qh.fromExtension(r,n.contentNameScopesList))}},eg=class{balancedBracketScopes;unbalancedBracketScopes;allowAny=!1;constructor(e,t){this.balancedBracketScopes=e.flatMap(e=>e===`*`?(this.allowAny=!0,[]):$m(e,Jh).map(e=>e.matcher)),this.unbalancedBracketScopes=t.flatMap(e=>$m(e,Jh).map(e=>e.matcher))}get matchesAlways(){return this.allowAny&&this.unbalancedBracketScopes.length===0}get matchesNever(){return this.balancedBracketScopes.length===0&&!this.allowAny}match(e){for(let t of this.unbalancedBracketScopes)if(t(e))return!1;for(let t of this.balancedBracketScopes)if(t(e))return!0;return this.allowAny}},tg=class{constructor(e,t,n,r){this.balancedBracketSelectors=r,this._emitBinaryTokens=e,this._tokenTypeOverrides=n,this._l Line truncated
\f\r &/=>`.split(``),`
\f\r "&'/=>\``.split(``)],[`\0
\f\r "&'/<=>`.split(``),`\0
@@ -14,10 +14,10 @@ import{A as e,B as t,C as n,D as r,E as i,F as a,H as o,I as s,L as c,M as l,N a
\f\r &>`.split(``),`\0
\f\r "&'<=>\``.split(``)],[`\0
\f\r "&'<=>\``.split(``),`\0
\f\r "&'<=>\``.split(``)]],single:[[`&'`.split(``),`"&'\``.split(``)],[`\0&'`.split(``),`\0"&'\``.split(``)]],double:[[`"&`.split(``),`"&'\``.split(``)],[`\0"&`.split(``),`\0"&'\``.split(``)]]};function zv(e,t,n,r){let i=r.schema,a=i.space!==`svg`&&r.settings.omitOptionalTags,o=i.space===`svg`?r.settings.closeEmptyElements:r.settings.voids.includes(e.tagName.toLowerCase()),s=[],c;i.space===`html`&&e.tagName===`svg`&&(r.schema=O_);let l=Bv(r,e.properties),u=r.all(i.space===`html`&&e.tagName===`template`?e.content:e);return r.schema=i,u&&(o=!1),(l||!a||!Mv(e,t,n))&&(s.push(`<`,e.tagName,l?` `+l:``),o&&(i.space===`svg`||r.settings.closeSelfClosing)&&(c=l.charAt(l.length-1),(!r.settings.tightSelfClosing||c===`/`||c&&c!==`"`&&c!==`'`)&&s.push(` `),s.push(`/`)),s.push(`>`)),s.push(u),!o&&(!a||!gv(e,t,n))&&s.push(`</`+e.tagName+`>`),s.join(``)}function Bv(e,t){let n=[],r=-1,i;if(t){for(i in t)if(t[i]!==null&&t[i]!==void 0){let r=Vv(e,i,t[i]);r&&n.push(r)}}for(;++r<n.length;){let t=e.settings.tightAttributes?n[r].charAt(n[r].length-1):void 0;r!==n.length-1&&t!==`"`&&t!==`'`&&(n[r]+=` `)}return n.join(``)}function Vv(e,t,n){let r=w_(e.schema,t),i=e.settings.allowParseErrors&&e.schema.space===`html`?0:1,a=+!e.settings.allowDangerousCharacters,o=e.quote,s;if(r.overloadedBoolean&&(n===r.attribute||n===``)?n=!0:(r.boolean||r.overloadedBoolean)&&(typeof n!=`string`||n===r.attribute||n===``)&&(n=!!n),n==null||n===!1||typeof n==`number`&&Number.isNaN(n))return``;let c=Q_(r.attribute,Object.assign({},e.settings.characterReferences,{subset:Rv.name[i][a]}));return n===!0||(n=Array.isArray(n)?(r.commaSeparated?av:ov)(n,{padLeft:!e.settings.tightCommaSeparatedLists}):String(n),e.settings.collapseEmptyAttributes&&!n)?c:(e.settings.preferUnquoted&&(s=Q_(n,Object.assign({},e.settings.characterReferences,{attribute:!0,subset:Rv.unquoted[i][a]}))),s!==n&&(e.settings.quoteSmart&&iv(n,o)>iv(n,e.alternative)&&(o=e.alternative),s=o+Q_(n,Object.assign({},e.settings.characterReferences,{subset:(o===`'`?Rv.single:Rv.double)[i][a],attribute:!0}))+o),c+(s&&`=`+s))}var Hv=[`<`,`&`];function Uv(e,t,n,r){return n&&n.type===`element`&&(n.tagName===`script`||n.tagName===`style`)?e.value:Q_(e.value,Object.assign({},r.settings.characterReferences,{subset:Hv}))}function Wv(e,t,n,r){return r.settings.allowDangerousHtml?e.value:Uv(e,t,n,r)}function Gv(e,t,n,r){return r.all(e)}var Kv=A_(`type`,{invalid:qv,unknown:Jv,handlers:{comment:nv,doctype:rv,element:zv,raw:Wv,root:Gv,text:Uv}});function qv(e){throw Error("Expected node, not `"+e+"`")}function Jv(e){throw Error("Cannot compile unknown node `"+e.type+"`")}var Yv={},Xv={},Zv=[];function Qv(e,t){let n=t||Yv,r=n.quote||`"`,i=r===`"`?`'`:`"`;if(r!==`"`&&r!==`'`)throw Error("Invalid quote `"+r+"`, expected `'` or `\"`");return{one:$v,all:ey,settings:{omitOptionalTags:n.omitOptionalTags||!1,allowParseErrors:n.allowParseErrors||!1,allowDangerousCharacters:n.allowDangerousCharacters||!1,quoteSmart:n.quoteSmart||!1,preferUnquoted:n.preferUnquoted||!1,tightAttributes:n.tightAttributes||!1,upperDoctype:n.upperDoctype||!1,tightDoctype:n.tightDoctype||!1,bogusComments:n.bogusComments||!1,tightCommaSeparatedLists:n.tightCommaSeparatedLists||!1,tightSelfClosing:n.tightSelfClosing||!1,collapseEmptyAttributes:n.collapseEmptyAttributes||!1,allowDangerousHtml:n.allowDangerousHtml||!1,voids:n.voids||Jg,characterReferences:n.characterReferences||Xv,closeSelfClosing:n.closeSelfClosing||!1,closeEmptyElements:n.closeEmptyElements||!1},schema:n.space===`svg`?O_:D_,quote:r,alternative:i}.one(Array.isArray(e)?{type:`root`,children:e}:e,void 0,void 0)}function $v(e,t,n){return Kv(e,t,n,this)}function ey(e){let t=[],n=e&&e.children||Zv,r=-1;for(;++r<n.length;)t[r]=this.one(n[r],r,e);return t.join(``)}var ty=/\s+/g;function ny(e,t){if(!t)return e;e.properties||={},e.properties.class||=[],typeof e.properties.class==`string`&&(e.properties.class=e.properties.class.split(ty)),Array.isArray(e.properties.class)||(e.properties.class=[]);let n=Array.isArray(t)?t:t.split(ty);for(let t of n)t&&!e.properties.class.includes(t)&&e.properties.class.push(t);return e}function ry(e){let t=gg(e,!0).map(([e])=>e);function n(n){if(n===e.length)return{line:t.length-1,character:t.at(-1).length};let r=n,i=0;for(let e of t){if(r<e.length)break;r-=e.length,i++}return{line:i,character:r}}function r(e,n){let r=0;for(let n=0;n<e;n++)r+=t[n].length;return r+=n,r}return{lines:t,indexToPos:n,posToIndex:r}}var iy=[`color`,`background-color`];function ay(e,t){let n=0,r=[];for(let i of t)i>n&&r.push({...e,content:e.content.slice(n,i),offset:e.offset+n}),n=i;return n<e.content.length&&r.push({...e,content:e.content.slice(n),offset:e.offset+n}),r}function oy(e,t){let n=0,r=e.length;for(;n<r;){let i=n+(r-n>>1);e[i]<=t?n=i+1:r=i}return n}function sy(e,t){let n=[...t instanceof Set?t:new Set(t)].sort((e,t)=>e-t);return n.length?e.map(e=>e.flatMap(e=>{let t=e.offset+e.content.length,r=oy(n,e.offset),i=r;for(;i<n.length&&n[i]<t;)i++;if(r===i)return e;let a=n.slice(rLine truncated
`}));let n={type:`element`,tagName:`span`,properties:{class:`line`},children:[]},r=0;for(let a of e){let e={type:`element`,tagName:`span`,properties:{...a.htmlAttrs},children:[{type:`text`,value:a.content}]},c=uy(a.htmlStyle||ly(a));c&&(e.properties.style=c);for(let o of i)e=o?.span?.call(p,e,t+1,r,n,a)||e;s===`inline`?o.children.push(e):s===`classic`&&n.children.push(e),r+=a.content.length}if(s===`classic`){for(let e of i)n=e?.line?.call(p,n,t+1)||n;f.push(n),a.push(n)}else s===`inline`&&f.push(n)}),s===`classic`){for(let e of i)d=e?.code?.call(p,d)||d;u.children.push(d);for(let e of i)u=e?.pre?.call(p,u)||u;o.children.push(u)}else if(s===`inline`){let e=[],t={type:`element`,tagName:`span`,properties:{class:`line`},children:[]};for(let n of o.children)n.type===`element`&&n.tagName===`br`?(e.push(t),t={type:`element`,tagName:`span`,properties:{class:`line`},children:[]}):(n.type===`element`||n.type===`text`)&&t.children.push(n);e.push(t);let n={type:`element`,tagName:`code`,properties:{},children:e};for(let e of i)n=e?.code?.call(p,n)||n;o.children=[];for(let e=0;e<n.children.length;e++){e>0&&o.children.push({type:`element`,tagName:`br`,properties:{},children:[]});let t=n.children[e];t.type===`element`&&o.children.push(...t.children)}}let m=o;for(let e of i)m=e?.root?.call(p,m)||m;return r&&Ag(m,r),m}function Ly(e){return e.map(e=>{let t=[],n=``,r;return e.forEach((i,a)=>{let o=!(i.fontStyle&&(i.fontStyle&Km.Underline||i.fontStyle&Km.Strikethrough));o&&Ny.test(i.content)&&e[a+1]?(r===void 0&&(r=i.offset),n+=i.content):n?(o?t.push({...i,offset:r,content:n+i.content}):t.push({content:n,offset:r},i),r=void 0,n=``):t.push(i)}),t})}function Ry(e){return e.map(e=>e.flatMap(e=>{if(Ny.test(e.content))return e;let t=e.content.match(Py);if(!t)return e;let[,n,r,i]=t;if(!n&&!i)return e;let a=[{...e,offset:e.offset+n.length,content:r}];return n&&a.unshift({content:n,offset:e.offset}),i&&a.push({content:i,offset:e.offset+n.length+r.length}),a}))}function zy(e){return e.map(e=>{let t=[];for(let n of e){if(t.length===0){t.push({...n});continue}let e=t.at(-1),r=uy(e.htmlStyle||ly(e)),i=uy(n.htmlStyle||ly(n)),a=e.fontStyle&&(e.fontStyle&Km.Underline||e.fontStyle&Km.Strikethrough),o=n.fontStyle&&(n.fontStyle&Km.Underline||n.fontStyle&Km.Strikethrough);!a&&!o&&r===i?e.content+=n.content:t.push({...n})}return t})}var By=Qv;function Vy(e,t,n){let r={meta:{},options:n,codeToHast:(t,n)=>Fy(e,t,n),codeToTokens:(t,n)=>jy(e,t,n)},i=By(Fy(e,t,n,r));for(let e of hy(n))i=e.postprocess?.call(r,i,n)||i;return i}async function Hy(e){let t=await Og(e);return{getLastGrammarState:(...e)=>Rg(t,...e),codeToTokensBase:(e,n)=>Ay(t,e,n),codeToTokensWithThemes:(e,n)=>Kg(t,e,n),codeToTokens:(e,n)=>jy(t,e,n),codeToHast:(e,n)=>Fy(t,e,n),codeToHtml:(e,n)=>Vy(t,e,n),getBundledLanguages:()=>({}),getBundledThemes:()=>({}),...t,getInternalContext:()=>t}}var Uy=4294967295;function Wy(e){return!e.sticky&&!e.rawOptions?.strategy}function Gy(e,t){return{index:e,captureIndices:t.map(e=>e==null?{start:Uy,end:Uy,length:0}:{start:e[0],end:e[1],length:e[1]-e[0]})}}var Ky=class{patterns;options;regexps;lastSearches;constructor(e,t={}){this.patterns=e,this.options=t;let{forgiving:n=!1,cache:r,regexConstructor:i}=t;if(!i)throw Error("Option `regexConstructor` is not provided");this.regexps=e.map(e=>{if(typeof e!=`string`)return e;let t=r?.get(e);if(t){if(t instanceof RegExp)return t;if(n)return null;throw t}try{let t=i(e);return r?.set(e,t),t}catch(t){if(r?.set(e,t),n)return null;throw t}}),this.lastSearches=this.regexps.map(e=>e&&Wy(e)?{strId:0,searchedFrom:0,matchIndex:-1,indices:null}:null)}findNextMatchSync(e,t,n){let r=typeof e==`string`?e:e.content,i=typeof e==`string`?0:e.id||0,a=-1,o=0,s=null;for(let e=0;e<this.regexps.length;e++){let n=this.regexps[e];if(n)try{let c=i?this.lastSearches[e]:null,l,u;if(c&&c.strId===i&&c.searchedFrom<=t&&(c.matchIndex===-1||c.matchIndex>=t))l=c.matchIndex,u=c.indices;else{n.lastIndex=t;let e=n.exec(r);l=e?e.index:-1,u=e?e.indices:null,c&&(c.strId=i,c.searchedFrom=t,c.matchIndex=l,c.indices=u)}if(l===-1)continue;if(l===t)return Gy(e,u);(a===-1||l<o)&&(a=e,o=l,s=u)}catch(e){if(this.options.forgiving)continue;throw e}}return a===-1?null:Gy(a,s)}},qy=0;function Jy(e){return{content:e,id:++qy}}function Yy(e){if([...e].length!==1)throw Error(`Expected "${e}" to be a single code point`);return e.codePointAt(0)}function Xy(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}var Zy=new Set([`alnum`,`alpha`,`ascii`,`blank`,`cntrl`,`digit`,`graph`,`lower`,`print`,`punct`,`space`,`upper`,`word`,`xdigit`]),Qy=String.raw;function $y(e,t){if(e==null)throw Error(t??`Value expected`);return e}var eb=Qy`\[\^?`,tb=`c.? | C(?:-.?)?|${Qy`[pP]\{(?:\^?[-\x20_]*[A-Za-z][-\x20\w]*\})?`}|${Qy`x[89A-Fa-f]\p{AHex}(?:\\x[89A-Fa-f]\p{AHex})*`}|${Qy`u(?:\p{AHex}{4})? | x\{[^\}]*\}? | x\p{AHex}{0,2}`}|${Qy`o\{[^\}]*\}?`}|${Qy`\d{1,3}`}`,nb=/[?*+][?+]?|\{(?:\d+(?:,\d*)?|,\d+)\}\??/,rb=new RegExp(Qy`
\f\r "&'<=>\``.split(``)]],single:[[`&'`.split(``),`"&'\``.split(``)],[`\0&'`.split(``),`\0"&'\``.split(``)]],double:[[`"&`.split(``),`"&'\``.split(``)],[`\0"&`.split(``),`\0"&'\``.split(``)]]};function Lv(e,t,n,r){let i=r.schema,a=i.space!==`svg`&&r.settings.omitOptionalTags,o=i.space===`svg`?r.settings.closeEmptyElements:r.settings.voids.includes(e.tagName.toLowerCase()),s=[],c;i.space===`html`&&e.tagName===`svg`&&(r.schema=E_);let l=Rv(r,e.properties),u=r.all(i.space===`html`&&e.tagName===`template`?e.content:e);return r.schema=i,u&&(o=!1),(l||!a||!Av(e,t,n))&&(s.push(`<`,e.tagName,l?` `+l:``),o&&(i.space===`svg`||r.settings.closeSelfClosing)&&(c=l.charAt(l.length-1),(!r.settings.tightSelfClosing||c===`/`||c&&c!==`"`&&c!==`'`)&&s.push(` `),s.push(`/`)),s.push(`>`)),s.push(u),!o&&(!a||!mv(e,t,n))&&s.push(`</`+e.tagName+`>`),s.join(``)}function Rv(e,t){let n=[],r=-1,i;if(t){for(i in t)if(t[i]!==null&&t[i]!==void 0){let r=zv(e,i,t[i]);r&&n.push(r)}}for(;++r<n.length;){let t=e.settings.tightAttributes?n[r].charAt(n[r].length-1):void 0;r!==n.length-1&&t!==`"`&&t!==`'`&&(n[r]+=` `)}return n.join(``)}function zv(e,t,n){let r=S_(e.schema,t),i=e.settings.allowParseErrors&&e.schema.space===`html`?0:1,a=+!e.settings.allowDangerousCharacters,o=e.quote,s;if(r.overloadedBoolean&&(n===r.attribute||n===``)?n=!0:(r.boolean||r.overloadedBoolean)&&(typeof n!=`string`||n===r.attribute||n===``)&&(n=!!n),n==null||n===!1||typeof n==`number`&&Number.isNaN(n))return``;let c=X_(r.attribute,Object.assign({},e.settings.characterReferences,{subset:Iv.name[i][a]}));return n===!0||(n=Array.isArray(n)?(r.commaSeparated?rv:iv)(n,{padLeft:!e.settings.tightCommaSeparatedLists}):String(n),e.settings.collapseEmptyAttributes&&!n)?c:(e.settings.preferUnquoted&&(s=X_(n,Object.assign({},e.settings.characterReferences,{attribute:!0,subset:Iv.unquoted[i][a]}))),s!==n&&(e.settings.quoteSmart&&nv(n,o)>nv(n,e.alternative)&&(o=e.alternative),s=o+X_(n,Object.assign({},e.settings.characterReferences,{subset:(o===`'`?Iv.single:Iv.double)[i][a],attribute:!0}))+o),c+(s&&`=`+s))}var Bv=[`<`,`&`];function Vv(e,t,n,r){return n&&n.type===`element`&&(n.tagName===`script`||n.tagName===`style`)?e.value:X_(e.value,Object.assign({},r.settings.characterReferences,{subset:Bv}))}function Hv(e,t,n,r){return r.settings.allowDangerousHtml?e.value:Vv(e,t,n,r)}function Uv(e,t,n,r){return r.all(e)}var Wv=O_(`type`,{invalid:Gv,unknown:Kv,handlers:{comment:ev,doctype:tv,element:Lv,raw:Hv,root:Uv,text:Vv}});function Gv(e){throw Error("Expected node, not `"+e+"`")}function Kv(e){throw Error("Cannot compile unknown node `"+e.type+"`")}var qv={},Jv={},Yv=[];function Xv(e,t){let n=t||qv,r=n.quote||`"`,i=r===`"`?`'`:`"`;if(r!==`"`&&r!==`'`)throw Error("Invalid quote `"+r+"`, expected `'` or `\"`");return{one:Zv,all:Qv,settings:{omitOptionalTags:n.omitOptionalTags||!1,allowParseErrors:n.allowParseErrors||!1,allowDangerousCharacters:n.allowDangerousCharacters||!1,quoteSmart:n.quoteSmart||!1,preferUnquoted:n.preferUnquoted||!1,tightAttributes:n.tightAttributes||!1,upperDoctype:n.upperDoctype||!1,tightDoctype:n.tightDoctype||!1,bogusComments:n.bogusComments||!1,tightCommaSeparatedLists:n.tightCommaSeparatedLists||!1,tightSelfClosing:n.tightSelfClosing||!1,collapseEmptyAttributes:n.collapseEmptyAttributes||!1,allowDangerousHtml:n.allowDangerousHtml||!1,voids:n.voids||Kg,characterReferences:n.characterReferences||Jv,closeSelfClosing:n.closeSelfClosing||!1,closeEmptyElements:n.closeEmptyElements||!1},schema:n.space===`svg`?E_:T_,quote:r,alternative:i}.one(Array.isArray(e)?{type:`root`,children:e}:e,void 0,void 0)}function Zv(e,t,n){return Wv(e,t,n,this)}function Qv(e){let t=[],n=e&&e.children||Yv,r=-1;for(;++r<n.length;)t[r]=this.one(n[r],r,e);return t.join(``)}var $v=/\s+/g;function ey(e,t){if(!t)return e;e.properties||={},e.properties.class||=[],typeof e.properties.class==`string`&&(e.properties.class=e.properties.class.split($v)),Array.isArray(e.properties.class)||(e.properties.class=[]);let n=Array.isArray(t)?t:t.split($v);for(let t of n)t&&!e.properties.class.includes(t)&&e.properties.class.push(t);return e}function ty(e){let t=mg(e,!0).map(([e])=>e);function n(n){if(n===e.length)return{line:t.length-1,character:t.at(-1).length};let r=n,i=0;for(let e of t){if(r<e.length)break;r-=e.length,i++}return{line:i,character:r}}function r(e,n){let r=0;for(let n=0;n<e;n++)r+=t[n].length;return r+=n,r}return{lines:t,indexToPos:n,posToIndex:r}}var ny=[`color`,`background-color`];function ry(e,t){let n=0,r=[];for(let i of t)i>n&&r.push({...e,content:e.content.slice(n,i),offset:e.offset+n}),n=i;return n<e.content.length&&r.push({...e,content:e.content.slice(n),offset:e.offset+n}),r}function iy(e,t){let n=0,r=e.length;for(;n<r;){let i=n+(r-n>>1);e[i]<=t?n=i+1:r=i}return n}function ay(e,t){let n=[...t instanceof Set?t:new Set(t)].sort((e,t)=>e-t);return n.length?e.map(e=>e.flatMap(e=>{let t=e.offset+e.content.length,r=iy(n,e.offset),i=r;for(;i<n.length&&n[i]<t;)i++;if(r===i)return e;let a=n.slice(rLine truncated
`}));let n={type:`element`,tagName:`span`,properties:{class:`line`},children:[]},r=0;for(let a of e){let e={type:`element`,tagName:`span`,properties:{...a.htmlAttrs},children:[{type:`text`,value:a.content}]},c=cy(a.htmlStyle||sy(a));c&&(e.properties.style=c);for(let o of i)e=o?.span?.call(p,e,t+1,r,n,a)||e;s===`inline`?o.children.push(e):s===`classic`&&n.children.push(e),r+=a.content.length}if(s===`classic`){for(let e of i)n=e?.line?.call(p,n,t+1)||n;f.push(n),a.push(n)}else s===`inline`&&f.push(n)}),s===`classic`){for(let e of i)d=e?.code?.call(p,d)||d;u.children.push(d);for(let e of i)u=e?.pre?.call(p,u)||u;o.children.push(u)}else if(s===`inline`){let e=[],t={type:`element`,tagName:`span`,properties:{class:`line`},children:[]};for(let n of o.children)n.type===`element`&&n.tagName===`br`?(e.push(t),t={type:`element`,tagName:`span`,properties:{class:`line`},children:[]}):(n.type===`element`||n.type===`text`)&&t.children.push(n);e.push(t);let n={type:`element`,tagName:`code`,properties:{},children:e};for(let e of i)n=e?.code?.call(p,n)||n;o.children=[];for(let e=0;e<n.children.length;e++){e>0&&o.children.push({type:`element`,tagName:`br`,properties:{},children:[]});let t=n.children[e];t.type===`element`&&o.children.push(...t.children)}}let m=o;for(let e of i)m=e?.root?.call(p,m)||m;return r&&Og(m,r),m}function Fy(e){return e.map(e=>{let t=[],n=``,r;return e.forEach((i,a)=>{let o=!(i.fontStyle&&(i.fontStyle&Wm.Underline||i.fontStyle&Wm.Strikethrough));o&&jy.test(i.content)&&e[a+1]?(r===void 0&&(r=i.offset),n+=i.content):n?(o?t.push({...i,offset:r,content:n+i.content}):t.push({content:n,offset:r},i),r=void 0,n=``):t.push(i)}),t})}function Iy(e){return e.map(e=>e.flatMap(e=>{if(jy.test(e.content))return e;let t=e.content.match(My);if(!t)return e;let[,n,r,i]=t;if(!n&&!i)return e;let a=[{...e,offset:e.offset+n.length,content:r}];return n&&a.unshift({content:n,offset:e.offset}),i&&a.push({content:i,offset:e.offset+n.length+r.length}),a}))}function Ly(e){return e.map(e=>{let t=[];for(let n of e){if(t.length===0){t.push({...n});continue}let e=t.at(-1),r=cy(e.htmlStyle||sy(e)),i=cy(n.htmlStyle||sy(n)),a=e.fontStyle&&(e.fontStyle&Wm.Underline||e.fontStyle&Wm.Strikethrough),o=n.fontStyle&&(n.fontStyle&Wm.Underline||n.fontStyle&Wm.Strikethrough);!a&&!o&&r===i?e.content+=n.content:t.push({...n})}return t})}var Ry=Xv;function zy(e,t,n){let r={meta:{},options:n,codeToHast:(t,n)=>Ny(e,t,n),codeToTokens:(t,n)=>ky(e,t,n)},i=Ry(Ny(e,t,n,r));for(let e of py(n))i=e.postprocess?.call(r,i,n)||i;return i}async function By(e){let t=await Eg(e);return{getLastGrammarState:(...e)=>Ig(t,...e),codeToTokensBase:(e,n)=>Oy(t,e,n),codeToTokensWithThemes:(e,n)=>Wg(t,e,n),codeToTokens:(e,n)=>ky(t,e,n),codeToHast:(e,n)=>Ny(t,e,n),codeToHtml:(e,n)=>zy(t,e,n),getBundledLanguages:()=>({}),getBundledThemes:()=>({}),...t,getInternalContext:()=>t}}var Vy=4294967295;function Hy(e){return!e.sticky&&!e.rawOptions?.strategy}function Uy(e,t){return{index:e,captureIndices:t.map(e=>e==null?{start:Vy,end:Vy,length:0}:{start:e[0],end:e[1],length:e[1]-e[0]})}}var Wy=class{patterns;options;regexps;lastSearches;constructor(e,t={}){this.patterns=e,this.options=t;let{forgiving:n=!1,cache:r,regexConstructor:i}=t;if(!i)throw Error("Option `regexConstructor` is not provided");this.regexps=e.map(e=>{if(typeof e!=`string`)return e;let t=r?.get(e);if(t){if(t instanceof RegExp)return t;if(n)return null;throw t}try{let t=i(e);return r?.set(e,t),t}catch(t){if(r?.set(e,t),n)return null;throw t}}),this.lastSearches=this.regexps.map(e=>e&&Hy(e)?{strId:0,searchedFrom:0,matchIndex:-1,indices:null}:null)}findNextMatchSync(e,t,n){let r=typeof e==`string`?e:e.content,i=typeof e==`string`?0:e.id||0,a=-1,o=0,s=null;for(let e=0;e<this.regexps.length;e++){let n=this.regexps[e];if(n)try{let c=i?this.lastSearches[e]:null,l,u;if(c&&c.strId===i&&c.searchedFrom<=t&&(c.matchIndex===-1||c.matchIndex>=t))l=c.matchIndex,u=c.indices;else{n.lastIndex=t;let e=n.exec(r);l=e?e.index:-1,u=e?e.indices:null,c&&(c.strId=i,c.searchedFrom=t,c.matchIndex=l,c.indices=u)}if(l===-1)continue;if(l===t)return Uy(e,u);(a===-1||l<o)&&(a=e,o=l,s=u)}catch(e){if(this.options.forgiving)continue;throw e}}return a===-1?null:Uy(a,s)}},Gy=0;function Ky(e){return{content:e,id:++Gy}}function qy(e){if([...e].length!==1)throw Error(`Expected "${e}" to be a single code point`);return e.codePointAt(0)}function Jy(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}var Yy=new Set([`alnum`,`alpha`,`ascii`,`blank`,`cntrl`,`digit`,`graph`,`lower`,`print`,`punct`,`space`,`upper`,`word`,`xdigit`]),Xy=String.raw;function Zy(e,t){if(e==null)throw Error(t??`Value expected`);return e}var Qy=Xy`\[\^?`,$y=`c.? | C(?:-.?)?|${Xy`[pP]\{(?:\^?[-\x20_]*[A-Za-z][-\x20\w]*\})?`}|${Xy`x[89A-Fa-f]\p{AHex}(?:\\x[89A-Fa-f]\p{AHex})*`}|${Xy`u(?:\p{AHex}{4})? | x\{[^\}]*\}? | x\p{AHex}{0,2}`}|${Xy`o\{[^\}]*\}?`}|${Xy`\d{1,3}`}`,eb=/[?*+][?+]?|\{(?:\d+(?:,\d*)?|,\d+)\}\??/,tb=new RegExp(Xy`
\\ (?:
${tb}
${$y}
| [gk]<[^>]*>?
| [gk]'[^']*'?
| .
@@ -34,20 +34,20 @@ import{A as e,B as t,C as n,D as r,E as i,F as a,H as o,I as s,L as c,M as l,N a
)?
| \*[^\)]*\)?
)?
| (?:${nb.source})+
| ${eb}
| (?:${eb.source})+
| ${Qy}
| .
`.replace(/\s+/g,``),`gsu`),ib=new RegExp(Qy`
`.replace(/\s+/g,``),`gsu`),nb=new RegExp(Xy`
\\ (?:
${tb}
${$y}
| .
)
| \[:(?:\^?\p{Alpha}+|\^):\]
| ${eb}
| ${Qy}
| &&
| .
`.replace(/\s+/g,``),`gsu`);function ab(e,t={}){let n={flags:``,...t,rules:{captureGroup:!1,singleline:!1,...t.rules}};if(typeof e!=`string`)throw Error(`String expected as pattern`);let r=Fb(n.flags),i=[r.extended],a={captureGroup:n.rules.captureGroup,getCurrentModX(){return i.at(-1)},numOpenGroups:0,popModX(){i.pop()},pushModX(e){i.push(e)},replaceCurrentModX(e){i[i.length-1]=e},singleline:n.rules.singleline},o=[],s;for(rb.lastIndex=0;s=rb.exec(e);){let t=ob(a,e,s[0],rb.lastIndex);t.tokens?o.push(...t.tokens):t.token&&o.push(t.token),t.lastIndex!==void 0&&(rb.lastIndex=t.lastIndex)}let c=[],l=0;o.filter(e=>e.type===`GroupOpen`).forEach(e=>{e.kind===`capturing`?e.number=++l:e.raw===`(`&&c.push(e)}),l||c.forEach((e,t)=>{e.kind=`capturing`,e.number=t+1});let u=l||c.length;return{tokens:o.map(e=>e.type===`EscapedNumber`?Lb(e,u):e).flat(),flags:r}}function ob(e,t,n,r){let[i,a]=n;if(n===`[`||n===`[^`){let e=sb(t,n,r);return{tokens:e.tokens,lastIndex:e.lastIndex}}if(i===`\\`){if(`AbBGyYzZ`.includes(a))return{token:db(n,n)};if(/^\\g[<']/.test(n)){if(!/^\\g(?:<[^>]+>|'[^']+')$/.test(n))throw Error(`Invalid group name "${n}"`);return{token:Tb(n)}}if(/^\\k[<']/.test(n)){if(!/^\\k(?:<[^>]+>|'[^']+')$/.test(n))throw Error(`Invalid group name "${n}"`);return{token:fb(n)}}if(a===`K`)return{token:yb(`keep`,n)};if(a===`N`||a===`R`)return{token:vb(`newline`,n,{negate:a===`N`})};if(a===`O`)return{token:vb(`any`,n)};if(a===`X`)return{token:vb(`text_segment`,n)};let e=lb(n,{inCharClass:!1});return Array.isArray(e)?{tokens:e}:{token:e}}if(i===`(`){if(a===`*`)return{token:Ab(n)};if(n===`(?{`)throw Error(`Unsupported callout "${n}"`);if(n.startsWith(`(?#`)){if(t[r]!==`)`)throw Error(`Unclosed comment group "(?#"`);return{lastIndex:r+1}}if(/^\(\?[-imx]+[:)]$/.test(n))return{token:kb(n,e)};if(e.pushModX(e.getCurrentModX()),e.numOpenGroups++,n===`(`&&!e.captureGroup||n===`(?:`)return{token:Sb(`group`,n)};if(n===`(?>`)return{token:Sb(`atomic`,n)};if(n===`(?=`||n===`(?!`||n===`(?<=`||n===`(?<!`)return{token:Sb(n[2]===`<`?`lookbehind`:`lookahead`,n,{negate:n.endsWith(`!`)})};if(n===`(`&&e.captureGroup||n.startsWith(`(?<`)&&n.endsWith(`>`)||n.startsWith(`(?'`)&&n.endsWith(`'`))return{token:Sb(`capturing`,n,{...n!==`(`&&{name:n.slice(3,-1)}})};if(n.startsWith(`(?~`)){if(n===`(?~|`)throw Error(`Unsupported absence function kind "${n}"`);return{token:Sb(`absence_repeater`,n)}}throw Error(n===`(?(`?`Unsupported conditional "${n}"`:`Invalid or unsupported group option "${n}"`)}if(n===`)`){if(e.popModX(),e.numOpenGroups--,e.numOpenGroups<0)throw Error(`Unmatched ")"`);return{token:xb(n)}}if(e.getCurrentModX()){if(n===`#`){let e=t.indexOf(`
`,r);return{lastIndex:e===-1?t.length:e}}if(/^\s$/.test(n)){let e=/\s+/y;return e.lastIndex=r,{lastIndex:e.exec(t)?e.lastIndex:r}}}return n===`.`?{token:vb(`dot`,n)}:n===`^`||n===`$`?{token:db(e.singleline?{"^":Qy`\A`,$:Qy`\Z`}[n]:n,n)}:n===`|`?{token:ub(n)}:nb.test(n)?{tokens:Rb(n)}:{token:pb(Yy(n),n)}}function sb(e,t,n){let r=[_b(t[1]===`^`,t)],i=1,a;for(ib.lastIndex=n;a=ib.exec(e);){let e=a[0];if(e[0]===`[`&&e[1]!==`:`)i++,r.push(_b(e[1]===`^`,e));else if(e===`]`){if(r.at(-1).type===`CharacterClassOpen`)r.push(pb(93,e));else if(i--,r.push(mb(e)),!i)break}else{let t=cb(e);Array.isArray(t)?r.push(...t):r.push(t)}}return{tokens:r,lastIndex:ib.lastIndex||e.length}}function cb(e){if(e[0]===`\\`)return lb(e,{inCharClass:!0});if(e[0]===`[`){let t=/\[:(?<negate>\^?)(?<name>[a-z]+):\]/.exec(e);if(!t||!Zy.has(t.groups.name))throw Error(`Invalid POSIX class "${e}"`);return vb(`posix`,e,{value:t.groups.name,negate:!!t.groups.negate})}return e===`-`?hb(e):e===`&&`?gb(e):pb(Yy(e),e)}function lb(e,{inCharClass:t}){let n=e[1];if(n===`c`||n===`C`)return Ob(e);if(`dDhHsSwW`.includes(n))return Mb(e);if(e.startsWith(Qy`\o{`))throw Error(`Incomplete, invalid, or unsupported octal code point "${e}"`);if(/^\\[pP]\{/.test(e)){if(e.length===3)throw Error(`Incomplete or invalid Unicode property "${e}"`);return Nb(e)}if(/^\\x[89A-Fa-f]\p{AHex}/u.test(e))try{let t=e.split(/\\x/).slice(1).map(e=>parseInt(e,16)),n=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0}).decode(new Uint8Array(t)),r=new TextEncoder;return[...n].map(e=>{let t=[...r.encode(e)].map(e=>`\\x${e.toString(16)}`).join(``);return pb(Yy(e),t)})}catch{throw Error(`Multibyte code "${e}" incomplete or invalid in Oniguruma`)}if(n===`u`||n===`x`)return pb(Ib(e),e);if(Db.has(n))return pb(Db.get(n),e);if(/\d/.test(n))return bb(t,e);if(e===`\\`)throw Error(Qy`Incomplete escape "\"`);if(n===`M`)throw Error(`Unsupported meta "${e}"`);if([...e].length===2)return pb(e.codePointAt(1),e);throw Error(`Unexpected escape "${e}"`)}function ub(e){return{type:`Alternator`,raw:e}}function db(e,t){return{type:`Assertion`,kind:e,raw:t}}function fb(e){return{type:`Backreference`,raw:e}}function pb(e,t){return{type:`Character`,value:e,raw:t}}function mb(e){return{type:`CharacterClassClose`,raw:e}}function hb(e){return{type:`CharacterClassHyphen`,raw:e}}function gb(e){return{type:`CharacterClassIntersector`,raw:e}}function _b(e,t){return{type:`CharacterClassOpen`,negate:e,raw:t}}function vb(e,t,n={}){return{type:`CharacterSet`,kind:e,...n,raw:t}}function yb(e,t,n={}){return e===`keep`?{type:`Directive`,kind:e,raw:t}:{type:`Directive`,kind:e,flags:$y(n.flags),raw:t}}function bb(e,t){return{type:`EscapedNumber`,inCharClass:e,raw:t}}function xb(e){return{type:`GroupClose`,raw:e}}function Sb(e,t,n={}){return{type:`GroupOpen`,kind:e,...n,raw:t}}function Cb(e,t,n,r){return{type:`NamedCallout`,kind:e,tag:t,arguments:n,raw:r}}function wb(e,t,n,r){return{type:`Quantifier`,kind:e,min:t,max:n,raw:r}}function Tb(e){return{type:`Subroutine`,raw:e}}var Eb=new Set([`COUNT`,`CMP`,`ERROR`,`FAIL`,`MAX`,`MISMATCH`,`SKIP`,`TOTAL_COUNT`]),Db=new Map([[`a`,7],[`b`,8],[`e`,27],[`f`,12],[`n`,10],[`r`,13],[`t`,9],[`v`,11]]);function Ob(e){let t=e[1]===`c`?e[2]:e[3];if(!t||!/[A-Za-z]/.test(t))throw Error(`Unsupported control character "${e}"`);return pb(Yy(t.toUpperCase())-64,e)}function kb(e,t){let{on:n,off:r}=/^\(\?(?<on>[imx]*)(?:-(?<off>[-imx]*))?/.exec(e).groups;r??=``;let i=(t.getCurrentModX()||n.includes(`x`))&&!r.includes(`x`),a=Pb(n),o=Pb(r),s={};if(a&&(s.enable=a),o&&(s.disable=o),e.endsWith(`)`))return t.replaceCurrentModX(i),yb(`flags`,e,{flags:s});if(e.endsWith(`:`))return t.pushModX(i),t.numOpenGroups++,Sb(`group`,e,{...(a||o)&&{flags:s}});throw Error(`Unexpected flag modifier "${e}"`)}function Ab(e){let t=/\(\*(?<name>[A-Za-z_]\w*)?(?:\[(?<tag>(?:[A-Za-z_]\w*)?)\])?(?:\{(?<args>[^}]*)\})?\)/.exec(e);if(!t)throw Error(`Incomplete or invalid named callout "${e}"`);let{name:n,tag:r,args:i}=t.groups;if(!n)throw Error(`Invalid named callout "${e}"`);if(r===``)throw Error(`Named callout tag with empty value not allowed "${e}"`);let a=i?i.split(`,`).filter(e=>e!==``).map(e=>/^[+-]?\d+$/.test(e)?+e:e):[],[o,s,c]=a,l=Eb.has(n)?n.toLowerCase():`custom`;switch(l){case`fail`:case`mismatch`:case`skip`:if(a.length>0)throw Error(`Named callout arguments not allowed "${a}"`);break;case`error`:if(a.length>1)throw Error(`Named callout allows only one argument "${a}"`);if(typeof o==`string`)throw Error(`Named callout argument must be a number "${o}"`);break;case`max`:if(!a.length||a.length>2)throw Error(`Named callout must have one or two arguments "${a}"`);if(typeof o==`string`&&!/^[A-Za-z_]\w*$/.test(o))throw Error(`Named callout argument one must be a tag or number "${o}"`);if(a.length===2&&(typeof s==`number`||!/^[<>X]$/.test(s)))throw Error(`Named callout optional argument two must be '<', '>', or 'X' "${s}"`);break;case`count`:case`total_count`:if(a.length>1)throw Error(`Named callout allows only one argument "${a}"`) Line truncated
`.replace(/\s+/g,``),`gsu`);function rb(e,t={}){let n={flags:``,...t,rules:{captureGroup:!1,singleline:!1,...t.rules}};if(typeof e!=`string`)throw Error(`String expected as pattern`);let r=Nb(n.flags),i=[r.extended],a={captureGroup:n.rules.captureGroup,getCurrentModX(){return i.at(-1)},numOpenGroups:0,popModX(){i.pop()},pushModX(e){i.push(e)},replaceCurrentModX(e){i[i.length-1]=e},singleline:n.rules.singleline},o=[],s;for(tb.lastIndex=0;s=tb.exec(e);){let t=ib(a,e,s[0],tb.lastIndex);t.tokens?o.push(...t.tokens):t.token&&o.push(t.token),t.lastIndex!==void 0&&(tb.lastIndex=t.lastIndex)}let c=[],l=0;o.filter(e=>e.type===`GroupOpen`).forEach(e=>{e.kind===`capturing`?e.number=++l:e.raw===`(`&&c.push(e)}),l||c.forEach((e,t)=>{e.kind=`capturing`,e.number=t+1});let u=l||c.length;return{tokens:o.map(e=>e.type===`EscapedNumber`?Fb(e,u):e).flat(),flags:r}}function ib(e,t,n,r){let[i,a]=n;if(n===`[`||n===`[^`){let e=ab(t,n,r);return{tokens:e.tokens,lastIndex:e.lastIndex}}if(i===`\\`){if(`AbBGyYzZ`.includes(a))return{token:lb(n,n)};if(/^\\g[<']/.test(n)){if(!/^\\g(?:<[^>]+>|'[^']+')$/.test(n))throw Error(`Invalid group name "${n}"`);return{token:Cb(n)}}if(/^\\k[<']/.test(n)){if(!/^\\k(?:<[^>]+>|'[^']+')$/.test(n))throw Error(`Invalid group name "${n}"`);return{token:ub(n)}}if(a===`K`)return{token:_b(`keep`,n)};if(a===`N`||a===`R`)return{token:gb(`newline`,n,{negate:a===`N`})};if(a===`O`)return{token:gb(`any`,n)};if(a===`X`)return{token:gb(`text_segment`,n)};let e=sb(n,{inCharClass:!1});return Array.isArray(e)?{tokens:e}:{token:e}}if(i===`(`){if(a===`*`)return{token:Ob(n)};if(n===`(?{`)throw Error(`Unsupported callout "${n}"`);if(n.startsWith(`(?#`)){if(t[r]!==`)`)throw Error(`Unclosed comment group "(?#"`);return{lastIndex:r+1}}if(/^\(\?[-imx]+[:)]$/.test(n))return{token:Db(n,e)};if(e.pushModX(e.getCurrentModX()),e.numOpenGroups++,n===`(`&&!e.captureGroup||n===`(?:`)return{token:bb(`group`,n)};if(n===`(?>`)return{token:bb(`atomic`,n)};if(n===`(?=`||n===`(?!`||n===`(?<=`||n===`(?<!`)return{token:bb(n[2]===`<`?`lookbehind`:`lookahead`,n,{negate:n.endsWith(`!`)})};if(n===`(`&&e.captureGroup||n.startsWith(`(?<`)&&n.endsWith(`>`)||n.startsWith(`(?'`)&&n.endsWith(`'`))return{token:bb(`capturing`,n,{...n!==`(`&&{name:n.slice(3,-1)}})};if(n.startsWith(`(?~`)){if(n===`(?~|`)throw Error(`Unsupported absence function kind "${n}"`);return{token:bb(`absence_repeater`,n)}}throw Error(n===`(?(`?`Unsupported conditional "${n}"`:`Invalid or unsupported group option "${n}"`)}if(n===`)`){if(e.popModX(),e.numOpenGroups--,e.numOpenGroups<0)throw Error(`Unmatched ")"`);return{token:yb(n)}}if(e.getCurrentModX()){if(n===`#`){let e=t.indexOf(`
`,r);return{lastIndex:e===-1?t.length:e}}if(/^\s$/.test(n)){let e=/\s+/y;return e.lastIndex=r,{lastIndex:e.exec(t)?e.lastIndex:r}}}return n===`.`?{token:gb(`dot`,n)}:n===`^`||n===`$`?{token:lb(e.singleline?{"^":Xy`\A`,$:Xy`\Z`}[n]:n,n)}:n===`|`?{token:cb(n)}:eb.test(n)?{tokens:Ib(n)}:{token:db(qy(n),n)}}function ab(e,t,n){let r=[hb(t[1]===`^`,t)],i=1,a;for(nb.lastIndex=n;a=nb.exec(e);){let e=a[0];if(e[0]===`[`&&e[1]!==`:`)i++,r.push(hb(e[1]===`^`,e));else if(e===`]`){if(r.at(-1).type===`CharacterClassOpen`)r.push(db(93,e));else if(i--,r.push(fb(e)),!i)break}else{let t=ob(e);Array.isArray(t)?r.push(...t):r.push(t)}}return{tokens:r,lastIndex:nb.lastIndex||e.length}}function ob(e){if(e[0]===`\\`)return sb(e,{inCharClass:!0});if(e[0]===`[`){let t=/\[:(?<negate>\^?)(?<name>[a-z]+):\]/.exec(e);if(!t||!Yy.has(t.groups.name))throw Error(`Invalid POSIX class "${e}"`);return gb(`posix`,e,{value:t.groups.name,negate:!!t.groups.negate})}return e===`-`?pb(e):e===`&&`?mb(e):db(qy(e),e)}function sb(e,{inCharClass:t}){let n=e[1];if(n===`c`||n===`C`)return Eb(e);if(`dDhHsSwW`.includes(n))return Ab(e);if(e.startsWith(Xy`\o{`))throw Error(`Incomplete, invalid, or unsupported octal code point "${e}"`);if(/^\\[pP]\{/.test(e)){if(e.length===3)throw Error(`Incomplete or invalid Unicode property "${e}"`);return jb(e)}if(/^\\x[89A-Fa-f]\p{AHex}/u.test(e))try{let t=e.split(/\\x/).slice(1).map(e=>parseInt(e,16)),n=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0}).decode(new Uint8Array(t)),r=new TextEncoder;return[...n].map(e=>{let t=[...r.encode(e)].map(e=>`\\x${e.toString(16)}`).join(``);return db(qy(e),t)})}catch{throw Error(`Multibyte code "${e}" incomplete or invalid in Oniguruma`)}if(n===`u`||n===`x`)return db(Pb(e),e);if(Tb.has(n))return db(Tb.get(n),e);if(/\d/.test(n))return vb(t,e);if(e===`\\`)throw Error(Xy`Incomplete escape "\"`);if(n===`M`)throw Error(`Unsupported meta "${e}"`);if([...e].length===2)return db(e.codePointAt(1),e);throw Error(`Unexpected escape "${e}"`)}function cb(e){return{type:`Alternator`,raw:e}}function lb(e,t){return{type:`Assertion`,kind:e,raw:t}}function ub(e){return{type:`Backreference`,raw:e}}function db(e,t){return{type:`Character`,value:e,raw:t}}function fb(e){return{type:`CharacterClassClose`,raw:e}}function pb(e){return{type:`CharacterClassHyphen`,raw:e}}function mb(e){return{type:`CharacterClassIntersector`,raw:e}}function hb(e,t){return{type:`CharacterClassOpen`,negate:e,raw:t}}function gb(e,t,n={}){return{type:`CharacterSet`,kind:e,...n,raw:t}}function _b(e,t,n={}){return e===`keep`?{type:`Directive`,kind:e,raw:t}:{type:`Directive`,kind:e,flags:Zy(n.flags),raw:t}}function vb(e,t){return{type:`EscapedNumber`,inCharClass:e,raw:t}}function yb(e){return{type:`GroupClose`,raw:e}}function bb(e,t,n={}){return{type:`GroupOpen`,kind:e,...n,raw:t}}function xb(e,t,n,r){return{type:`NamedCallout`,kind:e,tag:t,arguments:n,raw:r}}function Sb(e,t,n,r){return{type:`Quantifier`,kind:e,min:t,max:n,raw:r}}function Cb(e){return{type:`Subroutine`,raw:e}}var wb=new Set([`COUNT`,`CMP`,`ERROR`,`FAIL`,`MAX`,`MISMATCH`,`SKIP`,`TOTAL_COUNT`]),Tb=new Map([[`a`,7],[`b`,8],[`e`,27],[`f`,12],[`n`,10],[`r`,13],[`t`,9],[`v`,11]]);function Eb(e){let t=e[1]===`c`?e[2]:e[3];if(!t||!/[A-Za-z]/.test(t))throw Error(`Unsupported control character "${e}"`);return db(qy(t.toUpperCase())-64,e)}function Db(e,t){let{on:n,off:r}=/^\(\?(?<on>[imx]*)(?:-(?<off>[-imx]*))?/.exec(e).groups;r??=``;let i=(t.getCurrentModX()||n.includes(`x`))&&!r.includes(`x`),a=Mb(n),o=Mb(r),s={};if(a&&(s.enable=a),o&&(s.disable=o),e.endsWith(`)`))return t.replaceCurrentModX(i),_b(`flags`,e,{flags:s});if(e.endsWith(`:`))return t.pushModX(i),t.numOpenGroups++,bb(`group`,e,{...(a||o)&&{flags:s}});throw Error(`Unexpected flag modifier "${e}"`)}function Ob(e){let t=/\(\*(?<name>[A-Za-z_]\w*)?(?:\[(?<tag>(?:[A-Za-z_]\w*)?)\])?(?:\{(?<args>[^}]*)\})?\)/.exec(e);if(!t)throw Error(`Incomplete or invalid named callout "${e}"`);let{name:n,tag:r,args:i}=t.groups;if(!n)throw Error(`Invalid named callout "${e}"`);if(r===``)throw Error(`Named callout tag with empty value not allowed "${e}"`);let a=i?i.split(`,`).filter(e=>e!==``).map(e=>/^[+-]?\d+$/.test(e)?+e:e):[],[o,s,c]=a,l=wb.has(n)?n.toLowerCase():`custom`;switch(l){case`fail`:case`mismatch`:case`skip`:if(a.length>0)throw Error(`Named callout arguments not allowed "${a}"`);break;case`error`:if(a.length>1)throw Error(`Named callout allows only one argument "${a}"`);if(typeof o==`string`)throw Error(`Named callout argument must be a number "${o}"`);break;case`max`:if(!a.length||a.length>2)throw Error(`Named callout must have one or two arguments "${a}"`);if(typeof o==`string`&&!/^[A-Za-z_]\w*$/.test(o))throw Error(`Named callout argument one must be a tag or number "${o}"`);if(a.length===2&&(typeof s==`number`||!/^[<>X]$/.test(s)))throw Error(`Named callout optional argument two must be '<', '>', or 'X' "${s}"`);break;case`count`:case`total_count`:if(a.length>1)throw Error(`Named callout allows only one argument "${a}"`) Line truncated
\\(?: \d+
| c[A-Za-z]
| [gk]<[^>]+>
@@ -60,9 +60,9 @@ import{A as e,B as t,C as n,D as r,E as i,F as a,H as o,I as s,L as c,M as l,N a
| [A-Za-z\-]+:
| \(DEFINE\)
))?
| (?<qBase>${zx})(?<qMod>[?+]?)(?<invalidQ>[?*+\{]?)
| (?<qBase>${Rx})(?<qMod>[?+]?)(?<invalidQ>[?*+\{]?)
| \\?.
`.replace(/\s+/g,``),`gsu`);function Vx(e){if(!RegExp(`${zx}\\+`).test(e))return{pattern:e};let t=[],n=null,r=null,i=``,a=0,o;for(Bx.lastIndex=0;o=Bx.exec(e);){let{0:s,index:c,groups:{qBase:l,qMod:u,invalidQ:d}}=o;if(s===`[`)a||(r=c),a++;else if(s===`]`)a?a--:r=null;else if(!a){if(u===`+`&&i&&!i.startsWith(`(`)){if(d)throw Error(`Invalid quantifier "${s}"`);let t=-1;if(/^\{\d+\}$/.test(l))e=Ax(e,c+l.length,u,``);else{if(i===`)`||i===`]`){let t=i===`)`?n:r;if(t===null)throw Error(`Invalid unmatched "${i}"`);e=`${e.slice(0,t)}(?>${e.slice(t,c)}${l})${e.slice(c+s.length)}`}else e=`${e.slice(0,c-i.length)}(?>${i}${l})${e.slice(c+s.length)}`;t+=4}Bx.lastIndex+=t}else s[0]===`(`?t.push(c):s===`)`&&(n=t.length?t.pop():null)}i=s}return{pattern:e}}var Hx=String.raw,Ux=Hx`\(\?R=(?<rDepth>[^\)]+)\)|${Hx`\\g<(?<gRNameOrNum>[^>&]+)&R=(?<gRDepth>[^>]+)>`}`,Wx=Hx`\(\?<(?![=!])(?<captureName>[^>]+)>`,Gx=Hx`${Wx}|(?<unnamed>\()(?!\?)`,Kx=new RegExp(Hx`${Wx}|${Ux}|\(\?|\\?.`,`gsu`),qx=`Cannot use multiple overlapping recursions`;function Jx(e,t){let{hiddenCaptures:n,mode:r}={hiddenCaptures:[],mode:`plugin`,...t},i=t?.captureTransfers??new Map;if(!new RegExp(Ux,`su`).test(e))return{pattern:e,captureTransfers:i,hiddenCaptures:n};if(r===`plugin`&&Fx(e,Hx`\(\?\(DEFINE\)`,jx.DEFAULT))throw Error(`DEFINE groups cannot be used with recursion`);let a=[],o=Fx(e,Hx`\\[1-9]`,jx.DEFAULT),s=new Map,c=[],l=!1,u=0,d=0,f;for(Kx.lastIndex=0;f=Kx.exec(e);){let{0:t,groups:{captureName:p,rDepth:m,gRNameOrNum:h,gRDepth:g}}=f;if(t===`[`)u++;else if(u)t===`]`&&u--;else{if(m){if(Yx(m),l)throw Error(qx);if(o)throw Error(`${r===`external`?`Backrefs`:`Numbered backrefs`} cannot be used with global recursion`);let t=e.slice(0,f.index),s=e.slice(Kx.lastIndex);if(Fx(s,Ux,jx.DEFAULT))throw Error(qx);let c=m-1;e=Xx(t,s,c,!1,n,a,d),i=$x(i,t,c,a.length,0,d);break}if(h){Yx(g);let u=!1;for(let e of c)if(e.name===h||e.num===+h){if(u=!0,e.hasRecursedWithin)throw Error(qx);break}if(!u)throw Error(Hx`Recursive \g cannot be used outside the referenced group "${r===`external`?h:Hx`\g<${h}&R=${g}>`}"`);let p=s.get(h),m=Ix(e,p);if(o&&Fx(m,Hx`${Wx}|\((?!\?)`,jx.DEFAULT))throw Error(`${r===`external`?`Backrefs`:`Numbered backrefs`} cannot be used with recursion of capturing groups`);let _=e.slice(p,f.index),v=m.slice(_.length+t.length),y=a.length,b=g-1,x=Xx(_,v,b,!0,n,a,d);i=$x(i,_,b,a.length-y,y,d),e=`${e.slice(0,p)}${x}${e.slice(p+m.length)}`,Kx.lastIndex+=x.length-t.length-_.length-v.length,c.forEach(e=>e.hasRecursedWithin=!0),l=!0}else if(p)d++,s.set(String(d),Kx.lastIndex),s.set(p,Kx.lastIndex),c.push({num:d,name:p});else if(t[0]===`(`){let e=t===`(`;e&&(d++,s.set(String(d),Kx.lastIndex)),c.push(e?{num:d}:{})}else t===`)`&&c.pop()}}return n.push(...a),{pattern:e,captureTransfers:i,hiddenCaptures:n}}function Yx(e){let t=`Max depth must be integer between 2 and 100; used ${e}`;if(!/^[1-9]\d*$/.test(e)||(e=+e,e<2||e>100))throw Error(t)}function Xx(e,t,n,r,i,a,o){let s=new Set;r&&Nx(e+t,Wx,({groups:{captureName:e}})=>{s.add(e)},jx.DEFAULT);let c=[n,r?s:null,i,a,o];return`${e}${Zx(`(?:${e}`,`forward`,...c)}(?:)${Zx(`${t})`,`backward`,...c)}${t}`}function Zx(e,t,n,r,i,a,o){let s=e=>t===`forward`?e+2:n-e+2-1,c=``;for(let t=0;t<n;t++){let n=s(t);c+=Mx(e,Hx`${Gx}|\\k<(?<backref>[^>]+)>`,({0:e,groups:{captureName:t,unnamed:s,backref:c}})=>{if(c&&r&&!r.has(c))return e;let l=`_$${n}`;if(s||t){let n=o+a.length+1;return a.push(n),Qx(i,n),s?e:`(?<${t}${l}>`}return Hx`\k<${c}${l}>`},jx.DEFAULT)}return c}function Qx(e,t){for(let n=0;n<e.length;n++)e[n]>=t&&e[n]++}function $x(e,t,n,r,i,a){if(e.size&&r){let o=0;Nx(t,Gx,()=>o++,jx.DEFAULT);let s=a-o+i,c=new Map;return e.forEach((e,t)=>{let i=(r-o*n)/n,a=o*n,l=t>s+o?t+r:t,u=[];for(let t of e)if(t<=s)u.push(t);else if(t>s+o+i)u.push(t+r);else if(t<=s+o)for(let e=0;e<=n;e++)u.push(t+o*e);else for(let e=0;e<=n;e++)u.push(t+a+i*e);c.set(l,u)}),c}return e}var eS=String.fromCodePoint,tS=String.raw,nS={},rS=globalThis.RegExp;nS.flagGroups=(()=>{try{new rS(`(?i:)`)}catch{return!1}return!0})(),nS.unicodeSets=(()=>{try{new rS(`[[]]`,`v`)}catch{return!1}return!0})(),nS.bugFlagVLiteralHyphenIsRange=nS.unicodeSets?(()=>{try{new rS(tS`[\d\-a]`,`v`)}catch{return!0}return!1})():!1,nS.bugNestedClassIgnoresNegation=nS.unicodeSets&&new rS(`[[^a]]`,`v`).test(`a`);function iS(e,{enable:t,disable:n}){return{dotAll:!n?.dotAll&&!!(t?.dotAll||e.dotAll),ignoreCase:!n?.ignoreCase&&!!(t?.ignoreCase||e.ignoreCase)}}function aS(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}function oS(e,t){return cS[e]>=cS[t]}function sS(e,t){if(e==null)throw Error(t??`Value expected`);return e}var cS={ES2025:2025,ES2024:2024,ES2018:2018},lS={auto:`auto`,ES2025:`ES2025`,ES2024:`ES2024`,ES2018:`ES2018`};function uS(e={}){if({}.toString.call(e)!==`[object Object]`)throw Error(`Unexpected options`);if(e.target!==void 0&&!lS[e.target])throw Error(`Unexpected target "${e.target}"`);let t={accuracy:`default`,avoidSubclass:!1,flags:``,global:!1,hasIndices:!1,lazyCompileLength:1/0,target:`aLine truncated
`.replace(/\s+/g,``),`gsu`);function Bx(e){if(!RegExp(`${Rx}\\+`).test(e))return{pattern:e};let t=[],n=null,r=null,i=``,a=0,o;for(zx.lastIndex=0;o=zx.exec(e);){let{0:s,index:c,groups:{qBase:l,qMod:u,invalidQ:d}}=o;if(s===`[`)a||(r=c),a++;else if(s===`]`)a?a--:r=null;else if(!a){if(u===`+`&&i&&!i.startsWith(`(`)){if(d)throw Error(`Invalid quantifier "${s}"`);let t=-1;if(/^\{\d+\}$/.test(l))e=kx(e,c+l.length,u,``);else{if(i===`)`||i===`]`){let t=i===`)`?n:r;if(t===null)throw Error(`Invalid unmatched "${i}"`);e=`${e.slice(0,t)}(?>${e.slice(t,c)}${l})${e.slice(c+s.length)}`}else e=`${e.slice(0,c-i.length)}(?>${i}${l})${e.slice(c+s.length)}`;t+=4}zx.lastIndex+=t}else s[0]===`(`?t.push(c):s===`)`&&(n=t.length?t.pop():null)}i=s}return{pattern:e}}var Vx=String.raw,Hx=Vx`\(\?R=(?<rDepth>[^\)]+)\)|${Vx`\\g<(?<gRNameOrNum>[^>&]+)&R=(?<gRDepth>[^>]+)>`}`,Ux=Vx`\(\?<(?![=!])(?<captureName>[^>]+)>`,Wx=Vx`${Ux}|(?<unnamed>\()(?!\?)`,Gx=new RegExp(Vx`${Ux}|${Hx}|\(\?|\\?.`,`gsu`),Kx=`Cannot use multiple overlapping recursions`;function qx(e,t){let{hiddenCaptures:n,mode:r}={hiddenCaptures:[],mode:`plugin`,...t},i=t?.captureTransfers??new Map;if(!new RegExp(Hx,`su`).test(e))return{pattern:e,captureTransfers:i,hiddenCaptures:n};if(r===`plugin`&&Px(e,Vx`\(\?\(DEFINE\)`,Ax.DEFAULT))throw Error(`DEFINE groups cannot be used with recursion`);let a=[],o=Px(e,Vx`\\[1-9]`,Ax.DEFAULT),s=new Map,c=[],l=!1,u=0,d=0,f;for(Gx.lastIndex=0;f=Gx.exec(e);){let{0:t,groups:{captureName:p,rDepth:m,gRNameOrNum:h,gRDepth:g}}=f;if(t===`[`)u++;else if(u)t===`]`&&u--;else{if(m){if(Jx(m),l)throw Error(Kx);if(o)throw Error(`${r===`external`?`Backrefs`:`Numbered backrefs`} cannot be used with global recursion`);let t=e.slice(0,f.index),s=e.slice(Gx.lastIndex);if(Px(s,Hx,Ax.DEFAULT))throw Error(Kx);let c=m-1;e=Yx(t,s,c,!1,n,a,d),i=Qx(i,t,c,a.length,0,d);break}if(h){Jx(g);let u=!1;for(let e of c)if(e.name===h||e.num===+h){if(u=!0,e.hasRecursedWithin)throw Error(Kx);break}if(!u)throw Error(Vx`Recursive \g cannot be used outside the referenced group "${r===`external`?h:Vx`\g<${h}&R=${g}>`}"`);let p=s.get(h),m=Fx(e,p);if(o&&Px(m,Vx`${Ux}|\((?!\?)`,Ax.DEFAULT))throw Error(`${r===`external`?`Backrefs`:`Numbered backrefs`} cannot be used with recursion of capturing groups`);let _=e.slice(p,f.index),v=m.slice(_.length+t.length),y=a.length,b=g-1,x=Yx(_,v,b,!0,n,a,d);i=Qx(i,_,b,a.length-y,y,d),e=`${e.slice(0,p)}${x}${e.slice(p+m.length)}`,Gx.lastIndex+=x.length-t.length-_.length-v.length,c.forEach(e=>e.hasRecursedWithin=!0),l=!0}else if(p)d++,s.set(String(d),Gx.lastIndex),s.set(p,Gx.lastIndex),c.push({num:d,name:p});else if(t[0]===`(`){let e=t===`(`;e&&(d++,s.set(String(d),Gx.lastIndex)),c.push(e?{num:d}:{})}else t===`)`&&c.pop()}}return n.push(...a),{pattern:e,captureTransfers:i,hiddenCaptures:n}}function Jx(e){let t=`Max depth must be integer between 2 and 100; used ${e}`;if(!/^[1-9]\d*$/.test(e)||(e=+e,e<2||e>100))throw Error(t)}function Yx(e,t,n,r,i,a,o){let s=new Set;r&&Mx(e+t,Ux,({groups:{captureName:e}})=>{s.add(e)},Ax.DEFAULT);let c=[n,r?s:null,i,a,o];return`${e}${Xx(`(?:${e}`,`forward`,...c)}(?:)${Xx(`${t})`,`backward`,...c)}${t}`}function Xx(e,t,n,r,i,a,o){let s=e=>t===`forward`?e+2:n-e+2-1,c=``;for(let t=0;t<n;t++){let n=s(t);c+=jx(e,Vx`${Wx}|\\k<(?<backref>[^>]+)>`,({0:e,groups:{captureName:t,unnamed:s,backref:c}})=>{if(c&&r&&!r.has(c))return e;let l=`_$${n}`;if(s||t){let n=o+a.length+1;return a.push(n),Zx(i,n),s?e:`(?<${t}${l}>`}return Vx`\k<${c}${l}>`},Ax.DEFAULT)}return c}function Zx(e,t){for(let n=0;n<e.length;n++)e[n]>=t&&e[n]++}function Qx(e,t,n,r,i,a){if(e.size&&r){let o=0;Mx(t,Wx,()=>o++,Ax.DEFAULT);let s=a-o+i,c=new Map;return e.forEach((e,t)=>{let i=(r-o*n)/n,a=o*n,l=t>s+o?t+r:t,u=[];for(let t of e)if(t<=s)u.push(t);else if(t>s+o+i)u.push(t+r);else if(t<=s+o)for(let e=0;e<=n;e++)u.push(t+o*e);else for(let e=0;e<=n;e++)u.push(t+a+i*e);c.set(l,u)}),c}return e}var $x=String.fromCodePoint,eS=String.raw,tS={},nS=globalThis.RegExp;tS.flagGroups=(()=>{try{new nS(`(?i:)`)}catch{return!1}return!0})(),tS.unicodeSets=(()=>{try{new nS(`[[]]`,`v`)}catch{return!1}return!0})(),tS.bugFlagVLiteralHyphenIsRange=tS.unicodeSets?(()=>{try{new nS(eS`[\d\-a]`,`v`)}catch{return!0}return!1})():!1,tS.bugNestedClassIgnoresNegation=tS.unicodeSets&&new nS(`[[^a]]`,`v`).test(`a`);function rS(e,{enable:t,disable:n}){return{dotAll:!n?.dotAll&&!!(t?.dotAll||e.dotAll),ignoreCase:!n?.ignoreCase&&!!(t?.ignoreCase||e.ignoreCase)}}function iS(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}function aS(e,t){return sS[e]>=sS[t]}function oS(e,t){if(e==null)throw Error(t??`Value expected`);return e}var sS={ES2025:2025,ES2024:2024,ES2018:2018},cS={auto:`auto`,ES2025:`ES2025`,ES2024:`ES2024`,ES2018:`ES2018`};function lS(e={}){if({}.toString.call(e)!==`[object Object]`)throw Error(`Unexpected options`);if(e.target!==void 0&&!cS[e.target])throw Error(`Unexpected target "${e.target}"`);let t={accuracy:`default`,avoidSubclass:!1,flags:``,global:!1,hasIndices:!1,lazyCompileLength:1/0,target:`aLine truncated
Cc Control cntrl
Cf Format
Cn Unassigned
@@ -152,89 +152,89 @@ Uppercase Upper
Variation_Selector VS
White_Space space
XID_Continue XIDC
XID_Start XIDS`.split(/\s/).map(e=>[Sx(e),e])),gS=new Map([[`s`,eS(383)],[eS(383),`s`]]),_S=new Map([[eS(223),eS(7838)],[eS(107),eS(8490)],[eS(229),eS(8491)],[eS(969),eS(8486)]]),vS=new Map([xS(453),xS(456),xS(459),xS(498),...SS(8072,8079),...SS(8088,8095),...SS(8104,8111),xS(8124),xS(8140),xS(8188)]),yS=new Map([[`alnum`,tS`[\p{Alpha}\p{Nd}]`],[`alpha`,tS`\p{Alpha}`],[`ascii`,tS`\p{ASCII}`],[`blank`,tS`[\p{Zs}\t]`],[`cntrl`,tS`\p{Cc}`],[`digit`,tS`\p{Nd}`],[`graph`,tS`[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]`],[`lower`,tS`\p{Lower}`],[`print`,tS`[[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]\p{Zs}]`],[`punct`,tS`[\p{P}\p{S}]`],[`space`,tS`\p{space}`],[`upper`,tS`\p{Upper}`],[`word`,tS`[\p{Alpha}\p{M}\p{Nd}\p{Pc}]`],[`xdigit`,tS`\p{AHex}`]]);function bS(e,t){let n=[];for(let r=e;r<=t;r++)n.push(r);return n}function xS(e){let t=eS(e);return[t.toLowerCase(),t]}function SS(e,t){return bS(e,t).map(e=>xS(e))}var CS=new Set([`Lower`,`Lowercase`,`Upper`,`Uppercase`,`Ll`,`Lowercase_Letter`,`Lt`,`Titlecase_Letter`,`Lu`,`Uppercase_Letter`]);function wS(e,t){let n={accuracy:`default`,asciiWordBoundaries:!1,avoidSubclass:!1,bestEffortTarget:`ES2025`,...t};OS(e);let r={accuracy:n.accuracy,asciiWordBoundaries:n.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,flagDirectivesByAlt:new Map,jsGroupNameMap:new Map,minTargetEs2024:oS(n.bestEffortTarget,`ES2024`),passedLookbehind:!1,strategy:null,subroutineRefMap:new Map,supportedGNodes:new Set,digitIsAscii:e.flags.digitIsAscii,spaceIsAscii:e.flags.spaceIsAscii,wordIsAscii:e.flags.wordIsAscii};Tx(e,TS,r);let i={dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},a={currentFlags:i,prevFlags:null,globalFlags:i,groupOriginByCopy:new Map,groupsByName:new Map,multiplexCapturesToLeftByRef:new Map,openRefs:new Map,reffedNodesByReferencer:new Map,subroutineRefMap:r.subroutineRefMap};return Tx(e,ES,a),Tx(e,DS,{groupsByName:a.groupsByName,highestOrphanBackref:0,numCapturesToLeft:0,reffedNodesByReferencer:a.reffedNodesByReferencer}),e._originMap=a.groupOriginByCopy,e._strategy=r.strategy,e}var TS={AbsenceFunction({node:e,parent:t,replaceWith:n}){let{body:r,kind:i}=e;if(i===`repeater`){let e=sx();e.body[0].body.push(cx({negate:!0,body:r}),mx(`Any`));let i=sx();i.body[0].body.push(dx(`greedy`,0,1/0,e)),n(qS(i,t),{traverse:!0})}else throw Error(`Unsupported absence function "(?~|"`)},Alternative:{enter({node:e,parent:t,key:n},{flagDirectivesByAlt:r}){let i=e.body.filter(e=>e.kind===`flags`);for(let e=n+1;e<t.body.length;e++){let n=t.body[e];aS(r,n,[]).push(...i)}},exit({node:e},{flagDirectivesByAlt:t}){if(t.get(e)?.length){let n=FS(t.get(e));if(n){let t=sx({flags:n});t.body[0].body=e.body,e.body=[qS(t,e)]}}}},Assertion({node:e,parent:t,key:n,container:r,root:i,remove:a,replaceWith:o},s){let{kind:c,negate:l}=e,{asciiWordBoundaries:u,avoidSubclass:d,supportedGNodes:f,wordIsAscii:p}=s;if(c===`text_segment_boundary`)throw Error(`Unsupported text segment boundary "\\${l?`Y`:`y`}"`);if(c===`line_end`)o(qS(cx({body:[Qb({body:[$b(`string_end`)]}),Qb({body:[nx(10)]})]}),t));else if(c===`line_start`)o(qS(WS(tS`(?<=\A|\n(?!\z))`,{skipLookbehindValidation:!0}),t));else if(c===`search_start`){if(f.has(e))i.flags.sticky=!0,a();else{let e=r[n-1];if(e&&VS(e))o(qS(cx({negate:!0}),t));else if(d)throw Error(tS`Uses "\G" in a way that requires a subclass`);else o(KS($b(`string_start`),t)),s.strategy=`clip_search`}}else if(c!==`string_end`&&c!==`string_start`){if(c===`string_end_newline`)o(qS(WS(tS`(?=\n?\z)`),t));else if(c===`word_boundary`){if(!p&&!u){let e=`(?:(?<=${pS})(?!${pS})|(?<!${pS})(?=${pS}))`,n=`(?:(?<=${pS})(?=${pS})|(?<!${pS})(?!${pS}))`;o(qS(WS(l?n:e),t))}}else throw Error(`Unexpected assertion kind "${c}"`)}},Backreference({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n==`string`&&!US(n)&&(n=PS(n,t),e.ref=n)},CapturingGroup({node:e},{jsGroupNameMap:t,subroutineRefMap:n}){let{name:r}=e;r&&!US(r)&&(r=PS(r,t),e.name=r),n.set(e.number,e),r&&n.set(r,e)},CharacterClassRange({node:e,parent:t,replaceWith:n}){t.kind===`intersection`&&n(qS(rx({body:[e]}),t),{traverse:!0})},CharacterSet({node:e,parent:t,replaceWith:n},{accuracy:r,minTargetEs2024:i,digitIsAscii:a,spaceIsAscii:o,wordIsAscii:s}){let{kind:c,negate:l,value:u}=e;if(a&&(c===`digit`||u===`digit`))n(KS(ix(`digit`,{negate:l}),t));else if(o&&(c===`space`||u===`space`))n(qS(GS(WS(dS),l),t));else if(s&&(c===`word`||u===`word`))n(KS(ix(`word`,{negate:l}),t));else if(c===`any`)n(KS(mx(`Any`),t));else if(c===`digit`)n(KS(mx(`Nd`,{negate:l}),t));else if(c!==`dot`){if(c===`text_segment`){if(r===`strict`)throw Error(tS`Use of "\X" requires non-strict accuracy`);let e=`\\p{Emoji}(?:\\p{EMod}|\\uFE0F\\u20E3?|[\\x{E0020}-\\x{E007E}]+\\x{E007F})?`,a=tS`\p{RI}{2}|${e}(?:\u200D${e})*`;n(qS(WS(tS`(?>\r\n|${i?tS`\p{RGI_Emoji}`:a}|\P{M}\p{M}*)`,{skipPropertyNameValidation:!0}),t))}else if(c===`hex`)n(KS(mx(`AHex`,{negate:l}),t));else if(c===`newline`)n(qS(WS(l?`[^
XID_Start XIDS`.split(/\s/).map(e=>[xx(e),e])),hS=new Map([[`s`,$x(383)],[$x(383),`s`]]),gS=new Map([[$x(223),$x(7838)],[$x(107),$x(8490)],[$x(229),$x(8491)],[$x(969),$x(8486)]]),_S=new Map([bS(453),bS(456),bS(459),bS(498),...xS(8072,8079),...xS(8088,8095),...xS(8104,8111),bS(8124),bS(8140),bS(8188)]),vS=new Map([[`alnum`,eS`[\p{Alpha}\p{Nd}]`],[`alpha`,eS`\p{Alpha}`],[`ascii`,eS`\p{ASCII}`],[`blank`,eS`[\p{Zs}\t]`],[`cntrl`,eS`\p{Cc}`],[`digit`,eS`\p{Nd}`],[`graph`,eS`[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]`],[`lower`,eS`\p{Lower}`],[`print`,eS`[[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]\p{Zs}]`],[`punct`,eS`[\p{P}\p{S}]`],[`space`,eS`\p{space}`],[`upper`,eS`\p{Upper}`],[`word`,eS`[\p{Alpha}\p{M}\p{Nd}\p{Pc}]`],[`xdigit`,eS`\p{AHex}`]]);function yS(e,t){let n=[];for(let r=e;r<=t;r++)n.push(r);return n}function bS(e){let t=$x(e);return[t.toLowerCase(),t]}function xS(e,t){return yS(e,t).map(e=>bS(e))}var SS=new Set([`Lower`,`Lowercase`,`Upper`,`Uppercase`,`Ll`,`Lowercase_Letter`,`Lt`,`Titlecase_Letter`,`Lu`,`Uppercase_Letter`]);function CS(e,t){let n={accuracy:`default`,asciiWordBoundaries:!1,avoidSubclass:!1,bestEffortTarget:`ES2025`,...t};DS(e);let r={accuracy:n.accuracy,asciiWordBoundaries:n.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,flagDirectivesByAlt:new Map,jsGroupNameMap:new Map,minTargetEs2024:aS(n.bestEffortTarget,`ES2024`),passedLookbehind:!1,strategy:null,subroutineRefMap:new Map,supportedGNodes:new Set,digitIsAscii:e.flags.digitIsAscii,spaceIsAscii:e.flags.spaceIsAscii,wordIsAscii:e.flags.wordIsAscii};wx(e,wS,r);let i={dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},a={currentFlags:i,prevFlags:null,globalFlags:i,groupOriginByCopy:new Map,groupsByName:new Map,multiplexCapturesToLeftByRef:new Map,openRefs:new Map,reffedNodesByReferencer:new Map,subroutineRefMap:r.subroutineRefMap};return wx(e,TS,a),wx(e,ES,{groupsByName:a.groupsByName,highestOrphanBackref:0,numCapturesToLeft:0,reffedNodesByReferencer:a.reffedNodesByReferencer}),e._originMap=a.groupOriginByCopy,e._strategy=r.strategy,e}var wS={AbsenceFunction({node:e,parent:t,replaceWith:n}){let{body:r,kind:i}=e;if(i===`repeater`){let e=ox();e.body[0].body.push(sx({negate:!0,body:r}),px(`Any`));let i=ox();i.body[0].body.push(ux(`greedy`,0,1/0,e)),n(KS(i,t),{traverse:!0})}else throw Error(`Unsupported absence function "(?~|"`)},Alternative:{enter({node:e,parent:t,key:n},{flagDirectivesByAlt:r}){let i=e.body.filter(e=>e.kind===`flags`);for(let e=n+1;e<t.body.length;e++){let n=t.body[e];iS(r,n,[]).push(...i)}},exit({node:e},{flagDirectivesByAlt:t}){if(t.get(e)?.length){let n=PS(t.get(e));if(n){let t=ox({flags:n});t.body[0].body=e.body,e.body=[KS(t,e)]}}}},Assertion({node:e,parent:t,key:n,container:r,root:i,remove:a,replaceWith:o},s){let{kind:c,negate:l}=e,{asciiWordBoundaries:u,avoidSubclass:d,supportedGNodes:f,wordIsAscii:p}=s;if(c===`text_segment_boundary`)throw Error(`Unsupported text segment boundary "\\${l?`Y`:`y`}"`);if(c===`line_end`)o(KS(sx({body:[Xb({body:[Zb(`string_end`)]}),Xb({body:[ex(10)]})]}),t));else if(c===`line_start`)o(KS(US(eS`(?<=\A|\n(?!\z))`,{skipLookbehindValidation:!0}),t));else if(c===`search_start`){if(f.has(e))i.flags.sticky=!0,a();else{let e=r[n-1];if(e&&BS(e))o(KS(sx({negate:!0}),t));else if(d)throw Error(eS`Uses "\G" in a way that requires a subclass`);else o(GS(Zb(`string_start`),t)),s.strategy=`clip_search`}}else if(c!==`string_end`&&c!==`string_start`){if(c===`string_end_newline`)o(KS(US(eS`(?=\n?\z)`),t));else if(c===`word_boundary`){if(!p&&!u){let e=`(?:(?<=${fS})(?!${fS})|(?<!${fS})(?=${fS}))`,n=`(?:(?<=${fS})(?=${fS})|(?<!${fS})(?!${fS}))`;o(KS(US(l?n:e),t))}}else throw Error(`Unexpected assertion kind "${c}"`)}},Backreference({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n==`string`&&!HS(n)&&(n=NS(n,t),e.ref=n)},CapturingGroup({node:e},{jsGroupNameMap:t,subroutineRefMap:n}){let{name:r}=e;r&&!HS(r)&&(r=NS(r,t),e.name=r),n.set(e.number,e),r&&n.set(r,e)},CharacterClassRange({node:e,parent:t,replaceWith:n}){t.kind===`intersection`&&n(KS(tx({body:[e]}),t),{traverse:!0})},CharacterSet({node:e,parent:t,replaceWith:n},{accuracy:r,minTargetEs2024:i,digitIsAscii:a,spaceIsAscii:o,wordIsAscii:s}){let{kind:c,negate:l,value:u}=e;if(a&&(c===`digit`||u===`digit`))n(GS(rx(`digit`,{negate:l}),t));else if(o&&(c===`space`||u===`space`))n(KS(WS(US(uS),l),t));else if(s&&(c===`word`||u===`word`))n(GS(rx(`word`,{negate:l}),t));else if(c===`any`)n(GS(px(`Any`),t));else if(c===`digit`)n(GS(px(`Nd`,{negate:l}),t));else if(c!==`dot`){if(c===`text_segment`){if(r===`strict`)throw Error(eS`Use of "\X" requires non-strict accuracy`);let e=`\\p{Emoji}(?:\\p{EMod}|\\uFE0F\\u20E3?|[\\x{E0020}-\\x{E007E}]+\\x{E007F})?`,a=eS`\p{RI}{2}|${e}(?:\u200D${e})*`;n(KS(US(eS`(?>\r\n|${i?eS`\p{RGI_Emoji}`:a}|\P{M}\p{M}*)`,{skipPropertyNameValidation:!0}),t))}else if(c===`hex`)n(GS(px(`AHex`,{negate:l}),t));else if(c===`newline`)n(KS(US(l?`[^
]`:`(?>\r
?|[
\v\f…\u2028\u2029])`),t));else if(c===`posix`){if(!i&&(u===`graph`||u===`print`)){if(r===`strict`)throw Error(`POSIX class "${u}" requires min target ES2024 or non-strict accuracy`);let e={graph:`!-~`,print:` -~`}[u];l&&(e=`\0-${eS(e.codePointAt(0)-1)}${eS(e.codePointAt(2)+1)}-\u{10FFFF}`),n(qS(WS(`[${e}]`),t))}else n(qS(GS(WS(yS.get(u)),l),t))}else if(c===`property`)hS.has(Sx(u))||(e.key=`sc`);else if(c===`space`)n(KS(mx(`space`,{negate:l}),t));else if(c===`word`)n(qS(GS(WS(pS),l),t));else throw Error(`Unexpected character set kind "${c}"`)}},Directive({node:e,parent:t,root:n,remove:r,replaceWith:i,removeAllPrevSiblings:a,removeAllNextSiblings:o}){let{kind:s,flags:c}=e;if(s===`flags`){if(!c.enable&&!c.disable)r();else{let e=sx({flags:c});e.body[0].body=o(),i(qS(e,t),{traverse:!0})}}else if(s===`keep`){let e=n.body[0],r=n.body.length===1&&zb(e,{type:`Group`})&&e.body[0].body.length===1?e.body[0]:n;if(t.parent!==r||r.body.length>1)throw Error(tS`Uses "\K" in a way that's unsupported`);let o=cx({behind:!0});o.body[0].body=a(),i(qS(o,t))}else throw Error(`Unexpected directive kind "${s}"`)},Flags({node:e,parent:t}){if(e.posixIsAscii)throw Error(`Unsupported flag "P"`);if(e.textSegmentMode===`word`)throw Error(`Unsupported flag "y{w}"`);[`digitIsAscii`,`extended`,`posixIsAscii`,`spaceIsAscii`,`wordIsAscii`,`textSegmentMode`].forEach(t=>delete e[t]),Object.assign(e,{global:!1,hasIndices:!1,multiline:!1,sticky:e.sticky??!1}),t.options={disable:{x:!0,n:!0},force:{v:!0}}},Group({node:e}){if(!e.flags)return;let{enable:t,disable:n}=e.flags;t?.extended&&delete t.extended,n?.extended&&delete n.extended,t?.dotAll&&n?.dotAll&&delete t.dotAll,t?.ignoreCase&&n?.ignoreCase&&delete t.ignoreCase,t&&!Object.keys(t).length&&delete e.flags.enable,n&&!Object.keys(n).length&&delete e.flags.disable,!e.flags.enable&&!e.flags.disable&&delete e.flags},LookaroundAssertion({node:e},t){let{kind:n}=e;n===`lookbehind`&&(t.passedLookbehind=!0)},NamedCallout({node:e,parent:t,replaceWith:n}){let{kind:r}=e;if(r===`fail`)n(qS(cx({negate:!0}),t));else throw Error(`Unsupported named callout "(*${r.toUpperCase()}"`)},Quantifier({node:e}){if(e.body.type===`Quantifier`){let t=sx();t.body[0].body.push(e.body),e.body=qS(t,e)}},Regex:{enter({node:e},{supportedGNodes:t}){let n=[],r=!1,i=!1;for(let t of e.body)if(t.body.length===1&&t.body[0].kind===`search_start`)t.body.pop();else{let e=RS(t.body);e?(r=!0,Array.isArray(e)?n.push(...e):n.push(e)):i=!0}r&&!i&&n.forEach(e=>t.add(e))},exit(e,{accuracy:t,passedLookbehind:n,strategy:r}){if(t===`strict`&&n&&r)throw Error(tS`Uses "\G" in a way that requires non-strict accuracy`)}},Subroutine({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n==`string`&&!US(n)&&(n=PS(n,t),e.ref=n)}},ES={Backreference({node:e},{multiplexCapturesToLeftByRef:t,reffedNodesByReferencer:n}){let{orphan:r,ref:i}=e;r||n.set(e,[...t.get(i).map(({node:e})=>e)])},CapturingGroup:{enter({node:e,parent:t,replaceWith:n,skip:r},{groupOriginByCopy:i,groupsByName:a,multiplexCapturesToLeftByRef:o,openRefs:s,reffedNodesByReferencer:c}){let l=i.get(e);if(l&&s.has(e.number)){let r=KS(MS(e.number),t);c.set(r,s.get(e.number)),n(r);return}s.set(e.number,e),o.set(e.number,[]),e.name&&aS(o,e.name,[]);let u=o.get(e.name??e.number);for(let t=0;t<u.length;t++){let n=u[t];if(l===n.node||l&&l===n.origin||e===n.origin){u.splice(t,1);break}}if(o.get(e.number).push({node:e,origin:l}),e.name&&o.get(e.name).push({node:e,origin:l}),e.name){let t=aS(a,e.name,new Map),n=!1;if(l)n=!0;else for(let e of t.values())if(!e.hasDuplicateNameToRemove){n=!0;break}a.get(e.name).set(e,{node:e,hasDuplicateNameToRemove:n})}},exit({node:e},{openRefs:t}){t.get(e.number)===e&&t.delete(e.number)}},Group:{enter({node:e},t){t.prevFlags=t.currentFlags,e.flags&&(t.currentFlags=iS(t.currentFlags,e.flags))},exit(e,t){t.currentFlags=t.prevFlags}},Subroutine({node:e,parent:t,replaceWith:n},r){let{isRecursive:i,ref:a}=e;if(i){let n=t;for(;(n=n.parent)&&(n.type!==`CapturingGroup`||n.name!==a&&n.number!==a););r.reffedNodesByReferencer.set(e,n);return}let o=r.subroutineRefMap.get(a),s=a===0,c=s?MS(0):jS(o,r.groupOriginByCopy,null),l=c;if(!s){let e=FS(NS(o,e=>e.type===`Group`&&!!e.flags)),t=e?iS(r.globalFlags,e):r.globalFlags;kS(t,r.currentFlags)||(l=sx({flags:IS(t)}),l.body[0].body.push(c))}n(qS(l,t),{traverse:!s})}},DS={Backreference({node:e,parent:t,replaceWith:n},r){if(e.orphan){r.highestOrphanBackref=Math.max(r.highestOrphanBackref,e.ref);return}let i=r.reffedNodesByReferencer.get(e).filter(t=>AS(t,e));i.length?i.length>1?n(qS(sx({atomic:!0,body:i.reverse().map(e=>Qb({body:[ex(e.number)]}))}),t)):e.ref=i[0].number:n(qS(cx({negate:!0}),t))},CapturingGroup({node:e},t){e.number=++t.numCapturesToLeft,e.name&&t.groupsByName.get(e.name).get(e).hasDuplicateNameToRemove&&delete e.name},Regex:{exit({node:e},t){let n=Math.max(t.highestOrphanBackref-t.numCapturesToLeft,0);for(let t=0;t<n;t++){let t=tx();e.body.at(-1).body.push(t)}}},Subroutine({node:e},t){e.isRecursive&&e.ref!==0&&(e.ref=t.reffedNodesByR Line truncated
`).flatMap(e=>i(e)):i(e);return{lines:a.map(e=>e.map(e=>({content:e.content,htmlStyle:e.htmlStyle}))),state:n.getLastGrammarState(a)}}}}function jC(e,t){let n=at(null);N(()=>Ge(t),(e,t,r)=>{if(typeof window>`u`)return;let i=!1;r(()=>i=!0),n.value=null,AC(e).then(e=>{i||(n.value=e)}).catch(()=>{})},{immediate:!0});let r={highlighter:null,text:``,lines:[]};return Y(()=>{let t=Ge(e),i=t.endsWith(`
\v\f…\u2028\u2029])`),t));else if(c===`posix`){if(!i&&(u===`graph`||u===`print`)){if(r===`strict`)throw Error(`POSIX class "${u}" requires min target ES2024 or non-strict accuracy`);let e={graph:`!-~`,print:` -~`}[u];l&&(e=`\0-${$x(e.codePointAt(0)-1)}${$x(e.codePointAt(2)+1)}-\u{10FFFF}`),n(KS(US(`[${e}]`),t))}else n(KS(WS(US(vS.get(u)),l),t))}else if(c===`property`)mS.has(xx(u))||(e.key=`sc`);else if(c===`space`)n(GS(px(`space`,{negate:l}),t));else if(c===`word`)n(KS(WS(US(fS),l),t));else throw Error(`Unexpected character set kind "${c}"`)}},Directive({node:e,parent:t,root:n,remove:r,replaceWith:i,removeAllPrevSiblings:a,removeAllNextSiblings:o}){let{kind:s,flags:c}=e;if(s===`flags`){if(!c.enable&&!c.disable)r();else{let e=ox({flags:c});e.body[0].body=o(),i(KS(e,t),{traverse:!0})}}else if(s===`keep`){let e=n.body[0],r=n.body.length===1&&Lb(e,{type:`Group`})&&e.body[0].body.length===1?e.body[0]:n;if(t.parent!==r||r.body.length>1)throw Error(eS`Uses "\K" in a way that's unsupported`);let o=sx({behind:!0});o.body[0].body=a(),i(KS(o,t))}else throw Error(`Unexpected directive kind "${s}"`)},Flags({node:e,parent:t}){if(e.posixIsAscii)throw Error(`Unsupported flag "P"`);if(e.textSegmentMode===`word`)throw Error(`Unsupported flag "y{w}"`);[`digitIsAscii`,`extended`,`posixIsAscii`,`spaceIsAscii`,`wordIsAscii`,`textSegmentMode`].forEach(t=>delete e[t]),Object.assign(e,{global:!1,hasIndices:!1,multiline:!1,sticky:e.sticky??!1}),t.options={disable:{x:!0,n:!0},force:{v:!0}}},Group({node:e}){if(!e.flags)return;let{enable:t,disable:n}=e.flags;t?.extended&&delete t.extended,n?.extended&&delete n.extended,t?.dotAll&&n?.dotAll&&delete t.dotAll,t?.ignoreCase&&n?.ignoreCase&&delete t.ignoreCase,t&&!Object.keys(t).length&&delete e.flags.enable,n&&!Object.keys(n).length&&delete e.flags.disable,!e.flags.enable&&!e.flags.disable&&delete e.flags},LookaroundAssertion({node:e},t){let{kind:n}=e;n===`lookbehind`&&(t.passedLookbehind=!0)},NamedCallout({node:e,parent:t,replaceWith:n}){let{kind:r}=e;if(r===`fail`)n(KS(sx({negate:!0}),t));else throw Error(`Unsupported named callout "(*${r.toUpperCase()}"`)},Quantifier({node:e}){if(e.body.type===`Quantifier`){let t=ox();t.body[0].body.push(e.body),e.body=KS(t,e)}},Regex:{enter({node:e},{supportedGNodes:t}){let n=[],r=!1,i=!1;for(let t of e.body)if(t.body.length===1&&t.body[0].kind===`search_start`)t.body.pop();else{let e=LS(t.body);e?(r=!0,Array.isArray(e)?n.push(...e):n.push(e)):i=!0}r&&!i&&n.forEach(e=>t.add(e))},exit(e,{accuracy:t,passedLookbehind:n,strategy:r}){if(t===`strict`&&n&&r)throw Error(eS`Uses "\G" in a way that requires non-strict accuracy`)}},Subroutine({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n==`string`&&!HS(n)&&(n=NS(n,t),e.ref=n)}},TS={Backreference({node:e},{multiplexCapturesToLeftByRef:t,reffedNodesByReferencer:n}){let{orphan:r,ref:i}=e;r||n.set(e,[...t.get(i).map(({node:e})=>e)])},CapturingGroup:{enter({node:e,parent:t,replaceWith:n,skip:r},{groupOriginByCopy:i,groupsByName:a,multiplexCapturesToLeftByRef:o,openRefs:s,reffedNodesByReferencer:c}){let l=i.get(e);if(l&&s.has(e.number)){let r=GS(jS(e.number),t);c.set(r,s.get(e.number)),n(r);return}s.set(e.number,e),o.set(e.number,[]),e.name&&iS(o,e.name,[]);let u=o.get(e.name??e.number);for(let t=0;t<u.length;t++){let n=u[t];if(l===n.node||l&&l===n.origin||e===n.origin){u.splice(t,1);break}}if(o.get(e.number).push({node:e,origin:l}),e.name&&o.get(e.name).push({node:e,origin:l}),e.name){let t=iS(a,e.name,new Map),n=!1;if(l)n=!0;else for(let e of t.values())if(!e.hasDuplicateNameToRemove){n=!0;break}a.get(e.name).set(e,{node:e,hasDuplicateNameToRemove:n})}},exit({node:e},{openRefs:t}){t.get(e.number)===e&&t.delete(e.number)}},Group:{enter({node:e},t){t.prevFlags=t.currentFlags,e.flags&&(t.currentFlags=rS(t.currentFlags,e.flags))},exit(e,t){t.currentFlags=t.prevFlags}},Subroutine({node:e,parent:t,replaceWith:n},r){let{isRecursive:i,ref:a}=e;if(i){let n=t;for(;(n=n.parent)&&(n.type!==`CapturingGroup`||n.name!==a&&n.number!==a););r.reffedNodesByReferencer.set(e,n);return}let o=r.subroutineRefMap.get(a),s=a===0,c=s?jS(0):AS(o,r.groupOriginByCopy,null),l=c;if(!s){let e=PS(MS(o,e=>e.type===`Group`&&!!e.flags)),t=e?rS(r.globalFlags,e):r.globalFlags;OS(t,r.currentFlags)||(l=ox({flags:FS(t)}),l.body[0].body.push(c))}n(KS(l,t),{traverse:!s})}},ES={Backreference({node:e,parent:t,replaceWith:n},r){if(e.orphan){r.highestOrphanBackref=Math.max(r.highestOrphanBackref,e.ref);return}let i=r.reffedNodesByReferencer.get(e).filter(t=>kS(t,e));i.length?i.length>1?n(KS(ox({atomic:!0,body:i.reverse().map(e=>Xb({body:[Qb(e.number)]}))}),t)):e.ref=i[0].number:n(KS(sx({negate:!0}),t))},CapturingGroup({node:e},t){e.number=++t.numCapturesToLeft,e.name&&t.groupsByName.get(e.name).get(e).hasDuplicateNameToRemove&&delete e.name},Regex:{exit({node:e},t){let n=Math.max(t.highestOrphanBackref-t.numCapturesToLeft,0);for(let t=0;t<n;t++){let t=$b();e.body.at(-1).body.push(t)}}},Subroutine({node:e},t){e.isRecursive&&e.ref!==0&&(e.ref=t.reffedNodesByR Line truncated
`).flatMap(e=>i(e)):i(e);return{lines:a.map(e=>e.map(e=>({content:e.content,htmlStyle:e.htmlStyle}))),state:n.getLastGrammarState(a)}}}}function AC(e,t){let n=at(null);N(()=>Ge(t),(e,t,r)=>{if(typeof window>`u`)return;let i=!1;r(()=>i=!0),n.value=null,kC(e).then(e=>{i||(n.value=e)}).catch(()=>{})},{immediate:!0});let r={highlighter:null,text:``,lines:[]};return Y(()=>{let t=Ge(e),i=t.endsWith(`
`)?t.slice(0,-1):t,a=n.value;if(!a)return i.split(`
`).map(e=>e?[{content:e}]:[]);(r.highlighter!==a||!i.startsWith(r.text))&&(r={highlighter:a,text:``,lines:[]});let o=i.lastIndexOf(`
`)+1;if(o>r.text.length){let e=a.highlight(i.slice(r.text.length,o-1),r.state);r={highlighter:a,text:i.slice(0,o),lines:[...r.lines,...e.lines],state:e.state}}let s=a.highlight(i.slice(o),r.state).lines[0]??[];return[...r.lines,s]})}var MC=qe(`rounded-lg text-sm data-[size=sm]:text-xs has-[>[data-slot=code-block-content]:focus-visible]:ring-3 has-[>[data-slot=code-block-content]:focus-visible]:ring-ring/50 group/code-block relative flex w-full min-w-0 flex-col overflow-hidden`,{variants:{variant:{default:`border border-input text-foreground dark:bg-input/30 has-[>[data-slot=code-block-content]:focus-visible]:border-ring`,destructive:`border border-destructive/30 text-destructive dark:border-destructive/40`}},defaultVariants:{variant:`default`}}),NC=qe(`-mx-3 px-3 in-data-numbered:gap-x-3 before:min-w-6 before:text-end before:text-muted-foreground after:start-1 after:text-muted-foreground group-data-[size=sm]/code-block:-mx-2.5 group-data-[size=sm]/code-block:px-2.5 relative block min-h-lh after:absolute after:top-0 after:select-none in-data-numbered:col-span-2 in-data-numbered:grid in-data-numbered:grid-cols-subgrid in-data-numbered:[counter-increment:line] in-data-numbered:before:content-[counter(line)] in-data-numbered:before:select-none in-data-numbered:supports-[content:counter(line)_/_'']:before:content-[counter(line)_/_'']`,{variants:{variant:{default:``,added:`bg-muted after:content-['+']`,removed:`bg-destructive/10 after:text-destructive after:content-['−']`,highlighted:`bg-muted`}},defaultVariants:{variant:`default`}}),PC=P({__name:`Message`,props:{class:{type:[Boolean,null,String,Object,Array]},align:{default:`start`},asChild:{type:Boolean},as:{default:`div`}},setup(e){let t=e;return(n,r)=>(L(),q(V(dt),{"data-slot":`message`,"data-align":e.align,as:e.as,"as-child":e.asChild,class:z(V(W)(`text-sm gap-2 group/message relative flex w-full min-w-0 data-[align=end]:flex-row-reverse`,t.class))},{default:I(()=>[K(n.$slots,`default`)]),_:3},8,[`data-align`,`as`,`as-child`,`class`]))}}),FC=P({__name:`MessageContent`,props:{class:{type:[Boolean,null,String,Object,Array]},asChild:{type:Boolean},as:{default:`div`}},setup(e){let t=e;return(n,r)=>(L(),q(V(dt),{"data-slot":`message-content`,as:e.as,"as-child":e.asChild,class:z(V(W)(`gap-2.5 group-data-[align=end]/message:*:data-slot:self-end flex w-full min-w-0 flex-col wrap-break-word`,t.class))},{default:I(()=>[K(n.$slots,`default`)]),_:3},8,[`as`,`as-child`,`class`]))}}),IC=P({__name:`MessageFooter`,props:{class:{type:[Boolean,null,String,Object,Array]},asChild:{type:Boolean},as:{default:`div`}},setup(e){let t=e;return(n,r)=>(L(),q(V(dt),{"data-slot":`message-footer`,as:e.as,"as-child":e.asChild,class:z(V(W)(`text-xs font-medium text-muted-foreground px-3 group-has-data-[variant=ghost]/message:px-0 flex max-w-full min-w-0 items-center group-data-[align=end]/message:justify-end`,t.class))},{default:I(()=>[K(n.$slots,`default`)]),_:3},8,[`as`,`as-child`,`class`]))}});function LC(e){switch(e.type){case`image`:return`[photo]`;case`video`:return`[video]`;case`audio`:return`[audio]`;case`document`:return e.file_name?`[document: ${e.file_name}]`:`[document]`;default:return`[${e.type||`attachment`}]`}}function RC(e){let t=[];return e.mime_type&&t.push(e.mime_type),e.file_name&&t.push(e.file_name),e.file_size!==void 0&&t.push(`${e.file_size} bytes`),e.width&&e.height&&t.push(`${e.width}×${e.height}`),e.duration!==void 0&&t.push(`${e.duration} s`),t.join(` · `)}var zC={class:`truncate`},BC=P({__name:`ChatAttachment`,props:{attachment:{}},setup(e){return(t,n)=>(L(),q(_e(e.attachment.url?`a`:`span`),{href:e.attachment.url,target:e.attachment.url?`_blank`:void 0,rel:e.attachment.url?`noopener noreferrer`:void 0,title:V(RC)(e.attachment),class:`inline-flex max-w-full items-center gap-1.5 rounded-md border border-border bg-muted px-2.5 py-1 text-xs font-medium text-fg-muted`},{default:I(()=>[A(V(pte),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),R(`span`,zC,B(V(LC)(e.attachment)),1)]),_:1},8,[`href`,`target`,`rel`,`title`]))}}),VC=P({__name:`CodeView`,props:{code:{},lang:{},class:{}},setup(e){let t=e,n=jC(()=>t.code,()=>t.lang||`text`);return(r,i)=>(L(),q(V(gm),{class:z(V(W)(`bg-muted`,t.class))},{default:I(()=>[A(V(_m),null,{default:I(()=>[A(V(Cm),{value:e.code},null,8,[`value`])]),_:1}),A(V(xm),{wrap:``,class:`max-h-[60vh] pe-10 text-xs`},{default:I(()=>[(L(!0),j(U,null,M(V(n),(e,t)=>(L(),q(V(bm),{key:t},{default:I(()=>[(L(!0),j(U,null,M(e,(e,t)=>(L(),q(V(wm),{key:t,token:e},null,8,[`token`]))),128))]),_:2},1024))),128))]),_:1})]),_:1},8,[`class`]))}}),HC=[`src`,`alt`],UC={key:1},WC={key:2},GC={key:3,class:`rounded bg-foreground/10 px-1 py-0.5 font-mono text-[0.9em]`},KC=[`href`],qC={key:5},JC=P({__name:`ChatInline`,props:{inline:{}},setup(e){return(t,n)=>(L(!0),j(U,null,M(e.inline,(e,t)=>(L(),j(U,{key:t},[e.kind===`image`?(L(),j(`img`,{key:0,src:e.src,alt:e.alt,loading:`lazy`,class:`my-1 block max-h-96 max-w-full cursor-pointer rounded-md border border-border bgLine truncated
`),r=[],i=null,a=null,o=``,s=()=>{r.length&&(t.push({kind:`p`,inline:XC(r.join(` `))}),r=[])},c=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>XC(e))}),null)};for(let e=0;e<n.length;e++){let l=n[e];if(l.startsWith("```")){s(),c(),a?(t.push({kind:`pre`,code:a.join(`
`),lang:o}),a=null):(a=[],o=l.slice(3).trim().split(/\s/)[0]);continue}if(a){a.push(l);continue}let u=QC(l),d=e+1<n.length?QC(n[e+1]):null;if(u&&d&&$C(d)&&u.length===d.length){s(),c();let r=[];for(e+=2;e<n.length;e++){let t=QC(n[e]);if(!t||t.length!==u.length){e--;break}r.push(t)}t.push({kind:`table`,head:u.map(e=>XC(e)),rows:r.map(e=>e.map(e=>XC(e)))});continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),t.push({kind:`h${f[1].length}`,inline:XC(f[2])});continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let e=m?`ol`:`ul`;(!i||i.tag!==e)&&(c(),i={tag:e,items:[]}),i.items.push((p||m)[1])}else l.startsWith(`>`)?(s(),c(),t.push({kind:`blockquote`,inline:XC(l.replace(/^>\s?/,``))})):r.push(l)}return s(),c(),a&&t.push({kind:`pre`,code:a.join(`
`),lang:o}),t}function QC(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 $C(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var ew={class:`[overflow-wrap:anywhere]`},tw={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},nw={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},rw={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},iw={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},aw={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},ow={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},Jte={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},Yte={key:8,class:`mb-2.5 last:mb-0`},sw=P({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=Y(()=>ZC(t.text));return(e,t)=>(L(),j(`div`,ew,[(L(!0),j(U,null,M(n.value,(e,t)=>(L(),j(U,{key:t},[e.kind===`pre`?(L(),q(VC,{key:0,code:e.code,lang:e.lang,class:`my-2`},null,8,[`code`,`lang`])):e.kind===`table`?(L(),j(`table`,tw,[R(`thead`,null,[R(`tr`,null,[(L(!0),j(U,null,M(e.head,(e,t)=>(L(),j(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[A(JC,{inline:e},null,8,[`inline`])]))),128))])]),R(`tbody`,null,[(L(!0),j(U,null,M(e.rows,(e,t)=>(L(),j(`tr`,{key:t},[(L(!0),j(U,null,M(e,(e,t)=>(L(),j(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[A(JC,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(L(),j(`blockquote`,nw,[A(JC,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(L(),j(`h1`,rw,[A(JC,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(L(),j(`h2`,iw,[A(JC,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(L(),j(`h3`,aw,[A(JC,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(L(),j(`ul`,ow,[(L(!0),j(U,null,M(e.items,(e,t)=>(L(),j(`li`,{key:t},[A(JC,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(L(),j(`ol`,Jte,[(L(!0),j(U,null,M(e.items,(e,t)=>(L(),j(`li`,{key:t},[A(JC,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(L(),j(`p`,Yte,[A(JC,{inline:e.inline},null,8,[`inline`])])):F(``,!0)],64))),128))]))}}),Xte={class:`truncate`},Zte=P({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=Me(`RouterLink`);return L(),q(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-md 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:I(()=>[A(V(Ml),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),R(`span`,Xte,B(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),Qte={class:`font-mono text-foreground`},$te={key:0,class:`shrink-0 text-xs tabular-nums`},ene={class:`font-mono text-foreground`},tne={key:0,class:`shrink-0 text-xs tabular-nums`},cw=P({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=Y(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=Y(()=>t.tool.parameters||t.tool.Parameters||``),i=Y(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=Y(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||``),o=Y(()=>!a.value&&!i.value&&!!t.streaming),s=Y(()=>{let e=t.tool.duration_ms;return e?e<1e3?`${e}ms`:`${(e/1e3).toFixed(+(e<1e4))}s`:``}),c=Y(()=>{try{let e=JSON.parse(r.value);if(e&&typeof e==`object`&&!Array.isArray(e)){let t=Object.values(e).find(e=>typeof e==`string`&&e);return typeof t==`string`?t.split(`
`)+1;if(o>r.text.length){let e=a.highlight(i.slice(r.text.length,o-1),r.state);r={highlighter:a,text:i.slice(0,o),lines:[...r.lines,...e.lines],state:e.state}}let s=a.highlight(i.slice(o),r.state).lines[0]??[];return[...r.lines,s]})}var jC=qe(`rounded-lg text-sm data-[size=sm]:text-xs has-[>[data-slot=code-block-content]:focus-visible]:ring-3 has-[>[data-slot=code-block-content]:focus-visible]:ring-ring/50 group/code-block relative flex w-full min-w-0 flex-col overflow-hidden`,{variants:{variant:{default:`border border-input text-foreground dark:bg-input/30 has-[>[data-slot=code-block-content]:focus-visible]:border-ring`,destructive:`border border-destructive/30 text-destructive dark:border-destructive/40`}},defaultVariants:{variant:`default`}}),MC=qe(`-mx-3 px-3 in-data-numbered:gap-x-3 before:min-w-6 before:text-end before:text-muted-foreground after:start-1 after:text-muted-foreground group-data-[size=sm]/code-block:-mx-2.5 group-data-[size=sm]/code-block:px-2.5 relative block min-h-lh after:absolute after:top-0 after:select-none in-data-numbered:col-span-2 in-data-numbered:grid in-data-numbered:grid-cols-subgrid in-data-numbered:[counter-increment:line] in-data-numbered:before:content-[counter(line)] in-data-numbered:before:select-none in-data-numbered:supports-[content:counter(line)_/_'']:before:content-[counter(line)_/_'']`,{variants:{variant:{default:``,added:`bg-muted after:content-['+']`,removed:`bg-destructive/10 after:text-destructive after:content-['−']`,highlighted:`bg-muted`}},defaultVariants:{variant:`default`}}),NC=P({__name:`Message`,props:{class:{type:[Boolean,null,String,Object,Array]},align:{default:`start`},asChild:{type:Boolean},as:{default:`div`}},setup(e){let t=e;return(n,r)=>(L(),q(V(dt),{"data-slot":`message`,"data-align":e.align,as:e.as,"as-child":e.asChild,class:z(V(W)(`text-sm gap-2 group/message relative flex w-full min-w-0 data-[align=end]:flex-row-reverse`,t.class))},{default:I(()=>[K(n.$slots,`default`)]),_:3},8,[`data-align`,`as`,`as-child`,`class`]))}}),PC=P({__name:`MessageContent`,props:{class:{type:[Boolean,null,String,Object,Array]},asChild:{type:Boolean},as:{default:`div`}},setup(e){let t=e;return(n,r)=>(L(),q(V(dt),{"data-slot":`message-content`,as:e.as,"as-child":e.asChild,class:z(V(W)(`gap-2.5 group-data-[align=end]/message:*:data-slot:self-end flex w-full min-w-0 flex-col wrap-break-word`,t.class))},{default:I(()=>[K(n.$slots,`default`)]),_:3},8,[`as`,`as-child`,`class`]))}}),FC=P({__name:`MessageFooter`,props:{class:{type:[Boolean,null,String,Object,Array]},asChild:{type:Boolean},as:{default:`div`}},setup(e){let t=e;return(n,r)=>(L(),q(V(dt),{"data-slot":`message-footer`,as:e.as,"as-child":e.asChild,class:z(V(W)(`text-xs font-medium text-muted-foreground px-3 group-has-data-[variant=ghost]/message:px-0 flex max-w-full min-w-0 items-center group-data-[align=end]/message:justify-end`,t.class))},{default:I(()=>[K(n.$slots,`default`)]),_:3},8,[`as`,`as-child`,`class`]))}});function IC(e){switch(e.type){case`image`:return`[photo]`;case`video`:return`[video]`;case`audio`:return`[audio]`;case`document`:return e.file_name?`[document: ${e.file_name}]`:`[document]`;default:return`[${e.type||`attachment`}]`}}function LC(e){let t=[];return e.mime_type&&t.push(e.mime_type),e.file_name&&t.push(e.file_name),e.file_size!==void 0&&t.push(`${e.file_size} bytes`),e.width&&e.height&&t.push(`${e.width}×${e.height}`),e.duration!==void 0&&t.push(`${e.duration} s`),t.join(` · `)}var RC={class:`truncate`},zC=P({__name:`ChatAttachment`,props:{attachment:{}},setup(e){return(t,n)=>(L(),q(_e(e.attachment.url?`a`:`span`),{href:e.attachment.url,target:e.attachment.url?`_blank`:void 0,rel:e.attachment.url?`noopener noreferrer`:void 0,title:V(LC)(e.attachment),class:`inline-flex max-w-full items-center gap-1.5 rounded-md border border-border bg-muted px-2.5 py-1 text-xs font-medium text-fg-muted`},{default:I(()=>[A(V(pte),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),R(`span`,RC,B(V(IC)(e.attachment)),1)]),_:1},8,[`href`,`target`,`rel`,`title`]))}}),BC=P({__name:`CodeView`,props:{code:{},lang:{},class:{}},setup(e){let t=e,n=AC(()=>t.code,()=>t.lang||`text`);return(r,i)=>(L(),q(V(mm),{class:z(V(W)(`bg-muted`,t.class))},{default:I(()=>[A(V(hm),null,{default:I(()=>[A(V(xm),{value:e.code},null,8,[`value`])]),_:1}),A(V(ym),{wrap:``,class:`max-h-[60vh] pe-10 text-xs`},{default:I(()=>[(L(!0),j(U,null,M(V(n),(e,t)=>(L(),q(V(vm),{key:t},{default:I(()=>[(L(!0),j(U,null,M(e,(e,t)=>(L(),q(V(Sm),{key:t,token:e},null,8,[`token`]))),128))]),_:2},1024))),128))]),_:1})]),_:1},8,[`class`]))}}),VC=[`src`,`alt`],HC={key:1},UC={key:2},WC={key:3,class:`rounded bg-foreground/10 px-1 py-0.5 font-mono text-[0.9em]`},GC=[`href`],KC={key:5},qC=P({__name:`ChatInline`,props:{inline:{}},setup(e){return(t,n)=>(L(!0),j(U,null,M(e.inline,(e,t)=>(L(),j(U,{key:t},[e.kind===`image`?(L(),j(`img`,{key:0,src:e.src,alt:e.alt,loading:`lazy`,class:`my-1 block max-h-96 max-w-full cursor-pointer rounded-md border border-border bgLine truncated
`),r=[],i=null,a=null,o=``,s=()=>{r.length&&(t.push({kind:`p`,inline:YC(r.join(` `))}),r=[])},c=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>YC(e))}),null)};for(let e=0;e<n.length;e++){let l=n[e];if(l.startsWith("```")){s(),c(),a?(t.push({kind:`pre`,code:a.join(`
`),lang:o}),a=null):(a=[],o=l.slice(3).trim().split(/\s/)[0]);continue}if(a){a.push(l);continue}let u=ZC(l),d=e+1<n.length?ZC(n[e+1]):null;if(u&&d&&QC(d)&&u.length===d.length){s(),c();let r=[];for(e+=2;e<n.length;e++){let t=ZC(n[e]);if(!t||t.length!==u.length){e--;break}r.push(t)}t.push({kind:`table`,head:u.map(e=>YC(e)),rows:r.map(e=>e.map(e=>YC(e)))});continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),t.push({kind:`h${f[1].length}`,inline:YC(f[2])});continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let e=m?`ol`:`ul`;(!i||i.tag!==e)&&(c(),i={tag:e,items:[]}),i.items.push((p||m)[1])}else l.startsWith(`>`)?(s(),c(),t.push({kind:`blockquote`,inline:YC(l.replace(/^>\s?/,``))})):r.push(l)}return s(),c(),a&&t.push({kind:`pre`,code:a.join(`
`),lang:o}),t}function ZC(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 QC(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var $C={class:`[overflow-wrap:anywhere]`},ew={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},tw={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},nw={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},rw={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},iw={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},aw={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},ow={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},Jte={key:8,class:`mb-2.5 last:mb-0`},sw=P({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=Y(()=>XC(t.text));return(e,t)=>(L(),j(`div`,$C,[(L(!0),j(U,null,M(n.value,(e,t)=>(L(),j(U,{key:t},[e.kind===`pre`?(L(),q(BC,{key:0,code:e.code,lang:e.lang,class:`my-2`},null,8,[`code`,`lang`])):e.kind===`table`?(L(),j(`table`,ew,[R(`thead`,null,[R(`tr`,null,[(L(!0),j(U,null,M(e.head,(e,t)=>(L(),j(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[A(qC,{inline:e},null,8,[`inline`])]))),128))])]),R(`tbody`,null,[(L(!0),j(U,null,M(e.rows,(e,t)=>(L(),j(`tr`,{key:t},[(L(!0),j(U,null,M(e,(e,t)=>(L(),j(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[A(qC,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(L(),j(`blockquote`,tw,[A(qC,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(L(),j(`h1`,nw,[A(qC,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(L(),j(`h2`,rw,[A(qC,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(L(),j(`h3`,iw,[A(qC,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(L(),j(`ul`,aw,[(L(!0),j(U,null,M(e.items,(e,t)=>(L(),j(`li`,{key:t},[A(qC,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(L(),j(`ol`,ow,[(L(!0),j(U,null,M(e.items,(e,t)=>(L(),j(`li`,{key:t},[A(qC,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(L(),j(`p`,Jte,[A(qC,{inline:e.inline},null,8,[`inline`])])):F(``,!0)],64))),128))]))}}),Yte={class:`truncate`},Xte=P({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=Me(`RouterLink`);return L(),q(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-md 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:I(()=>[A(V(jl),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),R(`span`,Yte,B(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),Zte={class:`font-mono text-foreground`},Qte={key:0,class:`shrink-0 text-xs tabular-nums`},$te={class:`font-mono text-foreground`},ene={key:0,class:`shrink-0 text-xs tabular-nums`},cw=P({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=Y(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=Y(()=>t.tool.parameters||t.tool.Parameters||``),i=Y(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=Y(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||``),o=Y(()=>!a.value&&!i.value&&!!t.streaming),s=Y(()=>{let e=t.tool.duration_ms;return e?e<1e3?`${e}ms`:`${(e/1e3).toFixed(+(e<1e4))}s`:``}),c=Y(()=>{try{let e=JSON.parse(r.value);if(e&&typeof e==`object`&&!Array.isArray(e)){let t=Object.values(e).find(e=>typeof e==`string`&&e);return typeof t==`string`?t.split(`
`,1)[0]:Object.entries(e).map(([e,t])=>`${e}: ${typeof t==`object`?JSON.stringify(t):t}`).join(`, `)}}catch{}return r.value.split(`
`,1)[0]}),l=Y(()=>[r.value&&`> ${r.value}`,a.value].filter(Boolean).join(`
`));return(t,r)=>e.tool.path?(L(),q(Zte,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):l.value?(L(),q(V(cm),{key:1,"default-open":i.value},{default:I(()=>[A(V(dm),null,{default:I(()=>[A(V(pm),{status:i.value?`error`:o.value?`running`:void 0},{default:I(()=>[A(V(um),null,{default:I(()=>[i.value?(L(),q(V(Jl),{key:0})):o.value?(L(),q(V(gu),{key:1,class:`animate-spin`})):(L(),q(V(Wl),{key:2,class:`text-success`}))]),_:1}),R(`span`,Qte,B(n.value),1),A(V(mm),{class:`font-mono text-xs`},{default:I(()=>[H(B(c.value),1)]),_:1}),s.value?(L(),j(`span`,$te,B(s.value),1)):F(``,!0)]),_:1},8,[`status`])]),_:1}),A(V(lm),null,{default:I(()=>[A(V(gm),{size:`sm`},{default:I(()=>[A(V(xm),{wrap:``,class:`max-h-64`},{default:I(()=>[H(B(l.value),1)]),_:1})]),_:1})]),_:1})]),_:1},8,[`default-open`])):(L(),q(V(pm),{key:2,status:i.value?`error`:o.value?`running`:void 0},{default:I(()=>[A(V(um),null,{default:I(()=>[i.value?(L(),q(V(Jl),{key:0})):o.value?(L(),q(V(gu),{key:1,class:`animate-spin`})):(L(),q(V(Wl),{key:2,class:`text-success`}))]),_:1}),R(`span`,ene,B(n.value),1),A(V(mm),{class:`font-mono text-xs`},{default:I(()=>[H(B(c.value),1)]),_:1}),s.value?(L(),j(`span`,tne,B(s.value),1)):F(``,!0)]),_:1},8,[`status`]))}}),nne={class:`flex flex-col gap-1.5`},rne=P({__name:`ChatToolGroup`,props:{tools:{},streaming:{type:Boolean}},setup(e){let t=e,n=e=>!!(e.err||e.Err||e.failed),r=Y(()=>t.tools.some(n)),i=Y(()=>`${t.tools.length} tool call${t.tools.length===1?``:`s`}`);return(t,n)=>(L(),q(V(cm),{"default-open":r.value},{default:I(()=>[A(V(dm),null,{default:I(()=>[A(V(pm),{status:r.value?`error`:void 0},{default:I(()=>[A(V(um),null,{default:I(()=>[A(V(Dte))]),_:1}),A(V(mm),{class:`truncate`},{default:I(()=>[H(B(i.value),1)]),_:1})]),_:1},8,[`status`])]),_:1}),A(V(lm),null,{default:I(()=>[R(`div`,nne,[(L(!0),j(U,null,M(e.tools,(t,n)=>(L(),q(cw,{key:n,tool:t,streaming:e.streaming&&n===e.tools.length-1},null,8,[`tool`,`streaming`]))),128))])]),_:1})]),_:1},8,[`default-open`]))}}),ine={key:0,class:`mb-2 flex flex-wrap gap-1.5`},ane={key:2,class:`whitespace-pre-wrap`},one=P({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},media:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){let t=e,n=Y(()=>{let e=Array.from(t.text),n=[],r=0,i=!1;for(let a of t.tools){let t=Math.min(Math.max(a.text_offset??0,r),e.length);t>r&&(n.push({text:e.slice(r,t).join(``)}),r=t,i=!1);let o=n[n.length-1];!a.path&&i&&o&&`tools`in o?o.tools.push(a):(n.push({tools:[a]}),i=!a.path)}return r<e.length&&n.push({text:e.slice(r).join(``)}),n});return(t,r)=>(L(),q(V(PC),{align:e.assistant?`start`:`end`},{default:I(()=>[A(V(FC),null,{default:I(()=>[A(V(tm),{variant:e.assistant?`muted`:`tinted`,class:`max-w-[min(78ch,92%)]`},{default:I(()=>[A(V(nm),{class:`[overflow-wrap:anywhere]`},{default:I(()=>[e.media.length?(L(),j(`div`,ine,[(L(!0),j(U,null,M(e.media,(e,t)=>(L(),q(BC,{key:t,attachment:e},null,8,[`attachment`]))),128))])):F(``,!0),e.assistant?(L(!0),j(U,{key:1},M(n.value,(t,r)=>(L(),j(U,{key:r},[`text`in t?(L(),q(sw,{key:0,text:t.text},null,8,[`text`])):(L(),q(V(im),{key:1,class:`my-2`},{default:I(()=>[t.tools.length>1?(L(),q(rne,{key:0,tools:t.tools,streaming:e.streaming&&r===n.value.length-1},null,8,[`tools`,`streaming`])):(L(),q(cw,{key:1,tool:t.tools[0],streaming:e.streaming&&r===n.value.length-1},null,8,[`tool`,`streaming`]))]),_:2},1024))],64))),128)):(L(),j(`div`,ane,B(e.text),1)),K(t.$slots,`default`)]),_:3})]),_:3},8,[`variant`]),e.assistant&&!e.streaming&&e.text?(L(),q(V(IC),{key:0,class:`px-0 transition-opacity focus-within:opacity-100 [@media(hover:hover)]:opacity-0 [@media(hover:hover)]:group-hover/message:opacity-100`},{default:I(()=>[A(V(Cm),{value:e.text},null,8,[`value`])]),_:1})):F(``,!0)]),_:3})]),_:3},8,[`align`]))}}),sne={class:`text-sm`},cne={key:0,class:`mt-1 text-fg-muted`},lne={key:1,class:`mt-2 flex flex-wrap gap-2`},une=P({__name:`ChatChooseCard`,props:{choose:{}},setup(e){let t=Y(()=>ad.value.models??[]);return(e,n)=>(L(),j(`div`,sne,[n[0]||=R(`p`,{class:`font-medium`},`Choose a model`,-1),t.value.length?(L(),j(`div`,lne,[(L(!0),j(U,null,M(t.value,e=>(L(),q(V(X),{key:e,size:`sm`,variant:e===V(ad).active_model?`default`:`outline`,class:`font-mono`,onClick:t=>void V(yd)(e)},{default:I(()=>[H(B(e),1)]),_:2},1032,[`variant`,`onClick`]))),128))])):(L(),j(`p`,cne,`None configured.`))]))}}),dne={class:`text-sm`},fne={key:0},pne={class:`mt-1 space-y-0.5`},mne={class:`font-mono`},hne=[`href`],gne={key:0,class:`mt-3 flex gap-2`},_ne={key:1,class:`mt-2 text-fg-muted`},vne={key:2,class:`mt-2 text-fg-muted`},yne={key:3,class:`mt-2 text-ok`},bne={key:4,class:`mt-2 text-danger`},xne={key:5,class:`mt-2 text-xs text-fg-muted`},Sne=P({__name:`ChatUpdateCard`,props:{update:{}},setup(e){let t=e,n=Y(()=>t.update.available??[]),r=J(`idle`),i=J(``);async function a(){r.value=`installing`;try{let e=(await Z.updateInstall(t.update.snapshot)).result?.installed;i.value=e?Object.entries(e).map( Line truncated
`).map(e=>e.trim()).find(Boolean)||``,i=r.length>FT?`${r.slice(0,FT).trimEnd()}…`:r;return{text:i,full:n,truncated:i!==n}}function vie(e){return String(e||`event`).replaceAll(`_`,` `).replace(/\b\w/g,e=>e.toUpperCase())}function LT(e){let t=Number(e);if(!Number.isFinite(t)||t<0)return``;if(t<1e3)return`under 1 s`;let n=t/1e3;if(n<60)return`${n.toFixed(+(n<10))} s`;let r=Math.round(n),i=Math.floor(r/60),a=r%60;if(i<60)return a===0?`${i} min`:`${i} min ${a} s`;let o=Math.floor(i/60),s=i-o*60;return s===0?`${o} h`:`${o} h ${s} min`}function RT(e){let t=Number(e);return!Number.isFinite(t)||t<=0?``:t.toLocaleString(`en-US`)}function zT(e){return typeof e==`string`?e:``}function BT(e={}){let t=e.data||{},n=e.stage||`unknown stage`,r=e.workflow?`${e.workflow} workflow`:``;if(e.kind===`stage_start`)return{title:`Started stage: ${n}`,detail:r};if(e.kind===`stage_finish`){let e=[r,LT(t.duration_ms)].filter(Boolean).join(` · `);return{title:t.interrupted?`Stage interrupted: ${n}`:t.skipped?`Skipped stage: ${n}`:t.error?`Stage failed: ${n}`:`Finished stage: ${n}`,detail:[e,zT(t.error),zT(t.when)].filter(Boolean).join(` · `)}}if(e.kind===`task_retried`){let n=Number(t.retry_count);return{title:Number.isFinite(n)&&n>0?`Retry ${n}`:`Retry requested`,detail:[zT(t.previous_stage)&&`after ${zT(t.previous_stage)}`,zT(t.previous_reason)].filter(Boolean).join(`: `)||e.detail||``}}if(e.kind===`agent_finish`){let r=RT(t.iterations),i=RT(t.tokens),a=Number(t.cached_tokens)||0,o=RT((Number(t.prompt_tokens)||0)-a),s=RT(t.completion_tokens),c=RT(t.cached_tokens),l=[r&&`${r} iterations`,i&&`${i} tokens`,o&&`${o} fresh prompt`,s&&`${s} completion`,c&&`${c} cached`,zT(t.model)].filter(Boolean);return{title:`Agent ${zT(t.status)||`finished`}: ${n}`,detail:l.join(` · `)||e.detail||``}}if(e.kind===`remediation_round`){let e=Number(t.of),n=zT(t.author);return{title:`Remediation ${zT(t.round)}${e>0?` of ${e}`:``}`,detail:[n&&`answers ${n}'s review`,t.review_id?`#${zT(t.review_id)}`:``].filter(Boolean).join(` `)}}if(e.kind===`review_approved`){let e=zT(t.pr_number);return{title:`Pull request approved`,detail:[zT(t.author),e&&`#${e}`].filter(Boolean).join(` · `)}}if(e.kind===`step_retried`)return{title:`Attempt ${zT(t.attempt)} of ${zT(t.of)} failed: ${e.stage||`step`}`,detail:zT(t.error),tone:`warn`};if(e.kind===`config_captured`)return{title:`Configuration captured`,detail:`The effective task-runtime configuration for this run.`};if(e.kind===`binding_started`){let e=zT(t.source),n=zT(t.capture_id),r=[{label:`binding ${zT(t.binding_name)||zT(t.binding_id)}`,to:`/events?tab=bindings`},...n?[{label:`captured event`,to:`/events?tab=inspector&capture=${encodeURIComponent(n)}`}]:[]];return t.unsigned===!0?{title:`Started by an unsigned event`,detail:e?`source ${e}`:``,tone:`warn`,links:r}:{title:`Started by an event`,detail:e?`source ${e}`:``,links:r}}if(e.kind===`changes_captured`){let e=t.totals??{},n=Number(e.files);return{title:`Change capture recorded`,detail:[Number.isFinite(n)&&n>0?`${n} file${n===1?``:`s`} changed`:``,t.captured_after?`captured after ${zT(t.captured_after)}`:``].filter(Boolean).join(` · `)}}return{title:vie(e.kind||e.type),detail:e.detail||``}}var yie=[`title`],VT=P({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=PT();n.watchIdentities();let r=e,i=t,a=ST(),o=Y(()=>a.taskIDFor(r.event)),s=Y(()=>IT(r.event,n.identityName));function c(){o.value>0&&i(`open`,o.value)}return(t,n)=>(L(),q(V(AT),{class:z(o.value>0?`cursor-pointer`:``),role:o.value>0?`link`:void 0,tabindex:o.value>0?0:void 0,title:o.value>0?`Open task details`:void 0,onClick:c,onKeydown:[gt(pt(c,[`prevent`]),[`enter`]),gt(pt(c,[`prevent`]),[`space`])]},{default:I(()=>[A(V(kT),{class:`font-medium`},{default:I(()=>[H(B(V(BT)({...r.event,at:void 0,detail:void 0}).title),1)]),_:1}),A(V(kT),{class:`font-mono`},{default:I(()=>[H(B(o.value>0?`#${o.value}`:`–`),1)]),_:1}),A(V(kT),{class:`w-[55%] max-w-0`},{default:I(()=>[R(`span`,{class:`block truncate`,title:s.value.truncated?s.value.full:void 0},B(s.value.text),9,yie)]),_:1}),A(V(kT),null,{default:I(()=>[A(V(fw),{at:e.event.at},null,8,[`at`])]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}}),bie=[{value:`all`,label:`All`},{value:`tasks`,label:`Tasks`},{value:`system`,label:`System`}];function HT(e){return(Number(e?.task_id)||0)>0}function xie(e,t){return t===`tasks`?HT(e):t!==`system`||!HT(e)}function Sie(e,t){return e.filter(e=>xie(e,t))}function Cie(e,t){return e>0?``:t===`all`?`Waiting for activity`:t===`tasks`?`No task events yet`:`No system events yet`}function wie(e,t){return`${e}:${t??0}`}function Tie(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=wie(IT(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 Eie={role:`region`,"aria-label":`Activity`,"aria-live":`polite`},Die={class:`max-h-[28rem] overflow-y-auto`},Oie={clas Line truncated
`,1)[0]??``;return t.length>80?`${t.slice(0,79)}…`:t}function JE(e){return(e?.merged||0)+(e?.completed||0)}function YE(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 XE(e,t){return e.filter(e=>e.required&&!(t[e.name]??``).trim()).map(e=>e.name)}function ZE(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 QE(e,t){let n={};for(let r of e){let e=t[r.name];e!==void 0&&e!==``&&(n[r.name]=ZE(e,r.type))}return n}var $E=[`onKeydown`],eD={key:0,class:`text-sm text-danger`,role:`alert`},tD={key:1,class:`grid gap-1.5`},nD=[`for`],rD={key:0,class:`font-normal text-fg-subtle`},iD=[`id`],aD=[`value`],oD={key:0,class:`text-xs text-fg-subtle`},sD={key:2,class:`grid gap-1.5`},cD=[`id`],lD={class:`block truncate text-label font-medium`},uD={class:`block text-xs text-fg-subtle`},dD={key:0,class:`text-xs text-fg-subtle`},fD={key:3,class:`grid gap-3`},pD=[`for`],mD={class:`font-mono`},hD={key:0,class:`text-fg-subtle`},gD={class:`grid gap-1.5`},_D=[`for`],vD={class:`grid gap-1.5`},yD=[`for`],bD={key:4,class:`text-sm text-danger`,role:`alert`},xD={class:`flex items-center gap-2 border-t border-border pt-4`},SD={class:`mr-auto text-xs text-fg-subtle`},CD=P({__name:`NewTaskForm`,props:{workflow:{},draft:{},initialWorkflow:{},initialInstructions:{}},emits:[`started`,`cancel`],setup(e,{emit:t}){let n=e,r=t,i=we(),a=J([]),o=J([]),s=J([]),c=J(``);Be(async()=>{try{let[e,t]=await Promise.all([Z.workflows(),Z.repositories()]);a.value=(e?.definitions??[]).filter(e=>e.enabled),o.value=e?.workflows??[],s.value=(t??[]).map(e=>`${e.owner}/${e.name}`)}catch(e){c.value=String(e.message||e)}});let l=J(``),u=J(n.workflow??n.initialWorkflow??``),d=J(n.initialInstructions??``),f=J(qE(d.value)),p=J({});Ce(()=>{!u.value&&a.value[0]&&(u.value=a.value[0].id)});let m=Y(()=>a.value.find(e=>e.id===u.value)),h=Y(()=>YE(m.value)),g=Y(()=>XE(h.value,p.value)),_=Y(()=>m.value?.repository??`required`),v=Y(()=>_.value!==`optional`&&_.value!==`none`),y=e=>o.value.find(t=>t.workflow===e),b=J(!1),x=J(``),S=Y(()=>!(!l.value.trim()&&v.value||!u.value||!f.value.trim())&&g.value.length===0);async function C(){if(S.value&&!b.value){b.value=!0,x.value=``;try{let e=await Z.workRequest({repository:_.value===`none`?``:l.value.trim(),workflow:u.value,title:f.value.trim(),instructions:d.value,inputs:QE(h.value,p.value),...n.draft?{draft:n.draft}:{}});r(`started`,e.task_id)}catch(e){x.value=String(e.message||e)}finally{b.value=!1}}}return(e,t)=>(L(),j(`form`,{class:`grid gap-5`,onSubmit:pt(C,[`prevent`]),onKeydown:[gt(pt(C,[`meta`,`prevent`]),[`enter`]),gt(pt(C,[`ctrl`,`prevent`]),[`enter`])]},[c.value?(L(),j(`p`,eD,B(c.value),1)):F(``,!0),_.value===`none`?F(``,!0):(L(),j(`div`,tD,[R(`label`,{for:`${V(i)}-repo`,class:`text-label font-medium`},[t[5]||=H(`Repository`,-1),v.value?F(``,!0):(L(),j(`span`,rD,` (optional)`))],8,nD),A(V(Q),{id:`${V(i)}-repo`,modelValue:l.value,"onUpdate:modelValue":t[0]||=e=>l.value=e,class:`font-mono`,placeholder:`owner/repository`,list:`${V(i)}-repos`,required:v.value},null,8,[`id`,`modelValue`,`list`,`required`]),R(`datalist`,{id:`${V(i)}-repos`},[(L(!0),j(U,null,M(s.value,e=>(L(),j(`option`,{key:e,value:e},null,8,aD))),128))],8,iD),s.value.length?(L(),j(`p`,oD,[t[6]||=H(`Configured: `,-1),(L(!0),j(U,null,M(s.value,e=>(L(),q(V(X),{key:e,type:`button`,variant:`link`,size:`xs`,class:`h-auto px-1 font-mono text-fg-subtle`,onClick:t=>l.value=e},{default:I(()=>[H(B(e),1)]),_:2},1032,[`onClick`]))),128))])):F(``,!0)])),n.workflow?F(``,!0):(L(),j(`div`,sD,[R(`span`,{id:`${V(i)}-wf`,class:`text-label font-medium`},`Workflow`,8,cD),A(V(Fs),{modelValue:u.value,"onUpdate:modelValue":t[1]||=e=>u.value=e,"aria-labelledby":`${V(i)}-wf`,class:`grid grid-cols-1 gap-2 sm:grid-cols-3`,loop:``},{default:I(()=>[(L(!0),j(U,null,M(a.value,e=>(L(),q(V(Ls),{key:e.id,value:e.id,class:`rounded-md border border-border bg-card px-3 py-2.5 text-left transition-colors hover:bg-secondary focus-visible:outline-2 focus-visible:outline-ring data-[state=checked]:border-primary data-[state=checked]:bg-secondary`},{default:I(()=>[R(`span`,lD,B(e.name||e.id),1),R(`span`,uD,[H(B(y(e.id)?.runs||0)+` runs`,1),y(e.id)?.runs?(L(),j(U,{key:0},[H(` · `+B(Math.round(V(JE)(y(e.id))/(y(e.id)?.runs||1)*100))+`% delivered`,1)],64)):F(``,!0)])]),_:2},1032,[`value`]))),128))]),_:1},8,[`modelValue`,`aria-labelledby`]),!a.value.length&&!c.value?(L(),j(`p`,dD,`No enabled workflows.`)):F(``,!0)])),h.value.length?(L(),j(`div`,fD,[(L(!0),j(U,null,M(h.value,e=>(L(),j(`div`,{key:e.name,class:`grid gap-1.5`},[R(`label`,{for:`${V(i)}-input-${e.name}`,class:`text-label font-medium`},[R(`span`,mD,B(e.name),1),e.required?(L(),j(`span`,hD,` · required`)):F(``,!0)],8,pD),A(V(Q),{id:`${V(i)}-input-${e.name}`,"model-value":p.value[e.name 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 zD(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 BD(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 VD(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 HD(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 UD=J([]),WD=J([]),GD=J(!0),KD=J(null),qD=J(!0),JD=J(null),YD=J(!1),XD=J(null);async function ZD(){try{let e=await Z.eventTypes(LD().workspace);GD.value=e.enabled!==!1,UD.value=e.event_types||[],WD.value=e.proposals||[],KD.value=null}catch(e){KD.value=e.message||String(e)}finally{qD.value=!1}}function QD(e){return{headers:(e.headers||[]).map(e=>({...e})),payload:(e.payload||[]).map(e=>({...e}))}}function $D(e){XD.value=null,JD.value=e}function eO(e){let t=cO.value.find(t=>String(t.id)===e.sample_id);$D({mode:`proposal`,id:null,source:e.source,name:``,rule:QD(e.rule),headersText:``,body:t?.body||``,exampleHeaders:e.headers||{}})}function tO(e=``){$D({mode:`paste`,id:null,source:e,name:``,rule:{headers:[],payload:[]},headersText:``,body:``,exampleHeaders:{}})}function nO(e){$D({mode:`edit`,id:e.id,source:e.source,name:e.name,rule:QD(e.rule),headersText:``,body:``,exampleHeaders:{}})}function rO(){JD.value=null}async function iO(){let e=JD.value;if(e){YD.value=!0;try{if(e.mode===`edit`&&e.id)await Z.eventTypeUpdate(e.id,{name:e.name,rule:HD(e.rule)});else{let t=e.mode===`paste`?RD(e.headersText):e.exampleHeaders;await Z.eventTypeCreate({source:e.source,name:e.name,rule:e.mode===`paste`?void 0:HD(e.rule),example:{headers:t,body:e.body}})}JD.value=null,await ZD()}catch(e){XD.value=e.message||String(e)}finally{YD.value=!1}}}var aO=J(null);async function oO(){let e=aO.value;if(aO.value=null,e)try{await Z.eventTypeDelete(e.id),await ZD()}catch(e){KD.value=e.message||String(e)}}var sO=100,cO=J([]),lO=J(!0),uO=J(null),dO=J(!0),fO=J(null);async function pO(){try{let e=await Z.captures(sO);lO.value=e.enabled!==!1,cO.value=e.captures||[],uO.value=null}catch(e){uO.value=e.message||String(e)}finally{dO.value=!1}}function mO(e){let t=cO.value.find(t=>t.id===e);return t&&(fO.value=t),!!t}function hO(){cO.value.length&&(fO.value=cO.value[0])}function gO(){Zf(`captures`,()=>{pO(),ZD()})}var _O=P({__name:`Tabs`,props:{defaultValue:{},orientation:{},dir:{},activationMode:{},modelValue:{},unmountOnHide:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},emits:[`update:modelValue`],setup(e,{emit:t}){let n=e,r=t,i=ct(n,`class`),a=w(i,r);return(e,t)=>(L(),q(V(Ac),G({"data-slot":`tabs`,"data-orientation":V(a).orientation||`horizontal`},V(a),{class:V(W)(`gap-2 group/tabs flex data-horizontal:flex-col`,n.class)}),{default:I(t=>[K(e.$slots,`default`,Je(be(t)))]),_:3},16,[`data-orientation`,`class`]))}}),vO=P({__name:`TabsContent`,props:{value:{},forceMount:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=ct(t,`class`);return(e,r)=>(L(),q(V(Nc),G({"data-slot":`tabs-content`,class:V(W)(`text-sm flex-1 outline-none`,t.class)},V(n)),{default:I(()=>[K(e.$slots,`default`)]),_:3},16,[`class`]))}}),yO=P({__name:`TabsList`,props:{loop:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]},variant:{default:`default`}},setup(e){let t=e,n=ct(t,`class`,`variant`);return(r,i)=>(L(),q(V(Pc),G({"data-slot":`tabs-list`,"data-variant":e.variant},V(n),{class:V(W)(V(xO)({variant:e.variant}),t.class)}),{default:I(()=>[K(r.$slots,`default`)]),_:3},16,[`data-variant`,`class`]))}}),bO=P({__name:`TabsTrigger`,props:{value:{},disabled:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=ct(t,`class`),r=C(n);return(e,n)=>(L(),q(V(Fc),G({"data-slot":`tabs-trigger`,class:V(W)(`gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg:not([class*=size-])]:size-4 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:oLine truncated
`));return(t,r)=>e.tool.path?(L(),q(Xte,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):l.value?(L(),q(V(om),{key:1,"default-open":i.value},{default:I(()=>[A(V(lm),null,{default:I(()=>[A(V(dm),{status:i.value?`error`:o.value?`running`:void 0},{default:I(()=>[A(V(cm),null,{default:I(()=>[i.value?(L(),q(V(Kl),{key:0})):o.value?(L(),q(V(mu),{key:1,class:`animate-spin`})):(L(),q(V(Hl),{key:2,class:`text-success`}))]),_:1}),R(`span`,Zte,B(n.value),1),A(V(fm),{class:`font-mono text-xs`},{default:I(()=>[H(B(c.value),1)]),_:1}),s.value?(L(),j(`span`,Qte,B(s.value),1)):F(``,!0)]),_:1},8,[`status`])]),_:1}),A(V(sm),null,{default:I(()=>[A(V(mm),{size:`sm`},{default:I(()=>[A(V(ym),{wrap:``,class:`max-h-64`},{default:I(()=>[H(B(l.value),1)]),_:1})]),_:1})]),_:1})]),_:1},8,[`default-open`])):(L(),q(V(dm),{key:2,status:i.value?`error`:o.value?`running`:void 0},{default:I(()=>[A(V(cm),null,{default:I(()=>[i.value?(L(),q(V(Kl),{key:0})):o.value?(L(),q(V(mu),{key:1,class:`animate-spin`})):(L(),q(V(Hl),{key:2,class:`text-success`}))]),_:1}),R(`span`,$te,B(n.value),1),A(V(fm),{class:`font-mono text-xs`},{default:I(()=>[H(B(c.value),1)]),_:1}),s.value?(L(),j(`span`,ene,B(s.value),1)):F(``,!0)]),_:1},8,[`status`]))}}),tne={class:`flex flex-col gap-1.5`},nne=P({__name:`ChatToolGroup`,props:{tools:{},streaming:{type:Boolean}},setup(e){let t=e,n=e=>!!(e.err||e.Err||e.failed),r=Y(()=>t.tools.some(n)),i=Y(()=>`${t.tools.length} tool call${t.tools.length===1?``:`s`}`);return(t,n)=>(L(),q(V(om),{"default-open":r.value},{default:I(()=>[A(V(lm),null,{default:I(()=>[A(V(dm),{status:r.value?`error`:void 0},{default:I(()=>[A(V(cm),null,{default:I(()=>[A(V(Dte))]),_:1}),A(V(fm),{class:`truncate`},{default:I(()=>[H(B(i.value),1)]),_:1})]),_:1},8,[`status`])]),_:1}),A(V(sm),null,{default:I(()=>[R(`div`,tne,[(L(!0),j(U,null,M(e.tools,(t,n)=>(L(),q(cw,{key:n,tool:t,streaming:e.streaming&&n===e.tools.length-1},null,8,[`tool`,`streaming`]))),128))])]),_:1})]),_:1},8,[`default-open`]))}}),rne={key:0,class:`mb-2 flex flex-wrap gap-1.5`},ine={key:2,class:`whitespace-pre-wrap`},ane=P({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},media:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){let t=e,n=Y(()=>{let e=Array.from(t.text),n=[],r=0,i=!1;for(let a of t.tools){let t=Math.min(Math.max(a.text_offset??0,r),e.length);t>r&&(n.push({text:e.slice(r,t).join(``)}),r=t,i=!1);let o=n[n.length-1];!a.path&&i&&o&&`tools`in o?o.tools.push(a):(n.push({tools:[a]}),i=!a.path)}return r<e.length&&n.push({text:e.slice(r).join(``)}),n});return(t,r)=>(L(),q(V(NC),{align:e.assistant?`start`:`end`},{default:I(()=>[A(V(PC),null,{default:I(()=>[A(V($p),{variant:e.assistant?`muted`:`tinted`,class:`max-w-[min(78ch,92%)]`},{default:I(()=>[A(V(em),{class:`[overflow-wrap:anywhere]`},{default:I(()=>[e.media.length?(L(),j(`div`,rne,[(L(!0),j(U,null,M(e.media,(e,t)=>(L(),q(zC,{key:t,attachment:e},null,8,[`attachment`]))),128))])):F(``,!0),e.assistant?(L(!0),j(U,{key:1},M(n.value,(t,r)=>(L(),j(U,{key:r},[`text`in t?(L(),q(sw,{key:0,text:t.text},null,8,[`text`])):(L(),q(V(nm),{key:1,class:`my-2`},{default:I(()=>[t.tools.length>1?(L(),q(nne,{key:0,tools:t.tools,streaming:e.streaming&&r===n.value.length-1},null,8,[`tools`,`streaming`])):(L(),q(cw,{key:1,tool:t.tools[0],streaming:e.streaming&&r===n.value.length-1},null,8,[`tool`,`streaming`]))]),_:2},1024))],64))),128)):(L(),j(`div`,ine,B(e.text),1)),K(t.$slots,`default`)]),_:3})]),_:3},8,[`variant`]),e.assistant&&!e.streaming&&e.text?(L(),q(V(FC),{key:0,class:`px-0 transition-opacity focus-within:opacity-100 [@media(hover:hover)]:opacity-0 [@media(hover:hover)]:group-hover/message:opacity-100`},{default:I(()=>[A(V(xm),{value:e.text},null,8,[`value`])]),_:1})):F(``,!0)]),_:3})]),_:3},8,[`align`]))}}),one={class:`text-sm`},sne={key:0,class:`mt-1 text-fg-muted`},cne={key:1,class:`mt-2 flex flex-wrap gap-2`},lne=P({__name:`ChatChooseCard`,props:{choose:{}},setup(e){let t=Y(()=>id.value.models??[]);return(e,n)=>(L(),j(`div`,one,[n[0]||=R(`p`,{class:`font-medium`},`Choose a model`,-1),t.value.length?(L(),j(`div`,cne,[(L(!0),j(U,null,M(t.value,e=>(L(),q(V(X),{key:e,size:`sm`,variant:e===V(id).active_model?`default`:`outline`,class:`font-mono`,onClick:t=>void V(vd)(e)},{default:I(()=>[H(B(e),1)]),_:2},1032,[`variant`,`onClick`]))),128))])):(L(),j(`p`,sne,`None configured.`))]))}}),une={class:`text-sm`},dne={key:0},fne={class:`mt-1 space-y-0.5`},pne={class:`font-mono`},mne=[`href`],hne={key:0,class:`mt-3 flex gap-2`},gne={key:1,class:`mt-2 text-fg-muted`},_ne={key:2,class:`mt-2 text-fg-muted`},vne={key:3,class:`mt-2 text-ok`},yne={key:4,class:`mt-2 text-danger`},bne={key:5,class:`mt-2 text-xs text-fg-muted`},xne=P({__name:`ChatUpdateCard`,props:{update:{}},setup(e){let t=e,n=Y(()=>t.update.available??[]),r=J(`idle`),i=J(``);async function a(){r.value=`installing`;try{let e=(await Z.updateInstall(t.update.snapshot)).result?.installed;i.value=e?Object.entries(e).map( Line truncated
`).map(e=>e.trim()).find(Boolean)||``,i=r.length>FT?`${r.slice(0,FT).trimEnd()}…`:r;return{text:i,full:n,truncated:i!==n}}function gie(e){return String(e||`event`).replaceAll(`_`,` `).replace(/\b\w/g,e=>e.toUpperCase())}function LT(e){let t=Number(e);if(!Number.isFinite(t)||t<0)return``;if(t<1e3)return`under 1 s`;let n=t/1e3;if(n<60)return`${n.toFixed(+(n<10))} s`;let r=Math.round(n),i=Math.floor(r/60),a=r%60;if(i<60)return a===0?`${i} min`:`${i} min ${a} s`;let o=Math.floor(i/60),s=i-o*60;return s===0?`${o} h`:`${o} h ${s} min`}function RT(e){let t=Number(e);return!Number.isFinite(t)||t<=0?``:t.toLocaleString(`en-US`)}function zT(e){return typeof e==`string`?e:``}function BT(e={}){let t=e.data||{},n=e.stage||`unknown stage`,r=e.workflow?`${e.workflow} workflow`:``;if(e.kind===`stage_start`)return{title:`Started stage: ${n}`,detail:r};if(e.kind===`stage_finish`){let e=[r,LT(t.duration_ms)].filter(Boolean).join(` · `);return{title:t.interrupted?`Stage interrupted: ${n}`:t.skipped?`Skipped stage: ${n}`:t.error?`Stage failed: ${n}`:`Finished stage: ${n}`,detail:[e,zT(t.error),zT(t.when)].filter(Boolean).join(` · `)}}if(e.kind===`task_retried`){let n=Number(t.retry_count);return{title:Number.isFinite(n)&&n>0?`Retry ${n}`:`Retry requested`,detail:[zT(t.previous_stage)&&`after ${zT(t.previous_stage)}`,zT(t.previous_reason)].filter(Boolean).join(`: `)||e.detail||``}}if(e.kind===`agent_finish`){let r=RT(t.iterations),i=RT(t.tokens),a=Number(t.cached_tokens)||0,o=RT((Number(t.prompt_tokens)||0)-a),s=RT(t.completion_tokens),c=RT(t.cached_tokens),l=[r&&`${r} iterations`,i&&`${i} tokens`,o&&`${o} fresh prompt`,s&&`${s} completion`,c&&`${c} cached`,zT(t.model)].filter(Boolean);return{title:`Agent ${zT(t.status)||`finished`}: ${n}`,detail:l.join(` · `)||e.detail||``}}if(e.kind===`remediation_round`){let e=Number(t.of),n=zT(t.author);return{title:`Remediation ${zT(t.round)}${e>0?` of ${e}`:``}`,detail:[n&&`answers ${n}'s review`,t.review_id?`#${zT(t.review_id)}`:``].filter(Boolean).join(` `)}}if(e.kind===`review_approved`){let e=zT(t.pr_number);return{title:`Pull request approved`,detail:[zT(t.author),e&&`#${e}`].filter(Boolean).join(` · `)}}if(e.kind===`step_retried`)return{title:`Attempt ${zT(t.attempt)} of ${zT(t.of)} failed: ${e.stage||`step`}`,detail:zT(t.error),tone:`warn`};if(e.kind===`config_captured`)return{title:`Configuration captured`,detail:`The effective task-runtime configuration for this run.`};if(e.kind===`binding_started`){let e=zT(t.source),n=zT(t.capture_id),r=[{label:`binding ${zT(t.binding_name)||zT(t.binding_id)}`,to:`/events?tab=bindings`},...n?[{label:`captured event`,to:`/events?tab=inspector&capture=${encodeURIComponent(n)}`}]:[]];return t.unsigned===!0?{title:`Started by an unsigned event`,detail:e?`source ${e}`:``,tone:`warn`,links:r}:{title:`Started by an event`,detail:e?`source ${e}`:``,links:r}}if(e.kind===`changes_captured`){let e=t.totals??{},n=Number(e.files);return{title:`Change capture recorded`,detail:[Number.isFinite(n)&&n>0?`${n} file${n===1?``:`s`} changed`:``,t.captured_after?`captured after ${zT(t.captured_after)}`:``].filter(Boolean).join(` · `)}}return{title:gie(e.kind||e.type),detail:e.detail||``}}var _ie=[`title`],VT=P({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=PT();n.watchIdentities();let r=e,i=t,a=ST(),o=Y(()=>a.taskIDFor(r.event)),s=Y(()=>IT(r.event,n.identityName));function c(){o.value>0&&i(`open`,o.value)}return(t,n)=>(L(),q(V(AT),{class:z(o.value>0?`cursor-pointer`:``),role:o.value>0?`link`:void 0,tabindex:o.value>0?0:void 0,title:o.value>0?`Open task details`:void 0,onClick:c,onKeydown:[gt(pt(c,[`prevent`]),[`enter`]),gt(pt(c,[`prevent`]),[`space`])]},{default:I(()=>[A(V(kT),{class:`font-medium`},{default:I(()=>[H(B(V(BT)({...r.event,at:void 0,detail:void 0}).title),1)]),_:1}),A(V(kT),{class:`font-mono`},{default:I(()=>[H(B(o.value>0?`#${o.value}`:`–`),1)]),_:1}),A(V(kT),{class:`w-[55%] max-w-0`},{default:I(()=>[R(`span`,{class:`block truncate`,title:s.value.truncated?s.value.full:void 0},B(s.value.text),9,_ie)]),_:1}),A(V(kT),null,{default:I(()=>[A(V(fw),{at:e.event.at},null,8,[`at`])]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}}),vie=[{value:`all`,label:`All`},{value:`tasks`,label:`Tasks`},{value:`system`,label:`System`}];function HT(e){return(Number(e?.task_id)||0)>0}function yie(e,t){return t===`tasks`?HT(e):t!==`system`||!HT(e)}function bie(e,t){return e.filter(e=>yie(e,t))}function xie(e,t){return e>0?``:t===`all`?`Waiting for activity`:t===`tasks`?`No task events yet`:`No system events yet`}function Sie(e,t){return`${e}:${t??0}`}function Cie(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=Sie(IT(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 wie={role:`region`,"aria-label":`Activity`,"aria-live":`polite`},Tie={class:`max-h-[28rem] overflow-y-auto`},Eie={clas Line truncated
`,1)[0]??``;return t.length>80?`${t.slice(0,79)}…`:t}function JE(e){return(e?.merged||0)+(e?.completed||0)}function YE(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 XE(e,t){return e.filter(e=>e.required&&!(t[e.name]??``).trim()).map(e=>e.name)}function ZE(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 QE(e,t){let n={};for(let r of e){let e=t[r.name];e!==void 0&&e!==``&&(n[r.name]=ZE(e,r.type))}return n}var $E=[`onKeydown`],eD={key:0,class:`text-sm text-danger`,role:`alert`},tD={key:1,class:`grid gap-1.5`},nD=[`for`],rD={key:0,class:`font-normal text-fg-subtle`},iD=[`id`],aD=[`value`],oD={key:0,class:`text-xs text-fg-subtle`},sD={key:2,class:`grid gap-1.5`},cD=[`id`],lD={class:`block truncate text-label font-medium`},uD={class:`block text-xs text-fg-subtle`},dD={key:0,class:`text-xs text-fg-subtle`},fD={key:3,class:`grid gap-3`},pD=[`for`],mD={class:`font-mono`},hD={key:0,class:`text-fg-subtle`},gD={class:`grid gap-1.5`},_D=[`for`],vD={class:`grid gap-1.5`},yD=[`for`],bD={key:4,class:`text-sm text-danger`,role:`alert`},xD={class:`flex items-center gap-2 border-t border-border pt-4`},SD={class:`mr-auto text-xs text-fg-subtle`},CD=P({__name:`NewTaskForm`,props:{workflow:{},draft:{},initialWorkflow:{},initialInstructions:{}},emits:[`started`,`cancel`],setup(e,{emit:t}){let n=e,r=t,i=we(),a=J([]),o=J([]),s=J([]),c=J(``);Be(async()=>{try{let[e,t]=await Promise.all([Z.workflows(),Z.repositories()]);a.value=(e?.definitions??[]).filter(e=>e.enabled),o.value=e?.workflows??[],s.value=(t??[]).map(e=>`${e.owner}/${e.name}`)}catch(e){c.value=String(e.message||e)}});let l=J(``),u=J(n.workflow??n.initialWorkflow??``),d=J(n.initialInstructions??``),f=J(qE(d.value)),p=J({});Ce(()=>{!u.value&&a.value[0]&&(u.value=a.value[0].id)});let m=Y(()=>a.value.find(e=>e.id===u.value)),h=Y(()=>YE(m.value)),g=Y(()=>XE(h.value,p.value)),_=Y(()=>m.value?.repository??`required`),v=Y(()=>_.value!==`optional`&&_.value!==`none`),y=e=>o.value.find(t=>t.workflow===e),b=J(!1),x=J(``),S=Y(()=>!(!l.value.trim()&&v.value||!u.value||!f.value.trim())&&g.value.length===0);async function C(){if(S.value&&!b.value){b.value=!0,x.value=``;try{let e=await Z.workRequest({repository:_.value===`none`?``:l.value.trim(),workflow:u.value,title:f.value.trim(),instructions:d.value,inputs:QE(h.value,p.value),...n.draft?{draft:n.draft}:{}});r(`started`,e.task_id)}catch(e){x.value=String(e.message||e)}finally{b.value=!1}}}return(e,t)=>(L(),j(`form`,{class:`grid gap-5`,onSubmit:pt(C,[`prevent`]),onKeydown:[gt(pt(C,[`meta`,`prevent`]),[`enter`]),gt(pt(C,[`ctrl`,`prevent`]),[`enter`])]},[c.value?(L(),j(`p`,eD,B(c.value),1)):F(``,!0),_.value===`none`?F(``,!0):(L(),j(`div`,tD,[R(`label`,{for:`${V(i)}-repo`,class:`text-label font-medium`},[t[5]||=H(`Repository`,-1),v.value?F(``,!0):(L(),j(`span`,rD,` (optional)`))],8,nD),A(V(Q),{id:`${V(i)}-repo`,modelValue:l.value,"onUpdate:modelValue":t[0]||=e=>l.value=e,class:`font-mono`,placeholder:`owner/repository`,list:`${V(i)}-repos`,required:v.value},null,8,[`id`,`modelValue`,`list`,`required`]),R(`datalist`,{id:`${V(i)}-repos`},[(L(!0),j(U,null,M(s.value,e=>(L(),j(`option`,{key:e,value:e},null,8,aD))),128))],8,iD),s.value.length?(L(),j(`p`,oD,[t[6]||=H(`Configured: `,-1),(L(!0),j(U,null,M(s.value,e=>(L(),q(V(X),{key:e,type:`button`,variant:`link`,size:`xs`,class:`h-auto px-1 font-mono text-fg-subtle`,onClick:t=>l.value=e},{default:I(()=>[H(B(e),1)]),_:2},1032,[`onClick`]))),128))])):F(``,!0)])),n.workflow?F(``,!0):(L(),j(`div`,sD,[R(`span`,{id:`${V(i)}-wf`,class:`text-label font-medium`},`Workflow`,8,cD),A(V(Ps),{modelValue:u.value,"onUpdate:modelValue":t[1]||=e=>u.value=e,"aria-labelledby":`${V(i)}-wf`,class:`grid grid-cols-1 gap-2 sm:grid-cols-3`,loop:``},{default:I(()=>[(L(!0),j(U,null,M(a.value,e=>(L(),q(V(Is),{key:e.id,value:e.id,class:`rounded-md border border-border bg-card px-3 py-2.5 text-left transition-colors hover:bg-secondary focus-visible:outline-2 focus-visible:outline-ring data-[state=checked]:border-primary data-[state=checked]:bg-secondary`},{default:I(()=>[R(`span`,lD,B(e.name||e.id),1),R(`span`,uD,[H(B(y(e.id)?.runs||0)+` runs`,1),y(e.id)?.runs?(L(),j(U,{key:0},[H(` · `+B(Math.round(V(JE)(y(e.id))/(y(e.id)?.runs||1)*100))+`% delivered`,1)],64)):F(``,!0)])]),_:2},1032,[`value`]))),128))]),_:1},8,[`modelValue`,`aria-labelledby`]),!a.value.length&&!c.value?(L(),j(`p`,dD,`No enabled workflows.`)):F(``,!0)])),h.value.length?(L(),j(`div`,fD,[(L(!0),j(U,null,M(h.value,e=>(L(),j(`div`,{key:e.name,class:`grid gap-1.5`},[R(`label`,{for:`${V(i)}-input-${e.name}`,class:`text-label font-medium`},[R(`span`,mD,B(e.name),1),e.required?(L(),j(`span`,hD,` · required`)):F(``,!0)],8,pD),A(V(Q),{id:`${V(i)}-input-${e.name}`,"model-value":p.value[e.name 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 zD(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 BD(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 VD(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 HD(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 UD=J([]),WD=J([]),GD=J(!0),KD=J(null),qD=J(!0),JD=J(null),YD=J(!1),XD=J(null);async function ZD(){try{let e=await Z.eventTypes(LD().workspace);GD.value=e.enabled!==!1,UD.value=e.event_types||[],WD.value=e.proposals||[],KD.value=null}catch(e){KD.value=e.message||String(e)}finally{qD.value=!1}}function QD(e){return{headers:(e.headers||[]).map(e=>({...e})),payload:(e.payload||[]).map(e=>({...e}))}}function $D(e){XD.value=null,JD.value=e}function eO(e){let t=cO.value.find(t=>String(t.id)===e.sample_id);$D({mode:`proposal`,id:null,source:e.source,name:``,rule:QD(e.rule),headersText:``,body:t?.body||``,exampleHeaders:e.headers||{}})}function tO(e=``){$D({mode:`paste`,id:null,source:e,name:``,rule:{headers:[],payload:[]},headersText:``,body:``,exampleHeaders:{}})}function nO(e){$D({mode:`edit`,id:e.id,source:e.source,name:e.name,rule:QD(e.rule),headersText:``,body:``,exampleHeaders:{}})}function rO(){JD.value=null}async function iO(){let e=JD.value;if(e){YD.value=!0;try{if(e.mode===`edit`&&e.id)await Z.eventTypeUpdate(e.id,{name:e.name,rule:HD(e.rule)});else{let t=e.mode===`paste`?RD(e.headersText):e.exampleHeaders;await Z.eventTypeCreate({source:e.source,name:e.name,rule:e.mode===`paste`?void 0:HD(e.rule),example:{headers:t,body:e.body}})}JD.value=null,await ZD()}catch(e){XD.value=e.message||String(e)}finally{YD.value=!1}}}var aO=J(null);async function oO(){let e=aO.value;if(aO.value=null,e)try{await Z.eventTypeDelete(e.id),await ZD()}catch(e){KD.value=e.message||String(e)}}var sO=100,cO=J([]),lO=J(!0),uO=J(null),dO=J(!0),fO=J(null);async function pO(){try{let e=await Z.captures(sO);lO.value=e.enabled!==!1,cO.value=e.captures||[],uO.value=null}catch(e){uO.value=e.message||String(e)}finally{dO.value=!1}}function mO(e){let t=cO.value.find(t=>t.id===e);return t&&(fO.value=t),!!t}function hO(){cO.value.length&&(fO.value=cO.value[0])}function gO(){Yf(`captures`,()=>{pO(),ZD()})}var _O=P({__name:`Tabs`,props:{defaultValue:{},orientation:{},dir:{},activationMode:{},modelValue:{},unmountOnHide:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},emits:[`update:modelValue`],setup(e,{emit:t}){let n=e,r=t,i=ct(n,`class`),a=w(i,r);return(e,t)=>(L(),q(V(kc),G({"data-slot":`tabs`,"data-orientation":V(a).orientation||`horizontal`},V(a),{class:V(W)(`gap-2 group/tabs flex data-horizontal:flex-col`,n.class)}),{default:I(t=>[K(e.$slots,`default`,Je(be(t)))]),_:3},16,[`data-orientation`,`class`]))}}),vO=P({__name:`TabsContent`,props:{value:{},forceMount:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=ct(t,`class`);return(e,r)=>(L(),q(V(Mc),G({"data-slot":`tabs-content`,class:V(W)(`text-sm flex-1 outline-none`,t.class)},V(n)),{default:I(()=>[K(e.$slots,`default`)]),_:3},16,[`class`]))}}),yO=P({__name:`TabsList`,props:{loop:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]},variant:{default:`default`}},setup(e){let t=e,n=ct(t,`class`,`variant`);return(r,i)=>(L(),q(V(Nc),G({"data-slot":`tabs-list`,"data-variant":e.variant},V(n),{class:V(W)(V(xO)({variant:e.variant}),t.class)}),{default:I(()=>[K(r.$slots,`default`)]),_:3},16,[`data-variant`,`class`]))}}),bO=P({__name:`TabsTrigger`,props:{value:{},disabled:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=ct(t,`class`),r=C(n);return(e,n)=>(L(),q(V(Pc),G({"data-slot":`tabs-trigger`,class:V(W)(`gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg:not([class*=size-])]:size-4 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:oLine truncated
WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}}var SH=cH(`CharSizeService`),CH=cH(`CoreBrowserService`),wH=cH(`MouseService`),TH=cH(`RenderService`),EH=cH(`SelectionService`),DH=cH(`CharacterJoinerService`),OH=cH(`ThemeService`),kH=cH(`LinkProviderService`),AH=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?IH.isErrorNoTelemetry(e)?new IH(e.message+`
WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}}var pH=$V(`CharSizeService`),mH=$V(`CoreBrowserService`),hH=$V(`MouseService`),gH=$V(`RenderService`),_H=$V(`SelectionService`),vH=$V(`CharacterJoinerService`),yH=$V(`ThemeService`),bH=$V(`LinkProviderService`),xH=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?DH.isErrorNoTelemetry(e)?new DH(e.message+`
`+e.stack):Error(e.message+`
`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function jH(e){NH(e)||AH.onUnexpectedError(e)}var MH=`Canceled`;function NH(e){return e instanceof PH||e instanceof Error&&e.name===MH&&e.message===MH}var PH=class extends Error{constructor(){super(MH),this.name=this.message}};function FH(e){return Error(e?`Illegal argument: ${e}`:`Illegal argument`)}var IH=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}},LH=class e extends Error{constructor(t){super(t||`An unexpected bug occurred.`),Object.setPrototypeOf(this,e.prototype)}};function RH(e,t=0){return e[e.length-(1+t)]}var zH;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(zH||={});var BH=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>!t(n)||e(n)))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>!e(n)||(t=n,!1)),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||zH.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};BH.empty=new BH(e=>{});function VH(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var HH;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t<n;t++)yield e[t]}e.slice=_;function v(t,n=1/0){let r=[];if(n===0)return[r,t];let i=t[Symbol.iterator]();for(let t=0;t<n;t++){let t=i.next();if(t.done)return[r,e.empty()];r.push(t.value)}return[r,{[Symbol.iterator](){return i}}]}e.consume=v;async function y(e){let t=[];for await(let n of e)t.push(n);return Promise.resolve(t)}e.asyncToArray=y})(HH||={});var UH=null;function WH(e){return UH?.trackDisposable(e),e}function GH(e){UH?.markAsDisposed(e)}function KH(e,t){UH?.setParent(e,t)}function qH(e){return UH?.markAsSingleton(e),e}function JH(e){if(HH.is(e)){let t=[];for(let n of e)if(n)try{n.dispose()}catch(e){t.push(e)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function YH(...e){return XH(()=>JH(e))}function XH(e){let t=WH({dispose:VH(()=>{GH(t),e()})});return t}var ZH=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,WH(this)}dispose(){this._isDisposed||(GH(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{JH(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return KH(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`).stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),KH(e,null))}};ZH.DISABLE_DISPOSED_WARNING=!1;var QH=ZH,$H=class{constructor(){this._store=new QH,WH(this),KH(this._store,this)}dispose(){GH(thi Line truncated
`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function SH(e){wH(e)||xH.onUnexpectedError(e)}var CH=`Canceled`;function wH(e){return e instanceof TH||e instanceof Error&&e.name===CH&&e.message===CH}var TH=class extends Error{constructor(){super(CH),this.name=this.message}};function EH(e){return Error(e?`Illegal argument: ${e}`:`Illegal argument`)}var DH=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}},OH=class e extends Error{constructor(t){super(t||`An unexpected bug occurred.`),Object.setPrototypeOf(this,e.prototype)}};function kH(e,t=0){return e[e.length-(1+t)]}var AH;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(AH||={});var jH=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>!t(n)||e(n)))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>!e(n)||(t=n,!1)),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||AH.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};jH.empty=new jH(e=>{});function MH(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var NH;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t<n;t++)yield e[t]}e.slice=_;function v(t,n=1/0){let r=[];if(n===0)return[r,t];let i=t[Symbol.iterator]();for(let t=0;t<n;t++){let t=i.next();if(t.done)return[r,e.empty()];r.push(t.value)}return[r,{[Symbol.iterator](){return i}}]}e.consume=v;async function y(e){let t=[];for await(let n of e)t.push(n);return Promise.resolve(t)}e.asyncToArray=y})(NH||={});var PH=null;function FH(e){return PH?.trackDisposable(e),e}function IH(e){PH?.markAsDisposed(e)}function LH(e,t){PH?.setParent(e,t)}function RH(e){return PH?.markAsSingleton(e),e}function zH(e){if(NH.is(e)){let t=[];for(let n of e)if(n)try{n.dispose()}catch(e){t.push(e)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function BH(...e){return VH(()=>zH(e))}function VH(e){let t=FH({dispose:MH(()=>{IH(t),e()})});return t}var HH=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,FH(this)}dispose(){this._isDisposed||(IH(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{zH(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return LH(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`).stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),LH(e,null))}};HH.DISABLE_DISPOSED_WARNING=!1;var UH=HH,WH=class{constructor(){this._store=new UH,FH(this),LH(this._store,this)}dispose(){IH(thi Line truncated
`).slice(2).join(`
`))}},mU=class extends Error{constructor(e,t){super(e),this.name=`ListenerLeakError`,this.stack=t}},hU=class extends Error{constructor(e,t){super(e),this.name=`ListenerRefusalError`,this.stack=t}},gU=0,_U=class{constructor(e){this.value=e,this.id=gU++}},vU=2,yU=class{constructor(e){this._size=0,this._options=e,this._leakageMon=uU>0||this._options?.leakWarningThreshold?new fU(e?.onListenerError??jH,this._options?.leakWarningThreshold??uU):void 0,this._perfMon=this._options?._profName?new lU(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new hU(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||jH)(n),$H.None}if(this._disposed)return $H.None;t&&(e=e.bind(t));let r=new _U(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=pU.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof _U?(this._deliveryQueue??=new bU,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=XH(()=>{i?.(),this._removeListener(r)});return n instanceof QH?n.add(a):Array.isArray(n)&&n.push(a),a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*vU<=t.length){let e=0;for(let n=0;n<t.length;n++)t[n]?t[e++]=t[n]:r&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=e}}_deliver(e,t){if(!e)return;let n=this._options?.onListenerError||jH;if(!n)e.value(t);else try{e.value(t)}catch(e){n(e)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners){if(this._listeners instanceof _U)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}}this._perfMon?.stop()}hasListeners(){return this._size>0}},bU=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},xU=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new yU,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new yU,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};xU.INSTANCE=new xU;var SU=xU;function CU(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}SU.INSTANCE.onDidChangeZoomLevel;function wU(e){return SU.INSTANCE.getZoomFactor(e)}SU.INSTANCE.onDidChangeFullscreen;var TU=typeof navigator==`object`?navigator.userAgent:``,EU=TU.indexOf(`Firefox`)>=0,DU=TU.indexOf(`AppleWebKit`)>=0,OU=TU.indexOf(`Chrome`)>=0,kU=!OU&&TU.indexOf(`Safari`)>=0;TU.indexOf(`Electron/`),TU.indexOf(`Android`);var AU=!1;if(typeof tU.matchMedia==`function`){let e=tU.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=tU.matchMedia(`(display-mode: fullscreen)`);AU=e.matches,CU(tU,e,({matches:e})=>{AU&&t.matches||(AU=e)} Line truncated
`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(e=>this._handleScroll(e)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};EG=IV([LV(2,uH),LV(3,CH),LV(4,dH),LV(5,OH),LV(6,gH),LV(7,TH)],EG);var DG=class extends $H{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement(`div`),this._container.classList.add(`xterm-decoration-container`),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(e=>this._removeDecoration(e))),this._register(XH(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement(`div`);t.classList.add(`xterm-decoration`),t.classList.toggle(`xterm-decoration-top-layer`,e?.options?.layer===`top`),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display=`none`),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display=`none`,e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?`none`:`block`,this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderLine truncated
`,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``))($||={});var NG;(e=>(e.PAD=`€`,e.HOP=``,e.BPH=`‚`,e.NBH=`ƒ`,e.IND=`„`,e.NEL=`…`,e.SSA=`†`,e.ESA=`‡`,e.HTS=`ˆ`,e.HTJ=`‰`,e.VTS=`Š`,e.PLD=`‹`,e.PLU=`Œ`,e.RI=``,e.SS2=`Ž`,e.SS3=``,e.DCS=``,e.PU1=`‘`,e.PU2=`’`,e.STS=`“`,e.CCH=`”`,e.MW=`•`,e.SPA=`–`,e.EPA=`—`,e.SOS=`˜`,e.SGCI=`™`,e.SCI=`š`,e.CSI=`›`,e.ST=`œ`,e.OSC=``,e.PM=`ž`,e.APC=`Ÿ`))(NG||={});var PG;(e=>e.ST=`${$.ESC}\\`)(PG||={});var FG=class{constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=``}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=``,this._dataAlreadySent=``,this._compositionView.classList.add(`active`)}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let t;e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.length<e.length?this._coreService.triggerDataEvent(`${$.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let e=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),t=this._renderService.dimensions.css.cell.height,n=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=e*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+`px`,this._compositionView.style.top=n+`px`,this._compositionView.style.height=t+`px`,this._compositionView.style.lineHeight=t+`px`,this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+`px`;let i=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+`px`,this._textarea.style.top=n+`px`,this._textarea.style.width=Math.max(i.width,1)+`px`,this._textarea.style.height=Math.max(i.height,1)+`px`,this._textarea.style.lineHeight=i.height+`px`}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};FG=IV([LV(2,uH),LV(3,gH),LV(4,fH),LV(5,TH)],FG);var IG=0,LG=0,RG=0,zG=0,BG={css:`#00000000`,rgba:0},VG;(e=>{function t(e,t,n,r){return r===void 0?`#${KG(e)}${KG(t)}${KG(n)}`:`#${KG(e)}${KG(t)}${KG(n)}${KG(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(VG||={});var HG;(e=>{function t(e,t){if(zG=(t.rgba&255)/255,zG===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return IG=a+Math.round((n-a)*zG),LG=o+Math.round((r-o)*zG),RG=s+Math.round((i-s)*zG),{css:VG.toCss(IG,LG,RG),rgba:VG.toRgba(IG,LG,RG)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=GG.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return VG.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[IG,LG,RG]=GG.toChannels(t),{css:VG.toCss(IG,LG,RG),rgba:t}}e.opaque=i;function a(e,t){return zG=Math.round(t*255),[IG,LG,RG]=GG.toChannels(e.rgba),{css:VG.toCss(IG,LG,RG,zG),rgba:VG.toRgba(IG,LG,RG,zG)}}e.opacity=a;function o(e,t){return zG=e.rgba&255,a(e,zG*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.r Line truncated
`))}},aU=class extends Error{constructor(e,t){super(e),this.name=`ListenerLeakError`,this.stack=t}},oU=class extends Error{constructor(e,t){super(e),this.name=`ListenerRefusalError`,this.stack=t}},sU=0,cU=class{constructor(e){this.value=e,this.id=sU++}},lU=2,uU=class{constructor(e){this._size=0,this._options=e,this._leakageMon=tU>0||this._options?.leakWarningThreshold?new rU(e?.onListenerError??SH,this._options?.leakWarningThreshold??tU):void 0,this._perfMon=this._options?._profName?new eU(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new oU(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||SH)(n),WH.None}if(this._disposed)return WH.None;t&&(e=e.bind(t));let r=new cU(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=iU.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof cU?(this._deliveryQueue??=new dU,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=VH(()=>{i?.(),this._removeListener(r)});return n instanceof UH?n.add(a):Array.isArray(n)&&n.push(a),a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*lU<=t.length){let e=0;for(let n=0;n<t.length;n++)t[n]?t[e++]=t[n]:r&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=e}}_deliver(e,t){if(!e)return;let n=this._options?.onListenerError||SH;if(!n)e.value(t);else try{e.value(t)}catch(e){n(e)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners){if(this._listeners instanceof cU)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}}this._perfMon?.stop()}hasListeners(){return this._size>0}},dU=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},fU=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new uU,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new uU,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};fU.INSTANCE=new fU;var pU=fU;function mU(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}pU.INSTANCE.onDidChangeZoomLevel;function hU(e){return pU.INSTANCE.getZoomFactor(e)}pU.INSTANCE.onDidChangeFullscreen;var gU=typeof navigator==`object`?navigator.userAgent:``,_U=gU.indexOf(`Firefox`)>=0,vU=gU.indexOf(`AppleWebKit`)>=0,yU=gU.indexOf(`Chrome`)>=0,bU=!yU&&gU.indexOf(`Safari`)>=0;gU.indexOf(`Electron/`),gU.indexOf(`Android`);var xU=!1;if(typeof KH.matchMedia==`function`){let e=KH.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=KH.matchMedia(`(display-mode: fullscreen)`);xU=e.matches,mU(KH,e,({matches:e})=>{xU&&t.matches||(xU=e)} Line truncated
`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(e=>this._handleScroll(e)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};_G=DV([OV(2,tH),OV(3,mH),OV(4,nH),OV(5,yH),OV(6,sH),OV(7,gH)],_G);var vG=class extends WH{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement(`div`),this._container.classList.add(`xterm-decoration-container`),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(e=>this._removeDecoration(e))),this._register(VH(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement(`div`);t.classList.add(`xterm-decoration`),t.classList.toggle(`xterm-decoration-top-layer`,e?.options?.layer===`top`),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display=`none`),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display=`none`,e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?`none`:`block`,this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderLine truncated
`,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``))($||={});var wG;(e=>(e.PAD=`€`,e.HOP=``,e.BPH=`‚`,e.NBH=`ƒ`,e.IND=`„`,e.NEL=`…`,e.SSA=`†`,e.ESA=`‡`,e.HTS=`ˆ`,e.HTJ=`‰`,e.VTS=`Š`,e.PLD=`‹`,e.PLU=`Œ`,e.RI=``,e.SS2=`Ž`,e.SS3=``,e.DCS=``,e.PU1=`‘`,e.PU2=`’`,e.STS=`“`,e.CCH=`”`,e.MW=`•`,e.SPA=`–`,e.EPA=`—`,e.SOS=`˜`,e.SGCI=`™`,e.SCI=`š`,e.CSI=`›`,e.ST=`œ`,e.OSC=``,e.PM=`ž`,e.APC=`Ÿ`))(wG||={});var TG;(e=>e.ST=`${$.ESC}\\`)(TG||={});var EG=class{constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=``}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=``,this._dataAlreadySent=``,this._compositionView.classList.add(`active`)}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let t;e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.length<e.length?this._coreService.triggerDataEvent(`${$.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let e=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),t=this._renderService.dimensions.css.cell.height,n=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=e*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+`px`,this._compositionView.style.top=n+`px`,this._compositionView.style.height=t+`px`,this._compositionView.style.lineHeight=t+`px`,this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+`px`;let i=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+`px`,this._textarea.style.top=n+`px`,this._textarea.style.width=Math.max(i.width,1)+`px`,this._textarea.style.height=Math.max(i.height,1)+`px`,this._textarea.style.lineHeight=i.height+`px`}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};EG=DV([OV(2,tH),OV(3,sH),OV(4,rH),OV(5,gH)],EG);var DG=0,OG=0,kG=0,AG=0,jG={css:`#00000000`,rgba:0},MG;(e=>{function t(e,t,n,r){return r===void 0?`#${LG(e)}${LG(t)}${LG(n)}`:`#${LG(e)}${LG(t)}${LG(n)}${LG(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(MG||={});var NG;(e=>{function t(e,t){if(AG=(t.rgba&255)/255,AG===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return DG=a+Math.round((n-a)*AG),OG=o+Math.round((r-o)*AG),kG=s+Math.round((i-s)*AG),{css:MG.toCss(DG,OG,kG),rgba:MG.toRgba(DG,OG,kG)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=IG.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return MG.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[DG,OG,kG]=IG.toChannels(t),{css:MG.toCss(DG,OG,kG),rgba:t}}e.opaque=i;function a(e,t){return AG=Math.round(t*255),[DG,OG,kG]=IG.toChannels(e.rgba),{css:MG.toCss(DG,OG,kG,AG),rgba:MG.toRgba(DG,OG,kG,AG)}}e.opacity=a;function o(e,t){return AG=e.rgba&255,a(e,AG*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.r Line truncated
`:`
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),LK&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=oq(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=xK(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-sq),sq),t/=sq,t/Math.abs(t)+Math.round(t*(cq-1)))}shouldForceSelection(e){return NK?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),lq)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(NK&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._active Line truncated
`))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(IW(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(XH(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<lY+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===lY+1&&(this._liveRegion.textContent+=VV.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t<i.length?i[t]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(a&&o){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=``;let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let Line truncated
`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return zV.get()},set promptLabel(e){zV.set(e)},get tooMuchOutput(){return VV.get()},set tooMuchOutput(e){VV.set(e)}}}_verifyIntegers(...e){for(SY of e)if(SY===1/0||isNaN(SY)||SY%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(SY of e)if(SY&&(SY===1/0||isNaN(SY)||SY%1!=0||SY<0))throw Error(`This API only accepts positive integers`)}},wY=2,TY=1,EY=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(wY,Math.floor(u/e.css.cell.width)),rows:Math.max(TY,Math.floor(l/e.css.cell.height))}}},DY={class:`flex h-[32rem] min-h-0 flex-col gap-2`},OY={key:0,class:`text-sm text-fg-muted`,role:`status`},kY=P({__name:`SandboxView`,props:{taskId:{},attempt:{}},setup(e){let t=e,n=J(null),r=J(`connecting`),i=null,a=null,o=null,s=null;function c(){try{o?.fit()}catch{}}return Be(()=>{let e=n.value;if(!e)return;i=new CY({convertEol:!0,disableStdin:!0,cursorBlink:!1,fontFamily:`'IBM Plex Mono', ui-monospace, monospace`,fontSize:13,theme:{background:`#0b0f14`,foreground:`#e6edf3`}}),o=new EY,i.loadAddon(o),i.open(e),c();let l=window.location.protocol===`https:`?`wss:`:`ws:`,u=new URLSearchParams({attempt:String(t.attempt)}),d=new WebSocket(`${l}//${window.location.host}/api/tasks/${encodeURIComponent(t.taskId)}/sandbox?${u}`);a=d,d.binaryType=`arraybuffer`,d.onopen=()=>{r.value=`open`},d.onmessage=e=>{i&&(typeof e.data==`string`&&(r.value=`failed`),i.write(typeof e.data==`string`?e.data:new Uint8Array(e.data)))},d.onerror=()=>{r.value=`failed`},d.onclose=()=>{r.value!==`failed`&&(r.value=`closed`)},s=new ResizeObserver(c),s.observe(e)}),nt(()=>{s?.disconnect(),s=null,a?.close(),a=null,i?.dispose(),i=null,o=null}),(e,t)=>(L(),j(`div`,DY,[r.value===`open`?F(``,!0):(L(),j(`p`,OY,[r.value===`connecting`?(L(),j(U,{key:0},[H(`Connecting…`)],64)):r.value===`closed`?(L(),j(U,{key:1},[H(`The sandbox ended.`)],64)):(L(),j(U,{key:2},[H(`Sandbox unavailable.`)],64))])),R(`div`,{ref_key:`host`,ref:n,class:`min-h-0 flex-1 overflow-hidden rounded-md border border-border bg-[#0b0f14] p-2`},null,512)]))}}),AY={class:`flex flex-wrap items-center gap-3 border-b border-border pb-3`},jY={class:`inline-flex items-center gap-2`},MY={class:`inline-flex items-center gap-2`},NY=`__all__`,PY=P({__name:`TaskLogFilters`,props:{filters:{},stages:{}},emits:[`filter`],setup(e,{emit:t}){let n=e,r=t,i=Y(()=>yM.map(e=>({value:e.value||NY,label:e.label}))),a=Y(()=>n.filters.level||NY),o=Y(()=>n.filters.stage||NY);function s(e){r(`filter`,{...n.filters,...e})}function c(e){s({level:String(e)===NY?``:String(e)})}function l(e){s({stage:String(e)===NY?``:String(e)})}return(t,n)=>(L(),j(`div`,AY,[R(`div`,jY,[A(V(Bu),{"model-value":a.value,"onUpdate:modelValue":c},{default:I(()=>[A(V(Wu),{size:`sm`,"aria-label":`Filter log entries by level`},{default:I(()=>[A(V(Gu))]),_:1}),A(V(Vu),null,{default:I(()=>[A(V(Hu),null,{default:I(()=>[(L(!0),j(U,null,M(i.value,e=>(L(),q(V(Uu),{key:e.value,value:e.value},{default:I(()=>[H(B(e.label),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1})]),_:1},8,[`model-value`])]),R(`div`,MY,[A(V(Bu),{"model-value":o.value,"onUpdate:modelValue":l},{default:I(()=>[A(V(Wu),{size:`sm`,"aria-label":`Filter log entries by stage`},{default:I(()=>[A(V(Gu))]),_:1}),A(V(Vu),null,{default:I(()=>[A(V(Hu),null,{default:I(()=>[A(V(Uu),{value:NY},{default:I(()=>[...n[0]||=[H(`All stages`,-1)]]),_:1}),(L(!0),j(U,null,M(e.stages,e=>(L(),q(V(Uu),{key:e,value:e},{default:I(()=>[H(B(e),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1})]),_:1},8,[`model-value`])])]))}}),FY={class:`sr-only`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`},IY={key:2,class:`flex flex-col items-start gap-2 py-3`},LY={key:0,class:`mt-2 flex flex-wrap items-cent Line truncated
`)}};XZ.defaultYaml={explicit:!1,version:`1.2`},XZ.defaultTags={"!!":`tag:yaml.org,2002:`};function ZZ(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 QZ(e){let t=new Set;return UZ(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function $Z(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function eQ(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=QZ(e);let a=$Z(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&(FZ(t.node)||LZ(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 tQ(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=tQ(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=tQ(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=tQ(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=tQ(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}function nQ(e,t,n){if(Array.isArray(e))return e.map((e,t)=>nQ(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!zZ(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 rQ=class{constructor(e){Object.defineProperty(this,AZ,{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(!MZ(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=nQ(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?tQ(i,{"":o},``,o):o}},iQ=class extends rQ{constructor(e){super(wZ),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=[],UZ(e,{Node:(e,t)=>{(jZ(t)||zZ(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||=(nQ(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=aQ(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(ZZ(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 aQ(e,t,n){if(jZ(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(LZ(t)){let r=0;for(let i of t.items){let t=aQ(e,i,n);t>r&&(r=t)}return r}if(PZ(t)){let r=aQ(e,t.key,n),i=aQ(e,t.value,n);return Math.max(r,i)}return 1}var oQ=e=>!e||typeof e!=`function`&&typeof e!=`object`,sQ=class extends rQ{constructor(e){super(OZ),this.value=e}toJSON(e,t){return t?.keep?this.value:nQ(this.value,e,t)}toString(){return String(this.value)}};sQ.BLOCK_FOLDED=`BLOCK_FOLDED`,sQ.BLOCK_LITERAL=`BLOCK_LITERAL`,sQ.PLAIN=`PLAIN`,sQ.QUOTE_DOUBLE=`QUOTE_DOUBLE`,sQ.QUOTE_SINGLE=`QUOTE_SINGLE`;var cQ=`tag:yaml.org,2002:`;function lQ(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 uQ(e,t,n){if(MZ(e)&&(e=e.contents),RZ(e))return e;if(PZ(e)){let t=n.schema[EZ].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 iQ(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=cQ+t.slice(2));let l=lQ(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new sQ(e);return c&&(c.node=t),t Line truncated
`)?hQ(n,t):n.includes(`
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),OK&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=ZK(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=fK(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-QK),QK),t/=QK,t/Math.abs(t)+Math.round(t*($K-1)))}shouldForceSelection(e){return wK?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),eq)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(wK&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._active Line truncated
`))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(DW(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(VH(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<eY+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===eY+1&&(this._liveRegion.textContent+=MV.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t<i.length?i[t]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(a&&o){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=``;let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let Line truncated
`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return AV.get()},set promptLabel(e){AV.set(e)},get tooMuchOutput(){return MV.get()},set tooMuchOutput(e){MV.set(e)}}}_verifyIntegers(...e){for(pY of e)if(pY===1/0||isNaN(pY)||pY%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(pY of e)if(pY&&(pY===1/0||isNaN(pY)||pY%1!=0||pY<0))throw Error(`This API only accepts positive integers`)}},hY=2,gY=1,_Y=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(hY,Math.floor(u/e.css.cell.width)),rows:Math.max(gY,Math.floor(l/e.css.cell.height))}}},vY={class:`flex h-[32rem] min-h-0 flex-col gap-2`},yY={key:0,class:`text-sm text-fg-muted`,role:`status`},bY=P({__name:`SandboxView`,props:{taskId:{},attempt:{}},setup(e){let t=e,n=J(null),r=J(`connecting`),i=null,a=null,o=null,s=null;function c(){try{o?.fit()}catch{}}return Be(()=>{let e=n.value;if(!e)return;i=new mY({convertEol:!0,disableStdin:!0,cursorBlink:!1,fontFamily:`'IBM Plex Mono', ui-monospace, monospace`,fontSize:13,theme:{background:`#0b0f14`,foreground:`#e6edf3`}}),o=new _Y,i.loadAddon(o),i.open(e),c();let l=window.location.protocol===`https:`?`wss:`:`ws:`,u=new URLSearchParams({attempt:String(t.attempt)}),d=new WebSocket(`${l}//${window.location.host}/api/tasks/${encodeURIComponent(t.taskId)}/sandbox?${u}`);a=d,d.binaryType=`arraybuffer`,d.onopen=()=>{r.value=`open`},d.onmessage=e=>{i&&(typeof e.data==`string`&&(r.value=`failed`),i.write(typeof e.data==`string`?e.data:new Uint8Array(e.data)))},d.onerror=()=>{r.value=`failed`},d.onclose=()=>{r.value!==`failed`&&(r.value=`closed`)},s=new ResizeObserver(c),s.observe(e)}),nt(()=>{s?.disconnect(),s=null,a?.close(),a=null,i?.dispose(),i=null,o=null}),(e,t)=>(L(),j(`div`,vY,[r.value===`open`?F(``,!0):(L(),j(`p`,yY,[r.value===`connecting`?(L(),j(U,{key:0},[H(`Connecting…`)],64)):r.value===`closed`?(L(),j(U,{key:1},[H(`The sandbox ended.`)],64)):(L(),j(U,{key:2},[H(`Sandbox unavailable.`)],64))])),R(`div`,{ref_key:`host`,ref:n,class:`min-h-0 flex-1 overflow-hidden rounded-md border border-border bg-[#0b0f14] p-2`},null,512)]))}}),xY={class:`flex flex-wrap items-center gap-3 border-b border-border pb-3`},SY={class:`inline-flex items-center gap-2`},CY={class:`inline-flex items-center gap-2`},wY=`__all__`,TY=P({__name:`TaskLogFilters`,props:{filters:{},stages:{}},emits:[`filter`],setup(e,{emit:t}){let n=e,r=t,i=Y(()=>yM.map(e=>({value:e.value||wY,label:e.label}))),a=Y(()=>n.filters.level||wY),o=Y(()=>n.filters.stage||wY);function s(e){r(`filter`,{...n.filters,...e})}function c(e){s({level:String(e)===wY?``:String(e)})}function l(e){s({stage:String(e)===wY?``:String(e)})}return(t,n)=>(L(),j(`div`,xY,[R(`div`,SY,[A(V(zu),{"model-value":a.value,"onUpdate:modelValue":c},{default:I(()=>[A(V(Uu),{size:`sm`,"aria-label":`Filter log entries by level`},{default:I(()=>[A(V(Wu))]),_:1}),A(V(Bu),null,{default:I(()=>[A(V(Vu),null,{default:I(()=>[(L(!0),j(U,null,M(i.value,e=>(L(),q(V(Hu),{key:e.value,value:e.value},{default:I(()=>[H(B(e.label),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1})]),_:1},8,[`model-value`])]),R(`div`,CY,[A(V(zu),{"model-value":o.value,"onUpdate:modelValue":l},{default:I(()=>[A(V(Uu),{size:`sm`,"aria-label":`Filter log entries by stage`},{default:I(()=>[A(V(Wu))]),_:1}),A(V(Bu),null,{default:I(()=>[A(V(Vu),null,{default:I(()=>[A(V(Hu),{value:wY},{default:I(()=>[...n[0]||=[H(`All stages`,-1)]]),_:1}),(L(!0),j(U,null,M(e.stages,e=>(L(),q(V(Hu),{key:e,value:e},{default:I(()=>[H(B(e),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1})]),_:1},8,[`model-value`])])]))}}),EY={class:`sr-only`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`},DY={key:2,class:`flex flex-col items-start gap-2 py-3`},OY={key:0,class:`mt-2 flex flex-wrap items-cent Line truncated
`)}};VZ.defaultYaml={explicit:!1,version:`1.2`},VZ.defaultTags={"!!":`tag:yaml.org,2002:`};function HZ(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 UZ(e){let t=new Set;return PZ(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function WZ(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function GZ(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=UZ(e);let a=WZ(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&(EZ(t.node)||OZ(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 KZ(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=KZ(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=KZ(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=KZ(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=KZ(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}function qZ(e,t,n){if(Array.isArray(e))return e.map((e,t)=>qZ(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!AZ(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 JZ=class{constructor(e){Object.defineProperty(this,xZ,{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(!CZ(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=qZ(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?KZ(i,{"":o},``,o):o}},YZ=class extends JZ{constructor(e){super(hZ),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=[],PZ(e,{Node:(e,t)=>{(SZ(t)||AZ(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||=(qZ(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=XZ(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(HZ(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 XZ(e,t,n){if(SZ(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(OZ(t)){let r=0;for(let i of t.items){let t=XZ(e,i,n);t>r&&(r=t)}return r}if(TZ(t)){let r=XZ(e,t.key,n),i=XZ(e,t.value,n);return Math.max(r,i)}return 1}var ZZ=e=>!e||typeof e!=`function`&&typeof e!=`object`,QZ=class extends JZ{constructor(e){super(yZ),this.value=e}toJSON(e,t){return t?.keep?this.value:qZ(this.value,e,t)}toString(){return String(this.value)}};QZ.BLOCK_FOLDED=`BLOCK_FOLDED`,QZ.BLOCK_LITERAL=`BLOCK_LITERAL`,QZ.PLAIN=`PLAIN`,QZ.QUOTE_DOUBLE=`QUOTE_DOUBLE`,QZ.QUOTE_SINGLE=`QUOTE_SINGLE`;var $Z=`tag:yaml.org,2002:`;function eQ(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 tQ(e,t,n){if(CZ(e)&&(e=e.contents),kZ(e))return e;if(TZ(e)){let t=n.schema[_Z].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 YZ(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=$Z+t.slice(2));let l=eQ(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new QZ(e);return c&&(c.node=t),t Line truncated
`)?oQ(n,t):n.includes(`
`)?`
`+hQ(n,t):(e.endsWith(` `)?``:` `)+n,_Q=`flow`,vQ=`block`,yQ=`quoted`;function bQ(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=xQ(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=xQ(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(r===` `&&p&&p!==` `&&p!==`
`+oQ(n,t):(e.endsWith(` `)?``:` `)+n,cQ=`flow`,lQ=`block`,Gie=`quoted`;function uQ(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=dQ(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=dQ(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 xQ(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 SQ=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),CQ=e=>/^(%|---|\.\.\.)/m.test(e);function wQ(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 TQ(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(CQ(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 dQ(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 fQ=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),pQ=e=>/^(%|---|\.\.\.)/m.test(e);function mQ(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 hQ(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(pQ(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:bQ(o,a,yQ,SQ(t,!1))}function EQ(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
`)||/[ \t]\n|\n[ \t]/.test(e))return TQ(e,t);let n=t.indent||(CQ(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:bQ(r,n,_Q,SQ(t,!1))}function DQ(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=TQ;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?EQ:i&&!t?TQ:n?EQ:TQ}return r(e,t)}var OQ;try{OQ=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:uQ(o,a,Gie,fQ(t,!1))}function gQ(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
`)||/[ \t]\n|\n[ \t]/.test(e))return hQ(e,t);let n=t.indent||(pQ(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:uQ(r,n,cQ,fQ(t,!1))}function _Q(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=hQ;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?gQ:i&&!t?hQ:n?gQ:hQ}return r(e,t)}var vQ;try{vQ=RegExp(`(^|(?<!
))
+(?!
|$)`,`g`)}catch{OQ=/\n+(?!\n|$)/g}function kQ({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 DQ(n,r);let l=r.indent||(r.forceBlockIndent||CQ(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===sQ.BLOCK_FOLDED?!1:t===sQ.BLOCK_LITERAL||!wQ(n,c,l.length);if(!n)return u?`|
|$)`,`g`)}catch{vQ=/\n+(?!\n|$)/g}function yQ({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 _Q(n,r);let l=r.indent||(r.forceBlockIndent||pQ(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===QZ.BLOCK_FOLDED?!1:t===QZ.BLOCK_LITERAL||!mQ(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(OQ,`$&${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(vQ,`$&${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=SQ(r,!0);o!==`folded`&&t!==sQ.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=bQ(`${v}${e}${p}`,l,vQ,a);if(!i)return`>${y}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${y}\n${l}${v}${n}${p}`}function AQ(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 DQ(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
`)?DQ(a,t):kQ(e,t,n,r);if(!s&&!u&&i!==sQ.PLAIN&&a.includes(`
`))return kQ(e,t,n,r);if(CQ(a)){if(c===``)return t.forceBlockIndent=!0,kQ(e,t,n,r);if(s&&c===l)return DQ(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 DQ(a,t)}return s?d:bQ(d,c,_Q,SQ(t,!1))}function jQ(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!==sQ.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=sQ.QUOTE_DOUBLE);let c=e=>{switch(e){case sQ.BLOCK_FOLDED:case sQ.BLOCK_LITERAL:return i||a?DQ(o.value,t):kQ(o,t,n,r);case sQ.QUOTE_DOUBLE:return TQ(o.value,t);case sQ.QUOTE_SINGLE:return EQ(o.value,t);case sQ.PLAIN:return AQ(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 MQ(e,t){let n=Object.assign({blockQuote:!0,commentString:mQ,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 NQ(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(FZ(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 PQ(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=(FZ(e)||LZ(e))&&e.anchor;a&&ZZ(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 FQ(e,t,n,r){if(PZ(e))return e.toString(t,n,r);if(jZ(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=RZ(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=NQ(t.doc.schema.tags,a);let o=PQ(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):FZ(a)?jQ(a,t,n,r):a.toString(t,n,r);return o?FZ(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}function IQ({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=RZ(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(LZ(e)||!RZ(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||LZ(e)||(FZ(e)?e.type===sQ.BLOCK_FOLDED||e.type===sQ.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=FQ(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+=gQ(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=gQ(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=gQ(g,n.indent,l(f))));let _,v,y;RZ(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&&FZ(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&IZ(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let b=!1,x=FQ(t,n,()=>b=!0,()=>h=!0),S=` `;if(f||_||v){if(S=_?`
`:``,v){let e=l(v);S+=`\n${hQ(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=fQ(r,!0);o!==`folded`&&t!==QZ.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=uQ(`${v}${e}${p}`,l,lQ,a);if(!i)return`>${y}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${y}\n${l}${v}${n}${p}`}function bQ(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 _Q(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
`)?_Q(a,t):yQ(e,t,n,r);if(!s&&!u&&i!==QZ.PLAIN&&a.includes(`
`))return yQ(e,t,n,r);if(pQ(a)){if(c===``)return t.forceBlockIndent=!0,yQ(e,t,n,r);if(s&&c===l)return _Q(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 _Q(a,t)}return s?d:uQ(d,c,cQ,fQ(t,!1))}function xQ(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!==QZ.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=QZ.QUOTE_DOUBLE);let c=e=>{switch(e){case QZ.BLOCK_FOLDED:case QZ.BLOCK_LITERAL:return i||a?_Q(o.value,t):yQ(o,t,n,r);case QZ.QUOTE_DOUBLE:return hQ(o.value,t);case QZ.QUOTE_SINGLE:return gQ(o.value,t);case QZ.PLAIN:return bQ(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 SQ(e,t){let n=Object.assign({blockQuote:!0,commentString:aQ,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 CQ(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(EZ(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 wQ(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=(EZ(e)||OZ(e))&&e.anchor;a&&HZ(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 TQ(e,t,n,r){if(TZ(e))return e.toString(t,n,r);if(SZ(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=kZ(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=CQ(t.doc.schema.tags,a);let o=wQ(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):EZ(a)?xQ(a,t,n,r):a.toString(t,n,r);return o?EZ(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}function EQ({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=kZ(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(OZ(e)||!kZ(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||OZ(e)||(EZ(e)?e.type===QZ.BLOCK_FOLDED||e.type===QZ.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=TQ(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+=sQ(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=sQ(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=sQ(g,n.indent,l(f))));let _,v,y;kZ(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&&EZ(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&DZ(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let b=!1,x=TQ(t,n,()=>b=!0,()=>h=!0),S=` `;if(f||_||v){if(S=_?`
`:``,v){let e=l(v);S+=`\n${oQ(e,n.indent)}`}x===``&&!n.inFlow?S===`
`&&y&&(S=`
`):S+=`\n${n.indent}`}else if(!p&&LZ(t)){let e=x[0],r=x.indexOf(`
`):S+=`\n${n.indent}`}else if(!p&&OZ(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+=gQ(g,n.indent,l(y)):h&&i&&i(),g}function LQ(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var RQ=`<<`,zQ={identify:e=>e===RQ||typeof e==`symbol`&&e.description===RQ,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new sQ(Symbol(RQ)),{addToJSMap:VQ}),stringify:()=>RQ},BQ=(e,t)=>(zQ.identify(t)||FZ(t)&&(!t.type||t.type===sQ.PLAIN)&&zQ.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===zQ.tag&&e.default);function VQ(e,t,n){let r=UQ(e,n);if(IZ(r))for(let n of r.items)HQ(e,t,n);else if(Array.isArray(r))for(let n of r)HQ(e,t,n);else HQ(e,t,r)}function HQ(e,t,n){let r=UQ(e,n);if(!NZ(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 UQ(e,t){return e&&jZ(t)?t.resolve(e.doc,e):t}function WQ(e,t,{key:n,value:r}){if(RZ(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(BQ(e,n))VQ(e,t,r);else{let i=nQ(n,``,e);if(t instanceof Map)t.set(i,nQ(r,i,e));else if(t instanceof Set)t.add(i);else{let a=GQ(n,i,e),o=nQ(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function GQ(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(RZ(e)&&n?.doc){let t=MQ(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)+`..."`),LQ(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 KQ(e,t,n){return new qQ(uQ(e,void 0,n),uQ(t,void 0,n))}var qQ=class e{constructor(e,t=null){Object.defineProperty(this,AZ,{value:DZ}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return RZ(n)&&(n=n.clone(t)),RZ(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return WQ(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?IQ(this,e,t,n):JSON.stringify(this)}};function JQ(e,t,n){return(t.inFlow??e.flow?XQ:YQ)(e,t,n)}function YQ({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(RZ(i))!d&&i.spaceBefore&&f.push(``),ZQ(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if(PZ(i)){let e=RZ(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),ZQ(n,f,e.commentBefore,d))}d=!1;let s=FQ(i,u,()=>o=null,()=>d=!0);o&&(s+=gQ(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+=sQ(g,n.indent,l(y)):h&&i&&i(),g}function DQ(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var OQ=`<<`,kQ={identify:e=>e===OQ||typeof e==`symbol`&&e.description===OQ,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new QZ(Symbol(OQ)),{addToJSMap:jQ}),stringify:()=>OQ},AQ=(e,t)=>(kQ.identify(t)||EZ(t)&&(!t.type||t.type===QZ.PLAIN)&&kQ.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===kQ.tag&&e.default);function jQ(e,t,n){let r=NQ(e,n);if(DZ(r))for(let n of r.items)MQ(e,t,n);else if(Array.isArray(r))for(let n of r)MQ(e,t,n);else MQ(e,t,r)}function MQ(e,t,n){let r=NQ(e,n);if(!wZ(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 NQ(e,t){return e&&SZ(t)?t.resolve(e.doc,e):t}function PQ(e,t,{key:n,value:r}){if(kZ(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(AQ(e,n))jQ(e,t,r);else{let i=qZ(n,``,e);if(t instanceof Map)t.set(i,qZ(r,i,e));else if(t instanceof Set)t.add(i);else{let a=FQ(n,i,e),o=qZ(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function FQ(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(kZ(e)&&n?.doc){let t=SQ(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)+`..."`),DQ(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 IQ(e,t,n){return new LQ(tQ(e,void 0,n),tQ(t,void 0,n))}var LQ=class e{constructor(e,t=null){Object.defineProperty(this,xZ,{value:vZ}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return kZ(n)&&(n=n.clone(t)),kZ(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return PQ(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?EQ(this,e,t,n):JSON.stringify(this)}};function RQ(e,t,n){return(t.inFlow??e.flow?BQ:zQ)(e,t,n)}function zQ({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(kZ(i))!d&&i.spaceBefore&&f.push(``),VQ(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if(TZ(i)){let e=kZ(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),VQ(n,f,e.commentBefore,d))}d=!1;let s=TQ(i,u,()=>o=null,()=>d=!0);o&&(s+=sQ(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+=`
`+hQ(l(e),c),s&&s()):d&&o&&o(),p}function XQ({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(RZ(i))i.spaceBefore&&d.push(``),ZQ(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(PZ(i)){let e=RZ(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),ZQ(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=RZ(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=FQ(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+=gQ(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 ZQ({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=hQ(t(r),e);n.push(i.trimStart())}}function QQ(e,t){let n=FZ(t)?t.value:t;for(let r of e)if(PZ(r)&&(r.key===t||r.key===n||FZ(r.key)&&r.key.value===n))return r}var $Q=class extends pQ{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(EZ,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(KQ(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=PZ(e)?e:!e||typeof e!=`object`||!(`key`in e)?new qQ(e,e?.value):new qQ(e.key,e.value);let r=QQ(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);FZ(r.value)&&oQ(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=QQ(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=QQ(this.items,e)?.value;return(!t&&FZ(n)?n.value:n)??void 0}has(e){return!!QQ(this.items,e)}set(e,t){this.add(new qQ(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)WQ(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!PZ(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})),JQ(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}},e$={collection:`map`,default:!0,nodeClass:$Q,tag:`tag:yaml.org,2002:map`,resolve(e,t){return NZ(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>$Q.from(e,t,n)},t$=class extends pQ{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(kZ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=n$(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=n$(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&FZ(r)?r.value:r}has(e){let t=n$(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=n$(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];FZ(r)&&oQ(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(nQ(e,String(r++),t));return n}toString(e,t,n){return e?JQ(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(uQ(a,void 0,n))}}return i}};function n$(e){let t=FZ(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var r$={collection:`seq`,default:!0,nodeClass:t$,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return IZ(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>t$.from(e,t,n)},i$={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),jQ(e,t,n,r)}},a$={identify:e=>e==null,createNode:()=>new sQ(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new sQ(null),stringify:({source:e},t)=>typeof e==`string`&&a$.test.test(e)?e:t.options.nullStr},o$={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new sQ(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},n){return e&&o$.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}};function s$({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 c$={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:s$},l$={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 jQ({comment:e,type:t,value:s},r,i,a)}};function C$(e,t){if(IZ(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!PZ(r)){if(NZ(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new qQ(new sQ(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]=PZ(r)?r:new qQ(r)}}else t(`Expected a sequence for this tag`);return e}function w$(e,t,n){let{replacer:r}=n,i=new t$(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(KQ(o,s,n))}return i}var T$={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:C$,createNode:w$},E$=class e extends t${constructor(){super(),this.add=$Q.prototype.add.bind(this),this.delete=$Q.prototype.delete.bind(this),this.get=$Q.prototype.get.bind(this),this.has=$Q.prototype.has.bind(this),this.set=$Q.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(PZ(e)?(r=nQ(e.key,``,t),i=nQ(e.value,r,t)):r=nQ(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=w$(e,t,n),i=new this;return i.items=r.items,i}};E$.tag=`tag:yaml.org,2002:omap`;var D$={collection:`seq`,identify:e=>e instanceof Map,nodeClass:E$,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=C$(e,t),r=[];for(let{key:e}of n.items)FZ(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new E$,n)},createNode:(e,t,n)=>E$.from(e,t,n)};function O$({value:e,source:t},n){return t&&(e?k$:A$).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var k$={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 sQ(!0),stringify:O$},A$={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 sQ(!1),stringify:O$},j$={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:s$},M$={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():s$(e)}},N$={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 sQ(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:s$},P$=e=>typeof e==`bigint`||Number.isInteger(e);function F$(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 I$(e,t,n){let{value:r}=e;if(P$(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return s$(e)}var L$={identify:P$,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>F$(e,2,2,n),stringify:e=>I$(e,2,`0b`)},R$={identify:P$,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>F$(e,1,8,n),stringify:e=>I$(e,8,`0`)},z$={identify:P$,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>F$(e,0,10,n),stringify:s$},B$={identify:P$,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>F$(e,2,16,n),stringify:e=>I$(e,16,`0x`)},V$=class e extends $Q{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=PZ(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new qQ(e.key,null):new qQ(e,null),QQ(this.items,t.key)||this.items.push(t)}get(e,t){let n=QQ(this.items,e);return!t&&PZ(n)?FZ(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=QQ(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new qQ(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(hQ(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(hQ(a(t),``)))}return n.join(`
`+oQ(l(e),c),s&&s()):d&&o&&o(),p}function BQ({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(kZ(i))i.spaceBefore&&d.push(``),VQ(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(TZ(i)){let e=kZ(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),VQ(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=kZ(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=TQ(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+=sQ(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 VQ({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=oQ(t(r),e);n.push(i.trimStart())}}function HQ(e,t){let n=EZ(t)?t.value:t;for(let r of e)if(TZ(r)&&(r.key===t||r.key===n||EZ(r.key)&&r.key.value===n))return r}var UQ=class extends iQ{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(_Z,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(IQ(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=TZ(e)?e:!e||typeof e!=`object`||!(`key`in e)?new LQ(e,e?.value):new LQ(e.key,e.value);let r=HQ(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);EZ(r.value)&&ZZ(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=HQ(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=HQ(this.items,e)?.value;return(!t&&EZ(n)?n.value:n)??void 0}has(e){return!!HQ(this.items,e)}set(e,t){this.add(new LQ(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)PQ(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!TZ(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})),RQ(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}},WQ={collection:`map`,default:!0,nodeClass:UQ,tag:`tag:yaml.org,2002:map`,resolve(e,t){return wZ(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>UQ.from(e,t,n)},GQ=class extends iQ{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(bZ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=KQ(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=KQ(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&EZ(r)?r.value:r}has(e){let t=KQ(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=KQ(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];EZ(r)&&ZZ(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(qZ(e,String(r++),t));return n}toString(e,t,n){return e?RQ(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(tQ(a,void 0,n))}}return i}};function KQ(e){let t=EZ(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var qQ={collection:`seq`,default:!0,nodeClass:GQ,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return DZ(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>GQ.from(e,t,n)},JQ={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),xQ(e,t,n,r)}},YQ={identify:e=>e==null,createNode:()=>new QZ(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new QZ(null),stringify:({source:e},t)=>typeof e==`string`&&YQ.test.test(e)?e:t.options.nullStr},XQ={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new QZ(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},n){return e&&XQ.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}};function ZQ({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 QQ={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:ZQ},$Q={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 xQ({comment:e,type:t,value:s},r,i,a)}};function p$(e,t){if(DZ(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!TZ(r)){if(wZ(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new LQ(new QZ(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]=TZ(r)?r:new LQ(r)}}else t(`Expected a sequence for this tag`);return e}function m$(e,t,n){let{replacer:r}=n,i=new GQ(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(IQ(o,s,n))}return i}var h$={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:p$,createNode:m$},g$=class e extends GQ{constructor(){super(),this.add=UQ.prototype.add.bind(this),this.delete=UQ.prototype.delete.bind(this),this.get=UQ.prototype.get.bind(this),this.has=UQ.prototype.has.bind(this),this.set=UQ.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(TZ(e)?(r=qZ(e.key,``,t),i=qZ(e.value,r,t)):r=qZ(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=m$(e,t,n),i=new this;return i.items=r.items,i}};g$.tag=`tag:yaml.org,2002:omap`;var _$={collection:`seq`,identify:e=>e instanceof Map,nodeClass:g$,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=p$(e,t),r=[];for(let{key:e}of n.items)EZ(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new g$,n)},createNode:(e,t,n)=>g$.from(e,t,n)};function v$({value:e,source:t},n){return t&&(e?y$:b$).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var y$={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 QZ(!0),stringify:v$},b$={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 QZ(!1),stringify:v$},x$={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:ZQ},S$={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():ZQ(e)}},C$={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 QZ(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:ZQ},w$=e=>typeof e==`bigint`||Number.isInteger(e);function T$(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 E$(e,t,n){let{value:r}=e;if(w$(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return ZQ(e)}var D$={identify:w$,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>T$(e,2,2,n),stringify:e=>E$(e,2,`0b`)},O$={identify:w$,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>T$(e,1,8,n),stringify:e=>E$(e,8,`0`)},k$={identify:w$,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>T$(e,0,10,n),stringify:ZQ},A$={identify:w$,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>T$(e,2,16,n),stringify:e=>E$(e,16,`0x`)},j$=class e extends UQ{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=TZ(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new LQ(e.key,null):new LQ(e,null),HQ(this.items,t.key)||this.items.push(t)}get(e,t){let n=HQ(this.items,e);return!t&&TZ(n)?EZ(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=HQ(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new LQ(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(oQ(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(oQ(a(t),``)))}return n.join(`
`)+`
`}var n1=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,AZ,{value:TZ});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 XZ({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[AZ]:{value:TZ}});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=RZ(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){r1(this.contents)&&this.contents.add(e)}addIn(e,t){r1(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=QZ(this);e.anchor=!t||n.has(t)?$Z(t||`a`,n):t}return new iQ(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}=eQ(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=uQ(e,l,p);return o&&LZ(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){return new qQ(this.createNode(e,null,n),this.createNode(t,null,n))}delete(e){return r1(this.contents)?this.contents.delete(e):!1}deleteIn(e){return fQ(e)?this.contents!=null&&(this.contents=null,!0):r1(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return LZ(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return fQ(e)?!t&&FZ(this.contents)?this.contents.value:this.contents:LZ(this.contents)?this.contents.getIn(e,t):void 0}has(e){return LZ(this.contents)?this.contents.has(e):!1}hasIn(e){return fQ(e)?this.contents!==void 0:LZ(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=dQ(this.schema,[e],t):r1(this.contents)&&this.contents.set(e,t)}setIn(e,t){fQ(e)?this.contents=t:this.contents==null?this.contents=dQ(this.schema,Array.from(e),t):r1(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 XZ({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 XZ({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 e1(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=nQ(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`?tQ(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 t1(this,e)}};function r1(e){if(LZ(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var i1=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},a1=class extends i1{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},o1=class extends i1{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},s1=(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 c1(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 l1(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(l1(t.key)||l1(t.value))return!0}return!1;default:return!0}}function u1(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&l1(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}function d1(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||FZ(e)&&FZ(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var f1=`All mapping items must start at the same column`;function p1({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??$Q)(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=c1(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`,f1)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
`+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||l1(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`,f1);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&u1(r.indent,u,i),n.atKey=!1,d1(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=c1(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&&u1(r.indent,f,i),s=c.range[2];let l=new qQ(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 qQ(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 m1({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??t$)(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=c1(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&&u1(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}function h1(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 g1=`Block collections are not allowed within flow collections`,_1=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function v1({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?$Q:t$))(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=c1(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&&l1(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];PZ(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],_1(m)&&i(r.range,`BLOCK_IN_FLOW`,g1)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);_1(f)&&i(g.range,`BLOCK_IN_FLOW`,g1),n.atKey=!1;let _=c1(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?_1(m)&&i(v.range,`BLOCK_IN_FLOW`,g1):_.comment&&(g.comment?g.comment+=`
`+_.comment:g.comment=_.comment);let y=new qQ(g,v);if(n.options.keepSourceTokens&&(y.srcToken=l),o){let e=c;d1(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(y)}else{let e=new $Q(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=h1(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 y1(e,t,n,r,i,a){let o=n.type===`block-map`?p1(e,t,n,r,a):n.type===`block-seq`?m1(e,t,n,r,a):v1(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function b1(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===$Q.tagName&&s===`map`||o===t$.tagName&&s===`seq`)return y1(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),y1(e,t,n,i,o)}let l=y1(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=RZ(u)?u:new sQ(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function x1(e,t,n){let r=t.offset,i=S1(t,e.options.strict,n);if(!i)return{value:``,type:null,comment:``,range:[r,r,r]};let a=i.mode===`>`?sQ.BLOCK_FOLDED:sQ.BLOCK_LITERAL,o=t.source?C1(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 K$=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,xZ,{value:gZ});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 VZ({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[xZ]:{value:gZ}});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=kZ(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){q$(this.contents)&&this.contents.add(e)}addIn(e,t){q$(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=UZ(this);e.anchor=!t||n.has(t)?WZ(t||`a`,n):t}return new YZ(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}=GZ(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=tQ(e,l,p);return o&&OZ(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){return new LQ(this.createNode(e,null,n),this.createNode(t,null,n))}delete(e){return q$(this.contents)?this.contents.delete(e):!1}deleteIn(e){return rQ(e)?this.contents!=null&&(this.contents=null,!0):q$(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return OZ(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return rQ(e)?!t&&EZ(this.contents)?this.contents.value:this.contents:OZ(this.contents)?this.contents.getIn(e,t):void 0}has(e){return OZ(this.contents)?this.contents.has(e):!1}hasIn(e){return rQ(e)?this.contents!==void 0:OZ(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=nQ(this.schema,[e],t):q$(this.contents)&&this.contents.set(e,t)}setIn(e,t){rQ(e)?this.contents=t:this.contents==null?this.contents=nQ(this.schema,Array.from(e),t):q$(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 VZ({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 VZ({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 W$(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=qZ(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`?KZ(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 G$(this,e)}};function q$(e){if(OZ(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var J$=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},Y$=class extends J${constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},X$=class extends J${constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},Z$=(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 Q$(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 $$(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($$(t.key)||$$(t.value))return!0}return!1;default:return!0}}function e1(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&$$(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}function t1(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||EZ(e)&&EZ(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var n1=`All mapping items must start at the same column`;function r1({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??UQ)(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=Q$(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`,n1)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
`+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||$$(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`,n1);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&e1(r.indent,u,i),n.atKey=!1,t1(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=Q$(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&&e1(r.indent,f,i),s=c.range[2];let l=new LQ(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 LQ(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 i1({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??GQ)(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=Q$(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&&e1(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}function a1(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 o1=`Block collections are not allowed within flow collections`,s1=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function c1({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?UQ:GQ))(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=Q$(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&&$$(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];TZ(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],s1(m)&&i(r.range,`BLOCK_IN_FLOW`,o1)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);s1(f)&&i(g.range,`BLOCK_IN_FLOW`,o1),n.atKey=!1;let _=Q$(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?s1(m)&&i(v.range,`BLOCK_IN_FLOW`,o1):_.comment&&(g.comment?g.comment+=`
`+_.comment:g.comment=_.comment);let y=new LQ(g,v);if(n.options.keepSourceTokens&&(y.srcToken=l),o){let e=c;t1(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(y)}else{let e=new UQ(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=a1(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 l1(e,t,n,r,i,a){let o=n.type===`block-map`?r1(e,t,n,r,a):n.type===`block-seq`?i1(e,t,n,r,a):c1(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function u1(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===UQ.tagName&&s===`map`||o===GQ.tagName&&s===`seq`)return l1(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),l1(e,t,n,i,o)}let l=l1(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=kZ(u)?u:new QZ(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function d1(e,t,n){let r=t.offset,i=f1(t,e.options.strict,n);if(!i)return{value:``,type:null,comment:``,range:[r,r,r]};let a=i.mode===`>`?QZ.BLOCK_FOLDED:QZ.BLOCK_LITERAL,o=t.source?p1(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===sQ.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===QZ.BLOCK_LITERAL?(d+=f+t.slice(c)+r,f=`
`):t.length>c||r[0]===` `?(f===` `?f=`
`:!p&&f===`
`&&(f=`
@@ -247,59 +247,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 S1({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 C1(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 w1(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=sQ.PLAIN,c=T1(a,l);break;case`single-quoted-scalar`:s=sQ.QUOTE_SINGLE,c=E1(a,l);break;case`double-quoted-scalar`:s=sQ.QUOTE_DOUBLE,c=O1(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=h1(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function T1(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}`),D1(e)}function E1(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),D1(e.slice(1,-1)).replace(/''/g,`'`)}function D1(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 f1({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 p1(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 m1(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=QZ.PLAIN,c=h1(a,l);break;case`single-quoted-scalar`:s=QZ.QUOTE_SINGLE,c=g1(a,l);break;case`double-quoted-scalar`:s=QZ.QUOTE_DOUBLE,c=v1(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=a1(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function h1(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}`),_1(e)}function g1(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),_1(e.slice(1,-1)).replace(/''/g,`'`)}function _1(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 O1(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 v1(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}=k1(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=A1[i];if(a)n+=a;else if(i===`
`){let{fold:t,offset:i}=y1(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=b1[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+=j1(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+=x1(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 k1(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 y1(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 A1={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
`,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function j1(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 M1(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?x1(e,t,r):w1(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[OZ]:c?N1(e.schema,i,c,n,r):t.type===`scalar`?P1(e,i,t,r):e.schema[OZ];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=FZ(a)?a:new sQ(a)}catch(e){let a=e instanceof Error?e.message:String(e);r(n??t,`TAG_RESOLVE_FAILED`,a),u=new sQ(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 N1(e,t,n,r,i){if(n===`!`)return e[OZ];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[OZ])}function P1({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[OZ];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[OZ];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 F1(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 I1={composeNode:L1,composeEmptyNode:R1};function L1(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=z1(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=M1(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=b1(I1,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??=R1(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&&(!FZ(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 R1(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=M1(e,{type:`scalar`,offset:F1(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 z1({options:e},{offset:t,source:n,end:r},i){let a=new iQ(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=h1(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}function B1(e,t,{offset:n,start:r,value:i,end:a},o){let s=new n1(void 0,Object.assign({_directives:t},e)),c={atKey:!1,atRoot:!0,directives:s.directives,options:s.options,schema:s.schema},l=c1(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?L1(c,i,l,o):R1(c,l.end,r,null,l,o);let u=s.contents.range[2],d=h1(a,u,!1,o);return d.comment&&(s.comment=d.comment),s.range=[n,u,d.offset],s}function V1(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 H1(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 b1={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
`,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function x1(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 S1(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?d1(e,t,r):m1(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[yZ]:c?C1(e.schema,i,c,n,r):t.type===`scalar`?w1(e,i,t,r):e.schema[yZ];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=EZ(a)?a:new QZ(a)}catch(e){let a=e instanceof Error?e.message:String(e);r(n??t,`TAG_RESOLVE_FAILED`,a),u=new QZ(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 C1(e,t,n,r,i){if(n===`!`)return e[yZ];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[yZ])}function w1({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[yZ];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[yZ];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 T1(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 E1={composeNode:D1,composeEmptyNode:O1};function D1(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=k1(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=S1(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=u1(E1,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??=O1(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&&(!EZ(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 O1(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=S1(e,{type:`scalar`,offset:T1(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 k1({options:e},{offset:t,source:n,end:r},i){let a=new YZ(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=a1(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}function A1(e,t,{offset:n,start:r,value:i,end:a},o){let s=new K$(void 0,Object.assign({_directives:t},e)),c={atKey:!1,atRoot:!0,directives:s.directives,options:s.options,schema:s.schema},l=Q$(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?D1(c,i,l,o):O1(c,l.end,r,null,l,o);let u=s.contents.range[2],d=a1(a,u,!1,o);return d.comment&&(s.comment=d.comment),s.range=[n,u,d.offset],s}function j1(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 M1(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 U1=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=V1(e);r?this.warnings.push(new o1(i,t,n)):this.errors.push(new a1(i,t,n))},this.directives=new XZ({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=H1(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(LZ(i)&&!i.flow&&i.items.length>0){let e=i.items[0];PZ(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:H1(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=V1(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=B1(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 a1(V1(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 a1(V1(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=h1(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 a1(V1(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 n1(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}}},W1=Symbol(`break visit`),G1=Symbol(`skip children`),K1=Symbol(`remove item`);function q1(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),J1(Object.freeze([]),e,t)}q1.BREAK=W1,q1.SKIP=G1,q1.REMOVE=K1,q1.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},q1.parentCollection=(e,t)=>{let n=q1.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 J1(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=J1(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===W1)return W1;else r===K1&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}function Y1(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 N1=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=j1(e);r?this.warnings.push(new X$(i,t,n)):this.errors.push(new Y$(i,t,n))},this.directives=new VZ({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=M1(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(OZ(i)&&!i.flow&&i.items.length>0){let e=i.items[0];TZ(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:M1(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=j1(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=A1(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 Y$(j1(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 Y$(j1(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=a1(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 Y$(j1(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 K$(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}}},P1=Symbol(`break visit`),F1=Symbol(`skip children`),I1=Symbol(`remove item`);function L1(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),R1(Object.freeze([]),e,t)}L1.BREAK=P1,L1.SKIP=F1,L1.REMOVE=I1,L1.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},L1.parentCollection=(e,t)=>{let n=L1.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 R1(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=R1(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===P1)return P1;else r===I1&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}function z1(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 X1(e){switch(e){case void 0:case` `:case`
`:case`\r`:case` `:return!0;default:return!1}}var Z1=new Set(`0123456789ABCDEFabcdef`),Q1=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),$1=new Set(`,[]{}`),e0=new Set(` ,[]{}
\r `),t0=e=>!e||e0.has(e),n0=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 B1(e){switch(e){case void 0:case` `:case`
`:case`\r`:case` `:return!0;default:return!1}}var V1=new Set(`0123456789ABCDEFabcdef`),H1=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),U1=new Set(`,[]{}`),W1=new Set(` ,[]{}
\r `),G1=e=>!e||W1.has(e),K1=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===`...`)&&X1(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===`...`)&&X1(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&&!X1(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===`:`)&&X1(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(t0),`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(`...`))&&X1(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(t0),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||X1(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===`...`)&&B1(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===`...`)&&B1(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&&!B1(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===`:`)&&B1(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(G1),`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(`...`))&&B1(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(G1),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||B1(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=>X1(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=>B1(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(X1(r)||e&&$1.has(r))break;t=n}else if(X1(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(B1(r)||e&&U1.has(r))break;t=n}else if(B1(r)){let i=this.buffer[n+1];if(r===`\r`&&(i===`
`?(n+=1,r=`
`,i=this.buffer[n+1]):t=n),i===`#`||e&&$1.has(i))break;if(r===`
`){let e=this.continueScalar(n+1);if(e===-1)break;n=Math.max(n,e-2)}}else{if(e&&$1.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(t0),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(X1(n)||t&&$1.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(;!X1(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(Q1.has(t))t=this.buffer[++e];else if(t===`%`&&Z1.has(this.buffer[e+1])&&Z1.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&&U1.has(i))break;if(r===`
`){let e=this.continueScalar(n+1);if(e===-1)break;n=Math.max(n,e-2)}}else{if(e&&U1.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(G1),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(B1(n)||t&&U1.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(;!B1(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(H1.has(t))t=this.buffer[++e];else if(t===`%`&&V1.has(this.buffer[e+1])&&V1.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)}},r0=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 i0(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function a0(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 o0(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 s0(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 c0(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 l0(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 u0(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!i0(t.start,`explicit-key-ind`)&&!i0(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,o0(t.value)?t.value.end?l0(t.value.end,t.sep):t.value.end=t.sep:l0(t.start,t.sep),delete t.sep)}var d0=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 n0,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=Y1(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`&&u0(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&&a0(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)}},q1=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 J1(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Y1(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 X1(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 Z1(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 Q1(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 $1(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 e0(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!J1(t.start,`explicit-key-ind`)&&!J1(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,X1(t.value)?t.value.end?$1(t.value.end,t.sep):t.value.end=t.sep:$1(t.start,t.sep),delete t.sep)}var t0=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 K1,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=z1(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`&&e0(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&&Y1(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)){l0(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(i0(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=c0(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(i0(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(o0(t.key)&&!i0(t.sep,`newline`)){let e=c0(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]}):i0(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&&!i0(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)){l0(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||i0(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)){$1(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(J1(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=Q1(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(J1(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(X1(t.key)&&!J1(t.sep,`newline`)){let e=Q1(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]}):J1(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&&!J1(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)){$1(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||J1(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=c0(s0(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=c0(s0(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 f0(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new r0||null,prettyErrors:t}}function p0(e,t={}){let{lineCounter:n,prettyErrors:r}=f0(t),i=new d0(n?.addNewLine),a=new U1(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 a1(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(s1(e,n)),o.warnings.forEach(s1(e,n))),o}function m0(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let i=p0(e,n);if(!i)return null;if(i.warnings.forEach(e=>LQ(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 h0(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 MZ(e)&&!r?e.toString(n):new n1(e,r,n).toString(n)}var g0=e=>typeof e==`object`&&!!e&&!Array.isArray(e),_0=e=>g0(e)?Object.entries(e).map(([e,t])=>[e,Array.isArray(t)?t:[]]):[];function v0(e){if(g0(e)){if(g0(e.parallel))return{kind:`parallel`,base:[`parallel`],branches:_0(e.parallel)};if(g0(e.switch))return{kind:`switch`,base:[`switch`,`cases`],on:typeof e.switch.on==`string`?e.switch.on:``,branches:_0(e.switch.cases)}}}function y0(e){return e.slice(2).includes(`parallel`)}function b0(e,t){let n=p0(e).getIn(t,!0);if(NZ(n))return n.toJSON()}function x0(e,t,n){let r=p0(e);return r.setIn(t,r.createNode(N0(n))),r.toString()}function S0(e,t,n){let r=p0(e),i=t.slice(0,-1),a=y0(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(IZ(o)||(r.setIn(i,r.createNode([])),o=r.getIn(i,!0)),!IZ(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 C0(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 w0(e,t){let n=e.getIn(t,!0),r=v0(NZ(n)?n.toJSON():void 0),i=r?e.getIn([...t,...r.base],!0):void 0;if(!r||!NZ(i))throw Error(`This step has no branches.`);return{kind:r.kind,branches:i}}function T0(e,t,n){let r=p0(e),{kind:i,branches:a}=w0(r,t);if(C0(n,i),a.has(n))throw Error(`Branch ${n} already exists.`);return a.set(n,r.createNode([])),r.toString()}function E0(e,t,n,r){let i=p0(e),{kind:a,branches:o}=w0(i,t);if(C0(r,a),n!==r&&o.has(r))throw Error(`Branch ${r} already exists.`);let s=o.items.find(e=>FZ(e.key)&&e.key.value===n);if(!s||!FZ(s.key))throw Error(`Branch ${n} does not exist.`);return s.key.value=r,i.toString()}function D0(e,t,n){let r=p0(e),{kind:i,branches:a}=w0(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 J0(e,t){let n=JSON.stringify(e??{})+` `+(typeof t==`string`?`{{ ${t.replace(/^!/,``)} }}`:``);return[...new Set([...n.matchAll(W0)].map(e=>e[1]))]}function Y0(e){let t=p0(e).toJS(),n=G0(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=G0(e)?e:{},p=v0(d),m=p?.kind??(typeof d.type==`string`?d.type:``),h=G0(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,name:g||void 0,title:g||U0(m),type:m,step:l?.length===2?String(Number(l[1])+1).padStart(2,`0`):void 0,detail:p?.on?`on ${p.on.replace(/^steps\./,``)}`:K0(m,h),summary:q0(h),when:typeof d.when==`string`?d.when:void 0,retry:G0(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 J0([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=v0(t);if(n){let{kind:i,base:a,branches:o}=n,c=p(t,String(e+1),0,u*B0,void 0,void 0,[`steps`,e]);m(l,c,[`steps`,e-1]),u++;let d=G0(t)&&typeof t.id==`string`?t.id:i,f=i===`switch`&&!o.some(([e])=>e==="default"),h=o.length+ +!!f,g=[],_=Math.max(1,...o.map(([,e])=>e.length)),v=e=>(e-(h-1)/2)*V0,y=(e,t,n)=>r.push({id:e,type:`lane`,position:{x:t-12,y:u*B0-40},style:{width:`264px`,height:`${(_+1)*B0-24}px`},zIndex:-1,data:{kind:`step`,key:n,title:n,type:``,detail:``,lane:i}}),b=(u+_)*B0;if(o.forEach(([t,n],o)=>{let s=v(o),l=[c],f=[`steps`,e,...a,t];n.forEach((n,r)=>{let a=p(n,`${e+1}-${t}-${r+1}`,s,(u+r)*B0,t,d,[...f,r],i);m(l,a,[...f,r-1]),l=[a]});let h=`add-${e}-${t}`;r.push({id:h,type:`add`,position:{x:s+104,y:b},data:{kind:`step`,key:h,title:``,type:``,detail:``,branch:t,lane:i,insertAfter:[...f,n.length-1]}}),m(l,h),g.push(h),y(`lane-${e}-${t}`,s,t)}),f){let t=v(h-1),n=`pass-${e}`;r.push({id:n,type:`add`,position:{x:t+104,y:b},data:{kind:`step`,key:n,title:``,type:``,detail:``,lane:i}}),s.add(c),m([c],n),s.delete(c),g.push(n),y(`pass-lane-${e}`,t,`default`)}l=g,u+=_+1;continue}let i=p(t,String(e+1),0,u*B0,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*B0-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 X0={class:`truncate`},Z0=`\0`,Q0=P({inheritAttrs:!1,__name:`OptionSelect`,props:{modelValue:{},options:{},placeholder:{},disabled:{type:Boolean},size:{},class:{}},emits:[`update:modelValue`],setup(e,{emit:t}){let n=t;return(t,r)=>(L(),q(V(Bu),{"model-value":e.modelValue===``&&e.options.some(e=>e.value===``)?Z0:e.modelValue||void 0,disabled:e.disabled,"onUpdate:modelValue":r[0]||=e=>n(`update:modelValue`,e===Z0?``:String(e))},{default:I(()=>[A(V(Wu),G({size:e.size??`sm`,class:t.$props.class},t.$attrs),{default:I(()=>[A(V(Gu),{placeholder:e.placeholder},null,8,[`placeholder`])]),_:1},16,[`size`,`class`]),A(V(Vu),{position:`popper`,class:`max-w-[min(var(--reka-select-content-available-width),20rem)]`},{default:I(()=>[(L(!0),j(U,null,M(e.options,e=>(L(),q(V(Uu),{key:e.value,value:e.value===``?Z0:e.value,disabled:e.disabled,title:e.label,class:`*:[span]:last:min-w-0`},{default:I(()=>[R(`span`,X0,B(e.label),1)]),_:2},1032,[`value`,`disabled`,`title`]))),128))]),_:1})]),_:1},8,[`model-value`,`disabled`]))}}),$0=[`id`],e2=[`value`],t2=P({__name:`WorkflowPicker`,props:{value:{},workflows:{},label:{},class:{},editable:{type:Boolean}},emits:[`pick`],setup(e,{emit:t}){let n=we(),r=t;return(t,i)=>e.editable?(L(),j(U,{key:0},[A(V(Q),{"model-value":e.value,list:V(n),"aria-label":e.label,class:z(t.$props.class),placeholder:`Workflow id or {{ reference }}`,"onUpdate:modelValue":i[0]||=e=>r(`pick`,String(e))},null,8,[`model-value`,`list`,`aria-label`,`class`]),R(`datalist`,{id:V(n)},[(L(!0),j(U,null,M(e.workflows,e=>(L(),j(`option`,{key:e.id,value:e.id},null,8,e2))),128))],8,$0)],64)):(L(),q(V(Bu),{key:1,"model-value":e.value||void 0,"onUpdate:modelValue":i[1]||=e=>r(`pick`,String(e))},{default:I(()=>[A(V(Wu),{"aria-label":e.label,class:z(t.$props.class)},{default:I(()=>[A(V(Gu),{placeholder:`Choose workflow`})]),_:1},8,[`aria-label`,`class`]),A(V(Vu),null,{default:I(()=>[e.value& Line truncated
`).map((e,t)=>({number:t+1,text:e,tokens:h2(e)}))}var p2=/^(\s*)(-\s+)?/,m2=/^([^:#\s][^:#]*?)(:)(\s*)(.*)$/;function h2(e){let{code:t,comment:n}=g2(e),r=_2(t);return n&&r.push({text:n,kind:`comment`}),r}function g2(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 _2(e){if(!e)return[];let t=[],n=p2.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=m2.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,...v2(i[4]??``)]):[...t,...v2(r)]}function v2(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 y2(e){return e.split(`
`)[0]?.trim()||`invalid YAML`}function b2(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function x2(e){return typeof e==`string`&&e.trim()!==``}var S2={class:`space-y-4 px-3 py-3`},C2={key:0,class:`rounded-md bg-danger/10 px-2.5 py-1.5 text-xs text-danger`,role:`alert`},w2={key:1,class:`space-y-3`},T2={key:0,class:`block space-y-1.5`},E2=[`id`],D2=[`value`],O2={class:`text-xs font-medium text-fg-muted`},k2={class:`flex items-center gap-2`},A2={key:1,role:`alert`,class:`text-xs text-danger`},j2={key:2,class:`space-y-1.5`},M2=[`title`],N2={key:4,class:`flex flex-wrap items-center gap-1 pt-0.5`},P2={key:0,class:`divide-y divide-border rounded-md border border-border`},F2=[`title`],I2={key:0,class:`space-y-3`},L2={class:`text-label`},R2={key:0,class:`text-danger`},z2={class:`ml-2 text-xs text-fg-subtle`},B2={key:1,class:`space-y-3`},V2={class:`text-label`},H2={class:`ml-2 text-xs text-fg-subtle`},U2=[`title`],W2={key:0,class:`text-xs text-danger`},G2={class:`space-y-1.5`},K2={key:0,role:`alert`,class:`text-xs text-danger`},q2={class:`divide-y divide-border rounded-md border border-border`},J2={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},Y2={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},X2={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},Z2={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},Q2=[`for`],$2=P({__name:`StepEditor`,props:{yaml:{},path:{},vocabulary:{},workflows:{},modelAliases:{}},emits:[`update:yaml`],setup(e,{emit:t}){let n=we(),r=e,i=t,a=Y(()=>b0(r.yaml,r.path)??{}),o=Y(()=>v0(a.value)),s=Y(()=>o.value?.kind??(typeof a.value.type==`string`?a.value.type:``)),c=Y(()=>o.value?.branches.map(([e])=>e)??[]),l=Y(()=>s.value===`parallel`?2:1);function u(e){i(`update:yaml`,x0(r.yaml,r.path,{...a.value,switch:{...a.value.switch,on:e}}))}let d=J(``),f=J(``);function p(e,t,n=``){try{let a=e===`add`?T0(r.yaml,r.path,t):e===`rename`?E0(r.yaml,r.path,t,n):D0(r.yaml,r.path,t);i(`update:yaml`,a),d.value=``,f.value=``}catch(e){f.value=String(e.message)}}let m=Y(()=>r.vocabulary.find(e=>e.name===s.value)),h=Y(()=>typeof a.value.settings==`object`&&a.value.settings!==null?a.value.settings:{}),g=Y(()=>M0(r.yaml,r.path)),_=Y(()=>c2(a.value)),v=Y(()=>m.value?.settings&&a.value.settings?u2(a.value.settings,m.value.settings,`settings`):``),y=[`mission`,`workflow`,`message`,`body`,`plan`,`then`,`status`,`detail`,`run`,`rules`],b=/mission|body|detail|plan|rules/;function x(e,t){return[`workflow.call`,`workflow.handoff`].includes(s.value)&&e===`workflow`||s.value===`workflow.approve`&&e===`then`?`workflow`:s.value===`agent.run`&&e===`model`?`select`:t.type===`string`?t.enum?`select`:b.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 S=Y(()=>{let e=Object.entries(m.value?.settings?.properties??{}).filter(([e])=>s.value!==`workflow.call`||![`inputs`,`outputs`].includes(e)).map(([e,t])=>({key:e,schema:t,kind:x(e,t),options:s.value===`agent.run`&&e===`model`?r.modelAliases:t.enum??[]})),t=e.filter(e=>y.includes(e.key)&&e.kind!==`boolean`).sort((e,t)=>y.indexOf(e.key)-y.indexOf(t.key))[0],n=e.filter(e=>e!==t);return{lead:t,compact:n.filter(e=>[`workflow`,`select`,`line`,`number`,`boolean`].includes(e.kind)),long:n.filter(e=>[`text`,`lines`,`yaml`].includes(e.kind))}}),C=J(!S.value.lead&&!o.value),w=e=>[{value:``,label:`Default`},...e.map(e=>({value:e,label:e}))];function T(e){let{id:t,type:n,...a}=e;i(`update:yaml`,x0(r.yaml,r.path,{id:t,type:n,...a}))}function ee(e,t){T({...a.value,[e]:t})}function te(e){let t={...a.value.retry,...e};ee(`retry`,t.attempts===void 0&&!t.backoff?void 0:{...t,attempts:t.attempts??1})}function E(e,t){let n={...h.value,[e]:t};s.value===`workflow.call`&&e===`wait`&&t!==!0&&delete n.outputs,T({...a.value,settings:n})}function ne(e,t){let n={...h.value,[e]:t};s.value===`workflow.call`&&t!==h.value[e]&&(delete n.inputs,delete n.outputs),T({...a.value,settings:n})}let D=Y(()=>r.workflows.find(e=>e.id===h.value.workflow)),re=Y(()=>Object.entries(P0(D.value?.yaml??``,`inputs`)??{})),ie=Y(()=>Object.entries(P0(D.value?.yaml??``,`outputs`)??{})),ae=Y(()=>Object.entries(P0(r.yaml,`inputs`)??{})),k=Y(()=>Object.entries(P0(r.yaml,`outputs`)??{})),oe=Y(()=>h.value.inputs??{}),se=Y(()=>h.value.outputs??{}),ce=e=>typeof e==`string`&&e.startsWith(`inputs.`),le=e=>[`object`,`array`].includes(e.type??``),ue=e=>oe.value[e]===void 0?``:String(oe.value[e]);function de(e,t,n){E(`inputs`,{...oe.value,[e]:t===``?void 0:ce(t)?t:ZE(t,n??`string`)})}let fe=(e,t,n)=>e.filter(([,e])=>e.type===t.type||e.type===`any`||t.type===`any`).map(([e])=>({value:`${n}.${e}`,label:e})),pe=J(null);function me(e){let t=pe.value??S.value.lead?.key;if(!t)return;let n=typeof h.value[t]==`string`?h.value[t]:``,r=`{{ steps.${e}.summary }}`;E(t,n?`${n.trimEnd()} ${r}`:r)}let he=J({});function ge(e,t){try{E(e,t.trim()?m0(t):void 0),he.value={...he.value,[e]:``}}catch(t){he.value={...he.value,[e]:String(t.me Line truncated
`)[0]}}}let _e=e=>e===void 0?``:h0(e).trimEnd(),ve=(e,t)=>t.title??e.replaceAll(`_`,` `).replace(/^./,e=>e.toUpperCase()),ye=e=>typeof h.value[e]==`string`?h.value[e]:``,N=[{value:``,label:`Park the task`},{value:`continue`,label:`Continue`}];return(t,r)=>(L(),j(`div`,S2,[v.value?(L(),j(`p`,C2,B(v.value),1)):F(``,!0),o.value?(L(),j(`section`,w2,[s.value===`switch`?(L(),j(`label`,T2,[r[15]||=R(`span`,{class:`text-xs font-medium text-fg-muted`,title:`The value whose case runs; a case named default runs when none matches`},`Switch on`,-1),A(V(Q),{"model-value":o.value.on,class:`font-mono`,placeholder:`steps.assess.result.fit`,list:`${V(n)}-switch-on`,onChange:r[0]||=e=>u(e.target.value.trim())},null,8,[`model-value`,`list`]),R(`datalist`,{id:`${V(n)}-switch-on`},[(L(!0),j(U,null,M(g.value,e=>(L(),j(`option`,{key:e,value:`steps.${e}.result.`},null,8,D2))),128))],8,E2)])):F(``,!0),R(`div`,O2,B(s.value===`switch`?`Cases`:`Branches`),1),(L(!0),j(U,null,M(c.value,e=>(L(),j(`div`,{key:e,class:`flex items-center gap-2`},[A(V(Q),{"model-value":e,class:z(s.value===`switch`&&`font-mono`),"aria-label":`${s.value===`switch`?`Case`:`Branch`} ${e}`,onChange:t=>p(`rename`,e,t.target.value.trim())},null,8,[`model-value`,`class`,`aria-label`,`onChange`]),A(V(X),{type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":`Remove ${e}`,disabled:c.value.length<=l.value,onClick:t=>p(`delete`,e)},{default:I(()=>[A(V(ju))]),_:1},8,[`aria-label`,`disabled`,`onClick`])]))),128)),R(`div`,k2,[A(V(Q),{modelValue:d.value,"onUpdate:modelValue":r[1]||=e=>d.value=e,"aria-label":s.value===`switch`?`New case value`:`New branch name`,placeholder:s.value===`switch`?`Value, or default`:`Branch name`,onKeydown:r[2]||=gt(pt(e=>p(`add`,d.value.trim()),[`prevent`]),[`enter`])},null,8,[`modelValue`,`aria-label`,`placeholder`]),A(V(X),{type:`button`,size:`icon-sm`,variant:`outline`,"aria-label":s.value===`switch`?`Add case`:`Add branch`,disabled:!d.value.trim(),onClick:r[3]||=e=>p(`add`,d.value.trim())},{default:I(()=>[A(V(Tu))]),_:1},8,[`aria-label`,`disabled`])]),f.value?(L(),j(`p`,A2,B(f.value),1)):F(``,!0)])):F(``,!0),S.value.lead?(L(),j(`section`,j2,[R(`div`,{class:`flex items-center gap-1 text-xs font-medium text-fg-muted`,title:S.value.lead.schema.description},[H(B(ve(S.value.lead.key,S.value.lead.schema))+` `,1),S.value.lead.schema.description?(L(),q(V(Kl),{key:0,class:`size-3 text-fg-subtle`})):F(``,!0)],8,M2),S.value.lead.kind===`workflow`?(L(),q(t2,{key:0,editable:s.value!==`workflow.call`,value:ye(S.value.lead.key),workflows:e.workflows,label:ve(S.value.lead.key,S.value.lead.schema),onPick:r[4]||=e=>ne(S.value.lead.key,e)},null,8,[`editable`,`value`,`workflows`,`label`])):S.value.lead.kind===`select`?(L(),q(Q0,{key:1,class:`w-full`,"model-value":ye(S.value.lead.key),options:w(S.value.lead.options),"aria-label":ve(S.value.lead.key,S.value.lead.schema),"onUpdate:modelValue":r[5]||=e=>E(S.value.lead.key,e||void 0)},null,8,[`model-value`,`options`,`aria-label`])):S.value.lead.kind===`text`?(L(),q(V(Wd),{key:2,"model-value":ye(S.value.lead.key),class:`min-h-32 text-label leading-relaxed`,onFocus:r[6]||=e=>pe.value=S.value.lead.key,"onUpdate:modelValue":r[7]||=e=>E(S.value.lead.key,String(e))},null,8,[`model-value`])):(L(),q(V(Q),{key:3,"model-value":ye(S.value.lead.key),onFocus:r[8]||=e=>pe.value=S.value.lead.key,"onUpdate:modelValue":r[9]||=e=>E(S.value.lead.key,String(e))},null,8,[`model-value`])),g.value.length&&S.value.lead.kind!==`select`?(L(),j(`div`,N2,[r[16]||=R(`span`,{class:`text-caption text-fg-subtle`},`Insert`,-1),(L(!0),j(U,null,M(g.value,e=>(L(),q(V(X),{key:e,type:`button`,variant:`outline`,size:`xs`,class:`font-mono`,title:`{{ steps.${e}.summary }}`,onClick:t=>me(e)},{default:I(()=>[H(B(e),1)]),_:2},1032,[`title`,`onClick`]))),128))])):F(``,!0)])):F(``,!0),A(V(X),{type:`button`,variant:`ghost`,size:`xs`,class:`-ml-2 text-fg-muted aria-expanded:bg-transparent`,"aria-expanded":C.value,onClick:r[10]||=e=>C.value=!C.value},{default:I(()=>[A(V(O),{"data-icon":`inline-start`,class:z([`transition-transform`,!C.value&&`-rotate-90`])},null,8,[`class`]),r[17]||=H(`More `,-1)]),_:1},8,[`aria-expanded`]),C.value?(L(),j(U,{key:3},[S.value.compact.length?(L(),j(`section`,P2,[(L(!0),j(U,null,M(S.value.compact,t=>(L(),j(`div`,{key:t.key,class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},[R(`span`,{class:`flex flex-1 items-center gap-1 text-label`,title:t.schema.description},[H(B(ve(t.key,t.schema))+` `,1),t.schema.description?(L(),q(V(Kl),{key:0,class:`size-3 text-fg-subtle`})):F(``,!0)],8,F2),t.kind===`workflow`?(L(),q(t2,{key:0,editable:s.value!==`workflow.call`,class:`max-w-48`,value:ye(t.key),workflows:e.workflows,label:ve(t.key,t.schema),onPick:e=>ne(t.key,e)},null,8,[`editable`,`value`,`workflows`,`label`,`onPick`])):t.kind===`boolean`?(L(),q(V(aT),{key:1,"model-value":h.value[t.key]===!0,"onUpdate:modelValue":e=>E(t.key,e||void 0)},null,8,[`model-value`,`onUpdate:modelValue`])):t.kind===`select`?(L(),q(Q0,{key:2,class:`w-40`,"model-val Line 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=Q1(Z1(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=Q1(Z1(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 n0(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new q1||null,prettyErrors:t}}function r0(e,t={}){let{lineCounter:n,prettyErrors:r}=n0(t),i=new t0(n?.addNewLine),a=new N1(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 Y$(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(Z$(e,n)),o.warnings.forEach(Z$(e,n))),o}function i0(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let i=r0(e,n);if(!i)return null;if(i.warnings.forEach(e=>DQ(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 a0(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 CZ(e)&&!r?e.toString(n):new K$(e,r,n).toString(n)}var o0=e=>typeof e==`object`&&!!e&&!Array.isArray(e),s0=e=>o0(e)?Object.entries(e).map(([e,t])=>[e,Array.isArray(t)?t:[]]):[];function c0(e){if(o0(e)){if(o0(e.parallel))return{kind:`parallel`,base:[`parallel`],branches:s0(e.parallel)};if(o0(e.switch))return{kind:`switch`,base:[`switch`,`cases`],on:typeof e.switch.on==`string`?e.switch.on:``,branches:s0(e.switch.cases)}}}function l0(e){return e.slice(2).includes(`parallel`)}function u0(e,t){let n=r0(e).getIn(t,!0);if(wZ(n))return n.toJSON()}function d0(e,t,n){let r=r0(e);return r.setIn(t,r.createNode(C0(n))),r.toString()}function f0(e,t,n){let r=r0(e),i=t.slice(0,-1),a=l0(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(DZ(o)||(r.setIn(i,r.createNode([])),o=r.getIn(i,!0)),!DZ(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 p0(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 m0(e,t){let n=e.getIn(t,!0),r=c0(wZ(n)?n.toJSON():void 0),i=r?e.getIn([...t,...r.base],!0):void 0;if(!r||!wZ(i))throw Error(`This step has no branches.`);return{kind:r.kind,branches:i}}function h0(e,t,n){let r=r0(e),{kind:i,branches:a}=m0(r,t);if(p0(n,i),a.has(n))throw Error(`Branch ${n} already exists.`);return a.set(n,r.createNode([])),r.toString()}function g0(e,t,n,r){let i=r0(e),{kind:a,branches:o}=m0(i,t);if(p0(r,a),n!==r&&o.has(r))throw Error(`Branch ${r} already exists.`);let s=o.items.find(e=>EZ(e.key)&&e.key.value===n);if(!s||!EZ(s.key))throw Error(`Branch ${n} does not exist.`);return s.key.value=r,i.toString()}function _0(e,t,n){let r=r0(e),{kind:i,branches:a}=m0(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 R0(e,t){let n=JSON.stringify(e??{})+` `+(typeof t==`string`?`{{ ${t.replace(/^!/,``)} }}`:``);return[...new Set([...n.matchAll(P0)].map(e=>e[1]))]}function z0(e){let t=r0(e).toJS(),n=F0(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=F0(e)?e:{},p=c0(d),m=p?.kind??(typeof d.type==`string`?d.type:``),h=F0(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,name:g||void 0,title:g||N0(m),type:m,step:l?.length===2?String(Number(l[1])+1).padStart(2,`0`):void 0,detail:p?.on?`on ${p.on.replace(/^steps\./,``)}`:I0(m,h),summary:L0(h),when:typeof d.when==`string`?d.when:void 0,retry:F0(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 R0([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=c0(t);if(n){let{kind:i,base:a,branches:o}=n,c=p(t,String(e+1),0,u*A0,void 0,void 0,[`steps`,e]);m(l,c,[`steps`,e-1]),u++;let d=F0(t)&&typeof t.id==`string`?t.id:i,f=i===`switch`&&!o.some(([e])=>e==="default"),h=o.length+ +!!f,g=[],_=Math.max(1,...o.map(([,e])=>e.length)),v=e=>(e-(h-1)/2)*j0,y=(e,t,n)=>r.push({id:e,type:`lane`,position:{x:t-12,y:u*A0-40},style:{width:`264px`,height:`${(_+1)*A0-24}px`},zIndex:-1,data:{kind:`step`,key:n,title:n,type:``,detail:``,lane:i}}),b=(u+_)*A0;if(o.forEach(([t,n],o)=>{let s=v(o),l=[c],f=[`steps`,e,...a,t];n.forEach((n,r)=>{let a=p(n,`${e+1}-${t}-${r+1}`,s,(u+r)*A0,t,d,[...f,r],i);m(l,a,[...f,r-1]),l=[a]});let h=`add-${e}-${t}`;r.push({id:h,type:`add`,position:{x:s+104,y:b},data:{kind:`step`,key:h,title:``,type:``,detail:``,branch:t,lane:i,insertAfter:[...f,n.length-1]}}),m(l,h),g.push(h),y(`lane-${e}-${t}`,s,t)}),f){let t=v(h-1),n=`pass-${e}`;r.push({id:n,type:`add`,position:{x:t+104,y:b},data:{kind:`step`,key:n,title:``,type:``,detail:``,lane:i}}),s.add(c),m([c],n),s.delete(c),g.push(n),y(`pass-lane-${e}`,t,`default`)}l=g,u+=_+1;continue}let i=p(t,String(e+1),0,u*A0,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*A0-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 B0={class:`truncate`},V0=`\0`,H0=P({inheritAttrs:!1,__name:`OptionSelect`,props:{modelValue:{},options:{},placeholder:{},disabled:{type:Boolean},size:{},class:{}},emits:[`update:modelValue`],setup(e,{emit:t}){let n=t;return(t,r)=>(L(),q(V(zu),{"model-value":e.modelValue===``&&e.options.some(e=>e.value===``)?V0:e.modelValue||void 0,disabled:e.disabled,"onUpdate:modelValue":r[0]||=e=>n(`update:modelValue`,e===V0?``:String(e))},{default:I(()=>[A(V(Uu),G({size:e.size??`sm`,class:t.$props.class},t.$attrs),{default:I(()=>[A(V(Wu),{placeholder:e.placeholder},null,8,[`placeholder`])]),_:1},16,[`size`,`class`]),A(V(Bu),{position:`popper`,class:`max-w-[min(var(--reka-select-content-available-width),20rem)]`},{default:I(()=>[(L(!0),j(U,null,M(e.options,e=>(L(),q(V(Hu),{key:e.value,value:e.value===``?V0:e.value,disabled:e.disabled,title:e.label,class:`*:[span]:last:min-w-0`},{default:I(()=>[R(`span`,B0,B(e.label),1)]),_:2},1032,[`value`,`disabled`,`title`]))),128))]),_:1})]),_:1},8,[`model-value`,`disabled`]))}}),U0=[`id`],W0=[`value`],G0=P({__name:`WorkflowPicker`,props:{value:{},workflows:{},label:{},class:{},editable:{type:Boolean}},emits:[`pick`],setup(e,{emit:t}){let n=we(),r=t;return(t,i)=>e.editable?(L(),j(U,{key:0},[A(V(Q),{"model-value":e.value,list:V(n),"aria-label":e.label,class:z(t.$props.class),placeholder:`Workflow id or {{ reference }}`,"onUpdate:modelValue":i[0]||=e=>r(`pick`,String(e))},null,8,[`model-value`,`list`,`aria-label`,`class`]),R(`datalist`,{id:V(n)},[(L(!0),j(U,null,M(e.workflows,e=>(L(),j(`option`,{key:e.id,value:e.id},null,8,W0))),128))],8,U0)],64)):(L(),q(V(zu),{key:1,"model-value":e.value||void 0,"onUpdate:modelValue":i[1]||=e=>r(`pick`,String(e))},{default:I(()=>[A(V(Uu),{"aria-label":e.label,class:z(t.$props.class)},{default:I(()=>[A(V(Wu),{placeholder:`Choose workflow`})]),_:1},8,[`aria-label`,`class`]),A(V(Bu),null,{default:I(()=>[e.value& Line truncated
`).map((e,t)=>({number:t+1,text:e,tokens:a2(e)}))}var r2=/^(\s*)(-\s+)?/,i2=/^([^:#\s][^:#]*?)(:)(\s*)(.*)$/;function a2(e){let{code:t,comment:n}=o2(e),r=s2(t);return n&&r.push({text:n,kind:`comment`}),r}function o2(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 s2(e){if(!e)return[];let t=[],n=r2.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=i2.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,...c2(i[4]??``)]):[...t,...c2(r)]}function c2(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 l2(e){return e.split(`
`)[0]?.trim()||`invalid YAML`}function u2(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function d2(e){return typeof e==`string`&&e.trim()!==``}var f2={class:`space-y-4 px-3 py-3`},p2={key:0,class:`rounded-md bg-danger/10 px-2.5 py-1.5 text-xs text-danger`,role:`alert`},m2={key:1,class:`space-y-3`},h2={key:0,class:`block space-y-1.5`},g2=[`id`],_2=[`value`],v2={class:`text-xs font-medium text-fg-muted`},y2={class:`flex items-center gap-2`},b2={key:1,role:`alert`,class:`text-xs text-danger`},x2={key:2,class:`space-y-1.5`},S2=[`title`],C2={key:4,class:`flex flex-wrap items-center gap-1 pt-0.5`},w2={key:0,class:`divide-y divide-border rounded-md border border-border`},T2=[`title`],E2={key:0,class:`space-y-3`},D2={class:`text-label`},O2={key:0,class:`text-danger`},k2={class:`ml-2 text-xs text-fg-subtle`},A2={key:1,class:`space-y-3`},j2={class:`text-label`},M2={class:`ml-2 text-xs text-fg-subtle`},N2=[`title`],P2={key:0,class:`text-xs text-danger`},F2={class:`space-y-1.5`},I2={key:0,role:`alert`,class:`text-xs text-danger`},L2={class:`divide-y divide-border rounded-md border border-border`},R2={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},z2={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},B2={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},V2={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},H2=[`for`],U2=P({__name:`StepEditor`,props:{yaml:{},path:{},vocabulary:{},workflows:{},modelAliases:{}},emits:[`update:yaml`],setup(e,{emit:t}){let n=we(),r=e,i=t,a=Y(()=>u0(r.yaml,r.path)??{}),o=Y(()=>c0(a.value)),s=Y(()=>o.value?.kind??(typeof a.value.type==`string`?a.value.type:``)),c=Y(()=>o.value?.branches.map(([e])=>e)??[]),l=Y(()=>s.value===`parallel`?2:1);function u(e){i(`update:yaml`,d0(r.yaml,r.path,{...a.value,switch:{...a.value.switch,on:e}}))}let d=J(``),f=J(``);function p(e,t,n=``){try{let a=e===`add`?h0(r.yaml,r.path,t):e===`rename`?g0(r.yaml,r.path,t,n):_0(r.yaml,r.path,t);i(`update:yaml`,a),d.value=``,f.value=``}catch(e){f.value=String(e.message)}}let m=Y(()=>r.vocabulary.find(e=>e.name===s.value)),h=Y(()=>typeof a.value.settings==`object`&&a.value.settings!==null?a.value.settings:{}),g=Y(()=>S0(r.yaml,r.path)),_=Y(()=>Q0(a.value)),v=Y(()=>m.value?.settings&&a.value.settings?e2(a.value.settings,m.value.settings,`settings`):``),y=[`mission`,`workflow`,`message`,`body`,`plan`,`then`,`status`,`detail`,`run`,`rules`],b=/mission|body|detail|plan|rules/;function x(e,t){return[`workflow.call`,`workflow.handoff`].includes(s.value)&&e===`workflow`||s.value===`workflow.approve`&&e===`then`?`workflow`:s.value===`agent.run`&&e===`model`?`select`:t.type===`string`?t.enum?`select`:b.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 S=Y(()=>{let e=Object.entries(m.value?.settings?.properties??{}).filter(([e])=>s.value!==`workflow.call`||![`inputs`,`outputs`].includes(e)).map(([e,t])=>({key:e,schema:t,kind:x(e,t),options:s.value===`agent.run`&&e===`model`?r.modelAliases:t.enum??[]})),t=e.filter(e=>y.includes(e.key)&&e.kind!==`boolean`).sort((e,t)=>y.indexOf(e.key)-y.indexOf(t.key))[0],n=e.filter(e=>e!==t);return{lead:t,compact:n.filter(e=>[`workflow`,`select`,`line`,`number`,`boolean`].includes(e.kind)),long:n.filter(e=>[`text`,`lines`,`yaml`].includes(e.kind))}}),C=J(!S.value.lead&&!o.value),w=e=>[{value:``,label:`Default`},...e.map(e=>({value:e,label:e}))];function T(e){let{id:t,type:n,...a}=e;i(`update:yaml`,d0(r.yaml,r.path,{id:t,type:n,...a}))}function ee(e,t){T({...a.value,[e]:t})}function te(e){let t={...a.value.retry,...e};ee(`retry`,t.attempts===void 0&&!t.backoff?void 0:{...t,attempts:t.attempts??1})}function E(e,t){let n={...h.value,[e]:t};s.value===`workflow.call`&&e===`wait`&&t!==!0&&delete n.outputs,T({...a.value,settings:n})}function ne(e,t){let n={...h.value,[e]:t};s.value===`workflow.call`&&t!==h.value[e]&&(delete n.inputs,delete n.outputs),T({...a.value,settings:n})}let D=Y(()=>r.workflows.find(e=>e.id===h.value.workflow)),re=Y(()=>Object.entries(w0(D.value?.yaml??``,`inputs`)??{})),ie=Y(()=>Object.entries(w0(D.value?.yaml??``,`outputs`)??{})),ae=Y(()=>Object.entries(w0(r.yaml,`inputs`)??{})),k=Y(()=>Object.entries(w0(r.yaml,`outputs`)??{})),oe=Y(()=>h.value.inputs??{}),se=Y(()=>h.value.outputs??{}),ce=e=>typeof e==`string`&&e.startsWith(`inputs.`),le=e=>[`object`,`array`].includes(e.type??``),ue=e=>oe.value[e]===void 0?``:String(oe.value[e]);function de(e,t,n){E(`inputs`,{...oe.value,[e]:t===``?void 0:ce(t)?t:ZE(t,n??`string`)})}let fe=(e,t,n)=>e.filter(([,e])=>e.type===t.type||e.type===`any`||t.type===`any`).map(([e])=>({value:`${n}.${e}`,label:e})),pe=J(null);function me(e){let t=pe.value??S.value.lead?.key;if(!t)return;let n=typeof h.value[t]==`string`?h.value[t]:``,r=`{{ steps.${e}.summary }}`;E(t,n?`${n.trimEnd()} ${r}`:r)}let he=J({});function ge(e,t){try{E(e,t.trim()?i0(t):void 0),he.value={...he.value,[e]:``}}catch(t){he.value={...he.value,[e]:String(t.me Line truncated
`)[0]}}}let _e=e=>e===void 0?``:a0(e).trimEnd(),ve=(e,t)=>t.title??e.replaceAll(`_`,` `).replace(/^./,e=>e.toUpperCase()),ye=e=>typeof h.value[e]==`string`?h.value[e]:``,N=[{value:``,label:`Park the task`},{value:`continue`,label:`Continue`}];return(t,r)=>(L(),j(`div`,f2,[v.value?(L(),j(`p`,p2,B(v.value),1)):F(``,!0),o.value?(L(),j(`section`,m2,[s.value===`switch`?(L(),j(`label`,h2,[r[15]||=R(`span`,{class:`text-xs font-medium text-fg-muted`,title:`The value whose case runs; a case named default runs when none matches`},`Switch on`,-1),A(V(Q),{"model-value":o.value.on,class:`font-mono`,placeholder:`steps.assess.result.fit`,list:`${V(n)}-switch-on`,onChange:r[0]||=e=>u(e.target.value.trim())},null,8,[`model-value`,`list`]),R(`datalist`,{id:`${V(n)}-switch-on`},[(L(!0),j(U,null,M(g.value,e=>(L(),j(`option`,{key:e,value:`steps.${e}.result.`},null,8,_2))),128))],8,g2)])):F(``,!0),R(`div`,v2,B(s.value===`switch`?`Cases`:`Branches`),1),(L(!0),j(U,null,M(c.value,e=>(L(),j(`div`,{key:e,class:`flex items-center gap-2`},[A(V(Q),{"model-value":e,class:z(s.value===`switch`&&`font-mono`),"aria-label":`${s.value===`switch`?`Case`:`Branch`} ${e}`,onChange:t=>p(`rename`,e,t.target.value.trim())},null,8,[`model-value`,`class`,`aria-label`,`onChange`]),A(V(X),{type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":`Remove ${e}`,disabled:c.value.length<=l.value,onClick:t=>p(`delete`,e)},{default:I(()=>[A(V(Au))]),_:1},8,[`aria-label`,`disabled`,`onClick`])]))),128)),R(`div`,y2,[A(V(Q),{modelValue:d.value,"onUpdate:modelValue":r[1]||=e=>d.value=e,"aria-label":s.value===`switch`?`New case value`:`New branch name`,placeholder:s.value===`switch`?`Value, or default`:`Branch name`,onKeydown:r[2]||=gt(pt(e=>p(`add`,d.value.trim()),[`prevent`]),[`enter`])},null,8,[`modelValue`,`aria-label`,`placeholder`]),A(V(X),{type:`button`,size:`icon-sm`,variant:`outline`,"aria-label":s.value===`switch`?`Add case`:`Add branch`,disabled:!d.value.trim(),onClick:r[3]||=e=>p(`add`,d.value.trim())},{default:I(()=>[A(V(wu))]),_:1},8,[`aria-label`,`disabled`])]),f.value?(L(),j(`p`,b2,B(f.value),1)):F(``,!0)])):F(``,!0),S.value.lead?(L(),j(`section`,x2,[R(`div`,{class:`flex items-center gap-1 text-xs font-medium text-fg-muted`,title:S.value.lead.schema.description},[H(B(ve(S.value.lead.key,S.value.lead.schema))+` `,1),S.value.lead.schema.description?(L(),q(V(Wl),{key:0,class:`size-3 text-fg-subtle`})):F(``,!0)],8,S2),S.value.lead.kind===`workflow`?(L(),q(G0,{key:0,editable:s.value!==`workflow.call`,value:ye(S.value.lead.key),workflows:e.workflows,label:ve(S.value.lead.key,S.value.lead.schema),onPick:r[4]||=e=>ne(S.value.lead.key,e)},null,8,[`editable`,`value`,`workflows`,`label`])):S.value.lead.kind===`select`?(L(),q(H0,{key:1,class:`w-full`,"model-value":ye(S.value.lead.key),options:w(S.value.lead.options),"aria-label":ve(S.value.lead.key,S.value.lead.schema),"onUpdate:modelValue":r[5]||=e=>E(S.value.lead.key,e||void 0)},null,8,[`model-value`,`options`,`aria-label`])):S.value.lead.kind===`text`?(L(),q(V(Hd),{key:2,"model-value":ye(S.value.lead.key),class:`min-h-32 text-label leading-relaxed`,onFocus:r[6]||=e=>pe.value=S.value.lead.key,"onUpdate:modelValue":r[7]||=e=>E(S.value.lead.key,String(e))},null,8,[`model-value`])):(L(),q(V(Q),{key:3,"model-value":ye(S.value.lead.key),onFocus:r[8]||=e=>pe.value=S.value.lead.key,"onUpdate:modelValue":r[9]||=e=>E(S.value.lead.key,String(e))},null,8,[`model-value`])),g.value.length&&S.value.lead.kind!==`select`?(L(),j(`div`,C2,[r[16]||=R(`span`,{class:`text-caption text-fg-subtle`},`Insert`,-1),(L(!0),j(U,null,M(g.value,e=>(L(),q(V(X),{key:e,type:`button`,variant:`outline`,size:`xs`,class:`font-mono`,title:`{{ steps.${e}.summary }}`,onClick:t=>me(e)},{default:I(()=>[H(B(e),1)]),_:2},1032,[`title`,`onClick`]))),128))])):F(``,!0)])):F(``,!0),A(V(X),{type:`button`,variant:`ghost`,size:`xs`,class:`-ml-2 text-fg-muted aria-expanded:bg-transparent`,"aria-expanded":C.value,onClick:r[10]||=e=>C.value=!C.value},{default:I(()=>[A(V(O),{"data-icon":`inline-start`,class:z([`transition-transform`,!C.value&&`-rotate-90`])},null,8,[`class`]),r[17]||=H(`More `,-1)]),_:1},8,[`aria-expanded`]),C.value?(L(),j(U,{key:3},[S.value.compact.length?(L(),j(`section`,w2,[(L(!0),j(U,null,M(S.value.compact,t=>(L(),j(`div`,{key:t.key,class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},[R(`span`,{class:`flex flex-1 items-center gap-1 text-label`,title:t.schema.description},[H(B(ve(t.key,t.schema))+` `,1),t.schema.description?(L(),q(V(Wl),{key:0,class:`size-3 text-fg-subtle`})):F(``,!0)],8,T2),t.kind===`workflow`?(L(),q(G0,{key:0,editable:s.value!==`workflow.call`,class:`max-w-48`,value:ye(t.key),workflows:e.workflows,label:ve(t.key,t.schema),onPick:e=>ne(t.key,e)},null,8,[`editable`,`value`,`workflows`,`label`,`onPick`])):t.kind===`boolean`?(L(),q(V(aT),{key:1,"model-value":h.value[t.key]===!0,"onUpdate:modelValue":e=>E(t.key,e||void 0)},null,8,[`model-value`,`onUpdate:modelValue`])):t.kind===`select`?(L(),q(H0,{key:2,class:`w-40`,"model-val Line truncated
`):``,class:`min-h-16 font-mono text-xs`,placeholder:`One per line`,"onUpdate:modelValue":t=>E(e.key,String(t).split(`
`).filter(Boolean))},null,8,[`model-value`,`onUpdate:modelValue`])):(L(),j(U,{key:2},[A(V(Wd),{"model-value":_e(h.value[e.key]),class:`min-h-24 font-mono text-xs`,placeholder:`YAML`,onChange:t=>ge(e.key,t.target.value)},null,8,[`model-value`,`onChange`]),he.value[e.key]?(L(),j(`span`,W2,B(he.value[e.key]),1)):F(``,!0)],64))]))),128)),R(`section`,G2,[_.value?(L(),j(`p`,K2,B(_.value),1)):F(``,!0),R(`div`,q2,[R(`label`,J2,[r[20]||=R(`span`,{class:`flex-1 text-label`,title:`Empty always runs. A field such as inputs.enabled, !inputs.skip, or steps.plan.result.ready == true`},`Run only when`,-1),A(V(Q),{class:`h-8 w-48 font-mono text-xs`,placeholder:`inputs.enabled`,"aria-invalid":_.value&&_.value.startsWith(`when`)?!0:void 0,"model-value":a.value.when??``,"onUpdate:modelValue":r[11]||=e=>ee(`when`,String(e))},null,8,[`aria-invalid`,`model-value`])]),R(`label`,Y2,[r[21]||=R(`span`,{class:`flex-1 text-label`},`If it fails`,-1),A(Q0,{class:`w-36`,"aria-label":`If it fails`,"model-value":a.value.on_failure??``,options:N,"onUpdate:modelValue":r[12]||=e=>ee(`on_failure`,e||void 0)},null,8,[`model-value`])]),R(`label`,X2,[r[22]||=R(`span`,{class:`flex-1 text-label`},`Attempts`,-1),A(V(Q),{type:`number`,min:`1`,max:`10`,placeholder:`1`,class:`h-8 w-20 text-right text-label`,"model-value":a.value.retry?.attempts??``,"onUpdate:modelValue":r[13]||=e=>te({attempts:String(e)===``?void 0:Number(String(e))})},null,8,[`model-value`])]),R(`div`,Z2,[R(`label`,{for:`${V(n)}-backoff`,class:`flex-1 text-label`},`Retry backoff`,8,Q2),A(V(Qw),{id:`${V(n)}-backoff`,"model-value":a.value.retry?.backoff??``,units:[`s`,`m`,`h`],"onUpdate:modelValue":r[14]||=e=>te({backoff:e||void 0})},null,8,[`id`,`model-value`])])])])],64)):F(``,!0)]))}}),e4={class:`space-y-1.5`},t4={class:`flex items-center text-xs font-medium text-fg-muted`},n4={key:0,class:`divide-y divide-border rounded-md border border-border`},r4=P({__name:`SpecList`,props:{yaml:{},field:{}},emits:[`update:yaml`],setup(e,{emit:t}){let n=e,r=t,i=[`string`,`number`,`bool`,`object`,`array`,`any`].map(e=>({value:e,label:e})),a=Y(()=>Object.entries(P0(n.yaml,n.field)??{}));function o(e){r(`update:yaml`,F0(n.yaml,n.field,Object.fromEntries(e.filter(([e])=>e))))}function s(e,t,n){o(a.value.map((r,i)=>i===e?[t,n]:r))}function c(){let e=n.field.slice(0,-1),t=a.value.length+1;for(;a.value.some(([n])=>n===`${e}_${t}`);)t++;o([...a.value,[`${e}_${t}`,{type:`string`}]])}return(t,n)=>(L(),j(`section`,e4,[R(`div`,t4,[H(B(e.field===`inputs`?`Inputs`:`Outputs`)+` `,1),A(V(X),{type:`button`,variant:`ghost`,size:`xs`,class:`ml-auto`,onClick:c},{default:I(()=>[A(V(Tu),{"data-icon":`inline-start`}),n[0]||=H(`Add`,-1)]),_:1})]),a.value.length?(L(),j(`div`,n4,[(L(!0),j(U,null,M(a.value,([t,n],r)=>(L(),j(`div`,{key:r,class:`flex items-center gap-2 px-2 py-1.5`},[A(V(Q),{"model-value":t,class:`h-8 min-w-0 flex-1 font-mono text-xs`,"aria-label":`${e.field} name`,onChange:e=>s(r,e.target.value.trim(),n)},null,8,[`model-value`,`aria-label`,`onChange`]),A(Q0,{"model-value":n.type??`string`,options:V(i),class:`w-24`,"aria-label":`${t} type`,"onUpdate:modelValue":e=>s(r,t,{...n,type:e})},null,8,[`model-value`,`options`,`aria-label`,`onUpdate:modelValue`]),A(V(aT),{"model-value":n.required===!0,title:n.required?`Required`:`Optional`,"aria-label":`${t} required`,"onUpdate:modelValue":e=>s(r,t,{...n,required:e||void 0})},null,8,[`model-value`,`title`,`aria-label`,`onUpdate:modelValue`]),A(V(X),{type:`button`,variant:`ghost`,size:`icon-xs`,"aria-label":`Remove ${t}`,onClick:e=>o(a.value.filter((e,t)=>t!==r))},{default:I(()=>[A(V(ju))]),_:1},8,[`aria-label`,`onClick`])]))),128))])):F(``,!0)]))}}),i4={class:`space-y-4 px-3 py-3`},a4={class:`divide-y divide-border rounded-md border border-border`},o4={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},s4={key:0,role:`alert`,class:`px-3 py-2 text-xs text-danger`},c4={key:1,class:`px-3 py-2 text-xs text-fg-subtle`},l4={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},u4={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},d4={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},f4={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},p4={class:`space-y-1.5`},m4=`6f129e29-0e26-5246-99bd-74cb4496203b`,h4=P({__name:`WorkflowSettings`,props:{yaml:{}},emits:[`update:yaml`],setup(e,{emit:t}){let n=e,r=t,i=e=>{let t=P0(n.yaml,e);return typeof t==`string`?t:``};function a(e,t){r(`update:yaml`,F0(n.yaml,e,t))}let o=PT(),s=J([]),c=J(!0),l=J(``);async function u(){c.value=!0,l.value=``,s.value=[];try{await o.loadOrg();let e=await Z.orgAgents(o.homeOrg);s.value=e.agents.filter(e=>e.lifecycle===`active`),!i(`identity`)&&s.value.some(e=>e.id===m4)&&a(`identity`,m4)}catch(e){l.value=String(e.message||e)}finally{c.value=!1}}Be(u);let d=Y(()=>{let e=i(`identity`),t=s.value.map(e=>({value:e.id,label:e.display_name}));return e&&!c.value&&!s.value.some(t=>t.id===e)?[{value:e,label:`${e} (unknown)`,disabled:!0},...t]:t}),f=Jw(),p=Y(()=>{let e=Object.keys(f.stateFor(`agent-profilLine truncated
`).filter(Boolean))},null,8,[`model-value`,`onUpdate:modelValue`])):(L(),j(U,{key:2},[A(V(Hd),{"model-value":_e(h.value[e.key]),class:`min-h-24 font-mono text-xs`,placeholder:`YAML`,onChange:t=>ge(e.key,t.target.value)},null,8,[`model-value`,`onChange`]),he.value[e.key]?(L(),j(`span`,P2,B(he.value[e.key]),1)):F(``,!0)],64))]))),128)),R(`section`,F2,[_.value?(L(),j(`p`,I2,B(_.value),1)):F(``,!0),R(`div`,L2,[R(`label`,R2,[r[20]||=R(`span`,{class:`flex-1 text-label`,title:`Empty always runs. A field such as inputs.enabled, !inputs.skip, or steps.plan.result.ready == true`},`Run only when`,-1),A(V(Q),{class:`h-8 w-48 font-mono text-xs`,placeholder:`inputs.enabled`,"aria-invalid":_.value&&_.value.startsWith(`when`)?!0:void 0,"model-value":a.value.when??``,"onUpdate:modelValue":r[11]||=e=>ee(`when`,String(e))},null,8,[`aria-invalid`,`model-value`])]),R(`label`,z2,[r[21]||=R(`span`,{class:`flex-1 text-label`},`If it fails`,-1),A(H0,{class:`w-36`,"aria-label":`If it fails`,"model-value":a.value.on_failure??``,options:N,"onUpdate:modelValue":r[12]||=e=>ee(`on_failure`,e||void 0)},null,8,[`model-value`])]),R(`label`,B2,[r[22]||=R(`span`,{class:`flex-1 text-label`},`Attempts`,-1),A(V(Q),{type:`number`,min:`1`,max:`10`,placeholder:`1`,class:`h-8 w-20 text-right text-label`,"model-value":a.value.retry?.attempts??``,"onUpdate:modelValue":r[13]||=e=>te({attempts:String(e)===``?void 0:Number(String(e))})},null,8,[`model-value`])]),R(`div`,V2,[R(`label`,{for:`${V(n)}-backoff`,class:`flex-1 text-label`},`Retry backoff`,8,H2),A(V(Qw),{id:`${V(n)}-backoff`,"model-value":a.value.retry?.backoff??``,units:[`s`,`m`,`h`],"onUpdate:modelValue":r[14]||=e=>te({backoff:e||void 0})},null,8,[`id`,`model-value`])])])])],64)):F(``,!0)]))}}),W2={class:`space-y-1.5`},G2={class:`flex items-center text-xs font-medium text-fg-muted`},K2={key:0,class:`divide-y divide-border rounded-md border border-border`},q2=P({__name:`SpecList`,props:{yaml:{},field:{}},emits:[`update:yaml`],setup(e,{emit:t}){let n=e,r=t,i=[`string`,`number`,`bool`,`object`,`array`,`any`].map(e=>({value:e,label:e})),a=Y(()=>Object.entries(w0(n.yaml,n.field)??{}));function o(e){r(`update:yaml`,T0(n.yaml,n.field,Object.fromEntries(e.filter(([e])=>e))))}function s(e,t,n){o(a.value.map((r,i)=>i===e?[t,n]:r))}function c(){let e=n.field.slice(0,-1),t=a.value.length+1;for(;a.value.some(([n])=>n===`${e}_${t}`);)t++;o([...a.value,[`${e}_${t}`,{type:`string`}]])}return(t,n)=>(L(),j(`section`,W2,[R(`div`,G2,[H(B(e.field===`inputs`?`Inputs`:`Outputs`)+` `,1),A(V(X),{type:`button`,variant:`ghost`,size:`xs`,class:`ml-auto`,onClick:c},{default:I(()=>[A(V(wu),{"data-icon":`inline-start`}),n[0]||=H(`Add`,-1)]),_:1})]),a.value.length?(L(),j(`div`,K2,[(L(!0),j(U,null,M(a.value,([t,n],r)=>(L(),j(`div`,{key:r,class:`flex items-center gap-2 px-2 py-1.5`},[A(V(Q),{"model-value":t,class:`h-8 min-w-0 flex-1 font-mono text-xs`,"aria-label":`${e.field} name`,onChange:e=>s(r,e.target.value.trim(),n)},null,8,[`model-value`,`aria-label`,`onChange`]),A(H0,{"model-value":n.type??`string`,options:V(i),class:`w-24`,"aria-label":`${t} type`,"onUpdate:modelValue":e=>s(r,t,{...n,type:e})},null,8,[`model-value`,`options`,`aria-label`,`onUpdate:modelValue`]),A(V(aT),{"model-value":n.required===!0,title:n.required?`Required`:`Optional`,"aria-label":`${t} required`,"onUpdate:modelValue":e=>s(r,t,{...n,required:e||void 0})},null,8,[`model-value`,`title`,`aria-label`,`onUpdate:modelValue`]),A(V(X),{type:`button`,variant:`ghost`,size:`icon-xs`,"aria-label":`Remove ${t}`,onClick:e=>o(a.value.filter((e,t)=>t!==r))},{default:I(()=>[A(V(Au))]),_:1},8,[`aria-label`,`onClick`])]))),128))])):F(``,!0)]))}}),J2={class:`space-y-4 px-3 py-3`},Y2={class:`divide-y divide-border rounded-md border border-border`},X2={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},Z2={key:0,role:`alert`,class:`px-3 py-2 text-xs text-danger`},Q2={key:1,class:`px-3 py-2 text-xs text-fg-subtle`},$2={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},e4={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},t4={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},n4={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},r4={class:`space-y-1.5`},i4=`6f129e29-0e26-5246-99bd-74cb4496203b`,a4=P({__name:`WorkflowSettings`,props:{yaml:{}},emits:[`update:yaml`],setup(e,{emit:t}){let n=e,r=t,i=e=>{let t=w0(n.yaml,e);return typeof t==`string`?t:``};function a(e,t){r(`update:yaml`,T0(n.yaml,e,t))}let o=PT(),s=J([]),c=J(!0),l=J(``);async function u(){c.value=!0,l.value=``,s.value=[];try{await o.loadOrg();let e=await Z.orgAgents(o.homeOrg);s.value=e.agents.filter(e=>e.lifecycle===`active`),!i(`identity`)&&s.value.some(e=>e.id===i4)&&a(`identity`,i4)}catch(e){l.value=String(e.message||e)}finally{c.value=!1}}Be(u);let d=Y(()=>{let e=i(`identity`),t=s.value.map(e=>({value:e.id,label:e.display_name}));return e&&!c.value&&!s.value.some(t=>t.id===e)?[{value:e,label:`${e} (unknown)`,disabled:!0},...t]:t}),f=Jw(),p=Y(()=>{let e=Object.keys(f.stateFor(`agent-profilLine 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 ace(e,t){return n=>{if(!n.code&&!n.key)return!1;let r=oce(n.code,e);return Array.isArray(e)?e.some(e=>w5(n[r],e,t,n.type===`keyup`)):w5(n[r],e,t,n.type===`keyup`)}}function oce(e,t){return t.includes(e)?`code`:`key`}function T5(e,t){let n=Y(()=>Ge(t?.target)??rce),r=at(Ge(e)===!0),i=!1,a=new Set,o=c(Ge(e));N(()=>Ge(e),(e,t)=>{typeof t==`boolean`&&typeof e!=`boolean`&&s(),o=c(e)},{immediate:!0}),M3([`blur`,`contextmenu`],s),P3((...e)=>o(...e),e=>{let n=Ge(t?.actInsideInputWithModifier)??!0,a=Ge(t?.preventDefault)??!1;if(i=ice(e),(!i||i&&!n)&&C5(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}),P3((...e)=>o(...e),e=>{let n=Ge(t?.actInsideInputWithModifier)??!0;if(r.value){if((!i||i&&!n)&&C5(e))return;i=!1,r.value=!1}},{eventName:`keyup`,target:n});function s(){i=!1,a.clear(),r.value=Ge(e)===!0}function c(e){return e===null?(s(),()=>!1):typeof e==`boolean`?(s(),r.value=e,()=>!1):Array.isArray(e)||typeof e==`string`?ace(e,a):e}return r}var E5=`vue-flow__node-desc`,D5=`vue-flow__edge-desc`,sce=`vue-flow__aria-live`,O5=[`Enter`,` `,`Escape`],k5={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};function A5(e){return{...e.computedPosition||{x:0,y:0},width:e.dimensions.width||0,height:e.dimensions.height||0}}function j5(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 M5(e){return{width:e.offsetWidth,height:e.offsetHeight}}function N5(e,t=0,n=1){return Math.min(Math.max(e,t),n)}function P5(e,t){return{x:N5(e.x,t[0][0],t[1][0]),y:N5(e.y,t[0][1],t[1][1])}}function F5(e){let t=e.getRootNode();return`elementFromPoint`in t?t:window.document}function I5(e){return e&&typeof e==`object`&&`id`in e&&`source`in e&&`target`in e}function L5(e){return e&&typeof e==`object`&&`id`in e&&`position`in e&&!I5(e)}function R5(e){return L5(e)&&`computedPosition`in e}function z5(e){return!Number.isNaN(e)&&Number.isFinite(e)}function cce(e){return z5(e.width)&&z5(e.height)&&z5(e.x)&&z5(e.y)}function lce(e,t,n){let r={id:e.id.toString(),type:e.type??`default`,dimensions:He({width:0,height:0}),computedPosition:He({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:N7(e.data)?e.data:{},events:He(N7(e.events)?e.events:{})};return Object.assign(t??r,e,{id:e.id.toString(),parentNode:n})}function B5(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:N7(e.data)?e.data:{},events:He(N7(e.events)?e.events:{}),label:e.label??``,interactionWidth:e.interactionWidth??n?.interactionWidth,...n??{}};return Object.assign(t??r,e,{id:e.id.toString()})}function V5(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 uce(...e){if(e.length===3){let[t,n,r]=e;return V5(t,n,r,`target`)}let[t,n]=e,r=typeof t==`string`?t:t.id;return n.filter(e=>I5(e)&&e.source===r).map(e=>n.find(t=>L5(t)&&t.id===e.target))}function dce(...e){if(e.length===3){let[t,n,r]=e;return V5(t,n,r,`source`)}let[t,n]=e,r=typeof t==`string`?t:t.id;return n.filter(e=>I5(e)&&e.target===r).map(e=>n.find(t=>L5(t)&&t.id===e.source))}function H5({source:e,sourceHandle:t,target:n,targetHandle:r}){return`vueflow__edge-${e}${t??``}-${n}${r??``}`}function fce(e,t){return t.some(t=>I5(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 U5({x:e,y:t},{x:n,y:r,zoom:i}){return{x:e*i+n,y:t*i+r}}function W5({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?C7(s,o):s}function pce(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 G5({x:e,y:t,width:n,height:r}){return{x:e,y:t,x2:e+n,y2:t+r}}function mce({x:e,y:t,x2:n,y2:r}){return{x:e,y:t,width:n-e,height:r-t}}function K5(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=pce(t,G5({...r.computedPosition,...r.dimensions}))}return mce(t)}function q5(e,t,n={x:0,y:0,zoom:1},r=!1,i=!1){let a={...W5(t,n),width:t.width/n.zoom,height:t.height/n.zoom},o=[];for(let t of e){let{dimensions:e,selectabl 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 qse(e,t){return n=>{if(!n.code&&!n.key)return!1;let r=Jse(n.code,e);return Array.isArray(e)?e.some(e=>T5(n[r],e,t,n.type===`keyup`)):T5(n[r],e,t,n.type===`keyup`)}}function Jse(e,t){return t.includes(e)?`code`:`key`}function E5(e,t){let n=Y(()=>Ge(t?.target)??Gse),r=at(Ge(e)===!0),i=!1,a=new Set,o=c(Ge(e));N(()=>Ge(e),(e,t)=>{typeof t==`boolean`&&typeof e!=`boolean`&&s(),o=c(e)},{immediate:!0}),S3([`blur`,`contextmenu`],s),w3((...e)=>o(...e),e=>{let n=Ge(t?.actInsideInputWithModifier)??!0,a=Ge(t?.preventDefault)??!1;if(i=Kse(e),(!i||i&&!n)&&w5(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}),w3((...e)=>o(...e),e=>{let n=Ge(t?.actInsideInputWithModifier)??!0;if(r.value){if((!i||i&&!n)&&w5(e))return;i=!1,r.value=!1}},{eventName:`keyup`,target:n});function s(){i=!1,a.clear(),r.value=Ge(e)===!0}function c(e){return e===null?(s(),()=>!1):typeof e==`boolean`?(s(),r.value=e,()=>!1):Array.isArray(e)||typeof e==`string`?qse(e,a):e}return r}var D5=`vue-flow__node-desc`,O5=`vue-flow__edge-desc`,Yse=`vue-flow__aria-live`,k5=[`Enter`,` `,`Escape`],A5={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};function j5(e){return{...e.computedPosition||{x:0,y:0},width:e.dimensions.width||0,height:e.dimensions.height||0}}function M5(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 N5(e){return{width:e.offsetWidth,height:e.offsetHeight}}function P5(e,t=0,n=1){return Math.min(Math.max(e,t),n)}function F5(e,t){return{x:P5(e.x,t[0][0],t[1][0]),y:P5(e.y,t[0][1],t[1][1])}}function I5(e){let t=e.getRootNode();return`elementFromPoint`in t?t:window.document}function L5(e){return e&&typeof e==`object`&&`id`in e&&`source`in e&&`target`in e}function R5(e){return e&&typeof e==`object`&&`id`in e&&`position`in e&&!L5(e)}function z5(e){return R5(e)&&`computedPosition`in e}function B5(e){return!Number.isNaN(e)&&Number.isFinite(e)}function Xse(e){return B5(e.width)&&B5(e.height)&&B5(e.x)&&B5(e.y)}function Zse(e,t,n){let r={id:e.id.toString(),type:e.type??`default`,dimensions:He({width:0,height:0}),computedPosition:He({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:P7(e.data)?e.data:{},events:He(P7(e.events)?e.events:{})};return Object.assign(t??r,e,{id:e.id.toString(),parentNode:n})}function V5(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:P7(e.data)?e.data:{},events:He(P7(e.events)?e.events:{}),label:e.label??``,interactionWidth:e.interactionWidth??n?.interactionWidth,...n??{}};return Object.assign(t??r,e,{id:e.id.toString()})}function H5(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 Qse(...e){if(e.length===3){let[t,n,r]=e;return H5(t,n,r,`target`)}let[t,n]=e,r=typeof t==`string`?t:t.id;return n.filter(e=>L5(e)&&e.source===r).map(e=>n.find(t=>R5(t)&&t.id===e.target))}function $se(...e){if(e.length===3){let[t,n,r]=e;return H5(t,n,r,`source`)}let[t,n]=e,r=typeof t==`string`?t:t.id;return n.filter(e=>L5(e)&&e.target===r).map(e=>n.find(t=>R5(t)&&t.id===e.source))}function U5({source:e,sourceHandle:t,target:n,targetHandle:r}){return`vueflow__edge-${e}${t??``}-${n}${r??``}`}function ece(e,t){return t.some(t=>L5(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 W5({x:e,y:t},{x:n,y:r,zoom:i}){return{x:e*i+n,y:t*i+r}}function G5({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?w7(s,o):s}function tce(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 K5({x:e,y:t,width:n,height:r}){return{x:e,y:t,x2:e+n,y2:t+r}}function nce({x:e,y:t,x2:n,y2:r}){return{x:e,y:t,width:n-e,height:r-t}}function q5(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=tce(t,K5({...r.computedPosition,...r.dimensions}))}return nce(t)}function J5(e,t,n={x:0,y:0,zoom:1},r=!1,i=!1){let a={...G5(t,n),width:t.width/n.zoom,height:t.height/n.zoom},o=[];for(let t of e){let{dimensions:e,selectabl 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}
@@ -319,7 +319,7 @@ 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`},y7=class extends Error{constructor(e,...t){super(v7[e]?.call(v7,...t)),this.name=`VueFlowError`,this.code=e,this.args=t}};function b7(e){return`clientX`in e}function wce(e){return`sourceEvent`in e}function x7(e,t){let n=b7(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 S7=()=>typeof navigator<`u`&&(navigator==null?void 0:navigator.userAgent)?.indexOf(`Mac`)>=0;function Tce(e){return{width:e.dimensions?.width??e.width??0,height:e.dimensions?.height??e.height??0}}function C7(e,t=[1,1]){return{x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}}var Ece=()=>!0;function w7(e){e?.classList.remove(`valid`,`connecting`,`vue-flow__handle-valid`,`vue-flow__handle-connecting`)}function Dce(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())j5(i,A5(e))>0&&r.push(e);return r}var Oce=250;function kce(e,t,n,r){let i=[],a=1/0,o=Dce(e,n,t+Oce);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}=h7(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 T7(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:i,fromType:a,doc:o,lib:s,flowId:c,isValidConnection:l=Ece},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:_}=x7(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=E7(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===b5.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=D7(t,e,a,p,n,!0)}return b}function E7(e,t){return e||(t?.classList.contains(`target`)?`target`:t?.classList.contains(`source`)?`source`:null)}function Ace(e,t){let n=null;return t?n=`valid`:e&&!t&&(n=`invalid`),n}function jce(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}function D7(e,t,n,r,i,a=!1){let o=r.get(e);if(!o)return null;let s=i===b5.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,...h7(o,c,c.position,!0)}:c}var O7={[_5.Left]:_5.Right,[_5.Right]:_5.Left,[_5.Top]:_5.Bottom,[_5.Bottom]:_5.Top},Mce=[`production`,`prod`];function k7(e,...t){A7()&&console.warn(`[Vue Flow]: ${e}`,...t)}function A7(){return!Mce.includes(`production`)}function j7(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,...M5(t)}}):null}function M7(e,t,n,r,i,a=!1,o){i.value=!1,e.selected?(a||e.selected&&t)&&(r([e]),We(()=>{o.blur()})):n([e])}function N7(e){return V(e)!==void 0}function Nce(e,t,n,r){if(!e||!e.source||!e.target)return n(new y7(_7.EDGE_INVALID,e?.id??`[ID UNKNOWN]`)),!1;let i;return i=I5(e)?e:{...e,id:H5(e)},i=B5(i,void 0,r),!fce(i,t)&&i}function Pce(e,t,n,r,i){if(!t.source||!t.target)return i(new y7(_7.EDGE_INVALID,e.id)),!1;if(!n)return i(new y7(_7.EDGE_NOT_FOUND,e.id)),!1;let{id:a,...o}=e;return{...o,id:r?H5(t):a,source:t.source,target:t.target,sourceHandle:t.sourceHandle,targetHandle:t.targetHandle}}function P7(e,t,n){let r={},i=[];for(let a=0;a<e.length;++a){let o=e[a];if(!L5(o)){n(new y7(_7.NODE_INVALID,o?.id));continue}let s=lce(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 y7(_7.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 F7(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 I7(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}`;F7(`sourcLine truncated
`)},B(e.data.summary||e.data.detail),9,xue)):F(``,!0),e.data.when||e.data.retry||e.data.continues?(L(),j(`div`,Sue,[e.data.when?(L(),j(`span`,{key:0,class:`flex max-w-full min-w-0 items-center gap-0.5 rounded bg-secondary px-1 font-mono`,title:`Runs only when ${e.data.when}`},[A(V(su),{class:`size-3 shrink-0`,"aria-hidden":`true`}),R(`span`,wue,B(e.data.when),1)],8,Cue)):F(``,!0),e.data.retry?(L(),j(`span`,{key:1,class:`flex items-center gap-0.5 rounded bg-secondary px-1`,title:`Up to ${e.data.retry} attempts`},[A(V(hte),{class:`size-3`,"aria-hidden":`true`}),H(`×`+B(e.data.retry),1)],8,Tue)):F(``,!0),e.data.continues?(L(),j(`span`,Eue,[A(V(Ste),{class:`size-3`,"aria-hidden":`true`}),r[10]||=H(`continues`,-1)])):F(``,!0)])):F(``,!0),e.data.run?.error?(L(),j(`p`,{key:4,class:`mt-1 line-clamp-2 text-caption text-danger`,title:e.data.run.error},B(e.data.run.error),9,Due)):F(``,!0)],64))]),A(ut,{"enter-from-class":`opacity-0 -translate-y-1`,"enter-active-class":`transition duration-200`,"leave-to-class":`opacity-0`,"leave-active-class":`transition duration-100`},{default:I(()=>[e.data.expanded?(L(),j(`div`,{key:0,class:`nodrag nopan nowheel cursor-auto border-t border-border`,onClick:r[6]||=pt(()=>{},[`stop`])},[K(t.$slots,`default`)])):F(``,!0)]),_:3}),A(V(Q7),{type:`source`,position:V(_5).Bottom},null,8,[`position`]),A(V(Q7),{id:`data-out`,type:`source`,position:V(_5).Right,class:`!opacity-0`},null,8,[`position`]),e.data.type===`switch`?(L(),q(V(Q7),{key:1,id:`otherwise`,type:`source`,position:V(_5).Right,class:`!opacity-0`},null,8,[`position`])):F(``,!0)],2))}}),kue={class:`pointer-events-none size-full rounded-xl border border-dashed border-border bg-muted/30`},Aue={class:`flex items-center gap-1 px-2.5 pt-1.5 text-caption text-fg-subtle`},jue={key:0},Mue={key:1,class:`font-mono`},Nue=P({__name:`LaneNode`,props:{data:{}},setup(e){return(t,n)=>(L(),j(`div`,kue,[R(`div`,Aue,[e.data.lane===`switch`?(L(),j(U,{key:0},[A(V(ku),{class:`size-3`,"aria-hidden":`true`}),e.data.title==="default"?(L(),j(`span`,jue,`otherwise`)):(L(),j(`span`,Mue,`= `+B(e.data.title),1))],64)):(L(),j(U,{key:1},[A(V(lu),{class:`size-3`,"aria-hidden":`true`}),H(B(e.data.title),1)],64))])]))}}),Pue={class:`flex shrink-0 items-center justify-center gap-1 border-t border-border bg-card p-1`},C9=240,Fue=416,w9=-140,Iue=72,Lue=.9,T9=P({__name:`WorkflowCanvas`,props:{yaml:{},stages:{},open:{},triggers:{},types:{},readonly:{type:Boolean},restartable:{type:Boolean},marks:{},problems:{},title:{},summary:{}},emits:[`toggle`,`insert`,`duplicate`,`move`,`remove`,`rename`,`restart`],setup(e,{emit:t}){let n=e,r=t,i=Y(()=>!!n.types?.length&&!n.readonly),a=Y(()=>[...n.types??[],`parallel`,`switch`]),o=Y(()=>a.value.filter(e=>[`agent.run`,`workflow.call`].includes(e))),s=e=>e&&y0(e)?o.value:a.value,c=e=>e.kind===`step`?JSON.stringify(e.path??null):e.kind,l=J(null),u=J(null),d=lee(`(max-width: 767px)`),f=Y(()=>{let e=R0(Y0(n.yaml),n.stages??[]);return n.types?.length?{nodes:[{id:`workflow`,type:`step`,position:{x:0,y:w9},data:{kind:`workflow`,key:`workflow`,title:n.title||`Workflow`,type:``,detail:n.summary??``}},...e.nodes],edges:[{id:`flow-workflow-start`,source:`workflow`,target:`start`,kind:`flow`},...e.edges]}:e}),p=Y(()=>f.value.nodes.filter(e=>e.data.path?.length===2).length),m=J({}),h=J({}),g=Y(()=>f.value.nodes.find(e=>e.type===`step`&&c(e.data)===n.open));function _(e,t){m.value={...m.value,[e]:t},g.value?.id!==e&&(h.value={...h.value,[e]:t})}let v=Y(()=>{let e=d.value?void 0:g.value?.id;return e&&m.value[e]?Math.max(0,m.value[e]-(h.value[e]??m.value[e])):0}),y=Ot(),b=see(v,{duration:Y(()=>y.value===`reduce`?0:200)}),x=Y(()=>{let e=new Map;for(let t of f.value.nodes){if(t.type!==`step`)continue;let n=(t.id===g.value?.id?h.value[t.id]:void 0)??m.value[t.id];n!==void 0&&e.set(t.position.y,Math.max(e.get(t.position.y)??-72,n-Iue))}return[...e]}),S=e=>x.value.reduce((t,[n,r])=>n<e?t+r:t,0);function C(e){let t=e.data,a=c(t),o=t.path,s={triggers:t.kind===`start`?n.triggers??[]:t.triggers,expanded:!d.value&&a===n.open,editable:i.value,problem:o?n.problems?.[a]:void 0,onResize:t=>_(e.id,t)};return n.types?.length&&(s.onToggle=()=>r(`toggle`,a)),i.value&&o&&(s.onRename=e=>r(`rename`,o,e),s.onDuplicate=()=>r(`duplicate`,o),s.onRemove=()=>r(`remove`,o)),{...e,data:{...t,...s}}}let w=e=>{let t=g.value;return d.value||!t||!e.style?.width?!1:e.position.x<=t.position.x&&e.position.x+parseFloat(String(e.style.width))>=t.position.x+C9};function T(e){let t=g.value;if(d.value||!t)return 0;if(e.id===t.id||w(e))return-88;let n=t.position.x+C9/2,r=e.style?.width?parseFloat(String(e.style.width)):e.type===`step`?C9:32,i=e.position.x+r/2;return Math.abs(i-n)<C9/2?0:i<n?-88:88}let ee=Y(()=>{let e=g.value;return f.value.nodes.map(t=>{let a=t;t.type===`add`?t={...t,data:{...t.data,types:s(t.data.insertAfter),editable:i.value,onInsert:e=>r(`insert`,t.data.insertAfter,e)}}:t.type===`step`&&(t=C(t));let o=n.marks?.[t.id];o&&(t={...t,data:{...t.data,mark:o}});let c=t.position 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`},b7=class extends Error{constructor(e,...t){super(y7[e]?.call(y7,...t)),this.name=`VueFlowError`,this.code=e,this.args=t}};function x7(e){return`clientX`in e}function fce(e){return`sourceEvent`in e}function S7(e,t){let n=x7(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 C7=()=>typeof navigator<`u`&&(navigator==null?void 0:navigator.userAgent)?.indexOf(`Mac`)>=0;function pce(e){return{width:e.dimensions?.width??e.width??0,height:e.dimensions?.height??e.height??0}}function w7(e,t=[1,1]){return{x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}}var mce=()=>!0;function T7(e){e?.classList.remove(`valid`,`connecting`,`vue-flow__handle-valid`,`vue-flow__handle-connecting`)}function hce(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())M5(i,j5(e))>0&&r.push(e);return r}var gce=250;function _ce(e,t,n,r){let i=[],a=1/0,o=hce(e,n,t+gce);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}=g7(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 E7(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:i,fromType:a,doc:o,lib:s,flowId:c,isValidConnection:l=mce},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:_}=S7(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=D7(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===x5.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=O7(t,e,a,p,n,!0)}return b}function D7(e,t){return e||(t?.classList.contains(`target`)?`target`:t?.classList.contains(`source`)?`source`:null)}function vce(e,t){let n=null;return t?n=`valid`:e&&!t&&(n=`invalid`),n}function yce(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}function O7(e,t,n,r,i,a=!1){let o=r.get(e);if(!o)return null;let s=i===x5.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,...g7(o,c,c.position,!0)}:c}var k7={[v5.Left]:v5.Right,[v5.Right]:v5.Left,[v5.Top]:v5.Bottom,[v5.Bottom]:v5.Top},bce=[`production`,`prod`];function A7(e,...t){j7()&&console.warn(`[Vue Flow]: ${e}`,...t)}function j7(){return!bce.includes(`production`)}function M7(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,...N5(t)}}):null}function N7(e,t,n,r,i,a=!1,o){i.value=!1,e.selected?(a||e.selected&&t)&&(r([e]),We(()=>{o.blur()})):n([e])}function P7(e){return V(e)!==void 0}function xce(e,t,n,r){if(!e||!e.source||!e.target)return n(new b7(v7.EDGE_INVALID,e?.id??`[ID UNKNOWN]`)),!1;let i;return i=L5(e)?e:{...e,id:U5(e)},i=V5(i,void 0,r),!ece(i,t)&&i}function Sce(e,t,n,r,i){if(!t.source||!t.target)return i(new b7(v7.EDGE_INVALID,e.id)),!1;if(!n)return i(new b7(v7.EDGE_NOT_FOUND,e.id)),!1;let{id:a,...o}=e;return{...o,id:r?U5(t):a,source:t.source,target:t.target,sourceHandle:t.sourceHandle,targetHandle:t.targetHandle}}function F7(e,t,n){let r={},i=[];for(let a=0;a<e.length;++a){let o=e[a];if(!R5(o)){n(new b7(v7.NODE_INVALID,o?.id));continue}let s=Zse(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 b7(v7.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 I7(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 L7(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}`;I7(`sourcLine truncated
`)},B(e.data.summary||e.data.detail),9,uue)):F(``,!0),e.data.when||e.data.retry||e.data.continues?(L(),j(`div`,due,[e.data.when?(L(),j(`span`,{key:0,class:`flex max-w-full min-w-0 items-center gap-0.5 rounded bg-secondary px-1 font-mono`,title:`Runs only when ${e.data.when}`},[A(V(au),{class:`size-3 shrink-0`,"aria-hidden":`true`}),R(`span`,pue,B(e.data.when),1)],8,fue)):F(``,!0),e.data.retry?(L(),j(`span`,{key:1,class:`flex items-center gap-0.5 rounded bg-secondary px-1`,title:`Up to ${e.data.retry} attempts`},[A(V(hte),{class:`size-3`,"aria-hidden":`true`}),H(`×`+B(e.data.retry),1)],8,mue)):F(``,!0),e.data.continues?(L(),j(`span`,hue,[A(V(Ste),{class:`size-3`,"aria-hidden":`true`}),r[10]||=H(`continues`,-1)])):F(``,!0)])):F(``,!0),e.data.run?.error?(L(),j(`p`,{key:4,class:`mt-1 line-clamp-2 text-caption text-danger`,title:e.data.run.error},B(e.data.run.error),9,gue)):F(``,!0)],64))]),A(ut,{"enter-from-class":`opacity-0 -translate-y-1`,"enter-active-class":`transition duration-200`,"leave-to-class":`opacity-0`,"leave-active-class":`transition duration-100`},{default:I(()=>[e.data.expanded?(L(),j(`div`,{key:0,class:`nodrag nopan nowheel cursor-auto border-t border-border`,onClick:r[6]||=pt(()=>{},[`stop`])},[K(t.$slots,`default`)])):F(``,!0)]),_:3}),A(V($7),{type:`source`,position:V(v5).Bottom},null,8,[`position`]),A(V($7),{id:`data-out`,type:`source`,position:V(v5).Right,class:`!opacity-0`},null,8,[`position`]),e.data.type===`switch`?(L(),q(V($7),{key:1,id:`otherwise`,type:`source`,position:V(v5).Right,class:`!opacity-0`},null,8,[`position`])):F(``,!0)],2))}}),vue={class:`pointer-events-none size-full rounded-xl border border-dashed border-border bg-muted/30`},yue={class:`flex items-center gap-1 px-2.5 pt-1.5 text-caption text-fg-subtle`},bue={key:0},xue={key:1,class:`font-mono`},Sue=P({__name:`LaneNode`,props:{data:{}},setup(e){return(t,n)=>(L(),j(`div`,vue,[R(`div`,yue,[e.data.lane===`switch`?(L(),j(U,{key:0},[A(V(Ou),{class:`size-3`,"aria-hidden":`true`}),e.data.title==="default"?(L(),j(`span`,bue,`otherwise`)):(L(),j(`span`,xue,`= `+B(e.data.title),1))],64)):(L(),j(U,{key:1},[A(V(su),{class:`size-3`,"aria-hidden":`true`}),H(B(e.data.title),1)],64))])]))}}),Cue={class:`flex shrink-0 items-center justify-center gap-1 border-t border-border bg-card p-1`},C9=240,wue=416,w9=-140,Tue=72,Eue=.9,T9=P({__name:`WorkflowCanvas`,props:{yaml:{},stages:{},open:{},triggers:{},types:{},readonly:{type:Boolean},restartable:{type:Boolean},marks:{},problems:{},title:{},summary:{}},emits:[`toggle`,`insert`,`duplicate`,`move`,`remove`,`rename`,`restart`],setup(e,{emit:t}){let n=e,r=t,i=Y(()=>!!n.types?.length&&!n.readonly),a=Y(()=>[...n.types??[],`parallel`,`switch`]),o=Y(()=>a.value.filter(e=>[`agent.run`,`workflow.call`].includes(e))),s=e=>e&&l0(e)?o.value:a.value,c=e=>e.kind===`step`?JSON.stringify(e.path??null):e.kind,l=J(null),u=J(null),d=lee(`(max-width: 767px)`),f=Y(()=>{let e=O0(z0(n.yaml),n.stages??[]);return n.types?.length?{nodes:[{id:`workflow`,type:`step`,position:{x:0,y:w9},data:{kind:`workflow`,key:`workflow`,title:n.title||`Workflow`,type:``,detail:n.summary??``}},...e.nodes],edges:[{id:`flow-workflow-start`,source:`workflow`,target:`start`,kind:`flow`},...e.edges]}:e}),p=Y(()=>f.value.nodes.filter(e=>e.data.path?.length===2).length),m=J({}),h=J({}),g=Y(()=>f.value.nodes.find(e=>e.type===`step`&&c(e.data)===n.open));function _(e,t){m.value={...m.value,[e]:t},g.value?.id!==e&&(h.value={...h.value,[e]:t})}let v=Y(()=>{let e=d.value?void 0:g.value?.id;return e&&m.value[e]?Math.max(0,m.value[e]-(h.value[e]??m.value[e])):0}),y=Ot(),b=see(v,{duration:Y(()=>y.value===`reduce`?0:200)}),x=Y(()=>{let e=new Map;for(let t of f.value.nodes){if(t.type!==`step`)continue;let n=(t.id===g.value?.id?h.value[t.id]:void 0)??m.value[t.id];n!==void 0&&e.set(t.position.y,Math.max(e.get(t.position.y)??-72,n-Tue))}return[...e]}),S=e=>x.value.reduce((t,[n,r])=>n<e?t+r:t,0);function C(e){let t=e.data,a=c(t),o=t.path,s={triggers:t.kind===`start`?n.triggers??[]:t.triggers,expanded:!d.value&&a===n.open,editable:i.value,problem:o?n.problems?.[a]:void 0,onResize:t=>_(e.id,t)};return n.types?.length&&(s.onToggle=()=>r(`toggle`,a)),i.value&&o&&(s.onRename=e=>r(`rename`,o,e),s.onDuplicate=()=>r(`duplicate`,o),s.onRemove=()=>r(`remove`,o)),{...e,data:{...t,...s}}}let w=e=>{let t=g.value;return d.value||!t||!e.style?.width?!1:e.position.x<=t.position.x&&e.position.x+parseFloat(String(e.style.width))>=t.position.x+C9};function T(e){let t=g.value;if(d.value||!t)return 0;if(e.id===t.id||w(e))return-88;let n=t.position.x+C9/2,r=e.style?.width?parseFloat(String(e.style.width)):e.type===`step`?C9:32,i=e.position.x+r/2;return Math.abs(i-n)<C9/2?0:i<n?-88:88}let ee=Y(()=>{let e=g.value;return f.value.nodes.map(t=>{let a=t;t.type===`add`?t={...t,data:{...t.data,types:s(t.data.insertAfter),editable:i.value,onInsert:e=>r(`insert`,t.data.insertAfter,e)}}:t.type===`step`&&(t=C(t));let o=n.marks?.[t.id];o&&(t={...t,data:{...t.data,mark:o}});let c=t.position Line truncated
`),r=t.split(`
`),i=Array.from({length:n.length+1},()=>Array(r.length+1).fill(0));for(let e=n.length-1;e>=0;e--)for(let t=r.length-1;t>=0;t--)i[e][t]=n[e]===r[t]?i[e+1][t+1]+1:Math.max(i[e+1][t],i[e][t+1]);let a=[],o=0,s=0;for(;o<n.length&&s<r.length;)n[o]===r[s]?(a.push({kind:`same`,text:n[o++]}),s++):i[o+1][s]>=i[o][s+1]?a.push({kind:`del`,text:n[o++]}):a.push({kind:`add`,text:r[s++]});for(;o<n.length;)a.push({kind:`del`,text:n[o++]});for(;s<r.length;)a.push({kind:`add`,text:r[s++]});return a}function E9(e){let t=p0(e).toJS(),n=new Map;for(let r of Y0(e).nodes){let{kind:e,path:i,stage:a,occurrence:o}=r.data;if(r.type!==`step`||e!==`step`||!i||a===void 0)continue;let s=t;for(let e of i)s=s?.[e];n.set(`${a}#${o??0}`,{node:r.id,signature:JSON.stringify(s??null)})}return n}function D9(e,t,n){let r=E9(e),i=E9(t),a={};for(let[e,t]of r){let r=i.get(e);r?r.signature!==t.signature&&(a[t.node]=`changed`):a[t.node]=n}return a}var Hue={class:`flex flex-col gap-3 md:grid md:h-[calc(100dvh-17rem)] md:min-h-[26rem] md:grid-cols-[18rem_1fr]`},Uue=[`aria-current`,`onClick`],Wue={class:`flex items-center gap-2 text-sm`},Gue={class:`font-mono text-xs text-fg-subtle`},Kue=[`title`],que={key:0,class:`px-3 py-2 text-sm text-fg-muted`},Jue={key:1,class:`flex min-h-0 flex-col gap-2`},Yue={class:`flex items-center gap-2 max-md:flex-wrap`},Xue={key:0,class:`rounded-lg border border-border p-4 text-sm text-fg-muted`},Zue={key:1,class:`min-h-0 flex-1 overflow-auto rounded-lg border border-border pt-2 pb-[calc(0.5rem+var(--code-overscroll))] font-mono text-label leading-6`},Que={class:`inline-block w-4 select-none text-fg-subtle`},$ue={key:2,class:`grid min-h-0 flex-1 gap-3 max-md:flex-none md:grid-cols-2`},ede={class:`flex min-h-0 flex-col gap-1`},tde={class:`text-caption font-medium uppercase text-fg-muted`},nde={class:`min-h-0 flex-1 max-md:h-72 max-md:flex-none`},rde={class:`flex min-h-0 flex-col gap-1`},ide={class:`min-h-0 flex-1 max-md:h-72 max-md:flex-none`},ade=P({__name:`WorkflowHistory`,props:Ye({revisions:{},current:{},error:{}},{selected:{default:0},selectedModifiers:{},mode:{default:`yaml`},modeModifiers:{}}),emits:Ye([`restore`],[`update:selected`,`update:mode`]),setup(e,{emit:t}){let n=e,r=t,i=ke(e,`selected`),a=ke(e,`mode`);N(()=>n.revisions,e=>{e.some(e=>e.version===i.value)||(i.value=(e.find(e=>e.yaml!==n.current)??e[0])?.version??0)},{immediate:!0});let o=Y(()=>n.revisions.find(e=>e.version===i.value)),s=Y(()=>o.value?.yaml??null),c=Y(()=>s.value===null?[]:Vue(s.value,n.current)),l=Y(()=>s.value!==null&&s.value===n.current),u=Y(()=>s.value===null?{}:D9(s.value,n.current,`removed`)),d=Y(()=>s.value===null?{}:D9(n.current,s.value,`added`)),f={added:`default`,edited:`secondary`,removed:`destructive`};return(t,n)=>(L(),j(`div`,Hue,[R(`ol`,{class:z(V(W)(`min-h-0 divide-y divide-border overflow-y-auto rounded-lg border border-border`,e.revisions.length&&`max-md:hidden`)),"aria-label":`Revisions`},[(L(!0),j(U,null,M(e.revisions,e=>(L(),j(`li`,{key:e.version},[R(`button`,{type:`button`,class:z([`block w-full px-3 py-2 text-left hover:bg-secondary`,e.version===i.value&&`bg-secondary`]),"aria-current":e.version===i.value,onClick:t=>i.value=e.version},[R(`span`,Wue,[R(`span`,Gue,`v`+B(e.version),1),A(V(k),{variant:f[e.change]},{default:I(()=>[H(B(e.change),1)]),_:2},1032,[`variant`])]),R(`span`,{class:`mt-0.5 block truncate text-xs text-fg-muted`,title:e.at},[H(B(e.actor||`unknown`)+` · `+B(e.source||`unknown`)+` · `,1),A(V(fw),{at:e.at},null,8,[`at`])],8,Kue)],10,Uue)]))),128)),e.revisions.length?F(``,!0):(L(),j(`li`,que,B(e.error||`No recorded changes`),1))],2),e.revisions.length?(L(),q(V(Bu),{key:0,"model-value":String(i.value),"onUpdate:modelValue":n[0]||=e=>i.value=Number(e)},{default:I(()=>[A(V(Wu),{class:`w-full md:hidden`,"aria-label":`Revision`},{default:I(()=>[A(V(Gu))]),_:1}),A(V(Vu),null,{default:I(()=>[(L(!0),j(U,null,M(e.revisions,e=>(L(),q(V(Uu),{key:e.version,value:String(e.version)},{default:I(()=>[H(`v`+B(e.version)+` · `+B(e.change)+` · `+B(e.actor||`unknown`)+` · `+B(V(uw)(e.at)),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1},8,[`model-value`])):F(``,!0),o.value?(L(),j(`div`,Jue,[R(`div`,Yue,[A(V(_O),{modelValue:a.value,"onUpdate:modelValue":n[1]||=e=>a.value=e},{default:I(()=>[A(V(yO),null,{default:I(()=>[A(V(bO),{value:`yaml`},{default:I(()=>[...n[3]||=[H(`YAML`,-1)]]),_:1}),A(V(bO),{value:`canvas`},{default:I(()=>[...n[4]||=[H(`Canvas`,-1)]]),_:1})]),_:1})]),_:1},8,[`modelValue`]),A(V(X),{type:`button`,size:`sm`,variant:`outline`,class:`ml-auto`,disabled:s.value===null||l.value,title:s.value===null?`Workflow removed`:void 0,onClick:n[2]||=e=>r(`restore`,s.value)},{default:I(()=>[A(V(Eu),{"data-icon":`inline-start`}),n[5]||=H(` Restore this version`,-1)]),_:1},8,[`disabled`,`title`])]),s.value===null?(L(),j(`p`,Xue,`Workflow removed in this revision.`)):a.value===`yaml`?(L(),j(`pre`,Zue,[R(`code`,null,[(L(!0),j(U,null,M(c.value,(e,t)=>(L(),j(`span`,{key:t,class:z([`block min-h-6 px-3 whitespace-pre-wrap`,{"bg-o Line truncated
`),i=Array.from({length:n.length+1},()=>Array(r.length+1).fill(0));for(let e=n.length-1;e>=0;e--)for(let t=r.length-1;t>=0;t--)i[e][t]=n[e]===r[t]?i[e+1][t+1]+1:Math.max(i[e+1][t],i[e][t+1]);let a=[],o=0,s=0;for(;o<n.length&&s<r.length;)n[o]===r[s]?(a.push({kind:`same`,text:n[o++]}),s++):i[o+1][s]>=i[o][s+1]?a.push({kind:`del`,text:n[o++]}):a.push({kind:`add`,text:r[s++]});for(;o<n.length;)a.push({kind:`del`,text:n[o++]});for(;s<r.length;)a.push({kind:`add`,text:r[s++]});return a}function E9(e){let t=r0(e).toJS(),n=new Map;for(let r of z0(e).nodes){let{kind:e,path:i,stage:a,occurrence:o}=r.data;if(r.type!==`step`||e!==`step`||!i||a===void 0)continue;let s=t;for(let e of i)s=s?.[e];n.set(`${a}#${o??0}`,{node:r.id,signature:JSON.stringify(s??null)})}return n}function D9(e,t,n){let r=E9(e),i=E9(t),a={};for(let[e,t]of r){let r=i.get(e);r?r.signature!==t.signature&&(a[t.node]=`changed`):a[t.node]=n}return a}var jue={class:`flex flex-col gap-3 md:grid md:h-[calc(100dvh-17rem)] md:min-h-[26rem] md:grid-cols-[18rem_1fr]`},Mue=[`aria-current`,`onClick`],Nue={class:`flex items-center gap-2 text-sm`},Pue={class:`font-mono text-xs text-fg-subtle`},Fue=[`title`],Iue={key:0,class:`px-3 py-2 text-sm text-fg-muted`},Lue={key:1,class:`flex min-h-0 flex-col gap-2`},Rue={class:`flex items-center gap-2 max-md:flex-wrap`},zue={key:0,class:`rounded-lg border border-border p-4 text-sm text-fg-muted`},Bue={key:1,class:`min-h-0 flex-1 overflow-auto rounded-lg border border-border pt-2 pb-[calc(0.5rem+var(--code-overscroll))] font-mono text-label leading-6`},Vue={class:`inline-block w-4 select-none text-fg-subtle`},Hue={key:2,class:`grid min-h-0 flex-1 gap-3 max-md:flex-none md:grid-cols-2`},Uue={class:`flex min-h-0 flex-col gap-1`},Wue={class:`text-caption font-medium uppercase text-fg-muted`},Gue={class:`min-h-0 flex-1 max-md:h-72 max-md:flex-none`},Kue={class:`flex min-h-0 flex-col gap-1`},que={class:`min-h-0 flex-1 max-md:h-72 max-md:flex-none`},Jue=P({__name:`WorkflowHistory`,props:Ye({revisions:{},current:{},error:{}},{selected:{default:0},selectedModifiers:{},mode:{default:`yaml`},modeModifiers:{}}),emits:Ye([`restore`],[`update:selected`,`update:mode`]),setup(e,{emit:t}){let n=e,r=t,i=ke(e,`selected`),a=ke(e,`mode`);N(()=>n.revisions,e=>{e.some(e=>e.version===i.value)||(i.value=(e.find(e=>e.yaml!==n.current)??e[0])?.version??0)},{immediate:!0});let o=Y(()=>n.revisions.find(e=>e.version===i.value)),s=Y(()=>o.value?.yaml??null),c=Y(()=>s.value===null?[]:Aue(s.value,n.current)),l=Y(()=>s.value!==null&&s.value===n.current),u=Y(()=>s.value===null?{}:D9(s.value,n.current,`removed`)),d=Y(()=>s.value===null?{}:D9(n.current,s.value,`added`)),f={added:`default`,edited:`secondary`,removed:`destructive`};return(t,n)=>(L(),j(`div`,jue,[R(`ol`,{class:z(V(W)(`min-h-0 divide-y divide-border overflow-y-auto rounded-lg border border-border`,e.revisions.length&&`max-md:hidden`)),"aria-label":`Revisions`},[(L(!0),j(U,null,M(e.revisions,e=>(L(),j(`li`,{key:e.version},[R(`button`,{type:`button`,class:z([`block w-full px-3 py-2 text-left hover:bg-secondary`,e.version===i.value&&`bg-secondary`]),"aria-current":e.version===i.value,onClick:t=>i.value=e.version},[R(`span`,Nue,[R(`span`,Pue,`v`+B(e.version),1),A(V(k),{variant:f[e.change]},{default:I(()=>[H(B(e.change),1)]),_:2},1032,[`variant`])]),R(`span`,{class:`mt-0.5 block truncate text-xs text-fg-muted`,title:e.at},[H(B(e.actor||`unknown`)+` · `+B(e.source||`unknown`)+` · `,1),A(V(fw),{at:e.at},null,8,[`at`])],8,Fue)],10,Mue)]))),128)),e.revisions.length?F(``,!0):(L(),j(`li`,Iue,B(e.error||`No recorded changes`),1))],2),e.revisions.length?(L(),q(V(zu),{key:0,"model-value":String(i.value),"onUpdate:modelValue":n[0]||=e=>i.value=Number(e)},{default:I(()=>[A(V(Uu),{class:`w-full md:hidden`,"aria-label":`Revision`},{default:I(()=>[A(V(Wu))]),_:1}),A(V(Bu),null,{default:I(()=>[(L(!0),j(U,null,M(e.revisions,e=>(L(),q(V(Hu),{key:e.version,value:String(e.version)},{default:I(()=>[H(`v`+B(e.version)+` · `+B(e.change)+` · `+B(e.actor||`unknown`)+` · `+B(V(uw)(e.at)),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1},8,[`model-value`])):F(``,!0),o.value?(L(),j(`div`,Lue,[R(`div`,Rue,[A(V(_O),{modelValue:a.value,"onUpdate:modelValue":n[1]||=e=>a.value=e},{default:I(()=>[A(V(yO),null,{default:I(()=>[A(V(bO),{value:`yaml`},{default:I(()=>[...n[3]||=[H(`YAML`,-1)]]),_:1}),A(V(bO),{value:`canvas`},{default:I(()=>[...n[4]||=[H(`Canvas`,-1)]]),_:1})]),_:1})]),_:1},8,[`modelValue`]),A(V(X),{type:`button`,size:`sm`,variant:`outline`,class:`ml-auto`,disabled:s.value===null||l.value,title:s.value===null?`Workflow removed`:void 0,onClick:n[2]||=e=>r(`restore`,s.value)},{default:I(()=>[A(V(Tu),{"data-icon":`inline-start`}),n[5]||=H(` Restore this version`,-1)]),_:1},8,[`disabled`,`title`])]),s.value===null?(L(),j(`p`,zue,`Workflow removed in this revision.`)):a.value===`yaml`?(L(),j(`pre`,Bue,[R(`code`,null,[(L(!0),j(U,null,M(c.value,(e,t)=>(L(),j(`span`,{key:t,class:z([`block min-h-6 px-3 whitespace-pre-wrap`,{"bg-o Line truncated
+1 -1
View File
@@ -41,7 +41,7 @@ const orgSpecs: NavSpec[] = [
},
{
label: "Automation",
paths: ["/org/schedules", "/org/playbooks"],
paths: ["/org/playbooks"],
},
],
},
+1 -1
View File
@@ -16,7 +16,7 @@ const areas = [
{ title: "Execution identities", to: "/org/agents" },
{ title: "Connections", to: "/org/connections" },
{ title: "Models", to: "/org/models" },
{ title: "Schedules and playbooks", to: "/org/schedules" },
{ title: "Playbooks", to: "/org/playbooks" },
{ title: "Members and access", to: "/org/members" },
];
</script>
-8
View File
@@ -16,7 +16,6 @@ import OrgModelsPage from "@/org/OrgModelsPage.vue";
import SchedulingPolicyPage from "@/settings/SchedulingPolicyPage.vue";
import ToolsPage from "@/settings/ToolsPage.vue";
import InstructionsPage from "@/settings/InstructionsPage.vue";
import SchedulesPage from "@/settings/SchedulesPage.vue";
import ExtensionsPage from "@/settings/ExtensionsPage.vue";
import PluginsPage from "@/settings/PluginsPage.vue";
import SecretEnginesPage from "@/settings/SecretEnginesPage.vue";
@@ -252,12 +251,6 @@ const routes = [
component: InstructionsPage,
meta: { label: "Instructions", navPath: "/org" },
},
{
path: "schedules",
name: "org-schedules",
component: SchedulesPage,
meta: { label: "Schedules", navPath: "/org" },
},
{
path: "playbooks",
name: "org-playbooks",
@@ -283,7 +276,6 @@ const routes = [
"/settings/credential-bindings": "/org/credential-bindings",
"/settings/soul": "/org/instructions",
"/org/soul": "/org/instructions",
"/settings/schedules": "/org/schedules",
"/settings/playbooks": "/org/playbooks",
}).map(([path, redirect]) => ({ path, redirect, meta: { nav: false } })),
{
-190
View File
@@ -1,190 +0,0 @@
<script setup lang="ts">
import ApplyStatusRows from "./ApplyStatusRows.vue";
import { computed, onMounted, ref } from "vue";
import { storeToRefs } from "pinia";
import { CalendarClock, Plus } from "@lucide/vue";
import PageHeader from "@/base/PageHeader.vue";
import { Button } from "@/components/ui/button";
import {
Empty,
EmptyContent,
EmptyHeader,
EmptyMedia,
EmptyTitle,
} from "@/components/ui/empty";
import { DurationInput } from "@/components/ui/duration-input";
import { Input } from "@/components/ui/input";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { SettingRow } from "@/components/ui/setting-row";
import { Textarea } from "@/components/ui/textarea";
import { Timestamp } from "@/components/ui/timestamp";
import { resourcesForPage, useSettingsStore } from "@/stores/settings";
import CardAccordion from "./CardAccordion.vue";
import DraftHint from "./DraftHint.vue";
import HistoryLink from "./HistoryLink.vue";
const KIND = "schedules";
/** A scheduled job: "workflow" starts a task, "chat" sends a message. */
interface Job {
id: string;
kind: string;
detail?: string;
pool?: string;
schedule: { kind?: string; interval?: string; cron?: string; at?: string };
target: { channel?: string; chat_id?: string };
payload: { text?: string };
next_run?: string;
}
const store = useSettingsStore();
const { catalog, catalogError } = storeToRefs(store);
onMounted(store.load);
const resources = computed(() => resourcesForPage(catalog.value, "schedules"));
const jobs = computed(() => store.drafts[KIND]?.value as Job[] | undefined);
const error = computed(() => store.pageErrorFor(KIND));
const issues = computed(() => store.issuesFor(KIND));
const jobIssue = (i: number) => issues.value.find((entry) => entry.path.startsWith(`${i}.`));
const whenKinds = [
{ value: "interval", label: "Every" },
{ value: "cron", label: "Cron" },
{ value: "once", label: "Once" },
];
const jobKinds = [
{ value: "workflow", label: "Run a task" },
{ value: "chat", label: "Send a message" },
];
const pools = [
{ value: "sequential", label: "Sequential" },
{ value: "parallel", label: "Parallel" },
];
const open = ref("");
const unsaved = computed(() => store.changesFor(KIND).length > 0);
function add() {
if (unsaved.value || !jobs.value) return;
jobs.value.push({
id: crypto.randomUUID(),
kind: "workflow",
detail: "Scheduled task",
pool: "",
schedule: { kind: "interval", interval: "24h0m0s" },
target: {},
payload: { text: "" },
});
open.value = String(jobs.value.length - 1);
}
// datetime-local speaks local wall time without a zone; the document stores
// an RFC 3339 instant.
function toLocalInput(iso?: string): string {
if (!iso) return "";
const d = new Date(iso);
const pad = (n: number) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
function fromLocalInput(value: string): string | undefined {
return value ? new Date(value).toISOString() : undefined;
}
const whenKind = (job: Job) => job.schedule.kind || "interval";
</script>
<template>
<div>
<PageHeader title="Schedules">
<HistoryLink :kinds="resources.map((r) => r.kind)" />
<Button v-if="jobs?.length" size="sm" :disabled="unsaved" @click="add"><Plus data-icon="inline-start" />Add schedule</Button>
</PageHeader>
<ApplyStatusRows v-for="resource in resources" :key="resource.kind" :kind="resource.kind" class="mb-4" />
<p v-if="catalogError || error" class="mb-4 text-sm text-danger" role="alert">
{{ catalogError || error }}
</p>
<template v-if="jobs">
<Empty v-if="!jobs?.length">
<EmptyMedia variant="icon">
<CalendarClock />
</EmptyMedia>
<EmptyHeader>
<EmptyTitle>No schedules yet</EmptyTitle>
</EmptyHeader>
<EmptyContent>
<Button size="sm" @click="add"><Plus data-icon="inline-start" />Add schedule</Button>
</EmptyContent>
</Empty>
<CardAccordion v-model:open="open" :items="jobs" :title="(job) => job.detail || job.id || 'New schedule'" remove-label="Delete" @remove="jobs.splice($event, 1)">
<template #aside="{ item: job }">
<span v-if="job.next_run" class="text-xs text-fg-subtle">Next run <Timestamp :at="job.next_run" absolute /></span>
</template>
<template #default="{ item: job, index: i }">
<SettingRow label="Schedule name" :for="`job-${i}-name`" hint="Used as the task title for scheduled workflows.">
<Input :id="`job-${i}-name`" v-model="job.detail" class="max-w-md" />
<DraftHint :kind="KIND" :path="`${i}.detail`" />
<p v-if="jobIssue(i)" class="mt-1.5 text-xs text-danger" role="alert">{{ jobIssue(i)?.message }}</p>
</SettingRow>
<SettingRow label="Does">
<div class="flex flex-wrap items-center gap-3">
<ToggleGroup type="single" variant="outline" size="sm" :model-value="job.kind" aria-label="Does" @update:model-value="(value) => { if (!value) return; job.kind = value as string; job.target = value === 'chat' ? { channel: 'telegram', chat_id: '' } : {}; }">
<ToggleGroupItem v-for="option in jobKinds" :key="option.value" :value="option.value">{{ option.label }}</ToggleGroupItem>
</ToggleGroup>
<DraftHint :kind="KIND" :path="`${i}.kind`" />
</div>
</SettingRow>
<SettingRow v-if="job.kind === 'chat'" label="To" :for="`job-${i}-chat`">
<div class="flex flex-wrap items-center gap-3">
<Input v-model="job.target.channel" class="w-32 font-mono" aria-label="Channel" placeholder="telegram" />
<Input :id="`job-${i}-chat`" v-model="job.target.chat_id" class="w-48 font-mono" aria-label="Chat ID" placeholder="Chat ID" />
<DraftHint :kind="KIND" :path="`${i}.target.chat_id`" />
</div>
</SettingRow>
<SettingRow :label="job.kind === 'chat' ? 'Message' : 'Instructions'" :for="`job-${i}-text`">
<Textarea :id="`job-${i}-text`" v-model="job.payload.text" :rows="3" />
<DraftHint :kind="KIND" :path="`${i}.payload.text`" />
</SettingRow>
<SettingRow label="When">
<div class="flex flex-wrap items-center gap-3">
<ToggleGroup type="single" variant="outline" size="sm" :model-value="whenKind(job)" aria-label="When" @update:model-value="(value) => { if (value) job.schedule = { kind: value as string, interval: value === 'interval' ? '24h0m0s' : undefined }; }">
<ToggleGroupItem v-for="option in whenKinds" :key="option.value" :value="option.value">{{ option.label }}</ToggleGroupItem>
</ToggleGroup>
<DurationInput v-if="whenKind(job) === 'interval'" v-model="job.schedule.interval!" :units="['m', 'h']" />
<Input
v-else-if="whenKind(job) === 'cron'"
v-model="job.schedule.cron"
class="w-48 font-mono"
placeholder="0 9 * * 1-5"
aria-label="Cron expression"
/>
<Input
v-else
type="datetime-local"
class="w-60 font-mono"
aria-label="Run at"
:model-value="toLocalInput(job.schedule.at)"
@update:model-value="(v) => (job.schedule.at = fromLocalInput(String(v)))"
/>
<DraftHint
:kind="KIND"
:path="whenKind(job) === 'cron' ? `${i}.schedule.cron` : whenKind(job) === 'once' ? `${i}.schedule.at` : `${i}.schedule.interval`"
/>
<DraftHint :kind="KIND" :path="`${i}.schedule.kind`" />
</div>
</SettingRow>
<SettingRow label="Overlap">
<div class="flex flex-wrap items-center gap-3">
<ToggleGroup type="single" variant="outline" size="sm" :model-value="job.pool || 'sequential'" aria-label="Overlap" @update:model-value="(value) => { if (value) job.pool = value === 'sequential' ? '' : (value as string); }">
<ToggleGroupItem v-for="option in pools" :key="option.value" :value="option.value">{{ option.label }}</ToggleGroupItem>
</ToggleGroup>
<DraftHint :kind="KIND" :path="`${i}.pool`" />
</div>
</SettingRow>
</template>
</CardAccordion>
</template>
</div>
</template>
-24
View File
@@ -78,29 +78,6 @@ export function validateSchedulingPolicy(value: unknown): FieldIssue[] {
return issues;
}
interface ScheduleDraft {
id?: string;
}
/** validateSchedules mirrors validateSchedules: an ID on every job, and no two
* jobs sharing one. */
export function validateSchedules(value: unknown): FieldIssue[] {
const jobs = Array.isArray(value) ? (value as ScheduleDraft[]) : [];
const issues: FieldIssue[] = [];
const seen = new Set<string>();
jobs.forEach((job, i) => {
const id = job.id?.trim() ?? "";
if (!id) {
issues.push({ path: `${i}.id`, label: `Schedule ${i + 1}`, message: "ID is required." });
return;
}
if (seen.has(id))
issues.push({ path: `${i}.id`, label: `Schedule ${i + 1}`, message: `Duplicate schedule "${id}".` });
seen.add(id);
});
return issues;
}
const MODEL_ALIAS_NAME = /^[a-z0-9][a-z0-9._-]*$/;
/** validateModelAliases mirrors the server's validateModelAliases: alias
@@ -122,6 +99,5 @@ export function validateModelAliases(value: unknown): FieldIssue[] {
/** The rules the store applies to a dirty draft, keyed by resource kind. */
export const draftValidators: Record<string, DraftValidator> = {
"scheduling-policy": validateSchedulingPolicy,
schedules: validateSchedules,
"model-aliases": validateModelAliases,
};
-2
View File
@@ -171,7 +171,6 @@ export type ControlPlanePage =
| "scheduling"
| "tools"
| "soul"
| "schedules"
| "plugins"
| "containers"
| "review";
@@ -185,7 +184,6 @@ const PAGE_RESOURCES: Record<ControlPlanePage, string[]> = {
scheduling: ["scheduling-policy"],
tools: ["tool-settings"],
soul: ["soul"],
schedules: ["schedules"],
plugins: ["plugin-settings"],
containers: ["container-runtime-policies"],
review: ["review-settings"],
@@ -4,7 +4,6 @@ import test from "node:test";
import {
validateModelAliases,
validateSchedules,
validateSchedulingPolicy,
type DraftValidator,
} from "../src/settings/validation.ts";
@@ -46,7 +45,6 @@ const fixture = JSON.parse(
const validators: Record<string, DraftValidator> = {
"model-aliases": validateModelAliases,
"scheduling-policy": validateSchedulingPolicy,
schedules: validateSchedules,
};
test("the dashboard validators agree with the control plane's fixture", () => {
-17
View File
@@ -1,17 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import { validateSchedules } from "../src/settings/validation.ts";
test("schedules refuse an empty id and a duplicate, keeping each row's path", () => {
const issues = validateSchedules([
{ id: "daily" },
{ id: "" },
{ id: "daily" },
]);
assert.deepEqual(issues, [
{ path: "1.id", label: "Schedule 2", message: "ID is required." },
{ path: "2.id", label: "Schedule 3", message: 'Duplicate schedule "daily".' },
]);
assert.deepEqual(validateSchedules([{ id: "daily" }, { id: "weekly" }]), []);
});