diff --git a/adapters/lo/README.md b/adapters/lo/README.md index 44506a2..503a8d1 100644 --- a/adapters/lo/README.md +++ b/adapters/lo/README.md @@ -197,7 +197,7 @@ server, and a compatible native client. ## Native LO secretary -The Go adapter implements the native SDK 0.2 wire contract directly; it does not +The Go adapter implements the native SDK 0.6 wire contract directly; it does not import the TypeScript SDK or reuse Telegram consent flags. Use a deployment with `lo_schema_version=1`, policy versions, independent `lo_rights` and delegated source contexts. Ordinary bot messages remain a separate path. @@ -217,8 +217,10 @@ Consent and source policy are checked again before transcription, agent executio and delivery. Edits, deletion and connection changes cancel pending work. Native server guards remain authoritative for races with manual takeover or revocation. -Secretary runs use normal Flock tools and configured MCP servers. Approval gates -the outgoing reply, not tool actions. Workspaces and sessions are isolated by +Secretary runs use only authorized read-only knowledge tools (`kb_search`, +`kb_get`, `kb_list`) through the validated knowledge proxy and a `readonly_v2` +session. The model receives no shell, write or message-sending tool authority. +Owner approval authorizes only the exact final reply. Workspaces and sessions are isolated by owner, connection, conversation and policy version under `/lo`, outside `APPROVED_DIRECTORY`. Compose persists this root in `secretary_workspace`. Host runs must set @@ -279,15 +281,18 @@ server/client rollout, enable the pilot owner and bot capability, grant rights i LO, then test review, automatic reply, voice, edit/delete and revoke while running. Local HTTP contract and race tests do not establish production readiness. -Contract regression fixtures in `testdata/secretary-sdk-0.2.json` are generated -by the actual [SDK 0.2 HTTP adapter](https://github.com/lo-ink/lo-platform-adapters/blob/3cd0095a27467ed4f494b329158a365c44951daa/packages/bot-http-lo/src/secretary.ts). -The generator validates native receipts with that adapter before writing the -fixtures. Go tests compare delegated request bodies against those -fixtures, including IDs above JavaScript's safe integer range. Regenerate after -building the pinned SDK revision: +Contract regression fixtures in `testdata/secretary-sdk-0.6.json` are generated +by the published [Bot SDK 0.6.0](https://github.com/LO-ink/lo-bot-sdk/tree/b9525c01079d165ee8ac171c2fe936a4a072cf08) +public secretary client with a synthetic HTTP recorder. The SDK validates each +native receipt before the golden file is written. Go tests compare delegated +requests, including IDs above JavaScript's safe integer range. The obsolete +native proposal API is removed; persisted legacy reasons still refuse a direct +send and are never converted into new approved work. + +Create an isolated consumer with exactly `@lo-ink/bot-sdk@0.6.0` installed, then: ```sh -node adapters/lo/testdata/generate-secretary-sdk.mjs /path/to/packages/bot-http-lo/dist/secretary.js +node adapters/lo/testdata/generate-secretary-sdk.mjs /path/to/consumer ``` The merged Bot API also covers lossless string input in diff --git a/adapters/lo/secretary.go b/adapters/lo/secretary.go index d6fbd9a..b8dfb72 100644 --- a/adapters/lo/secretary.go +++ b/adapters/lo/secretary.go @@ -1,4 +1,4 @@ -//nolint:tagliatelle // LO Bot API uses snake_case wire keys, matching the native SDK 0.2 transport. +//nolint:tagliatelle // LO Bot API uses snake_case wire keys, matching the native SDK 0.6 transport. package lo import ( @@ -11,9 +11,9 @@ import ( "strings" ) -// Native SDK 0.2 bounds (human and bot namespaces differ): -// https://github.com/lo-ink/lo-platform-adapters/tree/3cd0095a27467ed4f494b329158a365c44951daa -// See packages/bot-http-lo/src/secretary.ts and the generated fixtures in testdata/. +// Native SDK 0.6 bounds (human and bot namespaces differ): +// https://github.com/LO-ink/lo-bot-sdk/tree/b9525c01079d165ee8ac171c2fe936a4a072cf08 +// See src/http/ and the generated fixtures in testdata/. const ( maxSecretaryConversationID = 2147483647 maxSecretaryUserID = 999999999999999 @@ -40,7 +40,7 @@ func (n *SecretaryNumber) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON keeps int64 IDs lossless across JSON gateways and the SDK 0.2 transport. +// MarshalJSON keeps int64 IDs lossless across JSON gateways and the SDK 0.6 transport. func (n SecretaryNumber) MarshalJSON() ([]byte, error) { return json.Marshal(n.String()) } // String returns a lossless decimal ID. @@ -208,24 +208,6 @@ type SecretaryAction struct { Reason string `json:"lo_draft_reason,omitempty"` } -// SecretaryDraft is reviewed by the account owner in LO, never by third-party callback buttons. -type SecretaryDraft struct { - ID string `json:"lo_draft_id"` - ConnectionID string `json:"business_connection_id"` - ConversationID SecretaryNumber `json:"lo_conversation_id"` - ChatID SecretaryNumber `json:"chat_id"` - SourceMessageID SecretaryNumber `json:"lo_source_message_id"` - Text string `json:"text"` - State string `json:"state"` - Mode string `json:"mode"` - Revision SecretaryNumber `json:"lo_revision"` - BotID SecretaryNumber `json:"lo_secretary_bot_id"` - Reason string `json:"reason"` - Date int64 `json:"date"` - ExpiresAt int64 `json:"expires_at"` - MessageID *SecretaryNumber `json:"message_id,omitempty"` -} - // WithSecretary enables native event subscription before polling starts. func (c *Client) WithSecretary(enabled bool) *Client { c.secretaryEnabled = enabled; return c } @@ -252,30 +234,6 @@ func (action SecretaryAction) Valid() bool { messageText(action.Text) == nil } -// ProposeBusinessDraft uses native server-side owner review; Flock cannot approve the draft. -func (c *Client) ProposeBusinessDraft(ctx context.Context, action SecretaryAction) (SecretaryDraft, error) { - var result SecretaryDraft - if !action.Valid() || action.Reason != "manual_review" { - return result, errors.New("invalid LO secretary draft") - } - if err := c.call(ctx, "proposeBusinessDraft", action, &result); err != nil { - return result, err - } - if !ValidSecretaryConnectionID(result.ID) || result.ConnectionID != action.ConnectionID || - result.ConversationID != action.Context.ConversationID || result.ChatID != action.ChatID || - result.SourceMessageID != action.Context.SourceMessageID || result.Revision <= 0 || result.BotID < minSecretaryBotID || - result.BotID > maxSecretarySafeInteger || result.Date <= 0 || result.ExpiresAt <= result.Date || - (result.State == "sent") != (result.MessageID != nil) || - !slices.Contains([]string{ - "manual_review", "owner_cancelled", "policy_changed", "source_changed", - "manual_takeover", "superseded", - }, result.Reason) || result.Text != action.Text || result.Mode != "review" || - !slices.Contains([]string{"draft", "approved", "sent", "cancelled", "expired"}, result.State) { - return SecretaryDraft{}, errors.New("invalid LO secretary draft response") - } - return result, nil -} - // SendSecretaryText sends one idempotent message from the human account, not a normal bot chat reply. func (c *Client) SendSecretaryText(ctx context.Context, action SecretaryAction, ownerID int64) error { if !action.Valid() || action.Reason != "" { diff --git a/adapters/lo/secretary_test.go b/adapters/lo/secretary_test.go index 29737ec..3427d3a 100644 --- a/adapters/lo/secretary_test.go +++ b/adapters/lo/secretary_test.go @@ -87,52 +87,27 @@ func TestSecretaryRejectsAmbiguousOrInvalidUpdatesWithoutBotFallback(t *testing. func TestSecretaryDelegatedWritesUseExactContextAndIdempotency(t *testing.T) { t.Parallel() - for _, draft := range []bool{false, true} { - t.Run(strconv.FormatBool(draft), func(t *testing.T) { - t.Parallel() - action := lo.SecretaryAction{ - ConnectionID: secretaryConnectionID, RequestID: "flock:durable-key", - Context: secretaryScope(), ChatID: 77, Text: "reply", - } - if draft { - action.Reason = "manual_review" - } - api := client(t, func(w http.ResponseWriter, r *http.Request) { - var received lo.SecretaryAction - if err := json.NewDecoder(r.Body).Decode(&received); err != nil { - t.Error(err) - } - if received != action { - t.Errorf("wrong delegated body: %+v", received) - } - if draft { - if !strings.HasSuffix(r.URL.Path, "/proposeBusinessDraft") { - t.Error("wrong method") - } - reply(w, `{"ok":true,"result":{"lo_draft_id":"69417813-99f5-4dc5-a6a8-4c45151b1e5c`+ - `","business_connection_id":"`+secretaryConnectionID+ - `","lo_conversation_id":19,"chat_id":77,"lo_source_message_id":"922337203`+ - `6854775806","text":"reply","state":"draft","mode":"review","lo_revision"`+ - `:1,"lo_secretary_bot_id":1000000000000001,"reason":"manual_review","date`+`":1,"expires_at":2}}`) - } else { - if !strings.HasSuffix(r.URL.Path, "/sendMessage") { - t.Error("wrong method") - } - reply(w, `{"ok":true,"result":{"message_id":2,"business_connection_id":"`+secretaryConnectionID+ - `","chat":{"id":77,"type":"private"},"from":{"id":1,"is_bot":false},"lo_s`+ - `ecretary_bot_id":1000000000000001,"text":"reply"}}`) - } - }) - if draft { - if _, err := api.ProposeBusinessDraft(t.Context(), action); err != nil { - t.Fatal(err) - } - } else { - if err := api.SendSecretaryText(t.Context(), action, 1); err != nil { - t.Fatal(err) - } - } - }) + action := lo.SecretaryAction{ + ConnectionID: secretaryConnectionID, RequestID: "flock:durable-key", + Context: secretaryScope(), ChatID: 77, Text: "reply", + } + api := client(t, func(w http.ResponseWriter, r *http.Request) { + var received lo.SecretaryAction + if err := json.NewDecoder(r.Body).Decode(&received); err != nil { + t.Error(err) + } + if received != action { + t.Errorf("wrong delegated body: %+v", received) + } + if !strings.HasSuffix(r.URL.Path, "/sendMessage") { + t.Error("wrong method") + } + reply(w, `{"ok":true,"result":{"message_id":2,"business_connection_id":"`+secretaryConnectionID+ + `","chat":{"id":77,"type":"private"},"from":{"id":1,"is_bot":false},`+ + `"lo_secretary_bot_id":1000000000000001,"text":"reply"}}`) + }) + if err := api.SendSecretaryText(t.Context(), action, 1); err != nil { + t.Fatal(err) } } @@ -205,9 +180,9 @@ func TestSecretaryVoiceUsesNestedNativeAttachment(t *testing.T) { } } -func TestSecretaryRequestsMatchRealSDK02Fixtures(t *testing.T) { +func TestSecretaryRequestsMatchRealSDK06Fixtures(t *testing.T) { t.Parallel() - data, err := os.ReadFile("testdata/secretary-sdk-0.2.json") + data, err := os.ReadFile("testdata/secretary-sdk-0.6.json") if err != nil { t.Fatal(err) } @@ -222,7 +197,7 @@ func TestSecretaryRequestsMatchRealSDK02Fixtures(t *testing.T) { if err := json.Unmarshal(data, &corpus); err != nil { t.Fatal(err) } - if len(corpus.Fixtures) != 3 { + if len(corpus.Fixtures) != 2 { t.Fatal("missing SDK fixtures") } for _, fixture := range corpus.Fixtures { @@ -240,7 +215,7 @@ func TestSecretaryRequestsMatchRealSDK02Fixtures(t *testing.T) { t.Error(err) } if !reflect.DeepEqual(got, want) { - t.Errorf("request differs from pinned SDK 0.2: %v", got) + t.Errorf("request differs from pinned SDK 0.6: %v", got) } reply(w, `{"ok":true,"result":`+string(fixture.Result)+`}`) }) @@ -259,10 +234,21 @@ func TestSecretaryRequestsMatchRealSDK02Fixtures(t *testing.T) { t.Fatal(err) } } else { - if _, err := api.ProposeBusinessDraft(t.Context(), action); err != nil { - t.Fatal(err) - } + t.Fatal("unknown SDK fixture operation") } }) } } + +func TestSecretaryLegacyProposalCannotBecomeDelegatedSend(t *testing.T) { + t.Parallel() + calls := 0 + api := client(t, func(http.ResponseWriter, *http.Request) { calls++ }) + action := lo.SecretaryAction{ + ConnectionID: secretaryConnectionID, RequestID: "flock:legacy-key", + Context: secretaryScope(), ChatID: 77, Text: "legacy proposal", Reason: "manual_review", + } + if err := api.SendSecretaryText(t.Context(), action, 1); err == nil || calls != 0 { + t.Fatal("legacy proposal was admitted as a new delegated send") + } +} diff --git a/adapters/lo/testdata/generate-secretary-sdk.mjs b/adapters/lo/testdata/generate-secretary-sdk.mjs index 21544fd..aaa11f2 100644 --- a/adapters/lo/testdata/generate-secretary-sdk.mjs +++ b/adapters/lo/testdata/generate-secretary-sdk.mjs @@ -1,39 +1,51 @@ -// Regenerate with the built LO SDK 0.2 HTTP adapter at the pinned source revision below. -// Usage: node adapters/lo/testdata/generate-secretary-sdk.mjs /path/to/dist/secretary.js -import { writeFile } from 'node:fs/promises'; +// Regenerate from the published SDK 0.6 public entry point; no network requests. +// Usage: node adapters/lo/testdata/generate-secretary-sdk.mjs /path/to/consumer +import { readFile, writeFile } from 'node:fs/promises'; import { pathToFileURL } from 'node:url'; -const { wireSecretaryRequest, normalizeSecretaryResult } = await import(pathToFileURL(process.argv[2])); -const source = 'https://github.com/lo-ink/lo-platform-adapters/blob/3cd0095a27467ed4f494b329158a365c44951daa/packages/bot-http-lo/src/secretary.ts'; +import { createRequire } from 'node:module'; +import { resolve } from 'node:path'; +const consumer = createRequire(pathToFileURL(resolve(process.argv[2], 'package.json'))); +const entry = pathToFileURL(consumer.resolve('@lo-ink/bot-sdk')); +const { version } = JSON.parse(await readFile(new URL('../package.json', entry), 'utf8')); +if (version !== '0.6.0') throw Error('Expected published Bot SDK 0.6.0'); +const { createLoSecretaryClient } = await import(entry); +const source = 'https://github.com/LO-ink/lo-bot-sdk/tree/b9525c01079d165ee8ac171c2fe936a4a072cf08'; const connectionId = '15eac687-9383-4da1-9644-826693923e44'; const context = { - conversationId: '19', chatId: '77', policyVersion: '9223372036854775807', - sourceMessageId: '9223372036854775806', sourceRevision: '1', + conversationId: '19', chatId: '77', policyVersion: '9223372036854775807', + sourceMessageId: '9223372036854775806', sourceRevision: '1', }; const action = { connectionId, context, requestId: 'flock:sdk-contract', text: 'SDK reply' }; const connection = { - id: connectionId, user: { id: 1, is_bot: false }, is_enabled: true, - lo_schema_version: 1, lo_policy_version: context.policyVersion, date: 1, - lo_rights: ['receive_messages', 'send_messages', 'mark_read', 'edit_sent', 'delete_sent', 'delete_all'], + id: connectionId, user: { id: 1, is_bot: false, first_name: 'Owner' }, is_enabled: true, + lo_schema_version: 1, lo_policy_version: context.policyVersion, date: 1, + lo_rights: ['receive_messages', 'send_messages', 'mark_read', 'edit_sent', 'delete_sent', 'delete_all'], }; const sent = { - message_id: '2', business_connection_id: connectionId, chat: { id: 77, type: 'private' }, - from: { id: 1, is_bot: false }, date: 1, text: action.text, lo_secretary_bot_id: '1000000000000001', + message_id: '2', business_connection_id: connectionId, chat: { id: 77, type: 'private' }, + from: { id: 1, is_bot: false, first_name: 'Owner' }, date: 1, text: action.text, lo_secretary_bot_id: '1000000000000001', }; -const draft = { - lo_draft_id: '69417813-99f5-4dc5-a6a8-4c45151b1e5c', business_connection_id: connectionId, - lo_conversation_id: context.conversationId, chat_id: context.chatId, - lo_source_message_id: context.sourceMessageId, lo_revision: '1', state: 'draft', mode: 'review', - text: action.text, reason: 'manual_review', date: 1, expires_at: 2, - lo_secretary_bot_id: '1000000000000001', -}; -const cases = [ - ['getConnection', { connectionId }, connection], - ['sendText', action, sent], - ['proposeDraft', { ...action, reason: 'manual_review' }, draft], -]; -const fixtures = cases.map(([operation, input, result]) => { - // The real adapter both produces the request and validates its corresponding native receipt. - normalizeSecretaryResult(operation, input, result); - return { operation, ...wireSecretaryRequest(operation, input), result }; -}); -await writeFile(new URL('./secretary-sdk-0.2.json', import.meta.url), JSON.stringify({ source, fixtures }, null, 2) + '\n'); +const fixtures = []; +for (const [operation, input, result] of [ + ['getConnection', { connectionId }, connection], + ['sendText', action, sent], +]) { + const calls = []; + const client = createLoSecretaryClient({ + token: '1000000000000001:synthetic_sdk_contract', + fetch: async (url, options) => { + calls.push({ method: new URL(url).pathname.split('/').at(-1), body: JSON.parse(options.body) }); + return Response.json({ ok: true, result }); + }, + }); + if (operation === 'getConnection') { + const normalized = await client.getConnection(input.connectionId); + if (normalized.policyVersion !== context.policyVersion) throw Error('Lossless connection revision changed'); + } else await client.sendText(input); + if (calls.length !== 1) throw Error('SDK must issue exactly one synthetic request'); + if (operation === 'sendText' && (calls[0].body.lo_context.policy_version !== context.policyVersion || + calls[0].body.lo_context.source_message_id !== context.sourceMessageId)) + throw Error('Lossless context IDs changed in the public SDK request'); + fixtures.push({ operation, ...calls[0], result }); +} +await writeFile(new URL('./secretary-sdk-0.6.json', import.meta.url), JSON.stringify({ source, sdkVersion: version, fixtures }, null, 2) + '\n'); diff --git a/adapters/lo/testdata/secretary-sdk-0.2.json b/adapters/lo/testdata/secretary-sdk-0.6.json similarity index 54% rename from adapters/lo/testdata/secretary-sdk-0.2.json rename to adapters/lo/testdata/secretary-sdk-0.6.json index f27a363..667493f 100644 --- a/adapters/lo/testdata/secretary-sdk-0.2.json +++ b/adapters/lo/testdata/secretary-sdk-0.6.json @@ -1,5 +1,6 @@ { - "source": "https://github.com/lo-ink/lo-platform-adapters/blob/3cd0095a27467ed4f494b329158a365c44951daa/packages/bot-http-lo/src/secretary.ts", + "source": "https://github.com/LO-ink/lo-bot-sdk/tree/b9525c01079d165ee8ac171c2fe936a4a072cf08", + "sdkVersion": "0.6.0", "fixtures": [ { "operation": "getConnection", @@ -11,7 +12,8 @@ "id": "15eac687-9383-4da1-9644-826693923e44", "user": { "id": 1, - "is_bot": false + "is_bot": false, + "first_name": "Owner" }, "is_enabled": true, "lo_schema_version": 1, @@ -52,45 +54,13 @@ }, "from": { "id": 1, - "is_bot": false + "is_bot": false, + "first_name": "Owner" }, "date": 1, "text": "SDK reply", "lo_secretary_bot_id": "1000000000000001" } - }, - { - "operation": "proposeDraft", - "method": "proposeBusinessDraft", - "body": { - "business_connection_id": "15eac687-9383-4da1-9644-826693923e44", - "lo_request_id": "flock:sdk-contract", - "lo_context": { - "conversation_id": "19", - "chat_id": "77", - "policy_version": "9223372036854775807", - "source_message_id": "9223372036854775806", - "source_revision": "1" - }, - "chat_id": "77", - "text": "SDK reply", - "lo_draft_reason": "manual_review" - }, - "result": { - "lo_draft_id": "69417813-99f5-4dc5-a6a8-4c45151b1e5c", - "business_connection_id": "15eac687-9383-4da1-9644-826693923e44", - "lo_conversation_id": "19", - "chat_id": "77", - "lo_source_message_id": "9223372036854775806", - "lo_revision": "1", - "state": "draft", - "mode": "review", - "text": "SDK reply", - "reason": "manual_review", - "date": 1, - "expires_at": 2, - "lo_secretary_bot_id": "1000000000000001" - } } ] }