From 63f258797396cb231ca5306a81908415f2abc8c9 Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Wed, 25 Nov 2026 16:14:38 -0500 Subject: [PATCH] feat(honcho): expose delivery status and recovery controls --- apps/albedo/manifest.toml | 2 +- apps/albedo/src/albedo/http/api_digest.gleam | 2 +- cli/internal/daemon/protocol/api.gen.go | 174 ++++++++++ cli/internal/daemon/protocol/digest.gen.go | 2 +- cli/internal/daemon/protocol/recovery.gen.go | 4 + docs/api-extension.gen.md | 12 + docs/openapi.yaml | 137 ++++++++ extensions/honcho/gleam.toml | 1 + extensions/honcho/manifest.toml | 1 + .../src/albedo_ext_honcho/delivery.gleam | 6 +- .../generated/sql/ledger_sql.gleam | 38 +++ .../honcho/src/albedo_ext_honcho/ledger.gleam | 52 ++- .../ledger/sql/advance_backfill.sql | 1 + .../albedo_ext_honcho/ledger/sql/backfill.sql | 1 + .../ledger/sql/count_pending.sql | 2 + .../src/albedo_ext_honcho/operator.gleam | 308 ++++++++++++++++++ robot-docs/honcho.md | 63 ++-- web/src/lib/api.gen.d.ts | 101 ++++++ 18 files changed, 873 insertions(+), 34 deletions(-) create mode 100644 extensions/honcho/src/albedo_ext_honcho/ledger/sql/advance_backfill.sql create mode 100644 extensions/honcho/src/albedo_ext_honcho/ledger/sql/backfill.sql create mode 100644 extensions/honcho/src/albedo_ext_honcho/ledger/sql/count_pending.sql create mode 100644 extensions/honcho/src/albedo_ext_honcho/operator.gleam diff --git a/apps/albedo/manifest.toml b/apps/albedo/manifest.toml index 3e6a2c1ca..dd4cbb21f 100644 --- a/apps/albedo/manifest.toml +++ b/apps/albedo/manifest.toml @@ -29,7 +29,7 @@ packages = [ { name = "albedo_ext_git", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_bytes", "albedo_sdk", "gleam_stdlib"], source = "local", path = "../../extensions/git" }, { name = "albedo_ext_github_copilot", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_anthropic", "albedo_bytes", "albedo_clock", "albedo_env", "albedo_file", "albedo_http", "albedo_model", "albedo_models_dev", "albedo_openai", "albedo_process", "albedo_sdk", "gleam_json", "gleam_stdlib"], source = "local", path = "../../extensions/github_copilot" }, { name = "albedo_ext_google_ai_studio", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_gemini", "albedo_http", "albedo_model", "albedo_models_dev", "albedo_openai", "albedo_sdk", "gleam_json", "gleam_stdlib"], source = "local", path = "../../extensions/google_ai_studio" }, - { name = "albedo_ext_honcho", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_bytes", "albedo_clock", "albedo_http", "albedo_process", "albedo_sdk", "albedo_sqlite", "gleam_erlang", "gleam_json", "gleam_otp", "gleam_stdlib", "sqlight"], source = "local", path = "../../extensions/honcho" }, + { name = "albedo_ext_honcho", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_bytes", "albedo_clock", "albedo_http", "albedo_process", "albedo_sdk", "albedo_sqlite", "gleam_erlang", "gleam_http", "gleam_json", "gleam_otp", "gleam_stdlib", "sqlight"], source = "local", path = "../../extensions/honcho" }, { name = "albedo_ext_hooks", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_file", "albedo_sdk", "gleam_json", "gleam_stdlib"], source = "local", path = "../../extensions/hooks" }, { name = "albedo_ext_imagegen", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_bytes", "albedo_model", "albedo_process", "albedo_protect", "albedo_sdk", "gleam_erlang", "gleam_json", "gleam_stdlib"], source = "local", path = "../../extensions/imagegen" }, { name = "albedo_ext_instructions", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_env", "albedo_sdk", "gleam_stdlib"], source = "local", path = "../../extensions/instructions" }, diff --git a/apps/albedo/src/albedo/http/api_digest.gleam b/apps/albedo/src/albedo/http/api_digest.gleam index 2f7168d25..f43ceeeda 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 = - "0cf000c7486970524c0a29cacf27cd80879d1b60eeab06d0f98ec0adcebc5a8a" + "3cc6cf0207c9b92b765aaa7d7401c526330180c43e310b91f6e45c4cc81552be" diff --git a/cli/internal/daemon/protocol/api.gen.go b/cli/internal/daemon/protocol/api.gen.go index 5dc55ccbb..05fac6a4b 100644 --- a/cli/internal/daemon/protocol/api.gen.go +++ b/cli/internal/daemon/protocol/api.gen.go @@ -1612,6 +1612,23 @@ type HistoryPage struct { // HistoryRead The requested view determines the item type. Empty pages are valid for either view. type HistoryRead = json.RawMessage +// HonchoSession defines model for HonchoSession. +type HonchoSession struct { + Page PageDescriptor `json:"page"` + Status struct { + AssistantPeer *string `json:"assistant_peer" nullable:"true"` + Endpoint *string `json:"endpoint" nullable:"true"` + Enrolled bool `json:"enrolled"` + HumanPeer *string `json:"human_peer" nullable:"true"` + LastDeliveryMs *int64 `json:"last_delivery_ms" nullable:"true"` + NextAttemptMs *int64 `json:"next_attempt_ms" nullable:"true"` + Paused string `json:"paused"` + Pending Counter `json:"pending"` + RemoteSession *string `json:"remote_session" nullable:"true"` + Workspace *string `json:"workspace" nullable:"true"` + } `json:"status"` +} + // Hook defines model for Hook. type Hook struct { ConfigurationResource HookConfigurationResource `json:"configuration_resource"` @@ -4910,6 +4927,11 @@ type DeleteDiscordBotParams struct { Revision int64 `form:"revision" json:"revision"` } +// ChangeHonchoSessionJSONBody defines parameters for ChangeHonchoSession. +type ChangeHonchoSessionJSONBody struct { + Action string `json:"action"` +} + // UnlinkWorkspaceParams defines parameters for UnlinkWorkspace. type UnlinkWorkspaceParams struct { Workspace Workspace `form:"workspace" json:"workspace"` @@ -5540,6 +5562,9 @@ type PutDiscordChannelJSONRequestBody = DiscordChannelSetting // PutDiscordDMJSONRequestBody defines body for PutDiscordDM for application/json ContentType. type PutDiscordDMJSONRequestBody = DiscordAllow +// ChangeHonchoSessionJSONRequestBody defines body for ChangeHonchoSession for application/json ContentType. +type ChangeHonchoSessionJSONRequestBody ChangeHonchoSessionJSONBody + // MergeLinkGroupsJSONRequestBody defines body for MergeLinkGroups for application/json ContentType. type MergeLinkGroupsJSONRequestBody = LinkMerge @@ -6109,6 +6134,25 @@ type ClientInterface interface { // Corresponds with DELETE /extensions/discord/bots/{bot_id}/requests/{user_id} (the `DeleteDiscordRequest` operationId). DeleteDiscordRequest(ctx context.Context, botID ID, userID ID, reqEditors ...RequestEditorFn) (*http.Response, error) + // ReadHonchoSession Read Honcho enrollment and delivery status + // + // Corresponds with GET /extensions/honcho/sessions/{session_id} (the `ReadHonchoSession` operationId). + ReadHonchoSession(ctx context.Context, sessionID ID, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ChangeHonchoSessionWithBody Change Honcho delivery for this session + // + // Takes any type of body and a specified content type. + // + // Corresponds with POST /extensions/honcho/sessions/{session_id} (the `ChangeHonchoSession` operationId). + ChangeHonchoSessionWithBody(ctx context.Context, sessionID ID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ChangeHonchoSession Change Honcho delivery for this session + // + // Takes a body of the `application/json` content type. + // + // Corresponds with POST /extensions/honcho/sessions/{session_id} (the `ChangeHonchoSession` operationId). + ChangeHonchoSession(ctx context.Context, sessionID ID, body ChangeHonchoSessionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + // UnlinkWorkspace Remove a member from the observed group // // Check membership at commit. Creates a singleton group; deletes no work or memory. Human-only. @@ -8359,6 +8403,55 @@ func (c *Client) DeleteDiscordRequest(ctx context.Context, botID ID, userID ID, return c.Client.Do(req) } +// ReadHonchoSession Read Honcho enrollment and delivery status +// +// Corresponds with GET /extensions/honcho/sessions/{session_id} (the `ReadHonchoSession` operationId). +func (c *Client) ReadHonchoSession(ctx context.Context, sessionID ID, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewReadHonchoSessionRequest(c.Server, sessionID) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// ChangeHonchoSessionWithBody Change Honcho delivery for this session +// +// Takes any type of body and a specified content type. +// +// Corresponds with POST /extensions/honcho/sessions/{session_id} (the `ChangeHonchoSession` operationId). +func (c *Client) ChangeHonchoSessionWithBody(ctx context.Context, sessionID ID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewChangeHonchoSessionRequestWithBody(c.Server, sessionID, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// ChangeHonchoSession Change Honcho delivery for this session +// +// Takes a body of the `application/json` content type. +// +// Corresponds with POST /extensions/honcho/sessions/{session_id} (the `ChangeHonchoSession` operationId). +func (c *Client) ChangeHonchoSession(ctx context.Context, sessionID ID, body ChangeHonchoSessionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewChangeHonchoSessionRequest(c.Server, sessionID, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + // UnlinkWorkspace Remove a member from the observed group // // Check membership at commit. Creates a singleton group; deletes no work or memory. Human-only. @@ -13167,6 +13260,87 @@ func NewDeleteDiscordRequestRequest(server string, botID ID, userID ID) (*http.R return req, nil } +// NewReadHonchoSessionRequest constructs an http.Request for the ReadHonchoSession method +func NewReadHonchoSessionRequest(server string, sessionID ID) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "session_id", sessionID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/extensions/honcho/sessions/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewChangeHonchoSessionRequest calls the generic ChangeHonchoSession builder with application/json body +func NewChangeHonchoSessionRequest(server string, sessionID ID, body ChangeHonchoSessionJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewChangeHonchoSessionRequestWithBody(server, sessionID, "application/json", bodyReader) +} + +// NewChangeHonchoSessionRequestWithBody constructs an http.Request for the ChangeHonchoSession method, with any body, and a specified content type +func NewChangeHonchoSessionRequestWithBody(server string, sessionID ID, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "session_id", sessionID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/extensions/honcho/sessions/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + // NewUnlinkWorkspaceRequest constructs an http.Request for the UnlinkWorkspace method func NewUnlinkWorkspaceRequest(server string, params *UnlinkWorkspaceParams) (*http.Request, error) { var err error diff --git a/cli/internal/daemon/protocol/digest.gen.go b/cli/internal/daemon/protocol/digest.gen.go index 8ffc5cbc3..d5cae88ef 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 = "0cf000c7486970524c0a29cacf27cd80879d1b60eeab06d0f98ec0adcebc5a8a" +const APIDigest = "3cc6cf0207c9b92b765aaa7d7401c526330180c43e310b91f6e45c4cc81552be" diff --git a/cli/internal/daemon/protocol/recovery.gen.go b/cli/internal/daemon/protocol/recovery.gen.go index b5c21713c..7720c9d14 100644 --- a/cli/internal/daemon/protocol/recovery.gen.go +++ b/cli/internal/daemon/protocol/recovery.gen.go @@ -69,6 +69,10 @@ func OperationRecovery(operation string) RecoveryPolicy { return RecoveryPolicy("safe-read") case "deleteDiscordRequest": return RecoveryPolicy("no-automatic-replay") + case "readHonchoSession": + return RecoveryPolicy("safe-read") + case "changeHonchoSession": + return RecoveryPolicy("no-automatic-replay") case "getLinkGroup": return RecoveryPolicy("safe-read") case "mergeLinkGroups": diff --git a/docs/api-extension.gen.md b/docs/api-extension.gen.md index a3628d7a2..d4e43c27e 100644 --- a/docs/api-extension.gen.md +++ b/docs/api-extension.gen.md @@ -120,6 +120,18 @@ Recovery: `safe-read`. Recovery: `no-automatic-replay`. +## readHonchoSession + +`GET /extensions/honcho/sessions/{session_id}` + +Recovery: `safe-read`. + +## changeHonchoSession + +`POST /extensions/honcho/sessions/{session_id}` + +Recovery: `no-automatic-replay`. + ## getLinkGroup `GET /extensions/links/groups` diff --git a/docs/openapi.yaml b/docs/openapi.yaml index b164f73e6..36002be70 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -6264,6 +6264,89 @@ paths: - $ref: '#/components/parameters/IfMatch' x-albedo-audience: extension x-albedo-recovery: no-automatic-replay + /extensions/honcho/sessions/{session_id}: + get: + operationId: readHonchoSession + summary: Read Honcho enrollment and delivery status + parameters: + - name: session_id + in: path + required: true + schema: + $ref: '#/components/schemas/ID' + responses: + '200': + description: Delivery status and operator actions. + content: + application/json: + schema: + $ref: '#/components/schemas/HonchoSession' + '400': + $ref: '#/components/responses/Problem400' + '401': + $ref: '#/components/responses/Problem401' + '404': + $ref: '#/components/responses/Problem404' + '405': + $ref: '#/components/responses/Problem405' + '406': + $ref: '#/components/responses/Problem406' + '413': + $ref: '#/components/responses/Problem413' + '415': + $ref: '#/components/responses/Problem415' + '503': + $ref: '#/components/responses/Problem503' + x-albedo-audience: extension + x-albedo-recovery: safe-read + post: + operationId: changeHonchoSession + summary: Change Honcho delivery for this session + parameters: + - name: session_id + in: path + required: true + schema: + $ref: '#/components/schemas/ID' + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + action: + type: string + enum: [bind, backfill, retry, resend] + required: [action] + additionalProperties: false + responses: + '200': + description: Delivery status and operator actions. + content: + application/json: + schema: + $ref: '#/components/schemas/HonchoSession' + '400': + $ref: '#/components/responses/Problem400' + '401': + $ref: '#/components/responses/Problem401' + '404': + $ref: '#/components/responses/Problem404' + '405': + $ref: '#/components/responses/Problem405' + '406': + $ref: '#/components/responses/Problem406' + '409': + $ref: '#/components/responses/Problem409' + '413': + $ref: '#/components/responses/Problem413' + '415': + $ref: '#/components/responses/Problem415' + '503': + $ref: '#/components/responses/Problem503' + x-albedo-audience: extension + x-albedo-recovery: no-automatic-replay /extensions/links/groups: get: operationId: getLinkGroup @@ -12936,6 +13019,60 @@ components: availability, ] additionalProperties: false + HonchoSession: + type: object + properties: + status: + type: object + properties: + enrolled: + type: boolean + pending: + $ref: '#/components/schemas/Counter' + endpoint: + type: [string, 'null'] + maxLength: 4096 + human_peer: + type: [string, 'null'] + maxLength: 4096 + assistant_peer: + type: [string, 'null'] + maxLength: 4096 + workspace: + type: [string, 'null'] + maxLength: 4096 + remote_session: + type: [string, 'null'] + maxLength: 4096 + next_attempt_ms: + type: [integer, 'null'] + minimum: 0 + maximum: 9007199254740991 + last_delivery_ms: + type: [integer, 'null'] + minimum: 0 + maximum: 9007199254740991 + paused: + type: string + maxLength: 4096 + required: + [ + enrolled, + pending, + endpoint, + human_peer, + assistant_peer, + next_attempt_ms, + workspace, + remote_session, + last_delivery_ms, + paused, + ] + additionalProperties: false + page: + $ref: '#/components/schemas/PageDescriptor' + required: [status, page] + additionalProperties: false QueueCollection: type: object properties: diff --git a/extensions/honcho/gleam.toml b/extensions/honcho/gleam.toml index 48441b8df..7a12dc3e8 100644 --- a/extensions/honcho/gleam.toml +++ b/extensions/honcho/gleam.toml @@ -7,6 +7,7 @@ gleam = ">= 1.19.0" target = "erlang" [dependencies] +gleam_http = ">= 4.4.0 and < 5.0.0" albedo_sqlite = { path = "../../packages/albedo_sqlite" } gleam_stdlib = ">= 1.0.0 and < 2.0.0" gleam_erlang = ">= 1.3.0 and < 2.0.0" diff --git a/extensions/honcho/manifest.toml b/extensions/honcho/manifest.toml index d7b5da1fe..0cc3eb2e7 100644 --- a/extensions/honcho/manifest.toml +++ b/extensions/honcho/manifest.toml @@ -52,6 +52,7 @@ albedo_process = { path = "../../packages/albedo_process" } albedo_sdk = { path = "../../packages/albedo_sdk" } albedo_sqlite = { path = "../../packages/albedo_sqlite" } gleam_erlang = { version = ">= 1.3.0 and < 2.0.0" } +gleam_http = { version = ">= 4.4.0 and < 5.0.0" } gleam_json = { version = ">= 3.1.0 and < 4.0.0" } gleam_otp = { version = ">= 1.3.0 and < 2.0.0" } gleam_stdlib = { version = ">= 1.0.0 and < 2.0.0" } diff --git a/extensions/honcho/src/albedo_ext_honcho/delivery.gleam b/extensions/honcho/src/albedo_ext_honcho/delivery.gleam index e8063093c..785d838e8 100644 --- a/extensions/honcho/src/albedo_ext_honcho/delivery.gleam +++ b/extensions/honcho/src/albedo_ext_honcho/delivery.gleam @@ -2,6 +2,7 @@ //// history and starts without a delivery grant on the receiving daemon. import albedo_ext_honcho/ledger +import albedo_ext_honcho/operator import albedo_ext_honcho/transfer import albedo_ext_honcho/worker import albedo_sdk/extension @@ -21,6 +22,8 @@ pub fn initialise(db: storage.Storage) -> Result(Nil, String) { pub fn plugins() -> List(extension.Plugin) { [ + operator.commands(), + operator.clients(), extension.StartupPlugin(start), extension.CleanPlugin(ledger.forget), extension.FollowPlugin(ledger.follow), @@ -47,6 +50,7 @@ fn start(host: extension.Startup) -> Result(List(extension.Started), String) { ), ) [ + operator.service(manager), extension.StartedManaged(fn(prep) { let opening = ledger.opening(prep.storage, prep.session) let session = prep.session @@ -60,7 +64,7 @@ fn start(host: extension.Startup) -> Result(List(extension.Started), String) { let published = case opening { Ok(o) -> Some(fn(db) { - use _ <- result.map(ledger.bind(db, session, o)) + use _ <- result.map(ledger.bind(db, session, o, False)) worker.send(manager, worker.Wake(session)) }) Error(_) -> None diff --git a/extensions/honcho/src/albedo_ext_honcho/generated/sql/ledger_sql.gleam b/extensions/honcho/src/albedo_ext_honcho/generated/sql/ledger_sql.gleam index 44a90d7c9..1e303af8a 100644 --- a/extensions/honcho/src/albedo_ext_honcho/generated/sql/ledger_sql.gleam +++ b/extensions/honcho/src/albedo_ext_honcho/generated/sql/ledger_sql.gleam @@ -17,6 +17,19 @@ pub fn advance( ) } +/// Generated from src/albedo_ext_honcho/ledger/sql/advance_backfill.sql +pub fn advance_backfill( + db db: sqlight.Connection, + through through: Int, + session session: String, +) -> Result(Nil, String) { + albedo_sqlite.run( + "UPDATE honcho_bindings SET backfill_cursor=@through WHERE session=@session", + on: db, + with: [sqlight.int(through), sqlight.text(session)], + ) +} + /// Generated from src/albedo_ext_honcho/ledger/sql/attempt.sql pub fn attempt( db db: sqlight.Connection, @@ -31,6 +44,18 @@ pub fn attempt( ) } +/// Generated from src/albedo_ext_honcho/ledger/sql/backfill.sql +pub fn backfill( + db db: sqlight.Connection, + session session: String, +) -> Result(Nil, String) { + albedo_sqlite.run( + "UPDATE honcho_bindings SET backfill_cursor=floor_seq WHERE session=@session AND backfill_cursor=-1", + on: db, + with: [sqlight.text(session)], + ) +} + /// Generated from src/albedo_ext_honcho/ledger/sql/bind.sql pub fn bind( db db: sqlight.Connection, @@ -180,6 +205,19 @@ pub fn clear_outbox( ) } +/// Generated from src/albedo_ext_honcho/ledger/sql/count_pending.sql +pub fn count_pending( + db db: sqlight.Connection, + session session: String, +) -> Result(List(Int), String) { + albedo_sqlite.rows( + "SELECT COUNT(*) AS pending FROM honcho_outbox WHERE session=@session", + on: db, + with: [sqlight.text(session)], + expecting: decode.field(0, decode.int, decode.success), + ) +} + /// Generated from src/albedo_ext_honcho/ledger/sql/defer.sql pub fn defer( db db: sqlight.Connection, diff --git a/extensions/honcho/src/albedo_ext_honcho/ledger.gleam b/extensions/honcho/src/albedo_ext_honcho/ledger.gleam index 5bd0fa4d6..f07e2c08b 100644 --- a/extensions/honcho/src/albedo_ext_honcho/ledger.gleam +++ b/extensions/honcho/src/albedo_ext_honcho/ledger.gleam @@ -13,6 +13,7 @@ import albedo_sdk/selection import albedo_sdk/session_info import albedo_sdk/sessions import albedo_sdk/storage +import albedo_sdk/transcript import albedo_sqlite import gleam/bool import gleam/int @@ -114,9 +115,13 @@ pub fn bind( db: storage.Storage, session: String, opening: Opening, + explicit: Bool, ) -> Result(Nil, String) { use now <- result.try(config.load()) - use <- bool.guard(now != opening.dest, Error("Honcho destination changed")) + use <- bool.guard( + now != opening.dest, + Error("Honcho destination changed; use /honcho bind"), + ) use conn <- storage.writing(db) use <- storage.transaction(conn) use _ <- result.try(standing(db, conn, session)) @@ -130,11 +135,12 @@ pub fn bind( ) case old { Some(row) if row.grant_token == opening.token -> - case dest(row) == now { - True -> Ok(Nil) - False -> Error("Honcho destination changed") + case dest(row) == now, explicit { + True, _ -> Ok(Nil) + False, False -> Error("Honcho destination changed; use /honcho bind") + False, True -> insert(conn, session, opening, old, explicit) } - _ -> insert(conn, session, opening, old) + _ -> insert(conn, session, opening, old, explicit) } } @@ -143,16 +149,18 @@ fn insert( session: String, opening: Opening, old: Option(sql.BindingRow), + explicit: Bool, ) -> Result(Nil, String) { use boundary <- result.try( sql.boundary(conn, session) |> albedo_sqlite.optional_first, ) use <- bool.guard( - option.map(boundary, fn(b) { b.require_bind }) == Some(1), - Error("Delivery is disabled for imported sessions"), + !explicit && option.map(boundary, fn(b) { b.require_bind }) == Some(1), + Error("Use /honcho bind to enroll this imported session"), ) let floor = case old, boundary { Some(_), _ -> opening.upper + _, Some(b) if b.require_bind == 1 -> opening.upper _, Some(b) -> b.floor_seq _, None -> 0 } @@ -211,7 +219,7 @@ fn inspect_in( use grant <- result.map(selection.grant_in(db, conn, session)) case grant == Some(row.grant_token), dest(row) == config { False, _ -> Inactive("Honcho session enrollment was revoked") - _, False -> Inactive("Honcho destination changed") + _, False -> Inactive("Honcho destination changed; use /honcho bind") True, True -> Active(row) } } @@ -251,8 +259,19 @@ pub fn capture( row: sql.BindingRow, ) -> Result(Bool, String) { use snapshot <- result.try(history.snapshot(db, row.session)) - use <- bool.guard(row.cursor >= snapshot.upper, Ok(False)) - use page <- result.try(history.conversation_page(db, snapshot, row.cursor, 32)) + let historical = + row.backfill_cursor >= 0 && row.backfill_cursor < row.start_seq + let #(after, upper) = case historical { + True -> #(row.backfill_cursor, int.min(row.start_seq, snapshot.upper)) + False -> #(row.cursor, snapshot.upper) + } + use <- bool.guard(!historical && after >= upper, Ok(False)) + use page <- result.try(history.conversation_page( + db, + transcript.Snapshot(..snapshot, upper:), + after, + 32, + )) let messages = list.map(page.messages, fn(m) { #(m, scalars.chunks(m.text, 25_000)) }) use d <- result.try(config.load()) @@ -285,6 +304,17 @@ pub fn capture( |> result.replace(Nil) }), ) - use _ <- result.try(sql.advance(conn, page.through, row.session)) + use _ <- result.try(case historical { + True -> + sql.advance_backfill( + conn, + case page.through >= upper { + True -> row.start_seq + False -> page.through + }, + row.session, + ) + False -> sql.advance(conn, page.through, row.session) + }) Ok(True) } diff --git a/extensions/honcho/src/albedo_ext_honcho/ledger/sql/advance_backfill.sql b/extensions/honcho/src/albedo_ext_honcho/ledger/sql/advance_backfill.sql new file mode 100644 index 000000000..65eb79849 --- /dev/null +++ b/extensions/honcho/src/albedo_ext_honcho/ledger/sql/advance_backfill.sql @@ -0,0 +1 @@ +UPDATE honcho_bindings SET backfill_cursor=@through WHERE session=@session diff --git a/extensions/honcho/src/albedo_ext_honcho/ledger/sql/backfill.sql b/extensions/honcho/src/albedo_ext_honcho/ledger/sql/backfill.sql new file mode 100644 index 000000000..32671d0a8 --- /dev/null +++ b/extensions/honcho/src/albedo_ext_honcho/ledger/sql/backfill.sql @@ -0,0 +1 @@ +UPDATE honcho_bindings SET backfill_cursor=floor_seq WHERE session=@session AND backfill_cursor=-1 diff --git a/extensions/honcho/src/albedo_ext_honcho/ledger/sql/count_pending.sql b/extensions/honcho/src/albedo_ext_honcho/ledger/sql/count_pending.sql new file mode 100644 index 000000000..5f9c649aa --- /dev/null +++ b/extensions/honcho/src/albedo_ext_honcho/ledger/sql/count_pending.sql @@ -0,0 +1,2 @@ +-- albedo: columns pending:INTEGER +SELECT COUNT(*) AS pending FROM honcho_outbox WHERE session=@session diff --git a/extensions/honcho/src/albedo_ext_honcho/operator.gleam b/extensions/honcho/src/albedo_ext_honcho/operator.gleam new file mode 100644 index 000000000..7468ac383 --- /dev/null +++ b/extensions/honcho/src/albedo_ext_honcho/operator.gleam @@ -0,0 +1,308 @@ +//// The session's Honcho controls and their declarative slash-command page. + +import albedo_clock +import albedo_ext_honcho/config +import albedo_ext_honcho/generated/sql/ledger_sql as sql +import albedo_ext_honcho/ledger +import albedo_ext_honcho/worker +import albedo_sdk/client_api as client +import albedo_sdk/command +import albedo_sdk/extension +import albedo_sdk/http_api as api +import albedo_sdk/service +import albedo_sdk/sessions +import albedo_sdk/storage +import albedo_sqlite +import gleam/bool +import gleam/dynamic/decode +import gleam/http +import gleam/int +import gleam/json +import gleam/list +import gleam/option.{None, Some} +import gleam/result + +const path = "/extensions/honcho/sessions/{session_id}" + +const actions = ["bind", "backfill", "retry", "resend"] + +pub fn commands() -> extension.Plugin { + extension.CommandPlugin([ + command.resource( + "/honcho", + "Inspect or change this session's Honcho enrollment and delivery.", + [command.Argument("action", "Session operation", False, actions)], + ), + ]) +} + +fn operation(method: http.Method, binding: client.Binding) -> client.Operation { + let name = case method { + http.Get -> "readHonchoSession" + _ -> "changeHonchoSession" + } + client.Operation(..client.operation_defaults(name, method, path, 200), path: [ + #("session_id", binding), + ]) +} + +pub fn clients() -> extension.Plugin { + let session = client.Session("/id") + extension.ClientPlugin([ + client.Command("/honcho", client.Read, [], operation(http.Get, session)), + client.Command( + "/honcho", + client.Mutation, + [client.choice_field("action", True, actions)], + client.Operation(..operation(http.Post, session), body: [ + #("/action", client.Form("/action")), + ]), + ), + ]) +} + +pub fn service(manager: worker.Manager) -> extension.Started { + extension.StartedService( + service.json(4096, fn(daemon, parts, req) { + use _ <- result.try(api.parameters(req, [])) + use session <- result.try(case parts { + ["sessions", id] -> Ok(id) + _ -> Error(api.Failure(404, "not_found", "Unknown Honcho resource")) + }) + use found <- result.try( + sessions.find(daemon.storage, session) + |> result.map_error(api.Failure(503, "storage_unavailable", _)), + ) + use <- bool.guard( + found == None, + Error(api.Failure(404, "not_found", "Unknown session")), + ) + use _ <- result.try(case req.method { + http.Get -> api.empty_body(req) + http.Post -> { + use action <- result.try(api.body( + req, + ["action"], + decode.field("action", decode.string, decode.success), + )) + use <- bool.guard( + !list.contains(actions, action), + Error(api.Failure(400, "invalid_action", "Unknown Honcho action")), + ) + change(manager, daemon.storage, session, action) + |> result.map_error(api.Failure(409, "honcho_conflict", _)) + } + _ -> Error(api.Failure(405, "method_not_allowed", "Use GET or POST")) + }) + status(daemon.storage, session) + |> result.map(api.reply(200, _)) + |> result.map_error(api.Failure(503, "storage_unavailable", _)) + }), + ) +} + +fn change( + manager: worker.Manager, + db: storage.Storage, + session: String, + action: String, +) -> Result(Nil, String) { + use _ <- result.try(case action { + "bind" -> { + use o <- result.try(ledger.opening(db, session)) + ledger.bind(db, session, o, True) + } + "backfill" | "retry" | "resend" -> { + use d <- result.try(config.load()) + use conn <- storage.writing(db) + use <- storage.transaction(conn) + use row <- result.try(ledger.current_in(db, conn, session, d)) + case action { + "backfill" -> sql.backfill(conn, session) + "retry" -> sql.unblock(conn, session) + _ -> + case row.blocked { + "" -> Ok(Nil) + _ -> { + use pending <- result.try( + sql.pending(conn, session) |> albedo_sqlite.optional_first, + ) + use _ <- result.try(case pending { + Some(p) -> sql.attempt(conn, 0, session, p.source_key) + None -> Ok(Nil) + }) + sql.unblock(conn, session) + } + } + } + } + _ -> Error("Expected status, bind, backfill, retry, or resend") + }) + worker.send(manager, worker.Wake(session)) + Ok(Nil) +} + +fn status(db: storage.Storage, session: String) -> Result(json.Json, String) { + use inspection <- result.try(ledger.inspection(db, session)) + use conn <- storage.reading(db) + use pending <- result.try( + sql.count_pending(conn, session) |> albedo_sqlite.first("No pending count"), + ) + use row <- result.try( + sql.binding(conn, session) |> albedo_sqlite.optional_first, + ) + let #(enrolled, reason) = case inspection { + ledger.Active(_) -> #(True, "") + ledger.Inactive(reason) -> #(False, reason) + } + let paused = case reason, row { + "", Some(b) -> b.blocked + _, _ -> reason + } + let details = + json.object([ + #("enrolled", json.bool(enrolled)), + #("pending", json.int(pending)), + #( + "endpoint", + json.nullable(option.map(row, fn(b) { b.endpoint }), json.string), + ), + #( + "human_peer", + json.nullable(option.map(row, fn(b) { b.human }), json.string), + ), + #( + "assistant_peer", + json.nullable(option.map(row, fn(b) { b.assistant }), json.string), + ), + #( + "next_attempt_ms", + json.nullable( + option.then(row, fn(b) { + case b.next_attempt { + 0 -> None + t -> Some(t) + } + }), + json.int, + ), + ), + #( + "workspace", + json.nullable(option.map(row, fn(b) { b.workspace }), json.string), + ), + #( + "remote_session", + json.nullable(option.map(row, fn(b) { b.remote }), json.string), + ), + #( + "last_delivery_ms", + json.nullable( + option.then(row, fn(b) { + case b.last_delivery { + 0 -> None + t -> Some(t) + } + }), + json.int, + ), + ), + #("paused", json.string(paused)), + ]) + let binding = client.Literal(json.string(session)) + use controls <- result.map( + client.actions( + list.map(actions, fn(action) { + let confirmation = case action { + "resend" -> + Some( + "Resend the pending message? Honcho may already have received it.", + ) + "backfill" -> + Some("Send earlier eligible messages in this session to Honcho?") + _ -> None + } + client.Action( + action, + action, + "", + confirmation, + [], + client.Operation(..operation(http.Post, binding), body: [ + #("/action", client.Literal(json.string(action))), + ]), + ) + }), + ), + ) + let summary = + case enrolled { + True -> "Enrolled" + False -> "Not enrolled" + } + <> " ยท " + <> int.to_string(pending) + <> " pending" + let rows = case row { + None -> [] + Some(b) -> + [ + Some(client.PageRow( + "destination", + "Workspace: " <> b.workspace, + None, + "plain", + Some("Endpoint: " <> b.endpoint), + json.null(), + )), + Some(status_row("remote", "Remote session", b.remote)), + Some(status_row("peers", "Peers", b.human <> " / " <> b.assistant)), + timestamp_row("delivered", "Last delivery", b.last_delivery), + timestamp_row("retry", "Next attempt", b.next_attempt), + ] + |> list.filter_map(option.to_result(_, Nil)) + } + let rows = case paused { + "" -> rows + _ -> [ + client.PageRow( + "paused", + "Delivery paused", + None, + "warning", + Some(paused), + json.null(), + ), + ..rows + ] + } + json.object([ + #("status", details), + #( + "page", + client.page(client.Page( + "Honcho", + summary, + "No destination bound", + None, + controls, + rows, + )), + ), + ]) +} + +fn status_row(id: String, title: String, value: String) -> client.PageRow { + client.PageRow(id, title <> ": " <> value, None, "plain", None, json.null()) +} + +fn timestamp_row( + id: String, + title: String, + value: Int, +) -> option.Option(client.PageRow) { + case value { + 0 -> None + _ -> Some(status_row(id, title, albedo_clock.format_rfc3339(value))) + } +} diff --git a/robot-docs/honcho.md b/robot-docs/honcho.md index 9a85d3812..031385ff4 100644 --- a/robot-docs/honcho.md +++ b/robot-docs/honcho.md @@ -28,33 +28,58 @@ the key when making a request. The owns field validation. See [settings](settings.md) for daemon settings and credentials. +Older ordinary chat and skill submissions lack a separately saved original text. +Backfill skips these human messages. It can still send their assistant replies. + ## Enroll a session -Configure the destination, choose Honcho explicitly in the session's extension -selection, and reload the session to allow export. When that composition enters -service, Albedo binds a remote session and records the current end of the -transcript. Subsequent committed human and assistant messages are eligible for -delivery. Reverting the session to inherited selection or disabling Honcho -revokes enrollment. Re-enabling starts at the new transcript boundary. +Set `enabled.honcho` to `true` as shown above and restart the daemon to mount +the operator service. Choose Honcho explicitly in the session's extension +selection and reload the session to allow export. When the selected composition +enters service, the +[delivery extension](../extensions/honcho/src/albedo_ext_honcho/delivery.gleam) +binds a new remote session and records the current end of the transcript. +Opening a tool menu or preparing a candidate that the runtime rejects cannot +enroll a session. Reload after configuring a destination if the session was +already running. + +Open the `/honcho` page to choose an action, or specify it directly, for example +`/honcho backfill`. The +[operator service](../extensions/honcho/src/albedo_ext_honcho/operator.gleam) +serves `GET /extensions/honcho/sessions/{session_id}` and accepts `POST` on that +path with an `action` field. The page shows the binding, pending message count, +last delivery, next retry, and any reason delivery paused. Disabling the +extension or returning its session choice to inheritance revokes the local +grant. Requests already sent can still complete. Re-enabling starts from the new +transcript boundary and drops any old pending deliveries. A destination change +pauses capture until you run `/honcho bind`. Binding the new destination starts +a fresh remote session. ## Delivery and recovery The [worker](../extensions/honcho/src/albedo_ext_honcho/worker.gleam) wakes at turn start, turn end, and daemon startup. It reads committed conversation text -in pages and saves each eligible message and its scan position in one +in pages, then saves each eligible message and its scan position in one transaction. Each part carries its original timestamp when known and a source -key for receipt lookup. Long messages split at 25,000 Unicode scalars. - -A temporary failure schedules another attempt. If a connection breaks during -delivery, the worker searches Honcho for a receipt with the same source key. -Delivery waits until the receipt appears. A destination change pauses delivery. -To start at a new destination, disable Honcho for the session, reload it, then -explicitly enable it and reload again. - -A fork starts a fresh remote session. Rewinding drops unsent parts beyond the -retained position. Deletion removes the local binding and queued data. Moving a -session stops the source daemon's delivery and leaves the imported session -unenrolled. +key for receipt lookup. Long messages split at 25,000 Unicode scalars. A worker +handles one part at a time. It waits outside the database while contacting +Honcho. + +A definite temporary failure schedules another attempt. If a connection breaks +while a message is being sent, the worker searches Honcho for a receipt with the +same source key. Missing receipts are checked again. Use `/honcho retry` after +fixing a configuration or credentials error to resume delivery or check a +receipt. Use `/honcho resend` only when you intend to authorize a new send of +the paused part: the original may still arrive. + +`/honcho backfill` includes the transcript before initial enrollment. The +backfill has its own durable cursor. Repeating the command resumes the same +interval. A fork omits the prefix copied from its source, including during +backfill. Rewinding drops unsent parts beyond the retained position. Previously +transmitted data remains in Honcho. Local deletion removes the binding and its +queued data. Moving a session leaves its binding with the source daemon, which +stops sending to it. Run `/honcho bind` on the target to enroll the moved +session from its current position. ## Related pages diff --git a/web/src/lib/api.gen.d.ts b/web/src/lib/api.gen.d.ts index 3a0bc1b14..7d3896dbc 100644 --- a/web/src/lib/api.gen.d.ts +++ b/web/src/lib/api.gen.d.ts @@ -1746,6 +1746,24 @@ export interface paths { patch: operations["patchSchedule"]; trace?: never; }; + "/extensions/honcho/sessions/{session_id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Read Honcho enrollment and delivery status */ + get: operations["readHonchoSession"]; + put?: never; + /** Change Honcho delivery for this session */ + post: operations["changeHonchoSession"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/extensions/links/groups": { parameters: { query?: never; @@ -3970,6 +3988,21 @@ export interface components { [key: string]: boolean; }; }; + HonchoSession: { + status: { + enrolled: boolean; + pending: components["schemas"]["Counter"]; + endpoint: string | null; + human_peer: string | null; + assistant_peer: string | null; + workspace: string | null; + remote_session: string | null; + next_attempt_ms: number | null; + last_delivery_ms: number | null; + paused: string; + }; + page: components["schemas"]["PageDescriptor"]; + }; /** * @example { * "items": [], @@ -11019,6 +11052,74 @@ export interface operations { 503: components["responses"]["Problem503"]; }; }; + readHonchoSession: { + parameters: { + query?: never; + header?: never; + path: { + session_id: components["schemas"]["ID"]; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Delivery status and operator actions. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HonchoSession"]; + }; + }; + 400: components["responses"]["Problem400"]; + 401: components["responses"]["Problem401"]; + 404: components["responses"]["Problem404"]; + 405: components["responses"]["Problem405"]; + 406: components["responses"]["Problem406"]; + 413: components["responses"]["Problem413"]; + 415: components["responses"]["Problem415"]; + 503: components["responses"]["Problem503"]; + }; + }; + changeHonchoSession: { + parameters: { + query?: never; + header?: never; + path: { + session_id: components["schemas"]["ID"]; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + /** @enum {string} */ + action: "bind" | "backfill" | "retry" | "resend"; + }; + }; + }; + responses: { + /** @description Delivery status and operator actions. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HonchoSession"]; + }; + }; + 400: components["responses"]["Problem400"]; + 401: components["responses"]["Problem401"]; + 404: components["responses"]["Problem404"]; + 405: components["responses"]["Problem405"]; + 406: components["responses"]["Problem406"]; + 409: components["responses"]["Problem409"]; + 413: components["responses"]["Problem413"]; + 415: components["responses"]["Problem415"]; + 503: components["responses"]["Problem503"]; + }; + }; getLinkGroup: { parameters: { query: { -- knotmirror 0.0.1