Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
22 KiB
signalbot Implementation Plan
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: A pure-Go library + CLI that sends and receives Signal text messages through a bbernhard/signal-cli-rest-api container.
Architecture: signalbot.Client wraps the REST API (HTTP for accounts, link, groups, send; websocket /v1/receive/{account} for incoming messages). The protocol is handled by signal-cli inside the container (MODE=json-rpc-native, JSON_RPC_RECEIVE_MODE=manual). A cmd/signalbot CLI (link, groups, send, listen) is built on the same client.
Tech Stack: Go (go directive 1.23), stdlib (net/http, encoding/json, log/slog, flag, text/tabwriter), github.com/coder/websocket v1.8.15 (lib), github.com/mdp/qrterminal/v3 v3.2.1 (CLI only).
Spec: docs/superpowers/specs/2026-11-20-signalbot-design.md
Global Constraints
- Module path:
git.siteop.biz/vincentb99/signalbot; packagesignalbot; CLI atcmd/signalbot. go.moddeclaresgo 1.23; no CGO;go vet ./...must pass (itsstdversioncheck catches stdlib APIs newer than 1.23 — the local toolchain is 1.27).- Library dependencies: stdlib +
github.com/coder/websocketonly.qrterminalis imported only bycmd/signalbot. - Licence MIT (
LICENSE, copyright holder "vincentb99", year 2026). - Text only: send with
"text_mode": "normal"; never interpret markdown. - Code, identifiers, comments, CLI output and README in English (public Go library convention — planner's call).
- No automatic retry on
Send.Listenreconnects automatically. - Every network method takes
ctx context.Contextfirst.Clientis safe for concurrent use. - Recipients/groups are passed through as given:
group.<base64>, E.164 number, or ACI UUID.
Upstream facts (verified in signal-cli-rest-api source, 2026-11-20)
GET /v1/accounts→[{"number":"+33…","aci":"uuid"|null}]; older versions return["+33…"]. Accept both.numbermay be""(then identify the account byaci).GET /v1/qrcodelink/raw?device_name=X→{"device_link_uri":"sgnl://linkdevice?…"}; 400 ifdevice_namemissing.GET /v1/groups/{account}→[{"id":"group.…","internal_id":"…","name":"…","admins":["+33…"|"uuid"],"permissions":{"send_messages":"only-admins"|"every-member",…},…}].POST /v2/sendbody{"number":acct,"recipients":[to],"message":text,"text_mode":"normal"}→ 201 on success; 400{"error":"…"}; 429{"error":"…","challenge_tokens":[…],"account":"…"}.GET /v1/health→ 204 when up.{account}path segment accepts a number or an ACI.- Websocket
/v1/receive/{account}(json-rpc mode) pushes one text frame per signal-clireceivenotification:{"envelope":{"source":"+33…","sourceNumber":"+33…","sourceUuid":"…","sourceName":"…","sourceDevice":1,"timestamp":1763640000000,"dataMessage":{"timestamp":…,"message":"hello","groupInfo":{"groupId":"<base64>","type":"DELIVER"}}},"account":"+33…"}. Receipts/typing/sync come as envelopes withreceiptMessage/typingMessage/syncMessageand nodataMessage. - Group id conversion: REST
id="group." + base64.StdEncoding(internal_id), andgroupInfo.groupIdin envelopes is the internal id. So reply id ="group." + base64.StdEncoding.EncodeToString([]byte(groupInfo.groupId)). - Latest stable image tag:
bbernhard/signal-cli-rest-api:0.101.
Review Focus
- Slow handler (handler takes longer than the server's ws ping interval): the connection must stay alive — reads (and pong replies) continue in a reader goroutine while handlers run sequentially. → test in Task 5.
- Echo loop: a message whose sender is the bot's own account (number or ACI) must not reach the handler, so
Replycan never answer itself. → test in Task 4. - Base URL variants: trailing slash and path prefix (
http://proxy/signal/) must build correct HTTP URLs, andhttp→ws/https→wssfor the websocket. → test in Task 1 and Task 5. - Handler panic: must not crash the host app; recovered, logged at Error via the client logger, next message still delivered. → test in Task 5.
- Unicode and newlines in text (emoji, accents,
\n) must round-trip byte-exact throughSendand through received messages. → tests in Task 2 and Task 4.
Task 1: Module scaffold, client core, errors, accounts, link URI
Files:
- Create:
go.mod,LICENSE,doc.go,client.go,errors.go - Test:
client_test.go,fake_test.go(shared fake server helpers for all lib tests)
Interfaces:
-
Produces:
func New(baseURL string, opts ...Option) (*Client, error)— no network; error only ifbaseURLdoesn't parse or isn't http/https.type Option func(*Client);WithNumber(number string) Option;WithHTTPClient(*http.Client) Option;WithLogger(*slog.Logger) Option(defaultslog.Default()).type Account struct { Number, ACI string }func (c *Client) Accounts(ctx) ([]Account, error)func (c *Client) LinkURI(ctx, deviceName string) (string, error)func (c *Client) Ping(ctx) error— health OK and account resolved.- unexported:
func (c *Client) account(ctx) (Account, error)(resolves once, caches under mutex; failures not cached);func (Account) id() string(Number if non-empty else ACI);func (c *Client) do(ctx, method, path string, in, out any) error(JSON in/out, maps errors);func (c *Client) endpoint(path string) string. - Errors:
ErrNotLinked,ErrMultipleAccounts,ErrUnavailable,ErrRateLimited,ErrEmptyText;type APIError struct { StatusCode int; Message string }withError()andIs(target error) bool(true forErrUnavailablewhenStatusCode >= 500,ErrRateLimitedwhen 429). Transport failures wrapErrUnavailableand the cause (fmt.Errorf("signalbot: %w: %w", ErrUnavailable, err)).
-
Step 1: Init module and licence —
go mod init git.siteop.biz/vincentb99/signalbot, setgo 1.23, MITLICENSE,doc.gowith a package comment summarising usage (New → Send / Listen) and that the service must runJSON_RPC_RECEIVE_MODE=manualwithListenrunning permanently. -
Step 2: Write failing tests in
client_test.go(fake server viahttptest.NewServer+ helpers infake_test.go):TestNewDoesNoNetwork:New("http://127.0.0.1:1")returns nil error.TestNewRejectsBadURL:New("ftp://x")andNew("::")error.TestAccountsObjectAndLegacyFormats:[{"number":"+331","aci":"a-1"},{"number":"","aci":"a-2"}]→[{+331 a-1} {"" a-2}];["+331"]→[{+331 ""}].TestAccountAutoDetect: one account → used; zero →errors.Is(err, ErrNotLinked); two →ErrMultipleAccounts.TestAccountWithNumber:WithNumber("+332")with accounts+331,+332→{+332 …}(ACI filled from list); with number absent from list →ErrNotLinked.TestAccountCachedAfterSuccess: twoPingcalls →/v1/accountshit once.TestPing: health 204 + one account → nil; health conn refused (closed server) →errors.Is(err, ErrUnavailable).TestAPIErrorMapping: handler returning 503{"error":"down"}→errors.Is(err, ErrUnavailable)anderrors.AsgivesStatusCode 503, Message "down"; 429 →ErrRateLimited; 400 → neither,Messageset; non-JSON body →Message= trimmed body.TestLinkURI: asserts querydevice_name=imdbotg, returnssgnl://linkdevice?uuid=x.TestEndpointJoin(Review Focus 3): basehttp://h/signal/andhttp://h/signal+/v1/accounts→http://h/signal/v1/accounts.
-
Step 3: Run
go test ./...→ FAIL (undefined symbols). -
Step 4: Implement
client.goanderrors.goper Interfaces. Accounts decoding: unmarshal into[]json.RawMessage, each element string or object. -
Step 5: Run
go test ./... && go vet ./...→ PASS. -
Step 6: Commit
feat: client core, accounts, link URI, errors.
Task 2: Send
Files:
- Create:
send.go - Test:
send_test.go
Interfaces:
-
Consumes:
account,do, errors (Task 1). -
Produces:
func (c *Client) Send(ctx context.Context, to, text string) error. -
Step 1: Write failing tests:
TestSendPayload: fake/v2/sendcaptures body;Send(ctx, "group.QUJD", "hi")with account+331→ body exactly{"number":"+331","recipients":["group.QUJD"],"message":"hi","text_mode":"normal"}(compare decoded maps), method POST,Content-Type: application/json.TestSendUsesACIWhenNoNumber: account{"" a-2}→"number":"a-2".TestSendEmptyText:Send(ctx, "+332", "")→errors.Is(err, ErrEmptyText), no HTTP call. Whitespace-only" \n"alsoErrEmptyText.TestSendUnicodeRoundTrip(Review Focus 5): text"Nouveauté 🎬\nligne 2"arrives byte-exact.TestSendErrors: 400{"error":"Invalid group id"}→*APIError{400,"Invalid group id"}; 429 →ErrRateLimited.
-
Step 2: Run
go test -run TestSend ./...→ FAIL. -
Step 3: Implement
Sendinsend.go(201 and 200 both success; response body ignored). -
Step 4: Run
go test ./... && go vet ./...→ PASS. -
Step 5: Commit
feat: send text messages.
Task 3: Groups
Files:
- Create:
groups.go - Test:
groups_test.go
Interfaces:
-
Consumes:
account,do(Task 1). -
Produces:
type Group struct { ID, Name string; IsAdmin, AdminsOnly bool };func (c *Client) Groups(ctx context.Context) ([]Group, error). -
Step 1: Write failing tests:
TestGroupsMapping: fakeGET /v1/groups/+331with two groups →IDfromid,Namefromname,AdminsOnlytrue iffpermissions.send_messages == "only-admins".TestGroupsIsAdminByNumberOrACI: account{+331 a-1}; group A admins["+331"]→ true; group B admins["a-1"]→ true; group C admins["+339"]→ false.TestGroupsEmpty:[]→ empty slice, nil error.
-
Step 2: Run
go test -run TestGroups ./...→ FAIL. -
Step 3: Implement
Groups(path segmenturl.PathEscape(acct.id())). -
Step 4: Run
go test ./... && go vet ./...→ PASS. -
Step 5: Commit
feat: list groups.
Task 4: Incoming message parsing and Reply
Files:
- Create:
message.go - Test:
message_test.go
Interfaces:
-
Consumes:
Send(Task 2),Account(Task 1). -
Produces:
type Message struct { From string; GroupID string; Text string; Timestamp time.Time; client *Client }—From=sourceNumberif non-empty elsesourceUuid;GroupID= converted id (see Upstream facts) or"";Timestamp=time.UnixMilli(envelope.timestamp).func (m Message) Reply(ctx context.Context, text string) error—SendtoGroupIDif set, elseFrom.- unexported
func parseEnvelope(data []byte, self Account) (Message, bool)— returns a Message withclientnil (Listen sets it; tests buildMessage{client: c, …}directly). False for: invalid JSON, nodataMessage, emptymessage, sender equal toself.Numberorself.ACI(non-empty values only).
-
Step 1: Write failing tests (fixtures as raw JSON strings in the test file, shaped exactly like Upstream facts):
TestParseDirectMessage: nogroupInfo→From "+33600000001",GroupID "",Text "hello",Timestamp == time.UnixMilli(1763640000000).TestParseGroupMessage:groupInfo.groupId "Z3JvdXAtaW50ZXJuYWw="→GroupID == "group."+base64.StdEncoding.EncodeToString([]byte("Z3JvdXAtaW50ZXJuYWw=")).TestParseFromUUIDWhenNoNumber:sourceNumber "",sourceUuid "u-1"→From "u-1".TestParseIgnored: receipt envelope, typing envelope, syncMessage envelope, dataMessage withmessage ""/absent (e.g. reaction only), invalid JSON → allok == false.TestParseIgnoresSelf(Review Focus 2): sendersourceNumber == self.Number→ false;sourceUuid == self.ACIwith empty number → false.TestParseUnicode(Review Focus 5):"message":"é 🎬\nx"→ exact.TestReplyTargets: fake/v2/send; group message reply → recipientGroupID; direct reply → recipientFrom.
-
Step 2: Run
go test -run 'TestParse|TestReply' ./...→ FAIL. -
Step 3: Implement
message.go. -
Step 4: Run
go test ./... && go vet ./...→ PASS. -
Step 5: Commit
feat: parse incoming messages and reply.
Task 5: Listen (websocket, reconnect, sequential handlers)
Files:
- Create:
listen.go - Modify:
go.mod(addgithub.com/coder/websocket v1.8.15) - Test:
listen_test.go
Interfaces:
- Consumes:
account,endpoint,parseEnvelope, logger (Tasks 1, 4). - Produces:
type Handler func(ctx context.Context, m Message)func (c *Client) Listen(ctx context.Context, h Handler) error— blocks; returnsctx.Err()when ctx is done; returns a non-nil error immediately forErrNotLinked/ErrMultipleAccountsand for a websocket handshake answered with HTTP 4xx (as*APIError); retries onErrUnavailable, 5xx handshake, dial errors and connection drops.- unexported fields
minBackoff(default 1s) andmaxBackoff(default 30s), set small in tests. Backoff doubles per consecutive failure, capped, reset after a successful handshake. Each retry logged at Warn with the error.
Design decided here: one reader goroutine per connection reads frames (conn.Read) into a buffered channel (cap 64); the Listen loop consumes it and calls h sequentially. Reading continuously keeps pongs flowing while a handler is slow. Each handler call is wrapped in recover(); a panic is logged at Error and the loop continues. Unlimited read size is not needed: conn.SetReadLimit(1 << 20).
-
Step 1: Write failing tests (fake ws server:
httptest.NewServer+websocket.Accepton/v1/receive/{acct}, plus/v1/accounts):TestListenDeliversInOrder: server sends 3 text envelopes + 1 receipt → handler sees 3 messages in order, receipt skipped.TestListenReconnects: server closes after first message; second connection sends another → both delivered; at least 2 handshakes observed.TestListenStopsOnCancel: cancel ctx →Listenreturnscontext.Canceledwithin 1s.TestListenNotLinked: accounts[]→ returnsErrNotLinkedwithout dialing.TestListenHandshake4xx: receive endpoint returns 400 → returns*APIErrorwith 400, no retry.TestListenRetriesWhenUnavailable: first 2 handshakes 503, then OK → message delivered.TestListenSlowHandler(Review Focus 1): handler blocks until signalled; server callsconn.Ping(ctx)with 1s timeout while handler is blocked → ping succeeds; then unblock.TestListenHandlerPanic(Review Focus 4): first handler call panics, second message still delivered; logger (slog.Newover a buffer) containspanic.TestListenWebsocketURL(Review Focus 3): basehttp://h/signal/→ dial URL path/signal/v1/receive/%2B331;https://base →wss://scheme (unit-test the URL builderfunc (c *Client) wsURL(acct Account) string).
-
Step 2: Run
go test -run TestListen ./...→ FAIL. -
Step 3: Implement
listen.go(go get github.com/coder/websocket@v1.8.15). -
Step 4: Run
go test -race ./... && go vet ./...→ PASS. -
Step 5: Commit
feat: listen for incoming messages with reconnect.
Task 6: CLI
Files:
- Create:
cmd/signalbot/main.go - Modify:
go.mod(addgithub.com/mdp/qrterminal/v3 v3.2.1) - Test:
cmd/signalbot/main_test.go
Interfaces:
- Consumes:
New,WithNumber,Accounts,LinkURI,Groups,Send,Listen. - Produces:
func run(ctx context.Context, args []string, stdout, stderr io.Writer) int(main calls it withsignal.NotifyContext(..., os.Interrupt)andos.Exit).
Subcommands (each its own flag.FlagSet; common -url, default $SIGNALBOT_URL else http://localhost:8080; -number on groups/send/listen):
-
link [-device-name signalbot] [-timeout 5m]: snapshotAccounts, fetchLinkURI, print QR (qrterminal.GenerateHalfBlock(uri, qrterminal.L, stdout)), the raw URI, and the instruction lineOn the bot's phone: Signal > Settings > Linked devices > +, then scan.; pollAccountsevery 2s until an account not in the snapshot appears → printLinked: <number or aci>, exit 0; timeout → exit 1. -
groups: tabwriter columnsNAME ID BOT ADMIN ADMINS ONLY(yes/no); after the table, awarning:line per group where the bot is not admin or the group is not admins-only. -
send -to <id|number|uuid> <text...>: joins remaining args with spaces; exit 0 on success. -
listen: prints one line per message[2006-01-02 15:04:05] <from> (<group id or "direct">): <text>until interrupt; exit 0 on ctx cancel. -
Unknown/missing subcommand → usage on stderr, exit 2. Errors →
error: <err>on stderr, exit 1. -
Step 1: Write failing tests against an
httptestfake (packagemaincannot use the lib's_test.gohelpers — write a small fake inmain_test.go):TestRunUsage: no args → 2, stderr containsusage.TestRunSend:send -url X -to group.QUJD hello world→ fake receives message"hello world", exit 0.TestRunGroups: two groups (one admin+admins-only, one not admin) → stdout contains both names and exactly onewarning:line naming the second group.TestRunLink: accounts[]first, then[{"number":"+331"}]on 2nd poll (poll interval overridable via an unexported package var) → stdout containssgnl://andLinked: +331, exit 0.TestRunListen: ws fake sends one direct message then ctx is cancelled → stdout line contains+33600000001 (direct): hello, exit 0.
-
Step 2: Run
go test ./cmd/...→ FAIL. -
Step 3: Implement
cmd/signalbot/main.go. -
Step 4: Run
go test ./... && go vet ./... && CGO_ENABLED=0 go build ./...→ PASS. -
Step 5: Commit
feat: signalbot CLI (link, groups, send, listen).
Task 7: README, compose example, integration test
Files:
- Create:
README.md,examples/docker-compose.yml,examples/main.go(minimal app: Listen + echo reply + Send on start, config fromSIGNAL_API_URL,SIGNAL_GROUP_ID),integration_test.go
Interfaces:
-
Consumes: public API from Tasks 1–6.
-
Step 1:
examples/docker-compose.yml— servicesignal-api: imagebbernhard/signal-cli-rest-api:0.101, envMODE=json-rpc-native,JSON_RPC_RECEIVE_MODE=manual, volumesignal-data:/home/.local/share/signal-cli,restart: unless-stopped, port127.0.0.1:8080:8080commented with "only while linking"; serviceappwithSIGNAL_API_URL=http://signal-api:8080andSIGNAL_GROUP_ID. -
Step 2:
README.mdsections: what it is (unofficial client, not affiliated with Signal); how it works (diagram from spec); install (go get,go install …/cmd/signalbot@latest); quick start code (Send + Listen); setup procedure (the 5 steps from the spec, including creating the group and enabling "only admins can send"); important notes: keepListenrunning even if you only publish (sender-key retries),JSON_RPC_RECEIVE_MODE=manual(otherwise messages are lost while the app is down), never expose the API publicly (no auth), losing the volume means re-linking,MODE=json-rpcfallback if native mode is unstable, browser alternativehttp://localhost:8080/v1/qrcodelink?device_name=x; licences (signalbot MIT; the container ships GPL/AGPL components, used unmodified). -
Step 3:
integration_test.go— skipped unlessSIGNALBOT_IT_URLandSIGNALBOT_IT_GROUPare set:TestIntegrationPingGroupsSend(Ping ok;GroupscontainsSIGNALBOT_IT_GROUP;Senda timestamped text succeeds). -
Step 4: Run
go test ./... && go vet ./... && go build ./examples/→ PASS (integration test SKIP). -
Step 5: Commit
docs: README, compose example, integration test.
Task 8: Live verification with the real number (with the user), then release
Needs the user at their phone. No code is assumed correct for the items below until observed.
- Step 1:
docker compose -f examples/docker-compose.yml up -d signal-api(port exposed),go run ./cmd/signalbot link -device-name signalbot-dev→ user scans →Linked:printed (verifies link wait injson-rpc-native). - Step 2: User creates a test group, admins-only, bot admin.
signalbot groupsshows it withyes yes, no warning. - Step 3: Run the integration test with
SIGNALBOT_IT_URL=http://localhost:8080 SIGNALBOT_IT_GROUP=<id>→ PASS. - Step 4:
signalbot listen; user sends a direct message and a group message → both printed with correctfrom/group; a reaction and read receipts print nothing. Save one real envelope of each kind (anonymised) as fixtures inmessage_test.goif they differ from the plan's shapes, and fixparseEnvelopeaccordingly. - Step 5: Stop
listen, user sends 2 messages, restartlisten→ both delivered (verifiesmanualmode). - Step 6: Send a 3 000-character text → observe how it arrives on the phone; document the result in README.
- Step 7: Trigger errors: send to
group.AAAA(unknown) and to an invalid number → record status codes/messages; if a distinct sentinel is clearly warranted, add it with a test; update README error section. - Step 8: Check Signal's support docs for how long a linked device / the primary account survive inactivity; document the result (and "keep the bot's phone opening Signal regularly" if applicable) in README.
- Step 9: Commit fixes
fix: align with observed signal-cli-rest-api behaviour. - Step 10: Ask the user for confirmation, then
git push -u origin main,git tag v0.1.0 && git push origin v0.1.0; from a temp dir,go mod init x && go get git.siteop.biz/vincentb99/signalbot@v0.1.0succeeds (repo must be public).