feat(controlplane): field-level sys_audit table, audit view on settings pages, whole-task time limit

This commit is contained in:
sam committed 2026-09-25 09:54:30 +10:00
1 parent 49d7527f1c
commit 8fea8e8686
43 files changed
+1176 -174

No files matched your search

+2 -1
View File
@@ -308,8 +308,9 @@ listen = "127.0.0.1:8484"
[budgets]
max_steps = 60
wall_clock = "30m"
wall_clock = "30m" # one agent call
gate_max_failures = 5
task_wall_clock = "4h" # a whole task run; keep containers.max_uptime at or above it
# Services selects contract adapters at composition time (see
# docs/prds/state-store-contract.md).
+4
View File
@@ -202,12 +202,16 @@ func (b *boot) applyWorkflowExecutionSettings(ctx context.Context, settings work
b.cfgHolder.Set(candidate.cfg)
b.applyStatus.Report(ctx, controlplane.WorkflowExecutionSettingsKind, version, nil)
b.log.Info("workflow execution settings applied", "version", version)
if limit, uptime := settings.MaxTaskRuntime, candidate.cfg.Containers.MaxUptime.Std(); uptime > 0 && (limit <= 0 || limit > uptime) {
b.log.Warn("containers.max_uptime is shorter than the task time limit; the container is killed first", "max_uptime", uptime, "max_task_runtime", limit)
}
return nil
}
func applyExecutionBudgets(cfg *config.Config, settings workflow.ExecutionSettings) {
cfg.Budgets = config.Budgets{
MaxSteps: settings.MaxModelToolSteps, WallClock: config.Duration(settings.MaxRuntime), GateMaxFailures: settings.MaxConsecutiveGateFailures,
TaskWallClock: config.Duration(settings.MaxTaskRuntime),
}
for i := range cfg.Identities {
cfg.Identities[i].Budgets = cfg.Budgets
@@ -25,7 +25,7 @@ import (
// limits stayed" and a test that asserts "the update was applied" cannot
// disagree about what "running" means.
var (
bootedSettings = workflow.ExecutionSettings{MaxModelToolSteps: 10, MaxRuntime: 5 * time.Minute, MaxConsecutiveGateFailures: 3}
bootedSettings = workflow.ExecutionSettings{MaxModelToolSteps: 10, MaxRuntime: 5 * time.Minute, MaxConsecutiveGateFailures: 3, MaxTaskRuntime: 4 * time.Hour}
bootedDocument = `{"max_model_tool_steps": 10, "max_runtime_seconds": 300, "max_consecutive_gate_failures": 3}`
)
@@ -124,6 +124,10 @@ func (*settingsWatchStub) History(context.Context, *pb.HistoryRequest, ...grpc.C
panic("unexpected History")
}
func (*settingsWatchStub) Audit(context.Context, *pb.AuditRequest, ...grpc.CallOption) (*pb.AuditResponse, error) {
return &pb.AuditResponse{}, nil
}
func (*settingsWatchStub) Command(context.Context, *pb.CommandRequest, ...grpc.CallOption) (*pb.CommandResponse, error) {
panic("unexpected Command")
}
@@ -297,7 +301,7 @@ func TestLiveExecutionSettingsRefusalIsReportedThroughTheClient(t *testing.T) {
{
name: "an update the process can run is applied",
document: `{"max_model_tool_steps": 25, "max_runtime_seconds": 3600, "max_consecutive_gate_failures": 4}`,
wantRunning: workflow.ExecutionSettings{MaxModelToolSteps: 25, MaxRuntime: time.Hour, MaxConsecutiveGateFailures: 4},
wantRunning: workflow.ExecutionSettings{MaxModelToolSteps: 25, MaxRuntime: time.Hour, MaxConsecutiveGateFailures: 4, MaxTaskRuntime: 4 * time.Hour},
wantVersion: 2,
},
{
@@ -353,5 +357,6 @@ func budgetsFor(settings workflow.ExecutionSettings) config.Budgets {
MaxSteps: settings.MaxModelToolSteps,
WallClock: config.Duration(settings.MaxRuntime),
GateMaxFailures: settings.MaxConsecutiveGateFailures,
TaskWallClock: config.Duration(settings.MaxTaskRuntime),
}
}
@@ -48,6 +48,10 @@ func (*controlPlaneStub) History(context.Context, *pb.HistoryRequest, ...grpc.Ca
panic("unexpected History")
}
func (*controlPlaneStub) Audit(context.Context, *pb.AuditRequest, ...grpc.CallOption) (*pb.AuditResponse, error) {
return &pb.AuditResponse{}, nil
}
func (*controlPlaneStub) Command(context.Context, *pb.CommandRequest, ...grpc.CallOption) (*pb.CommandResponse, error) {
panic("unexpected Command")
}
@@ -50,7 +50,7 @@ const documentedStaleWindow = 90 * time.Second
// fileConfig()'s [budgets] on all three fields, so a process that comes back on
// any file value is detectably not on the stored one.
var restartEditedSettings = workflow.ExecutionSettings{
MaxModelToolSteps: 40, MaxRuntime: 10 * time.Minute, MaxConsecutiveGateFailures: 2,
MaxModelToolSteps: 40, MaxRuntime: 10 * time.Minute, MaxConsecutiveGateFailures: 2, MaxTaskRuntime: 4 * time.Hour,
}
// controlPlaneRestartFixture is a real State Store for the restart test: the
@@ -181,7 +181,7 @@ func TestRestartKeepsADatabaseOwnedSettingsChange(t *testing.T) {
firstCtx, stopFirst := context.WithCancel(t.Context())
first := startRestartProcess(firstCtx, t, fixture.dial(t))
stopFirst()
if got := first.cfgHolder.Get().Budgets; got != budgetsFor(workflow.ExecutionSettings{MaxModelToolSteps: 1, MaxRuntime: time.Minute}) {
if got := first.cfgHolder.Get().Budgets; got != budgetsFor(workflow.ExecutionSettings{MaxModelToolSteps: 1, MaxRuntime: time.Minute, MaxTaskRuntime: 4 * time.Hour}) {
t.Fatalf("first process budgets = %+v, want the seeded file budgets", got)
}
if got := first.cfgHolder.Get().PluginDir; got != fileConfig().PluginDir {
@@ -191,7 +191,7 @@ func TestRestartKeepsADatabaseOwnedSettingsChange(t *testing.T) {
// 1. The dashboard writes the change. Its handler, not this test, supplies
// the attribution: webAudit attributes to identity.SystemID.
expectedVersion := int64(1)
executionSettingsDocument := []byte(`{"max_model_tool_steps":40,"max_runtime_seconds":600,"max_consecutive_gate_failures":2}`)
executionSettingsDocument := []byte(`{"max_model_tool_steps":40,"max_runtime_seconds":600,"max_consecutive_gate_failures":2,"max_task_runtime_seconds":14400}`)
if version := dashboardReplace(t, dashboard, controlplane.WorkflowExecutionSettingsKind, executionSettingsDocument, expectedVersion); version != 2 {
t.Fatalf("workflow execution settings after edit = version %d, want 2", version)
}
@@ -334,6 +334,7 @@ func decodeExecutionSettingsRevision(t *testing.T, value json.RawMessage) workfl
MaxModelToolSteps int `json:"max_model_tool_steps"`
MaxRuntimeSeconds int64 `json:"max_runtime_seconds"`
MaxConsecutiveGateFailures int `json:"max_consecutive_gate_failures"`
MaxTaskRuntimeSeconds int64 `json:"max_task_runtime_seconds"`
}
if err := json.Unmarshal(value, &document); err != nil {
t.Fatalf("decode revision value: %v (%s)", err, value)
@@ -342,6 +343,7 @@ func decodeExecutionSettingsRevision(t *testing.T, value json.RawMessage) workfl
MaxModelToolSteps: document.MaxModelToolSteps,
MaxRuntime: time.Duration(document.MaxRuntimeSeconds) * time.Second,
MaxConsecutiveGateFailures: document.MaxConsecutiveGateFailures,
MaxTaskRuntime: time.Duration(document.MaxTaskRuntimeSeconds) * time.Second,
}
}
@@ -78,6 +78,10 @@ func (*watchStub) History(context.Context, *pb.HistoryRequest, ...grpc.CallOptio
panic("unexpected History")
}
func (*watchStub) Audit(context.Context, *pb.AuditRequest, ...grpc.CallOption) (*pb.AuditResponse, error) {
return &pb.AuditResponse{}, nil
}
func (*watchStub) Command(context.Context, *pb.CommandRequest, ...grpc.CallOption) (*pb.CommandResponse, error) {
panic("unexpected Command")
}
@@ -177,7 +181,7 @@ func (s *scriptStream) Recv() (*pb.WatchResponse, error) {
func TestWorkflowExecutionSettingsWatchIsReEstablishedAfterTheStreamEnds(t *testing.T) {
// 25 steps and an hour, so an applied update is unmistakably not the value
// the daemon booted with.
updated := workflow.ExecutionSettings{MaxModelToolSteps: 25, MaxRuntime: time.Hour, MaxConsecutiveGateFailures: 4}
updated := workflow.ExecutionSettings{MaxModelToolSteps: 25, MaxRuntime: time.Hour, MaxConsecutiveGateFailures: 4, MaxTaskRuntime: 4 * time.Hour}
updatedDocument := `{"max_model_tool_steps": 25, "max_runtime_seconds": 3600, "max_consecutive_gate_failures": 4}`
for _, tt := range watchStreamEnds {
@@ -358,7 +362,7 @@ func TestWatchTransportFailureDoesNotOverwriteARefusal(t *testing.T) {
// already runs, and reported a second time.
func TestWatchReconnectDoesNotReplayWhatItAlreadyApplied(t *testing.T) {
t.Parallel()
updated := workflow.ExecutionSettings{MaxModelToolSteps: 25, MaxRuntime: time.Hour, MaxConsecutiveGateFailures: 4}
updated := workflow.ExecutionSettings{MaxModelToolSteps: 25, MaxRuntime: time.Hour, MaxConsecutiveGateFailures: 4, MaxTaskRuntime: 4 * time.Hour}
updatedDocument := `{"max_model_tool_steps": 25, "max_runtime_seconds": 3600, "max_consecutive_gate_failures": 4}`
b, recorder := newLiveApplyBoot(t, fileConfig())
stub := &watchStub{
@@ -1089,6 +1093,10 @@ func (busyWatch) History(context.Context, *pb.HistoryRequest, ...grpc.CallOption
panic("unexpected History")
}
func (busyWatch) Audit(context.Context, *pb.AuditRequest, ...grpc.CallOption) (*pb.AuditResponse, error) {
return &pb.AuditResponse{}, nil
}
func (busyWatch) Command(context.Context, *pb.CommandRequest, ...grpc.CallOption) (*pb.CommandResponse, error) {
panic("unexpected Command")
}
+28
View File
@@ -33,6 +33,7 @@ var (
type ResourceStore interface {
Resource(context.Context, string) (storecontract.Resource, error)
ResourceHistory(context.Context, string, int) ([]storecontract.Resource, error)
Audit(ctx context.Context, table string, keys []string, limit int) ([]storecontract.AuditEntry, error)
PutResource(context.Context, storecontract.ResourceWrite) (storecontract.Resource, error)
}
@@ -109,6 +110,33 @@ func (s *Server) History(ctx context.Context, request *pb.HistoryRequest) (*pb.H
return &pb.HistoryResponse{Revisions: out}, nil
}
// defaultAuditLimit caps an audit read: a page shows recent changes, not the
// whole trail.
const defaultAuditLimit = 500
func (s *Server) Audit(ctx context.Context, request *pb.AuditRequest) (*pb.AuditResponse, error) {
if request.GetTable() == "" || len(request.GetRecordKeys()) == 0 {
return nil, status.Error(codes.InvalidArgument, "table and record keys are required")
}
limit := int(request.GetLimit())
if limit <= 0 || limit > defaultAuditLimit {
limit = defaultAuditLimit
}
entries, err := s.store.Audit(ctx, request.GetTable(), request.GetRecordKeys(), limit)
if err != nil {
return nil, mapError(err)
}
out := make([]*pb.AuditEntry, 0, len(entries))
for _, entry := range entries {
out = append(out, &pb.AuditEntry{
Id: entry.ID, Table: entry.Table, RecordKey: entry.RecordKey, Field: entry.Field,
OldValueJson: entry.OldValue, NewValueJson: entry.NewValue, Version: entry.Version,
Actor: entry.Actor, Source: entry.Source, RequestId: entry.RequestID, At: timestamp(entry.At),
})
}
return &pb.AuditResponse{Entries: out}, nil
}
func (s *Server) Command(ctx context.Context, request *pb.CommandRequest) (*pb.CommandResponse, error) {
definition, ok := s.definitions[request.GetKind()]
if !ok || request.GetCommand() != "replace" {
@@ -39,6 +39,10 @@ func (scriptedWatchClient) History(context.Context, *pb.HistoryRequest, ...grpc.
panic("History is not part of the watch path")
}
func (scriptedWatchClient) Audit(context.Context, *pb.AuditRequest, ...grpc.CallOption) (*pb.AuditResponse, error) {
return &pb.AuditResponse{}, nil
}
func (scriptedWatchClient) Command(context.Context, *pb.CommandRequest, ...grpc.CallOption) (*pb.CommandResponse, error) {
panic("Command is not part of the watch path")
}
@@ -28,6 +28,10 @@ func (*runtimeConfigClient) History(context.Context, *pb.HistoryRequest, ...grpc
panic("unexpected History")
}
func (*runtimeConfigClient) Audit(context.Context, *pb.AuditRequest, ...grpc.CallOption) (*pb.AuditResponse, error) {
return &pb.AuditResponse{}, nil
}
func (*runtimeConfigClient) Command(context.Context, *pb.CommandRequest, ...grpc.CallOption) (*pb.CommandResponse, error) {
panic("unexpected Command")
}
@@ -320,6 +320,10 @@ func (c *definitionsClient) History(context.Context, *pb.HistoryRequest, ...grpc
panic("History is not part of the workflow-definitions path")
}
func (c *definitionsClient) Audit(context.Context, *pb.AuditRequest, ...grpc.CallOption) (*pb.AuditResponse, error) {
return &pb.AuditResponse{}, nil
}
func (c *definitionsClient) Command(_ context.Context, request *pb.CommandRequest, _ ...grpc.CallOption) (*pb.CommandResponse, error) {
c.command = request
return &pb.CommandResponse{Resource: &pb.Resource{Version: 5}}, nil
+19 -4
View File
@@ -14,10 +14,17 @@ import (
const WorkflowExecutionSettingsKind = "workflow-execution-settings"
// defaultTaskRuntime bounds a task run when the stored settings predate the
// limit.
const defaultTaskRuntime = 4 * time.Hour
type executionSettingsDocument struct {
MaxModelToolSteps int `json:"max_model_tool_steps"`
MaxRuntimeSeconds int64 `json:"max_runtime_seconds"`
MaxRuntimeSeconds int64 `json:"max_runtime_seconds" title:"Max seconds per agent call" doc:"Limit for one agent call inside a stage. 0 disables it."`
MaxConsecutiveGateFailures int `json:"max_consecutive_gate_failures"`
// MaxTaskRuntimeSeconds is a pointer so a document stored before the
// field existed reads as the default, while an explicit 0 disables it.
MaxTaskRuntimeSeconds *int64 `json:"max_task_runtime_seconds" title:"Max task runtime seconds" doc:"Limit for a whole task run; the task is parked when it passes. 0 disables it."`
}
// ImportWorkflowExecutionSettings preserves the focused bootstrap API for callers
@@ -46,14 +53,18 @@ func workflowDefinition() Definition {
return Definition{
Kind: WorkflowExecutionSettingsKind, Title: "Workflow execution settings", ApplyMode: "live", Document: executionSettingsDocument{},
Seed: func(cfg config.Config) any {
return executionSettingsDocument{cfg.Budgets.MaxSteps, int64(time.Duration(cfg.Budgets.WallClock) / time.Second), cfg.Budgets.GateMaxFailures}
taskRuntime := time.Duration(cfg.Budgets.TaskWallClock)
if taskRuntime == 0 {
taskRuntime = defaultTaskRuntime
}
return executionSettingsDocument{cfg.Budgets.MaxSteps, int64(time.Duration(cfg.Budgets.WallClock) / time.Second), cfg.Budgets.GateMaxFailures, new(int64(taskRuntime / time.Second))}
},
Validate: func(input []byte) error { _, err := decodeSettings(input); return err },
}
}
func encodeSettings(s workflow.ExecutionSettings) ([]byte, error) {
return json.Marshal(executionSettingsDocument{s.MaxModelToolSteps, int64(s.MaxRuntime / time.Second), s.MaxConsecutiveGateFailures})
return json.Marshal(executionSettingsDocument{s.MaxModelToolSteps, int64(s.MaxRuntime / time.Second), s.MaxConsecutiveGateFailures, new(int64(s.MaxTaskRuntime / time.Second))})
}
func decodeSettings(value []byte) (workflow.ExecutionSettings, error) {
@@ -61,7 +72,11 @@ func decodeSettings(value []byte) (workflow.ExecutionSettings, error) {
if err := json.Unmarshal(value, &document); err != nil {
return workflow.ExecutionSettings{}, fmt.Errorf("%w: invalid JSON: %w", ErrValidation, err)
}
settings := workflow.ExecutionSettings{MaxModelToolSteps: document.MaxModelToolSteps, MaxRuntime: time.Duration(document.MaxRuntimeSeconds) * time.Second, MaxConsecutiveGateFailures: document.MaxConsecutiveGateFailures}
taskRuntime := defaultTaskRuntime
if document.MaxTaskRuntimeSeconds != nil {
taskRuntime = time.Duration(*document.MaxTaskRuntimeSeconds) * time.Second
}
settings := workflow.ExecutionSettings{MaxModelToolSteps: document.MaxModelToolSteps, MaxRuntime: time.Duration(document.MaxRuntimeSeconds) * time.Second, MaxConsecutiveGateFailures: document.MaxConsecutiveGateFailures, MaxTaskRuntime: taskRuntime}
if err := settings.Validate(); err != nil {
return workflow.ExecutionSettings{}, fmt.Errorf("%w: %w", ErrValidation, err)
}
@@ -0,0 +1,36 @@
package controlplane
import (
"testing"
"time"
)
func TestWorkflowSettingsTaskRuntime(t *testing.T) {
for _, tc := range []struct {
name string
value string
want time.Duration
}{
{"stored before the limit existed", `{"max_model_tool_steps":90,"max_runtime_seconds":3600,"max_consecutive_gate_failures":5}`, defaultTaskRuntime},
{"explicitly disabled", `{"max_task_runtime_seconds":0}`, 0},
{"set", `{"max_task_runtime_seconds":7200}`, 2 * time.Hour},
} {
t.Run(tc.name, func(t *testing.T) {
settings, err := decodeSettings([]byte(tc.value))
if err != nil {
t.Fatal(err)
}
if settings.MaxTaskRuntime != tc.want {
t.Fatalf("MaxTaskRuntime = %s, want %s", settings.MaxTaskRuntime, tc.want)
}
encoded, err := encodeSettings(settings)
if err != nil {
t.Fatal(err)
}
again, err := decodeSettings(encoded)
if err != nil || again.MaxTaskRuntime != tc.want {
t.Fatalf("round trip = %s, %v; want %s", again.MaxTaskRuntime, err, tc.want)
}
})
}
}
+3 -1
View File
@@ -167,11 +167,13 @@ func (r Repo) EffectiveMaxRetries(global int) int {
return global
}
// Budgets bound every agent stage. Zero disables a limit.
// Budgets bound every agent stage, and TaskWallClock the whole task run. Zero
// disables a limit.
type Budgets struct {
MaxSteps int `toml:"max_steps" json:"max_steps" yaml:"max_steps"`
WallClock Duration `toml:"wall_clock" json:"wall_clock" yaml:"wall_clock"`
GateMaxFailures int `toml:"gate_max_failures" json:"gate_max_failures" yaml:"gate_max_failures"`
TaskWallClock Duration `toml:"task_wall_clock" json:"task_wall_clock" yaml:"task_wall_clock"`
}
// Provider configures one LLM provider for the runtime catalog.
@@ -547,6 +547,238 @@ func (x *HistoryResponse) GetRevisions() []*Revision {
return nil
}
// AuditEntry is one changed field of one record. Old and new values are JSON;
// an absent side is empty.
type AuditEntry struct {
state protoimpl.MessageState `protogen:"open.v1"`
Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
Table string `protobuf:"bytes,2,opt,name=table,proto3" json:"table,omitempty"`
RecordKey string `protobuf:"bytes,3,opt,name=record_key,json=recordKey,proto3" json:"record_key,omitempty"`
Field string `protobuf:"bytes,4,opt,name=field,proto3" json:"field,omitempty"`
OldValueJson []byte `protobuf:"bytes,5,opt,name=old_value_json,json=oldValueJson,proto3" json:"old_value_json,omitempty"`
NewValueJson []byte `protobuf:"bytes,6,opt,name=new_value_json,json=newValueJson,proto3" json:"new_value_json,omitempty"`
Version int64 `protobuf:"varint,7,opt,name=version,proto3" json:"version,omitempty"`
Actor string `protobuf:"bytes,8,opt,name=actor,proto3" json:"actor,omitempty"`
Source string `protobuf:"bytes,9,opt,name=source,proto3" json:"source,omitempty"`
RequestId string `protobuf:"bytes,10,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"`
At *timestamppb.Timestamp `protobuf:"bytes,11,opt,name=at,proto3" json:"at,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *AuditEntry) Reset() {
*x = AuditEntry{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[9]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *AuditEntry) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AuditEntry) ProtoMessage() {}
func (x *AuditEntry) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[9]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AuditEntry.ProtoReflect.Descriptor instead.
func (*AuditEntry) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{9}
}
func (x *AuditEntry) GetId() int64 {
if x != nil {
return x.Id
}
return 0
}
func (x *AuditEntry) GetTable() string {
if x != nil {
return x.Table
}
return ""
}
func (x *AuditEntry) GetRecordKey() string {
if x != nil {
return x.RecordKey
}
return ""
}
func (x *AuditEntry) GetField() string {
if x != nil {
return x.Field
}
return ""
}
func (x *AuditEntry) GetOldValueJson() []byte {
if x != nil {
return x.OldValueJson
}
return nil
}
func (x *AuditEntry) GetNewValueJson() []byte {
if x != nil {
return x.NewValueJson
}
return nil
}
func (x *AuditEntry) GetVersion() int64 {
if x != nil {
return x.Version
}
return 0
}
func (x *AuditEntry) GetActor() string {
if x != nil {
return x.Actor
}
return ""
}
func (x *AuditEntry) GetSource() string {
if x != nil {
return x.Source
}
return ""
}
func (x *AuditEntry) GetRequestId() string {
if x != nil {
return x.RequestId
}
return ""
}
func (x *AuditEntry) GetAt() *timestamppb.Timestamp {
if x != nil {
return x.At
}
return nil
}
type AuditRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Table string `protobuf:"bytes,1,opt,name=table,proto3" json:"table,omitempty"`
RecordKeys []string `protobuf:"bytes,2,rep,name=record_keys,json=recordKeys,proto3" json:"record_keys,omitempty"`
// Limit caps the entries returned, newest first. Zero means the server's
// own default.
Limit int32 `protobuf:"varint,3,opt,name=limit,proto3" json:"limit,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *AuditRequest) Reset() {
*x = AuditRequest{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[10]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *AuditRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AuditRequest) ProtoMessage() {}
func (x *AuditRequest) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[10]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AuditRequest.ProtoReflect.Descriptor instead.
func (*AuditRequest) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{10}
}
func (x *AuditRequest) GetTable() string {
if x != nil {
return x.Table
}
return ""
}
func (x *AuditRequest) GetRecordKeys() []string {
if x != nil {
return x.RecordKeys
}
return nil
}
func (x *AuditRequest) GetLimit() int32 {
if x != nil {
return x.Limit
}
return 0
}
type AuditResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Entries []*AuditEntry `protobuf:"bytes,1,rep,name=entries,proto3" json:"entries,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *AuditResponse) Reset() {
*x = AuditResponse{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[11]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *AuditResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AuditResponse) ProtoMessage() {}
func (x *AuditResponse) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[11]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AuditResponse.ProtoReflect.Descriptor instead.
func (*AuditResponse) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{11}
}
func (x *AuditResponse) GetEntries() []*AuditEntry {
if x != nil {
return x.Entries
}
return nil
}
type CommandRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"`
@@ -564,7 +796,7 @@ type CommandRequest struct {
func (x *CommandRequest) Reset() {
*x = CommandRequest{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[9]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[12]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -576,7 +808,7 @@ func (x *CommandRequest) String() string {
func (*CommandRequest) ProtoMessage() {}
func (x *CommandRequest) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[9]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[12]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -589,7 +821,7 @@ func (x *CommandRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use CommandRequest.ProtoReflect.Descriptor instead.
func (*CommandRequest) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{9}
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{12}
}
func (x *CommandRequest) GetKind() string {
@@ -650,7 +882,7 @@ type CommandResponse struct {
func (x *CommandResponse) Reset() {
*x = CommandResponse{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[10]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[13]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -662,7 +894,7 @@ func (x *CommandResponse) String() string {
func (*CommandResponse) ProtoMessage() {}
func (x *CommandResponse) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[10]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[13]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -675,7 +907,7 @@ func (x *CommandResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use CommandResponse.ProtoReflect.Descriptor instead.
func (*CommandResponse) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{10}
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{13}
}
func (x *CommandResponse) GetResource() *Resource {
@@ -695,7 +927,7 @@ type WatchRequest struct {
func (x *WatchRequest) Reset() {
*x = WatchRequest{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[11]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[14]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -707,7 +939,7 @@ func (x *WatchRequest) String() string {
func (*WatchRequest) ProtoMessage() {}
func (x *WatchRequest) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[11]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[14]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -720,7 +952,7 @@ func (x *WatchRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use WatchRequest.ProtoReflect.Descriptor instead.
func (*WatchRequest) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{11}
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{14}
}
func (x *WatchRequest) GetKind() string {
@@ -747,7 +979,7 @@ type WatchResponse struct {
func (x *WatchResponse) Reset() {
*x = WatchResponse{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[12]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[15]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -759,7 +991,7 @@ func (x *WatchResponse) String() string {
func (*WatchResponse) ProtoMessage() {}
func (x *WatchResponse) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[12]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[15]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -772,7 +1004,7 @@ func (x *WatchResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use WatchResponse.ProtoReflect.Descriptor instead.
func (*WatchResponse) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{12}
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{15}
}
func (x *WatchResponse) GetResource() *Resource {
@@ -832,7 +1064,30 @@ const file_controlplane_v1_controlplane_proto_rawDesc = "" +
"\x04kind\x18\x01 \x01(\tR\x04kind\x12\x14\n" +
"\x05limit\x18\x02 \x01(\x05R\x05limit\"J\n" +
"\x0fHistoryResponse\x127\n" +
"\trevisions\x18\x01 \x03(\v2\x19.controlplane.v1.RevisionR\trevisions\"\xd5\x01\n" +
"\trevisions\x18\x01 \x03(\v2\x19.controlplane.v1.RevisionR\trevisions\"\xc6\x02\n" +
"\n" +
"AuditEntry\x12\x0e\n" +
"\x02id\x18\x01 \x01(\x03R\x02id\x12\x14\n" +
"\x05table\x18\x02 \x01(\tR\x05table\x12\x1d\n" +
"\n" +
"record_key\x18\x03 \x01(\tR\trecordKey\x12\x14\n" +
"\x05field\x18\x04 \x01(\tR\x05field\x12$\n" +
"\x0eold_value_json\x18\x05 \x01(\fR\foldValueJson\x12$\n" +
"\x0enew_value_json\x18\x06 \x01(\fR\fnewValueJson\x12\x18\n" +
"\aversion\x18\a \x01(\x03R\aversion\x12\x14\n" +
"\x05actor\x18\b \x01(\tR\x05actor\x12\x16\n" +
"\x06source\x18\t \x01(\tR\x06source\x12\x1d\n" +
"\n" +
"request_id\x18\n" +
" \x01(\tR\trequestId\x12*\n" +
"\x02at\x18\v \x01(\v2\x1a.google.protobuf.TimestampR\x02at\"[\n" +
"\fAuditRequest\x12\x14\n" +
"\x05table\x18\x01 \x01(\tR\x05table\x12\x1f\n" +
"\vrecord_keys\x18\x02 \x03(\tR\n" +
"recordKeys\x12\x14\n" +
"\x05limit\x18\x03 \x01(\x05R\x05limit\"F\n" +
"\rAuditResponse\x125\n" +
"\aentries\x18\x01 \x03(\v2\x1b.controlplane.v1.AuditEntryR\aentries\"\xd5\x01\n" +
"\x0eCommandRequest\x12\x12\n" +
"\x04kind\x18\x01 \x01(\tR\x04kind\x12\x18\n" +
"\acommand\x18\x02 \x01(\tR\acommand\x12\x1d\n" +
@@ -850,11 +1105,12 @@ const file_controlplane_v1_controlplane_proto_rawDesc = "" +
"\rafter_version\x18\x02 \x01(\x03R\fafterVersion\"\\\n" +
"\rWatchResponse\x125\n" +
"\bresource\x18\x01 \x01(\v2\x19.controlplane.v1.ResourceR\bresource\x12\x14\n" +
"\x05error\x18\x02 \x01(\tR\x05error2\x91\x03\n" +
"\x05error\x18\x02 \x01(\tR\x05error2\xd9\x03\n" +
"\x13ControlPlaneService\x12L\n" +
"\aCatalog\x12\x1f.controlplane.v1.CatalogRequest\x1a .controlplane.v1.CatalogResponse\x12F\n" +
"\x05Query\x12\x1d.controlplane.v1.QueryRequest\x1a\x1e.controlplane.v1.QueryResponse\x12L\n" +
"\aHistory\x12\x1f.controlplane.v1.HistoryRequest\x1a .controlplane.v1.HistoryResponse\x12L\n" +
"\aHistory\x12\x1f.controlplane.v1.HistoryRequest\x1a .controlplane.v1.HistoryResponse\x12F\n" +
"\x05Audit\x12\x1d.controlplane.v1.AuditRequest\x1a\x1e.controlplane.v1.AuditResponse\x12L\n" +
"\aCommand\x12\x1f.controlplane.v1.CommandRequest\x1a .controlplane.v1.CommandResponse\x12H\n" +
"\x05Watch\x12\x1d.controlplane.v1.WatchRequest\x1a\x1e.controlplane.v1.WatchResponse0\x01B\xdc\x01\n" +
"\x13com.controlplane.v1B\x11ControlplaneProtoP\x01ZUgithub.com/samcharles93/archie-core/internal/contracts/controlplane/v1;controlplanev1\xa2\x02\x03CXX\xaa\x02\x0fControlplane.V1\xca\x02\x0fControlplane\\V1\xe2\x02\x1bControlplane\\V1\\GPBMetadata\xea\x02\x10Controlplane::V1b\x06proto3"
@@ -871,7 +1127,7 @@ func file_controlplane_v1_controlplane_proto_rawDescGZIP() []byte {
return file_controlplane_v1_controlplane_proto_rawDescData
}
var file_controlplane_v1_controlplane_proto_msgTypes = make([]protoimpl.MessageInfo, 13)
var file_controlplane_v1_controlplane_proto_msgTypes = make([]protoimpl.MessageInfo, 16)
var file_controlplane_v1_controlplane_proto_goTypes = []any{
(*ResourceDescriptor)(nil), // 0: controlplane.v1.ResourceDescriptor
(*CatalogRequest)(nil), // 1: controlplane.v1.CatalogRequest
@@ -882,35 +1138,42 @@ var file_controlplane_v1_controlplane_proto_goTypes = []any{
(*Revision)(nil), // 6: controlplane.v1.Revision
(*HistoryRequest)(nil), // 7: controlplane.v1.HistoryRequest
(*HistoryResponse)(nil), // 8: controlplane.v1.HistoryResponse
(*CommandRequest)(nil), // 9: controlplane.v1.CommandRequest
(*CommandResponse)(nil), // 10: controlplane.v1.CommandResponse
(*WatchRequest)(nil), // 11: controlplane.v1.WatchRequest
(*WatchResponse)(nil), // 12: controlplane.v1.WatchResponse
(*timestamppb.Timestamp)(nil), // 13: google.protobuf.Timestamp
(*AuditEntry)(nil), // 9: controlplane.v1.AuditEntry
(*AuditRequest)(nil), // 10: controlplane.v1.AuditRequest
(*AuditResponse)(nil), // 11: controlplane.v1.AuditResponse
(*CommandRequest)(nil), // 12: controlplane.v1.CommandRequest
(*CommandResponse)(nil), // 13: controlplane.v1.CommandResponse
(*WatchRequest)(nil), // 14: controlplane.v1.WatchRequest
(*WatchResponse)(nil), // 15: controlplane.v1.WatchResponse
(*timestamppb.Timestamp)(nil), // 16: google.protobuf.Timestamp
}
var file_controlplane_v1_controlplane_proto_depIdxs = []int32{
0, // 0: controlplane.v1.CatalogResponse.resources:type_name -> controlplane.v1.ResourceDescriptor
13, // 1: controlplane.v1.Resource.updated_at:type_name -> google.protobuf.Timestamp
16, // 1: controlplane.v1.Resource.updated_at:type_name -> google.protobuf.Timestamp
3, // 2: controlplane.v1.QueryResponse.resource:type_name -> controlplane.v1.Resource
13, // 3: controlplane.v1.Revision.at:type_name -> google.protobuf.Timestamp
16, // 3: controlplane.v1.Revision.at:type_name -> google.protobuf.Timestamp
6, // 4: controlplane.v1.HistoryResponse.revisions:type_name -> controlplane.v1.Revision
3, // 5: controlplane.v1.CommandResponse.resource:type_name -> controlplane.v1.Resource
3, // 6: controlplane.v1.WatchResponse.resource:type_name -> controlplane.v1.Resource
1, // 7: controlplane.v1.ControlPlaneService.Catalog:input_type -> controlplane.v1.CatalogRequest
4, // 8: controlplane.v1.ControlPlaneService.Query:input_type -> controlplane.v1.QueryRequest
7, // 9: controlplane.v1.ControlPlaneService.History:input_type -> controlplane.v1.HistoryRequest
9, // 10: controlplane.v1.ControlPlaneService.Command:input_type -> controlplane.v1.CommandRequest
11, // 11: controlplane.v1.ControlPlaneService.Watch:input_type -> controlplane.v1.WatchRequest
2, // 12: controlplane.v1.ControlPlaneService.Catalog:output_type -> controlplane.v1.CatalogResponse
5, // 13: controlplane.v1.ControlPlaneService.Query:output_type -> controlplane.v1.QueryResponse
8, // 14: controlplane.v1.ControlPlaneService.History:output_type -> controlplane.v1.HistoryResponse
10, // 15: controlplane.v1.ControlPlaneService.Command:output_type -> controlplane.v1.CommandResponse
12, // 16: controlplane.v1.ControlPlaneService.Watch:output_type -> controlplane.v1.WatchResponse
12, // [12:17] is the sub-list for method output_type
7, // [7:12] is the sub-list for method input_type
7, // [7:7] is the sub-list for extension type_name
7, // [7:7] is the sub-list for extension extendee
0, // [0:7] is the sub-list for field type_name
16, // 5: controlplane.v1.AuditEntry.at:type_name -> google.protobuf.Timestamp
9, // 6: controlplane.v1.AuditResponse.entries:type_name -> controlplane.v1.AuditEntry
3, // 7: controlplane.v1.CommandResponse.resource:type_name -> controlplane.v1.Resource
3, // 8: controlplane.v1.WatchResponse.resource:type_name -> controlplane.v1.Resource
1, // 9: controlplane.v1.ControlPlaneService.Catalog:input_type -> controlplane.v1.CatalogRequest
4, // 10: controlplane.v1.ControlPlaneService.Query:input_type -> controlplane.v1.QueryRequest
7, // 11: controlplane.v1.ControlPlaneService.History:input_type -> controlplane.v1.HistoryRequest
10, // 12: controlplane.v1.ControlPlaneService.Audit:input_type -> controlplane.v1.AuditRequest
12, // 13: controlplane.v1.ControlPlaneService.Command:input_type -> controlplane.v1.CommandRequest
14, // 14: controlplane.v1.ControlPlaneService.Watch:input_type -> controlplane.v1.WatchRequest
2, // 15: controlplane.v1.ControlPlaneService.Catalog:output_type -> controlplane.v1.CatalogResponse
5, // 16: controlplane.v1.ControlPlaneService.Query:output_type -> controlplane.v1.QueryResponse
8, // 17: controlplane.v1.ControlPlaneService.History:output_type -> controlplane.v1.HistoryResponse
11, // 18: controlplane.v1.ControlPlaneService.Audit:output_type -> controlplane.v1.AuditResponse
13, // 19: controlplane.v1.ControlPlaneService.Command:output_type -> controlplane.v1.CommandResponse
15, // 20: controlplane.v1.ControlPlaneService.Watch:output_type -> controlplane.v1.WatchResponse
15, // [15:21] is the sub-list for method output_type
9, // [9:15] is the sub-list for method input_type
9, // [9:9] is the sub-list for extension type_name
9, // [9:9] is the sub-list for extension extendee
0, // [0:9] is the sub-list for field type_name
}
func init() { file_controlplane_v1_controlplane_proto_init() }
@@ -924,7 +1187,7 @@ func file_controlplane_v1_controlplane_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_controlplane_v1_controlplane_proto_rawDesc), len(file_controlplane_v1_controlplane_proto_rawDesc)),
NumEnums: 0,
NumMessages: 13,
NumMessages: 16,
NumExtensions: 0,
NumServices: 1,
},
@@ -22,6 +22,7 @@ const (
ControlPlaneService_Catalog_FullMethodName = "/controlplane.v1.ControlPlaneService/Catalog"
ControlPlaneService_Query_FullMethodName = "/controlplane.v1.ControlPlaneService/Query"
ControlPlaneService_History_FullMethodName = "/controlplane.v1.ControlPlaneService/History"
ControlPlaneService_Audit_FullMethodName = "/controlplane.v1.ControlPlaneService/Audit"
ControlPlaneService_Command_FullMethodName = "/controlplane.v1.ControlPlaneService/Command"
ControlPlaneService_Watch_FullMethodName = "/controlplane.v1.ControlPlaneService/Watch"
)
@@ -33,6 +34,7 @@ type ControlPlaneServiceClient interface {
Catalog(ctx context.Context, in *CatalogRequest, opts ...grpc.CallOption) (*CatalogResponse, error)
Query(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error)
History(ctx context.Context, in *HistoryRequest, opts ...grpc.CallOption) (*HistoryResponse, error)
Audit(ctx context.Context, in *AuditRequest, opts ...grpc.CallOption) (*AuditResponse, error)
Command(ctx context.Context, in *CommandRequest, opts ...grpc.CallOption) (*CommandResponse, error)
Watch(ctx context.Context, in *WatchRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[WatchResponse], error)
}
@@ -75,6 +77,16 @@ func (c *controlPlaneServiceClient) History(ctx context.Context, in *HistoryRequ
return out, nil
}
func (c *controlPlaneServiceClient) Audit(ctx context.Context, in *AuditRequest, opts ...grpc.CallOption) (*AuditResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(AuditResponse)
err := c.cc.Invoke(ctx, ControlPlaneService_Audit_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *controlPlaneServiceClient) Command(ctx context.Context, in *CommandRequest, opts ...grpc.CallOption) (*CommandResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CommandResponse)
@@ -111,6 +123,7 @@ type ControlPlaneServiceServer interface {
Catalog(context.Context, *CatalogRequest) (*CatalogResponse, error)
Query(context.Context, *QueryRequest) (*QueryResponse, error)
History(context.Context, *HistoryRequest) (*HistoryResponse, error)
Audit(context.Context, *AuditRequest) (*AuditResponse, error)
Command(context.Context, *CommandRequest) (*CommandResponse, error)
Watch(*WatchRequest, grpc.ServerStreamingServer[WatchResponse]) error
mustEmbedUnimplementedControlPlaneServiceServer()
@@ -132,6 +145,9 @@ func (UnimplementedControlPlaneServiceServer) Query(context.Context, *QueryReque
func (UnimplementedControlPlaneServiceServer) History(context.Context, *HistoryRequest) (*HistoryResponse, error) {
return nil, status.Error(codes.Unimplemented, "method History not implemented")
}
func (UnimplementedControlPlaneServiceServer) Audit(context.Context, *AuditRequest) (*AuditResponse, error) {
return nil, status.Error(codes.Unimplemented, "method Audit not implemented")
}
func (UnimplementedControlPlaneServiceServer) Command(context.Context, *CommandRequest) (*CommandResponse, error) {
return nil, status.Error(codes.Unimplemented, "method Command not implemented")
}
@@ -213,6 +229,24 @@ func _ControlPlaneService_History_Handler(srv interface{}, ctx context.Context,
return interceptor(ctx, in, info, handler)
}
func _ControlPlaneService_Audit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(AuditRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ControlPlaneServiceServer).Audit(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ControlPlaneService_Audit_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ControlPlaneServiceServer).Audit(ctx, req.(*AuditRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ControlPlaneService_Command_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CommandRequest)
if err := dec(in); err != nil {
@@ -261,6 +295,10 @@ var ControlPlaneService_ServiceDesc = grpc.ServiceDesc{
MethodName: "History",
Handler: _ControlPlaneService_History_Handler,
},
{
MethodName: "Audit",
Handler: _ControlPlaneService_Audit_Handler,
},
{
MethodName: "Command",
Handler: _ControlPlaneService_Command_Handler,
+18 -3
View File
@@ -1276,9 +1276,11 @@ func (d *Daemon) process(ctx context.Context, task *workflow.Task) {
// worktreerpc clients to that identity, and the daemon registered one
// server pair per identity (plus the root pair), so a container-mode
// task is always served by its own forge client and worktree manager.
runCtx, stopWatch := withContainerExit(ctx, ctr.Exited())
limitCtx, stopLimit := withTaskTimeLimit(ctx, d.configFor(task).Budgets.TaskWallClock.Std())
runCtx, stopWatch := withContainerExit(limitCtx, ctr.Exited())
d.runViaAgent(runCtx, task, repo, profile)
stopWatch()
stopLimit()
// Teardown storage after workflow completes. The Docker backend is a
// no-op; future backends (temp volumes, NFS leases) use this hook.
@@ -1575,8 +1577,8 @@ func (d *Daemon) runViaAgent(ctx context.Context, task *workflow.Task, repo conf
}
reply, err := d.requestTaskRun(ctx, task.ID, data)
if err != nil && errors.Is(context.Cause(ctx), errContainerExited) {
err = errContainerExited
if cause := context.Cause(ctx); err != nil && (errors.Is(cause, errContainerExited) || errors.Is(cause, errTaskTimeLimit)) {
err = cause
}
if err != nil {
d.Log.Error("taskrun request failed", "task", task.ID, "err", err)
@@ -2099,3 +2101,16 @@ func withContainerExit(ctx context.Context, exited <-chan struct{}) (context.Con
}()
return runCtx, func() { cancel(nil) }
}
// errTaskTimeLimit is the cancellation cause when a task outruns its overall
// time limit (the execution settings' max task runtime).
var errTaskTimeLimit = errors.New("task exceeded its time limit")
// withTaskTimeLimit bounds a whole task run. A limit of zero or less applies
// no bound.
func withTaskTimeLimit(ctx context.Context, limit time.Duration) (context.Context, func()) {
if limit <= 0 {
return ctx, func() {}
}
return context.WithTimeoutCause(ctx, limit, fmt.Errorf("%w (%s)", errTaskTimeLimit, limit))
}
+37
View File
@@ -2399,3 +2399,40 @@ func TestRunViaAgentParksWhenTheContainerExits(t *testing.T) {
t.Fatalf("task = %+v, %v; want parked naming the container exit", got, err)
}
}
// A task that outruns its overall time limit is parked with the limit named,
// even while its agent is still alive and silent.
func TestRunViaAgentParksWhenTheTaskTimeLimitPasses(t *testing.T) {
d, s, busClient := daemonWithNATS(t)
ctx := context.Background()
if _, err := s.EnqueueIssue(ctx, "acme", "widget", 22, "t", "b", "", ""); err != nil {
t.Fatal(err)
}
task, err := s.ClaimNext(ctx)
if err != nil || task == nil {
t.Fatalf("claim: (%v, %v)", task, err)
}
sub, err := mustCoreConn(t, busClient).Subscribe(agentnats.SubjectForTask(task.ID), func(*natsio.Msg) {})
if err != nil {
t.Fatalf("subscribe: %v", err)
}
t.Cleanup(func() { _ = sub.Unsubscribe() })
runCtx, stop := withTaskTimeLimit(ctx, 100*time.Millisecond)
defer stop()
done := make(chan struct{})
go func() {
d.runViaAgent(runCtx, task, config.Repo{Owner: "acme", Name: "widget", Base: "main"}, config.AgentProfile{})
close(done)
}()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("runViaAgent still blocked after the task time limit passed")
}
got, err := s.TaskByID(ctx, task.ID)
if err != nil || got.Status != workflow.StatusParked || !strings.Contains(got.ParkReason, "task exceeded its time limit (100ms)") {
t.Fatalf("task = %+v, %v; want parked naming the time limit", got, err)
}
}
@@ -450,6 +450,27 @@ type Resource struct {
At time.Time
}
// AuditTableResources is the sys_audit table name for control-plane resources,
// keyed by resource kind.
const AuditTableResources = "resources"
// AuditEntry is one changed field of one record, as sys_audit holds it. Any
// store table may write entries; Table and RecordKey locate the record.
// OldValue and NewValue are JSON; an absent side is empty.
type AuditEntry struct {
ID int64
Table string
RecordKey string
Field string
OldValue []byte
NewValue []byte
Version int64
Actor string
Source string
RequestID string
At time.Time
}
// ResourceWrite is a control-plane resource write request. ExpectedVersion is
// the optimistic-concurrency guard: a write whose expectation does not match
// the stored revision is refused with ErrResourceVersionConflict.
@@ -11,6 +11,7 @@ type ExecutionSettings struct {
MaxModelToolSteps int `json:"max_model_tool_steps"`
MaxRuntime time.Duration `json:"max_runtime"`
MaxConsecutiveGateFailures int `json:"max_consecutive_gate_failures"`
MaxTaskRuntime time.Duration `json:"max_task_runtime"`
}
// Validate rejects negative limits. Zero preserves the established meaning of
@@ -23,6 +24,9 @@ func (s ExecutionSettings) Validate() error {
if s.MaxRuntime < 0 {
errs = append(errs, fmt.Errorf("max runtime must not be negative"))
}
if s.MaxTaskRuntime < 0 {
errs = append(errs, fmt.Errorf("max task runtime must not be negative"))
}
if s.MaxConsecutiveGateFailures < 0 {
errs = append(errs, fmt.Errorf("max consecutive gate failures must not be negative"))
}
@@ -0,0 +1,56 @@
-- sys_audit is the field-level audit trail: one row per changed field of one
-- record, whatever the table. Settings resources are the first writer.
-- +goose Up
CREATE TABLE sys_audit (
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
at timestamptz NOT NULL,
table_name text NOT NULL,
record_key text NOT NULL,
field text NOT NULL,
old_value jsonb,
new_value jsonb,
record_version bigint NOT NULL,
actor text NOT NULL,
source text NOT NULL,
request_id text NOT NULL
);
CREATE INDEX idx_sys_audit_record ON sys_audit (table_name, record_key, id DESC);
-- audit_json_diff lists the top-level fields that differ between two JSON
-- documents. A document that is not an object is audited whole, as field ''.
-- +goose StatementBegin
CREATE FUNCTION audit_json_diff(prev jsonb, doc jsonb)
RETURNS TABLE (field text, old_value jsonb, new_value jsonb)
LANGUAGE sql IMMUTABLE AS $$
SELECT k, prev -> k, doc -> k
FROM (
SELECT jsonb_object_keys(doc) AS k WHERE jsonb_typeof(doc) = 'object'
UNION
SELECT jsonb_object_keys(prev) WHERE jsonb_typeof(prev) = 'object'
) keys
WHERE jsonb_typeof(COALESCE(doc, '{}')) = 'object'
AND jsonb_typeof(COALESCE(prev, '{}')) = 'object'
AND (prev -> k) IS DISTINCT FROM (doc -> k)
UNION ALL
SELECT '', prev, doc
WHERE NOT (jsonb_typeof(COALESCE(doc, '{}')) = 'object'
AND jsonb_typeof(COALESCE(prev, '{}')) = 'object')
AND prev IS DISTINCT FROM doc
$$;
-- +goose StatementEnd
INSERT INTO sys_audit (at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id)
SELECT h.at, 'resources', h.kind, d.field, d.old_value, d.new_value, h.version, h.actor, h.source, h.request_id
FROM (
SELECT kind, version, actor, source, request_id, at,
convert_from(value, 'UTF8')::jsonb AS doc,
lag(convert_from(value, 'UTF8')::jsonb) OVER (PARTITION BY kind ORDER BY version) AS prev
FROM resource_history
) h
CROSS JOIN LATERAL audit_json_diff(h.prev, h.doc) d
ORDER BY h.kind, h.version, d.field;
-- +goose Down
DROP TABLE sys_audit;
DROP FUNCTION audit_json_diff(jsonb, jsonb);
@@ -0,0 +1,96 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: audit.sql
package postgresdb
import (
"context"
"time"
)
const auditForRecords = `-- name: AuditForRecords :many
SELECT id, at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id
FROM sys_audit
WHERE table_name = $1::text AND record_key = ANY($2::text[])
ORDER BY id DESC
LIMIT $3::bigint
`
type AuditForRecordsParams struct {
TableName string
RecordKeys []string
EntryLimit int64
}
func (q *Queries) AuditForRecords(ctx context.Context, arg AuditForRecordsParams) ([]SysAudit, error) {
rows, err := q.db.Query(ctx, auditForRecords, arg.TableName, arg.RecordKeys, arg.EntryLimit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []SysAudit
for rows.Next() {
var i SysAudit
if err := rows.Scan(
&i.ID,
&i.At,
&i.TableName,
&i.RecordKey,
&i.Field,
&i.OldValue,
&i.NewValue,
&i.RecordVersion,
&i.Actor,
&i.Source,
&i.RequestID,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const insertResourceAudit = `-- name: InsertResourceAudit :exec
INSERT INTO sys_audit (at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id)
SELECT $1::timestamptz, 'resources', $2::text, d.field, d.old_value, d.new_value,
$3::bigint, $4::text, $5::text, $6::text
FROM audit_json_diff(
(SELECT convert_from(h.value, 'UTF8')::jsonb FROM resource_history h
WHERE h.kind = $2::text AND h.version = $7::bigint),
convert_from($8::bytea, 'UTF8')::jsonb
) d
ORDER BY d.field
`
type InsertResourceAuditParams struct {
At time.Time
Kind string
Version int64
Actor string
Source string
RequestID string
PreviousVersion int64
Value []byte
}
// Records the fields one resource write changed, against the version it
// replaced. Runs in the write's own transaction.
func (q *Queries) InsertResourceAudit(ctx context.Context, arg InsertResourceAuditParams) error {
_, err := q.db.Exec(ctx, insertResourceAudit,
arg.At,
arg.Kind,
arg.Version,
arg.Actor,
arg.Source,
arg.RequestID,
arg.PreviousVersion,
arg.Value,
)
return err
}
@@ -212,6 +212,20 @@ type Source struct {
UpdatedAt time.Time
}
type SysAudit struct {
ID int64
At time.Time
TableName string
RecordKey string
Field string
OldValue []byte
NewValue []byte
RecordVersion int64
Actor string
Source string
RequestID string
}
type Task struct {
ID int64
Owner string
@@ -0,0 +1,19 @@
-- name: InsertResourceAudit :exec
-- Records the fields one resource write changed, against the version it
-- replaced. Runs in the write's own transaction.
INSERT INTO sys_audit (at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id)
SELECT sqlc.arg(at)::timestamptz, 'resources', sqlc.arg(kind)::text, d.field, d.old_value, d.new_value,
sqlc.arg(version)::bigint, sqlc.arg(actor)::text, sqlc.arg(source)::text, sqlc.arg(request_id)::text
FROM audit_json_diff(
(SELECT convert_from(h.value, 'UTF8')::jsonb FROM resource_history h
WHERE h.kind = sqlc.arg(kind)::text AND h.version = sqlc.arg(previous_version)::bigint),
convert_from(sqlc.arg(value)::bytea, 'UTF8')::jsonb
) d
ORDER BY d.field;
-- name: AuditForRecords :many
SELECT id, at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id
FROM sys_audit
WHERE table_name = sqlc.arg(table_name)::text AND record_key = ANY(sqlc.arg(record_keys)::text[])
ORDER BY id DESC
LIMIT sqlc.arg(entry_limit)::bigint;
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"math"
"time"
"github.com/jackc/pgx/v5"
@@ -54,6 +55,29 @@ func (s *Resources) ResourceHistory(ctx context.Context, kind string, limit int)
return resources, nil
}
// Audit returns the field-level audit of the named records of one table,
// newest first. A limit of zero or less returns every entry.
func (s *Resources) Audit(ctx context.Context, table string, keys []string, limit int) ([]storecontract.AuditEntry, error) {
if limit <= 0 {
limit = math.MaxInt32
}
rows, err := postgresdb.New(s.pool).AuditForRecords(ctx, postgresdb.AuditForRecordsParams{
TableName: table, RecordKeys: keys, EntryLimit: int64(limit),
})
if err != nil {
return nil, err
}
entries := make([]storecontract.AuditEntry, 0, len(rows))
for _, row := range rows {
entries = append(entries, storecontract.AuditEntry{
ID: row.ID, Table: row.TableName, RecordKey: row.RecordKey, Field: row.Field,
OldValue: row.OldValue, NewValue: row.NewValue, Version: row.RecordVersion,
Actor: row.Actor, Source: row.Source, RequestID: row.RequestID, At: row.At,
})
}
return entries, nil
}
func (s *Resources) PutResource(ctx context.Context, write storecontract.ResourceWrite) (_ storecontract.Resource, retErr error) {
tx, err := s.pool.Begin(ctx)
if err != nil {
@@ -111,6 +135,12 @@ func (s *Resources) PutResource(ctx context.Context, write storecontract.Resourc
if err != nil {
return storecontract.Resource{}, err
}
if err := queries.InsertResourceAudit(ctx, postgresdb.InsertResourceAuditParams{
At: write.At, Kind: write.Kind, Version: resource.Version, Actor: write.Actor,
Source: write.Source, RequestID: write.RequestID, PreviousVersion: current, Value: write.Value,
}); err != nil {
return storecontract.Resource{}, err
}
if err := tx.Commit(ctx); err != nil {
return storecontract.Resource{}, err
}
@@ -2,6 +2,8 @@ package postgres
import (
"errors"
"fmt"
"strings"
"testing"
"time"
@@ -296,3 +298,37 @@ func TestConcurrentResourceWritesAcceptOnlyOneExpectedVersion(t *testing.T) {
t.Fatalf("history after race = %+v, want exactly one version 1", history)
}
}
// TestResourceWritesRecordFieldLevelAudit: each write records one sys_audit row
// per field it changed, newest first, and a replayed write records nothing.
func TestResourceWritesRecordFieldLevelAudit(t *testing.T) {
resources := resourcesFor(t)
put := func(value string, expected int64, request string) {
t.Helper()
if _, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
Kind: "settings", Value: []byte(value), Actor: "sam", Source: "archie-ui",
RequestID: request, ExpectedVersion: expected,
}); err != nil {
t.Fatalf("PutResource(%s): %v", value, err)
}
}
put(`{"a":1,"b":2}`, 0, "r1")
put(`{"a":1,"b":3,"c":4}`, 1, "r2")
put(`{"a":1,"b":3,"c":4}`, 1, "r2")
audit, err := resources.Audit(t.Context(), storecontract.AuditTableResources, []string{"settings"}, 0)
if err != nil {
t.Fatalf("ResourceAudit: %v", err)
}
got := make([]string, 0, len(audit))
for _, entry := range audit {
got = append(got, fmt.Sprintf("v%d %s %s->%s by %s", entry.Version, entry.Field, entry.OldValue, entry.NewValue, entry.Actor))
}
want := []string{
"v2 c ->4 by sam", "v2 b 2->3 by sam",
"v1 b ->2 by sam", "v1 a ->1 by sam",
}
if strings.Join(got, "; ") != strings.Join(want, "; ") {
t.Fatalf("audit =\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
}
}
+61
View File
@@ -0,0 +1,61 @@
package webui
import (
"encoding/json"
"net/http"
"time"
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
)
// auditEntryView is one changed field of one record. An absent side of the
// change is JSON null.
type auditEntryView struct {
ID int64 `json:"id"`
Table string `json:"table"`
RecordKey string `json:"record_key"`
Field string `json:"field"`
OldValue json.RawMessage `json:"old_value"`
NewValue json.RawMessage `json:"new_value"`
Version int64 `json:"version"`
Actor string `json:"actor"`
Source string `json:"source"`
At *time.Time `json:"at,omitempty"`
}
// handleAudit is GET /api/control-plane/audit?table=T&key=K1&key=K2: the
// field-level audit of the named records of one table, newest first. A page
// passes the records it shows, so its audit list is scoped to that page.
func (s *Server) handleAudit(w http.ResponseWriter, r *http.Request) {
if s.ControlPlane == nil {
http.Error(w, "control plane unavailable", http.StatusServiceUnavailable)
return
}
query := r.URL.Query()
response, err := s.ControlPlane.Audit(r.Context(), &controlpb.AuditRequest{Table: query.Get("table"), RecordKeys: query["key"]})
if err != nil {
writeControlPlaneError(w, err)
return
}
entries := make([]auditEntryView, 0, len(response.Entries))
for _, entry := range response.Entries {
view := auditEntryView{
ID: entry.Id, Table: entry.Table, RecordKey: entry.RecordKey, Field: entry.Field,
OldValue: jsonOrNull(entry.OldValueJson), NewValue: jsonOrNull(entry.NewValueJson),
Version: entry.Version, Actor: entry.Actor, Source: entry.Source,
}
if entry.At != nil {
at := entry.At.AsTime()
view.At = &at
}
entries = append(entries, view)
}
writeJSON(w, map[string]any{"entries": entries})
}
func jsonOrNull(value []byte) json.RawMessage {
if len(value) == 0 {
return json.RawMessage("null")
}
return value
}
+43
View File
@@ -23,6 +23,8 @@ type controlPlaneClientStub struct {
query *controlpb.Resource
history *controlpb.HistoryRequest
revisions []*controlpb.Revision
audit *controlpb.AuditRequest
entries []*controlpb.AuditEntry
watch grpc.ServerStreamingClient[controlpb.WatchResponse]
err error
}
@@ -40,6 +42,11 @@ func (f *controlPlaneClientStub) History(_ context.Context, request *controlpb.H
return &controlpb.HistoryResponse{Revisions: f.revisions}, f.err
}
func (f *controlPlaneClientStub) Audit(_ context.Context, request *controlpb.AuditRequest, _ ...grpc.CallOption) (*controlpb.AuditResponse, error) {
f.audit = request
return &controlpb.AuditResponse{Entries: f.entries}, f.err
}
func (f *controlPlaneClientStub) Command(_ context.Context, request *controlpb.CommandRequest, _ ...grpc.CallOption) (*controlpb.CommandResponse, error) {
f.command = request
if f.err != nil {
@@ -177,3 +184,39 @@ func TestControlPlaneHistoryWithoutAControlPlaneIsUnavailable(t *testing.T) {
t.Fatalf("status = %d, want 503", response.Code)
}
}
// TestControlPlaneAuditFiltersByTableAndRecord: the page names its table and
// records; the endpoint forwards exactly those and returns each changed field
// with its JSON values intact.
func TestControlPlaneAuditFiltersByTableAndRecord(t *testing.T) {
client := &controlPlaneClientStub{entries: []*controlpb.AuditEntry{{
Id: 9, Table: "resources", RecordKey: "workflow-execution-settings", Field: "max_model_tool_steps",
OldValueJson: []byte("90"), NewValueJson: []byte("120"), Version: 2, Actor: "system", Source: "archie-ui",
}}}
server := &Server{ControlPlane: client}
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/control-plane/audit?table=resources&key=workflow-execution-settings&key=model-settings", nil)
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
if response.Code != http.StatusOK {
t.Fatalf("status = %d, body = %q", response.Code, response.Body.String())
}
if client.audit.GetTable() != "resources" || strings.Join(client.audit.GetRecordKeys(), ",") != "workflow-execution-settings,model-settings" {
t.Fatalf("forwarded %+v", client.audit)
}
var got struct {
Entries []struct {
Field string `json:"field"`
OldValue json.RawMessage `json:"old_value"`
NewValue json.RawMessage `json:"new_value"`
Version int64 `json:"version"`
} `json:"entries"`
}
if err := json.Unmarshal(response.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
if len(got.Entries) != 1 || got.Entries[0].Field != "max_model_tool_steps" || string(got.Entries[0].OldValue) != "90" || string(got.Entries[0].NewValue) != "120" || got.Entries[0].Version != 2 {
t.Fatalf("entries = %+v", got.Entries)
}
}
+1
View File
@@ -293,6 +293,7 @@ func (s *Server) registerConfigAndLogRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/control-plane/resources/{kind}/history", s.handleControlPlaneHistory)
mux.HandleFunc("POST /api/control-plane/resources/{kind}/commands/{command}", s.handleControlPlaneCommand)
mux.HandleFunc("GET /api/control-plane/watch/{kind}", s.handleControlPlaneWatch)
mux.HandleFunc("GET /api/control-plane/audit", s.handleAudit)
mux.HandleFunc("GET /api/identities", s.handleIdentitiesList)
mux.HandleFunc("GET /api/identities/watch", s.handleIdentitiesWatch)
mux.HandleFunc("POST /api/identities", s.handleIdentityCreate)
+25
View File
@@ -8,6 +8,7 @@ service ControlPlaneService {
rpc Catalog(CatalogRequest) returns (CatalogResponse);
rpc Query(QueryRequest) returns (QueryResponse);
rpc History(HistoryRequest) returns (HistoryResponse);
rpc Audit(AuditRequest) returns (AuditResponse);
rpc Command(CommandRequest) returns (CommandResponse);
rpc Watch(WatchRequest) returns (stream WatchResponse);
}
@@ -57,6 +58,30 @@ message HistoryRequest {
}
message HistoryResponse { repeated Revision revisions = 1; }
// AuditEntry is one changed field of one record. Old and new values are JSON;
// an absent side is empty.
message AuditEntry {
int64 id = 1;
string table = 2;
string record_key = 3;
string field = 4;
bytes old_value_json = 5;
bytes new_value_json = 6;
int64 version = 7;
string actor = 8;
string source = 9;
string request_id = 10;
google.protobuf.Timestamp at = 11;
}
message AuditRequest {
string table = 1;
repeated string record_keys = 2;
// Limit caps the entries returned, newest first. Zero means the server's
// own default.
int32 limit = 3;
}
message AuditResponse { repeated AuditEntry entries = 1; }
message CommandRequest {
string kind = 1;
string command = 2;
+1 -1
View File
@@ -1 +1 @@
.identities-page[data-v-f89d6a16]{max-width:960px}.identity-create[data-v-f89d6a16]{gap:.75rem;margin:1.5rem 0;display:flex}.identity-create input[data-v-f89d6a16]{flex:1}.identity-create input[data-v-f89d6a16],.identity-create select[data-v-f89d6a16],.identity-create button[data-v-f89d6a16],.actions button[data-v-f89d6a16]{border:1px solid var(--border);background:var(--surface);color:inherit;border-radius:.5rem;padding:.6rem .8rem}.identity-list[data-v-f89d6a16]{border-top:1px solid var(--border)}.identity-row[data-v-f89d6a16]{border-bottom:1px solid var(--border);justify-content:space-between;align-items:center;gap:1rem;padding:1rem 0;display:flex}.identity-row span[data-v-f89d6a16]{color:var(--muted-foreground);text-transform:capitalize;margin-top:.2rem;font-size:.85rem;display:block}.actions[data-v-f89d6a16]{gap:.5rem;display:flex}.actions .danger[data-v-f89d6a16],.error[data-v-f89d6a16]{color:var(--destructive)}@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){:root,:host{--shimmer-angle:20deg}*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:"";--tw-scrollbar-thumb:#0000;--tw-scrollbar-track:#0000;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-animation-delay:0s;--tw-animation-direction:normal;--tw-animation-duration:initial;--tw-animation-fill-mode:none;--tw-animation-iteration-count:1;--tw-enter-blur:0;--tw-enter-opacity:1;--tw-enter-rotate:0;--tw-enter-scale:1;--tw-enter-translate-x:0;--tw-enter-translate-y:0;--tw-exit-blur:0;--tw-exit-opacity:1;--tw-exit-rotate:0;--tw-exit-scale:1;--tw-exit-translate-x:0;--tw-exit-translate-y:0;--scroll-fade-t:0;--scroll-fade-b:0;--scroll-fade-s:0;--scroll-fade-e:0;--scroll-fade-mask:initial;--shimmer-image:initial;--shimmer-text-fill:initial}}}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+460-52F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-wght-normal.woff2)format("woff2-variations");unicode-range:U+301,U+400-45F,U+490-491,U+4B0-4B1,U+2116}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-vietnamese-wght-normal.woff2)format("woff2-variations");unicode-range:U+102-103,U+110-111,U+128-129,U+168-169,U+1A0-1A1,U+1AF-1B0,U+300-301,U+303-304,U+308-309,U+323,U+329,U+1EA0-1EF9,U+20AB}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+100-2BA,U+2BD-2C5,U+2C7-2CC,U+2CE-2D7,U+2DD-2FF,U+304,U+308,U+329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-wght-normal.woff2)format("woff2-variations");unicode-range:U+??,U+131,U+152-153,U+2BB-2BC,U+2C6,U+2DA,U+2DC,U+304,U+308,U+329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@layer thLine truncated
.identities-page[data-v-f89d6a16]{max-width:960px}.identity-create[data-v-f89d6a16]{gap:.75rem;margin:1.5rem 0;display:flex}.identity-create input[data-v-f89d6a16]{flex:1}.identity-create input[data-v-f89d6a16],.identity-create select[data-v-f89d6a16],.identity-create button[data-v-f89d6a16],.actions button[data-v-f89d6a16]{border:1px solid var(--border);background:var(--surface);color:inherit;border-radius:.5rem;padding:.6rem .8rem}.identity-list[data-v-f89d6a16]{border-top:1px solid var(--border)}.identity-row[data-v-f89d6a16]{border-bottom:1px solid var(--border);justify-content:space-between;align-items:center;gap:1rem;padding:1rem 0;display:flex}.identity-row span[data-v-f89d6a16]{color:var(--muted-foreground);text-transform:capitalize;margin-top:.2rem;font-size:.85rem;display:block}.actions[data-v-f89d6a16]{gap:.5rem;display:flex}.actions .danger[data-v-f89d6a16],.error[data-v-f89d6a16]{color:var(--destructive)}@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){:root,:host{--shimmer-angle:20deg}*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:"";--tw-scrollbar-thumb:#0000;--tw-scrollbar-track:#0000;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-animation-delay:0s;--tw-animation-direction:normal;--tw-animation-duration:initial;--tw-animation-fill-mode:none;--tw-animation-iteration-count:1;--tw-enter-blur:0;--tw-enter-opacity:1;--tw-enter-rotate:0;--tw-enter-scale:1;--tw-enter-translate-x:0;--tw-enter-translate-y:0;--tw-exit-blur:0;--tw-exit-opacity:1;--tw-exit-rotate:0;--tw-exit-scale:1;--tw-exit-translate-x:0;--tw-exit-translate-y:0;--scroll-fade-t:0;--scroll-fade-b:0;--scroll-fade-s:0;--scroll-fade-e:0;--scroll-fade-mask:initial;--shimmer-image:initial;--shimmer-text-fill:initial}}}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+460-52F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-wght-normal.woff2)format("woff2-variations");unicode-range:U+301,U+400-45F,U+490-491,U+4B0-4B1,U+2116}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-vietnamese-wght-normal.woff2)format("woff2-variations");unicode-range:U+102-103,U+110-111,U+128-129,U+168-169,U+1A0-1A1,U+1AF-1B0,U+300-301,U+303-304,U+308-309,U+323,U+329,U+1EA0-1EF9,U+20AB}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+100-2BA,U+2BD-2C5,U+2C7-2CC,U+2CE-2D7,U+2DD-2FF,U+304,U+308,U+329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-wght-normal.woff2)format("woff2-variations");unicode-range:U+??,U+131,U+152-153,U+2BB-2BC,U+2C6,U+2DA,U+2DC,U+304,U+308,U+329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@layer thLine truncated
+6 -6
View File
@@ -12,9 +12,9 @@ var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],en
- less than the value passed to \`max\` (or ${Ex} if no \`max\` prop is set)
- \`null\` or \`undefined\` if the progress is indeterminate.
Defaulting to \`null\`.`),null)}function jx(e){return kx(e)&&!Number.isNaN(e)&&e>0?e:(console.error(`Invalid prop \`max\` of value \`${e}\` supplied to \`ProgressRoot\`. Only numbers greater than 0 are valid max values. Defaulting to \`${Ex}\`.`),Ex)}var Mx=j({__name:`ProgressRoot`,props:{modelValue:{type:[Number,null],required:!1},max:{type:Number,required:!1,default:Ex},getValueLabel:{type:Function,required:!1,default:(e,t)=>kx(e)?`${Math.round(e/t*Ex)}%`:void 0},getValueText:{type:Function,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},emits:[`update:modelValue`,`update:max`],setup(e,{emit:t}){let n=e,r=t;Y();let i=Th(n,`modelValue`,r,{passive:n.modelValue===void 0}),a=Th(n,`max`,r,{passive:n.max===void 0});A(()=>i.value,async e=>{let t=Ax(e,n.max);t!==e&&(await or(),i.value=t)},{immediate:!0}),A(()=>n.max,e=>{let t=jx(n.max);t!==e&&(a.value=t)},{immediate:!0});let o=U(()=>Ym(i.value)?`indeterminate`:i.value===a.value?`complete`:`loading`);return Ox({modelValue:i,max:a,progressState:o}),(e,t)=>(F(),L(O(X),{"as-child":e.asChild,as:e.as,"aria-valuemax":O(a),"aria-valuemin":0,"aria-valuenow":kx(O(i))?O(i):void 0,"aria-valuetext":e.getValueText?.(O(i),O(a)),"aria-label":e.getValueLabel(O(i),O(a)),role:`progressbar`,"data-state":o.value,"data-value":O(i)??void 0,"data-max":O(a)},{default:k(()=>[N(e.$slots,`default`,{modelValue:O(i)})]),_:3},8,[`as-child`,`as`,`aria-valuemax`,`aria-valuenow`,`aria-valuetext`,`aria-label`,`data-state`,`data-value`,`data-max`]))}}),Nx=j({__name:`ProgressIndicator`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(e){let t=e,n=Dx();return Y(),(e,r)=>(F(),L(O(X),H(t,{"data-state":O(n).progressState.value,"data-value":O(n).modelValue?.value??void 0,"data-max":O(n).max.value}),{default:k(()=>[N(e.$slots,`default`)]),_:3},16,[`data-state`,`data-value`,`data-max`]))}}),Px=[` `,`Enter`,`ArrowUp`,`ArrowDown`],Fx=[` `,`Enter`];function Ix(e,t,n){return e===void 0?!1:Array.isArray(e)?e.some(e=>Lx(e,t,n)):Lx(e,t,n)}function Lx(e,t,n){return e===void 0||t===void 0?!1:typeof e==`string`?e===t:typeof n==`function`?n(e,t):typeof n==`string`?e?.[n]===t?.[n]:Wm(e,t)}function Rx(e){return e==null||e===``||Array.isArray(e)&&e.length===0}var zx=[`value`],[Bx,Vx]=Km(`SelectRoot`),Hx=j({inheritAttrs:!1,__name:`SelectRoot`,props:{open:{type:Boolean,required:!1,default:void 0},defaultOpen:{type:Boolean,required:!1},defaultValue:{type:null,required:!1},modelValue:{type:null,required:!1,default:void 0},nullableValue:{type:String,required:!1,default:``},by:{type:[String,Function],required:!1},dir:{type:String,required:!1},multiple:{type:Boolean,required:!1},autocomplete:{type:String,required:!1},disabled:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1}},emits:[`update:modelValue`,`update:open`],setup(e,{emit:t}){let n=e,r=t,{required:i,disabled:a,multiple:o,dir:s}=Dn(n),c=Th(n,`modelValue`,r,{defaultValue:n.defaultValue??(o.value?[]:void 0),passive:n.modelValue===void 0,deep:!0}),l=Th(n,`open`,r,{defaultValue:n.defaultOpen,passive:n.open===void 0}),u=D(),d=D(),f=D({x:0,y:0}),p=U(()=>o.value&&Array.isArray(c.value)?c.value?.length===0:Ym(c.value));N_({isProvider:!0});let m=Vh(s),h=Kh(u),g=D(new Set),_=U(()=>Array.from(g.value).map(e=>e.value).join(`;`));function v(e){if(o.value){let t=Array.isArray(c.value)?[...c.value]:[],r=t.findIndex(t=>Lx(t,e,n.by));r===-1?t.push(e):t.splice(r,1),c.value=[...t]}else c.value=e}function y(e){return Array.from(g.value).find(t=>Ix(e,t.value,n.by))}return Vx({triggerElement:u,onTriggerChange:e=>{u.value=e},valueElement:d,onValueElementChange:e=>{d.value=e},contentId:``,modelValue:c,onValueChange:v,by:n.by,open:l,multiple:o,required:i,onOpenChange:e=>{l.value=e},dir:m,triggerPointerDownPosRef:f,disabled:a,isEmptyModelValue:p,optionsSet:g,onOptionAdd:e=>{let t=y(e.value);t&&g.value.delete(t),g.value.add(e)},onOptionRemove:e=>{let t=y(e.value);t&&g.value.delete(t)}}),(e,t)=>(F(),L(O(K_),null,{default:k(()=>[N(e.$slots,`default`,{modelValue:O(c),open:O(l)}),O(h)&&e.name?(F(),L(Ux,{key:_.value,"aria-hidden":`true`,tabindex:`-1`,multiple:O(o),required:O(i),name:e.name,autocomplete:e.autocomplete,disabled:O(a),value:O(c)},{default:k(()=>[O(Ym)(O(c))?(F(),I(`option`,{key:0,value:e.nullableValue},null,8,zx)):V(`v-if`,!0),(F(!0),I(P,null,M(Array.from(g.value),e=>(F(),I(`option`,H({key:e.value??``},{ref_for:!0},e),null,16))),128))]),_:1},8,[`multiple`,`required`,`name`,`autocomplete`,`disabled`,`value`])):V(`v-if`,!0)]),_:3}))}}),Ux=j({__name:`BubbleSelect`,props:{autocomplete:{type:String,required:!1},autofocus:{type:Boolean,required:!1},disabled:{type:Boolean,required:!1},form:{type:String,required:!1},multiple:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1},size:{type:Number,required:!1},value:{type:null,required:!1}},setup(e){let t=e,n=D(),r=Bx();A(()=>t.value,(e,t)=>{let r=window.HTMLSelectElement.prototype,i=Object.getOwnPropertyDescrLine truncated
`),r=[],i=null,a=null,o=()=>{r.length&&(t.push({kind:`p`,inline:pT(r.join(` `))}),r=[])},s=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>pT(e))}),null)};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.push({kind:`pre`,code:a.join(`
`)}),a=null):a=[];continue}if(a){a.push(c);continue}let l=hT(c),u=e+1<n.length?hT(n[e+1]):null;if(l&&u&&gT(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=hT(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>pT(e)),rows:r.map(e=>e.map(e=>pT(e)))});continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.push({kind:`h${d[1].length}`,inline:pT(d[2])});continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tag!==e)&&(s(),i={tag:e,items:[]}),i.items.push((f||p)[1]);continue}if(c.startsWith(`>`)){o(),s(),t.push({kind:`blockquote`,inline:pT(c.replace(/^>\s?/,``))});continue}r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
`)}),t}function hT(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 gT(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var _T={class:`[overflow-wrap:anywhere]`},vT={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},yT={class:`font-mono text-[0.85em]`},bT={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},xT={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},ST={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},CT={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},wT={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},TT={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},ET={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},DT={key:8,class:`mb-2.5 last:mb-0`},OT=j({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=U(()=>mT(t.text));return(e,t)=>(F(),I(`div`,_T,[(F(!0),I(P,null,M(n.value,(e,t)=>(F(),I(P,{key:t},[e.kind===`pre`?(F(),I(`pre`,vT,[R(`code`,yT,E(e.code),1)])):e.kind===`table`?(F(),I(`table`,bT,[R(`thead`,null,[R(`tr`,null,[(F(!0),I(P,null,M(e.head,(e,t)=>(F(),I(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[z(dT,{inline:e},null,8,[`inline`])]))),128))])]),R(`tbody`,null,[(F(!0),I(P,null,M(e.rows,(e,t)=>(F(),I(`tr`,{key:t},[(F(!0),I(P,null,M(e,(e,t)=>(F(),I(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[z(dT,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(F(),I(`blockquote`,xT,[z(dT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(F(),I(`h1`,ST,[z(dT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(F(),I(`h2`,CT,[z(dT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(F(),I(`h3`,wT,[z(dT,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(F(),I(`ul`,TT,[(F(!0),I(P,null,M(e.items,(e,t)=>(F(),I(`li`,{key:t},[z(dT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(F(),I(`ol`,ET,[(F(!0),I(P,null,M(e.items,(e,t)=>(F(),I(`li`,{key:t},[z(dT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(F(),I(`p`,DT,[z(dT,{inline:e.inline},null,8,[`inline`])])):V(``,!0)],64))),128))]))}}),kT={class:`truncate`},AT=j({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=ha(`RouterLink`);return F(),L(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:k(()=>[z(O(bd),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),R(`span`,kT,E(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),jT={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},MT={class:`font-semibold text-foreground`},NT={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},PT=j({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=U(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=U(()=>t.tool.parameters||t.tool.Parameters||``),i=U(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=U(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||(t.streaming?i.value?`failed`:`running…`:`done`));return(t,o)=>e.tool.path?(F(),L(AT,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(F(),I(`div`,jT,[z(O($d),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),R(`span`,MT,E(n.value),1),r.value?(F(),I(`code`,NT,E(r.value),1)):V(``,!0),R(`span`,{class:T(O(K)(`text-fg-muted`,i.value&&`text-danger`))},E(a.value),3)]))}}),FT={key:0,class:`mb-2 grid gap-0.5 text-xs`},IT={key:2,class:`whitespace-pre-wrap`},LT=j({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(F(),I(`div`,{class:T([`flex`,e.assistant?`justify-start`:`justify-end`])},[R(`div`,{class:T(O(K)(`max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]`,e.assistant?`bg-muted`:`bg-primary/15`))},[e.assistant&&e.tools.length?(F(),I(`div`,FT,[(F(!0),I(P,null,M(e.tools,(t,n)=>(F(),L(PT,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):V(``,!0),e.assistant?(F(),L(OT,{key:1,text:e.text},null,8,[`text`])):(F(),I(`div`,IT,E(e.text),1)),N(t.$slots,`default`)],2)],2))}}),RT={class:`w-full self-center justify-self-center py-6 text-center`},zT={class:`grid gap-2`},BT=[`onClick`],VT=j({__name:`ChatEmptyState`,emits:[`prompt`],setup(e,{emit:t}){let n=t,r=[`Summarise active tasks`,`Show running agents`,`Check system status`];return(e,t)=>(F(),I(`div`,RT,[t[0]||=R(`span`,{"aria-hidden":`true`,class:`mx-auto mb-3 grid size-9 placLine truncated
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>uA?`${n.slice(0,uA).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var fA=[`title`],pA=j({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=U(()=>Rk(n.event)),a=U(()=>dA(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=U(()=>n.event.at?kO(n.event.at):`—`);return(e,t)=>(F(),L(O(cA),{class:T(i.value>0?`cursor-pointer`:``),role:i.value>0?`link`:void 0,tabindex:i.value>0?0:void 0,title:i.value>0?`Open task details`:void 0,onClick:o,onKeydown:[fu(uu(o,[`prevent`]),[`enter`]),fu(uu(o,[`prevent`]),[`space`])]},{default:k(()=>[z(O(Q),{class:`font-medium`},{default:k(()=>[B(E(n.event.kind||n.event.type||`event`),1)]),_:1}),z(O(Q),{class:`font-mono`},{default:k(()=>[B(E(i.value>0?`#${i.value}`:`—`),1)]),_:1}),z(O(Q),{class:`w-[55%] max-w-0`},{default:k(()=>[R(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},E(a.value.text),9,fA)]),_:1}),z(O(Q),null,{default:k(()=>[B(E(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}});function mA(e,t){return`${e}:${t??0}`}function hA(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=mA(dA(n).text,r),a=t[t.length-1];if(a&&a.key===i){a.count+=1,a.events.push(n);continue}t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var gA={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},_A={class:`max-h-[28rem] overflow-y-auto`},vA=[`aria-expanded`,`aria-label`,`onClick`],yA=[`title`],bA=j({__name:`LiveActivityCard`,setup(e){let t=uE(),{activity:n,streamKind:r,streamState:i}=od(dk()),a=rn(new Set),o=U(()=>hA(n.value));function s(e){a.has(e)?a.delete(e):a.add(e)}function c(e){return a.has(e.key)}function l(e){return dA(e.representative)}function u(e){return e.representative.at?kO(e.representative.at):`—`}function d(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(F(),L(O(xO),null,{default:k(()=>[z(O(EO),null,{default:k(()=>[z(O(DO),null,{default:k(()=>[...t[0]||=[B(`Live activity`,-1)]]),_:1}),z(O(SO),null,{default:k(()=>[z(O(sO),{variant:O(r)},{default:k(()=>[B(E(O(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),z(O(CO),null,{default:k(()=>[R(`div`,gA,[R(`div`,_A,[z(O(oA),null,{default:k(()=>[z(O(lA),{class:`sticky top-0 z-10 bg-card`},{default:k(()=>[z(O(cA),null,{default:k(()=>[z(O($),null,{default:k(()=>[...t[1]||=[B(`Event`,-1)]]),_:1}),z(O($),null,{default:k(()=>[...t[2]||=[B(`Task`,-1)]]),_:1}),z(O($),null,{default:k(()=>[...t[3]||=[B(`Detail`,-1)]]),_:1}),z(O($),null,{default:k(()=>[...t[4]||=[B(`When`,-1)]]),_:1})]),_:1})]),_:1}),z(O(sA),null,{default:k(()=>[O(n).length?V(``,!0):(F(),L(O(cA),{key:0},{default:k(()=>[z(O(Q),{colspan:`4`},{default:k(()=>[z(O($D),null,{default:k(()=>[z(O(nO),null,{default:k(()=>[z(O(aO),null,{default:k(()=>[...t[5]||=[B(`Waiting for activity`,-1)]]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})),O(n).length?(F(!0),I(P,{key:1},M(o.value,e=>(F(),I(P,{key:e.key},[e.count===1?(F(),L(pA,{key:0,event:e.representative,onOpen:d},null,8,[`event`])):(F(),I(P,{key:1},[z(O(cA),{class:T(e.taskID>0?`cursor-pointer`:``),role:e.taskID>0?`link`:void 0,tabindex:e.taskID>0?0:void 0,title:e.taskID>0?`Open task details`:void 0,onClick:t=>e.taskID>0&&d(e.taskID),onKeydown:[fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`enter`]),fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`space`])]},{default:k(()=>[z(O(Q),{class:`font-medium`},{default:k(()=>[R(`button`,{type:`button`,class:`inline-flex items-center gap-1 rounded hover:opacity-80`,"aria-expanded":c(e),"aria-label":`${c(e)?`Hide`:`Show`} ${e.count} ${e.label} events`,onClick:uu(t=>s(e.key),[`stop`])},[c(e)?(F(),L(O(Sd),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`})):(F(),L(O(wd),{key:1,class:`size-3.5 shrink-0 text-fg-subtle`})),B(` `+E(e.label)+` `,1),z(O(sO),{variant:`idle`},{default:k(()=>[B(`×`+E(e.count),1)]),_:2},1024)],8,vA)]),_:2},1024),z(O(Q),{class:`font-mono`},{default:k(()=>[B(E(e.taskID>0?`#${e.taskID}`:`—`),1)]),_:2},1024),z(O(Q),{class:`w-[55%] max-w-0`},{default:k(()=>[R(`span`,{class:`block truncate`,title:l(e).truncated?l(e).full:void 0},E(l(e).text),9,yA)]),_:2},1024),z(O(Q),null,{default:k(()=>[B(E(u(e)),1)]),_:2},1024)]),_:2},1032,[`class`,`role`,`tabindex`,`title`,`onClick`,`onKeydown`]),c(e)?(F(!0),I(P,{key:0},M(e.events,(t,n)=>(F(),L(pA,{key:`${e.key}:${n}`,event:t,onOpen:d},null,8,[`event`]))),128)):V(``,!0)],64))],64))),128)):V(``,!0)]),_:1})]),_:1})])])]),_:1})]),_:1}))}}),xA=j({__name:`Progress`,props:{modelValue:{default:0},max:{},getValueLabel:{},getValueText:{},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=oC(t,`class`);return(e,r)=>(F(),L(O(Mx),H({"data-slot":`progress`},O(n),{class:O(K)(`bg-muted h-1 rounded-full relative flex w-full items-center overflow-x-hidden`,t.class)}),{default:k(()=>[z(O(Nx),{"data-slot":`progress-indicator`,class:`bg-primary size-full flex-1 transition-all`,style:ye(`transLine 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 Zj(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 Qj(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 $j(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 eM(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??``})}}function tM(e,t){return t?e.filter(e=>e.event_type_id===t):[]}function nM(e){return(e?.repository??`required`)!==`none`}function rM(e,t){return e.filter(e=>t===`any`||e.type===`any`||e.type===t)}function iM(e,t){switch(t){case`string`:return e;case`number`:return e.trim()!==``&&!Number.isNaN(Number(e))?Number(e):e;case`bool`:return e===`true`||e!==`false`&&e;default:try{return JSON.parse(e)}catch{return e}}}var aM={pending_approval:`pending approval`,armed:`armed`},oM={pending_approval:`warn`,armed:`ok`};function sM(e){return e?aM[e]??e:`unknown`}function cM(e){return oM[e??``]??`idle`}function lM(){return{id:null,name:``,eventTypeId:``,mappingId:``,filter:``,workflow:``,owner:``,repo:``,repoParam:``,inputs:{}}}function uM(e,t){let n=t.find(t=>t.id===e.mapping_id);return{id:e.id,name:e.name,eventTypeId:n?.event_type_id||``,mappingId:e.mapping_id||``,filter:e.filter||``,workflow:e.workflow||``,owner:e.owner||``,repo:e.repo||``,repoParam:e.repo_param||``,inputs:Object.fromEntries(Object.entries(e.inputs??{}).map(([e,t])=>[e,{param:t.param??``,value:t.param?``:typeof t.value==`string`?t.value:JSON.stringify(t.value)}]))}}function dM(e,t,n){let r=t.find(t=>t.id===e.eventTypeId),i=n?.inputs??{},a={};for(let[t,n]of Object.entries(i)){let r=e.inputs[t];r?.param?a[t]={param:r.param}:r&&r.value!==``&&(a[t]={value:iM(r.value,n.type)})}let o=nM(n);return{name:e.name,matcher:{source:r?.source||``},mapping_id:e.mappingId,filter:e.filter.trim(),workflow:e.workflow,owner:o&&!e.repoParam?e.owner:``,repo:o&&!e.repoParam?e.repo:``,repo_param:o?e.repoParam:``,inputs:a}}function fM(e){return e.repo_param?`from ${e.repo_param}`:e.owner&&e.repo?`${e.owner}/${e.repo}`:`—`}function pM(e,t){return t.find(t=>t.id===e.mapping_id)?.event_type_id}var mM={class:`font-mono`},hM={class:`text-fg-muted`},gM={class:`grid grid-cols-2 items-start gap-3`},_M={class:`grid grid-cols-2 items-start gap-3`},vM=`__constant__`,yM=`__none__`,bM=j({__name:`BindingEditor`,props:Va({binding:{},mappings:{},eventTypes:{},workflows:{},saving:{type:Boolean},error:{}},{open:{type:Boolean,required:!0},openModifiers:{}}),emits:Va([`save`],[`update:open`]),setup(e,{emit:t}){let n=e,r=lo(e,`open`),i=t,a=D(lM());A(r,e=>{e&&(a.value=n.binding?uM(n.binding,n.mappings):lM())},{immediate:!0});let o=U(()=>tM(n.mappings,a.value.eventTypeId));A(()=>a.value.eventTypeId,()=>{o.value.some(e=>e.id===a.value.mappingId)||(a.value.mappingId=``)});let s=U(()=>n.workflows.find(e=>e.id===a.value.workflow)),c=U(()=>Object.entries(s.value?.inputs??{}).sort(([e],[t])=>e.localeCompare(t))),l=U(()=>n.mappings.find(e=>e.id===a.value.mappingId)?.fields??[]),u=U(()=>rM(l.value,`string`));function d(e){return a.value.inputs[e]??={param:``,value:``},a.value.inputs[e]}function f(e){return d(e).param||vM}function p(e,t){d(e).param=t===vM?``:String(t)}let m=U({get:()=>a.value.repoParam||yM,set:e=>{a.value.repoParam=e===yM?``:e}}),h=U(()=>n.binding?`Edit binding`:`New binding`);return(e,t)=>(F(),L(O(Uj),{open:r.value,"onUpdate:open":t[10]||=e=>r.value=e},{default:k(()=>[z(O(Gj),{class:`max-h-[85vh] overflow-y-auto sm:max-w-lg`},{default:k(()=>[z(O(Jj),null,{default:k(()=>[z(O(Yj),null,{default:k(()=>[B(E(h.value),1)]),_:1}),z(O(Kj),null,{default:k(()=>[...t[11]||=[B(` A binding is not armed until it is approved, and editing one drops it back to pending approval. `,-1)]]),_:1})]),_:1}),R(`form`,{onSubmit:t[9]||=uu(e=>i(`save`,a.value),[`prevent`])},[z(O(BC),null,{default:k(()=>[z(O(RC),null,{default:k(()=>[z(O(HC),{for:`binding-name`},{default:k(()=>[...t[12]||=[B(`Name`,-1)]]),_:1}),z(O(VO),{id:`binding-name`,modelValue:a.value.name,"onUpdate:modelValue":t[0]||=e=>a.value.name=e},null,8,[`modelValue`])]),_:1}),z(O(RC),null,{default:k(()=>[z(O(HC),{for:`binding-event-type`},{default:k(()=>[...t[13]||=[B(`Event type`,-1)]]),_:1}),z(O(qS),{modelValue:a.value.eventTypeId,"onUpdate:modelValue":t[1]||=e=>a.value.eventTypeId=e},{default:k(()=>[z(O(DC),{id:`binding-event-type`,class:`w-full`},{default:k(()=>[z(O(OC),{placeholder:`Pick an event type`})]),_:1}),z(O(xC),null,{default:k(()=>[z(O(SC),null,{default:k(()=>[(F(!0),I(P,null,M(n Line truncated
Defaulting to \`null\`.`),null)}function jx(e){return kx(e)&&!Number.isNaN(e)&&e>0?e:(console.error(`Invalid prop \`max\` of value \`${e}\` supplied to \`ProgressRoot\`. Only numbers greater than 0 are valid max values. Defaulting to \`${Ex}\`.`),Ex)}var Mx=j({__name:`ProgressRoot`,props:{modelValue:{type:[Number,null],required:!1},max:{type:Number,required:!1,default:Ex},getValueLabel:{type:Function,required:!1,default:(e,t)=>kx(e)?`${Math.round(e/t*Ex)}%`:void 0},getValueText:{type:Function,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},emits:[`update:modelValue`,`update:max`],setup(e,{emit:t}){let n=e,r=t;Y();let i=Th(n,`modelValue`,r,{passive:n.modelValue===void 0}),a=Th(n,`max`,r,{passive:n.max===void 0});A(()=>i.value,async e=>{let t=Ax(e,n.max);t!==e&&(await or(),i.value=t)},{immediate:!0}),A(()=>n.max,e=>{let t=jx(n.max);t!==e&&(a.value=t)},{immediate:!0});let o=U(()=>Ym(i.value)?`indeterminate`:i.value===a.value?`complete`:`loading`);return Ox({modelValue:i,max:a,progressState:o}),(e,t)=>(F(),L(O(X),{"as-child":e.asChild,as:e.as,"aria-valuemax":O(a),"aria-valuemin":0,"aria-valuenow":kx(O(i))?O(i):void 0,"aria-valuetext":e.getValueText?.(O(i),O(a)),"aria-label":e.getValueLabel(O(i),O(a)),role:`progressbar`,"data-state":o.value,"data-value":O(i)??void 0,"data-max":O(a)},{default:k(()=>[N(e.$slots,`default`,{modelValue:O(i)})]),_:3},8,[`as-child`,`as`,`aria-valuemax`,`aria-valuenow`,`aria-valuetext`,`aria-label`,`data-state`,`data-value`,`data-max`]))}}),Nx=j({__name:`ProgressIndicator`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(e){let t=e,n=Dx();return Y(),(e,r)=>(F(),L(O(X),H(t,{"data-state":O(n).progressState.value,"data-value":O(n).modelValue?.value??void 0,"data-max":O(n).max.value}),{default:k(()=>[N(e.$slots,`default`)]),_:3},16,[`data-state`,`data-value`,`data-max`]))}}),Px=[` `,`Enter`,`ArrowUp`,`ArrowDown`],Fx=[` `,`Enter`];function Ix(e,t,n){return e===void 0?!1:Array.isArray(e)?e.some(e=>Lx(e,t,n)):Lx(e,t,n)}function Lx(e,t,n){return e===void 0||t===void 0?!1:typeof e==`string`?e===t:typeof n==`function`?n(e,t):typeof n==`string`?e?.[n]===t?.[n]:Wm(e,t)}function Rx(e){return e==null||e===``||Array.isArray(e)&&e.length===0}var zx=[`value`],[Bx,Vx]=Km(`SelectRoot`),Hx=j({inheritAttrs:!1,__name:`SelectRoot`,props:{open:{type:Boolean,required:!1,default:void 0},defaultOpen:{type:Boolean,required:!1},defaultValue:{type:null,required:!1},modelValue:{type:null,required:!1,default:void 0},nullableValue:{type:String,required:!1,default:``},by:{type:[String,Function],required:!1},dir:{type:String,required:!1},multiple:{type:Boolean,required:!1},autocomplete:{type:String,required:!1},disabled:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1}},emits:[`update:modelValue`,`update:open`],setup(e,{emit:t}){let n=e,r=t,{required:i,disabled:a,multiple:o,dir:s}=Dn(n),c=Th(n,`modelValue`,r,{defaultValue:n.defaultValue??(o.value?[]:void 0),passive:n.modelValue===void 0,deep:!0}),l=Th(n,`open`,r,{defaultValue:n.defaultOpen,passive:n.open===void 0}),u=D(),d=D(),f=D({x:0,y:0}),p=U(()=>o.value&&Array.isArray(c.value)?c.value?.length===0:Ym(c.value));N_({isProvider:!0});let m=Vh(s),h=Kh(u),g=D(new Set),_=U(()=>Array.from(g.value).map(e=>e.value).join(`;`));function v(e){if(o.value){let t=Array.isArray(c.value)?[...c.value]:[],r=t.findIndex(t=>Lx(t,e,n.by));r===-1?t.push(e):t.splice(r,1),c.value=[...t]}else c.value=e}function y(e){return Array.from(g.value).find(t=>Ix(e,t.value,n.by))}return Vx({triggerElement:u,onTriggerChange:e=>{u.value=e},valueElement:d,onValueElementChange:e=>{d.value=e},contentId:``,modelValue:c,onValueChange:v,by:n.by,open:l,multiple:o,required:i,onOpenChange:e=>{l.value=e},dir:m,triggerPointerDownPosRef:f,disabled:a,isEmptyModelValue:p,optionsSet:g,onOptionAdd:e=>{let t=y(e.value);t&&g.value.delete(t),g.value.add(e)},onOptionRemove:e=>{let t=y(e.value);t&&g.value.delete(t)}}),(e,t)=>(F(),L(O(K_),null,{default:k(()=>[N(e.$slots,`default`,{modelValue:O(c),open:O(l)}),O(h)&&e.name?(F(),L(Ux,{key:_.value,"aria-hidden":`true`,tabindex:`-1`,multiple:O(o),required:O(i),name:e.name,autocomplete:e.autocomplete,disabled:O(a),value:O(c)},{default:k(()=>[O(Ym)(O(c))?(F(),I(`option`,{key:0,value:e.nullableValue},null,8,zx)):V(`v-if`,!0),(F(!0),I(P,null,M(Array.from(g.value),e=>(F(),I(`option`,H({key:e.value??``},{ref_for:!0},e),null,16))),128))]),_:1},8,[`multiple`,`required`,`name`,`autocomplete`,`disabled`,`value`])):V(`v-if`,!0)]),_:3}))}}),Ux=j({__name:`BubbleSelect`,props:{autocomplete:{type:String,required:!1},autofocus:{type:Boolean,required:!1},disabled:{type:Boolean,required:!1},form:{type:String,required:!1},multiple:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1},size:{type:Number,required:!1},value:{type:null,required:!1}},setup(e){let t=e,n=D(),r=Bx();A(()=>t.value,(e,t)=>{let r=window.HTMLSelectElement.prototype,i=Object.getOwnPropertyDescrLine truncated
`),r=[],i=null,a=null,o=()=>{r.length&&(t.push({kind:`p`,inline:hT(r.join(` `))}),r=[])},s=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>hT(e))}),null)};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.push({kind:`pre`,code:a.join(`
`)}),a=null):a=[];continue}if(a){a.push(c);continue}let l=_T(c),u=e+1<n.length?_T(n[e+1]):null;if(l&&u&&vT(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=_T(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>hT(e)),rows:r.map(e=>e.map(e=>hT(e)))});continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.push({kind:`h${d[1].length}`,inline:hT(d[2])});continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tag!==e)&&(s(),i={tag:e,items:[]}),i.items.push((f||p)[1]);continue}if(c.startsWith(`>`)){o(),s(),t.push({kind:`blockquote`,inline:hT(c.replace(/^>\s?/,``))});continue}r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
`)}),t}function _T(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 vT(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var yT={class:`[overflow-wrap:anywhere]`},bT={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},xT={class:`font-mono text-[0.85em]`},ST={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},CT={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},wT={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},TT={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},ET={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},DT={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},OT={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},kT={key:8,class:`mb-2.5 last:mb-0`},AT=j({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=U(()=>gT(t.text));return(e,t)=>(F(),I(`div`,yT,[(F(!0),I(P,null,M(n.value,(e,t)=>(F(),I(P,{key:t},[e.kind===`pre`?(F(),I(`pre`,bT,[R(`code`,xT,E(e.code),1)])):e.kind===`table`?(F(),I(`table`,ST,[R(`thead`,null,[R(`tr`,null,[(F(!0),I(P,null,M(e.head,(e,t)=>(F(),I(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[z(pT,{inline:e},null,8,[`inline`])]))),128))])]),R(`tbody`,null,[(F(!0),I(P,null,M(e.rows,(e,t)=>(F(),I(`tr`,{key:t},[(F(!0),I(P,null,M(e,(e,t)=>(F(),I(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[z(pT,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(F(),I(`blockquote`,CT,[z(pT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(F(),I(`h1`,wT,[z(pT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(F(),I(`h2`,TT,[z(pT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(F(),I(`h3`,ET,[z(pT,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(F(),I(`ul`,DT,[(F(!0),I(P,null,M(e.items,(e,t)=>(F(),I(`li`,{key:t},[z(pT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(F(),I(`ol`,OT,[(F(!0),I(P,null,M(e.items,(e,t)=>(F(),I(`li`,{key:t},[z(pT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(F(),I(`p`,kT,[z(pT,{inline:e.inline},null,8,[`inline`])])):V(``,!0)],64))),128))]))}}),jT={class:`truncate`},MT=j({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=ha(`RouterLink`);return F(),L(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:k(()=>[z(O(bd),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),R(`span`,jT,E(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),NT={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},PT={class:`font-semibold text-foreground`},FT={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},IT=j({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=U(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=U(()=>t.tool.parameters||t.tool.Parameters||``),i=U(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=U(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||(t.streaming?i.value?`failed`:`running…`:`done`));return(t,o)=>e.tool.path?(F(),L(MT,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(F(),I(`div`,NT,[z(O($d),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),R(`span`,PT,E(n.value),1),r.value?(F(),I(`code`,FT,E(r.value),1)):V(``,!0),R(`span`,{class:T(O(K)(`text-fg-muted`,i.value&&`text-danger`))},E(a.value),3)]))}}),LT={key:0,class:`mb-2 grid gap-0.5 text-xs`},RT={key:2,class:`whitespace-pre-wrap`},zT=j({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(F(),I(`div`,{class:T([`flex`,e.assistant?`justify-start`:`justify-end`])},[R(`div`,{class:T(O(K)(`max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]`,e.assistant?`bg-muted`:`bg-primary/15`))},[e.assistant&&e.tools.length?(F(),I(`div`,LT,[(F(!0),I(P,null,M(e.tools,(t,n)=>(F(),L(IT,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):V(``,!0),e.assistant?(F(),L(AT,{key:1,text:e.text},null,8,[`text`])):(F(),I(`div`,RT,E(e.text),1)),N(t.$slots,`default`)],2)],2))}}),BT={class:`w-full self-center justify-self-center py-6 text-center`},VT={class:`grid gap-2`},HT=[`onClick`],UT=j({__name:`ChatEmptyState`,emits:[`prompt`],setup(e,{emit:t}){let n=t,r=[`Summarise active tasks`,`Show running agents`,`Check system status`];return(e,t)=>(F(),I(`div`,BT,[t[0]||=R(`span`,{"aria-hidden":`true`,class:`mx-auto mb-3 grid size-9 placLine truncated
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>cA?`${n.slice(0,cA).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var uA=[`title`],dA=j({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=U(()=>Vk(n.event)),a=U(()=>lA(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=U(()=>n.event.at?fO(n.event.at):`—`);return(e,t)=>(F(),L(O(cO),{class:T(i.value>0?`cursor-pointer`:``),role:i.value>0?`link`:void 0,tabindex:i.value>0?0:void 0,title:i.value>0?`Open task details`:void 0,onClick:o,onKeydown:[fu(uu(o,[`prevent`]),[`enter`]),fu(uu(o,[`prevent`]),[`space`])]},{default:k(()=>[z(O(Q),{class:`font-medium`},{default:k(()=>[B(E(n.event.kind||n.event.type||`event`),1)]),_:1}),z(O(Q),{class:`font-mono`},{default:k(()=>[B(E(i.value>0?`#${i.value}`:`—`),1)]),_:1}),z(O(Q),{class:`w-[55%] max-w-0`},{default:k(()=>[R(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},E(a.value.text),9,uA)]),_:1}),z(O(Q),null,{default:k(()=>[B(E(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}});function fA(e,t){return`${e}:${t??0}`}function pA(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=fA(lA(n).text,r),a=t[t.length-1];if(a&&a.key===i){a.count+=1,a.events.push(n);continue}t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var mA={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},hA={class:`max-h-[28rem] overflow-y-auto`},gA=[`aria-expanded`,`aria-label`,`onClick`],_A=[`title`],vA=j({__name:`LiveActivityCard`,setup(e){let t=fE(),{activity:n,streamKind:r,streamState:i}=od(mk()),a=rn(new Set),o=U(()=>pA(n.value));function s(e){a.has(e)?a.delete(e):a.add(e)}function c(e){return a.has(e.key)}function l(e){return lA(e.representative)}function u(e){return e.representative.at?fO(e.representative.at):`—`}function d(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(F(),L(O(QD),null,{default:k(()=>[z(O(rO),null,{default:k(()=>[z(O(iO),null,{default:k(()=>[...t[0]||=[B(`Live activity`,-1)]]),_:1}),z(O($D),null,{default:k(()=>[z(O(zO),{variant:O(r)},{default:k(()=>[B(E(O(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),z(O(eO),null,{default:k(()=>[R(`div`,mA,[R(`div`,hA,[z(O(oO),null,{default:k(()=>[z(O(dO),{class:`sticky top-0 z-10 bg-card`},{default:k(()=>[z(O(cO),null,{default:k(()=>[z(O($),null,{default:k(()=>[...t[1]||=[B(`Event`,-1)]]),_:1}),z(O($),null,{default:k(()=>[...t[2]||=[B(`Task`,-1)]]),_:1}),z(O($),null,{default:k(()=>[...t[3]||=[B(`Detail`,-1)]]),_:1}),z(O($),null,{default:k(()=>[...t[4]||=[B(`When`,-1)]]),_:1})]),_:1})]),_:1}),z(O(sO),null,{default:k(()=>[O(n).length?V(``,!0):(F(),L(O(cO),{key:0},{default:k(()=>[z(O(Q),{colspan:`4`},{default:k(()=>[z(O(jO),null,{default:k(()=>[z(O(PO),null,{default:k(()=>[z(O(LO),null,{default:k(()=>[...t[5]||=[B(`Waiting for activity`,-1)]]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})),O(n).length?(F(!0),I(P,{key:1},M(o.value,e=>(F(),I(P,{key:e.key},[e.count===1?(F(),L(dA,{key:0,event:e.representative,onOpen:d},null,8,[`event`])):(F(),I(P,{key:1},[z(O(cO),{class:T(e.taskID>0?`cursor-pointer`:``),role:e.taskID>0?`link`:void 0,tabindex:e.taskID>0?0:void 0,title:e.taskID>0?`Open task details`:void 0,onClick:t=>e.taskID>0&&d(e.taskID),onKeydown:[fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`enter`]),fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`space`])]},{default:k(()=>[z(O(Q),{class:`font-medium`},{default:k(()=>[R(`button`,{type:`button`,class:`inline-flex items-center gap-1 rounded hover:opacity-80`,"aria-expanded":c(e),"aria-label":`${c(e)?`Hide`:`Show`} ${e.count} ${e.label} events`,onClick:uu(t=>s(e.key),[`stop`])},[c(e)?(F(),L(O(Sd),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`})):(F(),L(O(wd),{key:1,class:`size-3.5 shrink-0 text-fg-subtle`})),B(` `+E(e.label)+` `,1),z(O(zO),{variant:`idle`},{default:k(()=>[B(`×`+E(e.count),1)]),_:2},1024)],8,gA)]),_:2},1024),z(O(Q),{class:`font-mono`},{default:k(()=>[B(E(e.taskID>0?`#${e.taskID}`:`—`),1)]),_:2},1024),z(O(Q),{class:`w-[55%] max-w-0`},{default:k(()=>[R(`span`,{class:`block truncate`,title:l(e).truncated?l(e).full:void 0},E(l(e).text),9,_A)]),_:2},1024),z(O(Q),null,{default:k(()=>[B(E(u(e)),1)]),_:2},1024)]),_:2},1032,[`class`,`role`,`tabindex`,`title`,`onClick`,`onKeydown`]),c(e)?(F(!0),I(P,{key:0},M(e.events,(t,n)=>(F(),L(dA,{key:`${e.key}:${n}`,event:t,onOpen:d},null,8,[`event`]))),128)):V(``,!0)],64))],64))),128)):V(``,!0)]),_:1})]),_:1})])])]),_:1})]),_:1}))}}),yA=j({__name:`Progress`,props:{modelValue:{default:0},max:{},getValueLabel:{},getValueText:{},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=sC(t,`class`);return(e,r)=>(F(),L(O(Mx),H({"data-slot":`progress`},O(n),{class:O(K)(`bg-muted h-1 rounded-full relative flex w-full items-center overflow-x-hidden`,t.class)}),{default:k(()=>[z(O(Nx),{"data-slot":`progress-indicator`,class:`bg-primary size-full flex-1 transition-all`,style:ye(`transLine 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 Yj(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 Xj(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 Zj(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 Qj(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??``})}}function $j(e,t){return t?e.filter(e=>e.event_type_id===t):[]}function eM(e){return(e?.repository??`required`)!==`none`}function tM(e,t){return e.filter(e=>t===`any`||e.type===`any`||e.type===t)}function nM(e,t){switch(t){case`string`:return e;case`number`:return e.trim()!==``&&!Number.isNaN(Number(e))?Number(e):e;case`bool`:return e===`true`||e!==`false`&&e;default:try{return JSON.parse(e)}catch{return e}}}var rM={pending_approval:`pending approval`,armed:`armed`},iM={pending_approval:`warn`,armed:`ok`};function aM(e){return e?rM[e]??e:`unknown`}function oM(e){return iM[e??``]??`idle`}function sM(){return{id:null,name:``,eventTypeId:``,mappingId:``,filter:``,workflow:``,owner:``,repo:``,repoParam:``,inputs:{}}}function cM(e,t){let n=t.find(t=>t.id===e.mapping_id);return{id:e.id,name:e.name,eventTypeId:n?.event_type_id||``,mappingId:e.mapping_id||``,filter:e.filter||``,workflow:e.workflow||``,owner:e.owner||``,repo:e.repo||``,repoParam:e.repo_param||``,inputs:Object.fromEntries(Object.entries(e.inputs??{}).map(([e,t])=>[e,{param:t.param??``,value:t.param?``:typeof t.value==`string`?t.value:JSON.stringify(t.value)}]))}}function lM(e,t,n){let r=t.find(t=>t.id===e.eventTypeId),i=n?.inputs??{},a={};for(let[t,n]of Object.entries(i)){let r=e.inputs[t];r?.param?a[t]={param:r.param}:r&&r.value!==``&&(a[t]={value:nM(r.value,n.type)})}let o=eM(n);return{name:e.name,matcher:{source:r?.source||``},mapping_id:e.mappingId,filter:e.filter.trim(),workflow:e.workflow,owner:o&&!e.repoParam?e.owner:``,repo:o&&!e.repoParam?e.repo:``,repo_param:o?e.repoParam:``,inputs:a}}function uM(e){return e.repo_param?`from ${e.repo_param}`:e.owner&&e.repo?`${e.owner}/${e.repo}`:`—`}function dM(e,t){return t.find(t=>t.id===e.mapping_id)?.event_type_id}var fM={class:`font-mono`},pM={class:`text-fg-muted`},mM={class:`grid grid-cols-2 items-start gap-3`},hM={class:`grid grid-cols-2 items-start gap-3`},gM=`__constant__`,_M=`__none__`,vM=j({__name:`BindingEditor`,props:Va({binding:{},mappings:{},eventTypes:{},workflows:{},saving:{type:Boolean},error:{}},{open:{type:Boolean,required:!0},openModifiers:{}}),emits:Va([`save`],[`update:open`]),setup(e,{emit:t}){let n=e,r=lo(e,`open`),i=t,a=D(sM());A(r,e=>{e&&(a.value=n.binding?cM(n.binding,n.mappings):sM())},{immediate:!0});let o=U(()=>$j(n.mappings,a.value.eventTypeId));A(()=>a.value.eventTypeId,()=>{o.value.some(e=>e.id===a.value.mappingId)||(a.value.mappingId=``)});let s=U(()=>n.workflows.find(e=>e.id===a.value.workflow)),c=U(()=>Object.entries(s.value?.inputs??{}).sort(([e],[t])=>e.localeCompare(t))),l=U(()=>n.mappings.find(e=>e.id===a.value.mappingId)?.fields??[]),u=U(()=>tM(l.value,`string`));function d(e){return a.value.inputs[e]??={param:``,value:``},a.value.inputs[e]}function f(e){return d(e).param||gM}function p(e,t){d(e).param=t===gM?``:String(t)}let m=U({get:()=>a.value.repoParam||_M,set:e=>{a.value.repoParam=e===_M?``:e}}),h=U(()=>n.binding?`Edit binding`:`New binding`);return(e,t)=>(F(),L(O(Vj),{open:r.value,"onUpdate:open":t[10]||=e=>r.value=e},{default:k(()=>[z(O(Uj),{class:`max-h-[85vh] overflow-y-auto sm:max-w-lg`},{default:k(()=>[z(O(Kj),null,{default:k(()=>[z(O(qj),null,{default:k(()=>[B(E(h.value),1)]),_:1}),z(O(Wj),null,{default:k(()=>[...t[11]||=[B(` A binding is not armed until it is approved, and editing one drops it back to pending approval. `,-1)]]),_:1})]),_:1}),R(`form`,{onSubmit:t[9]||=uu(e=>i(`save`,a.value),[`prevent`])},[z(O(HC),null,{default:k(()=>[z(O(BC),null,{default:k(()=>[z(O(WC),{for:`binding-name`},{default:k(()=>[...t[12]||=[B(`Name`,-1)]]),_:1}),z(O(WO),{id:`binding-name`,modelValue:a.value.name,"onUpdate:modelValue":t[0]||=e=>a.value.name=e},null,8,[`modelValue`])]),_:1}),z(O(BC),null,{default:k(()=>[z(O(WC),{for:`binding-event-type`},{default:k(()=>[...t[13]||=[B(`Event type`,-1)]]),_:1}),z(O(qS),{modelValue:a.value.eventTypeId,"onUpdate:modelValue":t[1]||=e=>a.value.eventTypeId=e},{default:k(()=>[z(O(kC),{id:`binding-event-type`,class:`w-full`},{default:k(()=>[z(O(AC),{placeholder:`Pick an event type`})]),_:1}),z(O(CC),null,{default:k(()=>[z(O(wC),null,{default:k(()=>[(F(!0),I(P,null,M(n Line truncated
+129
View File
@@ -0,0 +1,129 @@
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Table,
TableBody,
TableCell,
TableEmpty,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { ago } from "@/lib/format";
import {
useControlPlaneStore,
type AuditEntry,
type ResourceDescriptor,
} from "@/stores/control-plane";
/**
* The field-level audit of the settings a page shows: one row per changed
* field, newest first. Restore puts a resource back to the version before a
* change, as an ordinary replace, so the restore is audited like any edit.
*/
const props = defineProps<{ resources: ResourceDescriptor[] }>();
const store = useControlPlaneStore();
const entries = ref<AuditEntry[]>([]);
const error = ref("");
const kinds = computed(() => props.resources.map((r) => r.kind));
const titles = computed(
() => new Map(props.resources.map((r) => [r.kind, r.title])),
);
// Every stored version on the page: a save anywhere refreshes the list.
const versions = computed(() =>
kinds.value.map((kind) => store.stateFor(kind).resource?.version).join(","),
);
async function load(): Promise<void> {
if (!kinds.value.length) return;
try {
entries.value = await store.audit("resources", kinds.value);
error.value = "";
} catch (err) {
error.value = String((err as Error).message || err);
}
}
watch([kinds, versions], load, { immediate: true });
function show(value: unknown): string {
return value === null || value === undefined ? "" : JSON.stringify(value);
}
async function restoreBefore(entry: AuditEntry): Promise<void> {
const previous = (await store.history(entry.record_key)).find(
(revision) => revision.version === entry.version - 1,
);
if (previous) await store.replace(entry.record_key, previous.value);
}
</script>
<template>
<Card class="mb-4">
<CardHeader><CardTitle>Audit</CardTitle></CardHeader>
<CardContent>
<p v-if="error" class="text-sm text-destructive" role="alert">
{{ error }}
</p>
<Table v-else>
<TableHeader>
<TableRow>
<TableHead>When</TableHead>
<TableHead>Setting</TableHead>
<TableHead>Field</TableHead>
<TableHead>Old value</TableHead>
<TableHead>New value</TableHead>
<TableHead>Version</TableHead>
<TableHead>Changed by</TableHead>
<TableHead />
</TableRow>
</TableHeader>
<TableBody>
<TableRow v-for="entry in entries" :key="entry.id">
<TableCell class="whitespace-nowrap" :title="entry.at">{{
entry.at ? ago(entry.at) : ""
}}</TableCell>
<TableCell>{{
titles.get(entry.record_key) || entry.record_key
}}</TableCell>
<TableCell class="font-mono text-xs">{{
entry.field || "(whole value)"
}}</TableCell>
<TableCell
class="max-w-64 truncate font-mono text-xs text-fg-muted"
:title="show(entry.old_value)"
>{{ show(entry.old_value) }}</TableCell
>
<TableCell
class="max-w-64 truncate font-mono text-xs"
:title="show(entry.new_value)"
>{{ show(entry.new_value) }}</TableCell
>
<TableCell>{{ entry.version }}</TableCell>
<TableCell class="whitespace-nowrap"
>{{ entry.actor
}}<span class="text-fg-muted"> · {{ entry.source }}</span></TableCell
>
<TableCell>
<Button
v-if="entry.version > 1"
variant="ghost"
size="sm"
:disabled="store.stateFor(entry.record_key).saving"
@click="restoreBefore(entry)"
>Restore</Button
>
</TableCell>
</TableRow>
<TableEmpty v-if="!entries.length" :colspan="8"
>No changes recorded yet.</TableEmpty
>
</TableBody>
</Table>
</CardContent>
</Card>
</template>
+2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import AuditTable from "@/base/AuditTable.vue";
import { computed, onMounted, ref } from "vue";
import { storeToRefs } from "pinia";
@@ -68,5 +69,6 @@ onMounted(() => Promise.all([load(), controlPlane.load()]));
:key="descriptor.kind"
:descriptor="descriptor"
/>
<AuditTable :resources="settings" />
</div>
</template>
-107
View File
@@ -1,107 +0,0 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import { RotateCcw } from "@lucide/vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { ago } from "@/lib/format";
import {
useControlPlaneStore,
type ResourceRevision,
} from "@/stores/control-plane";
/**
* A resource's audit trail, and the way back to any earlier value.
*
* Restoring is not its own command: a revision carries the value it held, so
* putting it back is an ordinary replace against the version currently stored.
* That keeps the restore in the same history as every other edit rather than
* rewriting the past.
*
* The list loads when it is opened. A settings page that nobody is auditing
* should not pay for the query on every render.
*/
const props = defineProps<{ kind: string }>();
const store = useControlPlaneStore();
const state = computed(() => store.stateFor(props.kind));
const revisions = ref<ResourceRevision[]>([]);
const open = ref(false);
const loading = ref(false);
const error = ref("");
async function load(): Promise<void> {
loading.value = true;
error.value = "";
try {
revisions.value = await store.history(props.kind);
} catch (err) {
error.value = String((err as Error).message || err);
} finally {
loading.value = false;
}
}
async function toggle(): Promise<void> {
open.value = !open.value;
if (open.value) await load();
}
async function restore(revision: ResourceRevision): Promise<void> {
if (await store.replace(props.kind, revision.value)) await load();
}
</script>
<template>
<div class="mt-5 border-t border-border pt-4">
<Button variant="ghost" size="sm" :aria-expanded="open" @click="toggle">
<Spinner v-if="loading" data-icon="inline-start" />
{{ open ? "Hide history" : "History" }}
</Button>
<p v-if="error" class="mt-2 text-sm text-destructive" role="alert">
{{ error }}
</p>
<div v-else-if="open && !loading" class="mt-3">
<p v-if="!revisions.length" class="text-sm text-muted-foreground">
No changes recorded yet.
</p>
<ul v-else class="space-y-1">
<li
v-for="revision in revisions"
:key="revision.version"
class="grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-3 border-t border-border py-2 first:border-t-0"
>
<Badge
:variant="
revision.version === state.resource?.version ? 'ok' : 'idle'
"
>v{{ revision.version }}</Badge
>
<span
class="min-w-0 truncate text-sm text-fg-muted"
:title="`${revision.actor} via ${revision.source}`"
>
{{ revision.actor }}
<span class="text-fg-subtle">via {{ revision.source }}</span>
<span v-if="revision.at" class="text-fg-subtle">
· {{ ago(revision.at) }}</span
>
</span>
<Button
v-if="revision.version !== state.resource?.version"
variant="outline"
size="sm"
:disabled="state.saving"
:title="`Replace the current value with version ${revision.version}`"
@click="restore(revision)"
>
<RotateCcw /> Restore
</Button>
</li>
</ul>
</div>
</div>
</template>
@@ -10,7 +10,6 @@ import {
type ResourceDescriptor,
} from "@/stores/control-plane";
import ConfigCard from "./ConfigCard.vue";
import ResourceHistory from "./ResourceHistory.vue";
import StructuredValueEditor from "./StructuredValueEditor.vue";
import { parseSchema } from "./resource-schema";
@@ -75,6 +74,5 @@ async function save(): Promise<void> {
</Button>
</div>
</form>
<ResourceHistory :kind="descriptor.kind" />
</ConfigCard>
</template>
+2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import AuditTable from "@/base/AuditTable.vue";
import { computed, onMounted } from "vue";
import { storeToRefs } from "pinia";
@@ -32,6 +33,7 @@ onMounted(load);
:key="descriptor.kind"
:descriptor="descriptor"
/>
<AuditTable :resources="resources" />
<ConfigCard title="Managed elsewhere">
<div class="flex flex-wrap gap-2">
<Button as-child variant="outline"
+2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import AuditTable from "@/base/AuditTable.vue";
import { computed, onMounted } from "vue";
import { storeToRefs } from "pinia";
@@ -27,5 +28,6 @@ onMounted(controlPlane.load);
descriptor.kind === 'provider-settings' ? 'providers' : 'roles'
"
/>
<AuditTable :resources="resources" />
</div>
</template>
+2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import AuditTable from "@/base/AuditTable.vue";
import { computed, onMounted } from "vue";
import { storeToRefs } from "pinia";
@@ -27,5 +28,6 @@ onMounted(controlPlane.load);
:descriptor="descriptor"
root-path="repositories"
/>
<AuditTable :resources="resources" />
</div>
</template>
+2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import AuditTable from "@/base/AuditTable.vue";
import { computed, onMounted } from "vue";
import { storeToRefs } from "pinia";
@@ -25,5 +26,6 @@ onMounted(controlPlane.load);
:key="descriptor.kind"
:descriptor="descriptor"
/>
<AuditTable :resources="resources" />
</div>
</template>
+24
View File
@@ -99,6 +99,20 @@ export interface ResourceRevision {
at?: string;
}
/** One changed field of one record, as sys_audit holds it. */
export interface AuditEntry {
id: number;
table: string;
record_key: string;
field: string;
old_value: unknown;
new_value: unknown;
version: number;
actor: string;
source: string;
at?: string;
}
interface HistoryResponse {
revisions?: ResourceRevision[];
}
@@ -365,6 +379,15 @@ export const useControlPlaneStore = defineStore("control-plane", () => {
return response.revisions ?? [];
}
async function audit(table: string, keys: string[]): Promise<AuditEntry[]> {
const query = new URLSearchParams({ table });
for (const key of keys) query.append("key", key);
const response = await request<{ entries?: AuditEntry[] }>(
`/api/control-plane/audit?${query}`,
);
return response.entries ?? [];
}
/** The shipped definitions the catalog offers as "restore shipped". */
function shippedWorkflows(): WorkflowDefinitionCollection {
const defaults = catalog.value.find(
@@ -384,6 +407,7 @@ export const useControlPlaneStore = defineStore("control-plane", () => {
catalogError,
states,
genericResources,
audit,
history,
load,
loadApplyStatus,
+24 -1
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { computed } from "vue";
import { useIntervalFn } from "@vueuse/core";
import { computed, ref } from "vue";
import {
Empty,
@@ -13,6 +14,8 @@ import AttemptSelector from "./AttemptSelector.vue";
import PanelError from "./PanelError.vue";
import PanelLoading from "./PanelLoading.vue";
import StageRow from "./StageRow.vue";
import { selectConfigEvent, taskTimeLimitMs } from "./attempt-config";
import { duration } from "./timeline-event";
import { stageStatusMeta } from "./stage-rail";
import { useTaskRun } from "./use-task-run";
import type { AttemptsState, Stage } from "./task-run";
@@ -61,6 +64,23 @@ function selectStage(stage: Stage): void {
run.setTab("log");
}
const now = ref(new Date());
useIntervalFn(() => (now.value = new Date()), 30_000);
const limitMs = computed(() =>
taskTimeLimitMs(selectConfigEvent(run.events, attempt.value?.attempt ?? null)),
);
/** Time used is shown only while the attempt runs: once it ends, the stage
* durations are the record, and wall time since the start is not work. */
const timeLimit = computed(() => {
if (!limitMs.value) return "";
const limit = duration(limitMs.value);
const started = Date.parse(attempt.value?.started_at ?? "");
if (attempt.value?.status !== "running" || Number.isNaN(started)) {
return `${limit} time limit`;
}
return `${duration(Math.max(0, now.value.getTime() - started))} used of ${limit} limit`;
});
/** An attempt's start is rendered as an absolute instant, never as "started 2
* days ago": on a still-running attempt a relative stamp reads as two days of
* work, which is exactly the elapsed-time claim the design forbids. */
@@ -108,6 +128,9 @@ const startedAt = computed(() => {
</template>
<Badge :variant="meta.kind">{{ meta.label }}</Badge>
<span class="text-xs text-fg-muted">{{ startedAt }}</span>
<span v-if="timeLimit" class="text-xs text-fg-muted">{{
timeLimit
}}</span>
</div>
<ol
v-if="stages.length"
+25
View File
@@ -25,3 +25,28 @@ export function selectConfigEvent(
) || null
);
}
const GO_DURATION_UNITS: Record<string, number> = {
h: 3600_000,
m: 60_000,
s: 1000,
ms: 1,
};
/**
* The whole-task time limit the attempt ran under, in milliseconds, from its
* captured config. The daemon writes it as a Go duration ("4h0m0s"); 0 means
* no limit or none recorded.
*/
export function taskTimeLimitMs(event: unknown): number {
const document = (event as { data?: { document?: unknown } } | null)?.data
?.document as { budgets?: { task_wall_clock?: unknown } } | undefined;
const value = document?.budgets?.task_wall_clock;
if (typeof value !== "string") return 0;
const parts = [...value.matchAll(/(\d+(?:\.\d+)?)(ms|h|m|s)/g)];
if (!parts.length || parts.map((p) => p[0]).join("") !== value) return 0;
return parts.reduce(
(total, [, n, unit]) => total + Number(n) * GO_DURATION_UNITS[unit],
0,
);
}
+24
View File
@@ -0,0 +1,24 @@
import assert from "node:assert/strict";
import test from "node:test";
import { taskTimeLimitMs } from "../src/tasks/attempt-config.ts";
const captured = (limit: unknown) => ({
kind: "config_captured",
attempt: 1,
data: { document: { budgets: { task_wall_clock: limit } } },
});
test("the attempt's task time limit is read from its captured config", () => {
for (const [limit, want] of [
["4h0m0s", 4 * 3600_000],
["1h30m0s", 5400_000],
["90s", 90_000],
["0s", 0],
[undefined, 0],
["nonsense", 0],
] as const) {
assert.equal(taskTimeLimitMs(captured(limit)), want, String(limit));
}
assert.equal(taskTimeLimitMs(null), 0);
});