Agent KakaoTalk
A TypeScript CLI tool that enables AI agents and humans to interact with KakaoTalk through a simple command interface. Features sub-device login that keeps your desktop app running.
Key Concepts
Before diving in, a few things about KakaoTalk's architecture:
- LOCO protocol = KakaoTalk's binary messaging protocol. The CLI handles this internally — you never interact with it directly.
- Chat rooms = conversations (1:1, group, or open chat). Referenced by numeric chat ID.
- Device slots = KakaoTalk allows one phone + one PC + one tablet session. The CLI registers as a tablet by default to avoid kicking your desktop app.
- Sub-device = a secondary device (PC or tablet). The CLI logs in as a sub-device, so your phone session is never affected.
- Passcode verification = when registering a new device, KakaoTalk displays a code on screen that you confirm on your phone.
- Log ID = a unique numeric identifier for each message, used for pagination.
Quick Start
# Login (registers as sub-device, desktop app stays running)
agent-kakaotalk auth login
# List chat rooms
agent-kakaotalk chat list
# Send a message
agent-kakaotalk message send <chat-id> "Hello from AI agent!"
# List messages in a chat
agent-kakaotalk message list <chat-id>
# Show your identity
agent-kakaotalk whoami
Authentication
Registers the CLI as a sub-device (tablet slot by default). Your desktop app keeps running.
agent-kakaotalk auth login
In interactive mode, this prompts for email and password. On macOS and Windows, the CLI first tries to extract cached credentials from the desktop app so you may not need to type anything. On Linux there is no desktop app, so always pass credentials explicitly via --email and --password (or --password-file).
For AI agents (non-interactive), provide credentials via flags:
agent-kakaotalk auth login --email user@example.com --password mypass
Device registration flow: On first login, KakaoTalk requires device verification:
- The CLI requests a passcode from KakaoTalk's server
- A numeric code is displayed — enter it on your phone when prompted
- The CLI polls until you confirm on your phone
- Login completes automatically after confirmation
IMPORTANT: NEVER guide the user to open a web browser, use DevTools, or manually copy tokens. Always use agent-kakaotalk auth login.
Agent Behavior (MANDATORY)
When a command fails because no account is configured, the agent MUST drive the auth flow itself:
Step 1: Check auth status
agent-kakaotalk auth status
If authenticated → retry the original command.
Step 2: Login (registers as sub-device — desktop app stays running)
agent-kakaotalk auth login
The CLI auto-extracts the email (and password if available) from the desktop app. On fresh installs, the CLI may prompt for the KakaoTalk password once (one-time device registration). After registration, the password is never needed again.
Possible responses:
{"authenticated": true, ...}→ Success. Retry original command.{"next_action": "confirm_on_phone", "passcode": "1234", ...}→ Tell the user to enter the displayed code on their phone. The CLI is polling — wait for it to complete, then the login will finish automatically.{"next_action": "choose_device", ...}→ Tablet slot is occupied. Ask user which slot to use, then re-run with--device-type pc --forceor--device-type tablet --force.{"error": "bad_credentials", ...}→ Wrong email or password. Ask the user to provide their credentials manually via--emailand--passwordflags.{"next_action": "run_interactive", ...}→ One-time device registration. On macOS/Windows, the CLI normally shows a native password dialog automatically. This response only appears in headless environments where no GUI or TTY is available. Ask the user to runagent-kakaotalk auth loginin any terminal. Do NOT ask for the password in chat.
Alternatively, use --password-file:
agent-kakaotalk auth login --password-file /tmp/.kakao-pw
The --password-file flag reads the password from the file and deletes the file immediately after reading. The password never appears in chat, shell history, or process list.
Step 3: Retry the original command
After successful auth, immediately execute whatever the user originally asked for.
Device Slots
KakaoTalk allows these simultaneous sessions:
- Phone (always active, never affected by the CLI)
- PC — will kick KakaoTalk desktop if the CLI uses this slot
- Tablet (default) — safe if you don't use a tablet for KakaoTalk
# Default: tablet slot (safe for most users)
agent-kakaotalk auth login
# Use PC slot instead (kicks desktop app)
agent-kakaotalk auth login --device-type pc
# Force login even if slot is occupied
agent-kakaotalk auth login --device-type tablet --force
Multi-Account
KakaoTalk supports multiple accounts. Each login stores credentials separately, keyed by user ID.
Listing Accounts
agent-kakaotalk auth list
agent-kakaotalk auth list --pretty
Switching Accounts
agent-kakaotalk auth use <account-id>
Using a Specific Account
All data commands accept --account <id> to use a specific account without switching the default:
agent-kakaotalk chat list --account 1234567890
agent-kakaotalk message list <chat-id> --account 1234567890
agent-kakaotalk message send <chat-id> "Hello" --account 1234567890
Without --account, commands use the current (default) account.
Memory
The agent maintains a ~/.config/agent-messenger/MEMORY.md file as persistent memory across sessions. This is agent-managed — the CLI does not read or write this file. Use the Read and Write tools to manage your memory file.
Reading Memory
At the start of every task, read ~/.config/agent-messenger/MEMORY.md using the Read tool to load any previously discovered chat IDs, friend names, and preferences.
- If the file doesn't exist yet, that's fine — proceed without it and create it when you first have useful information to store.
- If the file can't be read (permissions, missing directory), proceed without memory — don't error out.
Writing Memory
After discovering useful information, update ~/.config/agent-messenger/MEMORY.md using the Write tool. Write triggers include:
- After discovering chat IDs and participant names (from
chat list) - After discovering your own user ID (from
auth status) - After the user gives you an alias or preference ("call this the work chat", "my group chat with Alice is X")
- After discovering chat structure (group chats, 1:1 chats)
When writing, include the complete file content — the Write tool overwrites the entire file.
What to Store
- Chat IDs with participant names or display names
- Your own user ID
- User-given aliases ("work chat", "family group")
- Commonly referenced chat IDs
- Any user preference expressed during interaction
What NOT to Store
Never store tokens, passwords, credentials, or any sensitive data. Never store full message content (just IDs and chat context). Never store OAuth tokens or device UUIDs.
Handling Stale Data
If a memorized chat ID returns an error, remove it from MEMORY.md. Don't blindly trust memorized data — verify when something seems off. Prefer re-listing over using a memorized ID that might be stale.
Format / Example
# Agent Messenger Memory
## KakaoTalk Account
- User ID: `1234567890`
- Device type: tablet
## Chat Rooms
- `9876543210` — Work group chat (Alice, Bob, Charlie)
- `1111111111` — 1:1 with Alice
- `2222222222` — Family group
## Aliases
- "work" → `9876543210` (Work group chat)
- "alice" → `1111111111` (1:1 with Alice)
## Notes
- User prefers --pretty output
- Work chat is the most frequently used
Memory lets you skip repeated
chat listcalls. When you already know a chat ID from a previous session, use it directly.
Commands
Auth Commands
# Login as sub-device (recommended)
agent-kakaotalk auth login
agent-kakaotalk auth login --email <email> --password <password>
agent-kakaotalk auth login --device-type pc --force
agent-kakaotalk auth login --debug
# Check auth status
agent-kakaotalk auth status
# Remove stored credentials
agent-kakaotalk auth logout
agent-kakaotalk auth logout --account <account-id>
# List all stored accounts
agent-kakaotalk auth list
agent-kakaotalk auth list --pretty
# Switch the current account
agent-kakaotalk auth use <account-id>
# Check status of specific account
agent-kakaotalk auth status --account <account-id>
# Remove specific account
agent-kakaotalk auth logout --account <account-id>
Whoami Command
# Show current authenticated user
agent-kakaotalk whoami
agent-kakaotalk whoami --pretty
agent-kakaotalk whoami --account <account-id>
Output includes:
user_id— your KakaoTalk user IDnickname— your display nameprofile_image_url— profile image thumbnail URLoriginal_profile_image_url— original profile image URLstatus_message— your status messageaccount_display_id— your KakaoTalk ID (may be null if not set)background_image_url— background image URLoriginal_background_image_url— original background image URLfullname— real name (may be null)account_email— account email (may be null)pstn_number— phone number (may be null)email_verified— whether email is verified (may be null)
Chat Commands
# List all chat rooms (sorted by most recent activity)
agent-kakaotalk chat list
agent-kakaotalk chat list --pretty
agent-kakaotalk chat list --account <account-id>
agent-kakaotalk chat list --account <account-id> --pretty
# Resolve user-set room titles via CHATINFO (one extra LOCO call per chat;
# slower, but matches the room name shown in the official KakaoTalk app)
agent-kakaotalk chat list --resolve-titles
Output includes:
chat_id— numeric chat room IDtype— chat type (1:1, group, open chat)display_name— comma-separated member namestitle— user-set room title (only populated with--resolve-titles; otherwisenull). For open chats (OM/OD) without a user-set title, falls back to the OpenLink room name (one extraINFOLINKLOCO call per such chat).active_members— number of active membersunread_count— unread message countlast_message— most recent message preview, includingauthor_namewhen the sender's nickname is known from the chat list (otherwisenull)
Chat Leave
# Leave a chat room (works on 1:1, group, open, and PlusChat rooms)
agent-kakaotalk chat leave <chat-id>
agent-kakaotalk chat leave <chat-id> --pretty
agent-kakaotalk chat leave <chat-id> --account <account-id>
Output (JSON by default; --pretty pretty-prints the same JSON):
{ "success": true, "status_code": 0, "chat_id": "9876543210" }
The process exits non-zero when success is false.
Member Commands
# List all members of a chat room (read-only: CHATINFO + GETMEM, each read twice)
agent-kakaotalk member list <chat-id>
agent-kakaotalk member list <chat-id> --pretty
agent-kakaotalk member list <chat-id> --account <account-id>
# Return what could be read even if it is not confirmed complete
agent-kakaotalk member list <chat-id> --allow-partial
# Opt in to entering the room (CHATONROOM) when the read-only list is incomplete
agent-kakaotalk member list <chat-id> --allow-room-entry
agent-kakaotalk member list <chat-id> --allow-room-entry --allow-partial
By default member list fails (non-zero exit, error on stderr) unless the
member records match the chat's active member count and stay stable across
both reads. In some large open chats GETMEM returns fewer records than the
active member count, and members may also join or leave while the list is
read; either way the default command fails rather than returning an
incomplete list.
--allow-partialprints a snapshot object instead of a bare array, and
returns it even when it is incomplete:
```json
{
"chat_id": "9876543210",
"active_members": 1414,
"members": [{ "user_id": "1234567890", "nickname": "Alice", "...": "..." }],
"complete": false,
"consistency_basis": "stable_double_read_chatinfo_getmem",
"incomplete_reason": "member_count_mismatch"
}
```
incomplete_reason is member_count_mismatch (reads were stable but the
returned member set or count does not match the active roster, e.g. a
displayed member ID is missing) or membership_changed (the reads
disagreed, e.g. someone joined or left). It is absent when complete is
true. Always check complete before treating the list as the full roster.
--allow-room-entrylets an incomplete read-only list be filled from the
room's member id list (CHATONROOM), resolving ids GETMEM did not return
with MEMBER (100 ids per request). Output stays a bare array unless
--allow-partial is also given; consistency_basis is then
chatonroom_ids_member_batch. Side effect: CHATONROOM is the
room-entry command and can advance this account's unread state for the
chat (the chat may show as read). It is only sent when the read-only list
is incomplete.
Agent rule: Do not pass --allow-room-entry unless the user accepts that
the chat may be marked as read. Use --allow-partial when a best-effort
roster is enough, and never treat a complete: false result as the full
member list (for example, to decide that someone is not in the chat).
Each member includes:
user_id— numeric user ID (string for safety)nickname— display name in this chat (open chats may differ from the user's main Kakao nickname)profile_image_url,full_profile_image_url,original_profile_image_urlstatus_message,country_isouser_type— KakaoTalk's user type (100 = friend, 1000 = open profile, etc.);nullwhen the server omits the fieldopen_token,open_profile_link_id,open_permission— open-chat-only fields (nullfor normal chats;open_permissionis 1=OWNER, 2=NONE, 4=MANAGER, 8=BOT)
SDK-only:
KakaoTalkClient.getMembersByIds(chatId, userIds)is available for the >100-member case where you already have specific user IDs to resolve (typically from a CHATONROOMmiarray). It is not exposed as its own CLI command;member list --allow-room-entryuses it internally. Useagent-kakaotalk member listfor the common case.
Open Chat Moderation (Kick)
Open chats (오픈채팅) only. The account must be the room's host or a co-host. The open chat link ID is resolved from the chat ID automatically; regular chats fail with Chat <chat-id> is not an open chat before any moderation packet is sent. Only member kick (KICKMEM) has been used against a live server; the member kick-list (KLSYNC) and member unkick (KLDELITEM) request shapes and the kick-list response fields are unverified.
# Preview only: without --force, prints a warning and exits 1 without connecting
agent-kakaotalk member kick <chat-id> <user-id>
# Kick a member (IRREVERSIBLE — also blocks them from rejoining via the link)
agent-kakaotalk member kick <chat-id> <user-id> --force
agent-kakaotalk member kick <chat-id> <user-id> --force --pretty
agent-kakaotalk member kick <chat-id> <user-id> --force --account <account-id>
# List members on the room's kick list (blocked from rejoining)
agent-kakaotalk member kick-list <chat-id>
agent-kakaotalk member kick-list <chat-id> --pretty
agent-kakaotalk member kick-list <chat-id> --account <account-id>
# Remove a member from the kick list so they can rejoin (does not re-add them)
agent-kakaotalk member unkick <chat-id> <user-id>
agent-kakaotalk member unkick <chat-id> <user-id> --pretty
agent-kakaotalk member unkick <chat-id> <user-id> --account <account-id>
Get <user-id> from member list (user_id) or from message list (author_id).
member kick without --force:
{
"warning": "Kicking is irreversible and blocks the member from rejoining. Use --force to confirm.",
"action": "kick",
"chat_id": "9876543210",
"user_id": "1234567890"
}
member kick --force and member unkick:
{ "success": true, "status_code": 0, "chat_id": "9876543210", "user_id": "1234567890" }
member kick-list:
{
"success": true,
"status_code": 0,
"chat_id": "9876543210",
"members": [{ "user_id": "1234567890", "nickname": "Alice", "chat_id": "9876543210", "kicked_at": null }]
}
nickname,chat_id,kicked_atarenullwhen the server omits them.- When the server rejects the request (for example, the account is not the host or a co-host), the output has
success: falseand the server's non-zerostatus_code, and the process exits non-zero.kick-listreturns an emptymembersarray in that case. - If a successful
kick-listresponse has nokickMembersarray, the command fails withget_kick_list_failedinstead of reporting an empty list, because the response shape is unverified.
Agent rule: Never pass --force to member kick unless the user explicitly asked to kick that specific member. Confirm the target with member list first.
Message Commands
Uncertain sends are not automatically replayed by default. delivery_unknown
means the message may already have been delivered. Explicitly opt into one retry
only when duplicate delivery is acceptable:
agent-kakaotalk message send <chat-id> "Hello" --retry-unknown-delivery
agent-kakaotalk message upload <chat-id> ./report.pdf --retry-unknown-delivery
The opt-in can duplicate messages or uploads; it does not retry every provider
rejection or generic error. See Pattern 11 in references/common-patterns.md.
SDK protocol-field defaults/overrides and evidence limits are documented in
# List messages in a chat room
agent-kakaotalk message list <chat-id>
agent-kakaotalk message list <chat-id> -n 50
agent-kakaotalk message list <chat-id> --from <log-id>
agent-kakaotalk message list <chat-id> --pretty
# Read history losslessly, oldest first, one page at a time
agent-kakaotalk message page <chat-id> --from <log-id>
agent-kakaotalk message page <chat-id> --from <log-id> -n 50
agent-kakaotalk message page <chat-id> --pretty
# Send a text message
agent-kakaotalk message send <chat-id> "Hello world"
agent-kakaotalk message send <chat-id> "Hello world" --pretty
# Send a quoted reply to a specific message (use a log_id from `message list`)
agent-kakaotalk message send <chat-id> "Replying to this" --reply-to <log-id>
# Mention (tag) a member; the text must contain @<name>
agent-kakaotalk message send <chat-id> "@Alice hello" --mention <user-id>
agent-kakaotalk message send <chat-id> "@Alice hello" --mention <user-id>:Alice
# Send a quoted reply when you already have the target message (no history lookup)
agent-kakaotalk message send <chat-id> "Replying to this" \
--reply-to-json '{"log_id":"<log-id>","author_id":<author-id>,"message":"<target text>","type":1}'
# Send a file (auto-routes by MIME: photo / video / audio / generic file)
agent-kakaotalk message upload <chat-id> ./photo.jpg
agent-kakaotalk message upload <chat-id> ./clip.mp4
agent-kakaotalk message upload <chat-id> ./voice.m4a
agent-kakaotalk message upload <chat-id> ./report.pdf
# Send a multi-photo gallery (2+ images in one message)
agent-kakaotalk message upload <chat-id> ./img1.jpg ./img2.jpg ./img3.jpg
# Force a specific kind (override auto-routing)
agent-kakaotalk message upload <chat-id> ./clip.mp4 --as file # send as generic file, not video
agent-kakaotalk message upload <chat-id> ./image --as photo # extension-less file
agent-kakaotalk message upload <chat-id> ./data.bin --mime application/octet-stream
# Mark messages as read up to a given log ID
agent-kakaotalk message mark-read <chat-id> <log-id>
agent-kakaotalk message mark-read <chat-id> <log-id> --pretty
agent-kakaotalk message mark-read <chat-id> <log-id> --link-id <li> # open chats only
# Show the typing indicator ("..." dots) in a chat room for ~5s
agent-kakaotalk message typing <chat-id>
agent-kakaotalk message typing <chat-id> --pretty
agent-kakaotalk message typing <chat-id> --link-id <li> # open chats only
# Use a specific account
agent-kakaotalk message list <chat-id> --account <account-id>
agent-kakaotalk message page <chat-id> --from <log-id> --account <account-id>
agent-kakaotalk message send <chat-id> "Hello" --account <account-id>
agent-kakaotalk message upload <chat-id> ./photo.jpg --account <account-id>
agent-kakaotalk message mark-read <chat-id> <log-id> --account <account-id>
agent-kakaotalk message typing <chat-id> --account <account-id>
message send prints the send result (success, status_code, chat_id, log_id, sent_at). Like upload, mark-read, and typing, the process exits non-zero when success is false, so shell scripts can branch on the exit code as well as on the JSON.
Replying to a Message
--reply-to <log-id> sends the text as a quoted reply that references an existing message. Get the log_id from message list output. The CLI looks up the target in the chat's recent history (latest 100 messages) to build the quote, so the target must be reasonably recent. If it is not there, the command fails with code: "reply_target_not_found" without sending.
# Find the message you want to reply to
agent-kakaotalk message list <chat-id> -n 50
# Reply to it by its log_id
agent-kakaotalk message send <chat-id> "Good point!" --reply-to 1234567890
If the log_id is not found in the latest 100 messages, the command errors out without sending.
--reply-to-json <json> skips that lookup when you already hold the target message, for example a message event from the listener or a row from an earlier message list. Pass a JSON object with log_id, author_id, message, and type (the listener event calls it message_type). Extra fields such as author_name are ignored, so a message list row works as is. Because nothing is looked up, the target can be older than the latest 100 messages, and the send needs no MCHATLOGS/SYNCMSG round trips. The CLI does not check that the target exists or that the fields match it: the quote shows whatever you pass.
# Reply to a message you already have, even an old one
agent-kakaotalk message send <chat-id> "Good point!" \
--reply-to-json '{"log_id":"3947068532267313155","author_id":7,"message":"original text","type":1}'
# Pipe a row straight from message list
TARGET=$(agent-kakaotalk message list <chat-id> -n 1 | jq -c '.[0]')
agent-kakaotalk message send <chat-id> "Replying to the latest message" --reply-to-json "$TARGET"
- Ids may be decimal strings or bare JSON integers. Integers larger than
Number.MAX_SAFE_INTEGER(reallog_ids, open-chatauthor_ids) are parsed exactly, never rounded. - The optional
link_idis the open chat's link id. Leave it out and the CLI resolves it the same way as for--reply-to; pass it only for open chats, because the CLI writes it as given. --reply-toand--reply-to-jsoncannot be combined. A malformed object (bad JSON, a missing or non-integer id, amessagethat is neither a string nor null, a non-integertype) errors out without sending.
In open chats (오픈채팅) the reply also carries the room's link id as src_linkId. The CLI resolves it on its own: from the login snapshot when the room is there, otherwise through a read-only CHATINFO lookup that does not change read state. You never pass --link-id for a reply. The open-chat reply bubble itself has not been checked against a live server yet.
A send counts as delivered only when the server returns a non-zero log_id. A WRITE acknowledgment with status_code: 0 but log_id: "0" is reported as "success": false and the process exits non-zero, because no message was created.
Mentioning Users
--mention <user-id> tags a member so KakaoTalk renders the @name as a mention and notifies them. The text must already contain @<name> for every mentioned user. Repeat the flag to tag several users. The CLI also accepts --mention together with --reply-to, but mentions inside a quoted reply have not yet been verified against a live server.
# Name is looked up from the chat's member list (the member's nickname in this chat)
agent-kakaotalk message send <chat-id> "@Alice the build is green" --mention 1234567890
# Pass the name explicitly as <user-id>:<name> (no member lookup)
agent-kakaotalk message send <chat-id> "@Alice @Bob standup in 5" --mention 1234567890:Alice --mention 2345678901:Bob
# Mention inside a quoted reply
agent-kakaotalk message send <chat-id> "@Alice agreed" --reply-to <log-id> --mention 1234567890:Alice
- A bare
<user-id>is resolved to that member's nickname in the chat. If the nickname cannot be resolved, the command errors out without sending; pass<user-id>:<name>instead. - Every mentioned
@<name>must appear in the text as a whole tag. If one is missing, the command errors out without sending and names the missing@<name>. A Latin name followed directly by another Latin letter or digit does not count (@Kimberlydoes not tagKim). - Two different users with the same name cannot be told apart, so the command errors out without sending.
- The same user can be tagged more than once in one message; each
@<name>occurrence is tagged. - Output is the same send result as a plain
message send.
Sending Attachments
message upload sends photos, videos, audio, and arbitrary files to a chat. The CLI sniffs the MIME type from the filename and dispatches to the matching KakaoTalk message type, so the common case is a single command and a file path:
agent-kakaotalk message upload <chat-id> ./report.pdf
Routing rules:
| Filename / MIME | Sent as | KakaoTalk renders it as |
| --- | --- | --- |
| image/* (.jpg, .png, .gif, .webp) | photo | Inline image with tap-to-zoom |
| video/* (.mp4, .mov, .webm) | video | Inline player with play button |
| audio/* (.m4a, .mp3, .wav, .ogg) | audio | Voice-message bubble with waveform |
| anything else | file | Generic file attachment with download icon |
Multi-photo galleries (one message that contains several images): pass 2+ files and the CLI uses the gallery flow automatically.
agent-kakaotalk message upload <chat-id> ./img1.jpg ./img2.jpg ./img3.jpg
Override the auto-routing with --as <photo|video|audio|file|multi> when you need explicit control — for example, to send an .mp4 as a generic downloadable file instead of an inline video. Use --mime <type> to override MIME detection (handy for extension-less files or when the caller knows better than the filename).
Output (JSON by default; --pretty pretty-prints the same JSON):
{ "success": true, "status_code": 0, "chat_id": "9876543210", "log_id": "3846830417126748160", "sent_at": 1779509936 }
The process exits non-zero when success is false.
Notes:
- All attachment kinds use the same SHIP / POST / COMPLETE LOCO pipeline (and MSHIP / MPOST / FORWARD for multi-photo). The server registers the chatlog itself once the upload finishes; no follow-up text message is needed.
- KakaoTalk caps single-message attachment sizes server-side (currently ~300MB for files, ~20MB per image in multi-photo). The CLI surfaces the server's status code on rejection.
- Filenames are preserved on the recipient side for
filekind, used as a display label foraudio, and ignored forphoto/video(the client renders the bytes directly). - Each upload opens one fresh TCP+LOCO connection per attachment. Multi-photo opens N connections in parallel.
Read Status
The read-status API is SDK-only: getReadWatermarks(chatId) seeds each member's
last-read log_id, and computeReadStatus(...) reports who has read a message.
A member counts as having read it iff watermark >= log_id; always exclude the
message sender (and any other caller-selected IDs) from the calculation.
getReadWatermarks sends CHATONROOM, a room-entry call that may clear your own
unread count (#315), and the server returns watermarks only on the first
CHATONROOM for a chat in a session. Call it once per chat per LOCO session.
The result is a snapshot the SDK never updates: store it yourself and advance
each watermark from listener read events (DECUNREAD pushes), only ever
forward. Do not poll CHATONROOM. On disconnected, drop the stored
watermarks; after the reconnect you may seed each chat once again.
Mark as Read
message mark-read sends a LOCO NOTIREAD packet to advance the server-side read watermark for a chat. The watermark is a log_id — typically the latest message's log_id from message list — not a timestamp.
Output (JSON by default; --pretty pretty-prints the same JSON):
{ "success": true, "status_code": 0, "chat_id": "9876543210", "watermark": "123456789" }
The process exits non-zero when success is false so shell scripts can branch on it.
Notes:
- Caller-driven and explicit — there is no auto-mark-on-receive behavior. Blind acking incoming messages would be a distinct behavioral fingerprint against an undocumented protocol and is intentionally out of scope.
- Observed in testing on a sub-device tablet slot (the default
agent-messengerslot). KakaoTalk does not support third-party clients; server behavior may vary by chat type, account region, or client version. Use sparingly; avoid tight loops. - The phone's home-screen OS unread badge may lag until the phone client foregrounds; the in-app counter updates faster. Observed quirk, not a guaranteed contract.
- For open chats (오픈채팅) pass
--link-id <li>(thelifield on the open chat). Without it the server returns a non-zerobody.status, which the CLI reports as"success": falsewith the server's status code, and exits non-zero.
Typing Indicator
message typing sends one LOCO ACTION packet (typing subtype) so the other members see the animated "..." indicator. It does not create a message and does not change read state.
Output (JSON by default; --pretty pretty-prints the same JSON):
{ "success": true, "status_code": 0, "chat_id": "9876543210" }
Errors are printed as {"error": "..."} (plus code when available, see Error Handling) and the process exits non-zero:
- A non-zero LOCO status from the server is reported as
{"error": "ACTION failed: statusCode=<n>"}. - A non-numeric
<chat-id>or--link-idis rejected before the typingACTIONis sent (invalid_chat_id/invalid_link_id).
Notes:
- One pulse lasts about 5 seconds on the recipient's client. To keep the indicator up while you prepare a long reply, call it again every few seconds and stop once the reply is sent.
- Each CLI invocation logs in and opens its own LOCO connection. For frequent pulses (for example re-firing every 3s), prefer the SDK (
client.sendTyping()on one long-lived client) over calling the CLI repeatedly. - For open chats pass
--link-id <li>(thelifield on the open chat), the same valuemark-readtakes. The CLI does not look it up for you; for normal chats leave it out. - Like every LOCO write, this is an unofficial protocol call from a sub-device slot. Send it only when you are actually about to reply; avoid tight loops.
Message List Output
Each message includes:
log_id— unique message identifiertype— message type (1 = text, 2 = photo, 3 = video, 5 = audio, 12 = sticker, 18 = file, 20 = animated sticker, 27 = multi-photo, etc.)author_id— sender's user IDauthor_name— sender's nickname when known from the chat list (otherwisenull; only the room's "display members" are cached)message— message text content (empty string for non-text messages like stickers)attachment— parsed JSON metadata for non-text messages (e.g. photo URL/dimensions, sticker path), ornullfor plain text. Shape varies bytype; treat as an opaque object and narrow per message type.sent_at— Unix timestamp (milliseconds)mentions— present only when the message tags users:[{ "user_id": "1234567890", "at": [1], "len": 5 }].user_idis the tagged user as an exact decimal string,atlists which@characters inmessage(1-based, counting every@) start that user's tag, andlenis the tagged name's length without the@. (Observed live only for a single leading mention,at: [1]; the ordinal rule for multiple@characters is not yet verified.)scope— (optional) raw chat-log scope number, included only when the server sends it. Observed values:1for ordinary messages,3for open-chat thread replies. This mapping is observed behavior, not a documented contract.thread_id— (optional) raw chat-log thread id as an exact decimal string, omitted when absent or zero. For open-chat thread replies it has been observed to equal the parent message'slog_id.prev_id— (optional) raw chat-log previous log id as an exact decimal string, omitted when absent or zero.
Fetching More Messages
The CLI handles internal pagination automatically. Just increase -n to get more messages. Pagination is capped at ~4,000 raw messages (50 pages × 80 per page). If the cap is hit, a warning is printed to stderr and results may be incomplete.
# Get latest 20 messages (default)
agent-kakaotalk message list 9876543210
# Get 50 messages
agent-kakaotalk message list 9876543210 -n 50
# Get 200 messages
agent-kakaotalk message list 9876543210 -n 200
# Get messages newer than a known log ID (forward only)
agent-kakaotalk message list 9876543210 --from 123456789
message list --from returns the latest N messages after the cursor. If more than N messages arrived since that point, the older ones in between are not in the output. When you need every message after a known point (catching up, collecting a range for a summary), use message page instead.
Paging History Without Gaps
message page returns one page of messages strictly after --from <log-id>, sorted oldest first. It never drops the middle of a range: if more than -n messages are available, it returns the oldest -n and sets complete to false, so you continue from next_cursor.
| Flag | Default | Description |
| ---- | ------- | ----------- |
| --from <log-id> | start of available history | Exclusive cursor. Only messages with a larger log_id are returned. |
| -n, --count <number> | 100 | Page size, an integer from 1 to 100. Other values are rejected before login. |
| --account <id> | current account | Use a specific KakaoTalk account. |
| --pretty | off | Pretty print JSON output. |
Output:
{
"messages": [
{
"log_id": "123456790",
"type": 1,
"author_id": 1234567890,
"author_name": "Alice",
"message": "Hello",
"attachment": null,
"sent_at": 1700000000000
}
],
"next_cursor": "123456790",
"complete": false
}
messages— same fields asmessage list(see Message List Output), oldest first.next_cursor—log_idof the last message in this page. Pass it as the next--from.nullwhen the page is empty.complete—truewhen nothing newer than this page was available at read time. Whenfalse, call again with--from <next_cursor>.
CURSOR=123456789
while :; do
PAGE=$(agent-kakaotalk message page 9876543210 --from "$CURSOR") || exit 1
echo "$PAGE" | jq -c '.messages[]'
[ "$(echo "$PAGE" | jq -r '.complete')" = "true" ] && break
NEXT=$(echo "$PAGE" | jq -r '.next_cursor // empty')
[ -z "$NEXT" ] && { echo "message page: complete=false but no next_cursor; history may be incomplete" >&2; exit 1; }
CURSOR=$NEXT
done
Notes:
- Each CLI call logs in once. For long catch-ups prefer larger pages (
-n 100, the default) or the SDK'sclient.getMessagePage()on one long-lived client. - Reads use
MCHATLOGS, falling back toCHATINFO+SYNCMSG. Neither enters the room (CHATONROOM), so paging does not change read state. - Errors are printed as
{"error": "..."}and the process exits non-zero (for example an invalid--count, a non-numeric<chat-id>, an empty or non-numeric--from, or a non-zero LOCO status).
Output Format
JSON (Default)
All commands output JSON by default for AI consumption:
{
"chat_id": "9876543210",
"type": 2,
"display_name": "Alice, Bob",
"title": null,
"active_members": 3,
"unread_count": 5,
"last_message": {
"author_id": 1111111111,
"author_name": "Alice",
"message": "Hello everyone!",
"sent_at": 1705312200000
}
}
Pretty (Human-Readable)
Use --pretty flag for formatted output:
agent-kakaotalk chat list --pretty
Global Options
| Option | Description |
| ----------- | ------------------------------------------------------------ |
| --account | Use a specific KakaoTalk account (default: current account) |
| --pretty | Human-readable output instead of JSON |
Common Patterns
See references/common-patterns.md for typical AI agent workflows.
Templates
See templates/ directory for runnable examples:
post-message.sh- Send messages with error handlingmonitor-chat.sh- Monitor a chat for new messageschat-summary.sh- Generate chat summary
Error Handling
Errors raised while a command runs go through the shared error handler: they are printed to stderr as JSON and the process exits non-zero:
{
"error": "LOCO packet timeout: GETMEM (15000ms)"
}
Some failures do not go through that handler, so check the exit code first and read both streams:
- Missing or unknown account (
--accountnot found, no stored account) prints{"error": "..."}to stdout and exits 1. - Missing credentials are checked before any non-
authcommand runs. That failure is printed to stderr as plain text (not JSON) and exits 1. authsubcommands report their failures (and non-interactiveauth loginnext-action steps) as result JSON on stdout; check that JSON rather than expecting the shared stderr format.member kickwithout--force, andsuccess: falseresults frommessage upload,message mark-read,message typing,member kick,member kick-list, andmember unkickprint their result JSON to stdout and exit 1.message sendprints its result JSON to stdout but currently exits 0 even when the result reportssuccess: false. Check thesuccessfield of its output.
When the underlying error carries a machine-readable code, it is included as code. Branch on code rather than matching the English error text, which may change. Errors without a code (like the one above) omit the field.
{
"error": "Reply target log-id 1234567890 not found in the latest 100 messages of chat 9876543210",
"code": "reply_target_not_found"
}
Codes you are likely to see:
delivery_unknown— a send was written but not confirmed. The message may have been delivered; checkmessage listbefore resending.invalid_access_token— the stored token was rejected (server status -950). Runauth login.login_rejected— the server rejected the login with another status (see the message).invalid_mention— a--mentiontarget's@<name>is not in the text. Nothing was sent.reply_target_not_found— the--reply-tolog-id is not in the latest 100 messages. Nothing was sent; use--reply-to-jsonfor older messages.invalid_chat_id/invalid_link_id/invalid_log_id— a numeric argument was malformed. Nothing was sent.
Common errors:
No KakaoTalk credentials found— not authenticated. Runauth login.bad_credentials— wrong email or password. Cached credentials from the desktop app may be stale. Ask the user to provide credentials manually with--emailand--password.login_failed— device slot conflict or unknown login error. Run with--debugfor the full server response.passcode_request_failed— failed to request device verification code.registration_timeout— passcode expired before user confirmed on phone.login_http_error— network issue reaching KakaoTalk servers.LOCO packet timeout— messaging protocol timed out (server may be overloaded). A send that was already written times out asdelivery_unknowninstead.Message text does not contain "@<name>" for user .../Could not resolve a nickname for --mention ...— a--mentiontarget's@<name>is not in the text, or its nickname could not be looked up. Nothing was sent. Fix the text or pass--mention <user-id>:<name>.member_snapshot_changed_or_incomplete—member listcould not confirm a complete, stable member list (membership changed during the read, or the server returned fewer member records than the active count). Retry once; if it keeps failing, use--allow-partialfor a best-effort list, or--allow-room-entryif the user accepts that the chat may be marked as read.
Configuration
Credentials stored in ~/.config/agent-messenger/kakaotalk-credentials.json (0600 permissions). See references/authentication.md for format and security details.
Config format:
{
"current_account": "1234567890",
"accounts": {
"1234567890": {
"account_id": "1234567890",
"oauth_token": "...",
"user_id": "1234567890",
"refresh_token": "...",
"device_uuid": "...",
"device_type": "tablet",
"created_at": "2025-01-15T10:30:00.000Z",
"updated_at": "2025-01-15T10:30:00.000Z"
}
}
}
SDK: Programmatic Usage
KakaoTalkClient is available as a TypeScript SDK for building scripts and automations.
Setup
import { KakaoTalkClient } from 'agent-messenger/kakaotalk'
const client = await new KakaoTalkClient().login()
Or with manual credential management:
import { KakaoTalkClient, KakaoCredentialManager } from 'agent-messenger/kakaotalk'
const manager = new KakaoCredentialManager()
const account = await manager.getAccount()
if (!account) throw new Error('Not authenticated')
const client = await new KakaoTalkClient().login({ oauthToken: account.oauth_token, userId: account.user_id, deviceUuid: account.device_uuid })
For caller-managed token renewal, use the explicit SDK primitive:
import { refreshKakaoOAuthToken } from 'agent-messenger/kakaotalk'
if (!account.refresh_token) throw new Error('No KakaoTalk refresh token')
const refreshed = await refreshKakaoOAuthToken({
accessToken: account.oauth_token,
refreshToken: account.refresh_token,
deviceUuid: account.device_uuid,
})
const nextAccount = {
...account,
oauth_token: refreshed.accessToken,
refresh_token: refreshed.refreshToken,
updated_at: new Date().toISOString(),
}
// Persist nextAccount atomically before another client uses this credential.
// The refresh primitive intentionally does not write credential files or retry login.
Kakao can rotate the refresh token. Never refresh a copied production credential and discard the returned token set. See references/authentication.md for error codes and the controlled canary procedure.
Example
try {
// Get your profile
const profile = await client.getProfile()
// List chats
const chats = await client.getChats()
// Send a message
if (chats.length === 0) throw new Error('No chats found')
const chatId = chats[0].chat_id
const result = await client.sendMessage(chatId, 'Hello from SDK!')
// Send a file (photo / video / audio / file auto-routed by MIME). Pass
// an array to send several at once — all-image arrays become a gallery.
const photo = await Bun.file('./photo.jpg').bytes()
await client.sendAttachment(chatId, photo, 'photo.jpg')
// Read messages
const messages = await client.getMessages(chatId, { count: 50 })
// Reply to a message by quoting it
const target = messages[messages.length - 1]
await client.sendMessage(chatId, 'Replying to your last message', {
replyTo: { log_id: target.log_id, author_id: target.author_id, message: target.message, type: target.type },
})
// Optional: pass link_id (open chats) to skip the link id lookup
} finally {
// Always close when done (LOCO TCP connection)
client.close()
}
Full API Reference
See the KakaoTalk SDK documentation for complete method signatures, types, schemas, and examples.
Limitations
- Auto-extraction of email/password from the desktop app is macOS and Windows only (KakaoTalk desktop is not available on Linux). Linux users must pass
--emailand--password(or--password-file) explicitly — the LOCO protocol, login flow, and all messaging features work on Linux. - No chat room creation
- No friend list management
- No reactions or emoji
- No message editing or deletion
- No open chat (오픈채팅) browsing or joining. Moderation is limited to kicking members and managing the kick list (
member kick,member kick-list,member unkick) - No search across chats
- Stickers / emoticons cannot be sent (inbound stickers expose pack/path metadata, but the sticker store requires desktop-app purchase flows the SDK does not replicate). Photos, videos, audio, and arbitrary files can both be received and sent — see