@sayknow-cli/coding-agent 0.7.14 → 0.7.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,22 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.7.16] - 2026-11-03
6
+
7
+ ### Fixed
8
+
9
+ - Upgrading now replaces a Telegram daemon that is already running from an older release, so the rejected-token poll pause from 0.7.15 takes effect without a manual daemon restart. The daemon serving epoch moves to 4 and the generation to 32; the next session start reloads an epoch-3 daemon.
10
+
11
+ ## [0.7.15] - 2026-11-03
12
+
13
+ ### Added
14
+
15
+ - The bundled `emil-design-eng` skill now carries mandatory rules for faux product UI (hero demos, feature cards, bento grids, cursor walkthroughs), adapted from Benji Taylor's [Stageshow](https://benji.org/stageshow) (MIT). Depicted UI feedback keeps the skill's existing timing and easing; only storytelling motion runs slower. For a faux UI build the agent installs the full Stageshow skill and kit into the project itself. Prompts such as "hero demo", "bento grid", "mocked dashboard", "제품 데모" now route to the skill.
16
+
17
+ ### Fixed
18
+
19
+ - The Telegram daemon no longer polls `getUpdates` every second when Telegram rejects the bot token (401 revoked or 404 deleted bot). Polling pauses with exponential backoff (1 minute up to 30 minutes), the rejection is logged once with a re-pair hint, and `skc notify health` reports a `telegram_auth` error until a poll succeeds or the bot is re-paired.
20
+
5
21
  ## [0.7.14] - 2026-11-02
6
22
 
7
23
  ### Changed
@@ -15,5 +15,7 @@ export interface DaemonPaths {
15
15
  steal: string;
16
16
  aliases: string;
17
17
  seenUpdates: string;
18
+ /** Present while the running daemon's bot token is rejected by Telegram (401/404). */
19
+ authRejected: string;
18
20
  }
19
21
  export declare function daemonPaths(agentDir: string): DaemonPaths;
@@ -41,11 +41,16 @@ export declare const NOTIFICATION_PROTOCOL_VERSION = 3;
41
41
  * and capability-versioned mixed-host compatibility.
42
42
  * Generation 31 lets a Windows controller wait for a cooperative stop and has
43
43
  * the owner watch its control request during a long poll (upstream #6174).
44
+ * Generation 32 pauses getUpdates with backoff while Telegram rejects the bot
45
+ * token and records the rejection for `skc notify health`, so an upgraded host
46
+ * reloads a predecessor that would otherwise poll a revoked token every second.
44
47
  */
45
- export declare const DAEMON_GENERATION = 31;
48
+ export declare const DAEMON_GENERATION = 32;
46
49
  /**
47
50
  * Serving-compatibility boundary for daemon lifecycle requests. Epoch 1 covers
48
51
  * all builds published before this field existed; epoch 2 covered generation 29;
49
- * bump this to force serving convergence and reload of compatible live predecessors.
52
+ * epoch 3 covered generations 30-31; epoch 4 reloads those predecessors into
53
+ * generation 32 so a revoked bot token stops being polled every second.
54
+ * Bump this to force serving convergence and reload of compatible live predecessors.
50
55
  */
51
- export declare const SERVING_EPOCH = 3;
56
+ export declare const SERVING_EPOCH = 4;
@@ -641,12 +641,18 @@ export declare class TelegramBotTransport implements BotApi {
641
641
  noRetry?: boolean;
642
642
  }): Promise<unknown>;
643
643
  }
644
+ export interface TelegramAuthRejection {
645
+ errorCode: number;
646
+ description: string;
647
+ }
644
648
  export type TelegramUpdateOutcome = "consumed" | "retry";
645
649
  export type TelegramPollResult = {
646
650
  kind: "success";
647
651
  updateCount: number;
648
652
  } | {
649
653
  kind: "aborted";
654
+ } | {
655
+ kind: "auth_paused";
650
656
  } | {
651
657
  kind: "getUpdates_failed";
652
658
  error: string;
@@ -654,7 +660,10 @@ export type TelegramPollResult = {
654
660
  kind: "api_failure";
655
661
  errorCode?: number;
656
662
  description: string;
657
- } | {
663
+ } | ({
664
+ kind: "auth_rejected";
665
+ retryInMs: number;
666
+ } & TelegramAuthRejection) | {
658
667
  kind: "conflict";
659
668
  description: string;
660
669
  backoffMs: number;
@@ -668,6 +677,8 @@ export interface TelegramUpdatePollerOptions {
668
677
  };
669
678
  processUpdate: (update: unknown) => Promise<TelegramUpdateOutcome>;
670
679
  health?: TelegramPollHealth;
680
+ /** Called on each transition into (rejection) or out of (undefined) the auth-rejected state. */
681
+ onAuthRejected?: (rejection: TelegramAuthRejection | undefined) => void;
671
682
  }
672
683
  export declare class TelegramPollHealth {
673
684
  #private;
@@ -854,6 +865,8 @@ export declare class TelegramNotificationDaemon {
854
865
  private readonly selectedAckPending;
855
866
  private readonly pool;
856
867
  private readonly poller;
868
+ /** Serializes auth-rejected marker writes so a quick reject→recover cannot reorder. */
869
+ private authMarkerWrite;
857
870
  private readonly dispatchState;
858
871
  /** Bot-wide flood-control window; inbound polling remains eligible during it. */
859
872
  private botCooldownUntil;
@@ -957,6 +970,11 @@ export declare class TelegramNotificationDaemon {
957
970
  private readonly callBotApiClassified;
958
971
  private botApiWithOutcomeCollector;
959
972
  constructor(opts: TelegramDaemonOptions);
973
+ /**
974
+ * Persist the auth-rejected verdict for offline `notify health`, keyed by the
975
+ * token fingerprint so a re-paired config ignores a predecessor's marker.
976
+ */
977
+ private recordAuthRejected;
960
978
  private createSessionRouter;
961
979
  loadAliases(): Promise<void>;
962
980
  persistAliases(): Promise<void>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@sayknow-cli/coding-agent",
4
- "version": "0.7.14",
4
+ "version": "0.7.16",
5
5
  "description": "Sayknow-CLI CLI with read, bash, edit, write tools and session management",
6
6
  "homepage": "https://sayknow-cli.com",
7
7
  "author": "jaybeyond",
@@ -54,12 +54,12 @@
54
54
  "@agentclientprotocol/sdk": "1.3.0",
55
55
  "@babel/parser": "^7.29.3",
56
56
  "@mozilla/readability": "^0.6.0",
57
- "@sayknow-cli/stats": "0.7.14",
58
- "@sayknow-cli/agent-core": "0.7.14",
59
- "@sayknow-cli/ai": "0.7.14",
60
- "@sayknow-cli/natives": "0.7.14",
61
- "@sayknow-cli/tui": "0.7.14",
62
- "@sayknow-cli/utils": "0.7.14",
57
+ "@sayknow-cli/stats": "0.7.16",
58
+ "@sayknow-cli/agent-core": "0.7.16",
59
+ "@sayknow-cli/ai": "0.7.16",
60
+ "@sayknow-cli/natives": "0.7.16",
61
+ "@sayknow-cli/tui": "0.7.16",
62
+ "@sayknow-cli/utils": "0.7.16",
63
63
  "@puppeteer/browsers": "^2.13.0",
64
64
  "@types/turndown": "5.0.6",
65
65
  "@xterm/headless": "^6.0.0",
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Benji Taylor
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -25,6 +25,21 @@ loose companion files here expecting them to be readable at runtime.
25
25
  | [emilkowalski/skills](https://github.com/emilkowalski/skills) | MIT (`LICENSE.emilkowalski`), Copyright (c) 2026 Emil Kowalski | `emil-design-eng`, `animate`, `review-animations`, `improve-animations`, `find-animation-opportunities`, `pick-ui-library`, `prototype`, `mobile-native`, `animation-vocabulary`, `apple-design`, `ask-sonner` |
26
26
  | [Appllama/appllama-skills](https://github.com/Appllama/appllama-skills) | MIT (`LICENSE.appllama`) | `appllama-app-design-skill` |
27
27
 
28
+ ## SKC overlays
29
+
30
+ `scripts/ui-skill-overlays/<skill>.md` holds SKC-authored sections that the
31
+ generator splices into a vendored skill right after its `## SKC invocation`
32
+ block, so a regeneration keeps them.
33
+
34
+ | Overlay | Adapted from | License |
35
+ | --- | --- | --- |
36
+ | `emil-design-eng`: "Faux product UI (Stageshow) — mandatory" | [benjitaylor/skills `stageshow`](https://github.com/benjitaylor/skills/tree/main/stageshow) at `8020574` ([write-up](https://benji.org/stageshow)) | MIT (`LICENSE.benjitaylor`), Copyright (c) 2026 Benji Taylor |
37
+
38
+ Only the rules are adapted. The Stageshow kit, examples and filming scripts are
39
+ not vendored (they are React/TS sources, not readable from an embedded skill);
40
+ the overlay tells the agent to install the full skill into the user's project
41
+ with `npx -y skills@latest add benjitaylor/skills --skill stageshow -a universal -y`.
42
+
28
43
  ## Deliberate exclusions
29
44
 
30
45
  - `write-swift`, `animate-expo` (emilkowalski) — not web frontend craft.
@@ -11,6 +11,78 @@ SKC loads this skill automatically for matching frontend UI/UX work.
11
11
  Do not wait for a follow-up question. Apply the craft rules immediately
12
12
  and keep going on the user's actual task.
13
13
 
14
+ ## Faux product UI (Stageshow) — mandatory
15
+
16
+ These rules are required whenever the deliverable is an illustration of a product rather than the product itself: a fake or mocked UI, a hero or feature-card demo, a bento tile, a cursor walkthrough, a product shot for a marketing or docs page, or a still or looping animation of an app, phone, terminal or dashboard. They do not apply to building the real interface; the rest of this skill governs that.
17
+
18
+ Adapted from [Stageshow](https://benji.org/stageshow) by Benji Taylor (MIT).
19
+
20
+ ### Use the Stageshow kit
21
+
22
+ The full Stageshow skill ships a React kit (stage, windows, phones, cursor, motion parts), gold examples and filming scripts that cannot be embedded here. For any faux UI build, install it into the user's project yourself with `npx -y skills@latest add benjitaylor/skills --skill stageshow -a universal -y`, load `stageshow` with the `skill` tool, and start from its closest gold example. Do not ask the user to run the install. If it fails (offline, blocked registry), say so once and apply the rules below by hand.
23
+
24
+ ### How this fits with the rest of this skill
25
+
26
+ - **Depicted UI feedback stays real.** A press, menu, tooltip or toggle inside the demo follows this skill: under 300ms, ease-out custom curves, `scale(0.97)` on press, never from `scale(0)`. Only storytelling motion (travel, arrivals, camera, holds) runs slower; that is the "Marketing/explanatory" row of the duration table.
27
+ - **Stagger** stays 40-80ms between items in a scene, inside this skill's 30-80ms band. Tiles of a grid are the one exception: 80-120ms apart.
28
+ - **Reduced motion** shows the demo's poster frame: a complete still that tells the story with the result on screen. Movement is dropped, not the payoff.
29
+ - **Frequency rule.** A demo loop is decorative and rarely seen; it never blocks interaction and never reacts to the page's keyboard input.
30
+ - **Review output** still uses the Before/After/Why table from Review Format.
31
+
32
+ ### The one idea
33
+
34
+ **It reads as a real product, simplified to what the viewer needs, framed with intent, and every motion has a cause.**
35
+
36
+ Five ways it fails:
37
+
38
+ - **Too much.** Real text in every row, numbers everywhere, everything packed. The more detail, the more it looks generated.
39
+ - **Wireframe.** Two gray blobs and a button: built too small, or stripped of what made it recognizable.
40
+ - **Boxed.** A whole window shrunk into a card with even margins, like a pasted screenshot.
41
+ - **Flat.** Every object the same weight in the same bordered card; the eye has nowhere to land.
42
+ - **Bland.** A gray window with a cursor whatever the brief said. The brief's look and energy are the point.
43
+
44
+ The fix: a full, structured screen in quiet grays, real words only where the story is (usually 3 to 7 strings), placeholder lines for the rest, room to breathe, and a crop that puts the eye on the story. Simplify the words, not the context.
45
+
46
+ ### Workflow (decide before writing code)
47
+
48
+ 1. **Medium and place.** Still or animation (loop, once in view, hover); where it sits and at what size. Design at the shown size (about 720 × 340 beside copy, 900-1100 wide full-width, 400 × 300 for a card) and ship a redesigned compact version for a 358px phone column.
49
+ 2. **Look.** Map the product's real tokens, icons and chrome. Otherwise pick a theme (light, dark, blueprint, glass), a palette (accent or mono) and a fidelity (minimal, standard, realistic). A brief with a style gets that style in full.
50
+ 3. **Story.** Three to five beats and a payoff, 10 to 16 seconds. No cursor move you cannot explain. Data never rewinds in view without a cause. Between a richer story and a calmer frame, choose the frame.
51
+ 4. **Start from the closest example** and decide the crop before building, so nothing past the crop gets built.
52
+ 5. **Screen.** Spend the word budget on the story; mark what the cursor touches and measure positions, never hard-code them.
53
+ 6. **Choreograph.** Keep elements mounted so exits animate. Animate the relationship, not just the object: a new row carries the rows below it. Beats overlap, groups stagger, the payoff holds, and the loop ends where it began or resets with a visible cause.
54
+ 7. **Rehearse.** Set the poster frame first. Film the whole loop at the shown width and at 390, step through every press, menu, morph and the loop seam, fix the largest fault first (framing, then hierarchy, then motion, then polish), and compare against the closest gold example.
55
+
56
+ ### Framing
57
+
58
+ - One hero object, at most one or two satellites of different kinds. A satellite straddles the hero's edge about half outside and covers chrome, not content.
59
+ - Crop only filler. The payoff, the action, cursor targets and every real word stay whole. Crop 10-40% of the hero off stage; it fills at least two thirds of the stage width and runs off an edge.
60
+ - The stage masks everything. One gutter, measured in the final crop, on every edge: a full gutter or well past it, never just short.
61
+ - No plate behind a hero on a white or dark page, no window floating with air on four sides, no dead corners at any point in the loop.
62
+ - Real chrome only: no address bar on a native Mac app, no hand-drawn status bar or home indicator. Windows keep their device's shape.
63
+ - Start flat and frontal. Depth comes from shadow, z-order and scale; a tilt must be earned against the straight version.
64
+
65
+ ### Motion and the cursor
66
+
67
+ - Story motion uses two curves: travel `cubic-bezier(0.45, 0, 0.1, 1)`, arrival from nowhere `cubic-bezier(0.25, 0.8, 0.25, 1)` over 0.8-1s. Travel has a departure, clear travel and a soft arrival.
68
+ - Content moves instead of swapping; numbers roll only the digits that changed. Holding a result means stopping, with no new pulse.
69
+ - The cursor moves like a hand: shallow arcs timed by distance, presses you can see. It never covers the words it clicks, changes kind (I-beam, hand) by morphing as it crosses into an element, and every move travels to the next action. Use one cursor style per site; with no cursor, never walk a focus ring as a stand-in.
70
+ - On phones, use touch, not the macOS arrow, and act where people do: tap the notification, then act in the app.
71
+ - The camera needs a reason: push in only when the payoff is too small to read, once per story, in and back out.
72
+
73
+ ### Check before handing over
74
+
75
+ - Content that swaps instead of moving.
76
+ - Gray placeholder bars where the eye lands; filler belongs at the edges.
77
+ - A plate behind the window, or a window floating with air on four sides.
78
+ - Empty bands, cut controls or cut shadows.
79
+ - Stock AI marks and made-up logos: sparkles, purple, a letter in a colored square.
80
+ - Busy rows and uneven insets.
81
+ - Long holds, or a reset with no cause.
82
+ - A text selection that is not under the I-beam.
83
+ - A hand-drawn status bar or home indicator.
84
+ - A centered amount centered together with its sign.
85
+
14
86
 
15
87
  ## Core Philosophy
16
88
 
@@ -118,7 +118,7 @@ export const UI_SKILL_KEYWORD_DEFINITIONS: readonly UiSkillKeywordDefinition[] =
118
118
  skill: UI_SKILL_BASE,
119
119
  priority: 40,
120
120
  pattern:
121
- /\b(ui|ux|frontend|front-end|interface|design system|component|css|tailwind|styling|layout|responsive|modal|dropdown|tooltip|popover|drawer|button|spacing|typography)\b|프론트\s*엔드|프론트엔드|디자인\s*(시스템)?|컴포넌트|버튼|모달|드롭다운|툴팁|레이아웃|반응형|스타일링/i,
121
+ /\b(ui|ux|frontend|front-end|interface|design system|component|css|tailwind|styling|layout|responsive|modal|dropdown|tooltip|popover|drawer|button|spacing|typography)\b|\b(faux|fake|mock(ed)?) (ui|interface|app|dashboard)\b|\b(product|hero|cursor) (demo|shot|walkthrough|illustration)s?\b|\b(feature card|bento( grid)?|hero section)s?\b|프론트\s*엔드|프론트엔드|디자인\s*(시스템)?|컴포넌트|버튼|모달|드롭다운|툴팁|레이아웃|반응형|스타일링|목업|제품\s*(데모|소개\s*영상)|히어로|벤토|피처\s*카드/i,
122
122
  },
123
123
  ];
124
124
 
@@ -221,7 +221,7 @@ export function buildUiSkillDirectiveForSkill(skill: BundledSkcUiSkillName): str
221
221
  */
222
222
  export const BUNDLED_UI_SKILL_MEANINGS: Record<BundledSkcUiSkillName, string> = {
223
223
  "emil-design-eng":
224
- "General web UI/UX craft: building or reviewing components, layout, spacing, typography, design systems, CSS. The default for frontend work with no more specific fit.",
224
+ "General web UI/UX craft: building or reviewing components, layout, spacing, typography, design systems, CSS. The default for frontend work with no more specific fit. Also faux product UI for marketing and docs pages: hero demos, feature cards, bento grids, cursor walkthroughs, mocked app screenshots.",
225
225
  animate:
226
226
  "Adding new motion to a web UI: animations, transitions, easing, keyframes, hover effects, micro-interactions.",
227
227
  "review-animations": "Reviewing motion that already exists and judging whether it is good.",
@@ -97,7 +97,7 @@ export const EMBEDDED_DOCS: Readonly<Record<string, string>> = {
97
97
  "skc-session-clawhip-routing.md": "# Human-owned SKC tmux sessions\n\nA tmux-hosted SKC TUI is a **human-only terminal surface**. It is not an external control or viewing API.\n\n## Human operator use\n\nA human operator may start an interactive TUI in a dedicated worktree for local terminal visibility:\n\n```sh\n./scripts/skc-session/create.sh <session-name> <worktree-path>\n```\n\nThe person at that terminal interacts with the TUI directly. The helper retains durable, public owner-lifecycle receipts for local troubleshooting; it never accepts routed prompts, exposes pane output, or registers a machine observer.\n\n## External bots and machines\n\nAll external bots, machines, and automation must use a canonical external surface:\n\n- Coordinator MCP for bounded workflow control, turn status, questions, and reports.\n- ACP for an ACP client over the SDK-backed session surface.\n- The Sayknow-CLI SDK for authenticated lifecycle, control, and query operations.\n\nDo not inject prompts, scrape terminal output, or use tmux state as workflow evidence. Use Coordinator lifecycle events and SDK status for external decisions, notifications, and audit records.\n\n## Boundaries\n\n- Keep visible work in a dedicated worktree, never the shared canonical checkout.\n- Treat tmux existence and terminal output as human-only diagnostics.\n- Keep all bot credentials and routing configuration in the external Coordinator MCP/ACP/SDK deployment, not in the tmux helper.",
98
98
  "slack-onboarding.md": "# Slack notification onboarding\n\nThis is the managed Slack Socket Mode notification adapter. It is an SDK client:\nlocal SKC sessions continue to own loopback SDK endpoints, and Slack provides a\nper-session message thread for notifications and replies.\n\n## Prerequisites\n\nCreate a Slack app in the target workspace, enable Socket Mode, and create an\napp-level token with the Socket Mode connection scope. Install the app in the\nworkspace and invite it to the selected channel. Configure only the scopes and\nevent subscriptions the adapter needs:\n\n- `chat:write` to post session roots, replies, and closure markers\n- `channels:history` for a public channel, or the corresponding history scope\n for the channel type in use\n- the message event subscription for the selected channel type\n- Socket Mode enabled for Events API delivery\n\nKeep the selected channel private to people authorized to see local session\nmetadata. Do not add broad workspace scopes or use an app token for ordinary Web\nAPI calls.\n\n## Configure the adapter\n\n`skc notify setup slack` is non-interactive. It requires these flags:\n\n- `--slack-bot-token`\n- `--slack-app-token`\n- `--slack-workspace-id`\n- `--slack-channel-id`\n- `--slack-authorized-user-id` for the single Slack user authorized to submit replies and `/sdk` commands\n\nWithout `--slack-authorized-user-id`, the adapter remains outbound-only: every inbound envelope is acknowledged but denied before it can create a durable claim or reach an SDK endpoint. The user ID is an identifier, not a secret. It also accepts `--redact`. Provide secret values from an approved local secret mechanism, not shell history, committed configuration, tickets, screenshots, or chat. Setup writes:\n\n- `notifications.enabled = true`\n- `notifications.slack.botToken`\n- `notifications.slack.appToken`\n- `notifications.slack.workspaceId`\n- `notifications.slack.channelId`\n- `notifications.slack.authorizedUserId` when configured\n- `notifications.redact = true` when requested\n\n`skc notify status` masks all token values. It is status output, not a credential\nrecovery mechanism.\n\n## Socket Mode, threads, and resume\n\nThe daemon validates the configured workspace, channel, and paired user before durably claiming an inbound effect or sending its Socket Mode acknowledgement. The durable claim records the paired actor identity, replay identity, protected-effect reference, and captured endpoint generation; it never records Socket Mode cursors, endpoint tokens, or message bodies. Rejected, bot-authored, unauthorized, and already-claimed envelopes are acknowledged without an SDK endpoint call.\n\nAcknowledgement latency is therefore bounded by local durable-claim work rather\nthan SDK availability or command execution. After the ACK, the worker dispatches\nthe claimed effect asynchronously; a restart can replay the claim, and a retry\ncannot create a second injection. Do not treat an ACK as confirmation that the SDK\noperation completed.\n\nEach session starts with one root message. Root creation uses a caller-generated\nclient message ID and reconciliation lookup, preventing a duplicate root after\nan uncertain post. When a session closes, the daemon posts a closure marker. A\nresume starts a new immutable root, so replies to the old root are rejected and\ncannot steer the resumed session.\n\nEvents, retried deliveries, event contexts, and interaction/message identifiers\nare deduplicated in the durable claim before a reply is injected into the captured\ncurrent endpoint generation. After a Socket Mode reconnect, Slack may redeliver an\nenvelope; the new delivery is acknowledged after its claim is recognized and\ncannot cause a second injection.\n\n## Operational safety\n\nTreat rate limits, permission failures, and Socket Mode disconnects as transport\nfailures. Let the managed daemon reconnect or reconcile; do not run a competing\nSocket Mode consumer against the same app/state, manually modify conversation\nstate, persist delivery cursors, expose loopback endpoints, or use Slack as a\ngeneral remote shell.\n\nThe adapter only sends notifications and routes SDK replies. It does not support\nprovider registration, retaining endpoint credentials, or arbitrary remote\ncontrol.\n\n## Verification boundary\n\nAcceptance coverage uses an injectable fake Slack provider plus a production\nSession SDK host boundary proof. It covers durable-claim-before-acknowledgement\nfor accepted, rejected, duplicate, and reconnect-redelivered envelopes; root-post\nreconciliation; event/retry/context/interaction dedupe; generation and restart\nisolation; rate-limit/permission/disconnect failures; and the prohibition on\npersisted Socket Mode cursors. No live Slack credentials or workspace is required.\n",
99
99
  "standalone-mcp.md": "# Standalone MCP configuration\n\n`skc mcp add` writes only the definition supplied on that invocation to SKC's own MCP config (`~/.skc/agent/mcp.json` by default, or `./.skc/mcp.json` with `--project`). `skc mcp list` and `skc mcp remove` print redacted definitions. These commands are storage-only: normal standalone startup does not consume registered definitions.\n\n## Tool-result images\n\nSuccessful MCP tool results forward PNG, JPEG, GIF, and WebP images (including\nembedded resources with an image `mimeType` and base64 `blob`) to image-capable\nmodels on providers whose tool-result transport carries images. Providers that\nflatten tool results to text, including Kiro, receive the text markers instead.\nImages follow the text block in their original order. Text keeps an image\nor resource marker, with a coordinate-mapping note when an image is resized, and\nretains the untrusted-content wrapper. Forwarded images also carry an explicit\nnotice that they are untrusted server content and must be treated as data, not\ninstructions.\n\nImages use the built-in shared resizer: at most 1,568 pixels per dimension and\n500 KiB per image, with the same recompression and `SKC_NO_WEBP` behavior. Each\nresult attempts at most 16 supported images (matching the pasted-image count\nlimit), processes at most 16 MiB of base64 source data (the MCP response budget),\nand forwards at most 4 MiB of image-file bytes after resizing, before base64\nencoding. Before native decoding, source images must have dimensions no larger\nthan 8,192 pixels per side and no more than 16 million pixels total. Supported\nimage bytes determine the forwarded MIME type when a server mislabels an image.\nImages that are invalid, unsupported, or over these limits retain only their\ntext markers. Error results remain text-only. Models without\nimage input use the existing provider filtering and receive text instead of image\npayloads.\n\n## Use an explicit config\n\nA caller can opt one top-level standalone session into one trusted config file:\n\n```bash\nskc --mcp-config /absolute/path/to/mcp.json\n```\n\nThe path must be absolute and identify a regular file directly; symbolic links and other indirection are rejected. SKC reads the file through one open handle and rejects it if the path, file identity, size, or modification metadata changes during the read. It exposes only that file's MCP tools and owns the server processes for that session. It does not load server prompts, resources, instructions, sampling, or other config files. Expected read, parse, validation, and connection failures emit one sanitized warning and continue. Unexpected errors and final-catalog tool-name collisions clean up and abort startup.\n\nThere is no MCP config discovery or merge, reload while the session runs, subagent inheritance, or default behavior change. To use a stored registration, pass that exact stored config path with `--mcp-config`.\n\n## Supported integrations\n\n| Need | Use | Notes |\n| --- | --- | --- |\n| User trusts one MCP config for one standalone session | `skc --mcp-config /absolute/path/to/mcp.json` | Exact-file, top-level, tools-only opt-in; SKC owns cleanup. |\n| External bot or multi-session controller | [Coordinator MCP](./hermes-mcp-bridge.md) | Coordinator MCP exposes SKC lifecycle and coordination tools. |\n| External session control | [SDK machine interface](./sdk.md) | The SDK WebSocket protocol is the only external control interface. |\n| Editor/ACP client owns MCP servers | ACP via `skc --mode acp` or `skc acp` | ACP remains a stdio editor protocol. |\n| Codex / Claude Code delegation plugin | [Canonical sayknow-cli plugin](./hermes-mcp-bridge.md) | Installs Coordinator MCP plus SKC delegation commands. |\n\n## Example: free web search with Parallel\n\n[Parallel Search MCP](https://docs.parallel.ai/integrations/mcp/search-mcp) provides web search and page fetching over Streamable HTTP without an account or API key. Anonymous searches use Fast mode and have lower rate limits intended for exploration and light use.\n\nSearch objectives, queries, and fetch URLs are sent to Parallel when these tools are called; avoid including sensitive information.\n\nFrom the project where you want the tools, register the server:\n\n```bash\nskc mcp add parallel-search --project \\\n --type http --url https://search.parallel.ai/mcp \\\n --header 'User-Agent=sayknow-cli/parallel-search-mcp' \\\n --timeout 30000\nskc mcp list --project\n```\n\nThe registration is stored in `./.skc/mcp.json`. `list` confirms the stored definition and autoload eligibility; it does not test the remote connection. Start a new `skc` session in that project to load the server. The two tools are exposed as `mcp__parallel_search_web_search` and `mcp__parallel_search_web_fetch`. Use search for current information and fetch for a specific page that needs closer reading. Reuse one `session_id` across related calls in a conversation when supplying that optional argument.\n\nThis adds MCP tools alongside the built-in `web_search` tool; it does not select or configure the built-in Parallel API provider. Existing registrations are preserved, and an existing `parallel-search` entry is not overwritten unless you explicitly pass `--force`. Keep the positive timeout so remote discovery can complete in the background after the bounded startup wait described above. To remove the project registration:\n\n```bash\nskc mcp remove parallel-search --project\n```\n\n## Boundary\n\nStandalone SKC does not inherit arbitrary MCP server configurations from Claude Code, Codex, OpenCode, or other tools. MCP servers often carry credentials, filesystem reach, browser state, approval semantics, and lifecycle that belong to the configuring host.\n\n`--mode rpc`, `--mode rpc-ui`, and `--mode bridge` have been removed. Do not use the former RPC host-tool protocol to connect an MCP server; use the [SDK machine interface](./sdk.md) for supported external session control.\n\n## Related docs\n\n- [SDK machine interfaces](./sdk.md)\n- [Coordinator MCP bridge](./hermes-mcp-bridge.md)\n- [External control surface readiness](./external-control-readiness.md)",
100
- "telegram-onboarding.md": "# Telegram notification onboarding\n\nThis guide documents the bundled Telegram notification setup path from Sayknow-CLI\nsource. In an interactive SKC session, use `/settings` → **Notifications** as the\nrecommended path; `skc notify` remains the authoritative headless and automation\nfallback. It is for the managed reference client, not a separate remote-control\nproduct.\n\n## What you are setting up\n\nSayknow-CLI notifications are a loopback WebSocket SDK plus a managed Telegram\nreference daemon:\n\n- each SKC session publishes a local notification endpoint under\n `.skc/state/sdk/<sessionId>.json`;\n- the managed Telegram daemon scans those endpoints, connects to them, and sends\n action-needed events to the configured Telegram chat;\n- replies and inline button taps route back to the exact session/action through\n the same notification protocol. When the configured chat supports Telegram\n forum topics, each session is routed through its own topic.\n\nThe setup command stores global notification settings in your SKC agent config\nand later sessions auto-connect when notifications are enabled.\n\n## 1. Create a Telegram bot with BotFather\n\nUse Telegram's official BotFather flow to create a bot and copy its HTTP API\ntoken:\n\n- Official BotFather documentation: <https://core.telegram.org/bots/features#botfather>\n- General Telegram Bot API documentation: <https://core.telegram.org/bots/api>\n\nIn Telegram, open `@BotFather`, run `/newbot`, choose a display name and a unique\nusername ending in `bot`, then copy the token BotFather returns. Treat the token\nlike a password: do not paste it into logs, screenshots, issues, or shell history\nthat other people can read.\n\n## 2. Configure from `/settings` (recommended)\n\nIn an eligible running SKC session, open `/settings` and select the\n**Notifications** tab. It provides the interactive Telegram setup/reconfigure\nflow and the operational controls in one place:\n\n- Enable globally with stored credentials or disable globally;\n- turn notifications on or off for the current session only;\n- refresh or probe health, send a test notification, recover dead-owner\n artifacts, and reconnect the Telegram runtime;\n- remove Telegram credentials without removing configured Discord or Slack\n adapters.\n\nTelegram token entry is a masked setup field. After entry, the token is never\nprefilled, rendered, or shown by the tab; status and health use a masked value.\nThe tab also guides the BotFather Threaded Mode check and private-chat pairing.\n\n### CLI setup fallback\n\n`skc notify setup` retains the same setup workflow for terminal-driven setup and\nautomation:\n\n```sh\nskc notify setup\n```\n\nCurrent implementation path: `packages/coding-agent/src/cli/notify-cli.ts`.\n\nThe wizard does this:\n\n1. prompts for `Telegram BotFather token:`;\n2. validates the token with Telegram `getMe`;\n3. verifies private-chat Threaded Mode capability via `getMe.has_topics_enabled`\n and, when it is off in an interactive run, prints @BotFather guidance and\n lets you retry or continue unverified;\n4. asks you to message the bot from a private Telegram chat;\n5. polls Telegram `getUpdates` until it sees a private chat message;\n6. writes the paired chat id and enables notifications.\n\nThe setup pairing flow is private-chat only. If setup sees a `group`,\n`supergroup`, or `channel`, it rejects that chat and keeps waiting for a private\nDM. This is intentional for safe local discovery: group chats must not receive\nsession names, action ids, or pending status by accident.\n\nTelegram private-chat topics: the managed daemon's per-session delivery uses\nTelegram forum topics (`createForumTopic` + `message_thread_id`). Telegram now\nsupports forum topics in **private chats** when the bot owner enables **Threaded\nMode** for the bot in @BotFather. SKC cannot enable Threaded Mode through the Bot\nAPI; setup only detects the capability (`getMe.has_topics_enabled`) and guides the\nmanual BotFather toggle. A forum-enabled supergroup is no longer required.\n\nNote: enabling topics in private chats may require an additional Telegram Stars\npurchase fee, per Telegram's Terms of Service for Bot Developers.\n\nIf BotFather's **Bot Settings** menu does not show **Threads Settings** or\n**Threaded Mode**, do not treat that as a setup blocker. Telegram exposes this\ncapability unevenly across clients/accounts/bot states, and SKC cannot force the\nmenu to appear through the Bot API. The safe fallback is to continue setup with a\nprivate DM pairing: choose `skip` in the interactive prompt (or use\n`--token <botToken> --chat-id <chatId>` for non-interactive setup). SKC will save\n`threaded=unverified`/`threaded=unknown`, try topics at runtime when possible,\nand otherwise deliver flat to the paired private chat with outbound notifications\nand inline ask buttons only plus the one-time nudge shown below.\n\nSetup verification is capability verification, not a delivery guarantee: even when\nsetup reports `threaded=verified`, the first runtime `createForumTopic` for the\npaired chat can still fail if Telegram refuses it. When per-session topics are\nunavailable, the daemon does **not** drop notifications — it routes them to the\nnormal (flat) paired chat and posts a one-time nudge: `Flat Telegram private chat\nsupports outbound notifications and inline ask buttons only. Enable Threaded Mode\nin @BotFather > Bot Settings > Threads Settings for free-text replies and session\ncommands.` Because pairing is private-only, flat delivery lands in your own\nprivate DM with the bot.\n\nThe final setup line reports a `threaded=` status:\n\n- `threaded=verified`: the bot has Threaded Mode capability (`has_topics_enabled`\n was true during setup);\n- `threaded=unverified`: Threaded Mode was off and you skipped, or setup ran\n non-interactively; setup is saved, topics are attempted when available, and\n runtime delivery falls back to the paired flat private chat with outbound\n notifications and inline ask buttons only when Telegram refuses topic creation;\n- `threaded=unknown`: the Telegram response did not include `has_topics_enabled`,\n so capability could not be verified.\n\nAfter setup succeeds, it prints a masked token and the paired chat id:\n\n```text\nNotifications enabled. botToken=1234…(len N) chatId=123456789 threaded=verified\n```\n\nThe raw token is never printed by SKC status/setup output after it is stored.\n\n## 3. Non-interactive setup and CLI operations\n\nFor headless provisioning, scripts, and automation, the authoritative commands\nremain `skc notify setup`, `skc notify status`, `skc notify health`, `skc notify\ntest`, and `skc notify recovery`. The `/settings` tab does not replace these CLI\nsubcommands.\n\nFor scripts or CI-style local provisioning, pass the bot token and known private\nchat id explicitly. Non-interactive runs cannot prompt for the BotFather toggle,\nso if Threaded Mode is off (or the capability is unknown) setup is still saved\nwith a warning and a `threaded=unverified`/`threaded=unknown` status:\n\n```sh\nskc notify setup --token <botToken> --chat-id <chatId>\n```\n\nOptional redaction can be enabled during setup:\n\n```sh\nskc notify setup --token <botToken> --chat-id <chatId> --redact\n```\n\n`--redact` sets `notifications.redact = true`. Under redaction, idle summaries\nand streamed content are suppressed before remote delivery, but ask questions and\noptions remain readable because they must be answerable remotely.\n\n## 4. Check status without leaking secrets\n\n```sh\nskc notify status\n```\n\nThe status command reads the typed notification settings and prints:\n\n- `enabled`\n- masked `botToken`\n- paired `chatId`\n- `redact`\n\nIt uses the same masking helper as setup (`first 4 chars + … + length`), so it is\nsafe to paste into a support thread if the chat id itself is not sensitive in\nyour environment.\n\n## 5. Global configuration, adapters, and precedence\n\nTelegram credentials and all `notifications.*` values are **global-only**. SKC\nreads them from the user/global agent config with schema defaults; notification\nkeys from project config files are ignored, and runtime notification overrides\nare rejected. A project cannot supply, shadow, or disable an outbound\nnotification identity.\n\n`skc notify setup` writes these global Telegram settings through the SKC Settings\nlayer:\n\n- `notifications.enabled = true`\n- `notifications.telegram.botToken = <token>`\n- `notifications.telegram.chatId = <paired chat id>`\n- `notifications.redact = true` only when `--redact` was passed\n- `notifications.telegram.streaming.enabled = true` by default; set it to `false` to disable durable live Telegram assistant-output updates globally. `SKC_NOTIFICATIONS_STREAM=1` forces process-local streaming, while `0`, `off`, or `false` forces it off.\n\nA complete global configuration is `notifications.enabled` plus at least one\ncomplete adapter. Telegram needs its bot token and private-chat id; Discord and\nSlack each need their own credential and destination. Removing Telegram in\n`/settings` is adapter-local: it preserves a complete Discord or Slack adapter\nand global enablement, and disables global notifications only when Telegram was\nthe last complete adapter.\n\n\nThree lifecycle gates keep SDK hosting, setup, and managed delivery separate:\n\n1. An eligible host receives the dormant notification control surface. `SKC_NOTIFY=off`,\n `0`, or `false` is a hard process opt-out; unsupported hosts and\n helper/subagent sessions are also ineligible.\n2. Every eligible top-level session hosts its local SDK endpoint by default,\n independently of notification configuration. `SKC_SDK_DISABLE=1` opts out of\n SDK hosting for that session.\n3. A managed Telegram daemon is ensured only for a complete global Telegram\n configuration with managed delivery enabled. Discord-only, Slack-only, and\n environment-only sessions do not start a Telegram daemon.\n\nEnvironment/session precedence for managed delivery is implemented in\n`packages/coding-agent/src/sdk/bus/config.ts`:\n\nFor a SKC-spawned child, `notifications.sessionScope=primary` suppresses managed\nnotification delivery to avoid duplicate topics; `all` permits it.\n`SKC_NOTIFICATIONS=1` or `SKC_NOTIFICATIONS_TOKEN` explicitly opts that child in,\nbut never overrides a hard opt-out or a helper/subagent exclusion.\n\nManaged-delivery precedence is highest first; it does not change independently\nhosted SDK endpoints:\n\n1. `SKC_NOTIFY=off`, `0`, or `false` prevents the notification control surface\n for that process.\n2. `SKC_NOTIFICATIONS=0` is a hard managed-delivery opt-out.\n3. Local `/notify off` disables managed delivery only for the current session.\n4. `SKC_NOTIFICATIONS=1` or `SKC_NOTIFICATIONS_TOKEN` enables the legacy\n explicit managed-delivery path.\n5. A complete global configuration enables managed delivery automatically.\n6. Otherwise managed delivery stays off; the SDK endpoint remains hosted unless\n `SKC_SDK_DISABLE=1` is set.\n\n## 6. Start or reuse sessions\n\nAfter setup, start SKC normally:\n\n```sh\nskc --tmux\n```\n\nor use any other supported SKC launch mode. Every eligible top-level session\nwrites its SDK endpoint unless `SKC_SDK_DISABLE=1`; when managed Telegram\ndelivery is configured and enabled, it also ensures the Telegram daemon is running.\n\nThe managed daemon is a singleton per bot token/chat pair. Telegram allows only\none active `getUpdates` long-poll owner for a bot token, so SKC keeps a local\ndaemon lock/state file and makes later sessions attach to the fresh owner instead\nof starting a second poller. This avoids Telegram `409 Conflict` failures.\n\n### Same-token and foreign-owner safety\n\nSetup and reconfigure never compete with a live same-token daemon. When a live\nowner already has the stored paired chat, SKC reuses it after non-polling\nvalidation. If that owner has no stored chat or the chat changes, provide a\nvalidated private chat id; SKC performs zero `getUpdates` discovery polls. For a\nforeign or unknown owner, setup does not poll, kill, reload, or take over the\nowner; the default is to cancel before writing configuration.\n\nFor a Telegram-only setup, an explicit **Save inactive for later** choice may\nstore the credentials with notifications disabled. That choice is unavailable\nwhen a complete Discord or Slack adapter is active, because globally disabling\nnotifications would affect that adapter. A post-save identity race similarly\nstops the current session before reporting that activation is blocked; the\nforeign daemon remains untouched, and the editor offers an explicit restore or\nretain-configuration choice.\n\n## 7. Use the Telegram chat\n\nThe managed daemon prefers Telegram forum-topic delivery for per-session routing\nin the paired private chat. When Threaded Mode is available for the bot (verified\nduring setup via `getMe.has_topics_enabled`), the daemon calls\n`createForumTopic`/`editForumTopic` and sends messages with `message_thread_id`\nagainst the paired `notifications.telegram.chatId`. If BotFather does not show\n**Threads Settings**/**Threaded Mode**, or if Telegram refuses topic creation even\nafter setup reported `threaded=verified`, the daemon routes notifications to the\nnormal (flat) paired private chat and posts a one-time nudge to enable Threaded\nMode rather than dropping them.\n\n### Ask-control capability negotiation\n\nThe production Telegram multiplexer is\n`packages/coding-agent/src/sdk/bus/telegram-daemon.ts`. It already sends a\nprotocol-v3 ClientHello with `ask_controls_v1` and `ask_selected_ack_v1`. The\ngeneric `packages/coding-agent/src/sdk/bus/managed-daemon.ts` is\nliveness-only: it advertises `client_ping_pong` but is intentionally\nnon-capable for controlled asks.\n\nTelegram navigation controls appear only after `ask_controls_v1` is negotiated\non that session connection. A non-capable or older third-party client receives\nthe non-actionable `action_unavailable` diagnostic instead of a controlled ask\nwith stripped option buttons, so it cannot be left with unusable controls.\n\nFlat private chat is notification-only plus inline ask buttons. It is not a\nfree-text chat surface: replies typed as normal messages and session commands such\nas `/verbose`, `/lean`, `/verbosity`, and `/redact` require Threaded Mode/topic\nrouting.\n\nFlat private-chat fallback preserves outbound notifications and inline-button\nanswers, but it cannot provide a separate Telegram topic per SKC session. Free-\ntext replies and in-topic config commands depend on topic routing, so enable\nThreaded Mode in @BotFather > Bot Settings > Threads Settings when you need\nmulti-session reply separation or session commands from Telegram. Do not\npair a group, supergroup, or channel as a substitute: setup intentionally accepts\nonly a private DM, and hand-edited non-private chat ids remain fail-closed to\navoid leaking session data. If you specifically want group topics, create a\nforum-enabled Telegram group and use a separate/custom notification integration;\nthe bundled `skc notify setup` onboarding path is private-chat only.\n\nThe managed daemon can render:\n\n- session identity headers;\n- context updates;\n- live/finalized assistant output;\n- image attachments;\n- ask prompts with inline buttons;\n- activity/typing indicators;\n- inbound delivery acknowledgements.\n\nPer-tool activity is off by default so important notifications remain visible. This\nincludes `bash`, `read`, `task`, and subagent start/completion bubbles, including\nboth `ok` and `error` results. Send `/toolactivity on` in the paired private chat\nto opt in globally, or `/toolactivity off` to suppress these bubbles again. The\ntoggle is durable, works without an active SKC session, and has an equivalent\ncontrol under `/settings` → **Notifications** → **Preferences**. Turning it off\ndoes not affect assistant output, ask prompts, or session notifications.\n\nReply paths:\n\n- tap an inline button on an ask notification;\n- reply in the session topic with free text when forum-topic routing is\n available;\n- send in-topic config commands:\n - `/verbose` — per-tool-turn assistant text (and opt-in live streaming)\n - `/lean` — settled assistant answer when the agent reaches idle, plus immediate ask lead-ins (default; no intermediate tool-turn flood)\n - `/verbosity <lean|verbose>`\n - `/redact <on|off>`\n - `/btw <question>` is available only in an authorized, known private-session\n topic. It uses the current session context in an isolated side turn and never\n injects or persists either a user or assistant message in the main session\n history, so it can run while the main session is busy. It accepts no\n attachments; `/btw` with an attachment returns `Usage: /btw <question>`.\n Foreign bot-command suffixes are silently ignored.\n\n Each logical session permits at most two concurrent side questions. The host\n deadline is 120 seconds and cancels the actual provider work. Operational\n responses are: `Usage: /btw <question>` for an empty question; `Telegram\n /btw is disabled in local settings.` when disabled; `Restart this SKC session\n to enable /btw.` when the connected session does not support side turns; `Two\n /btw questions are already running. Wait for one to finish.` when busy; `This\n /btw question timed out after 120 seconds. Send it again to retry.` on\n timeout; `This /btw question stopped because the SKC session closed or\n changed. Reopen it and try again.` when stopped; and `This /btw question\n failed. Send it again to retry.` on failure.\n\n A transient reconnect to the exact session may deliver a result once.\n Graceful SKC or daemon shutdown cancels side questions. Crashes or identity\n changes do not promise delivery, and stale results are fenced.\n `/btw` rich replies use Telegram Bot API 10.1 Markdown only. An eligible,\n complete structured Markdown reply is sent once as\n `{rich_message:{markdown,skip_entity_detection:true}}`, correlated to the\n source message in the same topic; SKC does not send native `blocks` or\n `media`. Eligibility is conservative: valid Unicode; at most 32,768 scalars,\n 131,072 UTF-8 bytes, 500 blocks, 16 nesting levels, and 20 table columns.\n Tables and math use Telegram's 10.1 Markdown support. Ineligible content and\n a definite rich rejection use the existing correlated HTML delivery.\n Ambiguous rich outcomes never retry or fall back; `/rich off` keeps HTML-only\n behavior.\n- send paired-chat lifecycle commands from the Telegram command menu or by typing:\n - `/session_create path <dir>`\n - `/session_create worktree <repo> <branch>`\n - `/session_create dir <newdir>`\n - `/session_recent [create|resume]`\n - `/session_close <sessionId>`\n - `/session_resume <sessionId|prefix>`\n\nThe removed legacy `/answer <session-tag> <answer>` flow is not the primary UX;\nTelegram topic routing identifies the target session when the configured chat\nsupports it.\n### `/btw` operational rollback\n\n`notifications.telegram.btw.enabled` defaults to `true` and is the local kill\nswitch. Disabling it consumes `/btw` without forwarding it to the session. To\nroll back, restart the Telegram daemon, and probe health:\n\n```sh\nskc config set notifications.telegram.btw.enabled false\nskc daemon restart telegram --json\nskc notify health --probe\n```\n\n## 8. Local `/notify` inside a session\n\nInside a running SKC session, `/notify` controls the current session only; it\ndoes not edit global config or credentials:\n\n- `/notify status` reports current session notification status without secrets;\n- `/notify off` disables the current session endpoint and removes its discovery\n record without changing global setup;\n- `/notify on` re-enables the current session when a complete global\n configuration or explicit environment path is available, unless\n `SKC_NOTIFICATIONS=0` is forcing opt-out.\n\nNeither command changes `SKC_NOTIFY` or `SKC_NOTIFICATIONS` precedence. A\nprocess with `SKC_NOTIFY=off`, `0`, or `false` has no notification control\nsurface to override.\n\n## 9. Debug-only manual bridge\n\nThe manual Telegram CLI remains a reference/debug tool:\n\n```sh\nbun run packages/coding-agent/src/sdk/bus/telegram-cli.ts --bot-token \"$BOT_TOKEN\"\n```\n\nIf a fresh managed daemon already owns the same bot token and paired chat, the\nmanual CLI refuses to start by default because a second poller would cause\nTelegram `409 Conflict`. Use `--force` only for deliberate debugging after you\nunderstand which daemon owns polling.\n\n## Troubleshooting\n\n### `Telegram getMe failed`\n\nThe BotFather token is invalid or was revoked. Re-copy the token from BotFather\nor regenerate it in the official BotFather UI.\n\n### Setup times out waiting for a private chat\n\nSend any message directly to the bot from your Telegram user account. Do not add\nit to a group for pairing; groups/supergroups/channels are intentionally rejected\nby the current setup flow.\n\n### Setup succeeds but no Telegram session messages arrive\n\nCheck the `threaded=` status from the last `skc notify setup` run. If it is\n`threaded=unverified` or `threaded=unknown`, first try the current Telegram\nclient's @BotFather flow for this bot. If BotFather's **Bot Settings** menu lacks\n**Threads Settings**/**Threaded Mode**, continue with the saved private-chat\npairing; this is supported. SKC cannot enable Threaded Mode through the Bot API,\nand no paid/Stars option is required just to receive flat private-chat\nnotifications. When `createForumTopic` is refused for the paired chat, the daemon\nfalls back to flat delivery in the paired private chat and posts a one-time nudge\nthat points to @BotFather > Bot Settings > Threads Settings. Flat fallback is\nlimited to outbound notifications and inline ask buttons; free-text replies and\nsession commands require Threaded Mode/topic routing.\n\n### Third-party or older client lacks ask controls\n\nA custom client that omits ClientHello, or sends one without `ask_controls_v1`,\nwill still receive ordinary empty-controls asks but receives\n`action_unavailable` for controlled asks after the short Hello grace or explicit\nnon-capable negotiation. Upgrade it to send\n`{ \"type\": \"hello\", \"protocolVersion\": 3, \"capabilities\": [\"ask_controls_v1\"] }`\non each WebSocket open; reconnecting starts a new negotiation.\n\n### Telegram 409 conflict\n\nOnly one `getUpdates` poller can own a bot token. SKC never takes over a fresh\nforeign or unknown owner. If you own the other process, stop or reconfigure it,\nthen use `skc notify health`, `skc notify recovery`, or `skc notify reconnect`;\nrecovery removes only dead-owner artifacts and never touches a live owner.\n\n### A session does not send notifications\n\nCheck, in order:\n\n1. `skc notify status`\n2. `SKC_NOTIFICATIONS` is not set to `0`\n3. the session has not run `/notify off`\n4. the repo has `.skc/state/sdk/<sessionId>.json`\n5. the managed daemon state is fresh under the SKC agent notifications directory\n\nDo not paste endpoint discovery files into public issues; they contain the\nper-session WebSocket token needed by clients.\n",
100
+ "telegram-onboarding.md": "# Telegram notification onboarding\n\nThis guide documents the bundled Telegram notification setup path from Sayknow-CLI\nsource. In an interactive SKC session, use `/settings` → **Notifications** as the\nrecommended path; `skc notify` remains the authoritative headless and automation\nfallback. It is for the managed reference client, not a separate remote-control\nproduct.\n\n## What you are setting up\n\nSayknow-CLI notifications are a loopback WebSocket SDK plus a managed Telegram\nreference daemon:\n\n- each SKC session publishes a local notification endpoint under\n `.skc/state/sdk/<sessionId>.json`;\n- the managed Telegram daemon scans those endpoints, connects to them, and sends\n action-needed events to the configured Telegram chat;\n- replies and inline button taps route back to the exact session/action through\n the same notification protocol. When the configured chat supports Telegram\n forum topics, each session is routed through its own topic.\n\nThe setup command stores global notification settings in your SKC agent config\nand later sessions auto-connect when notifications are enabled.\n\n## 1. Create a Telegram bot with BotFather\n\nUse Telegram's official BotFather flow to create a bot and copy its HTTP API\ntoken:\n\n- Official BotFather documentation: <https://core.telegram.org/bots/features#botfather>\n- General Telegram Bot API documentation: <https://core.telegram.org/bots/api>\n\nIn Telegram, open `@BotFather`, run `/newbot`, choose a display name and a unique\nusername ending in `bot`, then copy the token BotFather returns. Treat the token\nlike a password: do not paste it into logs, screenshots, issues, or shell history\nthat other people can read.\n\n## 2. Configure from `/settings` (recommended)\n\nIn an eligible running SKC session, open `/settings` and select the\n**Notifications** tab. It provides the interactive Telegram setup/reconfigure\nflow and the operational controls in one place:\n\n- Enable globally with stored credentials or disable globally;\n- turn notifications on or off for the current session only;\n- refresh or probe health, send a test notification, recover dead-owner\n artifacts, and reconnect the Telegram runtime;\n- remove Telegram credentials without removing configured Discord or Slack\n adapters.\n\nTelegram token entry is a masked setup field. After entry, the token is never\nprefilled, rendered, or shown by the tab; status and health use a masked value.\nThe tab also guides the BotFather Threaded Mode check and private-chat pairing.\n\n### CLI setup fallback\n\n`skc notify setup` retains the same setup workflow for terminal-driven setup and\nautomation:\n\n```sh\nskc notify setup\n```\n\nCurrent implementation path: `packages/coding-agent/src/cli/notify-cli.ts`.\n\nThe wizard does this:\n\n1. prompts for `Telegram BotFather token:`;\n2. validates the token with Telegram `getMe`;\n3. verifies private-chat Threaded Mode capability via `getMe.has_topics_enabled`\n and, when it is off in an interactive run, prints @BotFather guidance and\n lets you retry or continue unverified;\n4. asks you to message the bot from a private Telegram chat;\n5. polls Telegram `getUpdates` until it sees a private chat message;\n6. writes the paired chat id and enables notifications.\n\nThe setup pairing flow is private-chat only. If setup sees a `group`,\n`supergroup`, or `channel`, it rejects that chat and keeps waiting for a private\nDM. This is intentional for safe local discovery: group chats must not receive\nsession names, action ids, or pending status by accident.\n\nTelegram private-chat topics: the managed daemon's per-session delivery uses\nTelegram forum topics (`createForumTopic` + `message_thread_id`). Telegram now\nsupports forum topics in **private chats** when the bot owner enables **Threaded\nMode** for the bot in @BotFather. SKC cannot enable Threaded Mode through the Bot\nAPI; setup only detects the capability (`getMe.has_topics_enabled`) and guides the\nmanual BotFather toggle. A forum-enabled supergroup is no longer required.\n\nNote: enabling topics in private chats may require an additional Telegram Stars\npurchase fee, per Telegram's Terms of Service for Bot Developers.\n\nIf BotFather's **Bot Settings** menu does not show **Threads Settings** or\n**Threaded Mode**, do not treat that as a setup blocker. Telegram exposes this\ncapability unevenly across clients/accounts/bot states, and SKC cannot force the\nmenu to appear through the Bot API. The safe fallback is to continue setup with a\nprivate DM pairing: choose `skip` in the interactive prompt (or use\n`--token <botToken> --chat-id <chatId>` for non-interactive setup). SKC will save\n`threaded=unverified`/`threaded=unknown`, try topics at runtime when possible,\nand otherwise deliver flat to the paired private chat with outbound notifications\nand inline ask buttons only plus the one-time nudge shown below.\n\nSetup verification is capability verification, not a delivery guarantee: even when\nsetup reports `threaded=verified`, the first runtime `createForumTopic` for the\npaired chat can still fail if Telegram refuses it. When per-session topics are\nunavailable, the daemon does **not** drop notifications — it routes them to the\nnormal (flat) paired chat and posts a one-time nudge: `Flat Telegram private chat\nsupports outbound notifications and inline ask buttons only. Enable Threaded Mode\nin @BotFather > Bot Settings > Threads Settings for free-text replies and session\ncommands.` Because pairing is private-only, flat delivery lands in your own\nprivate DM with the bot.\n\nThe final setup line reports a `threaded=` status:\n\n- `threaded=verified`: the bot has Threaded Mode capability (`has_topics_enabled`\n was true during setup);\n- `threaded=unverified`: Threaded Mode was off and you skipped, or setup ran\n non-interactively; setup is saved, topics are attempted when available, and\n runtime delivery falls back to the paired flat private chat with outbound\n notifications and inline ask buttons only when Telegram refuses topic creation;\n- `threaded=unknown`: the Telegram response did not include `has_topics_enabled`,\n so capability could not be verified.\n\nAfter setup succeeds, it prints a masked token and the paired chat id:\n\n```text\nNotifications enabled. botToken=1234…(len N) chatId=123456789 threaded=verified\n```\n\nThe raw token is never printed by SKC status/setup output after it is stored.\n\n## 3. Non-interactive setup and CLI operations\n\nFor headless provisioning, scripts, and automation, the authoritative commands\nremain `skc notify setup`, `skc notify status`, `skc notify health`, `skc notify\ntest`, and `skc notify recovery`. The `/settings` tab does not replace these CLI\nsubcommands.\n\nFor scripts or CI-style local provisioning, pass the bot token and known private\nchat id explicitly. Non-interactive runs cannot prompt for the BotFather toggle,\nso if Threaded Mode is off (or the capability is unknown) setup is still saved\nwith a warning and a `threaded=unverified`/`threaded=unknown` status:\n\n```sh\nskc notify setup --token <botToken> --chat-id <chatId>\n```\n\nOptional redaction can be enabled during setup:\n\n```sh\nskc notify setup --token <botToken> --chat-id <chatId> --redact\n```\n\n`--redact` sets `notifications.redact = true`. Under redaction, idle summaries\nand streamed content are suppressed before remote delivery, but ask questions and\noptions remain readable because they must be answerable remotely.\n\n## 4. Check status without leaking secrets\n\n```sh\nskc notify status\n```\n\nThe status command reads the typed notification settings and prints:\n\n- `enabled`\n- masked `botToken`\n- paired `chatId`\n- `redact`\n\nIt uses the same masking helper as setup (`first 4 chars + … + length`), so it is\nsafe to paste into a support thread if the chat id itself is not sensitive in\nyour environment.\n\n## 5. Global configuration, adapters, and precedence\n\nTelegram credentials and all `notifications.*` values are **global-only**. SKC\nreads them from the user/global agent config with schema defaults; notification\nkeys from project config files are ignored, and runtime notification overrides\nare rejected. A project cannot supply, shadow, or disable an outbound\nnotification identity.\n\n`skc notify setup` writes these global Telegram settings through the SKC Settings\nlayer:\n\n- `notifications.enabled = true`\n- `notifications.telegram.botToken = <token>`\n- `notifications.telegram.chatId = <paired chat id>`\n- `notifications.redact = true` only when `--redact` was passed\n- `notifications.telegram.streaming.enabled = true` by default; set it to `false` to disable durable live Telegram assistant-output updates globally. `SKC_NOTIFICATIONS_STREAM=1` forces process-local streaming, while `0`, `off`, or `false` forces it off.\n\nA complete global configuration is `notifications.enabled` plus at least one\ncomplete adapter. Telegram needs its bot token and private-chat id; Discord and\nSlack each need their own credential and destination. Removing Telegram in\n`/settings` is adapter-local: it preserves a complete Discord or Slack adapter\nand global enablement, and disables global notifications only when Telegram was\nthe last complete adapter.\n\n\nThree lifecycle gates keep SDK hosting, setup, and managed delivery separate:\n\n1. An eligible host receives the dormant notification control surface. `SKC_NOTIFY=off`,\n `0`, or `false` is a hard process opt-out; unsupported hosts and\n helper/subagent sessions are also ineligible.\n2. Every eligible top-level session hosts its local SDK endpoint by default,\n independently of notification configuration. `SKC_SDK_DISABLE=1` opts out of\n SDK hosting for that session.\n3. A managed Telegram daemon is ensured only for a complete global Telegram\n configuration with managed delivery enabled. Discord-only, Slack-only, and\n environment-only sessions do not start a Telegram daemon.\n\nEnvironment/session precedence for managed delivery is implemented in\n`packages/coding-agent/src/sdk/bus/config.ts`:\n\nFor a SKC-spawned child, `notifications.sessionScope=primary` suppresses managed\nnotification delivery to avoid duplicate topics; `all` permits it.\n`SKC_NOTIFICATIONS=1` or `SKC_NOTIFICATIONS_TOKEN` explicitly opts that child in,\nbut never overrides a hard opt-out or a helper/subagent exclusion.\n\nManaged-delivery precedence is highest first; it does not change independently\nhosted SDK endpoints:\n\n1. `SKC_NOTIFY=off`, `0`, or `false` prevents the notification control surface\n for that process.\n2. `SKC_NOTIFICATIONS=0` is a hard managed-delivery opt-out.\n3. Local `/notify off` disables managed delivery only for the current session.\n4. `SKC_NOTIFICATIONS=1` or `SKC_NOTIFICATIONS_TOKEN` enables the legacy\n explicit managed-delivery path.\n5. A complete global configuration enables managed delivery automatically.\n6. Otherwise managed delivery stays off; the SDK endpoint remains hosted unless\n `SKC_SDK_DISABLE=1` is set.\n\n## 6. Start or reuse sessions\n\nAfter setup, start SKC normally:\n\n```sh\nskc --tmux\n```\n\nor use any other supported SKC launch mode. Every eligible top-level session\nwrites its SDK endpoint unless `SKC_SDK_DISABLE=1`; when managed Telegram\ndelivery is configured and enabled, it also ensures the Telegram daemon is running.\n\nThe managed daemon is a singleton per bot token/chat pair. Telegram allows only\none active `getUpdates` long-poll owner for a bot token, so SKC keeps a local\ndaemon lock/state file and makes later sessions attach to the fresh owner instead\nof starting a second poller. This avoids Telegram `409 Conflict` failures.\n\n### Same-token and foreign-owner safety\n\nSetup and reconfigure never compete with a live same-token daemon. When a live\nowner already has the stored paired chat, SKC reuses it after non-polling\nvalidation. If that owner has no stored chat or the chat changes, provide a\nvalidated private chat id; SKC performs zero `getUpdates` discovery polls. For a\nforeign or unknown owner, setup does not poll, kill, reload, or take over the\nowner; the default is to cancel before writing configuration.\n\nFor a Telegram-only setup, an explicit **Save inactive for later** choice may\nstore the credentials with notifications disabled. That choice is unavailable\nwhen a complete Discord or Slack adapter is active, because globally disabling\nnotifications would affect that adapter. A post-save identity race similarly\nstops the current session before reporting that activation is blocked; the\nforeign daemon remains untouched, and the editor offers an explicit restore or\nretain-configuration choice.\n\n## 7. Use the Telegram chat\n\nThe managed daemon prefers Telegram forum-topic delivery for per-session routing\nin the paired private chat. When Threaded Mode is available for the bot (verified\nduring setup via `getMe.has_topics_enabled`), the daemon calls\n`createForumTopic`/`editForumTopic` and sends messages with `message_thread_id`\nagainst the paired `notifications.telegram.chatId`. If BotFather does not show\n**Threads Settings**/**Threaded Mode**, or if Telegram refuses topic creation even\nafter setup reported `threaded=verified`, the daemon routes notifications to the\nnormal (flat) paired private chat and posts a one-time nudge to enable Threaded\nMode rather than dropping them.\n\n### Ask-control capability negotiation\n\nThe production Telegram multiplexer is\n`packages/coding-agent/src/sdk/bus/telegram-daemon.ts`. It already sends a\nprotocol-v3 ClientHello with `ask_controls_v1` and `ask_selected_ack_v1`. The\ngeneric `packages/coding-agent/src/sdk/bus/managed-daemon.ts` is\nliveness-only: it advertises `client_ping_pong` but is intentionally\nnon-capable for controlled asks.\n\nTelegram navigation controls appear only after `ask_controls_v1` is negotiated\non that session connection. A non-capable or older third-party client receives\nthe non-actionable `action_unavailable` diagnostic instead of a controlled ask\nwith stripped option buttons, so it cannot be left with unusable controls.\n\nFlat private chat is notification-only plus inline ask buttons. It is not a\nfree-text chat surface: replies typed as normal messages and session commands such\nas `/verbose`, `/lean`, `/verbosity`, and `/redact` require Threaded Mode/topic\nrouting.\n\nFlat private-chat fallback preserves outbound notifications and inline-button\nanswers, but it cannot provide a separate Telegram topic per SKC session. Free-\ntext replies and in-topic config commands depend on topic routing, so enable\nThreaded Mode in @BotFather > Bot Settings > Threads Settings when you need\nmulti-session reply separation or session commands from Telegram. Do not\npair a group, supergroup, or channel as a substitute: setup intentionally accepts\nonly a private DM, and hand-edited non-private chat ids remain fail-closed to\navoid leaking session data. If you specifically want group topics, create a\nforum-enabled Telegram group and use a separate/custom notification integration;\nthe bundled `skc notify setup` onboarding path is private-chat only.\n\nThe managed daemon can render:\n\n- session identity headers;\n- context updates;\n- live/finalized assistant output;\n- image attachments;\n- ask prompts with inline buttons;\n- activity/typing indicators;\n- inbound delivery acknowledgements.\n\nPer-tool activity is off by default so important notifications remain visible. This\nincludes `bash`, `read`, `task`, and subagent start/completion bubbles, including\nboth `ok` and `error` results. Send `/toolactivity on` in the paired private chat\nto opt in globally, or `/toolactivity off` to suppress these bubbles again. The\ntoggle is durable, works without an active SKC session, and has an equivalent\ncontrol under `/settings` → **Notifications** → **Preferences**. Turning it off\ndoes not affect assistant output, ask prompts, or session notifications.\n\nReply paths:\n\n- tap an inline button on an ask notification;\n- reply in the session topic with free text when forum-topic routing is\n available;\n- send in-topic config commands:\n - `/verbose` — per-tool-turn assistant text (and opt-in live streaming)\n - `/lean` — settled assistant answer when the agent reaches idle, plus immediate ask lead-ins (default; no intermediate tool-turn flood)\n - `/verbosity <lean|verbose>`\n - `/redact <on|off>`\n - `/btw <question>` is available only in an authorized, known private-session\n topic. It uses the current session context in an isolated side turn and never\n injects or persists either a user or assistant message in the main session\n history, so it can run while the main session is busy. It accepts no\n attachments; `/btw` with an attachment returns `Usage: /btw <question>`.\n Foreign bot-command suffixes are silently ignored.\n\n Each logical session permits at most two concurrent side questions. The host\n deadline is 120 seconds and cancels the actual provider work. Operational\n responses are: `Usage: /btw <question>` for an empty question; `Telegram\n /btw is disabled in local settings.` when disabled; `Restart this SKC session\n to enable /btw.` when the connected session does not support side turns; `Two\n /btw questions are already running. Wait for one to finish.` when busy; `This\n /btw question timed out after 120 seconds. Send it again to retry.` on\n timeout; `This /btw question stopped because the SKC session closed or\n changed. Reopen it and try again.` when stopped; and `This /btw question\n failed. Send it again to retry.` on failure.\n\n A transient reconnect to the exact session may deliver a result once.\n Graceful SKC or daemon shutdown cancels side questions. Crashes or identity\n changes do not promise delivery, and stale results are fenced.\n `/btw` rich replies use Telegram Bot API 10.1 Markdown only. An eligible,\n complete structured Markdown reply is sent once as\n `{rich_message:{markdown,skip_entity_detection:true}}`, correlated to the\n source message in the same topic; SKC does not send native `blocks` or\n `media`. Eligibility is conservative: valid Unicode; at most 32,768 scalars,\n 131,072 UTF-8 bytes, 500 blocks, 16 nesting levels, and 20 table columns.\n Tables and math use Telegram's 10.1 Markdown support. Ineligible content and\n a definite rich rejection use the existing correlated HTML delivery.\n Ambiguous rich outcomes never retry or fall back; `/rich off` keeps HTML-only\n behavior.\n- send paired-chat lifecycle commands from the Telegram command menu or by typing:\n - `/session_create path <dir>`\n - `/session_create worktree <repo> <branch>`\n - `/session_create dir <newdir>`\n - `/session_recent [create|resume]`\n - `/session_close <sessionId>`\n - `/session_resume <sessionId|prefix>`\n\nThe removed legacy `/answer <session-tag> <answer>` flow is not the primary UX;\nTelegram topic routing identifies the target session when the configured chat\nsupports it.\n### `/btw` operational rollback\n\n`notifications.telegram.btw.enabled` defaults to `true` and is the local kill\nswitch. Disabling it consumes `/btw` without forwarding it to the session. To\nroll back, restart the Telegram daemon, and probe health:\n\n```sh\nskc config set notifications.telegram.btw.enabled false\nskc daemon restart telegram --json\nskc notify health --probe\n```\n\n## 8. Local `/notify` inside a session\n\nInside a running SKC session, `/notify` controls the current session only; it\ndoes not edit global config or credentials:\n\n- `/notify status` reports current session notification status without secrets;\n- `/notify off` disables the current session endpoint and removes its discovery\n record without changing global setup;\n- `/notify on` re-enables the current session when a complete global\n configuration or explicit environment path is available, unless\n `SKC_NOTIFICATIONS=0` is forcing opt-out.\n\nNeither command changes `SKC_NOTIFY` or `SKC_NOTIFICATIONS` precedence. A\nprocess with `SKC_NOTIFY=off`, `0`, or `false` has no notification control\nsurface to override.\n\n## 9. Debug-only manual bridge\n\nThe manual Telegram CLI remains a reference/debug tool:\n\n```sh\nbun run packages/coding-agent/src/sdk/bus/telegram-cli.ts --bot-token \"$BOT_TOKEN\"\n```\n\nIf a fresh managed daemon already owns the same bot token and paired chat, the\nmanual CLI refuses to start by default because a second poller would cause\nTelegram `409 Conflict`. Use `--force` only for deliberate debugging after you\nunderstand which daemon owns polling.\n\n## Troubleshooting\n\n### `Telegram getMe failed`\n\nThe BotFather token is invalid or was revoked. Re-copy the token from BotFather\nor regenerate it in the official BotFather UI.\n\n### Setup times out waiting for a private chat\n\nSend any message directly to the bot from your Telegram user account. Do not add\nit to a group for pairing; groups/supergroups/channels are intentionally rejected\nby the current setup flow.\n\n### Setup succeeds but no Telegram session messages arrive\n\nCheck the `threaded=` status from the last `skc notify setup` run. If it is\n`threaded=unverified` or `threaded=unknown`, first try the current Telegram\nclient's @BotFather flow for this bot. If BotFather's **Bot Settings** menu lacks\n**Threads Settings**/**Threaded Mode**, continue with the saved private-chat\npairing; this is supported. SKC cannot enable Threaded Mode through the Bot API,\nand no paid/Stars option is required just to receive flat private-chat\nnotifications. When `createForumTopic` is refused for the paired chat, the daemon\nfalls back to flat delivery in the paired private chat and posts a one-time nudge\nthat points to @BotFather > Bot Settings > Threads Settings. Flat fallback is\nlimited to outbound notifications and inline ask buttons; free-text replies and\nsession commands require Threaded Mode/topic routing.\n\n### Third-party or older client lacks ask controls\n\nA custom client that omits ClientHello, or sends one without `ask_controls_v1`,\nwill still receive ordinary empty-controls asks but receives\n`action_unavailable` for controlled asks after the short Hello grace or explicit\nnon-capable negotiation. Upgrade it to send\n`{ \"type\": \"hello\", \"protocolVersion\": 3, \"capabilities\": [\"ask_controls_v1\"] }`\non each WebSocket open; reconnecting starts a new negotiation.\n\n### Telegram 409 conflict\n\nOnly one `getUpdates` poller can own a bot token. SKC never takes over a fresh\nforeign or unknown owner. If you own the other process, stop or reconfigure it,\nthen use `skc notify health`, `skc notify recovery`, or `skc notify reconnect`;\nrecovery removes only dead-owner artifacts and never touches a live owner.\n\n### Telegram rejects the bot token (401/404)\n\nA revoked token (401) or a deleted bot (404) does not recover by retrying. The\ndaemon pauses `getUpdates` with exponential backoff (1 minute up to 30 minutes)\ninstead of polling every second, logs the rejection once, and\n`skc notify health` reports a `telegram_auth` error. Run `skc notify setup` with\na new token; the marker is keyed to the rejected token, so health ignores it\nonce the config holds the new one.\n\n### A session does not send notifications\n\nCheck, in order:\n\n1. `skc notify status`\n2. `SKC_NOTIFICATIONS` is not set to `0`\n3. the session has not run `/notify off`\n4. the repo has `.skc/state/sdk/<sessionId>.json`\n5. the managed daemon state is fresh under the SKC agent notifications directory\n\nDo not paste endpoint discovery files into public issues; they contain the\nper-session WebSocket token needed by clients.\n",
101
101
  "telegram-remote.md": "# Telegram Remote — control skc sessions from your phone\n\nTelegram Remote is a **tiny, safe operator remote** for Sayknow-CLI (`skc`)\nsessions. It lets you list, observe, start, and stop sessions from a Telegram\nchat — a control button, not a remote shell or cockpit. The real session owner\nstays on your machine (skc/tmux); Telegram only issues bounded, allowlisted\ncommands over the Coordinator MCP.\n\nThe gateway implementation lives in\n[`packages/telegram-remote`](../packages/telegram-remote/README.md); this guide\ncovers how to turn it on and use it.\n\n## What you get\n\nTwo backends, selected by `telegram.backend`:\n\n- **`coordinator`** (default) — multi-session lifecycle + observation. Bot\n commands: `/sessions`, `/observe <id>`, `/start-session <preset> [task]`,\n `/stop <id>`, `/help`.\n- **`rpc`** — attach/detach keyboard for one persistent `skc launch --output rpc`\n session. Bot commands: `/attach`, `/detach`, `/status`, `/abort`, `/help`.\n\nAnything outside this vocabulary is rejected as unknown.\n\n## Quick start (skc settings)\n\n1. **Create a bot.** Message [@BotFather](https://t.me/BotFather) → `/newbot`,\n copy the token (`123456:AA...`).\n2. **Find your Telegram id.** Message [@userinfobot](https://t.me/userinfobot)\n (or read it from your bot's `getUpdates`). You need your numeric user id\n and/or chat id.\n3. **Configure skc.** Open `skc`, go to **Settings → Integrations**, and set:\n - **Telegram Remote** (`telegram.enabled`) → on\n - **Bot Token** (`telegram.botToken`) → the @BotFather token\n - **Allowed User IDs** (`telegram.allowedUserIds`) → your id\n (comma-separated; or **Allowed Chat IDs**). At least one allowlist is\n required — unlisted senders are refused with no hints.\n - **Session Presets** (`telegram.presets`) → JSON array of approved presets\n (see below) if you want `/start-session`.\n\n Settings persist to your skc config; you can also edit them directly in\n `config.yml` under the `telegram.*` keys.\n\n4. **Start the gateway.**\n\n ```sh\n skc telegram start # start with current settings\n skc telegram status # show whether it is configured / running\n skc telegram env # print the SKC_TELEGRAM_REMOTE_* env it would use\n ```\n\n When `telegram.enabled` is on, skc also **auto-starts** the gateway in the\n background (PID-tracked, detached) the next time you launch an interactive\n session, so `skc telegram start` is only needed for a manual/one-off start.\n\n5. **Use it from Telegram.** Send `/help` to your bot, then `/sessions`,\n `/observe <id>`, `/start-session <preset>`, `/stop <id>` (coordinator mode).\n\n### Presets (`/start-session`)\n\nSession creation is **preset-only** — no workdir/command/branch ever comes from\nchat. A preset binds a fixed workdir + session command + an optional task\ntemplate with a single length-capped `{{task}}` slot:\n\n```json\n[\n {\n \"id\": \"proj\",\n \"workdir\": \"/home/you/src/project\",\n \"sessionCommand\": \"skc --worktree\",\n \"taskTemplate\": \"Use /skill:ralplan to plan: {{task}}\",\n \"taskMaxLen\": 2000\n }\n]\n```\n\n`/start-session proj fix the flaky auth test` starts the `proj` preset with the\ntask substituted into the template.\n\n## RPC mode (one persistent session)\n\nSet **Backend** (`telegram.backend`) → `rpc` to attach to a single existing\nowner-only socket exposed by `skc launch --output rpc --listen <socket>`. The\ngateway never spawns, kills, or tears down that session — it is only a Telegram\nattach/detach remote keyboard. RPC mode requires **RPC Socket**\n(`telegram.rpcSocket`) and **State Directory** (`telegram.stateDir`) for\nreconnect/resync. Agent questions and gates render as inline buttons;\nturn-complete delivery sends the final assistant text (HTML-escaped, chunked to\nTelegram's 4096-byte limit).\n\n## Safety properties\n\n- **Default deny.** Only allowlisted Telegram user/chat ids may issue any\n command; unlisted senders get an identical boring refusal.\n- **Preset-only creation.** No raw workdir/command/branch/shell/RPC from chat.\n- **Forced-minimal mutations.** The coordinator runs with the smallest mutation\n set — `sessions` (read + start), plus `reports` only when `/stop` is enabled\n (**Enable /stop**, `telegram.enableStop`). `questions` is never enabled.\n- **Redaction by construction.** Only a typed projection (session id, derived\n name, bounded status/turn enums, branch, timestamps, short sanitized blocker)\n ever leaves the machine. Raw tmux tail, transcripts, tool IO, diffs, file\n contents, env, prompts, and tokens are never transmitted.\n- **`/stop` confirmation.** `/stop <id>` arms; a second `/stop <id> confirm` (or\n the inline **Confirm stop** button) records a graceful coordinator\n `cancelled`. It does not kill a tmux process.\n\n## Rich messaging & push (optional)\n\n- **Rich Messages** (`telegram.enableRich`, default on) — HTML formatting +\n inline **Observe/Stop/Refresh** buttons. Set off for plain text.\n- **Register Bot Menu** (`telegram.registerCommands`, default on) — registers\n the Bot command menu at startup.\n- **Push Notifications** (`telegram.enablePush`) — Follow/Mute subscriptions via\n the coordinator event-watch surface (needs a state dir). Push never widens the\n transmitted-data allowlist.\n\n## Settings ↔ environment\n\nThe `skc telegram` command and autostart translate `telegram.*` settings into\n`SKC_TELEGRAM_REMOTE_*` environment variables consumed by the gateway (see\n`skc telegram env`). You can also run the gateway standalone with those env vars\ndirectly — see [`packages/telegram-remote/README.md`](../packages/telegram-remote/README.md)\nfor the full variable list, `.env.example`, and turnkey **systemd**/**launchd**\nservice examples for always-on deployment.\n\n## Non-goals\n\nTelegram Remote is not a remote RPC cockpit, remote shell, config editor, or\ntranscript viewer. It is a bounded lifecycle + observation button. For richer\ncontrol, use skc directly on the host.\n",
102
102
  "telegram-session-close-timeout-bug.md": "# Telegram `/session_close` uncertain outcome and delayed topic cleanup\n\n## Baseline\n\n- Branch: `fix/telegram-session-close-timeout`\n- Base: `upstream/dev` at `12aa7ebd18752c338b55a6ddc0ca8945f6e555cb`\n- Reported: 2026-07-22\n\n## Reproduction\n\n1. Create a SKC session from Telegram and wait until its topic/session is active.\n2. Send:\n\n```text\n/session_close <sessionID>\n```\n\n3. Observe the close response, process/session liveness, and Telegram topic lifecycle.\n\n## Expected behavior\n\n- A valid managed session ID is resolved deterministically.\n- The close request terminates the target session promptly.\n- The daemon returns one clear terminal close result.\n- The Telegram topic/thread is deleted promptly after the session reaches the terminal state.\n- A timeout is reserved for a genuinely unresponsive close operation, not the normal successful path.\n\n## Observed behavior\n\n- Telegram displays `Close outcome uncertain. The session may already be closed — check /session_recent before retrying.`\n- The target process appears to terminate, but the close request does not receive authoritative terminal confirmation.\n- The Telegram topic remains visible for approximately 60 seconds.\n- The topic is then deleted by the orphan-topic cleanup path after `ORPHAN_TOPIC_GRACE_MS`, rather than promptly by the authenticated `session_closed` handler.\n\nThe warning does not mean the session is confirmed closed. It means the close effect may have occurred, but the daemon could not prove the terminal result. The delayed deletion indicates that normal terminal cleanup was missed and the 60-second orphan fallback recovered it later.\n\n## Investigation focus\n\nTrace one lifecycle request ID across:\n\n- Telegram command parsing and acknowledgement\n- `session_close` lifecycle frame dispatch\n- managed tmux/session identity resolution\n- force-close SIGTERM, owner-verdict, and compatibility cleanup ordering\n- owner/supervisor terminal-state observation\n- close outcome generation\n- Telegram topic deletion\n\nPay particular attention to ordering. The managed owner must publish its immutable terminal verdict before runtime-state serialization, coordinator/state-file locks, and terminal-payload preservation can delay or return from postmortem handling. Topic cleanup remains an independent path: it must follow an authenticated `session_closed` frame for the current endpoint generation and lease, never a lifecycle acknowledgement alone. Also verify that the supplied session ID maps to the actual managed tmux name and generation.\n\n## Regression coverage\n\nAdd focused tests for:\n\n1. A live managed session closes before the timeout and emits one terminal outcome.\n2. Topic deletion occurs after terminal close evidence, without waiting for the timeout.\n3. A session that exits during the close race is treated idempotently as closed.\n4. Repeating the same close request returns the prior terminal result without another timeout.\n5. Unknown and unmanaged session IDs fail closed without deleting unrelated topics.\n6. A genuinely stuck process reaches the bounded force-close path and reports that distinct outcome.\n\n## Acceptance criteria\n\n- `/session_close <sessionID>` makes the managed session non-live promptly under normal conditions.\n- The normal path does not display an intermediate outcome that remains pending until timeout.\n- Topic deletion is prompt, deterministic, and tied to the correct session generation.\n- Timeout/force-close remains bounded and observable for genuinely unresponsive sessions.\n- Close remains replay-safe and cannot kill a reused tmux session belonging to another generation.\n",
103
103
  "theme.md": "# Theming Reference\n\nThis document describes how theming works in the coding-agent today: schema, loading, runtime behavior, and failure modes.\n\n## What the theme system controls\n\nThe theme system drives:\n\n- foreground/background color tokens used across the TUI\n- markdown styling adapters (`getMarkdownTheme()`)\n- selector/editor/settings list adapters (`getSelectListTheme()`, `getEditorTheme()`, `getSettingsListTheme()`)\n- symbol preset + symbol overrides (`unicode`, `nerd`, `ascii`)\n- syntax highlighting colors used by native highlighter (`@sayknow-cli/natives`)\n- status line segment colors\n\nPrimary implementation: `src/modes/theme/theme.ts`.\n\n## Theme JSON shape\n\nTheme files are JSON objects validated against the runtime schema in `theme.ts` (`ThemeJsonSchema`) and mirrored by `src/modes/theme/theme-schema.json`.\n\nTop-level fields:\n\n- `name` (required)\n- `colors` (required; all color tokens required)\n- `vars` (optional; reusable color variables)\n- `export` (optional; HTML export colors)\n- `symbols` (optional)\n - `preset` (optional: `unicode | nerd | ascii`)\n - `overrides` (optional: key/value overrides for `SymbolKey`)\n\nColor values accept:\n\n- hex string (`\"#RRGGBB\"`)\n- 256-color index (`0..255`)\n- variable reference string (resolved through `vars`)\n- empty string (`\"\"`) meaning terminal default (`\\x1b[39m` fg, `\\x1b[49m` bg)\n\n## Required color tokens (current)\n\nAll tokens below are required in `colors`.\n\n### Core text and borders (11)\n\n`accent`, `border`, `borderAccent`, `borderMuted`, `success`, `error`, `warning`, `muted`, `dim`, `text`, `thinkingText`\n\n### Background blocks (7)\n\n`selectedBg`, `userMessageBg`, `customMessageBg`, `toolPendingBg`, `toolSuccessBg`, `toolErrorBg`, `statusLineBg`\n\nIn the terminal, user prompts, tool blocks, and the composer are drawn on the bare terminal background with a colored rail (`▌` for prompts and the composer, `│` for tool output); they do not paint `userMessageBg` or the `tool*Bg` tokens. Those tokens remain required: session exports derive their palette from `userMessageBg`, and the status line paints `statusLineBg` behind powerline separators.\n\n### Message/tool text (5)\n\n`userMessageText`, `customMessageText`, `customMessageLabel`, `toolTitle`, `toolOutput`\n\n### Markdown (10)\n\n`mdHeading`, `mdLink`, `mdLinkUrl`, `mdCode`, `mdCodeBlock`, `mdCodeBlockBorder`, `mdQuote`, `mdQuoteBorder`, `mdHr`, `mdListBullet`\n\n### Tool diff + syntax highlighting (12)\n\n`toolDiffAdded`, `toolDiffRemoved`, `toolDiffContext`,\n`syntaxComment`, `syntaxKeyword`, `syntaxFunction`, `syntaxVariable`, `syntaxString`, `syntaxNumber`, `syntaxType`, `syntaxOperator`, `syntaxPunctuation`\n\n### Mode/thinking borders (8)\n\n`thinkingOff`, `thinkingMinimal`, `thinkingLow`, `thinkingMedium`, `thinkingHigh`, `thinkingXhigh`, `bashMode`, `pythonMode`\n\n### Status line segment colors (14)\n\n`statusLineSep`, `statusLineModel`, `statusLinePath`, `statusLineGitClean`, `statusLineGitDirty`, `statusLineContext`, `statusLineSpend`, `statusLineStaged`, `statusLineDirty`, `statusLineUntracked`, `statusLineOutput`, `statusLineCost`, `statusLineSubagents`\n\n## Optional tokens\n\n### `export` section (optional)\n\nUsed for HTML export theming helpers:\n\n- `export.pageBg`\n- `export.cardBg`\n- `export.infoBg`\n\nIf omitted, export code derives defaults from resolved theme colors.\n\n### `symbols` section (optional)\n\n- `symbols.preset` sets a theme-level default symbol set.\n- `symbols.overrides` can override individual `SymbolKey` values.\n\nRuntime precedence:\n\n1. settings `symbolPreset` override (if set)\n2. theme JSON `symbols.preset`\n3. fallback `\"unicode\"`\n\nInvalid override keys are ignored and logged (`logger.debug`).\n\n## Built-in vs custom theme sources\n\nTheme lookup order (`loadThemeJson`):\n\n1. built-in embedded themes (`blue-octopus.json`, `red-octopus.json`, `ink-octopus.json`, `glow-octopus.json`, `violet-octopus.json`, `claude-code.json`, `codex.json`, `gruvbox-dark.json`, and `opencode.json` compiled into `defaultThemes`)\n2. custom theme file: `<customThemesDir>/<name>.json`\n\nCustom themes directory comes from `getCustomThemesDir()`:\n\n- default: `~/.skc/agent/themes`\n- overridden by `SKC_CODING_AGENT_DIR` (`$SKC_CODING_AGENT_DIR/themes`)\n\n`getAvailableThemes()` returns merged built-in + custom names, sorted, with built-ins taking precedence on name collision.\n\n## Loading, validation, and resolution\n\nFor custom theme files:\n\n1. read JSON\n2. parse JSON\n3. validate against `ThemeJsonSchema`\n4. resolve `vars` references recursively\n5. convert resolved values to ANSI by terminal capability mode\n\nValidation behavior:\n\n- missing required color tokens: explicit grouped error message\n- bad token types/values: validation errors with JSON path\n- unknown theme file: `Theme not found: <name>`\n\nVar reference behavior:\n\n- supports nested references\n- throws on missing variable reference\n- throws on circular references\n\n## Terminal color mode behavior\n\nColor mode detection (`detectColorMode`):\n\n- `COLORTERM=truecolor|24bit` => truecolor\n- `WT_SESSION` => truecolor\n- `TERM` in `dumb`, `linux`, or empty => 256color\n- otherwise => truecolor\n\nConversion behavior:\n\n- hex -> `Bun.color(..., \"ansi-16m\" | \"ansi-256\")`\n- numeric -> `38;5` / `48;5` ANSI\n- `\"\"` -> default fg/bg reset\n\n## Runtime switching behavior\n\n### Initial theme (`initTheme`)\n\n`main.ts` initializes theme with settings:\n\n- `symbolPreset`\n- `colorBlindMode`\n- `theme.dark`\n- `theme.light`\n\nAuto theme slot selection uses terminal appearance in this order:\n\n1. terminal-reported OSC 11 background luminance, unless the macOS/Zellij fallback path is active\n2. `COLORFGBG` background index (`< 8` => dark, `>= 8` => light)\n3. macOS appearance fallback only for the known-broken macOS/Zellij OSC 11 path\n4. dark slot fallback\n\nBuilt-in theme note: `ink-octopus` (warm graphite with a single amber accent) is the default SKC theme for the dark slot and `blue-octopus` for the light slot. `red-octopus` is a bundled warm, high-contrast alternate, and two more dark octopus palettes are bundled: `glow-octopus` (teal-black with bioluminescent green) and `violet-octopus` (plum-dark with lavender). All five are cephalopod brand themes with separate semantic error/warning/diff-removal tokens and octopus-oriented symbol overrides. Three additional bundled migration themes — `claude-code`, `codex`, and `opencode` — mirror the look of those tools for easy eye-migration. All three are dark-classified and recommended for `theme.dark`, but are selectable in either slot; they keep SKC's default symbol identity (no crab-symbol overrides).\n\nCurrent defaults from settings schema:\n\n- `theme.dark = \"ink-octopus\"`\n- `theme.light = \"blue-octopus\"`\n- `symbolPreset = \"unicode\"`\n- `colorBlindMode = false`\n\n### Explicit switching (`setTheme`)\n\n- loads selected theme\n- updates global `theme` singleton\n- optionally starts watcher\n- triggers `onThemeChange` callback\n\nOn failure:\n\n- falls back to built-in `dark`\n- returns `{ success: false, error }`\n\n### Preview switching (`previewTheme`)\n\n- applies temporary preview theme to global `theme`\n- does **not** change persisted settings by itself\n- returns success/error without fallback replacement\n\nThe settings theme picker is confirm-only; arrow-key browsing does not call `previewTheme`, so the rendered theme and displayed/persisted theme name stay aligned until Enter confirms a new selection.\n\n## Watchers and live reload\n\nWhen watcher is enabled (`setTheme(..., true)` / interactive init):\n\n- watches `<customThemesDir>/<currentTheme>.json` only when that file exists\n- built-ins are effectively not watched; built-in theme lookup also takes precedence over same-name custom files\n- matching file changes schedule a debounced reload; reload errors or temporary file absence keep the last successfully loaded theme\n- the watcher does not perform a delete/rename fallback; it waits for a future successful reload or explicit theme switch\n\nAuto mode also reevaluates dark/light slot mapping from terminal appearance changes, `SIGWINCH`, and the macOS fallback observer when active.\n\n## Color-blind mode behavior\n\n`colorBlindMode` changes only one token at runtime:\n\n- `toolDiffAdded` is HSV-adjusted (green shifted toward blue)\n- adjustment is applied only when resolved value is a hex string\n\nOther tokens are unchanged.\n\n## Where theme settings are persisted\n\nTheme-related settings are persisted by `Settings` to global config YAML:\n\n- path: `<agentDir>/config.yml`\n- default agent dir: `~/.skc/agent`\n- effective default file: `~/.skc/agent/config.yml`\n\nPersisted keys:\n\n- `theme.dark`\n- `theme.light`\n- `symbolPreset`\n- `colorBlindMode`\n\nLegacy migration exists: old flat `theme: \"name\"` is migrated to nested `theme.dark` or `theme.light` based on luminance detection; legacy built-in names `dark`/`light` both map to `blue-octopus` (pinned explicitly, so they do not follow the `ink-octopus` dark default) unless matching custom theme files exist.\n\n## Creating a custom theme (practical)\n\n1. Create file in custom themes dir, e.g. `~/.skc/agent/themes/my-theme.json`.\n2. Include `name`, optional `vars`, and **all required** `colors` tokens.\n3. Optionally include `symbols` and `export`.\n4. Select the theme in Settings (`Display -> Dark theme` or `Display -> Light theme`) depending on which auto slot you want. All bundled themes are selectable: the octopus themes `blue-octopus`, `red-octopus`, `ink-octopus`, `glow-octopus`, and `violet-octopus`, plus the migration themes `claude-code`, `codex`, and `opencode` (dark-classified, recommended for the dark slot but selectable in either).\n\nMinimal skeleton:\n\n```json\n{\n \"name\": \"my-theme\",\n \"vars\": {\n \"accent\": \"#7aa2f7\",\n \"muted\": 244\n },\n \"colors\": {\n \"accent\": \"accent\",\n \"border\": \"#4c566a\",\n \"borderAccent\": \"accent\",\n \"borderMuted\": \"muted\",\n \"success\": \"#9ece6a\",\n \"error\": \"#f7768e\",\n \"warning\": \"#e0af68\",\n \"muted\": \"muted\",\n \"dim\": 240,\n \"text\": \"\",\n \"thinkingText\": \"muted\",\n\n \"selectedBg\": \"#2a2f45\",\n \"userMessageBg\": \"#1f2335\",\n \"userMessageText\": \"\",\n \"customMessageBg\": \"#24283b\",\n \"customMessageText\": \"\",\n \"customMessageLabel\": \"accent\",\n \"toolPendingBg\": \"#1f2335\",\n \"toolSuccessBg\": \"#1f2d2a\",\n \"toolErrorBg\": \"#2d1f2a\",\n \"toolTitle\": \"\",\n \"toolOutput\": \"muted\",\n\n \"mdHeading\": \"accent\",\n \"mdLink\": \"accent\",\n \"mdLinkUrl\": \"muted\",\n \"mdCode\": \"#c0caf5\",\n \"mdCodeBlock\": \"#c0caf5\",\n \"mdCodeBlockBorder\": \"muted\",\n \"mdQuote\": \"muted\",\n \"mdQuoteBorder\": \"muted\",\n \"mdHr\": \"muted\",\n \"mdListBullet\": \"accent\",\n\n \"toolDiffAdded\": \"#9ece6a\",\n \"toolDiffRemoved\": \"#f7768e\",\n \"toolDiffContext\": \"muted\",\n\n \"syntaxComment\": \"#565f89\",\n \"syntaxKeyword\": \"#bb9af7\",\n \"syntaxFunction\": \"#7aa2f7\",\n \"syntaxVariable\": \"#c0caf5\",\n \"syntaxString\": \"#9ece6a\",\n \"syntaxNumber\": \"#ff9e64\",\n \"syntaxType\": \"#2ac3de\",\n \"syntaxOperator\": \"#89ddff\",\n \"syntaxPunctuation\": \"#9aa5ce\",\n\n \"thinkingOff\": 240,\n \"thinkingMinimal\": 244,\n \"thinkingLow\": \"#7aa2f7\",\n \"thinkingMedium\": \"#2ac3de\",\n \"thinkingHigh\": \"#bb9af7\",\n \"thinkingXhigh\": \"#f7768e\",\n\n \"bashMode\": \"#2ac3de\",\n \"pythonMode\": \"#bb9af7\",\n\n \"statusLineBg\": \"#16161e\",\n \"statusLineSep\": 240,\n \"statusLineModel\": \"#bb9af7\",\n \"statusLinePath\": \"#7aa2f7\",\n \"statusLineGitClean\": \"#9ece6a\",\n \"statusLineGitDirty\": \"#e0af68\",\n \"statusLineContext\": \"#2ac3de\",\n \"statusLineSpend\": \"#7dcfff\",\n \"statusLineStaged\": \"#9ece6a\",\n \"statusLineDirty\": \"#e0af68\",\n \"statusLineUntracked\": \"#f7768e\",\n \"statusLineOutput\": \"#c0caf5\",\n \"statusLineCost\": \"#ff9e64\",\n \"statusLineSubagents\": \"#bb9af7\"\n }\n}\n```\n\n## Testing custom themes\n\nUse this workflow:\n\n1. Start interactive mode (watcher enabled from startup).\n2. Open settings and confirm the custom theme in the dark/light theme picker; arrow-key browsing is intentionally non-mutating.\n3. For custom theme files, edit the JSON while running and confirm auto-reload on save.\n4. Exercise critical surfaces:\n - markdown rendering\n - tool blocks (pending/success/error)\n - diff rendering (added/removed/context)\n - status line readability\n - thinking level border changes\n - bash/python mode border colors\n5. Validate both symbol presets if your theme depends on glyph width/appearance.\n\n## Real constraints and caveats\n\n- All `colors` tokens are required for custom themes.\n- `export` and `symbols` are optional.\n- `$schema` in theme JSON is informational; runtime validation is enforced by a Zod schema in code.\n- `setTheme` failure falls back to `dark`; `previewTheme` failure does not replace current theme.\n- File watcher reload errors or temporary missing files keep the current loaded theme until a successful reload or explicit theme switch.\n",
@@ -18,6 +18,8 @@ export interface DaemonPaths {
18
18
  steal: string;
19
19
  aliases: string;
20
20
  seenUpdates: string;
21
+ /** Present while the running daemon's bot token is rejected by Telegram (401/404). */
22
+ authRejected: string;
21
23
  }
22
24
 
23
25
  export function daemonPaths(agentDir: string): DaemonPaths {
@@ -32,5 +34,6 @@ export function daemonPaths(agentDir: string): DaemonPaths {
32
34
  steal: path.join(dir, "telegram-daemon.steal"),
33
35
  aliases: path.join(dir, "telegram-callback-aliases.json"),
34
36
  seenUpdates: path.join(dir, "telegram-seen-updates.json"),
37
+ authRejected: path.join(dir, "telegram-auth-rejected.json"),
35
38
  };
36
39
  }
@@ -634,6 +634,22 @@ export async function checkNotificationHealth(opts: HealthOptions): Promise<Noti
634
634
  checks.push({ name: "daemon", level: "ok", detail: `daemon pid ${daemon.pid} alive with a fresh heartbeat` });
635
635
  }
636
636
 
637
+ // A daemon whose bot token Telegram rejected (401/404) keeps a marker until a
638
+ // poll succeeds again; only the current token's marker is relevant.
639
+ if (telegramConfigured) {
640
+ const marker = await fs
641
+ .readFile(daemonPaths(opts.settings.getAgentDir()).authRejected, "utf8")
642
+ .then(raw => JSON.parse(raw) as { tokenFingerprint?: unknown; errorCode?: unknown; description?: unknown })
643
+ .catch(() => undefined);
644
+ if (marker?.tokenFingerprint === tokenFingerprint(cfg.botToken)) {
645
+ checks.push({
646
+ name: "telegram_auth",
647
+ level: "error",
648
+ detail: `Telegram rejected the configured bot token (${String(marker.errorCode)} ${sanitizeDiagnostic(String(marker.description ?? ""), cfg.botToken)}); polling is paused. Re-pair with \`skc notify setup\`.`,
649
+ });
650
+ }
651
+ }
652
+
637
653
  // Per-session endpoint discovery files.
638
654
  const dir = endpointDir(stateRoot);
639
655
  const files = await listEndpointFiles(fs, dir);
@@ -43,12 +43,17 @@ export const NOTIFICATION_PROTOCOL_VERSION = 3;
43
43
  * and capability-versioned mixed-host compatibility.
44
44
  * Generation 31 lets a Windows controller wait for a cooperative stop and has
45
45
  * the owner watch its control request during a long poll (upstream #6174).
46
+ * Generation 32 pauses getUpdates with backoff while Telegram rejects the bot
47
+ * token and records the rejection for `skc notify health`, so an upgraded host
48
+ * reloads a predecessor that would otherwise poll a revoked token every second.
46
49
  */
47
- export const DAEMON_GENERATION = 31;
50
+ export const DAEMON_GENERATION = 32;
48
51
 
49
52
  /**
50
53
  * Serving-compatibility boundary for daemon lifecycle requests. Epoch 1 covers
51
54
  * all builds published before this field existed; epoch 2 covered generation 29;
52
- * bump this to force serving convergence and reload of compatible live predecessors.
55
+ * epoch 3 covered generations 30-31; epoch 4 reloads those predecessors into
56
+ * generation 32 so a revoked bot token stops being polled every second.
57
+ * Bump this to force serving convergence and reload of compatible live predecessors.
53
58
  */
54
- export const SERVING_EPOCH = 3;
59
+ export const SERVING_EPOCH = 4;
@@ -3597,14 +3597,28 @@ export class TelegramBotTransport implements BotApi {
3597
3597
  type PairedChatPrivacy = "private" | "non-private" | "indeterminate";
3598
3598
  const PAIRED_CHAT_PRIVACY_RETRY_BASE_MS = 15_000;
3599
3599
  const PAIRED_CHAT_PRIVACY_RETRY_MAX_MS = 10 * 60_000;
3600
+ // A rejected bot token (401 revoked / 404 deleted) does not heal by retrying;
3601
+ // re-pairing swaps the token and replaces this daemon. Pause polling with a
3602
+ // long exponential backoff instead of hitting the Bot API every second.
3603
+ const AUTH_REJECTED_RETRY_BASE_MS = 60_000;
3604
+ const AUTH_REJECTED_RETRY_MAX_MS = 30 * 60_000;
3605
+ // Bound one paused wait so the run loop still reaches its idle-exit/stop checks.
3606
+ const AUTH_REJECTED_WAIT_STEP_MS = 25_000;
3607
+
3608
+ export interface TelegramAuthRejection {
3609
+ errorCode: number;
3610
+ description: string;
3611
+ }
3600
3612
 
3601
3613
  export type TelegramUpdateOutcome = "consumed" | "retry";
3602
3614
 
3603
3615
  export type TelegramPollResult =
3604
3616
  | { kind: "success"; updateCount: number }
3605
3617
  | { kind: "aborted" }
3618
+ | { kind: "auth_paused" }
3606
3619
  | { kind: "getUpdates_failed"; error: string }
3607
3620
  | { kind: "api_failure"; errorCode?: number; description: string }
3621
+ | ({ kind: "auth_rejected"; retryInMs: number } & TelegramAuthRejection)
3608
3622
  | { kind: "conflict"; description: string; backoffMs: number };
3609
3623
 
3610
3624
  export interface TelegramUpdatePollerOptions {
@@ -3613,16 +3627,18 @@ export interface TelegramUpdatePollerOptions {
3613
3627
  backoff: { next(): number; reset(): void };
3614
3628
  processUpdate: (update: unknown) => Promise<TelegramUpdateOutcome>;
3615
3629
  health?: TelegramPollHealth;
3630
+ /** Called on each transition into (rejection) or out of (undefined) the auth-rejected state. */
3631
+ onAuthRejected?: (rejection: TelegramAuthRejection | undefined) => void;
3616
3632
  }
3617
3633
 
3618
- type TelegramPollHealthStatus = "healthy" | "getUpdates_failed" | "api_failure" | "conflict";
3634
+ type TelegramPollHealthStatus = "healthy" | "getUpdates_failed" | "api_failure" | "auth_rejected" | "conflict";
3619
3635
 
3620
3636
  export class TelegramPollHealth {
3621
3637
  #status: TelegramPollHealthStatus = "healthy";
3622
3638
  #suppressedCount = 0;
3623
3639
 
3624
3640
  record(result: TelegramPollResult): void {
3625
- if (result.kind === "aborted") return;
3641
+ if (result.kind === "aborted" || result.kind === "auth_paused") return;
3626
3642
  if (result.kind === "success") {
3627
3643
  if (this.#status !== "healthy") {
3628
3644
  logger.info("notifications daemon: Telegram getUpdates recovered", {
@@ -3654,6 +3670,19 @@ export class TelegramPollHealth {
3654
3670
  });
3655
3671
  return;
3656
3672
  }
3673
+ if (result.kind === "auth_rejected") {
3674
+ logger.error(
3675
+ "notifications daemon: Telegram rejected the bot token; polling paused. Re-pair with `skc notify setup`",
3676
+ {
3677
+ errorCode: result.errorCode,
3678
+ description: result.description,
3679
+ retryInMs: result.retryInMs,
3680
+ previousStatus,
3681
+ suppressedCount,
3682
+ },
3683
+ );
3684
+ return;
3685
+ }
3657
3686
  if (result.kind === "api_failure") {
3658
3687
  logger.error("notifications daemon: Telegram getUpdates API failed", {
3659
3688
  errorCode: result.errorCode,
@@ -3691,6 +3720,10 @@ export class TelegramUpdatePoller {
3691
3720
  #offset = 0;
3692
3721
  #opts: TelegramUpdatePollerOptions;
3693
3722
  #health: TelegramPollHealth;
3723
+ #authFailures = 0;
3724
+ #authRetryAt = 0;
3725
+ /** Last state passed to onAuthRejected; undefined until the first verdict so a stale marker is cleared. */
3726
+ #authReported: boolean | undefined;
3694
3727
 
3695
3728
  constructor(opts: TelegramUpdatePollerOptions) {
3696
3729
  this.#opts = opts;
@@ -3710,6 +3743,13 @@ export class TelegramUpdatePoller {
3710
3743
  description?: string;
3711
3744
  result?: Array<{ update_id: number } & Record<string, unknown>>;
3712
3745
  };
3746
+ if (this.#authRetryAt > 0) {
3747
+ const remainingMs = this.#authRetryAt - this.#opts.runtime.now();
3748
+ if (remainingMs > 0) {
3749
+ await this.#opts.runtime.sleep(Math.min(remainingMs, AUTH_REJECTED_WAIT_STEP_MS), signal);
3750
+ return { kind: "auth_paused" };
3751
+ }
3752
+ }
3713
3753
  try {
3714
3754
  body = (await this.#opts.botApi.call(
3715
3755
  "getUpdates",
@@ -3730,6 +3770,23 @@ export class TelegramUpdatePoller {
3730
3770
  await this.#opts.runtime.sleep(backoffMs, signal);
3731
3771
  return { kind: "conflict", description: sanitizeDiagnostic(body.description ?? "no description"), backoffMs };
3732
3772
  }
3773
+ if (body?.ok === false && (body.error_code === 401 || body.error_code === 404)) {
3774
+ this.#authFailures += 1;
3775
+ const retryInMs = Math.min(
3776
+ AUTH_REJECTED_RETRY_MAX_MS,
3777
+ AUTH_REJECTED_RETRY_BASE_MS * 2 ** (this.#authFailures - 1),
3778
+ );
3779
+ this.#authRetryAt = this.#opts.runtime.now() + retryInMs;
3780
+ const rejection = {
3781
+ errorCode: body.error_code,
3782
+ description: sanitizeDiagnostic(body.description ?? "Unauthorized"),
3783
+ };
3784
+ if (this.#authReported !== true) {
3785
+ this.#authReported = true;
3786
+ this.#opts.onAuthRejected?.(rejection);
3787
+ }
3788
+ return { kind: "auth_rejected", retryInMs, ...rejection };
3789
+ }
3733
3790
  if (body?.ok !== true || !Array.isArray(body.result)) {
3734
3791
  await this.#opts.runtime.sleep(POLL_BACKOFF_MS, signal);
3735
3792
  return {
@@ -3739,6 +3796,12 @@ export class TelegramUpdatePoller {
3739
3796
  };
3740
3797
  }
3741
3798
  this.#opts.backoff.reset();
3799
+ this.#authFailures = 0;
3800
+ this.#authRetryAt = 0;
3801
+ if (this.#authReported !== false) {
3802
+ this.#authReported = false;
3803
+ this.#opts.onAuthRejected?.(undefined);
3804
+ }
3742
3805
  let malformedSeen = false;
3743
3806
  for (const update of body.result) {
3744
3807
  // A single malformed update_id must not wedge the poller. Skip the
@@ -4175,6 +4238,8 @@ export class TelegramNotificationDaemon {
4175
4238
  readonly #deliveryAbort = new AbortController();
4176
4239
  private readonly pool: RateLimitPool<TelegramQueuePayload>;
4177
4240
  private readonly poller: TelegramUpdatePoller;
4241
+ /** Serializes auth-rejected marker writes so a quick reject→recover cannot reorder. */
4242
+ private authMarkerWrite: Promise<void> = Promise.resolve();
4178
4243
  private readonly dispatchState = new TelegramEventDispatchState();
4179
4244
  /** Bot-wide flood-control window; inbound polling remains eligible during it. */
4180
4245
  private botCooldownUntil = 0;
@@ -4691,9 +4756,38 @@ export class TelegramNotificationDaemon {
4691
4756
  runtime: this.runtime,
4692
4757
  backoff: this.pollConflictBackoff,
4693
4758
  processUpdate: update => this.processTelegramUpdate(update),
4759
+ onAuthRejected: rejection => this.recordAuthRejected(rejection),
4694
4760
  });
4695
4761
  }
4696
4762
 
4763
+ /**
4764
+ * Persist the auth-rejected verdict for offline `notify health`, keyed by the
4765
+ * token fingerprint so a re-paired config ignores a predecessor's marker.
4766
+ */
4767
+ private recordAuthRejected(rejection: TelegramAuthRejection | undefined): void {
4768
+ const file = daemonPaths(this.opts.settings.getAgentDir()).authRejected;
4769
+ this.authMarkerWrite = this.authMarkerWrite
4770
+ .then(async () => {
4771
+ if (rejection) {
4772
+ await writeJsonAtomic(this.fsImpl, file, {
4773
+ tokenFingerprint: tokenFingerprint(this.opts.botToken),
4774
+ errorCode: rejection.errorCode,
4775
+ description: rejection.description,
4776
+ since: this.runtime.now(),
4777
+ });
4778
+ } else {
4779
+ await this.fsImpl.unlink(file).catch(error => {
4780
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
4781
+ });
4782
+ }
4783
+ })
4784
+ .catch(error => {
4785
+ logger.warn("notifications daemon: failed to update Telegram auth-rejected marker", {
4786
+ error: sanitizeDiagnostic(String(error), this.opts.botToken),
4787
+ });
4788
+ });
4789
+ }
4790
+
4697
4791
  private createSessionRouter(): OperatorEventRouter<SessionSocket> {
4698
4792
  return new OperatorEventRouter<SessionSocket>()
4699
4793
  .add({