Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ This is a TypeScript CLI for Microsoft Teams that talks directly to the internal
### Key design details

- `sendMessage()` wraps content in `<p>` tags and generates a random 19-digit `clientmessageid` using BigInt
- Channel replies use `replyToMessage()` and `POST /conversations/{encodeURIComponent(channelId + ";messageid=" + rootMessageId)}/messages`, with `conversationid` set to the channel and `replyChainId` set to the original post ID. This endpoint and linkage were observed in the Teams web client's reply request. Never fall back to a top-level send on failure.
- `getThreadMessages()` reads that same root-scoped conversation. The CLI exposes `reply <channel> <root-message-id> <message>`, `messages --thread <root-message-id>`, and opt-in `messages --ids`. Reply/thread helpers validate channel IDs (`@thread.tacv2`) and positive decimal root IDs before HTTP requests. Channel-wide results may mix posts and replies; `watch` remains flat and unchanged.
- `createDmThread()` uses `POST /threads` (without `/users/ME`) with `uniquerosterthread: true` for idempotent 1:1 chat creation
- `searchPeople()` uses Substrate Suggestions API (`/search/api/v1/suggestions?scenario=peoplepicker.newChat`), same endpoint as the Teams web client people picker
- `getMyMri()` extracts the user's MRI from the ic3 JWT token's `oid` claim — no extra API call needed
Expand All @@ -47,6 +49,8 @@ This is a TypeScript CLI for Microsoft Teams that talks directly to the internal
- System conversations (ID prefix `48:`) are filtered out of chat listings
- Login uses a **persistent browser profile** (`~/.teams-cli/browser-profile/`) so session cookies survive for silent token refresh
- Expired tokens are automatically refreshed via headless Playwright before each command — no user interaction unless the session itself has expired
- Login/refresh must ignore expired or invalid MSAL cache entries and select the newest unexpired audience match. Token presence alone is not proof of login. Both browser flows close their persistent context on failure; failed login preserves existing session data.
- Auth also captures the CSA inventory audience (`chatsvcagg.teams.microsoft.com`). `getToken(name, true)` can explicitly refresh a missing configured resource using an existing saved sign-in; the default missing-token behavior is unchanged. Opt-in refresh waits for that resource as well as chat. CSA is not an IC3 token and has no public CLI command/client.
- Playwright is dynamically imported at runtime (`await import("playwright")`) so it's not required at install time
- Native `fetch` is used for all HTTP calls (no external HTTP library needed with Node 18+)
- **Meeting transcripts** (`recordings`/`transcript` commands) use the SharePoint Stream API, not Graph:
Expand Down
25 changes: 23 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ Log in by launching a browser session. Sign in as you normally would (including
teams login
```

Tokens are stored in `~/.teams-cli/tokens.json`. Token lifetimes vary by API (the chat token lasts ~24 hours, the search token ~1.5 hours). Expired tokens are refreshed automatically via a headless browser using your saved session cookies — no manual re-login needed unless the session itself has expired.
Tokens are stored in `~/.teams-cli/tokens.json`. Token lifetimes vary by API and tenant policy. Expired tokens are refreshed automatically via a headless browser using your saved session cookies — no manual re-login needed unless the session itself has expired. Login and refresh wait for an **unexpired** token and prefer the newest valid audience match; stale browser-cache entries do not count as a successful sign-in. Failed login preserves the existing browser profile and saved tokens.

## Usage

Expand All @@ -65,6 +65,11 @@ teams messages a1b2
# Send a message
teams send a1b2 "Hello from the CLI"

# Show message IDs, then reply under an existing channel post
teams messages "19:example-channel@thread.tacv2" --ids
teams reply "19:example-channel@thread.tacv2" 1700000000000 "Reply from the CLI"
teams messages "19:example-channel@thread.tacv2" --thread 1700000000000 --ids

# Find a person by name or email
teams find "Jane Smith"

Expand Down Expand Up @@ -121,6 +126,22 @@ teams search "budget" --limit 10

Run `teams --help` or `teams <command> --help` for full details.

### Channel threads

`teams reply <channel> <root-message-id> <message>` replies under an existing
channel post. Use the **original post's** decimal message ID, not a reply's ID.
`messages --ids` displays IDs; `messages --thread <root-message-id>` retrieves
that thread (including its root when present in the returned page). Full channel
IDs ending in `@thread.tacv2`, or cached short IDs resolving to them, are supported.
Normal `send` behavior is unchanged; it does not attach a channel message to a post.

Channel-wide message retrieval can contain both posts and replies in a flat list.
The default output and `watch` do not group messages by thread or display parent
linkage. Use `messages --thread` to read a particular thread. Retrieval remains
limited to the requested page size; there is no automatic history pagination.
`watch` is unchanged and has no dedicated `--thread` option or new channel-reply
delivery guarantee. The reply API is undocumented and may change.

## Development

```sh
Expand All @@ -140,7 +161,7 @@ npm run dev -- chats
## How it works

1. `teams login` opens Chromium via Playwright, navigates to Teams, and waits for you to complete sign-in
2. Auth tokens are extracted from the browser's `localStorage` (three tokens: chat, search, presence) along with your region
2. Available auth tokens are extracted from the browser's `localStorage` (chat, search, presence, and CSA inventory) along with your region. CSA is captured for integrations; it does not add a public inventory command. Integrations may explicitly request acquisition of a missing configured token with `getToken(name, true)`, using the existing saved sign-in; normal missing-token behavior is unchanged.
3. CLI commands use these tokens to call the Teams Chat Service API (`teams.cloud.microsoft/api/chatsvc/`) and the Substrate Search API (`substrate.office.com`) directly via `fetch`
4. The `teams chats` command caches the conversation list locally so you can reference chats by short ID in subsequent commands
5. The `teams dm` command searches for a user via the Substrate Suggestions API, creates a 1:1 thread via `POST /threads`, and sends the message — all in one step
Expand Down
28 changes: 22 additions & 6 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,24 +28,25 @@ All constants live here: file paths, token audience strings, API headers, defaul

Key values:
- `DATA_DIR` — `~/.teams-cli/`, where tokens and caches are stored
- `TOKEN_AUDIENCES` — maps token names (`ic3`, `search`, `presence`) to the localStorage key patterns used to find them
- `TOKEN_AUDIENCES` — maps token names (`ic3`, `search`, `presence`, `csa`) to the localStorage key patterns used to find them. CSA targets `chatsvcagg.teams.microsoft.com` for integrations; no public CSA API client or command is exposed.
- `CLIENT_INFO` — the `clientinfo` header that the chatsvc API requires

### auth.ts

Handles token persistence, automatic refresh, and the Playwright login flow.

- `saveTokens()` / `loadTokens()` — JSON round-trip to `~/.teams-cli/tokens.json`
- `getToken()` — check token expiry, attempt silent refresh if expired, and retrieve by name
- `getToken()` — check token expiry, attempt silent refresh if expired, and retrieve by name. Optional `refreshMissing=true` also acquires a missing configured audience using a saved sign-in, waiting for the requested resource as well as chat. Defaults and behavior without a saved sign-in are unchanged.
- `getSharepointToken(host, recordingUrl)` — returns a cached SharePoint token for `host`, or acquires one via `acquireSharepointToken()` (drives the headless profile to the host root to bootstrap a SharePoint session via SSO, intercepts the `Bearer` token off an `/_api/` request, and caches it with the JWT's `exp`; the recording link is a fallback warmup)
- `getRegion()` — returns the user's region code (e.g. `au`, `amer`) extracted during login
- `getMyMri()` — extracts the current user's MRI (`8:orgid:{oid}`) by decoding the `oid` claim from the ic3 JWT token using `Buffer.from(payload, 'base64url')`. Used by the `dm` command to construct thread creation requests.
- `tryRefresh()` — silently refreshes expired tokens by launching a headless Chromium with the persistent browser profile (`~/.teams-cli/browser-profile/`). MSAL re-acquires tokens using the stored session cookies — no user interaction needed. Returns `true` on success, `false` if the session itself has expired.
- `tryRefresh()` — silently refreshes expired tokens by launching a headless Chromium with the persistent browser profile (`~/.teams-cli/browser-profile/`). MSAL re-acquires tokens using the stored session cookies — no user interaction needed. Returns `true` after capturing an unexpired chat token, otherwise `false` with a safe lifecycle diagnostic.
- Browser token selection rejects expired/invalid entries and chooses the newest valid audience match. Login/refresh polling waits for that valid token, not merely a cache key. Browser contexts close on all exit paths; failed login retains the existing profile/token file. Refresh failures report a safe lifecycle stage without printing credentials.
- `login()` — the interactive login flow:
1. Launches Chromium (headless=false) with a persistent browser profile so session cookies are preserved
2. Navigates to `teams.cloud.microsoft`
3. Polls `localStorage` every 2 seconds for up to 5 minutes until the IC3 token appears
4. Extracts all three tokens (ic3, search, presence) and the region from `localStorage`
3. Polls `localStorage` every 2 seconds for up to 5 minutes until an unexpired IC3 token is available
4. Extracts available unexpired tokens (ic3, search, presence, csa) and the region from `localStorage`
5. Saves everything to disk
- `logout()` — removes stored tokens and the browser profile directory

Expand All @@ -72,6 +73,8 @@ Async functions that make HTTP calls via the `ApiClient` wrapper. Each function

Key design decisions:
- `sendMessage()` wraps content in `<p>` tags and generates a random 19-digit `clientmessageid` using BigInt arithmetic, matching the Teams web client's behaviour
- `replyToMessage()` posts to a root-scoped channel conversation: `/conversations/{encodeURIComponent(channelId + ";messageid=" + rootMessageId)}/messages`. The payload includes the channel's `conversationid`, the original post's `replyChainId`, and `formatVariant: "TEAMS"`, matching the observed web reply request. The API response is not itself proof of linkage; verify the retrieved reply's `conversationLink` identifies the requested root. Errors propagate without retrying as a top-level post.
- `getThreadMessages()` reads the same scoped conversation. Shared validation rejects non-channel/compound IDs and non-positive/non-decimal root IDs before fetching. Channel-wide message retrieval may include replies as well as posts; thread retrieval filters by the requested root and retains normal page-size limits.
- `getThreadMembers()` uses the `/threads/{id}` endpoint rather than `/conversations/{id}/members` (which returns 404)
- `searchMessages()` builds the full Substrate Search API request body including correlation IDs and dimension metadata
- `searchPeople()` uses the Substrate Suggestions API (`/search/api/v1/suggestions?scenario=peoplepicker.newChat`) — the same people picker endpoint the Teams web client uses when composing a new chat
Expand Down Expand Up @@ -109,6 +112,12 @@ The chat index system works by having `teams chats` cache its formatted output t

The `watch` command uses an async poll loop, creating a fresh `ApiClient` per iteration because tokens may be refreshed between polls.

`reply <channel> <root-message-id> <message>` explicitly targets an existing
channel post. `messages --ids` adds message IDs without changing default display;
`messages --thread <root-message-id>` retrieves one channel thread. Neither
default message display nor `watch` groups replies or exposes parent linkage.
There is no dedicated thread-watch option or automatic thread-history pagination.

## API surfaces

The CLI talks to four separate Microsoft APIs, each requiring its own auth token:
Expand All @@ -119,7 +128,7 @@ The primary API for conversations, messages, and members.

- Base URL: `https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME`
- Token audience: `ic3.teams.office.com`
- Used by: `chats`, `messages`, `send`, `dm` (thread creation + send), `watch`, `activity`, `members`
- Used by: `chats`, `messages` (including `--thread`), `send`, `reply`, `dm` (thread creation + send), `watch`, `activity`, `members`

### Substrate Search API

Expand Down Expand Up @@ -153,9 +162,16 @@ Tests are organized to match the module structure:

- `formatting.test.ts` — unit tests for all pure formatting functions (27 tests). No mocking needed.
- `auth.test.ts` — tests token persistence, expiry, and JWT parsing using `vi.mock` to redirect file I/O to temp directories (9 tests). Does not test the Playwright login/refresh flows directly.
- `auth-refresh.test.ts` — mocks Playwright and browser storage to cover stale-cache rejection, newest-valid selection, waiting for renewed tokens, malformed/boundary expiry, browser cleanup, and preservation of saved sessions after unsuccessful login.
- `api.test.ts` — tests API functions using mocked `ApiClient.fetch` (6 tests). The chatsvc base URL is patched to a fixed value.
- `cli.test.ts` — tests command registration and structure (2 tests).

Channel reply coverage checks the encoded root-scoped endpoint, explicit payload
linkage, invalid inputs, HTTP error propagation without top-level fallback,
thread retrieval, CLI argument routing, and unchanged default send/read behavior.
Live thread verification must compare the reply's `conversationLink` with the
original root and retrieve that root's thread; a successful POST alone is insufficient.

The Playwright login flow is not unit-tested since it requires a real browser and user interaction. It's verified manually.

## Data flow example
Expand Down
18 changes: 17 additions & 1 deletion skills/teams-cli/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ Returns a table with short IDs (like `a1b2`), chat name, type, last message prev
```bash
teams messages <chat_id> # Read 20 most recent messages
teams messages <chat_id> -n 40 # Read 40 messages
teams messages <channel_id> --ids # Include message IDs
teams messages <channel_id> --thread <root_message_id> --ids
```
`<chat_id>` is either a short ID from `teams chats` or a full conversation ID (e.g. `19:abc@thread.v2`). Messages are shown oldest-first.

Expand All @@ -49,6 +51,18 @@ teams send <chat_id> "Your message here"
```
Sends a message to an existing conversation. Always confirm with the user before sending.

### Reply to a channel post
```bash
teams reply <channel_id> <root_message_id> "Your reply here"
```
Use the original channel post's decimal ID from `messages --ids`, not a reply's
ID. Channel IDs must end in `@thread.tacv2` (cached short IDs are also resolved).
Confirm the channel, original post, and reply text with the user before sending.
`send` does not target a post; never use it as a fallback for a failed reply.
Channel-wide messages may mix posts and replies in a flat list; use
`messages --thread` to read a particular thread. `watch` remains unchanged and
has no dedicated thread option.

### Search messages
```bash
teams search "quarterly report" # Search across all chats
Expand Down Expand Up @@ -121,7 +135,9 @@ Known limitations to set expectations with the user:
1. Run `teams chats` to find the conversation
2. Run `teams messages <short_id>` to read recent context
3. Draft a reply and confirm with the user before sending
4. Run `teams send <short_id> "message"`
4. For chat messages, run `teams send <short_id> "message"`. For a channel post,
identify the original root with `messages --ids` and run
`teams reply <channel_id> <root_message_id> "message"`.

### "Message someone I haven't chatted with"
1. Run `teams find "their name"` to look them up
Expand Down
54 changes: 54 additions & 0 deletions src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,60 @@ export async function sendMessage(
return (await jsonOrThrow(resp)) as Record<string, unknown>;
}

function channelThreadId(channelId: string, rootMessageId: string): string {
if (!/^19:[\w-]+@thread\.tacv2$/.test(channelId)) {
throw new Error(
"Thread replies require a channel ID ending in @thread.tacv2.",
);
}
if (!/^[1-9]\d*$/.test(rootMessageId)) {
throw new Error("Root message ID must be a positive decimal message ID.");
}
return encodeURIComponent(`${channelId};messageid=${rootMessageId}`);
}

export async function getThreadMessages(
client: ApiClient,
channelId: string,
rootMessageId: string,
pageSize = 20,
): Promise<Record<string, unknown>[]> {
return getMessages(
client,
channelThreadId(channelId, rootMessageId),
pageSize,
);
}

export async function replyToMessage(
client: ApiClient,
channelId: string,
rootMessageId: string,
content: string,
): Promise<Record<string, unknown>> {
const threadId = channelThreadId(channelId, rootMessageId);
if (!content.trim()) {
throw new Error("Reply message must not be empty.");
}
const resp = await client.fetch(
`${client.baseUrl}/conversations/${threadId}/messages`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
content: `<p>${content}</p>`,
messagetype: "RichText/Html",
contenttype: "Text",
clientmessageid: randomClientMessageId(),
conversationid: channelId,
replyChainId: rootMessageId,
properties: { formatVariant: "TEAMS" },
}),
},
);
return (await jsonOrThrow(resp)) as Record<string, unknown>;
}

export async function getThreadMembers(
client: ApiClient,
conversationId: string,
Expand Down
Loading