diff --git a/apps/albedo/src/albedo/http/api_digest.gleam b/apps/albedo/src/albedo/http/api_digest.gleam index 903d6e5cb..5de492634 100644 --- a/apps/albedo/src/albedo/http/api_digest.gleam +++ b/apps/albedo/src/albedo/http/api_digest.gleam @@ -2,4 +2,4 @@ //// GET /server reports it so a client built from another contract can tell. pub const digest = - "e46b36cd054c1748a4baa784ed7069a5d90bfb885707aa9c792100f685b1f50c" + "f232497ce0f3d13a04d4e730e54122cd2c141cb5f26131e164e60407174adae4" diff --git a/apps/albedo/src/albedo/http/http_sessions.gleam b/apps/albedo/src/albedo/http/http_sessions.gleam index 9c1481635..76b8e6e50 100644 --- a/apps/albedo/src/albedo/http/http_sessions.gleam +++ b/apps/albedo/src/albedo/http/http_sessions.gleam @@ -2171,8 +2171,7 @@ pub fn compaction( use host <- result.try( registry.host(registry) |> result.map_error(refusal.failure), ) - // Opening the owner reconciles orphaned receipts before a recovery read. - let worker = registry.lookup(registry, id) + use _ <- result.try(http_acp.guard_compaction(registry, id, req)) case req.method { http.Get -> { use receipt <- result.try( @@ -2184,12 +2183,17 @@ pub fn compaction( if receipt.operation.kind == operations.Recorded("compaction") && receipt.operation.target == id -> Ok(sdk_http_api.raw(200, receipt.response)) - _ -> + _ -> { + use _ <- result.try( + operations.validate_id(action_id, usage.now()) + |> result.map_error(refusal.failure), + ) Error(sdk_http_api.Failure( 404, "compaction_unknown", "compaction receipt not found", )) + } } } _ -> { @@ -2212,9 +2216,8 @@ pub fn compaction( use receipt <- result.try(case previous { Some(receipt) -> Ok(receipt) None -> { - use _ <- result.try(http_acp.guard_compaction(registry, id, req)) use worker <- result.try( - worker |> result.map_error(refusal.failure), + registry.lookup(registry, id) |> result.map_error(refusal.failure), ) session.admit_compaction(worker, action_id, strategy) |> result.map_error(refusal.failure) diff --git a/apps/albedo/src/albedo/http/http_wire.gleam b/apps/albedo/src/albedo/http/http_wire.gleam index 431cce9b1..caa9cb740 100644 --- a/apps/albedo/src/albedo/http/http_wire.gleam +++ b/apps/albedo/src/albedo/http/http_wire.gleam @@ -52,6 +52,10 @@ fn progress(snapshot: tool_progress.Snapshot) -> json.Json { pub fn summary_fields(capture: session.Capture) -> List(#(String, json.Json)) { [ #("id", json.string(capture.info.id)), + #( + "configuration_etag", + json.string(http_configuration.etag(capture.configuration)), + ), #( "name", json.string(session_configuration.display_name(capture.configuration)), @@ -161,6 +165,10 @@ pub fn summary( } json.object([ #("id", json.string(info.id)), + #( + "configuration_etag", + json.string(http_configuration.etag(durable.configuration)), + ), #( "name", json.string(session_configuration.display_name(durable.configuration)), diff --git a/apps/albedo/src/albedo/session.gleam b/apps/albedo/src/albedo/session.gleam index 06b0535d4..68bfe6354 100644 --- a/apps/albedo/src/albedo/session.gleam +++ b/apps/albedo/src/albedo/session.gleam @@ -464,6 +464,7 @@ pub type Message { Option(String), Subject(Result(turn.CompactionReport, Refusal)), ) + PersistCompaction(String, String) AdmitCompaction( String, Option(String), @@ -2536,6 +2537,10 @@ fn handle( False -> actor.continue(session_extensions.refresh_requested(state, reason)) } + PersistCompaction(id, response) -> { + persist_compaction(state, id, response) + actor.continue(state) + } AdmitCompaction(id, strategy, reply) -> { let request = compaction_action.request(id, state.info.id, strategy) let admitted = { @@ -2546,7 +2551,7 @@ fn handle( case previous { Some(receipt) -> Ok(#(receipt, False)) None -> { - use _ <- result.try(case busy(state) { + use _ <- result.try(case state.closing || busy(state) { True -> Error(refusal.Busy("session must be idle to compact")) False -> Ok(Nil) }) @@ -2555,6 +2560,7 @@ fn handle( db, request, compaction_action.receipt(id, state.info.id, "running", None), + fn(db) { family.open_in(db, request.target) }, ) }) } @@ -2570,7 +2576,7 @@ fn handle( } } Compact(strategy, action_id, reply) -> - case busy(state) { + case state.closing || busy(state) { True -> { finish_compaction( state, @@ -7285,25 +7291,48 @@ fn finish_compaction( reply: Subject(Result(turn.CompactionReport, Refusal)), outcome: Result(turn.CompactionReport, Refusal), ) -> Nil { - let saved = case action_id { - None -> Ok(Nil) + case action_id { + None -> process.send(reply, outcome) Some(id) -> { let #(status, report) = case outcome { Ok(report) -> #("completed", Some(report)) - Error(_) -> #("interrupted", None) - } - store.query(runtime.ledger(state.host), fn(db) { - operations.finish_compaction_in( - db, - id, - compaction_action.receipt(id, state.info.id, status, report), + Error(error) -> #( + "completed", + Some(turn.CompactionReport( + selection_applied: False, + effective_strategy: None, + state: "failed", + observation: None, + failure: Some(refusal.explain(error)), + )), ) - }) + } + persist_compaction( + state, + id, + compaction_action.receipt(id, state.info.id, status, report), + ) } } - case action_id, saved { - None, Ok(_) -> process.send(reply, outcome) - None, Error(error) -> process.send(reply, Error(refusal.Unavailable(error))) - Some(_), _ -> Nil +} + +/// Retry only the terminal write. The running receipt holds the admission +/// slot until this succeeds; owner death uses the existing interruption path. +fn persist_compaction(state: State, id: String, response: String) -> Nil { + case + store.query(runtime.ledger(state.host), fn(db) { + operations.finish_compaction_in(db, id, response) + }) + { + Ok(_) -> Nil + Error(_) -> { + let _ = + albedo_clock.send_after( + state.self, + 1000, + PersistCompaction(id, response), + ) + Nil + } } } diff --git a/apps/albedo/src/albedo/session/registry.gleam b/apps/albedo/src/albedo/session/registry.gleam index bd2d35c26..cb761aa17 100644 --- a/apps/albedo/src/albedo/session/registry.gleam +++ b/apps/albedo/src/albedo/session/registry.gleam @@ -358,6 +358,17 @@ fn serve(state: State, message: Message) -> actor.Next(State, a) { Ok(#(previous, _)) -> { // It cannot announce that it stopped; remove its own mark. bus.forget_running(previous.id, pid) + case + store.query(runtime.ledger(state.host), fn(db) { + store.transaction(db, fn() { + operations.interrupt_compactions_in(db, previous.id) + }) + }) + { + Ok(_) -> Nil + Error(reason) -> + io.println_error("compaction owner cleanup: " <> reason) + } case session_lookup.info( storage.host(runtime.ledger(state.host)), diff --git a/apps/albedo/src/albedo/storage/operations.gleam b/apps/albedo/src/albedo/storage/operations.gleam index 664917e32..de9c5a2c1 100644 --- a/apps/albedo/src/albedo/storage/operations.gleam +++ b/apps/albedo/src/albedo/storage/operations.gleam @@ -1245,12 +1245,14 @@ pub fn admit_compaction_in( db: sqlight.Connection, request: Request, response: String, + available: fn(sqlight.Connection) -> Result(Nil, Refusal), ) -> Result(#(Receipt, Bool), Refusal) { store.transaction_with(db, refusal.Unavailable, fn() { use previous <- result.try(check_in(db, request)) case previous { Some(receipt) -> Ok(#(receipt, False)) None -> { + use _ <- result.try(available(db)) use active <- result.try( store.rows( db, diff --git a/cli/internal/daemon/acp.go b/cli/internal/daemon/acp.go index ef92848e3..66a5f9f85 100644 --- a/cli/internal/daemon/acp.go +++ b/cli/internal/daemon/acp.go @@ -64,9 +64,13 @@ func RenewACP(ctx context.Context, conn *Connection, id, token string) error { }}, []int{204}, func(_ []byte, _ int) error { return nil }) } func ReleaseACP(ctx context.Context, conn *Connection, id, token string) error { - return executeMutation(ctx, conn, operation{Name: "release ACP", Policy: noRecovery, BuildRequest: func(base string, _ io.Reader) (*http.Request, error) { + err := executeMutation(ctx, conn, operation{Name: "release ACP", Policy: noRecovery, BuildRequest: func(base string, _ io.Reader) (*http.Request, error) { return protocol.NewReleaseACPSessionRequest(base, id, &protocol.ReleaseACPSessionParams{AlbedoAttachmentToken: token}) }}, []int{204}, func(_ []byte, _ int) error { return nil }) + if err == nil { + conn.compactions.Delete(compactionClient{id, token}) + } + return err } func (c *ChatClient) SeedCursor(cursor protocol.Cursor) { diff --git a/cli/internal/daemon/actions.go b/cli/internal/daemon/actions.go index 8b3e0c407..f7b05fa2f 100644 --- a/cli/internal/daemon/actions.go +++ b/cli/internal/daemon/actions.go @@ -7,6 +7,7 @@ import ( "io" "net/http" "strings" + "sync" "time" "albedo/cli/internal/daemon/protocol" @@ -104,20 +105,63 @@ func CompactSession(ctx context.Context, conn *Connection, id, strategy string) return CompactSessionWithToken(ctx, conn, id, strategy, "") } +type compactionClient struct{ session, token string } + +type pendingCompaction struct { + mu sync.Mutex + handle *OperationHandle + strategy string +} + // CompactSessionWithToken lets an ACP attachment holder compact its own session. func CompactSessionWithToken(ctx context.Context, conn *Connection, id, strategy, token string) (CompactionResult, error) { ctx, cancel := context.WithTimeout(ctx, completedActionTimeout) defer cancel() - handle, err := NewCompaction(id, strategy, token) - if err != nil { - return CompactionResult{}, err + key := compactionClient{id, token} + entry, _ := conn.compactions.LoadOrStore(key, &pendingCompaction{}) + pending := entry.(*pendingCompaction) + if !pending.mu.TryLock() { + return CompactionResult{}, errors.New("compaction is already being observed") + } + defer pending.mu.Unlock() + if active, ok := conn.compactions.Load(key); !ok || active != pending { + return CompactionResult{}, errors.New("compaction has already been observed") + } + var err error + resumed := pending.handle != nil + if !resumed { + pending.handle, err = NewCompaction(id, strategy, token) + if err != nil { + conn.compactions.CompareAndDelete(key, pending) + return CompactionResult{}, err + } + pending.strategy = strategy + } + handle := pending.handle + if strategy != pending.strategy { + return CompactionResult{}, fmt.Errorf("resolve compaction %s before changing its intent", handle.ID()) + } + submitted := !resumed + var receipt protocol.CompactionReceipt + if resumed { + receipt, err = ReadCompaction(ctx, conn, handle) + if api, ok := errors.AsType[*APIError](err); ok && api.Code == "compaction_unknown" { + submitted = true + receipt, err = SubmitCompaction(ctx, conn, handle) + } + } else { + receipt, err = SubmitCompaction(ctx, conn, handle) } - receipt, err := SubmitCompaction(ctx, conn, handle) if err != nil { + if submitted { + if _, uncertain := errors.AsType[*UncertainOutcomeError](err); !uncertain && !IsOperationExpired(err) { + conn.compactions.CompareAndDelete(key, pending) + } + } return CompactionResult{}, err } - for receipt.State == "running" { - timer := time.NewTimer(200 * time.Millisecond) + for delay := 200 * time.Millisecond; receipt.State == "running"; delay = min(2*time.Second, delay*2) { + timer := time.NewTimer(delay) select { case <-ctx.Done(): timer.Stop() @@ -129,6 +173,7 @@ func CompactSessionWithToken(ctx context.Context, conn *Connection, id, strategy return CompactionResult{}, uncertainOperation(handle.operation, err) } } + conn.compactions.CompareAndDelete(key, pending) if receipt.State == "interrupted" { return CompactionResult{}, fmt.Errorf("compaction %s was interrupted; inspect context before starting another action", handle.ID()) } @@ -149,7 +194,7 @@ func NewCompaction(session, strategy, token string) (*OperationHandle, error) { if token != "" { params.AlbedoAttachmentToken = &token } - handle := &OperationHandle{id: id, sessionID: session, kind: "compaction"} + handle := &OperationHandle{id: id, sessionID: session, kind: "compaction", attachmentToken: token} handle.operation = operation{Name: "compact session", Body: protocol.CompactionRequest{Strategy: optionalText(strategy)}, Policy: noRecovery, Handle: handle, BuildRequest: func(base string, body io.Reader) (*http.Request, error) { return protocol.NewPutCompactionRequestWithBody(base, session, id, params, "application/json", body) }} @@ -162,7 +207,8 @@ func ReadCompaction(ctx context.Context, conn *Connection, handle *OperationHand return receipt, errors.New("compaction handle required") } err := executeRead(ctx, conn, operation{Name: "read compaction", Policy: readRecovery, BuildRequest: func(base string, _ io.Reader) (*http.Request, error) { - return protocol.NewGetCompactionRequest(base, handle.sessionID, handle.id) + params := &protocol.GetCompactionParams{AlbedoAttachmentToken: optionalText(handle.attachmentToken)} + return protocol.NewGetCompactionRequest(base, handle.sessionID, handle.id, params) }}, func(data []byte) error { return decodeCompaction(data, handle, &receipt) }) return receipt, err } diff --git a/cli/internal/daemon/connection.go b/cli/internal/daemon/connection.go index b58b7fa1f..4f3f23e36 100644 --- a/cli/internal/daemon/connection.go +++ b/cli/internal/daemon/connection.go @@ -21,6 +21,7 @@ type ConnectionSnapshot struct { } type Connection struct { + compactions sync.Map // compactionClient to *pendingCompaction state atomic.Pointer[connectionState] httpClient *http.Client refreshGate chan struct{} diff --git a/cli/internal/daemon/credentials.go b/cli/internal/daemon/credentials.go index 1070b3c71..9016be6f3 100644 --- a/cli/internal/daemon/credentials.go +++ b/cli/internal/daemon/credentials.go @@ -1,7 +1,7 @@ package daemon import ( - "encoding/json" + "albedo/cli/internal/daemon/protocol" "errors" "time" ) @@ -57,25 +57,21 @@ type MCPSecretsPatch struct { ClearEnv bool } -func (patch MCPSecretsPatch) MarshalJSON() ([]byte, error) { - if (patch.BearerToken != nil && patch.RemoveBearerToken) || (patch.Headers != nil && patch.ClearHeaders) || (patch.Env != nil && patch.ClearEnv) { - return nil, errors.New("secret patch cannot replace and clear the same field") +func (patch MCPSecretsPatch) wire() (protocol.MCPSecretsPatch, error) { + var fields protocol.MCPSecretsPatch + if patch.BearerToken != nil && patch.RemoveBearerToken || patch.Headers != nil && patch.ClearHeaders || patch.Env != nil && patch.ClearEnv { + return fields, errors.New("secret patch cannot replace and clear the same field") } - fields := make(map[string]any) if patch.BearerToken != nil { - fields["bearer_token"] = *patch.BearerToken + fields.BearerToken = protocol.SetNullablePatch(*patch.BearerToken) } else if patch.RemoveBearerToken { - fields["bearer_token"] = nil + fields.BearerToken = protocol.ClearPatch[string]() } if patch.Headers != nil { - fields["headers"] = patch.Headers - } else if patch.ClearHeaders { - fields["headers"] = nil + fields.Headers = protocol.SetPatch(patch.Headers) } if patch.Env != nil { - fields["environment"] = patch.Env - } else if patch.ClearEnv { - fields["environment"] = nil + fields.Environment = protocol.SetPatch(patch.Env) } - return json.Marshal(fields) + return fields, nil } diff --git a/cli/internal/daemon/extensions.go b/cli/internal/daemon/extensions.go index 65f69a1a7..14a64f756 100644 --- a/cli/internal/daemon/extensions.go +++ b/cli/internal/daemon/extensions.go @@ -138,9 +138,7 @@ func PatchSessionCompactionStrategy(ctx context.Context, conn *Connection, sessi func SelectExtension(ctx context.Context, conn *Connection, session string, request ExtensionSelectionRequest) ([]ExtensionSummary, error) { if request.Scope == "global" { var change protocol.ExtensionSettingsChange - err := patchSettingsGroup(ctx, conn, "extensions", request.ETag, struct { - Defaults map[string]*bool `json:"defaults"` - }{map[string]*bool{request.Name: request.Enabled}}, &change) + err := patchSettingsGroup(ctx, conn, "extensions", request.ETag, protocol.ExtensionSettingsPatch{Defaults: protocol.SetPatch(map[string]*bool{request.Name: request.Enabled})}, &change) if err != nil { return nil, err } diff --git a/cli/internal/daemon/operations.go b/cli/internal/daemon/operations.go index 3912c8e95..3a9b819e9 100644 --- a/cli/internal/daemon/operations.go +++ b/cli/internal/daemon/operations.go @@ -17,10 +17,11 @@ import ( // OperationHandle freezes the chosen resource ID and exact admission payload. // Retries always use this same input or session resource. type OperationHandle struct { - id string - operation operation - kind string - sessionID string + id string + operation operation + kind string + sessionID string + attachmentToken string } func (handle *OperationHandle) ID() string { return handle.id } @@ -284,7 +285,7 @@ func ResolveCreation(ctx context.Context, conn *Connection, handle *OperationHan } func IsOperationExpired(err error) bool { api, ok := errors.AsType[*APIError](err) - return ok && api.StatusCode == http.StatusGone + return ok && (api.StatusCode == http.StatusGone || api.Code == "identity_expired") } func sameCreationIntent(expected, stored json.RawMessage) bool { diff --git a/cli/internal/daemon/protocol/api.gen.go b/cli/internal/daemon/protocol/api.gen.go index 378175a38..028d46ca6 100644 --- a/cli/internal/daemon/protocol/api.gen.go +++ b/cli/internal/daemon/protocol/api.gen.go @@ -3198,14 +3198,17 @@ type Server struct { // Session defines model for Session. type Session struct { // Acp Present only for ACP-owned sessions. Attachment state is read separately from the session capture. - Acp *ACPState `json:"acp,omitempty"` - ActiveOutput []ActiveOutput `json:"active_output"` - Activity Activity `json:"activity"` - ActivityAt *Timestamp `json:"activity_at" nullable:"true"` - Address *string `json:"address" nullable:"true"` - AutomaticName string `json:"automatic_name"` - Closed bool `json:"closed"` - Composition Composition `json:"composition"` + Acp *ACPState `json:"acp,omitempty"` + ActiveOutput []ActiveOutput `json:"active_output"` + Activity Activity `json:"activity"` + ActivityAt *Timestamp `json:"activity_at" nullable:"true"` + Address *string `json:"address" nullable:"true"` + AutomaticName string `json:"automatic_name"` + Closed bool `json:"closed"` + Composition Composition `json:"composition"` + + // ConfigurationEtag Strong opaque validator for the complete canonical representation. + ConfigurationEtag *ETag `json:"configuration_etag,omitempty"` ConfigurationResource SessionConfigurationResource `json:"configuration_resource"` CreatedAt *Timestamp `json:"created_at" nullable:"true"` @@ -3284,9 +3287,6 @@ type SessionChange struct { Session Session `json:"session"` } -// SessionChangeRequest defines model for SessionChangeRequest. -type SessionChangeRequest = json.RawMessage - // SessionCommittedEvent defines model for SessionCommittedEvent. type SessionCommittedEvent struct { Data struct { @@ -3637,17 +3637,20 @@ type SessionStatusRead struct { // SessionSummary Session live fields and cursor are captured together. ACP attachment metadata is read separately. Extra response fields may be ignored. type SessionSummary struct { // Acp Present only for ACP-owned sessions. Attachment state is read separately from the session capture. - Acp *ACPState `json:"acp,omitempty"` - Activity Activity `json:"activity"` - ActivityAt *Timestamp `json:"activity_at" nullable:"true"` - Address *string `json:"address" nullable:"true"` - AutomaticName string `json:"automatic_name"` - Closed bool `json:"closed"` - CreatedAt *Timestamp `json:"created_at" nullable:"true"` - CurrentProgress []ToolProgress `json:"current_progress"` - Cursor *Cursor `json:"cursor" nullable:"true"` - CyberAccess *string `json:"cyber_access,omitempty" nullable:"true"` - Depth int64 `json:"depth"` + Acp *ACPState `json:"acp,omitempty"` + Activity Activity `json:"activity"` + ActivityAt *Timestamp `json:"activity_at" nullable:"true"` + Address *string `json:"address" nullable:"true"` + AutomaticName string `json:"automatic_name"` + Closed bool `json:"closed"` + + // ConfigurationEtag Strong opaque validator for the complete canonical representation. + ConfigurationEtag *ETag `json:"configuration_etag,omitempty"` + CreatedAt *Timestamp `json:"created_at" nullable:"true"` + CurrentProgress []ToolProgress `json:"current_progress"` + Cursor *Cursor `json:"cursor" nullable:"true"` + CyberAccess *string `json:"cyber_access,omitempty" nullable:"true"` + Depth int64 `json:"depth"` // Effort Saved reasoning choice. inherit follows the profile override or model default; default bypasses the profile override. Other strings select an explicit supported level. Null retains legacy unset behavior. Effort *string `json:"effort" nullable:"true"` @@ -5080,6 +5083,12 @@ type GetSessionChangesParams struct { IfNoneMatch *string `json:"If-None-Match,omitempty"` } +// GetCompactionParams defines parameters for GetCompaction. +type GetCompactionParams struct { + // AlbedoAttachmentToken Required for kind acp creation and for input or scoped cancellation in an ACP session. Also authorizes compaction and scoped execution configuration patches by an ACP attachment holder. Ordinary creation ignores this header. Input, scoped cancellation, compaction for ACP sessions, and configuration patches parse and reject malformed supplied values. Not part of the durable intent. + AlbedoAttachmentToken *AttachmentTokenOptional `json:"Albedo-Attachment-Token,omitempty"` +} + // PutCompactionParams defines parameters for PutCompaction. type PutCompactionParams struct { // AlbedoAttachmentToken Required for kind acp creation and for input or scoped cancellation in an ACP session. Also authorizes compaction and scoped execution configuration patches by an ACP attachment holder. Ordinary creation ignores this header. Input, scoped cancellation, compaction for ACP sessions, and configuration patches parse and reject malformed supplied values. Not part of the durable intent. @@ -6616,7 +6625,7 @@ type ClientInterface interface { // GetCompaction Read a compaction receipt // // Corresponds with GET /sessions/{session_id}/compactions/{action_id} (the `GetCompaction` operationId). - GetCompaction(ctx context.Context, sessionID ID, actionID ID, reqEditors ...RequestEditorFn) (*http.Response, error) + GetCompaction(ctx context.Context, sessionID ID, actionID ID, params *GetCompactionParams, reqEditors ...RequestEditorFn) (*http.Response, error) // PutCompactionWithBody Admit identified compaction // @@ -9674,8 +9683,8 @@ func (c *Client) GetSessionChanges(ctx context.Context, sessionID ID, params *Ge // GetCompaction Read a compaction receipt // // Corresponds with GET /sessions/{session_id}/compactions/{action_id} (the `GetCompaction` operationId). -func (c *Client) GetCompaction(ctx context.Context, sessionID ID, actionID ID, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetCompactionRequest(c.Server, sessionID, actionID) +func (c *Client) GetCompaction(ctx context.Context, sessionID ID, actionID ID, params *GetCompactionParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetCompactionRequest(c.Server, sessionID, actionID, params) if err != nil { return nil, err } @@ -16596,7 +16605,7 @@ func NewGetSessionChangesRequest(server string, sessionID ID, params *GetSession } // NewGetCompactionRequest constructs an http.Request for the GetCompaction method -func NewGetCompactionRequest(server string, sessionID ID, actionID ID) (*http.Request, error) { +func NewGetCompactionRequest(server string, sessionID ID, actionID ID, params *GetCompactionParams) (*http.Request, error) { var err error var pathParam0 string @@ -16633,6 +16642,21 @@ func NewGetCompactionRequest(server string, sessionID ID, actionID ID) (*http.Re return nil, err } + if params != nil { + + if params.AlbedoAttachmentToken != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "Albedo-Attachment-Token", *params.AlbedoAttachmentToken, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + req.Header.Set("Albedo-Attachment-Token", headerParam0) + } + + } + return req, nil } diff --git a/cli/internal/daemon/protocol/digest.gen.go b/cli/internal/daemon/protocol/digest.gen.go index 1cfc39b0a..26abfe755 100644 --- a/cli/internal/daemon/protocol/digest.gen.go +++ b/cli/internal/daemon/protocol/digest.gen.go @@ -5,4 +5,4 @@ package protocol // APIDigest identifies the wire contract these types were generated from. // The daemon reports its own in GET /server; a different value means this // client's decoders may reject what the daemon sends. -const APIDigest = "e46b36cd054c1748a4baa784ed7069a5d90bfb885707aa9c792100f685b1f50c" +const APIDigest = "f232497ce0f3d13a04d4e730e54122cd2c141cb5f26131e164e60407174adae4" diff --git a/cli/internal/daemon/protocol/recovery.gen.go b/cli/internal/daemon/protocol/recovery.gen.go index 4108622b2..2ac73c18a 100644 --- a/cli/internal/daemon/protocol/recovery.gen.go +++ b/cli/internal/daemon/protocol/recovery.gen.go @@ -350,6 +350,8 @@ func OperationRecovery(operation string) RecoveryPolicy { // Problem constants are known values, not a closed validation enum. const ( + ProblemAcpOwned = "acp_owned" + ProblemAttachmentLost = "attachment_lost" ProblemCatalogChanged = "catalog_changed" ProblemCompactionUnknown = "compaction_unknown" ProblemConfigurationChanged = "configuration_changed" diff --git a/cli/internal/daemon/rotation.go b/cli/internal/daemon/rotation.go index baffa155a..d0450d414 100644 --- a/cli/internal/daemon/rotation.go +++ b/cli/internal/daemon/rotation.go @@ -93,16 +93,16 @@ func RotationTargets(extension string, profiles config.Profiles) []string { // RotationPatch is the providers settings patch that gives a service the // order and mode: every target profile takes the list and the mode, and // drops any pin. It is nil when no profile would change. -func RotationPatch(extension string, profiles config.Profiles, order []string, mode string) map[string]any { +func RotationPatch(extension string, profiles config.Profiles, order []string, mode string) *protocol.ProviderSettingsPatch { targets := RotationTargets(extension, profiles) if len(targets) == 0 { return nil } - patch := map[string]any{} + patch := map[string]*protocol.ProviderProfilePatch{} for _, name := range targets { - patch[name] = map[string]any{"account_ids": slices.Clone(order), "rotation": mode, "account_id": nil} + patch[name] = &protocol.ProviderProfilePatch{AccountIDs: protocol.SetNullablePatch(slices.Clone(order)), Rotation: protocol.SetPatch(mode), AccountID: protocol.ClearPatch[string]()} } - return map[string]any{"profiles": patch} + return &protocol.ProviderSettingsPatch{Profiles: protocol.SetPatch(patch)} } // SaveServiceRotation writes a service's order and mode in one patch. It diff --git a/cli/internal/daemon/rotation_test.go b/cli/internal/daemon/rotation_test.go index cccd4326d..8f407012f 100644 --- a/cli/internal/daemon/rotation_test.go +++ b/cli/internal/daemon/rotation_test.go @@ -4,6 +4,7 @@ package daemon import ( + "encoding/json" "reflect" "testing" @@ -53,11 +54,15 @@ func TestRotationPatchSkipsPinnedAndKeyedProfiles(t *testing.T) { "chatgpt": {Extension: "codex"}, }} got := RotationPatch("claude", profiles, []string{"b", "a"}, RotationSpread) - entry := map[string]any{"account_ids": []string{"b", "a"}, "rotation": "spread", "account_id": nil} - want := map[string]any{"profiles": map[string]any{"claude": entry, "team": entry}} - if !reflect.DeepEqual(got, want) { - t.Fatalf("patch %v, want %v", got, want) + wire, err := json.Marshal(got) + if err != nil { + t.Fatal(err) } + want := `{"profiles":{"claude":{"account_id":null,"account_ids":["b","a"],"rotation":"spread"},"team":{"account_id":null,"account_ids":["b","a"],"rotation":"spread"}}}` + if string(wire) != want { + t.Fatalf("patch %s, want %s", wire, want) + } + if RotationPatch("gemini", profiles, []string{"a"}, RotationFailover) != nil { t.Fatal("a service no profile runs got a patch") } diff --git a/cli/internal/daemon/server.go b/cli/internal/daemon/server.go index 4621f1f37..0d8a4e0f5 100644 --- a/cli/internal/daemon/server.go +++ b/cli/internal/daemon/server.go @@ -210,20 +210,20 @@ func noticeValues(rows []struct { } func DismissServerNotices(ctx context.Context, conn *Connection, etag string, ids []string) error { var change protocol.UISettingsChange - err := patchSettingsGroup(ctx, conn, "ui", etag, map[string]any{"dismissed_notices": ids}, &change) + err := patchSettingsGroup(ctx, conn, "ui", etag, protocol.UISettingsPatch{DismissedNotices: protocol.SetPatch(nonNil(ids))}, &change) return err } // SaveWebAllow keeps the networks `albedo web` serves to, for its next start. func SaveWebAllow(ctx context.Context, conn *Connection, etag string, networks []string) error { var change protocol.UISettingsChange - return patchSettingsGroup(ctx, conn, "ui", etag, map[string]any{"web_allow": append([]string{}, networks...)}, &change) + return patchSettingsGroup(ctx, conn, "ui", etag, protocol.UISettingsPatch{WebAllow: protocol.SetPatch(nonNil(networks))}, &change) } // SaveProxyAllow keeps the networks `albedo proxy` serves to, for its next start. func SaveProxyAllow(ctx context.Context, conn *Connection, etag string, networks []string) error { var change protocol.UISettingsChange - return patchSettingsGroup(ctx, conn, "ui", etag, map[string]any{"proxy_allow": append([]string{}, networks...)}, &change) + return patchSettingsGroup(ctx, conn, "ui", etag, protocol.UISettingsPatch{ProxyAllow: protocol.SetPatch(nonNil(networks))}, &change) } // BuildIdentity identifies daemon code by its label and content digest. diff --git a/cli/internal/daemon/sessions.go b/cli/internal/daemon/sessions.go index 98a393c40..277d4f252 100644 --- a/cli/internal/daemon/sessions.go +++ b/cli/internal/daemon/sessions.go @@ -419,7 +419,9 @@ func previewItems(ctx context.Context, conn *Connection, id string, entries []pr } func summaryValue(row protocol.SessionSummary) Session { - return sessionValue(protocol.Session{ID: row.ID, Name: row.Name, AutomaticName: row.AutomaticName, Workspace: row.Workspace, Location: row.Location, ParentID: row.ParentID, RootID: row.RootID, Address: row.Address, Depth: row.Depth, Closed: row.Closed, CreatedAt: row.CreatedAt, ActivityAt: row.ActivityAt, ProviderProfile: row.ProviderProfile, Model: row.Model, CyberAccess: row.CyberAccess, Effort: row.Effort, Status: row.Status, Preview: row.Preview, Preferences: row.Preferences, CurrentProgress: row.CurrentProgress, Activity: row.Activity, Cursor: row.Cursor, Moved: row.Moved, MovePending: row.MovePending}) + session := sessionValue(protocol.Session{ID: row.ID, Name: row.Name, AutomaticName: row.AutomaticName, Workspace: row.Workspace, Location: row.Location, ParentID: row.ParentID, RootID: row.RootID, Address: row.Address, Depth: row.Depth, Closed: row.Closed, CreatedAt: row.CreatedAt, ActivityAt: row.ActivityAt, ProviderProfile: row.ProviderProfile, Model: row.Model, CyberAccess: row.CyberAccess, Effort: row.Effort, Status: row.Status, Preview: row.Preview, Preferences: row.Preferences, CurrentProgress: row.CurrentProgress, Activity: row.Activity, Cursor: row.Cursor, Moved: row.Moved, MovePending: row.MovePending}) + session.ETag = value(row.ConfigurationEtag) + return session } func ListAllSessions(ctx context.Context, conn *Connection) ([]Session, error) { return listSessions(ctx, conn, protocol.ListSessionsParams{Scope: new("all")}) diff --git a/cli/internal/daemon/settings.go b/cli/internal/daemon/settings.go index c4007e6b3..b9f77f9e5 100644 --- a/cli/internal/daemon/settings.go +++ b/cli/internal/daemon/settings.go @@ -182,7 +182,7 @@ func saveProvider(ctx context.Context, conn *Connection, name string, profile co // and every session on it follow the new name. func RenameProvider(ctx context.Context, conn *Connection, from, to, etag string) error { var change protocol.ProviderSettingsChange - return patchSettingsGroup(ctx, conn, "providers", etag, map[string]any{"renames": map[string]string{from: to}}, &change) + return patchSettingsGroup(ctx, conn, "providers", etag, protocol.ProviderSettingsPatch{Renames: protocol.SetPatch(map[string]string{from: to})}, &change) } func DeleteProvider(ctx context.Context, conn *Connection, name string, profiles config.Profiles) error { body := protocol.ProviderSettingsPatch{Profiles: protocol.SetPatch(map[string]*protocol.ProviderProfilePatch{name: nil})} @@ -240,7 +240,7 @@ type MCPUpdateRequest struct { } func SaveMCP(ctx context.Context, conn *Connection, session string, request MCPUpdateRequest) (ReloadResult, error) { - var definition any + var definition *protocol.MCPDefinitionPatch if request.Server != nil { server := request.Server secrets := request.Secrets @@ -258,28 +258,32 @@ func SaveMCP(ctx context.Context, conn *Connection, session string, request MCPU secrets.Env[name] = nil } } - // These nulls clear fields when changing transports; nil optional - // pointers in MCPDefinitionPatch would omit them. - patch := map[string]any{ - "enabled": server.Enabled == nil || *server.Enabled, "transport": server.Type, - "command": optionalText(server.Command), "arguments": nonNil(server.Args), - "cwd": optionalText(server.CWD), "url": optionalText(server.URL), - "environment": nonNilMap(server.Env), "headers": nonNilMap(server.Headers), - "bearer_token_env_var": optionalText(server.BearerTokenEnvVar), - "enabled_tools": nullIfEmpty(server.EnabledTools), "disabled_tools": nonNil(server.DisabledTools), - "secrets": secrets, + secretPatch, err := secrets.wire() + if err != nil { + return ReloadResult{}, err + } + definition = &protocol.MCPDefinitionPatch{ + Enabled: protocol.SetPatch(server.Enabled == nil || *server.Enabled), Transport: protocol.SetPatch(server.Type), + Command: nullablePatch(optionalText(server.Command)), Arguments: protocol.SetPatch(nonNil(server.Args)), + Cwd: nullablePatch(optionalText(server.CWD)), URL: nullablePatch(optionalText(server.URL)), + Environment: protocol.SetNullablePatch(mcpValueSources(server.Env)), Headers: protocol.SetNullablePatch(mcpValueSources(server.Headers)), + BearerTokenEnvVar: nullablePatch(optionalText(server.BearerTokenEnvVar)), + EnabledTools: protocol.ClearPatch[[]string](), DisabledTools: protocol.SetPatch(nonNil(server.DisabledTools)), + Secrets: protocol.SetPatch(secretPatch), + } + if len(server.EnabledTools) > 0 { + definition.EnabledTools = protocol.SetNullablePatch(server.EnabledTools) } if server.StartupTimeoutMs != 0 { - patch["startup_timeout_ms"] = server.StartupTimeoutMs + definition.StartupTimeoutMs = protocol.SetPatch(int64(server.StartupTimeoutMs)) } if server.CallTimeoutMs != 0 { - patch["call_timeout_ms"] = server.CallTimeoutMs + definition.CallTimeoutMs = protocol.SetPatch(int64(server.CallTimeoutMs)) } - definition = patch } var change protocol.MCPSettingsChange - err := patchSettingsGroup(ctx, conn, "mcp", request.ETag, map[string]any{ - "definitions": map[string]any{request.Name: definition}, + err := patchSettingsGroup(ctx, conn, "mcp", request.ETag, protocol.MCPSettingsPatch{ + Definitions: protocol.SetPatch(map[string]*protocol.MCPDefinitionPatch{request.Name: definition}), }, &change) return applicationResult(change.Application), err } @@ -288,9 +292,9 @@ func SaveMCP(ctx context.Context, conn *Connection, session string, request MCPU // asks for a sign-in on its next request. func SignOutMCP(ctx context.Context, conn *Connection, name, etag string) error { var change protocol.MCPSettingsChange - return patchSettingsGroup(ctx, conn, "mcp", etag, map[string]any{ - "definitions": map[string]any{name: map[string]any{"secrets": map[string]any{"oauth": nil}}}, - "validate_connection": false, + return patchSettingsGroup(ctx, conn, "mcp", etag, protocol.MCPSettingsPatch{ + Definitions: protocol.SetPatch(map[string]*protocol.MCPDefinitionPatch{name: {Secrets: protocol.SetPatch(protocol.MCPSecretsPatch{Oauth: protocol.ClearPatch[any]()})}}), + ValidateConnection: protocol.SetPatch(false), }, &change) } @@ -314,13 +318,12 @@ func nonNil[T any](s []T) []T { return s } -// nullIfEmpty is the wire value for an optional allowlist: null means no -// allowlist, while an empty list would allow nothing. -func nullIfEmpty[T any](s []T) []T { - if len(s) == 0 { - return nil +func mcpValueSources(values map[string]map[string]string) map[string]*protocol.ValueSource { + sources := make(map[string]*protocol.ValueSource, len(values)) + for key, value := range values { + sources[key] = &protocol.ValueSource{Source: value["source"], Value: value["value"]} } - return s + return sources } func nonNilMap[K comparable, V any](m map[K]V) map[K]V { if m == nil { @@ -369,7 +372,7 @@ func DismissNotice(ctx context.Context, conn *Connection, id string) (UIPreferen return uiPreferences(wire, etag), nil } var change protocol.UISettingsChange - err = patchSettingsGroup(ctx, conn, "ui", etag, map[string]any{"dismissed_notices": append(slices.Clip(wire.DismissedNotices), id)}, &change) + err = patchSettingsGroup(ctx, conn, "ui", etag, protocol.UISettingsPatch{DismissedNotices: protocol.SetPatch(append(slices.Clip(wire.DismissedNotices), id))}, &change) if apiErr, stale := errors.AsType[*APIError](err); stale && apiErr.StatusCode == http.StatusPreconditionFailed && attempt == 0 { continue } @@ -555,7 +558,7 @@ func SaveExtensionSetting(ctx context.Context, conn *Connection, etag, section, // A nil value marshals to JSON null, which is how the daemon is asked to // drop the saved value. var change protocol.DeclaredSettingsChange - body := map[string]any{"values": map[string]any{section: map[string]any{key: value}}} + body := protocol.DeclaredSettingsPatch{Values: map[string]map[string]json.RawMessage{section: {key: value}}} if err := patchSettingsGroup(ctx, conn, "extension_settings", etag, body, &change); err != nil { return ExtensionSettings{}, err } diff --git a/cli/internal/daemon/submission_recovery_test.go b/cli/internal/daemon/submission_recovery_test.go index d7acd2b5c..c96ab9330 100644 --- a/cli/internal/daemon/submission_recovery_test.go +++ b/cli/internal/daemon/submission_recovery_test.go @@ -178,3 +178,35 @@ func TestCompactionRecoversLostAdmissionAndKeepsDomainFailure(t *testing.T) { t.Fatalf("action was replayed: puts=%d gets=%d", admissions.Load(), lookups.Load()) } } + +func TestCompactSessionRetainsUnresolvedAdmission(t *testing.T) { + var ready atomic.Bool + var first atomic.Pointer[string] + conn := controlledConnection(t, func(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path + first.CompareAndSwap(nil, &path) + if *first.Load() != path || r.Header.Get("Albedo-Attachment-Token") != "holder" { + t.Errorf("unexpected recovery request %s", path) + } + if !ready.Load() { + socket, _, err := w.(http.Hijacker).Hijack() + if err != nil { + t.Error(err) + return + } + _ = socket.Close() + return + } + if r.Method != "GET" { + t.Errorf("unexpected replay %s", r.Method) + } + _ = json.NewEncoder(w).Encode(map[string]any{"id": strings.TrimPrefix(path, "/sessions/s/compactions/"), "session_id": "s", "state": "completed", "result": map[string]any{"state": "unchanged", "selection_applied": false, "effective_strategy": nil, "observation": nil, "failure": nil}}) + }) + if _, err := CompactSessionWithToken(t.Context(), conn, "s", "rolling", "holder"); err == nil { + t.Fatal("expected uncertain admission") + } + ready.Store(true) + if _, err := CompactSessionWithToken(t.Context(), conn, "s", "rolling", "holder"); err != nil { + t.Fatal(err) + } +} diff --git a/cli/internal/tui/app_sessions.go b/cli/internal/tui/app_sessions.go index e0ea61701..537fa0fb8 100644 --- a/cli/internal/tui/app_sessions.go +++ b/cli/internal/tui/app_sessions.go @@ -85,17 +85,14 @@ func (m *AppModel) handleSessionResults(msg tea.Msg) (tea.Cmd, bool) { m.SessionPicker.notice = operationError(msg.Err, "Could not rename the session: ", "Session may have been renamed; refresh the session list before trying again.") return tea.Batch(cmd, m.refusedConfigurationCmd(msg.Err)), true } - for _, current := range m.Sessions { - if current.ID == msg.Configuration.Value.ID { - current.ETag = msg.Configuration.ETag - if msg.Configuration.Value.Name != nil { - current.Title = *msg.Configuration.Value.Name - } else { - current.Title = current.AutomaticTitle - } - m.updateSession(current) - break + if current, ok := m.session(msg.Configuration.Value.ID); ok { + current.ETag = msg.Configuration.ETag + if msg.Configuration.Value.Name != nil { + current.Title = *msg.Configuration.Value.Name + } else { + current.Title = current.AutomaticTitle } + m.updateSession(current) } m.SessionPicker.notice = "" return cmd, true diff --git a/docs/api-client.gen.md b/docs/api-client.gen.md index a0d9a43e0..4ef435d10 100644 --- a/docs/api-client.gen.md +++ b/docs/api-client.gen.md @@ -159,6 +159,10 @@ Recovery: `safe-read`. Documented HTTP problem codes: - `invalid_request` +- `acp_owned` +- `attachment_lost` +- `identity_expired` +- `identity_invalid` - `compaction_unknown` - `request_unavailable` @@ -171,6 +175,8 @@ Recovery: `repeat-identical-intent`. Documented HTTP problem codes: - `invalid_request` +- `acp_owned` +- `attachment_lost` - `identity_invalid` - `id_conflict` - `identity_expired` diff --git a/docs/client-api.md b/docs/client-api.md index 380b855c9..c6dae6e54 100644 --- a/docs/client-api.md +++ b/docs/client-api.md @@ -112,10 +112,12 @@ read configuration once before writing and consume the returned resource. Generated Go patch fields distinguish omission, a value, and nullable removal. Use `SetPatch` for nonnullable fields, `SetNullablePatch` for nullable values, -and `ClearPatch` only for nullable fields. A zero field is omitted. Containing -serializers preserve false, zero, empty strings, and empty collections. Response -types retain their ordinary representation. TypeScript keeps its native -undefined, null, and value semantics. +and `ClearPatch` only for nullable fields. A zero optional field is omitted. +Required fields are always serialized. The operation schema determines which +values are in bounds. Containing serializers preserve false, zero, empty +strings, and empty collections. Response types retain their ordinary +representation. TypeScript keeps its native undefined, null, and value +semantics. `NewCompaction`, `SubmitCompaction`, and `ReadCompaction` retain immutable action identity across uncertain delivery. The convenience compaction call polls diff --git a/docs/http-api-design.md b/docs/http-api-design.md index 30b84e16d..60f2b5305 100644 --- a/docs/http-api-design.md +++ b/docs/http-api-design.md @@ -561,8 +561,8 @@ compaction intent under a current UUIDv7. It requires idle for new work. The same ID and intent returns the retained receipt; changed intent returns `409 id_conflict`. `GET` on that URL reads the receipt. Acceptance is durable before work starts. Connection cancellation does not cancel accepted work. -Admission allows one active compaction per session and at most 64 across the -daemon. +Identified HTTP admission allows one active compaction per session and at most +64 across the daemon. Receipts are retained for at least seven days after completion or interruption, under the existing operation identity admission window. History does not expire @@ -572,6 +572,13 @@ definite result: strategy selection or compaction effects may already have committed. Inspect context and configuration before explicitly starting another action with a new ID. +While an ACP attachment owns the session, both replay and receipt reads require +its token. After deletion the session no longer has an attachment. Retained +receipts can still be read by authenticated daemon clients. + +The trusted in-process `command.Compact` bridge waits synchronously on the +session actor. It has no HTTP identity, receipt, or global admission slot. + A completed receipt contains the compaction result, including `selection_applied`, the effective strategy, and any failure. A failed compaction preserves a strategy that was successfully selected. HTTP errors diff --git a/docs/http-sessions.md b/docs/http-sessions.md index 17b3a3e1c..e0a7ab59a 100644 --- a/docs/http-sessions.md +++ b/docs/http-sessions.md @@ -68,7 +68,9 @@ match. Parent and family queries default to `scope=all`. Other queries default to roots. An explicitly supplied `scope=roots` with a parent or family filter -returns `400`. The result is a page of `SessionSummary` objects. A family query +returns `400`. The result is a page of `SessionSummary` objects. Each summary +carries the configuration ETag from the same durable capture as its displayed +settings. Clients retain that validator when queuing a change. A family query also returns `family: { "root_id": ..., "revision": ... }`. Agent trees are drawn from `parent_id`, `address`, and `depth`. There is no second agent identity or graph endpoint. Clients can traverse all pages. A missing requested @@ -228,12 +230,12 @@ counts one deliberate attachment. Repeating the UUIDv7 returns the same count without incrementing it again. Background refreshes do not create visits. Reads never change opens. Deleted sessions cannot be revived by a visit. -`DELETE /sessions/{session_id}/configuration` defaults to `scope=leaf`. It -requires the configuration `If-Match`, an idle session, and no children. -`scope=subtree` also requires the `family_revision` query parameter from the -session read. The daemon captures exactly that membership, prevents new child -admission during this operation, interrupts members, cancels pending inputs, and -deletes deepest first. +`DELETE /sessions/{session_id}` defaults to `scope=leaf`. It requires the +configuration `If-Match`, an idle session, and no children. `scope=subtree` also +requires the `family_revision` query parameter from the session read. The daemon +captures exactly that membership, prevents new child admission during this +operation, interrupts members, cancels pending inputs, and deletes deepest +first. Deletion returns `200` with `state: "complete"|"partial"`, `deleted_count`, `remaining_count`, `deleted_ids`, and `remaining` objects containing ID and safe diff --git a/docs/openapi.yaml b/docs/openapi.yaml index 01502dd47..a252510c9 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -8659,6 +8659,8 @@ paths: application/json: schema: $ref: '#/components/schemas/CompactionReceipt' + '410': + $ref: '#/components/responses/Problem410' parameters: - name: session_id in: path @@ -8682,6 +8684,8 @@ paths: x-albedo-recovery: repeat-identical-intent x-albedo-problem-codes: - invalid_request + - acp_owned + - attachment_lost - identity_invalid - id_conflict - identity_expired @@ -8720,12 +8724,15 @@ paths: $ref: '#/components/responses/Problem404' '409': $ref: '#/components/responses/Problem409' + '410': + $ref: '#/components/responses/Problem410' parameters: - name: session_id in: path required: true schema: $ref: '#/components/schemas/ID' + - $ref: '#/components/parameters/AttachmentTokenOptional' - name: action_id in: path required: true @@ -8735,6 +8742,10 @@ paths: x-albedo-recovery: safe-read x-albedo-problem-codes: - invalid_request + - acp_owned + - attachment_lost + - identity_expired + - identity_invalid - compaction_unknown - request_unavailable components: @@ -11599,6 +11610,8 @@ components: SessionSummary: type: object properties: + configuration_etag: + $ref: '#/components/schemas/ETag' id: $ref: '#/components/schemas/ID' name: @@ -12104,10 +12117,6 @@ components: examples: - workspace: /workspace/other-project family_revision: family-1 - SessionChangeRequest: - oneOf: - - $ref: '#/components/schemas/SessionPatch' - - $ref: '#/components/schemas/WorkspaceMoveRequest' NewSessionRequest: type: object properties: diff --git a/e2e/acp_daemon_test.py b/e2e/acp_daemon_test.py index 93b985f48..5d9a0f0b5 100644 --- a/e2e/acp_daemon_test.py +++ b/e2e/acp_daemon_test.py @@ -284,6 +284,12 @@ class AcpAttachmentTest(unittest.TestCase): ) with self.app.api(compaction, {}, method="PUT", headers=editor.headers()): pass + refused(self, lambda: self.app.api(compaction), 409, "acp_owned") + refused( + self, lambda: self.app.api(compaction, {}, method="PUT"), 409, "acp_owned" + ) + with self.app.api(compaction, headers=editor.headers()): + pass with self.app.api(f"/sessions/{session_id}/configuration") as response: etag = response.headers["ETag"] refused( diff --git a/e2e/compaction_receipts_test.py b/e2e/compaction_receipts_test.py index 95fe6263a..9b25dddb6 100644 --- a/e2e/compaction_receipts_test.py +++ b/e2e/compaction_receipts_test.py @@ -1,10 +1,13 @@ """Compaction identity survives response loss and daemon death without replay.""" import json +import sqlite3 +import time import threading import unittest import urllib.error +from inspect_support import Inspection from harness import Albedo, Provider, exclusive, operation_id, text @@ -33,8 +36,95 @@ class CompactionReceiptsTest(unittest.TestCase): json.load(response)["selection"]["extensions"]["rolling"] ) + @exclusive + def test_compaction_cap_deletion_and_expired_identity(self): + provider = Provider(lambda _: text("answer")) + self.addCleanup(provider.close) + with Albedo(provider) as app: + session = app.session() + action = operation_id() + route = f"/sessions/{session}/compactions/{action}" + intent = {"strategy": "rolling"} + # Occupy all slots without starting 64 provider calls. + with sqlite3.connect(app.home / "albedo.sqlite") as db: + db.executemany( + """ + INSERT INTO operations(id,fingerprint,kind,target,status,http_status,response,created_at) + VALUES(?,'fixture','compaction',?,'accepted',202,'{}',?) + """, + [ + (operation_id(), f"fixture-{index}", int(time.time() * 1000)) + for index in range(64) + ], + ) + with self.assertRaises(urllib.error.HTTPError) as full: + app.api(route, intent, method="PUT") + self.assertEqual(json.load(full.exception)["code"], "session_busy") + with sqlite3.connect(app.home / "albedo.sqlite") as db: + db.execute("DELETE FROM operations WHERE fingerprint='fixture'") + result = app.compact(session, intent, action_id=action) + with app.api(f"/sessions/{session}/configuration") as response: + etag = response.headers["etag"] + app.api( + f"/sessions/{session}", method="DELETE", headers={"If-Match": etag} + ).close() + for method in ("GET", "PUT"): + with app.api( + route, intent if method == "PUT" else None, method=method + ) as response: + self.assertEqual(json.load(response)["result"], result) + expired = operation_id(int(time.time() * 1000) - 8 * 86400000) + for method in ("GET", "PUT"): + with self.assertRaises(urllib.error.HTTPError) as gone: + app.api( + f"/sessions/{session}/compactions/{expired}", + intent if method == "PUT" else None, + method=method, + ) + self.assertEqual(json.load(gone.exception)["code"], "identity_expired") + + @exclusive + def test_terminal_write_recovers_after_storage_fault(self): + provider = Provider(lambda _: text("answer")) + self.addCleanup(provider.close) + with Albedo(provider) as app: + session = app.session() + action = operation_id() + route = f"/sessions/{session}/compactions/{action}" + with sqlite3.connect(app.home / "albedo.sqlite") as db: + db.execute(""" + CREATE TRIGGER fail_finish BEFORE UPDATE OF terminal_at ON operations + WHEN OLD.kind='compaction' AND NEW.terminal_at IS NOT NULL + BEGIN SELECT RAISE(FAIL,'terminal receipt unavailable'); END + """) + app.api(route, {"strategy": "rolling"}, method="PUT").close() + # Wait until selection has been applied and the actor has returned + # to idle. A same-ID PUT must still return the running receipt. + deadline = time.monotonic() + 15 + while True: + with app.api(f"/sessions/{session}/configuration") as response: + if json.load(response)["selection"]["extensions"].get("rolling"): + break + self.assertLess(time.monotonic(), deadline) + time.sleep(0.05) + app.idle(session) + with app.api(route) as response: + self.assertEqual(json.load(response)["state"], "running") + with sqlite3.connect(app.home / "albedo.sqlite") as db: + db.execute("DROP TRIGGER fail_finish") + result = app.compact(session, {"strategy": "rolling"}, action_id=action) + self.assertTrue(result["selection_applied"]) + self.assertEqual(result["state"], "failed") + @exclusive def test_crashed_compaction_is_interrupted_and_never_replayed(self): + self.check_interruption(owner_only=False) + + @exclusive + def test_owner_death_releases_admission_without_an_http_read(self): + self.check_interruption(owner_only=True) + + def check_interruption(self, *, owner_only): entered = threading.Event() release = threading.Event() compacting = threading.Event() @@ -51,7 +141,9 @@ class CompactionReceiptsTest(unittest.TestCase): provider = Provider(reply) self.addCleanup(provider.close) self.addCleanup(release.set) - with Albedo(provider) as app: + with Albedo( + provider, prepare=lambda app: app.env.update(ALBEDO_INSPECT="1") + ) as app: session = app.session() for prompt in ("older one", "older two", "newest"): app.prompt(session, prompt + " " + "x" * 6000).close() @@ -77,7 +169,24 @@ class CompactionReceiptsTest(unittest.TestCase): self.assertEqual(busy.exception.code, 409) busy.exception.close() count = len(calls) - app.restart(crash=True) + if owner_only: + probe = Inspection(app) + probe.evaluate( + f"""{{some, {{subject, Pid, _}}}} = Call('albedo@session', live, [<<"{session}">>]), """ + "true = Call(erlang, exit, [Pid, kill])" + ) + deadline = time.monotonic() + 10 + with sqlite3.connect(app.home / "albedo.sqlite") as db: + while ( + db.execute( + "SELECT terminal_at FROM operations WHERE id=?", (action,) + ).fetchone()[0] + is None + ): + self.assertLess(time.monotonic(), deadline) + time.sleep(0.05) + else: + app.restart(crash=True) release.set() with app.api(route) as response: interrupted = json.load(response) diff --git a/e2e/harness.py b/e2e/harness.py index 8a1a50b2f..12c83c0e4 100644 --- a/e2e/harness.py +++ b/e2e/harness.py @@ -1233,7 +1233,7 @@ class Albedo: if time.monotonic() >= deadline: self._fail(f"compaction did not settle: {receipt}") time.sleep(0.05) - with self.api(route) as response: + with self.api(route, headers=headers) as response: receipt = json.load(response) assert receipt["state"] == "completed", receipt return receipt["result"] diff --git a/web/scripts/session-configuration.test.mjs b/web/scripts/session-configuration.test.mjs index 3a8def81c..430ed23c5 100644 --- a/web/scripts/session-configuration.test.mjs +++ b/web/scripts/session-configuration.test.mjs @@ -43,10 +43,14 @@ test('a configuration save returns the confirmed embedded value', async (t) => { return Response.json({}, { headers: { etag: '"observed"' } }); }; assert.deepEqual( - await api.configureSession('session', { preferences: { pinned: true } }), - saved, + await api.configureSession( + 'session', + { preferences: { pinned: true } }, + '"observed"', + ), + { etag: '"saved"', value: saved }, ); - assert.deepEqual(requests, ['GET', 'PATCH']); + assert.deepEqual(requests, ['PATCH']); }); test('an observed stale edit is neither refreshed nor replayed', async (t) => { @@ -101,3 +105,38 @@ test('a lost compaction reply recovers the same identity and partial result', as ); assert.equal(calls[0].url, calls[1].url); }); + +test('overlapping compaction callers share admission and retain mismatched receipts for recovery', async (t) => { + const original = globalThis.fetch; + t.after(() => { + globalThis.fetch = original; + }); + const paths = []; + globalThis.fetch = async (url) => { + paths.push(url); + return Response.json({ + id: 'other', + session_id: 'overlap', + state: 'interrupted', + result: null, + }); + }; + const outcomes = await Promise.allSettled([ + api.compactSession('overlap'), + api.compactSession('overlap'), + ]); + assert.ok( + outcomes.every( + (result) => + result.status === 'rejected' && + result.reason.message.includes('Invalid compaction receipt'), + ), + ); + assert.equal(paths.length, 1); + globalThis.fetch = async (url) => { + assert.equal(url, paths[0]); + return Response.json({ code: 'identity_expired' }, { status: 409 }); + }; + await assert.rejects(api.compactSession('overlap'), /unknown outcome/); + await assert.rejects(api.compactSession('overlap'), /unknown outcome/); +}); diff --git a/web/src/lib/api.gen.d.ts b/web/src/lib/api.gen.d.ts index d6d381213..d3c0f5afd 100644 --- a/web/src/lib/api.gen.d.ts +++ b/web/src/lib/api.gen.d.ts @@ -3486,6 +3486,7 @@ export interface components { }; /** @description Session live fields and cursor are captured together. ACP attachment metadata is read separately. Extra response fields may be ignored. */ SessionSummary: { + configuration_etag?: components["schemas"]["ETag"]; id: components["schemas"]["ID"]; name: string; automatic_name: string; @@ -3742,7 +3743,6 @@ export interface components { workspace: components["schemas"]["Workspace"]; family_revision: components["schemas"]["ID"]; }; - SessionChangeRequest: components["schemas"]["SessionPatch"] | components["schemas"]["WorkspaceMoveRequest"]; /** * @example { * "kind": "new", @@ -12776,7 +12776,10 @@ export interface operations { getCompaction: { parameters: { query?: never; - header?: never; + header?: { + /** @description Required for kind acp creation and for input or scoped cancellation in an ACP session. Also authorizes compaction and scoped execution configuration patches by an ACP attachment holder. Ordinary creation ignores this header. Input, scoped cancellation, compaction for ACP sessions, and configuration patches parse and reject malformed supplied values. Not part of the durable intent. */ + "Albedo-Attachment-Token"?: components["parameters"]["AttachmentTokenOptional"]; + }; path: { session_id: components["schemas"]["ID"]; action_id: components["schemas"]["ID"]; @@ -12801,6 +12804,7 @@ export interface operations { 405: components["responses"]["Problem405"]; 406: components["responses"]["Problem406"]; 409: components["responses"]["Problem409"]; + 410: components["responses"]["Problem410"]; 413: components["responses"]["Problem413"]; 415: components["responses"]["Problem415"]; 503: components["responses"]["Problem503"]; @@ -12851,6 +12855,7 @@ export interface operations { 405: components["responses"]["Problem405"]; 406: components["responses"]["Problem406"]; 409: components["responses"]["Problem409"]; + 410: components["responses"]["Problem410"]; 413: components["responses"]["Problem413"]; 415: components["responses"]["Problem415"]; 503: components["responses"]["Problem503"]; diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 894543356..26be7b17a 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -21,7 +21,9 @@ function reportSettingsRevision(group: string, etag: string): void { export type Phase = components['schemas']['SessionStatus']['phase']; export type CompactionProgress = components['schemas']['CompactionProgress']; -export type Session = components['schemas']['SessionSummary']; +export type Session = components['schemas']['SessionSummary'] & { + configuration_resource?: components['schemas']['SessionConfigurationResource']; +}; export type PreferencePatch = components['schemas']['PreferencePatch']; export type SelectionPatch = components['schemas']['SelectionPatch']; export type CompactionResult = components['schemas']['CompactionResult']; @@ -168,7 +170,12 @@ export function getContextSummary( /** Compacts the session's model context now (optionally switching to `strategy` first). */ type CompactionReceipt = components['schemas']['CompactionReceipt']; -const pendingCompactions = new Map(); +interface PendingCompaction { + id: string; + strategy?: string; + observing?: Promise; +} +const pendingCompactions = new Map(); export function readCompaction( sessionId: string, @@ -186,34 +193,91 @@ export async function compactSession( throw new Error( `Resolve compaction ${action.id} before changing its intent.`, ); + const resumed = !!action; if (!action) { action = { id: uuidv7(), strategy }; pendingCompactions.set(sessionId, action); } - const url = `/sessions/${sessionId}/compactions/${action.id}`; - let receipt: CompactionReceipt; + if (action.observing) return action.observing; try { - receipt = await request('PUT', url, { - body: strategy ? { strategy } : {}, - }); + action.observing = observeCompaction(sessionId, action, resumed); + return await action.observing; } catch (error) { - if (error instanceof ApiError && error.status < 500) { - pendingCompactions.delete(sessionId); - throw error; + if (error instanceof ApiError && error.code === 'identity_expired') + throw new ApiError( + error.status, + error.code, + `Compaction ${action.id} expired with an unknown outcome. Inspect the session before reloading this page to start a new compaction.`, + ); + throw error; + } finally { + action.observing = undefined; + } +} + +async function observeCompaction( + sessionId: string, + action: PendingCompaction, + resumed: boolean, +): Promise { + const strategy = action.strategy; + const url = `/sessions/${sessionId}/compactions/${action.id}`; + async function submit(): Promise { + try { + return await request('PUT', url, { + body: strategy ? { strategy } : {}, + }); + } catch (error) { + if (error instanceof ApiError && error.status < 500) { + if (error.code !== 'identity_expired') + pendingCompactions.delete(sessionId); + throw error; + } + return readCompaction(sessionId, action.id); } - // A missing response does not authorize a fresh action identity. - receipt = await readCompaction(sessionId, action.id); } + let receipt: CompactionReceipt; + if (resumed) { + try { + receipt = await readCompaction(sessionId, action.id); + } catch (error) { + if (!( + error instanceof ApiError && + error.status === 404 && + error.code === 'compaction_unknown' + )) + throw error; + receipt = await submit(); + } + } else { + receipt = await submit(); + } + function validateReceipt(value: CompactionReceipt) { + if ( + value.id !== action.id || + value.session_id !== sessionId || + !['running', 'completed', 'interrupted'].includes(value.state) || + (value.state === 'completed') !== !!value.result + ) + throw new Error( + 'Invalid compaction receipt. Retry to resolve the same action.', + ); + } + validateReceipt(receipt); const deadline = Date.now() + 200_000; + let delay = 200; while (receipt.state === 'running') { if (Date.now() >= deadline) throw new Error( `Compaction ${action.id} is still unresolved. Retry to read the same action.`, ); - await new Promise((resolve) => setTimeout(resolve, 200)); + await new Promise((resolve) => setTimeout(resolve, delay)); + delay = Math.min(2000, delay * 2); receipt = await readCompaction(sessionId, action.id); + validateReceipt(receipt); } - pendingCompactions.delete(sessionId); + if (pendingCompactions.get(sessionId) === action) + pendingCompactions.delete(sessionId); if (receipt.state === 'interrupted' || !receipt.result) throw new Error( `Compaction ${action.id} was interrupted. Inspect context before starting another action.`, @@ -933,29 +997,25 @@ export type SessionConfigPatch = export async function configureSession( sessionId: string, change: SessionConfigPatch, - etag?: string, -): Promise { - return patchConfiguration(sessionId, change, etag); -} - -async function patchConfiguration( - sessionId: string, - change: SessionConfigPatch, - observedETag?: string, -): Promise { + etag: string, +) { + if (!etag) + throw new Error('Read the session before changing its configuration.'); const url = `/sessions/${sessionId}/configuration`; - let etag = observedETag; - if (etag === undefined) { - const response = await fetch(`/api${url}`, { - headers: { accept: 'application/json' }, - }); - if (!response.ok) throw await failure(response); - etag = response.headers.get('etag') ?? ''; + try { + const result = await request< + components['schemas']['SessionConfigurationChange'] + >('PATCH', url, { body: change, headers: { 'if-match': etag } }); + return result.resource; + } catch (error) { + if (error instanceof ApiError && error.status === 412) + throw new ApiError( + 412, + error.code, + 'Session configuration changed. Review the current values and choose again.', + ); + throw error; } - const result = await request< - components['schemas']['SessionConfigurationChange'] - >('PATCH', url, { body: change, headers: { 'if-match': etag } }); - return result.resource.value; } /** Moves a session to another folder, as the terminal's /cd does: on the same daemon, its kernel on that folder's host. */ diff --git a/web/src/lib/chat/ContextChip.svelte b/web/src/lib/chat/ContextChip.svelte index fa12fb33f..c3d5f85c1 100644 --- a/web/src/lib/chat/ContextChip.svelte +++ b/web/src/lib/chat/ContextChip.svelte @@ -1,4 +1,5 @@