Repository navigation
Identity propagation — canonical platform:id from channels through the agent - #119
Conversation
…h the agent
Ports picoclaw's pkg/identity pattern (BuildCanonicalID + per-channel
SenderInfo + IsAllowedSender allowlist) so embedder hooks and audit
logs can attribute each turn to the user that triggered it, and
channels can refuse non-allowlisted senders before invoking the
model. ~250 LOC.
- New src/pkg/identity/PasClaw.Identity.pas: TIdentity record
(Source, UserId, UserName, RoomId), BuildCanonicalID +
ParseCanonicalID (rightmost-colon-safe so Matrix MXIDs survive),
MakeIdentity, CanonicalOf, FormatIdentity, IsAllowedSender
with `*` and `<platform>:*` wildcard patterns. Empty allowlist
= no gate (matches picoclaw's channel/base.go default).
- TToolLoopConfig.Identity field; RunToolLoop logs
"toolloop start identity=…" at turn start when populated (empty
identity logs nothing — keeps CLI / cron noise low).
- TConfig.AllowSenders: array of string with JSON ser/deser. Stays
out of ToJSON when empty (stock configs remain tidy).
- All 7 channels wired (Telegram chat id, Discord author id +
username + channel id, LINE source id, WhatsApp from-number,
Matrix sender MXID + room id, IRC nick + reply target, Email
From addr). Each channel calls IsAllowedSender immediately
after building TIdentity; rejected senders are logged + skipped
BEFORE RunToolLoop, never reaching the model.
- Cmd.Agent sets `cli:$USER` (or `cli:local` if unset / Windows
%USERNAME% if MSWINDOWS); the gateway sets `gateway:anon` at all
three RunToolLoop sites since gateway terminates an unauthenticated
socket and client-asserted headers can't be trusted yet (header-
derived identity is a follow-up alongside gateway auth).
- Subagents currently inherit empty identity (parent's per-turn
identity isn't exposed to the spawn tool's stored context); the
parent loop logs its identity at start, so the audit chain is
intact. Threading identity into TSubagentContext is a v2 extension.
Verified with a focused test (created, built, ran, removed) covering
all six assertion groups: canonical compose/parse, MakeIdentity
overloads, FormatIdentity edge cases (empty, no UserName, with
UserName), IsAllowedSender (empty list, `*`, exact, `<platform>:*`,
mixed, unknown-identity-deny-without-`*`), and TConfig.AllowSenders
JSON roundtrip + defaults-out-of-ToJSON.
https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 12dc2442c8
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| Exit; | ||
| end; | ||
|
|
||
| LoopCfg.Identity := MakeIdentity('telegram', IntToStr(ChatId)); |
There was a problem hiding this comment.
Gate Telegram group messages by the actual sender
When the bot is added to a Telegram group, chat.id identifies the group rather than the user who sent the message. As a result, allowing telegram:<group-id> permits every member of that group to invoke the agent and its tools, while it is impossible to allow only selected group members. Parse message.from.id for Identity.UserId and keep chat.id separately as the room or reply target.
Useful? React with 👍 / 👎.
| client-asserted and unsafe to gate on. Stamp 'gateway:anon' so | ||
| downstream hooks/logs see SOMETHING; tightening this is a | ||
| follow-up alongside gateway auth. } | ||
| LoopCfg.Identity := MakeIdentity('gateway', 'anon'); |
There was a problem hiding this comment.
Preserve the system prompt on the legacy chat route
On the gateway's HandleChat route, adding gateway:anon replaced the existing LoopCfg.Options.SystemPrompt := BuildSystemPrompt(...) assignment instead of being added alongside it. Requests to this route now run without the configured PasClaw system prompt, unlike /v1/chat/completions and /v1/responses, which can change persona and tool-use behavior for existing clients.
Useful? React with 👍 / 👎.
| if not IsAllowedSender(LoopCfg.Identity, FCfg.AllowSenders) then | ||
| begin | ||
| LogInfo('email: sender %s rejected by allow_senders', | ||
| [FormatIdentity(LoopCfg.Identity)]); | ||
| Continue; |
There was a problem hiding this comment.
Mark globally rejected emails as seen
When an email passes the existing MatchesAllow check but fails the new global allow_senders check, this Continue skips the IMAP.StoreFlags(..., [mfSeen]) call. Because the message was fetched with RetrievePeek, it remains unseen and is fetched and rejected again on every poll indefinitely. Mark it seen here, as the earlier channel-specific rejection branch already does.
Useful? React with 👍 / 👎.
| StarPos := Pos('*', Pattern); | ||
| if StarPos = 0 then Exit(False); | ||
| { Only suffix wildcards supported — '<platform>:*' or '<platform>:<x>*'. | ||
| Match by prefix (everything up to but not including the star). } | ||
| Prefix := Copy(Pattern, 1, StarPos - 1); | ||
| Result := (Prefix <> '') | ||
| and (Length(Canon) >= Length(Prefix)) | ||
| and (Copy(Canon, 1, Length(Prefix)) = Prefix); |
There was a problem hiding this comment.
Reject wildcard patterns with trailing characters
For an accidentally malformed allowlist entry such as telegram:*admin, Pos('*', Pattern) finds the star and the matcher compares only the telegram: prefix, silently allowing every Telegram sender. The comment and README describe suffix wildcards, so patterns containing a star anywhere except the final position should fail closed rather than broadening access.
Useful? React with 👍 / 👎.
| Hooks read Cfg.Identity to gate behaviour by sender. The | ||
| allowlist check (PasClaw.Identity.IsAllowedSender) is run by | ||
| the channel BEFORE RunToolLoop — by the time the loop is | ||
| called, the operator has already approved this sender. *) | ||
| Identity: TIdentity; |
There was a problem hiding this comment.
Expose the propagated identity to hooks
The new field is documented as allowing hooks to gate behavior by sender, but none of the hook callbacks receive Cfg or an identity: BeforeTurn, BeforeToolCall, AfterToolResult, and OnError in PasClaw.Agent.Hooks retain their previous signatures, and the dispatch helpers pass only their existing arguments. Consequently, registered hooks cannot inspect the per-turn identity despite the newly documented API behavior. Thread the identity into the hook callbacks or provide an equivalent per-turn context.
Useful? React with 👍 / 👎.
| LoopCfg.Fallbacks := ResolveFallbacks(FCfg); | ||
| LoopCfg.Options := DefaultChatOptions; | ||
| ApplyPromptCacheConfig(LoopCfg.Options, FCfg.PromptCache); | ||
| LoopCfg.Identity := MakeIdentity('gateway', 'anon'); |
There was a problem hiding this comment.
Stamp identity on the responses tool-loop path
The added gateway identity assignment covers HandleChat and /v1/chat/completions, but the internal-tool-loop branch of /v1/responses still calls RunToolLoop at PasClaw.Gateway.Server.pas:3034 without setting LoopCfg.Identity. Requests to that endpoint therefore remain unattributed in the new audit log while equivalent gateway requests log gateway:anon. Add the same assignment when configuring that branch.
Useful? React with 👍 / 👎.
…ty, email mark-seen, wildcard fail-closed, hook identity Six Codex findings on the identity PR — all legit, all addressed in place on PR #119. P1 — Telegram from.id vs chat.id. message.chat.id identifies the GROUP in group chats, not the sender — keying TIdentity.UserId on chat.id let every group member through a single allowlist entry. Now parse message.from.id for UserId (+ from.username for UserName); chat.id rides on RoomId so room-level filters still work. allow_senders entries can finally gate per-user in groups. P2 — Gateway HandleChat dropped its system prompt. The identity edit overwrote the existing `LoopCfg.Options.SystemPrompt := BuildSystemPrompt(...)` line instead of being added alongside, so HandleChat requests started running without the PasClaw persona while /v1/chat/completions and /v1/responses kept theirs. Re-added — three of three gateway routes now stamp identity AND inject the system prompt. P2 — Email rejected via global allow_senders stayed unseen. After RetrievePeek (no mark-seen) the rejection branch called Continue without IMAP.StoreFlags(..., [mfSeen]); the same message would get re-fetched and re-rejected on every poll forever. Mark seen before Continue (matches the existing channel-specific MatchesAllow rejection branch above). P2 — Wildcard pattern fail-closed. MatchPattern used to extract the prefix from any `*` position, so a typo like "telegram:*admin" silently broadened to every Telegram user. Now require `*` to be the LAST character of the pattern; any mid-string star matches nothing. Suffix wildcards ("telegram:*") still work; bare "*" still works. P2 — Hook identity surface. The doc claimed hooks could gate by sender but no callback received Cfg or Identity — so a TPasClawHook subclass had no way to read the per-turn id. Added a public Identity: TIdentity field on TPasClawHook; RunToolLoop now writes it onto every registered hook once per loop, before any BeforeTurn / BeforeToolCall / AfterToolResult / OnError dispatch. Hooks read `Self.Identity` from any virtual — no signature change to existing hook subclasses, fully backwards-compatible. P2 — /v1/responses internal-tool-loop branch missed the identity stamp. HandleChat and /v1/chat/completions both got `LoopCfg.Identity := MakeIdentity('gateway', 'anon')`; the third RunToolLoop site (internal-tools branch of /v1/responses) didn't. Audit log was inconsistent. Added. Verified with a focused test (created, built, ran, removed) covering the three runtime-verifiable fixes: Telegram from.id keys the allowlist (Eli is allowed, Bob in the same group is rejected), malformed mid-string wildcards fail closed across multiple shapes (telegram:*admin, *:admin, tele*ram:U-eli), and TPasClawHook subclass reads Self.Identity from BeforeTurn. The three compile-checked fixes (gateway SystemPrompt re-add, email mark-seen, /v1/responses identity) are kept honest by the build itself + the line-by-line diff review. https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Summary
Ports picoclaw's
pkg/identity/identity.gopattern: every inbound channel message gets tagged with<platform>:<id>(e.g.slack:U12345,telegram:5551234,matrix:@eli:matrix.org), threaded throughTToolLoopConfig, and optionally gated by anallow_sendersconfig array. Was the one genuine parent-feature gap from the empty-dir audit — picoclaw has full identity plumbing through every channel + session keying +IsAllowedSender. ~320 LOC.What's new
src/pkg/identity/PasClaw.Identity.pas—TIdentityrecord (Source, UserId, UserName, RoomId),BuildCanonicalID/ParseCanonicalID(first-colon-split so Matrix MXIDs survive),MakeIdentity,CanonicalOf,FormatIdentity,IsAllowedSenderwith*and<platform>:*wildcard patterns.TToolLoopConfig.Identity— per-turn canonical identity.RunToolLooplogstoolloop start identity=…at turn start when populated (empty identity logs nothing to keep CLI / cron quiet).TConfig.AllowSenders: array of string— operator allowlist; ser/deser; stays out ofToJSONwhen empty.All 7 channels wired — each extracts the platform-native sender id at the inbound boundary, builds a
TIdentity, callsIsAllowedSender(LoopCfg.Identity, FCfg.AllowSenders)BEFORERunToolLoop. Rejected senders are dropped at the boundary with a log line; the model never sees them.telegramchat.id(as string)discordauthor.idusername, RoomId=channellinesource.userId/groupId/roomIdwhatsappfrom(phone)matrixsender(MXID)ircemailFrom:addressCmd.Agent stamps
cli:$USER(POSIX) /cli:%USERNAME%(Windows), falling back tocli:localso the canonical id is never empty.Gateway stamps
gateway:anonat all 3RunToolLoopsites. Header-derived identity is a follow-up alongside gateway auth — terminating an unauthenticated socket, client-asserted headers can't be trusted to gate by yet.allow_sendersconfigPatterns are exact canonical ids or
<platform>:*wildcards; bare*matches anyone. Empty array (default) = no gate, matching picoclaw'spkg/channels/base.go IsAllowedSenderdefault-allow semantics.Out of scope (v2)
RunToolLoopinherits empty identity since the parent's per-turn identity isn't on the storedTSubagentContext. Wiring this is one field + one assignment but I left it for v2 since spawn is parent-scoped already.X-PasClaw-Identity: slack:U123). Needs request signing to be safe to gate on; punt with gateway auth work.Test plan
make clean && makeclean (442213 lines)make smoke11/11 OKMakeIdentityoverloads,FormatIdentity(empty / no UserName / with UserName),IsAllowedSender(empty list /*/ exact /<platform>:*/ mixed / unknown-identity-deny-without-*),AllowSendersJSON roundtrip, defaults-out-of-ToJSONpasclaw agentstarts cleanly withcli:$USERidentity (live spot check)pasclaw agentagainst a real Telegram bot withallow_senders: ["telegram:<my-chat-id>"]— confirm non-allowlisted senders get the boundary-reject log line and don't reach the modelpasclaw gateway/v1/chat/completionsrequest shows up in logs asgateway:anonGenerated by Claude Code