forked from gastownhall/gascity
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanager.go
More file actions
1420 lines (1322 loc) · 48.4 KB
/
Copy pathmanager.go
File metadata and controls
1420 lines (1322 loc) · 48.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package session manages persistent, resumable chat sessions.
//
// A chat session is a conversation between a human and an agent template
// that can be started, suspended (freeing runtime resources), and resumed
// later. Sessions are backed by beads (type "session") for persistence
// and use runtime.Provider for runtime management.
package session
import (
"context"
"crypto/rand"
"errors"
"fmt"
"log"
"strings"
"time"
"github.com/gastownhall/gascity/internal/beads"
"github.com/gastownhall/gascity/internal/runtime"
)
// State represents the runtime state of a chat session.
type State string
const (
// StateActive means the conversation has a live runtime session.
StateActive State = "active"
// StateAsleep means the session is dormant with no live runtime.
StateAsleep State = "asleep"
// StateSuspended means the conversation is paused with no runtime resources.
StateSuspended State = "suspended"
// StateCreating means the session bead has been written but the runtime
// process has not yet been confirmed alive. Counts against pool occupancy.
StateCreating State = "creating"
// StateFailedCreate means create rollback wrote terminal metadata but the
// bead status close did not complete. It is eligible for cleanup/replacement.
StateFailedCreate State = "failed-create"
// StateDraining means the session is being gracefully stopped (in-flight
// work completing). The pool routing label has been removed so no new
// work is routed to this session.
StateDraining State = "draining"
// StateDrained marks an acknowledged drain that should remain dormant
// until an explicit compatible wake reason appears.
StateDrained State = "drained"
// StateAwake is equivalent to StateActive. Written by the reconciler's
// healState when a session transitions from asleep to running.
StateAwake State = "awake"
// StateArchived means the session completed its drain and is retained
// for history. Does NOT count against pool occupancy.
StateArchived State = "archived"
// StateQuarantined means the session hit the crash-loop threshold and
// is temporarily blocked from waking. Counts against pool occupancy.
StateQuarantined State = "quarantined"
)
// BeadType is the bead type for chat sessions.
const BeadType = "session"
// LabelSession is the label applied to all session beads for filtering.
const LabelSession = "gc:session"
// Info holds the user-facing details of a chat session.
type Info struct {
ID string
Template string
State State
Closed bool
Title string
Alias string
AgentName string // persisted concrete identity for MCP materialization
Provider string
Transport string
Command string // resolved command stored at creation
WorkDir string
SessionName string // tmux session name
SessionKey string // provider-specific resume handle (UUID)
ResumeFlag string // stored provider resume flag (e.g., "--resume")
ResumeStyle string // "flag" or "subcommand"
ResumeCommand string // explicit resume command template ({{.SessionKey}})
CreatedAt time.Time
LastActive time.Time
Attached bool
}
// RuntimeObservation reports the provider-backed live runtime state for a
// persisted session.
type RuntimeObservation struct {
Running bool
Alive bool
Attached bool
LastActive time.Time
SessionName string
}
func normalizeInfoState(state State) State {
switch state {
case "awake":
return StateActive
case "drained":
return StateAsleep
}
return state
}
// ProviderResume describes a provider's session resume capabilities.
// Populated from config.ResolvedProvider's resume fields.
type ProviderResume struct {
// ResumeFlag is the CLI flag for resuming (e.g., "--resume").
// Empty means the provider doesn't support resume.
ResumeFlag string
// ResumeStyle is "flag" (--resume <key>) or "subcommand" (command resume <key>).
ResumeStyle string
// ResumeCommand is the full shell command template for resuming.
// Supports {{.SessionKey}}. When set, takes precedence over ResumeFlag/ResumeStyle.
ResumeCommand string
// SessionIDFlag is the CLI flag for creating with a specific ID (e.g., "--session-id").
// Enables Generate & Pass strategy.
SessionIDFlag string
}
// Manager orchestrates chat session lifecycle using beads for persistence
// and runtime.Provider for runtime.
type Manager struct {
store beads.Store
sp runtime.Provider
cityPath string
transportResolver func(template, provider string) transportResolution
}
// PruneResult reports which sessions were pruned and which queued wait nudges
// should be eagerly withdrawn afterward.
type PruneResult struct {
Count int
SessionIDs []string
WaitNudgeIDs []string
}
type acpRouteRegistrar interface {
RouteACP(name string)
Unroute(name string)
}
type transportDetector interface {
DetectTransport(name string) string
}
type transportResolution struct {
transport string
allowStoppedFallback bool
}
func normalizeTransport(provider, transport string) string {
if transport != "" {
return transport
}
if provider == "acp" {
return "acp"
}
return ""
}
func transportFromMetadata(b beads.Bead) string {
return normalizeTransport(b.Metadata["provider"], b.Metadata["transport"])
}
func (m *Manager) resolveConfiguredTransport(template, provider string) (string, bool) {
if m.transportResolver == nil {
return "", false
}
resolution := m.transportResolver(strings.TrimSpace(template), strings.TrimSpace(provider))
return normalizeTransport(provider, resolution.transport), resolution.allowStoppedFallback
}
func (m *Manager) transportForBead(b beads.Bead, sessName string) (string, bool) {
transport := transportFromMetadata(b)
if transport != "" {
return transport, false
}
if strings.TrimSpace(b.Metadata[MCPIdentityMetadataKey]) != "" ||
strings.TrimSpace(b.Metadata[MCPServersSnapshotMetadataKey]) != "" {
return "acp", false
}
if strings.TrimSpace(b.Metadata["pending_create_claim"]) == "true" {
transport, _ = m.resolveConfiguredTransport(b.Metadata["template"], b.Metadata["provider"])
if transport != "" {
return transport, true
}
return "", false
}
if detector, ok := m.sp.(transportDetector); ok {
transport = normalizeTransport(b.Metadata["provider"], detector.DetectTransport(sessName))
if transport != "" {
return transport, true
}
}
if m.sp != nil && m.sp.IsRunning(sessName) {
return "", false
}
return "", false
}
func (m *Manager) persistTransport(id, provider, transport string) {
transport = normalizeTransport(provider, transport)
if transport == "" {
return
}
_ = m.store.SetMetadata(id, "transport", transport)
}
func (m *Manager) routeACPIfNeeded(provider, transport, sessName string) func() {
if normalizeTransport(provider, transport) != "acp" {
return nil
}
router, ok := m.sp.(acpRouteRegistrar)
if !ok {
return nil
}
router.RouteACP(sessName)
return func() { router.Unroute(sessName) }
}
// NewManager creates a Manager backed by the given bead store and session provider.
func NewManager(store beads.Store, sp runtime.Provider) *Manager {
return &Manager{store: store, sp: sp}
}
// NewManagerWithTransportResolver creates a Manager that can infer session
// transport from template or provider config when older beads do not have
// transport metadata.
func NewManagerWithTransportResolver(store beads.Store, sp runtime.Provider, resolver func(template, provider string) string) *Manager {
return &Manager{
store: store,
sp: sp,
transportResolver: func(template, provider string) transportResolution {
if resolver == nil {
return transportResolution{}
}
return transportResolution{transport: resolver(template, provider)}
},
}
}
// NewManagerWithCityPath creates a Manager that can persist deferred submits
// into the city's nudge queue.
func NewManagerWithCityPath(store beads.Store, sp runtime.Provider, cityPath string) *Manager {
return &Manager{store: store, sp: sp, cityPath: cityPath}
}
// NewManagerWithTransportResolverAndCityPath creates a Manager that can infer
// session transport from template or provider config and persist deferred
// submits into the city's nudge queue.
func NewManagerWithTransportResolverAndCityPath(store beads.Store, sp runtime.Provider, cityPath string, resolver func(template, provider string) string) *Manager {
return &Manager{
store: store,
sp: sp,
cityPath: cityPath,
transportResolver: func(template, provider string) transportResolution {
if resolver == nil {
return transportResolution{}
}
return transportResolution{transport: resolver(template, provider)}
},
}
}
// NewManagerWithTransportPolicyResolverAndCityPath creates a Manager that can
// infer transport from config and, when the resolver marks it safe, continue
// using that transport for stopped legacy sessions without persisted
// transport metadata.
func NewManagerWithTransportPolicyResolverAndCityPath(
store beads.Store,
sp runtime.Provider,
cityPath string,
resolver func(template, provider string) (string, bool),
) *Manager {
return &Manager{
store: store,
sp: sp,
cityPath: cityPath,
transportResolver: func(template, provider string) transportResolution {
if resolver == nil {
return transportResolution{}
}
transport, allowStoppedFallback := resolver(template, provider)
return transportResolution{
transport: transport,
allowStoppedFallback: allowStoppedFallback,
}
},
}
}
// Create creates a new chat session bead and starts the runtime session.
// The command is the full provider command to execute (e.g., "claude --dangerously-skip-permissions").
// The resume parameter carries provider resume capabilities; if the provider
// supports SessionIDFlag, a UUID session key is generated and injected.
// The caller is responsible for attaching after Create returns.
func (m *Manager) Create(ctx context.Context, template, title, command, workDir, provider string, env map[string]string, resume ProviderResume, hints runtime.Config) (Info, error) {
return m.CreateAliasedNamedWithTransportAndMetadata(ctx, "", "", template, title, command, workDir, provider, "", env, resume, hints, map[string]string{
"session_origin": "manual",
})
}
// CreateWithTransport creates a new chat session bead and starts the runtime
// session, preserving the transport override separately from the provider name
// so ACP-routed sessions can be resumed correctly.
func (m *Manager) CreateWithTransport(ctx context.Context, template, title, command, workDir, provider, transport string, env map[string]string, resume ProviderResume, hints runtime.Config) (Info, error) {
return m.CreateAliasedNamedWithTransportAndMetadata(ctx, "", "", template, title, command, workDir, provider, transport, env, resume, hints, map[string]string{
"session_origin": "manual",
})
}
// CreateAliasedNamedWithTransport creates a new chat session bead with an
// optional public alias and optional explicit runtime session_name.
func (m *Manager) CreateAliasedNamedWithTransport(ctx context.Context, alias, explicitName, template, title, command, workDir, provider, transport string, env map[string]string, resume ProviderResume, hints runtime.Config) (Info, error) {
return m.createAliasedNamedWithTransport(ctx, alias, explicitName, template, title, command, workDir, provider, transport, env, resume, hints, map[string]string{
"session_origin": "manual",
})
}
// CreateAliasedNamedWithTransportAndMetadata creates a new chat session bead
// with additional metadata published atomically at bead creation time.
func (m *Manager) CreateAliasedNamedWithTransportAndMetadata(ctx context.Context, alias, explicitName, template, title, command, workDir, provider, transport string, env map[string]string, resume ProviderResume, hints runtime.Config, extraMeta map[string]string) (Info, error) {
return m.createAliasedNamedWithTransport(ctx, alias, explicitName, template, title, command, workDir, provider, transport, env, resume, hints, extraMeta)
}
func (m *Manager) createAliasedNamedWithTransport(ctx context.Context, alias, explicitName, template, title, command, workDir, provider, transport string, env map[string]string, resume ProviderResume, hints runtime.Config, extraMeta map[string]string) (Info, error) {
alias, err := ValidateAlias(alias)
if err != nil {
return Info{}, err
}
explicitName, err = ValidateExplicitName(explicitName)
if err != nil {
return Info{}, err
}
if title == "" {
title = template
}
aliasOwner := ""
if extraMeta["configured_named_session"] == "true" && extraMeta["configured_named_identity"] == alias {
aliasOwner = alias
}
var info Info
err = withSessionIdentifierReservationLocks([]string{alias, explicitName}, func() error {
if err := ensureSessionAliasAvailable(m.store, nil, alias, "", aliasOwner); err != nil {
return err
}
if err := ensureSessionNameAvailableForSelfAndOwner(m.store, explicitName, "", aliasOwner); err != nil {
return err
}
// Generate session key only when the provider supports Generate & Pass
// (has SessionIDFlag). Otherwise the key would never be passed to the
// provider and BuildResumeCommand would produce invalid resume commands.
var sessionKey string
if resume.SessionIDFlag != "" {
generatedKey, genErr := GenerateSessionKey()
if genErr != nil {
return fmt.Errorf("generating session key: %w", genErr)
}
sessionKey = generatedKey
}
// Create the bead first to get the ID.
meta := map[string]string{
"template": template,
"state": string(StateActive),
"provider": provider,
"work_dir": workDir,
"command": command,
"resume_flag": resume.ResumeFlag,
"resume_style": resume.ResumeStyle,
"resume_command": resume.ResumeCommand,
"generation": fmt.Sprintf("%d", DefaultGeneration),
"continuation_epoch": fmt.Sprintf("%d", DefaultContinuationEpoch),
"instance_token": NewInstanceToken(),
}
// provider_kind may be injected via extraMeta when the caller has
// resolved the canonical builtin kind for a custom provider alias.
if alias != "" {
meta["alias"] = alias
}
if normalizedTransport := normalizeTransport(provider, transport); normalizedTransport != "" {
meta["transport"] = normalizedTransport
}
if sessionKey != "" {
meta["session_key"] = sessionKey
}
if explicitName != "" {
meta["session_name"] = explicitName
meta["session_name_explicit"] = "true"
}
for k, v := range extraMeta {
meta[k] = v
}
if meta["session_origin"] == "" {
meta["session_origin"] = "manual"
}
createdBead, createErr := m.store.Create(beads.Bead{
Title: title,
Type: BeadType,
Labels: []string{
LabelSession,
"template:" + template,
},
Metadata: meta,
})
if createErr != nil {
return fmt.Errorf("creating session bead: %w", createErr)
}
b := createdBead
sessName := explicitName
if sessName == "" {
sessName = sessionNameFor(b.ID)
if err := m.store.SetMetadata(b.ID, "session_name", sessName); err != nil {
_ = m.store.Close(b.ID)
return fmt.Errorf("storing session name: %w", err)
}
}
if b.Metadata == nil {
b.Metadata = make(map[string]string)
}
b.Metadata["session_name"] = sessName
if explicitName != "" {
b.Metadata["session_name_explicit"] = "true"
}
if err := m.syncStoredMCPServers(b.ID, &b, hints.MCPServers); err != nil {
_ = m.store.Close(b.ID)
return err
}
unroute := m.routeACPIfNeeded(provider, transport, sessName)
rollbackFailedCreate := func() error {
if unroute != nil {
unroute()
}
if explicitName != "" {
if err := m.store.SetMetadata(b.ID, "session_name", ""); err != nil {
return fmt.Errorf("clearing session name during rollback: %w", err)
}
if err := m.store.SetMetadata(b.ID, "session_name_explicit", ""); err != nil {
return fmt.Errorf("clearing explicit session name flag during rollback: %w", err)
}
b.Metadata["session_name"] = ""
b.Metadata["session_name_explicit"] = ""
}
if err := m.store.Close(b.ID); err != nil {
return fmt.Errorf("closing rolled-back session bead: %w", err)
}
return nil
}
// If the provider supports Generate & Pass, inject --session-id into command.
startCommand := command
if resume.SessionIDFlag != "" && sessionKey != "" {
startCommand = command + " " + resume.SessionIDFlag + " " + sessionKey
}
// Build the session config from the hints, overriding command/workdir/env.
cfg := hints
cfg.Command = startCommand
cfg.WorkDir = workDir
runtimeAlias := alias
if runtimeAlias == "" {
runtimeAlias = strings.TrimSpace(extraMeta["agent_name"])
}
cfg.Env = mergeEnv(mergeEnv(cfg.Env, env), RuntimeEnvWithSessionContext(
b.ID,
sessName,
runtimeAlias,
template,
meta["session_origin"],
DefaultGeneration,
DefaultContinuationEpoch,
meta["instance_token"],
))
if gcProvider := providerKindFromMetadata(meta, provider); gcProvider != "" {
cfg.Env = mergeEnv(cfg.Env, map[string]string{"GC_PROVIDER": gcProvider})
}
cfg = runtime.SyncWorkDirEnv(cfg)
// Start the runtime session.
if err := m.sp.Start(ctx, sessName, cfg); err != nil {
if runtimeSessionMatchesBead(m.sp, sessName, b.ID, meta["instance_token"]) {
if metaErr := m.confirmStartedRuntimeMetadata(b.ID, &b); metaErr != nil {
return metaErr
}
info = m.infoFromBead(b)
return nil
}
if errors.Is(err, runtime.ErrSessionExists) && m.sp.IsRunning(sessName) {
if rbErr := rollbackFailedCreate(); rbErr != nil {
return errors.Join(fmt.Errorf("%w: %q already active in runtime", ErrSessionNameExists, sessName), rbErr)
}
return fmt.Errorf("%w: %q already active in runtime", ErrSessionNameExists, sessName)
}
if rbErr := rollbackFailedCreate(); rbErr != nil {
return errors.Join(fmt.Errorf("starting session: %w", err), rbErr)
}
return fmt.Errorf("starting session: %w", err)
}
if metaErr := m.confirmStartedRuntimeMetadata(b.ID, &b); metaErr != nil {
if stopErr := m.sp.Stop(sessName); stopErr != nil {
metaErr = errors.Join(metaErr, fmt.Errorf("stopping runtime after metadata failure: %w", stopErr))
}
if rbErr := rollbackFailedCreate(); rbErr != nil {
return errors.Join(metaErr, rbErr)
}
return metaErr
}
info = m.infoFromBead(b)
return nil
})
if err != nil {
return Info{}, err
}
return info, nil
}
func (m *Manager) confirmStartedRuntimeMetadata(id string, b *beads.Bead) error {
metadata := ConfirmStartedPatch(time.Now().UTC())
if err := m.store.SetMetadataBatch(id, metadata); err != nil {
return fmt.Errorf("storing started runtime metadata: %w", err)
}
if b != nil {
if b.Metadata == nil {
b.Metadata = make(map[string]string, len(metadata))
}
for k, v := range metadata {
b.Metadata[k] = v
}
}
return nil
}
// CreateNamedWithTransport creates a new chat session bead with an optional
// explicit session_name and starts the runtime session.
//
// WARNING: withSessionNameReservationLock only serializes callers inside this
// process. Callers MUST also hold WithCitySessionNameLock(cityPath, explicitName)
// when explicitName is non-empty so duplicate names cannot race across processes.
func (m *Manager) CreateNamedWithTransport(ctx context.Context, explicitName, template, title, command, workDir, provider, transport string, env map[string]string, resume ProviderResume, hints runtime.Config) (Info, error) {
return m.CreateAliasedNamedWithTransportAndMetadata(ctx, "", explicitName, template, title, command, workDir, provider, transport, env, resume, hints, map[string]string{
"session_origin": "manual",
})
}
func runtimeSessionMatchesBead(sp runtime.Provider, sessionName, beadID, instanceToken string) bool {
if sp == nil {
return false
}
if liveID, err := sp.GetMeta(sessionName, "GC_SESSION_ID"); err == nil {
liveID = strings.TrimSpace(liveID)
if liveID != "" {
return liveID == beadID
}
}
instanceToken = strings.TrimSpace(instanceToken)
if instanceToken == "" {
return false
}
liveToken, err := sp.GetMeta(sessionName, "GC_INSTANCE_TOKEN")
if err != nil {
return false
}
return strings.TrimSpace(liveToken) == instanceToken
}
// CreateBeadOnly creates a session bead without starting the runtime process.
// The bead is created with state "creating" — the controller's reconciler
// will detect it in buildDesiredState and start the process on its next tick.
//
// This is the Phase 2 path: CLI creates intent (bead), reconciler executes.
func (m *Manager) CreateBeadOnly(template, title, command, workDir, provider, transport string, env map[string]string, resume ProviderResume) (Info, error) {
return m.CreateBeadOnlyNamed("", template, title, command, workDir, provider, transport, env, resume)
}
// CreateAliasedBeadOnlyNamed creates a session bead without starting the
// runtime process, preserving an optional public alias and explicit runtime
// session_name for the reconciler.
func (m *Manager) CreateAliasedBeadOnlyNamed(alias, explicitName, template, title, command, workDir, provider, transport string, _ map[string]string, resume ProviderResume) (Info, error) {
return m.createAliasedBeadOnlyNamed(alias, explicitName, template, title, command, workDir, provider, transport, resume, nil)
}
// CreateAliasedBeadOnlyNamedWithMetadata creates a session bead without
// starting the runtime process, publishing extra metadata atomically.
func (m *Manager) CreateAliasedBeadOnlyNamedWithMetadata(alias, explicitName, template, title, command, workDir, provider, transport string, resume ProviderResume, extraMeta map[string]string) (Info, error) {
return m.createAliasedBeadOnlyNamed(alias, explicitName, template, title, command, workDir, provider, transport, resume, extraMeta)
}
func (m *Manager) createAliasedBeadOnlyNamed(alias, explicitName, template, title, command, workDir, provider, transport string, resume ProviderResume, extraMeta map[string]string) (Info, error) {
alias, err := ValidateAlias(alias)
if err != nil {
return Info{}, err
}
explicitName, err = ValidateExplicitName(explicitName)
if err != nil {
return Info{}, err
}
if title == "" {
title = template
}
aliasOwner := ""
if extraMeta["configured_named_session"] == "true" && extraMeta["configured_named_identity"] == alias {
aliasOwner = alias
}
var info Info
err = withSessionIdentifierReservationLocks([]string{alias, explicitName}, func() error {
if err := ensureSessionAliasAvailable(m.store, nil, alias, "", aliasOwner); err != nil {
return err
}
if err := ensureSessionNameAvailableForSelfAndOwner(m.store, explicitName, "", aliasOwner); err != nil {
return err
}
var sessionKey string
if resume.SessionIDFlag != "" {
generatedKey, genErr := GenerateSessionKey()
if genErr != nil {
return fmt.Errorf("generating session key: %w", genErr)
}
sessionKey = generatedKey
}
meta := map[string]string{
"template": template,
"state": "creating",
"provider": provider,
"work_dir": workDir,
"command": command,
"resume_flag": resume.ResumeFlag,
"resume_style": resume.ResumeStyle,
"resume_command": resume.ResumeCommand,
"generation": fmt.Sprintf("%d", DefaultGeneration),
"continuation_epoch": fmt.Sprintf("%d", DefaultContinuationEpoch),
"instance_token": NewInstanceToken(),
}
if alias != "" {
meta["alias"] = alias
}
if normalizedTransport := normalizeTransport(provider, transport); normalizedTransport != "" {
meta["transport"] = normalizedTransport
}
if sessionKey != "" {
meta["session_key"] = sessionKey
}
meta["pending_create_claim"] = "true"
meta["pending_create_started_at"] = pendingCreateStartedAt(time.Now().UTC())
if explicitName != "" {
meta["session_name"] = explicitName
meta["session_name_explicit"] = "true"
}
for k, v := range extraMeta {
meta[k] = v
}
if meta["session_origin"] == "" {
meta["session_origin"] = "ephemeral"
}
createdBead, createErr := m.store.Create(beads.Bead{
Title: title,
Type: BeadType,
Labels: []string{
LabelSession,
"template:" + template,
},
Metadata: meta,
})
if createErr != nil {
return fmt.Errorf("creating session bead: %w", createErr)
}
b := createdBead
sessName := explicitName
if sessName == "" {
sessName = sessionNameFor(b.ID)
if err := m.store.SetMetadata(b.ID, "session_name", sessName); err != nil {
_ = m.store.Close(b.ID)
return fmt.Errorf("storing session name: %w", err)
}
}
if b.Metadata == nil {
b.Metadata = make(map[string]string)
}
b.Metadata["session_name"] = sessName
info = m.infoFromBead(b)
return nil
})
if err != nil {
return Info{}, err
}
return info, nil
}
// CreateBeadOnlyNamed creates a session bead without starting the runtime
// process, preserving an optional explicit session_name for the reconciler.
//
// WARNING: withSessionNameReservationLock only serializes callers inside this
// process. Callers MUST also hold WithCitySessionNameLock(cityPath, explicitName)
// when explicitName is non-empty so duplicate names cannot race across processes.
func (m *Manager) CreateBeadOnlyNamed(explicitName, template, title, command, workDir, provider, transport string, _ map[string]string, resume ProviderResume) (Info, error) {
return m.CreateAliasedBeadOnlyNamed("", explicitName, template, title, command, workDir, provider, transport, nil, resume)
}
// Attach attaches the user's terminal to the session. If the session is
// suspended, it is resumed first using resumeCommand. If the tmux session
// died (active bead but no process), it is restarted.
func (m *Manager) Attach(ctx context.Context, id string, resumeCommand string, hints runtime.Config) error {
return withSessionMutationLock(id, func() error {
b, sessName, err := m.sessionBead(id)
if err != nil {
return err
}
if err := m.ensureRunning(ctx, id, b, sessName, resumeCommand, hints); err != nil {
return err
}
return m.sp.Attach(sessName)
})
}
// Suspend saves session state and kills the runtime session.
func (m *Manager) Suspend(id string) error {
return withSessionMutationLock(id, func() error {
b, sessName, err := m.sessionBead(id)
if err != nil {
return err
}
// Closed beads are terminal; mutating lifecycle metadata after
// close produces impossible status=closed + live-state rows.
if b.Status == "closed" {
return &IllegalTransitionError{From: StateClosed, Command: CmdSuspend}
}
current := State(b.Metadata["state"])
if current == StateSuspended {
return nil // idempotent: already suspended
}
// Legacy bead normalization: pre-metadata cities may have empty
// state fields. Treat empty as StateActive so the state-machine
// transition works during upgrade. Matches what Close and
// checkTransition already do for the other lifecycle methods.
if current == StateNone {
current = StateActive
}
// StateAwake is the reconciler's alias for StateActive.
if current == StateAwake {
current = StateActive
}
if _, err := Transition(current, CmdSuspend); err != nil {
return err
}
// Kill the runtime session. Stop is provider-idempotent, so call it
// even when liveness already reports false; tmux remain-on-exit panes
// can be non-running but still need their session artifact removed.
if strings.TrimSpace(sessName) != "" {
running := m.sp.IsRunning(sessName)
err := m.sp.Stop(sessName)
if err != nil && !running {
// Preserve historical Suspend semantics for already-dead
// sessions: cleanup is best-effort when the runtime did not
// report a live process before Stop.
err = nil
}
if err != nil {
return fmt.Errorf("stopping runtime session: %w", err)
}
}
// Update state and suspension timestamp together so stores with a
// write-through cache preserve one coherent lifecycle transition.
if err := m.store.Update(id, beads.UpdateOpts{Metadata: map[string]string{
"state": string(StateSuspended),
"suspended_at": time.Now().UTC().Format(time.RFC3339),
}}); err != nil {
return fmt.Errorf("updating suspension state: %w", err)
}
return nil
})
}
// RequestFreshRestart marks a session for a controller-owned fresh restart
// without closing its bead or clearing resume metadata immediately.
func (m *Manager) RequestFreshRestart(id string) error {
return withSessionMutationLock(id, func() error {
if _, _, err := m.sessionBead(id); err != nil {
return err
}
return m.store.SetMetadataBatch(id, map[string]string{
"restart_requested": "true",
"continuation_reset_pending": "true",
})
})
}
// Close ends a conversation permanently.
func (m *Manager) Close(id string) error {
return withSessionMutationLock(id, func() error {
b, sessName, err := m.loadSessionBead(id, true)
if err != nil {
return err
}
if b.Status == "closed" {
_ = clearRuntimeMCPServersSnapshot(m.cityPath, id)
return nil // idempotent: already closed
}
// CmdClose is legal from any non-none state; this is effectively a
// documentation check that will catch future table changes. Treat
// empty metadata state as StateActive for bootstrap beads, and
// treat the reconciler's StateAwake alias as StateActive so
// already-awake beads can close cleanly.
current := State(b.Metadata["state"])
if current == StateNone {
current = StateActive
}
if current == StateAwake {
current = StateActive
}
if _, err := Transition(current, CmdClose); err != nil {
return err
}
// Best-effort stop cleans up any live runtime and allows auto.Provider
// to discard stale ACP route entries for suspended sessions as well.
_ = m.sp.Stop(sessName)
_ = CancelWaits(m.store, id, time.Now().UTC())
if err := m.clearWakeAndHoldOverrides(id); err != nil {
return err
}
if err := m.retireConfiguredNamedSessionIdentifiers(id, b); err != nil {
return err
}
if err := m.store.Close(id); err != nil {
return err
}
_ = clearRuntimeMCPServersSnapshot(m.cityPath, id)
return nil
})
}
func (m *Manager) clearWakeAndHoldOverrides(id string) error {
update := map[string]string{
"pin_awake": "",
"held_until": "",
"sleep_intent": "",
}
if err := m.store.SetMetadataBatch(id, update); err != nil {
return fmt.Errorf("clearing wake and hold overrides: %w", err)
}
return nil
}
func (m *Manager) retireConfiguredNamedSessionIdentifiers(id string, b beads.Bead) error {
if strings.TrimSpace(b.Metadata["configured_named_session"]) != "true" {
return nil
}
update := beads.UpdateOpts{
Metadata: UpdatedAliasMetadata(b.Metadata, ""),
}
update.Metadata["session_name"] = ""
update.Metadata["session_name_explicit"] = ""
update.Metadata["pending_create_claim"] = ""
update.Metadata["pending_create_started_at"] = ""
if err := m.store.Update(id, update); err != nil {
return fmt.Errorf("retiring configured named session identifiers: %w", err)
}
return nil
}
// Kill force-kills the runtime process for a session without changing bead
// state. This is intended for manual intervention; the reconciler will detect
// the dead process and restart it according to the session's lifecycle rules.
func (m *Manager) Kill(id string) error {
b, sessName, err := m.sessionBead(id)
if err != nil {
return err
}
// Accept any state where a runtime process could plausibly exist.
// The reconciler uses "awake" as equivalent to "active", and metadata
// state can lag behind reality, so also check provider liveness.
state := State(b.Metadata["state"])
switch state {
case StateActive, StateCreating, StateDraining, StateAwake:
// Known live states — proceed.
default:
if !m.sp.IsRunning(sessName) {
return fmt.Errorf("session %s is not active", id)
}
}
return m.sp.Stop(sessName)
}
// BeginDrain transitions a session to the draining state. The caller is
// responsible for signaling the runtime process to finish its work.
// Idempotent: returns nil if the session is already draining.
func (m *Manager) BeginDrain(id, reason string) error {
return withSessionMutationLock(id, func() error {
cmdLegal, err := m.checkTransition(id, CmdDrain, StateDraining)
if err != nil {
return err
}
if !cmdLegal {
return nil // idempotent: already draining
}
return m.store.SetMetadataBatch(id, BeginDrainPatch(time.Now().UTC(), reason))
})
}
// Archive transitions a session from draining to archived. Idempotent:
// returns nil if the session is already archived.
func (m *Manager) Archive(id, reason string) error {
return withSessionMutationLock(id, func() error {
cmdLegal, err := m.checkTransition(id, CmdArchive, StateArchived)
if err != nil {
return err
}
if !cmdLegal {
return nil // idempotent: already archived
}
return m.store.SetMetadataBatch(id, ArchivePatch(time.Now().UTC(), reason, false))
})
}
// Quarantine marks a session as crash-quarantined until the given time.
// Idempotent: returns nil if the session is already quarantined.
func (m *Manager) Quarantine(id string, until time.Time, cycle int) error {
return withSessionMutationLock(id, func() error {
cmdLegal, err := m.checkTransition(id, CmdQuarantine, StateQuarantined)
if err != nil {
return err
}
if !cmdLegal {
return nil // idempotent: already quarantined
}
return m.store.SetMetadataBatch(id, QuarantinePatch(until, cycle))
})
}
// Reactivate clears archive/quarantine blockers and returns a session to
// asleep so normal wake machinery owns the next runtime start. Idempotent:
// returns nil if the session is already in an awake-eligible state.
func (m *Manager) Reactivate(id string) error {
return withSessionMutationLock(id, func() error {
cmdLegal, err := m.checkTransition(id, CmdWake, StateAsleep)
if err != nil {
return err
}
if !cmdLegal {
return nil // idempotent: already in target state
}
b, err := m.store.Get(id)
if err != nil {
return err
}
view := ProjectLifecycle(LifecycleInput{
Status: b.Status,
Metadata: b.Metadata,
})
// Note: quarantine_cycle is intentionally preserved across reactivations.
// It tracks how many quarantine rounds the session has been through,
// enabling eviction after quarantine_max_attempts.
return m.store.SetMetadataBatch(id, ReactivatePatch(view.ContinuityEligible))
})
}
// ConfirmCreation transitions a session from creating to active after the
// runtime process has been confirmed alive. Idempotent: returns nil if the
// session is already active.
func (m *Manager) ConfirmCreation(id string) error {
return withSessionMutationLock(id, func() error {
cmdLegal, err := m.checkTransition(id, CmdReady, StateActive)
if err != nil {
return err
}
if !cmdLegal {
return nil // idempotent: already active
}
return m.store.SetMetadataBatch(id, ConfirmStartedPatch(time.Now()))
})
}
// checkTransition reads the current state of session id and reports whether
// cmd is legal. Empty state metadata is treated as StateActive for legacy
// bootstrap beads (pre-metadata upgrades). Closed beads are terminal and
// reject any lifecycle mutation (callers should use the dedicated Close
// idempotency branch, not a lifecycle transition). Returns:
// - cmdLegal: true if the command produces a real transition, false if
// the session is already in targetState (idempotent no-op)
// - err: *IllegalTransitionError wrapping ErrIllegalTransition when the
// command is neither legal nor a no-op
//
// MUST be called while holding withSessionMutationLock(id).
func (m *Manager) checkTransition(id string, cmd TransitionCommand, targetState State) (bool, error) {
b, _, err := m.sessionBead(id)
if err != nil {
return false, err